const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/LeadSiteHome-D5fFUXnF.js","assets/useLeadSiteSearchSuggestions-D70r42Jf.js","assets/AgentReviewsSection-vdLYMfic.js","assets/ListingCarouselModule-CaLRPR1a.js","assets/imageOptimization-Csrlnz8M.js","assets/ExchangeListingsSection-CU0pCVzL.js","assets/LeadSiteLuxuryHome-AwtSATBh.js","assets/LeadSiteExchangeListings-Cuv-LXYV.js","assets/LeadSiteLuxuryHome-DKt_VWIz.css","assets/LeadSiteLandRanchHome-DkyCt0hZ.js","assets/LeadSiteSearch-CvRigSQv.js","assets/LeadSiteListingCardImage-C8N2cjAt.js","assets/LeadSiteMap-Be5bUj6z.js","assets/LeadSiteLuxurySearch-DovwlnZi.js","assets/LeadSiteListingDetail-ekwhM1k5.js","assets/ListingVideoTour-BMlnr-hB.js","assets/useListingVideos-ChUB5Lud.js","assets/LeadSiteLuxuryListingDetail-mVQbhpz7.js","assets/LeadSiteBlog-BXjfzyQL.js","assets/purify.es-BYftNTi7.js","assets/LeadSiteCityPage-BXRFEnPv.js","assets/CityFaqSection-DjRWKbsy.js","assets/LeadSiteSubdivisionPage-Dvxv3526.js","assets/LeadSiteFocusPage-C9HZUDwX.js","assets/OrgSiteAgents-BMZsDAz0.js","assets/OrgSiteHome-Bk1xVtJ7.js","assets/OrgSitePages-CIFRiyvL.js","assets/OrgSiteListings-QzBnGwU8.js","assets/PublicLiveEvent-C2K9yfKd.js","assets/useLiveEngagement-ClJ1MxRv.js","assets/LiveEventConsole-BTq40bmP.js","assets/StagingStudio-nEIRnU4N.js","assets/presets-CIA3EqGB.js","assets/download-BqCckdNk.js","assets/BeforeAfterSlider-BjZYT0Wn.js","assets/BuyCreditsDialog-CsNm41-o.js","assets/StagingLibrary--5ZLYm1Q.js","assets/StagingCredits-CclcP9a1.js","assets/StagingSharePage-D7ngVeXj.js","assets/StagingStudioAdmin-Bph0DcU8.js","assets/PostcardManager-BD7slbSP.js","assets/usePostcardZones-X_RcWmcY.js","assets/MailStudio-ByrRnYs-.js","assets/LeadSiteEditor-5Bx2DjCT.js","assets/ImageUrlField-DqHWvCo4.js","assets/HomepageModuleManager-BoCwb0N2.js","assets/LeadSiteEditor-BzY4kI8E.css","assets/AdminLeadSiteThemes-Djg-oJTQ.js","assets/AdminFreeWebsiteOfferStudio-Zpa8PZts.js","assets/MLSListingDetail-Bhlnn6-0.js","assets/EmailCampaigns-Bjj___85.js","assets/sesRequest-DyjPI3_P.js","assets/EmailCampaignComposer-CNuzeP4O.js","assets/EditorModeSelector-B5ZRtRxs.js","assets/SharedCampaignTemplates-CRBn6GOq.js","assets/TemplateEditorDialog-DlwAiKOE.js","assets/AgentTemplates-Cla5riuB.js","assets/TheLocalMoveHome-BZvdZEHz.js","assets/tlm-hero-bg-BbD3acLf.js","assets/TheLocalMoveGetStarted-BKXJXHCw.js"])))=>i.map(i=>d[i]); var dgs=Object.defineProperty;var tpt=s=>{throw TypeError(s)};var ugs=(s,t,n)=>t in s?dgs(s,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):s[t]=n;var Nr=(s,t,n)=>ugs(s,typeof t!="symbol"?t+"":t,n),Y8e=(s,t,n)=>t.has(s)||tpt("Cannot "+n);var ye=(s,t,n)=>(Y8e(s,t,"read from private field"),n?n.call(s):t.get(s)),bs=(s,t,n)=>t.has(s)?tpt("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(s):t.set(s,n),Kt=(s,t,n,r)=>(Y8e(s,t,"write to private field"),r?r.call(s,n):t.set(s,n),n),ls=(s,t,n)=>(Y8e(s,t,"access private method"),n);var J0=(s,t,n,r)=>({set _(a){Kt(s,t,a,n)},get _(){return ye(s,t,r)}});function hgs(s,t){for(var n=0;nr[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"]'))r(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"&&r(l)}).observe(document,{childList:!0,subtree:!0});function n(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 r(a){if(a.ep)return;a.ep=!0;const i=n(a);fetch(a.href,i)}})();var Sp=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function au(s){return s&&s.__esModule&&Object.prototype.hasOwnProperty.call(s,"default")?s.default:s}function mgs(s){if(s.__esModule)return s;var t=s.default;if(typeof t=="function"){var n=function r(){return this instanceof r?Reflect.construct(t,arguments,this.constructor):t.apply(this,arguments)};n.prototype=t.prototype}else n={};return Object.defineProperty(n,"__esModule",{value:!0}),Object.keys(s).forEach(function(r){var a=Object.getOwnPropertyDescriptor(s,r);Object.defineProperty(n,r,a.get?a:{enumerable:!0,get:function(){return s[r]}})}),n}var LIt={exports:{}},SIe={},RIt={exports:{}},Tu={};/** * @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 gae=Symbol.for("react.element"),fgs=Symbol.for("react.portal"),pgs=Symbol.for("react.fragment"),ggs=Symbol.for("react.strict_mode"),xgs=Symbol.for("react.profiler"),ygs=Symbol.for("react.provider"),vgs=Symbol.for("react.context"),bgs=Symbol.for("react.forward_ref"),_gs=Symbol.for("react.suspense"),wgs=Symbol.for("react.memo"),jgs=Symbol.for("react.lazy"),spt=Symbol.iterator;function Ngs(s){return s===null||typeof s!="object"?null:(s=spt&&s[spt]||s["@@iterator"],typeof s=="function"?s:null)}var DIt={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},FIt=Object.assign,OIt={};function $W(s,t,n){this.props=s,this.context=t,this.refs=OIt,this.updater=n||DIt}$W.prototype.isReactComponent={};$W.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")};$W.prototype.forceUpdate=function(s){this.updater.enqueueForceUpdate(this,s,"forceUpdate")};function zIt(){}zIt.prototype=$W.prototype;function oJe(s,t,n){this.props=s,this.context=t,this.refs=OIt,this.updater=n||DIt}var lJe=oJe.prototype=new zIt;lJe.constructor=oJe;FIt(lJe,$W.prototype);lJe.isPureReactComponent=!0;var npt=Array.isArray,BIt=Object.prototype.hasOwnProperty,cJe={current:null},$It={key:!0,ref:!0,__self:!0,__source:!0};function UIt(s,t,n){var r,a={},i=null,l=null;if(t!=null)for(r in t.ref!==void 0&&(l=t.ref),t.key!==void 0&&(i=""+t.key),t)BIt.call(t,r)&&!$It.hasOwnProperty(r)&&(a[r]=t[r]);var o=arguments.length-2;if(o===1)a.children=n;else if(1>>1,J=ae[te];if(0>>1;tea(he,ne))uea(ve,he)?(ae[te]=ve,ae[ue]=ne,te=ue):(ae[te]=he,ae[_e]=ne,te=_e);else if(uea(ve,ne))ae[te]=ve,ae[ue]=ne,te=ue;else break e}}return ie}function a(ae,ie){var ne=ae.sortIndex-ie.sortIndex;return ne!==0?ne:ae.id-ie.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=[],u=1,h=null,m=3,f=!1,g=!1,x=!1,y=typeof setTimeout=="function"?setTimeout:null,v=typeof clearTimeout=="function"?clearTimeout:null,b=typeof setImmediate<"u"?setImmediate:null;typeof navigator<"u"&&navigator.scheduling!==void 0&&navigator.scheduling.isInputPending!==void 0&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function w(ae){for(var ie=n(d);ie!==null;){if(ie.callback===null)r(d);else if(ie.startTime<=ae)r(d),ie.sortIndex=ie.expirationTime,t(c,ie);else break;ie=n(d)}}function S(ae){if(x=!1,w(ae),!g)if(n(c)!==null)g=!0,Y(C);else{var ie=n(d);ie!==null&&X(S,ie.startTime-ae)}}function C(ae,ie){g=!1,x&&(x=!1,v(P),P=-1),f=!0;var ne=m;try{for(w(ie),h=n(c);h!==null&&(!(h.expirationTime>ie)||ae&&!O());){var te=h.callback;if(typeof te=="function"){h.callback=null,m=h.priorityLevel;var J=te(h.expirationTime<=ie);ie=s.unstable_now(),typeof J=="function"?h.callback=J:h===n(c)&&r(c),w(ie)}else r(c);h=n(c)}if(h!==null)var ce=!0;else{var _e=n(d);_e!==null&&X(S,_e.startTime-ie),ce=!1}return ce}finally{h=null,m=ne,f=!1}}var E=!1,I=null,P=-1,R=5,D=-1;function O(){return!(s.unstable_now()-Dae||125te?(ae.sortIndex=ne,t(d,ae),n(c)===null&&ae===n(d)&&(x?(v(P),P=-1):x=!0,X(S,ne-te))):(ae.sortIndex=J,t(c,ae),g||f||(g=!0,Y(C))),ae},s.unstable_shouldYield=O,s.unstable_wrapCallback=function(ae){var ie=m;return function(){var ne=m;m=ie;try{return ae.apply(this,arguments)}finally{m=ne}}}})(WIt);GIt.exports=WIt;var rJ=GIt.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 Rgs=j,M2=rJ;function vi(s){for(var t="https://reactjs.org/docs/error-decoder.html?invariant="+s,n=1;n"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),zqe=Object.prototype.hasOwnProperty,Dgs=/^[: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]*$/,apt={},ipt={};function Fgs(s){return zqe.call(ipt,s)?!0:zqe.call(apt,s)?!1:Dgs.test(s)?ipt[s]=!0:(apt[s]=!0,!1)}function Ogs(s,t,n,r){if(n!==null&&n.type===0)return!1;switch(typeof t){case"function":case"symbol":return!0;case"boolean":return r?!1:n!==null?!n.acceptsBooleans:(s=s.toLowerCase().slice(0,5),s!=="data-"&&s!=="aria-");default:return!1}}function zgs(s,t,n,r){if(t===null||typeof t>"u"||Ogs(s,t,n,r))return!0;if(r)return!1;if(n!==null)switch(n.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 O_(s,t,n,r,a,i,l){this.acceptsBooleans=t===2||t===3||t===4,this.attributeName=r,this.attributeNamespace=a,this.mustUseProperty=n,this.propertyName=s,this.type=t,this.sanitizeURL=i,this.removeEmptyString=l}var Ab={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(s){Ab[s]=new O_(s,0,!1,s,null,!1,!1)});[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(s){var t=s[0];Ab[t]=new O_(t,1,!1,s[1],null,!1,!1)});["contentEditable","draggable","spellCheck","value"].forEach(function(s){Ab[s]=new O_(s,2,!1,s.toLowerCase(),null,!1,!1)});["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(s){Ab[s]=new O_(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){Ab[s]=new O_(s,3,!1,s.toLowerCase(),null,!1,!1)});["checked","multiple","muted","selected"].forEach(function(s){Ab[s]=new O_(s,3,!0,s,null,!1,!1)});["capture","download"].forEach(function(s){Ab[s]=new O_(s,4,!1,s,null,!1,!1)});["cols","rows","size","span"].forEach(function(s){Ab[s]=new O_(s,6,!1,s,null,!1,!1)});["rowSpan","start"].forEach(function(s){Ab[s]=new O_(s,5,!1,s.toLowerCase(),null,!1,!1)});var uJe=/[\-:]([a-z])/g;function hJe(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(uJe,hJe);Ab[t]=new O_(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(uJe,hJe);Ab[t]=new O_(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(uJe,hJe);Ab[t]=new O_(t,1,!1,s,"http://www.w3.org/XML/1998/namespace",!1,!1)});["tabIndex","crossOrigin"].forEach(function(s){Ab[s]=new O_(s,1,!1,s.toLowerCase(),null,!1,!1)});Ab.xlinkHref=new O_("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1);["src","href","action","formAction"].forEach(function(s){Ab[s]=new O_(s,1,!1,s.toLowerCase(),null,!0,!0)});function mJe(s,t,n,r){var a=Ab.hasOwnProperty(t)?Ab[t]:null;(a!==null?a.type!==0:r||!(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{Q8e=!1,Error.prepareStackTrace=n}return(s=s?s.displayName||s.name:"")?eQ(s):""}function Bgs(s){switch(s.tag){case 5:return eQ(s.type);case 16:return eQ("Lazy");case 13:return eQ("Suspense");case 19:return eQ("SuspenseList");case 0:case 2:case 15:return s=J8e(s.type,!1),s;case 11:return s=J8e(s.type.render,!1),s;case 1:return s=J8e(s.type,!0),s;default:return""}}function qqe(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 BU:return"Fragment";case zU:return"Portal";case Bqe:return"Profiler";case fJe:return"StrictMode";case $qe:return"Suspense";case Uqe:return"SuspenseList"}if(typeof s=="object")switch(s.$$typeof){case ZIt:return(s.displayName||"Context")+".Consumer";case YIt:return(s._context.displayName||"Context")+".Provider";case pJe:var t=s.render;return s=s.displayName,s||(s=t.displayName||t.name||"",s=s!==""?"ForwardRef("+s+")":"ForwardRef"),s;case gJe:return t=s.displayName||null,t!==null?t:qqe(s.type)||"Memo";case nP:t=s._payload,s=s._init;try{return qqe(s(t))}catch{}}return null}function $gs(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 qqe(t);case 8:return t===fJe?"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 wL(s){switch(typeof s){case"boolean":case"number":case"string":case"undefined":return s;case"object":return s;default:return""}}function QIt(s){var t=s.type;return(s=s.nodeName)&&s.toLowerCase()==="input"&&(t==="checkbox"||t==="radio")}function Ugs(s){var t=QIt(s)?"checked":"value",n=Object.getOwnPropertyDescriptor(s.constructor.prototype,t),r=""+s[t];if(!s.hasOwnProperty(t)&&typeof n<"u"&&typeof n.get=="function"&&typeof n.set=="function"){var a=n.get,i=n.set;return Object.defineProperty(s,t,{configurable:!0,get:function(){return a.call(this)},set:function(l){r=""+l,i.call(this,l)}}),Object.defineProperty(s,t,{enumerable:n.enumerable}),{getValue:function(){return r},setValue:function(l){r=""+l},stopTracking:function(){s._valueTracker=null,delete s[t]}}}}function Jle(s){s._valueTracker||(s._valueTracker=Ugs(s))}function JIt(s){if(!s)return!1;var t=s._valueTracker;if(!t)return!0;var n=t.getValue(),r="";return s&&(r=QIt(s)?s.checked?"true":"false":s.value),s=r,s!==n?(t.setValue(s),!0):!1}function qAe(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 Vqe(s,t){var n=t.checked;return Gg({},t,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:n??s._wrapperState.initialChecked})}function lpt(s,t){var n=t.defaultValue==null?"":t.defaultValue,r=t.checked!=null?t.checked:t.defaultChecked;n=wL(t.value!=null?t.value:n),s._wrapperState={initialChecked:r,initialValue:n,controlled:t.type==="checkbox"||t.type==="radio"?t.checked!=null:t.value!=null}}function eLt(s,t){t=t.checked,t!=null&&mJe(s,"checked",t,!1)}function Hqe(s,t){eLt(s,t);var n=wL(t.value),r=t.type;if(n!=null)r==="number"?(n===0&&s.value===""||s.value!=n)&&(s.value=""+n):s.value!==""+n&&(s.value=""+n);else if(r==="submit"||r==="reset"){s.removeAttribute("value");return}t.hasOwnProperty("value")?Gqe(s,t.type,n):t.hasOwnProperty("defaultValue")&&Gqe(s,t.type,wL(t.defaultValue)),t.checked==null&&t.defaultChecked!=null&&(s.defaultChecked=!!t.defaultChecked)}function cpt(s,t,n){if(t.hasOwnProperty("value")||t.hasOwnProperty("defaultValue")){var r=t.type;if(!(r!=="submit"&&r!=="reset"||t.value!==void 0&&t.value!==null))return;t=""+s._wrapperState.initialValue,n||t===s.value||(s.value=t),s.defaultValue=t}n=s.name,n!==""&&(s.name=""),s.defaultChecked=!!s._wrapperState.initialChecked,n!==""&&(s.name=n)}function Gqe(s,t,n){(t!=="number"||qAe(s.ownerDocument)!==s)&&(n==null?s.defaultValue=""+s._wrapperState.initialValue:s.defaultValue!==""+n&&(s.defaultValue=""+n))}var tQ=Array.isArray;function Nq(s,t,n,r){if(s=s.options,t){t={};for(var a=0;a"+t.valueOf().toString()+"",t=ece.firstChild;s.firstChild;)s.removeChild(s.firstChild);for(;t.firstChild;)s.appendChild(t.firstChild)}});function Ate(s,t){if(t){var n=s.firstChild;if(n&&n===s.lastChild&&n.nodeType===3){n.nodeValue=t;return}}s.textContent=t}var aJ={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},qgs=["Webkit","ms","Moz","O"];Object.keys(aJ).forEach(function(s){qgs.forEach(function(t){t=t+s.charAt(0).toUpperCase()+s.substring(1),aJ[t]=aJ[s]})});function rLt(s,t,n){return t==null||typeof t=="boolean"||t===""?"":n||typeof t!="number"||t===0||aJ.hasOwnProperty(s)&&aJ[s]?(""+t).trim():t+"px"}function aLt(s,t){s=s.style;for(var n in t)if(t.hasOwnProperty(n)){var r=n.indexOf("--")===0,a=rLt(n,t[n],r);n==="float"&&(n="cssFloat"),r?s.setProperty(n,a):s[n]=a}}var Vgs=Gg({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 Yqe(s,t){if(t){if(Vgs[s]&&(t.children!=null||t.dangerouslySetInnerHTML!=null))throw Error(vi(137,s));if(t.dangerouslySetInnerHTML!=null){if(t.children!=null)throw Error(vi(60));if(typeof t.dangerouslySetInnerHTML!="object"||!("__html"in t.dangerouslySetInnerHTML))throw Error(vi(61))}if(t.style!=null&&typeof t.style!="object")throw Error(vi(62))}}function Zqe(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 Xqe=null;function xJe(s){return s=s.target||s.srcElement||window,s.correspondingUseElement&&(s=s.correspondingUseElement),s.nodeType===3?s.parentNode:s}var Qqe=null,kq=null,Sq=null;function hpt(s){if(s=vae(s)){if(typeof Qqe!="function")throw Error(vi(280));var t=s.stateNode;t&&(t=MIe(t),Qqe(s.stateNode,s.type,t))}}function iLt(s){kq?Sq?Sq.push(s):Sq=[s]:kq=s}function oLt(){if(kq){var s=kq,t=Sq;if(Sq=kq=null,hpt(s),t)for(s=0;s>>=0,s===0?32:31-(txs(s)/sxs|0)|0}var tce=64,sce=4194304;function sQ(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 WAe(s,t){var n=s.pendingLanes;if(n===0)return 0;var r=0,a=s.suspendedLanes,i=s.pingedLanes,l=n&268435455;if(l!==0){var o=l&~a;o!==0?r=sQ(o):(i&=l,i!==0&&(r=sQ(i)))}else l=n&~a,l!==0?r=sQ(l):i!==0&&(r=sQ(i));if(r===0)return 0;if(t!==0&&t!==r&&!(t&a)&&(a=r&-r,i=t&-t,a>=i||a===16&&(i&4194240)!==0))return t;if(r&4&&(r|=n&16),t=s.entangledLanes,t!==0)for(s=s.entanglements,t&=r;0n;n++)t.push(s);return t}function xae(s,t,n){s.pendingLanes|=t,t!==536870912&&(s.suspendedLanes=0,s.pingedLanes=0),s=s.eventTimes,t=31-YS(t),s[t]=n}function ixs(s,t){var n=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 r=s.eventTimes;for(s=s.expirationTimes;0=oJ),_pt=" ",wpt=!1;function CLt(s,t){switch(s){case"keyup":return Lxs.indexOf(t.keyCode)!==-1;case"keydown":return t.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function ALt(s){return s=s.detail,typeof s=="object"&&"data"in s?s.data:null}var $U=!1;function Dxs(s,t){switch(s){case"compositionend":return ALt(t);case"keypress":return t.which!==32?null:(wpt=!0,_pt);case"textInput":return s=t.data,s===_pt&&wpt?null:s;default:return null}}function Fxs(s,t){if($U)return s==="compositionend"||!kJe&&CLt(s,t)?(s=kLt(),lme=wJe=pI=null,$U=!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:n,offset:t-s};s=r}e:{for(;n;){if(n.nextSibling){n=n.nextSibling;break e}n=n.parentNode}n=void 0}n=Spt(n)}}function PLt(s,t){return s&&t?s===t?!0:s&&s.nodeType===3?!1:t&&t.nodeType===3?PLt(s,t.parentNode):"contains"in s?s.contains(t):s.compareDocumentPosition?!!(s.compareDocumentPosition(t)&16):!1:!1}function ILt(){for(var s=window,t=qAe();t instanceof s.HTMLIFrameElement;){try{var n=typeof t.contentWindow.location.href=="string"}catch{n=!1}if(n)s=t.contentWindow;else break;t=qAe(s.document)}return t}function SJe(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 Gxs(s){var t=ILt(),n=s.focusedElem,r=s.selectionRange;if(t!==n&&n&&n.ownerDocument&&PLt(n.ownerDocument.documentElement,n)){if(r!==null&&SJe(n)){if(t=r.start,s=r.end,s===void 0&&(s=t),"selectionStart"in n)n.selectionStart=t,n.selectionEnd=Math.min(s,n.value.length);else if(s=(t=n.ownerDocument||document)&&t.defaultView||window,s.getSelection){s=s.getSelection();var a=n.textContent.length,i=Math.min(r.start,a);r=r.end===void 0?i:Math.min(r.end,a),!s.extend&&i>r&&(a=r,r=i,i=a),a=Cpt(n,i);var l=Cpt(n,r);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>r?(s.addRange(t),s.extend(l.node,l.offset)):(t.setEnd(l.node,l.offset),s.addRange(t)))}}for(t=[],s=n;s=s.parentNode;)s.nodeType===1&&t.push({element:s,left:s.scrollLeft,top:s.scrollTop});for(typeof n.focus=="function"&&n.focus(),n=0;n=document.documentMode,UU=null,rVe=null,cJ=null,aVe=!1;function Apt(s,t,n){var r=n.window===n?n.document:n.nodeType===9?n:n.ownerDocument;aVe||UU==null||UU!==qAe(r)||(r=UU,"selectionStart"in r&&SJe(r)?r={start:r.selectionStart,end:r.selectionEnd}:(r=(r.ownerDocument&&r.ownerDocument.defaultView||window).getSelection(),r={anchorNode:r.anchorNode,anchorOffset:r.anchorOffset,focusNode:r.focusNode,focusOffset:r.focusOffset}),cJ&&Lte(cJ,r)||(cJ=r,r=ZAe(rVe,"onSelect"),0HU||(s.current=uVe[HU],uVe[HU]=null,HU--)}function Kf(s,t){HU++,uVe[HU]=s.current,s.current=t}var jL={},S1=e6(jL),Ew=e6(!1),R7=jL;function dG(s,t){var n=s.type.contextTypes;if(!n)return jL;var r=s.stateNode;if(r&&r.__reactInternalMemoizedUnmaskedChildContext===t)return r.__reactInternalMemoizedMaskedChildContext;var a={},i;for(i in n)a[i]=t[i];return r&&(s=s.stateNode,s.__reactInternalMemoizedUnmaskedChildContext=t,s.__reactInternalMemoizedMaskedChildContext=a),a}function Tw(s){return s=s.childContextTypes,s!=null}function QAe(){Cp(Ew),Cp(S1)}function Rpt(s,t,n){if(S1.current!==jL)throw Error(vi(168));Kf(S1,t),Kf(Ew,n)}function ULt(s,t,n){var r=s.stateNode;if(t=t.childContextTypes,typeof r.getChildContext!="function")return n;r=r.getChildContext();for(var a in r)if(!(a in t))throw Error(vi(108,$gs(s)||"Unknown",a));return Gg({},n,r)}function JAe(s){return s=(s=s.stateNode)&&s.__reactInternalMemoizedMergedChildContext||jL,R7=S1.current,Kf(S1,s),Kf(Ew,Ew.current),!0}function Dpt(s,t,n){var r=s.stateNode;if(!r)throw Error(vi(169));n?(s=ULt(s,t,R7),r.__reactInternalMemoizedMergedChildContext=s,Cp(Ew),Cp(S1),Kf(S1,s)):Cp(Ew),Kf(Ew,n)}var LA=null,PIe=!1,mze=!1;function qLt(s){LA===null?LA=[s]:LA.push(s)}function rys(s){PIe=!0,qLt(s)}function t6(){if(!mze&&LA!==null){mze=!0;var s=0,t=Dm;try{var n=LA;for(Dm=1;s>=l,a-=l,gE=1<<32-YS(t)+a|n<P?(R=I,I=null):R=I.sibling;var D=m(v,I,w[P],S);if(D===null){I===null&&(I=R);break}s&&I&&D.alternate===null&&t(v,I),b=i(D,b,P),E===null?C=D:E.sibling=D,E=D,I=R}if(P===w.length)return n(v,I),Kp&&LR(v,P),C;if(I===null){for(;PP?(R=I,I=null):R=I.sibling;var O=m(v,I,D.value,S);if(O===null){I===null&&(I=R);break}s&&I&&O.alternate===null&&t(v,I),b=i(O,b,P),E===null?C=O:E.sibling=O,E=O,I=R}if(D.done)return n(v,I),Kp&&LR(v,P),C;if(I===null){for(;!D.done;P++,D=w.next())D=h(v,D.value,S),D!==null&&(b=i(D,b,P),E===null?C=D:E.sibling=D,E=D);return Kp&&LR(v,P),C}for(I=r(v,I);!D.done;P++,D=w.next())D=f(I,v,P,D.value,S),D!==null&&(s&&D.alternate!==null&&I.delete(D.key===null?P:D.key),b=i(D,b,P),E===null?C=D:E.sibling=D,E=D);return s&&I.forEach(function(U){return t(v,U)}),Kp&&LR(v,P),C}function y(v,b,w,S){if(typeof w=="object"&&w!==null&&w.type===BU&&w.key===null&&(w=w.props.children),typeof w=="object"&&w!==null){switch(w.$$typeof){case Qle:e:{for(var C=w.key,E=b;E!==null;){if(E.key===C){if(C=w.type,C===BU){if(E.tag===7){n(v,E.sibling),b=a(E,w.props.children),b.return=v,v=b;break e}}else if(E.elementType===C||typeof C=="object"&&C!==null&&C.$$typeof===nP&&zpt(C)===E.type){n(v,E.sibling),b=a(E,w.props),b.ref=gZ(v,E,w),b.return=v,v=b;break e}n(v,E);break}else t(v,E);E=E.sibling}w.type===BU?(b=Fz(w.props.children,v.mode,S,w.key),b.return=v,v=b):(S=gme(w.type,w.key,w.props,null,v.mode,S),S.ref=gZ(v,b,w),S.return=v,v=S)}return l(v);case zU:e:{for(E=w.key;b!==null;){if(b.key===E)if(b.tag===4&&b.stateNode.containerInfo===w.containerInfo&&b.stateNode.implementation===w.implementation){n(v,b.sibling),b=a(b,w.children||[]),b.return=v,v=b;break e}else{n(v,b);break}else t(v,b);b=b.sibling}b=_ze(w,v.mode,S),b.return=v,v=b}return l(v);case nP:return E=w._init,y(v,b,E(w._payload),S)}if(tQ(w))return g(v,b,w,S);if(uZ(w))return x(v,b,w,S);cce(v,w)}return typeof w=="string"&&w!==""||typeof w=="number"?(w=""+w,b!==null&&b.tag===6?(n(v,b.sibling),b=a(b,w),b.return=v,v=b):(n(v,b),b=bze(w,v.mode,S),b.return=v,v=b),l(v)):n(v,b)}return y}var hG=WLt(!0),KLt=WLt(!1),sEe=e6(null),nEe=null,KU=null,TJe=null;function MJe(){TJe=KU=nEe=null}function PJe(s){var t=sEe.current;Cp(sEe),s._currentValue=t}function fVe(s,t,n){for(;s!==null;){var r=s.alternate;if((s.childLanes&t)!==t?(s.childLanes|=t,r!==null&&(r.childLanes|=t)):r!==null&&(r.childLanes&t)!==t&&(r.childLanes|=t),s===n)break;s=s.return}}function Aq(s,t){nEe=s,TJe=KU=null,s=s.dependencies,s!==null&&s.firstContext!==null&&(s.lanes&t&&(Nw=!0),s.firstContext=null)}function uk(s){var t=s._currentValue;if(TJe!==s)if(s={context:s,memoizedValue:t,next:null},KU===null){if(nEe===null)throw Error(vi(308));KU=s,nEe.dependencies={lanes:0,firstContext:s}}else KU=KU.next=s;return t}var i8=null;function IJe(s){i8===null?i8=[s]:i8.push(s)}function YLt(s,t,n,r){var a=t.interleaved;return a===null?(n.next=n,IJe(t)):(n.next=a.next,a.next=n),t.interleaved=n,lT(s,r)}function lT(s,t){s.lanes|=t;var n=s.alternate;for(n!==null&&(n.lanes|=t),n=s,s=s.return;s!==null;)s.childLanes|=t,n=s.alternate,n!==null&&(n.childLanes|=t),n=s,s=s.return;return n.tag===3?n.stateNode:null}var rP=!1;function LJe(s){s.updateQueue={baseState:s.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,interleaved:null,lanes:0},effects:null}}function ZLt(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 CE(s,t){return{eventTime:s,lane:t,tag:0,payload:null,callback:null,next:null}}function RI(s,t,n){var r=s.updateQueue;if(r===null)return null;if(r=r.shared,Sh&2){var a=r.pending;return a===null?t.next=t:(t.next=a.next,a.next=t),r.pending=t,lT(s,n)}return a=r.interleaved,a===null?(t.next=t,IJe(r)):(t.next=a.next,a.next=t),r.interleaved=t,lT(s,n)}function dme(s,t,n){if(t=t.updateQueue,t!==null&&(t=t.shared,(n&4194240)!==0)){var r=t.lanes;r&=s.pendingLanes,n|=r,t.lanes=n,vJe(s,n)}}function Bpt(s,t){var n=s.updateQueue,r=s.alternate;if(r!==null&&(r=r.updateQueue,n===r)){var a=null,i=null;if(n=n.firstBaseUpdate,n!==null){do{var l={eventTime:n.eventTime,lane:n.lane,tag:n.tag,payload:n.payload,callback:n.callback,next:null};i===null?a=i=l:i=i.next=l,n=n.next}while(n!==null);i===null?a=i=t:i=i.next=t}else a=i=t;n={baseState:r.baseState,firstBaseUpdate:a,lastBaseUpdate:i,shared:r.shared,effects:r.effects},s.updateQueue=n;return}s=n.lastBaseUpdate,s===null?n.firstBaseUpdate=t:s.next=t,n.lastBaseUpdate=t}function rEe(s,t,n,r){var a=s.updateQueue;rP=!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 u=s.alternate;u!==null&&(u=u.updateQueue,o=u.lastBaseUpdate,o!==l&&(o===null?u.firstBaseUpdate=d:o.next=d,u.lastBaseUpdate=c))}if(i!==null){var h=a.baseState;l=0,u=d=c=null,o=i;do{var m=o.lane,f=o.eventTime;if((r&m)===m){u!==null&&(u=u.next={eventTime:f,lane:0,tag:o.tag,payload:o.payload,callback:o.callback,next:null});e:{var g=s,x=o;switch(m=t,f=n,x.tag){case 1:if(g=x.payload,typeof g=="function"){h=g.call(f,h,m);break e}h=g;break e;case 3:g.flags=g.flags&-65537|128;case 0:if(g=x.payload,m=typeof g=="function"?g.call(f,h,m):g,m==null)break e;h=Gg({},h,m);break e;case 2:rP=!0}}o.callback!==null&&o.lane!==0&&(s.flags|=64,m=a.effects,m===null?a.effects=[o]:m.push(o))}else f={eventTime:f,lane:m,tag:o.tag,payload:o.payload,callback:o.callback,next:null},u===null?(d=u=f,c=h):u=u.next=f,l|=m;if(o=o.next,o===null){if(o=a.shared.pending,o===null)break;m=o,o=m.next,m.next=null,a.lastBaseUpdate=m,a.shared.pending=null}}while(!0);if(u===null&&(c=h),a.baseState=c,a.firstBaseUpdate=d,a.lastBaseUpdate=u,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);O7|=l,s.lanes=l,s.memoizedState=h}}function $pt(s,t,n){if(s=t.effects,t.effects=null,s!==null)for(t=0;tn?n:4,s(!0);var r=pze.transition;pze.transition={};try{s(!1),t()}finally{Dm=n,pze.transition=r}}function m6t(){return hk().memoizedState}function lys(s,t,n){var r=FI(s);if(n={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null},f6t(s))p6t(t,n);else if(n=YLt(s,t,n,r),n!==null){var a=k_();ZS(n,s,r,a),g6t(n,t,r)}}function cys(s,t,n){var r=FI(s),a={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null};if(f6t(s))p6t(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,n);if(a.hasEagerState=!0,a.eagerState=o,fC(o,l)){var c=t.interleaved;c===null?(a.next=a,IJe(t)):(a.next=c.next,c.next=a),t.interleaved=a;return}}catch{}finally{}n=YLt(s,t,a,r),n!==null&&(a=k_(),ZS(n,s,r,a),g6t(n,t,r))}}function f6t(s){var t=s.alternate;return s===Rg||t!==null&&t===Rg}function p6t(s,t){dJ=iEe=!0;var n=s.pending;n===null?t.next=t:(t.next=n.next,n.next=t),s.pending=t}function g6t(s,t,n){if(n&4194240){var r=t.lanes;r&=s.pendingLanes,n|=r,t.lanes=n,vJe(s,n)}}var oEe={readContext:uk,useCallback:Yb,useContext:Yb,useEffect:Yb,useImperativeHandle:Yb,useInsertionEffect:Yb,useLayoutEffect:Yb,useMemo:Yb,useReducer:Yb,useRef:Yb,useState:Yb,useDebugValue:Yb,useDeferredValue:Yb,useTransition:Yb,useMutableSource:Yb,useSyncExternalStore:Yb,useId:Yb,unstable_isNewReconciler:!1},dys={readContext:uk,useCallback:function(s,t){return w5().memoizedState=[s,t===void 0?null:t],s},useContext:uk,useEffect:qpt,useImperativeHandle:function(s,t,n){return n=n!=null?n.concat([s]):null,hme(4194308,4,l6t.bind(null,t,s),n)},useLayoutEffect:function(s,t){return hme(4194308,4,s,t)},useInsertionEffect:function(s,t){return hme(4,2,s,t)},useMemo:function(s,t){var n=w5();return t=t===void 0?null:t,s=s(),n.memoizedState=[s,t],s},useReducer:function(s,t,n){var r=w5();return t=n!==void 0?n(t):t,r.memoizedState=r.baseState=t,s={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:s,lastRenderedState:t},r.queue=s,s=s.dispatch=lys.bind(null,Rg,s),[r.memoizedState,s]},useRef:function(s){var t=w5();return s={current:s},t.memoizedState=s},useState:Upt,useDebugValue:UJe,useDeferredValue:function(s){return w5().memoizedState=s},useTransition:function(){var s=Upt(!1),t=s[0];return s=oys.bind(null,s[1]),w5().memoizedState=s,[t,s]},useMutableSource:function(){},useSyncExternalStore:function(s,t,n){var r=Rg,a=w5();if(Kp){if(n===void 0)throw Error(vi(407));n=n()}else{if(n=t(),kv===null)throw Error(vi(349));F7&30||e6t(r,t,n)}a.memoizedState=n;var i={value:n,getSnapshot:t};return a.queue=i,qpt(s6t.bind(null,r,i,s),[s]),r.flags|=2048,Ute(9,t6t.bind(null,r,i,n,t),void 0,null),n},useId:function(){var s=w5(),t=kv.identifierPrefix;if(Kp){var n=xE,r=gE;n=(r&~(1<<32-YS(r)-1)).toString(32)+n,t=":"+t+"R"+n,n=Bte++,0<\/script>",s=s.removeChild(s.firstChild)):typeof r.is=="string"?s=l.createElement(n,{is:r.is}):(s=l.createElement(n),n==="select"&&(l=s,r.multiple?l.multiple=!0:r.size&&(l.size=r.size))):s=l.createElementNS(s,n),s[l4]=t,s[Fte]=r,S6t(s,t,!1,!1),t.stateNode=s;e:{switch(l=Zqe(n,r),n){case"dialog":yp("cancel",s),yp("close",s),a=r;break;case"iframe":case"object":case"embed":yp("load",s),a=r;break;case"video":case"audio":for(a=0;apG&&(t.flags|=128,r=!0,xZ(i,!1),t.lanes=4194304)}else{if(!r)if(s=aEe(l),s!==null){if(t.flags|=128,r=!0,n=s.updateQueue,n!==null&&(t.updateQueue=n,t.flags|=4),xZ(i,!0),i.tail===null&&i.tailMode==="hidden"&&!l.alternate&&!Kp)return Zb(t),null}else 2*ey()-i.renderingStartTime>pG&&n!==1073741824&&(t.flags|=128,r=!0,xZ(i,!1),t.lanes=4194304);i.isBackwards?(l.sibling=t.child,t.child=l):(n=i.last,n!==null?n.sibling=l:t.child=l,i.last=l)}return i.tail!==null?(t=i.tail,i.rendering=t,i.tail=t.sibling,i.renderingStartTime=ey(),t.sibling=null,n=kg.current,Kf(kg,r?n&1|2:n&1),t):(Zb(t),null);case 22:case 23:return KJe(),r=t.memoizedState!==null,s!==null&&s.memoizedState!==null!==r&&(t.flags|=8192),r&&t.mode&1?Hj&1073741824&&(Zb(t),t.subtreeFlags&6&&(t.flags|=8192)):Zb(t),null;case 24:return null;case 25:return null}throw Error(vi(156,t.tag))}function yys(s,t){switch(AJe(t),t.tag){case 1:return Tw(t.type)&&QAe(),s=t.flags,s&65536?(t.flags=s&-65537|128,t):null;case 3:return mG(),Cp(Ew),Cp(S1),FJe(),s=t.flags,s&65536&&!(s&128)?(t.flags=s&-65537|128,t):null;case 5:return DJe(t),null;case 13:if(Cp(kg),s=t.memoizedState,s!==null&&s.dehydrated!==null){if(t.alternate===null)throw Error(vi(340));uG()}return s=t.flags,s&65536?(t.flags=s&-65537|128,t):null;case 19:return Cp(kg),null;case 4:return mG(),null;case 10:return PJe(t.type._context),null;case 22:case 23:return KJe(),null;case 24:return null;default:return null}}var uce=!1,m1=!1,vys=typeof WeakSet=="function"?WeakSet:Set,Mo=null;function YU(s,t){var n=s.ref;if(n!==null)if(typeof n=="function")try{n(null)}catch(r){gx(s,t,r)}else n.current=null}function jVe(s,t,n){try{n()}catch(r){gx(s,t,r)}}var egt=!1;function bys(s,t){if(iVe=KAe,s=ILt(),SJe(s)){if("selectionStart"in s)var n={start:s.selectionStart,end:s.selectionEnd};else e:{n=(n=s.ownerDocument)&&n.defaultView||window;var r=n.getSelection&&n.getSelection();if(r&&r.rangeCount!==0){n=r.anchorNode;var a=r.anchorOffset,i=r.focusNode;r=r.focusOffset;try{n.nodeType,i.nodeType}catch{n=null;break e}var l=0,o=-1,c=-1,d=0,u=0,h=s,m=null;t:for(;;){for(var f;h!==n||a!==0&&h.nodeType!==3||(o=l+a),h!==i||r!==0&&h.nodeType!==3||(c=l+r),h.nodeType===3&&(l+=h.nodeValue.length),(f=h.firstChild)!==null;)m=h,h=f;for(;;){if(h===s)break t;if(m===n&&++d===a&&(o=l),m===i&&++u===r&&(c=l),(f=h.nextSibling)!==null)break;h=m,m=h.parentNode}h=f}n=o===-1||c===-1?null:{start:o,end:c}}else n=null}n=n||{start:0,end:0}}else n=null;for(oVe={focusedElem:s,selectionRange:n},KAe=!1,Mo=t;Mo!==null;)if(t=Mo,s=t.child,(t.subtreeFlags&1028)!==0&&s!==null)s.return=t,Mo=s;else for(;Mo!==null;){t=Mo;try{var g=t.alternate;if(t.flags&1024)switch(t.tag){case 0:case 11:case 15:break;case 1:if(g!==null){var x=g.memoizedProps,y=g.memoizedState,v=t.stateNode,b=v.getSnapshotBeforeUpdate(t.elementType===t.type?x:gS(t.type,x),y);v.__reactInternalSnapshotBeforeUpdate=b}break;case 3:var w=t.stateNode.containerInfo;w.nodeType===1?w.textContent="":w.nodeType===9&&w.documentElement&&w.removeChild(w.documentElement);break;case 5:case 6:case 4:case 17:break;default:throw Error(vi(163))}}catch(S){gx(t,t.return,S)}if(s=t.sibling,s!==null){s.return=t.return,Mo=s;break}Mo=t.return}return g=egt,egt=!1,g}function uJ(s,t,n){var r=t.updateQueue;if(r=r!==null?r.lastEffect:null,r!==null){var a=r=r.next;do{if((a.tag&s)===s){var i=a.destroy;a.destroy=void 0,i!==void 0&&jVe(t,n,i)}a=a.next}while(a!==r)}}function RIe(s,t){if(t=t.updateQueue,t=t!==null?t.lastEffect:null,t!==null){var n=t=t.next;do{if((n.tag&s)===s){var r=n.create;n.destroy=r()}n=n.next}while(n!==t)}}function NVe(s){var t=s.ref;if(t!==null){var n=s.stateNode;switch(s.tag){case 5:s=n;break;default:s=n}typeof t=="function"?t(s):t.current=s}}function E6t(s){var t=s.alternate;t!==null&&(s.alternate=null,E6t(t)),s.child=null,s.deletions=null,s.sibling=null,s.tag===5&&(t=s.stateNode,t!==null&&(delete t[l4],delete t[Fte],delete t[dVe],delete t[sys],delete t[nys])),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 T6t(s){return s.tag===5||s.tag===3||s.tag===4}function tgt(s){e:for(;;){for(;s.sibling===null;){if(s.return===null||T6t(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 kVe(s,t,n){var r=s.tag;if(r===5||r===6)s=s.stateNode,t?n.nodeType===8?n.parentNode.insertBefore(s,t):n.insertBefore(s,t):(n.nodeType===8?(t=n.parentNode,t.insertBefore(s,n)):(t=n,t.appendChild(s)),n=n._reactRootContainer,n!=null||t.onclick!==null||(t.onclick=XAe));else if(r!==4&&(s=s.child,s!==null))for(kVe(s,t,n),s=s.sibling;s!==null;)kVe(s,t,n),s=s.sibling}function SVe(s,t,n){var r=s.tag;if(r===5||r===6)s=s.stateNode,t?n.insertBefore(s,t):n.appendChild(s);else if(r!==4&&(s=s.child,s!==null))for(SVe(s,t,n),s=s.sibling;s!==null;)SVe(s,t,n),s=s.sibling}var nb=null,IS=!1;function xM(s,t,n){for(n=n.child;n!==null;)M6t(s,t,n),n=n.sibling}function M6t(s,t,n){if(C4&&typeof C4.onCommitFiberUnmount=="function")try{C4.onCommitFiberUnmount(CIe,n)}catch{}switch(n.tag){case 5:m1||YU(n,t);case 6:var r=nb,a=IS;nb=null,xM(s,t,n),nb=r,IS=a,nb!==null&&(IS?(s=nb,n=n.stateNode,s.nodeType===8?s.parentNode.removeChild(n):s.removeChild(n)):nb.removeChild(n.stateNode));break;case 18:nb!==null&&(IS?(s=nb,n=n.stateNode,s.nodeType===8?hze(s.parentNode,n):s.nodeType===1&&hze(s,n),Pte(s)):hze(nb,n.stateNode));break;case 4:r=nb,a=IS,nb=n.stateNode.containerInfo,IS=!0,xM(s,t,n),nb=r,IS=a;break;case 0:case 11:case 14:case 15:if(!m1&&(r=n.updateQueue,r!==null&&(r=r.lastEffect,r!==null))){a=r=r.next;do{var i=a,l=i.destroy;i=i.tag,l!==void 0&&(i&2||i&4)&&jVe(n,t,l),a=a.next}while(a!==r)}xM(s,t,n);break;case 1:if(!m1&&(YU(n,t),r=n.stateNode,typeof r.componentWillUnmount=="function"))try{r.props=n.memoizedProps,r.state=n.memoizedState,r.componentWillUnmount()}catch(o){gx(n,t,o)}xM(s,t,n);break;case 21:xM(s,t,n);break;case 22:n.mode&1?(m1=(r=m1)||n.memoizedState!==null,xM(s,t,n),m1=r):xM(s,t,n);break;default:xM(s,t,n)}}function sgt(s){var t=s.updateQueue;if(t!==null){s.updateQueue=null;var n=s.stateNode;n===null&&(n=s.stateNode=new vys),t.forEach(function(r){var a=Eys.bind(null,s,r);n.has(r)||(n.add(r),r.then(a,a))})}}function eS(s,t){var n=t.deletions;if(n!==null)for(var r=0;ra&&(a=l),r&=~i}if(r=a,r=ey()-r,r=(120>r?120:480>r?480:1080>r?1080:1920>r?1920:3e3>r?3e3:4320>r?4320:1960*wys(r/1960))-r,10s?16:s,gI===null)var r=!1;else{if(s=gI,gI=null,dEe=0,Sh&6)throw Error(vi(331));var a=Sh;for(Sh|=4,Mo=s.current;Mo!==null;){var i=Mo,l=i.child;if(Mo.flags&16){var o=i.deletions;if(o!==null){for(var c=0;cey()-GJe?Dz(s,0):HJe|=n),Mw(s,t)}function z6t(s,t){t===0&&(s.mode&1?(t=sce,sce<<=1,!(sce&130023424)&&(sce=4194304)):t=1);var n=k_();s=lT(s,t),s!==null&&(xae(s,t,n),Mw(s,n))}function Ays(s){var t=s.memoizedState,n=0;t!==null&&(n=t.retryLane),z6t(s,n)}function Eys(s,t){var n=0;switch(s.tag){case 13:var r=s.stateNode,a=s.memoizedState;a!==null&&(n=a.retryLane);break;case 19:r=s.stateNode;break;default:throw Error(vi(314))}r!==null&&r.delete(t),z6t(s,n)}var B6t;B6t=function(s,t,n){if(s!==null)if(s.memoizedProps!==t.pendingProps||Ew.current)Nw=!0;else{if(!(s.lanes&n)&&!(t.flags&128))return Nw=!1,gys(s,t,n);Nw=!!(s.flags&131072)}else Nw=!1,Kp&&t.flags&1048576&&VLt(t,tEe,t.index);switch(t.lanes=0,t.tag){case 2:var r=t.type;mme(s,t),s=t.pendingProps;var a=dG(t,S1.current);Aq(t,n),a=zJe(null,t,r,s,a,n);var i=BJe();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,Tw(r)?(i=!0,JAe(t)):i=!1,t.memoizedState=a.state!==null&&a.state!==void 0?a.state:null,LJe(t),a.updater=LIe,t.stateNode=a,a._reactInternals=t,gVe(t,r,s,n),t=vVe(null,t,r,!0,i,n)):(t.tag=0,Kp&&i&&CJe(t),c_(null,t,a,n),t=t.child),t;case 16:r=t.elementType;e:{switch(mme(s,t),s=t.pendingProps,a=r._init,r=a(r._payload),t.type=r,a=t.tag=Mys(r),s=gS(r,s),a){case 0:t=yVe(null,t,r,s,n);break e;case 1:t=Xpt(null,t,r,s,n);break e;case 11:t=Ypt(null,t,r,s,n);break e;case 14:t=Zpt(null,t,r,gS(r.type,s),n);break e}throw Error(vi(306,r,""))}return t;case 0:return r=t.type,a=t.pendingProps,a=t.elementType===r?a:gS(r,a),yVe(s,t,r,a,n);case 1:return r=t.type,a=t.pendingProps,a=t.elementType===r?a:gS(r,a),Xpt(s,t,r,a,n);case 3:e:{if(j6t(t),s===null)throw Error(vi(387));r=t.pendingProps,i=t.memoizedState,a=i.element,ZLt(s,t),rEe(t,r,null,n);var l=t.memoizedState;if(r=l.element,i.isDehydrated)if(i={element:r,isDehydrated:!1,cache:l.cache,pendingSuspenseBoundaries:l.pendingSuspenseBoundaries,transitions:l.transitions},t.updateQueue.baseState=i,t.memoizedState=i,t.flags&256){a=fG(Error(vi(423)),t),t=Qpt(s,t,r,n,a);break e}else if(r!==a){a=fG(Error(vi(424)),t),t=Qpt(s,t,r,n,a);break e}else for(e2=LI(t.stateNode.containerInfo.firstChild),o2=t,Kp=!0,zS=null,n=KLt(t,null,r,n),t.child=n;n;)n.flags=n.flags&-3|4096,n=n.sibling;else{if(uG(),r===a){t=cT(s,t,n);break e}c_(s,t,r,n)}t=t.child}return t;case 5:return XLt(t),s===null&&mVe(t),r=t.type,a=t.pendingProps,i=s!==null?s.memoizedProps:null,l=a.children,lVe(r,a)?l=null:i!==null&&lVe(r,i)&&(t.flags|=32),w6t(s,t),c_(s,t,l,n),t.child;case 6:return s===null&&mVe(t),null;case 13:return N6t(s,t,n);case 4:return RJe(t,t.stateNode.containerInfo),r=t.pendingProps,s===null?t.child=hG(t,null,r,n):c_(s,t,r,n),t.child;case 11:return r=t.type,a=t.pendingProps,a=t.elementType===r?a:gS(r,a),Ypt(s,t,r,a,n);case 7:return c_(s,t,t.pendingProps,n),t.child;case 8:return c_(s,t,t.pendingProps.children,n),t.child;case 12:return c_(s,t,t.pendingProps.children,n),t.child;case 10:e:{if(r=t.type._context,a=t.pendingProps,i=t.memoizedProps,l=a.value,Kf(sEe,r._currentValue),r._currentValue=l,i!==null)if(fC(i.value,l)){if(i.children===a.children&&!Ew.current){t=cT(s,t,n);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===r){if(i.tag===1){c=CE(-1,n&-n),c.tag=2;var d=i.updateQueue;if(d!==null){d=d.shared;var u=d.pending;u===null?c.next=c:(c.next=u.next,u.next=c),d.pending=c}}i.lanes|=n,c=i.alternate,c!==null&&(c.lanes|=n),fVe(i.return,n,t),o.lanes|=n;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(vi(341));l.lanes|=n,o=l.alternate,o!==null&&(o.lanes|=n),fVe(l,n,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}c_(s,t,a.children,n),t=t.child}return t;case 9:return a=t.type,r=t.pendingProps.children,Aq(t,n),a=uk(a),r=r(a),t.flags|=1,c_(s,t,r,n),t.child;case 14:return r=t.type,a=gS(r,t.pendingProps),a=gS(r.type,a),Zpt(s,t,r,a,n);case 15:return b6t(s,t,t.type,t.pendingProps,n);case 17:return r=t.type,a=t.pendingProps,a=t.elementType===r?a:gS(r,a),mme(s,t),t.tag=1,Tw(r)?(s=!0,JAe(t)):s=!1,Aq(t,n),x6t(t,r,a),gVe(t,r,a,n),vVe(null,t,r,!0,s,n);case 19:return k6t(s,t,n);case 22:return _6t(s,t,n)}throw Error(vi(156,t.tag))};function $6t(s,t){return fLt(s,t)}function Tys(s,t,n,r){this.tag=s,this.key=n,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=r,this.subtreeFlags=this.flags=0,this.deletions=null,this.childLanes=this.lanes=0,this.alternate=null}function GN(s,t,n,r){return new Tys(s,t,n,r)}function ZJe(s){return s=s.prototype,!(!s||!s.isReactComponent)}function Mys(s){if(typeof s=="function")return ZJe(s)?1:0;if(s!=null){if(s=s.$$typeof,s===pJe)return 11;if(s===gJe)return 14}return 2}function OI(s,t){var n=s.alternate;return n===null?(n=GN(s.tag,t,s.key,s.mode),n.elementType=s.elementType,n.type=s.type,n.stateNode=s.stateNode,n.alternate=s,s.alternate=n):(n.pendingProps=t,n.type=s.type,n.flags=0,n.subtreeFlags=0,n.deletions=null),n.flags=s.flags&14680064,n.childLanes=s.childLanes,n.lanes=s.lanes,n.child=s.child,n.memoizedProps=s.memoizedProps,n.memoizedState=s.memoizedState,n.updateQueue=s.updateQueue,t=s.dependencies,n.dependencies=t===null?null:{lanes:t.lanes,firstContext:t.firstContext},n.sibling=s.sibling,n.index=s.index,n.ref=s.ref,n}function gme(s,t,n,r,a,i){var l=2;if(r=s,typeof s=="function")ZJe(s)&&(l=1);else if(typeof s=="string")l=5;else e:switch(s){case BU:return Fz(n.children,a,i,t);case fJe:l=8,a|=8;break;case Bqe:return s=GN(12,n,t,a|2),s.elementType=Bqe,s.lanes=i,s;case $qe:return s=GN(13,n,t,a),s.elementType=$qe,s.lanes=i,s;case Uqe:return s=GN(19,n,t,a),s.elementType=Uqe,s.lanes=i,s;case XIt:return FIe(n,a,i,t);default:if(typeof s=="object"&&s!==null)switch(s.$$typeof){case YIt:l=10;break e;case ZIt:l=9;break e;case pJe:l=11;break e;case gJe:l=14;break e;case nP:l=16,r=null;break e}throw Error(vi(130,s==null?s:typeof s,""))}return t=GN(l,n,t,a),t.elementType=s,t.type=r,t.lanes=i,t}function Fz(s,t,n,r){return s=GN(7,s,r,t),s.lanes=n,s}function FIe(s,t,n,r){return s=GN(22,s,r,t),s.elementType=XIt,s.lanes=n,s.stateNode={isHidden:!1},s}function bze(s,t,n){return s=GN(6,s,null,t),s.lanes=n,s}function _ze(s,t,n){return t=GN(4,s.children!==null?s.children:[],s.key,t),t.lanes=n,t.stateNode={containerInfo:s.containerInfo,pendingChildren:null,implementation:s.implementation},t}function Pys(s,t,n,r,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=tze(0),this.expirationTimes=tze(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=tze(0),this.identifierPrefix=r,this.onRecoverableError=a,this.mutableSourceEagerHydrationData=null}function XJe(s,t,n,r,a,i,l,o,c){return s=new Pys(s,t,n,o,c),t===1?(t=1,i===!0&&(t|=8)):t=0,i=GN(3,null,null,t),s.current=i,i.stateNode=s,i.memoizedState={element:r,isDehydrated:n,cache:null,transitions:null,pendingSuspenseBoundaries:null},LJe(i),s}function Iys(s,t,n){var r=3"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(H6t)}catch(s){console.error(s)}}H6t(),HIt.exports=U2;var wv=HIt.exports;const G6t=au(wv);var W6t,dgt=wv;W6t=dgt.createRoot,dgt.hydrateRoot;const Oys="modulepreload",zys=function(s){return"/"+s},ugt={},ri=function(t,n,r){let a=Promise.resolve();if(n&&n.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(n.map(c=>{if(c=zys(c),c in ugt)return;ugt[c]=!0;const d=c.endsWith(".css"),u=d?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${c}"]${u}`))return;const h=document.createElement("link");if(h.rel=d?"stylesheet":Oys,d||(h.as="script"),h.crossOrigin="",h.href=c,o&&h.setAttribute("nonce",o),document.head.appendChild(h),d)return new Promise((m,f)=>{h.addEventListener("load",m),h.addEventListener("error",()=>f(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)})},Bys=new Set(["localhost","relevelup.com","thelocalmove.com","www.thelocalmove.com"]),$ys=s=>s.toLowerCase().replace(/:\d+$/,"").replace(/^www\./,"");function Uys(s){return!!(s==="localhost"||s.endsWith(".localhost")||/^\d{1,3}(\.\d{1,3}){3}$/.test(s)||s.endsWith(".lovable.app")||s.endsWith(".lovableproject.com")||s.endsWith(".lovable.dev")||s.endsWith(".vercel.app")||s==="relevelup.com"||s.endsWith(".relevelup.com")||s==="thelocalmove.com"||s.endsWith(".thelocalmove.com")||Bys.has(s))}function K6t(s){return Y6t(s)!==null}function Y6t(s){const t=$ys(s);return Uys(t)?null:t}const qys=1,Vys=1e6;let wze=0;function Hys(){return wze=(wze+1)%Number.MAX_SAFE_INTEGER,wze.toString()}const jze=new Map,hgt=s=>{if(jze.has(s))return;const t=setTimeout(()=>{jze.delete(s),fJ({type:"REMOVE_TOAST",toastId:s})},Vys);jze.set(s,t)},Gys=(s,t)=>{switch(t.type){case"ADD_TOAST":return{...s,toasts:[t.toast,...s.toasts].slice(0,qys)};case"UPDATE_TOAST":return{...s,toasts:s.toasts.map(n=>n.id===t.toast.id?{...n,...t.toast}:n)};case"DISMISS_TOAST":{const{toastId:n}=t;return n?hgt(n):s.toasts.forEach(r=>{hgt(r.id)}),{...s,toasts:s.toasts.map(r=>r.id===n||n===void 0?{...r,open:!1}:r)}}case"REMOVE_TOAST":return t.toastId===void 0?{...s,toasts:[]}:{...s,toasts:s.toasts.filter(n=>n.id!==t.toastId)}}},xme=[];let yme={toasts:[]};function fJ(s){yme=Gys(yme,s),xme.forEach(t=>{t(yme)})}function _a({...s}){const t=Hys(),n=a=>fJ({type:"UPDATE_TOAST",toast:{...a,id:t}}),r=()=>fJ({type:"DISMISS_TOAST",toastId:t});return fJ({type:"ADD_TOAST",toast:{...s,id:t,open:!0,onOpenChange:a=>{a||r()}}}),{id:t,dismiss:r,update:n}}function Bi(){const[s,t]=j.useState(yme);return j.useEffect(()=>(xme.push(t),()=>{const n=xme.indexOf(t);n>-1&&xme.splice(n,1)}),[s]),{...s,toast:_a,dismiss:n=>fJ({type:"DISMISS_TOAST",toastId:n})}}var Wys=Object.defineProperty,VW=(s,t)=>Wys(s,"name",{value:t,configurable:!0}),Z6t=!!(typeof window<"u"&&window.document&&window.document.createElement);function Ra(s,t,{checkForDefaultPrevented:n=!0}={}){return VW(function(a){if(s==null||s(a),n===!1||!a||!a.defaultPrevented)return t==null?void 0:t(a)},"handleEvent")}VW(Ra,"composeEventHandlers");function Kys(s){var t;if(!Z6t)throw new Error("Cannot access window outside of the DOM");return((t=s==null?void 0:s.ownerDocument)==null?void 0:t.defaultView)??window}VW(Kys,"getOwnerWindow");function MVe(s){if(!Z6t)throw new Error("Cannot access document outside of the DOM");return(s==null?void 0:s.ownerDocument)??document}VW(MVe,"getOwnerDocument");function X6t(s,t=!1){const{activeElement:n}=MVe(s);if(!(n!=null&&n.nodeName))return null;if(Q6t(n)&&n.contentDocument)return X6t(n.contentDocument.body,t);if(t){const r=n.getAttribute("aria-activedescendant");if(r){const a=MVe(n).getElementById(r);if(a)return a}}return n}VW(X6t,"getActiveElement");function Q6t(s){return s.tagName==="IFRAME"}VW(Q6t,"isFrame");var Yys=Object.defineProperty,tet=(s,t)=>Yys(s,"name",{value:t,configurable:!0});function PVe(s,t){if(typeof s=="function")return s(t);s!=null&&(s.current=t)}tet(PVe,"setRef");function B7(...s){return t=>{let n=!1;const r=s.map(a=>{const i=PVe(a,t);return!n&&typeof i=="function"&&(n=!0),i});if(n)return()=>{for(let a=0;aZys(s,"name",{value:t,configurable:!0});function Xys(s,t){const n=j.createContext(t);n.displayName=s+"Context";const r=ON(i=>{const{children:l,...o}=i,c=j.useMemo(()=>o,Object.values(o));return e.jsx(n.Provider,{value:c,children:l})},"Provider");r.displayName=s+"Provider";function a(i,l={}){const{optional:o=!1}=l,c=j.useContext(n);if(c)return c;if(t!==void 0)return t;if(!o)throw new Error(`\`${i}\` must be used within \`${s}\``)}return ON(a,"useContext"),[r,a]}ON(Xys,"createContext");function tp(s,t=[]){let n=[];function r(i,l){const o=j.createContext(l);o.displayName=i+"Context";const c=n.length;n=[...n,l];const d=ON(h=>{var v;const{scope:m,children:f,...g}=h,x=((v=m==null?void 0:m[s])==null?void 0:v[c])||o,y=j.useMemo(()=>g,Object.values(g));return e.jsx(x.Provider,{value:y,children:f})},"Provider");d.displayName=i+"Provider";function u(h,m,f={}){var v;const{optional:g=!1}=f,x=((v=m==null?void 0:m[s])==null?void 0:v[c])||o,y=j.useContext(x);if(y)return y;if(l!==void 0)return l;if(!g)throw new Error(`\`${h}\` must be used within \`${i}\``)}return ON(u,"useContext"),[d,u]}ON(r,"createContext");const a=ON(()=>{const i=n.map(l=>j.createContext(l));return ON(function(o){const c=(o==null?void 0:o[s])||i;return j.useMemo(()=>({[`__scope${s}`]:{...o,[s]:c}}),[o,c])},"useScope")},"createScope");return a.scopeName=s,[r,J6t(a,...t)]}ON(tp,"createContextScope");function J6t(...s){const t=s[0];if(s.length===1)return t;const n=ON(()=>{const r=s.map(a=>({useScope:a(),scopeName:a.scopeName}));return ON(function(i){const l=r.reduce((o,{useScope:c,scopeName:d})=>{const h=c(i)[`__scope${d}`];return{...o,...h}},{});return j.useMemo(()=>({[`__scope${t.scopeName}`]:l}),[l])},"useComposedScopes")},"createScope");return n.scopeName=t.scopeName,n}ON(J6t,"composeContextScopes");var Qys=Object.defineProperty,_C=(s,t)=>Qys(s,"name",{value:t,configurable:!0});function pC(s){const t=j.forwardRef((n,r)=>{let{children:a,...i}=n,l=null,o=!1;const c=[];IVe(a)&&typeof fce=="function"&&(a=fce(a._payload)),j.Children.forEach(a,m=>{var f;if(rRt(m)){o=!0;const g=m;let x="child"in g.props?g.props.child:g.props.children;IVe(x)&&typeof fce=="function"&&(x=fce(x._payload)),l=Jys(g,x),c.push((f=l==null?void 0:l.props)==null?void 0:f.children)}else c.push(m)}),l?l=j.cloneElement(l,void 0,c):!o&&j.Children.count(a)===1&&j.isValidElement(a)&&(l=a);const d=l?nRt(l):void 0,u=Vo(r,d);if(!l){if(a||a===0)throw new Error(o?s0s(s):t0s(s));return a}const h=sRt(i,l.props??{});return l.type!==j.Fragment&&(h.ref=r?u:d),j.cloneElement(l,h)});return t.displayName=`${s}.Slot`,t}_C(pC,"createSlot");var set=pC("Slot"),eRt=Symbol.for("radix.slottable");function tRt(s){const t=_C(n=>"child"in n?n.children(n.child):n.children,"Slottable");return t.displayName=`${s}.Slottable`,t.__radixId=eRt,t}_C(tRt,"createSlottable");var Jys=_C((s,t)=>{if("child"in s.props){const n=s.props.child;return j.isValidElement(n)?j.cloneElement(n,void 0,s.props.children(n.props.children)):null}return j.isValidElement(t)?t:null},"getSlottableElementFromSlottable");function sRt(s,t){const n={...t};for(const r in t){const a=s[r],i=t[r];/^on[A-Z]/.test(r)?a&&i?n[r]=(...o)=>{const c=i(...o);return a(...o),c}:a&&(n[r]=a):r==="style"?n[r]={...a,...i}:r==="className"&&(n[r]=[a,i].filter(Boolean).join(" "))}return{...s,...n}}_C(sRt,"mergeProps");function nRt(s){var r,a;let t=(r=Object.getOwnPropertyDescriptor(s.props,"ref"))==null?void 0:r.get,n=t&&"isReactWarning"in t&&t.isReactWarning;return n?s.ref:(t=(a=Object.getOwnPropertyDescriptor(s,"ref"))==null?void 0:a.get,n=t&&"isReactWarning"in t&&t.isReactWarning,n?s.props.ref:s.props.ref||s.ref)}_C(nRt,"getElementRef");function rRt(s){return j.isValidElement(s)&&typeof s.type=="function"&&"__radixId"in s.type&&s.type.__radixId===eRt}_C(rRt,"isSlottable");var e0s=Symbol.for("react.lazy");function IVe(s){return s!=null&&typeof s=="object"&&"$$typeof"in s&&s.$$typeof===e0s&&"_payload"in s&&aRt(s._payload)}_C(IVe,"isLazyComponent");function aRt(s){return typeof s=="object"&&s!==null&&"then"in s}_C(aRt,"isPromiseLike");var t0s=_C(s=>`${s} failed to slot onto its children. Expected a single React element child or \`Slottable\`.`,"createSlotError"),s0s=_C(s=>`${s} failed to slot onto its \`Slottable\`. Expected \`Slottable\` to receive a single React element child.`,"createSlottableError"),fce=MB[" use ".trim().toString()],n0s=Object.defineProperty,yv=(s,t)=>n0s(s,"name",{value:t,configurable:!0});function LB(s){const t=s+"CollectionProvider",[n,r]=tp(t),[a,i]=n(t,{collectionRef:{current:null},itemMap:new Map}),l=yv(x=>{const{scope:y,children:v}=x,b=j.useRef(null),w=j.useRef(new Map).current;return e.jsx(a,{scope:y,itemMap:w,collectionRef:b,children:v})},"CollectionProvider");l.displayName=t;const o=s+"CollectionSlot",c=pC(o),d=j.forwardRef((x,y)=>{const{scope:v,children:b}=x,w=i(o,v),S=Vo(y,w.collectionRef);return e.jsx(c,{ref:S,children:b})});d.displayName=o;const u=s+"CollectionItemSlot",h="data-radix-collection-item",m=pC(u),f=j.forwardRef((x,y)=>{const{scope:v,children:b,...w}=x,S=j.useRef(null),C=Vo(y,S),E=i(u,v);return j.useEffect(()=>(E.itemMap.set(S,{ref:S,...w}),()=>void E.itemMap.delete(S))),e.jsx(m,{[h]:"",ref:C,children:b})});f.displayName=u;function g(x){const y=i(s+"CollectionConsumer",x);return j.useCallback(()=>{const b=y.collectionRef.current;if(!b)return[];const w=Array.from(b.querySelectorAll(`[${h}]`));return Array.from(y.itemMap.values()).sort((E,I)=>w.indexOf(E.ref.current)-w.indexOf(I.ref.current))},[y.collectionRef,y.itemMap])}return yv(g,"useCollection"),[{Provider:l,Slot:d,ItemSlot:f},g,r]}yv(LB,"createCollection");var mgt=new WeakMap,Ty,Wj,Nze=(Wj=class extends Map{constructor(n){super(n);bs(this,Ty);Kt(this,Ty,[...super.keys()]),mgt.set(this,!0)}set(n,r){return mgt.get(this)&&(this.has(n)?ye(this,Ty)[ye(this,Ty).indexOf(n)]=n:ye(this,Ty).push(n)),super.set(n,r),this}insert(n,r,a){const i=this.has(r),l=ye(this,Ty).length,o=net(n);let c=o>=0?o:l+o;const d=c<0||c>=l?-1:c;if(d===this.size||i&&d===this.size-1||d===-1)return this.set(r,a),this;const u=this.size+(i?0:1);o<0&&c++;const h=[...ye(this,Ty)];let m,f=!1;for(let g=c;g=this.size&&(i=this.size-1),this.at(i)}keyFrom(n,r){const a=this.indexOf(n);if(a===-1)return;let i=a+r;return i<0&&(i=0),i>=this.size&&(i=this.size-1),this.keyAt(i)}find(n,r){let a=0;for(const i of this){if(Reflect.apply(n,r,[i,a,this]))return i;a++}}findIndex(n,r){let a=0;for(const i of this){if(Reflect.apply(n,r,[i,a,this]))return a;a++}return-1}filter(n,r){const a=[];let i=0;for(const l of this)Reflect.apply(n,r,[l,i,this])&&a.push(l),i++;return new Wj(a)}map(n,r){const a=[];let i=0;for(const l of this)a.push([l[0],Reflect.apply(n,r,[l,i,this])]),i++;return new Wj(a)}reduce(...n){const[r,a]=n;let i=0,l=a??this.at(0);for(const o of this)i===0&&n.length===1?l=o:l=Reflect.apply(r,this,[l,o,i,this]),i++;return l}reduceRight(...n){const[r,a]=n;let i=a??this.at(-1);for(let l=this.size-1;l>=0;l--){const o=this.at(l);l===this.size-1&&n.length===1?i=o:i=Reflect.apply(r,this,[i,o,l,this])}return i}toSorted(n){const r=[...this.entries()].sort(n);return new Wj(r)}toReversed(){const n=new Wj;for(let r=this.size-1;r>=0;r--){const a=this.keyAt(r),i=this.get(a);n.set(a,i)}return n}toSpliced(...n){const r=[...this.entries()];return r.splice(...n),new Wj(r)}slice(n,r){const a=new Wj;let i=this.size-1;if(n===void 0)return a;n<0&&(n=n+this.size),r!==void 0&&r>0&&(i=r-1);for(let l=n;l<=i;l++){const o=this.keyAt(l),c=this.get(o);a.set(o,c)}return a}every(n,r){let a=0;for(const i of this){if(!Reflect.apply(n,r,[i,a,this]))return!1;a++}return!0}some(n,r){let a=0;for(const i of this){if(Reflect.apply(n,r,[i,a,this]))return!0;a++}return!1}},Ty=new WeakMap,yv(Wj,"OrderedDict"),Wj);function vme(s,t){if("at"in Array.prototype)return Array.prototype.at.call(s,t);const n=iRt(s,t);return n===-1?void 0:s[n]}yv(vme,"at");function iRt(s,t){const n=s.length,r=net(t),a=r>=0?r:n+r;return a<0||a>=n?-1:a}yv(iRt,"toSafeIndex");function net(s){return s!==s||s===0?0:Math.trunc(s)}yv(net,"toSafeInteger");function r0s(s){const t=s+"CollectionProvider",[n,r]=tp(t),[a,i]=n(t,{collectionElement:null,collectionRef:{current:null},collectionRefObject:{current:null},itemMap:new Nze,setItemMap:yv(()=>{},"setItemMap")}),l=yv(({state:w,...S})=>w?e.jsx(c,{...S,state:w}):e.jsx(o,{...S}),"CollectionProvider");l.displayName=t;const o=yv(w=>{const S=y();return e.jsx(c,{...w,state:S})},"CollectionInit");o.displayName=t+"Init";const c=yv(w=>{const{scope:S,children:C,state:E}=w,I=j.useRef(null),[P,R]=j.useState(null),D=Vo(I,R),[O,U]=E;return j.useEffect(()=>{if(!P)return;const W=cRt(()=>{});return W.observe(P,{childList:!0,subtree:!0}),()=>{W.disconnect()}},[P]),e.jsx(a,{scope:S,itemMap:O,setItemMap:U,collectionRef:D,collectionRefObject:I,collectionElement:P,children:C})},"CollectionProviderImpl");c.displayName=t+"Impl";const d=s+"CollectionSlot",u=pC(d),h=j.forwardRef((w,S)=>{const{scope:C,children:E}=w,I=i(d,C),P=Vo(S,I.collectionRef);return e.jsx(u,{ref:P,children:E})});h.displayName=d;const m=s+"CollectionItemSlot",f="data-radix-collection-item",g=pC(m),x=j.forwardRef((w,S)=>{const{scope:C,children:E,...I}=w,P=j.useRef(null),[R,D]=j.useState(null),O=Vo(S,P,D),U=i(m,C),{setItemMap:W}=U,V=j.useRef(I);oRt(V.current,I)||(V.current=I);const G=V.current;return j.useEffect(()=>{const Y=G;return W(X=>R?X.has(R)?X.set(R,{...Y,element:R}).toSorted(LVe):(X.set(R,{...Y,element:R}),X.toSorted(LVe)):X),()=>{W(X=>!R||!X.has(R)?X:(X.delete(R),new Nze(X)))}},[R,G,W]),e.jsx(g,{[f]:"",ref:O,children:E})});x.displayName=m;function y(){return j.useState(new Nze)}yv(y,"useInitCollection");function v(w){const{itemMap:S}=i(s+"CollectionConsumer",w);return S}return yv(v,"useCollection"),[{Provider:l,Slot:h,ItemSlot:x},{createCollectionScope:r,useCollection:v,useInitCollection:y}]}yv(r0s,"createCollection");function oRt(s,t){if(s===t)return!0;if(typeof s!="object"||typeof t!="object"||s==null||t==null)return!1;const n=Object.keys(s),r=Object.keys(t);if(n.length!==r.length)return!1;for(const a of n)if(!Object.prototype.hasOwnProperty.call(t,a)||s[a]!==t[a])return!1;return!0}yv(oRt,"shallowEqual");function lRt(s,t){return!!(t.compareDocumentPosition(s)&Node.DOCUMENT_POSITION_PRECEDING)}yv(lRt,"isElementPreceding");function LVe(s,t){return!s[1].element||!t[1].element?0:lRt(s[1].element,t[1].element)?-1:1}yv(LVe,"sortByDocumentPosition");function cRt(s){return new MutationObserver(n=>{for(const r of n)if(r.type==="childList"){s();return}})}yv(cRt,"getChildListObserver");var a0s=Object.defineProperty,i0s=(s,t)=>a0s(s,"name",{value:t,configurable:!0}),o0s=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],Ei=o0s.reduce((s,t)=>{const n=pC(`Primitive.${t}`),r=j.forwardRef((a,i)=>{const{asChild:l,...o}=a,c=l?n:t;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),e.jsx(c,{...o,ref:i})});return r.displayName=`Primitive.${t}`,{...s,[t]:r}},{});function UIe(s,t){s&&wv.flushSync(()=>s.dispatchEvent(t))}i0s(UIe,"dispatchDiscreteCustomEvent");var l0s=Object.defineProperty,c0s=(s,t)=>l0s(s,"name",{value:t,configurable:!0});function Yp(s){const t=j.useRef(s);return j.useEffect(()=>{t.current=s}),j.useMemo(()=>(...n)=>{var r;return(r=t.current)==null?void 0:r.call(t,...n)},[])}c0s(Yp,"useCallbackRef");var d0s=Object.defineProperty,g0=(s,t)=>d0s(s,"name",{value:t,configurable:!0}),RVe="dismissableLayer.update",u0s="dismissableLayer.pointerDownOutside",h0s="dismissableLayer.focusOutside",fgt,ret=j.createContext({layers:new Set,layersWithOutsidePointerEventsDisabled:new Set,branches:new Set,dismissableSurfaces:new Set}),RB=j.forwardRef(g0(function(t,n){const{disableOutsidePointerEvents:r=!1,deferPointerDownOutside:a=!1,onEscapeKeyDown:i,onPointerDownOutside:l,onFocusOutside:o,onInteractOutside:c,onDismiss:d,...u}=t,h=j.useContext(ret),[m,f]=j.useState(null),g=(m==null?void 0:m.ownerDocument)??(globalThis==null?void 0:globalThis.document),[,x]=j.useState({}),y=Vo(n,f),v=Array.from(h.layers),[b]=[...h.layersWithOutsidePointerEventsDisabled].slice(-1),w=b?v.indexOf(b):-1,S=m?v.indexOf(m):-1,C=h.layersWithOutsidePointerEventsDisabled.size>0,E=S>=w,I=j.useRef(!1),P=uRt(U=>{l==null||l(U),c==null||c(U),U.defaultPrevented||d==null||d()},{ownerDocument:g,deferPointerDownOutside:a,isDeferredPointerDownOutsideRef:I,dismissableSurfaces:h.dismissableSurfaces,shouldHandlePointerDownOutside:j.useCallback(U=>{if(!(U instanceof Node))return!1;const W=[...h.branches].some(V=>V.contains(U));return E&&!W},[h.branches,E])}),R=hRt(U=>{if(a&&I.current)return;const W=U.target;[...h.branches].some(G=>G.contains(W))||(o==null||o(U),c==null||c(U),U.defaultPrevented||d==null||d())},g),D=m?S===v.length-1:!1,O=Yp(U=>{U.key==="Escape"&&(i==null||i(U),!U.defaultPrevented&&d&&(U.preventDefault(),d()))});return j.useEffect(()=>{if(D)return g.addEventListener("keydown",O,{capture:!0}),()=>g.removeEventListener("keydown",O,{capture:!0})},[g,D,O]),j.useEffect(()=>{if(m)return r&&(h.layersWithOutsidePointerEventsDisabled.size===0&&(fgt=g.body.style.pointerEvents,g.body.style.pointerEvents="none"),h.layersWithOutsidePointerEventsDisabled.add(m)),h.layers.add(m),DVe(),()=>{r&&(h.layersWithOutsidePointerEventsDisabled.delete(m),h.layersWithOutsidePointerEventsDisabled.size===0&&(g.body.style.pointerEvents=fgt))}},[m,g,r,h]),j.useEffect(()=>()=>{m&&(h.layers.delete(m),h.layersWithOutsidePointerEventsDisabled.delete(m),DVe())},[m,h]),j.useEffect(()=>{const U=g0(()=>x({}),"handleUpdate");return document.addEventListener(RVe,U),()=>document.removeEventListener(RVe,U)},[]),e.jsx(Ei.div,{...u,ref:y,style:{pointerEvents:C?E?"auto":"none":void 0,...t.style},onFocusCapture:Ra(t.onFocusCapture,R.onFocusCapture),onBlurCapture:Ra(t.onBlurCapture,R.onBlurCapture),onPointerDownCapture:Ra(t.onPointerDownCapture,P.onPointerDownCapture)})},"DismissableLayer")),m0s=j.forwardRef(g0(function(t,n){const r=j.useContext(ret),a=j.useRef(null),i=Vo(n,a);return j.useEffect(()=>{const l=a.current;if(l)return r.branches.add(l),()=>{r.branches.delete(l)}},[r.branches]),e.jsx(Ei.div,{...t,ref:i})},"DismissableLayerBranch"));function dRt(){const s=j.useContext(ret),[t,n]=j.useState(null);return j.useEffect(()=>{if(t)return s.dismissableSurfaces.add(t),()=>{s.dismissableSurfaces.delete(t)}},[t,s.dismissableSurfaces]),n}g0(dRt,"useDismissableLayerSurface");var f0s=g0(()=>!0,"IS_TRUE");function uRt(s,t){const{ownerDocument:n=globalThis==null?void 0:globalThis.document,deferPointerDownOutside:r=!1,isDeferredPointerDownOutsideRef:a,dismissableSurfaces:i,shouldHandlePointerDownOutside:l=f0s}=t,o=Yp(s),c=j.useRef(!1),d=j.useRef(!1),u=j.useRef(new Map),h=j.useRef(()=>{});return j.useEffect(()=>{function m(){d.current=!1,a.current=!1,u.current.clear()}g0(m,"resetOutsideInteraction");function f(){return Array.from(u.current.values()).some(Boolean)}g0(f,"isOutsideInteractionIntercepted");function g(w){if(!d.current)return;const S=w.target;S instanceof Node&&[...i].some(E=>E.contains(S))||u.current.set(w.type,!0),w.type==="click"&&window.setTimeout(()=>{d.current&&h.current()},0)}g0(g,"handleInteractionCapture");function x(w){d.current&&u.current.set(w.type,!1)}g0(x,"handleInteractionBubble");const y=g0(w=>{if(w.target&&!c.current){let S=function(){n.removeEventListener("click",h.current);const E=f();m(),E||aet(u0s,o,C,{discrete:!0})};if(g0(S,"handleAndDispatchPointerDownOutsideEvent"),!l(w.target)){n.removeEventListener("click",h.current),m(),c.current=!1;return}const C={originalEvent:w};d.current=!0,a.current=r&&w.button===0,u.current.clear(),!r||w.button!==0?S():(n.removeEventListener("click",h.current),h.current=S,n.addEventListener("click",h.current,{once:!0}))}else n.removeEventListener("click",h.current),m();c.current=!1},"handlePointerDown"),v=["pointerup","mousedown","mouseup","touchstart","touchend","click"];for(const w of v)n.addEventListener(w,g,!0),n.addEventListener(w,x);const b=window.setTimeout(()=>{n.addEventListener("pointerdown",y)},0);return()=>{window.clearTimeout(b),n.removeEventListener("pointerdown",y),n.removeEventListener("click",h.current);for(const w of v)n.removeEventListener(w,g,!0),n.removeEventListener(w,x)}},[n,o,r,a,i,l]),{onPointerDownCapture:g0(()=>c.current=!0,"onPointerDownCapture")}}g0(uRt,"usePointerDownOutside");function hRt(s,t=globalThis==null?void 0:globalThis.document){const n=Yp(s),r=j.useRef(!1);return j.useEffect(()=>{const a=g0(i=>{i.target&&!r.current&&aet(h0s,n,{originalEvent:i},{discrete:!1})},"handleFocus");return t.addEventListener("focusin",a),()=>t.removeEventListener("focusin",a)},[t,n]),{onFocusCapture:g0(()=>r.current=!0,"onFocusCapture"),onBlurCapture:g0(()=>r.current=!1,"onBlurCapture")}}g0(hRt,"useFocusOutside");function DVe(){const s=new CustomEvent(RVe);document.dispatchEvent(s)}g0(DVe,"dispatchUpdate");function aet(s,t,n,{discrete:r}){const a=n.originalEvent.target,i=new CustomEvent(s,{bubbles:!1,cancelable:!0,detail:n});t&&a.addEventListener(s,t,{once:!0}),r?UIe(a,i):a.dispatchEvent(i)}g0(aet,"handleAndDispatchCustomEvent");var p0s=RB,g0s=m0s,Ef=globalThis!=null&&globalThis.document?j.useLayoutEffect:()=>{},x0s=Object.defineProperty,y0s=(s,t)=>x0s(s,"name",{value:t,configurable:!0}),_ae=j.forwardRef(y0s(function(t,n){var c;const{container:r,...a}=t,[i,l]=j.useState(!1);Ef(()=>l(!0),[]);const o=r||i&&((c=globalThis==null?void 0:globalThis.document)==null?void 0:c.body);return o?wv.createPortal(e.jsx(Ei.div,{...a,ref:n}),o):null},"Portal")),v0s=Object.defineProperty,dT=(s,t)=>v0s(s,"name",{value:t,configurable:!0});function mRt(s,t){return j.useReducer((n,r)=>t[n][r]??n,s)}dT(mRt,"useStateMachine");var xy=dT(s=>{const{present:t,children:n}=s,r=fRt(t),a=typeof n=="function"?n({present:r.isPresent}):j.Children.only(n),i=pRt(r.ref,gRt(a));return typeof n=="function"||r.isPresent?j.cloneElement(a,{ref:i}):null},"Presence");function fRt(s){const[t,n]=j.useState(),r=j.useRef(null),a=j.useRef(s),i=j.useRef("none"),l=j.useRef(void 0),o=s?"mounted":"unmounted",[c,d]=mRt(o,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return j.useEffect(()=>{c==="mounted"?(i.current=l.current??pU(r.current),l.current=void 0):i.current="none"},[c]),Ef(()=>{const u=r.current,h=a.current;if(h!==s){const f=i.current,g=pU(u);s?(l.current=g,d("MOUNT")):g==="none"||(u==null?void 0:u.display)==="none"?d("UNMOUNT"):d(h&&f!==g?"ANIMATION_OUT":"UNMOUNT"),a.current=s}},[s,d]),Ef(()=>{if(t){let u;const h=t.ownerDocument.defaultView??window,m=dT(g=>{const y=pU(r.current).includes(CSS.escape(g.animationName));if(g.target===t&&y&&(d("ANIMATION_END"),!a.current)){const v=t.style.animationFillMode;t.style.animationFillMode="forwards",u=h.setTimeout(()=>{t.style.animationFillMode==="forwards"&&(t.style.animationFillMode=v)})}},"handleAnimationEnd"),f=dT(g=>{g.target===t&&(i.current=pU(r.current))},"handleAnimationStart");return t.addEventListener("animationstart",f),t.addEventListener("animationcancel",m),t.addEventListener("animationend",m),()=>{h.clearTimeout(u),t.removeEventListener("animationstart",f),t.removeEventListener("animationcancel",m),t.removeEventListener("animationend",m)}}else d("ANIMATION_END")},[t,d]),{isPresent:["mounted","unmountSuspended"].includes(c),ref:j.useCallback(u=>{if(u){const h=getComputedStyle(u);r.current=h,l.current=pU(h)}else r.current=null;n(u)},[])}}dT(fRt,"usePresence");function FVe(s,t){if(typeof s=="function")return s(t);s!=null&&(s.current=t)}dT(FVe,"setRef");function pRt(...s){const t=j.useRef(s);return t.current=s,j.useCallback(n=>{const r=t.current;let a=!1;const i=r.map(l=>{const o=FVe(l,n);return!a&&typeof o=="function"&&(a=!0),o});if(a)return()=>{for(let l=0;lb0s(s,"name",{value:t,configurable:!0}),pgt=MB[" useEffectEvent ".trim().toString()],ggt=MB[" useInsertionEffect ".trim().toString()];function xRt(s){if(typeof pgt=="function")return pgt(s);const t=j.useRef(()=>{throw new Error("Cannot call an event handler while rendering.")});return typeof ggt=="function"?ggt(()=>{t.current=s}):Ef(()=>{t.current=s}),j.useMemo(()=>(...n)=>{var r;return(r=t.current)==null?void 0:r.call(t,...n)},[])}_0s(xRt,"useEffectEvent");var w0s=Object.defineProperty,wae=(s,t)=>w0s(s,"name",{value:t,configurable:!0}),j0s=MB[" useInsertionEffect ".trim().toString()]||Ef;function fy({prop:s,defaultProp:t,onChange:n=wae(()=>{},"onChange"),caller:r}){const[a,i,l]=yRt({defaultProp:t,onChange:n}),o=s!==void 0,c=o?s:a,d=j.useCallback(u=>{var h;if(o){const m=vRt(u)?u(s):u;m!==s&&((h=l.current)==null||h.call(l,m))}else i(u)},[o,s,i,l]);return[c,d]}wae(fy,"useControllableState");function yRt({defaultProp:s,onChange:t}){const[n,r]=j.useState(s),a=j.useRef(n),i=j.useRef(t);return j0s(()=>{i.current=t},[t]),j.useEffect(()=>{var l;a.current!==n&&((l=i.current)==null||l.call(i,n),a.current=n)},[n,a]),[n,r,i]}wae(yRt,"useUncontrolledState");function vRt(s){return typeof s=="function"}wae(vRt,"isFunction");var xgt=Symbol("RADIX:SYNC_STATE");function N0s(s,t,n,r){const{prop:a,defaultProp:i,onChange:l,caller:o}=t,c=a!==void 0,d=xRt(l),u=[{...n,state:i}];r&&u.push(r);const[h,m]=j.useReducer((y,v)=>{if(v.type===xgt)return{...y,state:v.state};const b=s(y,v);return c&&!Object.is(b.state,y.state)&&d(b.state),b},...u),f=h.state,g=j.useRef(f);j.useEffect(()=>{g.current!==f&&(g.current=f,c||d(f))},[f,g,c]);const x=j.useMemo(()=>a!==void 0?{...h,state:a}:h,[h,a]);return j.useEffect(()=>{c&&!Object.is(a,h.state)&&m({type:xgt,state:a})},[a,h.state,c]),[x,m]}wae(N0s,"useControllableStateReducer");var k0s=Object.defineProperty,S0s=(s,t)=>k0s(s,"name",{value:t,configurable:!0}),bRt=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"}),iet=j.forwardRef(S0s(function(t,n){return e.jsx(Ei.span,{...t,ref:n,style:{...bRt,...t.style}})},"VisuallyHidden")),C0s=iet,A0s=Object.defineProperty,_f=(s,t)=>A0s(s,"name",{value:t,configurable:!0}),_Rt="ToastProvider",[oet,wRt,E0s]=LB("Toast"),[jRt,Tkr]=tp("Toast",[E0s]),[T0s,qIe]=jRt(_Rt),M0s=_f(s=>{const{__scopeToast:t,label:n="Notification",duration:r=5e3,swipeDirection:a="right",swipeThreshold:i=50,announcerContainer:l,children:o}=s,[c,d]=j.useState(null),[u,h]=j.useState(0),m=j.useRef(!1);return n.trim()||console.error(`Invalid prop \`label\` supplied to \`${_Rt}\`. Expected non-empty \`string\`.`),e.jsx(oet.Provider,{scope:t,children:e.jsx(T0s,{scope:t,label:n,duration:r,swipeDirection:a,swipeThreshold:i,toastCount:u,viewport:c,onViewportChange:d,onToastAdd:j.useCallback(()=>h(f=>f+1),[]),onToastRemove:j.useCallback(()=>h(f=>f-1),[]),isClosePausedRef:m,announcerContainer:l,children:o})})},"ToastProvider"),P0s="ToastViewport",I0s=["F8"],OVe="toast.viewportPause",zVe="toast.viewportResume",L0s=j.forwardRef(_f(function(t,n){const{__scopeToast:r,hotkey:a=I0s,label:i="Notifications ({hotkey})",...l}=t,o=qIe(P0s,r),c=wRt(r),d=j.useRef(null),u=j.useRef(null),h=j.useRef(null),m=j.useRef(null),f=Vo(n,m,o.onViewportChange),g=a.join("+").replace(/Key/g,"").replace(/Digit/g,""),x=o.toastCount>0;j.useEffect(()=>{const v=_f(b=>{var S;a.length!==0&&a.every(C=>b[C]||b.code===C)&&((S=m.current)==null||S.focus())},"handleKeyDown");return document.addEventListener("keydown",v),()=>document.removeEventListener("keydown",v)},[a]),j.useEffect(()=>{const v=d.current,b=m.current;if(x&&v&&b){const w=_f(()=>{if(!o.isClosePausedRef.current){const I=new CustomEvent(OVe);b.dispatchEvent(I),o.isClosePausedRef.current=!0}},"handlePause"),S=_f(()=>{if(o.isClosePausedRef.current){const I=new CustomEvent(zVe);b.dispatchEvent(I),o.isClosePausedRef.current=!1}},"handleResume"),C=_f(I=>{!v.contains(I.relatedTarget)&&S()},"handleFocusOutResume"),E=_f(()=>{v.contains(document.activeElement)||S()},"handlePointerLeaveResume");return v.addEventListener("focusin",w),v.addEventListener("focusout",C),v.addEventListener("pointermove",w),v.addEventListener("pointerleave",E),window.addEventListener("blur",w),window.addEventListener("focus",S),()=>{v.removeEventListener("focusin",w),v.removeEventListener("focusout",C),v.removeEventListener("pointermove",w),v.removeEventListener("pointerleave",E),window.removeEventListener("blur",w),window.removeEventListener("focus",S)}}},[x,o.isClosePausedRef]);const y=j.useCallback(({tabbingDirection:v})=>{const w=c().map(S=>{const C=S.ref.current,E=[C,...ARt(C)];return v==="forwards"?E:E.reverse()});return(v==="forwards"?w.reverse():w).flat()},[c]);return j.useEffect(()=>{const v=m.current;if(v){const b=_f(w=>{var E,I,P;const S=w.altKey||w.ctrlKey||w.metaKey;if(w.key==="Tab"&&!S){const R=document.activeElement,D=w.shiftKey;if(w.target===v&&D){(E=u.current)==null||E.focus();return}const W=y({tabbingDirection:D?"backwards":"forwards"}),V=W.findIndex(G=>G===R);bme(W.slice(V+1))?w.preventDefault():D?(I=u.current)==null||I.focus():(P=h.current)==null||P.focus()}},"handleKeyDown");return v.addEventListener("keydown",b),()=>v.removeEventListener("keydown",b)}},[c,y]),e.jsxs(g0s,{ref:d,role:"region","aria-label":i.replace("{hotkey}",g),tabIndex:-1,style:{pointerEvents:x?void 0:"none"},children:[x&&e.jsx(ygt,{ref:u,onFocusFromOutsideViewport:()=>{const v=y({tabbingDirection:"forwards"});bme(v)}}),e.jsx(oet.Slot,{scope:r,children:e.jsx(Ei.ol,{tabIndex:-1,...l,ref:f})}),x&&e.jsx(ygt,{ref:h,onFocusFromOutsideViewport:()=>{const v=y({tabbingDirection:"backwards"});bme(v)}})]})},"ToastViewport")),R0s="ToastFocusProxy",ygt=j.forwardRef(_f(function(t,n){const{__scopeToast:r,onFocusFromOutsideViewport:a,...i}=t,l=qIe(R0s,r);return e.jsx(iet,{tabIndex:0,...i,ref:n,style:{position:"fixed"},onFocus:o=>{var u;const c=o.relatedTarget;!((u=l.viewport)!=null&&u.contains(c))&&a()}})},"ToastFocusProxy")),VIe="Toast",D0s="toast.swipeStart",F0s="toast.swipeMove",O0s="toast.swipeCancel",z0s="toast.swipeEnd",B0s=j.forwardRef(_f(function(t,n){const{forceMount:r,open:a,defaultOpen:i,onOpenChange:l,...o}=t,[c,d]=fy({prop:a,defaultProp:i??!0,onChange:l,caller:VIe});return e.jsx(xy,{present:r||c,children:e.jsx(q0s,{open:c,...o,ref:n,onClose:()=>d(!1),onPause:Yp(t.onPause),onResume:Yp(t.onResume),onSwipeStart:Ra(t.onSwipeStart,u=>{u.currentTarget.setAttribute("data-swipe","start")}),onSwipeMove:Ra(t.onSwipeMove,u=>{const{x:h,y:m}=u.detail.delta;u.currentTarget.setAttribute("data-swipe","move"),u.currentTarget.style.setProperty("--radix-toast-swipe-move-x",`${h}px`),u.currentTarget.style.setProperty("--radix-toast-swipe-move-y",`${m}px`)}),onSwipeCancel:Ra(t.onSwipeCancel,u=>{u.currentTarget.setAttribute("data-swipe","cancel"),u.currentTarget.style.removeProperty("--radix-toast-swipe-move-x"),u.currentTarget.style.removeProperty("--radix-toast-swipe-move-y"),u.currentTarget.style.removeProperty("--radix-toast-swipe-end-x"),u.currentTarget.style.removeProperty("--radix-toast-swipe-end-y")}),onSwipeEnd:Ra(t.onSwipeEnd,u=>{const{x:h,y:m}=u.detail.delta;u.currentTarget.setAttribute("data-swipe","end"),u.currentTarget.style.removeProperty("--radix-toast-swipe-move-x"),u.currentTarget.style.removeProperty("--radix-toast-swipe-move-y"),u.currentTarget.style.setProperty("--radix-toast-swipe-end-x",`${h}px`),u.currentTarget.style.setProperty("--radix-toast-swipe-end-y",`${m}px`),d(!1)})})})},"Toast")),[$0s,U0s]=jRt(VIe,{onClose(){}}),q0s=j.forwardRef(_f(function(t,n){const{__scopeToast:r,type:a="foreground",duration:i,open:l,onClose:o,onEscapeKeyDown:c,onPause:d,onResume:u,onSwipeStart:h,onSwipeMove:m,onSwipeCancel:f,onSwipeEnd:g,...x}=t,y=qIe(VIe,r),v=wRt(r),[b,w]=j.useState(null),S=Vo(n,w),C=j.useRef(null),E=j.useRef(null),I=i||y.duration,P=j.useRef(0),R=j.useRef(I),D=j.useRef(0),{onToastAdd:O,onToastRemove:U}=y,W=Yp(()=>{var X;(b==null?void 0:b.contains(document.activeElement))&&((X=y.viewport)==null||X.focus()),o()}),V=j.useCallback(Y=>{!Y||Y===1/0||(window.clearTimeout(D.current),P.current=new Date().getTime(),D.current=window.setTimeout(W,Y))},[W]);j.useEffect(()=>{const Y=y.viewport;if(Y){const X=_f(()=>{V(R.current),u==null||u()},"handleResume"),ae=_f(()=>{const ie=new Date().getTime()-P.current;R.current=R.current-ie,window.clearTimeout(D.current),d==null||d()},"handlePause");return Y.addEventListener(OVe,ae),Y.addEventListener(zVe,X),()=>{Y.removeEventListener(OVe,ae),Y.removeEventListener(zVe,X)}}},[y.viewport,I,d,u,V]),j.useEffect(()=>{l&&!y.isClosePausedRef.current&&V(I)},[l,I,y.isClosePausedRef,V]),j.useEffect(()=>()=>{window.clearTimeout(D.current)},[]),j.useEffect(()=>(O(),()=>U()),[O,U]);const G=j.useMemo(()=>b?cet(b):null,[b]);return y.viewport?e.jsxs(e.Fragment,{children:[G&&e.jsx(V0s,{__scopeToast:r,role:"status","aria-live":a==="foreground"?"assertive":"polite",children:G}),e.jsx($0s,{scope:r,onClose:W,children:wv.createPortal(e.jsx(oet.ItemSlot,{scope:r,children:e.jsx(p0s,{asChild:!0,onEscapeKeyDown:Ra(c,Y=>{v().some(ae=>{var ie;return(ie=ae.ref.current)==null?void 0:ie.contains(Y.target)})||W()}),children:e.jsx(Ei.li,{tabIndex:0,"data-state":l?"open":"closed","data-swipe-direction":y.swipeDirection,...x,ref:S,style:{userSelect:"none",touchAction:"none",...t.style},onKeyDown:Ra(t.onKeyDown,Y=>{Y.key==="Escape"&&(c==null||c(Y.nativeEvent),Y.nativeEvent.defaultPrevented||W())}),onPointerDown:Ra(t.onPointerDown,Y=>{Y.button===0&&(C.current={x:Y.clientX,y:Y.clientY})}),onPointerMove:Ra(t.onPointerMove,Y=>{if(!C.current)return;const X=Y.clientX-C.current.x,ae=Y.clientY-C.current.y,ie=!!E.current,ne=["left","right"].includes(y.swipeDirection),te=["left","up"].includes(y.swipeDirection)?Math.min:Math.max,J=ne?te(0,X):0,ce=ne?0:te(0,ae),_e=Y.pointerType==="touch"?10:2,he={x:J,y:ce},ue={originalEvent:Y,delta:he};ie?(E.current=he,rQ(F0s,m,ue,{discrete:!1})):vgt(he,y.swipeDirection,_e)?(E.current=he,rQ(D0s,h,ue,{discrete:!1}),Y.target.setPointerCapture(Y.pointerId)):(Math.abs(X)>_e||Math.abs(ae)>_e)&&(C.current=null)}),onPointerUp:Ra(t.onPointerUp,Y=>{const X=E.current,ae=Y.target;if(ae.hasPointerCapture(Y.pointerId)&&ae.releasePointerCapture(Y.pointerId),E.current=null,C.current=null,X){const ie=Y.currentTarget,ne={originalEvent:Y,delta:X};vgt(X,y.swipeDirection,y.swipeThreshold)?rQ(z0s,g,ne,{discrete:!0}):rQ(O0s,f,ne,{discrete:!0}),ie.addEventListener("click",te=>te.preventDefault(),{once:!0})}})})})}),y.viewport)})]}):null},"ToastImpl")),V0s=_f(s=>{const{__scopeToast:t,children:n,...r}=s,a=qIe(VIe,t),[i,l]=j.useState(!1),[o,c]=j.useState(!1);return SRt(()=>l(!0)),j.useEffect(()=>{const d=window.setTimeout(()=>c(!0),1e3);return()=>window.clearTimeout(d)},[]),o?null:e.jsx(_ae,{asChild:!0,container:a.announcerContainer||void 0,children:e.jsx(iet,{...r,children:i&&e.jsxs(e.Fragment,{children:[a.label," ",n]})})})},"ToastAnnounce"),H0s=j.forwardRef(_f(function(t,n){const{__scopeToast:r,...a}=t;return e.jsx(Ei.div,{...a,ref:n})},"ToastTitle")),G0s=j.forwardRef(_f(function(t,n){const{__scopeToast:r,...a}=t;return e.jsx(Ei.div,{...a,ref:n})},"ToastDescription")),W0s="ToastAction",K0s=j.forwardRef(_f(function(t,n){const{altText:r,...a}=t;return r.trim()?e.jsx(kRt,{altText:r,asChild:!0,children:e.jsx(NRt,{...a,ref:n})}):(console.error(`Invalid prop \`altText\` supplied to \`${W0s}\`. Expected non-empty \`string\`.`),null)},"ToastAction")),Y0s="ToastClose",NRt=j.forwardRef(_f(function(t,n){const{__scopeToast:r,...a}=t,i=U0s(Y0s,r);return e.jsx(kRt,{asChild:!0,children:e.jsx(Ei.button,{type:"button",...a,ref:n,onClick:Ra(t.onClick,i.onClose)})})},"ToastClose")),kRt=j.forwardRef(_f(function(t,n){const{__scopeToast:r,altText:a,...i}=t;return e.jsx(Ei.div,{"data-radix-toast-announce-exclude":"","data-radix-toast-announce-alt":a||void 0,...i,ref:n})},"ToastAnnounceExclude"));function cet(s){const t=[];return Array.from(s.childNodes).forEach(r=>{if(r.nodeType===r.TEXT_NODE&&r.textContent&&t.push(r.textContent),CRt(r)){const a=r.ariaHidden||r.hidden||r.style.display==="none",i=r.dataset.radixToastAnnounceExclude==="";if(!a)if(i){const l=r.dataset.radixToastAnnounceAlt;l&&t.push(l)}else t.push(...cet(r))}}),t}_f(cet,"getAnnounceTextContent");function rQ(s,t,n,{discrete:r}){const a=n.originalEvent.currentTarget,i=new CustomEvent(s,{bubbles:!0,cancelable:!0,detail:n});t&&a.addEventListener(s,t,{once:!0}),r?UIe(a,i):a.dispatchEvent(i)}_f(rQ,"handleAndDispatchCustomEvent");var vgt=_f((s,t,n=0)=>{const r=Math.abs(s.x),a=Math.abs(s.y),i=r>a;return t==="left"||t==="right"?i&&r>n:!i&&a>n},"isDeltaInDirection");function SRt(s=()=>{}){const t=Yp(s);Ef(()=>{let n=0,r=0;return n=window.requestAnimationFrame(()=>r=window.requestAnimationFrame(t)),()=>{window.cancelAnimationFrame(n),window.cancelAnimationFrame(r)}},[t])}_f(SRt,"useNextFrame");function CRt(s){return s.nodeType===s.ELEMENT_NODE}_f(CRt,"isHTMLElement");function ARt(s){const t=[],n=document.createTreeWalker(s,NodeFilter.SHOW_ELEMENT,{acceptNode:_f(r=>{const a=r.tagName==="INPUT"&&r.type==="hidden";return r.disabled||r.hidden||a?NodeFilter.FILTER_SKIP:r.tabIndex>=0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP},"acceptNode")});for(;n.nextNode();)t.push(n.currentNode);return t}_f(ARt,"getTabbableCandidates");function bme(s){const t=document.activeElement;return s.some(n=>n===t?!0:(n.focus(),document.activeElement!==t))}_f(bme,"focusFirst");var Z0s=M0s,ERt=L0s,TRt=B0s,MRt=H0s,PRt=G0s,IRt=K0s,LRt=NRt;function RRt(s){var t,n,r="";if(typeof s=="string"||typeof s=="number")r+=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,_gt=rd,DB=(s,t)=>n=>{var r;if((t==null?void 0:t.variants)==null)return _gt(s,n==null?void 0:n.class,n==null?void 0:n.className);const{variants:a,defaultVariants:i}=t,l=Object.keys(a).map(d=>{const u=n==null?void 0:n[d],h=i==null?void 0:i[d];if(u===null)return null;const m=bgt(u)||bgt(h);return a[d][m]}),o=n&&Object.entries(n).reduce((d,u)=>{let[h,m]=u;return m===void 0||(d[h]=m),d},{}),c=t==null||(r=t.compoundVariants)===null||r===void 0?void 0:r.reduce((d,u)=>{let{class:h,className:m,...f}=u;return Object.entries(f).every(g=>{let[x,y]=g;return Array.isArray(y)?y.includes({...i,...o}[x]):{...i,...o}[x]===y})?[...d,h,m]:d},[]);return _gt(s,l,c,n==null?void 0:n.class,n==null?void 0:n.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 X0s=s=>s.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),DRt=(...s)=>s.filter((t,n,r)=>!!t&&t.trim()!==""&&r.indexOf(t)===n).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 Q0s={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 FRt=j.forwardRef(({color:s="currentColor",size:t=24,strokeWidth:n=2,absoluteStrokeWidth:r,className:a="",children:i,iconNode:l,...o},c)=>j.createElement("svg",{ref:c,...Q0s,width:t,height:t,stroke:s,strokeWidth:r?Number(n)*24/Number(t):n,className:DRt("lucide",a),...o},[...l.map(([d,u])=>j.createElement(d,u)),...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 ge=(s,t)=>{const n=j.forwardRef(({className:r,...a},i)=>j.createElement(FRt,{ref:i,iconNode:t,className:DRt(`lucide-${X0s(s)}`,r),...a}));return n.displayName=`${s}`,n};/** * @license lucide-react v0.462.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=ge("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 wme=ge("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 jme=ge("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 Nme=ge("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 af=ge("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 kme=ge("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 Sme=ge("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 DR=ge("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 FR=ge("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 Cme=ge("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 OR=ge("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 Ame=ge("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 Eme=ge("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 Tme=ge("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 Mme=ge("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 Pme=ge("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 zI=ge("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 Ime=ge("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 Lme=ge("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 Rme=ge("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 Dme=ge("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 Fme=ge("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 Ome=ge("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 zme=ge("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 Bme=ge("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 $me=ge("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 Ume=ge("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 qme=ge("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 BI=ge("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 $I=ge("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 Vme=ge("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 Hme=ge("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 Gme=ge("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 Wme=ge("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 Kme=ge("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 Yme=ge("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 Zme=ge("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 Xme=ge("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 Qme=ge("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 Jme=ge("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 efe=ge("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 tfe=ge("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 sfe=ge("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 nfe=ge("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 rfe=ge("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 afe=ge("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 ife=ge("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 ofe=ge("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 lfe=ge("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 cfe=ge("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 dfe=ge("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 ufe=ge("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 hfe=ge("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 UI=ge("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 mfe=ge("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 Sv=ge("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 ffe=ge("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 pfe=ge("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 gfe=ge("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 xfe=ge("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 yfe=ge("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 vfe=ge("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 bfe=ge("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 _fe=ge("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 wfe=ge("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 jfe=ge("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 Nfe=ge("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 zR=ge("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 kfe=ge("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 Sfe=ge("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 Cfe=ge("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 pJ=ge("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 Afe=ge("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 Efe=ge("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 Tfe=ge("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 BR=ge("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 $R=ge("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 Dg=ge("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 Mfe=ge("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 gJ=ge("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 Pfe=ge("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 qa=ge("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 Ife=ge("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 E4=ge("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 Lfe=ge("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 ei=ge("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 Rfe=ge("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 Dfe=ge("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 UR=ge("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 By=ge("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 Ffe=ge("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 Ofe=ge("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 zfe=ge("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 qR=ge("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 Oz=ge("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 Bfe=ge("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 $fe=ge("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 VR=ge("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 Zf=ge("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 Ufe=ge("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 qfe=ge("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 Vfe=ge("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 Hfe=ge("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 Gfe=ge("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 Wfe=ge("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 Rm=ge("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 Kfe=ge("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 HR=ge("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 Yfe=ge("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 Zfe=ge("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 Xfe=ge("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 Qfe=ge("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 RA=ge("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 Jfe=ge("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 epe=ge("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 tpe=ge("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 spe=ge("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 npe=ge("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 rpe=ge("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 ape=ge("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 ipe=ge("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 ope=ge("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 lpe=ge("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 cpe=ge("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 dpe=ge("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 upe=ge("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 hpe=ge("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 mpe=ge("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 zz=ge("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 fpe=ge("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 ppe=ge("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 gpe=ge("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 xpe=ge("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 ype=ge("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 T0=ge("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 vpe=ge("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 bpe=ge("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 _pe=ge("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 wpe=ge("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 jpe=ge("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 Npe=ge("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 xJ=ge("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 kpe=ge("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 Spe=ge("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 T4=ge("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 Cpe=ge("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 l2=ge("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 Ape=ge("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 Epe=ge("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 Tpe=ge("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 Mpe=ge("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 Ppe=ge("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 Ipe=ge("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 XS=ge("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 Lpe=ge("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 QS=ge("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 qy=ge("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 GR=ge("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 WR=ge("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 Rpe=ge("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 Dpe=ge("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 Fpe=ge("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 Ope=ge("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 zpe=ge("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 Bpe=ge("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 $pe=ge("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 Upe=ge("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 qpe=ge("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 Vpe=ge("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 Hpe=ge("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 Gpe=ge("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 Wpe=ge("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 Kpe=ge("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 Ype=ge("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 Zpe=ge("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 AE=ge("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 Xpe=ge("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 Qpe=ge("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 Jpe=ge("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 ege=ge("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 tge=ge("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 sge=ge("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 nge=ge("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 KR=ge("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 rge=ge("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 age=ge("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 ige=ge("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 oge=ge("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 lge=ge("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 cge=ge("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 dge=ge("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 uge=ge("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 hge=ge("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 mge=ge("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 Xf=ge("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 fge=ge("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 pge=ge("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 gge=ge("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 xge=ge("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 yge=ge("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 vge=ge("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 bge=ge("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 _ge=ge("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 wge=ge("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 jge=ge("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 qI=ge("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 Nge=ge("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 M0=ge("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 kge=ge("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 Sge=ge("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 Cge=ge("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 M4=ge("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 yJ=ge("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 Age=ge("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 aP=ge("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 Ege=ge("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 Tge=ge("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 Mge=ge("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 vJ=ge("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 Pge=ge("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 Ige=ge("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 Lge=ge("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 Rge=ge("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 Sx=ge("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 Dge=ge("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 Fge=ge("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 Oge=ge("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 zge=ge("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 Bge=ge("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 ji=ge("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 VI=ge("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 $ge=ge("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 Uge=ge("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 qge=ge("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 Vge=ge("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 Hge=ge("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 Fg=ge("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 c2=ge("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 Gge=ge("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 Wge=ge("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 Kge=ge("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 Yge=ge("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 bb=ge("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 Au=ge("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 Zge=ge("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 Kc=ge("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 Xge=ge("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 JS=ge("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 Qge=ge("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 Jge=ge("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 Tq=ge("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 exe=ge("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 jv=ge("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 txe=ge("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 sxe=ge("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 nxe=ge("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 rxe=ge("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 bJ=ge("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 Ta=ge("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 axe=ge("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 Cx=ge("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 ixe=ge("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 oxe=ge("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 lxe=ge("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 cxe=ge("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 dxe=ge("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 YR=ge("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 uxe=ge("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 hxe=ge("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 mxe=ge("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 fxe=ge("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 pxe=ge("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 gxe=ge("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 xxe=ge("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 yxe=ge("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 vxe=ge("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 bxe=ge("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 _xe=ge("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 wxe=ge("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 jxe=ge("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 ZR=ge("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 XR=ge("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 Nxe=ge("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 kxe=ge("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 Sxe=ge("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 QR=ge("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 JR=ge("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 eD=ge("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 Cxe=ge("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 tD=ge("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 Axe=ge("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 Wl=ge("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 Exe=ge("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 sD=ge("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 Txe=ge("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 Mxe=ge("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 nD=ge("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 rD=ge("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 Pxe=ge("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 aD=ge("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 iD=ge("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 oD=ge("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 Ixe=ge("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 Bz=ge("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 la=ge("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 Lxe=ge("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 Rxe=ge("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 Tl=ge("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 Dxe=ge("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 Fxe=ge("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 Cd=ge("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 Di=ge("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 v1=ge("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 Oxe=ge("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 zxe=ge("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 Bxe=ge("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 $xe=ge("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 Uxe=ge("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 qxe=ge("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 Vxe=ge("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 Pw=ge("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 Hxe=ge("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 $z=ge("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 Gxe=ge("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 Wxe=ge("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 Kxe=ge("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 ll=ge("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 lD=ge("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 cD=ge("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 dD=ge("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 uD=ge("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 hD=ge("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 mD=ge("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 fD=ge("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 pD=ge("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 Nc=ge("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 qr=ge("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 gD=ge("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 xD=ge("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 yD=ge("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 vD=ge("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 Yxe=ge("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 bD=ge("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 Zxe=ge("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 Xxe=ge("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 Qxe=ge("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 Jxe=ge("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 eye=ge("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 tye=ge("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 sye=ge("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 _D=ge("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 s4=ge("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 wD=ge("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 nye=ge("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 jD=ge("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 ND=ge("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 kD=ge("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 SD=ge("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 tf=ge("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 CD=ge("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 AD=ge("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 ED=ge("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 rye=ge("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 TD=ge("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 MD=ge("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 PD=ge("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 ku=ge("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 Og=ge("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 aye=ge("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 iye=ge("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 Mq=ge("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 JN=ge("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 oye=ge("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 zg=ge("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 lye=ge("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 cye=ge("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 ID=ge("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 LD=ge("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 dye=ge("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 uye=ge("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 hye=ge("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 mye=ge("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 fye=ge("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 pye=ge("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 gye=ge("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 xye=ge("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 yye=ge("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 Pq=ge("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 vye=ge("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 bye=ge("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 _ye=ge("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 wye=ge("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 jye=ge("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 Nye=ge("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 kye=ge("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 Sye=ge("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 Cye=ge("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 da=ge("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 Aye=ge("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 Eye=ge("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 RD=ge("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 Tye=ge("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 Mye=ge("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 Pye=ge("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 Iye=ge("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 Lye=ge("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 Rye=ge("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 Dye=ge("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 Fye=ge("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 Oye=ge("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 zye=ge("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 Bye=ge("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 $ye=ge("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 iP=ge("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 Uye=ge("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 qye=ge("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 yE=ge("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 Vye=ge("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 n4=ge("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 EE=ge("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 Hye=ge("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 Gye=ge("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 P4=ge("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 Wye=ge("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 _J=ge("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 DD=ge("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 oP=ge("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 Kye=ge("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 Yye=ge("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 Zye=ge("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 Uz=ge("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 Xye=ge("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 Qye=ge("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 Jye=ge("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 e0e=ge("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 t0e=ge("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 FD=ge("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 HI=ge("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 s0e=ge("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 n0e=ge("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 r0e=ge("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 a0e=ge("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 i0e=ge("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 o0e=ge("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 l0e=ge("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 c0e=ge("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 d0e=ge("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 Ha=ge("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 u0e=ge("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 h0e=ge("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 m0e=ge("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 wJ=ge("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 f0e=ge("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 p0e=ge("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 g0e=ge("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 x0e=ge("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 y0e=ge("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 v0e=ge("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 b0e=ge("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 _0e=ge("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 Cv=ge("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 w0e=ge("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 j0e=ge("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 N0e=ge("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 k0e=ge("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 Bg=ge("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 S0e=ge("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 C0e=ge("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 A0e=ge("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 E0e=ge("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 T0e=ge("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 M0e=ge("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 P0e=ge("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 Iq=ge("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 I0e=ge("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 L0e=ge("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 R0e=ge("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 D0e=ge("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 OD=ge("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 F0e=ge("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 O0e=ge("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 z0e=ge("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 B0e=ge("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 $0e=ge("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 U0e=ge("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 q0e=ge("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 V0e=ge("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 H0e=ge("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 G0e=ge("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 W0e=ge("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 K0e=ge("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 Y0e=ge("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 Z0e=ge("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 X0e=ge("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 Q0e=ge("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 J0e=ge("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 eve=ge("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 tve=ge("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 ru=ge("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 sve=ge("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 nve=ge("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 d2=ge("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 rve=ge("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 di=ge("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 ave=ge("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 ive=ge("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 ove=ge("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 lve=ge("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 cve=ge("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 b1=ge("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 dve=ge("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 uve=ge("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 hve=ge("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 mve=ge("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 fve=ge("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 pve=ge("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 IN=ge("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 gve=ge("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 xve=ge("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 yve=ge("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 Lq=ge("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 ty=ge("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 h_=ge("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 vve=ge("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 bve=ge("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 _ve=ge("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 Rq=ge("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 wve=ge("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 jve=ge("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 Nve=ge("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 kr=ge("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 kve=ge("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 $g=ge("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 Ca=ge("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 Qp=ge("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 Sve=ge("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 Cve=ge("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 Ave=ge("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 Eve=ge("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 Tve=ge("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 Mve=ge("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 Pve=ge("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 Ive=ge("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 Lve=ge("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 Rve=ge("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 zD=ge("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 Dve=ge("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 Fve=ge("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 Ove=ge("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 BD=ge("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 $D=ge("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 UD=ge("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 qD=ge("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 qz=ge("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 jJ=ge("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 zve=ge("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 Bve=ge("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 $ve=ge("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 VD=ge("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 Uve=ge("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 qve=ge("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 u2=ge("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 Vve=ge("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 GI=ge("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 Hve=ge("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 Gve=ge("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 Wve=ge("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 Kve=ge("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 Yve=ge("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 Zve=ge("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 Xve=ge("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 Qve=ge("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 Jve=ge("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 ebe=ge("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 tbe=ge("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 m_=ge("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 HD=ge("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 Dq=ge("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 sbe=ge("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 nbe=ge("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 rbe=ge("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 abe=ge("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 NJ=ge("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 ibe=ge("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 ek=ge("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 kJ=ge("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 obe=ge("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 lbe=ge("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 Jr=ge("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 cbe=ge("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 dbe=ge("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 SJ=ge("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 ube=ge("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 hbe=ge("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 CJ=ge("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 mbe=ge("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 fbe=ge("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 pbe=ge("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 gbe=ge("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 xbe=ge("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 Fq=ge("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 ybe=ge("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 rf=ge("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 vbe=ge("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 Iw=ge("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 bbe=ge("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 _be=ge("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 wbe=ge("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 jbe=ge("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 Nbe=ge("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 kbe=ge("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 Sbe=ge("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 Cbe=ge("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 TE=ge("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 Abe=ge("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 nh=ge("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 Ebe=ge("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 Tbe=ge("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 Mbe=ge("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 I4=ge("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 Pbe=ge("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 Ibe=ge("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 AJ=ge("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 Lbe=ge("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 Rbe=ge("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 HS=ge("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 Dbe=ge("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 Fbe=ge("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 Obe=ge("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 zbe=ge("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 Bbe=ge("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 $be=ge("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 Ube=ge("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 qbe=ge("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 Vbe=ge("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 GD=ge("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 Hbe=ge("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 Gbe=ge("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 Wbe=ge("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 Kbe=ge("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 Ybe=ge("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 Zbe=ge("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 Xbe=ge("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 Qbe=ge("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 Jbe=ge("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 e1e=ge("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 t1e=ge("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 _b=ge("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 s1e=ge("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 WD=ge("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 EJ=ge("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 n1e=ge("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 r1e=ge("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 a1e=ge("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 i1e=ge("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 o1e=ge("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 l1e=ge("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 c1e=ge("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 d1e=ge("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 Oq=ge("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 u1e=ge("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 h1e=ge("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 m1e=ge("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 f1e=ge("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 p1e=ge("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 g1e=ge("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 x1e=ge("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 y1e=ge("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 v1e=ge("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 b1e=ge("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 _1e=ge("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 w1e=ge("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 j1e=ge("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 N1e=ge("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 k1e=ge("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 S1e=ge("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 C1e=ge("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 A1e=ge("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 E1e=ge("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 Vz=ge("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 ul=ge("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 T1e=ge("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 M1e=ge("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 KD=ge("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 P1e=ge("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 I1e=ge("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 L1e=ge("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 R1e=ge("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 D1e=ge("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 F1e=ge("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 O1e=ge("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 z1e=ge("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 B1e=ge("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 $1e=ge("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 U1e=ge("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 q1e=ge("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 V1e=ge("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 H1e=ge("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 G1e=ge("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 W1e=ge("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 K1e=ge("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 dl=ge("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 Y1e=ge("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 Z1e=ge("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 of=ge("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 X1e=ge("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 Q1e=ge("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 YD=ge("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 J1e=ge("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 ZD=ge("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 Uj=ge("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 e_e=ge("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 Ug=ge("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 t_e=ge("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 s_e=ge("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 n_e=ge("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 r_e=ge("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 TJ=ge("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 a_e=ge("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 MJ=ge("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 r4=ge("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 i_e=ge("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 o_e=ge("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 zq=ge("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 wb=ge("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 l_e=ge("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 c_e=ge("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 PJ=ge("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 d_e=ge("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 WI=ge("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 u_e=ge("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 h_e=ge("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 Bq=ge("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 Hz=ge("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 $q=ge("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 m_e=ge("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 f_e=ge("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 p_e=ge("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 g_e=ge("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 x_e=ge("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 y_e=ge("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 v_e=ge("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 b_e=ge("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 IJ=ge("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 __e=ge("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 w_e=ge("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 Jo=ge("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 j_e=ge("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 N_e=ge("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 k_e=ge("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 Lw=ge("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 S_e=ge("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 C_e=ge("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 A_e=ge("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 E_e=ge("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 LJ=ge("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 T_e=ge("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 M_e=ge("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 va=ge("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 XD=ge("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 QD=ge("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 RJ=ge("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 P_e=ge("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 I_e=ge("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 L_e=ge("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 R_e=ge("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 Av=ge("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 D_e=ge("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 F_e=ge("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 Mc=ge("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 O_e=ge("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 z_e=ge("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 Gz=ge("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 JD=ge("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 eF=ge("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 B_e=ge("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 Uq=ge("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 eC=ge("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 $_e=ge("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 Tf=ge("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 ME=ge("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 U_e=ge("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 q_e=ge("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 V_e=ge("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 H_e=ge("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 h2=ge("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 KI=ge("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 G_e=ge("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 S_=ge("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 W_e=ge("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 K_e=ge("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 Y_e=ge("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 Z_e=ge("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 X_e=ge("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 Q_e=ge("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 J_e=ge("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 ewe=ge("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 twe=ge("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 swe=ge("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 qq=ge("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 nwe=ge("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 rwe=ge("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 tF=ge("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 awe=ge("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 iwe=ge("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 owe=ge("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 lwe=ge("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 cwe=ge("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 dwe=ge("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 L4=ge("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 YI=ge("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 Qf=ge("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 uwe=ge("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 hwe=ge("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 mwe=ge("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 m2=ge("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 fwe=ge("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 pwe=ge("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 gwe=ge("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 xwe=ge("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 ywe=ge("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 f2=ge("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 Vq=ge("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 vwe=ge("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 bwe=ge("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 tC=ge("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 _we=ge("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 bd=ge("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 Ad=ge("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 hy=ge("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 wwe=ge("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 Ev=ge("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 jwe=ge("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 Nwe=ge("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 DJ=ge("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 kwe=ge("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 Swe=ge("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 p2=ge("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 FJ=ge("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 Cwe=ge("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 Awe=ge("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 Ewe=ge("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 Twe=ge("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 Mwe=ge("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 Pwe=ge("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 P0=ge("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 kt=ge("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 Iwe=ge("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 Lwe=ge("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 Rwe=ge("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 Dwe=ge("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 Hq=ge("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 sF=ge("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 OJ=ge("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 nF=ge("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 pc=ge("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 ZI=ge("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 Wz=ge("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 Fwe=ge("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 Owe=ge("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 zwe=ge("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 Bwe=ge("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 Kz=ge("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 $we=ge("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 Gq=ge("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 Wq=ge("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 Uwe=ge("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 qwe=ge("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 Vwe=ge("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 XI=ge("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 mn=ge("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 Hwe=ge("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 Gwe=ge("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 Wwe=ge("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 Kwe=ge("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 Ywe=ge("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 Zwe=ge("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 Xwe=ge("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 Qwe=ge("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 Jwe=ge("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 eje=ge("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 tje=ge("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 sje=ge("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 ci=ge("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 zJ=ge("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 Yz=ge("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 nje=ge("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 BJ=ge("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 Zz=ge("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 PE=ge("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 rje=ge("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 xm=ge("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 aje=ge("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 ije=ge("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 IE=ge("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 Xz=ge("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 oje=ge("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 lje=ge("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 Kq=ge("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 cje=ge("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 dje=ge("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 uje=ge("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 $J=ge("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 hje=ge("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 mje=ge("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 fje=ge("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 Th=ge("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 pje=ge("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 gje=ge("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 xje=ge("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 yje=ge("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 vje=ge("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 bje=ge("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 UJ=ge("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 _je=ge("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 p4=ge("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 LE=ge("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 qJ=ge("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 wje=ge("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 jje=ge("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 VJ=ge("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 Nje=ge("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 eo=ge("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 HJ=ge("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 kje=ge("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 rF=ge("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 Qz=ge("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 Sje=ge("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 Cje=ge("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 Aje=ge("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 Eje=ge("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 Tje=ge("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 Mje=ge("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 Pje=ge("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 Ije=ge("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 tk=ge("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 Lje=ge("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 Rje=ge("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 Dje=ge("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 Fje=ge("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 Oje=ge("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 zje=ge("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 Yq=ge("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 Bje=ge("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 $je=ge("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 Uje=ge("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 Jz=ge("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 qje=ge("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 sk=ge("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 Vje=ge("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 Hje=ge("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 Gje=ge("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 Wje=ge("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 Kje=ge("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 GJ=ge("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 Yje=ge("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 Lm=ge("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 hb=ge("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 Zje=ge("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 aF=ge("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 Xje=ge("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 Qje=ge("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 Jje=ge("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 e2e=ge("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 t2e=ge("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 s2e=ge("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 n2e=ge("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 r2e=ge("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 a2e=ge("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 i2e=ge("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 o2e=ge("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 l2e=ge("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 WJ=ge("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 c2e=ge("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 d2e=ge("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 u2e=ge("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 Zq=ge("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 h2e=ge("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 m2e=ge("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 f2e=ge("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 KJ=ge("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 p2e=ge("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 nk=ge("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 g2e=ge("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 x2e=ge("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 y2e=ge("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 v2e=ge("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 b2e=ge("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 _2e=ge("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 w2e=ge("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 j2e=ge("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 N2e=ge("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 BS=ge("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 k2e=ge("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 iF=ge("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 oF=ge("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 S2e=ge("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 C2e=ge("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 A2e=ge("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 E2e=ge("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 T2e=ge("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 M2e=ge("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 P2e=ge("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 I2e=ge("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 L2e=ge("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 R2e=ge("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 D2e=ge("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 F2e=ge("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 vm=ge("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 O2e=ge("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 z2e=ge("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 lF=ge("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 B2e=ge("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 Yc=ge("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 $2e=ge("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 cF=ge("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 U2e=ge("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 q2e=ge("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 dF=ge("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 uF=ge("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 hF=ge("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 mF=ge("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 V2e=ge("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 fF=ge("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 H2e=ge("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 G2e=ge("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 W2e=ge("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 pF=ge("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 K2e=ge("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 Y2e=ge("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 Z2e=ge("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 X2e=ge("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 DA=ge("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 QI=ge("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 Q2e=ge("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 J2e=ge("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 Ax=ge("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 Tv=ge("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 eNe=ge("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 tNe=ge("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 wf=ge("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 sNe=ge("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 RE=ge("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 LN=ge("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 Xq=ge("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 nNe=ge("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 rNe=ge("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 gi=ge("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 aNe=ge("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 Rw=ge("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 iNe=ge("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 oNe=ge("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 YJ=ge("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 lNe=ge("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 cNe=ge("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 dNe=ge("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 uNe=ge("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 hNe=ge("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 Da=ge("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 mNe=ge("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 fNe=ge("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 pNe=ge("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 gNe=ge("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 xNe=ge("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 ZJ=ge("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 yNe=ge("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 vNe=ge("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 bNe=ge("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 _Ne=ge("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 wNe=ge("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 XJ=ge("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 DE=ge("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 jNe=ge("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 NNe=ge("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 kNe=ge("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 SNe=ge("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 QJ=ge("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 Bu=ge("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 CNe=ge("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 gF=ge("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 g2=ge("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 dn=ge("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 ANe=ge("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 ENe=ge("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 TNe=ge("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 MNe=ge("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 PNe=ge("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 INe=ge("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 LNe=ge("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 RNe=ge("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 DNe=ge("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 JJ=ge("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 jb=ge("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 FNe=ge("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 FE=ge("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 ONe=ge("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 zNe=ge("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 BNe=ge("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 $Ne=ge("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 Jp=ge("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 x2=ge("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 UNe=ge("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 Qq=ge("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 qNe=ge("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 VNe=ge("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 HNe=ge("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 GNe=ge("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 Nb=ge("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 WNe=ge("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 KNe=ge("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 YNe=ge("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 ZNe=ge("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 XNe=ge("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 QNe=ge("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 JNe=ge("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 eke=ge("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 tke=ge("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 ske=ge("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 nke=ge("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 rke=ge("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 ake=ge("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 Jq=ge("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 xF=ge("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 ike=ge("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 oke=ge("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 lke=ge("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 cke=ge("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 dke=ge("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 OE=ge("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 uke=ge("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 eV=ge("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 hke=ge("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 ro=ge("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 mke=ge("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 fke=ge("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 pke=ge("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 gke=ge("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 eee=ge("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 zE=ge("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 xke=ge("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 yke=ge("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 vke=ge("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 tV=ge("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 bke=ge("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 _ke=ge("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 qg=ge("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 wke=ge("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 jke=ge("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 yF=ge("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 Nke=ge("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 Ex=ge("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 kke=ge("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 e7=ge("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 Ske=ge("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 sV=ge("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 Cke=ge("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 vF=ge("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 bF=ge("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 Ake=ge("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 Eke=ge("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 R4=ge("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 Tke=ge("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 Mke=ge("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 Pke=ge("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 Ike=ge("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 Lke=ge("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 Rke=ge("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 Dke=ge("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 Fke=ge("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 tl=ge("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 _F=ge("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 Oke=ge("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 zke=ge("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 Bke=ge("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 $ke=ge("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 Uke=ge("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 qke=ge("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 Vke=ge("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 Hke=ge("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 Gke=ge("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 Wke=ge("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 Kke=ge("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 Yke=ge("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 Zke=ge("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 Xke=ge("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 Qke=ge("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 nV=ge("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 Jke=ge("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 eSe=ge("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 tSe=ge("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 sSe=ge("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 rV=ge("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 Kr=ge("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 nSe=ge("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 wF=ge("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 rSe=ge("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 Yr=ge("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 aSe=ge("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 iSe=ge("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 oSe=ge("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 lSe=ge("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 cSe=ge("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 dSe=ge("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 sC=ge("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 Sd=ge("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 uSe=ge("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 zd=ge("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 tee=ge("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 hSe=ge("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 mSe=ge("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 aV=ge("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 fSe=ge("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 bm=ge("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 pSe=ge("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 gSe=ge("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 xSe=ge("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 t7=ge("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 ySe=ge("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 s7=ge("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 jF=ge("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 Mf=ge("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 vSe=ge("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 bSe=ge("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 _Se=ge("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 D4=ge("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 wSe=ge("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 nC=ge("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 jSe=ge("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 NSe=ge("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 kSe=ge("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 SSe=ge("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 n7=ge("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 CSe=ge("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 ASe=ge("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 ESe=ge("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 TSe=ge("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 MSe=ge("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 PSe=ge("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 ISe=ge("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 LSe=ge("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 see=ge("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 RSe=ge("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 DSe=ge("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 nee=ge("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 FSe=ge("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 OSe=ge("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 zSe=ge("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 BSe=ge("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 JI=ge("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 NF=ge("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 $Se=ge("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 USe=ge("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 _1=ge("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 qSe=ge("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 VSe=ge("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 HSe=ge("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 t2=ge("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 iV=ge("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 GSe=ge("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 WSe=ge("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 KSe=ge("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 eL=ge("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 Nn=ge("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 YSe=ge("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 ZSe=ge("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 XSe=ge("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 QSe=ge("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 JSe=ge("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 eCe=ge("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 tCe=ge("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 tL=ge("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 kF=ge("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 SF=ge("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 CF=ge("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 AF=ge("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 EF=ge("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 TF=ge("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 MF=ge("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 PF=ge("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 IF=ge("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 LF=ge("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 RF=ge("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 DF=ge("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 FF=ge("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 OF=ge("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 zF=ge("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 x5=ge("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 Kj=ge("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 BF=ge("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 $F=ge("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 UF=ge("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 qF=ge("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 VF=ge("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 HF=ge("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 sCe=ge("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 nCe=ge("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 GF=ge("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 WF=ge("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 KF=ge("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 YF=ge("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 ZF=ge("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 XF=ge("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 QF=ge("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 JF=ge("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 eO=ge("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 tO=ge("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 sO=ge("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 nO=ge("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 rO=ge("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 aO=ge("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 iO=ge("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 _p=ge("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 oO=ge("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 lO=ge("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 cO=ge("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 dO=ge("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 uO=ge("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 hO=ge("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 rCe=ge("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 mO=ge("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 fO=ge("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 pO=ge("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 gO=ge("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 xO=ge("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 aCe=ge("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 iCe=ge("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 yO=ge("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 vO=ge("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 bO=ge("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 _O=ge("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 C_=ge("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 oCe=ge("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 lCe=ge("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 cCe=ge("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 dCe=ge("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 uCe=ge("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 Ja=ge("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 hCe=ge("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 mCe=ge("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 fCe=ge("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 pCe=ge("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 r7=ge("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 oV=ge("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 gCe=ge("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 xCe=ge("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 ree=ge("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 yCe=ge("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 vCe=ge("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 bCe=ge("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 _Ce=ge("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 wCe=ge("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 rk=ge("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 jCe=ge("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 NCe=ge("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 kCe=ge("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 SCe=ge("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 CCe=ge("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 ACe=ge("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 ECe=ge("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 TCe=ge("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 MCe=ge("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 lV=ge("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 PCe=ge("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 ICe=ge("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 LCe=ge("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 RCe=ge("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 DCe=ge("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 FCe=ge("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 cV=ge("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 OCe=ge("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 dV=ge("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 zCe=ge("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 Ap=ge("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 aee=ge("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 BCe=ge("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 $Ce=ge("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 UCe=ge("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 qCe=ge("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 VCe=ge("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 HCe=ge("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 rh=ge("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 GCe=ge("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 WCe=ge("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 KCe=ge("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 YCe=ge("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 wO=ge("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 ZCe=ge("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 XCe=ge("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 uV=ge("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 QCe=ge("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 JCe=ge("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 e5e=ge("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 jO=ge("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 t5e=ge("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 s5e=ge("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 n5e=ge("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 r5e=ge("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 a5e=ge("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 iee=ge("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 Vy=ge("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 i5e=ge("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 o5e=ge("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 l5e=ge("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 c5e=ge("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 d5e=ge("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 u5e=ge("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 a7=ge("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 h5e=ge("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 m5e=ge("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 f5e=ge("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 p5e=ge("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 g5e=ge("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 x5e=ge("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 y5e=ge("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 v5e=ge("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 b5e=ge("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 _5e=ge("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 w5e=ge("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 j5e=ge("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 N5e=ge("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 k5e=ge("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 S5e=ge("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 C5e=ge("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 A5e=ge("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 E5e=ge("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 T5e=ge("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 NO=ge("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 Wn=ge("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 M5e=ge("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 P5e=ge("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 kO=ge("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 sL=ge("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 I5e=ge("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 L5e=ge("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 rC=ge("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 R5e=ge("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 Yl=ge("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 wl=ge("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 D5e=ge("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 F5e=ge("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 Kl=ge("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 oee=ge("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 O5e=ge("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 z5e=ge("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 SO=ge("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 B5e=ge("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 $5e=ge("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 lee=ge("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 U5e=ge("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 hV=ge("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 q5e=ge("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 V5e=ge("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 i7=ge("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 cee=ge("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 H5e=ge("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 BE=ge("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 G5e=ge("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 W5e=ge("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 K5e=ge("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 CO=ge("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 Y5e=ge("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 $E=ge("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 o7=ge("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 ni=ge("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 Z5e=ge("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 y2=ge("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 dee=ge("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 mV=ge("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 X5e=ge("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 sc=ge("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 lP=ge("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 AO=ge("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 EO=ge("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 Q5e=ge("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 TO=ge("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 fV=ge("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 MO=ge("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 cP=ge("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 J5e=ge("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 pV=ge("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 sl=ge("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 v0=ge("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 Zn=ge("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 PO=ge("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 IO=ge("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 e4e=ge("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 gV=ge("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 t4e=ge("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 s4e=ge("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 n4e=ge("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 r4e=ge("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 a4e=ge("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 i4e=ge("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 ua=ge("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 o4e=ge("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 l4e=ge("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 c4e=ge("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 d4e=ge("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 u4e=ge("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 uee=ge("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 h4e=ge("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 hee=ge("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 m4e=ge("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 f4e=ge("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 p4e=ge("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 LO=ge("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 l7=ge("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 g4e=ge("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 sy=ge("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 x4e=ge("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 y4e=ge("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 v4e=ge("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 b4e=ge("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 _4e=ge("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 w4e=ge("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 j4e=ge("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 N4e=ge("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 k4e=ge("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 S4e=ge("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 C4e=ge("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 A4e=ge("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 E4e=ge("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 T4e=ge("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 M4e=ge("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 P4e=ge("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 I4e=ge("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 L4e=ge("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 R4e=ge("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 D4e=ge("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 F4e=ge("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 O4e=ge("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 c7=ge("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 z4e=ge("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 B4e=ge("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 F4=ge("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 gr=ge("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 xV=ge("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 $4e=ge("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 eg=ge("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 nL=ge("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 yV=ge("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 J0s=Object.freeze(Object.defineProperty({__proto__:null,AArrowDown:_me,AArrowUp:wme,ALargeSmall:jme,Accessibility:Nme,Activity:af,AirVent:kme,Airplay:Sme,AlarmClock:Ame,AlarmClockCheck:DR,AlarmClockMinus:FR,AlarmClockOff:Cme,AlarmClockPlus:OR,AlarmSmoke:Eme,Album:Tme,AlignCenter:zI,AlignCenterHorizontal:Mme,AlignCenterVertical:Pme,AlignEndHorizontal:Ime,AlignEndVertical:Lme,AlignHorizontalDistributeCenter:Rme,AlignHorizontalDistributeEnd:Dme,AlignHorizontalDistributeStart:Fme,AlignHorizontalJustifyCenter:Ome,AlignHorizontalJustifyEnd:zme,AlignHorizontalJustifyStart:Bme,AlignHorizontalSpaceAround:$me,AlignHorizontalSpaceBetween:Ume,AlignJustify:qme,AlignLeft:BI,AlignRight:$I,AlignStartHorizontal:Vme,AlignStartVertical:Hme,AlignVerticalDistributeCenter:Gme,AlignVerticalDistributeEnd:Wme,AlignVerticalDistributeStart:Kme,AlignVerticalJustifyCenter:Yme,AlignVerticalJustifyEnd:Zme,AlignVerticalJustifyStart:Xme,AlignVerticalSpaceAround:Qme,AlignVerticalSpaceBetween:Jme,Ambulance:efe,Ampersand:tfe,Ampersands:sfe,Amphora:nfe,Anchor:rfe,Angry:afe,Annoyed:ife,Antenna:ofe,Anvil:lfe,Aperture:cfe,AppWindow:ufe,AppWindowMac:dfe,Apple:hfe,Archive:Sv,ArchiveRestore:UI,ArchiveX:mfe,Armchair:ffe,ArrowBigDown:gfe,ArrowBigDownDash:pfe,ArrowBigLeft:yfe,ArrowBigLeftDash:xfe,ArrowBigRight:bfe,ArrowBigRightDash:vfe,ArrowBigUp:wfe,ArrowBigUpDash:_fe,ArrowDown:Dg,ArrowDown01:jfe,ArrowDown10:Nfe,ArrowDownAZ:zR,ArrowDownFromLine:kfe,ArrowDownLeft:Sfe,ArrowDownNarrowWide:Cfe,ArrowDownRight:pJ,ArrowDownToDot:Afe,ArrowDownToLine:Efe,ArrowDownUp:Tfe,ArrowDownWideNarrow:BR,ArrowDownZA:$R,ArrowLeft:qa,ArrowLeftFromLine:Mfe,ArrowLeftRight:gJ,ArrowLeftToLine:Pfe,ArrowRight:ei,ArrowRightFromLine:Ife,ArrowRightLeft:E4,ArrowRightToLine:Lfe,ArrowUp:Zf,ArrowUp01:Rfe,ArrowUp10:Dfe,ArrowUpAZ:UR,ArrowUpDown:By,ArrowUpFromDot:Ffe,ArrowUpFromLine:Ofe,ArrowUpLeft:zfe,ArrowUpNarrowWide:qR,ArrowUpRight:Oz,ArrowUpToLine:Bfe,ArrowUpWideNarrow:$fe,ArrowUpZA:VR,ArrowsUpFromLine:Ufe,Asterisk:qfe,AtSign:Vfe,Atom:Hfe,AudioLines:Gfe,AudioWaveform:Wfe,Award:Rm,Axe:Kfe,Axis3d:HR,Baby:Yfe,Backpack:Zfe,Badge:hpe,BadgeAlert:Xfe,BadgeCent:Qfe,BadgeCheck:RA,BadgeDollarSign:Jfe,BadgeEuro:epe,BadgeHelp:tpe,BadgeIndianRupee:spe,BadgeInfo:npe,BadgeJapaneseYen:rpe,BadgeMinus:ape,BadgePercent:ipe,BadgePlus:ope,BadgePoundSterling:lpe,BadgeRussianRuble:cpe,BadgeSwissFranc:dpe,BadgeX:upe,BaggageClaim:mpe,Ban:zz,Banana:fpe,Bandage:ppe,Banknote:gpe,Barcode:xpe,Baseline:ype,Bath:T0,Battery:Npe,BatteryCharging:vpe,BatteryFull:bpe,BatteryLow:_pe,BatteryMedium:wpe,BatteryWarning:jpe,Beaker:xJ,Bean:Spe,BeanOff:kpe,Bed:l2,BedDouble:T4,BedSingle:Cpe,Beef:Ape,Beer:Tpe,BeerOff:Epe,Bell:qy,BellDot:Mpe,BellElectric:Ppe,BellMinus:Ipe,BellOff:XS,BellPlus:Lpe,BellRing:QS,BetweenHorizontalEnd:GR,BetweenHorizontalStart:WR,BetweenVerticalEnd:Rpe,BetweenVerticalStart:Dpe,BicepsFlexed:Fpe,Bike:Ope,Binary:zpe,Binoculars:Bpe,Biohazard:$pe,Bird:Upe,Bitcoin:qpe,Blend:Vpe,Blinds:Hpe,Blocks:Gpe,Bluetooth:Zpe,BluetoothConnected:Wpe,BluetoothOff:Kpe,BluetoothSearching:Ype,Bold:AE,Bolt:Xpe,Bomb:Qpe,Bone:Jpe,Book:_ge,BookA:ege,BookAudio:tge,BookCheck:sge,BookCopy:nge,BookDashed:KR,BookDown:rge,BookHeadphones:age,BookHeart:ige,BookImage:oge,BookKey:lge,BookLock:cge,BookMarked:dge,BookMinus:uge,BookOpen:Xf,BookOpenCheck:hge,BookOpenText:mge,BookPlus:fge,BookText:pge,BookType:gge,BookUp:yge,BookUp2:xge,BookUser:vge,BookX:bge,Bookmark:M0,BookmarkCheck:wge,BookmarkMinus:jge,BookmarkPlus:qI,BookmarkX:Nge,BoomBox:kge,Bot:M4,BotMessageSquare:Sge,BotOff:Cge,Box:yJ,Boxes:Age,Braces:aP,Brackets:Ege,Brain:vJ,BrainCircuit:Tge,BrainCog:Mge,BrickWall:Pge,Briefcase:Sx,BriefcaseBusiness:Ige,BriefcaseConveyorBelt:Lge,BriefcaseMedical:Rge,BringToFront:Dge,Brush:Fge,Bug:Bge,BugOff:Oge,BugPlay:zge,Building:VI,Building2:ji,Bus:Uge,BusFront:$ge,Cable:Vge,CableCar:qge,Cake:Fg,CakeSlice:Hge,Calculator:c2,Calendar:Ta,Calendar1:Gge,CalendarArrowDown:Wge,CalendarArrowUp:Kge,CalendarCheck:bb,CalendarCheck2:Yge,CalendarClock:Au,CalendarCog:Zge,CalendarDays:Kc,CalendarFold:Xge,CalendarHeart:JS,CalendarMinus:Jge,CalendarMinus2:Qge,CalendarOff:Tq,CalendarPlus:jv,CalendarPlus2:exe,CalendarRange:txe,CalendarSearch:sxe,CalendarSync:nxe,CalendarX:bJ,CalendarX2:rxe,Camera:Cx,CameraOff:axe,Candy:lxe,CandyCane:ixe,CandyOff:oxe,Cannabis:cxe,Captions:YR,CaptionsOff:dxe,Car:mxe,CarFront:uxe,CarTaxiFront:hxe,Caravan:fxe,Carrot:pxe,CaseLower:gxe,CaseSensitive:xxe,CaseUpper:yxe,CassetteTape:vxe,Cast:bxe,Castle:_xe,Cat:wxe,Cctv:jxe,ChartArea:ZR,ChartBar:QR,ChartBarBig:XR,ChartBarDecreasing:Nxe,ChartBarIncreasing:kxe,ChartBarStacked:Sxe,ChartCandlestick:JR,ChartColumn:Wl,ChartColumnBig:eD,ChartColumnDecreasing:Cxe,ChartColumnIncreasing:tD,ChartColumnStacked:Axe,ChartGantt:Exe,ChartLine:sD,ChartNetwork:Txe,ChartNoAxesColumn:rD,ChartNoAxesColumnDecreasing:Mxe,ChartNoAxesColumnIncreasing:nD,ChartNoAxesCombined:Pxe,ChartNoAxesGantt:aD,ChartPie:iD,ChartScatter:oD,ChartSpline:Ixe,Check:la,CheckCheck:Bz,ChefHat:Lxe,Cherry:Rxe,ChevronDown:Tl,ChevronFirst:Dxe,ChevronLast:Fxe,ChevronLeft:Cd,ChevronRight:Di,ChevronUp:v1,ChevronsDown:zxe,ChevronsDownUp:Oxe,ChevronsLeft:Uxe,ChevronsLeftRight:$xe,ChevronsLeftRightEllipsis:Bxe,ChevronsRight:Vxe,ChevronsRightLeft:qxe,ChevronsUp:Hxe,ChevronsUpDown:Pw,Chrome:$z,Church:Gxe,Cigarette:Kxe,CigaretteOff:Wxe,Circle:Og,CircleAlert:ll,CircleArrowDown:lD,CircleArrowLeft:cD,CircleArrowOutDownLeft:dD,CircleArrowOutDownRight:uD,CircleArrowOutUpLeft:hD,CircleArrowOutUpRight:mD,CircleArrowRight:fD,CircleArrowUp:pD,CircleCheck:qr,CircleCheckBig:Nc,CircleChevronDown:gD,CircleChevronLeft:xD,CircleChevronRight:yD,CircleChevronUp:vD,CircleDashed:Yxe,CircleDivide:bD,CircleDollarSign:Zxe,CircleDot:Qxe,CircleDotDashed:Xxe,CircleEllipsis:Jxe,CircleEqual:eye,CircleFadingArrowUp:tye,CircleFadingPlus:sye,CircleGauge:_D,CircleHelp:s4,CircleMinus:wD,CircleOff:nye,CircleParking:ND,CircleParkingOff:jD,CirclePause:kD,CirclePercent:SD,CirclePlay:tf,CirclePlus:CD,CirclePower:AD,CircleSlash:rye,CircleSlash2:ED,CircleStop:TD,CircleUser:PD,CircleUserRound:MD,CircleX:ku,CircuitBoard:aye,Citrus:iye,Clapperboard:Mq,Clipboard:mye,ClipboardCheck:JN,ClipboardCopy:oye,ClipboardList:zg,ClipboardMinus:lye,ClipboardPaste:cye,ClipboardPen:LD,ClipboardPenLine:ID,ClipboardPlus:dye,ClipboardType:uye,ClipboardX:hye,Clock:da,Clock1:fye,Clock10:pye,Clock11:gye,Clock12:xye,Clock2:yye,Clock3:Pq,Clock4:vye,Clock5:bye,Clock6:_ye,Clock7:wye,Clock8:jye,Clock9:Nye,ClockAlert:kye,ClockArrowDown:Sye,ClockArrowUp:Cye,Cloud:Uye,CloudAlert:Aye,CloudCog:Eye,CloudDownload:RD,CloudDrizzle:Tye,CloudFog:Mye,CloudHail:Pye,CloudLightning:Iye,CloudMoon:Rye,CloudMoonRain:Lye,CloudOff:Dye,CloudRain:Oye,CloudRainWind:Fye,CloudSnow:zye,CloudSun:$ye,CloudSunRain:Bye,CloudUpload:iP,Cloudy:qye,Clover:yE,Club:Vye,Code:EE,CodeXml:n4,Codepen:Hye,Codesandbox:Gye,Coffee:P4,Cog:Wye,Coins:_J,Columns2:DD,Columns3:oP,Columns4:Kye,Combine:Yye,Command:Zye,Compass:Uz,Component:Xye,Computer:Qye,ConciergeBell:Jye,Cone:e0e,Construction:t0e,Contact:HI,ContactRound:FD,Container:s0e,Contrast:n0e,Cookie:r0e,CookingPot:a0e,Copy:Ha,CopyCheck:i0e,CopyMinus:o0e,CopyPlus:l0e,CopySlash:c0e,CopyX:d0e,Copyleft:u0e,Copyright:h0e,CornerDownLeft:m0e,CornerDownRight:wJ,CornerLeftDown:f0e,CornerLeftUp:p0e,CornerRightDown:g0e,CornerRightUp:x0e,CornerUpLeft:y0e,CornerUpRight:v0e,Cpu:b0e,CreativeCommons:_0e,CreditCard:Cv,Croissant:w0e,Crop:j0e,Cross:N0e,Crosshair:k0e,Crown:Bg,Cuboid:S0e,CupSoda:C0e,Currency:A0e,Cylinder:E0e,Dam:T0e,Database:Iq,DatabaseBackup:M0e,DatabaseZap:P0e,Delete:I0e,Dessert:L0e,Diameter:R0e,Diamond:O0e,DiamondMinus:D0e,DiamondPercent:OD,DiamondPlus:F0e,Dice1:z0e,Dice2:B0e,Dice3:$0e,Dice4:U0e,Dice5:q0e,Dice6:V0e,Dices:H0e,Diff:G0e,Disc:Z0e,Disc2:W0e,Disc3:K0e,DiscAlbum:Y0e,Divide:X0e,Dna:J0e,DnaOff:Q0e,Dock:eve,Dog:tve,DollarSign:ru,Donut:sve,DoorClosed:nve,DoorOpen:d2,Dot:rve,Download:di,DraftingCompass:ave,Drama:ive,Dribbble:ove,Drill:lve,Droplet:cve,Droplets:b1,Drum:dve,Drumstick:uve,Dumbbell:hve,Ear:fve,EarOff:mve,Earth:IN,EarthLock:pve,Eclipse:gve,Egg:Lq,EggFried:xve,EggOff:yve,Ellipsis:h_,EllipsisVertical:ty,Equal:_ve,EqualApproximately:vve,EqualNot:bve,Eraser:Rq,EthernetPort:wve,Euro:jve,Expand:Nve,ExternalLink:kr,Eye:Ca,EyeClosed:kve,EyeOff:$g,Facebook:Qp,Factory:Sve,Fan:Cve,FastForward:Ave,Feather:Eve,Fence:Tve,FerrisWheel:Mve,Figma:Pve,File:Fq,FileArchive:Ive,FileAudio:Rve,FileAudio2:Lve,FileAxis3d:zD,FileBadge:Fve,FileBadge2:Dve,FileBox:Ove,FileChartColumn:$D,FileChartColumnIncreasing:BD,FileChartLine:UD,FileChartPie:qD,FileCheck:jJ,FileCheck2:qz,FileClock:zve,FileCode:$ve,FileCode2:Bve,FileCog:VD,FileDiff:Uve,FileDigit:qve,FileDown:u2,FileHeart:Vve,FileImage:GI,FileInput:Hve,FileJson:Wve,FileJson2:Gve,FileKey:Yve,FileKey2:Kve,FileLock:Xve,FileLock2:Zve,FileMinus:Jve,FileMinus2:Qve,FileMusic:ebe,FileOutput:tbe,FilePen:HD,FilePenLine:m_,FilePlus:sbe,FilePlus2:Dq,FileQuestion:nbe,FileScan:rbe,FileSearch:NJ,FileSearch2:abe,FileSliders:ibe,FileSpreadsheet:ek,FileStack:kJ,FileSymlink:obe,FileTerminal:lbe,FileText:Jr,FileType:dbe,FileType2:cbe,FileUp:SJ,FileUser:ube,FileVideo:CJ,FileVideo2:hbe,FileVolume:fbe,FileVolume2:mbe,FileWarning:pbe,FileX:xbe,FileX2:gbe,Files:ybe,Film:rf,Filter:Iw,FilterX:vbe,Fingerprint:bbe,FireExtinguisher:_be,Fish:Nbe,FishOff:wbe,FishSymbol:jbe,Flag:TE,FlagOff:kbe,FlagTriangleLeft:Sbe,FlagTriangleRight:Cbe,Flame:nh,FlameKindling:Abe,Flashlight:Tbe,FlashlightOff:Ebe,FlaskConical:I4,FlaskConicalOff:Mbe,FlaskRound:Pbe,FlipHorizontal:AJ,FlipHorizontal2:Ibe,FlipVertical:Rbe,FlipVertical2:Lbe,Flower:Dbe,Flower2:HS,Focus:Fbe,FoldHorizontal:Obe,FoldVertical:zbe,Folder:Oq,FolderArchive:Bbe,FolderCheck:$be,FolderClock:Ube,FolderClosed:qbe,FolderCode:Vbe,FolderCog:GD,FolderDot:Hbe,FolderDown:Gbe,FolderGit:Kbe,FolderGit2:Wbe,FolderHeart:Ybe,FolderInput:Zbe,FolderKanban:Xbe,FolderKey:Qbe,FolderLock:Jbe,FolderMinus:e1e,FolderOpen:_b,FolderOpenDot:t1e,FolderOutput:s1e,FolderPen:WD,FolderPlus:EJ,FolderRoot:n1e,FolderSearch:a1e,FolderSearch2:r1e,FolderSymlink:i1e,FolderSync:o1e,FolderTree:l1e,FolderUp:c1e,FolderX:d1e,Folders:u1e,Footprints:h1e,Forklift:m1e,Forward:f1e,Frame:p1e,Framer:g1e,Frown:x1e,Fuel:y1e,Fullscreen:v1e,GalleryHorizontal:_1e,GalleryHorizontalEnd:b1e,GalleryThumbnails:w1e,GalleryVertical:N1e,GalleryVerticalEnd:j1e,Gamepad:S1e,Gamepad2:k1e,Gauge:C1e,Gavel:A1e,Gem:E1e,Ghost:Vz,Gift:ul,GitBranch:M1e,GitBranchPlus:T1e,GitCommitHorizontal:KD,GitCommitVertical:P1e,GitCompare:L1e,GitCompareArrows:I1e,GitFork:R1e,GitGraph:D1e,GitMerge:F1e,GitPullRequest:q1e,GitPullRequestArrow:O1e,GitPullRequestClosed:z1e,GitPullRequestCreate:$1e,GitPullRequestCreateArrow:B1e,GitPullRequestDraft:U1e,Github:V1e,Gitlab:H1e,GlassWater:G1e,Glasses:W1e,Globe:dl,GlobeLock:K1e,Goal:Y1e,Grab:Z1e,GraduationCap:of,Grape:X1e,Grid2x2:ZD,Grid2x2Check:Q1e,Grid2x2Plus:YD,Grid2x2X:J1e,Grid3x3:Uj,Grip:t_e,GripHorizontal:e_e,GripVertical:Ug,Group:s_e,Guitar:n_e,Ham:r_e,Hammer:TJ,Hand:zq,HandCoins:a_e,HandHeart:MJ,HandHelping:r4,HandMetal:i_e,HandPlatter:o_e,Handshake:wb,HardDrive:PJ,HardDriveDownload:l_e,HardDriveUpload:c_e,HardHat:d_e,Hash:WI,Haze:u_e,HdmiPort:h_e,Heading:g_e,Heading1:Bq,Heading2:Hz,Heading3:$q,Heading4:m_e,Heading5:f_e,Heading6:p_e,HeadphoneOff:x_e,Headphones:y_e,Headset:v_e,Heart:Jo,HeartCrack:b_e,HeartHandshake:IJ,HeartOff:__e,HeartPulse:w_e,Heater:j_e,Hexagon:N_e,Highlighter:k_e,History:Lw,Hop:C_e,HopOff:S_e,Hospital:A_e,Hotel:E_e,Hourglass:LJ,House:va,HousePlug:T_e,HousePlus:M_e,IceCreamBowl:XD,IceCreamCone:QD,IdCard:RJ,Image:Mc,ImageDown:P_e,ImageMinus:I_e,ImageOff:L_e,ImagePlay:R_e,ImagePlus:Av,ImageUp:D_e,ImageUpscale:F_e,Images:O_e,Import:z_e,Inbox:Gz,IndentDecrease:JD,IndentIncrease:eF,IndianRupee:B_e,Infinity:Uq,Info:eC,InspectionPanel:$_e,Instagram:Tf,Italic:ME,IterationCcw:U_e,IterationCw:q_e,JapaneseYen:V_e,Joystick:H_e,Kanban:h2,Key:S_,KeyRound:KI,KeySquare:G_e,Keyboard:Y_e,KeyboardMusic:W_e,KeyboardOff:K_e,Lamp:twe,LampCeiling:Z_e,LampDesk:X_e,LampFloor:Q_e,LampWallDown:J_e,LampWallUp:ewe,LandPlot:swe,Landmark:qq,Languages:nwe,Laptop:awe,LaptopMinimal:tF,LaptopMinimalCheck:rwe,Lasso:owe,LassoSelect:iwe,Laugh:lwe,Layers:L4,Layers2:cwe,Layers3:dwe,LayoutDashboard:YI,LayoutGrid:Qf,LayoutList:uwe,LayoutPanelLeft:hwe,LayoutPanelTop:mwe,LayoutTemplate:m2,Leaf:fwe,LeafyGreen:pwe,Lectern:gwe,LetterText:xwe,Library:f2,LibraryBig:ywe,LifeBuoy:Vq,Ligature:vwe,Lightbulb:tC,LightbulbOff:bwe,Link:Ad,Link2:bd,Link2Off:_we,Linkedin:hy,List:P0,ListCheck:wwe,ListChecks:Ev,ListCollapse:jwe,ListEnd:Nwe,ListFilter:DJ,ListMinus:kwe,ListMusic:Swe,ListOrdered:p2,ListPlus:FJ,ListRestart:Cwe,ListStart:Awe,ListTodo:Ewe,ListTree:Twe,ListVideo:Mwe,ListX:Pwe,Loader:Lwe,LoaderCircle:kt,LoaderPinwheel:Iwe,Locate:Hq,LocateFixed:Rwe,LocateOff:Dwe,Lock:pc,LockKeyhole:OJ,LockKeyholeOpen:sF,LockOpen:nF,LogIn:ZI,LogOut:Wz,Logs:Fwe,Lollipop:Owe,Luggage:zwe,Magnet:Bwe,Mail:mn,MailCheck:Kz,MailMinus:$we,MailOpen:Gq,MailPlus:Wq,MailQuestion:Uwe,MailSearch:qwe,MailWarning:Vwe,MailX:XI,Mailbox:Hwe,Mails:Gwe,Map:Yz,MapPin:ci,MapPinCheck:Kwe,MapPinCheckInside:Wwe,MapPinHouse:Ywe,MapPinMinus:Xwe,MapPinMinusInside:Zwe,MapPinOff:Qwe,MapPinPlus:eje,MapPinPlusInside:Jwe,MapPinX:sje,MapPinXInside:tje,MapPinned:zJ,Martini:nje,Maximize:Zz,Maximize2:BJ,Medal:PE,Megaphone:xm,MegaphoneOff:rje,Meh:aje,MemoryStick:ije,Menu:IE,Merge:Xz,MessageCircle:Th,MessageCircleCode:oje,MessageCircleDashed:lje,MessageCircleHeart:Kq,MessageCircleMore:cje,MessageCircleOff:dje,MessageCirclePlus:uje,MessageCircleQuestion:$J,MessageCircleReply:hje,MessageCircleWarning:mje,MessageCircleX:fje,MessageSquare:eo,MessageSquareCode:pje,MessageSquareDashed:gje,MessageSquareDiff:xje,MessageSquareDot:yje,MessageSquareHeart:vje,MessageSquareLock:bje,MessageSquareMore:UJ,MessageSquareOff:_je,MessageSquarePlus:p4,MessageSquareQuote:LE,MessageSquareReply:qJ,MessageSquareShare:wje,MessageSquareText:jje,MessageSquareWarning:VJ,MessageSquareX:Nje,MessagesSquare:HJ,Mic:Qz,MicOff:kje,MicVocal:rF,Microchip:Sje,Microscope:Cje,Microwave:Aje,Milestone:Eje,Milk:Mje,MilkOff:Tje,Minimize:Ije,Minimize2:Pje,Minus:tk,Monitor:sk,MonitorCheck:Lje,MonitorCog:Rje,MonitorDot:Dje,MonitorDown:Fje,MonitorOff:Oje,MonitorPause:zje,MonitorPlay:Yq,MonitorSmartphone:Bje,MonitorSpeaker:$je,MonitorStop:Uje,MonitorUp:Jz,MonitorX:qje,Moon:Hje,MoonStar:Vje,Mountain:Wje,MountainSnow:Gje,Mouse:Zje,MouseOff:Kje,MousePointer:hb,MousePointer2:GJ,MousePointerBan:Yje,MousePointerClick:Lm,Move:WJ,Move3d:aF,MoveDiagonal:Qje,MoveDiagonal2:Xje,MoveDown:t2e,MoveDownLeft:Jje,MoveDownRight:e2e,MoveHorizontal:s2e,MoveLeft:n2e,MoveRight:r2e,MoveUp:o2e,MoveUpLeft:a2e,MoveUpRight:i2e,MoveVertical:l2e,Music:Zq,Music2:c2e,Music3:d2e,Music4:u2e,Navigation:KJ,Navigation2:m2e,Navigation2Off:h2e,NavigationOff:f2e,Network:p2e,Newspaper:nk,Nfc:g2e,Notebook:b2e,NotebookPen:x2e,NotebookTabs:y2e,NotebookText:v2e,NotepadText:w2e,NotepadTextDashed:_2e,Nut:N2e,NutOff:j2e,Octagon:S2e,OctagonAlert:BS,OctagonMinus:k2e,OctagonPause:iF,OctagonX:oF,Omega:C2e,Option:A2e,Orbit:E2e,Origami:T2e,Package:vm,Package2:M2e,PackageCheck:P2e,PackageMinus:I2e,PackageOpen:L2e,PackagePlus:R2e,PackageSearch:D2e,PackageX:F2e,PaintBucket:O2e,PaintRoller:z2e,Paintbrush:B2e,PaintbrushVertical:lF,Palette:Yc,PanelBottom:q2e,PanelBottomClose:$2e,PanelBottomDashed:cF,PanelBottomOpen:U2e,PanelLeft:mF,PanelLeftClose:dF,PanelLeftDashed:uF,PanelLeftOpen:hF,PanelRight:G2e,PanelRightClose:V2e,PanelRightDashed:fF,PanelRightOpen:H2e,PanelTop:Y2e,PanelTopClose:W2e,PanelTopDashed:pF,PanelTopOpen:K2e,PanelsLeftBottom:Z2e,PanelsRightBottom:X2e,PanelsTopLeft:DA,Paperclip:QI,Parentheses:Q2e,ParkingMeter:J2e,PartyPopper:Ax,Pause:Tv,PawPrint:eNe,PcCase:tNe,Pen:LN,PenLine:wf,PenOff:sNe,PenTool:RE,Pencil:gi,PencilLine:Xq,PencilOff:nNe,PencilRuler:rNe,Pentagon:aNe,Percent:Rw,PersonStanding:iNe,PhilippinePeso:oNe,Phone:Da,PhoneCall:YJ,PhoneForwarded:lNe,PhoneIncoming:cNe,PhoneMissed:dNe,PhoneOff:uNe,PhoneOutgoing:hNe,Pi:mNe,Piano:fNe,Pickaxe:pNe,PictureInPicture:xNe,PictureInPicture2:gNe,PiggyBank:ZJ,Pilcrow:bNe,PilcrowLeft:yNe,PilcrowRight:vNe,Pill:wNe,PillBottle:_Ne,Pin:DE,PinOff:XJ,Pipette:jNe,Pizza:NNe,Plane:QJ,PlaneLanding:kNe,PlaneTakeoff:SNe,Play:Bu,Plug:g2,Plug2:CNe,PlugZap:gF,Plus:dn,Pocket:ENe,PocketKnife:ANe,Podcast:TNe,Pointer:PNe,PointerOff:MNe,Popcorn:INe,Popsicle:LNe,PoundSterling:RNe,Power:JJ,PowerOff:DNe,Presentation:jb,Printer:FE,PrinterCheck:FNe,Projector:ONe,Proportions:zNe,Puzzle:BNe,Pyramid:$Ne,QrCode:Jp,Quote:x2,Rabbit:UNe,Radar:Qq,Radiation:qNe,Radical:VNe,Radio:Nb,RadioReceiver:HNe,RadioTower:GNe,Radius:WNe,RailSymbol:KNe,Rainbow:YNe,Rat:ZNe,Ratio:XNe,Receipt:Jq,ReceiptCent:QNe,ReceiptEuro:JNe,ReceiptIndianRupee:eke,ReceiptJapaneseYen:tke,ReceiptPoundSterling:ske,ReceiptRussianRuble:nke,ReceiptSwissFranc:rke,ReceiptText:ake,RectangleEllipsis:xF,RectangleHorizontal:ike,RectangleVertical:oke,Recycle:lke,Redo:OE,Redo2:cke,RedoDot:dke,RefreshCcw:eV,RefreshCcwDot:uke,RefreshCw:ro,RefreshCwOff:hke,Refrigerator:mke,Regex:fke,RemoveFormatting:pke,Repeat:zE,Repeat1:gke,Repeat2:eee,Replace:yke,ReplaceAll:xke,Reply:tV,ReplyAll:vke,Rewind:bke,Ribbon:_ke,Rocket:qg,RockingChair:wke,RollerCoaster:jke,Rotate3d:yF,RotateCcw:Ex,RotateCcwSquare:Nke,RotateCw:e7,RotateCwSquare:kke,Route:sV,RouteOff:Ske,Router:Cke,Rows2:vF,Rows3:bF,Rows4:Ake,Rss:Eke,Ruler:R4,RussianRuble:Tke,Sailboat:Mke,Salad:Pke,Sandwich:Ike,Satellite:Rke,SatelliteDish:Lke,Save:tl,SaveAll:Dke,SaveOff:Fke,Scale:Oke,Scale3d:_F,Scaling:zke,Scan:Wke,ScanBarcode:Bke,ScanEye:$ke,ScanFace:Uke,ScanLine:qke,ScanQrCode:Vke,ScanSearch:Hke,ScanText:Gke,School:Kke,Scissors:Zke,ScissorsLineDashed:Yke,ScreenShare:Qke,ScreenShareOff:Xke,Scroll:Jke,ScrollText:nV,Search:Kr,SearchCheck:eSe,SearchCode:tSe,SearchSlash:sSe,SearchX:rV,Section:nSe,Send:Yr,SendHorizontal:wF,SendToBack:rSe,SeparatorHorizontal:aSe,SeparatorVertical:iSe,Server:dSe,ServerCog:oSe,ServerCrash:lSe,ServerOff:cSe,Settings:Sd,Settings2:sC,Shapes:uSe,Share:tee,Share2:zd,Sheet:hSe,Shell:mSe,Shield:Mf,ShieldAlert:aV,ShieldBan:fSe,ShieldCheck:bm,ShieldEllipsis:pSe,ShieldHalf:gSe,ShieldMinus:xSe,ShieldOff:t7,ShieldPlus:ySe,ShieldQuestion:s7,ShieldX:jF,Ship:bSe,ShipWheel:vSe,Shirt:_Se,ShoppingBag:D4,ShoppingBasket:wSe,ShoppingCart:nC,Shovel:jSe,ShowerHead:NSe,Shrink:kSe,Shrub:SSe,Shuffle:n7,Sigma:CSe,Signal:PSe,SignalHigh:ASe,SignalLow:ESe,SignalMedium:TSe,SignalZero:MSe,Signature:ISe,Signpost:see,SignpostBig:LSe,Siren:RSe,SkipBack:DSe,SkipForward:nee,Skull:FSe,Slack:OSe,Slash:zSe,Slice:BSe,SlidersHorizontal:JI,SlidersVertical:NF,Smartphone:_1,SmartphoneCharging:$Se,SmartphoneNfc:USe,Smile:VSe,SmilePlus:qSe,Snail:HSe,Snowflake:t2,Sofa:iV,Soup:GSe,Space:WSe,Spade:KSe,Sparkle:eL,Sparkles:Nn,Speaker:YSe,Speech:ZSe,SpellCheck:QSe,SpellCheck2:XSe,Spline:JSe,Split:eCe,SprayCan:tCe,Sprout:tL,Square:C_,SquareActivity:kF,SquareArrowDown:AF,SquareArrowDownLeft:SF,SquareArrowDownRight:CF,SquareArrowLeft:EF,SquareArrowOutDownLeft:TF,SquareArrowOutDownRight:MF,SquareArrowOutUpLeft:PF,SquareArrowOutUpRight:IF,SquareArrowRight:LF,SquareArrowUp:FF,SquareArrowUpLeft:RF,SquareArrowUpRight:DF,SquareAsterisk:OF,SquareBottomDashedScissors:zF,SquareChartGantt:x5,SquareCheck:BF,SquareCheckBig:Kj,SquareChevronDown:$F,SquareChevronLeft:UF,SquareChevronRight:qF,SquareChevronUp:VF,SquareCode:HF,SquareDashed:KF,SquareDashedBottom:nCe,SquareDashedBottomCode:sCe,SquareDashedKanban:GF,SquareDashedMousePointer:WF,SquareDivide:YF,SquareDot:ZF,SquareEqual:XF,SquareFunction:QF,SquareKanban:JF,SquareLibrary:eO,SquareM:tO,SquareMenu:sO,SquareMinus:nO,SquareMousePointer:rO,SquareParking:iO,SquareParkingOff:aO,SquarePen:_p,SquarePercent:oO,SquarePi:lO,SquarePilcrow:cO,SquarePlay:dO,SquarePlus:uO,SquarePower:hO,SquareRadical:rCe,SquareScissors:mO,SquareSigma:fO,SquareSlash:pO,SquareSplitHorizontal:gO,SquareSplitVertical:xO,SquareSquare:aCe,SquareStack:iCe,SquareTerminal:yO,SquareUser:bO,SquareUserRound:vO,SquareX:_O,Squircle:oCe,Squirrel:lCe,Stamp:cCe,Star:Ja,StarHalf:dCe,StarOff:uCe,StepBack:hCe,StepForward:mCe,Stethoscope:fCe,Sticker:pCe,StickyNote:r7,Store:oV,StretchHorizontal:gCe,StretchVertical:xCe,Strikethrough:ree,Subscript:yCe,Sun:rk,SunDim:vCe,SunMedium:bCe,SunMoon:_Ce,SunSnow:wCe,Sunrise:jCe,Sunset:NCe,Superscript:kCe,SwatchBook:SCe,SwissFranc:CCe,SwitchCamera:ACe,Sword:ECe,Swords:TCe,Syringe:MCe,Table:cV,Table2:lV,TableCellsMerge:PCe,TableCellsSplit:ICe,TableColumnsSplit:LCe,TableOfContents:RCe,TableProperties:DCe,TableRowsSplit:FCe,Tablet:dV,TabletSmartphone:OCe,Tablets:zCe,Tag:Ap,Tags:aee,Tally1:BCe,Tally2:$Ce,Tally3:UCe,Tally4:qCe,Tally5:VCe,Tangent:HCe,Target:rh,Telescope:GCe,Tent:KCe,TentTree:WCe,Terminal:YCe,TestTube:ZCe,TestTubeDiagonal:wO,TestTubes:XCe,Text:t5e,TextCursor:QCe,TextCursorInput:uV,TextQuote:JCe,TextSearch:e5e,TextSelect:jO,Theater:s5e,Thermometer:a5e,ThermometerSnowflake:n5e,ThermometerSun:r5e,ThumbsDown:iee,ThumbsUp:Vy,Ticket:a7,TicketCheck:i5e,TicketMinus:o5e,TicketPercent:l5e,TicketPlus:c5e,TicketSlash:d5e,TicketX:u5e,Tickets:m5e,TicketsPlane:h5e,Timer:g5e,TimerOff:f5e,TimerReset:p5e,ToggleLeft:x5e,ToggleRight:y5e,Toilet:v5e,Tornado:b5e,Torus:_5e,Touchpad:j5e,TouchpadOff:w5e,TowerControl:N5e,ToyBrick:k5e,Tractor:S5e,TrafficCone:C5e,TrainFront:E5e,TrainFrontTunnel:A5e,TrainTrack:T5e,TramFront:NO,Trash:M5e,Trash2:Wn,TreeDeciduous:P5e,TreePalm:kO,TreePine:sL,Trees:I5e,Trello:L5e,TrendingDown:rC,TrendingUp:Yl,TrendingUpDown:R5e,Triangle:F5e,TriangleAlert:wl,TriangleRight:D5e,Trophy:Kl,Truck:oee,Turtle:O5e,Tv:B5e,TvMinimal:SO,TvMinimalPlay:z5e,Twitch:$5e,Twitter:lee,Type:hV,TypeOutline:U5e,Umbrella:V5e,UmbrellaOff:q5e,Underline:i7,Undo:BE,Undo2:cee,UndoDot:H5e,UnfoldHorizontal:G5e,UnfoldVertical:W5e,Ungroup:K5e,University:CO,Unlink:$E,Unlink2:Y5e,Unplug:o7,Upload:ni,Usb:Z5e,User:sl,UserCheck:y2,UserCog:dee,UserMinus:mV,UserPen:X5e,UserPlus:sc,UserRound:cP,UserRoundCheck:lP,UserRoundCog:AO,UserRoundMinus:EO,UserRoundPen:Q5e,UserRoundPlus:TO,UserRoundSearch:fV,UserRoundX:MO,UserSearch:J5e,UserX:pV,Users:Zn,UsersRound:v0,Utensils:IO,UtensilsCrossed:PO,UtilityPole:e4e,Variable:gV,Vault:t4e,Vegan:s4e,VenetianMask:n4e,Vibrate:a4e,VibrateOff:r4e,Video:ua,VideoOff:i4e,Videotape:o4e,View:l4e,Voicemail:c4e,Volleyball:d4e,Volume:m4e,Volume1:u4e,Volume2:uee,VolumeOff:h4e,VolumeX:hee,Vote:f4e,Wallet:l7,WalletCards:p4e,WalletMinimal:LO,Wallpaper:g4e,Wand:x4e,WandSparkles:sy,Warehouse:y4e,WashingMachine:v4e,Watch:b4e,Waves:_4e,Waypoints:w4e,Webcam:j4e,Webhook:k4e,WebhookOff:N4e,Weight:S4e,Wheat:A4e,WheatOff:C4e,WholeWord:E4e,Wifi:L4e,WifiHigh:T4e,WifiLow:M4e,WifiOff:P4e,WifiZero:I4e,Wind:D4e,WindArrowDown:R4e,Wine:O4e,WineOff:F4e,Workflow:c7,Worm:z4e,WrapText:B4e,Wrench:F4,X:gr,Youtube:xV,Zap:eg,ZapOff:$4e,ZoomIn:nL,ZoomOut:yV},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 HIe=Object.freeze(Object.defineProperty({__proto__:null,AArrowDown:_me,AArrowDownIcon:_me,AArrowUp:wme,AArrowUpIcon:wme,ALargeSmall:jme,ALargeSmallIcon:jme,Accessibility:Nme,AccessibilityIcon:Nme,Activity:af,ActivityIcon:af,ActivitySquare:kF,ActivitySquareIcon:kF,AirVent:kme,AirVentIcon:kme,Airplay:Sme,AirplayIcon:Sme,AlarmCheck:DR,AlarmCheckIcon:DR,AlarmClock:Ame,AlarmClockCheck:DR,AlarmClockCheckIcon:DR,AlarmClockIcon:Ame,AlarmClockMinus:FR,AlarmClockMinusIcon:FR,AlarmClockOff:Cme,AlarmClockOffIcon:Cme,AlarmClockPlus:OR,AlarmClockPlusIcon:OR,AlarmMinus:FR,AlarmMinusIcon:FR,AlarmPlus:OR,AlarmPlusIcon:OR,AlarmSmoke:Eme,AlarmSmokeIcon:Eme,Album:Tme,AlbumIcon:Tme,AlertCircle:ll,AlertCircleIcon:ll,AlertOctagon:BS,AlertOctagonIcon:BS,AlertTriangle:wl,AlertTriangleIcon:wl,AlignCenter:zI,AlignCenterHorizontal:Mme,AlignCenterHorizontalIcon:Mme,AlignCenterIcon:zI,AlignCenterVertical:Pme,AlignCenterVerticalIcon:Pme,AlignEndHorizontal:Ime,AlignEndHorizontalIcon:Ime,AlignEndVertical:Lme,AlignEndVerticalIcon:Lme,AlignHorizontalDistributeCenter:Rme,AlignHorizontalDistributeCenterIcon:Rme,AlignHorizontalDistributeEnd:Dme,AlignHorizontalDistributeEndIcon:Dme,AlignHorizontalDistributeStart:Fme,AlignHorizontalDistributeStartIcon:Fme,AlignHorizontalJustifyCenter:Ome,AlignHorizontalJustifyCenterIcon:Ome,AlignHorizontalJustifyEnd:zme,AlignHorizontalJustifyEndIcon:zme,AlignHorizontalJustifyStart:Bme,AlignHorizontalJustifyStartIcon:Bme,AlignHorizontalSpaceAround:$me,AlignHorizontalSpaceAroundIcon:$me,AlignHorizontalSpaceBetween:Ume,AlignHorizontalSpaceBetweenIcon:Ume,AlignJustify:qme,AlignJustifyIcon:qme,AlignLeft:BI,AlignLeftIcon:BI,AlignRight:$I,AlignRightIcon:$I,AlignStartHorizontal:Vme,AlignStartHorizontalIcon:Vme,AlignStartVertical:Hme,AlignStartVerticalIcon:Hme,AlignVerticalDistributeCenter:Gme,AlignVerticalDistributeCenterIcon:Gme,AlignVerticalDistributeEnd:Wme,AlignVerticalDistributeEndIcon:Wme,AlignVerticalDistributeStart:Kme,AlignVerticalDistributeStartIcon:Kme,AlignVerticalJustifyCenter:Yme,AlignVerticalJustifyCenterIcon:Yme,AlignVerticalJustifyEnd:Zme,AlignVerticalJustifyEndIcon:Zme,AlignVerticalJustifyStart:Xme,AlignVerticalJustifyStartIcon:Xme,AlignVerticalSpaceAround:Qme,AlignVerticalSpaceAroundIcon:Qme,AlignVerticalSpaceBetween:Jme,AlignVerticalSpaceBetweenIcon:Jme,Ambulance:efe,AmbulanceIcon:efe,Ampersand:tfe,AmpersandIcon:tfe,Ampersands:sfe,AmpersandsIcon:sfe,Amphora:nfe,AmphoraIcon:nfe,Anchor:rfe,AnchorIcon:rfe,Angry:afe,AngryIcon:afe,Annoyed:ife,AnnoyedIcon:ife,Antenna:ofe,AntennaIcon:ofe,Anvil:lfe,AnvilIcon:lfe,Aperture:cfe,ApertureIcon:cfe,AppWindow:ufe,AppWindowIcon:ufe,AppWindowMac:dfe,AppWindowMacIcon:dfe,Apple:hfe,AppleIcon:hfe,Archive:Sv,ArchiveIcon:Sv,ArchiveRestore:UI,ArchiveRestoreIcon:UI,ArchiveX:mfe,ArchiveXIcon:mfe,AreaChart:ZR,AreaChartIcon:ZR,Armchair:ffe,ArmchairIcon:ffe,ArrowBigDown:gfe,ArrowBigDownDash:pfe,ArrowBigDownDashIcon:pfe,ArrowBigDownIcon:gfe,ArrowBigLeft:yfe,ArrowBigLeftDash:xfe,ArrowBigLeftDashIcon:xfe,ArrowBigLeftIcon:yfe,ArrowBigRight:bfe,ArrowBigRightDash:vfe,ArrowBigRightDashIcon:vfe,ArrowBigRightIcon:bfe,ArrowBigUp:wfe,ArrowBigUpDash:_fe,ArrowBigUpDashIcon:_fe,ArrowBigUpIcon:wfe,ArrowDown:Dg,ArrowDown01:jfe,ArrowDown01Icon:jfe,ArrowDown10:Nfe,ArrowDown10Icon:Nfe,ArrowDownAZ:zR,ArrowDownAZIcon:zR,ArrowDownAz:zR,ArrowDownAzIcon:zR,ArrowDownCircle:lD,ArrowDownCircleIcon:lD,ArrowDownFromLine:kfe,ArrowDownFromLineIcon:kfe,ArrowDownIcon:Dg,ArrowDownLeft:Sfe,ArrowDownLeftFromCircle:dD,ArrowDownLeftFromCircleIcon:dD,ArrowDownLeftFromSquare:TF,ArrowDownLeftFromSquareIcon:TF,ArrowDownLeftIcon:Sfe,ArrowDownLeftSquare:SF,ArrowDownLeftSquareIcon:SF,ArrowDownNarrowWide:Cfe,ArrowDownNarrowWideIcon:Cfe,ArrowDownRight:pJ,ArrowDownRightFromCircle:uD,ArrowDownRightFromCircleIcon:uD,ArrowDownRightFromSquare:MF,ArrowDownRightFromSquareIcon:MF,ArrowDownRightIcon:pJ,ArrowDownRightSquare:CF,ArrowDownRightSquareIcon:CF,ArrowDownSquare:AF,ArrowDownSquareIcon:AF,ArrowDownToDot:Afe,ArrowDownToDotIcon:Afe,ArrowDownToLine:Efe,ArrowDownToLineIcon:Efe,ArrowDownUp:Tfe,ArrowDownUpIcon:Tfe,ArrowDownWideNarrow:BR,ArrowDownWideNarrowIcon:BR,ArrowDownZA:$R,ArrowDownZAIcon:$R,ArrowDownZa:$R,ArrowDownZaIcon:$R,ArrowLeft:qa,ArrowLeftCircle:cD,ArrowLeftCircleIcon:cD,ArrowLeftFromLine:Mfe,ArrowLeftFromLineIcon:Mfe,ArrowLeftIcon:qa,ArrowLeftRight:gJ,ArrowLeftRightIcon:gJ,ArrowLeftSquare:EF,ArrowLeftSquareIcon:EF,ArrowLeftToLine:Pfe,ArrowLeftToLineIcon:Pfe,ArrowRight:ei,ArrowRightCircle:fD,ArrowRightCircleIcon:fD,ArrowRightFromLine:Ife,ArrowRightFromLineIcon:Ife,ArrowRightIcon:ei,ArrowRightLeft:E4,ArrowRightLeftIcon:E4,ArrowRightSquare:LF,ArrowRightSquareIcon:LF,ArrowRightToLine:Lfe,ArrowRightToLineIcon:Lfe,ArrowUp:Zf,ArrowUp01:Rfe,ArrowUp01Icon:Rfe,ArrowUp10:Dfe,ArrowUp10Icon:Dfe,ArrowUpAZ:UR,ArrowUpAZIcon:UR,ArrowUpAz:UR,ArrowUpAzIcon:UR,ArrowUpCircle:pD,ArrowUpCircleIcon:pD,ArrowUpDown:By,ArrowUpDownIcon:By,ArrowUpFromDot:Ffe,ArrowUpFromDotIcon:Ffe,ArrowUpFromLine:Ofe,ArrowUpFromLineIcon:Ofe,ArrowUpIcon:Zf,ArrowUpLeft:zfe,ArrowUpLeftFromCircle:hD,ArrowUpLeftFromCircleIcon:hD,ArrowUpLeftFromSquare:PF,ArrowUpLeftFromSquareIcon:PF,ArrowUpLeftIcon:zfe,ArrowUpLeftSquare:RF,ArrowUpLeftSquareIcon:RF,ArrowUpNarrowWide:qR,ArrowUpNarrowWideIcon:qR,ArrowUpRight:Oz,ArrowUpRightFromCircle:mD,ArrowUpRightFromCircleIcon:mD,ArrowUpRightFromSquare:IF,ArrowUpRightFromSquareIcon:IF,ArrowUpRightIcon:Oz,ArrowUpRightSquare:DF,ArrowUpRightSquareIcon:DF,ArrowUpSquare:FF,ArrowUpSquareIcon:FF,ArrowUpToLine:Bfe,ArrowUpToLineIcon:Bfe,ArrowUpWideNarrow:$fe,ArrowUpWideNarrowIcon:$fe,ArrowUpZA:VR,ArrowUpZAIcon:VR,ArrowUpZa:VR,ArrowUpZaIcon:VR,ArrowsUpFromLine:Ufe,ArrowsUpFromLineIcon:Ufe,Asterisk:qfe,AsteriskIcon:qfe,AsteriskSquare:OF,AsteriskSquareIcon:OF,AtSign:Vfe,AtSignIcon:Vfe,Atom:Hfe,AtomIcon:Hfe,AudioLines:Gfe,AudioLinesIcon:Gfe,AudioWaveform:Wfe,AudioWaveformIcon:Wfe,Award:Rm,AwardIcon:Rm,Axe:Kfe,AxeIcon:Kfe,Axis3D:HR,Axis3DIcon:HR,Axis3d:HR,Axis3dIcon:HR,Baby:Yfe,BabyIcon:Yfe,Backpack:Zfe,BackpackIcon:Zfe,Badge:hpe,BadgeAlert:Xfe,BadgeAlertIcon:Xfe,BadgeCent:Qfe,BadgeCentIcon:Qfe,BadgeCheck:RA,BadgeCheckIcon:RA,BadgeDollarSign:Jfe,BadgeDollarSignIcon:Jfe,BadgeEuro:epe,BadgeEuroIcon:epe,BadgeHelp:tpe,BadgeHelpIcon:tpe,BadgeIcon:hpe,BadgeIndianRupee:spe,BadgeIndianRupeeIcon:spe,BadgeInfo:npe,BadgeInfoIcon:npe,BadgeJapaneseYen:rpe,BadgeJapaneseYenIcon:rpe,BadgeMinus:ape,BadgeMinusIcon:ape,BadgePercent:ipe,BadgePercentIcon:ipe,BadgePlus:ope,BadgePlusIcon:ope,BadgePoundSterling:lpe,BadgePoundSterlingIcon:lpe,BadgeRussianRuble:cpe,BadgeRussianRubleIcon:cpe,BadgeSwissFranc:dpe,BadgeSwissFrancIcon:dpe,BadgeX:upe,BadgeXIcon:upe,BaggageClaim:mpe,BaggageClaimIcon:mpe,Ban:zz,BanIcon:zz,Banana:fpe,BananaIcon:fpe,Bandage:ppe,BandageIcon:ppe,Banknote:gpe,BanknoteIcon:gpe,BarChart:nD,BarChart2:rD,BarChart2Icon:rD,BarChart3:Wl,BarChart3Icon:Wl,BarChart4:tD,BarChart4Icon:tD,BarChartBig:eD,BarChartBigIcon:eD,BarChartHorizontal:QR,BarChartHorizontalBig:XR,BarChartHorizontalBigIcon:XR,BarChartHorizontalIcon:QR,BarChartIcon:nD,Barcode:xpe,BarcodeIcon:xpe,Baseline:ype,BaselineIcon:ype,Bath:T0,BathIcon:T0,Battery:Npe,BatteryCharging:vpe,BatteryChargingIcon:vpe,BatteryFull:bpe,BatteryFullIcon:bpe,BatteryIcon:Npe,BatteryLow:_pe,BatteryLowIcon:_pe,BatteryMedium:wpe,BatteryMediumIcon:wpe,BatteryWarning:jpe,BatteryWarningIcon:jpe,Beaker:xJ,BeakerIcon:xJ,Bean:Spe,BeanIcon:Spe,BeanOff:kpe,BeanOffIcon:kpe,Bed:l2,BedDouble:T4,BedDoubleIcon:T4,BedIcon:l2,BedSingle:Cpe,BedSingleIcon:Cpe,Beef:Ape,BeefIcon:Ape,Beer:Tpe,BeerIcon:Tpe,BeerOff:Epe,BeerOffIcon:Epe,Bell:qy,BellDot:Mpe,BellDotIcon:Mpe,BellElectric:Ppe,BellElectricIcon:Ppe,BellIcon:qy,BellMinus:Ipe,BellMinusIcon:Ipe,BellOff:XS,BellOffIcon:XS,BellPlus:Lpe,BellPlusIcon:Lpe,BellRing:QS,BellRingIcon:QS,BetweenHorizonalEnd:GR,BetweenHorizonalEndIcon:GR,BetweenHorizonalStart:WR,BetweenHorizonalStartIcon:WR,BetweenHorizontalEnd:GR,BetweenHorizontalEndIcon:GR,BetweenHorizontalStart:WR,BetweenHorizontalStartIcon:WR,BetweenVerticalEnd:Rpe,BetweenVerticalEndIcon:Rpe,BetweenVerticalStart:Dpe,BetweenVerticalStartIcon:Dpe,BicepsFlexed:Fpe,BicepsFlexedIcon:Fpe,Bike:Ope,BikeIcon:Ope,Binary:zpe,BinaryIcon:zpe,Binoculars:Bpe,BinocularsIcon:Bpe,Biohazard:$pe,BiohazardIcon:$pe,Bird:Upe,BirdIcon:Upe,Bitcoin:qpe,BitcoinIcon:qpe,Blend:Vpe,BlendIcon:Vpe,Blinds:Hpe,BlindsIcon:Hpe,Blocks:Gpe,BlocksIcon:Gpe,Bluetooth:Zpe,BluetoothConnected:Wpe,BluetoothConnectedIcon:Wpe,BluetoothIcon:Zpe,BluetoothOff:Kpe,BluetoothOffIcon:Kpe,BluetoothSearching:Ype,BluetoothSearchingIcon:Ype,Bold:AE,BoldIcon:AE,Bolt:Xpe,BoltIcon:Xpe,Bomb:Qpe,BombIcon:Qpe,Bone:Jpe,BoneIcon:Jpe,Book:_ge,BookA:ege,BookAIcon:ege,BookAudio:tge,BookAudioIcon:tge,BookCheck:sge,BookCheckIcon:sge,BookCopy:nge,BookCopyIcon:nge,BookDashed:KR,BookDashedIcon:KR,BookDown:rge,BookDownIcon:rge,BookHeadphones:age,BookHeadphonesIcon:age,BookHeart:ige,BookHeartIcon:ige,BookIcon:_ge,BookImage:oge,BookImageIcon:oge,BookKey:lge,BookKeyIcon:lge,BookLock:cge,BookLockIcon:cge,BookMarked:dge,BookMarkedIcon:dge,BookMinus:uge,BookMinusIcon:uge,BookOpen:Xf,BookOpenCheck:hge,BookOpenCheckIcon:hge,BookOpenIcon:Xf,BookOpenText:mge,BookOpenTextIcon:mge,BookPlus:fge,BookPlusIcon:fge,BookTemplate:KR,BookTemplateIcon:KR,BookText:pge,BookTextIcon:pge,BookType:gge,BookTypeIcon:gge,BookUp:yge,BookUp2:xge,BookUp2Icon:xge,BookUpIcon:yge,BookUser:vge,BookUserIcon:vge,BookX:bge,BookXIcon:bge,Bookmark:M0,BookmarkCheck:wge,BookmarkCheckIcon:wge,BookmarkIcon:M0,BookmarkMinus:jge,BookmarkMinusIcon:jge,BookmarkPlus:qI,BookmarkPlusIcon:qI,BookmarkX:Nge,BookmarkXIcon:Nge,BoomBox:kge,BoomBoxIcon:kge,Bot:M4,BotIcon:M4,BotMessageSquare:Sge,BotMessageSquareIcon:Sge,BotOff:Cge,BotOffIcon:Cge,Box:yJ,BoxIcon:yJ,BoxSelect:KF,BoxSelectIcon:KF,Boxes:Age,BoxesIcon:Age,Braces:aP,BracesIcon:aP,Brackets:Ege,BracketsIcon:Ege,Brain:vJ,BrainCircuit:Tge,BrainCircuitIcon:Tge,BrainCog:Mge,BrainCogIcon:Mge,BrainIcon:vJ,BrickWall:Pge,BrickWallIcon:Pge,Briefcase:Sx,BriefcaseBusiness:Ige,BriefcaseBusinessIcon:Ige,BriefcaseConveyorBelt:Lge,BriefcaseConveyorBeltIcon:Lge,BriefcaseIcon:Sx,BriefcaseMedical:Rge,BriefcaseMedicalIcon:Rge,BringToFront:Dge,BringToFrontIcon:Dge,Brush:Fge,BrushIcon:Fge,Bug:Bge,BugIcon:Bge,BugOff:Oge,BugOffIcon:Oge,BugPlay:zge,BugPlayIcon:zge,Building:VI,Building2:ji,Building2Icon:ji,BuildingIcon:VI,Bus:Uge,BusFront:$ge,BusFrontIcon:$ge,BusIcon:Uge,Cable:Vge,CableCar:qge,CableCarIcon:qge,CableIcon:Vge,Cake:Fg,CakeIcon:Fg,CakeSlice:Hge,CakeSliceIcon:Hge,Calculator:c2,CalculatorIcon:c2,Calendar:Ta,Calendar1:Gge,Calendar1Icon:Gge,CalendarArrowDown:Wge,CalendarArrowDownIcon:Wge,CalendarArrowUp:Kge,CalendarArrowUpIcon:Kge,CalendarCheck:bb,CalendarCheck2:Yge,CalendarCheck2Icon:Yge,CalendarCheckIcon:bb,CalendarClock:Au,CalendarClockIcon:Au,CalendarCog:Zge,CalendarCogIcon:Zge,CalendarDays:Kc,CalendarDaysIcon:Kc,CalendarFold:Xge,CalendarFoldIcon:Xge,CalendarHeart:JS,CalendarHeartIcon:JS,CalendarIcon:Ta,CalendarMinus:Jge,CalendarMinus2:Qge,CalendarMinus2Icon:Qge,CalendarMinusIcon:Jge,CalendarOff:Tq,CalendarOffIcon:Tq,CalendarPlus:jv,CalendarPlus2:exe,CalendarPlus2Icon:exe,CalendarPlusIcon:jv,CalendarRange:txe,CalendarRangeIcon:txe,CalendarSearch:sxe,CalendarSearchIcon:sxe,CalendarSync:nxe,CalendarSyncIcon:nxe,CalendarX:bJ,CalendarX2:rxe,CalendarX2Icon:rxe,CalendarXIcon:bJ,Camera:Cx,CameraIcon:Cx,CameraOff:axe,CameraOffIcon:axe,CandlestickChart:JR,CandlestickChartIcon:JR,Candy:lxe,CandyCane:ixe,CandyCaneIcon:ixe,CandyIcon:lxe,CandyOff:oxe,CandyOffIcon:oxe,Cannabis:cxe,CannabisIcon:cxe,Captions:YR,CaptionsIcon:YR,CaptionsOff:dxe,CaptionsOffIcon:dxe,Car:mxe,CarFront:uxe,CarFrontIcon:uxe,CarIcon:mxe,CarTaxiFront:hxe,CarTaxiFrontIcon:hxe,Caravan:fxe,CaravanIcon:fxe,Carrot:pxe,CarrotIcon:pxe,CaseLower:gxe,CaseLowerIcon:gxe,CaseSensitive:xxe,CaseSensitiveIcon:xxe,CaseUpper:yxe,CaseUpperIcon:yxe,CassetteTape:vxe,CassetteTapeIcon:vxe,Cast:bxe,CastIcon:bxe,Castle:_xe,CastleIcon:_xe,Cat:wxe,CatIcon:wxe,Cctv:jxe,CctvIcon:jxe,ChartArea:ZR,ChartAreaIcon:ZR,ChartBar:QR,ChartBarBig:XR,ChartBarBigIcon:XR,ChartBarDecreasing:Nxe,ChartBarDecreasingIcon:Nxe,ChartBarIcon:QR,ChartBarIncreasing:kxe,ChartBarIncreasingIcon:kxe,ChartBarStacked:Sxe,ChartBarStackedIcon:Sxe,ChartCandlestick:JR,ChartCandlestickIcon:JR,ChartColumn:Wl,ChartColumnBig:eD,ChartColumnBigIcon:eD,ChartColumnDecreasing:Cxe,ChartColumnDecreasingIcon:Cxe,ChartColumnIcon:Wl,ChartColumnIncreasing:tD,ChartColumnIncreasingIcon:tD,ChartColumnStacked:Axe,ChartColumnStackedIcon:Axe,ChartGantt:Exe,ChartGanttIcon:Exe,ChartLine:sD,ChartLineIcon:sD,ChartNetwork:Txe,ChartNetworkIcon:Txe,ChartNoAxesColumn:rD,ChartNoAxesColumnDecreasing:Mxe,ChartNoAxesColumnDecreasingIcon:Mxe,ChartNoAxesColumnIcon:rD,ChartNoAxesColumnIncreasing:nD,ChartNoAxesColumnIncreasingIcon:nD,ChartNoAxesCombined:Pxe,ChartNoAxesCombinedIcon:Pxe,ChartNoAxesGantt:aD,ChartNoAxesGanttIcon:aD,ChartPie:iD,ChartPieIcon:iD,ChartScatter:oD,ChartScatterIcon:oD,ChartSpline:Ixe,ChartSplineIcon:Ixe,Check:la,CheckCheck:Bz,CheckCheckIcon:Bz,CheckCircle:Nc,CheckCircle2:qr,CheckCircle2Icon:qr,CheckCircleIcon:Nc,CheckIcon:la,CheckSquare:Kj,CheckSquare2:BF,CheckSquare2Icon:BF,CheckSquareIcon:Kj,ChefHat:Lxe,ChefHatIcon:Lxe,Cherry:Rxe,CherryIcon:Rxe,ChevronDown:Tl,ChevronDownCircle:gD,ChevronDownCircleIcon:gD,ChevronDownIcon:Tl,ChevronDownSquare:$F,ChevronDownSquareIcon:$F,ChevronFirst:Dxe,ChevronFirstIcon:Dxe,ChevronLast:Fxe,ChevronLastIcon:Fxe,ChevronLeft:Cd,ChevronLeftCircle:xD,ChevronLeftCircleIcon:xD,ChevronLeftIcon:Cd,ChevronLeftSquare:UF,ChevronLeftSquareIcon:UF,ChevronRight:Di,ChevronRightCircle:yD,ChevronRightCircleIcon:yD,ChevronRightIcon:Di,ChevronRightSquare:qF,ChevronRightSquareIcon:qF,ChevronUp:v1,ChevronUpCircle:vD,ChevronUpCircleIcon:vD,ChevronUpIcon:v1,ChevronUpSquare:VF,ChevronUpSquareIcon:VF,ChevronsDown:zxe,ChevronsDownIcon:zxe,ChevronsDownUp:Oxe,ChevronsDownUpIcon:Oxe,ChevronsLeft:Uxe,ChevronsLeftIcon:Uxe,ChevronsLeftRight:$xe,ChevronsLeftRightEllipsis:Bxe,ChevronsLeftRightEllipsisIcon:Bxe,ChevronsLeftRightIcon:$xe,ChevronsRight:Vxe,ChevronsRightIcon:Vxe,ChevronsRightLeft:qxe,ChevronsRightLeftIcon:qxe,ChevronsUp:Hxe,ChevronsUpDown:Pw,ChevronsUpDownIcon:Pw,ChevronsUpIcon:Hxe,Chrome:$z,ChromeIcon:$z,Church:Gxe,ChurchIcon:Gxe,Cigarette:Kxe,CigaretteIcon:Kxe,CigaretteOff:Wxe,CigaretteOffIcon:Wxe,Circle:Og,CircleAlert:ll,CircleAlertIcon:ll,CircleArrowDown:lD,CircleArrowDownIcon:lD,CircleArrowLeft:cD,CircleArrowLeftIcon:cD,CircleArrowOutDownLeft:dD,CircleArrowOutDownLeftIcon:dD,CircleArrowOutDownRight:uD,CircleArrowOutDownRightIcon:uD,CircleArrowOutUpLeft:hD,CircleArrowOutUpLeftIcon:hD,CircleArrowOutUpRight:mD,CircleArrowOutUpRightIcon:mD,CircleArrowRight:fD,CircleArrowRightIcon:fD,CircleArrowUp:pD,CircleArrowUpIcon:pD,CircleCheck:qr,CircleCheckBig:Nc,CircleCheckBigIcon:Nc,CircleCheckIcon:qr,CircleChevronDown:gD,CircleChevronDownIcon:gD,CircleChevronLeft:xD,CircleChevronLeftIcon:xD,CircleChevronRight:yD,CircleChevronRightIcon:yD,CircleChevronUp:vD,CircleChevronUpIcon:vD,CircleDashed:Yxe,CircleDashedIcon:Yxe,CircleDivide:bD,CircleDivideIcon:bD,CircleDollarSign:Zxe,CircleDollarSignIcon:Zxe,CircleDot:Qxe,CircleDotDashed:Xxe,CircleDotDashedIcon:Xxe,CircleDotIcon:Qxe,CircleEllipsis:Jxe,CircleEllipsisIcon:Jxe,CircleEqual:eye,CircleEqualIcon:eye,CircleFadingArrowUp:tye,CircleFadingArrowUpIcon:tye,CircleFadingPlus:sye,CircleFadingPlusIcon:sye,CircleGauge:_D,CircleGaugeIcon:_D,CircleHelp:s4,CircleHelpIcon:s4,CircleIcon:Og,CircleMinus:wD,CircleMinusIcon:wD,CircleOff:nye,CircleOffIcon:nye,CircleParking:ND,CircleParkingIcon:ND,CircleParkingOff:jD,CircleParkingOffIcon:jD,CirclePause:kD,CirclePauseIcon:kD,CirclePercent:SD,CirclePercentIcon:SD,CirclePlay:tf,CirclePlayIcon:tf,CirclePlus:CD,CirclePlusIcon:CD,CirclePower:AD,CirclePowerIcon:AD,CircleSlash:rye,CircleSlash2:ED,CircleSlash2Icon:ED,CircleSlashIcon:rye,CircleSlashed:ED,CircleSlashedIcon:ED,CircleStop:TD,CircleStopIcon:TD,CircleUser:PD,CircleUserIcon:PD,CircleUserRound:MD,CircleUserRoundIcon:MD,CircleX:ku,CircleXIcon:ku,CircuitBoard:aye,CircuitBoardIcon:aye,Citrus:iye,CitrusIcon:iye,Clapperboard:Mq,ClapperboardIcon:Mq,Clipboard:mye,ClipboardCheck:JN,ClipboardCheckIcon:JN,ClipboardCopy:oye,ClipboardCopyIcon:oye,ClipboardEdit:LD,ClipboardEditIcon:LD,ClipboardIcon:mye,ClipboardList:zg,ClipboardListIcon:zg,ClipboardMinus:lye,ClipboardMinusIcon:lye,ClipboardPaste:cye,ClipboardPasteIcon:cye,ClipboardPen:LD,ClipboardPenIcon:LD,ClipboardPenLine:ID,ClipboardPenLineIcon:ID,ClipboardPlus:dye,ClipboardPlusIcon:dye,ClipboardSignature:ID,ClipboardSignatureIcon:ID,ClipboardType:uye,ClipboardTypeIcon:uye,ClipboardX:hye,ClipboardXIcon:hye,Clock:da,Clock1:fye,Clock10:pye,Clock10Icon:pye,Clock11:gye,Clock11Icon:gye,Clock12:xye,Clock12Icon:xye,Clock1Icon:fye,Clock2:yye,Clock2Icon:yye,Clock3:Pq,Clock3Icon:Pq,Clock4:vye,Clock4Icon:vye,Clock5:bye,Clock5Icon:bye,Clock6:_ye,Clock6Icon:_ye,Clock7:wye,Clock7Icon:wye,Clock8:jye,Clock8Icon:jye,Clock9:Nye,Clock9Icon:Nye,ClockAlert:kye,ClockAlertIcon:kye,ClockArrowDown:Sye,ClockArrowDownIcon:Sye,ClockArrowUp:Cye,ClockArrowUpIcon:Cye,ClockIcon:da,Cloud:Uye,CloudAlert:Aye,CloudAlertIcon:Aye,CloudCog:Eye,CloudCogIcon:Eye,CloudDownload:RD,CloudDownloadIcon:RD,CloudDrizzle:Tye,CloudDrizzleIcon:Tye,CloudFog:Mye,CloudFogIcon:Mye,CloudHail:Pye,CloudHailIcon:Pye,CloudIcon:Uye,CloudLightning:Iye,CloudLightningIcon:Iye,CloudMoon:Rye,CloudMoonIcon:Rye,CloudMoonRain:Lye,CloudMoonRainIcon:Lye,CloudOff:Dye,CloudOffIcon:Dye,CloudRain:Oye,CloudRainIcon:Oye,CloudRainWind:Fye,CloudRainWindIcon:Fye,CloudSnow:zye,CloudSnowIcon:zye,CloudSun:$ye,CloudSunIcon:$ye,CloudSunRain:Bye,CloudSunRainIcon:Bye,CloudUpload:iP,CloudUploadIcon:iP,Cloudy:qye,CloudyIcon:qye,Clover:yE,CloverIcon:yE,Club:Vye,ClubIcon:Vye,Code:EE,Code2:n4,Code2Icon:n4,CodeIcon:EE,CodeSquare:HF,CodeSquareIcon:HF,CodeXml:n4,CodeXmlIcon:n4,Codepen:Hye,CodepenIcon:Hye,Codesandbox:Gye,CodesandboxIcon:Gye,Coffee:P4,CoffeeIcon:P4,Cog:Wye,CogIcon:Wye,Coins:_J,CoinsIcon:_J,Columns:DD,Columns2:DD,Columns2Icon:DD,Columns3:oP,Columns3Icon:oP,Columns4:Kye,Columns4Icon:Kye,ColumnsIcon:DD,Combine:Yye,CombineIcon:Yye,Command:Zye,CommandIcon:Zye,Compass:Uz,CompassIcon:Uz,Component:Xye,ComponentIcon:Xye,Computer:Qye,ComputerIcon:Qye,ConciergeBell:Jye,ConciergeBellIcon:Jye,Cone:e0e,ConeIcon:e0e,Construction:t0e,ConstructionIcon:t0e,Contact:HI,Contact2:FD,Contact2Icon:FD,ContactIcon:HI,ContactRound:FD,ContactRoundIcon:FD,Container:s0e,ContainerIcon:s0e,Contrast:n0e,ContrastIcon:n0e,Cookie:r0e,CookieIcon:r0e,CookingPot:a0e,CookingPotIcon:a0e,Copy:Ha,CopyCheck:i0e,CopyCheckIcon:i0e,CopyIcon:Ha,CopyMinus:o0e,CopyMinusIcon:o0e,CopyPlus:l0e,CopyPlusIcon:l0e,CopySlash:c0e,CopySlashIcon:c0e,CopyX:d0e,CopyXIcon:d0e,Copyleft:u0e,CopyleftIcon:u0e,Copyright:h0e,CopyrightIcon:h0e,CornerDownLeft:m0e,CornerDownLeftIcon:m0e,CornerDownRight:wJ,CornerDownRightIcon:wJ,CornerLeftDown:f0e,CornerLeftDownIcon:f0e,CornerLeftUp:p0e,CornerLeftUpIcon:p0e,CornerRightDown:g0e,CornerRightDownIcon:g0e,CornerRightUp:x0e,CornerRightUpIcon:x0e,CornerUpLeft:y0e,CornerUpLeftIcon:y0e,CornerUpRight:v0e,CornerUpRightIcon:v0e,Cpu:b0e,CpuIcon:b0e,CreativeCommons:_0e,CreativeCommonsIcon:_0e,CreditCard:Cv,CreditCardIcon:Cv,Croissant:w0e,CroissantIcon:w0e,Crop:j0e,CropIcon:j0e,Cross:N0e,CrossIcon:N0e,Crosshair:k0e,CrosshairIcon:k0e,Crown:Bg,CrownIcon:Bg,Cuboid:S0e,CuboidIcon:S0e,CupSoda:C0e,CupSodaIcon:C0e,CurlyBraces:aP,CurlyBracesIcon:aP,Currency:A0e,CurrencyIcon:A0e,Cylinder:E0e,CylinderIcon:E0e,Dam:T0e,DamIcon:T0e,Database:Iq,DatabaseBackup:M0e,DatabaseBackupIcon:M0e,DatabaseIcon:Iq,DatabaseZap:P0e,DatabaseZapIcon:P0e,Delete:I0e,DeleteIcon:I0e,Dessert:L0e,DessertIcon:L0e,Diameter:R0e,DiameterIcon:R0e,Diamond:O0e,DiamondIcon:O0e,DiamondMinus:D0e,DiamondMinusIcon:D0e,DiamondPercent:OD,DiamondPercentIcon:OD,DiamondPlus:F0e,DiamondPlusIcon:F0e,Dice1:z0e,Dice1Icon:z0e,Dice2:B0e,Dice2Icon:B0e,Dice3:$0e,Dice3Icon:$0e,Dice4:U0e,Dice4Icon:U0e,Dice5:q0e,Dice5Icon:q0e,Dice6:V0e,Dice6Icon:V0e,Dices:H0e,DicesIcon:H0e,Diff:G0e,DiffIcon:G0e,Disc:Z0e,Disc2:W0e,Disc2Icon:W0e,Disc3:K0e,Disc3Icon:K0e,DiscAlbum:Y0e,DiscAlbumIcon:Y0e,DiscIcon:Z0e,Divide:X0e,DivideCircle:bD,DivideCircleIcon:bD,DivideIcon:X0e,DivideSquare:YF,DivideSquareIcon:YF,Dna:J0e,DnaIcon:J0e,DnaOff:Q0e,DnaOffIcon:Q0e,Dock:eve,DockIcon:eve,Dog:tve,DogIcon:tve,DollarSign:ru,DollarSignIcon:ru,Donut:sve,DonutIcon:sve,DoorClosed:nve,DoorClosedIcon:nve,DoorOpen:d2,DoorOpenIcon:d2,Dot:rve,DotIcon:rve,DotSquare:ZF,DotSquareIcon:ZF,Download:di,DownloadCloud:RD,DownloadCloudIcon:RD,DownloadIcon:di,DraftingCompass:ave,DraftingCompassIcon:ave,Drama:ive,DramaIcon:ive,Dribbble:ove,DribbbleIcon:ove,Drill:lve,DrillIcon:lve,Droplet:cve,DropletIcon:cve,Droplets:b1,DropletsIcon:b1,Drum:dve,DrumIcon:dve,Drumstick:uve,DrumstickIcon:uve,Dumbbell:hve,DumbbellIcon:hve,Ear:fve,EarIcon:fve,EarOff:mve,EarOffIcon:mve,Earth:IN,EarthIcon:IN,EarthLock:pve,EarthLockIcon:pve,Eclipse:gve,EclipseIcon:gve,Edit:_p,Edit2:LN,Edit2Icon:LN,Edit3:wf,Edit3Icon:wf,EditIcon:_p,Egg:Lq,EggFried:xve,EggFriedIcon:xve,EggIcon:Lq,EggOff:yve,EggOffIcon:yve,Ellipsis:h_,EllipsisIcon:h_,EllipsisVertical:ty,EllipsisVerticalIcon:ty,Equal:_ve,EqualApproximately:vve,EqualApproximatelyIcon:vve,EqualIcon:_ve,EqualNot:bve,EqualNotIcon:bve,EqualSquare:XF,EqualSquareIcon:XF,Eraser:Rq,EraserIcon:Rq,EthernetPort:wve,EthernetPortIcon:wve,Euro:jve,EuroIcon:jve,Expand:Nve,ExpandIcon:Nve,ExternalLink:kr,ExternalLinkIcon:kr,Eye:Ca,EyeClosed:kve,EyeClosedIcon:kve,EyeIcon:Ca,EyeOff:$g,EyeOffIcon:$g,Facebook:Qp,FacebookIcon:Qp,Factory:Sve,FactoryIcon:Sve,Fan:Cve,FanIcon:Cve,FastForward:Ave,FastForwardIcon:Ave,Feather:Eve,FeatherIcon:Eve,Fence:Tve,FenceIcon:Tve,FerrisWheel:Mve,FerrisWheelIcon:Mve,Figma:Pve,FigmaIcon:Pve,File:Fq,FileArchive:Ive,FileArchiveIcon:Ive,FileAudio:Rve,FileAudio2:Lve,FileAudio2Icon:Lve,FileAudioIcon:Rve,FileAxis3D:zD,FileAxis3DIcon:zD,FileAxis3d:zD,FileAxis3dIcon:zD,FileBadge:Fve,FileBadge2:Dve,FileBadge2Icon:Dve,FileBadgeIcon:Fve,FileBarChart:BD,FileBarChart2:$D,FileBarChart2Icon:$D,FileBarChartIcon:BD,FileBox:Ove,FileBoxIcon:Ove,FileChartColumn:$D,FileChartColumnIcon:$D,FileChartColumnIncreasing:BD,FileChartColumnIncreasingIcon:BD,FileChartLine:UD,FileChartLineIcon:UD,FileChartPie:qD,FileChartPieIcon:qD,FileCheck:jJ,FileCheck2:qz,FileCheck2Icon:qz,FileCheckIcon:jJ,FileClock:zve,FileClockIcon:zve,FileCode:$ve,FileCode2:Bve,FileCode2Icon:Bve,FileCodeIcon:$ve,FileCog:VD,FileCog2:VD,FileCog2Icon:VD,FileCogIcon:VD,FileDiff:Uve,FileDiffIcon:Uve,FileDigit:qve,FileDigitIcon:qve,FileDown:u2,FileDownIcon:u2,FileEdit:HD,FileEditIcon:HD,FileHeart:Vve,FileHeartIcon:Vve,FileIcon:Fq,FileImage:GI,FileImageIcon:GI,FileInput:Hve,FileInputIcon:Hve,FileJson:Wve,FileJson2:Gve,FileJson2Icon:Gve,FileJsonIcon:Wve,FileKey:Yve,FileKey2:Kve,FileKey2Icon:Kve,FileKeyIcon:Yve,FileLineChart:UD,FileLineChartIcon:UD,FileLock:Xve,FileLock2:Zve,FileLock2Icon:Zve,FileLockIcon:Xve,FileMinus:Jve,FileMinus2:Qve,FileMinus2Icon:Qve,FileMinusIcon:Jve,FileMusic:ebe,FileMusicIcon:ebe,FileOutput:tbe,FileOutputIcon:tbe,FilePen:HD,FilePenIcon:HD,FilePenLine:m_,FilePenLineIcon:m_,FilePieChart:qD,FilePieChartIcon:qD,FilePlus:sbe,FilePlus2:Dq,FilePlus2Icon:Dq,FilePlusIcon:sbe,FileQuestion:nbe,FileQuestionIcon:nbe,FileScan:rbe,FileScanIcon:rbe,FileSearch:NJ,FileSearch2:abe,FileSearch2Icon:abe,FileSearchIcon:NJ,FileSignature:m_,FileSignatureIcon:m_,FileSliders:ibe,FileSlidersIcon:ibe,FileSpreadsheet:ek,FileSpreadsheetIcon:ek,FileStack:kJ,FileStackIcon:kJ,FileSymlink:obe,FileSymlinkIcon:obe,FileTerminal:lbe,FileTerminalIcon:lbe,FileText:Jr,FileTextIcon:Jr,FileType:dbe,FileType2:cbe,FileType2Icon:cbe,FileTypeIcon:dbe,FileUp:SJ,FileUpIcon:SJ,FileUser:ube,FileUserIcon:ube,FileVideo:CJ,FileVideo2:hbe,FileVideo2Icon:hbe,FileVideoIcon:CJ,FileVolume:fbe,FileVolume2:mbe,FileVolume2Icon:mbe,FileVolumeIcon:fbe,FileWarning:pbe,FileWarningIcon:pbe,FileX:xbe,FileX2:gbe,FileX2Icon:gbe,FileXIcon:xbe,Files:ybe,FilesIcon:ybe,Film:rf,FilmIcon:rf,Filter:Iw,FilterIcon:Iw,FilterX:vbe,FilterXIcon:vbe,Fingerprint:bbe,FingerprintIcon:bbe,FireExtinguisher:_be,FireExtinguisherIcon:_be,Fish:Nbe,FishIcon:Nbe,FishOff:wbe,FishOffIcon:wbe,FishSymbol:jbe,FishSymbolIcon:jbe,Flag:TE,FlagIcon:TE,FlagOff:kbe,FlagOffIcon:kbe,FlagTriangleLeft:Sbe,FlagTriangleLeftIcon:Sbe,FlagTriangleRight:Cbe,FlagTriangleRightIcon:Cbe,Flame:nh,FlameIcon:nh,FlameKindling:Abe,FlameKindlingIcon:Abe,Flashlight:Tbe,FlashlightIcon:Tbe,FlashlightOff:Ebe,FlashlightOffIcon:Ebe,FlaskConical:I4,FlaskConicalIcon:I4,FlaskConicalOff:Mbe,FlaskConicalOffIcon:Mbe,FlaskRound:Pbe,FlaskRoundIcon:Pbe,FlipHorizontal:AJ,FlipHorizontal2:Ibe,FlipHorizontal2Icon:Ibe,FlipHorizontalIcon:AJ,FlipVertical:Rbe,FlipVertical2:Lbe,FlipVertical2Icon:Lbe,FlipVerticalIcon:Rbe,Flower:Dbe,Flower2:HS,Flower2Icon:HS,FlowerIcon:Dbe,Focus:Fbe,FocusIcon:Fbe,FoldHorizontal:Obe,FoldHorizontalIcon:Obe,FoldVertical:zbe,FoldVerticalIcon:zbe,Folder:Oq,FolderArchive:Bbe,FolderArchiveIcon:Bbe,FolderCheck:$be,FolderCheckIcon:$be,FolderClock:Ube,FolderClockIcon:Ube,FolderClosed:qbe,FolderClosedIcon:qbe,FolderCode:Vbe,FolderCodeIcon:Vbe,FolderCog:GD,FolderCog2:GD,FolderCog2Icon:GD,FolderCogIcon:GD,FolderDot:Hbe,FolderDotIcon:Hbe,FolderDown:Gbe,FolderDownIcon:Gbe,FolderEdit:WD,FolderEditIcon:WD,FolderGit:Kbe,FolderGit2:Wbe,FolderGit2Icon:Wbe,FolderGitIcon:Kbe,FolderHeart:Ybe,FolderHeartIcon:Ybe,FolderIcon:Oq,FolderInput:Zbe,FolderInputIcon:Zbe,FolderKanban:Xbe,FolderKanbanIcon:Xbe,FolderKey:Qbe,FolderKeyIcon:Qbe,FolderLock:Jbe,FolderLockIcon:Jbe,FolderMinus:e1e,FolderMinusIcon:e1e,FolderOpen:_b,FolderOpenDot:t1e,FolderOpenDotIcon:t1e,FolderOpenIcon:_b,FolderOutput:s1e,FolderOutputIcon:s1e,FolderPen:WD,FolderPenIcon:WD,FolderPlus:EJ,FolderPlusIcon:EJ,FolderRoot:n1e,FolderRootIcon:n1e,FolderSearch:a1e,FolderSearch2:r1e,FolderSearch2Icon:r1e,FolderSearchIcon:a1e,FolderSymlink:i1e,FolderSymlinkIcon:i1e,FolderSync:o1e,FolderSyncIcon:o1e,FolderTree:l1e,FolderTreeIcon:l1e,FolderUp:c1e,FolderUpIcon:c1e,FolderX:d1e,FolderXIcon:d1e,Folders:u1e,FoldersIcon:u1e,Footprints:h1e,FootprintsIcon:h1e,ForkKnife:IO,ForkKnifeCrossed:PO,ForkKnifeCrossedIcon:PO,ForkKnifeIcon:IO,Forklift:m1e,ForkliftIcon:m1e,FormInput:xF,FormInputIcon:xF,Forward:f1e,ForwardIcon:f1e,Frame:p1e,FrameIcon:p1e,Framer:g1e,FramerIcon:g1e,Frown:x1e,FrownIcon:x1e,Fuel:y1e,FuelIcon:y1e,Fullscreen:v1e,FullscreenIcon:v1e,FunctionSquare:QF,FunctionSquareIcon:QF,GalleryHorizontal:_1e,GalleryHorizontalEnd:b1e,GalleryHorizontalEndIcon:b1e,GalleryHorizontalIcon:_1e,GalleryThumbnails:w1e,GalleryThumbnailsIcon:w1e,GalleryVertical:N1e,GalleryVerticalEnd:j1e,GalleryVerticalEndIcon:j1e,GalleryVerticalIcon:N1e,Gamepad:S1e,Gamepad2:k1e,Gamepad2Icon:k1e,GamepadIcon:S1e,GanttChart:aD,GanttChartIcon:aD,GanttChartSquare:x5,GanttChartSquareIcon:x5,Gauge:C1e,GaugeCircle:_D,GaugeCircleIcon:_D,GaugeIcon:C1e,Gavel:A1e,GavelIcon:A1e,Gem:E1e,GemIcon:E1e,Ghost:Vz,GhostIcon:Vz,Gift:ul,GiftIcon:ul,GitBranch:M1e,GitBranchIcon:M1e,GitBranchPlus:T1e,GitBranchPlusIcon:T1e,GitCommit:KD,GitCommitHorizontal:KD,GitCommitHorizontalIcon:KD,GitCommitIcon:KD,GitCommitVertical:P1e,GitCommitVerticalIcon:P1e,GitCompare:L1e,GitCompareArrows:I1e,GitCompareArrowsIcon:I1e,GitCompareIcon:L1e,GitFork:R1e,GitForkIcon:R1e,GitGraph:D1e,GitGraphIcon:D1e,GitMerge:F1e,GitMergeIcon:F1e,GitPullRequest:q1e,GitPullRequestArrow:O1e,GitPullRequestArrowIcon:O1e,GitPullRequestClosed:z1e,GitPullRequestClosedIcon:z1e,GitPullRequestCreate:$1e,GitPullRequestCreateArrow:B1e,GitPullRequestCreateArrowIcon:B1e,GitPullRequestCreateIcon:$1e,GitPullRequestDraft:U1e,GitPullRequestDraftIcon:U1e,GitPullRequestIcon:q1e,Github:V1e,GithubIcon:V1e,Gitlab:H1e,GitlabIcon:H1e,GlassWater:G1e,GlassWaterIcon:G1e,Glasses:W1e,GlassesIcon:W1e,Globe:dl,Globe2:IN,Globe2Icon:IN,GlobeIcon:dl,GlobeLock:K1e,GlobeLockIcon:K1e,Goal:Y1e,GoalIcon:Y1e,Grab:Z1e,GrabIcon:Z1e,GraduationCap:of,GraduationCapIcon:of,Grape:X1e,GrapeIcon:X1e,Grid:Uj,Grid2X2:ZD,Grid2X2Icon:ZD,Grid2X2Plus:YD,Grid2X2PlusIcon:YD,Grid2x2:ZD,Grid2x2Check:Q1e,Grid2x2CheckIcon:Q1e,Grid2x2Icon:ZD,Grid2x2Plus:YD,Grid2x2PlusIcon:YD,Grid2x2X:J1e,Grid2x2XIcon:J1e,Grid3X3:Uj,Grid3X3Icon:Uj,Grid3x3:Uj,Grid3x3Icon:Uj,GridIcon:Uj,Grip:t_e,GripHorizontal:e_e,GripHorizontalIcon:e_e,GripIcon:t_e,GripVertical:Ug,GripVerticalIcon:Ug,Group:s_e,GroupIcon:s_e,Guitar:n_e,GuitarIcon:n_e,Ham:r_e,HamIcon:r_e,Hammer:TJ,HammerIcon:TJ,Hand:zq,HandCoins:a_e,HandCoinsIcon:a_e,HandHeart:MJ,HandHeartIcon:MJ,HandHelping:r4,HandHelpingIcon:r4,HandIcon:zq,HandMetal:i_e,HandMetalIcon:i_e,HandPlatter:o_e,HandPlatterIcon:o_e,Handshake:wb,HandshakeIcon:wb,HardDrive:PJ,HardDriveDownload:l_e,HardDriveDownloadIcon:l_e,HardDriveIcon:PJ,HardDriveUpload:c_e,HardDriveUploadIcon:c_e,HardHat:d_e,HardHatIcon:d_e,Hash:WI,HashIcon:WI,Haze:u_e,HazeIcon:u_e,HdmiPort:h_e,HdmiPortIcon:h_e,Heading:g_e,Heading1:Bq,Heading1Icon:Bq,Heading2:Hz,Heading2Icon:Hz,Heading3:$q,Heading3Icon:$q,Heading4:m_e,Heading4Icon:m_e,Heading5:f_e,Heading5Icon:f_e,Heading6:p_e,Heading6Icon:p_e,HeadingIcon:g_e,HeadphoneOff:x_e,HeadphoneOffIcon:x_e,Headphones:y_e,HeadphonesIcon:y_e,Headset:v_e,HeadsetIcon:v_e,Heart:Jo,HeartCrack:b_e,HeartCrackIcon:b_e,HeartHandshake:IJ,HeartHandshakeIcon:IJ,HeartIcon:Jo,HeartOff:__e,HeartOffIcon:__e,HeartPulse:w_e,HeartPulseIcon:w_e,Heater:j_e,HeaterIcon:j_e,HelpCircle:s4,HelpCircleIcon:s4,HelpingHand:r4,HelpingHandIcon:r4,Hexagon:N_e,HexagonIcon:N_e,Highlighter:k_e,HighlighterIcon:k_e,History:Lw,HistoryIcon:Lw,Home:va,HomeIcon:va,Hop:C_e,HopIcon:C_e,HopOff:S_e,HopOffIcon:S_e,Hospital:A_e,HospitalIcon:A_e,Hotel:E_e,HotelIcon:E_e,Hourglass:LJ,HourglassIcon:LJ,House:va,HouseIcon:va,HousePlug:T_e,HousePlugIcon:T_e,HousePlus:M_e,HousePlusIcon:M_e,IceCream:QD,IceCream2:XD,IceCream2Icon:XD,IceCreamBowl:XD,IceCreamBowlIcon:XD,IceCreamCone:QD,IceCreamConeIcon:QD,IceCreamIcon:QD,Icon:FRt,IdCard:RJ,IdCardIcon:RJ,Image:Mc,ImageDown:P_e,ImageDownIcon:P_e,ImageIcon:Mc,ImageMinus:I_e,ImageMinusIcon:I_e,ImageOff:L_e,ImageOffIcon:L_e,ImagePlay:R_e,ImagePlayIcon:R_e,ImagePlus:Av,ImagePlusIcon:Av,ImageUp:D_e,ImageUpIcon:D_e,ImageUpscale:F_e,ImageUpscaleIcon:F_e,Images:O_e,ImagesIcon:O_e,Import:z_e,ImportIcon:z_e,Inbox:Gz,InboxIcon:Gz,Indent:eF,IndentDecrease:JD,IndentDecreaseIcon:JD,IndentIcon:eF,IndentIncrease:eF,IndentIncreaseIcon:eF,IndianRupee:B_e,IndianRupeeIcon:B_e,Infinity:Uq,InfinityIcon:Uq,Info:eC,InfoIcon:eC,Inspect:rO,InspectIcon:rO,InspectionPanel:$_e,InspectionPanelIcon:$_e,Instagram:Tf,InstagramIcon:Tf,Italic:ME,ItalicIcon:ME,IterationCcw:U_e,IterationCcwIcon:U_e,IterationCw:q_e,IterationCwIcon:q_e,JapaneseYen:V_e,JapaneseYenIcon:V_e,Joystick:H_e,JoystickIcon:H_e,Kanban:h2,KanbanIcon:h2,KanbanSquare:JF,KanbanSquareDashed:GF,KanbanSquareDashedIcon:GF,KanbanSquareIcon:JF,Key:S_,KeyIcon:S_,KeyRound:KI,KeyRoundIcon:KI,KeySquare:G_e,KeySquareIcon:G_e,Keyboard:Y_e,KeyboardIcon:Y_e,KeyboardMusic:W_e,KeyboardMusicIcon:W_e,KeyboardOff:K_e,KeyboardOffIcon:K_e,Lamp:twe,LampCeiling:Z_e,LampCeilingIcon:Z_e,LampDesk:X_e,LampDeskIcon:X_e,LampFloor:Q_e,LampFloorIcon:Q_e,LampIcon:twe,LampWallDown:J_e,LampWallDownIcon:J_e,LampWallUp:ewe,LampWallUpIcon:ewe,LandPlot:swe,LandPlotIcon:swe,Landmark:qq,LandmarkIcon:qq,Languages:nwe,LanguagesIcon:nwe,Laptop:awe,Laptop2:tF,Laptop2Icon:tF,LaptopIcon:awe,LaptopMinimal:tF,LaptopMinimalCheck:rwe,LaptopMinimalCheckIcon:rwe,LaptopMinimalIcon:tF,Lasso:owe,LassoIcon:owe,LassoSelect:iwe,LassoSelectIcon:iwe,Laugh:lwe,LaughIcon:lwe,Layers:L4,Layers2:cwe,Layers2Icon:cwe,Layers3:dwe,Layers3Icon:dwe,LayersIcon:L4,Layout:DA,LayoutDashboard:YI,LayoutDashboardIcon:YI,LayoutGrid:Qf,LayoutGridIcon:Qf,LayoutIcon:DA,LayoutList:uwe,LayoutListIcon:uwe,LayoutPanelLeft:hwe,LayoutPanelLeftIcon:hwe,LayoutPanelTop:mwe,LayoutPanelTopIcon:mwe,LayoutTemplate:m2,LayoutTemplateIcon:m2,Leaf:fwe,LeafIcon:fwe,LeafyGreen:pwe,LeafyGreenIcon:pwe,Lectern:gwe,LecternIcon:gwe,LetterText:xwe,LetterTextIcon:xwe,Library:f2,LibraryBig:ywe,LibraryBigIcon:ywe,LibraryIcon:f2,LibrarySquare:eO,LibrarySquareIcon:eO,LifeBuoy:Vq,LifeBuoyIcon:Vq,Ligature:vwe,LigatureIcon:vwe,Lightbulb:tC,LightbulbIcon:tC,LightbulbOff:bwe,LightbulbOffIcon:bwe,LineChart:sD,LineChartIcon:sD,Link:Ad,Link2:bd,Link2Icon:bd,Link2Off:_we,Link2OffIcon:_we,LinkIcon:Ad,Linkedin:hy,LinkedinIcon:hy,List:P0,ListCheck:wwe,ListCheckIcon:wwe,ListChecks:Ev,ListChecksIcon:Ev,ListCollapse:jwe,ListCollapseIcon:jwe,ListEnd:Nwe,ListEndIcon:Nwe,ListFilter:DJ,ListFilterIcon:DJ,ListIcon:P0,ListMinus:kwe,ListMinusIcon:kwe,ListMusic:Swe,ListMusicIcon:Swe,ListOrdered:p2,ListOrderedIcon:p2,ListPlus:FJ,ListPlusIcon:FJ,ListRestart:Cwe,ListRestartIcon:Cwe,ListStart:Awe,ListStartIcon:Awe,ListTodo:Ewe,ListTodoIcon:Ewe,ListTree:Twe,ListTreeIcon:Twe,ListVideo:Mwe,ListVideoIcon:Mwe,ListX:Pwe,ListXIcon:Pwe,Loader:Lwe,Loader2:kt,Loader2Icon:kt,LoaderCircle:kt,LoaderCircleIcon:kt,LoaderIcon:Lwe,LoaderPinwheel:Iwe,LoaderPinwheelIcon:Iwe,Locate:Hq,LocateFixed:Rwe,LocateFixedIcon:Rwe,LocateIcon:Hq,LocateOff:Dwe,LocateOffIcon:Dwe,Lock:pc,LockIcon:pc,LockKeyhole:OJ,LockKeyholeIcon:OJ,LockKeyholeOpen:sF,LockKeyholeOpenIcon:sF,LockOpen:nF,LockOpenIcon:nF,LogIn:ZI,LogInIcon:ZI,LogOut:Wz,LogOutIcon:Wz,Logs:Fwe,LogsIcon:Fwe,Lollipop:Owe,LollipopIcon:Owe,LucideAArrowDown:_me,LucideAArrowUp:wme,LucideALargeSmall:jme,LucideAccessibility:Nme,LucideActivity:af,LucideActivitySquare:kF,LucideAirVent:kme,LucideAirplay:Sme,LucideAlarmCheck:DR,LucideAlarmClock:Ame,LucideAlarmClockCheck:DR,LucideAlarmClockMinus:FR,LucideAlarmClockOff:Cme,LucideAlarmClockPlus:OR,LucideAlarmMinus:FR,LucideAlarmPlus:OR,LucideAlarmSmoke:Eme,LucideAlbum:Tme,LucideAlertCircle:ll,LucideAlertOctagon:BS,LucideAlertTriangle:wl,LucideAlignCenter:zI,LucideAlignCenterHorizontal:Mme,LucideAlignCenterVertical:Pme,LucideAlignEndHorizontal:Ime,LucideAlignEndVertical:Lme,LucideAlignHorizontalDistributeCenter:Rme,LucideAlignHorizontalDistributeEnd:Dme,LucideAlignHorizontalDistributeStart:Fme,LucideAlignHorizontalJustifyCenter:Ome,LucideAlignHorizontalJustifyEnd:zme,LucideAlignHorizontalJustifyStart:Bme,LucideAlignHorizontalSpaceAround:$me,LucideAlignHorizontalSpaceBetween:Ume,LucideAlignJustify:qme,LucideAlignLeft:BI,LucideAlignRight:$I,LucideAlignStartHorizontal:Vme,LucideAlignStartVertical:Hme,LucideAlignVerticalDistributeCenter:Gme,LucideAlignVerticalDistributeEnd:Wme,LucideAlignVerticalDistributeStart:Kme,LucideAlignVerticalJustifyCenter:Yme,LucideAlignVerticalJustifyEnd:Zme,LucideAlignVerticalJustifyStart:Xme,LucideAlignVerticalSpaceAround:Qme,LucideAlignVerticalSpaceBetween:Jme,LucideAmbulance:efe,LucideAmpersand:tfe,LucideAmpersands:sfe,LucideAmphora:nfe,LucideAnchor:rfe,LucideAngry:afe,LucideAnnoyed:ife,LucideAntenna:ofe,LucideAnvil:lfe,LucideAperture:cfe,LucideAppWindow:ufe,LucideAppWindowMac:dfe,LucideApple:hfe,LucideArchive:Sv,LucideArchiveRestore:UI,LucideArchiveX:mfe,LucideAreaChart:ZR,LucideArmchair:ffe,LucideArrowBigDown:gfe,LucideArrowBigDownDash:pfe,LucideArrowBigLeft:yfe,LucideArrowBigLeftDash:xfe,LucideArrowBigRight:bfe,LucideArrowBigRightDash:vfe,LucideArrowBigUp:wfe,LucideArrowBigUpDash:_fe,LucideArrowDown:Dg,LucideArrowDown01:jfe,LucideArrowDown10:Nfe,LucideArrowDownAZ:zR,LucideArrowDownAz:zR,LucideArrowDownCircle:lD,LucideArrowDownFromLine:kfe,LucideArrowDownLeft:Sfe,LucideArrowDownLeftFromCircle:dD,LucideArrowDownLeftFromSquare:TF,LucideArrowDownLeftSquare:SF,LucideArrowDownNarrowWide:Cfe,LucideArrowDownRight:pJ,LucideArrowDownRightFromCircle:uD,LucideArrowDownRightFromSquare:MF,LucideArrowDownRightSquare:CF,LucideArrowDownSquare:AF,LucideArrowDownToDot:Afe,LucideArrowDownToLine:Efe,LucideArrowDownUp:Tfe,LucideArrowDownWideNarrow:BR,LucideArrowDownZA:$R,LucideArrowDownZa:$R,LucideArrowLeft:qa,LucideArrowLeftCircle:cD,LucideArrowLeftFromLine:Mfe,LucideArrowLeftRight:gJ,LucideArrowLeftSquare:EF,LucideArrowLeftToLine:Pfe,LucideArrowRight:ei,LucideArrowRightCircle:fD,LucideArrowRightFromLine:Ife,LucideArrowRightLeft:E4,LucideArrowRightSquare:LF,LucideArrowRightToLine:Lfe,LucideArrowUp:Zf,LucideArrowUp01:Rfe,LucideArrowUp10:Dfe,LucideArrowUpAZ:UR,LucideArrowUpAz:UR,LucideArrowUpCircle:pD,LucideArrowUpDown:By,LucideArrowUpFromDot:Ffe,LucideArrowUpFromLine:Ofe,LucideArrowUpLeft:zfe,LucideArrowUpLeftFromCircle:hD,LucideArrowUpLeftFromSquare:PF,LucideArrowUpLeftSquare:RF,LucideArrowUpNarrowWide:qR,LucideArrowUpRight:Oz,LucideArrowUpRightFromCircle:mD,LucideArrowUpRightFromSquare:IF,LucideArrowUpRightSquare:DF,LucideArrowUpSquare:FF,LucideArrowUpToLine:Bfe,LucideArrowUpWideNarrow:$fe,LucideArrowUpZA:VR,LucideArrowUpZa:VR,LucideArrowsUpFromLine:Ufe,LucideAsterisk:qfe,LucideAsteriskSquare:OF,LucideAtSign:Vfe,LucideAtom:Hfe,LucideAudioLines:Gfe,LucideAudioWaveform:Wfe,LucideAward:Rm,LucideAxe:Kfe,LucideAxis3D:HR,LucideAxis3d:HR,LucideBaby:Yfe,LucideBackpack:Zfe,LucideBadge:hpe,LucideBadgeAlert:Xfe,LucideBadgeCent:Qfe,LucideBadgeCheck:RA,LucideBadgeDollarSign:Jfe,LucideBadgeEuro:epe,LucideBadgeHelp:tpe,LucideBadgeIndianRupee:spe,LucideBadgeInfo:npe,LucideBadgeJapaneseYen:rpe,LucideBadgeMinus:ape,LucideBadgePercent:ipe,LucideBadgePlus:ope,LucideBadgePoundSterling:lpe,LucideBadgeRussianRuble:cpe,LucideBadgeSwissFranc:dpe,LucideBadgeX:upe,LucideBaggageClaim:mpe,LucideBan:zz,LucideBanana:fpe,LucideBandage:ppe,LucideBanknote:gpe,LucideBarChart:nD,LucideBarChart2:rD,LucideBarChart3:Wl,LucideBarChart4:tD,LucideBarChartBig:eD,LucideBarChartHorizontal:QR,LucideBarChartHorizontalBig:XR,LucideBarcode:xpe,LucideBaseline:ype,LucideBath:T0,LucideBattery:Npe,LucideBatteryCharging:vpe,LucideBatteryFull:bpe,LucideBatteryLow:_pe,LucideBatteryMedium:wpe,LucideBatteryWarning:jpe,LucideBeaker:xJ,LucideBean:Spe,LucideBeanOff:kpe,LucideBed:l2,LucideBedDouble:T4,LucideBedSingle:Cpe,LucideBeef:Ape,LucideBeer:Tpe,LucideBeerOff:Epe,LucideBell:qy,LucideBellDot:Mpe,LucideBellElectric:Ppe,LucideBellMinus:Ipe,LucideBellOff:XS,LucideBellPlus:Lpe,LucideBellRing:QS,LucideBetweenHorizonalEnd:GR,LucideBetweenHorizonalStart:WR,LucideBetweenHorizontalEnd:GR,LucideBetweenHorizontalStart:WR,LucideBetweenVerticalEnd:Rpe,LucideBetweenVerticalStart:Dpe,LucideBicepsFlexed:Fpe,LucideBike:Ope,LucideBinary:zpe,LucideBinoculars:Bpe,LucideBiohazard:$pe,LucideBird:Upe,LucideBitcoin:qpe,LucideBlend:Vpe,LucideBlinds:Hpe,LucideBlocks:Gpe,LucideBluetooth:Zpe,LucideBluetoothConnected:Wpe,LucideBluetoothOff:Kpe,LucideBluetoothSearching:Ype,LucideBold:AE,LucideBolt:Xpe,LucideBomb:Qpe,LucideBone:Jpe,LucideBook:_ge,LucideBookA:ege,LucideBookAudio:tge,LucideBookCheck:sge,LucideBookCopy:nge,LucideBookDashed:KR,LucideBookDown:rge,LucideBookHeadphones:age,LucideBookHeart:ige,LucideBookImage:oge,LucideBookKey:lge,LucideBookLock:cge,LucideBookMarked:dge,LucideBookMinus:uge,LucideBookOpen:Xf,LucideBookOpenCheck:hge,LucideBookOpenText:mge,LucideBookPlus:fge,LucideBookTemplate:KR,LucideBookText:pge,LucideBookType:gge,LucideBookUp:yge,LucideBookUp2:xge,LucideBookUser:vge,LucideBookX:bge,LucideBookmark:M0,LucideBookmarkCheck:wge,LucideBookmarkMinus:jge,LucideBookmarkPlus:qI,LucideBookmarkX:Nge,LucideBoomBox:kge,LucideBot:M4,LucideBotMessageSquare:Sge,LucideBotOff:Cge,LucideBox:yJ,LucideBoxSelect:KF,LucideBoxes:Age,LucideBraces:aP,LucideBrackets:Ege,LucideBrain:vJ,LucideBrainCircuit:Tge,LucideBrainCog:Mge,LucideBrickWall:Pge,LucideBriefcase:Sx,LucideBriefcaseBusiness:Ige,LucideBriefcaseConveyorBelt:Lge,LucideBriefcaseMedical:Rge,LucideBringToFront:Dge,LucideBrush:Fge,LucideBug:Bge,LucideBugOff:Oge,LucideBugPlay:zge,LucideBuilding:VI,LucideBuilding2:ji,LucideBus:Uge,LucideBusFront:$ge,LucideCable:Vge,LucideCableCar:qge,LucideCake:Fg,LucideCakeSlice:Hge,LucideCalculator:c2,LucideCalendar:Ta,LucideCalendar1:Gge,LucideCalendarArrowDown:Wge,LucideCalendarArrowUp:Kge,LucideCalendarCheck:bb,LucideCalendarCheck2:Yge,LucideCalendarClock:Au,LucideCalendarCog:Zge,LucideCalendarDays:Kc,LucideCalendarFold:Xge,LucideCalendarHeart:JS,LucideCalendarMinus:Jge,LucideCalendarMinus2:Qge,LucideCalendarOff:Tq,LucideCalendarPlus:jv,LucideCalendarPlus2:exe,LucideCalendarRange:txe,LucideCalendarSearch:sxe,LucideCalendarSync:nxe,LucideCalendarX:bJ,LucideCalendarX2:rxe,LucideCamera:Cx,LucideCameraOff:axe,LucideCandlestickChart:JR,LucideCandy:lxe,LucideCandyCane:ixe,LucideCandyOff:oxe,LucideCannabis:cxe,LucideCaptions:YR,LucideCaptionsOff:dxe,LucideCar:mxe,LucideCarFront:uxe,LucideCarTaxiFront:hxe,LucideCaravan:fxe,LucideCarrot:pxe,LucideCaseLower:gxe,LucideCaseSensitive:xxe,LucideCaseUpper:yxe,LucideCassetteTape:vxe,LucideCast:bxe,LucideCastle:_xe,LucideCat:wxe,LucideCctv:jxe,LucideChartArea:ZR,LucideChartBar:QR,LucideChartBarBig:XR,LucideChartBarDecreasing:Nxe,LucideChartBarIncreasing:kxe,LucideChartBarStacked:Sxe,LucideChartCandlestick:JR,LucideChartColumn:Wl,LucideChartColumnBig:eD,LucideChartColumnDecreasing:Cxe,LucideChartColumnIncreasing:tD,LucideChartColumnStacked:Axe,LucideChartGantt:Exe,LucideChartLine:sD,LucideChartNetwork:Txe,LucideChartNoAxesColumn:rD,LucideChartNoAxesColumnDecreasing:Mxe,LucideChartNoAxesColumnIncreasing:nD,LucideChartNoAxesCombined:Pxe,LucideChartNoAxesGantt:aD,LucideChartPie:iD,LucideChartScatter:oD,LucideChartSpline:Ixe,LucideCheck:la,LucideCheckCheck:Bz,LucideCheckCircle:Nc,LucideCheckCircle2:qr,LucideCheckSquare:Kj,LucideCheckSquare2:BF,LucideChefHat:Lxe,LucideCherry:Rxe,LucideChevronDown:Tl,LucideChevronDownCircle:gD,LucideChevronDownSquare:$F,LucideChevronFirst:Dxe,LucideChevronLast:Fxe,LucideChevronLeft:Cd,LucideChevronLeftCircle:xD,LucideChevronLeftSquare:UF,LucideChevronRight:Di,LucideChevronRightCircle:yD,LucideChevronRightSquare:qF,LucideChevronUp:v1,LucideChevronUpCircle:vD,LucideChevronUpSquare:VF,LucideChevronsDown:zxe,LucideChevronsDownUp:Oxe,LucideChevronsLeft:Uxe,LucideChevronsLeftRight:$xe,LucideChevronsLeftRightEllipsis:Bxe,LucideChevronsRight:Vxe,LucideChevronsRightLeft:qxe,LucideChevronsUp:Hxe,LucideChevronsUpDown:Pw,LucideChrome:$z,LucideChurch:Gxe,LucideCigarette:Kxe,LucideCigaretteOff:Wxe,LucideCircle:Og,LucideCircleAlert:ll,LucideCircleArrowDown:lD,LucideCircleArrowLeft:cD,LucideCircleArrowOutDownLeft:dD,LucideCircleArrowOutDownRight:uD,LucideCircleArrowOutUpLeft:hD,LucideCircleArrowOutUpRight:mD,LucideCircleArrowRight:fD,LucideCircleArrowUp:pD,LucideCircleCheck:qr,LucideCircleCheckBig:Nc,LucideCircleChevronDown:gD,LucideCircleChevronLeft:xD,LucideCircleChevronRight:yD,LucideCircleChevronUp:vD,LucideCircleDashed:Yxe,LucideCircleDivide:bD,LucideCircleDollarSign:Zxe,LucideCircleDot:Qxe,LucideCircleDotDashed:Xxe,LucideCircleEllipsis:Jxe,LucideCircleEqual:eye,LucideCircleFadingArrowUp:tye,LucideCircleFadingPlus:sye,LucideCircleGauge:_D,LucideCircleHelp:s4,LucideCircleMinus:wD,LucideCircleOff:nye,LucideCircleParking:ND,LucideCircleParkingOff:jD,LucideCirclePause:kD,LucideCirclePercent:SD,LucideCirclePlay:tf,LucideCirclePlus:CD,LucideCirclePower:AD,LucideCircleSlash:rye,LucideCircleSlash2:ED,LucideCircleSlashed:ED,LucideCircleStop:TD,LucideCircleUser:PD,LucideCircleUserRound:MD,LucideCircleX:ku,LucideCircuitBoard:aye,LucideCitrus:iye,LucideClapperboard:Mq,LucideClipboard:mye,LucideClipboardCheck:JN,LucideClipboardCopy:oye,LucideClipboardEdit:LD,LucideClipboardList:zg,LucideClipboardMinus:lye,LucideClipboardPaste:cye,LucideClipboardPen:LD,LucideClipboardPenLine:ID,LucideClipboardPlus:dye,LucideClipboardSignature:ID,LucideClipboardType:uye,LucideClipboardX:hye,LucideClock:da,LucideClock1:fye,LucideClock10:pye,LucideClock11:gye,LucideClock12:xye,LucideClock2:yye,LucideClock3:Pq,LucideClock4:vye,LucideClock5:bye,LucideClock6:_ye,LucideClock7:wye,LucideClock8:jye,LucideClock9:Nye,LucideClockAlert:kye,LucideClockArrowDown:Sye,LucideClockArrowUp:Cye,LucideCloud:Uye,LucideCloudAlert:Aye,LucideCloudCog:Eye,LucideCloudDownload:RD,LucideCloudDrizzle:Tye,LucideCloudFog:Mye,LucideCloudHail:Pye,LucideCloudLightning:Iye,LucideCloudMoon:Rye,LucideCloudMoonRain:Lye,LucideCloudOff:Dye,LucideCloudRain:Oye,LucideCloudRainWind:Fye,LucideCloudSnow:zye,LucideCloudSun:$ye,LucideCloudSunRain:Bye,LucideCloudUpload:iP,LucideCloudy:qye,LucideClover:yE,LucideClub:Vye,LucideCode:EE,LucideCode2:n4,LucideCodeSquare:HF,LucideCodeXml:n4,LucideCodepen:Hye,LucideCodesandbox:Gye,LucideCoffee:P4,LucideCog:Wye,LucideCoins:_J,LucideColumns:DD,LucideColumns2:DD,LucideColumns3:oP,LucideColumns4:Kye,LucideCombine:Yye,LucideCommand:Zye,LucideCompass:Uz,LucideComponent:Xye,LucideComputer:Qye,LucideConciergeBell:Jye,LucideCone:e0e,LucideConstruction:t0e,LucideContact:HI,LucideContact2:FD,LucideContactRound:FD,LucideContainer:s0e,LucideContrast:n0e,LucideCookie:r0e,LucideCookingPot:a0e,LucideCopy:Ha,LucideCopyCheck:i0e,LucideCopyMinus:o0e,LucideCopyPlus:l0e,LucideCopySlash:c0e,LucideCopyX:d0e,LucideCopyleft:u0e,LucideCopyright:h0e,LucideCornerDownLeft:m0e,LucideCornerDownRight:wJ,LucideCornerLeftDown:f0e,LucideCornerLeftUp:p0e,LucideCornerRightDown:g0e,LucideCornerRightUp:x0e,LucideCornerUpLeft:y0e,LucideCornerUpRight:v0e,LucideCpu:b0e,LucideCreativeCommons:_0e,LucideCreditCard:Cv,LucideCroissant:w0e,LucideCrop:j0e,LucideCross:N0e,LucideCrosshair:k0e,LucideCrown:Bg,LucideCuboid:S0e,LucideCupSoda:C0e,LucideCurlyBraces:aP,LucideCurrency:A0e,LucideCylinder:E0e,LucideDam:T0e,LucideDatabase:Iq,LucideDatabaseBackup:M0e,LucideDatabaseZap:P0e,LucideDelete:I0e,LucideDessert:L0e,LucideDiameter:R0e,LucideDiamond:O0e,LucideDiamondMinus:D0e,LucideDiamondPercent:OD,LucideDiamondPlus:F0e,LucideDice1:z0e,LucideDice2:B0e,LucideDice3:$0e,LucideDice4:U0e,LucideDice5:q0e,LucideDice6:V0e,LucideDices:H0e,LucideDiff:G0e,LucideDisc:Z0e,LucideDisc2:W0e,LucideDisc3:K0e,LucideDiscAlbum:Y0e,LucideDivide:X0e,LucideDivideCircle:bD,LucideDivideSquare:YF,LucideDna:J0e,LucideDnaOff:Q0e,LucideDock:eve,LucideDog:tve,LucideDollarSign:ru,LucideDonut:sve,LucideDoorClosed:nve,LucideDoorOpen:d2,LucideDot:rve,LucideDotSquare:ZF,LucideDownload:di,LucideDownloadCloud:RD,LucideDraftingCompass:ave,LucideDrama:ive,LucideDribbble:ove,LucideDrill:lve,LucideDroplet:cve,LucideDroplets:b1,LucideDrum:dve,LucideDrumstick:uve,LucideDumbbell:hve,LucideEar:fve,LucideEarOff:mve,LucideEarth:IN,LucideEarthLock:pve,LucideEclipse:gve,LucideEdit:_p,LucideEdit2:LN,LucideEdit3:wf,LucideEgg:Lq,LucideEggFried:xve,LucideEggOff:yve,LucideEllipsis:h_,LucideEllipsisVertical:ty,LucideEqual:_ve,LucideEqualApproximately:vve,LucideEqualNot:bve,LucideEqualSquare:XF,LucideEraser:Rq,LucideEthernetPort:wve,LucideEuro:jve,LucideExpand:Nve,LucideExternalLink:kr,LucideEye:Ca,LucideEyeClosed:kve,LucideEyeOff:$g,LucideFacebook:Qp,LucideFactory:Sve,LucideFan:Cve,LucideFastForward:Ave,LucideFeather:Eve,LucideFence:Tve,LucideFerrisWheel:Mve,LucideFigma:Pve,LucideFile:Fq,LucideFileArchive:Ive,LucideFileAudio:Rve,LucideFileAudio2:Lve,LucideFileAxis3D:zD,LucideFileAxis3d:zD,LucideFileBadge:Fve,LucideFileBadge2:Dve,LucideFileBarChart:BD,LucideFileBarChart2:$D,LucideFileBox:Ove,LucideFileChartColumn:$D,LucideFileChartColumnIncreasing:BD,LucideFileChartLine:UD,LucideFileChartPie:qD,LucideFileCheck:jJ,LucideFileCheck2:qz,LucideFileClock:zve,LucideFileCode:$ve,LucideFileCode2:Bve,LucideFileCog:VD,LucideFileCog2:VD,LucideFileDiff:Uve,LucideFileDigit:qve,LucideFileDown:u2,LucideFileEdit:HD,LucideFileHeart:Vve,LucideFileImage:GI,LucideFileInput:Hve,LucideFileJson:Wve,LucideFileJson2:Gve,LucideFileKey:Yve,LucideFileKey2:Kve,LucideFileLineChart:UD,LucideFileLock:Xve,LucideFileLock2:Zve,LucideFileMinus:Jve,LucideFileMinus2:Qve,LucideFileMusic:ebe,LucideFileOutput:tbe,LucideFilePen:HD,LucideFilePenLine:m_,LucideFilePieChart:qD,LucideFilePlus:sbe,LucideFilePlus2:Dq,LucideFileQuestion:nbe,LucideFileScan:rbe,LucideFileSearch:NJ,LucideFileSearch2:abe,LucideFileSignature:m_,LucideFileSliders:ibe,LucideFileSpreadsheet:ek,LucideFileStack:kJ,LucideFileSymlink:obe,LucideFileTerminal:lbe,LucideFileText:Jr,LucideFileType:dbe,LucideFileType2:cbe,LucideFileUp:SJ,LucideFileUser:ube,LucideFileVideo:CJ,LucideFileVideo2:hbe,LucideFileVolume:fbe,LucideFileVolume2:mbe,LucideFileWarning:pbe,LucideFileX:xbe,LucideFileX2:gbe,LucideFiles:ybe,LucideFilm:rf,LucideFilter:Iw,LucideFilterX:vbe,LucideFingerprint:bbe,LucideFireExtinguisher:_be,LucideFish:Nbe,LucideFishOff:wbe,LucideFishSymbol:jbe,LucideFlag:TE,LucideFlagOff:kbe,LucideFlagTriangleLeft:Sbe,LucideFlagTriangleRight:Cbe,LucideFlame:nh,LucideFlameKindling:Abe,LucideFlashlight:Tbe,LucideFlashlightOff:Ebe,LucideFlaskConical:I4,LucideFlaskConicalOff:Mbe,LucideFlaskRound:Pbe,LucideFlipHorizontal:AJ,LucideFlipHorizontal2:Ibe,LucideFlipVertical:Rbe,LucideFlipVertical2:Lbe,LucideFlower:Dbe,LucideFlower2:HS,LucideFocus:Fbe,LucideFoldHorizontal:Obe,LucideFoldVertical:zbe,LucideFolder:Oq,LucideFolderArchive:Bbe,LucideFolderCheck:$be,LucideFolderClock:Ube,LucideFolderClosed:qbe,LucideFolderCode:Vbe,LucideFolderCog:GD,LucideFolderCog2:GD,LucideFolderDot:Hbe,LucideFolderDown:Gbe,LucideFolderEdit:WD,LucideFolderGit:Kbe,LucideFolderGit2:Wbe,LucideFolderHeart:Ybe,LucideFolderInput:Zbe,LucideFolderKanban:Xbe,LucideFolderKey:Qbe,LucideFolderLock:Jbe,LucideFolderMinus:e1e,LucideFolderOpen:_b,LucideFolderOpenDot:t1e,LucideFolderOutput:s1e,LucideFolderPen:WD,LucideFolderPlus:EJ,LucideFolderRoot:n1e,LucideFolderSearch:a1e,LucideFolderSearch2:r1e,LucideFolderSymlink:i1e,LucideFolderSync:o1e,LucideFolderTree:l1e,LucideFolderUp:c1e,LucideFolderX:d1e,LucideFolders:u1e,LucideFootprints:h1e,LucideForkKnife:IO,LucideForkKnifeCrossed:PO,LucideForklift:m1e,LucideFormInput:xF,LucideForward:f1e,LucideFrame:p1e,LucideFramer:g1e,LucideFrown:x1e,LucideFuel:y1e,LucideFullscreen:v1e,LucideFunctionSquare:QF,LucideGalleryHorizontal:_1e,LucideGalleryHorizontalEnd:b1e,LucideGalleryThumbnails:w1e,LucideGalleryVertical:N1e,LucideGalleryVerticalEnd:j1e,LucideGamepad:S1e,LucideGamepad2:k1e,LucideGanttChart:aD,LucideGanttChartSquare:x5,LucideGauge:C1e,LucideGaugeCircle:_D,LucideGavel:A1e,LucideGem:E1e,LucideGhost:Vz,LucideGift:ul,LucideGitBranch:M1e,LucideGitBranchPlus:T1e,LucideGitCommit:KD,LucideGitCommitHorizontal:KD,LucideGitCommitVertical:P1e,LucideGitCompare:L1e,LucideGitCompareArrows:I1e,LucideGitFork:R1e,LucideGitGraph:D1e,LucideGitMerge:F1e,LucideGitPullRequest:q1e,LucideGitPullRequestArrow:O1e,LucideGitPullRequestClosed:z1e,LucideGitPullRequestCreate:$1e,LucideGitPullRequestCreateArrow:B1e,LucideGitPullRequestDraft:U1e,LucideGithub:V1e,LucideGitlab:H1e,LucideGlassWater:G1e,LucideGlasses:W1e,LucideGlobe:dl,LucideGlobe2:IN,LucideGlobeLock:K1e,LucideGoal:Y1e,LucideGrab:Z1e,LucideGraduationCap:of,LucideGrape:X1e,LucideGrid:Uj,LucideGrid2X2:ZD,LucideGrid2X2Plus:YD,LucideGrid2x2:ZD,LucideGrid2x2Check:Q1e,LucideGrid2x2Plus:YD,LucideGrid2x2X:J1e,LucideGrid3X3:Uj,LucideGrid3x3:Uj,LucideGrip:t_e,LucideGripHorizontal:e_e,LucideGripVertical:Ug,LucideGroup:s_e,LucideGuitar:n_e,LucideHam:r_e,LucideHammer:TJ,LucideHand:zq,LucideHandCoins:a_e,LucideHandHeart:MJ,LucideHandHelping:r4,LucideHandMetal:i_e,LucideHandPlatter:o_e,LucideHandshake:wb,LucideHardDrive:PJ,LucideHardDriveDownload:l_e,LucideHardDriveUpload:c_e,LucideHardHat:d_e,LucideHash:WI,LucideHaze:u_e,LucideHdmiPort:h_e,LucideHeading:g_e,LucideHeading1:Bq,LucideHeading2:Hz,LucideHeading3:$q,LucideHeading4:m_e,LucideHeading5:f_e,LucideHeading6:p_e,LucideHeadphoneOff:x_e,LucideHeadphones:y_e,LucideHeadset:v_e,LucideHeart:Jo,LucideHeartCrack:b_e,LucideHeartHandshake:IJ,LucideHeartOff:__e,LucideHeartPulse:w_e,LucideHeater:j_e,LucideHelpCircle:s4,LucideHelpingHand:r4,LucideHexagon:N_e,LucideHighlighter:k_e,LucideHistory:Lw,LucideHome:va,LucideHop:C_e,LucideHopOff:S_e,LucideHospital:A_e,LucideHotel:E_e,LucideHourglass:LJ,LucideHouse:va,LucideHousePlug:T_e,LucideHousePlus:M_e,LucideIceCream:QD,LucideIceCream2:XD,LucideIceCreamBowl:XD,LucideIceCreamCone:QD,LucideIdCard:RJ,LucideImage:Mc,LucideImageDown:P_e,LucideImageMinus:I_e,LucideImageOff:L_e,LucideImagePlay:R_e,LucideImagePlus:Av,LucideImageUp:D_e,LucideImageUpscale:F_e,LucideImages:O_e,LucideImport:z_e,LucideInbox:Gz,LucideIndent:eF,LucideIndentDecrease:JD,LucideIndentIncrease:eF,LucideIndianRupee:B_e,LucideInfinity:Uq,LucideInfo:eC,LucideInspect:rO,LucideInspectionPanel:$_e,LucideInstagram:Tf,LucideItalic:ME,LucideIterationCcw:U_e,LucideIterationCw:q_e,LucideJapaneseYen:V_e,LucideJoystick:H_e,LucideKanban:h2,LucideKanbanSquare:JF,LucideKanbanSquareDashed:GF,LucideKey:S_,LucideKeyRound:KI,LucideKeySquare:G_e,LucideKeyboard:Y_e,LucideKeyboardMusic:W_e,LucideKeyboardOff:K_e,LucideLamp:twe,LucideLampCeiling:Z_e,LucideLampDesk:X_e,LucideLampFloor:Q_e,LucideLampWallDown:J_e,LucideLampWallUp:ewe,LucideLandPlot:swe,LucideLandmark:qq,LucideLanguages:nwe,LucideLaptop:awe,LucideLaptop2:tF,LucideLaptopMinimal:tF,LucideLaptopMinimalCheck:rwe,LucideLasso:owe,LucideLassoSelect:iwe,LucideLaugh:lwe,LucideLayers:L4,LucideLayers2:cwe,LucideLayers3:dwe,LucideLayout:DA,LucideLayoutDashboard:YI,LucideLayoutGrid:Qf,LucideLayoutList:uwe,LucideLayoutPanelLeft:hwe,LucideLayoutPanelTop:mwe,LucideLayoutTemplate:m2,LucideLeaf:fwe,LucideLeafyGreen:pwe,LucideLectern:gwe,LucideLetterText:xwe,LucideLibrary:f2,LucideLibraryBig:ywe,LucideLibrarySquare:eO,LucideLifeBuoy:Vq,LucideLigature:vwe,LucideLightbulb:tC,LucideLightbulbOff:bwe,LucideLineChart:sD,LucideLink:Ad,LucideLink2:bd,LucideLink2Off:_we,LucideLinkedin:hy,LucideList:P0,LucideListCheck:wwe,LucideListChecks:Ev,LucideListCollapse:jwe,LucideListEnd:Nwe,LucideListFilter:DJ,LucideListMinus:kwe,LucideListMusic:Swe,LucideListOrdered:p2,LucideListPlus:FJ,LucideListRestart:Cwe,LucideListStart:Awe,LucideListTodo:Ewe,LucideListTree:Twe,LucideListVideo:Mwe,LucideListX:Pwe,LucideLoader:Lwe,LucideLoader2:kt,LucideLoaderCircle:kt,LucideLoaderPinwheel:Iwe,LucideLocate:Hq,LucideLocateFixed:Rwe,LucideLocateOff:Dwe,LucideLock:pc,LucideLockKeyhole:OJ,LucideLockKeyholeOpen:sF,LucideLockOpen:nF,LucideLogIn:ZI,LucideLogOut:Wz,LucideLogs:Fwe,LucideLollipop:Owe,LucideLuggage:zwe,LucideMSquare:tO,LucideMagnet:Bwe,LucideMail:mn,LucideMailCheck:Kz,LucideMailMinus:$we,LucideMailOpen:Gq,LucideMailPlus:Wq,LucideMailQuestion:Uwe,LucideMailSearch:qwe,LucideMailWarning:Vwe,LucideMailX:XI,LucideMailbox:Hwe,LucideMails:Gwe,LucideMap:Yz,LucideMapPin:ci,LucideMapPinCheck:Kwe,LucideMapPinCheckInside:Wwe,LucideMapPinHouse:Ywe,LucideMapPinMinus:Xwe,LucideMapPinMinusInside:Zwe,LucideMapPinOff:Qwe,LucideMapPinPlus:eje,LucideMapPinPlusInside:Jwe,LucideMapPinX:sje,LucideMapPinXInside:tje,LucideMapPinned:zJ,LucideMartini:nje,LucideMaximize:Zz,LucideMaximize2:BJ,LucideMedal:PE,LucideMegaphone:xm,LucideMegaphoneOff:rje,LucideMeh:aje,LucideMemoryStick:ije,LucideMenu:IE,LucideMenuSquare:sO,LucideMerge:Xz,LucideMessageCircle:Th,LucideMessageCircleCode:oje,LucideMessageCircleDashed:lje,LucideMessageCircleHeart:Kq,LucideMessageCircleMore:cje,LucideMessageCircleOff:dje,LucideMessageCirclePlus:uje,LucideMessageCircleQuestion:$J,LucideMessageCircleReply:hje,LucideMessageCircleWarning:mje,LucideMessageCircleX:fje,LucideMessageSquare:eo,LucideMessageSquareCode:pje,LucideMessageSquareDashed:gje,LucideMessageSquareDiff:xje,LucideMessageSquareDot:yje,LucideMessageSquareHeart:vje,LucideMessageSquareLock:bje,LucideMessageSquareMore:UJ,LucideMessageSquareOff:_je,LucideMessageSquarePlus:p4,LucideMessageSquareQuote:LE,LucideMessageSquareReply:qJ,LucideMessageSquareShare:wje,LucideMessageSquareText:jje,LucideMessageSquareWarning:VJ,LucideMessageSquareX:Nje,LucideMessagesSquare:HJ,LucideMic:Qz,LucideMic2:rF,LucideMicOff:kje,LucideMicVocal:rF,LucideMicrochip:Sje,LucideMicroscope:Cje,LucideMicrowave:Aje,LucideMilestone:Eje,LucideMilk:Mje,LucideMilkOff:Tje,LucideMinimize:Ije,LucideMinimize2:Pje,LucideMinus:tk,LucideMinusCircle:wD,LucideMinusSquare:nO,LucideMonitor:sk,LucideMonitorCheck:Lje,LucideMonitorCog:Rje,LucideMonitorDot:Dje,LucideMonitorDown:Fje,LucideMonitorOff:Oje,LucideMonitorPause:zje,LucideMonitorPlay:Yq,LucideMonitorSmartphone:Bje,LucideMonitorSpeaker:$je,LucideMonitorStop:Uje,LucideMonitorUp:Jz,LucideMonitorX:qje,LucideMoon:Hje,LucideMoonStar:Vje,LucideMoreHorizontal:h_,LucideMoreVertical:ty,LucideMountain:Wje,LucideMountainSnow:Gje,LucideMouse:Zje,LucideMouseOff:Kje,LucideMousePointer:hb,LucideMousePointer2:GJ,LucideMousePointerBan:Yje,LucideMousePointerClick:Lm,LucideMousePointerSquareDashed:WF,LucideMove:WJ,LucideMove3D:aF,LucideMove3d:aF,LucideMoveDiagonal:Qje,LucideMoveDiagonal2:Xje,LucideMoveDown:t2e,LucideMoveDownLeft:Jje,LucideMoveDownRight:e2e,LucideMoveHorizontal:s2e,LucideMoveLeft:n2e,LucideMoveRight:r2e,LucideMoveUp:o2e,LucideMoveUpLeft:a2e,LucideMoveUpRight:i2e,LucideMoveVertical:l2e,LucideMusic:Zq,LucideMusic2:c2e,LucideMusic3:d2e,LucideMusic4:u2e,LucideNavigation:KJ,LucideNavigation2:m2e,LucideNavigation2Off:h2e,LucideNavigationOff:f2e,LucideNetwork:p2e,LucideNewspaper:nk,LucideNfc:g2e,LucideNotebook:b2e,LucideNotebookPen:x2e,LucideNotebookTabs:y2e,LucideNotebookText:v2e,LucideNotepadText:w2e,LucideNotepadTextDashed:_2e,LucideNut:N2e,LucideNutOff:j2e,LucideOctagon:S2e,LucideOctagonAlert:BS,LucideOctagonMinus:k2e,LucideOctagonPause:iF,LucideOctagonX:oF,LucideOmega:C2e,LucideOption:A2e,LucideOrbit:E2e,LucideOrigami:T2e,LucideOutdent:JD,LucidePackage:vm,LucidePackage2:M2e,LucidePackageCheck:P2e,LucidePackageMinus:I2e,LucidePackageOpen:L2e,LucidePackagePlus:R2e,LucidePackageSearch:D2e,LucidePackageX:F2e,LucidePaintBucket:O2e,LucidePaintRoller:z2e,LucidePaintbrush:B2e,LucidePaintbrush2:lF,LucidePaintbrushVertical:lF,LucidePalette:Yc,LucidePalmtree:kO,LucidePanelBottom:q2e,LucidePanelBottomClose:$2e,LucidePanelBottomDashed:cF,LucidePanelBottomInactive:cF,LucidePanelBottomOpen:U2e,LucidePanelLeft:mF,LucidePanelLeftClose:dF,LucidePanelLeftDashed:uF,LucidePanelLeftInactive:uF,LucidePanelLeftOpen:hF,LucidePanelRight:G2e,LucidePanelRightClose:V2e,LucidePanelRightDashed:fF,LucidePanelRightInactive:fF,LucidePanelRightOpen:H2e,LucidePanelTop:Y2e,LucidePanelTopClose:W2e,LucidePanelTopDashed:pF,LucidePanelTopInactive:pF,LucidePanelTopOpen:K2e,LucidePanelsLeftBottom:Z2e,LucidePanelsLeftRight:oP,LucidePanelsRightBottom:X2e,LucidePanelsTopBottom:bF,LucidePanelsTopLeft:DA,LucidePaperclip:QI,LucideParentheses:Q2e,LucideParkingCircle:ND,LucideParkingCircleOff:jD,LucideParkingMeter:J2e,LucideParkingSquare:iO,LucideParkingSquareOff:aO,LucidePartyPopper:Ax,LucidePause:Tv,LucidePauseCircle:kD,LucidePauseOctagon:iF,LucidePawPrint:eNe,LucidePcCase:tNe,LucidePen:LN,LucidePenBox:_p,LucidePenLine:wf,LucidePenOff:sNe,LucidePenSquare:_p,LucidePenTool:RE,LucidePencil:gi,LucidePencilLine:Xq,LucidePencilOff:nNe,LucidePencilRuler:rNe,LucidePentagon:aNe,LucidePercent:Rw,LucidePercentCircle:SD,LucidePercentDiamond:OD,LucidePercentSquare:oO,LucidePersonStanding:iNe,LucidePhilippinePeso:oNe,LucidePhone:Da,LucidePhoneCall:YJ,LucidePhoneForwarded:lNe,LucidePhoneIncoming:cNe,LucidePhoneMissed:dNe,LucidePhoneOff:uNe,LucidePhoneOutgoing:hNe,LucidePi:mNe,LucidePiSquare:lO,LucidePiano:fNe,LucidePickaxe:pNe,LucidePictureInPicture:xNe,LucidePictureInPicture2:gNe,LucidePieChart:iD,LucidePiggyBank:ZJ,LucidePilcrow:bNe,LucidePilcrowLeft:yNe,LucidePilcrowRight:vNe,LucidePilcrowSquare:cO,LucidePill:wNe,LucidePillBottle:_Ne,LucidePin:DE,LucidePinOff:XJ,LucidePipette:jNe,LucidePizza:NNe,LucidePlane:QJ,LucidePlaneLanding:kNe,LucidePlaneTakeoff:SNe,LucidePlay:Bu,LucidePlayCircle:tf,LucidePlaySquare:dO,LucidePlug:g2,LucidePlug2:CNe,LucidePlugZap:gF,LucidePlugZap2:gF,LucidePlus:dn,LucidePlusCircle:CD,LucidePlusSquare:uO,LucidePocket:ENe,LucidePocketKnife:ANe,LucidePodcast:TNe,LucidePointer:PNe,LucidePointerOff:MNe,LucidePopcorn:INe,LucidePopsicle:LNe,LucidePoundSterling:RNe,LucidePower:JJ,LucidePowerCircle:AD,LucidePowerOff:DNe,LucidePowerSquare:hO,LucidePresentation:jb,LucidePrinter:FE,LucidePrinterCheck:FNe,LucideProjector:ONe,LucideProportions:zNe,LucidePuzzle:BNe,LucidePyramid:$Ne,LucideQrCode:Jp,LucideQuote:x2,LucideRabbit:UNe,LucideRadar:Qq,LucideRadiation:qNe,LucideRadical:VNe,LucideRadio:Nb,LucideRadioReceiver:HNe,LucideRadioTower:GNe,LucideRadius:WNe,LucideRailSymbol:KNe,LucideRainbow:YNe,LucideRat:ZNe,LucideRatio:XNe,LucideReceipt:Jq,LucideReceiptCent:QNe,LucideReceiptEuro:JNe,LucideReceiptIndianRupee:eke,LucideReceiptJapaneseYen:tke,LucideReceiptPoundSterling:ske,LucideReceiptRussianRuble:nke,LucideReceiptSwissFranc:rke,LucideReceiptText:ake,LucideRectangleEllipsis:xF,LucideRectangleHorizontal:ike,LucideRectangleVertical:oke,LucideRecycle:lke,LucideRedo:OE,LucideRedo2:cke,LucideRedoDot:dke,LucideRefreshCcw:eV,LucideRefreshCcwDot:uke,LucideRefreshCw:ro,LucideRefreshCwOff:hke,LucideRefrigerator:mke,LucideRegex:fke,LucideRemoveFormatting:pke,LucideRepeat:zE,LucideRepeat1:gke,LucideRepeat2:eee,LucideReplace:yke,LucideReplaceAll:xke,LucideReply:tV,LucideReplyAll:vke,LucideRewind:bke,LucideRibbon:_ke,LucideRocket:qg,LucideRockingChair:wke,LucideRollerCoaster:jke,LucideRotate3D:yF,LucideRotate3d:yF,LucideRotateCcw:Ex,LucideRotateCcwSquare:Nke,LucideRotateCw:e7,LucideRotateCwSquare:kke,LucideRoute:sV,LucideRouteOff:Ske,LucideRouter:Cke,LucideRows:vF,LucideRows2:vF,LucideRows3:bF,LucideRows4:Ake,LucideRss:Eke,LucideRuler:R4,LucideRussianRuble:Tke,LucideSailboat:Mke,LucideSalad:Pke,LucideSandwich:Ike,LucideSatellite:Rke,LucideSatelliteDish:Lke,LucideSave:tl,LucideSaveAll:Dke,LucideSaveOff:Fke,LucideScale:Oke,LucideScale3D:_F,LucideScale3d:_F,LucideScaling:zke,LucideScan:Wke,LucideScanBarcode:Bke,LucideScanEye:$ke,LucideScanFace:Uke,LucideScanLine:qke,LucideScanQrCode:Vke,LucideScanSearch:Hke,LucideScanText:Gke,LucideScatterChart:oD,LucideSchool:Kke,LucideSchool2:CO,LucideScissors:Zke,LucideScissorsLineDashed:Yke,LucideScissorsSquare:mO,LucideScissorsSquareDashedBottom:zF,LucideScreenShare:Qke,LucideScreenShareOff:Xke,LucideScroll:Jke,LucideScrollText:nV,LucideSearch:Kr,LucideSearchCheck:eSe,LucideSearchCode:tSe,LucideSearchSlash:sSe,LucideSearchX:rV,LucideSection:nSe,LucideSend:Yr,LucideSendHorizonal:wF,LucideSendHorizontal:wF,LucideSendToBack:rSe,LucideSeparatorHorizontal:aSe,LucideSeparatorVertical:iSe,LucideServer:dSe,LucideServerCog:oSe,LucideServerCrash:lSe,LucideServerOff:cSe,LucideSettings:Sd,LucideSettings2:sC,LucideShapes:uSe,LucideShare:tee,LucideShare2:zd,LucideSheet:hSe,LucideShell:mSe,LucideShield:Mf,LucideShieldAlert:aV,LucideShieldBan:fSe,LucideShieldCheck:bm,LucideShieldClose:jF,LucideShieldEllipsis:pSe,LucideShieldHalf:gSe,LucideShieldMinus:xSe,LucideShieldOff:t7,LucideShieldPlus:ySe,LucideShieldQuestion:s7,LucideShieldX:jF,LucideShip:bSe,LucideShipWheel:vSe,LucideShirt:_Se,LucideShoppingBag:D4,LucideShoppingBasket:wSe,LucideShoppingCart:nC,LucideShovel:jSe,LucideShowerHead:NSe,LucideShrink:kSe,LucideShrub:SSe,LucideShuffle:n7,LucideSidebar:mF,LucideSidebarClose:dF,LucideSidebarOpen:hF,LucideSigma:CSe,LucideSigmaSquare:fO,LucideSignal:PSe,LucideSignalHigh:ASe,LucideSignalLow:ESe,LucideSignalMedium:TSe,LucideSignalZero:MSe,LucideSignature:ISe,LucideSignpost:see,LucideSignpostBig:LSe,LucideSiren:RSe,LucideSkipBack:DSe,LucideSkipForward:nee,LucideSkull:FSe,LucideSlack:OSe,LucideSlash:zSe,LucideSlashSquare:pO,LucideSlice:BSe,LucideSliders:NF,LucideSlidersHorizontal:JI,LucideSlidersVertical:NF,LucideSmartphone:_1,LucideSmartphoneCharging:$Se,LucideSmartphoneNfc:USe,LucideSmile:VSe,LucideSmilePlus:qSe,LucideSnail:HSe,LucideSnowflake:t2,LucideSofa:iV,LucideSortAsc:qR,LucideSortDesc:BR,LucideSoup:GSe,LucideSpace:WSe,LucideSpade:KSe,LucideSparkle:eL,LucideSparkles:Nn,LucideSpeaker:YSe,LucideSpeech:ZSe,LucideSpellCheck:QSe,LucideSpellCheck2:XSe,LucideSpline:JSe,LucideSplit:eCe,LucideSplitSquareHorizontal:gO,LucideSplitSquareVertical:xO,LucideSprayCan:tCe,LucideSprout:tL,LucideSquare:C_,LucideSquareActivity:kF,LucideSquareArrowDown:AF,LucideSquareArrowDownLeft:SF,LucideSquareArrowDownRight:CF,LucideSquareArrowLeft:EF,LucideSquareArrowOutDownLeft:TF,LucideSquareArrowOutDownRight:MF,LucideSquareArrowOutUpLeft:PF,LucideSquareArrowOutUpRight:IF,LucideSquareArrowRight:LF,LucideSquareArrowUp:FF,LucideSquareArrowUpLeft:RF,LucideSquareArrowUpRight:DF,LucideSquareAsterisk:OF,LucideSquareBottomDashedScissors:zF,LucideSquareChartGantt:x5,LucideSquareCheck:BF,LucideSquareCheckBig:Kj,LucideSquareChevronDown:$F,LucideSquareChevronLeft:UF,LucideSquareChevronRight:qF,LucideSquareChevronUp:VF,LucideSquareCode:HF,LucideSquareDashed:KF,LucideSquareDashedBottom:nCe,LucideSquareDashedBottomCode:sCe,LucideSquareDashedKanban:GF,LucideSquareDashedMousePointer:WF,LucideSquareDivide:YF,LucideSquareDot:ZF,LucideSquareEqual:XF,LucideSquareFunction:QF,LucideSquareGanttChart:x5,LucideSquareKanban:JF,LucideSquareLibrary:eO,LucideSquareM:tO,LucideSquareMenu:sO,LucideSquareMinus:nO,LucideSquareMousePointer:rO,LucideSquareParking:iO,LucideSquareParkingOff:aO,LucideSquarePen:_p,LucideSquarePercent:oO,LucideSquarePi:lO,LucideSquarePilcrow:cO,LucideSquarePlay:dO,LucideSquarePlus:uO,LucideSquarePower:hO,LucideSquareRadical:rCe,LucideSquareScissors:mO,LucideSquareSigma:fO,LucideSquareSlash:pO,LucideSquareSplitHorizontal:gO,LucideSquareSplitVertical:xO,LucideSquareSquare:aCe,LucideSquareStack:iCe,LucideSquareTerminal:yO,LucideSquareUser:bO,LucideSquareUserRound:vO,LucideSquareX:_O,LucideSquircle:oCe,LucideSquirrel:lCe,LucideStamp:cCe,LucideStar:Ja,LucideStarHalf:dCe,LucideStarOff:uCe,LucideStars:Nn,LucideStepBack:hCe,LucideStepForward:mCe,LucideStethoscope:fCe,LucideSticker:pCe,LucideStickyNote:r7,LucideStopCircle:TD,LucideStore:oV,LucideStretchHorizontal:gCe,LucideStretchVertical:xCe,LucideStrikethrough:ree,LucideSubscript:yCe,LucideSubtitles:YR,LucideSun:rk,LucideSunDim:vCe,LucideSunMedium:bCe,LucideSunMoon:_Ce,LucideSunSnow:wCe,LucideSunrise:jCe,LucideSunset:NCe,LucideSuperscript:kCe,LucideSwatchBook:SCe,LucideSwissFranc:CCe,LucideSwitchCamera:ACe,LucideSword:ECe,LucideSwords:TCe,LucideSyringe:MCe,LucideTable:cV,LucideTable2:lV,LucideTableCellsMerge:PCe,LucideTableCellsSplit:ICe,LucideTableColumnsSplit:LCe,LucideTableOfContents:RCe,LucideTableProperties:DCe,LucideTableRowsSplit:FCe,LucideTablet:dV,LucideTabletSmartphone:OCe,LucideTablets:zCe,LucideTag:Ap,LucideTags:aee,LucideTally1:BCe,LucideTally2:$Ce,LucideTally3:UCe,LucideTally4:qCe,LucideTally5:VCe,LucideTangent:HCe,LucideTarget:rh,LucideTelescope:GCe,LucideTent:KCe,LucideTentTree:WCe,LucideTerminal:YCe,LucideTerminalSquare:yO,LucideTestTube:ZCe,LucideTestTube2:wO,LucideTestTubeDiagonal:wO,LucideTestTubes:XCe,LucideText:t5e,LucideTextCursor:QCe,LucideTextCursorInput:uV,LucideTextQuote:JCe,LucideTextSearch:e5e,LucideTextSelect:jO,LucideTextSelection:jO,LucideTheater:s5e,LucideThermometer:a5e,LucideThermometerSnowflake:n5e,LucideThermometerSun:r5e,LucideThumbsDown:iee,LucideThumbsUp:Vy,LucideTicket:a7,LucideTicketCheck:i5e,LucideTicketMinus:o5e,LucideTicketPercent:l5e,LucideTicketPlus:c5e,LucideTicketSlash:d5e,LucideTicketX:u5e,LucideTickets:m5e,LucideTicketsPlane:h5e,LucideTimer:g5e,LucideTimerOff:f5e,LucideTimerReset:p5e,LucideToggleLeft:x5e,LucideToggleRight:y5e,LucideToilet:v5e,LucideTornado:b5e,LucideTorus:_5e,LucideTouchpad:j5e,LucideTouchpadOff:w5e,LucideTowerControl:N5e,LucideToyBrick:k5e,LucideTractor:S5e,LucideTrafficCone:C5e,LucideTrain:NO,LucideTrainFront:E5e,LucideTrainFrontTunnel:A5e,LucideTrainTrack:T5e,LucideTramFront:NO,LucideTrash:M5e,LucideTrash2:Wn,LucideTreeDeciduous:P5e,LucideTreePalm:kO,LucideTreePine:sL,LucideTrees:I5e,LucideTrello:L5e,LucideTrendingDown:rC,LucideTrendingUp:Yl,LucideTrendingUpDown:R5e,LucideTriangle:F5e,LucideTriangleAlert:wl,LucideTriangleRight:D5e,LucideTrophy:Kl,LucideTruck:oee,LucideTurtle:O5e,LucideTv:B5e,LucideTv2:SO,LucideTvMinimal:SO,LucideTvMinimalPlay:z5e,LucideTwitch:$5e,LucideTwitter:lee,LucideType:hV,LucideTypeOutline:U5e,LucideUmbrella:V5e,LucideUmbrellaOff:q5e,LucideUnderline:i7,LucideUndo:BE,LucideUndo2:cee,LucideUndoDot:H5e,LucideUnfoldHorizontal:G5e,LucideUnfoldVertical:W5e,LucideUngroup:K5e,LucideUniversity:CO,LucideUnlink:$E,LucideUnlink2:Y5e,LucideUnlock:nF,LucideUnlockKeyhole:sF,LucideUnplug:o7,LucideUpload:ni,LucideUploadCloud:iP,LucideUsb:Z5e,LucideUser:sl,LucideUser2:cP,LucideUserCheck:y2,LucideUserCheck2:lP,LucideUserCircle:PD,LucideUserCircle2:MD,LucideUserCog:dee,LucideUserCog2:AO,LucideUserMinus:mV,LucideUserMinus2:EO,LucideUserPen:X5e,LucideUserPlus:sc,LucideUserPlus2:TO,LucideUserRound:cP,LucideUserRoundCheck:lP,LucideUserRoundCog:AO,LucideUserRoundMinus:EO,LucideUserRoundPen:Q5e,LucideUserRoundPlus:TO,LucideUserRoundSearch:fV,LucideUserRoundX:MO,LucideUserSearch:J5e,LucideUserSquare:bO,LucideUserSquare2:vO,LucideUserX:pV,LucideUserX2:MO,LucideUsers:Zn,LucideUsers2:v0,LucideUsersRound:v0,LucideUtensils:IO,LucideUtensilsCrossed:PO,LucideUtilityPole:e4e,LucideVariable:gV,LucideVault:t4e,LucideVegan:s4e,LucideVenetianMask:n4e,LucideVerified:RA,LucideVibrate:a4e,LucideVibrateOff:r4e,LucideVideo:ua,LucideVideoOff:i4e,LucideVideotape:o4e,LucideView:l4e,LucideVoicemail:c4e,LucideVolleyball:d4e,LucideVolume:m4e,LucideVolume1:u4e,LucideVolume2:uee,LucideVolumeOff:h4e,LucideVolumeX:hee,LucideVote:f4e,LucideWallet:l7,LucideWallet2:LO,LucideWalletCards:p4e,LucideWalletMinimal:LO,LucideWallpaper:g4e,LucideWand:x4e,LucideWand2:sy,LucideWandSparkles:sy,LucideWarehouse:y4e,LucideWashingMachine:v4e,LucideWatch:b4e,LucideWaves:_4e,LucideWaypoints:w4e,LucideWebcam:j4e,LucideWebhook:k4e,LucideWebhookOff:N4e,LucideWeight:S4e,LucideWheat:A4e,LucideWheatOff:C4e,LucideWholeWord:E4e,LucideWifi:L4e,LucideWifiHigh:T4e,LucideWifiLow:M4e,LucideWifiOff:P4e,LucideWifiZero:I4e,LucideWind:D4e,LucideWindArrowDown:R4e,LucideWine:O4e,LucideWineOff:F4e,LucideWorkflow:c7,LucideWorm:z4e,LucideWrapText:B4e,LucideWrench:F4,LucideX:gr,LucideXCircle:ku,LucideXOctagon:oF,LucideXSquare:_O,LucideYoutube:xV,LucideZap:eg,LucideZapOff:$4e,LucideZoomIn:nL,LucideZoomOut:yV,Luggage:zwe,LuggageIcon:zwe,MSquare:tO,MSquareIcon:tO,Magnet:Bwe,MagnetIcon:Bwe,Mail:mn,MailCheck:Kz,MailCheckIcon:Kz,MailIcon:mn,MailMinus:$we,MailMinusIcon:$we,MailOpen:Gq,MailOpenIcon:Gq,MailPlus:Wq,MailPlusIcon:Wq,MailQuestion:Uwe,MailQuestionIcon:Uwe,MailSearch:qwe,MailSearchIcon:qwe,MailWarning:Vwe,MailWarningIcon:Vwe,MailX:XI,MailXIcon:XI,Mailbox:Hwe,MailboxIcon:Hwe,Mails:Gwe,MailsIcon:Gwe,Map:Yz,MapIcon:Yz,MapPin:ci,MapPinCheck:Kwe,MapPinCheckIcon:Kwe,MapPinCheckInside:Wwe,MapPinCheckInsideIcon:Wwe,MapPinHouse:Ywe,MapPinHouseIcon:Ywe,MapPinIcon:ci,MapPinMinus:Xwe,MapPinMinusIcon:Xwe,MapPinMinusInside:Zwe,MapPinMinusInsideIcon:Zwe,MapPinOff:Qwe,MapPinOffIcon:Qwe,MapPinPlus:eje,MapPinPlusIcon:eje,MapPinPlusInside:Jwe,MapPinPlusInsideIcon:Jwe,MapPinX:sje,MapPinXIcon:sje,MapPinXInside:tje,MapPinXInsideIcon:tje,MapPinned:zJ,MapPinnedIcon:zJ,Martini:nje,MartiniIcon:nje,Maximize:Zz,Maximize2:BJ,Maximize2Icon:BJ,MaximizeIcon:Zz,Medal:PE,MedalIcon:PE,Megaphone:xm,MegaphoneIcon:xm,MegaphoneOff:rje,MegaphoneOffIcon:rje,Meh:aje,MehIcon:aje,MemoryStick:ije,MemoryStickIcon:ije,Menu:IE,MenuIcon:IE,MenuSquare:sO,MenuSquareIcon:sO,Merge:Xz,MergeIcon:Xz,MessageCircle:Th,MessageCircleCode:oje,MessageCircleCodeIcon:oje,MessageCircleDashed:lje,MessageCircleDashedIcon:lje,MessageCircleHeart:Kq,MessageCircleHeartIcon:Kq,MessageCircleIcon:Th,MessageCircleMore:cje,MessageCircleMoreIcon:cje,MessageCircleOff:dje,MessageCircleOffIcon:dje,MessageCirclePlus:uje,MessageCirclePlusIcon:uje,MessageCircleQuestion:$J,MessageCircleQuestionIcon:$J,MessageCircleReply:hje,MessageCircleReplyIcon:hje,MessageCircleWarning:mje,MessageCircleWarningIcon:mje,MessageCircleX:fje,MessageCircleXIcon:fje,MessageSquare:eo,MessageSquareCode:pje,MessageSquareCodeIcon:pje,MessageSquareDashed:gje,MessageSquareDashedIcon:gje,MessageSquareDiff:xje,MessageSquareDiffIcon:xje,MessageSquareDot:yje,MessageSquareDotIcon:yje,MessageSquareHeart:vje,MessageSquareHeartIcon:vje,MessageSquareIcon:eo,MessageSquareLock:bje,MessageSquareLockIcon:bje,MessageSquareMore:UJ,MessageSquareMoreIcon:UJ,MessageSquareOff:_je,MessageSquareOffIcon:_je,MessageSquarePlus:p4,MessageSquarePlusIcon:p4,MessageSquareQuote:LE,MessageSquareQuoteIcon:LE,MessageSquareReply:qJ,MessageSquareReplyIcon:qJ,MessageSquareShare:wje,MessageSquareShareIcon:wje,MessageSquareText:jje,MessageSquareTextIcon:jje,MessageSquareWarning:VJ,MessageSquareWarningIcon:VJ,MessageSquareX:Nje,MessageSquareXIcon:Nje,MessagesSquare:HJ,MessagesSquareIcon:HJ,Mic:Qz,Mic2:rF,Mic2Icon:rF,MicIcon:Qz,MicOff:kje,MicOffIcon:kje,MicVocal:rF,MicVocalIcon:rF,Microchip:Sje,MicrochipIcon:Sje,Microscope:Cje,MicroscopeIcon:Cje,Microwave:Aje,MicrowaveIcon:Aje,Milestone:Eje,MilestoneIcon:Eje,Milk:Mje,MilkIcon:Mje,MilkOff:Tje,MilkOffIcon:Tje,Minimize:Ije,Minimize2:Pje,Minimize2Icon:Pje,MinimizeIcon:Ije,Minus:tk,MinusCircle:wD,MinusCircleIcon:wD,MinusIcon:tk,MinusSquare:nO,MinusSquareIcon:nO,Monitor:sk,MonitorCheck:Lje,MonitorCheckIcon:Lje,MonitorCog:Rje,MonitorCogIcon:Rje,MonitorDot:Dje,MonitorDotIcon:Dje,MonitorDown:Fje,MonitorDownIcon:Fje,MonitorIcon:sk,MonitorOff:Oje,MonitorOffIcon:Oje,MonitorPause:zje,MonitorPauseIcon:zje,MonitorPlay:Yq,MonitorPlayIcon:Yq,MonitorSmartphone:Bje,MonitorSmartphoneIcon:Bje,MonitorSpeaker:$je,MonitorSpeakerIcon:$je,MonitorStop:Uje,MonitorStopIcon:Uje,MonitorUp:Jz,MonitorUpIcon:Jz,MonitorX:qje,MonitorXIcon:qje,Moon:Hje,MoonIcon:Hje,MoonStar:Vje,MoonStarIcon:Vje,MoreHorizontal:h_,MoreHorizontalIcon:h_,MoreVertical:ty,MoreVerticalIcon:ty,Mountain:Wje,MountainIcon:Wje,MountainSnow:Gje,MountainSnowIcon:Gje,Mouse:Zje,MouseIcon:Zje,MouseOff:Kje,MouseOffIcon:Kje,MousePointer:hb,MousePointer2:GJ,MousePointer2Icon:GJ,MousePointerBan:Yje,MousePointerBanIcon:Yje,MousePointerClick:Lm,MousePointerClickIcon:Lm,MousePointerIcon:hb,MousePointerSquareDashed:WF,MousePointerSquareDashedIcon:WF,Move:WJ,Move3D:aF,Move3DIcon:aF,Move3d:aF,Move3dIcon:aF,MoveDiagonal:Qje,MoveDiagonal2:Xje,MoveDiagonal2Icon:Xje,MoveDiagonalIcon:Qje,MoveDown:t2e,MoveDownIcon:t2e,MoveDownLeft:Jje,MoveDownLeftIcon:Jje,MoveDownRight:e2e,MoveDownRightIcon:e2e,MoveHorizontal:s2e,MoveHorizontalIcon:s2e,MoveIcon:WJ,MoveLeft:n2e,MoveLeftIcon:n2e,MoveRight:r2e,MoveRightIcon:r2e,MoveUp:o2e,MoveUpIcon:o2e,MoveUpLeft:a2e,MoveUpLeftIcon:a2e,MoveUpRight:i2e,MoveUpRightIcon:i2e,MoveVertical:l2e,MoveVerticalIcon:l2e,Music:Zq,Music2:c2e,Music2Icon:c2e,Music3:d2e,Music3Icon:d2e,Music4:u2e,Music4Icon:u2e,MusicIcon:Zq,Navigation:KJ,Navigation2:m2e,Navigation2Icon:m2e,Navigation2Off:h2e,Navigation2OffIcon:h2e,NavigationIcon:KJ,NavigationOff:f2e,NavigationOffIcon:f2e,Network:p2e,NetworkIcon:p2e,Newspaper:nk,NewspaperIcon:nk,Nfc:g2e,NfcIcon:g2e,Notebook:b2e,NotebookIcon:b2e,NotebookPen:x2e,NotebookPenIcon:x2e,NotebookTabs:y2e,NotebookTabsIcon:y2e,NotebookText:v2e,NotebookTextIcon:v2e,NotepadText:w2e,NotepadTextDashed:_2e,NotepadTextDashedIcon:_2e,NotepadTextIcon:w2e,Nut:N2e,NutIcon:N2e,NutOff:j2e,NutOffIcon:j2e,Octagon:S2e,OctagonAlert:BS,OctagonAlertIcon:BS,OctagonIcon:S2e,OctagonMinus:k2e,OctagonMinusIcon:k2e,OctagonPause:iF,OctagonPauseIcon:iF,OctagonX:oF,OctagonXIcon:oF,Omega:C2e,OmegaIcon:C2e,Option:A2e,OptionIcon:A2e,Orbit:E2e,OrbitIcon:E2e,Origami:T2e,OrigamiIcon:T2e,Outdent:JD,OutdentIcon:JD,Package:vm,Package2:M2e,Package2Icon:M2e,PackageCheck:P2e,PackageCheckIcon:P2e,PackageIcon:vm,PackageMinus:I2e,PackageMinusIcon:I2e,PackageOpen:L2e,PackageOpenIcon:L2e,PackagePlus:R2e,PackagePlusIcon:R2e,PackageSearch:D2e,PackageSearchIcon:D2e,PackageX:F2e,PackageXIcon:F2e,PaintBucket:O2e,PaintBucketIcon:O2e,PaintRoller:z2e,PaintRollerIcon:z2e,Paintbrush:B2e,Paintbrush2:lF,Paintbrush2Icon:lF,PaintbrushIcon:B2e,PaintbrushVertical:lF,PaintbrushVerticalIcon:lF,Palette:Yc,PaletteIcon:Yc,Palmtree:kO,PalmtreeIcon:kO,PanelBottom:q2e,PanelBottomClose:$2e,PanelBottomCloseIcon:$2e,PanelBottomDashed:cF,PanelBottomDashedIcon:cF,PanelBottomIcon:q2e,PanelBottomInactive:cF,PanelBottomInactiveIcon:cF,PanelBottomOpen:U2e,PanelBottomOpenIcon:U2e,PanelLeft:mF,PanelLeftClose:dF,PanelLeftCloseIcon:dF,PanelLeftDashed:uF,PanelLeftDashedIcon:uF,PanelLeftIcon:mF,PanelLeftInactive:uF,PanelLeftInactiveIcon:uF,PanelLeftOpen:hF,PanelLeftOpenIcon:hF,PanelRight:G2e,PanelRightClose:V2e,PanelRightCloseIcon:V2e,PanelRightDashed:fF,PanelRightDashedIcon:fF,PanelRightIcon:G2e,PanelRightInactive:fF,PanelRightInactiveIcon:fF,PanelRightOpen:H2e,PanelRightOpenIcon:H2e,PanelTop:Y2e,PanelTopClose:W2e,PanelTopCloseIcon:W2e,PanelTopDashed:pF,PanelTopDashedIcon:pF,PanelTopIcon:Y2e,PanelTopInactive:pF,PanelTopInactiveIcon:pF,PanelTopOpen:K2e,PanelTopOpenIcon:K2e,PanelsLeftBottom:Z2e,PanelsLeftBottomIcon:Z2e,PanelsLeftRight:oP,PanelsLeftRightIcon:oP,PanelsRightBottom:X2e,PanelsRightBottomIcon:X2e,PanelsTopBottom:bF,PanelsTopBottomIcon:bF,PanelsTopLeft:DA,PanelsTopLeftIcon:DA,Paperclip:QI,PaperclipIcon:QI,Parentheses:Q2e,ParenthesesIcon:Q2e,ParkingCircle:ND,ParkingCircleIcon:ND,ParkingCircleOff:jD,ParkingCircleOffIcon:jD,ParkingMeter:J2e,ParkingMeterIcon:J2e,ParkingSquare:iO,ParkingSquareIcon:iO,ParkingSquareOff:aO,ParkingSquareOffIcon:aO,PartyPopper:Ax,PartyPopperIcon:Ax,Pause:Tv,PauseCircle:kD,PauseCircleIcon:kD,PauseIcon:Tv,PauseOctagon:iF,PauseOctagonIcon:iF,PawPrint:eNe,PawPrintIcon:eNe,PcCase:tNe,PcCaseIcon:tNe,Pen:LN,PenBox:_p,PenBoxIcon:_p,PenIcon:LN,PenLine:wf,PenLineIcon:wf,PenOff:sNe,PenOffIcon:sNe,PenSquare:_p,PenSquareIcon:_p,PenTool:RE,PenToolIcon:RE,Pencil:gi,PencilIcon:gi,PencilLine:Xq,PencilLineIcon:Xq,PencilOff:nNe,PencilOffIcon:nNe,PencilRuler:rNe,PencilRulerIcon:rNe,Pentagon:aNe,PentagonIcon:aNe,Percent:Rw,PercentCircle:SD,PercentCircleIcon:SD,PercentDiamond:OD,PercentDiamondIcon:OD,PercentIcon:Rw,PercentSquare:oO,PercentSquareIcon:oO,PersonStanding:iNe,PersonStandingIcon:iNe,PhilippinePeso:oNe,PhilippinePesoIcon:oNe,Phone:Da,PhoneCall:YJ,PhoneCallIcon:YJ,PhoneForwarded:lNe,PhoneForwardedIcon:lNe,PhoneIcon:Da,PhoneIncoming:cNe,PhoneIncomingIcon:cNe,PhoneMissed:dNe,PhoneMissedIcon:dNe,PhoneOff:uNe,PhoneOffIcon:uNe,PhoneOutgoing:hNe,PhoneOutgoingIcon:hNe,Pi:mNe,PiIcon:mNe,PiSquare:lO,PiSquareIcon:lO,Piano:fNe,PianoIcon:fNe,Pickaxe:pNe,PickaxeIcon:pNe,PictureInPicture:xNe,PictureInPicture2:gNe,PictureInPicture2Icon:gNe,PictureInPictureIcon:xNe,PieChart:iD,PieChartIcon:iD,PiggyBank:ZJ,PiggyBankIcon:ZJ,Pilcrow:bNe,PilcrowIcon:bNe,PilcrowLeft:yNe,PilcrowLeftIcon:yNe,PilcrowRight:vNe,PilcrowRightIcon:vNe,PilcrowSquare:cO,PilcrowSquareIcon:cO,Pill:wNe,PillBottle:_Ne,PillBottleIcon:_Ne,PillIcon:wNe,Pin:DE,PinIcon:DE,PinOff:XJ,PinOffIcon:XJ,Pipette:jNe,PipetteIcon:jNe,Pizza:NNe,PizzaIcon:NNe,Plane:QJ,PlaneIcon:QJ,PlaneLanding:kNe,PlaneLandingIcon:kNe,PlaneTakeoff:SNe,PlaneTakeoffIcon:SNe,Play:Bu,PlayCircle:tf,PlayCircleIcon:tf,PlayIcon:Bu,PlaySquare:dO,PlaySquareIcon:dO,Plug:g2,Plug2:CNe,Plug2Icon:CNe,PlugIcon:g2,PlugZap:gF,PlugZap2:gF,PlugZap2Icon:gF,PlugZapIcon:gF,Plus:dn,PlusCircle:CD,PlusCircleIcon:CD,PlusIcon:dn,PlusSquare:uO,PlusSquareIcon:uO,Pocket:ENe,PocketIcon:ENe,PocketKnife:ANe,PocketKnifeIcon:ANe,Podcast:TNe,PodcastIcon:TNe,Pointer:PNe,PointerIcon:PNe,PointerOff:MNe,PointerOffIcon:MNe,Popcorn:INe,PopcornIcon:INe,Popsicle:LNe,PopsicleIcon:LNe,PoundSterling:RNe,PoundSterlingIcon:RNe,Power:JJ,PowerCircle:AD,PowerCircleIcon:AD,PowerIcon:JJ,PowerOff:DNe,PowerOffIcon:DNe,PowerSquare:hO,PowerSquareIcon:hO,Presentation:jb,PresentationIcon:jb,Printer:FE,PrinterCheck:FNe,PrinterCheckIcon:FNe,PrinterIcon:FE,Projector:ONe,ProjectorIcon:ONe,Proportions:zNe,ProportionsIcon:zNe,Puzzle:BNe,PuzzleIcon:BNe,Pyramid:$Ne,PyramidIcon:$Ne,QrCode:Jp,QrCodeIcon:Jp,Quote:x2,QuoteIcon:x2,Rabbit:UNe,RabbitIcon:UNe,Radar:Qq,RadarIcon:Qq,Radiation:qNe,RadiationIcon:qNe,Radical:VNe,RadicalIcon:VNe,Radio:Nb,RadioIcon:Nb,RadioReceiver:HNe,RadioReceiverIcon:HNe,RadioTower:GNe,RadioTowerIcon:GNe,Radius:WNe,RadiusIcon:WNe,RailSymbol:KNe,RailSymbolIcon:KNe,Rainbow:YNe,RainbowIcon:YNe,Rat:ZNe,RatIcon:ZNe,Ratio:XNe,RatioIcon:XNe,Receipt:Jq,ReceiptCent:QNe,ReceiptCentIcon:QNe,ReceiptEuro:JNe,ReceiptEuroIcon:JNe,ReceiptIcon:Jq,ReceiptIndianRupee:eke,ReceiptIndianRupeeIcon:eke,ReceiptJapaneseYen:tke,ReceiptJapaneseYenIcon:tke,ReceiptPoundSterling:ske,ReceiptPoundSterlingIcon:ske,ReceiptRussianRuble:nke,ReceiptRussianRubleIcon:nke,ReceiptSwissFranc:rke,ReceiptSwissFrancIcon:rke,ReceiptText:ake,ReceiptTextIcon:ake,RectangleEllipsis:xF,RectangleEllipsisIcon:xF,RectangleHorizontal:ike,RectangleHorizontalIcon:ike,RectangleVertical:oke,RectangleVerticalIcon:oke,Recycle:lke,RecycleIcon:lke,Redo:OE,Redo2:cke,Redo2Icon:cke,RedoDot:dke,RedoDotIcon:dke,RedoIcon:OE,RefreshCcw:eV,RefreshCcwDot:uke,RefreshCcwDotIcon:uke,RefreshCcwIcon:eV,RefreshCw:ro,RefreshCwIcon:ro,RefreshCwOff:hke,RefreshCwOffIcon:hke,Refrigerator:mke,RefrigeratorIcon:mke,Regex:fke,RegexIcon:fke,RemoveFormatting:pke,RemoveFormattingIcon:pke,Repeat:zE,Repeat1:gke,Repeat1Icon:gke,Repeat2:eee,Repeat2Icon:eee,RepeatIcon:zE,Replace:yke,ReplaceAll:xke,ReplaceAllIcon:xke,ReplaceIcon:yke,Reply:tV,ReplyAll:vke,ReplyAllIcon:vke,ReplyIcon:tV,Rewind:bke,RewindIcon:bke,Ribbon:_ke,RibbonIcon:_ke,Rocket:qg,RocketIcon:qg,RockingChair:wke,RockingChairIcon:wke,RollerCoaster:jke,RollerCoasterIcon:jke,Rotate3D:yF,Rotate3DIcon:yF,Rotate3d:yF,Rotate3dIcon:yF,RotateCcw:Ex,RotateCcwIcon:Ex,RotateCcwSquare:Nke,RotateCcwSquareIcon:Nke,RotateCw:e7,RotateCwIcon:e7,RotateCwSquare:kke,RotateCwSquareIcon:kke,Route:sV,RouteIcon:sV,RouteOff:Ske,RouteOffIcon:Ske,Router:Cke,RouterIcon:Cke,Rows:vF,Rows2:vF,Rows2Icon:vF,Rows3:bF,Rows3Icon:bF,Rows4:Ake,Rows4Icon:Ake,RowsIcon:vF,Rss:Eke,RssIcon:Eke,Ruler:R4,RulerIcon:R4,RussianRuble:Tke,RussianRubleIcon:Tke,Sailboat:Mke,SailboatIcon:Mke,Salad:Pke,SaladIcon:Pke,Sandwich:Ike,SandwichIcon:Ike,Satellite:Rke,SatelliteDish:Lke,SatelliteDishIcon:Lke,SatelliteIcon:Rke,Save:tl,SaveAll:Dke,SaveAllIcon:Dke,SaveIcon:tl,SaveOff:Fke,SaveOffIcon:Fke,Scale:Oke,Scale3D:_F,Scale3DIcon:_F,Scale3d:_F,Scale3dIcon:_F,ScaleIcon:Oke,Scaling:zke,ScalingIcon:zke,Scan:Wke,ScanBarcode:Bke,ScanBarcodeIcon:Bke,ScanEye:$ke,ScanEyeIcon:$ke,ScanFace:Uke,ScanFaceIcon:Uke,ScanIcon:Wke,ScanLine:qke,ScanLineIcon:qke,ScanQrCode:Vke,ScanQrCodeIcon:Vke,ScanSearch:Hke,ScanSearchIcon:Hke,ScanText:Gke,ScanTextIcon:Gke,ScatterChart:oD,ScatterChartIcon:oD,School:Kke,School2:CO,School2Icon:CO,SchoolIcon:Kke,Scissors:Zke,ScissorsIcon:Zke,ScissorsLineDashed:Yke,ScissorsLineDashedIcon:Yke,ScissorsSquare:mO,ScissorsSquareDashedBottom:zF,ScissorsSquareDashedBottomIcon:zF,ScissorsSquareIcon:mO,ScreenShare:Qke,ScreenShareIcon:Qke,ScreenShareOff:Xke,ScreenShareOffIcon:Xke,Scroll:Jke,ScrollIcon:Jke,ScrollText:nV,ScrollTextIcon:nV,Search:Kr,SearchCheck:eSe,SearchCheckIcon:eSe,SearchCode:tSe,SearchCodeIcon:tSe,SearchIcon:Kr,SearchSlash:sSe,SearchSlashIcon:sSe,SearchX:rV,SearchXIcon:rV,Section:nSe,SectionIcon:nSe,Send:Yr,SendHorizonal:wF,SendHorizonalIcon:wF,SendHorizontal:wF,SendHorizontalIcon:wF,SendIcon:Yr,SendToBack:rSe,SendToBackIcon:rSe,SeparatorHorizontal:aSe,SeparatorHorizontalIcon:aSe,SeparatorVertical:iSe,SeparatorVerticalIcon:iSe,Server:dSe,ServerCog:oSe,ServerCogIcon:oSe,ServerCrash:lSe,ServerCrashIcon:lSe,ServerIcon:dSe,ServerOff:cSe,ServerOffIcon:cSe,Settings:Sd,Settings2:sC,Settings2Icon:sC,SettingsIcon:Sd,Shapes:uSe,ShapesIcon:uSe,Share:tee,Share2:zd,Share2Icon:zd,ShareIcon:tee,Sheet:hSe,SheetIcon:hSe,Shell:mSe,ShellIcon:mSe,Shield:Mf,ShieldAlert:aV,ShieldAlertIcon:aV,ShieldBan:fSe,ShieldBanIcon:fSe,ShieldCheck:bm,ShieldCheckIcon:bm,ShieldClose:jF,ShieldCloseIcon:jF,ShieldEllipsis:pSe,ShieldEllipsisIcon:pSe,ShieldHalf:gSe,ShieldHalfIcon:gSe,ShieldIcon:Mf,ShieldMinus:xSe,ShieldMinusIcon:xSe,ShieldOff:t7,ShieldOffIcon:t7,ShieldPlus:ySe,ShieldPlusIcon:ySe,ShieldQuestion:s7,ShieldQuestionIcon:s7,ShieldX:jF,ShieldXIcon:jF,Ship:bSe,ShipIcon:bSe,ShipWheel:vSe,ShipWheelIcon:vSe,Shirt:_Se,ShirtIcon:_Se,ShoppingBag:D4,ShoppingBagIcon:D4,ShoppingBasket:wSe,ShoppingBasketIcon:wSe,ShoppingCart:nC,ShoppingCartIcon:nC,Shovel:jSe,ShovelIcon:jSe,ShowerHead:NSe,ShowerHeadIcon:NSe,Shrink:kSe,ShrinkIcon:kSe,Shrub:SSe,ShrubIcon:SSe,Shuffle:n7,ShuffleIcon:n7,Sidebar:mF,SidebarClose:dF,SidebarCloseIcon:dF,SidebarIcon:mF,SidebarOpen:hF,SidebarOpenIcon:hF,Sigma:CSe,SigmaIcon:CSe,SigmaSquare:fO,SigmaSquareIcon:fO,Signal:PSe,SignalHigh:ASe,SignalHighIcon:ASe,SignalIcon:PSe,SignalLow:ESe,SignalLowIcon:ESe,SignalMedium:TSe,SignalMediumIcon:TSe,SignalZero:MSe,SignalZeroIcon:MSe,Signature:ISe,SignatureIcon:ISe,Signpost:see,SignpostBig:LSe,SignpostBigIcon:LSe,SignpostIcon:see,Siren:RSe,SirenIcon:RSe,SkipBack:DSe,SkipBackIcon:DSe,SkipForward:nee,SkipForwardIcon:nee,Skull:FSe,SkullIcon:FSe,Slack:OSe,SlackIcon:OSe,Slash:zSe,SlashIcon:zSe,SlashSquare:pO,SlashSquareIcon:pO,Slice:BSe,SliceIcon:BSe,Sliders:NF,SlidersHorizontal:JI,SlidersHorizontalIcon:JI,SlidersIcon:NF,SlidersVertical:NF,SlidersVerticalIcon:NF,Smartphone:_1,SmartphoneCharging:$Se,SmartphoneChargingIcon:$Se,SmartphoneIcon:_1,SmartphoneNfc:USe,SmartphoneNfcIcon:USe,Smile:VSe,SmileIcon:VSe,SmilePlus:qSe,SmilePlusIcon:qSe,Snail:HSe,SnailIcon:HSe,Snowflake:t2,SnowflakeIcon:t2,Sofa:iV,SofaIcon:iV,SortAsc:qR,SortAscIcon:qR,SortDesc:BR,SortDescIcon:BR,Soup:GSe,SoupIcon:GSe,Space:WSe,SpaceIcon:WSe,Spade:KSe,SpadeIcon:KSe,Sparkle:eL,SparkleIcon:eL,Sparkles:Nn,SparklesIcon:Nn,Speaker:YSe,SpeakerIcon:YSe,Speech:ZSe,SpeechIcon:ZSe,SpellCheck:QSe,SpellCheck2:XSe,SpellCheck2Icon:XSe,SpellCheckIcon:QSe,Spline:JSe,SplineIcon:JSe,Split:eCe,SplitIcon:eCe,SplitSquareHorizontal:gO,SplitSquareHorizontalIcon:gO,SplitSquareVertical:xO,SplitSquareVerticalIcon:xO,SprayCan:tCe,SprayCanIcon:tCe,Sprout:tL,SproutIcon:tL,Square:C_,SquareActivity:kF,SquareActivityIcon:kF,SquareArrowDown:AF,SquareArrowDownIcon:AF,SquareArrowDownLeft:SF,SquareArrowDownLeftIcon:SF,SquareArrowDownRight:CF,SquareArrowDownRightIcon:CF,SquareArrowLeft:EF,SquareArrowLeftIcon:EF,SquareArrowOutDownLeft:TF,SquareArrowOutDownLeftIcon:TF,SquareArrowOutDownRight:MF,SquareArrowOutDownRightIcon:MF,SquareArrowOutUpLeft:PF,SquareArrowOutUpLeftIcon:PF,SquareArrowOutUpRight:IF,SquareArrowOutUpRightIcon:IF,SquareArrowRight:LF,SquareArrowRightIcon:LF,SquareArrowUp:FF,SquareArrowUpIcon:FF,SquareArrowUpLeft:RF,SquareArrowUpLeftIcon:RF,SquareArrowUpRight:DF,SquareArrowUpRightIcon:DF,SquareAsterisk:OF,SquareAsteriskIcon:OF,SquareBottomDashedScissors:zF,SquareBottomDashedScissorsIcon:zF,SquareChartGantt:x5,SquareChartGanttIcon:x5,SquareCheck:BF,SquareCheckBig:Kj,SquareCheckBigIcon:Kj,SquareCheckIcon:BF,SquareChevronDown:$F,SquareChevronDownIcon:$F,SquareChevronLeft:UF,SquareChevronLeftIcon:UF,SquareChevronRight:qF,SquareChevronRightIcon:qF,SquareChevronUp:VF,SquareChevronUpIcon:VF,SquareCode:HF,SquareCodeIcon:HF,SquareDashed:KF,SquareDashedBottom:nCe,SquareDashedBottomCode:sCe,SquareDashedBottomCodeIcon:sCe,SquareDashedBottomIcon:nCe,SquareDashedIcon:KF,SquareDashedKanban:GF,SquareDashedKanbanIcon:GF,SquareDashedMousePointer:WF,SquareDashedMousePointerIcon:WF,SquareDivide:YF,SquareDivideIcon:YF,SquareDot:ZF,SquareDotIcon:ZF,SquareEqual:XF,SquareEqualIcon:XF,SquareFunction:QF,SquareFunctionIcon:QF,SquareGanttChart:x5,SquareGanttChartIcon:x5,SquareIcon:C_,SquareKanban:JF,SquareKanbanIcon:JF,SquareLibrary:eO,SquareLibraryIcon:eO,SquareM:tO,SquareMIcon:tO,SquareMenu:sO,SquareMenuIcon:sO,SquareMinus:nO,SquareMinusIcon:nO,SquareMousePointer:rO,SquareMousePointerIcon:rO,SquareParking:iO,SquareParkingIcon:iO,SquareParkingOff:aO,SquareParkingOffIcon:aO,SquarePen:_p,SquarePenIcon:_p,SquarePercent:oO,SquarePercentIcon:oO,SquarePi:lO,SquarePiIcon:lO,SquarePilcrow:cO,SquarePilcrowIcon:cO,SquarePlay:dO,SquarePlayIcon:dO,SquarePlus:uO,SquarePlusIcon:uO,SquarePower:hO,SquarePowerIcon:hO,SquareRadical:rCe,SquareRadicalIcon:rCe,SquareScissors:mO,SquareScissorsIcon:mO,SquareSigma:fO,SquareSigmaIcon:fO,SquareSlash:pO,SquareSlashIcon:pO,SquareSplitHorizontal:gO,SquareSplitHorizontalIcon:gO,SquareSplitVertical:xO,SquareSplitVerticalIcon:xO,SquareSquare:aCe,SquareSquareIcon:aCe,SquareStack:iCe,SquareStackIcon:iCe,SquareTerminal:yO,SquareTerminalIcon:yO,SquareUser:bO,SquareUserIcon:bO,SquareUserRound:vO,SquareUserRoundIcon:vO,SquareX:_O,SquareXIcon:_O,Squircle:oCe,SquircleIcon:oCe,Squirrel:lCe,SquirrelIcon:lCe,Stamp:cCe,StampIcon:cCe,Star:Ja,StarHalf:dCe,StarHalfIcon:dCe,StarIcon:Ja,StarOff:uCe,StarOffIcon:uCe,Stars:Nn,StarsIcon:Nn,StepBack:hCe,StepBackIcon:hCe,StepForward:mCe,StepForwardIcon:mCe,Stethoscope:fCe,StethoscopeIcon:fCe,Sticker:pCe,StickerIcon:pCe,StickyNote:r7,StickyNoteIcon:r7,StopCircle:TD,StopCircleIcon:TD,Store:oV,StoreIcon:oV,StretchHorizontal:gCe,StretchHorizontalIcon:gCe,StretchVertical:xCe,StretchVerticalIcon:xCe,Strikethrough:ree,StrikethroughIcon:ree,Subscript:yCe,SubscriptIcon:yCe,Subtitles:YR,SubtitlesIcon:YR,Sun:rk,SunDim:vCe,SunDimIcon:vCe,SunIcon:rk,SunMedium:bCe,SunMediumIcon:bCe,SunMoon:_Ce,SunMoonIcon:_Ce,SunSnow:wCe,SunSnowIcon:wCe,Sunrise:jCe,SunriseIcon:jCe,Sunset:NCe,SunsetIcon:NCe,Superscript:kCe,SuperscriptIcon:kCe,SwatchBook:SCe,SwatchBookIcon:SCe,SwissFranc:CCe,SwissFrancIcon:CCe,SwitchCamera:ACe,SwitchCameraIcon:ACe,Sword:ECe,SwordIcon:ECe,Swords:TCe,SwordsIcon:TCe,Syringe:MCe,SyringeIcon:MCe,Table:cV,Table2:lV,Table2Icon:lV,TableCellsMerge:PCe,TableCellsMergeIcon:PCe,TableCellsSplit:ICe,TableCellsSplitIcon:ICe,TableColumnsSplit:LCe,TableColumnsSplitIcon:LCe,TableIcon:cV,TableOfContents:RCe,TableOfContentsIcon:RCe,TableProperties:DCe,TablePropertiesIcon:DCe,TableRowsSplit:FCe,TableRowsSplitIcon:FCe,Tablet:dV,TabletIcon:dV,TabletSmartphone:OCe,TabletSmartphoneIcon:OCe,Tablets:zCe,TabletsIcon:zCe,Tag:Ap,TagIcon:Ap,Tags:aee,TagsIcon:aee,Tally1:BCe,Tally1Icon:BCe,Tally2:$Ce,Tally2Icon:$Ce,Tally3:UCe,Tally3Icon:UCe,Tally4:qCe,Tally4Icon:qCe,Tally5:VCe,Tally5Icon:VCe,Tangent:HCe,TangentIcon:HCe,Target:rh,TargetIcon:rh,Telescope:GCe,TelescopeIcon:GCe,Tent:KCe,TentIcon:KCe,TentTree:WCe,TentTreeIcon:WCe,Terminal:YCe,TerminalIcon:YCe,TerminalSquare:yO,TerminalSquareIcon:yO,TestTube:ZCe,TestTube2:wO,TestTube2Icon:wO,TestTubeDiagonal:wO,TestTubeDiagonalIcon:wO,TestTubeIcon:ZCe,TestTubes:XCe,TestTubesIcon:XCe,Text:t5e,TextCursor:QCe,TextCursorIcon:QCe,TextCursorInput:uV,TextCursorInputIcon:uV,TextIcon:t5e,TextQuote:JCe,TextQuoteIcon:JCe,TextSearch:e5e,TextSearchIcon:e5e,TextSelect:jO,TextSelectIcon:jO,TextSelection:jO,TextSelectionIcon:jO,Theater:s5e,TheaterIcon:s5e,Thermometer:a5e,ThermometerIcon:a5e,ThermometerSnowflake:n5e,ThermometerSnowflakeIcon:n5e,ThermometerSun:r5e,ThermometerSunIcon:r5e,ThumbsDown:iee,ThumbsDownIcon:iee,ThumbsUp:Vy,ThumbsUpIcon:Vy,Ticket:a7,TicketCheck:i5e,TicketCheckIcon:i5e,TicketIcon:a7,TicketMinus:o5e,TicketMinusIcon:o5e,TicketPercent:l5e,TicketPercentIcon:l5e,TicketPlus:c5e,TicketPlusIcon:c5e,TicketSlash:d5e,TicketSlashIcon:d5e,TicketX:u5e,TicketXIcon:u5e,Tickets:m5e,TicketsIcon:m5e,TicketsPlane:h5e,TicketsPlaneIcon:h5e,Timer:g5e,TimerIcon:g5e,TimerOff:f5e,TimerOffIcon:f5e,TimerReset:p5e,TimerResetIcon:p5e,ToggleLeft:x5e,ToggleLeftIcon:x5e,ToggleRight:y5e,ToggleRightIcon:y5e,Toilet:v5e,ToiletIcon:v5e,Tornado:b5e,TornadoIcon:b5e,Torus:_5e,TorusIcon:_5e,Touchpad:j5e,TouchpadIcon:j5e,TouchpadOff:w5e,TouchpadOffIcon:w5e,TowerControl:N5e,TowerControlIcon:N5e,ToyBrick:k5e,ToyBrickIcon:k5e,Tractor:S5e,TractorIcon:S5e,TrafficCone:C5e,TrafficConeIcon:C5e,Train:NO,TrainFront:E5e,TrainFrontIcon:E5e,TrainFrontTunnel:A5e,TrainFrontTunnelIcon:A5e,TrainIcon:NO,TrainTrack:T5e,TrainTrackIcon:T5e,TramFront:NO,TramFrontIcon:NO,Trash:M5e,Trash2:Wn,Trash2Icon:Wn,TrashIcon:M5e,TreeDeciduous:P5e,TreeDeciduousIcon:P5e,TreePalm:kO,TreePalmIcon:kO,TreePine:sL,TreePineIcon:sL,Trees:I5e,TreesIcon:I5e,Trello:L5e,TrelloIcon:L5e,TrendingDown:rC,TrendingDownIcon:rC,TrendingUp:Yl,TrendingUpDown:R5e,TrendingUpDownIcon:R5e,TrendingUpIcon:Yl,Triangle:F5e,TriangleAlert:wl,TriangleAlertIcon:wl,TriangleIcon:F5e,TriangleRight:D5e,TriangleRightIcon:D5e,Trophy:Kl,TrophyIcon:Kl,Truck:oee,TruckIcon:oee,Turtle:O5e,TurtleIcon:O5e,Tv:B5e,Tv2:SO,Tv2Icon:SO,TvIcon:B5e,TvMinimal:SO,TvMinimalIcon:SO,TvMinimalPlay:z5e,TvMinimalPlayIcon:z5e,Twitch:$5e,TwitchIcon:$5e,Twitter:lee,TwitterIcon:lee,Type:hV,TypeIcon:hV,TypeOutline:U5e,TypeOutlineIcon:U5e,Umbrella:V5e,UmbrellaIcon:V5e,UmbrellaOff:q5e,UmbrellaOffIcon:q5e,Underline:i7,UnderlineIcon:i7,Undo:BE,Undo2:cee,Undo2Icon:cee,UndoDot:H5e,UndoDotIcon:H5e,UndoIcon:BE,UnfoldHorizontal:G5e,UnfoldHorizontalIcon:G5e,UnfoldVertical:W5e,UnfoldVerticalIcon:W5e,Ungroup:K5e,UngroupIcon:K5e,University:CO,UniversityIcon:CO,Unlink:$E,Unlink2:Y5e,Unlink2Icon:Y5e,UnlinkIcon:$E,Unlock:nF,UnlockIcon:nF,UnlockKeyhole:sF,UnlockKeyholeIcon:sF,Unplug:o7,UnplugIcon:o7,Upload:ni,UploadCloud:iP,UploadCloudIcon:iP,UploadIcon:ni,Usb:Z5e,UsbIcon:Z5e,User:sl,User2:cP,User2Icon:cP,UserCheck:y2,UserCheck2:lP,UserCheck2Icon:lP,UserCheckIcon:y2,UserCircle:PD,UserCircle2:MD,UserCircle2Icon:MD,UserCircleIcon:PD,UserCog:dee,UserCog2:AO,UserCog2Icon:AO,UserCogIcon:dee,UserIcon:sl,UserMinus:mV,UserMinus2:EO,UserMinus2Icon:EO,UserMinusIcon:mV,UserPen:X5e,UserPenIcon:X5e,UserPlus:sc,UserPlus2:TO,UserPlus2Icon:TO,UserPlusIcon:sc,UserRound:cP,UserRoundCheck:lP,UserRoundCheckIcon:lP,UserRoundCog:AO,UserRoundCogIcon:AO,UserRoundIcon:cP,UserRoundMinus:EO,UserRoundMinusIcon:EO,UserRoundPen:Q5e,UserRoundPenIcon:Q5e,UserRoundPlus:TO,UserRoundPlusIcon:TO,UserRoundSearch:fV,UserRoundSearchIcon:fV,UserRoundX:MO,UserRoundXIcon:MO,UserSearch:J5e,UserSearchIcon:J5e,UserSquare:bO,UserSquare2:vO,UserSquare2Icon:vO,UserSquareIcon:bO,UserX:pV,UserX2:MO,UserX2Icon:MO,UserXIcon:pV,Users:Zn,Users2:v0,Users2Icon:v0,UsersIcon:Zn,UsersRound:v0,UsersRoundIcon:v0,Utensils:IO,UtensilsCrossed:PO,UtensilsCrossedIcon:PO,UtensilsIcon:IO,UtilityPole:e4e,UtilityPoleIcon:e4e,Variable:gV,VariableIcon:gV,Vault:t4e,VaultIcon:t4e,Vegan:s4e,VeganIcon:s4e,VenetianMask:n4e,VenetianMaskIcon:n4e,Verified:RA,VerifiedIcon:RA,Vibrate:a4e,VibrateIcon:a4e,VibrateOff:r4e,VibrateOffIcon:r4e,Video:ua,VideoIcon:ua,VideoOff:i4e,VideoOffIcon:i4e,Videotape:o4e,VideotapeIcon:o4e,View:l4e,ViewIcon:l4e,Voicemail:c4e,VoicemailIcon:c4e,Volleyball:d4e,VolleyballIcon:d4e,Volume:m4e,Volume1:u4e,Volume1Icon:u4e,Volume2:uee,Volume2Icon:uee,VolumeIcon:m4e,VolumeOff:h4e,VolumeOffIcon:h4e,VolumeX:hee,VolumeXIcon:hee,Vote:f4e,VoteIcon:f4e,Wallet:l7,Wallet2:LO,Wallet2Icon:LO,WalletCards:p4e,WalletCardsIcon:p4e,WalletIcon:l7,WalletMinimal:LO,WalletMinimalIcon:LO,Wallpaper:g4e,WallpaperIcon:g4e,Wand:x4e,Wand2:sy,Wand2Icon:sy,WandIcon:x4e,WandSparkles:sy,WandSparklesIcon:sy,Warehouse:y4e,WarehouseIcon:y4e,WashingMachine:v4e,WashingMachineIcon:v4e,Watch:b4e,WatchIcon:b4e,Waves:_4e,WavesIcon:_4e,Waypoints:w4e,WaypointsIcon:w4e,Webcam:j4e,WebcamIcon:j4e,Webhook:k4e,WebhookIcon:k4e,WebhookOff:N4e,WebhookOffIcon:N4e,Weight:S4e,WeightIcon:S4e,Wheat:A4e,WheatIcon:A4e,WheatOff:C4e,WheatOffIcon:C4e,WholeWord:E4e,WholeWordIcon:E4e,Wifi:L4e,WifiHigh:T4e,WifiHighIcon:T4e,WifiIcon:L4e,WifiLow:M4e,WifiLowIcon:M4e,WifiOff:P4e,WifiOffIcon:P4e,WifiZero:I4e,WifiZeroIcon:I4e,Wind:D4e,WindArrowDown:R4e,WindArrowDownIcon:R4e,WindIcon:D4e,Wine:O4e,WineIcon:O4e,WineOff:F4e,WineOffIcon:F4e,Workflow:c7,WorkflowIcon:c7,Worm:z4e,WormIcon:z4e,WrapText:B4e,WrapTextIcon:B4e,Wrench:F4,WrenchIcon:F4,X:gr,XCircle:ku,XCircleIcon:ku,XIcon:gr,XOctagon:oF,XOctagonIcon:oF,XSquare:_O,XSquareIcon:_O,Youtube:xV,YoutubeIcon:xV,Zap:eg,ZapIcon:eg,ZapOff:$4e,ZapOffIcon:$4e,ZoomIn:nL,ZoomInIcon:nL,ZoomOut:yV,ZoomOutIcon:yV,createLucideIcon:ge,icons:J0s},Symbol.toStringTag,{value:"Module"})),det="-",evs=s=>{const t=svs(s),{conflictingClassGroups:n,conflictingClassGroupModifiers:r}=s;return{getClassGroupId:l=>{const o=l.split(det);return o[0]===""&&o.length!==1&&o.shift(),ORt(o,t)||tvs(l)},getConflictingClassGroupIds:(l,o)=>{const c=n[l]||[];return o&&r[l]?[...c,...r[l]]:c}}},ORt=(s,t)=>{var l;if(s.length===0)return t.classGroupId;const n=s[0],r=t.nextPart.get(n),a=r?ORt(s.slice(1),r):void 0;if(a)return a;if(t.validators.length===0)return;const i=s.join(det);return(l=t.validators.find(({validator:o})=>o(i)))==null?void 0:l.classGroupId},wgt=/^\[(.+)\]$/,tvs=s=>{if(wgt.test(s)){const t=wgt.exec(s)[1],n=t==null?void 0:t.substring(0,t.indexOf(":"));if(n)return"arbitrary.."+n}},svs=s=>{const{theme:t,prefix:n}=s,r={nextPart:new Map,validators:[]};return rvs(Object.entries(s.classGroups),n).forEach(([i,l])=>{BVe(l,r,i,t)}),r},BVe=(s,t,n,r)=>{s.forEach(a=>{if(typeof a=="string"){const i=a===""?t:jgt(t,a);i.classGroupId=n;return}if(typeof a=="function"){if(nvs(a)){BVe(a(r),t,n,r);return}t.validators.push({validator:a,classGroupId:n});return}Object.entries(a).forEach(([i,l])=>{BVe(l,jgt(t,i),n,r)})})},jgt=(s,t)=>{let n=s;return t.split(det).forEach(r=>{n.nextPart.has(r)||n.nextPart.set(r,{nextPart:new Map,validators:[]}),n=n.nextPart.get(r)}),n},nvs=s=>s.isThemeGetter,rvs=(s,t)=>t?s.map(([n,r])=>{const a=r.map(i=>typeof i=="string"?t+i:typeof i=="object"?Object.fromEntries(Object.entries(i).map(([l,o])=>[t+l,o])):i);return[n,a]}):s,avs=s=>{if(s<1)return{get:()=>{},set:()=>{}};let t=0,n=new Map,r=new Map;const a=(i,l)=>{n.set(i,l),t++,t>s&&(t=0,r=n,n=new Map)};return{get(i){let l=n.get(i);if(l!==void 0)return l;if((l=r.get(i))!==void 0)return a(i,l),l},set(i,l){n.has(i)?n.set(i,l):a(i,l)}}},zRt="!",ivs=s=>{const{separator:t,experimentalParseClassName:n}=s,r=t.length===1,a=t[0],i=t.length,l=o=>{const c=[];let d=0,u=0,h;for(let y=0;yu?h-u:void 0;return{modifiers:c,hasImportantModifier:f,baseClassName:g,maybePostfixModifierPosition:x}};return n?o=>n({className:o,parseClassName:l}):l},ovs=s=>{if(s.length<=1)return s;const t=[];let n=[];return s.forEach(r=>{r[0]==="["?(t.push(...n.sort(),r),n=[]):n.push(r)}),t.push(...n.sort()),t},lvs=s=>({cache:avs(s.cacheSize),parseClassName:ivs(s),...evs(s)}),cvs=/\s+/,dvs=(s,t)=>{const{parseClassName:n,getClassGroupId:r,getConflictingClassGroupIds:a}=t,i=[],l=s.trim().split(cvs);let o="";for(let c=l.length-1;c>=0;c-=1){const d=l[c],{modifiers:u,hasImportantModifier:h,baseClassName:m,maybePostfixModifierPosition:f}=n(d);let g=!!f,x=r(g?m.substring(0,f):m);if(!x){if(!g){o=d+(o.length>0?" "+o:o);continue}if(x=r(m),!x){o=d+(o.length>0?" "+o:o);continue}g=!1}const y=ovs(u).join(":"),v=h?y+zRt:y,b=v+x;if(i.includes(b))continue;i.push(b);const w=a(x,g);for(let S=0;S0?" "+o:o)}return o};function uvs(){let s=0,t,n,r="";for(;s{if(typeof s=="string")return s;let t,n="";for(let r=0;rh(u),s());return n=lvs(d),r=n.cache.get,a=n.cache.set,i=o,o(c)}function o(c){const d=r(c);if(d)return d;const u=dvs(c,n);return a(c,u),u}return function(){return i(uvs.apply(null,arguments))}}const pp=s=>{const t=n=>n[s]||[];return t.isThemeGetter=!0,t},$Rt=/^\[(?:([a-z-]+):)?(.+)\]$/i,mvs=/^\d+\/\d+$/,fvs=new Set(["px","full","screen"]),pvs=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,gvs=/\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$/,xvs=/^(rgba?|hsla?|hwb|(ok)?(lab|lch)|color-mix)\(.+\)$/,yvs=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,vvs=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,Q3=s=>vV(s)||fvs.has(s)||mvs.test(s),yM=s=>HW(s,"length",Cvs),vV=s=>!!s&&!Number.isNaN(Number(s)),kze=s=>HW(s,"number",vV),vZ=s=>!!s&&Number.isInteger(Number(s)),bvs=s=>s.endsWith("%")&&vV(s.slice(0,-1)),Rd=s=>$Rt.test(s),vM=s=>pvs.test(s),_vs=new Set(["length","size","percentage"]),wvs=s=>HW(s,_vs,URt),jvs=s=>HW(s,"position",URt),Nvs=new Set(["image","url"]),kvs=s=>HW(s,Nvs,Evs),Svs=s=>HW(s,"",Avs),bZ=()=>!0,HW=(s,t,n)=>{const r=$Rt.exec(s);return r?r[1]?typeof t=="string"?r[1]===t:t.has(r[1]):n(r[2]):!1},Cvs=s=>gvs.test(s)&&!xvs.test(s),URt=()=>!1,Avs=s=>yvs.test(s),Evs=s=>vvs.test(s),Tvs=()=>{const s=pp("colors"),t=pp("spacing"),n=pp("blur"),r=pp("brightness"),a=pp("borderColor"),i=pp("borderRadius"),l=pp("borderSpacing"),o=pp("borderWidth"),c=pp("contrast"),d=pp("grayscale"),u=pp("hueRotate"),h=pp("invert"),m=pp("gap"),f=pp("gradientColorStops"),g=pp("gradientColorStopPositions"),x=pp("inset"),y=pp("margin"),v=pp("opacity"),b=pp("padding"),w=pp("saturate"),S=pp("scale"),C=pp("sepia"),E=pp("skew"),I=pp("space"),P=pp("translate"),R=()=>["auto","contain","none"],D=()=>["auto","hidden","clip","visible","scroll"],O=()=>["auto",Rd,t],U=()=>[Rd,t],W=()=>["",Q3,yM],V=()=>["auto",vV,Rd],G=()=>["bottom","center","left","left-bottom","left-top","right","right-bottom","right-top","top"],Y=()=>["solid","dashed","dotted","double","none"],X=()=>["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity"],ae=()=>["start","end","center","between","around","evenly","stretch"],ie=()=>["","0",Rd],ne=()=>["auto","avoid","all","avoid-page","page","left","right","column"],te=()=>[vV,Rd];return{cacheSize:500,separator:":",theme:{colors:[bZ],spacing:[Q3,yM],blur:["none","",vM,Rd],brightness:te(),borderColor:[s],borderRadius:["none","","full",vM,Rd],borderSpacing:U(),borderWidth:W(),contrast:te(),grayscale:ie(),hueRotate:te(),invert:ie(),gap:U(),gradientColorStops:[s],gradientColorStopPositions:[bvs,yM],inset:O(),margin:O(),opacity:te(),padding:U(),saturate:te(),scale:te(),sepia:ie(),skew:te(),space:U(),translate:U()},classGroups:{aspect:[{aspect:["auto","square","video",Rd]}],container:["container"],columns:[{columns:[vM]}],"break-after":[{"break-after":ne()}],"break-before":[{"break-before":ne()}],"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:[...G(),Rd]}],overflow:[{overflow:D()}],"overflow-x":[{"overflow-x":D()}],"overflow-y":[{"overflow-y":D()}],overscroll:[{overscroll:R()}],"overscroll-x":[{"overscroll-x":R()}],"overscroll-y":[{"overscroll-y":R()}],position:["static","fixed","absolute","relative","sticky"],inset:[{inset:[x]}],"inset-x":[{"inset-x":[x]}],"inset-y":[{"inset-y":[x]}],start:[{start:[x]}],end:[{end:[x]}],top:[{top:[x]}],right:[{right:[x]}],bottom:[{bottom:[x]}],left:[{left:[x]}],visibility:["visible","invisible","collapse"],z:[{z:["auto",vZ,Rd]}],basis:[{basis:O()}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["wrap","wrap-reverse","nowrap"]}],flex:[{flex:["1","auto","initial","none",Rd]}],grow:[{grow:ie()}],shrink:[{shrink:ie()}],order:[{order:["first","last","none",vZ,Rd]}],"grid-cols":[{"grid-cols":[bZ]}],"col-start-end":[{col:["auto",{span:["full",vZ,Rd]},Rd]}],"col-start":[{"col-start":V()}],"col-end":[{"col-end":V()}],"grid-rows":[{"grid-rows":[bZ]}],"row-start-end":[{row:["auto",{span:[vZ,Rd]},Rd]}],"row-start":[{"row-start":V()}],"row-end":[{"row-end":V()}],"grid-flow":[{"grid-flow":["row","col","dense","row-dense","col-dense"]}],"auto-cols":[{"auto-cols":["auto","min","max","fr",Rd]}],"auto-rows":[{"auto-rows":["auto","min","max","fr",Rd]}],gap:[{gap:[m]}],"gap-x":[{"gap-x":[m]}],"gap-y":[{"gap-y":[m]}],"justify-content":[{justify:["normal",...ae()]}],"justify-items":[{"justify-items":["start","end","center","stretch"]}],"justify-self":[{"justify-self":["auto","start","end","center","stretch"]}],"align-content":[{content:["normal",...ae(),"baseline"]}],"align-items":[{items:["start","end","center","baseline","stretch"]}],"align-self":[{self:["auto","start","end","center","stretch","baseline"]}],"place-content":[{"place-content":[...ae(),"baseline"]}],"place-items":[{"place-items":["start","end","center","baseline","stretch"]}],"place-self":[{"place-self":["auto","start","end","center","stretch"]}],p:[{p:[b]}],px:[{px:[b]}],py:[{py:[b]}],ps:[{ps:[b]}],pe:[{pe:[b]}],pt:[{pt:[b]}],pr:[{pr:[b]}],pb:[{pb:[b]}],pl:[{pl:[b]}],m:[{m:[y]}],mx:[{mx:[y]}],my:[{my:[y]}],ms:[{ms:[y]}],me:[{me:[y]}],mt:[{mt:[y]}],mr:[{mr:[y]}],mb:[{mb:[y]}],ml:[{ml:[y]}],"space-x":[{"space-x":[I]}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":[I]}],"space-y-reverse":["space-y-reverse"],w:[{w:["auto","min","max","fit","svw","lvw","dvw",Rd,t]}],"min-w":[{"min-w":[Rd,t,"min","max","fit"]}],"max-w":[{"max-w":[Rd,t,"none","full","min","max","fit","prose",{screen:[vM]},vM]}],h:[{h:[Rd,t,"auto","min","max","fit","svh","lvh","dvh"]}],"min-h":[{"min-h":[Rd,t,"min","max","fit","svh","lvh","dvh"]}],"max-h":[{"max-h":[Rd,t,"min","max","fit","svh","lvh","dvh"]}],size:[{size:[Rd,t,"auto","min","max","fit"]}],"font-size":[{text:["base",vM,yM]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:["thin","extralight","light","normal","medium","semibold","bold","extrabold","black",kze]}],"font-family":[{font:[bZ]}],"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",Rd]}],"line-clamp":[{"line-clamp":["none",vV,kze]}],leading:[{leading:["none","tight","snug","normal","relaxed","loose",Q3,Rd]}],"list-image":[{"list-image":["none",Rd]}],"list-style-type":[{list:["none","disc","decimal",Rd]}],"list-style-position":[{list:["inside","outside"]}],"placeholder-color":[{placeholder:[s]}],"placeholder-opacity":[{"placeholder-opacity":[v]}],"text-alignment":[{text:["left","center","right","justify","start","end"]}],"text-color":[{text:[s]}],"text-opacity":[{"text-opacity":[v]}],"text-decoration":["underline","overline","line-through","no-underline"],"text-decoration-style":[{decoration:[...Y(),"wavy"]}],"text-decoration-thickness":[{decoration:["auto","from-font",Q3,yM]}],"underline-offset":[{"underline-offset":["auto",Q3,Rd]}],"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:U()}],"vertical-align":[{align:["baseline","top","middle","bottom","text-top","text-bottom","sub","super",Rd]}],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",Rd]}],"bg-attachment":[{bg:["fixed","local","scroll"]}],"bg-clip":[{"bg-clip":["border","padding","content","text"]}],"bg-opacity":[{"bg-opacity":[v]}],"bg-origin":[{"bg-origin":["border","padding","content"]}],"bg-position":[{bg:[...G(),jvs]}],"bg-repeat":[{bg:["no-repeat",{repeat:["","x","y","round","space"]}]}],"bg-size":[{bg:["auto","cover","contain",wvs]}],"bg-image":[{bg:["none",{"gradient-to":["t","tr","r","br","b","bl","l","tl"]},kvs]}],"bg-color":[{bg:[s]}],"gradient-from-pos":[{from:[g]}],"gradient-via-pos":[{via:[g]}],"gradient-to-pos":[{to:[g]}],"gradient-from":[{from:[f]}],"gradient-via":[{via:[f]}],"gradient-to":[{to:[f]}],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":[v]}],"border-style":[{border:[...Y(),"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":[v]}],"divide-style":[{divide:Y()}],"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:["",...Y()]}],"outline-offset":[{"outline-offset":[Q3,Rd]}],"outline-w":[{outline:[Q3,yM]}],"outline-color":[{outline:[s]}],"ring-w":[{ring:W()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:[s]}],"ring-opacity":[{"ring-opacity":[v]}],"ring-offset-w":[{"ring-offset":[Q3,yM]}],"ring-offset-color":[{"ring-offset":[s]}],shadow:[{shadow:["","inner","none",vM,Svs]}],"shadow-color":[{shadow:[bZ]}],opacity:[{opacity:[v]}],"mix-blend":[{"mix-blend":[...X(),"plus-lighter","plus-darker"]}],"bg-blend":[{"bg-blend":X()}],filter:[{filter:["","none"]}],blur:[{blur:[n]}],brightness:[{brightness:[r]}],contrast:[{contrast:[c]}],"drop-shadow":[{"drop-shadow":["","none",vM,Rd]}],grayscale:[{grayscale:[d]}],"hue-rotate":[{"hue-rotate":[u]}],invert:[{invert:[h]}],saturate:[{saturate:[w]}],sepia:[{sepia:[C]}],"backdrop-filter":[{"backdrop-filter":["","none"]}],"backdrop-blur":[{"backdrop-blur":[n]}],"backdrop-brightness":[{"backdrop-brightness":[r]}],"backdrop-contrast":[{"backdrop-contrast":[c]}],"backdrop-grayscale":[{"backdrop-grayscale":[d]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[u]}],"backdrop-invert":[{"backdrop-invert":[h]}],"backdrop-opacity":[{"backdrop-opacity":[v]}],"backdrop-saturate":[{"backdrop-saturate":[w]}],"backdrop-sepia":[{"backdrop-sepia":[C]}],"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",Rd]}],duration:[{duration:te()}],ease:[{ease:["linear","in","out","in-out",Rd]}],delay:[{delay:te()}],animate:[{animate:["none","spin","ping","pulse","bounce",Rd]}],transform:[{transform:["","gpu","none"]}],scale:[{scale:[S]}],"scale-x":[{"scale-x":[S]}],"scale-y":[{"scale-y":[S]}],rotate:[{rotate:[vZ,Rd]}],"translate-x":[{"translate-x":[P]}],"translate-y":[{"translate-y":[P]}],"skew-x":[{"skew-x":[E]}],"skew-y":[{"skew-y":[E]}],"transform-origin":[{origin:["center","top","top-right","right","bottom-right","bottom","bottom-left","left","top-left",Rd]}],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",Rd]}],"caret-color":[{caret:[s]}],"pointer-events":[{"pointer-events":["none","auto"]}],resize:[{resize:["none","y","x",""]}],"scroll-behavior":[{scroll:["auto","smooth"]}],"scroll-m":[{"scroll-m":U()}],"scroll-mx":[{"scroll-mx":U()}],"scroll-my":[{"scroll-my":U()}],"scroll-ms":[{"scroll-ms":U()}],"scroll-me":[{"scroll-me":U()}],"scroll-mt":[{"scroll-mt":U()}],"scroll-mr":[{"scroll-mr":U()}],"scroll-mb":[{"scroll-mb":U()}],"scroll-ml":[{"scroll-ml":U()}],"scroll-p":[{"scroll-p":U()}],"scroll-px":[{"scroll-px":U()}],"scroll-py":[{"scroll-py":U()}],"scroll-ps":[{"scroll-ps":U()}],"scroll-pe":[{"scroll-pe":U()}],"scroll-pt":[{"scroll-pt":U()}],"scroll-pr":[{"scroll-pr":U()}],"scroll-pb":[{"scroll-pb":U()}],"scroll-pl":[{"scroll-pl":U()}],"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",Rd]}],fill:[{fill:[s,"none"]}],"stroke-w":[{stroke:[Q3,yM,kze]}],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"]}}},Mvs=hvs(Tvs);function Pt(...s){return Mvs(rd(s))}function Qm(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 Ngt(s){const t=new Date(s);return new Intl.DateTimeFormat("en-US",{month:"short",day:"numeric",year:"numeric"}).format(t)}function Vte(s){return s?s.replace(/<[^>]*>/g,""):""}const Pvs=Z0s,qRt=j.forwardRef(({className:s,...t},n)=>e.jsx(ERt,{ref:n,className:Pt("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}));qRt.displayName=ERt.displayName;const Ivs=DB("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"}}),VRt=j.forwardRef(({className:s,variant:t,...n},r)=>e.jsx(TRt,{ref:r,className:Pt(Ivs({variant:t}),s),...n}));VRt.displayName=TRt.displayName;const Lvs=j.forwardRef(({className:s,...t},n)=>e.jsx(IRt,{ref:n,className:Pt("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}));Lvs.displayName=IRt.displayName;const HRt=j.forwardRef(({className:s,...t},n)=>e.jsx(LRt,{ref:n,className:Pt("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(gr,{className:"h-4 w-4"})}));HRt.displayName=LRt.displayName;const GRt=j.forwardRef(({className:s,...t},n)=>e.jsx(MRt,{ref:n,className:Pt("text-sm font-semibold",s),...t}));GRt.displayName=MRt.displayName;const WRt=j.forwardRef(({className:s,...t},n)=>e.jsx(PRt,{ref:n,className:Pt("text-sm opacity-90",s),...t}));WRt.displayName=PRt.displayName;function Rvs(){const{toasts:s}=Bi();return e.jsxs(Pvs,{children:[s.map(function({id:t,title:n,description:r,action:a,...i}){return e.jsxs(VRt,{...i,children:[e.jsxs("div",{className:"grid gap-1",children:[n&&e.jsx(GRt,{children:n}),r&&e.jsx(WRt,{children:r})]}),a,e.jsx(HRt,{})]},t)}),e.jsx(qRt,{})]})}var kgt=["light","dark"],Dvs="(prefers-color-scheme: dark)",Fvs=j.createContext(void 0),Ovs={setTheme:s=>{},themes:[]},zvs=()=>{var s;return(s=j.useContext(Fvs))!=null?s:Ovs};j.memo(({forcedTheme:s,storageKey:t,attribute:n,enableSystem:r,enableColorScheme:a,defaultTheme:i,value:l,attrs:o,nonce:c})=>{let d=i==="system",u=n==="class"?`var d=document.documentElement,c=d.classList;${`c.remove(${o.map(g=>`'${g}'`).join(",")})`};`:`var d=document.documentElement,n='${n}',s='setAttribute';`,h=a?kgt.includes(i)&&i?`if(e==='light'||e==='dark'||!e)d.style.colorScheme=e||'${i}'`:"if(e==='light'||e==='dark')d.style.colorScheme=e":"",m=(g,x=!1,y=!0)=>{let v=l?l[g]:g,b=x?g+"|| ''":`'${v}'`,w="";return a&&y&&!x&&kgt.includes(g)&&(w+=`d.style.colorScheme = '${g}';`),n==="class"?x||v?w+=`c.add(${b})`:w+="null":v&&(w+=`d[s](n,${b})`),w},f=s?`!function(){${u}${m(s)}}()`:r?`!function(){try{${u}var e=localStorage.getItem('${t}');if('system'===e||(!e&&${d})){var t='${Dvs}',m=window.matchMedia(t);if(m.media!==t||m.matches){${m("dark")}}else{${m("light")}}}else if(e){${l?`var x=${JSON.stringify(l)};`:""}${m(l?"x[e]":"e",!0)}}${d?"":"else{"+m(i,!1,!1)+"}"}${h}}catch(e){}}()`:`!function(){try{${u}var e=localStorage.getItem('${t}');if(e){${l?`var x=${JSON.stringify(l)};`:""}${m(l?"x[e]":"e",!0)}}else{${m(i,!1,!1)};}${h}}catch(t){}}();`;return j.createElement("script",{nonce:c,dangerouslySetInnerHTML:{__html:f}})});var Bvs=s=>{switch(s){case"success":return qvs;case"info":return Hvs;case"warning":return Vvs;case"error":return Gvs;default:return null}},$vs=Array(12).fill(0),Uvs=({visible:s,className:t})=>Gt.createElement("div",{className:["sonner-loading-wrapper",t].filter(Boolean).join(" "),"data-visible":s},Gt.createElement("div",{className:"sonner-spinner"},$vs.map((n,r)=>Gt.createElement("div",{className:"sonner-loading-bar",key:`spinner-bar-${r}`})))),qvs=Gt.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},Gt.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"})),Vvs=Gt.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"currentColor",height:"20",width:"20"},Gt.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"})),Hvs=Gt.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},Gt.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"})),Gvs=Gt.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},Gt.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"})),Wvs=Gt.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"},Gt.createElement("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),Gt.createElement("line",{x1:"6",y1:"6",x2:"18",y2:"18"})),Kvs=()=>{let[s,t]=Gt.useState(document.hidden);return Gt.useEffect(()=>{let n=()=>{t(document.hidden)};return document.addEventListener("visibilitychange",n),()=>window.removeEventListener("visibilitychange",n)},[]),s},$Ve=1,Yvs=class{constructor(){this.subscribe=t=>(this.subscribers.push(t),()=>{let n=this.subscribers.indexOf(t);this.subscribers.splice(n,1)}),this.publish=t=>{this.subscribers.forEach(n=>n(t))},this.addToast=t=>{this.publish(t),this.toasts=[...this.toasts,t]},this.create=t=>{var n;let{message:r,...a}=t,i=typeof(t==null?void 0:t.id)=="number"||((n=t.id)==null?void 0:n.length)>0?t.id:$Ve++,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:r}),{...c,...t,id:i,dismissible:o,title:r}):c):this.addToast({title:r,...a,dismissible:o,id:i}),i},this.dismiss=t=>(this.dismissedToasts.add(t),t||this.toasts.forEach(n=>{this.subscribers.forEach(r=>r({id:n.id,dismiss:!0}))}),this.subscribers.forEach(n=>n({id:t,dismiss:!0})),t),this.message=(t,n)=>this.create({...n,message:t}),this.error=(t,n)=>this.create({...n,message:t,type:"error"}),this.success=(t,n)=>this.create({...n,type:"success",message:t}),this.info=(t,n)=>this.create({...n,type:"info",message:t}),this.warning=(t,n)=>this.create({...n,type:"warning",message:t}),this.loading=(t,n)=>this.create({...n,type:"loading",message:t}),this.promise=(t,n)=>{if(!n)return;let r;n.loading!==void 0&&(r=this.create({...n,promise:t,type:"loading",message:n.loading,description:typeof n.description!="function"?n.description:void 0}));let a=t instanceof Promise?t:t(),i=r!==void 0,l,o=a.then(async d=>{if(l=["resolve",d],Gt.isValidElement(d))i=!1,this.create({id:r,type:"default",message:d});else if(Xvs(d)&&!d.ok){i=!1;let u=typeof n.error=="function"?await n.error(`HTTP error! status: ${d.status}`):n.error,h=typeof n.description=="function"?await n.description(`HTTP error! status: ${d.status}`):n.description;this.create({id:r,type:"error",message:u,description:h})}else if(n.success!==void 0){i=!1;let u=typeof n.success=="function"?await n.success(d):n.success,h=typeof n.description=="function"?await n.description(d):n.description;this.create({id:r,type:"success",message:u,description:h})}}).catch(async d=>{if(l=["reject",d],n.error!==void 0){i=!1;let u=typeof n.error=="function"?await n.error(d):n.error,h=typeof n.description=="function"?await n.description(d):n.description;this.create({id:r,type:"error",message:u,description:h})}}).finally(()=>{var d;i&&(this.dismiss(r),r=void 0),(d=n.finally)==null||d.call(n)}),c=()=>new Promise((d,u)=>o.then(()=>l[0]==="reject"?u(l[1]):d(l[1])).catch(u));return typeof r!="string"&&typeof r!="number"?{unwrap:c}:Object.assign(r,{unwrap:c})},this.custom=(t,n)=>{let r=(n==null?void 0:n.id)||$Ve++;return this.create({jsx:t(r),id:r,...n}),r},this.getActiveToasts=()=>this.toasts.filter(t=>!this.dismissedToasts.has(t.id)),this.subscribers=[],this.toasts=[],this.dismissedToasts=new Set}},mw=new Yvs,Zvs=(s,t)=>{let n=(t==null?void 0:t.id)||$Ve++;return mw.addToast({title:s,...t,id:n}),n},Xvs=s=>s&&typeof s=="object"&&"ok"in s&&typeof s.ok=="boolean"&&"status"in s&&typeof s.status=="number",Qvs=Zvs,Jvs=()=>mw.toasts,ebs=()=>mw.getActiveToasts(),re=Object.assign(Qvs,{success:mw.success,info:mw.info,warning:mw.warning,error:mw.error,custom:mw.custom,message:mw.message,promise:mw.promise,dismiss:mw.dismiss,loading:mw.loading},{getHistory:Jvs,getToasts:ebs});function tbs(s,{insertAt:t}={}){if(typeof document>"u")return;let n=document.head||document.getElementsByTagName("head")[0],r=document.createElement("style");r.type="text/css",t==="top"&&n.firstChild?n.insertBefore(r,n.firstChild):n.appendChild(r),r.styleSheet?r.styleSheet.cssText=s:r.appendChild(document.createTextNode(s))}tbs(`: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 pce(s){return s.label!==void 0}var sbs=3,nbs="32px",rbs="16px",Sgt=4e3,abs=356,ibs=14,obs=20,lbs=200;function tS(...s){return s.filter(Boolean).join(" ")}function cbs(s){let[t,n]=s.split("-"),r=[];return t&&r.push(t),n&&r.push(n),r}var dbs=s=>{var t,n,r,a,i,l,o,c,d,u,h;let{invert:m,toast:f,unstyled:g,interacting:x,setHeights:y,visibleToasts:v,heights:b,index:w,toasts:S,expanded:C,removeToast:E,defaultRichColors:I,closeButton:P,style:R,cancelButtonStyle:D,actionButtonStyle:O,className:U="",descriptionClassName:W="",duration:V,position:G,gap:Y,loadingIcon:X,expandByDefault:ae,classNames:ie,icons:ne,closeButtonAriaLabel:te="Close toast",pauseWhenPageIsHidden:J}=s,[ce,_e]=Gt.useState(null),[he,ue]=Gt.useState(null),[ve,Ee]=Gt.useState(!1),[Se,Le]=Gt.useState(!1),[Fe,ke]=Gt.useState(!1),[Ve,je]=Gt.useState(!1),[Ae,Ce]=Gt.useState(!1),[qe,ze]=Gt.useState(0),[$e,ct]=Gt.useState(0),Xe=Gt.useRef(f.duration||V||Sgt),it=Gt.useRef(null),at=Gt.useRef(null),Ke=w===0,nt=w+1<=v,xt=f.type,rt=f.dismissible!==!1,Yt=f.className||"",qt=f.descriptionClassName||"",ts=Gt.useMemo(()=>b.findIndex(Ws=>Ws.toastId===f.id)||0,[b,f.id]),ys=Gt.useMemo(()=>{var Ws;return(Ws=f.closeButton)!=null?Ws:P},[f.closeButton,P]),Bt=Gt.useMemo(()=>f.duration||V||Sgt,[f.duration,V]),Ft=Gt.useRef(0),rs=Gt.useRef(0),St=Gt.useRef(0),Xs=Gt.useRef(null),[vt,gs]=G.split("-"),Ss=Gt.useMemo(()=>b.reduce((Ws,On,ds)=>ds>=ts?Ws:Ws+On.height,0),[b,ts]),Is=Kvs(),Ys=f.invert||m,cs=xt==="loading";rs.current=Gt.useMemo(()=>ts*Y+Ss,[ts,Ss]),Gt.useEffect(()=>{Xe.current=Bt},[Bt]),Gt.useEffect(()=>{Ee(!0)},[]),Gt.useEffect(()=>{let Ws=at.current;if(Ws){let On=Ws.getBoundingClientRect().height;return ct(On),y(ds=>[{toastId:f.id,height:On,position:f.position},...ds]),()=>y(ds=>ds.filter(gn=>gn.toastId!==f.id))}},[y,f.id]),Gt.useLayoutEffect(()=>{if(!ve)return;let Ws=at.current,On=Ws.style.height;Ws.style.height="auto";let ds=Ws.getBoundingClientRect().height;Ws.style.height=On,ct(ds),y(gn=>gn.find(As=>As.toastId===f.id)?gn.map(As=>As.toastId===f.id?{...As,height:ds}:As):[{toastId:f.id,height:ds,position:f.position},...gn])},[ve,f.title,f.description,y,f.id]);let js=Gt.useCallback(()=>{Le(!0),ze(rs.current),y(Ws=>Ws.filter(On=>On.toastId!==f.id)),setTimeout(()=>{E(f)},lbs)},[f,E,y,rs]);Gt.useEffect(()=>{if(f.promise&&xt==="loading"||f.duration===1/0||f.type==="loading")return;let Ws;return C||x||J&&Is?(()=>{if(St.current{var On;(On=f.onAutoClose)==null||On.call(f,f),js()},Xe.current)),()=>clearTimeout(Ws)},[C,x,f,xt,J,Is,js]),Gt.useEffect(()=>{f.delete&&js()},[js,f.delete]);function kn(){var Ws,On,ds;return ne!=null&&ne.loading?Gt.createElement("div",{className:tS(ie==null?void 0:ie.loader,(Ws=f==null?void 0:f.classNames)==null?void 0:Ws.loader,"sonner-loader"),"data-visible":xt==="loading"},ne.loading):X?Gt.createElement("div",{className:tS(ie==null?void 0:ie.loader,(On=f==null?void 0:f.classNames)==null?void 0:On.loader,"sonner-loader"),"data-visible":xt==="loading"},X):Gt.createElement(Uvs,{className:tS(ie==null?void 0:ie.loader,(ds=f==null?void 0:f.classNames)==null?void 0:ds.loader),visible:xt==="loading"})}return Gt.createElement("li",{tabIndex:0,ref:at,className:tS(U,Yt,ie==null?void 0:ie.toast,(t=f==null?void 0:f.classNames)==null?void 0:t.toast,ie==null?void 0:ie.default,ie==null?void 0:ie[xt],(n=f==null?void 0:f.classNames)==null?void 0:n[xt]),"data-sonner-toast":"","data-rich-colors":(r=f.richColors)!=null?r:I,"data-styled":!(f.jsx||f.unstyled||g),"data-mounted":ve,"data-promise":!!f.promise,"data-swiped":Ae,"data-removed":Se,"data-visible":nt,"data-y-position":vt,"data-x-position":gs,"data-index":w,"data-front":Ke,"data-swiping":Fe,"data-dismissible":rt,"data-type":xt,"data-invert":Ys,"data-swipe-out":Ve,"data-swipe-direction":he,"data-expanded":!!(C||ae&&ve),style:{"--index":w,"--toasts-before":w,"--z-index":S.length-w,"--offset":`${Se?qe:rs.current}px`,"--initial-height":ae?"auto":`${$e}px`,...R,...f.style},onDragEnd:()=>{ke(!1),_e(null),Xs.current=null},onPointerDown:Ws=>{cs||!rt||(it.current=new Date,ze(rs.current),Ws.target.setPointerCapture(Ws.pointerId),Ws.target.tagName!=="BUTTON"&&(ke(!0),Xs.current={x:Ws.clientX,y:Ws.clientY}))},onPointerUp:()=>{var Ws,On,ds,gn;if(Ve||!rt)return;Xs.current=null;let As=Number(((Ws=at.current)==null?void 0:Ws.style.getPropertyValue("--swipe-amount-x").replace("px",""))||0),hr=Number(((On=at.current)==null?void 0:On.style.getPropertyValue("--swipe-amount-y").replace("px",""))||0),Er=new Date().getTime()-((ds=it.current)==null?void 0:ds.getTime()),qn=ce==="x"?As:hr,hn=Math.abs(qn)/Er;if(Math.abs(qn)>=obs||hn>.11){ze(rs.current),(gn=f.onDismiss)==null||gn.call(f,f),ue(ce==="x"?As>0?"right":"left":hr>0?"down":"up"),js(),je(!0),Ce(!1);return}ke(!1),_e(null)},onPointerMove:Ws=>{var On,ds,gn,As;if(!Xs.current||!rt||((On=window.getSelection())==null?void 0:On.toString().length)>0)return;let hr=Ws.clientY-Xs.current.y,Er=Ws.clientX-Xs.current.x,qn=(ds=s.swipeDirections)!=null?ds:cbs(G);!ce&&(Math.abs(Er)>1||Math.abs(hr)>1)&&_e(Math.abs(Er)>Math.abs(hr)?"x":"y");let hn={x:0,y:0};ce==="y"?(qn.includes("top")||qn.includes("bottom"))&&(qn.includes("top")&&hr<0||qn.includes("bottom")&&hr>0)&&(hn.y=hr):ce==="x"&&(qn.includes("left")||qn.includes("right"))&&(qn.includes("left")&&Er<0||qn.includes("right")&&Er>0)&&(hn.x=Er),(Math.abs(hn.x)>0||Math.abs(hn.y)>0)&&Ce(!0),(gn=at.current)==null||gn.style.setProperty("--swipe-amount-x",`${hn.x}px`),(As=at.current)==null||As.style.setProperty("--swipe-amount-y",`${hn.y}px`)}},ys&&!f.jsx?Gt.createElement("button",{"aria-label":te,"data-disabled":cs,"data-close-button":!0,onClick:cs||!rt?()=>{}:()=>{var Ws;js(),(Ws=f.onDismiss)==null||Ws.call(f,f)},className:tS(ie==null?void 0:ie.closeButton,(a=f==null?void 0:f.classNames)==null?void 0:a.closeButton)},(i=ne==null?void 0:ne.close)!=null?i:Wvs):null,f.jsx||j.isValidElement(f.title)?f.jsx?f.jsx:typeof f.title=="function"?f.title():f.title:Gt.createElement(Gt.Fragment,null,xt||f.icon||f.promise?Gt.createElement("div",{"data-icon":"",className:tS(ie==null?void 0:ie.icon,(l=f==null?void 0:f.classNames)==null?void 0:l.icon)},f.promise||f.type==="loading"&&!f.icon?f.icon||kn():null,f.type!=="loading"?f.icon||(ne==null?void 0:ne[xt])||Bvs(xt):null):null,Gt.createElement("div",{"data-content":"",className:tS(ie==null?void 0:ie.content,(o=f==null?void 0:f.classNames)==null?void 0:o.content)},Gt.createElement("div",{"data-title":"",className:tS(ie==null?void 0:ie.title,(c=f==null?void 0:f.classNames)==null?void 0:c.title)},typeof f.title=="function"?f.title():f.title),f.description?Gt.createElement("div",{"data-description":"",className:tS(W,qt,ie==null?void 0:ie.description,(d=f==null?void 0:f.classNames)==null?void 0:d.description)},typeof f.description=="function"?f.description():f.description):null),j.isValidElement(f.cancel)?f.cancel:f.cancel&&pce(f.cancel)?Gt.createElement("button",{"data-button":!0,"data-cancel":!0,style:f.cancelButtonStyle||D,onClick:Ws=>{var On,ds;pce(f.cancel)&&rt&&((ds=(On=f.cancel).onClick)==null||ds.call(On,Ws),js())},className:tS(ie==null?void 0:ie.cancelButton,(u=f==null?void 0:f.classNames)==null?void 0:u.cancelButton)},f.cancel.label):null,j.isValidElement(f.action)?f.action:f.action&&pce(f.action)?Gt.createElement("button",{"data-button":!0,"data-action":!0,style:f.actionButtonStyle||O,onClick:Ws=>{var On,ds;pce(f.action)&&((ds=(On=f.action).onClick)==null||ds.call(On,Ws),!Ws.defaultPrevented&&js())},className:tS(ie==null?void 0:ie.actionButton,(h=f==null?void 0:f.classNames)==null?void 0:h.actionButton)},f.action.label):null))};function Cgt(){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 ubs(s,t){let n={};return[s,t].forEach((r,a)=>{let i=a===1,l=i?"--mobile-offset":"--offset",o=i?rbs:nbs;function c(d){["top","right","bottom","left"].forEach(u=>{n[`${l}-${u}`]=typeof d=="number"?`${d}px`:d})}typeof r=="number"||typeof r=="string"?c(r):typeof r=="object"?["top","right","bottom","left"].forEach(d=>{r[d]===void 0?n[`${l}-${d}`]=o:n[`${l}-${d}`]=typeof r[d]=="number"?`${r[d]}px`:r[d]}):c(o)}),n}var hbs=j.forwardRef(function(s,t){let{invert:n,position:r="bottom-right",hotkey:a=["altKey","KeyT"],expand:i,closeButton:l,className:o,offset:c,mobileOffset:d,theme:u="light",richColors:h,duration:m,style:f,visibleToasts:g=sbs,toastOptions:x,dir:y=Cgt(),gap:v=ibs,loadingIcon:b,icons:w,containerAriaLabel:S="Notifications",pauseWhenPageIsHidden:C}=s,[E,I]=Gt.useState([]),P=Gt.useMemo(()=>Array.from(new Set([r].concat(E.filter(J=>J.position).map(J=>J.position)))),[E,r]),[R,D]=Gt.useState([]),[O,U]=Gt.useState(!1),[W,V]=Gt.useState(!1),[G,Y]=Gt.useState(u!=="system"?u:typeof window<"u"&&window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"),X=Gt.useRef(null),ae=a.join("+").replace(/Key/g,"").replace(/Digit/g,""),ie=Gt.useRef(null),ne=Gt.useRef(!1),te=Gt.useCallback(J=>{I(ce=>{var _e;return(_e=ce.find(he=>he.id===J.id))!=null&&_e.delete||mw.dismiss(J.id),ce.filter(({id:he})=>he!==J.id)})},[]);return Gt.useEffect(()=>mw.subscribe(J=>{if(J.dismiss){I(ce=>ce.map(_e=>_e.id===J.id?{..._e,delete:!0}:_e));return}setTimeout(()=>{G6t.flushSync(()=>{I(ce=>{let _e=ce.findIndex(he=>he.id===J.id);return _e!==-1?[...ce.slice(0,_e),{...ce[_e],...J},...ce.slice(_e+1)]:[J,...ce]})})})}),[]),Gt.useEffect(()=>{if(u!=="system"){Y(u);return}if(u==="system"&&(window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches?Y("dark"):Y("light")),typeof window>"u")return;let J=window.matchMedia("(prefers-color-scheme: dark)");try{J.addEventListener("change",({matches:ce})=>{Y(ce?"dark":"light")})}catch{J.addListener(({matches:_e})=>{try{Y(_e?"dark":"light")}catch(he){console.error(he)}})}},[u]),Gt.useEffect(()=>{E.length<=1&&U(!1)},[E]),Gt.useEffect(()=>{let J=ce=>{var _e,he;a.every(ue=>ce[ue]||ce.code===ue)&&(U(!0),(_e=X.current)==null||_e.focus()),ce.code==="Escape"&&(document.activeElement===X.current||(he=X.current)!=null&&he.contains(document.activeElement))&&U(!1)};return document.addEventListener("keydown",J),()=>document.removeEventListener("keydown",J)},[a]),Gt.useEffect(()=>{if(X.current)return()=>{ie.current&&(ie.current.focus({preventScroll:!0}),ie.current=null,ne.current=!1)}},[X.current]),Gt.createElement("section",{ref:t,"aria-label":`${S} ${ae}`,tabIndex:-1,"aria-live":"polite","aria-relevant":"additions text","aria-atomic":"false",suppressHydrationWarning:!0},P.map((J,ce)=>{var _e;let[he,ue]=J.split("-");return E.length?Gt.createElement("ol",{key:J,dir:y==="auto"?Cgt():y,tabIndex:-1,ref:X,className:o,"data-sonner-toaster":!0,"data-theme":G,"data-y-position":he,"data-lifted":O&&E.length>1&&!i,"data-x-position":ue,style:{"--front-toast-height":`${((_e=R[0])==null?void 0:_e.height)||0}px`,"--width":`${abs}px`,"--gap":`${v}px`,...f,...ubs(c,d)},onBlur:ve=>{ne.current&&!ve.currentTarget.contains(ve.relatedTarget)&&(ne.current=!1,ie.current&&(ie.current.focus({preventScroll:!0}),ie.current=null))},onFocus:ve=>{ve.target instanceof HTMLElement&&ve.target.dataset.dismissible==="false"||ne.current||(ne.current=!0,ie.current=ve.relatedTarget)},onMouseEnter:()=>U(!0),onMouseMove:()=>U(!0),onMouseLeave:()=>{W||U(!1)},onDragEnd:()=>U(!1),onPointerDown:ve=>{ve.target instanceof HTMLElement&&ve.target.dataset.dismissible==="false"||V(!0)},onPointerUp:()=>V(!1)},E.filter(ve=>!ve.position&&ce===0||ve.position===J).map((ve,Ee)=>{var Se,Le;return Gt.createElement(dbs,{key:ve.id,icons:w,index:Ee,toast:ve,defaultRichColors:h,duration:(Se=x==null?void 0:x.duration)!=null?Se:m,className:x==null?void 0:x.className,descriptionClassName:x==null?void 0:x.descriptionClassName,invert:n,visibleToasts:g,closeButton:(Le=x==null?void 0:x.closeButton)!=null?Le:l,interacting:W,position:J,style:x==null?void 0:x.style,unstyled:x==null?void 0:x.unstyled,classNames:x==null?void 0:x.classNames,cancelButtonStyle:x==null?void 0:x.cancelButtonStyle,actionButtonStyle:x==null?void 0:x.actionButtonStyle,removeToast:te,toasts:E.filter(Fe=>Fe.position==ve.position),heights:R.filter(Fe=>Fe.position==ve.position),setHeights:D,expandByDefault:i,gap:v,loadingIcon:b,expanded:O,pauseWhenPageIsHidden:C,swipeDirections:s.swipeDirections})})):null}))});const mbs=({...s})=>{const{theme:t="system"}=zvs();return e.jsx(hbs,{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 fbs=Object.defineProperty,pbs=(s,t)=>fbs(s,"name",{value:t,configurable:!0}),gbs=MB[" useId ".trim().toString()]||(()=>{}),xbs=0;function my(s){const[t,n]=j.useState(gbs());return Ef(()=>{s||n(r=>r??String(xbs++))},[s]),s||(t?`radix-${t}`:"")}pbs(my,"useId");var ybs=Object.defineProperty,x_=(s,t)=>ybs(s,"name",{value:t,configurable:!0}),Sze="focusScope.autoFocusOnMount",Cze="focusScope.autoFocusOnUnmount",Agt={bubbles:!1,cancelable:!0},GIe=j.forwardRef(x_(function(t,n){const{loop:r=!1,trapped:a=!1,onMountAutoFocus:i,onUnmountAutoFocus:l,...o}=t,[c,d]=j.useState(null),u=Yp(i),h=Yp(l),m=j.useRef(null),f=Vo(n,d),g=j.useRef({paused:!1,pause(){this.paused=!0},resume(){this.paused=!1}}).current;j.useEffect(()=>{if(a){let y=function(S){if(g.paused||!c)return;const C=S.target;c.contains(C)?m.current=C:CA(m.current,{select:!0})},v=function(S){if(g.paused||!c)return;const C=S.relatedTarget;C!==null&&(c.contains(C)||CA(m.current,{select:!0}))},b=function(S){if(document.activeElement===document.body)for(const E of S)E.removedNodes.length>0&&CA(c)};x_(y,"handleFocusIn"),x_(v,"handleFocusOut"),x_(b,"handleMutations"),document.addEventListener("focusin",y),document.addEventListener("focusout",v);const w=new MutationObserver(b);return c&&w.observe(c,{childList:!0,subtree:!0}),()=>{document.removeEventListener("focusin",y),document.removeEventListener("focusout",v),w.disconnect()}}},[a,c,g.paused]),j.useEffect(()=>{if(c){Egt.add(g);const y=document.activeElement;if(!c.contains(y)){const b=new CustomEvent(Sze,Agt);c.addEventListener(Sze,u),c.dispatchEvent(b),b.defaultPrevented||(KRt(JRt(uet(c)),{select:!0}),document.activeElement===y&&CA(c))}return()=>{c.removeEventListener(Sze,u),setTimeout(()=>{const b=new CustomEvent(Cze,Agt);c.addEventListener(Cze,h),c.dispatchEvent(b),b.defaultPrevented||CA(y??document.body,{select:!0}),c.removeEventListener(Cze,h),Egt.remove(g)},0)}}},[c,u,h,g]);const x=j.useCallback(y=>{if(!r&&!a||g.paused)return;const v=y.key==="Tab"&&!y.altKey&&!y.ctrlKey&&!y.metaKey,b=document.activeElement;if(v&&b){const w=y.currentTarget,[S,C]=YRt(w);S&&C?!y.shiftKey&&b===C?(y.preventDefault(),r&&CA(S,{select:!0})):y.shiftKey&&b===S&&(y.preventDefault(),r&&CA(C,{select:!0})):b===w&&y.preventDefault()}},[r,a,g.paused]);return e.jsx(Ei.div,{tabIndex:-1,...o,ref:f,onKeyDown:x})},"FocusScope"));function KRt(s,{select:t=!1}={}){const n=document.activeElement;for(const r of s)if(CA(r,{select:t}),document.activeElement!==n)return}x_(KRt,"focusFirst");function YRt(s){const t=uet(s),n=UVe(t,s),r=UVe(t.reverse(),s);return[n,r]}x_(YRt,"getTabbableEdges");function uet(s){const t=[],n=document.createTreeWalker(s,NodeFilter.SHOW_ELEMENT,{acceptNode:x_(r=>{const a=r.tagName==="INPUT"&&r.type==="hidden";return r.disabled||r.hidden||a?NodeFilter.FILTER_SKIP:r.tabIndex>=0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP},"acceptNode")});for(;n.nextNode();)t.push(n.currentNode);return t}x_(uet,"getTabbableCandidates");function UVe(s,t){const n=typeof t.checkVisibility=="function"&&t.checkVisibility({checkVisibilityCSS:!0});for(const r of s)if(!(n?!r.checkVisibility({checkVisibilityCSS:!0}):ZRt(r,{upTo:t})))return r}x_(UVe,"findVisible");function ZRt(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}x_(ZRt,"isHidden");function XRt(s){return s instanceof HTMLInputElement&&"select"in s}x_(XRt,"isSelectableInput");function CA(s,{select:t=!1}={}){if(s&&s.focus){const n=document.activeElement;s.focus({preventScroll:!0}),s!==n&&XRt(s)&&t&&s.select()}}x_(CA,"focus");var Egt=QRt();function QRt(){let s=[];return{add(t){const n=s[0];t!==n&&(n==null||n.pause()),s=qVe(s,t),s.unshift(t)},remove(t){var n;s=qVe(s,t),(n=s[0])==null||n.resume()}}}x_(QRt,"createFocusScopesStack");function qVe(s,t){const n=[...s],r=n.indexOf(t);return r!==-1&&n.splice(r,1),n}x_(qVe,"arrayRemove");function JRt(s){return s.filter(t=>t.tagName!=="A")}x_(JRt,"removeLinks");var vbs=Object.defineProperty,het=(s,t)=>vbs(s,"name",{value:t,configurable:!0}),gce=0,t5=null;function bbs(s){return GW(),s.children}het(bbs,"FocusGuards");function GW(){j.useEffect(()=>{t5||(t5={start:VVe(),end:VVe()});const{start:s,end:t}=t5;return document.body.firstElementChild!==s&&document.body.insertAdjacentElement("afterbegin",s),document.body.lastElementChild!==t&&document.body.insertAdjacentElement("beforeend",t),gce++,()=>{gce===1&&(t5==null||t5.start.remove(),t5==null||t5.end.remove(),t5=null),gce=Math.max(0,gce-1)}},[])}het(GW,"useFocusGuards");function VVe(){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}het(VVe,"createFocusGuard");var c4=function(){return c4=Object.assign||function(t){for(var n,r=1,a=arguments.length;r"u")return Fbs;var t=Obs(s),n=document.documentElement.clientWidth,r=window.innerWidth;return{left:t[0],top:t[1],right:t[2],gap:Math.max(0,r-n+t[2]-t[0])}},Bbs=nDt(),bV="data-scroll-locked",$bs=function(s,t,n,r){var a=s.left,i=s.top,l=s.right,o=s.gap;return n===void 0&&(n="margin"),` .`.concat(wbs,` { overflow: hidden `).concat(r,`; padding-right: `).concat(o,"px ").concat(r,`; } body[`).concat(bV,`] { overflow: hidden `).concat(r,`; overscroll-behavior: contain; `).concat([t&&"position: relative ".concat(r,";"),n==="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(r,`; `),n==="padding"&&"padding-right: ".concat(o,"px ").concat(r,";")].filter(Boolean).join(""),` } .`).concat(U4e,` { right: `).concat(o,"px ").concat(r,`; } .`).concat(q4e,` { margin-right: `).concat(o,"px ").concat(r,`; } .`).concat(U4e," .").concat(U4e,` { right: 0 `).concat(r,`; } .`).concat(q4e," .").concat(q4e,` { margin-right: 0 `).concat(r,`; } body[`).concat(bV,`] { `).concat(jbs,": ").concat(o,`px; } `)},Mgt=function(){var s=parseInt(document.body.getAttribute(bV)||"0",10);return isFinite(s)?s:0},Ubs=function(){j.useEffect(function(){return document.body.setAttribute(bV,(Mgt()+1).toString()),function(){var s=Mgt()-1;s<=0?document.body.removeAttribute(bV):document.body.setAttribute(bV,s.toString())}},[])},qbs=function(s){var t=s.noRelative,n=s.noImportant,r=s.gapMode,a=r===void 0?"margin":r;Ubs();var i=j.useMemo(function(){return zbs(a)},[a]);return j.createElement(Bbs,{styles:$bs(i,!t,a,n?"":"!important")})},HVe=!1;if(typeof window<"u")try{var xce=Object.defineProperty({},"passive",{get:function(){return HVe=!0,!0}});window.addEventListener("test",xce,xce),window.removeEventListener("test",xce,xce)}catch{HVe=!1}var m$=HVe?{passive:!1}:!1,Vbs=function(s){return s.tagName==="TEXTAREA"},rDt=function(s,t){if(!(s instanceof Element))return!1;var n=window.getComputedStyle(s);return n[t]!=="hidden"&&!(n.overflowY===n.overflowX&&!Vbs(s)&&n[t]==="visible")},Hbs=function(s){return rDt(s,"overflowY")},Gbs=function(s){return rDt(s,"overflowX")},Pgt=function(s,t){var n=t.ownerDocument,r=t;do{typeof ShadowRoot<"u"&&r instanceof ShadowRoot&&(r=r.host);var a=aDt(s,r);if(a){var i=iDt(s,r),l=i[1],o=i[2];if(l>o)return!0}r=r.parentNode}while(r&&r!==n.body);return!1},Wbs=function(s){var t=s.scrollTop,n=s.scrollHeight,r=s.clientHeight;return[t,n,r]},Kbs=function(s){var t=s.scrollLeft,n=s.scrollWidth,r=s.clientWidth;return[t,n,r]},aDt=function(s,t){return s==="v"?Hbs(t):Gbs(t)},iDt=function(s,t){return s==="v"?Wbs(t):Kbs(t)},Ybs=function(s,t){return s==="h"&&t==="rtl"?-1:1},Zbs=function(s,t,n,r,a){var i=Ybs(s,window.getComputedStyle(t).direction),l=i*r,o=n.target,c=t.contains(o),d=!1,u=l>0,h=0,m=0;do{if(!o)break;var f=iDt(s,o),g=f[0],x=f[1],y=f[2],v=x-y-i*g;(g||v)&&aDt(s,o)&&(h+=v,m+=g);var b=o.parentNode;o=b&&b.nodeType===Node.DOCUMENT_FRAGMENT_NODE?b.host:b}while(!c&&o!==document.body||c&&(t.contains(o)||t===o));return(u&&Math.abs(h)<1||!u&&Math.abs(m)<1)&&(d=!0),d},yce=function(s){return"changedTouches"in s?[s.changedTouches[0].clientX,s.changedTouches[0].clientY]:[0,0]},Igt=function(s){return[s.deltaX,s.deltaY]},Lgt=function(s){return s&&"current"in s?s.current:s},Xbs=function(s,t){return s[0]===t[0]&&s[1]===t[1]},Qbs=function(s){return` .block-interactivity-`.concat(s,` {pointer-events: none;} .allow-interactivity-`).concat(s,` {pointer-events: all;} `)},Jbs=0,f$=[];function e1s(s){var t=j.useRef([]),n=j.useRef([0,0]),r=j.useRef(),a=j.useState(Jbs++)[0],i=j.useState(nDt)[0],l=j.useRef(s);j.useEffect(function(){l.current=s},[s]),j.useEffect(function(){if(s.inert){document.body.classList.add("block-interactivity-".concat(a));var x=_bs([s.lockRef.current],(s.shards||[]).map(Lgt),!0).filter(Boolean);return x.forEach(function(y){return y.classList.add("allow-interactivity-".concat(a))}),function(){document.body.classList.remove("block-interactivity-".concat(a)),x.forEach(function(y){return y.classList.remove("allow-interactivity-".concat(a))})}}},[s.inert,s.lockRef.current,s.shards]);var o=j.useCallback(function(x,y){if("touches"in x&&x.touches.length===2||x.type==="wheel"&&x.ctrlKey)return!l.current.allowPinchZoom;var v=yce(x),b=n.current,w="deltaX"in x?x.deltaX:b[0]-v[0],S="deltaY"in x?x.deltaY:b[1]-v[1],C,E=x.target,I=Math.abs(w)>Math.abs(S)?"h":"v";if("touches"in x&&I==="h"&&E.type==="range")return!1;var P=window.getSelection(),R=P&&P.anchorNode,D=R?R===E||R.contains(E):!1;if(D)return!1;var O=Pgt(I,E);if(!O)return!0;if(O?C=I:(C=I==="v"?"h":"v",O=Pgt(I,E)),!O)return!1;if(!r.current&&"changedTouches"in x&&(w||S)&&(r.current=C),!C)return!0;var U=r.current||C;return Zbs(U,y,x,U==="h"?w:S)},[]),c=j.useCallback(function(x){var y=x;if(!(!f$.length||f$[f$.length-1]!==i)){var v="deltaY"in y?Igt(y):yce(y),b=t.current.filter(function(C){return C.name===y.type&&(C.target===y.target||y.target===C.shadowParent)&&Xbs(C.delta,v)})[0];if(b&&b.should){y.cancelable&&y.preventDefault();return}if(!b){var w=(l.current.shards||[]).map(Lgt).filter(Boolean).filter(function(C){return C.contains(y.target)}),S=w.length>0?o(y,w[0]):!l.current.noIsolation;S&&y.cancelable&&y.preventDefault()}}},[]),d=j.useCallback(function(x,y,v,b){var w={name:x,delta:y,target:v,should:b,shadowParent:t1s(v)};t.current.push(w),setTimeout(function(){t.current=t.current.filter(function(S){return S!==w})},1)},[]),u=j.useCallback(function(x){n.current=yce(x),r.current=void 0},[]),h=j.useCallback(function(x){d(x.type,Igt(x),x.target,o(x,s.lockRef.current))},[]),m=j.useCallback(function(x){d(x.type,yce(x),x.target,o(x,s.lockRef.current))},[]);j.useEffect(function(){return f$.push(i),s.setCallbacks({onScrollCapture:h,onWheelCapture:h,onTouchMoveCapture:m}),document.addEventListener("wheel",c,m$),document.addEventListener("touchmove",c,m$),document.addEventListener("touchstart",u,m$),function(){f$=f$.filter(function(x){return x!==i}),document.removeEventListener("wheel",c,m$),document.removeEventListener("touchmove",c,m$),document.removeEventListener("touchstart",u,m$)}},[]);var f=s.removeScrollBar,g=s.inert;return j.createElement(j.Fragment,null,g?j.createElement(i,{styles:Qbs(a)}):null,f?j.createElement(qbs,{noRelative:s.noRelative,gapMode:s.gapMode}):null)}function t1s(s){for(var t=null;s!==null;)s instanceof ShadowRoot&&(t=s.host,s=s.host),s=s.parentNode;return t}const s1s=Tbs(sDt,e1s);var jae=j.forwardRef(function(s,t){return j.createElement(WIe,c4({},s,{ref:t,sideCar:s1s}))});jae.classNames=WIe.classNames;var n1s=function(s){if(typeof document>"u")return null;var t=Array.isArray(s)?s[0]:s;return t.ownerDocument.body},p$=new WeakMap,vce=new WeakMap,bce={},Mze=0,oDt=function(s){return s&&(s.host||oDt(s.parentNode))},r1s=function(s,t){return t.map(function(n){if(s.contains(n))return n;var r=oDt(n);return r&&s.contains(r)?r:(console.error("aria-hidden",n,"in not contained inside",s,". Doing nothing"),null)}).filter(function(n){return!!n})},a1s=function(s,t,n,r){var a=r1s(t,Array.isArray(s)?s:[s]);bce[n]||(bce[n]=new WeakMap);var i=bce[n],l=[],o=new Set,c=new Set(a),d=function(h){!h||o.has(h)||(o.add(h),d(h.parentNode))};a.forEach(d);var u=function(h){!h||c.has(h)||Array.prototype.forEach.call(h.children,function(m){if(o.has(m))u(m);else try{var f=m.getAttribute(r),g=f!==null&&f!=="false",x=(p$.get(m)||0)+1,y=(i.get(m)||0)+1;p$.set(m,x),i.set(m,y),l.push(m),x===1&&g&&vce.set(m,!0),y===1&&m.setAttribute(n,"true"),g||m.setAttribute(r,"true")}catch(v){console.error("aria-hidden: cannot operate on ",m,v)}})};return u(t),o.clear(),Mze++,function(){l.forEach(function(h){var m=p$.get(h)-1,f=i.get(h)-1;p$.set(h,m),i.set(h,f),m||(vce.has(h)||h.removeAttribute(r),vce.delete(h)),f||h.removeAttribute(n)}),Mze--,Mze||(p$=new WeakMap,p$=new WeakMap,vce=new WeakMap,bce={})}},KIe=function(s,t,n){n===void 0&&(n="data-aria-hidden");var r=Array.from(Array.isArray(s)?s:[s]),a=n1s(s);return a?(r.push.apply(r,Array.from(a.querySelectorAll("[aria-live], script"))),a1s(r,a,n,"aria-hidden")):function(){return null}},i1s=Object.defineProperty,V2=(s,t)=>i1s(s,"name",{value:t,configurable:!0}),met="Dialog",[lDt,cDt]=tp(met),[o1s,wC]=lDt(met),YIe=V2(s=>{const{__scopeDialog:t,children:n,open:r,defaultOpen:a,onOpenChange:i,modal:l=!0}=s,o=j.useRef(null),c=j.useRef(null),[d,u]=fy({prop:r,defaultProp:a??!1,onChange:i,caller:met}),[h,m]=j.useState(0),[f,g]=j.useState(0);return e.jsx(o1s,{scope:t,triggerRef:o,contentRef:c,contentId:my(),titleId:my(),descriptionId:my(),titlePresent:h>0,descriptionPresent:f>0,setTitleCount:m,setDescriptionCount:g,open:d,onOpenChange:u,onOpenToggle:j.useCallback(()=>u(x=>!x),[u]),modal:l,children:n})},"Dialog"),l1s="DialogTrigger",fet=j.forwardRef(V2(function(t,n){const{__scopeDialog:r,...a}=t,i=wC(l1s,r),l=Vo(n,i.triggerRef);return e.jsx(Ei.button,{type:"button","aria-haspopup":"dialog","aria-expanded":i.open,"aria-controls":i.open?i.contentId:void 0,"data-state":XIe(i.open),...a,ref:l,onClick:Ra(t.onClick,i.onOpenToggle)})},"DialogTrigger")),dDt="DialogPortal",[c1s,uDt]=lDt(dDt,{forceMount:void 0}),ZIe=V2(s=>{const{__scopeDialog:t,forceMount:n,children:r,container:a}=s,i=wC(dDt,t);return e.jsx(c1s,{scope:t,forceMount:n,children:j.Children.map(r,l=>e.jsx(xy,{present:n||i.open,children:e.jsx(_ae,{asChild:!0,container:a,children:l})}))})},"DialogPortal"),GVe="DialogOverlay",WW=j.forwardRef(V2(function(t,n){const r=uDt(GVe,t.__scopeDialog),{forceMount:a=r.forceMount,...i}=t,l=wC(GVe,t.__scopeDialog);return l.modal?e.jsx(xy,{present:a||l.open,children:e.jsx(u1s,{...i,ref:n})}):null},"DialogOverlay")),d1s=pC("DialogOverlay.RemoveScroll"),u1s=j.forwardRef(V2(function(t,n){const{__scopeDialog:r,...a}=t,i=wC(GVe,r),l=dRt(),o=Vo(n,l);return e.jsx(jae,{as:d1s,allowPinchZoom:!0,shards:[i.contentRef],children:e.jsx(Ei.div,{"data-state":XIe(i.open),...a,ref:o,style:{pointerEvents:"auto",...a.style}})})},"DialogOverlayImpl")),Hte="DialogContent",KW=j.forwardRef(V2(function(t,n){const r=uDt(Hte,t.__scopeDialog),{forceMount:a=r.forceMount,...i}=t,l=wC(Hte,t.__scopeDialog);return e.jsx(xy,{present:a||l.open,children:l.modal?e.jsx(h1s,{...i,ref:n}):e.jsx(m1s,{...i,ref:n})})},"DialogContent")),h1s=j.forwardRef(V2(function(t,n){const r=wC(Hte,t.__scopeDialog),a=j.useRef(null),i=Vo(n,r.contentRef,a);return j.useEffect(()=>{const l=a.current;if(l)return KIe(l)},[]),e.jsx(hDt,{...t,ref:i,trapFocus:r.open,disableOutsidePointerEvents:r.open,onCloseAutoFocus:Ra(t.onCloseAutoFocus,l=>{var o;l.preventDefault(),(o=r.triggerRef.current)==null||o.focus()}),onPointerDownOutside:Ra(t.onPointerDownOutside,l=>{const o=l.detail.originalEvent,c=o.button===0&&o.ctrlKey===!0;(o.button===2||c)&&l.preventDefault()}),onFocusOutside:Ra(t.onFocusOutside,l=>l.preventDefault())})},"DialogContentModal")),m1s=j.forwardRef(V2(function(t,n){const r=wC(Hte,t.__scopeDialog),a=j.useRef(!1),i=j.useRef(!1);return e.jsx(hDt,{...t,ref:n,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:l=>{var o,c;(o=t.onCloseAutoFocus)==null||o.call(t,l),l.defaultPrevented||(a.current||(c=r.triggerRef.current)==null||c.focus(),l.preventDefault()),a.current=!1,i.current=!1},onInteractOutside:l=>{var d,u;(d=t.onInteractOutside)==null||d.call(t,l),l.defaultPrevented||(a.current=!0,l.detail.originalEvent.type==="pointerdown"&&(i.current=!0));const o=l.target;((u=r.triggerRef.current)==null?void 0:u.contains(o))&&l.preventDefault(),l.detail.originalEvent.type==="focusin"&&i.current&&l.preventDefault()}})},"DialogContentNonModal")),hDt=j.forwardRef(V2(function(t,n){const{__scopeDialog:r,trapFocus:a,onOpenAutoFocus:i,onCloseAutoFocus:l,...o}=t,c=wC(Hte,r);return GW(),e.jsx(e.Fragment,{children:e.jsx(GIe,{asChild:!0,loop:!0,trapped:a,onMountAutoFocus:i,onUnmountAutoFocus:l,children:e.jsx(RB,{role:"dialog",id:c.contentId,"aria-describedby":c.descriptionPresent?c.descriptionId:void 0,"aria-labelledby":c.titlePresent?c.titleId:void 0,"data-state":XIe(c.open),...o,ref:n,deferPointerDownOutside:!0,onDismiss:()=>c.onOpenChange(!1)})})})},"DialogContentImpl")),f1s="DialogTitle",Nae=j.forwardRef(V2(function(t,n){const{__scopeDialog:r,...a}=t,i=wC(f1s,r),{setTitleCount:l}=i;return Ef(()=>(l(o=>o+1),()=>l(o=>o-1)),[l]),e.jsx(Ei.h2,{id:i.titleId,...a,ref:n})},"DialogTitle")),p1s="DialogDescription",kae=j.forwardRef(V2(function(t,n){const{__scopeDialog:r,...a}=t,i=wC(p1s,r),{setDescriptionCount:l}=i;return Ef(()=>(l(o=>o+1),()=>l(o=>o-1)),[l]),e.jsx(Ei.p,{id:i.descriptionId,...a,ref:n})},"DialogDescription")),g1s="DialogClose",Sae=j.forwardRef(V2(function(t,n){const{__scopeDialog:r,...a}=t,i=wC(g1s,r);return e.jsx(Ei.button,{type:"button",...a,ref:n,onClick:Ra(t.onClick,()=>i.onOpenChange(!1))})},"DialogClose"));function XIe(s){return s?"open":"closed"}V2(XIe,"getState");var x1s=Object.defineProperty,AT=(s,t)=>x1s(s,"name",{value:t,configurable:!0}),y1s="AlertDialog",[v1s,Pkr]=tp(y1s,[cDt]),ET=cDt(),b1s=AT(s=>{const{__scopeAlertDialog:t,...n}=s,r=ET(t);return e.jsx(YIe,{...r,...n,modal:!0})},"AlertDialog"),_1s=j.forwardRef(AT(function(t,n){const{__scopeAlertDialog:r,...a}=t,i=ET(r);return e.jsx(fet,{...i,...a,ref:n})},"AlertDialogTrigger")),w1s=AT(s=>{const{__scopeAlertDialog:t,...n}=s,r=ET(t);return e.jsx(ZIe,{...r,...n})},"AlertDialogPortal"),j1s=j.forwardRef(AT(function(t,n){const{__scopeAlertDialog:r,...a}=t,i=ET(r);return e.jsx(WW,{...i,...a,ref:n})},"AlertDialogOverlay")),N1s="AlertDialogContent",[k1s,S1s]=v1s(N1s),C1s=j.forwardRef(AT(function(t,n){const{__scopeAlertDialog:r,children:a,...i}=t,l=ET(r),o=j.useRef(null),c=Vo(n,o),d=j.useRef(null);return e.jsx(k1s,{scope:r,cancelRef:d,children:e.jsx(KW,{role:"alertdialog",...l,...i,ref:c,onOpenAutoFocus:Ra(i.onOpenAutoFocus,u=>{var h;u.preventDefault(),(h=d.current)==null||h.focus({preventScroll:!0})}),onPointerDownOutside:u=>u.preventDefault(),onInteractOutside:u=>u.preventDefault(),children:a})})},"AlertDialogContent")),A1s=j.forwardRef(AT(function(t,n){const{__scopeAlertDialog:r,...a}=t,i=ET(r);return e.jsx(Nae,{...i,...a,ref:n})},"AlertDialogTitle")),E1s=j.forwardRef(AT(function(t,n){const{__scopeAlertDialog:r,...a}=t,i=ET(r);return e.jsx(kae,{...i,...a,ref:n})},"AlertDialogDescription")),T1s=j.forwardRef(AT(function(t,n){const{__scopeAlertDialog:r,...a}=t,i=ET(r);return e.jsx(Sae,{...i,...a,ref:n})},"AlertDialogAction")),M1s="AlertDialogCancel",P1s=j.forwardRef(AT(function(t,n){const{__scopeAlertDialog:r,...a}=t,{cancelRef:i}=S1s(M1s,r),l=ET(r),o=Vo(n,i);return e.jsx(Sae,{...l,...a,ref:o})},"AlertDialogCancel")),I1s=b1s,L1s=_1s,R1s=w1s,mDt=j1s,fDt=C1s,pDt=T1s,gDt=P1s,xDt=A1s,yDt=E1s;const gG=DB("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"}}),$=j.forwardRef(({className:s,variant:t,size:n,asChild:r=!1,...a},i)=>{const l=r?set:"button";return e.jsx(l,{className:Pt(gG({variant:t,size:n,className:s})),ref:i,...a})});$.displayName="Button";const kc=I1s,jx=L1s,D1s=R1s,vDt=j.forwardRef(({className:s,...t},n)=>e.jsx(mDt,{className:Pt("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:n}));vDt.displayName=mDt.displayName;const cc=j.forwardRef(({className:s,...t},n)=>e.jsxs(D1s,{children:[e.jsx(vDt,{}),e.jsx(fDt,{ref:n,className:Pt("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})]}));cc.displayName=fDt.displayName;const dc=({className:s,...t})=>e.jsx("div",{className:Pt("flex flex-col space-y-2 text-center sm:text-left",s),...t});dc.displayName="AlertDialogHeader";const uc=({className:s,...t})=>e.jsx("div",{className:Pt("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",s),...t});uc.displayName="AlertDialogFooter";const hc=j.forwardRef(({className:s,...t},n)=>e.jsx(xDt,{ref:n,className:Pt("text-lg font-semibold",s),...t}));hc.displayName=xDt.displayName;const mc=j.forwardRef(({className:s,...t},n)=>e.jsx(yDt,{ref:n,className:Pt("text-sm text-muted-foreground",s),...t}));mc.displayName=yDt.displayName;const tc=j.forwardRef(({className:s,...t},n)=>e.jsx(pDt,{ref:n,className:Pt(gG(),s),...t}));tc.displayName=pDt.displayName;const fc=j.forwardRef(({className:s,...t},n)=>e.jsx(gDt,{ref:n,className:Pt(gG({variant:"outline"}),"mt-2 sm:mt-0",s),...t}));fc.displayName=gDt.displayName;let mEe=null;const F1s=["delete","remove","revoke","cannot be undone","permanently"];function fo(s,t={}){const n=typeof s=="string"?{description:s,...t}:s,r=`${n.title??""} ${n.description??""}`.toLowerCase(),a=n.destructive??F1s.some(i=>r.includes(i));return new Promise(i=>{if(!mEe){i(window.confirm(n.description??n.title??"Are you sure?"));return}mEe({...n,destructive:a,resolve:i})})}function O1s(){const[s,t]=j.useState(null);j.useEffect(()=>(mEe=a=>t(a),()=>{mEe=null}),[]);const n=a=>{s==null||s.resolve(a),t(null)},r=!!(s!=null&&s.destructive);return e.jsx(kc,{open:!!s,onOpenChange:a=>!a&&n(!1),children:e.jsxs(cc,{className:"sm:max-w-md",children:[e.jsx(dc,{children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:Pt("mt-0.5 flex h-10 w-10 shrink-0 items-center justify-center rounded-full",r?"bg-destructive/10 text-destructive":"bg-primary/10 text-primary"),children:e.jsx(wl,{className:"h-5 w-5"})}),e.jsxs("div",{className:"space-y-1.5 text-left",children:[e.jsx(hc,{children:(s==null?void 0:s.title)??(r?"Are you sure?":"Please confirm")}),(s==null?void 0:s.description)&&e.jsx(mc,{className:"leading-relaxed",children:s.description})]})]})}),e.jsxs(uc,{className:"gap-2 sm:gap-2",children:[e.jsx(fc,{onClick:()=>n(!1),children:(s==null?void 0:s.cancelText)??"Cancel"}),e.jsx(tc,{onClick:()=>n(!0),className:Pt(r&&"bg-destructive text-destructive-foreground hover:bg-destructive/90"),children:(s==null?void 0:s.confirmText)??(r?"Delete":"Continue")})]})]})})}const z1s=["top","right","bottom","left"],NL=Math.min,UE=Math.max,fEe=Math.round,_ce=Math.floor,qE=s=>({x:s,y:s}),B1s={left:"right",right:"left",bottom:"top",top:"bottom"};function bDt(s,t,n){return UE(s,NL(t,n))}function uT(s,t){return typeof s=="function"?s(t):s}function kL(s){return s.split("-")[0]}function YW(s){return s.split("-")[1]}function pet(s){return s==="x"?"y":"x"}function get(s){return s==="y"?"height":"width"}function g4(s){const t=s[0];return t==="t"||t==="b"?"y":"x"}function xet(s){return pet(g4(s))}function $1s(s,t,n){n===void 0&&(n=!1);const r=YW(s),a=xet(s),i=get(a);let l=a==="x"?r===(n?"end":"start")?"right":"left":r==="start"?"bottom":"top";return t.reference[i]>t.floating[i]&&(l=pEe(l)),[l,pEe(l)]}function U1s(s){const t=pEe(s);return[WVe(s),t,WVe(t)]}function WVe(s){return s.includes("start")?s.replace("start","end"):s.replace("end","start")}const Rgt=["left","right"],Dgt=["right","left"],q1s=["top","bottom"],V1s=["bottom","top"];function H1s(s,t,n){switch(s){case"top":case"bottom":return n?t?Dgt:Rgt:t?Rgt:Dgt;case"left":case"right":return t?q1s:V1s;default:return[]}}function G1s(s,t,n,r){const a=YW(s);let i=H1s(kL(s),n==="start",r);return a&&(i=i.map(l=>l+"-"+a),t&&(i=i.concat(i.map(WVe)))),i}function pEe(s){const t=kL(s);return B1s[t]+s.slice(t.length)}function W1s(s){var t,n,r,a;return{top:(t=s.top)!=null?t:0,right:(n=s.right)!=null?n:0,bottom:(r=s.bottom)!=null?r:0,left:(a=s.left)!=null?a:0}}function _Dt(s){return typeof s!="number"?W1s(s):{top:s,right:s,bottom:s,left:s}}function gEe(s){const{x:t,y:n,width:r,height:a}=s;return{width:r,height:a,top:n,left:t,right:t+r,bottom:n+a,x:t,y:n}}function Fgt(s,t,n){let{reference:r,floating:a}=s;const i=g4(t),l=xet(t),o=get(l),c=kL(t),d=i==="y",u=r.x+r.width/2-a.width/2,h=r.y+r.height/2-a.height/2,m=r[o]/2-a[o]/2;let f;switch(c){case"top":f={x:u,y:r.y-a.height};break;case"bottom":f={x:u,y:r.y+r.height};break;case"right":f={x:r.x+r.width,y:h};break;case"left":f={x:r.x-a.width,y:h};break;default:f={x:r.x,y:r.y}}const g=YW(t);return g&&(f[l]+=m*(g==="end"?1:-1)*(n&&d?-1:1)),f}async function K1s(s,t){var n;t===void 0&&(t={});const{x:r,y:a,platform:i,rects:l,elements:o,strategy:c}=s,{boundary:d="clippingAncestors",rootBoundary:u="viewport",elementContext:h="floating",altBoundary:m=!1,padding:f=0}=uT(t,s),g=_Dt(f),y=o[m?h==="floating"?"reference":"floating":h],v=gEe(await i.getClippingRect({element:(n=await(i.isElement==null?void 0:i.isElement(y)))==null||n?y:y.contextElement||await(i.getDocumentElement==null?void 0:i.getDocumentElement(o.floating)),boundary:d,rootBoundary:u,strategy:c})),b=h==="floating"?{x:r,y:a,width:l.floating.width,height:l.floating.height}:l.reference,w=await(i.getOffsetParent==null?void 0:i.getOffsetParent(o.floating)),S=await(i.isElement==null?void 0:i.isElement(w))&&await(i.getScale==null?void 0:i.getScale(w))||{x:1,y:1},C=gEe(i.convertOffsetParentRelativeRectToViewportRelativeRect?await i.convertOffsetParentRelativeRectToViewportRelativeRect({elements:o,rect:b,offsetParent:w,strategy:c}):b);return{top:(v.top-C.top+g.top)/S.y,bottom:(C.bottom-v.bottom+g.bottom)/S.y,left:(v.left-C.left+g.left)/S.x,right:(C.right-v.right+g.right)/S.x}}const Y1s=50,Z1s=async(s,t,n)=>{const{placement:r="bottom",strategy:a="absolute",middleware:i=[],platform:l}=n,o=l.detectOverflow?l:{...l,detectOverflow:K1s},c=await(l.isRTL==null?void 0:l.isRTL(t));let d=await l.getElementRects({reference:s,floating:t,strategy:a}),{x:u,y:h}=Fgt(d,r,c),m=r,f=0;const g={};for(let x=0;x({name:"arrow",options:s,async fn(t){const{x:n,y:r,placement:a,rects:i,platform:l,elements:o,middlewareData:c}=t,{element:d,padding:u=0}=uT(s,t)||{};if(d==null)return{};const h=_Dt(u),m={x:n,y:r},f=xet(a),g=get(f),x=await l.getDimensions(d),y=f==="y",v=y?"top":"left",b=y?"bottom":"right",w=y?"clientHeight":"clientWidth",S=i.reference[g]+i.reference[f]-m[f]-i.floating[g],C=m[f]-i.reference[f],E=await(l.getOffsetParent==null?void 0:l.getOffsetParent(d));let I=E?E[w]:0;(!I||!await(l.isElement==null?void 0:l.isElement(E)))&&(I=o.floating[w]||i.floating[g]);const P=S/2-C/2,R=I/2-x[g]/2-1,D=NL(h[v],R),O=NL(h[b],R),U=I-x[g]-O,W=I/2-x[g]/2+P,V=bDt(D,W,U),G=!c.arrow&&YW(a)!=null&&W!==V&&i.reference[g]/2-(WV<=0)){var O,U;const V=(((O=i.flip)==null?void 0:O.index)||0)+1,G=I[V];if(G&&(!(h==="alignment"?b!==g4(G):!1)||D.every(ae=>g4(ae.placement)===b?ae.overflows[0]>0:!0)))return{data:{index:V,overflows:D},reset:{placement:G}};let Y=(U=D.filter(X=>X.overflows[0]<=0).sort((X,ae)=>X.overflows[1]-ae.overflows[1])[0])==null?void 0:U.placement;if(!Y)switch(f){case"bestFit":{var W;const X=(W=D.filter(ae=>{if(E){const ie=g4(ae.placement);return ie===b||ie==="y"}return!0}).map(ae=>[ae.placement,ae.overflows.filter(ie=>ie>0).reduce((ie,ne)=>ie+ne,0)]).sort((ae,ie)=>ae[1]-ie[1])[0])==null?void 0:W[0];X&&(Y=X);break}case"initialPlacement":Y=o;break}if(a!==Y)return{reset:{placement:Y}}}return{}}}};function Ogt(s,t){return{top:s.top-t.height,right:s.right-t.width,bottom:s.bottom-t.height,left:s.left-t.width}}function zgt(s){return z1s.some(t=>s[t]>=0)}const J1s=function(s){return s===void 0&&(s={}),{name:"hide",options:s,async fn(t){const{rects:n,platform:r}=t,{strategy:a="referenceHidden",...i}=uT(s,t);switch(a){case"referenceHidden":{const l=await r.detectOverflow(t,{...i,elementContext:"reference"}),o=Ogt(l,n.reference);return{data:{referenceHiddenOffsets:o,referenceHidden:zgt(o)}}}case"escaped":{const l=await r.detectOverflow(t,{...i,altBoundary:!0}),o=Ogt(l,n.floating);return{data:{escapedOffsets:o,escaped:zgt(o)}}}default:return{}}}}},wDt=new Set(["left","top"]);async function e_s(s,t){const{placement:n,platform:r,elements:a}=s,i=await(r.isRTL==null?void 0:r.isRTL(a.floating)),l=kL(n),o=YW(n),c=g4(n)==="y",d=wDt.has(l)?-1:1,u=i&&c?-1:1,h=uT(t,s);let{mainAxis:m,crossAxis:f,alignmentAxis:g}=typeof h=="number"?{mainAxis:h,crossAxis:0,alignmentAxis:null}:{mainAxis:h.mainAxis||0,crossAxis:h.crossAxis||0,alignmentAxis:h.alignmentAxis};return o&&typeof g=="number"&&(f=o==="end"?g*-1:g),c?{x:f*u,y:m*d}:{x:m*d,y:f*u}}const t_s=function(s){return s===void 0&&(s=0),{name:"offset",options:s,async fn(t){var n,r;const{x:a,y:i,placement:l,middlewareData:o}=t,c=await e_s(t,s);return l===((n=o.offset)==null?void 0:n.placement)&&(r=o.arrow)!=null&&r.alignmentOffset?{}:{x:a+c.x,y:i+c.y,data:{...c,placement:l}}}}},s_s=function(s){return s===void 0&&(s={}),{name:"shift",options:s,async fn(t){const{x:n,y:r,placement:a,platform:i}=t,{mainAxis:l=!0,crossAxis:o=!1,limiter:c={fn:b=>{let{x:w,y:S}=b;return{x:w,y:S}}},...d}=uT(s,t),u={x:n,y:r},h=await i.detectOverflow(t,d),m=g4(a),f=pet(m);let g=u[f],x=u[m];const y=(b,w)=>bDt(w+h[b==="y"?"top":"left"],w,w-h[b==="y"?"bottom":"right"]);l&&(g=y(f,g)),o&&(x=y(m,x));const v=c.fn({...t,[f]:g,[m]:x});return{...v,data:{x:v.x-n,y:v.y-r,enabled:{[f]:l,[m]:o}}}}}},n_s=function(s){return s===void 0&&(s={}),{options:s,fn(t){var n,r;const{x:a,y:i,placement:l,rects:o,middlewareData:c}=t,{offset:d=0,mainAxis:u=!0,crossAxis:h=!0}=uT(s,t),m={x:a,y:i},f=g4(l),g=pet(f);let x=m[g],y=m[f];const v=uT(d,t),b=typeof v=="number"?{mainAxis:v,crossAxis:0}:{mainAxis:(n=v.mainAxis)!=null?n:0,crossAxis:(r=v.crossAxis)!=null?r:0};if(u){const C=g==="y"?"height":"width",E=o.reference[g]-o.floating[C]+b.mainAxis,I=o.reference[g]+o.reference[C]-b.mainAxis;xI&&(x=I)}if(h){var w,S;const C=g==="y"?"width":"height",E=wDt.has(kL(l)),I=o.reference[f]-o.floating[C]+(E&&((w=c.offset)==null?void 0:w[f])||0)+(E?0:b.crossAxis),P=o.reference[f]+o.reference[C]+(E?0:((S=c.offset)==null?void 0:S[f])||0)-(E?b.crossAxis:0);yP&&(y=P)}return{[g]:x,[f]:y}}}},r_s=function(s){return s===void 0&&(s={}),{name:"size",options:s,async fn(t){const{placement:n,rects:r,platform:a,elements:i}=t,{apply:l=()=>{},...o}=uT(s,t),c=await a.detectOverflow(t,o),d=kL(n),u=YW(n),h=g4(n)==="y",{width:m,height:f}=r.floating;let g,x;d==="top"||d==="bottom"?(g=d,x=u===(await(a.isRTL==null?void 0:a.isRTL(i.floating))?"start":"end")?"left":"right"):(x=d,g=u==="end"?"top":"bottom");const y=f-c.top-c.bottom,v=m-c.left-c.right,b=NL(f-c[g],y),w=NL(m-c[x],v),S=t.middlewareData.shift,C=!S;let E=b,I=w;S!=null&&S.enabled.x&&(I=v),S!=null&&S.enabled.y&&(E=y),C&&!u&&(h?I=m-2*UE(c.left,c.right):E=f-2*UE(c.top,c.bottom)),await l({...t,availableWidth:I,availableHeight:E});const P=await a.getDimensions(i.floating);return m!==P.width||f!==P.height?{reset:{rects:!0}}:{}}}};function QIe(){return typeof window<"u"}function ZW(s){return jDt(s)?(s.nodeName||"").toLowerCase():"#document"}function Dw(s){var t;return(s==null||(t=s.ownerDocument)==null?void 0:t.defaultView)||window}function TT(s){var t;return(t=(jDt(s)?s.ownerDocument:s.document)||window.document)==null?void 0:t.documentElement}function jDt(s){return QIe()?s instanceof Node||s instanceof Dw(s).Node:!1}function G4(s){return QIe()?s instanceof Element||s instanceof Dw(s).Element:!1}function s6(s){return QIe()?s instanceof HTMLElement||s instanceof Dw(s).HTMLElement:!1}function Bgt(s){return!QIe()||typeof ShadowRoot>"u"?!1:s instanceof ShadowRoot||s instanceof Dw(s).ShadowRoot}function JIe(s){const{overflow:t,overflowX:n,overflowY:r,display:a}=W4(s);return/auto|scroll|overlay|hidden|clip/.test(t+r+n)&&a!=="inline"&&a!=="contents"}function a_s(s){return/^(table|td|th)$/.test(ZW(s))}function eLe(s){try{if(s.matches(":popover-open"))return!0}catch{}try{return s.matches(":modal")}catch{return!1}}const i_s=/transform|translate|scale|rotate|perspective|filter/,o_s=/paint|layout|strict|content/,mR=s=>!!s&&s!=="none";let Pze;function yet(s){const t=G4(s)?W4(s):s;return mR(t.transform)||mR(t.translate)||mR(t.scale)||mR(t.rotate)||mR(t.perspective)||!vet()&&(mR(t.backdropFilter)||mR(t.filter))||i_s.test(t.willChange||"")||o_s.test(t.contain||"")}function l_s(s){let t=$7(s);for(;s6(t)&&!Gte(t);){if(yet(t))return t;if(eLe(t))return null;t=$7(t)}return null}function vet(){return Pze==null&&(Pze=typeof CSS<"u"&&CSS.supports&&CSS.supports("-webkit-backdrop-filter","none")),Pze}function Gte(s){return/^(html|body|#document)$/.test(ZW(s))}function W4(s){return Dw(s).getComputedStyle(s)}function tLe(s){return G4(s)?{scrollLeft:s.scrollLeft,scrollTop:s.scrollTop}:{scrollLeft:s.scrollX,scrollTop:s.scrollY}}function $7(s){if(ZW(s)==="html")return s;const t=s.assignedSlot||s.parentNode||Bgt(s)&&s.host||TT(s);return Bgt(t)?t.host:t}function NDt(s){const t=$7(s);return Gte(t)?(s.ownerDocument||s).body:s6(t)&&JIe(t)?t:NDt(t)}function Wte(s,t,n){var r;t===void 0&&(t=[]),n===void 0&&(n=!0);const a=NDt(s),i=a===((r=s.ownerDocument)==null?void 0:r.body),l=Dw(a);if(i){const o=KVe(l);return t.concat(l,l.visualViewport||[],JIe(a)?a:[],o&&n?Wte(o):[])}else return t.concat(a,Wte(a,[],n))}function KVe(s){return s.parent&&Object.getPrototypeOf(s.parent)?s.frameElement:null}function kDt(s){const t=W4(s);let n=parseFloat(t.width)||0,r=parseFloat(t.height)||0;const a=s6(s),i=a?s.offsetWidth:n,l=a?s.offsetHeight:r,o=fEe(n)!==i||fEe(r)!==l;return o&&(n=i,r=l),{width:n,height:r,$:o}}function bet(s){return G4(s)?s:s.contextElement}function _V(s){const t=bet(s);if(!s6(t))return qE(1);const n=t.getBoundingClientRect(),{width:r,height:a,$:i}=kDt(t);let l=(i?fEe(n.width):n.width)/r,o=(i?fEe(n.height):n.height)/a;return(!l||!Number.isFinite(l))&&(l=1),(!o||!Number.isFinite(o))&&(o=1),{x:l,y:o}}const c_s=qE(0);function SDt(s){const t=Dw(s);return!vet()||!t.visualViewport?c_s:{x:t.visualViewport.offsetLeft,y:t.visualViewport.offsetTop}}function d_s(s,t,n){return t===void 0&&(t=!1),!!n&&t&&n===Dw(s)}function U7(s,t,n,r){t===void 0&&(t=!1),n===void 0&&(n=!1);const a=s.getBoundingClientRect(),i=bet(s);let l=qE(1);t&&(r?G4(r)&&(l=_V(r)):l=_V(s));const o=d_s(i,n,r)?SDt(i):qE(0);let c=(a.left+o.x)/l.x,d=(a.top+o.y)/l.y,u=a.width/l.x,h=a.height/l.y;if(i&&r){const m=Dw(i),f=G4(r)?Dw(r):r;let g=m,x=KVe(g);for(;x&&f!==g;){const y=_V(x),v=x.getBoundingClientRect(),b=W4(x),w=v.left+(x.clientLeft+parseFloat(b.paddingLeft))*y.x,S=v.top+(x.clientTop+parseFloat(b.paddingTop))*y.y;c*=y.x,d*=y.y,u*=y.x,h*=y.y,c+=w,d+=S,g=Dw(x),x=KVe(g)}}return gEe({width:u,height:h,x:c,y:d})}function sLe(s,t){const n=tLe(s).scrollLeft;return t?t.left+n:U7(TT(s)).left+n}function CDt(s,t){const n=s.getBoundingClientRect(),r=n.left+t.scrollLeft-sLe(s,n),a=n.top+t.scrollTop;return{x:r,y:a}}function u_s(s){let{elements:t,rect:n,offsetParent:r,strategy:a}=s;const i=a==="fixed",l=TT(r),o=t?eLe(t.floating):!1;if(r===l||o&&i)return n;let c={scrollLeft:0,scrollTop:0},d=qE(1);const u=qE(0),h=s6(r);if((h||!i)&&((ZW(r)!=="body"||JIe(l))&&(c=tLe(r)),h)){const f=U7(r);d=_V(r),u.x=f.x+r.clientLeft,u.y=f.y+r.clientTop}const m=l&&!h&&!i?CDt(l,c):qE(0);return{width:n.width*d.x,height:n.height*d.y,x:n.x*d.x-c.scrollLeft*d.x+u.x+m.x,y:n.y*d.y-c.scrollTop*d.y+u.y+m.y}}function h_s(s){return s.getClientRects?Array.from(s.getClientRects()):[]}function m_s(s){const t=tLe(s),n=s.ownerDocument.body,r=UE(s.scrollWidth,s.clientWidth,n.scrollWidth,n.clientWidth),a=UE(s.scrollHeight,s.clientHeight,n.scrollHeight,n.clientHeight);let i=-t.scrollLeft+sLe(s);const l=-t.scrollTop;return W4(n).direction==="rtl"&&(i+=UE(s.clientWidth,n.clientWidth)-r),{width:r,height:a,x:i,y:l}}const f_s=25;function p_s(s,t,n){n===void 0&&(n="viewport");const r=n==="layoutViewport",a=Dw(s),i=TT(s),l=a.visualViewport;let o=i.clientWidth,c=i.clientHeight,d=0,u=0;if(l){const m=!vet()||t==="fixed";r?m||(d=-l.offsetLeft,u=-l.offsetTop):(o=l.width,c=l.height,m&&(d=l.offsetLeft,u=l.offsetTop))}if(sLe(i)<=0){const m=i.ownerDocument,f=m.body,g=getComputedStyle(f),x=m.compatMode==="CSS1Compat"&&parseFloat(g.marginLeft)+parseFloat(g.marginRight)||0,y=Math.abs(i.clientWidth-f.clientWidth-x),v=getComputedStyle(i).scrollbarGutter==="stable both-edges"?y/2:y;v<=f_s&&(o-=v)}return{width:o,height:c,x:d,y:u}}function g_s(s,t){const n=U7(s,!0,t==="fixed"),r=n.top+s.clientTop,a=n.left+s.clientLeft,i=_V(s),l=s.clientWidth*i.x,o=s.clientHeight*i.y,c=a*i.x,d=r*i.y;return{width:l,height:o,x:c,y:d}}function $gt(s,t,n){let r;if(t==="viewport"||t==="layoutViewport")r=p_s(s,n,t);else if(t==="document")r=m_s(TT(s));else if(G4(t))r=g_s(t,n);else{const a=SDt(s);r={x:t.x-a.x,y:t.y-a.y,width:t.width,height:t.height}}return gEe(r)}function x_s(s,t){const n=t.get(s);if(n)return n;let r=Wte(s,[],!1).filter(o=>G4(o)&&ZW(o)!=="body"),a=null;const i=W4(s).position==="fixed";let l=i?$7(s):s;for(;G4(l)&&!Gte(l);){const o=W4(l),c=yet(l),d=a?a.position:i?"fixed":"";!c&&(d==="fixed"||d==="absolute"&&o.position==="static")?r=r.filter(h=>h!==l):a=o,l=$7(l)}return t.set(s,r),r}function y_s(s){let{element:t,boundary:n,rootBoundary:r,strategy:a}=s;const l=[...n==="clippingAncestors"?eLe(t)?[]:x_s(t,this._c):[].concat(n),r],o=$gt(t,l[0],a);let c=o.top,d=o.right,u=o.bottom,h=o.left;for(let m=1;m{o(!1,1e-7)},1e3)}I=!1}try{r=new IntersectionObserver(P,{...E,root:i.ownerDocument})}catch{r=new IntersectionObserver(P,E)}r.observe(s)}const c=Dw(s),d=()=>o(n);return c.addEventListener("resize",d),o(!0),()=>{c.removeEventListener("resize",d),l()}}function k_s(s,t,n,r){r===void 0&&(r={});const{ancestorScroll:a=!0,ancestorResize:i=!0,elementResize:l=typeof ResizeObserver=="function",layoutShift:o=typeof IntersectionObserver=="function",animationFrame:c=!1}=r,d=bet(s),u=a||i?[...d?Wte(d):[],...t?Wte(t):[]]:[];u.forEach(v=>{a&&v.addEventListener("scroll",n),i&&v.addEventListener("resize",n)});const h=d&&o?N_s(d,n,i):null;let m=-1,f=null;l&&(f=new ResizeObserver(v=>{let[b]=v;b&&b.target===d&&f&&t&&(f.unobserve(t),cancelAnimationFrame(m),m=requestAnimationFrame(()=>{var w;(w=f)==null||w.observe(t)})),n()}),d&&!c&&f.observe(d),t&&f.observe(t));let g,x=c?U7(s):null;c&&y();function y(){const v=U7(s);x&&!EDt(x,v)&&n(),x=v,g=requestAnimationFrame(y)}return n(),()=>{var v;u.forEach(b=>{a&&b.removeEventListener("scroll",n),i&&b.removeEventListener("resize",n)}),h==null||h(),(v=f)==null||v.disconnect(),f=null,c&&cancelAnimationFrame(g)}}const S_s=t_s,C_s=s_s,A_s=Q1s,E_s=r_s,T_s=J1s,qgt=X1s,M_s=n_s,P_s=(s,t,n)=>{const r=new Map,a=n??{},i={...j_s,...a.platform,_c:r};return Z1s(s,t,{...a,platform:i})};var I_s=typeof document<"u",L_s=function(){},V4e=I_s?j.useLayoutEffect:L_s;function xEe(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 n,r,a;if(s&&t&&typeof s=="object"){if(Array.isArray(s)){if(n=s.length,n!==t.length)return!1;for(r=n;r--!==0;)if(!xEe(s[r],t[r]))return!1;return!0}if(a=Object.keys(s),n=a.length,n!==Object.keys(t).length)return!1;for(r=n;r--!==0;)if(!{}.hasOwnProperty.call(t,a[r]))return!1;for(r=n;r--!==0;){const i=a[r];if(!(i==="_owner"&&s.$$typeof)&&!xEe(s[i],t[i]))return!1}return!0}return s!==s&&t!==t}function TDt(s){return typeof window>"u"?1:(s.ownerDocument.defaultView||window).devicePixelRatio||1}function Vgt(s,t){const n=TDt(s);return Math.round(t*n)/n}function Lze(s){const t=j.useRef(s);return V4e(()=>{t.current=s}),t}function R_s(s){s===void 0&&(s={});const{placement:t="bottom",strategy:n="absolute",middleware:r=[],platform:a,elements:{reference:i,floating:l}={},transform:o=!0,whileElementsMounted:c,open:d}=s,[u,h]=j.useState({x:0,y:0,strategy:n,placement:t,middlewareData:{},isPositioned:!1}),[m,f]=j.useState(r);xEe(m,r)||f(r);const[g,x]=j.useState(null),[y,v]=j.useState(null),b=j.useCallback(ae=>{ae!==E.current&&(E.current=ae,x(ae))},[]),w=j.useCallback(ae=>{ae!==I.current&&(I.current=ae,v(ae))},[]),S=i||g,C=l||y,E=j.useRef(null),I=j.useRef(null),P=j.useRef(u),R=c!=null,D=Lze(c),O=Lze(a),U=Lze(d),W=j.useCallback(()=>{if(!E.current||!I.current)return;const ae={placement:t,strategy:n,middleware:m};O.current&&(ae.platform=O.current),P_s(E.current,I.current,ae).then(ie=>{const ne={...ie,isPositioned:U.current!==!1};V.current&&!xEe(P.current,ne)&&(P.current=ne,wv.flushSync(()=>{h(ne)}))})},[m,t,n,O,U]);V4e(()=>{d===!1&&P.current.isPositioned&&(P.current.isPositioned=!1,h(ae=>({...ae,isPositioned:!1})))},[d]);const V=j.useRef(!1);V4e(()=>(V.current=!0,()=>{V.current=!1}),[]),V4e(()=>{if(S&&(E.current=S),C&&(I.current=C),S&&C){if(D.current)return D.current(S,C,W);W()}},[S,C,W,D,R]);const G=j.useMemo(()=>({reference:E,floating:I,setReference:b,setFloating:w}),[b,w]),Y=j.useMemo(()=>({reference:S,floating:C}),[S,C]),X=j.useMemo(()=>{const ae={position:n,left:0,top:0};if(!Y.floating)return ae;const ie=Vgt(Y.floating,u.x),ne=Vgt(Y.floating,u.y);return o?{...ae,transform:"translate("+ie+"px, "+ne+"px)",...TDt(Y.floating)>=1.5&&{willChange:"transform"}}:{position:n,left:ie,top:ne}},[n,o,Y.floating,u.x,u.y]);return j.useMemo(()=>({...u,update:W,refs:G,elements:Y,floatingStyles:X}),[u,W,G,Y,X])}const D_s=s=>{function t(n){return{}.hasOwnProperty.call(n,"current")}return{name:"arrow",options:s,fn(n){const{element:r,padding:a}=typeof s=="function"?s(n):s;return r&&t(r)?r.current!=null?qgt({element:r.current,padding:a}).fn(n):{}:r?qgt({element:r,padding:a}).fn(n):{}}}},F_s=(s,t)=>{const n=S_s(s);return{name:n.name,fn:n.fn,options:[s,t]}},O_s=(s,t)=>{const n=C_s(s);return{name:n.name,fn:n.fn,options:[s,t]}},z_s=(s,t)=>({fn:M_s(s).fn,options:[s,t]}),B_s=(s,t)=>{const n=A_s(s);return{name:n.name,fn:n.fn,options:[s,t]}},$_s=(s,t)=>{const n=E_s(s);return{name:n.name,fn:n.fn,options:[s,t]}},U_s=(s,t)=>{const n=T_s(s);return{name:n.name,fn:n.fn,options:[s,t]}},q_s=(s,t)=>{const n=D_s(s);return{name:n.name,fn:n.fn,options:[s,t]}};var V_s=Object.defineProperty,H_s=(s,t)=>V_s(s,"name",{value:t,configurable:!0});function XW(s){const[t,n]=j.useState(void 0);return Ef(()=>{if(s){n({width:s.offsetWidth,height:s.offsetHeight});const r=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;n({width:l,height:o})});return r.observe(s,{box:"border-box"}),()=>r.unobserve(s)}else n(void 0)},[s]),t}H_s(XW,"useSize");var G_s=Object.defineProperty,rL=(s,t)=>G_s(s,"name",{value:t,configurable:!0}),MDt="Popper",[PDt,i3]=tp(MDt),[W_s,IDt]=PDt(MDt),K_s=rL(s=>{const{__scopePopper:t,children:n}=s,[r,a]=j.useState(null),[i,l]=j.useState(void 0);return e.jsx(W_s,{scope:t,anchor:r,onAnchorChange:a,placementState:i,setPlacementState:l,children:n})},"Popper"),Y_s="PopperAnchor",Z_s=j.forwardRef(rL(function(t,n){const{__scopePopper:r,virtualRef:a,...i}=t,l=IDt(Y_s,r),o=j.useRef(null),c=l.onAnchorChange,d=j.useCallback(x=>{o.current=x,x&&c(x)},[c]),u=Vo(n,d),h=j.useRef(null);j.useEffect(()=>{if(!a)return;const x=h.current;h.current=a.current,x!==h.current&&c(h.current)});const m=l.placementState&&nLe(l.placementState),f=m==null?void 0:m[0],g=m==null?void 0:m[1];return a?null:e.jsx(Ei.div,{"data-radix-popper-side":f,"data-radix-popper-align":g,...i,ref:u})},"PopperAnchor")),LDt="PopperContent",[X_s,Ikr]=PDt(LDt),Q_s=j.forwardRef(rL(function(t,n){var Se,Le,Fe,ke,Ve,je,Ae;const{__scopePopper:r,side:a="bottom",sideOffset:i=0,align:l="center",alignOffset:o=0,arrowPadding:c=0,avoidCollisions:d=!0,collisionBoundary:u=[],collisionPadding:h=0,sticky:m="partial",hideWhenDetached:f=!1,updatePositionStrategy:g="optimized",onPlaced:x,...y}=t,v=IDt(LDt,r),[b,w]=j.useState(null),S=Vo(n,w),[C,E]=j.useState(null),I=XW(C),P=(I==null?void 0:I.width)??0,R=(I==null?void 0:I.height)??0,D=a+(l!=="center"?"-"+l:""),O=typeof h=="number"?h:{top:0,right:0,bottom:0,left:0,...h},U=Array.isArray(u)?u:[u],W=U.length>0,V={padding:O,boundary:U.filter(RDt),altBoundary:W},{refs:G,floatingStyles:Y,placement:X,isPositioned:ae,middlewareData:ie}=R_s({strategy:"fixed",placement:D,whileElementsMounted:rL((...Ce)=>k_s(...Ce,{animationFrame:g==="always"}),"whileElementsMounted"),elements:{reference:v.anchor},middleware:[F_s({mainAxis:i+R,alignmentAxis:o}),d&&O_s({mainAxis:!0,crossAxis:!1,limiter:m==="partial"?z_s():void 0,...V}),d&&B_s({...V}),$_s({...V,apply:rL(({elements:Ce,rects:qe,availableWidth:ze,availableHeight:$e})=>{const{width:ct,height:Xe}=qe.reference,it=Ce.floating.style;it.setProperty("--radix-popper-available-width",`${ze}px`),it.setProperty("--radix-popper-available-height",`${$e}px`),it.setProperty("--radix-popper-anchor-width",`${ct}px`),it.setProperty("--radix-popper-anchor-height",`${Xe}px`)},"apply")}),C&&q_s({element:C,padding:c}),J_s({arrowWidth:P,arrowHeight:R}),f&&U_s({strategy:"referenceHidden",...V,boundary:W?V.boundary:void 0})]}),ne=v.setPlacementState;Ef(()=>(ne(X),()=>{ne(void 0)}),[X,ne]);const[te,J]=nLe(X),ce=Yp(x);Ef(()=>{ae&&(ce==null||ce())},[ae,ce]);const _e=(Se=ie.arrow)==null?void 0:Se.x,he=(Le=ie.arrow)==null?void 0:Le.y,ue=((Fe=ie.arrow)==null?void 0:Fe.centerOffset)!==0,[ve,Ee]=j.useState();return Ef(()=>{b&&Ee(window.getComputedStyle(b).zIndex)},[b]),e.jsx("div",{ref:G.setFloating,"data-radix-popper-content-wrapper":"",style:{...Y,transform:ae?Y.transform:"translate(0, -200%)",minWidth:"max-content",zIndex:ve,"--radix-popper-transform-origin":[(ke=ie.transformOrigin)==null?void 0:ke.x,(Ve=ie.transformOrigin)==null?void 0:Ve.y].join(" "),...((je=ie.hide)==null?void 0:je.referenceHidden)&&{visibility:"hidden",pointerEvents:"none"}},dir:t.dir,children:e.jsx(X_s,{scope:r,placedSide:te,placedAlign:J,onArrowChange:E,arrowX:_e,arrowY:he,shouldHideArrow:ue,children:e.jsx(Ei.div,{"data-side":te,"data-align":J,...y,ref:S,style:{...y.style,animation:ae?(Ae=y.style)==null?void 0:Ae.animation:"none"}})})})},"PopperContent"));function RDt(s){return s!==null}rL(RDt,"isNotNull");var J_s=rL(s=>({name:"transformOrigin",options:s,fn(t){var y,v,b;const{placement:n,rects:r,middlewareData:a}=t,l=((y=a.arrow)==null?void 0:y.centerOffset)!==0,o=l?0:s.arrowWidth,c=l?0:s.arrowHeight,[d,u]=nLe(n),h={start:"0%",center:"50%",end:"100%"}[u],m=(((v=a.arrow)==null?void 0:v.x)??0)+o/2,f=(((b=a.arrow)==null?void 0:b.y)??0)+c/2;let g="",x="";return d==="bottom"?(g=l?h:`${m}px`,x=`${-c}px`):d==="top"?(g=l?h:`${m}px`,x=`${r.floating.height+c}px`):d==="right"?(g=`${-c}px`,x=l?h:`${f}px`):d==="left"&&(g=`${r.floating.width+c}px`,x=l?h:`${f}px`),{data:{x:g,y:x}}}}),"transformOrigin");function nLe(s){const[t,n="center"]=s.split("-");return[t,n]}rL(nLe,"getSideAndAlignFromPlacement");var Cae=K_s,Aae=Z_s,Eae=Q_s,ews=Object.defineProperty,mb=(s,t)=>ews(s,"name",{value:t,configurable:!0}),[_et,Lkr]=tp("Tooltip",[i3]),wet=i3(),tws="TooltipProvider",sws=700,YVe="tooltip.open",[nws,jet]=_et(tws),rws=mb(s=>{const{__scopeTooltip:t,delayDuration:n=sws,skipDelayDuration:r=300,disableHoverableContent:a=!1,children:i}=s,l=j.useRef(!0),o=j.useRef(!1),c=j.useRef(0);return j.useEffect(()=>{const d=c.current;return()=>window.clearTimeout(d)},[]),e.jsx(nws,{scope:t,isOpenDelayedRef:l,delayDuration:n,onOpen:j.useCallback(()=>{r<=0||(window.clearTimeout(c.current),l.current=!1)},[r]),onClose:j.useCallback(()=>{r<=0||(window.clearTimeout(c.current),c.current=window.setTimeout(()=>l.current=!0,r))},[r]),isPointerInTransitRef:o,onPointerInTransitChange:j.useCallback(d=>{o.current=d},[]),disableHoverableContent:a,children:i})},"TooltipProvider"),ZVe="Tooltip",[aws,rLe]=_et(ZVe),iws=mb(s=>{const{__scopeTooltip:t,children:n,open:r,defaultOpen:a,onOpenChange:i,disableHoverableContent:l,delayDuration:o}=s,c=jet(ZVe,s.__scopeTooltip),d=wet(t),[u,h]=j.useState(null),[m,f]=j.useState(void 0),g=my(),x=j.useRef(0),y=l??c.disableHoverableContent,v=o??c.delayDuration,b=j.useRef(!1),[w,S]=fy({prop:r,defaultProp:a??!1,onChange:mb(D=>{D?(c.onOpen(),document.dispatchEvent(new CustomEvent(YVe))):c.onClose(),i==null||i(D)},"onChange"),caller:ZVe}),C=j.useMemo(()=>w?b.current?"delayed-open":"instant-open":"closed",[w]),E=j.useCallback(()=>{window.clearTimeout(x.current),x.current=0,b.current=!1,S(!0)},[S]),I=j.useCallback(()=>{window.clearTimeout(x.current),x.current=0,S(!1)},[S]),P=j.useCallback(()=>{window.clearTimeout(x.current),x.current=window.setTimeout(()=>{b.current=!0,S(!0),x.current=0},v)},[v,S]);j.useEffect(()=>()=>{x.current&&(window.clearTimeout(x.current),x.current=0)},[]);const R=m??g;return e.jsx(Cae,{...d,children:e.jsx(aws,{scope:t,contentId:R,setContentId:f,open:w,stateAttribute:C,trigger:u,onTriggerChange:h,onTriggerEnter:j.useCallback(()=>{c.isOpenDelayedRef.current?P():E()},[c.isOpenDelayedRef,P,E]),onTriggerLeave:j.useCallback(()=>{y?I():(window.clearTimeout(x.current),x.current=0)},[I,y]),onOpen:E,onClose:I,disableHoverableContent:y,children:n})})},"Tooltip"),Hgt="TooltipTrigger",ows=j.forwardRef(mb(function(t,n){const{__scopeTooltip:r,...a}=t,i=rLe(Hgt,r),l=jet(Hgt,r),o=wet(r),c=j.useRef(null),d=Vo(n,c,i.onTriggerChange),u=j.useRef(!1),h=j.useRef(!1),m=j.useCallback(()=>u.current=!1,[]);return j.useEffect(()=>()=>document.removeEventListener("pointerup",m),[m]),e.jsx(Aae,{asChild:!0,...o,children:e.jsx(Ei.button,{"aria-describedby":i.open?i.contentId:void 0,"data-state":i.stateAttribute,...a,ref:d,onPointerMove:Ra(t.onPointerMove,f=>{f.pointerType!=="touch"&&!h.current&&!l.isPointerInTransitRef.current&&(i.onTriggerEnter(),h.current=!0)}),onPointerLeave:Ra(t.onPointerLeave,()=>{i.onTriggerLeave(),h.current=!1}),onPointerDown:Ra(t.onPointerDown,()=>{i.open&&i.onClose(),u.current=!0,document.addEventListener("pointerup",m,{once:!0})}),onFocus:Ra(t.onFocus,()=>{u.current||i.onOpen()}),onBlur:Ra(t.onBlur,i.onClose),onClick:Ra(t.onClick,i.onClose)})})},"TooltipTrigger")),lws="TooltipPortal",[Rkr,cws]=_et(lws,{forceMount:void 0}),Kte="TooltipContent",dws=j.forwardRef(mb(function(t,n){const r=cws(Kte,t.__scopeTooltip),{forceMount:a=r.forceMount,side:i="top",...l}=t,o=rLe(Kte,t.__scopeTooltip);return e.jsx(xy,{present:a||o.open,children:o.disableHoverableContent?e.jsx(DDt,{side:i,...l,ref:n}):e.jsx(uws,{side:i,...l,ref:n})})},"TooltipContent")),uws=j.forwardRef(mb(function(t,n){const r=rLe(Kte,t.__scopeTooltip),a=jet(Kte,t.__scopeTooltip),i=j.useRef(null),l=Vo(n,i),[o,c]=j.useState(null),{trigger:d,onClose:u}=r,h=i.current,{onPointerInTransitChange:m}=a,f=j.useCallback(()=>{c(null),m(!1)},[m]),g=j.useCallback((x,y)=>{const v=x.currentTarget,b={x:x.clientX,y:x.clientY},w=FDt(b,v.getBoundingClientRect()),S=ODt(b,w),C=zDt(y.getBoundingClientRect()),E=$Dt([...S,...C]);c(E),m(!0)},[m]);return j.useEffect(()=>()=>f(),[f]),j.useEffect(()=>{if(d&&h){const x=mb(v=>g(v,h),"handleTriggerLeave"),y=mb(v=>g(v,d),"handleContentLeave");return d.addEventListener("pointerleave",x),h.addEventListener("pointerleave",y),()=>{d.removeEventListener("pointerleave",x),h.removeEventListener("pointerleave",y)}}},[d,h,g,f]),j.useEffect(()=>{if(o){const x=mb(y=>{const v=y.target,b={x:y.clientX,y:y.clientY},w=(d==null?void 0:d.contains(v))||(h==null?void 0:h.contains(v)),S=!BDt(b,o);w?f():S&&(f(),u())},"handleTrackPointerGrace");return document.addEventListener("pointermove",x),()=>document.removeEventListener("pointermove",x)}},[d,h,o,u,f]),e.jsx(DDt,{...t,ref:l})},"TooltipContentHoverable")),hws=tRt("TooltipContent"),DDt=j.forwardRef(mb(function(t,n){const{__scopeTooltip:r,children:a,"aria-label":i,id:l,onEscapeKeyDown:o,onPointerDownOutside:c,...d}=t,u=rLe(Kte,r),h=wet(r),{onClose:m}=u;j.useEffect(()=>(document.addEventListener(YVe,m),()=>document.removeEventListener(YVe,m)),[m]),j.useEffect(()=>{if(u.trigger){const g=mb(x=>{x.target instanceof Node&&x.target.contains(u.trigger)&&m()},"handleScroll");return window.addEventListener("scroll",g,{capture:!0}),()=>window.removeEventListener("scroll",g,{capture:!0})}},[u.trigger,m]);const{setContentId:f}=u;return Ef(()=>(f(l),()=>{f(void 0)}),[l,f]),e.jsx(RB,{asChild:!0,disableOutsidePointerEvents:!1,onEscapeKeyDown:o,onPointerDownOutside:c,onFocusOutside:g=>g.preventDefault(),onDismiss:m,children:e.jsxs(Eae,{"data-state":u.stateAttribute,role:i?void 0:"tooltip",id:i?void 0:u.contentId,...h,...d,ref:n,style:{...d.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(hws,{children:a}),i?e.jsx(C0s,{id:u.contentId,role:"tooltip",children:i}):null]})})},"TooltipContentImpl"));function FDt(s,t){const n=Math.abs(t.top-s.y),r=Math.abs(t.bottom-s.y),a=Math.abs(t.right-s.x),i=Math.abs(t.left-s.x);switch(Math.min(n,r,a,i)){case i:return"left";case a:return"right";case n:return"top";case r:return"bottom";default:throw new Error("unreachable")}}mb(FDt,"getExitSideFromRect");function ODt(s,t,n=5){const r=[];switch(t){case"top":r.push({x:s.x-n,y:s.y+n},{x:s.x+n,y:s.y+n});break;case"bottom":r.push({x:s.x-n,y:s.y-n},{x:s.x+n,y:s.y-n});break;case"left":r.push({x:s.x+n,y:s.y-n},{x:s.x+n,y:s.y+n});break;case"right":r.push({x:s.x-n,y:s.y-n},{x:s.x-n,y:s.y+n});break}return r}mb(ODt,"getPaddedExitPoints");function zDt(s){const{top:t,right:n,bottom:r,left:a}=s;return[{x:a,y:t},{x:n,y:t},{x:n,y:r},{x:a,y:r}]}mb(zDt,"getPointsFromRect");function BDt(s,t){const{x:n,y:r}=s;let a=!1;for(let i=0,l=t.length-1;ir!=m>r&&n<(h-d)*(r-u)/(m-u)+d&&(a=!a)}return a}mb(BDt,"isPointInPolygon");function $Dt(s){const t=s.slice();return t.sort((n,r)=>n.xr.x?1:n.yr.y?1:0),UDt(t)}mb($Dt,"getHull");function UDt(s){if(s.length<=1)return s.slice();const t=[];for(let r=0;r=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 n=[];for(let r=s.length-1;r>=0;r--){const a=s[r];for(;n.length>=2;){const i=n[n.length-1],l=n[n.length-2];if((i.x-l.x)*(a.y-l.y)>=(i.y-l.y)*(a.x-l.x))n.pop();else break}n.push(a)}return n.pop(),t.length===1&&n.length===1&&t[0].x===n[0].x&&t[0].y===n[0].y?t:t.concat(n)}mb(UDt,"getHullPresorted");var mws=rws,fws=iws,pws=ows,qDt=dws;const jk=mws,ly=fws,cy=pws,Nx=j.forwardRef(({className:s,sideOffset:t=4,...n},r)=>e.jsx(qDt,{ref:r,sideOffset:t,className:Pt("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),...n}));Nx.displayName=qDt.displayName;const VDt=j.createContext(void 0),Vt=s=>{const t=j.useContext(VDt);if(!t)throw new Error("No QueryClient set, use QueryClientProvider to set one");return t},gws=({client:s,children:t})=>(j.useEffect(()=>(s.mount(),()=>{s.unmount()}),[s]),e.jsx(VDt.Provider,{value:s,children:t})),xws={setTimeout:(s,t)=>setTimeout(s,t),clearTimeout:s=>clearTimeout(s),setInterval:(s,t)=>setInterval(s,t),clearInterval:s=>clearInterval(s)};var LP,iJe,wIt,yws=(wIt=class{constructor(){bs(this,LP,xws);bs(this,iJe,!1)}setTimeoutProvider(s){Kt(this,LP,s)}setTimeout(s,t){return ye(this,LP).setTimeout(s,t)}clearTimeout(s){ye(this,LP).clearTimeout(s)}setInterval(s,t){return ye(this,LP).setInterval(s,t)}clearInterval(s){ye(this,LP).clearInterval(s)}},LP=new WeakMap,iJe=new WeakMap,wIt);const l8=new yws;function vws(s){setTimeout(s,0)}const bws=typeof window>"u"||"Deno"in globalThis;function d_(){}function _ws(s,t){return typeof s=="function"?s(t):s}function HDt(s){return typeof s=="number"&&s>=0&&s!==1/0}function GDt(s,t){return Math.max(s+(t||0)-Date.now(),0)}function Hp(s,t){return typeof s=="function"?s(t):s}function Ggt(s,t){const{type:n="all",exact:r,fetchStatus:a,predicate:i,queryKey:l,stale:o}=s;if(l){if(r){if(t.queryHash!==Net(l,t.options))return!1}else if(!xG(t.queryKey,l))return!1}if(n!=="all"){const c=t.isActive();if(n==="active"&&!c||n==="inactive"&&c)return!1}return!(typeof o=="boolean"&&t.isStale()!==o||a&&a!==t.state.fetchStatus||i&&!i(t))}function Wgt(s,t){const{exact:n,status:r,predicate:a,mutationKey:i}=s;if(i){if(!t.options.mutationKey)return!1;if(n){if(q7(t.options.mutationKey)!==q7(i))return!1}else if(!xG(t.options.mutationKey,i))return!1}return!(r&&t.state.status!==r||a&&!a(t))}function Net(s,t){return((t==null?void 0:t.queryKeyHashFn)||q7)(s)}function q7(s){return JSON.stringify(s,(t,n)=>XVe(n)?Object.keys(n).sort().reduce((r,a)=>(r[a]=n[a],r),{}):n)}function xG(s,t){if(s===t)return!0;if(typeof s!=typeof t)return!1;if(s&&t&&typeof s=="object"&&typeof t=="object"){if(Array.isArray(s)&&Array.isArray(t)){if(t.length>s.length)return!1;for(let r=0;r500)return t;const r=Kgt(s)&&Kgt(t);if(!r&&!(XVe(s)&&XVe(t)))return t;const a=(r?s:Object.keys(s)).length,i=r?t:Object.keys(t),l=i.length,o=r?new Array(l):{};let c=0;for(let d=0;d{l8.setTimeout(t,s)})}function QVe(s,t,n){return typeof n.structuralSharing=="function"?n.structuralSharing(s,t):n.structuralSharing!==!1?WDt(s,t):t}function Nws(s,t,n=0){const r=[...s,t];return n&&r.length>n?r.slice(1):r}function kws(s,t,n=0){const r=[t,...s];return n&&r.length>n?r.slice(0,-1):r}const ket=Symbol();function KDt(s,t){return!s.queryFn&&(t!=null&&t.initialPromise)?()=>t.initialPromise:!s.queryFn||s.queryFn===ket?()=>Promise.reject(new Error(`Missing queryFn: '${s.queryHash}'`)):s.queryFn}function Cet(s,t){return typeof s=="function"?s(...t):!!s}function Sws(s,t,n){let r=!1,a;return Object.defineProperty(s,"signal",{enumerable:!0,get:()=>(a??(a=t()),r||(r=!0,a.aborted?n():a.addEventListener("abort",n,{once:!0})),a)}),s}let Cws=()=>bws;const Aet=()=>Cws();var QW=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(){}},T8,RP,QV,jIt,Aws=(jIt=class extends QW{constructor(){super();bs(this,T8);bs(this,RP);bs(this,QV);Kt(this,QV,t=>{if(typeof window<"u"&&window.addEventListener){const n=()=>t();return window.addEventListener("visibilitychange",n,!1),()=>{window.removeEventListener("visibilitychange",n)}}})}onSubscribe(){ye(this,RP)||this.setEventListener(ye(this,QV))}onUnsubscribe(){var t;this.hasListeners()||((t=ye(this,RP))==null||t.call(this),Kt(this,RP,void 0))}setEventListener(t){var n;Kt(this,QV,t),(n=ye(this,RP))==null||n.call(this),Kt(this,RP,t(r=>{typeof r=="boolean"?this.setFocused(r):this.onFocus()}))}setFocused(t){ye(this,T8)!==t&&(Kt(this,T8,t),this.onFocus())}onFocus(){const t=this.isFocused();this.listeners.forEach(n=>{n(t)})}isFocused(){var t;return typeof ye(this,T8)=="boolean"?ye(this,T8):((t=globalThis.document)==null?void 0:t.visibilityState)!=="hidden"}},T8=new WeakMap,RP=new WeakMap,QV=new WeakMap,jIt);const Eet=new Aws,Ews=vws;function Tws(){let s=[],t=0,n=o=>{o()},r=o=>{o()},a=Ews;const i=o=>{t?s.push(o):a(()=>{n(o)})},l=()=>{const o=s;s=[],o.length&&a(()=>{r(()=>{o.forEach(c=>{n(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=>{n=o},setBatchNotifyFunction:o=>{r=o},setScheduler:o=>{a=o}}}const b0=Tws();var JV,DP,eH,NIt,Mws=(NIt=class extends QW{constructor(){super();bs(this,JV,!0);bs(this,DP);bs(this,eH);Kt(this,eH,t=>{if(typeof window<"u"&&window.addEventListener){const n=()=>t(!0),r=()=>t(!1);return window.addEventListener("online",n,!1),window.addEventListener("offline",r,!1),()=>{window.removeEventListener("online",n),window.removeEventListener("offline",r)}}})}onSubscribe(){ye(this,DP)||this.setEventListener(ye(this,eH))}onUnsubscribe(){var t;this.hasListeners()||((t=ye(this,DP))==null||t.call(this),Kt(this,DP,void 0))}setEventListener(t){var n;Kt(this,eH,t),(n=ye(this,DP))==null||n.call(this),Kt(this,DP,t(this.setOnline.bind(this)))}setOnline(t){ye(this,JV)!==t&&(Kt(this,JV,t),this.listeners.forEach(n=>{n(t)}))}isOnline(){return ye(this,JV)}},JV=new WeakMap,DP=new WeakMap,eH=new WeakMap,NIt);const yEe=new Mws;function Pws(s){return Math.min(1e3*2**s,3e4)}function YDt(s){return(s??"online")==="online"?yEe.isOnline():!0}var JVe=class extends Error{constructor(s){super("CancelledError"),this.revert=s==null?void 0:s.revert,this.silent=s==null?void 0:s.silent}};function ZDt(s){let t=!1,n=0,r,a="pending",i,l;const o=new Promise((b,w)=>{i=b,l=w});o.catch(d_);const c=()=>a!=="pending",d=b=>{var w;if(!c()){const S=new JVe(b);x(S),(w=s.onCancel)==null||w.call(s,S)}},u=()=>{t=!0},h=()=>{t=!1},m=()=>Eet.isFocused()&&(s.networkMode==="always"||yEe.isOnline())&&s.canRun(),f=()=>YDt(s.networkMode)&&s.canRun(),g=b=>{c()||(r==null||r(),a="resolved",i(b))},x=b=>{c()||(r==null||r(),a="rejected",l(b))},y=()=>new Promise(b=>{var w;r=S=>{(c()||m())&&b(S)},(w=s.onPause)==null||w.call(s)}).then(()=>{var b;r=void 0,c()||(b=s.onContinue)==null||b.call(s)}),v=()=>{if(c())return;let b;const w=n===0?s.initialPromise:void 0;try{b=w??s.fn()}catch(S){b=Promise.reject(S)}Promise.resolve(b).then(g).catch(S=>{var R;if(c())return;const C=s.retry??(Aet()?0:3),E=s.retryDelay??Pws,I=typeof E=="function"?E(n,S):E,P=C===!0||typeof C=="number"&&nm()?void 0:y()).then(()=>{t?x(S):v()})})};return{promise:o,status:()=>a,cancel:d,continue:()=>(r==null||r(),o),cancelRetry:u,continueRetry:h,canStart:f,start:()=>(f()?v():y().then(v),o)}}var M8,kIt,XDt=(kIt=class{constructor(){bs(this,M8)}destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),HDt(this.gcTime)&&Kt(this,M8,l8.setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(s){this.gcTime=Math.max(this.gcTime||0,s??(Aet()?1/0:3e5))}clearGcTimeout(){ye(this,M8)!==void 0&&(l8.clearTimeout(ye(this,M8)),Kt(this,M8,void 0))}},M8=new WeakMap,kIt);function Iws(s){return{onFetch:(t,n)=>{var u,h,m,f,g;const r=t.options,a=(m=(h=(u=t.fetchOptions)==null?void 0:u.meta)==null?void 0:h.fetchMore)==null?void 0:m.direction,i=((f=t.state.data)==null?void 0:f.pages)||[],l=((g=t.state.data)==null?void 0:g.pageParams)||[];let o={pages:[],pageParams:[]},c=0;const d=async()=>{let x=!1;const y=w=>{Sws(w,()=>t.signal,()=>x=!0)},v=KDt(t.options,t.fetchOptions),b=async(w,S,C)=>{if(x)return Promise.reject(t.signal.reason);if(S==null&&w.pages.length)return Promise.resolve(w);const I=(()=>{const O={client:t.client,queryKey:t.queryKey,pageParam:S,direction:C?"backward":"forward",meta:t.options.meta};return y(O),O})(),P=await v(I),{maxPages:R}=t.options,D=C?kws:Nws;return{pages:D(w.pages,P,R),pageParams:D(w.pageParams,S,R)}};if(a&&i.length){const w=a==="backward",S=w?QDt:eHe,C={pages:i,pageParams:l};o=await b(C,S(r,C),w)}else{const w=s??i.length;do{const S=c===0?l[0]??r.initialPageParam:eHe(r,o);if(c>0&&S==null)break;o=await b(o,S),c++}while(c{var x,y;return(y=(x=t.options).persister)==null?void 0:y.call(x,d,{client:t.client,queryKey:t.queryKey,meta:t.options.meta,signal:t.signal},n)}:t.fetchFn=d}}}function eHe(s,{pages:t,pageParams:n}){const r=t.length-1;return t.length>0?s.getNextPageParam(t[r],t,n[r],n):void 0}function QDt(s,{pages:t,pageParams:n}){var r;return t.length>0?(r=s.getPreviousPageParam)==null?void 0:r.call(s,t[0],t,n[0],n):void 0}function Lws(s,t){return t?eHe(s,t)!=null:!1}function Rws(s,t){return!t||!s.getPreviousPageParam?!1:QDt(s,t)!=null}var tH,P8,sH,jN,I8,l0,Zne,L8,yS,yA,SIt,Dws=(SIt=class extends XDt{constructor(t){super();bs(this,yS);bs(this,tH);bs(this,P8);bs(this,sH);bs(this,jN);bs(this,I8);bs(this,l0);bs(this,Zne);bs(this,L8);Kt(this,L8,!1),Kt(this,Zne,t.defaultOptions),this.setOptions(t.options),this.observers=[],Kt(this,I8,t.client),Kt(this,jN,ye(this,I8).getQueryCache()),this.queryKey=t.queryKey,this.queryHash=t.queryHash,Kt(this,P8,Xgt(this.options)),this.state=t.state??ye(this,P8),this.scheduleGc()}get meta(){return this.options.meta}get queryType(){return ye(this,tH)}get promise(){var t;return(t=ye(this,l0))==null?void 0:t.promise}setOptions(t){if(this.options={...ye(this,Zne),...t},t!=null&&t._type&&Kt(this,tH,t._type),this.updateGcTime(this.options.gcTime),this.state&&this.state.data===void 0){const n=Xgt(this.options);n.data!==void 0&&(this.setState(Zgt(n.data,n.dataUpdatedAt)),Kt(this,P8,n))}}optionalRemove(){!this.observers.length&&this.state.fetchStatus==="idle"&&ye(this,jN).remove(this)}setData(t,n){const r=QVe(this.state.data,t,this.options);return ls(this,yS,yA).call(this,{data:r,type:"success",dataUpdatedAt:n==null?void 0:n.updatedAt,manual:n==null?void 0:n.manual}),r}setState(t){ls(this,yS,yA).call(this,{type:"setState",state:t})}cancel(t){var r,a;const n=(r=ye(this,l0))==null?void 0:r.promise;return(a=ye(this,l0))==null||a.cancel(t),n?n.then(d_).catch(d_):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}get resetState(){return ye(this,P8)}reset(){this.destroy(),this.setState(this.resetState)}isActive(){return this.observers.some(t=>Hp(t.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===ket||!this.isFetched()}isFetched(){return this.state.dataUpdateCount+this.state.errorUpdateCount>0}isStatic(){return this.getObserversCount()>0?this.observers.some(t=>Hp(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:!GDt(this.state.dataUpdatedAt,t)}onFocus(){var t,n;(t=this.observers.find(r=>r.shouldFetchOnWindowFocus()))==null||t.refetch({cancelRefetch:!1}),(n=ye(this,l0))==null||n.continue()}onOnline(){var t,n;(t=this.observers.find(r=>r.shouldFetchOnReconnect()))==null||t.refetch({cancelRefetch:!1}),(n=ye(this,l0))==null||n.continue()}addObserver(t){this.observers.includes(t)||(this.observers.push(t),this.clearGcTimeout(),ye(this,jN).notify({type:"observerAdded",query:this,observer:t}))}removeObserver(t){const n=this.observers.indexOf(t);n!==-1&&(this.observers.splice(n,1),this.observers.length||(ye(this,l0)&&(ye(this,L8)||this.state.fetchStatus==="paused"&&this.state.status==="pending"?ye(this,l0).cancel({revert:!0}):ye(this,l0).cancelRetry()),this.scheduleGc()),ye(this,jN).notify({type:"observerRemoved",query:this,observer:t}))}getObserversCount(){return this.observers.length}invalidate(){this.state.isInvalidated||ls(this,yS,yA).call(this,{type:"invalidate"})}async fetch(t,n){var d,u,h,m,f,g,x,y,v,b,w,S;if(this.state.fetchStatus!=="idle"&&((d=ye(this,l0))==null?void 0:d.status())!=="rejected"){if(this.state.data!==void 0&&(n!=null&&n.cancelRefetch))this.cancel({silent:!0});else if(ye(this,l0))return ye(this,l0).continueRetry(),ye(this,l0).promise}if(t&&this.setOptions(t),!this.options.queryFn){const C=this.observers.find(E=>E.options.queryFn);C&&this.setOptions(C.options)}const r=new AbortController,a=C=>{Object.defineProperty(C,"signal",{enumerable:!0,get:()=>(Kt(this,L8,!0),r.signal)})},i=()=>{const C=KDt(this.options,n),I=(()=>{const P={client:ye(this,I8),queryKey:this.queryKey,meta:this.meta};return a(P),P})();return Kt(this,L8,!1),this.options.persister?this.options.persister(C,I,this):C(I)},o=(()=>{const C={fetchOptions:n,options:this.options,queryKey:this.queryKey,client:ye(this,I8),state:this.state,fetchFn:i};return a(C),C})();(u=ye(this,tH)==="infinite"?Iws(this.options.pages):this.options.behavior)==null||u.onFetch(o,this),Kt(this,sH,this.state),(this.state.fetchStatus==="idle"||this.state.fetchMeta!==((h=o.fetchOptions)==null?void 0:h.meta))&&ls(this,yS,yA).call(this,{type:"fetch",meta:(m=o.fetchOptions)==null?void 0:m.meta});const c=Kt(this,l0,ZDt({initialPromise:n==null?void 0:n.initialPromise,fn:o.fetchFn,onCancel:C=>{C instanceof JVe&&C.revert&&this.setState({...ye(this,sH),fetchStatus:"idle"}),r.abort()},onFail:(C,E)=>{ls(this,yS,yA).call(this,{type:"failed",failureCount:C,error:E})},onPause:()=>{ls(this,yS,yA).call(this,{type:"pause"})},onContinue:()=>{ls(this,yS,yA).call(this,{type:"continue"})},retry:o.options.retry,retryDelay:o.options.retryDelay,networkMode:o.options.networkMode,canRun:()=>!0}));try{const C=await c.start();if(C===void 0)throw new Error(`${this.queryHash} data is undefined`);return this.setData(C),(g=(f=ye(this,jN).config).onSuccess)==null||g.call(f,C,this),(y=(x=ye(this,jN).config).onSettled)==null||y.call(x,C,this.state.error,this),C}catch(C){if(C instanceof JVe){if(C.silent)return ye(this,l0).promise;if(C.revert){if(this.state.data===void 0)throw C;return this.state.data}}throw ls(this,yS,yA).call(this,{type:"error",error:C}),(b=(v=ye(this,jN).config).onError)==null||b.call(v,C,this),(S=(w=ye(this,jN).config).onSettled)==null||S.call(w,this.state.data,C,this),C}finally{ye(this,l0)===c&&Kt(this,l0,void 0),this.scheduleGc()}}},tH=new WeakMap,P8=new WeakMap,sH=new WeakMap,jN=new WeakMap,I8=new WeakMap,l0=new WeakMap,Zne=new WeakMap,L8=new WeakMap,yS=new WeakSet,yA=function(t){const n=r=>{switch(t.type){case"failed":return{...r,fetchFailureCount:t.failureCount,fetchFailureReason:t.error};case"pause":return{...r,fetchStatus:"paused"};case"continue":return{...r,fetchStatus:"fetching"};case"fetch":return{...r,...JDt(r.data,this.options),fetchMeta:t.meta??null};case"success":const a={...r,...Zgt(t.data,t.dataUpdatedAt),dataUpdateCount:r.dataUpdateCount+1,...!t.manual&&{fetchStatus:"idle",fetchFailureCount:0,fetchFailureReason:null}};return Kt(this,sH,t.manual?a:void 0),a;case"error":const i=t.error;return{...r,error:i,errorUpdateCount:r.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:r.fetchFailureCount+1,fetchFailureReason:i,fetchStatus:"idle",status:"error",isInvalidated:!0};case"invalidate":return{...r,isInvalidated:!0};case"setState":return{...r,...t.state}}};this.state=n(this.state),b0.batch(()=>{this.observers.slice().forEach(r=>{r.onQueryUpdate()}),ye(this,jN).notify({query:this,type:"updated",action:t})})},SIt);function JDt(s,t){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:YDt(t.networkMode)?"fetching":"paused",...s===void 0&&{error:null,status:"pending"}}}function Zgt(s,t){return{data:s,dataUpdatedAt:t??Date.now(),error:null,isInvalidated:!1,status:"success"}}function Xgt(s){const t=typeof s.initialData=="function"?s.initialData():s.initialData,n=t!==void 0,r=n?typeof s.initialDataUpdatedAt=="function"?s.initialDataUpdatedAt():s.initialDataUpdatedAt:0;return{data:t,dataUpdateCount:0,dataUpdatedAt:n?r??Date.now():0,error:null,errorUpdateCount:0,errorUpdatedAt:0,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:null,isInvalidated:!1,status:n?"success":"pending",fetchStatus:"idle"}}var o_,Xu,Xne,l_,R8,nH,zA,Qne,rH,aH,D8,F8,FP,iH,im,aQ,tHe,sHe,nHe,rHe,aHe,iHe,oHe,lHe,CIt,eFt=(CIt=class extends QW{constructor(t,n){super();bs(this,im);bs(this,o_);bs(this,Xu);bs(this,Xne);bs(this,l_);bs(this,R8);bs(this,nH);bs(this,zA);bs(this,Qne);bs(this,rH);bs(this,aH);bs(this,D8);bs(this,F8);bs(this,FP);bs(this,iH,new Set);this.options=n,Kt(this,o_,t),Kt(this,zA,null),this.bindMethods(),this.setOptions(n)}bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(ye(this,Xu).addObserver(this),Qgt(ye(this,Xu),this.options)?ls(this,im,aQ).call(this):this.updateResult(),ls(this,im,aHe).call(this))}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return cHe(ye(this,Xu),this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return cHe(ye(this,Xu),this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,ls(this,im,iHe).call(this),ls(this,im,oHe).call(this),ye(this,Xu).removeObserver(this)}setOptions(t){const n=this.options,r=ye(this,Xu);if(this.options=ye(this,o_).defaultQueryOptions(t),this.options.enabled!==void 0&&typeof this.options.enabled!="boolean"&&typeof this.options.enabled!="function"&&typeof Hp(this.options.enabled,ye(this,Xu))!="boolean")throw new Error("Expected enabled to be a boolean or a callback that returns a boolean");ls(this,im,lHe).call(this),ye(this,Xu).setOptions(this.options),n._defaulted&&!H4e(this.options,n)&&ye(this,o_).getQueryCache().notify({type:"observerOptionsUpdated",query:ye(this,Xu),observer:this});const a=this.hasListeners();a&&Jgt(ye(this,Xu),r,this.options,n)&&ls(this,im,aQ).call(this),this.updateResult(),a&&(ye(this,Xu)!==r||Hp(this.options.enabled,ye(this,Xu))!==Hp(n.enabled,ye(this,Xu))||Hp(this.options.staleTime,ye(this,Xu))!==Hp(n.staleTime,ye(this,Xu)))&&ls(this,im,sHe).call(this);const i=ls(this,im,nHe).call(this);a&&(ye(this,Xu)!==r||Hp(this.options.enabled,ye(this,Xu))!==Hp(n.enabled,ye(this,Xu))||i!==ye(this,FP))&&ls(this,im,rHe).call(this,i)}getOptimisticResult(t){const n=ye(this,o_).getQueryCache().build(ye(this,o_),t),r=this.createResult(n,t);return H4e(this.getCurrentResult(),r)||(Kt(this,l_,r),Kt(this,nH,this.options),Kt(this,R8,ye(this,Xu).state)),r}getCurrentResult(){return ye(this,l_)}trackResult(t,n){return new Proxy(t,{get:(r,a)=>(this.trackProp(a),n==null||n(a),Reflect.get(r,a))})}trackProp(t){ye(this,iH).add(t)}getCurrentQuery(){return ye(this,Xu)}refetch({...t}={}){return this.fetch({...t})}fetchOptimistic(t){const n=ye(this,o_).defaultQueryOptions(t),r=ye(this,o_).getQueryCache().build(ye(this,o_),n);let a=()=>{},i;const l=new Promise(o=>{i=o,a=ye(this,o_).getQueryCache().subscribe(c=>{c.type==="updated"&&c.query.queryHash===r.queryHash&&r.state.data!==void 0&&(a(),o(this.createResult(r,n)))})});return Promise.race([r.fetch().then(()=>{const o=this.createResult(r,n);return i==null||i(o),o}).finally(()=>{a()}),l])}fetch(t){return ls(this,im,aQ).call(this,{...t,cancelRefetch:t.cancelRefetch??!0}).then(()=>(this.updateResult(),ye(this,l_)))}createResult(t,n){var E;const r=ye(this,Xu),a=this.options,i=ye(this,l_),l=ye(this,R8),o=ye(this,nH),c=t!==r?t.state:ye(this,Xne),{state:d}=t;let u={...d},h=!1,m;if(n._optimisticResults){const I=this.hasListeners(),P=!I&&Qgt(t,n),R=I&&Jgt(t,r,n,a);(P||R)&&(u={...u,...JDt(d.data,t.options)}),n._optimisticResults==="isRestoring"&&(u.fetchStatus="idle")}let{error:f,errorUpdatedAt:g,status:x}=u;m=u.data;let y=!1;if(n.placeholderData!==void 0&&m===void 0&&x==="pending"){let I;i!=null&&i.isPlaceholderData&&n.placeholderData===(o==null?void 0:o.placeholderData)?(I=i.data,y=!0):I=typeof n.placeholderData=="function"?n.placeholderData((E=ye(this,aH))==null?void 0:E.state.data,ye(this,aH)):n.placeholderData,I!==void 0&&(x="success",m=QVe(i==null?void 0:i.data,I,n),h=!0)}if(n.select&&m!==void 0&&!y)if(i&&m===(l==null?void 0:l.data)&&n.select===ye(this,Qne))m=ye(this,rH);else try{Kt(this,Qne,n.select),m=n.select(m),m=QVe(i==null?void 0:i.data,m,n),Kt(this,rH,m),Kt(this,zA,null)}catch(I){Kt(this,zA,I)}else m===void 0&&Kt(this,zA,null);ye(this,zA)&&(f=ye(this,zA),m=ye(this,rH),g=Date.now(),x="error",h=!1);const v=u.fetchStatus==="fetching",b=x==="pending",w=x==="error",S=b&&v,C=m!==void 0;return{status:x,fetchStatus:u.fetchStatus,isPending:b,isSuccess:x==="success",isError:w,isInitialLoading:S,isLoading:S,data:m,dataUpdatedAt:u.dataUpdatedAt,error:f,errorUpdatedAt:g,failureCount:u.fetchFailureCount,failureReason:u.fetchFailureReason,errorUpdateCount:u.errorUpdateCount,isFetched:t.isFetched(),isFetchedAfterMount:u.dataUpdateCount>c.dataUpdateCount||u.errorUpdateCount>c.errorUpdateCount,isFetching:v,isRefetching:v&&!b,isLoadingError:w&&!C,isPaused:u.fetchStatus==="paused",isPlaceholderData:h,isRefetchError:w&&C,isStale:Tet(t,n),refetch:this.refetch,isEnabled:Hp(n.enabled,t)!==!1}}updateResult(){const t=ye(this,l_),n=this.createResult(ye(this,Xu),this.options);if(Kt(this,R8,ye(this,Xu).state),Kt(this,nH,this.options),ye(this,R8).data!==void 0&&Kt(this,aH,ye(this,Xu)),H4e(n,t))return;Kt(this,l_,n);const a=(()=>{if(!t)return!0;const{notifyOnChangeProps:i}=this.options,l=typeof i=="function"?i():i;if(l==="all"||!l&&!ye(this,iH).size)return!0;const o=new Set(l??ye(this,iH));return this.options.throwOnError&&o.add("error"),Object.keys(ye(this,l_)).some(c=>{const d=c;return ye(this,l_)[d]!==t[d]&&o.has(d)})})();b0.batch(()=>{a&&this.listeners.forEach(i=>{i(ye(this,l_))}),ye(this,o_).getQueryCache().notify({query:ye(this,Xu),type:"observerResultsUpdated"})})}onQueryUpdate(){this.updateResult(),this.hasListeners()&&ls(this,im,aHe).call(this)}},o_=new WeakMap,Xu=new WeakMap,Xne=new WeakMap,l_=new WeakMap,R8=new WeakMap,nH=new WeakMap,zA=new WeakMap,Qne=new WeakMap,rH=new WeakMap,aH=new WeakMap,D8=new WeakMap,F8=new WeakMap,FP=new WeakMap,iH=new WeakMap,im=new WeakSet,aQ=function(t){ls(this,im,lHe).call(this);let n=ye(this,Xu).fetch(this.options,t);return t!=null&&t.throwOnError||(n=n.catch(d_)),n},tHe=function(t){return!Aet()&&Hp(this.options.enabled,ye(this,Xu))!==!1&&HDt(t)},sHe=function(){ls(this,im,iHe).call(this);const t=Hp(this.options.staleTime,ye(this,Xu));if(ye(this,l_).isStale||!ls(this,im,tHe).call(this,t))return;const n=GDt(ye(this,l_).dataUpdatedAt,t)+1;Kt(this,D8,l8.setTimeout(()=>{ye(this,l_).isStale||this.updateResult()},n))},nHe=function(){return Hp(this.options.refetchInterval,ye(this,Xu))??!1},rHe=function(t){ls(this,im,oHe).call(this),Kt(this,FP,t),!(ye(this,FP)===0||!ls(this,im,tHe).call(this,ye(this,FP)))&&Kt(this,F8,l8.setInterval(()=>{(this.options.refetchIntervalInBackground||Eet.isFocused())&&ls(this,im,aQ).call(this)},ye(this,FP)))},aHe=function(){ls(this,im,sHe).call(this),ls(this,im,rHe).call(this,ls(this,im,nHe).call(this))},iHe=function(){ye(this,D8)!==void 0&&(l8.clearTimeout(ye(this,D8)),Kt(this,D8,void 0))},oHe=function(){ye(this,F8)!==void 0&&(l8.clearInterval(ye(this,F8)),Kt(this,F8,void 0))},lHe=function(){const t=ye(this,o_).getQueryCache().build(ye(this,o_),this.options);if(t===ye(this,Xu))return;const n=ye(this,Xu);Kt(this,Xu,t),Kt(this,Xne,t.state),this.hasListeners()&&(n==null||n.removeObserver(this),t.addObserver(this))},CIt);function Fws(s,t){return Hp(t.enabled,s)!==!1&&s.state.data===void 0&&!(s.state.status==="error"&&Hp(t.retryOnMount,s)===!1)}function Qgt(s,t){return Fws(s,t)||s.state.data!==void 0&&cHe(s,t,t.refetchOnMount)}function cHe(s,t,n){if(Hp(t.enabled,s)!==!1&&Hp(t.staleTime,s)!=="static"){const r=Hp(n,s);return r==="always"||r!==!1&&Tet(s,t)}return!1}function Jgt(s,t,n,r){return(s!==t||Hp(r.enabled,s)===!1)&&(!n.suspense||s.state.status!=="error")&&Tet(s,n)}function Tet(s,t){return Hp(t.enabled,s)!==!1&&s.isStaleByTime(Hp(t.staleTime,s))}var Ows=class extends eFt{constructor(s,t){super(s,t)}bindMethods(){super.bindMethods(),this.fetchNextPage=this.fetchNextPage.bind(this),this.fetchPreviousPage=this.fetchPreviousPage.bind(this)}setOptions(s){s._type="infinite",super.setOptions(s)}getOptimisticResult(s){return s._type="infinite",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 f,g;const{state:n}=s,r=super.createResult(s,t),{isFetching:a,isRefetching:i,isError:l,isRefetchError:o}=r,c=(g=(f=n.fetchMeta)==null?void 0:f.fetchMore)==null?void 0:g.direction,d=l&&c==="forward",u=a&&c==="forward",h=l&&c==="backward",m=a&&c==="backward";return{...r,fetchNextPage:this.fetchNextPage,fetchPreviousPage:this.fetchPreviousPage,hasNextPage:Lws(t,n.data),hasPreviousPage:Rws(t,n.data),isFetchNextPageError:d,isFetchingNextPage:u,isFetchPreviousPageError:h,isFetchingPreviousPage:m,isRefetchError:o&&!d&&!h,isRefetching:i&&!u&&!m}}},Jne,R5,r1,O8,D5,qM,AIt,zws=(AIt=class extends XDt{constructor(t){super();bs(this,D5);bs(this,Jne);bs(this,R5);bs(this,r1);bs(this,O8);Kt(this,Jne,t.client),this.mutationId=t.mutationId,Kt(this,r1,t.mutationCache),Kt(this,R5,[]),this.state=t.state||tFt(),this.setOptions(t.options),this.scheduleGc()}setOptions(t){this.options=t,this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(t){ye(this,R5).includes(t)||(ye(this,R5).push(t),this.clearGcTimeout(),ye(this,r1).notify({type:"observerAdded",mutation:this,observer:t}))}removeObserver(t){Kt(this,R5,ye(this,R5).filter(n=>n!==t)),this.scheduleGc(),ye(this,r1).notify({type:"observerRemoved",mutation:this,observer:t})}optionalRemove(){ye(this,R5).length||(this.state.status==="pending"?this.scheduleGc():ye(this,r1).remove(this))}continue(){var t;return((t=ye(this,O8))==null?void 0:t.continue())??(this.state.status==="pending"?this.execute(this.state.variables):Promise.resolve())}async execute(t){var o,c,d,u,h,m,f,g,x,y,v,b,w,S,C,E,I,P;const n=()=>{ls(this,D5,qM).call(this,{type:"continue"})},r={client:ye(this,Jne),meta:this.options.meta,mutationKey:this.options.mutationKey},a=Kt(this,O8,ZDt({fn:()=>this.options.mutationFn?this.options.mutationFn(t,r):Promise.reject(new Error("No mutationFn found")),onFail:(R,D)=>{ls(this,D5,qM).call(this,{type:"failed",failureCount:R,error:D})},onPause:()=>{ls(this,D5,qM).call(this,{type:"pause"})},onContinue:n,retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:()=>ye(this,r1).canRun(this)})),i=this.state.status==="pending",l=!a.canStart();try{if(i)n();else{ls(this,D5,qM).call(this,{type:"pending",variables:t,isPaused:l}),ye(this,r1).config.onMutate&&await ye(this,r1).config.onMutate(t,this,r);const D=await((c=(o=this.options).onMutate)==null?void 0:c.call(o,t,r));D!==this.state.context&&ls(this,D5,qM).call(this,{type:"pending",context:D,variables:t,isPaused:l})}const R=await a.start();return await((u=(d=ye(this,r1).config).onSuccess)==null?void 0:u.call(d,R,t,this.state.context,this,r)),await((m=(h=this.options).onSuccess)==null?void 0:m.call(h,R,t,this.state.context,r)),await((g=(f=ye(this,r1).config).onSettled)==null?void 0:g.call(f,R,null,this.state.variables,this.state.context,this,r)),await((y=(x=this.options).onSettled)==null?void 0:y.call(x,R,null,t,this.state.context,r)),ls(this,D5,qM).call(this,{type:"success",data:R}),R}catch(R){try{await((b=(v=ye(this,r1).config).onError)==null?void 0:b.call(v,R,t,this.state.context,this,r))}catch(D){Promise.reject(D)}try{await((S=(w=this.options).onError)==null?void 0:S.call(w,R,t,this.state.context,r))}catch(D){Promise.reject(D)}try{await((E=(C=ye(this,r1).config).onSettled)==null?void 0:E.call(C,void 0,R,this.state.variables,this.state.context,this,r))}catch(D){Promise.reject(D)}try{await((P=(I=this.options).onSettled)==null?void 0:P.call(I,void 0,R,t,this.state.context,r))}catch(D){Promise.reject(D)}throw ls(this,D5,qM).call(this,{type:"error",error:R}),R}finally{ye(this,O8)===a&&Kt(this,O8,void 0),ye(this,r1).runNext(this)}}},Jne=new WeakMap,R5=new WeakMap,r1=new WeakMap,O8=new WeakMap,D5=new WeakSet,qM=function(t){const n=r=>{switch(t.type){case"failed":return{...r,failureCount:t.failureCount,failureReason:t.error};case"pause":return{...r,isPaused:!0};case"continue":return{...r,isPaused:!1};case"pending":return{...r,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{...r,data:t.data,failureCount:0,failureReason:null,error:null,status:"success",isPaused:!1};case"error":return{...r,data:void 0,error:t.error,failureCount:r.failureCount+1,failureReason:t.error,isPaused:!1,status:"error"}}};this.state=n(this.state),b0.batch(()=>{ye(this,R5).forEach(r=>{r.onMutationUpdate(t)}),ye(this,r1).notify({mutation:this,type:"updated",action:t})})},AIt);function tFt(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var BA,vS,ere,EIt,Bws=(EIt=class extends QW{constructor(t={}){super();bs(this,BA);bs(this,vS);bs(this,ere);this.config=t,Kt(this,BA,new Set),Kt(this,vS,new Map),Kt(this,ere,0)}build(t,n,r){const a=new zws({client:t,mutationCache:this,mutationId:++J0(this,ere)._,options:t.defaultMutationOptions(n),state:r});return this.add(a),a}add(t){ye(this,BA).add(t);const n=wce(t);if(typeof n=="string"){const r=ye(this,vS).get(n);r?r.push(t):ye(this,vS).set(n,[t])}this.notify({type:"added",mutation:t})}remove(t){if(ye(this,BA).delete(t)){const n=wce(t);if(typeof n=="string"){const r=ye(this,vS).get(n);if(r)if(r.length>1){const a=r.indexOf(t);a!==-1&&r.splice(a,1)}else r[0]===t&&ye(this,vS).delete(n)}}this.notify({type:"removed",mutation:t})}canRun(t){var r;const n=wce(t);if(typeof n=="string"){const a=(r=ye(this,vS).get(n))==null?void 0:r.find(i=>i.state.status==="pending");return!a||a===t}else return!0}runNext(t){var r,a;const n=wce(t);return typeof n=="string"?((a=(r=ye(this,vS).get(n))==null?void 0:r.find(i=>i!==t&&i.state.isPaused))==null?void 0:a.continue())??Promise.resolve():Promise.resolve()}clear(){b0.batch(()=>{ye(this,BA).forEach(t=>{this.notify({type:"removed",mutation:t})}),ye(this,BA).clear(),ye(this,vS).clear()})}getAll(){return Array.from(ye(this,BA))}find(t){const n={exact:!0,...t};return this.getAll().find(r=>Wgt(n,r))}findAll(t={}){return this.getAll().filter(n=>Wgt(t,n))}notify(t){b0.batch(()=>{this.listeners.forEach(n=>{n(t)})})}resumePausedMutations(){const t=this.getAll().filter(n=>n.state.isPaused);return b0.batch(()=>Promise.all(t.map(n=>n.continue().catch(d_))))}},BA=new WeakMap,vS=new WeakMap,ere=new WeakMap,EIt);function wce(s){var t;return(t=s.options.scope)==null?void 0:t.id}var $A,OP,a1,UA,S4,iQ,dHe,TIt,$ws=(TIt=class extends QW{constructor(n,r){super();bs(this,S4);bs(this,$A);bs(this,OP);bs(this,a1);bs(this,UA);Kt(this,$A,n),this.setOptions(r),this.bindMethods(),ls(this,S4,iQ).call(this)}bindMethods(){this.mutate=this.mutate.bind(this),this.reset=this.reset.bind(this)}setOptions(n){var a;const r=this.options;this.options=ye(this,$A).defaultMutationOptions(n),H4e(this.options,r)||ye(this,$A).getMutationCache().notify({type:"observerOptionsUpdated",mutation:ye(this,a1),observer:this}),r!=null&&r.mutationKey&&this.options.mutationKey&&q7(r.mutationKey)!==q7(this.options.mutationKey)?this.reset():((a=ye(this,a1))==null?void 0:a.state.status)==="pending"&&ye(this,a1).setOptions(this.options)}onSubscribe(){this.listeners.size===1&&ye(this,a1)&&(ye(this,a1).addObserver(this),ls(this,S4,iQ).call(this))}onUnsubscribe(){var n;this.hasListeners()||(n=ye(this,a1))==null||n.removeObserver(this)}onMutationUpdate(n){ls(this,S4,iQ).call(this),ls(this,S4,dHe).call(this,n)}getCurrentResult(){return ye(this,OP)}reset(){var n;(n=ye(this,a1))==null||n.removeObserver(this),Kt(this,a1,void 0),ls(this,S4,iQ).call(this),ls(this,S4,dHe).call(this)}mutate(n,r){var a;return Kt(this,UA,r),(a=ye(this,a1))==null||a.removeObserver(this),Kt(this,a1,ye(this,$A).getMutationCache().build(ye(this,$A),this.options)),ye(this,a1).addObserver(this),ye(this,a1).execute(n)}},$A=new WeakMap,OP=new WeakMap,a1=new WeakMap,UA=new WeakMap,S4=new WeakSet,iQ=function(){var r;const n=((r=ye(this,a1))==null?void 0:r.state)??tFt();Kt(this,OP,{...n,isPending:n.status==="pending",isSuccess:n.status==="success",isError:n.status==="error",isIdle:n.status==="idle",mutate:this.mutate,reset:this.reset})},dHe=function(n){b0.batch(()=>{var r,a,i,l,o,c,d,u;if(ye(this,UA)&&this.hasListeners()){const h=ye(this,OP).variables,m=ye(this,OP).context,f={client:ye(this,$A),meta:this.options.meta,mutationKey:this.options.mutationKey};if((n==null?void 0:n.type)==="success"){try{(a=(r=ye(this,UA)).onSuccess)==null||a.call(r,n.data,h,m,f)}catch(g){Promise.reject(g)}try{(l=(i=ye(this,UA)).onSettled)==null||l.call(i,n.data,null,h,m,f)}catch(g){Promise.reject(g)}}else if((n==null?void 0:n.type)==="error"){try{(c=(o=ye(this,UA)).onError)==null||c.call(o,n.error,h,m,f)}catch(g){Promise.reject(g)}try{(u=(d=ye(this,UA)).onSettled)==null||u.call(d,void 0,n.error,h,m,f)}catch(g){Promise.reject(g)}}}this.listeners.forEach(h=>{h(ye(this,OP))})})},TIt),F5,MIt,Uws=(MIt=class extends QW{constructor(t={}){super();bs(this,F5);this.config=t,Kt(this,F5,new Map)}build(t,n,r){const a=n.queryKey,i=n.queryHash??Net(a,n);let l=this.get(i);return l||(l=new Dws({client:t,queryKey:a,queryHash:i,options:t.defaultQueryOptions(n),state:r,defaultOptions:t.getQueryDefaults(a)}),this.add(l)),l}add(t){ye(this,F5).has(t.queryHash)||(ye(this,F5).set(t.queryHash,t),this.notify({type:"added",query:t}))}remove(t){ye(this,F5).get(t.queryHash)===t&&(t.destroy(),ye(this,F5).delete(t.queryHash),this.notify({type:"removed",query:t}))}clear(){b0.batch(()=>{this.getAll().forEach(t=>{this.remove(t)})})}get(t){return ye(this,F5).get(t)}getAll(){return[...ye(this,F5).values()]}find(t){const n={exact:!0,...t};return this.getAll().find(r=>Ggt(n,r))}findAll(t={}){const n=this.getAll();return Object.keys(t).length>0?n.filter(r=>Ggt(t,r)):n}notify(t){b0.batch(()=>{this.listeners.forEach(n=>{n(t)})})}onFocus(){b0.batch(()=>{this.getAll().forEach(t=>{t.onFocus()})})}onOnline(){b0.batch(()=>{this.getAll().forEach(t=>{t.onOnline()})})}},F5=new WeakMap,MIt),yg,zP,BP,oH,lH,$P,cH,dH,PIt,qws=(PIt=class{constructor(s={}){bs(this,yg);bs(this,zP);bs(this,BP);bs(this,oH);bs(this,lH);bs(this,$P);bs(this,cH);bs(this,dH);Kt(this,yg,s.queryCache||new Uws),Kt(this,zP,s.mutationCache||new Bws),Kt(this,BP,s.defaultOptions||{}),Kt(this,oH,new Map),Kt(this,lH,new Map),Kt(this,$P,0)}mount(){J0(this,$P)._++,ye(this,$P)===1&&(Kt(this,cH,Eet.subscribe(async s=>{s&&(await this.resumePausedMutations(),ye(this,yg).onFocus())})),Kt(this,dH,yEe.subscribe(async s=>{s&&(await this.resumePausedMutations(),ye(this,yg).onOnline())})))}unmount(){var s,t;J0(this,$P)._--,ye(this,$P)===0&&((s=ye(this,cH))==null||s.call(this),Kt(this,cH,void 0),(t=ye(this,dH))==null||t.call(this),Kt(this,dH,void 0))}isFetching(s){return ye(this,yg).findAll({...s,fetchStatus:"fetching"}).length}isMutating(s){return ye(this,zP).findAll({...s,status:"pending"}).length}getQueryData(s){var n;const t=this.defaultQueryOptions({queryKey:s});return(n=ye(this,yg).get(t.queryHash))==null?void 0:n.state.data}ensureQueryData(s){const t=this.defaultQueryOptions(s),n=ye(this,yg).build(this,t),r=n.state.data;return r===void 0?this.fetchQuery(s):(s.revalidateIfStale&&n.isStaleByTime(Hp(t.staleTime,n))&&this.prefetchQuery(t),Promise.resolve(r))}getQueriesData(s){return ye(this,yg).findAll(s).map(({queryKey:t,state:n})=>[t,n.data])}setQueryData(s,t,n){var l;const r=this.defaultQueryOptions({queryKey:s}),a=(l=ye(this,yg).get(r.queryHash))==null?void 0:l.state.data,i=_ws(t,a);if(i!==void 0)return ye(this,yg).build(this,r).setData(i,{...n,manual:!0})}setQueriesData(s,t,n){return b0.batch(()=>ye(this,yg).findAll(s).map(({queryKey:r})=>[r,this.setQueryData(r,t,n)]))}getQueryState(s){var n;const t=this.defaultQueryOptions({queryKey:s});return(n=ye(this,yg).get(t.queryHash))==null?void 0:n.state}removeQueries(s){const t=ye(this,yg);b0.batch(()=>{t.findAll(s).forEach(n=>{t.remove(n)})})}resetQueries(s,t){const n=ye(this,yg);return b0.batch(()=>{const r=n.findAll(s),a=new Set(r);return r.forEach(i=>{i.reset()}),this.refetchQueries({type:"active",predicate:i=>a.has(i)},t)})}cancelQueries(s,t={}){const n={revert:!0,...t},r=b0.batch(()=>ye(this,yg).findAll(s).map(a=>a.cancel(n)));return Promise.all(r).then(d_).catch(d_)}invalidateQueries(s,t={}){return b0.batch(()=>(ye(this,yg).findAll(s).forEach(n=>{n.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 n={...t,cancelRefetch:t.cancelRefetch??!0},r=b0.batch(()=>ye(this,yg).findAll(s).filter(a=>!a.isDisabled()&&!a.isStatic()).map(a=>{let i=a.fetch(void 0,n);return n.throwOnError||(i=i.catch(d_)),a.state.fetchStatus==="paused"?Promise.resolve():i}));return Promise.all(r).then(d_)}async query(s){const t=this.defaultQueryOptions(s);t.retry===void 0&&(t.retry=!1);const n=ye(this,yg).build(this,t),r=n.isStaleByTime(Hp(t.staleTime,n))?await n.fetch(t):n.state.data,a=t.select;return a?a(r):r}fetchQuery(s){const t=this.defaultQueryOptions(s);t.retry===void 0&&(t.retry=!1);const n=ye(this,yg).build(this,t);return n.isStaleByTime(Hp(t.staleTime,n))?n.fetch(t):Promise.resolve(n.state.data)}prefetchQuery(s){return this.fetchQuery(s).then(d_).catch(d_)}infiniteQuery(s){return s._type="infinite",this.query(s)}fetchInfiniteQuery(s){return s._type="infinite",this.fetchQuery(s)}prefetchInfiniteQuery(s){return this.fetchInfiniteQuery(s).then(d_).catch(d_)}ensureInfiniteQueryData(s){return s._type="infinite",this.ensureQueryData(s)}resumePausedMutations(){return yEe.isOnline()?ye(this,zP).resumePausedMutations():Promise.resolve()}getQueryCache(){return ye(this,yg)}getMutationCache(){return ye(this,zP)}getDefaultOptions(){return ye(this,BP)}setDefaultOptions(s){Kt(this,BP,s)}setQueryDefaults(s,t){ye(this,oH).set(q7(s),{queryKey:s,defaultOptions:t})}getQueryDefaults(s){const t=[...ye(this,oH).values()],n={};return t.forEach(r=>{xG(s,r.queryKey)&&Object.assign(n,r.defaultOptions)}),n}setMutationDefaults(s,t){ye(this,lH).set(q7(s),{mutationKey:s,defaultOptions:t})}getMutationDefaults(s){const t=[...ye(this,lH).values()],n={};return t.forEach(r=>{xG(s,r.mutationKey)&&Object.assign(n,r.defaultOptions)}),n}defaultQueryOptions(s){if(s._defaulted)return s;const t={...ye(this,BP).queries,...this.getQueryDefaults(s.queryKey),...s,_defaulted:!0};return t.queryHash||(t.queryHash=Net(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===ket&&(t.enabled=!1),t}defaultMutationOptions(s){return s!=null&&s._defaulted?s:{...ye(this,BP).mutations,...(s==null?void 0:s.mutationKey)&&this.getMutationDefaults(s.mutationKey),...s,_defaulted:!0}}clear(){ye(this,yg).clear(),ye(this,zP).clear()}},yg=new WeakMap,zP=new WeakMap,BP=new WeakMap,oH=new WeakMap,lH=new WeakMap,$P=new WeakMap,cH=new WeakMap,dH=new WeakMap,PIt);const sFt=j.createContext(!1),Vws=()=>j.useContext(sFt);sFt.Provider;function Hws(){let s=!1;return{clearReset:()=>{s=!1},reset:()=>{s=!0},isReset:()=>s}}const Gws=j.createContext(Hws()),Wws=()=>j.useContext(Gws),Kws=(s,t,n)=>{const r=n!=null&&n.state.error&&typeof s.throwOnError=="function"?Cet(s.throwOnError,[n.state.error,n]):s.throwOnError;(s.suspense||r)&&(t.isReset()||(s.retryOnMount=!1))},Yws=s=>{j.useEffect(()=>{s.clearReset()},[s])},Zws=({result:s,errorResetBoundary:t,throwOnError:n,query:r,suspense:a})=>s.isError&&!t.isReset()&&!s.isFetching&&r&&(a&&s.data===void 0||Cet(n,[s.error,r])),Xws=s=>{if(s.suspense){const n=a=>a==="static"?a:Math.max(a??1e3,1e3),r=s.staleTime;s.staleTime=typeof r=="function"?(...a)=>n(r(...a)):n(r),typeof s.gcTime=="number"&&(s.gcTime=Math.max(s.gcTime,1e3))}},Qws=(s,t)=>(s==null?void 0:s.suspense)&&t.isPending,Jws=(s,t,n)=>t.fetchOptimistic(s).catch(()=>{n.clearReset()});function nFt(s,t,n){const r=Vws(),a=Wws(),i=Vt(),l=i.defaultQueryOptions(s),o=i.getQueryCache().get(l.queryHash),c=s.subscribed!==!1;l._optimisticResults=r?"isRestoring":c?"optimistic":void 0,Xws(l),Kws(l,a,o),Yws(a);const[d]=j.useState(()=>new t(i,l)),u=d.getOptimisticResult(l),h=!r&&c;if(j.useSyncExternalStore(j.useCallback(m=>{const f=h?d.subscribe(b0.batchCalls(m)):d_;return d.updateResult(),f},[d,h]),()=>d.getCurrentResult(),()=>d.getCurrentResult()),j.useEffect(()=>{d.setOptions(l)},[l,d]),Qws(l,u))throw Jws(l,d,a);if(Zws({result:u,errorResetBoundary:a,throwOnError:l.throwOnError,query:o,suspense:l.suspense}))throw u.error;return l.notifyOnChangeProps?u:d.trackResult(u)}function tt(s,t){return nFt(s,eFt)}function ft(s,t){const n=Vt(),[r]=j.useState(()=>new $ws(n,s));j.useEffect(()=>{r.setOptions(s)},[r,s]);const a=j.useSyncExternalStore(j.useCallback(l=>r.subscribe(b0.batchCalls(l)),[r]),()=>r.getCurrentResult(),()=>r.getCurrentResult()),i=j.useCallback((...l)=>{r.mutate(l[0],l[1]).catch(d_)},[r]);if(a.error&&Cet(r.options.throwOnError,[a.error]))throw a.error;return{...a,mutate:i,mutateAsync:a.mutate}}function rFt(s,t){return nFt(s,Ows)}/** * @remix-run/router v1.23.4 * * Copyright (c) Remix Software Inc. * * This source code is licensed under the MIT license found in the * LICENSE.md file in the root directory of this source tree. * * @license MIT */function Yte(){return Yte=Object.assign?Object.assign.bind():function(s){for(var t=1;t"u")throw new Error(t)}function aFt(s,t){if(!s){typeof console<"u"&&console.warn(t);try{throw new Error(t)}catch{}}}function tjs(){return Math.random().toString(36).substr(2,8)}function txt(s,t){return{usr:s.state,key:s.key,idx:t}}function uHe(s,t,n,r){return n===void 0&&(n=null),Yte({pathname:typeof s=="string"?s:s.pathname,search:"",hash:""},typeof t=="string"?JW(t):t,{state:n,key:t&&t.key||r||tjs()})}function vEe(s){let{pathname:t="/",search:n="",hash:r=""}=s;return n&&n!=="?"&&(t+=n.charAt(0)==="?"?n:"?"+n),r&&r!=="#"&&(t+=r.charAt(0)==="#"?r:"#"+r),t}function JW(s){let t={};if(s){let n=s.indexOf("#");n>=0&&(t.hash=s.substr(n),s=s.substr(0,n));let r=s.indexOf("?");r>=0&&(t.search=s.substr(r),s=s.substr(0,r)),s&&(t.pathname=s)}return t}function sjs(s,t,n,r){r===void 0&&(r={});let{window:a=document.defaultView,v5Compat:i=!1}=r,l=a.history,o=xI.Pop,c=null,d=u();d==null&&(d=0,l.replaceState(Yte({},l.state,{idx:d}),""));function u(){return(l.state||{idx:null}).idx}function h(){o=xI.Pop;let y=u(),v=y==null?null:y-d;d=y,c&&c({action:o,location:x.location,delta:v})}function m(y,v){o=xI.Push;let b=uHe(x.location,y,v);d=u()+1;let w=txt(b,d),S=x.createHref(b);try{l.pushState(w,"",S)}catch(C){if(C instanceof DOMException&&C.name==="DataCloneError")throw C;a.location.assign(S)}i&&c&&c({action:o,location:x.location,delta:1})}function f(y,v){o=xI.Replace;let b=uHe(x.location,y,v);d=u();let w=txt(b,d),S=x.createHref(b);l.replaceState(w,"",S),i&&c&&c({action:o,location:x.location,delta:0})}function g(y){let v=a.location.origin!=="null"?a.location.origin:a.location.href,b=typeof y=="string"?y:vEe(y);return b=b.replace(/ $/,"%20"),Vg(v,"No window.location.(origin|href) available to create URL for href: "+b),new URL(b,v)}let x={get action(){return o},get location(){return s(a,l)},listen(y){if(c)throw new Error("A history only accepts one active listener");return a.addEventListener(ext,h),c=y,()=>{a.removeEventListener(ext,h),c=null}},createHref(y){return t(a,y)},createURL:g,encodeLocation(y){let v=g(y);return{pathname:v.pathname,search:v.search,hash:v.hash}},push:m,replace:f,go(y){return l.go(y)}};return x}var sxt;(function(s){s.data="data",s.deferred="deferred",s.redirect="redirect",s.error="error"})(sxt||(sxt={}));function njs(s,t,n){return n===void 0&&(n="/"),rjs(s,t,n)}function rjs(s,t,n,r){let a=typeof t=="string"?JW(t):t,i=yG(a.pathname||"/",n);if(i==null)return null;let l=iFt(s);ajs(l);let o=null,c=gjs(i);for(let d=0;o==null&&d{let c={relativePath:o===void 0?i.path||"":o,caseSensitive:i.caseSensitive===!0,childrenIndex:l,route:i};c.relativePath.startsWith("/")&&(Vg(c.relativePath.startsWith(r),'Absolute route path "'+c.relativePath+'" nested under path '+('"'+r+'" is not valid. An absolute child route path ')+"must start with the combined path of all its parent routes."),c.relativePath=c.relativePath.slice(r.length));let d=aL([r,c.relativePath]),u=n.concat(c);i.children&&i.children.length>0&&(Vg(i.index!==!0,"Index routes must not have child routes. Please remove "+('all child routes from route path "'+d+'".')),iFt(i.children,t,u,d)),!(i.path==null&&!i.index)&&t.push({path:d,score:hjs(d,i.index),routesMeta:u})};return s.forEach((i,l)=>{var o;if(i.path===""||!((o=i.path)!=null&&o.includes("?")))a(i,l);else for(let c of oFt(i.path))a(i,l,c)}),t}function oFt(s){let t=s.split("/");if(t.length===0)return[];let[n,...r]=t,a=n.endsWith("?"),i=n.replace(/\?$/,"");if(r.length===0)return a?[i,""]:[i];let l=oFt(r.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 ajs(s){s.sort((t,n)=>t.score!==n.score?n.score-t.score:mjs(t.routesMeta.map(r=>r.childrenIndex),n.routesMeta.map(r=>r.childrenIndex)))}const ijs=/^:[\w-]+$/,ojs=3,ljs=2,cjs=1,djs=10,ujs=-2,nxt=s=>s==="*";function hjs(s,t){let n=s.split("/"),r=n.length;return n.some(nxt)&&(r+=ujs),t&&(r+=ljs),n.filter(a=>!nxt(a)).reduce((a,i)=>a+(ijs.test(i)?ojs:i===""?cjs:djs),r)}function mjs(s,t){return s.length===t.length&&s.slice(0,-1).every((r,a)=>r===t[a])?s[s.length-1]-t[t.length-1]:0}function fjs(s,t,n){let{routesMeta:r}=s,a={},i="/",l=[];for(let o=0;o{let{paramName:m,isOptional:f}=u;if(m==="*"){let x=o[h]||"";l=i.slice(0,i.length-x.length).replace(/(.)\/+$/,"$1")}const g=o[h];return f&&!g?d[m]=void 0:d[m]=(g||"").replace(/%2F/g,"/"),d},{}),pathname:i,pathnameBase:l,pattern:s}}function pjs(s,t,n){t===void 0&&(t=!1),n===void 0&&(n=!0),aFt(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 r=[],a="^"+s.replace(/\/*\*?$/,"").replace(/^\/*/,"/").replace(/[\\.*+^${}|()[\]]/g,"\\$&").replace(/\/:([\w-]+)(\?)?/g,(l,o,c)=>(r.push({paramName:o,isOptional:c!=null}),c?"/?([^\\/]+)?":"/([^\\/]+)"));return s.endsWith("*")?(r.push({paramName:"*"}),a+=s==="*"||s==="/*"?"(.*)$":"(?:\\/(.+)|\\/*)$"):n?a+="\\/*$":s!==""&&s!=="/"&&(a+="(?:(?=\\/|$))"),[new RegExp(a,t?void 0:"i"),r]}function gjs(s){try{return s.split("/").map(t=>decodeURIComponent(t).replace(/\//g,"%2F")).join("/")}catch(t){return aFt(!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 yG(s,t){if(t==="/")return s;if(!s.toLowerCase().startsWith(t.toLowerCase()))return null;let n=t.endsWith("/")?t.length-1:t.length,r=s.charAt(n);return r&&r!=="/"?null:s.slice(n)||"/"}function xjs(s,t){t===void 0&&(t="/");let{pathname:n,search:r="",hash:a=""}=typeof s=="string"?JW(s):s,i;return n?(n=lFt(n),n.startsWith("/")?i=rxt(n.substring(1),"/"):i=rxt(n,t)):i=t,{pathname:i,search:bjs(r),hash:_js(a)}}function rxt(s,t){let n=t.replace(/\/+$/,"").split("/");return s.split("/").forEach(a=>{a===".."?n.length>1&&n.pop():a!=="."&&n.push(a)}),n.length>1?n.join("/"):"/"}function Rze(s,t,n,r){return"Cannot include a '"+s+"' character in a manually specified "+("`to."+t+"` field ["+JSON.stringify(r)+"]. Please separate it out to the ")+("`to."+n+"` field. Alternatively you may provide the full path as ")+'a string in and the router will parse it for you.'}function yjs(s){return s.filter((t,n)=>n===0||t.route.path&&t.route.path.length>0)}function Met(s,t){let n=yjs(s);return t?n.map((r,a)=>a===n.length-1?r.pathname:r.pathnameBase):n.map(r=>r.pathnameBase)}function Pet(s,t,n,r){r===void 0&&(r=!1);let a;typeof s=="string"?a=JW(s):(a=Yte({},s),Vg(!a.pathname||!a.pathname.includes("?"),Rze("?","pathname","search",a)),Vg(!a.pathname||!a.pathname.includes("#"),Rze("#","pathname","hash",a)),Vg(!a.search||!a.search.includes("#"),Rze("#","search","hash",a)));let i=s===""||a.pathname==="",l=i?"/":a.pathname,o;if(l==null)o=n;else{let h=t.length-1;if(!r&&l.startsWith("..")){let m=l.split("/");for(;m[0]==="..";)m.shift(),h-=1;a.pathname=m.join("/")}o=h>=0?t[h]:"/"}let c=xjs(a,o),d=l&&l!=="/"&&l.endsWith("/"),u=(i||l===".")&&n.endsWith("/");return!c.pathname.endsWith("/")&&(d||u)&&(c.pathname+="/"),c}const lFt=s=>s.replace(/\/\/+/g,"/"),aL=s=>lFt(s.join("/")),vjs=s=>s.replace(/\/+$/,"").replace(/^\/*/,"/"),bjs=s=>!s||s==="?"?"":s.startsWith("?")?s:"?"+s,_js=s=>!s||s==="#"?"":s.startsWith("#")?s:"#"+s;function wjs(s){return s!=null&&typeof s.status=="number"&&typeof s.statusText=="string"&&typeof s.internal=="boolean"&&"data"in s}const cFt=["post","put","patch","delete"];new Set(cFt);const jjs=["get",...cFt];new Set(jjs);/** * React Router v6.30.6 * * 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 Zte(){return Zte=Object.assign?Object.assign.bind():function(s){for(var t=1;t{o.current=!0}),j.useCallback(function(d,u){if(u===void 0&&(u={}),!o.current)return;if(typeof d=="number"){r.go(d);return}let h=Pet(d,JSON.parse(l),i,u.relative==="path");s==null&&t!=="/"&&(h.pathname=h.pathname==="/"?t:aL([t,h.pathname])),(u.replace?r.replace:r.push)(h,u.state,u)},[t,r,l,i,s])}const Sjs=j.createContext(null);function Cjs(s){let t=j.useContext(o3).outlet;return t&&j.createElement(Sjs.Provider,{value:s},t)}function Wi(){let{matches:s}=j.useContext(o3),t=s[s.length-1];return t?t.params:{}}function oLe(s,t){let{relative:n}=t===void 0?{}:t,{future:r}=j.useContext(MT),{matches:a}=j.useContext(o3),{pathname:i}=fu(),l=JSON.stringify(Met(a,r.v7_relativeSplatPath));return j.useMemo(()=>Pet(s,JSON.parse(l),i,n==="path"),[s,l,i,n])}function Ajs(s,t){return Ejs(s,t)}function Ejs(s,t,n,r){eK()||Vg(!1);let{navigator:a}=j.useContext(MT),{matches:i}=j.useContext(o3),l=i[i.length-1],o=l?l.params:{};l&&l.pathname;let c=l?l.pathnameBase:"/";l&&l.route;let d=fu(),u;if(t){var h;let y=typeof t=="string"?JW(t):t;c==="/"||(h=y.pathname)!=null&&h.startsWith(c)||Vg(!1),u=y}else u=d;let m=u.pathname||"/",f=m;if(c!=="/"){let y=c.replace(/^\//,"").split("/");f="/"+m.replace(/^\//,"").split("/").slice(y.length).join("/")}let g=njs(s,{pathname:f}),x=Ljs(g&&g.map(y=>Object.assign({},y,{params:Object.assign({},o,y.params),pathname:aL([c,a.encodeLocation?a.encodeLocation(y.pathname).pathname:y.pathname]),pathnameBase:y.pathnameBase==="/"?c:aL([c,a.encodeLocation?a.encodeLocation(y.pathnameBase).pathname:y.pathnameBase])})),i,n,r);return t&&x?j.createElement(iLe.Provider,{value:{location:Zte({pathname:"/",search:"",hash:"",state:null,key:"default"},u),navigationType:xI.Pop}},x):x}function Tjs(){let s=Ojs(),t=wjs(s)?s.status+" "+s.statusText:s instanceof Error?s.message:JSON.stringify(s),n=s instanceof Error?s.stack:null,a={padding:"0.5rem",backgroundColor:"rgba(200,200,200, 0.5)"};return j.createElement(j.Fragment,null,j.createElement("h2",null,"Unexpected Application Error!"),j.createElement("h3",{style:{fontStyle:"italic"}},t),n?j.createElement("pre",{style:a},n):null,null)}const Mjs=j.createElement(Tjs,null);class Pjs extends j.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,n){return n.location!==t.location||n.revalidation!=="idle"&&t.revalidation==="idle"?{error:t.error,location:t.location,revalidation:t.revalidation}:{error:t.error!==void 0?t.error:n.error,location:n.location,revalidation:t.revalidation||n.revalidation}}componentDidCatch(t,n){console.error("React Router caught the following error during render",t,n)}render(){return this.state.error!==void 0?j.createElement(o3.Provider,{value:this.props.routeContext},j.createElement(uFt.Provider,{value:this.state.error,children:this.props.component})):this.props.children}}function Ijs(s){let{routeContext:t,match:n,children:r}=s,a=j.useContext(aLe);return a&&a.static&&a.staticContext&&(n.route.errorElement||n.route.ErrorBoundary)&&(a.staticContext._deepestRenderedBoundaryId=n.route.id),j.createElement(o3.Provider,{value:t},r)}function Ljs(s,t,n,r){var a;if(t===void 0&&(t=[]),n===void 0&&(n=null),r===void 0&&(r=null),s==null){var i;if(!n)return null;if(n.errors)s=n.matches;else if((i=r)!=null&&i.v7_partialHydration&&t.length===0&&!n.initialized&&n.matches.length>0)s=n.matches;else return null}let l=s,o=(a=n)==null?void 0:a.errors;if(o!=null){let u=l.findIndex(h=>h.route.id&&(o==null?void 0:o[h.route.id])!==void 0);u>=0||Vg(!1),l=l.slice(0,Math.min(l.length,u+1))}let c=!1,d=-1;if(n&&r&&r.v7_partialHydration)for(let u=0;u=0?l=l.slice(0,d+1):l=[l[0]];break}}}return l.reduceRight((u,h,m)=>{let f,g=!1,x=null,y=null;n&&(f=o&&h.route.id?o[h.route.id]:void 0,x=h.route.errorElement||Mjs,c&&(d<0&&m===0?(Bjs("route-fallback"),g=!0,y=null):d===m&&(g=!0,y=h.route.hydrateFallbackElement||null)));let v=t.concat(l.slice(0,m+1)),b=()=>{let w;return f?w=x:g?w=y:h.route.Component?w=j.createElement(h.route.Component,null):h.route.element?w=h.route.element:w=u,j.createElement(Ijs,{match:h,routeContext:{outlet:u,matches:v,isDataRoute:n!=null},children:w})};return n&&(h.route.ErrorBoundary||h.route.errorElement||m===0)?j.createElement(Pjs,{location:n.location,revalidation:n.revalidation,component:x,error:f,children:b(),routeContext:{outlet:null,matches:v,isDataRoute:!0}}):b()},null)}var mFt=function(s){return s.UseBlocker="useBlocker",s.UseRevalidator="useRevalidator",s.UseNavigateStable="useNavigate",s}(mFt||{}),fFt=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}(fFt||{});function Rjs(s){let t=j.useContext(aLe);return t||Vg(!1),t}function Djs(s){let t=j.useContext(dFt);return t||Vg(!1),t}function Fjs(s){let t=j.useContext(o3);return t||Vg(!1),t}function pFt(s){let t=Fjs(),n=t.matches[t.matches.length-1];return n.route.id||Vg(!1),n.route.id}function Ojs(){var s;let t=j.useContext(uFt),n=Djs(),r=pFt();return t!==void 0?t:(s=n.errors)==null?void 0:s[r]}function zjs(){let{router:s}=Rjs(mFt.UseNavigateStable),t=pFt(fFt.UseNavigateStable),n=j.useRef(!1);return hFt(()=>{n.current=!0}),j.useCallback(function(a,i){i===void 0&&(i={}),n.current&&(typeof a=="number"?s.navigate(a):s.navigate(a,Zte({fromRouteId:t},i)))},[s,t])}const axt={};function Bjs(s,t,n){axt[s]||(axt[s]=!0)}function $js(s,t){s==null||s.v7_startTransition,s==null||s.v7_relativeSplatPath}function Fd(s){let{to:t,replace:n,state:r,relative:a}=s;eK()||Vg(!1);let{future:i,static:l}=j.useContext(MT),{matches:o}=j.useContext(o3),{pathname:c}=fu(),d=Qn(),u=Pet(t,Met(o,i.v7_relativeSplatPath),c,a==="path"),h=JSON.stringify(u);return j.useEffect(()=>d(JSON.parse(h),{replace:n,state:r,relative:a}),[d,h,a,n,r]),null}function Iet(s){return Cjs(s.context)}function ss(s){Vg(!1)}function Ujs(s){let{basename:t="/",children:n=null,location:r,navigationType:a=xI.Pop,navigator:i,static:l=!1,future:o}=s;eK()&&Vg(!1);let c=t.replace(/^\/*/,"/"),d=j.useMemo(()=>({basename:c,navigator:i,static:l,future:Zte({v7_relativeSplatPath:!1},o)}),[c,o,i,l]);typeof r=="string"&&(r=JW(r));let{pathname:u="/",search:h="",hash:m="",state:f=null,key:g="default"}=r,x=j.useMemo(()=>{let y=yG(u,c);return y==null?null:{location:{pathname:y,search:h,hash:m,state:f,key:g},navigationType:a}},[c,u,h,m,f,g,a]);return x==null?null:j.createElement(MT.Provider,{value:d},j.createElement(iLe.Provider,{children:n,value:x}))}function vG(s){let{children:t,location:n}=s;return Ajs(mHe(t),n)}new Promise(()=>{});function mHe(s,t){t===void 0&&(t=[]);let n=[];return j.Children.forEach(s,(r,a)=>{if(!j.isValidElement(r))return;let i=[...t,a];if(r.type===j.Fragment){n.push.apply(n,mHe(r.props.children,i));return}r.type!==ss&&Vg(!1),!r.props.index||!r.props.children||Vg(!1);let l={id:r.props.id||i.join("-"),caseSensitive:r.props.caseSensitive,element:r.props.element,Component:r.props.Component,index:r.props.index,path:r.props.path,loader:r.props.loader,action:r.props.action,errorElement:r.props.errorElement,ErrorBoundary:r.props.ErrorBoundary,hasErrorBoundary:r.props.ErrorBoundary!=null||r.props.errorElement!=null,shouldRevalidate:r.props.shouldRevalidate,handle:r.props.handle,lazy:r.props.lazy};r.props.children&&(l.children=mHe(r.props.children,i)),n.push(l)}),n}/** * React Router DOM v6.30.6 * * 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 bEe(){return bEe=Object.assign?Object.assign.bind():function(s){for(var t=1;t{let r=s[n];return t.concat(Array.isArray(r)?r.map(a=>[n,a]):[[n,r]])},[]))}function Hjs(s,t){let n=fHe(s);return t&&t.forEach((r,a)=>{n.has(a)||t.getAll(a).forEach(i=>{n.append(a,i)})}),n}const Gjs=["onClick","relative","reloadDocument","replace","state","target","to","preventScrollReset","viewTransition"],Wjs=["aria-current","caseSensitive","className","end","style","to","viewTransition","children"],Kjs="6";try{window.__reactRouterVersion=Kjs}catch{}const Yjs=j.createContext({isTransitioning:!1}),Zjs="startTransition",ixt=MB[Zjs];function Xjs(s){let{basename:t,children:n,future:r,window:a}=s,i=j.useRef();i.current==null&&(i.current=ejs({window:a,v5Compat:!0}));let l=i.current,[o,c]=j.useState({action:l.action,location:l.location}),{v7_startTransition:d}=r||{},u=j.useCallback(h=>{d&&ixt?ixt(()=>c(h)):c(h)},[c,d]);return j.useLayoutEffect(()=>l.listen(u),[l,u]),j.useEffect(()=>$js(r),[r]),j.createElement(Ujs,{basename:t,children:n,location:o.location,navigationType:o.action,navigator:l,future:r})}const Qjs=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u",Jjs=/^(?:[a-z][a-z0-9+.-]*:|\/\/)/i,wr=j.forwardRef(function(t,n){let{onClick:r,relative:a,reloadDocument:i,replace:l,state:o,target:c,to:d,preventScrollReset:u,viewTransition:h}=t,m=gFt(t,Gjs),{basename:f}=j.useContext(MT),g,x=!1;if(typeof d=="string"&&Jjs.test(d)&&(g=d,Qjs))try{let w=new URL(window.location.href),S=d.startsWith("//")?new URL(w.protocol+d):new URL(d),C=yG(S.pathname,f);S.origin===w.origin&&C!=null?d=C+S.search+S.hash:x=!0}catch{}let y=Njs(d,{relative:a}),v=t2s(d,{replace:l,state:o,target:c,preventScrollReset:u,relative:a,viewTransition:h});function b(w){r&&r(w),w.defaultPrevented||v(w)}return j.createElement("a",bEe({},m,{href:g||y,onClick:x||i?r:b,ref:n,target:c}))}),dP=j.forwardRef(function(t,n){let{"aria-current":r="page",caseSensitive:a=!1,className:i="",end:l=!1,style:o,to:c,viewTransition:d,children:u}=t,h=gFt(t,Wjs),m=oLe(c,{relative:h.relative}),f=fu(),g=j.useContext(dFt),{navigator:x,basename:y}=j.useContext(MT),v=g!=null&&s2s(m)&&d===!0,b=x.encodeLocation?x.encodeLocation(m).pathname:m.pathname,w=f.pathname,S=g&&g.navigation&&g.navigation.location?g.navigation.location.pathname:null;a||(w=w.toLowerCase(),S=S?S.toLowerCase():null,b=b.toLowerCase()),S&&y&&(S=yG(S,y)||S);const C=b!=="/"&&b.endsWith("/")?b.length-1:b.length;let E=w===b||!l&&w.startsWith(b)&&w.charAt(C)==="/",I=S!=null&&(S===b||!l&&S.startsWith(b)&&S.charAt(b.length)==="/"),P={isActive:E,isPending:I,isTransitioning:v},R=E?r:void 0,D;typeof i=="function"?D=i(P):D=[i,E?"active":null,I?"pending":null,v?"transitioning":null].filter(Boolean).join(" ");let O=typeof o=="function"?o(P):o;return j.createElement(wr,bEe({},h,{"aria-current":R,className:D,ref:n,style:O,to:c,viewTransition:d}),typeof u=="function"?u(P):u)});var pHe;(function(s){s.UseScrollRestoration="useScrollRestoration",s.UseSubmit="useSubmit",s.UseSubmitFetcher="useSubmitFetcher",s.UseFetcher="useFetcher",s.useViewTransitionState="useViewTransitionState"})(pHe||(pHe={}));var oxt;(function(s){s.UseFetcher="useFetcher",s.UseFetchers="useFetchers",s.UseScrollRestoration="useScrollRestoration"})(oxt||(oxt={}));function e2s(s){let t=j.useContext(aLe);return t||Vg(!1),t}function t2s(s,t){let{target:n,replace:r,state:a,preventScrollReset:i,relative:l,viewTransition:o}=t===void 0?{}:t,c=Qn(),d=fu(),u=oLe(s,{relative:l});return j.useCallback(h=>{if(Vjs(h,n)){h.preventDefault();let m=r!==void 0?r:vEe(d)===vEe(u);c(s,{replace:m,state:a,preventScrollReset:i,relative:l,viewTransition:o})}},[d,c,u,r,a,n,s,i,l,o])}function gc(s){let t=j.useRef(fHe(s)),n=j.useRef(!1),r=fu(),a=j.useMemo(()=>Hjs(r.search,n.current?null:t.current),[r.search]),i=Qn(),l=j.useCallback((o,c)=>{const d=fHe(typeof o=="function"?o(a):o);n.current=!0,i("?"+d,c)},[i,a]);return[a,l]}function s2s(s,t){t===void 0&&(t={});let n=j.useContext(Yjs);n==null&&Vg(!1);let{basename:r}=e2s(pHe.useViewTransitionState),a=oLe(s,{relative:t.relative});if(!n.isTransitioning)return!1;let i=yG(n.currentLocation.pathname,r)||n.currentLocation.pathname,l=yG(n.nextLocation.pathname,r)||n.nextLocation.pathname;return hHe(a.pathname,l)!=null||hHe(a.pathname,i)!=null}var n2s=typeof Element<"u",r2s=typeof Map=="function",a2s=typeof Set=="function",i2s=typeof ArrayBuffer=="function"&&!!ArrayBuffer.isView;function G4e(s,t){if(s===t)return!0;if(s&&t&&typeof s=="object"&&typeof t=="object"){if(s.constructor!==t.constructor)return!1;var n,r,a;if(Array.isArray(s)){if(n=s.length,n!=t.length)return!1;for(r=n;r--!==0;)if(!G4e(s[r],t[r]))return!1;return!0}var i;if(r2s&&s instanceof Map&&t instanceof Map){if(s.size!==t.size)return!1;for(i=s.entries();!(r=i.next()).done;)if(!t.has(r.value[0]))return!1;for(i=s.entries();!(r=i.next()).done;)if(!G4e(r.value[1],t.get(r.value[0])))return!1;return!0}if(a2s&&s instanceof Set&&t instanceof Set){if(s.size!==t.size)return!1;for(i=s.entries();!(r=i.next()).done;)if(!t.has(r.value[0]))return!1;return!0}if(i2s&&ArrayBuffer.isView(s)&&ArrayBuffer.isView(t)){if(n=s.length,n!=t.length)return!1;for(r=n;r--!==0;)if(s[r]!==t[r])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),n=a.length,n!==Object.keys(t).length)return!1;for(r=n;r--!==0;)if(!Object.prototype.hasOwnProperty.call(t,a[r]))return!1;if(n2s&&s instanceof Element)return!1;for(r=n;r--!==0;)if(!((a[r]==="_owner"||a[r]==="__v"||a[r]==="__o")&&s.$$typeof)&&!G4e(s[a[r]],t[a[r]]))return!1;return!0}return s!==s&&t!==t}var o2s=function(t,n){try{return G4e(t,n)}catch(r){if((r.message||"").match(/stack|recursion/i))return console.warn("react-fast-compare cannot handle circular refs"),!1;throw r}};const l2s=au(o2s);var c2s=function(s,t,n,r,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=[n,r,a,i,l,o],u=0;c=new Error(t.replace(/%s/g,function(){return d[u++]})),c.name="Invariant Violation"}throw c.framesToPop=1,c}},d2s=c2s;const lxt=au(d2s);var u2s=function(t,n,r,a){var i=r?r.call(a,t,n):void 0;if(i!==void 0)return!!i;if(t===n)return!0;if(typeof t!="object"||!t||typeof n!="object"||!n)return!1;var l=Object.keys(t),o=Object.keys(n);if(l.length!==o.length)return!1;for(var c=Object.prototype.hasOwnProperty.bind(n),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))(xFt||{}),Dze={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"]}},cxt=Object.values(xFt),Let={accesskey:"accessKey",charset:"charSet",class:"className",contenteditable:"contentEditable",contextmenu:"contextMenu","http-equiv":"httpEquiv",itemprop:"itemProp",tabindex:"tabIndex"},m2s=Object.entries(Let).reduce((s,[t,n])=>(s[n]=t,s),{}),GS="data-rh",wV={DEFAULT_TITLE:"defaultTitle",DEFER:"defer",ENCODE_SPECIAL_CHARACTERS:"encodeSpecialCharacters",ON_CHANGE_CLIENT_STATE:"onChangeClientState",TITLE_TEMPLATE:"titleTemplate",PRIORITIZE_SEO_TAGS:"prioritizeSeoTags"},jV=(s,t)=>{for(let n=s.length-1;n>=0;n-=1){const r=s[n];if(Object.prototype.hasOwnProperty.call(r,t))return r[t]}return null},f2s=s=>{let t=jV(s,"title");const n=jV(s,wV.TITLE_TEMPLATE);if(Array.isArray(t)&&(t=t.join("")),n&&t)return n.replace(/%s/g,()=>t);const r=jV(s,wV.DEFAULT_TITLE);return t||r||void 0},p2s=s=>jV(s,wV.ON_CHANGE_CLIENT_STATE)||(()=>{}),Fze=(s,t)=>t.filter(n=>typeof n[s]<"u").map(n=>n[s]).reduce((n,r)=>({...n,...r}),{}),g2s=(s,t)=>t.filter(n=>typeof n.base<"u").map(n=>n.base).reverse().reduce((n,r)=>{if(!n.length){const a=Object.keys(r);for(let i=0;iconsole&&typeof console.warn=="function"&&console.warn(s),_Z=(s,t,n)=>{const r={};return n.filter(a=>Array.isArray(a[s])?!0:(typeof a[s]<"u"&&x2s(`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 u=Object.keys(c);for(let m=0;ma.push(c));const o=Object.keys(l);for(let c=0;c{if(Array.isArray(s)&&s.length){for(let n=0;n({baseTag:g2s(["href"],s),bodyAttributes:Fze("bodyAttributes",s),defer:jV(s,wV.DEFER),encode:jV(s,wV.ENCODE_SPECIAL_CHARACTERS),htmlAttributes:Fze("htmlAttributes",s),linkTags:_Z("link",["rel","href"],s),metaTags:_Z("meta",["name","charset","http-equiv","property","itemprop"],s),noscriptTags:_Z("noscript",["innerHTML"],s),onChangeClientState:p2s(s),scriptTags:_Z("script",["src","innerHTML"],s),styleTags:_Z("style",["cssText"],s),title:f2s(s),titleAttributes:Fze("titleAttributes",s),prioritizeSeoTags:y2s(s,wV.PRIORITIZE_SEO_TAGS)}),yFt=s=>Array.isArray(s)?s.join(""):s,b2s=(s,t)=>{const n=Object.keys(s);for(let r=0;rArray.isArray(s)?s.reduce((n,r)=>(b2s(r,t)?n.priority.push(r):n.default.push(r),n),{priority:[],default:[]}):{default:s,priority:[]},dxt=(s,t)=>({...s,[t]:void 0}),_2s=["noscript","script","style"],gHe=(s,t=!0)=>t===!1?String(s):String(s).replace(/&/g,"&").replace(//g,">").replace(/"/g,""").replace(/'/g,"'"),vFt=s=>Object.keys(s).reduce((t,n)=>{const r=typeof s[n]<"u"?`${n}="${s[n]}"`:`${n}`;return t?`${t} ${r}`:r},""),w2s=(s,t,n,r)=>{const a=vFt(n),i=yFt(t);return a?`<${s} ${GS}="true" ${a}>${gHe(i,r)}`:`<${s} ${GS}="true">${gHe(i,r)}`},j2s=(s,t,n=!0)=>t.reduce((r,a)=>{const i=a,l=Object.keys(i).filter(d=>!(d==="innerHTML"||d==="cssText")).reduce((d,u)=>{const h=typeof i[u]>"u"?u:`${u}="${gHe(i[u],n)}"`;return d?`${d} ${h}`:h},""),o=i.innerHTML||i.cssText||"",c=_2s.indexOf(s)===-1;return`${r}<${s} ${GS}="true" ${l}${c?"/>":`>${o}`}`},""),bFt=(s,t={})=>Object.keys(s).reduce((n,r)=>{const a=Let[r];return n[a||r]=s[r],n},t),N2s=(s,t,n)=>{const r={key:t,[GS]:!0},a=bFt(n,r);return[Gt.createElement("title",a,t)]},W4e=(s,t)=>t.map((n,r)=>{const a={key:r,[GS]:!0};return Object.keys(n).forEach(i=>{const o=Let[i]||i;if(o==="innerHTML"||o==="cssText"){const c=n.innerHTML||n.cssText;a.dangerouslySetInnerHTML={__html:c}}else a[o]=n[i]}),Gt.createElement(s,a)}),wN=(s,t,n=!0)=>{switch(s){case"title":return{toComponent:()=>N2s(s,t.title,t.titleAttributes),toString:()=>w2s(s,t.title,t.titleAttributes,n)};case"bodyAttributes":case"htmlAttributes":return{toComponent:()=>bFt(t),toString:()=>vFt(t)};default:return{toComponent:()=>W4e(s,t),toString:()=>j2s(s,t,n)}}},k2s=({metaTags:s,linkTags:t,scriptTags:n,encode:r})=>{const a=Oze(s,Dze.meta),i=Oze(t,Dze.link),l=Oze(n,Dze.script);return{priorityMethods:{toComponent:()=>[...W4e("meta",a.priority),...W4e("link",i.priority),...W4e("script",l.priority)],toString:()=>`${wN("meta",a.priority,r)} ${wN("link",i.priority,r)} ${wN("script",l.priority,r)}`},metaTags:a.default,linkTags:i.default,scriptTags:l.default}},S2s=s=>{const{baseTag:t,bodyAttributes:n,encode:r=!0,htmlAttributes:a,noscriptTags:i,styleTags:l,title:o="",titleAttributes:c,prioritizeSeoTags:d}=s;let{linkTags:u,metaTags:h,scriptTags:m}=s,f={toComponent:()=>{},toString:()=>""};return d&&({priorityMethods:f,linkTags:u,metaTags:h,scriptTags:m}=k2s(s)),{priority:f,base:wN("base",t,r),bodyAttributes:wN("bodyAttributes",n,r),htmlAttributes:wN("htmlAttributes",a,r),link:wN("link",u,r),meta:wN("meta",h,r),noscript:wN("noscript",i,r),script:wN("script",m,r),style:wN("style",l,r),title:wN("title",{title:o,titleAttributes:c},r)}},xHe=S2s,jce=[],_Ft=!!(typeof window<"u"&&window.document&&window.document.createElement),yHe=class{constructor(s,t){Nr(this,"instances",[]);Nr(this,"canUseDOM",_Ft);Nr(this,"context");Nr(this,"value",{setHelmet:s=>{this.context.helmet=s},helmetInstances:{get:()=>this.canUseDOM?jce:this.instances,add:s=>{(this.canUseDOM?jce:this.instances).push(s)},remove:s=>{const t=(this.canUseDOM?jce:this.instances).indexOf(s);(this.canUseDOM?jce:this.instances).splice(t,1)}}});this.context=s,this.canUseDOM=t||!1,t||(s.helmet=xHe({baseTag:[],bodyAttributes:{},htmlAttributes:{},linkTags:[],metaTags:[],noscriptTags:[],scriptTags:[],styleTags:[],title:"",titleAttributes:{}}))}},C2s={},wFt=Gt.createContext(C2s),z8,jFt=(z8=class extends j.Component{constructor(n){super(n);Nr(this,"helmetData");this.helmetData=new yHe(this.props.context||{},z8.canUseDOM)}render(){return Gt.createElement(wFt.Provider,{value:this.helmetData.value},this.props.children)}},Nr(z8,"canUseDOM",_Ft),z8),g$=(s,t)=>{const n=document.head||document.querySelector("head"),r=n.querySelectorAll(`${s}[${GS}]`),a=[].slice.call(r),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 u=d,h=typeof o[u]>"u"?"":o[u];c.setAttribute(d,h)}c.setAttribute(GS,"true"),a.some((d,u)=>(l=u,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=>n.appendChild(o)),{oldTags:a,newTags:i}},vHe=(s,t)=>{const n=document.getElementsByTagName(s)[0];if(!n)return;const r=n.getAttribute(GS),a=r?r.split(","):[],i=[...a],l=Object.keys(t);for(const o of l){const c=t[o]||"";n.getAttribute(o)!==c&&n.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)n.removeAttribute(i[o]);a.length===i.length?n.removeAttribute(GS):n.getAttribute(GS)!==l.join(",")&&n.setAttribute(GS,l.join(","))},A2s=(s,t)=>{typeof s<"u"&&document.title!==s&&(document.title=yFt(s)),vHe("title",t)},uxt=(s,t)=>{const{baseTag:n,bodyAttributes:r,htmlAttributes:a,linkTags:i,metaTags:l,noscriptTags:o,onChangeClientState:c,scriptTags:d,styleTags:u,title:h,titleAttributes:m}=s;vHe("body",r),vHe("html",a),A2s(h,m);const f={baseTag:g$("base",n),linkTags:g$("link",i),metaTags:g$("meta",l),noscriptTags:g$("noscript",o),scriptTags:g$("script",d),styleTags:g$("style",u)},g={},x={};Object.keys(f).forEach(y=>{const{newTags:v,oldTags:b}=f[y];v.length&&(g[y]=v),b.length&&(x[y]=f[y].oldTags)}),t&&t(),c(s,g,x)},wZ=null,E2s=s=>{wZ&&cancelAnimationFrame(wZ),s.defer?wZ=requestAnimationFrame(()=>{uxt(s,()=>{wZ=null})}):(uxt(s),wZ=null)},T2s=E2s,hxt=class extends j.Component{constructor(){super(...arguments);Nr(this,"rendered",!1)}shouldComponentUpdate(t){return!h2s(t,this.props)}componentDidUpdate(){this.emitChange()}componentWillUnmount(){const{helmetInstances:t}=this.props.context;t.remove(this),this.emitChange()}emitChange(){const{helmetInstances:t,setHelmet:n}=this.props.context;let r=null;const a=v2s(t.get().map(i=>{const l={...i.props};return delete l.context,l}));jFt.canUseDOM?T2s(a):xHe&&(r=xHe(a)),n(r)}init(){if(this.rendered)return;this.rendered=!0;const{helmetInstances:t}=this.props.context;t.add(this),this.emitChange()}render(){return this.init(),null}},Oqe,Ml=(Oqe=class extends j.Component{shouldComponentUpdate(s){return!l2s(dxt(this.props,"helmetData"),dxt(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,n,r){return{...t,[s.type]:[...t[s.type]||[],{...n,...this.mapNestedChildrenToProps(s,r)}]}}mapObjectTypeChildren(s,t,n,r){switch(s.type){case"title":return{...t,[s.type]:r,titleAttributes:{...n}};case"body":return{...t,bodyAttributes:{...n}};case"html":return{...t,htmlAttributes:{...n}};default:return{...t,[s.type]:{...n}}}}mapArrayTypeChildrenToProps(s,t){let n={...t};return Object.keys(s).forEach(r=>{n={...n,[r]:s[r]}}),n}warnOnInvalidChildren(s,t){return lxt(cxt.some(n=>s.type===n),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 ${cxt.join(", ")} are allowed. Helmet does not support rendering <${s.type}> elements. Refer to our API for more information.`),lxt(!t||typeof t=="string"||Array.isArray(t)&&!t.some(n=>typeof n!="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 n={};return Gt.Children.forEach(s,r=>{if(!r||!r.props)return;const{children:a,...i}=r.props,l=Object.keys(i).reduce((c,d)=>(c[m2s[d]||d]=i[d],c),{});let{type:o}=r;switch(typeof o=="symbol"?o=o.toString():this.warnOnInvalidChildren(r,a),o){case"Symbol(react.fragment)":t=this.mapChildrenToProps(a,t);break;case"link":case"meta":case"noscript":case"script":case"style":n=this.flattenArrayTypeChildren(r,n,l,a);break;default:t=this.mapObjectTypeChildren(r,t,l,a);break}}),this.mapArrayTypeChildrenToProps(n,t)}render(){const{children:s,...t}=this.props;let n={...t},{helmetData:r}=t;if(s&&(n=this.mapChildrenToProps(s,n)),r&&!(r instanceof yHe)){const a=r;r=new yHe(a.context,!0),delete n.helmetData}return r?Gt.createElement(hxt,{...n,context:r.value}):Gt.createElement(wFt.Consumer,null,a=>Gt.createElement(hxt,{...n,context:a}))}},Nr(Oqe,"defaultProps",{defer:!0,encodeSpecialCharacters:!0,prioritizeSeoTags:!1}),Oqe);const M2s=s=>{let t;return s?t=s:typeof fetch>"u"?t=(...n)=>ri(async()=>{const{default:r}=await Promise.resolve().then(()=>tK);return{default:r}},void 0).then(({default:r})=>r(...n)):t=fetch,(...n)=>t(...n)};class Ret extends Error{constructor(t,n="FunctionsError",r){super(t),this.name=n,this.context=r}}class P2s extends Ret{constructor(t){super("Failed to send a request to the Edge Function","FunctionsFetchError",t)}}class I2s extends Ret{constructor(t){super("Relay Error invoking the Edge Function","FunctionsRelayError",t)}}class Tae extends Ret{constructor(t){super("Edge Function returned a non-2xx status code","FunctionsHttpError",t)}}var bHe;(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"})(bHe||(bHe={}));var L2s=function(s,t,n,r){function a(i){return i instanceof n?i:new n(function(l){l(i)})}return new(n||(n=Promise))(function(i,l){function o(u){try{d(r.next(u))}catch(h){l(h)}}function c(u){try{d(r.throw(u))}catch(h){l(h)}}function d(u){u.done?i(u.value):a(u.value).then(o,c)}d((r=r.apply(s,t||[])).next())})};class R2s{constructor(t,{headers:n={},customFetch:r,region:a=bHe.Any}={}){this.url=t,this.headers=n,this.region=a,this.fetch=M2s(r)}setAuth(t){this.headers.Authorization=`Bearer ${t}`}invoke(t,n={}){var r;return L2s(this,void 0,void 0,function*(){try{const{headers:a,method:i,body:l}=n;let o={},{region:c}=n;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 u=yield this.fetch(`${this.url}/${t}`,{method:i||"POST",headers:Object.assign(Object.assign(Object.assign({},o),this.headers),a),body:d}).catch(g=>{throw new P2s(g)}),h=u.headers.get("x-relay-error");if(h&&h==="true")throw new I2s(u);if(!u.ok)throw new Tae(u);let m=((r=u.headers.get("Content-Type"))!==null&&r!==void 0?r:"text/plain").split(";")[0].trim(),f;return m==="application/json"?f=yield u.json():m==="application/octet-stream"?f=yield u.blob():m==="text/event-stream"?f=u:m==="multipart/form-data"?f=yield u.formData():f=yield u.text(),{data:f,error:null}}catch(a){return{data:null,error:a}}})}}var _w={},Det={},lLe={},Mae={},cLe={},dLe={},D2s=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")},bG=D2s();const F2s=bG.fetch,NFt=bG.fetch.bind(bG),kFt=bG.Headers,O2s=bG.Request,z2s=bG.Response,tK=Object.freeze(Object.defineProperty({__proto__:null,Headers:kFt,Request:O2s,Response:z2s,default:NFt,fetch:F2s},Symbol.toStringTag,{value:"Module"})),B2s=mgs(tK);var uLe={};Object.defineProperty(uLe,"__esModule",{value:!0});let $2s=class extends Error{constructor(t){super(t.message),this.name="PostgrestError",this.details=t.details,this.hint=t.hint,this.code=t.code}};uLe.default=$2s;var SFt=Sp&&Sp.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(dLe,"__esModule",{value:!0});const U2s=SFt(B2s),q2s=SFt(uLe);let V2s=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=U2s.default:this.fetch=fetch}throwOnError(){return this.shouldThrowOnError=!0,this}setHeader(t,n){return this.headers=Object.assign({},this.headers),this.headers[t]=n,this}then(t,n){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 r=this.fetch;let a=r(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,u=null,h=null,m=i.status,f=i.statusText;if(i.ok){if(this.method!=="HEAD"){const v=await i.text();v===""||(this.headers.Accept==="text/csv"||this.headers.Accept&&this.headers.Accept.includes("application/vnd.pgrst.plan+text")?u=v:u=JSON.parse(v))}const x=(l=this.headers.Prefer)===null||l===void 0?void 0:l.match(/count=(exact|planned|estimated)/),y=(o=i.headers.get("content-range"))===null||o===void 0?void 0:o.split("/");x&&y&&y.length>1&&(h=parseInt(y[1])),this.isMaybeSingle&&this.method==="GET"&&Array.isArray(u)&&(u.length>1?(d={code:"PGRST116",details:`Results contain ${u.length} rows, application/vnd.pgrst.object+json requires 1 row`,hint:null,message:"JSON object requested, multiple (or no) rows returned"},u=null,h=null,m=406,f="Not Acceptable"):u.length===1?u=u[0]:u=null)}else{const x=await i.text();try{d=JSON.parse(x),Array.isArray(d)&&i.status===404&&(u=[],d=null,m=200,f="OK")}catch{i.status===404&&x===""?(m=204,f="No Content"):d={message:x}}if(d&&this.isMaybeSingle&&(!((c=d==null?void 0:d.details)===null||c===void 0)&&c.includes("0 rows"))&&(d=null,m=200,f="OK"),d&&this.shouldThrowOnError)throw new q2s.default(d)}return{error:d,data:u,count:h,status:m,statusText:f}});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,n)}returns(){return this}overrideTypes(){return this}};dLe.default=V2s;var H2s=Sp&&Sp.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(cLe,"__esModule",{value:!0});const G2s=H2s(dLe);let W2s=class extends G2s.default{select(t){let n=!1;const r=(t??"*").split("").map(a=>/\s/.test(a)&&!n?"":(a==='"'&&(n=!n),a)).join("");return this.url.searchParams.set("select",r),this.headers.Prefer&&(this.headers.Prefer+=","),this.headers.Prefer+="return=representation",this}order(t,{ascending:n=!0,nullsFirst:r,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}.${n?"asc":"desc"}${r===void 0?"":r?".nullsfirst":".nullslast"}`),this}limit(t,{foreignTable:n,referencedTable:r=n}={}){const a=typeof r>"u"?"limit":`${r}.limit`;return this.url.searchParams.set(a,`${t}`),this}range(t,n,{foreignTable:r,referencedTable:a=r}={}){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,`${n-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:n=!1,settings:r=!1,buffers:a=!1,wal:i=!1,format:l="text"}={}){var o;const c=[t?"analyze":null,n?"verbose":null,r?"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}};cLe.default=W2s;var K2s=Sp&&Sp.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(Mae,"__esModule",{value:!0});const Y2s=K2s(cLe);let Z2s=class extends Y2s.default{eq(t,n){return this.url.searchParams.append(t,`eq.${n}`),this}neq(t,n){return this.url.searchParams.append(t,`neq.${n}`),this}gt(t,n){return this.url.searchParams.append(t,`gt.${n}`),this}gte(t,n){return this.url.searchParams.append(t,`gte.${n}`),this}lt(t,n){return this.url.searchParams.append(t,`lt.${n}`),this}lte(t,n){return this.url.searchParams.append(t,`lte.${n}`),this}like(t,n){return this.url.searchParams.append(t,`like.${n}`),this}likeAllOf(t,n){return this.url.searchParams.append(t,`like(all).{${n.join(",")}}`),this}likeAnyOf(t,n){return this.url.searchParams.append(t,`like(any).{${n.join(",")}}`),this}ilike(t,n){return this.url.searchParams.append(t,`ilike.${n}`),this}ilikeAllOf(t,n){return this.url.searchParams.append(t,`ilike(all).{${n.join(",")}}`),this}ilikeAnyOf(t,n){return this.url.searchParams.append(t,`ilike(any).{${n.join(",")}}`),this}is(t,n){return this.url.searchParams.append(t,`is.${n}`),this}in(t,n){const r=Array.from(new Set(n)).map(a=>typeof a=="string"&&new RegExp("[,()]").test(a)?`"${a}"`:`${a}`).join(",");return this.url.searchParams.append(t,`in.(${r})`),this}contains(t,n){return typeof n=="string"?this.url.searchParams.append(t,`cs.${n}`):Array.isArray(n)?this.url.searchParams.append(t,`cs.{${n.join(",")}}`):this.url.searchParams.append(t,`cs.${JSON.stringify(n)}`),this}containedBy(t,n){return typeof n=="string"?this.url.searchParams.append(t,`cd.${n}`):Array.isArray(n)?this.url.searchParams.append(t,`cd.{${n.join(",")}}`):this.url.searchParams.append(t,`cd.${JSON.stringify(n)}`),this}rangeGt(t,n){return this.url.searchParams.append(t,`sr.${n}`),this}rangeGte(t,n){return this.url.searchParams.append(t,`nxl.${n}`),this}rangeLt(t,n){return this.url.searchParams.append(t,`sl.${n}`),this}rangeLte(t,n){return this.url.searchParams.append(t,`nxr.${n}`),this}rangeAdjacent(t,n){return this.url.searchParams.append(t,`adj.${n}`),this}overlaps(t,n){return typeof n=="string"?this.url.searchParams.append(t,`ov.${n}`):this.url.searchParams.append(t,`ov.{${n.join(",")}}`),this}textSearch(t,n,{config:r,type:a}={}){let i="";a==="plain"?i="pl":a==="phrase"?i="ph":a==="websearch"&&(i="w");const l=r===void 0?"":`(${r})`;return this.url.searchParams.append(t,`${i}fts${l}.${n}`),this}match(t){return Object.entries(t).forEach(([n,r])=>{this.url.searchParams.append(n,`eq.${r}`)}),this}not(t,n,r){return this.url.searchParams.append(t,`not.${n}.${r}`),this}or(t,{foreignTable:n,referencedTable:r=n}={}){const a=r?`${r}.or`:"or";return this.url.searchParams.append(a,`(${t})`),this}filter(t,n,r){return this.url.searchParams.append(t,`${n}.${r}`),this}};Mae.default=Z2s;var X2s=Sp&&Sp.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(lLe,"__esModule",{value:!0});const jZ=X2s(Mae);let Q2s=class{constructor(t,{headers:n={},schema:r,fetch:a}){this.url=t,this.headers=n,this.schema=r,this.fetch=a}select(t,{head:n=!1,count:r}={}){const a=n?"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),r&&(this.headers.Prefer=`count=${r}`),new jZ.default({method:a,url:this.url,headers:this.headers,schema:this.schema,fetch:this.fetch,allowEmpty:!1})}insert(t,{count:n,defaultToNull:r=!0}={}){const a="POST",i=[];if(this.headers.Prefer&&i.push(this.headers.Prefer),n&&i.push(`count=${n}`),r||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 jZ.default({method:a,url:this.url,headers:this.headers,schema:this.schema,body:t,fetch:this.fetch,allowEmpty:!1})}upsert(t,{onConflict:n,ignoreDuplicates:r=!1,count:a,defaultToNull:i=!0}={}){const l="POST",o=[`resolution=${r?"ignore":"merge"}-duplicates`];if(n!==void 0&&this.url.searchParams.set("on_conflict",n),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,u)=>d.concat(Object.keys(u)),[]);if(c.length>0){const d=[...new Set(c)].map(u=>`"${u}"`);this.url.searchParams.set("columns",d.join(","))}}return new jZ.default({method:l,url:this.url,headers:this.headers,schema:this.schema,body:t,fetch:this.fetch,allowEmpty:!1})}update(t,{count:n}={}){const r="PATCH",a=[];return this.headers.Prefer&&a.push(this.headers.Prefer),n&&a.push(`count=${n}`),this.headers.Prefer=a.join(","),new jZ.default({method:r,url:this.url,headers:this.headers,schema:this.schema,body:t,fetch:this.fetch,allowEmpty:!1})}delete({count:t}={}){const n="DELETE",r=[];return t&&r.push(`count=${t}`),this.headers.Prefer&&r.unshift(this.headers.Prefer),this.headers.Prefer=r.join(","),new jZ.default({method:n,url:this.url,headers:this.headers,schema:this.schema,fetch:this.fetch,allowEmpty:!1})}};lLe.default=Q2s;var hLe={},mLe={};Object.defineProperty(mLe,"__esModule",{value:!0});mLe.version=void 0;mLe.version="0.0.0-automated";Object.defineProperty(hLe,"__esModule",{value:!0});hLe.DEFAULT_HEADERS=void 0;const J2s=mLe;hLe.DEFAULT_HEADERS={"X-Client-Info":`postgrest-js/${J2s.version}`};var CFt=Sp&&Sp.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(Det,"__esModule",{value:!0});const eNs=CFt(lLe),tNs=CFt(Mae),sNs=hLe;let nNs=class AFt{constructor(t,{headers:n={},schema:r,fetch:a}={}){this.url=t,this.headers=Object.assign(Object.assign({},sNs.DEFAULT_HEADERS),n),this.schemaName=r,this.fetch=a}from(t){const n=new URL(`${this.url}/${t}`);return new eNs.default(n,{headers:Object.assign({},this.headers),schema:this.schemaName,fetch:this.fetch})}schema(t){return new AFt(this.url,{headers:this.headers,schema:t,fetch:this.fetch})}rpc(t,n={},{head:r=!1,get:a=!1,count:i}={}){let l;const o=new URL(`${this.url}/rpc/${t}`);let c;r||a?(l=r?"HEAD":"GET",Object.entries(n).filter(([u,h])=>h!==void 0).map(([u,h])=>[u,Array.isArray(h)?`{${h.join(",")}}`:`${h}`]).forEach(([u,h])=>{o.searchParams.append(u,h)})):(l="POST",c=n);const d=Object.assign({},this.headers);return i&&(d.Prefer=`count=${i}`),new tNs.default({method:l,url:o,headers:d,schema:this.schemaName,body:c,fetch:this.fetch,allowEmpty:!1})}};Det.default=nNs;var sK=Sp&&Sp.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(_w,"__esModule",{value:!0});_w.PostgrestError=_w.PostgrestBuilder=_w.PostgrestTransformBuilder=_w.PostgrestFilterBuilder=_w.PostgrestQueryBuilder=_w.PostgrestClient=void 0;const EFt=sK(Det);_w.PostgrestClient=EFt.default;const TFt=sK(lLe);_w.PostgrestQueryBuilder=TFt.default;const MFt=sK(Mae);_w.PostgrestFilterBuilder=MFt.default;const PFt=sK(cLe);_w.PostgrestTransformBuilder=PFt.default;const IFt=sK(dLe);_w.PostgrestBuilder=IFt.default;const LFt=sK(uLe);_w.PostgrestError=LFt.default;var rNs=_w.default={PostgrestClient:EFt.default,PostgrestQueryBuilder:TFt.default,PostgrestFilterBuilder:MFt.default,PostgrestTransformBuilder:PFt.default,PostgrestBuilder:IFt.default,PostgrestError:LFt.default};const{PostgrestClient:aNs,PostgrestQueryBuilder:Ukr,PostgrestFilterBuilder:qkr,PostgrestTransformBuilder:Vkr,PostgrestBuilder:Hkr,PostgrestError:Gkr}=rNs;let _He;typeof window>"u"?_He=require("ws"):_He=window.WebSocket;const iNs="2.11.10",oNs={"X-Client-Info":`realtime-js/${iNs}`},lNs="1.0.0",RFt=1e4,cNs=1e3;var NV;(function(s){s[s.connecting=0]="connecting",s[s.open=1]="open",s[s.closing=2]="closing",s[s.closed=3]="closed"})(NV||(NV={}));var a_;(function(s){s.closed="closed",s.errored="errored",s.joined="joined",s.joining="joining",s.leaving="leaving"})(a_||(a_={}));var LS;(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"})(LS||(LS={}));var wHe;(function(s){s.websocket="websocket"})(wHe||(wHe={}));var ZO;(function(s){s.Connecting="connecting",s.Open="open",s.Closing="closing",s.Closed="closed"})(ZO||(ZO={}));class dNs{constructor(){this.HEADER_LENGTH=1}decode(t,n){return t.constructor===ArrayBuffer?n(this._binaryDecode(t)):n(typeof t=="string"?JSON.parse(t):{})}_binaryDecode(t){const n=new DataView(t),r=new TextDecoder;return this._decodeBroadcast(t,n,r)}_decodeBroadcast(t,n,r){const a=n.getUint8(1),i=n.getUint8(2);let l=this.HEADER_LENGTH+2;const o=r.decode(t.slice(l,l+a));l=l+a;const c=r.decode(t.slice(l,l+i));l=l+i;const d=JSON.parse(r.decode(t.slice(l,t.byteLength)));return{ref:null,topic:o,event:c,payload:d}}}class DFt{constructor(t,n){this.callback=t,this.timerCalc=n,this.timer=void 0,this.tries=0,this.callback=t,this.timerCalc=n}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 $f;(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"})($f||($f={}));const mxt=(s,t,n={})=>{var r;const a=(r=n.skipTypes)!==null&&r!==void 0?r:[];return Object.keys(t).reduce((i,l)=>(i[l]=uNs(l,s,t,a),i),{})},uNs=(s,t,n,r)=>{const a=t.find(o=>o.name===s),i=a==null?void 0:a.type,l=n[s];return i&&!r.includes(i)?FFt(i,l):jHe(l)},FFt=(s,t)=>{if(s.charAt(0)==="_"){const n=s.slice(1,s.length);return pNs(t,n)}switch(s){case $f.bool:return hNs(t);case $f.float4:case $f.float8:case $f.int2:case $f.int4:case $f.int8:case $f.numeric:case $f.oid:return mNs(t);case $f.json:case $f.jsonb:return fNs(t);case $f.timestamp:return gNs(t);case $f.abstime:case $f.date:case $f.daterange:case $f.int4range:case $f.int8range:case $f.money:case $f.reltime:case $f.text:case $f.time:case $f.timestamptz:case $f.timetz:case $f.tsrange:case $f.tstzrange:return jHe(t);default:return jHe(t)}},jHe=s=>s,hNs=s=>{switch(s){case"t":return!0;case"f":return!1;default:return s}},mNs=s=>{if(typeof s=="string"){const t=parseFloat(s);if(!Number.isNaN(t))return t}return s},fNs=s=>{if(typeof s=="string")try{return JSON.parse(s)}catch(t){return console.log(`JSON parse error: ${t}`),s}return s},pNs=(s,t)=>{if(typeof s!="string")return s;const n=s.length-1,r=s[n];if(s[0]==="{"&&r==="}"){let i;const l=s.slice(1,n);try{i=JSON.parse("["+l+"]")}catch{i=l?l.split(","):[]}return i.map(o=>FFt(t,o))}return s},gNs=s=>typeof s=="string"?s.replace(" ","T"):s,OFt=s=>{let t=s;return t=t.replace(/^ws/i,"http"),t=t.replace(/(\/socket\/websocket|\/socket|\/websocket)\/?$/i,""),t.replace(/\/+$/,"")};class zze{constructor(t,n,r={},a=RFt){this.channel=t,this.event=n,this.payload=r,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,n){var r;return this._hasReceived(t)&&n((r=this.receivedResp)===null||r===void 0?void 0:r.response),this.recHooks.push({status:t,callback:n}),this}startTimeout(){if(this.timeoutTimer)return;this.ref=this.channel.socket._makeRef(),this.refEvent=this.channel._replyEventName(this.ref);const t=n=>{this._cancelRefEvent(),this._cancelTimeout(),this.receivedResp=n,this._matchReceive(n)};this.channel._on(this.refEvent,{},t),this.timeoutTimer=setTimeout(()=>{this.trigger("timeout",{})},this.timeout)}trigger(t,n){this.refEvent&&this.channel._trigger(this.refEvent,{status:t,response:n})}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:n}){this.recHooks.filter(r=>r.status===t).forEach(r=>r.callback(n))}_hasReceived(t){return this.receivedResp&&this.receivedResp.status===t}}var fxt;(function(s){s.SYNC="sync",s.JOIN="join",s.LEAVE="leave"})(fxt||(fxt={}));class mee{constructor(t,n){this.channel=t,this.state={},this.pendingDiffs=[],this.joinRef=null,this.caller={onJoin:()=>{},onLeave:()=>{},onSync:()=>{}};const r=(n==null?void 0:n.events)||{state:"presence_state",diff:"presence_diff"};this.channel._on(r.state,{},a=>{const{onJoin:i,onLeave:l,onSync:o}=this.caller;this.joinRef=this.channel._joinRef(),this.state=mee.syncState(this.state,a,i,l),this.pendingDiffs.forEach(c=>{this.state=mee.syncDiff(this.state,c,i,l)}),this.pendingDiffs=[],o()}),this.channel._on(r.diff,{},a=>{const{onJoin:i,onLeave:l,onSync:o}=this.caller;this.inPendingSyncState()?this.pendingDiffs.push(a):(this.state=mee.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,n,r,a){const i=this.cloneDeep(t),l=this.transformState(n),o={},c={};return this.map(i,(d,u)=>{l[d]||(c[d]=u)}),this.map(l,(d,u)=>{const h=i[d];if(h){const m=u.map(y=>y.presence_ref),f=h.map(y=>y.presence_ref),g=u.filter(y=>f.indexOf(y.presence_ref)<0),x=h.filter(y=>m.indexOf(y.presence_ref)<0);g.length>0&&(o[d]=g),x.length>0&&(c[d]=x)}else o[d]=u}),this.syncDiff(i,{joins:o,leaves:c},r,a)}static syncDiff(t,n,r,a){const{joins:i,leaves:l}={joins:this.transformState(n.joins),leaves:this.transformState(n.leaves)};return r||(r=()=>{}),a||(a=()=>{}),this.map(i,(o,c)=>{var d;const u=(d=t[o])!==null&&d!==void 0?d:[];if(t[o]=this.cloneDeep(c),u.length>0){const h=t[o].map(f=>f.presence_ref),m=u.filter(f=>h.indexOf(f.presence_ref)<0);t[o].unshift(...m)}r(o,u,c)}),this.map(l,(o,c)=>{let d=t[o];if(!d)return;const u=c.map(h=>h.presence_ref);d=d.filter(h=>u.indexOf(h.presence_ref)<0),t[o]=d,a(o,d,c),d.length===0&&delete t[o]}),t}static map(t,n){return Object.getOwnPropertyNames(t).map(r=>n(r,t[r]))}static transformState(t){return t=this.cloneDeep(t),Object.getOwnPropertyNames(t).reduce((n,r)=>{const a=t[r];return"metas"in a?n[r]=a.metas.map(i=>(i.presence_ref=i.phx_ref,delete i.phx_ref,delete i.phx_ref_prev,i)):n[r]=a,n},{})}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 pxt;(function(s){s.ALL="*",s.INSERT="INSERT",s.UPDATE="UPDATE",s.DELETE="DELETE"})(pxt||(pxt={}));var gxt;(function(s){s.BROADCAST="broadcast",s.PRESENCE="presence",s.POSTGRES_CHANGES="postgres_changes",s.SYSTEM="system"})(gxt||(gxt={}));var AA;(function(s){s.SUBSCRIBED="SUBSCRIBED",s.TIMED_OUT="TIMED_OUT",s.CLOSED="CLOSED",s.CHANNEL_ERROR="CHANNEL_ERROR"})(AA||(AA={}));class Fet{constructor(t,n={config:{}},r){this.topic=t,this.params=n,this.socket=r,this.bindings={},this.state=a_.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},n.config),this.timeout=this.socket.timeout,this.joinPush=new zze(this,LS.join,this.params,this.timeout),this.rejoinTimer=new DFt(()=>this._rejoinUntilConnected(),this.socket.reconnectAfterMs),this.joinPush.receive("ok",()=>{this.state=a_.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=a_.closed,this.socket._remove(this)}),this._onError(a=>{this._isLeaving()||this._isClosed()||(this.socket.log("channel",`error ${this.topic}`,a),this.state=a_.errored,this.rejoinTimer.scheduleTimeout())}),this.joinPush.receive("timeout",()=>{this._isJoining()&&(this.socket.log("channel",`timeout ${this.topic}`,this.joinPush.timeout),this.state=a_.errored,this.rejoinTimer.scheduleTimeout())}),this._on(LS.reply,{},(a,i)=>{this._trigger(this._replyEventName(i),a)}),this.presence=new mee(this),this.broadcastEndpointURL=OFt(this.socket.endPoint)+"/api/broadcast",this.private=this.params.config.private||!1}subscribe(t,n=this.timeout){var r,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(u=>t==null?void 0:t(AA.CHANNEL_ERROR,u)),this._onClose(()=>t==null?void 0:t(AA.CLOSED));const c={},d={broadcast:i,presence:l,postgres_changes:(a=(r=this.bindings.postgres_changes)===null||r===void 0?void 0:r.map(u=>u.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(n),this.joinPush.receive("ok",async({postgres_changes:u})=>{var h;if(this.socket.setAuth(),u===void 0){t==null||t(AA.SUBSCRIBED);return}else{const m=this.bindings.postgres_changes,f=(h=m==null?void 0:m.length)!==null&&h!==void 0?h:0,g=[];for(let x=0;x{this.state=a_.errored,t==null||t(AA.CHANNEL_ERROR,new Error(JSON.stringify(Object.values(u).join(", ")||"error")))}).receive("timeout",()=>{t==null||t(AA.TIMED_OUT)})}return this}presenceState(){return this.presence.state}async track(t,n={}){return await this.send({type:"presence",event:"track",payload:t},n.timeout||this.timeout)}async untrack(t={}){return await this.send({type:"presence",event:"untrack"},t)}on(t,n,r){return this._on(t,n,r)}async send(t,n={}){var r,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,(r=n.timeout)!==null&&r!==void 0?r: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,n.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=a_.leaving;const n=()=>{this.socket.log("channel",`leave ${this.topic}`),this._trigger(LS.close,"leave",this._joinRef())};return this.joinPush.destroy(),new Promise(r=>{const a=new zze(this,LS.leave,{},t);a.receive("ok",()=>{n(),r("ok")}).receive("timeout",()=>{n(),r("timed out")}).receive("error",()=>{r("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,n,r){const a=new AbortController,i=setTimeout(()=>a.abort(),r),l=await this.socket.fetch(t,Object.assign(Object.assign({},n),{signal:a.signal}));return clearTimeout(i),l}_push(t,n,r=this.timeout){if(!this.joinedOnce)throw`tried to push '${t}' to '${this.topic}' before joining. Use channel.subscribe() before pushing events`;let a=new zze(this,t,n,r);return this._canPush()?a.send():(a.startTimeout(),this.pushBuffer.push(a)),a}_onMessage(t,n,r){return n}_isMember(t){return this.topic===t}_joinRef(){return this.joinPush.ref}_trigger(t,n,r){var a,i;const l=t.toLocaleLowerCase(),{close:o,error:c,leave:d,join:u}=LS;if(r&&[o,c,d,u].indexOf(l)>=0&&r!==this._joinRef())return;let m=this._onMessage(l,n,r);if(n&&!m)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(f=>{var g,x,y;return((g=f.filter)===null||g===void 0?void 0:g.event)==="*"||((y=(x=f.filter)===null||x===void 0?void 0:x.event)===null||y===void 0?void 0:y.toLocaleLowerCase())===l}).map(f=>f.callback(m,r)):(i=this.bindings[l])===null||i===void 0||i.filter(f=>{var g,x,y,v,b,w;if(["broadcast","presence","postgres_changes"].includes(l))if("id"in f){const S=f.id,C=(g=f.filter)===null||g===void 0?void 0:g.event;return S&&((x=n.ids)===null||x===void 0?void 0:x.includes(S))&&(C==="*"||(C==null?void 0:C.toLocaleLowerCase())===((y=n.data)===null||y===void 0?void 0:y.type.toLocaleLowerCase()))}else{const S=(b=(v=f==null?void 0:f.filter)===null||v===void 0?void 0:v.event)===null||b===void 0?void 0:b.toLocaleLowerCase();return S==="*"||S===((w=n==null?void 0:n.event)===null||w===void 0?void 0:w.toLocaleLowerCase())}else return f.type.toLocaleLowerCase()===l}).map(f=>{if(typeof m=="object"&&"ids"in m){const g=m.data,{schema:x,table:y,commit_timestamp:v,type:b,errors:w}=g;m=Object.assign(Object.assign({},{schema:x,table:y,commit_timestamp:v,eventType:b,new:{},old:{},errors:w}),this._getPayloadRecords(g))}f.callback(m,r)})}_isClosed(){return this.state===a_.closed}_isJoined(){return this.state===a_.joined}_isJoining(){return this.state===a_.joining}_isLeaving(){return this.state===a_.leaving}_replyEventName(t){return`chan_reply_${t}`}_on(t,n,r){const a=t.toLocaleLowerCase(),i={type:a,filter:n,callback:r};return this.bindings[a]?this.bindings[a].push(i):this.bindings[a]=[i],this}_off(t,n){const r=t.toLocaleLowerCase();return this.bindings[r]=this.bindings[r].filter(a=>{var i;return!(((i=a.type)===null||i===void 0?void 0:i.toLocaleLowerCase())===r&&Fet.isEqual(a.filter,n))}),this}static isEqual(t,n){if(Object.keys(t).length!==Object.keys(n).length)return!1;for(const r in t)if(t[r]!==n[r])return!1;return!0}_rejoinUntilConnected(){this.rejoinTimer.scheduleTimeout(),this.socket.isConnected()&&this._rejoin()}_onClose(t){this._on(LS.close,{},t)}_onError(t){this._on(LS.error,{},n=>t(n))}_canPush(){return this.socket.isConnected()&&this._isJoined()}_rejoin(t=this.timeout){this._isLeaving()||(this.socket._leaveOpenTopic(this.topic),this.state=a_.joining,this.joinPush.resend(t))}_getPayloadRecords(t){const n={new:{},old:{}};return(t.type==="INSERT"||t.type==="UPDATE")&&(n.new=mxt(t.columns,t.record)),(t.type==="UPDATE"||t.type==="DELETE")&&(n.old=mxt(t.columns,t.old_record)),n}}const xxt=()=>{},xNs=` addEventListener("message", (e) => { if (e.data.event === "start") { setInterval(() => postMessage({ event: "keepAlive" }), e.data.interval); } });`;class yNs{constructor(t,n){var r;this.accessTokenValue=null,this.apiKey=null,this.channels=new Array,this.endPoint="",this.httpEndpoint="",this.headers=oNs,this.params={},this.timeout=RFt,this.heartbeatIntervalMs=25e3,this.heartbeatTimer=void 0,this.pendingHeartbeatRef=null,this.heartbeatCallback=xxt,this.ref=0,this.logger=xxt,this.conn=null,this.sendBuffer=[],this.serializer=new dNs,this.stateChangeCallbacks={open:[],close:[],error:[],message:[]},this.accessToken=null,this._resolveFetch=i=>{let l;return i?l=i:typeof fetch>"u"?l=(...o)=>ri(async()=>{const{default:c}=await Promise.resolve().then(()=>tK);return{default:c}},void 0).then(({default:c})=>c(...o)):l=fetch,(...o)=>l(...o)},this.endPoint=`${t}/${wHe.websocket}`,this.httpEndpoint=OFt(t),n!=null&&n.transport?this.transport=n.transport:this.transport=null,n!=null&&n.params&&(this.params=n.params),n!=null&&n.headers&&(this.headers=Object.assign(Object.assign({},this.headers),n.headers)),n!=null&&n.timeout&&(this.timeout=n.timeout),n!=null&&n.logger&&(this.logger=n.logger),(n!=null&&n.logLevel||n!=null&&n.log_level)&&(this.logLevel=n.logLevel||n.log_level,this.params=Object.assign(Object.assign({},this.params),{log_level:this.logLevel})),n!=null&&n.heartbeatIntervalMs&&(this.heartbeatIntervalMs=n.heartbeatIntervalMs);const a=(r=n==null?void 0:n.params)===null||r===void 0?void 0:r.apikey;if(a&&(this.accessTokenValue=a,this.apiKey=a),this.reconnectAfterMs=n!=null&&n.reconnectAfterMs?n.reconnectAfterMs:i=>[1e3,2e3,5e3,1e4][i-1]||1e4,this.encode=n!=null&&n.encode?n.encode:(i,l)=>l(JSON.stringify(i)),this.decode=n!=null&&n.decode?n.decode:this.serializer.decode.bind(this.serializer),this.reconnectTimer=new DFt(async()=>{this.disconnect(),this.connect()},this.reconnectAfterMs),this.fetch=this._resolveFetch(n==null?void 0:n.fetch),n!=null&&n.worker){if(typeof window<"u"&&!window.Worker)throw new Error("Web Worker is not supported");this.worker=(n==null?void 0:n.worker)||!1,this.workerUrl=n==null?void 0:n.workerUrl}this.accessToken=(n==null?void 0:n.accessToken)||null}connect(){if(!this.conn){if(this.transport||(this.transport=_He),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 vNs(this.endpointURL(),void 0,{close:()=>{this.conn=null}})}}endpointURL(){return this._appendParams(this.endPoint,Object.assign({},this.params,{vsn:lNs}))}disconnect(t,n){this.conn&&(this.conn.onclose=function(){},t?this.conn.close(t,n??""):this.conn.close(),this.conn=null,this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.reconnectTimer.reset(),this.channels.forEach(r=>r.teardown()))}getChannels(){return this.channels}async removeChannel(t){const n=await t.unsubscribe();return this.channels=this.channels.filter(r=>r._joinRef!==t._joinRef),this.channels.length===0&&this.disconnect(),n}async removeAllChannels(){const t=await Promise.all(this.channels.map(n=>n.unsubscribe()));return this.channels=[],this.disconnect(),t}log(t,n,r){this.logger(t,n,r)}connectionState(){switch(this.conn&&this.conn.readyState){case NV.connecting:return ZO.Connecting;case NV.open:return ZO.Open;case NV.closing:return ZO.Closing;default:return ZO.Closed}}isConnected(){return this.connectionState()===ZO.Open}channel(t,n={config:{}}){const r=`realtime:${t}`,a=this.getChannels().find(i=>i.topic===r);if(a)return a;{const i=new Fet(`realtime:${t}`,n,this);return this.channels.push(i),i}}push(t){const{topic:n,event:r,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",`${n} ${r} (${i})`,a),this.isConnected()?l():this.sendBuffer.push(l)}async setAuth(t=null){let n=t||this.accessToken&&await this.accessToken()||this.accessTokenValue;this.accessTokenValue!=n&&(this.accessTokenValue=n,this.channels.forEach(r=>{n&&r.updateJoinPayload({access_token:n,version:this.headers&&this.headers["X-Client-Info"]}),r.joinedOnce&&r._isJoined()&&r._push(LS.access_token,{access_token:n})}))}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(cNs,"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 n=this.channels.find(r=>r.topic===t&&(r._isJoined()||r._isJoining()));n&&(this.log("transport",`leaving duplicate topic "${t}"`),n.unsubscribe())}_remove(t){this.channels=this.channels.filter(n=>n.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,n=>{let{topic:r,event:a,payload:i,ref:l}=n;r==="phoenix"&&a==="phx_reply"&&this.heartbeatCallback(n.payload.status=="ok"?"ok":"error"),l&&l===this.pendingHeartbeatRef&&(this.pendingHeartbeatRef=null),this.log("receive",`${i.status||""} ${r} ${a} ${l&&"("+l+")"||""}`,i),Array.from(this.channels).filter(o=>o._isMember(r)).forEach(o=>o._trigger(a,i,l)),this.stateChangeCallbacks.message.forEach(o=>o(n))})}_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=n=>{this.log("worker","worker error",n.message),this.workerRef.terminate()},this.workerRef.onmessage=n=>{n.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(n=>n(t))}_onConnError(t){this.log("transport",t.message),this._triggerChanError(),this.stateChangeCallbacks.error.forEach(n=>n(t))}_triggerChanError(){this.channels.forEach(t=>t._trigger(LS.error))}_appendParams(t,n){if(Object.keys(n).length===0)return t;const r=t.match(/\?/)?"&":"?",a=new URLSearchParams(n);return`${t}${r}${a}`}_workerObjectUrl(t){let n;if(t)n=t;else{const r=new Blob([xNs],{type:"application/javascript"});n=URL.createObjectURL(r)}return n}}class vNs{constructor(t,n,r){this.binaryType="arraybuffer",this.onclose=()=>{},this.onerror=()=>{},this.onmessage=()=>{},this.onopen=()=>{},this.readyState=NV.connecting,this.send=()=>{},this.url=null,this.url=t,this.close=r.close}}class Oet extends Error{constructor(t){super(t),this.__isStorageError=!0,this.name="StorageError"}}function cv(s){return typeof s=="object"&&s!==null&&"__isStorageError"in s}class bNs extends Oet{constructor(t,n){super(t),this.name="StorageApiError",this.status=n}toJSON(){return{name:this.name,message:this.message,status:this.status}}}class NHe extends Oet{constructor(t,n){super(t),this.name="StorageUnknownError",this.originalError=n}}var _Ns=function(s,t,n,r){function a(i){return i instanceof n?i:new n(function(l){l(i)})}return new(n||(n=Promise))(function(i,l){function o(u){try{d(r.next(u))}catch(h){l(h)}}function c(u){try{d(r.throw(u))}catch(h){l(h)}}function d(u){u.done?i(u.value):a(u.value).then(o,c)}d((r=r.apply(s,t||[])).next())})};const zFt=s=>{let t;return s?t=s:typeof fetch>"u"?t=(...n)=>ri(async()=>{const{default:r}=await Promise.resolve().then(()=>tK);return{default:r}},void 0).then(({default:r})=>r(...n)):t=fetch,(...n)=>t(...n)},wNs=()=>_Ns(void 0,void 0,void 0,function*(){return typeof Response>"u"?(yield ri(()=>Promise.resolve().then(()=>tK),void 0)).Response:Response}),kHe=s=>{if(Array.isArray(s))return s.map(n=>kHe(n));if(typeof s=="function"||s!==Object(s))return s;const t={};return Object.entries(s).forEach(([n,r])=>{const a=n.replace(/([-_][a-z])/gi,i=>i.toUpperCase().replace(/[-_]/g,""));t[a]=kHe(r)}),t};var FB=function(s,t,n,r){function a(i){return i instanceof n?i:new n(function(l){l(i)})}return new(n||(n=Promise))(function(i,l){function o(u){try{d(r.next(u))}catch(h){l(h)}}function c(u){try{d(r.throw(u))}catch(h){l(h)}}function d(u){u.done?i(u.value):a(u.value).then(o,c)}d((r=r.apply(s,t||[])).next())})};const Bze=s=>s.msg||s.message||s.error_description||s.error||JSON.stringify(s),jNs=(s,t,n)=>FB(void 0,void 0,void 0,function*(){const r=yield wNs();s instanceof r&&!(n!=null&&n.noResolveJson)?s.json().then(a=>{t(new bNs(Bze(a),s.status||500))}).catch(a=>{t(new NHe(Bze(a),a))}):t(new NHe(Bze(s),s))}),NNs=(s,t,n,r)=>{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),r&&(a.body=JSON.stringify(r)),Object.assign(Object.assign({},a),n))};function Pae(s,t,n,r,a,i){return FB(this,void 0,void 0,function*(){return new Promise((l,o)=>{s(n,NNs(t,r,a,i)).then(c=>{if(!c.ok)throw c;return r!=null&&r.noResolveJson?c:c.json()}).then(c=>l(c)).catch(c=>jNs(c,o,r))})})}function _Ee(s,t,n,r){return FB(this,void 0,void 0,function*(){return Pae(s,"GET",t,n,r)})}function uP(s,t,n,r,a){return FB(this,void 0,void 0,function*(){return Pae(s,"POST",t,r,a,n)})}function kNs(s,t,n,r,a){return FB(this,void 0,void 0,function*(){return Pae(s,"PUT",t,r,a,n)})}function SNs(s,t,n,r){return FB(this,void 0,void 0,function*(){return Pae(s,"HEAD",t,Object.assign(Object.assign({},n),{noResolveJson:!0}),r)})}function BFt(s,t,n,r,a){return FB(this,void 0,void 0,function*(){return Pae(s,"DELETE",t,r,a,n)})}var tw=function(s,t,n,r){function a(i){return i instanceof n?i:new n(function(l){l(i)})}return new(n||(n=Promise))(function(i,l){function o(u){try{d(r.next(u))}catch(h){l(h)}}function c(u){try{d(r.throw(u))}catch(h){l(h)}}function d(u){u.done?i(u.value):a(u.value).then(o,c)}d((r=r.apply(s,t||[])).next())})};const CNs={limit:100,offset:0,sortBy:{column:"name",order:"asc"}},yxt={cacheControl:"3600",contentType:"text/plain;charset=UTF-8",upsert:!1};class ANs{constructor(t,n={},r,a){this.url=t,this.headers=n,this.bucketId=r,this.fetch=zFt(a)}uploadOrUpdate(t,n,r,a){return tw(this,void 0,void 0,function*(){try{let i;const l=Object.assign(Object.assign({},yxt),a);let o=Object.assign(Object.assign({},this.headers),t==="POST"&&{"x-upsert":String(l.upsert)});const c=l.metadata;typeof Blob<"u"&&r instanceof Blob?(i=new FormData,i.append("cacheControl",l.cacheControl),c&&i.append("metadata",this.encodeMetadata(c)),i.append("",r)):typeof FormData<"u"&&r instanceof FormData?(i=r,i.append("cacheControl",l.cacheControl),c&&i.append("metadata",this.encodeMetadata(c))):(i=r,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(n),u=this._getFinalPath(d),h=yield this.fetch(`${this.url}/object/${u}`,Object.assign({method:t,body:i,headers:o},l!=null&&l.duplex?{duplex:l.duplex}:{})),m=yield h.json();return h.ok?{data:{path:d,id:m.Id,fullPath:m.Key},error:null}:{data:null,error:m}}catch(i){if(cv(i))return{data:null,error:i};throw i}})}upload(t,n,r){return tw(this,void 0,void 0,function*(){return this.uploadOrUpdate("POST",t,n,r)})}uploadToSignedUrl(t,n,r,a){return tw(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",n);try{let c;const d=Object.assign({upsert:yxt.upsert},a),u=Object.assign(Object.assign({},this.headers),{"x-upsert":String(d.upsert)});typeof Blob<"u"&&r instanceof Blob?(c=new FormData,c.append("cacheControl",d.cacheControl),c.append("",r)):typeof FormData<"u"&&r instanceof FormData?(c=r,c.append("cacheControl",d.cacheControl)):(c=r,u["cache-control"]=`max-age=${d.cacheControl}`,u["content-type"]=d.contentType);const h=yield this.fetch(o.toString(),{method:"PUT",body:c,headers:u}),m=yield h.json();return h.ok?{data:{path:i,fullPath:m.Key},error:null}:{data:null,error:m}}catch(c){if(cv(c))return{data:null,error:c};throw c}})}createSignedUploadUrl(t,n){return tw(this,void 0,void 0,function*(){try{let r=this._getFinalPath(t);const a=Object.assign({},this.headers);n!=null&&n.upsert&&(a["x-upsert"]="true");const i=yield uP(this.fetch,`${this.url}/object/upload/sign/${r}`,{},{headers:a}),l=new URL(this.url+i.url),o=l.searchParams.get("token");if(!o)throw new Oet("No token returned by API");return{data:{signedUrl:l.toString(),path:t,token:o},error:null}}catch(r){if(cv(r))return{data:null,error:r};throw r}})}update(t,n,r){return tw(this,void 0,void 0,function*(){return this.uploadOrUpdate("PUT",t,n,r)})}move(t,n,r){return tw(this,void 0,void 0,function*(){try{return{data:yield uP(this.fetch,`${this.url}/object/move`,{bucketId:this.bucketId,sourceKey:t,destinationKey:n,destinationBucket:r==null?void 0:r.destinationBucket},{headers:this.headers}),error:null}}catch(a){if(cv(a))return{data:null,error:a};throw a}})}copy(t,n,r){return tw(this,void 0,void 0,function*(){try{return{data:{path:(yield uP(this.fetch,`${this.url}/object/copy`,{bucketId:this.bucketId,sourceKey:t,destinationKey:n,destinationBucket:r==null?void 0:r.destinationBucket},{headers:this.headers})).Key},error:null}}catch(a){if(cv(a))return{data:null,error:a};throw a}})}createSignedUrl(t,n,r){return tw(this,void 0,void 0,function*(){try{let a=this._getFinalPath(t),i=yield uP(this.fetch,`${this.url}/object/sign/${a}`,Object.assign({expiresIn:n},r!=null&&r.transform?{transform:r.transform}:{}),{headers:this.headers});const l=r!=null&&r.download?`&download=${r.download===!0?"":r.download}`:"";return i={signedUrl:encodeURI(`${this.url}${i.signedURL}${l}`)},{data:i,error:null}}catch(a){if(cv(a))return{data:null,error:a};throw a}})}createSignedUrls(t,n,r){return tw(this,void 0,void 0,function*(){try{const a=yield uP(this.fetch,`${this.url}/object/sign/${this.bucketId}`,{expiresIn:n,paths:t},{headers:this.headers}),i=r!=null&&r.download?`&download=${r.download===!0?"":r.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(cv(a))return{data:null,error:a};throw a}})}download(t,n){return tw(this,void 0,void 0,function*(){const a=typeof(n==null?void 0:n.transform)<"u"?"render/image/authenticated":"object",i=this.transformOptsToQueryString((n==null?void 0:n.transform)||{}),l=i?`?${i}`:"";try{const o=this._getFinalPath(t);return{data:yield(yield _Ee(this.fetch,`${this.url}/${a}/${o}${l}`,{headers:this.headers,noResolveJson:!0})).blob(),error:null}}catch(o){if(cv(o))return{data:null,error:o};throw o}})}info(t){return tw(this,void 0,void 0,function*(){const n=this._getFinalPath(t);try{const r=yield _Ee(this.fetch,`${this.url}/object/info/${n}`,{headers:this.headers});return{data:kHe(r),error:null}}catch(r){if(cv(r))return{data:null,error:r};throw r}})}exists(t){return tw(this,void 0,void 0,function*(){const n=this._getFinalPath(t);try{return yield SNs(this.fetch,`${this.url}/object/${n}`,{headers:this.headers}),{data:!0,error:null}}catch(r){if(cv(r)&&r instanceof NHe){const a=r.originalError;if([400,404].includes(a==null?void 0:a.status))return{data:!1,error:r}}throw r}})}getPublicUrl(t,n){const r=this._getFinalPath(t),a=[],i=n!=null&&n.download?`download=${n.download===!0?"":n.download}`:"";i!==""&&a.push(i);const o=typeof(n==null?void 0:n.transform)<"u"?"render/image":"object",c=this.transformOptsToQueryString((n==null?void 0:n.transform)||{});c!==""&&a.push(c);let d=a.join("&");return d!==""&&(d=`?${d}`),{data:{publicUrl:encodeURI(`${this.url}/${o}/public/${r}${d}`)}}}remove(t){return tw(this,void 0,void 0,function*(){try{return{data:yield BFt(this.fetch,`${this.url}/object/${this.bucketId}`,{prefixes:t},{headers:this.headers}),error:null}}catch(n){if(cv(n))return{data:null,error:n};throw n}})}list(t,n,r){return tw(this,void 0,void 0,function*(){try{const a=Object.assign(Object.assign(Object.assign({},CNs),n),{prefix:t||""});return{data:yield uP(this.fetch,`${this.url}/object/list/${this.bucketId}`,a,{headers:this.headers},r),error:null}}catch(a){if(cv(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 n=[];return t.width&&n.push(`width=${t.width}`),t.height&&n.push(`height=${t.height}`),t.resize&&n.push(`resize=${t.resize}`),t.format&&n.push(`format=${t.format}`),t.quality&&n.push(`quality=${t.quality}`),n.join("&")}}const ENs="2.7.1",TNs={"X-Client-Info":`storage-js/${ENs}`};var x$=function(s,t,n,r){function a(i){return i instanceof n?i:new n(function(l){l(i)})}return new(n||(n=Promise))(function(i,l){function o(u){try{d(r.next(u))}catch(h){l(h)}}function c(u){try{d(r.throw(u))}catch(h){l(h)}}function d(u){u.done?i(u.value):a(u.value).then(o,c)}d((r=r.apply(s,t||[])).next())})};class MNs{constructor(t,n={},r){this.url=t,this.headers=Object.assign(Object.assign({},TNs),n),this.fetch=zFt(r)}listBuckets(){return x$(this,void 0,void 0,function*(){try{return{data:yield _Ee(this.fetch,`${this.url}/bucket`,{headers:this.headers}),error:null}}catch(t){if(cv(t))return{data:null,error:t};throw t}})}getBucket(t){return x$(this,void 0,void 0,function*(){try{return{data:yield _Ee(this.fetch,`${this.url}/bucket/${t}`,{headers:this.headers}),error:null}}catch(n){if(cv(n))return{data:null,error:n};throw n}})}createBucket(t,n={public:!1}){return x$(this,void 0,void 0,function*(){try{return{data:yield uP(this.fetch,`${this.url}/bucket`,{id:t,name:t,public:n.public,file_size_limit:n.fileSizeLimit,allowed_mime_types:n.allowedMimeTypes},{headers:this.headers}),error:null}}catch(r){if(cv(r))return{data:null,error:r};throw r}})}updateBucket(t,n){return x$(this,void 0,void 0,function*(){try{return{data:yield kNs(this.fetch,`${this.url}/bucket/${t}`,{id:t,name:t,public:n.public,file_size_limit:n.fileSizeLimit,allowed_mime_types:n.allowedMimeTypes},{headers:this.headers}),error:null}}catch(r){if(cv(r))return{data:null,error:r};throw r}})}emptyBucket(t){return x$(this,void 0,void 0,function*(){try{return{data:yield uP(this.fetch,`${this.url}/bucket/${t}/empty`,{},{headers:this.headers}),error:null}}catch(n){if(cv(n))return{data:null,error:n};throw n}})}deleteBucket(t){return x$(this,void 0,void 0,function*(){try{return{data:yield BFt(this.fetch,`${this.url}/bucket/${t}`,{},{headers:this.headers}),error:null}}catch(n){if(cv(n))return{data:null,error:n};throw n}})}}class PNs extends MNs{constructor(t,n={},r){super(t,n,r)}from(t){return new ANs(this.url,this.headers,t,this.fetch)}}const INs="2.49.10";let oQ="";typeof Deno<"u"?oQ="deno":typeof document<"u"?oQ="web":typeof navigator<"u"&&navigator.product==="ReactNative"?oQ="react-native":oQ="node";const LNs={"X-Client-Info":`supabase-js-${oQ}/${INs}`},RNs={headers:LNs},DNs={schema:"public"},FNs={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},ONs={};var zNs=function(s,t,n,r){function a(i){return i instanceof n?i:new n(function(l){l(i)})}return new(n||(n=Promise))(function(i,l){function o(u){try{d(r.next(u))}catch(h){l(h)}}function c(u){try{d(r.throw(u))}catch(h){l(h)}}function d(u){u.done?i(u.value):a(u.value).then(o,c)}d((r=r.apply(s,t||[])).next())})};const BNs=s=>{let t;return s?t=s:typeof fetch>"u"?t=NFt:t=fetch,(...n)=>t(...n)},$Ns=()=>typeof Headers>"u"?kFt:Headers,UNs=(s,t,n)=>{const r=BNs(n),a=$Ns();return(i,l)=>zNs(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}`),r(i,Object.assign(Object.assign({},l),{headers:d}))})};var qNs=function(s,t,n,r){function a(i){return i instanceof n?i:new n(function(l){l(i)})}return new(n||(n=Promise))(function(i,l){function o(u){try{d(r.next(u))}catch(h){l(h)}}function c(u){try{d(r.throw(u))}catch(h){l(h)}}function d(u){u.done?i(u.value):a(u.value).then(o,c)}d((r=r.apply(s,t||[])).next())})};function VNs(s){return s.endsWith("/")?s:s+"/"}function HNs(s,t){var n,r;const{db:a,auth:i,realtime:l,global:o}=s,{db:c,auth:d,realtime:u,global:h}=t,m={db:Object.assign(Object.assign({},c),a),auth:Object.assign(Object.assign({},d),i),realtime:Object.assign(Object.assign({},u),l),global:Object.assign(Object.assign(Object.assign({},h),o),{headers:Object.assign(Object.assign({},(n=h==null?void 0:h.headers)!==null&&n!==void 0?n:{}),(r=o==null?void 0:o.headers)!==null&&r!==void 0?r:{})}),accessToken:()=>qNs(this,void 0,void 0,function*(){return""})};return s.accessToken?m.accessToken=s.accessToken:delete m.accessToken,m}const $Ft="2.69.1",gU=30*1e3,SHe=3,$ze=SHe*gU,GNs="http://localhost:9999",WNs="supabase.auth.token",KNs={"X-Client-Info":`gotrue-js/${$Ft}`},CHe="X-Supabase-Api-Version",UFt={"2024-01-01":{timestamp:Date.parse("2024-01-01T00:00:00.0Z"),name:"2024-01-01"}},YNs=/^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}$|[a-z0-9_-]{2}$)$/i,ZNs=6e5;class zet extends Error{constructor(t,n,r){super(t),this.__isAuthError=!0,this.name="AuthError",this.status=n,this.code=r}}function Dd(s){return typeof s=="object"&&s!==null&&"__isAuthError"in s}class XNs extends zet{constructor(t,n,r){super(t,n,r),this.name="AuthApiError",this.status=n,this.code=r}}function QNs(s){return Dd(s)&&s.name==="AuthApiError"}class qFt extends zet{constructor(t,n){super(t),this.name="AuthUnknownError",this.originalError=n}}class n6 extends zet{constructor(t,n,r,a){super(t,r,a),this.name=n,this.status=r}}class VM extends n6{constructor(){super("Auth session missing!","AuthSessionMissingError",400,void 0)}}function JNs(s){return Dd(s)&&s.name==="AuthSessionMissingError"}class Uze extends n6{constructor(){super("Auth session or user missing","AuthInvalidTokenResponseError",500,void 0)}}class Nce extends n6{constructor(t){super(t,"AuthInvalidCredentialsError",400,void 0)}}class kce extends n6{constructor(t,n=null){super(t,"AuthImplicitGrantRedirectError",500,void 0),this.details=null,this.details=n}toJSON(){return{name:this.name,message:this.message,status:this.status,details:this.details}}}function eks(s){return Dd(s)&&s.name==="AuthImplicitGrantRedirectError"}class vxt extends n6{constructor(t,n=null){super(t,"AuthPKCEGrantCodeExchangeError",500,void 0),this.details=null,this.details=n}toJSON(){return{name:this.name,message:this.message,status:this.status,details:this.details}}}class AHe extends n6{constructor(t,n){super(t,"AuthRetryableFetchError",n,void 0)}}function qze(s){return Dd(s)&&s.name==="AuthRetryableFetchError"}class bxt extends n6{constructor(t,n,r){super(t,"AuthWeakPasswordError",n,"weak_password"),this.reasons=r}}class fee extends n6{constructor(t){super(t,"AuthInvalidJwtError",400,"invalid_jwt")}}const _xt="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_".split(""),wxt=` \r=`.split(""),tks=(()=>{const s=new Array(128);for(let t=0;t-1)for(t.queue=t.queue<<6|r,t.queuedBits+=6;t.queuedBits>=8;)n(t.queue>>t.queuedBits-8&255),t.queuedBits-=8;else{if(r===-2)return;throw new Error(`Invalid Base64-URL character "${String.fromCharCode(s)}"`)}}function jxt(s){const t=[],n=l=>{t.push(String.fromCodePoint(l))},r={utf8seq:0,codepoint:0},a={queue:0,queuedBits:0},i=l=>{rks(l,r,n)};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 nks(s,t){for(let n=0;n55295&&r<=56319){const a=(r-55296)*1024&65535;r=(s.charCodeAt(n+1)-56320&65535|a)+65536,n+=1}sks(r,t)}}function rks(s,t,n){if(t.utf8seq===0){if(s<=127){n(s);return}for(let r=1;r<6;r+=1)if(!(s>>7-r&1)){t.utf8seq=r;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&&n(t.codepoint)}}function aks(s){const t=[],n={queue:0,queuedBits:0},r=a=>{t.push(a)};for(let a=0;at.push(n)),new Uint8Array(t)}function oks(s){return Math.round(Date.now()/1e3)+s}function lks(){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 y5=()=>typeof window<"u"&&typeof document<"u",fR={tested:!1,writable:!1},pee=()=>{if(!y5())return!1;try{if(typeof globalThis.localStorage!="object")return!1}catch{return!1}if(fR.tested)return fR.writable;const s=`lswt-${Math.random()}${Math.random()}`;try{globalThis.localStorage.setItem(s,s),globalThis.localStorage.removeItem(s),fR.tested=!0,fR.writable=!0}catch{fR.tested=!0,fR.writable=!1}return fR.writable};function cks(s){const t={},n=new URL(s);if(n.hash&&n.hash[0]==="#")try{new URLSearchParams(n.hash.substring(1)).forEach((a,i)=>{t[i]=a})}catch{}return n.searchParams.forEach((r,a)=>{t[a]=r}),t}const HFt=s=>{let t;return s?t=s:typeof fetch>"u"?t=(...n)=>ri(async()=>{const{default:r}=await Promise.resolve().then(()=>tK);return{default:r}},void 0).then(({default:r})=>r(...n)):t=fetch,(...n)=>t(...n)},dks=s=>typeof s=="object"&&s!==null&&"status"in s&&"ok"in s&&"json"in s&&typeof s.json=="function",GFt=async(s,t,n)=>{await s.setItem(t,JSON.stringify(n))},Sce=async(s,t)=>{const n=await s.getItem(t);if(!n)return null;try{return JSON.parse(n)}catch{return n}},Cce=async(s,t)=>{await s.removeItem(t)};class fLe{constructor(){this.promise=new fLe.promiseConstructor((t,n)=>{this.resolve=t,this.reject=n})}}fLe.promiseConstructor=Promise;function Vze(s){const t=s.split(".");if(t.length!==3)throw new fee("Invalid JWT structure");for(let r=0;r{setTimeout(()=>t(null),s)})}function hks(s,t){return new Promise((r,a)=>{(async()=>{for(let i=0;i<1/0;i++)try{const l=await s(i);if(!t(i,null,l)){r(l);return}}catch(l){if(!t(i,l)){a(l);return}}})()})}function mks(s){return("0"+s.toString(16)).substr(-2)}function fks(){const t=new Uint32Array(56);if(typeof crypto>"u"){const n="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~",r=n.length;let a="";for(let i=0;i<56;i++)a+=n.charAt(Math.floor(Math.random()*r));return a}return crypto.getRandomValues(t),Array.from(t,mks).join("")}async function pks(s){const n=new TextEncoder().encode(s),r=await crypto.subtle.digest("SHA-256",n),a=new Uint8Array(r);return Array.from(a).map(i=>String.fromCharCode(i)).join("")}async function gks(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 n=await pks(s);return btoa(n).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function y$(s,t,n=!1){const r=fks();let a=r;n&&(a+="/PASSWORD_RECOVERY"),await GFt(s,`${t}-code-verifier`,a);const i=await gks(r);return[i,r===i?"plain":"s256"]}const xks=/^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i;function yks(s){const t=s.headers.get(CHe);if(!t||!t.match(xks))return null;try{return new Date(`${t}T00:00:00.0Z`)}catch{return null}}function vks(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 bks(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 _ks=function(s,t){var n={};for(var r in s)Object.prototype.hasOwnProperty.call(s,r)&&t.indexOf(r)<0&&(n[r]=s[r]);if(s!=null&&typeof Object.getOwnPropertySymbols=="function")for(var a=0,r=Object.getOwnPropertySymbols(s);as.msg||s.message||s.error_description||s.error||JSON.stringify(s),wks=[502,503,504];async function Nxt(s){var t;if(!dks(s))throw new AHe(RO(s),0);if(wks.includes(s.status))throw new AHe(RO(s),s.status);let n;try{n=await s.json()}catch(i){throw new qFt(RO(i),i)}let r;const a=yks(s);if(a&&a.getTime()>=UFt["2024-01-01"].timestamp&&typeof n=="object"&&n&&typeof n.code=="string"?r=n.code:typeof n=="object"&&n&&typeof n.error_code=="string"&&(r=n.error_code),r){if(r==="weak_password")throw new bxt(RO(n),s.status,((t=n.weak_password)===null||t===void 0?void 0:t.reasons)||[]);if(r==="session_not_found")throw new VM}else if(typeof n=="object"&&n&&typeof n.weak_password=="object"&&n.weak_password&&Array.isArray(n.weak_password.reasons)&&n.weak_password.reasons.length&&n.weak_password.reasons.reduce((i,l)=>i&&typeof l=="string",!0))throw new bxt(RO(n),s.status,n.weak_password.reasons);throw new XNs(RO(n),s.status||500,r)}const jks=(s,t,n,r)=>{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(r),Object.assign(Object.assign({},a),n))};async function Du(s,t,n,r){var a;const i=Object.assign({},r==null?void 0:r.headers);i[CHe]||(i[CHe]=UFt["2024-01-01"].name),r!=null&&r.jwt&&(i.Authorization=`Bearer ${r.jwt}`);const l=(a=r==null?void 0:r.query)!==null&&a!==void 0?a:{};r!=null&&r.redirectTo&&(l.redirect_to=r.redirectTo);const o=Object.keys(l).length?"?"+new URLSearchParams(l).toString():"",c=await Nks(s,t,n+o,{headers:i,noResolveJson:r==null?void 0:r.noResolveJson},{},r==null?void 0:r.body);return r!=null&&r.xform?r==null?void 0:r.xform(c):{data:Object.assign({},c),error:null}}async function Nks(s,t,n,r,a,i){const l=jks(t,r,a,i);let o;try{o=await s(n,Object.assign({},l))}catch(c){throw console.error(c),new AHe(RO(c),0)}if(o.ok||await Nxt(o),r!=null&&r.noResolveJson)return o;try{return await o.json()}catch(c){await Nxt(c)}}function HM(s){var t;let n=null;Aks(s)&&(n=Object.assign({},s),s.expires_at||(n.expires_at=oks(s.expires_in)));const r=(t=s.user)!==null&&t!==void 0?t:s;return{data:{session:n,user:r},error:null}}function kxt(s){const t=HM(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((n,r)=>n&&typeof r=="string",!0)&&(t.data.weak_password=s.weak_password),t}function CP(s){var t;return{data:{user:(t=s.user)!==null&&t!==void 0?t:s},error:null}}function kks(s){return{data:s,error:null}}function Sks(s){const{action_link:t,email_otp:n,hashed_token:r,redirect_to:a,verification_type:i}=s,l=_ks(s,["action_link","email_otp","hashed_token","redirect_to","verification_type"]),o={action_link:t,email_otp:n,hashed_token:r,redirect_to:a,verification_type:i},c=Object.assign({},l);return{data:{properties:o,user:c},error:null}}function Cks(s){return s}function Aks(s){return s.access_token&&s.refresh_token&&s.expires_in}var Eks=function(s,t){var n={};for(var r in s)Object.prototype.hasOwnProperty.call(s,r)&&t.indexOf(r)<0&&(n[r]=s[r]);if(s!=null&&typeof Object.getOwnPropertySymbols=="function")for(var a=0,r=Object.getOwnPropertySymbols(s);a0&&(f.forEach(g=>{const x=parseInt(g.split(";")[0].split("=")[1].substring(0,1)),y=JSON.parse(g.split(";")[1].split("=")[1]);d[`${y}Page`]=x}),d.total=parseInt(m)),{data:Object.assign(Object.assign({},h),d),error:null}}catch(d){if(Dd(d))return{data:{users:[]},error:d};throw d}}async getUserById(t){try{return await Du(this.fetch,"GET",`${this.url}/admin/users/${t}`,{headers:this.headers,xform:CP})}catch(n){if(Dd(n))return{data:{user:null},error:n};throw n}}async updateUserById(t,n){try{return await Du(this.fetch,"PUT",`${this.url}/admin/users/${t}`,{body:n,headers:this.headers,xform:CP})}catch(r){if(Dd(r))return{data:{user:null},error:r};throw r}}async deleteUser(t,n=!1){try{return await Du(this.fetch,"DELETE",`${this.url}/admin/users/${t}`,{headers:this.headers,body:{should_soft_delete:n},xform:CP})}catch(r){if(Dd(r))return{data:{user:null},error:r};throw r}}async _listFactors(t){try{const{data:n,error:r}=await Du(this.fetch,"GET",`${this.url}/admin/users/${t.userId}/factors`,{headers:this.headers,xform:a=>({data:{factors:a},error:null})});return{data:n,error:r}}catch(n){if(Dd(n))return{data:null,error:n};throw n}}async _deleteFactor(t){try{return{data:await Du(this.fetch,"DELETE",`${this.url}/admin/users/${t.userId}/factors/${t.id}`,{headers:this.headers}),error:null}}catch(n){if(Dd(n))return{data:null,error:n};throw n}}}const Mks={getItem:s=>pee()?globalThis.localStorage.getItem(s):null,setItem:(s,t)=>{pee()&&globalThis.localStorage.setItem(s,t)},removeItem:s=>{pee()&&globalThis.localStorage.removeItem(s)}};function Sxt(s={}){return{getItem:t=>s[t]||null,setItem:(t,n)=>{s[t]=n},removeItem:t=>{delete s[t]}}}function Pks(){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 v$={debug:!!(globalThis&&pee()&&globalThis.localStorage&&globalThis.localStorage.getItem("supabase.gotrue-js.locks.debug")==="true")};class WFt extends Error{constructor(t){super(t),this.isAcquireTimeout=!0}}class Iks extends WFt{}async function Lks(s,t,n){v$.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquire lock",s,t);const r=new globalThis.AbortController;return t>0&&setTimeout(()=>{r.abort(),v$.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:r.signal},async a=>{if(a){v$.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquired",s,a.name);try{return await n()}finally{v$.debug&&console.log("@supabase/gotrue-js: navigatorLock: released",s,a.name)}}else{if(t===0)throw v$.debug&&console.log("@supabase/gotrue-js: navigatorLock: not immediately available",s),new Iks(`Acquiring an exclusive Navigator LockManager lock "${s}" immediately failed`);if(v$.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 n()}}))}Pks();const Rks={url:GNs,storageKey:WNs,autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:KNs,flowType:"implicit",debug:!1,hasCustomAuthorizationHeader:!1};async function Cxt(s,t,n){return await n()}class Xte{constructor(t){var n,r;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=Xte.nextInstanceID,Xte.nextInstanceID+=1,this.instanceID>0&&y5()&&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({},Rks),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 Tks({url:a.url,headers:a.headers,fetch:a.fetch}),this.url=a.url,this.headers=a.headers,this.fetch=HFt(a.fetch),this.lock=a.lock||Cxt,this.detectSessionInUrl=a.detectSessionInUrl,this.flowType=a.flowType,this.hasCustomAuthorizationHeader=a.hasCustomAuthorizationHeader,a.lock?this.lock=a.lock:y5()&&(!((n=globalThis==null?void 0:globalThis.navigator)===null||n===void 0)&&n.locks)?this.lock=Lks:this.lock=Cxt,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:pee()?this.storage=Mks:(this.memoryStorage={},this.storage=Sxt(this.memoryStorage)):(this.memoryStorage={},this.storage=Sxt(this.memoryStorage)),y5()&&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)}(r=this.broadcastChannel)===null||r===void 0||r.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} (${$Ft}) ${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 n=cks(window.location.href);let r="none";if(this._isImplicitGrantCallback(n)?r="implicit":await this._isPKCECallback(n)&&(r="pkce"),y5()&&this.detectSessionInUrl&&r!=="none"){const{data:a,error:i}=await this._getSessionFromURL(n,r);if(i){if(this._debug("#_initialize()","error detecting session from URL",i),eks(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(n){return Dd(n)?{error:n}:{error:new qFt("Unexpected error during initialization",n)}}finally{await this._handleVisibilityChange(),this._debug("#_initialize()","end")}}async signInAnonymously(t){var n,r,a;try{const i=await Du(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{data:(r=(n=t==null?void 0:t.options)===null||n===void 0?void 0:n.data)!==null&&r!==void 0?r:{},gotrue_meta_security:{captcha_token:(a=t==null?void 0:t.options)===null||a===void 0?void 0:a.captchaToken}},xform:HM}),{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(Dd(i))return{data:{user:null,session:null},error:i};throw i}}async signUp(t){var n,r,a;try{let i;if("email"in t){const{email:u,password:h,options:m}=t;let f=null,g=null;this.flowType==="pkce"&&([f,g]=await y$(this.storage,this.storageKey)),i=await Du(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,redirectTo:m==null?void 0:m.emailRedirectTo,body:{email:u,password:h,data:(n=m==null?void 0:m.data)!==null&&n!==void 0?n:{},gotrue_meta_security:{captcha_token:m==null?void 0:m.captchaToken},code_challenge:f,code_challenge_method:g},xform:HM})}else if("phone"in t){const{phone:u,password:h,options:m}=t;i=await Du(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{phone:u,password:h,data:(r=m==null?void 0:m.data)!==null&&r!==void 0?r:{},channel:(a=m==null?void 0:m.channel)!==null&&a!==void 0?a:"sms",gotrue_meta_security:{captcha_token:m==null?void 0:m.captchaToken}},xform:HM})}else throw new Nce("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(Dd(i))return{data:{user:null,session:null},error:i};throw i}}async signInWithPassword(t){try{let n;if("email"in t){const{email:i,password:l,options:o}=t;n=await Du(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:kxt})}else if("phone"in t){const{phone:i,password:l,options:o}=t;n=await Du(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:kxt})}else throw new Nce("You must provide either an email or phone number and a password");const{data:r,error:a}=n;return a?{data:{user:null,session:null},error:a}:!r||!r.session||!r.user?{data:{user:null,session:null},error:new Uze}:(r.session&&(await this._saveSession(r.session),await this._notifyAllSubscribers("SIGNED_IN",r.session)),{data:Object.assign({user:r.user,session:r.session},r.weak_password?{weakPassword:r.weak_password}:null),error:a})}catch(n){if(Dd(n))return{data:{user:null,session:null},error:n};throw n}}async signInWithOAuth(t){var n,r,a,i;return await this._handleProviderSignIn(t.provider,{redirectTo:(n=t.options)===null||n===void 0?void 0:n.redirectTo,scopes:(r=t.options)===null||r===void 0?void 0:r.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 n=await Sce(this.storage,`${this.storageKey}-code-verifier`),[r,a]=(n??"").split("/");try{const{data:i,error:l}=await Du(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:t,code_verifier:r},xform:HM});if(await Cce(this.storage,`${this.storageKey}-code-verifier`),l)throw l;return!i||!i.session||!i.user?{data:{user:null,session:null,redirectType:null},error:new Uze}:(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(Dd(i))return{data:{user:null,session:null,redirectType:null},error:i};throw i}}async signInWithIdToken(t){try{const{options:n,provider:r,token:a,access_token:i,nonce:l}=t,o=await Du(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,body:{provider:r,id_token:a,access_token:i,nonce:l,gotrue_meta_security:{captcha_token:n==null?void 0:n.captchaToken}},xform:HM}),{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 Uze}:(c.session&&(await this._saveSession(c.session),await this._notifyAllSubscribers("SIGNED_IN",c.session)),{data:c,error:d})}catch(n){if(Dd(n))return{data:{user:null,session:null},error:n};throw n}}async signInWithOtp(t){var n,r,a,i,l;try{if("email"in t){const{email:o,options:c}=t;let d=null,u=null;this.flowType==="pkce"&&([d,u]=await y$(this.storage,this.storageKey));const{error:h}=await Du(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{email:o,data:(n=c==null?void 0:c.data)!==null&&n!==void 0?n:{},create_user:(r=c==null?void 0:c.shouldCreateUser)!==null&&r!==void 0?r:!0,gotrue_meta_security:{captcha_token:c==null?void 0:c.captchaToken},code_challenge:d,code_challenge_method:u},redirectTo:c==null?void 0:c.emailRedirectTo});return{data:{user:null,session:null},error:h}}if("phone"in t){const{phone:o,options:c}=t,{data:d,error:u}=await Du(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:u}}throw new Nce("You must provide either an email or phone number.")}catch(o){if(Dd(o))return{data:{user:null,session:null},error:o};throw o}}async verifyOtp(t){var n,r;try{let a,i;"options"in t&&(a=(n=t.options)===null||n===void 0?void 0:n.redirectTo,i=(r=t.options)===null||r===void 0?void 0:r.captchaToken);const{data:l,error:o}=await Du(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},t),{gotrue_meta_security:{captcha_token:i}}),redirectTo:a,xform:HM});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(Dd(a))return{data:{user:null,session:null},error:a};throw a}}async signInWithSSO(t){var n,r,a;try{let i=null,l=null;return this.flowType==="pkce"&&([i,l]=await y$(this.storage,this.storageKey)),await Du(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:(r=(n=t.options)===null||n===void 0?void 0:n.redirectTo)!==null&&r!==void 0?r: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:kks})}catch(i){if(Dd(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:n},error:r}=t;if(r)throw r;if(!n)throw new VM;const{error:a}=await Du(this.fetch,"GET",`${this.url}/reauthenticate`,{headers:this.headers,jwt:n.access_token});return{data:{user:null,session:null},error:a}})}catch(t){if(Dd(t))return{data:{user:null,session:null},error:t};throw t}}async resend(t){try{const n=`${this.url}/resend`;if("email"in t){const{email:r,type:a,options:i}=t,{error:l}=await Du(this.fetch,"POST",n,{headers:this.headers,body:{email:r,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:r,type:a,options:i}=t,{data:l,error:o}=await Du(this.fetch,"POST",n,{headers:this.headers,body:{phone:r,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 Nce("You must provide either an email or phone number and a type")}catch(n){if(Dd(n))return{data:{user:null,session:null},error:n};throw n}}async getSession(){return await this.initializePromise,await this._acquireLock(-1,async()=>this._useSession(async n=>n))}async _acquireLock(t,n){this._debug("#_acquireLock","begin",t);try{if(this.lockAcquired){const r=this.pendingInLock.length?this.pendingInLock[this.pendingInLock.length-1]:Promise.resolve(),a=(async()=>(await r,await n()))();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 r=n();for(this.pendingInLock.push((async()=>{try{await r}catch{}})()),await r;this.pendingInLock.length;){const a=[...this.pendingInLock];await Promise.all(a),this.pendingInLock.splice(0,a.length)}return await r}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 n=await this.__loadSession();return await t(n)}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 n=await Sce(this.storage,this.storageKey);if(this._debug("#getSession()","session from storage",n),n!==null&&(this._isValidSession(n)?t=n:(this._debug("#getSession()","session from storage is not valid"),await this._removeSession())),!t)return{data:{session:null},error:null};const r=t.expires_at?t.expires_at*1e3-Date.now()<$ze:!1;if(this._debug("#__loadSession()",`session has${r?"":" not"} expired`,"expires_at",t.expires_at),!r){if(this.storage.isServer){let l=this.suppressGetSessionWarning;t=new Proxy(t,{get:(c,d,u)=>(!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,u))})}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 Du(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:t,xform:CP}):await this._useSession(async n=>{var r,a,i;const{data:l,error:o}=n;if(o)throw o;return!(!((r=l.session)===null||r===void 0)&&r.access_token)&&!this.hasCustomAuthorizationHeader?{data:{user:null},error:new VM}:await Du(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:CP})})}catch(n){if(Dd(n))return JNs(n)&&(await this._removeSession(),await Cce(this.storage,`${this.storageKey}-code-verifier`)),{data:{user:null},error:n};throw n}}async updateUser(t,n={}){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._updateUser(t,n))}async _updateUser(t,n={}){try{return await this._useSession(async r=>{const{data:a,error:i}=r;if(i)throw i;if(!a.session)throw new VM;const l=a.session;let o=null,c=null;this.flowType==="pkce"&&t.email!=null&&([o,c]=await y$(this.storage,this.storageKey));const{data:d,error:u}=await Du(this.fetch,"PUT",`${this.url}/user`,{headers:this.headers,redirectTo:n==null?void 0:n.emailRedirectTo,body:Object.assign(Object.assign({},t),{code_challenge:o,code_challenge_method:c}),jwt:l.access_token,xform:CP});if(u)throw u;return l.user=d.user,await this._saveSession(l),await this._notifyAllSubscribers("USER_UPDATED",l),{data:{user:l.user},error:null}})}catch(r){if(Dd(r))return{data:{user:null},error:r};throw r}}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 VM;const n=Date.now()/1e3;let r=n,a=!0,i=null;const{payload:l}=Vze(t.access_token);if(l.exp&&(r=l.exp,a=r<=n),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:r-n,expires_at:r},await this._saveSession(i),await this._notifyAllSubscribers("SIGNED_IN",i)}return{data:{user:i.user,session:i},error:null}}catch(n){if(Dd(n))return{data:{session:null,user:null},error:n};throw n}}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 n=>{var r;if(!t){const{data:l,error:o}=n;if(o)throw o;t=(r=l.session)!==null&&r!==void 0?r:void 0}if(!(t!=null&&t.refresh_token))throw new VM;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(n){if(Dd(n))return{data:{user:null,session:null},error:n};throw n}}async _getSessionFromURL(t,n){try{if(!y5())throw new kce("No browser detected.");if(t.error||t.error_description||t.error_code)throw new kce(t.error_description||"Error in URL with unspecified error_description",{error:t.error||"unspecified_error",code:t.error_code||"unspecified_code"});switch(n){case"implicit":if(this.flowType==="pkce")throw new vxt("Not a valid PKCE flow url.");break;case"pkce":if(this.flowType==="implicit")throw new kce("Not a valid implicit grant flow url.");break;default:}if(n==="pkce"){if(this._debug("#_initialize()","begin","is PKCE flow",!0),!t.code)throw new vxt("No code detected.");const{data:b,error:w}=await this._exchangeCodeForSession(t.code);if(w)throw w;const S=new URL(window.location.href);return S.searchParams.delete("code"),window.history.replaceState(window.history.state,"",S.toString()),{data:{session:b.session,redirectType:null},error:null}}const{provider_token:r,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 kce("No session defined in URL");const u=Math.round(Date.now()/1e3),h=parseInt(o);let m=u+h;c&&(m=parseInt(c));const f=m-u;f*1e3<=gU&&console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${f}s, should have been closer to ${h}s`);const g=m-h;u-g>=120?console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",g,m,u):u-g<0&&console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clock for skew",g,m,u);const{data:x,error:y}=await this._getUser(i);if(y)throw y;const v={provider_token:r,provider_refresh_token:a,access_token:i,expires_in:h,expires_at:m,refresh_token:l,token_type:d,user:x.user};return window.location.hash="",this._debug("#_getSessionFromURL()","clearing window.location.hash"),{data:{session:v,redirectType:t.type},error:null}}catch(r){if(Dd(r))return{data:{session:null,redirectType:null},error:r};throw r}}_isImplicitGrantCallback(t){return!!(t.access_token||t.error_description)}async _isPKCECallback(t){const n=await Sce(this.storage,`${this.storageKey}-code-verifier`);return!!(t.code&&n)}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 n=>{var r;const{data:a,error:i}=n;if(i)return{error:i};const l=(r=a.session)===null||r===void 0?void 0:r.access_token;if(l){const{error:o}=await this.admin.signOut(l,t);if(o&&!(QNs(o)&&(o.status===404||o.status===401||o.status===403)))return{error:o}}return t!=="others"&&(await this._removeSession(),await Cce(this.storage,`${this.storageKey}-code-verifier`)),{error:null}})}onAuthStateChange(t){const n=lks(),r={id:n,callback:t,unsubscribe:()=>{this._debug("#unsubscribe()","state change callback with id removed",n),this.stateChangeEmitters.delete(n)}};return this._debug("#onAuthStateChange()","registered callback with id",n),this.stateChangeEmitters.set(n,r),(async()=>(await this.initializePromise,await this._acquireLock(-1,async()=>{this._emitInitialSession(n)})))(),{data:{subscription:r}}}async _emitInitialSession(t){return await this._useSession(async n=>{var r,a;try{const{data:{session:i},error:l}=n;if(l)throw l;await((r=this.stateChangeEmitters.get(t))===null||r===void 0?void 0:r.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,n={}){let r=null,a=null;this.flowType==="pkce"&&([r,a]=await y$(this.storage,this.storageKey,!0));try{return await Du(this.fetch,"POST",`${this.url}/recover`,{body:{email:t,code_challenge:r,code_challenge_method:a,gotrue_meta_security:{captcha_token:n.captchaToken}},headers:this.headers,redirectTo:n.redirectTo})}catch(i){if(Dd(i))return{data:null,error:i};throw i}}async getUserIdentities(){var t;try{const{data:n,error:r}=await this.getUser();if(r)throw r;return{data:{identities:(t=n.user.identities)!==null&&t!==void 0?t:[]},error:null}}catch(n){if(Dd(n))return{data:null,error:n};throw n}}async linkIdentity(t){var n;try{const{data:r,error:a}=await this._useSession(async i=>{var l,o,c,d,u;const{data:h,error:m}=i;if(m)throw m;const f=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 Du(this.fetch,"GET",f,{headers:this.headers,jwt:(u=(d=h.session)===null||d===void 0?void 0:d.access_token)!==null&&u!==void 0?u:void 0})});if(a)throw a;return y5()&&!(!((n=t.options)===null||n===void 0)&&n.skipBrowserRedirect)&&window.location.assign(r==null?void 0:r.url),{data:{provider:t.provider,url:r==null?void 0:r.url},error:null}}catch(r){if(Dd(r))return{data:{provider:t.provider,url:null},error:r};throw r}}async unlinkIdentity(t){try{return await this._useSession(async n=>{var r,a;const{data:i,error:l}=n;if(l)throw l;return await Du(this.fetch,"DELETE",`${this.url}/user/identities/${t.identity_id}`,{headers:this.headers,jwt:(a=(r=i.session)===null||r===void 0?void 0:r.access_token)!==null&&a!==void 0?a:void 0})})}catch(n){if(Dd(n))return{data:null,error:n};throw n}}async _refreshAccessToken(t){const n=`#_refreshAccessToken(${t.substring(0,5)}...)`;this._debug(n,"begin");try{const r=Date.now();return await hks(async a=>(a>0&&await uks(200*Math.pow(2,a-1)),this._debug(n,"refreshing attempt",a),await Du(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:t},headers:this.headers,xform:HM})),(a,i)=>{const l=200*Math.pow(2,a);return i&&qze(i)&&Date.now()+l-r{try{await o.callback(t,n)}catch(c){i.push(c)}});if(await Promise.all(l),i.length>0){for(let o=0;othis._autoRefreshTokenTick(),gU);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 n=>{const{data:{session:r}}=n;if(!r||!r.refresh_token||!r.expires_at){this._debug("#_autoRefreshTokenTick()","no session");return}const a=Math.floor((r.expires_at*1e3-t)/gU);this._debug("#_autoRefreshTokenTick()",`access token expires in ${a} ticks, a tick lasts ${gU}ms, refresh threshold is ${SHe} ticks`),a<=SHe&&await this._callRefreshToken(r.refresh_token)})}catch(n){console.error("Auto refresh tick failed with error. This is likely a transient error.",n)}}finally{this._debug("#_autoRefreshTokenTick()","end")}})}catch(t){if(t.isAcquireTimeout||t instanceof WFt)this._debug("auto refresh token tick lock not available");else throw t}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!y5()||!(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 n=`#_onVisibilityChanged(${t})`;this._debug(n,"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(n,"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,n,r){const a=[`provider=${encodeURIComponent(n)}`];if(r!=null&&r.redirectTo&&a.push(`redirect_to=${encodeURIComponent(r.redirectTo)}`),r!=null&&r.scopes&&a.push(`scopes=${encodeURIComponent(r.scopes)}`),this.flowType==="pkce"){const[i,l]=await y$(this.storage,this.storageKey),o=new URLSearchParams({code_challenge:`${encodeURIComponent(i)}`,code_challenge_method:`${encodeURIComponent(l)}`});a.push(o.toString())}if(r!=null&&r.queryParams){const i=new URLSearchParams(r.queryParams);a.push(i.toString())}return r!=null&&r.skipBrowserRedirect&&a.push(`skip_http_redirect=${r.skipBrowserRedirect}`),`${t}?${a.join("&")}`}async _unenroll(t){try{return await this._useSession(async n=>{var r;const{data:a,error:i}=n;return i?{data:null,error:i}:await Du(this.fetch,"DELETE",`${this.url}/factors/${t.factorId}`,{headers:this.headers,jwt:(r=a==null?void 0:a.session)===null||r===void 0?void 0:r.access_token})})}catch(n){if(Dd(n))return{data:null,error:n};throw n}}async _enroll(t){try{return await this._useSession(async n=>{var r,a;const{data:i,error:l}=n;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 Du(this.fetch,"POST",`${this.url}/factors`,{body:o,headers:this.headers,jwt:(r=i==null?void 0:i.session)===null||r===void 0?void 0:r.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(n){if(Dd(n))return{data:null,error:n};throw n}}async _verify(t){return this._acquireLock(-1,async()=>{try{return await this._useSession(async n=>{var r;const{data:a,error:i}=n;if(i)return{data:null,error:i};const{data:l,error:o}=await Du(this.fetch,"POST",`${this.url}/factors/${t.factorId}/verify`,{body:{code:t.code,challenge_id:t.challengeId},headers:this.headers,jwt:(r=a==null?void 0:a.session)===null||r===void 0?void 0:r.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(n){if(Dd(n))return{data:null,error:n};throw n}})}async _challenge(t){return this._acquireLock(-1,async()=>{try{return await this._useSession(async n=>{var r;const{data:a,error:i}=n;return i?{data:null,error:i}:await Du(this.fetch,"POST",`${this.url}/factors/${t.factorId}/challenge`,{body:{channel:t.channel},headers:this.headers,jwt:(r=a==null?void 0:a.session)===null||r===void 0?void 0:r.access_token})})}catch(n){if(Dd(n))return{data:null,error:n};throw n}})}async _challengeAndVerify(t){const{data:n,error:r}=await this._challenge({factorId:t.factorId});return r?{data:null,error:r}:await this._verify({factorId:t.factorId,challengeId:n.id,code:t.code})}async _listFactors(){const{data:{user:t},error:n}=await this.getUser();if(n)return{data:null,error:n};const r=(t==null?void 0:t.factors)||[],a=r.filter(l=>l.factor_type==="totp"&&l.status==="verified"),i=r.filter(l=>l.factor_type==="phone"&&l.status==="verified");return{data:{all:r,totp:a,phone:i},error:null}}async _getAuthenticatorAssuranceLevel(){return this._acquireLock(-1,async()=>await this._useSession(async t=>{var n,r;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}=Vze(a.access_token);let o=null;l.aal&&(o=l.aal);let c=o;((r=(n=a.user.factors)===null||n===void 0?void 0:n.filter(h=>h.status==="verified"))!==null&&r!==void 0?r:[]).length>0&&(c="aal2");const u=l.amr||[];return{data:{currentLevel:o,nextLevel:c,currentAuthenticationMethods:u},error:null}}))}async fetchJwk(t,n={keys:[]}){let r=n.keys.find(l=>l.kid===t);if(r||(r=this.jwks.keys.find(l=>l.kid===t),r&&this.jwks_cached_at+ZNs>Date.now()))return r;const{data:a,error:i}=await Du(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 fee("JWKS is empty");if(this.jwks=a,this.jwks_cached_at=Date.now(),r=a.keys.find(l=>l.kid===t),!r)throw new fee("No matching signing key found in JWKS");return r}async getClaims(t,n={keys:[]}){try{let r=t;if(!r){const{data:f,error:g}=await this.getSession();if(g||!f.session)return{data:null,error:g};r=f.session.access_token}const{header:a,payload:i,signature:l,raw:{header:o,payload:c}}=Vze(r);if(vks(i.exp),!a.kid||a.alg==="HS256"||!("crypto"in globalThis&&"subtle"in globalThis.crypto)){const{error:f}=await this.getUser(r);if(f)throw f;return{data:{claims:i,header:a,signature:l},error:null}}const d=bks(a.alg),u=await this.fetchJwk(a.kid,n),h=await crypto.subtle.importKey("jwk",u,d,!0,["verify"]);if(!await crypto.subtle.verify(d,h,l,iks(`${o}.${c}`)))throw new fee("Invalid JWT signature");return{data:{claims:i,header:a,signature:l},error:null}}catch(r){if(Dd(r))return{data:null,error:r};throw r}}}Xte.nextInstanceID=0;const Dks=Xte;class Fks extends Dks{constructor(t){super(t)}}var Oks=function(s,t,n,r){function a(i){return i instanceof n?i:new n(function(l){l(i)})}return new(n||(n=Promise))(function(i,l){function o(u){try{d(r.next(u))}catch(h){l(h)}}function c(u){try{d(r.throw(u))}catch(h){l(h)}}function d(u){u.done?i(u.value):a(u.value).then(o,c)}d((r=r.apply(s,t||[])).next())})};class zks{constructor(t,n,r){var a,i,l;if(this.supabaseUrl=t,this.supabaseKey=n,!t)throw new Error("supabaseUrl is required.");if(!n)throw new Error("supabaseKey is required.");const o=VNs(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`,u={db:DNs,realtime:ONs,auth:Object.assign(Object.assign({},FNs),{storageKey:d}),global:RNs},h=HNs(r??{},u);this.storageKey=(a=h.auth.storageKey)!==null&&a!==void 0?a:"",this.headers=(i=h.global.headers)!==null&&i!==void 0?i:{},h.accessToken?(this.accessToken=h.accessToken,this.auth=new Proxy({},{get:(m,f)=>{throw new Error(`@supabase/supabase-js: Supabase Client is configured with the accessToken option, accessing supabase.auth.${String(f)} is not possible`)}})):this.auth=this._initSupabaseAuthClient((l=h.auth)!==null&&l!==void 0?l:{},this.headers,h.global.fetch),this.fetch=UNs(n,this._getAccessToken.bind(this),h.global.fetch),this.realtime=this._initRealtimeClient(Object.assign({headers:this.headers,accessToken:this._getAccessToken.bind(this)},h.realtime)),this.rest=new aNs(new URL("rest/v1",c).href,{headers:this.headers,schema:h.db.schema,fetch:this.fetch}),h.accessToken||this._listenForAuthEvents()}get functions(){return new R2s(this.functionsUrl.href,{headers:this.headers,customFetch:this.fetch})}get storage(){return new PNs(this.storageUrl.href,this.headers,this.fetch)}from(t){return this.rest.from(t)}schema(t){return this.rest.schema(t)}rpc(t,n={},r={}){return this.rest.rpc(t,n,r)}channel(t,n={config:{}}){return this.realtime.channel(t,n)}getChannels(){return this.realtime.getChannels()}removeChannel(t){return this.realtime.removeChannel(t)}removeAllChannels(){return this.realtime.removeAllChannels()}_getAccessToken(){var t,n;return Oks(this,void 0,void 0,function*(){if(this.accessToken)return yield this.accessToken();const{data:r}=yield this.auth.getSession();return(n=(t=r.session)===null||t===void 0?void 0:t.access_token)!==null&&n!==void 0?n:null})}_initSupabaseAuthClient({autoRefreshToken:t,persistSession:n,detectSessionInUrl:r,storage:a,storageKey:i,flowType:l,lock:o,debug:c},d,u){const h={Authorization:`Bearer ${this.supabaseKey}`,apikey:`${this.supabaseKey}`};return new Fks({url:this.authUrl.href,headers:Object.assign(Object.assign({},h),d),storageKey:i,autoRefreshToken:t,persistSession:n,detectSessionInUrl:r,storage:a,flowType:l,lock:o,debug:c,fetch:u,hasCustomAuthorizationHeader:"Authorization"in this.headers})}_initRealtimeClient(t){return new yNs(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((n,r)=>{this._handleTokenChanged(n,"CLIENT",r==null?void 0:r.access_token)})}_handleTokenChanged(t,n,r){(t==="TOKEN_REFRESHED"||t==="SIGNED_IN")&&this.changedAccessToken!==r?this.changedAccessToken=r:t==="SIGNED_OUT"&&(this.realtime.setAuth(),n=="STORAGE"&&this.auth.signOut(),this.changedAccessToken=void 0)}}const Bks=(s,t,n)=>new zks(s,t,n);function $ks(){var y,v;if(typeof window>"u")return;const s=location.hostname,n=["lovableproject.com","lovableproject-dev.com","lovable.app","gpt-eng.com","gptengineer.run"].some(b=>s===b||s.endsWith("."+b)),r="[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}",a=n?((y=s.match(new RegExp("^(?:id-preview(?:-[a-z0-9]+)?|project)--("+r+")(?:-dev)?(?=\\.|$)","i")))==null?void 0:y[1])??((v=s.match(new RegExp("^("+r+")(?=[.-])","i")))==null?void 0:v[1]):void 0,i=window.parent&&window.parent!==window;if(!a||!i)return localStorage;const l=s.endsWith(".lovableproject-dev.com")||s.endsWith(".gpt-eng.com"),o=l?/^https:\/\/([a-z0-9-]+\.)*(lovable\.dev|gptengineer\.app)$|^http:\/\/localhost:3000$/:/^https:\/\/([a-z0-9-]+\.)*(lovable\.dev|gptengineer\.app)$/,c=location.ancestorOrigins&&location.ancestorOrigins[0]||(document.referrer?new URL(document.referrer).origin:""),d=c&&o.test(c)?[c]:l?["https://lovable.dev","http://localhost:3000"]:["https://lovable.dev"],u="lovable-preview-auth:result",h=2e3,m=()=>Math.random().toString(36).slice(2)+Date.now().toString(36),f=(b,w,S)=>new Promise(C=>{const E=m();let I=!1,P;const R=U=>{I||(I=!0,clearTimeout(P),window.removeEventListener("message",D),C(U))},D=U=>{if(d.indexOf(U.origin)<0)return;const W=U.data;W&&W.type===u&&W.requestId===E&&R(W)};window.addEventListener("message",D);const O={type:b,requestId:E,projectId:a,key:w};S!==void 0&&(O.value=S);for(const U of d)window.parent.postMessage(O,U);P=setTimeout(()=>R(null),h)});let g=!0;const x=250;return{getItem:async b=>{let w=await f("lovable-preview-auth:get",b);return!w&&g&&(await new Promise(S=>setTimeout(S,x)),w=await f("lovable-preview-auth:get",b)),g=!1,w&&w.ok&&typeof w.value=="string"?w.value===""?(localStorage.removeItem(b),null):w.value:localStorage.getItem(b)},setItem:(b,w)=>(localStorage.setItem(b,w),f("lovable-preview-auth:set",b,w).then(S=>{S&&S.ok&&typeof S.value=="string"&&localStorage.getItem(b)===w&&(S.value===""?localStorage.removeItem(b):localStorage.setItem(b,S.value))})),removeItem:b=>(localStorage.removeItem(b),f("lovable-preview-auth:remove",b).then(()=>{}))}}const Uks="https://relzejiswnotikjgvjhz.supabase.co",qks="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InJlbHplamlzd25vdGlramd2amh6Iiwicm9sZSI6ImFub24iLCJpYXQiOjE3NjE5NTAzNDQsImV4cCI6MjA3NzUyNjM0NH0.dzIkIr_oFSbFE3oWS0ktIr83iKHHkZxt40Gc7SpC_mM",q=Bks(Uks,qks,{auth:{storage:$ks(),persistSession:!0,autoRefreshToken:!0}}),Vks=Object.freeze(Object.defineProperty({__proto__:null,supabase:q},Symbol.toStringTag,{value:"Module"})),KFt=j.createContext(void 0),Hks=({children:s})=>{const[t,n]=j.useState(null),[r,a]=j.useState(null),[i,l]=j.useState(!0),[o,c]=j.useState(!0),[d,u]=j.useState(!1),[h,m]=j.useState(!1),[f,g]=j.useState(!1),[x,y]=j.useState(null),[v,b]=j.useState([]),[w,S]=j.useState(null),C=j.useRef(null),E=j.useRef(!1),I=j.useRef(!1),P=Qn(),R=()=>{u(!1),m(!1),g(!1),y(null),b([]),S(null),C.current=null,E.current=!1},D=async V=>{if(E.current&&C.current===V||I.current)return;I.current=!0,c(!0);const G=window.setTimeout(()=>{console.warn("Role check timeout reached — unblocking UI."),I.current=!1,c(!1)},8e3);try{console.log("Checking roles via RPC for user:",V);const[{data:Y,error:X},{data:ae,error:ie},{data:ne,error:te}]=await Promise.all([q.rpc("has_role",{_user_id:V,_role:"admin"}),q.rpc("has_role",{_user_id:V,_role:"brokerage_manager"}),q.rpc("has_role",{_user_id:V,_role:"coach"})]);if(X||ie)console.error("Role RPC errors:",{isAdminError:X,isBrokerError:ie,isCoachError:te}),u(!1),m(!1),g(!1);else{const _e=!!Y,he=!!ae,ue=!!ne;console.log("RPC roles result:",{adminValue:_e,brokerValue:he,coachValue:ue}),u(_e),m(he),g(ue)}C.current=V,E.current=!0,window.clearTimeout(G),c(!1);const{data:J,error:ce}=await q.from("profiles").select("brokerage_id, is_paused, paused_reason").eq("id",V).single();if(!ce&&(J!=null&&J.is_paused)){const _e=J.paused_reason;try{sessionStorage.setItem("accountPausedReason",_e||"")}catch{}await q.auth.signOut(),R(),P("/auth?paused=1",{replace:!0});return}if(y(!ce&&J?J.brokerage_id:null),ae){console.log("Fetching managed brokerages for user:",V);const{data:_e,error:he}=await q.from("brokerage_manager_assignments").select("brokerage_id").eq("user_id",V);if(console.log("Managed brokerage assignments result:",{assignments:_e,assignmentsError:he}),he||!_e){console.error("Error fetching managed brokerage assignments:",he),b([]);return}const ue=Array.from(new Set(_e.map(Le=>Le.brokerage_id).filter(Boolean)));if(ue.length===0){b([]);return}const{data:ve,error:Ee}=await q.from("brokerages").select("id, name").in("id",ue);if(console.log("Managed brokerages details result:",{brokeragesData:ve,brokeragesError:Ee}),Ee||!ve){console.error("Error fetching managed brokerages details:",Ee),b([]);return}const Se=ve.map(Le=>({id:Le.id,name:Le.name})).sort((Le,Fe)=>ue.indexOf(Le.id)-ue.indexOf(Fe.id));console.log("Parsed managed brokerages:",Se),b(Se),Se.length>0&&S(Le=>Le??Se[0].id)}else console.log("User is not a brokerage manager, skipping managed brokerages fetch"),b([]);C.current=V,E.current=!0}catch(Y){console.error("Unexpected error in checkRoles:",Y),R()}finally{window.clearTimeout(G),I.current=!1,c(!1)}};j.useEffect(()=>{let V=!0,G=!1;const Y=()=>{!V||G||(G=!0,l(!1))},{data:{subscription:X}}=q.auth.onAuthStateChange((ie,ne)=>{console.log("Auth event:",ie),V&&(a(ne),n((ne==null?void 0:ne.user)??null),Y(),ie==="PASSWORD_RECOVERY"&&(console.log("Password recovery detected, redirecting to profile"),setTimeout(()=>{P("/profile?reset=true")},100)),ne!=null&&ne.user?(!E.current||C.current!==ne.user.id)&&setTimeout(()=>{D(ne.user.id)},0):(R(),c(!1)))}),ae=window.setTimeout(()=>{console.warn("Auth initialization timeout reached. Continuing without blocking UI."),Y()},8e3);return()=>{V=!1,window.clearTimeout(ae),X.unsubscribe()}},[]);const O=async(V,G)=>{var ie;const Y=(V||"").trim().toLowerCase(),{data:X,error:ae}=await q.auth.signInWithPassword({email:Y,password:G});if(ae)throw re.error(/invalid login credentials/i.test(ae.message)?`That email and password don't match an account. Check the email address, or use "Forgot password" to set a new password.`:ae.message),ae;if((ie=X.user)!=null&&ie.id){const{data:ne}=await q.from("profiles").select("is_paused, paused_reason").eq("id",X.user.id).maybeSingle();if(ne!=null&&ne.is_paused){const te=ne.paused_reason||"";try{sessionStorage.setItem("accountPausedReason",te)}catch{}await q.auth.signOut(),R(),n(null),a(null);const J=new Error(te?`Your account is paused. ${te}`:"Your account is paused. Please contact LevelUp support to reactivate it.");throw J.name="AccountPaused",re.error(J.message),J}}re.success("Welcome back!")},U=async(V,G,Y)=>{var te;const X="https://dashboard.relevelup.com/dashboard",ae=localStorage.getItem("levelup_referral_code")||null,{data:ie,error:ne}=await q.auth.signUp({email:V,password:G,options:{emailRedirectTo:X,data:{name:Y,referred_by_code:ae}}});if(ne)throw re.error(ne.message),ne;if(ae&&((te=ie.user)!=null&&te.id))try{await q.from("profiles").update({referred_by_code:ae}).eq("id",ie.user.id),localStorage.removeItem("levelup_referral_code")}catch(J){console.warn("Failed to attach referral code to profile",J)}re.success("Account created! Welcome to LevelUp."),P("/dashboard")},W=async()=>{try{const{data:{session:V}}=await q.auth.getSession();if(V){const{error:G}=await q.auth.signOut();G?G.message==="Auth session missing!"?console.warn("Sign out warning (ignored):",G.message):(console.error("Sign out error:",G),re.error(G.message)):re.success("Signed out successfully")}else console.log("No active session found, redirecting to auth");n(null),a(null),u(!1),m(!1),y(null),b([]),S(null),P("/auth")}catch(V){console.error("Unexpected sign out error:",V),P("/auth")}};return e.jsx(KFt.Provider,{value:{user:t,session:r,loading:i,rolesLoading:o,signIn:O,signUp:U,signOut:W,isAdmin:d,isBrokerageManager:h,isCoach:f,brokerageId:x,managedBrokerages:v,selectedBrokerageId:w,setSelectedBrokerageId:S},children:s})},vs=()=>{const s=j.useContext(KFt);if(s===void 0)throw new Error("useAuth must be used within an AuthProvider");return s},YFt=j.createContext({onlineUsers:[],totalOnline:0}),Gks=3*60*1e3,Wks=45*1e3,Kks=30*1e3,Yks=({children:s})=>{const{user:t,brokerageId:n,isAdmin:r}=vs(),[a,i]=j.useState([]),l=j.useRef(new Date().toISOString()),o=j.useCallback(async()=>{t&&await q.from("user_presence").upsert({user_id:t.id,last_seen_at:new Date().toISOString(),online_since:l.current,current_path:window.location.pathname},{onConflict:"user_id"})},[t==null?void 0:t.id]),c=j.useCallback(async()=>{if(!t)return;const u=new Date(Date.now()-Gks).toISOString(),{data:h}=await q.from("user_presence").select("user_id, last_seen_at, online_since").gte("last_seen_at",u).order("last_seen_at",{ascending:!1}).limit(200);if(!(h!=null&&h.length)){i([]);return}const m=h.map(x=>x.user_id),{data:f}=await q.from("profiles").select("id, name, email, avatar_url, brokerage_id").in("id",m),g=new Map((f||[]).map(x=>[x.id,x]));i(h.map(x=>{var v;const y=g.get(x.user_id);return{id:x.user_id,name:(y==null?void 0:y.name)||((v=y==null?void 0:y.email)==null?void 0:v.split("@")[0])||"Member",avatarUrl:(y==null?void 0:y.avatar_url)||void 0,brokerageId:(y==null?void 0:y.brokerage_id)||void 0,onlineSince:x.online_since||x.last_seen_at}}))},[t==null?void 0:t.id]);j.useEffect(()=>{if(!t){i([]);return}l.current=new Date().toISOString();let u=!1;const h=async()=>{u||(await o(),await c())};h();const m=window.setInterval(()=>{o()},Wks),f=window.setInterval(()=>{c()},Kks),g=()=>{document.visibilityState==="visible"&&h()};return document.addEventListener("visibilitychange",g),()=>{u=!0,window.clearInterval(m),window.clearInterval(f),document.removeEventListener("visibilitychange",g)}},[t==null?void 0:t.id,o,c]);const d=a.filter(u=>!!(u.id===(t==null?void 0:t.id)||r||n&&u.brokerageId===n||!n&&!u.brokerageId));return e.jsx(YFt.Provider,{value:{onlineUsers:d,totalOnline:d.length},children:s})},ZFt=()=>j.useContext(YFt),XFt=j.createContext(void 0),pR="levelup_admin_session",bM="levelup_impersonation",Hze="levelup_impersonation_return",Zks=({children:s})=>{const[t,n]=j.useState(!1),[r,a]=j.useState(null),[i,l]=j.useState(!1);j.useEffect(()=>{const d=sessionStorage.getItem(bM);if(d)try{const u=JSON.parse(d);n(!0),a(u)}catch{sessionStorage.removeItem(bM)}},[]);const o=async(d,u)=>{l(!0);try{const{data:{session:h}}=await q.auth.getSession();if(!h)return re.error("No active session found"),!1;const m={access_token:h.access_token,refresh_token:h.refresh_token};sessionStorage.setItem(pR,JSON.stringify(m)),u&&sessionStorage.setItem(Hze,u);const f=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/impersonate-user",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${h.access_token}`},body:JSON.stringify({targetUserId:d})}),g=await f.json();if(!f.ok)throw new Error(g.error||"Failed to impersonate user");const x={id:g.targetUser.id,name:g.targetUser.name,email:g.targetUser.email};if(sessionStorage.setItem(bM,JSON.stringify(x)),g.method==="session"){const{error:y}=await q.auth.setSession({access_token:g.access_token,refresh_token:g.refresh_token});if(y)throw console.error("Set session error:",y),sessionStorage.removeItem(pR),sessionStorage.removeItem(bM),new Error("Failed to establish impersonation session")}else{const y=g.type||"recovery",{error:v}=await q.auth.verifyOtp({token_hash:g.token_hash,type:y});if(v)throw console.error("Verify OTP error:",v),sessionStorage.removeItem(pR),sessionStorage.removeItem(bM),new Error("Failed to establish impersonation session")}return n(!0),a(x),re.success(`Now viewing as ${x.name}`),window.location.href="/dashboard",!0}catch(h){return console.error("Impersonation error:",h),re.error(h.message||"Failed to impersonate user"),sessionStorage.removeItem(pR),sessionStorage.removeItem(bM),!1}finally{l(!1)}},c=async()=>{l(!0);try{const d=sessionStorage.getItem(pR);if(!d){await q.auth.signOut(),window.location.href="/auth";return}const u=JSON.parse(d);await q.auth.signOut();const{error:h}=await q.auth.setSession({access_token:u.access_token,refresh_token:u.refresh_token});if(sessionStorage.removeItem(pR),sessionStorage.removeItem(bM),h){console.error("Failed to restore admin session:",h),re.error("Admin session expired, please sign in again"),window.location.href="/auth";return}n(!1),a(null),re.success("Returned to your account");const m=sessionStorage.getItem(Hze)||"/admin/members";sessionStorage.removeItem(Hze),window.location.href=m}catch(d){console.error("Stop impersonation error:",d),re.error("Failed to restore admin session"),sessionStorage.removeItem(pR),sessionStorage.removeItem(bM),window.location.href="/auth"}finally{l(!1)}};return e.jsx(XFt.Provider,{value:{isImpersonating:t,impersonatedUser:r,startImpersonation:o,stopImpersonation:c,isLoading:i},children:s})},pLe=()=>{const s=j.useContext(XFt);if(s===void 0)throw new Error("useImpersonation must be used within an ImpersonationProvider");return s},Xks=()=>{const{isImpersonating:s,impersonatedUser:t,stopImpersonation:n,isLoading:r}=pLe();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(wl,{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($,{size:"sm",variant:"secondary",onClick:n,disabled:r,className:"bg-amber-100 hover:bg-amber-200 text-amber-950 border-0",children:r?e.jsx(kt,{className:"h-4 w-4 animate-spin"}):e.jsxs(e.Fragment,{children:[e.jsx(gr,{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"})]})})]})})},QFt=j.createContext(void 0),b$="levelup_acting_as",Ace="levelup_acting_as_self",Qks=({children:s})=>{const{user:t}=vs(),[n,r]=j.useState(!1),[a,i]=j.useState([]),[l,o]=j.useState(null),[c,d]=j.useState({}),[u,h]=j.useState(!0),[m,f]=j.useState(()=>sessionStorage.getItem(Ace)==="true");j.useEffect(()=>{if(!(t!=null&&t.id)){r(!1),i([]),o(null),d({}),h(!1);return}(async()=>{h(!0);try{const{data:w}=await q.rpc("has_role",{_user_id:t.id,_role:"assistant"});if(!w){r(!1),i([]),o(null),d({}),h(!1);return}r(!0);const{data:S,error:C}=await q.from("agent_assistant_assignments").select("agent_id, permissions").eq("assistant_id",t.id);if(C||!S||S.length===0){i([]),h(!1);return}const E=S.map(R=>R.agent_id),{data:I}=await q.from("profiles").select("id, name, email, avatar_url").in("id",E),P=(I||[]).map(R=>({id:R.id,name:R.name||R.email||"Unknown",email:R.email||"",avatar_url:R.avatar_url}));if(i(P),sessionStorage.getItem(Ace)==="true")f(!0),o(null),d({});else{const R=sessionStorage.getItem(b$);if(R){const D=P.find(O=>O.id===R);if(D){o(D);const O=S.find(U=>U.agent_id===R);d((O==null?void 0:O.permissions)||{})}else if(P.length>0){o(P[0]);const O=S.find(U=>U.agent_id===P[0].id);d((O==null?void 0:O.permissions)||{}),sessionStorage.setItem(b$,P[0].id)}}else if(P.length>0){o(P[0]);const D=S.find(O=>O.agent_id===P[0].id);d((D==null?void 0:D.permissions)||{}),sessionStorage.setItem(b$,P[0].id)}}}catch(w){console.error("Error loading assistant data:",w)}finally{h(!1)}})()},[t==null?void 0:t.id]);const g=b=>{o(b),f(!1),sessionStorage.removeItem(Ace),b?(sessionStorage.setItem(b$,b.id),q.from("agent_assistant_assignments").select("permissions").eq("assistant_id",(t==null?void 0:t.id)||"").eq("agent_id",b.id).single().then(({data:w})=>{d((w==null?void 0:w.permissions)||{})})):(sessionStorage.removeItem(b$),d({}))},x=()=>{f(!0),o(null),d({}),sessionStorage.setItem(Ace,"true"),sessionStorage.removeItem(b$)},y=b=>!n||m?!0:c[b]===!0,v=n&&l&&!m?l.id:(t==null?void 0:t.id)||null;return e.jsx(QFt.Provider,{value:{isAssistant:n,assignedAgents:a,actingAsAgent:l,setActingAsAgent:g,effectiveUserId:v,permissions:c,hasPermission:y,isLoading:u,isActingAsSelf:m,setActingAsSelf:x},children:s})},Iae=()=>{const s=j.useContext(QFt);if(s===void 0)throw new Error("useActingAs must be used within an ActingAsProvider");return s},Sa=()=>{const{effectiveUserId:s}=Iae();return s};var Jks=Object.defineProperty,hT=(s,t)=>Jks(s,"name",{value:t,configurable:!0}),JFt="Avatar",[eSs,Wkr]=tp(JFt),tSs=[0,()=>{}],[sSs,eOt]=eSs(JFt),tOt=j.forwardRef(hT(function(t,n){const{__scopeAvatar:r,...a}=t,[i,l]=j.useState("idle"),[o,c]=aOt();return e.jsx(sSs,{scope:r,imageLoadingStatus:i,setImageLoadingStatus:l,imageCount:o,setImageCount:c,children:e.jsx(Ei.span,{...a,ref:n})})},"Avatar")),nSs="AvatarImage",sOt=j.forwardRef(hT(function(t,n){const{__scopeAvatar:r,src:a,onLoadingStatusChange:i,...l}=t,o=eOt(nSs,r);o.setImageCount;const c=rOt(a,{referrerPolicy:l.referrerPolicy,crossOrigin:l.crossOrigin,loadingStatus:o.imageLoadingStatus,setLoadingStatus:o.setImageLoadingStatus}),d=Yp(h=>{i==null||i(h)}),u=j.useRef(c);return Ef(()=>{const h=u.current;u.current=c,c!==h&&d(c)},[c,d]),c==="loaded"?e.jsx(Ei.img,{...l,ref:n,src:a}):null},"AvatarImage")),rSs="AvatarFallback",nOt=j.forwardRef(hT(function(t,n){const{__scopeAvatar:r,delayMs:a,...i}=t,l=eOt(rSs,r),[o,c]=j.useState(a===void 0);return j.useEffect(()=>{if(a!==void 0){const d=window.setTimeout(()=>c(!0),a);return()=>window.clearTimeout(d)}},[a]),o&&l.imageLoadingStatus!=="loaded"?e.jsx(Ei.span,{...i,ref:n}):null},"AvatarFallback"));function rOt(s,{loadingStatus:t,setLoadingStatus:n,referrerPolicy:r,crossOrigin:a}){return Ef(()=>{if(!s){n("error");return}const i=new window.Image,l=hT(c=>{const d=c.currentTarget;n(EHe(d))},"handleLoad"),o=hT(()=>n("error"),"handleError");return i.addEventListener("load",l),i.addEventListener("error",o),r&&(i.referrerPolicy=r),i.crossOrigin=a??null,i.src=s,n(EHe(i)),()=>{i.removeEventListener("load",l),i.removeEventListener("error",o),n("idle")}},[s,a,r,n]),t}hT(rOt,"useImageLoadingStatus");function EHe(s){return s.complete?s.naturalWidth>0?"loaded":"error":"loading"}hT(EHe,"getImageLoadingStatus");function aOt(){return tSs}hT(aOt,"useImageCount");function aSs(s){}hT(aSs,"useUpdateImageCount");const Oa=j.forwardRef(({className:s,...t},n)=>e.jsx(tOt,{ref:n,className:Pt("relative flex h-10 w-10 shrink-0 overflow-hidden rounded-full",s),...t}));Oa.displayName=tOt.displayName;const Li=j.forwardRef(({className:s,...t},n)=>e.jsx(sOt,{ref:n,className:Pt("aspect-square h-full w-full",s),...t}));Li.displayName=sOt.displayName;const za=j.forwardRef(({className:s,...t},n)=>e.jsx(nOt,{ref:n,className:Pt("flex h-full w-full items-center justify-center rounded-full bg-muted",s),...t}));za.displayName=nOt.displayName;const iSs=DB("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 Be({className:s,variant:t,...n}){return e.jsx("div",{className:Pt(iSs({variant:t}),s),...n})}var oSs=Object.defineProperty,lSs=(s,t)=>oSs(s,"name",{value:t,configurable:!0}),cSs=j.createContext(void 0);function l3(s){const t=j.useContext(cSs);return s||t||"ltr"}lSs(l3,"useDirection");var dSs=Object.defineProperty,Bet=(s,t)=>dSs(s,"name",{value:t,configurable:!0}),Gze=!1;function iOt(){const[s,t]=j.useState(Gze);return j.useEffect(()=>{Gze||(Gze=!0,t(!0))},[]),s}Bet(iOt,"useIsHydrated");var oOt=MB[" useSyncExternalStore ".trim().toString()];function lOt(){return()=>{}}Bet(lOt,"subscribe");function cOt(){return oOt(lOt,()=>!0,()=>!1)}Bet(cOt,"useIsHydratedModern");var uSs=typeof oOt=="function"?cOt:iOt,hSs=Object.defineProperty,OB=(s,t)=>hSs(s,"name",{value:t,configurable:!0}),Wze="rovingFocusGroup.onEntryFocus",mSs={bubbles:!1,cancelable:!0},gLe="RovingFocusGroup",[THe,dOt,fSs]=LB(gLe),[pSs,r6]=tp(gLe,[fSs]),[gSs,xSs]=pSs(gLe),ySs=j.forwardRef(OB(function(t,n){return e.jsx(THe.Provider,{scope:t.__scopeRovingFocusGroup,children:e.jsx(THe.Slot,{scope:t.__scopeRovingFocusGroup,children:e.jsx(vSs,{...t,ref:n})})})},"RovingFocusGroup")),vSs=j.forwardRef(OB(function(t,n){const{__scopeRovingFocusGroup:r,orientation:a,loop:i=!1,dir:l,currentTabStopId:o,defaultCurrentTabStopId:c,onCurrentTabStopIdChange:d,onEntryFocus:u,preventScrollOnEntryFocus:h=!1,...m}=t,f=j.useRef(null),g=Vo(n,f),x=l3(l),[y,v]=fy({prop:o,defaultProp:c??null,onChange:d,caller:gLe}),[b,w]=j.useState(!1),S=Yp(u),C=dOt(r),E=j.useRef(!1),[I,P]=j.useState(0);return j.useEffect(()=>{const R=f.current;if(R)return R.addEventListener(Wze,S),()=>R.removeEventListener(Wze,S)},[S]),e.jsx(gSs,{scope:r,orientation:a,dir:x,loop:i,currentTabStopId:y,onItemFocus:j.useCallback(R=>v(R),[v]),onItemShiftTab:j.useCallback(()=>w(!0),[]),onFocusableItemAdd:j.useCallback(()=>P(R=>R+1),[]),onFocusableItemRemove:j.useCallback(()=>P(R=>R-1),[]),children:e.jsx(Ei.div,{tabIndex:b||I===0?-1:0,"data-orientation":a,...m,ref:g,style:{outline:"none",...t.style},onMouseDown:Ra(t.onMouseDown,()=>{E.current=!0}),onFocus:Ra(t.onFocus,R=>{const D=!E.current;if(R.target===R.currentTarget&&D&&!b){const O=new CustomEvent(Wze,mSs);if(R.currentTarget.dispatchEvent(O),!O.defaultPrevented){const U=C().filter(X=>X.focusable),W=U.find(X=>X.active),V=U.find(X=>X.id===y),Y=[W,V,...U].filter(Boolean).map(X=>X.ref.current);$et(Y,h)}}E.current=!1}),onBlur:Ra(t.onBlur,()=>w(!1))})})},"RovingFocusGroupImpl")),bSs="RovingFocusGroupItem",_Ss=j.forwardRef(OB(function(t,n){const{__scopeRovingFocusGroup:r,focusable:a=!0,active:i=!1,tabStopId:l,children:o,...c}=t,d=my(),u=l||d,h=xSs(bSs,r),m=h.currentTabStopId===u,f=dOt(r),{onFocusableItemAdd:g,onFocusableItemRemove:x,currentTabStopId:y}=h,v=uSs();return Ef(()=>{if(!(!v||!a))return g(),()=>x()},[v,a,g,x]),j.useEffect(()=>{if(!(v||!a))return g(),()=>x()},[v,a,g,x]),e.jsx(THe.ItemSlot,{scope:r,id:u,focusable:a,active:i,children:e.jsx(Ei.span,{tabIndex:m?0:-1,"data-orientation":h.orientation,...c,ref:n,onMouseDown:Ra(t.onMouseDown,b=>{a?h.onItemFocus(u):b.preventDefault()}),onFocus:Ra(t.onFocus,()=>h.onItemFocus(u)),onKeyDown:Ra(t.onKeyDown,b=>{if(b.key==="Tab"&&b.shiftKey){h.onItemShiftTab();return}if(b.target!==b.currentTarget)return;const w=hOt(b,h.orientation,h.dir);if(w!==void 0){if(b.metaKey||b.ctrlKey||b.altKey||b.shiftKey)return;b.preventDefault();let C=f().filter(E=>E.focusable).map(E=>E.ref.current);if(w==="last")C.reverse();else if(w==="prev"||w==="next"){w==="prev"&&C.reverse();const E=C.indexOf(b.currentTarget);C=h.loop?mOt(C,E+1):C.slice(E+1)}setTimeout(()=>$et(C))}}),children:typeof o=="function"?o({isCurrentTabStop:m,hasTabStop:y!=null}):o})})},"RovingFocusGroupItem")),wSs={ArrowLeft:"prev",ArrowUp:"prev",ArrowRight:"next",ArrowDown:"next",PageUp:"first",Home:"first",PageDown:"last",End:"last"};function uOt(s,t){return t!=="rtl"?s:s==="ArrowLeft"?"ArrowRight":s==="ArrowRight"?"ArrowLeft":s}OB(uOt,"getDirectionAwareKey");function hOt(s,t,n){const r=uOt(s.key,n);if(!(t==="vertical"&&["ArrowLeft","ArrowRight"].includes(r))&&!(t==="horizontal"&&["ArrowUp","ArrowDown"].includes(r)))return wSs[r]}OB(hOt,"getFocusIntent");function $et(s,t=!1){const n=document.activeElement;for(const r of s)if(r===n||(r.focus({preventScroll:t}),document.activeElement!==n))return}OB($et,"focusFirst");function mOt(s,t){return s.map((n,r)=>s[(t+r)%s.length])}OB(mOt,"wrapArray");var xLe=ySs,yLe=_Ss,jSs=Object.defineProperty,Hh=(s,t)=>jSs(s,"name",{value:t,configurable:!0}),MHe=["Enter"," "],NSs=["ArrowDown","PageUp","Home"],fOt=["ArrowUp","PageDown","End"],kSs=[...NSs,...fOt],SSs={ltr:[...MHe,"ArrowRight"],rtl:[...MHe,"ArrowLeft"]},CSs={ltr:["ArrowLeft"],rtl:["ArrowRight"]},vLe="Menu",[Qte,ASs,ESs]=LB(vLe),[zB,pOt]=tp(vLe,[ESs,i3,r6]),Uet=i3(),gOt=r6(),[TSs,BB]=zB(vLe),[MSs,Lae]=zB(vLe),PSs=Hh(s=>{const{__scopeMenu:t,open:n=!1,children:r,dir:a,onOpenChange:i,modal:l=!0}=s,o=Uet(t),[c,d]=j.useState(null),u=j.useRef(!1),h=Yp(i),m=l3(a);return j.useEffect(()=>{const f=Hh(()=>{u.current=!0,document.addEventListener("pointerdown",g,{capture:!0,once:!0}),document.addEventListener("pointermove",g,{capture:!0,once:!0})},"handleKeyDown"),g=Hh(()=>u.current=!1,"handlePointer");return document.addEventListener("keydown",f,{capture:!0}),()=>{document.removeEventListener("keydown",f,{capture:!0}),document.removeEventListener("pointerdown",g,{capture:!0}),document.removeEventListener("pointermove",g,{capture:!0})}},[]),j.useEffect(()=>{if(!n)return;const f=Hh(()=>h(!1),"handleBlur");return window.addEventListener("blur",f),()=>window.removeEventListener("blur",f)},[n,h]),e.jsx(Cae,{...o,children:e.jsx(TSs,{scope:t,open:n,onOpenChange:h,content:c,onContentChange:d,children:e.jsx(MSs,{scope:t,onClose:j.useCallback(()=>h(!1),[h]),isUsingKeyboardRef:u,dir:m,modal:l,children:r})})})},"Menu"),xOt=j.forwardRef(Hh(function(t,n){const{__scopeMenu:r,...a}=t,i=Uet(r);return e.jsx(Aae,{...i,...a,ref:n})},"MenuAnchor")),yOt="MenuPortal",[ISs,vOt]=zB(yOt,{forceMount:void 0}),LSs=Hh(s=>{const{__scopeMenu:t,forceMount:n,children:r,container:a}=s,i=BB(yOt,t);return e.jsx(ISs,{scope:t,forceMount:n,children:e.jsx(xy,{present:n||i.open,children:e.jsx(_ae,{asChild:!0,container:a,children:r})})})},"MenuPortal"),aC="MenuContent",[RSs,qet]=zB(aC),DSs=j.forwardRef(Hh(function(t,n){const r=vOt(aC,t.__scopeMenu),{forceMount:a=r.forceMount,...i}=t,l=BB(aC,t.__scopeMenu),o=Lae(aC,t.__scopeMenu);return e.jsx(Qte.Provider,{scope:t.__scopeMenu,children:e.jsx(xy,{present:a||l.open,children:e.jsx(Qte.Slot,{scope:t.__scopeMenu,children:o.modal?e.jsx(FSs,{...i,ref:n}):e.jsx(OSs,{...i,ref:n})})})})},"MenuContent")),FSs=j.forwardRef(Hh(function(t,n){const r=BB(aC,t.__scopeMenu),a=j.useRef(null),i=Vo(n,a);return j.useEffect(()=>{const l=a.current;if(l)return KIe(l)},[]),e.jsx(Vet,{...t,ref:i,trapFocus:r.open,disableOutsidePointerEvents:r.open,disableOutsideScroll:!0,onFocusOutside:Ra(t.onFocusOutside,l=>l.preventDefault(),{checkForDefaultPrevented:!1}),onDismiss:()=>r.onOpenChange(!1)})},"MenuRootContentModal")),OSs=j.forwardRef(Hh(function(t,n){const r=BB(aC,t.__scopeMenu);return e.jsx(Vet,{...t,ref:n,trapFocus:!1,disableOutsidePointerEvents:!1,disableOutsideScroll:!1,onDismiss:()=>r.onOpenChange(!1)})},"MenuRootContentNonModal")),zSs=pC("MenuContent.ScrollLock"),Vet=j.forwardRef(Hh(function(t,n){const{__scopeMenu:r,loop:a=!1,trapFocus:i,onOpenAutoFocus:l,onCloseAutoFocus:o,disableOutsidePointerEvents:c,onEntryFocus:d,onEscapeKeyDown:u,onPointerDownOutside:h,onFocusOutside:m,onInteractOutside:f,onDismiss:g,disableOutsideScroll:x,...y}=t,v=BB(aC,r),b=Lae(aC,r),w=Uet(r),S=gOt(r),C=ASs(r),[E,I]=j.useState(null),P=j.useRef(null),R=Vo(n,P,v.onContentChange),D=j.useRef(0),O=j.useRef(""),U=j.useRef(0),W=j.useRef(null),V=j.useRef("right"),G=j.useRef(0),Y=x?jae:j.Fragment,X=x?{as:zSs,allowPinchZoom:!0}:void 0,ae=Hh(ne=>{var Ee,Se;const te=O.current+ne,J=C().filter(Le=>!Le.disabled),ce=document.activeElement,_e=(Ee=J.find(Le=>Le.ref.current===ce))==null?void 0:Ee.textValue,he=J.map(Le=>Le.textValue),ue=SOt(he,te,_e),ve=(Se=J.find(Le=>Le.textValue===ue))==null?void 0:Se.ref.current;Hh(function Le(Fe){O.current=Fe,window.clearTimeout(D.current),Fe!==""&&(D.current=window.setTimeout(()=>Le(""),1e3))},"updateSearch")(te),ve&&setTimeout(()=>ve.focus())},"handleTypeaheadSearch");j.useEffect(()=>()=>window.clearTimeout(D.current),[]),GW();const ie=j.useCallback(ne=>{var J,ce;return V.current===((J=W.current)==null?void 0:J.side)&&AOt(ne,(ce=W.current)==null?void 0:ce.area)},[]);return e.jsx(RSs,{scope:r,searchRef:O,onItemEnter:j.useCallback(ne=>{ie(ne)&&ne.preventDefault()},[ie]),onItemLeave:j.useCallback(ne=>{var te;ie(ne)||((te=P.current)==null||te.focus(),I(null))},[ie]),onTriggerLeave:j.useCallback(ne=>{ie(ne)&&ne.preventDefault()},[ie]),pointerGraceTimerRef:U,onPointerGraceIntentChange:j.useCallback(ne=>{W.current=ne},[]),children:e.jsx(Y,{...X,children:e.jsx(GIe,{asChild:!0,trapped:i,onMountAutoFocus:Ra(l,ne=>{var te;ne.preventDefault(),(te=P.current)==null||te.focus({preventScroll:!0})}),onUnmountAutoFocus:o,children:e.jsx(RB,{asChild:!0,disableOutsidePointerEvents:c,onEscapeKeyDown:u,onPointerDownOutside:h,onFocusOutside:m,onInteractOutside:f,onDismiss:g,children:e.jsx(xLe,{asChild:!0,...S,dir:b.dir,orientation:"vertical",loop:a,currentTabStopId:E,onCurrentTabStopIdChange:I,onEntryFocus:Ra(d,ne=>{b.isUsingKeyboardRef.current||ne.preventDefault()}),preventScrollOnEntryFocus:!0,children:e.jsx(Eae,{role:"menu","aria-orientation":"vertical","data-state":Get(v.open),"data-radix-menu-content":"",dir:b.dir,...w,...y,ref:R,style:{outline:"none",...y.style},onKeyDown:Ra(y.onKeyDown,ne=>{const J=ne.target.closest("[data-radix-menu-content]")===ne.currentTarget,ce=ne.ctrlKey||ne.altKey||ne.metaKey,_e=ne.key.length===1;J&&(ne.key==="Tab"&&ne.preventDefault(),!ce&&_e&&ae(ne.key));const he=P.current;if(ne.target!==he||!kSs.includes(ne.key))return;ne.preventDefault();const ve=C().filter(Ee=>!Ee.disabled).map(Ee=>Ee.ref.current);fOt.includes(ne.key)&&ve.reverse(),NOt(ve)}),onBlur:Ra(t.onBlur,ne=>{ne.currentTarget.contains(ne.target)||(window.clearTimeout(D.current),O.current="")}),onPointerMove:Ra(t.onPointerMove,_G(ne=>{const te=ne.target,J=G.current!==ne.clientX;if(ne.currentTarget.contains(te)&&J){const ce=ne.clientX>G.current?"right":"left";V.current=ce,G.current=ne.clientX}}))})})})})})})},"MenuContentImpl")),BSs=j.forwardRef(Hh(function(t,n){const{__scopeMenu:r,...a}=t;return e.jsx(Ei.div,{...a,ref:n})},"MenuLabel")),PHe="MenuItem",Axt="menu.itemSelect",Het=j.forwardRef(Hh(function(t,n){const{disabled:r=!1,onSelect:a,...i}=t,l=j.useRef(null),o=Lae(PHe,t.__scopeMenu),c=qet(PHe,t.__scopeMenu),d=Vo(n,l),u=j.useRef(!1),h=Hh(()=>{const m=l.current;if(!r&&m){const f=new CustomEvent(Axt,{bubbles:!0,cancelable:!0});m.addEventListener(Axt,g=>a==null?void 0:a(g),{once:!0}),UIe(m,f),f.defaultPrevented?u.current=!1:o.onClose()}},"handleSelect");return e.jsx(bOt,{...i,ref:d,disabled:r,onClick:Ra(t.onClick,h),onPointerDown:m=>{var f;(f=t.onPointerDown)==null||f.call(t,m),u.current=!0},onPointerUp:Ra(t.onPointerUp,m=>{var f;u.current||(f=m.currentTarget)==null||f.click()}),onKeyDown:Ra(t.onKeyDown,m=>{r||m.target!==m.currentTarget||c.searchRef.current!==""&&m.key===" "||MHe.includes(m.key)&&(m.currentTarget.click(),m.preventDefault())})})},"MenuItem")),bOt=j.forwardRef(Hh(function(t,n){const{__scopeMenu:r,disabled:a=!1,textValue:i,...l}=t,o=qet(PHe,r),c=gOt(r),d=j.useRef(null),u=Vo(n,d),[h,m]=j.useState(!1),[f,g]=j.useState("");return j.useEffect(()=>{const x=d.current;x&&g((x.textContent??"").trim())},[l.children]),e.jsx(Qte.ItemSlot,{scope:r,disabled:a,textValue:i??f,children:e.jsx(yLe,{asChild:!0,...c,focusable:!a,children:e.jsx(Ei.div,{role:"menuitem","data-highlighted":h?"":void 0,"aria-disabled":a||void 0,"data-disabled":a?"":void 0,...l,ref:u,onPointerMove:Ra(t.onPointerMove,_G(x=>{a?o.onItemLeave(x):(o.onItemEnter(x),x.defaultPrevented||x.currentTarget.focus({preventScroll:!0}))})),onPointerLeave:Ra(t.onPointerLeave,_G(x=>o.onItemLeave(x))),onFocus:Ra(t.onFocus,()=>m(!0)),onBlur:Ra(t.onBlur,()=>m(!1))})})})},"MenuItemImpl")),$Ss=j.forwardRef(Hh(function(t,n){const{checked:r=!1,onCheckedChange:a,...i}=t;return e.jsx(wOt,{scope:t.__scopeMenu,checked:r,children:e.jsx(Het,{role:"menuitemcheckbox","aria-checked":Jte(r)?"mixed":r,...i,ref:n,"data-state":bLe(r),onSelect:Ra(i.onSelect,()=>a==null?void 0:a(Jte(r)?!0:!r),{checkForDefaultPrevented:!1})})})},"MenuCheckboxItem")),USs="MenuRadioGroup",[Kkr,qSs]=zB(USs,{value:void 0,onValueChange:Hh(()=>{},"onValueChange")}),VSs="MenuRadioItem",HSs=j.forwardRef(Hh(function(t,n){const{value:r,...a}=t,i=qSs(VSs,t.__scopeMenu),l=r===i.value;return e.jsx(wOt,{scope:t.__scopeMenu,checked:l,children:e.jsx(Het,{role:"menuitemradio","aria-checked":l,...a,ref:n,"data-state":bLe(l),onSelect:Ra(a.onSelect,()=>{var o;return(o=i.onValueChange)==null?void 0:o.call(i,r)},{checkForDefaultPrevented:!1})})})},"MenuRadioItem")),_Ot="MenuItemIndicator",[wOt,GSs]=zB(_Ot,{checked:!1}),WSs=j.forwardRef(Hh(function(t,n){const{__scopeMenu:r,forceMount:a,...i}=t,l=GSs(_Ot,r);return e.jsx(xy,{present:a||Jte(l.checked)||l.checked===!0,children:e.jsx(Ei.span,{...i,ref:n,"data-state":bLe(l.checked)})})},"MenuItemIndicator")),KSs=j.forwardRef(Hh(function(t,n){const{__scopeMenu:r,...a}=t;return e.jsx(Ei.div,{role:"separator","aria-orientation":"horizontal",...a,ref:n})},"MenuSeparator")),YSs="MenuSub",[Ykr,jOt]=zB(YSs),Ece="MenuSubTrigger",ZSs=j.forwardRef(Hh(function(t,n){const r=BB(Ece,t.__scopeMenu),a=Lae(Ece,t.__scopeMenu),i=jOt(Ece,t.__scopeMenu),l=qet(Ece,t.__scopeMenu),o=j.useRef(null),{pointerGraceTimerRef:c,onPointerGraceIntentChange:d}=l,u={__scopeMenu:t.__scopeMenu},h=j.useCallback(()=>{o.current&&window.clearTimeout(o.current),o.current=null},[]);j.useEffect(()=>h,[h]),j.useEffect(()=>{const f=c.current;return()=>{window.clearTimeout(f),d(null)}},[c,d]);const m=Vo(n,i.onTriggerChange);return e.jsx(xOt,{asChild:!0,...u,children:e.jsx(bOt,{id:i.triggerId,"aria-haspopup":"menu","aria-expanded":r.open,"aria-controls":r.open?i.contentId:void 0,"data-state":Get(r.open),...t,ref:m,onClick:f=>{var g;(g=t.onClick)==null||g.call(t,f),!(t.disabled||f.defaultPrevented)&&(f.currentTarget.focus(),r.open||r.onOpenChange(!0))},onPointerMove:Ra(t.onPointerMove,_G(f=>{l.onItemEnter(f),!f.defaultPrevented&&!t.disabled&&!r.open&&!o.current&&(l.onPointerGraceIntentChange(null),o.current=window.setTimeout(()=>{r.onOpenChange(!0),h()},100))})),onPointerLeave:Ra(t.onPointerLeave,_G(f=>{var x,y;h();const g=(x=r.content)==null?void 0:x.getBoundingClientRect();if(g){const v=(y=r.content)==null?void 0:y.dataset.side,b=v==="right",w=b?-5:5,S=g[b?"left":"right"],C=g[b?"right":"left"];l.onPointerGraceIntentChange({area:[{x:f.clientX+w,y:f.clientY},{x:S,y:g.top},{x:C,y:g.top},{x:C,y:g.bottom},{x:S,y:g.bottom}],side:v}),window.clearTimeout(c.current),c.current=window.setTimeout(()=>l.onPointerGraceIntentChange(null),300)}else{if(l.onTriggerLeave(f),f.defaultPrevented)return;l.onPointerGraceIntentChange(null)}})),onKeyDown:Ra(t.onKeyDown,f=>{var x;t.disabled||f.target!==f.currentTarget||l.searchRef.current!==""&&f.key===" "||SSs[a.dir].includes(f.key)&&(r.onOpenChange(!0),(x=r.content)==null||x.focus(),f.preventDefault())})})})},"MenuSubTrigger")),XSs="MenuSubContent",QSs=j.forwardRef(Hh(function(t,n){const r=vOt(aC,t.__scopeMenu),{forceMount:a=r.forceMount,align:i="start",...l}=t,o=BB(aC,t.__scopeMenu),c=Lae(aC,t.__scopeMenu),d=jOt(XSs,t.__scopeMenu),u=j.useRef(null),h=Vo(n,u);return e.jsx(Qte.Provider,{scope:t.__scopeMenu,children:e.jsx(xy,{present:a||o.open,children:e.jsx(Qte.Slot,{scope:t.__scopeMenu,children:e.jsx(Vet,{id:d.contentId,"aria-labelledby":d.triggerId,...l,ref:h,align:i,side:c.dir==="rtl"?"left":"right",disableOutsidePointerEvents:!1,disableOutsideScroll:!1,trapFocus:!1,onOpenAutoFocus:m=>{var f;c.isUsingKeyboardRef.current&&((f=u.current)==null||f.focus()),m.preventDefault()},onCloseAutoFocus:m=>m.preventDefault(),onFocusOutside:Ra(t.onFocusOutside,m=>{m.target!==d.trigger&&o.onOpenChange(!1)}),onEscapeKeyDown:Ra(t.onEscapeKeyDown,m=>{c.onClose(),m.preventDefault()}),onKeyDown:Ra(t.onKeyDown,m=>{var x;const f=m.currentTarget.contains(m.target),g=CSs[c.dir].includes(m.key);f&&g&&(o.onOpenChange(!1),(x=d.trigger)==null||x.focus(),m.preventDefault())})})})})})},"MenuSubContent"));function Get(s){return s?"open":"closed"}Hh(Get,"getOpenState");function Jte(s){return s==="indeterminate"}Hh(Jte,"isIndeterminate");function bLe(s){return Jte(s)?"indeterminate":s?"checked":"unchecked"}Hh(bLe,"getCheckedState");function NOt(s){const t=document.activeElement;for(const n of s)if(n===t||(n.focus(),document.activeElement!==t))return}Hh(NOt,"focusFirst");function kOt(s,t){return s.map((n,r)=>s[(t+r)%s.length])}Hh(kOt,"wrapArray");function SOt(s,t,n){const a=t.length>1&&Array.from(t).every(d=>d===t[0])?t[0]:t,i=n?s.indexOf(n):-1;let l=kOt(s,Math.max(i,0));a.length===1&&(l=l.filter(d=>d!==n));const c=l.find(d=>d.toLowerCase().startsWith(a.toLowerCase()));return c!==n?c:void 0}Hh(SOt,"getNextMatch");function COt(s,t){const{x:n,y:r}=s;let a=!1;for(let i=0,l=t.length-1;ir!=m>r&&n<(h-d)*(r-u)/(m-u)+d&&(a=!a)}return a}Hh(COt,"isPointInPolygon");function AOt(s,t){if(!t)return!1;const n={x:s.clientX,y:s.clientY};return COt(n,t)}Hh(AOt,"isPointerInGraceArea");function _G(s){return t=>t.pointerType==="mouse"?s(t):void 0}Hh(_G,"whenMouse");var JSs=PSs,eCs=xOt,tCs=LSs,sCs=DSs,nCs=BSs,rCs=Het,aCs=$Ss,iCs=HSs,oCs=WSs,lCs=KSs,cCs=ZSs,dCs=QSs,uCs=Object.defineProperty,Nk=(s,t)=>uCs(s,"name",{value:t,configurable:!0}),Wet="DropdownMenu",[hCs,Zkr]=tp(Wet,[pOt]),kk=pOt(),[mCs,EOt]=hCs(Wet),fCs=Nk(s=>{const{__scopeDropdownMenu:t,children:n,dir:r,open:a,defaultOpen:i,onOpenChange:l,modal:o=!0}=s,c=kk(t),d=j.useRef(null),[u,h]=fy({prop:a,defaultProp:i??!1,onChange:l,caller:Wet});return e.jsx(mCs,{scope:t,triggerId:my(),triggerRef:d,contentId:my(),open:u,onOpenChange:h,onOpenToggle:j.useCallback(()=>h(m=>!m),[h]),modal:o,children:e.jsx(JSs,{...c,open:u,onOpenChange:h,dir:r,modal:o,children:n})})},"DropdownMenu"),pCs="DropdownMenuTrigger",gCs=j.forwardRef(Nk(function(t,n){const{__scopeDropdownMenu:r,disabled:a=!1,...i}=t,l=EOt(pCs,r),o=kk(r),c=Vo(n,l.triggerRef);return e.jsx(eCs,{asChild:!0,...o,children:e.jsx(Ei.button,{type:"button",id:l.triggerId,"aria-haspopup":"menu","aria-expanded":l.open,"aria-controls":l.open?l.contentId:void 0,"data-state":l.open?"open":"closed","data-disabled":a?"":void 0,disabled:a,...i,ref:c,onPointerDown:Ra(t.onPointerDown,d=>{!a&&d.button===0&&d.ctrlKey===!1&&(l.onOpenToggle(),l.open||d.preventDefault())}),onKeyDown:Ra(t.onKeyDown,d=>{a||(["Enter"," "].includes(d.key)&&l.onOpenToggle(),d.key==="ArrowDown"&&l.onOpenChange(!0),["Enter"," ","ArrowDown"].includes(d.key)&&d.preventDefault())})})})},"DropdownMenuTrigger")),xCs=Nk(s=>{const{__scopeDropdownMenu:t,...n}=s,r=kk(t);return e.jsx(tCs,{...r,...n})},"DropdownMenuPortal"),yCs="DropdownMenuContent",vCs=j.forwardRef(Nk(function(t,n){const{__scopeDropdownMenu:r,...a}=t,i=EOt(yCs,r),l=kk(r),o=j.useRef(!1);return e.jsx(sCs,{id:i.contentId,"aria-labelledby":i.triggerId,...l,...a,ref:n,onCloseAutoFocus:Ra(t.onCloseAutoFocus,c=>{var d;o.current||(d=i.triggerRef.current)==null||d.focus(),o.current=!1,c.preventDefault()}),onInteractOutside:Ra(t.onInteractOutside,c=>{const d=c.detail.originalEvent,u=d.button===0&&d.ctrlKey===!0,h=d.button===2||u;(!i.modal||h)&&(o.current=!0)}),style:{...t.style,"--radix-dropdown-menu-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-dropdown-menu-content-available-width":"var(--radix-popper-available-width)","--radix-dropdown-menu-content-available-height":"var(--radix-popper-available-height)","--radix-dropdown-menu-trigger-width":"var(--radix-popper-anchor-width)","--radix-dropdown-menu-trigger-height":"var(--radix-popper-anchor-height)"}})},"DropdownMenuContent")),bCs=j.forwardRef(Nk(function(t,n){const{__scopeDropdownMenu:r,...a}=t,i=kk(r);return e.jsx(nCs,{...i,...a,ref:n})},"DropdownMenuLabel")),_Cs=j.forwardRef(Nk(function(t,n){const{__scopeDropdownMenu:r,...a}=t,i=kk(r);return e.jsx(rCs,{...i,...a,ref:n})},"DropdownMenuItem")),wCs=j.forwardRef(Nk(function(t,n){const{__scopeDropdownMenu:r,...a}=t,i=kk(r);return e.jsx(aCs,{...i,...a,ref:n})},"DropdownMenuCheckboxItem")),jCs=j.forwardRef(Nk(function(t,n){const{__scopeDropdownMenu:r,...a}=t,i=kk(r);return e.jsx(iCs,{...i,...a,ref:n})},"DropdownMenuRadioItem")),NCs=j.forwardRef(Nk(function(t,n){const{__scopeDropdownMenu:r,...a}=t,i=kk(r);return e.jsx(oCs,{...i,...a,ref:n})},"DropdownMenuItemIndicator")),kCs=j.forwardRef(Nk(function(t,n){const{__scopeDropdownMenu:r,...a}=t,i=kk(r);return e.jsx(lCs,{...i,...a,ref:n})},"DropdownMenuSeparator")),SCs=j.forwardRef(Nk(function(t,n){const{__scopeDropdownMenu:r,...a}=t,i=kk(r);return e.jsx(cCs,{...i,...a,ref:n})},"DropdownMenuSubTrigger")),CCs=j.forwardRef(Nk(function(t,n){const{__scopeDropdownMenu:r,...a}=t,i=kk(r);return e.jsx(dCs,{...i,...a,ref:n,style:{...t.style,"--radix-dropdown-menu-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-dropdown-menu-content-available-width":"var(--radix-popper-available-width)","--radix-dropdown-menu-content-available-height":"var(--radix-popper-available-height)","--radix-dropdown-menu-trigger-width":"var(--radix-popper-anchor-width)","--radix-dropdown-menu-trigger-height":"var(--radix-popper-anchor-height)"}})},"DropdownMenuSubContent")),ACs=fCs,ECs=gCs,TCs=xCs,TOt=vCs,MOt=bCs,POt=_Cs,IOt=wCs,LOt=jCs,ROt=NCs,DOt=kCs,FOt=SCs,OOt=CCs;const Uu=ACs,qu=ECs,MCs=j.forwardRef(({className:s,inset:t,children:n,...r},a)=>e.jsxs(FOt,{ref:a,className:Pt("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),...r,children:[n,e.jsx(Di,{className:"ml-auto h-4 w-4"})]}));MCs.displayName=FOt.displayName;const PCs=j.forwardRef(({className:s,...t},n)=>e.jsx(OOt,{ref:n,className:Pt("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}));PCs.displayName=OOt.displayName;const Eu=j.forwardRef(({className:s,sideOffset:t=4,...n},r)=>e.jsx(TCs,{children:e.jsx(TOt,{ref:r,sideOffset:t,className:Pt("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),...n})}));Eu.displayName=TOt.displayName;const ja=j.forwardRef(({className:s,inset:t,...n},r)=>e.jsx(POt,{ref:r,className:Pt("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),...n}));ja.displayName=POt.displayName;const ICs=j.forwardRef(({className:s,children:t,checked:n,...r},a)=>e.jsxs(IOt,{ref:a,className:Pt("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:n,...r,children:[e.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:e.jsx(ROt,{children:e.jsx(la,{className:"h-4 w-4"})})}),t]}));ICs.displayName=IOt.displayName;const LCs=j.forwardRef(({className:s,children:t,...n},r)=>e.jsxs(LOt,{ref:r,className:Pt("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),...n,children:[e.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:e.jsx(ROt,{children:e.jsx(Og,{className:"h-2 w-2 fill-current"})})}),t]}));LCs.displayName=LOt.displayName;const SL=j.forwardRef(({className:s,inset:t,...n},r)=>e.jsx(MOt,{ref:r,className:Pt("px-2 py-1.5 text-sm font-semibold",t&&"pl-8",s),...n}));SL.displayName=MOt.displayName;const R0=j.forwardRef(({className:s,...t},n)=>e.jsx(DOt,{ref:n,className:Pt("-mx-1 my-1 h-px bg-muted",s),...t}));R0.displayName=DOt.displayName;const RCs=()=>{const{isAssistant:s,actingAsAgent:t,assignedAgents:n,setActingAsAgent:r,isActingAsSelf:a,setActingAsSelf:i}=Iae();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(sl,{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(Zn,{className:"h-4 w-4 flex-shrink-0"}),e.jsx("span",{className:"font-medium text-sm",children:"Acting as"})]}),e.jsxs(Uu,{children:[e.jsx(qu,{asChild:!0,children:e.jsxs($,{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(sl,{className:"h-4 w-4"}),e.jsx("strong",{children:"My Account"})]}):t?e.jsxs(e.Fragment,{children:[e.jsxs(Oa,{className:"h-5 w-5",children:[e.jsx(Li,{src:t.avatar_url||void 0}),e.jsx(za,{className:"text-[10px] bg-primary-foreground/30",children:l(t.name)})]}),e.jsx("strong",{children:t.name})]}):e.jsx("strong",{children:"Select..."}),e.jsx(Tl,{className:"h-3 w-3"})]})}),e.jsxs(Eu,{align:"start",className:"z-[2147483647]",children:[e.jsxs(ja,{onClick:i,className:"gap-2",children:[e.jsx(sl,{className:"h-4 w-4"}),e.jsx("span",{children:"My Account"}),a&&e.jsx(Be,{variant:"secondary",className:"ml-auto text-[10px]",children:"Current"})]}),e.jsx(R0,{}),n.map(o=>e.jsxs(ja,{onClick:()=>r(o),className:"gap-2",children:[e.jsxs(Oa,{className:"h-6 w-6",children:[e.jsx(Li,{src:o.avatar_url||void 0}),e.jsx(za,{className:"text-[10px]",children:l(o.name)})]}),e.jsx("span",{children:o.name}),!a&&o.id===(t==null?void 0:t.id)&&e.jsx(Be,{variant:"secondary",className:"ml-auto text-[10px]",children:"Current"})]},o.id))]})]})]}),e.jsx(Be,{variant:"secondary",className:"bg-primary-foreground/20 text-primary-foreground border-0 text-xs",children:a?"Personal Mode":"Assistant Mode"})]})})};function jC(){var c,d;const{user:s,isAdmin:t}=vs(),{data:n,isLoading:r}=tt({queryKey:["partnership-membership",s==null?void 0:s.id],enabled:!!(s!=null&&s.id),staleTime:5*60*1e3,queryFn:async()=>{const{data:u}=await q.from("partnership_memberships").select("id, status, package_id, program_id").eq("user_id",s.id).eq("status","active").maybeSingle();if(!u)return null;const[{data:h},{data:m}]=await Promise.all([q.from("partnership_packages").select("*").eq("id",u.package_id).maybeSingle(),q.from("partnership_programs").select("id, name, enabled, brokerage_id").eq("id",u.program_id).maybeSingle()]);return!h||!(m!=null&&m.enabled)?null:{membership:u,pkg:h,program:m}}}),a=j.useMemo(()=>{var u;return new Set(((u=n==null?void 0:n.pkg)==null?void 0:u.included_features)||[])},[n]),i=!!n,l=u=>t||!i?!0:a.has(u),o=u=>{var f,g;const h=((f=n==null?void 0:n.pkg)==null?void 0:f.feature_limits)||{},m=(g=h==null?void 0:h[u])==null?void 0:g.monthly_limit;return typeof m=="number"?m:null};return{isLoading:r,isMember:i,membership:(n==null?void 0:n.membership)??null,pkg:(n==null?void 0:n.pkg)??null,program:(n==null?void 0:n.program)??null,packageKey:((c=n==null?void 0:n.pkg)==null?void 0:c.key)??null,packageName:((d=n==null?void 0:n.pkg)==null?void 0:d.name)??null,features:a,hasFeature:l,limitFor:o,isRestricted:i&&!t}}const Ket={crm:"Contacts & CRM",mass_email:"Mass Email",website:"Agent Website",deals:"Deal Pipeline",listing_exchange:"Listing Exchange",smart_card:"Smart Card",guest_book:"Guest Book",landing_pages:"Landing Pages",learn:"Learn & Academy",community:"Community",quickvid:"QuickVid",reelflow:"ReelFlow",direct_mail:"Direct Mail",levelup_attract:"LevelUp Attract",listing_revival:"Listing Revival",fsbo_breakthrough:"By-Owner Breakthrough",weekly_reels:"Weekly Reels",coaching_access:"Coaching",marketing_studio:"Marketing Studio",video_library:"Video Library",presentations:"Presentations",card_studio:"Card Studio",newsletter:"Newsletters",scheduler:"Scheduler",client_portals:"Client Portals",social:"Social Swag"},Xkr=Object.keys(Ket),DCs={home:null,crm:"crm",deals:"deals",listings:"listing_exchange",marketing:"marketing_studio",websites:"website",academy:"learn",events:"learn",apps:null,brokerage:"community",more:null},Ext={"mission-control":"crm",contacts:"crm","sphere-gaps":"crm","mass-emails":"mass_email","bulk-email":"mass_email",newsletters:"newsletter","my-card":"smart_card","guest-book":"guest_book","landing-pages":"landing_pages","card-studio":"card_studio","direct-mail":"direct_mail",quickvid:"quickvid","video-library":"video_library",reelflow:"reelflow",scheduler:"scheduler",community:"community",coaching:"coaching_access","my-coach":"coaching_access","client-portals":"client_portals",presentations:"presentations","social-swag":"social",attract:"levelup_attract","listing-revival":"listing_revival",fsbo:"fsbo_breakthrough","weekly-reels":"weekly_reels"},FCs={quickvid:"quickvid","smart-card":"smart_card","smart-presentations":"presentations","listing-presentation-studio":"presentations","landing-pages":"landing_pages","guest-book":"guest_book","card-studio":"card_studio","direct-mail":"direct_mail",reelflow:"reelflow","mass-emails":"mass_email","newsletter-pro":"newsletter","listing-studio":"listing_exchange","listing-revival":"listing_revival","fsbo-breakthrough":"fsbo_breakthrough",attract:"levelup_attract",scheduler:"scheduler","client-portals":"client_portals","social-swag":"social","weekly-reels":"weekly_reels"};function OCs(s){return s.id in Ext?Ext[s.id]:DCs[s.primaryCategory]??null}function zCs(s){return FCs[s]??null}const BCs=[["/mission-control/pipeline","deals"],["/mission-control/transactions","deals"],["/mission-control/tasks","deals"],["/mission-control/client-portals","client_portals"],["/mission-control/scheduler","scheduler"],["/mission-control/guest-book","guest_book"],["/mission-control/landing-pages","landing_pages"],["/mission-control/card-studio","card_studio"],["/mission-control/direct-mail","direct_mail"],["/mission-control/video-library","video_library"],["/mission-control/video","quickvid"],["/mission-control/my-card","smart_card"],["/mission-control/listing-presentations","presentations"],["/mission-control/sent-emails","mass_email"],["/mission-control/listings","listing_exchange"],["/mission-control/listing-studio","listing_exchange"],["/mission-control/cma","listing_exchange"],["/apps/listing-presentation-studio","presentations"],["/apps/listing-revival","listing_revival"],["/apps/fsbo-breakthrough","fsbo_breakthrough"],["/marketing-studio","marketing_studio"],["/social-swag","social"],["/weekly-reels","weekly_reels"],["/newsletters","newsletter"],["/email-campaigns","mass_email"],["/templates","marketing_studio"],["/reelflow","reelflow"],["/attract","levelup_attract"],["/community","community"],["/coaching","coaching_access"],["/my-coach","coaching_access"],["/events","learn"],["/academy","learn"],["/levelup-u","learn"],["/toolbox","learn"],["/programs","learn"]];function zOt(s){let t=null;for(const n of BCs){const[r]=n;(s===r||s.startsWith(r+"/")||s.startsWith(r+"?"))&&(!t||r.length>t[0].length)&&(t=n)}return t?t[1]:null}const Ne=j.forwardRef(({className:s,...t},n)=>e.jsx("div",{ref:n,className:Pt("rounded-lg border bg-card text-card-foreground shadow-sm",s),...t}));Ne.displayName="Card";const Ct=j.forwardRef(({className:s,...t},n)=>e.jsx("div",{ref:n,className:Pt("flex flex-col space-y-1.5 p-6",s),...t}));Ct.displayName="CardHeader";const At=j.forwardRef(({className:s,...t},n)=>e.jsx("h3",{ref:n,className:Pt("text-2xl font-semibold leading-none tracking-tight",s),...t}));At.displayName="CardTitle";const Gn=j.forwardRef(({className:s,...t},n)=>e.jsx("p",{ref:n,className:Pt("text-sm text-muted-foreground",s),...t}));Gn.displayName="CardDescription";const Ie=j.forwardRef(({className:s,...t},n)=>e.jsx("div",{ref:n,className:Pt("p-6 pt-0",s),...t}));Ie.displayName="CardContent";const wEe=j.forwardRef(({className:s,...t},n)=>e.jsx("div",{ref:n,className:Pt("flex items-center p-6 pt-0",s),...t}));wEe.displayName="CardFooter";const Rs=j.forwardRef(({className:s,...t},n)=>e.jsx("textarea",{className:Pt("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:n,...t}));Rs.displayName="Textarea";const zs=YIe,jl=fet,$Cs=ZIe,Qkr=Sae,BOt=j.forwardRef(({className:s,...t},n)=>e.jsx(WW,{ref:n,className:Pt("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}));BOt.displayName=WW.displayName;const Os=j.forwardRef(({className:s,children:t,overlayClassName:n,...r},a)=>e.jsxs($Cs,{children:[e.jsx(BOt,{className:n}),e.jsxs(KW,{ref:a,className:Pt("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),...r,children:[t,e.jsxs(Sae,{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(gr,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only",children:"Close"})]})]})]}));Os.displayName=KW.displayName;const Us=({className:s,...t})=>e.jsx("div",{className:Pt("flex flex-col space-y-1.5 text-center sm:text-left",s),...t});Us.displayName="DialogHeader";const Ar=({className:s,...t})=>e.jsx("div",{className:Pt("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",s),...t});Ar.displayName="DialogFooter";const Bs=j.forwardRef(({className:s,...t},n)=>e.jsx(Nae,{ref:n,className:Pt("text-lg font-semibold leading-none tracking-tight",s),...t}));Bs.displayName=Nae.displayName;const Ir=j.forwardRef(({className:s,...t},n)=>e.jsx(kae,{ref:n,className:Pt("text-sm text-muted-foreground",s),...t}));Ir.displayName=kae.displayName;function UCs({featureKey:s,open:t,onOpenChange:n}){const{user:r}=vs(),a=Vt(),[i,l]=j.useState(""),{data:o}=tt({queryKey:["partnership-upgrade-requests",r==null?void 0:r.id],enabled:!!(r!=null&&r.id)&&t,queryFn:async()=>{const{data:h}=await q.from("lead_site_upgrade_requests").select("id, feature_key, status").eq("user_id",r.id);return h||[]}}),c=!!(o!=null&&o.some(h=>h.feature_key===s&&h.status!=="declined")),d=ft({mutationFn:async()=>{const{error:h}=await q.from("lead_site_upgrade_requests").insert({user_id:r.id,feature_key:s,notes:i||null});if(h)throw h},onSuccess:()=>{a.invalidateQueries({queryKey:["partnership-upgrade-requests"]}),re.success("Request sent — we'll be in touch shortly."),l(""),n(!1)},onError:h=>re.error((h==null?void 0:h.message)||"Could not send your request")}),u=Ket[s]||s;return e.jsx(zs,{open:t,onOpenChange:n,children:e.jsxs(Os,{className:"sm:max-w-md",children:[e.jsxs(Us,{children:[e.jsxs(Bs,{className:"flex items-center gap-2",children:[e.jsx(Nn,{className:"h-5 w-5 text-primary"}),"Request ",u]}),e.jsxs(Ir,{children:[u," is included with the Signature package. Send a request and we'll get you set up."]})]}),c?e.jsxs("div",{className:"rounded-lg border border-border bg-muted/40 p-4 text-sm flex items-start gap-2",children:[e.jsx(la,{className:"h-4 w-4 mt-0.5 text-primary"}),e.jsx("span",{children:"You've already requested this. We'll follow up soon."})]}):e.jsx(Rs,{placeholder:"Anything we should know? (optional)",value:i,onChange:h=>l(h.target.value),rows:4}),e.jsxs(Ar,{children:[e.jsx($,{variant:"outline",onClick:()=>n(!1),children:"Close"}),!c&&e.jsx($,{onClick:()=>d.mutate(),disabled:d.isPending,children:d.isPending?"Sending…":"Send request"})]})]})})}function qCs({featureKey:s}){const[t,n]=j.useState(!1),r=Ket[s]||s;return e.jsxs("div",{className:"flex items-center justify-center py-16 px-4",children:[e.jsx(Ne,{className:"max-w-lg w-full border-border/60",children:e.jsxs(Ie,{className:"p-8 text-center space-y-4",children:[e.jsx("div",{className:"mx-auto h-12 w-12 rounded-full bg-primary/10 flex items-center justify-center",children:e.jsx(pc,{className:"h-6 w-6 text-primary"})}),e.jsxs("h2",{className:"text-2xl font-semibold",children:[r," is a Signature feature"]}),e.jsxs("p",{className:"text-muted-foreground",children:["Your current package doesn't include ",r,". Request access and our team will upgrade your account."]}),e.jsxs($,{onClick:()=>n(!0),className:"gap-2",children:[e.jsx(Nn,{className:"h-4 w-4"})," Request access"]})]})}),e.jsx(UCs,{featureKey:s,open:t,onOpenChange:n})]})}const $Ot=s=>{const[t,n]=j.useState(null),[r,a]=j.useState(!0);return j.useEffect(()=>{if(!s){a(!1);return}(async()=>{try{const{data:o}=await q.storage.from("avatars").list(`${s}`);if(o&&o.length>0){const{data:c}=q.storage.from("avatars").getPublicUrl(`${s}/${o[0].name}`);n(`${c.publicUrl}?t=${Date.now()}`)}else n(null)}catch(o){console.error("Error fetching avatar:",o),n(null)}finally{a(!1)}})()},[s]),{avatarUrl:t,loading:r,refreshAvatar:async()=>{if(s)try{const{data:l}=await q.storage.from("avatars").list(`${s}`);if(l&&l.length>0){const{data:o}=q.storage.from("avatars").getPublicUrl(`${s}/${l[0].name}`);n(`${o.publicUrl}?t=${Date.now()}`)}}catch(l){console.error("Error refreshing avatar:",l)}}}},UOt=async s=>{const t=new Map;return await Promise.all(s.map(async n=>{try{const{data:r}=await q.storage.from("avatars").list(`${n}`);if(r&&r.length>0){const{data:a}=q.storage.from("avatars").getPublicUrl(`${n}/${r[0].name}`);t.set(n,a.publicUrl)}}catch{}})),t},VCs=s=>{const[t,n]=j.useState({isTrial:!1,isExpired:!1,expiresAt:null,daysLeft:null,loading:!0});return j.useEffect(()=>{if(!s){n(a=>({...a,loading:!1}));return}(async()=>{try{const{data:a,error:i}=await q.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),n(h=>({...h,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 h=new Date().getTime(),m=new Date(d).getTime(),f=Math.ceil((m-h)/(1e3*60*60*24)),g=f<=0;n({isTrial:!0,isExpired:g,expiresAt:d,daysLeft:g?0:f,loading:!1})}else n({isTrial:!1,isExpired:!1,expiresAt:null,daysLeft:null,loading:!1})}catch(a){console.error("Error in useTrialStatus:",a),n(i=>({...i,loading:!1}))}})()},[s]),t},Rae=()=>{const{data:s,isLoading:t}=tt({queryKey:["feature-flags"],queryFn:async()=>{const{data:r,error:a}=await q.from("feature_flags").select("*");if(a)throw a;return r}}),n=r=>{if(!s)return!1;const a=s.find(i=>i.key===r);return(a==null?void 0:a.enabled)??!1};return{flags:s,isLoading:t,isFeatureEnabled:n,isAgentOSEnabled:n("agent_os_enabled"),isInnerCircleEnabled:n("innercircle_enabled"),isMarketplaceEnabled:n("marketplace")}},Txt="community_last_seen_post_at";function HCs(){const{user:s}=vs(),t=fu(),[n,r]=j.useState(0),[a,i]=j.useState(null);j.useEffect(()=>{if(!s)return;const o=localStorage.getItem(`${Txt}_${s.id}`);i(o)},[s]),j.useEffect(()=>{if(!s)return;const o=`community_unread_count_${s.id}`,c=2*60*1e3;(async()=>{try{const f=sessionStorage.getItem(o);if(f){const g=JSON.parse(f);if(g.ts&&Date.now()-g.ts{if(!s)return;const o=q.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 u=t.pathname==="/community";u||r(x=>x+1);const{data:h}=await q.from("profiles").select("name").eq("id",d.user_id).single(),m=(h==null?void 0:h.name)||"Someone",f=d.content.replace(/@\[([^\]]+)\]\([^)]+\)/g,"@$1"),g=f.length>50?f.substring(0,50)+"...":f;u||re("New Community Post",{description:`${m}: ${g}`,action:{label:"View",onClick:()=>{window.location.href="/community"}}})}).subscribe();return()=>{q.removeChannel(o)}},[s,t.pathname]);const l=j.useCallback(()=>{if(!s)return;const o=new Date().toISOString();localStorage.setItem(`${Txt}_${s.id}`,o),i(o),r(0)},[s]);return j.useEffect(()=>{t.pathname==="/community"&&n>0&&l()},[t.pathname,n,l]),{unreadCount:n,markAsRead:l}}function GCs(){const{isAdmin:s}=vs(),{data:t=0}=tt({queryKey:["wishlist-open-count"],queryFn:async()=>{const{count:n,error:r}=await q.from("wishlist_items").select("*",{count:"exact",head:!0}).eq("status","open");if(r)throw r;return n||0},enabled:s,staleTime:6e4});return{openCount:s?t:0}}const Kze=s=>`levelup:activeTeam:${s}`,Dae=()=>{const s=Sa();return tt({queryKey:["user-teams",s],queryFn:async()=>{const{data:t,error:n}=await q.from("team_members").select("id, team_id, role").eq("user_id",s);if(n)throw n;if(!(t!=null&&t.length))return[];const{data:r,error:a}=await q.from("teams").select("*").in("id",t.map(l=>l.team_id));if(a)throw a;const i=new Map((r||[]).map(l=>[l.id,l]));return t.filter(l=>i.has(l.team_id)).map(l=>({membershipId:l.id,teamId:l.team_id,role:l.role,team:i.get(l.team_id)})).sort((l,o)=>{var c,d;return l.role!==o.role?l.role==="team_leader"?-1:1:(((c=l.team)==null?void 0:c.name)||"").localeCompare(((d=o.team)==null?void 0:d.name)||"")})},enabled:!!s,staleTime:5*60*1e3})},Hw=()=>{const s=Sa(),t=Dae(),n=j.useMemo(()=>t.data||[],[t.data]),[r,a]=j.useState(()=>!s||typeof window>"u"?null:window.localStorage.getItem(Kze(s)));j.useEffect(()=>{!s||typeof window>"u"||a(window.localStorage.getItem(Kze(s)))},[s]);const i=j.useCallback(o=>{a(o),s&&typeof window<"u"&&window.localStorage.setItem(Kze(s),o)},[s]),l=j.useMemo(()=>n.length?n.find(o=>o.teamId===r)||n[0]:null,[n,r]);return{...t,data:l,teams:n,activeTeamId:(l==null?void 0:l.teamId)??null,setActiveTeamId:i}},XU="weekly_reels";function _Le(){const{user:s,loading:t,isAdmin:n}=vs(),{data:r,isLoading:a}=tt({queryKey:["feature-entitlement",XU,s==null?void 0:s.id],enabled:!!s&&!n,staleTime:5*60*1e3,queryFn:async()=>{const{data:i,error:l}=await q.from("feature_entitlements").select("enabled, expires_at, tier").eq("user_id",s.id).eq("feature_key",XU).maybeSingle();if(l)throw l;return i?{hasAccess:i.enabled&&(!i.expires_at||new Date(i.expires_at).getTime()>Date.now()),tier:i.tier??null}:{hasAccess:!1,tier:null}}});return{hasAccess:n||!!(r!=null&&r.hasAccess),tier:n?"admin":(r==null?void 0:r.tier)??null,isLoading:t||!n&&!!s&&a}}const Wy=YIe,Fae=fet,WCs=ZIe,qOt=j.forwardRef(({className:s,...t},n)=>e.jsx(WW,{className:Pt("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:n}));qOt.displayName=WW.displayName;const KCs=DB("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"}}),py=j.forwardRef(({side:s="right",className:t,children:n,...r},a)=>e.jsxs(WCs,{children:[e.jsx(qOt,{}),e.jsxs(KW,{ref:a,className:Pt(KCs({side:s}),t),...r,children:[n,e.jsxs(Sae,{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(gr,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only",children:"Close"})]})]})]}));py.displayName=KW.displayName;const D0=({className:s,...t})=>e.jsx("div",{className:Pt("flex flex-col space-y-2 text-center sm:text-left",s),...t});D0.displayName="SheetHeader";const VOt=({className:s,...t})=>e.jsx("div",{className:Pt("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",s),...t});VOt.displayName="SheetFooter";const F0=j.forwardRef(({className:s,...t},n)=>e.jsx(Nae,{ref:n,className:Pt("text-lg font-semibold text-foreground",s),...t}));F0.displayName=Nae.displayName;const $B=j.forwardRef(({className:s,...t},n)=>e.jsx(kae,{ref:n,className:Pt("text-sm text-muted-foreground",s),...t}));$B.displayName=kae.displayName;var YCs=Object.defineProperty,ZCs=(s,t)=>YCs(s,"name",{value:t,configurable:!0});function wG(s,[t,n]){return Math.min(n,Math.max(t,s))}ZCs(wG,"clamp");var XCs=Object.defineProperty,Su=(s,t)=>XCs(s,"name",{value:t,configurable:!0});function HOt(s,t){return j.useReducer((n,r)=>t[n][r]??n,s)}Su(HOt,"useStateMachine");var GOt="ScrollArea",[WOt,Jkr]=tp(GOt),[QCs,Sk]=WOt(GOt),JCs=j.forwardRef(Su(function(t,n){const{__scopeScrollArea:r,type:a="hover",dir:i,scrollHideDelay:l=600,...o}=t,[c,d]=j.useState(null),[u,h]=j.useState(null),[m,f]=j.useState(null),[g,x]=j.useState(null),[y,v]=j.useState(null),[b,w]=j.useState(0),[S,C]=j.useState(0),[E,I]=j.useState(!1),[P,R]=j.useState(!1),D=Vo(n,d),O=l3(i);return e.jsx(QCs,{scope:r,type:a,dir:O,scrollHideDelay:l,scrollArea:c,viewport:u,onViewportChange:h,content:m,onContentChange:f,scrollbarX:g,onScrollbarXChange:x,scrollbarXEnabled:E,onScrollbarXEnabledChange:I,scrollbarY:y,onScrollbarYChange:v,scrollbarYEnabled:P,onScrollbarYEnabledChange:R,onCornerWidthChange:w,onCornerHeightChange:C,children:e.jsx(Ei.div,{dir:O,...o,ref:D,style:{position:"relative","--radix-scroll-area-corner-width":b+"px","--radix-scroll-area-corner-height":S+"px",...t.style}})})},"ScrollArea")),e5s="ScrollAreaViewport",t5s=j.forwardRef(Su(function(t,n){const{__scopeScrollArea:r,children:a,nonce:i,...l}=t,o=Sk(e5s,r),c=j.useRef(null),d=Vo(n,c,o.onViewportChange);return e.jsxs(e.Fragment,{children:[e.jsx(s5s,{nonce:i}),e.jsx(Ei.div,{"data-radix-scroll-area-viewport":"",...l,ref:d,style:{overflowX:o.scrollbarXEnabled?"scroll":"hidden",overflowY:o.scrollbarYEnabled?"scroll":"hidden",...t.style},children:e.jsx("div",{ref:o.onContentChange,style:{minWidth:"100%",display:"table"},children:a})})]})},"ScrollAreaViewport")),s5s=j.memo(Su(function({nonce:t}){return 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:t})},"ScrollAreaViewportStyle"),(s,t)=>s.nonce===t.nonce),PT="ScrollAreaScrollbar",KOt=j.forwardRef(Su(function(t,n){const{forceMount:r,...a}=t,i=Sk(PT,t.__scopeScrollArea),{onScrollbarXEnabledChange:l,onScrollbarYEnabledChange:o}=i,c=t.orientation==="horizontal";return j.useEffect(()=>(c?l(!0):o(!0),()=>{c?l(!1):o(!1)}),[c,l,o]),i.type==="hover"?e.jsx(n5s,{...a,ref:n,forceMount:r}):i.type==="scroll"?e.jsx(r5s,{...a,ref:n,forceMount:r}):i.type==="auto"?e.jsx(YOt,{...a,ref:n,forceMount:r}):i.type==="always"?e.jsx(Yet,{...a,ref:n,"data-state":"visible"}):null},"ScrollAreaScrollbar")),n5s=j.forwardRef(Su(function(t,n){const{forceMount:r,...a}=t,i=Sk(PT,t.__scopeScrollArea),[l,o]=j.useState(!1);return j.useEffect(()=>{const c=i.scrollArea;let d=0;if(c){const u=Su(()=>{window.clearTimeout(d),o(!0)},"handlePointerEnter"),h=Su(()=>{d=window.setTimeout(()=>o(!1),i.scrollHideDelay)},"handlePointerLeave");return c.addEventListener("pointerenter",u),c.addEventListener("pointerleave",h),()=>{window.clearTimeout(d),c.removeEventListener("pointerenter",u),c.removeEventListener("pointerleave",h)}}},[i.scrollArea,i.scrollHideDelay]),e.jsx(xy,{present:r||l,children:e.jsx(YOt,{"data-state":l?"visible":"hidden",...a,ref:n})})},"ScrollAreaScrollbarHover")),r5s=j.forwardRef(Su(function(t,n){const{forceMount:r,...a}=t,i=Sk(PT,t.__scopeScrollArea),l=t.orientation==="horizontal",o=zae(()=>d("SCROLL_END"),100),[c,d]=HOt("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 j.useEffect(()=>{if(c==="idle"){const u=window.setTimeout(()=>d("HIDE"),i.scrollHideDelay);return()=>window.clearTimeout(u)}},[c,i.scrollHideDelay,d]),j.useEffect(()=>{const u=i.viewport,h=l?"scrollLeft":"scrollTop";if(u){let m=u[h];const f=Su(()=>{const g=u[h];m!==g&&(d("SCROLL"),o()),m=g},"handleScroll");return u.addEventListener("scroll",f),()=>u.removeEventListener("scroll",f)}},[i.viewport,l,d,o]),e.jsx(xy,{present:r||c!=="hidden",children:e.jsx(Yet,{"data-state":c==="hidden"?"hidden":"visible",...a,ref:n,onPointerEnter:Ra(t.onPointerEnter,()=>d("POINTER_ENTER")),onPointerLeave:Ra(t.onPointerLeave,()=>d("POINTER_LEAVE"))})})},"ScrollAreaScrollbarScroll")),YOt=j.forwardRef(Su(function(t,n){const r=Sk(PT,t.__scopeScrollArea),{forceMount:a,...i}=t,[l,o]=j.useState(!1),c=t.orientation==="horizontal",d=zae(()=>{if(r.viewport){const u=r.viewport.offsetWidth0&&u<1,onThumbChange:Su(f=>l.current=f,"onThumbChange"),onThumbPointerUp:Su(()=>o.current=0,"onThumbPointerUp"),onThumbPointerDown:Su(f=>o.current=f,"onThumbPointerDown")};function m(f,g){return JOt(f,o.current,c,g)}return Su(m,"getScrollPosition"),r==="horizontal"?e.jsx(a5s,{...h,ref:n,onThumbPositionChange:()=>{if(i.viewport&&l.current){const f=i.viewport.scrollLeft,g=LHe(f,c,i.dir);l.current.style.transform=`translate3d(${g}px, 0, 0)`}},onWheelScroll:f=>{i.viewport&&(i.viewport.scrollLeft=f)},onDragScroll:f=>{i.viewport&&(i.viewport.scrollLeft=m(f,i.dir))}}):r==="vertical"?e.jsx(i5s,{...h,ref:n,onThumbPositionChange:()=>{if(i.viewport&&l.current){const f=i.viewport.scrollTop,g=LHe(f,c);l.current.style.transform=`translate3d(0, ${g}px, 0)`}},onWheelScroll:f=>{i.viewport&&(i.viewport.scrollTop=f)},onDragScroll:f=>{i.viewport&&(i.viewport.scrollTop=m(f))}}):null},"ScrollAreaScrollbarVisible")),a5s=j.forwardRef(Su(function(t,n){const{sizes:r,onSizesChange:a,...i}=t,l=Sk(PT,t.__scopeScrollArea),[o,c]=j.useState(),d=j.useRef(null),u=Vo(n,d,l.onScrollbarXChange);return j.useEffect(()=>{d.current&&c(getComputedStyle(d.current))},[d]),e.jsx(XOt,{"data-orientation":"horizontal",...i,ref:u,sizes:r,style:{bottom:0,left:l.dir==="rtl"?"var(--radix-scroll-area-corner-width)":0,right:l.dir==="ltr"?"var(--radix-scroll-area-corner-width)":0,"--radix-scroll-area-thumb-width":Oae(r)+"px",...t.style},onThumbPointerDown:h=>t.onThumbPointerDown(h.x),onDragScroll:h=>t.onDragScroll(h.x),onWheelScroll:(h,m)=>{if(l.viewport){const f=l.viewport.scrollLeft+h.deltaX;t.onWheelScroll(f),Qet(f,m)&&h.preventDefault()}},onResize:()=>{d.current&&l.viewport&&o&&a({content:l.viewport.scrollWidth,viewport:l.viewport.offsetWidth,scrollbar:{size:d.current.clientWidth,paddingStart:ese(o.paddingLeft),paddingEnd:ese(o.paddingRight)}})}})},"ScrollAreaScrollbarX")),i5s=j.forwardRef(Su(function(t,n){const{sizes:r,onSizesChange:a,...i}=t,l=Sk(PT,t.__scopeScrollArea),[o,c]=j.useState(),d=j.useRef(null),u=Vo(n,d,l.onScrollbarYChange);return j.useEffect(()=>{d.current&&c(getComputedStyle(d.current))},[d]),e.jsx(XOt,{"data-orientation":"vertical",...i,ref:u,sizes:r,style:{top:0,right:l.dir==="ltr"?0:void 0,left:l.dir==="rtl"?0:void 0,bottom:"var(--radix-scroll-area-corner-height)","--radix-scroll-area-thumb-height":Oae(r)+"px",...t.style},onThumbPointerDown:h=>t.onThumbPointerDown(h.y),onDragScroll:h=>t.onDragScroll(h.y),onWheelScroll:(h,m)=>{if(l.viewport){const f=l.viewport.scrollTop+h.deltaY;t.onWheelScroll(f),Qet(f,m)&&h.preventDefault()}},onResize:()=>{d.current&&l.viewport&&o&&a({content:l.viewport.scrollHeight,viewport:l.viewport.offsetHeight,scrollbar:{size:d.current.clientHeight,paddingStart:ese(o.paddingTop),paddingEnd:ese(o.paddingBottom)}})}})},"ScrollAreaScrollbarY")),[o5s,ZOt]=WOt(PT),XOt=j.forwardRef(Su(function(t,n){const{__scopeScrollArea:r,sizes:a,hasThumb:i,onThumbChange:l,onThumbPointerUp:o,onThumbPointerDown:c,onThumbPositionChange:d,onDragScroll:u,onWheelScroll:h,onResize:m,...f}=t,g=Sk(PT,r),[x,y]=j.useState(null),v=Vo(n,y),b=j.useRef(null),w=j.useRef(""),S=g.viewport,C=a.content-a.viewport,E=Yp(h),I=Yp(d),P=zae(m,10);function R(D){if(b.current){const O=D.clientX-b.current.left,U=D.clientY-b.current.top;u({x:O,y:U})}}return Su(R,"handleDragScroll"),j.useEffect(()=>{const D=Su(O=>{const U=O.target;(x==null?void 0:x.contains(U))&&E(O,C)},"handleWheel");return document.addEventListener("wheel",D,{passive:!1}),()=>document.removeEventListener("wheel",D,{passive:!1})},[S,x,C,E]),j.useEffect(I,[a,I]),V7(x,P),V7(g.content,P),e.jsx(o5s,{scope:r,scrollbar:x,hasThumb:i,onThumbChange:Yp(l),onThumbPointerUp:Yp(o),onThumbPositionChange:I,onThumbPointerDown:Yp(c),children:e.jsx(Ei.div,{...f,ref:v,style:{position:"absolute",...f.style},onPointerDown:Ra(t.onPointerDown,D=>{D.button===0&&(D.target.setPointerCapture(D.pointerId),b.current=x.getBoundingClientRect(),w.current=document.body.style.webkitUserSelect,document.body.style.webkitUserSelect="none",g.viewport&&(g.viewport.style.scrollBehavior="auto"),R(D))}),onPointerMove:Ra(t.onPointerMove,R),onPointerUp:Ra(t.onPointerUp,D=>{const O=D.target;O.hasPointerCapture(D.pointerId)&&O.releasePointerCapture(D.pointerId),document.body.style.webkitUserSelect=w.current,g.viewport&&(g.viewport.style.scrollBehavior=""),b.current=null})})})},"ScrollAreaScrollbarImpl")),IHe="ScrollAreaThumb",l5s=j.forwardRef(Su(function(t,n){const{forceMount:r,...a}=t,i=ZOt(IHe,t.__scopeScrollArea);return e.jsx(xy,{present:r||i.hasThumb,children:e.jsx(c5s,{ref:n,...a})})},"ScrollAreaThumb")),c5s=j.forwardRef(Su(function(t,n){const{__scopeScrollArea:r,style:a,...i}=t,l=Sk(IHe,r),o=ZOt(IHe,r),{onThumbPositionChange:c}=o,d=Vo(n,o.onThumbChange),u=j.useRef(void 0),h=zae(()=>{u.current&&(u.current(),u.current=void 0)},100);return j.useEffect(()=>{const m=l.viewport;if(m){const f=Su(()=>{if(h(),!u.current){const g=h5s(m,c);u.current=g,c()}},"handleScroll");return c(),m.addEventListener("scroll",f),()=>m.removeEventListener("scroll",f)}},[l.viewport,h,c]),e.jsx(Ei.div,{"data-state":o.hasThumb?"visible":"hidden",...i,ref:d,style:{width:"var(--radix-scroll-area-thumb-width)",height:"var(--radix-scroll-area-thumb-height)",...a},onPointerDownCapture:Ra(t.onPointerDownCapture,m=>{const g=m.target.getBoundingClientRect(),x=m.clientX-g.left,y=m.clientY-g.top;o.onThumbPointerDown({x,y})}),onPointerUp:Ra(t.onPointerUp,o.onThumbPointerUp)})},"ScrollAreaThumbImpl")),QOt="ScrollAreaCorner",d5s=j.forwardRef(Su(function(t,n){const r=Sk(QOt,t.__scopeScrollArea),a=!!(r.scrollbarX&&r.scrollbarY);return r.type!=="scroll"&&a?e.jsx(u5s,{...t,ref:n}):null},"ScrollAreaCorner")),u5s=j.forwardRef(Su(function(t,n){const{__scopeScrollArea:r,...a}=t,i=Sk(QOt,r),[l,o]=j.useState(0),[c,d]=j.useState(0),u=!!(l&&c),{onCornerWidthChange:h,onCornerHeightChange:m}=i;return V7(i.scrollbarX,()=>{var g;const f=((g=i.scrollbarX)==null?void 0:g.offsetHeight)||0;i.onCornerHeightChange(f),d(f)}),V7(i.scrollbarY,()=>{var g;const f=((g=i.scrollbarY)==null?void 0:g.offsetWidth)||0;i.onCornerWidthChange(f),o(f)}),j.useEffect(()=>()=>{h(0),m(0)},[h,m]),u?e.jsx(Ei.div,{...a,ref:n,style:{width:l,height:c,position:"absolute",right:i.dir==="ltr"?0:void 0,left:i.dir==="rtl"?0:void 0,bottom:0,...t.style}}):null},"ScrollAreaCornerImpl"));function ese(s){return s?parseInt(s,10):0}Su(ese,"toInt");function Zet(s,t){const n=s/t;return isNaN(n)?0:n}Su(Zet,"getThumbRatio");function Oae(s){const t=Zet(s.viewport,s.content),n=s.scrollbar.paddingStart+s.scrollbar.paddingEnd,r=(s.scrollbar.size-n)*t;return Math.max(r,18)}Su(Oae,"getThumbSize");function JOt(s,t,n,r="ltr"){const a=Oae(n),i=a/2,l=t||i,o=a-l,c=n.scrollbar.paddingStart+l,d=n.scrollbar.size-n.scrollbar.paddingEnd-o,u=n.content-n.viewport,h=r==="ltr"?[0,u]:[u*-1,0];return Xet([c,d],h)(s)}Su(JOt,"getScrollPositionFromPointer");function LHe(s,t,n="ltr"){const r=Oae(t),a=t.scrollbar.paddingStart+t.scrollbar.paddingEnd,i=t.scrollbar.size-a,l=t.content-t.viewport,o=i-r,c=n==="ltr"?[0,l]:[l*-1,0],d=wG(s,c);return Xet([0,l],[0,o])(d)}Su(LHe,"getThumbOffsetFromScroll");function Xet(s,t){return n=>{if(s[0]===s[1]||t[0]===t[1])return t[0];const r=(t[1]-t[0])/(s[1]-s[0]);return t[0]+r*(n-s[0])}}Su(Xet,"linearScale");function Qet(s,t){return s>0&&s{})=>{let n={left:s.scrollLeft,top:s.scrollTop},r=0;return Su(function a(){const i={left:s.scrollLeft,top:s.scrollTop},l=n.left!==i.left,o=n.top!==i.top;(l||o)&&t(),n=i,r=window.requestAnimationFrame(a)},"loop")(),()=>window.cancelAnimationFrame(r)},"addUnlinkedScrollListener");function zae(s,t){const n=Yp(s),r=j.useRef(0);return j.useEffect(()=>()=>window.clearTimeout(r.current),[]),j.useCallback(()=>{window.clearTimeout(r.current),r.current=window.setTimeout(n,t)},[n,t])}Su(zae,"useDebounceCallback");function V7(s,t){const n=Yp(t);Ef(()=>{let r=0;if(s){const a=new ResizeObserver(()=>{cancelAnimationFrame(r),r=window.requestAnimationFrame(n)});return a.observe(s),()=>{window.cancelAnimationFrame(r),a.unobserve(s)}}},[s,n])}Su(V7,"useResizeObserver");var e8t=JCs,m5s=t5s,f5s=d5s;const uo=j.forwardRef(({className:s,children:t,...n},r)=>e.jsxs(e8t,{ref:r,className:Pt("relative overflow-hidden",s),...n,children:[e.jsx(m5s,{className:"h-full w-full rounded-[inherit]",children:t}),e.jsx(Bae,{}),e.jsx(f5s,{})]}));uo.displayName=e8t.displayName;const Bae=j.forwardRef(({className:s,orientation:t="vertical",...n},r)=>e.jsx(KOt,{ref:r,orientation:t,className:Pt("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),...n,children:e.jsx(l5s,{className:"relative flex-1 rounded-full bg-border"})}));Bae.displayName=KOt.displayName;const p5s="/assets/levelup-logo-Eif24dqY.png",g5s="/assets/levelup-logo-icon-C-7iromj.png",x5s="/assets/levelup-logo-mobile-B9skSjUG.png";var $ae=s=>s.type==="checkbox",wLe=s=>s.type==="file",yI=s=>s instanceof Date,mv=s=>s==null;const Jet=s=>typeof s=="object";var Sg=s=>!mv(s)&&!Array.isArray(s)&&Jet(s)&&!yI(s),RHe=s=>Sg(s)&&s.target?$ae(s.target)?s.target.checked:wLe(s.target)?s.target.files:s.target.value:s;const y5s=/[.[\]'"]/;var H7=s=>s.split(y5s).filter(Boolean);function v5s(s,t){const n=H7(t);let r=s._formValues,a=s._defaultValues;for(let i=0;it.split(".").some((n,r,a)=>!isNaN(Number(n))&&s.has(a.slice(0,r).join("."))),jLe=typeof window<"u"&&typeof window.HTMLElement<"u"&&typeof document<"u";function qf(s){if(s===null||typeof s!="object")return s;if(s instanceof Date)return new Date(s);const t=typeof Blob<"u"&&s instanceof Blob,n=typeof FileList<"u"&&s instanceof FileList;if(jLe&&(t||n))return s;const r=Array.isArray(s);if(!r&&s.constructor!==Object)return s;const a=r?[]:Object.create(Object.getPrototypeOf(s));for(const i in s)Object.prototype.hasOwnProperty.call(s,i)&&(a[i]=qf(s[i]));return a}const hP={BLUR:"blur",FOCUS_OUT:"focusout",CHANGE:"change",SUBMIT:"submit",TRIGGER:"trigger",VALID:"valid"},zN={onBlur:"onBlur",onChange:"onChange",onSubmit:"onSubmit",onTouched:"onTouched",all:"all"},dv={max:"max",min:"min",maxLength:"maxLength",minLength:"minLength",pattern:"pattern",required:"required",validate:"validate"},b5s=[dv.required,dv.min,dv.max,dv.minLength,dv.maxLength,dv.pattern,dv.validate],lQ="form",s8t="root",ett=["__proto__","constructor","prototype"],_5s=/^\w*$/;var jG=s=>_5s.test(s),$h=s=>s===void 0,Mi=(s,t,n)=>{if(!t||!Sg(s))return n;const r=jG(t)?[t]:H7(t);if(r.some(i=>ett.includes(i)))return n;const a=r.reduce((i,l)=>mv(i)?void 0:i[l],s);return $h(a)||a===s?$h(s[t])?n:s[t]:a},gw=s=>typeof s=="boolean",ob=s=>typeof s=="function",Bh=(s,t,n)=>{let r=-1;const a=jG(t)?[t]:H7(t),i=a.length,l=i-1;for(;++rGt.useContext(ttt);var n8t=(s,t,n,r=!0)=>{const a={};for(const i in s)Object.defineProperty(a,i,{get:()=>{const l=i;return t._proxyFormState[l]!==zN.all&&(t._proxyFormState[l]=!r||zN.all),n&&(n[l]=!0),s[l]}});return a};const ntt=jLe?Gt.useLayoutEffect:Gt.useEffect;var w5s=s=>{const t=s.constructor&&s.constructor.prototype;return Sg(t)&&t.hasOwnProperty("isPrototypeOf")},DHe=s=>mv(s)||!Jet(s);const Mxt=(s,t)=>t.length===0&&!Array.isArray(s)&&!w5s(s);function xw(s,t,n=new WeakMap){if(s===t)return!0;if(DHe(s)||DHe(t))return Object.is(s,t);if(yI(s)&&yI(t))return Object.is(s.getTime(),t.getTime());const r=Object.keys(s),a=Object.keys(t);if(r.length!==a.length)return!1;if(Mxt(s,r)||Mxt(t,a))return Object.is(s,t);if(!r.length&&Array.isArray(s)!==Array.isArray(t))return!1;const i=n.get(s);if(i&&i.has(t))return!0;if(i)i.add(t);else{const l=new WeakSet;l.add(t),n.set(s,l)}for(const l of r){const o=s[l];if(!(l in t))return!1;if(l!=="ref"){const c=t[l];if(yI(o)&&yI(c)||(Sg(o)||Array.isArray(o))&&(Sg(c)||Array.isArray(c))?!xw(o,c,n):!Object.is(o,c))return!1}}return!0}function rtt(s){const t=Gt.useRef(!1),n=Gt.useRef(!1),r=Gt.useRef(void 0),a=Gt.useRef(0);a.current++,!n.current&&s&&(n.current=!0,r.current=qf(s()));const i=Gt.useCallback((o,c,d)=>{if(o&&(t.current||n.current&&a.current>1)){const u=c();xw(r.current,u)||d(u)}t.current=!0},[]),l=Gt.useCallback((o,c)=>{o&&(r.current=qf(c()))},[]);return{resyncIfNeeded:i,snapshot:l}}function j5s(s){const t=stt(),{control:n=t,disabled:r,name:a,exact:i}=s||{},l=()=>({...n._formState,defaultValues:n._defaultValues}),[o,c]=Gt.useState(l),d=Gt.useRef({isDirty:!1,isLoading:!1,dirtyFields:!1,touchedFields:!1,validatingFields:!1,isValidating:!1,isValid:!1,errors:!1}),{resyncIfNeeded:u,snapshot:h}=rtt(l);return ntt(()=>{u(!r,l,c);const m=n._subscribe({name:a,formState:d.current,exact:i,callback:f=>{!r&&c({...n._formState,...f,defaultValues:n._defaultValues})}});return()=>{m(),h(!r,l)}},[n,a,r,i,u,h]),Gt.useEffect(()=>{d.current.isValid&&n._setValid(!0)},[n]),Gt.useMemo(()=>n8t(o,n,d.current,!1),[o,n])}var xv=s=>typeof s=="string",FHe=(s,t,n,r,a)=>xv(s)?(r&&t.watch.add(s),Mi(n,s,a)):Array.isArray(s)?s.map(i=>(r&&t.watch.add(i),Mi(n,i,Mi(a,i)))):(r&&(t.watchAll=!0),n);function N5s(s){const t=stt(),{control:n=t,name:r,defaultValue:a,disabled:i,exact:l,compute:o}=s||{},c=Gt.useRef(a),d=Gt.useRef(o),u=Gt.useRef(n),h=Gt.useRef(r);d.current=o;const m=()=>{const R=n._getWatch(r,c.current);return d.current?d.current(R):R},[f,g]=Gt.useState(m),x=Gt.useRef(f),y=Gt.useCallback(R=>{const D=FHe(r,n._names,R||n._formValues,!1,c.current);return d.current?d.current(D):D},[n._formValues,n._names,r]),v=Gt.useCallback(R=>{if(!i){const D=FHe(r,n._names,R||n._formValues,!1,c.current);if(d.current){const O=d.current(D);xw(O,x.current)||(g(O),x.current=O)}else g(D)}},[n._formValues,n._names,i,r]),{resyncIfNeeded:b,snapshot:w}=rtt(m),S=Gt.useRef(v);S.current=v;const C=Gt.useRef(y);C.current=y,ntt(()=>{u.current!==n||!xw(h.current,r)?(u.current=n,h.current=r,S.current()):b(!i,()=>C.current(),D=>{g(D),x.current=D});const R=n._subscribe({name:r,formState:{values:!0},exact:l,callback:D=>{S.current(D.values)}});return()=>{R(),w(!i,()=>C.current())}},[n,l,r,i,b,w]),Gt.useEffect(()=>n._removeUnmounted());const E=u.current!==n,I=h.current;return Gt.useMemo(()=>{if(i)return!1;const R=!E&&!xw(I,r);return E||R},[i,E,r,I])?y():f}function k5s(s){const t=stt(),{name:n,disabled:r,control:a=t,shouldUnregister:i,defaultValue:l,exact:o=!0}=s,c=t8t(a._names.array,n),d=Gt.useMemo(()=>{const S=Mi(a._formValues,n,Mi(a._defaultValues,n,l));return $h(S)?v5s(a,n):S},[a,n,l]),u=N5s({control:a,name:n,defaultValue:d,exact:o}),h=j5s({control:a,name:n,exact:o}),m=Gt.useRef(s),f=Gt.useRef(null),g=Gt.useRef(a.register(n,{...s.rules,value:u,...gw(s.disabled)?{disabled:s.disabled}:{}}));m.current=s;const x=Gt.useMemo(()=>Object.defineProperties({},{invalid:{enumerable:!0,get:()=>!!Mi(h.errors,n)},isDirty:{enumerable:!0,get:()=>!!Mi(h.dirtyFields,n)},isTouched:{enumerable:!0,get:()=>!!Mi(h.touchedFields,n)},isValidating:{enumerable:!0,get:()=>!!Mi(h.validatingFields,n)},error:{enumerable:!0,get:()=>Mi(h.errors,n)}}),[h,n]),y=Gt.useCallback(S=>{const C=RHe(S);return Mi(a._fields,n)||(g.current=a.register(n,{...m.current.rules,value:C})),g.current.onChange({target:{value:RHe(S),name:n},type:hP.CHANGE})},[n,a]),v=Gt.useCallback(()=>g.current.onBlur({target:{value:Mi(a._formValues,n),name:n},type:hP.BLUR}),[n,a._formValues]),b=Gt.useCallback(S=>{S&&(f.current={focus:()=>ob(S.focus)&&S.focus(),select:()=>ob(S.select)&&S.select(),setCustomValidity:E=>ob(S.setCustomValidity)&&S.setCustomValidity(E),reportValidity:()=>ob(S.reportValidity)&&S.reportValidity()});const C=Mi(a._fields,n);C&&C._f&&S&&(C._f.ref=f.current,C._f._c=!0)},[a._fields,n]),w=Gt.useMemo(()=>({name:n,value:u,...gw(r)||h.disabled?{disabled:h.disabled||r}:{},onChange:y,onBlur:v,ref:b}),[n,r,h.disabled,y,v,b,u]);return Gt.useEffect(()=>{const S=a._options.shouldUnregister||i;g.current=a.register(n,{...m.current.rules,...gw(m.current.disabled)?{disabled:m.current.disabled}:{}});const C=(E,I)=>{const P=Mi(a._fields,E);P&&P._f&&(P._f.mount=I,P._f._c=I)};if(C(n,!0),S){const E=qf(Mi(i?a._defaultValues:a._options.values||a._defaultValues,n,Mi(a._options.defaultValues,n,m.current.defaultValue)));Bh(a._defaultValues,n,E),$h(Mi(a._formValues,n))&&Bh(a._formValues,n,E)}if(!c&&a.register(n,{...m.current.rules,...gw(m.current.disabled)?{disabled:m.current.disabled}:{}}),f.current){const E=Mi(a._fields,n);E&&E._f&&(E._f.ref=f.current)}return()=>{(c?S&&!a._state.action:S)?a.unregister(n):C(n,!1)}},[n,a,c,i]),Gt.useEffect(()=>{a._setDisabledField({disabled:r,name:n})},[r,n,a]),Gt.useMemo(()=>({field:w,formState:h,fieldState:x}),[w,h,x])}const S5s=s=>s.render(k5s(s));var Tce=s=>({isOnSubmit:!s||s===zN.onSubmit,isOnBlur:s===zN.onBlur,isOnChange:s===zN.onChange,isOnAll:s===zN.all,isOnTouch:s===zN.onTouched}),Yze=(s,t,n)=>{if(n)return!1;if(t.watchAll||t.watch.has(s))return!0;for(const r of t.watch)if(s.startsWith(r)&&s.charAt(r.length)===".")return!0;return!1};const gee=(s,t,n)=>{for(const r of n||Object.keys(s)){if(r==="_f")continue;const a=n?Mi(s,r):s[r];if(a){const{_f:i}=a;if(i){if(i.refs&&i.refs[0]&&t(i.refs[0],i.name))return!0;if(i.ref&&t(i.ref,i.name))return!0;if(gee(a,t))return!0}else if((Sg(a)||Array.isArray(a))&&gee(a,t))return!0}}};var Pxt=(s,t,n)=>{const r=Mi(s,n),a=Array.isArray(r)?r:[];return Bh(a,s8t,t[n]),Bh(s,n,a),s},Yx=s=>Sg(s)&&!Object.keys(s).length,jEe=s=>{if(!jLe)return!1;const t=s?s.ownerDocument:0;return s instanceof(t&&t.defaultView?t.defaultView.HTMLElement:HTMLElement)},att=s=>s.type==="radio",NEe=s=>s instanceof RegExp,r8t=(s,t,n,r,a)=>t?{...n[s],types:{...n[s]&&n[s].types?n[s].types:{},[r]:a||!0}}:{};const Ixt={value:!1,isValid:!1},Lxt={value:!0,isValid:!0};var a8t=s=>{if(!Array.isArray(s))return Ixt;if(s.length>1){const n=s.filter(r=>r&&r.checked&&!r.disabled).map(r=>r.value);return{value:n,isValid:!!n.length}}const t=s[0];return!t||!t.checked||t.disabled?Ixt:!t.attributes||!("value"in t.attributes)||$h(t.value)||t.value===""?Lxt:{value:t.value,isValid:!0}};const Rxt={isValid:!1,value:null};var i8t=s=>Array.isArray(s)?s.reduce((t,n)=>n&&n.checked&&!n.disabled?{isValid:!0,value:n.value}:t,Rxt):Rxt;function Dxt(s,t,n="validate"){if(xv(s)||Array.isArray(s)&&s.every(xv)||gw(s)&&!s)return{type:n,message:xv(s)?s:"",ref:t}}var _$=s=>Sg(s)&&!NEe(s)?s:{value:s,message:""},Fxt=async(s,t,n,r,a,i)=>{const{ref:l,refs:o,required:c,maxLength:d,minLength:u,min:h,max:m,pattern:f,validate:g,name:x,valueAsNumber:y,mount:v,_c:b}=s._f,w=Mi(n,x);if(!v||t.has(x))return{};const S=o?o[0]:l,C=V=>{if(a&&S.reportValidity){const G=gw(V)?"":V||"";o?o.forEach(Y=>ob(Y.setCustomValidity)&&Y.setCustomValidity(G)):S.setCustomValidity(G),S.reportValidity()}},E={},I=att(l),P=$ae(l),R=I||P,D=(y||wLe(l))&&$h(l.value)&&$h(w)||jEe(l)&&l.value===""&&!b||w===""||Array.isArray(w)&&!w.length,O=r8t.bind(null,x,r,E),U=(V,G,Y,X=dv.maxLength,ae=dv.minLength)=>{const ie=V?G:Y;E[x]={type:V?X:ae,message:ie,ref:l,...O(V?X:ae,ie)}};if(i?!Array.isArray(w)||!w.length:c&&(!R&&(D||mv(w))||gw(w)&&!w||P&&!a8t(o).isValid||I&&!i8t(o).isValid)){const{value:V,message:G}=xv(c)?{value:!!c,message:c}:_$(c);if(V&&(E[x]={type:dv.required,message:G,ref:S,...O(dv.required,G)},!r))return C(G),E}if(!D&&(!mv(h)||!mv(m))){let V,G;const Y=_$(m),X=_$(h);if(!mv(w)&&!yI(w)&&!isNaN(w)){const ae=l.valueAsNumber||w&&+w;mv(Y.value)||(V=ae>Y.value),mv(X.value)||(G=aenew Date(new Date().toDateString()+" "+J),ne=l.type=="time",te=l.type=="week";xv(Y.value)&&w&&(V=ne?ie(w)>ie(Y.value):te?w>Y.value:ae>new Date(Y.value)),xv(X.value)&&w&&(G=ne?ie(w)+V.value,X=!mv(G.value)&&w.length<+G.value;if((Y||X)&&(U(Y,V.message,G.message),!r))return C(E[x].message),E}if(f&&!D&&xv(w)){const{value:V,message:G}=_$(f);if(NEe(V)&&!w.match(V)&&(E[x]={type:dv.pattern,message:G,ref:l,...O(dv.pattern,G)},!r))return C(G),E}if(g){if(ob(g)){const V=await g(w,n),G=Dxt(V,S);if(G&&(E[x]={...G,...O(dv.validate,G.message)},!r))return C(G.message),E}else if(Sg(g)){let V={};for(const G in g){if(!Yx(V)&&!r)break;const Y=Dxt(await g[G](w,n),S,G);Y&&(V={...Y,...O(G,Y.message)},r||C(Y.message),r&&(E[x]=V))}if(!Yx(V)&&(E[x]={ref:S,...V},!r))return E}}const W=E[x];return C(W?W.message:!0),E},K4e=s=>Array.isArray(s)?s:[s],o8t=s=>Array.isArray(s)?s.filter(Boolean):[];function C5s(s,t){const n=t.length-1;let r=0;for(;rett.includes(String(l))))return s;const r=n.length===1?s:C5s(s,n),a=n.length-1,i=n[a];return r&&delete r[i],a!==0&&(Sg(r)&&Yx(r)||Array.isArray(r)&&A5s(r))&&ux(s,n.slice(0,-1)),s}const itt=Gt.createContext(null);itt.displayName="HookFormContext";const E5s=()=>Gt.useContext(itt),T5s=({children:s,watch:t,getValues:n,getErrors:r,getFieldState:a,setError:i,clearErrors:l,setValue:o,setValues:c,trigger:d,formState:u,resetField:h,reset:m,resetDefaultValues:f,handleSubmit:g,unregister:x,control:y,register:v,setFocus:b,subscribe:w})=>{const S=Gt.useMemo(()=>({watch:t,getValues:n,getErrors:r,getFieldState:a,setError:i,clearErrors:l,setValue:o,setValues:c,trigger:d,formState:u,resetField:h,reset:m,resetDefaultValues:f,handleSubmit:g,unregister:x,control:y,register:v,setFocus:b,subscribe:w}),[l,y,u,r,a,n,g,v,m,f,h,i,b,o,c,w,d,x,t]);return Gt.createElement(itt.Provider,{value:S},Gt.createElement(ttt.Provider,{value:S.control},s))};var Oxt=()=>{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=[]}}};function l8t(s,t){const n=Array.isArray(s)?[]:{};for(const r in s)if(s.hasOwnProperty(r)){const a=s[r],i=t[r];a&&(Sg(a)||Array.isArray(a))&&i?n[r]=l8t(a,i):s[r]&&(n[r]=i)}return n}const zxt=(s,t)=>s!==null&&Jet(s)&&Object.prototype.hasOwnProperty.call(s,t);var M5s=(s,t)=>{if(!t)return!1;let n=s;for(const r of jG(t)?[t]:H7(t)){if(!zxt(n,r))return zxt(s,t);n=n[r]}return!0},c8t=s=>s.type==="select-multiple",P5s=s=>att(s)||$ae(s),Zze=s=>jEe(s)&&s.isConnected;function Bxt(s){return Array.isArray(s)||Sg(s)}function d8t(s,t,n="",r=[]){for(const a in s){const i=n?`${n}.${a}`:a,l=s[a];Bxt(l)&&Bxt(Mi(t,i))?d8t(l,t,i,r):r.push(i)}return r}var I5s=s=>{for(const t in s)if(ob(s[t]))return!0;return!1};function u8t(s){return Array.isArray(s)||Sg(s)&&!I5s(s)}function h8t(s){return!!(s&&"_f"in s)}function m8t(s){return Array.isArray(s)?!s.some(t=>!$h(t)):!Object.keys(s).length}function OHe(s,t){Array.isArray(s)?s[t]=void 0:delete s[t]}function zHe(s,t={},n){for(const r in s){const a=s[r],i=n&&n[r];u8t(a)&&(!Array.isArray(a)||!h8t(i))?(t[r]=Array.isArray(a)?[]:{},zHe(a,t[r],i),m8t(t[r])&&OHe(t,r)):$h(a)||(t[r]=!0)}return t}function GM(s,t,n,r){n||(n=zHe(t,{},r));for(const a in s){const i=s[a],l=r&&r[a];u8t(i)&&(!Array.isArray(i)||!h8t(l))?($h(t)||DHe(n[a])?n[a]=zHe(i,Array.isArray(i)?[]:{},l):GM(i,mv(t)?{}:t[a],n[a],l),m8t(n[a])&&OHe(n,a)):xw(i,t[a])?OHe(n,a):n[a]=!0}return n}var L5s=(s,t)=>{const n=t.split("."),r=[];let a=n[0];for(let i=1;i$h(s)?s:t?s===""?NaN:s&&+s:n&&xv(s)?new Date(s):r?r(s):s;function $xt(s){const t=s.ref;return wLe(t)?t.files:att(t)?i8t(s.refs).value:c8t(t)?[...t.selectedOptions].map(({value:n})=>n):$ae(t)?a8t(s.refs).value:BHe(t.value,s)}var R5s=(s,t,n,r)=>{const a={};for(const i of s){const l=Mi(t,i);l&&Bh(a,i,l._f)}return{criteriaMode:n,names:[...s],fields:a,shouldUseNativeValidation:r}},NZ=s=>$h(s)?s:NEe(s)?s.source:Sg(s)?NEe(s.value)?s.value.source:s.value:s;const Uxt="AsyncFunction";var D5s=s=>{if(!s||!s.validate)return!1;if(ob(s.validate))return s.validate.constructor.name===Uxt;if(Sg(s.validate)){for(const t in s.validate)if(s.validate[t].constructor.name===Uxt)return!0}return!1},F5s=s=>s.mount&&(s.required||!$h(s.required)&&s.required!==!1||!$h(s.min)||!$h(s.max)||!$h(s.maxLength)||!$h(s.minLength)||s.pattern||s.validate);function qxt(s,t,n){const r=Mi(s,n);if(r!=null&&r.type||r!=null&&r.message||Array.isArray(r))return{error:r,name:n};const a=n.split(".");for(;a.length;){const i=a.join("."),l=Mi(t,i),o=Mi(s,i);if(l&&!Array.isArray(l)&&n!==i)return{name:n};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:n}}var O5s=(s,t,n,r)=>{n(s);const a=Object.keys(s).filter(i=>i!=="name");return!a.length||r&&a.length>=Object.keys(t).length||a.find(i=>t[i]===(!r||zN.all))},z5s=(s,t,n)=>!s||!t||s===t||K4e(s).some(r=>r&&(n?r===t||r.startsWith(t+"."):r.startsWith(t)||t.startsWith(r))),B5s=(s,t,n,r,a)=>a.isOnAll?!1:!n&&a.isOnTouch?!(t||s):(n?r.isOnBlur:a.isOnBlur)?!s:(n?r.isOnChange:a.isOnChange)?s:!0,$5s=(s,t)=>{const n=Mi(s,t);!o8t(n).length&&!(n!=null&&n.root)&&ux(s,t)};const U5s={mode:zN.onSubmit,reValidateMode:zN.onChange,shouldFocusError:!0},q5s=(s,t)=>{for(const n in s)n in t||delete s[n];Object.assign(s,t)},f8t={submitCount:0,isDirty:!1,isReady:!1,isValidating:!1,isSubmitted:!1,isSubmitting:!1,isSubmitSuccessful:!1,isValid:!1,touchedFields:{},dirtyFields:{},validatingFields:{}};function V5s(s={}){let t={...U5s,...s},n={...qf(f8t),isLoading:ob(t.defaultValues),errors:t.errors||{},disabled:t.disabled||!1},r={},a=Sg(t.defaultValues)||Sg(t.values)?qf(t.defaultValues||t.values)||{}:{},i=t.shouldUnregister?{}:qf(a),l={action:!1,actionArrayLengths:new Map,mount:!1,watch:!1,keepIsValid:!1},o={mount:new Set,disabled:new Set,unMount:new Set,array:new Set,watch:new Set,registerName:new Set};const c={},d={};let u=0,h=Tce(t.mode),m=Tce(t.reValidateMode);const f={isDirty:!1,dirtyFields:!1,validatingFields:!1,touchedFields:!1,isValidating:!1,isValid:!1,errors:!1},g={...f};let x={...g};const y=(...vt)=>vt.some(gs=>g[gs]||x[gs]),v={array:Oxt(),state:Oxt()};let b=0,w=0,S=t.criteriaMode===zN.all;const C=(vt,gs)=>Ss=>{clearTimeout(d[vt]),d[vt]=setTimeout(gs,Ss)},E=vt=>{clearTimeout(d[vt]),delete d[vt],delete c[vt]},I=vt=>{E(vt);const gs=`${vt}.`;for(const Ss of Object.keys(c))Ss.startsWith(gs)&&E(Ss)},P=async vt=>{if(!l.keepIsValid&&!t.disabled&&(y("isValid")||vt)){const gs=++b;let Ss;t.resolver?(Ss=Yx((await ie()).errors),gs===b&&R()):Ss=await J({fields:r,onlyCheckValid:!0,eventType:hP.VALID}),gs===b&&Ss!==n.isValid&&v.state.next({isValid:Ss})}},R=(vt,gs)=>{!t.disabled&&y("isValidating","validatingFields")&&((vt||o.mount).forEach(Ss=>{Ss&&(gs?Bh(n.validatingFields,Ss,gs):ux(n.validatingFields,Ss))}),v.state.next({validatingFields:n.validatingFields,isValidating:!Yx(n.validatingFields)}))},D=()=>{n.dirtyFields=GM(a,i,void 0,r)},O=(vt,gs=[],Ss,Is,Ys=!0,cs=!0)=>{if(Is&&Ss&&!t.disabled){l.action=!0;const js=Mi(r,vt);if(l.actionArrayLengths.has(vt)||l.actionArrayLengths.set(vt,Array.isArray(js)?js.length:0),cs&&Array.isArray(js)){const gn=Ss(js,Is.argA,Is.argB);Ys&&Bh(r,vt,gn)}const kn=Mi(n.errors,vt);if(cs&&Array.isArray(kn)){const gn=kn.root,As=Ss(kn,Is.argA,Is.argB)||kn;gn&&(As.root=gn),Ys&&Bh(n.errors,vt,As),$5s(n.errors,vt)}const Ws=Mi(n.touchedFields,vt),On=cs&&Array.isArray(Ws);if(On){const gn=Ss(Ws,Is.argA,Is.argB);Ys&&Bh(n.touchedFields,vt,gn)}const ds=Mi(n.dirtyFields,vt);if(cs&&Array.isArray(ds)){const gn=Ss(ds,Is.argA,Is.argB)||ds;Ys&&Bh(n.dirtyFields,vt,gn)}y("dirtyFields")&&D(),v.state.next({name:vt,isDirty:_e(vt,gs),dirtyFields:n.dirtyFields,...On&&{touchedFields:n.touchedFields},errors:n.errors,isValid:n.isValid})}else Bh(i,vt,gs)},U=(vt,gs)=>{Bh(n.errors,vt,gs),n.errors={...n.errors},v.state.next({errors:n.errors})},W=vt=>{Object.keys(c).forEach(E);const gs=!Yx(vt);n.errors=vt,v.state.next({errors:n.errors,...gs?{isValid:!1}:{}}),!gs&&l.mount&&P()},V=vt=>{const gs=jG(vt)?[vt]:H7(vt);let Ss=i,Is=a;for(let Ys=0;Ys{if(!l.actionArrayLengths.size)return!1;const gs=jG(vt)?[vt]:H7(vt);let Ss=i,Is="",Ys=-1,cs=0;for(let js=0;js=Ss.length)return Ys===-1?!1:js===Ys?+knYs&&+gs[Ys]{const Ys=Mi(r,vt);if(Ys){if(V(vt)||G(vt))return;const cs=$h(Mi(i,vt)),js=Mi(i,vt,$h(Ss)?Mi(a,vt):Ss);$h(js)||Is&&Is.defaultChecked||gs?Bh(i,vt,gs?js:$xt(Ys._f)):ve(vt,js),l.mount&&!l.action&&(t.resolver&&y("isValidating","validatingFields")?Promise.resolve().then(()=>P()):P(),cs&&n.isDirty&&y("isDirty")&&(_e()||(n.isDirty=!1,v.state.next({...n}))),s.shouldUnregister&&cs&&!$h(Mi(i,vt))&&Yze(vt,o)&&(l.watch=!0))}},X=(vt,gs,Ss,Is,Ys)=>{let cs=!1,js=!1;const kn={name:vt};if(!t.disabled||Is===!0){if(!Ss||Is){const Ws=xw(Mi(a,vt),gs);y("isDirty")&&(js=n.isDirty,n.isDirty=kn.isDirty=!Ws||_e(),cs=js!==kn.isDirty),js=!!Mi(n.dirtyFields,vt),Ws!==n.isDirty?q5s(n.dirtyFields,GM(a,i,void 0,r)):Ws?ux(n.dirtyFields,vt):Bh(n.dirtyFields,vt,!0),kn.dirtyFields=n.dirtyFields,cs=cs||y("dirtyFields")&&js!==!Ws}if(Ss){const Ws=Mi(n.touchedFields,vt);Ws||(Bh(n.touchedFields,vt,Ss),kn.touchedFields=n.touchedFields,cs=cs||y("touchedFields")&&Ws!==Ss)}cs&&Ys&&v.state.next(kn)}return cs?kn:{}},ae=(vt,gs,Ss,Is)=>{const Ys=Mi(n.errors,vt),cs=y("isValid")&&gw(gs)&&n.isValid!==gs;if(t.delayError&&Ss?(c[vt]=C(vt,()=>U(vt,Ss)),c[vt](t.delayError)):(E(vt),Ss?Bh(n.errors,vt,Ss):ux(n.errors,vt),n.errors={...n.errors}),(Ss?!xw(Ys,Ss):Ys)||!Yx(Is)||cs){const js={...Is,...cs&&gw(gs)?{isValid:gs}:{},errors:n.errors,name:vt};v.state.next(js)}},ie=async vt=>(R(vt,!0),await t.resolver(i,t.context,R5s(vt||o.mount,r,t.criteriaMode,t.shouldUseNativeValidation))),ne=async vt=>{const gs=w,{errors:Ss}=await ie(vt);if(gs!==w)return Ss;if(R(vt),vt){for(const Is of vt){const Ys=Mi(Ss,Is);I(Is);const cs=o.array.has(Is)&&Sg(Ys)&&!Object.keys(Ys).some(Ws=>!Number.isNaN(Number(Ws))),js=Mi(r,Is),kn=Sg(js)&&Object.keys(js).some(Ws=>Ws!=="_f");cs?Pxt(n.errors,{[Is]:Ys},Is):Ys!=null&&Ys.type||Ys!=null&&Ys.message||Array.isArray(Ys)||Sg(Ys)&&kn?Bh(n.errors,Is,Ys):ux(n.errors,Is)}n.errors={...n.errors}}else Object.keys(c).forEach(E),n.errors=Ss;return Ss},te=async({name:vt,eventType:gs})=>{if(t.validate){const Ss=w,Is=await t.validate({formValues:i,formState:n,name:vt,eventType:gs});if(Ss!==w)return!0;if(Sg(Is)){let Ys=!0;ze(lQ);for(const cs in Is){const js=Is[cs];js&&(Ys=!1,$e(`${lQ}.${cs}`,{message:xv(js.message)?js.message:"",type:js.type||dv.validate}))}return Ys}else return xv(Is)||!Is?($e(lQ,{message:Is||"",type:dv.validate}),!1):(ze(lQ),!0)}return!0},J=async({fields:vt,onlyCheckValid:gs,name:Ss,eventType:Is,context:Ys={valid:!0,runRootValidation:!1}})=>{const cs=w;if(t.validate&&!Ys.runRootValidation&&(Ys.runRootValidation=!0,!await te({name:Ss,eventType:Is})&&(Ys.valid=!1,gs)))return Ys.valid;for(const js in vt){const kn=vt[js];if(kn){const{_f:Ws,...On}=kn;if(Ws){const ds=o.array.has(Ws.name),gn=kn._f&&D5s(kn._f),As=y("isValidating","validatingFields");gn&&As&&R([Ws.name],!0);const hr=await Fxt(kn,o.disabled,i,S,t.shouldUseNativeValidation&&!gs,ds);if(cs!==w)return Ys.valid;if(gn&&As&&R([Ws.name]),hr[Ws.name]&&(Ys.valid=!1,gs)||(gs||(E(Ws.name),Mi(hr,Ws.name)?ds?Pxt(n.errors,hr,Ws.name):Bh(n.errors,Ws.name,hr[Ws.name]):ux(n.errors,Ws.name)),s.shouldUseNativeValidation&&hr[Ws.name]))break}!Yx(On)&&await J({context:Ys,onlyCheckValid:gs,fields:On,name:js,eventType:Is})}}return Ys.valid},ce=()=>{for(const vt of o.unMount){const gs=Mi(r,vt);gs&&(gs._f.refs?gs._f.refs.every(Ss=>!Zze(Ss)):!Zze(gs._f.ref))&&at(vt)}o.unMount=new Set},_e=(vt,gs)=>(vt&&gs&&Bh(i,vt,gs),!xw(l.mount?i:a,a)),he=(vt,gs,Ss)=>FHe(vt,o,{...l.mount?i:$h(gs)||xv(vt)?a:gs},Ss,gs),ue=vt=>o8t(Mi(l.mount?i:a,vt,t.shouldUnregister?Mi(a,vt,[]):[])),ve=(vt,gs,Ss={},Is=!1,Ys=!1,cs=!1)=>{const js=Mi(r,vt);let kn=gs;if(js){const Ws=js._f;Ws&&(!Ws.disabled&&Bh(i,vt,BHe(gs,Ws)),kn=jEe(Ws.ref)&&mv(gs)?"":gs,c8t(Ws.ref)?[...Ws.ref.options].forEach(On=>On.selected=kn.includes(On.value)):Ws.refs?$ae(Ws.ref)?Ws.refs.forEach(On=>{(!On.defaultChecked||!On.disabled)&&(Array.isArray(kn)?On.checked=!!kn.find(ds=>ds===On.value):On.checked=kn===On.value||!!kn)}):Ws.refs.forEach(On=>On.checked=On.value===kn):wLe(Ws.ref)?Ws.ref.value="":(Ws.ref.value=kn,!Ws.ref.type&&!Ys&&!cs&&v.state.next({name:vt,values:Is?i:qf(i)})))}(Ss.shouldDirty||Ss.shouldTouch)&&X(vt,js&&js._f&&!js._f.disabled&&(js._f.valueAsNumber||js._f.valueAsDate||js._f.setValueAs)?BHe(gs,js._f):kn,Ss.shouldTouch,Ss.shouldDirty,!Ys),Ss.shouldValidate&&je(vt,{delayError:Ss.delayError}),Ss.shouldValidate&&js&&js._f&&js._f.deps&&(!Array.isArray(js._f.deps)||js._f.deps.length>0)&&je(js._f.deps)},Ee=(vt,gs,Ss,Is=!1,Ys=!1,cs=!1)=>{o.array.has(vt)&&v.array.next({name:vt,values:Is?i:qf(i)});for(const js in gs){if(!gs.hasOwnProperty(js))continue;const kn=gs[js],Ws=vt+"."+js,On=Mi(r,Ws);(o.array.has(vt)||Sg(kn)||On&&!On._f)&&!yI(kn)?Ee(Ws,kn,Ss,Is,Ys,cs):ve(Ws,kn,Ss,Is,Ys,cs)}},Se=(vt,gs,Ss,Is,Ys=!1)=>{const cs=Mi(r,vt),js=o.array.has(vt),kn=Is?gs:qf(gs),Ws=Mi(i,vt),On=xw(Ws,kn);if(On||Bh(i,vt,kn),js)v.array.next({name:vt,values:Is?i:qf(i)}),y("isDirty","dirtyFields")&&Ss.shouldDirty&&(D(),Ys||v.state.next({name:vt,dirtyFields:n.dirtyFields,isDirty:_e(vt,kn)})),Ss.shouldValidate&&je(vt,{delayError:Ss.delayError});else{const ds=Array.isArray(kn)&&!kn.length||Yx(kn),gn=!On&&!Ys;!cs||cs._f||mv(kn)||ds?ve(vt,kn,Ss,Is,Ys,gn):Ee(vt,kn,Ss,Is,Ys,gn)}if(!On&&!Ys){const ds=Yze(vt,o),gn=Is?i:qf(i);if(v.state.next({...ds&&n,name:l.mount||ds?vt:void 0,values:gn}),!js)for(const As of L5s(o.array,vt))v.state.next({name:As,values:gn})}},Le=(vt,gs,Ss={})=>Se(vt,gs,Ss,!1),Fe=(vt,gs={})=>{const Ss=ob(vt)?vt(i):vt;if(!xw(i,Ss)){i={...i,...Ss};for(const Is of o.mount)M5s(Ss,Is)&&Se(Is,Mi(Ss,Is),gs,!0,!0);v.state.next({...n,name:void 0,type:void 0,...u?{values:i}:{}}),gs.shouldValidate&&P()}},ke=async vt=>{l.mount=!0;const gs=vt.target;let Ss=gs.name,Is=!0;const Ys=Mi(r,Ss),cs=js=>{Is=Number.isNaN(js)||yI(js)&&isNaN(js.getTime())||xw(js,Mi(i,Ss,js))};if(Ys){let js,kn;const Ws=gs.type?$xt(Ys._f):RHe(vt),On=vt.type===hP.BLUR||vt.type===hP.FOCUS_OUT,ds=!F5s(Ys._f)&&!t.validate&&!t.resolver&&!Mi(n.errors,Ss)&&!Ys._f.deps,gn=ds||B5s(On,Mi(n.touchedFields,Ss),n.isSubmitted,m,h),As=Yze(Ss,o,On);if(Bh(i,Ss,qf(Ws)),On){if(!gs||!gs.readOnly){Ys._f.onBlur&&Ys._f.onBlur(vt);const qn=c[Ss];qn&&qn(0)}}else Ys._f.onChange&&Ys._f.onChange(vt);const hr=X(Ss,Ws,On),Er=!Yx(hr)||As;if(!On&&v.state.next({name:Ss,type:vt.type,...u?{values:qf(i)}:{}}),gn)return(!ds||!n.isValid)&&y("isValid")&&(t.mode==="onBlur"?On&&P():On||P()),Er&&v.state.next({name:Ss,...As?{}:hr});if(!t.resolver&&t.validate&&await te({name:Ss,eventType:vt.type}),!On&&As&&v.state.next({...n}),t.resolver){const qn=w,{errors:hn}=await ie([Ss]);if(qn!==w)return;if(R([Ss]),cs(Ws),!Is){!Yx(hr)&&v.state.next(hr);return}const Fn=qxt(n.errors,r,Ss),vn=qxt(hn,r,Fn.name||Ss);js=vn.error,Ss=vn.name,kn=Yx(hn)}else{const qn=w;if(R([Ss],!0),js=(await Fxt(Ys,o.disabled,i,S,t.shouldUseNativeValidation))[Ss],qn!==w)return;if(R([Ss]),cs(Ws),Is){if(js)kn=!1;else if(y("isValid")&&(kn=await J({fields:r,onlyCheckValid:!0,name:Ss,eventType:vt.type}),qn!==w))return}}Is&&(Ys._f.deps&&(!Array.isArray(Ys._f.deps)||Ys._f.deps.length>0)&&je(Ys._f.deps),ae(Ss,kn,js,hr))}},Ve=(vt,gs)=>{if(Mi(n.errors,gs)&&vt.focus)return vt.focus(),1},je=async(vt,gs={})=>{let Ss,Is;const Ys=K4e(vt);if(t.resolver){const cs=w,js=await ne($h(vt)?vt:Ys);if(Ss=Yx(js),Is=vt?!Ys.some(kn=>Mi(js,kn)):Ss,cs!==w)return Is}else vt?(Is=(await Promise.all(Ys.map(async cs=>{const js=Mi(r,cs);return await J({fields:js&&js._f?{[cs]:js}:js,eventType:hP.TRIGGER})}))).every(Boolean),!(!Is&&!n.isValid)&&P()):Is=Ss=await J({fields:r,name:vt,eventType:hP.TRIGGER});if(gs.delayError&&t.delayError&&xv(vt)){const cs=Mi(n.errors,vt);cs?(ux(n.errors,vt),c[vt]=C(vt,()=>U(vt,cs)),c[vt](t.delayError)):E(vt)}if(gs.shouldTouch)for(const cs of vt?Ys:o.mount)!o.array.has(cs)&&Bh(n.touchedFields,cs,!0);return v.state.next({...!xv(vt)||y("isValid")&&Ss!==n.isValid?{}:{name:vt},...t.resolver||!vt?{isValid:Ss}:{},...gs.shouldTouch&&y("touchedFields")?{touchedFields:n.touchedFields}:{},errors:n.errors}),gs.shouldFocus&&!Is&&gee(r,Ve,vt?Ys:o.mount),Is},Ae=(vt,gs)=>{let Ss={...l.mount?i:a};return gs&&(Ss=l8t(gs.dirtyFields?n.dirtyFields:n.touchedFields,Ss)),$h(vt)?Ss:xv(vt)?Mi(Ss,vt):vt.map(Is=>Mi(Ss,Is))},Ce=vt=>$h(vt)?{...n.errors}:xv(vt)?Mi(n.errors,vt):vt.map(gs=>Mi(n.errors,gs)),qe=(vt,gs)=>{const Ss=gs||n,Is=Mi(Ss.errors,vt);return{invalid:!!Is,isDirty:!!Mi(Ss.dirtyFields,vt),error:Is,isValidating:!!Mi(Ss.validatingFields,vt),isTouched:!!Mi(Ss.touchedFields,vt)}},ze=vt=>{const gs=vt?K4e(vt):void 0;gs?gs.forEach(Ss=>{I(Ss),ux(n.errors,Ss),v.state.next({name:Ss,errors:n.errors})}):(Object.keys(c).forEach(E),n.errors={},v.state.next({errors:n.errors}))},$e=(vt,gs,Ss)=>{I(vt);const Is=(Mi(r,vt,{_f:{}})._f||{}).ref,Ys=Mi(n.errors,vt)||{},{ref:cs,message:js,type:kn,types:Ws,...On}=Ys;Bh(n.errors,vt,{...On,...gs,ref:Is}),v.state.next({name:vt,errors:n.errors,isValid:!1}),Ss&&Ss.shouldFocus&&Is&&Is.focus&&Is.focus()},ct=(vt,gs)=>{if(ob(vt)){u++;const{unsubscribe:Ss}=v.state.subscribe({next:Ys=>"values"in Ys&&vt(Ys.values||he(void 0,gs),Ys)});let Is=!1;return{unsubscribe:()=>{Is||(Is=!0,u--,Ss())}}}return he(vt,gs,!0)},Xe=vt=>{var gs;const Ss=!!(!((gs=vt.formState)===null||gs===void 0)&&gs.values);Ss&&u++;const{unsubscribe:Is}=v.state.subscribe({next:cs=>{if(z5s(vt.name,cs.name,vt.exact)&&O5s(cs,vt.formState||g,Ft,vt.reRenderRoot)){const js={...i};vt.callback({values:js,...n,...cs,defaultValues:a})}}});if(!Ss)return Is;let Ys=!1;return()=>{Ys||(Ys=!0,u--,Is())}},it=vt=>(l.mount=!0,x={...x,...vt.formState},Xe({...vt,formState:{...f,...vt.formState}})),at=(vt,gs={})=>{for(const Ss of vt?K4e(vt):o.mount)o.mount.delete(Ss),o.array.delete(Ss),o.disabled.delete(Ss),gs.keepValue||(ux(r,Ss),ux(i,Ss)),gs.keepError||(I(Ss),ux(n.errors,Ss)),!gs.keepDirty&&ux(n.dirtyFields,Ss),!gs.keepTouched&&ux(n.touchedFields,Ss),!gs.keepIsValidating&&ux(n.validatingFields,Ss),!t.shouldUnregister&&!gs.keepDefaultValue&&ux(a,Ss);u&&v.state.next({values:qf(i)}),v.state.next({...n,...gs.keepDirty?{}:{isDirty:_e()},...gs.keepIsValidating?{}:{isValidating:!Yx(n.validatingFields)}}),!gs.keepIsValid&&P()},Ke=({disabled:vt,name:gs})=>{if(gw(vt)&&l.mount||vt||o.disabled.has(gs)){const Ys=o.disabled.has(gs)!==!!vt;vt?o.disabled.add(gs):o.disabled.delete(gs),Ys&&l.mount&&!l.action&&P()}},nt=(vt,gs={})=>{let Ss=Mi(r,vt);const Is=gw(gs.disabled)||gw(t.disabled),Ys=!o.registerName.has(vt)&&Ss&&Ss._f&&!Ss._f.mount;if(Bh(r,vt,{...Ss||{},_f:{...Ss&&Ss._f?Ss._f:{ref:{name:vt}},name:vt,mount:!0,...gs}}),o.mount.add(vt),Ss&&Ss._f){const cs=Mi(r,vt);for(const js of b5s)js in gs||delete cs._f[js]}return Ss&&!Ys?Ke({disabled:gw(gs.disabled)?gs.disabled:t.disabled,name:vt}):Y(vt,!0,gs.value),{...Is?{disabled:gs.disabled||t.disabled}:{},...t.progressive?{required:!!gs.required,min:NZ(gs.min),max:NZ(gs.max),minLength:NZ(gs.minLength),maxLength:NZ(gs.maxLength),pattern:NZ(gs.pattern)}:{},name:vt,onChange:ke,onBlur:ke,ref:cs=>{if(cs){o.registerName.add(vt),nt(vt,gs),o.registerName.delete(vt),Ss=Mi(r,vt);const js=$h(cs.value)&&cs.querySelectorAll&&cs.querySelectorAll("input,select,textarea")[0]||cs,kn=P5s(js),Ws=Ss._f.refs||[];if(kn?Ws.find(ds=>ds===js):js===Ss._f.ref)return;const On={...Ss._f};kn?(On.refs=[...Ws.filter(Zze),js,...Array.isArray(Mi(a,vt))?[{}]:[]],On.ref={type:js.type,name:vt}):(On.ref=js,delete On.refs),Bh(r,vt,{_f:On}),Y(vt,!1,void 0,js)}else Ss=Mi(r,vt,{}),Ss._f&&(Ss._f.mount=!1),(t.shouldUnregister||gs.shouldUnregister)&&!(t8t(o.array,vt)&&l.action)&&o.unMount.add(vt)}}},xt=()=>t.shouldFocusError&&!t.shouldUseNativeValidation&&gee(r,Ve,o.mount),rt=vt=>{gw(vt)&&(v.state.next({disabled:vt}),gee(r,(gs,Ss)=>{const Is=Mi(r,Ss);Is&&(gs.disabled=Is._f.disabled||vt,Array.isArray(Is._f.refs)&&Is._f.refs.forEach(Ys=>{Ys.disabled=Is._f.disabled||vt}))},0))},Yt=(vt,gs)=>async Ss=>{let Is,Ys;Ss&&(Ss.preventDefault&&Ss.preventDefault(),Ss.persist&&Ss.persist());let cs=qf(i);if(v.state.next({isSubmitting:!0}),t.resolver){const js=w,{errors:kn,values:Ws}=await ie();if(js!==w)return;R(),Object.keys(c).forEach(E),n.errors=kn,cs=qf(Ws)}else{const js=w;if(await J({fields:r,eventType:hP.SUBMIT}),js!==w)return;ux(n.errors,s8t)}if(o.disabled.size)for(const js of o.disabled)ux(cs,js);if(Yx(n.errors)){v.state.next({errors:{}});try{Is=await vt(cs,Ss)}catch(js){Ys=js}}else gs&&await gs({...n.errors},Ss),xt(),setTimeout(xt);if(v.state.next({isSubmitted:!0,isSubmitting:!1,isSubmitSuccessful:Yx(n.errors)&&!Ys,submitCount:n.submitCount+1,errors:n.errors}),Ys)throw Ys;return Is},qt=(vt,gs={})=>{Mi(r,vt)&&(ux(n.validatingFields,vt),$h(gs.defaultValue)?Le(vt,qf(Mi(a,vt))):(Le(vt,gs.defaultValue),Bh(a,vt,qf(gs.defaultValue))),gs.keepTouched||ux(n.touchedFields,vt),gs.keepDirty||(ux(n.dirtyFields,vt),n.isDirty=gs.defaultValue?_e(vt,qf(Mi(a,vt))):_e()),gs.keepError||(I(vt),ux(n.errors,vt),P()),v.state.next({...n,isValidating:!Yx(n.validatingFields)}))},ts=(vt,gs={})=>{w++;const Ss=vt?qf(vt):a,Is=qf(Ss),Ys=Yx(vt),cs=Is,js=r;if(Object.keys(c).forEach(E),gs.keepDefaultValues||(a=Ss),!gs.keepValues){if(gs.keepDirtyValues){const kn=new Set([...o.mount,...d8t(GM(a,i,void 0,js),n.dirtyFields)]);for(const Ws of kn){const On=Mi(n.dirtyFields,Ws),ds=Mi(i,Ws),gn=Mi(cs,Ws);On&&!$h(ds)?Bh(cs,Ws,ds):!On&&!$h(gn)&&Le(Ws,gn)}}else{if(jLe&&$h(vt))for(const kn of o.mount){const Ws=Mi(r,kn);if(Ws&&Ws._f){const On=Array.isArray(Ws._f.refs)?Ws._f.refs[0]:Ws._f.ref;if(jEe(On)){const ds=On.closest("form");if(ds){ds.reset();break}}}}if(gs.keepFieldsRef)for(const kn of o.mount)Le(kn,Mi(cs,kn));else r={}}if(t.shouldUnregister){if(i=gs.keepDefaultValues?qf(a):{},gs.keepFieldsRef)for(const kn of o.mount)Bh(i,kn,Mi(cs,kn))}else i=qf(cs);v.array.next({values:{...cs}}),v.state.next({name:void 0,type:void 0,values:{...cs}})}o={mount:gs.keepDirtyValues?o.mount:new Set,unMount:new Set,array:new Set,registerName:new Set,disabled:new Set,watch:new Set,watchAll:!1,focus:""},l.mount=!g.isValid||!!gs.keepIsValid||!!gs.keepDirtyValues||!t.shouldUnregister&&!Yx(cs),l.watch=!!t.shouldUnregister,l.keepIsValid=!!gs.keepIsValid,l.action=!1,l.actionArrayLengths.clear(),gs.keepErrors||(n.errors={}),v.state.next({submitCount:gs.keepSubmitCount?n.submitCount:0,isDirty:Ys?!1:gs.keepDirty?n.isDirty:gs.keepValues?_e():!!(gs.keepDefaultValues&&!xw(vt,a)),isSubmitted:gs.keepIsSubmitted?n.isSubmitted:!1,dirtyFields:Ys?{}:gs.keepDirtyValues?gs.keepDefaultValues&&i?GM(a,i,void 0,js):n.dirtyFields:gs.keepDefaultValues&&vt?GM(a,vt,void 0,js):gs.keepDirty?n.dirtyFields:gs.keepValues?GM(a,i,void 0,js):{},touchedFields:gs.keepTouched?n.touchedFields:{},...!gs.keepIsValidating&&(n.isValidating||!Yx(n.validatingFields))?{validatingFields:{},isValidating:!1}:null,errors:gs.keepErrors?n.errors:{},isSubmitSuccessful:gs.keepIsSubmitSuccessful?n.isSubmitSuccessful:!1,isSubmitting:!1,defaultValues:a})},ys=(vt,gs)=>ts(ob(vt)?vt(i):vt,{...t.resetOptions,...gs}),Bt=(vt,gs={})=>{const Ss=Mi(r,vt),Is=Ss&&Ss._f;if(Is){const Ys=Is.refs?Is.refs[0]:Is.ref;Ys.focus&&setTimeout(()=>{Ys.focus(),gs.shouldSelect&&ob(Ys.select)&&Ys.select()})}},Ft=vt=>{const{name:gs,type:Ss,values:Is,...Ys}=vt;n={...n,...Ys}};v.state.subscribe({next:Ft});const Xs={control:{register:nt,unregister:at,getFieldState:qe,handleSubmit:Yt,setError:$e,_subscribe:Xe,_runSchema:ie,_updateIsValidating:R,_focusError:xt,_getWatch:he,_getDirty:_e,_setValid:P,_setFieldArray:O,_setDisabledField:Ke,_setErrors:W,_getFieldArray:ue,_reset:ts,_resetDefaultValues:()=>ob(t.defaultValues)&&t.defaultValues().then(vt=>{ys(vt,t.resetOptions),v.state.next({isLoading:!1})}),_removeUnmounted:ce,_disableForm:rt,_subjects:v,_proxyFormState:g,get _fields(){return r},get _formValues(){return i},get _state(){return l},set _state(vt){l=vt},get _defaultValues(){return a},get _names(){return o},set _names(vt){o=vt},get _formState(){return n},get _options(){return t},set _options(vt){t={...t,...vt},h=Tce(t.mode),m=Tce(t.reValidateMode),S=t.criteriaMode===zN.all}},subscribe:it,trigger:je,register:nt,handleSubmit:Yt,watch:ct,setValue:Le,setValues:Fe,getValues:Ae,getErrors:Ce,reset:ys,resetField:qt,resetDefaultValues:(vt,gs={})=>{if(a=qf(vt),!gs.keepDirty){const Ss=GM(a,i,void 0,r);n.dirtyFields=Ss,n.isDirty=!Yx(Ss)}gs.keepIsValid||P(),v.state.next({...n,defaultValues:a})},clearErrors:ze,unregister:at,setError:$e,setFocus:Bt,getFieldState:qe};return{...Xs,formControl:Xs}}function NLe(s={}){const t=Gt.useRef(void 0),n=Gt.useRef(void 0),r=Gt.useRef(s.formControl),a=Gt.useRef(!!s.validate),[i,l]=Gt.useState(()=>({...qf(f8t),isLoading:ob(s.defaultValues),errors:s.errors||{},disabled:s.disabled||!1,defaultValues:ob(s.defaultValues)?void 0:s.defaultValues}));if(!t.current||s.formControl&&r.current!==s.formControl)if(r.current=s.formControl,s.formControl)t.current={...s.formControl,formState:i},s.defaultValues&&!ob(s.defaultValues)&&s.formControl.reset(s.defaultValues,s.resetOptions);else{const{formControl:h,...m}=V5s(s);t.current={...m,formState:i}}const o=t.current.control;o._options={...s,validate:s.validate};const c=()=>({...o._formState,defaultValues:o._defaultValues}),{resyncIfNeeded:d,snapshot:u}=rtt(c);return ntt(()=>{d(!0,c,l);const h=o._subscribe({formState:o._proxyFormState,callback:()=>l({...o._formState,defaultValues:o._defaultValues}),reRenderRoot:!0});return l(m=>({...m,isReady:!0})),o._formState.isReady=!0,()=>{h(),u(!0,c)}},[o,d,u]),Gt.useEffect(()=>o._disableForm(s.disabled),[o,s.disabled]),Gt.useEffect(()=>{s.mode&&(o._options.mode=s.mode),s.reValidateMode&&(o._options.reValidateMode=s.reValidateMode)},[o,s.mode,s.reValidateMode]),Gt.useEffect(()=>{s.errors&&(o._setErrors(s.errors),o._focusError())},[o,s.errors]),Gt.useEffect(()=>{var h;a.current&&!s.validate&&((h=t.current)===null||h===void 0||h.clearErrors(lQ)),a.current=!!s.validate},[s.validate]),Gt.useEffect(()=>{s.shouldUnregister&&o._subjects.state.next({values:o._getWatch()})},[o,s.shouldUnregister]),Gt.useEffect(()=>{if(o._proxyFormState.isDirty){const h=o._getDirty();h!==i.isDirty&&o._subjects.state.next({isDirty:h})}},[o,i.isDirty]),Gt.useEffect(()=>{var h;s.values&&!xw(s.values,n.current)?(o._reset(s.values,{keepFieldsRef:!0,...o._options.resetOptions}),!((h=o._options.resetOptions)===null||h===void 0)&&h.keepIsValid||o._setValid(),n.current=s.values,l(m=>({...m}))):o._resetDefaultValues()},[o,s.values]),Gt.useEffect(()=>{o._state.mount||(o._setValid(),o._state.mount=!0),o._state.watch&&(o._state.watch=!1,o._subjects.state.next({...o._formState})),o._removeUnmounted()}),t.current.formState=Gt.useMemo(()=>n8t(i,o),[o,i]),t.current}const Vxt=(s,t,n)=>{if(s&&"reportValidity"in s){const r=Mi(n,t);s.setCustomValidity(r&&r.message||""),s.reportValidity()}},p8t=(s,t)=>{for(const n in t.fields){const r=t.fields[n];r&&r.ref&&"reportValidity"in r.ref?Vxt(r.ref,n,s):r.refs&&r.refs.forEach(a=>Vxt(a,n,s))}},H5s=(s,t)=>{t.shouldUseNativeValidation&&p8t(s,t);const n={};for(const r in s){const a=Mi(t.fields,r),i=Object.assign(s[r]||{},{ref:a&&a.ref});if(G5s(t.names||Object.keys(s),r)){const l=Object.assign({},Mi(n,r));Bh(l,"root",i),Bh(n,r,l)}else Bh(n,r,i)}return n},G5s=(s,t)=>s.some(n=>n.startsWith(t+"."));var W5s=function(s,t){for(var n={};s.length;){var r=s[0],a=r.code,i=r.message,l=r.path.join(".");if(!n[l])if("unionErrors"in r){var o=r.unionErrors[0].errors[0];n[l]={message:o.message,type:o.code}}else n[l]={message:i,type:a};if("unionErrors"in r&&r.unionErrors.forEach(function(u){return u.errors.forEach(function(h){return s.push(h)})}),t){var c=n[l].types,d=c&&c[r.code];n[l]=r8t(l,t,n,a,d?[].concat(d,r.message):r.message)}s.shift()}return n},kLe=function(s,t,n){return n===void 0&&(n={}),function(r,a,i){try{return Promise.resolve(function(l,o){try{var c=Promise.resolve(s[n.mode==="sync"?"parse":"parseAsync"](r,t)).then(function(d){return i.shouldUseNativeValidation&&p8t({},i),{errors:{},values:n.raw?r: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:H5s(W5s(l.errors,!i.shouldUseNativeValidation&&i.criteriaMode==="all"),i)};throw l}))}catch(l){return Promise.reject(l)}}};function $He(s){const t=Object.values(s).filter(r=>typeof r=="number");return Object.entries(s).filter(([r,a])=>t.indexOf(+r)===-1).map(([r,a])=>a)}function Hxt(s,t="|"){return s.map(n=>_8t(n)).join(t)}function UHe(s,t){return typeof t=="bigint"?t.toString():t}class K5s{constructor(t){this._getter=t,this._value=void 0}get value(){const t=this._getter;return t!==void 0&&(this._value=t(),this._getter=void 0),this._value}}function ott(s){return new K5s(s)}function Y5s(s){return s==null}function ltt(s){const t=s.startsWith("^")?1:0,n=s.endsWith("$")?s.length-1:s.length;return s.slice(t,n)}function Z5s(s,t){const n=s/t,r=Math.round(n),a=4*Number.EPSILON*Math.max(Math.abs(n),1);return Math.abs(n-r){const o=t._zod.def.shape[i];return r?r(o,i):o}):y8t(s,i,r?r(l.value,i):l.value))}}function X5s(s,t){for(const n of Reflect.ownKeys(t)){const r=Object.getOwnPropertyDescriptor(t,n);r.enumerable&&(r.get?x8t(s,n,()=>t[n]):y8t(s,n,r.value))}}function Zj(...s){const t={};for(const n of s){const r=Object.getOwnPropertyDescriptors(n);Object.assign(t,r)}return Object.defineProperties({},t)}function Q5s(s){return JSON.stringify(s)}function J5s(s){return s.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}const v8t="captureStackTrace"in Error?Error.captureStackTrace:(...s)=>{};function kEe(s){return typeof s=="object"&&s!==null&&!Array.isArray(s)}const e4s=ott(()=>{var s;if(K4.jitless||typeof navigator<"u"&&((s=navigator==null?void 0:navigator.userAgent)!=null&&s.includes("Cloudflare")))return!1;try{const t=Function;return new t(""),!0}catch{return!1}});function tse(s){if(kEe(s)===!1)return!1;const t=s.constructor;if(t===void 0||typeof t!="function")return!0;const n=t.prototype;return!(kEe(n)===!1||Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")===!1)}function b8t(s){return tse(s)?{...s}:Array.isArray(s)?[...s]:s instanceof Map?new Map(s):s instanceof Set?new Set(s):s}const t4s=new Set(["string","number","symbol"]);function NG(s){return s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function a6(s,t,n){const r=new s._zod.constr(t??s._zod.def);return(!t||n!=null&&n.parent)&&(r._zod.parent=s),r}function Pl(s){const t=s;if(!t)return{};if(typeof t=="string")return{error:()=>t};if((t==null?void 0:t.message)!==void 0){if((t==null?void 0:t.error)!==void 0)throw new Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error=="string"?{...t,error:()=>t.error}:t}function _8t(s){return typeof s=="bigint"?s.toString()+"n":typeof s=="string"?`"${s}"`:`${s}`}function s4s(s){return Object.keys(s).filter(t=>s[t]._zod.optin!==void 0&&s[t]._zod.optout==="optional")}const w8t={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},n4s={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function r4s(s,t){const n=s._zod.def,r=n.checks;if(r&&r.length>0)throw new Error(".pick() cannot be used on object schemas containing refinements");const i={};return G7(i,s,SLe(s,t)),a6(s,Zj(n,{shape:i,checks:[]}))}function SLe(s,t){var a;const n=mT(s),r=[];for(const i of Reflect.ownKeys(t)){if(!((a=Object.getOwnPropertyDescriptor(n,i))!=null&&a.enumerable))throw new Error(`Unrecognized key: "${String(i)}"`);t[i]&&r.push(i)}return r}function a4s(s,t){const n=s._zod.def,r=n.checks;if(r&&r.length>0)throw new Error(".omit() cannot be used on object schemas containing refinements");const i=new Set(SLe(s,t)),l={};return G7(l,s,Reflect.ownKeys(mT(s)).filter(o=>!i.has(o))),a6(s,Zj(n,{shape:l,checks:[]}))}function i4s(s,t){if(!tse(t))throw new Error("Invalid input to extend: expected a plain object");const n=s._zod.def.checks;if(n&&n.length>0){const a=mT(s);for(const i of Reflect.ownKeys(t))if(Object.getOwnPropertyDescriptor(a,i)!==void 0)throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}return a6(s,Zj(s._zod.def,{shape:j8t(s,t)}))}function j8t(s,t){const n={};return G7(n,s,Reflect.ownKeys(mT(s))),X5s(n,t),n}function o4s(s,t){if(!tse(t))throw new Error("Invalid input to safeExtend: expected a plain object");return a6(s,Zj(s._zod.def,{shape:j8t(s,t)}))}function l4s(s,t){var a,i;if(!((a=t==null?void 0:t._zod)!=null&&a.def))throw new Error("Invalid input to merge: expected an object schema. To merge a plain shape, use `.extend()`.");if((i=s._zod.def.checks)!=null&&i.length)throw new Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");const n={};G7(n,s,Reflect.ownKeys(mT(s))),G7(n,t,Reflect.ownKeys(mT(t)));const r=Zj(s._zod.def,{shape:n,get catchall(){return t._zod.def.catchall},checks:t._zod.def.checks??[]});return a6(s,r)}function Gxt(s,t,n,r="partial"){const i=t._zod.def.checks;if(i&&i.length>0)throw new Error(`.${r}() cannot be used on object schemas containing refinements`);const o=n?new Set(SLe(t,n)):void 0,c={};return G7(c,t,Reflect.ownKeys(mT(t)),s&&((d,u)=>o&&!o.has(u)?d:new s({type:"optional",innerType:d}))),a6(t,Zj(t._zod.def,{shape:c,checks:[]}))}function c4s(s,t,n){const r=n?new Set(SLe(t,n)):void 0,a={};return G7(a,t,Reflect.ownKeys(mT(t)),(i,l)=>r&&!r.has(l)?i:new s({type:"nonoptional",innerType:i})),a6(t,Zj(t._zod.def,{shape:a}))}function vE(s,t=0){var n;if(s.aborted===!0)return!0;for(let r=t;r{var r;return(r=n).path??(r.path=[]),n.path.unshift(s),n})}function kZ(s){return typeof s=="string"?s:s==null?void 0:s.message}function Wxt(s,t,n){var r;for(let a=t;as;return t[y4s]=!0,t}var Kxt;const Qze={value:void 0,enumerable:!1};let Yxt="captureStackTrace"in Error?Error:null;function b4s(s){const t=Yxt;if(t){const n=t.stackTraceLimit;if(typeof n=="number"){try{t.stackTraceLimit=0}catch{return Yxt=null,new s}try{return new s}finally{t.stackTraceLimit=n}}}return new s}function Ma(s,t,n,r){const a={};function i(m){this.def=m,this.constr=h,this.traits=new Set}i.prototype=a;const l=n,o=l&&new WeakSet;function c(m,f){if(m._zod){if(m._zod.traits.has(s))return}else{Qze.value=new i(f);try{Object.defineProperty(m,"_zod",Qze)}finally{Qze.value=void 0}}if(m._zod.traits.add(s),t(m,f),o){const x=Object.getPrototypeOf(m),y=m._zod.constr.prototype;let v=x;for(;v&&v!==y;)v=Object.getPrototypeOf(v);const b=v??x;o.has(b)||(o.add(b),m4s(b,l))}const g=h.prototype;for(const x in g)Object.prototype.hasOwnProperty.call(g,x)&&(x in m||(m[x]=g[x].bind(m)))}const d=(r==null?void 0:r.Parent)??Object;class u extends d{}Object.defineProperty(u,"name",{value:s});function h(m){var y;const f=r!=null&&r.Parent?b4s(u):this;c(f,m);const g=f._zod.deferred;if(g){for(const v of g)v();f._zod.deferred=void 0}const x=(y=globalThis.__zod_globalConfig)==null?void 0:y.postProcessor;return x&&x(f),f}return Object.defineProperty(h,"init",{value:c}),Object.defineProperty(h,Symbol.hasInstance,{value:m=>{var f,g;return r!=null&&r.Parent&&m instanceof r.Parent?!0:(g=(f=m==null?void 0:m._zod)==null?void 0:f.traits)==null?void 0:g.has(s)}}),Object.defineProperty(h,"name",{value:s}),h}class d7 extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class C8t extends Error{constructor(t){super(`Encountered unidirectional transform during encode: ${t}`),this.name="ZodEncodeError"}}(Kxt=globalThis).__zod_globalConfig??(Kxt.__zod_globalConfig={});const K4=globalThis.__zod_globalConfig;function i6(s){return s&&Object.assign(K4,s),K4}function _4s(){const s=this._zod;return s.message??(s.message=JSON.stringify(s.def,UHe,2)),s.message}function w4s(s){this._zod.message=s}const j4s={get:_4s,set:w4s,enumerable:!0,configurable:!0},Jze={value:void 0,enumerable:!1},Zxt=new WeakSet([Object.prototype,Error.prototype]),N4s=(s,t)=>{s.name="$ZodError",Jze.value=t,Object.defineProperty(s,"issues",Jze),Jze.value=void 0,Object.defineProperty(s,"message",j4s);const n=Object.getPrototypeOf(s);Zxt.has(n)||(Zxt.add(n),Object.defineProperty(n,"toString",{configurable:!0,enumerable:!1,get(){const r=()=>this.message;return Object.defineProperty(this,"toString",{value:r,configurable:!0,writable:!0}),r},set(r){Object.defineProperty(this,"toString",{value:r,configurable:!0,writable:!0})}}))},k4s=Ma("$ZodError",N4s);function S4s(s,t,n){return Object.prototype.hasOwnProperty.call(s,t)||(t==="__proto__"?Object.defineProperty(s,t,{value:n(),writable:!0,enumerable:!0,configurable:!0}):s[t]=n()),s[t]}function C4s(s,t=n=>n.message){const n={},r=[];for(const a of s.issues)a.path.length>0?S4s(n,a.path[0],()=>[]).push(t(a)):r.push(t(a));return{formErrors:r,fieldErrors:n}}function A4s(s,t=n=>n.message){const n={_errors:[]},r=(a,i=[])=>{for(const l of a.issues)if(l.code==="invalid_union"&&l.errors.length)l.errors.map(o=>r({issues:o},[...i,...l.path]));else if(l.code==="invalid_key")r({issues:l.issues},[...i,...l.path]);else if(l.code==="invalid_element")r({issues:l.issues},[...i,...l.path]);else{const o=[...i,...l.path];if(o.length===0)n._errors.push(t(l));else{let c=n,d=0;for(;d{const t=(n,r,a,i)=>{const l=a?{...a,async:!1}:{async:!1},o=n._zod.run({value:r,issues:[]},l);if(o instanceof Promise)throw new d7;if(o.issues.length){const c=new((i==null?void 0:i.Err)??s)(o.issues.map(d=>nK(d,l,i6())));throw v8t(c,(i==null?void 0:i.callee)??t),c}return o.value};return t},htt=s=>{const t=async(n,r,a,i)=>{const l=a?{...a,async:!0}:{async:!0};let o=n._zod.run({value:r,issues:[]},l);if(o instanceof Promise&&(o=await o),o.issues.length){const c=new((i==null?void 0:i.Err)??s)(o.issues.map(d=>nK(d,l,i6())));throw v8t(c,(i==null?void 0:i.callee)??t),c}return o.value};return t},mtt=s=>(t,n,r)=>{const a=r?{...r,async:!1}:{async:!1},i=t._zod.run({value:n,issues:[]},a);if(i instanceof Promise)throw new d7;return i.issues.length?A8t(s,i.issues,a):{success:!0,data:i.value}};function A8t(s,t,n){let r;return{success:!1,get error(){return r||(r=new s(t.map(a=>nK(a,n,i6()))),t=void 0,n=void 0),r},set error(a){r=a,t=void 0,n=void 0}}}const ftt=s=>async(t,n,r)=>{const a=r?{...r,async:!0}:{async:!0};let i=t._zod.run({value:n,issues:[]},a);return i instanceof Promise&&(i=await i),i.issues.length?A8t(s,i.issues,a):{success:!0,data:i.value}},E4s=Symbol.for("zod.compile.invalid"),T4s=Symbol.for("zod.compile.fallback"),M4s=(s,t,n)=>{const r=s._zod.bag.validator;if(r!==void 0){if(r(t)!==E4s)return!0;if(r.definite===!0&&n===void 0)return!1}return P4s(s,t,n)};function P4s(s,t,n){const r=n?{...n,async:!1,abortEarly:!0}:{async:!1,abortEarly:!0},a=s._zod.bag.fallbackRun;let i;if(a?(r[T4s]=!0,i=a({value:t,issues:[]},r)):i=s._zod.run({value:t,issues:[]},r),i instanceof Promise)throw new d7;return i.issues.length===0}const I4s=async(s,t,n)=>{const r=n?{...n,async:!0,abortEarly:!0}:{async:!0,abortEarly:!0};let a=s._zod.run({value:t,issues:[]},r);return a instanceof Promise&&(a=await a),a.issues.length===0},L4s=s=>{const t=utt(s),n=(r,a,i,l)=>{const o=i?{...i,direction:"backward"}:{direction:"backward"};return t(r,a,o,CLe(n,l))};return n},R4s=s=>{const t=utt(s),n=(r,a,i,l)=>t(r,a,i,CLe(n,l));return n},D4s=s=>{const t=htt(s),n=async(r,a,i,l)=>{const o=i?{...i,direction:"backward"}:{direction:"backward"};return await t(r,a,o,CLe(n,l))};return n},F4s=s=>{const t=htt(s),n=async(r,a,i,l)=>await t(r,a,i,CLe(n,l));return n},O4s=s=>(t,n,r)=>{const a=r?{...r,direction:"backward"}:{direction:"backward"};return mtt(s)(t,n,a)},z4s=s=>(t,n,r)=>mtt(s)(t,n,r),B4s=s=>async(t,n,r)=>{const a=r?{...r,direction:"backward"}:{direction:"backward"};return ftt(s)(t,n,a)},$4s=s=>async(t,n,r)=>ftt(s)(t,n,r),U4s=/^[cC][0-9a-z]{6,}$/,q4s=/^[0-9a-z]+$/,V4s=/^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/,H4s=/^[0-9a-vA-V]{20}$/,G4s=/^[A-Za-z0-9]{27}$/,W4s=/^[a-zA-Z0-9_-]{21}$/;function K4s(s){return new RegExp(`^[a-zA-Z0-9_-]{${s}}$`)}const Y4s=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,Z4s=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,Xxt=s=>s?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${s}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/,X4s=/^(?:[A-Za-z0-9_'+\-]+\.)*[A-Za-z0-9_'+\-]*[A-Za-z0-9_+-]@(?:[A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,Q4s="^(?=[\\s\\S]*[\\p{Extended_Pictographic}\\p{Regional_Indicator}\\u20E3])[\\p{Extended_Pictographic}\\p{Emoji_Component}]+$";function J4s(){return new RegExp(Q4s,"u")}const e3s=/^(?:(?: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])$/,t3s=/^(([0-9a-fA-F]{1,4}:){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}|:))$/,s3s=/^((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])\/([0-9]|[1-2][0-9]|3[0-2])$/,n3s=/^(([0-9a-fA-F]{1,4}:){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}|:))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,r3s=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,a3s=/^(?:[A-Za-z0-9_-]{4})*(?:[A-Za-z0-9_-]{2,3})?$/,i3s=/^https?$/,o3s=/^\+[1-9]\d{6,14}$/,E8t="(?:(?:\\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])))";function l3s(s){return new RegExp(`^${s}$`)}const c3s=l3s(E8t);function qHe(s){const t="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof s.precision=="number"?s.precision===-1?`${t}`:s.precision===0?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${s.precision}}`:s.seconds?`${t}:[0-5]\\d(?:\\.\\d+)?`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}function d3s(s){return new RegExp(`^${qHe(s)}$`)}function u3s(s){const t=["Z"];s.offset&&t.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");const n=`${qHe({precision:s.precision,seconds:!0})}(?:${t.join("|")})`,r=s.local?`${n}|${qHe({precision:s.precision})}`:n;return new RegExp(`^${E8t}T(?:${r})$`)}const h3s=/^[\s\S]{0,}$/,m3s=/^-?\d+(?:\.\d+)?$/,f3s=/^(?:true|false)$/i,p3s=/^[^A-Z]*$/,g3s=/^[^a-z]*$/,Gw=Ma("$ZodCheck",(s,t)=>{var n;s._zod??(s._zod={}),s._zod.def=t,(n=s._zod).onattach??(n.onattach=[])}),ptt=s=>{const t=s.value;return!Y5s(t)&&t.length!==void 0},SEe={number:"number",bigint:"bigint",object:"date"},T8t=Ma("$ZodCheckLessThan",(s,t)=>{Gw.init(s,t);const n=SEe[typeof t.value];s._zod.check=r=>{(t.inclusive?r.value<=t.value:r.value{Gw.init(s,t);const n=SEe[typeof t.value];s._zod.check=r=>{(t.inclusive?r.value>=t.value:r.value>t.value)||r.issues.push({origin:SEe[typeof r.value]??n,code:"too_small",minimum:typeof t.value=="object"?t.value.getTime():t.value,input:r.value,inclusive:t.inclusive,inst:s,continue:!t.abort})}}),x3s=Ma("$ZodCheckMultipleOf",(s,t)=>{Gw.init(s,t),s._zod.check=n=>{if(typeof n.value!=typeof t.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof n.value=="bigint"?t.value!==BigInt(0)&&n.value%t.value===BigInt(0):Z5s(n.value,t.value)===0)||n.issues.push({origin:typeof n.value,code:"not_multiple_of",divisor:t.value,input:n.value,inst:s,continue:!t.abort})}}),y3s=Ma("$ZodCheckNumberFormat",(s,t)=>{var l;Gw.init(s,t),t.format=t.format||"float64";const n=(l=t.format)==null?void 0:l.includes("int"),r=n?"int":"number",[a,i]=w8t[t.format];s._zod.check=o=>{const c=o.value;if(n){if(!Number.isInteger(c)){o.issues.push({expected:r,format:t.format,code:"invalid_type",continue:!1,input:c,inst:s});return}if(!Number.isSafeInteger(c)){c>0?o.issues.push({input:c,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:s,origin:r,inclusive:!0,continue:!t.abort}):o.issues.push({input:c,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:s,origin:r,inclusive:!0,continue:!t.abort});return}}ci&&o.issues.push({origin:"number",input:c,code:"too_big",maximum:i,inclusive:!0,inst:s,continue:!t.abort})}}),v3s=Ma("$ZodCheckMaxLength",(s,t)=>{var n;Gw.init(s,t),(n=s._zod.def).when??(n.when=ptt),s._zod.check=r=>{const a=r.value,i=a.length;if((typeof a=="string"&&i>t.maximum?ctt(a):i)<=t.maximum)return;const o=dtt(a);r.issues.push({origin:o,code:"too_big",maximum:t.maximum,inclusive:!0,input:a,inst:s,continue:!t.abort})}}),b3s=Ma("$ZodCheckMinLength",(s,t)=>{var n;Gw.init(s,t),(n=s._zod.def).when??(n.when=ptt),s._zod.check=r=>{const a=r.value,i=a.length;if((typeof a=="string"&&i>=t.minimum&&i=t.minimum)return;const o=dtt(a);r.issues.push({origin:o,code:"too_small",minimum:t.minimum,inclusive:!0,input:a,inst:s,continue:!t.abort})}}),_3s=Ma("$ZodCheckLengthEquals",(s,t)=>{var n;Gw.init(s,t),(n=s._zod.def).when??(n.when=ptt),s._zod.check=r=>{const a=r.value,i=a.length,l=typeof a=="string"&&i>=t.length&&i<=t.length*2?ctt(a):i;if(l===t.length)return;const o=dtt(a),c=l>t.length;r.issues.push({origin:o,...c?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:r.value,inst:s,continue:!t.abort})}}),ALe=Ma("$ZodCheckStringFormat",(s,t)=>{var n,r;Gw.init(s,t),t.pattern?(n=s._zod).check??(n.check=a=>{t.pattern.lastIndex=0,!t.pattern.test(a.value)&&a.issues.push({origin:"string",code:"invalid_format",format:t.format,input:a.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:s,continue:!t.abort})}):(r=s._zod).check??(r.check=()=>{})}),w3s=Ma("$ZodCheckRegex",(s,t)=>{ALe.init(s,t),s._zod.check=n=>{t.pattern.lastIndex=0,!t.pattern.test(n.value)&&n.issues.push({origin:"string",code:"invalid_format",format:"regex",input:n.value,pattern:t.pattern.toString(),inst:s,continue:!t.abort})}}),j3s=Ma("$ZodCheckLowerCase",(s,t)=>{t.pattern??(t.pattern=p3s),ALe.init(s,t)}),N3s=Ma("$ZodCheckUpperCase",(s,t)=>{t.pattern??(t.pattern=g3s),ALe.init(s,t)}),k3s=Ma("$ZodCheckIncludes",(s,t)=>{Gw.init(s,t);const n=NG(t.includes),r=new RegExp(typeof t.position=="number"?`^.{${t.position},}${n}`:n);t.pattern=r,s._zod.check=a=>{a.value.includes(t.includes,t.position)||a.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:a.value,inst:s,continue:!t.abort})}}),S3s=Ma("$ZodCheckStartsWith",(s,t)=>{Gw.init(s,t);const n=new RegExp(`^${NG(t.prefix)}.*`);t.pattern??(t.pattern=n),s._zod.check=r=>{r.value.startsWith(t.prefix)||r.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:r.value,inst:s,continue:!t.abort})}}),C3s=Ma("$ZodCheckEndsWith",(s,t)=>{Gw.init(s,t);const n=new RegExp(`.*${NG(t.suffix)}$`);t.pattern??(t.pattern=n),s._zod.check=r=>{r.value.endsWith(t.suffix)||r.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:r.value,inst:s,continue:!t.abort})}}),A3s=Ma("$ZodCheckOverwrite",(s,t)=>{Gw.init(s,t),s._zod.check=n=>{n.value=t.tx(n.value)}});class E3s{constructor(t=[],n={}){this.content=[],this.indent=0,this.args=t,this.closed=n}indented(t){this.indent+=1;try{t(this)}finally{this.indent-=1}}write(t){if(typeof t=="function"){t(this,{execution:"sync"}),t(this,{execution:"async"});return}const r=t.split(` `).filter(l=>l),a=Math.min(...r.map(l=>l.length-l.trimStart().length)),i=r.map(l=>l.slice(a)).map(l=>" ".repeat(this.indent*2)+l);for(const l of i)this.content.push(l)}compile(){const t=Function,n=(this==null?void 0:this.content)??[""];return new t(...Object.keys(this.closed),`return function (${this.args.join(", ")}) { ${n.join(` `)} };`)(...Object.values(this.closed))}}const T3s={major:4,minor:6,patch:5},Px=Ma("$ZodType",(s,t)=>{var i;var n;s??(s={}),s._zod.def=t,s._zod.bag=s._zod.bag||{},s._zod.version=T3s;const r=s._zod.def.checks,a=s._zod.traits.has("$ZodCheck")?[s,...r??[]]:r!=null&&r.length?[...r]:[];for(const l of a)for(const o of l._zod.onattach)o(s);if(a.length===0)(n=s._zod).deferred??(n.deferred=[]),(i=s._zod.deferred)==null||i.push(()=>{s._zod.run=s._zod.parse});else{const l=(c,d,u)=>{if(c.memo)return c;let h=vE(c),m;for(const f of d){if(f._zod.def.when){if(d4s(c)||!f._zod.def.when(c))continue}else if(h)continue;const g=c.issues.length,x=f._zod.check(c);if(x instanceof Promise&&(u==null?void 0:u.async)===!1)throw new d7;if(m||x instanceof Promise)m=(m??Promise.resolve()).then(async()=>{await x,c.issues.length!==g&&(Wxt(c.issues,g,s),h||(h=vE(c,g)))});else{if(c.issues.length===g)continue;Wxt(c.issues,g,s),h||(h=vE(c,g))}}return m?m.then(()=>c):c},o=(c,d,u)=>{if(vE(c))return c.aborted=!0,c;const h=l(d,a,u);if(h instanceof Promise){if(u.async===!1)throw new d7;return h.then(m=>s._zod.parse(m,u))}return s._zod.parse(h,u)};s._zod.run=(c,d)=>{if(d.skipChecks)return s._zod.parse(c,d);if(d.direction==="backward"){const h=s._zod.parse({value:c.value,issues:[]},{...d,skipChecks:!0});return h instanceof Promise?h.then(m=>o(m,c,d)):o(h,c,d)}const u=s._zod.parse(c,d);if(u instanceof Promise){if(d.async===!1)throw new d7;return u.then(h=>l(h,a,d))}return l(u,a,d)}}},{get"~standard"(){return k8t(this,"~standard",I8t(this))},set"~standard"(s){CL(this,"~standard",s)}}),P8t=(s,t)=>s.issues.length?{issues:s.issues.map(n=>nK(n,t,i6()))}:{value:s.value};async function M3s(s,t){const n={async:!0};return P8t(await s._zod.run({value:t,issues:[]},n),n)}function I8t(s){return{validate:t=>{const n={async:!1};try{const r=s._zod.run({value:t,issues:[]},n);if(!(r instanceof Promise))return P8t(r,n)}catch{}return M3s(s,t)},vendor:"zod",version:1}}const gtt=Ma("$ZodString",(s,t)=>{Px.init(s,t),s._zod.pattern=t.pattern??h3s,s._zod.parse=(n,r)=>{if(t.coerce)try{n.value=String(n.value)}catch{}return typeof n.value=="string"||n.issues.push({expected:"string",code:"invalid_type",input:n.value,inst:s}),n}}),sg=Ma("$ZodStringFormat",(s,t)=>{ALe.init(s,t),gtt.init(s,t)}),P3s=Ma("$ZodGUID",(s,t)=>{t.pattern??(t.pattern=Z4s),sg.init(s,t)}),I3s=Ma("$ZodUUID",(s,t)=>{if(t.version){const r={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(r===void 0)throw new Error(`Invalid UUID version: "${t.version}"`);t.pattern??(t.pattern=Xxt(r))}else t.pattern??(t.pattern=Xxt());sg.init(s,t)}),L3s=Ma("$ZodEmail",(s,t)=>{t.pattern??(t.pattern=X4s),sg.init(s,t)}),L8t=1,CEe=2;function R8t(s){try{return typeof URL<"u"&&typeof URL.canParse=="function"?URL.canParse(s):(new URL(s),!0)}catch{return!1}}function R3s(s,t){return!("normalize"in t)&&!("hostname"in t)&&!("protocol"in t)?R8t(s)||CEe:D3s(s,t)}function D3s(s,t){var n;if(!t.normalize&&((n=t.protocol)==null?void 0:n.source)===i3s.source&&!/^https?:\/\//i.test(s))return L8t;try{if(typeof URL<"u"){const r=URL;if(typeof r.parse=="function")return r.parse(s)??CEe}return new URL(s)}catch{return CEe}}const F3s=/[\t\n\r]/g;function Qxt(s){return s.replace(F3s,"")}function O3s(s,t){return t.lastIndex=0,t.test(s.hostname)}function z3s(s,t){return t.lastIndex=0,t.test(s.protocol.endsWith(":")?s.protocol.slice(0,-1):s.protocol)}const B3s=Ma("$ZodURL",(s,t)=>{sg.init(s,t),s._zod.check=n=>{try{const r=n.value.trim(),a=R3s(r,t);if(a===L8t){n.issues.push({code:"invalid_format",format:"url",note:"Invalid URL format",input:n.value,inst:s,continue:!t.abort});return}if(a===CEe){n.issues.push({code:"invalid_format",format:"url",input:n.value,inst:s,continue:!t.abort});return}if(a===!0){n.value=Qxt(r);return}t.hostname&&!O3s(a,t.hostname)&&n.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:t.hostname.source,input:n.value,inst:s,continue:!t.abort}),t.protocol&&!z3s(a,t.protocol)&&n.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:t.protocol.source,input:n.value,inst:s,continue:!t.abort}),n.value=t.normalize?a.href:Qxt(r);return}catch{n.issues.push({code:"invalid_format",format:"url",input:n.value,inst:s,continue:!t.abort})}}}),$3s=Ma("$ZodEmoji",(s,t)=>{t.pattern??(t.pattern=J4s()),sg.init(s,t)}),U3s=Ma("$ZodNanoID",(s,t)=>{if(t.length!==void 0&&(!Number.isInteger(t.length)||t.length<1))throw new Error(`Invalid nanoid length: ${t.length}`);t.pattern??(t.pattern=t.length===void 0?W4s:K4s(t.length)),sg.init(s,t)}),q3s=Ma("$ZodCUID",(s,t)=>{t.pattern??(t.pattern=U4s),sg.init(s,t)}),V3s=Ma("$ZodCUID2",(s,t)=>{t.pattern??(t.pattern=q4s),sg.init(s,t)}),H3s=Ma("$ZodULID",(s,t)=>{t.pattern??(t.pattern=V4s),sg.init(s,t)}),G3s=Ma("$ZodXID",(s,t)=>{t.pattern??(t.pattern=H4s),sg.init(s,t)}),W3s=Ma("$ZodKSUID",(s,t)=>{t.pattern??(t.pattern=G4s),sg.init(s,t)}),K3s=Ma("$ZodISODateTime",(s,t)=>{t.pattern??(t.pattern=u3s(t)),sg.init(s,t)}),Y3s=Ma("$ZodISODate",(s,t)=>{t.pattern??(t.pattern=c3s),sg.init(s,t)}),Z3s=Ma("$ZodISOTime",(s,t)=>{t.pattern??(t.pattern=d3s(t)),sg.init(s,t)}),X3s=Ma("$ZodISODuration",(s,t)=>{t.pattern??(t.pattern=Y4s),sg.init(s,t)}),Q3s=Ma("$ZodIPv4",(s,t)=>{t.pattern??(t.pattern=e3s),sg.init(s,t)}),J3s=/^[0-9a-fA-F:.]+$/;function D8t(s){return J3s.test(s)?R8t(`http://[${s}]`):!1}const eAs=Ma("$ZodIPv6",(s,t)=>{t.pattern??(t.pattern=t3s),sg.init(s,t),s._zod.check=n=>{D8t(n.value)||n.issues.push({code:"invalid_format",format:"ipv6",input:n.value,inst:s,continue:!t.abort})}}),tAs=Ma("$ZodCIDRv4",(s,t)=>{t.pattern??(t.pattern=s3s),sg.init(s,t)});function sAs(s){const t=s.split("/");if(t.length!==2)return!1;const[n,r]=t;if(!r)return!1;const a=Number(r);return`${a}`!==r||a<0||a>128?!1:D8t(n)}const nAs=Ma("$ZodCIDRv6",(s,t)=>{t.pattern??(t.pattern=n3s),sg.init(s,t),s._zod.check=n=>{sAs(n.value)||n.issues.push({code:"invalid_format",format:"cidrv6",input:n.value,inst:s,continue:!t.abort})}});function F8t(s){if(s==="")return!0;if(/\s/.test(s)||s.length%4!==0)return!1;try{return atob(s),!0}catch{return!1}}const O8t=/^[0-9a-zA-Z+/]*={0,2}$/,rAs=Ma("$ZodBase64",(s,t)=>{t.pattern??(t.pattern=O8t),sg.init(s,t),s._zod.check=n=>{F8t(n.value)||n.issues.push({code:"invalid_format",format:"base64",input:n.value,inst:s,continue:!t.abort})}}),xtt=/^[A-Za-z0-9_-]*$/;function aAs(s){if(!xtt.test(s))return!1;const t=s.replace(/[-_]/g,r=>r==="-"?"+":"/"),n=t.padEnd(Math.ceil(t.length/4)*4,"=");return F8t(n)}const iAs=Ma("$ZodBase64URL",(s,t)=>{t.pattern??(t.pattern=xtt),sg.init(s,t),s._zod.check=n=>{aAs(n.value)||n.issues.push({code:"invalid_format",format:"base64url",input:n.value,inst:s,continue:!t.abort})}}),oAs=Ma("$ZodE164",(s,t)=>{t.pattern??(t.pattern=o3s),sg.init(s,t)});function lAs(s,t=null){try{const n=s.split(".");if(n.length!==3)return!1;const[r]=n;if(!r)return!1;const a=JSON.parse(atob(r));return!("typ"in a&&(a==null?void 0:a.typ)!=="JWT"||!a.alg||t&&(!("alg"in a)||a.alg!==t))}catch{return!1}}const cAs=Ma("$ZodJWT",(s,t)=>{sg.init(s,t),s._zod.check=n=>{lAs(n.value,t.alg)||n.issues.push({code:"invalid_format",format:"jwt",input:n.value,inst:s,continue:!t.abort})}}),z8t=Ma("$ZodNumber",(s,t)=>{Px.init(s,t),s._zod.pattern=m3s,s._zod.parse=(n,r)=>{if(t.coerce)try{n.value=Number(n.value)}catch{}const a=n.value;if(typeof a=="number"&&!Number.isNaN(a)&&Number.isFinite(a))return n;const i=typeof a=="number"?Number.isNaN(a)?"NaN":Number.isFinite(a)?void 0:String(a):void 0;return n.issues.push({expected:"number",code:"invalid_type",input:a,inst:s,...i?{received:i}:{}}),n}}),dAs=Ma("$ZodNumberFormat",(s,t)=>{y3s.init(s,t),z8t.init(s,t)}),uAs=Ma("$ZodBoolean",(s,t)=>{Px.init(s,t),s._zod.pattern=f3s,s._zod.parse=(n,r)=>{if(t.coerce)try{n.value=!!n.value}catch{}const a=n.value;return typeof a=="boolean"||n.issues.push({expected:"boolean",code:"invalid_type",input:a,inst:s}),n}}),hAs=Ma("$ZodUnknown",(s,t)=>{Px.init(s,t),s._zod.parse=n=>n}),mAs=Ma("$ZodNever",(s,t)=>{Px.init(s,t),s._zod.parse=(n,r)=>(n.issues.push({expected:"never",code:"invalid_type",input:n.value,inst:s}),n)});function Jxt(s,t,n){s.issues.length&&t.issues.push(...N8t(n,s.issues)),t.value[n]=s.value}const fAs=Ma("$ZodArray",(s,t)=>{Px.init(s,t);const n=K4.memoizer;n==null||n.attach(s),s._zod.parse=(r,a)=>{const i=r.value;if(!Array.isArray(i))return r.issues.push({expected:"array",code:"invalid_type",input:i,inst:s}),r;r.value=n?n.alloc(s,r,Array(i.length),a):Array(i.length);const l=[],o=a==null?void 0:a.abortEarly;for(let c=0;cJxt(h,r,c)));else if(Jxt(u,r,c),o&&u.issues.length!==0&&vE(u))break}return l.length?Promise.all(l).then(()=>r):r}});function AEe(s,t,n,r,a,i){const l=n in r,o=i==="optional";if(!(!l&&o&&a==="optional")){if(s.issues.length){if(a!==void 0&&o&&!l)return;t.issues.push(...N8t(n,s.issues))}if(!l&&a===void 0){s.issues.length||t.issues.push({code:"invalid_type",expected:"nonoptional",input:void 0,path:[n]});return}s.value===void 0?(l||a==="defaulted"&&!o)&&(t.value[n]=void 0):t.value[n]=s.value}}const pAs=[];function B8t(s){var l,o,c,d;const t=Object.keys(s.shape),n=Object.getOwnPropertySymbols(s.shape),r=n.length?n:pAs,a=r.length?[...t,...r]:t;for(const u of a)if(!((d=(c=(o=(l=s.shape)==null?void 0:l[u])==null?void 0:o._zod)==null?void 0:c.traits)!=null&&d.has("$ZodType")))throw new Error(`Invalid element at key "${String(u)}": expected a Zod schema`);const i=s4s(s.shape);return{...s,allKeys:a,symbolKeys:r,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(i)}}function $8t(s,t,n,r,a,i,l){const o=[],c=a.keySet,d=a.catchall._zod,u=d.def.type,h=d.optin,m=d.optout;let f=0;for(const g in t){if(l&&n.issues.length!==f){if(vE(n,f))break;f=n.issues.length}if(c.has(g))continue;if(g==="__proto__"){u==="never"&&o.push(g);continue}if(u==="never"){o.push(g);continue}const x=d.run({value:t[g],issues:[]},r);x instanceof Promise?s.push(x.then(y=>AEe(y,n,g,t,h,m))):AEe(x,n,g,t,h,m)}return o.length&&n.issues.push({code:"unrecognized_keys",keys:o,input:t,inst:i,continue:!0}),s.length?Promise.all(s).then(()=>n):n}const gAs=Ma("$ZodObject",(s,t)=>{Px.init(s,t);const n=Object.getOwnPropertyDescriptor(t,"shape"),r=n!=null&&n.get?n.get.raw:t.shape??{};if(r){const d=()=>{const u={...r};return Object.defineProperty(t,"shape",{value:u}),d.raw=u,u};d.raw=r,Object.defineProperty(t,"shape",{get:d})}const a=ott(()=>B8t(t));ym(s,"propValues",d=>{const u=d.def.shape,h={};for(const m in u){const f=u[m]._zod;if(f.values){Object.prototype.hasOwnProperty.call(h,m)||UB(h,m,new Set);for(const g of f.values)h[m].add(g);f.optin!==void 0&&h[m].add(void 0)}}return h});const i=kEe,l=t.catchall;let o;const c=K4.memoizer;c==null||c.attach(s),s._zod.parse=(d,u)=>{o??(o=a.value);const h=d.value;if(!i(h))return d.issues.push({expected:"object",code:"invalid_type",input:h,inst:s}),d;d.value=c?c.alloc(s,d,{},u):{};const m=[],f=o.shape,g=u==null?void 0:u.abortEarly;let x=d.issues.length;for(const y of o.allKeys){if(g&&d.issues.length!==x){if(vE(d,x))break;x=d.issues.length}if(y==="__proto__")continue;const v=f[y],b=v._zod.optin,w=v._zod.optout,S=v._zod.run({value:h[y],issues:[]},u);S instanceof Promise?m.push(S.then(C=>AEe(C,d,y,h,b,w))):AEe(S,d,y,h,b,w)}return l?$8t(m,h,d,u,a.value,s,g===!0):m.length?Promise.all(m).then(()=>d):d}}),xAs=Ma("$ZodObjectJIT",(s,t)=>{gAs.init(s,t);const n=s._zod.parse,r=ott(()=>B8t(t)),a=K4.memoizer,i=f=>{var C,E;const g=r.value,x=g.symbolKeys,y=new E3s(["payload","ctx"],{shape:f,inst:s,memo:a,syms:x}),v=I=>`shape[${I}]._zod.run({ value: input[${I}], issues: [] }, ctx)`,b=(I,P)=>` let ${I}_ab = false; for (let i = 0; i < ${I}.issues.length; i++) { const iss = ${I}.issues[i]; iss.path = iss.path ? [${P}, ...iss.path] : [${P}]; payload.issues.push(iss); if (iss.continue !== true) ${I}_ab = true; } if (${I}_ab && ctx && ctx.abortEarly) { payload.value = newResult; return payload; }`;y.write("const input = payload.value;");const w=Object.create(null);let S=0;for(const I of g.allKeys)w[I]=`key_${S++}`;y.write(a?"const newResult = memo.alloc(inst, payload, {}, ctx);":"const newResult = {};");for(const I of g.allKeys){if(I==="__proto__")continue;const P=w[I],R=typeof I=="symbol"?`syms[${x.indexOf(I)}]`:Q5s(I),D=`${R} in input`,O=f[I],U=(C=O==null?void 0:O._zod)==null?void 0:C.optin,W=U!==void 0,V=((E=O==null?void 0:O._zod)==null?void 0:E.optout)==="optional";if(y.write(`const ${P} = ${v(R)};`),W&&V){const G=U==="optional"?`${P}_present`:`${P}.value !== undefined || ${P}_present`;y.write(` const ${P}_present = ${D}; if (!${P}.issues.length || ${P}_present) { if (${P}.issues.length) {${b(P,R)} } if (${G}) { newResult[${R}] = ${P}.value; } } `)}else W?(y.write(` if (${P}.issues.length) {${b(P,R)} } `),U==="defaulted"?y.write(`newResult[${R}] = ${P}.value;`):y.write(` if (${P}.value !== undefined || ${D}) { newResult[${R}] = ${P}.value; } `)):y.write(` const ${P}_present = ${D}; if (${P}.issues.length) {${b(P,R)} } if (!${P}_present && !${P}.issues.length) { payload.issues.push({ code: "invalid_type", expected: "nonoptional", input: undefined, path: [${R}] }); if (ctx && ctx.abortEarly) { payload.value = newResult; return payload; } } if (${P}_present) { newResult[${R}] = ${P}.value; } `)}return y.write("payload.value = newResult;"),y.write("return payload;"),y.compile()};let l;const o=kEe,c=!K4.jitless,u=c&&e4s.value,h=t.catchall;let m;s._zod.parse=(f,g)=>{m??(m=r.value);const x=f.value;return o(x)?c&&u&&(g==null?void 0:g.async)===!1&&g.jitless!==!0?(l||(l=i(t.shape)),f=l(f,g),h?$8t([],x,f,g,m,s,(g==null?void 0:g.abortEarly)===!0):f):n(f,g):(f.issues.push({expected:"object",code:"invalid_type",input:x,inst:s}),f)}});function eyt(s,t,n,r){for(const i of s)if(i.issues.length===0)return t.value=i.value,t;const a=s.filter(i=>!vE(i));return a.length===1?(t.value=a[0].value,a[0]):(t.issues.push({code:"invalid_union",input:t.value,inst:n,errors:s.map(i=>i.issues.map(l=>nK(l,r,i6())))}),t)}const yAs=Ma("$ZodUnion",(s,t)=>{Px.init(s,t),ym(s,"optin",r=>r.def.options.some(a=>a._zod.optin==="defaulted")?"defaulted":r.def.options.some(a=>a._zod.optin!==void 0)?"optional":void 0),ym(s,"optout",r=>r.def.options.some(a=>a._zod.optout==="optional")?"optional":void 0),ym(s,"values",r=>{if(r.def.options.every(a=>a._zod.values))return new Set(r.def.options.flatMap(a=>Array.from(a._zod.values)))}),ym(s,"pattern",r=>{if(r.def.options.every(a=>a._zod.pattern)){const a=r.def.options.map(i=>i._zod.pattern);return new RegExp(`^(${a.map(i=>ltt(i.source)).join("|")})$`)}});const n=t.options.length===1?t.options[0]._zod.run:null;s._zod.parse=(r,a)=>{if(n)return n(r,a);let i=!1;const l=[];for(const o of t.options){const c=o._zod.run({value:r.value,issues:[]},a);if(c instanceof Promise)l.push(c),i=!0;else{if(c.issues.length===0)return c;l.push(c)}}return i?Promise.all(l).then(o=>eyt(o,r,s,a)):eyt(l,r,s,a)}}),vAs=Ma("$ZodIntersection",(s,t)=>{Px.init(s,t),s._zod.parse=(n,r)=>{const a=n.value,i=t.left._zod.run({value:a,issues:[]},r),l=t.right._zod.run({value:a,issues:[]},r);return i instanceof Promise||l instanceof Promise?Promise.all([i,l]).then(([c,d])=>tyt(n,c,d)):tyt(n,i,l)}});function VHe(s,t){if(s===t)return{valid:!0,data:s};if(s instanceof Date&&t instanceof Date&&+s==+t)return{valid:!0,data:s};if(tse(s)&&tse(t)){const n=Object.keys(t),r=Object.keys(s).filter(i=>n.indexOf(i)!==-1),a={...s,...t};Object.prototype.hasOwnProperty.call(a,"__proto__")&&delete a.__proto__;for(const i of r){if(i==="__proto__")continue;const l=VHe(s[i],t[i]);if(!l.valid)return{valid:!1,mergeErrorPath:[i,...l.mergeErrorPath]};a[i]=l.data}return{valid:!0,data:a}}if(Array.isArray(s)&&Array.isArray(t)){if(s.length!==t.length)return{valid:!1,mergeErrorPath:[]};const n=[];for(let r=0;r{var m,f;let h;if(d.code==="unrecognized_keys"&&!((m=d.path)!=null&&m.length))a??(a=d),h=d.keys;else if(d.code==="invalid_key"&&d.origin==="record"&&((f=d.path)==null?void 0:f.length)===1){const g=String(d.path[0]);i.has(g)||i.set(g,d),h=[g]}else return!1;for(const g of h)r.has(g)||r.set(g,{}),r.get(g)[u]=!0;return!0};for(const d of t.issues)l(d,"l")||s.issues.push(d);for(const d of n.issues)l(d,"r")||s.issues.push(d);const o=[...r].filter(([,d])=>d.l&&d.r).map(([d])=>d);if(o.length){const d=a?o.filter(u=>a.keys.includes(u)):[];d.length&&s.issues.push({...a,keys:d});for(const u of o)!d.includes(u)&&i.has(u)&&s.issues.push(i.get(u))}const c=VHe(t.value,n.value);if(!c.valid){if(vE(s))return s;throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(c.mergeErrorPath)}`)}return s.value=c.data,s}const bAs=Ma("$ZodEnum",(s,t)=>{Px.init(s,t);const n=$He(t.entries),r=new Set(n);s._zod.values=r,ym(s,"pattern",a=>{const i=$He(a.def.entries).filter(l=>t4s.has(typeof l));return new RegExp(i.length?`^(${i.map(l=>NG(l.toString())).join("|")})$`:"^[^\\s\\S]$")}),s._zod.parse=(a,i)=>{const l=a.value;return r.has(l)||a.issues.push({code:"invalid_value",values:n,input:l,inst:s}),a}}),_As=Ma("$ZodLiteral",(s,t)=>{Px.init(s,t);const n=new Set(t.values);s._zod.values=n,ym(s,"pattern",r=>{const a=r.def.values;return new RegExp(a.length?`^(${a.map(i=>typeof i=="string"?NG(i):i?NG(i.toString()):String(i)).join("|")})$`:"^[^\\s\\S]$")}),s._zod.parse=(r,a)=>{const i=r.value;return n.has(i)||r.issues.push({code:"invalid_value",values:t.values,input:i,inst:s}),r}}),wAs=Ma("$ZodTransform",(s,t)=>{var n;Px.init(s,t),s._zod.optin="optional",(n=K4.memoizer)==null||n.guard(s),s._zod.parse=(r,a)=>{if(a.direction==="backward")throw new C8t(s.constructor.name);const i=t.transform(r.value,r);if(a.async)return(i instanceof Promise?i:Promise.resolve(i)).then(o=>(r.value=o,r));if(i instanceof Promise)throw new d7;return r.value=i,r}});function syt(s,t){return s.value=t.issues.length?void 0:t.value,s}const U8t=Ma("$ZodOptional",(s,t)=>{Px.init(s,t),ym(s,"optin",n=>n.def.innerType._zod.optin==="defaulted"?"defaulted":"optional"),s._zod.optout="optional",ym(s,"values",n=>{const r=n.def.innerType._zod.values;return r?new Set([...r,void 0]):void 0}),ym(s,"pattern",n=>{const r=n.def.innerType._zod.pattern;return r?new RegExp(`^(${ltt(r.source)})?$`):void 0}),s._zod.parse=(n,r)=>{if(n.value===void 0){if(t.innerType._zod.optin!=="defaulted")return n;const a=t.innerType._zod.run({value:n.value,issues:[]},r);return a instanceof Promise?a.then(i=>syt(n,i)):syt(n,a)}return t.innerType._zod.run(n,r)}}),jAs=Ma("$ZodExactOptional",(s,t)=>{U8t.init(s,t),ym(s,"values",n=>n.def.innerType._zod.values),ym(s,"pattern",n=>n.def.innerType._zod.pattern),s._zod.parse=(n,r)=>t.innerType._zod.run(n,r)}),NAs=Ma("$ZodNullable",(s,t)=>{Px.init(s,t),ym(s,"optin",n=>n.def.innerType._zod.optin),ym(s,"optout",n=>n.def.innerType._zod.optout),ym(s,"pattern",n=>{const r=n.def.innerType._zod.pattern;return r?new RegExp(`^(${ltt(r.source)}|null)$`):void 0}),ym(s,"values",n=>n.def.innerType._zod.values?new Set([...n.def.innerType._zod.values,null]):void 0),s._zod.parse=(n,r)=>n.value===null?n:t.innerType._zod.run(n,r)}),kAs=Ma("$ZodDefault",(s,t)=>{Px.init(s,t),s._zod.optin="defaulted",ym(s,"values",n=>n.def.innerType._zod.values),s._zod.parse=(n,r)=>{if(r.direction==="backward")return t.innerType._zod.run(n,r);if(n.value===void 0)return n.value=t.defaultValue,n;const a=t.innerType._zod.run(n,r);return a instanceof Promise?a.then(i=>nyt(i,t)):nyt(a,t)}});function nyt(s,t){return s.value===void 0&&(s.value=t.defaultValue),s}const SAs=Ma("$ZodPrefault",(s,t)=>{Px.init(s,t),s._zod.optin="defaulted",ym(s,"values",n=>n.def.innerType._zod.values),s._zod.parse=(n,r)=>(r.direction==="backward"||n.value===void 0&&(n.value=t.defaultValue),t.innerType._zod.run(n,r))}),CAs=Ma("$ZodNonOptional",(s,t)=>{Px.init(s,t),ym(s,"values",n=>{const r=n.def.innerType._zod.values;return r?new Set([...r].filter(a=>a!==void 0)):void 0}),s._zod.parse=(n,r)=>{const a=t.innerType._zod.run(n,r);return a instanceof Promise?a.then(i=>ryt(i,s)):ryt(a,s)}});function ryt(s,t){return!s.issues.length&&s.value===void 0&&s.issues.push({code:"invalid_type",expected:"nonoptional",input:s.value,inst:t}),s}function ayt(s,t,n,r){return t.issues.length?(s.value=n.catchValue({...t,value:s.value,error:{issues:t.issues.map(a=>nK(a,r,i6()))},input:s.value}),s):(s.value=t.value,t.memo&&(s.memo=!0),s)}const AAs=Ma("$ZodCatch",(s,t)=>{Px.init(s,t),ym(s,"optin",n=>n.def.innerType._zod.optin==="defaulted"?"defaulted":"optional"),ym(s,"optout",n=>n.def.innerType._zod.optout),ym(s,"values",n=>n.def.innerType._zod.values),s._zod.parse=(n,r)=>{if(r.direction==="backward")return t.innerType._zod.run(n,r);const a=t.innerType._zod.run({value:n.value,issues:[]},r);return a instanceof Promise?a.then(i=>ayt(n,i,t,r)):ayt(n,a,t,r)}}),EAs=Ma("$ZodPipe",(s,t)=>{Px.init(s,t),ym(s,"values",n=>n.def.in._zod.values),ym(s,"optin",n=>n.def.in._zod.optin),ym(s,"optout",n=>n.def.out._zod.optout),ym(s,"propValues",n=>n.def.in._zod.propValues),s._zod.parse=(n,r)=>{if(r.direction==="backward"){const i=t.out._zod.run(n,r);return i instanceof Promise?i.then(l=>Mce(l,t.in,r)):Mce(i,t.in,r)}const a=t.in._zod.run(n,r);return a instanceof Promise?a.then(i=>Mce(i,t.out,r)):Mce(a,t.out,r)}});function Mce(s,t,n){return s.issues.some(r=>r.code!=="unrecognized_keys")?(s.aborted=!0,s):t._zod.run({value:s.value,issues:s.issues},n)}const TAs=Ma("$ZodReadonly",(s,t)=>{Px.init(s,t),ym(s,"propValues",n=>n.def.innerType._zod.propValues),ym(s,"values",n=>n.def.innerType._zod.values),ym(s,"optin",n=>{var r,a;return(a=(r=n.def.innerType)==null?void 0:r._zod)==null?void 0:a.optin}),ym(s,"optout",n=>{var r,a;return(a=(r=n.def.innerType)==null?void 0:r._zod)==null?void 0:a.optout}),s._zod.parse=(n,r)=>{if(r.direction==="backward")return t.innerType._zod.run(n,r);const a=t.innerType._zod.run(n,r);return a instanceof Promise?a.then(iyt):iyt(a)}});function iyt(s){return s.memo||(s.value=Object.freeze(s.value)),s}const MAs=Ma("$ZodCustom",(s,t)=>{Gw.init(s,t),Px.init(s,t),s._zod.parse=(n,r)=>n,s._zod.check=n=>{const r=n.value,a=t.fn(r);if(a instanceof Promise)return a.then(i=>oyt(i,n,r,s));oyt(a,n,r,s)}});function oyt(s,t,n,r){if(!s){const a={code:"custom",input:n,inst:r,path:[...r._zod.def.path??[]],continue:!r._zod.def.abort};r._zod.def.params&&(a.params=r._zod.def.params),t.issues.push(sse(a))}}class PAs extends Error{constructor(){super("Cannot parse a reference cycle that closes through a transform"),this.name="ZodCyclicError"}}const HHe="~memo",lyt=[];function q8t(s){return s!==null&&typeof s=="object"}function e7e(s){return s.map(t=>t.path?{...t,path:t.path.slice()}:{...t})}const V8t=new WeakMap,cQ=0,Y4e=1,xee=2;function Z4e(s,t,n){const r=V8t.get(s);if(r!==void 0)return r?xee:cQ;if(t.has(s))return xee;t.add(s);let a=cQ;const i=u=>{if(a!==xee&&(u!=null&&u._zod)){const h=Z4e(u,t);h>a&&(a=h)}},l=(u,h)=>{var f;let m=cQ;for(const g of Reflect.ownKeys(u)){const x=Object.getOwnPropertyDescriptor(u,g);if(!x.enumerable)continue;const y=x.get?Y4e:(f=x.value)!=null&&f._zod?Z4e(x.value,t):cQ;y>m&&(m=y)}return m},o=u=>{u>a&&(a=u)},c=s._zod.def;switch(c.type){case"object":{const u=g8t(c);o(u?l(u):Y4e),i(c.catchall);break}case"array":i(c.element);break;case"tuple":for(const u of c.items)i(u);i(c.rest);break;case"record":case"map":i(c.keyType),i(c.valueType);break;case"set":i(c.valueType);break;case"union":for(const u of c.options)i(u);break;case"intersection":i(c.left),i(c.right);break;case"optional":case"nullable":case"default":case"prefault":case"catch":case"readonly":case"nonoptional":case"promise":case"success":i(c.innerType);break;case"pipe":i(c.in),i(c.out);break;case"function":i(c.input),i(c.output);break;case"lazy":{const u=c._cachedInner??void 0;o(u?Z4e(u,t):Y4e);break}case"template_literal":case"string":case"number":case"int":case"boolean":case"bigint":case"symbol":case"undefined":case"null":case"void":case"never":case"any":case"unknown":case"date":case"nan":case"enum":case"literal":case"file":case"transform":case"custom":break;default:for(const u in c){const h=Object.getOwnPropertyDescriptor(c,u);if(!h||h.get)continue;const m=h.value;if(!(!m||typeof m!="object")){if(m._zod)i(m);else if(Array.isArray(m))for(const f of m)i(f)}}}return t.delete(s),IAs(s,a)}function IAs(s,t){return t!==Y4e&&V8t.set(s,t===xee),t}function LAs(s,t){let n=s.buckets.get(t);return n||(n=new WeakMap,s.buckets.set(t,n)),n}let Pce;const Ice=[],RAs={alloc(s,t,n){const r=Pce;if(!r)return n;Pce=void 0;const a={value:n,issues:null};return r.set(t.value,a),Ice.push(a),n},guard(s){var t;(t=s._zod).deferred??(t.deferred=[]),s._zod.deferred.push(()=>{const n=s._zod.parse,r=(a,i)=>{if(i.direction!=="backward"&&FAs(i,a.value))throw new PAs;return n(a,i)};s._zod.parse=r,s._zod.run===n&&(s._zod.run=r)})},attach(s){var t;let n,r=!1,a,i;(t=s._zod).deferred??(t.deferred=[]),s._zod.deferred.push(()=>{const l=s._zod.parse,o=(c,d)=>{if(n===void 0){const v=Z4e(s,new Set);if(v===cQ)return s._zod.parse=l,s._zod.run===o&&(s._zod.run=l),l(c,d);v===xee||r?n=!0:r=!0}const u=c.value;if(!q8t(u))return l(c,d);let h=d[HHe];h||(h={buckets:new WeakMap,backEdges:void 0},d[HHe]=h);let m;a===d?m=i:(m=LAs(h,s),a=d,i=m);const f=m.get(u);if(f)return c.value=f.value,f.issues?f.issues.length&&c.issues.push(...e7e(f.issues)):(c.memo=!0,h.backEdges??(h.backEdges=new WeakSet),h.backEdges.add(f.value)),c;Pce=m;const g=Ice.length,x=l(c,d);Pce=void 0;const y=Ice.length>g?Ice.pop():void 0;return x instanceof Promise?x.then(v=>(y&&(y.issues=v.issues.length?e7e(v.issues):lyt),v)):(y&&(y.issues=x.issues.length?e7e(x.issues):lyt),x)};s._zod.parse=o,s._zod.run===l&&(s._zod.run=o)})}};function DAs(){return RAs}function FAs(s,t){var r;const n=(r=s[HHe])==null?void 0:r.backEdges;return n!==void 0&&q8t(t)&&n.has(t)}const OAs=()=>{const s={string:{unit:"characters",verb:"to have"},file:{unit:"bytes",verb:"to have"},array:{unit:"items",verb:"to have"},set:{unit:"items",verb:"to have"},map:{unit:"entries",verb:"to have"}};function t(i){return s[i]??null}const n={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",mac:"MAC address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",currency_code:"currency code",credit_card:"credit card number",iban:"IBAN",jwt:"JWT",template_literal:"input"},r={nan:"NaN"};function a(i,l){return i==="number"&&typeof l=="number"&&!Number.isFinite(l)?String(l):r[i]??i}return i=>{switch(i.code){case"invalid_type":{const l=a(i.expected),o=h4s(i.input),c=a(o,i.input);return`Invalid input: expected ${l}, received ${c}`}case"invalid_value":return i.values.length===1?`Invalid input: expected ${_8t(i.values[0])}`:`Invalid option: expected one of ${Hxt(i.values,"|")}`;case"too_big":{const l=i.exact?"exactly ":i.inclusive?"<=":"<",o=t(i.origin);return o?`Too big: expected ${i.origin??"value"} to have ${l}${i.maximum.toString()} ${o.unit??"elements"}`:`Too big: expected ${i.origin??"value"} to be ${l}${i.maximum.toString()}`}case"too_small":{const l=i.exact?"exactly ":i.inclusive?">=":">",o=t(i.origin);return o?`Too small: expected ${i.origin} to have ${l}${i.minimum.toString()} ${o.unit}`:`Too small: expected ${i.origin} to be ${l}${i.minimum.toString()}`}case"invalid_format":{const l=i;return l.format==="starts_with"?`Invalid string: must start with "${l.prefix}"`:l.format==="ends_with"?`Invalid string: must end with "${l.suffix}"`:l.format==="includes"?`Invalid string: must include "${l.includes}"`:l.format==="regex"?`Invalid string: must match pattern ${l.pattern}`:`Invalid ${n[l.format]??i.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${i.divisor}`;case"unrecognized_keys":return`Unrecognized key${i.keys.length>1?"s":""}: ${Hxt(i.keys,", ")}`;case"invalid_key":return`Invalid key in ${i.origin}`;case"invalid_union":return i.options&&Array.isArray(i.options)&&i.options.length>0?`Invalid discriminator value. Expected ${i.options.map(o=>`'${o}'`).join(" | ")}`:i.inclusive===!1?"Invalid input: more than one option matched":"Invalid input";case"invalid_element":return`Invalid value in ${i.origin}`;default:return"Invalid input"}}};function zAs(){return{localeError:OAs()}}var cyt;class BAs{constructor(){this._map=new WeakMap,this._idmap=new Map}add(t,...n){const r=n[0];return this._map.set(t,r),r&&typeof r=="object"&&"id"in r&&this._idmap.set(r.id,t),this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(t){const n=this._map.get(t);return n&&typeof n=="object"&&"id"in n&&this._idmap.delete(n.id),this._map.delete(t),this}get(t){const n=t._zod.parent;if(n){const r={...this.get(n)??{}};delete r.id;const a={...r,...this._map.get(t)};return Object.keys(a).length?a:void 0}return this._map.get(t)}has(t){return this._map.has(t)}}function $As(){return new BAs}(cyt=globalThis).__zod_globalRegistry??(cyt.__zod_globalRegistry=$As());const dQ=globalThis.__zod_globalRegistry;function H8t(s){return s.checks&&(s.checks=[...s.checks]),s}function UAs(s,t){return new s(H8t({type:"string",...Pl(t)}))}function qAs(s,t){return new s({type:"string",format:"email",check:"string_format",abort:!1,...Pl(t)})}function VAs(s,t){return new s({type:"string",format:"guid",check:"string_format",abort:!1,...Pl(t)})}function HAs(s,t){return new s({type:"string",format:"uuid",check:"string_format",abort:!1,...Pl(t)})}function GAs(s,t){return new s({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...Pl(t)})}function WAs(s,t){return new s({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...Pl(t)})}function KAs(s,t){return new s({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...Pl(t)})}function YAs(s,t){return new s({type:"string",format:"url",check:"string_format",abort:!1,...Pl(t)})}function ZAs(s,t){return new s({type:"string",format:"emoji",check:"string_format",abort:!1,...Pl(t)})}function XAs(s,t){return new s({type:"string",format:"nanoid",check:"string_format",abort:!1,...Pl(t)})}function QAs(s,t){return new s({type:"string",format:"cuid",check:"string_format",abort:!1,...Pl(t)})}function JAs(s,t){return new s({type:"string",format:"cuid2",check:"string_format",abort:!1,...Pl(t)})}function eEs(s,t){return new s({type:"string",format:"ulid",check:"string_format",abort:!1,...Pl(t)})}function tEs(s,t){return new s({type:"string",format:"xid",check:"string_format",abort:!1,...Pl(t)})}function sEs(s,t){return new s({type:"string",format:"ksuid",check:"string_format",abort:!1,...Pl(t)})}function nEs(s,t){return new s({type:"string",format:"ipv4",check:"string_format",abort:!1,...Pl(t)})}function rEs(s,t){return new s({type:"string",format:"ipv6",check:"string_format",abort:!1,...Pl(t)})}function aEs(s,t){return new s({type:"string",format:"cidrv4",check:"string_format",abort:!1,...Pl(t)})}function iEs(s,t){return new s({type:"string",format:"cidrv6",check:"string_format",abort:!1,...Pl(t)})}function oEs(s,t){return new s({type:"string",format:"base64",check:"string_format",abort:!1,...Pl(t)})}function lEs(s,t){return new s({type:"string",format:"base64url",check:"string_format",abort:!1,...Pl(t)})}function cEs(s,t){return new s({type:"string",format:"e164",check:"string_format",abort:!1,...Pl(t)})}function dEs(s,t){return new s({type:"string",format:"jwt",check:"string_format",abort:!1,...Pl(t)})}function uEs(s,t){return new s({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...Pl(t)})}function hEs(s,t){return new s({type:"string",format:"date",check:"string_format",...Pl(t)})}function mEs(s,t){return new s({type:"string",format:"time",check:"string_format",precision:null,...Pl(t)})}function fEs(s,t){return new s({type:"string",format:"duration",check:"string_format",...Pl(t)})}function pEs(s,t){return new s(H8t({type:"number",checks:[],...Pl(t)}))}function gEs(s,t){return new s({type:"number",check:"number_format",abort:!1,format:"safeint",...Pl(t)})}function xEs(s,t){return new s({type:"boolean",...Pl(t)})}function yEs(s){return new s({type:"unknown"})}function vEs(s,t){return new s({type:"never",...Pl(t)})}function dyt(s,t){return new T8t({check:"less_than",...Pl(t),value:s,inclusive:!1})}function t7e(s,t){return new T8t({check:"less_than",...Pl(t),value:s,inclusive:!0})}function uyt(s,t){return new M8t({check:"greater_than",...Pl(t),value:s,inclusive:!1})}function s7e(s,t){return new M8t({check:"greater_than",...Pl(t),value:s,inclusive:!0})}function hyt(s,t){return new x3s({check:"multiple_of",...Pl(t),value:s})}function G8t(s,t){return new v3s({check:"max_length",...Pl(t),maximum:s})}function EEe(s,t){return new b3s({check:"min_length",...Pl(t),minimum:s})}function W8t(s,t){return new _3s({check:"length_equals",...Pl(t),length:s})}function bEs(s,t){return new w3s({check:"string_format",format:"regex",...Pl(t),pattern:s})}function _Es(s){return new j3s({check:"string_format",format:"lowercase",...Pl(s)})}function wEs(s){return new N3s({check:"string_format",format:"uppercase",...Pl(s)})}function jEs(s,t){return new k3s({check:"string_format",format:"includes",...Pl(t),includes:s})}function NEs(s,t){return new S3s({check:"string_format",format:"starts_with",...Pl(t),prefix:s})}function kEs(s,t){return new C3s({check:"string_format",format:"ends_with",...Pl(t),suffix:s})}function rK(s){return new A3s({check:"overwrite",tx:s})}function SEs(s){return rK(t=>t.normalize(s))}function CEs(){return rK(s=>s.trim())}function AEs(){return rK(s=>s.toLowerCase())}function EEs(){return rK(s=>s.toUpperCase())}function TEs(){return rK(s=>J5s(s))}function MEs(s,t,n){return new s({type:"array",element:t,...Pl(n)})}function PEs(s,t,n){return new s({type:"custom",check:"custom",fn:t,...Pl(n)})}function IEs(s,t){const n=LEs(r=>(r.addIssue=a=>{if(typeof a=="string")r.issues.push(sse(a,r.value,n._zod.def));else{const i=a;i.fatal&&(i.continue=!1),i.code??(i.code="custom"),"input"in i||(i.input=r.value),i.inst??(i.inst=n),i.continue??(i.continue=!n._zod.def.abort),r.issues.push(sse(i))}},s(r.value,r)),t);return n}function LEs(s,t){const n=new Gw({check:"custom",...Pl(t)});return n._zod.check=s,n}function yee(s,...t){for(const n of t)for(const r of Reflect.ownKeys(n))Object.prototype.propertyIsEnumerable.call(n,r)&&UB(s,r,n[r]);return s}function K8t(s){let t=(s==null?void 0:s.target)??"draft-2020-12";return t==="draft-4"&&(t="draft-04"),t==="draft-7"&&(t="draft-07"),{processors:s.processors??{},metadataRegistry:(s==null?void 0:s.metadata)??dQ,target:t,unrepresentable:(s==null?void 0:s.unrepresentable)??"throw",override:(s==null?void 0:s.override)??(()=>{}),io:(s==null?void 0:s.io)??"output",counter:0,seen:new Map,sharedDefsExtractedFor:void 0,sharedEmitDoneFor:void 0,cycles:(s==null?void 0:s.cycles)??"ref",reused:(s==null?void 0:s.reused)??"inline",intersections:[],deferred:[],external:(s==null?void 0:s.external)??void 0}}function AL(s,t,n,r,a){const i=typeof t.unrepresentable=="function"?t.unrepresentable({zodSchema:s,path:r.path,message:a}):t.unrepresentable;if(i==="any")return!1;if(i===void 0||i==="throw")throw new Error(a);return Object.assign(n,i),!0}function Eb(s,t,n={path:[],schemaPath:[]}){var u,h;var r;const a=s._zod.def,i=t.seen.get(s);if(i)return i.count++,n.schemaPath.includes(s)&&(i.cycle=n.path),i.schema;const l={schema:{},count:1,cycle:void 0,path:n.path};t.seen.set(s,l),t.sharedDefsExtractedFor=void 0,t.sharedEmitDoneFor=void 0;const o=(h=(u=s._zod).toJSONSchema)==null?void 0:h.call(u);if(o)l.schema=o;else{const m={...n,schemaPath:[...n.schemaPath,s],path:n.path};if(s._zod.processJSONSchema)s._zod.processJSONSchema(t,l.schema,m);else{const g=l.schema,x=t.processors[a.type];if(!x)throw new Error(`[toJSONSchema]: Non-representable type encountered: ${a.type}`);x(s,t,g,m)}const f=s._zod.parent;f&&(l.ref||(l.ref=f),Eb(f,t,m),t.seen.get(f).isParent=!0)}const c=t.metadataRegistry.get(s);return c&&yee(l.schema,c),t.io==="input"&&e_(s)&&(delete l.schema.examples,delete l.schema.default),t.io==="input"&&"_prefault"in l.schema&&((r=l.schema).default??(r.default=l.schema._prefault)),delete l.schema._prefault,t.seen.get(s).schema}function myt(s){return s.replace(/~/g,"~0").replace(/\//g,"~1")}function Y8t(s,t){var l,o,c,d;const n=s.seen.get(t);if(!n)throw new Error("Unprocessed schema. This is a bug in Zod.");if(s.external&&s.sharedDefsExtractedFor===s.external)return;const r=new Map;for(const u of s.seen.entries()){const h=(l=s.metadataRegistry.get(u[0]))==null?void 0:l.id;if(h){const m=r.get(h);if(m&&m!==u[0])throw new Error(`Duplicate schema id "${h}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);r.set(h,u[0])}}const a=u=>{var x;const h=s.target==="draft-2020-12"?"$defs":"definitions";if(s.external){const y=(x=s.external.registry.get(u[0]))==null?void 0:x.id,v=s.external.uri??(w=>w);if(y)return{ref:v(y)};const b=u[1].defId??u[1].schema.id??`schema${s.counter++}`;return u[1].defId=b,{defId:b,ref:`${v("__shared")}#/${h}/${myt(b)}`}}const m="#",f=`${m}/${h}/`;if(u[1]===n&&!u[1].schema.id)return{ref:m};const g=u[1].schema.id??`__schema${s.counter++}`;return{defId:g,ref:f+myt(g)}},i=u=>{if(u[1].schema.$ref)return;const h=u[1],{ref:m,defId:f}=a(u);h.def={...h.schema},f&&(h.defId=f);const g=h.schema;for(const x in g)delete g[x];g.$ref=m};if(s.cycles==="throw")for(const u of s.seen.entries()){const h=u[1];if(h.cycle)throw new Error(`Cycle detected: #/${(o=h.cycle)==null?void 0:o.join("/")}/ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(const u of s.seen.entries()){const h=u[1];if(t===u[0]){i(u);continue}if(s.external){const f=(c=s.external.registry.get(u[0]))==null?void 0:c.id;if(t!==u[0]&&f){i(u);continue}}if((d=s.metadataRegistry.get(u[0]))==null?void 0:d.id){i(u);continue}if(h.cycle){i(u);continue}h.count>1&&s.reused==="ref"&&i(u)}s.external&&(s.sharedDefsExtractedFor=s.external)}function Z8t(s){const t=s.anyOf;if(!Array.isArray(t)||t.length===0||s.type!==void 0)return;const n=[];for(const r of t){if(!r||typeof r!="object")return;Z8t(r);const a=Object.keys(r);if(a.length!==1||a[0]!=="type")return;const i=r.type;for(const l of Array.isArray(i)?i:[i]){if(typeof l!="string")return;n.includes(l)||n.push(l)}}delete s.anyOf,s.type=n.length===1?n[0]:n}const X8t=new Set(["type","properties","required","additionalProperties"]),fyt=["oneOf","anyOf"];function pyt(s){const t=s.additionalProperties;return t===void 0||t===!1||typeof t!="object"||t===null?null:Object.keys(t).length?t:null}function GHe(s){var i;const t=[];for(const l of s){if(typeof l!="object"||l.type!=="object")return null;for(const o in l)if(!X8t.has(o))return null;t.push(l)}const n={},r=new Set;for(const l of t){for(const o in l.properties){if(Object.prototype.hasOwnProperty.call(n,o))continue;const c=[];for(const u of t){const h=((i=u.properties)==null?void 0:i[o])??pyt(u);h!=null&&(c.some(m=>JSON.stringify(m)===JSON.stringify(h))||c.push(h))}const d=c.length===1?c[0]:GHe(c)??{allOf:c};UB(n,o,d)}for(const o of l.required??[])r.add(o)}const a={type:"object",properties:n};if(r.size&&(a.required=[...r]),t.every(l=>l.additionalProperties===!1))a.additionalProperties=!1;else{const l=[];for(const o of t){const c=pyt(o);c&&!l.some(d=>JSON.stringify(d)===JSON.stringify(c))&&l.push(c)}l.length===1?a.additionalProperties=l[0]:l.length>1&&(a.additionalProperties={allOf:l})}return a}function REs(s){const t=s.allOf;if(!Array.isArray(t)||t.length<2)return;for(const a of X8t)if(a in s)return;const n=t.filter(a=>fyt.some(i=>Array.isArray(a[i])));let r=null;if(!n.length)r=GHe(t);else{const a=n[0],i=fyt.find(c=>Array.isArray(a[c]));if(Object.keys(a).length!==1)return;const l=t.filter(c=>c!==a),o=a[i].map(c=>GHe([...l,c]));if(o.some(c=>!c))return;r={[i]:o}}r&&(delete s.allOf,yee(s,r))}function Q8t(s,t){var o,c,d,u;const n=s.seen.get(t);if(!n)throw new Error("Unprocessed schema. This is a bug in Zod.");const r=h=>{const m=s.seen.get(h);if(m.ref===null)return;const f=m.def??m.schema,g={...f},x=m.ref;if(m.ref=null,x){r(x);const v=s.seen.get(x),b=v.schema;if(b.$ref&&(s.target==="draft-07"||s.target==="draft-04"||s.target==="openapi-3.0")?(f.allOf=f.allOf??[],f.allOf.push(b)):yee(f,b),yee(f,g),h._zod.parent===x)for(const S in f)S==="$ref"||S==="allOf"||S in g||delete f[S];if(b.$ref&&v.def)for(const S in f)S==="$ref"||S==="allOf"||S in v.def&&JSON.stringify(f[S])===JSON.stringify(v.def[S])&&delete f[S]}const y=h._zod.parent;if(y&&y!==x){r(y);const v=s.seen.get(y);if(v!=null&&v.schema.$ref&&(f.$ref=v.schema.$ref,v.def))for(const b in f)b==="$ref"||b==="allOf"||b in v.def&&JSON.stringify(f[b])===JSON.stringify(v.def[b])&&delete f[b]}s.override({zodSchema:h,jsonSchema:f,path:m.path??[]})};if(!s.external||s.sharedEmitDoneFor!==s.external){for(const h of[...s.seen.entries()].reverse())r(h[0]);if(s.target!=="openapi-3.0")for(const h of s.seen.entries())Z8t(h[1].def??h[1].schema);for(const h of s.deferred)h();if(s.intersections.length){const h=new Map;for(const m of s.seen.values())for(const f of[m.schema,m.def]){const g=f==null?void 0:f.allOf;if(!Array.isArray(g))continue;const x=h.get(g);x?x.push(f):h.set(g,[f])}for(const m of s.intersections)for(const f of h.get(m)??[])REs(f)}}const a={};if(s.target==="draft-2020-12"?a.$schema="https://json-schema.org/draft/2020-12/schema":s.target==="draft-07"?a.$schema="http://json-schema.org/draft-07/schema#":s.target==="draft-04"?a.$schema="http://json-schema.org/draft-04/schema#":s.target,(o=s.external)!=null&&o.uri){const h=(c=s.external.registry.get(t))==null?void 0:c.id;if(!h)throw new Error("Schema is missing an `id` property");a.$id=s.external.uri(h)}yee(a,n.defId?n.schema:n.def??n.schema);const i=(d=s.metadataRegistry.get(t))==null?void 0:d.id;i!==void 0&&a.id===i&&delete a.id;const l=((u=s.external)==null?void 0:u.defs)??{};if(!s.external||s.sharedEmitDoneFor!==s.external)for(const h of s.seen.entries()){const m=h[1];m.def&&m.defId&&(m.def.id===m.defId&&delete m.def.id,UB(l,m.defId,m.def))}s.external&&(s.sharedEmitDoneFor=s.external),s.external||Object.keys(l).length>0&&(s.target==="draft-2020-12"?a.$defs=l:a.definitions=l);try{const h=JSON.parse(JSON.stringify(a));return Object.defineProperty(h,"~standard",{value:{...t["~standard"],jsonSchema:{input:TEe(t,"input",s.processors),output:TEe(t,"output",s.processors)}},enumerable:!1,writable:!1}),h}catch{throw new Error("Error converting schema to JSON.")}}function e_(s,t){const n=t??{seen:new Set};if(n.seen.has(s))return!1;n.seen.add(s);const r=s._zod.def;if(r.type==="transform")return!0;if(r.type==="array")return e_(r.element,n);if(r.type==="set")return e_(r.valueType,n);if(r.type==="lazy")return e_(r.getter(),n);if(r.type==="promise"||r.type==="optional"||r.type==="nonoptional"||r.type==="nullable"||r.type==="readonly"||r.type==="default"||r.type==="prefault"||r.type==="catch")return e_(r.innerType,n);if(r.type==="intersection")return e_(r.left,n)||e_(r.right,n);if(r.type==="record"||r.type==="map")return e_(r.keyType,n)||e_(r.valueType,n);if(r.type==="pipe")return s._zod.traits.has("$ZodCodec")?!0:e_(r.in,n)||e_(r.out,n);if(r.type==="object"){for(const a in r.shape)if(e_(r.shape[a],n))return!0;return!1}if(r.type==="union"){for(const a of r.options)if(e_(a,n))return!0;return!1}if(r.type==="tuple"){for(const a of r.items)if(e_(a,n))return!0;return!!(r.rest&&e_(r.rest,n))}return!1}const DEs=(s,t={})=>n=>{const r=K8t({...n,processors:t});return Eb(s,r),Y8t(r,s),Q8t(r,s)},TEe=(s,t,n={})=>r=>{const{libraryOptions:a,target:i}=r??{},l=K8t({...a??{},target:i,io:t,processors:n});return Eb(s,l),Y8t(l,s),Q8t(l,s)},kG=(s,t,n)=>{(s[t]===void 0||n>s[t])&&(s[t]=n)},SG=(s,t,n)=>{(s[t]===void 0||n{kG(s,"minimum",t),SG(s,"maximum",t)},J8t=(s,t)=>{s.multipleOf??(s.multipleOf=[]),s.multipleOf.includes(t)||s.multipleOf.push(t)},ezt=(s,t)=>{s.patterns??(s.patterns=new Set),s.patterns.add(t)},tzt=(s,t)=>{s.mime=s.mime?s.mime.filter(n=>t.includes(n)):[...t]},szt=(s,t)=>{s.format=t,t.includes("int")&&(s.isInt=!0)},xyt=(s,t)=>kG(s,"minimum",t.minimum),yyt=(s,t)=>SG(s,"maximum",t.maximum),vyt=s=>(t,n)=>{szt(t,n.format);const[r,a]=s[n.format];kG(t,"minimum",r),SG(t,"maximum",a)},n7e={greater_than:(s,t)=>kG(s,t.inclusive?"minimum":"exclusiveMinimum",t.value),less_than:(s,t)=>SG(s,t.inclusive?"maximum":"exclusiveMaximum",t.value),multiple_of:(s,t)=>J8t(s,t.value),number_format:vyt(w8t),bigint_format:vyt(n4s),min_length:xyt,max_length:yyt,length_equals:(s,t)=>gyt(s,t.length),min_size:xyt,max_size:yyt,size_equals:(s,t)=>gyt(s,t.size),string_format:(s,t)=>{szt(s,t.format),t.pattern&&ezt(s,t.pattern),(t.format==="base64"||t.format==="base64url")&&(s.contentEncoding=t.format),(t.local||t.precision===-1)&&(s.laxFormat=!0)},mime_type:(s,t)=>tzt(s,t.mime)};function x4(s){var i;const t={},n=s._zod.def,r=s._zod.traits.has("$ZodCheck")?[s,...n.checks??[]]:n.checks??[];for(const l of r)(i=n7e[l._zod.def.check])==null||i.call(n7e,t,l._zod.def);const a=s._zod.bag;a.minimum!==void 0&&kG(t,"minimum",a.minimum),a.exclusiveMinimum!==void 0&&kG(t,"exclusiveMinimum",a.exclusiveMinimum),a.maximum!==void 0&&SG(t,"maximum",a.maximum),a.exclusiveMaximum!==void 0&&SG(t,"exclusiveMaximum",a.exclusiveMaximum),a.multipleOf!==void 0&&J8t(t,a.multipleOf),a.format!==void 0&&(t.format??(t.format=a.format),a.format.includes("int")&&(t.isInt=!0)),a.mime&&tzt(t,a.mime);for(const l of a.patterns??[])ezt(t,l);return t}const FEs={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},OEs=new Map([[O8t,r3s],[xtt,a3s]]),zEs=s=>OEs.get(s)??s,BEs=(s,t,n,r)=>{const a=n;a.type="string";const{minimum:i,maximum:l,format:o,patterns:c,contentEncoding:d,laxFormat:u}=x4(s);if(typeof i=="number"&&(a.minLength=i),typeof l=="number"&&(a.maxLength=l),o&&(a.format=FEs[o]??o,a.format===""&&delete a.format,(o==="time"||u)&&delete a.format),d&&(a.contentEncoding=d),c&&c.size>0){const h=[...c].map(zEs);h.length===1?a.pattern=h[0].source:h.length>1&&(a.allOf=[...h.map(m=>({...t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0"?{type:"string"}:{},pattern:m.source}))])}},$Es=(s,t,n,r)=>{const a=n,{minimum:i,maximum:l,multipleOf:o,exclusiveMaximum:c,exclusiveMinimum:d,isInt:u}=x4(s);a.type=u?"integer":"number";const h=typeof d=="number"&&d>=(i??Number.NEGATIVE_INFINITY),m=typeof c=="number"&&c<=(l??Number.POSITIVE_INFINITY),f=t.target==="draft-04"||t.target==="openapi-3.0";if(h?f?(a.minimum=d,a.exclusiveMinimum=!0):a.exclusiveMinimum=d:typeof i=="number"&&(a.minimum=i),m?f?(a.maximum=c,a.exclusiveMaximum=!0):a.exclusiveMaximum=c:typeof l=="number"&&(a.maximum=l),o){const g=new Set;for(const v of o)Number.isFinite(v)&&v!==0?g.add(Math.abs(v)):AL(s,t,a,r,`A multipleOf divisor of ${v} cannot be represented in JSON Schema`);const[x,...y]=g;x!==void 0&&(a.multipleOf=x),y.length&&(a.allOf=[...a.allOf??[],...y.map(v=>({multipleOf:v}))])}},UEs=(s,t,n,r)=>{n.type="boolean"},qEs=(s,t,n,r)=>{n.not={}},VEs=(s,t,n,r)=>{},HEs=(s,t,n,r)=>{const a=s._zod.def,i=$He(a.entries);if(i.length===0){n.not={};return}i.every(l=>typeof l=="number")&&(n.type="number"),i.every(l=>typeof l=="string")&&(n.type="string"),n.enum=i},GEs=(s,t,n,r)=>{const a=s._zod.def;if(a.values.length===0){n.not={};return}const i=[];for(const l of a.values)if(l===void 0){if(AL(s,t,n,r,"Literal `undefined` cannot be represented in JSON Schema"))return}else if(typeof l=="bigint"){if(AL(s,t,n,r,"BigInt literals cannot be represented in JSON Schema"))return;i.push(Number(l))}else i.push(l);if(i.length!==0)if(i.length===1){const l=i[0];n.type=l===null?"null":typeof l,t.target==="draft-04"||t.target==="openapi-3.0"?n.enum=[l]:n.const=l}else i.every(l=>typeof l=="number")&&(n.type="number"),i.every(l=>typeof l=="string")&&(n.type="string"),i.every(l=>typeof l=="boolean")&&(n.type="boolean"),i.every(l=>l===null)&&(n.type="null"),n.enum=i},WEs=(s,t,n,r)=>{AL(s,t,n,r,"Custom types cannot be represented in JSON Schema")},KEs=(s,t,n,r)=>{AL(s,t,n,r,"Transforms cannot be represented in JSON Schema")},YEs=(s,t,n,r)=>{const a=n,i=s._zod.def,{minimum:l,maximum:o}=x4(s);typeof l=="number"&&(a.minItems=l),typeof o=="number"&&(a.maxItems=o),a.type="array",a.items=Eb(i.element,t,{...r,path:[...r.path,"items"]})};function WHe(s){const t=s._zod.def;return t.type==="pipe"&&t.in._zod.traits.has("$ZodTransform")?WHe(t.out):t.type==="catch"?WHe(t.innerType):s._zod.optin}const ZEs=(s,t,n,r)=>{var d;const a=n,i=s._zod.def,l=i.shape;if(Object.getOwnPropertySymbols(l).length&&AL(s,t,a,r,"Symbol keys cannot be represented in JSON Schema"))return;a.type="object",a.properties={};for(const u in l)UB(a.properties,u,Eb(l[u],t,{...r,path:[...r.path,"properties",u]}));const c=[];for(const u of Object.keys(l)){const h=i.shape[u];(t.io==="input"?WHe(h)===void 0:h._zod.optout===void 0)&&c.push(u)}c.length>0&&(a.required=c),((d=i.catchall)==null?void 0:d._zod.def.type)==="never"?a.additionalProperties=!1:i.catchall?i.catchall&&(a.additionalProperties=Eb(i.catchall,t,{...r,path:[...r.path,"additionalProperties"]})):t.io==="output"&&(a.additionalProperties=!1)},XEs=(s,t,n,r)=>{const a=s._zod.def,i=a.inclusive===!1,l=a.options.map((o,c)=>Eb(o,t,{...r,path:[...r.path,i?"oneOf":"anyOf",c]}));i?n.oneOf=l:n.anyOf=l},QEs=(s,t,n,r)=>{const a=s._zod.def,i=Eb(a.left,t,{...r,path:[...r.path,"allOf",0]}),l=Eb(a.right,t,{...r,path:[...r.path,"allOf",1]}),o=d=>"allOf"in d&&Object.keys(d).length===1,c=[...o(i)?i.allOf:[i],...o(l)?l.allOf:[l]];n.allOf=c,t.intersections.push(c)},JEs=(s,t,n,r)=>{const a=s._zod.def,i=Eb(a.innerType,t,r),l=t.seen.get(s);t.target==="openapi-3.0"?(l.ref=a.innerType,n.nullable=!0):n.anyOf=[i,{type:"null"}]},eTs=(s,t,n,r)=>{const a=s._zod.def;Eb(a.innerType,t,r);const i=t.seen.get(s);i.ref=a.innerType},ytt=Symbol();function nzt(s,t,n,r,a){let i=!1;const l=JSON.stringify(s,(o,c)=>typeof c!="bigint"?c:(i=!0,null));return i?(AL(t,n,r,a,"BigInt defaults cannot be represented in JSON Schema"),ytt):JSON.parse(l)}const tTs=(s,t,n,r)=>{const a=s._zod.def;Eb(a.innerType,t,r);const i=t.seen.get(s);i.ref=a.innerType;const l=nzt(a.defaultValue,s,t,n,r);l!==ytt&&(n.default=l)},sTs=(s,t,n,r)=>{const a=s._zod.def;Eb(a.innerType,t,r);const i=t.seen.get(s);if(i.ref=a.innerType,t.io!=="input")return;const l=nzt(a.defaultValue,s,t,n,r);l!==ytt&&(n._prefault=l)},nTs=(s,t,n,r)=>{const a=s._zod.def;Eb(a.innerType,t,r);const i=t.seen.get(s);i.ref=a.innerType;let l;try{l=a.catchValue(void 0)}catch{AL(s,t,n,r,"Dynamic catch values are not supported in JSON Schema");return}n.default=l},rTs=(s,t,n,r)=>{const a=s._zod.def,i=a.in._zod.traits.has("$ZodTransform"),l=t.io==="input"?i?a.out:a.in:a.out;Eb(l,t,r);const o=t.seen.get(s);o.ref=l},aTs=(s,t,n,r)=>{const a=s._zod.def;Eb(a.innerType,t,r);const i=t.seen.get(s);i.ref=a.innerType,n.readOnly=!0},rzt=(s,t,n,r)=>{const a=s._zod.def;Eb(a.innerType,t,r);const i=t.seen.get(s);i.ref=a.innerType},byt=new WeakSet([Object.prototype,Error.prototype]);function Lce(s,t,n){Object.defineProperty(s,t,{configurable:!0,enumerable:!1,get(){const r=n(this);return Object.defineProperty(this,t,{value:r,configurable:!0,writable:!0}),r},set(r){Object.defineProperty(this,t,{value:r,configurable:!0,writable:!0})}})}const azt=(s,t)=>{k4s.init(s,t),s.name="ZodError";const n=Object.getPrototypeOf(s);byt.has(n)||(byt.add(n),Lce(n,"format",r=>a=>A4s(r,a)),Lce(n,"flatten",r=>a=>C4s(r,a)),Lce(n,"addIssue",r=>a=>{r.issues.push(a),r.message=JSON.stringify(r.issues,UHe,2)}),Lce(n,"addIssues",r=>a=>{r.issues.push(...a),r.message=JSON.stringify(r.issues,UHe,2)}),Object.defineProperty(n,"isEmpty",{configurable:!0,enumerable:!1,get(){return this.issues.length===0}}))},iTs=Ma("ZodError",azt),Ck=Ma("ZodError",azt,void 0,{Parent:Error}),oTs=utt(Ck),lTs=htt(Ck),cTs=mtt(Ck),dTs=ftt(Ck),uTs=L4s(Ck),hTs=R4s(Ck),mTs=D4s(Ck),fTs=F4s(Ck),pTs=O4s(Ck),gTs=z4s(Ck),xTs=B4s(Ck),yTs=$4s(Ck);function vTs(){K4.localeError||i6(zAs())}function vtt(){K4.memoizer||i6({memoizer:DAs()})}const Ix=Ma("ZodType",(s,t)=>(vTs(),Px.init(s,t),s.def=t,s.type=t.type,s),{check(...s){const t=this.def;return this.clone(Zj(t,{checks:[...t.checks??[],...s.map(n=>typeof n=="function"?{_zod:{check:n,def:{check:"custom"},onattach:[]}}:n)]}),{parent:!0})},with(...s){return this.check(...s)},clone(s,t){return a6(this,s,t)},brand(){return this},register(s,t){return s.add(this,t),this},refine(s,t){return this.check(yMs(s,t))},superRefine(s,t){return this.check(vMs(s,t))},overwrite(s){return this.check(rK(s))},optional(){return jyt(this)},exactOptional(){return aMs(this)},nullable(){return Nyt(this)},nullish(){return jyt(Nyt(this))},nonoptional(s){return uMs(this,s)},array(){return ZTs(this)},or(s){return JTs([this,s])},and(s){return tMs(this,s)},transform(s){return kyt(this,rMs(s))},default(s){return lMs(this,s)},prefault(s){return dMs(this,s)},catch(s){return mMs(this,s)},pipe(s){return kyt(this,s)},readonly(){return gMs(this)},describe(s){const t=this.clone();return dQ.add(t,{description:s}),t},meta(...s){if(s.length===0)return dQ.get(this);const t=this.clone();return dQ.add(t,s[0]),t},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(s,...t){return t.length===0?s(this):s(this,...t)},get"~standard"(){return k8t(this,"~standard",{...I8t(this),jsonSchema:{input:TEe(this,"input"),output:TEe(this,"output")}})},set"~standard"(s){CL(this,"~standard",s)},parse:function s(t,n){return oTs(this,t,n,{callee:s})},parseAsync:async function s(t,n){return await lTs(this,t,n,{callee:s})},safeParse(s,t){return cTs(this,s,t)},async safeParseAsync(s,t){return dTs(this,s,t)},get spa(){return this==null?void 0:this.safeParseAsync},set spa(s){CL(this,"spa",s)},validate(s,t){return M4s(this,s,t)},validateAsync(s,t){return I4s(this,s,t)},encode:function s(t,n){return uTs(this,t,n,{callee:s})},decode:function s(t,n){return hTs(this,t,n,{callee:s})},encodeAsync:async function s(t,n){return await mTs(this,t,n,{callee:s})},decodeAsync:async function s(t,n){return await fTs(this,t,n,{callee:s})},safeEncode(s,t){return pTs(this,s,t)},safeDecode(s,t){return gTs(this,s,t)},async safeEncodeAsync(s,t){return xTs(this,s,t)},async safeDecodeAsync(s,t){return yTs(this,s,t)},toJSONSchema(s){return DEs(this,{})(s)},get description(){var s;return(s=dQ.get(this))==null?void 0:s.description},get _def(){return this._zod.def}}),izt=Ma("_ZodString",(s,t)=>{gtt.init(s,t),Ix.init(s,t),s._zod.processJSONSchema=(n,r,a)=>BEs(s,n,r)},S8t({format:s=>x4(s).format??null,minLength:s=>x4(s).minimum??null,maxLength:s=>x4(s).maximum??null},{regex(...s){return this.check(bEs(...s))},includes(...s){return this.check(jEs(...s))},startsWith(...s){return this.check(NEs(...s))},endsWith(...s){return this.check(kEs(...s))},min(...s){return this.check(EEe(...s))},max(...s){return this.check(G8t(...s))},length(...s){return this.check(W8t(...s))},nonempty(...s){return this.check(EEe(1,...s))},lowercase(s){return this.check(_Es(s))},uppercase(s){return this.check(wEs(s))},trim(){return this.check(CEs())},normalize(...s){return this.check(SEs(...s))},toLowerCase(){return this.check(AEs())},toUpperCase(){return this.check(EEs())},slugify(){return this.check(TEs())}})),bTs=Ma("ZodString",(s,t)=>{gtt.init(s,t),izt.init(s,t)},{email(s){return this.check(qAs(kTs,s))},url(s){return this.check(YAs(CTs,s))},jwt(s){return this.check(dEs(UTs,s))},emoji(s){return this.check(ZAs(ATs,s))},guid(s){return this.check(VAs(STs,s))},uuid(s){return this.check(HAs(Rce,s))},uuidv4(s){return this.check(GAs(Rce,s))},uuidv6(s){return this.check(WAs(Rce,s))},uuidv7(s){return this.check(KAs(Rce,s))},nanoid(s){return this.check(XAs(ETs,s))},cuid(s){return this.check(QAs(TTs,s))},cuid2(s){return this.check(JAs(MTs,s))},ulid(s){return this.check(eEs(PTs,s))},base64(s){return this.check(oEs(zTs,s))},base64url(s){return this.check(lEs(BTs,s))},xid(s){return this.check(tEs(ITs,s))},ksuid(s){return this.check(sEs(LTs,s))},ipv4(s){return this.check(nEs(RTs,s))},ipv6(s){return this.check(rEs(DTs,s))},cidrv4(s){return this.check(aEs(FTs,s))},cidrv6(s){return this.check(iEs(OTs,s))},e164(s){return this.check(cEs($Ts,s))},datetime(s){return this.check(uEs(_Ts,s))},date(s){return this.check(hEs(wTs,s))},time(s){return this.check(mEs(jTs,s))},duration(s){return this.check(fEs(NTs,s))}});function vl(s){return UAs(bTs,s)}const Kg=Ma("ZodStringFormat",(s,t)=>{sg.init(s,t),izt.init(s,t)}),_Ts=Ma("ZodISODateTime",(s,t)=>{K3s.init(s,t),Kg.init(s,t)}),wTs=Ma("ZodISODate",(s,t)=>{Y3s.init(s,t),Kg.init(s,t)}),jTs=Ma("ZodISOTime",(s,t)=>{Z3s.init(s,t),Kg.init(s,t)}),NTs=Ma("ZodISODuration",(s,t)=>{X3s.init(s,t),Kg.init(s,t)}),kTs=Ma("ZodEmail",(s,t)=>{L3s.init(s,t),Kg.init(s,t)}),STs=Ma("ZodGUID",(s,t)=>{P3s.init(s,t),Kg.init(s,t)}),Rce=Ma("ZodUUID",(s,t)=>{I3s.init(s,t),Kg.init(s,t)}),CTs=Ma("ZodURL",(s,t)=>{B3s.init(s,t),Kg.init(s,t)}),ATs=Ma("ZodEmoji",(s,t)=>{$3s.init(s,t),Kg.init(s,t)}),ETs=Ma("ZodNanoID",(s,t)=>{U3s.init(s,t),Kg.init(s,t)}),TTs=Ma("ZodCUID",(s,t)=>{q3s.init(s,t),Kg.init(s,t)}),MTs=Ma("ZodCUID2",(s,t)=>{V3s.init(s,t),Kg.init(s,t)}),PTs=Ma("ZodULID",(s,t)=>{H3s.init(s,t),Kg.init(s,t)}),ITs=Ma("ZodXID",(s,t)=>{G3s.init(s,t),Kg.init(s,t)}),LTs=Ma("ZodKSUID",(s,t)=>{W3s.init(s,t),Kg.init(s,t)}),RTs=Ma("ZodIPv4",(s,t)=>{Q3s.init(s,t),Kg.init(s,t)}),DTs=Ma("ZodIPv6",(s,t)=>{eAs.init(s,t),Kg.init(s,t)}),FTs=Ma("ZodCIDRv4",(s,t)=>{tAs.init(s,t),Kg.init(s,t)}),OTs=Ma("ZodCIDRv6",(s,t)=>{nAs.init(s,t),Kg.init(s,t)}),zTs=Ma("ZodBase64",(s,t)=>{rAs.init(s,t),Kg.init(s,t)}),BTs=Ma("ZodBase64URL",(s,t)=>{iAs.init(s,t),Kg.init(s,t)}),$Ts=Ma("ZodE164",(s,t)=>{oAs.init(s,t),Kg.init(s,t)}),UTs=Ma("ZodJWT",(s,t)=>{cAs.init(s,t),Kg.init(s,t)}),ozt=Ma("ZodNumber",(s,t)=>{z8t.init(s,t),Ix.init(s,t),s._zod.processJSONSchema=(n,r,a)=>$Es(s,n,r,a),s.isFinite=!0},S8t({minValue:s=>{const{minimum:t,exclusiveMinimum:n}=x4(s);return Math.max(t??Number.NEGATIVE_INFINITY,n??Number.NEGATIVE_INFINITY)},maxValue:s=>{const{maximum:t,exclusiveMaximum:n}=x4(s);return Math.min(t??Number.POSITIVE_INFINITY,n??Number.POSITIVE_INFINITY)},isInt:s=>{const{isInt:t,multipleOf:n}=x4(s);return!!t||!!(n!=null&&n.some(Number.isSafeInteger))},format:s=>x4(s).format??null},{gt(s,t){return this.check(uyt(s,t))},gte(s,t){return this.check(s7e(s,t))},min(s,t){return this.check(s7e(s,t))},lt(s,t){return this.check(dyt(s,t))},lte(s,t){return this.check(t7e(s,t))},max(s,t){return this.check(t7e(s,t))},int(s){return this.check(_yt(s))},safe(s){return this.check(_yt(s))},positive(s){return this.check(uyt(0,s))},nonnegative(s){return this.check(s7e(0,s))},negative(s){return this.check(dyt(0,s))},nonpositive(s){return this.check(t7e(0,s))},multipleOf(s,t){return this.check(hyt(s,t))},step(s,t){return this.check(hyt(s,t))},finite(){return this}}));function vee(s){return pEs(ozt,s)}const qTs=Ma("ZodNumberFormat",(s,t)=>{dAs.init(s,t),ozt.init(s,t)});function _yt(s){return gEs(qTs,s)}const VTs=Ma("ZodBoolean",(s,t)=>{uAs.init(s,t),Ix.init(s,t),s._zod.processJSONSchema=(n,r,a)=>UEs(s,n,r)});function HTs(s){return xEs(VTs,s)}const GTs=Ma("ZodUnknown",(s,t)=>{hAs.init(s,t),Ix.init(s,t),s._zod.processJSONSchema=(n,r,a)=>VEs()});function wyt(){return yEs(GTs)}const WTs=Ma("ZodNever",(s,t)=>{mAs.init(s,t),Ix.init(s,t),s._zod.processJSONSchema=(n,r,a)=>qEs(s,n,r)});function KTs(s){return vEs(WTs,s)}const YTs=Ma("ZodArray",(s,t)=>{vtt(),fAs.init(s,t),Ix.init(s,t),s._zod.processJSONSchema=(n,r,a)=>YEs(s,n,r,a),s.element=t.element},{min(s,t){return this.check(EEe(s,t))},nonempty(s){return this.check(EEe(1,s))},max(s,t){return this.check(G8t(s,t))},length(s,t){return this.check(W8t(s,t))},unwrap(){return this.element}});function ZTs(s,t){return MEs(YTs,s,t)}const XTs=Ma("ZodObject",(s,t)=>{vtt(),xAs.init(s,t),Ix.init(s,t),s._zod.processJSONSchema=(n,r,a)=>ZEs(s,n,r,a),x4s(s,"shape",n=>n._zod.def.shape,!1)},{keyof(){return btt(Object.keys(this._zod.def.shape))},catchall(s){return this.clone(Zj(this._zod.def,{catchall:s}))},passthrough(){return this.clone(Zj(this._zod.def,{catchall:wyt()}))},loose(){return this.clone(Zj(this._zod.def,{catchall:wyt()}))},strict(){return this.clone(Zj(this._zod.def,{catchall:KTs()}))},strip(){return this.clone(Zj(this._zod.def,{catchall:void 0}))},extend(s){return i4s(this,s)},safeExtend(s){return o4s(this,s)},merge(s){return l4s(this,s)},pick(s){return r4s(this,s)},omit(s){return a4s(this,s)},partial(...s){return Gxt(lzt,this,s[0])},exactPartial(...s){return Gxt(czt,this,s[0],"exactPartial")},required(...s){return c4s(dzt,this,s[0])}});function H2(s,t){const n={type:"object",shape:s??{},...Pl(t)};return new XTs(n)}const QTs=Ma("ZodUnion",(s,t)=>{yAs.init(s,t),Ix.init(s,t),s._zod.processJSONSchema=(n,r,a)=>XEs(s,n,r,a),s.options=t.options});function JTs(s,t){return new QTs({type:"union",options:s,...Pl(t)})}const eMs=Ma("ZodIntersection",(s,t)=>{vAs.init(s,t),Ix.init(s,t),s._zod.processJSONSchema=(n,r,a)=>QEs(s,n,r,a)});function tMs(s,t){return new eMs({type:"intersection",left:s,right:t})}const KHe=Ma("ZodEnum",(s,t)=>{bAs.init(s,t),Ix.init(s,t),s._zod.processJSONSchema=(r,a,i)=>HEs(s,r,a),s.enum=t.entries,s.options=[...s._zod.values];const n=new Set(Object.keys(t.entries));s.extract=(r,a)=>{const i={};for(const l of r)if(n.has(l))i[l]=t.entries[l];else throw new Error(`Key ${l} not found in enum`);return new KHe({...t,checks:[],...Pl(a),entries:i})},s.exclude=(r,a)=>{const i={...t.entries};for(const l of r)if(n.has(l))delete i[l];else throw new Error(`Key ${l} not found in enum`);return new KHe({...t,checks:[],...Pl(a),entries:i})}});function btt(s,t){const n=Array.isArray(s)?Object.fromEntries(s.map(r=>[r,r])):s;return new KHe({type:"enum",entries:n,...Pl(t)})}const sMs=Ma("ZodLiteral",(s,t)=>{_As.init(s,t),Ix.init(s,t),s._zod.processJSONSchema=(n,r,a)=>GEs(s,n,r,a),s.values=new Set(t.values),Object.defineProperty(s,"value",{get(){if(t.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function yx(s,t){return new sMs({type:"literal",values:Array.isArray(s)?s:[s],...Pl(t)})}const nMs=Ma("ZodTransform",(s,t)=>{vtt(),wAs.init(s,t),Ix.init(s,t),s._zod.processJSONSchema=(n,r,a)=>KEs(s,n,r,a),s._zod.parse=(n,r)=>{if(r.direction==="backward")throw new C8t(s.constructor.name);n.addIssue=i=>{if(typeof i=="string")n.issues.push(sse(i,n.value,t));else{const l=i;l.fatal&&(l.continue=!1),l.code??(l.code="custom"),"input"in l||(l.input=n.value),l.inst??(l.inst=s),n.issues.push(sse(l))}};const a=t.transform(n.value,n);return a instanceof Promise?a.then(i=>(n.value=i,n)):(n.value=a,n)}});function rMs(s){return new nMs({type:"transform",transform:s})}const lzt=Ma("ZodOptional",(s,t)=>{U8t.init(s,t),Ix.init(s,t),s._zod.processJSONSchema=(n,r,a)=>rzt(s,n,r,a),s.unwrap=()=>s._zod.def.innerType});function jyt(s){return new lzt({type:"optional",innerType:s})}const czt=Ma("ZodExactOptional",(s,t)=>{jAs.init(s,t),Ix.init(s,t),s._zod.processJSONSchema=(n,r,a)=>rzt(s,n,r,a),s.unwrap=()=>s._zod.def.innerType});function aMs(s){return new czt({type:"optional",innerType:s})}const iMs=Ma("ZodNullable",(s,t)=>{NAs.init(s,t),Ix.init(s,t),s._zod.processJSONSchema=(n,r,a)=>JEs(s,n,r,a),s.unwrap=()=>s._zod.def.innerType});function Nyt(s){return new iMs({type:"nullable",innerType:s})}const oMs=Ma("ZodDefault",(s,t)=>{kAs.init(s,t),Ix.init(s,t),s._zod.processJSONSchema=(n,r,a)=>tTs(s,n,r,a),s.unwrap=()=>s._zod.def.innerType,s.removeDefault=s.unwrap});function lMs(s,t){return new oMs({type:"default",innerType:s,get defaultValue(){return typeof t=="function"?t():b8t(t)}})}const cMs=Ma("ZodPrefault",(s,t)=>{SAs.init(s,t),Ix.init(s,t),s._zod.processJSONSchema=(n,r,a)=>sTs(s,n,r,a),s.unwrap=()=>s._zod.def.innerType});function dMs(s,t){return new cMs({type:"prefault",innerType:s,get defaultValue(){return typeof t=="function"?t():b8t(t)}})}const dzt=Ma("ZodNonOptional",(s,t)=>{CAs.init(s,t),Ix.init(s,t),s._zod.processJSONSchema=(n,r,a)=>eTs(s,n,r,a),s.unwrap=()=>s._zod.def.innerType});function uMs(s,t){return new dzt({type:"nonoptional",innerType:s,...Pl(t)})}const hMs=Ma("ZodCatch",(s,t)=>{AAs.init(s,t),Ix.init(s,t),s._zod.processJSONSchema=(n,r,a)=>nTs(s,n,r,a),s.unwrap=()=>s._zod.def.innerType,s.removeCatch=s.unwrap});function mMs(s,t){return new hMs({type:"catch",innerType:s,catchValue:typeof t=="function"?t:v4s(t)})}const fMs=Ma("ZodPipe",(s,t)=>{EAs.init(s,t),Ix.init(s,t),s._zod.processJSONSchema=(n,r,a)=>rTs(s,n,r,a),s.in=t.in,s.out=t.out});function kyt(s,t){return new fMs({type:"pipe",in:s,out:t})}const pMs=Ma("ZodReadonly",(s,t)=>{TAs.init(s,t),Ix.init(s,t),s._zod.processJSONSchema=(n,r,a)=>aTs(s,n,r,a),s.unwrap=()=>s._zod.def.innerType});function gMs(s){return new pMs({type:"readonly",innerType:s})}const xMs=Ma("ZodCustom",(s,t)=>{MAs.init(s,t),Ix.init(s,t),s._zod.processJSONSchema=(n,r,a)=>WEs(s,n,r,a)});function yMs(s,t={}){return PEs(xMs,s,t)}function vMs(s,t){return IEs(s,t)}var bMs=Object.defineProperty,_Ms=(s,t)=>bMs(s,"name",{value:t,configurable:!0}),wMs=j.forwardRef(_Ms(function(t,n){return e.jsx(Ei.label,{...t,ref:n,onMouseDown:r=>{var i;r.target.closest("button, input, select, textarea")||((i=t.onMouseDown)==null||i.call(t,r),!r.defaultPrevented&&r.detail>1&&r.preventDefault())}})},"Label")),uzt=wMs;const jMs=DB("text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"),ee=j.forwardRef(({className:s,...t},n)=>e.jsx(uzt,{ref:n,className:Pt(jMs(),s),...t}));ee.displayName=uzt.displayName;const ELe=T5s,hzt=j.createContext({}),jg=({...s})=>e.jsx(hzt.Provider,{value:{name:s.name},children:e.jsx(S5s,{...s})}),TLe=()=>{const s=j.useContext(hzt),t=j.useContext(mzt),{getFieldState:n,formState:r}=E5s(),a=n(s.name,r);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}},mzt=j.createContext({}),Up=j.forwardRef(({className:s,...t},n)=>{const r=j.useId();return e.jsx(mzt.Provider,{value:{id:r},children:e.jsx("div",{ref:n,className:Pt("space-y-2",s),...t})})});Up.displayName="FormItem";const qp=j.forwardRef(({className:s,...t},n)=>{const{error:r,formItemId:a}=TLe();return e.jsx(ee,{ref:n,className:Pt(r&&"text-destructive",s),htmlFor:a,...t})});qp.displayName="FormLabel";const Vp=j.forwardRef(({...s},t)=>{const{error:n,formItemId:r,formDescriptionId:a,formMessageId:i}=TLe();return e.jsx(set,{ref:t,id:r,"aria-describedby":n?`${a} ${i}`:`${a}`,"aria-invalid":!!n,...s})});Vp.displayName="FormControl";const X4e=j.forwardRef(({className:s,...t},n)=>{const{formDescriptionId:r}=TLe();return e.jsx("p",{ref:n,id:r,className:Pt("text-sm text-muted-foreground",s),...t})});X4e.displayName="FormDescription";const y_=j.forwardRef(({className:s,children:t,...n},r)=>{const{error:a,formMessageId:i}=TLe(),l=a?String(a==null?void 0:a.message):t;return l?e.jsx("p",{ref:r,id:i,className:Pt("text-sm font-medium text-destructive",s),...n,children:l}):null});y_.displayName="FormMessage";const pe=j.forwardRef(({className:s,type:t,...n},r)=>e.jsx("input",{type:t,className:Pt("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:r,...n}));pe.displayName="Input";var NMs=Object.defineProperty,kMs=(s,t)=>NMs(s,"name",{value:t,configurable:!0});function _tt(s){const t=j.useRef({value:s,previous:s});return j.useMemo(()=>(t.current.value!==s&&(t.current.previous=t.current.value,t.current.value=s),t.current.previous),[s])}kMs(_tt,"usePrevious");var SMs=Object.defineProperty,Fu=(s,t)=>SMs(s,"name",{value:t,configurable:!0}),CMs=[" ","Enter","ArrowUp","ArrowDown"],AMs=[" ","Enter"],CG="Select",[MLe,PLe,EMs]=LB(CG),[qB,eSr]=tp(CG,[EMs,i3]),wtt=i3(),[TMs,o6]=qB(CG),[MMs,PMs]=qB(CG);function fzt(s){const{__scopeSelect:t,children:n,open:r,defaultOpen:a,onOpenChange:i,value:l,defaultValue:o,onValueChange:c,dir:d,name:u,autoComplete:h,disabled:m,required:f,form:g,internal_do_not_use_render:x}=s,y=wtt(t),[v,b]=j.useState(null),[w,S]=j.useState(null),[C,E]=j.useState(!1),I=l3(d),[P,R]=fy({prop:r,defaultProp:a??!1,onChange:i,caller:CG}),[D,O]=fy({prop:l,defaultProp:o,onChange:c,caller:CG}),U=j.useRef(null),W=j.useRef(D);j.useEffect(()=>{const J=g?v==null?void 0:v.ownerDocument.getElementById(g):v==null?void 0:v.form;if(J instanceof HTMLFormElement){const ce=Fu(()=>O(W.current),"reset");return J.addEventListener("reset",ce),()=>J.removeEventListener("reset",ce)}},[g,v,O]);const V=v?!!g||!!v.closest("form"):!0,[G,Y]=j.useState(new Set),X=my(),ae=Array.from(G).map(J=>J.props.value).join(";"),ie=j.useCallback(J=>{Y(ce=>new Set(ce).add(J))},[]),ne=j.useCallback(J=>{Y(ce=>{const _e=new Set(ce);return _e.delete(J),_e})},[]),te={required:f,trigger:v,onTriggerChange:b,valueNode:w,onValueNodeChange:S,valueNodeHasChildren:C,onValueNodeHasChildrenChange:E,contentId:X,value:D,onValueChange:O,open:P,onOpenChange:R,dir:I,triggerPointerDownPosRef:U,disabled:m,name:u,autoComplete:h,form:g,nativeOptions:G,nativeSelectKey:ae,isFormControl:V};return e.jsx(Cae,{...y,children:e.jsx(TMs,{scope:t,...te,children:e.jsx(MLe.Provider,{scope:t,children:e.jsx(MMs,{scope:t,onNativeOptionAdd:ie,onNativeOptionRemove:ne,children:kzt(x)?x(te):n})})})})}Fu(fzt,"SelectProvider");var IMs=Fu(s=>{const{__scopeSelect:t,children:n,...r}=s;return e.jsx(fzt,{__scopeSelect:t,...r,internal_do_not_use_render:({isFormControl:a})=>e.jsxs(e.Fragment,{children:[n,a?e.jsx(rPs,{__scopeSelect:t}):null]})})},"Select"),LMs="SelectTrigger",pzt=j.forwardRef(Fu(function(t,n){const{__scopeSelect:r,disabled:a=!1,...i}=t,l=wtt(r),o=o6(LMs,r),c=o.disabled||a,d=Vo(n,o.onTriggerChange),u=PLe(r),h=j.useRef("touch"),[m,f,g]=Ntt(y=>{const v=u().filter(S=>!S.disabled),b=v.find(S=>S.value===o.value),w=ktt(v,y,b);w!==void 0&&o.onValueChange(w.value)}),x=Fu(y=>{c||(o.onOpenChange(!0),g()),y&&(o.triggerPointerDownPosRef.current={x:Math.round(y.pageX),y:Math.round(y.pageY)})},"handleOpen");return e.jsx(Aae,{asChild:!0,...l,children:e.jsx(Ei.button,{type:"button",role:"combobox","aria-controls":o.open?o.contentId:void 0,"aria-expanded":o.open,"aria-required":o.required,"aria-autocomplete":"none",dir:o.dir,"data-state":o.open?"open":"closed",disabled:c,"data-disabled":c?"":void 0,"data-placeholder":Uae(o.value)?"":void 0,...i,ref:d,onClick:Ra(i.onClick,y=>{y.currentTarget.focus(),h.current!=="mouse"&&x(y)}),onPointerDown:Ra(i.onPointerDown,y=>{h.current=y.pointerType;const v=y.target;v.hasPointerCapture(y.pointerId)&&v.releasePointerCapture(y.pointerId),y.button===0&&y.ctrlKey===!1&&y.pointerType==="mouse"&&(x(y),y.preventDefault())}),onKeyDown:Ra(i.onKeyDown,y=>{const v=m.current!=="";!(y.ctrlKey||y.altKey||y.metaKey)&&y.key.length===1&&f(y.key),!(v&&y.key===" ")&&CMs.includes(y.key)&&(x(),y.preventDefault())})})})},"SelectTrigger")),RMs="SelectValue",DMs=j.forwardRef(Fu(function(t,n){const{__scopeSelect:r,className:a,style:i,children:l,placeholder:o="",...c}=t,d=o6(RMs,r),{onValueNodeHasChildrenChange:u}=d,h=l!==void 0,m=Vo(n,d.onValueNodeChange);Ef(()=>{u(h)},[u,h]);const f=Uae(d.value);return e.jsx(Ei.span,{...c,asChild:f?!1:c.asChild,ref:m,style:{pointerEvents:"none"},children:e.jsx(j.Fragment,{children:f?o:l},f?"placeholder":"value")})},"SelectValue")),FMs=j.forwardRef(Fu(function(t,n){const{__scopeSelect:r,children:a,...i}=t;return e.jsx(Ei.span,{"aria-hidden":!0,...i,ref:n,children:a||"▼"})},"SelectIcon")),OMs="SelectPortal",[zMs,BMs]=qB(OMs,{forceMount:void 0}),$Ms=Fu(s=>{const{__scopeSelect:t,forceMount:n,...r}=s;return e.jsx(zMs,{scope:s.__scopeSelect,forceMount:n,children:e.jsx(_ae,{asChild:!0,...r})})},"SelectPortal"),W7="SelectContent",gzt=j.forwardRef(Fu(function(t,n){const r=BMs(W7,t.__scopeSelect),{forceMount:a=r.forceMount,...i}=t,l=o6(W7,t.__scopeSelect),[o,c]=j.useState();return Ef(()=>{c(new DocumentFragment)},[]),e.jsx(xy,{present:a||l.open,children:({present:d})=>d?e.jsx(VMs,{...i,ref:n}):e.jsx(UMs,{...i,fragment:o})})},"SelectContent")),UMs=j.forwardRef(Fu(function(t,n){const{__scopeSelect:r,children:a,fragment:i}=t;return i?wv.createPortal(e.jsx(xzt,{scope:r,children:e.jsx(MLe.Slot,{scope:r,children:e.jsx("div",{ref:n,children:a})})}),i):null},"SelectContentFragment")),uS=10,[xzt,VB]=qB(W7),qMs=pC("SelectContent.RemoveScroll"),VMs=j.forwardRef(Fu(function(t,n){const{__scopeSelect:r}=t,{position:a="item-aligned",onCloseAutoFocus:i,onEscapeKeyDown:l,onPointerDownOutside:o,side:c,sideOffset:d,align:u,alignOffset:h,arrowPadding:m,collisionBoundary:f,collisionPadding:g,sticky:x,hideWhenDetached:y,avoidCollisions:v,...b}=t,w=o6(W7,r),[S,C]=j.useState(null),[E,I]=j.useState(null),P=Vo(n,C),[R,D]=j.useState(null),[O,U]=j.useState(null),W=PLe(r),[V,G]=j.useState(!1),Y=j.useRef(!1);j.useEffect(()=>{if(S)return KIe(S)},[S]),GW();const X=j.useCallback(Ee=>{const[Se,...Le]=W().map(Ve=>Ve.ref.current),[Fe]=Le.slice(-1),ke=document.activeElement;for(const Ve of Ee)if(Ve===ke||(Ve==null||Ve.scrollIntoView({block:"nearest"}),Ve===Se&&E&&(E.scrollTop=0),Ve===Fe&&E&&(E.scrollTop=E.scrollHeight),Ve==null||Ve.focus(),document.activeElement!==ke))return},[W,E]),ae=j.useCallback(()=>X([R,S]),[X,R,S]);j.useEffect(()=>{V&&ae()},[V,ae]);const{onOpenChange:ie,triggerPointerDownPosRef:ne}=w;j.useEffect(()=>{if(S){let Ee={x:0,y:0};const Se=Fu(Fe=>{var ke,Ve;Ee={x:Math.abs(Math.round(Fe.pageX)-(((ke=ne.current)==null?void 0:ke.x)??0)),y:Math.abs(Math.round(Fe.pageY)-(((Ve=ne.current)==null?void 0:Ve.y)??0))}},"handlePointerMove"),Le=Fu(Fe=>{Ee.x<=10&&Ee.y<=10?Fe.preventDefault():Fe.composedPath().includes(S)||ie(!1),document.removeEventListener("pointermove",Se),ne.current=null},"handlePointerUp");return ne.current!==null&&(document.addEventListener("pointermove",Se),document.addEventListener("pointerup",Le,{capture:!0,once:!0})),()=>{document.removeEventListener("pointermove",Se),document.removeEventListener("pointerup",Le,{capture:!0})}}},[S,ie,ne]),j.useEffect(()=>{const Ee=Fu(()=>ie(!1),"close");return window.addEventListener("blur",Ee),window.addEventListener("resize",Ee),()=>{window.removeEventListener("blur",Ee),window.removeEventListener("resize",Ee)}},[ie]);const[te,J]=Ntt(Ee=>{const Se=W().filter(ke=>!ke.disabled),Le=Se.find(ke=>ke.ref.current===document.activeElement),Fe=ktt(Se,Ee,Le);Fe&&setTimeout(()=>{var ke;return(ke=Fe.ref.current)==null?void 0:ke.focus()})}),ce=j.useCallback((Ee,Se,Le)=>{const Fe=!Y.current&&!Le;(w.value!==void 0&&w.value===Se||Fe)&&(D(Ee),Fe&&(Y.current=!0))},[w.value]),_e=j.useCallback(()=>S==null?void 0:S.focus(),[S]),he=j.useCallback((Ee,Se,Le)=>{const Fe=!Y.current&&!Le;(w.value!==void 0&&w.value===Se||Fe)&&U(Ee)},[w.value]),ue=a==="popper"?Syt:HMs,ve=ue===Syt?{side:c,sideOffset:d,align:u,alignOffset:h,arrowPadding:m,collisionBoundary:f,collisionPadding:g,sticky:x,hideWhenDetached:y,avoidCollisions:v}:{};return e.jsx(xzt,{scope:r,content:S,viewport:E,onViewportChange:I,itemRefCallback:ce,selectedItem:R,onItemLeave:_e,itemTextRefCallback:he,focusSelectedItem:ae,selectedItemText:O,position:a,isPositioned:V,searchRef:te,children:e.jsx(jae,{as:qMs,allowPinchZoom:!0,children:e.jsx(GIe,{asChild:!0,trapped:w.open,onMountAutoFocus:Ee=>{Ee.preventDefault()},onUnmountAutoFocus:Ra(i,Ee=>{var Se;(Se=w.trigger)==null||Se.focus({preventScroll:!0}),Ee.preventDefault()}),children:e.jsx(RB,{asChild:!0,disableOutsidePointerEvents:!0,onEscapeKeyDown:l,onPointerDownOutside:o,onFocusOutside:Ee=>Ee.preventDefault(),onDismiss:()=>w.onOpenChange(!1),children:e.jsx(ue,{role:"listbox",id:w.contentId,"data-state":w.open?"open":"closed",dir:w.dir,onContextMenu:Ee=>Ee.preventDefault(),...b,...ve,onPlaced:()=>G(!0),ref:P,style:{display:"flex",flexDirection:"column",outline:"none",...b.style},onKeyDown:Ra(b.onKeyDown,Ee=>{const Se=Ee.ctrlKey||Ee.altKey||Ee.metaKey;if(Ee.key==="Tab"&&Ee.preventDefault(),!Se&&Ee.key.length===1&&J(Ee.key),["ArrowUp","ArrowDown","Home","End"].includes(Ee.key)){let Fe=W().filter(ke=>!ke.disabled).map(ke=>ke.ref.current);if(["ArrowUp","End"].includes(Ee.key)&&(Fe=Fe.slice().reverse()),["ArrowUp","ArrowDown"].includes(Ee.key)){const ke=Ee.target,Ve=Fe.indexOf(ke);Fe=Fe.slice(Ve+1)}setTimeout(()=>X(Fe)),Ee.preventDefault()}})})})})})})},"SelectContentImpl")),HMs=j.forwardRef(Fu(function(t,n){const{__scopeSelect:r,onPlaced:a,...i}=t,l=o6(W7,r),o=VB(W7,r),[c,d]=j.useState(null),[u,h]=j.useState(null),m=Vo(n,h),f=PLe(r),g=j.useRef(!1),x=j.useRef(!0),{viewport:y,selectedItem:v,selectedItemText:b,focusSelectedItem:w}=o,S=j.useCallback(()=>{if(l.trigger&&l.valueNode&&c&&u&&y&&v&&b){const P=l.trigger.getBoundingClientRect(),R=u.getBoundingClientRect(),D=l.valueNode.getBoundingClientRect(),O=b.getBoundingClientRect();if(l.dir!=="rtl"){const ke=O.left-R.left,Ve=D.left-ke,je=P.left-Ve,Ae=P.width+je,Ce=Math.max(Ae,R.width),qe=window.innerWidth-uS,ze=wG(Ve,[uS,Math.max(uS,qe-Ce)]);c.style.minWidth=Ae+"px",c.style.left=ze+"px"}else{const ke=R.right-O.right,Ve=window.innerWidth-D.right-ke,je=window.innerWidth-P.right-Ve,Ae=P.width+je,Ce=Math.max(Ae,R.width),qe=window.innerWidth-uS,ze=wG(Ve,[uS,Math.max(uS,qe-Ce)]);c.style.minWidth=Ae+"px",c.style.right=ze+"px"}const U=f(),W=window.innerHeight-uS*2,V=y.scrollHeight,G=window.getComputedStyle(u),Y=parseInt(G.borderTopWidth,10),X=parseInt(G.paddingTop,10),ae=parseInt(G.borderBottomWidth,10),ie=parseInt(G.paddingBottom,10),ne=Y+X+V+ie+ae,te=Math.min(v.offsetHeight*5,ne),J=window.getComputedStyle(y),ce=parseInt(J.paddingTop,10),_e=parseInt(J.paddingBottom,10),he=P.top+P.height/2-uS,ue=W-he,ve=v.offsetHeight/2,Ee=v.offsetTop+ve,Se=Y+X+Ee,Le=ne-Se;if(Se<=he){const ke=U.length>0&&v===U[U.length-1].ref.current;c.style.bottom="0px";const Ve=u.clientHeight-y.offsetTop-y.offsetHeight,je=Math.max(ue,ve+(ke?_e:0)+Ve+ae),Ae=Se+je;c.style.height=Ae+"px"}else{const ke=U.length>0&&v===U[0].ref.current;c.style.top="0px";const je=Math.max(he,Y+y.offsetTop+(ke?ce:0)+ve)+Le;c.style.height=je+"px",y.scrollTop=Se-he+y.offsetTop}c.style.margin=`${uS}px 0`,c.style.minHeight=te+"px",c.style.maxHeight=W+"px",a==null||a(),requestAnimationFrame(()=>g.current=!0)}},[f,l.trigger,l.valueNode,c,u,y,v,b,l.dir,a]);Ef(()=>S(),[S]);const[C,E]=j.useState();Ef(()=>{u&&E(window.getComputedStyle(u).zIndex)},[u]);const I=j.useCallback(P=>{P&&x.current===!0&&(S(),w==null||w(),x.current=!1)},[S,w]);return e.jsx(GMs,{scope:r,contentWrapper:c,shouldExpandOnScrollRef:g,onScrollButtonChange:I,children:e.jsx("div",{ref:d,style:{display:"flex",flexDirection:"column",position:"fixed",zIndex:C},children:e.jsx(Ei.div,{...i,ref:m,style:{boxSizing:"border-box",maxHeight:"100%",...i.style}})})})},"SelectItemAlignedPosition")),Syt=j.forwardRef(Fu(function(t,n){const{__scopeSelect:r,align:a="start",collisionPadding:i=uS,...l}=t,o=wtt(r);return e.jsx(Eae,{...o,...l,ref:n,align:a,collisionPadding:i,style:{boxSizing:"border-box",...l.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)"}})},"SelectPopperPosition")),[GMs,jtt]=qB(W7,{}),Cyt="SelectViewport",WMs=j.forwardRef(Fu(function(t,n){const{__scopeSelect:r,nonce:a,...i}=t,l=VB(Cyt,r),o=jtt(Cyt,r),c=Vo(n,l.onViewportChange),d=j.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:a}),e.jsx(MLe.Slot,{scope:r,children:e.jsx(Ei.div,{"data-radix-select-viewport":"",role:"presentation",...i,ref:c,style:{position:"relative",flex:1,overflow:"hidden auto",...i.style},onScroll:Ra(i.onScroll,u=>{const h=u.currentTarget,{contentWrapper:m,shouldExpandOnScrollRef:f}=o;if(f!=null&&f.current&&m){const g=Math.abs(d.current-h.scrollTop);if(g>0){const x=window.innerHeight-uS*2,y=parseFloat(m.style.minHeight),v=parseFloat(m.style.height),b=Math.max(y,v);if(b0?C:0,m.style.justifyContent="flex-end")}}}d.current=h.scrollTop})})})]})},"SelectViewport")),KMs="SelectGroup",[YMs,ZMs]=qB(KMs),XMs=j.forwardRef(Fu(function(t,n){const{__scopeSelect:r,...a}=t,i=my();return e.jsx(YMs,{scope:r,id:i,children:e.jsx(Ei.div,{role:"group","aria-labelledby":i,...a,ref:n})})},"SelectGroup")),QMs="SelectLabel",yzt=j.forwardRef(Fu(function(t,n){const{__scopeSelect:r,...a}=t,i=ZMs(QMs,r);return e.jsx(Ei.div,{id:i.id,...a,ref:n})},"SelectLabel")),YHe="SelectItem",[JMs,vzt]=qB(YHe),bzt=j.forwardRef(Fu(function(t,n){const{__scopeSelect:r,value:a,disabled:i=!1,textValue:l,...o}=t,c=o6(YHe,r),d=VB(YHe,r),u=c.value===a,[h,m]=j.useState(l??""),[f,g]=j.useState(!1),x=Yp(S=>{var C;return(C=d.itemRefCallback)==null?void 0:C.call(d,S,a,i)}),y=Vo(n,x),v=my(),b=j.useRef("touch"),w=Fu(()=>{i||(c.onValueChange(a),c.onOpenChange(!1))},"handleSelect");return e.jsx(JMs,{scope:r,value:a,disabled:i,textId:v,isSelected:u,onItemTextChange:j.useCallback(S=>{m(C=>C||((S==null?void 0:S.textContent)??"").trim())},[]),children:e.jsx(MLe.ItemSlot,{scope:r,value:a,disabled:i,textValue:h,children:e.jsx(Ei.div,{role:"option","aria-labelledby":v,"data-highlighted":f?"":void 0,"aria-selected":u&&f,"data-state":u?"checked":"unchecked","aria-disabled":i||void 0,"data-disabled":i?"":void 0,tabIndex:i?void 0:-1,...o,ref:y,onFocus:Ra(o.onFocus,()=>g(!0)),onBlur:Ra(o.onBlur,()=>g(!1)),onClick:Ra(o.onClick,()=>{b.current!=="mouse"&&w()}),onPointerUp:Ra(o.onPointerUp,()=>{b.current==="mouse"&&w()}),onPointerDown:Ra(o.onPointerDown,S=>{b.current=S.pointerType}),onPointerMove:Ra(o.onPointerMove,S=>{var C;b.current=S.pointerType,i?(C=d.onItemLeave)==null||C.call(d):b.current==="mouse"&&S.currentTarget.focus({preventScroll:!0})}),onPointerLeave:Ra(o.onPointerLeave,S=>{var C;S.currentTarget===document.activeElement&&((C=d.onItemLeave)==null||C.call(d))}),onKeyDown:Ra(o.onKeyDown,S=>{var E;i||S.target!==S.currentTarget||((E=d.searchRef)==null?void 0:E.current)!==""&&S.key===" "||(AMs.includes(S.key)&&w(),S.key===" "&&S.preventDefault())})})})})},"SelectItem")),Dce="SelectItemText",ePs=j.forwardRef(Fu(function(t,n){const{__scopeSelect:r,className:a,style:i,...l}=t,o=o6(Dce,r),c=VB(Dce,r),d=vzt(Dce,r),u=PMs(Dce,r),[h,m]=j.useState(null),f=Yp(w=>{var S;return(S=c.itemTextRefCallback)==null?void 0:S.call(c,w,d.value,d.disabled)}),g=Vo(n,m,d.onItemTextChange,f),x=h==null?void 0:h.textContent,y=j.useMemo(()=>e.jsx("option",{value:d.value,disabled:d.disabled,children:x},d.value),[d.disabled,d.value,x]),{onNativeOptionAdd:v,onNativeOptionRemove:b}=u;return Ef(()=>(v(y),()=>b(y)),[v,b,y]),e.jsxs(e.Fragment,{children:[e.jsx(Ei.span,{id:d.textId,...l,ref:g}),d.isSelected&&o.valueNode&&!o.valueNodeHasChildren&&!Uae(o.value)?wv.createPortal(l.children,o.valueNode):null]})},"SelectItemText")),tPs="SelectItemIndicator",sPs=j.forwardRef(Fu(function(t,n){const{__scopeSelect:r,...a}=t;return vzt(tPs,r).isSelected?e.jsx(Ei.span,{"aria-hidden":!0,...a,ref:n}):null},"SelectItemIndicator")),Ayt="SelectScrollUpButton",_zt=j.forwardRef(Fu(function(t,n){const r=VB(Ayt,t.__scopeSelect),a=jtt(Ayt,t.__scopeSelect),[i,l]=j.useState(!1),o=Vo(n,a.onScrollButtonChange);return Ef(()=>{if(r.viewport&&r.isPositioned){let c=function(){const u=d.scrollTop>0;l(u)};Fu(c,"handleScroll");const d=r.viewport;return c(),d.addEventListener("scroll",c),()=>d.removeEventListener("scroll",c)}},[r.viewport,r.isPositioned]),i?e.jsx(jzt,{...t,ref:o,onAutoScroll:()=>{const{viewport:c,selectedItem:d}=r;c&&d&&(c.scrollTop=c.scrollTop-d.offsetHeight)}}):null},"SelectScrollUpButton")),Eyt="SelectScrollDownButton",wzt=j.forwardRef(Fu(function(t,n){const r=VB(Eyt,t.__scopeSelect),a=jtt(Eyt,t.__scopeSelect),[i,l]=j.useState(!1),o=Vo(n,a.onScrollButtonChange);return Ef(()=>{if(r.viewport&&r.isPositioned){let c=function(){const u=d.scrollHeight-d.clientHeight,h=Math.ceil(d.scrollTop)d.removeEventListener("scroll",c)}},[r.viewport,r.isPositioned]),i?e.jsx(jzt,{...t,ref:o,onAutoScroll:()=>{const{viewport:c,selectedItem:d}=r;c&&d&&(c.scrollTop=c.scrollTop+d.offsetHeight)}}):null},"SelectScrollDownButton")),jzt=j.forwardRef(Fu(function(t,n){const{__scopeSelect:r,onAutoScroll:a,...i}=t,l=VB("SelectScrollButton",r),o=j.useRef(null),c=PLe(r),d=j.useCallback(()=>{o.current!==null&&(window.clearInterval(o.current),o.current=null)},[]);return j.useEffect(()=>()=>d(),[d]),Ef(()=>{var h;const u=c().find(m=>m.ref.current===document.activeElement);(h=u==null?void 0:u.ref.current)==null||h.scrollIntoView({block:"nearest"})},[c]),e.jsx(Ei.div,{"aria-hidden":!0,...i,ref:n,style:{flexShrink:0,...i.style},onPointerDown:Ra(i.onPointerDown,()=>{o.current===null&&(o.current=window.setInterval(a,50))}),onPointerMove:Ra(i.onPointerMove,()=>{var u;(u=l.onItemLeave)==null||u.call(l),o.current===null&&(o.current=window.setInterval(a,50))}),onPointerLeave:Ra(i.onPointerLeave,()=>{d()})})},"SelectScrollButtonImpl")),Nzt=j.forwardRef(Fu(function(t,n){const{__scopeSelect:r,...a}=t;return e.jsx(Ei.div,{"aria-hidden":!0,...a,ref:n})},"SelectSeparator")),nPs="SelectBubbleInput",rPs=j.forwardRef(Fu(function({__scopeSelect:t,...n},r){const a=o6(nPs,t),{value:i,onValueChange:l,required:o,disabled:c,name:d,autoComplete:u,form:h}=a,{nativeOptions:m,nativeSelectKey:f}=a,g=j.useRef(null),x=Vo(r,g),y=i??"",v=_tt(y),b=Array.from(m).some(w=>(w.props.value??"")==="");return j.useEffect(()=>{const w=g.current;if(!w)return;const S=window.HTMLSelectElement.prototype,E=Object.getOwnPropertyDescriptor(S,"value").set;if(v!==y&&E){const I=new Event("change",{bubbles:!0});E.call(w,y),w.dispatchEvent(I)}},[v,y]),e.jsxs(Ei.select,{"aria-hidden":!0,required:o,tabIndex:-1,name:d,autoComplete:u,disabled:c,form:h,onChange:w=>l(w.target.value),...n,style:{...bRt,...n.style},ref:x,defaultValue:y,children:[Uae(i)&&!b?e.jsx("option",{value:""}):null,Array.from(m)]},f)},"SelectBubbleInput"));function kzt(s){return typeof s=="function"}Fu(kzt,"isFunction");function Uae(s){return s===""||s===void 0}Fu(Uae,"shouldShowPlaceholder");function Ntt(s){const t=Yp(s),n=j.useRef(""),r=j.useRef(0),a=j.useCallback(l=>{const o=n.current+l;t(o),Fu(function c(d){n.current=d,window.clearTimeout(r.current),d!==""&&(r.current=window.setTimeout(()=>c(""),1e3))},"updateSearch")(o)},[t]),i=j.useCallback(()=>{n.current="",window.clearTimeout(r.current)},[]);return j.useEffect(()=>()=>window.clearTimeout(r.current),[]),[n,a,i]}Fu(Ntt,"useTypeaheadSearch");function ktt(s,t,n){const a=t.length>1&&Array.from(t).every(d=>d===t[0])?t[0]:t,i=n?s.indexOf(n):-1;let l=Szt(s,Math.max(i,0));a.length===1&&(l=l.filter(d=>d!==n));const c=l.find(d=>d.textValue.toLowerCase().startsWith(a.toLowerCase()));return c!==n?c:void 0}Fu(ktt,"findNextItem");function Szt(s,t){return s.map((n,r)=>s[(t+r)%s.length])}Fu(Szt,"wrapArray");const ms=IMs,aPs=XMs,fs=DMs,us=j.forwardRef(({className:s,children:t,...n},r)=>e.jsxs(pzt,{ref:r,className:Pt("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),...n,children:[t,e.jsx(FMs,{asChild:!0,children:e.jsx(Tl,{className:"h-4 w-4 opacity-50"})})]}));us.displayName=pzt.displayName;const Czt=j.forwardRef(({className:s,...t},n)=>e.jsx(_zt,{ref:n,className:Pt("flex cursor-default items-center justify-center py-1",s),...t,children:e.jsx(v1,{className:"h-4 w-4"})}));Czt.displayName=_zt.displayName;const Azt=j.forwardRef(({className:s,...t},n)=>e.jsx(wzt,{ref:n,className:Pt("flex cursor-default items-center justify-center py-1",s),...t,children:e.jsx(Tl,{className:"h-4 w-4"})}));Azt.displayName=wzt.displayName;const hs=j.forwardRef(({className:s,children:t,position:n="popper",...r},a)=>e.jsx($Ms,{children:e.jsxs(gzt,{ref:a,className:Pt("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",n==="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:n,...r,children:[e.jsx(Czt,{}),e.jsx(WMs,{className:Pt("p-1",n==="popper"&&"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)]"),children:t}),e.jsx(Azt,{})]})}));hs.displayName=gzt.displayName;const Ezt=j.forwardRef(({className:s,...t},n)=>e.jsx(yzt,{ref:n,className:Pt("py-1.5 pl-8 pr-2 text-sm font-semibold",s),...t}));Ezt.displayName=yzt.displayName;const Ge=j.forwardRef(({className:s,children:t,...n},r)=>e.jsxs(bzt,{ref:r,className:Pt("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),...n,children:[e.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:e.jsx(sPs,{children:e.jsx(la,{className:"h-4 w-4"})})}),e.jsx(ePs,{children:t})]}));Ge.displayName=bzt.displayName;const iPs=j.forwardRef(({className:s,...t},n)=>e.jsx(Nzt,{ref:n,className:Pt("-mx-1 my-1 h-px bg-muted",s),...t}));iPs.displayName=Nzt.displayName;const oPs=H2({category:btt(["general","technology","crm","marketing"]),subject:vl().min(5,"Subject must be at least 5 characters").max(200),description:vl().min(20,"Please provide more details (at least 20 characters)").max(2e3)}),lPs={general:"General Support",technology:"Technology Support",crm:"CRM Support",marketing:"Marketing Support"};function ZHe({trigger:s}){const[t,n]=j.useState(!1),[r,a]=j.useState(!1),{user:i}=vs(),l=NLe({resolver:kLe(oPs),defaultValues:{category:"general",subject:"",description:""}}),o=async c=>{if(!i){re.error("You must be logged in to submit a ticket");return}a(!0);try{const{error:d}=await q.from("support_tickets").insert({user_id:i.id,category:c.category,subject:c.subject,description:c.description});if(d)throw d;try{await q.functions.invoke("support-ticket-notify",{body:{category:lPs[c.category],subject:c.subject}})}catch(u){console.log("Notification send attempted:",u)}re.success("Support ticket submitted successfully!"),l.reset(),n(!1)}catch(d){console.error("Error submitting ticket:",d),re.error("Failed to submit ticket. Please try again.")}finally{a(!1)}};return e.jsxs(zs,{open:t,onOpenChange:n,children:[e.jsx(jl,{asChild:!0,children:s||e.jsxs($,{variant:"ghost",size:"icon",className:"relative",children:[e.jsx($J,{className:"h-5 w-5"}),e.jsx("span",{className:"sr-only",children:"Support"})]})}),e.jsxs(Os,{className:"sm:max-w-[500px]",children:[e.jsxs(Us,{children:[e.jsx(Bs,{children:"Need Help?"}),e.jsx(Ir,{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(Da,{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(ELe,{...l,children:e.jsxs("form",{onSubmit:l.handleSubmit(o),className:"space-y-4",children:[e.jsx(jg,{control:l.control,name:"category",render:({field:c})=>e.jsxs(Up,{children:[e.jsx(qp,{children:"Category"}),e.jsxs(ms,{onValueChange:c.onChange,defaultValue:c.value,children:[e.jsx(Vp,{children:e.jsx(us,{children:e.jsx(fs,{placeholder:"Select a category"})})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"general",children:"General Support"}),e.jsx(Ge,{value:"technology",children:"Technology Support"}),e.jsx(Ge,{value:"crm",children:"CRM Support"}),e.jsx(Ge,{value:"marketing",children:"Marketing Support"})]})]}),e.jsx(y_,{})]})}),e.jsx(jg,{control:l.control,name:"subject",render:({field:c})=>e.jsxs(Up,{children:[e.jsx(qp,{children:"Subject"}),e.jsx(Vp,{children:e.jsx(pe,{placeholder:"Brief description of your issue",...c})}),e.jsx(y_,{})]})}),e.jsx(jg,{control:l.control,name:"description",render:({field:c})=>e.jsxs(Up,{children:[e.jsx(qp,{children:"Description"}),e.jsx(Vp,{children:e.jsx(Rs,{placeholder:"Please describe your issue in detail...",className:"min-h-[120px]",...c})}),e.jsx(y_,{})]})}),e.jsxs("div",{className:"flex justify-end gap-2 pt-4",children:[e.jsx($,{type:"button",variant:"outline",onClick:()=>n(!1),children:"Cancel"}),e.jsx($,{type:"submit",disabled:r,children:r?"Submitting...":"Submit Ticket"})]})]})})]})]})}function So(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 Mm(s,t){return s instanceof Date?new s.constructor(t):new Date(t)}function Tm(s,t){const n=So(s);return isNaN(t)?Mm(s,NaN):(t&&n.setDate(n.getDate()+t),n)}function Mv(s,t){const n=So(s);if(isNaN(t))return Mm(s,NaN);if(!t)return n;const r=n.getDate(),a=Mm(s,n.getTime());a.setMonth(n.getMonth()+t+1,0);const i=a.getDate();return r>=i?a:(n.setFullYear(a.getFullYear(),a.getMonth(),r),n)}function Tzt(s,t){const n=+So(s);return Mm(s,n+t)}const Stt=6048e5,cPs=864e5,ILe=6e4,LLe=36e5,dPs=1e3,Fce=43200,Tyt=1440;function Myt(s,t){return Tzt(s,t*LLe)}let uPs={};function l6(){return uPs}function C1(s,t){var o,c,d,u;const n=l6(),r=(t==null?void 0:t.weekStartsOn)??((c=(o=t==null?void 0:t.locale)==null?void 0:o.options)==null?void 0:c.weekStartsOn)??n.weekStartsOn??((u=(d=n.locale)==null?void 0:d.options)==null?void 0:u.weekStartsOn)??0,a=So(s),i=a.getDay(),l=(i=a.getTime()?n+1:t.getTime()>=l.getTime()?n:n-1}function Mg(s){const t=So(s);return t.setHours(0,0,0,0),t}function EL(s){const t=So(s),n=new Date(Date.UTC(t.getFullYear(),t.getMonth(),t.getDate(),t.getHours(),t.getMinutes(),t.getSeconds(),t.getMilliseconds()));return n.setUTCFullYear(t.getFullYear()),+s-+n}function fb(s,t){const n=Mg(s),r=Mg(t),a=+n-EL(n),i=+r-EL(r);return Math.round((a-i)/cPs)}function hPs(s){const t=Mzt(s),n=Mm(s,0);return n.setFullYear(t,0,4),n.setHours(0,0,0,0),fT(n)}function Pyt(s,t){return Tzt(s,t*ILe)}function c8(s,t){const n=t*7;return Tm(s,n)}function mPs(s,t){return Mv(s,t*12)}function fPs(s){let t;return s.forEach(function(n){const r=So(n);(t===void 0||t{const r=So(n);(!t||t>r||isNaN(+r))&&(t=r)}),t||new Date(NaN)}function Q4e(s,t){const n=So(s),r=So(t),a=n.getTime()-r.getTime();return a<0?-1:a>0?1:a}function RLe(s){return Mm(s,Date.now())}function nf(s,t){const n=Mg(s),r=Mg(t);return+n==+r}function Ctt(s){return s instanceof Date||typeof s=="object"&&Object.prototype.toString.call(s)==="[object Date]"}function XHe(s){if(!Ctt(s)&&typeof s!="number")return!1;const t=So(s);return!isNaN(Number(t))}function AG(s,t){const n=So(s),r=So(t),a=n.getFullYear()-r.getFullYear(),i=n.getMonth()-r.getMonth();return a*12+i}function gPs(s,t,n){const r=C1(s,n),a=C1(t,n),i=+r-EL(r),l=+a-EL(a);return Math.round((i-l)/Stt)}function mk(s,t){const n=So(s),r=So(t),a=Iyt(n,r),i=Math.abs(fb(n,r));n.setDate(n.getDate()-a*i);const l=+(Iyt(n,r)===-a),o=a*(i-l);return o===0?0:o}function Iyt(s,t){const n=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 n<0?-1:n>0?1:n}function xPs(s){return t=>{const r=(s?Math[s]:Math.trunc)(t);return r===0?0:r}}function yPs(s,t){return+So(s)-+So(t)}function vPs(s){const t=So(s);return t.setHours(23,59,59,999),t}function yw(s){const t=So(s),n=t.getMonth();return t.setFullYear(t.getFullYear(),n+1,0),t.setHours(23,59,59,999),t}function bPs(s){const t=So(s);return+vPs(t)==+yw(t)}function _Ps(s,t){const n=So(s),r=So(t),a=Q4e(n,r),i=Math.abs(AG(n,r));let l;if(i<1)l=0;else{n.getMonth()===1&&n.getDate()>27&&n.setDate(30),n.setMonth(n.getMonth()-a*i);let o=Q4e(n,r)===-a;bPs(So(s))&&i===1&&Q4e(s,r)===1&&(o=!1),l=a*(i-Number(o))}return l===0?0:l}function wPs(s,t,n){const r=yPs(s,t)/1e3;return xPs(n==null?void 0:n.roundingMethod)(r)}function jPs(s,t){const n=So(s.start),r=So(s.end);let a=+n>+r;const i=a?+n:+r,l=a?r:n;l.setHours(0,0,0,0);let o=1;const c=[];for(;+l<=i;)c.push(So(l)),l.setDate(l.getDate()+o),l.setHours(0,0,0,0);return a?c.reverse():c}function NPs(s){const t=So(s),n=t.getMonth(),r=n-n%3;return t.setMonth(r,1),t.setHours(0,0,0,0),t}function Xm(s){const t=So(s);return t.setDate(1),t.setHours(0,0,0,0),t}function Att(s){const t=So(s),n=Mm(s,0);return n.setFullYear(t.getFullYear(),0,1),n.setHours(0,0,0,0),n}function DLe(s,t){var o,c,d,u;const n=l6(),r=(t==null?void 0:t.weekStartsOn)??((c=(o=t==null?void 0:t.locale)==null?void 0:o.options)==null?void 0:c.weekStartsOn)??n.weekStartsOn??((u=(d=n.locale)==null?void 0:d.options)==null?void 0:u.weekStartsOn)??0,a=So(s),i=a.getDay(),l=(i{let r;const a=kPs[s];return typeof a=="string"?r=a:t===1?r=a.one:r=a.other.replace("{{count}}",t.toString()),n!=null&&n.addSuffix?n.comparison&&n.comparison>0?"in "+r:r+" ago":r};function r7e(s){return(t={})=>{const n=t.width?String(t.width):s.defaultWidth;return s.formats[n]||s.formats[s.defaultWidth]}}const CPs={full:"EEEE, MMMM do, y",long:"MMMM do, y",medium:"MMM d, y",short:"MM/dd/yyyy"},APs={full:"h:mm:ss a zzzz",long:"h:mm:ss a z",medium:"h:mm:ss a",short:"h:mm a"},EPs={full:"{{date}} 'at' {{time}}",long:"{{date}} 'at' {{time}}",medium:"{{date}}, {{time}}",short:"{{date}}, {{time}}"},TPs={date:r7e({formats:CPs,defaultWidth:"full"}),time:r7e({formats:APs,defaultWidth:"full"}),dateTime:r7e({formats:EPs,defaultWidth:"full"})},MPs={lastWeek:"'last' eeee 'at' p",yesterday:"'yesterday at' p",today:"'today at' p",tomorrow:"'tomorrow at' p",nextWeek:"eeee 'at' p",other:"P"},PPs=(s,t,n,r)=>MPs[s];function SZ(s){return(t,n)=>{const r=n!=null&&n.context?String(n.context):"standalone";let a;if(r==="formatting"&&s.formattingValues){const l=s.defaultFormattingWidth||s.defaultWidth,o=n!=null&&n.width?String(n.width):l;a=s.formattingValues[o]||s.formattingValues[l]}else{const l=s.defaultWidth,o=n!=null&&n.width?String(n.width):s.defaultWidth;a=s.values[o]||s.values[l]}const i=s.argumentCallback?s.argumentCallback(t):t;return a[i]}}const IPs={narrow:["B","A"],abbreviated:["BC","AD"],wide:["Before Christ","Anno Domini"]},LPs={narrow:["1","2","3","4"],abbreviated:["Q1","Q2","Q3","Q4"],wide:["1st quarter","2nd quarter","3rd quarter","4th quarter"]},RPs={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"]},DPs={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"]},FPs={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"}},OPs={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"}},zPs=(s,t)=>{const n=Number(s),r=n%100;if(r>20||r<10)switch(r%10){case 1:return n+"st";case 2:return n+"nd";case 3:return n+"rd"}return n+"th"},BPs={ordinalNumber:zPs,era:SZ({values:IPs,defaultWidth:"wide"}),quarter:SZ({values:LPs,defaultWidth:"wide",argumentCallback:s=>s-1}),month:SZ({values:RPs,defaultWidth:"wide"}),day:SZ({values:DPs,defaultWidth:"wide"}),dayPeriod:SZ({values:FPs,defaultWidth:"wide",formattingValues:OPs,defaultFormattingWidth:"wide"})};function CZ(s){return(t,n={})=>{const r=n.width,a=r&&s.matchPatterns[r]||s.matchPatterns[s.defaultMatchWidth],i=t.match(a);if(!i)return null;const l=i[0],o=r&&s.parsePatterns[r]||s.parsePatterns[s.defaultParseWidth],c=Array.isArray(o)?UPs(o,h=>h.test(l)):$Ps(o,h=>h.test(l));let d;d=s.valueCallback?s.valueCallback(c):c,d=n.valueCallback?n.valueCallback(d):d;const u=t.slice(l.length);return{value:d,rest:u}}}function $Ps(s,t){for(const n in s)if(Object.prototype.hasOwnProperty.call(s,n)&&t(s[n]))return n}function UPs(s,t){for(let n=0;n{const r=t.match(s.matchPattern);if(!r)return null;const a=r[0],i=t.match(s.parsePattern);if(!i)return null;let l=s.valueCallback?s.valueCallback(i[0]):i[0];l=n.valueCallback?n.valueCallback(l):l;const o=t.slice(a.length);return{value:l,rest:o}}}const VPs=/^(\d+)(th|st|nd|rd)?/i,HPs=/\d+/i,GPs={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},WPs={any:[/^b/i,/^(a|c)/i]},KPs={narrow:/^[1234]/i,abbreviated:/^q[1234]/i,wide:/^[1234](th|st|nd|rd)? quarter/i},YPs={any:[/1/i,/2/i,/3/i,/4/i]},ZPs={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},XPs={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]},QPs={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},JPs={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]},eIs={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},tIs={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}},sIs={ordinalNumber:qPs({matchPattern:VPs,parsePattern:HPs,valueCallback:s=>parseInt(s,10)}),era:CZ({matchPatterns:GPs,defaultMatchWidth:"wide",parsePatterns:WPs,defaultParseWidth:"any"}),quarter:CZ({matchPatterns:KPs,defaultMatchWidth:"wide",parsePatterns:YPs,defaultParseWidth:"any",valueCallback:s=>s+1}),month:CZ({matchPatterns:ZPs,defaultMatchWidth:"wide",parsePatterns:XPs,defaultParseWidth:"any"}),day:CZ({matchPatterns:QPs,defaultMatchWidth:"wide",parsePatterns:JPs,defaultParseWidth:"any"}),dayPeriod:CZ({matchPatterns:eIs,defaultMatchWidth:"any",parsePatterns:tIs,defaultParseWidth:"any"})},FLe={code:"en-US",formatDistance:SPs,formatLong:TPs,formatRelative:PPs,localize:BPs,match:sIs,options:{weekStartsOn:0,firstWeekContainsDate:1}};function nIs(s){const t=So(s);return fb(t,Att(t))+1}function Ett(s){const t=So(s),n=+fT(t)-+hPs(t);return Math.round(n/Stt)+1}function Ttt(s,t){var u,h,m,f;const n=So(s),r=n.getFullYear(),a=l6(),i=(t==null?void 0:t.firstWeekContainsDate)??((h=(u=t==null?void 0:t.locale)==null?void 0:u.options)==null?void 0:h.firstWeekContainsDate)??a.firstWeekContainsDate??((f=(m=a.locale)==null?void 0:m.options)==null?void 0:f.firstWeekContainsDate)??1,l=Mm(s,0);l.setFullYear(r+1,0,i),l.setHours(0,0,0,0);const o=C1(l,t),c=Mm(s,0);c.setFullYear(r,0,i),c.setHours(0,0,0,0);const d=C1(c,t);return n.getTime()>=o.getTime()?r+1:n.getTime()>=d.getTime()?r:r-1}function rIs(s,t){var o,c,d,u;const n=l6(),r=(t==null?void 0:t.firstWeekContainsDate)??((c=(o=t==null?void 0:t.locale)==null?void 0:o.options)==null?void 0:c.firstWeekContainsDate)??n.firstWeekContainsDate??((u=(d=n.locale)==null?void 0:d.options)==null?void 0:u.firstWeekContainsDate)??1,a=Ttt(s,t),i=Mm(s,0);return i.setFullYear(a,0,r),i.setHours(0,0,0,0),C1(i,t)}function Mtt(s,t){const n=So(s),r=+C1(n,t)-+rIs(n,t);return Math.round(r/Stt)+1}function Am(s,t){const n=s<0?"-":"",r=Math.abs(s).toString().padStart(t,"0");return n+r}const _M={y(s,t){const n=s.getFullYear(),r=n>0?n:1-n;return Am(t==="yy"?r%100:r,t.length)},M(s,t){const n=s.getMonth();return t==="M"?String(n+1):Am(n+1,2)},d(s,t){return Am(s.getDate(),t.length)},a(s,t){const n=s.getHours()/12>=1?"pm":"am";switch(t){case"a":case"aa":return n.toUpperCase();case"aaa":return n;case"aaaaa":return n[0];case"aaaa":default:return n==="am"?"a.m.":"p.m."}},h(s,t){return Am(s.getHours()%12||12,t.length)},H(s,t){return Am(s.getHours(),t.length)},m(s,t){return Am(s.getMinutes(),t.length)},s(s,t){return Am(s.getSeconds(),t.length)},S(s,t){const n=t.length,r=s.getMilliseconds(),a=Math.trunc(r*Math.pow(10,n-3));return Am(a,t.length)}},w$={midnight:"midnight",noon:"noon",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"},Lyt={G:function(s,t,n){const r=s.getFullYear()>0?1:0;switch(t){case"G":case"GG":case"GGG":return n.era(r,{width:"abbreviated"});case"GGGGG":return n.era(r,{width:"narrow"});case"GGGG":default:return n.era(r,{width:"wide"})}},y:function(s,t,n){if(t==="yo"){const r=s.getFullYear(),a=r>0?r:1-r;return n.ordinalNumber(a,{unit:"year"})}return _M.y(s,t)},Y:function(s,t,n,r){const a=Ttt(s,r),i=a>0?a:1-a;if(t==="YY"){const l=i%100;return Am(l,2)}return t==="Yo"?n.ordinalNumber(i,{unit:"year"}):Am(i,t.length)},R:function(s,t){const n=Mzt(s);return Am(n,t.length)},u:function(s,t){const n=s.getFullYear();return Am(n,t.length)},Q:function(s,t,n){const r=Math.ceil((s.getMonth()+1)/3);switch(t){case"Q":return String(r);case"QQ":return Am(r,2);case"Qo":return n.ordinalNumber(r,{unit:"quarter"});case"QQQ":return n.quarter(r,{width:"abbreviated",context:"formatting"});case"QQQQQ":return n.quarter(r,{width:"narrow",context:"formatting"});case"QQQQ":default:return n.quarter(r,{width:"wide",context:"formatting"})}},q:function(s,t,n){const r=Math.ceil((s.getMonth()+1)/3);switch(t){case"q":return String(r);case"qq":return Am(r,2);case"qo":return n.ordinalNumber(r,{unit:"quarter"});case"qqq":return n.quarter(r,{width:"abbreviated",context:"standalone"});case"qqqqq":return n.quarter(r,{width:"narrow",context:"standalone"});case"qqqq":default:return n.quarter(r,{width:"wide",context:"standalone"})}},M:function(s,t,n){const r=s.getMonth();switch(t){case"M":case"MM":return _M.M(s,t);case"Mo":return n.ordinalNumber(r+1,{unit:"month"});case"MMM":return n.month(r,{width:"abbreviated",context:"formatting"});case"MMMMM":return n.month(r,{width:"narrow",context:"formatting"});case"MMMM":default:return n.month(r,{width:"wide",context:"formatting"})}},L:function(s,t,n){const r=s.getMonth();switch(t){case"L":return String(r+1);case"LL":return Am(r+1,2);case"Lo":return n.ordinalNumber(r+1,{unit:"month"});case"LLL":return n.month(r,{width:"abbreviated",context:"standalone"});case"LLLLL":return n.month(r,{width:"narrow",context:"standalone"});case"LLLL":default:return n.month(r,{width:"wide",context:"standalone"})}},w:function(s,t,n,r){const a=Mtt(s,r);return t==="wo"?n.ordinalNumber(a,{unit:"week"}):Am(a,t.length)},I:function(s,t,n){const r=Ett(s);return t==="Io"?n.ordinalNumber(r,{unit:"week"}):Am(r,t.length)},d:function(s,t,n){return t==="do"?n.ordinalNumber(s.getDate(),{unit:"date"}):_M.d(s,t)},D:function(s,t,n){const r=nIs(s);return t==="Do"?n.ordinalNumber(r,{unit:"dayOfYear"}):Am(r,t.length)},E:function(s,t,n){const r=s.getDay();switch(t){case"E":case"EE":case"EEE":return n.day(r,{width:"abbreviated",context:"formatting"});case"EEEEE":return n.day(r,{width:"narrow",context:"formatting"});case"EEEEEE":return n.day(r,{width:"short",context:"formatting"});case"EEEE":default:return n.day(r,{width:"wide",context:"formatting"})}},e:function(s,t,n,r){const a=s.getDay(),i=(a-r.weekStartsOn+8)%7||7;switch(t){case"e":return String(i);case"ee":return Am(i,2);case"eo":return n.ordinalNumber(i,{unit:"day"});case"eee":return n.day(a,{width:"abbreviated",context:"formatting"});case"eeeee":return n.day(a,{width:"narrow",context:"formatting"});case"eeeeee":return n.day(a,{width:"short",context:"formatting"});case"eeee":default:return n.day(a,{width:"wide",context:"formatting"})}},c:function(s,t,n,r){const a=s.getDay(),i=(a-r.weekStartsOn+8)%7||7;switch(t){case"c":return String(i);case"cc":return Am(i,t.length);case"co":return n.ordinalNumber(i,{unit:"day"});case"ccc":return n.day(a,{width:"abbreviated",context:"standalone"});case"ccccc":return n.day(a,{width:"narrow",context:"standalone"});case"cccccc":return n.day(a,{width:"short",context:"standalone"});case"cccc":default:return n.day(a,{width:"wide",context:"standalone"})}},i:function(s,t,n){const r=s.getDay(),a=r===0?7:r;switch(t){case"i":return String(a);case"ii":return Am(a,t.length);case"io":return n.ordinalNumber(a,{unit:"day"});case"iii":return n.day(r,{width:"abbreviated",context:"formatting"});case"iiiii":return n.day(r,{width:"narrow",context:"formatting"});case"iiiiii":return n.day(r,{width:"short",context:"formatting"});case"iiii":default:return n.day(r,{width:"wide",context:"formatting"})}},a:function(s,t,n){const a=s.getHours()/12>=1?"pm":"am";switch(t){case"a":case"aa":return n.dayPeriod(a,{width:"abbreviated",context:"formatting"});case"aaa":return n.dayPeriod(a,{width:"abbreviated",context:"formatting"}).toLowerCase();case"aaaaa":return n.dayPeriod(a,{width:"narrow",context:"formatting"});case"aaaa":default:return n.dayPeriod(a,{width:"wide",context:"formatting"})}},b:function(s,t,n){const r=s.getHours();let a;switch(r===12?a=w$.noon:r===0?a=w$.midnight:a=r/12>=1?"pm":"am",t){case"b":case"bb":return n.dayPeriod(a,{width:"abbreviated",context:"formatting"});case"bbb":return n.dayPeriod(a,{width:"abbreviated",context:"formatting"}).toLowerCase();case"bbbbb":return n.dayPeriod(a,{width:"narrow",context:"formatting"});case"bbbb":default:return n.dayPeriod(a,{width:"wide",context:"formatting"})}},B:function(s,t,n){const r=s.getHours();let a;switch(r>=17?a=w$.evening:r>=12?a=w$.afternoon:r>=4?a=w$.morning:a=w$.night,t){case"B":case"BB":case"BBB":return n.dayPeriod(a,{width:"abbreviated",context:"formatting"});case"BBBBB":return n.dayPeriod(a,{width:"narrow",context:"formatting"});case"BBBB":default:return n.dayPeriod(a,{width:"wide",context:"formatting"})}},h:function(s,t,n){if(t==="ho"){let r=s.getHours()%12;return r===0&&(r=12),n.ordinalNumber(r,{unit:"hour"})}return _M.h(s,t)},H:function(s,t,n){return t==="Ho"?n.ordinalNumber(s.getHours(),{unit:"hour"}):_M.H(s,t)},K:function(s,t,n){const r=s.getHours()%12;return t==="Ko"?n.ordinalNumber(r,{unit:"hour"}):Am(r,t.length)},k:function(s,t,n){let r=s.getHours();return r===0&&(r=24),t==="ko"?n.ordinalNumber(r,{unit:"hour"}):Am(r,t.length)},m:function(s,t,n){return t==="mo"?n.ordinalNumber(s.getMinutes(),{unit:"minute"}):_M.m(s,t)},s:function(s,t,n){return t==="so"?n.ordinalNumber(s.getSeconds(),{unit:"second"}):_M.s(s,t)},S:function(s,t){return _M.S(s,t)},X:function(s,t,n){const r=s.getTimezoneOffset();if(r===0)return"Z";switch(t){case"X":return Dyt(r);case"XXXX":case"XX":return DO(r);case"XXXXX":case"XXX":default:return DO(r,":")}},x:function(s,t,n){const r=s.getTimezoneOffset();switch(t){case"x":return Dyt(r);case"xxxx":case"xx":return DO(r);case"xxxxx":case"xxx":default:return DO(r,":")}},O:function(s,t,n){const r=s.getTimezoneOffset();switch(t){case"O":case"OO":case"OOO":return"GMT"+Ryt(r,":");case"OOOO":default:return"GMT"+DO(r,":")}},z:function(s,t,n){const r=s.getTimezoneOffset();switch(t){case"z":case"zz":case"zzz":return"GMT"+Ryt(r,":");case"zzzz":default:return"GMT"+DO(r,":")}},t:function(s,t,n){const r=Math.trunc(s.getTime()/1e3);return Am(r,t.length)},T:function(s,t,n){const r=s.getTime();return Am(r,t.length)}};function Ryt(s,t=""){const n=s>0?"-":"+",r=Math.abs(s),a=Math.trunc(r/60),i=r%60;return i===0?n+String(a):n+String(a)+t+Am(i,2)}function Dyt(s,t){return s%60===0?(s>0?"-":"+")+Am(Math.abs(s)/60,2):DO(s,t)}function DO(s,t=""){const n=s>0?"-":"+",r=Math.abs(s),a=Am(Math.trunc(r/60),2),i=Am(r%60,2);return n+a+t+i}const Fyt=(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"})}},Izt=(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"})}},aIs=(s,t)=>{const n=s.match(/(P+)(p+)?/)||[],r=n[1],a=n[2];if(!a)return Fyt(s,t);let i;switch(r){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}}",Fyt(r,t)).replace("{{time}}",Izt(a,t))},QHe={p:Izt,P:aIs},iIs=/^D+$/,oIs=/^Y+$/,lIs=["D","DD","YY","YYYY"];function Lzt(s){return iIs.test(s)}function Rzt(s){return oIs.test(s)}function JHe(s,t,n){const r=cIs(s,t,n);if(console.warn(r),lIs.includes(s))throw new RangeError(r)}function cIs(s,t,n){const r=s[0]==="Y"?"years":"days of the month";return`Use \`${s.toLowerCase()}\` instead of \`${s}\` (in \`${t}\`) for formatting ${r} to the input \`${n}\`; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md`}const dIs=/[yYQqMLwIdDecihHKkms]o|(\w)\1*|''|'(''|[^'])+('|$)|./g,uIs=/P+p+|P+|p+|''|'(''|[^'])+('|$)|./g,hIs=/^'([^]*?)'?$/,mIs=/''/g,fIs=/[a-zA-Z]/;function en(s,t,n){var u,h,m,f,g,x,y,v;const r=l6(),a=(n==null?void 0:n.locale)??r.locale??FLe,i=(n==null?void 0:n.firstWeekContainsDate)??((h=(u=n==null?void 0:n.locale)==null?void 0:u.options)==null?void 0:h.firstWeekContainsDate)??r.firstWeekContainsDate??((f=(m=r.locale)==null?void 0:m.options)==null?void 0:f.firstWeekContainsDate)??1,l=(n==null?void 0:n.weekStartsOn)??((x=(g=n==null?void 0:n.locale)==null?void 0:g.options)==null?void 0:x.weekStartsOn)??r.weekStartsOn??((v=(y=r.locale)==null?void 0:y.options)==null?void 0:v.weekStartsOn)??0,o=So(s);if(!XHe(o))throw new RangeError("Invalid time value");let c=t.match(uIs).map(b=>{const w=b[0];if(w==="p"||w==="P"){const S=QHe[w];return S(b,a.formatLong)}return b}).join("").match(dIs).map(b=>{if(b==="''")return{isToken:!1,value:"'"};const w=b[0];if(w==="'")return{isToken:!1,value:pIs(b)};if(Lyt[w])return{isToken:!0,value:b};if(w.match(fIs))throw new RangeError("Format string contains an unescaped latin alphabet character `"+w+"`");return{isToken:!1,value:b}});a.localize.preprocessor&&(c=a.localize.preprocessor(o,c));const d={firstWeekContainsDate:i,weekStartsOn:l,locale:a};return c.map(b=>{if(!b.isToken)return b.value;const w=b.value;(!(n!=null&&n.useAdditionalWeekYearTokens)&&Rzt(w)||!(n!=null&&n.useAdditionalDayOfYearTokens)&&Lzt(w))&&JHe(w,t,String(s));const S=Lyt[w[0]];return S(o,w,a.localize,d)}).join("")}function pIs(s){const t=s.match(hIs);return t?t[1].replace(mIs,"'"):s}function gIs(s,t,n){const r=l6(),a=(n==null?void 0:n.locale)??r.locale??FLe,i=2520,l=Q4e(s,t);if(isNaN(l))throw new RangeError("Invalid time value");const o=Object.assign({},n,{addSuffix:n==null?void 0:n.addSuffix,comparison:l});let c,d;l>0?(c=So(t),d=So(s)):(c=So(s),d=So(t));const u=wPs(d,c),h=(EL(d)-EL(c))/1e3,m=Math.round((u-h)/60);let f;if(m<2)return n!=null&&n.includeSeconds?u<5?a.formatDistance("lessThanXSeconds",5,o):u<10?a.formatDistance("lessThanXSeconds",10,o):u<20?a.formatDistance("lessThanXSeconds",20,o):u<40?a.formatDistance("halfAMinute",0,o):u<60?a.formatDistance("lessThanXMinutes",1,o):a.formatDistance("xMinutes",1,o):m===0?a.formatDistance("lessThanXMinutes",1,o):a.formatDistance("xMinutes",m,o);if(m<45)return a.formatDistance("xMinutes",m,o);if(m<90)return a.formatDistance("aboutXHours",1,o);if(mr.getTime()}function iC(s,t){const n=So(s),r=So(t);return+n<+r}function jIs(s){return+So(s)>Date.now()}function NIs(s,t){const n=t instanceof Date?Mm(t,0):new t(0);return n.setFullYear(s.getFullYear(),s.getMonth(),s.getDate()),n.setHours(s.getHours(),s.getMinutes(),s.getSeconds(),s.getMilliseconds()),n}const kIs=10;class Dzt{constructor(){Nr(this,"subPriority",0)}validate(t,n){return!0}}class SIs extends Dzt{constructor(t,n,r,a,i){super(),this.value=t,this.validateValue=n,this.setValue=r,this.priority=a,i&&(this.subPriority=i)}validate(t,n){return this.validateValue(t,this.value,n)}set(t,n,r){return this.setValue(t,n,this.value,r)}}class CIs extends Dzt{constructor(){super(...arguments);Nr(this,"priority",kIs);Nr(this,"subPriority",-1)}set(n,r){return r.timestampIsSet?n:Mm(n,NIs(n,Date))}}class lm{run(t,n,r,a){const i=this.parse(t,n,r,a);return i?{setter:new SIs(i.value,this.validate,this.set,this.priority,this.subPriority),rest:i.rest}:null}validate(t,n,r){return!0}}class AIs extends lm{constructor(){super(...arguments);Nr(this,"priority",140);Nr(this,"incompatibleTokens",["R","u","t","T"])}parse(n,r,a){switch(r){case"G":case"GG":case"GGG":return a.era(n,{width:"abbreviated"})||a.era(n,{width:"narrow"});case"GGGGG":return a.era(n,{width:"narrow"});case"GGGG":default:return a.era(n,{width:"wide"})||a.era(n,{width:"abbreviated"})||a.era(n,{width:"narrow"})}}set(n,r,a){return r.era=a,n.setFullYear(a,0,1),n.setHours(0,0,0,0),n}}const dy={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}/},d4={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 uy(s,t){return s&&{value:t(s.value),rest:s.rest}}function Eg(s,t){const n=t.match(s);return n?{value:parseInt(n[0],10),rest:t.slice(n[0].length)}:null}function u4(s,t){const n=t.match(s);if(!n)return null;if(n[0]==="Z")return{value:0,rest:t.slice(1)};const r=n[1]==="+"?1:-1,a=n[2]?parseInt(n[2],10):0,i=n[3]?parseInt(n[3],10):0,l=n[5]?parseInt(n[5],10):0;return{value:r*(a*LLe+i*ILe+l*dPs),rest:t.slice(n[0].length)}}function Fzt(s){return Eg(dy.anyDigitsSigned,s)}function Tx(s,t){switch(s){case 1:return Eg(dy.singleDigit,t);case 2:return Eg(dy.twoDigits,t);case 3:return Eg(dy.threeDigits,t);case 4:return Eg(dy.fourDigits,t);default:return Eg(new RegExp("^\\d{1,"+s+"}"),t)}}function MEe(s,t){switch(s){case 1:return Eg(dy.singleDigitSigned,t);case 2:return Eg(dy.twoDigitsSigned,t);case 3:return Eg(dy.threeDigitsSigned,t);case 4:return Eg(dy.fourDigitsSigned,t);default:return Eg(new RegExp("^-?\\d{1,"+s+"}"),t)}}function Ptt(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 Ozt(s,t){const n=t>0,r=n?t:1-t;let a;if(r<=50)a=s||100;else{const i=r+50,l=Math.trunc(i/100)*100,o=s>=i%100;a=s+l-(o?100:0)}return n?a:1-a}function zzt(s){return s%400===0||s%4===0&&s%100!==0}class EIs extends lm{constructor(){super(...arguments);Nr(this,"priority",130);Nr(this,"incompatibleTokens",["Y","R","u","w","I","i","e","c","t","T"])}parse(n,r,a){const i=l=>({year:l,isTwoDigitYear:r==="yy"});switch(r){case"y":return uy(Tx(4,n),i);case"yo":return uy(a.ordinalNumber(n,{unit:"year"}),i);default:return uy(Tx(r.length,n),i)}}validate(n,r){return r.isTwoDigitYear||r.year>0}set(n,r,a){const i=n.getFullYear();if(a.isTwoDigitYear){const o=Ozt(a.year,i);return n.setFullYear(o,0,1),n.setHours(0,0,0,0),n}const l=!("era"in r)||r.era===1?a.year:1-a.year;return n.setFullYear(l,0,1),n.setHours(0,0,0,0),n}}class TIs extends lm{constructor(){super(...arguments);Nr(this,"priority",130);Nr(this,"incompatibleTokens",["y","R","u","Q","q","M","L","I","d","D","i","t","T"])}parse(n,r,a){const i=l=>({year:l,isTwoDigitYear:r==="YY"});switch(r){case"Y":return uy(Tx(4,n),i);case"Yo":return uy(a.ordinalNumber(n,{unit:"year"}),i);default:return uy(Tx(r.length,n),i)}}validate(n,r){return r.isTwoDigitYear||r.year>0}set(n,r,a,i){const l=Ttt(n,i);if(a.isTwoDigitYear){const c=Ozt(a.year,l);return n.setFullYear(c,0,i.firstWeekContainsDate),n.setHours(0,0,0,0),C1(n,i)}const o=!("era"in r)||r.era===1?a.year:1-a.year;return n.setFullYear(o,0,i.firstWeekContainsDate),n.setHours(0,0,0,0),C1(n,i)}}class MIs extends lm{constructor(){super(...arguments);Nr(this,"priority",130);Nr(this,"incompatibleTokens",["G","y","Y","u","Q","q","M","L","w","d","D","e","c","t","T"])}parse(n,r){return MEe(r==="R"?4:r.length,n)}set(n,r,a){const i=Mm(n,0);return i.setFullYear(a,0,4),i.setHours(0,0,0,0),fT(i)}}class PIs extends lm{constructor(){super(...arguments);Nr(this,"priority",130);Nr(this,"incompatibleTokens",["G","y","Y","R","w","I","i","e","c","t","T"])}parse(n,r){return MEe(r==="u"?4:r.length,n)}set(n,r,a){return n.setFullYear(a,0,1),n.setHours(0,0,0,0),n}}class IIs extends lm{constructor(){super(...arguments);Nr(this,"priority",120);Nr(this,"incompatibleTokens",["Y","R","q","M","L","w","I","d","D","i","e","c","t","T"])}parse(n,r,a){switch(r){case"Q":case"QQ":return Tx(r.length,n);case"Qo":return a.ordinalNumber(n,{unit:"quarter"});case"QQQ":return a.quarter(n,{width:"abbreviated",context:"formatting"})||a.quarter(n,{width:"narrow",context:"formatting"});case"QQQQQ":return a.quarter(n,{width:"narrow",context:"formatting"});case"QQQQ":default:return a.quarter(n,{width:"wide",context:"formatting"})||a.quarter(n,{width:"abbreviated",context:"formatting"})||a.quarter(n,{width:"narrow",context:"formatting"})}}validate(n,r){return r>=1&&r<=4}set(n,r,a){return n.setMonth((a-1)*3,1),n.setHours(0,0,0,0),n}}class LIs extends lm{constructor(){super(...arguments);Nr(this,"priority",120);Nr(this,"incompatibleTokens",["Y","R","Q","M","L","w","I","d","D","i","e","c","t","T"])}parse(n,r,a){switch(r){case"q":case"qq":return Tx(r.length,n);case"qo":return a.ordinalNumber(n,{unit:"quarter"});case"qqq":return a.quarter(n,{width:"abbreviated",context:"standalone"})||a.quarter(n,{width:"narrow",context:"standalone"});case"qqqqq":return a.quarter(n,{width:"narrow",context:"standalone"});case"qqqq":default:return a.quarter(n,{width:"wide",context:"standalone"})||a.quarter(n,{width:"abbreviated",context:"standalone"})||a.quarter(n,{width:"narrow",context:"standalone"})}}validate(n,r){return r>=1&&r<=4}set(n,r,a){return n.setMonth((a-1)*3,1),n.setHours(0,0,0,0),n}}class RIs extends lm{constructor(){super(...arguments);Nr(this,"incompatibleTokens",["Y","R","q","Q","L","w","I","D","i","e","c","t","T"]);Nr(this,"priority",110)}parse(n,r,a){const i=l=>l-1;switch(r){case"M":return uy(Eg(dy.month,n),i);case"MM":return uy(Tx(2,n),i);case"Mo":return uy(a.ordinalNumber(n,{unit:"month"}),i);case"MMM":return a.month(n,{width:"abbreviated",context:"formatting"})||a.month(n,{width:"narrow",context:"formatting"});case"MMMMM":return a.month(n,{width:"narrow",context:"formatting"});case"MMMM":default:return a.month(n,{width:"wide",context:"formatting"})||a.month(n,{width:"abbreviated",context:"formatting"})||a.month(n,{width:"narrow",context:"formatting"})}}validate(n,r){return r>=0&&r<=11}set(n,r,a){return n.setMonth(a,1),n.setHours(0,0,0,0),n}}class DIs extends lm{constructor(){super(...arguments);Nr(this,"priority",110);Nr(this,"incompatibleTokens",["Y","R","q","Q","M","w","I","D","i","e","c","t","T"])}parse(n,r,a){const i=l=>l-1;switch(r){case"L":return uy(Eg(dy.month,n),i);case"LL":return uy(Tx(2,n),i);case"Lo":return uy(a.ordinalNumber(n,{unit:"month"}),i);case"LLL":return a.month(n,{width:"abbreviated",context:"standalone"})||a.month(n,{width:"narrow",context:"standalone"});case"LLLLL":return a.month(n,{width:"narrow",context:"standalone"});case"LLLL":default:return a.month(n,{width:"wide",context:"standalone"})||a.month(n,{width:"abbreviated",context:"standalone"})||a.month(n,{width:"narrow",context:"standalone"})}}validate(n,r){return r>=0&&r<=11}set(n,r,a){return n.setMonth(a,1),n.setHours(0,0,0,0),n}}function FIs(s,t,n){const r=So(s),a=Mtt(r,n)-t;return r.setDate(r.getDate()-a*7),r}class OIs extends lm{constructor(){super(...arguments);Nr(this,"priority",100);Nr(this,"incompatibleTokens",["y","R","u","q","Q","M","L","I","d","D","i","t","T"])}parse(n,r,a){switch(r){case"w":return Eg(dy.week,n);case"wo":return a.ordinalNumber(n,{unit:"week"});default:return Tx(r.length,n)}}validate(n,r){return r>=1&&r<=53}set(n,r,a,i){return C1(FIs(n,a,i),i)}}function zIs(s,t){const n=So(s),r=Ett(n)-t;return n.setDate(n.getDate()-r*7),n}class BIs extends lm{constructor(){super(...arguments);Nr(this,"priority",100);Nr(this,"incompatibleTokens",["y","Y","u","q","Q","M","L","w","d","D","e","c","t","T"])}parse(n,r,a){switch(r){case"I":return Eg(dy.week,n);case"Io":return a.ordinalNumber(n,{unit:"week"});default:return Tx(r.length,n)}}validate(n,r){return r>=1&&r<=53}set(n,r,a){return fT(zIs(n,a))}}const $Is=[31,28,31,30,31,30,31,31,30,31,30,31],UIs=[31,29,31,30,31,30,31,31,30,31,30,31];class qIs extends lm{constructor(){super(...arguments);Nr(this,"priority",90);Nr(this,"subPriority",1);Nr(this,"incompatibleTokens",["Y","R","q","Q","w","I","D","i","e","c","t","T"])}parse(n,r,a){switch(r){case"d":return Eg(dy.date,n);case"do":return a.ordinalNumber(n,{unit:"date"});default:return Tx(r.length,n)}}validate(n,r){const a=n.getFullYear(),i=zzt(a),l=n.getMonth();return i?r>=1&&r<=UIs[l]:r>=1&&r<=$Is[l]}set(n,r,a){return n.setDate(a),n.setHours(0,0,0,0),n}}class VIs extends lm{constructor(){super(...arguments);Nr(this,"priority",90);Nr(this,"subpriority",1);Nr(this,"incompatibleTokens",["Y","R","q","Q","M","L","w","I","d","E","i","e","c","t","T"])}parse(n,r,a){switch(r){case"D":case"DD":return Eg(dy.dayOfYear,n);case"Do":return a.ordinalNumber(n,{unit:"date"});default:return Tx(r.length,n)}}validate(n,r){const a=n.getFullYear();return zzt(a)?r>=1&&r<=366:r>=1&&r<=365}set(n,r,a){return n.setMonth(0,a),n.setHours(0,0,0,0),n}}function Itt(s,t,n){var h,m,f,g;const r=l6(),a=(n==null?void 0:n.weekStartsOn)??((m=(h=n==null?void 0:n.locale)==null?void 0:h.options)==null?void 0:m.weekStartsOn)??r.weekStartsOn??((g=(f=r.locale)==null?void 0:f.options)==null?void 0:g.weekStartsOn)??0,i=So(s),l=i.getDay(),c=(t%7+7)%7,d=7-a,u=t<0||t>6?t-(l+d)%7:(c+d)%7-(l+d)%7;return Tm(i,u)}class HIs extends lm{constructor(){super(...arguments);Nr(this,"priority",90);Nr(this,"incompatibleTokens",["D","i","e","c","t","T"])}parse(n,r,a){switch(r){case"E":case"EE":case"EEE":return a.day(n,{width:"abbreviated",context:"formatting"})||a.day(n,{width:"short",context:"formatting"})||a.day(n,{width:"narrow",context:"formatting"});case"EEEEE":return a.day(n,{width:"narrow",context:"formatting"});case"EEEEEE":return a.day(n,{width:"short",context:"formatting"})||a.day(n,{width:"narrow",context:"formatting"});case"EEEE":default:return a.day(n,{width:"wide",context:"formatting"})||a.day(n,{width:"abbreviated",context:"formatting"})||a.day(n,{width:"short",context:"formatting"})||a.day(n,{width:"narrow",context:"formatting"})}}validate(n,r){return r>=0&&r<=6}set(n,r,a,i){return n=Itt(n,a,i),n.setHours(0,0,0,0),n}}class GIs extends lm{constructor(){super(...arguments);Nr(this,"priority",90);Nr(this,"incompatibleTokens",["y","R","u","q","Q","M","L","I","d","D","E","i","c","t","T"])}parse(n,r,a,i){const l=o=>{const c=Math.floor((o-1)/7)*7;return(o+i.weekStartsOn+6)%7+c};switch(r){case"e":case"ee":return uy(Tx(r.length,n),l);case"eo":return uy(a.ordinalNumber(n,{unit:"day"}),l);case"eee":return a.day(n,{width:"abbreviated",context:"formatting"})||a.day(n,{width:"short",context:"formatting"})||a.day(n,{width:"narrow",context:"formatting"});case"eeeee":return a.day(n,{width:"narrow",context:"formatting"});case"eeeeee":return a.day(n,{width:"short",context:"formatting"})||a.day(n,{width:"narrow",context:"formatting"});case"eeee":default:return a.day(n,{width:"wide",context:"formatting"})||a.day(n,{width:"abbreviated",context:"formatting"})||a.day(n,{width:"short",context:"formatting"})||a.day(n,{width:"narrow",context:"formatting"})}}validate(n,r){return r>=0&&r<=6}set(n,r,a,i){return n=Itt(n,a,i),n.setHours(0,0,0,0),n}}class WIs extends lm{constructor(){super(...arguments);Nr(this,"priority",90);Nr(this,"incompatibleTokens",["y","R","u","q","Q","M","L","I","d","D","E","i","e","t","T"])}parse(n,r,a,i){const l=o=>{const c=Math.floor((o-1)/7)*7;return(o+i.weekStartsOn+6)%7+c};switch(r){case"c":case"cc":return uy(Tx(r.length,n),l);case"co":return uy(a.ordinalNumber(n,{unit:"day"}),l);case"ccc":return a.day(n,{width:"abbreviated",context:"standalone"})||a.day(n,{width:"short",context:"standalone"})||a.day(n,{width:"narrow",context:"standalone"});case"ccccc":return a.day(n,{width:"narrow",context:"standalone"});case"cccccc":return a.day(n,{width:"short",context:"standalone"})||a.day(n,{width:"narrow",context:"standalone"});case"cccc":default:return a.day(n,{width:"wide",context:"standalone"})||a.day(n,{width:"abbreviated",context:"standalone"})||a.day(n,{width:"short",context:"standalone"})||a.day(n,{width:"narrow",context:"standalone"})}}validate(n,r){return r>=0&&r<=6}set(n,r,a,i){return n=Itt(n,a,i),n.setHours(0,0,0,0),n}}function KIs(s,t){const n=So(s),r=vIs(n),a=t-r;return Tm(n,a)}class YIs extends lm{constructor(){super(...arguments);Nr(this,"priority",90);Nr(this,"incompatibleTokens",["y","Y","u","q","Q","M","L","w","d","D","E","e","c","t","T"])}parse(n,r,a){const i=l=>l===0?7:l;switch(r){case"i":case"ii":return Tx(r.length,n);case"io":return a.ordinalNumber(n,{unit:"day"});case"iii":return uy(a.day(n,{width:"abbreviated",context:"formatting"})||a.day(n,{width:"short",context:"formatting"})||a.day(n,{width:"narrow",context:"formatting"}),i);case"iiiii":return uy(a.day(n,{width:"narrow",context:"formatting"}),i);case"iiiiii":return uy(a.day(n,{width:"short",context:"formatting"})||a.day(n,{width:"narrow",context:"formatting"}),i);case"iiii":default:return uy(a.day(n,{width:"wide",context:"formatting"})||a.day(n,{width:"abbreviated",context:"formatting"})||a.day(n,{width:"short",context:"formatting"})||a.day(n,{width:"narrow",context:"formatting"}),i)}}validate(n,r){return r>=1&&r<=7}set(n,r,a){return n=KIs(n,a),n.setHours(0,0,0,0),n}}class ZIs extends lm{constructor(){super(...arguments);Nr(this,"priority",80);Nr(this,"incompatibleTokens",["b","B","H","k","t","T"])}parse(n,r,a){switch(r){case"a":case"aa":case"aaa":return a.dayPeriod(n,{width:"abbreviated",context:"formatting"})||a.dayPeriod(n,{width:"narrow",context:"formatting"});case"aaaaa":return a.dayPeriod(n,{width:"narrow",context:"formatting"});case"aaaa":default:return a.dayPeriod(n,{width:"wide",context:"formatting"})||a.dayPeriod(n,{width:"abbreviated",context:"formatting"})||a.dayPeriod(n,{width:"narrow",context:"formatting"})}}set(n,r,a){return n.setHours(Ptt(a),0,0,0),n}}class XIs extends lm{constructor(){super(...arguments);Nr(this,"priority",80);Nr(this,"incompatibleTokens",["a","B","H","k","t","T"])}parse(n,r,a){switch(r){case"b":case"bb":case"bbb":return a.dayPeriod(n,{width:"abbreviated",context:"formatting"})||a.dayPeriod(n,{width:"narrow",context:"formatting"});case"bbbbb":return a.dayPeriod(n,{width:"narrow",context:"formatting"});case"bbbb":default:return a.dayPeriod(n,{width:"wide",context:"formatting"})||a.dayPeriod(n,{width:"abbreviated",context:"formatting"})||a.dayPeriod(n,{width:"narrow",context:"formatting"})}}set(n,r,a){return n.setHours(Ptt(a),0,0,0),n}}class QIs extends lm{constructor(){super(...arguments);Nr(this,"priority",80);Nr(this,"incompatibleTokens",["a","b","t","T"])}parse(n,r,a){switch(r){case"B":case"BB":case"BBB":return a.dayPeriod(n,{width:"abbreviated",context:"formatting"})||a.dayPeriod(n,{width:"narrow",context:"formatting"});case"BBBBB":return a.dayPeriod(n,{width:"narrow",context:"formatting"});case"BBBB":default:return a.dayPeriod(n,{width:"wide",context:"formatting"})||a.dayPeriod(n,{width:"abbreviated",context:"formatting"})||a.dayPeriod(n,{width:"narrow",context:"formatting"})}}set(n,r,a){return n.setHours(Ptt(a),0,0,0),n}}class JIs extends lm{constructor(){super(...arguments);Nr(this,"priority",70);Nr(this,"incompatibleTokens",["H","K","k","t","T"])}parse(n,r,a){switch(r){case"h":return Eg(dy.hour12h,n);case"ho":return a.ordinalNumber(n,{unit:"hour"});default:return Tx(r.length,n)}}validate(n,r){return r>=1&&r<=12}set(n,r,a){const i=n.getHours()>=12;return i&&a<12?n.setHours(a+12,0,0,0):!i&&a===12?n.setHours(0,0,0,0):n.setHours(a,0,0,0),n}}class eLs extends lm{constructor(){super(...arguments);Nr(this,"priority",70);Nr(this,"incompatibleTokens",["a","b","h","K","k","t","T"])}parse(n,r,a){switch(r){case"H":return Eg(dy.hour23h,n);case"Ho":return a.ordinalNumber(n,{unit:"hour"});default:return Tx(r.length,n)}}validate(n,r){return r>=0&&r<=23}set(n,r,a){return n.setHours(a,0,0,0),n}}class tLs extends lm{constructor(){super(...arguments);Nr(this,"priority",70);Nr(this,"incompatibleTokens",["h","H","k","t","T"])}parse(n,r,a){switch(r){case"K":return Eg(dy.hour11h,n);case"Ko":return a.ordinalNumber(n,{unit:"hour"});default:return Tx(r.length,n)}}validate(n,r){return r>=0&&r<=11}set(n,r,a){return n.getHours()>=12&&a<12?n.setHours(a+12,0,0,0):n.setHours(a,0,0,0),n}}class sLs extends lm{constructor(){super(...arguments);Nr(this,"priority",70);Nr(this,"incompatibleTokens",["a","b","h","H","K","t","T"])}parse(n,r,a){switch(r){case"k":return Eg(dy.hour24h,n);case"ko":return a.ordinalNumber(n,{unit:"hour"});default:return Tx(r.length,n)}}validate(n,r){return r>=1&&r<=24}set(n,r,a){const i=a<=24?a%24:a;return n.setHours(i,0,0,0),n}}class nLs extends lm{constructor(){super(...arguments);Nr(this,"priority",60);Nr(this,"incompatibleTokens",["t","T"])}parse(n,r,a){switch(r){case"m":return Eg(dy.minute,n);case"mo":return a.ordinalNumber(n,{unit:"minute"});default:return Tx(r.length,n)}}validate(n,r){return r>=0&&r<=59}set(n,r,a){return n.setMinutes(a,0,0),n}}class rLs extends lm{constructor(){super(...arguments);Nr(this,"priority",50);Nr(this,"incompatibleTokens",["t","T"])}parse(n,r,a){switch(r){case"s":return Eg(dy.second,n);case"so":return a.ordinalNumber(n,{unit:"second"});default:return Tx(r.length,n)}}validate(n,r){return r>=0&&r<=59}set(n,r,a){return n.setSeconds(a,0),n}}class aLs extends lm{constructor(){super(...arguments);Nr(this,"priority",30);Nr(this,"incompatibleTokens",["t","T"])}parse(n,r){const a=i=>Math.trunc(i*Math.pow(10,-r.length+3));return uy(Tx(r.length,n),a)}set(n,r,a){return n.setMilliseconds(a),n}}class iLs extends lm{constructor(){super(...arguments);Nr(this,"priority",10);Nr(this,"incompatibleTokens",["t","T","x"])}parse(n,r){switch(r){case"X":return u4(d4.basicOptionalMinutes,n);case"XX":return u4(d4.basic,n);case"XXXX":return u4(d4.basicOptionalSeconds,n);case"XXXXX":return u4(d4.extendedOptionalSeconds,n);case"XXX":default:return u4(d4.extended,n)}}set(n,r,a){return r.timestampIsSet?n:Mm(n,n.getTime()-EL(n)-a)}}class oLs extends lm{constructor(){super(...arguments);Nr(this,"priority",10);Nr(this,"incompatibleTokens",["t","T","X"])}parse(n,r){switch(r){case"x":return u4(d4.basicOptionalMinutes,n);case"xx":return u4(d4.basic,n);case"xxxx":return u4(d4.basicOptionalSeconds,n);case"xxxxx":return u4(d4.extendedOptionalSeconds,n);case"xxx":default:return u4(d4.extended,n)}}set(n,r,a){return r.timestampIsSet?n:Mm(n,n.getTime()-EL(n)-a)}}class lLs extends lm{constructor(){super(...arguments);Nr(this,"priority",40);Nr(this,"incompatibleTokens","*")}parse(n){return Fzt(n)}set(n,r,a){return[Mm(n,a*1e3),{timestampIsSet:!0}]}}class cLs extends lm{constructor(){super(...arguments);Nr(this,"priority",20);Nr(this,"incompatibleTokens","*")}parse(n){return Fzt(n)}set(n,r,a){return[Mm(n,a),{timestampIsSet:!0}]}}const dLs={G:new AIs,y:new EIs,Y:new TIs,R:new MIs,u:new PIs,Q:new IIs,q:new LIs,M:new RIs,L:new DIs,w:new OIs,I:new BIs,d:new qIs,D:new VIs,E:new HIs,e:new GIs,c:new WIs,i:new YIs,a:new ZIs,b:new XIs,B:new QIs,h:new JIs,H:new eLs,K:new tLs,k:new sLs,m:new nLs,s:new rLs,S:new aLs,X:new iLs,x:new oLs,t:new lLs,T:new cLs},uLs=/[yYQqMLwIdDecihHKkms]o|(\w)\1*|''|'(''|[^'])+('|$)|./g,hLs=/P+p+|P+|p+|''|'(''|[^'])+('|$)|./g,mLs=/^'([^]*?)'?$/,fLs=/''/g,pLs=/\S/,gLs=/[a-zA-Z]/;function Ltt(s,t,n,r){var x,y,v,b;const a=yIs(),i=a.locale??FLe,l=a.firstWeekContainsDate??((y=(x=a.locale)==null?void 0:x.options)==null?void 0:y.firstWeekContainsDate)??1,o=a.weekStartsOn??((b=(v=a.locale)==null?void 0:v.options)==null?void 0:b.weekStartsOn)??0;if(t==="")return s===""?So(n):Mm(n,NaN);const c={firstWeekContainsDate:l,weekStartsOn:o,locale:i},d=[new CIs],u=t.match(hLs).map(w=>{const S=w[0];if(S in QHe){const C=QHe[S];return C(w,i.formatLong)}return w}).join("").match(uLs),h=[];for(let w of u){Rzt(w)&&JHe(w,t,s),Lzt(w)&&JHe(w,t,s);const S=w[0],C=dLs[S];if(C){const{incompatibleTokens:E}=C;if(Array.isArray(E)){const P=h.find(R=>E.includes(R.token)||R.token===S);if(P)throw new RangeError(`The format string mustn't contain \`${P.fullToken}\` and \`${w}\` at the same time`)}else if(C.incompatibleTokens==="*"&&h.length>0)throw new RangeError(`The format string mustn't contain \`${w}\` and any other token at the same time`);h.push({token:S,fullToken:w});const I=C.run(s,w,i.match,c);if(!I)return Mm(n,NaN);d.push(I.setter),s=I.rest}else{if(S.match(gLs))throw new RangeError("Format string contains an unescaped latin alphabet character `"+S+"`");if(w==="''"?w="'":S==="'"&&(w=xLs(w)),s.indexOf(w)===0)s=s.slice(w.length);else return Mm(n,NaN)}}if(s.length>0&&pLs.test(s))return Mm(n,NaN);const m=d.map(w=>w.priority).sort((w,S)=>S-w).filter((w,S,C)=>C.indexOf(w)===S).map(w=>d.filter(S=>S.priority===w).sort((S,C)=>C.subPriority-S.subPriority)).map(w=>w[0]);let f=So(n);if(isNaN(f.getTime()))return Mm(n,NaN);const g={};for(const w of m){if(!w.validate(f,c))return Mm(n,NaN);const S=w.set(f,g,c);Array.isArray(S)?(f=S[0],Object.assign(g,S[1])):f=S}return Mm(n,f)}function xLs(s){return s.match(mLs)[1].replace(fLs,"'")}function z4(s){return+So(s)i-l);return n>=r&&n<=a}function J4e(s,t){return Tm(s,-t)}function vv(s,t){const r=kLs(s);let a;if(r.date){const c=SLs(r.date,2);a=CLs(c.restDateString,c.year)}if(!a||isNaN(a.getTime()))return new Date(NaN);const i=a.getTime();let l=0,o;if(r.time&&(l=ALs(r.time),isNaN(l)))return new Date(NaN);if(r.timezone){if(o=ELs(r.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 Oce={dateTimeDelimiter:/[T ]/,timeZoneDelimiter:/[Z ]/i,timezone:/([Z+-].*)$/},wLs=/^-?(?:(\d{3})|(\d{2})(?:-?(\d{2}))?|W(\d{2})(?:-?(\d{1}))?|)$/,jLs=/^(\d{2}(?:[.,]\d*)?)(?::?(\d{2}(?:[.,]\d*)?))?(?::?(\d{2}(?:[.,]\d*)?))?$/,NLs=/^([+-])(\d{2})(?::?(\d{2}))?$/;function kLs(s){const t={},n=s.split(Oce.dateTimeDelimiter);let r;if(n.length>2)return t;if(/:/.test(n[0])?r=n[0]:(t.date=n[0],r=n[1],Oce.timeZoneDelimiter.test(t.date)&&(t.date=s.split(Oce.timeZoneDelimiter)[0],r=s.substr(t.date.length,s.length))),r){const a=Oce.timezone.exec(r);a?(t.time=r.replace(a[1],""),t.timezone=a[1]):t.time=r}return t}function SLs(s,t){const n=new RegExp("^(?:(\\d{4}|[+-]\\d{"+(4+t)+"})|(\\d{2}|[+-]\\d{"+(2+t)+"})$)"),r=s.match(n);if(!r)return{year:NaN,restDateString:""};const a=r[1]?parseInt(r[1]):null,i=r[2]?parseInt(r[2]):null;return{year:i===null?a:i*100,restDateString:s.slice((r[1]||r[2]).length)}}function CLs(s,t){if(t===null)return new Date(NaN);const n=s.match(wLs);if(!n)return new Date(NaN);const r=!!n[4],a=AZ(n[1]),i=AZ(n[2])-1,l=AZ(n[3]),o=AZ(n[4]),c=AZ(n[5])-1;if(r)return LLs(t,o,c)?TLs(t,o,c):new Date(NaN);{const d=new Date(0);return!PLs(t,i,l)||!ILs(t,a)?new Date(NaN):(d.setUTCFullYear(t,i,Math.max(a,l)),d)}}function AZ(s){return s?parseInt(s):1}function ALs(s){const t=s.match(jLs);if(!t)return NaN;const n=a7e(t[1]),r=a7e(t[2]),a=a7e(t[3]);return RLs(n,r,a)?n*LLe+r*ILe+a*1e3:NaN}function a7e(s){return s&&parseFloat(s.replace(",","."))||0}function ELs(s){if(s==="Z")return 0;const t=s.match(NLs);if(!t)return 0;const n=t[1]==="+"?-1:1,r=parseInt(t[2]),a=t[3]&&parseInt(t[3])||0;return DLs(r,a)?n*(r*LLe+a*ILe):NaN}function TLs(s,t,n){const r=new Date(0);r.setUTCFullYear(s,0,4);const a=r.getUTCDay()||7,i=(t-1)*7+n+1-a;return r.setUTCDate(r.getUTCDate()+i),r}const MLs=[31,null,31,30,31,30,31,31,30,31,30,31];function Bzt(s){return s%400===0||s%4===0&&s%100!==0}function PLs(s,t,n){return t>=0&&t<=11&&n>=1&&n<=(MLs[t]||(Bzt(s)?29:28))}function ILs(s,t){return t>=1&&t<=(Bzt(s)?366:365)}function LLs(s,t,n){return t>=1&&t<=53&&n>=0&&n<=6}function RLs(s,t,n){return s===24?t===0&&n===0:n>=0&&n<60&&t>=0&&t<60&&s>=0&&s<25}function DLs(s,t){return t>=0&&t<=59}function i7e(s,t){const n=So(s),r=n.getFullYear(),a=n.getDate(),i=Mm(s,0);i.setFullYear(r,t,15),i.setHours(0,0,0,0);const l=xIs(i);return n.setMonth(t,Math.min(a,l)),n}function $zt(s,t){const n=So(s);return n.setHours(t),n}function Uzt(s,t){const n=So(s);return n.setMinutes(t),n}function zyt(s,t){const n=So(s);return isNaN(+n)?Mm(s,NaN):(n.setFullYear(t),n)}function d8(s,t){return Mv(s,-t)}const FLs=()=>{const{user:s}=vs(),t=Qn(),[n,r]=j.useState([]),[a,i]=j.useState(0),[l,o]=j.useState(!1),[c,d]=j.useState(null),u=j.useRef(null);j.useEffect(()=>{u.current=c},[c]),j.useEffect(()=>{if(!s)return;const x=`notification_last_read_${s.id}`,y=localStorage.getItem(x);y&&!u.current&&(u.current=y,d(y));const v=`nb_cache_${s.id}`,b=60*1e3,w=async()=>{try{const P=sessionStorage.getItem(v);if(P){const R=JSON.parse(P);if(R.ts&&Date.now()-R.ts{r(E);const I=u.current?new Date(u.current):null,P=E.filter(R=>I?new Date(R.created_at)>I:!0);i(P.length)};w();const C=q.channel("push-notifications").on("postgres_changes",{event:"INSERT",schema:"public",table:"push_notifications"},E=>{const I=E.new;r(R=>{const D=[I,...R].slice(0,20);try{sessionStorage.setItem(v,JSON.stringify({ts:Date.now(),data:D}))}catch{}return D});const P=u.current?new Date(u.current):null;(!P||new Date(I.created_at)>P)&&i(R=>R+1),Notification.permission==="granted"&&new Notification(I.title,{body:I.body,icon:"/favicon.ico"})}).subscribe();return()=>{q.removeChannel(C)}},[s]);const h=x=>{const y=x.toLowerCase();return y.includes("community")||y.includes("post")?eo:y.includes("academy")||y.includes("video")?ua:y.includes("template")?Yc:y.includes("event")?Ta:y.includes("newsletter")?nk:y.includes("brokerage")?Sx:y.includes("swag")||y.includes("social")?ul:y.includes("toolbox")||y.includes("tool")?F4:y.includes("brief")?Nn:eo},m=x=>{o(!1),x.url&&x.url!=="/"&&t(x.url)},f=()=>{if(!s)return;const x=new Date().toISOString(),y=`notification_last_read_${s.id}`;localStorage.setItem(y,x),d(x),i(0)},g=x=>{o(x),x&&a>0&&f()};return e.jsxs(Uu,{open:l,onOpenChange:g,children:[e.jsx(qu,{asChild:!0,children:e.jsxs($,{variant:"ghost",size:"icon",className:"relative",children:[e.jsx(qy,{className:"h-5 w-5"}),a>0&&e.jsx(Be,{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(Eu,{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"}),n.length>0&&e.jsx($,{variant:"ghost",size:"sm",className:"text-xs h-6",onClick:f,children:"Mark all read"})]}),e.jsx(uo,{className:"h-[300px]",children:n.length===0?e.jsx("div",{className:"p-4 text-center text-muted-foreground text-sm",children:"No notifications yet"}):n.map(x=>{const y=h(x.title);return e.jsxs(ja,{className:"group flex items-start gap-3 p-3 cursor-pointer data-[highlighted]:bg-accent data-[highlighted]:text-accent-foreground",onClick:()=>m(x),children:[e.jsx("div",{className:"flex-shrink-0 mt-0.5",children:e.jsx(y,{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:x.title}),e.jsx("span",{className:"text-xs text-muted-foreground line-clamp-2 group-data-[highlighted]:text-accent-foreground/80",children:x.body}),e.jsx("span",{className:"text-xs text-muted-foreground group-data-[highlighted]:text-accent-foreground/80",children:mu(new Date(x.created_at),{addSuffix:!0})})]})]},x.id)})})]})]})};function OLs(s){return s!=null&&s.length?s.find(t=>t.is_active&&t.mls_provider_id&&!t.no_mls_mode)||s[0]:null}function ng(){const{user:s}=vs(),{data:t,isLoading:n}=tt({queryKey:["agent-lead-site",s==null?void 0:s.id],queryFn:async()=>{const{data:r,error:a}=await q.from("lead_sites").select("id, subdomain_slug, custom_domain, site_title, is_active, plan_tier, mls_provider_id, no_mls_mode, mls_agent_id, mls_agent_key, mls_office_id, mls_service_cities, mls_disclaimer_text, brokerage_legal_name").eq("agent_id",s.id).eq("is_active",!0).order("created_at",{ascending:!0}).limit(10);if(a)throw a;return OLs(r)},enabled:!!s,staleTime:5*60*1e3});return{leadSite:t??null,hasLeadSite:!!t,isFreePlan:(t==null?void 0:t.plan_tier)==="free_luxury",hasIdx:!!(t!=null&&t.mls_provider_id)&&!(t!=null&&t.no_mls_mode),isLoading:n,siteUrl:t?t.custom_domain?`https://${t.custom_domain}`:`https://${t.subdomain_slug}.thelocalmove.com`:null}}function OLe(s=!0){const{user:t}=vs(),{data:n,isLoading:r}=tt({queryKey:["free-lead-site-offer",t==null?void 0:t.id],enabled:!!t&&s,staleTime:5*60*1e3,queryFn:async()=>{const{data:a}=await q.from("profiles").select("brokerage_id").eq("id",t.id).maybeSingle();if(!(a!=null&&a.brokerage_id))return null;const{data:i}=await q.from("lead_site_brokerage_offers").select("*").eq("brokerage_id",a.brokerage_id).eq("enabled",!0).maybeSingle();return i??null}});return{offer:n??null,hasOffer:!!n,isLoading:r}}const zLs="coaching_access";function qzt(){const{user:s,loading:t,isAdmin:n,isCoach:r}=vs(),{data:a,isLoading:i}=tt({queryKey:["coaching-access",s==null?void 0:s.id],enabled:!!s,staleTime:5*60*1e3,queryFn:async()=>{const[l,o]=await Promise.all([q.from("coaching_assignments").select("id").eq("agent_id",s.id).eq("status","active").limit(1),q.from("feature_entitlements").select("enabled, expires_at").eq("user_id",s.id).eq("feature_key",zLs).maybeSingle()]),c=(l.data||[]).length>0,d=o.data,u=!!(d!=null&&d.enabled)&&(!d.expires_at||new Date(d.expires_at).getTime()>Date.now());return{hasAssignment:c,entitled:u}}});return{hasAccess:!!(n||r||a!=null&&a.hasAssignment||a!=null&&a.entitled),hasAssignment:!!(a!=null&&a.hasAssignment),isLoading:t||i}}const Ou=q,PEe=[{value:"contract",label:"Under contract"},{value:"inspection",label:"Inspection / due diligence"},{value:"closing",label:"Closing"},{value:"closed",label:"Closed"}];function eGe(s){return s.total_items===0?"not_started":s.rejected_items>0?"changes_requested":s.approved_items>=s.total_items?"compliant":"in_review"}const Vzt={not_started:"Not started",in_review:"In review",changes_requested:"Changes requested",compliant:"Compliant"};function Rtt(){return tt({queryKey:["transaction-admin-seats"],queryFn:async()=>{const{data:s}=await q.auth.getUser();if(!s.user)return[];const{data:t,error:n}=await Ou.from("brokerage_transaction_admins").select("brokerage_id").eq("user_id",s.user.id);if(n)throw n;return t||[]}})}function BLs(s){return tt({queryKey:["transaction-admins",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await Ou.from("brokerage_transaction_admins").select("id, user_id, created_at").eq("brokerage_id",s);if(n)throw n;const r=t||[];if(r.length===0)return[];const{data:a}=await Ou.from("profiles").select("id, name, email").in("id",r.map(l=>l.user_id)),i=new Map((a||[]).map(l=>[l.id,{name:l.name??null,email:l.email??null}]));return r.map(l=>{var o,c;return{...l,name:((o=i.get(l.user_id))==null?void 0:o.name)??null,email:((c=i.get(l.user_id))==null?void 0:c.email)??null}})}})}function $Ls(){const s=Vt();return ft({mutationFn:async({brokerageId:t,userId:n})=>{const{error:r}=await Ou.from("brokerage_transaction_admins").insert({brokerage_id:t,user_id:n});if(r)throw r},onSuccess:(t,n)=>s.invalidateQueries({queryKey:["transaction-admins",n.brokerageId]})})}function ULs(){const s=Vt();return ft({mutationFn:async({id:t})=>{const{error:n}=await Ou.from("brokerage_transaction_admins").delete().eq("id",t);if(n)throw n},onSuccess:(t,n)=>s.invalidateQueries({queryKey:["transaction-admins",n.brokerageId]})})}function qLs(s){return tt({queryKey:["compliance-settings",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await Ou.from("brokerage_compliance_settings").select("*").eq("brokerage_id",s).maybeSingle();if(n)throw n;return t}})}function VLs(){const s=Vt();return ft({mutationFn:async t=>{const{error:n}=await Ou.from("brokerage_compliance_settings").upsert(t,{onConflict:"brokerage_id"});if(n)throw n},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["compliance-settings",n.brokerage_id]}),s.invalidateQueries({queryKey:["compliance-deals"]})}})}function Hzt(s){return tt({queryKey:["compliance-templates",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await Ou.from("brokerage_checklist_templates").select("*").eq("brokerage_id",s).order("created_at",{ascending:!0});if(n)throw n;return t||[]}})}function HLs(s){return tt({queryKey:["compliance-template-items",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await Ou.from("brokerage_checklist_template_items").select("*").eq("template_id",s).order("sort_order",{ascending:!0});if(n)throw n;return t||[]}})}function GLs(){const s=Vt();return ft({mutationFn:async t=>{if(t.id){const{error:a}=await Ou.from("brokerage_checklist_templates").update(t).eq("id",t.id);if(a)throw a;return t.id}const{data:n,error:r}=await Ou.from("brokerage_checklist_templates").insert(t).select("id").single();if(r)throw r;return n.id},onSuccess:(t,n)=>s.invalidateQueries({queryKey:["compliance-templates",n.brokerage_id]})})}function WLs(){const s=Vt();return ft({mutationFn:async({id:t})=>{const{error:n}=await Ou.from("brokerage_checklist_templates").delete().eq("id",t);if(n)throw n},onSuccess:(t,n)=>s.invalidateQueries({queryKey:["compliance-templates",n.brokerageId]})})}function KLs(){const s=Vt();return ft({mutationFn:async t=>{if(t.id){const{error:r}=await Ou.from("brokerage_checklist_template_items").update(t).eq("id",t.id);if(r)throw r;return}const{error:n}=await Ou.from("brokerage_checklist_template_items").insert(t);if(n)throw n},onSuccess:(t,n)=>s.invalidateQueries({queryKey:["compliance-template-items",n.template_id]})})}function YLs(){const s=Vt();return ft({mutationFn:async({id:t})=>{const{error:n}=await Ou.from("brokerage_checklist_template_items").delete().eq("id",t);if(n)throw n},onSuccess:(t,n)=>s.invalidateQueries({queryKey:["compliance-template-items",n.templateId]})})}function Dtt(s){return tt({queryKey:["compliance-deals",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await Ou.rpc("get_brokerage_compliance_deals",{_brokerage_id:s});if(n)throw n;return t||[]}})}function Gzt(s){return tt({queryKey:["deal-compliance-items",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await Ou.from("deal_compliance_items").select("*").eq("deal_id",s).order("sort_order",{ascending:!0});if(n)throw n;return t||[]}})}function ZLs(s){return tt({queryKey:["deal-compliance-events",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await Ou.from("deal_compliance_events").select("*").eq("deal_id",s).order("created_at",{ascending:!1}).limit(200);if(n)throw n;return t||[]}})}async function zLe(s){var n;const{data:t}=await q.auth.getUser();await Ou.from("deal_compliance_events").insert({deal_id:s.dealId,brokerage_id:s.brokerageId??null,item_id:s.itemId??null,actor_user_id:((n=t.user)==null?void 0:n.id)??null,event_type:s.eventType,detail:s.detail??null})}function XLs(){const s=Vt();return ft({mutationFn:async({item:t,status:n,note:r})=>{var l;const{data:a}=await q.auth.getUser(),{error:i}=await Ou.from("deal_compliance_items").update({status:n,review_note:r??null,reviewed_by:((l=a.user)==null?void 0:l.id)??null,reviewed_at:new Date().toISOString()}).eq("id",t.id);if(i)throw i;await zLe({dealId:t.deal_id,brokerageId:t.brokerage_id,itemId:t.id,eventType:n==="approved"?"item_approved":n==="rejected"?"item_rejected":"item_updated",detail:r?`${t.title}: ${r}`:t.title})},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["deal-compliance-items",n.item.deal_id]}),s.invalidateQueries({queryKey:["deal-compliance-events",n.item.deal_id]}),s.invalidateQueries({queryKey:["compliance-deals"]})}})}function QLs(){const s=Vt();return ft({mutationFn:async({dealId:t,brokerageId:n,templateId:r,deal:a})=>{const{data:i,error:l}=await Ou.from("brokerage_checklist_template_items").select("*").eq("template_id",r).order("sort_order",{ascending:!0});if(l)throw l;const o=(u,h)=>{if(!u)return null;const[m,f,g]=u.split(/[-/T]/).map(Number);return new Date(Date.UTC(m,f-1,g+(h||0))).toISOString().slice(0,10)},c=(i||[]).map(u=>({deal_id:t,brokerage_id:n,template_item_id:u.id,title:u.title,description:u.description,phase:u.phase,requires_document:u.requires_document,required_for_closing:u.required_for_closing,due_date:u.due_anchor==="contract_date"?o(a==null?void 0:a.contract_date,u.due_offset_days):u.due_anchor==="target_close_date"?o(a==null?void 0:a.target_close_date,u.due_offset_days):null,sort_order:u.sort_order}));if(c.length===0)return;const{error:d}=await Ou.from("deal_compliance_items").insert(c);if(d)throw d;await zLe({dealId:t,brokerageId:n,eventType:"checklist_applied",detail:`${c.length} items added`})},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["deal-compliance-items",n.dealId]}),s.invalidateQueries({queryKey:["deal-compliance-events",n.dealId]}),s.invalidateQueries({queryKey:["compliance-deals"]})}})}function JLs(s){return tt({queryKey:["deal-compliance-files",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await Ou.from("deal_files").select("id, deal_id, compliance_item_id, file_name, file_size, storage_path, version_no, is_current, created_at, owner_user_id").eq("deal_id",s).not("compliance_item_id","is",null).order("version_no",{ascending:!1});if(n)throw n;return t||[]}})}function e6s(){const s=Vt();return ft({mutationFn:async({item:t,file:n})=>{var h,m;const{data:r}=await q.auth.getUser(),a=(h=r.user)==null?void 0:h.id;if(!a)throw new Error("Not signed in");const{data:i}=await Ou.from("deal_files").select("id, version_no").eq("compliance_item_id",t.id).order("version_no",{ascending:!1}).limit(1),l=(((m=i==null?void 0:i[0])==null?void 0:m.version_no)||0)+1,o=n.name.split(".").pop(),c=`${a}/${t.deal_id}/${crypto.randomUUID()}.${o}`,{error:d}=await q.storage.from("deal-files").upload(c,n);if(d)throw d;i!=null&&i.length&&await Ou.from("deal_files").update({is_current:!1}).eq("compliance_item_id",t.id);const{error:u}=await Ou.from("deal_files").insert({deal_id:t.deal_id,owner_user_id:a,file_name:n.name,file_size:n.size,file_type:n.type||null,storage_path:c,compliance_item_id:t.id,version_no:l,is_current:!0});if(u)throw u;await Ou.from("deal_compliance_items").update({status:"submitted",review_note:null,reviewed_at:null,reviewed_by:null}).eq("id",t.id),await zLe({dealId:t.deal_id,brokerageId:t.brokerage_id,itemId:t.id,eventType:"document_uploaded",detail:`${t.title} — ${n.name} (v${l})`})},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["deal-compliance-files",n.item.deal_id]}),s.invalidateQueries({queryKey:["deal-compliance-items",n.item.deal_id]}),s.invalidateQueries({queryKey:["deal-compliance-events",n.item.deal_id]}),s.invalidateQueries({queryKey:["deal-files",n.item.deal_id]}),s.invalidateQueries({queryKey:["compliance-deals"]})}})}async function Byt(s){const{data:t,error:n}=await q.storage.from("deal-files").createSignedUrl(s,3600);if(n)throw n;window.open(t.signedUrl,"_blank","noopener,noreferrer")}function t6s(s){return tt({queryKey:["deal-compliance-messages",s],enabled:!!s,refetchInterval:3e4,queryFn:async()=>{const{data:t,error:n}=await Ou.from("deal_compliance_messages").select("*").eq("deal_id",s).order("created_at",{ascending:!0});if(n)throw n;const r=t||[],a=Array.from(new Set(r.map(o=>o.sender_user_id)));if(a.length===0)return r;const{data:i}=await Ou.from("profiles").select("id, name").in("id",a),l=new Map((i||[]).map(o=>[o.id,o.name??null]));return r.map(o=>({...o,sender_name:l.get(o.sender_user_id)??null}))}})}function s6s(){const s=Vt();return ft({mutationFn:async({dealId:t,brokerageId:n,body:r,senderRole:a,itemId:i})=>{var u;const{data:l}=await q.auth.getUser(),o=(u=l.user)==null?void 0:u.id;if(!o)throw new Error("Not signed in");const{data:c,error:d}=await Ou.from("deal_compliance_messages").insert({deal_id:t,brokerage_id:n,sender_user_id:o,sender_role:a,item_id:i??null,body:r.trim()}).select("id").single();if(d)throw d;try{await q.functions.invoke("compliance-message-notify",{body:{messageId:c.id}})}catch(h){console.error("compliance message notify failed",h)}return c.id},onSuccess:(t,n)=>s.invalidateQueries({queryKey:["deal-compliance-messages",n.dealId]})})}function n6s(){const s=Vt();return ft({mutationFn:async({dealId:t,senderRole:n})=>{const{error:r}=await Ou.from("deal_compliance_messages").update({read_at:new Date().toISOString()}).eq("deal_id",t).neq("sender_role",n).is("read_at",null);if(r)throw r},onSuccess:(t,n)=>s.invalidateQueries({queryKey:["deal-compliance-messages",n.dealId]})})}function r6s(s){return tt({queryKey:["brokerage-agent-roster",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await Ou.from("profiles").select("id, name, email, avatar_url").eq("brokerage_id",s).order("name",{ascending:!0});if(n)throw n;return t||[]}})}function a6s(s){return tt({queryKey:["agent-pipeline-stages",s],enabled:!!s,queryFn:async()=>{const t=async()=>{const{data:r,error:a}=await Ou.from("deal_pipeline_stages").select("id, name, sort_order, default_probability").eq("owner_user_id",s).order("sort_order",{ascending:!0});if(a)throw a;return r||[]};let n=await t();if(n.length===0){const{error:r}=await Ou.rpc("initialize_deal_pipeline_stages",{p_user_id:s});r||(n=await t())}return n}})}function i6s(){const s=Vt();return ft({mutationFn:async t=>{const n=t.price!=null&&t.commissionPercentage!=null?Math.round(t.price*(t.commissionPercentage/100)*100)/100:null,{data:r,error:a}=await Ou.from("deal_pipeline").insert({owner_user_id:t.ownerUserId,deal_name:t.dealName.trim(),deal_type:t.dealType,stage_id:t.stageId,property_address:t.propertyAddress||null,city:t.city||null,state:t.state||null,zip_code:t.zipCode||null,contract_date:t.contractDate||null,target_close_date:t.targetCloseDate||null,actual_close_date:t.actualCloseDate||null,expected_price:t.price??null,sale_price:t.actualCloseDate?t.price??null:null,commission_percentage:t.commissionPercentage??null,expected_commission:n,notes:t.notes||null}).select("id").single();if(a)throw a;const i=r.id;try{await Ou.rpc("ensure_deal_compliance",{_deal_id:i})}catch(l){console.error("ensure_deal_compliance failed",l)}return await zLe({dealId:i,brokerageId:t.brokerageId,eventType:"deal_added_by_staff",detail:"Deal added by brokerage staff for the agent's pipeline"}),i},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["compliance-deals",n.brokerageId]}),s.invalidateQueries({queryKey:["deal-pipeline"]})}})}const BLe=[{id:"home",label:"Home",icon:YI,route:"/dashboard",accent:"nav-home"},{id:"crm",label:"CRM",icon:Jo,description:"Contacts and follow-up",accent:"nav-crm"},{id:"deals",label:"Deals",icon:h2,description:"Pipeline, transactions and tasks",accent:"nav-deals"},{id:"listings",label:"Listings",icon:ji,description:"Win and market listings",accent:"nav-listings"},{id:"marketing",label:"Marketing",icon:xm,description:"Content, email and video",accent:"nav-marketing"},{id:"websites",label:"Websites",icon:dl,description:"Your site and add-ons",accent:"nav-websites"},{id:"academy",label:"Learn",icon:of,description:"Training, programs and coaching",accent:"nav-academy"},{id:"events",label:"Events",icon:a7,route:"/events",accent:"nav-events"},{id:"apps",label:"Apps",icon:Uj,route:"/apps",accent:"nav-apps"},{id:"team",label:"Team",icon:Zn,route:"/team",description:"Your team hub — production, pond and resources",accent:"nav-team",visible:s=>s.isOnTeam&&!s.isAdmin&&!s.isBrokerageManager},{id:"brokerage",label:"Brokerage",icon:qq,description:"Your brokerage, teams and recruiting",accent:"nav-brokerage",visible:s=>!s.isAdmin&&(!!s.brokerageId||s.isBrokerageManager||s.isOnTeam)},{id:"more",label:"More",icon:h_,description:"Community, marketplace and help",accent:"nav-more"}],Q1=s=>t=>t.hasPermission(s),o6s=[{id:"mission-control",label:"Mission Control",route:"/mission-control",icon:M4,description:"Your daily relationship command center",primaryCategory:"crm",section:"Overview",visible:Q1("contacts"),searchKeywords:["agent os","mission control","dashboard"],displayOrder:10},{id:"client-portals",label:"Client Portals",route:"/mission-control/client-portals",icon:Nn,description:"Private portals for buyers and sellers",primaryCategory:"crm",section:"Overview",searchKeywords:["portal","client portal"],displayOrder:20},{id:"contacts",label:"All Contacts",route:"/mission-control/contacts",icon:Zn,description:"Every contact in your database",primaryCategory:"crm",section:"Contacts",visible:Q1("contacts"),searchKeywords:["contacts","database","sphere","people"],displayOrder:30},{id:"relationship-report",label:"Relationship Report",route:"/mission-control/relationship-scorecard",icon:af,description:"See who needs attention next",primaryCategory:"crm",section:"Contacts",visible:Q1("contacts"),searchKeywords:["relationship","scorecard","report"],displayOrder:40},{id:"sphere-gaps",label:"Sphere Gaps",route:"/mission-control/sphere-gaps",icon:rV,description:"Find missing info across your sphere",primaryCategory:"crm",section:"Contacts",visible:Q1("contacts"),searchKeywords:["gaps","missing data"],displayOrder:50},{id:"sent-emails",label:"Sent Emails",route:"/mission-control/sent-emails",icon:Yr,description:"History of everything you have sent",primaryCategory:"crm",section:"Contacts",visible:Q1("contacts"),searchKeywords:["sent","email history"],displayOrder:60},{id:"connect-page",label:"Connect Page",route:"/mission-control/connect-page",icon:bd,description:"Your shareable intake and link page",primaryCategory:"crm",section:"Contacts",visible:Q1("contacts"),searchKeywords:["connect","link in bio","intake"],displayOrder:70},{id:"property-intelligence",label:"Property Intelligence",route:"/mission-control/property-intelligence",icon:ji,description:"Enrich property data for your contacts",primaryCategory:"crm",section:"Contacts",visible:s=>s.isAdmin,searchKeywords:["property","zillow","enrichment","intelligence","home value"],displayOrder:75},{id:"touchplans",label:"TouchPlans",route:"/mission-control/plans",icon:Kc,description:"Structured touch plans for your people",primaryCategory:"crm",section:"Follow-Up",visible:Q1("contacts"),searchKeywords:["touch plan","follow up plan"],displayOrder:80},{id:"smart-drips",label:"Smart Drips",route:"/mission-control/smart-drips",icon:eg,description:"Automated drip campaigns that pause when they reply",primaryCategory:"crm",section:"Follow-Up",badge:"beta",searchKeywords:["drip","automation","campaign"],displayOrder:90},{id:"email-templates",label:"Email Templates",route:"/email-campaigns/templates",icon:mn,description:"Reusable email templates",primaryCategory:"crm",section:"Follow-Up",searchKeywords:["email template"],displayOrder:100},{id:"signals",label:"Signals",route:"/mission-control/signals",icon:Qq,description:"Buying and selling signals from your database",primaryCategory:"crm",section:"Follow-Up",searchKeywords:["signals","intent","hot leads"],displayOrder:110},{id:"popbys",label:"Popbys",route:"/mission-control/popbys",icon:ul,description:"Plan and log in-person pop-bys",primaryCategory:"crm",section:"Follow-Up",visible:Q1("popbys"),searchKeywords:["pop by","gifts","drop off"],displayOrder:120},{id:"pipeline",label:"Deal Pipeline",route:"/mission-control/pipeline",icon:h2,description:"Track every deal from lead to close",primaryCategory:"deals",section:"Pipeline",visible:Q1("pipeline"),searchKeywords:["pipeline","deals","kanban"],displayOrder:130},{id:"transactions",label:"Transactions",route:"/mission-control/transactions",icon:JN,description:"Closed and in-progress transactions",primaryCategory:"deals",section:"Pipeline",visible:Q1("pipeline"),searchKeywords:["transactions","closings"],displayOrder:140},{id:"forms",label:"Forms Library",route:"/mission-control/forms",icon:m_,description:"Your PDF form templates, filled from any deal",primaryCategory:"deals",section:"Pipeline",visible:Q1("pipeline"),searchKeywords:["forms","pdf","templates","contracts","documents"],displayOrder:145},{id:"tasks",label:"Tasks",route:"/mission-control/tasks",icon:Kj,description:"Everything on your plate today",primaryCategory:"deals",section:"Pipeline",visible:Q1("pipeline"),searchKeywords:["tasks","to do"],displayOrder:150},{id:"scorecard",label:"Scorecard",route:"/mission-control/scorecard",icon:Wl,description:"Your production numbers at a glance",primaryCategory:"deals",section:"Pipeline",visible:Q1("scorecard"),searchKeywords:["scorecard","production","goals"],displayOrder:160},{id:"my-calendar",label:"My Calendar",route:"/mission-control/calendar",icon:Kc,description:"Every appointment, deadline and task in one view",primaryCategory:"crm",section:"Overview",visible:()=>!0,searchKeywords:["calendar","schedule","agenda","google calendar","my calendar"],displayOrder:24},{id:"scheduler",label:"LevelUp Scheduler",route:"/mission-control/scheduler",icon:Kc,description:"Share your booking link and sync your calendar",primaryCategory:"crm",section:"Overview",toolId:"scheduler",visible:()=>!0,searchKeywords:["scheduler","booking","calendar","appointments"],displayOrder:25},{id:"listing-exchange",label:"Listing Exchange",route:"/mission-control/listings",icon:ji,description:"Publish and browse member listings",primaryCategory:"listings",section:"Manage Listings",visible:Q1("listings"),searchKeywords:["listings","exchange","my listings"],displayOrder:10},{id:"listing-presentation-studio",label:"Listing Presentation Studio",route:"/apps/listing-presentation-studio",icon:jb,description:"Build a polished listing presentation PDF",primaryCategory:"listings",section:"Win the Listing",toolId:"listing-presentation-studio",searchKeywords:["listing presentation","pdf","pitch"],displayOrder:20},{id:"listing-revival",label:"Listing Revival",route:"/apps/listing-revival",icon:nh,description:"Win expired and withdrawn listings",primaryCategory:"listings",section:"Win the Listing",toolId:"listing-revival",searchKeywords:["expired","revival","withdrawn"],displayOrder:30},{id:"fsbo-breakthrough",label:"By-Owner Breakthrough",route:"/apps/fsbo-breakthrough",icon:va,description:"Convert for-sale-by-owner sellers",primaryCategory:"listings",section:"Win the Listing",toolId:"fsbo-breakthrough",searchKeywords:["fsbo","by owner"],displayOrder:40},{id:"cma",label:"CMA Reports",route:"/mission-control/cma",icon:c2,description:"Comparative market analysis for sellers",primaryCategory:"listings",section:"Win the Listing",toolId:"cma",visible:s=>s.hasLeadSiteMLS,searchKeywords:["cma","market analysis","pricing"],displayOrder:50},{id:"guest-book",label:"Guest Book",route:"/mission-control/guest-book",icon:JN,description:"Digital open house sign-in",primaryCategory:"listings",section:"Open Houses",toolId:"guest-book",searchKeywords:["open house","sign in","guest book"],displayOrder:60},{id:"listing-studio",label:"Listing Studio",route:"/mission-control/listing-studio",icon:Mc,description:"Marketing assets for a listing",primaryCategory:"listings",section:"Market the Listing",toolId:"listing-studio",searchKeywords:["listing marketing","flyer","just listed"],displayOrder:70},{id:"templates",label:"Templates",route:"/templates",icon:Yc,description:"Ready-to-edit Canva templates",primaryCategory:"marketing",section:"Create",searchKeywords:["templates","canva","graphics"],displayOrder:10},{id:"staging-studio",label:"Staging Studio",route:"/apps/staging-studio",icon:iV,description:"Virtually stage, declutter and brighten listing photos",primaryCategory:"marketing",section:"Create",toolId:"staging-studio",visible:s=>s.isAdmin||s.stagingStudioEnabled,searchKeywords:["staging","virtual staging","twilight","declutter","sky replacement","photo"],displayOrder:11},{id:"reviews",label:"Reviews",route:"/apps/reviews",icon:Ja,description:"Collect, showcase and reply to client reviews",primaryCategory:"marketing",section:"Create",searchKeywords:["reviews","agent reviews","google reviews","testimonials","reputation","review link","review page","ratings","video review"],displayOrder:12},{id:"marketing-studio",label:"Marketing Studio",route:"/marketing-studio",icon:Mc,description:"Create branded marketing assets",primaryCategory:"marketing",section:"Create",searchKeywords:["marketing studio","design","brand kit"],displayOrder:20},{id:"social-studio",label:"Social Studio",route:"/social-studio",icon:_1,description:"Post to all your social accounts from one composer",primaryCategory:"marketing",section:"Social & Content",searchKeywords:["social","posts","instagram","facebook","linkedin","google business","schedule","swag"],displayOrder:29},{id:"social-swag",label:"Social Swag",route:"/social-swag-2",icon:_1,description:"Daily social posts you can publish in a tap",primaryCategory:"marketing",section:"Social & Content",searchKeywords:["social","posts","instagram","facebook"],displayOrder:30},{id:"weekly-reels",label:"Weekly Reels",route:"/weekly-reels",icon:rf,description:"A fresh reel script every Monday",primaryCategory:"marketing",section:"Social & Content",toolId:"weekly-reels",visible:s=>s.hasWeeklyReels,searchKeywords:["reels","video script","instagram"],displayOrder:40},{id:"newsletter-pro",label:"Newsletter Pro",route:"/newsletters",icon:nk,description:"Send a branded monthly newsletter",primaryCategory:"marketing",section:"Email & Mail",badge:"new",toolId:"newsletter-pro",searchKeywords:["newsletter","email marketing"],displayOrder:50},{id:"mass-emails",label:"Mass Emails",route:"/admin/email-campaigns",icon:mn,description:"Email your whole database at once",primaryCategory:"marketing",section:"Email & Mail",toolId:"mass-emails",searchKeywords:["mass email","campaign","blast"],displayOrder:60},{id:"direct-mail",label:"Mail Studio (beta)",route:"/mission-control/direct-mail",icon:Yr,description:"Postcards & letters via your thanks.io account",primaryCategory:"marketing",section:"Email & Mail",visible:s=>s.isAdmin,toolId:"direct-mail",searchKeywords:["postcard","direct mail","farming","letter","thanks.io","mail studio"],displayOrder:70},{id:"card-studio",label:"Card Studio",route:"/mission-control/card-studio",icon:ul,description:"Send digital celebration cards",primaryCategory:"marketing",section:"Email & Mail",toolId:"card-studio",searchKeywords:["cards","birthday","anniversary"],displayOrder:80},{id:"video-library",label:"Video Library",route:"/mission-control/video-library",icon:ua,description:"All of your recorded videos",primaryCategory:"marketing",section:"Video",visible:Q1("videos"),searchKeywords:["videos","library"],displayOrder:90},{id:"quickvid",label:"QuickVid",route:"/mission-control/video/record",icon:ua,description:"Record a personalized video in seconds",primaryCategory:"marketing",section:"Video",toolId:"quickvid",searchKeywords:["record video","video email","screen record"],displayOrder:100},{id:"reelflow",label:"ReelFlow",route:"/admin/beta/homereel",icon:rf,description:"AI-assisted short-form video creation",primaryCategory:"marketing",section:"Video",toolId:"reelflow",searchKeywords:["reelflow","ai video","reels"],displayOrder:110},{id:"landing-pages",label:"Landing Pages",route:"/mission-control/landing-pages",icon:qg,description:"Capture leads with focused landing pages",primaryCategory:"marketing",section:"Lead Capture",toolId:"landing-pages",searchKeywords:["landing page","lead capture","funnel"],displayOrder:120},{id:"buyer-match",label:"Buyer Match",route:"/mission-control/buyer-match",icon:wb,description:"Turn a buyer's wish list into seller conversations",primaryCategory:"marketing",section:"Lead Capture",searchKeywords:["buyer match","buyer needs","seller leads","wish list"],displayOrder:125},{id:"smart-card",label:"Smart Card",route:"/mission-control/my-card",icon:bd,description:"Your digital business card",primaryCategory:"marketing",section:"Lead Capture",toolId:"smart-card",searchKeywords:["digital card","business card","qr"],displayOrder:130},{id:"my-websites",label:"My Websites",route:"/websites",icon:Qf,description:"Every site you can edit: yours, your company and your team",primaryCategory:"websites",section:"My Website",visible:s=>s.hasLeadSite||s.isBrokerageManager||s.isTeamLeader||s.isAdmin,searchKeywords:["websites","my sites","edit website","company site","team site"],displayOrder:1},{id:"get-my-website",label:"Get My Website",route:"/get-my-website",icon:dl,description:"Claim the free site your brokerage offers",primaryCategory:"websites",section:"My Website",visible:s=>!s.hasLeadSite&&s.hasFreeSiteOffer,searchKeywords:["website","claim site","free site"],displayOrder:5},{id:"need-a-website",label:"Need a Website",route:"/need-a-website",icon:dl,description:"Request your free beta agent website",primaryCategory:"websites",section:"My Website",badge:"beta",visible:s=>!s.hasLeadSite&&!s.hasFreeSiteOffer,searchKeywords:["website","need a website","beta site","free website"],displayOrder:6},{id:"view-site",label:"View Site",route:s=>s.siteUrl||"#",icon:Ca,description:"Open your live website",primaryCategory:"websites",section:"My Website",external:!0,openInNewTab:!0,visible:s=>s.hasLeadSite&&!!s.siteUrl,searchKeywords:["view site","live site"],displayOrder:10},{id:"edit-website",label:"Edit My Site",route:s=>`/my-website/${s.leadSiteId}/edit`,icon:gi,description:"Site builder for pages, branding and content",primaryCategory:"websites",section:"My Website",visible:s=>s.hasLeadSite&&!!s.leadSiteId,searchKeywords:["edit website","site builder","pages"],displayOrder:20},{id:"brokerage-website",label:"Edit Company Site",route:"/brokerage/website",icon:ji,description:"Your company site: agents, listings, recruiting and leads",primaryCategory:"websites",section:"My Website",badge:"new",visible:s=>s.isBrokerageManager||s.isAdmin,searchKeywords:["website","company site","brokerage site","agents","roster"],displayOrder:24},{id:"team-website",label:"Edit Team Site",route:"/team/website",icon:Zn,description:"Your team site: members, listings and leads",primaryCategory:"websites",section:"My Website",badge:"new",visible:s=>s.isTeamLeader||s.isAdmin,searchKeywords:["team website","team site","team page"],displayOrder:26},{id:"mls-listings",label:"MLS Listings",route:"/my-website/mls-listings",icon:va,description:"Control which listings appear on your site",primaryCategory:"websites",section:"My Website",visible:s=>s.hasLeadSite,searchKeywords:["mls","idx","listings on site"],displayOrder:30},{id:"market-reports",label:"Market Reports",route:"/my-website/market-report",icon:Wl,description:"Monthly market reports for your areas",primaryCategory:"websites",section:"My Website",visible:s=>s.hasLeadSite&&s.hasLeadSiteMLS,searchKeywords:["market report","stats"],displayOrder:40},{id:"website-activity",label:"Website Activity",route:"/mission-control/website-activity",icon:af,description:"See who is browsing your site",primaryCategory:"websites",section:"My Website",visible:s=>s.hasLeadSite,searchKeywords:["website activity","visitors","analytics"],displayOrder:50},{id:"mobile-command",label:"Mobile Command",route:"/m",icon:_1,description:"The mobile-first agent console",primaryCategory:"websites",section:"My Website",visible:s=>s.hasLeadSite,searchKeywords:["mobile","command"],displayOrder:60},{id:"website-apps",label:"Website Apps",route:"/website-apps",icon:Nn,description:"Lead magnets, video greeter and more",primaryCategory:"websites",section:"Website Add-Ons",toolId:"website-apps",searchKeywords:["widgets","lead magnet","video greeter"],displayOrder:70},{id:"levelup-u",label:"LevelUp U",route:"/levelup-u",icon:of,description:"Structured courses and certifications",primaryCategory:"academy",section:"Learn",badge:"new",searchKeywords:["levelup u","courses","training"],displayOrder:10},{id:"academy",label:"Academy",route:"/academy",icon:Xf,description:"On-demand training videos",primaryCategory:"academy",section:"Learn",searchKeywords:["academy","videos","training"],displayOrder:20},{id:"toolbox",label:"Toolbox",route:"/toolbox",icon:F4,description:"Scripts, checklists and downloads",primaryCategory:"academy",section:"Learn",searchKeywords:["toolbox","scripts","downloads"],displayOrder:30},{id:"events",label:"Events",route:"/events",icon:a7,description:"Live trainings and member events",primaryCategory:"events",section:"Events",searchKeywords:["events","live","webinar"],displayOrder:10},{id:"programs",label:"Programs",route:"/programs",icon:qg,description:"Cohort programs like Reel Estate 90",primaryCategory:"academy",section:"Programs & Coaching",searchKeywords:["programs","reel estate 90","cohort"],displayOrder:50},{id:"coaching",label:"Coaching",route:"/coaching",icon:of,description:"Your coaching hub and calendar",primaryCategory:"academy",section:"Programs & Coaching",visible:s=>s.isCoach,searchKeywords:["coaching","coach hub"],displayOrder:60},{id:"my-coach",label:"Coaching",route:"/my-coach",icon:Jo,description:"Sessions, goals and notes with your coach",primaryCategory:"academy",section:"Programs & Coaching",visible:s=>!s.isCoach&&(s.hasCoach||s.hasCoachingAccess),searchKeywords:["my coach","coaching","sessions","book session"],displayOrder:70},{id:"community",label:"Community",route:"/community",icon:eo,description:"Talk shop with other LevelUp members",primaryCategory:"more",section:"Community",badgeKey:"community",searchKeywords:["community","forum","posts"],displayOrder:10},{id:"wishlist",label:"Wishlist",route:"/wishlist",icon:tC,description:"Request and vote on new features",primaryCategory:"more",section:"Community",badgeKey:"wishlist",searchKeywords:["wishlist","feature request"],displayOrder:20},{id:"facebook-group",label:"Facebook Group",route:"https://www.facebook.com/share/g/1CC6thti2V/",icon:kr,description:"Our private Facebook community",primaryCategory:"more",section:"Community",external:!0,openInNewTab:!0,searchKeywords:["facebook group"],displayOrder:30},{id:"marketplace",label:"Marketplace",route:"/marketplace",icon:oV,description:"Print and promo products",primaryCategory:"more",section:"The Goods",badge:"new",visible:s=>s.isMarketplaceEnabled,searchKeywords:["marketplace","shop","print"],displayOrder:40},{id:"reward-store",label:"Reward Store",route:"/reward-store",icon:Kl,description:"Spend the points you have earned",primaryCategory:"more",section:"The Goods",searchKeywords:["rewards","points","store"],displayOrder:50},{id:"refer-friends",label:"Refer & Earn",route:"/refer-friends",icon:ul,description:"Invite agents and earn rewards",primaryCategory:"more",section:"The Goods",searchKeywords:["referral","refer a friend"],displayOrder:60},{id:"support",label:"Support",route:"/support",icon:Vq,description:"Get help from the LevelUp team",primaryCategory:"more",section:"Help & Services",searchKeywords:["support","help","ticket"],displayOrder:70},{id:"additional-services",label:"Additional Services",route:"/additional-services",icon:Nn,description:"Done-for-you services from LevelUp",primaryCategory:"more",section:"Help & Services",searchKeywords:["services","done for you"],displayOrder:80},{id:"integrations",label:"Integrations",route:"/mission-control/integrations",icon:g2,description:"Connect your CRM, calendar and socials",primaryCategory:"more",section:"Help & Services",searchKeywords:["integrations","connect","crm sync"],displayOrder:90},{id:"browser-extension",label:"Browser Extension",route:"/mission-control/browser-extension",icon:g2,description:"Install the LevelUp Chrome extension",primaryCategory:"more",section:"Help & Services",searchKeywords:["extension","chrome"],displayOrder:100},{id:"attract",label:"LevelUp Attract",route:"/attract",icon:Nn,description:"Relationship-first attraction coach",primaryCategory:"more",section:"Help & Services",badge:"beta",visible:s=>s.email==="jeremy@relevelup.com",searchKeywords:["attract","recruiting"],displayOrder:110},{id:"admin-dashboard",label:"Admin Dashboard",route:"/admin",icon:pc,description:"Manage members, content and settings",primaryCategory:"more",section:"Admin",visible:s=>s.isAdmin,searchKeywords:["admin"],displayOrder:120},{id:"agent-activation",label:"Agent Activation",route:"/admin/agent-activation",icon:eg,description:"Wake up dormant agents with branded email sequences",primaryCategory:"more",section:"Admin",visible:s=>s.isAdmin,searchKeywords:["activation","dormant","adoption","agents"],displayOrder:121},{id:"my-brokerage",label:"My Brokerage",route:"/my-brokerage",icon:ji,description:"Your brokerage hub",primaryCategory:"brokerage",section:"My Brokerage",visible:s=>!!s.brokerageId&&!s.isAdmin,searchKeywords:["brokerage"],displayOrder:130},{id:"help-board",label:"Help Board",route:"/brokerage/help-board",icon:r4,description:"Ask for showing and open house coverage",primaryCategory:"brokerage",section:"My Brokerage",visible:s=>!!s.brokerageId&&!s.isAdmin,searchKeywords:["help board","coverage"],displayOrder:140},{id:"brokerage-content",label:"Brokerage Content",route:"/brokerage-content",icon:Xf,description:"Content shared by your brokerage",primaryCategory:"brokerage",section:"My Brokerage",visible:s=>!!s.brokerageId&&!s.isAdmin,searchKeywords:["brokerage content"],displayOrder:150},{id:"team-hub",label:"Team Hub",route:"/team",icon:Zn,description:"Production, leaderboard, pond and resources for your team",primaryCategory:"team",section:"My Team",searchKeywords:["team","leaderboard","production","team hub","standing"],displayOrder:155},{id:"my-team",label:"My Team",route:"/my-team",icon:Zn,description:"Your team roster and lead pond",primaryCategory:"brokerage",section:"My Team",visible:s=>s.isOnTeam&&!s.isBrokerageManager&&!s.isAdmin,searchKeywords:["team","lead pond"],displayOrder:160},{id:"manage-brokerages",label:"Manage Brokerages",route:"/brokerage/dashboard",icon:Sd,description:"Brokerage manager dashboard",primaryCategory:"brokerage",section:"Manage Brokerage",visible:s=>s.isBrokerageManager&&!s.isAdmin,searchKeywords:["manage brokerage"],displayOrder:170},{id:"brokerage-teams",label:"Teams",route:"/brokerage/teams",icon:Zn,description:"Teams, rosters and lead ponds",primaryCategory:"brokerage",section:"Manage Brokerage",badge:"new",visible:s=>s.isBrokerageManager&&!s.isAdmin,searchKeywords:["teams","pond"],displayOrder:180},{id:"brokerage-recruiting",label:"Recruiting",route:"/brokerage/recruiting",icon:xm,description:"Recruit and nurture agents",primaryCategory:"brokerage",section:"Manage Brokerage",visible:s=>s.isBrokerageManager&&!s.isAdmin,searchKeywords:["recruiting"],displayOrder:190},{id:"brokerage-onboarding",label:"Agent Onboarding",route:"/brokerage/onboarding",icon:zg,description:"Onboarding checklists, documents and agent notes",primaryCategory:"brokerage",section:"Manage Brokerage",badge:"new",visible:s=>s.isBrokerageManager&&!s.isAdmin,searchKeywords:["onboarding","checklist","documents","new agent"],displayOrder:195},{id:"brokerage-operations",label:"Operations",route:"/brokerage/operations",icon:YI,description:"Daily action feed, office task board and brokerage calendar",primaryCategory:"brokerage",section:"Manage Brokerage",badge:"new",visible:s=>(s.isBrokerageManager||s.isTransactionAdmin)&&!s.isAdmin,searchKeywords:["operations","tasks","today","calendar","action items"],displayOrder:188},{id:"brokerage-commission-plans",label:"Financials",route:"/brokerage/commission-plans",icon:Rw,description:"Commission plans, company dollar and fee statements",primaryCategory:"brokerage",section:"Manage Brokerage",badge:"new",visible:s=>(s.isBrokerageManager||s.isTransactionAdmin)&&!s.isAdmin,searchKeywords:["commission","split","cap","fees","agent plans"],displayOrder:195},{id:"brokerage-transactions",label:"Transactions & Compliance",route:"/brokerage/transactions",icon:zg,description:"Review agent files, required documents and closing compliance",primaryCategory:"brokerage",section:"Manage Brokerage",badge:"new",visible:s=>(s.isBrokerageManager||s.isTransactionAdmin)&&!s.isAdmin,searchKeywords:["compliance","transactions","documents","closing","paperless"],displayOrder:196},{id:"brokerage-vendors",label:"Vendors",route:"/brokerage/vendors",icon:wb,description:"Preferred vendor directory",primaryCategory:"brokerage",section:"Manage Brokerage",visible:s=>s.isBrokerageManager&&!s.isAdmin,searchKeywords:["vendors"],displayOrder:200},{id:"brokerage-forms",label:"Brokerage Forms",route:"/brokerage/forms",icon:Jr,description:"Official forms your agents can use",primaryCategory:"brokerage",section:"Manage Brokerage",badge:"new",visible:s=>s.isBrokerageManager&&!s.isAdmin,searchKeywords:["forms","pdf","documents"],displayOrder:205},{id:"brokerage-resources",label:"Brokerage Resources",route:"/brokerage-resources",icon:Sx,description:"Documents and links for your agents",primaryCategory:"brokerage",section:"Manage Brokerage",visible:s=>s.isBrokerageManager&&!s.isAdmin,searchKeywords:["resources"],displayOrder:210},{id:"my-partnership",label:"My Package",route:"/my-partnership",icon:Nn,description:"What is included in your partnership package",primaryCategory:"more",section:"Account",visible:s=>s.isPartnershipMember,searchKeywords:["partnership","package","upgrade","exp luxury"],displayOrder:5},{id:"coaching-onboarding",label:"Coaching Onboarding",route:"/coaching/onboarding",icon:zg,description:"Tell your coach about your business before session one",primaryCategory:"academy",section:"Coaching",visible:s=>s.hasCoachingOnboarding,searchKeywords:["coaching","onboarding","intake"],displayOrder:45}];function Wzt(s,t){return typeof s.route=="function"?s.route(t):s.route}function Kzt(){const{user:s,isAdmin:t,isBrokerageManager:n,isCoach:r,brokerageId:a}=vs(),{hasPermission:i}=Iae(),{isInnerCircleEnabled:l,isMarketplaceEnabled:o,isFeatureEnabled:c}=Rae(),{hasAccess:d}=_Le(),{data:u,teams:h}=Hw(),{leadSite:m,hasLeadSite:f,siteUrl:g}=ng(),{hasOffer:x}=OLe(!f),y=jC(),{hasAccess:v}=qzt(),{data:b}=Rtt(),w=Vt(),{data:S}=tt({queryKey:["my-coach-nav",s==null?void 0:s.id],enabled:!!(s!=null&&s.id),staleTime:5*60*1e3,queryFn:async()=>{const{data:X}=await q.from("coaching_assignments").select("id").eq("agent_id",s.id).eq("status","active").limit(1);return(X||[]).length>0}}),{data:C}=tt({queryKey:["user-tool-favorites",s==null?void 0:s.id],enabled:!!(s!=null&&s.id),staleTime:60*1e3,queryFn:async()=>{const{data:X}=await q.from("user_tool_favorites").select("tool_id").eq("user_id",s.id);return(X||[]).map(ae=>ae.tool_id)}}),E=j.useMemo(()=>new Set(C||[]),[C]),I=ft({mutationFn:async X=>{s!=null&&s.id&&(E.has(X)?await q.from("user_tool_favorites").delete().eq("user_id",s.id).eq("tool_id",X):await q.from("user_tool_favorites").insert({user_id:s.id,tool_id:X}))},onSuccess:()=>{w.invalidateQueries({queryKey:["user-tool-favorites"]}),w.invalidateQueries({queryKey:["app-catalog"]})}}),P=j.useMemo(()=>{var X,ae;return{isAdmin:!!t,isBrokerageManager:!!n,isTransactionAdmin:((b==null?void 0:b.length)||0)>0,isCoach:!!r,isOnTeam:!!u,isTeamLeader:(h||[]).some(ie=>ie.role==="team_leader"),hasCoach:!!S,brokerageId:a??null,hasPermission:i,isInnerCircleEnabled:!!l,stagingStudioEnabled:c("staging_studio_enabled"),isMarketplaceEnabled:!!o,hasWeeklyReels:!!d,hasLeadSite:!!f,hasLeadSiteMLS:!!(m!=null&&m.mls_provider_id),hasFreeSiteOffer:!!x,leadSiteId:(m==null?void 0:m.id)??null,siteUrl:g??null,email:(s==null?void 0:s.email)??null,isPartnershipMember:y.isMember,hasCoachingOnboarding:y.isMember&&!!((X=y.pkg)!=null&&X.includes_coaching),hasCoachingAccess:!!v||y.isMember&&!!((ae=y.pkg)!=null&&ae.includes_coaching)}},[t,n,b,r,u,h,S,a,i,l,o,c,d,f,m,x,g,s==null?void 0:s.email,y.isMember,y.pkg,v]),R=j.useMemo(()=>o6s.filter(X=>X.visible?X.visible(P):!0).map(X=>{if(!y.isRestricted)return X;const ae=OCs(X);return!ae||y.hasFeature(ae)?X:{...X,locked:!0,route:`/upgrade/${ae}`}}).sort((X,ae)=>X.displayOrder-ae.displayOrder),[P,y.isRestricted,y.features]),D=j.useMemo(()=>BLe.filter(X=>X.visible?X.visible(P):!0),[P]),O=j.useMemo(()=>D.filter(X=>!X.route).map(X=>{const ae=R.filter(te=>te.primaryCategory===X.id),ie=[],ne=new Map;for(const te of ae)ne.has(te.section)||(ne.set(te.section,[]),ie.push(te.section)),ne.get(te.section).push(te);return{id:X.id,label:X.label,sections:ie.map(te=>({title:te,items:ne.get(te)}))}}),[R,D]),U=j.useMemo(()=>new Map(O.map(X=>[X.id,X])),[O]),W=X=>X.toolId||`nav:${X.id}`,V=X=>E.has(W(X));return{ctx:P,categories:O,railCategories:D,categoryMap:U,destinations:R,favorites:E,isFavorite:V,favoritesFor:X=>R.filter(ae=>ae.primaryCategory===X&&V(ae)),favoriteKey:W,toggleFavorite:X=>I.mutate(X),searchDestinations:X=>{const ae=X.trim().toLowerCase();return ae?R.map(ne=>{const te=ne.label.toLowerCase(),J=(ne.description||"").toLowerCase(),ce=(ne.searchKeywords||[]).join(" ").toLowerCase();let _e=0;return te===ae?_e=100:te.startsWith(ae)?_e=80:te.includes(ae)?_e=60:ce.includes(ae)?_e=40:J.includes(ae)?_e=20:ne.section.toLowerCase().includes(ae)&&(_e=10),_e&&V(ne)&&(_e+=5),{d:ne,score:_e}}).filter(ne=>ne.score>0).sort((ne,te)=>te.score-ne.score).map(ne=>ne.d):[]},routeFor:X=>Wzt(X,P)}}var $yt=1,l6s=.9,c6s=.8,d6s=.17,o7e=.1,l7e=.999,u6s=.9999,h6s=.99,m6s=/[\\\/_+.#"@\[\(\{&]/,f6s=/[\\\/_+.#"@\[\(\{&]/g,p6s=/[\s-]/,Yzt=/[\s-]/g;function tGe(s,t,n,r,a,i,l){if(i===t.length)return a===s.length?$yt:h6s;var o=`${a},${i}`;if(l[o]!==void 0)return l[o];for(var c=r.charAt(i),d=n.indexOf(c,a),u=0,h,m,f,g;d>=0;)h=tGe(s,t,n,r,d+1,i+1,l),h>u&&(d===a?h*=$yt:m6s.test(s.charAt(d-1))?(h*=c6s,f=s.slice(a,d-1).match(f6s),f&&a>0&&(h*=Math.pow(l7e,f.length))):p6s.test(s.charAt(d-1))?(h*=l6s,g=s.slice(a,d-1).match(Yzt),g&&a>0&&(h*=Math.pow(l7e,g.length))):(h*=d6s,a>0&&(h*=Math.pow(l7e,d-a))),s.charAt(d)!==t.charAt(i)&&(h*=u6s)),(hh&&(h=m*o7e)),h>u&&(u=h),d=n.indexOf(c,d+1);return l[o]=u,u}function Uyt(s){return s.toLowerCase().replace(Yzt," ")}function g6s(s,t,n){return s=n&&n.length>0?`${s+" "+n.join(" ")}`:s,tGe(s,t,Uyt(s),Uyt(t),0,0,{})}var EZ='[cmdk-group=""]',c7e='[cmdk-group-items=""]',x6s='[cmdk-group-heading=""]',Zzt='[cmdk-item=""]',qyt=`${Zzt}:not([aria-disabled="true"])`,sGe="cmdk-item-select",xU="data-value",y6s=(s,t,n)=>g6s(s,t,n),Xzt=j.createContext(void 0),Vae=()=>j.useContext(Xzt),Qzt=j.createContext(void 0),Ftt=()=>j.useContext(Qzt),Jzt=j.createContext(void 0),e7t=j.forwardRef((s,t)=>{let n=yU(()=>{var J,ce;return{search:"",value:(ce=(J=s.value)!=null?J:s.defaultValue)!=null?ce:"",selectedItemId:void 0,filtered:{count:0,items:new Map,groups:new Set}}}),r=yU(()=>new Set),a=yU(()=>new Map),i=yU(()=>new Map),l=yU(()=>new Set),o=t7t(s),{label:c,children:d,value:u,onValueChange:h,filter:m,shouldFilter:f,loop:g,disablePointerSelection:x=!1,vimBindings:y=!0,...v}=s,b=my(),w=my(),S=my(),C=j.useRef(null),E=E6s();K7(()=>{if(u!==void 0){let J=u.trim();n.current.value=J,I.emit()}},[u]),K7(()=>{E(6,W)},[]);let I=j.useMemo(()=>({subscribe:J=>(l.current.add(J),()=>l.current.delete(J)),snapshot:()=>n.current,setState:(J,ce,_e)=>{var he,ue,ve,Ee;if(!Object.is(n.current[J],ce)){if(n.current[J]=ce,J==="search")U(),D(),E(1,O);else if(J==="value"){if(document.activeElement.hasAttribute("cmdk-input")||document.activeElement.hasAttribute("cmdk-root")){let Se=document.getElementById(S);Se?Se.focus():(he=document.getElementById(b))==null||he.focus()}if(E(7,()=>{var Se;n.current.selectedItemId=(Se=V())==null?void 0:Se.id,I.emit()}),_e||E(5,W),((ue=o.current)==null?void 0:ue.value)!==void 0){let Se=ce??"";(Ee=(ve=o.current).onValueChange)==null||Ee.call(ve,Se);return}}I.emit()}},emit:()=>{l.current.forEach(J=>J())}}),[]),P=j.useMemo(()=>({value:(J,ce,_e)=>{var he;ce!==((he=i.current.get(J))==null?void 0:he.value)&&(i.current.set(J,{value:ce,keywords:_e}),n.current.filtered.items.set(J,R(ce,_e)),E(2,()=>{D(),I.emit()}))},item:(J,ce)=>(r.current.add(J),ce&&(a.current.has(ce)?a.current.get(ce).add(J):a.current.set(ce,new Set([J]))),E(3,()=>{U(),D(),n.current.value||O(),I.emit()}),()=>{i.current.delete(J),r.current.delete(J),n.current.filtered.items.delete(J);let _e=V();E(4,()=>{U(),(_e==null?void 0:_e.getAttribute("id"))===J&&O(),I.emit()})}),group:J=>(a.current.has(J)||a.current.set(J,new Set),()=>{i.current.delete(J),a.current.delete(J)}),filter:()=>o.current.shouldFilter,label:c||s["aria-label"],getDisablePointerSelection:()=>o.current.disablePointerSelection,listId:b,inputId:S,labelId:w,listInnerRef:C}),[]);function R(J,ce){var _e,he;let ue=(he=(_e=o.current)==null?void 0:_e.filter)!=null?he:y6s;return J?ue(J,n.current.search,ce):0}function D(){if(!n.current.search||o.current.shouldFilter===!1)return;let J=n.current.filtered.items,ce=[];n.current.filtered.groups.forEach(he=>{let ue=a.current.get(he),ve=0;ue.forEach(Ee=>{let Se=J.get(Ee);ve=Math.max(Se,ve)}),ce.push([he,ve])});let _e=C.current;G().sort((he,ue)=>{var ve,Ee;let Se=he.getAttribute("id"),Le=ue.getAttribute("id");return((ve=J.get(Le))!=null?ve:0)-((Ee=J.get(Se))!=null?Ee:0)}).forEach(he=>{let ue=he.closest(c7e);ue?ue.appendChild(he.parentElement===ue?he:he.closest(`${c7e} > *`)):_e.appendChild(he.parentElement===_e?he:he.closest(`${c7e} > *`))}),ce.sort((he,ue)=>ue[1]-he[1]).forEach(he=>{var ue;let ve=(ue=C.current)==null?void 0:ue.querySelector(`${EZ}[${xU}="${encodeURIComponent(he[0])}"]`);ve==null||ve.parentElement.appendChild(ve)})}function O(){let J=G().find(_e=>_e.getAttribute("aria-disabled")!=="true"),ce=J==null?void 0:J.getAttribute(xU);I.setState("value",ce||void 0)}function U(){var J,ce,_e,he;if(!n.current.search||o.current.shouldFilter===!1){n.current.filtered.count=r.current.size;return}n.current.filtered.groups=new Set;let ue=0;for(let ve of r.current){let Ee=(ce=(J=i.current.get(ve))==null?void 0:J.value)!=null?ce:"",Se=(he=(_e=i.current.get(ve))==null?void 0:_e.keywords)!=null?he:[],Le=R(Ee,Se);n.current.filtered.items.set(ve,Le),Le>0&&ue++}for(let[ve,Ee]of a.current)for(let Se of Ee)if(n.current.filtered.items.get(Se)>0){n.current.filtered.groups.add(ve);break}n.current.filtered.count=ue}function W(){var J,ce,_e;let he=V();he&&(((J=he.parentElement)==null?void 0:J.firstChild)===he&&((_e=(ce=he.closest(EZ))==null?void 0:ce.querySelector(x6s))==null||_e.scrollIntoView({block:"nearest"})),he.scrollIntoView({block:"nearest"}))}function V(){var J;return(J=C.current)==null?void 0:J.querySelector(`${Zzt}[aria-selected="true"]`)}function G(){var J;return Array.from(((J=C.current)==null?void 0:J.querySelectorAll(qyt))||[])}function Y(J){let ce=G()[J];ce&&I.setState("value",ce.getAttribute(xU))}function X(J){var ce;let _e=V(),he=G(),ue=he.findIndex(Ee=>Ee===_e),ve=he[ue+J];(ce=o.current)!=null&&ce.loop&&(ve=ue+J<0?he[he.length-1]:ue+J===he.length?he[0]:he[ue+J]),ve&&I.setState("value",ve.getAttribute(xU))}function ae(J){let ce=V(),_e=ce==null?void 0:ce.closest(EZ),he;for(;_e&&!he;)_e=J>0?C6s(_e,EZ):A6s(_e,EZ),he=_e==null?void 0:_e.querySelector(qyt);he?I.setState("value",he.getAttribute(xU)):X(J)}let ie=()=>Y(G().length-1),ne=J=>{J.preventDefault(),J.metaKey?ie():J.altKey?ae(1):X(1)},te=J=>{J.preventDefault(),J.metaKey?Y(0):J.altKey?ae(-1):X(-1)};return j.createElement(Ei.div,{ref:t,tabIndex:-1,...v,"cmdk-root":"",onKeyDown:J=>{var ce;(ce=v.onKeyDown)==null||ce.call(v,J);let _e=J.nativeEvent.isComposing||J.keyCode===229;if(!(J.defaultPrevented||_e))switch(J.key){case"n":case"j":{y&&J.ctrlKey&&ne(J);break}case"ArrowDown":{ne(J);break}case"p":case"k":{y&&J.ctrlKey&&te(J);break}case"ArrowUp":{te(J);break}case"Home":{J.preventDefault(),Y(0);break}case"End":{J.preventDefault(),ie();break}case"Enter":{J.preventDefault();let he=V();if(he){let ue=new Event(sGe);he.dispatchEvent(ue)}}}}},j.createElement("label",{"cmdk-label":"",htmlFor:P.inputId,id:P.labelId,style:M6s},c),$Le(s,J=>j.createElement(Qzt.Provider,{value:I},j.createElement(Xzt.Provider,{value:P},J))))}),v6s=j.forwardRef((s,t)=>{var n,r;let a=my(),i=j.useRef(null),l=j.useContext(Jzt),o=Vae(),c=t7t(s),d=(r=(n=c.current)==null?void 0:n.forceMount)!=null?r:l==null?void 0:l.forceMount;K7(()=>{if(!d)return o.item(a,l==null?void 0:l.id)},[d]);let u=s7t(a,i,[s.value,s.children,i],s.keywords),h=Ftt(),m=TL(E=>E.value&&E.value===u.current),f=TL(E=>d||o.filter()===!1?!0:E.search?E.filtered.items.get(a)>0:!0);j.useEffect(()=>{let E=i.current;if(!(!E||s.disabled))return E.addEventListener(sGe,g),()=>E.removeEventListener(sGe,g)},[f,s.onSelect,s.disabled]);function g(){var E,I;x(),(I=(E=c.current).onSelect)==null||I.call(E,u.current)}function x(){h.setState("value",u.current,!0)}if(!f)return null;let{disabled:y,value:v,onSelect:b,forceMount:w,keywords:S,...C}=s;return j.createElement(Ei.div,{ref:B7(i,t),...C,id:a,"cmdk-item":"",role:"option","aria-disabled":!!y,"aria-selected":!!m,"data-disabled":!!y,"data-selected":!!m,onPointerMove:y||o.getDisablePointerSelection()?void 0:x,onClick:y?void 0:g},s.children)}),b6s=j.forwardRef((s,t)=>{let{heading:n,children:r,forceMount:a,...i}=s,l=my(),o=j.useRef(null),c=j.useRef(null),d=my(),u=Vae(),h=TL(f=>a||u.filter()===!1?!0:f.search?f.filtered.groups.has(l):!0);K7(()=>u.group(l),[]),s7t(l,o,[s.value,s.heading,c]);let m=j.useMemo(()=>({id:l,forceMount:a}),[a]);return j.createElement(Ei.div,{ref:B7(o,t),...i,"cmdk-group":"",role:"presentation",hidden:h?void 0:!0},n&&j.createElement("div",{ref:c,"cmdk-group-heading":"","aria-hidden":!0,id:d},n),$Le(s,f=>j.createElement("div",{"cmdk-group-items":"",role:"group","aria-labelledby":n?d:void 0},j.createElement(Jzt.Provider,{value:m},f))))}),_6s=j.forwardRef((s,t)=>{let{alwaysRender:n,...r}=s,a=j.useRef(null),i=TL(l=>!l.search);return!n&&!i?null:j.createElement(Ei.div,{ref:B7(a,t),...r,"cmdk-separator":"",role:"separator"})}),w6s=j.forwardRef((s,t)=>{let{onValueChange:n,...r}=s,a=s.value!=null,i=Ftt(),l=TL(d=>d.search),o=TL(d=>d.selectedItemId),c=Vae();return j.useEffect(()=>{s.value!=null&&i.setState("search",s.value)},[s.value]),j.createElement(Ei.input,{ref:t,...r,"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),n==null||n(d.target.value)}})}),j6s=j.forwardRef((s,t)=>{let{children:n,label:r="Suggestions",...a}=s,i=j.useRef(null),l=j.useRef(null),o=TL(d=>d.selectedItemId),c=Vae();return j.useEffect(()=>{if(l.current&&i.current){let d=l.current,u=i.current,h,m=new ResizeObserver(()=>{h=requestAnimationFrame(()=>{let f=d.offsetHeight;u.style.setProperty("--cmdk-list-height",f.toFixed(1)+"px")})});return m.observe(d),()=>{cancelAnimationFrame(h),m.unobserve(d)}}},[]),j.createElement(Ei.div,{ref:B7(i,t),...a,"cmdk-list":"",role:"listbox",tabIndex:-1,"aria-activedescendant":o,"aria-label":r,id:c.listId},$Le(s,d=>j.createElement("div",{ref:B7(l,c.listInnerRef),"cmdk-list-sizer":""},d)))}),N6s=j.forwardRef((s,t)=>{let{open:n,onOpenChange:r,overlayClassName:a,contentClassName:i,container:l,...o}=s;return j.createElement(YIe,{open:n,onOpenChange:r},j.createElement(ZIe,{container:l},j.createElement(WW,{"cmdk-overlay":"",className:a}),j.createElement(KW,{"aria-label":s.label,"cmdk-dialog":"",className:i},j.createElement(e7t,{ref:t,...o}))))}),k6s=j.forwardRef((s,t)=>TL(n=>n.filtered.count===0)?j.createElement(Ei.div,{ref:t,...s,"cmdk-empty":"",role:"presentation"}):null),S6s=j.forwardRef((s,t)=>{let{progress:n,children:r,label:a="Loading...",...i}=s;return j.createElement(Ei.div,{ref:t,...i,"cmdk-loading":"",role:"progressbar","aria-valuenow":n,"aria-valuemin":0,"aria-valuemax":100,"aria-label":a},$Le(s,l=>j.createElement("div",{"aria-hidden":!0},l)))}),Ww=Object.assign(e7t,{List:j6s,Item:v6s,Input:w6s,Group:b6s,Separator:_6s,Dialog:N6s,Empty:k6s,Loading:S6s});function C6s(s,t){let n=s.nextElementSibling;for(;n;){if(n.matches(t))return n;n=n.nextElementSibling}}function A6s(s,t){let n=s.previousElementSibling;for(;n;){if(n.matches(t))return n;n=n.previousElementSibling}}function t7t(s){let t=j.useRef(s);return K7(()=>{t.current=s}),t}var K7=typeof window>"u"?j.useEffect:j.useLayoutEffect;function yU(s){let t=j.useRef();return t.current===void 0&&(t.current=s()),t}function TL(s){let t=Ftt(),n=()=>s(t.snapshot());return j.useSyncExternalStore(t.subscribe,n,n)}function s7t(s,t,n,r=[]){let a=j.useRef(),i=Vae();return K7(()=>{var l;let o=(()=>{var d;for(let u of n){if(typeof u=="string")return u.trim();if(typeof u=="object"&&"current"in u)return u.current?(d=u.current.textContent)==null?void 0:d.trim():a.current}})(),c=r.map(d=>d.trim());i.value(s,o,c),(l=t.current)==null||l.setAttribute(xU,o),a.current=o}),a}var E6s=()=>{let[s,t]=j.useState(),n=yU(()=>new Map);return K7(()=>{n.current.forEach(r=>r()),n.current=new Map},[s]),(r,a)=>{n.current.set(r,a),t({})}};function T6s(s){let t=s.type;return typeof t=="function"?t(s.props):"render"in t?t.render(s.props):s}function $Le({asChild:s,children:t},n){return s&&j.isValidElement(t)?j.cloneElement(T6s(t),{ref:t.ref},n(t.props.children)):n(t)}var M6s={position:"absolute",width:"1px",height:"1px",padding:"0",margin:"-1px",overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",borderWidth:"0"};const P2=j.forwardRef(({className:s,...t},n)=>e.jsx(Ww,{ref:n,className:Pt("flex h-full w-full flex-col overflow-hidden rounded-md bg-popover text-popover-foreground",s),...t}));P2.displayName=Ww.displayName;const P6s=({children:s,...t})=>e.jsx(zs,{...t,children:e.jsx(Os,{className:"overflow-hidden p-0 shadow-lg",children:e.jsx(P2,{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})})}),I2=j.forwardRef(({className:s,...t},n)=>e.jsxs("div",{className:"flex items-center border-b px-3","cmdk-input-wrapper":"",children:[e.jsx(Kr,{className:"mr-2 h-4 w-4 shrink-0 opacity-50"}),e.jsx(Ww.Input,{ref:n,className:Pt("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})]}));I2.displayName=Ww.Input.displayName;const L2=j.forwardRef(({className:s,...t},n)=>e.jsx(Ww.List,{ref:n,className:Pt("max-h-[300px] overflow-y-auto overflow-x-hidden",s),...t}));L2.displayName=Ww.List.displayName;const R2=j.forwardRef((s,t)=>e.jsx(Ww.Empty,{ref:t,className:"py-6 text-center text-sm",...s}));R2.displayName=Ww.Empty.displayName;const Uw=j.forwardRef(({className:s,...t},n)=>e.jsx(Ww.Group,{ref:n,className:Pt("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}));Uw.displayName=Ww.Group.displayName;const I6s=j.forwardRef(({className:s,...t},n)=>e.jsx(Ww.Separator,{ref:n,className:Pt("-mx-1 h-px bg-border",s),...t}));I6s.displayName=Ww.Separator.displayName;const g1=j.forwardRef(({className:s,...t},n)=>e.jsx(Ww.Item,{ref:n,className:Pt("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}));g1.displayName=Ww.Item.displayName;const L6s={event:{label:"Events",icon:Kc,color:"bg-blue-500/10 text-blue-600"},template:{label:"Templates",icon:Yc,color:"bg-purple-500/10 text-purple-600"},academy:{label:"Academy",icon:of,color:"bg-amber-500/10 text-amber-600"},toolbox:{label:"Toolbox",icon:F4,color:"bg-green-500/10 text-green-600"},"social-swag":{label:"Social Swag",icon:Nn,color:"bg-fuchsia-500/10 text-fuchsia-600"}},Vyt=()=>{const[s,t]=j.useState(!1),[n,r]=j.useState(""),[a,i]=j.useState([]),[l,o]=j.useState(!1),c=Qn(),{searchDestinations:d,isFavorite:u,routeFor:h}=Kzt(),m=n.trim()?d(n).slice(0,6):[];j.useEffect(()=>{const y=v=>{v.key==="k"&&(v.metaKey||v.ctrlKey)&&(v.preventDefault(),t(b=>!b))};return document.addEventListener("keydown",y),()=>document.removeEventListener("keydown",y)},[]);const f=j.useCallback(async y=>{if(!y.trim()){i([]);return}o(!0);const v=`%${y}%`;try{const[b,w,S,C,E]=await Promise.all([q.from("events").select("id, title, description, event_date").eq("is_published",!0).or(`title.ilike.${v},description.ilike.${v}`).limit(5),q.from("canva_templates").select("id, name, description, publish_date").or(`name.ilike.${v},description.ilike.${v}`).limit(5),q.from("academy_videos").select("id, title, description, publish_date").eq("is_published",!0).or(`title.ilike.${v},description.ilike.${v}`).limit(5),q.from("resource_kits").select("id, name, description, publish_date").eq("is_published",!0).or(`name.ilike.${v},description.ilike.${v}`).limit(5),q.from("social_swag").select("id, title, description, publish_date").eq("is_published",!0).or(`title.ilike.${v},description.ilike.${v}`).limit(5)]),I=[];b.data&&b.data.forEach(P=>{I.push({id:P.id,title:P.title,description:P.description,type:"event",date:P.event_date,path:`/event/${P.id}`})}),w.data&&w.data.forEach(P=>{I.push({id:P.id,title:P.name,description:P.description,type:"template",date:P.publish_date,path:`/templates/${P.id}`})}),S.data&&S.data.forEach(P=>{I.push({id:P.id,title:P.title,description:P.description,type:"academy",date:P.publish_date,path:`/academy/${P.id}`})}),C.data&&C.data.forEach(P=>{I.push({id:P.id,title:P.name,description:P.description,type:"toolbox",date:P.publish_date,path:`/toolbox/${P.id}`})}),E.data&&E.data.forEach(P=>{I.push({id:P.id,title:P.title,description:P.description,type:"social-swag",date:P.publish_date,path:`/social-swag/${P.id}`})}),i(I)}catch(b){console.error("Search error:",b)}finally{o(!1)}},[]);j.useEffect(()=>{const y=setTimeout(()=>{f(n)},300);return()=>clearTimeout(y)},[n,f]);const g=y=>{t(!1),r(""),c(y)},x=a.reduce((y,v)=>(y[v.type]||(y[v.type]=[]),y[v.type].push(v),y),{});return e.jsxs(e.Fragment,{children:[e.jsxs($,{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(Kr,{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(P6s,{open:s,onOpenChange:t,children:[e.jsx(I2,{placeholder:"Search events, templates, academy, toolbox, social swag...",value:n,onValueChange:r}),e.jsxs(L2,{children:[m.length>0&&e.jsx(Uw,{heading:"Go to",children:m.map(y=>{const v=y.icon;return e.jsxs(g1,{value:`nav-${y.id}-${y.label}`,onSelect:()=>{const b=h(y);y.external||y.openInNewTab?(t(!1),r(""),window.open(b,"_blank","noopener,noreferrer")):g(b)},className:"flex items-start gap-3 py-3 cursor-pointer",children:[e.jsx("div",{className:"p-2 rounded-md bg-primary/10 text-primary",children:e.jsx(v,{className:"h-4 w-4"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"font-medium truncate flex items-center gap-1.5",children:[y.label,u(y)&&e.jsx(M0,{className:"h-3 w-3 fill-current text-primary"})]}),y.description&&e.jsx("div",{className:"text-sm text-muted-foreground truncate",children:y.description})]}),e.jsx(Be,{variant:"secondary",className:"text-xs shrink-0",children:y.section})]},`nav-${y.id}`)})}),l&&e.jsx("div",{className:"py-6 text-center text-sm text-muted-foreground",children:"Searching..."}),!l&&n&&a.length===0&&m.length===0&&e.jsxs(R2,{children:['No results found for "',n,'"']}),!l&&!n&&e.jsx("div",{className:"py-6 text-center text-sm text-muted-foreground",children:"Start typing to search pages, apps and content..."}),Object.entries(x).map(([y,v])=>{const b=L6s[y],w=b.icon;return e.jsx(Uw,{heading:b.label,children:v.map(S=>e.jsxs(g1,{value:`${S.type}-${S.id}-${S.title}`,onSelect:()=>g(S.path),className:"flex items-start gap-3 py-3 cursor-pointer",children:[e.jsx("div",{className:`p-2 rounded-md ${b.color}`,children:e.jsx(w,{className:"h-4 w-4"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"font-medium truncate",children:S.title}),S.description&&e.jsx("div",{className:"text-sm text-muted-foreground truncate group-data-[selected=true]:text-primary-foreground/80",children:S.description})]}),e.jsxs("div",{className:"flex flex-col items-end gap-1 shrink-0",children:[e.jsx(Be,{variant:"secondary",className:"text-xs",children:b.label}),e.jsx("span",{className:"text-xs text-muted-foreground",children:mu(new Date(S.date),{addSuffix:!0})})]})]},`${S.type}-${S.id}`))},y)})]})]})]})},R6s=({expiresAt:s,className:t,showUpgradeButton:n=!0})=>{const[r,a]=j.useState(null),i=Qn();if(j.useEffect(()=>{const d=()=>{const h=new Date().getTime(),f=new Date(s).getTime()-h;if(f<=0){a({days:0,hours:0,minutes:0});return}const g=Math.floor(f/(1e3*60*60*24)),x=Math.floor(f%(1e3*60*60*24)/(1e3*60*60)),y=Math.floor(f%(1e3*60*60)/(1e3*60));a({days:g,hours:x,minutes:y})};d();const u=setInterval(d,6e4);return()=>clearInterval(u)},[s]),!r)return null;const l=r.days===0&&r.hours===0&&r.minutes===0,o=r.days<=1,c=r.days<=3&&!o;return l?e.jsxs("div",{className:Pt("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(wl,{className:"h-4 w-4 text-destructive"}),e.jsx("span",{className:"text-sm font-medium text-destructive",children:"Your free trial has expired"})]}),n&&e.jsxs($,{size:"sm",onClick:()=>i("/subscription"),className:"bg-primary hover:bg-primary/90 text-xs h-7 px-3",children:[e.jsx(Nn,{className:"h-3 w-3 mr-1"}),"Upgrade Now"]})]}):e.jsxs("div",{className:Pt("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(da,{className:Pt("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:Pt("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:[r.days>0&&e.jsxs("span",{className:Pt("text-sm font-bold",o?"text-destructive":c?"text-amber-600":"text-primary"),children:[r.days,"d"]}),e.jsxs("span",{className:Pt("text-sm font-bold",o?"text-destructive":c?"text-amber-600":"text-primary"),children:[r.hours,"h"]}),e.jsxs("span",{className:Pt("text-sm font-bold",o?"text-destructive":c?"text-amber-600":"text-primary"),children:[r.minutes,"m"]}),e.jsx("span",{className:Pt("text-xs",o?"text-destructive/70":c?"text-amber-600/70":"text-primary/70"),children:"remaining"})]})]})]}),n&&e.jsxs($,{size:"sm",onClick:()=>i("/subscription"),variant:o?"destructive":c?"default":"outline",className:Pt("text-xs h-7 px-3",c&&"bg-amber-500 hover:bg-amber-600 text-white"),children:[e.jsx(Nn,{className:"h-3 w-3 mr-1"}),"Upgrade"]})]})},D6s=()=>{const s=Qn();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(Ne,{className:"w-full max-w-2xl shadow-2xl border-destructive/20 my-8",children:[e.jsxs(Ct,{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(wl,{className:"h-8 w-8 text-destructive"})}),e.jsx(At,{className:"text-2xl",children:"Your Free Trial Has Ended"}),e.jsx(Gn,{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(Ie,{className:"space-y-6",children:[e.jsxs("div",{className:"grid sm:grid-cols-2 gap-4",children:[e.jsx(Ne,{className:"border-2 border-primary/20 hover:border-primary/50 transition-colors cursor-pointer",onClick:()=>s("/subscription"),children:e.jsxs(Ie,{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(Zn,{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($,{className:"w-full",onClick:t=>{t.stopPropagation(),s("/subscription")},children:[e.jsx(Nn,{className:"h-4 w-4 mr-2"}),"Choose Individual"]})]})}),e.jsx(Ne,{className:"border-2 border-amber-500/20 hover:border-amber-500/50 transition-colors cursor-pointer",onClick:()=>s("/subscription"),children:e.jsxs(Ie,{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(ji,{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($,{variant:"outline",className:"w-full border-amber-500 text-amber-600 hover:bg-amber-50",onClick:t=>{t.stopPropagation(),s("/subscription")},children:[e.jsx(ji,{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(Da,{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(mn,{className:"h-4 w-4"}),e.jsx("span",{children:"support@relevelup.com"})]})]})]})]})]})})},F6s=({hasUnseenBrief:s,onClick:t,className:n})=>e.jsxs(ly,{children:[e.jsx(cy,{asChild:!0,children:e.jsxs($,{variant:"ghost",size:"icon",onClick:t,className:Pt("relative transition-colors",s&&"text-primary hover:text-primary",n),children:[e.jsx(xm,{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(Nx,{children:e.jsx("p",{children:"The LevelUp Brief"})})]});var O6s=Object.defineProperty,pT=(s,t)=>O6s(s,"name",{value:t,configurable:!0}),Ott="Checkbox",[z6s,tSr]=tp(Ott),[B6s,ztt]=z6s(Ott);function n7t(s){const{__scopeCheckbox:t,checked:n,children:r,defaultChecked:a,disabled:i,form:l,name:o,onCheckedChange:c,required:d,value:u="on",internal_do_not_use_render:h}=s,[m,f]=fy({prop:n,defaultProp:a??!1,onChange:c,caller:Ott}),[g,x]=j.useState(null),[y,v]=j.useState(null),b=j.useRef(!1),[w,S]=j.useReducer(I=>I+1,0),C=g?!!l||!!g.closest("form"):!0,E={checked:m,disabled:i,setChecked:f,control:g,setControl:x,name:o,form:l,value:u,hasConsumerStoppedPropagationRef:b,userInteractionCount:w,onUserInteraction:S,required:d,defaultChecked:VE(a)?!1:a,isFormControl:C,bubbleInput:y,setBubbleInput:v};return e.jsx(B6s,{scope:t,...E,children:a7t(h)?h(E):r})}pT(n7t,"CheckboxProvider");var $6s="CheckboxTrigger",U6s=j.forwardRef(pT(function({__scopeCheckbox:t,onKeyDown:n,onClick:r,...a},i){const{control:l,value:o,disabled:c,checked:d,required:u,setControl:h,setChecked:m,hasConsumerStoppedPropagationRef:f,onUserInteraction:g,isFormControl:x,bubbleInput:y}=ztt($6s,t),v=Vo(i,h),b=j.useRef(d);return j.useEffect(()=>{const w=l==null?void 0:l.form;if(w){const S=pT(()=>m(b.current),"reset");return w.addEventListener("reset",S),()=>w.removeEventListener("reset",S)}},[l,m]),e.jsx(Ei.button,{type:"button",role:"checkbox","aria-checked":VE(d)?"mixed":d,"aria-required":u,"data-state":Btt(d),"data-disabled":c?"":void 0,disabled:c,value:o,...a,ref:v,onKeyDown:Ra(n,w=>{w.key==="Enter"&&w.preventDefault()}),onClick:Ra(r,w=>{g(),m(S=>VE(S)?!0:!S),y&&x&&(f.current=w.isPropagationStopped(),f.current||w.stopPropagation())})})},"CheckboxTrigger")),r7t=j.forwardRef(pT(function(t,n){const{__scopeCheckbox:r,name:a,checked:i,defaultChecked:l,required:o,disabled:c,value:d,onCheckedChange:u,form:h,...m}=t;return e.jsx(n7t,{__scopeCheckbox:r,checked:i,defaultChecked:l,disabled:c,required:o,onCheckedChange:u,name:a,form:h,value:d,internal_do_not_use_render:({isFormControl:f})=>e.jsxs(e.Fragment,{children:[e.jsx(U6s,{...m,ref:n,__scopeCheckbox:r}),f&&e.jsx(G6s,{__scopeCheckbox:r})]})})},"Checkbox")),q6s="CheckboxIndicator",V6s=j.forwardRef(pT(function(t,n){const{__scopeCheckbox:r,forceMount:a,...i}=t,l=ztt(q6s,r);return e.jsx(xy,{present:a||VE(l.checked)||l.checked===!0,children:e.jsx(Ei.span,{"data-state":Btt(l.checked),"data-disabled":l.disabled?"":void 0,...i,ref:n,style:{pointerEvents:"none",...t.style}})})},"CheckboxIndicator")),H6s="CheckboxBubbleInput",G6s=j.forwardRef(pT(function({__scopeCheckbox:t,onClick:n,...r},a){const{control:i,hasConsumerStoppedPropagationRef:l,userInteractionCount:o,checked:c,defaultChecked:d,required:u,disabled:h,name:m,value:f,form:g,bubbleInput:x,setBubbleInput:y}=ztt(H6s,t),v=Vo(a,y),b=XW(i),w=j.useRef(!1),S=j.useRef(c),C=j.useRef(o);j.useEffect(()=>{const I=x;if(!I)return;const P=window.HTMLInputElement.prototype,D=Object.getOwnPropertyDescriptor(P,"checked").set,O=o!==C.current;C.current=o;const U=S.current!==c;S.current=c;const W=!(O&&l.current);if(U&&D){w.current=!O;const V=new Event("click",{bubbles:W});I.indeterminate=VE(c),D.call(I,VE(c)?!1:c),I.dispatchEvent(V),w.current=!1}},[x,c,l,o]);const E=j.useRef(VE(c)?!1:c);return e.jsx(Ei.input,{type:"checkbox","aria-hidden":!0,defaultChecked:d??E.current,required:u,disabled:h,name:m,value:f,form:g,...r,tabIndex:-1,ref:v,onClick:Ra(n,I=>{w.current&&I.stopPropagation()}),style:{...r.style,...b,position:"absolute",pointerEvents:"none",opacity:0,margin:0,transform:"translateX(-100%)"}})},"CheckboxBubbleInput"));function a7t(s){return typeof s=="function"}pT(a7t,"isFunction");function VE(s){return s==="indeterminate"}pT(VE,"isIndeterminate");function Btt(s){return VE(s)?"indeterminate":s?"checked":"unchecked"}pT(Btt,"getState");const ai=j.forwardRef(({className:s,...t},n)=>e.jsx(r7t,{ref:n,className:Pt("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(V6s,{className:Pt("flex items-center justify-center text-current"),children:e.jsx(la,{className:"h-4 w-4"})})}));ai.displayName=r7t.displayName;var W6s=Object.defineProperty,w1=(s,t)=>W6s(s,"name",{value:t,configurable:!0}),i7t="Radio",[K6s,o7t]=tp(i7t),[Y6s,ULe]=K6s(i7t);function l7t(s){const{__scopeRadio:t,checked:n=!1,children:r,disabled:a,form:i,name:l,onCheck:o,required:c,value:d="on",internal_do_not_use_render:u}=s,[h,m]=j.useState(null),[f,g]=j.useState(null),x=j.useRef(!1),[y,v]=j.useReducer(S=>S+1,0),b=h?!!i||!!h.closest("form"):!0,w={checked:n,disabled:a,required:c,name:l,form:i,value:d,control:h,setControl:m,hasConsumerStoppedPropagationRef:x,userInteractionCount:y,onUserInteraction:v,isFormControl:b,bubbleInput:f,setBubbleInput:g,onCheck:w1(()=>o==null?void 0:o(),"onCheck")};return e.jsx(Y6s,{scope:t,...w,children:c7t(u)?u(w):r})}w1(l7t,"RadioProvider");var Z6s="RadioTrigger",X6s=j.forwardRef(w1(function({__scopeRadio:t,onClick:n,...r},a){const{checked:i,disabled:l,value:o,setControl:c,onCheck:d,hasConsumerStoppedPropagationRef:u,onUserInteraction:h,isFormControl:m,bubbleInput:f}=ULe(Z6s,t),g=Vo(a,c);return e.jsx(Ei.button,{type:"button",role:"radio","aria-checked":i,"data-state":$tt(i),"data-disabled":l?"":void 0,disabled:l,value:o,...r,ref:g,onClick:Ra(n,x=>{i||(h(),d()),f&&m&&(u.current=x.isPropagationStopped(),u.current||x.stopPropagation())})})},"RadioTrigger")),Q6s="RadioIndicator",J6s=j.forwardRef(w1(function(t,n){const{__scopeRadio:r,forceMount:a,...i}=t,l=ULe(Q6s,r);return e.jsx(xy,{present:a||l.checked,children:e.jsx(Ei.span,{"data-state":$tt(l.checked),"data-disabled":l.disabled?"":void 0,...i,ref:n})})},"RadioIndicator")),eRs="RadioBubbleInput",tRs=j.forwardRef(w1(function({__scopeRadio:t,onClick:n,...r},a){const{control:i,checked:l,required:o,disabled:c,name:d,value:u,form:h,bubbleInput:m,setBubbleInput:f,hasConsumerStoppedPropagationRef:g,userInteractionCount:x}=ULe(eRs,t),y=Vo(a,f),v=XW(i),b=j.useRef(!1),w=j.useRef(l),S=j.useRef(x);j.useEffect(()=>{const E=m;if(!E)return;const I=window.HTMLInputElement.prototype,R=Object.getOwnPropertyDescriptor(I,"checked").set,D=x!==S.current;S.current=x;const O=w.current!==l;w.current=l;const U=!(D&&g.current);if(O&&R){b.current=!D;const W=new Event("click",{bubbles:U});R.call(E,l),E.dispatchEvent(W),b.current=!1}},[m,l,g,x]);const C=j.useRef(l);return e.jsx(Ei.input,{type:"radio","aria-hidden":!0,defaultChecked:C.current,required:o,disabled:c,name:d,value:u,form:h,...r,tabIndex:-1,ref:y,onClick:Ra(n,E=>{b.current&&E.stopPropagation()}),style:{...r.style,...v,position:"absolute",pointerEvents:"none",opacity:0,margin:0,transform:"translateX(-100%)"}})},"RadioBubbleInput"));function c7t(s){return typeof s=="function"}w1(c7t,"isFunction");function $tt(s){return s?"checked":"unchecked"}w1($tt,"getState");var sRs=["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"],Utt="RadioGroup",[nRs,sSr]=tp(Utt,[r6,o7t]),d7t=r6(),qLe=o7t(),[rRs,aRs]=nRs(Utt),u7t=j.forwardRef(w1(function(t,n){const{__scopeRadioGroup:r,name:a,form:i,defaultValue:l,value:o,required:c=!1,disabled:d=!1,orientation:u,dir:h,loop:m=!0,onValueChange:f,...g}=t,x=d7t(r),y=l3(h),[v,b]=fy({prop:o,defaultProp:l??null,onChange:f,caller:Utt}),[w,S]=j.useState(null),C=Vo(n,S),E=j.useRef(v);return j.useEffect(()=>{const I=i?w==null?void 0:w.ownerDocument.getElementById(i):w==null?void 0:w.closest("form");if(I instanceof HTMLFormElement){const P=w1(()=>b(E.current),"reset");return I.addEventListener("reset",P),()=>I.removeEventListener("reset",P)}},[w,i,b]),e.jsx(rRs,{scope:r,name:a,form:i,required:c,disabled:d,value:v,onValueChange:b,children:e.jsx(xLe,{asChild:!0,...x,orientation:u,dir:y,loop:m,children:e.jsx(Ei.div,{role:"radiogroup","aria-required":c,"aria-orientation":u,"data-disabled":d?"":void 0,dir:y,...g,ref:C})})})},"RadioGroup")),iRs="RadioGroupItemProvider",oRs="RadioGroupItemTrigger";function h7t(s){const{__scopeRadioGroup:t,value:n,disabled:r,children:a,internal_do_not_use_render:i}=s,l=aRs(iRs,t),o=qLe(t),c=l.disabled||r;return e.jsx(l7t,{...o,checked:l.value===n,disabled:c,required:l.required,name:l.name,form:l.form,value:n,onCheck:()=>l.onValueChange(n),internal_do_not_use_render:i,children:a})}w1(h7t,"RadioGroupItemProvider");var lRs=j.forwardRef(w1(function(t,n){const{__scopeRadioGroup:r,...a}=t,i=d7t(r),l=qLe(r),{checked:o,disabled:c}=ULe(oRs,l.__scopeRadio),d=j.useRef(null),u=Vo(n,d),h=j.useRef(!1);return j.useEffect(()=>{const m=w1(g=>{sRs.includes(g.key)&&(h.current=!0)},"handleKeyDown"),f=w1(()=>h.current=!1,"handleKeyUp");return document.addEventListener("keydown",m),document.addEventListener("keyup",f),()=>{document.removeEventListener("keydown",m),document.removeEventListener("keyup",f)}},[]),e.jsx(yLe,{asChild:!0,...i,focusable:!c,active:o,children:e.jsx(X6s,{...l,...a,ref:u,onKeyDown:Ra(a.onKeyDown,m=>{m.key==="Enter"&&m.preventDefault()}),onFocus:Ra(a.onFocus,()=>{var m;h.current&&((m=d.current)==null||m.click())})})})},"RadioGroupItemTrigger")),m7t=j.forwardRef(w1(function(t,n){const{__scopeRadioGroup:r,value:a,disabled:i,...l}=t;return e.jsx(h7t,{__scopeRadioGroup:r,value:a,disabled:i,internal_do_not_use_render:({isFormControl:o})=>e.jsxs(e.Fragment,{children:[e.jsx(lRs,{...l,ref:n,__scopeRadioGroup:r}),o&&e.jsx(cRs,{__scopeRadioGroup:r})]})})},"RadioGroupItem")),cRs=j.forwardRef(w1(function(t,n){const{__scopeRadioGroup:r,...a}=t,i=qLe(r);return e.jsx(tRs,{...i,...a,ref:n})},"RadioGroupItemBubbleInput")),dRs=j.forwardRef(w1(function(t,n){const{__scopeRadioGroup:r,...a}=t,i=qLe(r);return e.jsx(J6s,{...i,...a,ref:n})},"RadioGroupIndicator"));const kw=j.forwardRef(({className:s,...t},n)=>e.jsx(u7t,{className:Pt("grid gap-2",s),...t,ref:n}));kw.displayName=u7t.displayName;const Ym=j.forwardRef(({className:s,...t},n)=>e.jsx(m7t,{ref:n,className:Pt("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(dRs,{className:"flex items-center justify-center",children:e.jsx(Og,{className:"h-2.5 w-2.5 fill-current text-current"})})}));Ym.displayName=m7t.displayName;const uRs=({brief:s,open:t,onClose:n,onDismiss:r})=>{const{user:a}=vs(),[i,l]=j.useState({}),[o,c]=j.useState({}),[d,u]=j.useState([]);j.useEffect(()=>{t&&a&&s.polls.length>0&&h()},[t,a,s.polls]);const h=async()=>{if(!a)return;const y=s.polls.map(b=>b.id),{data:v}=await q.from("levelup_brief_poll_responses").select("poll_id, option_id").eq("user_id",a.id).in("poll_id",y);if(v){const b={};v.forEach(w=>{b[w.poll_id]||(b[w.poll_id]=[]),b[w.poll_id].push(w.option_id)}),c(b)}},m=(y,v)=>{l(b=>({...b,[y]:v}))},f=(y,v,b)=>{l(w=>{const S=w[y]||[];return b?{...w,[y]:[...S,v]}:{...w,[y]:S.filter(C=>C!==v)}})},g=async y=>{if(!a)return;const v=i[y];if(!v||Array.isArray(v)&&v.length===0){re.error("Please select an option");return}u(b=>[...b,y]);try{await q.from("levelup_brief_poll_responses").delete().eq("poll_id",y).eq("user_id",a.id);const b=Array.isArray(v)?v:[v],w=b.map(C=>({poll_id:y,option_id:C,user_id:a.id})),{error:S}=await q.from("levelup_brief_poll_responses").insert(w);if(S)throw S;c(C=>({...C,[y]:b})),re.success("Response submitted!")}catch(b){console.error("Error submitting poll response:",b),re.error("Failed to submit response")}finally{u(b=>b.filter(w=>w!==y))}},x=y=>(y.includes("mediadelivery.net")||y.includes("bunny"),y);return e.jsx(zs,{open:t,onOpenChange:y=>!y&&n(),children:e.jsxs(Os,{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:n,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(gr,{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(xm,{className:"h-6 w-6"})}),e.jsxs("div",{children:[e.jsx(Be,{variant:"secondary",className:"mb-1 bg-white/20 text-white border-0",children:"The LevelUp Brief"}),e.jsx(Bs,{className:"text-xl font-bold text-white",children:s.brief.title})]})]})]}),e.jsx(uo,{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:x(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(y=>e.jsxs($,{variant:"outline",size:"sm",onClick:()=>window.open(y.url,"_blank"),className:"gap-2",children:[e.jsx(kr,{className:"h-4 w-4"}),y.title]},y.id))})]}),s.polls.map(y=>{var w,S;const v=((w=o[y.id])==null?void 0:w.length)>0,b=d.includes(y.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:y.question}),v&&e.jsxs(Be,{variant:"secondary",className:"gap-1",children:[e.jsx(qr,{className:"h-3 w-3"}),"Responded"]})]}),y.poll_type==="single"?e.jsx(kw,{value:i[y.id]||((S=o[y.id])==null?void 0:S[0])||"",onValueChange:C=>m(y.id,C),className:"space-y-2",children:y.options.map(C=>e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Ym,{value:C.id,id:C.id}),e.jsx(ee,{htmlFor:C.id,className:"cursor-pointer",children:C.option_text})]},C.id))}):e.jsx("div",{className:"space-y-2",children:y.options.map(C=>{const I=(i[y.id]||o[y.id]||[]).includes(C.id);return e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(ai,{id:C.id,checked:I,onCheckedChange:P=>f(y.id,C.id,P)}),e.jsx(ee,{htmlFor:C.id,className:"cursor-pointer",children:C.option_text})]},C.id)})}),e.jsx($,{size:"sm",onClick:()=>g(y.id),disabled:b,children:b?"Submitting...":v?"Update Response":"Submit"})]},y.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($,{onClick:n,className:"w-full max-w-xs",children:"Got it!"}),e.jsx($,{variant:"ghost",size:"sm",onClick:r,children:"Don't show again"})]})]})})},hRs=()=>{const{user:s}=vs(),[t,n]=j.useState(null),[r,a]=j.useState(!1),[i,l]=j.useState(!0),[o,c]=j.useState(!1),d=j.useCallback(async()=>{if(!s){l(!1);return}try{const{data:g,error:x}=await q.from("levelup_briefs").select("*").eq("is_published",!0).lte("publish_date",new Date().toISOString()).order("publish_date",{ascending:!1}).limit(1).single();if(x||!g){l(!1);return}const{data:y}=await q.from("levelup_brief_views").select("*").eq("brief_id",g.id).eq("user_id",s.id).maybeSingle(),[v,b]=await Promise.all([q.from("levelup_brief_links").select("*").eq("brief_id",g.id).order("sort_order"),q.from("levelup_brief_polls").select("*").eq("brief_id",g.id).order("sort_order")]),w=[];if(b.data)for(const P of b.data){const{data:R}=await q.from("levelup_brief_poll_options").select("*").eq("poll_id",P.id).order("sort_order");w.push({...P,options:R||[]})}const S={brief:g,links:v.data||[],polls:w};n(S);const C=!!y,E=(y==null?void 0:y.dismissed_at)!=null,I=localStorage.getItem(`brief-dismissed-${g.id}`)==="true";if(E||I)c(!1),a(!1);else if(!C)a(!0),c(!0);else if(g.show_frequency==="every_login")a(!0),c(!0);else if(g.show_frequency==="daily"){const P=new Date(y.viewed_at);(new Date().getTime()-P.getTime())/(1e3*60*60)>=24&&(a(!0),c(!0))}else c(!1)}catch(g){console.error("Error fetching brief:",g)}finally{l(!1)}},[s]);j.useEffect(()=>{d()},[d]);const u=async()=>{if(!(!s||!t))try{const{data:g}=await q.from("levelup_brief_views").select("id").eq("brief_id",t.brief.id).eq("user_id",s.id).maybeSingle();g?await q.from("levelup_brief_views").update({viewed_at:new Date().toISOString()}).eq("id",g.id):await q.from("levelup_brief_views").insert({brief_id:t.brief.id,user_id:s.id})}catch(g){console.error("Error marking brief as viewed:",g)}};return{currentBrief:t,shouldShowPopup:r,hasUnseenBrief:o,loading:i,openBrief:()=>{a(!0)},closeBrief:()=>{a(!1),u()},dismissBrief:async()=>{if(!(!s||!t)){a(!1),c(!1);try{const{data:g,error:x}=await q.from("levelup_brief_views").select("id").eq("brief_id",t.brief.id).eq("user_id",s.id).maybeSingle();if(x&&console.error("Error checking existing brief view:",x),g){const{error:y}=await q.from("levelup_brief_views").update({dismissed_at:new Date().toISOString()}).eq("id",g.id).eq("user_id",s.id);y&&console.error("Error updating brief dismiss:",y)}else{const{error:y}=await q.from("levelup_brief_views").insert({brief_id:t.brief.id,user_id:s.id,dismissed_at:new Date().toISOString()});y&&console.error("Error inserting brief dismiss:",y)}localStorage.setItem(`brief-dismissed-${t.brief.id}`,"true")}catch(g){console.error("Error dismissing brief:",g),t&&localStorage.setItem(`brief-dismissed-${t.brief.id}`,"true")}}},refetch:d}};function mRs(){const[s,t]=j.useState(!1),[n,r]=j.useState(!1),[a,i]=j.useState(null);j.useEffect(()=>{const c=localStorage.getItem("install-banner-dismissed"),d=localStorage.getItem("install-banner-shown");if(c||d)return;if(window.matchMedia("(display-mode: standalone)").matches||window.matchMedia("(display-mode: fullscreen)").matches||window.matchMedia("(display-mode: minimal-ui)").matches||window.navigator.standalone===!0||document.referrer.startsWith("android-app://")){localStorage.setItem("install-banner-dismissed","true");return}if(!/iPhone|iPad|iPod|Android/i.test(navigator.userAgent))return;const m=/iPhone|iPad|iPod/i.test(navigator.userAgent);r(m),t(!0),localStorage.setItem("install-banner-shown","true");const f=g=>{g.preventDefault(),i(g)};return window.addEventListener("beforeinstallprompt",f),()=>{window.removeEventListener("beforeinstallprompt",f)}},[]);const l=()=>{localStorage.setItem("install-banner-dismissed","true"),localStorage.setItem("install-banner-shown","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(di,{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"}),n?e.jsxs("p",{className:"text-xs opacity-80 flex items-center gap-1",children:["Tap ",e.jsx(tee,{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:[!n&&a&&e.jsx($,{size:"sm",variant:"secondary",onClick:o,className:"text-xs",children:"Install"}),e.jsx($,{size:"sm",variant:"secondary",onClick:l,className:"text-xs",children:"Got it"}),e.jsx("button",{onClick:l,className:"p-1.5 hover:bg-primary-foreground/10 rounded-full transition-colors","aria-label":"Dismiss",children:e.jsx(gr,{className:"h-4 w-4"})})]})]})}):null}const fRs=({children:s,onRefresh:t})=>{const[n,r]=j.useState(!1),[a,i]=j.useState(0),[l,o]=j.useState(!1),c=j.useRef(null),d=j.useRef(0),u=Vt(),h=80,m=120,f=j.useCallback(b=>{const w=c.current;w&&w.scrollTop<=0&&(d.current=b.touches[0].clientY,r(!0))},[]),g=j.useCallback(b=>{if(!n||l)return;const w=c.current;if(!w||w.scrollTop>0){r(!1),i(0);return}const C=b.touches[0].clientY-d.current;if(C>0){const I=Math.min(C*.5,m);i(I),I>10&&b.preventDefault()}},[n,l]),x=j.useCallback(async()=>{if(n)if(r(!1),a>=h&&!l){o(!0),i(h);try{t?await t():await u.invalidateQueries()}catch(b){console.error("Refresh failed:",b)}finally{o(!1),i(0)}}else i(0)},[n,a,l,t,u]),y=Math.min(a/h,1),v=y*180;return e.jsxs("div",{ref:c,className:"h-full overflow-auto",onTouchStart:f,onTouchMove:g,onTouchEnd:x,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:y},children:e.jsx("div",{className:`p-2 rounded-full bg-primary/10 ${l?"animate-spin":""}`,style:{transform:l?void 0:`rotate(${v}deg)`,transition:l?void 0:"transform 0.1s ease-out"},children:e.jsx(ro,{className:"h-5 w-5 text-primary"})})}),e.jsx("div",{style:{transform:a>0?`translateY(${Math.max(0,a-60)}px)`:void 0,transition:n?void 0:"transform 0.2s ease-out"},children:s})]})},f7t=()=>{const{user:s}=vs(),[t,n]=j.useState(!1),[r,a]=j.useState(!1),[i,l]=j.useState(0),[o,c]=j.useState(!0);j.useEffect(()=>{(async()=>{if(!s){c(!1);return}try{const{data:f}=await q.from("membership_reviews").select("id").eq("user_id",s.id).maybeSingle();if(f){a(!0),n(!1),c(!1);return}const{data:g}=await q.from("profiles").select("login_count").eq("id",s.id).single(),x=(g==null?void 0:g.login_count)||0;l(x);const y=sessionStorage.getItem("review-prompt-dismissed");n(x>=4&&!y)}catch(f){console.error("Error checking review eligibility:",f)}finally{c(!1)}})()},[s]);const d=j.useCallback(()=>{sessionStorage.setItem("review-prompt-dismissed","true"),n(!1)},[]),u=j.useCallback(async(m,f)=>{if(!s)return{success:!1,error:"Not authenticated"};try{const{error:g}=await q.from("membership_reviews").insert({user_id:s.id,rating:m,review_text:f});if(g)throw g;return a(!0),n(!1),{success:!0,pointsAwarded:25}}catch(g){return console.error("Error submitting review:",g),{success:!1,error:g.message}}},[s]),h=j.useCallback(async()=>{if(s)try{await q.from("membership_reviews").update({posted_to_google:!0}).eq("user_id",s.id)}catch(m){console.error("Error updating Google review status:",m)}},[s]);return{shouldShowPrompt:t,hasSubmittedReview:r,loginCount:i,isLoading:o,dismissPrompt:d,submitReview:u,markPostedToGoogle:h}},pRs="https://search.google.com/local/writereview?placeid=ChIJM73ERQD1QogRPxupMFObuck&source=g.page.m.ia._&laa=nmx-review-solicitation-ia2",gRs=()=>{const{shouldShowPrompt:s,isLoading:t,dismissPrompt:n,submitReview:r,markPostedToGoogle:a}=f7t(),[i,l]=j.useState(!1),[o,c]=j.useState("review"),[d,u]=j.useState(0),[h,m]=j.useState(0),[f,g]=j.useState(""),[x,y]=j.useState(!1),[v,b]=j.useState(!1);if(t||!s&&!v)return null;const w=async()=>{if(d===0){_a({title:"Please select a rating",variant:"destructive"});return}y(!0);const E=await r(d,f);y(!1),E.success?(b(!0),_a({title:"Thank you for your feedback!",description:"Your review helps us improve."}),c("google")):_a({title:"Error submitting review",description:E.error,variant:"destructive"})},S=async E=>{E&&(await navigator.clipboard.writeText(f||`${d} star rating for LevelUp!`),_a({title:"Review copied!",description:"Paste it on Google Reviews."}),await a(),window.open(pRs,"_blank")),l(!1),n()},C=()=>{l(!1),n()};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(Ja,{className:"h-3.5 w-3.5 fill-current"}),e.jsx("span",{className:"hidden sm:inline",children:"Leave a Review"})]}),e.jsx(zs,{open:i,onOpenChange:C,children:e.jsx(Os,{className:"sm:max-w-md",children:o==="review"?e.jsxs(e.Fragment,{children:[e.jsxs(Us,{children:[e.jsx(Bs,{className:"text-center",children:"How are you enjoying LevelUp?"}),e.jsx(Ir,{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(E=>e.jsx("button",{type:"button",onClick:()=>u(E),onMouseEnter:()=>m(E),onMouseLeave:()=>m(0),className:"p-1 transition-transform hover:scale-110",children:e.jsx(Ja,{className:Pt("h-8 w-8 transition-colors",(h||d)>=E?"fill-yellow-400 text-yellow-400":"text-muted-foreground")})},E))}),e.jsx(Rs,{placeholder:"Tell us about your experience (optional)",value:f,onChange:E=>g(E.target.value),rows:4,className:"resize-none"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx($,{variant:"outline",onClick:C,className:"flex-1",children:"Maybe Later"}),e.jsx($,{onClick:w,disabled:x||d===0,className:"flex-1",children:x?"Submitting...":"Submit Review"})]})]})]}):e.jsxs(e.Fragment,{children:[e.jsxs(Us,{children:[e.jsx(Bs,{className:"text-center",children:"🎉 Thank you!"}),e.jsx(Ir,{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($,{variant:"outline",onClick:()=>S(!1),className:"flex-1",children:"No Thanks"}),e.jsx($,{onClick:()=>S(!0),className:"flex-1",children:"Yes, Open Google"})]})]})]})})})]})};function xRs(s){const t="=".repeat((4-s.length%4)%4),n=(s+t).replace(/-/g,"+").replace(/_/g,"/"),r=window.atob(n),a=new Uint8Array(r.length);for(let i=0;i{if(!h){l(!1);return}(async()=>{try{const x="vapid_public_key";let y=localStorage.getItem(x);if(!y){const{data:w,error:S}=await q.functions.invoke("get-vapid-public-key",{body:{}});if(S)throw S;if(y=(w==null?void 0:w.vapidPublicKey)??null,!y)throw new Error("Missing VAPID public key");localStorage.setItem(x,y)}u(y);const v=await navigator.serviceWorker.register("/push-sw.js",{scope:"/push-notifications/"});c(v),n(Notification.permission);const b=await v.pushManager.getSubscription();a(!!b)}catch(x){console.error("Error initializing push notifications:",x)}finally{l(!1)}})()},[h]);const m=j.useCallback(async()=>{if(!h||!o||!s)return console.error("Push notifications not supported or user not logged in"),!1;if(!d)return re.error("Push notifications are not ready yet. Please try again in a moment."),!1;try{l(!0);const g=await o.pushManager.getSubscription();if(g){try{await g.unsubscribe()}catch(S){console.warn("Failed to unsubscribe existing push subscription:",S)}const{error:w}=await q.from("push_subscriptions").delete().eq("user_id",s.id);w&&console.warn("Failed to cleanup push_subscriptions rows:",w)}if(Notification.permission!=="granted"){const w=await Notification.requestPermission();if(n(w),w!=="granted")return w==="denied"?re.error("Notifications blocked. Please enable them in your browser settings (click the lock icon in the address bar)."):re.error("Notification permission was dismissed. Please try again."),!1}const x=xRs(d);let y;try{y=await o.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:x})}catch(w){console.error("PushManager.subscribe() failed:",w);const S=(w==null?void 0:w.message)||String(w);return S.includes("permission")?re.error("Push permission denied. Check your browser notification settings."):S.includes("key")||S.includes("VAPID")?re.error("Push configuration error. Please contact support."):S.includes("AbortError")?re.error("Push subscription was cancelled. Please try again."):re.error(`Failed to subscribe: ${S}`),!1}const v=y.toJSON(),{error:b}=await q.from("push_subscriptions").upsert({user_id:s.id,endpoint:v.endpoint,p256dh_key:v.keys.p256dh,auth_key:v.keys.auth},{onConflict:"user_id,endpoint"});if(b)throw console.error("Error saving subscription:",b),re.error("Failed to save notification preferences. Please try again."),b;return a(!0),re.success("Push notifications enabled!"),!0}catch(g){if(console.error("Error subscribing to push notifications:",g),!(g instanceof Error&&g.message.includes("toast"))){const x=g instanceof Error?g.message:"Unknown error";re.error("Failed to enable push notifications: "+x)}return!1}finally{l(!1)}},[h,o,s,d]),f=j.useCallback(async()=>{if(!o||!s)return!1;try{l(!0);const g=await o.pushManager.getSubscription();return g&&await g.unsubscribe(),await q.from("push_subscriptions").delete().eq("user_id",s.id),a(!1),re.success("Push notifications disabled"),!0}catch(g){console.error("Error unsubscribing:",g);const x=g instanceof Error?g.message:"Unknown error";return re.error("Failed to disable push notifications: "+x),!1}finally{l(!1)}},[o,s]);return{isSupported:h,permission:t,isSubscribed:r,isLoading:i,vapidPublicKey:d,subscribe:m,unsubscribe:f}}const d7e="push_notification_prompt_dismissed",yRs=["/dashboard","/admin"],vRs=()=>{const{user:s}=vs(),{isSupported:t,isSubscribed:n,isLoading:r,subscribe:a}=p7t(),i=fu(),[l,o]=j.useState(!1),[c,d]=j.useState(!1),u=yRs.some(f=>i.pathname===f||i.pathname.startsWith(`${f}/`));j.useEffect(()=>{if(u){o(!1);return}if(!s||!t||n||r||localStorage.getItem(`${d7e}_${s.id}`))return;const g=setTimeout(()=>{o(!0)},2e3);return()=>clearTimeout(g)},[s,t,n,r,u]);const h=async()=>{d(!0);const f=await a();d(!1),f&&(s&&localStorage.setItem(`${d7e}_${s.id}`,"true"),o(!1))},m=()=>{s&&localStorage.setItem(`${d7e}_${s.id}`,"true"),o(!1)};return!t||n||u?null:e.jsx(zs,{open:l,onOpenChange:f=>!f&&m(),children:e.jsxs(Os,{className:"sm:max-w-md",children:[e.jsxs(Us,{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(qy,{className:"h-6 w-6 text-primary"})}),e.jsx(Bs,{className:"text-center",children:"Stay in the Loop!"}),e.jsx(Ir,{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($,{onClick:h,disabled:c,className:"w-full",children:c?"Enabling...":"Enable Notifications"}),e.jsx($,{variant:"ghost",onClick:m,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."})]})})},Hyt=s=>{let t;const n=new Set,r=(d,u)=>{const h=typeof d=="function"?d(t):d;if(!Object.is(h,t)){const m=t;t=u??(typeof h!="object"||h===null)?h:Object.assign({},t,h),n.forEach(f=>f(t,m))}},a=()=>t,o={setState:r,getState:a,getInitialState:()=>c,subscribe:d=>(n.add(d),()=>n.delete(d))},c=t=s(r,a,o);return o},bRs=s=>s?Hyt(s):Hyt,_Rs=s=>s;function wRs(s,t=_Rs){const n=Gt.useSyncExternalStore(s.subscribe,Gt.useCallback(()=>t(s.getState()),[s,t]),Gt.useCallback(()=>t(s.getInitialState()),[s,t]));return Gt.useDebugValue(n),n}const Gyt=s=>{const t=bRs(s),n=r=>wRs(t,r);return Object.assign(n,t),n},jRs=s=>s?Gyt(s):Gyt;function NRs(s,t){let n;try{n=s()}catch{return}return{getItem:a=>{var i;const l=c=>c===null?null:JSON.parse(c,void 0),o=(i=n.getItem(a))!=null?i:null;return o instanceof Promise?o.then(l):l(o)},setItem:(a,i)=>n.setItem(a,JSON.stringify(i,void 0)),removeItem:a=>n.removeItem(a)}}const nGe=s=>t=>{try{const n=s(t);return n instanceof Promise?n:{then(r){return nGe(r)(n)},catch(r){return this}}}catch(n){return{then(r){return this},catch(r){return nGe(r)(n)}}}},kRs=(s,t)=>(n,r,a)=>{let i={storage:NRs(()=>window.localStorage),partialize:y=>y,version:0,merge:(y,v)=>({...v,...y}),...t},l=!1,o=0;const c=new Set,d=new Set;let u=i.storage;if(!u)return s((...y)=>{console.warn(`[zustand persist middleware] Unable to update item '${i.name}', the given storage is currently unavailable.`),n(...y)},r,a);const h=()=>{const y=i.partialize({...r()});return u.setItem(i.name,{state:y,version:i.version})},m=a.setState;a.setState=(y,v)=>(m(y,v),h());const f=s((...y)=>(n(...y),h()),r,a);a.getInitialState=()=>f;let g;const x=()=>{var y,v;if(!u)return;const b=++o;l=!1,c.forEach(S=>{var C;return S((C=r())!=null?C:f)});const w=((v=i.onRehydrateStorage)==null?void 0:v.call(i,(y=r())!=null?y:f))||void 0;return nGe(u.getItem.bind(u))(i.name).then(S=>{if(S)if(typeof S.version=="number"&&S.version!==i.version){if(i.migrate){const C=i.migrate(S.state,S.version);return C instanceof Promise?C.then(E=>[!0,E]):[!0,C]}console.error("State loaded from storage couldn't be migrated since no migrate function was provided")}else return[!1,S.state];return[!1,void 0]}).then(S=>{var C;if(b!==o)return;const[E,I]=S;if(g=i.merge(I,(C=r())!=null?C:f),n(g,!0),E)return h()}).then(()=>{b===o&&(w==null||w(r(),void 0),g=r(),l=!0,d.forEach(S=>S(g)))}).catch(S=>{b===o&&(w==null||w(void 0,S))})};return a.persist={setOptions:y=>{i={...i,...y},y.storage&&(u=y.storage)},clearStorage:()=>{++o,u==null||u.removeItem(i.name)},getOptions:()=>i,rehydrate:()=>x(),hasHydrated:()=>l,onHydrate:y=>(c.add(y),()=>{c.delete(y)}),onFinishHydration:y=>(d.add(y),()=>{d.delete(y)})},i.skipHydration||x(),g||f},SRs=kRs,VLe=jRs()(SRs((s,t)=>({cartItems:[],addToCart:(n,r,a=1,i)=>{s(l=>{const o=l.cartItems.findIndex(c=>{var d;return c.product.id===n.id&&((d=c.variant)==null?void 0:d.id)===(r==null?void 0:r.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:n,variant:r,quantity:a,artworkUrl:i}]}})},removeFromCart:(n,r)=>{s(a=>({cartItems:a.cartItems.filter(i=>{var l;return!(i.product.id===n&&((l=i.variant)==null?void 0:l.id)===r)})}))},updateQuantity:(n,r,a)=>{s(i=>({cartItems:i.cartItems.map(l=>{var o;return l.product.id===n&&((o=l.variant)==null?void 0:o.id)===r?{...l,quantity:Math.max(1,a)}:l})}))},updateArtwork:(n,r,a)=>{s(i=>({cartItems:i.cartItems.map(l=>{var o;return l.product.id===n&&((o=l.variant)==null?void 0:o.id)===r?{...l,artworkUrl:a}:l})}))},clearCart:()=>s({cartItems:[]}),getItemPrice:n=>{const r=Number(n.product.base_price),a=n.variant?Number(n.variant.price_adjustment):0;return r+a},getSubtotal:()=>{const{cartItems:n,getItemPrice:r}=t();return n.reduce((a,i)=>a+r(i)*i.quantity,0)},getShippingTotal:()=>{const{cartItems:n}=t();return n.reduce((r,a)=>r+Number(a.product.shipping_fee)*a.quantity,0)},getTotal:()=>{const{getSubtotal:n,getShippingTotal:r}=t();return n()+r()}}),{name:"marketplace-cart",partialize:s=>({cartItems:s.cartItems})}));function CRs({activeCategory:s,currentCategory:t,onSelect:n,onHover:r,badgeCounts:a,categories:i=BLe}){return e.jsx("nav",{"aria-label":"Primary",className:"flex flex-col gap-1 p-2",children:i.map(l=>{const o=l.icon,c=s===l.id,d=t===l.id,u=(a==null?void 0:a[l.id])??0,h=`hsl(var(--${l.accent}))`,m=c||d;return e.jsxs("button",{type:"button",onClick:()=>n(l.id),onMouseEnter:()=>r==null?void 0:r(l.id),"aria-expanded":l.route?void 0:c,"aria-controls":l.route?void 0:"primary-nav-flyout","aria-current":d?"page":void 0,style:{color:m?h:void 0,backgroundColor:m?`hsl(var(--${l.accent}) / 0.12)`:void 0},className:Pt("group relative flex flex-col items-center gap-1 rounded-xl px-1 py-2.5 text-[11px] font-medium transition-colors","text-sidebar-foreground/70 hover:bg-sidebar-accent/10","focus:outline-none focus-visible:ring-2 focus-visible:ring-primary"),children:[d&&e.jsx("span",{className:"absolute left-0 top-1/2 h-6 w-1 -translate-y-1/2 rounded-r",style:{backgroundColor:h}}),e.jsxs("span",{className:"relative",children:[e.jsx(o,{className:"h-5 w-5 transition-colors",style:{color:h}}),u>0&&e.jsx("span",{className:"absolute -right-1.5 -top-1 flex h-4 min-w-4 items-center justify-center rounded-full px-1 text-[9px] font-bold text-primary-foreground",style:{backgroundColor:h},children:u>9?"9+":u})]}),e.jsx("span",{className:"leading-tight",children:l.label})]},l.id)})})}function ARs({category:s,top:t,left:n,onClose:r,onNavigate:a,isFavorite:i,favorites:l,onToggleFavorite:o,isCurrent:c,badgeCounts:d}){const u=j.useRef(null);j.useEffect(()=>{const m=g=>{g.key==="Escape"&&r()},f=g=>{var y;if(!u.current)return;const x=g.target;!u.current.contains(x)&&!((y=x==null?void 0:x.closest)!=null&&y.call(x,"[data-nav-rail]"))&&r()};return document.addEventListener("keydown",m),document.addEventListener("mousedown",f),()=>{document.removeEventListener("keydown",m),document.removeEventListener("mousedown",f)}},[r]);const h=m=>{const f=m.icon,g=m.badgeKey?(d==null?void 0:d[m.badgeKey])??0:0;return e.jsxs("div",{className:Pt("group flex items-start gap-3 rounded-lg p-2 transition-colors hover:bg-muted",c(m)&&"bg-muted"),children:[e.jsxs("button",{type:"button",onClick:()=>a(m),className:"flex flex-1 items-start gap-3 text-left focus:outline-none focus-visible:ring-2 focus-visible:ring-primary rounded-md",children:[e.jsx("span",{className:"mt-0.5 flex h-8 w-8 shrink-0 items-center justify-center rounded-lg bg-primary/10 text-primary",children:e.jsx(f,{className:"h-4 w-4"})}),e.jsxs("span",{className:"min-w-0",children:[e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"text-sm font-medium text-foreground",children:m.label}),m.badge==="new"&&e.jsx("span",{className:"rounded bg-primary px-1 py-px text-[9px] font-bold uppercase tracking-wide text-primary-foreground",children:"New"}),m.badge==="beta"&&e.jsx("span",{className:"rounded border border-amber-500 bg-amber-500/10 px-1 py-px text-[9px] font-bold uppercase tracking-wide text-amber-600 dark:text-amber-400",children:"Beta"}),m.locked&&e.jsx(pc,{className:"h-3 w-3 text-muted-foreground","aria-label":"Upgrade required"}),g>0&&e.jsx("span",{className:"flex h-4 min-w-4 items-center justify-center rounded-full bg-muted-foreground/15 px-1 text-[10px] font-medium text-muted-foreground",children:g>9?"9+":g})]}),m.description&&e.jsx("span",{className:"mt-0.5 block text-xs leading-snug text-muted-foreground line-clamp-2",children:m.description})]})]}),e.jsx("button",{type:"button","aria-label":i(m)?`Remove ${m.label} from favorites`:`Add ${m.label} to favorites`,onClick:x=>{x.stopPropagation(),o(m)},className:Pt("mt-1 rounded p-1 opacity-0 transition-opacity focus:outline-none focus-visible:ring-2 focus-visible:ring-primary group-hover:opacity-100",i(m)&&"opacity-100 text-primary",!i(m)&&"text-muted-foreground/60 hover:text-primary"),children:e.jsx(M0,{className:Pt("h-4 w-4",i(m)&&"fill-current")})})]},m.id)};return e.jsxs("div",{id:"primary-nav-flyout",ref:u,role:"dialog","aria-label":`${s.label} navigation`,style:{top:t,left:n,maxHeight:`calc(100vh - ${t+16}px)`},className:"fixed z-40 hidden w-[min(720px,calc(100vw-8rem))] animate-in fade-in-0 slide-in-from-left-2 duration-200 motion-reduce:animate-none overflow-hidden rounded-2xl border border-border bg-card shadow-2xl md:block",children:[e.jsx("div",{className:"flex items-center justify-between border-b border-border px-5 py-3",children:e.jsx("h2",{className:"text-sm font-semibold text-foreground",children:s.label})}),e.jsxs("div",{className:"max-h-[70vh] overflow-y-auto p-4",children:[l.length>0&&e.jsxs("section",{className:"mb-4",children:[e.jsxs("h3",{className:"mb-2 flex items-center gap-1.5 px-2 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground",children:[e.jsx(M0,{className:"h-3 w-3 fill-current text-primary"})," My Favorites"]}),e.jsx("div",{className:"grid grid-cols-1 gap-1 sm:grid-cols-2",children:l.map(h)})]}),s.sections.map(m=>e.jsxs("section",{className:"mb-4 last:mb-0",children:[e.jsx("h3",{className:"mb-2 px-2 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground",children:m.title}),e.jsx("div",{className:"grid grid-cols-1 gap-1 sm:grid-cols-2",children:m.items.map(h)})]},m.title)),s.sections.length===0&&e.jsx("p",{className:"px-2 py-6 text-sm text-muted-foreground",children:"Nothing here yet."})]})]})}function ERs({categories:s,railCategories:t=BLe,currentCategory:n,onNavigate:r,onNavigateRoute:a,isCurrent:i,badgeCounts:l,isFavorite:o,onToggleFavorite:c}){const[d,u]=j.useState(n);return e.jsx("nav",{"aria-label":"Primary",className:"p-2",children:t.map(h=>{const m=h.icon;if(h.route)return e.jsxs("button",{type:"button",onClick:()=>a(h.route),className:Pt("flex w-full items-center gap-3 rounded-lg px-3 py-3 text-sm font-medium text-sidebar-foreground hover:bg-sidebar-accent",n===h.id&&"bg-sidebar-accent"),children:[e.jsx(m,{className:"h-4 w-4",style:{color:`hsl(var(--${h.accent}))`}}),h.label]},h.id);const f=s.find(x=>x.id===h.id),g=d===h.id;return e.jsxs("div",{children:[e.jsxs("button",{type:"button","aria-expanded":g,onClick:()=>u(g?null:h.id),className:Pt("flex w-full items-center gap-3 rounded-lg px-3 py-3 text-sm font-medium text-sidebar-foreground hover:bg-sidebar-accent",n===h.id&&"text-primary"),children:[e.jsx(m,{className:"h-4 w-4",style:{color:`hsl(var(--${h.accent}))`}}),h.label,e.jsx(Tl,{className:Pt("ml-auto h-4 w-4 transition-transform",g&&"rotate-180")})]}),g&&f&&e.jsx("div",{className:"space-y-3 pb-3 pl-4 pr-1",children:f.sections.map(x=>e.jsxs("div",{children:[e.jsx("p",{className:"px-2 py-1 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground",children:x.title}),x.items.map(y=>{const v=y.icon,b=y.badgeKey?(l==null?void 0:l[y.badgeKey])??0:0,w=(o==null?void 0:o(y))??!1;return e.jsxs("div",{className:Pt("flex w-full items-center gap-2 rounded-md pr-1 hover:bg-sidebar-accent",i(y)&&"bg-sidebar-accent"),children:[e.jsxs("button",{type:"button",onClick:()=>r(y),className:"flex flex-1 items-center gap-2 px-2 py-2 text-left text-sm text-sidebar-foreground",children:[e.jsx(v,{className:"h-4 w-4 shrink-0"}),e.jsx("span",{className:"truncate",children:y.label}),b>0&&e.jsx("span",{className:"ml-auto flex h-5 w-5 items-center justify-center rounded-full bg-muted text-xs text-muted-foreground",children:b>9?"9+":b})]}),c&&e.jsx("button",{type:"button","aria-label":w?`Remove ${y.label} from favorites`:`Add ${y.label} to favorites`,onClick:()=>c(y),className:Pt("rounded p-2",w?"text-primary":"text-muted-foreground/60"),children:e.jsx(M0,{className:Pt("h-4 w-4",w&&"fill-current")})})]},y.id)})]},x.title))})]},h.id)})})}function g7t(){const s=Qn(),t=fu(),n=Kzt(),r=j.useCallback(o=>Wzt(o,n.ctx),[n.ctx]),a=j.useMemo(()=>{if(t.pathname.startsWith("/apps"))return"apps";if(t.pathname==="/dashboard")return"home";let o=null;for(const c of n.destinations){if(c.external)continue;const d=r(c);d!=="/"&&t.pathname.startsWith(d)&&(!o||d.length>o.len)&&(o={id:c.primaryCategory,len:d.length})}return(o==null?void 0:o.id)??null},[t.pathname,n.destinations,r]),i=j.useCallback(o=>!o.external&&t.pathname===r(o),[t.pathname,r]),l=j.useCallback(o=>{const c=r(o);if(o.external||o.openInNewTab){window.open(c,"_blank","noopener,noreferrer");return}s(c)},[s,r]);return{nav:n,navigate:s,currentCategory:a,isCurrent:i,go:l}}function TRs({communityUnreadCount:s=0,wishlistOpenCount:t=0,flyoutTop:n=64,flyoutLeft:r=80}){const{nav:a,navigate:i,currentCategory:l,isCurrent:o,go:c}=g7t(),[d,u]=j.useState(null),h=j.useRef(null),m=x=>{const y=BLe.find(v=>v.id===x);if(y!=null&&y.route){u(null),i(y.route);return}u(v=>v===x?null:x)},f=d?a.categoryMap.get(d):void 0,g={more:s+t};return e.jsxs("div",{"data-nav-rail":!0,className:"flex h-full flex-col",onMouseLeave:()=>{h.current&&window.clearTimeout(h.current),h.current=window.setTimeout(()=>u(null),250)},onMouseEnter:()=>{h.current&&window.clearTimeout(h.current)},children:[e.jsx(CRs,{activeCategory:d,currentCategory:l,onSelect:m,categories:a.railCategories,badgeCounts:g}),f&&e.jsx(ARs,{category:f,top:n,left:r,onClose:()=>u(null),onNavigate:x=>{u(null),c(x)},isFavorite:a.isFavorite,favorites:a.favoritesFor(f.id),onToggleFavorite:x=>a.toggleFavorite(a.favoriteKey(x)),isCurrent:o,badgeCounts:{community:s,wishlist:t}})]})}function MRs({communityUnreadCount:s=0,wishlistOpenCount:t=0,onNavigated:n}){const{nav:r,navigate:a,currentCategory:i,isCurrent:l,go:o}=g7t();return e.jsx(ERs,{categories:r.categories,railCategories:r.railCategories,currentCategory:i,isCurrent:l,isFavorite:r.isFavorite,onToggleFavorite:c=>r.toggleFavorite(r.favoriteKey(c)),badgeCounts:{community:s,wishlist:t},onNavigate:c=>{o(c),n==null||n()},onNavigateRoute:c=>{a(c),n==null||n()}})}const PRs=({bannerHeight:s,communityUnreadCount:t,wishlistOpenCount:n,isTrial:r,isExpired:a})=>{const i=Qn();return e.jsxs("div",{className:"flex h-full flex-col",children:[e.jsx("div",{className:"flex h-16 shrink-0 items-center justify-center border-b border-sidebar-border",children:e.jsx("button",{type:"button",onClick:()=>i("/dashboard"),"aria-label":"LevelUp home",children:e.jsx("img",{src:g5s,alt:"LevelUp",className:"h-8 w-auto"})})}),e.jsxs(uo,{className:"flex-1 [&_[data-radix-scroll-area-scrollbar]]:w-1.5",children:[e.jsx(TRs,{communityUnreadCount:t,wishlistOpenCount:n,flyoutTop:s+64,flyoutLeft:80}),r&&!a&&e.jsx("div",{className:"p-2",children:e.jsxs("button",{type:"button",onClick:()=>i("/subscription"),className:"flex w-full flex-col items-center gap-1 rounded-xl border border-amber-500/30 bg-amber-500/10 px-1 py-2 text-[10px] font-semibold text-amber-600 dark:text-amber-400",children:[e.jsx(Nn,{className:"h-4 w-4"}),"Upgrade"]})})]})]})},IRs=({isTrial:s,isExpired:t,expiresAt:n,communityUnreadCount:r,wishlistOpenCount:a,pathname:i,onSignOut:l,onNavigated:o})=>{const c=Qn();return e.jsxs("div",{className:"flex h-full flex-col",children:[e.jsx("div",{className:"flex items-center gap-2 border-b border-sidebar-border p-3",children:e.jsx("img",{src:p5s,alt:"LevelUp",className:"h-8 w-auto"})}),e.jsxs(uo,{className:"flex-1",children:[s&&!t&&e.jsx("div",{className:"p-2",children:e.jsx("button",{type:"button",onClick:()=>{c("/subscription"),o==null||o()},className:Pt("relative mb-1 w-full overflow-hidden rounded-md p-[1.5px]","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(Nn,{className:"h-4 w-4 text-amber-500"}),e.jsx("span",{className:"flex-1 text-left",children:"Ready to Upgrade?"}),n&&e.jsxs("span",{className:"rounded border border-amber-500/30 bg-amber-500/15 px-1.5 py-0.5 text-[10px] font-bold uppercase tracking-wide text-amber-600 dark:text-amber-400",children:[Math.max(0,Math.ceil((Date.parse(n)-Date.now())/864e5)),"d left"]})]})})}),e.jsx(MRs,{communityUnreadCount:r,wishlistOpenCount:a,onNavigated:o})]}),e.jsxs("div",{className:"border-t border-sidebar-border p-3",children:[e.jsxs($,{variant:"ghost",size:"sm",className:Pt("w-full justify-start gap-2 text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",i==="/profile"&&"bg-sidebar-accent text-sidebar-accent-foreground"),onClick:()=>{c("/profile"),o==null||o()},children:[e.jsx(sl,{className:"h-4 w-4"}),"Profile"]}),e.jsxs($,{variant:"ghost",size:"sm",className:"w-full justify-start gap-2 text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",onClick:l,children:[e.jsx(Wz,{className:"h-4 w-4"}),"Sign Out"]})]})]})},Vs=({children:s,title:t})=>{var J;const{user:n,signOut:r,isAdmin:a,isBrokerageManager:i,isCoach:l,brokerageId:o}=vs(),{isAssistant:c,actingAsAgent:d,hasPermission:u}=Iae();_Le();const{isImpersonating:h}=pLe(),f=(c&&!!d?40:0)+(h?40:0),{avatarUrl:g}=$Ot(n==null?void 0:n.id),{isTrial:x,isExpired:y,expiresAt:v}=VCs(n==null?void 0:n.id),{isMarketplaceEnabled:b}=Rae(),{currentBrief:w,shouldShowPopup:S,hasUnseenBrief:C,openBrief:E,closeBrief:I,dismissBrief:P}=hRs(),{unreadCount:R}=HCs(),{openCount:D}=GCs();Hw();const U=VLe(ce=>ce.cartItems).reduce((ce,_e)=>ce+_e.quantity,0),{hasLeadSite:W}=ng();OLe(!W);const V=Qn(),G=fu(),[Y,X]=j.useState(null);j.useEffect(()=>{n!=null&&n.id&&q.from("profiles").select("name").eq("id",n.id).single().then(({data:ce})=>{ce!=null&&ce.name&&X(ce.name)})},[n==null?void 0:n.id]);const ae=Y||((J=n==null?void 0:n.user_metadata)==null?void 0:J.name)||(n==null?void 0:n.email)||"User",[ie,ne]=j.useState(!1),te=ce=>ce.split(" ").map(_e=>_e[0]).join("").toUpperCase().slice(0,2);return e.jsx(jk,{children:e.jsxs("div",{className:"min-h-screen bg-background flex",children:[x&&y&&G.pathname!=="/subscription"&&e.jsx(D6s,{}),typeof document<"u"&&wv.createPortal(e.jsx("aside",{className:"hidden md:flex flex-col bg-card border-r border-border fixed left-0 z-30 !pointer-events-auto w-20",style:{top:`${f}px`,height:`calc(100vh - ${f}px)`},children:e.jsx(PRs,{bannerHeight:f,communityUnreadCount:R,wishlistOpenCount:D,isTrial:x,isExpired:y})}),document.body),e.jsxs("div",{className:"flex-1 flex flex-col overflow-hidden md:ml-20",style:{height:`calc(100vh - ${f}px)`,marginTop:`${f}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(Wy,{open:ie,onOpenChange:ne,children:[e.jsx(Fae,{asChild:!0,children:e.jsx($,{variant:"ghost",size:"icon",className:"md:hidden",children:e.jsx(IE,{className:"h-5 w-5"})})}),e.jsx(py,{side:"left",className:"w-72 p-0 bg-card",children:e.jsx(IRs,{isTrial:x,isExpired:y,expiresAt:v,communityUnreadCount:R,wishlistOpenCount:D,pathname:G.pathname,onSignOut:r,onNavigated:()=>ne(!1)})})]}),e.jsx("div",{className:"flex-1 md:hidden",children:e.jsx("img",{src:x5s,alt:"LevelUp",className:"h-8 w-auto"})}),e.jsx("div",{className:"hidden md:flex flex-1 justify-center",children:e.jsx(Vyt,{})}),e.jsxs("div",{className:"flex items-center gap-3 ml-auto",children:[x&&!y&&v&&e.jsx(R6s,{expiresAt:v,className:"hidden lg:flex"}),e.jsx("div",{className:"md:hidden",children:e.jsx(Vyt,{})}),w&&e.jsx(F6s,{hasUnseenBrief:C,onClick:E}),b&&e.jsxs($,{variant:"ghost",size:"icon",className:"relative",onClick:()=>V("/marketplace/cart"),children:[e.jsx(nC,{className:"h-5 w-5"}),U>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:U>99?"99+":U})]}),e.jsx($,{variant:"ghost",size:"icon","aria-label":"My Calendar",title:"My Calendar",onClick:()=>V("/mission-control/calendar"),children:e.jsx(Kc,{className:"h-5 w-5"})}),e.jsx(FLs,{}),e.jsx(ZHe,{}),e.jsxs("span",{className:"hidden sm:block text-sm font-medium text-foreground",children:["Hello, ",ae.split(" ")[0],"!"]}),e.jsxs(Uu,{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(Oa,{className:"h-9 w-9 cursor-pointer hover:opacity-80 transition-opacity",children:[e.jsx(Li,{src:g||void 0}),e.jsx(za,{className:"bg-primary text-primary-foreground font-medium text-sm",children:te(ae)})]})})}),e.jsxs(Eu,{align:"end",className:"w-48",children:[e.jsxs(ja,{onClick:()=>V("/profile"),className:"cursor-pointer",children:[e.jsx(sl,{className:"h-4 w-4 mr-2"}),"Profile"]}),e.jsxs(ja,{onClick:()=>V("/mission-control/integrations"),className:"cursor-pointer",children:[e.jsx(g2,{className:"h-4 w-4 mr-2"}),"Integrations"]}),e.jsxs(ja,{onClick:()=>V("/mission-control/browser-extension"),className:"cursor-pointer",children:[e.jsx(g2,{className:"h-4 w-4 mr-2"}),"Browser Extension"]}),e.jsx(R0,{}),e.jsxs(ja,{onClick:r,className:"cursor-pointer text-destructive focus:text-destructive",children:[e.jsx(Wz,{className:"h-4 w-4 mr-2"}),"Sign Out"]})]})]})]})]})}),e.jsx(fRs,{children:e.jsx("main",{className:"p-4 sm:p-6 lg:p-8 overflow-x-hidden",children:s})}),w&&e.jsx(uRs,{brief:w,open:S,onClose:I,onDismiss:P}),e.jsx(mRs,{}),e.jsx(gRs,{}),e.jsx(vRs,{})]})]})})},wn=({children:s,requireAdmin:t=!1,requireBrokerageManager:n=!1})=>{const{user:r,loading:a,rolesLoading:i,isAdmin:l,isBrokerageManager:o}=vs(),c=fu(),d=jC();if(a||(t||n)&&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(!r){const u=c.pathname+c.search+c.hash;return u&&u!=="/auth"&&sessionStorage.setItem("redirectAfterLogin",u),e.jsx(Fd,{to:"/auth",replace:!0})}if(t&&!l)return e.jsx(Fd,{to:"/dashboard",replace:!0});if(n&&!o&&!l)return e.jsx(Fd,{to:"/dashboard",replace:!0});if(d.isRestricted&&!d.isLoading){const u=zOt(c.pathname);if(u&&!d.hasFeature(u))return e.jsx(Vs,{title:"Upgrade required",children:e.jsx(qCs,{featureKey:u})})}return e.jsx(e.Fragment,{children:s})};function u7e({children:s}){const{isAdmin:t,loading:n,rolesLoading:r}=vs(),{isFeatureEnabled:a,isLoading:i}=Rae();return n||r||i?e.jsx("div",{className:"flex min-h-[50vh] items-center justify-center",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}):!t&&!a("staging_studio_enabled")?e.jsx(Fd,{to:"/apps",replace:!0}):e.jsx(Vs,{title:"Staging Studio",children:e.jsx(j.Suspense,{fallback:e.jsx("div",{className:"flex min-h-[50vh] items-center justify-center",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}),children:s})})}var qtt={};(function s(t,n,r,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 ne=new OffscreenCanvas(1,1),te=ne.getContext("2d");te.fillRect(0,0,1,1);var J=ne.transferToImageBitmap();te.createPattern(J,"no-repeat")}catch{return!1}return!0}();function c(){}function d(ne){var te=n.exports.Promise,J=te!==void 0?te:t.Promise;return typeof J=="function"?new J(ne):(ne(c,c),null)}var u=function(ne,te){return{transform:function(J){if(ne)return J;if(te.has(J))return te.get(J);var ce=new OffscreenCanvas(J.width,J.height),_e=ce.getContext("2d");return _e.drawImage(J,0,0),te.set(J,ce),ce},clear:function(){te.clear()}}}(o,new Map),h=function(){var ne=Math.floor(16.666666666666668),te,J,ce={},_e=0;return typeof requestAnimationFrame=="function"&&typeof cancelAnimationFrame=="function"?(te=function(he){var ue=Math.random();return ce[ue]=requestAnimationFrame(function ve(Ee){_e===Ee||_e+ne-1{const{data:t,error:n}=await q.from("celebration_queue").select("*").eq("user_id",s.id).is("seen_at",null).order("created_at",{ascending:!0});if(n)throw n;return t},enabled:!!(s!=null&&s.id),refetchOnWindowFocus:!0,staleTime:0})}function RRs(){const s=Vt();return ft({mutationFn:async t=>{const{error:n}=await q.from("celebration_queue").update({seen_at:new Date().toISOString()}).eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["celebrations"]})}})}function DRs(){const s=Vt(),{user:t}=vs();return ft({mutationFn:async n=>{const{error:r}=await q.from("celebration_queue").insert({user_id:n.user_id,celebration_type:n.celebration_type,title:n.title,message:n.message||null,points_amount:n.points_amount||null,created_by:t==null?void 0:t.id});if(r)throw r},onSuccess:()=>{s.invalidateQueries({queryKey:["celebrations"]})}})}const FRs={points_earned:Kl,listing_created:va,deal_closed:ru,custom:Ja},Kyt={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"},Yyt=()=>{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 ORs(){const{user:s}=vs(),t=Vt(),{data:n}=LRs(),r=RRs(),[a,i]=j.useState(null),[l,o]=j.useState(!1),c=j.useCallback(()=>{const f=Date.now()+3e3,g={startVelocity:30,spread:360,ticks:60,zIndex:9999},x=(v,b)=>Math.random()*(b-v)+v,y=setInterval(()=>{const v=f-Date.now();if(v<=0){clearInterval(y);return}const b=50*(v/3e3);Wyt({...g,particleCount:b,origin:{x:x(.1,.3),y:Math.random()-.2},colors:["#ff6b6b","#feca57","#48dbfb","#ff9ff3","#54a0ff","#5f27cd"]}),Wyt({...g,particleCount:b,origin:{x:x(.7,.9),y:Math.random()-.2},colors:["#ff6b6b","#feca57","#48dbfb","#ff9ff3","#54a0ff","#5f27cd"]})},250)},[]);j.useEffect(()=>{Yyt()||n&&n.length>0&&!a&&(i(n[0]),o(!0),setTimeout(c,100))},[n,a,c]);const d=async()=>{if(a){const m=a.id;o(!1),i(null),t.setQueryData(["celebrations","pending",s==null?void 0:s.id],f=>(f==null?void 0:f.filter(g=>g.id!==m))??[]),await r.mutateAsync(m)}};if(Yyt()||!a)return null;const u=FRs[a.celebration_type]||Ja,h=Kyt[a.celebration_type]||Kyt.custom;return e.jsx(zs,{open:l,onOpenChange:m=>!m&&d(),children:e.jsxs(Os,{className:"sm:max-w-md text-center border-0 overflow-hidden",children:[e.jsx("div",{className:`absolute inset-0 bg-gradient-to-br ${h} 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 ${h} flex items-center justify-center animate-bounce`,children:e.jsx(u,{className:"w-10 h-10 text-white"})})}),e.jsxs("div",{className:"flex justify-center gap-1 mb-4",children:[e.jsx(Nn,{className:"w-5 h-5 text-yellow-500 animate-pulse"}),e.jsx(Nn,{className:"w-5 h-5 text-yellow-500 animate-pulse delay-75"}),e.jsx(Nn,{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($,{onClick:d,className:"w-full",size:"lg",children:"Awesome! 🙌"}),n&&n.length>1&&e.jsxs("p",{className:"text-sm text-muted-foreground mt-3",children:["+",n.length-1," more celebration",n.length>2?"s":""," waiting"]})]})]})})}function yn({className:s,...t}){return e.jsx("div",{className:Pt("animate-pulse rounded-md bg-muted",s),...t})}var zRs=Object.defineProperty,aK=(s,t)=>zRs(s,"name",{value:t,configurable:!0}),Vtt="Tabs",[BRs,nSr]=tp(Vtt,[r6]),x7t=r6(),[$Rs,Htt]=BRs(Vtt),URs=j.forwardRef(aK(function(t,n){const{__scopeTabs:r,value:a,onValueChange:i,defaultValue:l,orientation:o="horizontal",dir:c,activationMode:d="automatic",...u}=t,h=l3(c),[m,f]=fy({prop:a,onChange:i,defaultProp:l??"",caller:Vtt});return e.jsx($Rs,{scope:r,baseId:my(),value:m,onValueChange:f,orientation:o,dir:h,activationMode:d,children:e.jsx(Ei.div,{dir:h,"data-orientation":o,...u,ref:n})})},"Tabs")),qRs="TabsList",VRs=j.forwardRef(aK(function(t,n){const{__scopeTabs:r,loop:a=!0,...i}=t,l=Htt(qRs,r),o=x7t(r);return e.jsx(xLe,{asChild:!0,...o,orientation:l.orientation,dir:l.dir,loop:a,children:e.jsx(Ei.div,{role:"tablist","aria-orientation":l.orientation,...i,ref:n})})},"TabsList")),HRs="TabsTrigger",GRs=j.forwardRef(aK(function(t,n){const{__scopeTabs:r,value:a,disabled:i=!1,...l}=t,o=Htt(HRs,r),c=x7t(r),d=Gtt(o.baseId,a),u=Wtt(o.baseId,a),h=a===o.value;return e.jsx(yLe,{asChild:!0,...c,focusable:!i,active:h,children:e.jsx(Ei.button,{type:"button",role:"tab","aria-selected":h,"aria-controls":u,"data-state":h?"active":"inactive","data-disabled":i?"":void 0,disabled:i,id:d,...l,ref:n,onMouseDown:Ra(t.onMouseDown,m=>{!i&&m.button===0&&m.ctrlKey===!1?o.onValueChange(a):m.preventDefault()}),onKeyDown:Ra(t.onKeyDown,m=>{i||m.target!==m.currentTarget||[" ","Enter"].includes(m.key)&&o.onValueChange(a)}),onFocus:Ra(t.onFocus,()=>{const m=o.activationMode!=="manual";!h&&!i&&m&&o.onValueChange(a)})})})},"TabsTrigger")),WRs="TabsContent",KRs=j.forwardRef(aK(function(t,n){const{__scopeTabs:r,value:a,forceMount:i,children:l,...o}=t,c=Htt(WRs,r),d=Gtt(c.baseId,a),u=Wtt(c.baseId,a),h=a===c.value,m=j.useRef(h);return j.useEffect(()=>{const f=requestAnimationFrame(()=>m.current=!1);return()=>cancelAnimationFrame(f)},[]),e.jsx(xy,{present:i||h,children:({present:f})=>e.jsx(Ei.div,{"data-state":h?"active":"inactive","data-orientation":c.orientation,role:"tabpanel","aria-labelledby":d,hidden:!f,id:u,tabIndex:0,...o,ref:n,style:{...t.style,animationDuration:m.current?"0s":void 0},children:f&&l})})},"TabsContent"));function Gtt(s,t){return`${s}-trigger-${t}`}aK(Gtt,"makeTriggerId");function Wtt(s,t){return`${s}-content-${t}`}aK(Wtt,"makeContentId");var YRs=URs,y7t=VRs,v7t=GRs,b7t=KRs;const ha=YRs,ma=j.forwardRef(({className:s,...t},n)=>e.jsx(y7t,{ref:n,className:Pt("inline-flex h-10 items-center justify-center rounded-md bg-muted p-1 text-muted-foreground",s),...t}));ma.displayName=y7t.displayName;const Zt=j.forwardRef(({className:s,...t},n)=>e.jsx(v7t,{ref:n,className:Pt("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}));Zt.displayName=v7t.displayName;const Xt=j.forwardRef(({className:s,...t},n)=>e.jsx(b7t,{ref:n,className:Pt("mt-2 ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",s),...t}));Xt.displayName=b7t.displayName;const nse="#0d0d0d",IEe="#1a1a1a",ub="#c9a84c",Hae="#f0d78c",Y4={captured:"lup_lead_captured_v1",stickyDismissed:"lup_sticky_dismissed_v1",exitShown:"lup_exit_shown_v1",savedListings:"lup_saved_listings_v1"};async function HLe(s){const t={...s,source_page:typeof window<"u"?window.location.pathname:null,user_agent:typeof navigator<"u"?navigator.userAgent:null,referrer:typeof document<"u"?document.referrer:null},{data:n,error:r}=await q.functions.invoke("public-site-lead",{body:t});if(r)throw r;try{localStorage.setItem(Y4.captured,JSON.stringify({email:s.email,ts:Date.now()}))}catch{}return n}function Ktt(){try{return!!localStorage.getItem(Y4.captured)}catch{return!1}}function ZRs(){try{const s=localStorage.getItem(Y4.captured);return s?JSON.parse(s).email??null:null}catch{return null}}function Ytt({open:s,onClose:t,children:n}){return j.useEffect(()=>{if(!s)return;const r=document.body.style.overflow;return document.body.style.overflow="hidden",()=>{document.body.style.overflow=r}},[s]),s?wv.createPortal(e.jsx("div",{className:"fixed inset-0 z-[100] flex items-center justify-center p-4 animate-in fade-in",style:{background:"rgba(0,0,0,0.82)",backdropFilter:"blur(6px)"},onClick:t,children:e.jsxs("div",{onClick:r=>r.stopPropagation(),className:"relative w-full max-w-md rounded-2xl overflow-hidden animate-in zoom-in-95",style:{background:`linear-gradient(180deg, ${IEe} 0%, ${nse} 100%)`,border:`1px solid ${ub}33`,boxShadow:`0 30px 80px rgba(0,0,0,0.6), 0 0 0 1px ${ub}22 inset`},children:[e.jsx("button",{onClick:t,className:"absolute right-4 top-4 z-10 rounded-full p-2 text-white/60 hover:text-white hover:bg-white/10 transition","aria-label":"Close",children:e.jsx(gr,{className:"h-4 w-4"})}),n]})}),document.body):null}function Ztt(){const[s,t]=j.useState({first_name:"",email:"",phone:"",area:""}),[n,r]=j.useState(!1),[a,i]=j.useState("");return{values:s,setValues:t,loading:n,setLoading:r,honeypot:a,setHoneypot:i}}function Xtt({values:s,setValues:t,honeypot:n,setHoneypot:r,showPhone:a=!0,showArea:i=!0,areaPlaceholder:l="City, ZIP, or neighborhood"}){const o="w-full rounded-lg px-11 py-3 text-sm text-white placeholder:text-white/40 border transition focus:outline-none",c={background:"rgba(255,255,255,0.04)",borderColor:"rgba(255,255,255,0.12)"};return e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"relative",children:[e.jsx(sl,{className:"absolute left-3.5 top-1/2 -translate-y-1/2 h-4 w-4 text-white/40"}),e.jsx("input",{type:"text",placeholder:"First name",value:s.first_name,onChange:d=>t({...s,first_name:d.target.value}),className:o,style:c})]}),e.jsxs("div",{className:"relative",children:[e.jsx(mn,{className:"absolute left-3.5 top-1/2 -translate-y-1/2 h-4 w-4 text-white/40"}),e.jsx("input",{type:"email",required:!0,placeholder:"Email address",value:s.email,onChange:d=>t({...s,email:d.target.value}),className:o,style:c})]}),a&&e.jsxs("div",{className:"relative",children:[e.jsx(Da,{className:"absolute left-3.5 top-1/2 -translate-y-1/2 h-4 w-4 text-white/40"}),e.jsx("input",{type:"tel",placeholder:"Phone (optional)",value:s.phone,onChange:d=>t({...s,phone:d.target.value}),className:o,style:c})]}),i&&e.jsxs("div",{className:"relative",children:[e.jsx(ci,{className:"absolute left-3.5 top-1/2 -translate-y-1/2 h-4 w-4 text-white/40"}),e.jsx("input",{type:"text",placeholder:l,value:s.area,onChange:d=>t({...s,area:d.target.value}),className:o,style:c})]}),e.jsx("input",{type:"text",value:n,onChange:d=>r(d.target.value),tabIndex:-1,autoComplete:"off",className:"absolute -left-[9999px] w-0 h-0 opacity-0","aria-hidden":"true"})]})}function Qtt({children:s,disabled:t,onClick:n,type:r="button"}){return e.jsx("button",{type:r,disabled:t,onClick:n,className:"w-full rounded-lg py-3 text-sm font-semibold uppercase tracking-widest transition disabled:opacity-60 disabled:cursor-not-allowed",style:{background:`linear-gradient(180deg, ${Hae} 0%, ${ub} 100%)`,color:nse,boxShadow:`0 8px 24px ${ub}55`},children:s})}function Zyt({open:s,onClose:t,initialCriteria:n}){const{values:r,setValues:a,loading:i,setLoading:l,honeypot:o,setHoneypot:c}=Ztt(),[d,u]=j.useState(!1),h=async m=>{if(m.preventDefault(),!!r.email){l(!0);try{await HLe({lead_type:"new_listing_alerts",email:r.email.trim().toLowerCase(),first_name:r.first_name.trim()||void 0,phone:r.phone.trim()||void 0,criteria:{...n||{},...r.area.trim()?{area:r.area.trim()}:{}}}),u(!0);try{localStorage.setItem(Y4.stickyDismissed,"1")}catch{}setTimeout(t,2200)}catch{re.error("Something went wrong. Please try again.")}finally{l(!1)}}};return e.jsx(Ytt,{open:s,onClose:t,children:e.jsxs("div",{className:"p-8",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[e.jsx(qy,{className:"h-4 w-4",style:{color:ub}}),e.jsx("span",{className:"text-xs uppercase tracking-[0.2em]",style:{color:Hae},children:"New Listing Alerts"})]}),e.jsx("h2",{className:"text-2xl font-serif text-white leading-tight mb-2",children:"Be the first to know."}),e.jsx("p",{className:"text-sm text-white/60 mb-6 leading-relaxed",children:"The best homes go before they hit the market. Get instant alerts the moment new listings match your search."}),d?e.jsxs("div",{className:"py-6 text-center",children:[e.jsx("div",{className:"mx-auto mb-3 h-12 w-12 rounded-full flex items-center justify-center",style:{background:`${ub}22`,border:`1px solid ${ub}55`},children:e.jsx(Nn,{className:"h-5 w-5",style:{color:ub}})}),e.jsx("div",{className:"text-white font-medium",children:"You're on the list."}),e.jsx("div",{className:"text-white/50 text-xs mt-1",children:"Check your inbox for confirmation."})]}):e.jsxs("form",{onSubmit:h,className:"space-y-4",children:[e.jsx(Xtt,{values:r,setValues:a,honeypot:o,setHoneypot:c}),e.jsx(Qtt,{type:"submit",disabled:i||!r.email,children:i?"Activating…":"Activate Alerts"}),e.jsx("p",{className:"text-[10px] text-white/40 text-center leading-relaxed",children:"We respect your inbox. Unsubscribe any time."})]})]})})}function XRs(){const[s,t]=j.useState(!0),[n,r]=j.useState(!1);j.useEffect(()=>{try{const i=!!localStorage.getItem(Y4.stickyDismissed)||Ktt();t(i)}catch{t(!1)}},[]);const a=()=>{t(!0);try{localStorage.setItem(Y4.stickyDismissed,"1")}catch{}};return s?e.jsx(Zyt,{open:n,onClose:()=>r(!1)}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"fixed bottom-0 left-0 right-0 z-40 animate-in slide-in-from-bottom",style:{background:`linear-gradient(180deg, ${IEe} 0%, ${nse} 100%)`,borderTop:`1px solid ${ub}44`,boxShadow:"0 -8px 30px rgba(0,0,0,0.5)"},children:e.jsxs("div",{className:"max-w-6xl mx-auto px-4 sm:px-6 py-3 flex items-center gap-3",children:[e.jsx("div",{className:"hidden sm:flex h-9 w-9 rounded-full items-center justify-center flex-shrink-0",style:{background:`${ub}22`,border:`1px solid ${ub}55`},children:e.jsx(qy,{className:"h-4 w-4",style:{color:ub}})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"text-white text-sm font-medium truncate",children:"Be the first to know when new homes hit the market"}),e.jsx("div",{className:"text-white/50 text-xs hidden sm:block",children:"Instant alerts. No spam. Unsubscribe anytime."})]}),e.jsx("button",{onClick:()=>r(!0),className:"rounded-lg px-4 py-2 text-xs font-semibold uppercase tracking-wider whitespace-nowrap transition hover:brightness-110",style:{background:`linear-gradient(180deg, ${Hae} 0%, ${ub} 100%)`,color:nse},children:"Get Alerts"}),e.jsx("button",{onClick:a,className:"p-2 text-white/50 hover:text-white transition","aria-label":"Dismiss",children:e.jsx(gr,{className:"h-4 w-4"})})]})}),e.jsx(Zyt,{open:n,onClose:()=>r(!1)})]})}function QRs(){const[s,t]=j.useState(!1),n=j.useRef(!1);j.useEffect(()=>{try{if(sessionStorage.getItem(Y4.exitShown)||Ktt())return}catch{}const m=setTimeout(()=>{n.current=!0},8e3),f=g=>{if(n.current&&!(g.clientY>0)){t(!0);try{sessionStorage.setItem(Y4.exitShown,"1")}catch{}window.removeEventListener("mouseleave",f),document.removeEventListener("mouseleave",f)}};return document.addEventListener("mouseleave",f),()=>{clearTimeout(m),document.removeEventListener("mouseleave",f)}},[]);const{values:r,setValues:a,loading:i,setLoading:l,honeypot:o,setHoneypot:c}=Ztt(),[d,u]=j.useState(!1),h=async m=>{if(m.preventDefault(),!!r.email){l(!0);try{await HLe({lead_type:"exit_intent",email:r.email.trim().toLowerCase(),first_name:r.first_name.trim()||void 0,phone:r.phone.trim()||void 0,criteria:r.area.trim()?{area:r.area.trim()}:void 0}),u(!0),setTimeout(()=>t(!1),2200)}catch{re.error("Something went wrong. Please try again.")}finally{l(!1)}}};return e.jsx(Ytt,{open:s,onClose:()=>t(!1),children:e.jsxs("div",{className:"relative",children:[e.jsx("div",{className:"h-32 w-full",style:{background:`linear-gradient(135deg, ${nse} 0%, ${IEe} 60%, ${ub} 130%)`},children:e.jsx("div",{className:"absolute top-4 left-6",children:e.jsx("span",{className:"text-[10px] uppercase tracking-[0.25em]",style:{color:Hae},children:"Before You Go"})})}),e.jsxs("div",{className:"p-8 -mt-10",children:[e.jsx("div",{className:"mx-auto mb-5 h-16 w-16 rounded-full flex items-center justify-center",style:{background:IEe,border:`1px solid ${ub}55`,boxShadow:"0 8px 24px rgba(0,0,0,0.5)"},children:e.jsx(Nn,{className:"h-6 w-6",style:{color:ub}})}),e.jsx("h2",{className:"text-2xl font-serif text-white text-center leading-tight mb-2",children:"Wait — get a fresh list of homes."}),e.jsx("p",{className:"text-sm text-white/60 text-center mb-6 leading-relaxed",children:"Drop your email and we'll send you a curated list of homes matching your area, updated weekly."}),d?e.jsxs("div",{className:"py-4 text-center",children:[e.jsx("div",{className:"text-white font-medium",children:"Sent — check your inbox."}),e.jsx("div",{className:"text-white/50 text-xs mt-1",children:"Your list is on its way."})]}):e.jsxs("form",{onSubmit:h,className:"space-y-4",children:[e.jsx(Xtt,{values:r,setValues:a,honeypot:o,setHoneypot:c,showPhone:!1}),e.jsx(Qtt,{type:"submit",disabled:i||!r.email,children:i?"Sending…":"Send My List"})]})]})]})})}function JRs(){const[s,t]=j.useState([]);j.useEffect(()=>{try{const o=localStorage.getItem(Y4.savedListings);o&&t(JSON.parse(o))}catch{}},[]);const n=o=>{t(o);try{localStorage.setItem(Y4.savedListings,JSON.stringify(o))}catch{}},r=j.useCallback(o=>s.includes(o),[s]),a=o=>{s.includes(o)||n([...s,o])},i=o=>n(s.filter(c=>c!==o));return{ids:s,has:r,add:a,remove:i,toggle:o=>s.includes(o)?i(o):a(o)}}function eDs({listingId:s,listingAddress:t,className:n}){const{has:r,add:a,remove:i}=JRs(),l=r(s),[o,c]=j.useState(!1),d=()=>{if(l){i(s);return}if(Ktt()){a(s),re.success("Saved to your favorites"),HLe({lead_type:"saved_listing",email:ZRs()||"unknown@local",listing_id:s,listing_address:t}).catch(()=>{});return}c(!0)};return e.jsxs(e.Fragment,{children:[e.jsx("button",{onClick:d,className:n,"aria-label":l?"Remove from favorites":"Save to favorites",children:e.jsx(Jo,{className:`h-5 w-5 ${l?"fill-current":""}`})}),e.jsx(tDs,{open:o,onClose:()=>c(!1),listingId:s,listingAddress:t,onSaved:()=>a(s)})]})}function tDs({open:s,onClose:t,listingId:n,listingAddress:r,onSaved:a}){const{values:i,setValues:l,loading:o,setLoading:c,honeypot:d,setHoneypot:u}=Ztt(),h=async m=>{if(m.preventDefault(),!!i.email){c(!0);try{await HLe({lead_type:"saved_listing",email:i.email.trim().toLowerCase(),first_name:i.first_name.trim()||void 0,phone:i.phone.trim()||void 0,listing_id:n,listing_address:r}),a(),re.success("Saved to your favorites"),t()}catch{re.error("Something went wrong. Please try again.")}finally{c(!1)}}};return e.jsx(Ytt,{open:s,onClose:t,children:e.jsxs("div",{className:"p-8",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[e.jsx(Jo,{className:"h-4 w-4",style:{color:ub}}),e.jsx("span",{className:"text-xs uppercase tracking-[0.2em]",style:{color:Hae},children:"Save This Home"})]}),e.jsx("h2",{className:"text-2xl font-serif text-white leading-tight mb-2",children:"One click to save."}),e.jsx("p",{className:"text-sm text-white/60 mb-6 leading-relaxed",children:"Get an alert if the price drops or the status changes. No spam — just the updates that matter."}),e.jsxs("form",{onSubmit:h,className:"space-y-4",children:[e.jsx(Xtt,{values:i,setValues:l,honeypot:d,setHoneypot:u}),e.jsx(Qtt,{type:"submit",disabled:o||!i.email,children:o?"Saving…":"Save Home"})]})]})})}var sDs=Object.defineProperty,qh=(s,t)=>sDs(s,"name",{value:t,configurable:!0}),_7t=["PageUp","PageDown"],w7t=["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"],j7t={"from-left":["Home","PageDown","ArrowDown","ArrowLeft"],"from-right":["Home","PageDown","ArrowDown","ArrowRight"],"from-bottom":["Home","PageDown","ArrowDown","ArrowLeft"],"from-top":["Home","PageDown","ArrowUp","ArrowLeft"]},Gae="Slider",[rGe,nDs,rDs]=LB(Gae),[Jtt,rSr]=tp(Gae,[rDs]),[aDs,Wae]=Jtt(Gae),N7t=j.forwardRef(qh(function(t,n){const{name:r,min:a=0,max:i=100,step:l=1,orientation:o="horizontal",disabled:c=!1,minStepsBetweenThumbs:d=0,defaultValue:u=[a],value:h,onValueChange:m=qh(()=>{},"onValueChange"),onValueCommit:f=qh(()=>{},"onValueCommit"),inverted:g=!1,form:x,...y}=t,v=j.useRef(new Set),b=j.useRef(0),w=j.useRef(!1),C=o==="horizontal"?iDs:oDs,[E,I]=j.useState(null),P=Vo(n,I),[R=[],D]=fy({prop:h,defaultProp:u,onChange:qh(X=>{var ie;(ie=[...v.current][b.current])==null||ie.focus({preventScroll:!0,focusVisible:w.current}),w.current=!1,m(X)},"onChange")}),O=j.useRef(R),U=j.useRef(R);j.useEffect(()=>{const X=x?E==null?void 0:E.ownerDocument.getElementById(x):E==null?void 0:E.closest("form");if(X instanceof HTMLFormElement){const ae=qh(()=>D(U.current),"reset");return X.addEventListener("reset",ae),()=>X.removeEventListener("reset",ae)}},[E,x,D]);function W(X){const ae=P7t(R,X);Y(X,ae)}qh(W,"handleSlideStart");function V(X){Y(X,b.current)}qh(V,"handleSlideMove");function G(){String(R)!==String(O.current)&&f(R)}qh(G,"handleSlideEnd");function Y(X,ae,{commit:ie}={commit:!1}){const ne=tst(l),te=bee(Math.round((X-a)/l)*l+a,ne),J=wG(te,[a,i]);D((ce=[])=>{const _e=T7t(ce,J,ae);if(R7t(_e,d*l)){b.current=_e.indexOf(J);const he=String(_e)!==String(ce);return he&&ie&&f(_e),he?_e:ce}else return ce})}return qh(Y,"updateValues"),e.jsx(aDs,{scope:t.__scopeSlider,name:r,disabled:c,min:a,max:i,valueIndexToChangeRef:b,thumbs:v.current,values:R,orientation:o,form:x,children:e.jsx(rGe.Provider,{scope:t.__scopeSlider,children:e.jsx(rGe.Slot,{scope:t.__scopeSlider,children:e.jsx(C,{"aria-disabled":c,"data-disabled":c?"":void 0,...y,ref:P,onPointerDown:Ra(y.onPointerDown,()=>{c||(O.current=R,w.current=!1)}),min:a,max:i,inverted:g,onSlideStart:c?void 0:W,onSlideMove:c?void 0:V,onSlideEnd:c?void 0:G,onHomeKeyDown:()=>{c||(w.current=!0,Y(a,0,{commit:!0}))},onEndKeyDown:()=>{c||(w.current=!0,Y(i,R.length-1,{commit:!0}))},onStepKeyDown:({event:X,direction:ae})=>{if(!c){w.current=!0;const te=_7t.includes(X.key)||X.shiftKey&&w7t.includes(X.key)?10:1,J=b.current,ce=R[J],_e=D7t(ce,{min:a,step:l,direction:ae,multiplier:te});Y(_e,J,{commit:!0})}}})})})})},"Slider")),[k7t,S7t]=Jtt(Gae,{startEdge:"left",endEdge:"right",size:"width",direction:1}),iDs=j.forwardRef(qh(function(t,n){const{min:r,max:a,dir:i,inverted:l,onSlideStart:o,onSlideMove:c,onSlideEnd:d,onStepKeyDown:u,...h}=t,[m,f]=j.useState(null),g=Vo(n,f),x=j.useRef(void 0),y=l3(i),v=y==="ltr",b=v&&!l||!v&&l;function w(S){const C=x.current||m.getBoundingClientRect(),E=[0,C.width],P=GLe(E,b?[r,a]:[a,r]);return x.current=C,P(S-C.left)}return qh(w,"getValueFromPointer"),e.jsx(k7t,{scope:t.__scopeSlider,startEdge:b?"left":"right",endEdge:b?"right":"left",direction:b?1:-1,size:"width",children:e.jsx(C7t,{dir:y,"data-orientation":"horizontal",...h,ref:g,style:{...h.style,"--radix-slider-thumb-transform":"translateX(-50%)"},onSlideStart:S=>{const C=w(S.clientX);o==null||o(C)},onSlideMove:S=>{const C=w(S.clientX);c==null||c(C)},onSlideEnd:()=>{x.current=void 0,d==null||d()},onStepKeyDown:S=>{const E=j7t[b?"from-left":"from-right"].includes(S.key);u==null||u({event:S,direction:E?-1:1})}})})},"SliderHorizontal")),oDs=j.forwardRef(qh(function(t,n){const{min:r,max:a,inverted:i,onSlideStart:l,onSlideMove:o,onSlideEnd:c,onStepKeyDown:d,...u}=t,h=j.useRef(null),m=Vo(n,h),f=j.useRef(void 0),g=!i;function x(y){const v=f.current||h.current.getBoundingClientRect(),b=[0,v.height],S=GLe(b,g?[a,r]:[r,a]);return f.current=v,S(y-v.top)}return qh(x,"getValueFromPointer"),e.jsx(k7t,{scope:t.__scopeSlider,startEdge:g?"bottom":"top",endEdge:g?"top":"bottom",size:"height",direction:g?1:-1,children:e.jsx(C7t,{"data-orientation":"vertical",...u,ref:m,style:{...u.style,"--radix-slider-thumb-transform":"translateY(50%)"},onSlideStart:y=>{const v=x(y.clientY);l==null||l(v)},onSlideMove:y=>{const v=x(y.clientY);o==null||o(v)},onSlideEnd:()=>{f.current=void 0,c==null||c()},onStepKeyDown:y=>{const b=j7t[g?"from-bottom":"from-top"].includes(y.key);d==null||d({event:y,direction:b?-1:1})}})})},"SliderVertical")),C7t=j.forwardRef(qh(function(t,n){const{__scopeSlider:r,onSlideStart:a,onSlideMove:i,onSlideEnd:l,onHomeKeyDown:o,onEndKeyDown:c,onStepKeyDown:d,...u}=t,h=Wae(Gae,r);return e.jsx(Ei.span,{...u,ref:n,onKeyDown:Ra(t.onKeyDown,m=>{m.key==="Home"?(o(m),m.preventDefault()):m.key==="End"?(c(m),m.preventDefault()):_7t.concat(w7t).includes(m.key)&&(d(m),m.preventDefault())}),onPointerDown:Ra(t.onPointerDown,m=>{const f=m.target;f.setPointerCapture(m.pointerId),m.preventDefault(),h.thumbs.has(f)?f.focus({preventScroll:!0,focusVisible:!1}):a(m)}),onPointerMove:Ra(t.onPointerMove,m=>{m.target.hasPointerCapture(m.pointerId)&&i(m)}),onPointerUp:Ra(t.onPointerUp,m=>{const f=m.target;f.hasPointerCapture(m.pointerId)&&(f.releasePointerCapture(m.pointerId),l(m))})})},"SliderImpl")),lDs="SliderTrack",cDs=j.forwardRef(qh(function(t,n){const{__scopeSlider:r,...a}=t,i=Wae(lDs,r);return e.jsx(Ei.span,{"data-disabled":i.disabled?"":void 0,"data-orientation":i.orientation,...a,ref:n})},"SliderTrack")),Xyt="SliderRange",dDs=j.forwardRef(qh(function(t,n){const{__scopeSlider:r,...a}=t,i=Wae(Xyt,r),l=S7t(Xyt,r),o=j.useRef(null),c=Vo(n,o),d=i.values.length,u=i.values.map(f=>est(f,i.min,i.max)),h=d>1?Math.min(...u):0,m=100-Math.max(...u);return e.jsx(Ei.span,{"data-orientation":i.orientation,"data-disabled":i.disabled?"":void 0,...a,ref:c,style:{...t.style,[l.startEdge]:h+"%",[l.endEdge]:m+"%"}})},"SliderRange")),uDs="SliderThumb",[hDs,A7t]=Jtt(uDs),mDs="SliderThumbProvider";function E7t(s){const{__scopeSlider:t,name:n,children:r,internal_do_not_use_render:a}=s,i=Wae(mDs,t),l=nDs(t),[o,c]=j.useState(null),d=j.useMemo(()=>o?l().findIndex(y=>y.ref.current===o):-1,[l,o]),u=XW(o),h=o?!!i.form||!!o.closest("form"):!0,m=i.values[d],f=n??(i.name?i.name+(i.values.length>1?"[]":""):void 0),g=m===void 0?0:est(m,i.min,i.max);j.useEffect(()=>{if(o)return i.thumbs.add(o),()=>{i.thumbs.delete(o)}},[o,i.thumbs]);const x={value:m,name:f,form:i.form,isFormControl:h,index:d,thumb:o,onThumbChange:c,percent:g,size:u};return e.jsx(hDs,{scope:t,...x,children:F7t(a)?a(x):r})}qh(E7t,"SliderThumbProvider");var h7e="SliderThumbTrigger",fDs=j.forwardRef(qh(function(t,n){const{__scopeSlider:r,...a}=t,i=Wae(h7e,r),l=S7t(h7e,r),{index:o,value:c,percent:d,size:u,onThumbChange:h}=A7t(h7e,r),m=Vo(n,h),f=M7t(o,i.values.length),g=u==null?void 0:u[l.size],x=g?I7t(g,d,l.direction):0;return e.jsx("span",{style:{transform:"var(--radix-slider-thumb-transform)",position:"absolute",[l.startEdge]:`calc(${d}% + ${x}px)`},children:e.jsx(rGe.ItemSlot,{scope:r,children:e.jsx(Ei.span,{role:"slider","aria-label":t["aria-label"]||f,"aria-valuemin":i.min,"aria-valuenow":c,"aria-valuemax":i.max,"aria-orientation":i.orientation,"data-orientation":i.orientation,"data-disabled":i.disabled?"":void 0,tabIndex:i.disabled?void 0:0,...a,ref:m,style:c===void 0?{display:"none"}:t.style,onFocus:Ra(t.onFocus,()=>{i.valueIndexToChangeRef.current=o})})})})},"SliderThumbTrigger")),pDs=j.forwardRef(qh(function(t,n){const{__scopeSlider:r,name:a,...i}=t;return e.jsx(E7t,{__scopeSlider:r,name:a,internal_do_not_use_render:({index:l,isFormControl:o})=>e.jsxs(e.Fragment,{children:[e.jsx(fDs,{...i,ref:n,__scopeSlider:r}),o?e.jsx(xDs,{__scopeSlider:r},l):null]})})},"SliderThumb")),gDs="SliderBubbleInput",xDs=j.forwardRef(qh(function({__scopeSlider:t,...n},r){const{value:a,name:i,form:l}=A7t(gDs,t),o=j.useRef(null),c=Vo(o,r),d=_tt(a);return j.useEffect(()=>{const u=o.current;if(!u)return;const h=window.HTMLInputElement.prototype,f=Object.getOwnPropertyDescriptor(h,"value").set;if(d!==a&&f){const g=new Event("input",{bubbles:!0});f.call(u,a),u.dispatchEvent(g)}},[d,a]),e.jsx(Ei.input,{style:{display:"none"},name:i,form:l,...n,ref:c,defaultValue:a})},"SliderBubbleInput"));function T7t(s=[],t,n){const r=[...s];return r[n]=t,r.sort((a,i)=>a-i)}qh(T7t,"getNextSortedValues");function est(s,t,n){const i=100/(n-t)*(s-t);return wG(i,[0,100])}qh(est,"convertValueToPercentage");function M7t(s,t){return t>2?`Value ${s+1} of ${t}`:t===2?["Minimum","Maximum"][s]:void 0}qh(M7t,"getLabel");function P7t(s,t){if(s.length===1)return 0;const n=s.map(a=>Math.abs(a-t)),r=Math.min(...n);return n.indexOf(r)}qh(P7t,"getClosestValueIndex");function I7t(s,t,n){const r=s/2,i=GLe([0,50],[0,r]);return(r-i(t)*n)*n}qh(I7t,"getThumbInBoundsOffset");function L7t(s){return s.slice(0,-1).map((t,n)=>s[n+1]-t)}qh(L7t,"getStepsBetweenValues");function R7t(s,t){if(t>0){const n=L7t(s);return Math.min(...n)>=t}return!0}qh(R7t,"hasMinStepsBetweenValues");function GLe(s,t){return n=>{if(s[0]===s[1]||t[0]===t[1])return t[0];const r=(t[1]-t[0])/(s[1]-s[0]);return t[0]+r*(n-s[0])}}qh(GLe,"linearScale");function tst(s){if(!Number.isFinite(s))return 0;const t=s.toString();if(t.includes("e")){const[r,a]=t.split("e"),i=r.split(".")[1]||"",l=Number(a);return Math.max(0,i.length-l)}const n=t.split(".")[1];return n?n.length:0}qh(tst,"getDecimalCount");function bee(s,t){const n=Math.pow(10,t);return Math.round(s*n)/n}qh(bee,"roundValue");function D7t(s,{min:t,step:n,direction:r,multiplier:a}){const i=tst(n),l=(s-t)/n,o=Math.round(l),c=bee(o*n+t,i)===bee(s,i);let d;return c?d=o+a*r:r>0?d=Math.ceil(l):d=Math.floor(l),bee(d*n+t,i)}qh(D7t,"getNextStepValue");function F7t(s){return typeof s=="function"}qh(F7t,"isFunction");const kx=j.forwardRef(({className:s,...t},n)=>e.jsxs(N7t,{ref:n,className:Pt("relative flex w-full touch-none select-none items-center",s),...t,children:[e.jsx(cDs,{className:"relative h-2 w-full grow overflow-hidden rounded-full bg-secondary",children:e.jsx(dDs,{className:"absolute h-full bg-primary"})}),e.jsx(pDs,{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"})]}));kx.displayName=N7t.displayName;const yDs=s=>tt({queryKey:["public-listings",s],queryFn:async()=>{let t=q.from("listings").select(` id, slug, agent_id, property_address, city, state, neighborhood, price, property_type, listing_class, 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, phone, avatar_url, brokerage_name, brokerage:brokerages(name)) `).eq("is_approved",!0).eq("is_public",!0).or("lifecycle_stage.is.null,lifecycle_stage.neq.pitch").or("listing_class.is.null,listing_class.neq.commercial").order("created_at",{ascending:!1});if(s!=null&&s.status?t=t.eq("status",s.status):t=t.neq("status","sold"),s!=null&&s.propertyType&&(t=t.eq("property_type",s.propertyType)),s!=null&&s.city){const a=s.city.replace(/[%,()]/g," ").trim();if(a){const i=`%${a}%`;t=t.or(`city.ilike.${i},neighborhood.ilike.${i},property_address.ilike.${i}`)}}s!=null&&s.minPrice&&(t=t.gte("price",s.minPrice)),s!=null&&s.maxPrice&&(t=t.lte("price",s.maxPrice));const{data:n,error:r}=await t;if(r)throw r;return n}}),vDs=()=>tt({queryKey:["public-listings-search-index"],staleTime:5*60*1e3,queryFn:async()=>{const{data:s,error:t}=await q.from("listings").select("city, state, neighborhood, property_address").eq("is_approved",!0).eq("is_public",!0);if(t)throw t;const n=new Map,r=new Map,a=new Map;return(s||[]).forEach(i=>{if(i.city){const l=`${i.city}|${i.state||""}`.toLowerCase(),o=i.state?`${i.city}, ${i.state}`:i.city,c=n.get(l);c?c.count++:n.set(l,{label:o,city:i.city,state:i.state,count:1})}if(i.neighborhood){const l=`${i.neighborhood}|${i.city||""}`.toLowerCase(),o=i.city?`${i.neighborhood} — ${i.city}`:i.neighborhood,c=r.get(l);c?c.count++:r.set(l,{label:o,city:i.city||"",neighborhood:i.neighborhood,count:1})}if(i.property_address){const l=String(i.property_address).match(/\b(\d{5})(?:-\d{4})?\b/);if(l){const o=l[1],c=a.get(o);c?c.count++:a.set(o,{label:o,zip:o,count:1})}}}),{cities:Array.from(n.values()).sort((i,l)=>l.count-i.count),neighborhoods:Array.from(r.values()).sort((i,l)=>l.count-i.count),zips:Array.from(a.values()).sort((i,l)=>l.count-i.count)}}}),bDs=s=>tt({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 n=q.from("listings").select(` id, slug, agent_id, property_address, city, state, neighborhood, price, property_type, listing_class, 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, page_config, page_theme, created_at, updated_at, co_agent_name, co_agent_email, co_agent_phone, co_agent_brokerage, co_agent_photo_url, photos:listing_photos(id, photo_url, is_primary, sort_order), agent:profiles!listings_agent_id_fkey(id, name, email, phone, avatar_url, brokerage_name, 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?n=n.eq("id",s):n=n.eq("slug",s);const{data:r,error:a}=await n.single();if(a)throw a;const i=r;return Array.isArray(i==null?void 0:i.photos)&&(i.photos=[...i.photos].sort((l,o)=>(l.sort_order??0)-(o.sort_order??0)||(o.is_primary?1:0)-(l.is_primary?1:0))),i},enabled:!!s}),_Ds=()=>ft({mutationFn:async({listingId:s,agentId:t,firstName:n,lastName:r,email:a,phone:i,shareToken:l,leadType:o="info_request",preferredDate:c,preferredTime:d,showingMode:u,message:h})=>{let m=null,f=null;if(l){const{data:b}=await q.from("listing_shares").select("id, sharing_agent_id").eq("share_token",l).eq("listing_id",s).maybeSingle();b&&(m=b.id,f=b.sharing_agent_id)}const g=crypto.randomUUID(),x={id:g},{error:y}=await q.from("listing_leads").insert({id:g,listing_id:s,agent_id:f||t,first_name:n,last_name:r,email:a,phone:i,share_id:m,referred_by_agent_id:f,lead_type:o,preferred_date:c||null,preferred_time:d||null,showing_mode:u||null,message:h||null});if(y)throw y;const{error:v}=await q.functions.invoke("process-listing-lead",{body:{leadId:x.id}});return v&&console.error("Error processing lead:",v),x}}),wDs=()=>ft({mutationFn:async s=>{const{error:t}=await q.rpc("increment_listing_share_click",{p_share_token:s});if(t)throw t}});function O7t({title:s,subtitle:t,areaLabel:n,sections:r,agent:a,tone:i="light"}){const l=i==="dark",o=l?"text-white/65":"text-muted-foreground",c=l?"border-white/10":"border-border";return e.jsxs("div",{className:l?"text-white":"text-foreground",id:"community-guide-print",children:[e.jsxs("header",{className:`border-b ${c} pb-6 mb-8`,children:[e.jsxs("div",{className:`flex items-center gap-2 text-[11px] uppercase tracking-[0.22em] ${o} mb-3`,children:[e.jsx(Xf,{className:"h-3.5 w-3.5"}),"Insider's Community Guide"]}),e.jsx("h1",{className:"font-display text-3xl sm:text-4xl font-semibold leading-tight",children:s}),t&&e.jsx("p",{className:`mt-3 text-base leading-relaxed ${o}`,children:t}),n&&e.jsxs("p",{className:`mt-3 flex items-center gap-1.5 text-sm ${o}`,children:[e.jsx(ci,{className:"h-3.5 w-3.5"}),n]})]}),e.jsx("div",{className:"space-y-10",children:r.map((d,u)=>e.jsxs("section",{children:[e.jsxs("div",{className:"flex items-baseline gap-3 mb-2",children:[e.jsx("span",{className:"font-display text-2xl text-primary font-semibold",children:String(u+1).padStart(2,"0")}),e.jsx("h2",{className:"font-display text-xl sm:text-2xl font-semibold",children:d.heading})]}),d.intro&&e.jsx("p",{className:`text-sm sm:text-base leading-relaxed ${o} mb-4`,children:d.intro}),e.jsx("ul",{className:"space-y-3",children:(d.items??[]).map((h,m)=>e.jsxs("li",{className:`rounded-xl border ${c} ${l?"bg-white/[0.03]":"bg-muted/40"} px-4 py-3`,children:[e.jsx("p",{className:"font-medium text-sm sm:text-base",children:h.name}),h.note&&e.jsx("p",{className:`text-sm mt-1 leading-relaxed ${o}`,children:h.note})]},m))})]},u))}),(a==null?void 0:a.name)&&e.jsxs("footer",{className:`mt-10 pt-6 border-t ${c}`,children:[e.jsxs("div",{className:"flex items-center gap-4",children:[a.avatar_url?e.jsx("img",{src:a.avatar_url,alt:a.name,className:"h-14 w-14 rounded-full object-cover border border-primary/30"}):null,e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:`text-[11px] uppercase tracking-[0.2em] ${o}`,children:"Prepared for you by"}),e.jsx("p",{className:"font-display text-lg font-semibold leading-tight",children:a.name}),a.brokerage&&e.jsx("p",{className:`text-sm ${o}`,children:a.brokerage}),e.jsxs("div",{className:`flex flex-wrap gap-4 mt-1.5 text-sm ${o}`,children:[a.phone&&e.jsxs("a",{href:`tel:${a.phone}`,className:"flex items-center gap-1.5 hover:text-primary",children:[e.jsx(Da,{className:"h-3.5 w-3.5"}),a.phone]}),a.email&&e.jsxs("a",{href:`mailto:${a.email}`,className:"flex items-center gap-1.5 hover:text-primary",children:[e.jsx(mn,{className:"h-3.5 w-3.5"}),a.email]})]})]})]}),e.jsxs("p",{className:`mt-4 text-sm ${o}`,children:["Thinking about a move in ",n||"the area","? Reach out any time — happy to share what never makes it online."]})]})]})}const zce="border-white/15 bg-white/5 text-white placeholder:text-white/40";function jDs({listingId:s}){const[t,n]=j.useState(null),[r,a]=j.useState({firstName:"",lastName:"",email:"",phone:""}),[i,l]=j.useState(!1),[o,c]=j.useState(null),[d,u]=j.useState(!1);if(j.useEffect(()=>{let m=!1;return q.functions.invoke("community-guide-public",{body:{action:"teaser",listingId:s}}).then(({data:f})=>{!m&&f&&n(f)}).catch(()=>{}),()=>{m=!0}},[s]),!(t!=null&&t.available))return null;const h=async m=>{if(m.preventDefault(),!r.firstName.trim()||!r.email.trim()){re.error("Please add your name and email.");return}l(!0);try{const{data:f,error:g}=await q.functions.invoke("community-guide-public",{body:{action:"unlock",listingId:s,...r}});if(g||f!=null&&f.error)throw new Error((f==null?void 0:f.error)||"Something went wrong.");c(f),u(!0),re.success("Your guide is ready!")}catch(f){re.error((f==null?void 0:f.message)||"We could not send your guide. Please try again.")}finally{l(!1)}};return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"rounded-2xl border border-white/10 bg-white/[0.03] p-6 backdrop-blur",children:[e.jsxs("div",{className:"flex items-center gap-2 text-[11px] uppercase tracking-[0.2em] text-white/60 mb-3",children:[e.jsx(Xf,{className:"h-3.5 w-3.5"}),"Free Community Guide"]}),e.jsx("h3",{className:"font-display text-xl text-white font-medium leading-snug",children:t.title}),t.subtitle&&e.jsx("p",{className:"text-sm text-white/60 mt-2 leading-relaxed",children:t.subtitle}),(t.teaser??[]).length>0&&e.jsx("ul",{className:"mt-4 space-y-2",children:t.teaser.map((m,f)=>e.jsxs("li",{className:"flex gap-2 text-sm text-white/70",children:[e.jsx(la,{className:"h-4 w-4 text-primary shrink-0 mt-0.5"}),m]},f))}),o?e.jsxs($,{className:"w-full mt-5",onClick:()=>u(!0),children:[e.jsx(Xf,{className:"h-4 w-4 mr-2"}),"Read your guide"]}):e.jsxs("form",{onSubmit:h,className:"mt-5 space-y-3",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{htmlFor:"cg-first",className:"text-xs text-white/60",children:"First name"}),e.jsx(pe,{id:"cg-first",value:r.firstName,onChange:m=>a({...r,firstName:m.target.value}),className:zce,required:!0})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{htmlFor:"cg-last",className:"text-xs text-white/60",children:"Last name"}),e.jsx(pe,{id:"cg-last",value:r.lastName,onChange:m=>a({...r,lastName:m.target.value}),className:zce})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{htmlFor:"cg-email",className:"text-xs text-white/60",children:"Email"}),e.jsx(pe,{id:"cg-email",type:"email",value:r.email,onChange:m=>a({...r,email:m.target.value}),className:zce,required:!0})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{htmlFor:"cg-phone",className:"text-xs text-white/60",children:"Cell phone"}),e.jsx(pe,{id:"cg-phone",type:"tel",value:r.phone,onChange:m=>a({...r,phone:m.target.value}),className:zce})]}),e.jsxs($,{type:"submit",className:"w-full",disabled:i,children:[i?e.jsx(kt,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(di,{className:"h-4 w-4 mr-2"}),i?"Preparing your guide…":"Get the free guide"]}),e.jsxs("p",{className:"text-[11px] text-white/50 flex items-center gap-1.5 justify-center",children:[e.jsx(pc,{className:"h-3 w-3"}),"Instant access. We never share your details."]})]})]}),e.jsx(zs,{open:d,onOpenChange:u,children:e.jsx(Os,{className:"max-w-2xl p-0 gap-0",children:e.jsx(uo,{className:"max-h-[82vh]",children:e.jsxs("div",{className:"p-6 sm:p-8",children:[e.jsx("div",{id:"community-guide-print",children:o&&e.jsx(O7t,{title:o.title,subtitle:o.subtitle,areaLabel:o.area_label,sections:o.sections??[],agent:o.agent})}),e.jsx("div",{className:"mt-8 flex justify-end print:hidden",children:e.jsxs($,{variant:"outline",onClick:()=>NDs(o==null?void 0:o.title),children:[e.jsx(di,{className:"h-4 w-4 mr-2"}),"Save as PDF"]})})]})})})})]})}function NDs(s){const t=document.getElementById("community-guide-print");if(!t)return window.print();const n=t.cloneNode(!0);n.removeAttribute("id"),n.setAttribute("data-print-root",""),document.body.appendChild(n),document.body.classList.add("printing-doc");const r=document.title;s&&(document.title=s);let a=!1;const i=()=>{a||(a=!0,n.remove(),document.body.classList.remove("printing-doc"),document.title=r,window.removeEventListener("afterprint",i))};window.addEventListener("afterprint",i);try{window.print()}finally{setTimeout(i,1e3)}}const ML={sale:"For Sale",lease:"For Lease",sale_or_lease:"For Sale or Lease",investment:"Investment Offering"},c6={office:"Office",retail:"Retail",industrial:"Industrial",flex:"Flex / R&D",multifamily:"Multifamily",land:"Land",medical:"Medical",hospitality:"Hospitality",self_storage:"Self Storage",mixed_use:"Mixed Use",special_purpose:"Special Purpose"},kDs=["NNN","Modified Gross","Full Service","Gross","Absolute Net","Ground Lease"],SDs={sf_year:"/SF/YR",sf_month:"/SF/MO",month:"/MO"},aGe={om:"Offering Memorandum",flyer:"Flyer",rent_roll:"Rent Roll",financials:"Financials",survey:"Survey",site_plan:"Site Plan",lease:"Lease Documents",other:"Other"},Qyt={public:"Open download",email:"Email required",nda:"NDA required"},iGe={principal:"Principal / Investor",broker:"Broker",tenant:"Tenant / User",lender:"Lender",other:"Other"},m7e=[{key:"pitch",label:"Pitch",blurb:"Competing for the assignment"},{key:"won",label:"Won",blurb:"Assignment secured"},{key:"launched",label:"Launch",blurb:"Microsite & materials live"},{key:"marketing",label:"Market",blurb:"Campaign in market"},{key:"under_contract",label:"Under Contract",blurb:"Deal in escrow"},{key:"closed",label:"Closed",blurb:"Transaction complete"}],e3e=[{key:"photos",label:"Professional photography uploaded",detail:"At least 6 images for the microsite hero and gallery"},{key:"financials",label:"Financial snapshot completed",detail:"NOI, cap rate, occupancy or lease rate entered"},{key:"highlights",label:"Investment highlights written",detail:"3–6 reasons this opportunity matters"},{key:"om",label:"Offering Memorandum uploaded",detail:"Gated OM available for qualified prospects"},{key:"microsite",label:"Microsite published",detail:"Public commercial microsite is live"},{key:"email",label:"Broker & investor email sent",detail:"First distribution to your database"},{key:"social",label:"Social / LinkedIn announcement",detail:"Launch post published"},{key:"signage",label:"Signage & QR deployed",detail:"On-site QR code linking to the microsite"}],z7t=[{label:"Day 1 — Positioning & pricing",detail:"Finalize the pricing strategy, opportunity narrative and target buyer/tenant profile."},{label:"Day 2–4 — Institutional-grade materials",detail:"Photography, Offering Memorandum, investor teaser and branded flyer produced."},{label:"Day 5 — Property microsite goes live",detail:"Dedicated commercial microsite with gated OM, tour requests and full analytics."},{label:"Week 1 — Targeted broker & investor outreach",detail:"Direct email to qualified buyers, brokers and 1031 investors in the LevelUp database."},{label:"Week 2 — Digital & social distribution",detail:"LinkedIn campaign, syndication and QR-coded on-site signage."},{label:"Weekly — Owner activity reporting",detail:"Every week you receive views, OM requests, downloads, tours and prospect-level interest."}];function BN(s,t=0){return s==null||Number.isNaN(Number(s))?null:new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:t}).format(Number(s))}function Jyt(s){if(s==null)return null;const t=Number(s);return Number.isNaN(t)?null:t>=1e6?`$${(t/1e6).toFixed(t>=1e7?1:2).replace(/\.0+$/,"")}M`:t>=1e3?`$${Math.round(t/1e3)}K`:BN(t)}function bE(s){return s==null?null:`${new Intl.NumberFormat("en-US").format(Number(s))} SF`}function LEe(s,t=2){return s==null?null:`${Number(s).toFixed(t).replace(/\.?0+$/,"")}%`}function oGe(s){if(!(s!=null&&s.lease_rate))return null;const t=SDs[s.lease_rate_unit||"sf_year"]??"";return`${s.lease_rate_unit==="month"?BN(s.lease_rate):`$${Number(s.lease_rate).toFixed(2).replace(/\.00$/,"")}`}${t}${s.lease_type?` ${s.lease_type}`:""}`}function EG(s,t){if(!s)return BN(t)??"Price on request";if(s.deal_type==="lease")return oGe(s)??"Rate on request";const n=s.asking_price??t;if(s.deal_type==="sale_or_lease"){const r=[BN(n),oGe(s)].filter(Boolean);return r.length?r.join(" · "):"Price on request"}return BN(n)??"Price on request"}function iL(s,t){return t!=null&&t.opportunity_title?t.opportunity_title:t!=null&&t.hide_address||t!=null&&t.is_confidential?`Confidential ${t!=null&&t.commercial_type?c6[t.commercial_type]:"Commercial"} Opportunity`:s.property_address||`${s.city??""}, ${s.state??""}`}function Kae(s,t){const n=(t==null?void 0:t.submarket)||s.neighborhood,r=[s.city,s.state].filter(Boolean).join(", ");return n?`${n} · ${r}`:r}function CDs(s,t){var i;const n=(s==null?void 0:s.launch_checklist)??{},r=[],a={photos:t.photoCount>=6,financials:!!(s!=null&&s.noi||s!=null&&s.cap_rate||s!=null&&s.lease_rate||s!=null&&s.occupancy_pct),highlights:(((i=s==null?void 0:s.investment_highlights)==null?void 0:i.length)??0)>=3,om:t.hasOm,microsite:t.isPublic};for(const l of e3e)(a[l.key]||n[l.key])&&r.push(l.key);return{done:r,total:e3e.length,score:Math.round(r.length/e3e.length*100)}}const e0t={om_download:10,om_request:9,tour_request:15,inquiry:12,doc_download:8,om_view:5,gallery_view:2,page_view:1,contact_click:4,share_click:2,email_click:3,email_open:1,map_view:1};function t0t(s){return s>=30?{label:"Hot",tone:"bg-amber-500/15 text-amber-600 border-amber-500/30"}:s>=12?{label:"Warm",tone:"bg-orange-500/10 text-orange-600 border-orange-500/20"}:{label:"Tracking",tone:"bg-muted text-muted-foreground border-border"}}const ADs="https://commercial.relevelup.com",Z4=q;function B7t(s){return tt({queryKey:["commercial-details",s],queryFn:async()=>{const{data:t,error:n}=await Z4.from("commercial_listing_details").select("*").eq("listing_id",s).maybeSingle();if(n)throw n;return t??null},enabled:!!s})}function $7t(){const s=Vt(),{user:t}=vs();return ft({mutationFn:async({listingId:n,values:r})=>{const{data:a,error:i}=await Z4.from("commercial_listing_details").upsert({listing_id:n,agent_id:t==null?void 0:t.id,...r},{onConflict:"listing_id"}).select().single();if(i)throw i;return a},onSuccess:(n,r)=>{s.invalidateQueries({queryKey:["commercial-details",r.listingId]}),s.invalidateQueries({queryKey:["listing",r.listingId]})}})}function EDs(s){return tt({queryKey:["commercial-pitch",s],queryFn:async()=>{const{data:t,error:n}=await Z4.from("commercial_pitch_details").select("*").eq("listing_id",s).maybeSingle();if(n)throw n;return t??null},enabled:!!s})}function U7t(){const s=Vt(),{user:t}=vs();return ft({mutationFn:async({listingId:n,values:r})=>{const{data:a,error:i}=await Z4.from("commercial_pitch_details").upsert({listing_id:n,agent_id:t==null?void 0:t.id,...r},{onConflict:"listing_id"}).select().single();if(i)throw i;return a},onSuccess:(n,r)=>s.invalidateQueries({queryKey:["commercial-pitch",r.listingId]})})}function q7t(){const s=Vt();return ft({mutationFn:async({listingId:t,stage:n,lostReason:r})=>{const a=n==="won",i=n==="lost",l={lifecycle_stage:n};a&&(l.status="coming_soon"),i&&(l.is_public=!1,l.allow_sharing=!1);const{error:o}=await Z4.from("listings").update(l).eq("id",t);if(o)throw o;return(a||i)&&await Z4.from("commercial_pitch_details").update({outcome:a?"won":"lost",won_at:a?new Date().toISOString():null,lost_at:i?new Date().toISOString():null,lost_reason:i?r??null:null}).eq("listing_id",t),n},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["listing",n.listingId]}),s.invalidateQueries({queryKey:["commercial-pitch",n.listingId]}),s.invalidateQueries({queryKey:["my-listings"]}),s.invalidateQueries({queryKey:["listings"]})}})}function TDs(){const s=Vt();return ft({mutationFn:async({listingId:t,values:n})=>{const{error:r}=await Z4.from("listings").update(n).eq("id",t);if(r)throw r},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["listing",n.listingId]}),s.invalidateQueries({queryKey:["my-listings"]})}})}function sst(s,t=90){return tt({queryKey:["commercial-engagement",s,t],queryFn:async()=>{const n=new Date(Date.now()-t*864e5).toISOString(),{data:r,error:a}=await Z4.from("commercial_engagement_events").select("*").eq("listing_id",s).gte("created_at",n).order("created_at",{ascending:!1}).limit(1e3);if(a)throw a;return r??[]},enabled:!!s})}function nst(s){return tt({queryKey:["commercial-leads",s],queryFn:async()=>{const{data:t,error:n}=await Z4.from("listing_leads").select("*").eq("listing_id",s).order("created_at",{ascending:!1});if(n)throw n;return t??[]},enabled:!!s})}const s0t="lu_commercial_session";function V7t(){try{let s=localStorage.getItem(s0t);return s||(s=crypto.randomUUID(),localStorage.setItem(s0t,s)),s}catch{return"anonymous"}}async function j$(s,t,n={}){try{await Z4.from("commercial_engagement_events").insert({listing_id:s,event_type:t,session_id:V7t(),source:typeof document<"u"&&document.referrer||null,metadata:n})}catch{}}const MDs={om_request:{eyebrow:"Confidential materials",title:"Request the Offering Memorandum",blurb:"Complete the form below and the offering package will be released to you immediately.",cta:"Request access"},tour_request:{eyebrow:"Property tour",title:"Schedule a tour",blurb:"Tell us who you represent and preferred timing — the listing broker will confirm directly.",cta:"Request tour"},investor_inquiry:{eyebrow:"Investment inquiry",title:"Request information",blurb:"Send a note to the listing broker about this opportunity.",cta:"Send inquiry"}};function PDs({open:s,onOpenChange:t,listingId:n,kind:r,documentId:a,requiresNda:i,brokerName:l}){const o=MDs[r],[c,d]=j.useState({firstName:"",lastName:"",email:"",phone:"",company:"",role:"principal",message:""}),[u,h]=j.useState(!1),[m,f]=j.useState(!1),[g,x]=j.useState(null),y=async()=>{if(!c.firstName.trim()||!c.email.trim()){re.error("Name and email are required");return}if(i&&r==="om_request"&&!u){re.error("Please acknowledge the confidentiality terms");return}f(!0);try{const{data:v,error:b}=await q.functions.invoke("commercial-lead",{body:{listingId:n,documentId:a??null,leadType:r,firstName:c.firstName,lastName:c.lastName,email:c.email,phone:c.phone||null,company:c.company||null,role:c.role,message:c.message||null,ndaAccepted:u,sessionId:V7t()}});if(b)throw b;if(v!=null&&v.error)throw new Error(v.error);x({signedUrl:(v==null?void 0:v.signedUrl)??null,fileName:(v==null?void 0:v.fileName)??null}),v!=null&&v.signedUrl&&window.open(v.signedUrl,"_blank")}catch(v){re.error(v.message||"Something went wrong. Please try again.")}finally{f(!1)}};return e.jsx(zs,{open:s,onOpenChange:v=>{t(v),v||x(null)},children:e.jsxs(Os,{className:"max-w-lg overflow-hidden border-white/10 bg-[#0b0f14] p-0 text-white",children:[e.jsxs("div",{className:"border-b border-white/10 bg-gradient-to-b from-white/[0.06] to-transparent px-7 py-6",children:[e.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-[0.24em] text-white/45",children:o.eyebrow}),e.jsx("h2",{className:"mt-2 font-serif text-2xl",children:g?"Access granted":o.title}),e.jsx("p",{className:"mt-1.5 text-sm text-white/60",children:g?g.signedUrl?"Your download has opened in a new tab. The secure link expires in 30 minutes.":`Your request has been sent${l?` to ${l}`:""}. You'll hear back shortly.`:o.blurb})]}),g?e.jsxs("div",{className:"space-y-4 px-7 py-7",children:[e.jsxs("div",{className:"flex items-center gap-3 rounded-xl border border-emerald-400/20 bg-emerald-400/10 px-4 py-3",children:[e.jsx(qr,{className:"h-5 w-5 text-emerald-400"}),e.jsx("p",{className:"text-sm text-white/80",children:g.fileName??"Request received"})]}),g.signedUrl&&e.jsx($,{className:"w-full",onClick:()=>window.open(g.signedUrl,"_blank"),children:"Download again"}),e.jsx($,{variant:"ghost",className:"w-full text-white/60 hover:text-white",onClick:()=>t(!1),children:"Close"})]}):e.jsxs("div",{className:"space-y-4 px-7 py-6",children:[e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2",children:[e.jsx(gR,{label:"First name *",children:e.jsx(pe,{value:c.firstName,onChange:v=>d({...c,firstName:v.target.value}),className:"border-white/15 bg-white/5 text-white"})}),e.jsx(gR,{label:"Last name",children:e.jsx(pe,{value:c.lastName,onChange:v=>d({...c,lastName:v.target.value}),className:"border-white/15 bg-white/5 text-white"})})]}),e.jsx(gR,{label:"Email *",children:e.jsx(pe,{type:"email",value:c.email,onChange:v=>d({...c,email:v.target.value}),className:"border-white/15 bg-white/5 text-white"})}),e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2",children:[e.jsx(gR,{label:"Company",children:e.jsx(pe,{value:c.company,onChange:v=>d({...c,company:v.target.value}),className:"border-white/15 bg-white/5 text-white"})}),e.jsx(gR,{label:"Phone",children:e.jsx(pe,{value:c.phone,onChange:v=>d({...c,phone:v.target.value}),className:"border-white/15 bg-white/5 text-white"})})]}),e.jsx(gR,{label:"I am a *",children:e.jsxs(ms,{value:c.role,onValueChange:v=>d({...c,role:v}),children:[e.jsx(us,{className:"border-white/15 bg-white/5 text-white",children:e.jsx(fs,{})}),e.jsx(hs,{children:Object.entries(iGe).map(([v,b])=>e.jsx(Ge,{value:v,children:b},v))})]})}),r!=="om_request"&&e.jsx(gR,{label:"Message",children:e.jsx(Rs,{rows:3,value:c.message,onChange:v=>d({...c,message:v.target.value}),className:"border-white/15 bg-white/5 text-white",placeholder:r==="tour_request"?"Preferred dates and times…":"Your question…"})}),i&&r==="om_request"&&e.jsxs("label",{className:"flex cursor-pointer items-start gap-3 rounded-xl border border-white/10 bg-white/[0.04] p-3",children:[e.jsx(ai,{checked:u,onCheckedChange:v=>h(!!v),className:"mt-0.5 border-white/30"}),e.jsxs("span",{className:"text-xs leading-relaxed text-white/65",children:[e.jsx(bm,{className:"mr-1 inline h-3.5 w-3.5"}),"I acknowledge these materials are confidential and agree not to distribute them without the listing broker's written consent."]})]}),e.jsxs($,{className:"w-full",size:"lg",onClick:y,disabled:m,children:[m?e.jsx(kt,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(pc,{className:"mr-2 h-4 w-4"}),o.cta]}),e.jsx("p",{className:"text-center text-[11px] text-white/40",children:"Your information is shared only with the listing broker."})]})]})})}function gR({label:s,children:t}){return e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{className:"text-[11px] font-medium uppercase tracking-wider text-white/50",children:s}),t]})}function rst(s){if(!s)return[];const t=[],n=(r,a)=>{a&&t.push({label:r,value:a})};return n("Cap Rate",LEe(s.cap_rate)),n("NOI",Jyt(s.noi)),n("Occupancy",s.occupancy_pct!=null?`${Math.round(Number(s.occupancy_pct))}%`:null),n("Building SF",bE(s.building_sf)),n("Available SF",bE(s.available_sf)),n("Lot Size",s.lot_acres!=null?`${Number(s.lot_acres)} AC`:null),n("Units",s.units!=null?String(s.units):null),n("Price / SF",s.price_per_sf!=null?BN(s.price_per_sf,2):null),n("Price / Unit",Jyt(s.price_per_unit)),n("Lease Rate",s.deal_type!=="sale"?oGe(s):null),n("Year Built",null),n("Zoning",s.zoning??null),t}function H7t({details:s,className:t="",tone:n="light"}){const r=rst(s).slice(0,8);if(!r.length)return null;const a=n==="dark";return e.jsx("div",{className:`grid gap-px overflow-hidden rounded-xl border ${a?"border-white/10 bg-white/10":"bg-border"} sm:grid-cols-2 lg:grid-cols-4 ${t}`,children:r.map(i=>e.jsxs("div",{className:`${a?"bg-[#0b0f14]":"bg-card"} px-5 py-4`,children:[e.jsx("p",{className:`text-[10px] font-semibold uppercase tracking-[0.18em] ${a?"text-white/45":"text-muted-foreground"}`,children:i.label}),e.jsx("p",{className:`mt-1.5 text-xl font-semibold tabular-nums ${a?"text-white":""}`,children:i.value})]},i.label))})}function IDs(s){return tt({queryKey:["commercial-microsite",s],queryFn:async()=>{const{data:t,error:n}=await q.functions.invoke("commercial-public",{body:{slug:s}});if(n)throw n;if(t!=null&&t.error)throw new Error(t.error);return t},enabled:!!s})}function LDs({slug:s}){var O,U;const{data:t,isLoading:n,error:r}=IDs(s),[a,i]=j.useState(null),[l,o]=j.useState(null),c=t==null?void 0:t.listing,d=(t==null?void 0:t.details)??void 0,u=(t==null?void 0:t.documents)??[],h=(c==null?void 0:c.photos)??[],m=c==null?void 0:c.agent,f=!!(d!=null&&d.is_confidential||d!=null&&d.hide_address),g=j.useMemo(()=>rst(d).slice(0,8),[d]);if(j.useEffect(()=>{c!=null&&c.id&&j$(c.id,"page_view",{slug:s})},[c==null?void 0:c.id,s]),j.useEffect(()=>{if(a===null)return;const W=V=>{V.key==="Escape"&&i(null),V.key==="ArrowRight"&&i(G=>G===null?G:(G+1)%h.length),V.key==="ArrowLeft"&&i(G=>G===null?G:(G-1+h.length)%h.length)};return window.addEventListener("keydown",W),()=>window.removeEventListener("keydown",W)},[a,h.length]),n)return e.jsx("div",{className:"flex min-h-screen items-center justify-center bg-[#0b0f14]",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-2 border-white/20 border-t-white/70"})});if(r||!c)return e.jsx("div",{className:"flex min-h-screen items-center justify-center bg-[#0b0f14] px-6 text-center text-white/60",children:"This offering is no longer available."});const x=iL(c,d),y=Kae(c,d),v=c.latitude&&c.longitude?`${c.latitude},${c.longitude}`:f?[d==null?void 0:d.submarket,c.city,c.state].filter(Boolean).join(", ")||null:[c.property_address,c.city,c.state].filter(Boolean).join(", ")||null,b=(O=h[0])==null?void 0:O.photo_url,w=(d==null?void 0:d.tenants)??[],S=(d==null?void 0:d.spaces)??[],C=(d==null?void 0:d.demographics)??{},E=(d==null?void 0:d.traffic_counts)??[],I=(d==null?void 0:d.investment_highlights)??[],P=(d==null?void 0:d.property_highlights)??[],R=["radius_1","radius_3","radius_5"].some(W=>(C==null?void 0:C[W])&&Object.values(C[W]).some(Boolean)),D=(W,V)=>{o({kind:W,documentId:V}),j$(c.id,W==="om_request"?"om_request":W,{})};return e.jsxs("div",{className:"min-h-screen bg-[#0b0f14] text-white antialiased",children:[e.jsxs(Ml,{children:[e.jsx("title",{children:`${x} | ${y}`}),e.jsx("meta",{name:"description",content:(c.description??"").slice(0,155)||`${ML[(d==null?void 0:d.deal_type)??"sale"]} — ${y}`}),f&&e.jsx("meta",{name:"robots",content:"noindex,nofollow"}),e.jsx("meta",{property:"og:title",content:x}),e.jsx("meta",{property:"og:type",content:"website"})]}),e.jsx("header",{className:"fixed inset-x-0 top-0 z-40 border-b border-white/10 bg-[#0b0f14]/80 backdrop-blur",children:e.jsxs("div",{className:"mx-auto flex max-w-7xl items-center justify-between px-6 py-3.5 md:px-10",children:[e.jsxs("a",{href:typeof window<"u"&&window.location.hostname.startsWith("commercial.")?"/":"/public/commercial",className:"flex items-center gap-2 text-[11px] font-semibold uppercase tracking-[0.22em] text-white/70 transition-colors hover:text-white",children:[e.jsx("span",{"aria-hidden":!0,children:"←"})," All opportunities"]}),e.jsx("span",{className:"text-[11px] font-semibold uppercase tracking-[0.22em] text-white/45",children:"LevelUp Commercial"})]})}),e.jsxs("section",{className:"relative min-h-[86vh] w-full overflow-hidden",children:[b?e.jsx("img",{src:b,alt:x,className:"absolute inset-0 h-full w-full object-cover"}):e.jsx("div",{className:"absolute inset-0 bg-gradient-to-br from-[#12202b] to-[#0b0f14]"}),e.jsx("div",{className:"absolute inset-0 bg-gradient-to-t from-[#0b0f14] via-[#0b0f14]/60 to-[#0b0f14]/30"}),e.jsxs("div",{className:"relative mx-auto flex min-h-[86vh] max-w-7xl flex-col justify-end px-6 pb-16 pt-24 md:px-10",children:[e.jsxs("div",{className:"mb-5 flex flex-wrap items-center gap-2.5",children:[e.jsx("span",{className:"rounded-full border border-white/25 px-3.5 py-1 text-[10px] font-semibold uppercase tracking-[0.22em]",children:ML[(d==null?void 0:d.deal_type)??"sale"]}),(d==null?void 0:d.commercial_type)&&e.jsx("span",{className:"rounded-full border border-white/15 bg-white/5 px-3.5 py-1 text-[10px] font-semibold uppercase tracking-[0.22em] text-white/70",children:c6[d.commercial_type]}),f&&e.jsxs("span",{className:"inline-flex items-center gap-1.5 rounded-full border border-amber-300/30 bg-amber-300/10 px-3.5 py-1 text-[10px] font-semibold uppercase tracking-[0.22em] text-amber-200",children:[e.jsx(pc,{className:"h-3 w-3"})," Confidential offering"]})]}),e.jsx("h1",{className:"max-w-4xl font-serif text-4xl leading-[1.05] tracking-tight md:text-6xl lg:text-7xl",children:x}),e.jsxs("p",{className:"mt-4 flex items-center gap-2 text-sm uppercase tracking-[0.2em] text-white/60",children:[e.jsx(ci,{className:"h-4 w-4"})," ",y]}),e.jsxs("div",{className:"mt-8 flex flex-wrap items-end gap-x-10 gap-y-5",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-[0.24em] text-white/45",children:(d==null?void 0:d.deal_type)==="lease"?"Lease rate":"Asking price"}),e.jsx("p",{className:"mt-1 text-3xl font-semibold tabular-nums md:text-4xl",children:EG(d,c.price)})]}),(d==null?void 0:d.cap_rate)!=null&&e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-[0.24em] text-white/45",children:"Cap rate"}),e.jsx("p",{className:"mt-1 text-3xl font-semibold tabular-nums md:text-4xl",children:LEe(d.cap_rate)})]})]}),e.jsxs("div",{className:"mt-9 flex flex-wrap gap-3",children:[e.jsxs($,{size:"lg",className:"rounded-full px-7",onClick:()=>{var W;return D("om_request",((W=u.find(V=>V.doc_kind==="om"))==null?void 0:W.id)??null)},children:["Request Offering Memorandum ",e.jsx(ei,{className:"ml-2 h-4 w-4"})]}),e.jsx($,{size:"lg",variant:"outline",className:"rounded-full border-white/25 bg-white/5 px-7 text-white hover:bg-white/10 hover:text-white",onClick:()=>D("tour_request"),children:"Schedule a tour"})]})]})]}),g.length>0&&e.jsx("section",{className:"border-y border-white/10 bg-white/[0.02]",children:e.jsx("div",{className:"mx-auto grid max-w-7xl gap-px bg-white/10",style:{gridTemplateColumns:`repeat(${Math.min(g.length,4)}, minmax(0, 1fr))`},children:g.map(W=>e.jsxs("div",{className:"bg-[#0b0f14] px-6 py-8",children:[e.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-[0.2em] text-white/40",children:W.label}),e.jsx("p",{className:"mt-2 text-2xl font-semibold tabular-nums md:text-3xl",children:W.value})]},W.label))})}),I.length>0&&e.jsx(wM,{eyebrow:"The opportunity",title:"Investment highlights",children:e.jsx("div",{className:"grid gap-x-12 gap-y-8 md:grid-cols-2",children:I.map((W,V)=>e.jsxs("div",{className:"flex gap-5 border-t border-white/10 pt-6",children:[e.jsx("span",{className:"font-serif text-2xl text-white/25 tabular-nums",children:String(V+1).padStart(2,"0")}),e.jsx("p",{className:"text-lg leading-relaxed text-white/85",children:W})]},V))})}),(c.description||P.length>0)&&e.jsx(wM,{eyebrow:"Property",title:"The asset",children:e.jsxs("div",{className:"grid gap-12 lg:grid-cols-[1.4fr_1fr]",children:[c.description&&e.jsx("div",{className:"space-y-5 text-lg leading-relaxed text-white/70",children:String(c.description).split(/\n{2,}/).map((W,V)=>e.jsx("p",{children:W},V))}),P.length>0&&e.jsx("ul",{className:"space-y-3 self-start rounded-2xl border border-white/10 bg-white/[0.03] p-7",children:P.map((W,V)=>e.jsxs("li",{className:"flex gap-3 text-sm text-white/75",children:[e.jsx("span",{className:"mt-2 h-1 w-1 shrink-0 rounded-full bg-white/50"})," ",W]},V))})]})}),h.length>1&&e.jsx(wM,{eyebrow:"Gallery",title:"Property imagery",children:e.jsx("div",{className:"grid gap-3 md:grid-cols-3",children:h.slice(1,10).map((W,V)=>e.jsx("button",{onClick:()=>{i(V+1),j$(c.id,"gallery_view",{})},className:`group relative overflow-hidden rounded-xl ${V===0?"md:col-span-2 md:row-span-2":""}`,children:e.jsx("img",{src:W.photo_url,alt:`${x} — image ${V+2}`,loading:"lazy",className:`w-full object-cover transition-transform duration-700 group-hover:scale-[1.04] ${V===0?"h-full min-h-[280px] md:min-h-[560px]":"h-[180px] md:h-[275px]"}`})},W.id))})}),((d==null?void 0:d.noi)||(d==null?void 0:d.gross_income)||(d==null?void 0:d.operating_expenses)||(d==null?void 0:d.occupancy_pct)!=null)&&e.jsxs(wM,{eyebrow:"Financials",title:"Offering snapshot",children:[e.jsx("div",{className:"grid gap-px overflow-hidden rounded-2xl border border-white/10 bg-white/10 sm:grid-cols-2 lg:grid-cols-4",children:[{l:"Net operating income",v:BN(d==null?void 0:d.noi)},{l:"Gross income",v:BN(d==null?void 0:d.gross_income)},{l:"Operating expenses",v:BN(d==null?void 0:d.operating_expenses)},{l:"Occupancy",v:(d==null?void 0:d.occupancy_pct)!=null?`${Math.round(Number(d.occupancy_pct))}%`:null},{l:"Price per SF",v:(d==null?void 0:d.price_per_sf)!=null?BN(d.price_per_sf,2):null},{l:"Price per unit",v:BN(d==null?void 0:d.price_per_unit)},{l:"Tenancy",v:d!=null&&d.tenancy?`${d.tenancy[0].toUpperCase()}${d.tenancy.slice(1)} tenant`:null},{l:"Broker co-op",v:(d==null?void 0:d.broker_coop_pct)!=null?`${d.broker_coop_pct}%`:null}].filter(W=>W.v).map(W=>e.jsxs("div",{className:"bg-[#0b0f14] px-6 py-7",children:[e.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-[0.2em] text-white/40",children:W.l}),e.jsx("p",{className:"mt-2 text-xl font-semibold tabular-nums",children:W.v})]},W.l))}),(d==null?void 0:d.call_for_offers_at)&&e.jsxs("p",{className:"mt-6 inline-flex items-center gap-2 rounded-full border border-amber-300/25 bg-amber-300/10 px-5 py-2 text-sm text-amber-100",children:["Call for offers · ",new Date(d.call_for_offers_at).toLocaleDateString(void 0,{month:"long",day:"numeric",year:"numeric"})]})]}),(w.length>0||S.length>0)&&e.jsx(wM,{eyebrow:"Occupancy",title:S.length?"Space availability":"Tenant roster",children:e.jsx("div",{className:"overflow-hidden rounded-2xl border border-white/10",children:e.jsxs("table",{className:"w-full text-left text-sm",children:[e.jsx("thead",{className:"bg-white/[0.04] text-[10px] uppercase tracking-[0.18em] text-white/45",children:e.jsxs("tr",{children:[e.jsx("th",{className:"px-6 py-4",children:S.length?"Suite":"Tenant"}),e.jsx("th",{className:"px-6 py-4",children:"SF"}),e.jsx("th",{className:"px-6 py-4",children:S.length?"Rate":"Rent"}),e.jsx("th",{className:"px-6 py-4",children:S.length?"Availability":"Lease expiry"})]})}),e.jsx("tbody",{className:"divide-y divide-white/5",children:(S.length?S:w).map((W,V)=>e.jsxs("tr",{className:"text-white/80",children:[e.jsx("td",{className:"px-6 py-4 font-medium text-white",children:W.suite??W.name??"—"}),e.jsx("td",{className:"px-6 py-4 tabular-nums",children:W.sf?bE(Number(W.sf)):"—"}),e.jsx("td",{className:"px-6 py-4",children:W.rate??W.rent??"—"}),e.jsx("td",{className:"px-6 py-4",children:W.availability??W.lease_expiry??"—"})]},V))})]})})}),e.jsx(wM,{eyebrow:"Location",title:d!=null&&d.submarket?`${d.submarket} submarket`:y,children:e.jsxs("div",{className:"grid gap-8 lg:grid-cols-[1.2fr_1fr]",children:[v?e.jsx("div",{className:"overflow-hidden rounded-2xl border border-white/10",children:e.jsx("iframe",{title:"Property location",className:"h-[420px] w-full",loading:"lazy",src:`https://www.google.com/maps?q=${encodeURIComponent(v)}&z=${c.latitude&&c.longitude?15:12}&output=embed`,onLoad:()=>j$(c.id,"map_view",{})})}):e.jsx("div",{className:"flex h-[420px] items-center justify-center rounded-2xl border border-white/10 bg-white/[0.03] text-center text-sm text-white/50",children:f?"Exact location released with the Offering Memorandum.":y}),e.jsxs("div",{className:"space-y-5",children:[(d==null?void 0:d.zoning)&&e.jsx(N$,{label:"Zoning",value:d.zoning}),(d==null?void 0:d.lot_acres)!=null&&e.jsx(N$,{label:"Site size",value:`${d.lot_acres} acres`}),(d==null?void 0:d.parking_spaces)!=null&&e.jsx(N$,{label:"Parking",value:`${d.parking_spaces} spaces`}),(d==null?void 0:d.opportunity_zone)&&e.jsx(N$,{label:"Opportunity Zone",value:"Qualified"}),E.filter(W=>W.road||W.count).map((W,V)=>e.jsx(N$,{label:`Traffic count — ${W.road??"Adjacent road"}`,value:`${W.count??"—"} VPD`},V)),!(d!=null&&d.zoning)&&(d==null?void 0:d.lot_acres)==null&&(d==null?void 0:d.parking_spaces)==null&&!(d!=null&&d.opportunity_zone)&&e.jsx(N$,{label:"Submarket",value:(d==null?void 0:d.submarket)||y})]})]})}),R&&e.jsx(wM,{eyebrow:"Market",title:"Demographics",children:e.jsx("div",{className:"grid gap-4 md:grid-cols-3",children:[["radius_1","1 mile"],["radius_3","3 miles"],["radius_5","5 miles"]].map(([W,V])=>{const G=C==null?void 0:C[W];return!G||!Object.values(G).some(Boolean)?null:e.jsxs("div",{className:"rounded-2xl border border-white/10 bg-white/[0.03] p-7",children:[e.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-[0.2em] text-white/40",children:V}),e.jsx("dl",{className:"mt-5 space-y-3 text-sm",children:[["Population",G.population],["Households",G.households],["Avg. income",G.avg_income],["Daytime pop.",G.daytime_pop]].filter(([,Y])=>Y).map(([Y,X])=>e.jsxs("div",{className:"flex justify-between gap-4",children:[e.jsx("dt",{className:"text-white/50",children:Y}),e.jsx("dd",{className:"font-medium tabular-nums",children:X})]},Y))})]},W)})})}),u.length>0&&e.jsx(wM,{eyebrow:"Deal room",title:"Offering documents",children:e.jsx("div",{className:"grid gap-4 md:grid-cols-2",children:u.map(W=>{const V=W.gate_level==="public";return e.jsxs("div",{className:"flex items-center gap-4 rounded-2xl border border-white/10 bg-white/[0.03] p-5 transition-colors hover:border-white/20",children:[e.jsx("div",{className:"flex h-11 w-11 shrink-0 items-center justify-center rounded-xl border border-white/10 bg-white/5",children:V?e.jsx(di,{className:"h-5 w-5"}):W.gate_level==="nda"?e.jsx(bm,{className:"h-5 w-5"}):e.jsx(pc,{className:"h-5 w-5"})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"truncate font-medium",children:W.title||aGe[W.doc_kind||"other"]}),e.jsx("p",{className:"text-xs text-white/45",children:V?"Available to download":W.gate_level==="nda"?"Confidentiality acknowledgement required":"Registration required"})]}),e.jsx($,{size:"sm",variant:"outline",className:"border-white/20 bg-transparent text-white hover:bg-white/10 hover:text-white",onClick:()=>D("om_request",W.id),children:V?"Download":"Request"})]},W.id)})})}),m&&e.jsx("section",{className:"border-t border-white/10 bg-white/[0.02]",children:e.jsx("div",{className:"mx-auto max-w-7xl px-6 py-20 md:px-10",children:e.jsxs("div",{className:"flex flex-col items-start gap-8 md:flex-row md:items-center md:justify-between",children:[e.jsxs("div",{className:"flex items-center gap-6",children:[m.avatar_url&&e.jsx("img",{src:m.avatar_url,alt:m.name,className:"h-24 w-24 rounded-full object-cover ring-1 ring-white/15"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-[0.22em] text-white/40",children:"Exclusively listed by"}),e.jsx("p",{className:"mt-2 font-serif text-2xl",children:m.name}),e.jsx("p",{className:"text-sm text-white/55",children:((U=m.brokerage)==null?void 0:U.name)||m.brokerage_name})]})]}),e.jsxs("div",{className:"flex flex-wrap gap-3",children:[m.email&&e.jsxs($,{variant:"outline",className:"rounded-full border-white/20 bg-transparent text-white hover:bg-white/10 hover:text-white",onClick:()=>{j$(c.id,"contact_click",{}),window.location.href=`mailto:${m.email}`},children:[e.jsx(mn,{className:"mr-2 h-4 w-4"})," Email"]}),m.phone&&e.jsxs($,{variant:"outline",className:"rounded-full border-white/20 bg-transparent text-white hover:bg-white/10 hover:text-white",onClick:()=>{j$(c.id,"contact_click",{}),window.location.href=`tel:${m.phone}`},children:[e.jsx(Da,{className:"mr-2 h-4 w-4"})," Call"]}),e.jsx($,{className:"rounded-full",onClick:()=>D("investor_inquiry"),children:"Request information"})]})]})})}),e.jsx("footer",{className:"border-t border-white/10 py-10 text-center text-xs text-white/35",children:e.jsx("p",{children:"The information contained herein has been obtained from sources believed reliable but is not guaranteed. Prospective purchasers and tenants should conduct their own independent investigation."})}),e.jsx("div",{className:"sticky bottom-0 z-30 border-t border-white/10 bg-[#0b0f14]/90 backdrop-blur-xl",children:e.jsxs("div",{className:"mx-auto flex max-w-7xl flex-wrap items-center justify-between gap-3 px-6 py-3.5 md:px-10",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"truncate text-sm font-medium",children:x}),e.jsxs("p",{className:"truncate text-xs text-white/50",children:[EG(d,c.price)," · ",y]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx($,{size:"sm",variant:"outline",className:"rounded-full border-white/20 bg-transparent text-white hover:bg-white/10 hover:text-white",onClick:()=>D("tour_request"),children:"Tour"}),e.jsx($,{size:"sm",className:"rounded-full",onClick:()=>{var W;return D("om_request",((W=u.find(V=>V.doc_kind==="om"))==null?void 0:W.id)??null)},children:"Request OM"})]})]})}),e.jsx(zs,{open:a!==null,onOpenChange:W=>!W&&i(null),children:e.jsx(Os,{className:"max-w-[96vw] border-none bg-transparent p-0 shadow-none",children:a!==null&&h[a]&&e.jsxs("div",{className:"relative",children:[e.jsx("img",{src:h[a].photo_url,alt:"",className:"max-h-[88vh] w-full rounded-xl object-contain"}),e.jsx("button",{className:"absolute right-3 top-3 rounded-full bg-black/60 p-2",onClick:()=>i(null),children:e.jsx(gr,{className:"h-5 w-5"})}),e.jsx("button",{className:"absolute left-3 top-1/2 -translate-y-1/2 rounded-full bg-black/60 p-2",onClick:()=>i(W=>(W-1+h.length)%h.length),children:e.jsx(Cd,{className:"h-6 w-6"})}),e.jsx("button",{className:"absolute right-3 top-1/2 -translate-y-1/2 rounded-full bg-black/60 p-2",onClick:()=>i(W=>(W+1)%h.length),children:e.jsx(Di,{className:"h-6 w-6"})})]})})}),l&&e.jsx(PDs,{open:!0,onOpenChange:W=>!W&&o(null),listingId:c.id,kind:l.kind,documentId:l.documentId,requiresNda:!!(d!=null&&d.requires_nda)||(d==null?void 0:d.om_gate_mode)==="nda",brokerName:m==null?void 0:m.name})]})}function wM({eyebrow:s,title:t,children:n}){return e.jsx("section",{className:"border-t border-white/10",children:e.jsxs("div",{className:"mx-auto max-w-7xl px-6 py-20 md:px-10 md:py-24",children:[e.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-[0.24em] text-white/40",children:s}),e.jsx("h2",{className:"mt-3 font-serif text-3xl tracking-tight md:text-4xl",children:t}),e.jsx("div",{className:"mt-12",children:n})]})})}function N$({label:s,value:t}){return e.jsxs("div",{className:"border-t border-white/10 pt-4",children:[e.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-[0.2em] text-white/40",children:s}),e.jsx("p",{className:"mt-1 text-lg",children:t})]})}const n0t="/assets/levelup-logo-color-BeKd2k_g.png",RDs={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-600"},f7e={active:"For Sale",coming_soon:"Coming Soon",office_exclusive:"Office Exclusive",pre_market:"Pre-Market",price_improvement:"Price Improvement",under_contract:"Under Contract",sold:"Sold"},r0t={single_family:"Single Family",condo:"Condo",townhouse:"Townhouse",land:"Land",multi_family:"Multi-Family",luxury:"Luxury",commercial:"Commercial",other:"Other"},p7e=s=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(s),TZ=s=>new Intl.NumberFormat("en-US").format(s);function ast({slugOverride:s}={}){var St,Xs,vt,gs,Ss,Is;const t=Wi(),n=s||t.slugOrId,[r]=gc(),{data:a,isLoading:i}=bDs(n||""),l=_Ds(),o=wDs(),c=r.get("ref"),[d,u]=j.useState(""),[h,m]=j.useState(""),[f,g]=j.useState(""),[x,y]=j.useState(""),[v,b]=j.useState(""),[w,S]=j.useState(""),[C,E]=j.useState(""),[I,P]=j.useState("in_person"),[R,D]=j.useState("info"),[O,U]=j.useState(!1),[W,V]=j.useState(!1),[G,Y]=j.useState(null),[X,ae]=j.useState(!1),[ie,ne]=j.useState(!1),[te,J]=j.useState(!1),[ce,_e]=j.useState(20),[he,ue]=j.useState(6.5),[ve,Ee]=j.useState(30),Se=j.useRef(null),[Le,Fe]=j.useState(!1);j.useEffect(()=>{const Ys=()=>Fe(window.scrollY>300);return window.addEventListener("scroll",Ys,{passive:!0}),()=>window.removeEventListener("scroll",Ys)},[]),j.useEffect(()=>{c&&o.mutate(c)},[c]),j.useEffect(()=>{window.scrollTo({top:0,left:0,behavior:"auto"})},[n]);const ke=(a==null?void 0:a.photos)||[],Ve=ke.find(Ys=>Ys.is_primary)||ke[0],je=j.useMemo(()=>{if(!(a!=null&&a.price))return 0;const Ys=a.price*(1-ce/100),cs=he/100/12,js=ve*12;return cs===0?Ys/js:Ys*cs/(1-Math.pow(1+cs,-js))},[a==null?void 0:a.price,ce,he,ve]),Ae=async()=>{const Ys=window.location.href;if(navigator.share)try{await navigator.share({title:document.title,url:Ys})}catch{}else await navigator.clipboard.writeText(Ys),re.success("Link copied to clipboard")},Ce=async Ys=>{if(Ys.preventDefault(),!d.trim()||!f.trim()||!a)return;const cs=R==="showing";if(cs&&!w){re.error("Please pick a preferred date for your showing");return}U(!0);try{await l.mutateAsync({listingId:a.id,agentId:a.agent_id,firstName:d.trim(),lastName:h.trim(),email:f.trim(),phone:x.trim(),shareToken:c,leadType:cs?"showing_request":"info_request",preferredDate:cs?w:null,preferredTime:cs&&C||null,showingMode:cs?I:null,message:v.trim()||null}),V(!0),re.success(cs?"Showing request sent! The agent will confirm details shortly.":"Thanks! The agent will be in touch soon.")}catch(js){console.error("Lead submission error:",js),re.error(`Failed to submit: ${js.message||"Please try again"}`)}finally{U(!1)}},qe=()=>{G!==null&&Y(G===0?ke.length-1:G-1)},ze=()=>{G!==null&&Y(G===ke.length-1?0:G+1)};if((a==null?void 0:a.listing_class)==="commercial")return e.jsx(LDs,{slug:n});if(i)return e.jsx("div",{className:"min-h-screen bg-neutral-950",children:e.jsx(yn,{className:"h-[100svh] w-full rounded-none bg-neutral-900"})});if(!a)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(wr,{to:"/public/listings",className:"flex items-center gap-2",children:e.jsx("img",{src:n0t,alt:"LevelUp",className:"h-8"})})})}),e.jsxs("div",{className:"container mx-auto px-4 py-24 text-center",children:[e.jsx(va,{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-6",children:"This listing may no longer be available."}),e.jsx($,{asChild:!0,children:e.jsx(wr,{to:typeof window<"u"&&window.location.host==="listings.relevelup.com"?"/":"/public/listings",children:"Browse All Listings"})})]})]});const $e=a.property_address?`${a.property_address} — ${a.city}, ${a.state}`:`${a.city}, ${a.state} Home for Sale`,ct=((Xs=(St=a.agent)==null?void 0:St.brokerage)==null?void 0:Xs.name)||((vt=a.agent)==null?void 0:vt.brokerage_name),Xe=((gs=a.agent)==null?void 0:gs.name)||"",it=ct||Xe||"",at=f7e[a.status]==="Sold"?"Just Sold":f7e[a.status],Ke=at?`${at}: ${$e}`:$e,nt=[`${p7e(a.price)} · ${a.city}, ${a.state}`,Xe?`Presented by ${Xe}${ct?`, ${ct}`:""}.`:""].filter(Boolean).join(" · "),xt=a.latitude&&a.longitude?`https://maps.google.com/maps?q=${a.latitude},${a.longitude}&z=15&output=embed`:a.property_address?`https://maps.google.com/maps?q=${encodeURIComponent(`${a.property_address}, ${a.city}, ${a.state}`)}&z=15&output=embed`:null,rt=a.description||"",Yt=rt.length>420,qt=te||!Yt?rt:rt.slice(0,420).trimEnd()+"…",ts=a.page_config||{},ys=Ys=>{var cs;return(((cs=ts.sections)==null?void 0:cs[Ys])??!0)!==!1},Bt=Array.isArray(ts.addons)?ts.addons:[],Ft=ts.custom_note||"",rs=ts.accent_color||null;return e.jsxs(e.Fragment,{children:[e.jsxs(Ml,{children:[e.jsx("title",{children:it?`${$e} | ${it}`:$e}),e.jsx("meta",{name:"description",content:`${p7e(a.price)} · ${a.bedrooms||""}BD ${a.bathrooms||""}BA ${a.square_footage?a.square_footage.toLocaleString()+" sqft · ":""}${r0t[a.property_type]} in ${a.city}, ${a.state}. ${rt.slice(0,140)}`}),e.jsx("link",{rel:"canonical",href:`https://listings.relevelup.com/${a.slug||a.id}`}),e.jsx("link",{rel:"preconnect",href:"https://fonts.googleapis.com"}),e.jsx("link",{rel:"preconnect",href:"https://fonts.gstatic.com",crossOrigin:""}),e.jsx("link",{href:"https://fonts.googleapis.com/css2?family=Fraunces:opsz,wght@9..144,300;9..144,400;9..144,500;9..144,600&display=swap",rel:"stylesheet"}),e.jsx("meta",{property:"og:title",content:Ke}),e.jsx("meta",{property:"og:description",content:nt}),e.jsx("meta",{property:"og:type",content:"website"}),e.jsx("meta",{property:"og:url",content:`https://listings.relevelup.com/${a.slug||a.id}`}),Ve&&e.jsx("meta",{property:"og:image",content:Ve.photo_url}),it&&e.jsx("meta",{property:"og:site_name",content:it}),e.jsx("meta",{name:"twitter:card",content:"summary_large_image"}),e.jsx("meta",{name:"twitter:title",content:Ke}),e.jsx("meta",{name:"twitter:description",content:nt}),Ve&&e.jsx("meta",{name:"twitter:image",content:Ve.photo_url}),e.jsx("meta",{name:"robots",content:"index, follow"}),e.jsx("script",{type:"application/ld+json",children:JSON.stringify({"@context":"https://schema.org","@type":"RealEstateListing",name:a.property_address||`${a.city}, ${a.state} Home`,description:rt,url:`https://listings.relevelup.com/${a.slug||a.id}`,datePosted:a.created_at,image:ke.map(Ys=>Ys.photo_url),address:{"@type":"PostalAddress",streetAddress:a.property_address||void 0,addressLocality:a.city,addressRegion:a.state,addressCountry:"US"},offers:{"@type":"Offer",price:a.price,priceCurrency:"USD",availability:a.status==="sold"?"https://schema.org/SoldOut":a.status==="under_contract"?"https://schema.org/LimitedAvailability":"https://schema.org/InStock"},numberOfRooms:a.bedrooms||void 0,numberOfBathroomsTotal:a.bathrooms||void 0,floorSize:a.square_footage?{"@type":"QuantitativeValue",value:a.square_footage,unitCode:"FTK"}:void 0,yearBuilt:a.year_built||void 0})}),e.jsx("style",{children:` .font-display { font-family: 'Fraunces', ui-serif, Georgia, serif; font-optical-sizing: auto; letter-spacing: -0.02em; } @keyframes kb-zoom { from { transform: scale(1.08); } to { transform: scale(1); } } .kb-zoom { animation: kb-zoom 12s ease-out forwards; } .noscroll::-webkit-scrollbar { display: none; } `})]}),e.jsxs("div",{className:"bg-neutral-950 text-neutral-100 min-h-screen",children:[e.jsx("header",{className:`fixed inset-x-0 top-0 z-40 transition-all duration-300 ${Le?"bg-neutral-950/85 backdrop-blur-xl border-b border-white/10 py-3":"bg-gradient-to-b from-black/60 to-transparent py-4"}`,children:e.jsxs("div",{className:"max-w-7xl mx-auto px-4 sm:px-6 flex items-center justify-between gap-3",children:[e.jsxs(wr,{to:typeof window<"u"&&window.location.host==="listings.relevelup.com"?"/":"/public/listings",className:"flex items-center gap-2 text-white/90 hover:text-white",children:[e.jsx(qa,{className:"h-4 w-4"}),e.jsx("span",{className:"text-sm font-medium hidden sm:inline",children:"All Listings"})]}),Le&&e.jsx("div",{className:"hidden md:flex items-center gap-1 text-sm",children:[["overview","Overview"],["gallery","Gallery"],["story","The Story"],["video","Video"],["map","Location"],["payment","Payment"],["agent","Agent"]].map(([Ys,cs])=>e.jsx("a",{href:`#${Ys}`,className:"px-3 py-1.5 rounded-full text-white/70 hover:text-white hover:bg-white/10 transition",children:cs},Ys))}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(eDs,{listingId:a.id,listingAddress:a.property_address?`${a.property_address}, ${a.city}, ${a.state}`:`${a.city}, ${a.state}`,className:"h-9 w-9 rounded-full border border-white/20 bg-white/5 backdrop-blur hover:bg-white/15 flex items-center justify-center transition text-white"}),e.jsx("button",{onClick:Ae,className:"h-9 w-9 rounded-full border border-white/20 bg-white/5 backdrop-blur hover:bg-white/15 flex items-center justify-center transition","aria-label":"Share",children:e.jsx(zd,{className:"h-4 w-4 text-white"})}),e.jsx($,{size:"sm",onClick:()=>ae(!0),className:"hidden sm:inline-flex bg-white text-neutral-900 hover:bg-white/90 rounded-full h-9 px-4 font-medium",children:"Request Tour"})]})]})}),e.jsxs("section",{ref:Se,id:"overview",className:"relative h-[100svh] min-h-[620px] w-full overflow-hidden",children:[Ve?e.jsx("img",{src:Ve.photo_url,alt:a.property_address||`${a.city}, ${a.state}`,className:"absolute inset-0 h-full w-full object-cover kb-zoom"}):e.jsx("div",{className:"absolute inset-0 bg-gradient-to-br from-neutral-800 to-neutral-950"}),e.jsx("div",{className:"absolute inset-0 bg-gradient-to-t from-black via-black/50 to-black/20"}),e.jsx("div",{className:"absolute inset-0 bg-gradient-to-r from-black/40 via-transparent to-transparent"}),e.jsxs("div",{className:"absolute top-24 right-4 sm:right-8 z-10 flex flex-col items-end gap-2",children:[e.jsx(Be,{className:`${RDs[a.status]} text-white border-0 uppercase tracking-widest text-[10px] px-3 py-1 rounded-full shadow-lg`,children:f7e[a.status]}),ke.length>0&&e.jsxs("button",{onClick:()=>Y(0),className:"flex items-center gap-1.5 text-xs text-white/90 bg-black/40 backdrop-blur border border-white/20 rounded-full px-3 py-1.5 hover:bg-black/60 transition",children:[e.jsx(Cx,{className:"h-3.5 w-3.5"}),ke.length," photos"]})]}),e.jsx("div",{className:"absolute inset-x-0 bottom-0 z-10 px-4 sm:px-8 pb-10 sm:pb-14",children:e.jsxs("div",{className:"max-w-7xl mx-auto",children:[e.jsxs("div",{className:"flex items-end justify-between gap-6 flex-wrap",children:[e.jsxs("div",{className:"max-w-3xl",children:[a.neighborhood&&e.jsxs("p",{className:"text-white/70 uppercase tracking-[0.25em] text-xs mb-3 font-medium",children:[a.neighborhood," · ",a.city,", ",a.state]}),a.property_address&&e.jsx("h1",{className:"font-display text-white text-4xl sm:text-6xl md:text-7xl leading-[0.95] mb-4 font-light",children:a.property_address}),!a.property_address&&e.jsxs("h1",{className:"font-display text-white text-4xl sm:text-6xl md:text-7xl leading-[0.95] mb-4 font-light",children:[a.city,", ",a.state]}),e.jsxs("div",{className:"flex items-center gap-4 flex-wrap",children:[e.jsx("p",{className:"font-display text-white text-3xl sm:text-4xl md:text-5xl font-medium",children:p7e(a.price)}),e.jsx("div",{className:"h-8 w-px bg-white/30 hidden sm:block"}),e.jsxs("div",{className:"flex items-center gap-4 text-white/80 text-sm sm:text-base",children:[a.bedrooms&&e.jsxs("span",{children:[e.jsx("span",{className:"font-semibold text-white",children:a.bedrooms})," bd"]}),a.bathrooms&&e.jsxs("span",{children:[e.jsx("span",{className:"font-semibold text-white",children:a.bathrooms})," ba"]}),a.square_footage&&e.jsxs("span",{children:[e.jsx("span",{className:"font-semibold text-white",children:TZ(a.square_footage)})," sqft"]})]})]})]}),a.agent&&e.jsxs("div",{className:"hidden md:flex items-center gap-3 bg-white/10 backdrop-blur-xl border border-white/20 rounded-2xl px-4 py-3 shadow-2xl",children:[a.agent.avatar_url?e.jsx("img",{src:a.agent.avatar_url,alt:a.agent.name,className:"h-12 w-12 rounded-full object-cover"}):e.jsx("div",{className:"h-12 w-12 rounded-full bg-white/20 flex items-center justify-center",children:e.jsx(sl,{className:"h-6 w-6 text-white"})}),e.jsxs("div",{className:"pr-2",children:[e.jsx("p",{className:"text-[11px] uppercase tracking-widest text-white/60",children:"Listing Agent"}),e.jsx("p",{className:"text-white font-medium leading-tight",children:a.agent.name}),ct&&e.jsx("p",{className:"text-xs text-white/60",children:ct})]}),e.jsx($,{size:"sm",onClick:()=>ae(!0),className:"bg-white text-neutral-900 hover:bg-white/90 rounded-full h-9 px-4",children:"Contact"})]})]}),e.jsxs("div",{className:"mt-10 flex items-center gap-2 text-white/50 text-xs uppercase tracking-widest",children:[e.jsx("span",{className:"h-px w-8 bg-white/30"}),"Scroll to explore"]})]})})]}),ys("stats")&&e.jsx("section",{className:"border-b border-white/10 bg-neutral-950",children:e.jsx("div",{className:"max-w-7xl mx-auto px-4 sm:px-8 py-8 grid grid-cols-2 md:grid-cols-5 gap-6",children:[a.bedrooms&&{icon:l2,label:"Bedrooms",value:a.bedrooms},a.bathrooms&&{icon:T0,label:"Bathrooms",value:a.bathrooms},a.square_footage&&{icon:C_,label:"Interior",value:`${TZ(a.square_footage)} sqft`},a.lot_size&&{icon:R4,label:"Lot Size",value:a.lot_size},a.year_built&&{icon:Ta,label:"Year Built",value:a.year_built},!a.year_built&&a.square_footage&&{icon:c2,label:"Price / sqft",value:`$${TZ(Math.round(a.price/a.square_footage))}`}].filter(Boolean).slice(0,5).map((Ys,cs)=>e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"h-10 w-10 rounded-full bg-white/5 border border-white/10 flex items-center justify-center shrink-0",children:e.jsx(Ys.icon,{className:"h-4 w-4 text-white/70"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-[11px] uppercase tracking-widest text-white/50",children:Ys.label}),e.jsx("p",{className:"font-display text-2xl text-white font-light",children:Ys.value})]})]},cs))})}),e.jsxs("div",{className:"max-w-7xl mx-auto px-4 sm:px-8 py-16 grid lg:grid-cols-3 gap-12",children:[e.jsxs("div",{className:"lg:col-span-2 space-y-20",children:[ys("story")&&rt&&e.jsxs("section",{id:"story",children:[e.jsx("p",{className:"text-[11px] uppercase tracking-[0.3em] text-white/40 mb-3",children:"The Story"}),e.jsx("h2",{className:"font-display text-3xl sm:text-4xl font-light mb-6 text-white",children:"A closer look at this home"}),e.jsx("div",{className:"prose prose-invert prose-lg max-w-none",children:e.jsx("p",{className:"text-white/75 leading-relaxed whitespace-pre-wrap",children:qt})}),Yt&&e.jsx("button",{onClick:()=>J(!te),className:"mt-4 text-sm text-white/60 hover:text-white underline underline-offset-4",children:te?"Show less":"Read more"}),e.jsxs("div",{className:"mt-8 flex flex-wrap gap-2",children:[e.jsxs(Be,{variant:"outline",className:"border-white/20 text-white/80 bg-white/5",children:[e.jsx(ji,{className:"h-3 w-3 mr-1.5"}),r0t[a.property_type]]}),a.has_hoa&&e.jsx(Be,{variant:"outline",className:"border-white/20 text-white/80 bg-white/5",children:"HOA"}),a.mls_link&&e.jsx($,{variant:"outline",size:"sm",asChild:!0,className:"ml-2 border-white/20 bg-white/5 text-white hover:bg-white/15",children:e.jsxs("a",{href:a.mls_link,target:"_blank",rel:"noopener noreferrer",children:[e.jsx(kr,{className:"h-3.5 w-3.5 mr-1.5"})," MLS"]})})]}),(Ft||a.agent_notes&&a.agent_notes_public)&&e.jsxs("div",{className:"mt-10 rounded-2xl border border-white/10 bg-white/5 p-6",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[e.jsx(Nn,{className:"h-4 w-4 text-amber-300"}),e.jsx("p",{className:"text-[11px] uppercase tracking-[0.25em] text-white/60",children:"A note from the agent"})]}),e.jsxs("p",{className:"text-white/80 whitespace-pre-wrap leading-relaxed italic font-display",children:['"',Ft||a.agent_notes,'"']})]})]}),ys("gallery")&&ke.length>1&&e.jsxs("section",{id:"gallery",children:[e.jsxs("div",{className:"flex items-end justify-between mb-6",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-[11px] uppercase tracking-[0.3em] text-white/40 mb-2",children:"Gallery"}),e.jsx("h2",{className:"font-display text-3xl sm:text-4xl font-light text-white",children:"Every angle, every detail"})]}),e.jsxs("button",{onClick:()=>Y(0),className:"text-sm text-white/60 hover:text-white underline underline-offset-4 hidden sm:inline",children:["View all ",ke.length]})]}),e.jsx("div",{className:"grid grid-cols-4 gap-2 sm:gap-3",children:ke.slice(0,7).map((Ys,cs)=>{const js=["col-span-4 sm:col-span-2 sm:row-span-2 aspect-square sm:aspect-auto","col-span-2 sm:col-span-2 aspect-[4/3]","col-span-2 sm:col-span-2 aspect-[4/3]","col-span-2 sm:col-span-1 aspect-square","col-span-2 sm:col-span-1 aspect-square","col-span-2 sm:col-span-1 aspect-square","col-span-2 sm:col-span-1 aspect-square"],kn=cs===6&&ke.length>7;return e.jsxs("button",{onClick:()=>Y(cs),className:`${js[cs]} relative rounded-xl overflow-hidden group bg-neutral-900`,children:[e.jsx("img",{src:Ys.photo_url,alt:`Photo ${cs+1}`,className:"absolute inset-0 h-full w-full object-cover group-hover:scale-[1.04] transition-transform duration-500"}),kn&&e.jsxs("div",{className:"absolute inset-0 bg-black/60 flex flex-col items-center justify-center text-white",children:[e.jsx(Cx,{className:"h-6 w-6 mb-1"}),e.jsxs("span",{className:"font-medium",children:["+",ke.length-7," more"]})]})]},Ys.id)})})]}),ys("video")&&((Ss=a.video)==null?void 0:Ss.playback_url)&&e.jsxs("section",{id:"video",children:[e.jsx("p",{className:"text-[11px] uppercase tracking-[0.3em] text-white/40 mb-2",children:"Video Tour"}),e.jsx("h2",{className:"font-display text-3xl sm:text-4xl font-light text-white mb-6",children:"Walk through the home"}),e.jsx("div",{className:"relative rounded-2xl overflow-hidden bg-black shadow-2xl aspect-video",children:e.jsx("iframe",{src:a.video.playback_url,className:"absolute inset-0 h-full w-full",allow:"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture",allowFullScreen:!0,title:"Video Tour"})})]}),ys("map")&&xt&&e.jsxs("section",{id:"map",children:[e.jsx("p",{className:"text-[11px] uppercase tracking-[0.3em] text-white/40 mb-2",children:"Location"}),e.jsxs("h2",{className:"font-display text-3xl sm:text-4xl font-light text-white mb-6",children:[a.neighborhood?a.neighborhood:a.city,", ",a.state]}),e.jsx("div",{className:"rounded-2xl overflow-hidden border border-white/10 shadow-2xl aspect-[16/10]",children:e.jsx("iframe",{src:xt,className:"w-full h-full grayscale-[.2] contrast-[1.05]",loading:"lazy",title:"Map"})}),e.jsxs("div",{className:"mt-4 flex items-center gap-2 text-white/60 text-sm",children:[e.jsx(ci,{className:"h-4 w-4"}),a.property_address?`${a.property_address}, `:"",a.city,", ",a.state]})]}),ys("payment")&&e.jsxs("section",{id:"payment",children:[e.jsx("p",{className:"text-[11px] uppercase tracking-[0.3em] text-white/40 mb-2",children:"Payment"}),e.jsx("h2",{className:"font-display text-3xl sm:text-4xl font-light text-white mb-6",children:"Estimate your monthly"}),e.jsxs("div",{className:"rounded-2xl border border-white/10 bg-gradient-to-br from-white/5 to-transparent p-6 sm:p-8",children:[e.jsxs("div",{className:"flex items-baseline gap-3 mb-8",children:[e.jsxs("p",{className:"font-display text-5xl sm:text-6xl font-light text-white",children:["$",TZ(Math.round(je))]}),e.jsx("p",{className:"text-white/60",children:"/ month"})]}),e.jsxs("div",{className:"grid sm:grid-cols-3 gap-8",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx(ee,{className:"text-white/70 text-xs uppercase tracking-widest",children:"Down Payment"}),e.jsxs("span",{className:"text-white font-medium",children:[ce,"%"]})]}),e.jsx(kx,{value:[ce],onValueChange:Ys=>_e(Ys[0]),min:0,max:50,step:1}),e.jsxs("p",{className:"text-xs text-white/50 mt-2",children:["$",TZ(Math.round(a.price*ce/100))," down"]})]}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx(ee,{className:"text-white/70 text-xs uppercase tracking-widest",children:"Interest Rate"}),e.jsxs("span",{className:"text-white font-medium",children:[he.toFixed(2),"%"]})]}),e.jsx(kx,{value:[he],onValueChange:Ys=>ue(Ys[0]),min:2,max:10,step:.125})]}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx(ee,{className:"text-white/70 text-xs uppercase tracking-widest",children:"Loan Term"}),e.jsxs("span",{className:"text-white font-medium",children:[ve," yr"]})]}),e.jsx(kx,{value:[ve],onValueChange:Ys=>Ee(Ys[0]),min:10,max:30,step:5})]})]}),e.jsx("p",{className:"text-xs text-white/40 mt-6",children:"Estimated principal & interest only. Taxes, insurance, and HOA not included."})]})]}),Bt.map(Ys=>{const cs=Ys.type,js=Ys.data||{};if(cs==="extra_video"&&js.url){const kn=String(js.url).includes("youtu")?`https://www.youtube.com/embed/${String(js.url).split(/[/=]/).pop()}`:js.url;return e.jsxs("section",{children:[e.jsx("p",{className:"text-[11px] uppercase tracking-[0.3em] text-white/40 mb-2",children:js.eyebrow||"Featured Video"}),e.jsx("h2",{className:"font-display text-3xl sm:text-4xl font-light text-white mb-6",children:js.title||"Watch"}),e.jsx("div",{className:"relative rounded-2xl overflow-hidden bg-black shadow-2xl aspect-video",children:e.jsx("iframe",{src:kn,className:"absolute inset-0 h-full w-full",allowFullScreen:!0,title:js.title||"Video"})})]},Ys.id)}return cs==="3d_tour"&&js.url?e.jsxs("section",{children:[e.jsx("p",{className:"text-[11px] uppercase tracking-[0.3em] text-white/40 mb-2",children:"3D Tour"}),e.jsx("h2",{className:"font-display text-3xl sm:text-4xl font-light text-white mb-6",children:js.title||"Step inside"}),e.jsx("div",{className:"relative rounded-2xl overflow-hidden bg-black shadow-2xl aspect-video",children:e.jsx("iframe",{src:js.url,className:"absolute inset-0 h-full w-full",allowFullScreen:!0,title:"3D Tour"})})]},Ys.id):cs==="floor_plan"&&js.image_url?e.jsxs("section",{children:[e.jsx("p",{className:"text-[11px] uppercase tracking-[0.3em] text-white/40 mb-2",children:"Floor Plan"}),e.jsx("h2",{className:"font-display text-3xl sm:text-4xl font-light text-white mb-6",children:js.title||"Layout"}),e.jsx("img",{src:js.image_url,alt:"Floor plan",className:"w-full rounded-2xl border border-white/10"})]},Ys.id):cs==="testimonial"&&js.quote?e.jsxs("section",{className:"rounded-2xl border border-white/10 bg-white/[0.03] p-8",children:[e.jsxs("p",{className:"font-display italic text-2xl text-white/90 leading-relaxed",children:['"',js.quote,'"']}),js.author&&e.jsxs("p",{className:"mt-4 text-sm text-white/60",children:["— ",js.author]})]},Ys.id):cs==="custom_cta"&&js.label?e.jsxs("section",{className:"rounded-2xl p-8 text-center",style:{background:rs?`${rs}22`:"rgba(255,255,255,0.05)",border:`1px solid ${rs||"rgba(255,255,255,0.1)"}`},children:[js.title&&e.jsx("h3",{className:"font-display text-3xl text-white mb-4",children:js.title}),e.jsx($,{asChild:!0,size:"lg",style:rs?{background:rs}:void 0,children:e.jsx("a",{href:js.url||"#agent",children:js.label})})]},Ys.id):null})]}),e.jsxs("aside",{id:"agent",className:"lg:sticky lg:top-24 lg:self-start space-y-6",children:[e.jsx(jDs,{listingId:a.id}),a.agent&&e.jsxs("div",{className:"rounded-2xl border border-white/10 bg-white/[0.03] p-6 backdrop-blur",children:[e.jsxs("div",{className:"flex items-start gap-4",children:[a.agent.avatar_url?e.jsx("img",{src:a.agent.avatar_url,alt:a.agent.name,className:"h-16 w-16 rounded-full object-cover border-2 border-white/20"}):e.jsx("div",{className:"h-16 w-16 rounded-full bg-white/10 flex items-center justify-center border-2 border-white/20",children:e.jsx(sl,{className:"h-7 w-7 text-white/70"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-[10px] uppercase tracking-widest text-white/50",children:"Listing Agent"}),e.jsx("p",{className:"font-display text-xl text-white font-medium leading-tight",children:a.agent.name}),ct&&e.jsx("p",{className:"text-sm text-white/60 mt-0.5",children:ct})]})]}),e.jsxs("div",{className:"mt-4 grid grid-cols-2 gap-2",children:[a.agent.phone&&e.jsx($,{asChild:!0,variant:"outline",size:"sm",className:"border-white/20 bg-white/5 text-white hover:bg-white/15",children:e.jsxs("a",{href:`tel:${a.agent.phone}`,children:[e.jsx(Da,{className:"h-3.5 w-3.5 mr-1.5"}),"Call"]})}),a.agent.email&&e.jsx($,{asChild:!0,variant:"outline",size:"sm",className:"border-white/20 bg-white/5 text-white hover:bg-white/15",children:e.jsxs("a",{href:`mailto:${a.agent.email}`,children:[e.jsx(mn,{className:"h-3.5 w-3.5 mr-1.5"}),"Email"]})})]})]}),a.co_agent_name&&e.jsxs("div",{className:"rounded-2xl border border-white/10 bg-white/[0.03] p-6 backdrop-blur",children:[e.jsxs("div",{className:"flex items-start gap-4",children:[a.co_agent_photo_url?e.jsx("img",{src:a.co_agent_photo_url,alt:a.co_agent_name,className:"h-16 w-16 rounded-full object-cover border-2 border-white/20"}):e.jsx("div",{className:"h-16 w-16 rounded-full bg-white/10 flex items-center justify-center border-2 border-white/20",children:e.jsx(sl,{className:"h-7 w-7 text-white/70"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-[10px] uppercase tracking-widest text-white/50",children:"Co-Listing Agent"}),e.jsx("p",{className:"font-display text-xl text-white font-medium leading-tight",children:a.co_agent_name}),a.co_agent_brokerage&&e.jsx("p",{className:"text-sm text-white/60 mt-0.5",children:a.co_agent_brokerage})]})]}),(a.co_agent_phone||a.co_agent_email)&&e.jsxs("div",{className:"mt-4 grid grid-cols-2 gap-2",children:[a.co_agent_phone&&e.jsx($,{asChild:!0,variant:"outline",size:"sm",className:"border-white/20 bg-white/5 text-white hover:bg-white/15",children:e.jsxs("a",{href:`tel:${a.co_agent_phone}`,children:[e.jsx(Da,{className:"h-3.5 w-3.5 mr-1.5"}),"Call"]})}),a.co_agent_email&&e.jsx($,{asChild:!0,variant:"outline",size:"sm",className:"border-white/20 bg-white/5 text-white hover:bg-white/15",children:e.jsxs("a",{href:`mailto:${a.co_agent_email}`,children:[e.jsx(mn,{className:"h-3.5 w-3.5 mr-1.5"}),"Email"]})})]})]}),e.jsx("div",{id:"contact",className:"rounded-2xl border border-white/10 bg-white text-neutral-900 p-6 shadow-2xl",children:e.jsx(a0t,{submitted:W,activeTab:R,setActiveTab:D,firstName:d,setFirstName:u,lastName:h,setLastName:m,email:f,setEmail:g,phone:x,setPhone:y,message:v,setMessage:b,preferredDate:w,setPreferredDate:S,preferredTime:C,setPreferredTime:E,showingMode:I,setShowingMode:P,isSubmitting:O,onSubmit:Ce})})]})]}),e.jsxs("div",{className:"lg:hidden fixed bottom-0 inset-x-0 z-40 bg-neutral-950/95 backdrop-blur-xl border-t border-white/10 px-4 py-3 flex items-center gap-2 safe-area-inset-bottom",children:[((Is=a.agent)==null?void 0:Is.phone)&&e.jsx($,{asChild:!0,variant:"outline",size:"sm",className:"border-white/20 bg-white/5 text-white hover:bg-white/15 flex-1",children:e.jsxs("a",{href:`tel:${a.agent.phone}`,children:[e.jsx(Da,{className:"h-4 w-4 mr-1.5"}),"Call"]})}),e.jsxs($,{onClick:()=>ae(!0),className:"bg-white text-neutral-900 hover:bg-white/90 flex-[2] font-medium",children:[e.jsx(Au,{className:"h-4 w-4 mr-1.5"}),"Request Tour"]})]}),e.jsx("footer",{className:"border-t border-white/10 py-10 mt-24 mb-16 lg:mb-0",children:e.jsxs("div",{className:"max-w-7xl mx-auto px-4 sm:px-8 flex flex-col sm:flex-row items-center justify-between gap-4 text-sm text-white/50",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("img",{src:n0t,alt:"LevelUp",className:"h-6 opacity-80"}),e.jsxs("span",{children:["© ",new Date().getFullYear()," LevelUp"]})]}),e.jsx("a",{href:"https://relevelup.com",target:"_blank",rel:"noopener noreferrer",className:"hover:text-white",children:"relevelup.com"})]})}),e.jsx(zs,{open:G!==null,onOpenChange:()=>Y(null),children:e.jsxs(Os,{className:"max-w-6xl p-0 bg-black/95 border-0",children:[e.jsx(Us,{className:"sr-only",children:e.jsx(Bs,{children:"Photo Gallery"})}),e.jsx("button",{onClick:()=>Y(null),className:"absolute right-4 top-4 z-50 rounded-full bg-white/10 hover:bg-white/20 p-2 text-white",children:e.jsx(gr,{className:"h-5 w-5"})}),G!==null&&ke[G]&&e.jsxs("div",{className:"relative",children:[e.jsx("img",{src:ke[G].photo_url,alt:`Photo ${G+1}`,className:"w-full max-h-[85vh] object-contain"}),ke.length>1&&e.jsxs(e.Fragment,{children:[e.jsx("button",{onClick:qe,className:"absolute left-4 top-1/2 -translate-y-1/2 rounded-full bg-white/10 hover:bg-white/20 p-3 text-white",children:e.jsx(Cd,{className:"h-6 w-6"})}),e.jsx("button",{onClick:ze,className:"absolute right-4 top-1/2 -translate-y-1/2 rounded-full bg-white/10 hover:bg-white/20 p-3 text-white",children:e.jsx(Di,{className:"h-6 w-6"})}),e.jsxs("div",{className:"absolute bottom-4 left-1/2 -translate-x-1/2 text-white bg-black/60 px-3 py-1 rounded-full text-sm",children:[G+1," / ",ke.length]})]})]})]})}),e.jsx(zs,{open:X,onOpenChange:ae,children:e.jsxs(Os,{className:"max-w-md p-0 bg-white text-neutral-900",children:[e.jsx(Us,{className:"sr-only",children:e.jsx(Bs,{children:"Contact the agent"})}),e.jsx("div",{className:"p-6",children:e.jsx(a0t,{submitted:W,activeTab:R,setActiveTab:D,firstName:d,setFirstName:u,lastName:h,setLastName:m,email:f,setEmail:g,phone:x,setPhone:y,message:v,setMessage:b,preferredDate:w,setPreferredDate:S,preferredTime:C,setPreferredTime:E,showingMode:I,setShowingMode:P,isSubmitting:O,onSubmit:Ce})})]})})]})]})}function a0t(s){const{submitted:t,activeTab:n,setActiveTab:r,firstName:a,setFirstName:i,lastName:l,setLastName:o,email:c,setEmail:d,phone:u,setPhone:h,message:m,setMessage:f,preferredDate:g,setPreferredDate:x,preferredTime:y,setPreferredTime:v,showingMode:b,setShowingMode:w,isSubmitting:S,onSubmit:C}=s;return t?e.jsxs("div",{className:"text-center py-6",children:[e.jsx("div",{className:"h-14 w-14 rounded-full bg-emerald-100 flex items-center justify-center mx-auto mb-3",children:e.jsx(la,{className:"h-7 w-7 text-emerald-600"})}),e.jsx("p",{className:"font-display text-2xl font-medium mb-1",children:n==="showing"?"Showing request sent!":"Thanks — you're all set!"}),e.jsx("p",{className:"text-sm text-neutral-600",children:n==="showing"?"The listing agent will reach out to confirm your showing time.":"The listing agent will contact you shortly with more details."})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"mb-4",children:[e.jsx("p",{className:"text-[10px] uppercase tracking-[0.25em] text-neutral-500 mb-1",children:"Interested?"}),e.jsx("h3",{className:"font-display text-2xl font-medium",children:"Talk to the listing agent"})]}),e.jsxs(ha,{value:n,onValueChange:E=>r(E),children:[e.jsxs(ma,{className:"grid w-full grid-cols-2 mb-4",children:[e.jsxs(Zt,{value:"info",className:"gap-1.5",children:[e.jsx(eo,{className:"h-3.5 w-3.5"})," Get Info"]}),e.jsxs(Zt,{value:"showing",className:"gap-1.5",children:[e.jsx(Au,{className:"h-3.5 w-3.5"})," Request Tour"]})]}),e.jsxs("form",{onSubmit:C,className:"space-y-3",children:[e.jsxs(Xt,{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(ee,{htmlFor:"preferredDate",children:"Preferred Date *"}),e.jsx(pe,{id:"preferredDate",type:"date",value:g,onChange:E=>x(E.target.value),min:new Date().toISOString().split("T")[0],required:n==="showing"})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"preferredTime",children:"Preferred Time"}),e.jsxs(ms,{value:y,onValueChange:v,children:[e.jsx(us,{id:"preferredTime",children:e.jsx(fs,{placeholder:"Any time"})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"morning",children:"Morning (9am–12pm)"}),e.jsx(Ge,{value:"afternoon",children:"Afternoon (12pm–5pm)"}),e.jsx(Ge,{value:"evening",children:"Evening (5pm–8pm)"})]})]})]})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"showingMode",children:"Tour Type"}),e.jsxs(ms,{value:b,onValueChange:E=>w(E),children:[e.jsx(us,{id:"showingMode",children:e.jsx(fs,{})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"in_person",children:"🏡 In-person showing"}),e.jsx(Ge,{value:"video",children:"📱 Video tour (FaceTime/Zoom)"}),e.jsx(Ge,{value:"either",children:"Either works for me"})]})]})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"firstName",children:"First Name *"}),e.jsx(pe,{id:"firstName",value:a,onChange:E=>i(E.target.value),required:!0})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"lastName",children:"Last Name"}),e.jsx(pe,{id:"lastName",value:l,onChange:E=>o(E.target.value)})]})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"email",children:"Email *"}),e.jsx(pe,{id:"email",type:"email",value:c,onChange:E=>d(E.target.value),required:!0})]}),e.jsxs("div",{children:[e.jsxs(ee,{htmlFor:"phone",children:["Phone ",n==="showing"&&"*"]}),e.jsx(pe,{id:"phone",type:"tel",value:u,onChange:E=>h(E.target.value),required:n==="showing"})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"message",children:n==="showing"?"Anything else?":"Message (optional)"}),e.jsx(Rs,{id:"message",value:m,onChange:E=>f(E.target.value),rows:2})]}),e.jsx($,{type:"submit",disabled:S,className:"w-full bg-neutral-900 hover:bg-neutral-800 text-white h-11",children:S?"Sending…":n==="showing"?"Request Showing":"Get More Info"}),e.jsx("p",{className:"text-[11px] text-neutral-500 text-center",children:"The listing agent will contact you directly. No spam."})]})]})]})}const TG="/assets/levelup-logo-white-C2RAgAoG.png",DDs="/assets/listings-hero-noir-BHCJrhvU.jpg";var G7t={exports:{}};(function(s,t){(function(n,r){s.exports=r()})(Sp,function(){let n,r,a;typeof self<"u"&&(self.__mapboxImport=o=>import(o));function i(o,c){if(!n)n=c;else if(!r)r=c;else{const d={};n(void 0,d),a=c(d);const u="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 = {}; self.__mapboxImport = (u) => import(u); ("+n+")(undefined, sharedChunk); ("+r+")(undefined, sharedChunk); self.onerror = null;";typeof window<"u"&&window&&window.URL&&window.URL.createObjectURL&&(a.workerUrl=window.URL.createObjectURL(new Blob([u],{type:"text/javascript"})))}}i(["require","exports"],function(o,c){var d="3.31.0",u=1e-6,h=typeof Float32Array<"u"?Float32Array:Array;function m(N,p){var _=p[0],A=p[1],M=p[2],F=p[3],z=_*F-M*A;return z?(N[0]=F*(z=1/z),N[1]=-A*z,N[2]=-M*z,N[3]=_*z,N):null}function f(){var N=new h(9);return h!=Float32Array&&(N[1]=0,N[2]=0,N[3]=0,N[5]=0,N[6]=0,N[7]=0),N[0]=1,N[4]=1,N[8]=1,N}function g(N,p,_){var A=p[0],M=p[1],F=p[2],z=p[3],H=p[4],Z=p[5],se=p[6],fe=p[7],xe=p[8],be=_[0],Te=_[1],De=_[2],Ue=_[3],Ye=_[4],st=_[5],ot=_[6],mt=_[7],lt=_[8];return N[0]=be*A+Te*z+De*se,N[1]=be*M+Te*H+De*fe,N[2]=be*F+Te*Z+De*xe,N[3]=Ue*A+Ye*z+st*se,N[4]=Ue*M+Ye*H+st*fe,N[5]=Ue*F+Ye*Z+st*xe,N[6]=ot*A+mt*z+lt*se,N[7]=ot*M+mt*H+lt*fe,N[8]=ot*F+mt*Z+lt*xe,N}function x(N,p){var _=Math.sin(p),A=Math.cos(p);return N[0]=A,N[1]=_,N[2]=0,N[3]=-_,N[4]=A,N[5]=0,N[6]=0,N[7]=0,N[8]=1,N}function y(){var N=new h(16);return h!=Float32Array&&(N[1]=0,N[2]=0,N[3]=0,N[4]=0,N[6]=0,N[7]=0,N[8]=0,N[9]=0,N[11]=0,N[12]=0,N[13]=0,N[14]=0),N[0]=1,N[5]=1,N[10]=1,N[15]=1,N}function v(N){var p=new h(16);return p[0]=N[0],p[1]=N[1],p[2]=N[2],p[3]=N[3],p[4]=N[4],p[5]=N[5],p[6]=N[6],p[7]=N[7],p[8]=N[8],p[9]=N[9],p[10]=N[10],p[11]=N[11],p[12]=N[12],p[13]=N[13],p[14]=N[14],p[15]=N[15],p}function b(N,p){return N[0]=p[0],N[1]=p[1],N[2]=p[2],N[3]=p[3],N[4]=p[4],N[5]=p[5],N[6]=p[6],N[7]=p[7],N[8]=p[8],N[9]=p[9],N[10]=p[10],N[11]=p[11],N[12]=p[12],N[13]=p[13],N[14]=p[14],N[15]=p[15],N}function w(N){return N[0]=1,N[1]=0,N[2]=0,N[3]=0,N[4]=0,N[5]=1,N[6]=0,N[7]=0,N[8]=0,N[9]=0,N[10]=1,N[11]=0,N[12]=0,N[13]=0,N[14]=0,N[15]=1,N}function S(N,p){if(N===p){var _=p[1],A=p[2],M=p[3],F=p[6],z=p[7],H=p[11];N[1]=p[4],N[2]=p[8],N[3]=p[12],N[4]=_,N[6]=p[9],N[7]=p[13],N[8]=A,N[9]=F,N[11]=p[14],N[12]=M,N[13]=z,N[14]=H}else N[0]=p[0],N[1]=p[4],N[2]=p[8],N[3]=p[12],N[4]=p[1],N[5]=p[5],N[6]=p[9],N[7]=p[13],N[8]=p[2],N[9]=p[6],N[10]=p[10],N[11]=p[14],N[12]=p[3],N[13]=p[7],N[14]=p[11],N[15]=p[15];return N}function C(N,p){var _=p[0],A=p[1],M=p[2],F=p[3],z=p[4],H=p[5],Z=p[6],se=p[7],fe=p[8],xe=p[9],be=p[10],Te=p[11],De=p[12],Ue=p[13],Ye=p[14],st=p[15],ot=_*H-A*z,mt=_*Z-M*z,lt=_*se-F*z,yt=A*Z-M*H,Nt=A*se-F*H,as=M*se-F*Z,Et=fe*Ue-xe*De,$t=fe*Ye-be*De,Jt=fe*st-Te*De,ns=xe*Ye-be*Ue,Ls=xe*st-Te*Ue,Gs=be*st-Te*Ye,pn=ot*Gs-mt*Ls+lt*ns+yt*Jt-Nt*$t+as*Et;return pn?(N[0]=(H*Gs-Z*Ls+se*ns)*(pn=1/pn),N[1]=(M*Ls-A*Gs-F*ns)*pn,N[2]=(Ue*as-Ye*Nt+st*yt)*pn,N[3]=(be*Nt-xe*as-Te*yt)*pn,N[4]=(Z*Jt-z*Gs-se*$t)*pn,N[5]=(_*Gs-M*Jt+F*$t)*pn,N[6]=(Ye*lt-De*as-st*mt)*pn,N[7]=(fe*as-be*lt+Te*mt)*pn,N[8]=(z*Ls-H*Jt+se*Et)*pn,N[9]=(A*Jt-_*Ls-F*Et)*pn,N[10]=(De*Nt-Ue*lt+st*ot)*pn,N[11]=(xe*lt-fe*Nt-Te*ot)*pn,N[12]=(H*$t-z*ns-Z*Et)*pn,N[13]=(_*ns-A*$t+M*Et)*pn,N[14]=(Ue*mt-De*yt-Ye*ot)*pn,N[15]=(fe*yt-xe*mt+be*ot)*pn,N):null}function E(N,p,_){var A=p[0],M=p[1],F=p[2],z=p[3],H=p[4],Z=p[5],se=p[6],fe=p[7],xe=p[8],be=p[9],Te=p[10],De=p[11],Ue=p[12],Ye=p[13],st=p[14],ot=p[15],mt=_[0],lt=_[1],yt=_[2],Nt=_[3];return N[0]=mt*A+lt*H+yt*xe+Nt*Ue,N[1]=mt*M+lt*Z+yt*be+Nt*Ye,N[2]=mt*F+lt*se+yt*Te+Nt*st,N[3]=mt*z+lt*fe+yt*De+Nt*ot,N[4]=(mt=_[4])*A+(lt=_[5])*H+(yt=_[6])*xe+(Nt=_[7])*Ue,N[5]=mt*M+lt*Z+yt*be+Nt*Ye,N[6]=mt*F+lt*se+yt*Te+Nt*st,N[7]=mt*z+lt*fe+yt*De+Nt*ot,N[8]=(mt=_[8])*A+(lt=_[9])*H+(yt=_[10])*xe+(Nt=_[11])*Ue,N[9]=mt*M+lt*Z+yt*be+Nt*Ye,N[10]=mt*F+lt*se+yt*Te+Nt*st,N[11]=mt*z+lt*fe+yt*De+Nt*ot,N[12]=(mt=_[12])*A+(lt=_[13])*H+(yt=_[14])*xe+(Nt=_[15])*Ue,N[13]=mt*M+lt*Z+yt*be+Nt*Ye,N[14]=mt*F+lt*se+yt*Te+Nt*st,N[15]=mt*z+lt*fe+yt*De+Nt*ot,N}function I(N,p,_){var A,M,F,z,H,Z,se,fe,xe,be,Te,De,Ue=_[0],Ye=_[1],st=_[2];return p===N?(N[12]=p[0]*Ue+p[4]*Ye+p[8]*st+p[12],N[13]=p[1]*Ue+p[5]*Ye+p[9]*st+p[13],N[14]=p[2]*Ue+p[6]*Ye+p[10]*st+p[14],N[15]=p[3]*Ue+p[7]*Ye+p[11]*st+p[15]):(M=p[1],F=p[2],z=p[3],H=p[4],Z=p[5],se=p[6],fe=p[7],xe=p[8],be=p[9],Te=p[10],De=p[11],N[0]=A=p[0],N[1]=M,N[2]=F,N[3]=z,N[4]=H,N[5]=Z,N[6]=se,N[7]=fe,N[8]=xe,N[9]=be,N[10]=Te,N[11]=De,N[12]=A*Ue+H*Ye+xe*st+p[12],N[13]=M*Ue+Z*Ye+be*st+p[13],N[14]=F*Ue+se*Ye+Te*st+p[14],N[15]=z*Ue+fe*Ye+De*st+p[15]),N}function P(N,p,_){var A=_[0],M=_[1],F=_[2];return N[0]=p[0]*A,N[1]=p[1]*A,N[2]=p[2]*A,N[3]=p[3]*A,N[4]=p[4]*M,N[5]=p[5]*M,N[6]=p[6]*M,N[7]=p[7]*M,N[8]=p[8]*F,N[9]=p[9]*F,N[10]=p[10]*F,N[11]=p[11]*F,N[12]=p[12],N[13]=p[13],N[14]=p[14],N[15]=p[15],N}function R(N,p,_){var A=Math.sin(_),M=Math.cos(_),F=p[4],z=p[5],H=p[6],Z=p[7],se=p[8],fe=p[9],xe=p[10],be=p[11];return p!==N&&(N[0]=p[0],N[1]=p[1],N[2]=p[2],N[3]=p[3],N[12]=p[12],N[13]=p[13],N[14]=p[14],N[15]=p[15]),N[4]=F*M+se*A,N[5]=z*M+fe*A,N[6]=H*M+xe*A,N[7]=Z*M+be*A,N[8]=se*M-F*A,N[9]=fe*M-z*A,N[10]=xe*M-H*A,N[11]=be*M-Z*A,N}function D(N,p,_){var A=Math.sin(_),M=Math.cos(_),F=p[0],z=p[1],H=p[2],Z=p[3],se=p[8],fe=p[9],xe=p[10],be=p[11];return p!==N&&(N[4]=p[4],N[5]=p[5],N[6]=p[6],N[7]=p[7],N[12]=p[12],N[13]=p[13],N[14]=p[14],N[15]=p[15]),N[0]=F*M-se*A,N[1]=z*M-fe*A,N[2]=H*M-xe*A,N[3]=Z*M-be*A,N[8]=F*A+se*M,N[9]=z*A+fe*M,N[10]=H*A+xe*M,N[11]=Z*A+be*M,N}function O(N,p,_){var A=Math.sin(_),M=Math.cos(_),F=p[0],z=p[1],H=p[2],Z=p[3],se=p[4],fe=p[5],xe=p[6],be=p[7];return p!==N&&(N[8]=p[8],N[9]=p[9],N[10]=p[10],N[11]=p[11],N[12]=p[12],N[13]=p[13],N[14]=p[14],N[15]=p[15]),N[0]=F*M+se*A,N[1]=z*M+fe*A,N[2]=H*M+xe*A,N[3]=Z*M+be*A,N[4]=se*M-F*A,N[5]=fe*M-z*A,N[6]=xe*M-H*A,N[7]=be*M-Z*A,N}function U(N,p){return N[0]=1,N[1]=0,N[2]=0,N[3]=0,N[4]=0,N[5]=1,N[6]=0,N[7]=0,N[8]=0,N[9]=0,N[10]=1,N[11]=0,N[12]=p[0],N[13]=p[1],N[14]=p[2],N[15]=1,N}function W(N,p){return N[0]=p[0],N[1]=0,N[2]=0,N[3]=0,N[4]=0,N[5]=p[1],N[6]=0,N[7]=0,N[8]=0,N[9]=0,N[10]=p[2],N[11]=0,N[12]=0,N[13]=0,N[14]=0,N[15]=1,N}function V(N,p,_){var A,M,F,z=_[0],H=_[1],Z=_[2],se=Math.sqrt(z*z+H*H+Z*Z);return se0?(Ye=2*Math.sqrt(Ue+1),N[3]=.25*Ye,N[0]=(xe-Te)/Ye,N[1]=(be-Z)/Ye,N[2]=(H-se)/Ye):z>fe&&z>De?(Ye=2*Math.sqrt(1+z-fe-De),N[3]=(xe-Te)/Ye,N[0]=.25*Ye,N[1]=(H+se)/Ye,N[2]=(be+Z)/Ye):fe>De?(Ye=2*Math.sqrt(1+fe-z-De),N[3]=(be-Z)/Ye,N[0]=(H+se)/Ye,N[1]=.25*Ye,N[2]=(xe+Te)/Ye):(Ye=2*Math.sqrt(1+De-z-fe),N[3]=(H-se)/Ye,N[0]=(be+Z)/Ye,N[1]=(xe+Te)/Ye,N[2]=.25*Ye),N}function X(N,p){var _=p[0],A=p[1],M=p[2],F=p[3],z=_+_,H=A+A,Z=M+M,se=_*z,fe=A*z,xe=A*H,be=M*z,Te=M*H,De=M*Z,Ue=F*z,Ye=F*H,st=F*Z;return N[0]=1-xe-De,N[1]=fe+st,N[2]=be-Ye,N[3]=0,N[4]=fe-st,N[5]=1-se-De,N[6]=Te+Ue,N[7]=0,N[8]=be+Ye,N[9]=Te-Ue,N[10]=1-se-xe,N[11]=0,N[12]=0,N[13]=0,N[14]=0,N[15]=1,N}var ae=function(N,p,_,A,M){var F=1/Math.tan(p/2);if(N[0]=F/_,N[1]=0,N[2]=0,N[3]=0,N[4]=0,N[5]=F,N[6]=0,N[7]=0,N[8]=0,N[9]=0,N[11]=-1,N[12]=0,N[13]=0,N[15]=0,M!=null&&M!==1/0){var z=1/(A-M);N[10]=(M+A)*z,N[14]=2*M*A*z}else N[10]=-1,N[14]=-2*A;return N},ie=function(N,p,_,A,M,F,z){var H=1/(p-_),Z=1/(A-M),se=1/(F-z);return N[0]=-2*H,N[1]=0,N[2]=0,N[3]=0,N[4]=0,N[5]=-2*Z,N[6]=0,N[7]=0,N[8]=0,N[9]=0,N[10]=2*se,N[11]=0,N[12]=(p+_)*H,N[13]=(M+A)*Z,N[14]=(z+F)*se,N[15]=1,N},ne=E;function te(){var N=new h(3);return h!=Float32Array&&(N[0]=0,N[1]=0,N[2]=0),N}function J(N){var p=new h(3);return p[0]=N[0],p[1]=N[1],p[2]=N[2],p}function ce(N){var p=N[0],_=N[1],A=N[2];return Math.sqrt(p*p+_*_+A*A)}function _e(N,p,_){var A=new h(3);return A[0]=N,A[1]=p,A[2]=_,A}function he(N,p,_,A){return N[0]=p,N[1]=_,N[2]=A,N}function ue(N,p,_){return N[0]=p[0]+_[0],N[1]=p[1]+_[1],N[2]=p[2]+_[2],N}function ve(N,p,_){return N[0]=p[0]-_[0],N[1]=p[1]-_[1],N[2]=p[2]-_[2],N}function Ee(N,p,_){return N[0]=p[0]*_[0],N[1]=p[1]*_[1],N[2]=p[2]*_[2],N}function Se(N,p,_){return N[0]=Math.min(p[0],_[0]),N[1]=Math.min(p[1],_[1]),N[2]=Math.min(p[2],_[2]),N}function Le(N,p,_){return N[0]=Math.max(p[0],_[0]),N[1]=Math.max(p[1],_[1]),N[2]=Math.max(p[2],_[2]),N}function Fe(N,p,_){return N[0]=p[0]*_,N[1]=p[1]*_,N[2]=p[2]*_,N}function ke(N,p,_,A){return N[0]=p[0]+_[0]*A,N[1]=p[1]+_[1]*A,N[2]=p[2]+_[2]*A,N}function Ve(N,p){var _=p[0]-N[0],A=p[1]-N[1],M=p[2]-N[2];return Math.sqrt(_*_+A*A+M*M)}function je(N,p){var _=p[0]-N[0],A=p[1]-N[1],M=p[2]-N[2];return _*_+A*A+M*M}function Ae(N){var p=N[0],_=N[1],A=N[2];return p*p+_*_+A*A}function Ce(N,p){return N[0]=-p[0],N[1]=-p[1],N[2]=-p[2],N}function qe(N,p){var _=p[0],A=p[1],M=p[2],F=_*_+A*A+M*M;return F>0&&(F=1/Math.sqrt(F)),N[0]=p[0]*F,N[1]=p[1]*F,N[2]=p[2]*F,N}function ze(N,p){return N[0]*p[0]+N[1]*p[1]+N[2]*p[2]}function $e(N,p,_){var A=p[0],M=p[1],F=p[2],z=_[0],H=_[1],Z=_[2];return N[0]=M*Z-F*H,N[1]=F*z-A*Z,N[2]=A*H-M*z,N}function ct(N,p,_,A){var M=p[0],F=p[1],z=p[2];return N[0]=M+A*(_[0]-M),N[1]=F+A*(_[1]-F),N[2]=z+A*(_[2]-z),N}function Xe(N,p,_){var A=p[0],M=p[1],F=p[2],z=_[3]*A+_[7]*M+_[11]*F+_[15];return N[0]=(_[0]*A+_[4]*M+_[8]*F+_[12])/(z=z||1),N[1]=(_[1]*A+_[5]*M+_[9]*F+_[13])/z,N[2]=(_[2]*A+_[6]*M+_[10]*F+_[14])/z,N}function it(N,p,_){var A=p[0],M=p[1],F=p[2];return N[0]=A*_[0]+M*_[3]+F*_[6],N[1]=A*_[1]+M*_[4]+F*_[7],N[2]=A*_[2]+M*_[5]+F*_[8],N}function at(N,p,_){var A=_[0],M=_[1],F=_[2],z=_[3],H=p[0],Z=p[1],se=p[2],fe=M*se-F*Z,xe=F*H-A*se,be=A*Z-M*H;return N[0]=H+z*(fe+=fe)+M*(be+=be)-F*(xe+=xe),N[1]=Z+z*xe+F*fe-A*be,N[2]=se+z*be+A*xe-M*fe,N}function Ke(N){return N[0]=0,N[1]=0,N[2]=0,N}function nt(N,p){return N[0]===p[0]&&N[1]===p[1]&&N[2]===p[2]}var xt=ve,rt=Ee,Yt=ce;function qt(){var N=new h(4);return h!=Float32Array&&(N[0]=0,N[1]=0,N[2]=0,N[3]=0),N}function ts(N,p,_,A){var M=new h(4);return M[0]=N,M[1]=p,M[2]=_,M[3]=A,M}function ys(N,p,_){return N[0]=p[0]*_,N[1]=p[1]*_,N[2]=p[2]*_,N[3]=p[3]*_,N}function Bt(N,p){var _=p[0],A=p[1],M=p[2],F=p[3],z=_*_+A*A+M*M+F*F;return z>0&&(z=1/Math.sqrt(z)),N[0]=_*z,N[1]=A*z,N[2]=M*z,N[3]=F*z,N}function Ft(N,p,_){var A=p[0],M=p[1],F=p[2],z=p[3];return N[0]=_[0]*A+_[4]*M+_[8]*F+_[12]*z,N[1]=_[1]*A+_[5]*M+_[9]*F+_[13]*z,N[2]=_[2]*A+_[6]*M+_[10]*F+_[14]*z,N[3]=_[3]*A+_[7]*M+_[11]*F+_[15]*z,N}function rs(){var N=new h(4);return h!=Float32Array&&(N[0]=0,N[1]=0,N[2]=0),N[3]=1,N}function St(N){return N[0]=0,N[1]=0,N[2]=0,N[3]=1,N}function Xs(N,p){var _=2*Math.acos(p[3]),A=Math.sin(_/2);return A>u?(N[0]=p[0]/A,N[1]=p[1]/A,N[2]=p[2]/A):(N[0]=1,N[1]=0,N[2]=0),_}function vt(N,p,_){_*=.5;var A=p[0],M=p[1],F=p[2],z=p[3],H=Math.sin(_),Z=Math.cos(_);return N[0]=A*Z+z*H,N[1]=M*Z+F*H,N[2]=F*Z-M*H,N[3]=z*Z-A*H,N}function gs(N,p,_){_*=.5;var A=p[0],M=p[1],F=p[2],z=p[3],H=Math.sin(_),Z=Math.cos(_);return N[0]=A*Z-F*H,N[1]=M*Z+z*H,N[2]=F*Z+A*H,N[3]=z*Z-M*H,N}function Ss(N,p,_){_*=.5;var A=p[0],M=p[1],F=p[2],z=p[3],H=Math.sin(_),Z=Math.cos(_);return N[0]=A*Z+M*H,N[1]=M*Z-A*H,N[2]=F*Z+z*H,N[3]=z*Z-F*H,N}te(),qt();var Is,Ys,cs,js=Bt,kn=(Is=te(),Ys=_e(1,0,0),cs=_e(0,1,0),function(N,p,_){var A=ze(p,_);return A<-.999999?($e(Is,Ys,p),Yt(Is)<1e-6&&$e(Is,cs,p),qe(Is,Is),function(M,F,z){z*=.5;var H=Math.sin(z);M[0]=H*F[0],M[1]=H*F[1],M[2]=H*F[2],M[3]=Math.cos(z)}(N,Is,Math.PI),N):A>.999999?(N[0]=0,N[1]=0,N[2]=0,N[3]=1,N):($e(Is,p,_),N[0]=Is[0],N[1]=Is[1],N[2]=Is[2],N[3]=1+A,js(N,N))});function Ws(){var N=new h(2);return h!=Float32Array&&(N[0]=0,N[1]=0),N}function On(N,p){var _=new h(2);return _[0]=N,_[1]=p,_}function ds(N,p,_){return N[0]=p,N[1]=_,N}function gn(N,p,_){return N[0]=p[0]+_[0],N[1]=p[1]+_[1],N}function As(N,p,_){return N[0]=p[0]-_[0],N[1]=p[1]-_[1],N}function hr(N,p,_){return N[0]=p[0]*_,N[1]=p[1]*_,N}function Er(N){var p=N[0],_=N[1];return Math.sqrt(p*p+_*_)}function qn(N,p){var _=p[0],A=p[1],M=_*_+A*A;return M>0&&(M=1/Math.sqrt(M)),N[0]=p[0]*M,N[1]=p[1]*M,N}function hn(N,p){return N[0]*p[0]+N[1]*p[1]}rs(),rs(),f();var Fn=As;function vn(N,p,_,A){const M=3*N,F=3*(_-N)-M,z=1-M-F,H=3*p,Z=3*(A-p)-H,se=1-H-Z;return function(fe,xe=1e-6){if(fe<=0)return 0;if(fe>=1)return 1;let be=fe;for(let Ue=0;Ue<8;Ue++){const Ye=((z*be+F)*be+M)*be-fe;if(Math.abs(Ye)Ye?Te=be:De=be,be=.5*(Te+De)}return((se*be+Z)*be+H)*be}}function xs(N,p){this.x=N,this.y=p}function Lr(N,p){if(Array.isArray(N)){if(!Array.isArray(p)||N.length!==p.length)return!1;for(let _=0;__;){if(A-_>600){const Z=A-_+1,se=p-_+1,fe=Math.log(Z),xe=.5*Math.exp(2*fe/3),be=.5*Math.sqrt(fe*xe*(Z-xe)/Z)*(se-Z/2<0?-1:1);Or(N,p,Math.max(_,Math.floor(p-se*xe/Z+be)),Math.min(A,Math.floor(p+(Z-se)*xe/Z+be)),M)}const F=N[p];let z=_,H=A;for(ca(N,_,p),M(N[A],F)>0&&ca(N,_,A);z0;)H--}M(N[_],F)===0?ca(N,_,H):(H++,ca(N,H,A)),H<=p&&(_=H+1),p<=H&&(A=H-1)}}function ca(N,p,_){const A=N[p];N[p]=N[_],N[_]=A}function Jn(N,p){return Np?1:0}function Sr(N){let p=0;for(let _,A,M=0,F=N.length,z=F-1;M1)for(let z=0;z=p[2]||N[1]<=p[1]||N[3]>=p[3])}function Rn(N,p,_){const A=N[0]-p[0],M=N[1]-p[1],F=N[0]-_[0],z=N[1]-_[1];return A*z-F*M===0&&A*F<=0&&M*z<=0}function xa(N,p,_){return p[1]>N[1]!=_[1]>N[1]&&N[0]<(_[0]-p[0])*(N[1]-p[1])/(_[1]-p[1])+p[0]}function Ya(N,p,_=!1){let A=!1;for(let M=0,F=p.length;M0&&H<0||z<0&&H>0}function Pc(N,p,_,A){return(M=[A[0]-_[0],A[1]-_[1]])[0]*(F=[p[0]-N[0],p[1]-N[1]])[1]-M[1]*F[0]!==0&&!(!ho(N,p,_,A)||!ho(_,A,N,p));var M,F}function $d(N){const p=new xs(Number.POSITIVE_INFINITY,Number.POSITIVE_INFINITY),_=new xs(Number.NEGATIVE_INFINITY,Number.NEGATIVE_INFINITY);for(const A of N[0])p.x>A.x&&(p.x=A.x),p.y>A.y&&(p.y=A.y),_.x=1)return 1;const p=N*N,_=p*N;return 4*(N<.5?_:3*(N-p)+_-.75)}const ao=vn(.25,.1,.25,1);function ta(N,p,_){return Math.min(_,Math.max(p,N))}function xc(N,p,_){return(_=ta((_-N)/(p-N),0,1))*_*(3-2*_)}function fl(N,p,_){const A=_-p,M=((N-p)%A+A)%A+p;return M===p?_:M}function Co(N,p,_){if(!N.length)return _(null,[]);let A=N.length;const M=new Array(N.length);let F=null;N.forEach((z,H)=>{p(z,(Z,se)=>{Z&&(F=Z),M[H]=se,--A===0&&_(F,M)})})}function pu(N,p){const _={};for(let A=0;A>p/4)).toString(16):([1e7]+-[1e3]+-4e3+-8e3+-1e11).replace(/[018]/g,N)}()}function zr(N){return N<=1?1:Math.pow(2,Math.ceil(Math.log2(N)))}function Hi(N){return!!N&&ti.test(N)}function Bc(N,p){N.forEach(_=>{p[_]&&(p[_]=p[_].bind(p))})}function $c(N,p,_){const A={};for(const M in N)A[M]=p.call(this,N[M],M,N);return A}function yc(N,p,_){const A={};for(const M in N)p.call(this,N[M],M,N)&&(A[M]=N[M]);return A}function Ul(N){return Array.isArray(N)?N.map(Ul):typeof N=="object"&&N?$c(N,Ul):N}function rg(N,p){for(let _=0;_(p.y-N.y)*(_.x-N.x)}function Ih([N,p,_]){const A=Xr(p+90),M=Xr(_);return{x:N*Math.cos(A)*Math.sin(M),y:N*Math.sin(A)*Math.sin(M),z:N*Math.cos(M),azimuthal:p,polar:_}}function cm(N,p,_){const A=Math.sqrt(N*N+p*p+_*_),M=A>0?Math.acos(_/A)*Ho:0;let F=N!==0||p!==0?Math.atan2(-p,-N)*Ho+90:0;return F<0&&(F+=360),[A,F,M]}function Xc(N){return(typeof self<"u"||N!==void 0)&&typeof WorkerGlobalScope<"u"&&(N!==void 0?N:self)instanceof WorkerGlobalScope}function _s(N){const p={};if(N.replace(/(?:^|(?:\s*\,\s*))([^\x00-\x20\(\)<>@\,;\:\\"\/\[\]\?\=\{\}\x7F]+)(?:\=(?:([^\x00-\x20\(\)<>@\,;\:\\"\/\[\]\?\=\{\}\x7F]+)|(?:\"((?:[^"\\]|\\.)*)\")))?/g,(_,A,M,F)=>{const z=M||F;return p[A]=!z||z.toLowerCase(),""}),p["max-age"]){const _=parseInt(p["max-age"],10);isNaN(_)?delete p["max-age"]:p["max-age"]=_}return p}function Xa(N){return N?{cacheControl:N.get("cache-control"),expires:N.get("expires")}:{cacheControl:void 0,expires:void 0}}function No(N){try{const p=self[N];return p.setItem("_mapbox_test_",1),p.removeItem("_mapbox_test_"),!0}catch{return!1}}function Ba(N,p){return[N[4*p],N[4*p+1],N[4*p+2],N[4*p+3]]}function io(N,p,_){N[4*p+0]=_[0],N[4*p+1]=_[1],N[4*p+2]=_[2],N[4*p+3]=_[3]}function ko(N){return[Math.pow(N[0],1/2.2),Math.pow(N[1],1/2.2),Math.pow(N[2],1/2.2)]}function qi(N){return N>0?1/(1.001-N):1+N}function dm(N){return N>0?1-1/(1.001-N):-N}function Zo(N,p,_){return(N-p.min)*(_.max-_.min)/(p.max-p.min)+_.min}function vo(N){return N*N*N*N*N}function Zg(N){return N>>>=0,N=Math.imul(2747636419^N,2654435769)>>>0,N=Math.imul(N^N>>>16,2654435769)>>>0,(N=Math.imul(N^N>>>16,2654435769)>>>0)/4294967296}let Ol,zl,vy,Xd,Wh,df;function Yy(){return Ol??(Ol=self.OffscreenCanvas&&!!new OffscreenCanvas(1,1).getContext("2d")&&typeof self.createImageBitmap=="function"),Ol}const oh={requestIdleCallback:N=>{if(typeof requestIdleCallback<"u")return requestIdleCallback(N);setTimeout(()=>N({didTimeout:!1,timeRemaining:()=>50}),0)},now:()=>Xd!==void 0?Xd:performance.now(),setNow(N){Xd=N},restoreNow(){Xd=void 0},frame(N){const p=requestAnimationFrame(N);return{cancel:()=>cancelAnimationFrame(p)}},getImageData(N,p=0){const{width:_,height:A}=N;Wh||(Wh=document.createElement("canvas"));const M=Wh.getContext("2d",{willReadFrequently:!0});if(!M)throw new Error("failed to create canvas 2d context");return(_>Wh.width||A>Wh.height)&&(Wh.width=_,Wh.height=A),M.clearRect(-p,-p,_+2*p,A+2*p),M.drawImage(N,0,0,_,A),M.getImageData(-p,-p,_+2*p,A+2*p)},resolveURL:N=>(zl||(zl=document.createElement("a")),zl.href=N,zl.href),get devicePixelRatio(){return window.devicePixelRatio},get prefersReducedMotion(){return!!window.matchMedia&&(vy??(vy=window.matchMedia("(prefers-reduced-motion: reduce)")),vy.matches)},hasCanvasFingerprintNoise(){if(df!==void 0)return df;if(!Yy())return df=!1,!1;const N=new OffscreenCanvas(85,1),p=N.getContext("2d",{willReadFrequently:!0});let _=0;for(let M=0;M0?`?${F}`:""}`}const Wt="mapbox-tiles";let ws=500,Ms=50;const Ns=["language","worldview","jobid"];let Ps;function fn(){try{return caches}catch{}}function xn(){const N=fn();N&&Ps==null&&(Ps=N.open(Wt))}let bn=1/0;function Pn(N){return gt.API_URL_REGEX.test(N)}function or(N){return N.indexOf("mapbox:")===0}function tr(N){return gt.API_CDN_URL_REGEX.test(N)}function sr(N){return gt.API_SPRITE_REGEX.test(N)}function br(N){return gt.API_STYLE_REGEX.test(N)&&!sr(N)}const vr={Unknown:"Unknown",Style:"Style",Source:"Source",Tile:"Tile",Glyphs:"Glyphs",SpriteImage:"SpriteImage",SpriteJSON:"SpriteJSON",Iconset:"Iconset",Image:"Image",Model:"Model"};Object.freeze(vr);class Va extends Error{constructor(p,_,A){super(),this.url=A,this.statusText=p,this.status=_}get message(){return this.status===401&&Pn(this.url)?`${this.statusText}: you may have provided an invalid Mapbox access token. See https://docs.mapbox.com/api/guides/#access-tokens-and-token-scopes`:this.statusText}toString(){return`${this.name}: ${this.message} (${this.status}): ${this.url}`}}function Je(N){return typeof N=="object"&&N!==null&&"status"in N&&N.status===404}const Ht=Xc()?()=>self.worker.referrer:()=>(location.protocol==="blob:"?parent:self).location.href,Ts=/^\w+:/,ln=/[\r\n]+/;async function tn(N,p){let _;return _=N.type==="arrayBuffer"?await p.arrayBuffer():N.type==="json"?await p.json():await p.text(),{data:_,headers:p.headers}}async function nr(N,p){return p&&p.throwIfAborted(),(_=N.url).startsWith("file:")||Ht().startsWith("file:")&&!Ts.test(_)?async function(A,M){return new Promise((F,z)=>{const H=new XMLHttpRequest,Z=()=>{M.removeEventListener("abort",Z),H.abort(),z(M.reason)};M&&M.addEventListener("abort",Z),H.open(A.method||"GET",A.url,!0),A.type==="arrayBuffer"&&(H.responseType="arraybuffer");for(const se in A.headers)H.setRequestHeader(se,A.headers[se]);A.type==="json"&&(H.responseType="text",H.setRequestHeader("Accept","application/json")),H.withCredentials=A.credentials==="include",H.onerror=()=>{M&&M.removeEventListener("abort",Z),z(new Error(H.statusText))},H.onload=()=>{if(M&&M.removeEventListener("abort",Z),(H.status>=200&&H.status<300||H.status===0)&&H.response!==null){let se=H.response;if(A.type==="json")try{se=JSON.parse(H.response)}catch(xe){return void z(xe)}const fe=new Headers;H.getAllResponseHeaders().trim().split(ln).forEach(xe=>{const be=xe.split(": "),Te=be.shift(),De=be.join(": ");Te&&fe.set(Te,De)}),F({data:se,headers:fe})}else z(new Va(H.statusText,H.status,A.url))},H.send(A.body)})}(N,p):async function(A,M){const F=new Request(A.url,{method:A.method||"GET",body:A.body,credentials:A.credentials,headers:A.headers,referrer:Ht(),referrerPolicy:A.referrerPolicy,signal:M}),z=(H=F.url).indexOf("sku=")>0&&Pn(H);var H;if(A.type==="json"&&F.headers.set("Accept","application/json"),z){let be=null;try{be=await async function(Te){if(xn(),Ps==null)return null;const De=await Ps;let Ue=zt(Te.url,{persistentParams:Ns});const Ye=Te.headers.get("Range");Ye&&(Ue=Rt(Ue,{range:Ye}));const st=await De.match(Ue);if(!st)return null;const ot=function(mt){if(!mt)return!1;const lt=new Date(mt.headers.get("expires")||0),yt=_s(mt.headers.get("cache-control")||"");return Number(lt)>Date.now()&&!yt["no-cache"]}(st);return De.delete(Ue).catch(mt=>Yo(mt.message)),ot&&De.put(Ue,st.clone()).catch(mt=>Yo(mt.message)),{response:st,fresh:ot}}(F)}catch(Te){Te.message!=="SecurityError"&&Yo(Te.toString())}if(be&&be.fresh)return M&&M.throwIfAborted(),tn(A,be.response)}const Z=Date.now();let se;try{se=await fetch(F)}catch(be){throw be.name==="AbortError"?be:new Error(`${be.message} ${A.url}`,{cause:be})}if(M&&M.throwIfAborted(),!se.ok)throw new Va(se.statusText,se.status,A.url);const fe=z?se.clone():null,xe=await tn(A,se);return fe&&async function(be,Te,De){if(xn(),Ps==null)return;const Ue=_s(Te.headers.get("cache-control")||"");if(Ue["no-store"])return;const Ye={status:Te.status,statusText:Te.statusText,headers:new Headers(Te.headers)};Ue["max-age"]&&Ye.headers.set("Expires",new Date(De+1e3*Ue["max-age"]).toUTCString());const st=Ye.headers.get("expires");if(!st||new Date(st).getTime()-De<42e4)return;let ot=zt(be.url,{persistentParams:Ns});if(Te.status===206){const yt=be.headers.get("Range");if(!yt)return;Ye.status=200,ot=Rt(ot,{range:yt})}const mt=new Response((lt=Te.status)!==200&<!==404&&[101,103,204,205,304].includes(lt)?null:Te.body,Ye);var lt;if(xn(),Ps!=null)try{await(await Ps).put(ot,mt)}catch(yt){Yo(yt.message)}}(F,fe,Z),xe}(N,p);var _}async function rr(N,p){return nr(Object.assign(N,{type:"json"}),p)}async function Qr(N,p){return nr(Object.assign(N,{type:"arrayBuffer"}),p)}function na(N){const p=document.createElement("a");return p.href=N,p.protocol===location.protocol&&p.host===location.host}let $a,Na;$a=[],Na=0;const La="01",to={create:"create",load:"load",fullLoad:"fullLoad"},xo={mark(N){performance.mark(N)},measure(N,p,_){performance.measure(N,p,_)}};function oo(N){const p=N.name.split("?")[0];return tr(p)&&p.includes("mapbox-gl.js")?"javascript":tr(p)&&p.includes("mapbox-gl.css")?"css":function(_){return gt.API_FONTS_REGEX.test(_)}(p)?"fontRange":sr(p)?"sprite":br(p)?"style":function(_){return gt.API_TILEJSON_REGEX.test(_)}(p)?"tilejson":"other"}const Lo=/(\.(png|jpg)\d*)(?=$)/,ql=/^.+\/v4\//,po=/\.[\w]+$/,nl=/^(\/v4\/|\/(raster|rasterarrays)\/v1\/)/,Il=/^access_token=(.*)$/,Ed="NO_ACCESS_TOKEN",iu=/^(\w+):\/\/([^/?]*)(\/[^?]+)?\??(.+)?/;function Ut(N){const p=N.match(iu);if(!p)throw new Error("Unable to parse URL object");return{protocol:p[1],authority:p[2],path:p[3]||"/",params:p[4]?p[4].split("&"):[]}}function Cn(N){const p=N.params.length?`?${N.params.join("&")}`:"";return`${N.protocol}://${N.authority}${N.path}${p}`}const ar="mapbox.eventData";function ra(N){if(!N)return null;const p=N.split(".");if(!p||p.length!==3)return null;try{return JSON.parse(decodeURIComponent(atob(p[1]).split("").map(_=>"%"+("00"+_.charCodeAt(0).toString(16)).slice(-2)).join("")))}catch{return null}}function Zr(N){return!(!gt.EVENTS_URL||!N&&!gt.ACCESS_TOKEN)}let Aa;const xi=/^[\w.+-]+(\/[\w.+-]+)?$/;let Ia="other";class el{constructor(p){this.type=p,this.anonId=null,this.anonIdTimestamp=null,this.eventData={},this.queue=[],this.pendingRequest=!1}getStorageKey(p){const _=ra(gt.ACCESS_TOKEN);let A="";return A=_&&_.u?btoa(encodeURIComponent(_.u).replace(/%([0-9A-F]{2})/g,(M,F)=>String.fromCharCode(+("0x"+F)))):gt.ACCESS_TOKEN||"",p?`${ar}.${p}:${A}`:`${ar}:${A}`}fetchEventData(){const p=No("localStorage"),_=this.getStorageKey(),A=this.getStorageKey("uuid"),M=this.getStorageKey("uuidTimestamp");if(p)try{const F=localStorage.getItem(_);F&&(this.eventData=JSON.parse(F));const z=localStorage.getItem(A);z&&(this.anonId=z);const H=localStorage.getItem(M);H&&(this.anonIdTimestamp=Number(H));const Z=Date.now()-864e5;(!this.anonIdTimestamp||this.anonIdTimestamp=1&&localStorage.setItem(_,JSON.stringify(this.eventData)),z&&localStorage.setItem(M,z.toString())}catch{Yo("Unable to write to LocalStorage")}}processRequests(){}postEvent(p,_,A,M){if(!gt.EVENTS_URL)return;const F=Ut(gt.EVENTS_URL);F.params.push(`access_token=${M||gt.ACCESS_TOKEN||""}`);const z={event:this.type,created:new Date(p).toISOString()},H=_?Object.assign(z,_):z,Z={url:Cn(F),headers:{"Content-Type":"text/plain"},body:JSON.stringify([H])};this.pendingRequest=!0,async function(se){return nr(Object.assign(se,{method:"POST"}),void 0)}(Z).then(()=>{this.pendingRequest=!1,A(null),this.saveEventData(),this.processRequests()}).catch(se=>{this.pendingRequest=!1,A(se),this.saveEventData(),this.processRequests()})}queueRequest(p,_){this.queue.push({...p,customAccessToken:_}),this.processRequests()}}class zo extends el{constructor(p){super("metrics"),p&&(this.data=p)}postMetricsEvent(p){if(!Zr(p))return;this.anonId||this.fetchEventData(),Hi(this.anonId)||this.refreshUUID();const _={...this.data,sessionId:this.anonId};this.queueRequest({timestamp:Date.now(),payload:_},p)}processRequests(){if(this.pendingRequest||this.queue.length===0)return;const{timestamp:p,payload:_,customAccessToken:A}=this.queue.shift();this.postEvent(p,_,()=>{},A)}}const Lc=new class extends el{constructor(N){super("appUserTurnstile"),this._customAccessToken=N}postTurnstileEvent(N,p){Zr(p)&&Array.isArray(N)&&N.some(_=>or(_)||Pn(_))&&this.queueRequest({timestamp:Date.now()},p)}processRequests(){if(this.pendingRequest||this.queue.length===0)return;this.anonId&&this.anonIdTimestamp&&this.eventData.lastSuccess&&this.eventData.tokenU||this.fetchEventData();const N=ra(gt.ACCESS_TOKEN),p=N?N.u:gt.ACCESS_TOKEN;let _=p!==this.eventData.tokenU;Hi(this.anonId)||(this.refreshUUID(),_=!0);const{timestamp:A,customAccessToken:M}=this.queue.shift();if(this.eventData.lastSuccess){const z=new Date(this.eventData.lastSuccess),H=new Date(A),Z=(A-this.eventData.lastSuccess)/864e5;_=_||Z>=1||Z<-1||z.getDate()!==H.getDate()}else _=!0;if(!_)return void this.processRequests();const F={version:"2.2",sdkIdentifier:"mapbox-gl-js",sdkVersion:d,skuId:La,"enabled.telemetry":!1,userId:this.anonId,bundleFormat:"umd",bundleDistribution:Ia};Aa&&(F.sdkInfo=Aa),this.postEvent(A,F,z=>{z||(this.eventData.lastSuccess=A,this.eventData.tokenU=p)},M)}},Mu=Lc.postTurnstileEvent.bind(Lc),ou=new class extends el{constructor(){super("map.load"),this.success={},this.skuToken=""}postMapLoadEvent(N,p,_,A){this.skuToken=p,this.errorCb=A,gt.EVENTS_URL&&(_||gt.ACCESS_TOKEN?this.queueRequest({id:N,timestamp:Date.now()},_):this.errorCb(new Error(Ed)))}processRequests(){if(this.pendingRequest||this.queue.length===0)return;const{id:N,timestamp:p,customAccessToken:_}=this.queue.shift();if(N&&this.success[N])return;this.anonId&&this.anonIdTimestamp||this.fetchEventData(),Hi(this.anonId)||this.refreshUUID();const A={version:"2.2",sdkIdentifier:"mapbox-gl-js",sdkVersion:d,skuId:La,skuToken:this.skuToken,userId:this.anonId,bundleFormat:"umd",bundleDistribution:Ia};Aa&&(A.sdkInfo=Aa),this.postEvent(p,A,M=>{M?this.errorCb(M):N&&(this.success[N]=!0)},_)}remove(){this.errorCb=null}},um=ou.postMapLoadEvent.bind(ou),Td=new class extends el{constructor(){super("style.load"),this.eventIdPerMapInstanceMap=new Map,this.mapInstanceIdMap=new WeakMap}getMapInstanceId(N){let p=this.mapInstanceIdMap.get(N);return p||(p=ad(),this.mapInstanceIdMap.set(N,p)),p}getEventId(N){const p=this.eventIdPerMapInstanceMap.get(N)||0;return this.eventIdPerMapInstanceMap.set(N,p+1),p}postStyleLoadEvent(N,p){const{map:_,style:A,importedStyles:M}=p;if(!Zr(N))return;const F=this.getMapInstanceId(_),z={mapInstanceId:F,eventId:this.getEventId(F),style:A};M.length&&(z.importedStyles=M),this.queueRequest({timestamp:Date.now(),payload:z},N)}processRequests(){if(this.pendingRequest||this.queue.length===0)return;const{timestamp:N,payload:p,customAccessToken:_}=this.queue.shift();this.postEvent(N,p,()=>{},_)}},gu=Td.postStyleLoadEvent.bind(Td),Qc=new zo({attributes:[{name:"maps/js/layer-animations/style-with-appearances"}]}),id=Qc.postMetricsEvent.bind(Qc),lh=new zo({attributes:[{name:"maps/js/layer-animations/runtime-appearances"}]}),If=lh.postMetricsEvent.bind(lh),Ud=new class extends el{constructor(){super("gljs.performance")}postPerformanceEvent(N,p){Zr(N)&&this.queueRequest({timestamp:Date.now(),performanceData:p},N)}processRequests(){if(this.pendingRequest||this.queue.length===0)return;const{timestamp:N,performanceData:p,customAccessToken:_}=this.queue.shift(),A=function(M){const F=performance.getEntriesByType("resource"),z=performance.getEntriesByType("mark"),H=function(Te){const De={};if(Te){for(const Ue in Te)if(Ue!=="other")for(const Ye of Te[Ue]){const st=`${Ue}ResolveRangeMin`,ot=`${Ue}ResolveRangeMax`,mt=`${Ue}RequestCount`,lt=`${Ue}RequestCachedCount`;De[st]=Math.min(De[st]||1/0,Ye.startTime),De[ot]=Math.max(De[ot]||-1/0,Ye.responseEnd);const yt=Nt=>{De[Nt]===void 0&&(De[Nt]=0),++De[Nt]};Ye.transferSize!==void 0&&Ye.transferSize===0&&yt(lt),yt(mt)}}return De}(function(Te,De){const Ue={};if(Te)for(const Ye of Te){const st=De(Ye);Ue[st]===void 0&&(Ue[st]=[]),Ue[st].push(Ye)}return Ue}(F,oo)),Z=window.devicePixelRatio,se=navigator.connection||navigator.mozConnection||navigator.webkitConnection,fe=se?se.effectiveType:void 0,xe={counters:[],metadata:[],attributes:[]},be=(Te,De,Ue)=>{Ue!=null&&Te.push({name:De,value:Ue.toString()})};for(const Te in H)be(xe.counters,Te,H[Te]);if(M.interactionRange[0]!==1/0&&M.interactionRange[1]!==-1/0&&(be(xe.counters,"interactionRangeMin",M.interactionRange[0]),be(xe.counters,"interactionRangeMax",M.interactionRange[1])),z)for(const Te of Object.values(to)){const De=z.find(Ue=>Ue.name===Te);De&&be(xe.counters,Te,De.startTime)}return be(xe.counters,"visibilityHidden",M.visibilityHidden),be(xe.attributes,"style",function(Te){if(Te)for(const De of Te){const Ue=De.name.split("?")[0];if(br(Ue)){const Ye=Ue.split("/").slice(-2);if(Ye.length===2)return`mapbox://styles/${Ye[0]}/${Ye[1]}`}}}(F)),be(xe.attributes,"terrainEnabled",M.terrainEnabled?"true":"false"),be(xe.attributes,"fogEnabled",M.fogEnabled?"true":"false"),be(xe.attributes,"projection",M.projection),be(xe.attributes,"zoom",M.zoom),be(xe.metadata,"devicePixelRatio",Z),be(xe.metadata,"connectionEffectiveType",fe),be(xe.metadata,"navigatorUserAgent",navigator.userAgent),be(xe.metadata,"screenWidth",window.screen.width),be(xe.metadata,"screenHeight",window.screen.height),be(xe.metadata,"windowWidth",window.innerWidth),be(xe.metadata,"windowHeight",window.innerHeight),be(xe.metadata,"mapWidth",M.width/Z),be(xe.metadata,"mapHeight",M.height/Z),be(xe.metadata,"webglRenderer",M.renderer),be(xe.metadata,"webglVendor",M.vendor),be(xe.metadata,"sdkVersion",d),be(xe.metadata,"sdkIdentifier","mapbox-gl-js"),xe}(p);for(const M of A.metadata);for(const M of A.counters);for(const M of A.attributes);this.postEvent(N,A,()=>{},_)}},od=Ud.postPerformanceEvent.bind(Ud),Lh=new class extends el{constructor(){super("map.auth"),this.success={},this.skuToken=""}getSession(N,p,_,A){if(!gt.API_URL||!gt.SESSION_PATH)return;const M=Ut(gt.API_URL+gt.SESSION_PATH);M.params.push(`sku=${p||""}`),M.params.push(`access_token=${A||gt.ACCESS_TOKEN||""}`);const F={url:Cn(M),headers:{"Content-Type":"text/plain"}};this.pendingRequest=!0,async function(z){return nr(Object.assign(z,{method:"GET"}),void 0)}(F).then(()=>{this.pendingRequest=!1,_(null),this.saveEventData(),this.processRequests()}).catch(z=>{this.pendingRequest=!1,_(z),this.saveEventData(),this.processRequests()})}getSessionAPI(N,p,_,A){this.skuToken=p,this.errorCb=A,gt.EVENTS_URL&>.SESSION_PATH&>.API_URL&&(_||gt.ACCESS_TOKEN?this.queueRequest({id:N,timestamp:Date.now()},_):this.errorCb(new Error(Ed)))}processRequests(){if(this.pendingRequest||this.queue.length===0)return;const{id:N,timestamp:p,customAccessToken:_}=this.queue.shift();N&&this.success[N]||this.getSession(p,this.skuToken,A=>{A?this.errorCb(A):N&&(this.success[N]=!0)},_)}remove(){this.errorCb=null}},Gu=Lh.getSessionAPI.bind(Lh),qd=new Set;function hd(N,p=0){const M=N.length,F=M-(3&M);let z,H=0|p,Z=0;for(;Z>>17,z=Math.imul(z,461845907),H^=z,H=H<<13|H>>>19,H=Math.imul(H,5)+3864292196|0;z=0;const se=3&M;return se>0&&(se>=3&&(z^=(255&N.charCodeAt(Z+2))<<16),se>=2&&(z^=(255&N.charCodeAt(Z+1))<<8),z^=255&N.charCodeAt(Z),z=Math.imul(z,3432918353),z=z<<15|z>>>17,z=Math.imul(z,461845907),H^=z),H^=M,H^=H>>>16,H=Math.imul(H,2246822507),H^=H>>>13,H=Math.imul(H,3266489909),H^=H>>>16,H>>>0}class Bl{constructor(p,..._){Object.assign(this,_[0]||{}),this.type=p}}class Xi extends Bl{constructor(p,_={}){super("error",{error:p,..._}),this.error=p}}function Md(N,p,_){_[N]&&_[N].includes(p)||(_[N]=_[N]||[],_[N].push(p))}function lu(N,p,_){if(_[N]){const A=_[N].indexOf(p);A!==-1&&_[N].splice(A,1)}}class Jc{constructor(){this._listeners={},this._oneTimeListeners={}}on(p,_){return Md(p,_,this._listeners),this}off(p,_){return lu(p,_,this._listeners),lu(p,_,this._oneTimeListeners),this}once(p,_){return _?(Md(p,_,this._oneTimeListeners),this):new Promise(A=>{this.once(p,A)})}fire(p,_){const A=typeof p=="string"?new Bl(p,_):p,M=A.type;if(this.listens(M)){A.target=this;const F=this._listeners[M]?this._listeners[M].slice():[];for(const Z of F)Z.call(this,A);const z=this._oneTimeListeners[M]?this._oneTimeListeners[M].slice():[];for(const Z of z)lu(M,Z,this._oneTimeListeners),Z.call(this,A);const H=this._eventedParent;if(H){const Z=typeof this._eventedParentData=="function"?this._eventedParentData():this._eventedParentData;Object.assign(A,Z),H.fire(A)}}else A instanceof Xi&&console.error(A.error);return this}listens(p){return!!(this._listeners[p]&&this._listeners[p].length>0||this._oneTimeListeners[p]&&this._oneTimeListeners[p].length>0||this._eventedParent&&this._eventedParent.listens(p))}setEventedParent(p,_){return this._eventedParent=p,this._eventedParentData=_,this}}class _d{constructor(p){typeof p=="string"?this.name=p:(this.name=p.name,this.iconsetId=p.iconsetId)}static from(p){return new _d(p)}static toString(p){return p.iconsetId?`${p.name}${p.iconsetId}`:p.name}static parse(p){const[_,A]=p.split("");return new _d({name:_,iconsetId:A})}static isEqual(p,_){return p.name===_.name&&p.iconsetId===_.iconsetId}toString(){return _d.toString(this)}serialize(){return{name:this.name,iconsetId:this.iconsetId}}}var Ep,zv={},Rx=function(){if(Ep)return zv;Ep=1;var N={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 p(F){return(F=Math.round(F))<0?0:F>255?255:F}function _(F){return p(F[F.length-1]==="%"?parseFloat(F)/100*255:parseInt(F))}function A(F){return(z=F[F.length-1]==="%"?parseFloat(F)/100:parseFloat(F))<0?0:z>1?1:z;var z}function M(F,z,H){return H<0?H+=1:H>1&&(H-=1),6*H<1?F+(z-F)*H*6:2*H<1?z:3*H<2?F+(z-F)*(2/3-H)*6:F}try{zv.parseCSSColor=function(F){var z,H=F.replace(/ /g,"").toLowerCase();if(H in N)return N[H].slice();if(H[0]==="#")return H.length===4?(z=parseInt(H.substr(1),16))>=0&&z<=4095?[(3840&z)>>4|(3840&z)>>8,240&z|(240&z)>>4,15&z|(15&z)<<4,1]:null:H.length===7&&(z=parseInt(H.substr(1),16))>=0&&z<=16777215?[(16711680&z)>>16,(65280&z)>>8,255&z,1]:null;var Z=H.indexOf("("),se=H.indexOf(")");if(Z!==-1&&se+1===H.length){var fe=H.substr(0,Z),xe=H.substr(Z+1,se-(Z+1)).split(","),be=1;switch(fe){case"rgba":if(xe.length!==4)return null;be=A(xe.pop());case"rgb":return xe.length!==3?null:[_(xe[0]),_(xe[1]),_(xe[2]),be];case"hsla":if(xe.length!==4)return null;be=A(xe.pop());case"hsl":if(xe.length!==3)return null;var Te=(parseFloat(xe[0])%360+360)%360/360,De=A(xe[1]),Ue=A(xe[2]),Ye=Ue<=.5?Ue*(De+1):Ue+De-Ue*De,st=2*Ue-Ye;return[p(255*M(st,Ye,Te+1/3)),p(255*M(st,Ye,Te)),p(255*M(st,Ye,Te-1/3)),be];default:return null}}return null}}catch{}return zv}();function ya(N,p,_){return N*(1-_)+p*_}const Zy=new Map;class Ci{constructor(p,_,A,M=1){this.r=p,this.g=_,this.b=A,this.a=M}static parse(p){if(!p)return;if(p instanceof Ci)return p;if(typeof p!="string")return;const _=Zy.get(p);if(_)return _;const A=Rx.parseCSSColor(p);if(!A)return;const M=new Ci(A[0]/255,A[1]/255,A[2]/255,A[3]);return Zy.set(p,M),M}toString(){const{r:p,g:_,b:A,a:M}=this;return`rgba(${Math.round(255*p)},${Math.round(255*_)},${Math.round(255*A)},${M})`}toNonPremultipliedRenderColor(p){const{r:_,g:A,b:M,a:F}=this;return new zm(p,_,A,M,F)}toPremultipliedRenderColor(p){const{r:_,g:A,b:M,a:F}=this;return new Dx(p,_*F,A*F,M*F,F)}clone(){return new Ci(this.r,this.g,this.b,this.a)}}class Xg{constructor(p,_,A,M,F,z=!1){if(this.premultiplied=!1,this.premultiplied=z,p){const H=p.image.height,Z=H*H;this.premultiplied?(_=F===0?0:_/F*(H-1),A=F===0?0:A/F*(H-1),M=F===0?0:M/F*(H-1)):(_*=H-1,A*=H-1,M*=H-1),_=Math.max(0,Math.min(H-1,_)),A=Math.max(0,Math.min(H-1,A)),M=Math.max(0,Math.min(H-1,M));const se=Math.floor(_),fe=Math.floor(A),xe=Math.floor(M),be=Math.ceil(_),Te=Math.ceil(A),De=Math.ceil(M),Ue=_-se,Ye=A-fe,st=M-xe,ot=p.image.data,mt=4*(se+fe*Z+xe*H),lt=4*(se+fe*Z+De*H),yt=4*(se+Te*Z+xe*H),Nt=4*(se+Te*Z+De*H),as=4*(be+fe*Z+xe*H),Et=4*(be+fe*Z+De*H),$t=4*(be+Te*Z+xe*H),Jt=4*(be+Te*Z+De*H);this.r=ya(ya(ya(ot[mt],ot[lt],st),ya(ot[yt],ot[Nt],st),Ye),ya(ya(ot[as],ot[Et],st),ya(ot[$t],ot[Jt],st),Ye),Ue)/255*(this.premultiplied?F:1),this.g=ya(ya(ya(ot[mt+1],ot[lt+1],st),ya(ot[yt+1],ot[Nt+1],st),Ye),ya(ya(ot[as+1],ot[Et+1],st),ya(ot[$t+1],ot[Jt+1],st),Ye),Ue)/255*(this.premultiplied?F:1),this.b=ya(ya(ya(ot[mt+2],ot[lt+2],st),ya(ot[yt+2],ot[Nt+2],st),Ye),ya(ya(ot[as+2],ot[Et+2],st),ya(ot[$t+2],ot[Jt+2],st),Ye),Ue)/255*(this.premultiplied?F:1),this.a=F}else this.r=_,this.g=A,this.b=M,this.a=F}toArray(){const{r:p,g:_,b:A,a:M}=this;return[255*p,255*_,255*A,M]}toHslaArray(){let{r:p,g:_,b:A,a:M}=this;if(this.premultiplied){if(M===0)return[0,0,0,0];const De=1/M;p*=De,_*=De,A*=De}const F=Math.min(Math.max(p,0),1),z=Math.min(Math.max(_,0),1),H=Math.min(Math.max(A,0),1),Z=Math.min(F,z,H),se=Math.max(F,z,H),fe=se-Z,xe=.5*(Z+se);if(fe===0)return[0,0,100*xe,M];const be=xe>.5?fe/(2-se-Z):fe/(se+Z);let Te;switch(se){case F:Te=60*((z-H)/fe+(zya(A,p[M],_))}Ci.black=new Ci(0,0,0,1),Ci.white=new Ci(1,1,1,1),Ci.transparent=new Ci(0,0,0,0),Ci.red=new Ci(1,0,0,1),Ci.blue=new Ci(0,0,1,1);var Sc=Object.freeze({__proto__:null,array:Wu,color:function(N,p,_){return new Ci(ya(N.r,p.r,_),ya(N.g,p.g,_),ya(N.b,p.b,_),ya(N.a,p.a,_))},number:ya});class Ro extends Error{constructor(p,_){super(_),this.message=_,this.key=p}}class kl{constructor(p,_=[]){this.parent=p,this.bindings=Object.create(null);for(const[A,M]of _)this.bindings[A]=M}concat(p){return new kl(this,p)}get(p){if(this.bindings[p])return this.bindings[p];if(this.parent)return this.parent.get(p);throw new Error(`${p} not found in scope.`)}has(p){return!!this.bindings[p]||!!this.parent&&this.parent.has(p)}}const xu={kind:"null"},fa={kind:"number"},Ao={kind:"string"},pl={kind:"boolean"},ed={kind:"color"},ag={kind:"object"},Wo={kind:"value"},q0={kind:"collator"},yh={kind:"formatted"},uf={kind:"resolvedImage"};function Vd(N,p){return{kind:"array",itemType:N,N:p}}function yu(N){if(N.kind==="array"){const p=yu(N.itemType);return typeof N.N=="number"?`array<${p}, ${N.N}>`:N.itemType.kind==="value"?"array":`array<${p}>`}return N.kind}const B_=[xu,fa,Ao,pl,ed,yh,ag,Vd(Wo),uf];function Bv(N,p){if(p.kind==="error")return null;if(N.kind==="array"){if(p.kind==="array"&&(p.N===0&&p.itemType.kind==="value"||!Bv(N.itemType,p.itemType))&&(typeof N.N!="number"||N.N===p.N))return null}else{if(N.kind===p.kind)return null;if(N.kind==="value"){for(const _ of B_)if(!Bv(_,p))return null}}return`Expected ${yu(N)} but found ${yu(p)} instead.`}function Fx(N,p){return p.some(_=>_==="null"?N===null:_==="array"?Array.isArray(N):_==="object"?N&&!Array.isArray(N)&&typeof N=="object":_===typeof N)}function Rb(N,p){return N.kind==="array"&&p.kind==="array"?N.N===p.N&&Rb(N.itemType,p.itemType):N.kind===p.kind}class ej{constructor(p,_,A){this.sensitivity=p?_?"variant":"case":_?"accent":"base",this.locale=A,this.collator=new Intl.Collator(this.locale?this.locale:[],{sensitivity:this.sensitivity,usage:"search"})}compare(p,_){return this.collator.compare(p,_)}resolvedLocale(){return new Intl.Collator(this.locale?this.locale:[]).resolvedOptions().locale}}class Bm{constructor(p,_,A,M,F){this.text=p.normalize?p.normalize():p,this.image=_,this.scale=A,this.fontStack=M,this.textColor=F}}class vu{constructor(p){this.sections=p}static fromString(p){return new vu([new Bm(p,null,null,null,null)])}isEmpty(){return this.sections.length===0||!this.sections.some(p=>p.text.length!==0||!!p.image&&p.image.hasPrimary())}static factory(p){return p instanceof vu?p:vu.fromString(p)}toString(){return this.sections.length===0?"":this.sections.map(p=>p.text).join("")}serialize(){const p=["format"];for(const _ of this.sections){if(_.image){const M=_.image.getPrimary().id.toString();p.push(["image",M]);continue}p.push(_.text);const A={};_.fontStack&&(A["text-font"]=["literal",_.fontStack.split(",")]),_.scale&&(A["font-scale"]=_.scale),_.textColor&&(A["text-color"]=["rgba"].concat(_.textColor.toNonPremultipliedRenderColor(null).toArray())),p.push(A)}return p}}class Rh{constructor(p,_={}){this.id=_d.from(p),this.params=_.params,this.sx=_.sx||1,this.sy=_.sy||1}toString(){return JSON.stringify(this)}static parse(p){let _,A,M,F;try{({id:_,params:A,sx:M,sy:F}=JSON.parse(p)||{})}catch{return null}return _?new Rh(_,{params:A,sx:M,sy:F}):null}scaleSelf(p,_=p){return this.sx*=p,this.sy*=_,this}}class vh{constructor(p,_,A,M,F=!1){this.primaryId=_d.from(p),this.primaryOptions=_,A&&(this.secondaryId=_d.from(A)),this.secondaryOptions=M,this.available=F}toString(){return this.primaryId&&this.secondaryId?`[${this.primaryId.name},${this.secondaryId.name}]`:this.primaryId.name}hasPrimary(){return!!this.primaryId}getPrimary(){return new Rh(this.primaryId,this.primaryOptions)}hasSecondary(){return!!this.secondaryId}getSecondary(){return this.secondaryId?new Rh(this.secondaryId,this.secondaryOptions):null}static from(p){return typeof p!="string"?p:vh.build({name:p})}static build(p,_,A,M){return!p||typeof p=="object"&&!("name"in p)?null:new vh(p,A,_,M)}}function Ui(N,p,_,A){return typeof N=="number"&&N>=0&&N<=255&&typeof p=="number"&&p>=0&&p<=255&&typeof _=="number"&&_>=0&&_<=255?A===void 0||typeof A=="number"&&A>=0&&A<=1?null:`Invalid rgba value [${[N,p,_,A].join(", ")}]: 'a' must be between 0 and 1.`:`Invalid rgba value [${(typeof A=="number"?[N,p,_,A]:[N,p,_]).join(", ")}]: 'r', 'g', and 'b' must be between 0 and 255.`}function hm(N){if(N===null||typeof N=="string"||typeof N=="boolean"||typeof N=="number"||N instanceof Ci||N instanceof ej||N instanceof vu||N instanceof vh)return!0;if(Array.isArray(N)){for(const p of N)if(!hm(p))return!1;return!0}if(typeof N=="object"){for(const p in N)if(!hm(N[p]))return!1;return!0}return!1}function ch(N){if(N===null)return xu;if(typeof N=="string")return Ao;if(typeof N=="boolean")return pl;if(typeof N=="number")return fa;if(N instanceof Ci)return ed;if(N instanceof ej)return q0;if(N instanceof vu)return yh;if(N instanceof vh)return uf;if(Array.isArray(N)){const p=N.length;let _;for(const A of N){const M=ch(A);if(_){if(_===M)continue;_=Wo;break}_=M}return Vd(_||Wo,p)}return ag}function np(N){return N===null?"":typeof N=="string"||typeof N=="number"||typeof N=="boolean"?String(N):N instanceof vu||N instanceof vh||N instanceof Ci?N.toString():JSON.stringify(N)}class Qg{constructor(p,_){this.type=p,this.value=_}static parse(p,_){if(p.length!==2)return _.error(`'literal' expression requires exactly one argument, but found ${p.length-1} instead.`);if(!hm(p[1]))return _.error("invalid value");const A=p[1];let M=ch(A);const F=_.expectedType;return M.kind!=="array"||M.N!==0||!F||F.kind!=="array"||typeof F.N=="number"&&F.N!==0||(M=F),new Qg(M,A)}evaluate(){return this.value}eachChild(){}outputDefined(){return!0}serialize(){return this.type.kind==="array"||this.type.kind==="object"?["literal",this.value]:this.value instanceof Ci?["rgba"].concat(this.value.toNonPremultipliedRenderColor(null).toArray()):this.value instanceof vu?this.value.serialize():this.value}}class dh{constructor(p){this.name="ExpressionEvaluationError",this.message=p}toJSON(){return this.message}}const Rc={string:Ao,number:fa,boolean:pl,object:ag};class Jg{constructor(p,_){this.type=p,this.args=_}static parse(p,_){if(p.length<2)return _.error("Expected at least one argument.");let A,M=1;const F=p[0];if(F==="array"){let H,Z;if(p.length>2){const se=p[1];if(typeof se!="string"||!(se in Rc)||se==="object")return _.error('The item type argument of "array" must be one of string, number, boolean',1);H=Rc[se],M++}else H=Wo;if(p.length>3){if(p[2]!==null&&(typeof p[2]!="number"||p[2]<0||p[2]!==Math.floor(p[2])))return _.error('The length argument to "array" must be a positive integer literal',2);Z=p[2],M++}A=Vd(H,Z)}else A=Rc[F];const z=[];for(;Mp.outputDefined())}serialize(){const p=this.type,_=[p.kind];if(p.kind==="array"){const A=p.itemType;if(A.kind==="string"||A.kind==="number"||A.kind==="boolean"){_.push(A.kind);const M=p.N;(typeof M=="number"||this.args.length>1)&&_.push(M)}}return _.concat(this.args.map(A=>A.serialize()))}}class F1{constructor(p){this.type=yh,this.sections=p}static parse(p,_){if(p.length<2)return _.error("Expected at least one argument.");const A=p[1];if(!Array.isArray(A)&&typeof A=="object")return _.error("First argument must be an image or text section.");const M=[];let F=!1;for(let z=1;z<=p.length-1;++z){const H=p[z];if(F&&typeof H=="object"&&!Array.isArray(H)){F=!1;let Z=null;if(H["font-scale"]&&(Z=_.parseObjectValue(H["font-scale"],z,"font-scale",fa),!Z))return null;let se=null;if(H["text-font"]&&(se=_.parseObjectValue(H["text-font"],z,"text-font",Vd(Ao)),!se))return null;let fe=null;if(H["text-color"]&&(fe=_.parseObjectValue(H["text-color"],z,"text-color",ed),!fe))return null;const xe=M.at(-1);xe.scale=Z,xe.font=se,xe.textColor=fe}else{const Z=_.parse(p[z],z,Wo);if(!Z)return null;const se=Z.type.kind;if(se!=="string"&&se!=="value"&&se!=="null"&&se!=="resolvedImage")return _.error("Formatted text type must be 'string', 'value', 'image' or 'null'.");F=!0,M.push({content:Z,scale:null,font:null,textColor:null})}}return new F1(M)}evaluate(p){return new vu(this.sections.map(_=>{const A=_.content.evaluate(p);return Rb(ch(A),uf)?new Bm("",A,null,null,null):new Bm(np(A),null,_.scale?_.scale.evaluate(p):null,_.font?_.font.evaluate(p).join(","):null,_.textColor?_.textColor.evaluate(p):null)}))}eachChild(p){for(const _ of this.sections)p(_.content),_.scale&&p(_.scale),_.font&&p(_.font),_.textColor&&p(_.textColor)}outputDefined(){return!1}serialize(){const p=["format"];for(const _ of this.sections){p.push(_.content.serialize());const A={};_.scale&&(A["font-scale"]=_.scale.serialize()),_.font&&(A["text-font"]=_.font.serialize()),_.textColor&&(A["text-color"]=_.textColor.serialize()),p.push(A)}return p}}class O1{constructor(p,_,A,M){this._imageWarnHistory={},this.type=uf,this.namePrimary=p,this.nameSecondary=_,A&&(this.paramsPrimary=A.params,this.iconsetIdPrimary=A.iconset?A.iconset.id:void 0),M&&(this.paramsSecondary=M.params,this.iconsetIdSecondary=M.iconset?M.iconset.id:void 0)}static parse(p,_){if(p.length<2)return _.error("Expected two or more arguments.");let A=1;const M=[];function F(){if(A_d.isEqual(z,F)),M.available){const z=M.getSecondary()?M.getSecondary().id:null;z&&(M.available=p.availableImages.some(H=>_d.isEqual(H,z)))}}return M}eachChild(p){if(p(this.namePrimary),this.paramsPrimary)for(const _ in this.paramsPrimary)this.paramsPrimary[_]&&p(this.paramsPrimary[_]);if(this.nameSecondary&&(p(this.nameSecondary),this.paramsSecondary))for(const _ in this.paramsSecondary)this.paramsSecondary[_]&&p(this.paramsSecondary[_])}outputDefined(){return!1}serializeOptions(p,_){const A={};if(_&&(A.iconset={id:_}),p){A.params={};for(const M in p)p[M]&&(A.params[M]=p[M].serialize())}return Object.keys(A).length>0?A:void 0}serialize(){const p=["image",this.namePrimary.serialize()];if(this.paramsPrimary||this.iconsetIdPrimary){const _=this.serializeOptions(this.paramsPrimary,this.iconsetIdPrimary);_&&p.push(_)}if(this.nameSecondary&&(p.push(this.nameSecondary.serialize()),this.paramsSecondary||this.iconsetIdSecondary)){const _=this.serializeOptions(this.paramsSecondary,this.iconsetIdSecondary);_&&p.push(_)}return p}}function z1(N){return sj(N)?"string":$_(N)?"number":Rk(N)?"boolean":Array.isArray(N)?"array":N===null?"null":tj(N)?"object":typeof N}function tj(N){return N!=null&&!Array.isArray(N)&&typeof N!="function"&&!(N instanceof String||N instanceof Number||N instanceof Boolean)&&typeof N=="object"}function sj(N){return typeof N=="string"||N instanceof String}function $_(N){return typeof N=="number"||N instanceof Number}function Rk(N){return typeof N=="boolean"||N instanceof Boolean}const Db={"to-boolean":pl,"to-color":ed,"to-number":fa,"to-string":Ao};class $v{constructor(p,_){this.type=p,this.args=_}static parse(p,_){if(p.length<2)return _.error("Expected at least one argument.");const A=p[0],M=[];let F=xu;if(A==="to-array"){if(!Array.isArray(p[1]))return null;const z=p[1].length;if(_.expectedType){if(_.expectedType.kind!=="array")return _.error(`Expected ${_.expectedType.kind} but found array.`);F=Vd(_.expectedType.itemType,z)}else{if(!(z>0&&hm(p[1][0])))return null;F=Vd(ch(p[1][0]),z)}for(let H=0;H4?`Invalid rbga value ${JSON.stringify(_)}: expected an array containing either three or four numeric values.`:Ui(_[0],_[1],_[2],_[3]),!A))return new Ci(_[0]/255,_[1]/255,_[2]/255,_[3])}throw new dh(A||`Could not parse color from value '${typeof _=="string"?_:String(JSON.stringify(_))}'`)}if(this.type.kind==="number"){let _=null;for(const A of this.args){if(_=A.evaluate(p),_===null)return 0;const M=Number(_);if(!isNaN(M))return M}throw new dh(`Could not convert ${JSON.stringify(_)} to number.`)}return this.type.kind==="formatted"?vu.fromString(np(this.args[0].evaluate(p))):this.type.kind==="resolvedImage"?vh.build(np(this.args[0].evaluate(p))):this.type.kind==="array"?this.args.map(_=>_.evaluate(p)):np(this.args[0].evaluate(p))}eachChild(p){this.args.forEach(p)}outputDefined(){return this.args.every(p=>p.outputDefined())}serialize(){if(this.type.kind==="formatted")return new F1([{content:this.args[0],scale:null,font:null,textColor:null}]).serialize();if(this.type.kind==="resolvedImage")return new O1(this.args[0]).serialize();const p=this.type.kind==="array"?[]:[`to-${this.type.kind}`];return this.eachChild(_=>{p.push(_.serialize())}),p}}const C3=["Unknown","Point","LineString","Polygon"];class Z2{constructor(p,_,A){this.globals=null,this.feature=null,this.featureState=null,this.formattedSection=null,this.availableImages=null,this.canonical=null,this.featureTileCoord=null,this.featureDistanceData=null,this.scope=p,this.options=_,this.iconImageUseTheme=A}id(){return this.feature&&this.feature.id!==void 0?this.feature.id:null}geometryType(){return this.feature?typeof this.feature.type=="number"?C3[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(p){return this.globals.brightness||0}distanceFromCenter(){if(this.featureTileCoord&&this.featureDistanceData){const p=this.featureDistanceData.center,_=this.featureDistanceData.scale,{x:A,y:M}=this.featureTileCoord;return this.featureDistanceData.bearing[0]*(A*_-p[0])+this.featureDistanceData.bearing[1]*(M*_-p[1])}return 0}parseColor(p){return Ci.parse(p)}getConfig(p){return this.options?this.options.get(p):null}}class rp{constructor(p,_,A,M,F){this.name=p,this.type=_,this._evaluate=A,this.args=M,this._overloadIndex=F}evaluate(p){if(!this._evaluate){const _=rp.definitions[this.name];this._evaluate=Array.isArray(_)?_[2]:_.overloads[this._overloadIndex][1]}return this._evaluate(p,this.args)}eachChild(p){this.args.forEach(p)}outputDefined(){return!1}serialize(){return[this.name].concat(this.args.map(p=>p.serialize()))}static parse(p,_){const A=p[0],M=rp.definitions[A];if(!M)return _.error(`Unknown expression "${A}". If you wanted a literal array, use ["literal", [...]].`,0);const F=Array.isArray(M)?M[0]:M.type,z=Array.isArray(M)?[[M[1],M[2]]]:M.overloads,H=[];let Z=null,se=-1;for(const[fe,xe]of z){if(Array.isArray(fe)&&fe.length!==p.length-1)continue;H.push(fe),se++,Z===null?Z=_._forkForSignature():Z.errors.length=0;const be=[];let Te=!1;for(let De=1;Debe)).map(Dk).join(" | "),xe=[];for(let be=1;be_[2]){const M=.5*A;let F=N[0]-_[0]>M?-A:_[0]-N[0]>M?A:0;F===0&&(F=N[0]-_[2]>M?-A:_[2]-N[0]>M?A:0),N[0]+=F}ii(p,N)}function E3(N,p,_,A){const M=Math.pow(2,A.z)*Uv,F=[A.x*Uv,A.y*Uv],z=[];if(!N)return z;for(const H of N)for(const Z of H){const se=[Z.x+F[0],Z.y+F[1]];DC(se,p,_,M),z.push(se)}return z}function Ob(N,p,_,A){const M=Math.pow(2,A.z)*Uv,F=[A.x*Uv,A.y*Uv],z=[];if(!N)return z;for(const Z of N){const se=[];for(const fe of Z){const xe=[fe.x+F[0],fe.y+F[1]];ii(p,xe),se.push(xe)}z.push(se)}if(p[2]-p[0]<=M/2){(H=p)[0]=H[1]=1/0,H[2]=H[3]=-1/0;for(const Z of z)for(const se of Z)DC(se,p,_,M)}var H;return z}class ip{constructor(p,_){this.type=pl,this.geojson=p,this.geometries=_}static parse(p,_){if(p.length!==2)return _.error(`'within' expression requires exactly one argument, but found ${p.length-1} instead.`);if(hm(p[1])){const A=p[1];if(A.type==="FeatureCollection")for(let M=0;MAM?1:0){if(this.data=p,this.length=this.data.length,this.compare=_,this.length>0)for(let A=(this.length>>1)-1;A>=0;A--)this._down(A)}push(p){this.data.push(p),this._up(this.length++)}pop(){if(this.length===0)return;const p=this.data[0],_=this.data.pop();return--this.length>0&&(this.data[0]=_,this._down(0)),p}peek(){return this.data[0]}_up(p){const{data:_,compare:A}=this,M=_[p];for(;p>0;){const F=p-1>>1,z=_[F];if(A(M,z)>=0)break;_[p]=z,p=F}_[p]=M}_down(p){const{data:_,compare:A}=this,M=this.length>>1,F=_[p];for(;p=0)break;_[p]=_[z],p=z}_[p]=F}}var Fr=8192;function Fk(N,p,_){return[N,p,_].filter(Boolean).join("")}function FC(N,p){switch(N){case"string":return np(p);case"number":return+p;case"boolean":return!!p;case"color":return Ci.parse(p);case"formatted":return vu.fromString(np(p));case"resolvedImage":return vh.build(np(p))}return p}function tx(N,p,_,A){return A!==void 0&&(N=A*Math.round(N/A)),p!==void 0&&N_&&(N=_),N}class hf{constructor(p,_,A,M=!1){this.type=p,this.key=_,this.scope=A,this.featureConstant=M}static parse(p,_){let A=_.expectedType;if(A??(A=Wo),p.length<2||p.length>3)return _.error("Invalid number of arguments for 'config' expression.");const M=_.parse(p[1],1);if(!(M instanceof Qg))return _.error("Key name of 'config' expression must be a string literal.");let F,z=!0;const H=np(M.value);if(p.length>=3){const Z=_.parse(p[2],2);if(!(Z instanceof Qg))return _.error("Scope of 'config' expression must be a string literal.");F=np(Z.value)}if(_.options){const Z=Fk(H,F,_._scope),se=_.options.get(Z);se&&(z=$1(se.value||se.default))}return new hf(A,H,F,z)}evaluate(p){const _=Fk(this.key,this.scope,p.scope),A=p.getConfig(_);if(!A)return null;const{type:M,value:F,values:z,minValue:H,maxValue:Z,stepValue:se}=A,fe=A.default.evaluate(p);let xe=fe;if(F){const be=p.scope;p.scope=(be||"").split("").slice(1).join(""),xe=F.evaluate(p),p.scope=be}return M&&(xe=FC(M,xe)),xe===void 0||H===void 0&&Z===void 0&&se===void 0||(typeof xe=="number"?xe=tx(xe,H,Z,se):Array.isArray(xe)&&(xe=xe.map(be=>typeof be=="number"?tx(be,H,Z,se):be))),F!==void 0&&xe!==void 0&&z&&!z.includes(xe)&&(xe=fe,M&&(xe=FC(M,xe))),(M&&M!==this.type||xe!==void 0&&!Rb(ch(xe),this.type))&&(xe=FC(this.type.kind,xe)),xe}eachChild(){}outputDefined(){return!1}serialize(){const p=["config",this.key];return this.scope&&p.concat(this.scope),p}}function $1(N){if(N instanceof rp&&(N.name==="get"&&N.args.length===1||N.name==="feature-state"||N.name==="has"&&N.args.length===1||N.name==="properties"||N.name==="geometry-type"||N.name==="id"||N.name.startsWith("filter-"))||N instanceof ip||N instanceof Fi)return!1;if(N instanceof hf)return N.featureConstant;let p=!0;return N.eachChild(_=>{p&&!$1(_)&&(p=!1)}),p}function H0(N){if(N instanceof rp&&N.name==="feature-state")return!1;let p=!0;return N.eachChild(_=>{p&&!H0(_)&&(p=!1)}),p}function G0(N,p){if(N instanceof rp&&p.has(N.name))return!1;let _=!0;return N.eachChild(A=>{_&&!G0(A,p)&&(_=!1)}),_}function zx(N,p){return G0(N,new Set(p))}const Ok=1/298.257223563,X2=Ok*(2-Ok),zk=Math.PI/180;function Bk(N){const p=6378.137*zk*1e3,_=Math.cos(N*zk),A=1/(1-X2*(1-_*_)),M=Math.sqrt(A);return[p*M*_,p*M*A*(1-X2)]}function U_(N){for(;N<-180;)N+=360;for(;N>180;)N-=360;return N}function rj(N,p,_,A){const M=U_(N[0]-p[0])*_,F=(N[1]-p[1])*A;return Math.sqrt(M*M+F*F)}function q_(N,p,_,A,M){let F=p[0],z=p[1],H=U_(_[0]-F)*A,Z=(_[1]-z)*M;if(H!==0||Z!==0){const se=(U_(N[0]-F)*A*H+(N[1]-z)*M*Z)/(H*H+Z*Z);se>1?(F=_[0],z=_[1]):se>0&&(F+=H/A*se,z+=Z/M*se)}return H=U_(N[0]-F)*A,Z=(N[1]-z)*M,Math.sqrt(H*H+Z*Z)}function OC(N,p){return p.dist-N.dist}function Q2(N){const p=[1/0,1/0,-1/0,-1/0];if(p.length!==N.length)return!1;for(let _=0;_=N[0]&&N[1]N[1])return[null,null];const _=V_(N);if(p){if(_===2)return[N,null];const A=Math.floor(_/2);return[[N[0],N[0]+A],[N[0]+A,N[1]]]}{if(_===1)return[N,null];const A=Math.floor(_/2)-1;return[[N[0],N[0]+A],[N[0]+A+1,N[1]]]}}function U1(N,p){const _=[1/0,1/0,-1/0,-1/0];if(!sx(p,N.length))return _;for(let A=p[0];A<=p[1];++A)ii(_,N[A]);return _}function aj(N){const p=[1/0,1/0,-1/0,-1/0];for(let _=0;_p[2]&&(M=N[0]-p[2]),N[1]>p[3]&&(F=N[1]-p[3]),N[3]1?(Te=F[be+1][0],De=F[be+1][1]):st>0&&(Te+=Ue/H*st,De+=Ye/Z*st)),Ue=U_(z[0]-Te)*H,Ye=(z[1]-De)*Z;const ot=Ue*Ue+Ye*Ye;ot=M)return M;if($i(F,z)){if(Xn(N,p))return 0}else if(Xn(p,N))return 0;let H=M;for(const Z of N)for(let se=0,fe=Z.length,xe=fe-1;se=z)continue;const xe=fe.range1;if(V_(xe)<=Z){if(!sx(xe,N.length))return NaN;if(p){const be=on(N,xe,_,A,M);if((z=Math.min(z,be))===0)return z}else for(let be=xe[0];be<=xe[1];++be){const Te=qs(N[be],_,A,M);if((z=Math.min(z,Te))===0)return z}}else{const be=zC(xe,p);if(be[0]!==null){const Te=Pe(U1(N,be[0]),se,A,M);Te=H)continue;const be=xe.range1,Te=xe.range2;if(V_(be)<=se&&V_(Te)<=fe){if(!sx(be,N.length)||!sx(Te,_.length))return NaN;if(p&&A?H=Math.min(H,Es(N,be,_,Te,M,F)):p||A?p&&!A?H=Math.min(H,is(_,Te,N,be,M,F)):!p&&A&&(H=Math.min(H,is(N,be,_,Te,M,F))):H=Math.min(H,Ds(N,be,_,Te,M,F)),H===0)return H}else{const De=zC(be,p),Ue=zC(Te,A);Js(Z,H,M,F,N,_,De[0],Ue[0]),Js(Z,H,M,F,N,_,De[0],Ue[1]),Js(Z,H,M,F,N,_,De[1],Ue[0]),Js(Z,H,M,F,N,_,De[1],Ue[1])}}return H}function aa(N,p,_,A,M,F=1/0){let z=F;const H=U1(N,[0,N.length-1]);for(const Z of _)if(!(z!==1/0&&Pe(H,U1(Z,[0,Z.length-1]),A,M)>=z)&&(z=Math.min(z,_r(N,p,Z,!0,A,M,z)),z===0))return z;return z}function mr(N,p,_,A,M,F=1/0){let z=F;const H=U1(N,[0,N.length-1]);for(const Z of _){if(z!==1/0&&Pe(H,aj(Z),A,M)>=z)continue;const se=lr(N,p,Z,A,M,z);if(isNaN(se))return se;if((z=Math.min(z,se))===0)return z}return z}function pa(N,p,_){const A=[];for(const z of N)for(const H of z)A.push(He(H,p));const[M,F]=Bk(A[0][1]);return _.type==="Point"||_.type==="MultiPoint"||_.type==="LineString"?_r(A,!1,_.type==="Point"?[_.coordinates]:_.coordinates,_.type==="LineString",M,F):_.type==="MultiLineString"?aa(A,!1,_.coordinates,M,F):_.type==="Polygon"||_.type==="MultiPolygon"?mr(A,!1,_.type==="Polygon"?[_.coordinates]:_.coordinates,M,F):null}function dr(N,p,_){const A=[];for(const z of N){const H=[];for(const Z of z)H.push(He(Z,p));A.push(H)}const[M,F]=Bk(A[0][0][1]);if(_.type==="Point"||_.type==="MultiPoint"||_.type==="LineString")return aa(_.type==="Point"?[_.coordinates]:_.coordinates,_.type==="LineString",A,M,F);if(_.type==="MultiLineString"){let z=1/0;for(let H=0;H<_.coordinates.length;H++){const Z=aa(_.coordinates[H],!0,A,M,F,z);if(isNaN(Z))return Z;if((z=Math.min(z,Z))===0)return z}return z}if(_.type==="Polygon"||_.type==="MultiPolygon"){let z=1/0;for(let H=0;H`[${M}]`).join("")}`;this.errors.push(new Ro(A,p))}checkSubtype(p,_,A){const M=Bv(p,_);return M&&this.error(M,...typeof A=="number"?[A]:[]),M}}const Dc=new Set(["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 mf(N,p,_){return _==="assert"?new Jg(p,[N]):_==="coerce"?new $v(p,[N]):N}function Zl(N){if(N instanceof bl)return Zl(N.boundExpression);if(N instanceof rp&&N.name==="error"||N instanceof B1||N instanceof ip||N instanceof Fi||N instanceof hf)return!1;const p=N instanceof $v||N instanceof Jg;let _=!0;return N.eachChild(A=>{_=p?_&&Zl(A):_&&A instanceof Qg}),!!_&&$1(N)&&G0(N,Dc)}function yo(N,p){const _=N.length-1;let A,M,F=0,z=_,H=0;for(;F<=z;)if(H=Math.floor((F+z)/2),A=N[H],M=N[H+1],A<=p){if(H===_||pp))throw new dh("Input is not a number.");z=H-1}return 0}class bi{constructor(p,_,A){this.type=p,this.input=_,this.labels=[],this.outputs=[];for(const[M,F]of A)this.labels.push(M),this.outputs.push(F)}static parse(p,_){if(p.length-1<4)return _.error(`Expected at least 4 arguments, but found only ${p.length-1}.`);if((p.length-1)%2!=0)return _.error("Expected an even number of arguments.");const A=_.parse(p[1],1,fa);if(!A)return null;const M=[];let F=null;_.expectedType&&_.expectedType.kind!=="value"&&(F=_.expectedType);for(let z=1;z=H)return _.error('Input/output pairs for "step" expressions must be arranged with input values in strictly ascending order.',se);const xe=_.parse(Z,fe,F);if(!xe)return null;F=F||xe.type,M.push([H,xe])}return new bi(F,A,M)}evaluate(p){const _=this.labels,A=this.outputs;if(_.length===1)return A[0].evaluate(p);const M=this.input.evaluate(p);if(M<=_[0])return A[0].evaluate(p);const F=_.length;return M>=_[F-1]?A[F-1].evaluate(p):A[yo(_,M)].evaluate(p)}eachChild(p){p(this.input);for(const _ of this.outputs)p(_)}outputDefined(){return this.outputs.every(p=>p.outputDefined())}serialize(){const p=["step",this.input.serialize()];for(let _=0;_0&&p.push(this.labels[_]),p.push(this.outputs[_].serialize());return p}}const mm=.95047,To=1.08883,Xl=4/29,Uc=6/29,Lf=3*Uc*Uc,ig=Uc*Uc*Uc,Qd=Math.PI/180,og=180/Math.PI;function Dh(N){return N>ig?Math.pow(N,1/3):N/Lf+Xl}function ff(N){return N>Uc?N*N*N:Lf*(N-Xl)}function md(N){return 255*(N<=.0031308?12.92*N:1.055*Math.pow(N,1/2.4)-.055)}function cu(N){return(N/=255)<=.04045?N/12.92:Math.pow((N+.055)/1.055,2.4)}function uh(N){const p=cu(N.r),_=cu(N.g),A=cu(N.b),M=Dh((.4124564*p+.3575761*_+.1804375*A)/mm),F=Dh((.2126729*p+.7151522*_+.072175*A)/1);return{l:116*F-16,a:500*(M-F),b:200*(F-Dh((.0193339*p+.119192*_+.9503041*A)/To)),alpha:N.a}}function du(N){let p=(N.l+16)/116,_=isNaN(N.a)?p:p+N.a/500,A=isNaN(N.b)?p:p-N.b/200;return p=1*ff(p),_=mm*ff(_),A=To*ff(A),new Ci(md(3.2404542*_-1.5371385*p-.4985314*A),md(-.969266*_+1.8760108*p+.041556*A),md(.0556434*_-.2040259*p+1.0572252*A),N.alpha)}function Rf(N,p,_){const A=p-N;return N+_*(A>180||A<-180?A-360*Math.round(A/360):A)}const op={forward:uh,reverse:du,interpolate:function(N,p,_){return{l:ya(N.l,p.l,_),a:ya(N.a,p.a,_),b:ya(N.b,p.b,_),alpha:ya(N.alpha,p.alpha,_)}}},hh={forward:function(N){const{l:p,a:_,b:A}=uh(N),M=Math.atan2(A,_)*og;return{h:M<0?M+360:M,c:Math.sqrt(_*_+A*A),l:p,alpha:N.a}},reverse:function(N){const p=N.h*Qd,_=N.c;return du({l:N.l,a:Math.cos(p)*_,b:Math.sin(p)*_,alpha:N.alpha})},interpolate:function(N,p,_){return{h:Rf(N.h,p.h,_),c:ya(N.c,p.c,_),l:ya(N.l,p.l,_),alpha:ya(N.alpha,p.alpha,_)}}};var bh=Object.freeze({__proto__:null,hcl:hh,lab:op});class vc{constructor(p,_,A,M,F){this.type=p,this.operator=_,this.interpolation=A,this.input=M,this.labels=[],this.outputs=[];for(const[z,H]of F)this.labels.push(z),this.outputs.push(H)}static interpolationFactor(p,_,A,M){let F=0;if(p.name==="exponential")F=Fh(_,p.base,A,M);else if(p.name==="linear")F=Fh(_,1,A,M);else if(p.name==="cubic-bezier"){const z=p.controlPoints;F=vn(z[0],z[1],z[2],z[3])(Fh(_,1,A,M))}return F}static parse(p,_){let[A,M,F,...z]=p;if(!Array.isArray(M)||M.length===0)return _.error("Expected an interpolation type expression.",1);if(M[0]==="linear")M={name:"linear"};else if(M[0]==="exponential"){const se=M[1];if(typeof se!="number")return _.error("Exponential interpolation requires a numeric base.",1,1);M={name:"exponential",base:se}}else{if(M[0]!=="cubic-bezier")return _.error(`Unknown interpolation type ${String(M[0])}`,1,0);{const se=M.slice(1);if(se.length!==4||se.some(fe=>typeof fe!="number"||fe<0||fe>1))return _.error("Cubic bezier interpolation requires four numeric arguments with values between 0 and 1.",1);M={name:"cubic-bezier",controlPoints:se}}}if(p.length-1<4)return _.error(`Expected at least 4 arguments, but found only ${p.length-1}.`);if(p.length-1>3&&(p.length-1)%2!=0)return _.error("Expected an even number of arguments.");if(F=_.parse(F,2,fa),!F)return null;const H=[];let Z=null;A==="interpolate-hcl"||A==="interpolate-lab"?Z=ed:_.expectedType&&_.expectedType.kind!=="value"&&(Z=_.expectedType);for(let se=0;se=fe)return _.error('Input/output pairs for "interpolate" expressions must be arranged with input values in strictly ascending order.',be);const De=_.parse(xe,Te,Z);if(!De)return null;Z=Z||De.type,H.push([fe,De])}return Z.kind==="number"||Z.kind==="color"||Z.kind==="array"&&Z.itemType.kind==="number"&&typeof Z.N=="number"?new vc(Z,A,M,F,H):_.error(`Type ${yu(Z)} is not interpolatable.`)}evaluate(p){const _=this.labels,A=this.outputs;if(_.length===1)return A[0].evaluate(p);const M=this.input.evaluate(p);if(M<=_[0])return A[0].evaluate(p);const F=_.length;if(M>=_[F-1])return A[F-1].evaluate(p);const z=yo(_,M),H=vc.interpolationFactor(this.interpolation,M,_[z],_[z+1]),Z=A[z].evaluate(p),se=A[z+1].evaluate(p);return this.operator==="interpolate"?Sc[this.type.kind.toLowerCase()](Z,se,H):this.operator==="interpolate-hcl"?hh.reverse(hh.interpolate(hh.forward(Z),hh.forward(se),H)):op.reverse(op.interpolate(op.forward(Z),op.forward(se),H))}eachChild(p){p(this.input);for(const _ of this.outputs)p(_)}outputDefined(){return this.outputs.every(p=>p.outputDefined())}serialize(){let p;p=this.interpolation.name==="linear"?["linear"]:this.interpolation.name==="exponential"?this.interpolation.base===1?["linear"]:["exponential",this.interpolation.base]:["cubic-bezier",...this.interpolation.controlPoints];const _=[this.operator,p,this.input.serialize()];for(let A=0;ABv(M,H.type));return new $m(z?Wo:A,F)}evaluate(p){let _,A=null,M=0;for(const F of this.args){if(M++,A=F.evaluate(p),A&&A instanceof vh&&!A.available&&(_||(_=A),A=null,M===this.args.length))return _;if(A!==null)break}return A}eachChild(p){this.args.forEach(p)}outputDefined(){return this.args.every(p=>p.outputDefined())}serialize(){const p=["coalesce"];return this.eachChild(_=>{p.push(_.serialize())}),p}}const Df=/[^a-zA-Z0-9_]/;class Mp{constructor(p,_){this.type=_.type,this.bindings=[].concat(p),this.result=_}evaluate(p){return this.result.evaluate(p)}eachChild(p){for(const _ of this.bindings)p(_[1]);p(this.result)}static parse(p,_){if(p.length<4)return _.error(`Expected at least 3 arguments, but found ${p.length-1} instead.`);const A=[];for(let F=1;F=A.length)throw new dh("Array index out of bounds: index exceeds array size");if(_!==Math.floor(_))throw new dh("Array index must be an integer. Use at-interpolated for fractional indices");return A[_]}eachChild(p){p(this.index),p(this.input)}outputDefined(){return!1}serialize(){return["at",this.index.serialize(),this.input.serialize()]}}class Pp{constructor(p,_,A){this.type=p,this.index=_,this.input=A}static parse(p,_){if(p.length!==3)return _.error(`Expected 2 arguments, but found ${p.length-1} instead.`);const A=_.parse(p[1],1,fa),M=_.parse(p[2],2,Vd(_.expectedType||Wo));return A&&M?new Pp(M.type.itemType,A,M):null}evaluate(p){const _=this.index.evaluate(p),A=this.input.evaluate(p);if(_<0)throw new dh(`Array index out of bounds: ${_} < 0.`);if(_>A.length-1)throw new dh(`Array index out of bounds: ${_} > ${A.length-1}.`);if(_===Math.floor(_))return A[_];const M=Math.floor(_),F=Math.ceil(_),z=A[M],H=A[F];if(typeof z!="number"||typeof H!="number")throw new dh(`Cannot interpolate between non-number values at index ${_}.`);return ya(z,H,_-M)}eachChild(p){p(this.index),p(this.input)}outputDefined(){return!1}serialize(){return["at-interpolated",this.index.serialize(),this.input.serialize()]}}class rx{constructor(p,_,A,M,F,z){this.inputType=p,this.type=_,this.input=A,this.cases=M,this.outputs=F,this.otherwise=z}static parse(p,_){if(p.length<5)return _.error(`Expected at least 4 arguments, but found only ${p.length-1}.`);if(p.length%2!=1)return _.error("Expected an even number of arguments.");let A,M;_.expectedType&&_.expectedType.kind!=="value"&&(M=_.expectedType);const F={},z=[];for(let se=2;seNumber.MAX_SAFE_INTEGER)return _.error(`Branch labels must be integers no larger than ${Number.MAX_SAFE_INTEGER}.`,se);if(typeof Te=="number"&&Math.floor(Te)!==Te)return _.error("Numeric branch labels must be integer values.",se);if(A){if(_.checkSubtype(A,ch(Te),se))return null}else A=ch(Te);if(F[String(Te)]!==void 0)return _.error("Branch labels must be unique.",se);F[String(Te)]=z.length}const be=_.parse(xe,se,M);if(!be)return null;M=M||be.type,z.push(be)}const H=_.parse(p[1],1,Wo);if(!H)return null;const Z=_.parse(p.at(-1),p.length-1,M);return Z?H.type.kind!=="value"&&_.checkSubtype(A,H.type,1)?null:new rx(A,M,H,F,z,Z):null}evaluate(p){const _=this.input.evaluate(p);return(Rb(ch(_),this.inputType)&&this.outputs[this.cases[_]]||this.otherwise).evaluate(p)}eachChild(p){p(this.input),this.outputs.forEach(p),p(this.otherwise)}outputDefined(){return this.outputs.every(p=>p.outputDefined())&&this.otherwise.outputDefined()}serialize(){const p=["match",this.input.serialize()],_=Object.keys(this.cases).sort(),A=[],M={};for(const z of _){const H=M[this.cases[z]];H===void 0?(M[this.cases[z]]=A.length,A.push([this.cases[z],[z]])):A[H][1].push(z)}const F=z=>this.inputType.kind==="number"?Number(z):z;for(const[z,H]of A)p.push(H.length===1?F(H[0]):H.map(F)),p.push(this.outputs[z].serialize());return p.push(this.otherwise.serialize()),p}}class Jd{constructor(p,_,A){this.type=p,this.branches=_,this.otherwise=A}static parse(p,_){if(p.length<4)return _.error(`Expected at least 3 arguments, but found only ${p.length-1}.`),null;if(p.length%2!=0)return _.error("Expected an odd number of arguments."),null;let A;_.expectedType&&_.expectedType.kind!=="value"&&(A=_.expectedType);const M=[];for(let z=1;z_.outputDefined())&&this.otherwise.outputDefined()}serialize(){const p=["case"];return this.eachChild(_=>{p.push(_.serialize())}),p}}class pf{constructor(p,_,A,M){this.type=p,this.input=_,this.beginIndex=A,this.endIndex=M}static parse(p,_){if(p.length<=2||p.length>=5)return _.error(`Expected 3 or 4 arguments, but found ${p.length-1} instead.`),null;const A=_.parse(p[1],1,Wo),M=_.parse(p[2],2,fa);if(!A||!M)return null;if(F=A.type,![Vd(Wo),Ao,Wo].some(z=>z.kind===F.kind))return _.error(`Expected first argument to be of type array or string, but found ${yu(A.type)} instead`),null;var F;if(p.length===4){const z=_.parse(p[3],3,fa);return z?new pf(A.type,A,M,z):null}return new pf(A.type,A,M)}evaluate(p){const _=this.input.evaluate(p),A=this.beginIndex.evaluate(p);if(!Fx(_,["string","array"]))throw new dh(`Expected first argument to be of type array or string, but found ${yu(ch(_))} instead.`);if(this.endIndex){const M=this.endIndex.evaluate(p);return _.slice(A,M)}return _.slice(A)}eachChild(p){p(this.input),p(this.beginIndex),this.endIndex&&p(this.endIndex)}outputDefined(){return!1}serialize(){if(this.endIndex!=null&&this.endIndex!==void 0){const p=this.endIndex.serialize();return["slice",this.input.serialize(),this.beginIndex.serialize(),p]}return["slice",this.input.serialize(),this.beginIndex.serialize()]}}function Pd(N,p){return N==="=="||N==="!="?p.kind==="boolean"||p.kind==="string"||p.kind==="number"||p.kind==="null"||p.kind==="value":p.kind==="string"||p.kind==="number"||p.kind==="value"}function Ql(N,p,_,A){return A.compare(p,_)===0}function Gd(N,p,_){const A=N!=="=="&&N!=="!=";return class W7t{constructor(F,z,H){this.type=pl,this.lhs=F,this.rhs=z,this.collator=H,this.hasUntypedArgument=F.type.kind==="value"||z.type.kind==="value"}static parse(F,z){if(F.length!==3&&F.length!==4)return z.error("Expected two or three arguments.");const H=F[0];let Z=z.parse(F[1],1,Wo);if(!Z)return null;if(!Pd(H,Z.type))return z.error(`"${H}" comparisons are not supported for type '${yu(Z.type)}'.`,1);let se=z.parse(F[2],2,Wo);if(!se)return null;if(!Pd(H,se.type))return z.error(`"${H}" comparisons are not supported for type '${yu(se.type)}'.`,2);if(Z.type.kind!==se.type.kind&&Z.type.kind!=="value"&&se.type.kind!=="value")return z.error(`Cannot compare types '${yu(Z.type)}' and '${yu(se.type)}'.`);A&&(Z.type.kind==="value"&&se.type.kind!=="value"?Z=new Jg(se.type,[Z]):Z.type.kind!=="value"&&se.type.kind==="value"&&(se=new Jg(Z.type,[se])));let fe=null;if(F.length===4){if(Z.type.kind!=="string"&&se.type.kind!=="string"&&Z.type.kind!=="value"&&se.type.kind!=="value")return z.error("Cannot use collator to compare non-string types.");if(fe=z.parse(F[3],3,q0),!fe)return null}return new W7t(Z,se,fe)}evaluate(F){const z=this.lhs.evaluate(F),H=this.rhs.evaluate(F);if(A&&this.hasUntypedArgument){const Z=ch(z),se=ch(H);if(Z.kind!==se.kind||Z.kind!=="string"&&Z.kind!=="number")throw new dh(`Expected arguments for "${N}" to be (string, string) or (number, number), but found (${Z.kind}, ${se.kind}) instead.`)}if(this.collator&&!A&&this.hasUntypedArgument){const Z=ch(z),se=ch(H);if(Z.kind!=="string"||se.kind!=="string")return p(F,z,H)}return this.collator?_(F,z,H,this.collator.evaluate(F)):p(F,z,H)}eachChild(F){F(this.lhs),F(this.rhs),this.collator&&F(this.collator)}outputDefined(){return!0}serialize(){const F=[N];return this.eachChild(z=>{F.push(z.serialize())}),F}}}const wd=Gd("==",function(N,p,_){return p===_},Ql),Ff=Gd("!=",function(N,p,_){return p!==_},function(N,p,_,A){return!Ql(0,p,_,A)}),Bx=Gd("<",function(N,p,_){return p<_},function(N,p,_,A){return A.compare(p,_)<0}),q1=Gd(">",function(N,p,_){return p>_},function(N,p,_,A){return A.compare(p,_)>0}),wm=Gd("<=",function(N,p,_){return p<=_},function(N,p,_,A){return A.compare(p,_)<=0}),$k=Gd(">=",function(N,p,_){return p>=_},function(N,p,_,A){return A.compare(p,_)>=0});class V1{constructor(p,_,A,M,F,z){this.type=Ao,this.number=p,this.locale=_,this.currency=A,this.unit=M,this.minFractionDigits=F,this.maxFractionDigits=z}static parse(p,_){if(p.length!==3)return _.error("Expected two arguments.");const A=_.parse(p[1],1,fa);if(!A)return null;const M=p[2];if(typeof M!="object"||Array.isArray(M))return _.error("NumberFormat options argument must be an object.");let F=null;if(M.locale&&(F=_.parseObjectValue(M.locale,2,"locale",Ao),!F))return null;let z=null;if(M.currency&&(z=_.parseObjectValue(M.currency,2,"currency",Ao),!z))return null;let H=null;if(M.unit&&(H=_.parseObjectValue(M.unit,2,"unit",Ao),!H))return null;let Z=null;if(M["min-fraction-digits"]!==void 0&&(Z=_.parseObjectValue(M["min-fraction-digits"],2,"min-fraction-digits",fa),!Z))return null;let se=null;return M["max-fraction-digits"]===void 0||(se=_.parseObjectValue(M["max-fraction-digits"],2,"max-fraction-digits",fa),se)?new V1(A,F,z,H,Z,se):null}evaluate(p){return new Intl.NumberFormat(this.locale?this.locale.evaluate(p):[],{style:(this.currency?"currency":this.unit&&"unit")||"decimal",currency:this.currency?this.currency.evaluate(p):void 0,unit:this.unit?this.unit.evaluate(p):void 0,minimumFractionDigits:this.minFractionDigits?this.minFractionDigits.evaluate(p):void 0,maximumFractionDigits:this.maxFractionDigits?this.maxFractionDigits.evaluate(p):void 0}).format(this.number.evaluate(p))}eachChild(p){p(this.number),this.locale&&p(this.locale),this.currency&&p(this.currency),this.unit&&p(this.unit),this.minFractionDigits&&p(this.minFractionDigits),this.maxFractionDigits&&p(this.maxFractionDigits)}outputDefined(){return!1}serialize(){const p={};return this.locale&&(p.locale=this.locale.serialize()),this.currency&&(p.currency=this.currency.serialize()),this.unit&&(p.unit=this.unit.serialize()),this.minFractionDigits&&(p["min-fraction-digits"]=this.minFractionDigits.serialize()),this.maxFractionDigits&&(p["max-fraction-digits"]=this.maxFractionDigits.serialize()),["number-format",this.number.serialize(),p]}}class H1{constructor(p){this.type=fa,this.input=p}static parse(p,_){if(p.length!==2)return _.error(`Expected 1 argument, but found ${p.length-1} instead.`),null;const A=_.parse(p[1],1);return A?A.type.kind!=="array"&&A.type.kind!=="string"&&A.type.kind!=="value"?(_.error(`Expected argument of type string or array, but found ${yu(A.type)} instead.`),null):new H1(A):null}evaluate(p){const _=this.input.evaluate(p);if(typeof _=="string"||Array.isArray(_))return _.length;throw new dh(`Expected value to be of type string or array, but found ${yu(ch(_))} instead.`)}eachChild(p){p(this.input)}outputDefined(){return!1}serialize(){const p=["length"];return this.eachChild(_=>{p.push(_.serialize())}),p}}function lg(N){return function(){N=1831565813+(N|=0)|0;let p=Math.imul(N^N>>>15,1|N);return p=p+Math.imul(p^p>>>7,61|p)^p,((p^p>>>14)>>>0)/4294967296}}const zb={"==":wd,"!=":Ff,">":q1,"<":Bx,">=":$k,"<=":wm,array:Jg,at:nx,"at-interpolated":Pp,boolean:Jg,case:Jd,coalesce:$m,collator:B1,format:F1,image:O1,interpolate:vc,"interpolate-hcl":vc,"interpolate-lab":vc,length:H1,let:Mp,literal:Qg,match:rx,number:Jg,"number-format":V1,object:Jg,slice:pf,step:bi,string:Jg,"to-boolean":$v,"to-color":$v,"to-number":$v,"to-string":$v,var:bl,within:ip,distance:Fi,config:hf};function ax(N,[p,_,A,M]){p=p.evaluate(N),_=_.evaluate(N),A=A.evaluate(N);const F=M?M.evaluate(N):1,z=Ui(p,_,A,F);if(z)throw new dh(z);return new Ci(p/255,_/255,A/255,F)}function J2(N,[p,_,A,M]){p=p.evaluate(N),_=_.evaluate(N),A=A.evaluate(N);const F=M?M.evaluate(N):1,z=function(se,fe,xe,be){return typeof se=="number"&&se>=0&&se<=360?typeof fe=="number"&&fe>=0&&fe<=100&&typeof xe=="number"&&xe>=0&&xe<=100?be===void 0||typeof be=="number"&&be>=0&&be<=1?null:`Invalid hsla value [${[se,fe,xe,be].join(", ")}]: 'a' must be between 0 and 1.`:`Invalid hsla value [${(typeof be=="number"?[se,fe,xe,be]:[se,fe,xe]).join(", ")}]: 's', and 'l' must be between 0 and 100.`:`Invalid hsla value [${(typeof be=="number"?[se,fe,xe,be]:[se,fe,xe]).join(", ")}]: 'h' must be between 0 and 360.`}(p,_,A,F);if(z)throw new dh(z);const H=`hsla(${p}, ${_}%, ${A}%, ${F})`,Z=Ci.parse(H);if(!Z)throw new dh(`Failed to parse HSLA color: ${H}`);return Z}function Uk(N,p){return N in p}function by(N,p){const _=p[N];return _===void 0?null:_}function _y(N){return{type:N}}function ij(N,p){if(!Fx(N,["boolean","string","number","null"]))throw new dh(`Expected first argument to be of type boolean, string, number or null, but found ${yu(ch(N))} instead.`);if(!Fx(p,["string","array"]))throw new dh(`Expected second argument to be of type array or string, but found ${yu(ch(p))} instead.`)}function Bb(N){if(N instanceof hf)return new Set([N.key]);let p=new Set;return N.eachChild(_=>{p=new Set([...p,...Bb(_)])}),p}function $x(N){if(N instanceof rp&&N.name==="is-active-floor")return!0;let p=!1;return N.eachChild(_=>{!p&&$x(_)&&(p=!0)}),p}function G1(N){return{result:"success",value:N}}function lp(N){return{result:"error",value:N}}function H_(N,p){return!!N&&!!N.parameters&&N.parameters.includes(p)}function Xy(N){return N["property-type"]==="data-driven"}function qk(N){return H_(N.expression,"measure-light")}function oj(N){return H_(N.expression,"zoom")}function Qy(N){return!!N.expression&&N.expression.interpolated}function cp(N){return typeof N=="object"&&N!==null&&!Array.isArray(N)}function W1(N){return N}function Ux(N,p){const _=p.type==="color",A=N.stops&&typeof N.stops[0][0]=="object",M=A||!(A||N.property!==void 0),F=N.type||(Qy(p)?"exponential":"interval");if(_&&((N={...N}).stops&&(N.stops=N.stops.map(se=>[se[0],Ci.parse(se[1])])),N.default=Ci.parse(N.default?N.default:p.default)),N.colorSpace&&N.colorSpace!=="rgb"&&!bh[N.colorSpace])throw new Error(`Unknown color space: ${N.colorSpace}`);let z,H,Z;if(F==="exponential")z=Vk;else if(F==="interval")z=T3;else if(F==="categorical"){z=K1,H=Object.create(null);for(const se of N.stops)H[se[0]]=se[1];Z=typeof N.stops[0][0]}else{if(F!=="identity")throw new Error(`Unknown function type "${F}"`);z=KT}if(A){const se={},fe=[];for(let Te=0;TeTe[0]),evaluate:({zoom:Te},De)=>Vk({stops:xe,base:N.base},p,Te).evaluate(Te,De)}}if(M){const se=F==="exponential"?{name:"exponential",base:N.base!==void 0?N.base:1}:null;return{kind:"camera",interpolationType:se,interpolationFactor:vc.interpolationFactor.bind(void 0,se),zoomStops:N.stops.map(fe=>fe[0]),evaluate:({zoom:fe})=>z(N,p,fe,H,Z)}}return{kind:"source",evaluate(se,fe){const xe=fe&&fe.properties?fe.properties[N.property]:void 0;return xe===void 0?dp(N.default,p.default):z(N,p,xe,H,Z)}}}function dp(N,p,_){return N!==void 0?N:p!==void 0?p:_!==void 0?_:void 0}function K1(N,p,_,A,M){return dp(typeof _===M?A[_]:void 0,N.default,p.default)}function T3(N,p,_){if(!$_(_))return dp(N.default,p.default);const A=N.stops.length;if(A===1||_<=N.stops[0][0])return N.stops[0][1];if(_>=N.stops[A-1][0])return N.stops[A-1][1];const M=yo(N.stops.map(F=>F[0]),_);return N.stops[M][1]}function Vk(N,p,_){const A=N.base!==void 0?N.base:1;if(!$_(_))return dp(N.default,p.default);const M=N.stops.length;if(M===1||_<=N.stops[0][0])return N.stops[0][1];if(_>=N.stops[M-1][0])return N.stops[M-1][1];const F=yo(N.stops.map(fe=>fe[0]),_),z=function(fe,xe,be,Te){const De=Te-be,Ue=fe-be;return De===0?0:xe===1?Ue/De:(Math.pow(xe,Ue)-1)/(Math.pow(xe,De)-1)}(_,A,N.stops[F][0],N.stops[F+1][0]),H=N.stops[F][1],Z=N.stops[F+1][1];let se=Sc[p.type]||W1;if(N.colorSpace&&N.colorSpace!=="rgb"){const fe=bh[N.colorSpace];se=(xe,be)=>fe.reverse(fe.interpolate(fe.forward(xe),fe.forward(be),z))}return typeof H.evaluate=="function"?{evaluate(...fe){const xe=H.evaluate.apply(void 0,fe),be=Z.evaluate.apply(void 0,fe);if(xe!==void 0&&be!==void 0)return se(xe,be,z)}}:se(H,Z,z)}function KT(N,p,_){return p.type==="color"?_=Ci.parse(_):p.type==="formatted"?_=vu.fromString(_.toString()):p.type==="resolvedImage"?_=vh.build(_.toString()):z1(_)===p.type||p.type==="enum"&&p.values[_]||(_=void 0),dp(_,N.default,p.default)}rp.register(zb,{error:[{kind:"error"},[Ao],(N,[p])=>{throw new dh(p.evaluate(N))}],typeof:[Ao,[Wo],(N,[p])=>yu(ch(p.evaluate(N)))],"to-rgba":[Vd(fa,4),[ed],(N,[p])=>p.evaluate(N).toNonPremultipliedRenderColor(null).toArray()],"to-hsla":[Vd(fa,4),[ed],(N,[p])=>p.evaluate(N).toNonPremultipliedRenderColor(null).toHslaArray()],rgb:[ed,[fa,fa,fa],ax],rgba:[ed,[fa,fa,fa,fa],ax],hsl:[ed,[fa,fa,fa],J2],hsla:[ed,[fa,fa,fa,fa],J2],has:{type:pl,overloads:[[[Ao],(N,[p])=>Uk(p.evaluate(N),N.properties())],[[Ao,ag],(N,[p,_])=>Uk(p.evaluate(N),_.evaluate(N))]]},get:{type:Wo,overloads:[[[Ao],(N,[p])=>by(p.evaluate(N),N.properties())],[[Ao,ag],(N,[p,_])=>by(p.evaluate(N),_.evaluate(N))]]},"feature-state":[Wo,[Ao],(N,[p])=>by(p.evaluate(N),N.featureState||{})],properties:[ag,[],N=>N.properties()],"geometry-type":[Ao,[],N=>N.geometryType()],worldview:[Ao,[],N=>N.globals.worldview||""],"is-active-floor":[pl,_y(Ao),(N,p)=>{if(!(N.globals&&N.globals.activeFloors&&N.globals.activeFloors.size>0))return!1;if(p.length===0)return!0;const _=N.globals.activeFloors;return p.some(A=>{const M=A.evaluate(N);return _.has(M)})}],id:[Wo,[],N=>N.id()],zoom:[fa,[],N=>N.globals.zoom],pitch:[fa,[],N=>N.globals.pitch||0],"distance-from-center":[fa,[],N=>N.distanceFromCenter()],"measure-light":[fa,[Ao],(N,[p])=>N.measureLight(p.evaluate(N))],"heatmap-density":[fa,[],N=>N.globals.heatmapDensity||0],"line-progress":[fa,[],N=>N.globals.lineProgress||0],"raster-value":[fa,[],N=>N.globals.rasterValue||0],"raster-particle-speed":[fa,[],N=>N.globals.rasterParticleSpeed||0],"sky-radial-progress":[fa,[],N=>N.globals.skyRadialProgress||0],accumulated:[Wo,[],N=>N.globals.accumulated===void 0?null:N.globals.accumulated],"+":[fa,_y(fa),(N,p)=>{let _=0;for(const A of p)_+=A.evaluate(N);return _}],"*":[fa,_y(fa),(N,p)=>{let _=1;for(const A of p)_*=A.evaluate(N);return _}],"-":{type:fa,overloads:[[[fa,fa],(N,[p,_])=>p.evaluate(N)-_.evaluate(N)],[[fa],(N,[p])=>-p.evaluate(N)]]},"/":[fa,[fa,fa],(N,[p,_])=>p.evaluate(N)/_.evaluate(N)],"%":[fa,[fa,fa],(N,[p,_])=>p.evaluate(N)%_.evaluate(N)],ln2:[fa,[],()=>Math.LN2],pi:[fa,[],()=>Math.PI],e:[fa,[],()=>Math.E],"^":[fa,[fa,fa],(N,[p,_])=>Math.pow(p.evaluate(N),_.evaluate(N))],sqrt:[fa,[fa],(N,[p])=>Math.sqrt(p.evaluate(N))],log10:[fa,[fa],(N,[p])=>Math.log(p.evaluate(N))/Math.LN10],ln:[fa,[fa],(N,[p])=>Math.log(p.evaluate(N))],log2:[fa,[fa],(N,[p])=>Math.log2(p.evaluate(N))],sin:[fa,[fa],(N,[p])=>Math.sin(p.evaluate(N))],cos:[fa,[fa],(N,[p])=>Math.cos(p.evaluate(N))],tan:[fa,[fa],(N,[p])=>Math.tan(p.evaluate(N))],asin:[fa,[fa],(N,[p])=>Math.asin(p.evaluate(N))],acos:[fa,[fa],(N,[p])=>Math.acos(p.evaluate(N))],atan:[fa,[fa],(N,[p])=>Math.atan(p.evaluate(N))],min:[fa,_y(fa),(N,p)=>Math.min(...p.map(_=>_.evaluate(N)))],max:[fa,_y(fa),(N,p)=>Math.max(...p.map(_=>_.evaluate(N)))],abs:[fa,[fa],(N,[p])=>Math.abs(p.evaluate(N))],round:[fa,[fa],(N,[p])=>{const _=p.evaluate(N);return _<0?-Math.round(-_):Math.round(_)}],floor:[fa,[fa],(N,[p])=>Math.floor(p.evaluate(N))],ceil:[fa,[fa],(N,[p])=>Math.ceil(p.evaluate(N))],"filter-==":[pl,[Ao,Wo],(N,[p,_])=>N.properties()[p.value]===_.value],"filter-id-==":[pl,[Wo],(N,[p])=>N.id()===p.value],"filter-type-==":[pl,[Ao],(N,[p])=>N.geometryType()===p.value],"filter-<":[pl,[Ao,Wo],(N,[p,_])=>{const A=N.properties()[p.value],M=_.value;return typeof A==typeof M&&A{const _=N.id(),A=p.value;return typeof _==typeof A&&_":[pl,[Ao,Wo],(N,[p,_])=>{const A=N.properties()[p.value],M=_.value;return typeof A==typeof M&&A>M}],"filter-id->":[pl,[Wo],(N,[p])=>{const _=N.id(),A=p.value;return typeof _==typeof A&&_>A}],"filter-<=":[pl,[Ao,Wo],(N,[p,_])=>{const A=N.properties()[p.value],M=_.value;return typeof A==typeof M&&A<=M}],"filter-id-<=":[pl,[Wo],(N,[p])=>{const _=N.id(),A=p.value;return typeof _==typeof A&&_<=A}],"filter->=":[pl,[Ao,Wo],(N,[p,_])=>{const A=N.properties()[p.value],M=_.value;return typeof A==typeof M&&A>=M}],"filter-id->=":[pl,[Wo],(N,[p])=>{const _=N.id(),A=p.value;return typeof _==typeof A&&_>=A}],"filter-has":[pl,[Wo],(N,[p])=>p.value in N.properties()],"filter-has-id":[pl,[],N=>N.id()!==null&&N.id()!==void 0],"filter-type-in":[pl,[Vd(Ao)],(N,[p])=>p.value.includes(N.geometryType())],"filter-id-in":[pl,[Vd(Wo)],(N,[p])=>p.value.includes(N.id())],"filter-in-small":[pl,[Ao,Vd(Wo)],(N,[p,_])=>_.value.includes(N.properties()[p.value])],"filter-in-large":[pl,[Ao,Vd(Wo)],(N,[p,_])=>function(A,M,F,z){for(;F<=z;){const H=F+z>>1;if(M[H]===A)return!0;M[H]>A?z=H-1:F=H+1}return!1}(N.properties()[p.value],_.value,0,_.value.length-1)],all:{type:pl,overloads:[[[pl,pl],(N,[p,_])=>p.evaluate(N)&&_.evaluate(N)],[_y(pl),(N,p)=>{for(const _ of p)if(!_.evaluate(N))return!1;return!0}]]},any:{type:pl,overloads:[[[pl,pl],(N,[p,_])=>p.evaluate(N)||_.evaluate(N)],[_y(pl),(N,p)=>{for(const _ of p)if(_.evaluate(N))return!0;return!1}]]},"!":[pl,[pl],(N,[p])=>!p.evaluate(N)],"is-supported-script":[pl,[Ao],(N,[p])=>{const _=N.globals&&N.globals.isSupportedScript;return!_||_(p.evaluate(N))}],upcase:[Ao,[Ao],(N,[p])=>p.evaluate(N).toUpperCase()],downcase:[Ao,[Ao],(N,[p])=>p.evaluate(N).toLowerCase()],concat:[Ao,_y(Wo),(N,p)=>p.map(_=>np(_.evaluate(N))).join("")],split:[Vd(Ao),[Ao,Ao],(N,[p,_])=>p.evaluate(N).split(_.evaluate(N))],in:[pl,[Wo,Wo],(N,[p,_])=>{const A=p.evaluate(N),M=_.evaluate(N);return M!=null&&(ij(A,M),M.includes(A))}],"index-of":{type:fa,overloads:[[[Wo,Wo],(N,[p,_])=>{const A=p.evaluate(N),M=_.evaluate(N);return ij(A,M),M.indexOf(A)}],[[Wo,Wo,fa],(N,[p,_,A])=>{const M=p.evaluate(N),F=_.evaluate(N),z=A.evaluate(N);return ij(M,F),F.indexOf(M,z)}]]},"resolved-locale":[Ao,[q0],(N,[p])=>p.evaluate(N).resolvedLocale()],random:[fa,[fa,fa,Wo],(N,p)=>{const[_,A,M]=p.map(z=>z.evaluate(N));if(_>A||_===A)return _;let F;if(typeof M=="string")F=function(z){let H=0;if(z.length===0)return H;for(let Z=0;ZJSON.stringify(xe)).join(", ")}, but found ${JSON.stringify(fe)} instead.`);return fe}catch(fe){const xe=fe;return this._warningHistory[xe.message]||(this._warningHistory[xe.message]=!0,typeof console<"u"&&console.warn(`Failed to evaluate expression "${JSON.stringify(this.expression.serialize())}". ${xe.message}`)),this._defaultValue}}}function Vv(N){return Array.isArray(N)&&N.length>0&&typeof N[0]=="string"&&Object.hasOwn(zb,N[0])}function W0(N,p,_,A,M){const F=new lo(zb,[],p?function(H){const Z={color:ed,string:Ao,number:fa,enum:Ao,boolean:pl,formatted:yh,resolvedImage:uf,object:ag};return H.type==="array"?Vd(Z[H.value]||Wo,H.length):Z[H.type]}(p):void 0,void 0,void 0,_,A,M),z=F.parse(N,void 0,void 0,void 0,p&&p.type==="string"?{typeAnnotation:"coerce"}:void 0);return z?G1(new qv(z,p,_,A,M)):lp(F.errors)}class G_{constructor(p,_,A,M){this.kind=p,this._styleExpression=_,this.isLightConstant=A,this.isLineProgressConstant=M,this.isStateDependent=p!=="constant"&&!H0(_.expression),this.configDependencies=Bb(_.expression),this.isIndoorDependent=$x(_.expression)}evaluateWithoutErrorHandling(p,_,A,M,F,z){return this._styleExpression.evaluateWithoutErrorHandling(p,_,A,M,F,z)}evaluate(p,_,A,M,F,z,H){return this._styleExpression.evaluate(p,_,A,M,F,z,void 0,void 0,H)}}class cg{constructor(p,_,A,M,F,z){this.kind=p,this.zoomStops=A,this._styleExpression=_,this.isStateDependent=p!=="camera"&&!H0(_.expression),this.isIndoorDependent=$x(_.expression),this.isLightConstant=F,this.isLineProgressConstant=z,this.configDependencies=Bb(_.expression),this.interpolationType=M}evaluateWithoutErrorHandling(p,_,A,M,F,z){return this._styleExpression.evaluateWithoutErrorHandling(p,_,A,M,F,z)}evaluate(p,_,A,M,F,z){return this._styleExpression.evaluate(p,_,A,M,F,z)}interpolationFactor(p,_,A){return this.interpolationType?vc.interpolationFactor(this.interpolationType,p,_,A):0}}function K0(N,p,_,A,M){if((N=W0(N,p,_,A,M)).result==="error")return N;const F=N.value.expression,z=$1(F);if(!z&&!Xy(p))return lp([new Ro("","data expressions not supported")]);const H=zx(F,["zoom","pitch","distance-from-center"]);if(!H&&!oj(p))return lp([new Ro("","zoom expressions not supported")]);const Z=zx(F,["measure-light"]);if(!Z&&!qk(p))return lp([new Ro("","measure-light expression not supported")]);const se=zx(F,["line-progress"]);if(!se&&!function(be){return H_(be.expression,"line-progress")}(p))return lp([new Ro("","line-progress expression not supported")]);const fe=p.expression&&p.expression.relaxZoomRestriction,xe=up(F);return xe||H||fe?xe instanceof Ro?lp([xe]):xe instanceof vc&&!Qy(p)?lp([new Ro("",'"interpolate" expressions cannot be used with this property')]):G1(xe?new cg(z&&se?"camera":"composite",N.value,xe.labels,xe instanceof vc?xe.interpolation:void 0,Z,se):new G_(z&&se?"constant":"source",N.value,Z,se)):lp([new Ro("",'"zoom" expression may only be used as input to a top-level "step" or "interpolate" expression, or in the properties of atmosphere.')])}class Jy{constructor(p,_){this._parameters=p,this._specification=_,Object.assign(this,Ux(this._parameters,this._specification))}static deserialize(p){return new Jy(p._parameters,p._specification)}static serialize(p){return{_parameters:p._parameters,_specification:p._specification}}}function up(N){let p=null;if(N instanceof Mp)p=up(N.result);else if(N instanceof $m){for(const _ of N.args)if(p=up(_),p)break}else(N instanceof bi||N instanceof vc)&&N.input instanceof rp&&N.input.name==="zoom"&&(p=N);return p instanceof Ro||N.eachChild(_=>{const A=up(_);A instanceof Ro?p=A:p&&A&&p!==A&&(p=new Ro("",'Only one zoom-based "step" or "interpolate" subexpression may be used in an expression.'))}),p}class Hv{constructor(p,_,A){if(this.boxSeen=new Uint32Array(0),this.circleSeen=new Uint32Array(0),this.generation=0,p instanceof ArrayBuffer){const M=new Int32Array(p);this.width=M[0],this.height=M[1],this.xCellCount=M[2],this.yCellCount=M[3],this.boxUid=M[4],this.circleUid=M[5];const F=this.xCellCount*this.yCellCount,z=[];for(let fe=0;fethis.width||M<0||_>this.height)return z;const H=this._nextGen(),{boxCells:Z,circleCells:se,boxKeys:fe,circleKeys:xe,bboxes:be,circles:Te,boxSeen:De,circleSeen:Ue,xCellCount:Ye}=this,st=this._xCell(p),ot=this._yCell(_),mt=this._xCell(A),lt=this._yCell(M);for(let yt=st;yt<=mt;yt++)for(let Nt=ot;Nt<=lt;Nt++){const as=Ye*Nt+yt,Et=Z[as];if(Et)for(let Jt=0;Jt=Gs&&M>=pn&&(!F||F(fe[ns]))&&z.push({key:fe[ns],x1:Gs,y1:pn,x2:cn,y2:jn})}const $t=se[as];if($t)for(let Jt=0;Jt<$t.length;Jt++){const ns=$t[Jt];if(Ue[ns]===H)continue;Ue[ns]=H;const Ls=3*ns,Gs=Te[Ls],pn=Te[Ls+1],cn=Te[Ls+2];!this._circleAndRectCollide(Gs,pn,cn,p,_,A,M)||F&&!F(xe[ns])||z.push({key:xe[ns],x1:Gs-cn,y1:pn-cn,x2:Gs+cn,y2:pn+cn})}}return z}queryKeys(p,_,A,M,F){const z=[];if(A<0||p>this.width||M<0||_>this.height)return z;const H=this._nextGen(),{boxCells:Z,boxKeys:se,bboxes:fe,boxSeen:xe,xCellCount:be,xScale:Te,yScale:De}=this,Ue=this._xCell(p),Ye=this._yCell(_),st=this._xCell(A),ot=this._yCell(M);for(let mt=Ue;mt<=st;mt++)for(let lt=Ye;lt<=ot;lt++){if(F&&!F(mt/Te,lt/De,(mt+1)/Te,(lt+1)/De))continue;const yt=Z[be*lt+mt];if(yt)for(let Nt=0;Nt=$t&&M>=Jt)&&z.push(se[as])}}return z}hitTest(p,_,A,M,F){if(A<0||p>this.width||M<0||_>this.height)return!1;const z=this._nextGen(),{boxCells:H,circleCells:Z,boxKeys:se,circleKeys:fe,bboxes:xe,circles:be,boxSeen:Te,circleSeen:De,xCellCount:Ue}=this,Ye=this._xCell(p),st=this._yCell(_),ot=this._xCell(A),mt=this._yCell(M);for(let lt=Ye;lt<=ot;lt++)for(let yt=st;yt<=mt;yt++){const Nt=Ue*yt+lt,as=H[Nt];if(as)for(let $t=0;$t=xe[ns]&&M>=xe[ns+1]&&(!F||F(se[Jt])))return!0}const Et=Z[Nt];if(Et)for(let $t=0;$tthis.width||Z<0||z>this.height)return!1;const se=this._nextGen(),{boxCells:fe,circleCells:xe,boxKeys:be,circleKeys:Te,bboxes:De,circles:Ue,boxSeen:Ye,circleSeen:st,xCellCount:ot}=this,mt=this._xCell(F),lt=this._yCell(z),yt=this._xCell(H),Nt=this._yCell(Z);for(let as=mt;as<=yt;as++)for(let Et=lt;Et<=Nt;Et++){const $t=ot*Et+as,Jt=fe[$t];if(Jt)for(let Ls=0;Ls>>0,this.generation===0&&(this.boxSeen.fill(0),this.circleSeen.fill(0),this.generation=1),this.generation}_circlesCollide(p,_,A,M,F,z){const H=M-p,Z=F-_,se=A+z;return se*se>H*H+Z*Z}_circleAndRectCollide(p,_,A,M,F,z,H){const Z=(z-M)/2,se=Math.abs(p-(M+Z));if(se>Z+A)return!1;const fe=(H-F)/2,xe=Math.abs(_-(F+fe));if(xe>fe+A)return!1;if(se<=Z||xe<=fe)return!0;const be=se-Z,Te=xe-fe;return be*be+Te*Te<=A*A}}const eN={};function oa(N,p,_={}){Object.defineProperty(N,"_classRegistryKey",{value:p,writable:!1}),eN[p]={klass:N,omit:_.omit||[]}}oa(Object,"Object"),oa(Hv,"Grid"),delete xs.prototype.constructor,oa(Ci,"Color"),oa(vu,"Formatted"),oa(Bm,"FormattedSection"),oa(vh,"ResolvedImage"),oa(Jy,"StylePropertyFunction"),oa(qv,"StyleExpression",{omit:["_evaluator"]}),oa(_d,"ImageId"),oa(Rh,"ImageVariant"),oa(cg,"ZoomDependentExpression"),oa(G_,"ZoomConstantExpression"),oa(rp,"CompoundExpression",{omit:["_evaluate"]});for(const N in zb)eN[zb[N]._classRegistryKey]||oa(zb[N],`Expression${N}`);function M3(N){return N&&(N instanceof ArrayBuffer||N.constructor&&N.constructor.name==="ArrayBuffer")}const tN={Error,TypeError,RangeError,SyntaxError,ReferenceError,URIError,EvalError},dg=new Set(["message","stack","cause","errors","name","class"]);function Gv(N,p){if(N===null)return null;const _=typeof N;if(_!=="object")return _==="bigint"?{$name:"BigInt",value:N.toString()}:N;if(Array.isArray(N)){const z=N.length,H=[];H.length=z;for(let Z=0;Zfe!==z).map(fe=>Gv(fe,p)));const se=z;for(const fe in se)Object.hasOwn(se,fe)&&(dg.has(fe)||(Z[fe]=Gv(se[fe],p)));return Z}const A=N.constructor||Object,M=A._classRegistryKey;if(!M)throw new Error(`Can't serialize object of unregistered class "${A.name}".`);const F=A.serialize?A.serialize(N,p):{};if(!A.serialize){const z=eN[M].omit,H=N;for(const Z in H)Object.hasOwn(H,Z)&&(z.includes(Z)||(F[Z]=Gv(H[Z],p)))}if(F.$name)throw new Error("$name property is reserved for worker serialization logic.");return M!=="Object"&&(F.$name=M),F}function qx(N){if(N===null||typeof N!="object")return N;if(Array.isArray(N)){for(let M=0;MN>=1536&&N<=1791,jm=N=>N>=1872&&N<=1919,P3=N=>N>=2208&&N<=2303,YT=N=>N>=11904&&N<=12031,A9=N=>N>=12032&&N<=12255,E9=N=>N>=12272&&N<=12287,Hk=N=>N>=12288&&N<=12351,BC=N=>N>=12352&&N<=12447,$C=N=>N>=12448&&N<=12543,Y0=N=>N>=12544&&N<=12591,ZT=N=>N>=12704&&N<=12735,I3=N=>N>=12736&&N<=12783,$b=N=>N>=12784&&N<=12799,Gk=N=>N>=12800&&N<=13055,lj=N=>N>=13056&&N<=13311,Wk=N=>N>=13312&&N<=19903,UC=N=>N>=19968&&N<=40959,qC=N=>N>=40960&&N<=42127,B6=N=>N>=42128&&N<=42191,L3=N=>N>=44032&&N<=55215,$6=N=>N>=63744&&N<=64255,XT=N=>N>=64336&&N<=65023,U6=N=>N>=65040&&N<=65055,VC=N=>N>=65072&&N<=65103,T9=N=>N>=65104&&N<=65135,q6=N=>N>=65136&&N<=65279,oe=N=>N>=65280&&N<=65519;function de(N){for(const p of N)if(et(p.charCodeAt(0)))return!0;return!1}function Oe(N){return!(sN(N)||jm(N)||P3(N)||XT(N)||q6(N))}function et(N){return!(N!==746&&N!==747&&(N<4352||!(ZT(N)||Y0(N)||VC(N)&&!(N>=65097&&N<=65103)||$6(N)||lj(N)||YT(N)||I3(N)||!(!Hk(N)||N>=12296&&N<=12305||N>=12308&&N<=12319||N===12336)||Wk(N)||UC(N)||Gk(N)||(p=>p>=12592&&p<=12687)(N)||(p=>p>=43360&&p<=43391)(N)||(p=>p>=55216&&p<=55295)(N)||(p=>p>=4352&&p<=4607)(N)||L3(N)||BC(N)||E9(N)||(p=>p>=12688&&p<=12703)(N)||A9(N)||$b(N)||$C(N)&&N!==12540||!(!oe(N)||N===65288||N===65289||N===65293||N>=65306&&N<=65310||N===65339||N===65341||N===65343||N>=65371&&N<=65503||N===65507||N>=65512&&N<=65519)||!(!T9(N)||N>=65112&&N<=65118||N>=65123&&N<=65126)||(p=>p>=5120&&p<=5759)(N)||(p=>p>=6320&&p<=6399)(N)||U6(N)||(p=>p>=19904&&p<=19967)(N)||qC(N)||B6(N))))}function dt(N){return!(et(N)||function(p){return!!((_=>_>=128&&_<=255)(p)&&(p===167||p===169||p===174||p===177||p===188||p===189||p===190||p===215||p===247)||(_=>_>=8192&&_<=8303)(p)&&(p===8214||p===8224||p===8225||p===8240||p===8241||p===8251||p===8252||p===8258||p===8263||p===8264||p===8265||p===8273)||(_=>_>=8448&&_<=8527)(p)||(_=>_>=8528&&_<=8591)(p)||(_=>_>=8960&&_<=9215)(p)&&(p>=8960&&p<=8967||p>=8972&&p<=8991||p>=8996&&p<=9e3||p===9003||p>=9085&&p<=9114||p>=9150&&p<=9165||p===9167||p>=9169&&p<=9179||p>=9186&&p<=9215)||(_=>_>=9216&&_<=9279)(p)&&p!==9251||(_=>_>=9280&&_<=9311)(p)||(_=>_>=9312&&_<=9471)(p)||(_=>_>=9632&&_<=9727)(p)||(_=>_>=9728&&_<=9983)(p)&&!(p>=9754&&p<=9759)||(_=>_>=11008&&_<=11263)(p)&&(p>=11026&&p<=11055||p>=11088&&p<=11097||p>=11192&&p<=11243)||Hk(p)||$C(p)||(_=>_>=57344&&_<=63743)(p)||VC(p)||T9(p)||oe(p)||p===8734||p===8756||p===8757||p>=9984&&p<=10087||p>=10102&&p<=10131||p===65532||p===65533)}(N))}function Ot(N){return N>=1424&&N<=2303||XT(N)||q6(N)}function Ks(N,p){return!(!p&&Ot(N)||N>=2304&&N<=3583||N>=3840&&N<=4255||(_=>_>=6016&&_<=6143)(N))}function fr(N){for(const p of N)if(Ot(p.charCodeAt(0)))return!0;return!1}const $r={unavailable:"unavailable",deferred:"deferred",loading:"loading",parsing:"parsing",parsed:"parsed",loaded:"loaded",error:"error"};let ui=null,Pi=$r.unavailable,gl=null;const Zi=function(N){N&&(Pi=$r.error),ui&&ui(N)};function Kh(){mh.fire(new Bl("pluginStateChange",{pluginStatus:Pi,pluginURL:gl}))}const mh=new Jc,wy=function(){return Pi},W_=function(){if(Pi!==$r.deferred||!gl)throw new Error("rtl-text-plugin cannot be downloaded unless a pluginURL is specified");Pi=$r.loading,Kh(),gl&&Qr({url:gl}).then(()=>{Pi=$r.loaded,Kh()}).catch(N=>{Zi(N)})},Ur={applyArabicShaping:null,processBidirectionalText:null,processStyledBidirectionalText:null,isLoaded:()=>Pi===$r.loaded||Ur.applyArabicShaping!=null,isLoading:()=>Pi===$r.loading,setState(N){Pi=N.pluginStatus,gl=N.pluginURL},isParsing:()=>Pi===$r.parsing,isParsed:()=>Pi===$r.parsed,getPluginURL:()=>gl};class Kn{constructor(p,_){this.zoom=p,_?(this.now=_.now,this.fadeDuration=_.fadeDuration,this.transition=_.transition,this.pitch=_.pitch,this.brightness=_.brightness,this.worldview=_.worldview,this.activeFloors=_.activeFloors):(this.now=0,this.fadeDuration=0,this.transition={},this.pitch=0,this.brightness=0)}isSupportedScript(p){return function(_,A){for(const M of _)if(!Ks(M.charCodeAt(0),A))return!1;return!0}(p,Ur.isLoaded())}}class ia{constructor(p,_,A,M,F){this.property=p,this.value=_,this.expression=function(z,H,Z,se,fe){if(cp(z))return new Jy(z,H);if(Vv(z)||Array.isArray(z)&&z.length>0){const xe=K0(z,H,Z,se,fe);if(xe.result==="error")throw new Error(xe.value.map(be=>`${be.key}: ${be.message}`).join(", "));return xe.value}{let xe=z;return typeof z=="string"&&H.type==="color"&&(xe=Ci.parse(z)),{kind:"constant",configDependencies:new Set,isIndoorDependent:!1,evaluate:()=>xe}}}(_===void 0?p.specification.default:_,p.specification,A,M,F)}isIndoorDependent(){return this.expression.isIndoorDependent}isDataDriven(){return this.expression.kind==="source"||this.expression.kind==="composite"}possiblyEvaluate(p,_,A,M){return this.property.possiblyEvaluate(this,p,_,A,M)}}class Qi{constructor(p,_,A,M){this.property=p,this.value=new ia(p,void 0,_,A,M)}transitioned(p,_){return new td(this.property,this.value,_,{...p.transition,...this.transition},p.now)}untransitioned(){return new td(this.property,this.value,null,{},0)}}class xl{constructor(p,_,A,M){this._properties=p,this._values=Object.create(p.defaultTransitionablePropertyValues),this._scope=_,this._options=A,this._iconImageUseTheme=M,this._isIndoorDependent=!1,this.configDependencies=new Set}getValue(p){return Ul(this._values[p].value.value)}setValue(p,_){Object.hasOwn(this._values,p)||(this._values[p]=new Qi(this._values[p].property,this._scope,this._options,this._iconImageUseTheme)),this._values[p].value=new ia(this._values[p].property,_===null?void 0:Ul(_),this._scope,this._options,this._iconImageUseTheme),this._values[p].value.expression.configDependencies&&(this.configDependencies=new Set([...this.configDependencies,...this._values[p].value.expression.configDependencies]),this._isIndoorDependent=this._isIndoorDependent||this._values[p].value.isIndoorDependent())}setTransitionOrValue(p,_){_&&(this._options=_);const A=this._properties.properties;if(p)for(const M in p){const F=p[M];if(M.endsWith("-transition")){const z=M.slice(0,-11);A[z]&&this.setTransition(z,F)}else Object.hasOwn(A,M)&&this.setValue(M,F)}}getTransition(p){return Ul(this._values[p].transition)}setTransition(p,_){Object.hasOwn(this._values,p)||(this._values[p]=new Qi(this._values[p].property)),this._values[p].transition=Ul(_)||void 0}serialize(){const p={};for(const _ of Object.keys(this._values)){const A=this.getValue(_);A!==void 0&&(p[_]=A);const M=this.getTransition(_);M!==void 0&&(p[`${_}-transition`]=M)}return p}transitioned(p,_){const A=new Cc(this._properties);for(const M of Object.keys(this._values))A._values[M]=this._values[M].transitioned(p,_._values[M]);return A}untransitioned(){const p=new Cc(this._properties);for(const _ of Object.keys(this._values))p._values[_]=this._values[_].untransitioned();return p}isIndoorDependent(){return this._isIndoorDependent}}class td{constructor(p,_,A,M,F){const z=M.delay||0,H=M.duration||0;F=F||0,this.property=p,this.value=_,this.begin=F+z,this.end=this.begin+H,p.specification.transition&&(M.delay||M.duration)&&(this.prior=A)}possiblyEvaluate(p,_,A){const M=p.now||0,F=this.value.possiblyEvaluate(p,_,A),z=this.prior;if(z){if(M>this.end)return this.prior=null,F;if(this.value.isDataDriven())return this.prior=null,F;if(M":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_stop":{"type":"array","minimum":0,"maximum":24,"length":2,"value":["number","color"]},"fog":{"range":{"type":"array","default":[0.5,10],"minimum":-20,"maximum":20,"length":2,"value":"number","expression":{"interpolated":1,"parameters":["measure-light","zoom"],"relaxZoomRestriction":1},"transition":1},"color":{"type":"color","default":"#ffffff","expression":{"interpolated":1,"parameters":["measure-light","zoom"],"relaxZoomRestriction":1},"transition":1,"use-theme":1},"high-color":{"type":"color","default":"#245cdf","expression":{"interpolated":1,"parameters":["measure-light","zoom"],"relaxZoomRestriction":1},"transition":1,"use-theme":1},"space-color":{"type":"color","default":["interpolate",["linear"],["zoom"],4,"#010b19",7,"#367ab9"],"expression":{"interpolated":1,"parameters":["measure-light","zoom"],"relaxZoomRestriction":1},"transition":1,"use-theme":1},"horizon-blend":{"type":"number","default":["interpolate",["linear"],["zoom"],4,0.2,7,0.1],"minimum":0,"maximum":1,"expression":{"interpolated":1,"parameters":["measure-light","zoom"],"relaxZoomRestriction":1},"transition":1},"star-intensity":{"type":"number","default":["interpolate",["linear"],["zoom"],5,0.35,6,0],"minimum":0,"maximum":1,"expression":{"interpolated":1,"parameters":["measure-light","zoom"],"relaxZoomRestriction":1},"transition":1},"vertical-range":{"type":"array","default":[0,0],"minimum":0,"length":2,"value":"number","expression":{"interpolated":1,"parameters":["measure-light","zoom"],"relaxZoomRestriction":1},"transition":1}},"snow":{"density":{"type":"number","default":["interpolate",["linear"],["zoom"],11,0,13,0.85],"minimum":0,"maximum":1,"expression":{"interpolated":1,"parameters":["measure-light","zoom"],"relaxZoomRestriction":1},"transition":1},"intensity":{"type":"number","default":1,"minimum":0,"maximum":1,"expression":{"interpolated":1,"parameters":["measure-light","zoom"],"relaxZoomRestriction":1},"transition":1},"color":{"type":"color","default":"#ffffff","expression":{"interpolated":1,"parameters":["measure-light","zoom"],"relaxZoomRestriction":1},"transition":1,"use-theme":1},"opacity":{"type":"number","default":1,"minimum":0,"maximum":1,"expression":{"interpolated":1,"parameters":["measure-light","zoom"],"relaxZoomRestriction":1},"transition":1},"vignette":{"type":"number","default":["interpolate",["linear"],["zoom"],11,0,13,0.3],"minimum":0,"maximum":1,"expression":{"interpolated":1,"parameters":["measure-light","zoom"],"relaxZoomRestriction":1},"transition":1},"vignette-color":{"type":"color","default":"#ffffff","expression":{"interpolated":1,"parameters":["measure-light","zoom"],"relaxZoomRestriction":1},"transition":1,"use-theme":1},"center-thinning":{"type":"number","default":0.4,"minimum":0,"maximum":1,"expression":{"interpolated":1,"parameters":["measure-light","zoom"],"relaxZoomRestriction":1},"transition":1},"direction":{"type":"array","default":[0,50],"minimum":0,"maximum":360,"length":2,"value":"number","expression":{"interpolated":1,"parameters":["measure-light","zoom"],"relaxZoomRestriction":1},"transition":1},"flake-size":{"type":"number","default":0.71,"minimum":0,"maximum":5,"expression":{"interpolated":1,"parameters":["measure-light","zoom"],"relaxZoomRestriction":1},"transition":1}},"rain":{"density":{"type":"number","default":["interpolate",["linear"],["zoom"],11,0,13,0.5],"minimum":0,"maximum":1,"expression":{"interpolated":1,"parameters":["measure-light","zoom"],"relaxZoomRestriction":1},"transition":1},"intensity":{"type":"number","default":1,"minimum":0,"maximum":1,"expression":{"interpolated":1,"parameters":["measure-light","zoom"],"relaxZoomRestriction":1},"transition":1},"color":{"type":"color","default":["interpolate",["linear"],["measure-light","brightness"],0,"#03113d",0.3,"#a8adbc"],"expression":{"interpolated":1,"parameters":["measure-light","zoom"],"relaxZoomRestriction":1},"transition":1,"use-theme":1},"opacity":{"type":"number","default":["interpolate",["linear"],["measure-light","brightness"],0,0.88,1,0.7],"minimum":0,"maximum":1,"expression":{"interpolated":1,"parameters":["measure-light","zoom"],"relaxZoomRestriction":1},"transition":1},"vignette":{"type":"number","default":["interpolate",["linear"],["zoom"],11,0,13,1],"minimum":0,"maximum":1,"expression":{"interpolated":1,"parameters":["measure-light","zoom"],"relaxZoomRestriction":1},"transition":1},"vignette-color":{"type":"color","default":["interpolate",["linear"],["measure-light","brightness"],0,"#001736",0.3,"#464646"],"expression":{"interpolated":1,"parameters":["measure-light","zoom"],"relaxZoomRestriction":1},"transition":1,"use-theme":1},"center-thinning":{"type":"number","default":0.57,"minimum":0,"maximum":1,"expression":{"interpolated":1,"parameters":["measure-light","zoom"],"relaxZoomRestriction":1},"transition":1},"direction":{"type":"array","default":[0,80],"minimum":0,"maximum":360,"length":2,"value":"number","expression":{"interpolated":1,"parameters":["measure-light","zoom"],"relaxZoomRestriction":1},"transition":1},"droplet-size":{"type":"array","default":[2.6,18.2],"minimum":0,"maximum":50,"length":2,"value":"number","expression":{"interpolated":1,"parameters":["measure-light","zoom"],"relaxZoomRestriction":1},"transition":1},"distortion-strength":{"type":"number","default":0.7,"minimum":0,"maximum":1,"expression":{"interpolated":1,"parameters":["measure-light","zoom"],"relaxZoomRestriction":1},"transition":1}},"camera":{"camera-projection":{"type":"enum","default":"perspective","values":{"perspective":1,"orthographic":1}}},"colorTheme":{"data":{"type":"string","expression":1}},"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","expression":{"interpolated":1,"parameters":["zoom"]},"transition":1},"color":{"type":"color","default":"#ffffff","expression":{"interpolated":1,"parameters":["zoom"]},"transition":1,"use-theme":1},"intensity":{"type":"number","default":0.5,"minimum":0,"maximum":1,"expression":{"interpolated":1,"parameters":["zoom"]},"transition":1}},"projection":{"name":{"type":"enum","default":"mercator","values":{"albers":1,"equalEarth":1,"equirectangular":1,"lambertConformalConic":1,"mercator":1,"naturalEarth":1,"winkelTripel":1,"globe":1}},"center":{"type":"array","minimum":[-180,-90],"maximum":[180,90],"length":2,"value":"number"},"parallels":{"type":"array","minimum":[-90,-90],"maximum":[90,90],"length":2,"value":"number"}},"terrain":{"source":{"type":"string"},"exaggeration":{"type":"number","default":1,"minimum":0,"maximum":1000,"expression":{"interpolated":1,"parameters":["zoom"]},"transition":1}},"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,"expression":{"interpolated":1,"parameters":["feature","feature-state","measure-light","zoom"]},"transition":1,"property-type":"data-driven"},"fill-color":{"type":"color","default":"#000000","expression":{"interpolated":1,"parameters":["feature","feature-state","measure-light","zoom"]},"transition":1,"use-theme":1,"property-type":"data-driven"},"fill-outline-color":{"type":"color","expression":{"interpolated":1,"parameters":["feature","feature-state","measure-light","zoom"]},"transition":1,"use-theme":1,"property-type":"data-driven"},"fill-translate":{"type":"array","default":[0,0],"length":2,"value":"number","expression":{"interpolated":1,"parameters":["zoom"]},"transition":1},"fill-translate-anchor":{"type":"enum","default":"map","values":{"map":1,"viewport":1},"expression":{"parameters":["zoom"]}},"fill-pattern":{"type":"resolvedImage","expression":{"parameters":["feature","zoom"]},"property-type":"data-driven"},"fill-pattern-cross-fade":{"type":"number","default":0,"minimum":0,"maximum":1,"expression":{"interpolated":1,"parameters":["measure-light","zoom"]}},"fill-emissive-strength":{"type":"number","default":0,"minimum":0,"expression":{"interpolated":1,"parameters":["measure-light","zoom"]},"transition":1},"fill-z-offset":{"type":"number","default":0,"minimum":0,"expression":{"interpolated":1,"parameters":["feature","zoom"]},"transition":1,"property-type":"data-driven"},"fill-bridge-guard-rail-color":{"type":"color","default":"rgba(241, 236, 225, 255)","expression":{"interpolated":1,"parameters":["feature","measure-light","zoom"]},"transition":1,"use-theme":1,"property-type":"data-driven"},"fill-tunnel-structure-color":{"type":"color","default":"rgba(241, 236, 225, 255)","expression":{"interpolated":1,"parameters":["feature","measure-light","zoom"]},"transition":1,"use-theme":1,"property-type":"data-driven"}},"paint_fill-extrusion":{"fill-extrusion-opacity":{"type":"number","default":1,"minimum":0,"maximum":1,"expression":{"interpolated":1,"parameters":["zoom"]},"transition":1},"fill-extrusion-color":{"type":"color","default":"#000000","expression":{"interpolated":1,"parameters":["feature","feature-state","measure-light","zoom"]},"transition":1,"use-theme":1,"property-type":"data-driven"},"fill-extrusion-translate":{"type":"array","default":[0,0],"length":2,"value":"number","expression":{"interpolated":1,"parameters":["zoom"]},"transition":1},"fill-extrusion-translate-anchor":{"type":"enum","default":"map","values":{"map":1,"viewport":1},"expression":{"parameters":["zoom"]}},"fill-extrusion-pattern":{"type":"resolvedImage","expression":{"parameters":["feature","zoom"]},"property-type":"data-driven"},"fill-extrusion-pattern-cross-fade":{"type":"number","default":0,"minimum":0,"maximum":1,"expression":{"interpolated":1,"parameters":["measure-light","zoom"]}},"fill-extrusion-height":{"type":"number","default":0,"minimum":0,"expression":{"interpolated":1,"parameters":["feature","feature-state","zoom"]},"transition":1,"property-type":"data-driven"},"fill-extrusion-base":{"type":"number","default":0,"minimum":0,"expression":{"interpolated":1,"parameters":["feature","feature-state","zoom"]},"transition":1,"property-type":"data-driven"},"fill-extrusion-height-alignment":{"type":"enum","default":"flat","values":{"terrain":1,"flat":1}},"fill-extrusion-base-alignment":{"type":"enum","default":"terrain","values":{"terrain":1,"flat":1}},"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":1,"parameters":["zoom"]},"transition":1},"fill-extrusion-ambient-occlusion-radius":{"type":"number","default":3,"minimum":0,"expression":{"interpolated":1,"parameters":["zoom"]},"transition":1},"fill-extrusion-ambient-occlusion-wall-radius":{"type":"number","default":3,"minimum":0,"expression":{"interpolated":1,"parameters":["zoom"]},"transition":1},"fill-extrusion-ambient-occlusion-ground-radius":{"type":"number","default":3,"minimum":0,"expression":{"interpolated":1,"parameters":["zoom"]},"transition":1},"fill-extrusion-ambient-occlusion-ground-attenuation":{"type":"number","default":0.69,"minimum":0,"maximum":1,"expression":{"interpolated":1,"parameters":["zoom"]},"transition":1},"fill-extrusion-flood-light-color":{"type":"color","default":"#ffffff","expression":{"interpolated":1,"parameters":["measure-light","zoom"]},"transition":1,"use-theme":1},"fill-extrusion-flood-light-intensity":{"type":"number","default":0,"minimum":0,"maximum":1,"expression":{"interpolated":1,"parameters":["measure-light","zoom"]},"transition":1},"fill-extrusion-flood-light-wall-radius":{"type":"number","default":0,"minimum":0,"expression":{"interpolated":1,"parameters":["feature","feature-state"]},"transition":1,"property-type":"data-driven"},"fill-extrusion-flood-light-ground-radius":{"type":"number","default":0,"expression":{"interpolated":1,"parameters":["feature","feature-state"]},"transition":1,"property-type":"data-driven"},"fill-extrusion-flood-light-ground-attenuation":{"type":"number","default":0.69,"minimum":0,"maximum":1,"expression":{"interpolated":1,"parameters":["zoom"]},"transition":1},"fill-extrusion-vertical-scale":{"type":"number","default":1,"minimum":0,"expression":{"interpolated":1,"parameters":["zoom"]},"transition":1},"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":1},"fill-extrusion-front-cutoff":{"type":"array","default":[0,0,1],"minimum":[0,0,0],"maximum":[1,1,1],"length":3,"value":"number","expression":{"interpolated":1,"parameters":["zoom"]}},"fill-extrusion-emissive-strength":{"type":"number","default":0,"minimum":0,"expression":{"interpolated":1,"parameters":["feature-state","measure-light","zoom"]},"transition":1,"property-type":"data-driven"},"fill-extrusion-line-width":{"type":"number","default":0,"minimum":0,"expression":{"interpolated":1,"parameters":["feature","feature-state","measure-light","zoom"]},"transition":1,"property-type":"data-driven"},"fill-extrusion-cast-shadows":{"type":"boolean","default":true}},"paint_building":{"building-opacity":{"type":"number","default":1,"minimum":0,"maximum":1,"expression":{"interpolated":1,"parameters":["zoom"]},"transition":1},"building-ambient-occlusion-intensity":{"type":"number","default":0,"minimum":0,"maximum":1,"expression":{"parameters":[]},"transition":1},"building-ambient-occlusion-ground-intensity":{"type":"number","default":0,"minimum":0,"maximum":1,"expression":{"interpolated":1,"parameters":["zoom"]},"transition":1},"building-ambient-occlusion-ground-radius":{"type":"number","default":3,"minimum":0,"expression":{"interpolated":1,"parameters":["zoom"]},"transition":1},"building-ambient-occlusion-ground-attenuation":{"type":"number","default":0.69,"minimum":0,"maximum":1,"expression":{"interpolated":1,"parameters":["zoom"]},"transition":1},"building-vertical-scale":{"type":"number","default":1,"minimum":0,"expression":{"interpolated":1,"parameters":["zoom"]},"transition":1},"building-cast-shadows":{"type":"boolean","default":true},"building-color":{"type":"color","default":"rgba(193, 154, 127, 1)","expression":{"interpolated":1,"parameters":["feature","feature-state","measure-light"]},"use-theme":1,"property-type":"data-driven"},"building-emissive-strength":{"type":"number","default":0,"minimum":0,"maximum":5,"expression":{"interpolated":1,"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":1,"parameters":["measure-light","zoom"]}},"building-cutoff-fade-range":{"type":"number","default":0,"minimum":0,"maximum":1,"expression":1},"building-front-cutoff":{"type":"array","default":[0,0,1],"minimum":[0,0,0],"maximum":[1,1,1],"length":3,"value":"number","expression":{"interpolated":1,"parameters":["zoom"]}},"building-flood-light-color":{"type":"color","default":"#ffffff","expression":{"interpolated":1,"parameters":["measure-light","zoom"]},"transition":1,"use-theme":1},"building-flood-light-intensity":{"type":"number","default":0,"minimum":0,"maximum":1,"expression":{"interpolated":1,"parameters":["measure-light","zoom"]},"transition":1},"building-flood-light-ground-attenuation":{"type":"number","default":0.69,"minimum":0,"maximum":1,"expression":{"interpolated":1,"parameters":["zoom"]},"transition":1}},"paint_line":{"line-opacity":{"type":"number","default":1,"minimum":0,"maximum":1,"expression":{"interpolated":1,"parameters":["feature","feature-state","measure-light","zoom"]},"transition":1,"property-type":"data-driven"},"line-color":{"type":"color","default":"#000000","expression":{"interpolated":1,"parameters":["feature","feature-state","measure-light","zoom"]},"transition":1,"use-theme":1,"property-type":"data-driven"},"line-translate":{"type":"array","default":[0,0],"length":2,"value":"number","expression":{"interpolated":1,"parameters":["zoom"]},"transition":1},"line-translate-anchor":{"type":"enum","default":"map","values":{"map":1,"viewport":1},"expression":{"parameters":["zoom"]}},"line-width":{"type":"number","default":1,"minimum":0,"expression":{"interpolated":1,"parameters":["feature","feature-state","line-progress","measure-light","zoom"]},"transition":1,"property-type":"data-driven"},"line-gap-width":{"type":"number","default":0,"minimum":0,"expression":{"interpolated":1,"parameters":["feature","feature-state","measure-light","zoom"]},"transition":1,"property-type":"data-driven"},"line-offset":{"type":"number","default":0,"expression":{"interpolated":1,"parameters":["feature","feature-state","measure-light","zoom"]},"transition":1,"property-type":"data-driven"},"line-blur":{"type":"number","default":0,"minimum":0,"expression":{"interpolated":1,"parameters":["feature","feature-state","measure-light","zoom"]},"transition":1,"property-type":"data-driven"},"line-dasharray":{"type":"array","minimum":0,"value":"number","expression":{"parameters":["feature","zoom"]},"property-type":"data-driven"},"line-pattern":{"type":"resolvedImage","expression":{"parameters":["feature","zoom"]},"property-type":"data-driven"},"line-pattern-cross-fade":{"type":"number","default":0,"minimum":0,"maximum":1,"expression":{"interpolated":1,"parameters":["measure-light","zoom"]}},"line-gradient":{"type":"color","expression":{"interpolated":1,"parameters":["line-progress"]},"use-theme":1},"line-trim-offset":{"type":"array","default":[0,0],"minimum":[0,0],"maximum":[1,1],"length":2,"value":"number"},"line-trim-fade-range":{"type":"array","default":[0,0],"minimum":[0,0],"maximum":[1,1],"length":2,"value":"number","expression":{"interpolated":1,"parameters":["measure-light","zoom"]}},"line-trim-color":{"type":"color","default":"transparent","expression":{"interpolated":1,"parameters":["measure-light","zoom"]},"transition":1,"use-theme":1},"line-emissive-strength":{"type":"number","default":0,"minimum":0,"expression":{"interpolated":1,"parameters":["line-progress","measure-light","zoom"]},"transition":1,"property-type":"data-driven"},"line-border-width":{"type":"number","default":0,"minimum":0,"expression":{"interpolated":1,"parameters":["feature","feature-state","zoom"]},"transition":1,"property-type":"data-driven"},"line-border-color":{"type":"color","default":"rgba(0, 0, 0, 0)","expression":{"interpolated":1,"parameters":["feature","feature-state","zoom"]},"transition":1,"use-theme":1,"property-type":"data-driven"},"line-border-gradient":{"type":"color","expression":{"interpolated":1,"parameters":["line-progress"]},"use-theme":1},"line-occlusion-opacity":{"type":"number","default":0,"minimum":0,"maximum":1,"expression":{"interpolated":1,"parameters":["zoom"]},"transition":1},"line-blend-mode":{"type":"enum","default":"default","values":{"default":1,"multiply":1,"additive":1},"expression":{"parameters":["zoom"]}},"line-blend-additive-clamp":{"type":"number","default":0,"minimum":0,"expression":{"interpolated":1,"parameters":["zoom"]}},"line-cutout-depth":{"type":"number","default":0,"minimum":0,"expression":{"interpolated":1,"parameters":["zoom"]},"transition":1}},"paint_circle":{"circle-radius":{"type":"number","default":5,"minimum":0,"expression":{"interpolated":1,"parameters":["feature","feature-state","measure-light","zoom"]},"transition":1,"property-type":"data-driven"},"circle-color":{"type":"color","default":"#000000","expression":{"interpolated":1,"parameters":["feature","feature-state","measure-light","zoom"]},"transition":1,"use-theme":1,"property-type":"data-driven"},"circle-blur":{"type":"number","default":0,"expression":{"interpolated":1,"parameters":["feature","feature-state","measure-light","zoom"]},"transition":1,"property-type":"data-driven"},"circle-opacity":{"type":"number","default":1,"minimum":0,"maximum":1,"expression":{"interpolated":1,"parameters":["feature","feature-state","measure-light","zoom"]},"transition":1,"property-type":"data-driven"},"circle-translate":{"type":"array","default":[0,0],"length":2,"value":"number","expression":{"interpolated":1,"parameters":["zoom"]},"transition":1},"circle-translate-anchor":{"type":"enum","default":"map","values":{"map":1,"viewport":1},"expression":{"parameters":["zoom"]}},"circle-pitch-scale":{"type":"enum","default":"map","values":{"map":1,"viewport":1},"expression":{"parameters":["zoom"]}},"circle-pitch-alignment":{"type":"enum","default":"viewport","values":{"map":1,"viewport":1},"expression":{"parameters":["zoom"]}},"circle-stroke-width":{"type":"number","default":0,"minimum":0,"expression":{"interpolated":1,"parameters":["feature","feature-state","measure-light","zoom"]},"transition":1,"property-type":"data-driven"},"circle-stroke-color":{"type":"color","default":"#000000","expression":{"interpolated":1,"parameters":["feature","feature-state","measure-light","zoom"]},"transition":1,"use-theme":1,"property-type":"data-driven"},"circle-stroke-opacity":{"type":"number","default":1,"minimum":0,"maximum":1,"expression":{"interpolated":1,"parameters":["feature","feature-state","measure-light","zoom"]},"transition":1,"property-type":"data-driven"},"circle-emissive-strength":{"type":"number","default":0,"minimum":0,"expression":{"interpolated":1,"parameters":["measure-light","zoom"]},"transition":1}},"paint_heatmap":{"heatmap-radius":{"type":"number","default":30,"minimum":1,"expression":{"interpolated":1,"parameters":["feature","feature-state","measure-light","zoom"]},"transition":1,"property-type":"data-driven"},"heatmap-weight":{"type":"number","default":1,"minimum":0,"expression":{"interpolated":1,"parameters":["feature","feature-state","measure-light","zoom"]},"property-type":"data-driven"},"heatmap-intensity":{"type":"number","default":1,"minimum":0,"expression":{"interpolated":1,"parameters":["zoom"]},"transition":1},"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"],"expression":{"interpolated":1,"parameters":["heatmap-density"]},"use-theme":1},"heatmap-opacity":{"type":"number","default":1,"minimum":0,"maximum":1,"expression":{"interpolated":1,"parameters":["zoom"]},"transition":1}},"paint_symbol":{"icon-opacity":{"type":"number","default":1,"minimum":0,"maximum":1,"expression":{"interpolated":1,"parameters":["feature","feature-state","measure-light","zoom"]},"transition":1,"property-type":"data-driven","appearance":1},"icon-occlusion-opacity":{"type":"number","default":0,"minimum":0,"maximum":1,"expression":{"interpolated":1,"parameters":["feature","feature-state","measure-light","zoom"]},"transition":1,"property-type":"data-driven","appearance":1},"icon-emissive-strength":{"type":"number","default":1,"minimum":0,"expression":{"interpolated":1,"parameters":["feature-state","measure-light","zoom"]},"transition":1,"property-type":"data-driven","appearance":1},"text-emissive-strength":{"type":"number","default":1,"minimum":0,"expression":{"interpolated":1,"parameters":["feature-state","measure-light","zoom"]},"transition":1,"property-type":"data-driven","appearance":1},"icon-color":{"type":"color","default":"#000000","expression":{"interpolated":1,"parameters":["feature","feature-state","measure-light","zoom"]},"transition":1,"use-theme":1,"property-type":"data-driven","appearance":1},"icon-halo-color":{"type":"color","default":"rgba(0, 0, 0, 0)","expression":{"interpolated":1,"parameters":["feature","feature-state","measure-light","zoom"]},"transition":1,"use-theme":1,"property-type":"data-driven","appearance":1},"icon-halo-width":{"type":"number","default":0,"minimum":0,"expression":{"interpolated":1,"parameters":["feature","feature-state","measure-light","zoom"]},"transition":1,"property-type":"data-driven","appearance":1},"icon-halo-blur":{"type":"number","default":0,"minimum":0,"expression":{"interpolated":1,"parameters":["feature","feature-state","measure-light","zoom"]},"transition":1,"property-type":"data-driven","appearance":1},"icon-translate":{"type":"array","default":[0,0],"length":2,"value":"number","expression":{"interpolated":1,"parameters":["zoom"]},"transition":1,"appearance":1},"icon-translate-anchor":{"type":"enum","default":"map","values":{"map":1,"viewport":1},"expression":{"parameters":["zoom"]}},"icon-image-cross-fade":{"type":"number","default":0,"minimum":0,"maximum":1,"expression":{"interpolated":1,"parameters":["measure-light","zoom"]}},"text-opacity":{"type":"number","default":1,"minimum":0,"maximum":1,"expression":{"interpolated":1,"parameters":["feature","feature-state","measure-light","zoom"]},"transition":1,"property-type":"data-driven","appearance":1},"text-occlusion-opacity":{"type":"number","default":0,"minimum":0,"maximum":1,"expression":{"interpolated":1,"parameters":["feature","feature-state","measure-light","zoom"]},"transition":1,"property-type":"data-driven","appearance":1},"text-color":{"type":"color","default":"#000000","expression":{"interpolated":1,"parameters":["feature","feature-state","measure-light","zoom"]},"transition":1,"use-theme":1,"property-type":"data-driven","appearance":1,"overridable":1},"text-halo-color":{"type":"color","default":"rgba(0, 0, 0, 0)","expression":{"interpolated":1,"parameters":["feature","feature-state","measure-light","zoom"]},"transition":1,"use-theme":1,"property-type":"data-driven","appearance":1},"text-halo-width":{"type":"number","default":0,"minimum":0,"expression":{"interpolated":1,"parameters":["feature","feature-state","measure-light","zoom"]},"transition":1,"property-type":"data-driven","appearance":1},"text-halo-blur":{"type":"number","default":0,"minimum":0,"expression":{"interpolated":1,"parameters":["feature","feature-state","measure-light","zoom"]},"transition":1,"property-type":"data-driven","appearance":1},"text-translate":{"type":"array","default":[0,0],"length":2,"value":"number","expression":{"interpolated":1,"parameters":["zoom"]},"transition":1,"appearance":1},"text-translate-anchor":{"type":"enum","default":"map","values":{"map":1,"viewport":1},"expression":{"parameters":["zoom"]}},"icon-color-saturation":{"type":"number","default":0,"minimum":-1,"maximum":1,"expression":1},"icon-color-contrast":{"type":"number","default":0,"minimum":-1,"maximum":1,"expression":1},"icon-color-brightness-min":{"type":"number","default":0,"minimum":0,"maximum":1,"expression":1},"icon-color-brightness-max":{"type":"number","default":1,"minimum":0,"maximum":1,"expression":1},"symbol-z-offset":{"type":"number","default":0,"minimum":0,"expression":{"interpolated":1,"parameters":["feature","zoom"]},"transition":1,"property-type":"data-driven","appearance":1},"placement-priority":{"type":"number","default":0,"minimum":0,"expression":{"interpolated":1,"parameters":["distance-from-center","feature","feature-state","measure-light","pitch","zoom"]},"property-type":"data-driven","appearance":1},"placement-group":{"type":"string","expression":{"parameters":["distance-from-center","feature","feature-state","measure-light","pitch","zoom"]},"property-type":"data-driven","appearance":1}},"paint_raster":{"raster-opacity":{"type":"number","default":1,"minimum":0,"maximum":1,"expression":{"interpolated":1,"parameters":["zoom"]},"transition":1},"raster-color":{"type":"color","expression":{"interpolated":1,"parameters":["raster-value"]},"use-theme":1},"raster-color-mix":{"type":"array","default":[0.2126,0.7152,0.0722,0],"length":4,"value":"number","expression":{"interpolated":1,"parameters":["zoom"]},"transition":1},"raster-color-range":{"type":"array","length":2,"value":"number","expression":{"interpolated":1,"parameters":["zoom"]},"transition":1},"raster-color-scale":{"type":"enum","default":"linear","values":{"linear":1,"log":1},"expression":{"parameters":[]}},"raster-hue-rotate":{"type":"number","default":0,"expression":{"interpolated":1,"parameters":["zoom"]},"transition":1},"raster-brightness-min":{"type":"number","default":0,"minimum":0,"maximum":1,"expression":{"interpolated":1,"parameters":["zoom"]},"transition":1},"raster-brightness-max":{"type":"number","default":1,"minimum":0,"maximum":1,"expression":{"interpolated":1,"parameters":["zoom"]},"transition":1},"raster-saturation":{"type":"number","default":0,"minimum":-1,"maximum":1,"expression":{"interpolated":1,"parameters":["zoom"]},"transition":1},"raster-contrast":{"type":"number","default":0,"minimum":-1,"maximum":1,"expression":{"interpolated":1,"parameters":["zoom"]},"transition":1},"raster-resampling":{"type":"enum","default":"linear","values":{"linear":1,"nearest":1},"expression":{"parameters":["zoom"]}},"raster-fade-duration":{"type":"number","default":300,"minimum":0,"expression":{"interpolated":1,"parameters":["zoom"]}},"raster-emissive-strength":{"type":"number","default":0,"minimum":0,"expression":{"interpolated":1,"parameters":["measure-light","zoom"]},"transition":1},"raster-array-band":{"type":"string"},"raster-elevation":{"type":"number","default":0,"minimum":0,"expression":{"interpolated":1,"parameters":["zoom"]},"transition":1},"raster-elevation-reference":{"type":"enum","default":"sea","values":{"sea":1,"ground":1},"expression":1}},"paint_raster-particle":{"raster-particle-array-band":{"type":"string"},"raster-particle-count":{"type":"number","default":512,"minimum":1},"raster-particle-color":{"type":"color","expression":{"interpolated":1,"parameters":["raster-particle-speed"]},"use-theme":1},"raster-particle-max-speed":{"type":"number","default":1,"minimum":1},"raster-particle-speed-factor":{"type":"number","default":0.2,"minimum":0,"maximum":1,"expression":{"interpolated":1,"parameters":["zoom"]},"transition":1},"raster-particle-fade-opacity-factor":{"type":"number","default":0.98,"minimum":0,"maximum":1,"expression":{"interpolated":1,"parameters":["zoom"]},"transition":1},"raster-particle-reset-rate-factor":{"type":"number","default":0.8,"minimum":0,"maximum":1},"raster-particle-elevation":{"type":"number","default":0,"minimum":0,"expression":{"interpolated":1,"parameters":["zoom"]},"transition":1}},"paint_hillshade":{"hillshade-illumination-direction":{"type":"number","default":335,"minimum":0,"maximum":359,"expression":{"interpolated":1,"parameters":["zoom"]}},"hillshade-illumination-anchor":{"type":"enum","default":"viewport","values":{"map":1,"viewport":1},"expression":{"parameters":["zoom"]}},"hillshade-exaggeration":{"type":"number","default":0.5,"minimum":0,"maximum":1,"expression":{"interpolated":1,"parameters":["zoom"]},"transition":1},"hillshade-shadow-color":{"type":"color","default":"#000000","expression":{"interpolated":1,"parameters":["measure-light","zoom"]},"transition":1,"use-theme":1},"hillshade-highlight-color":{"type":"color","default":"#FFFFFF","expression":{"interpolated":1,"parameters":["measure-light","zoom"]},"transition":1,"use-theme":1},"hillshade-accent-color":{"type":"color","default":"#000000","expression":{"interpolated":1,"parameters":["measure-light","zoom"]},"transition":1,"use-theme":1},"hillshade-emissive-strength":{"type":"number","default":0,"minimum":0,"expression":{"interpolated":1,"parameters":["measure-light","zoom"]},"transition":1}},"paint_background":{"background-pitch-alignment":{"type":"enum","default":"map","values":{"map":1,"viewport":1},"expression":{"parameters":[]}},"background-color":{"type":"color","default":"#000000","expression":{"interpolated":1,"parameters":["measure-light","zoom"]},"transition":1,"use-theme":1},"background-pattern":{"type":"resolvedImage","expression":{"parameters":["zoom"]}},"background-opacity":{"type":"number","default":1,"minimum":0,"maximum":1,"expression":{"interpolated":1,"parameters":["zoom"]},"transition":1},"background-emissive-strength":{"type":"number","default":0,"minimum":0,"expression":{"interpolated":1,"parameters":["measure-light","zoom"]},"transition":1}},"paint_sky":{"sky-type":{"type":"enum","default":"atmosphere","values":{"gradient":1,"atmosphere":1},"expression":{"parameters":["zoom"]}},"sky-atmosphere-sun":{"type":"array","minimum":[0,0],"maximum":[360,180],"length":2,"value":"number","expression":{"parameters":["zoom"]}},"sky-atmosphere-sun-intensity":{"type":"number","default":10,"minimum":0,"maximum":100},"sky-gradient-center":{"type":"array","default":[0,0],"minimum":[0,0],"maximum":[360,180],"length":2,"value":"number","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"],"expression":{"interpolated":1,"parameters":["sky-radial-progress"]},"use-theme":1},"sky-atmosphere-halo-color":{"type":"color","default":"white","use-theme":1},"sky-atmosphere-color":{"type":"color","default":"white","use-theme":1},"sky-opacity":{"type":"number","default":1,"minimum":0,"maximum":1,"expression":{"interpolated":1,"parameters":["zoom"]},"transition":1}},"paint_model":{"model-opacity":{"type":"number","default":1,"minimum":0,"maximum":1,"expression":{"interpolated":1,"parameters":["feature","feature-state","zoom"]},"transition":1,"property-type":"data-driven"},"model-rotation":{"type":"array","default":[0,0,0],"length":3,"value":"number","expression":{"interpolated":1,"parameters":["feature","feature-state","zoom"]},"transition":1,"property-type":"data-driven"},"model-scale":{"type":"array","default":[1,1,1],"length":3,"value":"number","expression":{"interpolated":1,"parameters":["feature","feature-state","zoom"]},"transition":1,"property-type":"data-driven"},"model-translation":{"type":"array","default":[0,0,0],"length":3,"value":"number","expression":{"interpolated":1,"parameters":["feature","feature-state","zoom"]},"transition":1,"property-type":"data-driven"},"model-color":{"type":"color","default":"#ffffff","expression":{"interpolated":1,"parameters":["feature","feature-state","measure-light","zoom"]},"transition":1,"use-theme":1,"property-type":"data-driven"},"model-color-mix-intensity":{"type":"number","default":0,"minimum":0,"maximum":1,"expression":{"interpolated":1,"parameters":["feature","feature-state","measure-light"]},"transition":1,"property-type":"data-driven"},"model-type":{"type":"enum","default":"common-3d","values":{"common-3d":1,"location-indicator":1}},"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":1,"parameters":["zoom"]},"transition":1},"model-emissive-strength":{"type":"number","default":0,"minimum":0,"maximum":5,"expression":{"interpolated":1,"parameters":["feature","feature-state","measure-light"]},"transition":1,"property-type":"data-driven"},"model-roughness":{"type":"number","default":1,"minimum":0,"maximum":1,"expression":{"interpolated":1,"parameters":["feature","feature-state"]},"transition":1,"property-type":"data-driven"},"model-height-based-emissive-strength-multiplier":{"type":"array","default":[1,1,1,1,0],"length":5,"value":"number","expression":{"interpolated":1,"parameters":["feature","feature-state","measure-light"]},"transition":1,"property-type":"data-driven"},"model-cutoff-fade-range":{"type":"number","default":0,"minimum":0,"maximum":1,"expression":1},"model-front-cutoff":{"type":"array","default":[0,0,1],"minimum":[0,0,0],"maximum":[1,1,1],"length":3,"value":"number","expression":{"interpolated":1,"parameters":["zoom"]}},"model-elevation-reference":{"type":"enum","default":"ground","values":{"sea":1,"ground":1,"hd-road-markup":1},"expression":1},"model-line-cutout-mode":{"type":"enum","default":"enabled","values":{"enabled":1,"disabled":1,"enabled-above-cutout":1},"expression":1}},"promoteId":{"*":{"type":"*"}}}');function M9(N){return N instanceof Number||N instanceof String||N instanceof Boolean?N.valueOf():N}function P9(N){if(Array.isArray(N))return N.map(P9);if(N instanceof Object&&!(N instanceof Number||N instanceof String||N instanceof Boolean)){const p={},_=N;for(const A in _)p[A]=P9(_[A]);return p}return M9(N)}function V6(N){if(N===!0||N===!1)return!0;if(!Array.isArray(N)||N.length===0)return!1;switch(N[0]){case"has":return N.length>=2&&N[1]!=="$id"&&N[1]!=="$type";case"in":return N.length>=3&&(typeof N[1]!="string"||Array.isArray(N[2]));case"!in":case"!has":case"none":return!1;case"==":case"!=":case">":case">=":case"<":case"<=":return N.length!==3||Array.isArray(N[1])||Array.isArray(N[2]);case"any":case"all":for(const p of N.slice(1))if(!V6(p)&&typeof p!="boolean")return!1;return!0;default:return!0}}function gY(N,p="",_=null,A="fill"){if(N==null)return{filter:()=>!0,needGeometry:!1,needFeature:!1};V6(N)||(N=H6(N));const M=N;let F=!0;try{F=function(fe){if(!QT(fe))return fe;let xe=P9(fe);return poe(xe),xe=foe(xe),xe}(M)}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(M,null,2)} `)}let z=null,H=null;if(A!=="background"&&A!=="sky"&&A!=="slot"){H=Zs[`filter_${A}`];const fe=W0(F,H,p,_);if(fe.result==="error")throw new Error(fe.value.map(xe=>`${xe.key}: ${xe.message}`).join(", "));z=(xe,be,Te)=>fe.value.evaluate(xe,be,{},Te)}let Z=null,se=null;if(F!==M){const fe=W0(M,H,p,_);if(fe.result==="error")throw new Error(fe.value.map(xe=>`${xe.key}: ${xe.message}`).join(", "));Z=(xe,be,Te,De,Ue)=>fe.value.evaluate(xe,be,{},Te,void 0,void 0,De,Ue),se=!$1(fe.value.expression)}return{filter:z,dynamicFilter:Z||void 0,needGeometry:xoe(F),needFeature:!!se}}function foe(N){if(!Array.isArray(N))return N;const p=function(_){if(goe.has(_[0])){for(let A=1;A<_.length;A++)if(QT(_[A]))return!0}return _}(N);return p===!0?p:p.map(_=>foe(_))}function poe(N){let p=!1;const _=[];if(N[0]==="case"){for(let A=1;A",">=","<","<=","to-boolean"]);function xY(N,p){return Np?1:0}function xoe(N){if(!Array.isArray(N))return!1;if(N[0]==="within"||N[0]==="distance")return!0;for(let p=1;p"||p==="<="||p===">="?I9(N[1],N[2],p):p==="any"?(_=N.slice(1),["any"].concat(_.map(H6))):p==="all"?["all"].concat(N.slice(1).map(H6)):p==="none"?["all"].concat(N.slice(1).map(H6).map(D3)):p==="in"?yoe(N[1],N.slice(2)):p==="!in"?D3(yoe(N[1],N.slice(2))):p==="has"?L9(N[1]):p!=="!has"||D3(L9(N[1]));var _}function I9(N,p,_){switch(N){case"$type":return[`filter-type-${_}`,p];case"$id":return[`filter-id-${_}`,p];default:return[`filter-${_}`,N,p]}}function yoe(N,p){if(p.length===0)return!1;switch(N){case"$type":return["filter-type-in",["literal",p]];case"$id":return["filter-id-in",["literal",p]];default:return p.length>200&&!p.some(_=>typeof _!=typeof p[0])?["filter-in-large",N,["literal",p.sort(xY)]]:["filter-in-small",N,["literal",p]]}}function L9(N){switch(N){case"$type":return!0;case"$id":return["filter-has-id"];default:return["filter-has",N]}}function D3(N){return["!",N]}const JT="";function G6(N,p){return p?`${N}${JT}${p}`:N}function yY(N){const p=N.indexOf(JT);return p>=0?N.slice(p+1):""}let voe,vY=1;const boe=()=>voe||(voe=new Ku({"icon-size":new Tr(Zs.layout_symbol["icon-size"]),"icon-image":new Tr(Zs.layout_symbol["icon-image"]),"icon-rotate":new Tr(Zs.layout_symbol["icon-rotate"]),"icon-offset":new Tr(Zs.layout_symbol["icon-offset"]),"text-size":new Tr(Zs.layout_symbol["text-size"]),"text-rotate":new Tr(Zs.layout_symbol["text-rotate"]),"text-offset":new Tr(Zs.layout_symbol["text-offset"])}));let _oe;const woe=()=>_oe||(_oe=new Ku({"icon-opacity":new Tr(Zs.paint_symbol["icon-opacity"]),"icon-occlusion-opacity":new Tr(Zs.paint_symbol["icon-occlusion-opacity"]),"icon-emissive-strength":new Tr(Zs.paint_symbol["icon-emissive-strength"]),"text-emissive-strength":new Tr(Zs.paint_symbol["text-emissive-strength"]),"icon-color":new Tr(Zs.paint_symbol["icon-color"]),"icon-halo-color":new Tr(Zs.paint_symbol["icon-halo-color"]),"icon-halo-width":new Tr(Zs.paint_symbol["icon-halo-width"]),"icon-halo-blur":new Tr(Zs.paint_symbol["icon-halo-blur"]),"icon-translate":new Tr(Zs.paint_symbol["icon-translate"]),"text-opacity":new Tr(Zs.paint_symbol["text-opacity"]),"text-occlusion-opacity":new Tr(Zs.paint_symbol["text-occlusion-opacity"]),"text-color":new Tr(Zs.paint_symbol["text-color"],{runtimeType:ed,getOverride:N=>N.textColor,hasOverride:N=>!!N.textColor}),"text-halo-color":new Tr(Zs.paint_symbol["text-halo-color"]),"text-halo-width":new Tr(Zs.paint_symbol["text-halo-width"]),"text-halo-blur":new Tr(Zs.paint_symbol["text-halo-blur"]),"text-translate":new Tr(Zs.paint_symbol["text-translate"]),"symbol-z-offset":new Tr(Zs.paint_symbol["symbol-z-offset"]),"placement-priority":new Tr(Zs.paint_symbol["placement-priority"]),"placement-group":new Tr(Zs.paint_symbol["placement-group"]),"icon-color-use-theme":new Tr({type:"string",default:"default","property-type":"data-driven"}),"icon-halo-color-use-theme":new Tr({type:"string",default:"default","property-type":"data-driven"}),"text-color-use-theme":new Tr({type:"string",default:"default","property-type":"data-driven"}),"text-halo-color-use-theme":new Tr({type:"string",default:"default","property-type":"data-driven"})}));class OFe{constructor(p,_,A,M,F,z){this._conditionSpec=p,this._propertiesSpec=A;const H=W0(p,Zs.appearance.condition);if(H.result==="success"&&(this.condition=H.value),this.name=_,A){this.layoutProperties=new Sl(boe()),this.unevaluatedLayout=new Id(boe(),M,F,z),this.paintProperties=new Sl(woe()),this.unevaluatedPaint=new Id(woe(),M,F,"");for(const Z in A)Z in this.unevaluatedLayout._values?this.unevaluatedLayout.setValue(Z,A[Z]):Z in this.unevaluatedPaint._values&&this.unevaluatedPaint.setValue(Z,A[Z])}}isActive(p){return!(this.condition||!p.isHidden||this.name!=="hidden")||this.condition.evaluate(p.globals,p.feature,p.featureState,p.canonical)}getCondition(){return this.condition}getName(){return this.name}getLayoutProperty(p){return this.layoutProperties.get(p)}getPaintProperty(p){return this.paintProperties.get(p)}getUnevaluatedLayoutProperties(){return this.unevaluatedLayout}getUnevaluatedLayoutProperty(p){return this.unevaluatedLayout._values[p]}getUnevaluatedPaintProperty(p){return this.unevaluatedPaint._values[p]}recalculate(p,_,A){this.unevaluatedLayout&&(this.layoutProperties=this.unevaluatedLayout.possiblyEvaluate(p,void 0,_,A)),this.unevaluatedPaint&&(this.paintProperties=this.unevaluatedPaint.possiblyEvaluate(p,void 0,_,""))}serialize(){const p={};p.condition=this.condition.expression.serialize(),this.name&&(p.name=this.name);const _={...this.unevaluatedLayout?this.unevaluatedLayout.serialize():{},...this.unevaluatedPaint?this.unevaluatedPaint.serialize():{}};return Object.keys(_).length>0&&(p.properties=_),p}hasIconLayoutProperties(){const p=this.hasLayoutProperty("icon-image"),_=this.hasLayoutProperty("icon-size"),A=this.hasLayoutProperty("icon-offset"),M=this.hasLayoutProperty("icon-rotate");return p||_||A||M}hasTextLayoutProperties(){const p=this.hasLayoutProperty("text-size"),_=this.hasLayoutProperty("text-offset"),A=this.hasLayoutProperty("text-rotate");return p||_||A}hasIconPaintProperties(){return!!this.unevaluatedPaint&&Object.keys(this.unevaluatedPaint._values).filter(p=>!p.endsWith("-use-theme")).some(p=>(p.startsWith("icon-")||p==="symbol-z-offset")&&this.hasPaintProperty(p))}hasTextPaintProperties(){return!!this.unevaluatedPaint&&Object.keys(this.unevaluatedPaint._values).filter(p=>!p.endsWith("-use-theme")).some(p=>(p.startsWith("text-")||p==="symbol-z-offset")&&this.hasPaintProperty(p))}hasLayoutProperty(p){return this.unevaluatedLayout&&this.unevaluatedLayout._values[p].value!==void 0}hasPaintProperty(p){return this.unevaluatedPaint&&this.unevaluatedPaint._values[p].value!==void 0}}const bY="-transition",zFe=new Set(["fill","line","background","hillshade","raster"]);class e0 extends Jc{constructor(p,_,A,M,F,z){if(super(),this.id=p.id,this.fqid=G6(this.id,A),this.runtimeLayerUID=vY++,this.type=p.type,this.scope=A,this.lut=M,this.options=F,this.iconImageUseTheme=z,this.appearances=new Array,this.appearancesVersion=0,this._featureFilter={filter:()=>!0,needGeometry:!1,needFeature:!1},this._filterCompiled=!1,p.type!=="custom"&&(this.metadata=p.metadata,this.minzoom=p.minzoom,this.maxzoom=p.maxzoom,p.type&&p.type!=="background"&&p.type!=="sky"&&p.type!=="slot"&&p.type!=="placement-group"&&(this.source=p.source,this.sourceLayer=p["source-layer"],this.filter=p.filter),p.slot&&(this.slot=p.slot),p.appearances&&this.setAppearances(p.appearances),_.layout&&(this._unevaluatedLayout=new Id(_.layout,this.scope,F,this.iconImageUseTheme)),_.paint)){this._transitionablePaint=new xl(_.paint,this.scope,F);for(const H in p.paint)this.setPaintProperty(H,p.paint[H]);for(const H in p.layout)this.setLayoutProperty(H,p.layout[H]);this._transitioningPaint=this._transitionablePaint.untransitioned(),this.paint=new Sl(_.paint)}}onAdd(p){}onRemove(p){}placeSymbols(p,_,A,M,F){}isDraped(p){return!this.is3D(!0)&&zFe.has(this.type)}getLayoutProperty(p){return p==="visibility"?this.visibility:this._unevaluatedLayout.getValue(p)}setLayoutProperty(p,_){if(this.type==="custom"&&p==="visibility")return void(this.visibility=_);const A=this._unevaluatedLayout;A._properties.properties[p]&&(A.setValue(p,_),p==="visibility"&&this.possiblyEvaluateVisibility())}setAppearances(p){this.appearances=[],p.forEach(_=>{this.appearances.push(new OFe(_.condition,_.name,_.properties,this.scope,this.options,this.iconImageUseTheme))}),this.appearancesVersion++}possiblyEvaluateVisibility(){this._unevaluatedLayout._values.visibility&&(this.visibility=this._unevaluatedLayout._values.visibility.possiblyEvaluate({zoom:0}))}getPaintProperty(p){return p.endsWith(bY)?this._transitionablePaint.getTransition(p.slice(0,-11)):this._transitionablePaint.getValue(p)}isPaintProperty(p){return!!this._transitionablePaint._properties.properties[p]}setPaintProperty(p,_){const A=this._transitionablePaint,M=A._properties.properties;if(p.endsWith(bY)){const xe=p.slice(0,-11);return M[xe]&&A.setTransition(xe,_||void 0),!1}if(!M[p])return!1;const F=A._values[p],z=F.value.isDataDriven(),H=F.value;A.setValue(p,_),this._handleSpecialPaintPropertyUpdate(p);const Z=A._values[p].value,se=Z.isDataDriven(),fe=p.endsWith("pattern")||p==="line-dasharray";return se||z||fe||this._handleOverridablePaintPropertyUpdate(p,H,Z)}_handleSpecialPaintPropertyUpdate(p){}getProgramIds(){return null}getDefaultProgramParams(p,_,A){return null}_handleOverridablePaintPropertyUpdate(p,_,A){return!1}isHidden(p){return!!(this.minzoom&&p=this.maxzoom)||this.visibility==="none"}updateTransitions(p){this._transitioningPaint=this._transitionablePaint.transitioned(p,this._transitioningPaint)}hasTransition(){return this._transitioningPaint.hasTransition()}recalculate(p,_){this._unevaluatedLayout&&(this.layout=this._unevaluatedLayout.possiblyEvaluate(p,void 0,_,this.iconImageUseTheme)),this.paint=this._transitioningPaint.possiblyEvaluate(p,void 0,_)}serialize(){const p={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&&(p.appearances=this.appearances.map(_=>_.serialize())),yc(p,(_,A)=>!(_===void 0||A==="layout"&&!Object.keys(_).length||A==="paint"&&!Object.keys(_).length))}is3D(p){return!1}hasElevation(){return!1}mayUse(p){return!1}prepare(){return Promise.resolve()}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 p in this.paint._values){const _=this.paint.get(p);if(_ instanceof _h&&Xy(_.property.specification)&&(_.value.kind==="source"||_.value.kind==="composite")&&_.value.isStateDependent)return!0}for(const p of this.appearances)if(!H0(p.condition.expression))return!0;return!1}compileFilter(p){this._filterCompiled||(this._featureFilter=gY(this.filter,this.scope,p),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(p){this._stats&&(p.renderPass==="shadow"?this._stats.numRenderedVerticesInShadowPass=0:this._stats.numRenderedVerticesInTransparentPass=0)}getAppearances(){return this.appearances}queryRenderedFeatures(p,_,A){return{}}queryRadius(p){}queryIntersectsFeature(p,_,A,M,F,z,H,Z,se,fe){}}function R9(N,p,_){if(!N._unevaluatedLayout)return!1;const A=N._unevaluatedLayout.getValue(p);return A!==void 0&&(typeof A!="string"||_(A))}function eM(N,p,_=2){const A=p&&p.length,M=A?p[0]*_:N.length;let F=joe(N,0,M,_,!0);const z=[];if(!F||F.next===F.prev)return z;let H,Z,se;if(A&&(F=function(fe,xe,be,Te){const De=[];for(let Ue=0,Ye=xe.length;Ue80*_){H=N[0],Z=N[1];let fe=H,xe=Z;for(let be=_;befe&&(fe=Te),De>xe&&(xe=De)}se=Math.max(fe-H,xe-Z),se=se!==0?32767/se:0}return W6(F,z,_,H,Z,se,0),z}function joe(N,p,_,A,M){let F;if(M===function(z,H,Z,se){let fe=0;for(let xe=H,be=Z-se;xe0)for(let z=p;z<_;z+=A)F=Aoe(z/A|0,N[z],N[z+1],F);else for(let z=_-A;z>=p;z-=A)F=Aoe(z/A|0,N[z],N[z+1],F);return F&&sM(F,F.next)&&(Z6(F),F=F.next),F}function F3(N,p){if(!N)return N;p||(p=N);let _,A=N;do if(_=!1,A.steiner||!sM(A,A.next)&&Of(A.prev,A,A.next)!==0)A=A.next;else{if(Z6(A),A=p=A.prev,A===A.next)break;_=!0}while(_||A!==p);return p}function W6(N,p,_,A,M,F,z){if(!N)return;!z&&F&&function(Z,se,fe,xe){let be=Z;do be.z===0&&(be.z=O9(be.x,be.y,se,fe,xe)),be.prevZ=be.prev,be.nextZ=be.next,be=be.next;while(be!==Z);be.prevZ.nextZ=null,be.prevZ=null,function(Te){let De,Ue=1;do{let Ye,st=Te;Te=null;let ot=null;for(De=0;st;){De++;let mt=st,lt=0;for(let Nt=0;Nt0||yt>0&&mt;)lt!==0&&(yt===0||!mt||st.z<=mt.z)?(Ye=st,st=st.nextZ,lt--):(Ye=mt,mt=mt.nextZ,yt--),ot?ot.nextZ=Ye:Te=Ye,Ye.prevZ=ot,ot=Ye;st=mt}ot.nextZ=null,Ue*=2}while(De>1)}(be)}(N,A,M,F);let H=N;for(;N.prev!==N.next;){const Z=N.prev,se=N.next;if(F?$Fe(N,A,M,F):BFe(N))p.push(Z.i,N.i,se.i),Z6(N),N=se.next,H=se.next;else if((N=se)===H){z?z===1?W6(N=D9(F3(N),p),p,_,A,M,F,2):z===2&&UFe(N,p,_,A,M,F):W6(F3(N),p,_,A,M,F,1);break}}}function BFe(N){const p=N.prev,_=N,A=N.next;if(Of(p,_,A)>=0)return!1;const M=p.x,F=_.x,z=A.x,H=p.y,Z=_.y,se=A.y,fe=Math.min(M,F,z),xe=Math.min(H,Z,se),be=Math.max(M,F,z),Te=Math.max(H,Z,se);let De=A.next;for(;De!==p;){if(De.x>=fe&&De.x<=be&&De.y>=xe&&De.y<=Te&&tM(M,H,F,Z,z,se,De.x,De.y)&&Of(De.prev,De,De.next)>=0)return!1;De=De.next}return!0}function $Fe(N,p,_,A){const M=N.prev,F=N,z=N.next;if(Of(M,F,z)>=0)return!1;const H=M.x,Z=F.x,se=z.x,fe=M.y,xe=F.y,be=z.y,Te=Math.min(H,Z,se),De=Math.min(fe,xe,be),Ue=Math.max(H,Z,se),Ye=Math.max(fe,xe,be),st=O9(Te,De,p,_,A),ot=O9(Ue,Ye,p,_,A);let mt=N.prevZ,lt=N.nextZ;for(;mt&&mt.z>=st&<&<.z<=ot;){if(mt.x>=Te&&mt.x<=Ue&&mt.y>=De&&mt.y<=Ye&&mt!==M&&mt!==z&&tM(H,fe,Z,xe,se,be,mt.x,mt.y)&&Of(mt.prev,mt,mt.next)>=0||(mt=mt.prevZ,lt.x>=Te&<.x<=Ue&<.y>=De&<.y<=Ye&<!==M&<!==z&&tM(H,fe,Z,xe,se,be,lt.x,lt.y)&&Of(lt.prev,lt,lt.next)>=0))return!1;lt=lt.nextZ}for(;mt&&mt.z>=st;){if(mt.x>=Te&&mt.x<=Ue&&mt.y>=De&&mt.y<=Ye&&mt!==M&&mt!==z&&tM(H,fe,Z,xe,se,be,mt.x,mt.y)&&Of(mt.prev,mt,mt.next)>=0)return!1;mt=mt.prevZ}for(;lt&<.z<=ot;){if(lt.x>=Te&<.x<=Ue&<.y>=De&<.y<=Ye&<!==M&<!==z&&tM(H,fe,Z,xe,se,be,lt.x,lt.y)&&Of(lt.prev,lt,lt.next)>=0)return!1;lt=lt.nextZ}return!0}function D9(N,p){let _=N;do{const A=_.prev,M=_.next.next;!sM(A,M)&&Soe(A,_,_.next,M)&&Y6(A,M)&&Y6(M,A)&&(p.push(A.i,_.i,M.i),Z6(_),Z6(_.next),_=N=M),_=_.next}while(_!==N);return F3(_)}function UFe(N,p,_,A,M,F){let z=N;do{let H=z.next.next;for(;H!==z.prev;){if(z.i!==H.i&&koe(z,H)){let Z=Coe(z,H);return z=F3(z,z.next),Z=F3(Z,Z.next),W6(z,p,_,A,M,F,0),void W6(Z,p,_,A,M,F,0)}H=H.next}z=z.next}while(z!==N)}function qFe(N,p){let _=N.x-p.x;return _===0&&(_=N.y-p.y,_===0)&&(_=(N.next.y-N.y)/(N.next.x-N.x)-(p.next.y-p.y)/(p.next.x-p.x)),_}function F9(N,p){const _=function(M,F){let z=F;const H=M.x,Z=M.y;let se,fe=-1/0;if(sM(M,z))return z;do{if(sM(M,z.next))return z.next;if(Z<=z.y&&Z>=z.next.y&&z.next.y!==z.y){const Ue=z.x+(Z-z.y)*(z.next.x-z.x)/(z.next.y-z.y);if(Ue<=H&&Ue>fe&&(fe=Ue,se=z.x=z.x&&z.x>=be&&H!==z.x&&Noe(Zse.x||z.x===se.x&&VFe(se,z)))&&(se=z,De=Ue)}z=z.next}while(z!==xe);return se}(N,p);if(!_)return p;const A=Coe(_,N);return F3(A,A.next),F3(_,_.next)}function VFe(N,p){return Of(N.prev,N,p.prev)<0&&Of(p.next,N,N.next)<0}function O9(N,p,_,A,M){return(N=1431655765&((N=858993459&((N=252645135&((N=16711935&((N=(N-_)*M|0)|N<<8))|N<<4))|N<<2))|N<<1))|(p=1431655765&((p=858993459&((p=252645135&((p=16711935&((p=(p-A)*M|0)|p<<8))|p<<4))|p<<2))|p<<1))<<1}function HFe(N){let p=N,_=N;do(p.x<_.x||p.x===_.x&&p.y<_.y)&&(_=p),p=p.next;while(p!==N);return _}function Noe(N,p,_,A,M,F,z,H){return(M-z)*(p-H)>=(N-z)*(F-H)&&(N-z)*(A-H)>=(_-z)*(p-H)&&(_-z)*(F-H)>=(M-z)*(A-H)}function tM(N,p,_,A,M,F,z,H){return!(N===z&&p===H)&&Noe(N,p,_,A,M,F,z,H)}function koe(N,p){return N.next.i!==p.i&&N.prev.i!==p.i&&!function(_,A){let M=_;do{if(M.i!==_.i&&M.next.i!==_.i&&M.i!==A.i&&M.next.i!==A.i&&Soe(M,M.next,_,A))return!0;M=M.next}while(M!==_);return!1}(N,p)&&(Y6(N,p)&&Y6(p,N)&&function(_,A){let M=_,F=!1;const z=(_.x+A.x)/2,H=(_.y+A.y)/2;do M.y>H!=M.next.y>H&&M.next.y!==M.y&&z<(M.next.x-M.x)*(H-M.y)/(M.next.y-M.y)+M.x&&(F=!F),M=M.next;while(M!==_);return F}(N,p)&&(Of(N.prev,N,p.prev)||Of(N,p.prev,p))||sM(N,p)&&Of(N.prev,N,N.next)>0&&Of(p.prev,p,p.next)>0)}function Of(N,p,_){return(p.y-N.y)*(_.x-p.x)-(p.x-N.x)*(_.y-p.y)}function sM(N,p){return N.x===p.x&&N.y===p.y}function Soe(N,p,_,A){const M=z9(Of(N,p,_)),F=z9(Of(N,p,A)),z=z9(Of(_,A,N)),H=z9(Of(_,A,p));return M!==F&&z!==H||!(M!==0||!K6(N,_,p))||!(F!==0||!K6(N,A,p))||!(z!==0||!K6(_,N,A))||!(H!==0||!K6(_,p,A))}function K6(N,p,_){return p.x<=Math.max(N.x,_.x)&&p.x>=Math.min(N.x,_.x)&&p.y<=Math.max(N.y,_.y)&&p.y>=Math.min(N.y,_.y)}function z9(N){return N>0?1:N<0?-1:0}function Y6(N,p){return Of(N.prev,N,N.next)<0?Of(N,p,N.next)>=0&&Of(N,N.prev,p)>=0:Of(N,p,N.prev)<0||Of(N,N.next,p)<0}function Coe(N,p){const _=_Y(N.i,N.x,N.y),A=_Y(p.i,p.x,p.y),M=N.next,F=p.prev;return N.next=p,p.prev=N,_.next=M,M.prev=_,A.next=_,_.prev=A,F.next=A,A.prev=F,A}function Aoe(N,p,_,A){const M=_Y(N,p,_);return A?(M.next=A.next,M.prev=A,A.next.prev=M,A.next=M):(M.prev=M,M.next=M),M}function Z6(N){N.next.prev=N.prev,N.prev.next=N.next,N.prevZ&&(N.prevZ.nextZ=N.nextZ),N.nextZ&&(N.nextZ.prevZ=N.prevZ)}function _Y(N,p,_){return{i:N,x:p,y:_,prev:null,next:null,z:0,prevZ:null,nextZ:null,steiner:!1}}function wY(N,p,_=1){if(!N)return null;const A=typeof N=="string"?vh.from(N).getPrimary():N.getPrimary(),M=typeof N=="string"?null:N.getSecondary();for(const F of[A,M]){if(!F)continue;const z=F.id.toString();p.has(z)||p.set(z,[]),F.scaleSelf(_),p.get(z).push(F)}return{primary:A.toString(),secondary:M?M.toString():null}}function X6(N,p,_,A){const M=A.patternDependencies;let F=!1;for(const z of p){const H=z.paint.get(`${N}-pattern`);H.isConstant()||(F=!0),wY(H.constantOr(null),M,_)&&(F=!0)}return F}function jY(N,p,_,A,M,F){const z=F.patternDependencies;for(const H of p){const Z=H.paint.get(`${N}-pattern`).value;if(Z.kind!=="constant"){const se=wY(Z.evaluate({zoom:A},_,{},void 0,F.availableImages),z,M);if(!se)continue;const{primary:fe,secondary:xe}=se;fe&&(_.patterns[H.id]=[fe,xe].filter(Boolean))}}return _}const gf=Fr/Math.PI/2,Kk=64,NY=[Kk,32,16],Wv=-gf,K_=gf;function cj(N,p,_,A=gf){return _=Xr(_),[N*Math.sin(_)*A,-p*A,N*Math.cos(_)*A]}function O3(N,p,_){return cj(Math.cos(Xr(N)),Math.sin(Xr(N)),p,_)}const nM=63710088e-1,kY=2*Math.PI*nM;class Ll{constructor(p,_){if(isNaN(p)||isNaN(_))throw new Error(`Invalid LngLat object: (${p}, ${_})`);if(this.lng=+p,this.lat=+_,this.lat>90||this.lat<-90)throw new Error("Invalid LngLat latitude value: must be between -90 and 90")}wrap(){return new Ll(fl(this.lng,-180,180),this.lat)}toArray(){return[this.lng,this.lat]}toString(){return`LngLat(${this.lng}, ${this.lat})`}distanceTo(p){const _=Math.PI/180,A=this.lat*_,M=p.lat*_,F=Math.sin(A)*Math.sin(M)+Math.cos(A)*Math.cos(M)*Math.cos((p.lng-this.lng)*_);return nM*Math.acos(Math.min(F,1))}toBounds(p=0){const _=360*p/40075017,A=_/Math.cos(Math.PI/180*this.lat);return new Y_({lng:this.lng-A,lat:this.lat-_},{lng:this.lng+A,lat:this.lat+_})}toEcef(p){return O3(this.lat,this.lng,gf+p*gf/nM)}static convert(p){if(p instanceof Ll)return p;if(Array.isArray(p)&&(p.length===2||p.length===3))return new Ll(Number(p[0]),Number(p[1]));if(!Array.isArray(p)&&typeof p=="object"&&p!==null)return new Ll(Number("lng"in p?p.lng:p.lon),Number(p.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 Y_{constructor(p,_){p&&(_?this.setSouthWest(p).setNorthEast(_):Array.isArray(p)&&p.length===4?this.setSouthWest([p[0],p[1]]).setNorthEast([p[2],p[3]]):this.setSouthWest(p[0]).setNorthEast(p[1]))}setNorthEast(p){return this._ne=p instanceof Ll?new Ll(p.lng,p.lat):Ll.convert(p),this}setSouthWest(p){return this._sw=p instanceof Ll?new Ll(p.lng,p.lat):Ll.convert(p),this}extend(p){const _=this._sw,A=this._ne;let M,F;if(p instanceof Ll)M=p,F=p;else{if(!(p instanceof Y_))return Array.isArray(p)?p.length===4||p.every(Array.isArray)?this.extend(Y_.convert(p)):this.extend(Ll.convert(p)):typeof p=="object"&&p!==null&&Object.hasOwn(p,"lat")&&(Object.hasOwn(p,"lon")||Object.hasOwn(p,"lng"))?this.extend(Ll.convert(p)):this;if(M=p._sw,F=p._ne,!M||!F)return this}return _||A?(_.lng=Math.min(M.lng,_.lng),_.lat=Math.min(M.lat,_.lat),A.lng=Math.max(F.lng,A.lng),A.lat=Math.max(F.lat,A.lat)):(this._sw=new Ll(M.lng,M.lat),this._ne=new Ll(F.lng,F.lat)),this}getCenter(){return new Ll((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 Ll(this.getWest(),this.getNorth())}getSouthEast(){return new Ll(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(p){const{lng:_,lat:A}=Ll.convert(p);let M=this._sw.lng<=_&&_<=this._ne.lng;return this._sw.lng>this._ne.lng&&(M=this._sw.lng>=_&&_>=this._ne.lng),this._sw.lat<=A&&A<=this._ne.lat&&M}static convert(p){if(p)return p instanceof Y_?p:new Y_(p)}}function Q6(N){return kY*Math.cos(N*Math.PI/180)}function eu(N,p){return N/Q6(p)}function Eoe(N,p){return N*Q6(Hd(p))}const L=85.051129;function k(N){return Math.cos(Xr(ta(N,-85.051129,L)))}function T(N,p){const _=ta(p,0,25.5),A=Math.pow(2,_);return k(N)*kY/(512*A)}function B(N){return 1/Math.cos(N*Math.PI/180)}function K(N,p=0){const _=Math.exp(Math.PI*(1-(N.y+p/Fr)/(1<=Z?(le(N,p,_,se,fe,F,xe,H,Z),le(N,se,fe,A,M,xe,z,H,Z)):N.push(z)}function me(N,p,_){let A=N[0],M=A.x,F=A.y;p(A);const z=[A];for(let H=1;HN.x+1||AN.y+1)&&Yo("Geometry exceeds allowed extent, reduce your vector tile buffer size"),N}function ht(N,p,_){const A=N.loadGeometry(),M=N.extent,F=Fr/M;if(p&&_&&_.projection.isReprojectedInTileSpace){const z=1<{const Te=Ox((p.x+be.x/M)/z),De=Hd((p.y+be.y/M)/z),Ue=fe.project(Te,De);be.x=(Ue.x*H-Z)*M,be.y=(Ue.y*H-se)*M};for(let be=0;be=M||De.y<0||De.y>=M||(xe(De),Te.push(De));A[be]=Te}}for(const z of A)for(const H of z)Qe(H,F);return A}function _t(N,p){return{type:N.type,id:N.id,properties:N.properties,geometry:p?ht(N):[]}}const bt={Int8:Int8Array,Uint8:Uint8Array,Int16:Int16Array,Uint16:Uint16Array,Int32:Int32Array,Uint32:Uint32Array,Float32:Float32Array};class Mt{constructor(p,_){this._structArray=p,this._pos1=_*this.size,this._pos2=this._pos1/2,this._pos4=this._pos1/4,this._pos8=this._pos1/8}}const es=new ArrayBuffer(0);class Qt{constructor(){this._reallocCount=0,this.capacity=0,this.length=0}static serialize(p,_){return p._trim(),_&&p.arrayBuffer&&_.add(p.arrayBuffer),{length:p.length,arrayBuffer:p.arrayBuffer}}static deserialize(p){const _=Object.create(this.prototype);return _.arrayBuffer=p.arrayBuffer,_.length=p.length,p.arrayBuffer?_.capacity=p.arrayBuffer.byteLength/_.bytesPerElement:(_.capacity=0,_.arrayBuffer=es),_._refreshViews(),_}_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(p){this.reserve(p),this.length=p}resizeExact(p){this.reserveExact(p),this.length=p}reserve(p){p>this.capacity&&this._allocate(Math.max(p,Math.floor(5*this.capacity),128))}reserveExact(p){(p>this.capacity||!this.arrayBuffer)&&this._allocate(p)}_allocate(p){this._reallocCount++,this.capacity=p,this.arrayBuffer=new ArrayBuffer(this.capacity*this.bytesPerElement);const _=this.uint8;this._refreshViews(),_&&this.uint8.set(_)}reserveForAdditional(p){this.reserve(this.length+p)}_refreshViews(){throw new Error("StructArray#_refreshViews() must be implemented by each concrete StructArray layout")}emplace(...p){throw new Error("StructArray#emplace() must be implemented by each concrete StructArray layout")}emplaceBack(...p){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 Lt(N,p=1){let _=0,A=0;return{members:N.map(M=>{const F=bt[M.type].BYTES_PER_ELEMENT,z=_=ps(_,Math.max(p,F)),H=M.components||1;return A=Math.max(A,F),_+=F*H,{name:M.name,type:M.type,components:H,offset:z,normalized:M.normalized}}),size:ps(_,Math.max(A,p)),alignment:p}}function ps(N,p){return Math.ceil(N/p)*p}class Hs extends Qt{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(p,_){const A=this.length;return this.resize(A+1),this.emplace(A,p,_)}emplace(p,_,A){const M=2*p;return this.int16[M+0]=_,this.int16[M+1]=A,p}}Hs.prototype.bytesPerElement=4,oa(Hs,"StructArrayLayout2i4");class Fs extends Qt{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(p,_,A){const M=this.length;return this.resize(M+1),this.emplace(M,p,_,A)}emplace(p,_,A,M){const F=3*p;return this.int16[F+0]=_,this.int16[F+1]=A,this.int16[F+2]=M,p}}Fs.prototype.bytesPerElement=6,oa(Fs,"StructArrayLayout3i6");class nn extends Qt{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(p,_,A,M){const F=this.length;return this.resize(F+1),this.emplace(F,p,_,A,M)}emplace(p,_,A,M,F){const z=4*p;return this.int16[z+0]=_,this.int16[z+1]=A,this.uint16[z+2]=M,this.uint16[z+3]=F,p}}nn.prototype.bytesPerElement=8,oa(nn,"StructArrayLayout2i2ui8");class $s extends Qt{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(p){const _=this.length;return this.resize(_+1),this.emplace(_,p)}emplace(p,_){return this.float32[1*p+0]=_,p}}$s.prototype.bytesPerElement=4,oa($s,"StructArrayLayout1f4");class rn extends Qt{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(p,_,A){const M=this.length;return this.resize(M+1),this.emplace(M,p,_,A)}emplace(p,_,A,M){const F=4*p,z=2*p;return this.int16[F+0]=_,this.int16[F+1]=A,this.float32[z+1]=M,p}}rn.prototype.bytesPerElement=8,oa(rn,"StructArrayLayout2i1f8");class _n extends Qt{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(p,_,A){const M=this.length;return this.resize(M+1),this.emplace(M,p,_,A)}emplace(p,_,A,M){const F=4*p;return this.int16[F+0]=_,this.int16[F+1]=A,this.int16[F+2]=M,p}}_n.prototype.bytesPerElement=8,oa(_n,"StructArrayLayout3i8");class Mn extends Qt{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(p,_,A,M){const F=this.length;return this.resize(F+1),this.emplace(F,p,_,A,M)}emplace(p,_,A,M,F){const z=4*p;return this.int16[z+0]=_,this.int16[z+1]=A,this.int16[z+2]=M,this.int16[z+3]=F,p}}Mn.prototype.bytesPerElement=8,oa(Mn,"StructArrayLayout4i8");class Yn extends Qt{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(p,_,A,M,F){const z=this.length;return this.resize(z+1),this.emplace(z,p,_,A,M,F)}emplace(p,_,A,M,F,z){const H=5*p;return this.int16[H+0]=_,this.int16[H+1]=A,this.int16[H+2]=M,this.int16[H+3]=F,this.int16[H+4]=z,p}}Yn.prototype.bytesPerElement=10,oa(Yn,"StructArrayLayout5i10");class $n extends Qt{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(p,_,A,M,F,z,H){const Z=this.length;return this.resize(Z+1),this.emplace(Z,p,_,A,M,F,z,H)}emplace(p,_,A,M,F,z,H,Z){const se=6*p,fe=12*p,xe=3*p;return this.int16[se+0]=_,this.int16[se+1]=A,this.uint8[fe+4]=M,this.uint8[fe+5]=F,this.uint8[fe+6]=z,this.uint8[fe+7]=H,this.float32[xe+2]=Z,p}}$n.prototype.bytesPerElement=12,oa($n,"StructArrayLayout2i4ub1f12");class zn extends Qt{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(p,_,A){const M=this.length;return this.resize(M+1),this.emplace(M,p,_,A)}emplace(p,_,A,M){const F=3*p;return this.float32[F+0]=_,this.float32[F+1]=A,this.float32[F+2]=M,p}}zn.prototype.bytesPerElement=12,oa(zn,"StructArrayLayout3f12");class Dr extends Qt{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(p,_,A,M,F){const z=this.length;return this.resize(z+1),this.emplace(z,p,_,A,M,F)}emplace(p,_,A,M,F,z){const H=6*p,Z=3*p;return this.uint16[H+0]=_,this.uint16[H+1]=A,this.uint16[H+2]=M,this.uint16[H+3]=F,this.float32[Z+2]=z,p}}Dr.prototype.bytesPerElement=12,oa(Dr,"StructArrayLayout4ui1f12");class An extends Qt{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(p,_,A,M){const F=this.length;return this.resize(F+1),this.emplace(F,p,_,A,M)}emplace(p,_,A,M,F){const z=4*p;return this.uint16[z+0]=_,this.uint16[z+1]=A,this.uint16[z+2]=M,this.uint16[z+3]=F,p}}An.prototype.bytesPerElement=8,oa(An,"StructArrayLayout4ui8");class yr extends Qt{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(p,_,A,M,F,z){const H=this.length;return this.resize(H+1),this.emplace(H,p,_,A,M,F,z)}emplace(p,_,A,M,F,z,H){const Z=6*p;return this.int16[Z+0]=_,this.int16[Z+1]=A,this.int16[Z+2]=M,this.int16[Z+3]=F,this.int16[Z+4]=z,this.int16[Z+5]=H,p}}yr.prototype.bytesPerElement=12,oa(yr,"StructArrayLayout6i12");class sa extends Qt{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(p,_,A,M,F,z,H,Z,se,fe,xe,be){const Te=this.length;return this.resize(Te+1),this.emplace(Te,p,_,A,M,F,z,H,Z,se,fe,xe,be)}emplace(p,_,A,M,F,z,H,Z,se,fe,xe,be,Te){const De=12*p;return this.int16[De+0]=_,this.int16[De+1]=A,this.int16[De+2]=M,this.int16[De+3]=F,this.uint16[De+4]=z,this.uint16[De+5]=H,this.uint16[De+6]=Z,this.uint16[De+7]=se,this.int16[De+8]=fe,this.int16[De+9]=xe,this.int16[De+10]=be,this.int16[De+11]=Te,p}}sa.prototype.bytesPerElement=24,oa(sa,"StructArrayLayout4i4ui4i24");class ka extends Qt{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(p,_,A,M,F,z){const H=this.length;return this.resize(H+1),this.emplace(H,p,_,A,M,F,z)}emplace(p,_,A,M,F,z,H){const Z=10*p,se=5*p;return this.int16[Z+0]=_,this.int16[Z+1]=A,this.int16[Z+2]=M,this.float32[se+2]=F,this.float32[se+3]=z,this.float32[se+4]=H,p}}ka.prototype.bytesPerElement=20,oa(ka,"StructArrayLayout3i3f20");class Hr extends Qt{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(p,_,A,M){const F=this.length;return this.resize(F+1),this.emplace(F,p,_,A,M)}emplace(p,_,A,M,F){const z=4*p;return this.float32[z+0]=_,this.float32[z+1]=A,this.float32[z+2]=M,this.float32[z+3]=F,p}}Hr.prototype.bytesPerElement=16,oa(Hr,"StructArrayLayout4f16");class ea extends Qt{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint32=new Uint32Array(this.arrayBuffer)}emplaceBack(p){const _=this.length;return this.resize(_+1),this.emplace(_,p)}emplace(p,_){return this.uint32[1*p+0]=_,p}}ea.prototype.bytesPerElement=4,oa(ea,"StructArrayLayout1ul4");class si extends Qt{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(p,_){const A=this.length;return this.resize(A+1),this.emplace(A,p,_)}emplace(p,_,A){const M=2*p;return this.uint16[M+0]=_,this.uint16[M+1]=A,p}}si.prototype.bytesPerElement=4,oa(si,"StructArrayLayout2ui4");class Wr extends Qt{_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(p,_,A,M,F,z,H,Z,se,fe,xe,be,Te){const De=this.length;return this.resize(De+1),this.emplace(De,p,_,A,M,F,z,H,Z,se,fe,xe,be,Te)}emplace(p,_,A,M,F,z,H,Z,se,fe,xe,be,Te,De){const Ue=20*p,Ye=10*p;return this.int16[Ue+0]=_,this.int16[Ue+1]=A,this.int16[Ue+2]=M,this.int16[Ue+3]=F,this.int16[Ue+4]=z,this.float32[Ye+3]=H,this.float32[Ye+4]=Z,this.float32[Ye+5]=se,this.float32[Ye+6]=fe,this.int16[Ue+14]=xe,this.uint32[Ye+8]=be,this.uint16[Ue+18]=Te,this.uint16[Ue+19]=De,p}}Wr.prototype.bytesPerElement=40,oa(Wr,"StructArrayLayout5i4f1i1ul2ui40");class Mr extends Qt{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(p,_,A,M,F,z,H){const Z=this.length;return this.resize(Z+1),this.emplace(Z,p,_,A,M,F,z,H)}emplace(p,_,A,M,F,z,H,Z){const se=8*p;return this.int16[se+0]=_,this.int16[se+1]=A,this.int16[se+2]=M,this.int16[se+4]=F,this.int16[se+5]=z,this.int16[se+6]=H,this.int16[se+7]=Z,p}}Mr.prototype.bytesPerElement=16,oa(Mr,"StructArrayLayout3i2i2i16");class Gr extends Qt{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(p,_,A,M,F){const z=this.length;return this.resize(z+1),this.emplace(z,p,_,A,M,F)}emplace(p,_,A,M,F,z){const H=4*p,Z=8*p;return this.float32[H+0]=_,this.float32[H+1]=A,this.float32[H+2]=M,this.int16[Z+6]=F,this.int16[Z+7]=z,p}}Gr.prototype.bytesPerElement=16,oa(Gr,"StructArrayLayout2f1f2i16");class Ga extends Qt{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(p,_,A,M,F,z){const H=this.length;return this.resize(H+1),this.emplace(H,p,_,A,M,F,z)}emplace(p,_,A,M,F,z,H){const Z=20*p,se=5*p;return this.uint8[Z+0]=_,this.uint8[Z+1]=A,this.float32[se+1]=M,this.float32[se+2]=F,this.float32[se+3]=z,this.float32[se+4]=H,p}}Ga.prototype.bytesPerElement=20,oa(Ga,"StructArrayLayout2ub4f20");class Vr extends Qt{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(p,_,A){const M=this.length;return this.resize(M+1),this.emplace(M,p,_,A)}emplace(p,_,A,M){const F=3*p;return this.uint16[F+0]=_,this.uint16[F+1]=A,this.uint16[F+2]=M,p}}Vr.prototype.bytesPerElement=6,oa(Vr,"StructArrayLayout3ui6");class Za extends Qt{_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(p,_,A,M,F,z,H,Z,se,fe,xe,be,Te,De,Ue,Ye,st,ot,mt,lt,yt){const Nt=this.length;return this.resize(Nt+1),this.emplace(Nt,p,_,A,M,F,z,H,Z,se,fe,xe,be,Te,De,Ue,Ye,st,ot,mt,lt,yt)}emplace(p,_,A,M,F,z,H,Z,se,fe,xe,be,Te,De,Ue,Ye,st,ot,mt,lt,yt,Nt){const as=30*p,Et=15*p,$t=60*p;return this.int16[as+0]=_,this.int16[as+1]=A,this.int16[as+2]=M,this.float32[Et+2]=F,this.float32[Et+3]=z,this.uint16[as+8]=H,this.uint16[as+9]=Z,this.uint32[Et+5]=se,this.uint32[Et+6]=fe,this.uint32[Et+7]=xe,this.uint16[as+16]=be,this.uint16[as+17]=Te,this.uint16[as+18]=De,this.float32[Et+10]=Ue,this.float32[Et+11]=Ye,this.uint8[$t+48]=st,this.uint8[$t+49]=ot,this.uint8[$t+50]=mt,this.uint32[Et+13]=lt,this.int16[as+28]=yt,this.uint8[$t+58]=Nt,p}}Za.prototype.bytesPerElement=60,oa(Za,"StructArrayLayout3i2f2ui3ul3ui2f3ub1ul1i1ub60");class Oi extends Qt{_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(p,_,A,M,F,z,H,Z,se,fe,xe,be,Te,De,Ue,Ye,st,ot,mt,lt,yt,Nt,as,Et,$t,Jt,ns,Ls,Gs,pn,cn,jn,Hn){const Cs=this.length;return this.resize(Cs+1),this.emplace(Cs,p,_,A,M,F,z,H,Z,se,fe,xe,be,Te,De,Ue,Ye,st,ot,mt,lt,yt,Nt,as,Et,$t,Jt,ns,Ls,Gs,pn,cn,jn,Hn)}emplace(p,_,A,M,F,z,H,Z,se,fe,xe,be,Te,De,Ue,Ye,st,ot,mt,lt,yt,Nt,as,Et,$t,Jt,ns,Ls,Gs,pn,cn,jn,Hn,Cs){const Qs=20*p,an=40*p,Ln=80*p;return this.float32[Qs+0]=_,this.float32[Qs+1]=A,this.int16[an+4]=M,this.int16[an+5]=F,this.int16[an+6]=z,this.int16[an+7]=H,this.int16[an+8]=Z,this.int16[an+9]=se,this.int16[an+10]=fe,this.int16[an+11]=xe,this.int16[an+12]=be,this.uint16[an+13]=Te,this.uint16[an+14]=De,this.uint16[an+15]=Ue,this.uint16[an+16]=Ye,this.uint16[an+17]=st,this.uint16[an+18]=ot,this.uint16[an+19]=mt,this.uint16[an+20]=lt,this.uint16[an+21]=yt,this.uint16[an+22]=Nt,this.uint16[an+23]=as,this.uint16[an+24]=Et,this.uint16[an+25]=$t,this.uint16[an+26]=Jt,this.uint16[an+27]=ns,this.uint32[Qs+14]=Ls,this.float32[Qs+15]=Gs,this.float32[Qs+16]=pn,this.float32[Qs+17]=cn,this.float32[Qs+18]=jn,this.uint8[Ln+76]=Hn,this.uint16[an+39]=Cs,p}}Oi.prototype.bytesPerElement=80,oa(Oi,"StructArrayLayout2f9i15ui1ul4f1ub1ui80");class Do extends Qt{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(p,_,A,M,F,z){const H=this.length;return this.resize(H+1),this.emplace(H,p,_,A,M,F,z)}emplace(p,_,A,M,F,z,H){const Z=6*p;return this.float32[Z+0]=_,this.float32[Z+1]=A,this.float32[Z+2]=M,this.float32[Z+3]=F,this.float32[Z+4]=z,this.float32[Z+5]=H,p}}Do.prototype.bytesPerElement=24,oa(Do,"StructArrayLayout6f24");class so extends Qt{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(p,_,A,M,F){const z=this.length;return this.resize(z+1),this.emplace(z,p,_,A,M,F)}emplace(p,_,A,M,F,z){const H=5*p;return this.float32[H+0]=_,this.float32[H+1]=A,this.float32[H+2]=M,this.float32[H+3]=F,this.float32[H+4]=z,p}}so.prototype.bytesPerElement=20,oa(so,"StructArrayLayout5f20");class Vl extends Qt{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(p,_,A,M,F,z,H){const Z=this.length;return this.resize(Z+1),this.emplace(Z,p,_,A,M,F,z,H)}emplace(p,_,A,M,F,z,H,Z){const se=7*p;return this.float32[se+0]=_,this.float32[se+1]=A,this.float32[se+2]=M,this.float32[se+3]=F,this.float32[se+4]=z,this.float32[se+5]=H,this.float32[se+6]=Z,p}}Vl.prototype.bytesPerElement=28,oa(Vl,"StructArrayLayout7f28");class bu extends Qt{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(p,_,A,M,F,z,H,Z,se,fe,xe){const be=this.length;return this.resize(be+1),this.emplace(be,p,_,A,M,F,z,H,Z,se,fe,xe)}emplace(p,_,A,M,F,z,H,Z,se,fe,xe,be){const Te=11*p;return this.float32[Te+0]=_,this.float32[Te+1]=A,this.float32[Te+2]=M,this.float32[Te+3]=F,this.float32[Te+4]=z,this.float32[Te+5]=H,this.float32[Te+6]=Z,this.float32[Te+7]=se,this.float32[Te+8]=fe,this.float32[Te+9]=xe,this.float32[Te+10]=be,p}}bu.prototype.bytesPerElement=44,oa(bu,"StructArrayLayout11f44");class qc extends Qt{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(p,_,A,M,F,z,H,Z,se){const fe=this.length;return this.resize(fe+1),this.emplace(fe,p,_,A,M,F,z,H,Z,se)}emplace(p,_,A,M,F,z,H,Z,se,fe){const xe=9*p;return this.float32[xe+0]=_,this.float32[xe+1]=A,this.float32[xe+2]=M,this.float32[xe+3]=F,this.float32[xe+4]=z,this.float32[xe+5]=H,this.float32[xe+6]=Z,this.float32[xe+7]=se,this.float32[xe+8]=fe,p}}qc.prototype.bytesPerElement=36,oa(qc,"StructArrayLayout9f36");class Ko extends Qt{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(p,_){const A=this.length;return this.resize(A+1),this.emplace(A,p,_)}emplace(p,_,A){const M=2*p;return this.float32[M+0]=_,this.float32[M+1]=A,p}}Ko.prototype.bytesPerElement=8,oa(Ko,"StructArrayLayout2f8");class no extends Qt{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint32=new Uint32Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(p,_,A,M){const F=this.length;return this.resize(F+1),this.emplace(F,p,_,A,M)}emplace(p,_,A,M,F){const z=6*p;return this.uint32[3*p+0]=_,this.uint16[z+2]=A,this.uint16[z+3]=M,this.uint16[z+4]=F,p}}no.prototype.bytesPerElement=12,oa(no,"StructArrayLayout1ul3ui12");class jd extends Qt{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(p){const _=this.length;return this.resize(_+1),this.emplace(_,p)}emplace(p,_){return this.uint16[1*p+0]=_,p}}jd.prototype.bytesPerElement=2,oa(jd,"StructArrayLayout1ui2");class Yh extends Qt{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int8=new Int8Array(this.arrayBuffer)}emplaceBack(p,_,A,M){const F=this.length;return this.resize(F+1),this.emplace(F,p,_,A,M)}emplace(p,_,A,M,F){const z=4*p;return this.int8[z+0]=_,this.int8[z+1]=A,this.int8[z+2]=M,this.int8[z+3]=F,p}}Yh.prototype.bytesPerElement=4,oa(Yh,"StructArrayLayout4b4");class wh extends Qt{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(p,_,A,M,F,z,H,Z,se,fe,xe,be,Te,De,Ue,Ye){const st=this.length;return this.resize(st+1),this.emplace(st,p,_,A,M,F,z,H,Z,se,fe,xe,be,Te,De,Ue,Ye)}emplace(p,_,A,M,F,z,H,Z,se,fe,xe,be,Te,De,Ue,Ye,st){const ot=16*p;return this.float32[ot+0]=_,this.float32[ot+1]=A,this.float32[ot+2]=M,this.float32[ot+3]=F,this.float32[ot+4]=z,this.float32[ot+5]=H,this.float32[ot+6]=Z,this.float32[ot+7]=se,this.float32[ot+8]=fe,this.float32[ot+9]=xe,this.float32[ot+10]=be,this.float32[ot+11]=Te,this.float32[ot+12]=De,this.float32[ot+13]=Ue,this.float32[ot+14]=Ye,this.float32[ot+15]=st,p}}wh.prototype.bytesPerElement=64,oa(wh,"StructArrayLayout16f64");class Hl extends Qt{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(p){const _=this.length;return this.resize(_+1),this.emplace(_,p)}emplace(p,_){return this.int16[1*p+0]=_,p}}Hl.prototype.bytesPerElement=2,oa(Hl,"StructArrayLayout1i2");class fm extends Qt{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer)}emplaceBack(p){const _=this.length;return this.resize(_+1),this.emplace(_,p)}emplace(p,_){return this.uint8[1*p+0]=_,p}}fm.prototype.bytesPerElement=1,oa(fm,"StructArrayLayout1ub1");class bc extends Mt{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]}}bc.prototype.size=40;class rc extends Wr{get(p){return new bc(this,p)}}oa(rc,"CollisionBoxArray");class Oh extends Mt{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(p){this._structArray.uint8[this._pos1+49]=p}get hidden(){return this._structArray.uint8[this._pos1+50]}set hidden(p){this._structArray.uint8[this._pos1+50]=p}get crossTileID(){return this._structArray.uint32[this._pos4+13]}set crossTileID(p){this._structArray.uint32[this._pos4+13]=p}get associatedIconIndex(){return this._structArray.int16[this._pos2+28]}get flipState(){return this._structArray.uint8[this._pos1+58]}set flipState(p){this._structArray.uint8[this._pos1+58]=p}}Oh.prototype.size=60;class Zh extends Za{get(p){return new Oh(this,p)}}oa(Zh,"PlacedSymbolArray");class Ld extends Mt{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(p){this._structArray.uint32[this._pos4+14]=p}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(p){this._structArray.float32[this._pos4+18]=p}get hasIconTextFit(){return this._structArray.uint8[this._pos1+76]}get elevationFeatureIndex(){return this._structArray.uint16[this._pos2+39]}}Ld.prototype.size=80;class _c extends Oi{get(p){return new Ld(this,p)}}oa(_c,"SymbolInstanceArray");class Xh extends $s{getoffsetX(p){return this.float32[1*p+0]}}oa(Xh,"GlyphOffsetArray");class ug extends Hs{getx(p){return this.int16[2*p+0]}gety(p){return this.int16[2*p+1]}}oa(ug,"SymbolLineVertexArray");class Z_ extends Mt{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]}}Z_.prototype.size=12;class t0 extends no{get(p){return new Z_(this,p)}}oa(t0,"FeatureIndexArray");class dj extends si{geta_centroid_pos0(p){return this.uint16[2*p+0]}geta_centroid_pos1(p){return this.uint16[2*p+1]}}oa(dj,"FillExtrusionCentroidArray");class _u extends Mt{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]}}_u.prototype.size=6;class ld extends Fs{get(p){return new _u(this,p)}}oa(ld,"FillExtrusionWallArray");const Fc=Lt([{name:"a_pos",components:2,type:"Int16"}],4),Qh=Lt([{name:"a_road_z_offset",components:1,type:"Float32"}],4),ix=Lt([{name:"a_pos",components:2,type:"Int16"},{name:"a_height",components:1,type:"Float32"}],4),Yu=Lt([{name:"a_pos_normal_3",components:3,type:"Int16"}],4);class Ri{constructor(p=[]){this.segments=p}_prepareSegment(p,_,A,M,F){let z=this.segments.at(-1);return p>Ri.MAX_VERTEX_ARRAY_LENGTH&&Yo(`Max vertices per segment is ${Ri.MAX_VERTEX_ARRAY_LENGTH}: bucket requested ${p}`),(!z||z.vertexLength+p>Ri.MAX_VERTEX_ARRAY_LENGTH||z.sortKey!==M||F!==void 0&&z&&z.batchIndex!==void 0&&z.batchIndex!==F)&&(z={vertexOffset:_,primitiveOffset:A,vertexLength:0,primitiveLength:0},M!==void 0&&(z.sortKey=M),F!==void 0&&(z.batchIndex=F),this.segments.push(z)),z}prepareSegment(p,_,A,M,F){return this._prepareSegment(p,_.length,A.length,M,F)}get(){return this.segments}destroy(){for(const p of this.segments)for(const _ in p.vaos)p.vaos[_].destroy()}static simpleSegment(p,_,A,M){return new Ri([{vertexOffset:p,primitiveOffset:_,vertexLength:A,primitiveLength:M,vaos:{},sortKey:0}])}}function Nm(N,p){return 256*(N=ta(Math.floor(N),0,255))+ta(Math.floor(p),0,255)}Ri.MAX_VERTEX_ARRAY_LENGTH=Math.pow(2,16)-1,oa(Ri,"SegmentVector");const hg=Lt([{name:"a_pattern",components:4,type:"Uint16"},{name:"a_pixel_ratio",components:1,type:"Float32"}]),uj=Lt([{name:"a_pattern_b",components:4,type:"Uint16"}]),hj=Lt([{name:"a_dash",components:4,type:"Uint16"}]);class Ub{constructor(){this.ids=[],this.uniqueIds=[],this.positions=[],this.indexed=!1}add(p,_,A,M){this.ids.push(qb(p)),this.positions.push(_,A,M)}eachPosition(p,_){const A=qb(p);let M=0,F=this.ids.length-1;for(;M>1;this.ids[z]>=A?F=z:M=z+1}for(;this.ids[M]===A;)_(this.positions[3*M],this.positions[3*M+1],this.positions[3*M+2]),M++}static serialize(p,_){const A=new Float64Array(p.ids),M=new Uint32Array(p.positions);return nN(A,M,0,A.length-1),_&&(_.add(A.buffer),_.add(M.buffer)),{ids:A,positions:M}}static deserialize(p){const _=new Ub;let A;_.ids=p.ids,_.positions=p.positions;for(const M of _.ids)M!==A&&_.uniqueIds.push(M),A=M;return _.indexed=!0,_}}function qb(N){const p=+N;return Number.isSafeInteger(p)?p:hd(String(N))}function nN(N,p,_,A){for(;_>1];let F=_-1,z=A+1;for(;;){do F++;while(N[F]M);if(F>=z)break;Vb(N,F,z),Vb(p,3*F,3*z),Vb(p,3*F+1,3*z+1),Vb(p,3*F+2,3*z+2)}z-_`u_${F}`),this.type=A,this.context=M}setUniform(p,_,A,M,F){const z=M.constantOr(this.value);_.set(p,F,z instanceof Ci?z.toPremultipliedRenderColor(this.lutExpression&&this.lutExpression.kind==="constant"&&this.lutExpression.value==="none"?null:this.context.lut):z)}getBinding(p,_){return this.type==="color"?new J6(p):new co(p)}}class CY{constructor(p,_){this.uniformNames=_.map(A=>`u_${A}`),this.pattern=null,this.patternTransition=null,this.pixelRatio=1}setConstantPatternPositions(p,_){this.pixelRatio=p.pixelRatio||1,this.pattern=p.tl.concat(p.br),this.patternTransition=_?_.tl.concat(_.br):this.pattern}setUniform(p,_,A,M,F){let z=null;F!=="u_pattern"&&F!=="u_dash"||(z=this.pattern),F==="u_pattern_b"&&(z=this.patternTransition),F==="u_pixel_ratio"&&(z=this.pixelRatio),z&&_.set(p,F,z)}getBinding(p,_){return _==="u_pattern"||_==="u_pattern_b"||_==="u_dash"?new SY(p):new co(p)}}class z3{constructor(p,_,A,M){this.expression=p,this.type=A,this.maxValue=0,this.paintVertexAttributes=_.map(F=>({name:`a_${F}`,type:"Float32",components:A==="color"?2:1,offset:0})),this.paintVertexArray=new M}populatePaintArray(p,_,A,M,F,z,H,Z){const se=this.paintVertexArray.length,fe=this.expression.kind==="composite"||this.expression.kind==="source"?this.expression.evaluate(new Kn(0,{brightness:z,worldview:Z}),_,{},F,M,H):this.expression.kind==="constant"&&this.expression.value,xe=$9(this.lutExpression,_,{},M,F,z,H,Z);this.paintVertexArray.resize(p),this._setPaintValue(se,p,fe,xe?null:this.context.lut)}updatePaintArray(p,_,A,M,F,z,H,Z){const se=this.expression.kind==="composite"||this.expression.kind==="source"?this.expression.evaluate({zoom:0,brightness:H,worldview:Z},A,M,void 0,F):this.expression.kind==="constant"&&this.expression.value,fe=$9(this.lutExpression,A,M,F,void 0,H,void 0,Z);this._setPaintValue(p,_,se,fe?null:this.context.lut)}_setPaintValue(p,_,A,M){if(this.type==="color"){const F=B9(A.toPremultipliedRenderColor(M));for(let z=p;z<_;z++)this.paintVertexArray.emplace(z,F[0],F[1])}else{for(let F=p;F<_;F++)this.paintVertexArray.emplace(F,A);this.maxValue=Math.max(this.maxValue,Math.abs(A))}}upload(p){this.paintVertexArray&&this.paintVertexArray.arrayBuffer&&(this.paintVertexBuffer&&this.paintVertexBuffer.buffer?this.paintVertexBuffer.updateData(this.paintVertexArray):this.paintVertexBuffer=p.createVertexBuffer(this.paintVertexArray,this.paintVertexAttributes,this.lutExpression&&this.lutExpression.kind!=="constant"&&(this.lutExpression.isStateDependent||!this.lutExpression.isLightConstant)||this.expression.kind!=="constant"&&(this.expression.isStateDependent||!this.expression.isLightConstant)))}destroy(){this.paintVertexBuffer&&this.paintVertexBuffer.destroy()}}class HC{constructor(p,_,A,M,F,z){this.expression=p,this.uniformNames=_.map(H=>`u_${H}_t`),this.type=A,this.useIntegerZoom=M,this.context=F,this.maxValue=0,this.paintVertexAttributes=_.map(H=>({name:`a_${H}`,type:"Float32",components:A==="color"?4:2,offset:0})),this.paintVertexArray=new z}populatePaintArray(p,_,A,M,F,z,H,Z){const se=this.expression.evaluate(new Kn(this.context.zoom,{brightness:z,worldview:Z}),_,{},F,M,H),fe=this.expression.evaluate(new Kn(this.context.zoom+1,{brightness:z,worldview:Z}),_,{},F,M,H),xe=$9(this.lutExpression,_,{},M,F,z,H,Z),be=this.paintVertexArray.length;this.paintVertexArray.resize(p),this._setPaintValue(be,p,se,fe,xe?null:this.context.lut)}updatePaintArray(p,_,A,M,F,z,H,Z){const se=this.expression.evaluate({zoom:this.context.zoom,brightness:H,worldview:Z},A,M,void 0,F),fe=this.expression.evaluate({zoom:this.context.zoom+1,brightness:H,worldview:Z},A,M,void 0,F),xe=$9(this.lutExpression,A,M,F,void 0,H,void 0,Z);this._setPaintValue(p,_,se,fe,xe?null:this.context.lut)}_setPaintValue(p,_,A,M,F){if(this.type==="color"){const z=B9(A.toPremultipliedRenderColor(F)),H=B9(M.toPremultipliedRenderColor(F));for(let Z=p;Z<_;Z++)this.paintVertexArray.emplace(Z,z[0],z[1],H[0],H[1])}else{for(let z=p;z<_;z++)this.paintVertexArray.emplace(z,A,M);this.maxValue=Math.max(this.maxValue,Math.abs(A),Math.abs(M))}}upload(p){this.paintVertexArray&&this.paintVertexArray.arrayBuffer&&(this.paintVertexBuffer&&this.paintVertexBuffer.buffer?this.paintVertexBuffer.updateData(this.paintVertexArray):this.paintVertexBuffer=p.createVertexBuffer(this.paintVertexArray,this.paintVertexAttributes,this.expression.isStateDependent||!this.expression.isLightConstant))}destroy(){this.paintVertexBuffer&&this.paintVertexBuffer.destroy()}setUniform(p,_,A,M,F){const z=this.useIntegerZoom?Math.floor(A.zoom):A.zoom,H=ta(this.expression.interpolationFactor(z,this.context.zoom,this.context.zoom+1),0,1);_.set(p,F,H)}getBinding(p,_){return new co(p)}}class GC{constructor(p,_,A,M,F){this.expression=p,this.layerId=F,this.paintVertexAttributes=(A==="array"?hj:hg).members;for(let z=0;z<_.length;++z);this.paintVertexArray=new M,this.paintTransitionVertexArray=new An}populatePaintArray(p,_,A,M){const F=this.paintVertexArray.length;this.paintVertexArray.resize(p),this._setPaintValues(F,p,_.patterns&&_.patterns[this.layerId],A)}updatePaintArray(p,_,A,M,F,z,H){this._setPaintValues(p,_,A.patterns&&A.patterns[this.layerId],z)}_setPaintValues(p,_,A,M){if(!M||!A)return;const F=M[A[0]],z=M[A[1]];if(F){if(F){const{tl:H,br:Z,pixelRatio:se}=F;for(let fe=p;fe<_;fe++)this.paintVertexArray.emplace(fe,H[0],H[1],Z[0],Z[1],se)}if(z){this.paintTransitionVertexArray.resize(this.paintVertexArray.length);const{tl:H,br:Z}=z;for(let se=p;se<_;se++)this.paintTransitionVertexArray.emplace(se,H[0],H[1],Z[0],Z[1])}}}upload(p){const _=this.expression.isStateDependent||!this.expression.isLightConstant;this.paintVertexArray&&this.paintVertexArray.arrayBuffer&&(this.paintVertexBuffer=p.createVertexBuffer(this.paintVertexArray,this.paintVertexAttributes,_)),this.paintTransitionVertexArray&&this.paintTransitionVertexArray.length&&(this.paintTransitionVertexBuffer=p.createVertexBuffer(this.paintTransitionVertexArray,uj.members,_))}destroy(){this.paintVertexBuffer&&this.paintVertexBuffer.destroy(),this.paintTransitionVertexBuffer&&this.paintTransitionVertexBuffer.destroy()}}class tR{constructor(p,_,A=()=>!0){this.binders={},this._buffers=[],this.context=_;const M=[],F=p;for(const z in p.paint._values){const H=F.paint.get(z);if(z.endsWith("-use-theme")||!A(z)||!(H instanceof _h&&Xy(H.property.specification)))continue;const Z=ths(z,p.type),se=H.value,fe=H.property.specification.type,xe=!!H.property.useIntegerZoom,be=z==="line-dasharray"||z.endsWith("pattern"),Te=F.paint.get(`${z}-use-theme`),De=z==="line-dasharray"&&F.layout.get("line-cap").value.kind!=="constant"||Te&&Te.value.kind!=="constant";if(se.kind!=="constant"||De)if(se.kind==="source"||De||be){const Ue=cdt(z,fe,"source");this.binders[z]=be?new GC(se,Z,fe,Ue,p.id):new z3(se,Z,fe,Ue),M.push(`/a_${z}`)}else{const Ue=cdt(z,fe,"composite");this.binders[z]=new HC(se,Z,fe,xe,_,Ue),M.push(`/z_${z}`)}else this.binders[z]=be?new CY(se.value,Z):new Toe(se.value,Z,fe,_),M.push(`/u_${z}`);Te&&(this.binders[z].lutExpression=Te.value)}this.cacheKey=M.sort().join("")}updateExpressions(p){const _=p;for(const A in this.binders){const M=this.binders[A];if(M instanceof z3||M instanceof HC||M instanceof GC){const F=_.paint.get(A);M.expression=F.value}}}getMaxValue(p){const _=this.binders[p];return _ instanceof z3||_ instanceof HC?_.maxValue:0}populatePaintArrays(p,_,A,M,F,z,H,Z){for(const se in this.binders){const fe=this.binders[se];fe.context=this.context,(fe instanceof z3||fe instanceof HC||fe instanceof GC)&&fe.populatePaintArray(p,_,A,M,F,z,H,Z)}}setConstantPatternPositions(p,_){for(const A in this.binders){const M=this.binders[A];M instanceof CY&&M.setConstantPatternPositions(p,_)}}getPatternTransitionVertexBuffer(p){const _=this.binders[p];return _ instanceof GC?_.paintTransitionVertexBuffer:null}updatePaintArrays(p,_,A,M,F,z,H,Z,se,fe){let xe=!1;const be=Object.keys(p),Te=be.length!==0&&!Z,De=Te?be:_.uniqueIds;this.context.lut=F.lut;for(const Ue in this.binders){const Ye=this.binders[Ue];if(Ye.context=this.context,(Ye instanceof z3||Ye instanceof HC||Ye instanceof GC)&&Ye.expression&&Ye.expression.kind&&Ye.expression.kind!=="constant"&&(Ye.expression.isStateDependent===!0||Ye.expression.isLightConstant===!1)){const st=F.paint.get(Ue);Ye.expression=st.value;for(const ot of De){const mt=p[ot.toString()];_.eachPosition(ot,(lt,yt,Nt)=>{const as=M.feature(lt);Ye.updatePaintArray(yt,Nt,as,mt,z,H,se,fe)})}if(!Te)for(const ot of A.uniqueIds){const mt=p[ot.toString()];A.eachPosition(ot,(lt,yt,Nt)=>{const as=M.feature(lt);Ye.updatePaintArray(yt,Nt,as,mt,z,H,se,fe)})}xe=!0}}return xe}defines(){const p=[];for(const _ in this.binders){const A=this.binders[_];(A instanceof Toe||A instanceof CY)&&p.push(...A.uniformNames.map(M=>`#define HAS_UNIFORM_${M}`))}return p}getPaintVertexBuffers(){return this._buffers}getUniforms(p){const _=[];for(const A in this.binders){const M=this.binders[A];if(M instanceof Toe||M instanceof CY||M instanceof HC)for(const F of M.uniformNames)_.push({name:F,property:A,binding:M.getBinding(p,F)})}return _}setUniforms(p,_,A,M,F){for(const{name:z,property:H,binding:Z}of A)this.binders[H].setUniform(p,Z,F,M.get(H),z)}updatePaintBuffers(){this._buffers=[];for(const p in this.binders){const _=this.binders[p];(_ instanceof z3||_ instanceof HC||_ instanceof GC)&&_.paintVertexBuffer&&this._buffers.push(_.paintVertexBuffer),_ instanceof GC&&_.paintTransitionVertexBuffer&&this._buffers.push(_.paintTransitionVertexBuffer)}}upload(p){for(const _ in this.binders){const A=this.binders[_];(A instanceof z3||A instanceof HC||A instanceof GC)&&A.upload(p)}this.updatePaintBuffers()}destroy(){for(const p in this.binders){const _=this.binders[p];(_ instanceof z3||_ instanceof HC||_ instanceof GC)&&_.destroy()}}}class Yk{constructor(p,_,A=()=>!0){this.programConfigurations={};for(const M of p)this.programConfigurations[M.id]=new tR(M,_,A);this.needsUpload=!1,this._featureMap=new Ub,this._featureMapWithoutIds=new Ub,this._bufferOffset=0,this._idlessCounter=0}populatePaintArrays(p,_,A,M,F,z,H,Z,se){for(const fe in this.programConfigurations)this.programConfigurations[fe].populatePaintArrays(p,_,M,F,z,H,Z,se);_.id!==void 0?this._featureMap.add(_.id,A,this._bufferOffset,p):(this._featureMapWithoutIds.add(this._idlessCounter,A,this._bufferOffset,p),this._idlessCounter+=1),this._bufferOffset=p,this.needsUpload=!0}updatePaintArrays(p,_,A,M,F,z,H,Z){for(const se of A)this.needsUpload=this.programConfigurations[se.id].updatePaintArrays(p,this._featureMap,this._featureMapWithoutIds,_,se,M,F,z,H||0,Z)||this.needsUpload}get(p){return this.programConfigurations[p]}upload(p){if(this.needsUpload){for(const _ in this.programConfigurations)this.programConfigurations[_].upload(p);this.needsUpload=!1}}destroy(){for(const p in this.programConfigurations)this.programConfigurations[p].destroy()}updateExpressions(p){const _=new Set;for(const A of p){const M=this.programConfigurations[A.id];M&&(M.updateExpressions(A),_.add(A.id))}for(const A in this.programConfigurations)_.has(A)||delete this.programConfigurations[A]}}const ehs={"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 ths(N,p){return ehs[N]||[N.replace(`${p}-`,"").replace(/-/g,"_")]}const shs={"line-pattern":{source:Dr,composite:Dr},"fill-pattern":{source:Dr,composite:Dr},"fill-extrusion-pattern":{source:Dr,composite:Dr},"line-dasharray":{source:An,composite:An}},nhs={color:{source:Ko,composite:Hr},number:{source:$s,composite:Ko}};function cdt(N,p,_){const A=shs[N];return A&&A[_]||nhs[p][_]}oa(Toe,"ConstantBinder"),oa(CY,"PatternConstantBinder"),oa(z3,"SourceExpressionBinder",{omit:["expression"]}),oa(GC,"PatternCompositeBinder",{omit:["expression"]}),oa(HC,"CompositeExpressionBinder",{omit:["expression"]}),oa(tR,"ProgramConfiguration",{omit:["_buffers"]}),oa(Yk,"ProgramConfigurationSet");class GFe{constructor(p,_,A){this.layoutVertexArray=new Hs,this.indexArray=new Vr,this.lineIndexArray=new si,this.triangleSegments=new Ri,this.lineSegments=new Ri,this.programConfigurations=new Yk(p,{zoom:_,lut:A}),this.uploaded=!1}update(p,_,A,M,F,z,H,Z){this.programConfigurations.updatePaintArrays(p,_,F,A,M,z,H,Z)}isEmpty(){return this.layoutVertexArray.length===0}needsUpload(){return this.programConfigurations.needsUpload}upload(p){this.uploaded||(this.layoutVertexBuffer=p.createVertexBuffer(this.layoutVertexArray,Fc.members),this.indexBuffer=p.createIndexBuffer(this.indexArray),this.lineIndexBuffer=p.createIndexBuffer(this.lineIndexArray)),this.programConfigurations.upload(p),this.uploaded=!0}destroy(){this.layoutVertexBuffer&&(this.layoutVertexBuffer.destroy(),this.indexBuffer.destroy(),this.lineIndexBuffer.destroy(),this.programConfigurations.destroy(),this.triangleSegments.destroy(),this.lineSegments.destroy())}populatePaintArrays(p,_,A,M,F,z,H){this.programConfigurations.populatePaintArrays(this.layoutVertexArray.length,p,_,A,M,F,z,void 0,H)}}oa(GFe,"FillBufferData");class WFe{constructor(p){this.zoom=p.zoom,this.pixelRatio=p.pixelRatio,this.overscaling=p.overscaling,this.layers=p.layers,this.layerIds=this.layers.map(_=>_.fqid),this.index=p.index,this.hasPattern=!1,this.patternFeatures=[],this.lut=p.lut,this.bufferData=new GFe(p.layers,p.zoom,p.lut),this.stateDependentLayerIds=this.layers.filter(_=>_.isStateDependent()).map(_=>_.id),this.projection=p.projection,this.sourceLayerIndex=p.sourceLayerIndex,this.sourceLayerName=p.sourceLayerName||"",this.worldview=p.worldview,this.hasAppearances=null}updateFootprints(p,_){}updateAppearances(p,_,A,M){return{hasLayoutChanges:!1,hasUboChanges:!1}}populate(p,_,A,M){this.hasPattern=X6("fill",this.layers,this.pixelRatio,_);const F=this.layers[0].layout.get("fill-sort-key"),z=[];for(const{feature:H,id:Z,index:se,sourceLayerIndex:fe}of p){const xe=this.layers[0]._featureFilter.needGeometry,be=_t(H,xe);if(!this.layers[0]._featureFilter.filter(new Kn(this.zoom,{worldview:this.worldview,activeFloors:_.activeFloors}),be,A))continue;const Te=F?F.evaluate(be,{},A,_.availableImages):void 0,De={id:Z,properties:H.properties,type:H.type,sourceLayerIndex:fe,index:se,geometry:xe?be.geometry:ht(H,A,M),patterns:{},sortKey:Te};z.push(De)}F&&z.sort((H,Z)=>H.sortKey-Z.sortKey);for(const H of z){const{geometry:Z,index:se,sourceLayerIndex:fe}=H;if(this.hasPattern){const xe=jY("fill",this.layers,H,this.zoom,this.pixelRatio,_);this.patternFeatures.push(xe)}else this.addFeature(H,Z,se,A,{},_.availableImages,_.brightness,_.elevationFeatures);_.featureIndex.insert(p[se].feature,Z,se,fe,this.index)}!this.hasPattern&&this.hdExt&&this.hdExt.buildFrcSegments(this)}update(p,_,A,M,F,z,H){this.bufferData.update(p,_,A,M,F,z,H,this.worldview),this.hdExt&&this.hdExt.update(p,_,A,M,F,z,H,this.worldview)}updateExpressions(p){this.bufferData.programConfigurations.updateExpressions(p),this.hdExt&&this.hdExt.updateExpressions(p)}addFeatures(p,_,A,M,F,z){for(const H of this.patternFeatures)this.addFeature(H,H.geometry,H.index,_,A,M,z,p.elevationFeatures);this.hdExt&&this.hdExt.buildFrcSegments(this)}isEmpty(){return this.bufferData.isEmpty()&&(!this.hdExt||this.hdExt.isEmpty())}uploadPending(){return!this.uploaded||this.bufferData.needsUpload()||this.hdExt!=null&&this.hdExt.needsUpload()}upload(p){this.bufferData.upload(p),this.hdExt&&this.hdExt.upload(p)}destroy(){this.bufferData.destroy(),this.hdExt&&this.hdExt.destroy()}addFeature(p,_,A,M,F,z=[],H,Z){const se=this.hdExt?this.hdExt.trackFeatureFrc(p.properties):null,fe=this.bufferData.indexArray.length,xe=Pa(_,500);this.hdExt!=null&&this.hdExt.handleFeature(p,xe,A,M,Z,this)||this.addGeometry(xe,this.bufferData),this.bufferData.populatePaintArrays(p,A,F,z,M,H,this.worldview),this.hdExt&&this.hdExt.populatePaintArrays(p,A,F,z,M,H,this.worldview),this.hdExt&&this.hdExt.recordFeatureRange(this,fe,this.bufferData.indexArray.length,se)}addGeometry(p,_,A,M){let F=Number.POSITIVE_INFINITY,z=Number.NEGATIVE_INFINITY,H=null;A&&(H=A.elevationSampler.constantElevation(A.elevation,A.bias),H!=null&&(F=H,z=H));const Z=A?_:null,se=(fe,xe,be)=>{if(A!=null)if(xe.push(fe),H!=null)Z.elevatedLayoutVertexArray.emplaceBack(H),be.push(H);else{const Te=A.elevationSampler.pointElevation(fe,A.elevation,A.bias);Z.elevatedLayoutVertexArray.emplaceBack(Te),be.push(Te),F=Math.min(F,Te),z=Math.max(z,Te)}};for(const fe of p){let xe=0;for(const yt of fe)xe+=yt.length;const be=_.triangleSegments.prepareSegment(xe,_.layoutVertexArray,_.indexArray),Te=be.vertexLength,De=[],Ue=[],Ye=[],st=[],ot=[],mt=_.layoutVertexArray.length;for(const yt of fe){if(yt.length===0)continue;yt!==fe[0]&&Ue.push(De.length/2);const Nt=_.lineSegments.prepareSegment(yt.length,_.layoutVertexArray,_.lineIndexArray),as=Nt.vertexLength;A&&ot.push(_.layoutVertexArray.length-mt),se(yt[0],Ye,st),_.layoutVertexArray.emplaceBack(yt[0].x,yt[0].y),_.lineIndexArray.emplaceBack(as+yt.length-1,as),De.push(yt[0].x),De.push(yt[0].y);for(let Et=1;Et0&&A&&M){const yt=A.elevation.isTunnel(),Nt=A.elevation.safeArea,as=M.addVertices(Ye,st);M.addTriangles(lt,as,yt);const Et=ot.length;if(Et>0){for(let $t=0;$t>3,z===0)continue}if(z--,F===1)H+=p.readSVarint(),Z+=p.readSVarint(),M&&A.push(M),M=[new xs(H,Z)];else if(F===2)H+=p.readSVarint(),Z+=p.readSVarint(),M&&M.push(new xs(H,Z));else{if(F!==7)throw new Error(`unknown command ${F}`);M&&M.push(M[0].clone())}}return M&&A.push(M),A}bbox(){if(this._geometry<0)throw new Error("feature has no geometry");const p=this._pbf;p.pos=this._geometry;const _=p.readVarint()+p.pos;let A=1,M=0,F=0,z=0,H=1/0,Z=-1/0,se=1/0,fe=-1/0;for(;p.pos<_;){if(M<=0){const xe=p.readVarint();if(A=7&xe,M=xe>>3,M===0)continue}if(M--,A===1||A===2)F+=p.readSVarint(),z+=p.readSVarint(),FZ&&(Z=F),zfe&&(fe=z);else if(A!==7)throw new Error(`unknown command ${A}`)}return[H,se,Z,fe]}toGeoJSON(p,_,A){const M=this.extent*Math.pow(2,A),F=this.extent*p,z=this.extent*_,H=this.loadGeometry();function Z(be){return[360*(be.x+F)/M-180,360/Math.PI*Math.atan(Math.exp((1-2*(be.y+z)/M)*Math.PI))-90]}function se(be){return be.map(Z)}let fe;if(this.type===1){const be=[];for(const De of H)be.push(De[0]);const Te=se(be);fe=be.length===1?{type:"Point",coordinates:Te[0]}:{type:"MultiPoint",coordinates:Te}}else if(this.type===2){const be=H.map(se);fe=be.length===1?{type:"LineString",coordinates:be[0]}:{type:"MultiLineString",coordinates:be}}else{if(this.type!==3)throw new Error("unknown feature type");{const be=function(De){const Ue=De.length;if(Ue<=1)return[De];const Ye=[];let st,ot;for(let mt=0;mt=this._features.length)throw new Error("feature index out of bounds");this._pbf.pos=this._features[p];const _=this._pbf.readVarint()+this._pbf.pos;return new rM(this._pbf,_,this.extent,this._keys,this._values)}}function phs(N){let p=null;const _=N.readVarint()+N.pos;for(;N.pos<_;){const A=N.readVarint();p=A===10?N.readString():A===21?N.readFloat():A===25?N.readDouble():A===32?N.readVarint(!0):A===40?N.readVarint():A===48?N.readSVarint():A===56?N.readBoolean():(N.skip(A),null)}if(p==null)throw new Error("unknown feature value");return p}class KFe{constructor(p,_=p.length){const A=Object.create(null);for(;p.pos<_;){const M=p.readVarint();if(M===26){const F=new fhs(p,p.readVarint()+p.pos);F.length&&(A[F.name]=F)}else p.skip(M)}this.layers=A}}function YFe(N,p){for(let _=0;_1){if(XFe(N,p))return!0;for(let A=0;A1?_:_.sub(p)._mult(M)._add(p))}function udt(N,p){let _,A,M,F=!1;for(let z=0;zp.y!=M.y>p.y&&p.x<(M.x-A.x)*(p.y-A.y)/(M.y-A.y)+A.x&&(F=!F)}return F}function aM(N,p){let _=!1;for(let A=0,M=N.length-1;Ap.y!=z.y>p.y&&p.x<(z.x-F.x)*(p.y-F.y)/(z.y-F.y)+F.x&&(_=!_)}return _}function eOe(N,p,_,A,M){for(const z of N)if(p<=z.x&&_<=z.y&&A>=z.x&&M>=z.y)return!0;const F=[new xs(p,_),new xs(p,M),new xs(A,M),new xs(A,_)];if(N.length>2){for(const z of F)if(aM(N,z))return!0}for(let z=0;zM.x&&p.x>M.x||N.yM.y&&p.y>M.y)return!1;const F=Ic(N,p,_[0]);return F!==Ic(N,p,_[1])||F!==Ic(N,p,_[2])||F!==Ic(N,p,_[3])}function q9(N,p,_,A,M,F){let z=p.y-N.y,H=N.x-p.x;if(F=F||0){const Z=z*z+H*H;if(Z===0)return!0;const se=Math.sqrt(Z);z/=se,H/=se}return!((_.x-N.x)*z+(_.y-N.y)*H-F<0||(A.x-N.x)*z+(A.y-N.y)*H-F<0||(M.x-N.x)*z+(M.y-N.y)*H-F<0)}function tOe(N,p,_,A,M,F,z){return!(q9(N,p,A,M,F,z)||q9(p,_,A,M,F,z)||q9(_,N,A,M,F,z)||q9(A,M,N,p,_,z)||q9(M,F,N,p,_,z)||q9(F,A,N,p,_,z))}class sR extends xs{constructor(p,_,A){super(p,_),this.z=A}}class hdt extends sR{constructor(p,_,A,M){super(p,_,A),this.w=M}}function mdt(N,p,_,A){const M=_==="x"?"y":"x",F=(A-N[_])/(p[_]-N[_]);N[M]=Math.round(N[M]+(p[M]-N[M])*F),N[_]=A,Object.hasOwn(N,"z")&&(N.z=ya(N.z,p.z,F)),Object.hasOwn(N,"w")&&(N.w=ya(N.w,p.w,F))}function fdt(N,p,_,A){const M=_,F=A;for(const z of["x","y"]){let H=N,Z=p;H[z]>=Z[z]&&(H=p,Z=N),H[z]M&&mdt(H,Z,z,M),H[z]F&&mdt(Z,H,z,F)}}function sOe(N,p,_,A,M,F){const z=[];for(let H=0;H=A&&De.x>=A||(Te.x>=A?Te=new xs(A,Te.y+(A-Te.x)/(De.x-Te.x)*(De.y-Te.y))._round():De.x>=A&&(De=new xs(A,Te.y+(A-Te.x)/(De.x-Te.x)*(De.y-Te.y))._round()),Te.y>=M&&De.y>=M||(Te.y>=M?Te=new xs(Te.x+(M-Te.y)/(De.y-Te.y)*(De.x-Te.x),M)._round():De.y>=M&&(De=new xs(Te.x+(M-Te.y)/(De.y-Te.y)*(De.x-Te.x),M)._round()),se&&Te.equals(se.at(-1))||(se=[Te],z.push(se),F&&F.push({progress:{min:Ye+pdt(st,ot,Te)*Ue,max:1},parentIndex:H,prevPoint:st,nextPoint:ot})),se.push(De),F&&(F.at(-1).progress.max=Ye+pdt(st,ot,De)*Ue,F.at(-1).nextPoint=ot)))))}if(F&&xe>0)for(let be=fe;bese.t-fe.t);let z=0,H=0,Z=[];for(A.push(Z);z!==N.length;){if(H===F.length){for(;z!==N.length;)Z.length!==0&&Z.at(-1).equals(N[z])||Z.push(N[z]),z++;break}F[H].t<=z?(Z.length!==0&&Z.at(-1).equals(F[H].point)||Z.push(F[H].point),Math.trunc(F[H].t),H++):(Z.length!==0&&Z.at(-1).equals(N[z])||Z.push(N[z]),z++)}}function pdt(N,p,_){return N.x!==p.x?(_.x-N.x)/(p.x-N.x):N.y!==p.y?(_.y-N.y)/(p.y-N.y):0}function gdt(N,{width:p,height:_},A,M){if(M){if(M instanceof Uint8ClampedArray)M=new Uint8Array(M.buffer);else if(M.length!==p*_*A)throw new RangeError("mismatched image size")}else M=new Uint8Array(p*_*A);return N.width=p,N.height=_,N.data=M,N}function xdt(N,p,_){const{width:A,height:M}=p;A===N.width&&M===N.height||(nOe(N,p,{x:0,y:0},{x:0,y:0},{width:Math.min(N.width,A),height:Math.min(N.height,M)},_,null),N.width=A,N.height=M,N.data=p.data)}function nOe(N,p,_,A,M,F,z,H){if(M.width===0||M.height===0)return p;if(M.width>N.width||M.height>N.height||_.x>N.width-M.width||_.y>N.height-M.height)throw new RangeError("out of range source coordinates for image copy");if(M.width>p.width||M.height>p.height||A.x>p.width-M.width||A.y>p.height-M.height)throw new RangeError("out of range destination coordinates for image copy");const Z=N.data,se=p.data,fe=F===4&&H;for(let xe=0;xe1&&(Z=p[++H]);const fe=Math.abs(se-Z.left),xe=Math.abs(se-Z.right),be=Math.min(fe,xe);let Te;const De=F/A*(M+1);if(Z.isDash){const Ue=M-Math.abs(De);Te=Math.sqrt(be*be+Ue*Ue)}else Te=M-Math.sqrt(be*be+De*De);this.image.data[z+se]=Math.max(0,Math.min(255,Te+128))}}}addRegularDash(p,_){for(let Z=p.length-1;Z>=0;--Z){const se=p[Z],fe=p[Z+1];se.zeroLength?p.splice(Z,1):fe&&fe.isDash===se.isDash&&(fe.left=se.left,p.splice(Z,1))}const A=p[0],M=p.at(-1);A.isDash===M.isDash&&(A.left=M.left-this.width,M.right=A.right+this.width);const F=this.width*this.nextRow;let z=0,H=p[z];for(let Z=0;Z1&&(H=p[++z]);const se=Math.abs(Z-H.left),fe=Math.abs(Z-H.right),xe=Math.min(se,fe);this.image.data[F+Z]=Math.max(0,Math.min(255,(H.isDash?xe:-xe)+_+128))}}addDash(p,_){const A=this.getKey(p,_);if(this.positions[A])return this.positions[A];const M=_==="round",F=M?7:0,z=2*F+1;if(this.nextRow+z>this.height)return Yo("LineAtlas out of space"),null;p.length===0&&p.push(1);let H=0;for(let Te=0;Te=128&&se++}const fe=Math.round(se/this.width*4095);this.nextRow+=z;const xe=Math.floor(H),be={tl:[Z,F|fe<<4],br:[xe,Math.round(65535*(H-xe))]};return this.positions[A]=be,be}}oa(vdt,"LineAtlas");const B3="3d_elevation_id",bdt="level",_hs=rM.types,whs=Math.cos(Math.PI/180*37.5),jhs=Math.cos(Math.PI/180*5);class rOe{constructor(p){this.evaluationGlobals={zoom:0,lineProgress:void 0},this.elevationType="none",this.isSeaLevelReference=!1,this.showElevationIdDebug=!1,this.terrainEnabled=!1,this.zoom=p.zoom,this.evaluationGlobals.zoom=this.zoom,this.overscaling=p.overscaling,this.pixelRatio=p.pixelRatio,this.layers=p.layers,this.layerIds=this.layers.map(_=>_.fqid),this.index=p.index,this.projection=p.projection,this.hasPattern=!1,this.hasCrossSlope=!1,this.patternFeatures=[],this.lineClipsArray=[],this.gradients={},this.borderGradients={},this.layers.forEach(_=>{this.gradients[_.id]={},this.borderGradients[_.id]={}}),this.layoutVertexArray=new $n,this.layoutVertexArray2=new zn,this.patternVertexArray=new zn,this.indexArray=new Vr,this.programConfigurations=new Yk(p.layers,{zoom:p.zoom,lut:p.lut}),this.segments=new Ri,this.sourceLayerName=p.sourceLayerName||"",this.maxLineLength=0,this.zOffsetVertexArray=new Hr,this.elevationIdColVertexArray=new zn,this.elevationGroundScaleVertexArray=new $s,this.stateDependentLayerIds=this.layers.filter(_=>_.isStateDependent()).map(_=>_.id),this.tessellationStep=p.tessellationStep?p.tessellationStep:128,this.worldview=p.worldview,this.hasAppearances=null}updateFootprints(p,_){}updateAppearances(p,_,A,M){return{hasLayoutChanges:!1,hasUboChanges:!1}}populate(p,_,A,M){this.showElevationIdDebug=_.showElevationIdDebug,this.terrainEnabled=_.terrainEnabled,this.hasPattern=X6("line",this.layers,this.pixelRatio,_);const F=this.layers[0].layout.get("line-sort-key");this.tileToMeter=K(A);const z=this.layers[0].layout.get("line-elevation-reference");if(z==="hd-road-markup")this.elevationType="road";else{const be=this.layers[0].layout.get("line-z-offset"),Te=be.isConstant()&&!be.constantOr(0);this.elevationType=z!=="sea"&&z!=="ground"&&Te?"none":"offset",this.elevationType==="offset"&&z==="none"&&Yo(`line-elevation-reference: ground is used for the layer ${this.layerIds[0]} because non-zero line-z-offset value was found.`),this.isSeaLevelReference=z==="sea"}const H=this.layers[0].layout.get("line-cross-slope");this.hasCrossSlope=this.elevationType==="offset"&&H!==void 0;const Z=[];for(const{feature:be,id:Te,index:De,sourceLayerIndex:Ue}of p){const Ye=this.layers[0]._featureFilter.needGeometry,st=_t(be,Ye);if(!this.layers[0]._featureFilter.filter(new Kn(this.zoom,{worldview:this.worldview,activeFloors:_.activeFloors}),st,A))continue;const ot=F?F.evaluate(st,{},A):void 0,mt={id:Te,properties:be.properties,type:be.type,sourceLayerIndex:Ue,index:De,geometry:Ye?st.geometry:ht(be,A,M),patterns:{},sortKey:ot};Z.push(mt)}F&&Z.sort((be,Te)=>be.sortKey-Te.sortKey);const{lineAtlas:se,featureIndex:fe}=_,xe=this.addConstantDashes(se);for(const be of Z){const{geometry:Te,index:De,sourceLayerIndex:Ue}=be;if(xe&&this.addFeatureDashes(be,se),this.hasPattern){const Ye=jY("line",this.layers,be,this.zoom,this.pixelRatio,_);this.patternFeatures.push(Ye)}else this.addFeature(be,Te,De,A,se.positions,_.availableImages,_.brightness,_.elevationFeatures,_.elevationParams,_.crossSourceElevationEnabled);fe.insert(p[De].feature,Te,De,Ue,this.index)}!this.hasPattern&&this.hdExt&&this.hdExt.buildFrcSegments(this),this.hdExt&&this.hdExt.endPopulate()}addConstantDashes(p){let _=!1;for(const A of this.layers){const M=A.paint.get("line-dasharray").value,F=A.layout.get("line-cap").value;if(M.kind!=="constant"||F.kind!=="constant")_=!0;else{const z=F.value,H=M.value;if(!H)continue;p.addDash(H,z)}}return _}addFeatureDashes(p,_){const A=this.zoom;for(const M of this.layers){const F=M.paint.get("line-dasharray").value,z=M.layout.get("line-cap").value;if(F.kind==="constant"&&z.kind==="constant")continue;let H,Z;if(F.kind==="constant"){if(H=F.value,!H)continue}else H=F.evaluate({zoom:A},p);Z=z.kind==="constant"?z.value:z.evaluate({zoom:A},p),_.addDash(H,Z),p.patterns[M.id]=[_.getKey(H,Z)]}}update(p,_,A,M,F,z,H,Z,se){this.programConfigurations.updatePaintArrays(p,_,F,A,M,z,H,se)}updateExpressions(p){this.programConfigurations.updateExpressions(p)}addFeatures(p,_,A,M,F,z){for(const H of this.patternFeatures)this.addFeature(H,H.geometry,H.index,_,A,M,z,p.elevationFeatures,p.elevationParams,p.crossSourceElevationEnabled);this.hdExt&&(this.hdExt.buildFrcSegments(this),this.hdExt.endPopulate())}isEmpty(){return this.layoutVertexArray.length===0}uploadPending(){return!this.uploaded||this.programConfigurations.needsUpload}upload(p){this.uploaded||(this.layoutVertexArray2.length!==0&&(this.layoutVertexBuffer2=p.createVertexBuffer(this.layoutVertexArray2,dhs)),this.patternVertexArray.length!==0&&(this.patternVertexBuffer=p.createVertexBuffer(this.patternVertexArray,hhs)),!this.zOffsetVertexBuffer&&this.zOffsetVertexArray.length>0&&(this.zOffsetVertexBuffer=p.createVertexBuffer(this.zOffsetVertexArray,ahs.members,!0)),!this.elevationIdColVertexBuffer&&this.elevationIdColVertexArray.length>0&&(this.elevationIdColVertexBuffer=p.createVertexBuffer(this.elevationIdColVertexArray,ihs.members,!0)),!this.elevationGroundScaleVertexBuffer&&this.elevationGroundScaleVertexArray.length>0&&(this.elevationGroundScaleVertexBuffer=p.createVertexBuffer(this.elevationGroundScaleVertexArray,ohs.members,!0)),this.layoutVertexBuffer=p.createVertexBuffer(this.layoutVertexArray,lhs),this.indexBuffer=p.createIndexBuffer(this.indexArray)),this.programConfigurations.upload(p),this.uploaded=!0}destroy(){this.layoutVertexBuffer&&(this.zOffsetVertexBuffer&&this.zOffsetVertexBuffer.destroy(),this.elevationIdColVertexBuffer&&this.elevationIdColVertexBuffer.destroy(),this.elevationGroundScaleVertexBuffer&&this.elevationGroundScaleVertexBuffer.destroy(),this.layoutVertexBuffer.destroy(),this.indexBuffer.destroy(),this.programConfigurations.destroy(),this.segments.destroy())}lineFeatureClips(p,_){let A,M;if(_&&_>0?(A=`mapbox_clip_start_${_}`,M=`mapbox_clip_end_${_}`):(A="mapbox_clip_start",M="mapbox_clip_end"),p.properties&&Object.hasOwn(p.properties,A)&&Object.hasOwn(p.properties,M))return{start:+p.properties[A],end:+p.properties[M]}}addFeature(p,_,A,M,F,z,H,Z,se,fe){const xe=this.layers[0].layout,be=this.hdExt?this.hdExt.trackFeatureFrc(p.properties):null,Te=this.indexArray.length,De=xe.get("line-join").evaluate(p,{}),Ue=xe.get("line-cap").evaluate(p,{}),Ye=xe.get("line-miter-limit"),st=xe.get("line-round-limit");this.lineClips=this.lineFeatureClips(p),this.lineFeature=p;const ot=!(!p.properties||!Object.hasOwn(p.properties,"mapbox_line_metrics"))&&p.properties.mapbox_line_metrics;this.zOffsetValue=xe.get("line-z-offset").value;const mt=this.layers[0].paint,lt=mt.get("line-width").value;lt.kind!=="constant"&<.isLineProgressConstant===!1&&(this.variableWidthValue=lt);const yt=mt.get("line-emissive-strength").value;if(yt.kind!=="constant"&&yt.isLineProgressConstant===!1&&(this.variableEmissiveStrengthValue=yt),this.isSeaLevelReference){const Nt=xe.get("line-elevation-ground-scale").value;Nt.kind==="constant"&&Nt.value===0||(this.elevationGroundScaleValue=Nt)}if(this.hdExt==null||!this.hdExt.handleFeature(p,_,M,Z,se,!!fe,De,Ue,Ye,st,this))for(let Nt=0;Nt<_.length;Nt++)this.addLine(_[Nt],p,M,De,Ue,Ye,st,void 0,ot&&Nt>0?Nt:null);this.programConfigurations.populatePaintArrays(this.layoutVertexArray.length,p,A,F,z,M,H,void 0,this.worldview),this.hdExt&&this.hdExt.recordFeatureRange(this,Te,this.indexArray.length,be)}fillNonElevatedRoadSegment(p){for(let _=Math.max(p,this.zOffsetVertexArray.length);_0,be=Z&&Z.progress.max<1;if(this.lineClips){let $t={min:this.lineClips.start,max:this.lineClips.end},Jt=1;if(Z){const Gs=this.lineClips.end-this.lineClips.start;$t=function(pn,cn,jn){return{min:Zo(pn.min,cn,jn),max:Zo(pn.max,cn,jn)}}(Z.progress,{min:0,max:1},$t),Gs>0&&(Jt=($t.max-$t.min)/Gs)}const ns=+_.properties.mapbox_clip_feature_len,Ls=+_.properties.mapbox_clip_seg_len;if(Number.isNaN(ns)||Number.isNaN(Ls)){for(let pn=0;pn=2&&p[De-1].equals(p[De-2]);)De--;let Ue=0;for(;Ue0,Qs=this.overscaling<=16?122880/(512*this.overscaling):0;if(Jt&&ns==="round"){if(cnz&&(ns="bevel"),ns==="bevel"&&(cn>2&&(ns="flipbevel"),cn2*Qs){const In=st.sub(st.sub(ot)._mult(Qs/an)._round());this.updateDistance(ot,In),this.addCurrentVertex(In,lt,0,0,Ye,Et),ot=In}this.updateDistance(ot,st),Gs._mult(cn),this.addCurrentVertex(st,Gs,0,0,Ye,Et);const Ln=st.dist(mt);if(Ln>2*Qs){const In=st.add(mt.sub(st)._mult(Qs/Ln)._round());this.updateDistance(st,In),this.addCurrentVertex(In,yt,0,0,Ye,Et),st=In}}else Gs._mult(cn),this.addCurrentVertex(st,Gs,0,0,Ye,Et);else if(ns==="flipbevel"){if(cn>100)Gs=yt.mult(-1);else{const an=cn*lt.add(yt).mag()/lt.sub(yt).mag();Gs._perp()._mult(an*(Cs?-1:1))}this.addCurrentVertex(st,Gs,0,0,Ye,Et),this.addCurrentVertex(st,Gs.mult(-1),0,0,Ye,Et)}else if(ns==="bevel"||ns==="fakeround"){const an=st.dist(ot);let Ln=1;if(this.elevationType==="offset"&&ns==="bevel"&&this.currentLineJoinType!=="round"&&!this.patternJoinNone&&Et!=null&&ot&&mt){const cr=4*Qs;an1){this.lineSoFar=p.w;const Ue=(_.x-p.x)/xe,Ye=(_.y-p.y)/xe,st=(_.z-p.z)/xe,ot=(_.w-p.w)/xe,mt=_.x-p.x,lt=_.y-p.y,yt=Math.sqrt(mt*mt+lt*lt);if(yt===0)return;const Nt=-lt/yt,as=mt/yt,Et=Nt,$t=as,Jt=-Nt,ns=-as;for(let Ls=1;Ls=0&&this.e2>=0&&(this.indexArray.emplaceBack(this.e1,this.e2,fe),Z.primitiveLength++),z?this.e2=fe:this.e1=fe,se!=null&&(this.zOffsetVertexArray.emplaceBack(se.zOffset,se.variableWidth,se.variableWidth,se.variableEmissiveStrength),this.showElevationIdDebug&&this.elevationIdColVertexArray.emplaceBack(0,0,0)),this.elevationGroundScaleValue){const xe=se?se.elevationGroundScale:this.evaluateElevationGroundScale();this.elevationGroundScaleVertexArray.emplaceBack(xe)}}updateScaledDistance(){this.lineClips?(this.scaledDistance=this.distance/this.totalDistance,this.lineSoFar=this.totalFeatureLength*this.lineClips.start+this.distance):this.lineSoFar=this.distance}updateDistance(p,_){this.prevDistance=this.distance,this.distance+=p.dist(_),this.updateScaledDistance()}}function aOe(N,p,_){return N.x_||N.y_}oa(rOe,"LineBucket",{omit:["layers","patternFeatures","currentVertex","currentVertexIsOutside"]});const Nhs=Lt([{name:"a_pos",components:2,type:"Int16"}],4),khs=Lt([{name:"a_circle_z_offset",components:1,type:"Float32"}],4),Shs=Lt([{name:"a_pos_3",components:3,type:"Int16"},{name:"a_pos_normal_3",components:3,type:"Int16"}]);class Moe{constructor(p){this.zoom=p.zoom,this.overscaling=p.overscaling,this.layers=p.layers,this.layerIds=this.layers.map(_=>_.fqid),this.index=p.index,this.hasPattern=!1,this.projection=p.projection,this.layoutVertexArray=new Hs,this.indexArray=new Vr,this.segments=new Ri,this.programConfigurations=new Yk(p.layers,{zoom:p.zoom,lut:p.lut}),this.stateDependentLayerIds=this.layers.filter(_=>_.isStateDependent()).map(_=>_.id),this.worldview=p.worldview,this.hasAppearances=null}updateFootprints(p,_){}updateAppearances(p,_,A,M){return{hasLayoutChanges:!1,hasUboChanges:!1}}populate(p,_,A,M){const F=this.layers[0],z=[];let H=null;F.type==="circle"&&(H=F.layout.get("circle-sort-key"));for(const{feature:se,id:fe,index:xe,sourceLayerIndex:be}of p){const Te=this.layers[0]._featureFilter.needGeometry,De=_t(se,Te);if(!this.layers[0]._featureFilter.filter(new Kn(this.zoom,{worldview:this.worldview,activeFloors:_.activeFloors}),De,A))continue;const Ue=H?H.evaluate(De,{},A):void 0,Ye={id:fe,properties:se.properties,type:se.type,sourceLayerIndex:be,index:xe,geometry:Te?De.geometry:ht(se,A,M),patterns:{},sortKey:Ue};z.push(Ye)}H&&z.sort((se,fe)=>se.sortKey-fe.sortKey);let Z=null;M.projection.name==="globe"&&(this.globeExtVertexArray=new yr,Z=M.projection);for(const se of z){const{geometry:fe,index:xe,sourceLayerIndex:be}=se,Te=p[xe].feature;this.addFeature(se,fe,xe,_.availableImages,A,Z,_.brightness,_.elevationFeatures),_.featureIndex.insert(Te,fe,xe,be,this.index)}this.hdExt&&this.hdExt.finalize()}update(p,_,A,M,F,z,H){this.programConfigurations.updatePaintArrays(p,_,F,A,M,z,H,this.worldview)}updateExpressions(p){this.programConfigurations.updateExpressions(p)}isEmpty(){return this.layoutVertexArray.length===0}uploadPending(){return!this.uploaded||this.programConfigurations.needsUpload}upload(p){this.uploaded||(this.layoutVertexBuffer=p.createVertexBuffer(this.layoutVertexArray,Nhs.members),this.indexBuffer=p.createIndexBuffer(this.indexArray),this.globeExtVertexArray&&(this.globeExtVertexBuffer=p.createVertexBuffer(this.globeExtVertexArray,Shs.members)),this.hdExt&&this.hdExt.upload(p)),this.programConfigurations.upload(p),this.uploaded=!0}destroy(){this.layoutVertexBuffer&&(this.layoutVertexBuffer.destroy(),this.indexBuffer.destroy(),this.programConfigurations.destroy(),this.segments.destroy(),this.globeExtVertexBuffer&&this.globeExtVertexBuffer.destroy(),this.hdExt&&this.hdExt.destroy())}addFeature(p,_,A,M,F,z,H,Z){this.hdExt&&this.hdExt.beginFeature(p,Z,F);for(const se of _)for(const fe of se){const xe=fe.x,be=fe.y;if(xe<0||xe>=Fr||be<0||be>=Fr)continue;if(z){const Ue=z.projectTilePoint(xe,be,F),Ye=z.upVector(F,xe,be);this.addGlobeExtVertex(Ue,Ye),this.addGlobeExtVertex(Ue,Ye),this.addGlobeExtVertex(Ue,Ye),this.addGlobeExtVertex(Ue,Ye)}const Te=this.segments.prepareSegment(4,this.layoutVertexArray,this.indexArray,p.sortKey),De=Te.vertexLength;this.addCircleVertex(xe,be,-1,-1),this.addCircleVertex(xe,be,1,-1),this.addCircleVertex(xe,be,1,1),this.addCircleVertex(xe,be,-1,1),this.hdExt&&this.hdExt.writeVertexQuad(xe,be),this.indexArray.emplaceBack(De,De+1,De+2),this.indexArray.emplaceBack(De,De+2,De+3),Te.vertexLength+=4,Te.primitiveLength+=2}this.programConfigurations.populatePaintArrays(this.layoutVertexArray.length,p,A,{},M,F,H,void 0,this.worldview)}addCircleVertex(p,_,A,M){this.layoutVertexArray.emplaceBack(2*p+(A+1)/2,2*_+(M+1)/2)}addGlobeExtVertex(p,_){this.globeExtVertexArray.emplaceBack(p.x,p.y,p.z,_[0]*16384,_[1]*16384,_[2]*16384)}}oa(Moe,"CircleBucket",{omit:["layers"]});const Chs=Lt([{name:"a_pos_offset",components:4,type:"Int16"},{name:"a_tex_size",components:4,type:"Uint16"},{name:"a_pixeloffset",components:4,type:"Int16"}],4),Ahs=Lt([{name:"a_globe_anchor",components:3,type:"Int16"},{name:"a_globe_normal",components:3,type:"Float32"}],4),Ehs=Lt([{name:"a_projected_pos",components:4,type:"Float32"}],4);Lt([{name:"a_fade_opacity",components:1,type:"Uint32"}],4);const Ths=Lt([{name:"a_auto_z_offset",components:1,type:"Float32"}],4),Mhs=Lt([{name:"a_feature_index",components:1,type:"Float32"}],4),Phs=Lt([{name:"a_x_axis",components:3,type:"Float32"},{name:"a_y_axis",components:3,type:"Float32"}]),Ihs=Lt([{name:"a_texb",components:2,type:"Uint16"}]),Lhs=Lt([{name:"a_placed",components:2,type:"Uint8"},{name:"a_shift",components:2,type:"Float32"},{name:"a_elevation_from_sea",components:2,type:"Float32"}]),Rhs=Lt([{name:"a_size_scale",components:1,type:"Float32"},{name:"a_padding",components:2,type:"Float32"},{name:"a_auto_z_offset",components:1,type:"Float32"}]);Lt([{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 _dt=Lt([{name:"a_pos",components:3,type:"Int16"},{name:"a_anchor_pos",components:2,type:"Int16"},{name:"a_extrude",components:2,type:"Int16"}],4),Dhs=Lt([{name:"a_pos_2f",components:2,type:"Float32"},{name:"a_radius",components:1,type:"Float32"},{name:"a_flags",components:2,type:"Int16"}],4);Lt([{name:"triangle",components:3,type:"Uint16"}]),Lt([{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"}]),Lt([{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"}]),Lt([{type:"Float32",name:"offsetX"}]),Lt([{type:"Int16",name:"x"},{type:"Int16",name:"y"}]);const wdt=new Float32Array(1),Fhs=new Uint32Array(wdt.buffer);function Poe(N){return wdt[0]=N,Fhs[0]}const V9=class vU{static getBlockIndices(p){let _=vU._blockIndicesTemplate;if(!_){_=vU._blockIndicesTemplate=new Uint32Array(p);for(let A=0;Ap.maxUniformBlockSize)throw new Error(`UBO size ${this.totalBytes} exceeds device limit ${p.maxUniformBlockSize}`);_.isContextLost()||(this.headerBuffer=_.createBuffer(),_.bindBuffer(_.UNIFORM_BUFFER,this.headerBuffer),_.bufferData(_.UNIFORM_BUFFER,vU.HEADER_BYTES,_.DYNAMIC_DRAW),this.propertiesBuffer=_.createBuffer(),_.bindBuffer(_.UNIFORM_BUFFER,this.propertiesBuffer),_.bufferData(_.UNIFORM_BUFFER,this.totalBytes,_.DYNAMIC_DRAW),this.blockIndicesBuffer=_.createBuffer(),_.bindBuffer(_.UNIFORM_BUFFER,this.blockIndicesBuffer),_.bufferData(_.UNIFORM_BUFFER,this.totalBytes,_.DYNAMIC_DRAW),_.bindBuffer(_.UNIFORM_BUFFER,null))}markHeaderDirty(){this._headerDirty=!0}writeDataDrivenBlock(p,_){const A=this.headerData,M=4*A[2];if(M===0)return;const F=_*M;if(F+M>this.propertiesData.length)throw new Error(`UBO write out of bounds: feature index ${_} exceeds propertiesData capacity`);const z=A[0];for(let Z=0;Z<9;Z++)z&1<this._propsDirtyMax&&(this._propsDirtyMax=H)}rightSizeForTransfer(){const p=this._propsDirtyMax===-1?0:this._propsDirtyMax;p>>_&1?8:4);const F=vU.EVAL_FLAT_OFFSETS[_];this.propertiesData.set(A.subarray(F,F+M),p)}upload(p){this.context||(this.context=p);const _=p.gl;this.headerBuffer&&this.propertiesBuffer&&this.blockIndicesBuffer||this._initBuffers(p);let A=!1;if(this._headerDirty&&(_.bindBuffer(_.UNIFORM_BUFFER,this.headerBuffer),_.bufferSubData(_.UNIFORM_BUFFER,0,this.headerData),this._headerDirty=!1,A=!0),this._propsDirtyMin!==-1){const M=this._propsDirtyMin,F=this._propsDirtyMax;_.bindBuffer(_.UNIFORM_BUFFER,this.propertiesBuffer),_.bufferSubData(_.UNIFORM_BUFFER,4*M,this.propertiesData,M,F-M),this._propsDirtyMin=-1,this._propsDirtyMax=-1,A=!0}this._blockIndicesDirty&&(_.bindBuffer(_.UNIFORM_BUFFER,this.blockIndicesBuffer),_.bufferSubData(_.UNIFORM_BUFFER,0,vU.getBlockIndices(this.propsDwords)),this._blockIndicesDirty=!1,A=!0),A&&_.bindBuffer(_.UNIFORM_BUFFER,null)}bind(p,_){const A=p.gl,M=(z,H,Z)=>{if(!H)return;const se=A.getUniformBlockIndex(_,z);se!==A.INVALID_INDEX&&(A.uniformBlockBinding(_,se,Z),A.bindBufferBase(A.UNIFORM_BUFFER,Z,H))},F=3*this.batchIndex;M("SymbolPaintPropertiesHeaderUniform",this.headerBuffer,F),M("SymbolPaintPropertiesUniform",this.propertiesBuffer,F+1),M("SymbolPaintPropertiesIndexUniform",this.blockIndicesBuffer,F+2)}destroy(){if(this.context){const p=this.context.gl;this.headerBuffer&&(p.deleteBuffer(this.headerBuffer),this.headerBuffer=null),this.propertiesBuffer&&(p.deleteBuffer(this.propertiesBuffer),this.propertiesBuffer=null),this.blockIndicesBuffer&&(p.deleteBuffer(this.blockIndicesBuffer),this.blockIndicesBuffer=null)}}};V9.HEADER_DWORDS=16,V9.HEADER_BYTES=64,V9.EVAL_FLAT_OFFSETS=[0,8,16,20,24,28,32,36,40],V9.EVAL_FLAT_TOTAL=48,V9._blockIndicesTemplate=null;let AY=V9;function jdt(N,p,_,A,M,F,z,H){return!!N&&(N.kind==="constant"?N.value==="none":N.evaluate({zoom:0,brightness:F,worldview:H},p,_,M,A,z)==="none")}function Ndt(N){if(!(N instanceof _h))return!1;const p=N.value;return(p.kind==="source"||p.kind==="composite")&&p.isStateDependent}oa(AY,"SymbolPropertiesUBO",{omit:["headerBuffer","propertiesBuffer","blockIndicesBuffer"]});const EY=["icon","text"].map(N=>[`${N}-color`,`${N}-halo-color`,`${N}-opacity`,`${N}-halo-width`,`${N}-halo-blur`,`${N}-emissive-strength`,`${N}-occlusion-opacity`,"symbol-z-offset",`${N}-translate`]),km=new Float32Array(AY.EVAL_FLAT_TOTAL),Ohs=[0,0],kdt=new WeakMap;class iOe{constructor(p,_,A,M,F="",z,H){this.layer=p,this.zoom=_,this.lut=A,this.isText=M,this.worldview=F,this.maxUniformBufferBindings=z||24,this.uboSizeDwords=H||4096,this.allFeatureVtIndices=[],this.allFeatureIds=[],this.allFormattedSections=[],this.featureVertexRangesFromId=null,this.featureVertexRangesFromVtIndex=null,this.ubos=[],this.featureCount=0,this.cachedConstantUniforms=null,this.cachedConstantRenderZoom=null,this.cachedConstantBrightness=void 0,this.cachedConstantPaint=null,this.activeAppearanceByVtIndex=null,this.zoomDependency=new Uint8Array(9),this.sharedZoomRanges=new Float32Array(18),this._zoomRangeScratch=new Float32Array(2),this._floorZoom=Math.floor(this.zoom),this.header=new Uint32Array(AY.HEADER_DWORDS),this.updateHeader(),this.isAllConstant=this.header[0]===0;const Z=4*this.header[2];this.maxFeaturesPerBatch=Z===0?Number.MAX_SAFE_INTEGER:Math.floor(this.uboSizeDwords/Z)}updateHeader(){const p=this.layer.paint;let _=0,A=0,M=0,F=0,z=!0;const H=this._floorZoom,Z=EY[+this.isText];for(let se=0;se<9;se++){const fe=Z[se],xe=se<2,be=p.get(fe),Te=!(!be||typeof be.isConstant!="function"||be.isConstant()),De=this._appearancesHavePaintProperties(fe);if(!Te&&!De){const yt=this._layerUnevaluated(fe);yt&&yt.expression&&yt.expression.kind==="camera"&&(M|=1<{if(!se)return;this._computeZoomRange(se,_,this._zoomRangeScratch,0);const fe=this._zoomRangeScratch[0],xe=this._zoomRangeScratch[1];A?fe===z&&xe===H||(M=!0):(A=!0,z=fe,H=xe,F=se)};Z(this._zoomExprOf(this._layerUnevaluated(p)));for(const se of this.layer.getAppearances()||[])se.hasPaintProperty(p)&&Z(this._zoomExprOf(se.getUnevaluatedPaintProperty(p)));return{hasZoom:A,differs:M,representative:F}}evaluateAllProperties(p,_,A,M,F,z,H){const Z={brightness:F,worldview:this.worldview},se={feature:p,featureState:_,canonical:A,availableImages:M,params:new Kn(this.zoom,Z),paramsNext:new Kn(this.zoom+1,Z),formattedSection:z,activeAppearance:H},fe=EY[+this.isText];for(let xe=0;xe<9;xe++){const be=fe[xe],Te=xe<2,De=xe===8,Ue=this.zoomDependency[xe],Ye=Ue!==0,st=Ue===2,ot=AY.EVAL_FLAT_OFFSETS[xe],mt=ot+(Te||De?4:2);Te?this._evaluateColorValue(be,xe,Ye,st,mt,se,ot):De?this._evaluateTranslateValue(be,xe,Ye,st,mt,se,ot):this._evaluateFloatValue(be,xe,Ye,st,mt,se,ot)}return km}_resolveProp(p,_,A=!1,M){const F=this.layer.paint,z=F.get(p),H=p,Z=!(!_||!_.hasPaintProperty(H)),se=Z?M&&z&&z.property.overrides&&z.property.overrides.hasOverride(M)?z:_.paintProperties.get(H):F.get(p);if(A||!se||typeof se.isConstant!="function"||!se.isConstant())return se;const fe=Z?_.getUnevaluatedPaintProperty(H):this._layerUnevaluated(p);return this._unbakeCamera(se,fe)}_unbakeCamera(p,_){const A=_&&_.expression;if(!A||A.kind!=="camera")return p;let M=kdt.get(_);return M||(M=new _h(p.property,A,p.parameters,p.iconImageUseTheme),kdt.set(_,M)),M}_layerUnevaluated(p){const _=this.layer._transitionablePaint._values[p];return _&&_.value}_zoomExprOf(p){const _=p&&p.expression;return!_||_.kind!=="composite"&&_.kind!=="camera"?null:_}_evalAt(p,_,A){return p.property.evaluate(p.value,_,A.feature,A.featureState,A.canonical,A.availableImages,p.iconImageUseTheme,A.formattedSection)}_evaluateColorValue(p,_,A,M,F,z,H){const Z=this._resolveProp(p,z.activeAppearance,!1,z.formattedSection);if(this._writePropertyZoomRange(_,A,M,Z,F),!Z)return km[H]=0,km[H+1]=0,km[H+2]=0,void(km[H+3]=1);const se=this._resolveProp(`${p}-use-theme`,z.activeAppearance,!0),fe=jdt(se&&typeof se!="string"?se.value:void 0,z.feature,z.featureState,z.availableImages,z.canonical,z.params.brightness,z.formattedSection,this.worldview)?null:this.lut,xe=(Z.isConstant()?Z.constantOr(Ci.transparent):this._evalAt(Z,z.params,z)||Ci.transparent).toNonPremultipliedRenderColor(fe);if(km[H]=Nm(255*xe.r,255*xe.g),km[H+1]=Nm(255*xe.b,255*xe.a),A){const be=(this._evalAt(Z,z.paramsNext,z)||Ci.transparent).toNonPremultipliedRenderColor(fe);km[H+2]=Nm(255*be.r,255*be.g),km[H+3]=Nm(255*be.b,255*be.a)}else km[H+2]=km[H],km[H+3]=km[H+1]}_computeZoomRange(p,_,A,M){let F=0,z=1;const H=!p||p.kind!=="composite"&&p.kind!=="camera"?null:p.zoomStops;if(H&&H.length>0)if(p.interpolationType==null){F=z=1;for(const Z of H)if(Z>_&&Z<_+1){F=z=Z-_;break}}else H[0]>_&&H[0]<_+1&&(F=H[0]-_);A[M]=F,A[M+1]=z}_writeZoomRange(p,_){this._computeZoomRange(p&&p.value,this._floorZoom,km,_)}_writePropertyZoomRange(p,_,A,M,F){A?this._writeZoomRange(M,F):_?(km[F]=this.sharedZoomRanges[2*p],km[F+1]=this.sharedZoomRanges[2*p+1]):(km[F]=0,km[F+1]=0)}_evaluateFloatValue(p,_,A,M,F,z,H){const Z=p.endsWith("opacity")?1:0,se=this._resolveProp(p,z.activeAppearance);this._writePropertyZoomRange(_,A,M,se,F);const fe=(se?se.isConstant()?se.constantOr(Z):this._evalAt(se,z.params,z):Z)??Z;if(km[H]=fe,A){const xe=this._evalAt(se,z.paramsNext,z);km[H+1]=xe??Z}else km[H+1]=fe}_evaluateTranslateValue(p,_,A,M,F,z,H){const Z=this._resolveProp(p,z.activeAppearance);this._writePropertyZoomRange(_,A,M,Z,F);const se=!!Z&&typeof Z.isConstant=="function"&&!Z.isConstant(),fe=Z?typeof Z.isConstant!="function"?Z:se?this._evalAt(Z,z.params,z):Z.constantOr(Ohs):void 0;if(km[H]=fe?fe[0]:0,km[H+1]=fe?fe[1]:0,A){const xe=se?this._evalAt(Z,z.paramsNext,z):fe;km[H+2]=xe?xe[0]:0,km[H+3]=xe?xe[1]:0}else km[H+2]=km[H],km[H+3]=km[H+1]}_appearancesHavePaintProperties(p){return this.layer.getAppearances().some(_=>_.hasPaintProperty(p))}hasStateDependentPaint(p){const _=p.paint,A=EY[+this.isText];for(const M of A)if(Ndt(_.get(M)))return!0;for(const M of p.getAppearances()||[])for(const F of A){const z=F;if(M.hasPaintProperty(z)&&Ndt(M.paintProperties.get(z)))return!0}return!1}hasPerFeatureTranslate(){return!!(256&this.header[0])}getCurrentBatchIndex(){return this.maxFeaturesPerBatch===0?0:Math.floor(this.featureCount/this.maxFeaturesPerBatch)}_writeFeatureBlock(p,_){const A=this.isAllConstant?0:p;let M=Math.floor(A/this.maxFeaturesPerBatch),F=A%this.maxFeaturesPerBatch;this._batchExceedsDeviceLimit(M)&&(M=0,F=0);const z=this.ubos[M];return!!z&&(z.writeDataDrivenBlock(_,F),!0)}_batchExceedsDeviceLimit(p){return 3*p+2>=this.maxUniformBufferBindings}_reevaluateAt(p,_,A,M,F,z){if(!_)return;const H=this.allFeatureVtIndices[p],Z=_.feature(H);if(!Z)return;const se=this.allFeatureIds[p],fe=se!=null&&F[se]||{},xe={type:Z.type,id:se,properties:Z.properties||{},geometry:[]},be=this.activeAppearanceByVtIndex?this.activeAppearanceByVtIndex.get(H):void 0,Te=this.evaluateAllProperties(xe,fe,A,M,z,(this.allFormattedSections?this.allFormattedSections[p]:void 0)||void 0,be);this._writeFeatureBlock(p,Te)}_ensureRangeMaps(){if(!this.featureVertexRangesFromId){this.featureVertexRangesFromId=new Map,this.featureVertexRangesFromVtIndex=new Map;for(let p=0;p{const be=H[xe],Te=M.get(be);if(!Te)return[0,0,0,1];const De=M.get(`${be}-use-theme`),Ue=jdt(De&&typeof De!="string"?De.value:void 0,z,{},[],void 0,_,void 0,this.worldview)?null:this.lut;return(this.cameraMask&1<{const Te=M.get(H[xe]);return Te?this.cameraMask&1<{A.text=function(M,F,z){const H=F.layout.get("text-transform").evaluate(z,{});return H==="uppercase"?M=M.toLocaleUpperCase():H==="lowercase"&&(M=M.toLocaleLowerCase()),Ur.applyArabicShaping&&(M=Ur.applyArabicShaping(M)),M}(A.text,p,_)}),N}const $3={horizontal:1,vertical:2,horizontalOnly:3};function Sdt(N){let p=.5,_=.5;switch(N){case"right":case"top-right":case"bottom-right":p=1;break;case"left":case"top-left":case"bottom-left":p=0}switch(N){case"bottom":case"bottom-right":case"bottom-left":_=1;break;case"top":case"top-right":case"top-left":_=0}return{horizontalAlign:p,verticalAlign:_}}function Cdt(N,p,_,A){const{horizontalAlign:M,verticalAlign:F}=Sdt(A),z=_[0]-N.displaySize[0]*M,H=_[1]-N.displaySize[1]*F;return{imagePrimary:N,imageSecondary:p,top:H,bottom:H+N.displaySize[1],left:z,right:z+N.displaySize[0]}}function Adt(N,p,_,A,M,F){const z=N.imagePrimary;let H;if(z.content){const Ye=z.content,st=z.pixelRatio||1;H=[Ye[0]/st,Ye[1]/st,z.displaySize[0]-Ye[2]/st,z.displaySize[1]-Ye[3]/st]}const Z=p.left*F,se=p.right*F;let fe,xe,be,Te;_==="width"||_==="both"?(Te=M[0]+Z-A[3],xe=M[0]+se+A[1]):(Te=M[0]+(Z+se-z.displaySize[0])/2,xe=Te+z.displaySize[0]);const De=p.top*F,Ue=p.bottom*F;return _==="height"||_==="both"?(fe=M[1]+De-A[0],be=M[1]+Ue+A[2]):(fe=M[1]+(De+Ue-z.displaySize[1])/2,be=fe+z.displaySize[1]),{imagePrimary:z,imageSecondary:void 0,top:fe,right:xe,bottom:be,left:Te,collisionPadding:H}}const TY={"!":"︕","#":"#",$:"$","%":"%","&":"&","(":"︵",")":"︶","*":"*","+":"+",",":"︐","-":"︲",".":"・","/":"/",":":"︓",";":"︔","<":"︿","=":"=",">":"﹀","?":"︖","@":"@","[":"﹇","\\":"\","]":"﹈","^":"^",_:"︳","`":"`","{":"︷","|":"―","}":"︸","~":"~","¢":"¢","£":"£","¥":"¥","¦":"¦","¬":"¬","¯":" ̄","–":"︲","—":"︱","‘":"﹃","’":"﹄","“":"﹁","”":"﹂","…":"︙","‧":"・","₩":"₩","、":"︑","。":"︒","〈":"︿","〉":"﹀","《":"︽","》":"︾","「":"﹁","」":"﹂","『":"﹃","』":"﹄","【":"︻","】":"︼","〔":"︹","〕":"︺","〖":"︗","〗":"︘","!":"︕","(":"︵",")":"︶",",":"︐","-":"︲",".":"・",":":"︓",";":"︔","<":"︿",">":"﹀","?":"︖","[":"﹇","]":"﹈","_":"︳","{":"︷","|":"―","}":"︸","⦅":"︵","⦆":"︶","。":"︒","「":"﹁","」":"﹂"};function Bhs(N){return N==="︶"||N==="﹈"||N==="︸"||N==="﹄"||N==="﹂"||N==="︾"||N==="︼"||N==="︺"||N==="︘"||N==="﹀"||N==="︐"||N==="︓"||N==="︔"||N==="`"||N===" ̄"||N==="︑"||N==="︒"}function $hs(N){return N==="︵"||N==="﹇"||N==="︷"||N==="﹃"||N==="﹁"||N==="︽"||N==="︻"||N==="︹"||N==="︗"||N==="︿"}const oM=128;function G9(N,p,_,A){const{expression:M}=p;if(M.kind==="constant")return{kind:"constant",layoutSize:M.evaluate(new Kn(N+1,{worldview:_}),void 0,void 0,void 0,A)};if(M.kind==="source")return{kind:"source"};{const{zoomStops:F,interpolationType:z}=M;let H=0;for(;HZ*H)}}function Tdt(N,p,_,A,M,F,z){return{appearanceTextOffset:W9(N,p,_,A,"text-offset",M,([Z,se])=>[Z*H9,se*H9]),appearanceTextRotate:W9(N,p,_,A,"text-rotate",F),appearanceTextSize:W9(N,p,_,A,"text-size",z)}}function Mdt(N,p,_,A,M,F,z,H,Z,se){if(!N)return;const fe=function(xe,be,Te,De,Ue,Ye,st){if(xe.kind==="camera")return xe.maxSize;if(xe.kind==="composite"){const ot=be.possiblyEvaluate(new Kn(xe.maxZoom,{worldview:Ye}),Te,st).evaluate(Ue,{},Te,st),mt=be.possiblyEvaluate(new Kn(xe.minZoom,{worldview:Ye}),Te,st).evaluate(Ue,{},Te,st);return Math.max(ot,mt)}return be.possiblyEvaluate(new Kn(De,{worldview:Ye}),Te,st).evaluate(Ue,{},Te,st)}(p,_,A,M,F,Z,se);return N.scaleSelf(fe*H*z)}function oOe(N,p,_,A,M,F,z,H,Z,se){return{iconPrimary:Mdt(N.getPrimary(),p,_,A,M,F,z,H,Z,se),iconSecondary:Mdt(N.getSecondary(),p,_,A,M,F,z,H,Z,se)}}function Pdt(N,p){return N*p/24}function Idt(N,p,_,A,M,F){let z=null;return p.kind==="source"?(z=[oM*_*A],z[0]>nR&&Yo(`${N}: Value for "text-size" or "icon-size" is >= 255. Reduce your "text-size" or "icon-size".`)):p.kind==="composite"&&(z=[oM*M*A,oM*F*A],(z[0]>nR||z[1]>nR)&&Yo(`${N}: Value for "text-size" or "icon-size" is >= 255. Reduce your "text-size" or "icon-size".`)),z}const Vhs=Lt([{type:"Float32",name:"a_globe_pos",components:3},{type:"Float32",name:"a_uv",components:2}]),{members:Loe}=Vhs,Hhs=Lt([{name:"a_pos_3",components:3,type:"Int16"}]);var lOe=Lt([{name:"a_pos",type:"Int16",components:2}]);class Ghs{constructor(p,_){this.pos=p,this.dir=_}intersectsPlane(p,_,A){const M=hn(_,this.dir);if(Math.abs(M)<1e-6)return!1;const F=((p[0]-this.pos[0])*_[0]+(p[1]-this.pos[1])*_[1])/M;return A[0]=this.pos[0]+this.dir[0]*F,A[1]=this.pos[1]+this.dir[1]*F,!0}}class Roe{constructor(p,_){this.pos=p,this.dir=_}intersectsPlane(p,_,A){const M=ze(_,this.dir);if(Math.abs(M)<1e-6)return!1;const F=((p[0]-this.pos[0])*_[0]+(p[1]-this.pos[1])*_[1]+(p[2]-this.pos[2])*_[2])/M;return A[0]=this.pos[0]+this.dir[0]*F,A[1]=this.pos[1]+this.dir[1]*F,A[2]=this.pos[2]+this.dir[2]*F,!0}closestPointOnSphere(p,_,A){if(function(Te,De){var Ue=Te[0],Ye=Te[1],st=Te[2],ot=De[0],mt=De[1],lt=De[2];return Math.abs(Ue-ot)<=u*Math.max(1,Math.abs(Ue),Math.abs(ot))&&Math.abs(Ye-mt)<=u*Math.max(1,Math.abs(Ye),Math.abs(mt))&&Math.abs(st-lt)<=u*Math.max(1,Math.abs(st),Math.abs(lt))}(this.pos,p)||_===0)return A[0]=A[1]=A[2]=0,!1;const[M,F,z]=this.dir,H=this.pos[0]-p[0],Z=this.pos[1]-p[1],se=this.pos[2]-p[2],fe=M*M+F*F+z*z,xe=2*(H*M+Z*F+se*z),be=xe*xe-4*fe*(H*H+Z*Z+se*se-_*_);if(be<0){const Te=Math.max(-xe/2,0),De=H+M*Te,Ue=Z+F*Te,Ye=se+z*Te,st=Math.hypot(De,Ue,Ye);return A[0]=De*_/st,A[1]=Ue*_/st,A[2]=Ye*_/st,!1}{const Te=(-xe-Math.sqrt(be))/(2*fe);if(Te<0){const De=Math.hypot(H,Z,se);return A[0]=H*_/De,A[1]=Z*_/De,A[2]=se*_/De,!1}return A[0]=H+M*Te,A[1]=Z+F*Te,A[2]=se+z*Te,!0}}}class cOe{constructor(p,_,A,M,F){this.TL=p,this.TR=_,this.BR=A,this.BL=M,this.horizon=F}static fromInvProjectionMatrix(p,_,A){const M=[-1,1,1],F=[1,1,1],z=[1,-1,1],H=[-1,-1,1],Z=Xe(M,M,p),se=Xe(F,F,p),fe=Xe(z,z,p),xe=Xe(H,H,p);return new cOe(Z,se,fe,xe,_/A)}}function dOe(N,p,_,A){const M=p[0],F=p[1],z=p[2],H=_[0],Z=_[1],se=_[2];let fe=1/0,xe=-1/0;for(let be=0;bexe&&(xe=De)}return A[0]=fe,A[1]=xe,A}function Ldt(N,p){let _=!0;for(let A=0;A=0);if(F===0)return 0;F!==p.length&&(_=!1)}return _?2:1}const Whs=[0,0];function Rdt(N,p){for(const _ of N.projections){const A=dOe(p,N.points[0],_.axis,Whs);if(_.projection[1]A[1])return 0}return 1}function Ddt(N,p){const _=p[0],A=p[1],M=p[2],F=p[3];for(let z=0;z=0)return!0}return!1}class q3{constructor(p,_){this.points=p||new Array(8).fill([0,0,0]),this.planes=_||new Array(6).fill([0,0,0,0]),this.bounds=uu.fromPoints(this.points),this.projections=[],this.frustumEdges=[xt([],this.points[2],this.points[3]),xt([],this.points[0],this.points[3]),xt([],this.points[4],this.points[0]),xt([],this.points[5],this.points[1]),xt([],this.points[6],this.points[2]),xt([],this.points[7],this.points[3])];for(const A of this.frustumEdges){const M=[0,-A[2],A[1]],F=[A[2],0,-A[0]];this.projections.push({axis:M,projection:dOe(this.points,this.points[0],M,[0,0])}),this.projections.push({axis:F,projection:dOe(this.points,this.points[0],F,[0,0])})}}static fromInvProjectionMatrix(p,_,A,M){const F=Math.pow(2,A),z=[[-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(se=>{const fe=Ft([],se,p),xe=1/fe[3]/_*F;return(be=fe)[0]=(Te=fe)[0]*(De=[xe,xe,M?1/fe[3]:xe,xe])[0],be[1]=Te[1]*De[1],be[2]=Te[2]*De[2],be[3]=Te[3]*De[3],be;var be,Te,De}),H=[[0,1,2],[6,5,4],[0,3,7],[2,1,5],[3,2,6],[0,4,5]].map(se=>{const fe=qe([],$e([],xt([],z[se[0]],z[se[1]]),xt([],z[se[2]],z[se[1]]))),xe=-ze(fe,z[se[1]]);return fe.concat(xe)}),Z=[];for(let se=0;seDe&&(De=mt)}let Ue=1/0,Ye=-1/0;for(let st=0;stYe&&(Ye=mt)}if(Te>Ye||Ue>De)return 0}return 1}containsPoint(p){for(const _ of this.planes){const A=_[3];if(ze([_[0],_[1],_[2]],p)+A<0)return!1}return!0}}class uu{static fromPoints(p){const _=[1/0,1/0,1/0],A=[-1/0,-1/0,-1/0];for(const M of p)Se(_,_,M),Le(A,A,M);return new uu(_,A)}static fromTileIdAndHeight(p,_,A){const M=1<p.max[_]||p.min[_]>this.max[_])return!1;return!0}intersectsAabbXY(p){return!(this.min[0]>p.max[0]||p.min[0]>this.max[0]||this.min[1]>p.max[1]||p.min[1]>this.max[1])}encapsulate(p){for(let _=0;_<3;_++)this.min[_]=Math.min(this.min[_],p.min[_]),this.max[_]=Math.max(this.max[_],p.max[_])}encapsulatePoint(p){for(let _=0;_<3;_++)this.min[_]=Math.min(this.min[_],p[_]),this.max[_]=Math.max(this.max[_],p[_])}closestPoint(p){return[Math.max(Math.min(this.max[0],p[0]),this.min[0]),Math.max(Math.min(this.max[1],p[1]),this.min[1]),Math.max(Math.min(this.max[2],p[2]),this.min[2])]}}function Doe(N){return N*gf/nM}oa(uu,"Aabb");const Khs=[new uu([Wv,Wv,Wv],[K_,K_,K_]),new uu([Wv,Wv,Wv],[0,0,K_]),new uu([0,Wv,Wv],[K_,0,K_]),new uu([Wv,0,Wv],[0,K_,K_]),new uu([0,0,Wv],[K_,K_,K_])];function Fdt(N,p,_,A=!0){const M=Fe([],N._camera.position,N.worldSize),F=[p,_,1,1];Ft(F,F,N.pixelMatrixInverse),ys(F,F,1/F[3]);const z=qe([],xt([],F,M)),H=N.globeMatrix,Z=[H[12],H[13],H[14]],se=xt([],Z,M),fe=ce(se),xe=qe([],se),be=N.worldSize/(2*Math.PI),Te=ze(xe,z),De=Math.asin(be/fe);if(De1?null:function(A,M,F,z){const H=Math.sin(F);return A*(Math.sin((1-z)*F)/H)+M*(Math.sin(z*F)/H)}(N.a[p],N.b[p],N.angle,ta(_,0,1))+N.center[p]}function WC(N){if(N.z<=1)return Khs[N.z+2*N.y+N.x];const p=mOe(Foe(N));return uu.fromPoints(p)}function V3(N,p,_){return Fe(N,N,1-_),ke(N,N,p,_)}function Odt(N,p,_){for(const A of N)Xe(A,A,p),Fe(A,A,_)}function hOe(N,p,_,A){const M=p/N.worldSize,F=N.globeMatrix;if(_.z<=1){const $t=WC(_).getCorners();return Odt($t,F,M),uu.fromPoints($t)}const z=Foe(_,A),H=mOe(z,gf+Doe(N._tileCoverLift));Odt(H,F,M);const Z=Number.MAX_VALUE,se=[-Z,-Z,-Z],fe=[Z,Z,Z];if(z.contains(N.center)){for(const ns of H)Se(fe,fe,ns),Le(se,se,ns);se[2]=0;const $t=N.point,Jt=[$t.x*M,$t.y*M,0];return Se(fe,fe,Jt),Le(se,se,Jt),new uu(fe,se)}if(N._tileCoverLift>0){for(const $t of H)Se(fe,fe,$t),Le(se,se,$t);return new uu(fe,se)}const xe=[F[12]*M,F[13]*M,F[14]*M],be=z.getCenter(),Te=ta(N.center.lat,-85.051129,L),De=ta(be.lat,-85.051129,L),Ue=ex(N.center.lng),Ye=ap(Te);let st=Ue-ex(be.lng);const ot=Ye-ap(De);st>.5?st-=1:st<-.5&&(st+=1);let mt=0;Math.abs(st)>Math.abs(ot)?mt=st>=0?1:3:(mt=ot>=0?0:2,ke(xe,xe,[F[4]*M,F[5]*M,F[6]*M],-Math.sin(Xr(ot>=0?z.getSouth():z.getNorth()))*gf));const lt=H[mt],yt=H[(mt+1)%4],Nt=new Yhs(lt,yt,xe),as=[uOe(Nt,0)||lt[0],uOe(Nt,1)||lt[1],uOe(Nt,2)||lt[2]],Et=H3(N.zoom);if(Et>0){const $t=function({x:ns,y:Ls,z:Gs},pn,cn,jn,Hn){const Cs=1/(1<.5?Vn=-1:Dn<-.5&&(Vn=1),Qs=((Qs+Vn)*pn-(jn*=pn))*cn+jn,an=((an+Vn)*pn-jn)*cn+jn,Ln=(Ln*pn-(Hn*=pn))*cn+Hn,In=(In*pn-Hn)*cn+Hn,[[Qs,In,0],[an,In,0],[an,Ln,0],[Qs,Ln,0]]}(_,p,N._pixelsPerMercatorPixel,Ue,Ye);for(let ns=0;nsMath.PI/2*1.01}const Udt=Xr(85),Zhs=Math.cos(Udt),Xhs=Math.sin(Udt);function qdt(N,p){const _=N.fovAboveCenter,A=N.elevation?N.elevation.getMinElevationBelowMSL()*p:0,M=Math.min(A,N.isOrthographic?-10*p:0),F=(N._camera.position[2]*N.worldSize-M)/Math.cos(N._pitch),z=Math.sin(_)*F/Math.sin(Math.max(Math.PI/2-N._pitch-_,.01));let H=Math.sin(N._pitch)*z+F;const Z=F*(1/N._horizonShift);if(!N.elevation||N.elevation.exaggeration()===0){let se=Math.max(N.zoom-17,0);N.isOrthographic&&(se/=10),H*=1+se}return Math.min(1.01*H,Z)}class lM{constructor(p,_,A){this.z=p,this.x=_,this.y=A,this.key=cM(0,p,p,_,A)}equals(p){return this.z===p.z&&this.x===p.x&&this.y===p.y}isChildOf(p){const _=this.z-p.z;return p.z===0||p.z>_&&p.y===this.y>>_}url(p,_){const A=function(F,z,H){const Z=2**H,se=2*Math.PI*6378137,fe=se*(F/Z-.5),xe=se*(.5-(z+1)/Z);return`${fe},${xe},${fe+se/Z},${xe+se/Z}`}(this.x,this.y,this.z),M=function(F,z,H){let Z,se="";for(let fe=F;fe>0;fe--)Z=1<this.canonical.z?new mg(p,this.wrap,this.canonical.z,this.canonical.x,this.canonical.y):new mg(p,this.wrap,p,this.canonical.x>>_,this.canonical.y>>_)}calculateScaledKey(p,_=!0){if(this.overscaledZ===p&&_)return this.key;if(p>this.canonical.z)return cM(this.wrap*+_,p,this.canonical.z,this.canonical.x,this.canonical.y);{const A=this.canonical.z-p;return cM(this.wrap*+_,p,p,this.canonical.x>>A,this.canonical.y>>A)}}isChildOf(p){if(p.wrap!==this.wrap)return!1;const _=this.canonical.z-p.canonical.z;return p.overscaledZ===0||p.overscaledZ>_&&p.canonical.y===this.canonical.y>>_}children(p){if(this.overscaledZ>=p)return[new mg(this.overscaledZ+1,this.wrap,this.canonical.z,this.canonical.x,this.canonical.y)];const _=this.canonical.z+1,A=2*this.canonical.x,M=2*this.canonical.y;return[new mg(_,this.wrap,_,A,M),new mg(_,this.wrap,_,A+1,M),new mg(_,this.wrap,_,A,M+1),new mg(_,this.wrap,_,A+1,M+1)]}isLessThan(p){return this.wrapp.wrap)&&(this.overscaledZp.overscaledZ)&&(this.canonical.xp.canonical.x)&&this.canonical.y{let p=N.canonical.x-1,_=N.wrap;return p<0&&(p=(1<{let p=N.canonical.x+1,_=N.wrap;return p===1<new mg(N.overscaledZ,N.wrap,N.canonical.z,N.canonical.x,(N.canonical.y===0?1<new mg(N.overscaledZ,N.wrap,N.canonical.z,N.canonical.x,N.canonical.y===(1<mt&&(lt(Nt,pn,Et,$t,Ls,Gs),lt(pn,as,Ls,Gs,Jt,ns))}lt(xe,be,A,F,M,F),lt(be,Te,M,F,M,z),lt(Te,De,M,z,A,z),lt(De,xe,A,z,A,F),Ue-=mt,Ye-=mt,st+=mt,ot+=mt;const yt=1/Math.max(st-Ue,ot-Ye);return{scale:yt,x:Ue*yt,y:Ye*yt,x2:st*yt,y2:ot*yt,projection:p}}function Hdt(N,p,_,A,M,F,z,H,Z){if(Z.name==="globe")return hOe(N,p,new lM(_,A,M),!1);const se=xOe({z:_,x:A,y:M},Z);return new uu([(F+se.x/se.scale)*p,p*(se.y/se.scale),z],[(F+se.x2/se.scale)*p,p*(se.y2/se.scale),H])}oa(lM,"CanonicalTileID"),oa(mg,"OverscaledTileID",{omit:["projMatrix","expandedProjMatrix"]});const Qhs=w(new Float32Array(16));class dM{constructor(p){this.spec=p,this.name=p.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(p,_){return{x:0,y:0,z:0}}unproject(p,_){return new Ll(0,0)}projectTilePoint(p,_,A){return{x:p,y:_,z:0}}locationPoint(p,_,A,M=!0){return p._coordinatePoint(p.locationCoordinate(_,A),M)}pixelsPerMeter(p,_){return eu(1,p)*_}pixelSpaceConversion(p,_,A){return 1}farthestPixelDistance(p){return qdt(p,p.pixelsPerMeter)}pointCoordinate(p,_,A,M){const F=p.horizonLineFromTop(!1),z=new xs(_,Math.max(F,A));return p.rayIntersectionCoordinate(p.pointRayIntersection(z,M))}pointCoordinate3D(p,_,A){const M=new xs(_,A);if(p.elevation)return p.elevation.pointCoordinate(M);{const F=this.pointCoordinate(p,M.x,M.y,0);return[F.x,F.y,F.z]}}isPointAboveHorizon(p,_){if(p.elevation&&p.elevation.visibleDemTiles.length)return!this.pointCoordinate3D(p,_.x,_.y);const A=p.horizonLineFromTop();return _.y0?_<-K9+A&&(_=-K9+A):_>K9-A&&(_=K9-A);const z=F/Math.pow(qoe(_),M);let H=z*Math.sin(M*p),Z=F-z*Math.cos(M*p);return H=.5*(H/Math.PI+.5),Z=.5*(Z/Math.PI+.5),{x:H,y:this.southernCenter?Z:1-Z,z:0}}unproject(p,_){p=(2*p-.5)*Math.PI,this.southernCenter&&(_=1-_),_=(2*(1-_)-.5)*Math.PI;const{n:A,f:M}=this,F=M-_,z=Math.sign(F),H=Math.sign(A)*Math.sqrt(p*p+F*F);let Z=Math.atan2(p,Math.abs(F))*z;F*A<0&&(Z-=Math.PI*Math.sign(p)*z);const se=ta(Eo(Z/A)+this.center[0],-180,180),fe=ta(Eo(2*Math.atan(Math.pow(M/H,1/A))-K9),-85.051129,L);return new Ll(se,this.southernCenter?-fe:fe)}}class Gdt extends dM{constructor(p){super(p),this.wrap=!0,this.supportsWorldCopies=!0,this.supportsTerrain=!0,this.supportsFog=!0,this.supportsFreeCamera=!0,this.isReprojectedInTileSpace=!1,this.unsupportedLayers=[],this.range=null}project(p,_){return{x:ex(p),y:ap(_),z:0}}unproject(p,_){const A=Ox(p),M=Hd(_);return new Ll(A,M)}}const Wdt=Xr(L);class nms extends dM{project(p,_){const A=(_=Xr(_))*_,M=A*A;return{x:.5*((p=Xr(p))*(.8707-.131979*A+M*(M*(.003971*A-.001529*M)-.013791))/Math.PI+.5),y:1-.5*(_*(1.007226+A*(.015085+M*(.028874*A-.044475-.005916*M)))/Math.PI+1),z:0}}unproject(p,_){p=(2*p-.5)*Math.PI;let A=_=(2*(1-_)-1)*Math.PI,M=25,F=0,z=A*A;do{z=A*A;const se=z*z;F=(A*(1.007226+z*(.015085+se*(.028874*z-.044475-.005916*se)))-_)/(1.007226+z*(.045255+se*(.259866*z-.311325-.005916*11*se))),A=ta(A-F,-Wdt,Wdt)}while(Math.abs(F)>1e-6&&--M>0);z=A*A;const H=ta(Eo(p/(.8707+z*(z*(z*z*z*(.003971-.001529*z)-.013791)-.131979))),-180,180),Z=Eo(A);return new Ll(H,Z)}}const Kdt=Xr(L);class rms extends dM{project(p,_){_=Xr(_),p=Xr(p);const A=Math.cos(_),M=2/Math.PI,F=Math.acos(A*Math.cos(p/2)),z=Math.sin(F)/F,H=.5*(p*M+2*A*Math.sin(p/2)/z)||0,Z=.5*(_+Math.sin(_)/z)||0;return{x:.5*(H/Math.PI+.5),y:1-.5*(Z/Math.PI+1),z:0}}unproject(p,_){let A=p=(2*p-.5)*Math.PI,M=_=(2*(1-_)-1)*Math.PI,F=25;const z=1e-6;let H=0,Z=0;do{const se=Math.cos(M),fe=Math.sin(M),xe=2*fe*se,be=fe*fe,Te=se*se,De=Math.cos(A/2),Ue=Math.sin(A/2),Ye=2*De*Ue,st=Ue*Ue,ot=1-Te*De*De,mt=ot?1/ot:0,lt=ot?Math.acos(se*De)*Math.sqrt(1/ot):0,yt=.5*(2*lt*se*Ue+2*A/Math.PI)-p,Nt=.5*(lt*fe+M)-_,as=.5*mt*(Te*st+lt*se*De*be)+1/Math.PI,Et=mt*(Ye*xe/4-lt*fe*Ue),$t=.125*mt*(xe*Ue-lt*fe*Te*Ye),Jt=.5*mt*(be*De+lt*st*se)+.5,ns=Et*$t-Jt*as;H=(Nt*Et-yt*Jt)/ns,Z=(yt*$t-Nt*as)/ns,A=ta(A-H,-Math.PI,Math.PI),M=ta(M-Z,-Kdt,Kdt)}while((Math.abs(H)>z||Math.abs(Z)>z)&&--F>0);return new Ll(Eo(A),Eo(M))}}class Ydt extends dM{constructor(p){super(p),this.center=p.center||[0,0],this.parallels=p.parallels||[0,0],this.cosPhi=Math.max(.01,Math.cos(Xr(this.parallels[0]))),this.scale=1/(2*Math.max(Math.PI*this.cosPhi,1/this.cosPhi)),this.wrap=!0,this.supportsWorldCopies=!0}project(p,_){const{scale:A,cosPhi:M}=this;return{x:Xr(p)*M*A+.5,y:-Math.sin(Xr(_))/M*A+.5,z:0}}unproject(p,_){const{scale:A,cosPhi:M}=this,F=-(_-.5)/A,z=ta(Eo((p-.5)/A)/M,-180,180),H=Math.asin(ta(F*M,-1,1)),Z=ta(Eo(H),-85.051129,L);return new Ll(z,Z)}}class ams extends Gdt{constructor(p){super(p),this.requiresDraping=!0,this.supportsWorldCopies=!1,this.supportsFog=!0,this.zAxisUnit="pixels",this.unsupportedLayers=["debug"],this.range=[3,5]}projectTilePoint(p,_,A){const M=MY(p,_,A);return Xe(M,M,Boe(WC(A))),{x:M[0],y:M[1],z:M[2]}}locationPoint(p,_,A){const M=O3(_.lat,_.lng),F=qe([],M),z=A?p._centerAltitude+A:p.elevation?p.elevation.getAtPointOrZero(p.locationCoordinate(_),p._centerAltitude):p._centerAltitude;ke(M,M,F,eu(1,0)*Fr*z);const H=w(new Float64Array(16));return E(H,p.pixelMatrix,p.globeMatrix),Xe(M,M,H),new xs(M[0],M[1])}pixelsPerMeter(p,_){return eu(1,0)*_}pixelSpaceConversion(p,_,A){const M=eu(1,p)*_,F=ya(eu(1,45)*_,M,A);return this.pixelsPerMeter(p,_)/F}createTileMatrix(p,_,A){const M=fOe(WC(A.canonical));return E(new Float64Array(16),p.globeMatrix,M)}createInversionMatrix(p,_){const{center:A}=p,M=Boe(WC(_));return D(M,M,Xr(A.lng)),R(M,M,Xr(A.lat)),P(M,M,[p._pixelsPerMercatorPixel,p._pixelsPerMercatorPixel,1]),Float32Array.from(M)}pointCoordinate(p,_,A,M){return Fdt(p,_,A,!0)||new Q(0,0)}pointCoordinate3D(p,_,A){const M=this.pointCoordinate(p,_,A,0);return[M.x,M.y,M.z]}isPointAboveHorizon(p,_){return!Fdt(p,_.x,_.y,!1)}farthestPixelDistance(p){const _=function(M,F){const z=M.cameraToCenterDistance,H=M._centerAltitude*F,Z=M._camera,se=M._camera.forward(),fe=ue([],Fe([],se,-z),[0,0,H]),xe=M.worldSize/(2*Math.PI),be=[0,0,-xe],Te=M.width/M.height,De=Math.tan(M.fovAboveCenter),Ue=Fe([],Z.up(),De),Ye=Fe([],Z.right(),De*Te),st=qe([],ue([],ue([],se,Ue),Ye)),ot=[];let mt;if(new Roe(fe,st).closestPointOnSphere(be,xe,ot)){const lt=ue([],ot,be),yt=xt([],lt,fe);mt=Math.cos(M.fovAboveCenter)*ce(yt)}else{const lt=xt([],fe,be),yt=xt([],be,fe);qe(yt,yt);const Nt=ce(lt)-xe;mt=Math.sqrt(Nt*(Nt+2*xe));const as=Math.acos(mt/(xe+Nt))-Math.acos(ze(se,yt));mt*=Math.cos(as)}return 1.01*mt}(p,this.pixelsPerMeter(p.center.lat,p.worldSize)),A=H3(p.zoom);if(A>0){const M=qdt(p,eu(1,p.center.lat)*p.worldSize),F=p.worldSize/(2*Math.PI),z=Math.max(p.width,p.height)/p.worldSize*Math.PI;return ya(_,M+F*(1-Math.cos(z)),Math.pow(A,10))}return _}upVector(p,_,A){return MY(_,A,p,1)}upVectorScale(p){return{metersToTile:Doe(Ooe(WC(p)))}}}function Voe(N){const p=N.parallels,_=!!p&&Math.abs(p[0]+p[1])<.01;switch(N.name){case"mercator":return new Gdt(N);case"equirectangular":return new tms(N);case"naturalEarth":return new nms(N);case"equalEarth":return new ems(N);case"winkelTripel":return new rms(N);case"albers":return _?new Ydt(N):new Jhs(N);case"lambertConformalConic":return _?new Ydt(N):new sms(N);case"globe":return new ams(N)}throw new Error(`Invalid projection name: ${N.name}`)}const DY=Number.MAX_SAFE_INTEGER,ims=DY-1;function yOe(N,p,_,A){return N.orderp.max.x||N.max.xp.max.y||N.max.ynew xs((Z.x+F.x*Fr)*H-z.x*Fr,(Z.y+F.y*Fr)*H-z.y*Fr))}return bOe(_,M,N.indices,0,N.indices.length,0,0)}function _Oe(N,p,_,A){const M=Math.pow(2,A.z-_.z);return new xs((N+_.x*Fr)*M-A.x*Fr,(p+_.y*Fr)*M-A.y*Fr)}function Woe(N,p){const _=[];p.grid.queryPoint(N,_);const A=p.indices,M=p.vertices;for(let F=0;F<_.length;F++){const z=_[F];if(aM([M[A[3*z+0]],M[A[3*z+1]],M[A[3*z+2]]],N))return!0}return!1}const FY={None:0,Model:1,Symbol:2,FillExtrusion:4};function wOe(N,p,_){const A=p[0],M=p[1];return N[0]=_[0]*A+_[4]*M+_[12],N[1]=_[1]*A+_[5]*M+_[13],N[3]=_[3]*A+_[7]*M+_[15],N}class jOe{isDataAvailableAtPoint(p){const _=this._source();if(this.isUsingMockSource()||!_||p.y<0||p.y>1)return!1;const A=_.getSource().maxzoom,M=1<1)return _;const F=M.getSource().maxzoom,z=1<{const Z=this.getAtTileOffset(p,F,z,H),se=M.upVector(p.canonical,F.x,F.y);return Fe(se,se,Z*M.upVectorScale(p.canonical,_,A).metersToTile),se}}getForTilePoints(p,_,A,M){if(this.isUsingMockSource())return!1;const F=Y9.create(this,p,M);return!!F&&(_.forEach(z=>{z[2]=this.exaggeration()*F.getElevationAt(z[0],z[1],A,!0)}),!0)}getMinMaxForTile(p){if(this.isUsingMockSource())return null;const _=this.findDEMTileFor(p);if(!_||!_.dem)return null;const A=_.dem.tree,M=_.tileID,F=1<"u"?null:new TextDecoder("utf-8");class Yoe{constructor(p){this.buf=ArrayBuffer.isView(p)?p:new Uint8Array(p),this.dataView=new DataView(this.buf.buffer,this.buf.byteOffset,this.buf.byteLength),this.pos=0,this.type=0,this._valueStart=-1,this.length=this.buf.length}readFields(p,_,A=this.length){let M;for(;M=this.nextField(A);)p(M,_,this);return _}readMessage(p,_){return this.readFields(p,_,this.readVarint()+this.pos)}readFixed32(){const p=this.dataView.getUint32(this.pos,!0);return this.pos+=4,p}readSFixed32(){const p=this.dataView.getInt32(this.pos,!0);return this.pos+=4,p}readFixed64(){const p=this.dataView.getUint32(this.pos,!0)+this.dataView.getUint32(this.pos+4,!0)*SOe;return this.pos+=8,p}readSFixed64(){const p=this.dataView.getUint32(this.pos,!0)+this.dataView.getInt32(this.pos+4,!0)*SOe;return this.pos+=8,p}readFloat(){const p=this.dataView.getFloat32(this.pos,!0);return this.pos+=4,p}readDouble(){const p=this.dataView.getFloat64(this.pos,!0);return this.pos+=8,p}readVarint(p){const _=this.buf,A=_[this.pos++];if(A<128)return A;let M,F=127&A;return M=_[this.pos++],F|=(127&M)<<7,M<128?F:(M=_[this.pos++],F|=(127&M)<<14,M<128?F:(M=_[this.pos++],F|=(127&M)<<21,M<128?F:(M=_[this.pos],F|=(15&M)<<28,function(z,H,Z){const se=Z.buf;let fe,xe;if(xe=se[Z.pos++],fe=(112&xe)>>4,xe<128||(xe=se[Z.pos++],fe|=(127&xe)<<3,xe<128)||(xe=se[Z.pos++],fe|=(127&xe)<<10,xe<128)||(xe=se[Z.pos++],fe|=(127&xe)<<17,xe<128)||(xe=se[Z.pos++],fe|=(127&xe)<<24,xe<128)||(xe=se[Z.pos++],fe|=(1&xe)<<31,xe<128))return Z9(z,fe,H);throw new Error("Expected varint not more than 10 bytes")}(F,p,this))))}readSVarint(){const p=this.readVarint();return p%2==1?(p+1)/-2:p/2}readBoolean(){return!!this.readVarint()}readString(){const p=this.readVarint()+this.pos,_=this.pos;return this.pos=p,p-_>=12&&rut?rut.decode(this.buf.subarray(_,p)):function(A,M,F){let z="",H=M;for(;H239?4:Z>223?3:Z>191?2:1;if(H+Te>F)break;Te===1?Z<128&&(be=Z):Te===2?(se=A[H+1],(192&se)==128&&(be=(31&Z)<<6|63&se,be<=127&&(be=null))):Te===3?(se=A[H+1],fe=A[H+2],(192&se)==128&&(192&fe)==128&&(be=(15&Z)<<12|(63&se)<<6|63&fe,(be<=2047||be>=55296&&be<=57343)&&(be=null))):Te===4&&(se=A[H+1],fe=A[H+2],xe=A[H+3],(192&se)==128&&(192&fe)==128&&(192&xe)==128&&(be=(15&Z)<<18|(63&se)<<12|(63&fe)<<6|63&xe,(be<=65535||be>=1114112)&&(be=null))),be===null?(be=65533,Te=1):be>65535&&(be-=65536,z+=String.fromCharCode(be>>>10&1023|55296),be=56320|1023&be),z+=String.fromCharCode(be),H+=Te}return z}(this.buf,_,p)}readBytes(){const p=this.readVarint()+this.pos,_=this.buf.subarray(this.pos,p);return this.pos=p,_}readPackedVarint(p=[],_){const A=this.readPackedEnd();for(;this.pos=p)return 0;const _=this.readVarint();return this.type=7&_,this._valueStart=this.pos,_>>>3}skip(p){const _=7&p;if(_===0)for(;this.buf[this.pos++]>127;);else if(_===2)this.pos=this.readVarint()+this.pos;else if(_===5)this.pos+=4;else{if(_!==1)throw new Error(`Unimplemented type: ${_}`);this.pos+=8}}}function Z9(N,p,_){return _?4294967296*p+(N>>>0):4294967296*(p>>>0)+(N>>>0)}function aut(N,p,_){const A=p<=16383?1:p<=2097151?2:p<=268435455?3:Math.floor(Math.log(p)/(7*Math.LN2));_.realloc(A),_.buf.copyWithin(N+A,N,_.pos)}function lms(N,p){const _=N.length;let A=p.buf,M=p.pos,F=p.length;for(let z=0;z<_;z++){let H=N[z];if(H<0||M+10>F)p.pos=M,p.writeVarint(H),A=p.buf,M=p.pos,F=p.length;else{for(;H>127;)A[M++]=H%128|128,H=Math.floor(H/128);A[M++]=H}}p.pos=M}function cms(N,p){for(let _=0;_H.h-z.h);const A=[{x:0,y:0,w:Math.max(Math.ceil(Math.sqrt(p/.95)),_),h:1/0}];let M=0,F=0;for(const z of N)for(let H=A.length-1;H>=0;H--){const Z=A[H];if(!(z.w>Z.w||z.h>Z.h)){if(z.x=Z.x,z.y=Z.y,F=Math.max(F,z.y+z.h),M=Math.max(M,z.x+z.w),z.w===Z.w&&z.h===Z.h){const se=A.pop();se&&Hp.id?1:N.versionp.version?1:N.sxp.sx?1:N.syp.sy?1:0}function Xoe(N){let p=0;for(let _=0;_0,out(p,A,this.iconDescriptors,z),out(_,A,this.patternDescriptors,z),this.iconDescriptors.sort(Zoe),this.patternDescriptors.sort(Zoe);let H=0;H=mj(H,Xoe(F)),H=mj(H,1);const Z=M?M.data:"";Z&&(H=mj(H,Xoe(Z))),H=mj(H,1);for(const se of this.iconDescriptors)H=mj(H,Xoe(se.id)),H=mj(H,se.version),H=mj(H,se.sx),H=mj(H,se.sy);H=mj(H,1);for(const se of this.patternDescriptors)H=mj(H,Xoe(se.id)),H=mj(H,se.version),H=mj(H,se.sx),H=mj(H,se.sy);this.hash=H}subsetOf(p){return this.scope===p.scope&&this.isSubsetArray(this.iconDescriptors,p.iconDescriptors,Zoe)&&this.isSubsetArray(this.patternDescriptors,p.patternDescriptors,Zoe)}isSubsetArray(p,_,A){let M=0,F=0;if(p.length>_.length)return!1;for(;M0&&fe>0){const be=this.useMipmap?Math.floor(Math.log2(Math.max(se,fe)))+1:1;z.texStorage2D(z.TEXTURE_2D,be,this.format,se,fe),this.size=[se,fe]}this.size&&(xe?z.texSubImage2D(z.TEXTURE_2D,0,H,Z,AOe(this.format),EOe(this.format),p):"data"in p&&p.data&&z.texSubImage2D(z.TEXTURE_2D,0,H,Z,A,M,AOe(this.format),EOe(this.format),p.data)),this.useMipmap&&z.generateMipmap(z.TEXTURE_2D)}bind(p,_,A=!1){const{context:M}=this,{gl:F}=M;F.bindTexture(F.TEXTURE_2D,this.texture),p!==this.minFilter&&(F.texParameteri(F.TEXTURE_2D,F.TEXTURE_MAG_FILTER,p),F.texParameteri(F.TEXTURE_2D,F.TEXTURE_MIN_FILTER,this.useMipmap&&!A?p===F.NEAREST?F.NEAREST_MIPMAP_NEAREST:F.LINEAR_MIPMAP_LINEAR:p),this.minFilter=p),_!==this.wrapS&&(F.texParameteri(F.TEXTURE_2D,F.TEXTURE_WRAP_S,_),F.texParameteri(F.TEXTURE_2D,F.TEXTURE_WRAP_T,_),this.wrapS=_)}bindExtraParam(p,_,A,M,F){const{context:z}=this,{gl:H}=z;H.bindTexture(H.TEXTURE_2D,this.texture),_!==this.magFilter&&(H.texParameteri(H.TEXTURE_2D,H.TEXTURE_MAG_FILTER,_),this.magFilter=_),p!==this.minFilter&&(H.texParameteri(H.TEXTURE_2D,H.TEXTURE_MIN_FILTER,this.useMipmap?p===H.NEAREST?H.NEAREST_MIPMAP_NEAREST:H.LINEAR_MIPMAP_LINEAR:p),this.minFilter=p),A!==this.wrapS&&(H.texParameteri(H.TEXTURE_2D,H.TEXTURE_WRAP_S,A),this.wrapS=A),M!==this.wrapT&&(H.texParameteri(H.TEXTURE_2D,H.TEXTURE_WRAP_T,M),this.wrapT=M),F!==this.compareMode&&(F?(H.texParameteri(H.TEXTURE_2D,H.TEXTURE_COMPARE_MODE,H.COMPARE_REF_TO_TEXTURE),H.texParameteri(H.TEXTURE_2D,H.TEXTURE_COMPARE_FUNC,F)):H.texParameteri(H.TEXTURE_2D,H.TEXTURE_COMPARE_MODE,H.NONE),this.compareMode=F)}destroy(){const{gl:p}=this.context;p.deleteTexture(this.texture),this.texture=null}}class lut{constructor(p,_,A,M){this.context=p,this.format=M,this.size=A,this.texture=p.gl.createTexture();const[F,z,H]=this.size,{gl:Z}=p;Z.bindTexture(Z.TEXTURE_3D,this.texture),p.pixelStoreUnpackFlipY.set(!1),p.pixelStoreUnpack.set(1),p.pixelStoreUnpackPremultiplyAlpha.set(!1),"data"in _&&_.data&&Z.texImage3D(Z.TEXTURE_3D,0,this.format,F,z,H,0,AOe(this.format),EOe(this.format),_.data)}bind(p,_){const{context:A}=this,{gl:M}=A;M.bindTexture(M.TEXTURE_3D,this.texture),p!==this.minFilter&&(M.texParameteri(M.TEXTURE_3D,M.TEXTURE_MAG_FILTER,p),M.texParameteri(M.TEXTURE_3D,M.TEXTURE_MIN_FILTER,p),this.minFilter=p),_!==this.wrapS&&(M.texParameteri(M.TEXTURE_3D,M.TEXTURE_WRAP_S,_),M.texParameteri(M.TEXTURE_3D,M.TEXTURE_WRAP_T,_),this.wrapS=_)}destroy(){const{gl:p}=this.context;p.deleteTexture(this.texture),this.texture=null}}class zY{static getImagePositionScale(p,_,A){if(_&&p){const{sx:M,sy:F}=p;return{x:M,y:F}}return{x:A,y:A}}constructor(p,_,A,M){this.paddedRect=p;const{pixelRatio:F,version:z,stretchX:H,stretchY:Z,content:se,sdf:fe,usvg:xe}=_;this.pixelRatio=F,this.stretchX=H,this.stretchY=Z,this.content=se,this.version=z,this.padding=A,this.sdf=fe,this.usvg=xe,this.scale=zY.getImagePositionScale(M,xe,F)}get tl(){return[this.paddedRect.x+this.padding,this.paddedRect.y+this.padding]}get br(){return[this.paddedRect.x+this.paddedRect.w-this.padding,this.paddedRect.y+this.paddedRect.h-this.padding]}get displaySize(){return[(this.paddedRect.w-2*this.padding)/this.scale.x,(this.paddedRect.h-2*this.padding)/this.scale.y]}}function cut(N,p,_){const A=Rh.parse(N),M=function(F,z,H=[1,1]){return{x:0,y:0,w:(F.data?F.data.width:F.width*H[0])+2*z,h:(F.data?F.data.height:F.height*H[1])+2*z}}(p,_,[A.sx,A.sy]);return{bin:M,imagePosition:new zY(M,p,_,A),imageVariant:A}}function TOe(N,p){const _=[];for(const[M,F]of N.entries()){const z=Rh.parse(M);z&&(_.push({key:M,value:F,variant:z}),p&&p.set(M,z))}_.sort((M,F)=>{const z=M.variant.id.toString().localeCompare(F.variant.id.toString());return z!==0?z:M.variant.sx!==F.variant.sx?M.variant.sx-F.variant.sx:M.variant.sy!==F.variant.sy?M.variant.sy-F.variant.sy:M.key.localeCompare(F.key)});const A=new Map;for(const M of _)A.set(M.key,M.value);return A}class dut{constructor(p){this.sourceAtlasHash=p}}class uut{constructor(p,_,A,M,F=""){const z=new Map,H=new Map;this.haveRenderCallbacks=[];const Z=[],se=M!==void 0,fe=se?new Map:void 0,xe=se?TOe(p,fe):p,be=se?TOe(_,fe):_;this.addImages(xe,z,1,Z),this.addImages(be,H,2,Z);const{w:Te,h:De}=iut(Z),Ue=new s0({width:Te||1,height:De||1});for(const[Ye,st]of xe.entries()){const ot=z.get(Ye).paddedRect;s0.copy(st.data,Ue,{x:0,y:0},{x:ot.x+1,y:ot.y+1},st.data,null,st.sdf)}for(const[Ye,st]of be.entries()){const ot=H.get(Ye),mt=ot.paddedRect;let lt=ot.padding;const yt=mt.x+lt,Nt=mt.y+lt,as=st.data.width,Et=st.data.height;lt=lt>1?lt-1:lt,s0.copy(st.data,Ue,{x:0,y:0},{x:yt,y:Nt},st.data,A),s0.copy(st.data,Ue,{x:0,y:Et-lt},{x:yt,y:Nt-lt},{width:as,height:lt},A),s0.copy(st.data,Ue,{x:0,y:0},{x:yt,y:Nt+Et},{width:as,height:lt},A),s0.copy(st.data,Ue,{x:as-lt,y:0},{x:yt-lt,y:Nt},{width:lt,height:Et},A),s0.copy(st.data,Ue,{x:0,y:0},{x:yt+as,y:Nt},{width:lt,height:Et},A),s0.copy(st.data,Ue,{x:as-lt,y:Et-lt},{x:yt-lt,y:Nt-lt},{width:lt,height:lt},A),s0.copy(st.data,Ue,{x:0,y:Et-lt},{x:yt+as,y:Nt-lt},{width:lt,height:lt},A),s0.copy(st.data,Ue,{x:0,y:0},{x:yt+as,y:Nt+Et},{width:lt,height:lt},A),s0.copy(st.data,Ue,{x:as-lt,y:0},{x:yt-lt,y:Nt+Et},{width:lt,height:lt},A)}this.lut=A,this.image=Ue,this.iconPositions=z,this.patternPositions=H,se&&(this.contentDescriptor=new COe(xe,be,M,A,F,fe))}addImages(p,_,A,M){for(const[F,z]of p.entries()){const{bin:H,imagePosition:Z,imageVariant:se}=cut(F,z,A);_.set(F,Z),M.push(H),z.hasRenderCallback&&this.haveRenderCallbacks.push(se.id)}}patchUpdatedImages(p,_,A,M){this.haveRenderCallbacks=this.haveRenderCallbacks.filter(F=>p.hasImage(F,A)),p.dispatchRenderCallbacks(this.haveRenderCallbacks,A);for(const F of p.getUpdatedImages(A)){for(const z of this.iconPositions.keys()){const H=Rh.parse(z);if(_d.isEqual(H.id,F)){const Z=p.getImage(F,A);this.patchUpdatedImage(this.iconPositions.get(z),Z,_,null)}}for(const z of this.patternPositions.keys()){const H=Rh.parse(z);if(_d.isEqual(H.id,F)){const Z=p.getImage(F,A);this.patchUpdatedImage(this.patternPositions.get(z),Z,_,M||this.lut)}}}}patchUpdatedImage(p,_,A,M=null){if(!p||!_||p.version===_.version)return;p.version=_.version;const[F,z]=p.tl,H=p.sdf;if(this.lut||H){const Z={width:_.data.width,height:_.data.height},se=new s0(Z);s0.copy(_.data,se,{x:0,y:0},{x:0,y:0},Z,M,H),A.update(se,{position:{x:F,y:z},recreateWhenResize:!1})}else A.update(_.data,{position:{x:F,y:z},recreateWhenResize:!1})}}oa(zY,"ImagePosition"),oa(uut,"ImageAtlas",{omit:["lut"]}),oa(dut,"ImageAtlasReference");class BY{constructor(p){this.pendingRequests=new Map,this.cachedRanges=new Map,this.fontstackCompositing=p&&p.fontstackCompositing||"client"}loadGlyphRange(p,_,A,M,F){if(this.fontstackCompositing==="server")return void BY.loadGlyphRange(p,_,A,M,F);const z=p.split(",").map(H=>H.trim()).filter(H=>H.length>0);z.length!==0?z.length!==1?this._loadMultipleFonts(z,_,A,M,F):this._loadFont(z[0],_,A,M,F):F(new Error("Empty fontstack"))}_loadMultipleFonts(p,_,A,M,F){const z=p.map(()=>null),H={completed:0,firstError:null,callbackCalled:!1},Z=(se,fe,xe)=>{if(!H.callbackCalled&&(fe&&!H.firstError&&(H.firstError=fe),xe&&(z[se]=xe),H.completed++,H.completed===p.length)){H.callbackCalled=!0;const be=z.filter(De=>De!==null);if(be.length===0)return void F(H.firstError||new Error("All fonts failed to load"));const Te=this._composeGlyphs(be);F(null,Te)}};for(let se=0;se{Z(se,fe,xe)})}_loadFont(p,_,A,M,F){const z=`${p}:${_}`;if(this.cachedRanges.has(z)){const Z=this.cachedRanges.get(z);return void oh.frame(()=>F(null,Z))}const H=this.pendingRequests.get(z);H?H.push(F):(this.pendingRequests.set(z,[F]),BY.loadGlyphRange(p,_,A,M,(Z,se)=>{Z||this.cachedRanges.set(z,se||null);const fe=this.pendingRequests.get(z);if(this.pendingRequests.delete(z),fe)for(const xe of fe)xe(Z,se)}))}_composeGlyphs(p){const _={};let A,M;for(const F of p)if(A===void 0&&F.ascender!==void 0&&(A=F.ascender),M===void 0&&F.descender!==void 0&&(M=F.descender),F.glyphs)for(const z in F.glyphs)_[z]===void 0&&(_[z]=F.glyphs[z]);return{glyphs:_,ascender:A,descender:M}}}BY.loadGlyphRange=async function(N,p,_,A,M){const F=256*p,z=F+255;let H;try{const Z=await A.transformRequest(A.normalizeGlyphsURL(_).replace("{fontstack}",N).replace("{range}",`${F}-${z}`),vr.Glyphs),{data:se}=await Qr(Z),fe={},xe=function(be){return function(Te){const De={glyphs:[]};let Ue;for(;Ue=Te.nextField();)Ue===1&&xms(Te,Te.readVarint()+Te.pos,De);return De}(new Yoe(be))}(se);for(const be of xe.glyphs)fe[be.id]=be;H={glyphs:fe,ascender:xe.ascender,descender:xe.descender}}catch(Z){return M(Z)}M(null,H)};const $Y=1e20,MOe=new Float64Array(256);for(let N=0;N<256;N++){const p=.5-Math.pow(N/255,.45454545454545453);MOe[N]=p*Math.abs(p)}function hut(N,p,_,A,M,F,z,H,Z){for(let se=p;se-1);Z++,F[Z]=H,z[Z]=se,z[Z+1]=$Y}for(let H=0,Z=0;H{if(z){M.ascender=z.ascender,M.descender=z.descender;for(const H in z.glyphs)this._doesCharSupportLocalGlyph(+H)||(M.glyphs[+H]=z.glyphs[+H]);M.ranges[_]=!0}for(const H of M.requests[_]||[])H(F,z);delete M.requests[_]}))}getGlyphs(p,_){const A=[],M=this.url||gt.GLYPHS_URL;for(const F in p)for(const z of p[F])A.push({stack:F,id:z});Co(A,({stack:F,id:z},H)=>{let Z=this.entries[F];Z||(Z=this.entries[F]={glyphs:{},requests:{},ranges:{},ascender:void 0,descender:void 0});let se=Z.glyphs[z];if(se!==void 0)return void H(null,{stack:F,id:z,glyph:se});if(se=this._tinySDF(Z,F,z),se)return Z.glyphs[z]=se,void H(null,{stack:F,id:z,glyph:se});const fe=Math.floor(z/256);if(256*fe>65535)return Yo("glyphs > 65535 not supported"),void H(null,{stack:F,id:z,glyph:se});if(Z.ranges[fe])return void H(null,{stack:F,id:z,glyph:se});let xe=Z.requests[fe];xe||(xe=Z.requests[fe]=[],this.glyphLoader.loadGlyphRange(F,fe,M,this.requestManager,(be,Te)=>{if(Te){Z.ascender=Te.ascender,Z.descender=Te.descender;for(const De in Te.glyphs)this._doesCharSupportLocalGlyph(+De)||(Z.glyphs[+De]=Te.glyphs[+De]);Z.ranges[fe]=!0}for(const De of xe)De(be,Te);delete Z.requests[fe]})),xe.push((be,Te)=>{be?H(be):Te&&H(null,{stack:F,id:z,glyph:Te.glyphs[z]||null})})},(F,z)=>{if(F)_(F);else if(z){const H={};for(const{stack:Z,id:se,glyph:fe}of z)H[Z]===void 0&&(H[Z]={}),H[Z].glyphs===void 0&&(H[Z].glyphs={}),H[Z].glyphs[se]=fe&&{id:fe.id,bitmap:fe.bitmap.clone(),metrics:fe.metrics},H[Z].ascender=this.entries[Z].ascender,H[Z].descender=this.entries[Z].descender;_(null,H)}})}_doesCharSupportLocalGlyph(p){return this.localGlyphMode!==POe.none&&(this.localGlyphMode===POe.all?!!this.localFontFamily:!!this.localFontFamily&&(UC(p)||L3(p)||BC(p)||$C(p)||Hk(p)||Wk(p)||(_=p)>=131072&&_<=173791||(A=>A>=66736&&A<=66815)(p)));var _}_tinySDF(p,_,A){const M=this.localFontFamily;if(!M||!this._doesCharSupportLocalGlyph(A))return;let F=p.tinySDF;if(!F){let Ye="400";vms.test(_)?Ye="900":bms.test(_)?Ye="500":_ms.test(_)&&(Ye="200"),F=p.tinySDF=new Joe.TinySDF({fontFamily:M,fontWeight:Ye,fontSize:48,buffer:6,radius:16}),F.fontWeight=Ye}const z=F.fontWeight;if(this.localGlyphs[z][A])return this.localGlyphs[z][A];const H=String.fromCodePoint(A),{data:Z,width:se,height:fe,glyphWidth:xe,glyphHeight:be,glyphLeft:Te,glyphTop:De,glyphAdvance:Ue}=F.draw(H);return this.localGlyphs[z][A]={id:A,bitmap:new iM({width:se,height:fe},Z),metrics:{width:xe/2,height:be/2,left:Te/2,top:De/2-27,advance:Ue/2,localGlyph:!0}}}}function fut(N,p){return N+p[1]-p[0]}function put(N,p,_,A,M=1){const F=[],z=N.imagePrimary,H=z.pixelRatio,Z=z.paddedRect.w-2,se=z.paddedRect.h-2,fe=(N.right-N.left)*M,xe=(N.bottom-N.top)*M,be=z.stretchX||[[0,Z]],Te=z.stretchY||[[0,se]],De=be.reduce(fut,0),Ue=Te.reduce(fut,0),Ye=Z-De,st=se-Ue;let ot=0,mt=De,lt=0,yt=Ue,Nt=0,as=Ye,Et=0,$t=st;if(z.content&&A){const ns=z.content;ot=ele(be,0,ns[0]),lt=ele(Te,0,ns[1]),mt=ele(be,ns[0],ns[2]),yt=ele(Te,ns[1],ns[3]),Nt=ns[0]-ot,Et=ns[1]-lt,as=ns[2]-ns[0]-mt,$t=ns[3]-ns[1]-yt}const Jt=(ns,Ls,Gs,pn)=>{const cn=tle(ns.stretch-ot,mt,fe,N.left*M),jn=sle(ns.fixed-Nt,as,ns.stretch,De),Hn=tle(Ls.stretch-lt,yt,xe,N.top*M),Cs=sle(Ls.fixed-Et,$t,Ls.stretch,Ue),Qs=tle(Gs.stretch-ot,mt,fe,N.left*M),an=sle(Gs.fixed-Nt,as,Gs.stretch,De),Ln=tle(pn.stretch-lt,yt,xe,N.top*M),In=sle(pn.fixed-Et,$t,pn.stretch,Ue),Vn=new xs(cn,Hn),Dn=new xs(Qs,Hn),ir=new xs(Qs,Ln),Bn=new xs(cn,Ln),Rr=new xs(jn/H,Cs/H),cr=new xs(an/H,In/H),jr=p*Math.PI/180;if(jr){const Ni=Math.sin(jr),Fo=Math.cos(jr),rl=[Fo,-Ni,Ni,Fo];Vn._matMult(rl),Dn._matMult(rl),Bn._matMult(rl),ir._matMult(rl)}const Wa=ns.stretch+ns.fixed,Ka=Gs.stretch+Gs.fixed,oi=Ls.stretch+Ls.fixed,Fa=pn.stretch+pn.fixed,Ai=N.imageSecondary;return{tl:Vn,tr:Dn,bl:Bn,br:ir,texPrimary:{x:z.paddedRect.x+1+Wa,y:z.paddedRect.y+1+oi,w:Ka-Wa,h:Fa-oi},texSecondary:Ai?{x:Ai.paddedRect.x+1+Wa,y:Ai.paddedRect.y+1+oi,w:Ka-Wa,h:Fa-oi}:void 0,writingMode:void 0,glyphOffset:[0,0],sectionIndex:0,pixelOffsetTL:Rr,pixelOffsetBR:cr,minFontScaleX:as/H/fe,minFontScaleY:$t/H/xe,isSDF:_}};if(z.stretchX||z.stretchY){const ns=gut(be,Ye,De),Ls=gut(Te,st,Ue);for(let Gs=0;Gs0?[ot,-mt]:lt<0?[-ot,mt]:ot===0?[mt,ot]:[mt,-ot]}(_);let Te=Math.abs(p.top-p.bottom);for(const st of p.positionedLines)Te-=st.lineOffset;const De=p.positionedLines.length,Ue=Te/De;let Ye=p.top-_[1];for(let st=0;stfunction(F){if(!F.condition)return{featureDependent:!1,stateDependent:!1,zoomDependent:!1,pitchDependent:!1,brightnessDependent:!1,worldviewDependent:!1};const z=F.condition.expression;return{featureDependent:!$1(z),stateDependent:!H0(z),zoomDependent:!zx(z,["zoom"]),pitchDependent:!zx(z,["pitch"]),brightnessDependent:!zx(z,["brightness","measure-light"]),worldviewDependent:!zx(z,["worldview"])}}(M));this.anyFeatureDependent=A.some(M=>M.featureDependent),this.anyStateDependent=A.some(M=>M.stateDependent)}update(p,_){const A=this.lastParams,M=!A||A.zoom!==p.zoom||A.pitch!==(p.pitch||0)||A.brightness!==(p.brightness||0)||A.worldview!==p.worldview;this.lastParams={zoom:p.zoom,pitch:p.pitch||0,brightness:p.brightness||0,worldview:p.worldview};const F=_&&this.anyStateDependent;if(!M&&!F&&this.lastAllFeaturesIndex!==-2)return{kind:"no-changes"};if(!this.anyFeatureDependent&&!F){const z=this.evaluateAllFeatures(p);return z===this.lastAllFeaturesIndex?{kind:"no-changes"}:(this.lastAllFeaturesIndex=z,{kind:"all-features",appearanceIndex:z})}return{kind:"per-feature"}}evaluateAllFeatures(p){for(let _=0;_z-H),F=new Map;for(const z of M){const H=A.get(z);F.set(z,new Ri(H))}return _&&(this.cachedBatchIndices=M,this.cachedBatchSegments=F),{batchIndices:M,batchSegments:F}}snapshotSymbolVertexData(p,_){const A=p*X9;return this.layoutVertexArray.uint16.slice(A,A+_*X9)}restoreSymbolVertexData(p,_){this.layoutVertexArray.uint16.set(_,p*X9)}snapshotIconTransitioningVertexData(p,_){const A=2*p;return this.iconTransitioningVertexArray.uint16.slice(A,A+2*_)}restoreIconTransitioningVertexData(p,_){this.iconTransitioningVertexArray.uint16.set(_,2*p)}updateSymbolVertexData(p,_,A,M,F,z,H,Z,se,fe,xe,be,Te){const De=this.layoutVertexArray.uint16,Ue=p*X9;De[Ue]=_,De[Ue+1]=A,De[Ue+2]=M,De[Ue+3]=F,De[Ue+4]=z,De[Ue+5]=H,De[Ue+6]=Z,De[Ue+7]=se,De[Ue+8]=fe,De[Ue+9]=xe,De[Ue+10]=be,De[Ue+11]=Te}upload(p,_,A,M,F,z){this.isEmpty()||(A&&(this.cachedBatchIndices=null,this.cachedBatchSegments=null,this.layoutVertexBuffer=p.createVertexBuffer(this.layoutVertexArray,Chs.members,!!z),this.indexBuffer=p.createIndexBuffer(this.indexArray,_),this.dynamicLayoutVertexBuffer=p.createVertexBuffer(this.dynamicLayoutVertexArray,Ehs.members,!0),this.opacityVertexBuffer=p.createVertexBuffer(this.opacityVertexArray,kms,!0),this.iconTransitioningVertexArray.length>0&&(this.iconTransitioningVertexBuffer=p.createVertexBuffer(this.iconTransitioningVertexArray,Ihs.members,!0)),this.globeExtVertexArray.length>0&&(this.globeExtVertexBuffer=p.createVertexBuffer(this.globeExtVertexArray,Ahs.members,!0)),!this.zOffsetVertexBuffer&&(this.zOffsetVertexArray.length>0||F)&&(this.zOffsetVertexBuffer=p.createVertexBuffer(this.zOffsetVertexArray,Ths.members,!0)),!this.orientationVertexBuffer&&this.orientationVertexArray&&this.orientationVertexArray.length>0&&(this.orientationVertexBuffer=p.createVertexBuffer(this.orientationVertexArray,Phs.members,!0)),this.opacityVertexBuffer.itemSize=1,this.featureIdArray.length>0&&(this.featureIdBuffer=p.createVertexBuffer(this.featureIdArray,Mhs.members,!1))),(A||M)&&(this.programConfigurations.upload(p),this.uboBinder&&this.uboBinder.upload(p)))}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())}}oa(IOe,"SymbolBuffers",{omit:["cachedBatchIndices","cachedBatchSegments"]});class LOe{constructor(p,_,A){this.layoutVertexArray=new p,this.layoutAttributes=_,this.indexArray=new A,this.segments=new Ri,this.collisionVertexArray=new Ga,this.collisionVertexArrayExt=new Hr}upload(p){this.layoutVertexBuffer=p.createVertexBuffer(this.layoutVertexArray,this.layoutAttributes),this.indexBuffer=p.createIndexBuffer(this.indexArray),this.collisionVertexBuffer=p.createVertexBuffer(this.collisionVertexArray,Lhs.members,!0),this.collisionVertexBufferExt=p.createVertexBuffer(this.collisionVertexArrayExt,Rhs.members,!0)}destroy(){this.layoutVertexBuffer&&(this.layoutVertexBuffer.destroy(),this.indexBuffer.destroy(),this.segments.destroy(),this.collisionVertexBuffer.destroy(),this.collisionVertexBufferExt.destroy())}}oa(LOe,"CollisionBuffers");class rle{constructor(p){this.collisionBoxArray=p.collisionBoxArray,this.zoom=p.zoom,this.overscaling=p.overscaling,this.layers=p.layers,this.layerIds=this.layers.map(z=>z.fqid),this.index=p.index,this.pixelRatio=p.pixelRatio,this.sourceLayerIndex=p.sourceLayerIndex,this.hasPattern=!1,this.hasRTLText=!1,this.fullyClipped=!1,this.hasAnyIconTextFit=!1,this.sortKeyRanges=[],this.placementIdRangeStart=null,this.placementVariantVisible=[],this.collisionCircleArray=[],this.placementInvProjMatrix=w([]),this.placementViewportMatrix=w([]);const _=this.layers[0]._unevaluatedLayout._values;this.worldview=p.worldview,this.localizable=p.localizable,this.maxUniformBufferBindings=p.maxUniformBufferBindings,this.maxUniformBlockSizeDwords=p.maxUniformBlockSizeDwords,this.textSizeData=G9(this.zoom,_["text-size"],this.worldview,p.availableImages),this.iconSizeData=G9(this.zoom,_["icon-size"],this.worldview,p.availableImages);const A=this.layers[0].layout,M=A.get("symbol-sort-key"),F=A.get("symbol-z-order");this.lut=p.lut,this.canOverlap=A.get("text-allow-overlap")||A.get("icon-allow-overlap")||A.get("text-ignore-placement")||A.get("icon-ignore-placement"),this.sortFeaturesByKey=F!=="viewport-y"&&M.constantOr(1)!==void 0,this.sortFeaturesByY=(F==="viewport-y"||F==="auto"&&!this.sortFeaturesByKey)&&this.canOverlap,this.writingModes=A.get("text-writing-mode").map(z=>$3[z]),this.stateDependentLayerIds=this.layers.filter(z=>z.isStateDependent()).map(z=>z.id),this.sourceID=p.sourceID,this.projection=p.projection,this.hasAnyZOffset=!1,this.zOffsetSortDirty=!1,this.zOffsetBuffersNeedUpload=!1,this.elevationType="none",this.activeReplacements=[],this.replacementUpdateTime=0,this.hasAnySecondaryIcon=!1,this.hasAppearances=null,this.featureAppearances=null,this.featureAppearanceData=new Map}hasAnyAppearanceLayoutProperty(p){const _=this.layers[0].getAppearances();if(!_||_.length===0)return!1;const A=Array.isArray(p)?p:[p];return _.some(M=>A.some(F=>M.hasLayoutProperty(F)))}getAppearanceFeatureData(p){return this.featureAppearanceData.get(p)}createArrays(){this.text=new IOe(new Yk(this.layers,{zoom:this.zoom,lut:this.lut},p=>p.startsWith("text")||p.startsWith("symbol"))),this.icon=new IOe(new Yk(this.layers,{zoom:this.zoom,lut:this.lut},p=>p.startsWith("icon")||p.startsWith("symbol"))),this.text.uboBinder=new iOe(this.layers[0],this.zoom,this.lut,!0,"",this.maxUniformBufferBindings,this.maxUniformBlockSizeDwords),this.icon.uboBinder=new iOe(this.layers[0],this.zoom,this.lut,!1,"",this.maxUniformBufferBindings,this.maxUniformBlockSizeDwords),this.glyphOffsetArray=new Xh,this.lineVertexArray=new ug,this.symbolInstances=new _c}calculateGlyphDependencies(p,_,A,M,F){for(const z of p){const H=z.codePointAt(0);if(H===void 0)break;if(_[H]=!0,M&&F&&H<=65535){const Z=TY[z];Z&&(_[Z.charCodeAt(0)]=!0)}}}calculateEffectiveAppearanceIconSize(p,_,A,M,F,z,H){if(!p.hasLayoutProperty("icon-size"))return H*z;let Z=1;const se=p.getUnevaluatedLayoutProperty("icon-size"),fe=G9(this.zoom,se,this.worldview,F),xe=U3(fe,_);if(fe.kind!=="constant"&&fe.kind!=="camera"||(Z=xe.uSize),fe.kind==="composite"){const{minZoom:be,maxZoom:Te}=fe,De=se.possiblyEvaluate(new Kn(be,{worldview:this.worldview}),M),Ue=se.possiblyEvaluate(new Kn(Te,{worldview:this.worldview}),M),Ye=De.evaluate(A,{},M,F);Z=Ye+(Ue.evaluate(A,{},M,F)-Ye)*xe.uSizeT}return fe.kind==="source"&&(Z=se.possiblyEvaluate(new Kn(this.zoom,{worldview:this.worldview}),M).evaluate(A,{},M,F)),Z*z}updateFootprints(p,_){}hideSymbolVariant(p,_){this._setSymbolVariantVisibility(p,!1)}showSymbolVariant(p,_){this._setSymbolVariantVisibility(p,!0)}_initPlacementOpacities(){const p=_=>{const A=_.layoutVertexArray.length/4;for(let M=0;M{if(Z<0)return;const se=H.placedSymbolArray.get(Z),fe=se.vertexStartIndex/4;for(let xe=0;xe{for(let A=0;A<_.opacityVertexArray.length;A++)_.opacityVertexArray.emplace(A,0);_.opacityVertexBuffer&&_.opacityVertexBuffer.updateData(_.opacityVertexArray)};this.hasTextData()&&p(this.text),this.hasIconData()&&p(this.icon)}addToPlacement(p,_,A,M,F,z,H,Z,se,fe,xe,be){if(this.symbolInstances.length===0)return;if(be&&this.updateReplacement(H.tileID,be),!this.collisionArrays){if(!H.collisionBoxArray)return;this.deserializeCollisionBoxes(H.collisionBoxArray)}this.placementIdRangeStart===null&&(this.placementIdRangeStart=_.allocateRange(A,this.symbolInstances.length),this.placementVariantVisible=new Array(this.symbolInstances.length).fill(!1),this._initPlacementOpacities());const Te=this.placementIdRangeStart,De=this.layers[0];if(De.appearances&&De.appearances.length>0)return void Yo("new placement: symbol appearances are not supported yet; hiding symbols");if(De.layout.get("symbol-placement")!=="point")return void Yo("new placement: along-line symbol placement is not supported yet; hiding symbols");const Ue=!!De.layout.get("text-variable-anchor"),Ye=this.getProjection(),st=Ye.name!=="globe";st||Yo("new placement: globe projection is not supported yet; hiding symbols");const ot=H.tileID.toUnwrapped(),mt=F.pitch>0,lt={collisionRules:{},insertIntoCollisionGrid:!0},yt=F.zoom,Nt=U3(this.iconSizeData,yt),as=U3(this.textSizeData,yt),Et=De.paint.get("symbol-z-offset"),$t=De.layout.get("symbol-elevation-reference")==="sea",Jt=!Et.isConstant(),ns=Jt?0:Et.evaluate(null,{}),Ls=F.elevation,Gs=sut(fe),pn=Bn=>{if(!Bn)return Gs;const Rr=se.get(G6(Bn,De.scope));return Rr!==void 0?Rr:(Yo(`global placement: placement-group "${Bn}" does not match any placement-group layer; using the layer's implicit group`),Gs)},cn=De.paint.get("placement-priority"),jn=De.paint.get("placement-group"),Hn=!cn.isConstant(),Cs=!jn.isConstant(),Qs=Hn?0:cn.evaluate(null,{}),an=Cs?Gs:pn(jn.evaluate(null,{})),Ln=Hn||Cs,In=Jt||Ln?H.latestFeatureIndex:null;In&&In.loadVTLayers();const Vn=In?In.sourceLayerCoder.decode(this.sourceLayerIndex):"",Dn=(Bn,Rr,cr)=>{let jr;if(this.elevationType==="road")jr=$t?cr:cr+jOe.getAtTileOffset(H.tileID,new xs(Bn.tileAnchorX,Bn.tileAnchorY),Ls,null);else{const Ai=this.hdExt?this.hdExt.elevationFeatures[Rr.elevationFeatureIndex]:void 0;jr=$t?cr:cr+jOe.getAtTileOffset(H.tileID,new xs(Bn.tileAnchorX,Bn.tileAnchorY),Ls,Ai)}if(jr+=Rr.zOffset,!jr)return{x:Bn.projectedAnchorX,y:Bn.projectedAnchorY,z:Bn.projectedAnchorZ,elevated:!1};const[Wa,Ka,oi]=Ye.upVector(H.tileID.canonical,Bn.tileAnchorX,Bn.tileAnchorY),Fa=Ye.upVectorScale(H.tileID.canonical,F.center.lat,F.worldSize).metersToTile;return{x:Bn.projectedAnchorX+Wa*jr*Fa,y:Bn.projectedAnchorY+Ka*jr*Fa,z:Bn.projectedAnchorZ+oi*jr*Fa,elevated:!0}},ir=(Bn,Rr,cr,jr)=>{if(!Bn)return;const{x:Wa,y:Ka,z:oi,elevated:Fa}=Dn(Bn,Rr,cr),Ai=function(Z0,Jh,_l,Wd,fh,Hm,mo,fp,Lp){const xf=[Jh,_l,Wd,1];let Vx=!1;Wd||fh.pitch>0?(Ft(xf,xf,Z0),fp&&Hm.name!=="globe"&&(Vx=Jdt(fp,Jh,_l,Wd,Lp,fh)>.9)):wOe(xf,xf,Z0);const Hx=xf[3];return{x:(xf[0]/Hx+1)/2*fh.width,y:(-xf[1]/Hx+1)/2*fh.height,perspectiveRatio:Math.min(.5+fh.getCameraToCenterDistance(Hm)/Hx*.5,1.5),occluded:mo&&xf[2]>Hx||Vx}}(M,Wa,Ka,oi,F,Ye,mt||Fa,Z,ot);if(Ai.occluded||Ai.perspectiveRatio<=.55)return;const Ni=jr(),Fo=z*Ai.perspectiveRatio,rl=(Bn.x1*Ni-Bn.padding)*Fo+Ai.x,$l=(Bn.y1*Ni-Bn.padding)*Fo+Ai.y,wc=(Bn.x2*Ni+Bn.padding)*Fo+Ai.x,Vm=(Bn.y2*Ni+Bn.padding)*Fo+Ai.y;rl0||Rr.numVerticalGlyphVertices>0)){Yo("new placement: text-variable-anchor is not supported yet; skipping symbols");continue}if(Rr.numVerticalGlyphVertices>0){Yo("new placement: vertical text-writing-mode is not supported yet; skipping symbols");continue}const cr=this.collisionArrays[Bn];if(!cr.iconBox&&!cr.textBox)continue;let jr=!1;for(const Fo of this.activeReplacements)if(!yOe(Fo,fe,FY.Symbol,De.scope)&&!(Fo.min.x>Rr.tileAnchorX||Rr.tileAnchorX>Fo.max.x||Fo.min.y>Rr.tileAnchorY||Rr.tileAnchorY>Fo.max.y)&&(jr=Woe(_Oe(Rr.tileAnchorX,Rr.tileAnchorY,H.tileID.canonical,Fo.footprintTileId.canonical),Fo.footprint),jr))break;const Wa={symbolId:{styleLayerId:A,symbolIdOrigin:1,symbolId:Te+Bn},variantIdx:0},Ka=In?In.loadFeature({featureIndex:Rr.featureIndex,sourceLayerIndex:this.sourceLayerIndex,bucketIndex:this.index,layoutVertexArrayOffset:0}):null,oi=Ln&&Ka&&In?In.getId(Ka,Vn):void 0,Fa=oi!==void 0&&xe[String(oi)]||Cms,Ai=Hn&&Ka?cn.evaluate(Ka,Fa):Qs,Ni=Cs&&Ka?pn(jn.evaluate(Ka,Fa)):an;if(p.startSymbolVariantProcessing(Wa,{placementSubgroupOrder:Ni,symbolPlacementPriority:Ai,symbolVariantVisibility:this.placementVariantVisible[Bn]?kOe.VARIANT_VISIBLE:kOe.SYMBOL_INVISIBLE,symbolPlacementType:1,styleLayerOrder:fe,symbolDisplayOrder:0},lt),st&&!jr){const Fo=Jt&&Ka?Et.evaluate(Ka,{}):ns;ir(cr.iconBox,Rr,Fo,()=>this.getSymbolInstanceIconSize(Nt,yt,Rr.placedIconSymbolIndex)),ir(cr.textBox,Rr,Fo,()=>this.getSymbolInstanceTextSize(as,Rr,yt,Bn))}p.finishVariantProcessing()}}updateReplacement(p,_){if(_.updateTime===this.replacementUpdateTime)return!1;this.replacementUpdateTime=_.updateTime;const A=_.getReplacementRegionsForTile(p.toUnwrapped(),!0);return!Goe(this.activeReplacements,A)&&(this.activeReplacements=A,!0)}getResolvedImageFromTokens(p){return typeof p=="string"?vh.build(p):p}populate(p,_,A,M){const F=this.layers[0],z=F.layout,H=this.projection.name==="globe",Z=z.get("text-font"),se=z.get("text-field"),fe=z.get("icon-image"),[xe,be]=z.get("icon-size-scale-range"),Te=ta(_.scaleFactor||1,xe,be),[De,Ue]=z.get("text-size-scale-range"),Ye=ta(_.scaleFactor||1,De,Ue),st=(se.value.kind!=="constant"||se.value.value instanceof vu&&!se.value.value.isEmpty()||se.value.value.toString().length>0)&&(Z.value.kind!=="constant"||Z.value.value.length>0),ot=fe.value.kind!=="constant"||!!fe.value.value||Object.keys(fe.parameters).length>0,mt=this.hasAnyAppearanceLayoutProperty("icon-image"),lt=z.get("symbol-sort-key");if(this.features=[],this.featureAppearanceData=new Map,!st&&!ot&&!mt)return;const yt=_.iconDependencies,Nt=_.glyphDependencies,as=_.availableImages,Et=new Kn(this.zoom,{worldview:this.worldview,activeFloors:_.activeFloors}),$t=Jt=>{const ns=Jt.id.toString();yt.has(ns)?yt.get(ns).push(Jt):yt.set(ns,[Jt])};for(const Jt of p){const{feature:ns,id:Ls,index:Gs,sourceLayerIndex:pn}=Jt,cn=F._featureFilter.needGeometry,jn=_t(ns,cn);if(!F._featureFilter.filter(Et,jn,A))continue;if(cn||(jn.geometry=ht(ns,A,M)),H&&ns.type!==1&&A.z<=5){const Dn=jn.geometry,ir=.98078528056,Bn=(Rr,cr)=>ze(MY(Rr.x,Rr.y,A,1),MY(cr.x,cr.y,A,1)){if(!Dn.getLayoutProperty("icon-image"))return;const{iconPrimary:ir,iconSecondary:Bn}=this.getCombinedIconVariants(Dn,Qs,jn,A,as,In,Te);ir&&($t(ir),Bn&&(this.hasAnySecondaryIcon=!0,$t(Bn)))}),Hn){const Dn=Z.evaluate(jn,{},A).join(","),ir=z.get("text-rotation-alignment")==="map"&&z.get("symbol-placement")!=="point";this.allowVerticalPlacement=this.writingModes&&this.writingModes.includes($3.vertical);for(const Bn of Hn.sections)if(Bn.image){const Rr=Bn.image.getPrimary().scaleSelf(this.pixelRatio*Ye),cr=Rr.id.toString(),jr=yt.get(cr)||[];jr.push(Rr),yt.set(cr,jr)}else{const Rr=de(Hn.toString()),cr=Bn.fontStack||Dn,jr=Nt[cr]=Nt[cr]||{};this.calculateGlyphDependencies(Bn.text,jr,ir,this.allowVerticalPlacement,Rr)}}}z.get("symbol-placement")==="line"&&(this.features=function(Jt){const ns={},Ls={},Gs=[];let pn=0;function cn(Qs){Gs.push(Jt[Qs]),pn++}function jn(Qs,an,Ln){const In=Ls[Qs];return delete Ls[Qs],Ls[an]=In,Gs[In].geometry[0].pop(),Gs[In].geometry[0]=Gs[In].geometry[0].concat(Ln[0]),In}function Hn(Qs,an,Ln){const In=ns[an];return delete ns[an],ns[Qs]=In,Gs[In].geometry[0].shift(),Gs[In].geometry[0]=Ln[0].concat(Gs[In].geometry[0]),In}function Cs(Qs,an,Ln){const In=Ln?an[0].at(-1):an[0][0];return`${Qs}:${In.x}:${In.y}`}for(let Qs=0;Qs1){cn(Qs);continue}const Vn=Cs(In,Ln,!1),Dn=Cs(In,Ln,!0);if(Vn in Ls&&Dn in ns&&Ls[Vn]!==ns[Dn]){const ir=Hn(Vn,Dn,Ln),Bn=jn(Vn,Dn,Gs[ir].geometry);delete ns[Vn],delete Ls[Dn],Ls[Cs(In,Gs[Bn].geometry,!0)]=Bn,Gs[ir].geometry=null}else Vn in Ls?jn(Vn,Dn,Ln):Dn in ns?Hn(Vn,Dn,Ln):(cn(Qs),ns[Vn]=pn-1,Ls[Dn]=pn-1)}return Gs.filter(Qs=>Qs.geometry)}(this.features)),z.get("symbol-elevation-reference")==="hd-road-markup"?(this.elevationType="road",this.hdExt&&(this.hdExt.configureCrossSource(A,_.elevationParams,_.crossSourceElevationEnabled,_.terrainEnabled),_.elevationFeatures&&_.elevationFeatures.length>0&&this.hdExt.addElevationFeatures(_.elevationFeatures,A))):z.get("symbol-z-elevate")&&(this.elevationType="offset"),this.elevationType!=="none"&&(this.zOffsetBuffersNeedUpload=!0),this.sortFeaturesByKey&&this.features.sort((Jt,ns)=>Jt.sortKey-ns.sortKey)}getCombinedIconVariants(p,_,A,M,F,z,H){let Z;if(p.hasLayoutProperty("icon-image")){const se=_.getAppearanceValueAndResolveTokens(p,"icon-image",A,M,F);Z=this.getResolvedImageFromTokens(se)}else{const se=_.getValueAndResolveTokens("icon-image",A,M,F);Z=this.getResolvedImageFromTokens(se)}if(Z){const se=p.hasLayoutProperty("icon-size")?p.getUnevaluatedLayoutProperty("icon-size"):_._unevaluatedLayout._values["icon-size"],fe=G9(this.zoom,se,this.worldview,F),{iconPrimary:xe,iconSecondary:be}=oOe(Z,fe,se,M,this.zoom,z,this.pixelRatio,H,this.worldview,F);return{iconPrimary:xe,iconSecondary:be}}return{iconPrimary:void 0,iconSecondary:void 0}}getCombinedIconPrimary(p,_,A,M,F,z,H){return this.getCombinedIconVariants(p,_,A,M,F,z,H).iconPrimary}updateSymbolInstanceIconVertices(p,_,A,M,F,z){const{canonical:H,availableImages:Z,globalProperties:se,layer:fe,iconScaleFactor:xe,featureState:be,layoutIconOffset:Te,layoutIconSize:De,layoutIconRotate:Ue}=z;if(p.placedIconSymbolIndex<0)return{vertexOffsetDelta:0,hasChanges:!1};if(_.activeAppearanceIndex===A)return{vertexOffsetDelta:p.numIconVertices,hasChanges:!1};const Ye=A>=0?fe.appearances[A]:null;if(Ye){const st={sortKey:void 0,text:void 0,icon:null,index:p.featureIndex,sourceLayerIndex:p.featureIndex,geometry:[],properties:_.properties,type:"Point",id:_.id},{iconPrimary:ot,iconSecondary:mt}=this.getCombinedIconVariants(Ye,fe,M,H,Z,st,xe);if(!ot)return{vertexOffsetDelta:0,hasChanges:!1};const lt=ot.toString(),yt=this.iconAtlasPositions&&this.iconAtlasPositions.get(lt);if(yt){const{appearanceIconOffset:Nt,appearanceIconRotate:as}=Edt(Ye,fe,M,H,Te,Ue,De,xe),Et=fe.layout.get("icon-anchor").evaluate(M,be,H);let $t=Cdt(yt,mt?this.iconAtlasPositions&&this.iconAtlasPositions.get(mt.toString()):void 0,Nt,Et);const Jt=yt.sdf,ns=fe.layout.get("icon-text-fit").constantOr("none");ns!=="none"&&_.textShaping&&_.iconTextFitPadding&&_.fontScale&&($t=Adt($t,_.textShaping,ns,_.iconTextFitPadding,Nt,_.fontScale));const Ls=this.calculateEffectiveAppearanceIconSize(Ye,se.zoom,M,H,Z,xe,De),Gs=0,pn=1+(Math.min(nR,Math.round(Ls*oM))<<1),cn=put($t,as,Jt,ns!=="none",xe),jn=this.icon.iconTransitioningVertexArray.length>0;_.isUsingAppearanceIconVertexData||(_.isUsingAppearanceIconVertexData=!0,_.layoutBasedIconVertexData=this.icon.snapshotSymbolVertexData(F,p.numIconVertices),jn&&(_.layoutBasedIconTransitioningVertexData=this.icon.snapshotIconTransitioningVertexData(F,p.numIconVertices)));const Hn=Math.floor(p.numIconVertices/4),Cs=Math.min(cn.length,Hn);let Qs=F;const an=jn?this.icon.iconTransitioningVertexArray.uint16:null;for(let In=0;In0||p.numVerticalGlyphVertices>0;if(!lt)return{vertexOffsetDelta:lt?p.numHorizontalGlyphVertices+p.numVerticalGlyphVertices:0,hasChanges:!1};if(_.activeAppearanceIndex===A)return{vertexOffsetDelta:p.numHorizontalGlyphVertices+p.numVerticalGlyphVertices,hasChanges:!1};const yt=A>=0?Z.appearances[A]:null;if(yt&&_.textShaping){const{appearanceTextOffset:Nt,appearanceTextRotate:as,appearanceTextSize:Et}=Tdt(yt,Z,M,H,be,De,Te);_.fontScale=Pdt(Et,_.textScaleFactor);const $t=yt.getUnevaluatedLayoutProperty("text-size");let Jt=this.textSizeData,ns=st,Ls=ot;yt.hasLayoutProperty("text-size")&&(Jt=G9(this.zoom,$t,this.worldview,mt),ns=this.textSizeData.kind==="composite"?this.textSizeData.minZoom:0,Ls=this.textSizeData.kind==="composite"?this.textSizeData.maxZoom:0);const Gs=_.textShaping.bottom-be[1],pn=_.textShaping.left-be[0],cn=_.textShaping.right-be[0];_.textShaping.top=Nt[1]+(_.textShaping.top-be[1]),_.textShaping.bottom=Nt[1]+Gs,_.textShaping.left=Nt[0]+pn,_.textShaping.right=Nt[0]+cn;const jn=yut(0,_.textShaping,Nt,Z,!1,M,fe,this.allowVerticalPlacement,as),Hn=Et&&Jt.kind==="composite"?$t.possiblyEvaluate(new Kn(ns,{}),H).evaluate(M,xe,H):Ue,Cs=Et&&Jt.kind==="composite"?$t.possiblyEvaluate(new Kn(Ls,{}),H).evaluate(M,xe,H):Ye,Qs=Idt(yt.name,Jt,Et,se,Hn,Cs),an=Array.isArray(Qs)?Qs[1]:Et,Ln=0,In=1+(Math.min(nR,Math.round(an*oM))<<1);_.isUsingAppearanceTextVertexData||(_.isUsingAppearanceTextVertexData=!0,_.layoutBasedTextVertexData=this.text.snapshotSymbolVertexData(F,p.numHorizontalGlyphVertices+p.numVerticalGlyphVertices));for(let Vn=0;Vn0){const se=F[0],fe=[this.text.uboBinder,this.icon.uboBinder].filter(xe=>xe&&xe.hasStateDependentPaint(se));if(fe.length>0){const xe=new Set(Object.keys(p).map(be=>{const Te=Number(be);return!isNaN(Te)&&Number.isSafeInteger(Te)&&String(Te)===be?Te:be}));for(const be of fe)be.updateFeatures(xe,se,_,Z,A,p,H)}}}}updateZOffset(){const p=(F,z,H)=>{A+=z,A>F.length&&F.resize(A);for(let Z=-z;Z<0;Z++)F.emplace(Z+A,H)},_=(F,z,H)=>{M+=z,M>F.length&&F.resize(M);for(let Z=-z;Z<0;Z++)F.emplace(Z+M,H)};if(!this.zOffsetBuffersNeedUpload)return;this.zOffsetBuffersNeedUpload=!1;let A=0,M=0;for(let F=0;F0;if((H>0||Z>0)&&(p(this.text.zOffsetVertexArray,H,fe),p(this.text.zOffsetVertexArray,Z,fe)),xe){const{placedIconSymbolIndex:be,verticalPlacedIconSymbolIndex:Te}=z;be>=0&&_(this.icon.zOffsetVertexArray,se,fe),Te>=0&&_(this.icon.zOffsetVertexArray,z.numVerticalIconVertices,fe)}}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(p,_,A,M,F){!this.uploaded&&this.hasDebugData()&&(this.textCollisionBox.upload(p),this.iconCollisionBox.upload(p)),this.text.upload(p,this.sortFeaturesByY,!this.uploaded,this.text.programConfigurations.needsUpload,this.zOffsetBuffersNeedUpload,this.hasAppearances),this.hasAppearances===null&&(this.hasAppearances=this.layers.some(z=>z.appearances&&z.appearances.length>0)),this.icon.upload(p,this.sortFeaturesByY,!this.uploaded,this.icon.programConfigurations.needsUpload,this.zOffsetBuffersNeedUpload,this.hasAppearances),this.uploaded=!0}updateAppearances(p,_,A,M,F,z=!1){const H={hasLayoutChanges:!1,hasUboChanges:!1};if(!p||!A||!this.featureAppearanceData)return H;const Z=_||{},se=this.icon.layoutVertexArray&&this.icon.layoutVertexArray.length>0&&this.icon.layoutVertexArray.arrayBuffer,fe=this.text.layoutVertexArray&&this.text.layoutVertexArray.length>0&&this.text.layoutVertexArray.arrayBuffer;if(!se&&!fe)return H;const xe=this.layers[0],be=xe.layout;this.featureAppearances&&this.featureAppearances.appearancesVersion===xe.appearancesVersion||(this.featureAppearances=new jms(xe.appearances,xe.appearancesVersion));const Te=this.featureAppearances.update(M,z);if(Te.kind==="no-changes")return H;let De=1,Ue=0,Ye=!1,st=!1;if(se){const[as,Et]=be.get("icon-size-scale-range");De=ta(1,as,Et)}let ot=1,mt=0,lt=!1;if(fe){const[as,Et]=be.get("text-size-scale-range");ot=ta(1,as,Et)}const yt=new Map;if(F&&A)for(const as of A){const Et=F.getImage(as,xe.scope);if(Et){const $t=new Rh(as.toString());yt.set($t.toString(),Et)}}const Nt=[this.text.uboBinder,this.icon.uboBinder];for(let as=0;asjn.isActive({globals:M,feature:Ls,canonical:p,featureState:ns})):-1;Gs=cn>=0?cn:-1}const pn=$t.activeAppearanceIndex!==Gs;if(fe){const cn=be.get("text-size"),jn=this.textSizeData.kind==="composite"?this.textSizeData.minZoom:0,Hn=this.textSizeData.kind==="composite"?this.textSizeData.maxZoom:0,Cs={canonical:p,layer:xe,featureState:ns,availableImages:A,textScaleFactor:ot,imageMap:yt,layoutTextOffset:be.get("text-offset").evaluate(Ls,ns,p).map(an=>an*H9),layoutTextSize:cn.evaluate(Ls,ns,p),layoutTextRotate:be.get("text-rotate").evaluate(Ls,ns,p),layoutMinZoomSize:cn.evaluate(Ls,{zoom:jn},p),layoutMaxZoomSize:cn.evaluate(Ls,{zoom:Hn},p),layoutTextSizeMinZoom:jn,layoutTextSizeMaxZoom:Hn},Qs=this.updateSymbolInstanceTextVertices(Et,$t,Gs,Ls,mt,Cs);mt+=Qs.vertexOffsetDelta,lt=lt||Qs.hasChanges}if(se){const cn={canonical:p,layer:xe,featureState:ns,availableImages:A,globalProperties:M,iconScaleFactor:De,layoutIconOffset:be.get("icon-offset").evaluate(Ls,ns,p),layoutIconSize:be.get("icon-size").evaluate(Ls,ns,p,A),layoutIconRotate:be.get("icon-rotate").evaluate(Ls,ns,p)},jn=this.updateSymbolInstanceIconVertices(Et,$t,Gs,Ls,Ue,cn);Ue+=jn.vertexOffsetDelta,Ye=Ye||jn.hasChanges}if(pn){const cn=Et.featureIndex,jn=M?M.brightness:null,Hn=ns||{},Cs=Gs>=0?xe.appearances[Gs]:null;for(const Qs of Nt)Qs&&(Qs.layer=xe,st=Qs.updateFeaturePaintForAppearance(cn,Ls,Hn,p,A,jn,Cs)||st)}$t.activeAppearanceIndex=Gs}return Ye&&this.icon.layoutVertexBuffer&&this.icon.layoutVertexArray.arrayBuffer!==null&&this.icon.layoutVertexArray.length===this.icon.layoutVertexBuffer.length&&this.icon.layoutVertexBuffer.updateData(this.icon.layoutVertexArray),Ye&&this.icon.iconTransitioningVertexBuffer&&this.icon.iconTransitioningVertexArray.length>0&&this.icon.iconTransitioningVertexArray.length===this.icon.iconTransitioningVertexBuffer.length&&this.icon.iconTransitioningVertexBuffer.updateData(this.icon.iconTransitioningVertexArray),lt&&this.text.layoutVertexBuffer&&this.text.layoutVertexArray.arrayBuffer!==null&&this.text.layoutVertexArray.length===this.text.layoutVertexBuffer.length&&this.text.layoutVertexBuffer.updateData(this.text.layoutVertexArray),{hasLayoutChanges:Ye||lt,hasUboChanges:st}}destroyDebugData(){this.textCollisionBox.destroy(),this.iconCollisionBox.destroy()}getProjection(){return this.projectionInstance||(this.projectionInstance=Voe(this.projection)),this.projectionInstance}destroy(){this.text.destroy(),this.icon.destroy(),this.hasDebugData()&&this.destroyDebugData()}addToLineVertexArray(p,_){const A=this.lineVertexArray.length;if(p.segment!==void 0)for(const{x:M,y:F}of _)this.lineVertexArray.emplaceBack(M,F);return{lineStartIndex:A,lineLength:this.lineVertexArray.length-A}}addSymbols(p,_,A,M,F,z,H,Z,se,fe,xe,be,Te,De,Ue,Ye,st,ot){const mt=p.indexArray,lt=p.layoutVertexArray,yt=p.globeExtVertexArray,Nt=ot,as=p.uboBinder?p.uboBinder.getCurrentBatchIndex():void 0,Et=p.segments.prepareSegment(4*Nt,lt,mt,this.canOverlap?z.sortKey:void 0,as),$t=this.glyphOffsetArray.length,Jt=Et.vertexLength,ns=this.allowVerticalPlacement&&H===$3.vertical?Math.PI/2:0,Ls=z.text&&z.text.sections;let Gs=lt.length,pn=-1;for(let Hn=0;Hn<_.length;Hn++){const{tl:Cs,tr:Qs,bl:an,br:Ln,texPrimary:In,texSecondary:Vn,pixelOffsetTL:Dn,pixelOffsetBR:ir,minFontScaleX:Bn,minFontScaleY:Rr,glyphOffset:cr,isSDF:jr,sectionIndex:Wa}=_[Hn],Ka=Et.vertexLength,oi=cr[1];if(UY(lt,se.x,se.y,Cs.x,oi+Cs.y,In.x,In.y,A,jr,Dn.x,Dn.y,Bn,Rr),UY(lt,se.x,se.y,Qs.x,oi+Qs.y,In.x+In.w,In.y,A,jr,ir.x,Dn.y,Bn,Rr),UY(lt,se.x,se.y,an.x,oi+an.y,In.x,In.y+In.h,A,jr,Dn.x,ir.y,Bn,Rr),UY(lt,se.x,se.y,Ln.x,oi+Ln.y,In.x+In.w,In.y+In.h,A,jr,ir.x,ir.y,Bn,Rr),Z){const{x:Fa,y:Ai,z:Ni}=Z.anchor,[Fo,rl,$l]=Z.up;VY(yt,Fa,Ai,Ni,Fo,rl,$l),VY(yt,Fa,Ai,Ni,Fo,rl,$l),VY(yt,Fa,Ai,Ni,Fo,rl,$l),VY(yt,Fa,Ai,Ni,Fo,rl,$l),rR(p.dynamicLayoutVertexArray,Fa,Ai,Ni,ns)}else rR(p.dynamicLayoutVertexArray,se.x,se.y,se.z,ns);if(Ye){const Fa=Vn||In;qY(p.iconTransitioningVertexArray,Fa.x,Fa.y),qY(p.iconTransitioningVertexArray,Fa.x+Fa.w,Fa.y),qY(p.iconTransitioningVertexArray,Fa.x,Fa.y+Fa.h),qY(p.iconTransitioningVertexArray,Fa.x+Fa.w,Fa.y+Fa.h)}if(mt.emplaceBack(Ka,Ka+1,Ka+2),mt.emplaceBack(Ka+1,Ka+2,Ka+3),Et.vertexLength+=4,Et.primitiveLength+=2,this.glyphOffsetArray.emplaceBack(cr[0]),(Hn===_.length-1||Wa!==_[Hn+1].sectionIndex)&&(p.uboBinder||p.programConfigurations.populatePaintArrays(lt.length,z,z.index,{},Te,De,Ue,Ls&&Ls[Wa],this.worldview),p.uboBinder)){const Fa=p.uboBinder.populateUBO(z,z.index,De,Te,Ue,Ls&&Ls[Wa]);pn=Fa;const Ai=lt.length-Gs;for(let Ni=0;Ni=0)){const Hn=4*cn;for(let Cs=0;Cs=0?p.rightJustifiedTextSymbolIndex:p.centerJustifiedTextSymbolIndex>=0?p.centerJustifiedTextSymbolIndex:p.leftJustifiedTextSymbolIndex>=0?p.leftJustifiedTextSymbolIndex:p.verticalPlacedTextSymbolIndex>=0?p.verticalPlacedTextSymbolIndex:_}getSymbolInstanceTextSize(p,_,A,M){const F=this.defaultPlacedTextSymbolIndex(_,M),z=this.text.placedSymbolArray.get(F),H=Ioe(this.textSizeData,p,z)/H9;return this.tilePixelRatio*H}getSymbolInstanceIconSize(p,_,A){const M=this.icon.placedSymbolArray.get(A),F=Ioe(this.iconSizeData,p,M);return this.tilePixelRatio*F}_commitDebugCollisionVertexUpdate(p,_,A,M){p.emplaceBack(_,-A,-A,M),p.emplaceBack(_,A,-A,M),p.emplaceBack(_,A,A,M),p.emplaceBack(_,-A,A,M)}_updateTextDebugCollisionBoxes(p,_,A,M,F,z,H){for(let Z=M;Z0}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(p,_){const A=p.placedSymbolArray.get(_),M=A.vertexStartIndex+4*A.numGlyphs;for(let F=A.vertexStartIndex;FM[H]-M[Z]||F[Z]-F[H]),z}getSortedIndexesByZOffset(){if(!this.zOffsetSortDirty)return this.symbolInstanceIndexesSortedZOffset;if(!this.symbolInstanceIndexesSortedZOffset){this.symbolInstanceIndexesSortedZOffset=[];for(let p=0;pthis.symbolInstances.get(_).zOffset-this.symbolInstances.get(p).zOffset)}addToSortKeyRanges(p,_){const A=this.sortKeyRanges.at(-1);A&&A.sortKey===_?A.symbolInstanceEnd=p+1:this.sortKeyRanges.push({sortKey:_,symbolInstanceStart:p,symbolInstanceEnd:p+1})}sortFeatures(p){if(this.sortFeaturesByY&&this.sortedAngle!==p)if(this.text.segments.get().length>1||this.icon.segments.get().length>1)this.sortFeaturesByY=!1;else{this.symbolInstanceIndexes=this.getSortedSymbolIndexes(p),this.sortedAngle=p,this.text.indexArray.clear(),this.icon.indexArray.clear(),this.featureSortOrder=[];for(const _ of this.symbolInstanceIndexes){const A=this.symbolInstances.get(_);this.featureSortOrder.push(A.featureIndex);const{rightJustifiedTextSymbolIndex:M,centerJustifiedTextSymbolIndex:F,leftJustifiedTextSymbolIndex:z,verticalPlacedTextSymbolIndex:H,placedIconSymbolIndex:Z,verticalPlacedIconSymbolIndex:se}=A;M>=0&&this.addIndicesForPlacedSymbol(this.text,M),F>=0&&F!==M&&this.addIndicesForPlacedSymbol(this.text,F),z>=0&&z!==F&&z!==M&&this.addIndicesForPlacedSymbol(this.text,z),H>=0&&this.addIndicesForPlacedSymbol(this.text,H),Z>=0&&this.addIndicesForPlacedSymbol(this.icon,Z),se>=0&&this.addIndicesForPlacedSymbol(this.icon,se)}this.text.indexBuffer&&this.text.indexBuffer.updateData(this.text.indexArray),this.icon.indexBuffer&&this.icon.indexBuffer.updateData(this.icon.indexArray)}}}oa(rle,"SymbolBucket",{omit:["layers","collisionBoxArray","compareText","features"]}),rle.addDynamicAttributes=rR;class vut extends GFe{constructor(p,_,A){super(p,_,A),this.elevatedLayoutVertexArray=new $s}upload(p){const _=this.uploaded;super.upload(p),!_&&this.elevatedLayoutVertexArray.length>0&&(this.elevatedLayoutVertexBuffer=p.createVertexBuffer(this.elevatedLayoutVertexArray,Qh.members))}destroy(){this.elevatedLayoutVertexBuffer&&this.elevatedLayoutVertexBuffer.destroy(),super.destroy()}}oa(vut,"ElevatedFillBufferData");class G3{constructor(){this.portals=[]}static isOnBorder(p,_){return p<=0&&_<=0||p>=Fr&&_>=Fr}static evaluate(p){if(p.length===0)return new G3;let _=[];for(const Z of p)_.push(...Z.portals);if(_.length===0)return new G3;for(const Z of _){const se=Z.va,fe=Z.vb;(G3.isOnBorder(se.x,fe.x)||G3.isOnBorder(se.y,fe.y))&&(Z.type="border")}const A=_.filter(Z=>Z.type!=="unevaluated"),M=_.filter(Z=>Z.type==="unevaluated");if(M.length===0)return new G3;M.sort((Z,se)=>Z.hash===se.hash?Z.isTunnel===se.isTunnel?0:Z.isTunnel?-1:1:Z.hashZ.hashF!=="fill-tunnel-structure-color"),this.tunnelProgramConfigurations=new Yk(_,{zoom:A,lut:M},F=>F!=="fill-bridge-guard-rail-color")}addVertices(p,_){const A=this.unevalVertices.length;for(let M=0;M=F.min.x&&xe.x<=F.max.x&&xe.y>=F.min.y&&xe.y<=F.max.y||be.x>=F.min.x&&be.x<=F.max.x&&be.y>=F.min.y&&be.y<=F.max.y||U9(xe,be,H))||this.isOnBorder(xe.x,be.x)||this.isOnBorder(xe.y,be.y))continue;const Te=Y1.computeEdgeHash(this.unevalVertices[se],this.unevalVertices[fe]);let De,Ue=this.vertexHashLookup.get(Y1.computePosHash(xe));Ue!=null?De=Ue.next:(Ue=this.vertexHashLookup.get(Y1.computePosHash(be)),De=Ue!=null?Ue.prev:Te),this.unevalEdges.push({polygonIdx:p,a:se,b:fe,hash:Te,portalHash:De,isTunnel:M,type:"unevaluated",featureInfo:z})}}addPortalCandidates(p,_,A,M,F){if(_.length!==0){this.vertexHashLookup.clear();for(const z of _){if(z.length===0)continue;const H=z[0];let Z=Y1.computeEdgeHash(H[H.length-2],H.at(-1));for(let se=0;se({vertexOffset:0,primitiveOffset:this.indexArray.length}),A=be=>{be.primitiveLength=this.indexArray.length-be.primitiveOffset},M=new Ams(this.vertexPositions,this.vertexNormals,this.indexArray);this.prepareEdges(p.portals,this.unevalEdges);const F=_(),z=_(),H=_(),Z=(be,Te)=>{be.sort((Ue,Ye)=>Ue.type===Te&&Ye.type!==Te?-1:Ue.type!==Te&&Ye.type===Te?1:0);const De=be.findIndex(Ue=>Ue.type!==Te);return De>=0?De:be.length};let se=0;this.unevalEdges.length>0&&(se=Z(this.unevalEdges,"none"),this.constructBridgeStructures(M,this.unevalVertices,this.unevalHeights,this.unevalEdges,{min:0,max:se},this.tileToMeters)),A(H);const fe=_(),xe=_();if(this.unevalEdges.length>0){const be=this.unevalEdges.splice(se),Te=Z(be,"tunnel")+se;this.unevalEdges.push(...be),this.constructTunnelStructures(M,this.unevalVertices,this.unevalHeights,this.unevalEdges,{min:0,max:se},{min:se,max:Te})}A(fe),M.addTriangles(this.unevalTriangles,this.unevalVertices,this.unevalHeights),A(xe),M.addTriangles(this.unevalTunnelTriangles,this.unevalVertices,this.unevalHeights),A(z),M.addTriangles(this.unevalTunnelTriangles,this.unevalVertices,this.unevalHeights,4),A(F),this.maskSegments=Ri.simpleSegment(0,xe.primitiveOffset,0,xe.primitiveLength),this.depthSegments=Ri.simpleSegment(0,z.primitiveOffset,0,z.primitiveLength),this.renderableBridgeSegments=Ri.simpleSegment(0,H.primitiveOffset,0,H.primitiveLength),this.renderableTunnelSegments=Ri.simpleSegment(0,fe.primitiveOffset,0,fe.primitiveLength),this.shadowCasterSegments=Ri.simpleSegment(0,F.primitiveOffset,0,F.primitiveLength)}update(p,_,A,M,F,z,H,Z){this.bridgeProgramConfigurations.updatePaintArrays(p,_,F,A,M,z,H,Z),this.tunnelProgramConfigurations.updatePaintArrays(p,_,F,A,M,z,H,Z)}upload(p){this.vertexBuffer||this.vertexPositions.length===0||this.vertexNormals.length===0||this.indexArray.length===0||(this.vertexBuffer=p.createVertexBuffer(this.vertexPositions,ix.members),this.vertexBufferNormal=p.createVertexBuffer(this.vertexNormals,Yu.members),this.indexBuffer=p.createIndexBuffer(this.indexArray),this.bridgeProgramConfigurations.upload(p),this.tunnelProgramConfigurations.upload(p))}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(p,_,A,M,F){const z=(H,Z)=>{for(let se=0;sehe(cn,_[jn].x,_[jn].y,A[jn]*Z),xe=te(),be=te(),Te=te(),De=te(),Ue=te(),Ye=(cn,jn)=>{const Hn=H.get(Y1.computePosHash(_[jn])),Cs=Hn.from,Qs=Hn.to;if(!Cs||!Qs)return;fe(xe,Cs),fe(be,jn),fe(Te,Qs),Ke(De),nt(xe,be)||(xt(Ue,be,xe),qe(De,Ue)),nt(Te,be)||(xt(Ue,Te,be),ue(De,De,qe(Ue,Ue)));const an=Yt(De);return an>0?Fe(cn,De,1/an):void 0};let st=Number.POSITIVE_INFINITY;this.sortSubarray(M,F.min,F.max,(cn,jn)=>cn.featureInfo.featureIndex-jn.featureInfo.featureIndex);const ot=te(),mt=te(),lt=te(),yt=te(),Nt=te(),as=te(),Et=te(),$t=te(),Jt=te(),ns=[te(),te(),te(),te()],Ls=[te(),te(),te(),te()],Gs=[{coord:new xs(0,0),height:0},{coord:new xs(0,0),height:0}],pn=(cn,jn)=>cn>jn;for(let cn=F.min;cnst.featureInfo.featureIndex-ot.featureInfo.featureIndex;this.sortSubarray(M,F.min,F.max,Z),this.sortSubarray(M,z.min,z.max,Z);const se=st=>qe(st,st),fe=[{coord:new xs(0,0),height:0},{coord:new xs(0,0),height:0}],xe=(st,ot)=>stH.hash===Z.hash?Z.polygonIdx-H.polygonIdx:Z.hash>H.hash?1:-1);let A=0,M=0,F=0,z=_[A].polygonIdx;do M++,(M===_.length||_[A].hash!==_[M].hash)&&((M-A===1||_[M-1].polygonIdx!==z)&&(Fse.portalHashfe.hash?H++:fe.hash>se.portalHash?Z++:(se.type=fe.type,H++)}}}isOnBorder(p,_){return p<=0&&_<=0||p>=Fr&&_>=Fr}addFeatureSection(p,_,A,M){return p!==_&&(_=p,A.push({featureIndex:p,vertexStart:M.getVertexCount()}),M.clearVertexLookup()),_}sortSubarray(p,_,A,M){const F=p.slice(_,A);F.sort(M),p.splice(_,F.length,...F)}static computeEdgeHash(p,_){return(p.y===_.y&&p.x>_.x||p.y>_.y)&&([p,_]=[_,p]),BigInt(Y1.computePosHash(p))<<32n|BigInt(Y1.computePosHash(_))}static computePosHash(p){return((65535&p.x)<<16|65535&p.y)>>>0}}class Ems{constructor(){this._valid=!1}reset(p){return this.feature=p,this._valid=!0,this._geometry=p.loadGeometry(),this._geometry.length!==0&&this._geometry[0].length!==0||(this._valid=!1),this}geometry(p,_){return this._valid&&p(_(this._geometry)),this}require(p,_,A){return this.get(p,!0,_,A)}optional(p,_,A){return this.get(p,!1,_,A)}success(){return this._valid}get(p,_,A,M){const F=Object.hasOwn(this.feature.properties,p)?+this.feature.properties[p]:void 0;return this._valid&&F!==void 0&&!Number.isNaN(F)?A(M?M(F):F):_&&(this._valid=!1),this}}class but{constructor(p,_){this.featureFunc=p,this.vertexFunc=_}parseFeature(p,_,A){return this.featureFunc(p,_,A)}parseVertex(p,_,A){return this.vertexFunc(p,_,A)}}const Tms=new but((N,p,_)=>N.reset(p).require(B3,A=>{_.id=A}).optional("fixed_height_relative",A=>{_.constantHeight=A},W3.decodeRelativeHeight).geometry(A=>{_.bounds=A},$d).success(),(N,p,_)=>N.reset(p).require(B3,A=>{_.id=A}).require("elevation_idx",A=>{_.idx=A}).require("extent",A=>{_.extent=A}).require("height_relative",A=>{_.height=A},W3.decodeRelativeHeight).geometry(A=>{_.position=A},W3.getPoint).success()),Mms=new but((N,p,_)=>N.reset(p).require(B3,A=>{_.id=A}).optional("fixed_height",A=>{_.constantHeight=A},W3.decodeMetricHeight).geometry(A=>{_.bounds=A},$d).success(),(N,p,_)=>N.reset(p).require(B3,A=>{_.id=A}).require("elevation_idx",A=>{_.idx=A}).require("extent",A=>{_.extent=A}).require("height",A=>{_.height=A},W3.decodeMetricHeight).geometry(A=>{_.position=A},W3.getPoint).success());class W3{static getPoint(p){return On(p[0][0].x,p[0][0].y)}static decodeRelativeHeight(p){return 1e-4*p*5}static decodeMetricHeight(p){return 1e-4*p}static getVersionSchema(p){return p?p==="1.0.1"?Mms:void 0:Tms}static parse(p){const _=[],A=[],M=p.length,F=new Ems;for(let z=0;z{return H.a0?Fe(Z,Z,1/se):he(Z,0,0,1)}getSafeArea(){return this.safeArea}isTunnel(){return this.heightRange.max<=-5}getClosestEdge(p){if(this.edges.length===0)return;let _=0,A=Number.POSITIVE_INFINITY,M=0;const[F,z,H,Z,se,fe,xe]=Pms;ds(xe,p.x,p.y);const be=new Ghs(xe,null);for(let Te=0;Te0?hn(Z,H)/lt:0,Nt=ta(yt,0,1),as=Math.abs((yt-Nt)*this.edgeProps[Te].len);As(se,xe,Ye),ds(fe,Ue[1],-Ue[0]);const Et=as+Math.abs(hn(se,fe));Et=0;--z){const H=this.edges[z].a,Z=this.edges[z].b,{position:se,height:fe,extent:xe}=this.vertices[H],{position:be,height:Te,extent:De}=this.vertices[Z],Ue=this.vertexProps[H].dir,Ye=this.vertexProps[Z].dir;if(he(_,se[0]/p,se[1]/p,fe),he(A,be[0]/p,be[1]/p,Te),he(M,Ue[1],-Ue[0],0),Fe(M,M,xe),he(F,Ye[1],-Ye[0],0),Fe(F,F,De),this.distSqLines(_e(_[0]+.5*M[0],_[1]+.5*M[1],_[2]+.5*M[2]),_e(A[0]-.5*F[0],A[1]-.5*F[1],A[2]-.5*F[2]),_e(_[0]-.5*M[0],_[1]-.5*M[1],_[2]-.5*M[2]),_e(A[0]+.5*F[0],A[1]+.5*F[1],A[2]+.5*F[2]))<=.0025000000000000005)continue;const st=this.vertices.length,ot=gn(Ws(),se,be);this.vertices.push({position:hr(ot,ot,.5),height:.5*(fe+Te),extent:.5*(xe+De),index:.5*((this.vertices[H].index!==void 0?this.vertices[H].index:H)+(this.vertices[Z].index!==void 0?this.vertices[Z].index:Z))});const mt=gn(Ws(),Ue,Ye);this.vertexProps.push({dir:qn(mt,mt)}),this.edges.splice(z,1),this.edgeProps.splice(z,1),this.edges.push({a:H,b:st}),this.edges.push({a:st,b:Z});const lt=As(Ws(),this.vertices[st].position,se),yt=Er(lt),Nt={vec:lt,dir:hr(Ws(),lt,1/yt),len:yt};this.edgeProps.push(Nt),this.edgeProps.push(Nt)}}distSqLines(p,_,A,M){const F=ve(te(),_,p),z=ve(te(),M,A),H=ve(te(),p,A),Z=ze(F,F),se=ze(F,z),fe=ze(F,H),xe=ze(z,z),be=ze(z,H),Te=Z*xe-se*se;if(Te===0)return je(ct(F,A,M,ze(H,z)/ze(z,z)),p);const De=(Z*be-se*fe)/Te;return je(ct(F,p,_,(se*be-fe*xe)/Te),ct(z,A,M,De))}static serialize(p,_){const A={id:p.id,heightRange:{min:p.heightRange.min,max:p.heightRange.max},safeArea:(M=p.safeArea,{min:{x:M.min.x,y:M.min.y},max:{x:M.max.x,y:M.max.y}})};var M;return p.constantHeight!=null?(A.constantHeight=p.constantHeight,A):p.vertices.length===0?(A.vertices=[],A.vertexProps=[],A.edges=[],A.edgeProps=[],A):(A.vertices=p.vertices.map(F=>({position:ale(F.position),height:F.height,extent:F.extent,index:F.index})),A.vertexProps=p.vertexProps.map(F=>({dir:ale(F.dir)})),A.edges=p.edges.map(F=>({a:F.a,b:F.b})),A.edgeProps=p.edgeProps.map(F=>({vec:ale(F.vec),dir:ale(F.dir),len:F.len})),A)}static deserialize(p){const _=function(M){return{min:new xs(M.min.x,M.min.y),max:new xs(M.max.x,M.max.y)}}(p.safeArea);if(p.constantHeight!=null)return new K3(p.id,_,p.constantHeight);if(!p.vertices||p.vertices.length===0){const M=Object.create(K3.prototype);return M.id=p.id,M.constantHeight=void 0,M.heightRange={min:p.heightRange.min,max:p.heightRange.max},M.safeArea=_,M.vertices=[],M.vertexProps=[],M.edges=[],M.edgeProps=[],M}const A=Object.create(K3.prototype);return A.id=p.id,A.constantHeight=void 0,A.heightRange={min:p.heightRange.min,max:p.heightRange.max},A.safeArea=_,A.vertices=p.vertices.map(M=>({position:ile(M.position),height:M.height,extent:M.extent,index:M.index})),A.vertexProps=(p.vertexProps||[]).map(M=>({dir:ile(M.dir)})),A.edges=(p.edges||[]).map(M=>({a:M.a,b:M.b})),A.edgeProps=(p.edgeProps||[]).map(M=>({vec:ile(M.vec),dir:ile(M.dir),len:M.len})),A}}class Q9{constructor(p,_){this.zScale=1,this.xOffset=0,this.yOffset=0,p.equals(_)||(this.zScale=Math.pow(2,_.z-p.z),this.xOffset=(p.x*this.zScale-_.x)*Fr,this.yOffset=(p.y*this.zScale-_.y)*Fr)}pointTransform(p){return On(p[0]*this.zScale+this.xOffset,p[1]*this.zScale+this.yOffset)}pointTransformInPlace(p){p[0]=p[0]*this.zScale+this.xOffset,p[1]=p[1]*this.zScale+this.yOffset}constantElevation(p,_){if(p.constantHeight!=null)return this.computeBiasedHeight(p.constantHeight,_)}pointElevation(p,_,A){const M=this.constantElevation(_,A);return M??(p.x=p.x*this.zScale+this.xOffset,p.y=p.y*this.zScale+this.yOffset,this.computeBiasedHeight(_.pointElevation(p),A))}computeBiasedHeight(p,_){return _<=0?p:p+_*xc(0,_,p>=0?p:Math.abs(.5*p))}}function Ims(N){if(N===0)return[0,0,0];const p=lg(N);return[p(),p(),p()]}function wut(N,p){let _=0,A=N.length-1;for(;_<=A;){const M=_+A>>1;N[M].feature.idH.id===M);if(z&&A)return{tileId:A,feature:z}}if(!_||_.length===0)return;const F=wut(_,M);if(!(F<0)){if(A){for(let z=F;z<_.length&&_[z].feature.id===M;z++)if(_[z].tileId.key===A.key)return _[z]}return _[F]}}function Lms(N,p){return N>p?1:N0))return _;_=_.left}}return null}contains(p){for(var _=this._root,A=this._compare;_;){var M=A(p,_.key);if(M===0)return!0;_=M<0?_.left:_.right}return!1}remove(p){var _=this.find(p);if(!_)return!1;if(this.splay(_),_.left)if(_.right){var A=this.minNode(_.right);A.parent!==_&&(this.replace(A,A.right),A.right=_.right,A.right.parent=A),this.replace(_,A),A.left=_.left,A.left.parent=A}else this.replace(_,_.left);else this.replace(_,_.right);return this._size--,!0}removeNode(p){if(!p)return!1;if(this.splay(p),p.left)if(p.right){var _=this.minNode(p.right);_.parent!==p&&(this.replace(_,_.right),_.right=p.right,_.right.parent=_),this.replace(p,_),_.left=p.left,_.left.parent=_}else this.replace(p,p.left);else this.replace(p,p.right);return this._size--,!0}erase(p){var _=this.find(p);if(_){this.splay(_);var A=_.left,M=_.right,F=null;A&&(A.parent=null,F=this.maxNode(A),this.splay(F),this._root=F),M&&(A?F.right=M:this._root=M,M.parent=F),this._size--}}pop(){var p=this._root,_=null;if(p){for(;p.left;)p=p.left;_={key:p.key,data:p.data},this.remove(p.key)}return _}next(p){var _=p;if(_)if(_.right)for(_=_.right;_&&_.left;)_=_.left;else for(_=p.parent;_&&_.right===p;)p=_,_=_.parent;return _}prev(p){var _=p;if(_)if(_.left)for(_=_.left;_&&_.right;)_=_.right;else for(_=p.parent;_&&_.left===p;)p=_,_=_.parent;return _}forEach(p){for(var _=this._root,A=[],M=!1,F=0;!M;)_?(A.push(_),_=_.left):A.length>0?(p(_=A.pop(),F++),_=_.right):M=!0;return this}range(p,_,A,M){const F=[],z=this._compare;let H,Z=this._root;for(;F.length!==0||Z;)if(Z)F.push(Z),Z=Z.left;else{if(Z=F.pop(),H=z(Z.key,_),H>0)break;if(z(Z.key,p)>=0&&A.call(M,Z))return this;Z=Z.right}return this}keys(){for(var p=this._root,_=[],A=[],M=!1;!M;)p?(_.push(p),p=p.left):_.length>0?(p=_.pop(),A.push(p.key),p=p.right):M=!0;return A}values(){for(var p=this._root,_=[],A=[],M=!1;!M;)p?(_.push(p),p=p.left):_.length>0?(p=_.pop(),A.push(p.data),p=p.right):M=!0;return A}at(p){for(var _=this._root,A=[],M=!1,F=0;!M;)if(_)A.push(_),_=_.left;else if(A.length>0){if(_=A.pop(),F===p)return _;F++,_=_.right}else M=!0;return null}load(p=[],_=[],A=!1){if(this._size!==0)throw new Error("bulk-load: tree is not empty");const M=p.length;return A&&FOe(p,_,0,M-1,this._compare),this._root=DOe(null,p,_,0,M),this._size=M,this}min(){var p=this.minNode(this._root);return p?p.key:null}max(){var p=this.maxNode(this._root);return p?p.key:null}isEmpty(){return this._root===null}get size(){return this._size}static createTree(p,_,A,M,F){return new ROe(A,F).load(p,_,M)}}function DOe(N,p,_,A,M){const F=M-A;if(F>0){const z=A+Math.floor(F/2),H={key:p[z],data:_[z],parent:N};return H.left=DOe(H,p,_,A,z),H.right=DOe(H,p,_,z+1,M),H}return null}function FOe(N,p,_,A,M){if(_>=A)return;const F=N[_+A>>1];let z=_-1,H=A+1;for(;;){do z++;while(M(N[z],F)<0);do H--;while(M(N[H],F)>0);if(z>=H)break;let Z=N[z];N[z]=N[H],N[H]=Z,Z=p[z],p[z]=p[H],p[H]=Z}FOe(N,p,_,H,M),FOe(N,p,H+1,A,M)}const jut=11102230246251565e-32,Hb=134217729,Rms=(3+8*jut)*jut;function OOe(N,p,_,A,M){let F,z,H,Z,se=p[0],fe=A[0],xe=0,be=0;fe>se==fe>-se?(F=se,se=p[++xe]):(F=fe,fe=A[++be]);let Te=0;if(xese==fe>-se?(z=se+F,H=F-(z-se),se=p[++xe]):(z=fe+F,H=F-(z-fe),fe=A[++be]),F=z,H!==0&&(M[Te++]=H);xese==fe>-se?(z=F+se,Z=z-F,H=F-(z-Z)+(se-Z),se=p[++xe]):(z=F+fe,Z=z-F,H=F-(z-Z)+(fe-Z),fe=A[++be]),F=z,H!==0&&(M[Te++]=H);for(;xe0:(A[0]-p[0])*(_[1]-p[1])-(_[0]-p[0])*(A[1]-p[1])>0}isAbove(p){return!this.isBelow(p)}isVertical(){return this.point[0]===this.otherEvent.point[0]}get inResult(){return this.resultTransition!==0}clone(){const p=new e$(this.point,this.left,this.otherEvent,this.isSubject,this.type);return p.contourId=this.contourId,p.resultTransition=this.resultTransition,p.prevInResult=this.prevInResult,p.isExteriorRing=this.isExteriorRing,p.inOut=this.inOut,p.otherInOut=this.otherInOut,p}}function KC(N,p){return N[0]===p[0]&&N[1]===p[1]}function zOe(N,p,_){const A=function(M,F,z,H,Z,se){const fe=(F-se)*(z-Z),xe=(M-Z)*(H-se),be=fe-xe;if(fe===0||xe===0||fe>0!=xe>0)return be;const Te=Math.abs(fe+xe);return Math.abs(be)>=33306690738754716e-32*Te?be:-function(De,Ue,Ye,st,ot,mt,lt){let yt,Nt,as,Et,$t,Jt,ns,Ls,Gs,pn,cn,jn,Hn,Cs,Qs,an,Ln,In;const Vn=De-ot,Dn=Ye-ot,ir=Ue-mt,Bn=st-mt;Cs=Vn*Bn,Jt=Hb*Vn,ns=Jt-(Jt-Vn),Ls=Vn-ns,Jt=Hb*Bn,Gs=Jt-(Jt-Bn),pn=Bn-Gs,Qs=Ls*pn-(Cs-ns*Gs-Ls*Gs-ns*pn),an=ir*Dn,Jt=Hb*ir,ns=Jt-(Jt-ir),Ls=ir-ns,Jt=Hb*Dn,Gs=Jt-(Jt-Dn),pn=Dn-Gs,Ln=Ls*pn-(an-ns*Gs-Ls*Gs-ns*pn),cn=Qs-Ln,$t=Qs-cn,J9[0]=Qs-(cn+$t)+($t-Ln),jn=Cs+cn,$t=jn-Cs,Hn=Cs-(jn-$t)+(cn-$t),cn=Hn-an,$t=Hn-cn,J9[1]=Hn-(cn+$t)+($t-an),In=jn+cn,$t=In-jn,J9[2]=jn-(In-$t)+(cn-$t),J9[3]=In;let Rr=function(oi,Fa){let Ai=Fa[0];for(let Ni=1;Ni<4;Ni++)Ai+=Fa[Ni];return Ai}(0,J9),cr=22204460492503146e-32*lt;if(Rr>=cr||-Rr>=cr||($t=De-Vn,yt=De-(Vn+$t)+($t-ot),$t=Ye-Dn,as=Ye-(Dn+$t)+($t-ot),$t=Ue-ir,Nt=Ue-(ir+$t)+($t-mt),$t=st-Bn,Et=st-(Bn+$t)+($t-mt),yt===0&&Nt===0&&as===0&&Et===0)||(cr=11093356479670487e-47*lt+Rms*Math.abs(Rr),Rr+=Vn*Et+Bn*yt-(ir*as+Dn*Nt),Rr>=cr||-Rr>=cr))return Rr;Cs=yt*Bn,Jt=Hb*yt,ns=Jt-(Jt-yt),Ls=yt-ns,Jt=Hb*Bn,Gs=Jt-(Jt-Bn),pn=Bn-Gs,Qs=Ls*pn-(Cs-ns*Gs-Ls*Gs-ns*pn),an=Nt*Dn,Jt=Hb*Nt,ns=Jt-(Jt-Nt),Ls=Nt-ns,Jt=Hb*Dn,Gs=Jt-(Jt-Dn),pn=Dn-Gs,Ln=Ls*pn-(an-ns*Gs-Ls*Gs-ns*pn),cn=Qs-Ln,$t=Qs-cn,Z1[0]=Qs-(cn+$t)+($t-Ln),jn=Cs+cn,$t=jn-Cs,Hn=Cs-(jn-$t)+(cn-$t),cn=Hn-an,$t=Hn-cn,Z1[1]=Hn-(cn+$t)+($t-an),In=jn+cn,$t=In-jn,Z1[2]=jn-(In-$t)+(cn-$t),Z1[3]=In;const jr=OOe(4,J9,4,Z1,Nut);Cs=Vn*Et,Jt=Hb*Vn,ns=Jt-(Jt-Vn),Ls=Vn-ns,Jt=Hb*Et,Gs=Jt-(Jt-Et),pn=Et-Gs,Qs=Ls*pn-(Cs-ns*Gs-Ls*Gs-ns*pn),an=ir*as,Jt=Hb*ir,ns=Jt-(Jt-ir),Ls=ir-ns,Jt=Hb*as,Gs=Jt-(Jt-as),pn=as-Gs,Ln=Ls*pn-(an-ns*Gs-Ls*Gs-ns*pn),cn=Qs-Ln,$t=Qs-cn,Z1[0]=Qs-(cn+$t)+($t-Ln),jn=Cs+cn,$t=jn-Cs,Hn=Cs-(jn-$t)+(cn-$t),cn=Hn-an,$t=Hn-cn,Z1[1]=Hn-(cn+$t)+($t-an),In=jn+cn,$t=In-jn,Z1[2]=jn-(In-$t)+(cn-$t),Z1[3]=In;const Wa=OOe(jr,Nut,4,Z1,kut);Cs=yt*Et,Jt=Hb*yt,ns=Jt-(Jt-yt),Ls=yt-ns,Jt=Hb*Et,Gs=Jt-(Jt-Et),pn=Et-Gs,Qs=Ls*pn-(Cs-ns*Gs-Ls*Gs-ns*pn),an=Nt*as,Jt=Hb*Nt,ns=Jt-(Jt-Nt),Ls=Nt-ns,Jt=Hb*as,Gs=Jt-(Jt-as),pn=as-Gs,Ln=Ls*pn-(an-ns*Gs-Ls*Gs-ns*pn),cn=Qs-Ln,$t=Qs-cn,Z1[0]=Qs-(cn+$t)+($t-Ln),jn=Cs+cn,$t=jn-Cs,Hn=Cs-(jn-$t)+(cn-$t),cn=Hn-an,$t=Hn-cn,Z1[1]=Hn-(cn+$t)+($t-an),In=jn+cn,$t=In-jn,Z1[2]=jn-(In-$t)+(cn-$t),Z1[3]=In;const Ka=OOe(Wa,kut,4,Z1,Sut);return Sut[Ka-1]}(M,F,z,H,Z,se,Te)}(N[0],N[1],p[0],p[1],_[0],_[1]);return A>0?-1:A<0?1:0}function uM(N,p){const _=N.point,A=p.point;return _[0]>A[0]?1:_[0]A[1]?1:-1:function(M,F,z){return M.left!==F.left?M.left?1:-1:zOe(z,M.otherEvent.point,F.otherEvent.point)!==0?M.isBelow(F.otherEvent.point)?-1:1:!M.isSubject&&F.isSubject?1:-1}(N,p,_)}function hM(N,p,_){const A=new e$(p,!1,N,N.isSubject),M=new e$(p,!0,N.otherEvent,N.isSubject);return KC(N.point,N.otherEvent.point)&&console.warn("what is that, a collapsed segment?",N),A.contourId=M.contourId=N.contourId,uM(M,N.otherEvent)>0&&(N.otherEvent.left=!0,M.left=!1),N.otherEvent.otherEvent=M,N.otherEvent=A,_.push(M),_.push(A),_}function ole(N,p){return N[0]*p[1]-N[1]*p[0]}function BOe(N,p){return N[0]*p[0]+N[1]*p[1]}function $Oe(N,p,_){const A=function(Z,se,fe,xe){const be=[se[0]-Z[0],se[1]-Z[1]],Te=[xe[0]-fe[0],xe[1]-fe[1]];function De(as,Et,$t){return[as[0]+Et*$t[0],as[1]+Et*$t[1]]}const Ue=[fe[0]-Z[0],fe[1]-Z[1]];let Ye=ole(be,Te),st=Ye*Ye;const ot=BOe(be,be);if(st>0){const as=ole(Ue,Te)/Ye;if(as<0||as>1)return null;const Et=ole(Ue,be)/Ye;return Et<0||Et>1?null:as===0||as===1?[De(Z,as,be)]:Et===0||Et===1?[De(fe,Et,Te)]:[De(Z,as,be)]}if(Ye=ole(Ue,be),st=Ye*Ye,st>0)return null;const mt=BOe(be,Ue)/ot,lt=mt+BOe(be,Te)/ot,yt=Math.min(mt,lt),Nt=Math.max(mt,lt);return yt<=1&&Nt>=0?yt===1?[De(Z,yt>0?yt:0,be)]:Nt===0?[De(Z,Nt<1?Nt:1,be)]:[De(Z,yt>0?yt:0,be),De(Z,Nt<1?Nt:1,be)]:null}(N.point,N.otherEvent.point,p.point,p.otherEvent.point),M=A?A.length:0;if(M===0||M===1&&(KC(N.point,p.point)||KC(N.otherEvent.point,p.otherEvent.point))||M===2&&N.isSubject===p.isSubject)return 0;if(M===1)return!KC(N.point,A[0])&&!KC(N.otherEvent.point,A[0])&&hM(N,A[0],_),!KC(p.point,A[0])&&!KC(p.otherEvent.point,A[0])&&hM(p,A[0],_),1;const F=[];let z=!1,H=!1;return KC(N.point,p.point)?z=!0:uM(N,p)===1?F.push(p,N):F.push(N,p),KC(N.otherEvent.point,p.otherEvent.point)?H=!0:uM(N.otherEvent,p.otherEvent)===1?F.push(p.otherEvent,N.otherEvent):F.push(N.otherEvent,p.otherEvent),z&&H||z?(p.type=1,N.type=p.inOut===N.inOut?2:3,z&&!H&&hM(F[1].otherEvent,F[0].point,_),2):H?(hM(F[0],F[1].point,_),3):F[0]!==F[3].otherEvent?(hM(F[0],F[1].point,_),hM(F[1],F[2].point,_),3):(hM(F[0],F[1].point,_),hM(F[3].otherEvent,F[2].point,_),3)}function Dms(N,p){if(N===p)return 0;if(zOe(N.point,N.otherEvent.point,p.point)!==0||zOe(N.point,N.otherEvent.point,p.otherEvent.point)!==0)return KC(N.point,p.point)?N.isBelow(p.otherEvent.point)?-1:1:N.point[0]===p.point[0]?N.point[1](p.contourId??0)?1:-1}return uM(N,p)===1?1:-1}class Fms{constructor(){this.points=[],this.holeIds=[],this.holeOf=null,this.depth=null}isExterior(){return this.holeOf==null}}function Oms(N,p,_,A){let M,F=N+1,z=p[N].point;const H=p.length;for(FA;)F--;return F}function zms(N,p,_){const A=new Fms;if(N.prevInResult!=null){const M=N.prevInResult,F=M.outputContourId;if(M.resultTransition>0){const z=p[F];if(z.holeOf!=null){const H=z.holeOf;p[H].holeIds.push(_),A.holeOf=H,A.depth=p[F].depth}else p[F].holeIds.push(_),A.holeOf=F,A.depth=p[F].depth+1}else A.holeOf=null,A.depth=p[F].depth}else A.holeOf=null,A.depth=0;return A}const Aut=Math.max,Eut=Math.min;let lle=0;function Tut(N,p,_,A,M,F){let z,H,Z,se,fe,xe;for(z=0,H=N.length-1;z0?xe.left=!0:fe.left=!0;const be=Z[0],Te=Z[1];M[0]=Eut(M[0],be),M[1]=Eut(M[1],Te),M[2]=Aut(M[2],be),M[3]=Aut(M[3],Te),A.push(fe),A.push(xe)}}const cle=[];function Mut(N,p,_){let A=N,M=p;typeof N[0][0][0]=="number"&&(A=[N]),typeof p[0][0][0]=="number"&&(M=[p]);let F=function(be,Te,De){let Ue=null;return be.length*Te.length===0&&(De===0?Ue=cle:De===2?Ue=be:(De===1||De===3)&&(Ue=be.length===0?Te:be)),Ue}(A,M,_);if(F)return F===cle?null:F;const z=[1/0,1/0,-1/0,-1/0],H=[1/0,1/0,-1/0,-1/0],Z=function(be,Te,De,Ue,Ye){const st=new nj(void 0,uM);let ot,mt,lt,yt,Nt,as;for(lt=0,yt=be.length;ltUe[2]||Ue[0]>De[2]||De[1]>Ue[3]||Ue[1]>De[3])&&(Ye===0?st=cle:Ye===2?st=be:(Ye===1||Ye===3)&&(st=be.concat(Te))),st}(A,M,z,H,_),F)return F===cle?null:F;const se=function(be,Te,De,Ue,Ye,st){const ot=new ROe(Dms),mt=[],lt=Math.min(Ue[2],Ye[2]);let yt,Nt,as;for(;be.length!==0;){let Et=be.pop();if(mt.push(Et),st===0&&Et.point[0]>lt||st===2&&Et.point[0]>Ue[2])break;if(Et.left){Nt=yt=ot.insert(Et),as=ot.minNode(),yt=yt!==as?ot.prev(yt):null,Nt=ot.next(Nt);const $t=yt?yt.key:null;let Jt;if(WY(Et,$t,st),Nt&&$Oe(Et,Nt.key,be)===2&&(WY(Et,$t,st),WY(Nt.key,Et,st)),yt&&$Oe(yt.key,Et,be)===2){let ns=yt;ns=ns!==as?ot.prev(ns):null,Jt=ns?ns.key:null,WY($t,Jt,st),WY(Et,$t,st)}}else Et=Et.otherEvent,Nt=yt=ot.find(Et),yt&&Nt&&(yt=yt!==as?ot.prev(yt):null,Nt=ot.next(Nt),ot.remove(Et),Nt&&yt&&$Oe(yt.key,Nt.key,be))}return mt}(Z,0,0,z,H,_),fe=function(be){let Te,De;const Ue=function(ot){let mt,lt,yt,Nt,as;const Et=[];for(lt=0,yt=ot.length;lt{Ye[as]=!0,as=Ue.length)&&Ue[yt];);st.push(mt)}return st}(se),xe=[];for(let be=0;be0&&(M=Mut(M,F,2)),Iut(M,1/65536,.001)}function UOe(N,p=1){return[N.map(_=>_.map(A=>[A.x*p,A.y*p]))]}function Put(N,p){const _=Math.floor(N)+.5;return Math.abs(N-_)<=p?Math.round(_):Math.round(N)}class Ums{constructor(p){this.xs=[],this.ys=[],this.ixs=[],this.iys=[],this.buckets=new Map,this.tolerance=p}canonicalize(p,_){const A=this.tolerance,M=Math.floor(p/A),F=Math.floor(_/A);for(let Z=-1;Z<=1;Z++){const se=this.buckets.get(M+Z);if(se)for(let fe=-1;fe<=1;fe++){const xe=se.get(F+fe);if(xe){for(const be of xe)if(Math.abs(this.xs[be]-p)<=A&&Math.abs(this.ys[be]-_)<=A){const Te=this.ixs[be],De=this.iys[be];return this.xs[be]===p&&this.ys[be]===_||this.store(p,_,Te,De,M,F),[Te,De]}}}}const z=Put(p,A),H=Put(_,A);return this.store(p,_,z,H,M,F),[z,H]}store(p,_,A,M,F,z){const H=this.xs.length;this.xs.push(p),this.ys.push(_),this.ixs.push(A),this.iys.push(M);let Z=this.buckets.get(F);Z||(Z=new Map,this.buckets.set(F,Z));let se=Z.get(z);se||(se=[],Z.set(z,se)),se.push(H)}}function Iut(N,p=1,_){const A=_!=null?new Ums(_):null;return N.map(M=>M.map((F,z)=>{const H=F.map(Z=>{const se=Z[0]*p,fe=Z[1]*p;if(A){const[xe,be]=A.canonicalize(se,fe);return new xs(xe,be)}return new xs(Math.round(se),Math.round(fe))});return z>0&&H.reverse(),H}))}class qOe{constructor(){this.frcCoverage=new Set,this.featureTriSegments=[],this.frcPerLevel=new Map,this.frcNonRoadSegments=new Ri}empty(){return this.frcCoverage.size===0}}function Lut(N,p,_){if(N.frcCoverage.size===0||N.featureTriSegments.length===0)return;const A=_.get(),M=p.uint16,F=[];N.featureTriSegments.sort((xe,be)=>xe.segIdx!==be.segIdx?xe.segIdx-be.segIdx:xe.frc===null&&be.frc===null?0:xe.frc===null?-1:be.frc===null?1:be.frc-xe.frc);const z=new Map;let H=0,Z=N.featureTriSegments[0].frc,se={vertexOffset:A[H].vertexOffset,primitiveOffset:0,vertexLength:A[H].vertexLength,primitiveLength:0,vaos:{},sortKey:void 0};const fe=()=>{se.primitiveLength>0&&(z.has(Z)||z.set(Z,[]),z.get(Z).push({...se}))};for(const xe of N.featureTriSegments){xe.segIdx!==H&&(fe(),H=xe.segIdx,Z=xe.frc,se={vertexOffset:A[H].vertexOffset,primitiveOffset:F.length/3,vertexLength:A[H].vertexLength,primitiveLength:0,vaos:{},sortKey:void 0}),xe.frc!==Z&&(fe(),Z=xe.frc,se={...se,primitiveOffset:F.length/3,primitiveLength:0});for(let be=xe.start;be0?F.length-1:0,frc:M})}buildFrcSegments(p){this.frcData&&!this.frcData.empty()&&Lut(this.frcData,p.bufferData.indexArray,p.bufferData.triangleSegments)}handleFeature(p,_,A,M,F,z){const H=new Array;if(!this.elevationMode)return!1;const Z=HY(p,F,void 0,M);if(!Z)return!1;{const fe=this.clipPolygonsToTile(_,1);fe.length>0&&H.push({polygons:fe,elevationFeature:Z.feature,elevationTileID:Z.tileId})}const se={guardRailEnabled:z.layers[0].layout.get("fill-construct-bridge-guard-rail").evaluate(p,{},M),featureIndex:A};for(const fe of H)if(fe.elevationFeature){if(this.elevationMode==="hd-road-base"){this.elevatedStructures||(this.elevatedStructures=new Y1(fe.elevationTileID,z.layers,z.zoom,z.lut));const be=fe.elevationFeature.isTunnel();let Te=0;Object.hasOwn(p.properties,bdt)&&(Te=+p.properties[bdt]),this.elevatedStructures.addPortalCandidates(fe.elevationFeature.id,fe.polygons,be,fe.elevationFeature,Te)}fe.elevationFeature.constantHeight==null&&(fe.polygons=this.prepareElevatedPolygons(fe.polygons,fe.elevationFeature,fe.elevationTileID));const xe=new Q9(M,fe.elevationTileID);this.addElevatedGeometry(z,fe.polygons,xe,fe.elevationFeature,this.elevationMode==="hd-road-base"?0:.05,A,se)}return!0}populatePaintArrays(p,_,A,M,F,z,H){this.elevationBufferData&&this.elevationBufferData.populatePaintArrays(p,_,A,M,F,z,H)}update(p,_,A,M,F,z,H,Z){this.elevationBufferData&&this.elevationBufferData.update(p,_,A,M,F,z,H,Z),this.elevatedStructures&&this.elevatedStructures.update(p,_,A,M,F,z,H,Z)}updateExpressions(p){this.elevationBufferData&&this.elevationBufferData.programConfigurations.updateExpressions(p),this.elevatedStructures&&(this.elevatedStructures.bridgeProgramConfigurations.updateExpressions(p),this.elevatedStructures.tunnelProgramConfigurations.updateExpressions(p))}upload(p){this.elevationBufferData&&this.elevationBufferData.upload(p),this.elevatedStructures&&this.elevatedStructures.upload(p)}destroy(){this.elevationBufferData&&this.elevationBufferData.destroy(),this.elevatedStructures&&this.elevatedStructures.destroy()}getUnevaluatedPortalGraph(){return this.elevatedStructures?this.elevatedStructures.unevaluatedPortals:void 0}setEvaluatedPortalGraph(p,_,A,M,F,z){this.elevatedStructures&&(this.elevatedStructures.construct(p),this.elevatedStructures.populatePaintArrays(_,A,M,F,z))}addElevatedGeometry(p,_,A,M,F,z,H){const Z={elevation:M,elevationSampler:A,bias:F,index:z,featureInfo:H},[se,fe]=p.addGeometry(_,this.elevationBufferData,Z,this.elevatedStructures);this.elevationBufferData.heightRange==null?this.elevationBufferData.heightRange={min:se,max:fe}:(this.elevationBufferData.heightRange.min=Math.min(this.elevationBufferData.heightRange.min,se),this.elevationBufferData.heightRange.max=Math.max(this.elevationBufferData.heightRange.max,fe))}prepareElevatedPolygons(p,_,A){const M=1/K(A),F=[];for(const z of p){const H=$ms(z,new _ut(_,M),.1);F.push(...H)}return F}clipPolygonsToTile(p,_){const A=-_,M=-_,F=Fr+_,z=Fr+_;let H=0;const Z=[],se=[];for(;H=A&&Te.max.x<=F&&Te.min.y>=M&&Te.max.y<=z?Z:se).push(be)}if(Z.length===p.length)return p;const fe=[new xs(A,M),new xs(F,M),new xs(F,z),new xs(A,z),new xs(A,M)],xe=Z;for(const be of se)xe.push(...Bms(be,fe));return xe}}function Vms(N,p){return N.nextPoint.sub(p.at(-2)).unit()}function Hms(N,p){return p[1].sub(N.prevPoint).unit()}oa(Rut,"FillHDExtension"),oa(Y1,"ElevatedStructures");class Dut{constructor(p,_){this.elevationEnabled=p,this.hasDeferredElevationFeatures=!1,_&&(this.frcData=new qOe)}isEmpty(){const p=!this.elevationEnabled||this.heightRange===void 0,_=!this.frcData||this.frcData.empty();return p&&_}trackFeatureFrc(p){if(!this.frcData)return null;const _=dle(p||{});return _!==null&&this.frcData.frcCoverage.add(_),_}recordFeatureRange(p,_,A,M){if(!this.frcData||A<=_)return;const F=p.segments.get();this.frcData.featureTriSegments.push({start:3*_,end:3*A,segIdx:F.length>0?F.length-1:0,frc:M})}buildFrcSegments(p){this.frcData&&!this.frcData.empty()&&Lut(this.frcData,p.indexArray,p.segments)}handleFeature(p,_,A,M,F,z,H,Z,se,fe,xe){if(!this.elevationEnabled)return!1;if(!xe.terrainEnabled){const Ye=HY(p,M,F?F.registry:void 0,A),st=p.properties!=null&&Object.hasOwn(p.properties,B3)&&!Number.isNaN(+p.properties[B3]);if(!Ye&&st&&z&&(!F||!F.allProvidersReady))return this.hasDeferredElevationFeatures=!0,!0;if(Ye){let ot=Ye.feature,mt=Ye.tileId;if(!Ye.tileId.equals(A)){const Nt=this.mergedFeatureCache?this.mergedFeatureCache.get(ot.id):void 0;if(Nt)ot=Nt,mt=A;else{const as=function(Et,$t,Jt){if(!Et.properties||!$t||$t.length===0)return[];const ns=+Et.properties[B3];if(Number.isNaN(ns))return[];const Ls=wut($t,ns);if(Ls<0)return[];const Gs=[];for(let pn=Ls;pn<$t.length&&$t[pn].feature.id===ns;pn++){const cn=$t[pn];(cn.tileId.isChildOf(Jt)||Jt.isChildOf(cn.tileId)||cn.feature.constantHeight!=null)&&Gs.push(cn)}return Gs}(p,F?F.registry:void 0,A);as.length>1&&(ot=function(Et,$t){const Jt=$t.slice().sort((Cs,Qs)=>Qs.tileId.z-Cs.tileId.z),ns=new xs(Number.POSITIVE_INFINITY,Number.POSITIVE_INFINITY),Ls=new xs(Number.NEGATIVE_INFINITY,Number.NEGATIVE_INFINITY),Gs=[];for(const Cs of Jt){const Qs=new Q9(Cs.tileId,Et);for(const Ln of Cs.feature.vertices)Gs.push({position:Qs.pointTransform(Ln.position),height:Ln.height,extent:Ln.extent,index:Ln.index});const an=Cs.feature.safeArea;aR[0]=an.min.x,aR[1]=an.min.y,iR[0]=an.max.x,iR[1]=an.max.y,Qs.pointTransformInPlace(aR),Qs.pointTransformInPlace(iR),ns.x=Math.min(ns.x,aR[0],iR[0]),ns.y=Math.min(ns.y,aR[1],iR[1]),Ls.x=Math.max(Ls.x,aR[0],iR[0]),Ls.y=Math.max(Ls.y,aR[1],iR[1])}const pn={min:ns,max:Ls};if(Jt[0].feature.constantHeight!=null)return new K3(Jt[0].feature.id,pn,Jt[0].feature.constantHeight);Gs.sort((Cs,Qs)=>Cs.index-Qs.index);const cn=[];for(const Cs of Gs)cn.length!==0&&cn.at(-1).index===Cs.index||cn.push(Cs);const jn=[];for(let Cs=1;Cs>1,xe.layoutVertexArray.int16[6*Jt+1]>>1),Ls=Et.pointElevation(ns,ot,.05);this.updateHeightRange(Ls),Jt0?ot.parentIndex:null)}return xe.fillNonElevatedRoadSegment(Te),!0}prepareElevatedLines(p,_,A,M){if(_.constantHeight!=null)return p;const F=[],z=1/K(M),H=A.equals(M)?null:new Q9(A,M);for(const Z of p)bhs(Z,new _ut(_,z,H),0,F);return F}updateHeightRange(p){this.heightRange?(this.heightRange.min=Math.min(this.heightRange.min,p),this.heightRange.max=Math.max(this.heightRange.max,p)):this.heightRange={min:p,max:p}}endPopulate(){this.mergedFeatureCache=void 0}}oa(Dut,"LineHDExtension");class Fut{constructor(){this.elevatedLayoutVertexArray=new $s,this.hasElevation=!1}beginFeature(p,_,A){const M=HY(p,_,void 0,A);this.currentFeatureElevation=M?M.feature:void 0}writeVertexQuad(p,_){const A=this.currentFeatureElevation?this.currentFeatureElevation.pointElevation(new xs(p,_)):0;this.hasElevation=this.hasElevation||A!==0;for(let M=0;M<4;M++)this.elevatedLayoutVertexArray.emplaceBack(A)}finalize(){this.hasElevation||(this.elevatedLayoutVertexArray=void 0)}upload(p){this.elevatedLayoutVertexArray&&!this.elevatedLayoutVertexBuffer&&(this.elevatedLayoutVertexBuffer=p.createVertexBuffer(this.elevatedLayoutVertexArray,khs.members))}destroy(){this.elevatedLayoutVertexBuffer&&this.elevatedLayoutVertexBuffer.destroy()}}oa(Fut,"CircleHDExtension");const ule=(N,p,_,A)=>{for(let M=0;M=this.elevationFeatures.length)return!1;const A=this.elevationFeatureTileIds[p];return A!=null&&!A.equals(_)}getRoadFeatureHeightAtAnchor(p,_,A){if(p===65535||p>=this.elevationFeatures.length)return null;const M=this.elevationFeatures[p],F=this.elevationFeatureTileIds[p];return F.equals(A)?M.pointElevation(_):this.getElevationFeatureSampler(A,F).pointElevation(new xs(_.x,_.y),M,0)}sampleRoadFeatureHeight(p,_,A){const M=this.getRoadFeatureHeightAtAnchor(p,_,A);return M===null?void 0:M}clearWorkerState(){this.consumerCanonical=void 0,this.elevationParams=null,this.crossSourceElevationEnabled=!1,this.terrainEnabled=!1,this.elevationFeatureIdToIndex.clear()}updateRoadElevation(p,_){if(this.elevationStateComplete)return;this.elevationStateComplete=!0,p.hasAnyZOffset=!1;let A=!1;const M=K(_),F=1/M;let z=!1,H=!1;for(let Z=0;Z0||Te>0,st=De>0,ot=se.elevationFeatureIndex,mt=ot=0&&ule(p.icon.orientationVertexArray,De,fe,xe),yt>=0&&ule(p.icon.orientationVertexArray,Ue,fe,xe)}}z||(p.text.orientationVertexArray=void 0),H||(p.icon.orientationVertexArray=void 0),A&&(p.zOffsetBuffersNeedUpload=!0,p.zOffsetSortDirty=!0)}getRoadFeatureHeightForPlacedSymbol(p,_,A,M,F){const z=p.symbolInstances.get(_.symbolInstanceIndices[A]);return this.getRoadFeatureHeightAtAnchor(z.elevationFeatureIndex,M,F)}getElevationFeatureForPlacedSymbol(p,_,A){const M=p.symbolInstances.get(_.symbolInstanceIndices[A]).elevationFeatureIndex;if(M{const De=this.getRoadFeatureHeightForPlacedSymbol(p,_,A,Te,M.canonical);return function(Ue,Ye,st,ot,mt,lt){const yt=ot.upVector(Ye,st.x,st.y);return Fe(yt,yt,Ue*ot.upVectorScale(Ye,mt,lt).metersToTile),[yt[0],yt[1],yt[2]]}(De!==null?De:0,M.canonical,Te,H,Z,se)},elevation:z,elevationFeature:null}:{getElevation:F,elevation:z,elevationFeature:xe}}}oa(Out,"SymbolHDExtension",{omit:["consumerCanonical","elevationParams","crossSourceElevationEnabled","terrainEnabled","hasDeferredElevationFeatures","elevationFeatureIdToIndex"]});let Zk=null,hle=null,HOe=null,mle=null;const zut=5120,But=5121,$ut=5122,Uut=5123,qut=5125,Vut=5126,t$={[zut]:Int8Array,[But]:Uint8Array,[$ut]:Int16Array,[Uut]:Uint16Array,[qut]:Uint32Array,[Vut]:Float32Array},Gms={[zut]:"DT_INT8",[But]:"DT_UINT8",[$ut]:"DT_INT16",[Uut]:"DT_UINT16",[qut]:"DT_UINT32",[Vut]:"DT_FLOAT32"},s$={SCALAR:1,VEC2:2,VEC3:3,VEC4:4,MAT2:4,MAT3:9,MAT4:16};function Hut(N,p,_){const A=_.json.bufferViews.length,M=_.buffers.length;p.bufferView=A,_.json.bufferViews[A]={buffer:M,byteLength:N.byteLength},_.buffers[M]=N}const GOe="KHR_draco_mesh_compression";function Wms(N,p){const _=N.extensions&&N.extensions[GOe];if(!_)return;const A=new Zk.Decoder,M=Yut(p,_.bufferView),F=new Zk.Mesh;if(!A.DecodeArrayToMesh(M,M.byteLength,F))throw new Error("Failed to decode Draco mesh");const z=p.json.accessors[N.indices],H=t$[z.componentType],Z=z.count*H.BYTES_PER_ELEMENT,se=Zk._malloc(Z);H===Uint16Array?A.GetTrianglesUInt16Array(F,Z,se):A.GetTrianglesUInt32Array(F,Z,se),Hut(Zk.memory.buffer.slice(se,se+Z),z,p),Zk._free(se);for(const fe of Object.keys(_.attributes)){const xe=A.GetAttributeByUniqueId(F,_.attributes[fe]),be=p.json.accessors[N.attributes[fe]],Te=Gms[be.componentType],De=be.count*s$[be.type]*t$[be.componentType].BYTES_PER_ELEMENT,Ue=Zk._malloc(De);A.GetAttributeDataArrayForAllPoints(F,xe,Zk[Te],De,Ue),Hut(Zk.memory.buffer.slice(Ue,Ue+De),be,p),Zk._free(Ue)}A.destroy(),F.destroy(),delete N.extensions[GOe]}const fle="EXT_meshopt_compression";function Kms(N,p){if(!N.extensions||!N.extensions[fle])return;const _=N.extensions[fle],A=new Uint8Array(p.buffers[_.buffer],_.byteOffset||0,_.byteLength||0),M=new Uint8Array(_.count*_.byteStride);HOe.decodeGltfBuffer(M,_.count,_.byteStride,A,_.mode,_.filter),N.buffer=p.buffers.length,N.byteOffset=0,p.buffers[N.buffer]=M.buffer,delete N.extensions[fle]}const Gut=1179937895,Wut=new TextDecoder("utf8");function Kut(N,p){return new URL(N,p).href}async function Yms(N,p,_,A,M){const F=await fetch(Kut(N.uri,A),{signal:M}),z=await F.arrayBuffer();p.buffers[_]=z}function Yut(N,p){const _=N.json.bufferViews[p];return new Uint8Array(N.buffers[_.buffer],_.byteOffset||0,_.byteLength)}async function Zms(N,p,_,A,M){if(N.uri){const F=Kut(N.uri,A),z=await fetch(F,{signal:M}),H=await z.blob(),Z=await createImageBitmap(H);p.images[_]=Z}else if(N.bufferView!==void 0){const F=Yut(p,N.bufferView),z=new Blob([F],{type:N.mimeType}),H=await createImageBitmap(z);p.images[_]=H}}async function Zut(N,p=0,_,A){const M={json:null,images:[],buffers:[]};if(new Uint32Array(N,p,1)[0]===Gut){const Te=new Uint32Array(N,p);let De=2;const Ue=(Te[De++]>>2)-3,Ye=Te[De++]>>2;if(De++,M.json=JSON.parse(Wut.decode(Te.subarray(De,De+Ye))),De+=Ye,De>>0,Math.ceil(1.2*mt)),yt=Math.ceil((lt-mt)/65536);try{return Ue.grow(yt),Ye(),!0}catch{return!1}},b:st}}).then(ot=>{const{Rb:mt,Qb:lt,P:yt,T:Nt,X:as,Ja:Et,La:$t,Qa:Jt,Va:ns,Wa:Ls,eb:Gs,jb:pn,f:cn,e:jn,yb:Hn,zb:Cs,Ab:Qs,Bb:an,Db:Ln,Gb:In}=ot.instance.exports;Ue=jn;const Vn=(()=>{let Dn=0,ir=0,Bn=0,Rr=0;return cr=>{Bn&&(mt(Rr),mt(Dn),ir+=Bn,Bn=Dn=0),Dn||(ir+=128,Dn=lt(ir));const jr=cr.length+7&-8;let Wa=Dn;jr>=ir&&(Bn=jr,Wa=Rr=lt(jr));for(let Ka=0;Ka{Zk=Te,hle=null})),hle}()),be&&fe.push(function(){var Te;if(!HOe)return mle!=null||(mle=(Te=fetch(ut()),WebAssembly.instantiateStreaming(Te,{}).then(De=>{const{sbrk:Ue,memory:Ye,meshopt_decodeVertexBuffer:st,meshopt_decodeIndexBuffer:ot,meshopt_decodeIndexSequence:mt,meshopt_decodeFilterOct:lt,meshopt_decodeFilterQuat:yt,meshopt_decodeFilterExp:Nt}=De.instance.exports,as={ATTRIBUTES:st,TRIANGLES:ot,INDICES:mt},Et={OCTAHEDRAL:lt,QUATERNION:yt,EXPONENTIAL:Nt};return De.instance.exports.__wasm_call_ctors(),{decodeGltfBuffer($t,Jt,ns,Ls,Gs,pn){const cn=Jt+3&-4,jn=Ue(cn*ns),Hn=Ue(Ls.length),Cs=new Uint8Array(Ye.buffer);Cs.set(Ls,Hn);const Qs=as[Gs](jn,Jt,ns,Hn,Ls.length);if(Qs===0&&Et[pn]&&Et[pn](jn,cn,ns),$t.set(Cs.subarray(jn,jn+Jt*ns)),Ue(jn-Ue(0)),Qs!==0)throw new Error(`Malformed buffer data: ${Qs}`)}}})).then(De=>{HOe=De,mle=null})),mle}()),z)for(let Te=0;Texe.cellIdx-be.cellIdx||xe.triIdx-be.triIdx);let fe=0;for(;fethis.max.x||this.min.x>p.x||p.y>this.max.y||this.min.y>p.y)return;const A=YC(p.x-this.min.x,this.xScale,this.cellsX),M=YC(p.y-this.min.y,this.yScale,this.cellsY),F=this.cells[M*this.cellsX+A];if(F){this._lazyInitLookup();for(let z=0;zthis.max.x||this.min.x>_.x||p.y>this.max.y||this.min.y>_.y)return;this._lazyInitLookup();const M=YC(p.x-this.min.x,this.xScale,this.cellsX),F=YC(_.x-this.min.x,this.xScale,this.cellsX),z=YC(p.y-this.min.y,this.yScale,this.cellsY),H=YC(_.y-this.min.y,this.yScale,this.cellsY);for(let Z=z;Z<=H;Z++)for(let se=M;se<=F;se++){const fe=this.cells[Z*this.cellsX+se];if(fe)for(let xe=0;xe0){const F=function(z,H){const Z=H.worldSize,se=eu(1,0)*Z*T(H.center.lat,H.zoom)/pOe(Z),fe=eu(1,H.center.lat)*Z,xe=w([]);D(xe,xe,Xr(H.center.lng)),R(xe,xe,Xr(H.center.lat)),I(xe,xe,[0,0,gf]),P(xe,xe,[se,se,se*fe]);const be=H.point;return I(xe,xe,[-be.x,-be.y,0]),E(xe,xe,z),E(xe,H.globeMatrix,xe)}(N,p);return function(z,H,Z){const se=(De,Ue,Ye)=>{const st=ce(De),ot=ce(Ue),mt=V3(De,Ue,Ye);return Fe(mt,mt,1/ce(mt)*ya(st,ot,Ye))},fe=se([z[0],z[1],z[2]],[H[0],H[1],H[2]],Z),xe=se([z[4],z[5],z[6]],[H[4],H[5],H[6]],Z),be=se([z[8],z[9],z[10]],[H[8],H[9],H[10]],Z),Te=V3([z[12],z[13],z[14]],[H[12],H[13],H[14]],Z);return[fe[0],fe[1],fe[2],0,xe[0],xe[1],xe[2],0,be[0],be[1],be[2],0,Te[0],Te[1],Te[2],1]}(M,F,A)}return M}function KOe(N,p,_,A){const M=uu.projectAabbCorners(A,_);let F=Number.MAX_VALUE;for(let H=0;H0||Ye===0&&De[0]*Ue[0]+De[1]*Ue[1]>=0&&De[0]*De[0]+De[1]*De[1]>Ue[0]*Ue[0]+Ue[1]*Ue[1])&&(fe=Te)}xe=fe}while(xe!==se);return Z.length>0&&Z.push(Z[0]),Z}(M);if(YFe(N,z))return F}const oR=64,YOe=["","wall","door","roof","window","lamp","logo"],ifs=[1,1,1];function yle(N,p,_,A,M,F,z,H,Z,se=!1){const fe=_.zoom,xe=_.project(A),be=T(A.lat,fe),Te=1/be;w(N),I(N,N,[xe.x+z[0]*Te,xe.y+z[1]*Te,z[2]]);let De=1,Ue=1;const Ye=_.worldSize;if(se){if(_.projection.name==="mercator"){let lt=0;_.elevation&&(lt=_.elevation.getAtPointOrZero(new Q(xe.x/Ye,xe.y/Ye),0));const yt=Ft([],[xe.x,xe.y,lt,1],_.projMatrix)[3]/_.cameraToCenterDistance;De=yt,Ue=yt*T(_.center.lat,fe)}else if(_.projection.name==="globe"){const lt=xle(N,_),yt=[0,0,0,1];Ft(yt,yt,E([],_.projMatrix,lt));const Nt=yt[3]/_.cameraToCenterDistance,as=H3(fe),Et=_.projection.pixelsPerMeter(A.lat,Ye)*T(A.lat,fe),$t=_.projection.pixelsPerMeter(_.center.lat,Ye)*T(_.center.lat,fe);De=Nt/ya(Et,k(_.center.lat),as),Ue=Nt*be/Et,De*=$t,Ue*=$t}}else De=Te;P(N,N,[De,De,Ue]);const st=[...N],ot=p.orientation,mt=[];if(tht(mt,[ot[0]+(M?M[0]:0),ot[1]+(M?M[1]:0),ot[2]+(M?M[2]:0)],F),E(N,st,mt),H&&_.elevation){let lt=0;const yt=[];if(Z&&_.elevation){lt=function(as,Et,$t,Jt,ns){const Ls=Et.elevation;if(!Ls)return 0;const Gs=uu.projectAabbCorners($t,Jt),pn=eu(1,ns.lat)*Et.worldSize,cn=function(Bn,Rr){const cr=[0,0,1],jr=[{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 Wa of jr){const Ka=Bn[Wa.corners[0]],oi=Bn[Wa.corners[1]],Fa=Bn[Wa.corners[2]],Ai=[oi[0]-Ka[0],oi[1]-Ka[1],Rr*(oi[2]-Ka[2])],Ni=$e(Ai,Ai,[Fa[0]-Ka[0],Fa[1]-Ka[1],Rr*(Fa[2]-Ka[2])]);qe(Ni,Ni),Wa.dotProductWithUp=ze(Ni,cr)}return jr.sort((Wa,Ka)=>Wa.dotProductWithUp-Ka.dotProductWithUp),jr[0].corners}(Gs,pn),jn=Gs[cn[0]],Hn=Gs[cn[1]],Cs=Gs[cn[2]],Qs=Gs[cn[3]],an=Ls.getAtPointOrZero(new Q(jn[0]/Et.worldSize,jn[1]/Et.worldSize),0),Ln=Ls.getAtPointOrZero(new Q(Hn[0]/Et.worldSize,Hn[1]/Et.worldSize),0),In=Ls.getAtPointOrZero(new Q(Cs[0]/Et.worldSize,Cs[1]/Et.worldSize),0),Vn=Ls.getAtPointOrZero(new Q(Qs[0]/Et.worldSize,Qs[1]/Et.worldSize),0),Dn=(an+Vn)/2,ir=(Ln+In)/2;return Dn>ir?Ln=p.gl.NEAREST_MIPMAP_NEAREST}),N.uploaded=!0,N.image=null)}function nht(N,p,_){N.indexBuffer=p.createIndexBuffer(N.indexArray,!1,!0),N.vertexBuffer=p.createVertexBuffer(N.vertexArray,Xms.members,!1,!0),N.normalArray&&(N.normalBuffer=p.createVertexBuffer(N.normalArray,sfs.members,!1,!0)),N.texcoordArray&&(N.texcoordBuffer=p.createVertexBuffer(N.texcoordArray,(N.texcoordArray.bytesPerElement===8?efs:tfs).members,!1,!0)),N.colorArray&&(N.colorBuffer=p.createVertexBuffer(N.colorArray,(N.colorArray.bytesPerElement===12?Qms:Jms).members,!1,!0)),N.featureArray&&(N.featureBuffer=p.createVertexBuffer(N.featureArray,rfs.members,!1,!0)),N.segments=Ri.simpleSegment(0,0,N.vertexArray.length,N.indexArray.length);const A=N.material;A.pbrMetallicRoughness.baseColorTexture&&YY(A.pbrMetallicRoughness.baseColorTexture,p),A.pbrMetallicRoughness.metallicRoughnessTexture&&YY(A.pbrMetallicRoughness.metallicRoughnessTexture,p),A.normalTexture&&YY(A.normalTexture,p),A.occlusionTexture&&YY(A.occlusionTexture,p,_),A.emissionTexture&&YY(A.emissionTexture,p)}function ZOe(N,p,_){if(N.meshes)for(const A of N.meshes)nht(A,p,_);if(N.lodMeshes)for(const A of N.lodMeshes)nht(A,p,_);if(N.children)for(const A of N.children)ZOe(A,p,_)}function rht(N){N.indexArray.destroy(),N.vertexArray.destroy(),N.colorArray&&N.colorArray.destroy(),N.normalArray&&N.normalArray.destroy(),N.texcoordArray&&N.texcoordArray.destroy(),N.featureArray&&N.featureArray.destroy()}function vle(N){if(N.meshes)for(const p of N.meshes)rht(p);if(N.lodMeshes)for(const p of N.lodMeshes)rht(p);if(N.children)for(const p of N.children)vle(p)}function aht(N){var p;N.vertexBuffer&&(N.vertexBuffer.destroy(),N.indexBuffer.destroy(),N.normalBuffer&&N.normalBuffer.destroy(),N.texcoordBuffer&&N.texcoordBuffer.destroy(),N.colorBuffer&&N.colorBuffer.destroy(),N.featureBuffer&&N.featureBuffer.destroy(),N.segments.destroy(),N.material&&((p=N.material).pbrMetallicRoughness.baseColorTexture&&p.pbrMetallicRoughness.baseColorTexture.gfxTexture&&p.pbrMetallicRoughness.baseColorTexture.gfxTexture.destroy(),p.pbrMetallicRoughness.metallicRoughnessTexture&&p.pbrMetallicRoughness.metallicRoughnessTexture.gfxTexture&&p.pbrMetallicRoughness.metallicRoughnessTexture.gfxTexture.destroy(),p.normalTexture&&p.normalTexture.gfxTexture&&p.normalTexture.gfxTexture.destroy(),p.emissionTexture&&p.emissionTexture.gfxTexture&&p.emissionTexture.gfxTexture.destroy(),p.occlusionTexture&&p.occlusionTexture.gfxTexture&&p.occlusionTexture.gfxTexture.destroy()))}function XOe(N){if(N.meshes)for(const p of N.meshes)aht(p);if(N.lodMeshes)for(const p of N.lodMeshes)aht(p);if(N.footprintDebugMesh&&(N.footprintDebugMesh.vertexBuffer.destroy(),N.footprintDebugMesh.indexBuffer.destroy(),N.footprintDebugMesh.segments.destroy()),N.children)for(const p of N.children)XOe(p)}function QOe(N,p,_,A){return N[0]<=A[0]&&p[0]>=_[0]&&N[1]<=A[1]&&p[1]>=_[1]&&N[2]<=A[2]&&p[2]>=_[2]}function ofs(N,p,_,A,M,F,z,H,Z,se,fe){const xe=.5*(se[0]+fe[0]),be=.5*(se[1]+fe[1]),Te=.5*(se[2]+fe[2]),De=.5*(fe[0]-se[0]),Ue=.5*(fe[1]-se[1]),Ye=.5*(fe[2]-se[2]),st=N-xe,ot=p-be,mt=_-Te,lt=A-xe,yt=M-be,Nt=F-Te,as=z-xe,Et=H-be,$t=Z-Te,Jt=lt-st,ns=yt-ot,Ls=Nt-mt,Gs=as-lt,pn=Et-yt,cn=$t-Nt,jn=st-as,Hn=ot-Et,Cs=mt-$t;let Qs,an,Ln,In,Vn,Dn;if(Qs=mt*ns-ot*Ls,an=Nt*ns-yt*Ls,Ln=$t*ns-Et*Ls,In=Math.min(Qs,an,Ln),Vn=Math.max(Qs,an,Ln),Dn=Math.abs(Ls)*Ue+Math.abs(ns)*Ye,In>Dn||Vn<-Dn||(Qs=mt*pn-ot*cn,an=Nt*pn-yt*cn,Ln=$t*pn-Et*cn,In=Math.min(Qs,an,Ln),Vn=Math.max(Qs,an,Ln),Dn=Math.abs(cn)*Ue+Math.abs(pn)*Ye,In>Dn||Vn<-Dn)||(Qs=mt*Hn-ot*Cs,an=Nt*Hn-yt*Cs,Ln=$t*Hn-Et*Cs,In=Math.min(Qs,an,Ln),Vn=Math.max(Qs,an,Ln),Dn=Math.abs(Cs)*Ue+Math.abs(Hn)*Ye,In>Dn||Vn<-Dn)||(Qs=st*Ls-mt*Jt,an=lt*Ls-Nt*Jt,Ln=as*Ls-$t*Jt,In=Math.min(Qs,an,Ln),Vn=Math.max(Qs,an,Ln),Dn=Math.abs(Ls)*De+Math.abs(Jt)*Ye,In>Dn||Vn<-Dn)||(Qs=st*cn-mt*Gs,an=lt*cn-Nt*Gs,Ln=as*cn-$t*Gs,In=Math.min(Qs,an,Ln),Vn=Math.max(Qs,an,Ln),Dn=Math.abs(cn)*De+Math.abs(Gs)*Ye,In>Dn||Vn<-Dn)||(Qs=st*Cs-mt*jn,an=lt*Cs-Nt*jn,Ln=as*Cs-$t*jn,In=Math.min(Qs,an,Ln),Vn=Math.max(Qs,an,Ln),Dn=Math.abs(Cs)*De+Math.abs(jn)*Ye,In>Dn||Vn<-Dn)||(Qs=ot*Jt-st*ns,an=yt*Jt-lt*ns,Ln=Et*Jt-as*ns,In=Math.min(Qs,an,Ln),Vn=Math.max(Qs,an,Ln),Dn=Math.abs(ns)*De+Math.abs(Jt)*Ue,In>Dn||Vn<-Dn)||(Qs=ot*Gs-st*pn,an=yt*Gs-lt*pn,Ln=Et*Gs-as*pn,In=Math.min(Qs,an,Ln),Vn=Math.max(Qs,an,Ln),Dn=Math.abs(pn)*De+Math.abs(Gs)*Ue,In>Dn||Vn<-Dn)||(Qs=ot*jn-st*Hn,an=yt*jn-lt*Hn,Ln=Et*jn-as*Hn,In=Math.min(Qs,an,Ln),Vn=Math.max(Qs,an,Ln),Dn=Math.abs(Hn)*De+Math.abs(jn)*Ue,In>Dn||Vn<-Dn)||(In=Math.min(st,lt,as),Vn=Math.max(st,lt,as),In>De||Vn<-De)||(In=Math.min(ot,yt,Et),Vn=Math.max(ot,yt,Et),In>Ue||Vn<-Ue)||(In=Math.min(mt,Nt,$t),Vn=Math.max(mt,Nt,$t),In>Ye||Vn<-Ye))return!1;const ir=ns*cn-Ls*pn,Bn=Ls*Gs-Jt*cn,Rr=Jt*pn-ns*Gs,cr=-(ir*st+Bn*ot+Rr*mt);return Dn=De*Math.abs(ir)+Ue*Math.abs(Bn)+Ye*Math.abs(Rr),!(Math.abs(cr)>Dn)}const lfs=[];class iht{serializeFromGltf(p,_,A,M){if(p.length<7)return;let F=0;if(p[F++]!==109||p[F++]!==98||p[F++]!==120||p[F++]!==98||p[F++]!==118||p[F++]!==104||p[F++]!==43)return;const z=new DataView(p.buffer,p.byteOffset),H=z.getUint16(F,!0);if(F+=2,H===0)return;this._nodes=[];let Z=0;for(let fe=0;fe0;){const F=A.pop(),z=this._nodes[F];if(z.aabbMax[2]<=M)continue;if(z.backChild===65535){for(let Te=0;Te=0?M:null}}function oht(N){switch(N){case Int8Array:return 1/127;case Uint8Array:return 1/255;case Int16Array:return 1/32767;case Uint16Array:return 1/65535;default:return 1}}function n$(N,p){const _=N.json.bufferViews[p.bufferView],A=t$[p.componentType];return new A(N.buffers[_.buffer],(p.byteOffset||0)+(_.byteOffset||0),p.count*(_.byteStride&&_.byteStride!==s$[p.type]*A.BYTES_PER_ELEMENT?_.byteStride/A.BYTES_PER_ELEMENT:s$[p.type]))}function lht(N,p,_,A){const M=n$(N,p),F=M instanceof Float32Array?M:new Uint32Array(M.buffer,M.byteOffset,p.count),z=new si;z.reserveExact(p.count);let H=-1;for(let Z=0;Z>>16|F[Z]<<16:F[Z],fe=65535&se,xe=se>>>16;H=H<0&&(15&xe)==2?fe:H,z.emplaceBack(fe,xe)}A.featureArray=z,H>=0&&(A.doorVertexColor=H)}function JOe(N,p,_,A,M=!0){const F=t$[p.componentType],z=s$[p.type],H=M?oht(F):1,Z=N.json.bufferViews[p.bufferView],se=Z.byteStride?Z.byteStride/F.BYTES_PER_ELEMENT:z,fe=p.count*se;for(let xe=0,be=0;xe0){const ot=p.json.accessors[M.TEXCOORD_0],mt=n$(p,ot);ot.normalized&&t$[ot.componentType]===Uint16Array?(F.texcoordArray=new si,F.texcoordArray.resizeExact(ot.count),JOe(p,ot,F.texcoordArray.uint16,mt,!1)):(F.texcoordArray=new Ko,F.texcoordArray.resizeExact(ot.count),JOe(p,ot,F.texcoordArray.float32,mt))}const Ye=!(!p.json.extensionsUsed||!p.json.extensionsUsed.includes("EXT_meshopt_compression"));M._FEATURE_ID_RGBA4444!==void 0&&Ye&&lht(p,p.json.accessors[M._FEATURE_ID_RGBA4444],!1,F),M._FEATURE_RGBA4444!==void 0&&lht(p,p.json.accessors[M._FEATURE_RGBA4444],!Ye,F),F.hasFeatureData=!!F.featureArray;const st=N.material;return F.material=function(ot,mt){const{emissiveFactor:lt=[0,0,0],alphaMode:yt="OPAQUE",alphaCutoff:Nt=.5,normalTexture:as,occlusionTexture:Et,emissiveTexture:$t,doubleSided:Jt,name:ns}=ot,{baseColorFactor:Ls=[1,1,1,1],metallicFactor:Gs=1,roughnessFactor:pn=1,baseColorTexture:cn,metallicRoughnessTexture:jn}=ot.pbrMetallicRoughness||{},Hn=Et?mt[Et.index]:void 0;if(Et&&Et.extensions&&Et.extensions.KHR_texture_transform&&Hn){const Cs=Et.extensions.KHR_texture_transform;Hn.offsetScale=[Cs.offset[0],Cs.offset[1],Cs.scale[0],Cs.scale[1]]}return{name:ns,pbrMetallicRoughness:{baseColorFactor:new Ci(...Ls),metallicFactor:Gs,roughnessFactor:pn,baseColorTexture:cn?mt[cn.index]:void 0,metallicRoughnessTexture:jn?mt[jn.index]:void 0},doubleSided:Jt,emissiveFactor:new Ci(...lt),alphaMode:yt,alphaCutoff:Nt,normalTexture:as?mt[as.index]:void 0,occlusionTexture:Hn,emissionTexture:$t?mt[$t.index]:void 0,defined:ot.defined===void 0}}(st!==void 0?p.json.materials[st]:{defined:!1},_),F}function e8e(N,p,_){const{matrix:A,rotation:M,translation:F,scale:z,mesh:H,extras:Z,children:se,name:fe}=N,xe={};if(xe.name=fe,xe.localMatrix=A||function(be,Te,De,Ue){var Ye=Te[0],st=Te[1],ot=Te[2],mt=Te[3],lt=Ye+Ye,yt=st+st,Nt=ot+ot,as=Ye*lt,Et=Ye*yt,$t=Ye*Nt,Jt=st*yt,ns=st*Nt,Ls=ot*Nt,Gs=mt*lt,pn=mt*yt,cn=mt*Nt,jn=Ue[0],Hn=Ue[1],Cs=Ue[2];return be[0]=(1-(Jt+Ls))*jn,be[1]=(Et+cn)*jn,be[2]=($t-pn)*jn,be[3]=0,be[4]=(Et-cn)*Hn,be[5]=(1-(as+Ls))*Hn,be[6]=(ns+Gs)*Hn,be[7]=0,be[8]=($t+pn)*Cs,be[9]=(ns-Gs)*Cs,be[10]=(1-(as+Jt))*Cs,be[11]=0,be[12]=De[0],be[13]=De[1],be[14]=De[2],be[15]=1,be}([],M||[0,0,0,1],F||[0,0,0],z||[1,1,1]),xe.globalMatrix=v(xe.localMatrix),H!==void 0){xe.meshes=_[H];const be=xe.anchor=[0,0];for(const Te of xe.meshes){const{min:De,max:Ue}=Te.aabb;be[0]+=De[0]+Ue[0],be[1]+=De[1]+Ue[1]}be[0]=Math.floor(be[0]/xe.meshes.length/2),be[1]=Math.floor(be[1]/xe.meshes.length/2)}if(Z&&(Z.id&&(xe.id=Z.id),Z.lights&&(xe.lights=function(be){if(!be.length)return[];const Te=function(ot){const mt=atob(ot),lt=new Uint8Array(mt.length);for(let yt=0;yt=mt.length||Ye>=mt.length||st>=mt.length||ot>=mt.length)return null;const lt=mt[Ue],yt=mt[Ye],Nt=mt[st],as=mt[ot];if(lt.bufferView===void 0||yt.bufferView===void 0||Nt.bufferView===void 0||as.bufferView===void 0)return null;const Et=be.json.bufferViews;if(lt.bufferView>=Et.length||yt.bufferView>=Et.length||Nt.bufferView>=Et.length||as.bufferView>=Et.length)return null;const $t=Et[lt.bufferView],Jt=Et[yt.bufferView],ns=Et[Nt.bufferView],Ls=Et[as.bufferView];if($t.buffer>=be.buffers.length||Jt.buffer>=be.buffers.length||ns.buffer>=be.buffers.length||Ls.buffer>=be.buffers.length)return null;const Gs=(Vn,Dn,ir)=>Vn>=0&&Vn<=ir&&Dn<=ir-Vn,pn=lt.byteOffset||0,cn=yt.byteOffset||0,jn=Nt.byteOffset||0,Hn=as.byteOffset||0;if(!(Gs(pn,0,$t.byteLength)&&Gs(cn,3*yt.count*4,Jt.byteLength)&&Gs(jn,3*Nt.count*4,ns.byteLength)&&Gs(Hn,4*as.count,Ls.byteLength)))return null;const Cs=new Uint8Array(be.buffers[$t.buffer],($t.byteOffset||0)+pn,$t.byteLength-pn),Qs=new Float32Array(be.buffers[Jt.buffer],(Jt.byteOffset||0)+cn,3*yt.count),an=new Float32Array(be.buffers[ns.buffer],(ns.byteOffset||0)+jn,3*Nt.count),Ln=new Uint32Array(be.buffers[Ls.buffer],(Ls.byteOffset||0)+Hn,as.count),In=new iht;if(In.serializeFromGltf(Cs,Qs,an,Ln),De!==void 0&&be.json.meshes&&be.json.meshes[De]){const Vn=be.json.meshes[De].primitives[0];if(Vn&&Vn.attributes.POSITION!==void 0&&Vn.attributes.POSITION1&&A.at(-1).equals(A[0])&&A.pop();let M=0;for(let z=0;z0&&A.reverse();const F=eM(A.flatMap(z=>[z.x,z.y]),[]);return F.length===0?null:{vertices:A,indices:F}}function hfs(N,p){const _=[],A=[];let M=0;const F=[];for(const z of N){M=_.length;const H=z.vertexArray.float32,Z=z.indexArray.uint16;for(let se=0;se0&&([A[z+1],A[z+2]]=[A[z+2],A[z+1]])}return{vertices:_,indices:A}}function cht(N,p){for(let _=0;_0){const Ue=Array.from(De.values()).sort((Ye,st)=>Ye-st);for(let Ye=Ue.length-1;Ye>=0;Ye--)fe.splice(Ue[Ye],1)}})(Z,H,N.json.nodes);const se=A?cht(A,"LOD"):-1;if(se>=0){const fe=A[se].nodes,xe=new Map;for(const be of fe){const Te=e8e(F[be],N,_);Te.id&&xe.set(Te.id,Te)}for(const be of Z)if(be.id){const Te=xe.get(be.id);Te&&Te.meshes&&(be.lodMeshes=Te.meshes,Te.meshBVH&&(be.meshBVH=Te.meshBVH))}}return Z}function mfs(N){N.heightmap=new Float32Array(4096),N.heightmap.fill(-1);const p=N.vertexArray.float32,_=N.aabb.min[0]-1,A=N.aabb.min[1]-1,M=oR/(N.aabb.max[0]-_+2),F=oR/(N.aabb.max[1]-A+2);for(let z=0;zN.heightmap[se*oR+Z]&&(N.heightmap[se*oR+Z]=H)}}function dht(N,p,_,A,M){_.reserve(_.length+4*N.length),A.reserve(A.length+10*N.length),M.reserve(M.length+10*N.length);let F=A.length;for(const z of N){const H=Math.min(10,Math.max(4,1.3*z.height))*p,Z=[-z.normal[1],z.normal[0],0],se=Math.min(.29,.1*z.width/z.depth),fe=z.width-2*z.depth*p*(se+.01),xe=ke([],z.pos,Z,fe/2),be=ke([],z.pos,Z,-fe/2),Te=[xe[0],xe[1],xe[2]+z.height],De=[be[0],be[1],be[2]+z.height],Ue=ke([],z.normal,Z,se);Fe(Ue,Ue,H);const Ye=ke([],z.normal,Z,-se);Fe(Ye,Ye,H),ue(Ue,xe,Ue),ue(Ye,be,Ye),xe[2]+=.1,be[2]+=.1,A.emplaceBack(Ue[0],Ue[1],Ue[2]),A.emplaceBack(Ye[0],Ye[1],Ye[2]),A.emplaceBack(xe[0],xe[1],xe[2]),A.emplaceBack(be[0],be[1],be[2]),A.emplaceBack(Te[0],Te[1],Te[2]),A.emplaceBack(De[0],De[1],De[2]),A.emplaceBack(xe[0],xe[1],xe[2]),A.emplaceBack(be[0],be[1],be[2]),A.emplaceBack(Ue[0],Ue[1],Ue[2]),A.emplaceBack(Ye[0],Ye[1],Ye[2]);const st=fe/H/2;M.emplaceBack(-st-se,-1,st,.8),M.emplaceBack(st+se,-1,st,.8),M.emplaceBack(-st,0,st,1.3),M.emplaceBack(st,0,st,1.3),M.emplaceBack(st+se,-.8,st,.7),M.emplaceBack(st+se,-.8,st,.7),M.emplaceBack(0,0,st,1.3),M.emplaceBack(0,0,st,1.3),M.emplaceBack(st+se,-1.2,st,.8),M.emplaceBack(st+se,-1.2,st,.8),_.emplaceBack(6+F,4+F,8+F),_.emplaceBack(7+F,9+F,5+F),_.emplaceBack(0+F,1+F,2+F),_.emplaceBack(1+F,3+F,2+F),F+=10}}function ffs(N,p,_){const A={};A.indexArray=new Vr,A.vertexArray=new zn,A.colorArray=new Hr,A.indexArray.reserveExact(4*N.length),A.vertexArray.reserveExact(10*N.length),A.colorArray.reserveExact(10*N.length),dht(N,p,A.indexArray,A.vertexArray,A.colorArray),A.featureArray=new si,A.featureArray.reserveExact(A.vertexArray.length);for(let z=0;z{z.push(new xs(xe,Z+(xe-H)/(se-H)*(fe-Z)))}:(z,H,Z,se,fe,xe)=>{z.push(new xs(H+(xe-Z)/(fe-Z)*(se-H),xe))};for(const z of N){const H=[];for(const Z of z){if(Z.length<=2)continue;const se=[];for(let be=0;bep&&F(se,Te,De,Ue,Ye,p):st>_?ot<_&&F(se,Te,De,Ue,Ye,_):se.push(Z[be]),ot=p&&F(se,Te,De,Ue,Ye,p),ot>_&&st<=_&&F(se,Te,De,Ue,Ye,_)}let fe=Z.at(-1);const xe=A===0?fe.x:fe.y;xe>=p&&xe<=_&&se.push(fe),se.length&&(fe=se.at(-1),se[0].x===fe.x&&se[0].y===fe.y||se.push(se[0]),H.push(se))}H.length&&M.push(H)}return M}const s8e=[new xs(0,0),new xs(Fr,0),new xs(Fr,Fr),new xs(0,Fr)];function mht(N,p){const _=[];let A=[];if(!p||N.length<2)return[N];if(N.length===2)return U9(N[0],N[1],s8e)?[N]:[];for(let M=0;M0&&(A.length>1&&_.push(A),A=[])}return A.length>1&&_.push(A),_}const n8e=rM.types,Tfs=["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"],Mfs=["fill-extrusion-flood-light-ground-radius"],Pfs=Math.pow(2,13),Ifs=Math.pow(2,15)-1,_le=new xs(0,1),Y3=2147483648,wle=1073741824;function ZY(N,p,_,A,M,F,z,H){N.emplaceBack((p<<1)+z,(_<<1)+F,(Math.floor(A*Pfs)<<1)+M,Math.round(H))}function XY(N,p,_){N.emplaceBack(p.x*Fr,p.y*Fr,_?1:0)}function jle(N,p,_,A,M,F){N.emplaceBack(p.x,p.y,(_.x<<1)+A,(_.y<<1)+M,F)}function QY(N,p,_){N.emplaceBack(p.x,p.y,p.z,_[0]*16384,_[1]*16384,_[2]*16384)}class fht{constructor(){this.vertexOffset=0,this.vertexCount=0,this.indexOffset=0,this.indexCount=0}}class Nle{constructor(){this.data=[]}get length(){return this.data.length}push(p){this.data.push(p)}get(p){return this.data[p]}static serialize(p,_){const A=p.data.length,M=new Uint32Array(4*A),F=[];F.length=A;for(let z=0;zp.max.x&&(p.max.x=_.x,M=!0),_.yp.max.y&&(p.max.y=_.y,M=!0),((_.x===0||_.x===Fr)&&_.x===A.x)!=((_.y===0||_.y===Fr)&&_.y===A.y)&&this.processBorderOverlap(_,A),M&&this.checkBorderIntersection(_,A)}checkBorderIntersection(p,_){_.x<0!=p.x<0&&this.addBorderIntersection(0,ya(_.y,p.y,(0-_.x)/(p.x-_.x))),_.x>Fr!=p.x>Fr&&this.addBorderIntersection(1,ya(_.y,p.y,(Fr-_.x)/(p.x-_.x))),_.y<0!=p.y<0&&this.addBorderIntersection(2,ya(_.x,p.x,(0-_.y)/(p.y-_.y))),_.y>Fr!=p.y>Fr&&this.addBorderIntersection(3,ya(_.x,p.x,(Fr-_.y)/(p.y-_.y)))}addBorderIntersection(p,_){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 A=this.borders[p];_A[1]&&(A[1]=_)}processBorderOverlap(p,_){if(p.x===_.x){if(p.y===_.y)return;const A=p.x===0?0:1;this.addBorderIntersection(A,_.y),this.addBorderIntersection(A,p.y)}else{const A=p.y===0?2:3;this.addBorderIntersection(A,_.x),this.addBorderIntersection(A,p.x)}}centroid(){return this.accCount===0?new xs(0,0):new xs(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((p,_)=>p+ +(_[0]!==Number.MAX_VALUE),0):0}}function pht(N,p){const _=N.add(p)._unit(),A=ta(N.x*_.x+N.y*_.y,-1,1);var M,F,z;return z=Math.acos(A),Math.min(4,Math.max(-4,Math.tan(z)))/4*Ifs*((M=N).x*(F=p).y-M.y*F.x<0?-1:1)}const Lfs=[N=>N.x<0,N=>N.x>Fr,N=>N.y<0,N=>N.y>Fr];function Rfs(N,p,_,A){const M=[4];if(A===0)return M;_._mult(A);const F=N.sub(_),z=p.sub(_),H=[N,p,F,z];for(let Z=0;Z<4;Z++)for(const se of H)if(Lfs[Z](se)){M.push(Z);break}return M}class a8e{constructor(p){this.groundRadiusArray=null,this.groundRadiusBuffer=null,this.vertexArray=new Yn,this.indexArray=new Vr,this.programConfigurations=new Yk(p.layers,{zoom:p.zoom,lut:p.lut},_=>Mfs.includes(_)),this._segments=new Ri,this.hiddenByLandmarkVertexArray=new fm,this._segmentToGroundQuads={},this._segmentToGroundQuads[0]=[],this._segmentToRegionTriCounts={},this._segmentToRegionTriCounts[0]=[0,0,0,0,0],this.regionSegments={},this.regionSegments[4]=new Ri}getDefaultSegment(){return this.regionSegments[4]}hasData(){return this.vertexArray.length!==0}addData(p,_,A,M=!1){const F=p.length;if(F>2){let z=Math.max(0,this._segments.get().length-1);const H=this._segments._prepareSegment(4*F,this.vertexArray.length,2*this._segmentToGroundQuads[z].length);let Z;z!==this._segments.get().length-1&&(z++,this._segmentToGroundQuads[z]=[],this._segmentToRegionTriCounts[z]=[0,0,0,0,0]);{const se=p[0],fe=p[1];Z=pht(se.sub(p[F-1])._perp()._unit(),fe.sub(se)._perp()._unit())}for(let se=0;seM.region-F.region);for(let A=0;A<_;A++){const M=this._segmentToGroundQuads[A],F=p[A],z=this._segmentToRegionTriCounts[A];z.reduce((Z,se)=>Z+se,0);let H=0;for(let Z=0;Z<=4;Z++){const se=z[Z];if(se!==0){let fe=this.regionSegments[Z];fe||(fe=this.regionSegments[Z]=new Ri);const xe={vertexOffset:F.vertexOffset,primitiveOffset:F.primitiveOffset+H,vertexLength:F.vertexLength,primitiveLength:se};fe.get().push(xe)}H+=se}for(let Z=0;Z0?this.hiddenByLandmarkVertexBuffer=p.createVertexBuffer(this.hiddenByLandmarkVertexArray,Cfs.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 p=0;p<=4;p++){const _=this.regionSegments[p];_&&_.destroy()}}}}class Cle{constructor(p){this.zoom=p.zoom,this.canonical=p.canonical,this.overscaling=p.overscaling,this.layers=p.layers,this.pixelRatio=p.pixelRatio,this.layerIds=this.layers.map(_=>_.fqid),this.index=p.index,this.hasPattern=!1,this.edgeRadius=0,this.projection=p.projection,this.activeReplacements=[],this.replacementUpdateTime=0,this.centroidData=new Sle,this.footprintIndices=new Vr,this.footprintVertices=new Hs,this.footprintSegments=new Nle,this.layoutVertexArray=new Mn,this.centroidVertexArray=new dj,this.wallVertexArray=new ld,this.indexArray=new Vr,this.programConfigurations=new Yk(p.layers,{zoom:p.zoom,lut:p.lut},_=>Tfs.includes(_)),this.segments=new Ri,this.stateDependentLayerIds=this.layers.filter(_=>_.isStateDependent()).map(_=>_.id),this.groundEffect=new a8e(p),this.maxHeight=0,this.partLookup={},this.triangleSubSegments=[],this.polygonSegments=[],this.buildingGroups=new Map,this.worldview=p.worldview,this.hasAppearances=null}updateFootprints(p,_){}updateAppearances(p,_,A,M){return{hasLayoutChanges:!1,hasUboChanges:!1}}populate(p,_,A,M){this.features=[],this.hasPattern=X6("fill-extrusion",this.layers,this.pixelRatio,_),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=K(A),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:F,id:z,index:H,sourceLayerIndex:Z}of p){const se=this.layers[0]._featureFilter.needGeometry,fe=_t(F,se);if(!this.layers[0]._featureFilter.filter(new Kn(this.zoom,{worldview:this.worldview,activeFloors:_.activeFloors}),fe,A))continue;const xe={id:z,sourceLayerIndex:Z,index:H,geometry:se?fe.geometry:ht(F,A,M),properties:F.properties,type:F.type,patterns:{}},be=this.layoutVertexArray.length,Te=n8e[xe.type]==="Polygon";if(this.hasPattern)this.features.push({featureId:F.id,feature:jY("fill-extrusion",this.layers,xe,this.zoom,this.pixelRatio,_)});else if(this.wallMode)for(const De of xe.geometry)for(const Ue of mht(De,Te))this.addFeature(F.id,xe,[Ue],H,A,{},_.availableImages,M,_.brightness);else this.addFeature(F.id,xe,xe.geometry,H,A,{},_.availableImages,M,_.brightness);_.featureIndex.insert(F,xe.geometry,H,Z,this.index,be)}this._finalizeBuildingGroups(),this.sortBorders(),this.projection.name==="mercator"&&this.splitToSubtiles(),this.groundEffect.prepareBorderSegments(),this.polygonSegments.length=0}addFeatures(p,_,A,M,F,z){for(const{featureId:H,feature:Z}of this.features){const se=n8e[Z.type]==="Polygon",{geometry:fe}=Z;if(this.wallMode)for(const xe of fe)for(const be of mht(xe,se))this.addFeature(H,Z,[be],Z.index,_,A,M,F,z);else this.addFeature(H,Z,fe,Z.index,_,A,M,F,z)}this._finalizeBuildingGroups(),this.sortBorders(),this.projection.name==="mercator"&&this.splitToSubtiles()}update(p,_,A,M,F,z,H){this.programConfigurations.updatePaintArrays(p,_,F,A,M,z,H,this.worldview),this.groundEffect.update(p,_,F,A,M,z,H,this.worldview)}updateExpressions(p){this.programConfigurations.updateExpressions(p),this.groundEffect.programConfigurations.updateExpressions(p)}isEmpty(){return this.layoutVertexArray.length===0}uploadPending(){return!this.uploaded||this.programConfigurations.needsUpload||this.groundEffect.programConfigurations.needsUpload}upload(p){this.uploaded||(this.layoutVertexBuffer=p.createVertexBuffer(this.layoutVertexArray,Efs),this.indexBuffer=p.createIndexBuffer(this.indexArray),this.wallVertexBuffer=p.createVertexBuffer(this.wallVertexArray,Sfs.members),this.layoutVertexExtArray&&(this.layoutVertexExtBuffer=p.createVertexBuffer(this.layoutVertexExtArray,Afs.members,!0)),this.groundEffect.upload(p)),this.groundEffect.uploadPaintProperties(p),this.programConfigurations.upload(p),this.uploaded=!0}uploadCentroid(p){this.groundEffect.uploadHiddenByLandmark(p),this.needsCentroidUpdate&&(!this.centroidVertexBuffer&&this.centroidVertexArray.length>0?this.centroidVertexBuffer=p.createVertexBuffer(this.centroidVertexArray,kfs.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(p,_,A,M,F,z,H,Z,se){const fe=this.layers[0].paint.get("fill-extrusion-flood-light-ground-radius").evaluate(_,{})/this.tileToMeter,xe=[new xs(0,0),new xs(Fr,Fr)],be=Z.projection,Te=be.name==="globe",De=this.wallMode||n8e[_.type]==="Polygon",Ue=new r8e;Ue.centroidDataIndex=this.centroidData.length;const Ye=new kle;Ye.buildingId=p,_.properties&&Object.hasOwn(_.properties,"building_id")&&(Ye.buildingId=Number(_.properties.building_id)),Ue.buildingId=Ye.buildingId;const st=this.layers[0].paint.get("fill-extrusion-base").evaluate(_,{},F)<=0,ot=this.layers[0].paint.get("fill-extrusion-height").evaluate(_,{},F);let mt;if(Ye.height=ot,Ye.vertexArrayOffset=this.layoutVertexArray.length,Ye.groundVertexArrayOffset=this.groundEffect.vertexArray.length,Te&&!this.layoutVertexExtArray&&(this.layoutVertexExtArray=new yr),this.wallMode){if(Te)return void Yo("Non zero fill-extrusion-line-width is not yet supported on globe.");if(A.length!==1)return;mt=function(Jt){const ns=Jt[0].x===Jt.at(-1).x&&Jt[0].y===Jt.at(-1).y;(function(ir){let Bn=0;const Rr=ir.length;for(let cr=0;cr=0})(Jt)||(Jt=Jt.reverse());const Gs={geometry:[],joinNormals:[],indices:[]},pn=[],cn=[],jn=[];let Hn=Jt.length;for(;Hn>=2&&Jt[Hn-1].equals(Jt[Hn-2]);)Hn--;if(Hn<(ns?3:2))return Gs;let Cs,Qs,an,Ln,In,Vn=0;for(;Vn0;let Wa="miter";const Ka=2;Wa==="miter"&&cr>Ka&&(Wa="bevel"),Wa==="bevel"&&(cr>100&&(Wa="flipbevel"),cr{const rl=new xs(Fa.x,Fa.y),$l=new xs(Fa.x,Fa.y);rl.x+=Ai.x*Fo,rl.y+=Ai.y*Fo,$l.x-=Ai.x*Math.max(Ni,1),$l.y-=Ai.y*Math.max(Ni,1),jn.push(Ai),pn.push(rl),cn.push($l)};if(Wa==="miter")Bn._mult(cr),oi(Cs,Bn,0,0);else if(Wa==="flipbevel")Bn=In.mult(-1),oi(Cs,Bn,0,0),oi(Cs,Bn.mult(-1),0,0);else{const Fa=-Math.sqrt(cr*cr-1),Ai=jr?Fa:0,Ni=jr?0:Fa;Qs&&oi(Cs,Ln,Ai,Ni),an&&oi(Cs,In,Ai,Ni)}}Gs.geometry=[...pn,...cn.reverse(),pn[0]],Gs.joinNormals=[...jn,...jn.reverse(),jn.at(-1)];const Dn=Gs.geometry.length-1;for(let ir=0;irJt<(ns.length-1)/2||Jt===ns.length-1,yt=this.wallMode?[A]:Pa(A,500);for(let Jt=yt.length-1;Jt>=0;Jt--){const ns=yt[Jt];(ns.length===0||Ofs(ns[0]))&&yt.splice(Jt,1)}let Nt;if(Te)Nt=wht(yt,xe,F);else{Nt=[];for(const Jt of yt)Nt.push({polygon:Jt,bounds:xe})}const as=De?this.edgeRadius:0,Et=as>0&&this.zoom<17,$t=(Jt,ns)=>{if(Jt.length===0)return!1;const Ls=Jt.at(-1);return ns.x===Ls.x&&ns.y===Ls.y};for(const{polygon:Jt,bounds:ns}of Nt){let Ls=0,Gs=0;for(const Hn of Jt)De&&!Hn[0].equals(Hn.at(-1))&&Hn.push(Hn[0]),Gs+=De?Hn.length-1:Hn.length;const pn=this.segments.prepareSegment((De?5:4)*Gs,this.layoutVertexArray,this.indexArray);Ye.footprintSegIdx<0&&(Ye.footprintSegIdx=this.footprintSegments.length),Ye.polygonSegIdx<0&&(Ye.polygonSegIdx=this.polygonSegments.length);const cn={triangleArrayOffset:this.indexArray.length,triangleCount:0,triangleSegIdx:this.segments.segments.length-1},jn=new fht;if(jn.vertexOffset=this.footprintVertices.length,jn.indexOffset=3*this.footprintIndices.length,jn.ringIndices=[],De){const Hn=[],Cs=[];Ls=pn.vertexLength;for(let an=0;an4&&vht(Cs[Cs.length-2],Cs[0],Cs[1]),an=as?Ffs(Cs[Cs.length-2],Cs[0],Cs[1],as):0;const Ln=[];let In,Vn,Dn;Vn=Cs[1].sub(Cs[0])._perp()._unit();let ir=!0;for(let Bn=1,Rr=0;Bn0?1:0,Ai=cr.dist(jr);if(Rr+Ai>32768&&(Rr=0),as){Dn=Ale(jr,Wa,Vn);let $l=xht(cr,jr,Wa,i8e(Vn,Dn),as);isNaN($l)&&($l=0);const wc=Dfs(cr,jr,new xs(0,0));cr=cr.add(wc.mult(an))._round(),jr=jr.add(wc.mult(-$l))._round(),an=$l,Vn=Dn,st&&this.zoom>=17&&($t(Ln,cr)||Ln.push(cr),$t(Ln,jr)||Ln.push(jr))}const Ni=pn.vertexLength,Fo=Cs.length>4&&vht(cr,jr,Wa);let rl=bht(Rr,Qs,ir);if(ZY(this.layoutVertexArray,cr.x,cr.y,oi,Fa,0,0,rl),ZY(this.layoutVertexArray,cr.x,cr.y,oi,Fa,0,1,rl),this.wallMode){const $l=lt(Bn-1,Cs),wc=mt.joinNormals[Bn-1];XY(this.wallVertexArray,wc,$l),XY(this.wallVertexArray,wc,$l)}if(Rr+=Ai,rl=bht(Rr,Fo,!ir),Qs=Fo,ZY(this.layoutVertexArray,jr.x,jr.y,oi,Fa,0,0,rl),ZY(this.layoutVertexArray,jr.x,jr.y,oi,Fa,0,1,rl),this.wallMode){const $l=lt(Bn,Cs),wc=mt.joinNormals[Bn];XY(this.wallVertexArray,wc,$l),XY(this.wallVertexArray,wc,$l)}if(pn.vertexLength+=4,this.indexArray.emplaceBack(Ni+0,Ni+1,Ni+2),this.indexArray.emplaceBack(Ni+1,Ni+3,Ni+2),pn.primitiveLength+=2,as){const $l=Ls+(Bn===1?Cs.length-2:Bn-2),wc=Bn===1?Ls:$l+1;if(this.indexArray.emplaceBack(Ni+1,$l,Ni+3),this.indexArray.emplaceBack($l,wc,Ni+3),pn.primitiveLength+=2,In===void 0&&(In=Ni),!o8e(Wa,Cs[Bn],ns)){const Vm=Bn===Cs.length-1?In:pn.vertexLength;this.indexArray.emplaceBack(Ni+2,Ni+3,Vm),this.indexArray.emplaceBack(Ni+3,Vm+1,Vm),this.indexArray.emplaceBack(Ni+3,wc,Vm+1),pn.primitiveLength+=3}ir=!ir}if(Te){const $l=this.layoutVertexExtArray,wc=be.projectTilePoint(cr.x,cr.y,F),Vm=be.projectTilePoint(jr.x,jr.y,F),Z0=be.upVector(F,cr.x,cr.y),Jh=be.upVector(F,jr.x,jr.y);QY($l,wc,Z0),QY($l,wc,Z0),QY($l,Vm,Jh),QY($l,Vm,Jh)}}De&&(Ls+=Cs.length-1),st&&as&&this.zoom>=17&&(Ln.length!==0&&$t(Ln,Ln[0])&&Ln.pop(),this.groundEffect.addData(Ln,ns,fe,as>0))}this.footprintSegments.push(jn),cn.triangleCount=this.indexArray.length-cn.triangleArrayOffset,this.polygonSegments.push(cn),++Ye.footprintSegLen,++Ye.polygonSegLen}if(Ye.vertexCount=this.layoutVertexArray.length-Ye.vertexArrayOffset,Ye.groundVertexCount=this.groundEffect.vertexArray.length-Ye.groundVertexArrayOffset,Ye.vertexCount!==0){if(Ye.centroidXY=Ue.borders?_le:this.encodeCentroid(Ue,Ye),_.properties&&Object.hasOwn(_.properties,"building_id")){const Jt=Ye.buildingId;let ns=this.buildingGroups.get(Jt);ns||(ns={accX:0,accY:0,accCount:0,mergedMin:new xs(Number.MAX_VALUE,Number.MAX_VALUE),mergedMax:new xs(-Number.MAX_VALUE,-Number.MAX_VALUE),partIndices:[]},this.buildingGroups.set(Jt,ns)),ns.accX+=Ue.acc.x,ns.accY+=Ue.acc.y,ns.accCount+=Ue.accCount,ns.mergedMin.x=Math.min(ns.mergedMin.x,Ye.min.x),ns.mergedMin.y=Math.min(ns.mergedMin.y,Ye.min.y),ns.mergedMax.x=Math.max(ns.mergedMax.x,Ye.max.x),ns.mergedMax.y=Math.max(ns.mergedMax.y,Ye.max.y),ns.partIndices.push(this.centroidData.length)}if(this.centroidData.push(Ye),Ue.borders){this.featuresOnBorder.push(Ue);const Jt=this.featuresOnBorder.length-1;for(let ns=0;nsthis.featuresOnBorder[_].borders[p][0]-this.featuresOnBorder[A].borders[p][0])}splitToSubtiles(){const p=[];for(let H=0;HFr),fe=2*se+(+(Z.min.x+Z.max.x>Fr)^se);for(let xe=0;xeH.triangleSegmentIdx===Z.triangleSegmentIdx?H.subtile-Z.subtile:H.triangleSegmentIdx-Z.triangleSegmentIdx);let A=0,M=0,F=0;for(const H of p){if(H.triangleSegmentIdx!==A)break;F++}const z=p.length;for(;M!==p.length;){A=p[M].triangleSegmentIdx;let H=0,Z=M,se=M;for(let fe=Z;fe0&&this.triangleSubSegments.push({segment:Te,min:xe,max:be}),Z=se;for(let De=Z;De[ya(Ue[0],Ye[0],st[0]),ya(Ue[1],Ye[1],st[1])],Te=[],De=[];for(const Ue of this.triangleSubSegments){Te[0]=Ue.min.x/Fr,Te[1]=Ue.min.y/Fr,De[0]=Ue.max.x/Fr,De[1]=Ue.max.y/Fr;const Ye=be(fe,xe,Te),st=be(fe,xe,De);if(new uu([Ye[0],Ye[1],F],[st[0],st[1],z]).intersectsPrecise(A)===0){se&&(M.segments.push(se),se=void 0);continue}const ot=Ue.segment;se&&se.vertexOffset!==ot.vertexOffset&&(M.segments.push(se),se=void 0),se?(se.vertexLength+=ot.vertexLength,se.primitiveLength+=ot.primitiveLength):se={vertexOffset:ot.vertexOffset,primitiveLength:ot.primitiveLength,vertexLength:ot.vertexLength,primitiveOffset:ot.primitiveOffset,sortKey:void 0,vaos:{}}}return se&&M.segments.push(se),M}encodeCentroid(p,_){const A=p.centroid(),M=_.span(),F=Math.min(7,Math.round(M.x*this.tileToMeter/10)),z=Math.min(6,Math.round(M.y*this.tileToMeter/10));return new xs(ta(A.x,1,8191)<<3|F,ta(A.y,1,8191)<<3|z)}encodeBorderCentroid(p){if(!p.borders)return new xs(0,0);const _=p.borders,A=Number.MAX_VALUE;if(_[0][0]!==A||_[1][0]!==A){const M=_[0][0]!==A?0:1;return new xs(6|(_[0][0]!==A?0:65528),(_[M][0]+_[M][1])/2<<3|6)}{const M=_[2][0]!==A?2:3;return new xs((_[M][0]+_[M][1])/2<<3|6,6|(_[2][0]!==A?0:65528))}}showCentroid(p,_){const A=this.centroidData.get(p.centroidDataIndex);if(A.flags&=Y3,_!=="keep"||7&~A.centroidXY.y){if(A.groupCentroidPos.x!==0||A.groupCentroidPos.y!==0){const M=A.span(),F=Math.min(7,Math.round(M.x*this.tileToMeter/10)),z=Math.min(6,Math.round(M.y*this.tileToMeter/10));A.centroidXY=new xs(ta(A.groupCentroidPos.x,1,8191)<<3|F,ta(A.groupCentroidPos.y,1,8191)<<3|z)}else A.centroidXY=new xs(0,0);this.writeCentroidToBuffer(A)}else this.writeCentroidToBuffer(A)}writeCentroidToBuffer(p){this.groundEffect.updateHiddenByLandmark(p);const _=p.vertexArrayOffset,A=p.vertexCount+p.vertexArrayOffset,M=-1073741824&p.flags?_le:p.centroidXY,F=this.centroidVertexArray.geta_centroid_pos0(_);if(this.centroidVertexArray.geta_centroid_pos1(_)!==M.y||F!==M.x){for(let z=_;zZ.max.x||Z.min.x>z.max.x||z.min.y>Z.max.y||Z.min.y>z.max.y||z.footprint.buildingIds.has(Z.buildingId)&&(Z.flags|=z.clipMask!==FY.None?-1073741824:Y3);else for(const Z of this.centroidData)if(!(Z.flags&Y3||Z.flags&wle||z.min.x>Z.max.x||Z.min.x>z.max.x||z.min.y>Z.max.y||Z.min.y>z.max.y))for(let se=0;se_!=Te>_&&p<(this.footprintVertices.int16[2*(fe+z.vertexOffset)+0]-xe)*(_-be)/(Te-be)+xe&&(M=!M)}H=Z}}return M}getHeightAtTileCoord(p,_){let A=Number.NEGATIVE_INFINITY,M=!0;const F=4*(p+Fr)*Fr+(_+Fr);if(Object.hasOwn(this.partLookup,F)){const Z=this.partLookup[F];return Z?{height:Z.height,hidden:!!(Z.flags&Y3)}:void 0}const z=this.centroidData.buffer,H=this.centroidData.length;for(let Z=0;Zz[se+4]||z[se+2]>p||_>z[se+5]||z[se+3]>_)continue;const fe=z[se+13];if(fe<=A)continue;const xe=this.centroidData.get(Z);this.footprintContainsPoint(p,_,xe)&&(A=fe,this.partLookup[F]=xe,M=!!(xe.flags&Y3))}if(A!==Number.NEGATIVE_INFINITY)return{height:A,hidden:M};this.partLookup[F]=void 0}}function Dfs(N,p,_){return N.equals(p)?_:p.sub(N)._unit()}function Ale(N,p,_){return N.equals(p)?_:p.sub(N)._perp()._unit()}function ght(N,p){const _=N.add(p),A=_.mag();return A===0?N:_.div(A)}function i8e(N,p){const _=ght(N,p);return N.x*_.x+N.y*_.y}function Ffs(N,p,_,A){let M,F;return N.equals(p)?(F=Ale(p,_,new xs(0,0)),M=F):(M=p.sub(N)._perp()._unit(),F=Ale(p,_,M)),xht(N,p,_,i8e(M,F),A)}function xht(N,p,_,A,M){const F=Math.sqrt(1-A*A);return Math.min(N.dist(p)/3,p.dist(_)/3,M*F/A)}function o8e(N,p,_){return N.x<_[0].x&&p.x<_[0].x||N.x>_[1].x&&p.x>_[1].x||N.y<_[0].y&&p.y<_[0].y||N.y>_[1].y&&p.y>_[1].y}function yht(N,p){return N.xp[1].x||N.yp[1].y}function Ofs(N){return N.every(p=>p.x<=0)||N.every(p=>p.x>=Fr)||N.every(p=>p.y<=0)||N.every(p=>p.y>=Fr)}function vht(N,p,_){if(N.x<0||N.x>=Fr||p.x<0||p.x>=Fr||_.x<0||_.x>=Fr)return!1;const A=_.sub(p),M=A.perp(),F=N.sub(p);return(A.x*F.x+A.y*F.y)/Math.sqrt((A.x*A.x+A.y*A.y)*(F.x*F.x+F.y*F.y))>-.866&&M.x*F.x+M.y*F.y<0}function bht(N,p,_){const A=p?2|N:-3&N;return _?1|A:-2&A}function _ht(){const N=Math.PI/32,p=Math.tan(N),_=nM;return _*Math.sqrt(1+2*p*p)-_}function wht(N,p,_){const A=1<<_.z,M=Ox(_.x/A),F=Ox((_.x+1)/A),z=Hd(_.y/A),H=Hd((_.y+1)/A);return function(Z,se,fe,xe,be=0,Te){const De=[];if(!Z.length||!fe||!xe)return De;const Ue=(Nt,as)=>{for(const Et of Nt)De.push({polygon:Et,bounds:as})},Ye=Math.ceil(Math.log2(fe)),st=Math.ceil(Math.log2(xe)),ot=Ye-st,mt=[];for(let Nt=0;Nt0?0:1);for(let Nt=0;Ntas+1?yt.push({polygons:pn,bounds:jn,depth:as+1}):Ue(pn,jn)}if(cn.length){const jn=[new xs(Et===0?Gs:$t.x,Et===1?Gs:$t.y),Jt];mt.length>as+1?yt.push({polygons:cn,bounds:jn,depth:as+1}):Ue(cn,jn)}}return De}(N,p,Math.ceil((F-M)/11.25),Math.ceil((z-H)/11.25),1,(Z,se,fe)=>{if(Z===0)return .5*(se+fe);{const xe=Hd((_.y+se/Fr)/A);return(ap(.5*(Hd((_.y+fe/Fr)/A)+xe))*A-_.y)*Fr}})}function zfs(N,p,_,A,M,F){const z=Math.pow(2,A.z-M.z);for(let H=0;H<_;H++){let Z=N.int16[2*(H+p)+0],se=N.int16[2*(H+p)+1];Z=(Z+M.x*Fr)*z-A.x*Fr,se=(se+M.y*Fr)*z-A.y*Fr,F.push(new xs(Z,se))}}oa(Cle,"FillExtrusionBucket",{omit:["layers","features"]}),oa(kle,"PartData"),oa(Sle,"PartDataArray"),oa(Nle,"FootprintSegmentArray"),oa(r8e,"BorderCentroidData"),oa(a8e,"GroundEffect");const l8e=4096;class Bfs{constructor(p){this.module=p,this.memoryStack=this.module.malloc(l8e),this.memoryStackNextFree=this.memoryStack}createIntArray(p){const _=this.memoryStackNextFree;return this.memoryStackNextFree+=p.length*Int32Array.BYTES_PER_ELEMENT,this.memoryStackNextFree-this.memoryStack>l8e?-1:(new Int32Array(this.module.heap32.buffer,_,p.length).set(p),_)}createFloatArray(p){const _=this.memoryStackNextFree;return this.memoryStackNextFree+=p.length*Float32Array.BYTES_PER_ELEMENT,this.memoryStackNextFree-this.memoryStack>l8e?-1:(new Float32Array(this.module.heapF32.buffer,_,p.length).set(p),_)}readStringBuffer(p){let _="";for(;this.module.heapU8[p]!==0;)_+=String.fromCharCode(this.module.heapU8[p]),++p;return _}setStyle(p){const _=p.normalScale;this.module.setStyle(_[0],_[1],_[2],p.tileToMeters)}setAOOptions(p,_){this.module.setAOOptions(p?1:0,_)}setMetricOptions(p,_){this.module.setMetricOptions(p?1:0,_)}setStructuralOptions(p){this.module.setStructuralOptions(p?1:0)}setFacadeOptions(p,_){this.module.setFacadeOptions(p,_?1:0)}setFauxFacadeOptions(p,_,A){this.module.setFauxFacadeOptions(p?1:0,_?1:0,A)}setFacadeClassifierOptions(p){this.module.setFacadeClassifierOptions(p)}generateMesh(p,_){this.memoryStackNextFree=this.memoryStack;for(const H of p){const Z=this.createIntArray(H.ringIndices),se=this.createFloatArray(H.coordinates);if(Z===-1||se===-1)return`building_gen: Out of stack memory: ${this.memoryStackNextFree-this.memoryStack}/4096`;this.module.addFeature(H.id,H.sourceId,H.minHeight,H.height,H.roofType,se,Z,H.ringIndices.length-1)}for(const H of _){let Z;Z=H.entrances?JSON.parse(H.entrances):[];const se=this.createFloatArray(Z),fe=this.createFloatArray(H.coordinates);if(se===-1||fe===-1)return`building_gen: Out of stack memory: ${this.memoryStackNextFree-this.memoryStack}/4096`;this.module.addFacade(H.sourceId,H.crossPerc,H.distanceToRoad,se,Z.length,fe,H.coordinates.length)}if(!this.module.generateMesh()){const H=this.module.getLastError();return this.readStringBuffer(H)}const A=this.module.getMeshCount(),M=new Array(A);for(let H=0;H_||M.y<-p||M.y>_)return!1;return!0}function Ufs(N){switch(N){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: ${N}`)}}let Nht,kht,r$=null,Sht=null,fj=null;class c8e{constructor(){this.layoutVertexArray=new zn,this.layoutAttenuationArray=new Hr,this.layoutColorArray=new si,this.indexArray=new Vr,this.indexArrayForConflation=new Vr,this.segmentsBucket=new Ri}}class d8e{constructor(p){this.layoutFacadePaintArray=null,this.layoutFacadeDataArray=null,this.layoutFacadeVerticalRangeArray=null,this.segmentsBucket=new Ri,this.entranceBloom=new c8e;const _=66560;this.layoutVertexArray=new zn,this.layoutVertexArray.reserve(_),this.layoutNormalArray=new Fs,this.layoutNormalArray.reserve(_),this.layoutCentroidArray=new Fs,this.layoutCentroidArray.reserve(_),this.layoutColorArray=new si,this.layoutColorArray.reserve(_),this.layoutFloodLightDataArray=new Hl,this.layoutFloodLightDataArray.reserve(_),this.layoutAOArray=new fm,this.layoutAOArray.reserve(_),this.indexArray=new Vr,this.indexArray.reserve(66560),this.indexArrayForConflation=new Vr,this.segmentsBucket=new Ri,this.entranceBloom=new c8e,p&&(this.layoutFacadePaintArray=new si,this.layoutFacadeDataArray=new An,this.layoutFacadeVerticalRangeArray=new si)}reserve(p,_,A){this.layoutVertexArray.reserveForAdditional(p),this.layoutCentroidArray.reserveForAdditional(p),this.layoutFloodLightDataArray.reserveForAdditional(p),this.layoutNormalArray.reserveForAdditional(p),this.layoutAOArray.reserveForAdditional(p),this.layoutColorArray.reserveForAdditional(p),this.indexArray.reserveForAdditional(_),A&&(this.layoutFacadePaintArray.reserveForAdditional(p),this.layoutFacadeDataArray.reserveForAdditional(p),this.layoutFacadeVerticalRangeArray.reserveForAdditional(p))}}class Cht{constructor(p){this.requiresHDRuntime=!0,this.colorBufferUploaded=!1,this.maxHeight=0,this.replacementUpdateTime=0,this.activeReplacements=[],this.footprints=[],this.footprintsVertices=new Ko,this.footprintsIndices=new jd,this.footprintsMin=new xs(1/0,1/0),this.footprintsMax=new xs(-1/0,-1/0),this.featuresOnBorder=[],this.buildingWithoutFacade=new d8e(!1),this.buildingWithFacade=new d8e(!0),this.indexArrayForConflationUploaded=!1,this.featureFootprintLookup=new Map,this.buildingIds=new Set,this.footprintLookup={},this.zoom=p.zoom,this.canonical=p.canonical,this.layers=p.layers,this.layerIds=this.layers.map(_=>_.fqid),this.index=p.index,this.hasPattern=!1,this.worldview=p.worldview,this.lut=p.lut,this.programConfigurations=new Yk(p.layers,{zoom:p.zoom,lut:p.lut}),this.stateDependentLayerIds=this.layers.filter(_=>_.isStateDependent()).map(_=>_.id),this.projection=p.projection,this.groundEffect=new a8e(p),this.groundEffect.groundRadiusArray=new $s,this.hasAppearances=null}updateFootprints(p,_){const A=new ple([],[],1),M={vertices:[],indices:new Uint32Array(0),grid:A,min:this.footprintsMin,max:this.footprintsMax,buildingIds:this.buildingIds};_.push({footprint:M,id:p})}updateAppearances(p,_,A,M){return{hasLayoutChanges:!1,hasUboChanges:!1}}populate(p,_,A,M){if(!fj)return;const F=K(A);this.tileToMeter=F,this.brightness=_.brightness,fj.setStyle({normalScale:[1,-1,F],tileToMeters:F}),fj.setAOOptions(!1,.3),fj.setMetricOptions(!1,16),fj.setStructuralOptions(!0),fj.setFacadeClassifierOptions(3);const z=new Map,H=new Map;let Z=0;for(const{feature:Ye}of p){if(jht[Ye.type]!=="LineString"){z.set(Ye.id,Ye.properties.source_id);continue}const st=this.layers[0]._featureFilter.needGeometry;if(st&&!this.layers[0]._featureFilter.filter(new Kn(this.zoom),Ye,A))continue;const ot=_t(Ye,st);if(!st&&!this.layers[0]._featureFilter.filter(new Kn(this.zoom),ot,A))continue;const mt=st?ot.geometry:ht(Ye,A,M),lt=[];for(const Et of mt)for(const $t of Et)lt.push($t.x),lt.push($t.y);const yt={coordinates:lt,crossPerc:Ye.properties.cross_perc,distanceToRoad:Ye.properties.distance_to_road,entrances:Ye.properties.entrances,sourceId:0},Nt=Ye.properties.source_id;let as=H.get(Nt);as||(as=[],H.set(Nt,as)),as.push(yt),++Z}this.maxHeight=0;const se=new Array,fe=new Set,xe=Ye=>{Ye!=null&&fe.add(Ye)},be=(Ye,st)=>{Ye!=null&&se.push({buildingId:Ye,footprintIndex:st})},Te=64*(p.length-Z),De=Te/2;this.buildingWithFacade.reserve(Te,De,!0),this.buildingWithoutFacade.reserve(2*Te,2*De,!1),this.footprintsIndices.reserve(16*(p.length-Z)),this.footprintsVertices.reserve(8*(p.length-Z));for(const{feature:Ye,id:st,index:ot,sourceLayerIndex:mt}of p){if(jht[Ye.type]==="LineString")continue;const lt=this.layers[0]._featureFilter.needGeometry;if(lt&&!this.layers[0]._featureFilter.filter(new Kn(this.zoom),Ye,A))continue;let yt=null;if(Ye.properties&&Object.hasOwn(Ye.properties,"building_id")&&(yt=Number(Ye.properties.building_id),fe.has(yt)))continue;const Nt=_t(Ye,lt);if(!lt&&!this.layers[0]._featureFilter.filter(new Kn(this.zoom),Nt,A))continue;const as=lt?Nt.geometry:ht(Ye,A,M),Et=Pa(as,500);let $t=!1;for(const wo of Et)if(wo.length!==1){$t=!0;break}if($t){xe(yt);continue}if(!$fs(as,163)){xe(yt);continue}const Jt=this.layers[0],ns=Ufs(Jt.layout.get("building-roof-shape").evaluate(Ye,{},A)),Ls=Jt.layout.get("building-base").evaluate(Ye,{},A),Gs=Jt.layout.get("building-height").evaluate(Ye,{},A),pn=Jt.layout.get("building-flood-light-ground-radius").evaluate(Ye,{},A),cn=Jt.paint.get("building-ambient-occlusion-intensity"),jn=pn/this.tileToMeter;Ye.properties["building-part"]="roof";const Hn=Jt.paint.get("building-color").evaluate(Ye,{},this.canonical).toPremultipliedRenderColor(this.lut),Cs=Jt.paint.get("building-emissive-strength").evaluate(Ye,{},this.canonical);Ye.properties["building-part"]="wall";const Qs=Jt.paint.get("building-color").evaluate(Ye,{},this.canonical).toPremultipliedRenderColor(this.lut),an=Jt.paint.get("building-emissive-strength").evaluate(Ye,{},this.canonical);Ye.properties["building-part"]="window";const Ln=Jt.paint.get("building-color").evaluate(Ye,{},this.canonical).toPremultipliedRenderColor(this.lut),In=Jt.paint.get("building-emissive-strength").evaluate(Ye,{},this.canonical);Ye.properties["building-part"]="door";const Vn=Jt.paint.get("building-color").evaluate(Ye,{},this.canonical).toPremultipliedRenderColor(this.lut),Dn=Jt.paint.get("building-emissive-strength").evaluate(Ye,{},this.canonical);let ir=Jt.layout.get("building-flood-light-wall-radius").evaluate(Ye,{},A);ir=ta(ir,0,2048);const Bn=ir/2048*Ele,Rr=z.get(st),cr=H.get(Rr)||[],jr=cr.length!==0&&Jt.layout.get("building-facade").evaluate(Ye,{},A);fj.setFacadeOptions(4,!0),fj.setFauxFacadeOptions(jr,!1,1);let Wa=0,Ka=0,oi=0,Fa=0,Ai=0,Ni=0,Fo=0,rl=0,$l=0,wc=0,Vm=0;if(jr){let wo=Math.round(Jt.layout.get("building-facade-floors").evaluate(Ye,{},A));if(Ls===0){wo=Math.max(1,wo-(cr.length>0?1:0));let Pu=4;if(Gs>100){const Gm=[10,13,15];Pu=Gm[Ye.id?Ye.id%Gm.length:0]}else Gs<=10&&(Pu=3);fj.setFacadeOptions(Pu,!0),Ai=(Gs<15?1.3:1.61803)*Pu/F}else Ai=Ls/F;Ni=Gs/F,Ai=Math.min(Ai,Ni),oi=Jt.layout.get("building-facade-unit-width").evaluate(Ye,{},A)/F,Fa=(Ni-Ai)/wo,fj.setFauxFacadeOptions(!0,!0,oi);const pg=Jt.layout.get("building-facade-window").evaluate(Ye,{},A);Wa=pg[0],Ka=pg[1],Fo=Math.floor(65535*Math.min(1,Ai/Fr)),rl=Math.floor(65535*Math.min(1,Ni/Fr)),$l=Math.floor(255*Wa)<<8|Math.floor(255*Ka),wc=Math.floor(65535*Math.min(1,oi/Fr)),Vm=Math.floor(65535*Math.min(1,Fa/Fr))}const Z0=Array(Et.length),Jh={x:1/0,y:1/0},_l={x:-1/0,y:-1/0},Wd={x:0,y:0};let fh=0;for(let wo=0;wo0){const Pu=[],Gm=Array(pg.length+1);Gm[0]=0;for(let J_=0;J_Fr||Jh.y<0||_l.y>Fr)&&this.featuresOnBorder.push({featureId:Ye.id,footprintIndex:this.footprints.length});{const wo=eM(Jk,null,2);this.footprintsIndices.resize(this.footprintsIndices.length+wo.length),this.footprintsIndices.uint16.set(wo,Kb),this.buildingIds.add(yt??Ye.id),this.footprintsMin.x=Math.min(this.footprintsMin.x,Q_.x),this.footprintsMin.y=Math.min(this.footprintsMin.y,Q_.y),this.footprintsMax.x=Math.max(this.footprintsMax.x,X0.x),this.footprintsMax.y=Math.max(this.footprintsMax.y,X0.y);const pg={footprintVertexOffset:fg,footprintVertexLength:this.footprintsVertices.length-fg,footprintIndexOffset:Kb,footprintIndexLength:this.footprintsIndices.length-Kb,min:Q_,max:X0,hiddenFlags:0,indicesOffset:Cy,indicesLength:Wb,bloomIndicesOffset:Hx,bloomIndicesLength:Gb,groundEffectVertexOffset:QC,groundEffectVertexLength:uR,hasFauxFacade:jr,height:Yv,promoteId:st,feature:Nt,parts:xf,buildingBloom:Vx},Pu=this.footprints.length;Ye.id!==void 0&&this.featureFootprintLookup.set(Ye.id,Pu),be(yt,Pu),this.footprints.push(pg)}this.programConfigurations.populatePaintArrays(mo.layoutVertexArray.length,Ye,ot,{},_.availableImages,A,_.brightness),this.groundEffect.addPaintPropertiesData(Ye,ot,{},_.availableImages,A,_.brightness),_.featureIndex.insert(Ye,as,ot,mt,this.index,Sy)}se.forEach(({buildingId:Ye,footprintIndex:st})=>{fe.has(Ye)&&(this.footprints[st].hiddenFlags|=4)});const Ue=new Set;this.buildingIds.forEach((Ye,st,ot)=>{fe.has(Ye)||Ue.add(Ye)}),this.buildingIds=Ue,this.groundEffect.prepareBorderSegments()}update(p,_,A,M,F,z,H){this.programConfigurations.updatePaintArrays(p,_,F,A,M,z,H),this.groundEffect.update(p,_,F,A,M,z,H),this.evaluate(this.layers[0],p),this.colorBufferUploaded=!1}updateExpressions(p){this.programConfigurations.updateExpressions(p),this.groundEffect.programConfigurations.updateExpressions(p)}isEmpty(){return this.buildingWithoutFacade.layoutVertexArray.length===0&&this.buildingWithFacade.layoutVertexArray.length===0}uploadPending(){return!this.uploaded||this.programConfigurations.needsUpload||this.groundEffect.programConfigurations.needsUpload}upload(p){const _=A=>{A.layoutVertexBuffer=p.createVertexBuffer(A.layoutVertexArray,uht.members),A.layoutNormalBuffer=p.createVertexBuffer(A.layoutNormalArray,pfs.members),A.layoutCentroidBuffer=p.createVertexBuffer(A.layoutCentroidArray,gfs.members),A.layoutFloodLightDataBuffer=p.createVertexBuffer(A.layoutFloodLightDataArray,_fs.members),A.layoutFacadeDataArray&&A.layoutFacadeDataArray.length&&(A.layoutFacadeDataBuffer=p.createVertexBuffer(A.layoutFacadeDataArray,yfs.members)),A.layoutFacadeVerticalRangeArray&&A.layoutFacadeVerticalRangeArray.length&&(A.layoutFacadeVerticalRangeBuffer=p.createVertexBuffer(A.layoutFacadeVerticalRangeArray,vfs.members)),A.entranceBloom.layoutVertexArray.length&&(A.entranceBloom.layoutVertexBuffer=p.createVertexBuffer(A.entranceBloom.layoutVertexArray,uht.members),A.entranceBloom.layoutAttenuationBuffer=p.createVertexBuffer(A.entranceBloom.layoutAttenuationArray,bfs.members)),this.uploadUpdatedColorBuffer(p),this.uploadUpdatedIndexBuffer(p)};this.uploaded||(_(this.buildingWithoutFacade),_(this.buildingWithFacade),this.groundEffect.upload(p)),this.groundEffect.uploadPaintProperties(p),this.programConfigurations.upload(p),this.uploaded=!0}destroy(){const p=_=>{_.layoutVertexBuffer&&(_.layoutVertexBuffer.destroy(),_.layoutNormalBuffer.destroy(),_.layoutColorBuffer.destroy(),_.segmentsBucket.destroy(),_.indexBuffer&&_.indexBuffer.destroy(),_.entranceBloom.layoutVertexBuffer&&(_.entranceBloom.layoutVertexBuffer.destroy(),_.entranceBloom.layoutColorBuffer.destroy(),_.entranceBloom.layoutAttenuationBuffer.destroy(),_.entranceBloom.indexBuffer.destroy(),_.entranceBloom.segmentsBucket.destroy()))};p(this.buildingWithoutFacade),p(this.buildingWithFacade),this.groundEffect.destroy(),this.programConfigurations.destroy()}updateFootprintHiddenFlags(p,_,A=!0){let M=!1;const F=A?_:0,z=0|(A?-1:~_);this.groundEffect.hiddenByLandmarkVertexArray.length===0&&this.groundEffect.hiddenByLandmarkVertexArray.resize(this.groundEffect.vertexArray.length);for(const H of p){const Z=this.footprints[H],se=Z.hiddenFlags&z|F;Z.hiddenFlags!==se&&(Z.hiddenFlags=se,M=!0,this.groundEffect.updateHiddenByLandmarkRange(Z.groundEffectVertexOffset,Z.groundEffectVertexLength,Z.hiddenFlags!==0))}return M&&(this.indexArrayForConflationUploaded=!1),M}uploadUpdatedIndexBuffer(p){if(this.groundEffect.uploadHiddenByLandmark(p),this.indexArrayForConflationUploaded)return;const _=M=>{M.indexArray.length!==0&&(M.indexArrayForConflation.resize(M.indexArray.length),M.indexArrayForConflation.uint16.set(M.indexArray.uint16),M.entranceBloom.indexArrayForConflation.resize(M.entranceBloom.indexArray.length),M.entranceBloom.indexArrayForConflation.uint16.set(M.entranceBloom.indexArray.uint16))};_(this.buildingWithoutFacade),_(this.buildingWithFacade);for(const M of this.footprints){const F=M.hasFauxFacade?this.buildingWithFacade:this.buildingWithoutFacade,z=M.indicesOffset+M.indicesLength;if(M.hiddenFlags!==0){for(let Z=M.indicesOffset;Z{M.indexArray.length!==0&&(M.indexBuffer?M.indexBuffer.updateData(M.indexArrayForConflation):M.indexBuffer=p.createIndexBuffer(M.indexArrayForConflation,!0),M.entranceBloom.indexBuffer?M.entranceBloom.indexBuffer.updateData(M.entranceBloom.indexArrayForConflation):M.entranceBloom.indexBuffer=p.createIndexBuffer(M.entranceBloom.indexArrayForConflation,!0))};A(this.buildingWithoutFacade),A(this.buildingWithFacade),this.indexArrayForConflationUploaded=!0}uploadUpdatedColorBuffer(p){const _=A=>{A.layoutColorBuffer?A.layoutColorBuffer.updateData(A.layoutColorArray):A.layoutColorBuffer=p.createVertexBuffer(A.layoutColorArray,hht.members,!0),A.layoutFacadePaintArray&&(A.layoutFacadePaintBuffer?A.layoutFacadePaintBuffer.updateData(A.layoutFacadePaintArray):A.layoutFacadePaintBuffer=p.createVertexBuffer(A.layoutFacadePaintArray,xfs.members,!0)),A.entranceBloom.layoutColorBuffer?A.entranceBloom.layoutColorBuffer.updateData(A.entranceBloom.layoutColorArray):A.entranceBloom.layoutColorBuffer=p.createVertexBuffer(A.entranceBloom.layoutColorArray,hht.members,!0)};_(this.buildingWithoutFacade),_(this.buildingWithFacade),this.colorBufferUploaded=!0}evaluate(p,_){const A=p.paint.get("building-ambient-occlusion-intensity");for(const M of this.footprints){if(4&M.hiddenFlags)continue;const F=_[M.promoteId],z=M.feature;z.properties["building-part"]="roof";const H=p.paint.get("building-color").evaluate(z,F,this.canonical).toPremultipliedRenderColor(this.lut),Z=p.paint.get("building-emissive-strength").evaluate(z,F,this.canonical);z.properties["building-part"]="wall";const se=p.paint.get("building-color").evaluate(z,F,this.canonical).toPremultipliedRenderColor(this.lut),fe=p.paint.get("building-emissive-strength").evaluate(z,F,this.canonical);z.properties["building-part"]="window";const xe=p.paint.get("building-color").evaluate(z,F,this.canonical).toPremultipliedRenderColor(this.lut),be=p.paint.get("building-emissive-strength").evaluate(z,F,this.canonical);z.properties["building-part"]="door";const Te=p.paint.get("building-color").evaluate(z,F,this.canonical).toPremultipliedRenderColor(this.lut),De=p.paint.get("building-emissive-strength").evaluate(z,F,this.canonical),Ue=M.hasFauxFacade?this.buildingWithFacade:this.buildingWithoutFacade;for(const st of M.parts){let ot,mt=H;st.part===1?(mt=H,ot=Z):st.part===0?(mt=se,ot=fe):st.part===2?(mt=xe,ot=be):st.part===3&&(mt=Te,ot=De),ot=ta(ot,0,1);for(let lt=0;ltz.max.x||Z.max.xz.max.y||Z.max.yH.max.x||H.min.x>p||_>H.max.y||H.min.y>_||H.height<=A||qfs(z,this.footprintsVertices.float32.subarray(2*H.footprintVertexOffset,2*(H.footprintVertexOffset+H.footprintVertexLength)),this.footprintsIndices.uint16.subarray(H.footprintIndexOffset,H.footprintIndexOffset+H.footprintIndexLength))&&(A=H.height,this.footprintLookup[F]=H,M=H.hiddenFlags!==0);if(A!==Number.NEGATIVE_INFINITY)return{height:A,hidden:M};this.footprintLookup[F]=void 0}}function qfs(N,p,_){for(let A=0;A<_.length;A+=3){const M=_[A],F=_[A+1],z=_[A+2],H=p[2*M+0],Z=p[2*M+1],se=p[2*F+0],fe=p[2*F+1],xe=p[2*z+0],be=p[2*z+1],Te=(H-xe)*(N.y-be)-(Z-be)*(N.x-xe),De=(se-H)*(N.y-Z)-(fe-Z)*(N.x-H);if(Te<0!=De<0&&Te!==0&&De!==0)continue;const Ue=(xe-se)*(N.y-fe)-(be-fe)*(N.x-se);if(Ue===0||Ue<0==Te+De<=0)return!0}return!1}function Vfs(N,p,_,A,M,F){const z=Math.pow(2,A.z-M.z);for(let H=0;H<_;H++){let Z=N.float32[2*(H+p)+0],se=N.float32[2*(H+p)+1];Z=(Z+M.x*Fr)*z-A.x*Fr,se=(se+M.y*Fr)*z-A.y*Fr,F.push(new xs(Z,se))}}oa(Cht,"BuildingBucket",{omit:["layers"]}),oa(d8e,"BuildingGeometry"),oa(c8e,"BuildingBloomGeometry");class Aht{constructor(p=0,_=[]){this.frcMask=p,this.rings=_}hasGeometry(){return this.rings.length>0&&this.rings[0].length>0}}async function Tle(){}function a$(N,p,_){const A=p.paint.get(N).value;return A.kind==="constant"?A.value:_.programConfigurations.get(p.id).getMaxValue(N)}function Mle(N){return Math.sqrt(N[0]*N[0]+N[1]*N[1])}function Eht(N,p,_,A,M){if(!p[0]&&!p[1])return N;const F=xs.convert(p)._mult(M);_==="viewport"&&F._rotate(-A);const z=[];for(let H=0;H{const p=[];return N.paint.get("circle-pitch-alignment")==="map"&&p.push("PITCH_WITH_MAP"),N.paint.get("circle-pitch-scale")==="map"&&p.push("SCALE_WITH_MAP"),p};function Pht(N,p,_,A,M,F,z,H,Z){if(F&&N.queryGeometry.isAboveHorizon)return!1;F&&(Z*=N.pixelToTileUnitsFactor);const se=N.tileID.canonical,fe=_.projection.upVectorScale(se,_.center.lat,_.worldSize).metersToTile;for(const xe of p)for(const be of xe){const Te=be.add(H),De=M&&_.elevation?_.elevation.exaggeration()*M.getElevationAt(Te.x,Te.y,!0):0,Ue=_.projection.projectTilePoint(Te.x,Te.y,se);if(De>0){const mt=_.projection.upVector(se,Te.x,Te.y);Ue.x+=mt[0]*fe*De,Ue.y+=mt[1]*fe*De,Ue.z+=mt[2]*fe*De}const Ye=F?Te:Gfs(Ue.x,Ue.y,Ue.z,A),st=F?N.tilespaceRays.map(mt=>Kfs(mt,De)):N.queryGeometry.screenGeometry,ot=Ft([],[Ue.x,Ue.y,Ue.z,1],A);if(!z&&F?Z*=ot[3]/_.cameraToCenterDistance:z&&!F&&(Z*=_.cameraToCenterDistance/ot[3]),F){const mt=Hd((be.y/Fr+se.y)/(1<ya(p,_,A==="log"?(Math.pow(10,N)-1)/9:N);function JY(N){const{expression:p,evaluationKey:_,resolution:A=256,clips:M,scale:F="linear",lut:z=null}=N,H=M?M.length:1,Z=N.image||new s0({width:A,height:H}),se={},fe=(xe,be,Te)=>{se[_]=Te;const De=p.evaluate(se),Ue=(De==null?void 0:De.toNonPremultipliedRenderColor(z))??null;Ue&&(Z.data[xe+be+0]=Math.floor(255*Ue.r),Z.data[xe+be+1]=Math.floor(255*Ue.g),Z.data[xe+be+2]=Math.floor(255*Ue.b),Z.data[xe+be+3]=Math.floor(255*Ue.a))};for(let xe=0,be=0;xe_.fqid),this.index=p.index,this.hasPattern=!1,this.stateDependentLayerIds=this.layers.filter(_=>_.isStateDependent()).map(_=>_.id),this.footprints=[],this.worldview=p.worldview,this.hasAppearances=null}updateFootprints(p,_){for(const A of this.footprints)_.push({footprint:A,id:p})}updateAppearances(p,_,A,M){return{hasLayoutChanges:!1,hasUboChanges:!1}}populate(p,_,A,M){const F=[];for(const{feature:z,id:H,index:Z,sourceLayerIndex:se}of p){const fe=this.layers[0]._featureFilter.needGeometry,xe=_t(z,fe);if(!this.layers[0]._featureFilter.filter(new Kn(this.zoom,{worldview:this.worldview,activeFloors:_.activeFloors}),xe,A))continue;const be={id:H,properties:z.properties,type:z.type,sourceLayerIndex:se,index:Z,geometry:fe?xe.geometry:ht(z,A,M),patterns:{}};F.push(be)}for(const z of F){const{geometry:H,index:Z,sourceLayerIndex:se}=z;this.addFeature(z,H,Z,A,{},_.availableImages,_.brightness),_.featureIndex.insert(p[Z].feature,H,Z,se,this.index)}}isEmpty(){return this.footprints.length===0}uploadPending(){return!1}upload(p){}update(p,_,A,M,F,z,H){}destroy(){}addFeature(p,_,A,M,F,z=[],H){for(const Z of Pa(_,2)){const se=[],fe=[],xe=[],be=new xs(1/0,1/0),Te=new xs(-1/0,-1/0);for(const Ye of Z)if(Ye.length!==0){Ye!==Z[0]&&xe.push(fe.length/2);for(let st=0;st{Gs[0]=pn,Gs[1]=cn,Gs[2]=jn,Gs[3]=1},Ls=_ht();Te>0&&(Te+=Ls),De+=Ls;for(const Gs of be){const pn=[],cn=[];for(const jn of Gs){const Hn=jn.x+Ue.x,Cs=jn.y+Ue.y,Qs=xe.projection.projectTilePoint(Hn,Cs,yt),an=xe.projection.upVector(yt,jn.x,jn.y);let Ln=Te,In=De;if(st){const Vn=Jht(Hn,Cs,Te,De,st,ot,mt,lt);Ln+=Vn.base,In+=Vn.top}Te!==0?ns($t,Qs.x+an[0]*Et*Ln,Qs.y+an[1]*Et*Ln,Qs.z+an[2]*Et*Ln):ns($t,Qs.x,Qs.y,Qs.z),ns(Jt,Qs.x+an[0]*Et*In,Qs.y+an[1]*Et*In,Qs.z+an[2]*Et*In),Xe($t,$t,Ye),Xe(Jt,Jt,Ye),pn.push(new sR($t[0],$t[1],$t[2])),cn.push(new sR(Jt[0],Jt[1],Jt[2]))}Nt.push(pn),as.push(cn)}return[Nt,as]}(N,p,_,A,M,F,z,H,Z,se,fe):z?function(xe,be,Te,De,Ue,Ye,st,ot,mt){const lt=[],yt=[],Nt=[0,0,0,1];for(const as of xe){const Et=[],$t=[];for(const Jt of as){const ns=Jt.x+De.x,Ls=Jt.y+De.y,Gs=Jht(ns,Ls,be,Te,Ye,st,ot,mt);Nt[0]=ns,Nt[1]=Ls,Nt[2]=Gs.base,Nt[3]=1,Ft(Nt,Nt,Ue),Nt[3]=Math.max(Nt[3],1e-5);const pn=new sR(Nt[0]/Nt[3],Nt[1]/Nt[3],Nt[2]/Nt[3]);Nt[0]=ns,Nt[1]=Ls,Nt[2]=Gs.top,Nt[3]=1,Ft(Nt,Nt,Ue),Nt[3]=Math.max(Nt[3],1e-5);const cn=new sR(Nt[0]/Nt[3],Nt[1]/Nt[3],Nt[2]/Nt[3]);Et.push(pn),$t.push(cn)}lt.push(Et),yt.push($t)}return[lt,yt]}(p,_,A,M,F,z,H,Z,se):function(xe,be,Te,De,Ue){const Ye=[],st=[],ot=Ue[8]*be,mt=Ue[9]*be,lt=Ue[10]*be,yt=Ue[11]*be,Nt=Ue[8]*Te,as=Ue[9]*Te,Et=Ue[10]*Te,$t=Ue[11]*Te;for(const Jt of xe){const ns=[],Ls=[];for(const Gs of Jt){const pn=Gs.x+De.x,cn=Gs.y+De.y,jn=Ue[0]*pn+Ue[4]*cn+Ue[12],Hn=Ue[1]*pn+Ue[5]*cn+Ue[13],Cs=Ue[2]*pn+Ue[6]*cn+Ue[14],Qs=Ue[3]*pn+Ue[7]*cn+Ue[15],an=jn+ot,Ln=Hn+mt,In=Cs+lt,Vn=Math.max(Qs+yt,1e-5),Dn=jn+Nt,ir=Hn+as,Bn=Cs+Et,Rr=Math.max(Qs+$t,1e-5);ns.push(new sR(an/Vn,Ln/Vn,In/Vn)),Ls.push(new sR(Dn/Rr,ir/Rr,Bn/Rr))}Ye.push(ns),st.push(Ls)}return[Ye,st]}(p,_,A,M,F)}function Jht(N,p,_,A,M,F,z,H){const Z=z*M.getElevationAt(N,p,!0,!0),se=F[0]!==0,fe=se?F[1]===0?z*(F[0]/7-450):z*function(xe,be,Te){const De=Math.floor(be[0]/8),Ue=Math.floor(be[1]/8),Ye=10*(be[0]-8*De),st=10*(be[1]-8*Ue),ot=xe.getElevationAt(De,Ue,!0,!0),mt=xe.getMeterToDEM(Te),lt=Math.floor(.5*(Ye*mt-1)),yt=Math.floor(.5*(st*mt-1)),Nt=xe.tileCoordToPixel(De,Ue),as=2*lt+1,Et=2*yt+1,$t=function(cn,jn,Hn,Cs,Qs){return[cn.getElevationAtPixel(jn,Hn,!0),cn.getElevationAtPixel(jn+Qs,Hn,!0),cn.getElevationAtPixel(jn,Hn+Qs,!0),cn.getElevationAtPixel(jn+Cs,Hn+Qs,!0)]}(xe,Nt.x-lt,Nt.y-yt,as,Et),Jt=Math.abs($t[0]-$t[1]),ns=Math.abs($t[2]-$t[3]),Ls=Math.abs($t[0]-$t[2])+Math.abs($t[1]-$t[3]),Gs=Math.min(.25,.5*mt*(Jt+ns)/as),pn=Math.min(.25,.5*mt*Ls/Et);return ot+Math.max(Gs*Ye,pn*st)}(M,F,H):Z;return{base:Z+(_===0?-1:_),top:se?Math.max(fe+A,Z+_+2):Z+A}}function tZ(N,p,_){return p*(Fr/(N.tileSize*Math.pow(2,_-N.tileID.overscaledZ)))}function emt(N,p){return 1/tZ(N,1,p.tileZoom)}function tmt(N,p,_,A){return N.translatePosMatrix(A||p.tileID.projMatrix,p,_.paint.get("line-translate"),_.paint.get("line-translate-anchor"))}oa(Yht,"ClipBucket",{omit:["layers"]});const smt=N=>{const p=[];nmt(N)&&p.push("RENDER_LINE_DASH"),N.paint.get("line-gradient")&&p.push("RENDER_LINE_GRADIENT"),N.paint.get("line-blend-mode")==="multiply"&&p.push("LINE_BLEND_MULTIPLY"),N.paint.get("line-blend-mode")==="additive"&&p.push("LINE_BLEND_ADDITIVE");const _=N.paint.get("line-trim-offset");_[0]===0&&_[1]===0||p.push("RENDER_LINE_TRIM_OFFSET");const A=N.paint.get("line-border-width").constantOr(1)!==0;A&&p.push("RENDER_LINE_BORDER"),A&&N.paint.get("line-border-gradient")&&p.push("RENDER_LINE_BORDER_GRADIENT");const M=N.layout.get("line-join").constantOr("miter")==="none",F=!!N.paint.get("line-pattern").constantOr(1);return M&&F&&p.push("LINE_JOIN_NONE"),p};function nmt(N){const p=N.paint.get("line-dasharray").value;return p.kind!=="constant"||p.value}let u8e;const rmt=()=>u8e||(u8e={layout:Wht||(Wht=new Ku({"line-cap":new Tr(Zs.layout_line["line-cap"]),"line-join":new Tr(Zs.layout_line["line-join"]),"line-miter-limit":new xr(Zs.layout_line["line-miter-limit"]),"line-round-limit":new xr(Zs.layout_line["line-round-limit"]),"line-sort-key":new Tr(Zs.layout_line["line-sort-key"]),"line-z-offset":new Tr(Zs.layout_line["line-z-offset"]),"line-elevation-reference":new xr(Zs.layout_line["line-elevation-reference"]),"line-cross-slope":new xr(Zs.layout_line["line-cross-slope"]),visibility:new xr(Zs.layout_line.visibility),"line-width-unit":new xr(Zs.layout_line["line-width-unit"]),"line-elevation-ground-scale":new Tr(Zs.layout_line["line-elevation-ground-scale"])})),paint:Kht||(Kht=new Ku({"line-opacity":new Tr(Zs.paint_line["line-opacity"]),"line-color":new Tr(Zs.paint_line["line-color"]),"line-translate":new xr(Zs.paint_line["line-translate"]),"line-translate-anchor":new xr(Zs.paint_line["line-translate-anchor"]),"line-width":new Tr(Zs.paint_line["line-width"]),"line-gap-width":new Tr(Zs.paint_line["line-gap-width"]),"line-offset":new Tr(Zs.paint_line["line-offset"]),"line-blur":new Tr(Zs.paint_line["line-blur"]),"line-dasharray":new Tr(Zs.paint_line["line-dasharray"]),"line-pattern":new Tr(Zs.paint_line["line-pattern"]),"line-pattern-cross-fade":new xr(Zs.paint_line["line-pattern-cross-fade"]),"line-gradient":new R3(Zs.paint_line["line-gradient"]),"line-trim-offset":new xr(Zs.paint_line["line-trim-offset"]),"line-trim-fade-range":new xr(Zs.paint_line["line-trim-fade-range"]),"line-trim-color":new xr(Zs.paint_line["line-trim-color"]),"line-emissive-strength":new Tr(Zs.paint_line["line-emissive-strength"]),"line-border-width":new Tr(Zs.paint_line["line-border-width"]),"line-border-color":new Tr(Zs.paint_line["line-border-color"]),"line-border-gradient":new R3(Zs.paint_line["line-border-gradient"]),"line-occlusion-opacity":new xr(Zs.paint_line["line-occlusion-opacity"]),"line-blend-mode":new xr(Zs.paint_line["line-blend-mode"]),"line-blend-additive-clamp":new xr(Zs.paint_line["line-blend-additive-clamp"]),"line-cutout-depth":new xr(Zs.paint_line["line-cutout-depth"]),"line-color-use-theme":new Tr({type:"string",default:"default","property-type":"data-driven"}),"line-gradient-use-theme":new Tr({type:"string",default:"default","property-type":"data-driven"}),"line-trim-color-use-theme":new Tr({type:"string",default:"default","property-type":"data-driven"}),"line-border-color-use-theme":new Tr({type:"string",default:"default","property-type":"data-driven"}),"line-border-gradient-use-theme":new Tr({type:"string",default:"default","property-type":"data-driven"})}))},u8e);class Zfs extends Tr{possiblyEvaluate(p,_){return _=new Kn(Math.floor(_.zoom),{now:_.now,fadeDuration:_.fadeDuration,transition:_.transition,worldview:_.worldview}),super.possiblyEvaluate(p,_)}evaluate(p,_,A,M){return _={..._,zoom:Math.floor(_.zoom)},super.evaluate(p,_,A,M)}}let sZ,amt,imt,h8e;function omt(N,p){return p>0?p+2*N:N}function lmt(N,p){return p.replace(/{([^{}]+)}/g,(_,A)=>A in N?String(N[A]):"")}class cmt{constructor(p){this.type=p.property.overrides?p.property.overrides.runtimeType:xu,this.defaultValue=p}evaluate(p){if(p.formattedSection){const _=this.defaultValue.property.overrides;if(_&&_.hasOverride(p.formattedSection))return _.getOverride(p.formattedSection)}return p.feature&&p.featureState?this.defaultValue.evaluate(p.feature,p.featureState):this.defaultValue.property.specification.default}eachChild(p){this.defaultValue.isConstant()||p(this.defaultValue.value._styleExpression.expression)}outputDefined(){return!1}serialize(){return null}}oa(cmt,"FormatSectionOverride",{omit:["defaultValue"]});const Xfs={};function dmt(N){return N.value.kind!=="constant"&&N.value.isStateDependent}const m8e=()=>h8e||(h8e={layout:amt||(amt=new Ku({"symbol-placement":new xr(Zs.layout_symbol["symbol-placement"]),"symbol-spacing":new xr(Zs.layout_symbol["symbol-spacing"]),"symbol-avoid-edges":new xr(Zs.layout_symbol["symbol-avoid-edges"]),"symbol-sort-key":new Tr(Zs.layout_symbol["symbol-sort-key"]),"symbol-z-order":new xr(Zs.layout_symbol["symbol-z-order"]),"symbol-z-elevate":new xr(Zs.layout_symbol["symbol-z-elevate"]),"symbol-elevation-reference":new xr(Zs.layout_symbol["symbol-elevation-reference"]),"icon-allow-overlap":new xr(Zs.layout_symbol["icon-allow-overlap"]),"icon-ignore-placement":new xr(Zs.layout_symbol["icon-ignore-placement"]),"icon-optional":new xr(Zs.layout_symbol["icon-optional"]),"icon-rotation-alignment":new xr(Zs.layout_symbol["icon-rotation-alignment"]),"icon-size":new Tr(Zs.layout_symbol["icon-size"]),"icon-size-scale-range":new xr(Zs.layout_symbol["icon-size-scale-range"]),"icon-text-fit":new Tr(Zs.layout_symbol["icon-text-fit"]),"icon-text-fit-padding":new Tr(Zs.layout_symbol["icon-text-fit-padding"]),"icon-image":new Tr(Zs.layout_symbol["icon-image"]),"icon-image-use-theme":new xr({type:"string",default:"default","property-type":"data-constant"}),"icon-rotate":new Tr(Zs.layout_symbol["icon-rotate"]),"icon-padding":new xr(Zs.layout_symbol["icon-padding"]),"icon-keep-upright":new xr(Zs.layout_symbol["icon-keep-upright"]),"icon-offset":new Tr(Zs.layout_symbol["icon-offset"]),"icon-anchor":new Tr(Zs.layout_symbol["icon-anchor"]),"icon-pitch-alignment":new xr(Zs.layout_symbol["icon-pitch-alignment"]),"text-pitch-alignment":new xr(Zs.layout_symbol["text-pitch-alignment"]),"text-rotation-alignment":new xr(Zs.layout_symbol["text-rotation-alignment"]),"text-field":new Tr(Zs.layout_symbol["text-field"]),"text-font":new Tr(Zs.layout_symbol["text-font"]),"text-size":new Tr(Zs.layout_symbol["text-size"]),"text-size-scale-range":new xr(Zs.layout_symbol["text-size-scale-range"]),"text-max-width":new Tr(Zs.layout_symbol["text-max-width"]),"text-line-height":new Tr(Zs.layout_symbol["text-line-height"]),"text-letter-spacing":new Tr(Zs.layout_symbol["text-letter-spacing"]),"text-justify":new Tr(Zs.layout_symbol["text-justify"]),"text-radial-offset":new Tr(Zs.layout_symbol["text-radial-offset"]),"text-variable-anchor":new xr(Zs.layout_symbol["text-variable-anchor"]),"text-anchor":new Tr(Zs.layout_symbol["text-anchor"]),"text-max-angle":new xr(Zs.layout_symbol["text-max-angle"]),"text-writing-mode":new xr(Zs.layout_symbol["text-writing-mode"]),"text-rotate":new Tr(Zs.layout_symbol["text-rotate"]),"text-padding":new xr(Zs.layout_symbol["text-padding"]),"text-keep-upright":new xr(Zs.layout_symbol["text-keep-upright"]),"text-transform":new Tr(Zs.layout_symbol["text-transform"]),"text-offset":new Tr(Zs.layout_symbol["text-offset"]),"text-allow-overlap":new xr(Zs.layout_symbol["text-allow-overlap"]),"text-ignore-placement":new xr(Zs.layout_symbol["text-ignore-placement"]),"text-optional":new xr(Zs.layout_symbol["text-optional"]),visibility:new xr(Zs.layout_symbol.visibility)})),paint:imt||(imt=new Ku({"icon-opacity":new Tr(Zs.paint_symbol["icon-opacity"]),"icon-occlusion-opacity":new Tr(Zs.paint_symbol["icon-occlusion-opacity"]),"icon-emissive-strength":new Tr(Zs.paint_symbol["icon-emissive-strength"]),"text-emissive-strength":new Tr(Zs.paint_symbol["text-emissive-strength"]),"icon-color":new Tr(Zs.paint_symbol["icon-color"]),"icon-halo-color":new Tr(Zs.paint_symbol["icon-halo-color"]),"icon-halo-width":new Tr(Zs.paint_symbol["icon-halo-width"]),"icon-halo-blur":new Tr(Zs.paint_symbol["icon-halo-blur"]),"icon-translate":new xr(Zs.paint_symbol["icon-translate"]),"icon-translate-anchor":new xr(Zs.paint_symbol["icon-translate-anchor"]),"icon-image-cross-fade":new xr(Zs.paint_symbol["icon-image-cross-fade"]),"text-opacity":new Tr(Zs.paint_symbol["text-opacity"]),"text-occlusion-opacity":new Tr(Zs.paint_symbol["text-occlusion-opacity"]),"text-color":new Tr(Zs.paint_symbol["text-color"],{runtimeType:ed,getOverride:N=>N.textColor,hasOverride:N=>!!N.textColor}),"text-halo-color":new Tr(Zs.paint_symbol["text-halo-color"]),"text-halo-width":new Tr(Zs.paint_symbol["text-halo-width"]),"text-halo-blur":new Tr(Zs.paint_symbol["text-halo-blur"]),"text-translate":new xr(Zs.paint_symbol["text-translate"]),"text-translate-anchor":new xr(Zs.paint_symbol["text-translate-anchor"]),"icon-color-saturation":new xr(Zs.paint_symbol["icon-color-saturation"]),"icon-color-contrast":new xr(Zs.paint_symbol["icon-color-contrast"]),"icon-color-brightness-min":new xr(Zs.paint_symbol["icon-color-brightness-min"]),"icon-color-brightness-max":new xr(Zs.paint_symbol["icon-color-brightness-max"]),"symbol-z-offset":new Tr(Zs.paint_symbol["symbol-z-offset"]),"placement-priority":new Tr(Zs.paint_symbol["placement-priority"]),"placement-group":new Tr(Zs.paint_symbol["placement-group"]),"icon-color-use-theme":new Tr({type:"string",default:"default","property-type":"data-driven"}),"icon-halo-color-use-theme":new Tr({type:"string",default:"default","property-type":"data-driven"}),"text-color-use-theme":new Tr({type:"string",default:"default","property-type":"data-driven"}),"text-halo-color-use-theme":new Tr({type:"string",default:"default","property-type":"data-driven"})}))},h8e);class Ple extends e0{constructor(p,_,A,M){super(p,m8e(),_,A,M,p.layout?p.layout["icon-image-use-theme"]:null),this._colorAdjustmentMatrix=w([]),this.hasOcclusionOpacityProperties=p.paint!==void 0&&("icon-occlusion-opacity"in p.paint||"text-occlusion-opacity"in p.paint)}_handleSpecialPaintPropertyUpdate(p){p!=="icon-occlusion-opacity"&&p!=="text-occlusion-opacity"||(this.hasOcclusionOpacityProperties=!0)}recalculate(p,_){super.recalculate(p,_),this.appearances&&this.appearances.forEach(M=>{M.recalculate(p,_,this.iconImageUseTheme)}),this.appearances.length!==0&&delete this.layout._values["text-variable-anchor"],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 A=this.layout.get("text-writing-mode");if(A){const M=[];for(const F of A)M.includes(F)||M.push(F);this.layout._values["text-writing-mode"]=M}else this.layout._values["text-writing-mode"]=this.layout.get("symbol-placement")==="point"?["horizontal"]:["horizontal","vertical"];this._setPaintOverrides()}getColorAdjustmentMatrix(p,_,A,M){return this._saturation===p&&this._contrast===_&&this._brightnessMin===A&&this._brightnessMax===M||(this._colorAdjustmentMatrix=function(F,z,H,Z){F=dm(F),z=qi(z);const se=y(),fe=F/3,xe=1-2*fe,be=[xe,fe,fe,0,fe,xe,fe,0,fe,fe,xe,0,0,0,0,1],Te=.5-.5*z,De=Z-H;return E(se,[De,0,0,0,0,De,0,0,0,0,De,0,H,H,H,1],[z,0,0,0,0,z,0,0,0,0,z,0,Te,Te,Te,1]),E(se,se,be),se}(p,_,A,M),this._saturation=p,this._contrast=_,this._brightnessMin=A,this._brightnessMax=M),this._colorAdjustmentMatrix}getValueAndResolveTokens(p,_,A,M){const F=this.layout.get(p).evaluate(_,{},A,M),z=this._unevaluatedLayout._values[p];return z.isDataDriven()||Vv(z.value)||!F?F:lmt(_.properties,F)}getAppearanceValueAndResolveTokens(p,_,A,M,F){const z=p.getLayoutProperty(_);if(!z)return;const H=z.evaluate(A,{},M,F),Z=p.getUnevaluatedLayoutProperties()._values[_];return Z.isDataDriven()||Vv(Z.value)||!H||typeof H!="string"?H:lmt(A.properties,H)}createBucket(p){return new rle(p)}placeSymbols(p,_,A,M,F){const{globalPlacement:z,idRangeAllocator:H,transform:Z,buildingIndex:se,fogState:fe,groupOrders:xe,replacementSource:be}=p,Te=this.runtimeLayerUID,De=dmt(this.paint.get("placement-group"))||dmt(this.paint.get("placement-priority"))?M._state.getState(this.sourceLayer||"_geojsonTileLayer"):Xfs;for(const Ue of _){const Ye=Ue.getBucket(this);if(!Ye||this.fqid!==Ye.layerIds[0])continue;Ye.elevationType==="offset"&&se?se.updateZOffset(Ye,Ue.tileID):Ye.elevationType==="road"&&Ye.hdExt&&Ye.hdExt.updateRoadElevation(Ye,Ue.tileID.canonical),Ye.updateZOffset(),z.startSymbolSourceProcessing(Ye);const st=tut(Ue.tileID,Ye.getProjection(),Z,Z.projection.name);Ye.addToPlacement(z,H,Te,st,Z,Ue.tileSize/Fr,Ue,fe,xe,A,De,F?be:null),z.finishSourceProcessing()}}queryRadius(){return 0}queryIntersectsFeature(){return!1}_setPaintOverrides(){for(const p of m8e().paint.overridableProperties){if(!Ple.hasPaintOverride(this.layout,p))continue;const _=this.paint.get(p),A=new cmt(_),M=new qv(A,_.property.specification,this.scope,this.options,this.layout.get("icon-image-use-theme"));let F=null;F=_.value.kind==="constant"||_.value.kind==="source"?new G_("source",M):new cg("composite",M,_.value.zoomStops,_.value.interpolationType),this.paint._values[p]=new _h(_.property,F,_.parameters)}}_handleOverridablePaintPropertyUpdate(p,_,A){return!(!this.layout||_.isDataDriven()||A.isDataDriven())&&Ple.hasPaintOverride(this.layout,p)}static hasPaintOverride(p,_){const A=p.get("text-field"),M=m8e().paint.properties[_];let F=!1;const z=H=>{for(const Z of H)if(M.overrides&&M.overrides.hasOverride(Z))return void(F=!0)};if(A.value.kind==="constant"&&A.value.value instanceof vu)z(A.value.value.sections);else if(A.value.kind==="source"){const H=se=>{F||(se instanceof Qg&&ch(se.value)===yh?z(se.value.sections):se instanceof F1?z(se.sections):se.eachChild(H))},Z=A.value;Z._styleExpression&&H(Z._styleExpression.expression)}return F}getProgramIds(){return["symbol"]}getDefaultProgramParams(p,_,A){return{config:new tR(this,{zoom:_,lut:A}),overrideFog:!1}}hasElevation(){return this.layout&&this.layout.get("symbol-elevation-reference")==="hd-road-markup"}mayUse(p){return p==="HD"&&R9(this,"symbol-elevation-reference",_=>_==="hd-road-markup")}prepare(){return this.mayUse("HD")?Tle():Promise.resolve()}}let umt,hmt,mmt,fmt;const f8e=1024,Qfs=(Math.pow(f8e,2)-1)/268170240;class pmt extends e0{constructor(p,_,A,M){super(p,{layout:mmt||(mmt=new Ku({visibility:new xr(Zs.layout_raster.visibility)})),paint:fmt||(fmt=new Ku({"raster-opacity":new xr(Zs.paint_raster["raster-opacity"]),"raster-color":new R3(Zs.paint_raster["raster-color"]),"raster-color-mix":new xr(Zs.paint_raster["raster-color-mix"]),"raster-color-range":new xr(Zs.paint_raster["raster-color-range"]),"raster-color-scale":new xr(Zs.paint_raster["raster-color-scale"]),"raster-hue-rotate":new xr(Zs.paint_raster["raster-hue-rotate"]),"raster-brightness-min":new xr(Zs.paint_raster["raster-brightness-min"]),"raster-brightness-max":new xr(Zs.paint_raster["raster-brightness-max"]),"raster-saturation":new xr(Zs.paint_raster["raster-saturation"]),"raster-contrast":new xr(Zs.paint_raster["raster-contrast"]),"raster-resampling":new xr(Zs.paint_raster["raster-resampling"]),"raster-fade-duration":new xr(Zs.paint_raster["raster-fade-duration"]),"raster-emissive-strength":new xr(Zs.paint_raster["raster-emissive-strength"]),"raster-array-band":new xr(Zs.paint_raster["raster-array-band"]),"raster-elevation":new xr(Zs.paint_raster["raster-elevation"]),"raster-elevation-reference":new xr(Zs.paint_raster["raster-elevation-reference"]),"raster-color-use-theme":new Tr({type:"string",default:"default","property-type":"data-driven"})}))},_,A,M),this.updateColorRamp(),this._curRampRange=[NaN,NaN]}getProgramIds(){return["raster"]}hasColorMap(){return!!this._transitionablePaint._values["raster-color"].value.value}tileCoverLift(){return this.paint.get("raster-elevation")}isDraped(p){const _=p?p._source:null;return(!_||_.type!=="image"&&_.type!=="video"&&_.type!=="canvas"||!_.onNorthPole&&!_.onSouthPole)&&this.paint.get("raster-elevation")===0}_handleSpecialPaintPropertyUpdate(p){p!=="raster-color"&&p!=="raster-color-range"&&p!=="raster-color-scale"||(this._curRampRange=[NaN,NaN],this.updateColorRamp())}_clear(){this.colorRampTexture&&(this.colorRampTexture.destroy(),this.colorRampTexture=null)}updateColorRamp(p){if(!this.hasColorMap()||!this._curRampRange)return;const _=this._transitionablePaint._values["raster-color"].value.expression,[A,M]=p||this._transitionablePaint._values["raster-color-range"].value.expression.evaluate({zoom:0})||[NaN,NaN];if(isNaN(A)&&isNaN(M)||A===this._curRampRange[0]&&M===this._curRampRange[1])return;const F=this._transitionablePaint._values["raster-color-scale"].value.expression.evaluate({zoom:0});this.colorRamp=JY({expression:_,evaluationKey:"rasterValue",image:this.colorRamp,clips:[{start:A,end:M}],resolution:f8e,scale:F}),this.colorRampTexture=null,this._curRampRange=[A,M]}is3D(p){return this.paint.get("raster-elevation")>0}}let gmt,xmt,ymt,vmt,bmt,_mt,wmt,jmt;class Nmt extends e0{constructor(p,_,A,M){super(p,{layout:gmt||(gmt=new Ku({visibility:new xr(Zs["layout_raster-particle"].visibility)})),paint:xmt||(xmt=new Ku({"raster-particle-array-band":new xr(Zs["paint_raster-particle"]["raster-particle-array-band"]),"raster-particle-count":new xr(Zs["paint_raster-particle"]["raster-particle-count"]),"raster-particle-color":new R3(Zs["paint_raster-particle"]["raster-particle-color"]),"raster-particle-max-speed":new xr(Zs["paint_raster-particle"]["raster-particle-max-speed"]),"raster-particle-speed-factor":new xr(Zs["paint_raster-particle"]["raster-particle-speed-factor"]),"raster-particle-fade-opacity-factor":new xr(Zs["paint_raster-particle"]["raster-particle-fade-opacity-factor"]),"raster-particle-reset-rate-factor":new xr(Zs["paint_raster-particle"]["raster-particle-reset-rate-factor"]),"raster-particle-elevation":new xr(Zs["paint_raster-particle"]["raster-particle-elevation"]),"raster-particle-color-use-theme":new Tr({type:"string",default:"default","property-type":"data-driven"})}))},_,A,M),this._updateColorRamp(),this.lastInvalidatedAt=oh.now()}mayUse(p){return p==="HD"}_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(p){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(p){return!1}_handleSpecialPaintPropertyUpdate(p){p!=="raster-particle-color"&&p!=="raster-particle-max-speed"||(this._updateColorRamp(),this._invalidateAnimationState()),p==="raster-particle-count"&&this._invalidateAnimationState()}_updateColorRamp(){if(!this.hasColorMap())return;const p=this._transitionablePaint._values["raster-particle-color"].value.expression,_=this._transitionablePaint._values["raster-particle-max-speed"].value.expression.evaluate({zoom:0});this.colorRamp=JY({expression:p,evaluationKey:"rasterParticleSpeed",image:this.colorRamp,clips:[{start:0,end:_}],resolution:256}),this.colorRampTexture=null}_invalidateAnimationState(){this.lastInvalidatedAt=oh.now()}tileCoverLift(){return this.paint.get("raster-particle-elevation")}}class Jfs extends e0{constructor(p,_){super(p,{},_,null),this.implementation=p,p.slot&&(this.slot=p.slot)}is3D(p){return this.implementation.renderingMode==="3d"}hasOffscreenPass(){return this.implementation.prerender!==void 0}isDraped(p){return this.implementation.renderToTile!==void 0}shouldRedrape(){return!!this.implementation.shouldRerenderTiles&&this.implementation.shouldRerenderTiles()}recalculate(){}updateTransitions(){}hasTransition(){return!1}serialize(){}onAdd(p){this.implementation.onAdd&&this.implementation.onAdd(p,p.painter.context.gl)}onRemove(p){this.implementation.onRemove&&this.implementation.onRemove(p,p.painter.context.gl)}}function p8e(N,p,_){const A=[0,0,1],M=St([]);return gs(M,M,_?-Xr(N)+Math.PI:Xr(N)),vt(M,M,-Xr(p)),at(A,A,M),qe(A,A)}class kmt{constructor(p,_){this.feature=p,this.instancedDataOffset=_,this.instancedDataCount=0,this.rotation=[0,0,0],this.scale=[1,1,1],this.translation=[0,0,0]}}class Smt{constructor(){this.maxScale=1,this.maxXYTranslationDistance=0,this.instancedDataArray=new wh,this.instancesEvaluatedElevation=[],this.features=[],this.idToFeaturesIndex={}}colorForInstance(p){const _=16*p,A=this.instancedDataArray.float32;let M=Math.floor(A[_+2]);const F=1.05*(A[_+2]-M);return M/=100,[A[_]%1*1.05,A[_+1]%1*1.05,F,M]}tileCoordinatesForInstance(p){const _=16*p,A=this.instancedDataArray.float32;let M=A[_+0];return M=M>Fr?M-Fr:M,new xs(Math.trunc(M),Math.trunc(A[_+1]))}translationForInstance(p){const _=16*p,A=this.instancedDataArray.float32;return[A[_+4],A[_+5],A[_+6]]}rotationScaleForInstance(p){const _=16*p,A=this.instancedDataArray.float32;return[A[_+7],A[_+8],A[_+9],A[_+10],A[_+11],A[_+12],A[_+13],A[_+14],A[_+15]]}transformForInstance(p){const _=16*p,A=this.instancedDataArray.float32;return[A[_+7],A[_+8],A[_+9],A[_+4],A[_+10],A[_+11],A[_+12],A[_+5],A[_+13],A[_+14],A[_+15],A[_+6],0,0,0,1]}}class g8e{constructor(p){this.requiresStandardRuntime=!0,this.zoom=p.zoom,this.canonical=p.canonical,this.overscaledZ=this.canonical.z+Math.log2(p.overscaling),this.layers=p.layers,this.layerIds=this.layers.map(_=>_.fqid),this.projection=p.projection,this.index=p.index,this.worldview=p.worldview,this.hasZoomDependentProperties=this.layers[0].isZoomDependent(),this.stateDependentLayerIds=this.layers.filter(_=>_.isStateDependent()).map(_=>_.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=p.styleDefinedModelURLs,this.hasAppearances=null}updateFootprints(p,_){}updateAppearances(p,_,A,M){return{hasLayoutChanges:!1,hasUboChanges:!1}}populate(p,_,A,M){this.tileToMeter=K(A);const F=this.layers[0]._featureFilter.needGeometry;this.lookup=new Uint8Array(this.lookupDim*this.lookupDim);const z=this.layers[0].paint.get("model-elevation-reference")==="hd-road-markup"?_.elevationFeatures:void 0;for(const{feature:H,id:Z,index:se,sourceLayerIndex:fe}of p){const xe=Z??(H.properties&&Object.hasOwn(H.properties,"id")?H.properties.id:void 0),be=_t(H,F);if(!this.layers[0]._featureFilter.filter(new Kn(this.zoom,{worldview:this.worldview,activeFloors:_.activeFloors}),be,A))continue;const Te={id:xe,sourceLayerIndex:fe,index:se,geometry:F?be.geometry:ht(H,A,M),properties:H.properties,type:H.type,patterns:{}},De=this.addFeature(Te,Te.geometry,be,z,A);De&&_.featureIndex.insert(H,Te.geometry,se,fe,this.index,this.instancesPerModel[De].instancedDataArray.length,256)}this.lookup=null}evaluateQueryRenderedFeaturePadding(){const p=this.layers[0].modelManager,_=this.layers[0].scope;let A=0;for(const M of this.modelUris){const F=p.getModel(M,_);if(!F)continue;const z=this.instancesPerModel[M];if(z){const H=.5*Ve(F.aabb.max,F.aabb.min)*z.maxScale+z.maxXYTranslationDistance,Z=Math.min(Fr,Math.max(H/this.tileToMeter,256));A=Math.max(Z,A)}}return A}update(p,_,A,M){for(const F in this.instancesPerModel){const z=this.instancesPerModel[F];for(const H in p)Object.hasOwn(z.idToFeaturesIndex,H)&&(this.evaluate(z.features[z.idToFeaturesIndex[H]],p[H],z,!0),this.uploaded=!1)}this.maxHeight=0}updateZoomBasedPaintProperties(){if(!this.hasZoomDependentProperties)return!1;let p=!1;for(const _ in this.instancesPerModel){const A=this.instancesPerModel[_];for(const M of A.features){const F=this.layers[0],z=M.feature,H=this.canonical,Z=F.paint.get("model-rotation").evaluate(z,{},H),se=F.paint.get("model-scale").evaluate(z,{},H),fe=F.paint.get("model-translation").evaluate(z,{},H);nt(M.rotation,Z)&&nt(M.scale,se)&&nt(M.translation,fe)||(this.evaluate(M,M.featureStates,A,!0),p=!0)}}return p}updateReplacement(p,_,A,M){if(_.updateTime===this.replacementUpdateTime)return!1;this.replacementUpdateTime=_.updateTime;const F=_.getReplacementRegionsForTile(p.toUnwrapped(),!0);if(Goe(this.activeReplacements,F))return!1;this.activeReplacements=F;let z=!1;for(const H in this.instancesPerModel){const Z=this.instancesPerModel[H],se=Z.instancedDataArray;for(const fe of Z.features){const xe=fe.instancedDataOffset,be=fe.instancedDataCount;for(let Te=0;TeFr;Ue=Ye?Ue-Fr:Ue;const st=Math.floor(Ue),ot=Math.floor(se.float32[De+1]);let mt=!1;for(const lt of this.activeReplacements)if(!yOe(lt,A,FY.Model,M)&&!(lt.min.x>st||st>lt.max.x||lt.min.y>ot||ot>lt.max.y)&&(mt=Woe(_Oe(st,ot,p.canonical,lt.footprintTileId.canonical),lt.footprint),mt))break;se.float32[De]=mt?Ue+Fr:Ue,z=z||mt!==Ye}}}return z}isEmpty(){for(const p in this.instancesPerModel)if(this.instancesPerModel[p].instancedDataArray.length!==0)return!1;return!0}uploadPending(){return!this.uploaded}upload(p){if(!this.uploaded)for(const _ in this.instancesPerModel){const A=this.instancesPerModel[_];A.instancedDataArray.length<0||A.instancedDataArray.length===0||(A.instancedDataBuffer?A.instancedDataBuffer.updateData(A.instancedDataArray):A.instancedDataBuffer=p.createVertexBuffer(A.instancedDataArray,nfs.members,!0,void 0,this.instanceCount))}this.uploaded=!0}destroy(p){for(const A in this.instancesPerModel){const M=this.instancesPerModel[A];M.instancedDataArray.length!==0&&M.instancedDataBuffer&&M.instancedDataBuffer.destroy()}const _=this.layers[0].modelManager;if(p&&_&&this.modelUris&&this.modelsRequested)for(const A of this.modelUris)_.removeModel(A,"",!0)}addFeature(p,_,A,M,F){const z=this.layers[0],H=z.layout.get("model-id"),Z=z.layout.get("model-allow-density-reduction"),se=H.evaluate(A,{},this.canonical);if(!se)return Yo(`modelId is not evaluated for layer ${z.id} and it is not going to get rendered.`),se;!se.includes("://")&&!this.styleDefinedModelURLs[se]||this.modelUris.includes(se)||this.modelUris.push(se),this.instancesPerModel[se]||(this.instancesPerModel[se]=new Smt);const fe=this.instancesPerModel[se],xe=fe.instancedDataArray,be=new kmt(A,xe.length);let Te;if(M){const De=HY(p,M,void 0,F);Te=De?De.feature:void 0}for(const De of _)for(const Ue of De){if(Ue.x<0||Ue.x>=Fr||Ue.y<0||Ue.y>=Fr)continue;if(this.lookupDim!==0&&Z){const st=(this.lookupDim-1)/Fr,ot=this.lookupDim*(Ue.y*st|0)+Ue.x*st|0;if(this.lookup){if(this.lookup[ot]!==0)continue;this.lookup[ot]=1}}this.instanceCount++;const Ye=xe.length;if(xe.resize(Ye+1),M){fe.instancesRoadElevation||(fe.instancesRoadElevation=[]);const st=Te?Te.pointElevation(new xs(Ue.x,Ue.y)):0;fe.instancesRoadElevation.push(st)}fe.instancesEvaluatedElevation.push(0),xe.float32[16*Ye]=Ue.x,xe.float32[16*Ye+1]=Ue.y}return be.instancedDataCount=fe.instancedDataArray.length-be.instancedDataOffset,be.instancedDataCount>0&&(p.id&&(fe.idToFeaturesIndex[p.id]=fe.features.length),fe.features.push(be),this.evaluate(be,{},fe,!1)),se}getModelUris(){return this.modelUris}evaluate(p,_,A,M){const F=this.layers[0],z=p.feature,H=this.canonical,Z=p.rotation=F.paint.get("model-rotation").evaluate(z,_,H),se=p.scale=F.paint.get("model-scale").evaluate(z,_,H),fe=p.translation=F.paint.get("model-translation").evaluate(z,_,H),{r:xe,g:be,b:Te}=F.paint.get("model-color").evaluate(z,_,H),De=F.paint.get("model-color-mix-intensity").evaluate(z,_,H),Ue=[];this.maxVerticalOffset0?Math.sqrt(Ye):0;A.maxScale=Math.max(Math.max(A.maxScale,se[0]),Math.max(se[1],se[2])),A.maxXYTranslationDistance=Math.max(A.maxXYTranslationDistance,st),this.maxScale=Math.max(Math.max(this.maxScale,se[0]),Math.max(se[1],se[2])),tht(Ue,Z,se);const ot=Math.round(100*De)+Te/1.05;for(let mt=0;mt10?this.tileToMeter:K(H,Et)),Nt[yt+4]=fe[0],Nt[yt+5]=fe[1],Nt[yt+6]=fe[2]+(A.instancesRoadElevation?A.instancesRoadElevation[lt]:0)+as,Nt[yt+7]=Ue[0],Nt[yt+8]=Ue[1],Nt[yt+9]=Ue[2],Nt[yt+10]=Ue[4],Nt[yt+11]=Ue[5],Nt[yt+12]=Ue[6],Nt[yt+13]=Ue[8],Nt[yt+14]=Ue[9],Nt[yt+15]=Ue[10],A.instancesEvaluatedElevation[lt]=fe[2]}}}oa(g8e,"ModelBucket",{omit:["layers"]}),oa(Smt,"PerModelAttributes"),oa(kmt,"ModelFeature");const Cmt=new WeakMap;class eps{constructor(p,_){const A=p.gl;if(this.context=p,this.buffer=A.createBuffer(),!this.buffer)throw new Error("Failed to create model part style UBO buffer");A.bindBuffer(A.UNIFORM_BUFFER,this.buffer),A.bufferData(A.UNIFORM_BUFFER,_,A.DYNAMIC_DRAW),A.bindBuffer(A.UNIFORM_BUFFER,null)}update(p){const _=this.context.gl;_.bindBuffer(_.UNIFORM_BUFFER,this.buffer),_.bufferSubData(_.UNIFORM_BUFFER,0,p),_.bindBuffer(_.UNIFORM_BUFFER,null)}bind(p,_){let A=Cmt.get(_);if(A===void 0){const F=p.gl,z=F.getUniformBlockIndex(_,"ModelPartStyleUniform");A=z!==F.INVALID_INDEX,A&&F.uniformBlockBinding(_,z,0),Cmt.set(_,A)}if(!A)return;const M=p.gl;M.bindBufferBase(M.UNIFORM_BUFFER,0,this.buffer)}destroy(){this.buffer&&(this.context.gl.deleteBuffer(this.buffer),this.buffer=null)}}const x8e=new Float32Array(262144),lR=new Uint8Array(262144),Ile=[0,0,0],Lle=[0,0,0];function Amt(N){let p=0;if(N.meshes)for(const _ of N.meshes)p=Math.max(p,_.aabb.max[2]);if(N.children)for(const _ of N.children)p=Math.max(p,Amt(_));return p}function Emt(N,p,_){if(N.meshes)for(const A of N.meshes){if(A.aabb.min[0]===1/0)continue;const M=uu.applyTransform(A.aabb,N.globalMatrix);_.insert(p,M.min[0],M.min[1],M.max[0],M.max[1])}if(N.children)for(const A of N.children)Emt(A,p,_)}class Tmt{constructor(p){this.node=p,this.evaluatedRMEA=[[1,0,0,1],[1,0,0,1],[1,0,0,1],[1,0,0,1],[.4,1,0,1],[1,0,0,1],[1,0,0,1]],this.hiddenByReplacement=!1,this.evaluatedTranslation=[0,0,0],this.evaluatedScale=[1,1,1],this.evaluatedColor=[],this.emissionHeightBasedParams=[],this.partStyle=new Float32Array(112),this.partStyleUBO=null,this.needsPartStyleUBO=!1,this.cameraCollisionOpacity=1,this.targetLod=-1,this.feature={type:"Point",id:p.id,geometry:[],properties:{height:Amt(p)}},this.aabb=this._getLocalBounds(),this.state=null}_getLocalBounds(){if(!this.node.meshes)return new uu([1/0,1/0,1/0],[-1/0,-1/0,-1/0]);if(!this.aabb){let p=0;const _=new uu([1/0,1/0,1/0],[-1/0,-1/0,-1/0]);for(const A of this.node.meshes)this.node.lightMeshIndex!==p&&(A.transformedAabb=uu.applyTransformFast(A.aabb,this.node.globalMatrix),_.encapsulate(A.transformedAabb)),p++;this.aabb=_}return this.aabb}}class Mmt{constructor(p,_,A,M,F,z,H,Z){this.requiresStandardRuntime=!0,this.isTiled3dModelBucket=!0,this.id=A,this.layers=p,this.layerIds=this.layers.map(se=>se.fqid),this.stateDependentLayerIds=this.layers.filter(se=>se.isStateDependent()).map(se=>se.id),this.modelTraits|=1,this.uploaded=!1,this.hasPattern=!1,M&&(this.modelTraits|=4),F&&(this.modelTraits|=8),this.zoom=-1,this.terrainExaggeration=1,this.projection={name:"mercator"},this.replacementUpdateTime=0,this.elevationReadFromZ=255,this.brightness=z,this.worldview=Z,this.dirty=!0,this.needsPartStyleUBOs=!1,this.filter=null,this.nodesInfo=[];for(const se of _)this.nodesInfo.push(new Tmt(se)),Emt(se,H.featureIndexArray.length,H.grid),H.featureIndexArray.emplaceBack(this.nodesInfo.length-1,0,H.bucketLayerIDs.length-1,0);this.states={},this.hasAppearances=null}updateFootprints(p,_){for(const A of this.getNodesInfo()){const M=A.node;M.footprint&&_.push({footprint:M.footprint,id:p})}}updateAppearances(p,_,A,M){return{hasLayoutChanges:!1,hasUboChanges:!1}}update(p){const _=Object.keys(p).length!==0;if(_&&!this.stateDependentLayers.length)return;const A=_?this.stateDependentLayers:this.layers;if(!Lr(p,this.states))for(const M of A)this.evaluate(M,p);this.states=structuredClone(p)}populate(){console.log("populate 3D model bucket")}uploadPending(){return!this.uploaded||this.needsPartStyleUBOs}upload(p){if(this.needsPartStyleUBOs&&(this.createPartStyleUBOs(p),this.needsPartStyleUBOs=!1),!this.uploaded){const _=this.getNodesInfo();for(const A of _)ZOe(A.node,p,!0);for(const A of _)vle(A.node);this.uploaded=!0}}createPartStyleUBOs(p){for(const _ of this.getNodesInfo())_.needsPartStyleUBO&&(_.partStyleUBO=new eps(p,_.partStyle),_.needsPartStyleUBO=!1)}needsReEvaluation(p,_,A){const M=p.transform.projectionOptions,F=p.style.getBrightness(),z=this.brightness!==F;if(!this.uploaded||this.dirty||M.name!==this.projection.name||nZ(A.paint.get("model-color").value,z)||nZ(A.paint.get("model-color-mix-intensity").value,z)||nZ(A.paint.get("model-roughness").value,z)||nZ(A.paint.get("model-emissive-strength").value,z)||nZ(A.paint.get("model-height-based-emissive-strength-multiplier").value,z)){this.projection=M,this.brightness=F;const H=this.getNodesInfo();for(const Z of H)Z.state=null;return!0}return!1}evaluateTransform(p,_){if(p.transform.zoom===this.zoom)return;this.zoom=p.transform.zoom;const A=this.getNodesInfo(),M=this.id.canonical;for(const F of A){const z=F.feature;F.evaluatedTranslation=_.paint.get("model-translation").evaluate(z,{},M),F.evaluatedScale=_.paint.get("model-scale").evaluate(z,{},M)}}evaluate(p,_){const A=this.getNodesInfo();for(const M of A){if(!M.node.meshes)continue;const F=M.feature,z=_&&_[F.id];if(Lr(z,M.state))continue;M.state=structuredClone(z);const H=M.node.meshes&&M.node.meshes[0].hasFeatureData,Z=this.id.canonical;if(M.hasTranslucentParts=!1,H){for(let se=0;se=Nt)continue;const Hn=x8e[jn],Cs=Math.abs(Hn);Cs>ns&&(Jt=Hn,ns=Cs,Ls=cn,Gs=pn)}if(ns>.1){const pn=1-(Nt+.5*Math.abs(Ls*Gs))/De;let cn=_._dem.get(Et,as)+Jt*pn;const jn=_._dem.get(Et+Ls,as+Gs),Hn=_._dem.get(Et-Ls,as-Gs,!0);(cn-jn)*(cn-Hn)>0&&(cn=(jn+Hn)/2),x8e[$t]=_._dem.set(Et,as,cn),lR[$t]=Nt}}}}}H&&(_._demTile.needsDEMTextureUpload=!0,_._dem._timestamp=oh.now())}setFilter(p){this.filter=p?gY(p):null}getNodesInfo(){return this.filter?this.nodesInfo.filter(p=>this.filter.filter(new Kn(this.id.overscaledZ,{worldview:this.worldview}),p.feature,this.id.canonical)):this.nodesInfo}destroy(){const p=this.getNodesInfo();for(const _ of p)vle(_.node),XOe(_.node),_.partStyleUBO&&(_.partStyleUBO.destroy(),_.partStyleUBO=null)}isEmpty(){return!this.nodesInfo.length}updateReplacement(p,_){if(_.updateTime===this.replacementUpdateTime)return;this.replacementUpdateTime=_.updateTime;const A=_.getReplacementRegionsForTile(p.toUnwrapped());for(const M of this.getNodesInfo()){const F=M.node.footprint;M.hiddenByReplacement=!!F&&!A.some(z=>z.footprint===F)}}getHeightAtTileCoord(p,_){const A=[0,0,0],M=w([]);for(const F of this.getNodesInfo()){const z=F.node.meshes[0],H=z.transformedAabb;if(pH.max[0]||_>H.max[1])continue;if(F.node.hidden===!0)return{height:1/0,maxHeight:F.feature.properties.height,hidden:!1,verticalScale:F.evaluatedScale[2]};if(C(M,F.node.globalMatrix),A[0]=p,A[1]=_,A[2]=0,Xe(A,A,M),F.node.meshBVH){const xe=A[0],be=A[1];Ile[0]=xe-1,Ile[1]=be-1,Ile[2]=-1e3,Lle[0]=xe+1,Lle[1]=be+1,Lle[2]=1e3;const Te=F.node.meshBVH.findHighestPoint(Ile,Lle);if(Te!==null)return{height:Te,maxHeight:F.feature.properties.height,hidden:F.hiddenByReplacement,verticalScale:F.evaluatedScale[2]};continue}if(!z.heightmap)continue;const Z=(A[0]-z.aabb.min[0])/(z.aabb.max[0]-z.aabb.min[0])*oR|0,se=Math.min(63,(A[1]-z.aabb.min[1])/(z.aabb.max[1]-z.aabb.min[1])*oR|0)*oR+Math.min(63,Z),fe=z.heightmap[se];if(fe<0&&F.node.footprint){const xe=[];if(F.node.footprint.grid.query(new xs(p,_),new xs(p,_),xe),xe.length>0)return{height:void 0,maxHeight:F.feature.properties.height,hidden:F.hiddenByReplacement,verticalScale:F.evaluatedScale[2]};continue}return F.hiddenByReplacement?void 0:{height:fe,maxHeight:F.feature.properties.height,hidden:!1,verticalScale:F.evaluatedScale[2]}}}}function nZ(N,p){return N instanceof G_&&!N.isLightConstant&&p}function tps(N,p){N[p+4]=16*Math.floor(15*N[p+4])/255,N[p+5]=16*Math.floor(15*N[p+5])/255,N[p+6]=Math.min(Math.floor(127.5*N[p+6]+.5),255)/255*2,N[p+7]=Math.floor(255*N[p+7])/255;const _=Math.floor(255*N[p+10])/256,A=Math.floor(255*(N[p+10]+N[p+11]))/256;N[p+10]=_,N[p+11]=A-_}function sps(N){const p=N.partStyle;for(let _=0;_{let mt=Imt,lt=0,yt=Imt;if(!ot){const $t=M.style.light,Jt=$t.properties.get("position");if(mt=[-Jt.x,-Jt.y,Jt.z],$t.properties.get("anchor")==="viewport"){const Ls=f();x(Ls,-M.transform.angle),it(mt,mt,Ls)}const ns=$t.properties.get("color").toNonPremultipliedRenderColor(null);lt=$t.properties.get("intensity"),yt=[ns.r,ns.g,ns.b]}const Nt=fe.alphaMode==="MASK",as=be.paint.get("model-ambient-occlusion-intensity"),Et=be.paint.get("model-color").constantOr(Ci.white).toNonPremultipliedRenderColor(null);return Et.a=be.paint.get("model-color-mix-intensity").constantOr(0),Ye&&(Et.r=Ye[0],Et.g=Ye[1],Et.b=Ye[2],Et.a=Ye[3]),Ue&&(Et.r=Ue.color.r,Et.g=Ue.color.g,Et.b=Ue.color.b,Et.a=Ue.colorMix,xe=Ue.emissionStrength,F*=Ue.opacity),{u_matrix:N,u_lighting_matrix:p,u_normal_matrix:_,u_node_matrix:A||y8e,u_lightpos:mt,u_lightintensity:lt,u_lightcolor:yt,u_camera_pos:Te,u_opacity:F,u_baseTextureIsAlpha:0,u_alphaMask:+Nt,u_alphaCutoff:fe.alphaCutoff,u_baseColorFactor:z.toNonPremultipliedRenderColor(null).toArray01(),u_emissiveFactor:H.toNonPremultipliedRenderColor(null).toArray01(),u_metallicFactor:Z,u_roughnessFactor:se,u_baseColorTexture:Kv.BaseColor,u_metallicRoughnessTexture:Kv.MetallicRoughness,u_normalTexture:Kv.Normal,u_occlusionTexture:Kv.Occlusion,u_emissionTexture:Kv.Emission,u_lutTexture:Kv.LUT,u_color_mix:Et.toArray01(),u_aoIntensity:as,u_emissive_strength:xe,u_occlusionTextureTransform:De||[0,0,0,0],u_dithered_discard_threshold:st,u_model_mesh_params:[0,1,0,0]}},Lmt=(N,p=y8e,_=y8e)=>({u_matrix:N,u_instance:p,u_node_matrix:_}),b8e=7680;class pj{constructor(p,_,A,M,F,z){this.test=p,this.ref=_,this.mask=A,this.fail=M,this.depthFail=F,this.pass=z}}pj.disabled=new pj({func:519,mask:0},0,0,b8e,b8e,b8e);const Rle=770,i$=771;class jh{constructor(p,_,A,M){this.blendFunction=p,this.blendColor=_.toNonPremultipliedRenderColor(null),this.mask=A,this.blendEquation=M}}jh.Replace=[1,0,1,0],jh.disabled=new jh(jh.Replace,Ci.transparent,[!1,!1,!1,!1]),jh.unblended=new jh(jh.Replace,Ci.transparent,[!0,!0,!0,!0]),jh.alphaBlended=new jh([1,i$,1,i$],Ci.transparent,[!0,!0,!0,!0]),jh.alphaBlendedNonPremultiplied=new jh([Rle,i$,Rle,i$],Ci.transparent,[!0,!0,!0,!0]),jh.multiply=new jh([774,0,774,0],Ci.transparent,[!0,!0,!0,!0]),jh.multiplyAccumulateAlpha=new jh([774,0,1,i$],Ci.transparent,[!0,!0,!0,!0]),jh.additive=new jh([1,1,1,1],Ci.transparent,[!0,!0,!0,!0]),jh.additiveAlphaWeighted=new jh([Rle,1,773,1],Ci.transparent,[!0,!0,!0,!0]),jh.additiveAlphaWeightedUnboundedAlpha=new jh([Rle,1,1,1],Ci.transparent,[!0,!0,!0,!0]);class Ny{constructor(p,_,A){this.func=p,this.mask=_,this.range=A}}Ny.ReadOnly=!1,Ny.ReadWrite=!0,Ny.disabled=new Ny(519,Ny.ReadOnly,[0,1]);const _8e=1029,w8e=2305;class ky{constructor(p,_,A){this.enable=p,this.mode=_,this.frontFace=A}}ky.disabled=new ky(!1,_8e,w8e),ky.backCCW=new ky(!0,_8e,w8e),ky.backCW=new ky(!0,_8e,2304),ky.frontCW=new ky(!0,1028,2304),ky.frontCCW=new ky(!0,1028,w8e);class j8e{constructor(p=0,_=0,A=0,M=0){if(isNaN(p)||p<0||isNaN(_)||_<0||isNaN(A)||A<0||isNaN(M)||M<0)throw new Error("Invalid value for edge-insets, top, bottom, left and right must all be numbers");this.top=p,this.bottom=_,this.left=A,this.right=M}interpolate(p,_,A){return _.top!=null&&p.top!=null&&(this.top=ya(p.top,_.top,A)),_.bottom!=null&&p.bottom!=null&&(this.bottom=ya(p.bottom,_.bottom,A)),_.left!=null&&p.left!=null&&(this.left=ya(p.left,_.left,A)),_.right!=null&&p.right!=null&&(this.right=ya(p.right,_.right,A)),this}getCenter(p,_){return new xs(ta((this.left+p-this.right)/2,0,p),ta((this.top+_-this.bottom)/2,0,_))}equals(p){return this.top===p.top&&this.bottom===p.bottom&&this.left===p.left&&this.right===p.right}clone(){return new j8e(this.top,this.bottom,this.left,this.right)}toJSON(){return{top:this.top,bottom:this.bottom,left:this.left,right:this.right}}}function Rmt(N,p){const _=Ba(N,3);X(N,p),io(N,3,_)}function N8e(N,p){const _=St([]);return Ss(_,_,-p),vt(_,_,-N),_}function Dmt(N,p){const _=[N[0],N[1],0],A=[p[0],p[1],0];if(ce(_)>=1e-15){const z=qe([],_);Fe(A,z,ze(A,z)),p[0]=A[0],p[1]=A[1]}const M=$e([],p,N);if(Yt(M)<1e-15)return null;const F=Math.atan2(-M[1],M[0]);return N8e(Math.atan2(Math.sqrt(N[0]*N[0]+N[1]*N[1]),-N[2]),F)}class Fmt{constructor(p,_){this.position=p,this.orientation=_}get position(){return this._position}set position(p){if(p){const _=p instanceof Q?p:new Q(p[0],p[1],p[2]);this._renderWorldCopies&&(_.x=fl(_.x,0,1)),this._position=_}else this._position=null}lookAtPoint(p,_,A){if(this.orientation=null,!this.position)return;const M=this.position,F=A||(this._elevation?this._elevation.getAtPointOrZero(Q.fromLngLat(p)):0),z=Q.fromLngLat(p,F),H=[z.x-M.x,z.y-M.y,z.z-M.z];_||(_=[0,0,1]),_[2]=Math.abs(_[2]),this.orientation=Dmt(H,_)}setPitchBearing(p,_){this.orientation=N8e(Xr(p),Xr(-_))}}class Dle{constructor(p,_){this._transform=w([]),this.orientation=_,this.position=p}get mercatorPosition(){const p=this.position;return new Q(p[0],p[1],p[2])}get position(){const p=Ba(this._transform,3);return[p[0],p[1],p[2]]}set position(p){var _;p&&io(this._transform,3,[(_=p)[0],_[1],_[2],1])}get orientation(){return this._orientation}set orientation(p){this._orientation=p||St([]),p&&Rmt(this._transform,this._orientation)}getPitchBearing(){const p=this.forward(),_=this.right();return{bearing:Math.atan2(-_[1],_[0]),pitch:Math.atan2(Math.sqrt(p[0]*p[0]+p[1]*p[1]),-p[2])}}setPitchBearing(p,_){this._orientation=N8e(p,_),Rmt(this._transform,this._orientation)}forward(){const p=Ba(this._transform,2);return[-p[0],-p[1],-p[2]]}up(){const p=Ba(this._transform,1);return[-p[0],-p[1],-p[2]]}right(){const p=Ba(this._transform,0);return[p[0],p[1],p[2]]}getCameraToWorld(p,_){const A=new Float64Array(16);return C(A,this.getWorldToCamera(p,_)),A}getCameraToWorldMercator(){return this._transform}getWorldToCameraPosition(p,_,A){const M=this.position;Fe(M,M,-p);const F=new Float64Array(16);return W(F,[A,A,A]),I(F,F,M),F[10]*=_,F}getWorldToCamera(p,_){const A=new Float64Array(16),M=new Float64Array(4),F=this.position;var z,H;return(z=M)[0]=-(H=this._orientation)[0],z[1]=-H[1],z[2]=-H[2],z[3]=H[3],Fe(F,F,-p),X(A,M),I(A,A,F),A[1]*=-1,A[5]*=-1,A[9]*=-1,A[13]*=-1,A[8]*=_,A[9]*=_,A[10]*=_,A[11]*=_,A}getCameraToClipPerspective(p,_,A,M){const F=new Float64Array(16);return ae(F,p,_,A,M),F}getCameraToClipOrthographic(p,_,A,M,F,z){const H=new Float64Array(16);return ie(H,p,_,A,M,F,z),H}getDistanceToElevation(p,_=!1){const A=p===0?0:eu(p,_?Hd(this.position[1]):this.position[1]),M=this.forward();return(A-this.position[2])/M[2]}clone(){return new Dle([...this.position],[...this.orientation])}}const rps=Math.tan(85*Math.PI/180);function k8e(N,p,_,A,M,F,z){const H=y();if(_)if(F.name==="globe"){const Z=function(se,fe){const{x:xe,y:be}=se.point,Te=Bdt(xe,be,se.worldSize/se._pixelsPerMercatorPixel,0,0);return E(Te,Te,fOe(WC(fe)))}(M,p);E(H,H,Z)}else{const Z=m([],z);H[0]=Z[0],H[1]=Z[1],H[4]=Z[2],H[5]=Z[3],A||O(H,H,M.angle)}else E(H,M.labelPlaneMatrix,N);return H}function fM(N,p,_,A){const M=[N,p,_,1];_?Ft(M,M,A):wOe(M,M,A);const F=M[3];return M[0]/=F,M[1]/=F,M[2]/=F,M}function Omt(N,p){return Math.min(.5+N/p*.5,1.5)}function aps(N,p){const _=N[0]/N[3],A=N[1]/N[3];return _>=-p[0]&&_<=p[0]&&A>=-p[1]&&A<=p[1]}function zmt(N,p,_,A,M,F,z,H,Z,se,fe,xe,be,Te,De,Ue,Ye,st){const{lineStartIndex:ot,glyphStartIndex:mt,segment:lt}=H,yt=mt+H.numGlyphs,Nt=ot+H.lineLength,as=p.getoffsetX(mt),Et=p.getoffsetX(yt-1),$t=Fle(N*as,_,A,M,F,z,lt,ot,Nt,Z,se,fe,xe,be,!0,Te,De,Ue,Ye,st);if(!$t)return null;const Jt=Fle(N*Et,_,A,M,F,z,lt,ot,Nt,Z,se,fe,xe,be,!0,Te,De,Ue,Ye,st);return Jt?{first:$t,last:Jt}:null}function Bmt(N,p,_,A){return N===$3.horizontal&&Math.abs(A)>Math.abs(_)?{useVertical:!0}:N===$3.vertical?A>0?{needsFlipping:!0}:null:p!==0&&function(M,F){return M===0||Math.abs(F/M)>rps}(_,A)?p===1?{needsFlipping:!0}:null:_<0?{needsFlipping:!0}:null}function $mt(N,p,_,A,M,F,z,H,Z,se,fe,xe,be,Te,De,Ue,Ye,st,ot,mt,lt){const yt=p/24,Nt=N.lineOffsetX*yt,as=N.lineOffsetY*yt,{lineStartIndex:Et,glyphStartIndex:$t,numGlyphs:Jt,segment:ns,writingMode:Ls,flipState:Gs}=N,pn=Et+N.lineLength,cn=jn=>{if(fe){const[an,Ln,In]=jn.up,Vn=se.length;nle(fe,Vn+0,an,Ln,In),nle(fe,Vn+1,an,Ln,In),nle(fe,Vn+2,an,Ln,In),nle(fe,Vn+3,an,Ln,In)}const[Hn,Cs,Qs]=jn.point;rR(se,Hn,Cs,Qs,jn.angle)};if(Jt>1){const jn=zmt(yt,H,Nt,as,_,xe,be,N,Z,F,Te,Ue,!1,Ye,st,ot,mt,lt);if(!jn)return{notEnoughRoom:!0};if(A&&!_){let[Hn,Cs,Qs]=jn.first.point,[an,Ln,In]=jn.last.point;[Hn,Cs]=fM(Hn,Cs,Qs,z),[an,Ln]=fM(an,Ln,In,z);const Vn=Bmt(Ls,Gs,(an-Hn)*De,Ln-Cs);if(N.flipState=Vn&&Vn.needsFlipping?1:2,Vn)return Vn}cn(jn.first);for(let Hn=$t+1;Hn<$t+Jt-1;Hn++){const Cs=Fle(yt*H.getoffsetX(Hn),Nt,as,_,xe,be,ns,Et,pn,Z,F,Te,Ue,!1,!1,Ye,st,ot,mt,lt);if(!Cs)return se.length-=4*(Hn-$t),{notEnoughRoom:!0};cn(Cs)}cn(jn.last)}else{if(A&&!_){const Hn=fM(be.x,be.y,0,M),Cs=Et+ns+1,Qs=new xs(Z.getx(Cs),Z.gety(Cs)),an=fM(Qs.x,Qs.y,0,M),Ln=an[3]>0?an:Vmt(be,Qs,Hn,1,M,void 0,Ye,st.canonical),In=Bmt(Ls,Gs,(Ln[0]-Hn[0])*De,Ln[1]-Hn[1]);if(N.flipState=In&&In.needsFlipping?1:2,In)return In}const jn=Fle(yt*H.getoffsetX($t),Nt,as,_,xe,be,ns,Et,pn,Z,F,Te,Ue,!1,!1,Ye,st,ot,mt,lt);if(!jn)return{notEnoughRoom:!0};cn(jn)}return{}}function Umt(N,p,_){const A=1<0?1:-1,Nt=0;A&&(yt*=-1,Nt=Math.PI),yt<0&&(Nt+=Math.PI);let as=H+z+(yt>0?0:1)|0,Et=M,$t=M,Jt=0,ns=0;const Ls=Math.abs(lt),Gs=[],pn=[];let cn=F,jn=cn,Hn=Ke([]);const Cs=()=>Vmt(jn,cn,$t,Ls-Jt+1,fe,be,Ue,Ye.canonical,mt);for(;Jt+ns<=Ls;){if(as+=yt,as=Z)return null;if($t=Et,jn=cn,Gs.push($t),Te&&pn.push(jn),cn=new xs(se.getx(as),se.gety(as)),Et=xe[as],!Et){const cr=qmt(cn,Ye.canonical,fe,Ue,be,mt);Et=cr[3]>0?xe[as]=cr:Cs()}Jt+=ns;const Bn=xt([],Et,$t),Rr=Ve($t,Et);if(_&&Rr>0&&ns>0&&ze(Hn,Bn)/(ns*Rr)0&&this.elevation.exaggeration()>0&&this._centerAltitudeValidForExaggeration;if(!this._elevation||p===Number.NEGATIVE_INFINITY&&(!_||!this._centerAltitude))return this._centerAltitude=0,this._seaLevelZoom=null,void(this._centerAltitudeValidForExaggeration=void 0);const A=this._elevation;_||this._centerAltitude&&this._centerAltitudeValidForExaggeration&&A.exaggeration()&&this._centerAltitudeValidForExaggeration!==A.exaggeration()?(this._centerAltitude=this._centerAltitude/this._centerAltitudeValidForExaggeration*A.exaggeration(),this._centerAltitudeValidForExaggeration=A.exaggeration()):(this._centerAltitude=p||0,this._centerAltitudeValidForExaggeration=A.exaggeration()),this._updateSeaLevelZoom()}_updateSeaLevelZoom(){if(this._centerAltitudeValidForExaggeration===void 0)return;const p=Math.max(0,(this.pixelsPerMeter*this._centerAltitude+this.cameraToCenterDistance)/this.worldSize);this._seaLevelZoom=this._zoomFromMercatorZ(p)}sampleAverageElevation(){if(!this._elevation)return 0;const p=this._elevation,_=[[.5,.2],[.3,.5],[.5,.5],[.7,.5],[.5,.8]],A=this.horizonLineFromTop();let M=0,F=0;for(let z=0;z<_.length;z++){const H=new xs(_[z][0]*this.width,A+_[z][1]*(this.height-A)),Z=p.pointCoordinate(H);if(!Z)continue;const se=1/Math.hypot(Z[0]-this._camera.position[0],Z[1]-this._camera.position[1]);M+=Z[3]*se,F+=se}return F===0?NaN:M/F}get center(){return this._center}set center(p){p.lat===this._center.lat&&p.lng===this._center.lng||(this._unmodified=!1,this._center=p,this._terrainEnabled()&&(this.cameraElevationReference==="ground"?this._updateCameraOnTerrain():this._updateZoomFromElevation()),this._constrain(),this._calcMatrices())}_updateZoomFromElevation(){if(this._seaLevelZoom==null||!this._elevation)return;const p=this._seaLevelZoom,_=this._elevation.getAtPointOrZero(this.locationCoordinate(this.center)),A=this.pixelsPerMeter/this.worldSize*_,M=this._mercatorZfromZoom(p),F=this._mercatorZfromZoom(this._maxZoom),z=Math.max(M-A,F);this._setZoom(this._zoomFromMercatorZ(z))}get padding(){return this._edgeInsets.toJSON()}set padding(p){this._edgeInsets.equals(p)||(this._unmodified=!1,this._edgeInsets.interpolate(this._edgeInsets,p,1),this._calcMatrices())}equals(p){const _=this.elevation,A=p.elevation,M=_!=null!=(A!=null)||_&&A&&_.exaggeration()!==A.exaggeration();return this.width===p.width&&this.height===p.height&&this.center.lng===p.center.lng&&this.center.lat===p.center.lat&&this.zoom===p.zoom&&this.bearing===p.bearing&&this.pitch===p.pitch&&this.fov===p.fov&&this.projection.name===p.projection.name&&this._edgeInsets.equals(p.padding)&&!M}computeZoomRelativeTo(p){const _=this.rayIntersectionCoordinate(this.pointRayIntersection(this.centerPoint,p.toAltitude()));let A;A=p.z{const Ye=cM(be,xe,Te,De,Ue);Z.has(Ye)||(F.push(new mg(xe,be,Te,De,Ue)),Z.add(Ye))};for(let xe=0;xebe.canonical.z)continue;const Te=be.canonical,De=be.overscaledZ,Ue=be.wrap,Ye=1<0,mt=Te.y+10,yt=be.wrap-(ot?0:1),Nt=be.wrap+(st?0:1),as=ot?Te.x-1:Ye-1,Et=st?Te.x+1:0;if(z)A[0]<0?(se(De,Nt,Te.z,Et,Te.y),A[1]<0&&mt&&(se(De,Ue,Te.z,Te.x,Te.y+1),se(De,Nt,Te.z,Et,Te.y+1)),A[1]>0&<&&(se(De,Ue,Te.z,Te.x,Te.y-1),se(De,Nt,Te.z,Et,Te.y-1))):A[0]>0?(se(De,yt,Te.z,as,Te.y),A[1]<0&&mt&&(se(De,Ue,Te.z,Te.x,Te.y+1),se(De,yt,Te.z,as,Te.y+1)),A[1]>0&<&&(se(De,Ue,Te.z,Te.x,Te.y-1),se(De,yt,Te.z,as,Te.y-1))):A[1]<0&&mt?se(De,Ue,Te.z,Te.x,Te.y+1):lt&&se(De,Ue,Te.z,Te.x,Te.y-1);else{const $t=be.visibleQuadrants;1&$t&&(se(De,yt,Te.z,as,Te.y),lt&&(se(De,Ue,Te.z,Te.x,Te.y-1),se(De,yt,Te.z,as,Te.y-1))),2&$t&&(se(De,Nt,Te.z,Et,Te.y),lt&&(se(De,Ue,Te.z,Te.x,Te.y-1),se(De,Nt,Te.z,Et,Te.y-1))),4&$t&&(se(De,yt,Te.z,as,Te.y),mt&&(se(De,Ue,Te.z,Te.x,Te.y+1),se(De,yt,Te.z,as,Te.y+1))),8&$t&&(se(De,Nt,Te.z,Et,Te.y),mt&&(se(De,Ue,Te.z,Te.x,Te.y+1),se(De,Nt,Te.z,Et,Te.y+1)))}}const fe=[];for(const xe of F)F.some(be=>xe.isChildOf(be))||fe.push(xe);if(F=fe.filter(xe=>!p.some(be=>!!(xe.overscaledZ<_&&be.isChildOf(xe))||xe.equals(be)||xe.isChildOf(be))),H){const xe=1<<_,be=this.projection.name==="globe"?this._camera.mercatorPosition:this.pointCoordinate(this.getCameraPoint()),Te=[xe*be.x,xe*be.y],De=4,Ue=De*De;F=F.filter(Ye=>{const st=Ye.canonical.x+.5-Te[0],ot=Ye.canonical.y+.5-Te[1];return st*st+ot*ot{const as=cM(mt,ot,lt,yt,Nt);F.has(as)||(M.push(new mg(ot,mt,lt,yt,Nt)),F.add(as))},H=p.reduce((ot,mt)=>Math.max(ot,mt.overscaledZ),A),Z=1<{const lt=Math.floor(ot[0]),yt=Math.floor(ot[1]),Nt=(ot[0]-lt)*Fr,as=(ot[1]-yt)*Fr,Et=Math.floor(mt[0]),$t=Math.floor(mt[1]),Jt=(mt[0]-Et)*Fr,ns=(mt[1]-$t)*Fr;for(let Ls=-1;Ls<=1;Ls++){const Gs=lt+Ls;if(!(Gs<0||Gs>=Z)){fe.x=Nt-Ls*Fr,xe.x=Jt-(Gs-Et)*Fr;for(let pn=-1;pn<=1;pn++){const cn=yt+pn;fe.y=as-pn*Fr,xe.y=ns-(cn-$t)*Fr,U9(fe,xe,se)&&z(H,0,A,Gs,cn)}}}},Te=_.points,De=Te[3],Ue=Te[2],Ye=this._projectToGround(De,Te[7]),st=this._projectToGround(Ue,Te[6]);return be(De,Ye),be(Ue,st),M}_projectToGround(p,_){return ct(te(),p,_,p[2]/(p[2]-_[2]))}_projectToZ(p,_,A){const M=p[2]-_[2];return Math.abs(M)<1e-6?J(p):ct(te(),p,_,(p[2]-A)/M)}extendTileCoverForTunnels(p,_,A,M){if(A<18)return[];const F=_.points,z=F[0],H=F[1],Z=F[4],se=F[5];if(Z[2]>=0&&se[2]>=0||z[2]<=0||H[2]<=0)return[];const fe=Z[2]<0?this._projectToZ(z,Z,0):Z,xe=se[2]<0?this._projectToZ(H,se,0):se,be=-M,Te=Z[2]3&&(Ue.length=3),Ue}_findExtensionTilesInQuad(p,_,A,M){const F=[],z=new Set;for(const Et of p)z.add(Et.key);const H=p.reduce((Et,$t)=>Math.max(Et,$t.overscaledZ),_),Z=1<<_,se=[new xs(A[0][0],A[0][1]),new xs(A[1][0],A[1][1]),new xs(A[3][0],A[3][1]),new xs(A[2][0],A[2][1]),new xs(A[0][0],A[0][1])],fe=A[0][0],xe=A[1][0],be=A[2][0],Te=A[3][0],De=A[0][1],Ue=A[1][1],Ye=A[2][1],st=A[3][1],ot=Math.max(0,Math.floor(Math.min(fe,xe,be,Te))),mt=Math.min(Z-1,Math.ceil(Math.max(fe,xe,be,Te))-1),lt=Math.max(0,Math.floor(Math.min(De,Ue,Ye,st))),yt=Math.min(Z-1,Math.ceil(Math.max(De,Ue,Ye,st))-1);for(let Et=lt;Et<=yt;Et++)for(let $t=ot;$t<=mt;$t++){if(!eOe(se,$t,Et,$t+1,Et+1))continue;const Jt=cM(0,H,_,$t,Et);z.has(Jt)||(F.push(new mg(H,0,_,$t,Et)),z.add(Jt))}const Nt=M[0],as=M[1];return F.sort((Et,$t)=>{const Jt=Et.canonical.x+.5-Nt,ns=Et.canonical.y+.5-as,Ls=$t.canonical.x+.5-Nt,Gs=$t.canonical.y+.5-as;return Jt*Jt+ns*ns-(Ls*Ls+Gs*Gs)||Et.canonical.x-$t.canonical.x||Et.canonical.y-$t.canonical.y}),F}coveringTiles(p){let _=this.coveringZoomLevel(p);const A=_,M=this.elevation&&this.elevation.exaggeration(),F=M&&!p.isTerrainDEM,z=this.projection.name==="mercator";if(p.minzoom!==void 0&&_p.maxzoom&&(_=p.maxzoom);const H=this.locationCoordinate(this.center),Z=this.center.lat,se=1<<_,fe=[se*H.x,se*H.y,0],xe=this.projection.name==="globe",be=!xe,Te=q3.fromInvProjectionMatrix(this.invProjMatrix,this.worldSize,_,be),De=xe?this._camera.mercatorPosition:this.pointCoordinate(this.getCameraPoint()),Ue=se*eu(1,this.center.lat),Ye=this._camera.position[2]/eu(1,this.center.lat),st=[se*De.x,se*De.y,Ye*(be?1:Ue)],ot=xe||M,mt=this.cameraToCenterDistance/p.tileSize*(p.roundZoom?1:.502),lt=this.isLODDisabled(!0)?_:0;let yt;if(this._elevation&&p.isTerrainDEM)yt=1e4*this._elevation.exaggeration();else if(this._elevation){const Cs=this._elevation.getMinMaxForVisibleTiles();yt=Cs?Cs.max:this._centerAltitude}else yt=this._centerAltitude;const Nt=p.isTerrainDEM?-yt:this._elevation?this._elevation.getMinElevationBelowMSL():0,as=this.projection.isReprojectedInTileSpace?Jut(this):1,Et=Cs=>{const an=new Q(Cs.x+25e-6,Cs.y,Cs.z),Ln=new Q(Cs.x,Cs.y+25e-6,Cs.z),In=Cs.toLngLat(),Vn=an.toLngLat(),Dn=Ln.toLngLat(),ir=this.locationCoordinate(In),Bn=this.locationCoordinate(Vn),Rr=this.locationCoordinate(Dn),cr=Math.hypot(Bn.x-ir.x,Bn.y-ir.y),jr=Math.hypot(Rr.x-ir.x,Rr.y-ir.y);return Math.sqrt(cr*jr)*as/25e-6},$t=Cs=>{const Qs=yt,an=Nt;return{aabb:Hdt(this,se,0,0,0,Cs,an,Qs,this.projection),zoom:0,x:0,y:0,minZ:an,maxZ:Qs,wrap:Cs,fullyVisible:!1}},Jt=[];let ns=[];const Ls=_,Gs=p.reparseOverscaled?A:_,pn=(Ye-this._centerAltitude)*Ue,cn=Cs=>{if(!this._elevation||!Cs.tileID||!z)return;const Qs=this._elevation.getMinMaxForTile(Cs.tileID),an=Cs.aabb;Qs?(an.min[2]=Qs.min,an.max[2]=Qs.max,an.center[2]=(an.min[2]+an.max[2])/2):(Cs.shouldSplit=Hn(Cs),Cs.shouldSplit||(an.min[2]=an.max[2]=an.center[2]=this._centerAltitude))},jn=(Cs,Qs)=>{if(.707*Qs{if(Cs.zoom=.9)return!0}else if(F&&(Ln=Cs.aabb.distanceZ(st)*Ue),this.projection.isReprojectedInTileSpace&&A<=5){const jr=Math.pow(2,Cs.zoom),Wa=Et(new Q((Cs.x+.5)/jr,(Cs.y+.5)/jr));In=Wa>.85?1:Wa}if(!z&&!xe){const jr=Math.sqrt(Qs*Qs+an*an+Ln*Ln);let Wa=(1<0;){const Cs=Jt.pop(),Qs=Cs.x,an=Cs.y;let Ln=Cs.fullyVisible;const In=()=>this.projection.name==="globe"&&(Cs.y===0||Cs.y===(1<Vn)continue;let Dn=0;if(!Ln){let cr=ot?Cs.aabb.intersectsPrecise(Te):Cs.aabb.intersectsPreciseFlat(Te);if(cr===0&&In()){const jr=new lM(Cs.zoom,Qs,an);cr=hOe(this,se,jr,!0).intersectsPrecise(Te)}if(cr===0)continue;if(p.calculateQuadrantVisibility)if(Te.containsPoint(Cs.aabb.center))Dn=15;else for(let jr=0;jr<4;jr++)Cs.aabb.quadrant(jr).intersects(Te)!==0&&(Dn|=1<>1),Bn={aabb:z?Cs.aabb.quadrant(Vn):Hdt(this,se,Cs.zoom+1,Dn,ir,Cs.wrap,Cs.minZ,Cs.maxZ,this.projection),zoom:Cs.zoom+1,x:Dn,y:ir,wrap:Cs.wrap,fullyVisible:Ln,tileID:void 0,shouldSplit:void 0,minZ:Cs.minZ,maxZ:Cs.maxZ};F&&!xe&&(Bn.tileID=new mg(Cs.zoom+1===Ls?Gs:Cs.zoom+1,Cs.wrap,Cs.zoom+1,Dn,ir),cn(Bn)),Jt.push(Bn)}}if(this.fogCullDistSq){const Cs=this.fogCullDistSq,Qs=this.horizonLineFromTop();ns=ns.filter(an=>{const Ln=[0,0,0,1],In=[Fr,Fr,0,1],Vn=this.calculateFogTileMatrix(an.tileID.toUnwrapped());Ft(Ln,Ln,Vn),Ft(In,In,Vn);const Dn=(cr=Ln,jr=In,(Rr=[])[0]=Math.min(cr[0],jr[0]),Rr[1]=Math.min(cr[1],jr[1]),Rr[2]=Math.min(cr[2],jr[2]),Rr[3]=Math.min(cr[3],jr[3]),Rr),ir=function(oi,Fa,Ai){return oi[0]=Math.max(Fa[0],Ai[0]),oi[1]=Math.max(Fa[1],Ai[1]),oi[2]=Math.max(Fa[2],Ai[2]),oi[3]=Math.max(Fa[3],Ai[3]),oi}([],Ln,In),Bn=function(oi,Fa){let Ai=0;for(let Ni=0;Ni<2;++Ni)oi[Ni]>0&&(Ai+=(oi[Ni]-0)*(oi[Ni]-0)),Fa[Ni]<0&&(Ai+=(0-Fa[Ni])*(0-Fa[Ni]));return Ai}(Dn,ir);var Rr,cr,jr;if(Bn===0)return!0;let Wa=!1;const Ka=this._elevation;if(Ka&&Bn>Cs&&Qs!==0){const oi=this.calculateProjMatrix(an.tileID.toUnwrapped());let Fa;p.isTerrainDEM||(Fa=Ka.getMinMaxForTile(an.tileID)),Fa||(Fa={min:Nt,max:yt});const Ai=function(Fo){const rl=Math.round((Fo+45+360)%360/90)%4;return Ph[rl]}(this.rotation),Ni=[Ai[0]*Fr,Ai[1]*Fr,Fa.max];Xe(Ni,Ni,oi),Wa=(1-Ni[1])*this.height*.5Cs.distanceSq-Qs.distanceSq).map(Cs=>Cs.tileID)}resize(p,_){this.width=p,this.height=_,this.pixelsToGLUnits=[2/p,-2/_],this._constrain(),this._calcMatrices()}get unmodified(){return this._unmodified}zoomScale(p){return Math.pow(2,p)}scaleZoom(p){return Math.log2(p)}project(p){const _=ta(p.lat,-85.051129,L),A=this.projection.project(p.lng,_);return new xs(A.x*this.worldSize,A.y*this.worldSize)}unproject(p){return this.projection.unproject(p.x/this.worldSize,p.y/this.worldSize)}get point(){return this.project(this.center)}get pointMerc(){return this.point._div(this.worldSize)}get pixelsPerMeterRatio(){return this.pixelsPerMeter/eu(1,this.center.lat)/this.worldSize}setLocationAtPoint(p,_){let A,M;const F=this.centerPoint;if(this.projection.name==="globe"){const H=this.worldSize;A=(_.x-F.x)/H,M=(_.y-F.y)/H}else{const H=this.pointCoordinate(_),Z=this.pointCoordinate(F);A=H.x-Z.x,M=H.y-Z.y}const z=this.locationCoordinate(p);this.setLocation(new Q(z.x-A,z.y-M))}setLocation(p){this.center=this.coordinateLocation(p),this.projection.wrap&&(this.center=this.center.wrap())}locationPoint(p,_){return this.projection.locationPoint(this,p,_)}locationPoint3D(p,_){return this.projection.locationPoint(this,p,_,!0)}pointLocation(p){return this.coordinateLocation(this.pointCoordinate(p))}pointLocation3D(p,_){return this.coordinateLocation(this.pointCoordinate3D(p,_))}locationCoordinate(p,_){const A=_?eu(_,p.lat):void 0,M=this.projection.project(p.lng,p.lat);return new Q(M.x,M.y,A)}coordinateLocation(p){return this.projection.unproject(p.x,p.y)}pointRayIntersection(p,_){const A=_??this._centerAltitude,M=[p.x,p.y,0,1],F=[p.x,p.y,1,1];Ft(M,M,this.pixelMatrixInverse),Ft(F,F,this.pixelMatrixInverse);const z=F[3];ys(M,M,1/M[3]),ys(F,F,1/z);const H=M[2],Z=F[2];return{p0:M,p1:F,t:H===Z?0:(A-H)/(Z-H)}}screenPointToMercatorRay(p){const _=[p.x,p.y,0,1],A=[p.x,p.y,1,1];return Ft(_,_,this.pixelMatrixInverse),Ft(A,A,this.pixelMatrixInverse),ys(_,_,1/_[3]),ys(A,A,1/A[3]),_[2]=eu(_[2],this._center.lat)*this.worldSize,A[2]=eu(A[2],this._center.lat)*this.worldSize,ys(_,_,1/this.worldSize),ys(A,A,1/this.worldSize),new Roe([_[0],_[1],_[2]],qe([],xt([],A,_)))}rayIntersectionCoordinate(p){const{p0:_,p1:A,t:M}=p,F=eu(_[2],this._center.lat),z=eu(A[2],this._center.lat);return new Q(ya(_[0],A[0],M)/this.worldSize,ya(_[1],A[1],M)/this.worldSize,ya(F,z,M))}pointCoordinate(p,_=this._centerAltitude){return this.projection.pointCoordinate(this,p.x,p.y,_)}pointCoordinate3D(p,_){if(!this.elevation)return this.pointCoordinate(p,_);let A=this.projection.pointCoordinate3D(this,p.x,p.y);if(A)return new Q(A[0],A[1],A[2]);let M=0,F=this.horizonLineFromTop();if(p.y>F)return this.pointCoordinate(p,_);const z=.02*F,H=p.clone();for(let Z=0;Z<10&&F-M>z;Z++){H.y=ya(M,F,.66);const se=this.projection.pointCoordinate3D(this,H.x,H.y);se?(F=H.y,A=se):M=H.y}return A?new Q(A[0],A[1],A[2]):this.pointCoordinate(p)}isPointAboveHorizon(p){return this.projection.isPointAboveHorizon(this,p)}isPointOnSurface(p){if(p.y<0||p.y>this.height||p.x<0||p.x>this.width)return!1;if(this.elevation||this.zoom>=6)return!this.isPointAboveHorizon(p);const _=this.pointCoordinate(p);return _.y>=0&&_.y<=1}_coordinatePoint(p,_){const A=_&&this.elevation?this.elevation.getAtPointOrZero(p,this._centerAltitude):this._centerAltitude,M=[p.x*this.worldSize,p.y*this.worldSize,A+p.toAltitude(),1];return Ft(M,M,this.pixelMatrix),M[3]>0?new xs(M[0]/M[3],M[1]/M[3]):new xs(Number.MAX_VALUE,Number.MAX_VALUE)}_getBoundsNonRectangular(){const{top:p,left:_}=this._edgeInsets,A=this.height-this._edgeInsets.bottom,M=this.width-this._edgeInsets.right,F=this.pointLocation3D(new xs(_,p)),z=this.pointLocation3D(new xs(M,p)),H=this.pointLocation3D(new xs(M,A)),Z=this.pointLocation3D(new xs(_,A));let se=Math.min(F.lng,z.lng,H.lng,Z.lng),fe=Math.max(F.lng,z.lng,H.lng,Z.lng),xe=Math.min(F.lat,z.lat,H.lat,Z.lat),be=Math.max(F.lat,z.lat,H.lat,Z.lat);const Te=Math.pow(2,-this.zoom)/16*270,De=this.projection.name==="globe"?1:4,Ue=(Ye,st,ot,mt,lt)=>{const yt=(Ye+ot)/2,Nt=(st+mt)/2,as=new xs(yt,Nt),{lng:Et,lat:$t}=this.pointLocation3D(as),Jt=Math.max(0,se-Et,xe-$t,Et-fe,$t-be);se=Math.min(se,Et),fe=Math.max(fe,Et),xe=Math.min(xe,$t),be=Math.max(be,$t),(ltTe)&&(Ue(Ye,st,yt,Nt,lt+1),Ue(yt,Nt,ot,mt,lt+1))};if(Ue(_,p,M,p,1),Ue(M,p,M,A,1),Ue(M,A,_,A,1),Ue(_,A,_,p,1),this.projection.name==="globe"){const[Ye,st]=function(ot){const mt=w(new Float64Array(16));E(mt,ot.pixelMatrix,ot.globeMatrix);const lt=[0,Wv,0],yt=[0,K_,0];return Xe(lt,lt,mt),Xe(yt,yt,mt),[lt[0]>0&<[0]<=ot.width&<[1]>0&<[1]<=ot.height&&!gOe(ot,new Ll(ot.center.lat,90)),yt[0]>0&&yt[0]<=ot.width&&yt[1]>0&&yt[1]<=ot.height&&!gOe(ot,new Ll(ot.center.lat,-90))]}(this);Ye?(be=90,fe=180,se=-180):st&&(xe=-90,fe=180,se=-180)}return new Y_(new Ll(se,xe),new Ll(fe,be))}_getBoundsRectangular(p,_){const{top:A,left:M}=this._edgeInsets,F=this.height-this._edgeInsets.bottom,z=this.width-this._edgeInsets.right,H=new xs(M,A),Z=new xs(z,A),se=new xs(z,F),fe=new xs(M,F);let xe=this.pointCoordinate(H,p),be=this.pointCoordinate(Z,p);const Te=this.pointCoordinate(se,_),De=this.pointCoordinate(fe,_),Ue=(Ye,st)=>(st.y-Ye.y)/(st.x-Ye.x);return xe.y>1&&be.y>=0?xe=new Q((1-De.y)/Ue(De,xe)+De.x,1):xe.y<0&&be.y<=1&&(xe=new Q(-De.y/Ue(De,xe)+De.x,0)),be.y>1&&xe.y>=0?be=new Q((1-Te.y)/Ue(Te,be)+Te.x,1):be.y<0&&xe.y<=1&&(be=new Q(-Te.y/Ue(Te,be)+Te.x,0)),new Y_().extend(this.coordinateLocation(xe)).extend(this.coordinateLocation(be)).extend(this.coordinateLocation(De)).extend(this.coordinateLocation(Te))}_getBoundsRectangularTerrain(){const p=this.elevation;if(!p.visibleDemTiles.length||p.isUsingMockSource())return this._getBoundsRectangular(0,0);const _=p.visibleDemTiles.reduce((A,M)=>{if(M.dem){const F=M.dem.tree;A.min=Math.min(A.min,F.minimums[0]),A.max=Math.max(A.max,F.maximums[0])}return A},{min:Number.MAX_VALUE,max:0});return this._getBoundsRectangular(_.min*p.exaggeration(),_.max*p.exaggeration())}getBounds(){return this.projection.name==="mercator"||this.projection.name==="equirectangular"?this._terrainEnabled()?this._getBoundsRectangularTerrain():this._getBoundsRectangular(0,0):this._getBoundsNonRectangular()}horizonLineFromTop(p=!0){const _=this.height/2/Math.tan(this._fov/2)/Math.tan(Math.max(this._pitch,.1))-this.centerOffset.y,A=this.height/2-_*(1-this._horizonShift);return p?Math.max(0,A):A}getMaxBounds(){return this.maxBounds}setMaxBounds(p){this.maxBounds=p,this.minLat=-85.051129,this.maxLat=L,this.minLng=-180,this.maxLng=180,p&&(this.minLat=p.getSouth(),this.maxLat=p.getNorth(),this.minLng=p.getWest(),this.maxLng=p.getEast(),this.maxLngxe&&(H=xe-se),xe-feTe&&(z=Te-Z),Te-be{for(let Gs=0;Gs<16;Gs++)$t[Gs]=ya(Jt[Gs],ns[Gs],Ls)})(H,H,Z,vo(this.pitch>=o$?1:this.pitch/o$))}else H=Z;const se=ne([],Z,z),fe=ne([],H,z);if(this.projection.isReprojectedInTileSpace){const yt=this.locationCoordinate(this.center);w(this._mat4Scratch);const Nt=this._mat4Scratch;I(Nt,Nt,[yt.x*this.worldSize,yt.y*this.worldSize,0]),E(Nt,Nt,Qut(this)),I(Nt,Nt,[-yt.x*this.worldSize,-yt.y*this.worldSize,0]),E(fe,fe,Nt),E(se,se,Nt),this.inverseAdjustmentMatrix=function(as){const Et=Qut(as,!0);return m([],[Et[0],Et[1],Et[4],Et[5]])}(this)}else this.inverseAdjustmentMatrix=[1,0,0,1];if(P(this.mercatorMatrix,fe,[this.worldSize,this.worldSize,this.worldSize/F,1]),this.projMatrix=fe,C(this.invProjMatrix,this.projMatrix),_){const yt=this._camera.getCameraToClipPerspective(this._fov,this.width/this.height,this._nearZ,1/0);yt[8]=2*-p.x/this.width,yt[9]=2*p.y/this.height,ne(this._expandedFarZProjMatrixBuf,yt,z),this.expandedFarZProjMatrix=this._expandedFarZProjMatrixBuf}else this.expandedFarZProjMatrix=this.projMatrix;C(this._mat4Scratch,H),this.frustumCorners=cOe.fromInvProjectionMatrix(this._mat4Scratch,this.horizonLineFromTop(),this.height),this.cameraFrustum=q3.fromInvProjectionMatrix(this.invProjMatrix,this.worldSize,0,!_),W(this.skyboxMatrix,[1,-1,1]),R(this.skyboxMatrix,this.skyboxMatrix,this._pitch),O(this.skyboxMatrix,this.skyboxMatrix,this.angle),ae(this.starsProjMatrix,this._fov,this.width/this.height,this._nearZ,this._farZ);const xe=(Math.PI/2-this._pitch)*(this.height/this._fov)*this._horizonShift;b(this._mat4Scratch,this.starsProjMatrix),this._mat4Scratch[8]=2*-p.x/this.width,this._mat4Scratch[9]=2*(p.y+xe)/this.height,E(this.skyboxMatrix,this._mat4Scratch,this.skyboxMatrix);const be=this.point,Te=be.x,De=be.y,Ue=this.width%2/2,Ye=this.height%2/2,st=Math.cos(this.angle),ot=Math.sin(this.angle),mt=Te-Math.round(Te)+st*Ue+ot*Ye,lt=De-Math.round(De)+st*Ye+ot*Ue;if(b(this.alignedProjMatrix,fe),I(this.alignedProjMatrix,this.alignedProjMatrix,[mt>.5?mt-1:mt,lt>.5?lt-1:lt,0]),W(this.labelPlaneMatrix,[this.width/2,-this.height/2,1]),I(this.labelPlaneMatrix,this.labelPlaneMatrix,[1,-1,0]),W(this.glCoordMatrix,[1,-1,1]),I(this.glCoordMatrix,this.glCoordMatrix,[-1,-1,0]),P(this.glCoordMatrix,this.glCoordMatrix,[2/this.width,2/this.height,1]),E(this.pixelMatrix,this.labelPlaneMatrix,se),this._calcFogMatrices(),this._distanceTileDataCache={},!C(this.pixelMatrixInverse,this.pixelMatrix))throw new Error("failed to invert matrix");if(this.projection.name==="globe"||this.mercatorFromTransition){this.globeMatrix=function(Nt){const{x:as,y:Et}=Nt.point,{lng:$t,lat:Jt}=Nt._center;return Bdt(as,Et,Nt.worldSize,$t,Jt)}(this);const yt=[this.globeMatrix[12],this.globeMatrix[13],this.globeMatrix[14]];this.globeCenterInViewSpace=Xe(yt,yt,z),this.globeRadius=this.worldSize/2/Math.PI-1}else this.globeMatrix=this.pixelMatrixInverse;this._projMatrixCache={},this._alignedProjMatrixCache={},this._pixelsToTileUnitsCache={},this._expandedProjMatrixCache={}}_calcFogMatrices(){this._fogTileMatrixCache={};const p=this.cameraWorldSizeForFog,_=this.cameraPixelsPerMeter,A=this._camera.position,M=1/this.height/this._pixelsPerMercatorPixel,F=[p,p,_];Fe(F,F,M),Fe(A,A,-1),Ee(A,A,F),U(this.mercatorFogMatrix,A),P(this.mercatorFogMatrix,this.mercatorFogMatrix,F),this.worldToFogMatrix=this._camera.getWorldToCameraPosition(p,_,M)}_computeCameraPosition(p){const _=(p=p||this.pixelsPerMeter)/this.pixelsPerMeter,A=this._camera.forward(),M=this.point,F=this._mercatorZfromZoom(this._seaLevelZoom?this._seaLevelZoom:this._zoom)*_-p/this.worldSize*this._centerAltitude;return[M.x/this.worldSize-A[0]*F,M.y/this.worldSize-A[1]*F,p/this.worldSize*this._centerAltitude-A[2]*F]}_updateCameraState(){this.height&&(this._camera.setPitchBearing(this._pitch,this.angle),this._camera.position=this._computeCameraPosition())}_translateCameraConstrained(p){const _=this._maxCameraBoundsDistance()*Math.cos(this._pitch),A=this._camera.position[2],M=p[2];let F=1;this.projection.wrap&&(this.center=this.center.wrap()),M>0&&(F=Math.min((_-A)/M,1)),this._camera.position=ke([],this._camera.position,p,F),this._updateStateFromCamera()}_updateStateFromCamera(){const p=this._camera.position,_=this._camera.forward(),{pitch:A,bearing:M}=this._camera.getPitchBearing(),F=eu(this._centerAltitude,this.center.lat)*this._pixelsPerMercatorPixel,z=this._mercatorZfromZoom(this._maxZoom)*Math.cos(Xr(this._maxPitch)),H=Math.max((p[2]-F)/Math.cos(A),z),Z=this._zoomFromMercatorZ(H);ke(p,p,_,H),this._pitch=ta(A,Xr(this.minPitch),Xr(this.maxPitch)),this.angle=fl(M,-Math.PI,Math.PI),this._setZoom(ta(Z,this._minZoom,this._maxZoom)),this._updateSeaLevelZoom(),this._center=this.coordinateLocation(new Q(p[0],p[1],p[2])),this._unmodified=!1,this._constrain(),this._calcMatrices()}_worldSizeFromZoom(p){return Math.pow(2,p)*this.tileSize}_mercatorZfromZoom(p){return this.cameraToCenterDistance/this._worldSizeFromZoom(p)}_minimumHeightOverTerrain(){const p=Math.min(this._seaLevelZoom??this._zoom,this._maxZoom)+4;return this._mercatorZfromZoom(p)}_zoomFromMercatorZ(p){return this.scaleZoom(this.cameraToCenterDistance/(Math.max(0,p)*this.tileSize))}zoomFromMercatorZAdjusted(p){let _=0,A=6,M=0,F=1/0;for(;A-_>1e-6&&A>_;){const z=_+.5*(A-_),H=this.tileSize*Math.pow(2,z),Z=this.getCameraToCenterDistance(this.projection,z,H),se=this.scaleZoom(Z/(Math.max(0,p)*this.tileSize)),fe=Math.abs(z-se);fese||be.y>1)return!0}return!1}isHorizonVisible(){return this.pitch+Eo(this.fovAboveCenter)>88||this.anyCornerOffEdge(new xs(0,0),new xs(this.width,this.height))}zoomDeltaToMovement(p,_){const A=ce(xt([],this._camera.position,p)),M=this._zoomFromMercatorZ(A)+_;return A-this._mercatorZfromZoom(M)}getCameraPoint(){if(this.projection.name==="globe"){const p=function([_,A,M],F){const z=[_,A,M,1];Ft(z,z,F);const H=z[3]=Math.max(z[3],1e-6);return z[0]/=H,z[1]/=H,z[2]/=H,z}([this.globeMatrix[12],this.globeMatrix[13],this.globeMatrix[14]],this.pixelMatrix);return new xs(p[0],p[1])}{const p=Math.tan(this._pitch)*(this.cameraToCenterDistance||1);return this.centerPoint.add(new xs(0,p))}}getCameraToCenterDistance(p,_=this.zoom,A=this.worldSize){const M=KY(p,_,this.width,this.height,1024),F=p.pixelSpaceConversion(this.center.lat,A,M);let z=.5/Math.tan(.5*this._fov)*this.height*F;return this.isOrthographic&&(z=ya(1,z,vo(this.pitch>=o$?1:this.pitch/o$))),z}getWorldToCameraMatrix(){const p=this._camera.getWorldToCamera(this.worldSize,this.projection.zAxisUnit==="meters"?this.pixelsPerMeter:1);return this.projection.name==="globe"&&E(p,p,this.globeMatrix),p}getFrustum(p){return q3.fromInvProjectionMatrix(this.invProjMatrix,this.worldSize,p,this.projection.zAxisUnit==="meters")}}const l$=(N,p)=>{if(p<=0||N.terrain)return{shouldRenderCutoff:!1,uniformValues:{u_cutoff_params:[0,0,0,1]}};const _=N.transform,A=_.pitch,M=_.isLODDisabled(!1)?60:30;if(A0,uniformValues:{u_cutoff_params:[_._nearZ,_._farZ,(fe-_._nearZ)/F,(fe-xe-_._nearZ)/F]}}};function C8e(N,p,_,A){const M=1<({u_matrix:N,u_color:p,u_overlay:0,u_overlay_scale:_}),ZC=new Float64Array(16),pM=new Float64Array(16),Gmt=new Float64Array(16),A8e=new Float64Array(16),E8e=new Float64Array(16),Ole=new Float64Array(16),ips=new Float64Array(16),zle=[0,0,0],ops=new Float32Array(16),Ble=[0,0,0],lps=[0,0,0],T8e=[];function Wmt(N,p,_){const A=_.cameraWorldSizeForFog/_.worldSize;return P(N,_.worldToFogMatrix,[A,A,1]),E(N,N,p),N}function aZ(N,p,_,A){return I(N,p,_),nt(A,ifs)||P(N,N,A),N}function cps(N,p,_,A){const M=_?p.lightsStyleAabb:N.aabb,F=M?M.min[2]:1/0,z=(M?M.max[2]:-1/0)-F;return[isFinite(F)?F:0,z>0&&isFinite(z)?z:1,A?1:0,0]}function dps(N,p){return p.featureBuffer?N.partStyleUBO:null}function M8e(N,p,_,A,M,F=null){const z=_.material,H=A.context,{baseColorTexture:Z,metallicRoughnessTexture:se}=z.pbrMetallicRoughness,{normalTexture:fe,occlusionTexture:xe,emissionTexture:be}=z;function Te(Ue,Ye,st){if(Ue&&(N.push(Ye),H.activeTexture.set(H.gl.TEXTURE0+st),Ue.gfxTexture)){const{minFilter:ot,magFilter:mt,wrapS:lt,wrapT:yt}=Ue.sampler;Ue.gfxTexture.bindExtraParam(ot,mt,lt,yt)}}Te(Z,"HAS_TEXTURE_u_baseColorTexture",Kv.BaseColor),Te(se,"HAS_TEXTURE_u_metallicRoughnessTexture",Kv.MetallicRoughness),Te(fe,"HAS_TEXTURE_u_normalTexture",Kv.Normal),Te(xe,"HAS_TEXTURE_u_occlusionTexture",Kv.Occlusion),Te(be,"HAS_TEXTURE_u_emissionTexture",Kv.Emission),M&&(M.texture||(M.texture=new lut(A.context,M.image,[M.image.height,M.image.height,M.image.height],H.gl.RGBA8)),H.activeTexture.set(H.gl.TEXTURE0+Kv.LUT),M.texture&&M.texture.bind(H.gl.LINEAR,H.gl.CLAMP_TO_EDGE),N.push("APPLY_LUT_ON_GPU")),_.texcoordBuffer&&(N.push("HAS_ATTRIBUTE_a_uv_2f"),p.push(_.texcoordBuffer)),_.colorBuffer&&(N.push(_.colorBuffer.itemSize===12?"HAS_ATTRIBUTE_a_color_3f":"HAS_ATTRIBUTE_a_color_4f"),p.push(_.colorBuffer)),_.normalBuffer&&(N.push("HAS_ATTRIBUTE_a_normal_4n"),p.push(_.normalBuffer)),F&&(N.push("HAS_ATTRIBUTE_a_feature"),p.push(_.featureBuffer)),z.alphaMode!=="OPAQUE"&&z.alphaMode!=="MASK"||N.push("UNPREMULT_TEXTURE_IN_SHADER"),z.defined||N.push("DIFFUSE_SHADED");const De=A.shadowRenderer;De&&(N.push("RENDER_SHADOWS"),De.useNormalOffset&&N.push("NORMAL_OFFSET"))}function P8e(N,p,_,A,M,F){const z=N.modelOpacity,H=p.context,Z=new Ny(p.context.gl.LEQUAL,N.isLightMesh?Ny.ReadOnly:Ny.ReadWrite,p.depthRangeFor3D),se=p.transform,fe=N.mesh,xe=fe.material,be=xe.pbrMetallicRoughness,Te=p.style.fog;p.transform.projection.zAxisUnit==="pixels"?ZC.set(N.nodeModelMatrix):E(ZC,A.zScaleMatrix,N.nodeModelMatrix),E(ZC,A.negCameraPosMatrix,ZC),C(pM,ZC),S(pM,pM);const De=_.paint.get("model-color-use-theme").constantOr("default")==="none",Ue=_.paint.get("model-emissive-strength").constantOr(0),Ye={defines:[]},st=[],ot=p.shadowRenderer;ot&&(ot.useNormalOffset=!1),M8e(Ye.defines,st,fe,p,De?null:_.lut);let mt=null;if(Te&&(mt=Wmt(Gmt,N.nodeModelMatrix,p.transform),se.projection.name!=="globe")){const as=fe.aabb.min,Et=fe.aabb.max,[$t,Jt]=Te.getOpacityForBounds(mt,as[0],as[1],Et[0],Et[1]);Ye.overrideFog=$t>=OY||Jt>=OY}const lt=l$(p,_.paint.get("model-cutoff-fade-range"));lt.shouldRenderCutoff&&Ye.defines.push("RENDER_CUTOFF");const yt=p.getOrCreateProgram("model",Ye),Nt=v8e(N.worldViewProjection,ZC,pM,null,p,z,be.baseColorFactor,xe.emissiveFactor,be.metallicFactor,be.roughnessFactor,xe,Ue,_,void 0,void 0,N.materialOverride,N.modelColor,1,yt.fixedDefines.includes("LIGHTING_3D_MODE"));p.uploadCommonUniforms(H,yt,null,mt,lt,N.lightOverrides),p.renderPass!=="shadow"&&ot&&ot.setupShadowsFromMatrix(N.nodeModelMatrix,yt),yt.draw(p,H.gl.TRIANGLES,Z,M,F,fe.material.doubleSided?ky.disabled:ky.backCCW,Nt,_.id,fe.vertexBuffer,fe.indexBuffer,fe.segments,_.paint,p.transform.zoom,void 0,st)}function Kmt(N,p){return N.style._importedAsBasemap?"basemap":p.scope}function I8e(N,p,_,A,M,F,z,H,Z,se,fe){const xe=N.transform,be=!!p.isGeometryBloom&&p.isGeometryBloom;if(p.minZoom!==void 0&&N.transform.zoomp.maxZoom||be&&N.renderPass==="shadow")return;const Te=xe.projection.name==="globe"?xle(_,xe):[..._];E(Te,Te,p.globalMatrix);const De=E([],A,Te);if(p.meshes)for(const Ue of p.meshes){const Ye=H.get(Ue.material.name);if(Ye&&Ye.opacity<=0)continue;if(Ue.material.alphaMode!=="BLEND"){z.push({mesh:Ue,depth:0,modelIndex:M,worldViewProjection:De,nodeModelMatrix:Te,isLightMesh:be,materialOverride:Ye,modelOpacity:Z,modelColor:se,lightOverrides:fe,node:p,modelMatrix:_});continue}const st=Xe([],Ue.centroid,De);!xe.isOrthographic&&st[2]<=0||F.push({mesh:Ue,depth:st[2],modelIndex:M,worldViewProjection:De,nodeModelMatrix:Te,isLightMesh:be,materialOverride:Ye,modelOpacity:Z,modelColor:se,lightOverrides:fe,node:p,modelMatrix:_})}if(p.children)for(const Ue of p.children)I8e(N,Ue,_,A,M,F,z,H,Z,se,fe)}function iZ(N,p,_,A,M){const F=_.shadowRenderer;if(!F)return;const z=F.getShadowPassDepthMode(),H=M||F.calculateShadowPassMatrixFromMatrix(p),Z=Lmt(H);_.getOrCreateProgram("modelDepth").draw(_,_.context.gl.TRIANGLES,z,pj.disabled,jh.disabled,ky.disabled,Z,A.id,N.vertexBuffer,N.indexBuffer,N.segments,A.paint,_.transform.zoom,void 0,void 0)}function Ymt(N,p,_,A){const M=function(fe,xe){if(xe.footprintDebugMesh)return xe.footprintDebugMesh;if(!xe.footprint)return null;const be=fe.context,Te=xe.footprint.vertices,De=xe.footprint.indices,Ue=new Hs;Ue.reserve(Te.length);for(const Jt of Te)Ue.emplaceBack(Jt.x,Jt.y);const Ye=new Vr;Ye.reserve(De.length);for(let Jt=0;Jt0){const be=F.terrain,Te=be.findDEMTileFor(H);Te&&Te.dem?Z=Y9.create(be,H,Te):xe=0}if(xe===0&&(z.terrainElevationMin=0,z.terrainElevationMax=0),xe===z.validForExaggeration&&(xe===0||Z&&Z._demTile&&Z._demTile.tileID===z.validForDEMTile.id&&Z._dem._timestamp===z.validForDEMTile.timestamp))return!1;for(const be in z.instancesPerModel){const Te=z.instancesPerModel[be];for(let De=0;Dese&&(se=Te.max)}const fe=ta(A.x,F,z)-A.x,xe=ta(A.y,H,Z)-A.y,be=eu(se,p.center.lat)-A.z;return p._zoomFromMercatorZ(Math.sqrt(fe*fe+xe*xe+be*be))}function Xmt(N,p,_,A,M,F,z){const H=N.context,Z=N.renderPass==="shadow",se=N.shadowRenderer,fe=Z&&se?se.getShadowPassDepthMode():new Ny(H.gl.LEQUAL,Ny.ReadWrite,N.depthRangeFor3D),xe=N.isTileAffectedByFog(F),be=N.transform.projection.name==="globe";if(_.meshes)for(const Te of _.meshes){const De=be?[]:["MODEL_POSITION_ON_GPU"],Ue=[];let Ye,st,ot;const mt=!be&&A.instancedDataArray.length>20;mt&&De.push("INSTANCED_ARRAYS");const lt=l$(N,p.paint.get("model-cutoff-fade-range"));if(lt.shouldRenderCutoff&&De.push("RENDER_CUTOFF"),Z&&se)Ye=N.getOrCreateProgram("modelDepth",{defines:De}),st=Lmt(z.shadowTileMatrix,z.shadowTileMatrix,_.globalMatrix),ot=jh.disabled;else{M8e(De,Ue,Te,N,p.paint.get("model-color-use-theme").constantOr("default")==="none"?null:p.lut),Ye=N.getOrCreateProgram("model",{defines:De,overrideFog:xe});const Nt=Te.material,as=Nt.pbrMetallicRoughness,Et=p.paint.get("model-opacity").constantOr(1),$t=p.paint.get("model-emissive-strength").constantOr(0);st=v8e(F.expandedProjMatrix,_.globalMatrix,ops,null,N,Et,as.baseColorFactor,Nt.emissiveFactor,as.metallicFactor,as.roughnessFactor,Nt,$t,p,M,void 0,void 0,void 0,1,Ye.fixedDefines.includes("LIGHTING_3D_MODE")),se&&(z.shadowUniformsInitialized?Ye.setShadowUniformValues(H,se.getShadowUniformValues()):(se.setupShadows(F.toUnwrapped(),Ye,"model-tile"),z.shadowUniformsInitialized=!0)),ot=lt.shouldRenderCutoff||Et<1||Nt.alphaMode!=="OPAQUE"?jh.alphaBlended:jh.unblended}N.uploadCommonUniforms(H,Ye,F.toUnwrapped(),null,lt);const yt=Te.material.doubleSided?ky.disabled:ky.backCCW;if(mt)Ue.push(A.instancedDataBuffer),Ye.draw(N,H.gl.TRIANGLES,fe,pj.disabled,ot,yt,st,p.id,Te.vertexBuffer,Te.indexBuffer,Te.segments,p.paint,N.transform.zoom,void 0,Ue,A.instancedDataArray.length);else{const Nt=Z?"u_instance":"u_normal_matrix";for(let as=0;as0)if(N.targetLod<0)N.targetLod=p>A?1:0;else{const z=M>0?_/1e3/M:1;N.targetLod=ta(p>A?N.targetLod+z:N.targetLod-z,0,1)}else N.targetLod=0}function gps(N,p,_,A){if(!_.modelManager)return!0;const M=_.modelManager;if(!_.shadowRenderer)return!0;const F=_.shadowRenderer,z=p.aabb;let H=!0,Z=N.maxHeight;if(Z===0){let fe=0;for(const xe in N.instancesPerModel){const be=M.getModel(xe,A);be?fe=Math.max(fe,Math.max(Math.max(be.aabb.max[0],be.aabb.max[1]),be.aabb.max[2])):H=!1}Z=N.maxScale*fe*1.41+N.maxVerticalOffset,H&&(N.maxHeight=Z)}z.max[2]=Z,z.min[2]+=N.terrainElevationMin,z.max[2]+=N.terrainElevationMax,Xe(z.min,z.min,p.tileMatrix),Xe(z.max,z.max,p.tileMatrix);const se=z.intersects(F.getCurrentCascadeFrustum());return _.currentShadowCascade===0&&(N.isInsideFirstShadowMapFrustum=se===2),se===0}function xps(N,p){const _=N.uniformValues.u_cutoff_params[0],A=N.uniformValues.u_cutoff_params[1],M=N.uniformValues.u_cutoff_params[2],F=N.uniformValues.u_cutoff_params[3];return A===_||F===M?1:ta(((p-_)/(A-_)-M)/(F-M),0,1)}function yps(N,p,_,A){if(p.pitch<20)return 1;const M=p.getWorldToCameraMatrix();E(M,M,N);const F=ts(_.min[0],_.min[1],_.min[2],1);let z=Ft(qt(),F,M),H=z,Z=z;F[1]=_.max[1],z=Ft(qt(),F,M),H=z[1]Z[1]?z:Z,F[0]=_.max[0],z=Ft(qt(),F,M),H=z[1]Z[1]?z:Z,F[1]=_.min[1],z=Ft(qt(),F,M),H=z[1]Z[1]?z:Z;const se=ta(A[0],0,1),fe=100*p.pixelsPerMeter*ta(A[1],0,1),xe=ta(A[2],0,1),be=(Ue=qt(),lt=(Ye=H)[1],yt=Ye[2],Nt=Ye[3],Ue[0]=(mt=Ye[0])+(ot=se)*((st=Z)[0]-mt),Ue[1]=lt+ot*(st[1]-lt),Ue[2]=yt+ot*(st[2]-yt),Ue[3]=Nt+ot*(st[3]-Nt),Ue),Te=Math.tan(.5*p.fovX),De=-be[2]*Te;var Ue,Ye,st,ot,mt,lt,yt,Nt;if(fe===0)return be[1]<-Math.abs(De)?xe:1;const as=ta(ya(1,xe,(-Math.abs(De)-be[1])/fe),xe,1);return ya(1,as,ta((p.pitch-20)/20,0,1))}var L8e=` #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`,Qmt=` #define FLIP_VIEWPORT_UV_Y(uv) #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;}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 );int viewport_dither_index(vec2 fragCoordXY) {return (int(fragCoordXY.x) % 4)*4+(int(fragCoordXY.y) % 4);} #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 premultiplyColor(vec3 nonPremultipliedColor,float a) {return vec4(nonPremultipliedColor*a,a);}vec3 unpremultiplyColor(vec4 premultipliedColor) {if (premultipliedColor.a > 0.0) {return premultipliedColor.rgb/premultipliedColor.a;}return premultipliedColor.rgb;}vec3 applyLUT(highp sampler3D lut,vec3 col) {vec3 size=vec3(textureSize(lut,0));vec3 uvw=(col.rbg*float(size-1.0)+0.5)/size;return texture(lut,uvw).rgb;}vec4 applyLUT(highp sampler3D lut,vec4 premultipliedColor) {return premultiplyColor(applyLUT(lut,unpremultiplyColor(premultipliedColor)),premultipliedColor.a);}void storeEmissiveColor(vec4 color,float emissiveStrength) { #ifdef DUAL_SOURCE_BLENDING glFragColorSrc1=vec4(vec3(0.0),emissiveStrength); #else #ifdef USE_MRT1 #ifdef USE_MRT1_RGBA out_Target1=vec4(color.rgb*emissiveStrength,color.a); #else out_Target1=vec4(emissiveStrength*color.a,0.0,0.0,glFragColor.a); #endif #endif #endif }`,Jmt=` #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);} #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 `,eft="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;}",tft=` #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; #endif vec3 elevationVector(vec2 pos) { #ifdef PROJECTION_GLOBE_VIEW 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 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 }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);} #endif float elevation(vec2 apos) { #ifdef TERRAIN #ifdef TERRAIN_VERTEX_MORPHING float nextElevation=currentElevation(apos);float prevElevation=prevElevation(apos);return mix(prevElevation,nextElevation,u_dem_lerp); #else return currentElevation(apos); #endif #else 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 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;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;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`,sft=`#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`,nft=`#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;FLIP_VIEWPORT_UV_Y(uv);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`,R8e=` #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`,rft=`#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`,aft=`#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`,ift=`#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;highp vec2 shadow_map_ndc_to_uv(highp vec2 ndc_xy) {return ndc_xy*0.5+0.5;}highp vec3 shadow_map_ndc_to_sample_space(highp vec3 ndc) {return vec3(shadow_map_ndc_to_uv(ndc.xy),ndc.z*0.5+0.5);}float shadow_sample(sampler2DShadow shadowmap,highp vec3 pos,highp float bias) {highp vec3 coord=vec3(shadow_map_ndc_to_uv(pos.xy),pos.z*0.5+0.5-bias);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=shadow_map_ndc_to_sample_space(light_view_pos0.xyz/light_view_pos0.w);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 oft=/^#include\s+"([^"]+)"\s*\r?\n/gm,lft=/#pragma mapbox: ([\w\-]+) ([\w]+) ([\w]+) ([\w]+)/g,vps=/\b[A-Za-z_][A-Za-z0-9_]*\b/g,bps=new Set(["ifdef","ifndef","elif","if","defined"]),$le=new Set;c$(L8e,$le),c$(Jmt,$le),c$(Qmt,$le);const cft={"_prelude_fog.vertex.glsl":sft,"_prelude_terrain.vertex.glsl":tft,"_prelude_shadow.vertex.glsl":aft,"_prelude_material_table.vertex.glsl":"","_prelude_fog.fragment.glsl":nft,"_prelude_shadow.fragment.glsl":ift,"_prelude_lighting.glsl":R8e,"_prelude_raster_array.glsl":rft,"_prelude_indicator_cutout.fragment.glsl":` vec4 applyCutout(vec4 color,float height) {return color;}`,"_prelude_feature_cutout.fragment.glsl":`// feature cutout (gl-native only) `,"_prelude_feature_cutout.vertex.glsl":`// feature cutout (gl-native only) `},Ule={},dft="precision highp float;",uft="precision mediump float;",hft=` #if defined(GL_EXT_blend_func_extended) && defined(DUAL_SOURCE_BLENDING) #extension GL_EXT_blend_func_extended : require #endif`,mft={preludeTerrain:fd("",tft),preludeFog:fd(nft,sft),preludeShadow:fd(ift,aft),preludeRasterArray:fd(rft,""),preludeLighting:fd(R8e,R8e),preludePrecisionQualifiers:fd(uft,dft),prelude:fd(Qmt,Jmt),preludeExtensions:fd(hft,"")},_ps=[hft,uft,L8e,mft.prelude.fragmentSource].join(` `),wps=[dft,L8e,mft.prelude.vertexSource].join(` `);var jps={background:fd(`#include "_prelude_fog.fragment.glsl" #include "_prelude_feature_cutout.fragment.glsl" uniform vec4 u_color;uniform float u_opacity;uniform mediump float u_emissive_strength; #ifdef LIGHTING_3D_MODE in vec4 v_color; #endif void main() {vec4 out_color; #ifdef LIGHTING_3D_MODE out_color=v_color; #else out_color=u_color; #endif #ifdef FOG out_color=fog_dither(fog_apply_premultiplied(out_color,v_fog_pos)); #endif glFragColor=out_color*u_opacity;storeEmissiveColor(glFragColor,u_emissive_strength); #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); #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 }`),backgroundPattern:fd(`#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;storeEmissiveColor(glFragColor,u_emissive_strength); #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 }`),circle:fd(`#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:fd("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:fd(`#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_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:fd(`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:fd("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:fd("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:fd("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 }`),fill:fd(`#include "_prelude_fog.fragment.glsl" #include "_prelude_lighting.glsl" #include "_prelude_shadow.fragment.glsl" #include "_prelude_indicator_cutout.fragment.glsl" #include "_prelude_feature_cutout.fragment.glsl" #pragma mapbox: define highp vec4 color #pragma mapbox: define lowp float opacity uniform float u_emissive_strength;uniform lowp float u_opacity_multiplier; #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 void main() { #pragma mapbox: initialize highp vec4 color #pragma mapbox: initialize lowp float opacity vec2 cutout_factors=vec2(0.0);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*u_opacity_multiplier);glFragColor=out_color;storeEmissiveColor(glFragColor,u_emissive_strength); #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 uniform mat4 u_matrix;uniform lowp float u_opacity_multiplier; #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 }`),fillOutline:fd(`#include "_prelude_fog.fragment.glsl" #include "_prelude_lighting.glsl" #include "_prelude_shadow.fragment.glsl" #include "_prelude_feature_cutout.fragment.glsl" in highp vec2 v_pos;uniform float u_emissive_strength;uniform lowp float u_opacity_multiplier; #ifdef ELEVATED_ROADS in highp float v_road_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 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 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 glFragColor=out_color*(alpha*opacity*u_opacity_multiplier);storeEmissiveColor(glFragColor,u_emissive_strength); #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 uniform mat4 u_matrix;uniform vec2 u_world;uniform lowp float u_opacity_multiplier;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;v_road_z_offset=z_offset; #endif float hidden=float(opacity==0.0);gl_Position=mix(u_matrix*vec4(a_pos,z_offset,1),AWAY,hidden);v_pos=(gl_Position.xy/gl_Position.w+1.0)/2.0*u_world; #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:fd(`#include "_prelude_fog.fragment.glsl" #include "_prelude_lighting.glsl" #include "_prelude_shadow.fragment.glsl" #include "_prelude_feature_cutout.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;uniform lowp float u_opacity_multiplier; #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 #ifdef ELEVATED_ROADS in highp float v_road_z_offset; #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=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 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 glFragColor=out_color*(alpha*opacity*u_opacity_multiplier);storeEmissiveColor(glFragColor,u_emissive_strength); #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 lowp float u_opacity_multiplier;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;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;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);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);v_pos_world=(gl_Position.xy/gl_Position.w+1.0)/2.0*u_world; #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:fd(`#include "_prelude_fog.fragment.glsl" #include "_prelude_lighting.glsl" #include "_prelude_shadow.fragment.glsl" #include "_prelude_feature_cutout.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;uniform lowp float u_opacity_multiplier; #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 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 FOG out_color=fog_dither(fog_apply_premultiplied(out_color,v_fog_pos)); #endif glFragColor=out_color*(opacity*u_opacity_multiplier);storeEmissiveColor(glFragColor,u_emissive_strength); #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 lowp float u_opacity_multiplier;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:fd(`uniform highp sampler2D u_image;uniform float u_opacity;uniform int u_blend_mode;uniform highp float u_max_density;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;}highp float density=color.a;vec3 avgColor=color.rgb/max(density,0.001);highp float n=density/max(u_max_density,0.001);highp float t=sqrt(n/(n+1.0));glFragColor=vec4(avgColor*t,t);} 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;}"),lineBlendReduce:fd("uniform highp sampler2D u_image;uniform vec2 u_texel_size;uniform bool u_first_pass;in vec2 v_pos;void main() {vec2 o=u_texel_size*0.5;vec4 s0=texture(u_image,v_pos+vec2(-o.x,-o.y));vec4 s1=texture(u_image,v_pos+vec2( o.x,-o.y));vec4 s2=texture(u_image,v_pos+vec2(-o.x, o.y));vec4 s3=texture(u_image,v_pos+vec2( o.x, o.y));float r0; float g0;float r1; float g1;float r2; float g2;float r3; float g3;if (u_first_pass) {float a0=s0.a;float a1=s1.a;float a2=s2.a;float a3=s3.a;r0=a0; g0=a0 > 0.0 ? 1.0 : 0.0;r1=a1; g1=a1 > 0.0 ? 1.0 : 0.0;r2=a2; g2=a2 > 0.0 ? 1.0 : 0.0;r3=a3; g3=a3 > 0.0 ? 1.0 : 0.0;} else {r0=s0.r; g0=s0.g;r1=s1.r; g1=s1.g;r2=s2.r; g2=s2.g;r3=s3.r; g3=s3.g;}glFragColor=vec4((r0+r1+r2+r3)*0.25,(g0+g1+g2+g3)*0.25,0.0,0.0);}","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:fd(`#include "_prelude_fog.fragment.glsl" #include "_prelude_shadow.fragment.glsl" #include "_prelude_lighting.glsl" #include "_prelude_indicator_cutout.fragment.glsl" #include "_prelude_feature_cutout.fragment.glsl" in vec4 v_color;in vec4 v_flat; #if defined(RENDER_FRONT_CUTOFF) || defined(ROUTE_CORRIDOR) in float v_dither_opacity; #endif #ifdef RENDER_SHADOWS in highp vec4 v_pos_light_view_0;in highp vec4 v_pos_light_view_1; #endif uniform lowp float u_opacity; #ifdef FAUX_AO uniform lowp vec2 u_ao;in vec2 v_ao; #endif #if defined(ZERO_ROOF_RADIUS) && !defined(LIGHTING_3D_MODE) in vec4 v_roof_color; #endif #if defined(ZERO_ROOF_RADIUS) || defined(RENDER_SHADOWS) || defined(LIGHTING_3D_MODE) in highp vec3 v_normal; #endif uniform vec3 u_flood_light_color;uniform highp float u_vertical_scale;uniform float u_flood_light_intensity;uniform vec3 u_ground_shadow_factor; #if defined(LIGHTING_3D_MODE) && defined(FLOOD_LIGHT) in float v_flood_radius;in float v_has_floodlight; #endif in float v_height; #pragma mapbox: define highp float emissive_strength void main() { #pragma mapbox: initialize highp float emissive_strength #if defined(ZERO_ROOF_RADIUS) || defined(RENDER_SHADOWS) || defined(LIGHTING_3D_MODE) vec3 normal=normalize(v_normal); #endif float z;vec4 color=v_color; #ifdef ZERO_ROOF_RADIUS z=float(normal.z > 0.00001); #ifdef LIGHTING_3D_MODE normal=mix(normal,vec3(0.0,0.0,1.0),z); #else color=mix(v_color,v_roof_color,z); #endif #endif float h=max(0.0,v_height);float ao_shade=1.0; #ifdef FAUX_AO float intensity=u_ao[0];float h_floors=h/(u_ao[1]*u_vertical_scale);float y_shade=1.0-0.9*intensity*min(v_ao.y,1.0);ao_shade=(1.0-0.08*intensity)*(y_shade+(1.0-y_shade)*(1.0-pow(1.0-min(h_floors/16.0,1.0),16.0)))+0.08*intensity*min(h_floors/160.0,1.0);float concave=v_ao.x*v_ao.x; #ifdef ZERO_ROOF_RADIUS concave*=(1.0-z); #endif float x_shade=mix(1.0,mix(0.6,0.75,min(h_floors/30.0,1.0)),intensity)+0.1*intensity*min(h,1.0);ao_shade*=mix(1.0,x_shade*x_shade*x_shade,concave); #ifdef LIGHTING_3D_MODE #ifdef FLOOD_LIGHT color.rgb*=mix(ao_shade,1.0,v_has_floodlight); #else color.rgb*=ao_shade; #endif #else color.rgb*=ao_shade; #endif #endif #ifdef LIGHTING_3D_MODE float flood_radiance=0.0; #ifdef FLOOD_LIGHT flood_radiance=(1.0-min(h/v_flood_radius,1.0))*u_flood_light_intensity*v_has_floodlight; #endif #ifdef RENDER_SHADOWS #ifdef FLOOD_LIGHT float ndotl_unclamped=dot(normal,u_shadow_direction);float ndotl=max(0.0,ndotl_unclamped);float occlusion=ndotl_unclamped < 0.0 ? 1.0 : shadow_occlusion(ndotl,v_pos_light_view_0,v_pos_light_view_1,1.0/gl_FragCoord.w);vec3 litColor=apply_lighting(color.rgb,normal,(1.0-u_shadow_intensity*occlusion)*ndotl);vec3 floodLitColor=compute_flood_lighting(u_flood_light_color*u_opacity,1.0-u_shadow_intensity,occlusion,u_ground_shadow_factor);color.rgb=mix(litColor,floodLitColor,flood_radiance); #else float shadowed_lighting_factor; #ifdef RENDER_CUTOFF shadowed_lighting_factor=shadowed_light_factor_normal_opacity(normal,v_pos_light_view_0,v_pos_light_view_1,1.0/gl_FragCoord.w,v_cutoff_opacity);if (v_cutoff_opacity==0.0) {discard;} #else shadowed_lighting_factor=shadowed_light_factor_normal(normal,v_pos_light_view_0,v_pos_light_view_1,1.0/gl_FragCoord.w); #endif color.rgb=apply_lighting(color.rgb,normal,shadowed_lighting_factor); #endif #else color.rgb=apply_lighting(color.rgb,normal); #ifdef FLOOD_LIGHT color.rgb=mix(color.rgb,u_flood_light_color*u_opacity,flood_radiance); #endif #endif color.rgb=mix(color.rgb,v_flat.rgb,emissive_strength);color*=u_opacity; #endif #ifdef FOG color=fog_dither(fog_apply_premultiplied(color,v_fog_pos,h)); #endif #if defined(RENDER_FRONT_CUTOFF) || defined(ROUTE_CORRIDOR) if (v_dither_opacity < 1.0) {int index=viewport_dither_index(gl_FragCoord.xy);if (v_dither_opacity < DITHER_THRESHOLDS[index]) {discard;}} #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" #include "_prelude_feature_cutout.vertex.glsl" uniform mat4 u_matrix; #ifndef LIGHTING_3D_MODE uniform vec3 u_lightcolor;uniform lowp vec3 u_lightpos;uniform lowp float u_lightintensity; #endif 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; #if defined(RENDER_FRONT_CUTOFF) || defined(ROUTE_CORRIDOR) #ifdef RENDER_FRONT_CUTOFF uniform vec3 u_front_cutoff_params; #endif out float v_dither_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;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) || defined(ROUTE_CORRIDOR) 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_FRONT_CUTOFF) || defined(ROUTE_CORRIDOR) float frontCutoffOpacity=1.0;float routeFade=0.0; #endif #if defined(RENDER_CUTOFF) || defined(RENDER_FRONT_CUTOFF) vec4 ground=u_matrix*vec4(centroid_decoded,ele,1.0); #endif #ifdef RENDER_CUTOFF cutoff=cutoff_opacity(u_cutoff_params,ground.z);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 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);frontCutoffOpacity=mix(u_front_cutoff_params.z,1.0,t);} #endif #if defined(RENDER_FRONT_CUTOFF) || defined(ROUTE_CORRIDOR) v_dither_opacity=1.0; #ifdef RENDER_FRONT_CUTOFF v_dither_opacity=min(v_dither_opacity,frontCutoffOpacity); #endif #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 }`),fillExtrusionPattern:fd(`#include "_prelude_fog.fragment.glsl" #include "_prelude_lighting.glsl" #include "_prelude_indicator_cutout.fragment.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 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; #ifndef LIGHTING_3D_MODE uniform vec3 u_lightcolor;uniform lowp vec3 u_lightpos;uniform lowp float u_lightintensity; #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 #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 }`),hillshadePrepare:fd(`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:fd(`#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 storeEmissiveColor(glFragColor,u_emissive_strength); #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:fd(`#include "_prelude_fog.fragment.glsl" #include "_prelude_lighting.glsl" #include "_prelude_shadow.fragment.glsl" #include "_prelude_indicator_cutout.fragment.glsl" #include "_prelude_feature_cutout.fragment.glsl" uniform lowp float u_device_pixel_ratio;uniform highp float u_width_scale;uniform float u_alpha_discard_threshold;uniform lowp float u_opacity_multiplier;uniform bool u_clip_to_tile_borders;in vec4 v_width2_dilute;in vec2 v_normal;in float v_gamma_scale;in vec2 v_tile_pos; #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;uniform highp float u_floor_width_scale;in highp vec2 v_tex; #endif #ifdef DEBUG_ELEVATION_ID in vec3 v_elevation_id_col; #endif #if defined(RENDER_LINE_GRADIENT) || defined(RENDER_LINE_BORDER_GRADIENT) || defined(RENDER_LINE_TRIM_OFFSET) in highp vec3 v_uv; #endif #ifdef RENDER_LINE_GRADIENT uniform sampler2D u_gradient_image; #endif #ifdef RENDER_LINE_BORDER_GRADIENT uniform sampler2D u_border_gradient_image; #endif #ifdef RENDER_LINE_TRIM_OFFSET 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; #endif #ifdef RENDER_SHADOWS uniform bool u_emissive_in_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;float ANTIALIASING=1.0/u_device_pixel_ratio/2.0; #ifdef RENDER_LINE_BORDER #ifndef VARIABLE_LINE_WIDTH ANTIALIASING*=8.0; #endif #endif #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);float pxStep;float delta; #ifdef RENDER_LINE_BORDER #ifndef VARIABLE_LINE_WIDTH pxStep=fwidth(dist);float out_edge=v_width2_dilute.x-dist;float in_edge=dist-(v_width2_dilute.y-2.0*ANTIALIASING);delta=v_width2_dilute.y > 0.0 ? min(in_edge,out_edge) : out_edge;float edge=ANTIALIASING;alpha=delta > 0.0 ? smoothstep(edge-pxStep,u_width_scale*blur+edge+pxStep,delta) : 0.0; #endif #endif #ifdef RENDER_LINE_DASH highp float dash_w=float(dash.w);highp float dash_len=float(dash.z)+dash_w/65535.0;float sdfgamma=ANTIALIASING/float(dash_len);float scaled_floorwidth=(floorwidth*u_floor_width_scale);float periods_per_pixel=fwidth(v_tex.x);float dash_coverage=float(dash.y >> 4u)/4095.0;float fade=linearstep(0.25,0.5,periods_per_pixel);float gamma=max(sdfgamma/scaled_floorwidth,0.5*periods_per_pixel);if (fade >=1.0) {alpha*=dash_coverage;} else if (periods_per_pixel < 0.1) {float sdfdist=texture(u_dash_image,v_tex).r;alpha*=linearstep(0.5-gamma,0.5+gamma,sdfdist);} else {float span=min(periods_per_pixel,1.0);float tap_offset=span*0.25;float sdf0=texture(u_dash_image,vec2(v_tex.x-tap_offset,v_tex.y)).r;float sdf1=texture(u_dash_image,vec2(v_tex.x+tap_offset,v_tex.y)).r;alpha*=mix(0.5*( linearstep(0.5-gamma,0.5+gamma,sdf0)+linearstep(0.5-gamma,0.5+gamma,sdf1) ),dash_coverage,fade);} #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 edge2=border_width*u_width_scale+ANTIALIASING;float alpha2=smoothstep(edge2-pxStep,edge2+pxStep,delta);if (alpha2 < 1.) { #ifdef RENDER_LINE_BORDER_GRADIENT vec4 border_gradient_color=texture(u_border_gradient_image,v_uv.xy);out_color=mix(border_gradient_color*trim_alpha,out_color,alpha2); #else if (border_color.a==0.0) { #ifndef RENDER_LINE_GRADIENT 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-alpha2));} else {out_color.rgb*=(0.6+0.4*alpha2);} #else out_color.rgb*=(0.6+0.4*alpha2); #endif } else {out_color=mix(border_color*trim_alpha,out_color,alpha2);} #endif out_color*=v_width2_dilute.w;} #endif #endif vec2 cutout_factors=vec2(0.0); #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*u_opacity_multiplier); #ifdef LINE_BLEND_ADDITIVE {float cov=alpha*diluted_opacity;glFragColor=vec4(cov > 0.0 ? out_color.rgb/cov : vec3(0.0),cov);} #else #ifdef LINE_BLEND_MULTIPLY glFragColor=vec4(out_color.rgb+(1.0-out_color.a),1.0); #else glFragColor=out_color; #endif #endif storeEmissiveColor(glFragColor,emissive_strength); #ifdef OVERDRAW_INSPECTOR glFragColor=vec4(1.0); #endif #ifdef DEBUG_ELEVATION_ID glFragColor=vec4(v_elevation_id_col,1.0); #endif if (u_clip_to_tile_borders) {if (v_tile_pos.x > 1.0 || v_tile_pos.y > 1.0 || v_tile_pos.x < 0.0 || v_tile_pos.y < 0.0) {discard;}}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) || defined(VARIABLE_LINE_EMISSIVE_STRENGTH) in vec4 a_z_offset_width; #endif #ifdef DEBUG_ELEVATION_ID in vec3 a_elevation_id_col; #endif #ifdef DEBUG_ELEVATION_ID out vec3 v_elevation_id_col; #endif #ifdef ELEVATION_GROUND_SCALE in float a_elevation_ground_scale; #endif #if defined(RENDER_LINE_GRADIENT) || defined(RENDER_LINE_BORDER_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 float u_z_offset;uniform highp float u_road_view_depth_bias;uniform highp vec4 u_road_clip_to_view; #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 vec2 v_tile_pos; #ifdef ELEVATED_ROADS out highp float v_road_z_offset; #endif #ifdef VARIABLE_LINE_WIDTH out float stub_side;uniform float u_width_addition; #endif #ifdef RENDER_LINE_DASH uniform highp float u_floor_width_scale;uniform vec2 u_texsize;uniform float u_tile_units_to_pixels;out highp vec2 v_tex; #endif #if defined(RENDER_LINE_GRADIENT) || defined(RENDER_LINE_BORDER_GRADIENT) || defined(RENDER_LINE_TRIM_OFFSET) out highp vec3 v_uv; #endif #if defined(RENDER_LINE_GRADIENT) || defined(RENDER_LINE_BORDER_GRADIENT) uniform float u_image_height; #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 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 #ifdef VARIABLE_LINE_EMISSIVE_STRENGTH emissive_strength=a_z_offset_width.w; #endif float a_z_offset=u_z_offset; #if defined(ELEVATED) || defined(ELEVATED_ROADS) a_z_offset+=a_z_offset_width.x; #endif #ifdef DEBUG_ELEVATION_ID v_elevation_id_col=a_elevation_id_col; #endif highp float line_progress=0.0; #if defined(RENDER_LINE_GRADIENT) || defined(RENDER_LINE_BORDER_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; #ifdef RENDER_LINE_BORDER #ifndef VARIABLE_LINE_WIDTH ANTIALIASING*=8.0; #endif #endif 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;gapwidth=gapwidth/2.0;float halfwidth;float dilute_scale=1.0;float dilute_border_scale=1.0;float symmetric_outset=0.0; #ifdef VARIABLE_LINE_WIDTH float left_width=a_z_offset_width.y;float right_width=a_z_offset_width.z;bool zero_right_width=border_width==0.0 && right_width==0.0;halfwidth=left ? left_width : right_width;halfwidth+=u_width_addition*(zero_right_width ? (left ? 1.0 : 0.0) : 0.5); halfwidth*=u_width_scale;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*=apply;}offset=border_width > 0.0 ? (left_width+right_width+u_width_addition)*u_width_scale : offset;halfwidth=border_width > 0.0 ? border_width*u_width_scale*0.5 : halfwidth;symmetric_outset=zero_right_width ? u_width_scale*(left_width+u_width_addition) : halfwidth;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 ? ANTIALIASING : 0.0);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;v_tile_pos=pos+offset2*u_pixels_to_tile_units;gl_Position=u_matrix*vec4(v_tile_pos,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 v_tile_pos=offset_pos;gl_Position=u_matrix*vec4(v_tile_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 v_tile_pos=pos+offset2*u_pixels_to_tile_units;gl_Position=u_matrix*vec4(v_tile_pos,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 if (gapwidth > 0.0) {float visible_ratio=(halfwidth+ANTIALIASING)/outset;vec2 visible_screen_width=screen_width*visible_ratio;float max_visible_component=max(visible_screen_width.x,visible_screen_width.y);dilute_scale=min(1.0,max_visible_component/min_pixel);}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 v_tile_pos=(v_tile_pos+extrude)/EXTENT; #ifdef ELEVATED_ROADS gl_Position=gl_Position+projected_extrude; #ifdef VARIABLE_LINE_WIDTH #ifndef ELEVATED highp float road_view_depth_bias=u_road_view_depth_bias*smoothstep(-0.5,0.0,a_z_offset);if (road_view_depth_bias > 0.0) {highp float z_in=gl_Position.z/gl_Position.w*0.5+0.5;highp float a=u_road_clip_to_view.x;highp float b=u_road_clip_to_view.y;highp float c=u_road_clip_to_view.z;highp float d=u_road_clip_to_view.w;highp float view=(a*z_in+b)/(c*z_in+d);highp float view_new=view+road_view_depth_bias;highp float z_new=(view_new*d-b)/(a-view_new*c);z_new=clamp(z_new,0.0,1.0);gl_Position.z=(z_new*2.0-1.0)*gl_Position.w;} #endif #endif #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_BORDER_GRADIENT) || defined(RENDER_LINE_TRIM_OFFSET) highp float a_uv_x=a_packed[0];float a_split_index=a_packed[1]; #if defined(RENDER_LINE_GRADIENT) || defined(RENDER_LINE_BORDER_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);highp float dash_w=float(dash.w);highp float totalLength=float(dash.z)+dash_w/65535.0;float scale=totalLength==0.0 ? 0.0 : u_tile_units_to_pixels/totalLength;float dash_half_height=float(dash.y & 15u);v_tex=vec2(a_linesofar*scale/(floorwidth*u_floor_width_scale),(-normal.y*dash_half_height+dashf.x+0.5)/u_texsize.y); #endif v_width2_dilute=vec4(outset,inset,dilute_scale,dilute_border_scale); #ifdef VARIABLE_LINE_WIDTH v_width2_dilute.x=symmetric_outset; #endif #ifdef FOG v_fog_pos=fog_position(pos); #endif }`),linePattern:fd(`#include "_prelude_fog.fragment.glsl" #include "_prelude_lighting.glsl" #include "_prelude_shadow.fragment.glsl" #include "_prelude_indicator_cutout.fragment.glsl" uniform highp float u_device_pixel_ratio;uniform highp float u_width_scale;uniform highp float u_alpha_discard_threshold;uniform lowp float u_opacity_multiplier;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 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*u_opacity_multiplier);if (u_alpha_discard_threshold !=0.0) {if (color.a < u_alpha_discard_threshold) {discard;}}glFragColor=color;storeEmissiveColor(glFragColor,emissive_strength); #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 vec4 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 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 }`),raster:fd(`#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;uniform highp float u_color_ramp_size; #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; #ifdef RASTER_COLOR_SCALE_LOG float N=u_color_ramp_size;float vNorm=max((value.x-0.5/N)*N/(N-1.0),0.0);vNorm=log(vNorm*(10.0-1.0)+1.0)/log(10.0);value.x=0.5/N+vNorm*(N-1.0)/N; #endif #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 storeEmissiveColor(glFragColor,u_emissive_strength);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 }`),symbol:fd(`#include "_prelude_lighting.glsl" #include "_prelude_shadow.fragment.glsl" #include "_prelude_indicator_cutout.fragment.glsl" #include "_prelude_feature_cutout.fragment.glsl" #define SDF_PX 8.0 #define SDF 1.0 #define ICON 0.0 uniform sampler2D u_texture; #ifdef RENDER_TEXT_AND_SYMBOL uniform sampler2D u_texture_icon; #endif uniform highp float u_gamma_scale;uniform lowp float u_device_pixel_ratio;uniform bool u_is_text;uniform bool u_is_sdf;uniform lowp float u_scale_factor;uniform lowp float u_opacity_multiplier; #ifdef ICON_TRANSITION uniform float u_icon_transition; #endif #ifdef COLOR_ADJUSTMENT uniform mat4 u_color_adj_mat; #endif #ifdef RENDER_SHADOWS in highp float v_z_offset; #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 in lowp float v_opacity;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; #ifdef LIGHTING_3D_MODE in lowp float v_emissive_strength; #endif void main() {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;if (u_is_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;}lowp float emissive_strength=0.0; #ifdef LIGHTING_3D_MODE emissive_strength=v_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*u_opacity_multiplier;glFragColor=texture(u_texture_icon,tex_icon)*alpha; #ifdef OVERDRAW_INSPECTOR glFragColor=vec4(1.0); #endif return;} #endif vec2 cutout_factors=vec2(0.0);if (u_is_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 }out_color*=opacity*fade_opacity*u_opacity_multiplier; #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 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 ELEVATED_ROADS in vec3 a_x_axis;in vec3 a_y_axis;uniform float u_normal_scale; #endif #ifdef RENDER_SHADOWS out highp float v_z_offset; #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; #ifdef RENDER_SHADOWS uniform mat4 u_inv_matrix; #endif 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; #ifdef PROJECTION_GLOBE_VIEW uniform vec3 u_up_vector; #endif #ifdef RENDER_TEXT_AND_SYMBOL uniform vec2 u_texsize_icon; #endif 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 #ifndef MAX_UBO_SIZE_VEC4 #define MAX_UBO_SIZE_VEC4 1024u #endif #define SPP_HEADER_SIZE_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;};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 highp float u_spp_z_offset;uniform lowp vec2 u_spp_translate_rotation;uniform highp float u_spp_zoom_fraction;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;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; #ifdef LIGHTING_3D_MODE out lowp float v_emissive_strength; #endif float zoomFactor(float zm,float zM) {if (zm==zM) return u_spp_zoom_fraction-zm >=0.0 ? 1.0 : 0.0;return clamp((u_spp_zoom_fraction-zm)/(zM-zm),0.0,1.0);}vec4 readColor(uint base,bool isDataDriven,uint offsetVec4,uint dzr,vec2 headerZoom,vec4 fallbackValue) {if (!isDataDriven) return fallbackValue;vec4 value=u_spp_properties.properties[base+offsetVec4];vec2 blockZoom=u_spp_properties.properties[base+offsetVec4+dzr].xy;vec2 zr=mix(headerZoom,blockZoom,float(dzr));return unpack_mix_color(value,zoomFactor(zr.x,zr.y));}uint uvec4At(uvec4 v,uint index) {return (index==0u) ? v.x : (index==1u) ? v.y : (index==2u) ? v.z : v.w;}float readScalar(uint base,bool isDataDriven,uint offsetVec4,float fallbackValue) {if (!isDataDriven) return fallbackValue;vec4 slot=u_spp_properties.properties[base+offsetVec4];return unpack_mix_vec2(slot.xy,zoomFactor(slot.z,slot.w));}vec2 readTranslate(uint base,bool isDataDriven,uint offsetVec4,uint dzr) {if (!isDataDriven) return vec2(0.0);vec4 value=u_spp_properties.properties[base+offsetVec4];vec2 blockZoom=u_spp_properties.properties[base+offsetVec4+dzr].xy;float t=zoomFactor(blockZoom.x,blockZoom.y)*float(dzr);return mix(value.xy,value.zw,t);}SymbolPaintProperties readSymbolPaintProperties() {uint dataDrivenMask=u_spp_header.header[0][0];uint dzrMask =u_spp_header.header[0][1];uint blockSizeVec4 =u_spp_header.header[0][2];uint fillColorDzr=dzrMask & 1u;uint haloColorDzr=(dzrMask >> 1u) & 1u;vec2 fillColorHeaderZoom=uintBitsToFloat(u_spp_header.header[3].xy);vec2 haloColorHeaderZoom=uintBitsToFloat(u_spp_header.header[3].zw);uint featureIndex=uint(a_feature_index);uvec4 indexSlot=u_spp_index.block_indices[featureIndex/4u];uint base=uvec4At(indexSlot,featureIndex % 4u)*blockSizeVec4;SymbolPaintProperties props;props.fill_np_color =readColor(base,(dataDrivenMask & (1u << 0u)) !=0u,u_spp_header.header[0][3],fillColorDzr,fillColorHeaderZoom,u_spp_fill_np_color);props.halo_np_color =readColor(base,(dataDrivenMask & (1u << 1u)) !=0u,u_spp_header.header[1][0],haloColorDzr,haloColorHeaderZoom,u_spp_halo_np_color);props.opacity =readScalar(base,(dataDrivenMask & (1u << 2u)) !=0u,u_spp_header.header[1][1],u_spp_opacity);props.halo_width =readScalar(base,(dataDrivenMask & (1u << 3u)) !=0u,u_spp_header.header[1][2],u_spp_halo_width);props.halo_blur =readScalar(base,(dataDrivenMask & (1u << 4u)) !=0u,u_spp_header.header[1][3],u_spp_halo_blur);props.emissive_strength=readScalar(base,(dataDrivenMask & (1u << 5u)) !=0u,u_spp_header.header[2][0],u_spp_emissive_strength);props.occlusion_opacity=readScalar(base,(dataDrivenMask & (1u << 6u)) !=0u,u_spp_header.header[2][1],u_spp_occlusion_opacity);props.z_offset =readScalar(base,(dataDrivenMask & (1u << 7u)) !=0u,u_spp_header.header[2][2],u_spp_z_offset);uint translateDzr=(dzrMask >> 8u) & 1u;props.translate =readTranslate(base,(dataDrivenMask & (1u << 8u)) !=0u,u_spp_header.header[2][3],translateDzr);return props;}vec2 unpack_opacity(uint packedOpacity) {return vec2(float(packedOpacity/2u)/127.0,float(packedOpacity & 1u));}void main() {SymbolPaintProperties paint_properties=readSymbolPaintProperties();lowp float opacity=paint_properties.opacity;v_opacity=opacity;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; #ifdef LIGHTING_3D_MODE v_emissive_strength=paint_properties.emissive_strength; #endif lowp float occlusion_opacity=paint_properties.occlusion_opacity;highp float z_offset=paint_properties.z_offset;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 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);{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;}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 RENDER_SHADOWS v_z_offset=e; #endif }`),skybox:fd(`#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 }`,eft),skyboxGradient:fd(`#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 }`,eft),skyboxCapture:fd(` 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);}"),globeAtmosphere:fd(`#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 glFragColor=vec4(0,0,0,1);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);}`),stars:fd(`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);}`),occlusion:fd("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 c$(N,p){const _=N.split(` `);for(let A of _){if(A=A.trimStart(),A[0]!=="#"||!A.includes("if")||A.startsWith("#endif"))continue;const M=A.match(vps);if(M)for(const F of M)bps.has(F)||p.add(F)}}function fft(N){return new Set(["uint","int","uvec2","ivec2","uvec3","ivec3","uvec4","ivec4"]).has(N)}function fd(N,p){const _=new Set,A=[],M=[];N=N.replace(oft,(z,H)=>(M.push(H),"")),p=p.replace(oft,(z,H)=>(A.push(H),""));let F=new Set($le);c$(N,F),c$(p,F);for(const z of[...A,...M])Ule[z]||(Ule[z]=new Set,c$(cft[z],Ule[z])),F=new Set([...F,...Ule[z]]);return{fragmentSource:N=N.replace(lft,(z,H,Z,se,fe)=>(_.add(fe),H==="define"?` #ifndef HAS_UNIFORM_u_${fe} ${fft(se)?"flat ":""}in ${Z} ${se} ${fe}; #else uniform ${Z} ${se} u_${fe}; #endif `:H==="initialize"?` #ifdef HAS_UNIFORM_u_${fe} ${Z} ${se} ${fe} = u_${fe}; #endif `:H==="define-attribute"?` #ifdef HAS_ATTRIBUTE_a_${fe} in ${Z} ${se} ${fe}; #endif `:H==="initialize-attribute"?"":void 0)),vertexSource:p=p.replace(lft,(z,H,Z,se,fe)=>{const xe=`MATERIAL_ATTRIBUTE_OFFSET_${fe}`,be=se==="float"?"vec2":se,Te=`GET_ATTRIBUTE_${be}(a_${fe}, materialInfo, ${xe})`,De=fe.includes("color")?"color":be;return H==="define-attribute-vertex-shader-only"?` #ifdef HAS_ATTRIBUTE_a_${fe} in ${Z} ${se} a_${fe}; #endif `:_.has(fe)?H==="define"?` #ifndef HAS_UNIFORM_u_${fe} uniform lowp float u_${fe}_t; #if !defined(${xe}) in ${Z} ${be} a_${fe}; #endif ${fft(se)?"flat ":""}out ${Z} ${se} ${fe}; #else uniform ${Z} ${se} u_${fe}; #endif `:H==="initialize"?De==="vec4"||De==="uvec4"?` #ifndef HAS_UNIFORM_u_${fe} ${fe} = a_${fe}; #else ${Z} ${se} ${fe} = u_${fe}; #endif `:` #if !defined(HAS_UNIFORM_u_${fe}) #ifdef ${xe} ${fe} = unpack_mix_${De}(${Te}, u_${fe}_t); #else ${fe} = unpack_mix_${De}(a_${fe}, u_${fe}_t); #endif #else ${Z} ${se} ${fe} = u_${fe}; #endif `:H==="define-attribute"?` #ifdef HAS_ATTRIBUTE_a_${fe} in ${Z} ${se} a_${fe}; out ${Z} ${se} ${fe}; #endif `:H==="initialize-attribute"?` #ifdef HAS_ATTRIBUTE_a_${fe} ${fe} = a_${fe}; #endif `:void 0:H==="define"?` #ifndef HAS_UNIFORM_u_${fe} uniform lowp float u_${fe}_t; #if !defined(${xe}) in ${Z} ${be} a_${fe}; #endif #else uniform ${Z} ${se} u_${fe}; #endif `:H==="define-instanced"?De==="mat4"?` #ifdef INSTANCED_ARRAYS in vec4 a_${fe}0; in vec4 a_${fe}1; in vec4 a_${fe}2; in vec4 a_${fe}3; #else uniform ${Z} ${se} u_${fe}; #endif `:` #ifdef INSTANCED_ARRAYS in ${Z} ${be} a_${fe}; #else uniform ${Z} ${se} u_${fe}; #endif `:H==="initialize-attribute-custom"?` #ifdef HAS_ATTRIBUTE_a_${fe} ${Z} ${se} ${fe} = a_${fe}; #endif `:De==="vec4"||De==="uvec4"?` #ifndef HAS_UNIFORM_u_${fe} #ifdef ${xe} ${Z} ${se} ${fe} = ${Te}; #else ${Z} ${se} ${fe} = a_${fe}; #endif #else ${Z} ${se} ${fe} = u_${fe}; #endif `:` #ifndef HAS_UNIFORM_u_${fe} #ifdef ${xe} ${Z} ${se} ${fe} = unpack_mix_${De}(${Te}, u_${fe}_t); #else ${Z} ${se} ${fe} = unpack_mix_${De}(a_${fe}, u_${fe}_t); #endif #else ${Z} ${se} ${fe} = u_${fe}; #endif `}),usedDefines:F,vertexIncludes:A,fragmentIncludes:M}}var Nps={model:fd(`#include "_prelude_fog.fragment.glsl" #include "_prelude_shadow.fragment.glsl" #include "_prelude_lighting.glsl" #include "_prelude_indicator_cutout.fragment.glsl" #include "_prelude_feature_cutout.fragment.glsl" uniform float u_opacity; #ifdef DITHERED_DISCARD uniform float u_dithered_discard_threshold; #endif #ifndef LIGHTING_3D_MODE uniform vec3 u_lightcolor;uniform vec3 u_lightpos;uniform float u_lightintensity; #endif 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 vec4 normal_4n #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 vec4 normal_4n #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_feature 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 #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_feature #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 texColor=vec4(unpremultiplyColor(texColor),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;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_4n n=normalize(normal_4n.xyz); #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));n=normalize(cross(fdx,fdy))*-1.0; #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_feature 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() {vec3 lightDir;vec3 lightColor; #ifdef LIGHTING_3D_MODE lightDir=u_lighting_directional_dir;lightDir.xy=-lightDir.xy;lightColor=u_lighting_directional_color; #else lightDir=u_lightpos;lightColor=u_lightcolor; #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_feature 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 glFragColor=finalColor; #ifdef OVERDRAW_INSPECTOR glFragColor=vec4(1.0); #endif HANDLE_WIREFRAME_DEBUG;}`,`#include "_prelude_fog.vertex.glsl" #include "_prelude_shadow.vertex.glsl" #include "_prelude_feature_cutout.vertex.glsl" in vec3 a_pos_3f; #pragma mapbox: define-attribute highp vec4 normal_4n #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 uvec2 feature #define MODEL_PART_COUNT 7u #define MODEL_PART_STYLE_SIZE_VEC4 28u #ifdef HAS_ATTRIBUTE_a_feature struct ModelPartStyle {vec4 color_mix;vec4 rmea;vec4 gradient;float gradient_power;};layout(std140) uniform ModelPartStyleUniform {vec4 part_style[MODEL_PART_STYLE_SIZE_VEC4];} u_model_part_style;uniform vec4 u_model_mesh_params; #endif 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 HAS_ATTRIBUTE_a_feature 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));} #ifdef HAS_ATTRIBUTE_a_feature uint decodeModelPartId(uvec2 feature) {uint partId=feature.y & 0xFu;return partId < MODEL_PART_COUNT ? partId : 0u;}vec4 decodeModelVertexColor(uvec2 feature) {uvec4 nibbles=uvec4(feature.x >> 12u,feature.x >> 8u,feature.x >> 4u,feature.x) & 0xFu;return vec4(nibbles*17u)/255.0;}ModelPartStyle readModelPartStyle(uint partId) {uint base=partId*4u;ModelPartStyle style;style.color_mix=u_model_part_style.part_style[base];style.rmea=u_model_part_style.part_style[base+1u];style.gradient=u_model_part_style.part_style[base+2u];style.gradient_power=u_model_part_style.part_style[base+3u].x;return style;}vec3 modelAlbedo(ModelPartStyle style,vec4 vertexColor) {float ambientOcclusion=mix(1.0,vertexColor.a,u_model_mesh_params.z);return ambientOcclusion*mix(vertexColor.rgb,style.color_mix.rgb,style.color_mix.a);}vec4 resolveModelEmissiveGradient(ModelPartStyle style,float height) {float begin=u_model_mesh_params.x+u_model_mesh_params.y*style.gradient.x;float span=u_model_mesh_params.y*(style.gradient.y-style.gradient.x);return vec4((height-begin)/span,style.gradient_power,style.gradient.z,style.gradient.w);} #endif void main() { #pragma mapbox: initialize-attribute highp vec4 normal_4n #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 uvec2 feature 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_feature ModelPartStyle part_style=readModelPartStyle(decodeModelPartId(feature));v_color_mix=vec4(modelAlbedo(part_style,decodeModelVertexColor(feature)),1.0);v_roughness_metallic_emissive_alpha=part_style.rmea;v_height_based_emission_params=resolveModelEmissiveGradient(part_style,a_pos_3f.z); #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 HAS_ATTRIBUTE_a_normal_4n #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_4n=vec4(rs*((u_lighting_matrix*vec4(normal_4n.xyz,0.0)).xyz/squared_scale),0.0);normal_4n=normalize(normal_4n); #else normal_4n=vec4((normal_matrix*vec4(normal_4n.xyz,0)).xyz,0.0); #endif #endif #ifdef HAS_ATTRIBUTE_a_feature #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_4n #ifdef MODEL_POSITION_ON_GPU vec3 offset=shadow_normal_offset(vec3(-normal_4n.xy,normal_4n.z));shadow_pos.xyz+=offset*shadow_normal_offset_multiplier0(); #else vec3 offset=shadow_normal_offset_model(normal_4n.xyz);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:fd("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 }`),fillExtrusionDepth:fd("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);}`),fillExtrusionGroundEffect:fd(`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 }`),groundShadow:fd(`#include "_prelude_shadow.fragment.glsl" #include "_prelude_indicator_cutout.fragment.glsl" #include "_prelude_feature_cutout.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 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 }`)};const kps=(N,p)=>({u_matrix:N,u_ground_shadow_factor:p});function pft(N,p,_=0){const A=Math.pow(2,p.tileID.overscaledZ),M=p.tileSize*Math.pow(2,N.transform.tileZoom)/A,F=M*(p.tileID.canonical.x+p.tileID.wrap*A),z=M*p.tileID.canonical.y;return{u_image:0,u_texsize:p.imageAtlasTexture?p.imageAtlasTexture.size:[0,0],u_tile_units_to_pixels:1/tZ(p,1,N.transform.tileZoom),u_pixel_coord_upper:[F>>16,z>>16],u_pixel_coord_lower:[65535&F,65535&z],u_pattern_transition:_}}const qle={terrain:0,flat:1},Sps=y(),gft=[0,0,0],xft=(N,p,_,A,M,F,z,H,Z,se,fe,xe,be,Te,De,Ue,Ye,st,ot=[0,0,1],mt=!1)=>{let lt=gft,yt=0,Nt=gft;if(!mt){const $t=p.style.light,Jt=$t.properties.get("position");if(lt=[Jt.x,Jt.y,Jt.z],$t.properties.get("anchor")==="viewport"){const Ls=f();x(Ls,-p.transform.angle),it(lt,lt,Ls)}const ns=$t.properties.get("color").toPremultipliedRenderColor(null);yt=$t.properties.get("intensity"),Nt=[ns.r,ns.g,ns.b]}const as=p.transform,Et={u_matrix:N,u_lightpos:lt,u_lightintensity:yt,u_lightcolor:Nt,u_vertical_gradient:+_,u_opacity:A,u_tile_id:[0,0,0],u_zoom_transition:0,u_inv_rot_matrix:Sps,u_merc_center:[0,0],u_up_dir:[0,0,0],u_height_lift:0,u_height_type:qle[se],u_base_type:qle[fe],u_ao:M,u_edge_radius:F,u_width_scale:z,u_flood_light_color:De,u_vertical_scale:Ue,u_flood_light_intensity:Ye,u_ground_shadow_factor:st,u_front_cutoff_params:ot};return as.projection.name==="globe"&&(Et.u_tile_id=[H.canonical.x,H.canonical.y,1<{let an=$t;jn.groundRadiusBuffer!=null&&(an=$t.concat("HAS_ATTRIBUTE_a_flood_light_ground_radius"));const Ln=jn.programConfigurations.get(A.id),In=p.isTileAffectedByFog(cn),Vn=p.getOrCreateProgram("fillExtrusionGroundEffect",{config:Ln,defines:an,overrideFog:In}),Dn=((Bn,Rr,cr,jr,Wa,Ka,oi,Fa,Ai,Ni)=>({u_matrix:Bn,u_opacity:Rr,u_ao_pass:cr?1:0,u_meter_to_tile:jr,u_ao:Wa,u_flood_light_intensity:Ka,u_flood_light_color:oi,u_attenuation:Fa,u_edge_radius:Ai,u_fb:0,u_fb_size:Ni,u_dynamic_offset:1}))(Cs,xe,se,Qs,[be,Te*Qs],De,Ue,Ye,Et>=17?0:Ls*Qs,mt?mt.size[0]:0),ir=[];st&&ir.push(jn.hiddenByLandmarkVertexBuffer),jn.groundRadiusBuffer!=null&&ir.push(jn.groundRadiusBuffer),p.uploadCommonUniforms(yt,Vn,cn.toUnwrapped(),null,Gs),Vn.draw(p,yt.gl.TRIANGLES,F,z,H,Z,Dn,A.id,jn.vertexBuffer,jn.indexBuffer,Hn,A.paint,Et,Ln,ir)};for(const cn of M){const jn=_.getTile(cn),Hn=jn.getBucket(A);if(!Hn||Hn.projection.name!==as.projection.name||!Hn.groundEffect||Hn.groundEffect&&!Hn.groundEffect.hasData())continue;const Cs=Hn.groundEffect,Qs=1/Hn.tileToMeter;{const an=p.translatePosMatrix(cn.projMatrix,jn,Jt,ns),Ln=Cs.getDefaultSegment();pn(cn,Cs,Ln,an,Qs)}if(ot)for(let an=0;an<4;an++){const Ln=Vdt[an](cn),In=_.getTile(Ln);if(!In)continue;const Vn=In.getBucket(A);if(!Vn||Vn.projection.name!==as.projection.name||!Vn.groundEffect||Vn.groundEffect&&!Vn.groundEffect.hasData())continue;const Dn=Vn.groundEffect;let ir,Bn;an===0?(ir=[-8192,0,0],Bn=1):an===1?(ir=[Fr,0,0],Bn=0):an===2?(ir=[0,-8192,0],Bn=3):(ir=[0,Fr,0],Bn=2);const Rr=Dn.regionSegments[Bn];Rr&&(I(yft,cn.projMatrix,ir),pn(cn,Dn,Rr,p.translatePosMatrix(yft,jn,Jt,ns),Qs))}}}const Cps={model:N=>({u_matrix:new zf(N),u_lighting_matrix:new zf(N),u_normal_matrix:new zf(N),u_node_matrix:new zf(N),u_lightpos:new qm(N),u_lightintensity:new co(N),u_lightcolor:new qm(N),u_camera_pos:new qm(N),u_opacity:new co(N),u_baseColorFactor:new X_(N),u_emissiveFactor:new X_(N),u_metallicFactor:new co(N),u_roughnessFactor:new co(N),u_baseTextureIsAlpha:new Um(N),u_alphaMask:new Um(N),u_alphaCutoff:new co(N),u_baseColorTexture:new Um(N),u_metallicRoughnessTexture:new Um(N),u_normalTexture:new Um(N),u_occlusionTexture:new Um(N),u_emissionTexture:new Um(N),u_lutTexture:new Um(N),u_color_mix:new X_(N),u_aoIntensity:new co(N),u_emissive_strength:new co(N),u_occlusionTextureTransform:new X_(N),u_dithered_discard_threshold:new co(N),u_model_mesh_params:new X_(N)}),modelDepth:N=>({u_matrix:new zf(N),u_instance:new zf(N),u_node_matrix:new zf(N)}),groundShadow:N=>({u_matrix:new zf(N),u_ground_shadow_factor:new qm(N)}),fillExtrusionDepth:N=>({u_matrix:new zf(N),u_edge_radius:new co(N),u_width_scale:new co(N),u_vertical_scale:new co(N),u_height_type:new Um(N),u_base_type:new Um(N)}),fillExtrusionGroundEffect:N=>({u_matrix:new zf(N),u_opacity:new co(N),u_ao_pass:new co(N),u_meter_to_tile:new co(N),u_ao:new hp(N),u_flood_light_intensity:new co(N),u_flood_light_color:new qm(N),u_attenuation:new co(N),u_edge_radius:new co(N),u_fb:new Um(N),u_fb_size:new co(N),u_dynamic_offset:new co(N)})};function bft(N){const p=N.properties.get("direction"),_=cm(p.x,p.y,p.z);_[2]=ta(_[2],0,75);const A=Ih([_[0],_[1],_[2]]);return _e(A.x,A.y,A.z)}function _ft(N,p,_){const A=p.properties.get("color-use-theme")==="none",M=p.properties.get("color"),F=p.properties.get("intensity"),z=p.properties.get("direction"),H=[z.x,z.y,z.z],Z=_.properties.get("color-use-theme")==="none",se=_.properties.get("color"),fe=_.properties.get("intensity"),xe=Math.max(ze([0,0,1],H),0),be=[0,0,0];Fe(be,se.toPremultipliedRenderColor(Z?null:N.getLut(p.scope)).toArray01Linear().slice(0,3),fe);const Te=[0,0,0];return Fe(Te,M.toPremultipliedRenderColor(A?null:N.getLut(_.scope)).toArray01Linear().slice(0,3),xe*F),ko([be[0]>0?be[0]/(be[0]+Te[0]):0,be[1]>0?be[1]/(be[1]+Te[1]):0,be[2]>0?be[2]/(be[2]+Te[2]):0])}const Vle=[];function wft(N){return Vle[N]=Vle[N]||new Float64Array(16)}const Hle=[],Aps=new Float32Array(16);class Eps{constructor(p,_){this.aabb=p,this.lastCascade=_}}class Tps{add(p,_){const A=this.receivers[p.key];A!==void 0?(A.aabb.min[0]=Math.min(A.aabb.min[0],_.min[0]),A.aabb.min[1]=Math.min(A.aabb.min[1],_.min[1]),A.aabb.min[2]=Math.min(A.aabb.min[2],_.min[2]),A.aabb.max[0]=Math.max(A.aabb.max[0],_.max[0]),A.aabb.max[1]=Math.max(A.aabb.max[1],_.max[1]),A.aabb.max[2]=Math.max(A.aabb.max[2],_.max[2])):this.receivers[p.key]=new Eps(_,null)}clear(){this.receivers={}}get(p){return this.receivers[p.key]}computeRequiredCascades(p,_,A){const M=uu.fromPoints(p.points);let F=0;for(const z in this.receivers){const H=this.receivers[z];if(!H||!M.intersectsAabb(H.aabb))continue;H.aabb.min=M.closestPoint(H.aabb.min),H.aabb.max=M.closestPoint(H.aabb.max);const Z=H.aabb.getCorners();for(let se=0;se1||be[1]<-1||be[1]>1){fe=!1;break}}if(H.lastCascade=se,F=Math.max(F,se),fe)break}}return F+1}}function Gle(N,p,_){const A=$e([],xt([],_,p),xt([],N,p)),M=ce(A);return M===0?[0,0,1,0]:(Fe(A,A,1/M),[A[0],A[1],A[2],-ze(A,p)])}function Mps(N,p,_,A,M,F){const z=N.zoom,H=N.scale,Z=N.worldSize,se=1/Z,fe=N.aspect,xe=Math.sqrt(1+fe*fe)*Math.tan(.5*N.fovX),be=xe*xe,Te=A-_,De=A+_;let Ue,Ye;be>Te/De?(Ue=A,Ye=A*xe):(Ue=.5*De*(1+be),Ye=.5*Math.sqrt(Te*Te+2*(A*A+_*_)*be+De*De*be*be));const st=N.projection.pixelsPerMeter(N.center.lat,Z),ot=[0,0,-Ue*se];Xe(ot,ot,N._camera.getCameraToWorldMercator());let mt=Ye*se;const lt=function(Qs){return Qs[0]/=H,Qs[1]/=H,Qs[2]=eu(Qs[2],N._center.lat),Qs},yt=N._edgeInsets;if(!(yt.left===0&&yt.top===0&&yt.right===0&&yt.bottom===0||yt.left===yt.right&&yt.top===yt.bottom)){const Qs=N._camera.getWorldToCamera(N.worldSize,N.projection.zAxisUnit==="meters"?st:1),an=N._camera.getCameraToClipPerspective(N._fov,N.width/N.height,_,A);an[8]=2*-N.centerOffset.x/N.width,an[9]=2*N.centerOffset.y/N.height;const Ln=new Float64Array(16);ne(Ln,an,Qs);const In=new Float64Array(16);C(In,Ln);const Vn=q3.fromInvProjectionMatrix(In,Z,z,!0);for(const Dn of Vn.points){const ir=lt(Dn);mt=Math.max(mt,Yt(ve([],ot,ir)))}}mt*=M/(M-1);const Nt=Math.acos(p[2]),as=Math.atan2(-p[0],-p[1]),Et=new Dle;Et.position=ot,Et.setPitchBearing(Nt,as);const $t=Et.getWorldToCamera(Z,st),Jt=mt*Z,ns=Math.min(N._mercatorZfromZoom(17)*Z*-2,-2*Jt),Ls=Et.getCameraToClipOrthographic(-Jt,Jt,-Jt,Jt,ns,(Jt+F*st)/p[2]),Gs=new Float64Array(16);E(Gs,Ls,$t);const pn=.5*M,cn=[0,0,0];Xe(cn,_e(Math.floor(1e6*ot[0])/1e6*Z,Math.floor(1e6*ot[1])/1e6*Z,0),Gs),Fe(cn,cn,pn);const jn=[Math.floor(cn[0]),Math.floor(cn[1]),Math.floor(cn[2])],Hn=[0,0,0];xt(Hn,cn,jn),Fe(Hn,Hn,-1/pn);const Cs=new Float64Array(16);return w(Cs),I(Cs,Cs,Hn),E(Gs,Cs,Gs),[Gs,Jt]}class Z3 extends Jc{constructor(p,_,A,M){super(),this.id=p,this.type="model",this.models=[],this._options=_,this._modelsInfo=new Map,this._abortController=null}cancelModelRequests(){this._abortController&&(this._abortController.abort(),this._abortController=null)}async loadGLTFFromURI(p,_){return Xut((await this.map._requestManager.transformRequest(p,vr.Model,_)).url,_)}async loadModel(p,_,A){try{const M=await this.loadGLTFFromURI(_.uri,A);if(A.aborted)return;const F=this._modelsInfo.get(p);if(!F)return;const z=t8e(M),H=F.modelSpec,Z=new sht(p,H.uri,H.position,H.orientation,z);Z3.applyModelSpecification(Z,H),Z.computeBoundsAndApplyParent(),this.models.push(Z),F.model=Z}catch(M){if(A.aborted)return;this.fire(new Xi(new Error(`Could not load model ${p} from ${_.uri}`,{cause:M})))}}async load(){this._abortController||(this._abortController=new AbortController);const p=this._abortController.signal,_=[];for(const A in this._options.models){const M=this._options.models[A],F=this._modelsInfo.get(A);if(F&&F.model){F.modelSpec=M;const z=F.model;z.position=M.position!=null?new Ll(M.position[0],M.position[1]):new Ll(0,0),z.orientation=M.orientation??[0,0,0],Z3.applyModelSpecification(z,M),z.computeBoundsAndApplyParent(),this.models.push(z)}else F?F.modelSpec=M:(this._modelsInfo.set(A,{modelSpec:M,model:null}),_.push(this.loadModel(A,M,p)))}_.length!==0?(await Promise.allSettled(_),p.aborted||this.fire(new Bl("data",{dataType:"source",sourceDataType:"metadata"}))):this.loaded()&&this.fire(new Bl("data",{dataType:"source",sourceDataType:"metadata"}))}static arrayFromColorSpecification(p){const _=p;if(_===void 0)return;if(Array.isArray(_))return[_[0],_[1],_[2]];const A=Ci.parse(_);return A?[A.r,A.g,A.b]:void 0}static applyModelSpecification(p,_){if(_.nodeOverrides&&Z3.convertNodeOverrides(p,_.nodeOverrides),_.materialOverrides&&Z3.convertMaterialOverrides(p,_.materialOverrides),_.nodeOverrideNames&&(p.nodeOverrideNames=[..._.nodeOverrideNames]),_.materialOverrideNames&&(p.materialOverrideNames=[..._.materialOverrideNames]),_.featureProperties&&(p.featureProperties=_.featureProperties),_.lightOverrides){const A=_.lightOverrides,M=Z3.arrayFromColorSpecification(A["light-ambient-color"]),F=Z3.arrayFromColorSpecification(A["light-directional-color"]);p.lightOverrides={ambientIntensity:A["light-ambient-intensity"],ambientColor:M,directionalIntensity:A["light-directional-intensity"],directionalColor:F}}else p.lightOverrides=void 0}static convertNodeOverrides(p,_){if(Array.isArray(_)&&_.every(A=>typeof A=="string")){p.nodeOverrideNames=[];for(const A of _)p.nodeOverrideNames.push(A)}else Object.entries(_).forEach(([A,M])=>{const F={orientation:[0,0,0],minZoom:void 0,maxZoom:void 0};if(Object.hasOwn(M,"orientation")){const z=M.orientation;z&&(F.orientation=z)}Object.hasOwn(M,"minzoom")&&(F.minZoom=M.minzoom),Object.hasOwn(M,"maxzoom")&&(F.maxZoom=M.maxzoom),p.nodeOverrides.set(A,F)})}static convertMaterialOverrides(p,_){if(Array.isArray(_)&&_.every(A=>typeof A=="string")){p.materialOverrideNames=[];for(const A of _)p.materialOverrideNames.push(A)}else Object.entries(_).forEach(([A,M])=>{const F=Z3.arrayFromColorSpecification(M["model-color"]),z={color:F!==void 0?new Ci(F[0],F[1],F[2]):new Ci(1,1,1),colorMix:0,emissionStrength:0,opacity:1},H=M["model-color-mix-intensity"];H!==void 0&&(z.colorMix=H);const Z=M["model-emissive-strength"];Z!==void 0&&(z.emissionStrength=Z);const se=M["model-opacity"];se!==void 0&&(z.opacity=se),p.materialOverrides.set(A,z)})}onAdd(p){this.map=p,this.load()}hasTransition(){return!1}loaded(){if(this._modelsInfo.size===0)return!0;for(const p of this._modelsInfo.values())if(p.model==null)return!1;return!0}getModels(){return this.models}loadTile(p,_){}serialize(){return this._options}setProperty(p,_){return!1}reload(){this.cancelModelRequests();const p=G6(this.id,this.scope);this.map.style.clearSource(p),this.models=[],this._modelsInfo.clear(),this.load()}onRemove(p){this.cancelModelRequests()}setModels(p){this.models=[];const _=new Map;for(const A in p){const M=p[A],F=this._modelsInfo.get(A);F&&F.modelSpec.uri===M.uri&&_.set(A,F)}if(this._modelsInfo.size!==_.size){this.cancelModelRequests();for(const[A,M]of _)M.model||_.delete(A)}this._modelsInfo=_,this._options.models=p,this.load()}}function jft(N,p,_){try{p=function(M){if(!M.variants)return M;if(!Array.isArray(M.variants))throw new Error("variants must be an array");let F=null,z=null;for(const Z of M.variants){if(Z==null||typeof Z!="object"||Z.constructor!==Object)throw new Error("variant must be an object");if(!Array.isArray(Z.capabilities))throw new Error("capabilities must be an array");Z.capabilities.length===1&&(Z.capabilities[0]==="meshopt-v2+lod"?z=Z:Z.capabilities[0]==="meshopt"&&(F=Z))}const H=z!==null?z:F;return H!==null?Object.assign(M,H):M}(p)}catch(M){return new Error("Failed to process TileJSON variants",{cause:M})}const A=pu({...p,...N},["tilejson","tiles","minzoom","maxzoom","attribution","mapbox_logo","bounds","extra_bounds","scheme","tileSize","encoding","vector_layers","raster_layers","worldview_options","worldview_default","worldview"]);return N.url&&p.tiles&&N.tiles&&(A.tiles=p.tiles),A.tiles=_.canonicalizeTileset(A,N.url),A}function Nft(N,p,_,A,M){const F=function(H,Z){if(H)return M(H);if(Z){N.url&&Z.tiles&&N.tiles&&delete N.tiles;const se=jft(N,Z,p);if(se instanceof Error)return M(se);M(null,se)}},z=function(H,Z,se){if(!H)return null;if(!Z&&!se)return H;se=se||H.worldview_default;const fe=Object.values(H.language||{});if(fe.length===0)return null;const xe=Object.values(H.worldview||{});if(xe.length===0)return null;const be=fe.every(De=>De===Z),Te=xe.every(De=>De===se);return be&&Te?H:Z in(H.language_options||{})||se in(H.worldview_options||{})?null:H.language_options&&H.worldview_options?H:null}(N.data,_,A);if(z)return oh.frame(()=>F(null,z));if(N.url){const H=new AbortController;return(async()=>{const Z=await p.transformRequest(p.normalizeSourceURL(N.url,null,_,A),vr.Source,H.signal),{data:se}=await rr(Z,H.signal);F(null,se)})().catch(Z=>{H.signal.aborted||F(Z)}),{cancel:()=>H.abort()}}return oh.frame(()=>{const{data:H,...Z}=N;F(null,Z)})}function kft(N,p){const _=Math.pow(2,p.z),A=Math.floor(ex(N.getWest())*_),M=Math.floor(ap(N.getNorth())*_),F=Math.ceil(ex(N.getEast())*_),z=Math.ceil(ap(N.getSouth())*_);return p.x>=A&&p.x=M&&p.ythis.maxzoom||p.z{se&&(se.useNormalOffset=!0,fe||(se.enabled=!0))},be=p.getSource();if(N.renderPass==="light-beam"&&be.type!=="batched-model")return;if(be.type==="vector"||be.type==="geojson")return function(lt,yt,Nt,as,Et){const $t=lt.transform,Jt=$t.projection.name==="globe",ns=$t.getFreeCameraOptions().position;if(!lt.modelManager)return;const Ls=lt.modelManager;Nt.modelManager=Ls;const Gs=lt.shadowRenderer;if(!Object.hasOwn(Nt._unevaluatedLayout._values,"model-id"))return;const pn=Nt._unevaluatedLayout._values["model-id"],cn={...Nt.layout.get("model-id").parameters},jn=lt.style.order.indexOf(Nt.fqid),Hn=Nt.paint.get("model-opacity").constantOr(1);for(const Cs of as){const Qs=yt.getTile(Cs).getBucket(Nt);if(!Qs||Qs.projection.name!==$t.projection.name)continue;const an=Qs.getModelUris();if(an&&!Qs.modelsRequested&&(Ls.addModelsFromBucket(an,Et),Qs.modelsRequested=!0),Jt)cn.zoom=Cs.overscaledZ;else{const cr=fps(Cs,$t);cn.zoom=cr}const Ln=pn.possiblyEvaluate(cn);if(mps(lt,Qs,Cs),XC.shadowUniformsInitialized=!1,XC.useSingleShadowCascade=!!Gs&&Gs.getMaxCascadeForTile(Cs.toUnwrapped())===0,lt.renderPass==="shadow"&&Gs){if(lt.currentShadowCascade===1&&Qs.isInsideFirstShadowMapFrustum)continue;const cr=$t.calculatePosMatrix(Cs.toUnwrapped(),$t.worldSize);if(XC.tileMatrix.set(cr),XC.shadowTileMatrix.set(Gs.calculateShadowPassMatrixFromMatrix(cr)),XC.aabb.min=[0,0,0],XC.aabb.max[0]=XC.aabb.max[1]=Fr,XC.aabb.max[2]=0,gps(Qs,XC,lt,Nt.scope))continue}const In=1<0&<.style.isLayerClipped(Nt,yt.getSource())&&Qs.updateReplacement(Cs,lt.replacementSource,jn,Nt.scope)&&(Qs.uploaded=!1,Qs.upload(lt.context));let Dn=0;const ir=new Array,Bn=new Array,Rr=new Array;for(let cr in Qs.instancesPerModel){const jr=Qs.instancesPerModel[cr];jr.features.length>0&&!Jt&&(cr=Ln.evaluate(jr.features[0].feature,{}));const Wa=Ls.getModel(cr,Et);if(Wa||Ls.hasURLBeenRequested(cr)||Qs.modelUris.includes(cr)||(Qs.modelUris.push(cr),Qs.modelsRequested=!1),Wa&&Wa.uploaded)if(Jt){const Ka=Fe([],[ns.x,ns.y,ns.z],lt.transform.worldSize);Ce(Ka,Ka);for(let oi=0;oi0&&Fo.elevationUpdate(jr.terrain,Fa,Ni,Ka.source),Fo.needsReEvaluation(jr,Ai,Ka)&&Fo.evaluate(Ka))}})(lt,yt,Nt,as),function(){const jr=new Map;let Wa,Ka,oi;Bn?(Wa=as.length-1,Ka=-1,oi=-1):(Wa=0,Ka=as.length,oi=1);const Fa=te(),Ai=new xs(0,0);for(let Ni=Wa;Ni!==Ka;Ni+=oi){const Fo=as[Ni],rl=yt.getTile(Fo).getBucket(Nt);if(!rl||!rl.uploaded)continue;let $l=!1;ns&&($l=ns.getMaxCascadeForTile(Fo.toUnwrapped())===0);const wc=$t.calculatePosMatrix(Fo.toUnwrapped(),$t.worldSize),Vm=!!(4&rl.modelTraits);E(A8e,jn,wc),E(E8e,$t.expandedFarZProjMatrix,wc),C(Ole,A8e),S(Ole,Ole);const Z0=!Ln&&ns&&ns.enabled?ns.computeCascadeTileMatrices(wc):null;!Ln&&Bn&&(C(pM,wc),Xe(Fa,Gs,pM),Ai.x=Fa[0],Ai.y=Fa[1]);const Jh=[];rl.setFilter(Nt.filter);for(const _l of rl.getNodesInfo()){if(_l.hiddenByReplacement||!_l.node.meshes)continue;const Wd=_l.node;let fh=0;lt.terrain&&Wd.elevation&&(fh=Wd.elevation*lt.terrain.exaggeration());const Hm=()=>{const Zu=_l.aabb,Wb=an.min,Kb=an.max;return Wb[0]=Zu.min[0],Wb[1]=Zu.min[1],Wb[2]=Zu.min[2]+fh,Kb[0]=Zu.max[0],Kb[1]=Zu.max[1],Kb[2]=Zu.max[2]+fh,Xe(Wb,Wb,wc),Xe(Kb,Kb,wc),an},mo=Hm(),fp=_l.evaluatedScale;if(fp[0]<=1&&fp[1]<=1&&fp[2]<=1&&mo.intersects(Dn)===0)continue;if(!Ln){const Zu=mo.min,Wb=mo.max;Ble[0]=.5*(Zu[0]+Wb[0]),Ble[1]=.5*(Zu[1]+Wb[1]),Ble[2]=.5*(Zu[2]+Wb[2]);const Kb=Ve(Gs,Ble)*cn,fg=lt._debugParams.lodSwitchDistance,Jk=fg>=0;if(Jk&&fg>=9999)_l.targetLod=0;else{let Q_;if(Jk)Q_=fg;else{const X0=(Wb[2]-Zu[2])*cn*fp[2],X3=Math.max(Wb[0]-Zu[0],Wb[1]-Zu[1])*cn*Math.max(fp[0],fp[1]);let QC;QC=X0>=30?1:X3>=80?.5:Math.max(X0,X3)>=20?.25:0,Q_=2e3+3e3*QC}pps(_l,Kb,Math.min(lt.frameTimeDelta,1e3/30),Q_,lt._debugParams.lodSwitchFadeDuration)}}if(!Ln&&Bn){const Zu=.16666666666666666;_l.cameraCollisionOpacity=Gs[0]>mo.min[0]&&Gs[0]mo.min[1]&&Gs[1]!Bn||_l.opacity===1&&Wd.opacity===1?_l.depthWd.depth?-1:1);for(const _l of Jh){const Wd=_l.nodeInfo,fh=Wd.node;let Hm=null;if(lt._debugParams.show3DModelFootprints&&fh.footprint){const Cy=fh.id||fh.name||"footprint";if(!jr.has(Cy)){const Yv=aZ(new Float64Array(16),E8e,_l.tileTranslation,_l.nodeInfo.evaluatedScale);jr.set(Cy,{node:fh,mvp:Yv})}}const mo=_l.nodeInfo.evaluatedScale;aZ(ZC,A8e,_l.tileTranslation,mo),zle[0]=1/mo[0],zle[1]=-1/mo[1],zle[2]=1/mo[2],P(pM,Ole,zle),E(ZC,ZC,fh.globalMatrix);const fp=Vm?0:Wd.evaluatedRMEA[0][2],Lp=Wd.targetLod,xf=fh.lodMeshes&&fh.lodMeshes.length>0,Vx=xf&&Lp>0&&Lp<1;if(Ln&&xf&&Math.round(Lp)===1)continue;const Hx=!Ln&&Jt?Wmt(Gmt,_l.nodeModelMatrix,lt.transform):null,Gb=Ln&&ns?ns.calculateShadowPassMatrixFromMatrix(_l.nodeModelMatrix):null,Sy=Vx?2:1,Gx=xf&&Math.round(Lp)===1;for(let Cy=0;Cy=OY||V8e>=OY}const wo=fg.material;let pg;wo.occlusionTexture&&wo.occlusionTexture.offsetScale&&(pg=wo.occlusionTexture.offsetScale,X0.defines.push("OCCLUSION_TEXTURE_TRANSFORM")),Vx&&X0.defines.push("DITHERED_DISCARD");const Pu=lt.getOrCreateProgram("model",X0);if(!Ln&&ns&&ns.enabled)if(Hm!==QC){for(let Wx=0;Wx0){const Ni=Array.from(jr.keys()).sort();for(const Fo of Ni){const{node:rl,mvp:$l}=jr.get(Fo);Ymt(lt,0,rl,$l)}}}()}(N,p,_,A),void xe();if(be.type!=="model")return;const Te=be.getModels(),De=[],Ue=N.transform.getFreeCameraOptions().position,Ye=Fe([],[Ue.x,Ue.y,Ue.z],N.transform.worldSize);Ce(Ye,Ye);const st=[],ot=[];let mt=0;for(const lt of Te){const yt=p.getFeatureState("",lt.id),Nt={type:"Unknown",id:lt.id,properties:lt.featureProperties},as=_.paint.get("model-rotation").evaluate(Nt,yt),Et=_.paint.get("model-scale").evaluate(Nt,yt),$t=_.paint.get("model-translation").evaluate(Nt,yt),Jt=_.paint.get("model-opacity").evaluate(Nt,yt);ups(_,lt.id,yt,lt.featureProperties,lt.nodeOverrideNames,lt.nodeOverrides),hps(_,lt.id,yt,lt.featureProperties,lt.materialOverrideNames,lt.materialOverrides),lt.nodeOverrides.size>0&<.computeBoundsAndApplyParent(),lt.computeModelMatrix(N,as,Et,$t,H,z,!1);const ns=U([],Ye),Ls=W([],[1,1,1/T(lt.position.lat,N.transform.zoom)]);De.push({zScaleMatrix:Ls,negCameraPosMatrix:ns});for(const Gs of lt.nodes)I8e(N,Gs,lt.matrix,N.transform.expandedFarZProjMatrix,mt,st,ot,lt.materialOverrides,Jt,void 0,lt.lightOverrides);mt++}if(st.sort((lt,yt)=>yt.depth-lt.depth),N.renderPass!=="shadow"){if(N._debugParams.show3DModelFootprints){const lt=N.transform.projMatrix,yt=new Map,Nt=(Et,$t)=>{if(Et.footprint){const Jt=Et.id||Et.name||"footprint";if(!yt.has(Jt)){const ns=E([],lt,$t);yt.set(Jt,{node:Et,mvp:ns})}}};for(const Et of ot)Nt(Et.node,Et.modelMatrix);for(const Et of st)Nt(Et.node,Et.modelMatrix);const as=Array.from(yt.keys()).sort();for(const Et of as){const{node:$t,mvp:Jt}=yt.get(Et);Ymt(N,0,$t,Jt)}}Zmt(N,_,st,ot,De),xe()}else{for(const lt of ot)iZ(lt.mesh,lt.nodeModelMatrix,N,_);for(const lt of st)iZ(lt.mesh,lt.nodeModelMatrix,N,_);xe()}},prepare:function(N,p,_){const A=p.getSource();if(!A.loaded())return;if(A.type==="vector"||A.type==="geojson")return void(_.modelManager&&_.modelManager.upload(_,Kmt(_,N)));if(A.type==="batched-model"||A.type!=="model")return;const M=A.getModels();for(const F of M)F.upload(_.context)},shaders:Nps,programUniforms:Cps,ShadowRenderer:class{constructor(N){this.painter=N,this._enabled=!1,this._drawShadowAfterLayer=-1,this._numCascadesToRender=0,this._cascades=[],this._groundShadowTiles=[],this._receivers=new Tps,this._depthMode=new Ny(N.context.gl.LEQUAL,Ny.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._devtoolsFolder=null,this.useNormalOffset=!1,this._shadowParameters={cascadeCount:2,normalOffset:3,shadowMapResolution:2048}}destroy(){for(const N of this._cascades)N.texture.destroy(),N.framebuffer.destroy();this._cascades=[]}_hasCasterGeometry(N,p){const _=this.painter.style.getLayerSourceCache(N);if(!_)return!1;const A=_.getSource();if(A.type==="model")return A.getModels().length>0;const M=p[_.id];if(!M)return!1;for(const F of M){const z=_.getTile(F);if(z&&z.getBucket(N))return!0}return!1}updateShadowParameters(N,p,_){const A=this.painter;if(this._enabled=!1,this._drawShadowAfterLayer=-1,this._receivers.clear(),!p||!p.properties)return;const M=p.properties.get("shadow-intensity"),F=p.properties.get("shadow-draw-before-layer");if(!p.shadowsEnabled()||M<=0)return;let z=-1,H=0;for(const st of A.style.order){const ot=A.style._mergedLayers[st];ot.hasShadowPass()&&!ot.isHidden(N.zoom)&&this._hasCasterGeometry(ot,_)&&(z=H),!F||F!==st&&F!==ot.slot||(this._drawShadowAfterLayer=H>0?H-1:0),H+=1}if(this._enabled=z>=0,!this.enabled)return;this._drawShadowAfterLayer<0&&(this._drawShadowAfterLayer=z);const Z=A.context,se=this._shadowParameters.shadowMapResolution,fe=this._shadowParameters.shadowMapResolution;if(this._cascades.length===0||this._shadowParameters.shadowMapResolution!==this._cascades[0].texture.size[0]){this._cascades=[];for(let st=0;stmt.dem).forEach(mt=>{const lt=mt.dem.tree;ot[0]=Math.min(ot[0],lt.minimums[0]),ot[1]=Math.max(ot[1],lt.maximums[0])}),ot[0]!==1e4&&(xe=(ot[1]-ot[0])*st.exaggeration())}const be=1.5*N.cameraToCenterDistance,Te=3*be,De=new Float64Array(16);for(let st=0;st=0)return{};const M=function(H,Z,se){const fe=se/(1<0&&(ue(M[1],M[1],[A[0]*F,0,0]),ue(M[2],M[2],[A[0]*F,0,0])),A[1]<0?(ue(M[0],M[0],[0,A[1]*F,0]),ue(M[1],M[1],[0,A[1]*F,0])):A[1]>0&&(ue(M[2],M[2],[0,A[1]*F,0]),ue(M[3],M[3],[0,A[1]*F,0]));const z={};return z.vertices=M,z.planes=[Gle(M[1],M[0],M[4]),Gle(M[2],M[1],M[5]),Gle(M[3],M[2],M[6]),Gle(M[0],M[3],M[7])],z}addShadowReceiver(N,p,_){this._receivers.add(N,uu.fromTileIdAndHeight(N,p,_))}getMaxCascadeForTile(N){const p=this._receivers.get(N);return p&&p.lastCascade?p.lastCascade:0}},drawGroundEffect:vft,queryModelLayerRendered:function(N,p,_,A){const M=_.getSource();if(!M||M.type!=="model")return{};const F=M,z={};z[N.id]=[];const H=z[N.id];let Z=0;for(const se of F.models){const fe=_.getFeatureState(N.sourceLayer,se.id),xe={type:"Unknown",id:se.id,properties:se.featureProperties},be=N.paint.get("model-rotation").evaluate(xe,fe),Te=N.paint.get("model-scale").evaluate(xe,fe),De=N.paint.get("model-translation").evaluate(xe,fe),Ue=N.paint.get("model-elevation-reference");let Ye=[];yle(Ye,se,A,se.position,be,Te,De,Ue==="ground",Ue==="ground",!1),A.projection.name==="globe"&&(Ye=xle(Ye,A));const st=E([],A.projMatrix,Ye),ot=KOe(p.isPointQuery()?p.screenBounds:p.screenGeometry,A,st,se.aabb);if(ot!=null){const mt=new cR(void 0,0,0,0,se.id);mt.layer=N.layer,mt.properties=structuredClone(se.featureProperties),mt.properties.layer=N.id,mt.properties.uri=se.uri,mt.properties.orientation=se.orientation,mt.sourceLayer=N.sourceLayer,mt.geometry={type:"Point",coordinates:[se.position.lng,se.position.lat]},mt.state=fe,mt.source=N.source,H.push({featureIndex:Z,feature:mt,intersectionZ:ot})}++Z}return z},queryModelLayerIntersectsFeature:function(N,p,_,A,M,F){if(!N.modelManager)return!1;const z=N.modelManager,H=p.tile.getBucket(N);if(!(H&&H instanceof g8e))return!1;for(const Z in H.instancesPerModel){const se=H.instancesPerModel[Z],fe=_.id!==void 0?_.id:_.properties&&Object.hasOwn(_.properties,"id")?_.properties.id:void 0;if(Object.hasOwn(se.idToFeaturesIndex,fe)){const xe=se.features[se.idToFeaturesIndex[fe]],be=z.getModel(Z,F||N.scope);if(!be)return!1;let Te=[];const De=new Ll(0,0),Ue=H.canonical;let Ye=Number.MAX_VALUE;for(let st=0;stthis.map.style.clearSource(N))}cancelTileJSONRequest(){this._tileJSONRequest&&(this._tileJSONRequest.cancel(),this._tileJSONRequest=null)}load(N){this._loaded=!1,this.fire(new Bl("dataloading",{dataType:"source"}));const p=Array.isArray(this.map._language)?this.map._language.join():this.map._language,_=this.map.getWorldview();this._tileJSONRequest=Nft(this._options,this.map._requestManager,p,_,(A,M)=>{this._tileJSONRequest=null,this._loaded=!0,A?(p&&console.warn(`Ensure that your requested language string is a valid BCP-47 code or list of codes. Found: ${p}`),_&&_.length!==2&&console.warn(`Requested worldview strings must be a valid ISO alpha-2 code. Found: ${_}`),this.fire(new Xi(A))):M&&(Object.assign(this,M),M.bounds&&(this.tileBounds=new Wle(M.bounds,this.minzoom,this.maxzoom)),Mu(M.tiles,this.map._requestManager._customAccessToken),this.fire(new Bl("data",{dataType:"source",sourceDataType:"metadata"})),this.fire(new Bl("data",{dataType:"source",sourceDataType:"content"}))),N&&N(A)})}hasTransition(){return!1}hasTile(N){return!this.tileBounds||this.tileBounds.contains(N.canonical)}loaded(){return this._loaded}async loadTile(N,p){const _=this.map._requestManager.normalizeTileURL(N.tileID.canonical.url(this.tiles,this.scheme)),A=!N.actor||N.state==="expired";if(A)N.actor=this.dispatcher.getActor();else{if(N.state==="loading")return void(N.reloadCallback=p);if(N.buckets){const H=Object.values(N.buckets);for(const Z of H)Z.dirty=!0;return void(N.state="loaded")}}const M=A?"loadTile":"reloadTile",F=new AbortController;N.request=F;const z=(H,Z)=>(delete N.request,N.aborted?p(null):H&&!Je(H)?p(H):(this.map._refreshExpiredTiles&&Z&&N.setExpiryData(Xa(Z.headers)),N.loadModelData(Z,this.map.painter),N.state="loaded",p(null),void(N.reloadCallback&&(this.loadTile(N,N.reloadCallback),N.reloadCallback=null))));try{const H=await this.map._requestManager.transformRequest(_,vr.Tile,F.signal);if(F.signal.aborted)return p(null);const Z={request:H,data:void 0,uid:N.uid,tileID:N.tileID,tileZoom:N.tileZoom,zoom:N.tileID.overscaledZ,tileSize:this.tileSize*N.tileID.overscaleFactor(),type:this.type,source:this.id,scope:this.scope,showCollisionBoxes:this.map.showCollisionBoxes,renderSourceType:N.renderSourceType,brightness:this.map.style&&this.map.style.getBrightness()||0,pixelRatio:oh.devicePixelRatio,promoteId:this.promoteId};N.request=N.actor.sendCancelable(M,Z,{},z)}catch(H){if(F.signal.aborted)return p(null);p(H)}}abortTile(N){N.request&&(N.request.abort(),delete N.request),N.actor&&N.actor.notify("abortTile",{uid:N.uid,type:this.type,source:this.id,scope:this.scope})}serialize(){return{...this._options}}},loadModel:async function(N,p,_){const A=await Xut(N),M=new sht(p,_,void 0,void 0,t8e(A));return M.computeBoundsAndApplyParent(),M}};class Sft{constructor(p,_){this.tileID=p,this.x=p.canonical.x,this.y=p.canonical.y,this.z=p.canonical.z,this.grid=new Hv(Fr,Fr,512),this.featureIndexArray=new t0,this.promoteId=_,this.is3DTile=!1,this.serializedLayersCache=new Map}insert(p,_,A,M,F,z=0,H=0){const Z=this.featureIndexArray.length;this.featureIndexArray.emplaceBack(A,M,F,z);const se=this.grid;for(let fe=0;fe<_.length;fe++){const xe=_[fe],be=[1/0,1/0,-1/0,-1/0];for(let Te=0;Te=0&&be[3]>=0&&se.insert(Z,be[0],be[1],be[2],be[3])}}loadVTLayers(){if(!this.vtLayers){this.vtLayers=new KFe(new Yoe(this.rawTileData)).layers,this.sourceLayerCoder=new Pmt(this.vtLayers?Object.keys(this.vtLayers).sort():["_geojsonTileLayer"]),this.vtFeatures={};for(const p in this.vtLayers)this.vtFeatures[p]=[]}return this.vtLayers}query(p,_){const{tilespaceGeometry:A,transform:M,tileTransform:F,pixelPosMatrix:z,availableImages:H,worldview:Z}=_;this.loadVTLayers(),this.serializedLayersCache.clear();const se=_.queryRadius?_.queryRadius:0,fe=A.bufferedTilespaceBounds,xe=this.grid.queryKeys(fe.min.x,fe.min.y,fe.max.x,fe.max.y,(Ue,Ye,st,ot)=>eOe(A.bufferedTilespaceGeometry,Ue-se,Ye-se,st+se,ot+se));xe.sort(Pps);let be=null;M.elevation&&xe.length>0&&(be=Y9.create(M.elevation,this.tileID));const Te={};let De;for(let Ue=0;Ue(ot||(ot=ht(mt,this.tileID.canonical,F)),lt.queryIntersectsFeature(A,mt,yt,ot,this.z,M,z,be,Nt,_.scope)))}return Te}loadMatchingFeature(p,_,A,M,F,z){const{featureIndex:H,bucketIndex:Z,sourceLayerIndex:se,layoutVertexArrayOffset:fe}=_,xe=this.bucketLayerIDs[Z],be=A.layers,Te=Object.keys(be);if(Te.length&&!rg(Te,xe))return;const De=A.sourceCache,Ue=this.sourceLayerCoder.decode(se),Ye=this.vtLayers[Ue].feature(H),st=this.getId(Ye,Ue);for(let ot=0;ot`${H.key}: ${H.message}`).join(", ");return void Yo(`Failed to create expression for promoteId: ${z}`)}this.promoteIdExpression=F.value}A=this.promoteIdExpression.evaluate({zoom:0},p)}else A=p.properties[M];typeof A=="boolean"&&(A=Number(A))}return A}}function Cft(N,p,_,A,M){return $c(N,(F,z)=>{const H=p instanceof Sl?p.get(z):null;return H&&H.evaluate?H.evaluate(_,A,void 0,M):H})}function Pps(N,p){return p-N}async function Aft(){return Promise.resolve()}oa(Sft,"FeatureIndex",{omit:["rawTileData","sourceLayerCoder"]});const Ips={circle:class extends e0{constructor(N,p,_,A){super(N,{layout:Nht||(Nht=new Ku({"circle-sort-key":new Tr(Zs.layout_circle["circle-sort-key"]),"circle-elevation-reference":new xr(Zs.layout_circle["circle-elevation-reference"]),visibility:new xr(Zs.layout_circle.visibility)})),paint:kht||(kht=new Ku({"circle-radius":new Tr(Zs.paint_circle["circle-radius"]),"circle-color":new Tr(Zs.paint_circle["circle-color"]),"circle-blur":new Tr(Zs.paint_circle["circle-blur"]),"circle-opacity":new Tr(Zs.paint_circle["circle-opacity"]),"circle-translate":new xr(Zs.paint_circle["circle-translate"]),"circle-translate-anchor":new xr(Zs.paint_circle["circle-translate-anchor"]),"circle-pitch-scale":new xr(Zs.paint_circle["circle-pitch-scale"]),"circle-pitch-alignment":new xr(Zs.paint_circle["circle-pitch-alignment"]),"circle-stroke-width":new Tr(Zs.paint_circle["circle-stroke-width"]),"circle-stroke-color":new Tr(Zs.paint_circle["circle-stroke-color"]),"circle-stroke-opacity":new Tr(Zs.paint_circle["circle-stroke-opacity"]),"circle-emissive-strength":new xr(Zs.paint_circle["circle-emissive-strength"]),"circle-color-use-theme":new Tr({type:"string",default:"default","property-type":"data-driven"}),"circle-stroke-color-use-theme":new Tr({type:"string",default:"default","property-type":"data-driven"})}))},p,_,A)}createBucket(N){return new Moe(N)}queryRadius(N){const p=N;return a$("circle-radius",this,p)+a$("circle-stroke-width",this,p)+Mle(this.paint.get("circle-translate"))}queryIntersectsFeature(N,p,_,A,M,F,z,H){const Z=Tht(this.paint.get("circle-translate"),this.paint.get("circle-translate-anchor"),F.angle,N.pixelToTileUnitsFactor),se=this.paint.get("circle-radius").evaluate(p,_)+this.paint.get("circle-stroke-width").evaluate(p,_);return Pht(N,A,F,z,H,this.paint.get("circle-pitch-alignment")==="map",this.paint.get("circle-pitch-scale")==="map",Z,se)}getProgramIds(){return["circle"]}getDefaultProgramParams(N,p,_){const A=Mht(this);return{config:new tR(this,{zoom:p,lut:_}),defines:A,overrideFog:!1}}is3D(N){return!N&&!!this.layout&&this.layout.get("circle-elevation-reference")!=="none"}hasElevation(){return this.layout&&this.layout.get("circle-elevation-reference")!=="none"}mayUse(N){return N==="HD"&&R9(this,"circle-elevation-reference",p=>p==="hd-road-markup")}prepare(){return this.mayUse("HD")?Tle():Promise.resolve()}},heatmap:class extends e0{createBucket(N){return new Lht(N)}constructor(N,p,_,A){super(N,{layout:Rht||(Rht=new Ku({visibility:new xr(Zs.layout_heatmap.visibility)})),paint:Dht||(Dht=new Ku({"heatmap-radius":new Tr(Zs.paint_heatmap["heatmap-radius"]),"heatmap-weight":new Tr(Zs.paint_heatmap["heatmap-weight"]),"heatmap-intensity":new xr(Zs.paint_heatmap["heatmap-intensity"]),"heatmap-color":new R3(Zs.paint_heatmap["heatmap-color"]),"heatmap-opacity":new xr(Zs.paint_heatmap["heatmap-opacity"]),"heatmap-color-use-theme":new Tr({type:"string",default:"default","property-type":"data-driven"})}))},p,_,A),this._updateColorRamp()}_handleSpecialPaintPropertyUpdate(N){N==="heatmap-color"&&this._updateColorRamp()}_updateColorRamp(){this.colorRamp=JY({expression:this._transitionablePaint._values["heatmap-color"].value.expression,evaluationKey:"heatmapDensity",image:this.colorRamp}),this.colorRampTexture=null}resize(){this.heatmapFbo&&(this.heatmapFbo.destroy(),this.heatmapFbo=null)}_clear(){this.heatmapFbo&&(this.heatmapFbo.destroy(),this.heatmapFbo=null),this.colorRampTexture&&(this.colorRampTexture.destroy(),this.colorRampTexture=null)}queryRadius(N){return a$("heatmap-radius",this,N)}queryIntersectsFeature(N,p,_,A,M,F,z,H){const Z=this.paint.get("heatmap-radius").evaluate(p,_);return Pht(N,A,F,z,H,!0,!0,new xs(0,0),Z)}hasOffscreenPass(){return this.paint.get("heatmap-opacity")!==0&&this.visibility!=="none"}getProgramIds(){return["heatmap","heatmapTexture"]}getDefaultProgramParams(N,p,_){return N==="heatmap"?{config:new tR(this,{zoom:p,lut:_}),overrideFog:!1}:{}}},hillshade:class extends e0{constructor(N,p,_,A){super(N,{layout:Fht||(Fht=new Ku({visibility:new xr(Zs.layout_hillshade.visibility)})),paint:Oht||(Oht=new Ku({"hillshade-illumination-direction":new xr(Zs.paint_hillshade["hillshade-illumination-direction"]),"hillshade-illumination-anchor":new xr(Zs.paint_hillshade["hillshade-illumination-anchor"]),"hillshade-exaggeration":new xr(Zs.paint_hillshade["hillshade-exaggeration"]),"hillshade-shadow-color":new xr(Zs.paint_hillshade["hillshade-shadow-color"]),"hillshade-highlight-color":new xr(Zs.paint_hillshade["hillshade-highlight-color"]),"hillshade-accent-color":new xr(Zs.paint_hillshade["hillshade-accent-color"]),"hillshade-emissive-strength":new xr(Zs.paint_hillshade["hillshade-emissive-strength"]),"hillshade-shadow-color-use-theme":new Tr({type:"string",default:"default","property-type":"data-driven"}),"hillshade-highlight-color-use-theme":new Tr({type:"string",default:"default","property-type":"data-driven"}),"hillshade-accent-color-use-theme":new Tr({type:"string",default:"default","property-type":"data-driven"})}))},p,_,A)}shouldRedrape(){return this.hasOffscreenPass()&&this.paint.get("hillshade-illumination-anchor")==="viewport"}hasOffscreenPass(){return this.paint.get("hillshade-exaggeration")!==0&&this.visibility!=="none"}getProgramIds(){return["hillshade","hillshadePrepare"]}getDefaultProgramParams(N,p,_){return{overrideFog:!1}}},fill:class extends e0{constructor(N,p,_,A){super(N,{layout:zht||(zht=new Ku({"fill-sort-key":new Tr(Zs.layout_fill["fill-sort-key"]),visibility:new xr(Zs.layout_fill.visibility),"fill-elevation-reference":new xr(Zs.layout_fill["fill-elevation-reference"]),"fill-construct-bridge-guard-rail":new Tr(Zs.layout_fill["fill-construct-bridge-guard-rail"])})),paint:Bht||(Bht=new Ku({"fill-antialias":new xr(Zs.paint_fill["fill-antialias"]),"fill-opacity":new Tr(Zs.paint_fill["fill-opacity"]),"fill-color":new Tr(Zs.paint_fill["fill-color"]),"fill-outline-color":new Tr(Zs.paint_fill["fill-outline-color"]),"fill-translate":new xr(Zs.paint_fill["fill-translate"]),"fill-translate-anchor":new xr(Zs.paint_fill["fill-translate-anchor"]),"fill-pattern":new Tr(Zs.paint_fill["fill-pattern"]),"fill-pattern-cross-fade":new xr(Zs.paint_fill["fill-pattern-cross-fade"]),"fill-emissive-strength":new xr(Zs.paint_fill["fill-emissive-strength"]),"fill-z-offset":new Tr(Zs.paint_fill["fill-z-offset"]),"fill-bridge-guard-rail-color":new Tr(Zs.paint_fill["fill-bridge-guard-rail-color"]),"fill-tunnel-structure-color":new Tr(Zs.paint_fill["fill-tunnel-structure-color"]),"fill-color-use-theme":new Tr({type:"string",default:"default","property-type":"data-driven"}),"fill-outline-color-use-theme":new Tr({type:"string",default:"default","property-type":"data-driven"}),"fill-bridge-guard-rail-color-use-theme":new Tr({type:"string",default:"default","property-type":"data-driven"}),"fill-tunnel-structure-color-use-theme":new Tr({type:"string",default:"default","property-type":"data-driven"})}))},p,_,A)}getProgramIds(){const N=this.paint.get("fill-pattern"),p=N&&N.constantOr(1),_=[p?"fillPattern":"fill"];return this.paint.get("fill-antialias")&&_.push(p&&!this.getPaintProperty("fill-outline-color")?"fillOutlinePattern":"fillOutline"),_}getDefaultProgramParams(N,p,_){return{config:new tR(this,{zoom:p,lut:_}),overrideFog:!1}}recalculate(N,p){super.recalculate(N,p);const _=this.paint._values["fill-outline-color"];_.value.kind==="constant"&&_.value.value===void 0&&(this.paint._values["fill-outline-color"]=this.paint._values["fill-color"])}createBucket(N){return new WFe(N)}queryRadius(){return Mle(this.paint.get("fill-translate"))}queryIntersectsFeature(N,p,_,A,M,F){return!N.queryGeometry.isAboveHorizon&&ZFe(Eht(N.tilespaceGeometry,this.paint.get("fill-translate"),this.paint.get("fill-translate-anchor"),F.angle,N.pixelToTileUnitsFactor),A)}isTileClipped(){return this.paint.get("fill-z-offset").constantOr(1)===0}is3D(N){if(this.paint.get("fill-z-offset").constantOr(1)!==0)return!0;const p=this.layout&&this.layout.get("fill-elevation-reference")!=="none";return N!=null?p&&!N:p}hasElevation(){return this.layout&&this.layout.get("fill-elevation-reference")!=="none"}mayUse(N){return N==="HD"&&R9(this,"fill-elevation-reference",p=>p!=="none")}prepare(){return this.mayUse("HD")?Tle():Promise.resolve()}hasShadowPass(){return this.layout&&this.layout.get("fill-elevation-reference")!=="none"}},"fill-extrusion":class extends e0{constructor(N,p,_,A){super(N,{layout:qht||(qht=new Ku({visibility:new xr(Zs["layout_fill-extrusion"].visibility),"fill-extrusion-edge-radius":new xr(Zs["layout_fill-extrusion"]["fill-extrusion-edge-radius"]),"source-max-zoom":new xr(Zs["layout_fill-extrusion"]["source-max-zoom"])})),paint:Vht||(Vht=new Ku({"fill-extrusion-opacity":new xr(Zs["paint_fill-extrusion"]["fill-extrusion-opacity"]),"fill-extrusion-color":new Tr(Zs["paint_fill-extrusion"]["fill-extrusion-color"]),"fill-extrusion-translate":new xr(Zs["paint_fill-extrusion"]["fill-extrusion-translate"]),"fill-extrusion-translate-anchor":new xr(Zs["paint_fill-extrusion"]["fill-extrusion-translate-anchor"]),"fill-extrusion-pattern":new Tr(Zs["paint_fill-extrusion"]["fill-extrusion-pattern"]),"fill-extrusion-pattern-cross-fade":new xr(Zs["paint_fill-extrusion"]["fill-extrusion-pattern-cross-fade"]),"fill-extrusion-height":new Tr(Zs["paint_fill-extrusion"]["fill-extrusion-height"]),"fill-extrusion-base":new Tr(Zs["paint_fill-extrusion"]["fill-extrusion-base"]),"fill-extrusion-height-alignment":new xr(Zs["paint_fill-extrusion"]["fill-extrusion-height-alignment"]),"fill-extrusion-base-alignment":new xr(Zs["paint_fill-extrusion"]["fill-extrusion-base-alignment"]),"fill-extrusion-vertical-gradient":new xr(Zs["paint_fill-extrusion"]["fill-extrusion-vertical-gradient"]),"fill-extrusion-ambient-occlusion-intensity":new xr(Zs["paint_fill-extrusion"]["fill-extrusion-ambient-occlusion-intensity"]),"fill-extrusion-ambient-occlusion-radius":new xr(Zs["paint_fill-extrusion"]["fill-extrusion-ambient-occlusion-radius"]),"fill-extrusion-ambient-occlusion-wall-radius":new xr(Zs["paint_fill-extrusion"]["fill-extrusion-ambient-occlusion-wall-radius"]),"fill-extrusion-ambient-occlusion-ground-radius":new xr(Zs["paint_fill-extrusion"]["fill-extrusion-ambient-occlusion-ground-radius"]),"fill-extrusion-ambient-occlusion-ground-attenuation":new xr(Zs["paint_fill-extrusion"]["fill-extrusion-ambient-occlusion-ground-attenuation"]),"fill-extrusion-flood-light-color":new xr(Zs["paint_fill-extrusion"]["fill-extrusion-flood-light-color"]),"fill-extrusion-flood-light-intensity":new xr(Zs["paint_fill-extrusion"]["fill-extrusion-flood-light-intensity"]),"fill-extrusion-flood-light-wall-radius":new Tr(Zs["paint_fill-extrusion"]["fill-extrusion-flood-light-wall-radius"]),"fill-extrusion-flood-light-ground-radius":new Tr(Zs["paint_fill-extrusion"]["fill-extrusion-flood-light-ground-radius"]),"fill-extrusion-flood-light-ground-attenuation":new xr(Zs["paint_fill-extrusion"]["fill-extrusion-flood-light-ground-attenuation"]),"fill-extrusion-vertical-scale":new xr(Zs["paint_fill-extrusion"]["fill-extrusion-vertical-scale"]),"fill-extrusion-rounded-roof":new xr(Zs["paint_fill-extrusion"]["fill-extrusion-rounded-roof"]),"fill-extrusion-cutoff-fade-range":new xr(Zs["paint_fill-extrusion"]["fill-extrusion-cutoff-fade-range"]),"fill-extrusion-front-cutoff":new xr(Zs["paint_fill-extrusion"]["fill-extrusion-front-cutoff"]),"fill-extrusion-emissive-strength":new Tr(Zs["paint_fill-extrusion"]["fill-extrusion-emissive-strength"]),"fill-extrusion-line-width":new Tr(Zs["paint_fill-extrusion"]["fill-extrusion-line-width"]),"fill-extrusion-cast-shadows":new xr(Zs["paint_fill-extrusion"]["fill-extrusion-cast-shadows"]),"fill-extrusion-color-use-theme":new Tr({type:"string",default:"default","property-type":"data-driven"}),"fill-extrusion-flood-light-color-use-theme":new Tr({type:"string",default:"default","property-type":"data-driven"})}))},p,_,A),this._stats={numRenderedVerticesInShadowPass:0,numRenderedVerticesInTransparentPass:0}}createBucket(N){return new Cle(N)}queryRadius(){return Mle(this.paint.get("fill-extrusion-translate"))}is3D(N){return!0}hasShadowPass(){return this.paint.get("fill-extrusion-cast-shadows")}cutoffRange(){return this.paint.get("fill-extrusion-cutoff-fade-range")}canCastShadows(){return!0}getProgramIds(){return[this.paint.get("fill-extrusion-pattern").constantOr(1)?"fillExtrusionPattern":"fillExtrusion"]}queryIntersectsFeature(N,p,_,A,M,F,z,H,Z){const se=Tht(this.paint.get("fill-extrusion-translate"),this.paint.get("fill-extrusion-translate-anchor"),F.angle,N.pixelToTileUnitsFactor),fe=this.paint.get("fill-extrusion-height").evaluate(p,_),xe=this.paint.get("fill-extrusion-base").evaluate(p,_),be=[0,0],Te=H&&F.elevation,De=F.elevation?F.elevation.exaggeration():1,Ue=N.tile.getBucket(this);if(Ue instanceof Cle){const lt=Ue.centroidData.find(yt=>Z>=yt.vertexArrayOffset&&Zlt.polygon).flat());const Ye=Te?H:null,[st,ot]=Qht(F,A,xe,fe,se,z,Ye,be,De,F.center.lat,N.tileID.canonical),mt=N.queryGeometry;return Xht(st,ot,mt.isPointQuery()?mt.screenBounds:mt.screenGeometry)}},building:class extends e0{constructor(N,p,_,A){super(N,{layout:Hht||(Hht=new Ku({visibility:new xr(Zs.layout_building.visibility),"building-facade":new Tr(Zs.layout_building["building-facade"]),"building-facade-floors":new Tr(Zs.layout_building["building-facade-floors"]),"building-facade-unit-width":new Tr(Zs.layout_building["building-facade-unit-width"]),"building-facade-window":new Tr(Zs.layout_building["building-facade-window"]),"building-roof-shape":new Tr(Zs.layout_building["building-roof-shape"]),"building-height":new Tr(Zs.layout_building["building-height"]),"building-base":new Tr(Zs.layout_building["building-base"]),"building-flood-light-wall-radius":new Tr(Zs.layout_building["building-flood-light-wall-radius"]),"building-flood-light-ground-radius":new Tr(Zs.layout_building["building-flood-light-ground-radius"]),"building-flip-roof-orientation":new Tr(Zs.layout_building["building-flip-roof-orientation"])})),paint:Ght||(Ght=new Ku({"building-opacity":new xr(Zs.paint_building["building-opacity"]),"building-ambient-occlusion-intensity":new xr(Zs.paint_building["building-ambient-occlusion-intensity"]),"building-ambient-occlusion-ground-intensity":new xr(Zs.paint_building["building-ambient-occlusion-ground-intensity"]),"building-ambient-occlusion-ground-radius":new xr(Zs.paint_building["building-ambient-occlusion-ground-radius"]),"building-ambient-occlusion-ground-attenuation":new xr(Zs.paint_building["building-ambient-occlusion-ground-attenuation"]),"building-vertical-scale":new xr(Zs.paint_building["building-vertical-scale"]),"building-cast-shadows":new xr(Zs.paint_building["building-cast-shadows"]),"building-color":new Tr(Zs.paint_building["building-color"]),"building-emissive-strength":new Tr(Zs.paint_building["building-emissive-strength"]),"building-facade-emissive-chance":new xr(Zs.paint_building["building-facade-emissive-chance"]),"building-cutoff-fade-range":new xr(Zs.paint_building["building-cutoff-fade-range"]),"building-front-cutoff":new xr(Zs.paint_building["building-front-cutoff"]),"building-flood-light-color":new xr(Zs.paint_building["building-flood-light-color"]),"building-flood-light-intensity":new xr(Zs.paint_building["building-flood-light-intensity"]),"building-flood-light-ground-attenuation":new xr(Zs.paint_building["building-flood-light-ground-attenuation"]),"building-color-use-theme":new Tr({type:"string",default:"default","property-type":"data-driven"}),"building-flood-light-color-use-theme":new Tr({type:"string",default:"default","property-type":"data-driven"})}))},p,_,A),this._stats={numRenderedVerticesInShadowPass:0,numRenderedVerticesInTransparentPass:0}}mayUse(N){return N==="HD"}prepare(){return async function(){return function(){if(!Xc(self)||fj!=null||Sht!=null)return null;if(r$!=null)return r$;const N=fetch(jt());return r$=function(p){let _,A,M,F,z;function H(){_=new Uint8Array(z.buffer),A=new Int16Array(z.buffer),M=new Int32Array(z.buffer),F=new Float32Array(z.buffer)}function Z(){throw new Error("Unexpected BuildingGen error.")}const se=()=>{},fe={a:{a:Z,f:function(xe){const be=_.length,Te=Math.max(xe>>>0,Math.ceil(1.2*be)),De=Math.ceil((Te-be)/65536);try{return z.grow(De),H(),!0}catch{return!1}},g:Z,b:se,c:se,d:se,e:se}};return(WebAssembly.instantiateStreaming?WebAssembly.instantiateStreaming(p,fe):p.then(xe=>xe.arrayBuffer()).then(xe=>WebAssembly.instantiate(xe,fe))).then(xe=>{const be=xe.instance.exports;return(0,be.g)(),z=be.f,H(),new Bfs({setStyle:be.h,setAOOptions:be.i,setMetricOptions:be.j,setStructuralOptions:be.k,setFacadeOptions:be.l,setFauxFacadeOptions:be.m,setFacadeClassifierOptions:be.n,addFeature:be.o,addFacade:be.p,generateMesh:be.q,getLastError:be.r,getOuterRingLength:be.s,getMeshCount:be.t,getPositionsPtr:be.u,getPositionsLength:be.v,getNormalsPtr:be.w,getNormalsLength:be.x,getAOPtr:be.y,getAOLength:be.z,getUVPtr:be.A,getUVLength:be.B,getFauxFacadePtr:be.C,getFauxFacadeLength:be.D,getIndicesPtr:be.E,getIndicesLength:be.F,getBuildingPart:be.G,getRingCount:be.H,getRingPtr:be.I,getRingLength:be.J,malloc:be.K,free:be.L,heapU8:_,heap16:A,heap32:M,heapF32:F})})}(N).then(p=>{r$=null,fj=p}).catch(p=>{Yo("Could not load building-gen"),r$=null,Sht=p}),r$}()}()}createBucket(N){return new Cht(N)}cutoffRange(){return this.paint.get("building-cutoff-fade-range")}hasShadowPass(){return this.paint.get("building-cast-shadows")}hasLightBeamPass(){return!0}canCastShadows(){return!0}is3D(N){return!0}queryRadius(N){return 0}queryIntersectsFeature(N,p,_,A,M,F,z,H,Z,se){let fe=this.layout.get("building-height").evaluate(p,_);const xe=this.layout.get("building-base").evaluate(p,_),be=N.tile.getBucket(this).getFootprint(p);if(be){if(be.hiddenFlags!==0)return!1;fe=be.height}const[Te,De]=Qht(F,A,xe,fe,new xs(0,0),z,null,[0,0],1,F.center.lat,N.tileID.canonical),Ue=N.queryGeometry;return Xht(Te,De,Ue.isPointQuery()?Ue.screenBounds:Ue.screenGeometry)}},line:class extends e0{constructor(N,p,_,A){const M=rmt();super(N,M,p,_,A),M.layout&&(this.layout=new Sl(M.layout)),this.gradientVersion=0,this.borderGradientVersion=0,this.hasElevatedBuckets=!1,this.hasNonElevatedBuckets=!1,this.lineBlendFbos=null,this.lineBlendDensityReadback=null}_handleSpecialPaintPropertyUpdate(N){if(N==="line-gradient"){const p=this._transitionablePaint._values["line-gradient"].value.expression;this.stepInterpolant=p._styleExpression&&p._styleExpression.expression instanceof bi,this.gradientVersion=(this.gradientVersion+1)%Number.MAX_SAFE_INTEGER}else if(N==="line-gradient-use-theme")this.gradientVersion=(this.gradientVersion+1)%Number.MAX_SAFE_INTEGER;else if(N==="line-border-gradient"){const p=this._transitionablePaint._values["line-border-gradient"].value.expression;this.borderStepInterpolant=p._styleExpression&&p._styleExpression.expression instanceof bi,this.borderGradientVersion=(this.borderGradientVersion+1)%Number.MAX_SAFE_INTEGER}else N==="line-border-gradient-use-theme"&&(this.borderGradientVersion=(this.borderGradientVersion+1)%Number.MAX_SAFE_INTEGER)}gradientExpression(){return this._transitionablePaint._values["line-gradient"].value.expression}borderGradientExpression(){return this._transitionablePaint._values["line-border-gradient"].value.expression}widthExpression(){return this._transitionablePaint._values["line-width"].value.expression}emissiveStrengthExpression(){return this._transitionablePaint._values["line-emissive-strength"].value.expression}recalculate(N,p){super.recalculate(N,p),this.paint._values["line-floorwidth"]=(()=>{if(sZ)return sZ;const _=rmt();return sZ=new Zfs(_.paint.properties["line-width"].specification),sZ.useIntegerZoom=!0,sZ})().possiblyEvaluate(this._transitioningPaint._values["line-width"].value,N)}createBucket(N){return new rOe(N)}getProgramIds(){const N=[this.paint.get("line-pattern").constantOr(1)?"linePattern":"line"];return this.paint.get("line-blend-mode")!=="default"&&N.push("lineBlendComposite"),N}getDefaultProgramParams(N,p,_){if(N==="lineBlendComposite")return{};const A=smt(this);return{config:new tR(this,{zoom:p,lut:_}),defines:A,overrideFog:!1}}queryRadius(N){const p=N,_=omt(a$("line-width",this,p),a$("line-gap-width",this,p)),A=a$("line-offset",this,p);return _/2+Math.abs(A)+Mle(this.paint.get("line-translate"))}queryIntersectsFeature(N,p,_,A,M,F){if(N.queryGeometry.isAboveHorizon)return!1;const z=Eht(N.tilespaceGeometry,this.paint.get("line-translate"),this.paint.get("line-translate-anchor"),F.angle,N.pixelToTileUnitsFactor),H=N.pixelToTileUnitsFactor/2*omt(this.paint.get("line-width").evaluate(p,_),this.paint.get("line-gap-width").evaluate(p,_)),Z=this.paint.get("line-offset").evaluate(p,_);return Z&&(A=function(se,fe){const xe=[],be=new xs(0,0);for(let Te=0;Te=3){for(let De=0;Dep==="hd-road-markup"):N==="Lite"&&function(p){if(!p._unevaluatedLayout)return!1;const _=p._unevaluatedLayout.getValue("line-elevation-reference");if(_!==void 0&&(typeof _!="string"||_!=="none"))return!0;const A=p._unevaluatedLayout.getValue("line-z-offset");return A!==void 0&&(typeof A!="number"||A!==0)}(this)}prepare(){return this.mayUse("HD")?Tle():Promise.resolve()}hasOffscreenPass(){return this.paint.get("line-blend-mode")!=="default"&&this.paint.get("line-opacity").constantOr(1)!==0&&this.paint.get("line-width").constantOr(1)!==0&&this.visibility!=="none"}resize(){this._destroyLineBlendFbo()}onRemove(N){this._destroyLineBlendFbo(N.painter&&N.painter.context&&N.painter.context.gl||void 0)}_clear(){this._destroyLineBlendFbo()}_destroyLineBlendFbo(N){this.lineBlendFbos&&(this.lineBlendFbos.destroy(),this.lineBlendFbos=null),N&&this.lineBlendDensityReadback&&this.lineBlendDensityReadback.destroy(N),this.lineBlendDensityReadback=null}},symbol:Ple,background:class extends e0{constructor(N,p,_,A){super(N,{layout:umt||(umt=new Ku({visibility:new xr(Zs.layout_background.visibility)})),paint:hmt||(hmt=new Ku({"background-pitch-alignment":new xr(Zs.paint_background["background-pitch-alignment"]),"background-color":new xr(Zs.paint_background["background-color"]),"background-pattern":new xr(Zs.paint_background["background-pattern"]),"background-opacity":new xr(Zs.paint_background["background-opacity"]),"background-emissive-strength":new xr(Zs.paint_background["background-emissive-strength"]),"background-color-use-theme":new Tr({type:"string",default:"default","property-type":"data-driven"})}))},p,_,A)}getProgramIds(){return[this.paint.get("background-pattern")?"backgroundPattern":"background"]}getDefaultProgramParams(N,p,_){return{overrideFog:!1}}is3D(N){return this.paint.get("background-pitch-alignment")==="viewport"}},raster:pmt,"raster-particle":Nmt,sky:class extends e0{constructor(N,p,_,A){super(N,{layout:ymt||(ymt=new Ku({visibility:new xr(Zs.layout_sky.visibility)})),paint:vmt||(vmt=new Ku({"sky-type":new xr(Zs.paint_sky["sky-type"]),"sky-atmosphere-sun":new xr(Zs.paint_sky["sky-atmosphere-sun"]),"sky-atmosphere-sun-intensity":new xr(Zs.paint_sky["sky-atmosphere-sun-intensity"]),"sky-gradient-center":new xr(Zs.paint_sky["sky-gradient-center"]),"sky-gradient-radius":new xr(Zs.paint_sky["sky-gradient-radius"]),"sky-gradient":new R3(Zs.paint_sky["sky-gradient"]),"sky-atmosphere-halo-color":new xr(Zs.paint_sky["sky-atmosphere-halo-color"]),"sky-atmosphere-color":new xr(Zs.paint_sky["sky-atmosphere-color"]),"sky-opacity":new xr(Zs.paint_sky["sky-opacity"]),"sky-gradient-use-theme":new Tr({type:"string",default:"default","property-type":"data-driven"}),"sky-atmosphere-halo-color-use-theme":new Tr({type:"string",default:"default","property-type":"data-driven"}),"sky-atmosphere-color-use-theme":new Tr({type:"string",default:"default","property-type":"data-driven"})}))},p,_,A),this._updateColorRamp()}_clear(){this.skyboxFbo&&(this.skyboxFbo.destroy(),this.skyboxFbo=null),this.colorRampTexture&&(this.colorRampTexture.destroy(),this.colorRampTexture=null),this._skyboxInvalidated=!0}_handleSpecialPaintPropertyUpdate(N){N==="sky-gradient"?this._updateColorRamp():N!=="sky-atmosphere-sun"&&N!=="sky-atmosphere-halo-color"&&N!=="sky-atmosphere-color"&&N!=="sky-atmosphere-sun-intensity"||(this._skyboxInvalidated=!0)}_updateColorRamp(){this.colorRamp=JY({expression:this._transitionablePaint._values["sky-gradient"].value.expression,evaluationKey:"skyRadialProgress"}),this.colorRampTexture&&(this.colorRampTexture.destroy(),this.colorRampTexture=null)}needsSkyboxCapture(N){if(this._skyboxInvalidated||!this.skyboxTexture||!this.skyboxGeometry)return!0;if(!this.paint.get("sky-atmosphere-sun")){const p=N.style.light.properties.get("position");return this._lightPosition.azimuthal!==p.azimuthal||this._lightPosition.polar!==p.polar}return!1}getCenter(N,p){if(this.paint.get("sky-type")==="atmosphere"){const A=this.paint.get("sky-atmosphere-sun"),M=!A,F=N.style.light,z=F.properties.get("position");return M&&F.properties.get("anchor")==="viewport"&&Yo("The sun direction is attached to a light with viewport anchor, lighting may behave unexpectedly."),M?p8e(z.azimuthal,90-z.polar,p):p8e(A[0],90-A[1],p)}const _=this.paint.get("sky-gradient-center");return p8e(_[0],90-_[1],p)}isSky(){return!0}markSkyboxValid(N){this._skyboxInvalidated=!1,this._lightPosition=N.style.light.properties.get("position")}hasOffscreenPass(){return!0}getProgramIds(){const N=this.paint.get("sky-type");return N==="atmosphere"?["skyboxCapture","skybox"]:N==="gradient"?["skyboxGradient"]:null}},slot:class extends e0{constructor(N,p,_,A){super(N,{paint:bmt||(bmt=new Ku({}))},p,null)}},"placement-group":class extends e0{constructor(N,p,_,A){super(N,{paint:_mt||(_mt=new Ku({}))},p,_,A)}},model:class extends e0{constructor(N,p,_,A){super(N,{layout:wmt||(wmt=new Ku({visibility:new xr(Zs.layout_model.visibility),"model-id":new Tr(Zs.layout_model["model-id"]),"model-allow-density-reduction":new xr(Zs.layout_model["model-allow-density-reduction"])})),paint:jmt||(jmt=new Ku({"model-opacity":new Tr(Zs.paint_model["model-opacity"]),"model-rotation":new Tr(Zs.paint_model["model-rotation"]),"model-scale":new Tr(Zs.paint_model["model-scale"]),"model-translation":new Tr(Zs.paint_model["model-translation"]),"model-color":new Tr(Zs.paint_model["model-color"]),"model-color-mix-intensity":new Tr(Zs.paint_model["model-color-mix-intensity"]),"model-type":new xr(Zs.paint_model["model-type"]),"model-cast-shadows":new xr(Zs.paint_model["model-cast-shadows"]),"model-receive-shadows":new xr(Zs.paint_model["model-receive-shadows"]),"model-ambient-occlusion-intensity":new xr(Zs.paint_model["model-ambient-occlusion-intensity"]),"model-emissive-strength":new Tr(Zs.paint_model["model-emissive-strength"]),"model-roughness":new Tr(Zs.paint_model["model-roughness"]),"model-height-based-emissive-strength-multiplier":new Tr(Zs.paint_model["model-height-based-emissive-strength-multiplier"]),"model-cutoff-fade-range":new xr(Zs.paint_model["model-cutoff-fade-range"]),"model-front-cutoff":new xr(Zs.paint_model["model-front-cutoff"]),"model-elevation-reference":new xr(Zs.paint_model["model-elevation-reference"]),"model-line-cutout-mode":new xr(Zs.paint_model["model-line-cutout-mode"]),"model-color-use-theme":new Tr({type:"string",default:"default","property-type":"data-driven"})}))},p,_,A),this.layer=N,this._stats={numRenderedVerticesInShadowPass:0,numRenderedVerticesInTransparentPass:0}}mayUse(N){return N==="Standard"}prepare(){return Aft()}createBucket(N){return new g8e(N)}getProgramIds(){return["model"]}is3D(N){return!0}hasShadowPass(){return this.paint.get("model-cast-shadows")}canCastShadows(){return!0}hasLightBeamPass(){return!0}cutoffRange(){return this.paint.get("model-cutoff-fade-range")}queryRadius(N){return N.isTiled3dModelBucket?8191:0}queryRenderedFeatures(N,p,_){return dR.queryModelLayerRendered?dR.queryModelLayerRendered(this,N,p,_):{}}queryIntersectsFeature(N,p,_,A,M,F,z,H,Z,se){return!!dR.queryModelLayerIntersectsFeature&&dR.queryModelLayerIntersectsFeature(this,N,p,_,F,se)}_handleOverridablePaintPropertyUpdate(N,p,_){return!(!this.layout||p.isDataDriven()||_.isDataDriven()||N!=="model-color"&&N!=="model-color-mix-intensity"&&N!=="model-rotation"&&N!=="model-scale"&&N!=="model-translation"&&N!=="model-emissive-strength")}_isPropertyZoomDependent(N){const p=this._transitionablePaint._values[N];return p!=null&&p.value!=null&&p.value.expression!=null&&p.value.expression instanceof cg}isZoomDependent(){return this._isPropertyZoomDependent("model-scale")||this._isPropertyZoomDependent("model-rotation")||this._isPropertyZoomDependent("model-translation")}},clip:class extends e0{constructor(N,p,_,A){super(N,{layout:$ht||($ht=new Ku({"clip-layer-types":new xr(Zs.layout_clip["clip-layer-types"]),"clip-layer-scope":new xr(Zs.layout_clip["clip-layer-scope"]),visibility:new xr(Zs.layout_clip.visibility)})),paint:Uht||(Uht=new Ku({}))},p,_,A)}recalculate(N,p){super.recalculate(N,p)}createBucket(N){return new Yht(N)}is3D(N){return!0}}};class D8e{constructor(p){this.capacity=p,this.cache=new Map}get(p){if(!this.cache.has(p))return;const _=this.cache.get(p);return this.cache.delete(p),this.cache.set(p,_),_}put(p,_){this.cache.has(p)?this.cache.delete(p):this.cache.size===this.capacity&&this.cache.delete(this.cache.keys().next().value),this.cache.set(p,_)}delete(p){this.cache.delete(p)}}oa(D8e,"LRUCache");class Lps{constructor(p){this._callback=p,this._triggered=!1,typeof MessageChannel<"u"&&(this._channel=new MessageChannel,this._channel.port2.onmessage=()=>{this._triggered=!1,this._callback()})}trigger(){this._triggered||(this._triggered=!0,this._channel?this._channel.port1.postMessage(!0):setTimeout(()=>{this._triggered=!1,this._callback()},0))}remove(){this._channel&&(this._channel.port1.close(),this._channel.port2.close()),this._callback=()=>{}}}const Eft={Other:0,Symbol:1,FillExtrusion:2,HdRoadCoverage:3};class Rps{constructor(){this.tasks=new Map,Bc(["process"],this),this.invoker=new Lps(this.process),this.nextId=0}add(p,_){const A=this.nextId++,M=function({type:F,renderSourceType:z,zoom:H}){H=H||0;const Z=z===Eft.Symbol;return F==="message"?0:F!=="maybePrepare"||Z?F!=="parseTile"||Z?F==="parseTile"&&Z?300-H:F==="maybePrepare"&&Z?400-H:500:200-H:100-H}(_);if(M===0){try{p()}finally{}return null}return this.tasks.set(A,{fn:p,metadata:_,priority:M,id:A}),this.invoker.trigger(),{cancel:()=>{this.tasks.delete(A)}}}process(){try{const p=this.pick();if(!p)return;this.tasks.delete(p.id),this.tasks.size>0&&this.invoker.trigger(),p.fn()}finally{}}pick(){let p=null,_=1/0;for(const A of this.tasks.values())A.priority<_&&(_=A.priority,p=A);return p}remove(){this.tasks.clear(),this.invoker.remove()}}const Tft={type:"message"},F8e=new Map,Mft=new Map;class Pft{constructor(p){this.size=p,this.minimums=[],this.maximums=[],this.leaves=[]}getElevation(p,_){const A=this.toIdx(p,_);return{min:this.minimums[A],max:this.maximums[A]}}isLeaf(p,_){return this.leaves[this.toIdx(p,_)]}toIdx(p,_){return _*this.size+p}}function Ift(N,p,_,A){let M=0,F=Number.MAX_VALUE;for(let z=0;z<3;z++)if(Math.abs(A[z])<1e-15){if(_[z]p[z])return null}else{const H=1/A[z];let Z=(N[z]-_[z])*H,se=(p[z]-_[z])*H;if(Z>se){const fe=Z;Z=se,se=fe}if(Z>M&&(M=Z),seF)return null}return M}function Lft(N,p,_,A,M,F,z,H,Z,se,fe){const xe=A-N,be=M-p,Te=F-_,De=z-N,Ue=H-p,Ye=Z-_,st=fe[1]*Ye-fe[2]*Ue,ot=fe[2]*De-fe[0]*Ye,mt=fe[0]*Ue-fe[1]*De,lt=xe*st+be*ot+Te*mt;if(Math.abs(lt)<1e-15)return null;const yt=1/lt,Nt=se[0]-N,as=se[1]-p,Et=se[2]-_,$t=(Nt*st+as*ot+Et*mt)*yt;if($t<0||$t>1)return null;const Jt=as*Te-Et*be,ns=Et*xe-Nt*Te,Ls=Nt*be-as*xe,Gs=(fe[0]*Jt+fe[1]*ns+fe[2]*Ls)*yt;return Gs<0||$t+Gs>1?null:(De*Jt+Ue*ns+Ye*Ls)*yt}function Rft(N,p,_,A,M,F,z,H,Z){const se=1<<_,fe=F-A,xe=z-M,be=(N+1)/se*fe+A,Te=(p+0)/se*xe+M,De=(p+1)/se*xe+M;H[0]=(N+0)/se*fe+A,H[1]=Te,Z[0]=be,Z[1]=De}class Dft{constructor(p){if(this.maximums=[],this.minimums=[],this.leaves=[],this.childOffsets=[],this.nodeCount=0,this.dem=p,this._siblingOffset=[[0,0],[1,0],[0,1],[1,1]],!this.dem)return;const _=function(F){const z=F.dim,H=Math.ceil(Math.log2(z/8)),Z=[];let se=Math.ceil(Math.pow(2,H));const fe=(Ye,st,ot,mt,lt)=>{const yt=mt?1:0,Nt=(Ye+1)*ot-yt,as=st*ot,Et=(st+1)*ot-yt;lt[0]=Ye*ot,lt[1]=as,lt[2]=Nt,lt[3]=Et};let xe=new Pft(se);const be=1/se,{floatView:Te,stride:De}=F,Ue=[];for(let Ye=0;YeLs&&(Ls=jn)}}xe.minimums.push(as),xe.maximums.push(Ls),xe.leaves.push(1)}for(Z.push(xe),se/=2;se>=1;se/=2){const Ye=Z.at(-1);xe=new Pft(se);for(let st=0;st0;){const{idx:De,t:Ue,nodex:Ye,nodey:st,depth:ot}=Te.pop();if(this.leaves[De]){Rft(Ye,st,ot,p,_,A,M,xe,be);const lt=1<1e-10,ir=Math.abs(z[1])>1e-10,Bn=z[0]>=0?1:-1,Rr=z[1]>=0?1:-1;let cr=Math.max(0,Math.min(cn-1,Math.floor((In-Hn)/Qs))),jr=Math.max(0,Math.min(jn-1,Math.floor((Vn-Cs)/an)));const Wa=Dn?Math.abs(Qs/z[0]):Number.MAX_VALUE,Ka=ir?Math.abs(an/z[1]):Number.MAX_VALUE;let oi=Dn?Ln+(Hn+(z[0]>=0?cr+1:cr)*Qs-In)/z[0]:Number.MAX_VALUE,Fa=ir?Ln+(Cs+(z[1]>=0?jr+1:jr)*an-Vn)/z[1]:Number.MAX_VALUE;const Ai=(Hm,mo)=>Jt[(mo+1)*ns+Hm+1]*H;let Ni=Ai(Ls+cr,pn+jr),Fo=Ai(Ls+cr+1,pn+jr),rl=Ai(Ls+cr,pn+jr+1),$l=Ai(Ls+cr+1,pn+jr+1),wc=null;for(let Hm=0;Hm=0||F[2]+z[2]*mo<=Math.max(Ni,Fo,rl,$l)){const Lp=Hn+cr*Qs,xf=Lp+Qs,Vx=Cs+jr*an,Hx=Vx+an,Gb=Lft(xf,Vx,Fo,Lp,Vx,Ni,Lp,Hx,rl,F,z),Sy=Lft(Lp,Hx,rl,xf,Hx,$l,xf,Vx,Fo,F,z);Gb!=null&&Gb>=0&&(wc===null||Gb=0&&(wc===null||Sy=cn||jr<0||jr>=jn||wc!==null&&mo>wc)break;fp?Bn>0?(Ni=Fo,rl=$l,Fo=Ai(Ls+cr+1,pn+jr),$l=Ai(Ls+cr+1,pn+jr+1)):(Fo=Ni,$l=rl,Ni=Ai(Ls+cr,pn+jr),rl=Ai(Ls+cr,pn+jr+1)):Rr>0?(Ni=rl,Fo=$l,rl=Ai(Ls+cr,pn+jr+1),$l=Ai(Ls+cr+1,pn+jr+1)):(rl=Ni,$l=Fo,Ni=Ai(Ls+cr,pn+jr),Fo=Ai(Ls+cr+1,pn+jr))}if(wc!==null)return wc||0;const Vm=ke([],F,z,Ue),Z0=(Vm[0]-xe[0])/(be[0]-xe[0]),Jh=(Vm[1]-xe[1])/(be[1]-xe[1]),_l=gM(yt,as,this.dem)*H,Wd=gM(Nt,as,this.dem)*H,fh=gM(Nt,Et,this.dem)*H;if(Fft(_l,Wd,gM(yt,Et,this.dem)*H,fh,Z0,Jh)>=Vm[2])return Ue;continue}let mt=0;for(let lt=0;lt=se[fe[Et]]&&(fe.splice(Et,0,lt),as=!0);as||(fe[mt]=lt),mt++}}for(let lt=0;lt=this.dim+1||_<-1||_>=this.dim+1)throw new RangeError("out of range source coordinates for DEM data");return(_+1)*this.stride+(p+1)}static pack(p,_){const A=[0,0,0,0],M=Kle.getUnpackVector(_);let F=Math.floor((p+M[3])/M[2]);return A[2]=F%256,F=Math.floor(F/256),A[1]=F%256,F=Math.floor(F/256),A[0]=F,A}getPixels(){return new ydt({width:this.stride,height:this.stride},this.pixels)}backfillBorder(p,_,A){if(this.dim!==p.dim)throw new Error("dem dimension mismatch");let M=_*this.dim,F=_*this.dim+this.dim,z=A*this.dim,H=A*this.dim+this.dim;switch(_){case-1:M=F-1;break;case 1:F=M+1}switch(A){case-1:z=H-1;break;case 1:H=z+1}const Z=-_*this.dim,se=-A*this.dim;for(let fe=z;fe=1;A--){const M=A===1?1:0,F=A===2?1:0;for(let z=0;z>>1^-(1&N[p]);return N}function Wps(N,p){switch(p){case"uint32":return N;case"uint16":for(let _=0;_>4|(61440&A)>>8|(240&M)<<4|61440&M,N[_+1]=15&A|(3840&A)>>4|(15&M)<<8|(3840&M)<<4}return N;case"uint8":for(let _=0;_>6|(192&M)>>4|(192&F)>>2|192&z,N[_+1]=(48&A)>>4|(48&M)>>2|48&F|(48&z)<<2,N[_+2]=(12&A)>>2|12&M|(12&F)<<2|(12&z)<<4,N[_+3]=3&A|(3&M)<<2|(3&F)<<4|(3&z)<<6}return N;default:throw new Error(`Invalid pixel format, "${p}"`)}}oa(Kle,"DEMData"),oa(Dft,"DemMinMaxQuadTree",{omit:["dem"]});var gj=Uint8Array,oZ=Uint16Array,Kps=Int32Array,Oft=new gj([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]),zft=new gj([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]),Yps=new gj([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),Bft=function(N,p){for(var _=new oZ(31),A=0;A<31;++A)_[A]=p+=1<>1|(21845&mp)<<1;qft[mp]=((65280&(d$=(61680&(d$=(52428&d$)>>2|(13107&d$)<<2))>>4|(3855&d$)<<4))>>8|(255&d$)<<8)>>1}var lZ=function(N,p,_){for(var A=N.length,M=0,F=new oZ(p);M>Z]=se;return z},cZ=new gj(288);for(mp=0;mp<144;++mp)cZ[mp]=8;for(mp=144;mp<256;++mp)cZ[mp]=9;for(mp=256;mp<280;++mp)cZ[mp]=7;for(mp=280;mp<288;++mp)cZ[mp]=8;var Vft=new gj(32);for(mp=0;mp<32;++mp)Vft[mp]=5;var Qps=lZ(cZ,9),Jps=lZ(Vft,5),O8e=function(N){for(var p=N[0],_=1;_p&&(p=N[_]);return p},Xk=function(N,p,_){var A=p/8|0;return(N[A]|N[A+1]<<8)>>(7&p)&_},z8e=function(N,p){var _=p/8|0;return(N[_]|N[_+1]<<8|N[_+2]<<16)>>(7&p)},egs=function(N){return(N+7)/8|0},tgs=["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"],Qk=function(N,p,_){var A=new Error(p||tgs[N]);if(A.code=N,Error.captureStackTrace&&Error.captureStackTrace(A,Qk),!_)throw A;return A},sgs=new gj(0),ngs=typeof TextDecoder<"u"&&new TextDecoder;try{ngs.decode(sgs,{stream:!0})}catch{}const rgs={gzip_data:"gzip"};class rN extends Error{constructor(p){super(p),this.name="MRTError"}}const ags={0:"uint32",1:"uint32",2:"uint16",3:"uint8"},Hft={uint32:1,uint16:2,uint8:4},igs={uint32:Uint32Array,uint16:Uint16Array,uint8:Uint8Array};let B8e;class Yle{constructor(p=5){this.x=NaN,this.y=NaN,this.z=NaN,this.layers={},this._cacheSize=p}getLayer(p){const _=this.layers[p];if(!_)throw new rN(`Layer '${p}' not found`);return _}getHeaderLength(p){const _=new Uint8Array(p),A=new DataView(p);if(_[0]!==13)throw new rN("File is not a valid MRT.");return A.getUint32(1,!0)}parseHeader(p){const _=new Uint8Array(p),A=this.getHeaderLength(p);if(_.length= ${A} but got buffer of length ${_.length}`);const M=function(F){const z={headerLength:0,x:0,y:0,z:0,layers:[]};let H;for(;H=F.nextField(void 0);)H===1?z.headerLength=F.readFixed32():H===2?z.x=F.readVarint():H===3?z.y=F.readVarint():H===4?z.z=F.readVarint():H===5&&z.layers.push(qps(F,F.readVarint()+F.pos));return z}(new B8e(_.subarray(0,A)));if(!isNaN(this.x)&&(this.x!==M.x||this.y!==M.y||this.z!==M.z))throw new rN(`Invalid attempt to parse header ${M.z}/${M.x}/${M.y} for tile ${this.z}/${this.x}/${this.y}`);this.x=M.x,this.y=M.y,this.z=M.z;for(const F of M.layers)this.layers[F.name]=new Gft(F,{cacheSize:this._cacheSize});return this}createDecodingTask(p){const _=[],A=this.getLayer(p.layerName);for(let M of p.blockIndices){const F=A.dataIndex[M],z=F.firstByte-p.firstByte,H=F.lastByte-p.firstByte;if(A._blocksInProgress.has(M))continue;const Z={layerName:A.name,firstByte:z,lastByte:H,pixelFormat:A.pixelFormat,blockIndex:M,blockShape:[F.bands.length].concat(A.bandShape),buffer:A.buffer,codec:F.codec.codec,filters:F.filters.map(se=>se.filter)};A._blocksInProgress.add(M),_.push(Z)}return new Wft(_,()=>{_.forEach(M=>A._blocksInProgress.delete(M.blockIndex))},(M,F)=>{if(_.forEach(z=>A._blocksInProgress.delete(z.blockIndex)),M)throw M;F.forEach(z=>{this.getLayer(z.layerName).processDecodedData(z)})})}}class Gft{constructor({version:p,name:_,units:A,tileSize:M,pixelFormat:F,buffer:z,dataIndex:H},Z){if(this.version=p,this.version!==1)throw new rN(`Cannot parse raster layer encoded with MRT version ${p}`);this.name=_,this.units=A,this.tileSize=M,this.buffer=z,this.pixelFormat=ags[F],this.dataIndex=H,this.bandShape=[M+2*z,M+2*z,Hft[this.pixelFormat]],this._decodedBlocks=new D8e(Z?Z.cacheSize:5),this._blocksInProgress=new Set}get dimension(){return Hft[this.pixelFormat]}get cacheSize(){return this._decodedBlocks.capacity}getBandList(){return this.dataIndex.map(({bands:p})=>p).flat()}processDecodedData(p){const _=p.blockIndex.toString();this._decodedBlocks.get(_)||this._decodedBlocks.put(_,p.data)}getBlockForBand(p){let _=0;switch(typeof p){case"string":for(const[A,M]of this.dataIndex.entries()){for(const[F,z]of M.bands.entries())if(z===p)return{bandIndex:_+F,blockIndex:A,blockBandIndex:F};_+=M.bands.length}break;case"number":for(const[A,M]of this.dataIndex.entries()){if(p>=_&&p<_+M.bands.length)return{bandIndex:p,blockIndex:A,blockBandIndex:p-_};_+=M.bands.length}break;default:throw new rN(`Invalid band \`${JSON.stringify(p)}\`. Expected string or integer.`)}return{blockIndex:-1,blockBandIndex:-1}}getDataRange(p){let _=1/0,A=-1/0;const M=[],F=new Set;for(const z of p){const{blockIndex:H}=this.getBlockForBand(z);if(H<0)throw new rN(`Invalid band: ${JSON.stringify(z)}`);const Z=this.dataIndex[H];M.includes(H)||M.push(H),F.add(H),_=Math.min(_,Z.firstByte),A=Math.max(A,Z.lastByte)}if(F.size>this.cacheSize)throw new rN(`Number of blocks to decode (${F.size}) exceeds cache size (${this.cacheSize}).`);return{layerName:this.name,firstByte:_,lastByte:A,blockIndices:M}}hasBand(p){const{blockIndex:_}=this.getBlockForBand(p);return _>=0}hasDataForBand(p){const{blockIndex:_}=this.getBlockForBand(p);return _>=0&&!!this._decodedBlocks.get(_.toString())}getBandView(p){const{blockIndex:_,blockBandIndex:A}=this.getBlockForBand(p);if(_<0)throw new rN(`Band not found: ${JSON.stringify(p)}`);const M=this._decodedBlocks.get(_.toString());if(!M)throw new rN(`Data for band ${JSON.stringify(p)} of layer "${this.name}" not decoded.`);const F=this.dataIndex[_],z=this.bandShape.reduce((se,fe)=>se*fe,1),H=A*z,Z=M.subarray(H,H+z);return{data:Z,bytes:new Uint8Array(Z.buffer).subarray(Z.byteOffset,Z.byteOffset+Z.byteLength),tileSize:this.tileSize,buffer:this.buffer,pixelFormat:this.pixelFormat,dimension:this.dimension,offset:F.offset,scale:F.scale}}}Yle.setPbf=function(N){B8e=N};class Wft{constructor(p,_,A){this.tasks=p,this._onCancel=_,this._onComplete=A,this._finalized=!1}cancel(){this._finalized||(this._onCancel(),this._finalized=!0)}complete(p,_){this._finalized||(this._onComplete(p,_),this._finalized=!0)}}Yle.performDecoding=function(N,p){const _=new Uint8Array(N);return Promise.all(p.tasks.map(A=>{const{layerName:M,firstByte:F,lastByte:z,pixelFormat:H,blockShape:Z,blockIndex:se,filters:fe,codec:xe}=A,be=_.subarray(F,z+1),Te=new Uint32Array(Z[0]*Z[1]*Z[2]);let De;if(xe!=="gzip_data")throw new rN(`Unhandled codec: ${xe}`);return De=function(Ue,Ye){if(!globalThis.DecompressionStream&&Ye==="gzip_data")return Promise.resolve((yt=function(Et){Et[0]==31&&Et[1]==139&&Et[2]==8||Qk(6,"invalid gzip data");var $t=Et[3],Jt=10;4&$t&&(Jt+=2+(Et[10]|Et[11]<<8));for(var ns=($t>>3&1)+($t>>4&1);ns>0;ns-=!Et[Jt++]);return Jt+(2&$t)}(st=Ue),yt+8>st.length&&Qk(6,"invalid gzip data"),function(Et,$t,Jt,ns){var Ls=Et.length;if(!Ls||$t.f&&!$t.l)return Jt||new gj(0);var Gs=!Jt,pn=Gs||$t.i!=2,cn=$t.i;Gs&&(Jt=new gj(3*Ls));var jn=function(Sy){var Gx=Jt.length;if(Sy>Gx){var Cy=new gj(Math.max(2*Gx,Sy));Cy.set(Jt),Jt=Cy}},Hn=$t.f||0,Cs=$t.p||0,Qs=$t.b||0,an=$t.l,Ln=$t.d,In=$t.m,Vn=$t.n,Dn=8*Ls;do{if(!an){Hn=Xk(Et,Cs,1);var ir=Xk(Et,Cs+1,3);if(Cs+=3,!ir){var Bn=Et[(rl=egs(Cs)+4)-4]|Et[rl-3]<<8,Rr=rl+Bn;if(Rr>Ls){cn&&Qk(0);break}pn&&jn(Qs+Bn),Jt.set(Et.subarray(rl,Rr),Qs),$t.b=Qs+=Bn,$t.p=Cs=8*Rr,$t.f=Hn;continue}if(ir==1)an=Qps,Ln=Jps,In=9,Vn=5;else if(ir==2){var cr=Xk(Et,Cs,31)+257,jr=Xk(Et,Cs+10,15)+4,Wa=cr+Xk(Et,Cs+5,31)+1;Cs+=14;for(var Ka=new gj(Wa),oi=new gj(19),Fa=0;Fa>4)<16)Ka[Fa++]=rl;else{var wc=0,Vm=0;for(rl==16?(Vm=3+Xk(Et,Cs,3),Cs+=2,wc=Ka[Fa-1]):rl==17?(Vm=3+Xk(Et,Cs,7),Cs+=3):rl==18&&(Vm=11+Xk(Et,Cs,127),Cs+=7);Vm--;)Ka[Fa++]=wc}}var Z0=Ka.subarray(0,cr),Jh=Ka.subarray(cr);In=O8e(Z0),Vn=O8e(Jh),an=lZ(Z0,In),Ln=lZ(Jh,Vn)}else Qk(1);if(Cs>Dn){cn&&Qk(0);break}}pn&&jn(Qs+131072);for(var _l=(1<>4;if((Cs+=15&wc)>Dn){cn&&Qk(0);break}if(wc||Qk(2),Hm<256)Jt[Qs++]=Hm;else{if(Hm==256){fh=Cs,an=null;break}var mo=Hm-254;Hm>264&&(mo=Xk(Et,Cs,(1<<(xf=Oft[Fa=Hm-257]))-1)+Uft[Fa],Cs+=xf);var fp=Ln[z8e(Et,Cs)&Wd],Lp=fp>>4;if(fp||Qk(3),Cs+=15&fp,Jh=Xps[Lp],Lp>3){var xf=zft[Lp];Jh+=z8e(Et,Cs)&(1<Dn){cn&&Qk(0);break}pn&&jn(Qs+131072);var Vx=Qs+mo;if(QsSy.length)&&(Cy=Sy.length),new gj(Sy.subarray(0,Cy))}(Jt,0,Qs):Jt.subarray(0,Qs)}(st.subarray(yt,-8),{i:2},new gj(((mt=st)[(lt=mt.length)-4]|mt[lt-3]<<8|mt[lt-2]<<16|mt[lt-1]<<24)>>>0),ot)));var st,ot,mt,lt,yt;const Nt=rgs[Ye];if(!Nt)throw new Error(`Unhandled codec: ${Ye}`);const as=new globalThis.DecompressionStream(Nt);return new Response(new Blob([Ue]).stream().pipeThrough(as)).arrayBuffer().then(Et=>new Uint8Array(Et))}(be,xe).then(Ue=>(function(Ye,st){let ot;for(;ot=Ye.nextField();)if(ot===2)Vps(Ye,Ye.readVarint()+Ye.pos,st);else if(ot===3)throw new Error("Not implemented")}(new B8e(Ue),Te),new igs[H](Te.buffer))),De.then(Ue=>{for(let Ye=fe.length-1;Ye>=0;Ye--)switch(fe[Ye]){case"delta_filter":Hps(Ue,Z);break;case"zigzag_filter":Gps(Ue);break;case"bitshuffle_filter":Wps(Ue,H);break;default:throw new rN(`Unhandled filter "${fe[Ye]}"`)}return{layerName:M,blockIndex:se,data:Ue}}).catch(Ue=>{throw Ue})}))},oa(Wft,"MRTDecodingBatch",{omit:["_onCancel","_onComplete"]}),oa(Yle,"MapboxRasterTile"),oa(Gft,"MapboxRasterLayer",{omit:["_blocksInProgress"]});const Kft=[Int8Array,Uint8Array,Uint8ClampedArray,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array],Ip=new Uint32Array(96);class $8e{static from(p){if(!p||p.byteLength===void 0||p.buffer)throw new Error("Data must be an instance of ArrayBuffer or SharedArrayBuffer.");const[_,A]=new Uint8Array(p,0,2);if(_!==219)throw new Error("Data does not appear to be in a KDBush format.");const M=A>>4;if(M!==1)throw new Error(`Got v${M} data when expected v1.`);const F=Kft[15&A];if(!F)throw new Error("Unrecognized array type.");const[z]=new Uint16Array(p,2,1),[H]=new Uint32Array(p,4,1);return new $8e(H,z,F,void 0,p)}constructor(p,_=64,A=Float64Array,M=ArrayBuffer,F){if(isNaN(p)||p<0)throw new Error(`Unexpected numItems value: ${p}.`);this.numItems=+p,this.nodeSize=Math.min(Math.max(+_,2),65535),this.ArrayType=A,this.IndexArrayType=p<65536?Uint16Array:Uint32Array;const z=Kft.indexOf(this.ArrayType),H=2*p*this.ArrayType.BYTES_PER_ELEMENT,Z=p*this.IndexArrayType.BYTES_PER_ELEMENT,se=(8-Z%8)%8;if(z<0)throw new Error(`Unexpected typed array class: ${A}.`);if(F)this.data=F,this.ids=new this.IndexArrayType(F,8,p),this.coords=new A(F,8+Z+se,2*p),this._pos=2*p,this._finished=!0;else{const fe=this.data=new M(8+H+Z+se);this.ids=new this.IndexArrayType(fe,8,p),this.coords=new A(fe,8+Z+se,2*p),this._pos=0,this._finished=!1,new Uint8Array(fe,0,2).set([219,16+z]),new Uint16Array(fe,2,1)[0]=_,new Uint32Array(fe,4,1)[0]=p}}add(p,_){const A=this._pos>>1;return this.ids[A]=A,this.coords[this._pos++]=p,this.coords[this._pos++]=_,A}finish(){const p=this._pos>>1;if(p!==this.numItems)throw new Error(`Added ${p} items when expected ${this.numItems}.`);return U8e(this.ids,this.coords,this.nodeSize,0,this.numItems-1,0),this._finished=!0,this}range(p,_,A,M){if(!this._finished)throw new Error("Data not yet indexed - call index.finish().");const{ids:F,coords:z,nodeSize:H}=this;Ip[0]=0,Ip[1]=F.length-1,Ip[2]=0;let Z=3;const se=[];for(;Z>0;){const fe=Ip[--Z],xe=Ip[--Z],be=Ip[--Z];if(xe-be<=H){for(let Ye=be;Ye<=xe;Ye++){const st=z[2*Ye],ot=z[2*Ye+1];st>=p&&st<=A&&ot>=_&&ot<=M&&se.push(F[Ye])}continue}const Te=be+xe>>1,De=z[2*Te],Ue=z[2*Te+1];De>=p&&De<=A&&Ue>=_&&Ue<=M&&se.push(F[Te]),(fe===0?p<=De:_<=Ue)&&(Ip[Z++]=be,Ip[Z++]=Te-1,Ip[Z++]=1-fe),(fe===0?A>=De:M>=Ue)&&(Ip[Z++]=Te+1,Ip[Z++]=xe,Ip[Z++]=1-fe)}return se}within(p,_,A){const M=[];return this.withinInto(p,_,A,M),M}withinInto(p,_,A,M){if(!this._finished)throw new Error("Data not yet indexed - call index.finish().");const{ids:F,coords:z,nodeSize:H}=this;Ip[0]=0,Ip[1]=F.length-1,Ip[2]=0;let Z=3,se=0;const fe=A*A;for(;Z>0;){const xe=Ip[--Z],be=Ip[--Z],Te=Ip[--Z];if(be-Te<=H){for(let st=Te;st<=be;st++)Zft(z[2*st],z[2*st+1],p,_)<=fe&&(M[se++]=F[st]);continue}const De=Te+be>>1,Ue=z[2*De],Ye=z[2*De+1];Zft(Ue,Ye,p,_)<=fe&&(M[se++]=F[De]),(xe===0?p-A<=Ue:_-A<=Ye)&&(Ip[Z++]=Te,Ip[Z++]=De-1,Ip[Z++]=1-xe),(xe===0?p+A>=Ue:_+A>=Ye)&&(Ip[Z++]=De+1,Ip[Z++]=be,Ip[Z++]=1-xe)}return se}}function U8e(N,p,_,A,M,F){if(M-A<=_)return;const z=A+M>>1;Yft(N,p,z,A,M,F),U8e(N,p,_,A,z-1,1-F),U8e(N,p,_,z+1,M,1-F)}function Yft(N,p,_,A,M,F){for(;M>A;){if(M-A>600){const se=M-A+1,fe=_-A+1,xe=Math.log(se),be=.5*Math.exp(2*xe/3),Te=.5*Math.sqrt(xe*be*(se-be)/se)*(fe-se/2<0?-1:1);Yft(N,p,_,Math.max(A,Math.floor(_-fe*be/se+Te)),Math.min(M,Math.floor(_+(se-fe)*be/se+Te)),F)}const z=p[2*_+F];let H=A,Z=M;for(dZ(N,p,A,_),p[2*M+F]>z&&dZ(N,p,A,M);Hz;)Z--}p[2*A+F]===z?dZ(N,p,A,Z):(Z++,dZ(N,p,Z,M)),Z<=_&&(A=Z+1),_<=Z&&(M=Z-1)}}function dZ(N,p,_,A){q8e(N,_,A),q8e(p,2*_,2*A),q8e(p,2*_+1,2*A+1)}function q8e(N,p,_){const A=N[p];N[p]=N[_],N[_]=A}function Zft(N,p,_,A){const M=N-_,F=p-A;return M*M+F*F}c.$=ky,c.A=H0,c.B=zx,c.C=Ci,c.D=$1,c.E=Jc,c.F=rp,c.G=Rk,c.H=sj,c.I=_d,c.J=V6,c.K=/^(.*)-transition$/,c.L=D8e,c.M=cp,c.N=qk,c.O=Lr,c.P=xs,c.Q=v,c.R=vr,c.S=H3,c.T=Qoe,c.U=/^(.*)-use-theme$/,c.V=function(N,p){const _=H3(p.zoom);if(_===0)return WC(N);const A=Foe(N),M=mOe(A),F=ex(A.getWest())*p.worldSize,z=ex(A.getEast())*p.worldSize,H=ap(A.getNorth())*p.worldSize,Z=ap(A.getSouth())*p.worldSize,se=[F,H,0],fe=[z,H,0],xe=[F,Z,0],be=[z,Z,0],Te=C([],p.globeMatrix);return Xe(se,se,Te),Xe(fe,fe,Te),Xe(xe,xe,Te),Xe(be,be,Te),M[0]=V3(M[0],xe,_),M[1]=V3(M[1],be,_),M[2]=V3(M[2],fe,_),M[3]=V3(M[3],se,_),uu.fromPoints(M)},c.W=fOe,c.X=E,c.Y=y,c.Z=Ny,c._=pj,c.a=async function(N,p){N.headers||(N.headers={}),N.headers.accept="image/webp,*/*";const _=await function(A){return new Promise((M,F)=>{if(A&&A.aborted)return void F(A.reason);const z=()=>{const se=$a.shift();se?se():Na--};if(Na{A&&A.removeEventListener("abort",Z),M(z)},Z=()=>{const se=$a.indexOf(H);se!==-1&&$a.splice(se,1),F(A.reason)};A&&A.addEventListener("abort",Z),$a.push(H)})}(p);try{const{data:A,headers:M}=await Qr(N,p);let F;try{F=await createImageBitmap(new Blob([new Uint8Array(A)],{type:"image/png"}))}catch(z){throw new Error(`Could not load image because of ${z.message}. Please make sure to use a supported image type such as PNG or JPEG. Note that SVGs are not supported.`,{cause:z})}return p&&p.throwIfAborted(),{data:F,headers:M}}finally{_()}},c.a$=Lt,c.a0=Hmt,c.a1=jh,c.a2=hp,c.a3=co,c.a4=zf,c.a5=qm,c.a6=Fr,c.a7=ex,c.a8=ap,c.a9=function(N,p,_){if(p.projection.name===_.projection.name)return N.projMatrix;const A=_.clone();return A.setProjection(p.projection),NOe(A,p.getProjection(),N)},c.aA=q3,c.aB=T,c.aC=Vdt,c.aD=Cle,c.aE=_ht,c.aF=l$,c.aG=_ft,c.aH=vh,c.aI=(N,p,_,A,M,F,z,H,Z,se,fe,xe,be,Te,De,Ue,Ye,st,ot=!1)=>{const mt=xft(N,p,_,A,M,F,z,H,se,fe,xe,be,Te,De,Ue,Ye,1,[0,0,0],[0,0,1],ot),lt={u_height_factor:-Math.pow(2,H.overscaledZ)/Z.tileSize/8};return Object.assign(mt,pft(p,Z,st),lt)},c.aJ=xft,c.aK=Y3,c.aL=450,c.aM=7,c.aN=(N,p,_,A,M,F)=>({u_matrix:N,u_edge_radius:p,u_width_scale:_,u_vertical_scale:A,u_height_type:qle[M],u_base_type:qle[F]}),c.aO=P,c.aP=C,c.aQ=S,c.aR=vft,c.aS=4,c.aT=2,c.aU=YFe,c.aV=ZFe,c.aW=Bc,c.aX=class{static calculate(N,p,_){const A=new Set,M=new Map,F=new Set,z=new Set;for(const Z of Object.values(N))for(const[se,fe]of Object.entries(Z.floors)){F.add(se),fe.isDefault&&z.add(se),fe.conflicts&&M.set(se,fe.conflicts);const xe=se===p,be=fe.connections&&p&&fe.connections.has(p);(xe||be)&&A.add(se)}const H=Z=>{const se=M.get(Z)||new Set;for(const fe of A)if((M.get(fe)||new Set).has(Z)||se.has(fe))return!0;return!1};if(_)for(const Z of _)F.has(Z)&&(H(Z)||A.add(Z));for(const Z of z)A.has(Z)||H(Z)||A.add(Z);return A}},c.aY=Um,c.aZ=X_,c.a_=class extends jy{constructor(N){super(N),this.current=new Float32Array(9)}set(N,p,_){if(!this.fetchUniformLocation(N,p))return;const A=this.current;for(let M=0;M<9;M++)if(_[M]!==A[M]){A.set(_),this.gl.uniformMatrix3fv(this.location,!1,A);break}}},c.aa=ne,c.ab=Gr,c.ac=Dhs,c.ad=Ri,c.ae=Vr,c.af=xl,c.ag=Ku,c.ah=xr,c.ai=class{constructor(N){this.specification=N}possiblyEvaluate(N,p){return Ih(N.expression.evaluate(p))}interpolate(N,p,_){return{x:ya(N.x,p.x,_),y:ya(N.y,p.y,_),z:ya(N.z,p.z,_),azimuthal:ya(N.azimuthal,p.azimuthal,_),polar:ya(N.polar,p.polar,_)}}},c.aj=Kn,c.ak=cg,c.al=Sl,c.am=ya,c.an=xc,c.ao=65,c.ap=45,c.aq=function(N,p,_){const A=Q.fromLngLat(p),M=_.elevation?_.elevation.getAtPointOrZero(A):0;return eut(N,A.x,A.y,M,_)},c.ar=function(N,p,_,A,M,F,z){const H=[[_,A,0],[M,A,0],[M,F,0],[_,F,0]];let Z=Number.MAX_VALUE,se=-Number.MAX_VALUE;for(const fe of H){const xe=ce(Xe([],fe,p));Z=Math.min(Z,xe),se=Math.max(se,xe)}return[Koe(N,Z,z.pitch),Koe(N,se,z.pitch)]},c.as=Wu,c.at=eut,c.au=OY,c.av=Xr,c.aw=function(){return nc++},c.ax=class{constructor(N,p,_){this.target=N,this.parent=p,this.mapId=_,this.pendingResponses=new Map,Bc(["receive"],this),this.target.addEventListener("message",this.receive,!1),this.scheduler=new Rps}send(N,p,_){const{signal:A,targetMapId:M,metadata:F}=_||{},z=Math.round(1e18*Math.random()).toString(36).substring(0,10),H=new Set;return A&&A.aborted?Promise.reject(A.reason):(this.target.postMessage({id:z,type:N,targetMapId:M,sourceMapId:this.mapId,data:Gv(p,H)},[...H]),new Promise((Z,se)=>{const fe={resolve:Z,reject:se,metadata:F||Tft};if(A){const xe=()=>{this.pendingResponses.delete(z),se(A.reason)};A.addEventListener("abort",xe,{once:!0}),fe.detach=()=>A.removeEventListener("abort",xe)}this.pendingResponses.set(z,fe)}))}notify(N,p,_){const{targetMapId:A}=_||{},M=new Set;this.target.postMessage({type:N,targetMapId:A,sourceMapId:this.mapId,data:Gv(p,M)},[...M])}sendCancelable(N,p,_,A){const M=new AbortController;return this.send(N,p,{..._,signal:M.signal}).then(F=>A(null,F)).catch(F=>{F.name!=="AbortError"&&A(F)}),M}getWorkerSourceActor(N){return{scheduler:this.scheduler,send:(p,_,A)=>this.send(p,_,{...A,targetMapId:N}),notify:(p,_)=>{this.notify(p,_,{targetMapId:N})},sendCancelable:(p,_,A,M)=>this.sendCancelable(p,_,{...A,targetMapId:N},M)}}receive(N){const p=N.data;if(!p)return;const _=p.id;if(!p.targetMapId||this.mapId===p.targetMapId)if(Xc(self)){const A=this.pendingResponses.get(_);this.scheduler.add(()=>{this.processTask(_,p)},A&&A.metadata||Tft)}else this.processTask(_,p)}async processTask(N,p){if(p.type===""){const M=this.pendingResponses.get(N);if(this.pendingResponses.delete(N),M){M.detach&&M.detach();try{p.error?M.reject(qx(p.error)):M.resolve(qx(p.data))}catch(F){M.reject(F)}}return}const _=new Set,A=qx(p.data);try{let M;if(this.parent[p.type])M=await this.parent[p.type](p.sourceMapId,A);else{if(!this.parent.getWorkerSource)throw new Error(`Could not find function ${p.type}`);{const F=p.type.split("."),{source:z,scope:H}=A;M=await this.parent.getWorkerSource(p.sourceMapId,{type:F[0],source:z,scope:H})[F[1]](A)}}if(!N)return;this.target.postMessage({id:N,type:"",sourceMapId:this.mapId,error:null,data:Gv(M,_)},[..._])}catch(M){this.target.postMessage({id:N,type:"",sourceMapId:this.mapId,error:Gv(M),data:null},[])}}remove(){for(const N of this.pendingResponses.values())N.detach&&N.detach(),N.reject(new DOMException("Actor removed","AbortError"));this.pendingResponses.clear(),this.scheduler.remove(),this.target.removeEventListener("message",this.receive,!1)}},c.ay=class{constructor(N){this.specification=N}possiblyEvaluate(N,p){return function([_,A]){const M=Ih([1,_,A]);return{x:M.x,y:M.y,z:M.z}}(N.expression.evaluate(p))}interpolate(N,p,_){return{x:ya(N.x,p.x,_),y:ya(N.y,p.y,_),z:ya(N.z,p.z,_)}}},c.az=dR,c.b=s0,c.b$=ih,c.b0=Hl,c.b1=ta,c.b2=6,c.b3=Foe,c.b4=function(N){const p=80.051129;N=ta(N,-80.051129,p)/p*90;const _=Math.pow(Math.abs(Math.sin(Xr(N))),3);return Math.round(_*(NY.length-1))},c.b5=Boe,c.b6=WC,c.b7=function(N){const p=N.pixelsPerMeter,_=p/eu(1,N.center.lat),A=w(new Float64Array(16));return I(A,A,[N.point.x,N.point.y,0]),P(A,A,[_,_,p]),Float32Array.from(A)},c.b8=function(N,p,_,A){const M=p.getNorth(),F=p.getSouth(),z=p.getWest(),H=p.getEast(),Z=1<0){const De=180/A;g(Te,Te,[De/se+1,0,0,0,De/fe+1,0,-.5*De/xe,.5*De/be,1])}return Te[2]=Z,Te[5]=N.x,Te[8]=N.y,Te},c.b9=Zg,c.bA=rOe,c.bB=WFe,c.bC=ht,c.bD=Hs,c.bE=jd,c.bF=lOe,c.bG=eM,c.bH=MY,c.bI=Xe,c.bJ=V3,c.bK=Fs,c.bL=Hhs,c.bM=W,c.bN=I,c.bO=function(){Ur.isLoading()||Ur.isLoaded()||wy()!=="deferred"||W_()},c.bP=Je,c.bQ=mg,c.bR=function(N,p){const _=[];for(const A in N)A in p||_.push(A);return _},c.bS=Eft,c.bT=Q,c.bU=Co,c.bV="hd_road_coverage",c.bW=lM,c.bX=$oe,c.bY=J6,c.bZ=ie,c.b_=cm,c.ba=256,c.bb=cft,c.bc=fd,c.bd=Ko,c.be=St,c.bf=vt,c.bg=Ss,c.bh=X,c.bi=_e,c.bj=lg,c.bk=nM,c.bl=qc,c.bm=bu,c.bn=Eoe,c.bo=o$,c.bp=vo,c.bq=xOe,c.br=Ox,c.bs=Hd,c.bt=nn,c.bu=rc,c.bv=rle,c.bw=gY,c.bx=_t,c.by=cR,c.bz=_s,c.c=W0,c.c$=Yoe,c.c0=function(N,p,_){const A=H3(_.zoom),M=N.style.map._antialias,F=N.terrain&&N.terrain.exaggeration()>0;return A===0&&!M&&!F},c.c1=function(N,p,_){const A=w(new Float64Array(16)),M=(p/(1<{A(F,z)},p):A(F,z),()=>{}}return M.callbacks.push(A),M.cancel||(M.cancel=_((F,z)=>{M.result=[F,z];for(const H of M.callbacks)this.scheduler?this.scheduler.add(()=>{H(F,z)},p):H(F,z);setTimeout(()=>delete this.entries[N],3e3)})),()=>{M.result||(M.callbacks=M.callbacks.filter(F=>F!==A),M.callbacks.length||(M.cancel(),delete this.entries[N]))}}},c.cD=function(N){if("provider"in N&&!N.provider)return null;let p=N.provider;if(!p&&"url"in N&&N.url&&(p=function(M){try{const F=new URL(M).pathname.split("/").pop()||"",z=F.lastIndexOf(".");return z>=0?F.slice(z+1):""}catch{return""}}(N.url)),!p)return null;const _=gt.TILE_PROVIDER_URLS[p];if(!_)return null;let A;try{A=new URL(_,gt.API_URL).href}catch{return new Error(`TileProvider "${p}" has an invalid URL: "${_}"`)}return{name:p,url:A}},c.cE=Nft,c.cF=Wle,c.cG=or,c.cH=function(N,p,_){const A=JSON.stringify(N.request);return N.data&&(this.deduped.entries[A]={result:[null,N.data]}),this.deduped.request(A,{type:"parseTile",renderSourceType:N.renderSourceType,zoom:N.tileZoom},M=>{const F=new AbortController;return Qr(N.request,F.signal).then(({data:z,headers:H})=>{M(null,{rawData:z,vectorTile:_?void 0:new KFe(new Yoe(z)),headers:H})}).catch(z=>{F.signal.aborted||(Je(z)?M(null,null):M(z))}),()=>{F.abort(),M(null,null)}},p)},c.cI=Xa,c.cJ=function(N){bn++,bn>Ms&&(N.getActor().notify("enforceCacheSizeLimit",ws),bn=0)},c.cK=Mu,c.cL=async function(N,p,_){const A=N.url&&!N.tiles?await p.transformRequest(N.url,vr.Source,_):void 0;return{request:A,options:A?{...N,url:A.url}:N}},c.cM=function(N,p,_){return p?jft(N,p,_):N.tiles&&N.tiles.length>0?{tiles:N.tiles}:new Error('TileJSON is missing required "tiles" property')},c.cN=async function(N,p){const _=Mft.get(N);if(_)return _;const A=F8e.get(N);if(A!==void 0)return A;const M=self.__mapboxImport(p).catch(F=>{throw new Error(`TileProvider "${N}" failed to load: ${F instanceof Error?F.message:String(F)}`)}).then(F=>{const z=F.default;if(typeof z!="function")throw new Error(`TileProvider "${N}" module must default-export a class`);if(typeof z.prototype.loadTile!="function")throw new Error(`TileProvider "${N}" class must have a loadTile method`);return Mft.set(N,z),z}).finally(()=>{F8e.delete(N)});return F8e.set(N,M),M},c.cO=class{constructor(N,p){this.context=N,this.texture=p}bind(N,p){const{context:_}=this,{gl:A}=_;A.bindTexture(A.TEXTURE_2D,this.texture),N!==this.minFilter&&(A.texParameteri(A.TEXTURE_2D,A.TEXTURE_MAG_FILTER,N),A.texParameteri(A.TEXTURE_2D,A.TEXTURE_MIN_FILTER,N),this.minFilter=N),p!==this.wrapS&&(A.texParameteri(A.TEXTURE_2D,A.TEXTURE_WRAP_S,p),A.texParameteri(A.TEXTURE_2D,A.TEXTURE_WRAP_T,p),this.wrapS=p)}},c.cP=L,c.cQ=function(N,p,_,A){for(;p<_;){const M=p+_>>1;N[M]<=A?p=M+1:_=M}return p},c.cR=function(N,p,_,A){for(;p<_;){const M=p+_>>1;N[M]{p.onloadstart=()=>_(),p.onerror=()=>A(new Error(`Could not load video: ${N.join(", ")}`))}),p},c.cX=pmt,c.cY=Nmt,c.cZ=Ll,c.c_=Yle,c.ca=ke,c.cb=pft,c.cc=zdt,c.cd=tZ,c.ce=f8e,c.cf=qi,c.cg=dm,c.ch=function(N,p){const _=[0,0,0];return Xe(_,_,Boe(WC(p.canonical))),Xe(_,_,N),_},c.ci=Kv,c.cj=function(N,p,_,A,M,F){const{width:z,height:H}=A.imageManager.getPixelSize(p),Z=Math.pow(2,F.tileID.overscaledZ),se=F.tileSize*Math.pow(2,A.transform.tileZoom)/Z,fe=se*(F.tileID.canonical.x+F.tileID.wrap*Z),xe=se*F.tileID.canonical.y;return{u_image:0,u_pattern_tl:_.tl,u_pattern_br:_.br,u_texsize:[z,H],u_pattern_size:_.displaySize,u_pattern_units_to_pixels:M?[A.transform.width,-1*A.transform.height]:[1/tZ(F,1,A.transform.tileZoom),1/tZ(F,1,A.transform.tileZoom)],u_pixel_coord_upper:[fe>>16,xe>>16],u_pixel_coord_lower:[65535&fe,65535&xe]}},c.ck=N=>({u_matrix:new zf(N),u_texsize:new hp(N),u_pixels_to_tile_units:new eR(N),u_device_pixel_ratio:new co(N),u_width_scale:new co(N),u_floor_width_scale:new co(N),u_image:new Um(N),u_units_to_pixels:new hp(N),u_tile_units_to_pixels:new co(N),u_alpha_discard_threshold:new co(N),u_trim_offset:new hp(N),u_trim_fade_range:new hp(N),u_trim_gradient_mix_range:new hp(N),u_trim_color:new X_(N),u_zbias_factor:new co(N),u_tile_to_meter:new co(N),u_ground_shadow_factor:new qm(N),u_pattern_transition:new co(N),u_opacity_multiplier:new co(N)}),c.cl=N=>({u_matrix:new zf(N),u_pixels_to_tile_units:new eR(N),u_device_pixel_ratio:new co(N),u_width_scale:new co(N),u_floor_width_scale:new co(N),u_units_to_pixels:new hp(N),u_dash_image:new Um(N),u_gradient_image:new Um(N),u_border_gradient_image:new Um(N),u_image_height:new co(N),u_texsize:new hp(N),u_tile_units_to_pixels:new co(N),u_alpha_discard_threshold:new co(N),u_trim_offset:new hp(N),u_trim_fade_range:new hp(N),u_trim_gradient_mix_range:new hp(N),u_trim_color:new X_(N),u_zbias_factor:new co(N),u_road_view_depth_bias:new co(N),u_road_clip_to_view:new X_(N),u_tile_to_meter:new co(N),u_ground_shadow_factor:new qm(N),u_opacity_multiplier:new co(N)}),c.cm=N=>({u_color:new J6(N),u_matrix:new zf(N),u_overlay:new Um(N),u_overlay_scale:new co(N)}),c.cn=N=>({u_camera_to_center_distance:new co(N),u_extrude_scale:new eR(N),u_device_pixel_ratio:new co(N),u_matrix:new zf(N),u_inv_rot_matrix:new zf(N),u_merc_center:new hp(N),u_tile_id:new qm(N),u_zoom_transition:new co(N),u_up_dir:new qm(N),u_emissive_strength:new co(N)}),c.co=N=>({u_matrix:new zf(N),u_lightpos:new qm(N),u_lightintensity:new co(N),u_lightcolor:new qm(N),u_vertical_gradient:new co(N),u_height_factor:new co(N),u_edge_radius:new co(N),u_width_scale:new co(N),u_ao:new hp(N),u_height_type:new Um(N),u_base_type:new Um(N),u_tile_id:new qm(N),u_zoom_transition:new co(N),u_inv_rot_matrix:new zf(N),u_merc_center:new hp(N),u_up_dir:new qm(N),u_height_lift:new co(N),u_image:new Um(N),u_texsize:new hp(N),u_pixel_coord_upper:new hp(N),u_pixel_coord_lower:new hp(N),u_tile_units_to_pixels:new co(N),u_opacity:new co(N),u_pattern_transition:new co(N)}),c.cp=N=>({u_matrix:new zf(N),u_lightpos:new qm(N),u_lightintensity:new co(N),u_lightcolor:new qm(N),u_vertical_gradient:new co(N),u_opacity:new co(N),u_edge_radius:new co(N),u_width_scale:new co(N),u_ao:new hp(N),u_height_type:new Um(N),u_base_type:new Um(N),u_tile_id:new qm(N),u_zoom_transition:new co(N),u_inv_rot_matrix:new zf(N),u_merc_center:new hp(N),u_up_dir:new qm(N),u_height_lift:new co(N),u_flood_light_color:new qm(N),u_vertical_scale:new co(N),u_flood_light_intensity:new co(N),u_ground_shadow_factor:new qm(N),u_front_cutoff_params:new qm(N)}),c.cq=function(N,p,_=0,A=!0){const M=new xs(_,_),F=N.sub(M),z=p.add(M),H=[F,new xs(z.x,F.y),z,new xs(F.x,z.y)];return A&&H.push(F.clone()),H},c.cr=function(N,p){const _=[];for(let A=0;A{this.cache.delete(p),this.clearExpiredTextures()})}beginFrame(){this.currentFrameAtlases.clear()}calculateTextureMemory(N){return N.image?Math.ceil(N.image.width*N.image.height*4*(N.patternPositions.size>0?1.33:1)):0}evictTexture(N){const p=this.textures.get(N);if(p){const _=this.calculateTextureMemory(N);p.destroy(),this.textures.delete(N),this.textureAccessTimes.delete(N),this.textureMemoryUsed-=_,N.uploaded=!1}}evictTexturesIfNeeded(N){for(;this.textureMemoryUsed+N>this.maxTextureMemory&&this.textures.size>0;){let p=null,_=1/0;for(const[A]of this.textures.entries()){if(this.currentFrameAtlases.has(A))continue;const M=this.textureAccessTimes.get(A)||0;M<_&&(_=M,p=A)}if(!p)break;this.evictTexture(p)}}findCachedAtlas(N){const p=this.cache.get(N.hash);if(p){const _=p.deref();if(_&&_.contentDescriptor&&this.isMipmapCompatible(N,_.contentDescriptor))return _}for(const[,_]of this.cache.entries()){const A=_.deref();if(A&&A.contentDescriptor){const M=N.subsetOf(A.contentDescriptor),F=this.isMipmapCompatible(N,A.contentDescriptor);if(M&&F)return A}}}getTextureForAtlas(N,p,_){this.textureAccessTimes.set(N,performance.now()),this.currentFrameAtlases.add(N);let A=this.textures.get(N);if(A)return A;if(N.image){const M=this.calculateTextureMemory(N);return this.evictTexturesIfNeeded(M),A=new Qoe(p,N.image,_,{useMipmap:!!N.patternPositions.size}),this.textures.set(N,A),this.textureMemoryUsed+=M,A}return null}clearExpiredTextures(){for(const[N]of this.textures.entries())if(!this.isAtlasCached(N)){const p=this.textures.get(N);if(p){const _=this.calculateTextureMemory(N);p.destroy(),this.textureMemoryUsed-=_}this.textures.delete(N),this.textureAccessTimes.delete(N)}}isAtlasCached(N){if(!N.contentDescriptor)return!1;const p=this.cache.get(N.contentDescriptor.hash);return!!p&&p.deref()===N}getOrCache(N){if(!("image"in N)){const M=this.cache.get(N.sourceAtlasHash);if(M){const F=M.deref();if(F)return F}return Yo("ImageAtlasReference points to GC'd atlas - atlas may have been evicted"),null}if(!N.contentDescriptor)return N;const p=N.contentDescriptor,_=p.hash,A=this.cache.get(_);if(A){const M=A.deref();if(M&&M.contentDescriptor&&this.isMipmapCompatible(p,M.contentDescriptor))return M}return this.cache.set(_,new WeakRef(N)),this.finalizationRegistry.register(N,_,N),N}isMipmapCompatible(N,p){return!N.requiresMipMaps||p.requiresMipMaps}destroyTextures(){for(const N of this.textures.values())N&&N.destroy();this.textures.clear(),this.textureAccessTimes.clear(),this.textureMemoryUsed=0}clear(){for(const N of this.textures.values())N&&N.destroy();this.cache.clear(),this.textures.clear(),this.textureAccessTimes.clear(),this.textureMemoryUsed=0}},c.d$=N=>({u_cutoff_params:new X_(N)}),c.d0=Qr,c.d1=["type","source","source-layer","minzoom","maxzoom","filter","layout"],c.d2=Hv,c.d3=On,c.d4=hr,c.d5=gn,c.d6=Fn,c.d7=fl,c.d8=ts,c.d9=.55,c.dA=Ht,c.dB=Joe,c.dC=POe,c.dD=Zi,c.dE=zt,c.dF=hd,c.dG=Ul,c.dH=function(N){const p=N.indexOf(JT);return p>=0?N.slice(0,p):N},c.dI=function(N){return N.includes(JT)},c.dJ=function(N){const p=N.lastIndexOf(JT);return p>=0?N.slice(p+1):""},c.dK=function(N,p={}){const _=p.type&&!p.array&&Array.isArray(N)?{type:p.type,"property-type":"data-constant"}:void 0;return W0(N===null||typeof N!="object"||Array.isArray(N)?N:["literal",N],_)},c.dL=function(N){const p=[],_=N.id;return _===void 0&&p.push({message:`layers.${_}: missing required property "id"`}),N.render===void 0&&p.push({message:`layers.${_}: missing required method "render"`}),N.renderingMode&&N.renderingMode!=="2d"&&N.renderingMode!=="3d"&&p.push({message:`layers.${_}: property "renderingMode" must be either "2d" or "3d"`}),p},c.dM=function(N,p,_,A){return N.type==="custom"?new Jfs(N,p):new Ips[N.type](N,p,_,A)},c.dN=yc,c.dO=yY,c.dP=class extends cR{constructor(N,p){super(N._vectorTileFeature,N._z,N._x,N._y,N.id),N.state&&(this.state={...N.state}),this.target=p.target,this.namespace=p.namespace,p.properties&&(this.properties=p.properties),this.target&&("featuresetId"in this.target&&!this.target.importId||"layerId"in this.target)&&(this.source=N.source,this.sourceLayer=N.sourceLayer,this.layer=N.layer)}toJSON(){const N=super.toJSON();return N.target=this.target,N.namespace=this.namespace,N}},c.dQ=mh,c.dR=bft,c.dS=sut,c.dT=function(){return{API_URL:gt.API_URL,DRACO_URL:gt.DRACO_URL,MESHOPT_URL:gt.MESHOPT_URL,MESHOPT_SIMD_URL:gt.MESHOPT_SIMD_URL,BUILDING_GEN_URL:gt.BUILDING_GEN_URL}},c.dU=function(N,p){return[Math.pow(N[0],2.2)*p,Math.pow(N[1],2.2)*p,Math.pow(N[2],2.2)*p]},c.dV=Fe,c.dW=ue,c.dX=ko,c.dY=ze,c.dZ=_ps,c.d_=wps,c.da=fM,c.db=zmt,c.dc=sOe,c.dd=Jdt,c.de=wOe,c.df=w,c.dg=H9,c.dh=.9,c.di=tut,c.dj=function(N,p,_,A,M,F,z){const H=k8e(N,p,_,A,M,F,z);return F.name==="globe"&&_||(H[2]=H[6]=H[10]=H[14]=0),H},c.dk=function(N,p,_,A,M,F,z){if(_){if(F.name==="globe"){const H=k8e(N,p,_,A,M,F,z);return C(H,H),E(H,N,H),H}{const H=v(N),[Z,se,fe,xe]=z,[be,Te,De,Ue,Ye,st,ot,mt]=H;return H[0]=Z*be+se*Ye,H[1]=Z*Te+se*st,H[2]=Z*De+se*ot,H[3]=Z*Ue+se*mt,H[4]=fe*be+xe*Ye,H[5]=fe*Te+xe*st,H[6]=fe*De+xe*ot,H[7]=fe*Ue+xe*mt,A||O(H,H,-M.angle),H}}return M.glCoordMatrix},c.dl=U3,c.dm=yOe,c.dn=FY,c.dp=_Oe,c.dq=Woe,c.dr=qt,c.ds=Ioe,c.dt=$3,c.du=Sdt,c.dv=function(N,[p,_]){let A=0,M=0;if(_===Uhs){p<0&&(p=0);const F=p/qhs;switch(N){case"top-right":case"top-left":M=F-7;break;case"bottom-right":case"bottom-left":M=7-F;break;case"bottom":M=7-p;break;case"top":M=p-7}switch(N){case"top-right":case"bottom-right":A=-F;break;case"top-left":case"bottom-left":A=F;break;case"left":A=p;break;case"right":A=-p}}else{switch(p=Math.abs(p),_=Math.abs(_),N){case"top-right":case"top-left":case"top":M=_-7;break;case"bottom-right":case"bottom-left":case"bottom":M=7-_}switch(N){case"top-right":case"bottom-right":case"right":A=-p;break;case"top-left":case"bottom-left":case"left":A=p}}return[A,M]},c.dw=function(N){switch(N){case"right":case"top-right":case"bottom-right":return"right";case"left":case"top-left":case"bottom-left":return"left"}return"center"},c.dx=$8e,c.dy=kOe,c.dz=function(N){return N({pluginStatus:Pi,pluginURL:gl}),mh.on("pluginStateChange",N),N},c.e=oh,c.e$=Ed,c.e0=N=>({u_light_matrix_0:new zf(N),u_light_matrix_1:new zf(N),u_fade_range:new hp(N),u_shadow_normal_offset:new qm(N),u_shadow_intensity:new co(N),u_shadow_texel_size:new co(N),u_shadow_map_resolution:new co(N),u_shadow_direction:new qm(N),u_shadow_bias:new qm(N),u_shadowmap_0:new Um(N),u_shadowmap_1:new Um(N)}),c.e1=function(N,p,_){return p.name===_.projection.name?N.projMatrix:NOe(_,p,N)},c.e2=k8e,c.e3=rZ,c.e4=Omt,c.e5=rR,c.e6=function(N,p,_,A,M,F,z,H,Z,se,fe=1){const xe=_.transform,be=A?N.textSizeData:N.iconSizeData,Te=U3(be,_.transform.zoom,fe),De=xe.projection.name==="globe",Ue=(()=>{if(!De)return null;const Et=H3(xe.zoom);return Et===0?null:{t:Et,invMatrix:xe.projection.createInversionMatrix(xe,se.canonical),mercCenter:[ex(xe.center.lng),ap(xe.center.lat)]}})(),Ye=[256/_.width*2+1,256/_.height*2+1],st=A?N.text.dynamicLayoutVertexArray:N.icon.dynamicLayoutVertexArray;st.clear();let ot=null;De&&(ot=A?N.text.globeExtVertexArray:N.icon.globeExtVertexArray);const mt=N.lineVertexArray,lt=A?N.text.placedSymbolArray:N.icon.placedSymbolArray,yt=_.transform.width/_.transform.height;let Nt,as=!1;for(let Et=0;Et{const z=N.transform,H=z.projection.name==="globe";let Z;if(F.paint.get("circle-pitch-alignment")==="map")if(H){const fe=zdt(z.zoom,p.canonical)*z._pixelsPerMercatorPixel;Z=Float32Array.from([fe,0,0,fe])}else Z=z.calculatePixelsToTileUnitsMatrix(_);else Z=new Float32Array([z.pixelsToGLUnits[0],0,0,z.pixelsToGLUnits[1]]);const se={u_camera_to_center_distance:N.transform.getCameraToCenterDistance(z.projection),u_matrix:N.translatePosMatrix(p.projMatrix,_,F.paint.get("circle-translate"),F.paint.get("circle-translate-anchor")),u_device_pixel_ratio:oh.devicePixelRatio,u_extrude_scale:Z,u_inv_rot_matrix:Hfs,u_merc_center:[0,0],u_tile_id:[0,0,0],u_zoom_transition:0,u_up_dir:[0,0,0],u_emissive_strength:F.paint.get("circle-emissive-strength")};if(H){se.u_inv_rot_matrix=A,se.u_merc_center=M,se.u_tile_id=[p.canonical.x,p.canonical.y,1<this._skuTokenExpiresAt}async transformRequest(N,p,_){if(!this._transformRequestFn)return{url:N};const A=_?{signal:_}:{};return await this._transformRequestFn(N,p,A)||{url:N}}normalizeStyleURL(N,p){if(!or(N))return N;const _=Ut(N);return _.params.push(`sdk=js-${d}`),_.path=`/styles/v1${_.path}`,this._makeAPIURL(_,this._customAccessToken||p)}normalizeGlyphsURL(N,p){if(!or(N))return N;const _=Ut(N);return _.path=`/fonts/v1${_.path}`,this._makeAPIURL(_,this._customAccessToken||p)}normalizeModelURL(N,p){if(!or(N))return N;const _=Ut(N);return _.path=`/models/v1${_.path}`,this._makeAPIURL(_,this._customAccessToken||p)}normalizeSourceURL(N,p,_,A){if(!or(N))return N;const M=Ut(N);return M.path=`/v4/${M.authority}.json`,M.params.push("secure"),_&&M.params.push(`language=${_}`),A&&M.params.push(`worldview=${A}`),this._makeAPIURL(M,this._customAccessToken||p)}normalizeIconsetURL(N,p){const _=Ut(N);return or(N)?(_.path=`/styles/v1${_.path}/iconset.pbf`,this._makeAPIURL(_,this._customAccessToken||p)):Cn(_)}normalizeSpriteURL(N,p,_,A){const M=Ut(N);return or(N)?(M.path=`/styles/v1${M.path}/sprite${p}${_}`,this._makeAPIURL(M,this._customAccessToken||A)):(M.path+=`${p}${_}`,Cn(M))}normalizeTileURL(N,p,_){if(this._isSkuTokenExpired()&&this._createSkuToken(),N&&!or(N))return N;const A=Ut(N);A.path=A.path.replace(Lo,(p||_&&A.authority!=="raster"&&_===512?"@2x":"")+".webp"),A.authority==="raster"?A.path=`/${gt.RASTER_URL_PREFIX}${A.path}`:A.authority==="rasterarrays"?A.path=`/${gt.RASTERARRAYS_URL_PREFIX}${A.path}`:A.authority==="3dtiles"?A.path=`/${gt.TILES3D_URL_PREFIX}${A.path}`:(A.path=A.path.replace(ql,"/"),A.path=`/${gt.TILE_URL_VERSION}${A.path}`);const M=this._customAccessToken||function(F){for(const z of F){const H=z.match(Il);if(H)return H[1]}return null}(A.params)||gt.ACCESS_TOKEN;return gt.REQUIRE_ACCESS_TOKEN&&M&&this._skuToken&&A.params.push(`sku=${this._skuToken}`),this._makeAPIURL(A,M)}canonicalizeTileURL(N,p){const _=Ut(N);if(!nl.test(_.path)||!po.test(_.path))return N;let A="mapbox://";_.path.startsWith("/raster/v1/")?A+=`raster/${_.path.replace(`/${gt.RASTER_URL_PREFIX}/`,"")}`:_.path.startsWith("/rasterarrays/v1/")?A+=`rasterarrays/${_.path.replace(`/${gt.RASTERARRAYS_URL_PREFIX}/`,"")}`:A+=`tiles/${_.path.replace(`/${gt.TILE_URL_VERSION}/`,"")}`;let M=_.params;return p&&(M=M.filter(F=>!F.match(Il))),M.length&&(A+=`?${M.join("&")}`),A}canonicalizeTileset(N,p){const _=!!p&&or(p),A=[];for(const M of N.tiles||[])Pn(M)?A.push(this.canonicalizeTileURL(M,_)):A.push(M);return A}_makeAPIURL(N,p){const _="See https://docs.mapbox.com/api/overview/#access-tokens-and-token-scopes",A=Ut(gt.API_URL);if(N.protocol=A.protocol,N.authority=A.authority,N.protocol==="http"){const M=N.params.indexOf("secure");M>=0&&N.params.splice(M,1)}if(A.path!=="/"&&(N.path=`${A.path}${N.path}`),!gt.REQUIRE_ACCESS_TOKEN)return Cn(N);if(p=p||gt.ACCESS_TOKEN,!this._silenceAuthErrors){if(!p)throw new Error(`An API access token is required to use Mapbox GL. ${_}`);if(p[0]==="s")throw new Error(`Use a public access token (pk.*) with Mapbox GL, not a secret access token (sk.*). ${_}`)}return N.params=N.params.filter(M=>!M.includes("access_token")),N.params.push(`access_token=${p||""}`),Cn(N)}},c.eX=ra,c.eY=function(N,p){p?qd.add(N):qd.delete(N)},c.eZ=od,c.e_=Gu,c.ea=smt,c.eb=(N,p,_,A,M,F,z,H,Z,se)=>{const fe=N.transform,xe=fe.pitch<15?ya(.07,.7,ta((14-fe.zoom)/5,0,1)):.07,be=_.paint.get("line-trim-color-use-theme").constantOr("default")==="none";return{u_matrix:tmt(N,p,_,A),u_texsize:p.imageAtlasTexture?p.imageAtlasTexture.size:[0,0],u_pixels_to_tile_units:fe.calculatePixelsToTileUnitsMatrix(p),u_device_pixel_ratio:M,u_width_scale:F,u_floor_width_scale:z,u_image:0,u_tile_units_to_pixels:emt(p,fe),u_units_to_pixels:[1/fe.pixelsToGLUnits[0],1/fe.pixelsToGLUnits[1]],u_alpha_discard_threshold:0,u_trim_offset:H,u_trim_fade_range:_.paint.get("line-trim-fade-range"),u_trim_gradient_mix_range:[1,1],u_trim_color:_.paint.get("line-trim-color").toPremultipliedRenderColor(be?null:_.lut).toArray01(),u_zbias_factor:xe,u_tile_to_meter:K(p.tileID.canonical,0),u_ground_shadow_factor:Z,u_pattern_transition:se,u_opacity_multiplier:1}},c.ec=(N,p,_,A,M,F,z,H,Z,se)=>{const fe=N.transform,xe=fe.calculatePixelsToTileUnitsMatrix(p),be=_.paint.get("line-trim-color-use-theme").constantOr("default")==="none",Te=fe.pitch<15?ya(.07,.7,ta((14-fe.zoom)/5,0,1)):.07;return{u_matrix:tmt(N,p,_,A),u_pixels_to_tile_units:xe,u_device_pixel_ratio:F,u_width_scale:z,u_floor_width_scale:H,u_units_to_pixels:[1/fe.pixelsToGLUnits[0],1/fe.pixelsToGLUnits[1]],u_dash_image:0,u_gradient_image:1,u_border_gradient_image:2,u_image_height:M,u_texsize:nmt(_)&&p.lineAtlasTexture?p.lineAtlasTexture.size:[0,0],u_tile_units_to_pixels:emt(p,N.transform),u_alpha_discard_threshold:0,u_trim_offset:Z,u_trim_fade_range:_.paint.get("line-trim-fade-range"),u_trim_gradient_mix_range:[1,1],u_trim_color:_.paint.get("line-trim-color").toPremultipliedRenderColor(be?null:_.lut).toArray01(),u_zbias_factor:Te,u_road_view_depth_bias:0,u_road_clip_to_view:[0,0,0,0],u_tile_to_meter:K(p.tileID.canonical,0),u_ground_shadow_factor:se,u_opacity_multiplier:1}},c.ed=zr,c.ee=JY,c.ef=5,c.eg=Qfs,c.eh=zn,c.ei=function(N,p){var _=Math.sin(p),A=Math.cos(p);return N[0]=A,N[1]=0,N[2]=-_,N[3]=0,N[4]=0,N[5]=1,N[6]=0,N[7]=0,N[8]=_,N[9]=0,N[10]=A,N[11]=0,N[12]=0,N[13]=0,N[14]=0,N[15]=1,N},c.ej=function(N,p){var _=Math.sin(p),A=Math.cos(p);return N[0]=1,N[1]=0,N[2]=0,N[3]=0,N[4]=0,N[5]=A,N[6]=_,N[7]=0,N[8]=0,N[9]=-_,N[10]=A,N[11]=0,N[12]=0,N[13]=0,N[14]=0,N[15]=1,N},c.ek=function(N,p){return N[0]=p[0],N[1]=p[1],N[2]=p[2],N[3]=p[4],N[4]=p[5],N[5]=p[6],N[6]=p[8],N[7]=p[9],N[8]=p[10],N},c.el=f,c.em=so,c.en=1,c.eo=i$,c.ep=0,c.eq=Vl,c.er=function(N,p,_,A,M){return ta((N-p)/(_-p)*(M-A)+A,A,M)},c.es=ce,c.et=gs,c.eu=function(N,p){var _=p[0],A=p[1],M=p[2],F=p[3],z=p[4],H=p[5],Z=p[6],se=p[7],fe=p[8],xe=fe*z-H*se,be=-fe*F+H*Z,Te=se*F-z*Z,De=_*xe+A*be+M*Te;return De?(N[0]=xe*(De=1/De),N[1]=(-fe*A+M*se)*De,N[2]=(H*A-M*z)*De,N[3]=be*De,N[4]=(fe*_-M*Z)*De,N[5]=(-H*_+M*F)*De,N[6]=Te*De,N[7]=(-se*_+A*Z)*De,N[8]=(z*_-A*F)*De,N):null},c.ev=si,c.ew=class{constructor(){this._updateTime=0,this._sourceIds=[],this._activeRegions=[],this._prevRegions=[],this._globalClipBounds={min:new xs(1/0,1/0),max:new xs(-1/0,-1/0)}}clear(){this._activeRegions.length>0&&++this._updateTime,this._activeRegions=[],this._prevRegions=[]}get updateTime(){return this._updateTime}getReplacementRegionsForTile(N,p=!1){const _=Xdt(new xs(0,0),new xs(Fr,Fr),N),A=[];if(p&&!vOe(_,this._globalClipBounds))return A;for(const M of this._activeRegions){if(M.hiddenByOverlap||!vOe(_,M))continue;const F=oms(M.min,M.max,N);A.push({min:F.min,max:F.max,sourceId:this._sourceIds[M.priority],footprint:M.footprint,footprintTileId:M.tileId,order:M.order,clipMask:M.clipMask,clipScope:M.clipScope})}return A}setSources(N){this._setSources(N.map(p=>({getSourceId:()=>p.cache.id,getFootprints:()=>{const _=[];for(const A of p.cache.getVisibleCoordinates()){const M=p.cache.getTile(A).buckets[p.layer];M&&M.updateFootprints(A.toUnwrapped(),_)}return _},getOrder:()=>p.order,getClipMask:()=>p.clipMask,getClipScope:()=>p.clipScope})))}_addSource(N){const p=N.getFootprints();if(p.length===0)return;const _=N.getOrder(),A=N.getClipMask(),M=N.getClipScope();for(const F of p){if(!F.footprint)continue;const z=Xdt(F.footprint.min,F.footprint.max,F.id);this._activeRegions.push({min:z.min,max:z.max,hiddenByOverlap:!1,priority:this._sourceIds.length,tileId:F.id,footprint:F.footprint,order:_,clipMask:A,clipScope:M})}this._sourceIds.push(N.getSourceId())}_computeReplacement(){this._activeRegions.sort((p,_)=>p.priority-_.priority||Hoe(p.min,_.min)||Hoe(p.max,_.max)||p.order-_.order||p.clipMask-_.clipMask||function(A,M){const F=(z,H)=>z+H;return A.length-M.length||A.reduce(F,"").localeCompare(M.reduce(F,""))}(p.clipScope,_.clipScope));let N=this._activeRegions.length!==this._prevRegions.length;if(!N){let p=0;for(;!N&&p!==this._activeRegions.length;){const _=this._activeRegions[p],A=this._prevRegions[p];N=_.priority!==A.priority||!Zdt(_,A)||_.order!==A.order||_.clipMask!==A.clipMask||!Lr(_.clipScope,A.clipScope),this._activeRegions[p].hiddenByOverlap=A.hiddenByOverlap,++p}}if(N){++this._updateTime;for(const _ of this._activeRegions)_.order!==DY&&(this._globalClipBounds.min.x=Math.min(this._globalClipBounds.min.x,_.min.x),this._globalClipBounds.min.y=Math.min(this._globalClipBounds.min.y,_.min.y),this._globalClipBounds.max.x=Math.max(this._globalClipBounds.max.x,_.max.x),this._globalClipBounds.max.y=Math.max(this._globalClipBounds.max.y,_.max.y));const p=_=>{const A=this._activeRegions;if(_>=A.length)return _;const M=A[_].priority;for(;_1){let _=0,A=p(_);for(;_!==A;){let M=_;const F=_;for(;M!==A;){const z=this._activeRegions[M];z.hiddenByOverlap=!1;for(let H=0;H=0;p--)this._addSource(N[p]);this._computeReplacement()}},c.ex=DY,c.ey=class{constructor(N){this._createGrid(N),this._createPoles(N)}destroy(){this._poleIndexBuffer.destroy(),this._gridBuffer.destroy(),this._gridIndexBuffer.destroy(),this._poleNorthVertexBuffer.destroy(),this._poleSouthVertexBuffer.destroy();for(const N of this._poleSegments)N.destroy();for(const N of this._gridSegments)N.withSkirts.destroy(),N.withoutSkirts.destroy()}_fillGridMeshWithLods(N,p){const _=new Hs,A=new Vr,M=[],F=N+1+2,z=p[0]+1,H=p[0]+1+(1+p.length),Z=(se,fe,xe)=>{let be=se===F-1?se-2:se===0?se:se-1;return be+=xe?24575:0,[be,fe]};for(let se=0;se0&&VOe(p,N.layers[0].source,N.sourceLayerName);(A||M)&&(N.hdExt=new Rut(N,A,M))},c.fC=function(N,p){const _=N.layers[0].layout.get("line-elevation-reference")==="hd-road-markup",A=!!p&&p.length>0&&VOe(p,N.layers[0].source,N.sourceLayerName);(_||A)&&(N.hdExt=new Dut(_,A))},c.fD=Moe,c.fE=function(N){const p=N.layers[0];p.type==="circle"&&p.layout.get("circle-elevation-reference")==="hd-road-markup"&&(N.hdExt=new Fut)},c.fF=function(N){N.layers[0].layout.get("symbol-elevation-reference")==="hd-road-markup"&&(N.hdExt=new Out)},c.fG=Sft,c.fH=function(N){let p=0;if(new Uint32Array(N,0,1)[0]!==Gut){const _=new Uint32Array(N,0,7),[,,A,M,F,z]=_;p=_.byteLength+M+F+z+F,(A!==N.byteLength||p>=N.byteLength)&&Yo("Invalid b3dm header information.")}return Zut(N,p)},c.fI=function(N,p){const _=t8e(N);for(const A of _){if(!A.meshBVH)for(const M of A.meshes)mfs(M);if(A.lights){let M=65535;for(const F of A.meshes)F.doorVertexColor!==void 0&&(M=F.doorVertexColor,A.lightsStyleAabb=F.aabb);A.lightMeshIndex=A.meshes.length,A.meshes.push(ffs(A.lights,p,M))}}return _},c.fJ=K,c.fK=Mmt,c.fL=oa,c.fM=function(N,p){let _="";for(let A=0;A=8592&&N<=8595||N===8208||N===8229||N===8741||N>=9472&&N<=9547||N===65294||N===65309||N===65374||N===65507},c.fS=3,c.fT=nj,c.fU=ddt,c.fV=B3,c.fW=function(N){for(const p of N)if(!Oe(p.charCodeAt(0)))return!1;return!0},c.fX=de,c.fY=oOe,c.fZ=Cdt,c.f_=Pdt,c.fa=Eo,c.fb=$dt,c.fc=function(N){const p=[0,0,0],_=w(new Float64Array(16));return E(_,N.pixelMatrix,N.globeMatrix),Xe(p,p,_),new xs(p[0],p[1])},c.fd=function(N){Ia=N},c.fe=tr,c.ff=Fmt,c.fg=function(N,p){if(!N||!p)throw new Error("TileProvider name and URL are required");gt.TILE_PROVIDER_URLS[N]=oh.resolveURL(p)},c.fh=function(N){typeof N!="string"||N.length>64||!xi.test(N)?Yo(`Invalid SDK info "${N}"; expected a "Name/version" string. Ignoring.`):Aa=N},c.fi=wy,c.fj=function(N,p,_=!1){if(Pi===$r.deferred||Pi===$r.loading||Pi===$r.loaded)throw new Error("setRTLTextPlugin cannot be called multiple times.");gl=oh.resolveURL(N),Pi=$r.deferred,ui=p,Kh(),_||W_()},c.fk=function(N){gt.BUILDING_GEN_URL=oh.resolveURL(N)},c.fl=jt,c.fm=function(N){const p=oh.resolveURL(N);gt.MESHOPT_URL=p,gt.MESHOPT_SIMD_URL=p},c.fn=ut,c.fo=function(N){gt.DRACO_URL=oh.resolveURL(N)},c.fp=We,c.fq=function(N){const p=fn();if(!p)return;const _=p.delete(Wt);N&&_.then(()=>N()).catch(N)},c.fr=function(N){gt.MAX_PARALLEL_IMAGE_REQUESTS=N},c.fs=function(N){gt.API_URL=N},c.ft=function(N){gt.ACCESS_TOKEN=N},c.fu="hd_road_elevation",c.fv=class{static parseFrom(N,p){const _=W3.parse(N);if(!_)return[];let{vertices:A,features:M}=_;const F=1/K(p);M.sort((se,fe)=>se.id-fe.id),A.sort((se,fe)=>se.id-fe.id||se.idx-fe.idx),A=A.filter((se,fe,xe)=>fe===xe.findIndex(be=>be.id===se.id&&be.idx===se.idx));const z=new Array;let H=0;const Z=A.length;for(const se of M){if(se.constantHeight){z.push(new K3(se.id,se.bounds,se.constantHeight));continue}for(;H!==Z&&A[H].id=0&&N<128)return this.pos>=this.length&&this.realloc(1),void(this.buf[this.pos++]=N);N>268435455||N<0?function(p,_){let A,M;if(p>=0?(A=p%4294967296|0,M=p/4294967296|0):(A=~(-p%4294967296),M=~(-p/4294967296),4294967295^A?A=A+1|0:(A=0,M=M+1|0)),p>=18446744073709552e3||p<-18446744073709552e3)throw new Error("Given varint doesn't fit into 10 bytes");_.realloc(10),function(F,z,H){H.buf[H.pos++]=127&F|128,F>>>=7,H.buf[H.pos++]=127&F|128,F>>>=7,H.buf[H.pos++]=127&F|128,F>>>=7,H.buf[H.pos++]=127&F|128,H.buf[H.pos]=127&(F>>>=7)}(A,0,_),function(F,z){const H=(7&F)<<4;z.buf[z.pos++]|=H|((F>>>=3)?128:0),F&&(z.buf[z.pos++]=127&F|((F>>>=7)?128:0),F&&(z.buf[z.pos++]=127&F|((F>>>=7)?128:0),F&&(z.buf[z.pos++]=127&F|((F>>>=7)?128:0),F&&(z.buf[z.pos++]=127&F|((F>>>=7)?128:0),F&&(z.buf[z.pos++]=127&F)))))}(M,_)}(N,this):(this.realloc(4),this.buf[this.pos++]=127&N|(N>127?128:0),N<=127||(this.buf[this.pos++]=127&(N>>>=7)|(N>127?128:0),N<=127||(this.buf[this.pos++]=127&(N>>>=7)|(N>127?128:0),N<=127||(this.buf[this.pos++]=N>>>7&127))))}writeSVarint(N){this.writeVarint(N<0?2*-N-1:2*N)}writeBoolean(N){this.writeVarint(+N)}writeString(N){N=String(N),this.realloc(4*N.length),this.pos++;const p=this.pos;this.pos=function(A,M,F){for(let z,H,Z=0;Z55295&&z<57344){if(!H){z>56319||Z+1===M.length?(A[F++]=239,A[F++]=191,A[F++]=189):H=z;continue}if(z<56320){A[F++]=239,A[F++]=191,A[F++]=189,H=z;continue}z=H-55296<<10|z-56320|65536,H=null}else H&&(A[F++]=239,A[F++]=191,A[F++]=189,H=null);z<128?A[F++]=z:(z<2048?A[F++]=z>>6|192:(z<65536?A[F++]=z>>12|224:(A[F++]=z>>18|240,A[F++]=z>>12&63|128),A[F++]=z>>6&63|128),A[F++]=63&z|128)}return F}(this.buf,N,this.pos);const _=this.pos-p;_>=128&&aut(p,_,this),this.pos=p-1,this.writeVarint(_),this.pos+=_}writeFloat(N){this.realloc(4),this.dataView.setFloat32(this.pos,N,!0),this.pos+=4}writeDouble(N){this.realloc(8),this.dataView.setFloat64(this.pos,N,!0),this.pos+=8}writeBytes(N){const p=N.length;this.writeVarint(p),this.realloc(p),this.buf.set(N,this.pos),this.pos+=p}writeRawMessage(N,p){this.pos++;const _=this.pos;N(p,this);const A=this.pos-_;A>=128&&aut(_,A,this),this.pos=_-1,this.writeVarint(A),this.pos+=A}writeMessage(N,p,_){this.writeTag(N,2),this.writeRawMessage(p,_)}writePackedVarint(N,p){p.length&&this.writeMessage(N,lms,p)}writePackedSVarint(N,p){p.length&&this.writeMessage(N,cms,p)}writePackedBoolean(N,p){p.length&&this.writeMessage(N,hms,p)}writePackedFloat(N,p){p.length&&this.writeMessage(N,dms,p)}writePackedDouble(N,p){p.length&&this.writeMessage(N,ums,p)}writePackedFixed32(N,p){p.length&&this.writeMessage(N,mms,p)}writePackedSFixed32(N,p){p.length&&this.writeMessage(N,fms,p)}writePackedFixed64(N,p){p.length&&this.writeMessage(N,pms,p)}writePackedSFixed64(N,p){p.length&&this.writeMessage(N,gms,p)}writeBytesField(N,p){this.writeTag(N,2),this.writeBytes(p)}writeFixed32Field(N,p){this.writeTag(N,5),this.writeFixed32(p)}writeSFixed32Field(N,p){this.writeTag(N,5),this.writeSFixed32(p)}writeFixed64Field(N,p){this.writeTag(N,1),this.writeFixed64(p)}writeSFixed64Field(N,p){this.writeTag(N,1),this.writeSFixed64(p)}writeVarintField(N,p){this.writeTag(N,0),this.writeVarint(p)}writeSVarintField(N,p){this.writeTag(N,0),this.writeSVarint(p)}writeStringField(N,p){this.writeTag(N,2),this.writeString(p)}writeFloatField(N,p){this.writeTag(N,5),this.writeFloat(p)}writeDoubleField(N,p){this.writeTag(N,1),this.writeDouble(p)}writeBooleanField(N,p){this.writeVarintField(N,+p)}},c.gq=Xc,c.gr=Voe,c.gs=$r,c.gt=Aft,c.gu=function(N){xn(),Ps!=null&&Ps.then(p=>{p.keys().then(_=>{for(let A=0;A<_.length-N;A++)p.delete(_[A]).catch(M=>Yo(M.message))}).catch(_=>Yo(_.message))}).catch(p=>Yo(p.message))},c.h=Bl,c.i=Rh,c.j=2,c.k=zY,c.l=tj,c.m=G6,c.n=z1,c.o=Yy,c.p=iut,c.q=$_,c.r=Qy,c.s=Zs,c.t=Xy,c.u=M9,c.v=oj,c.w=Yo,c.x=Vv,c.y=P9,c.z=K0}),i(["require","./shared"],function(o,c){function d(gt){const We=gt?gt.url.toString():void 0;return We?performance.getEntriesByName(We):[]}function u(gt,We){if(Object.hasOwn(gt.layers,c.fu))return c.fv.parseFrom(gt.layers[c.fu],We)}function h({buckets:gt,data:We,sourceLayerCoder:ut,canonical:jt,options:Rt}){if(!Rt.elevationFeatures||Rt.elevationFeatures.length===0)return;const zt=[];for(const ws of Object.values(gt))if(ws instanceof c.bB&&ws.hdExt){const Ms=ws.hdExt.getUnevaluatedPortalGraph();Ms&&zt.push(Ms)}const Wt=c.fw.evaluate(zt);for(const ws of Object.values(gt))if(ws instanceof c.bB&&ws.hdExt){const Ms=We.layers[ut.decode(ws.sourceLayerIndex)];ws.hdExt.setEvaluatedPortalGraph(Wt,Ms,jt,Rt.availableImages,Rt.brightness,ws.worldview)}}function m(gt){const We=[];for(let ut=0;ut0){let Ms=!1;for(const Ns of Wt[0])if(Ns.x<0||Ns.x>c.a6||Ns.y<0||Ns.y>c.a6){Ms=!0;break}if(Ms)continue}const ws=Wt.length===1&&Wt[0].length===5&&Wt[0].some(Ms=>Ms.x<=0&&Ms.y<=0)&&Wt[0].some(Ms=>Ms.x>=c.a6&&Ms.y<=0)&&Wt[0].some(Ms=>Ms.x>=c.a6&&Ms.y>=c.a6)&&Wt[0].some(Ms=>Ms.x<=0&&Ms.y>=c.a6);We.push(new c.fx(zt,ws?[]:Wt))}return We}function f(gt,We,ut,jt,Rt){const zt=c.fy(We);if(zt===null)return!1;let Wt=ut.x,ws=ut.y;const Ms=Rt??jt.z;if(jt.z!==Ms){const Ns=1<fn.map(xn=>[xn.x,xn.y]));if(c.fz([Wt,ws],Ps))return!0}return!1}function g(gt,We,ut,jt){const Rt=We.indoorState.activeFloorsVisible;if(!We.sourceLayers)return Rt?We.indoorState.activeFloors:void 0;const zt=function(Ms,Ns){if(!Ms)return c.w("No source layers defined in indoor specification"),Ns;if(Ms.size===0)return Ns;const Ps=Ms.difference(Ns);for(const fn of Ps)c.w(`Missing source layer required in indoor specification: ${fn}`);return Ns.intersection(Ns)}(We.sourceLayers,new Set(Object.keys(gt.layers))),Wt=We.indoorState,ws=function(Ms,Ns,Ps,fn,xn){const bn={};for(const Pn of Ns){const or=Ms.layers[Pn];if(or)for(let tr=0;trPn.map(or=>c.fA(or,fn,Ps.extent)));return bn.length===0?void 0:{type:"Polygon",coordinates:[bn[0]]}}(gt,We);return{id:ut,isDefault:jt,connections:Rt,conflicts:zt,buildings:Wt,name:ws,zIndex:Ms,geometry:Ns}}function w(gt,We){return We.every(ut=>gt.properties&>.properties[ut]!=null)}function S(gt){return w(gt,["type","id","name"])&>.properties.type==="structure"}function C(gt){return w(gt,["type","id","name","z_index"])&>.properties.type==="floor"}function E(gt,We){gt instanceof c.bB?c.fB(gt,We):gt instanceof c.bA?c.fC(gt,We):gt instanceof c.fD?c.fE(gt):gt instanceof c.bv&&c.fF(gt)}function I(gt){for(const We in gt){const ut=gt[We];if(ut instanceof c.bA&&ut.hdExt&&ut.hdExt.hasDeferredElevationFeatures||ut instanceof c.bv&&ut.hdExt&&ut.hdExt.hasDeferredElevationFeatures)return!0}return!1}class P{constructor(We,ut,jt){this.tileID=new c.bQ(We.tileID.overscaledZ,We.tileID.wrap,We.tileID.canonical.z,We.tileID.canonical.x,We.tileID.canonical.y),this.tileZoom=We.tileZoom,this.uid=We.uid,this.zoom=We.zoom,this.canonical=We.tileID.canonical,this.pixelRatio=We.pixelRatio,this.tileSize=We.tileSize,this.source=We.source,this.overscaling=this.tileID.overscaleFactor(),this.projection=We.projection,this.brightness=ut,this.worldview=jt}async parse(We,ut,jt){this.status="parsing";const Rt=new c.bQ(jt.tileID.overscaledZ,jt.tileID.wrap,jt.tileID.canonical.z,jt.tileID.canonical.x,jt.tileID.canonical.y),zt=[],Wt=ut.familiesBySource[jt.source],ws=new c.fG(Rt,jt.promoteId);ws.bucketLayerIDs=[],ws.is3DTile=!0;const Ms=await c.fH(We),Ns=Ms.json.extensionsUsed&&Ms.json.extensionsUsed.includes("MAPBOX_mesh_features")||Ms.json.asset.extras&&Ms.json.asset.extras.MAPBOX_mesh_features,Ps=Ms.json.extensionsUsed&&Ms.json.extensionsUsed.includes("EXT_meshopt_compression"),fn=new c.aj(this.zoom,{brightness:this.brightness,worldview:this.worldview});for(const xn in Wt)for(const bn of Wt[xn]){const Pn=bn[0];ws.bucketLayerIDs.push(bn.map(sr=>c.m(sr.id,sr.scope))),Pn.recalculate(fn,[]);const or=c.fI(Ms,1/c.fJ(jt.tileID.canonical)),tr=new c.fK(bn,or,Rt,Ns,Ps,this.brightness,ws,this.worldview);zt.push(tr),tr.evaluate(Pn)}return this.status="done",{buckets:zt,featureIndex:ws,collisionBoxArray:null,glyphAtlasImage:null,lineAtlas:null,imageAtlas:null,brightness:null}}}class R{constructor({actor:We,layerIndex:ut,availableImages:jt,availableModels:Rt,brightness:zt,worldview:Wt}){this.actor=We,this.layerIndex=ut,this.availableImages=jt,this.availableModels=Rt,this.brightness=zt,this.loading={},this.loaded={},this.worldview=Wt}async loadTile(We){const ut=We.uid,jt=new AbortController,Rt=this.loading[ut]=new P(We,this.brightness,this.worldview);Rt.abort=()=>jt.abort();const zt=(ws,Ms)=>{const Ns=Rt.reloadCallback;Ns&&(delete Rt.reloadCallback,Ns(ws,Ms))};let Wt;try{Wt=(await c.d0(We.request,jt.signal)).data}catch(ws){if(delete this.loading[ut],Rt.status="done",this.loaded[ut]=Rt,jt.signal.aborted)return null;throw ws}if(delete this.loading[ut],!Wt||Wt.byteLength===0)return Rt.status="done",this.loaded[ut]=Rt,null;try{const ws=await Rt.parse(Wt,this.layerIndex,We);return this.loaded[ut]=Rt,zt(null,ws),ws}catch(ws){throw this.loaded[ut]=Rt,zt(ws),ws}}async reloadTile(We){const ut=this.loaded&&this.loaded[We.uid];if(ut)return ut.projection=We.projection,ut.brightness=We.brightness,ut.status==="parsing"&&await new Promise((jt,Rt)=>{ut.reloadCallback=zt=>{zt?Rt(zt):jt()}}),this.loadTile(We)}abortTile(We){const ut=We.uid,jt=this.loading[ut];jt&&(jt.abort&&jt.abort(),delete this.loading[ut])}removeTile(We){const ut=this.loaded,jt=We.uid;ut&&ut[jt]&&delete ut[jt]}}function D(gt){if(typeof gt=="number"||typeof gt=="boolean"||typeof gt=="string"||gt==null)return JSON.stringify(gt);if(Array.isArray(gt)){let ut="[";for(const jt of gt)ut+=`${D(jt)},`;return`${ut}]`}let We="{";for(const ut of Object.keys(gt).sort())We+=`${ut}:${D(gt[ut])},`;return`${We}}`}function O(gt){let We="";for(const ut of c.d1)We+=`/${D(gt[ut])}`;return We}function U(gt,We){return function ut(jt){return typeof jt=="string"&&jt===We||(Array.isArray(jt)?jt.some(ut):!(!jt||typeof jt!="object")&&Object.values(jt).some(ut))}(gt)}class W{constructor(We){this.keyCache=Object.create(null),this._layers=Object.create(null),this._layerConfigs=Object.create(null),We&&this.replace(We)}replace(We,ut){this._layerConfigs=Object.create(null),this._layers=Object.create(null),this.update(We,[],ut)}update(We,ut,jt){this._options=jt;for(const zt of We)this._layerConfigs[zt.id]=zt,(this._layers[zt.id]=c.dM(zt,this.scope,null,this._options)).compileFilter(jt),this.keyCache[zt.id]&&delete this.keyCache[zt.id];for(const zt of ut)delete this.keyCache[zt],delete this._layerConfigs[zt],delete this._layers[zt];this.familiesBySource=Object.create(null);const Rt=function(zt,Wt){const ws=Object.create(null);for(let Ns=0;Nsthis._layers[xn.id]),ws=Wt[0];if(ws.visibility==="none")continue;const Ms=ws.source||"";let Ns=this.familiesBySource[Ms];Ns||(Ns=this.familiesBySource[Ms]=Object.create(null));const Ps=ws.sourceLayer||"_geojsonTileLayer";let fn=Ns[Ps];fn||(fn=Ns[Ps]=[]),fn.push(Wt)}}}class V extends c.P{constructor(We,ut,jt,Rt,zt){super(We,ut),this.angle=Rt,this.z=jt,zt!==void 0&&(this.segment=zt)}clone(){return new V(this.x,this.y,this.z,this.angle,this.segment)}}function G(gt,We,ut,jt,Rt){if(We.segment===void 0)return!0;let zt=We,Wt=We.segment+1,ws=0;for(;ws>-ut/2;){if(Wt--,Wt<0)return!1;ws-=gt[Wt].dist(zt),zt=gt[Wt]}ws+=gt[Wt].dist(gt[Wt+1]),Wt++;const Ms=[];let Ns=0;for(;wsjt;)Ns-=Ms.shift().angleDelta;if(Ns>Rt)return!1;Wt++,ws+=Ps.dist(fn)}return!0}function Y(gt){let We=0;for(let ut=0;utNs){const Pn=(Ns-Ms)/bn,or=c.am(fn.x,xn.x,Pn),tr=c.am(fn.y,xn.y,Pn),sr=new V(or,tr,0,xn.angleTo(fn),Ps);return!Wt||G(gt,sr,ws,Wt,We)?sr:void 0}Ms+=bn}}function ne(gt,We,ut,jt,Rt,zt,Wt,ws,Ms){const Ns=X(jt,zt,Wt),Ps=ae(jt,Rt),fn=Ps*Wt,xn=gt[0].x===0||gt[0].x===Ms||gt[0].y===0||gt[0].y===Ms;return We-fn=0&&Va=0&&Je=0&&xn+Ns<=Ps){const Ht=new V(Va,Je,0,br,Pn);jt&&!G(gt,Ht,zt,jt,Rt)||bn.push(Ht)}}fn+=sr}return ws||bn.length||Wt||(bn=te(gt,fn/2,ut,jt,Rt,zt,Wt,!0,Ms)),bn}c.fL(V,"Anchor");class J{constructor(){this.scale=1,this.fontStack="",this.image=null}static forText(We,ut){const jt=new J;return jt.scale=We||1,jt.fontStack=ut,jt}static forImage(We){const ut=new J;return ut.image=We,ut}}class ce{constructor(){this.text="",this.sectionIndex=[],this.sections=[],this.imageSectionID=null}static fromFeature(We,ut,jt,Rt=1){const zt=new ce;for(let Wt=0;Wt=0&&jt>=We&&ue[this.text.charCodeAt(jt)];jt--)ut--;this.text=this.text.substring(We,ut),this.sectionIndex=this.sectionIndex.slice(We,ut)}substring(We,ut){const jt=new ce;return jt.text=this.text.substring(We,ut),jt.sectionIndex=this.sectionIndex.slice(We,ut),jt.sections=this.sections,jt}toString(){return this.text}getMaxScale(){return this.sectionIndex.reduce((We,ut)=>Math.max(We,this.sections[ut].scale),0)}addTextSection(We,ut){this.text+=We.text,this.sections.push(J.forText(We.scale,We.fontStack||ut));const jt=this.sections.length-1;for(let Rt=0;Rt=63743?null:++this.imageSectionID:(this.imageSectionID=57344,this.imageSectionID)}}function _e(gt,We){if(!gt.image)return!1;const ut=We.get(gt.image.toString());return!!ut&&ut.sdf}function he(gt,We,ut,jt,Rt,zt,Wt,ws,Ms,Ns,Ps,fn,xn,bn,Pn,or=1,tr=1){const sr=ce.fromFeature(gt,Rt,or,tr);fn===c.dt.vertical&&sr.verticalizePunctuation(xn);const br=sr.toString();if(function(tn,nr){const rr=tn.sections.findIndex(Na=>_e(Na,nr));if(rr===-1)return;c.w(`SDF image ${tn.sections[rr].image.id.name} is not supported in text-field`);const Qr=tn.sections.map(Na=>_e(Na,nr));let na="";const $a=[];for(let Na=0;Na0&&lu>zo&&(zo=lu)}else{const hd=rr[Td.fontStack];if(!hd)continue;hd[Qc]&&(If=hd[Qc]);const Bl=nr[Td.fontStack];if(!Bl)continue;const Xi=Bl.glyphs[Qc];if(!Xi)continue;if(lh=Xi.metrics,od=Qc!==8203?c.dg:0,iu){const Md=Bl.ascender!==void 0?Math.abs(Bl.ascender):0,lu=Bl.descender!==void 0?Math.abs(Bl.descender):0,Jc=(Md+lu)*id;Lczt)&&(zt=Pn.x),(!bn||Pn.y>Wt)&&(Wt=Pn.y)}const Ms=Math.min(zt-jt,Wt-Rt);let Ns=Ms/2;const Ps=new c.fT([],Ae);if(Ms===0)return new c.P(jt,Rt);for(let bn=jt;bnfn.d||!fn.d)&&(fn=bn,ut&&console.log("found best %d after %d probes",Math.round(1e4*bn.d)/1e4,xn)),bn.max-fn.d<=We||(Ns=bn.h/2,Ps.push(new Ce(bn.p.x-Ns,bn.p.y-Ns,Ns,gt)),Ps.push(new Ce(bn.p.x+Ns,bn.p.y-Ns,Ns,gt)),Ps.push(new Ce(bn.p.x-Ns,bn.p.y+Ns,Ns,gt)),Ps.push(new Ce(bn.p.x+Ns,bn.p.y+Ns,Ns,gt)),xn+=4)}return ut&&(console.log(`num probes: ${xn}`),console.log(`best distance: ${fn.d}`)),fn.p}function Ae(gt,We){return We.max-gt.max}class Ce{constructor(We,ut,jt,Rt){this.p=new c.P(We,ut),this.h=jt,this.d=function(zt,Wt){let ws=!1,Ms=1/0;for(let Ns=0;Nszt.y!=or.y>zt.y&&zt.x<(or.x-Pn.x)*(zt.y-Pn.y)/(or.y-Pn.y)+Pn.x&&(ws=!ws),Ms=Math.min(Ms,c.fU(zt,Pn,or))}}return(ws?1:-1)*Math.sqrt(Ms)}(this.p,Rt),this.max=this.d+this.h*Math.SQRT2}}const qe=Object.keys;function ze(gt){return gt.imagePrimary!==void 0&>.top!==void 0&>.bottom!==void 0&>.left!==void 0&>.right!==void 0}function $e(gt){return!gt.imagePrimary.stretchX}function ct(gt){return!gt.imagePrimary.stretchY}function Xe(gt){return{width:gt.right-gt.left,height:gt.bottom-gt.top}}const it=Number.POSITIVE_INFINITY;function at(gt,We,ut,jt,Rt,zt){const Wt=ze(gt)&>.collisionPadding?gt.collisionPadding:[0,0,0,0],ws={top:gt.top-Wt[1],bottom:gt.bottom+Wt[3],left:gt.left-Wt[0],right:gt.right+Wt[2],scaled:!1};return jt!==void 0&&function(Ms,Ns){Ms.top*=Ns,Ms.bottom*=Ns,Ms.left*=Ns,Ms.right*=Ns,Ms.scaled=!0}(ws,jt),zt&&(ws.left+=zt[0],ws.right+=zt[0],ws.top+=zt[1],ws.bottom+=zt[1]),ut&&function(Ms,Ns,Ps){if(!Ns)return;const fn=c.av(Ns),xn=new c.P(Ps?Ps[0]:0,Ps?Ps[1]:0),bn=new c.P(Ms.left,Ms.top),Pn=new c.P(Ms.right,Ms.top),or=new c.P(Ms.left,Ms.bottom),tr=new c.P(Ms.right,Ms.bottom);bn._rotateAround(fn,xn),Pn._rotateAround(fn,xn),or._rotateAround(fn,xn),tr._rotateAround(fn,xn),Ms.left=Math.min(bn.x,Pn.x,or.x,tr.x),Ms.right=Math.max(bn.x,Pn.x,or.x,tr.x),Ms.top=Math.min(bn.y,Pn.y,or.y,tr.y),Ms.bottom=Math.max(bn.y,Pn.y,or.y,tr.y)}(ws,ut,Rt),We?{top:Math.min(We.top,ws.top),bottom:Math.max(We.bottom,ws.bottom),left:Math.min(We.left,ws.left),right:Math.max(We.right,ws.right),scaled:We.scaled||ws.scaled}:ws}function Ke(gt,We,ut,jt,Rt,zt,Wt,ws=1,Ms,Ns,Ps,fn,xn,bn,Pn,or,tr){gt.createArrays(),gt.tilePixelRatio=c.a6/(512*gt.overscaling),gt.compareText={},gt.iconsNeedLinear=!1;const sr=gt.layers[0].layout,br=gt.layers[0]._unevaluatedLayout._values,vr={};vr.scaleFactor=ws,vr.textSizeScaleRange=sr.get("text-size-scale-range"),vr.iconSizeScaleRange=sr.get("icon-size-scale-range");const[Va,Je]=vr.textSizeScaleRange,[Ht,Ts]=vr.iconSizeScaleRange;vr.textScaleFactor=c.b1(vr.scaleFactor,Va,Je),vr.iconScaleFactor=c.b1(vr.scaleFactor,Ht,Ts);const ln=br["text-size"],tn=br["icon-size"];if(gt.textSizeData.kind==="composite"){const{minZoom:La,maxZoom:to}=gt.textSizeData;vr.compositeTextSizes=[ln.possiblyEvaluate(new c.aj(La,{worldview:Ps}),zt),ln.possiblyEvaluate(new c.aj(to,{worldview:Ps}),zt)]}if(gt.iconSizeData.kind==="composite"){const{minZoom:La,maxZoom:to}=gt.iconSizeData;vr.compositeIconSizes=[tn.possiblyEvaluate(new c.aj(La,{worldview:Ps}),zt,fn),tn.possiblyEvaluate(new c.aj(to,{worldview:Ps}),zt,fn)]}vr.layoutTextSize=ln.possiblyEvaluate(new c.aj(Wt+1,{worldview:Ps}),zt),vr.layoutIconSize=tn.possiblyEvaluate(new c.aj(Wt+1,{worldview:Ps}),zt,fn),vr.textMaxSize=ln.possiblyEvaluate(new c.aj(18,{worldview:Ps}),zt);const nr=sr.get("symbol-placement"),rr=sr.get("text-rotation-alignment")==="map"&&nr!=="point",Qr=sr.get("text-size");let na=!1;const $a=[],Na=xn!=null&&xn!==0;for(const La of gt.features){if(Na&&La.properties&&or&&or(La.properties,xn))continue;let to=65535;if(gt.hdExt&&La.properties&&Object.hasOwn(La.properties,c.fV)){const gu=+La.properties[c.fV];if(!Number.isNaN(gu)){const Qc=gt.hdExt.resolveRoadElevation(La,gu);if(Qc==="defer")continue;to=Qc}}const xo=sr.get("text-font").evaluate(La,{},zt).join(","),oo=Qr.evaluate(La,{},zt)*vr.textScaleFactor,Lo=vr.layoutTextSize.evaluate(La,{},zt)*vr.textScaleFactor,ql=vr.layoutIconSize.evaluate(La,{},zt,fn)*vr.iconScaleFactor,po={horizontal:{},vertical:void 0},nl=La.text;let Il,Ed=[0,0];if(nl){const gu=nl.toString(),Qc=sr.get("text-letter-spacing").evaluate(La,{},zt)*c.dg,id=sr.get("text-line-height").evaluate(La,{},zt)*c.dg,lh=c.fW(gu)?Qc:0,If=sr.get("text-anchor").evaluate(La,{},zt),Ud=sr.get("text-variable-anchor");if(!Ud){const hd=sr.get("text-radial-offset").evaluate(La,{},zt);if(hd)Ed=c.dv(If,[hd*c.dg,it]);else{const Bl=sr.get("text-offset").evaluate(La,{},zt);Ed=[Bl[0]*c.dg,Bl[1]*c.dg]}}let od=rr?"center":sr.get("text-justify").evaluate(La,{},zt);const Lh=nr==="point",Gu=Lh?sr.get("text-max-width").evaluate(La,{},zt)*c.dg:1/0,qd=hd=>{gt.allowVerticalPlacement&&c.fX(gu)&&(po.vertical=he(nl,We,ut,Rt,xo,Gu,id,If,hd,lh,Ed,c.dt.vertical,!0,Lo,oo,Ms,vr.textScaleFactor))};if(!rr&&Ud){const hd=od==="auto"?Ud.map(Xi=>c.dw(Xi)):[od];let Bl=!1;for(let Xi=0;Xi0?sr/Ms:1;br&&(gt.iconBBox=at(br,gt.iconBBox,tr,Je!==1?Je:void 0)),vr&&(gt.iconVerticalBBox=at(vr,gt.iconVerticalBBox,tr+90,Je!==1?Je:void 0))}function rt(gt,We,ut,jt,Rt,zt,Wt,ws){let Ms=null;const Ns=We.getAppearanceValueAndResolveTokens(ut,"icon-image",jt,Rt,ws);if(Ns){const Ps=gt.getResolvedImageFromTokens(Ns),fn=ut.hasLayoutProperty("icon-size")?ut.getUnevaluatedLayoutProperty("icon-size"):We._unevaluatedLayout._values["icon-size"],xn=c.g5(gt.zoom,fn,gt.worldview,ws),bn=c.fY(Ps,xn,fn,Rt,gt.zoom,jt,gt.pixelRatio,Wt,gt.worldview,ws);Ms=zt.get(bn.iconPrimary.toString())}return Ms}function Yt(gt,We,ut,jt,Rt,zt,Wt,ws,Ms,Ns){const{appearanceTextOffset:Ps,appearanceTextRotate:fn,appearanceTextSize:xn}=c.g3(ut,We,jt,Rt,zt,Wt,ws),bn=xn/ws,Pn=[(Ps[0]-zt[0])*bn,(Ps[1]-zt[1])*bn],or=Pn[0]!==0||Pn[1]!==0;Ms&&(gt.textBBox=at(Ms,gt.textBBox,fn,bn,Ps,or?Pn:void 0)),Ns&&(gt.textVerticalBBox=at(Ns,gt.textVerticalBBox,fn+90,bn,Ps,or?Pn:void 0))}function qt(gt,We,ut,jt,Rt,zt,Wt,ws){if(!gt||!gt.usvg)return;const Ms=Xe(ut),Ns=Xe(jt),Ps=Rt!=="both"&&Rt!=="width"||!$e(ut)?1:Ns.width/Ms.width,fn=Rt!=="both"&&Rt!=="height"||!ct(ut)?1:Ns.height/Ms.height;We.scaleSelf(Ps,fn);const xn=We.toString();zt.set(xn,We),Wt.set(xn,gt);const{imagePosition:bn}=c.g0(xn,gt,c.g1);ws.set(xn,bn)}function ts(gt,We,ut){if(!We)return;const jt=ut.get(gt.toString()),Rt=ut.get(We.toString());jt&&Rt&&(jt.paddedRect.w===Rt.paddedRect.w&&jt.paddedRect.h===Rt.paddedRect.h||c.w(`Mismatch in icon variant sizes: ${gt.toString()} and ${We.toString()}`),jt.usvg!==Rt.usvg&&c.w(`Mismatch in icon variant image types: ${gt.id} and ${We.id}`))}function ys(gt,We,ut,jt,Rt,zt,Wt,ws,Ms,Ns){gt.iconAtlasPositions=Ns.iconPositions;const{featureData:Ps,sizes:fn,textAlongLine:xn,symbolPlacement:bn,coveragePolygons:Pn,coverageTileZoom:or,symbolAnchorInFrcCoverage:tr}=We,sr=We.hasAnySecondaryIcon||gt.hasAnySecondaryIcon;for(const br of Ps){const{shapedIcon:vr,verticallyShapedIcon:Va,feature:Je,shapedTextOrientations:Ht,shapedText:Ts,layoutTextSize:ln,textOffset:tn,isSDFIcon:nr,iconPrimary:rr,iconSecondary:Qr,iconTextFit:na,iconOffset:$a,iconCollisionBounds:Na,iconVerticalCollisionBounds:La,textCollisionBounds:to,elevationFeatureIndex:xo}=br;Bt(vr,Ns.iconPositions,rr,Qr),Bt(Va,Ns.iconPositions,rr,Qr),Ft(Ht,Ns.iconPositions),ts(rr,Qr,Ns.iconPositions),(Ts||vr)&&Xs(gt,Je,Ht,vr,Va,Ms,fn,ln,0,tn,nr,jt,Rt,Wt,ws,sr,na,$a,xn,bn,Na,La,to,0,0,Pn,or,tr,xo)}ut&>.generateCollisionDebugBuffers(zt,gt.collisionBoxArray,fn.textScaleFactor),gt.text.uboBinder&>.text.uboBinder.finalize(),gt.icon.uboBinder&>.icon.uboBinder.finalize()}function Bt(gt,We,ut,jt){if(!gt)return;const Rt=We.get(ut.toString());if(Rt&&(gt.imagePrimary=Rt),jt){const zt=We.get(jt.toString());gt.imageSecondary=zt}}function Ft(gt,We){for(const ut in gt.horizontal)rs(gt.horizontal[ut],We);rs(gt.vertical,We)}function rs(gt,We){if(gt){for(const ut of gt.positionedLines)for(const jt of ut.positionedGlyphs)if(jt.image!==null){const Rt=jt.image.toString();jt.rect=We.get(Rt).paddedRect}}}function St(gt,We,ut,jt,Rt,zt,Wt,ws,Ms){const Ns=gs(zt.horizontal)||zt.vertical,Ps=ut.get("icon-text-fit-padding").evaluate(jt,{},Rt);let fn,xn=We;return We&&Ms!=="none"&&(gt.allowVerticalPlacement&&zt.vertical&&(fn=c.f$(We,zt.vertical,Ms,Ps,ws,Wt)),Ns&&(xn=c.f$(We,Ns,Ms,Ps,ws,Wt))),{defaultShapedIcon:xn,verticallyShapedIcon:fn}}function Xs(gt,We,ut,jt,Rt,zt,Wt,ws,Ms,Ns,Ps,fn,xn,bn,Pn,or,tr,sr,br,vr,Va,Je,Ht,Ts,ln,tn,nr,rr,Qr=65535){let na=Wt.textMaxSize.evaluate(We,{},xn);na===void 0?na=ws*Wt.textScaleFactor:na*=Wt.textScaleFactor;const $a=gt.layers[0].layout,Na=c.dg,La=c.f_(ws,Wt.textScaleFactor),to=gs(ut.horizontal)||ut.vertical,xo=gt.hasAnyAppearanceLayoutProperty(["text-size","text-offset","text-rotate"]),oo=gt.getAppearanceFeatureData(We.index);(tr!=="none"||xo)&&oo&&(oo.textShaping=to,oo.iconTextFitPadding=$a.get("icon-text-fit-padding").evaluate(We,{},xn),oo.fontScale=La,oo.textScaleFactor=Wt.textScaleFactor);const Lo=bn.name==="globe",ql=gt.tilePixelRatio*na/Na,po=(Cn=gt.overscaling,gt.zoom>18&&Cn>2&&(Cn>>=1),Math.max(c.a6/(512*Cn),1)*$a.get("symbol-spacing")),nl=$a.get("text-padding")*gt.tilePixelRatio,Il=$a.get("icon-padding")*gt.tilePixelRatio,Ed=c.av($a.get("text-max-angle")),iu=$a.get("icon-rotation-alignment")==="map"&&vr!=="point",Ut=po/2;var Cn;gt.hasAnyIconTextFit===!1&&tr!=="none"&&(gt.hasAnyIconTextFit=!0);const ar=(ra,Zr,Aa)=>{if(Zr.x<0||Zr.x>=c.a6||Zr.y<0||Zr.y>=c.a6||tn&&tn.length>0&&We.properties&&rr&&rr(tn,We.properties,Zr,xn,nr))return;let xi=null;if(Lo){const{x:Ia,y:el,z:zo}=bn.projectTilePoint(Zr.x,Zr.y,Aa);xi={anchor:new V(Ia,el,zo,0,void 0),up:bn.upVector(Aa,Zr.x,Zr.y)}}(function(Ia,el,zo,Lc,Mu,ou,um,Td,gu,Qc,id,lh,If,Ud,od,Lh,Gu,qd,hd,Bl,Xi,Md,lu,Jc,_d,Ep,zv,Rx,ya,Zy,Ci,Xg){const zm=Ia.addToLineVertexArray(el,Lc);let Dx,Wu,Sc,Ro,kl,xu,fa,Ao=0,pl=0,ed=0,ag=0,Wo=-1,q0=-1;const yh={};let uf=c.dF("");const Vd=zo?zo.anchor:el,yu=Rx!=="none";let B_=0,Bv=0;if(gu._unevaluatedLayout.getValue("text-radial-offset")===void 0){const Bm=gu.layout.get("text-offset").evaluate(Xi,{},_d);B_=Bm[0]*c.dg,Bv=Bm[1]*c.dg}else B_=gu.layout.get("text-radial-offset").evaluate(Xi,{},_d)*c.dg,Bv=it;if(Ia.allowVerticalPlacement&&Mu.vertical){const Bm=Mu.vertical;if(od)xu=Is(Bm),Td&&(fa=Is(Td));else{const vu=gu.layout.get("text-rotate").evaluate(Xi,{},_d)+90;Sc=Ss(Qc,Vd,el,id,lh,If,Bm,Ud,vu,Lh,Xg),Td&&(Ro=Ss(Qc,Vd,el,id,lh,If,Td,qd,vu,null,Ci))}}if(ou){const Bm=gu.layout.get("icon-rotate").evaluate(Xi,{},_d),vu=c.g6(ou,Bm,lu,yu,Md.iconScaleFactor),Rh=Td?c.g6(Td,Bm,lu,yu,Md.iconScaleFactor):void 0;Wu=Ss(Qc,Vd,el,id,lh,If,ou,qd,Bm,null,Zy);const vh=function(Qg,dh,Rc,Jg,F1,O1,z1,tj,sj){const $_=Qg.layers[0],Rk=$_.appearances;let Db=dh.length;if(Rc&&(Db=Math.max(Db,Rc.length)),Rk.length===0)return Db;const[$v,C3]=Jg.get("icon-size-scale-range"),Z2=c.b1(1,$v,C3);for(const rp of Rk)if(rp.hasLayoutProperty("icon-image")){const Dk=rt(Qg,$_,rp,F1,O1,z1,Z2,sj);Dk&&(Db=Math.max(Db,c.g8(Dk)))}return Db}(Ia,vu,Rh,gu.layout,Xi,_d,Ia.iconAtlasPositions,0,Jc);Ao=4*vh;const Ui=gu.layout.get("icon-size").evaluate(Xi,{},_d,Jc),hm=Md.compositeIconSizes?Md.compositeIconSizes[0].evaluate(Xi,{},_d,Jc):0,ch=Md.compositeIconSizes?Md.compositeIconSizes[1].evaluate(Xi,{},_d,Jc):0,np=c.g7(Ia.layerIds[0],Ia.iconSizeData,Ui,ou.imagePrimary.usvg?1:Md.iconScaleFactor,hm,ch);Ia.addSymbols(Ia.icon,vu,np,Bl,hd,Xi,void 0,zo,el,zm.lineStartIndex,zm.lineLength,-1,Jc,_d,Ep,zv,Ia.symbolInstances.length,vh),Wo=Ia.icon.placedSymbolArray.length-1,Rh&&(pl=4*vh,Ia.addSymbols(Ia.icon,Rh,np,Bl,hd,Xi,c.dt.vertical,zo,el,zm.lineStartIndex,zm.lineLength,-1,Jc,_d,Ep,zv,Ia.symbolInstances.length,vh),q0=Ia.icon.placedSymbolArray.length-1)}for(const Bm in Mu.horizontal){const vu=Bm,Rh=Mu.horizontal[vu];Dx||(uf=c.dF(Rh.text),od?kl=Is(Rh):Dx=Ss(Qc,Vd,el,id,lh,If,Rh,Ud,gu.layout.get("text-rotate").evaluate(Xi,{},_d),Lh,Xg));const vh=Rh.positionedLines.length===1;if(ed+=vt(Ia,zo,el,Rh,um,gu,od,Xi,Lh,zm,Mu.vertical?c.dt.horizontal:c.dt.horizontalOnly,vh?qe(Mu.horizontal):[vu],yh,Wo,Md,Jc,_d,Ia.symbolInstances.length,Ep),vh)break}Mu.vertical&&(ag+=vt(Ia,zo,el,Mu.vertical,um,gu,od,Xi,Lh,zm,c.dt.vertical,["vertical"],yh,q0,Md,Jc,_d,Ia.symbolInstances.length,Ep));let Fx=-1;const Rb=(Bm,vu)=>Bm?Math.max(Bm,vu):vu;Fx=Rb(kl,Fx),Fx=Rb(xu,Fx),Fx=Rb(fa,Fx);const ej=Fx>-1?1:0;Ia.glyphOffsetArray.length>=65535&&c.w("Too many glyphs being rendered in a tile. See https://github.com/mapbox/mapbox-gl-js/issues/2907"),Xi.sortKey!==void 0&&Ia.addToSortKeyRanges(Ia.symbolInstances.length,Xi.sortKey),Ia.symbolInstances.emplaceBack(el.x,el.y,Vd.x,Vd.y,Vd.z,yh.right>=0?yh.right:-1,yh.center>=0?yh.center:-1,yh.left>=0?yh.left:-1,yh.vertical>=0?yh.vertical:-1,Wo,q0,uf,Dx!==void 0?Dx:Ia.collisionBoxArray.length,Dx!==void 0?Dx+1:Ia.collisionBoxArray.length,Sc!==void 0?Sc:Ia.collisionBoxArray.length,Sc!==void 0?Sc+1:Ia.collisionBoxArray.length,Wu!==void 0?Wu:Ia.collisionBoxArray.length,Wu!==void 0?Wu+1:Ia.collisionBoxArray.length,Ro||Ia.collisionBoxArray.length,Ro?Ro+1:Ia.collisionBoxArray.length,id,ed,ag,Ao,pl,ej,0,B_,Bv,Fx,0,yu?1:0,ya)})(gt,Zr,xi,ra,ut,jt,zt,Rt,gt.layers[0],gt.collisionBoxArray,We.index,We.sourceLayerIndex,gt.index,nl,br,Ns,0,Il,iu,sr,We,Wt,Ps,fn,xn,Pn,or,tr,Qr,Va,Je,Ht)};if(vr==="line")for(const ra of c.dc(We.geometry,0,0,c.a6,c.a6)){const Zr=ne(ra,po,Ed,ut.vertical||to,jt,Na,ql,gt.overscaling,c.a6);for(const Aa of Zr)to&&Ys(gt,to.text,Ut,Aa)||ar(ra,Aa,xn)}else if(vr==="line-center"){for(const ra of We.geometry)if(ra.length>1){const Zr=ie(ra,Ed,ut.vertical||to,jt,Na,ql);Zr&&ar(ra,Zr,xn)}}else if(We.type==="Polygon")for(const ra of c.g4(We.geometry,0)){const Zr=je(ra,16);ar(ra[0],new V(Zr.x,Zr.y,0,0,void 0),xn)}else if(We.type==="LineString")for(const ra of We.geometry)ar(ra,new V(ra[0].x,ra[0].y,0,0,void 0),xn);else if(We.type==="Point")for(const ra of We.geometry)for(const Zr of ra)ar([Zr],new V(Zr.x,Zr.y,0,0,void 0),xn)}function vt(gt,We,ut,jt,Rt,zt,Wt,ws,Ms,Ns,Ps,fn,xn,bn,Pn,or,tr,sr,br){const vr=c.g9(ut,jt,Ms,zt,Wt,ws,Rt,gt.allowVerticalPlacement,void 0,Pn.textScaleFactor),Va=zt.layout.get("text-size").evaluate(ws,{},tr),Je=Pn.compositeTextSizes?Pn.compositeTextSizes[0].evaluate(ws,{},tr):0,Ht=Pn.compositeTextSizes?Pn.compositeTextSizes[1].evaluate(ws,{},tr):0,Ts=c.g7(gt.layerIds[0],gt.textSizeData,Va,Pn.textScaleFactor,Je,Ht);gt.addSymbols(gt.text,vr,Ts,Ms,Wt,ws,Ps,We,ut,Ns.lineStartIndex,Ns.lineLength,bn,or,tr,br,!1,sr,vr.length);for(const ln of fn)xn[ln]=gt.text.placedSymbolArray.length-1;return 4*vr.length}function gs(gt){for(const We in gt)return gt[We];return null}function Ss(gt,We,ut,jt,Rt,zt,Wt,ws,Ms,Ns,Ps){let fn,xn,bn,Pn;if(fn=Ps?Ps.top:Wt.top,xn=Ps?Ps.bottom:Wt.bottom,bn=Ps?Ps.left:Wt.left,Pn=Ps?Ps.right:Wt.right,ze(Wt)&&Wt.collisionPadding){const or=Wt.collisionPadding;bn-=or[0],fn-=or[1],Pn+=or[2],xn+=or[3]}if(Ms){const or=new c.P(bn,fn),tr=new c.P(Pn,fn),sr=new c.P(bn,xn),br=new c.P(Pn,xn),vr=c.av(Ms);let Va=new c.P(0,0);Ns&&(Va=new c.P(Ns[0],Ns[1])),or._rotateAround(vr,Va),tr._rotateAround(vr,Va),sr._rotateAround(vr,Va),br._rotateAround(vr,Va),bn=Math.min(or.x,tr.x,sr.x,br.x),Pn=Math.max(or.x,tr.x,sr.x,br.x),fn=Math.min(or.y,tr.y,sr.y,br.y),xn=Math.max(or.y,tr.y,sr.y,br.y)}return gt.emplaceBack(We.x,We.y,We.z,ut.x,ut.y,bn,fn,Pn,xn,ws,jt,Rt,zt),gt.length-1}function Is(gt){ze(gt)&>.collisionPadding&&(gt.top-=gt.collisionPadding[1],gt.bottom+=gt.collisionPadding[3]);const We=gt.bottom-gt.top;return We>0?Math.max(10,We):null}function Ys(gt,We,ut,jt){const Rt=gt.compareText;if(We in Rt){const zt=Rt[We];for(let Wt=zt.length-1;Wt>=0;Wt--)if(jt.dist(zt[Wt])=We.maxzoom||We.visibility==="none")}parse(We,ut,jt,Rt,zt,Wt){this._parseAfterHD(We,ut,jt,Rt,zt,Wt)}_parseAfterHD(We,ut,jt,Rt,zt,Wt){let ws;if(this.status="parsing",this.data=We,this.renderSourceType===c.bS.HdRoadCoverage){const tr=We.layers[c.bV];ws=tr&&m?m(tr):[]}this.collisionBoxArray=new c.bu;const Ms=new c.gc(Object.keys(We.layers).sort()),Ns=new c.fG(this.tileID,this.promoteId);Ns.bucketLayerIDs=[];const Ps={},fn=new c.gd(256,256),xn={featureIndex:Ns,iconDependencies:new Map,patternDependencies:new Map,glyphDependencies:{},lineAtlas:fn,availableImages:jt,brightness:this.brightness,scaleFactor:this.scaleFactor,showElevationIdDebug:this.showElevationIdDebug,elevationFeatures:void 0,elevationParams:this.elevation,crossSourceElevationEnabled:this.crossSourceElevationEnabled,terrainEnabled:this.terrainEnabled,activeFloors:void 0};this.indoor&&g&&(xn.activeFloors=g(We,this.indoor,zt,this.canonical));const bn=[],Pn=ut.familiesBySource[this.source];if(this.deferRoadStructure=!1,this.renderSourceType!==c.bS.HdRoadCoverage&&this.frcCoverage!=null&&!this.frcCoverage.resolved&&this.frcCoverage.frcMask===null){for(const tr in Pn)if(c.ge&&c.ge(this.frcCoverage.sourceLayers,this.source,tr)){this.deferRoadStructure=!0;break}}for(const tr in Pn){const sr=We.layers[tr];if(!sr)continue;let br=!1,vr=!1,Va=!1,Je=!1;for(const rr of Pn[tr])rr[0].type==="symbol"?br=!0:rr[0].type==="fill-extrusion"?vr=!0:Va=!0,rr[0].is3D()&&rr[0].type!=="model"&&(Je=!0);if(this.extraShadowCaster&&!Je||this.renderSourceType===c.bS.Symbol&&!br||this.renderSourceType===c.bS.FillExtrusion&&!vr||(this.renderSourceType===c.bS.Other||this.renderSourceType===c.bS.HdRoadCoverage)&&!Va)continue;const Ht=this.frcCoverage!=null&&!!c.ge&&c.ge(this.frcCoverage.sourceLayers,this.source,tr);if(this.deferRoadStructure&&Ht)continue;sr.version===1&&c.w(`Vector tile source "${this.source}" layer "${tr}" does not use vector tile spec v2 and therefore may have some rendering errors.`);const Ts=Ms.encode(tr),ln=[],tn=this.localizableLayerIds&&this.localizableLayerIds.has(tr);let nr=!1;for(let rr=0,Qr=0;rrc.m(Na.id,Na.scope)));const $a=()=>{gn(rr,this.zoom,xn.brightness,jt,this.worldview,xn.activeFloors);const Na=Ps[Qr.id]=Qr.createBucket({index:na,layers:rr,zoom:this.zoom,lut:this.lut,canonical:this.canonical,pixelRatio:this.pixelRatio,overscaling:this.overscaling,collisionBoxArray:this.collisionBoxArray,sourceLayerIndex:Ts,sourceLayerName:tr,sourceID:this.source,projection:this.projection.spec,tessellationStep:this.tessellationStep,styleDefinedModelURLs:Rt,worldview:this.worldview,localizable:tn,availableImages:jt,maxUniformBufferBindings:this.maxUniformBufferBindings,maxUniformBlockSizeDwords:this.maxUniformBlockSizeDwords});E&&E(Na,this.frcCoverage?this.frcCoverage.sourceLayers:null),Na.populate(ln,xn,this.tileID.canonical,this.tileTransform)};Qr.mayUse("HD")||Qr.mayUse("Standard")?bn.push(Qr.prepare().then(()=>$a())):$a()}}const or=()=>{fn.trim();const tr=!(!xn.elevationFeatures||!xn.elevationFeatures.some(Qr=>Qr.heightRange.min<0));let sr,br,vr,Va,Je,Ht,Ts,ln=xn.elevationFeatures;this.crossSourceElevationEnabled&&u&&(ln=ln||u(We,this.canonical)||[]);const tn={type:"maybePrepare",renderSourceType:this.renderSourceType,zoom:this.zoom},nr=()=>{if(sr)return this.status="done",Wt(sr);if(this.extraShadowCaster){this.status="done";const Qr=Object.values(Ps).filter(na=>!na.isEmpty());Wt(null,{buckets:Qr,containsHdExt:kn(Qr),containsStandardExt:Ws(Qr),featureIndex:Ns,collisionBoxArray:null,hasTunnelGeometry:tr,glyphAtlasImage:null,lineAtlas:null,imageAtlas:null,brightness:xn.brightness,hasDeferredElevationFeatures:!!I&&I(Ps),parsedElevationFeatures:ln,glyphMap:null,iconMap:null,glyphPositions:null})}else if(br&&vr&&Va&&Ts){const na=new js(br),$a=new Map;for(const[La,to]of vr.entries()){const{imagePosition:xo}=c.g0(La,to,c.g1);$a.set(La,xo)}const Na={};for(const La in Ps){const to=Ps[La];if(to instanceof c.bv){gn(to.layers,this.zoom,xn.brightness,jt,this.worldview,xn.activeFloors);const xo=On(this.frcCoverage,this.source,to.layers[0].sourceLayer);Na[La]=Ke(to,br,na.positions,vr,$a,this.tileID.canonical,this.tileZoom,this.scaleFactor,this.pixelRatio,Je,this.worldview,jt,xo.frcMask,xo.polygons,xo.tileZoom,c.gf||null,f||null)}}Je.size||Ht.size?this.rasterizeTask=zt.sendCancelable("rasterizeImages",{scope:this.scope,iconTasks:Je,patternTasks:Ht},{},(La,to)=>{if(!La)for(const[xo,oo]of to.entries())vr.has(xo)&&vr.set(xo,Object.assign(vr.get(xo),{data:oo})),Va.has(xo)&&Va.set(xo,Object.assign(Va.get(xo),{data:oo}));rr(Na,na,void 0,Ts)}):rr(Na,na,void 0,Ts)}},rr=(Qr,na,$a,Na)=>{const La=vr.size>0||Va.size>0,to=Object.keys(Qr).length>0;if(!La&&!to){this.status="done";const oo=Object.values(Ps).filter(Lo=>!Lo.isEmpty());return void Wt(null,{buckets:oo,containsHdExt:kn(oo),containsStandardExt:Ws(oo),featureIndex:Ns,collisionBoxArray:this.collisionBoxArray,hasTunnelGeometry:tr,glyphAtlasImage:na.image,lineAtlas:fn,imageAtlas:null,brightness:xn.brightness,hasDeferredRoadStructure:this.deferRoadStructure,frcCoveragePolygons:ws,hasDeferredElevationFeatures:!!I&&I(Ps),parsedElevationFeatures:ln})}const xo=(oo,Lo)=>{for(const po in Ps){const nl=Ps[po];if(po in Qr)ys(nl,Qr[po],this.showCollisionBoxes,jt,this.tileID.canonical,this.tileZoom,this.projection,this.brightness,vr,Lo);else if(nl.hasPattern&&(nl instanceof c.bA||nl instanceof c.bB||nl instanceof c.aD)){gn(nl.layers,this.zoom,xn.brightness,jt,this.worldview,xn.activeFloors);const Il=Object.fromEntries(Lo.patternPositions);nl.addFeatures(xn,this.tileID.canonical,Il,jt,this.tileTransform,this.brightness)}}this.status="done";const ql=Object.values(Ps).filter(po=>!po.isEmpty());Wt(null,{buckets:ql,containsHdExt:kn(ql),containsStandardExt:Ws(ql),featureIndex:Ns,collisionBoxArray:this.collisionBoxArray,hasTunnelGeometry:tr,glyphAtlasImage:na.image,lineAtlas:fn,imageAtlas:oo,brightness:xn.brightness,hasDeferredRoadStructure:this.deferRoadStructure,frcCoveragePolygons:ws,hasDeferredElevationFeatures:!!I&&I(Ps),parsedElevationFeatures:ln})};if(La){const oo=new Map,Lo=c.gh(vr,oo),ql=c.gh(Va,oo),po=new c.gi(Lo,ql,Na,this.lut,this.scope,oo);zt.send("checkAtlasCache",{descriptor:po,scope:this.scope}).then(nl=>{let Il,Ed;if(nl)Il=new c.gj(nl.sourceHash),Ed=nl;else{const iu=new c.gk(vr,Va,this.lut,Na,this.scope);Il=iu,Ed=iu}xo(Il,Ed)}).catch(nl=>{nl.name!=="AbortError"&&c.w(`[Worker] Error checking atlas cache: ${nl.message}`);const Il=new c.gk(vr,Va,this.lut,Na,this.scope);xo(Il,Il)})}else xo(null,{iconPositions:new Map,patternPositions:new Map})};if(!this.extraShadowCaster){const Qr=c.gg(xn.glyphDependencies,Na=>Object.keys(Na).map(Number));Object.keys(Qr).length?zt.send("getGlyphs",{uid:this.uid,stacks:Qr},{metadata:tn}).then(Na=>{sr||(br=Na,nr())}).catch(Na=>{sr||(sr=Na,nr())}):br={},Ts=new Map;const na=Array.from(xn.iconDependencies.keys()).map(Na=>c.I.parse(Na)),$a=Array.from(xn.patternDependencies.keys()).map(Na=>c.I.parse(Na));na.length||$a.length?zt.send("getImages",{icons:na,patterns:$a,source:this.source,scope:this.scope,tileID:this.tileID},{metadata:tn}).then(Na=>{if(!sr){vr=new Map,Va=new Map,Je=this.updateImageMapAndGetImageTaskQueue(vr,Na.images,xn.iconDependencies),Ht=this.updateImageMapAndGetImageTaskQueue(Va,Na.images,xn.patternDependencies);for(const[La,to]of Na.versions.entries())Ts.set(La,to);nr()}}).catch(Na=>{sr||(sr=Na,nr())}):(vr=new Map,Va=new Map,Je=new Map,Ht=new Map)}h&&h({buckets:Ps,data:We,sourceLayerCoder:Ms,canonical:this.tileID.canonical,options:xn}),nr()};bn.length>0?Promise.allSettled(bn).then(or).catch(Wt):or()}updateParameters(We){this.scaleFactor=We.scaleFactor,this.showCollisionBoxes=We.showCollisionBoxes,this.showElevationIdDebug=We.showElevationIdDebug,this.projection=We.projection,this.brightness=We.brightness,this.tileTransform=c.bq(We.tileID.canonical,We.projection),this.extraShadowCaster=We.extraShadowCaster,this.lut=We.lut,this.worldview=We.worldview,this.indoor=We.indoor,this.frcCoverage=We.frcCoverage||null,this.elevation=We.elevation||null,this.crossSourceElevationEnabled=!!We.crossSourceElevationEnabled,this.terrainEnabled=!!We.terrainEnabled}updateImageMapAndGetImageTaskQueue(We,ut,jt){const Rt=new Map;for(const zt of ut.keys()){const Wt=jt.get(zt)||[];for(const ws of Wt){const Ms=ws.toString(),Ns=ut.get(ws.id.toString());Ns.usvg?Rt.has(Ms)||(Rt.set(Ms,ws),We.set(Ms,{...Ns})):We.set(Ms,Ns)}}return Rt}cancelRasterize(){this.rasterizeTask&&this.rasterizeTask.abort()}}function gn(gt,We,ut,jt,Rt,zt){const Wt=new c.aj(We,{brightness:ut,worldview:Rt,activeFloors:zt});for(const ws of gt)ws.recalculate(Wt,jt)}class As extends c.E{constructor({actor:We,layerIndex:ut,availableImages:jt,availableModels:Rt,isSpriteLoaded:zt,tileProvider:Wt,brightness:ws,maxUniformBufferBindings:Ms,maxUniformBlockSizeDwords:Ns}){super(),this.actor=We,this.layerIndex=ut,this.availableImages=jt,this.availableModels=Rt,this.loadVectorData=c.cH,this.tileProvider=Wt,this.loading={},this.loaded={},this.deduped=new c.cC(We.scheduler),this.isSpriteLoaded=zt,this.scheduler=We.scheduler,this.brightness=ws,this.maxUniformBufferBindings=Ms,this.maxUniformBlockSizeDwords=Ns}loadTileData(We,ut){if(!this.tileProvider)return this.loadVectorData(We,ut);const jt=new AbortController;return this.loadTileWithProvider(this.tileProvider,We,jt,ut),()=>jt.abort()}async loadTileWithProvider(We,ut,jt,Rt){const{z:zt,x:Wt,y:ws}=ut.tileID.canonical;try{const Ms=await We.loadTile({z:zt,x:Wt,y:ws},{request:ut.request,signal:jt.signal});if(jt.signal.aborted)return;if(Ms==null){const Ps=new Error("Tile not found");return Ps.status=404,Rt(Ps)}if(Ms.data==null)return Rt(null,null);if(Ms.data instanceof ImageBitmap)return Rt(new Error("Vector tiles require ArrayBuffer data"));const Ns=new Headers;Ms.expires&&Ns.set("expires",Ms.expires),Ms.cacheControl&&Ns.set("cache-control",Ms.cacheControl),Rt(null,{rawData:Ms.data,headers:Ns})}catch(Ms){if(jt.signal.aborted)return;Rt(Ms instanceof Error?Ms:new Error(String(Ms)))}}_fetchTileData(We,ut){return new Promise((jt,Rt)=>{We.abort=this.loadTileData(ut,(zt,Wt)=>{zt?Rt(zt):jt(Wt)})})}async _parse(We,ut){const jt=!this.isSpriteLoaded;return jt&&await this.once("isSpriteLoaded"),new Promise((Rt,zt)=>{const Wt=()=>We.parse(We.vectorTile,this.layerIndex,this.availableImages,this.availableModels,this.actor,(ws,Ms)=>{ws?zt(ws):Rt(Ms)});jt&&this.scheduler?this.scheduler.add(Wt,{type:"parseTile",renderSourceType:ut.renderSourceType,zoom:ut.tileZoom}):Wt()})}async loadTile(We){const ut=We.uid,jt=We&&We.request,Rt=jt&&jt.collectResourceTiming,zt=this.loading[ut]=new ds(We);zt.maxUniformBufferBindings=this.maxUniformBufferBindings,zt.maxUniformBlockSizeDwords=this.maxUniformBlockSizeDwords;const Wt=(Pn,or)=>{const tr=zt.reloadCallback;tr&&(delete zt.reloadCallback,Pn||!or?tr(Pn,null):zt.parse(zt.vectorTile,this.layerIndex,this.availableImages,this.availableModels,this.actor,tr))};let ws,Ms;try{ws=await this._fetchTileData(zt,We)}catch(Pn){Ms=Pn}const Ns=!this.loading[ut];if(delete this.loading[ut],zt.cancelRasterize(),Ms||Ns||!ws){if(zt.status="done",Ns||(this.loaded[ut]=zt),Ms)throw Ms;return null}const Ps=ws.rawData;let fn;zt.vectorTile=ws.vectorTile||new c.gl(new c.c$(Ps)),this.loaded=this.loaded||{},this.loaded[ut]=zt;try{fn=await this._parse(zt,We)}catch(Pn){throw Wt(Pn),Pn}if(!fn)return Wt(null,null),null;const xn={};if(Rt){const Pn=d(jt);Pn.length>0&&(xn.resourceTiming=JSON.parse(JSON.stringify(Pn)))}const bn={rawTileData:Ps.slice(0),headers:ws.headers,...fn,...xn};return Wt(null,fn),bn}async reloadTile(We){const ut=this.loaded,jt=We.uid;if(ut&&ut[jt])return new Promise((Rt,zt)=>{const Wt=ut[jt];Wt.updateParameters(We);const ws=(Ms,Ns)=>{const Ps=Wt.reloadCallback;Ps&&(delete Wt.reloadCallback,Wt.parse(Wt.vectorTile,this.layerIndex,this.availableImages,this.availableModels,this.actor,Ps)),Ms?zt(Ms):Rt(Ns)};Wt.status==="parsing"?Wt.reloadCallback=ws:Wt.status==="done"?Wt.vectorTile?Wt.parse(Wt.vectorTile,this.layerIndex,this.availableImages,this.availableModels,this.actor,ws):ws():Rt(void 0)})}abortTile(We){const ut=We.uid,jt=this.loading[ut];jt&&(jt.abort&&jt.abort(),delete this.loading[ut])}removeTile(We){const ut=this.loaded,jt=We.uid;ut&&ut[jt]&&delete ut[jt]}}class hr{constructor(We){this.tileProvider=We.tileProvider,this.loading={}}async loadTile(We){const ut=We.uid,jt=new AbortController;if(this.loading[ut]={cancel:()=>jt.abort()},this.tileProvider)return this.loadTileWithProvider(this.tileProvider,ut,We,jt);try{const{data:Rt,headers:zt}=await c.d0(We.request,jt.signal);if(!Rt)return null;const Wt=await this.decodeTile(ut,Rt,We.encoding);return Wt.headers=zt,Wt}catch(Rt){if(jt.signal.aborted)return null;throw Rt}finally{delete this.loading[ut]}}async decodeTile(We,ut,jt){const Rt=ut instanceof ImageBitmap?ut:await createImageBitmap(new Blob([new Uint8Array(ut)],{type:"image/png"})),zt=1-(Rt.width-c.gm(Rt.width))/2,Wt=zt<1,ws=this.getImageData(Rt,zt);return Rt.close(),{dem:new c.gn(We,ws,jt,Wt),borderReady:Wt}}async loadTileWithProvider(We,ut,jt,Rt){const{z:zt,x:Wt,y:ws}=jt.tileID.canonical;try{const Ms=await We.loadTile({z:zt,x:Wt,y:ws},{request:jt.request,signal:Rt.signal});if(Rt.signal.aborted)return null;if(Ms==null){const fn=new Error("Tile not found");throw fn.status=404,fn}if(Ms.data==null)return null;const Ns=await this.decodeTile(ut,Ms.data,jt.encoding);if(Rt.signal.aborted)return null;const Ps=new Headers;return Ms.expires&&Ps.set("expires",Ms.expires),Ms.cacheControl&&Ps.set("cache-control",Ms.cacheControl),Ns.headers=Ps,Ns}catch(Ms){if(Rt.signal.aborted)return null;throw Ms}finally{delete this.loading[ut]}}async reloadTile(We){}abortTile(We){const ut=We.uid,jt=this.loading[ut];jt&&(jt.cancel(),delete this.loading[ut])}removeTile(We){}getImageData(We,ut){this.offscreenCanvas&&this.offscreenCanvasContext||(this.offscreenCanvas=new OffscreenCanvas(We.width,We.height),this.offscreenCanvasContext=this.offscreenCanvas.getContext("2d",{willReadFrequently:!0})),this.offscreenCanvas.width=We.width,this.offscreenCanvas.height=We.height,this.offscreenCanvasContext.drawImage(We,0,0,We.width,We.height);const jt=this.offscreenCanvasContext.getImageData(-ut,-ut,We.width+2*ut,We.height+2*ut);return this.offscreenCanvasContext.clearRect(0,0,this.offscreenCanvas.width,this.offscreenCanvas.height),jt}}const Er=c.go.prototype.toGeoJSON;class qn{constructor(We){this._feature=We,this.extent=c.a6,this.type=We.type===4?1:We.type,this.properties=We.tags||{},"id"in We&&!isNaN(We.id)&&(this.id=parseInt(We.id,10))}loadGeometry(){const We=this._feature,ut=[];if(We.type===4)ut.push([new c.P(We.x,We.y)]);else if(We.type===1)for(let jt=0;jt(zt-vn)/Rt&&jt>(Wt-vn)/Rt}function Or(gt){const{id:We,geometry:ut,properties:jt}=gt;if(ut.type==="GeometryCollection")throw new Error("GeometryCollection not supported in dynamic mode.");const{type:Rt,coordinates:zt}=ut,Wt={id:We,type:1,geometry:[],tags:jt,minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0},ws=Wt.geometry;if(Rt==="Point")ca(zt,ws,Wt);else if(Rt==="MultiPoint")for(const Ms of zt)ca(Ms,ws,Wt);else if(Rt==="LineString")Wt.type=2,Jn(zt,ws,Wt);else if(Rt==="MultiLineString")Wt.type=2,Sr(zt,ws,Wt);else if(Rt==="Polygon")Wt.type=3,Sr(zt,ws,Wt,!0);else{if(Rt!=="MultiPolygon")throw new Error("Input data is not a valid GeoJSON object.");Wt.type=3;for(const Ms of zt)Sr(Ms,ws,Wt,!0)}return Wt}function ca([gt,We],ut,jt){const Rt=c.a7(gt);let zt=c.a8(We);zt=zt<0?0:zt>1?1:zt,ut.push(Rt,zt),jt.minX=Math.min(jt.minX,Rt),jt.minY=Math.min(jt.minY,zt),jt.maxX=Math.max(jt.maxX,Rt),jt.maxY=Math.max(jt.maxY,zt)}function Jn(gt,We,ut,jt=!1,Rt=!1){const zt=[];for(const Wt of gt)ca(Wt,zt,ut);We.push(zt),jt&&function(Wt,ws){let Ms=0;for(let Ns=0,Ps=Wt.length,fn=Ps-2;Ns0===ws)for(let Ns=0,Ps=Wt.length;Ns=Wt&&fn>=Wt||(Ns>=Wt?(Ps+=Math.round(Pn*((Wt-Ns)/bn)),Ns=Wt):fn>=Wt&&(xn=Ps+Math.round(Pn*((Wt-Ns)/bn)),fn=Wt),Ps>=Wt&&xn>=Wt||(Ps>=Wt?(Ns+=Math.round(bn*((Wt-Ps)/Pn)),Ps=Wt):xn>=Wt&&(fn=Ns+Math.round(bn*((Wt-Ps)/Pn)),xn=Wt),ws&&Ns===ws.at(-2)&&Ps===ws.at(-1)||(ws=[Ns,Ps],Rt.push(ws)),ws.push(fn,xn)))))}}function ii(gt,We,ut,jt,Rt){const zt=(ut-vn)/We,Wt=(jt-vn)/We,ws=(ut+1+vn)/We,Ms=(jt+1+vn)/We;function Ns(xn,bn){let Pn=0;return xnws&&(Pn|=2),bnMs&&(Pn|=8),Pn}let Ps=[];for(let xn=1;xn<=8;xn*=2){let bn=gt.at(-2),Pn=gt.at(-1),or=!(Ns(bn,Pn)&xn);for(let tr=0;tr>31}function Pc(gt,We){if(gt.type===4)return We.writeVarint(Ya(1,1)),We.writeVarint(ho(gt.x)),void We.writeVarint(ho(gt.y));let ut=0,jt=0;if(gt.type===1){const{geometry:Rt}=gt;We.writeVarint(Ya(1,Rt.length>>1));for(let zt=0;zt>1)-(Rt?1:0);for(let ws=0;wsgt},Ho=1073741824,ti=1/Ho,Xr=gt=>(gt-.5)*Ho,Eo=gt=>gt*ti+.5;class Ph{constructor(We){const ut=this.options=Object.assign(Object.create(Nl),We);ut.maxZoom=Math.min(ut.maxZoom,30),ut.minZoom=Math.min(ut.minZoom,ut.maxZoom),this.trees=new Array(ut.maxZoom+1),this.stride=ut.reduce?7:6,this.clusterProps=[]}load(We){const{log:ut,minZoom:jt,maxZoom:Rt}=this.options;ut&&console.time("total time");const zt=Rt+1,Wt=`z${zt}: ${We.length} points`;ut&&console.time(Wt);const ws=this.stride;let Ms=We.length;for(const br of We){const vr=br.geometry;vr&&vr.type==="MultiPoint"&&(Ms+=vr.coordinates.length-1)}this.numPoints=Ms;const Ns=this.props=new Array(Ms),Ps=this.coords=new Float64Array(2*Ms);let fn=null;const xn=new Int32Array(Ms*ws);let bn=0,Pn=0;for(const br of We){const vr=br.geometry;if(!vr){Pn++;continue}const Va=vr.coordinates,Je=vr.type==="MultiPoint";for(let Ht=0,Ts=Je?Va.length:1;Ht=jt;br--){const vr=performance.now(),Va=sr||new Int32Array(tr*ws);sr=null;const Je=this._cluster(or,tr,br,Va);Je===tr?(this.trees[br]=this.trees[br+1],sr=Va):(this.trees[br]=this._createTree(Va,Je),or=Va,tr=Je),ut&&console.log(`z${br}: ${this.trees[br].numItems} clusters in ${(performance.now()-vr).toFixed(2)}ms`)}return ut&&console.timeEnd("total time"),this}getClusters(We,ut){let jt=((We[0]+180)%360+360)%360-180;const Rt=Math.max(-90,Math.min(90,We[1]));let zt=We[2]===180?180:((We[2]+180)%360+360)%360-180;const Wt=Math.max(-90,Math.min(90,We[3]));if(We[2]-We[0]>=360)jt=-180,zt=180;else if(jt>zt){const fn=this.getClusters([jt,Rt,180,Wt],ut),xn=this.getClusters([-180,Rt,zt,Wt],ut);return fn.concat(xn)}const ws=this.trees[this._limitZoom(ut)],Ms=ws.range(Xr(ao(jt)),Xr(ta(Wt)),Xr(ao(zt)),Xr(ta(Rt))),Ns=ws.data,Ps=[];for(const fn of Ms)Ps.push(this._featureJSON(Ns,this.stride*fn));return Ps}getChildren(We){const ut=this._getOriginId(We),jt=this._getOriginZoom(We),Rt="No cluster with the specified id.",zt=this.trees[jt];if(!zt)throw new Error(Rt);const Wt=zt.data;if(ut>=zt.numItems)throw new Error(Rt);const ws=this.options.radius/(this.options.extent*Math.pow(2,jt-1)),Ms=zt.within(Wt[ut*this.stride],Wt[ut*this.stride+1],ws*Ho),Ns=[];for(const Ps of Ms){const fn=Ps*this.stride;Wt[fn+4]===We&&Ns.push(this._featureJSON(Wt,fn))}if(Ns.length===0)throw new Error(Rt);return Ns}getLeaves(We,ut,jt){const Rt=[];return this._appendLeaves(Rt,We,ut=ut||10,jt=jt||0,0),Rt}getTile(We,ut,jt){return this._getTile(We,ut,jt,!1)}getTileRaw(We,ut,jt){return this._getTile(We,ut,jt,!0)}_getTile(We,ut,jt,Rt){const zt=this.trees[this._limitZoom(We)],Wt=Math.pow(2,We),{extent:ws,radius:Ms}=this.options,Ns=Ms/ws,Ps=Xr((jt-Ns)/Wt),fn=Xr((jt+1+Ns)/Wt),xn={features:[]};return this._addTileFeatures(zt.range(Xr((ut-Ns)/Wt),Ps,Xr((ut+1+Ns)/Wt),fn),zt.data,ut,jt,Wt,xn,Rt),ut===0&&this._addTileFeatures(zt.range(Xr(1-Ns/Wt),Ps,Xr(1),fn),zt.data,Wt,jt,Wt,xn,Rt),ut===Wt-1&&this._addTileFeatures(zt.range(Xr(0),Ps,Xr(Ns/Wt),fn),zt.data,-1,jt,Wt,xn,Rt),xn.features.length?xn:null}getClusterExpansionZoom(We){let ut=this._getOriginZoom(We)-1;for(;ut<=this.options.maxZoom;){const jt=this.getChildren(We);if(ut++,jt.length!==1)break;We=jt[0].properties.cluster_id}return ut}_appendLeaves(We,ut,jt,Rt,zt){const Wt=this.getChildren(ut);for(const ws of Wt){const Ms=ws.properties;if(Ms&&Ms.cluster?zt+Ms.point_count<=Rt?zt+=Ms.point_count:zt=this._appendLeaves(We,Ms.cluster_id,jt,Rt,zt):zt1;let fn,xn,bn;if(Ps)fn=ih(ut,Ns,this.clusterProps),xn=Eo(ut[Ns]),bn=Eo(ut[Ns+1]);else{const vr=ut[Ns+3];fn=this.props[vr],xn=this.coords[2*vr],bn=this.coords[2*vr+1]}const Pn=Math.round(this.options.extent*(xn*zt-jt)),or=Math.round(this.options.extent*(bn*zt-Rt)),tr=ws?{type:4,x:Pn,y:or,tags:fn}:{type:1,geometry:[[Pn,or]],tags:fn},sr=ut[Ns+3],br=Ps||this.options.generateId?sr:this.ids?this.ids[sr]:void 0;br!==void 0&&(tr.id=br),Wt.features.push(tr)}}_limitZoom(We){return Math.max(this.options.minZoom,Math.min(Math.floor(+We),this.options.maxZoom+1))}_cluster(We,ut,jt,Rt){const{radius:zt,extent:Wt,reduce:ws,minPoints:Ms,maxZoom:Ns}=this.options,Ps=zt/(Wt*(1<jt&&(Ht+=We[ln+5])}if(Ht>Je&&Ht>=Ms){let Ts,ln=br*Je,tn=vr*Je,nr=-1;const rr=(sr/bn<<5)+(jt+1)+this.numPoints;for(let Qr=0;Qr1)for(let Ts=0;Ts>5}_getOriginZoom(We){return(We-this.numPoints)%32}_featureJSON(We,ut){const jt=We[ut+3],Rt=We[ut+5]>1,zt=Rt?jt:this.ids?this.ids[jt]:void 0,Wt={type:"Feature",properties:Rt?ih(We,ut,this.clusterProps):this.props[jt],geometry:{type:"Point",coordinates:Rt?[xc(Eo(We[ut])),fl(Eo(We[ut+1]))]:[xc(this.coords[2*jt]),fl(this.coords[2*jt+1])]}};return zt!==void 0&&(Wt.id=zt),Wt}_map(We,ut,jt){if(We[ut+5]>1){const Wt=this.clusterProps[We[ut+6]];return jt?Object.assign({},Wt):Wt}const Rt=this.props[We[ut+3]],zt=this.options.map(Rt);return jt&&zt===Rt?Object.assign({},zt):zt}}function ih(gt,We,ut){const jt=gt[We+5],Rt=jt>=1e4?`${Math.round(jt/1e3)}k`:jt>=1e3?Math.round(jt/100)/10+"k":jt,zt=gt[We+6],Wt=zt===-1?{}:Object.assign({},ut[zt]);return Object.assign(Wt,{cluster:!0,cluster_id:gt[We+3],point_count:jt,point_count_abbreviated:Rt})}function ao(gt){return gt/360+.5}function ta(gt){const We=Math.sin(gt*Math.PI/180),ut=.5-.25*Math.log((1+We)/(1-We))/Math.PI;return ut<0?0:ut>1?1:ut}function xc(gt){return 360*(gt-.5)}function fl(gt){const We=(180-360*gt)*Math.PI/180;return 360*Math.atan(Math.exp(We))/Math.PI-90}const Co=2147483647;function pu(gt,We,ut,jt){return{id:gt,type:4,x:We,y:ut,tags:jt}}function nc(gt,We,ut,jt){const Rt={id:gt,type:We,geometry:ut,tags:jt,minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0};if(We===1)ad(Rt,ut,0,ut.length);else{const zt=We===3;for(let Wt=0;Wt=0)&&ad(Rt,ut,ws,Ms),Wt=Ms}}return Rt}function ad(gt,We,ut,jt){for(let Rt=ut;Rtgt.maxX&&(gt.maxX=zt),Wt>gt.maxY&&(gt.maxY=Wt)}}function zr(gt,We,ut,jt){let Rt=jt;const zt=We+(ut-We>>1);let Wt,ws=ut-We;const Ms=gt[We],Ns=gt[We+1],Ps=gt[ut],fn=gt[ut+1];for(let xn=We+3;xnRt)Wt=xn,Rt=bn;else if(bn===Rt){const Pn=Math.abs(xn-zt);Pnjt){const xn=Wt;xn-We>3&&zr(gt,We,xn,jt),gt[xn+2]=Math.min(Math.sqrt(Rt),Co),ut-xn>3&&zr(gt,xn,ut,jt)}}function Hi(gt,We,ut,jt,Rt,zt){let Wt=Rt-ut,ws=zt-jt;if(Wt!==0||ws!==0){const Ms=((gt-ut)*Wt+(We-jt)*ws)/(Wt*Wt+ws*ws);Ms>1?(ut=Rt,jt=zt):Ms>0&&(ut+=Wt*Ms,jt+=ws*Ms)}return Wt=gt-ut,ws=We-jt,Wt*Wt+ws*ws}const Bc="Input data is not a valid GeoJSON object.";function $c(gt,We,ut,jt){var Pn;const Rt=We.geometry;if(!Rt)return;const zt=Rt.type==="GeometryCollection"?Rt.geometries:Rt.coordinates;if(!zt)throw new Error(Bc);if(!zt.length)return;const Wt=ut.tolerance*ut.worldScale/((1<0&&(We+=2+3*ut.length);return We}let Ul=0;function rg(gt,We,ut,jt,Rt,zt,Wt){const ws=nc(We,ut,jt,Rt);ut===2&&zt.lineMetrics&&(ws.start=0,ws.end=ws.size=Wt),gt.push(ws)}function Lx(gt,We,ut,jt,Rt,zt){const Wt=new zt.CoordArray(2+3*ut.length);Yo(Wt,0,ut,Rt,!1,!1,zt.worldScale,zt.originShift,zt.useInt32),rg(gt,We,2,Wt,jt,zt,Ul)}function Yo(gt,We,ut,jt,Rt,zt,Wt,ws,Ms){if(ut.length===0)return We;const Ns=We,Ps=We+=2;let fn=0,xn=0,bn=0;for(let tr=0;tr0)if(Rt)bn+=(fn*br-sr*xn)/2;else{const vr=sr-fn,Va=br-xn;bn+=Math.sqrt(vr*vr+Va*Va)}fn=sr,xn=br}const Pn=We;if(Rt&&(zt&&bn<0||!zt&&bn>=0)){const tr=Pn-Ps;for(let sr=0;sr1?1:Rt)-ut)*We}function Xc(gt,We,ut,jt,Rt,zt,Wt){if(Rt>=We&&zt=ut)return null;const ws=Wt.lineMetrics,Ms=Wt.CoordArray;let Ns=null;for(let Ps=0;Ps=We&&tr=We&&or=ut?Ns===null&&(Ns=gt.slice(0,Ps)):(Ns===null&&(Ns=gt.slice(0,Ps)),xn!==1?Xa(bn,xn,We,ut,jt,fn,Ns,ws,Ms):_s(bn,We,ut,jt,fn,Ns,Ms))}return Ns===null?gt:Ns.length?Ns:null}function _s(gt,We,ut,jt,Rt,zt,Wt){let ws=0;for(let Ps=0;Ps=We&>[Ps+jt]=We&>[Ps+jt]=jt&&(Ns++,Ps++):bn>Rt?Pn<=Rt&&(Ns++,Ps++):Ns++,Pn=jt&&(Ns++,Ps++,or=!0),Pn>Rt&&bn<=Rt&&(Ns++,Ps++,or=!0),!Wt&&or&&(Ns>0&&(Ms+=Ns,ws++),Ns=0)}const fn=gt[ut-3+zt];return fn>=jt&&fn<=Rt&&Ns++,Wt&&Ns>=2&&Ps>=1&&Ns++,Ns>0&&(Ms+=Ns,ws++),3*Ms+2*ws}function Ba(gt,We,ut,jt,Rt,zt,Wt,ws,Ms,Ns,Ps,fn,xn){const bn=fn!==null;let Pn=zt;Rt[zt]=0,Rt[zt+1]=jt;let or=zt+=2,tr=xn,sr=tr,br=0,vr=0;for(let nr=We;nr=Wt&&(vr=io(Rt,zt,rr,Qr,$a,Na,Wt,Ms,Ps),zt+=3,bn&&(sr=tr+br*vr)):La>ws?to<=ws&&(vr=io(Rt,zt,rr,Qr,$a,Na,ws,Ms,Ps),zt+=3,bn&&(sr=tr+br*vr)):(Rt[zt]=rr,Rt[zt+1]=Qr,Rt[zt+2]=na,zt+=3),to=Wt&&(vr=io(Rt,zt,rr,Qr,$a,Na,Wt,Ms,Ps),zt+=3,xo=!0),to>ws&&La<=ws&&(vr=io(Rt,zt,rr,Qr,$a,Na,ws,Ms,Ps),zt+=3,xo=!0),!Ns&&xo){const oo=(zt-or)/3;oo>0&&(Rt[Pn]=oo,bn&&fn.push(sr,tr+br*vr),Pn=zt,Rt[zt]=0,Rt[zt+1]=jt,or=zt+=2)}bn&&(tr+=br)}const Va=ut-3,Je=gt[Va],Ht=gt[Va+1],Ts=gt[Va+2],ln=Ms===0?Je:Ht;ln>=Wt&&ln<=ws&&(Rt[zt]=Je,Rt[zt+1]=Ht,Rt[zt+2]=Ts,zt+=3),Ns&&zt-or>=6&&(Rt[zt-3]!==Rt[or]||Rt[zt-2]!==Rt[or+1])&&(Rt[zt]=Rt[or],Rt[zt+1]=Rt[or+1],Rt[zt+2]=Rt[or+2],zt+=3);const tn=(zt-or)/3;return tn>0?(Rt[Pn]=tn,bn&&fn.push(sr,tr)):zt=Pn,zt}function io(gt,We,ut,jt,Rt,zt,Wt,ws,Ms){let Ns;if(ws===0){Ns=(Wt-ut)/(Rt-ut);const Ps=jt+(zt-jt)*Ns;gt[We]=Wt,gt[We+1]=Ms?Math.floor(Ps+.5):Ps}else{Ns=(Wt-jt)/(zt-jt);const Ps=ut+(Rt-ut)*Ns;gt[We]=Ms?Math.floor(Ps+.5):Ps,gt[We+1]=Wt}return gt[We+2]=Co,Ns}function ko(gt,We){const ut=[];for(const jt of gt){if(jt.type===4){ut.push(pu(jt.id,jt.x+We,jt.y,jt.tags));continue}const Rt=qi(jt.geometry,jt.type,We),zt=nc(jt.id,jt.type,Rt,jt.tags);jt.start!==void 0&&(zt.start=jt.start,zt.end=jt.end,zt.size=jt.size),ut.push(zt)}return ut}function qi(gt,We,ut){const jt=gt.slice();if(We===1)for(let Rt=0;Rtgt.maxX&&(gt.maxX=tr),sr>gt.maxY&&(gt.maxY=sr),gt.numPoints++,gt.numSimplified++;const br={x:Zo(tr,Rt,zt,ws,Ns,Ps),y:Zo(sr,Rt,Wt,ws,Ns,Ps),type:4,tags:We.tags||null};return We.id!==void 0&&(br.id=We.id),void gt.features.push(br)}const xn=We.geometry;let bn;if(We.minXgt.maxX&&(gt.maxX=We.maxX),We.maxY>gt.maxY&&(gt.maxY=We.maxY),fn===1){const tr=xn.length/3;bn=new Ms(2*tr);for(let sr=0,br=0;sr0?Math.max(0,tr/br):0,Pn.mapbox_clip_end=sr>=br?1:sr/br}const or={geometry:bn,type:fn,tags:Pn};We.id!==void 0&&(or.id=We.id),gt.features.push(or)}function Zg(gt,We,ut,jt,Rt,zt,Wt,ws,Ms,Ns,Ps,fn,xn,bn,Pn){const or=(jt-ut)/3;if(Math.abs(Rt)Wt&&tr++;zt.numPoints+=or,zt.numSimplified+=tr;const sr=new xn(2*tr);let br=0;for(let vr=ut;vrWt)&&(sr[br++]=Zo(We[vr],Ms,Ns,fn,bn,Pn),sr[br++]=Zo(We[vr+1],Ms,Ps,fn,bn,Pn));gt.push(sr)}const Ol={maxZoom:14,indexMaxZoom:5,indexMaxPoints:1e5,tolerance:3,extent:4096,buffer:64,lineMetrics:!1,promoteId:null,generateId:!1,debug:0};class zl{constructor(We,ut){const jt=this.options=Object.assign(Object.create(Ol),ut),Rt=jt.debug;if(Rt&&console.time("preprocess data"),jt.maxZoom<0||jt.maxZoom>24)throw new Error("maxZoom should be in the 0-24 range");if(jt.promoteId&&jt.generateId)throw new Error("promoteId and generateId cannot be used together.");const zt=(jt.extent+2*jt.buffer)*(1<1&&console.time("creation"),Pn=this.tiles[bn]=dm(We,ut,jt,Rt,Ps),this.tileCoords.push({z:ut,x:jt,y:Rt}),this.stats[ut]=(this.stats[ut]||0)+1,this.total++,fn>1&&(console.log(`tile z${ut}-${jt}-${Rt} (features: ${Pn.numFeatures}, points: ${Pn.numPoints}, simplified: ${Pn.numSimplified})`),console.timeEnd("creation"))),Pn.source=We,zt==null){if(ut===Ps.indexMaxZoom||Pn.numPoints<=Ps.indexMaxPoints)continue}else{if(ut===Ps.maxZoom||ut===zt)continue;{const rr=zt-ut;if(jt!==Wt>>rr||Rt!==ws>>rr)continue}}if(Pn.source=null,We.length===0)continue;fn>1&&console.time("clipping");const or=Ps.worldScale,tr=Ps.originShift,sr=or/xn,br=.5*Ps.buffer*or/(xn*Ps.extent),vr=(jt/xn-tr)*or,Va=(Rt/xn-tr)*or;let Je=null,Ht=null,Ts=null,ln=null;const tn=Xc(We,vr-br,vr+sr/2+br,0,Pn.minX,Pn.maxX,Ps),nr=Xc(We,vr+sr/2-br,vr+sr+br,0,Pn.minX,Pn.maxX,Ps);tn&&(Je=Xc(tn,Va-br,Va+sr/2+br,1,Pn.minY,Pn.maxY,Ps),Ht=Xc(tn,Va+sr/2-br,Va+sr+br,1,Pn.minY,Pn.maxY,Ps)),nr&&(Ts=Xc(nr,Va-br,Va+sr/2+br,1,Pn.minY,Pn.maxY,Ps),ln=Xc(nr,Va+sr/2-br,Va+sr+br,1,Pn.minY,Pn.maxY,Ps)),fn>1&&console.timeEnd("clipping"),Ms.push(Je||[],Ht||[],Ts||[],ln||[]),Ns.push(ut+1,2*jt,2*Rt,ut+1,2*jt,2*Rt+1,ut+1,2*jt+1,2*Rt,ut+1,2*jt+1,2*Rt+1)}}getTile(We,ut,jt){const Rt=this.findTile(We,ut,jt);return Rt?function(zt){const Wt=[];for(const ws of zt.features){let Ms;Ms=ws.type===4?{type:1,geometry:[[ws.x,ws.y]],tags:ws.tags??null}:ws.type===1?{type:1,geometry:vy(ws.geometry),tags:ws.tags??null}:{type:ws.type,geometry:ws.geometry.map(vy),tags:ws.tags??null},ws.id!=null&&(Ms.id=ws.id),Wt.push(Ms)}return{features:Wt}}(Rt):null}getTileRaw(We,ut,jt){const Rt=this.findTile(We,ut,jt);return Rt?{features:Rt.features}:null}findTile(We,ut,jt){const Rt=this.options.debug;if((We=+We)<0||We>24)return null;const zt=1<1&&console.log("drilling down to z%d-%d-%d",We,ut,jt);let ws,Ms=We,Ns=ut,Ps=jt;for(;!ws&&Ms>0;)Ms--,Ns>>=1,Ps>>=1,ws=this.tiles[Xd(Ms,Ns,Ps)];return ws&&ws.source?(Rt>1&&(console.log("found parent tile z%d-%d-%d",Ms,Ns,Ps),console.time("drilling down")),this.splitTile(ws.source,Ms,Ns,Ps,We,ut,jt),Rt>1&&console.timeEnd("drilling down"),this.tiles[Wt]??null):null}}function vy(gt){const We=[];for(let ut=0;utNs.tags&&"3d_elevation_id"in Ns.tags&&"source"in Ns.tags&&Ns.tags.source==="elevation",zt=jt.features.filter(Rt);let Wt={_geojsonTileLayer:jt.features};zt.length>0&&(Wt={_geojsonTileLayer:jt.features.filter(Ns=>!Rt(Ns)),hd_road_elevation:zt});const ws=new Fn(Wt),Ms=function(Ns){const Ps=new c.gp;for(const fn of Object.keys(Ns))Ps.writeMessage(3,$i,{name:fn,features:Ns[fn]});return Ps.finish()}(Wt).buffer;We(null,{vectorTile:ws,rawData:Ms,headers:new Headers})}class df extends As{constructor(We){super(We),this.loadVectorData=Wh,this._dynamicIndex=new xs}async loadData(We){const ut=We&&We.request,jt=ut&&ut.collectResourceTiming;this._geoJSONIndex=null;let Rt=await new Promise((Wt,ws)=>{this.loadGeoJSON(We,(Ms,Ns)=>{Ms?ws(Ms):Wt(Ns)})});if(!Rt)return{};if(typeof Rt!="object")throw new Error(`Input data given to '${We.source}' is not a valid GeoJSON object.`);if(We.filter){const Wt=c.c(We.filter,{type:"boolean","property-type":"data-driven",overridable:!1,transition:!1});if(Wt.result==="error")throw new Error(Wt.value.map(ws=>`${ws.key}: ${ws.message}`).join(", "));Rt.features=Rt.features.filter(ws=>Wt.value.evaluate({zoom:0},ws))}We.dynamic?(Rt.type==="Feature"&&(Rt={type:"FeatureCollection",features:[Rt]}),We.append||(this._dynamicIndex.clear(),this.loaded={}),this._dynamicIndex.load(Rt.features,this.loaded),We.cluster&&(Rt.features=this._dynamicIndex.getFeatures())):this.loaded={},this._geoJSONIndex=We.cluster?new Ph(function({superclusterOptions:Wt,clusterProperties:ws}){if(!ws||!Wt)return Wt;const Ms={},Ns={},Ps={accumulated:null,zoom:0},fn={properties:null},xn=Object.keys(ws);for(const bn of xn){const[Pn,or]=ws[bn],tr=c.c(or),sr=c.c(typeof Pn=="string"?[Pn,["accumulated"],["get",bn]]:Pn);Ms[bn]=tr.value,Ns[bn]=sr.value}return Wt.map=bn=>{fn.properties=bn;const Pn={};for(const or of xn)Pn[or]=Ms[or].evaluate(Ps,fn);return Pn},Wt.reduce=(bn,Pn)=>{fn.properties=Pn;for(const or of xn)Ps.accumulated=bn[or],bn[or]=Ns[or].evaluate(Ps,fn)},Wt}(We)).load(Rt.features):We.dynamic?this._dynamicIndex:new zl(Rt,We.geojsonVtOptions);const zt={};if(jt){const Wt=d(ut);Wt&&(zt.resourceTiming={},zt.resourceTiming[We.source]=JSON.parse(JSON.stringify(Wt)))}return zt}async reloadTile(We){const ut=this.loaded;return ut&&ut[We.uid]?We.partial?void 0:super.reloadTile(We):this.loadTile(We)}loadGeoJSON(We,ut){if(We.request)c.g(We.request).then(({data:jt})=>ut(null,jt)).catch(jt=>ut(jt));else{if(typeof We.data!="string")return ut(new Error(`Input data given to '${We.source}' is not a valid GeoJSON object.`));setTimeout(()=>{try{return ut(null,JSON.parse(We.data))}catch{return ut(new Error(`Input data given to '${We.source}' is not a valid GeoJSON object.`))}},0)}}getClusterExpansionZoom(We){return this._geoJSONIndex.getClusterExpansionZoom(We.clusterId)}getClusterChildren(We){return this._geoJSONIndex.getChildren(We.clusterId)}getClusterLeaves(We){return this._geoJSONIndex.getLeaves(We.clusterId,We.limit,We.offset)}}c.c_.setPbf(c.c$);class Yy{constructor(We){this._mrt=new c.c_(We.partial?30:1/0),this._isHeaderLoaded=!1,this.uid=We.uid,this.tileID=We.tileID,this.source=We.source}async parse(We){const ut=this._mrt;this.status="parsing",this._entireBuffer=We,ut.parseHeader(We),this._isHeaderLoaded=!0;const jt=[];for(const Rt in ut.layers){const zt=ut.getLayer(Rt),Wt=zt.getDataRange(zt.getBandList()),ws=ut.createDecodingTask(Wt),Ms=We.slice(Wt.firstByte,Wt.lastByte+1);jt.push(c.c_.performDecoding(Ms,ws).then(Ns=>ws.complete(null,Ns)).catch(Ns=>ws.complete(Ns,null)))}return await Promise.allSettled(jt),ut}}class oh{constructor({actor:We}){this.actor=We,this.loading={},this.loaded={}}async loadTile(We){const ut=We.uid,jt=new AbortController,Rt=this.loading[ut]=new Yy(We);Rt.abort=()=>jt.abort();try{const{data:zt,headers:Wt}=await c.d0(We.request,jt.signal);return zt?(this.loaded[ut]=Rt,{mrt:await Rt.parse(zt),headers:Wt}):(Rt.status="done",this.loaded[ut]=Rt,null)}catch(zt){if(jt.signal.aborted)return null;throw Rt.status="done",this.loaded[ut]=Rt,zt}finally{delete this.loading[ut]}}async reloadTile(We){}abortTile(We){const ut=We.uid,jt=this.loading[ut];jt&&(jt.abort&&jt.abort(),delete this.loading[ut])}removeTile(We){const ut=We.uid;this.loaded[ut]&&delete this.loaded[ut]}async decodeRasterArray(We){return c.c_.performDecoding(We.buffer,We.task)}}class xh{constructor(We){this.self=We,this.actor=new c.ax(We,this),this.layerIndexes={},this.availableImages={},this.availableModels={},this.isSpriteLoaded={},this.rtlPluginParsingListeners=[],this.projections={},this.defaultProjection=c.gr({name:"mercator"}),this.workerSourceTypes={vector:As,geojson:df,"raster-dem":hr},this.workerSources={},this.self.registerRTLTextPlugin=ut=>{if(c.fN.isParsed())throw new Error("RTL text plugin already registered.");c.fN.setState({pluginStatus:c.gs.parsed,pluginURL:c.fN.getPluginURL()}),c.fN.applyArabicShaping=ut.applyArabicShaping,c.fN.processBidirectionalText=ut.processBidirectionalText,c.fN.processStyledBidirectionalText=ut.processStyledBidirectionalText;for(const{resolve:jt}of this.rtlPluginParsingListeners)jt(!0);this.rtlPluginParsingListeners=[]}}clearCaches(We,ut){delete this.layerIndexes[We],delete this.availableImages[We],delete this.availableModels[We],delete this.workerSources[We],delete this.isSpriteLoaded[We]}checkIfReady(We,ut){}spriteLoaded(We,ut){const{scope:jt}=ut;if(this.isSpriteLoaded[We]||(this.isSpriteLoaded[We]={}),this.isSpriteLoaded[We][jt]=!0,this.workerSources[We]&&this.workerSources[We][jt])for(const Rt in this.workerSources[We][jt]){const zt=this.workerSources[We][jt][Rt];for(const Wt in zt){const ws=zt[Wt];ws instanceof As&&(ws.isSpriteLoaded=!0,ws.fire(new c.h("isSpriteLoaded")))}}}setImages(We,ut){this.availableImages[We]||(this.availableImages[We]={});const{scope:jt,images:Rt}=ut;if(this.availableImages[We][jt]=Rt,ut.isSpriteLoaded&&this.spriteLoaded(We,{scope:jt}),this.workerSources[We]&&this.workerSources[We][jt])for(const zt in this.workerSources[We][jt]){const Wt=this.workerSources[We][jt][zt];for(const ws in Wt)Wt[ws].availableImages=Rt}}setModels(We,{scope:ut,models:jt}){if(this.availableModels[We]||(this.availableModels[We]={}),this.availableModels[We][ut]=jt,this.workerSources[We]&&this.workerSources[We][ut])for(const Rt in this.workerSources[We][ut]){const zt=this.workerSources[We][ut][Rt];for(const Wt in zt)zt[Wt].availableModels=jt}}setProjection(We,ut){this.projections[We]=c.gr(ut)}setGlobalParams(We,ut){if(this.referrer=ut.referrer,Object.assign(c.eS,ut.config),ut.contextOptions){const{maxBindingPoints:jt,maxUniformBlockSizeDwords:Rt}=ut.contextOptions;this.maxUniformBufferBindings=jt,this.maxUniformBlockSizeDwords=Rt}}upsertRenderParams(We,ut){ut.brightness!==void 0&&(this.brightness=ut.brightness),ut.worldview!==void 0&&(this.worldview=ut.worldview)}setLayers(We,ut){this.getLayerIndex(We,ut.scope).replace(ut.layers,ut.options)}updateLayers(We,ut){this.getLayerIndex(We,ut.scope).update(ut.layers,ut.removedIds,ut.options)}async loadTile(We,ut){if(ut.projection=this.projections[We]||this.defaultProjection,ut.type==="batched-model"&&!this.workerSourceTypes["batched-model"]){if(await c.gt(),!R)throw new Error('Could not load Standard module for "batched-model" source.');this.workerSourceTypes["batched-model"]=R}return ut.type==="raster-array"&&await this.ensureRasterArrayWorkerSource(),this.getWorkerSource(We,ut).loadTile(ut)}async ensureRasterArraySource(We,ut){await this.ensureRasterArrayWorkerSource()}async ensureRasterArrayWorkerSource(){if(!this.workerSourceTypes["raster-array"]){if(await async function(){return Promise.resolve()}(),!oh)throw new Error('Could not load raster-array module for "raster-array" source.');this.workerSourceTypes["raster-array"]=oh}}async decodeRasterArray(We,ut){return await this.ensureRasterArrayWorkerSource(),this.getWorkerSource(We,ut).decodeRasterArray(ut)}reloadTile(We,ut){return ut.projection=this.projections[We]||this.defaultProjection,this.getWorkerSource(We,ut).reloadTile(ut)}abortTile(We,ut){const jt=this.getExistingWorkerSource(We,ut);return jt?jt.abortTile(ut):void 0}removeTile(We,ut){const jt=this.getExistingWorkerSource(We,ut);return jt?jt.removeTile(ut):void 0}getExistingWorkerSource(We,ut){const{type:jt,source:Rt,scope:zt}=ut,Wt=this.workerSources[We];if(Wt&&Wt[zt]&&Wt[zt][jt])return Wt[zt][jt][Rt]}async removeSource(We,ut){const{type:jt,source:Rt,scope:zt}=ut,Wt=this.workerSources[We]&&this.workerSources[We][zt]&&this.workerSources[We][zt][jt],ws=Wt&&Wt[Rt];ws&&(delete Wt[Rt],ws.removeSource&&await ws.removeSource({source:Rt}))}async loadTileProvider(We,ut){const jt=new(await c.cN(ut.name,ut.url))(ut.options);return this.getWorkerSource(We,{type:ut.type,source:ut.source,scope:ut.scope},jt),jt.load&&ut.request?jt.load({request:ut.request}):null}async syncRTLPluginState(We,ut){if(c.fN.isParsed())return!0;if(c.fN.isParsing())return new Promise((Rt,zt)=>{this.rtlPluginParsingListeners.push({resolve:Rt,reject:zt})});c.fN.setState(ut);const jt=c.fN.getPluginURL();if(!c.fN.isLoaded()||c.fN.isParsed()||c.fN.isParsing())return!1;c.fN.setState({pluginStatus:c.gs.parsing,pluginURL:jt});try{return await self.__mapboxImport(jt),!!c.fN.isParsed()||new Promise((Rt,zt)=>{this.rtlPluginParsingListeners.push({resolve:Rt,reject:zt})})}catch(Rt){c.fN.setState({pluginStatus:c.gs.error,pluginURL:jt});for(const{reject:zt}of this.rtlPluginParsingListeners)zt(Rt);throw this.rtlPluginParsingListeners=[],Rt}}getAvailableImages(We,ut){this.availableImages[We]||(this.availableImages[We]={});let jt=this.availableImages[We][ut];return jt||(jt=[]),jt}getAvailableModels(We,ut){this.availableModels[We]||(this.availableModels[We]={});let jt=this.availableModels[We][ut];return jt||(jt={}),jt}getLayerIndex(We,ut){this.layerIndexes[We]||(this.layerIndexes[We]={});let jt=this.layerIndexes[We][ut];return jt||(jt=this.layerIndexes[We][ut]=new W,jt.scope=ut),jt}getWorkerSource(We,ut,jt){const{type:Rt,source:zt,scope:Wt}=ut,ws=this.workerSources;if(ws[We]||(ws[We]={}),ws[We][Wt]||(ws[We][Wt]={}),ws[We][Wt][Rt]||(ws[We][Wt][Rt]={}),this.isSpriteLoaded[We]||(this.isSpriteLoaded[We]={}),this.getExistingWorkerSource(We,ut))jt&&(ws[We][Wt][Rt][zt].tileProvider=jt);else{const Ms=this.actor.getWorkerSourceActor(We),Ns=this.workerSourceTypes[Rt];if(!Ns)throw new Error(`Unknown worker source type "${Rt}".`);ws[We][Wt][Rt][zt]=new Ns({actor:Ms,layerIndex:this.getLayerIndex(We,Wt),availableImages:this.getAvailableImages(We,Wt),availableModels:this.getAvailableModels(We,Wt),isSpriteLoaded:this.isSpriteLoaded[We][Wt],tileProvider:jt,brightness:this.brightness,worldview:this.worldview,maxUniformBufferBindings:this.maxUniformBufferBindings,maxUniformBlockSizeDwords:this.maxUniformBlockSizeDwords})}return ws[We][Wt][Rt][zt]}enforceCacheSizeLimit(We,ut){c.gu(ut)}}return c.gq(self)&&(self.worker=new xh(self)),xh}),i(["./shared"],function(o){const c={antialias:!1,alpha:!0,stencil:!0,depth:!0};let d,u;function h(L){const k=document.createElement("canvas"),T=Object.create(c);T.failIfMajorPerformanceCaveat=L;const B=k.getContext("webgl2",T);if(!B)return!1;let K;try{K=B.createShader(B.VERTEX_SHADER)}catch{return!1}return!(!K||B.isContextLost())&&(B.shaderSource(K,"void main() {}"),B.compileShader(K),B.getShaderParameter(K,B.COMPILE_STATUS)===!0)}const m=/firefox/i,f=/macintosh/i;function g(L,k,T){const B=document.createElement(L);return k!=null&&(B.className=k),T&&T.appendChild(B),B}function x(L,k,T){const B=document.createElementNS("http://www.w3.org/2000/svg",L);for(const K of Object.keys(k))B.setAttributeNS(null,K,String(k[K]));return T&&T.appendChild(B),B}const y=typeof document<"u"?document.documentElement&&document.documentElement.style:null,v=y&&y.userSelect!==void 0?"userSelect":"WebkitUserSelect";let b;function w(){y&&v&&(b=y[v],y[v]="none")}function S(){y&&v&&(y[v]=b)}function C(L){L.preventDefault(),L.stopPropagation(),window.removeEventListener("click",C,!0)}function E(){window.addEventListener("click",C,!0),window.setTimeout(()=>{window.removeEventListener("click",C,!0)},0)}function I(L,k){const T=L.getBoundingClientRect();return D(L,T,k)}function P(L,k){const T=L.getBoundingClientRect(),B=[];for(let K=0;K>16&255)/255,(L>>8&255)/255,(255&L)/255,1)}function Ee(L,k){const T={spread_method:1,stops:[],x1:0,y1:0,x2:1,y2:0};let B;for(;B=L.nextField(k);)B===1?T.transform=ce(L,L.readVarint()+L.pos):B===2?T.spread_method=L.readVarint():B===3?T.stops.push(Se(L,L.readVarint()+L.pos)):B===4?T.x1=L.readFloat():B===5?T.y1=L.readFloat():B===6?T.x2=L.readFloat():B===7&&(T.y2=L.readFloat());return T}function Se(L,k){const T={offset:0,opacity:255,rgb_color:V};let B;for(;B=L.nextField(k);)B===1?T.offset=L.readFloat():B===2?T.opacity=L.readVarint():B===3&&(T.rgb_color=ve(L.readVarint()));return T}function Le(L,k){const T={spread_method:1,stops:[],cx:.5,cy:.5,r:.5,fx:.5,fy:.5,fr:0};let B;for(;B=L.nextField(k);)B===1?T.transform=ce(L,L.readVarint()+L.pos):B===2?T.spread_method=L.readVarint():B===3?T.stops.push(Se(L,L.readVarint()+L.pos)):B===4?T.cx=L.readFloat():B===5?T.cy=L.readFloat():B===6?T.r=L.readFloat():B===7?T.fx=L.readFloat():B===8?T.fy=L.readFloat():B===9&&(T.fr=L.readFloat());return T}function Fe(L,k){const T={children:[]};let B;for(;B=L.nextField(k);)B===1?T.transform=ce(L,L.readVarint()+L.pos):B===2?T.clip_path_idx=L.readVarint():B===3&&T.children.push(te(L,L.readVarint()+L.pos));return T}function ke(L,k){const T={left:0,width:20,mask_type:1,children:[]};let B;for(;B=L.nextField(k);)B===1?T.left=T.top=L.readFloat():B===2?T.width=T.height=L.readFloat():B===3?T.top=L.readFloat():B===4?T.height=L.readFloat():B===5?T.mask_type=L.readVarint():B===6?T.mask_idx=L.readVarint():B===7&&T.children.push(te(L,L.readVarint()+L.pos));return T.height??(T.height=T.width),T.top??(T.top=T.left),T}class Ve{static calculate(k={},T=[]){const B=new Map,K=new Map;if(Object.keys(k).length===0)return B;T.forEach(Q=>{K.set(Q.name,Q.rgb_color||new o.C(0,0,0))});for(const[Q,le]of Object.entries(k))K.has(Q)?B.set(K.get(Q).toString(),le):console.warn(`Ignoring unknown image variable "${Q}"`);return B}}function je(L,k=255,T){const B=T.get(L.toString())||L;return k===255?B.toString():new o.C(B.r,B.g,B.b,B.a*k/255).toString()}const Ae=[];let Ce=0;function qe(L,k){if(Ce>=Ae.length){const B=o.o()?new OffscreenCanvas(L,k).getContext("2d",{willReadFrequently:!0}):document.createElement("canvas").getContext("2d",{willReadFrequently:!0});Ae.push(B)}const T=Ae[Ce++];return T.canvas.width=L,T.canvas.height=k,T}function ze(){Ce--}function $e(L,k,T,B,K){for(const Q of B.children)ct(L,k,T,Q,K)}function ct(L,k,T,B,K){B.group?(L.save(),function(Q,le,me,we,Me){const Re=we.mask_idx!=null?me.masks[we.mask_idx]:null,Ze=we.clip_path_idx!=null?me.clip_paths[we.clip_path_idx]:null;if(we.transform&&(le=qt(we.transform).preMultiplySelf(le)),!function(ht,_t,bt){return ht.opacity!==255||_t||bt}(we,Ze!=null,Re!=null))return void $e(Q,le,me,we,Me);const Qe=qe(Q.canvas.width,Q.canvas.height);$e(Qe,le,me,we,Me),Ze&&rt(Qe,le,me,Ze),Re&&Yt(Qe,le,me,Re,Me),Q.globalAlpha=we.opacity/255,Q.drawImage(Qe.canvas,0,0),ze()}(L,k,T,B.group,K),L.restore()):B.path&&(L.save(),function(Q,le,me,we,Me){Q.setTransform(le),we.paint_order===1?(Xe(Q,me,we,Me),at(Q,me,we,Me)):(at(Q,me,we,Me),Xe(Q,me,we,Me))}(L,k,T,B.path,K),L.restore())}function Xe(L,k,T,B){const K=T.fill;if(!K)return;const Q=K.opacity/255;switch(L.save(),L.beginPath(),ts(T,L),K.paint){case"rgb_color":L.fillStyle=je(K.rgb_color,K.opacity,B);break;case"linear_gradient_idx":{const le=k.linear_gradients[K.linear_gradient_idx];le.transform&&L.setTransform(qt(le.transform).preMultiplySelf(L.getTransform())),L.fillStyle=Ke(L,le,Q,B);break}case"radial_gradient_idx":{const le=k.radial_gradients[K.radial_gradient_idx];le.transform&&L.setTransform(qt(le.transform).preMultiplySelf(L.getTransform())),L.fillStyle=nt(L,le,Q,B)}}L.fill(it(T)),L.restore()}function it(L){return L.rule===1?"nonzero":L.rule===2?"evenodd":void 0}function at(L,k,T,B){const K=T.stroke;if(!K)return;const Q=ys(T);L.lineWidth=K.width,L.miterLimit=K.miterlimit,L.setLineDash(K.dasharray),L.lineDashOffset=K.dashoffset;const le=K.opacity/255;switch(K.paint){case"rgb_color":L.strokeStyle=je(K.rgb_color,K.opacity,B);break;case"linear_gradient_idx":L.strokeStyle=Ke(L,k.linear_gradients[K.linear_gradient_idx],le,B,!0);break;case"radial_gradient_idx":L.strokeStyle=nt(L,k.radial_gradients[K.radial_gradient_idx],le,B,!0)}switch(K.linejoin){case 2:case 1:L.lineJoin="miter";break;case 3:L.lineJoin="round";break;case 4:L.lineJoin="bevel"}switch(K.linecap){case 1:L.lineCap="butt";break;case 2:L.lineCap="round";break;case 3:L.lineCap="square"}L.stroke(Q)}function Ke(L,k,T,B,K=!1){if(k.stops.length===1){const Qe=k.stops[0];return je(Qe.rgb_color,Qe.opacity*T,B)}const{x1:Q,y1:le,x2:me,y2:we}=k;let Me=new DOMPoint(Q,le),Re=new DOMPoint(me,we);if(K){const Qe=qt(k.transform);Me=Qe.transformPoint(Me),Re=Qe.transformPoint(Re)}const Ze=L.createLinearGradient(Me.x,Me.y,Re.x,Re.y);for(const Qe of k.stops)Ze.addColorStop(Qe.offset,je(Qe.rgb_color,Qe.opacity*T,B));return Ze}function nt(L,k,T,B,K=!1){if(k.stops.length===1){const es=k.stops[0];return je(es.rgb_color,es.opacity*T,B)}const Q=qt(k.transform),{fx:le,fy:me,fr:we,cx:Me,cy:Re,r:Ze}=k;let Qe=new DOMPoint(le,me),ht=new DOMPoint(Me,Re),_t=we,bt=Ze;if(K){Qe=Q.transformPoint(Qe),ht=Q.transformPoint(ht);const es=(Q.a+Q.d)/2;_t=we*es,bt=k.r*es}const Mt=L.createRadialGradient(Qe.x,Qe.y,_t,ht.x,ht.y,bt);for(const es of k.stops)Mt.addColorStop(es.offset,je(es.rgb_color,es.opacity*T,B));return Mt}function xt(L,k,T,B){const K=B.transform?qt(B.transform).preMultiplySelf(k):k,Q=qe(L.canvas.width,L.canvas.height);for(const me of B.children)if(me.group)xt(Q,K,T,me.group);else if(me.path){const we=me.path,Me=new Path2D;Me.addPath(ys(we),K),Q.fill(Me,it(we))}const le=B.clip_path_idx!=null?T.clip_paths[B.clip_path_idx]:null;le&&rt(Q,K,T,le),L.globalCompositeOperation="source-over",L.drawImage(Q.canvas,0,0),ze()}function rt(L,k,T,B){const K=qe(L.canvas.width,L.canvas.height);xt(K,k,T,B),L.globalCompositeOperation="destination-in",L.drawImage(K.canvas,0,0),ze()}function Yt(L,k,T,B,K){if(B.children.length===0)return;const Q=B.mask_idx!=null?T.masks[B.mask_idx]:null;Q&&Yt(L,k,T,Q,K);const le=L.canvas.width,me=L.canvas.height,we=qe(le,me),Me=B.width,Re=B.height,Ze=B.left,Qe=B.top,ht=new Path2D,_t=new Path2D;_t.rect(Ze,Qe,Me,Re),ht.addPath(_t,k),we.clip(ht);for(const es of B.children)ct(we,k,T,es,K);const bt=we.getImageData(0,0,le,me),Mt=bt.data;if(B.mask_type===1)for(let es=0;eso.I.from(T))}getImageVersions(k){return this.imageVersions.get(k)||new Map}hasImageProviderForSource(k,T){const B=this.imageProviders.get(T);if(!B)return!1;for(const K of B.values())if(K.sourceCache.getSource().id===k)return!0;return!1}getImages(k,T,B){const K=[],Q=[],le=this.imageProviders.get(T);for(const Re of k){if(!Re.iconsetId){K.push(Re);continue}const Ze=le.get(Re.iconsetId);Ze&&(this.getImage(Re,T)?Q.push(Re):Ze.addPendingRequest(Re))}if(K.length===0)return void this._notify(Q,T,B);let me=!0;const we=!!this.loaded.get(T),Me=this.images.get(T);if(!we)for(const Re of K)Me.has(Re.toString())||(me=!1);we||me?this._notify(K,T,B):this.requestors.push({ids:K,scope:T,callback:B})}rasterizeImages(k,T){const B=new Map,{iconTasks:K,patternTasks:Q,scope:le}=k;for(const me of[K,Q])for(const[we,Me]of me.entries()){const Re=this.getImage(Me.id,le);Re&&B.set(we,{image:Re,imageVariant:Me})}T(null,this._rasterizeImages(le,B))}_rasterizeImages(k,T){const B=new Map;for(const[K,{image:Q,imageVariant:le}]of T.entries())B.set(K,this.imageRasterizer.rasterize(le,Q,k,0));return B}getUpdatedImages(k){return this.updatedImages.get(k)||new Set}_notify(k,T,B){const K=this.images.get(T),Q=new Map;for(const le of k){if(!K.get(le.toString())){if(le.iconsetId)continue;this.fire(new o.h("styleimagemissing",{id:le.name}))}const me=K.get(le.toString());if(!me){o.w(`Image "${le.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 we={data:me.usvg?null:me.data.clone(),pixelRatio:me.pixelRatio,sdf:me.sdf,usvg:me.usvg,stretchX:me.stretchX,stretchY:me.stretchY,content:me.content,hasRenderCallback:!!(me.userImage&&me.userImage.render)};me.usvg&&Object.assign(we,{width:me.icon.usvg_tree.width,height:me.icon.usvg_tree.height}),Q.set(o.I.toString(le),we)}B(null,{images:Q,versions:this.getImageVersions(T)})}getPixelSize(k){const{width:T,height:B}=this.atlasImage.get(k);return{width:T,height:B}}getPattern(k,T,B){const K=k.toString(),Q=this.patterns.get(T),le=Q.get(K),me=this.getImage(k,T);if(!me)return null;if(le){if(le.position.version===me.version)return le.position;le.position.version=me.version}else{if(me.usvg&&!me.data){const we=this.getPatternInFlightId(K,T);if(this.patternsInFlight.has(we))return null;this.patternsInFlight.add(we);const Me=new o.i(k).scaleSelf(o.e.devicePixelRatio),Re=new Map([[Me.toString(),{image:me,imageVariant:Me}]]),Ze=this._rasterizeImages(T,Re);return this.storePatternImage(Me,T,me,B,Ze),null}this.storePattern(k,T,me)}return this._updatePatternAtlas(T,B),Q.get(K).position}getPatternInFlightId(k,T){return o.m(k,T)}hasPatternsInFlight(){return this.patternsInFlight.size!==0}storePatternImage(k,T,B,K,Q){const le=k.toString(),me=Q?Q.get(le):void 0;me&&(B.data=me,this.storePattern(k.id,T,B),this._updatePatternAtlas(T,K),this.patternsInFlight.delete(this.getPatternInFlightId(k.id.toString(),T)))}storePattern(k,T,B){const K={w:B.data.width+2*o.j,h:B.data.height+2*o.j,x:0,y:0},Q=new o.k(K,B,o.j);this.patterns.get(T).set(k.toString(),{bin:K,position:Q})}destroyAtlasTextures(){for(const k of this.atlasTexture.values())k&&k.destroy();this.atlasTexture.clear()}bind(k,T){const B=k.gl;let K=this.atlasTexture.get(T);K?this.dirty&&(K.update(this.atlasImage.get(T)),this.dirty=!1):(K=new o.T(k,this.atlasImage.get(T),B.RGBA8),this.atlasTexture.set(T,K)),K.bind(B.LINEAR,B.CLAMP_TO_EDGE)}_updatePatternAtlas(k,T){const B=this.patterns.get(k),K=Array.from(B.values()).map(({bin:Me})=>Me),{w:Q,h:le}=o.p(K),me=this.atlasImage.get(k);me.resize({width:Q||1,height:le||1});const we=this.images.get(k);for(const[Me,{bin:Re,position:Ze}]of B.entries()){let Qe=Ze.padding;const ht=Re.x+Qe,_t=Re.y+Qe,bt=we.get(Me).data,Mt=bt.width,es=bt.height;Qe=Qe>1?Qe-1:Qe,o.b.copy(bt,me,{x:0,y:0},{x:ht,y:_t},{width:Mt,height:es},T),o.b.copy(bt,me,{x:0,y:es-Qe},{x:ht,y:_t-Qe},{width:Mt,height:Qe},T),o.b.copy(bt,me,{x:0,y:0},{x:ht,y:_t+es},{width:Mt,height:Qe},T),o.b.copy(bt,me,{x:Mt-Qe,y:0},{x:ht-Qe,y:_t},{width:Qe,height:es},T),o.b.copy(bt,me,{x:0,y:0},{x:ht+Mt,y:_t},{width:Qe,height:es},T),o.b.copy(bt,me,{x:Mt-Qe,y:es-Qe},{x:ht-Qe,y:_t-Qe},{width:Qe,height:Qe},T),o.b.copy(bt,me,{x:0,y:es-Qe},{x:ht+Mt,y:_t-Qe},{width:Qe,height:Qe},T),o.b.copy(bt,me,{x:0,y:0},{x:ht+Mt,y:_t+es},{width:Qe,height:Qe},T),o.b.copy(bt,me,{x:Mt-Qe,y:0},{x:ht-Qe,y:_t+es},{width:Qe,height:Qe},T)}this.dirty=!0}beginFrame(){for(const k of this.images.keys())this.callbackDispatchedThisFrame.set(k,new Set);this.imageAtlasCache.beginFrame()}dispatchRenderCallbacks(k,T){const B=this.images.get(T);for(const K of k){if(this.callbackDispatchedThisFrame.get(T).has(K.toString()))continue;this.callbackDispatchedThisFrame.get(T).add(K.toString());const Q=B.get(K.toString());W(Q)&&this.updateImage(K,T,Q)}}}class rs{constructor(k,T,B,K){this.message=(k?`${k}: `:"")+B,K&&(this.identifier=K),T!=null&&T.__line__&&(this.line=T.__line__)}}class St extends rs{}function Xs(L){const k=L.value,T=L.valueSpec,B=L.style,K=L.styleSpec,Q=L.key,le=L.arrayElementValidator||ur;if(!Array.isArray(k))return[new rs(Q,k,`array expected, ${o.n(k)} found`)];if(T.length&&k.length!==T.length)return[new rs(Q,k,`array length ${T.length} expected, length ${k.length} found`)];if(T["min-length"]&&k.lengthK)return[new rs(k,T,`${T} is greater than the maximum value ${K}`)]}return[]}function gs(L){const k=L.key,T=L.value;if(!o.l(T))return[new rs(k,T,`object expected, ${o.n(T)} found`)];const B=L.valueSpec,K=o.u(T.type);let Q,le,me,we={};const Me=K!=="categorical"&&T.property===void 0,Re=!Me,Ze=function(bt){const Mt=bt.stops;return Array.isArray(Mt)&&Array.isArray(Mt[0])&&o.l(Mt[0][0])}(T),Qe=Pa({key:L.key,value:L.value,valueSpec:L.styleSpec.function,style:L.style,styleSpec:L.styleSpec,objectElementValidators:{stops:function(bt){if(K==="identity")return[new rs(bt.key,bt.value,'identity function may not have a "stops" property')];let Mt=[];const es=bt.value;return Mt=Mt.concat(Xs({key:bt.key,value:es,valueSpec:bt.valueSpec,style:bt.style,styleSpec:bt.styleSpec,arrayElementValidator:ht})),Array.isArray(es)&&es.length===0&&Mt.push(new rs(bt.key,es,"array must have at least one stop")),Mt},default:function(bt){return ur({key:bt.key,value:bt.value,valueSpec:B,style:bt.style,styleSpec:bt.styleSpec})}}});return K==="identity"&&Me&&Qe.push(new rs(L.key,L.value,'missing required property "property"')),K==="identity"||T.stops||Qe.push(new rs(L.key,L.value,'missing required property "stops"')),K==="exponential"&&B.expression&&!o.r(B)&&Qe.push(new rs(L.key,L.value,"exponential functions not supported")),L.styleSpec.$version>=8&&(Re&&!o.t(B)?Qe.push(new rs(L.key,L.value,"property functions not supported")):Me&&!o.v(B)&&Qe.push(new rs(L.key,L.value,"zoom functions not supported"))),K!=="categorical"&&!Ze||T.property!==void 0||Qe.push(new rs(L.key,L.value,'"property" property is required')),Qe;function ht(bt){let Mt=[];const es=bt.value,Qt=bt.key;if(!Array.isArray(es))return[new rs(Qt,es,`array expected, ${o.n(es)} found`)];if(es.length!==2)return[new rs(Qt,es,`array length 2 expected, length ${es.length} found`)];if(Ze){if(!o.l(es[0]))return[new rs(Qt,es,`object expected, ${o.n(es[0])} found`)];const Lt=es[0];if(Lt.zoom===void 0)return[new rs(Qt,es,"object stop key must have zoom")];if(Lt.value===void 0)return[new rs(Qt,es,"object stop key must have value")];const ps=o.u(Lt.zoom);if(typeof ps!="number")return[new rs(Qt,Lt.zoom,"stop zoom values must be numbers")];if(me&&me>ps)return[new rs(Qt,Lt.zoom,"stop zoom values must appear in ascending order")];ps!==me&&(me=ps,le=void 0,we={}),Mt=Mt.concat(Pa({key:`${Qt}[0]`,value:es[0],valueSpec:{zoom:{}},style:bt.style,styleSpec:bt.styleSpec,objectElementValidators:{zoom:vt,value:_t}}))}else Mt=Mt.concat(_t({key:`${Qt}[0]`,value:es[0],style:bt.style,styleSpec:bt.styleSpec},es));return o.x(o.y(es[1]))?Mt.concat([new rs(`${Qt}[1]`,es[1],"expressions are not allowed in function stops.")]):Mt.concat(ur({key:`${Qt}[1]`,value:es[1],valueSpec:B,style:bt.style,styleSpec:bt.styleSpec}))}function _t(bt,Mt){const es=o.n(bt.value),Qt=o.u(bt.value),Lt=bt.value!==null?bt.value:Mt;if(Q){if(es!==Q)return[new rs(bt.key,Lt,`${es} stop domain type must match previous stop domain type ${Q}`)]}else Q=es;if(es!=="number"&&es!=="string"&&es!=="boolean"&&typeof Qt!="number"&&typeof Qt!="string"&&typeof Qt!="boolean")return[new rs(bt.key,Lt,"stop domain value must be a number, string, or boolean")];if(es!=="number"&&K!=="categorical"){let ps=`number expected, ${es} found`;return o.t(B)&&K===void 0&&(ps+='\nIf you intended to use a categorical function, specify `"type": "categorical"`.'),[new rs(bt.key,Lt,ps)]}return K!=="categorical"||es!=="number"||typeof Qt=="number"&&isFinite(Qt)&&Math.floor(Qt)===Qt?K!=="categorical"&&es==="number"&&typeof Qt=="number"&&typeof le=="number"&&le!==void 0&&Qtnew rs(`${L.key}${B.key}`,L.value,B.message));const T=k.value.expression||k.value._styleExpression.expression;if(L.expressionContext==="property"&&L.propertyKey==="text-font"&&!T.outputDefined())return[new rs(L.key,L.value,`Invalid data expression for "${L.propertyKey}". Output values must be contained as literals within the expression.`)];if(L.expressionContext==="property"&&L.propertyType==="layout"&&!o.A(T))return[new rs(L.key,L.value,'"feature-state" data expressions are not supported with layout properties.')];if(L.expressionContext==="filter")return Is(T,L);if(L.expressionContext==="appearance")return js(T,L);if(L.expressionContext&&L.expressionContext.indexOf("cluster")===0){if(!o.B(T,["zoom","feature-state"]))return[new rs(L.key,L.value,'"zoom" and "feature-state" expressions are not supported with cluster properties.')];if(L.expressionContext==="cluster-initial"&&!o.D(T))return[new rs(L.key,L.value,"Feature data expressions are not supported with initial expression part of cluster properties.")]}return[]}function Is(L,k){const T=new Set(["zoom","feature-state","pitch","distance-from-center"]);if(k.valueSpec&&k.valueSpec.expression)for(const K of k.valueSpec.expression.parameters)T.delete(K);if(T.size===0)return[];const B=[];return L instanceof o.F&&T.has(L.name)?[new rs(k.key,k.value,`["${L.name}"] expression is not supported in a filter for a ${k.object.type} layer with id: ${k.object.id}`)]:(L.eachChild(K=>{B.push(...Is(K,k))}),B)}const Ys=new Set(["get","has","properties","geometry-type","id"]),cs=new Set(["zoom","pitch","distance-from-center","feature","feature-state","measure-light","heatmap-density","line-progress","raster-value","raster-particle-speed","sky-radial-progress"]);function js(L,k){if(k.valueSpec&&k.valueSpec.expression)for(const B of k.valueSpec.expression.parameters)cs.delete(B);if(cs.size===0)return[];const T=[];if(L instanceof o.F){const B=Ys.has(L.name)?"feature":L.name;if(cs.has(B))return[new rs(k.key,k.value,`["${L.name}"] is not an allowed parameter`)]}return L.eachChild(B=>{T.push(...js(B,k))}),T}function kn(L){const k=L.key,T=L.value,B=L.valueSpec,K=[];return Array.isArray(B.values)?B.values.includes(o.u(T))||K.push(new rs(k,T,`expected one of [${B.values.join(", ")}], ${JSON.stringify(T)} found`)):Object.keys(B.values).includes(o.u(T))||K.push(new rs(k,T,`expected one of [${Object.keys(B.values).join(", ")}], ${JSON.stringify(T)} found`)),K}function Ws(L){if(o.J(o.y(L.value))){const k=L.layerType||"fill";return Ss({...L,expressionContext:"filter",valueSpec:L.styleSpec[`filter_${k}`]})}return On(L)}function On(L){const k=L.value,T=L.key;if(!Array.isArray(k))return[new rs(T,k,`array expected, ${o.n(k)} found`)];if(k.length<1)return[new rs(T,k,"filter array must have at least 1 element")];const B=L.styleSpec;let K=kn({key:`${T}[0]`,value:k[0],valueSpec:B.filter_operator});const Q=()=>{k.length>=2&&(o.H(k[1])||K.push(new rs(`${T}[1]`,k[1],`string expected, ${o.n(k[1])} found`)));for(let le=2;le":case">=":k.length>=2&&o.u(k[1])==="$type"&&K.push(new rs(T,k,`"$type" cannot be use with operator "${k[0]}"`)),k.length!==3&&K.push(new rs(T,k,`filter array for operator "${k[0]}" must have 3 elements`)),Q();break;case"==":case"!=":k.length!==3&&K.push(new rs(T,k,`filter array for operator "${k[0]}" must have 3 elements`)),Q();break;case"in":case"!in":Q();break;case"any":case"all":case"none":for(let le=1;le{Me in T&&k.push(new rs(B,T[Me],`"${Me}" is prohibited for ref layers`))}),K.layers.forEach(Me=>{o.u(Me.id)===me&&(we=Me)}),we?we.ref?k.push(new rs(B,T.ref,"ref cannot reference another ref layer")):le=o.u(we.type):typeof me=="string"&&k.push(new rs(B,T.ref,`ref layer "${me}" not found`))}else if(le!=="background"&&le!=="sky"&&le!=="slot"&&le!=="placement-group")if(T.source)if(o.H(T.source)){const we=K.sources&&Object.hasOwn(K.sources,T.source)?K.sources[T.source]:void 0,Me=we&&o.u(we.type);we?Me==="vector"&&le==="raster"?k.push(new rs(B,T.source,`layer "${T.id}" requires a raster source`)):Me==="raster"&&le!=="raster"?k.push(new rs(B,T.source,`layer "${T.id}" requires a vector source`)):Me!=="vector"||T["source-layer"]?Me==="raster-dem"&&le!=="hillshade"?k.push(new rs(B,T.source,"raster-dem source can only be used with layer type 'hillshade'.")):Me!=="raster-array"||["raster","raster-particle"].includes(le)?le==="line"&&T.paint&&T.paint["line-gradient"]&&Me==="geojson"&&!we.lineMetrics?k.push(new rs(B,T,`layer "${T.id}" specifies a line-gradient, which requires the GeoJSON source to have \`lineMetrics\` enabled.`)):le==="line"&&T.paint&&T.paint["line-trim-offset"]&&Me==="geojson"&&!we.lineMetrics?k.push(new rs(B,T,`layer "${T.id}" specifies a line-trim-offset, which requires the GeoJSON source to have \`lineMetrics\` enabled.`)):le==="raster-particle"&&Me!=="raster-array"&&k.push(new rs(B,T.source,`layer "${T.id}" requires a 'raster-array' source.`)):k.push(new rs(B,T.source,"raster-array source can only be used with layer type 'raster'.")):k.push(new rs(B,T,`layer "${T.id}" must specify a "source-layer"`)):k.push(new rs(B,T.source,`source "${T.source}" not found`))}else k.push(new rs(`${B}.source`,T.source,'"source" must be a string'));else k.push(new rs(B,T,'missing required property "source"'));return k=k.concat(Pa({key:B,value:T,valueSpec:Q.layer,style:L.style,styleSpec:L.styleSpec,objectElementValidators:{"*":()=>[],type:()=>ur({key:`${B}.type`,value:T.type,valueSpec:Q.layer.type,style:L.style,styleSpec:L.styleSpec,object:T,objectKey:"type"}),filter:we=>Ws({layerType:le,...we}),layout:we=>Pa({layer:T,key:we.key,value:we.value,valueSpec:{},style:we.style,styleSpec:we.styleSpec,objectElementValidators:{"*":Me=>hr({layerType:le,...Me})}}),paint:we=>Pa({layer:T,key:we.key,value:we.value,valueSpec:{},style:we.style,styleSpec:we.styleSpec,objectElementValidators:{"*":Me=>As({layerType:le,layer:T,...Me})}}),appearances(we){const Me=Xs({key:we.key,value:we.value,valueSpec:we.valueSpec,style:we.style,styleSpec:we.styleSpec,arrayElementValidator:Qe=>function(ht){const{key:_t,layer:bt,layerType:Mt}=ht,es=o.u(ht.value),Qt=o.u(es.name),Lt=o.u(es.condition),ps=Pa({key:_t,value:es,valueSpec:ht.styleSpec.appearance,style:ht.style,styleSpec:ht.styleSpec,objectElementValidators:{condition:Hs=>function(Fs){const nn=[];return nn.push(...Ss({key:Fs.key,value:Fs.object.condition,valueSpec:o.s.appearance.condition,expressionContext:"appearance"})),nn}({...Hs}),properties:Hs=>function(Fs){const nn=[],{styleSpec:$s,layer:rn,layerType:_n}=Fs,Mn=$s[`paint_${_n}`],Yn=$s[`layout_${_n}`],$n=Fs.object[Fs.objectKey];for(const zn in $n){const Dr=zn in Mn?"paint":zn in Yn?"layout":void 0;if(!Dr){nn.push(new rs(Fs.key,zn,`unknown property "${zn}" for layer type "${_n}"`));continue}const An={...Fs,key:`${Fs.key}.${zn}`,objectKey:zn,layer:rn,layerType:_n,value:$n[zn],valueSpec:Dr==="paint"?Mn[zn]:Yn[zn]};nn.push(...gn(An,Dr))}return nn}({layer:bt,layerType:Mt,...Hs})}});return Qt!=="hidden"&&Lt===void 0&&ps.push(new rs(ht.key,"name",'Appearance with name different than "hidden" must have a condition')),ps}({layerType:le,layer:T,...Qe})}),Re=Array.isArray(we.value)?we.value:[],Ze=new Set;return Re.forEach((Qe,ht)=>{const _t=o.u(Qe.name);if(_t)if(Ze.has(_t)){const bt=o.u(T.id);Me.push(new rs(we.key,_t,`Duplicated appearance name "${_t}" for layer "${bt}"`))}else Ze.add(_t)}),Me}}})),k}function qn({key:L,value:k}){return o.H(k)?[]:[new rs(L,k,`string expected, ${o.n(k)} found`)]}const hn={promoteId:function L({key:k,value:T}){if(o.H(T))return qn({key:k,value:T});if(Array.isArray(T)){const K=[],Q=o.y(T),le=o.c(Q);return le.result==="error"?(le.value.forEach(me=>{K.push(new rs(`${k}${me.key}`,null,`${me.message}`))}),K):(o.B(le.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"])||K.push(new rs(`${k}`,null,"promoteId expression should be only feature dependent")),K)}if(!o.l(T))return[new rs(k,T,`string, expression or object expected, "${o.n(T)}" found`)];const B=[];for(const K in T)B.push(...L({key:`${k}.${K}`,value:T[K]}));return B}};function Fn(L){const k=L.value,T=L.key,B=L.styleSpec,K=L.style;if(!o.l(k))return[new rs(T,k,`object expected, ${o.n(k)} found`)];if(!("type"in k))return[new rs(T,k,'"type" is required')];const Q=o.u(k.type);let le=[];switch(["vector","raster","raster-dem","raster-array"].includes(Q)&&("url"in k||"tiles"in k||le.push(new St(T,k,'Either "url" or "tiles" is required.'))),Q){case"vector":case"raster":case"raster-dem":case"raster-array":return le=le.concat(Pa({key:T,value:k,valueSpec:B[`source_${Q.replace("-","_")}`],style:L.style,styleSpec:B,objectElementValidators:hn})),le;case"geojson":if(le=Pa({key:T,value:k,valueSpec:B.source_geojson,style:K,styleSpec:B,objectElementValidators:hn}),"cluster"in k&&"clusterProperties"in k){if(!o.l(k.clusterProperties))return[new rs(`${T}.clusterProperties`,k,`object expected, ${o.n(k)} found`)];for(const me in k.clusterProperties){const we=k.clusterProperties[me];if(!Array.isArray(we))return[new rs(`${T}.clusterProperties.${me}`,we,"array expected")];const[Me,Re]=we,Ze=typeof Me=="string"?[Me,["accumulated"],["get",me]]:Me;le.push(...Ss({key:`${T}.${me}.map`,value:Re,expressionContext:"cluster-map"})),le.push(...Ss({key:`${T}.${me}.reduce`,value:Ze,expressionContext:"cluster-reduce"}))}}return le;case"video":return Pa({key:T,value:k,valueSpec:B.source_video,style:K,styleSpec:B});case"image":return Pa({key:T,value:k,valueSpec:B.source_image,style:K,styleSpec:B});case"canvas":return[new rs(T,null,"Please use runtime APIs to add canvas sources, rather than including them in stylesheets.","source.canvas")];default:return kn({key:`${T}.type`,value:k.type,valueSpec:{values:vn(B)}})}}function vn(L){return L.source.reduce((k,T)=>{const B=L[T];return B.type.type==="enum"&&(k=k.concat(Object.keys(B.type.values||{}))),k},[])}function xs(L,k){const T=!L.includes("://");try{return new URL(L,T&&k?"http://example.com":void 0),!0}catch{return!1}}function Lr(L){const k=L.value;return k?o.H(k)?xs(k,!0)?[]:[new rs(L.key,k,`invalid url "${k}"`)]:[new rs(L.key,k,`string expected, "${o.n(k)}" found`)]:[]}function Or(L){const k=L.value,T=L.styleSpec,B=T.light,K=L.style;if(k===void 0)return[];if(!o.l(k))return[new rs("light",k,`object expected, ${o.n(k)} found`)];let Q=[];for(const le in k){const me=le.match(o.K),we=le.match(o.U);Q=Q.concat(we&&B[we[1]]?ur({key:le,value:k[le],valueSpec:{type:"string"},style:K,styleSpec:T}):me&&B[me[1]]&&B[me[1]].transition?ur({key:le,value:k[le],valueSpec:T.transition,style:K,styleSpec:T}):B[le]?ur({key:le,value:k[le],valueSpec:B[le],style:K,styleSpec:T}):[new rs(le,k[le],`unknown property "${le}"`)])}return Q}function ca(L){const k=L.value;if(!k)return[];const T=L.key;if(!o.l(k))return[new rs(T,k,`object expected, ${o.n(k)} found`)];let B=[];const K=L.styleSpec,Q=K["light-3d"],le=L.style,me=L.style.lights;for(const Re of["type","id"])if(!(Re in k))return B=B.concat([new rs(T,k,`missing property "${Re}"`)]),B;if(!o.H(k.type))return B=B.concat([new rs(`${T}.type`,k.type,"string expected")]),B;if(me)for(let Re=0;Re[],array:Xs,boolean:function(L){const k=L.value,T=L.key;return o.G(k)?[]:[new rs(T,k,`boolean expected, ${o.n(k)} found`)]},number:vt,color:function({key:L,value:k}){return o.H(k)?o.C.parse(o.u(k))===void 0?[new rs(L,k,`color expected, "${k}" found`)]:[]:[new rs(L,k,`color expected, ${o.n(k)} found`)]},enum:kn,filter:Ws,function:gs,layer:Er,object:Pa,source:Fn,model:Lr,light:Or,"light-3d":ca,terrain:Jn,fog:Sr,string:qn,formatted:function(L){return qn(L).length===0?[]:Ss(L)},resolvedImage:function(L){return qn(L).length===0?[]:Ss(L)},projection:function(L){const k=L.value,T=L.styleSpec,B=T.projection,K=L.style;if(o.l(k)){let Q=[];for(const le in k)Q=Q.concat(ur({key:le,value:k[le],valueSpec:B[le],style:K,styleSpec:T}));return Q}return o.H(k)?[]:[new rs("projection",k,`object or string expected, ${o.n(k)} found`)]},import:function(L){const k=L.key,{value:T,styleSpec:B}=L;if(!o.l(T))return[new rs(k,T,"import must be an object")];const{data:K,...Q}=T;Object.defineProperty(Q,"__line__",{value:T.__line__,enumerable:!1});let le=Pa({...L,value:Q,valueSpec:B.import});o.u(Q.id)===""&&le.push(new rs(`${L.key}.id`,Q,"import id can't be an empty string"));const me=o.u(Q.id);return me!=="__proto__"&&me!=="constructor"&&me!=="prototype"||le.push(new rs(`${L.key}.id`,Q,`import id can't be "${String(me)}"`)),K&&(le=le.concat($i(K,B,{key:`${L.key}.data`}))),le},iconset:function(L){const k=L.value,T=L.key,B=L.styleSpec,K=L.style;if(!o.l(k))return[new rs(T,k,"object expected")];if(!k.type)return[new rs(T,k,'"type" is required')];const Q=o.u(k.type);let le=[];if(le=le.concat(Pa({key:T,value:k,valueSpec:B[`iconset_${Q}`],style:K,styleSpec:B})),function(me,we){return!(me!=="source"||!we.source)}(Q,k)){const me=K.sources&&Object.hasOwn(K.sources,k.source)?K.sources[k.source]:void 0,we=me&&o.u(me.type);me?we!=="raster-array"&&le.push(new rs(T,k.source,`iconset cannot be used with a source of type ${String(we)}, it only be used with a "raster-array" source type`)):le.push(new rs(T,k.source,`source "${k.source}" not found`))}return le},option:function(L){const k=L.styleSpec,T=L.value,B=o.l(T)&&o.u(T.array)===!0||!o.l(T)?void 0:o.u(T.type);return Pa({...L,valueSpec:k.option,objectElementValidators:{default:K=>{const Q=K.value;return o.l(Q)?ur({...K,valueSpec:{...K.valueSpec,type:"*",expression:void 0}}):B&&Array.isArray(Q)?ur({...K,valueSpec:{...K.valueSpec,type:B}}):ur(K)}}})}};function ur(L,k=!1){const T=L.value,B=L.valueSpec,K=L.styleSpec;if(B.expression){if(o.M(o.u(T)))return gs(L);if(o.x(o.y(T)))return Ss(L)}if(B.type&&Un[B.type]){const Q=Un[B.type](L);return k===!0&&Q.length>0&&Array.isArray(L.value)?Ss(L):Q}return Pa({...L,valueSpec:B.type?K[B.type]:B})}function Pa(L){const k=L.key,T=L.value,B=L.valueSpec||{},K=L.objectElementValidators||{},Q=L.style,le=L.styleSpec;if(!o.l(T))return[new rs(k,T,`object expected, ${o.n(T)} found`)];let me=[];for(const we in T){if(!Object.hasOwn(T,we))continue;const Me=we.split(".")[0],Re=Object.hasOwn(B,Me),Ze=Object.hasOwn(B,"*"),Qe=Re?B[Me]:Ze?B["*"]:void 0;let ht;Object.hasOwn(K,Me)?ht=K[Me]:Re?ht=ur:Object.hasOwn(K,"*")?ht=K["*"]:Ze&&(ht=ur),ht?me=me.concat(ht({key:(k&&`${k}.`)+we,value:T[we],valueSpec:Qe,style:Q,styleSpec:le,object:T,objectKey:we},T)):me.push(new St(k,T[we],`unknown property "${we}"`))}for(const we in B){if(!Object.hasOwn(B,we)||Object.hasOwn(K,we))continue;const Me=B[we];!Me.required||Me.default!==void 0||Object.hasOwn(T,we)&&T[we]!==void 0||me.push(new rs(k,T,`missing required property "${we}"`))}return me}function ii({key:L,value:k}){const T=qn({key:L,value:k});if(T.length)return T;const B=k;return B.includes("{fontstack}")||T.push(new rs(L,k,'"glyphs" url must include a "{fontstack}" token')),B.includes("{range}")||T.push(new rs(L,k,'"glyphs" url must include a "{range}" token')),T}function $i(L,k=o.s,T={}){return Pa({key:T.key||"",value:L,valueSpec:{...k.$root,"*":{type:"*"}},styleSpec:k,style:L,objectElementValidators:{glyphs:ii}})}function Rn(L){return L.slice().sort((k,T)=>k.line&&T.line?k.line-T.line:0)}const xa="setStyle",Ya="addLayer",ho="removeLayer",Pc="setPaintProperty",$d="setLayerProperty",Nl="setTerrain",Ho="removeImport",ti="addIconset",Xr="removeIconset";function Eo(L,k,T){T.push({command:"addSource",args:[L,k[L]]})}function Ph(L,k,T){k.push({command:"removeSource",args:[L]}),T[L]=!0}function ih(L,k,T,B){Ph(L,T,B),Eo(L,k,T)}function ao(L,k,T){let B;for(B in L[T])if(Object.hasOwn(L[T],B)&&B!=="data"&&!o.O(L[T][B],k[T][B]))return!1;for(B in k[T])if(Object.hasOwn(k[T],B)&&B!=="data"&&!o.O(L[T][B],k[T][B]))return!1;return!0}function ta(L,k,T,B,K,Q){let le;for(le in k=k||{},L=L||{})Object.hasOwn(L,le)&&(o.O(L[le],k[le])||T.push({command:Q,args:[B,le,k[le],K]}));for(le in k)Object.hasOwn(k,le)&&!Object.hasOwn(L,le)&&(o.O(L[le],k[le])||T.push({command:Q,args:[B,le,k[le],K]}))}function xc(L){return L.id}function fl(L,k){return L[k.id]=k,L}const Co=new o.C(1,0,0,1),pu=new o.C(0,1,0,1),nc=new o.C(0,0,1,1),ad=new o.C(1,0,1,1),zr=new o.C(0,1,1,1);function Hi(L,k,T,B,K,Q,le){const me=L.context,we=L.transform,Me=me.gl,Re=we.projection.name==="globe",Ze=Re?["PROJECTION_GLOBE_VIEW"]:[];let Qe=o.Q(T.projMatrix);if(Re&&o.S(we.zoom)>0){const Yn=o.V(T.canonical,we),$n=o.W(Yn);Qe=o.X(new Float32Array(16),we.globeMatrix,$n),o.X(Qe,we.projMatrix,Qe)}const ht=o.Y();ht[12]+=2*K/(o.e.devicePixelRatio*we.width),ht[13]+=2*Q/(o.e.devicePixelRatio*we.height),o.X(Qe,ht,Qe);const _t=L.getOrCreateProgram("debug",{defines:Ze}),bt=k.getTileByID(T.key);L.terrain&&L.terrain.setupElevationDraw(bt,_t);const Mt=o.Z.disabled,es=o._.disabled,Qt=L.colorModeForRenderPass(),Lt="$debug";me.activeTexture.set(Me.TEXTURE0),L.emptyTexture.bind(Me.LINEAR,Me.CLAMP_TO_EDGE),Re?bt._makeGlobeTileDebugBuffers(L.context,we):bt._makeDebugTileBoundsBuffers(L.context,we.projection);const ps=bt._tileDebugBuffer||L.debugBuffer,Hs=bt._tileDebugIndexBuffer||L.debugIndexBuffer,Fs=bt._tileDebugSegments||L.debugSegments;if(_t.draw(L,Me.LINE_STRIP,Mt,es,Qt,o.$.disabled,o.a0(Qe,B.toPremultipliedRenderColor(null)),Lt,ps,Hs,Fs,null,null,null,[bt._globeTileDebugBorderBuffer]),le){const Yn=bt.latestRawTileData,$n=Math.floor((Yn&&Yn.byteLength||0)/1024);let zn=T.canonical.toString();T.overscaledZ!==T.canonical.z&&(zn+=` => ${T.overscaledZ}`),zn+=` ${bt.state}`,zn+=` ${$n}kb`,function(Dr,An){Dr.initDebugOverlayCanvas();const yr=Dr.debugOverlayCanvas,sa=Dr.context.gl,ka=Dr.debugOverlayCanvas.getContext("2d");ka.clearRect(0,0,yr.width,yr.height),ka.shadowColor="white",ka.shadowBlur=2,ka.lineWidth=1.5,ka.strokeStyle="white",ka.textBaseline="top",ka.font="bold 36px Open Sans, sans-serif",ka.fillText(An,5,5),ka.strokeText(An,5,5),Dr.debugOverlayTexture.update(yr),Dr.debugOverlayTexture.bind(sa.LINEAR,sa.CLAMP_TO_EDGE)}(L,zn)}const nn=k.getTile(T).tileSize,$s=512/Math.min(nn,512)*(T.overscaledZ/we.zoom)*.5,rn=bt._tileDebugTextBuffer||L.debugBuffer,_n=bt._tileDebugTextIndexBuffer||L.quadTriangleIndexBuffer,Mn=bt._tileDebugTextSegments||L.debugSegments;_t.draw(L,Me.TRIANGLES,Mt,es,o.a1.alphaBlended,o.$.disabled,o.a0(Qe,o.C.transparent.toPremultipliedRenderColor(null),$s),Lt,rn,_n,Mn,null,null,null,[bt._globeTileDebugTextBuffer])}function Bc(L,k,T,B){yc(L,0,k+T/2,L.transform.width,T,B)}function $c(L,k,T,B){yc(L,k-T/2,0,T,L.transform.height,B)}function yc(L,k,T,B,K,Q){const le=L.context,me=le.gl;me.enable(me.SCISSOR_TEST),me.scissor(k*o.e.devicePixelRatio,T*o.e.devicePixelRatio,B*o.e.devicePixelRatio,K*o.e.devicePixelRatio),le.clear({color:Q}),me.disable(me.SCISSOR_TEST)}function Ul(L,k,T){const B=L.context,K=B.gl,Q=T.projMatrix,le=L.getOrCreateProgram("debug"),me=k.getTileByID(T.key);L.terrain&&L.terrain.setupElevationDraw(me,le);const we=o.Z.disabled,Me=o._.disabled,Re=L.colorModeForRenderPass(),Ze="$debug";B.activeTexture.set(K.TEXTURE0),L.emptyTexture.bind(K.LINEAR,K.CLAMP_TO_EDGE);const Qe=me.queryGeometryDebugViz,ht=me.queryBoundsDebugViz;if(Qe&&Qe.vertices.length>0){Qe.lazyUpload(B);const _t=Qe.vertexBuffer,bt=Qe.indexBuffer,Mt=Qe.segments;_t!=null&&bt!=null&&Mt!=null&&le.draw(L,K.LINE_STRIP,we,Me,Re,o.$.disabled,o.a0(Q,Qe.color.toPremultipliedRenderColor(null)),Ze,_t,bt,Mt)}if(ht&&ht.vertices.length>0){ht.lazyUpload(B);const _t=ht.vertexBuffer,bt=ht.indexBuffer,Mt=ht.segments;_t!=null&&bt!=null&&Mt!=null&&le.draw(L,K.LINE_STRIP,we,Me,Re,o.$.disabled,o.a0(Q,ht.color.toPremultipliedRenderColor(null)),Ze,_t,bt,Mt)}}const rg=(L,k,T,B,K,Q,le,me)=>{const we=o.a6/Q.tileSize;return{u_matrix:L,u_inv_rot_matrix:k,u_camera_to_center_distance:T.getCameraToCenterDistance(me),u_extrude_scale:[T.pixelsToGLUnits[0]/we,T.pixelsToGLUnits[1]/we],u_zoom_transition:B,u_tile_id:le,u_merc_center:K}},Lx=(L,k,T,B)=>({u_matrix:L,u_inv_matrix:k,u_camera_to_center_distance:T.getCameraToCenterDistance(B),u_viewport_size:[T.width,T.height]});let Yo;const Ic={loaded:!0,validateStyle:function(L,k=o.s){return Rn($i(L,k))},validateSource:L=>Rn(Fn(L)),validateLight:L=>Rn(Or(L)),validateLights:L=>Rn(ca(L)),validateTerrain:L=>Rn(Jn(L)),validateFog:L=>Rn(Sr(L)),validateSnow:L=>Rn(function(k){const T=k.value,B=k.style,K=k.styleSpec,Q=K.snow;if(T===void 0)return[];if(!o.l(T))return[new rs("snow",T,`object expected, ${o.n(T)} found`)];let le=[];for(const me in T){const we=me.match(o.K);le=le.concat(we&&Q[we[1]]&&Q[we[1]].transition?ur({key:me,value:T[me],valueSpec:K.transition,style:B,styleSpec:K}):Q[me]?ur({key:me,value:T[me],valueSpec:Q[me],style:B,styleSpec:K}):[new St(me,T[me],`unknown property "${me}"`)])}return le}(L)),validateRain:L=>Rn(function(k){const T=k.value,B=k.style,K=k.styleSpec,Q=K.rain;if(T===void 0)return[];if(!o.l(T))return[new rs("rain",T,`object expected, ${o.n(T)} found`)];let le=[];for(const me in T){const we=me.match(o.K);le=le.concat(we&&Q[we[1]]&&Q[we[1]].transition?ur({key:me,value:T[me],valueSpec:K.transition,style:B,styleSpec:K}):Q[me]?ur({key:me,value:T[me],valueSpec:Q[me],style:B,styleSpec:K}):[new St(me,T[me],`unknown property "${me}"`)])}return le}(L)),validateLayer:L=>Rn(Er(L)),validateFilter:L=>Rn(Ws(L)),validatePaintProperty:L=>Rn(As(L)),validateLayoutProperty:L=>Rn(hr(L)),validateModel:L=>Rn(Lr(L)),diffStyles:function(L,k){if(!L)return[{command:xa,args:[k]}];let T=[];try{if(!o.O(L.version,k.version))return[{command:xa,args:[k]}];if(o.O(L.center,k.center)||T.push({command:"setCenter",args:[k.center]}),o.O(L.zoom,k.zoom)||T.push({command:"setZoom",args:[k.zoom]}),o.O(L.bearing,k.bearing)||T.push({command:"setBearing",args:[k.bearing]}),o.O(L.pitch,k.pitch)||T.push({command:"setPitch",args:[k.pitch]}),o.O(L.sprite,k.sprite)||T.push({command:"setSprite",args:[k.sprite]}),o.O(L.glyphs,k.glyphs)||T.push({command:"setGlyphs",args:[k.glyphs]}),o.O(L.imports,k.imports)||function(me=[],we=[],Me){we=we||[];const Re=(me=me||[]).map(xc),Ze=we.map(xc),Qe=me.reduce(fl,{}),ht=we.reduce(fl,{}),_t=Re.slice();let bt,Mt,es,Qt;for(bt=0,Mt=0;bt{me.source&&B[me.source]?T.push({command:ho,args:[me.id]}):Q.push(me)});let le=L.terrain;le&&B[le.source]&&(T.push({command:Nl,args:[void 0]}),le=void 0),T=T.concat(K),o.O(le,k.terrain)||T.push({command:Nl,args:[k.terrain]}),function(me,we,Me){we=we||[];const Re=(me=me||[]).map(xc),Ze=we.map(xc),Qe=me.reduce(fl,{}),ht=we.reduce(fl,{}),_t=Re.slice(),bt=Object.create(null);let Mt,es,Qt,Lt,ps,Hs,Fs;for(Mt=0,es=0;Mt0){const Vr=o.Y(),Za=Wr;o.aa(Vr,Mn.placementInvProjMatrix,Me.glCoordMatrix),o.aa(Vr,Vr,Mn.placementViewportMatrix),Mt.push({circleArray:Gr,circleOffset:Qt,transform:Za,invTransform:Vr,projection:Mn.getProjection()}),es+=Gr.length/4,Qt=es}if(!Mr)continue;L.terrain&&L.terrain.setupElevationDraw(_n,si);const Ga=Hr?[rn.canonical.x,rn.canonical.y,1<{const T=Ic[L];return T?T(...k):[]}}const _s=Xc("validateStyle"),Xa=Xc("validateSource"),No=Xc("validateLight"),Ba=Xc("validateLights"),io=Xc("validateTerrain"),ko=Xc("validateFog"),qi=Xc("validateSnow"),dm=Xc("validateRain"),Zo=Xc("validateLayer"),vo=Xc("validateFilter"),Zg=Xc("validatePaintProperty"),Ol=Xc("validateLayoutProperty"),zl=Xc("validateModel"),vy=o.s.light;let Xd;class Wh extends o.E{constructor(k,T="flat"){super(),this._transitionable=new o.af(Xd||(Xd=new o.ag({anchor:new o.ah(vy.anchor),position:new o.ai(vy.position),color:new o.ah(vy.color),intensity:new o.ah(vy.intensity)}))),this.setLight(k,T),this._transitioning=this._transitionable.untransitioned()}getLight(){return this._transitionable.serialize()}setLight(k,T,B={}){this._validate(No,k,B)||(this._transitionable.setTransitionOrValue(k),this.id=T)}updateTransitions(k){this._transitioning=this._transitionable.transitioned(k,this._transitioning)}hasTransition(){return this._transitioning.hasTransition()}recalculate(k){this.properties=this._transitioning.possiblyEvaluate(k)}_validate(k,T,B){return(!B||B.validate!==!1)&&cm(this,k.call(_s,{value:T,style:{glyphs:!0,sprite:!0},styleSpec:o.s}))}}const df=o.s.terrain;let Yy=class extends o.E{constructor(L,k,T,B,K){super(),this.scope=T,this._transitionable=new o.af(new o.ag({source:new o.ah(df.source),exaggeration:new o.ah(df.exaggeration)}),T,B),this._transitionable.setTransitionOrValue(L,B),this._transitioning=this._transitionable.untransitioned(),this.drapeRenderMode=k,this.worldview=K}get(){return this._transitionable.serialize()}set(L,k){this._transitionable.setTransitionOrValue(L,k)}updateTransitions(L){this._transitioning=this._transitionable.transitioned(L,this._transitioning)}hasTransition(){return this._transitioning.hasTransition()}recalculate(L){this.properties=this._transitioning.possiblyEvaluate(L)}getExaggeration(L){return this._transitioning.possiblyEvaluate(new o.aj(L,{worldview:this.worldview})).get("exaggeration")}getAttenuationRange(){if(!this.isZoomDependent())return null;const L=this._transitionable._values.exaggeration;if(!L)return null;const k=L.value.expression;if(!k)return null;let T=-1,B=-1,K=1;for(const Q of k.zoomStops)K=k.evaluate(new o.aj(Q,{worldview:this.worldview})),K>.01?(T=Q,B=-1):B=Q;return K<.01&&T>0&&B>T?[T,B]:null}isZoomDependent(){const L=this._transitionable._values.exaggeration;return L!=null&&L.value!=null&&L.value.expression!=null&&L.value.expression instanceof o.ak}};function oh(L,k){const T=L?L.terrain:null;return!!T&&(!k||!!k.projection.requiresDraping||!T.isZoomDependent()||T.getExaggeration(k.zoom)>0)}const xh=o.s.fog;class gt extends o.E{constructor(k,T,B,K){super();const Q=new o.ag({range:new o.ah(xh.range),color:new o.ah(xh.color),"color-use-theme":new o.ah({type:"string","property-type":"data-constant",default:"default"}),"high-color":new o.ah(xh["high-color"]),"high-color-use-theme":new o.ah({type:"string","property-type":"data-constant",default:"default"}),"space-color":new o.ah(xh["space-color"]),"space-color-use-theme":new o.ah({type:"string","property-type":"data-constant",default:"default"}),"horizon-blend":new o.ah(xh["horizon-blend"]),"star-intensity":new o.ah(xh["star-intensity"]),"vertical-range":new o.ah(xh["vertical-range"])});this._transitionable=new o.af(Q,B,K),this.set(k,K),this._transitioning=this._transitionable.untransitioned(),this._transform=T,this.properties=new o.al(Q),this.scope=B}get state(){const k=this._transform,T=k.projection.name==="globe",B=o.S(k.zoom),K=this.properties.get("range"),Q=[2,4.5],le=.5/Math.tan(.5*k._fov),me=[K[0]+le,K[1]+le];return{range:T?[o.am(Q[0],me[0],B),o.am(Q[1],me[1],B)]:me,horizonBlend:this.properties.get("horizon-blend"),alpha:this.properties.get("color").a}}get(){return this._transitionable.serialize()}set(k,T,B={}){if(this._validate(ko,k,B))return;const K={...k};for(const Q of Object.keys(xh))K[Q]===void 0&&(K[Q]=xh[Q].default);this._options=K,this._transitionable.setTransitionOrValue(this._options,T)}getOpacity(k){if(!this._transform.projection.supportsFog)return 0;const T=this.properties&&this.properties.get("color")||1;return(this._transform.projection.name==="globe"?1:o.an(o.ap,o.ao,k))*T.a}getOpacityAtLatLng(k,T){return this._transform.projection.supportsFog?o.aq(this.state,k,T):0}getOpacityForTile(k){if(!this._transform.projection.supportsFog)return[1,1];const T=this._transform.calculateFogTileMatrix(k.toUnwrapped());return o.ar(this.state,T,0,0,o.a6,o.a6,this._transform)}getOpacityForBounds(k,T,B,K,Q){return this._transform.projection.supportsFog?o.ar(this.state,k,T,B,K,Q,this._transform):[1,1]}getRangeForProjection(){return this._transform.projection.supportsFog?this.state.range:[0,1]}isVisibleOnFrustum(k){if(!this._transform.projection.supportsFog)return!1;const T=[4,5,6,7];for(const B of T){const K=k.points[B];let Q;if(K[2]>=0)Q=K;else{const le=k.points[B-4];Q=o.as(le,K,le[2]/(le[2]-K[2]))}if(o.at(this.state,Q[0],Q[1],0,this._transform)>=o.au)return!0}return!1}updateConfig(k){this._transitionable.setTransitionOrValue(this._options,k)}updateTransitions(k){this._transitioning=this._transitionable.transitioned(k,this._transitioning)}hasTransition(){return this._transitioning.hasTransition()}recalculate(k){this.properties=this._transitioning.possiblyEvaluate(k)}_validate(k,T,B){return(!B||B.validate!==!1)&&cm(this,k.call(_s,{value:T,style:{glyphs:!0,sprite:!0},styleSpec:o.s}))}}let We,ut,jt=class extends o.E{constructor(L,k,T,B){super();const K=We||(We=new o.ag({density:new o.ah(o.s.snow.density),intensity:new o.ah(o.s.snow.intensity),color:new o.ah(o.s.snow.color),opacity:new o.ah(o.s.snow.opacity),vignette:new o.ah(o.s.snow.vignette),"vignette-color":new o.ah(o.s.snow["vignette-color"]),"center-thinning":new o.ah(o.s.snow["center-thinning"]),direction:new o.ah(o.s.snow.direction),"flake-size":new o.ah(o.s.snow["flake-size"])}));this._transitionable=new o.af(K,T,B),this.set(L,B),this._transitioning=this._transitionable.untransitioned(),this.properties=new o.al(K),this.scope=T}get state(){const L=this.properties.get("opacity"),k=this.properties.get("color"),T=this.properties.get("direction"),B=o.av(T[0]),K=-Math.max(o.av(T[1]),.01),Q=[Math.cos(B)*Math.cos(K),Math.sin(B)*Math.cos(K),Math.sin(K)],le=this.properties.get("vignette"),me=this.properties.get("vignette-color"),we=new o.C(me.r,me.g,me.b,le);return{density:this.properties.get("density"),intensity:this.properties.get("intensity"),color:new o.C(k.r,k.g,k.b,k.a*L),direction:Q,centerThinning:this.properties.get("center-thinning"),flakeSize:this.properties.get("flake-size"),vignetteColor:we}}get(){return this._transitionable.serialize()}set(L,k,T={}){if(this._validate(qi,L,T))return;const B={...L},K=o.s.snow;for(const Q of Object.keys(K))B[Q]===void 0&&(B[Q]=K[Q].default);this._options=B,this._transitionable.setTransitionOrValue(this._options,k)}updateConfig(L){this._transitionable.setTransitionOrValue(this._options,L)}updateTransitions(L){this._transitioning=this._transitionable.transitioned(L,this._transitioning)}hasTransition(){return this._transitioning.hasTransition()}recalculate(L){this.properties=this._transitioning.possiblyEvaluate(L)}_validate(L,k,T){return(!T||T.validate!==!1)&&cm(this,L.call(_s,{value:k,style:{glyphs:!0,sprite:!0},styleSpec:o.s}))}},Rt=class extends o.E{constructor(L,k,T,B){super();const K=ut||(ut=new o.ag({density:new o.ah(o.s.rain.density),intensity:new o.ah(o.s.rain.intensity),color:new o.ah(o.s.rain.color),opacity:new o.ah(o.s.rain.opacity),vignette:new o.ah(o.s.rain.vignette),"vignette-color":new o.ah(o.s.rain["vignette-color"]),"center-thinning":new o.ah(o.s.rain["center-thinning"]),direction:new o.ah(o.s.rain.direction),"droplet-size":new o.ah(o.s.rain["droplet-size"]),"distortion-strength":new o.ah(o.s.rain["distortion-strength"])}));this._transitionable=new o.af(K,T,B),this.set(L,B),this._transitioning=this._transitionable.untransitioned(),this.properties=new o.al(K),this.scope=T}get state(){const L=this.properties.get("opacity"),k=this.properties.get("color"),T=this.properties.get("direction"),B=o.av(T[0]),K=-Math.max(o.av(T[1]),.01),Q=[Math.cos(B)*Math.cos(K),Math.sin(B)*Math.cos(K),Math.sin(K)],le=this.properties.get("vignette-color"),me=new o.C(le.r,le.g,le.b,this.properties.get("vignette"));return{density:this.properties.get("density"),intensity:this.properties.get("intensity"),color:new o.C(k.r,k.g,k.b,k.a*L),direction:Q,centerThinning:this.properties.get("center-thinning"),dropletSize:this.properties.get("droplet-size"),distortionStrength:this.properties.get("distortion-strength"),vignetteColor:me}}get(){return this._transitionable.serialize()}set(L,k,T={}){if(this._validate(dm,L,T))return;const B={...L},K=o.s.rain;for(const Q of Object.keys(K))B[Q]===void 0&&(B[Q]=K[Q].default);this._options=B,this._transitionable.setTransitionOrValue(this._options,k)}updateConfig(L){this._transitionable.setTransitionOrValue(this._options,L)}updateTransitions(L){this._transitioning=this._transitionable.transitioned(L,this._transitioning)}hasTransition(){return this._transitioning.hasTransition()}recalculate(L){this.properties=this._transitioning.possiblyEvaluate(L)}_validate(L,k,T){return(!T||T.validate!==!1)&&cm(this,L.call(_s,{value:k,style:{glyphs:!0,sprite:!0},styleSpec:o.s}))}};const zt={workerUrl:"",workerClass:null,workerParams:void 0};function Wt(L){return zt.workerClass!=null?new zt.workerClass:new self.Worker(zt.workerUrl,{name:L,type:"module",...zt.workerParams})}const ws="mapboxgl_preloaded_worker_pool";class Ms{constructor(k){this.active={},this.workers=null,this.name=k}acquire(k,T=Ms.workerCount){if(!this.workers)for(this.workers=[];this.workers.length{T.terminate()}),this.workers=null)}isPreloaded(){return!!this.active[ws]}numActive(){return Object.keys(this.active).length}}Ms.workerCount=2;class Ns{constructor(k,T,B="Worker",K=Ms.workerCount){this.workerPool=k,this.actors=[],this.currentActor=0,this.id=o.aw();const Q=this.workerPool.acquire(this.id,K);for(let le=0;le{this.ready=!0}).catch(()=>{})}send(k,T,B){return Promise.all(this.actors.map(K=>K.send(k,T,B)))}broadcast(k,T){for(const B of this.actors)B.notify(k,T)}getActor(){return this.currentActor=(this.currentActor+1)%this.actors.length,this.actors[this.currentActor]}remove(){this.actors.forEach(k=>{k.remove()}),this.actors=[],this.workerPool.release(this.id)}}Ns.Actor=o.ax;class Ps extends o.E{constructor(k,T,B,K){super(),this.scope=B,this._options=k,this.properties=new o.al(T),this._transitionable=new o.af(T,B,K),this._transitionable.setTransitionOrValue(k.properties),this._transitioning=this._transitionable.untransitioned()}updateConfig(k){this._transitionable.setTransitionOrValue(this._options.properties,k)}updateTransitions(k){this._transitioning=this._transitionable.transitioned(k,this._transitioning)}hasTransition(){return this._transitioning.hasTransition()}recalculate(k){this.properties=this._transitioning.possiblyEvaluate(k)}get(){return this._options.properties=this._transitionable.serialize(),this._options}set(k,T){this._options=k,this._transitionable.setTransitionOrValue(k.properties,T)}shadowsEnabled(){return!!this.properties&&this.properties.get("cast-shadows")===!0}}let fn;const xn=()=>fn||(fn=new o.ag({color:new o.ah(o.s.properties_light_ambient.color),"color-use-theme":new o.ah({type:"string",default:"default","property-type":"data-constant"}),intensity:new o.ah(o.s.properties_light_ambient.intensity)}));let bn;const Pn=()=>bn||(bn=new o.ag({direction:new o.ay(o.s.properties_light_directional.direction),color:new o.ah(o.s.properties_light_directional.color),"color-use-theme":new o.ah({type:"string",default:"default","property-type":"data-constant"}),intensity:new o.ah(o.s.properties_light_directional.intensity),"cast-shadows":new o.ah(o.s.properties_light_directional["cast-shadows"]),"shadow-quality":new o.ah(o.s.properties_light_directional["shadow-quality"]),"shadow-intensity":new o.ah(o.s.properties_light_directional["shadow-intensity"]),"shadow-draw-before-layer":new o.ah(o.s.properties_light_directional["shadow-draw-before-layer"])})),or=(L,k,T,B,K,Q,le,me,we,Me=[0,0,1])=>({u_matrix:L,u_normal_matrix:k,u_opacity:T,u_faux_facade_ao_intensity:B,u_camera_pos:K,u_tile_to_meter:Q,u_facade_emissive_chance:le,u_flood_light_color:me,u_flood_light_intensity:we,u_front_cutoff_params:Me}),tr=L=>({u_matrix:L}),sr=L=>({u_matrix:L}),br=o.az;async function vr(){return Promise.resolve()}function Va(L,k,T,B,K,Q,le,me){T.resetLayerRenderingStats(L);const we=L.context,Me=we.gl,Re=L.transform,Ze=T.paint.get("fill-extrusion-pattern"),Qe=T.paint.get("fill-extrusion-pattern-cross-fade"),ht=Ze.constantOr(null),_t=Ze.constantOr(1),bt=T.paint.get("fill-extrusion-opacity"),Mt=L.style.enable3dLights(),es=T.paint.get(Mt&&!_t?"fill-extrusion-ambient-occlusion-wall-radius":"fill-extrusion-ambient-occlusion-radius"),Qt=[T.paint.get("fill-extrusion-ambient-occlusion-intensity"),es],Lt=T.layout.get("fill-extrusion-edge-radius"),ps=Lt>0&&!T.paint.get("fill-extrusion-rounded-roof"),Hs=ps?0:Lt,Fs=Re.projection.name==="globe"?o.aE():0,nn=Re.projection.name==="globe",$s=nn?o.S(Re.zoom):0,rn=[o.a7(Re.center.lng),o.a8(Re.center.lat)],_n=T.paint.get("fill-extrusion-flood-light-color-use-theme").constantOr("default")==="none",Mn=T.paint.get("fill-extrusion-flood-light-color").toNonPremultipliedRenderColor(_n?null:T.lut).toArray01().slice(0,3),Yn=T.paint.get("fill-extrusion-flood-light-intensity"),$n=T.paint.get("fill-extrusion-vertical-scale"),zn=T.paint.get("fill-extrusion-line-width").constantOr(1)!==0,Dr=T.paint.get("fill-extrusion-height-alignment"),An=T.paint.get("fill-extrusion-base-alignment"),yr=o.aF(L,T.paint.get("fill-extrusion-cutoff-fade-range")),sa=T.paint.get("fill-extrusion-front-cutoff"),ka=Ht(Re.pitch,sa,!!L.terrain),Hr=ka[2]<1;Hr&&(L.maxFrontCutoffRawStart=Math.max(L.maxFrontCutoffRawStart,sa[0]));const ea=[];let si;nn&&ea.push("PROJECTION_GLOBE_VIEW"),Qt[0]>0&&ea.push("FAUX_AO"),ps&&ea.push("ZERO_ROOF_RADIUS"),me&&ea.push("HAS_CENTROID"),Yn>0&&ea.push("FLOOD_LIGHT"),yr.shouldRenderCutoff&&ea.push("RENDER_CUTOFF"),Hr&&ea.push("RENDER_FRONT_CUTOFF"),zn&&ea.push("RENDER_WALL_MODE");const Wr=L.renderPass==="shadow",Mr=L.shadowRenderer,Gr=Wr&&!!Mr,Ga=Wr?o.$.disabled:o.$.backCCW;L.shadowRenderer&&(L.shadowRenderer.useNormalOffset=!0);let Vr=[0,0,0];if(Mr){const Do=L.style.directionalLight,so=L.style.ambientLight;Do&&so&&(Vr=o.aG(L.style,Do,so)),Wr||(ea.push("RENDER_SHADOWS"),Mr.useNormalOffset&&ea.push("NORMAL_OFFSET")),si=ea.concat(["SHADOWS_SINGLE_CASCADE"])}const Za=Gr?"fillExtrusionDepth":_t?"fillExtrusionPattern":"fillExtrusion",Oi=T.getLayerRenderingStats();for(const Do of B){const so=k.getTile(Do),Vl=so.getBucket(T);if(!Vl||Vl.projection.name!==Re.projection.name)continue;let bu=!1;Mr&&(bu=Mr.getMaxCascadeForTile(Do.toUnwrapped())===0);const qc=L.isTileAffectedByFog(Do),Ko=Vl.programConfigurations.get(T.id);let no=!1;if(ht&&so.imageAtlas){const rc=so.imageAtlas,Oh=o.aH.from(ht),Zh=Oh.getPrimary().scaleSelf(o.e.devicePixelRatio).toString(),Ld=Oh.getSecondary(),_c=rc.patternPositions.get(Zh),Xh=Ld?rc.patternPositions.get(Ld.scaleSelf(o.e.devicePixelRatio).toString()):null;no=!!_c&&!!Xh,_c&&Ko.setConstantPatternPositions(_c,Xh)}Qe>0&&(no||Ko.getPatternTransitionVertexBuffer("fill-extrusion-pattern"))&&ea.push("FILL_EXTRUSION_PATTERN_TRANSITION");const jd=L.getOrCreateProgram(Za,{config:Ko,defines:bu?si:ea,overrideFog:qc});if(L.terrain&&L.terrain.setupElevationDraw(so,jd,{useMeterToDem:!0}),!Vl.centroidVertexBuffer){const rc=jd.getAttributeLocation(Me,"a_centroid_pos");rc!==-1&&Me.vertexAttribI4ui(rc,0,0,0,0)}!Wr&&Mr&&Mr.setupShadows(so.tileID.toUnwrapped(),jd,"vector-tile"),_t&&(L.context.activeTexture.set(Me.TEXTURE0),so.imageAtlasTexture&&so.imageAtlasTexture.bind(Me.LINEAR,Me.CLAMP_TO_EDGE),Ko.updatePaintBuffers());const Yh=T.paint.get("fill-extrusion-vertical-gradient"),wh=1/Vl.tileToMeter;let Hl;if(Wr&&Mr){if(rr(so.tileID,Vl.maxHeight,L))continue;const rc=Mr.calculateShadowPassMatrixFromTile(so.tileID.toUnwrapped());Hl=o.aN(rc,Hs,wh,$n,Dr,An)}else{const rc=L.translatePosMatrix(Do.expandedProjMatrix,so,T.paint.get("fill-extrusion-translate"),T.paint.get("fill-extrusion-translate-anchor")),Oh=Re.projection.createInversionMatrix(Re,Do.canonical),Zh=jd.fixedDefines.includes("LIGHTING_3D_MODE");Hl=_t?o.aI(rc,L,Yh,bt,Qt,Hs,wh,Do,so,Fs,Dr,An,$s,rn,Oh,Mn,$n,Qe,Zh):o.aJ(rc,L,Yh,bt,Qt,Hs,wh,Do,Fs,Dr,An,$s,rn,Oh,Mn,$n,Yn,Vr,ka,Zh)}L.uploadCommonUniforms(we,jd,Do.toUnwrapped(),null,yr);let fm=Vl.segments;if(Re.projection.name==="mercator"&&!Wr&&(fm=Vl.getVisibleSegments(so.tileID,L.terrain,L.transform.getFrustum(0)),!fm.get().length))continue;if(Oi)if(Wr)for(const rc of fm.get())Oi.numRenderedVerticesInShadowPass+=rc.primitiveLength;else for(const rc of fm.get())Oi.numRenderedVerticesInTransparentPass+=rc.primitiveLength;const bc=[];(L.terrain||me)&&bc.push(Vl.centroidVertexBuffer),nn&&bc.push(Vl.layoutVertexExtBuffer),zn&&bc.push(Vl.wallVertexBuffer),jd.draw(L,we.gl.TRIANGLES,K,Q,le,Ga,Hl,T.id,Vl.layoutVertexBuffer,Vl.indexBuffer,fm,T.paint,L.transform.zoom,Ko,bc)}L.shadowRenderer&&(L.shadowRenderer.useNormalOffset=!1)}class Je{constructor(){this.translate=[0,0],this.translateAnchor="map",this.edgeRadius=0,this.cutoffFadeRange=0}}function Ht(L,k,T){if(!(k[2]<1)||T)return[0,0,1];const B=180*L/Math.PI;if(B<15)return[-.5,k[1],k[2]];const K=Math.min(1,Math.max(0,(B-15)/5)),Q=K*K*(3-2*K);return[-.5*(1-Q)+k[0]*Q,k[1],k[2]]}function Ts(L,k,T,B,K,Q,le){B.centroidVertexArray.length===0&&B.createCentroidsBuffer();const me=Q?Q.findDEMTileFor(T):null;if(!(me&&me.dem||le))return;Q&&me&&me.dem&&B.selfDEMTileTimestamp!==me.dem._timestamp&&(B.borderDoneWithNeighborZ=[-1,-1,-1,-1],B.selfDEMTileTimestamp=me.dem._timestamp);const we=(Lt,ps)=>{(Lt.flags|ps.flags)&o.aK?(Lt.flags|=o.aK,ps.flags|=o.aK):(Lt.flags&=~o.aK,ps.flags&=~o.aK)},Me=Lt=>new o.P(Math.ceil((Lt+o.aL)*o.aM),0),Re=(Lt,ps,Hs)=>{const Fs=Math.ceil((Lt+o.aL)*o.aM),nn=Math.floor(Math.max(0,Math.min(o.a6-1,Hs))/4);return new o.P(Fs,nn<<5|(3&ps)<<3|7)},Ze=(Lt,ps)=>{const Hs=Number.MAX_VALUE,Fs=ps[0][0]!==Hs,nn=ps[1][0]!==Hs,$s=ps[2][0]!==Hs,rn=ps[3][0]!==Hs;if(!((Fs?1:0)+(nn?1:0)+($s?1:0)+(rn?1:0)>2))return Lt<2?$s===rn?void 0:$s?0:o.a6-1:Fs===nn?void 0:Fs?0:o.a6-1},Qe=(Lt,ps,Hs,Fs)=>(ps?Ze(Lt,ps):void 0)??(Fs?Ze(Hs,Fs):void 0),ht=Lt=>{const ps=k.getSource().minzoom,Hs=nn=>{const $s=k.getTileByID(nn);if($s&&$s.hasData())return $s.getBucket(K)},Fs=[0,-1,1];for(const nn of Fs){if(Lt.overscaledZ+nn(_t[0]=Math.min(Lt.min.y,ps.min.y),_t[1]=Math.max(Lt.max.y,ps.max.y),_t[2]=o.a6-ps.min.x>Lt.max.x?ps.min.x-o.a6:Lt.max.x,_t),Mt=(Lt,ps)=>(_t[0]=Math.min(Lt.min.x,ps.min.x),_t[1]=Math.max(Lt.max.x,ps.max.x),_t[2]=o.a6-ps.min.y>Lt.max.y?ps.min.y-o.a6:Lt.max.y,_t),es=[(Lt,ps)=>bt(Lt,ps),(Lt,ps)=>bt(ps,Lt),(Lt,ps)=>Mt(Lt,ps),(Lt,ps)=>Mt(ps,Lt)],Qt=(Lt,ps,Hs,Fs,nn,$s,rn)=>{if(!Q)return 0;const _n=[[$s?Hs:Lt,$s?Lt:Hs,0],[$s?Hs:ps,$s?ps:Hs,0]],Mn=rn<0?o.a6+rn:rn,Yn=[$s?Mn:(Lt+ps)/2,$s?(Lt+ps)/2:Mn,0];return Hs===0&&rn<0||Hs!==0&&rn>0?Q.getForTilePoints(nn,[Yn],!0,Fs):_n.push(Yn),Q.getForTilePoints(T,_n,!0,me),Math.max(_n[0][2],_n[1][2],Yn[2])/Q.exaggeration()};for(let Lt=0;Lt<4;Lt++){const ps=B.borderFeatureIndices[Lt];if(ps.length===0)continue;const Hs=o.aC[Lt](T),Fs=ht(Hs);if(!(Fs&&Fs instanceof o.aD))continue;const nn=Q?Q.findDEMTileFor(Hs):null;if(!(nn&&nn.dem||le)||(Q&&nn&&nn.dem&&B.borderDEMTileTimestamp[Lt]!==nn.dem._timestamp&&(B.borderDoneWithNeighborZ[Lt]=-1,B.borderDEMTileTimestamp[Lt]=nn.dem._timestamp),B.borderDoneWithNeighborZ[Lt]===Fs.canonical.z))continue;Fs.centroidVertexArray.length===0&&Fs.createCentroidsBuffer();const $s=(Lt<2?1:5)-Lt,rn=Fs.borderDoneWithNeighborZ[$s]!==B.canonical.z,_n=Fs.borderFeatureIndices[$s];let Mn=0;if(B.canonical.z!==Fs.canonical.z){for(const Dr of ps)B.showCentroid(B.featuresOnBorder[Dr],"discard");if(rn)for(const Dr of _n)Fs.showCentroid(Fs.featuresOnBorder[Dr],"discard");B.borderDoneWithNeighborZ[Lt]=Fs.canonical.z,Fs.borderDoneWithNeighborZ[$s]=B.canonical.z;continue}const Yn=new Map,$n=new Set,zn=new Set;for(let Dr=0;Dr<_n.length;Dr++){const An=Fs.featuresOnBorder[_n[Dr]];An.buildingId!==void 0&&Yn.set(An.buildingId,Dr)}for(const Dr of ps){const An=B.featuresOnBorder[Dr],yr=B.centroidData.get(An.centroidDataIndex);if(An.buildingId===void 0)continue;const sa=Yn.get(An.buildingId);if(sa===void 0)continue;const ka=Fs.featuresOnBorder[_n[sa]],Hr=Fs.centroidData.get(ka.centroidDataIndex);$n.add(Dr),zn.add(sa),le&&we(yr,Hr);const ea=yr.groupCentroidPos.x!==0||yr.groupCentroidPos.y!==0?yr.groupCentroidPos:An.centroid(),si=Hr.groupCentroidPos.x!==0||Hr.groupCentroidPos.y!==0?Hr.groupCentroidPos:ka.centroid(),Wr=Q?void 0:Qe(Lt,An.borders,$s,ka.borders),Mr=Wr!==void 0?Wr:Lt<2?Math.round((ea.y+si.y)/2):Math.round((ea.x+si.x)/2),Gr=An.intersectsCount()>1||ka.intersectsCount()>1;{let Ga=0;if(nn&&nn.dem&&!Gr){const Vr=es[Lt](yr,Hr),Za=Lt%2?o.a6-1:0;Ga=Qt(Vr[0],Math.min(o.a6-1,Vr[1]),Za,nn,Hs,Lt<2,Vr[2])}yr.centroidXY=Re(Ga,Lt,Mr),Hr.centroidXY=Re(Ga,$s,Mr)}if(B.writeCentroidToBuffer(yr),Fs.writeCentroidToBuffer(Hr),An.buildingId!==void 0){for(const Ga of B.centroidData)Ga.buildingId===An.buildingId&&Ga!==yr&&(Ga.centroidXY=yr.centroidXY,B.writeCentroidToBuffer(Ga));for(const Ga of Fs.centroidData)Ga.buildingId===An.buildingId&&Ga!==Hr&&(Ga.centroidXY=Hr.centroidXY,Fs.writeCentroidToBuffer(Ga))}}for(const Dr of ps){if($n.has(Dr))continue;const An=B.featuresOnBorder[Dr],yr=B.centroidData.get(An.centroidDataIndex),sa=An.borders[Lt];let ka;for(;Mn<_n.length;){if(zn.has(Mn)){Mn++;continue}ka=Fs.featuresOnBorder[_n[Mn]];const Hr=ka.borders[$s];if(Hr[1]>sa[0]+3||Hr[0]>sa[0]-3)break;Fs.showCentroid(ka,"keep"),Mn++}if(ka&&Mn<_n.length){let Hr=Mn,ea=0;for(;;)if(zn.has(Mn)){if(++Mn===_n.length)break;ka=Fs.featuresOnBorder[_n[Mn]]}else{if(ka.borders[$s][0]>sa[1]-3||(ea++,++Mn===_n.length))break;ka=Fs.featuresOnBorder[_n[Mn]]}for(;Hr<_n.length&&zn.has(Hr);)Hr++;if(Hr>=_n.length){B.showCentroid(An,"keep");continue}ka=Fs.featuresOnBorder[_n[Hr]];let si=!1;if(ea>=1){const Gr=ka.borders[$s];Math.abs(sa[0]-Gr[0])<3&&Math.abs(sa[1]-Gr[1])<3&&(ea=1,si=!0,Mn=Hr+1)}else if(ea===0){B.showCentroid(An,"keep");continue}const Wr=Fs.centroidData.get(ka.centroidDataIndex);le&&si&&we(yr,Wr);const Mr=An.intersectsCount()>1||ka.intersectsCount()>1;if(ea>1)Mn=Hr,yr.centroidXY=Wr.centroidXY=new o.P(0,0);else if(nn&&nn.dem&&!Mr){const Gr=es[Lt](yr,Wr),Ga=Lt%2?o.a6-1:0,Vr=Qt(Gr[0],Math.min(o.a6-1,Gr[1]),Ga,nn,Hs,Lt<2,Gr[2]);yr.centroidXY=Wr.centroidXY=Me(Vr)}else if(Mr){const Gr=Q?void 0:Qe(Lt,An.borders,$s,ka.borders);Gr!==void 0?(yr.centroidXY=Re(0,Lt,Gr),Wr.centroidXY=Re(0,$s,Gr)):yr.centroidXY=Wr.centroidXY=new o.P(0,0)}else yr.centroidXY=B.encodeBorderCentroid(An),Wr.centroidXY=Fs.encodeBorderCentroid(ka);B.writeCentroidToBuffer(yr),Fs.writeCentroidToBuffer(Wr)}else B.showCentroid(An,"keep")}B.borderDoneWithNeighborZ[Lt]=Fs.canonical.z,Fs.borderDoneWithNeighborZ[$s]=B.canonical.z}(B.needsCentroidUpdate||!B.centroidVertexBuffer&&B.centroidVertexArray.length!==0)&&B.uploadCentroid(L)}const ln=[1,0,0],tn=[0,1,0],nr=[0,0,1];function rr(L,k,T){const B=T.transform,K=T.shadowRenderer;if(!K)return!0;const Q=T.frameCounter,le=T.currentShadowCascade;let me=T._shadowCullCache;if(!me||me.frame!==Q||me.cascade!==le){const es=B.tileSize*K._cascades[le].scale,Qt=B.scaleZoom(es),Lt=K.shadowDirection,ps=[Lt[0],Lt[1],-Lt[2]],Hs=[ln,tn,nr,ps,[ps[0],0,ps[2]],[0,ps[1],ps[2]]];me={frame:Q,cascade:le,cameraFrustum:o.aA.fromInvProjectionMatrix(B.invProjMatrix,B.worldSize,Qt,B.projection.name!=="globe"),edges:Hs,shadowDir:ps,ws:es,zoom:Qt},T._shadowCullCache=me}const{cameraFrustum:we,edges:Me,shadowDir:Re,ws:Ze,zoom:Qe}=me;let ht=k;if(B.elevation){const es=B.elevation.getMinMaxForTile(L);es&&(ht+=es.max)}ht/=o.aB(B.center.lat,Qe);const _t=K.computeSimplifiedTileShadowVolume(L.toUnwrapped(),ht,Ze,Re);if(!_t)return!1;const{vertices:bt,planes:Mt}=_t;return we.intersectsPrecise(bt,Mt,Me)===0||K.getCurrentCascadeFrustum().intersectsPrecise(bt,Mt,Me)===0}const Qr=new Float32Array(16),na=new Float32Array(16);function $a(L){const{painter:k,source:T,layer:B,coords:K}=L;let Q=L.defines;const le=k.context,me=k.renderPass==="shadow",we=k.renderPass==="light-beam",Me=k.shadowRenderer,Re=o.aB(k.transform.center.lat,k.transform.zoom),Ze=o.aF(k,B.paint.get("building-cutoff-fade-range"));Ze.shouldRenderCutoff&&(Q=Q.concat("RENDER_CUTOFF"));const Qe=B.paint.get("building-front-cutoff"),ht=Qe[2]<1&&!k.terrain,_t=Ht(k.transform.pitch,Qe,!!k.terrain);ht&&(Q=Q.concat("RENDER_FRONT_CUTOFF"),k.maxFrontCutoffRawStart=Math.max(k.maxFrontCutoffRawStart,Qe[0])),L.floodLightIntensity>0&&(Q=Q.concat("FLOOD_LIGHT"));for(const bt of K){const Mt=T.getTile(bt),es=Mt.getBucket(B);if(!es)continue;Me&&Me.getMaxCascadeForTile(bt.toUnwrapped())===0&&(Q=Q.concat("SHADOWS_SINGLE_CASCADE"));const Qt=es.programConfigurations.get(B.id);let Lt,ps;const Hs=k.translatePosMatrix(bt.expandedProjMatrix,Mt,[0,0],"map");o.aO(Qr,Hs,[1,1,L.verticalScale]);const Fs=Qr;let nn;if(me&&Me){if(rr(Mt.tileID,es.maxHeight*Re,k))continue;const rn=Me.calculateShadowPassMatrixFromTile(Mt.tileID.toUnwrapped());o.aO(rn,rn,[1,1,L.verticalScale]),nn=sr(rn),Lt=ps=k.getOrCreateProgram("buildingDepth",{config:Qt,defines:Q,overrideFog:!1})}else if(we)Lt=ps=k.getOrCreateProgram("buildingBloom",{config:Qt,defines:Q,overrideFog:!1}),nn=tr(Fs);else{const rn=k.transform.calculatePosMatrix(bt.toUnwrapped(),k.transform.worldSize);o.aO(rn,rn,[1,1,L.verticalScale]),o.aO(na,rn,[1,-1,1/Re]),o.aP(na,na),o.aQ(na,na);const _n=na,Mn=k.transform.getFreeCameraOptions().position,Yn=1<{if(we){const Mn=rn.entranceBloom;_n.draw(k,le.gl.TRIANGLES,L.depthMode,o._.disabled,L.blendMode,o.$.disabled,nn,B.id,Mn.layoutVertexBuffer,Mn.indexBuffer,Mn.segmentsBucket,B.paint,k.transform.zoom,Qt,[Mn.layoutAttenuationBuffer,Mn.layoutColorBuffer])}else{const Mn=rn.segmentsBucket;let Yn=[rn.layoutNormalBuffer,rn.layoutCentroidBuffer,rn.layoutColorBuffer,rn.layoutFloodLightDataBuffer];rn.layoutFacadePaintBuffer&&(Yn=Yn.concat([rn.layoutFacadeDataBuffer,rn.layoutFacadeVerticalRangeBuffer,rn.layoutFacadePaintBuffer])),_n.draw(k,le.gl.TRIANGLES,L.depthMode,o._.disabled,L.blendMode,me?o.$.disabled:o.$.backCW,nn,B.id,rn.layoutVertexBuffer,rn.indexBuffer,Mn,B.paint,k.transform.zoom,Qt,Yn)}};k.uploadCommonUniforms(le,ps,bt.toUnwrapped(),null,Ze),es.buildingWithoutFacade&&$s(es.buildingWithoutFacade,ps),es.buildingWithFacade&&(Lt!==ps&&k.uploadCommonUniforms(le,Lt,bt.toUnwrapped(),null,Ze),$s(es.buildingWithFacade,Lt))}}function Na(L,k,T,B,K,Q,le,me,we,Me,Re,Ze,Qe,ht){const _t=L.context.gl,bt=L.depthModeForSublayer(1,o.Z.ReadOnly,_t.LEQUAL,!0),Mt=o.am(.1,3,Re),es=L._showOverdrawInspector,Qt=Ze,Lt=new Je;if(!es){const ps=new o._({func:_t.ALWAYS,mask:255},255,255,_t.KEEP,_t.KEEP,_t.REPLACE),Hs=new o.a1([_t.ONE,_t.ONE,_t.ONE,_t.ONE],o.C.transparent,[!1,!1,!1,!0],_t.MIN);o.aR(Lt,L,k,T,B,bt,ps,Hs,o.$.disabled,K,"sdf",Q,le,me,we,Me,Mt,Qt,!1,void 0)}{const ps=es?o._.disabled:new o._({func:_t.EQUAL,mask:255},255,255,_t.KEEP,_t.DECR,_t.DECR),Hs=es?L.colorModeForRenderPass():new o.a1([_t.ONE_MINUS_DST_ALPHA,_t.DST_ALPHA,_t.ONE,_t.ONE],o.C.transparent,[!0,!0,!0,!0]);o.aR(Lt,L,k,T,B,bt,ps,Hs,o.$.disabled,K,"color",Q,le,me,we,Me,Mt,Qt,!1,void 0)}}class La{constructor(){this._previousClosestBuildingId=null,this._hysteresisRatio=.8,this._indoorMinimumZoom=16}findClosestBuilding(k,T,B,K,Q){if(Bwe*this._hysteresisRatio&&(le=this._previousClosestBuildingId):Me&&!le&&(le=this._previousClosestBuildingId),this._previousClosestBuildingId=le,le}_calculateDistance(k,T){if(!T.center)return Number.MAX_VALUE;const B=k.lat-T.center[1],K=k.lng-T.center[0];return B*B+K*K}_isBuildingVisible(k,T,B){if(!B)return!1;for(const K of k.floorIds){const Q=k.floors[K];if(!Q.geometry)continue;const le=Q.geometry;if(le.type==="Polygon"){const me=this._convertRingToPoints(le.coordinates[0]);if(o.aU(me,B))return!0}else if(le.type==="MultiPolygon"){const me=this._convertMultiPolygonToPoints(le.coordinates);if(o.aV(B,me))return!0}}return!1}_convertRingToPoints(k){return k.map(T=>new o.P(T[0],T[1]))}_convertMultiPolygonToPoints(k){return k.map(T=>T.length===0?[]:T[0].map(B=>new o.P(B[0],B[1])))}}const to=.05,xo=(L,k,T,B,K,Q,le,me,we,Me,Re,Ze)=>({u_matrix:L,u_normalize_matrix:k,u_globe_matrix:T,u_merc_matrix:B,u_grid_matrix:K,u_tl_parent:Q,u_scale_parent:Me,u_fade_t:Re.mix,u_opacity:Re.opacity,u_image0:0,u_image1:1,u_raster_elevation:Ze,u_zoom_transition:le,u_merc_center:me,u_cutoff_params:we}),oo=(L,k,T,B,K,Q,le,me,we,Me)=>({u_particle_texture:L,u_particle_texture_side_len:k,u_tile_offset:T,u_velocity:B,u_color_ramp:Q,u_velocity_res:K,u_max_speed:le,u_uv_offset:me,u_data_scale:[255*we[0],255*we[1]],u_data_offset:Me,u_particle_pos_scale:1.1,u_particle_pos_offset:[to,to]}),Lo=(L,k,T,B,K,Q,le,me,we,Me)=>({u_particle_texture:L,u_particle_texture_side_len:k,u_velocity:T,u_velocity_res:B,u_max_speed:K,u_speed_factor:Q,u_reset_rate:le,u_rand_seed:Math.random(),u_uv_offset:me,u_data_scale:[255*we[0],255*we[1]],u_data_offset:Me,u_particle_pos_scale:1.1,u_particle_pos_offset:[to,to]});function ql(L,[k,T,B,K],[Q,le]){if(Q===le)return[0,0,0,0];const me=255*(L-1)/(L*(le-Q));return[k*me,T*me,B*me,K*me]}function po(L,k,[T,B]){return T===B?0:.5/L+(k-T)*(L-1)/(L*(B-T))}var nl=o.a$([{name:"a_index",type:"Int16",components:1}]);class Il{constructor(k,T,B,K){const Q={width:B[0],height:B[1],data:null},le=k.gl;this.targetColorTexture=new o.T(k,Q,le.RGBA8,{useMipmap:!1}),this.backgroundColorTexture=new o.T(k,Q,le.RGBA8,{useMipmap:!1}),this.context=k,this.updateParticleTexture(T,K),this.lastInvalidatedAt=0}updateParticleTexture(k,T){if(this.particleTextureDimension===T.width)return;(this.particleTexture0||this.particleTexture1||this.particleIndexBuffer||this.particleSegment)&&(this.particleTexture0.destroy(),this.particleTexture1.destroy(),this.particleIndexBuffer.destroy(),this.particleSegment.destroy());const B=this.context.gl,K=T.width*T.height;this.particleTexture0=new o.T(this.context,T,B.RGBA8,{premultiply:!1,useMipmap:!1}),this.particleTexture1=new o.T(this.context,T,B.RGBA8,{premultiply:!1,useMipmap:!1});const Q=new o.b0;Q.reserve(K);for(let le=0;le0){const Q=o.e.now(),le=(Q-L.timeAdded)/K,me=k?(Q-k.timeAdded)/K:-1,we=T.getSource(),Me=B.coveringZoomLevel({tileSize:we.tileSize,roundZoom:we.roundZoom}),Re=!k||Math.abs(k.tileID.overscaledZ-Me)>Math.abs(L.tileID.overscaledZ-Me),Ze=Re&&L.refreshedUponExpiration?1:o.b1(Re?le:1-me,0,1);return k?{opacity:1,mix:1-Ze,isFading:le<1}:{opacity:Ze,mix:0,isFading:le<1}}return{opacity:1,mix:0,isFading:!1}}function iu(L,k,T){if(!L)return null;const B=k.getTextureDescriptor(L,T,!0);if(!B)return null;let{texture:K,mix:Q,offset:le,tileSize:me,buffer:we,format:Me}=B;if(!K||!Me)return null;let Re=!1;return Me==="uint32"&&(Re=!0,Q[3]=0,Q=ql(o.ba,Q,[0,T.paint.get("raster-particle-max-speed")]),le=po(o.ba,le,[0,T.paint.get("raster-particle-max-speed")])),{texture:K,textureOffset:[we/(me+2*we),me/(me+2*we)],tileSize:me,scalarData:Re,scale:Q,offset:le,defines:["RASTER_ARRAY",{uint8:"DATA_FORMAT_UINT8",uint16:"DATA_FORMAT_UINT16",uint32:"DATA_FORMAT_UINT32"}[Me]]}}function Ut(L){const k=L._nearZ,T=L.projection.farthestPixelDistance(L),B=T-k,K=.2*L.height,Q=k+K;return[k,T,(Q-K-k)/B,(Q-k)/B]}var Cn=`#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;}`;o.bb["_prelude_raster_particle.glsl"]||(o.bb["_prelude_raster_particle.glsl"]=Cn);var ar={building:o.bc(`#include "_prelude_fog.fragment.glsl" #include "_prelude_shadow.fragment.glsl" #include "_prelude_lighting.glsl" #include "_prelude_indicator_cutout.fragment.glsl" #include "_prelude_feature_cutout.fragment.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; #if defined(RENDER_FRONT_CUTOFF) || defined(ROUTE_CORRIDOR) in float v_dither_opacity; #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 (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;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; #if defined(RENDER_FRONT_CUTOFF) || defined(ROUTE_CORRIDOR) if (v_dither_opacity < 1.0) {int index=viewport_dither_index(gl_FragCoord.xy);if (v_dither_opacity < DITHER_THRESHOLDS[index]) {discard;}} #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" #include "_prelude_feature_cutout.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; #if defined(RENDER_FRONT_CUTOFF) || defined(ROUTE_CORRIDOR) #ifdef RENDER_FRONT_CUTOFF uniform vec3 u_front_cutoff_params; #endif out float v_dither_opacity; #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;float frontCutoffOpacity=1.0;float routeFade=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 {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);frontCutoffOpacity=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; #if defined(RENDER_FRONT_CUTOFF) || defined(ROUTE_CORRIDOR) v_dither_opacity=1.0; #ifdef RENDER_FRONT_CUTOFF v_dither_opacity=min(v_dither_opacity,frontCutoffOpacity); #endif #endif }`),buildingBloom:o.bc(`in vec4 v_color_emissive; #pragma mapbox: define-attribute highp vec4 bloom_attenuation float saturate(float val) {return clamp(val,0.0,1.0);}void main() { #pragma mapbox: initialize-attribute highp vec4 bloom_attenuation 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:o.bc("void main() {}","in vec3 a_pos_3f;uniform mat4 u_matrix;void main() {gl_Position=u_matrix*vec4(a_pos_3f,1.0);}"),rasterParticle:o.bc(`#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:o.bc("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:o.bc("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:o.bc(`#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);}"),snowParticle:o.bc("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:o.bc("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:o.bc("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);}"),elevatedStructuresDepth:o.bc("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;}"),elevatedStructures:o.bc(`#include "_prelude_fog.fragment.glsl" #include "_prelude_lighting.glsl" #include "_prelude_shadow.fragment.glsl" #include "_prelude_indicator_cutout.fragment.glsl" #include "_prelude_feature_cutout.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;uniform float u_opacity_multiplier; #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 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);out_color*=u_opacity_multiplier;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 }`),elevatedStructuresDepthReconstruct:o.bc(`#include "_prelude_feature_cutout.fragment.glsl" #ifdef DEPTH_RECONSTRUCTION in float v_height; #endif void main() { #ifdef DEPTH_RECONSTRUCTION if (v_height >=0.0) discard; #else #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;}`)};o.bc(Cn,"");const ra=o.a$([{type:"Float32",name:"a_pos_3f",components:3},{type:"Float32",name:"a_uv",components:2},{type:"Float32",name:"a_rainParticleData",components:4}]),Zr=o.a$([{type:"Float32",name:"a_pos_2f",components:2}]);class Aa{destroy(){this.vignetteVx&&this.vignetteVx.destroy(),this.vignetteIdx&&this.vignetteIdx.destroy()}draw(k,T){const B=k.getOrCreateProgram("vignette");if(!this.vignetteVx||!this.vignetteIdx){const le=new o.bd,me=new o.ae;le.emplaceBack(-1,-1),le.emplaceBack(1,-1),le.emplaceBack(1,1),le.emplaceBack(-1,1),me.emplaceBack(0,1,2),me.emplaceBack(0,2,3),this.vignetteVx=k.context.createVertexBuffer(le,Zr.members),this.vignetteIdx=k.context.createIndexBuffer(me)}const K=o.ad.simpleSegment(0,0,4,6);if(this.vignetteVx&&this.vignetteIdx){k.uploadCommonUniforms(k.context,B);const le={u_vignetteShape:(Q={vignetteShape:[T.start,T.range,Math.pow(10,T.fadePower)],vignetteColor:[T.color.r,T.color.g,T.color.b,T.color.a*T.strength]}).vignetteShape,u_vignetteColor:Q.vignetteColor};B.draw(k,k.context.gl.TRIANGLES,o.Z.disabled,o._.disabled,o.a1.alphaBlended,o.$.disabled,le,"vignette",this.vignetteVx,this.vignetteIdx,K)}var Q}}class xi{constructor(){this._accumulatedOffsetX=0,this._accumulatedOffsetY=0,this._accumulatedElevation=0}update(k,T){const B=k.getFreeCameraOptions().position,K=B.toAltitude(),Q=B.toLngLat(),le=o.av(Q.lng),me=o.av(Q.lat),we=k.pixelsPerMeter/T,Me=le*o.bk,Re=o.bk*Math.log(Math.tan(Math.PI/4+me/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 Ze=-this._offsetYPrev+Re,Qe=-this._elevationPrev+K;this._accumulatedOffsetX+=(-this._offsetXPrev+Me)*we,this._accumulatedOffsetY+=Ze*we,this._accumulatedElevation+=Qe*we,this._offsetXPrev=Me,this._offsetYPrev=Re,this._elevationPrev=K}}getPosition(){return[this._accumulatedOffsetX,this._accumulatedOffsetY,this._accumulatedElevation]}}function Ia(L,k){return[-(L[0]-Math.floor(L[0]/k)*k),-(L[1]-Math.floor(L[1]/k)*k),-(L[2]-Math.floor(L[2]/k)*k)]}function el(L){const k=o.bj(1323123451230),T=[];for(let B=0;B({u_matrix:L,u_depth_bias:k}),um=(L,k)=>({u_matrix:L,u_ground_shadow_factor:k,u_opacity_multiplier:1}),Td=(L,k,T,B,K)=>({u_matrix:L,u_camera_pos:[k[0],k[1],k[2]],u_depth_bias:T,u_height_scale:B,u_reset_depth:K}),gu={building:L=>({u_matrix:new o.a4(L),u_normal_matrix:new o.a4(L),u_opacity:new o.a3(L),u_faux_facade_ao_intensity:new o.a3(L),u_camera_pos:new o.a5(L),u_tile_to_meter:new o.a3(L),u_facade_emissive_chance:new o.a3(L),u_flood_light_color:new o.a5(L),u_flood_light_intensity:new o.a3(L),u_front_cutoff_params:new o.a5(L)}),buildingBloom:L=>({u_matrix:new o.a4(L)}),buildingDepth:L=>({u_matrix:new o.a4(L)}),elevatedStructuresDepth:L=>({u_matrix:new o.a4(L),u_depth_bias:new o.a3(L)}),elevatedStructures:L=>({u_matrix:new o.a4(L),u_ground_shadow_factor:new o.a5(L),u_opacity_multiplier:new o.a3(L)}),elevatedStructuresDepthReconstruct:L=>({u_matrix:new o.a4(L),u_camera_pos:new o.a5(L),u_depth_bias:new o.a3(L),u_height_scale:new o.a3(L),u_reset_depth:new o.a3(L)}),rasterParticle:L=>({u_matrix:new o.a4(L),u_normalize_matrix:new o.a4(L),u_globe_matrix:new o.a4(L),u_merc_matrix:new o.a4(L),u_grid_matrix:new o.a_(L),u_tl_parent:new o.a2(L),u_scale_parent:new o.a3(L),u_fade_t:new o.a3(L),u_opacity:new o.a3(L),u_image0:new o.aY(L),u_image1:new o.aY(L),u_raster_elevation:new o.a3(L),u_zoom_transition:new o.a3(L),u_merc_center:new o.a2(L),u_cutoff_params:new o.aZ(L)}),rasterParticleTexture:L=>({u_texture:new o.aY(L),u_opacity:new o.a3(L)}),rasterParticleDraw:L=>({u_particle_texture:new o.aY(L),u_particle_texture_side_len:new o.a3(L),u_tile_offset:new o.a2(L),u_velocity:new o.aY(L),u_color_ramp:new o.aY(L),u_velocity_res:new o.a2(L),u_max_speed:new o.a3(L),u_uv_offset:new o.a2(L),u_data_scale:new o.a2(L),u_data_offset:new o.a3(L),u_particle_pos_scale:new o.a3(L),u_particle_pos_offset:new o.a2(L)}),rasterParticleUpdate:L=>({u_particle_texture:new o.aY(L),u_particle_texture_side_len:new o.a3(L),u_velocity:new o.aY(L),u_velocity_res:new o.a2(L),u_max_speed:new o.a3(L),u_speed_factor:new o.a3(L),u_reset_rate:new o.a3(L),u_rand_seed:new o.a3(L),u_uv_offset:new o.a2(L),u_data_scale:new o.a2(L),u_data_offset:new o.a3(L),u_particle_pos_scale:new o.a3(L),u_particle_pos_offset:new o.a2(L)}),snowParticle:L=>({u_modelview:new o.a4(L),u_projection:new o.a4(L),u_time:new o.a3(L),u_cam_pos:new o.a5(L),u_velocityConeAperture:new o.a3(L),u_velocity:new o.a3(L),u_horizontalOscillationRadius:new o.a3(L),u_horizontalOscillationRate:new o.a3(L),u_boxSize:new o.a3(L),u_billboardSize:new o.a3(L),u_simpleShapeParameters:new o.a2(L),u_screenSize:new o.a2(L),u_thinningCenterPos:new o.a2(L),u_thinningShape:new o.a5(L),u_thinningAffectedRatio:new o.a3(L),u_thinningParticleOffset:new o.a3(L),u_particleColor:new o.aZ(L),u_direction:new o.a5(L)}),rainParticle:L=>({u_modelview:new o.a4(L),u_projection:new o.a4(L),u_time:new o.a3(L),u_cam_pos:new o.a5(L),u_texScreen:new o.aY(L),u_velocityConeAperture:new o.a3(L),u_velocity:new o.a3(L),u_boxSize:new o.a3(L),u_rainDropletSize:new o.a2(L),u_distortionStrength:new o.a3(L),u_rainDirection:new o.a5(L),u_color:new o.aZ(L),u_screenSize:new o.a2(L),u_thinningCenterPos:new o.a2(L),u_thinningShape:new o.a5(L),u_thinningAffectedRatio:new o.a3(L),u_thinningParticleOffset:new o.a3(L),u_shapeDirectionalPower:new o.a3(L),u_shapeNormalPower:new o.a3(L),u_mode:new o.a3(L)}),vignette:L=>({u_vignetteShape:new o.a5(L),u_vignetteColor:new o.aZ(L)})};function Qc(L,k){const T=1<0;--T){const B=Math.floor(k.x/(1<0;--Ze){const Qe=Math.floor(k.x/(1<me[Qt]!=bt>me[Qt]&&le[Qt]B&&(Mt|=2),htK&&(Mt|=8),_tB&&(es|=2),btK&&(es|=8),!(Mt&es)&&(Mt===0||es===0||Ud(Qe,ht,_t,bt,k,T,B,K)))return!1}}for(let we=0;we<4;++we)if(!(1&Q[we]))return!1;return!0}function Ud(L,k,T,B,K,Q,le,me){const we=(Me,Re,Ze,Qe,ht,_t,bt,Mt)=>{const es=(Ze-Me)*(_t-Re)-(Qe-Re)*(ht-Me),Qt=(Ze-Me)*(Mt-Re)-(Qe-Re)*(bt-Me);if(es>0&&Qt>0||es<0&&Qt<0)return!1;const Lt=(bt-ht)*(Re-_t)-(Mt-_t)*(Me-ht),ps=(bt-ht)*(Qe-_t)-(Mt-_t)*(Ze-ht);return!(Lt>0&&ps>0||Lt<0&&ps<0)};return!!(we(L,k,T,B,K,Q,le,Q)||we(L,k,T,B,le,Q,le,me)||we(L,k,T,B,K,me,le,me)||we(L,k,T,B,K,Q,K,me))}class od{constructor(){this._tileCoverages=[],this._snapshot=new lh}clear(){this._tileCoverages=[]}addTileCoverage(k,T){this._tileCoverages.push({tileId:k,polygons:T,frcMask:id(T)})}empty(){return this._tileCoverages.length===0}updateSnapshotIfNeeded(){if(this._snapshot.equals(this._tileCoverages))return this._snapshot;const k=this._tileCoverages.map(T=>({tileId:T.tileId,polygons:T.polygons,frcMask:T.frcMask}));return this._snapshot=new lh(k),this._snapshot}}function Lh(L,k){const T={};if(!k)return T;for(const B of L){const K=B.layerIds.map(Q=>k.getLayer(Q)).filter(Boolean);if(K.length!==0){B.layers=K,B.stateDependentLayerIds&&(B.stateDependentLayers=B.stateDependentLayerIds.map(Q=>K.filter(le=>le.id===Q)[0])),B.updateExpressions&&B.updateExpressions(K);for(const Q of K)T[Q.fqid]=B}}return T}const Gu=32,qd=33,hd=new Uint16Array(8184);for(let L=0;L<2046;L++){let k=L+2,T=0,B=0,K=0,Q=0,le=0,me=0;for(1&k?K=Q=le=Gu:T=B=me=Gu;(k>>=1)>1;){const Me=T+K>>1,Re=B+Q>>1;1&k?(K=T,Q=B,T=le,B=me):(T=K,B=Q,K=le,Q=me),le=Me,me=Re}const we=4*L;hd[we+0]=T,hd[we+1]=B,hd[we+2]=K,hd[we+3]=Q}const Bl=new Uint16Array(2178),Xi=new Uint8Array(1089),Md=new Uint16Array(1089);function lu(L){return L===0?-.03125:L===32?.03125:0}var Jc=o.a$([{name:"a_pos",type:"Int16",components:2},{name:"a_texture_pos",type:"Uint16",components:2}]);const _d={type:2,extent:o.a6,loadGeometry:()=>[[new o.P(0,0),new o.P(o.a6+1,0),new o.P(o.a6+1,o.a6+1),new o.P(0,o.a6+1),new o.P(0,0)]]};let Ep,zv=0;class Rx{constructor(k,T,B,K,Q,le){this.tileID=k,this.uid=o.aw(),this.uses=0,this.tileSize=T,this.tileZoom=B,this.dashIdealZ=k.overscaledZ,this.buckets={},this.expirationTime=null,this.queryPadding=0,this.hasSymbolBuckets=!1,this.hasTunnelGeometry=!1,this.hasRTLText=!1,this.dependencies={},this.isRaster=Q,K&&K.style&&(this._lastUpdatedBrightness=K.style.getBrightness()),this._lastAvailableImagesCount=0,this._firstPrepareComplete=!1,this.expiredRequestCount=0,this.state="loading",K&&K.transform&&(this.projection=K.transform.projection),this.worldview=le,this._hasAppearances=null}registerFadeDuration(k){const T=k+this.timeAdded;T0&&(this.frcCoveragePolygons=k.frcCoveragePolygons),this.hasDeferredRoadStructure=!!k.hasDeferredRoadStructure,k.parsedElevationFeatures!==void 0&&(this.parsedElevationFeatures=k.parsedElevationFeatures,this.parsedElevationGeneration=++zv),this.hasDeferredElevationFeatures=!!k.hasDeferredElevationFeatures,this.hasSymbolBuckets=!1,this.hasTunnelGeometry=!!k.hasTunnelGeometry;for(const K in this.buckets){const Q=this.buckets[K];if(Q instanceof o.bv){if(this.hasSymbolBuckets=!0,!B)break;Q.justReloaded=!0}}if(this.hasRTLText=!1,this.hasSymbolBuckets)for(const K in this.buckets){const Q=this.buckets[K];if(Q instanceof o.bv&&Q.hasRTLText){this.hasRTLText=!0,o.bO();break}}this.queryPadding=0;for(const K in this.buckets){const Q=this.buckets[K],le=T.style.getOwnLayer(K);if(!le)continue;const me=le.queryRadius(Q)||0;this.queryPadding=Math.max(this.queryPadding,me)}k.imageAtlas&&(this.imageAtlas=T.style.imageManager.imageAtlasCache.getOrCache(k.imageAtlas)),k.glyphAtlasImage&&(this.glyphAtlasImage=k.glyphAtlasImage),k.lineAtlas&&(this.lineAtlas=k.lineAtlas),this._lastUpdatedBrightness=k.brightness}else this.collisionBoxArray=new o.bu}resetPlacementVisibility(){var k,T;for(const B in this.buckets)(T=(k=this.buckets[B]).resetPlacementVisibility)==null||T.call(k)}unloadVectorData(){if(this.hasData()){for(const k in this.buckets)this.buckets[k].destroy();this.buckets={},this.imageAtlas&&(this.imageAtlas=null),this.lineAtlas&&(this.lineAtlas=null),this.imageAtlasTexture&&(this.imageAtlasTexture=null),this.glyphAtlasTexture&&this.glyphAtlasTexture.destroy(),this.lineAtlasTexture&&this.lineAtlasTexture.destroy(),this._tileBoundsBuffer&&(this._tileBoundsBuffer.destroy(),this._tileBoundsIndexBuffer.destroy(),this._tileBoundsSegments.destroy(),this._tileBoundsBuffer=null),this._tileDebugBuffer&&(this._tileDebugBuffer.destroy(),this._tileDebugSegments.destroy(),this._tileDebugBuffer=null),this._tileDebugIndexBuffer&&(this._tileDebugIndexBuffer.destroy(),this._tileDebugIndexBuffer=null),this._globeTileDebugBorderBuffer&&(this._globeTileDebugBorderBuffer.destroy(),this._globeTileDebugBorderBuffer=null),this._tileDebugTextBuffer&&(this._tileDebugTextBuffer.destroy(),this._tileDebugTextSegments.destroy(),this._tileDebugTextIndexBuffer.destroy(),this._tileDebugTextBuffer=null),this._globeTileDebugTextBuffer&&(this._globeTileDebugTextBuffer.destroy(),this._globeTileDebugTextBuffer=null),this.latestFeatureIndex=null,this.state="unloaded"}}loadModelData(k,T,B){k&&(k.resourceTiming&&(this.resourceTiming=k.resourceTiming),this.buckets={...this.buckets,...Lh(k.buckets,T.style)},k.featureIndex&&(this.latestFeatureIndex=k.featureIndex))}getBucket(k){return this.buckets[k.fqid]}upload(k,T){for(const Q in this.buckets){const le=this.buckets[Q];if(le.uploadPending()){let me={},we=[],Me={zoom:0,pitch:0,brightness:0,worldview:""};if(T){if(T.style){we=T.style.listImages();const Re=le.layers[0],Ze=Re.sourceLayer||"_geojsonTileLayer",Qe=T.style.getLayerSourceCache(Re);Qe&&(me=Qe._state.getState(Ze,void 0))}Me={zoom:T.transform.zoom||0,pitch:T.transform.pitch||0,brightness:T.style.getBrightness()||0,worldview:T.worldview||""}}le.upload(k,this.tileID.canonical,me,we,Me)}}const B=k.gl,K=this.imageAtlas;K&&T&&(this.imageAtlasTexture=T.style.imageManager.imageAtlasCache.getTextureForAtlas(K,k,B.RGBA8),K.uploaded=!0),this.glyphAtlasImage&&(this.glyphAtlasTexture=new o.T(k,this.glyphAtlasImage,B.R8),this.glyphAtlasImage=null),this.lineAtlas&&!this.lineAtlas.uploaded&&(this.lineAtlasTexture=new o.T(k,this.lineAtlas.image,B.R8),this.lineAtlas.uploaded=!0)}prepare(k,T,B){if(this.imageAtlas&&this.imageAtlasTexture&&T){const Qe=T.style.getLut(B);this.imageAtlas.patchUpdatedImages(k,this.imageAtlasTexture,B,Qe)}if(!T||!this.latestFeatureIndex||!this.latestFeatureIndex.rawTileData)return;const K=T.style.getBrightness(),Q=T.style.listImages(),le=Q.length,me=T.style._changes.getUpdatedPaintProperties(),we=Object.keys(this.buckets).some(Qe=>this.buckets[Qe].layers.some(ht=>me.has(ht.fqid))),Me=Object.keys(this.buckets).some(Qe=>this.buckets[Qe].layers.some(ht=>ht.hasTransition&&ht.hasTransition())),Re=this._firstPrepareComplete&&le!==this._lastAvailableImagesCount;this._hasAppearances===null&&(this._hasAppearances=this.hasAppearances(T));const Ze=this._lastUpdatedBrightness!==K;this._lastAvailableImagesCount=le,this._firstPrepareComplete=!0,(this._lastUpdatedBrightness||K||this._hasAppearances||we||Me||Re)&&(!(this._hasAppearances||we||Me||Re)&&this._lastUpdatedBrightness&&K&&Math.abs(this._lastUpdatedBrightness-K)<.001||(this.updateBuckets(T,Ze,void 0,Re||we||Me,me,Q),this._lastUpdatedBrightness=K))}evaluateQueryRenderedFeaturePadding(){let k=0;for(const T in this.buckets){const B=this.buckets[T];B.evaluateQueryRenderedFeaturePadding&&(k=Math.max(k,B.evaluateQueryRenderedFeaturePadding()))}return k}queryRenderedFeatures(k,T,B,K,Q,le,me){if(!this.latestFeatureIndex||!this.latestFeatureIndex.rawTileData&&!this.latestFeatureIndex.is3DTile)return{};const we=this.evaluateQueryRenderedFeaturePadding(),Me=function(Re,Ze){const Qe=o.bM([],[.5*Re.width,.5*-Re.height,1]);return o.bN(Qe,Qe,[1,-1,0]),o.X(Qe,Qe,Re.calculateProjMatrix(Ze.toUnwrapped())),Float32Array.from(Qe)}(Q,this.tileID);return this.latestFeatureIndex.query(k,{tilespaceGeometry:T,pixelPosMatrix:Me,transform:K,availableImages:B,tileTransform:this.tileTransform,worldview:this.worldview,queryRadius:we,scope:me})}querySourceFeatures(k,T){const B=this.latestFeatureIndex;if(!B||!B.rawTileData)return;const K=B.loadVTLayers(),Q=T?T.sourceLayer:"",le=K._geojsonTileLayer||K[Q];if(!le)return;const me=o.bw(T&&T.filter),{z:we,x:Me,y:Re}=this.tileID.canonical,Ze={z:we,x:Me,y:Re};for(let Qe=0;QeB)K=!1;else if(T)if(this.expirationTimeB.appearances&&B.appearances.length>0))return!0;return!1}updateBuckets(k,T,B,K,Q,le){if(!this.latestFeatureIndex||!k.style)return;const me=le||k.style.listImages(),we=k.style.getBrightness(),Me=Q||new Set;for(const Re in this.buckets){if(!k.style.hasLayer(Re))continue;const Ze=this.buckets[Re],Qe=Ze.layers[0],ht=Qe.sourceLayer||"_geojsonTileLayer",_t=k.style.getLayerSourceCache(Qe),bt=Ze.layers.some(Fs=>Me.has(Fs.fqid)),Mt=(K||bt)&&Ze instanceof o.bv?k.style.getOwnLayer(Re):void 0;let es=B&&B[ht]||{};_t&&!B&&(es=_t._state.getState(ht,void 0));const Qt=this.imageAtlas?Object.fromEntries(this.imageAtlas.patternPositions):{},Lt=Object.keys(es).length>0&&!T;Ze.hasAppearances=Ze.layers.some(Fs=>Fs.appearances&&Fs.appearances.length>0);const ps=Lt?Ze.stateDependentLayers:Ze.layers;if(Lt&&Ze.stateDependentLayers.length!==0||T||bt||K){const Fs=this.latestFeatureIndex.loadVTLayers()[ht];if(Ze.update(es,Fs,me,Qt,ps,T,we,this.tileID.canonical),(K||bt)&&(!T||T&&Ze instanceof o.bv&&(!Ze.text.uboBinder||Ze.text.uboBinder.isLightConstant||!Ze.icon.uboBinder||Ze.icon.uboBinder.isLightConstant))&&Ze instanceof o.bv&&Mt&&Mt.type==="symbol"){const nn=Ze;nn.text&&nn.text.uboBinder&&nn.text.uboBinder.updateDynamicExpressions(Mt,Fs,this.tileID.canonical,me,es,we),nn.icon&&nn.icon.uboBinder&&nn.icon.uboBinder.updateDynamicExpressions(Mt,Fs,this.tileID.canonical,me,es,we)}if(Ze instanceof o.bv){const nn=Ze,$s=k.context;nn.text&&nn.text.uboBinder&&nn.text.uboBinder.upload($s),nn.icon&&nn.icon.uboBinder&&nn.icon.uboBinder.upload($s)}}if(Lt&&Ze.stateDependentLayers.length!==0||T||Ze.hasAppearances){const Fs={zoom:k.transform.zoom,pitch:k.transform.pitch,brightness:k.style.getBrightness()||0,worldview:k.worldview},nn=Ze.updateAppearances(this.tileID.canonical,es,me,Fs,k.imageManager,Lt&&Ze.stateDependentLayers.length!==0);if(nn&&nn.hasUboChanges){const $s=k.context;Ze instanceof o.bv&&Ze.text&&Ze.text.uboBinder&&Ze.text.uboBinder.upload($s),Ze instanceof o.bv&&Ze.icon&&Ze.icon.uboBinder&&Ze.icon.uboBinder.upload($s)}}(Ze instanceof o.bA||Ze instanceof o.bB)&&k._terrain&&k._terrain.enabled&&_t&&Ze.uploadPending()&&k._terrain._clearRenderCacheForTile(_t.id,this.tileID);const Hs=k&&k.style&&k.style.getOwnLayer(Re);Hs&&(this.queryPadding=Math.max(this.queryPadding,Hs.queryRadius(Ze)||0))}}holdingForFade(){return this.symbolFadeHoldUntil!==void 0}symbolFadeFinished(){return!this.symbolFadeHoldUntil||this.symbolFadeHoldUntil=0;Mt--){const es=4*Mt,Qt=hd[es+0],Lt=hd[es+1],ps=hd[es+2],Hs=hd[es+3],Fs=Qt+ps>>1,nn=Lt+Hs>>1,$s=Fs+nn-Lt,rn=nn+Qt-Fs,_n=Lt*qd+Qt,Mn=Hs*qd+ps,Yn=nn*qd+Fs,$n=Math.hypot((Bl[2*_n+0]+Bl[2*Mn+0])/2-Bl[2*Yn+0],(Bl[2*_n+1]+Bl[2*Mn+1])/2-Bl[2*Yn+1])>=16;Xi[Yn]=Xi[Yn]||($n?1:0),Mt<1022&&(Xi[Yn]=Xi[Yn]||Xi[(Lt+rn>>1)*qd+(Qt+$s>>1)]||Xi[(Hs+rn>>1)*qd+(ps+$s>>1)])}const Ze=new o.bt,Qe=new o.ae;let ht=0;function _t(Mt,es){const Qt=es*qd+Mt;return Md[Qt]===0&&(Ze.emplaceBack(Bl[2*Qt+0],Bl[2*Qt+1],Mt*o.a6/Gu,es*o.a6/Gu),Md[Qt]=++ht),Md[Qt]-1}function bt(Mt,es,Qt,Lt,ps,Hs){const Fs=Mt+Qt>>1,nn=es+Lt>>1;if(Math.abs(Mt-ps)+Math.abs(es-Hs)>1&&Xi[nn*qd+Fs])bt(ps,Hs,Mt,es,Fs,nn),bt(Qt,Lt,ps,Hs,Fs,nn);else{const $s=_t(Mt,es),rn=_t(Qt,Lt),_n=_t(ps,Hs);Qe.emplaceBack($s,rn,_n)}}return bt(0,0,Gu,Gu,Gu,0),bt(Gu,Gu,0,0,0,Gu),{vertices:Ze,indices:Qe}}(this.tileID.canonical,T);K=le.vertices,Q=le.indices}else{K=new o.bt,Q=new o.ae;for(const{x:me,y:we}of B)K.emplaceBack(me,we,0,0);const le=o.bG(K.int16.subarray(0,4*K.length),void 0,4);for(let me=0;me0&&(we=o.aP(new Float64Array(16),T.globeMatrix)),this._makeGlobeTileDebugBorderBuffer(k,K,T,le,we,me),this._makeGlobeTileDebugTextBuffer(k,K,T,le,we,me)}_globePoint(k,T,B,K,Q,le,me){let we=o.bH(k,T,B);if(le){const Me=1<.5?ht=-1:Qe<-.5&&(ht=1);let _t=(k/o.a6+B.x)/Me+ht,bt=(T/o.a6+B.y)/Me;_t=(_t-Re)*K._pixelsPerMercatorPixel+Re,bt=(bt-Ze)*K._pixelsPerMercatorPixel+Ze;const Mt=[_t*K.worldSize,bt*K.worldSize,0];o.bI(Mt,Mt,le),we=o.bJ(we,Mt,me)}return o.bI(we,we,Q)}_makeGlobeTileDebugBorderBuffer(k,T,B,K,Q,le){const me=new o.bD,we=new o.bE,Me=new o.bK,Re=(Qe,ht,_t,bt,Mt)=>{const es=(_t-Qe)/(Mt-1),Qt=(bt-ht)/(Mt-1),Lt=me.length;for(let ps=0;psZe*ht+_t;for(let ht=0;ht{this.remove(k,Q)},B)),this.data[K].push(Q),this.order.push(K),this.order.length>this.max){const le=this._getAndRemoveByKey(this.order[0]);le&&this.onRemove(le)}return this}has(k){return k.wrapped().key in this.data}getAndRemove(k){return this.has(k)?this._getAndRemoveByKey(k.wrapped().key):null}_getAndRemoveByKey(k){const T=this.data[k].shift();return T.timeout&&clearTimeout(T.timeout),this.data[k].length===0&&delete this.data[k],this.order.splice(this.order.indexOf(k),1),T.value}getByKey(k){const T=this.data[k];return T?T[0].value:null}get(k){return this.has(k)?this.data[k.wrapped().key][0].value:null}remove(k,T){if(!this.has(k))return this;const B=k.wrapped().key,K=T===void 0?0:this.data[B].indexOf(T),Q=this.data[B][K];return this.data[B].splice(K,1),Q.timeout&&clearTimeout(Q.timeout),this.data[B].length===0&&delete this.data[B],this.onRemove(Q.value),this.order.splice(this.order.indexOf(B),1),this}setMaxSize(k){for(this.max=k;this.order.length>this.max;){const T=this._getAndRemoveByKey(this.order[0]);T&&this.onRemove(T)}return this}filter(k){const T=[];for(const B in this.data)for(const K of this.data[B])k(K.value)||T.push(K);for(const B of T)this.remove(B.value.tileID,B)}}class Zy{constructor(){this.state=Object.create(null),this.stateChanges=Object.create(null),this.deletedStates=Object.create(null)}updateState(k,T,B){const K=String(T);if(this.stateChanges[k]=this.stateChanges[k]||Object.create(null),this.stateChanges[k][K]=this.stateChanges[k][K]||Object.create(null),Object.assign(this.stateChanges[k][K],B),this.deletedStates[k]===null){this.deletedStates[k]=Object.create(null);for(const Q in this.state[k])Q!==K&&(this.deletedStates[k][Q]=null)}else if(this.deletedStates[k]&&this.deletedStates[k][K]===null){this.deletedStates[k][K]=Object.create(null);for(const Q in this.state[k][K])B[Q]||(this.deletedStates[k][K][Q]=null)}else for(const Q in B)this.deletedStates[k]&&this.deletedStates[k][K]&&this.deletedStates[k][K][Q]===null&&delete this.deletedStates[k][K][Q]}removeFeatureState(k,T,B){if(this.deletedStates[k]===null)return;const K=String(T);if(this.deletedStates[k]=this.deletedStates[k]||Object.create(null),B&&T!==void 0)this.deletedStates[k][K]!==null&&(this.deletedStates[k][K]=this.deletedStates[k][K]||Object.create(null),this.deletedStates[k][K][B]=null);else if(T!==void 0)if(this.stateChanges[k]&&this.stateChanges[k][K])for(B in this.deletedStates[k][K]=Object.create(null),this.stateChanges[k][K])this.deletedStates[k][K][B]=null;else this.deletedStates[k][K]=null;else this.deletedStates[k]=null}getState(k,T){const B=this.state[k]||Object.create(null),K=this.stateChanges[k]||Object.create(null),Q=this.deletedStates[k];if(Q===null)return Object.create(null);if(T!==void 0){const me=String(T),we=Object.assign(Object.create(null),B[me],K[me]);if(Q){const Me=Q[T];if(Me===null)return Object.create(null);for(const Re in Me)delete we[Re]}return we}const le=Object.assign(Object.create(null),B,K);if(Q)for(const me in Q)delete le[me];return le}initializeTileState(k,T){k.refreshFeatureState(T)}coalesceChanges(k,T){const B=Object.create(null);for(const K in this.stateChanges){this.state[K]=this.state[K]||Object.create(null);const Q=Object.create(null);for(const le in this.stateChanges[K])this.state[K][le]||(this.state[K][le]=Object.create(null)),Object.assign(this.state[K][le],this.stateChanges[K][le]),Q[le]=this.state[K][le];B[K]=Q}for(const K in this.deletedStates){this.state[K]=this.state[K]||Object.create(null);const Q=Object.create(null);if(this.deletedStates[K]===null)for(const le in this.state[K])Q[le]=Object.create(null),this.state[K][le]=Object.create(null);else for(const le in this.deletedStates[K]){if(this.deletedStates[K][le]===null)this.state[K][le]=Object.create(null);else if(this.state[K][le])for(const me of Object.keys(this.deletedStates[K][le]))delete this.state[K][le][me];Q[le]=this.state[K][le]}B[K]=B[K]||Object.create(null),Object.assign(B[K],Q)}if(this.stateChanges=Object.create(null),this.deletedStates=Object.create(null),Object.keys(B).length!==0)for(const K in k)k[K].refreshFeatureState(T,B)}}class Ci extends o.E{constructor(k,T,B){super(),this.id=k,this._renderSourceType=B,this._maxzoomOverride=null,this.setSource(T),this._tiles={},this._cache=new ya(0,this._unloadTile.bind(this)),this._timers={},this._cacheTimers={},this._minTileCacheSize=T.minTileCacheSize,this._maxTileCacheSize=T.maxTileCacheSize,this._loadedParentTiles={},this.castsShadows=!1,this.tileCoverLift=0,this._coveredTiles={},this._shadowCasterTiles={},this._state=new Zy,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(k){this.map=k,this._minTileCacheSize=this._minTileCacheSize===void 0&&k?k._minTileCacheSize:this._minTileCacheSize,this._maxTileCacheSize=this._maxTileCacheSize===void 0&&k?k._maxTileCacheSize:this._maxTileCacheSize}setSource(k){k.on("data",T=>{T.dataType==="source"&&T.sourceDataType==="metadata"&&(this._sourceLoaded=!0),this._sourceLoaded&&!this._paused&&T.dataType==="source"&&T.sourceDataType==="content"&&(this.reload(),this.transform&&this.update(this.transform))}),k.on("error",()=>{this._sourceErrored=!0}),this._source=k}loaded(){if(this._sourceErrored)return!0;if(!this._sourceLoaded||!this._source.loaded())return!1;for(const k in this._tiles)if(!this._tiles[k].loaded())return!1;return!0}getSource(){return this._source}pause(){this._paused=!0}resume(){if(!this._paused)return;const k=this._shouldReloadOnResume;this._paused=!1,this._shouldReloadOnResume=!1,k&&this.reload(),this.transform&&this.update(this.transform)}setMaxzoomOverride(k){this._maxzoomOverride=k}_loadTile(k,T){return k.renderSourceType=this._renderSourceType,k.isExtraShadowCaster=this._shadowCasterTiles[k.tileID.key],this._source.loadTile(k,T)}_unloadTile(k){if(this._source.unloadTile)return this._source.unloadTile(k)}_abortTile(k){if(this._source.abortTile)return this._source.abortTile(k)}serialize(){return this._source.serialize()}prepare(k){this._source.prepare&&this._source.prepare(),this._state.coalesceChanges(this._tiles,this.map?this.map.painter:null);for(const T in this._tiles){const B=this._tiles[T];B.upload(k,this.map?this.map.painter:void 0),B.prepare(this.map.style.imageManager,this.map?this.map.painter:null,this._source.scope)}}getIds(){return Object.values(this._tiles).map(k=>k.tileID).sort(Xg).map(k=>k.key)}getRenderableIds(k,T){const B=[];for(const K in this._tiles)this._isIdRenderable(+K,k,T)&&B.push(this._tiles[K]);return k?B.sort((K,Q)=>{const le=K.tileID,me=Q.tileID,we=new o.P(le.canonical.x,le.canonical.y)._rotate(this.transform.angle),Me=new o.P(me.canonical.x,me.canonical.y)._rotate(this.transform.angle);return le.overscaledZ-me.overscaledZ||Me.y-we.y||Me.x-we.x}).map(K=>K.tileID.key):B.map(K=>K.tileID).sort(Xg).map(K=>K.key)}hasRenderableParent(k){const T=this.findLoadedParent(k,0);return!!T&&this._isIdRenderable(T.tileID.key)}_isIdRenderable(k,T,B){return this._tiles[k]&&this._tiles[k].hasData()&&!this._coveredTiles[k]&&(T||!this._tiles[k].holdingForFade())&&(B||!this._shadowCasterTiles[k])}reload(){if(this._paused)this._shouldReloadOnResume=!0;else{this._cache.reset();for(const k in this._tiles)this._tiles[k].state!=="errored"&&this._reloadTile(+k,"reloading")}}_reloadTile(k,T){const B=this._tiles[k];B&&(B.state!=="loading"&&(B.state=T),this._loadTile(B,this._tileLoaded.bind(this,B,k,T)))}_tileLoaded(k,T,B,K,Q){if(K){if(k.state="errored",o.bP(K)){if(this._source.fire(new o.h("data",{dataType:"source",sourceDataType:"error",sourceId:this._source.id,tile:k})),!(k.tileID.key in this._loadedParentTiles))return;if(this._source.type==="raster-dem"&&this.usedForTerrain&&this.map.painter.terrain){const me=this.map.painter.terrain;this.update(this.transform,me.getScaledDemTileSize(),!0),me.resetTileLookupCache(this.id)}else this.update(this.transform)}else this._source.fire(new o.f(K,{tile:k}));return}k.timeAdded=o.e.now(),B==="expired"&&(k.refreshedUponExpiration=!0),this._setTileReloadTimer(T,k),this._source.type==="raster-dem"&&k.dem&&this._backfillDEM(k),this._state.initializeTileState(k,this.map?this.map.painter:null);let le=new Headers;Q&&Q.headers&&(le=Q.headers),this._source.fire(new o.h("data",{dataType:"source",tile:k,coord:k.tileID,sourceCacheId:this.id,responseHeaders:le}))}_hasTunnelGeometry(){for(const k in this._tiles){const T=this._tiles[k];if(T&&T.hasTunnelGeometry)return!0}return!1}_backfillDEM(k){const T=this.getRenderableIds();for(let K=0;K1||(Math.abs(le)>1&&(Math.abs(le+we)===1?le+=we:Math.abs(le-we)===1&&(le-=we)),Q.dem&&K.dem&&(K.dem.backfillBorder(Q.dem,le,me),K.neighboringTiles&&K.neighboringTiles[Me]&&(K.neighboringTiles[Me].backfilled=!0)))}}getTile(k){return this.getTileByID(k.key)}getTileByID(k){return this._tiles[k]}_retainLoadedChildren(k,T,B,K){const Q=this._source.type==="raster-array";for(const le in this._tiles){let me=this._tiles[le];if(K[le]||!me.hasData()||me.tileID.overscaledZ<=T||me.tileID.overscaledZ>B||Q&&me.parentTile)continue;let we=me.tileID;for(;me&&me.tileID.overscaledZ>T+1;){const Re=me.tileID.scaledTo(me.tileID.overscaledZ-1);me=this._tiles[Re.key],me&&me.hasData()&&(we=Re)}let Me=we;for(;Me.overscaledZ>T;)if(Me=Me.scaledTo(Me.overscaledZ-1),k[Me.key]){K[we.key]=we;const Re=this._tiles[we.key];Re&&(Re.dashIdealZ=Me.overscaledZ);break}}}findLoadedParent(k,T){if(k.key in this._loadedParentTiles){const B=this._loadedParentTiles[k.key];return B&&B.tileID.overscaledZ>=T?B:null}for(let B=k.overscaledZ-1;B>=T;B--){const K=k.scaledTo(B),Q=this._getLoadedTile(K);if(Q)return Q}}_getLoadedTile(k){const T=this._tiles[k.key];return T&&T.hasData()?T:this._cache.getByKey(this._source.reparseOverscaled?k.wrapped().key:k.canonical.key)}updateCacheSize(k,T){T=T||this._source.tileSize;const B=Math.ceil(k.width/T)+1,K=Math.ceil(k.height/T)+1,Q=Math.floor(B*K*5),le=typeof this._minTileCacheSize=="number"?Math.max(this._minTileCacheSize,Q):Q,me=typeof this._maxTileCacheSize=="number"?Math.min(this._maxTileCacheSize,le):le;this._cache.setMaxSize(me)}handleWrapJump(k){const T=Math.round((k-(this._prevLng===void 0?k:this._prevLng))/360);if(this._prevLng=k,T){const B={};for(const K in this._tiles){const Q=this._tiles[K];Q.tileID=Q.tileID.unwrapTo(Q.tileID.wrap+T),B[Q.tileID.key]=Q}this._tiles=B;for(const K in this._timers)clearTimeout(this._timers[K]),delete this._timers[K];for(const K in this._tiles)this._setTileReloadTimer(+K,this._tiles[K])}}update(k,T,B,K,Q){if(this.transform=k,!this._sourceLoaded||this._paused||this.transform.freezeTileCoverage||this.usedForTerrain&&!B)return;this.updateCacheSize(k,T),this.transform.projection.name!=="globe"&&this.handleWrapJump(this.transform.center.lng),this._shadowCasterTiles={},this._coveredTiles={};const le=this._source.type==="batched-model";let me,we=this._source.maxzoom;this._maxzoomOverride!==null&&(we=Math.min(we,this._maxzoomOverride));const Me=this.map&&this.map.painter?this.map.painter._terrain:null;if(Me&&Me.sourceCache===this&&Me.attenuationRange()){const ht=Me.attenuationRange()[0],_t=Math.floor(ht)-Math.log2(Me.getDemUpscale());we>_t&&(we=_t)}const Re=this._maxzoomOverride===null&&this._source.reparseOverscaled;if(this.used||this.usedForTerrain){if(this._source.tileID)me=k.getVisibleUnwrappedCoordinates(this._source.tileID).map(ht=>new o.bQ(ht.canonical.z,ht.wrap,ht.canonical.z,ht.canonical.x,ht.canonical.y));else if(this.tileCoverLift!==0){const ht=k.clone();ht.tileCoverLift=this.tileCoverLift,me=ht.coveringTiles({tileSize:T||this._source.tileSize,minzoom:this._source.minzoom,maxzoom:we,roundZoom:this._source.roundZoom&&!B,reparseOverscaled:Re,isTerrainDEM:this.usedForTerrain,calculateQuadrantVisibility:le}),this._source.minzoom<=1&&k.projection.name==="globe"&&(me.push(new o.bQ(1,0,1,0,0)),me.push(new o.bQ(1,0,1,1,0)),me.push(new o.bQ(1,0,1,0,1)),me.push(new o.bQ(1,0,1,1,1)))}else if(me=k.coveringTiles({tileSize:T||this._source.tileSize,minzoom:this._source.minzoom,maxzoom:we,roundZoom:this._source.roundZoom&&!B,reparseOverscaled:Re,isTerrainDEM:this.usedForTerrain,calculateQuadrantVisibility:le}),this._source.hasTile){const ht=this._source.hasTile.bind(this._source);me=me.filter(_t=>ht(_t))}}else me=[];if(me.length>0&&this.transform.projection.name!=="globe"&&!this.usedForTerrain&&!this._supportsFading){const ht=k.coveringZoomLevel({tileSize:T||this._source.tileSize,roundZoom:this._source.roundZoom&&!B}),_t=Math.min(ht,we);if(le){const bt=k.extendTileCover(me,_t);for(const Mt of bt)me.push(Mt)}else if(Q){const bt=this.transform.getFrustum(_t),Mt=k.extendTileCoverToNearPlane(me,bt,_t);for(const es of Mt)me.push(es);if(_t>=18&&this._hasTunnelGeometry()){const es=k.extendTileCoverForTunnels(me,bt,_t,20);for(const Qt of es)me.push(Qt)}}else if(this.castsShadows&&K){const bt=k.extendTileCover(me,_t,K,16);for(const Mt of bt)this._shadowCasterTiles[Mt.key]=!0,me.push(Mt)}}for(const ht in this._tiles){const _t=this._tiles[ht];_t.dashIdealZ=_t.tileID.overscaledZ}const Ze=this._updateRetainedTiles(me);if(this._supportsFading&&me.length!==0){const ht={},_t={},bt=o.e.now(),Mt=Object.keys(Ze);for(const Qt of Mt){const Lt=Ze[Qt],ps=this._tiles[Qt];if(!ps||ps.fadeEndTime!==void 0&&ps.fadeEndTime<=bt)continue;const Hs=this.findLoadedParent(Lt,Math.max(Lt.overscaledZ-Ci.maxOverzooming,this._source.minzoom));Hs&&(this._addTile(Hs.tileID),ht[Hs.tileID.key]=Hs.tileID),_t[Qt]=Lt}const es=me.at(-1).overscaledZ;for(const Qt in this._tiles){const Lt=this._tiles[Qt];if(Ze[Qt]||!Lt.hasData())continue;let ps=Lt.tileID;for(;ps.overscaledZ>es;){ps=ps.scaledTo(ps.overscaledZ-1);const Hs=this._tiles[ps.key];if(Hs&&Hs.hasData()&&_t[ps.key]){Ze[Qt]=Lt.tileID;break}}}for(const Qt in ht)Ze[Qt]||(this._coveredTiles[Qt]=!0,Ze[Qt]=ht[Qt])}for(const ht in Ze)this._tiles[ht].clearFadeHold();const Qe=o.bR(this._tiles,Ze);for(const ht of Qe){const _t=this._tiles[ht];_t.hasSymbolBuckets&&!_t.holdingForFade()?_t.setHoldDuration(this.map._fadeDuration):_t.hasSymbolBuckets&&!_t.symbolFadeFinished()||this._removeTile(+ht)}this._updateLoadedParentTileCache(),this._renderSourceType===o.bS.Symbol&&this._source.afterUpdate&&this._source.afterUpdate()}releaseSymbolFadeTiles(){for(const k in this._tiles)this._tiles[k].holdingForFade()&&this._removeTile(+k)}_updateRetainedTiles(k){const T={};if(k.length===0)return T;const B={},K=k.reduce((Me,Re)=>Math.min(Me,Re.overscaledZ),1/0),Q=k[0].overscaledZ,le=Math.max(Q-Ci.maxOverzooming,this._source.minzoom),me=Math.max(Q+Ci.maxUnderzooming,this._source.minzoom),we={};for(const Me of k){const Re=this._addTile(Me);T[Me.key]=Me,Re.hasData()||K=this._source.maxzoom){const Qe=Me.children(this._source.maxzoom)[0],ht=this.getTile(Qe);if(ht&&ht.hasData()){T[Qe.key]=Qe,ht.dashIdealZ=Me.overscaledZ;continue}}else{const Qe=Me.children(this._source.maxzoom);if(T[Qe[0].key]&&T[Qe[1].key]&&T[Qe[2].key]&&T[Qe[3].key])continue}let Ze=Re.wasRequested();for(let Qe=Me.overscaledZ-1;Qe>=le;--Qe){const ht=Me.scaledTo(Qe);if(B[ht.key]||(B[ht.key]=!0,Re=this.getTile(ht),!Re&&Ze&&(Re=this._addTile(ht)),Re&&(T[ht.key]=ht,Re.dashIdealZ=Me.overscaledZ,Ze=Re.wasRequested(),Re.hasData())))break}}return T}_updateLoadedParentTileCache(){this._loadedParentTiles={};for(const k in this._tiles){const T=[];let B,K=this._tiles[k].tileID;for(;K.overscaledZ>0;){if(K.key in this._loadedParentTiles){B=this._loadedParentTiles[K.key];break}T.push(K.key);const Q=K.scaledTo(K.overscaledZ-1);if(B=this._getLoadedTile(Q),B)break;K=Q}for(const Q of T)this._loadedParentTiles[Q]=B}}_addTile(k){let T=this._tiles[k.key];if(T)return T.isExtraShadowCaster!==!0||this._shadowCasterTiles[k.key]||this._reloadTile(k.key,"reloading"),T;T=this._cache.getAndRemove(k),T&&(this._setTileReloadTimer(k.key,T),T.tileID=k,this._state.initializeTileState(T,this.map?this.map.painter:null),this._cacheTimers[k.key]&&(clearTimeout(this._cacheTimers[k.key]),delete this._cacheTimers[k.key],this._setTileReloadTimer(k.key,T)),T.resetPlacementVisibility());const B=!!T;if(!B){const K=this.map?this.map.painter:null,Q=this._source.tileSize*k.overscaleFactor();T=this._source.type==="raster-array"?function(le,me,we,Me,Re){if(!Ep)throw new Error("Raster-array module is not loaded.");return Ep(le,me,we,Me,Re)}(k,Q,this.transform.tileZoom,K,this._isRaster):new Rx(k,Q,this.transform.tileZoom,K,this._isRaster,this._source.worldview),this._loadTile(T,this._tileLoaded.bind(this,T,k.key,T.state))}return T.uses++,this._tiles[k.key]=T,B||this._source.fire(new o.h("dataloading",{tile:T,coord:T.tileID,dataType:"source"})),T}_setTileReloadTimer(k,T){k in this._timers&&(clearTimeout(this._timers[k]),delete this._timers[k]);const B=T.getExpiryTimeout();B&&(this._timers[k]=setTimeout(()=>{this._reloadTile(k,"expired"),delete this._timers[k]},B))}_removeTile(k){const T=this._tiles[k];T&&(T.uses--,delete this._tiles[k],this._timers[k]&&(clearTimeout(this._timers[k]),delete this._timers[k]),T.uses>0||(T.hasData()&&T.state!=="reloading"||T.state==="empty"?this._cache.add(T.tileID,T,T.getExpiryTimeout()):(T.aborted=!0,this._abortTile(T),this._unloadTile(T))))}clearTiles(){this._shouldReloadOnResume=!1,this._paused=!1;for(const k in this._tiles)this._removeTile(+k);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(k,T,B){const K=[],Q=this.transform;if(!Q)return K;const le=Q.projection.name==="globe",me=o.a7(Q.center.lng),we=Q.getFreeCameraOptions().position||new o.bT(0,0,0);for(const Me in this._tiles){const Re=this._tiles[Me];if(B&&Re.clearQueryDebugViz(),Re.holdingForFade())continue;let Ze;if(le){const Qe=Re.tileID.canonical;if(Qe.z===0){const ht=[Math.abs(o.b1(me,...zm(Qe,-1))-me),Math.abs(o.b1(me,...zm(Qe,1))-me)];Ze=[0,2*ht.indexOf(Math.min(...ht))-1]}else{const ht=[Math.abs(o.b1(me,...zm(Qe,-1))-me),Math.abs(o.b1(me,...zm(Qe,0))-me),Math.abs(o.b1(me,...zm(Qe,1))-me)];Ze=[ht.indexOf(Math.min(...ht))-1]}}else Ze=[0];for(const Qe of Ze){const ht=k.containsTile(Re,Q,T,Qe,we);ht&&K.push(ht)}}return K}getShadowCasterCoordinates(){return this._getRenderableCoordinates(!1,!0)}getVisibleCoordinates(k){return this._getRenderableCoordinates(k)}_getRenderableCoordinates(k,T){if(!this.transform)return[];const B=this.getRenderableIds(k,T).map(Q=>this._tiles[Q].tileID),K=this.transform.projection.name==="globe";for(const Q of B)Q.projMatrix=this.transform.calculateProjMatrix(Q.toUnwrapped()),Q.expandedProjMatrix=K?this.transform.calculateProjMatrix(Q.toUnwrapped(),!1,!0):Q.projMatrix;return B}sortCoordinatesByDistance(k){if(!this.transform)return k.slice();const T=k.slice(),B=this.transform._camera.position,K=this.transform._camera.forward(),Q={};for(const le of T){const me=1/(1<Q[le.key]-Q[me.key]),T}hasTransition(){if(this._source.hasTransition())return!0;if(this._supportsFading){const k=o.e.now();for(const T in this._tiles){const B=this._tiles[T];if(B.fadeEndTime!==void 0&&B.fadeEndTime>=k)return!0}}return!1}setFeatureState(k,T,B){this._state.updateState(k=k||"_geojsonTileLayer",T,B)}removeFeatureState(k,T,B){this._state.removeFeatureState(k=k||"_geojsonTileLayer",T,B)}getFeatureState(k,T){return this._state.getState(k=k||"_geojsonTileLayer",T)}setDependencies(k,T,B){const K=this._tiles[k];K&&K.setDependencies(T,B)}reloadTilesForDependencies(k,T){for(const B in this._tiles)this._tiles[B].hasDependency(k,T)&&this._reloadTile(+B,"reloading");this._cache.filter(B=>!B.hasDependency(k,T))}_preloadTiles(k,T){if(!this._sourceLoaded){const we=()=>{this._sourceLoaded&&(this._source.off("data",we),this._preloadTiles(k,T))};return void this._source.on("data",we)}const B=new Map,K=Array.isArray(k)?k:[k],Q=this.map.painter.terrain,le=this.usedForTerrain&&Q?Q.getScaledDemTileSize():this._source.tileSize;for(const we of K){const Me=we.coveringTiles({tileSize:le,minzoom:this._source.minzoom,maxzoom:this._source.maxzoom,roundZoom:this._source.roundZoom&&!this.usedForTerrain,reparseOverscaled:this._source.reparseOverscaled,isTerrainDEM:this.usedForTerrain});for(const Re of Me)B.set(Re.key,Re);this.usedForTerrain&&we.updateElevation(!1)}const me=Array.from(B.values());o.bU(me,(we,Me)=>{const Re=new Rx(we,this._source.tileSize*we.overscaleFactor(),this.transform.tileZoom,this.map.painter,this._isRaster,this._source.worldview);this._loadTile(Re,Ze=>{this._source.type==="raster-dem"&&Re.dem&&this._backfillDEM(Re),Me(Ze,Re)})},T)}}function Xg(L,k){const T=Math.abs(2*L.wrap)-+(L.wrap<0),B=Math.abs(2*k.wrap)-+(k.wrap<0);return L.overscaledZ-k.overscaledZ||B-T||k.canonical.y-L.canonical.y||k.canonical.x-L.canonical.x}function zm(L,k){const T=1<>B===L.x&&k.y>>B===L.y}const T=L.z-k.z;return L.x>>T===k.x&&L.y>>T===k.y}function Wu(L,k){return L.sourceFQID!==k.sourceFQID?L.sourceFQID{return!!me.hasDeferredElevationFeatures||le&&(we=K,kl(B,Me=me.tileID.canonical)!==kl(we,Me));var we,Me})}const yu=L=>({u_matrix:L});function B_(L,k){const T=L.context.gl;return new o._({func:T.EQUAL,mask:255},L._tileClippingMaskIDs[k.key]||0,0,T.KEEP,T.KEEP,T.KEEP)}function Bv(L,k){const T=L.context.gl;return new o._({func:T.EQUAL,mask:255},255&~(L._tileClippingMaskIDs[k.key]||0),0,T.KEEP,T.KEEP,T.KEEP)}function Fx(L,k){if(!L.frcCoverageSnapshot||!L.frcCoverageRenderer)return null;const T=L.frcCoverageSnapshot.getTileOrParent(k.canonical);if(!T||T.frcMask===0)return null;const B=L.frcCoverageRenderer.getBuffers(T.tileId);if(!B)return null;const K=new o.bW(T.tileId.z,T.tileId.x,T.tileId.y),Q=new o.bX(k.wrap,K);return{buffers:B,projMatrix:L.transform.calculateProjMatrix(Q),coverageTile:T}}function Rb(L,k,T){if(!L.frcCoverageSnapshot)return;const B=L.context,K=B.gl,Q=L.getOrCreateProgram("clippingMask");B.setColorMode(o.a1.disabled),B.setDepthMode(o.Z.disabled);for(const le of k){const me=Fx(L,le);if(!me)continue;const we=me.buffers.frcLevelSegments[T];we&&Q.draw(L,K.TRIANGLES,o.Z.disabled,new o._({func:K.EQUAL,mask:255},L._tileClippingMaskIDs[le.key]||0,255,K.KEEP,K.KEEP,K.INVERT),o.a1.disabled,o.$.disabled,yu(me.projMatrix),`$frc_coverage_${T}`,me.buffers.vertexBuffer,me.buffers.indexBuffer,we)}}function ej(L,k,T){if(!L.frcCoverageSnapshot)return;const B=L.context,K=B.gl,Q=L.getOrCreateProgram("clippingMask");B.setColorMode(o.a1.disabled),B.setDepthMode(o.Z.disabled);for(const le of k){const me=Fx(L,le);if(!me)continue;const we=me.buffers.frcLevelSegments[T];we&&Q.draw(L,K.TRIANGLES,o.Z.disabled,new o._({func:K.EQUAL,mask:255},255&~(L._tileClippingMaskIDs[le.key]||0),255,K.KEEP,K.KEEP,K.INVERT),o.a1.disabled,o.$.disabled,yu(me.projMatrix),`$frc_coverage_restore_${T}`,me.buffers.vertexBuffer,me.buffers.indexBuffer,we)}}function Bm(L,k,T,B,K){if(k.length===0)return;let Q=0;for(const me of k)Q|=me.frcMask;const le=k.map(me=>me.coord);for(let me=0;me<9;++me)if(Q&1<0&&K)for(const we of k)we.frcMask&1<0&&k.rings[0].length>0)return!0;return!1}function Rh(L){const k=L.frcCoverageFadeRange;return!k||k[1]<=k[0]?0:1-Math.max(0,Math.min(1,(L.transform.zoom-k[0])/(k[1]-k[0])))}const vh={loaded:!0,drawBuilding:function(L,k,T,B){L.currentLayer0&&Q>0,Me=!0;const Re=T.paint.get("building-vertical-scale");if(Re<=0)return;L.shadowRenderer||(Me=!1);const Ze=L.conflationActive&&L.style.isLayerClipped(T,k.getSource()),Qe=L.style.order.indexOf(T.fqid);if(function(ht,_t,bt,Mt,es,Qt){for(const Lt of Qt){const ps=_t.getTile(Lt).getBucket(bt);ps&&(es&&ps.updateReplacement(Lt,ht.replacementSource,Mt),ps.uploadUpdatedIndexBuffer(ht.context))}}(L,k,T,Qe,Ze,B),function(ht,_t,bt,Mt){for(const es of Mt){const Qt=_t.getTile(es).getBucket(bt);Qt&&Qt.needsEvaluation()&&Qt.uploadUpdatedColorBuffer(ht.context)}}(L,k,T,B),T.resetLayerRenderingStats(L),L.shadowRenderer&&(L.shadowRenderer.useNormalOffset=!0),L.renderPass==="shadow"&&L.shadowRenderer){const ht=[],_t=L.shadowRenderer.getShadowPassDepthMode();$a({painter:L,source:k,layer:T,coords:B,defines:ht,blendMode:o.a1.disabled,depthMode:_t,opacity:me,verticalScale:Re,facadeEmissiveChance:0,facadeAOIntensity:0,floodLightIntensity:0,floodLightColor:[0,0,0]})}else if(L.renderPass==="translucent"){let ht=["HAS_ATTRIBUTE_a_part_color_emissive","LIGHTING_3D_MODE"];Me&&(ht=ht.concat("RENDER_SHADOWS")),L.shadowRenderer&&L.shadowRenderer.useNormalOffset&&(ht=ht.concat("NORMAL_OFFSET"));const _t=T.paint.get("building-facade-emissive-chance"),bt=T.paint.get("building-ambient-occlusion-intensity"),Mt=T.paint.get("building-flood-light-intensity"),es=T.paint.get("building-flood-light-color-use-theme").constantOr("default")==="none",Qt=T.paint.get("building-flood-light-color").toNonPremultipliedRenderColor(es?null:T.lut).toArray01().slice(0,3),Lt=T.paint.get("building-flood-light-ground-attenuation"),ps=Mt>0,Hs=new o.Z(L.context.gl.LEQUAL,o.Z.ReadWrite,L.depthRangeFor3D);me<1&&$a({painter:L,source:k,layer:T,coords:B,defines:ht,blendMode:o.a1.disabled,depthMode:Hs,opacity:me,verticalScale:Re,facadeEmissiveChance:_t,facadeAOIntensity:bt,floodLightIntensity:Mt,floodLightColor:Qt,depthOnly:!0});const Fs=L.colorModeForRenderPass();$a({painter:L,source:k,layer:T,coords:B,defines:ht,blendMode:Fs,depthMode:Hs,opacity:me,verticalScale:Re,facadeEmissiveChance:_t,facadeAOIntensity:bt,floodLightIntensity:Mt,floodLightColor:Qt});const nn=T.paint.get("building-front-cutoff");Ht(L.transform.pitch,nn,!!L.terrain),we&&Na(L,k,T,B,!0,me,K,Q,Mt,Qt,le,Ze),ps&&Na(L,k,T,B,!1,me,K,Q,Mt,Qt,Lt,Ze)}else if(L.renderPass==="light-beam"){const ht=["HAS_ATTRIBUTE_a_part_color_emissive","HAS_ATTRIBUTE_a_bloom_attenuation"],_t=new o.Z(L.context.gl.LEQUAL,o.Z.ReadOnly,L.depthRangeFor3D);$a({painter:L,source:k,layer:T,coords:B,defines:ht,blendMode:o.a1.alphaBlended,depthMode:_t,opacity:me,verticalScale:Re,facadeEmissiveChance:0,facadeAOIntensity:0,floodLightIntensity:0,floodLightColor:[0,0,0]})}L.shadowRenderer&&(L.shadowRenderer.useNormalOffset=!1),L.resetStencilClippingMasks()},BuildingTileBorderManager:class{constructor(){this.visibleTiles=[]}updateBorders(L,k){const T=[],B=[],K=L._getRenderableCoordinates(!1,!0);for(const me of K){const we=L.getTile(me);if(!we.hasData())continue;const Me=we.getBucket(k);Me&&(Me.isEmpty()||(T.push(me.key),B.push({bucket:Me,tileID:me.canonical})))}let Q=T.length!==this.visibleTiles.length;if(!Q){T.sort();for(let me=0;meme.tileID.z-we.tileID.z||me.tileID.x-we.tileID.x||me.tileID.y-we.tileID.y);for(const me of B){const we=new Array,Me=new Array,Re=me.bucket;for(const Ze of Re.featuresOnBorder)Re.footprints[Ze.footprintIndex].hiddenFlags&o.aS||(le.has(Ze.featureId)?Me.push(Ze.footprintIndex):(le.add(Ze.featureId),we.push(Ze.footprintIndex)));Re.updateFootprintHiddenFlags(we,o.aT,!1),Re.updateFootprintHiddenFlags(Me,o.aT,!0)}}},drawRasterParticle:function(L,k,T,B,K,Q){L.renderPass==="offscreen"&&function(le,me,we,Me){if(!Me.length)return;const Re=le.context,Ze=Re.gl,Qe=me.getSource();if(Qe.type!=="raster-array")return;const ht=Math.ceil(Math.sqrt(we.paint.get("raster-particle-count")));let _t=we.particlePositionRGBAImage;if(!_t||_t.width!==ht){const Lt=function(ps){const Hs=ps*ps,Fs=new Uint8Array(4*Hs),nn=.9090909090909091;for(let $s=0;$so.aC[Hr]($n));yr.push($n);const sa=$n.canonical.x,ka=$n.canonical.y;for(const Hr of yr){const ea=ps.getTile(_n?Hr.wrapped():Hr);if(!ea)continue;const si=ea.rasterParticleState;if(!si)continue;const Wr=Hr.canonical.x+(1<k.getTileByID(me));for(const me of le)me.updateNeeded(L.id,Q)&&(me._isHeaderLoaded||me.parentTile)&&B.prepareTile(me,K,L.id,Q)},Rain:class extends Lc{constructor(){super(4.25),this._params={intensity:.5,timeFactor:1,velocityConeAperture:0,velocity:300,boxSize:2500,dropletSizeX:1,dropletSizeYScale:10,distortionStrength:70,screenThinning:{intensity:.57,start:.46,range:1.17,fadePower:.17,affectedRatio:1,particleOffset:-.2},color:{r:.66,g:.68,b:.74,a:.7},direction:{x:-50,y:-35},shapeDirPower:2,shapeNormalPower:1},this._vignetteParams={strength:1,start:.7,range:1,fadePower:.4,color:{r:.27,g:.27,b:.27,a:1}},this.particlesCount=16e3,this._devtoolsFolder=null,this._painter=null}destroy(){super.destroy()}update(L){const k=L.context;if(!this.particlesVx){const T=el(this.particlesCount),B=new o.bl,K=new o.ae;let Q=0;const le=o.bj(1323123451230);for(let me=0;mele)return;const me=zo(0,1,B.revealStart,B.revealStart+B.revealRange,le);if(!this.particlesVx||!this.particlesIdx)return;Q.strength*=me;const we=this.updateOnRender(L,T.timeFactor),Me=L.context,Re=Me.gl,Ze=L.transform;this.screenTexture&&this.screenTexture.size[0]===L.width&&this.screenTexture.size[1]===L.height||(this.screenTexture=new o.T(Me,{width:L.width,height:L.height,data:null},Re.RGBA8)),T.distortionStrength>0&&(Me.activeTexture.set(Re.TEXTURE0),this.screenTexture.bind(Re.LINEAR,Re.CLAMP_TO_EDGE),Re.copyTexSubImage2D(Re.TEXTURE_2D,0,0,0,0,0,L.width,L.height));const Qe=L.getOrCreateProgram("rainParticle");L.uploadCommonUniforms(Me,Qe),Me.activeTexture.set(Re.TEXTURE0),this.screenTexture.bind(Re.LINEAR,Re.CLAMP_TO_EDGE);const ht=[T.color.r,T.color.g,T.color.b,T.color.a],_t=(bt,Mt)=>{const es=Ia(this._movement.getPosition(),bt),Qt=T.dropletSizeX,Lt=T.dropletSizeX*T.dropletSizeYScale,ps=L.width/2,Hs=L.height/2,Fs=zo(0,T.screenThinning.start,0,1,T.screenThinning.intensity),nn=zo(.001,T.screenThinning.range,0,1,T.screenThinning.intensity),$s=zo(0,T.screenThinning.particleOffset,0,1,T.screenThinning.intensity),rn=(_n={modelview:we.modelviewMatrix,projection:we.projectionMatrix,time:this._accumulatedTimeFromStart,camPos:es,velocityConeAperture:T.velocityConeAperture,velocity:T.velocity,boxSize:bt,rainDropletSize:[Qt,Lt],distortionStrength:T.distortionStrength,rainDirection:K,color:ht,screenSize:[Ze.width,Ze.height],thinningCenterPos:[ps,Hs],thinningShape:[Fs,nn,Math.pow(10,T.screenThinning.fadePower)],thinningAffectedRatio:T.screenThinning.affectedRatio,thinningParticleOffset:$s,shapeDirectionalPower:T.shapeDirPower,shapeNormalPower:T.shapeNormalPower,mode:Mt?0:1},{u_modelview:Float32Array.from(_n.modelview),u_projection:Float32Array.from(_n.projection),u_time:_n.time,u_cam_pos:_n.camPos,u_texScreen:0,u_velocityConeAperture:_n.velocityConeAperture,u_velocity:_n.velocity,u_boxSize:_n.boxSize,u_rainDropletSize:_n.rainDropletSize,u_distortionStrength:_n.distortionStrength,u_rainDirection:_n.rainDirection,u_color:_n.color,u_screenSize:_n.screenSize,u_thinningCenterPos:_n.thinningCenterPos,u_thinningShape:_n.thinningShape,u_thinningAffectedRatio:_n.thinningAffectedRatio,u_thinningParticleOffset:_n.thinningParticleOffset,u_shapeDirectionalPower:_n.shapeDirectionalPower,u_shapeNormalPower:_n.shapeNormalPower,u_mode:_n.mode});var _n;const Mn=Math.round(T.intensity*this.particlesCount),Yn=o.ad.simpleSegment(0,0,4*Mn,2*Mn);Qe.draw(L,Re.TRIANGLES,o.Z.disabled,o._.disabled,o.a1.alphaBlended,o.$.disabled,rn,"rain_particles",this.particlesVx,this.particlesIdx,Yn)};T.distortionStrength>0&&_t(T.boxSize,!0),_t(T.boxSize,!1),this._vignette.draw(L,Q)}},Snow:class extends Lc{constructor(){super(2.25),this._params={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._vignetteParams={strength:.3,start:.78,range:.46,fadePower:.2,color:{r:1,g:1,b:1,a:1}},this.particlesCount=16e3,this._devtoolsFolder=null,this._painter=null}destroy(){super.destroy()}update(L){const k=L.context;if(!this.particlesVx){const T=el(this.particlesCount),B=new o.bm,K=new o.ae;let Q=0;const le=o.bj(1323123451230);for(let me=0;mele)return;const me=zo(0,1,B.revealStart,B.revealStart+B.revealRange,le);Q.strength*=me;const we=this.updateOnRender(L,T.timeFactor);if(!this.particlesVx||!this.particlesIdx)return;const Me=L.context,Re=Me.gl,Ze=L.transform,Qe=L.getOrCreateProgram("snowParticle");L.uploadCommonUniforms(Me,Qe),((ht,_t,bt)=>{const Mt=Ia(this._movement.getPosition(),ht),es=Ze.width/2,Qt=Ze.height/2,Lt=zo(0,bt.screenThinning.start,0,1,bt.screenThinning.intensity),ps=zo(.001,bt.screenThinning.range,0,1,bt.screenThinning.intensity),Hs=zo(0,bt.screenThinning.particleOffset,0,1,bt.screenThinning.intensity),Fs=(nn={modelview:we.modelviewMatrix,projection:we.projectionMatrix,time:this._accumulatedTimeFromStart,camPos:Mt,velocityConeAperture:bt.velocityConeAperture,velocity:bt.velocity,horizontalOscillationRadius:bt.horizontalOscillationRadius,horizontalOscillationRate:bt.horizontalOscillationRate,boxSize:ht,billboardSize:1*bt.billboardSize,simpleShapeParameters:[bt.shapeFadeStart,bt.shapeFadePower],screenSize:[Ze.width,Ze.height],thinningCenterPos:[es,Qt],thinningShape:[Lt,ps,Math.pow(10,bt.screenThinning.fadePower)],thinningAffectedRatio:bt.screenThinning.affectedRatio,thinningParticleOffset:Hs,color:[bt.color.r,bt.color.g,bt.color.b,bt.color.a],direction:K},{u_modelview:Float32Array.from(nn.modelview),u_projection:Float32Array.from(nn.projection),u_time:nn.time,u_cam_pos:nn.camPos,u_velocityConeAperture:nn.velocityConeAperture,u_velocity:nn.velocity,u_horizontalOscillationRadius:nn.horizontalOscillationRadius,u_horizontalOscillationRate:nn.horizontalOscillationRate,u_boxSize:nn.boxSize,u_billboardSize:nn.billboardSize,u_simpleShapeParameters:nn.simpleShapeParameters,u_screenSize:nn.screenSize,u_thinningCenterPos:nn.thinningCenterPos,u_thinningShape:nn.thinningShape,u_thinningAffectedRatio:nn.thinningAffectedRatio,u_thinningParticleOffset:nn.thinningParticleOffset,u_particleColor:nn.color,u_direction:nn.direction});var nn;const $s=Math.round(bt.intensity*this.particlesCount),rn=o.ad.simpleSegment(0,0,4*$s,2*$s);this.particlesVx&&this.particlesIdx&&Qe.draw(L,Re.TRIANGLES,o.Z.disabled,o._.disabled,o.a1.alphaBlended,o.$.disabled,Fs,"snow_particles",this.particlesVx,this.particlesIdx,rn)})(T.boxSize,0,T),this._vignette.draw(L,Q)}},shaders:ar,programUniforms:gu,drawElevatedStructures:function(L){const{painter:k,sourceCache:T,layer:B,coords:K,colorMode:Q}=L,le=k.context.gl,me=L.painter.shadowRenderer,we=!!me&&me.enabled,Me=new o.Z(k.context.gl.LEQUAL,o.Z.ReadOnly,k.depthRangeFor3D);let Re=[0,0,0];if(we){const Qe=k.style.directionalLight,ht=k.style.ambientLight;Qe&&ht&&(Re=o.aG(k.style,Qe,ht))}const Ze=Qe=>{for(const ht of K){const _t=T.getTile(ht),bt=_t.getBucket(B);if(!bt)continue;const Mt=bt.hdExt?bt.hdExt.elevatedStructures:void 0;if(!Mt)continue;let es,Qt;if(Qe?(es=Mt.renderableBridgeSegments,Qt=Mt.bridgeProgramConfigurations.get(B.id)):(es=Mt.renderableTunnelSegments,Qt=Mt.tunnelProgramConfigurations.get(B.id)),!es||es.segments[0].primitiveLength===0)continue;Qt.updatePaintBuffers(),k.prepareDrawTile();const Lt=k.isTileAffectedByFog(ht),ps=[];we&&ps.push("RENDER_SHADOWS","NORMAL_OFFSET");const Hs=k.getOrCreateProgram("elevatedStructures",{config:Qt,overrideFog:Lt,defines:ps}),Fs=k.translatePosMatrix(ht.projMatrix,_t,B.paint.get("fill-translate"),B.paint.get("fill-translate-anchor"));we&&me.setupShadows(_t.tileID.toUnwrapped(),Hs,"vector-tile");const nn=um(Fs,Re);k.uploadCommonUniforms(k.context,Hs,ht.toUnwrapped()),Hs.draw(k,le.TRIANGLES,Me,o._.disabled,Q,o.$.backCCW,nn,B.id,Mt.vertexBuffer,Mt.indexBuffer,es,B.paint,k.transform.zoom,Qt,[Mt.vertexBufferNormal])}};Ze(!0),Ze(!1)},drawElevatedFillShadows:function(L){const{painter:k,sourceCache:T,layer:B,coords:K}=L,Q=k.context.gl,le=L.painter.shadowRenderer;for(const me of K){const we=T.getTile(me),Me=we.getBucket(B);if(!Me)continue;const Re=Me.hdExt?Me.hdExt.elevatedStructures:void 0;if(!Re||!Re.shadowCasterSegments||Re.shadowCasterSegments.segments[0].primitiveLength===0)continue;k.prepareDrawTile();const Ze=Me.bufferData.programConfigurations.get(B.id),Qe=k.isTileAffectedByFog(me),ht=k.getOrCreateProgram("elevatedStructuresDepth",{config:Ze,overrideFog:Qe}),_t=le.calculateShadowPassMatrixFromTile(we.tileID.toUnwrapped());k.uploadCommonUniforms(k.context,ht,me.toUnwrapped());const bt=ou(_t,0);ht.draw(k,Q.TRIANGLES,le.getShadowPassDepthMode(),o._.disabled,o.a1.disabled,o.$.disabled,bt,B.id,Re.vertexBuffer,Re.indexBuffer,Re.shadowCasterSegments,B.paint,k.transform.zoom,Ze)}},drawDepthPrepass:function(L,k,T,B,K){if(!k||!T.layout||T.layout.get("fill-elevation-reference")==="none"||T.paint.get("fill-opacity").constantOr(1)===0)return;const Q=L.context.gl,le=new o.Z(L.context.gl.LEQUAL,o.Z.ReadWrite,L.depthRangeFor3D),me=new o.Z(L.context.gl.GREATER,o.Z.ReadWrite,L.depthRangeFor3D),we=function(Qe){let ht=.01;return Qe.isOrthographic&&(ht=o.am(1e-4,ht,o.bp(Qe.pitch>=o.bo?1:Qe.pitch/o.bo))),2*ht}(L.transform),Me=L.transform.getFreeCameraOptions().position,Re="elevatedStructuresDepthReconstruct";let Ze;for(const Qe of B){const ht=k.getTile(Qe),_t=ht.getBucket(T);if(!_t||!_t.hdExt)continue;const bt=_t.hdExt.elevatedStructures,Mt=_t.hdExt.elevationBufferData;if(!bt||!bt.depthSegments||!Mt)continue;const es=Mt.heightRange,Qt=Qc(Qe.toUnwrapped(),Me),Lt=L.translatePosMatrix(Qe.projMatrix,ht,T.paint.get("fill-translate"),T.paint.get("fill-translate-anchor"));let ps,Hs,Fs;if(K==="initialize"){if(!es||es.min>=1||bt.depthSegments.segments[0].primitiveLength===0)continue;ps=Td(Lt,Qt,we,1,0),Hs=le,Fs=bt.depthSegments,Ze=Ze||L.getOrCreateProgram(Re,{defines:["DEPTH_RECONSTRUCTION"]})}else if(K==="reset"){if(!es||es.min>=0||bt.maskSegments.segments[0].primitiveLength===0)continue;ps=Td(Lt,Qt,0,0,1),Hs=me,Fs=bt.maskSegments,Ze=Ze||L.getOrCreateProgram(Re,{defines:["DEPTH_RECONSTRUCTION"]})}else if(K==="geometry"){if(bt.depthSegments.segments[0].primitiveLength===0)continue;ps=Td(Lt,Qt,we,1,0),Hs=le,Fs=bt.depthSegments,Ze=Ze||L.getOrCreateProgram(Re)}Ze.draw(L,Q.TRIANGLES,Hs,o._.disabled,o.a1.disabled,o.$.disabled,ps,T.id,bt.vertexBuffer,bt.indexBuffer,Fs,T.paint,L.transform.zoom)}},drawGroundShadowMask:function(L,k,T,B){if(!k||!T.layout||T.layout.get("fill-elevation-reference")==="none"||T.paint.get("fill-opacity").constantOr(1)===0)return;const K=L.context.gl,Q=new o.Z(K.LEQUAL,o.Z.ReadOnly,L.depthRangeFor3D),le=new o._({func:K.ALWAYS,mask:255},255,255,K.KEEP,K.KEEP,K.REPLACE),me=L.transform.getFreeCameraOptions().position;let we;for(const Me of B){const Re=k.getTile(Me),Ze=Re.getBucket(T);if(!Ze)continue;const Qe=Ze.hdExt?Ze.hdExt.elevatedStructures:void 0;if(!Qe||!Qe.depthSegments||Qe.depthSegments.segments[0].primitiveLength===0)continue;const ht=Qc(Me.toUnwrapped(),me),_t=L.translatePosMatrix(Me.projMatrix,Re,T.paint.get("fill-translate"),T.paint.get("fill-translate-anchor"));we=we||L.getOrCreateProgram("elevatedStructuresDepthReconstruct");const bt=Td(_t,ht,0,1,0);we.draw(L,K.TRIANGLES,Q,le,o.a1.disabled,o.$.disabled,bt,T.id,Qe.vertexBuffer,Qe.indexBuffer,Qe.depthSegments,T.paint,L.transform.zoom)}},IndoorManager:class extends o.E{constructor(L,k=!1){super(),this._style=L,this._buildings={},this._activeFloors=new Set,this._closestBuildingId=null,this._indoorState={selectedFloorId:null,activeFloorsVisible:!0,activeFloors:this._activeFloors},this._buildingDetectionStrategy=new La,this._initialLoadDone=!1,o.aW(["_updateUI"],this);const T=()=>{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))};k?(this._initialLoadDone=!0,T()):this._style.on("style.load",T)}destroy(){this._buildings={},this._activeFloors=new Set,this._indoorState=null}selectFloor(L){L===this._selectedFloorId&&this._indoorState&&this._indoorState.activeFloorsVisible||(this._selectedFloorId=L,this._recalculateActiveFloors())}setActiveFloorsVisibility(L){this._updateActiveFloors(L),this._updateIndoorSelector()}setIndoorData(L){let k=!1;for(const[T,B]of Object.entries(L.buildings))if(this._buildings[T])for(const K of B.floorIds)this._buildings[T].floorIds.add(K),this._buildings[T].floors[K]?this._mergeFloors(this._buildings[T].floors[K],B.floors[K]):(this._buildings[T].floors[K]=B.floors[K],k=!0);else this._buildings[T]=B,k=!0;k&&this._recalculateActiveFloors()}getIndoorTileOptions(L,k){return this._indoorState?{sourceLayers:this._style.getIndoorSourceLayers(L,k),indoorState:this._indoorState}:null}getControlState(){const L=this._buildings,k=this._closestBuildingId,T=k&&L?L[k]:void 0;if(!T)return{selectedFloorId:null,activeFloorsVisible:!!this._indoorState&&this._indoorState.activeFloorsVisible,floors:[]};let B=null;for(const Q of T.floorIds)if(this._activeFloors&&this._activeFloors.has(Q)){B=Q;break}const K=Array.from(T.floorIds).map(Q=>({id:Q,name:T.floors[Q].name,zIndex:T.floors[Q].zIndex})).sort((Q,le)=>le.zIndex-Q.zIndex).filter((Q,le,me)=>le===0||Q.zIndex!==me[le-1].zIndex);return{selectedFloorId:B,activeFloorsVisible:!!this._indoorState&&this._indoorState.activeFloorsVisible,floors:K}}_updateUI(){this._initialLoadDone=!0;const L=this._style.map.transform,k=this._buildingDetectionStrategy.findClosestBuilding(this._buildings,L.center,L.zoom,L.getBounds(),this._makeViewportPolygon());if(k!==this._closestBuildingId){const T=this._closestBuildingId;this._closestBuildingId=k,this._onBuildingTransition(T,k),this._updateIndoorSelector()}}_onBuildingTransition(L,k){if(!this._indoorState)return;!k&&L?(this._indoorState.activeFloors=new Set,this._indoorState.activeFloorsVisible=!1,this._style.updateIndoorDependentLayers()):!!k&&!L&&(this._recalculateActiveFloors(),this._updateActiveFloors(!0))}_updateIndoorSelector(){this.fire(new o.h("selector-update",this.getControlState()))}_updateActiveFloors(L){this._indoorState={selectedFloorId:this._selectedFloorId,activeFloorsVisible:L,activeFloors:this._activeFloors},this._initialLoadDone?this._style.updateIndoorDependentLayers():this._indoorState.needsUpdate=!0}_recalculateActiveFloors(){if(!this._buildings)return;const L=o.aX.calculate(this._buildings,this._selectedFloorId,this._activeFloors);(function(k,T){if(k===T)return!0;if(!k||!T||k.size!==T.size)return!1;for(const B of k)if(!T.has(B))return!1;return!0})(L,this._activeFloors)||(this._activeFloors=L,this._updateActiveFloors(!!this._indoorState&&this._indoorState.activeFloorsVisible),this._updateIndoorSelector())}_mergeFloors(L,k){k.geometry&&(L.geometry?(L.geometry.type==="Polygon"&&(L.geometry={type:"MultiPolygon",coordinates:[L.geometry.coordinates]}),k.geometry.type==="Polygon"?L.geometry.coordinates.push(k.geometry.coordinates):k.geometry.type==="MultiPolygon"&&L.geometry.coordinates.push(...k.geometry.coordinates)):L.geometry=k.geometry)}_makeViewportPolygon(){const L=this._style.map.transform,k=L.width,T=L.height;return[L.pointLocation(new o.P(0,0)),L.pointLocation(new o.P(k,0)),L.pointLocation(new o.P(k,T)),L.pointLocation(new o.P(0,T))].map(B=>new o.P(B.lng,B.lat))}},HdCoverageState:class{constructor(){this.coverageSourceCaches={},this.manager=new od}},updateFrcCoverage:function(L,k){k.manager.clear();for(const B in L._mergedHdRoadCoverageSourceCaches){const K=L._mergedHdRoadCoverageSourceCaches[B]._tiles;for(const Q in K){const le=K[Q];if(!le||!le.loaded())continue;const me=le.frcCoveragePolygons;k.manager.addTileCoverage(le.tileID.canonical,me&&me.length>0?me:[])}}const T=k.manager.updateSnapshotIfNeeded();if(L.map.painter&&(L.map.painter.frcCoverageSnapshot=T.empty()?null:T),!T.empty()){const B=[L._mergedOtherSourceCaches,L._mergedSymbolSourceCaches];for(const K of B)for(const Q in K){const le=K[Q];for(const me in le._tiles){const we=le._tiles[me];we&&we.hasDeferredRoadStructure&&(we.hasDeferredRoadStructure=!1,le._reloadTile(+me,"reloading"))}}}},updateHdCoverageSourceCache:function(L,k,T){if(T.type!=="fill"||T.sourceLayer!==o.bV||k.coverageSourceCaches[T.source])return;const B=L.getOwnSource(T.source);if(!B||B.type!=="vector")return;const K=`hd-road-coverage:${T.source}`,Q=o.m(K,L.scope),le=L._sourceCaches[K]=new Ci(Q,B,o.bS.HdRoadCoverage);k.coverageSourceCaches[T.source]=le,le.setMaxzoomOverride(14),le.onAdd(L.map);const me=L._otherSourceCaches[T.source];me&&me._sourceLoaded&&(le._sourceLoaded=!0)},updateFrcCoverageFadeRange:function(L,k){let T=null,B=null;const K={globals:{zoom:0}};L.forEachFragmentStyle(Q=>{if(T)return;const le=Q.stylesheet?Q.stylesheet.schema:null;if(!le||!le.sdCoverageFadeRange)return;const me=o.m("sdCoverageFadeRange",Q.scope),we=Q.options?Q.options.get(me):void 0,Me=we?we.value||we.default:null;if(Me){const ht=Me.evaluate(K);Array.isArray(ht)&&ht.length===2&&(ht[0]>0||ht[1]>0)&&(T=[ht[0],ht[1]])}const Re=o.m("sdCoverageSourceLayers",Q.scope),Ze=Q.options?Q.options.get(Re):void 0,Qe=Ze?Ze.value||Ze.default:null;if(Qe){const ht=Qe.evaluate(K);Array.isArray(ht)&&ht.length>0&&(B=ht)}else{const ht=L.stylesheet&&L.stylesheet.imports||[];for(const _t of ht)if(_t.id===Q.scope){const bt=_t.config?_t.config.sdCoverageSourceLayers:void 0;Array.isArray(bt)&&bt.length>0&&(B=bt);break}}}),k.frcCoverageFadeRange=T,k.frcCoverageSourceLayers=T!=null?B||["road","structure"]:[]},HdElevationState:q0,setupAndUpdateElevationCoverage:function(L){if(!function(K){for(const Q in K._mergedLayers)if(Ao(K._mergedLayers[Q]))return!0;return!1}(L))return void uf(L);const k=oh(L,L.map&&L.map.transform);L._hdElevation||(L._hdElevation=new q0);const T=L._hdElevation._terrainActiveLast;if(L._hdElevation._terrainActiveLast=k,T!==void 0&&T!==k&&Wo(L,void 0,!0),k)return void(L.map.painter&&(L.map.painter.elevationCoverageSnapshot=null));if(!ed(L))return void uf(L);T===void 0&&Wo(L,void 0,!0);const B=L._hdElevation;B._needsCrossSourceElevation=!0,L._crossSourceElevationActive=!0,B._ingestFQIDs=ag(L),Vd(L,B)},updateElevationCoverage:Vd,updateCrossSourceElevationGate:function(L){L._crossSourceElevationActive=ed(L)},buildElevationRequestParams:function(L,k,T){if(oh(L.style,L.transform)||!T)return null;const B=L.painter?L.painter.elevationCoverageSnapshot:null,K=!(!L.painter||!L.painter.elevationProvidersReady);return B?function(Q,le,me){const we=Q.getTilesIntersecting(le);if(we.length===0)return{registry:[],hasCoveringTile:!1,allProvidersReady:me};const Me=[];for(const Re of we)for(const Ze of Re.features)Me.push({tileId:Re.tileId,feature:Ze});return Me.sort((Re,Ze)=>Re.feature.id-Ze.feature.id),{registry:Me,hasCoveringTile:!0,allProvidersReady:me}}(B,k.tileID.canonical,K):{registry:[],hasCoveringTile:!1,allProvidersReady:K}},FrcCoverageRenderer:class{constructor(){this.tileBuffers=new Map,this._context=null}update(L,k){this._context=L;const T=new Set;for(const B of k){if(B.frcMask===0)continue;let K=!1;for(const le of B.polygons)if(le.hasGeometry()){K=!0;break}if(!K)continue;const Q=`${B.tileId.z}/${B.tileId.x}/${B.tileId.y}`;if(T.add(Q),!this.tileBuffers.has(Q)){const le=this._createBuffers(L,B);le&&this.tileBuffers.set(Q,le)}}for(const B of this.tileBuffers.keys())if(!T.has(B)){const K=this.tileBuffers.get(B);K.vertexBuffer.destroy(),K.indexBuffer.destroy();for(const Q of K.frcLevelSegments)Q&&Q.destroy();this.tileBuffers.delete(B)}}getBuffers(L){return this.tileBuffers.get(`${L.z}/${L.x}/${L.y}`)||null}destroy(){for(const L of this.tileBuffers.values()){L.vertexBuffer.destroy(),L.indexBuffer.destroy();for(const k of L.frcLevelSegments)k&&k.destroy()}this.tileBuffers.clear()}_createBuffers(L,k){const T=new o.bD,B=new o.ae,K=[];for(const le of k.polygons){if(!le.hasGeometry()||le.rings.length===0)continue;const me=T.length,we=B.length,Me=T.length,Re=[],Ze=[];let Qe=0;for(let _t=0;_t0&&Ze.push(Qe);for(const Mt of bt)T.emplaceBack(Mt.x,Mt.y),Re.push(Mt.x,Mt.y),Qe++}}const ht=o.bG(Re,Ze.length>0?Ze:void 0);for(let _t=0;_t0&&L.program.draw(k,L.drawMode,L.depthMode,L.stencilMode,L.colorMode,o.$.disabled,L.uniformValues,L.layer.id,L.bufferData.layoutVertexBuffer,L.indexBuffer,we.frcNonRoadSegments,L.layer.paint,Qe,L.programConfiguration,L.dynamicBuffers),"drawn"}return"fallthrough"},drawFillFrcCoverageSecondPass:function(L,k,T,B,K){if(T.length===0)return;const Q=Rh(L),le=L.transform.zoom,me=(we,Me,Re)=>{Re!==1&&(we.uniformValues.u_opacity_multiplier=Re),we.program.draw(L,B,we.depthMode,Me,K,o.$.disabled,we.uniformValues,k.id,we.bufferData.layoutVertexBuffer,we.indexBuffer,we.segments,k.paint,le,we.programConfiguration,we.dynamicBuffers),Re!==1&&(we.uniformValues.u_opacity_multiplier=1)};Bm(L,T,Q,(we,Me,Re)=>me(we,Re,1),(we,Me,Re)=>me(we,Re,Q))},drawLineFrcCoverageDetect:function(L,k,T,B,K,Q,le,me,we,Me){const Re=k.hdExt&&k.hdExt.frcData;if(!Re||Re.frcPerLevel.size===0||!L.frcCoverageSnapshot||B)return null;const Ze=L.frcCoverageSnapshot.getTileOrParent(T.canonical);if(!Ze||Ze.frcMask===0)return null;const Qe=vu(Ze.polygons),ht=L.frcCoverageFadeRange,_t=ht!=null&&L.transform.zoom>=ht[0];if(Qe&&_t){let bt=!1;for(const Mt of Re.frcPerLevel.keys())if(Ze.frcMask&1<0&&B(T,le)},drawLineFrcFadePass:function(L,k,T,B,K,Q,le){if(B.hasPolygonGeometry)return;const me=k.hdExt&&k.hdExt.frcData;if(!me||!L.frcCoverageFadeRange)return;const[we,Me]=L.frcCoverageFadeRange;if(we>=Me)return;const Re=1-Math.max(0,Math.min(1,(L.transform.zoom-we)/(Me-we)));if(Re<=0)return;const Ze=K?Q:L.stencilModeForClipping(T),Qe=B.frcMask;for(const[ht,_t]of me.frcPerLevel)Qe&1<{const Ze=me.bucket.hdExt&&me.bucket.hdExt.frcData,Qe=Ze&&Ze.frcPerLevel.get(we);Qe&&Qe.segments.length!==0&&(Re!==1&&(me.uniformValues.u_opacity_multiplier=Re),me.program.draw(L,B.TRIANGLES,me.depthMode,Me,me.colorMode,o.$.disabled,me.uniformValues,k.id,me.bucket.layoutVertexBuffer,me.bucket.indexBuffer,Qe,k.paint,Q,me.programConfiguration,[me.bucket.layoutVertexBuffer2,me.bucket.patternVertexBuffer,me.bucket.zOffsetVertexBuffer,me.bucket.elevationIdColVertexBuffer,me.bucket.elevationGroundScaleVertexBuffer]),Re!==1&&(me.uniformValues.u_opacity_multiplier=1))};Bm(L,T,K,(me,we,Me)=>le(me,we,Me,1),(me,we,Me)=>le(me,we,Me,K))}},Ui=vh;async function hm(){return Promise.resolve()}function ch(L,k){const T=Math.pow(2,k.canonical.z),B=k.canonical.y;return[new o.bT(0,B/T).toLngLat().lat,new o.bT(0,(B+1)/T).toLngLat().lat]}function np(L,k,T,B,K,Q,le){const me=L.context,we=me.gl,Me=T.hillshadeFBO;if(!Me)return;L.prepareDrawTile();const Re=L.isTileAffectedByFog(k),Ze=[];L.terrain&&L.terrain.renderingToTexture&&L.isEmissiveMrtActive()&&(Ze.push("USE_MRT1"),L.emissiveMode==="mrt-full-rgba"&&Ze.push("USE_MRT1_RGBA"));const Qe=L.getOrCreateProgram("hillshade",{overrideFog:Re,defines:Ze});me.activeTexture.set(we.TEXTURE0),we.bindTexture(we.TEXTURE_2D,Me.colorAttachment0.get());const ht=((es,Qt,Lt,ps)=>{const Hs=Lt.paint.get("hillshade-shadow-color"),Fs=Lt.paint.get("hillshade-shadow-color-use-theme").constantOr("default")==="none",nn=Lt.paint.get("hillshade-highlight-color"),$s=Lt.paint.get("hillshade-highlight-color-use-theme").constantOr("default")==="none",rn=Lt.paint.get("hillshade-accent-color"),_n=Lt.paint.get("hillshade-accent-color-use-theme").constantOr("default")==="none",Mn=Lt.paint.get("hillshade-emissive-strength");let Yn=o.av(Lt.paint.get("hillshade-illumination-direction"));if(Lt.paint.get("hillshade-illumination-anchor")==="viewport")Yn-=es.transform.angle;else if(es.style&&es.style.enable3dLights()&&es.style.directionalLight){const zn=es.style.directionalLight.properties.get("direction"),Dr=o.b_(zn.x,zn.y,zn.z);Yn=o.av(Dr[1])}const $n=!es.options.moving;return{u_matrix:ps||es.transform.calculateProjMatrix(Qt.tileID.toUnwrapped(),$n),u_image:0,u_latrange:ch(0,Qt.tileID),u_light:[Lt.paint.get("hillshade-exaggeration"),Yn],u_shadow:Hs.toPremultipliedRenderColor(Fs?null:Lt.lut),u_highlight:nn.toPremultipliedRenderColor($s?null:Lt.lut),u_emissive_strength:Mn,u_accent:rn.toPremultipliedRenderColor(_n?null:Lt.lut)}})(L,T,B,L.terrain?k.projMatrix:null);L.uploadCommonUniforms(me,Qe,k.toUnwrapped());const{tileBoundsBuffer:_t,tileBoundsIndexBuffer:bt,tileBoundsSegments:Mt}=L.getTileBoundsBuffers(T);Qe.draw(L,we.TRIANGLES,K,Q,le,o.$.disabled,ht,B.id,_t,bt,Mt)}function Qg(L,k,T){if(!k.needsDEMTextureUpload)return;const B=L.context,K=B.gl;B.pixelStoreUnpackPremultiplyAlpha.set(!1),k.demTexture=k.demTexture||L.getTileTexture(T.stride);const Q=T.getPixels();k.demTexture?k.demTexture.update(Q,{premultiply:!1}):k.demTexture=new o.T(B,Q,K.R32F,{premultiply:!1}),k.needsDEMTextureUpload=!1}function dh(L,k,T){const B=L.context,K=B.gl;if(!k.dem)return;const Q=k.dem;if(B.activeTexture.set(K.TEXTURE1),Qg(L,k,Q),!k.demTexture)return;k.demTexture.bind(K.NEAREST,K.CLAMP_TO_EDGE);const le=Q.dim;B.activeTexture.set(K.TEXTURE0);let me=k.hillshadeFBO;if(!me){const Qe=new o.T(B,{width:le,height:le,data:null},K.RGBA8);Qe.bind(K.LINEAR,K.CLAMP_TO_EDGE),me=k.hillshadeFBO=B.createFramebuffer(le,le,1,"renderbuffer"),me.colorAttachment0.set(Qe.texture)}B.bindFramebuffer.set(me.framebuffer),B.viewport.set([0,0,le,le]);const{tileBoundsBuffer:we,tileBoundsIndexBuffer:Me,tileBoundsSegments:Re}=L.getMercatorTileBoundsBuffers(),Ze=[];L.linearFloatFilteringSupported()&&Ze.push("TERRAIN_DEM_FLOAT_FORMAT"),L.terrain&&L.terrain.renderingToTexture&&L.isEmissiveMrtActive()&&(Ze.push("USE_MRT1"),L.emissiveMode==="mrt-full-rgba"&&Ze.push("USE_MRT1_RGBA")),L.getOrCreateProgram("hillshadePrepare",{defines:Ze}).draw(L,K.TRIANGLES,o.Z.disabled,o._.disabled,o.a1.unblended,o.$.disabled,((Qe,ht)=>{const _t=ht.stride,bt=o.Y();return o.bZ(bt,0,o.a6,-o.a6,0,0,1),o.bN(bt,bt,[0,-o.a6,0]),{u_matrix:bt,u_image:1,u_dimension:[_t,_t],u_zoom:Qe.overscaledZ}})(k.tileID,Q),T.id,we,Me,Re),k.needsHillshadePrepare=!1}class Rc{constructor(k){this.gl=k.gl,this.default=this.getDefault(),this.current=this.default,this.dirty=!1}get(){return this.current}set(k){}getDefault(){return this.default}setDefault(){this.set(this.default)}}class Jg extends Rc{getDefault(){return o.C.transparent.toNonPremultipliedRenderColor(null)}set(k){const T=this.current;(k.r!==T.r||k.g!==T.g||k.b!==T.b||k.a!==T.a||this.dirty)&&(this.gl.clearColor(k.r,k.g,k.b,k.a),this.current=k,this.dirty=!1)}}class F1 extends Rc{getDefault(){return 1}set(k){(k!==this.current||this.dirty)&&(this.gl.clearDepth(k),this.current=k,this.dirty=!1)}}class O1 extends Rc{getDefault(){return 0}set(k){(k!==this.current||this.dirty)&&(this.gl.clearStencil(k),this.current=k,this.dirty=!1)}}class z1 extends Rc{getDefault(){return[!0,!0,!0,!0]}set(k){const T=this.current;(k[0]!==T[0]||k[1]!==T[1]||k[2]!==T[2]||k[3]!==T[3]||this.dirty)&&(this.gl.colorMask(k[0],k[1],k[2],k[3]),this.current=k,this.dirty=!1)}}class tj extends Rc{getDefault(){return!0}set(k){(k!==this.current||this.dirty)&&(this.gl.depthMask(k),this.current=k,this.dirty=!1)}}class sj extends Rc{getDefault(){return 255}set(k){(k!==this.current||this.dirty)&&(this.gl.stencilMask(k),this.current=k,this.dirty=!1)}}class $_ extends Rc{getDefault(){return{func:this.gl.ALWAYS,ref:0,mask:255}}set(k){const T=this.current;(k.func!==T.func||k.ref!==T.ref||k.mask!==T.mask||this.dirty)&&(this.gl.stencilFunc(k.func,k.ref,k.mask),this.current=k,this.dirty=!1)}}class Rk extends Rc{getDefault(){const k=this.gl;return[k.KEEP,k.KEEP,k.KEEP]}set(k){const T=this.current;(k[0]!==T[0]||k[1]!==T[1]||k[2]!==T[2]||this.dirty)&&(this.gl.stencilOp(k[0],k[1],k[2]),this.current=k,this.dirty=!1)}}class Db extends Rc{getDefault(){return!1}set(k){if(k===this.current&&!this.dirty)return;const T=this.gl;k?T.enable(T.STENCIL_TEST):T.disable(T.STENCIL_TEST),this.current=k,this.dirty=!1}}class $v extends Rc{getDefault(){return[0,1]}set(k){const T=this.current;(k[0]!==T[0]||k[1]!==T[1]||this.dirty)&&(this.gl.depthRange(k[0],k[1]),this.current=k,this.dirty=!1)}}class C3 extends Rc{getDefault(){return!1}set(k){if(k===this.current&&!this.dirty)return;const T=this.gl;k?T.enable(T.DEPTH_TEST):T.disable(T.DEPTH_TEST),this.current=k,this.dirty=!1}}class Z2 extends Rc{getDefault(){return this.gl.LESS}set(k){(k!==this.current||this.dirty)&&(this.gl.depthFunc(k),this.current=k,this.dirty=!1)}}class rp extends Rc{getDefault(){return!1}set(k){if(k===this.current&&!this.dirty)return;const T=this.gl;k?T.enable(T.BLEND):T.disable(T.BLEND),this.current=k,this.dirty=!1}}class Dk extends Rc{getDefault(){const k=this.gl;return[k.ONE,k.ZERO,k.ONE,k.ZERO]}set(k){const T=this.current;(k[0]!==T[0]||k[1]!==T[1]||k[2]!==T[2]||k[3]!==T[3]||this.dirty)&&(this.gl.blendFuncSeparate(k[0],k[1],k[2],k[3]),this.current=k,this.dirty=!1)}}class B1 extends Rc{getDefault(){return o.C.transparent.toNonPremultipliedRenderColor(null)}set(k){const T=this.current;(k.r!==T.r||k.g!==T.g||k.b!==T.b||k.a!==T.a||this.dirty)&&(this.gl.blendColor(k.r,k.g,k.b,k.a),this.current=k,this.dirty=!1)}}class ex extends Rc{getDefault(){return this.gl.FUNC_ADD}set(k){(k!==this.current||this.dirty)&&(this.gl.blendEquationSeparate(k,k),this.current=k,this.dirty=!1)}}class ap extends Rc{getDefault(){return!1}set(k){if(k===this.current&&!this.dirty)return;const T=this.gl;k?T.enable(T.CULL_FACE):T.disable(T.CULL_FACE),this.current=k,this.dirty=!1}}class Ox extends Rc{getDefault(){return this.gl.BACK}set(k){(k!==this.current||this.dirty)&&(this.gl.cullFace(k),this.current=k,this.dirty=!1)}}class Hd extends Rc{getDefault(){return this.gl.CCW}set(k){(k!==this.current||this.dirty)&&(this.gl.frontFace(k),this.current=k,this.dirty=!1)}}let Uv=class extends Rc{getDefault(){return null}set(L){(L!==this.current||this.dirty)&&(this.gl.useProgram(L),this.current=L,this.dirty=!1)}};class RC extends Rc{getDefault(){return this.gl.TEXTURE0}set(k){(k!==this.current||this.dirty)&&(this.gl.activeTexture(k),this.current=k,this.dirty=!1)}}class GT extends Rc{getDefault(){const k=this.gl;return[0,0,k.drawingBufferWidth,k.drawingBufferHeight]}set(k){const T=this.current;(k[0]!==T[0]||k[1]!==T[1]||k[2]!==T[2]||k[3]!==T[3]||this.dirty)&&(this.gl.viewport(k[0],k[1],k[2],k[3]),this.current=k,this.dirty=!1)}}class WT extends Rc{getDefault(){return null}set(k){if(k===this.current&&!this.dirty)return;const T=this.gl;T.bindFramebuffer(T.FRAMEBUFFER,k),this.current=k,this.dirty=!1}}class A3 extends Rc{getDefault(){return null}set(k){if(k===this.current&&!this.dirty)return;const T=this.gl;T.bindRenderbuffer(T.RENDERBUFFER,k),this.current=k,this.dirty=!1}}class Fb extends Rc{getDefault(){return null}set(k){if(k===this.current&&!this.dirty)return;const T=this.gl;T.bindTexture(T.TEXTURE_2D,k),this.current=k,this.dirty=!1}}class Tp extends Rc{getDefault(){return null}set(k){if(k===this.current&&!this.dirty)return;const T=this.gl;T.bindBuffer(T.ARRAY_BUFFER,k),this.current=k,this.dirty=!1}}class V0 extends Rc{getDefault(){return null}set(k){const T=this.gl;T.bindBuffer(T.ELEMENT_ARRAY_BUFFER,k),this.current=k,this.dirty=!1}}class DC extends Rc{getDefault(){return null}set(k){this.gl&&(k!==this.current||this.dirty)&&(this.gl.bindVertexArray(k),this.current=k,this.dirty=!1)}}class E3 extends Rc{getDefault(){return 4}set(k){if(k===this.current&&!this.dirty)return;const T=this.gl;T.pixelStorei(T.UNPACK_ALIGNMENT,k),this.current=k,this.dirty=!1}}class Ob extends Rc{getDefault(){return!1}set(k){if(k===this.current&&!this.dirty)return;const T=this.gl;T.pixelStorei(T.UNPACK_PREMULTIPLY_ALPHA_WEBGL,k),this.current=k,this.dirty=!1}}class ip extends Rc{getDefault(){return!1}set(k){if(k===this.current&&!this.dirty)return;const T=this.gl;T.pixelStorei(T.UNPACK_FLIP_Y_WEBGL,k),this.current=k,this.dirty=!1}}class nj extends Rc{constructor(k,T){super(k),this.context=k,this.parent=T}getDefault(){return null}}class Fr extends nj{constructor(k,T,B=0){super(k,T),this.attachmentPoint=k.gl.COLOR_ATTACHMENT0+B}setDirty(){this.dirty=!0}set(k){if(k===this.current&&!this.dirty)return;this.context.bindFramebuffer.set(this.parent);const T=this.gl;T.framebufferTexture2D(T.FRAMEBUFFER,this.attachmentPoint,T.TEXTURE_2D,k,0),this.current=k,this.dirty=!1}}class Fk extends nj{attachment(){return this.gl.DEPTH_ATTACHMENT}set(k){if(k===this.current&&!this.dirty)return;this.context.bindFramebuffer.set(this.parent);const T=this.gl;T.framebufferRenderbuffer(T.FRAMEBUFFER,this.attachment(),T.RENDERBUFFER,k),this.current=k,this.dirty=!1}}class FC extends nj{attachment(){return this.gl.DEPTH_ATTACHMENT}set(k){if(k===this.current&&!this.dirty)return;this.context.bindFramebuffer.set(this.parent);const T=this.gl;T.framebufferTexture2D(T.FRAMEBUFFER,this.attachment(),T.TEXTURE_2D,k,0),this.current=k,this.dirty=!1}}class tx extends Fk{attachment(){return this.gl.DEPTH_STENCIL_ATTACHMENT}}const hf=(L,k,T,B)=>({u_matrix:L,u_image0:0,u_image1:1,u_skirt_height:k,u_ground_shadow_factor:T,u_emissive_texture_available:B}),$1=(L,k,T,B,K,Q,le,me,we,Me,Re,Ze,Qe,ht,_t,bt,Mt)=>({u_proj_matrix:Float32Array.from(L),u_globe_matrix:k,u_normalize_matrix:Float32Array.from(B),u_merc_matrix:T,u_zoom_transition:K,u_merc_center:Q,u_image0:0,u_image1:1,u_frustum_tl:le,u_frustum_tr:me,u_frustum_br:we,u_frustum_bl:Me,u_globe_pos:Re,u_globe_radius:Ze,u_viewport:Qe,u_grid_matrix:Mt?Float32Array.from(Mt):new Float32Array(9),u_skirt_height:ht,u_far_z_cutoff:_t,u_emissive_texture_available:bt});function H0(L,k){return L!=null&&k!=null&&!(!L.hasData()||!k.hasData())&&L.demTexture!=null&&k.demTexture!=null&&L.tileID.key!==k.tileID.key}const G0=new class{constructor(){this.operations={}}newMorphing(L,k,T,B,K){if(L in this.operations){const Q=this.operations[L];Q.to.tileID.key!==T.tileID.key&&(Q.queued=T)}else this.operations[L]={startTime:B,phase:0,duration:K,from:k,to:T,queued:null}}getMorphValuesForProxy(L){if(!(L in this.operations))return null;const k=this.operations[L];return{from:k.from,to:k.to,phase:k.phase}}update(L){for(const k in this.operations){const T=this.operations[k];for(T.phase=(L-T.startTime)/T.duration;T.phase>=1||!this._validOp(T);)if(!this._nextOp(T,L)){delete this.operations[k];break}}}_nextOp(L,k){return!!L.queued&&(L.from=L.to,L.to=L.queued,L.queued=null,L.phase=0,L.startTime=k,!0)}_validOp(L){return L.from.hasData()&&L.to.hasData()}};function zx(L,k,T){if(k===0)return 0;const B=k<1&&T===514?.25/k:1;return 6*Math.pow(1.5,22-L)*Math.max(k,1)*B}function Ok(L,k){const T=1<{if(Q[le.key]="",!this._tiles[le.key]){const me=new Rx(le,this._source.tileSize*le.overscaleFactor(),k.tileZoom,void 0,void 0,this._source.worldview);me.state="loaded",this._tiles[le.key]=me}return Q},{});for(const Q in this._tiles)Q in K||(this.freeFBO(Q),this._tiles[Q].unloadVectorData(),delete this._tiles[Q])}freeFBO(k){const T=this.proxyCachedFBO[k];if(T!==void 0){const B=Object.values(T);this.renderCachePool.push(...B),delete this.proxyCachedFBO[k]}}deallocRenderCache(){this.renderCache.forEach(k=>k.fb.destroy()),this.renderCache=[],this.renderCachePool=[],this.proxyCachedFBO={}}}class rj extends o.bQ{constructor(k,T,B){super(k.overscaledZ,k.wrap,k.canonical.z,k.canonical.x,k.canonical.y),this.proxyTileKey=T,this.projMatrix=B}}function q_(L,k){return k==="rgba8"?L.RGBA8:L.R8}class OC extends o.c2{constructor(k,T){super(),this.painter=k,this.terrainTileForTile={},this.prevTerrainTileForTile={};const[B,K,Q]=function(){const we=new o.bD,Me=new o.ae,Re=131;we.reserve(17161),Me.reserve(33800);const Ze=o.a6/128,Qe=o.a6+Ze/2,ht=Qe+Ze;for(let bt=-Ze;btQe||bt<0||bt>Qe?24575:0,Qt=o.b1(Math.round(Mt),0,o.a6),Lt=o.b1(Math.round(bt),0,o.a6);we.emplaceBack(Qt+es,Lt)}const _t=(bt,Mt)=>{const es=Mt*Re+bt;Me.emplaceBack(es+1,es,es+Re),Me.emplaceBack(es+Re,es+Re+1,es+1)};for(let bt=1;bt<129;bt++)for(let Mt=1;Mt<129;Mt++)_t(Mt,bt);return[0,129].forEach(bt=>{for(let Mt=0;Mt<130;Mt++)_t(Mt,bt),_t(bt,Mt)}),[we,Me,32768]}(),le=k.context;this.gridBuffer=le.createVertexBuffer(B,o.bF.members),this.gridIndexBuffer=le.createIndexBuffer(K),this.gridSegments=o.ad.simpleSegment(0,0,B.length,K.length),this.gridNoSkirtSegments=o.ad.simpleSegment(0,0,B.length,Q),this.proxyCoords=[],this.proxiedCoords={},this._visibleDemTiles=[],this._drapedRenderBatches=[],this._sourceTilesOverlap={},this.proxySourceCache=new U_(T.map),this.orthoMatrix=o.Y(),o.bZ(this.orthoMatrix,this.painter.transform.projection.name==="globe"?.015:0,o.a6,0,o.a6,0,1);const me=le.gl;this._overlapStencilMode=new o._({func:me.GEQUAL,mask:255},0,255,me.KEEP,me.KEEP,me.REPLACE),this._previousZoom=k.transform.zoom,this.pool=[],this._findCoveringTileCache={},this._tilesDirty={},this.style=T,this._useVertexMorphing=!0,this._exaggeration=1,this._mockSourceCache=new Bk(T.map),this._pendingGroundEffectLayers=[],this._emissiveTexture="none",this._devtoolsFolder=null}set style(k){k.on("data",this._onStyleDataEvent.bind(this)),this._style=k,this._style.map.on("moveend",()=>{this._clearLineLayersFromRenderCache()})}update(k,T,B){if(k&&k.terrain){this._style!==k&&(this.style=k,this._evaluationZoom=void 0);const K=k.terrain.properties,Q=k.terrain.drapeRenderMode===0,le=k.terrain.isZoomDependent();this._previousUpdateTimestamp=this.enabled?this._updateTimestamp:void 0,this._updateTimestamp=o.e.now();const me=k.terrain&&k.terrain.scope,we=K.get("source"),Me=Q?this._mockSourceCache:k.getSourceCache(we,me);if(!Me)return void o.w(`Couldn't find terrain source "${we}".`);if(this.sourceCache=Me,this._attenuationRange=k.terrain.getAttenuationRange(),this._exaggeration=le?this.calculateExaggeration(T):K.get("exaggeration"),!T.projection.requiresDraping&&le&&this._exaggeration===0)return void this._disable();this.enabled=!0;const Re=()=>{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 Ze=this.getScaledDemTileSize();this.sourceCache.update(T,Ze,!0),this.resetTileLookupCache(this.sourceCache.id)};this.sourceCache.usedForTerrain||(this.resetTileLookupCache(this.sourceCache.id),this.sourceCache.usedForTerrain=!0,Re(),this._initializing=!0),Re(),T.updateElevation(!0,B),this.resetTileLookupCache(this.proxySourceCache.id),this.proxySourceCache.update(T),this._emptyDEMTextureDirty=!0,this._previousZoom=T.zoom}else this._disable()}calculateExaggeration(k){if(this._attenuationRange&&k.zoom>=Math.ceil(this._attenuationRange[1]))return this._style.terrain.getExaggeration(k.zoom);const T=this._previousCameraAltitude,B=k.getFreeCameraOptions().position.z/k.pixelsPerMeter*k.worldSize;this._previousCameraAltitude=B;const K=T!=null?B-T:Number.MAX_VALUE;if(Math.abs(K)<2)return this._exaggeration;const Q=k.zoom,le=this._style.terrain;if(!this._previousUpdateTimestamp)return le.getExaggeration(Q);let me=Q-this._previousZoom;const we=this._previousUpdateTimestamp;let Me=Q;this._evaluationZoom!=null&&(Me=this._evaluationZoom,Math.abs(Q-Me)>.5&&(me=.5*(Q-Me+me)),me*K<0&&(Me+=me)),this._evaluationZoom=Me;const Re=le.getExaggeration(Me),Ze=Re===le.getExaggeration(Math.max(0,Me-.1));if(Ze&&Math.abs(Re-this._exaggeration)<.01)return Re;let Qe=Math.min(.1,.00375*(this._updateTimestamp-we));return(Ze||Re<.1||Math.abs(me)<1e-4)&&(Qe=Math.min(.2,4*Qe)),o.am(this._exaggeration,Re,Qe)}resetTileLookupCache(k){this._findCoveringTileCache[k]={}}attenuationRange(){return this._attenuationRange}getDemUpscale(){return this.proxySourceCache.getSource().tileSize/128}getScaledDemTileSize(){return this.sourceCache.getSource().tileSize/128*this.proxySourceCache.getSource().tileSize}_onStyleDataEvent(k){k.dataType==="source"&&k.coord?this._clearRenderCacheForTile(k.sourceCacheId,k.coord):k.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 k in this._style._mergedSourceCaches)this._style._mergedSourceCaches[k].usedForTerrain=!1}destroy(){this._disable(),this._emptyDEMTexture&&this._emptyDEMTexture.destroy(),this.pool.forEach(k=>k.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 k=2*this.proxySourceCache.getSource().tileSize;return[k,k]}set useVertexMorphing(k){this._useVertexMorphing=k}updateTileBinding(k){if(!this.enabled)return;this.prevTerrainTileForTile=this.terrainTileForTile;const T=this.proxySourceCache,B=this.painter.transform;this._initializing&&(this._initializing=B._centerAltitude===0&&this.getAtPointOrZero(o.bT.fromLngLat(B.center),-1)===-1,this._emptyDEMTextureDirty=!this._initializing);const K=this.proxyCoords=T.getIds().map(we=>{const Me=T.getTileByID(we).tileID;return Me.projMatrix=B.calculateProjMatrix(Me.toUnwrapped()),Me});(function(we,Me){const Re=Me.transform.pointCoordinate(Me.transform.getCameraPoint()),Ze=new o.P(Re.x,Re.y);we.sort((Qe,ht)=>{if(ht.overscaledZ-Qe.overscaledZ)return ht.overscaledZ-Qe.overscaledZ;const _t=new o.P(Qe.canonical.x+(1<{this.proxyToSource[we.key]={}}),this.terrainTileForTile={};const le=this._style._mergedSourceCaches;for(const we in le){const Me=le[we];if(!Me.used||!Me.transform||(Me!==this.sourceCache&&this.resetTileLookupCache(Me.id),this._setupProxiedCoordsForOrtho(Me,k[we],Q),Me.usedForTerrain))continue;const Re=k[we];(Me.getSource().reparseOverscaled||Me._isRasterElevatedOverTerrain)&&this._assignTerrainTiles(Re)}this.proxiedCoords[T.id]=K.map(we=>new rj(we,we.key,this.orthoMatrix)),this._assignTerrainTiles(K),this._prepareDEMTextures(),this._setupDrapedRenderBatches(),this._initFBOPool(),this._setupRenderCache(Q),this.renderingToTexture=!1;const me={};this._visibleDemTiles=[];for(const we of this.proxyCoords){const Me=this.terrainTileForTile[we.key];if(!Me)continue;const Re=Me.tileID.key;Re in me||(this._visibleDemTiles.push(Me),me[Re]=Re)}}_assignTerrainTiles(k){this._initializing||k.forEach(T=>{if(this.terrainTileForTile[T.key])return;const B=this._findTileCoveringTileID(T,this.sourceCache);B&&(this.terrainTileForTile[T.key]=B)})}_prepareDEMTextures(){const k=this.painter.context,T=k.gl;for(const B in this.terrainTileForTile){const K=this.terrainTileForTile[B],Q=K.dem;!Q||K.demTexture&&!K.needsDEMTextureUpload||(k.activeTexture.set(T.TEXTURE1),Qg(this.painter,K,Q))}}_prepareDemTileUniforms(k,T,B,K){if(!T||T.demTexture==null)return!1;const Q=k.tileID.canonical,le=Math.pow(2,T.tileID.canonical.z-Q.z),me=K||"";return B[`u_dem_tl${me}`]=[Q.x*le%1,Q.y*le%1],B[`u_dem_scale${me}`]=le,!0}get emptyDEMTexture(){return!this._emptyDEMTextureDirty&&this._emptyDEMTexture?this._emptyDEMTexture:this._updateEmptyDEMTexture()}_getLoadedAreaMinimum(){if(!this.enabled)return 0;let k=0;const T=this._visibleDemTiles.reduce((B,K)=>{if(!K.dem)return B;const Q=K.dem.tree.minimums[0];return Q>0&&k++,B+Q},0);return k?T/k:0}_updateEmptyDEMTexture(){const k=this.painter.context,T=k.gl;k.activeTexture.set(T.TEXTURE2);const B=this._getLoadedAreaMinimum(),K=new o.c3({width:1,height:1},new Float32Array([B]));this._emptyDEMTextureDirty=!1;let Q=this._emptyDEMTexture;return Q?Q.update(K,{premultiply:!1}):Q=this._emptyDEMTexture=new o.T(k,K,T.R32F,{premultiply:!1}),Q}setupElevationDraw(k,T,B){const K=this.painter.context,Q=K.gl,le={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};le.u_exaggeration=this.exaggeration();let me=null,we=null,Me=1;if(B&&B.morphing&&this._useVertexMorphing){const ht=B.morphing.srcDemTile,_t=B.morphing.dstDemTile;Me=B.morphing.phase,ht&&_t&&(this._prepareDemTileUniforms(k,ht,le,"_prev")&&(we=ht),this._prepareDemTileUniforms(k,_t,le)&&(me=_t))}const Re=ht=>ht&&ht.demTexture&&this.painter.linearFloatFilteringSupported()?Q.LINEAR:Q.NEAREST;let Ze=null;var Qe;if(this.enabled?we&&me?(Ze=me.demTexture,K.activeTexture.set(Q.TEXTURE4),we.demTexture.bind(Re(we),Q.CLAMP_TO_EDGE),le.u_dem_lerp=Me):(me=this.terrainTileForTile[k.tileID.key],Ze=this._prepareDemTileUniforms(k,me,le)?me.demTexture:this.emptyDEMTexture):Ze=this.emptyDEMTexture,K.activeTexture.set(Q.TEXTURE2),Ze&&(le.u_dem_size=(Qe=Ze).size[0]===1?1:Qe.size[0]-2,Ze.bind(Re(me),Q.CLAMP_TO_EDGE)),this.painter.setupDepthForOcclusion(B&&B.useDepthForOcclusion,T,le),B&&B.useMeterToDem&&me){const ht=(1<{if(es===zn)return;const Dr=[];zn===1&&Dr.push("TERRAIN_VERTEX_MORPHING"),Dr.push("PROJECTION_GLOBE_VIEW"),Lt&&Dr.push("CUSTOM_ANTIALIASING");const An=Me.isTileAffectedByFog($n);Mt=Me.getOrCreateProgram("globeRaster",{defines:Dr,overrideFog:An}),es=zn},Hs=Me.colorModeForRenderPass(),Fs=new o.Z(bt.LEQUAL,o.Z.ReadWrite,Me.depthRangeFor3D);G0.update(ht);const nn=o.b7(Qt),$s=[o.a7(Qt.center.lng),o.a8(Qt.center.lat)],rn=Me.globeSharedBuffers,_n=[Qt.width*o.e.devicePixelRatio,Qt.height*o.e.devicePixelRatio],Mn=Float32Array.from(Qt.globeMatrix),Yn={useDenormalizedUpVectorScale:!0};{const $n=Me.transform,zn=zx($n.zoom,Re.exaggeration(),Re.sourceCache._source.tileSize);es=-1;const Dr=bt.TRIANGLES;for(const An of Qe){const yr=Ze.getTile(An),sa=o._.disabled,ka=Re.prevTerrainTileForTile[An.key],Hr=Re.terrainTileForTile[An.key];H0(ka,Hr)&&G0.newMorphing(An.key,ka,Hr,ht,250),X2(Me,yr.emissiveTexture),_t.activeTexture.set(bt.TEXTURE0),yr.texture&&yr.texture.bind(bt.LINEAR,bt.CLAMP_TO_EDGE);const ea=G0.getMorphValuesForProxy(An.key),si=ea?1:0;ea&&Object.assign(Yn,{morphing:{srcDemTile:ea.from,dstDemTile:ea.to,phase:o.b$(ea.phase)}});const Wr=o.b3(An.canonical),Mr=o.b4(Wr.getCenter().lat),Gr=o.b8(An.canonical,Wr,Mr,$n.worldSize/$n._pixelsPerMercatorPixel),Ga=o.b5(o.b6(An.canonical)),Vr=Me.isEmissiveMrtActive()?1:0,Za=$1($n.expandedFarZProjMatrix,Mn,nn,Ga,o.S($n.zoom),$s,$n.frustumCorners.TL,$n.frustumCorners.TR,$n.frustumCorners.BR,$n.frustumCorners.BL,$n.globeCenterInViewSpace,$n.globeRadius,_n,zn,$n._farZ,Vr,Gr);if(ps(An,si),Mt&&(Re.setupElevationDraw(yr,Mt,Yn),Me.uploadCommonUniforms(_t,Mt,An.toUnwrapped()),rn)){const[Oi,Do,so]=rn.getGridBuffers(Mr,zn!==0);Mt.draw(Me,Dr,Fs,sa,Hs,o.$.backCCW,Za,"globe_raster",Oi,Do,so)}}}if(rn&&(Me.renderDefaultNorthPole||Me.renderDefaultSouthPole)){const $n=["GLOBE_POLES","PROJECTION_GLOBE_VIEW"];Lt&&$n.push("CUSTOM_ANTIALIASING"),Mt=Me.getOrCreateProgram("globeRaster",{defines:$n});for(const zn of Qe){const{x:Dr,y:An,z:yr}=zn.canonical,sa=An===0,ka=An===(1<Oi.draw(Me,bt.TRIANGLES,Fs,o._.disabled,Hs,o.$.disabled,$1(Qt.expandedFarZProjMatrix,Gr,Gr,Ga,0,$s,Qt.frustumCorners.TL,Qt.frustumCorners.TR,Qt.frustumCorners.BR,Qt.frustumCorners.BL,Qt.globeCenterInViewSpace,Qt.globeRadius,_n,0,Qt._farZ,Vr),"globe_pole_raster",Do,si,Wr);Re.setupElevationDraw(Mr,Mt,Yn),Me.uploadCommonUniforms(_t,Mt,zn.toUnwrapped()),sa&&Me.renderDefaultNorthPole&&Za(Mt,Hr),ka&&Me.renderDefaultSouthPole&&(Gr=o.aO(o.Y(),Gr,[1,-1,1]),Za(Mt,ea))}}}})(K,Q,le,me,we);else{const Me=K.context,Re=Me.gl;let Ze,Qe;const ht=K.shadowRenderer,_t=o.aF(K,K.longestCutoffRange),bt=Hs=>{if(Qe===Hs)return;const Fs=[];Hs===1&&Fs.push("TERRAIN_VERTEX_MORPHING"),_t.shouldRenderCutoff&&Fs.push("RENDER_CUTOFF"),ht&&(Fs.push("RENDER_SHADOWS"),ht.useNormalOffset&&Fs.push("NORMAL_OFFSET")),Ze=K.getOrCreateProgram("terrainRaster",{defines:Fs}),Qe=Hs},Mt=K.colorModeForRenderPass(),es=new o.Z(Re.LEQUAL,o.Z.ReadWrite,K.depthRangeFor3D);G0.update(we);const Qt=K.transform,Lt=zx(Qt.zoom,Q.exaggeration(),Q.sourceCache._source.tileSize);let ps=[0,0,0];if(ht){const Hs=K.style.directionalLight,Fs=K.style.ambientLight;Hs&&Fs&&(ps=o.aG(K.style,Hs,Fs))}{Qe=-1;const Hs=Re.TRIANGLES,[Fs,nn]=[Q.gridIndexBuffer,Q.gridSegments];for(const $s of me){const rn=le.getTile($s),_n=o._.disabled,Mn=Q.prevTerrainTileForTile[$s.key],Yn=Q.terrainTileForTile[$s.key];H0(Mn,Yn)&&G0.newMorphing($s.key,Mn,Yn,we,250),X2(K,rn.emissiveTexture),Me.activeTexture.set(Re.TEXTURE0),rn.texture&&rn.texture.bind(Re.LINEAR,Re.CLAMP_TO_EDGE);const $n=G0.getMorphValuesForProxy($s.key),zn=$n?1:0;let Dr;$n&&(Dr={morphing:{srcDemTile:$n.from,dstDemTile:$n.to,phase:o.b$($n.phase)}});const An=K.isEmissiveMrtActive()?1:0,yr=hf($s.projMatrix,Ok($s.canonical,Qt.renderWorldCopies)?Lt/10:Lt,ps,An);if(bt(zn),!Ze)continue;Q.setupElevationDraw(rn,Ze,Dr);const sa=$s.toUnwrapped();ht&&ht.setupShadows(sa,Ze),K.uploadCommonUniforms(Me,Ze,sa,null,_t),Ze.draw(K,Hs,es,_n,Mt,o.$.backCCW,yr,"terrain_raster",Q.gridBuffer,Fs,nn)}}}}(T,this,this.proxySourceCache,k,this._updateTimestamp),this.renderingToTexture=!0,T.gpuTimingDeferredRenderEnd(),k.splice(0,k.length))}renderBatch(k){if(this._drapedRenderBatches.length===0)return k+1;this.renderingToTexture=!0;const T=this.painter,B=this.painter.context,K=this.proxySourceCache,Q=this.proxiedCoords[K.id],le=this._drapedRenderBatches.shift(),me=T.style.order,we=[];this._updateFBOs(T.emissiveMode==="mrt-full-rgba"?"rgba8":T.emissiveMode==="mrt-fallback"?"r8":"none");let Me=0;for(const Re of Q){const Ze=K.getTileByID(Re.proxyTileKey),Qe=K.proxyCachedFBO[Re.key]?K.proxyCachedFBO[Re.key][k]:void 0,ht=Qe!==void 0?K.renderCache[Qe]:this.pool[Me++],_t=Qe!==void 0;if(Ze.texture=ht.tex,Ze.emissiveTexture=ht.emissiveTex,_t&&!ht.dirty){we.push(Ze.tileID);continue}B.bindFramebuffer.set(ht.fb.framebuffer);const bt=B.gl;let Mt;T.isEmissiveMrtActive()?bt.drawBuffers([bt.COLOR_ATTACHMENT0,bt.COLOR_ATTACHMENT1]):bt.drawBuffers([bt.COLOR_ATTACHMENT0]),this.renderedToTile=!1,ht.dirty&&(B.clear({color:o.C.transparent,stencil:0}),ht.dirty=!1);for(let es=le.start;es<=le.end;++es){const Qt=T.style._mergedLayers[me[es]];if(Qt.isHidden(T.transform.zoom))continue;const Lt=T.style.getLayerSourceCache(Qt),ps=Lt?this.proxyToSource[Re.key][Lt.id]:[Re];if(!ps)continue;const Hs=ps;B.viewport.set([0,0,ht.fb.width,ht.fb.height]),Mt!==(Lt?Lt.id:null)&&(this._setupStencil(ht,ps,Qt,Lt),Mt=Lt?Lt.id:null),T.renderLayer(T,Lt,Qt,Hs)}if(bt.drawBuffers([bt.COLOR_ATTACHMENT0]),this._drapedRenderBatches.length===0)for(const es of this._pendingGroundEffectLayers){const Qt=T.style._mergedLayers[me[es]];if(Qt.isHidden(T.transform.zoom))continue;const Lt=T.style.getLayerSourceCache(Qt),ps=Lt?this.proxyToSource[Re.key][Lt.id]:[Re];if(!ps)continue;const Hs=ps;B.viewport.set([0,0,ht.fb.width,ht.fb.height]),Mt!==(Lt?Lt.id:null)&&(this._setupStencil(ht,ps,Qt,Lt),Mt=Lt?Lt.id:null),T.renderLayer(T,Lt,Qt,Hs)}this.renderedToTile?(ht.dirty=!0,we.push(Ze.tileID)):_t||--Me,Me===5&&(Me=0,this.renderToBackBuffer(we))}return this.renderToBackBuffer(we),this.renderingToTexture=!1,B.bindFramebuffer.set(null),B.viewport.set([0,0,T.width,T.height]),le.end+1}postRender(){}isLayerOrderingCorrect(k){const T=k.order.length;let B=-1,K=T;for(let Q=0;QB}getMinElevationBelowMSL(){let k=0;return this._visibleDemTiles.filter(T=>T.dem).forEach(T=>{k=Math.min(k,T.dem.tree.minimums[0])}),k===0?k:(k-30)*this._exaggeration}raycast(k,T,B){if(!this._visibleDemTiles)return null;const K=this._visibleDemTiles.filter(Q=>Q.dem).map(Q=>{const le=Q.tileID,me=1<(Q.t!==null?Q.t:Number.MAX_VALUE)-(le.t!==null?le.t:Number.MAX_VALUE));for(const Q of K){if(Q.t==null)return null;const le=Q.tile.dem.tree.raycast(Q.minx,Q.miny,Q.maxx,Q.maxy,k,T,B);if(le!=null)return le}return null}_createFBO(){const k=this.painter.context,T=k.gl,B=this.drapeBufferSize;k.activeTexture.set(T.TEXTURE0);const K=new o.T(k,{width:B[0],height:B[1],data:null},T.RGBA8);K.bind(T.LINEAR,T.CLAMP_TO_EDGE);const Q=k.createFramebuffer(B[0],B[1],1,null);let le;return Q.colorAttachment0.set(K.texture),this._emissiveTexture!=="none"&&(le=new o.T(k,{width:B[0],height:B[1],data:null},q_(T,this._emissiveTexture)),le.bind(T.LINEAR,T.CLAMP_TO_EDGE),Q.createColorAttachment(k,1),Q.colorAttachment1.set(le.texture)),Q.depthAttachment=new tx(k,Q.framebuffer),this._sharedDepthStencil===void 0?(this._sharedDepthStencil=k.createRenderbuffer(k.gl.DEPTH_STENCIL,B[0],B[1]),this._stencilRef=0,Q.depthAttachment.set(this._sharedDepthStencil),k.clear({stencil:0})):Q.depthAttachment.set(this._sharedDepthStencil),k.extTextureFilterAnisotropic&&T.texParameterf(T.TEXTURE_2D,k.extTextureFilterAnisotropic.TEXTURE_MAX_ANISOTROPY_EXT,k.extTextureFilterAnisotropicMax),{fb:Q,tex:K,emissiveTex:le,dirty:!1}}_updateFBOs(k){if(this._emissiveTexture!==k){for(const T of this.pool)this._updateFBO(T,k);for(const T of this.proxySourceCache.renderCache)this._updateFBO(T,k);this._emissiveTexture=k}}_updateFBO(k,T){const B=k.fb,K=this.painter.context,Q=K.gl,le=this.drapeBufferSize;if(T!=="none"){const me=new o.T(K,{width:le[0],height:le[1],data:null},q_(Q,T));me.bind(Q.LINEAR,Q.CLAMP_TO_EDGE),k.emissiveTex=me,B.createColorAttachment(K,1),B.colorAttachment1.set(me.texture)}else k.emissiveTex=void 0,B.removeColorAttachment(K,1);k.dirty=!0}_initFBOPool(){for(;this.pool.length{const T=this._style._mergedLayers[k],B=T.isHidden(this.painter.transform.zoom);return T.type==="hillshade"||T.type==="custom"?!B&&T.shouldRedrape():!B&&T.hasTransition()})}_clearLineLayersFromRenderCache(){let k=!1;for(const B of this._style.getSources())if(B.type==="vector"){k=!0;break}if(!k)return;const T={};for(let B=0;Bwe>me.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=B}_setupRenderCache(k){const T=this.proxySourceCache;if(this._shouldDisableRenderCache()||this.invalidateRenderCache){if(this.invalidateRenderCache=!1,T.renderCache.length>T.renderCachePool.length){const le=Object.values(T.proxyCachedFBO);T.proxyCachedFBO={};for(let me=0;me=0;le--){const me=B[le];if(T.getTileByID(me.key),T.proxyCachedFBO[me.key]!==void 0){const we=k[me.key],Me=this.proxyToSource[me.key];let Re=0;for(const Ze in Me){const Qe=Me[Ze],ht=we[Ze];if(!ht||ht.length!==Qe.length||Qe.some((_t,bt)=>_t!==ht[bt]||K[Ze]&&Object.hasOwn(K[Ze],_t.key))){Re=-1;break}++Re}for(const Ze in T.proxyCachedFBO[me.key])T.renderCache[T.proxyCachedFBO[me.key][Ze]].dirty=Re<0||Re!==Object.values(we).length}}const Q=[...this._drapedRenderBatches];Q.sort((le,me)=>me.end-me.start-(le.end-le.start));for(const le of Q)for(const me of B){if(T.proxyCachedFBO[me.key])continue;let we=T.renderCachePool.pop();we===void 0&&T.renderCache.length<50&&(we=T.renderCache.length,T.renderCache.push(this._createFBO())),we!==void 0&&(T.proxyCachedFBO[me.key]={},T.proxyCachedFBO[me.key][le.start]=we,T.renderCache[we].dirty=!0)}this._tilesDirty={}}_setupStencil(k,T,B,K){if(!K||!this._sourceTilesOverlap[K.id])return void(this._overlapStencilType&&(this._overlapStencilType=!1));const Q=this.painter.context,le=Q.gl;if(T.length<=1)return void(this._overlapStencilType=!1);let me;if(B.isTileClipped())me=T.length,this._overlapStencilMode.test={func:le.EQUAL,mask:255},this._overlapStencilType="Clip";else{if(!(T[0].overscaledZ>T.at(-1).overscaledZ))return void(this._overlapStencilType=!1);me=1,this._overlapStencilMode.test={func:le.GREATER,mask:255},this._overlapStencilType="Mask"}this._stencilRef+me>255&&(Q.clear({stencil:0}),this._stencilRef=0),this._stencilRef+=me,this._overlapStencilMode.ref=this._stencilRef,B.isTileClipped()&&this._renderTileClippingMasks(T,this._overlapStencilMode.ref)}clipOrMaskOverlapStencilType(){return this._overlapStencilType==="Clip"||this._overlapStencilType==="Mask"}stencilModeForRTTOverlap(k){return this.renderingToTexture&&this._overlapStencilType?(this._overlapStencilType==="Clip"&&(this._overlapStencilMode.ref=this.painter._tileClippingMaskIDs[k.key]),this._overlapStencilMode):o._.disabled}_renderTileClippingMasks(k,T){const B=this.painter,K=this.painter.context,Q=K.gl;B._tileClippingMaskIDs={},K.setColorMode(o.a1.disabled),K.setDepthMode(o.Z.disabled);const le=B.getOrCreateProgram("clippingMask");for(const me of k){const we=B._tileClippingMaskIDs[me.key]=--T;le.draw(B,Q.TRIANGLES,o.Z.disabled,new o._({func:Q.ALWAYS,mask:0},we,255,Q.KEEP,Q.KEEP,Q.REPLACE),o.a1.disabled,o.$.disabled,yu(me.projMatrix),"$clipping",B.tileExtentBuffer,B.quadTriangleIndexBuffer,B.tileExtentSegments)}}pointCoordinate(k){const T=this.painter.transform;if(k.x<0||k.x>T.width||k.y<0||k.y>T.height)return null;const B=[k.x,k.y,1,1];o.c6(B,B,T.pixelMatrixInverse),o.c7(B,B,1/B[3]),B[0]/=T.worldSize,B[1]/=T.worldSize;const K=T._camera.position,Q=o.c4(1,T.center.lat),le=[K[0],K[1],K[2]/Q,0],me=o.c8([],B.slice(0,3),le);o.c9(me,me);const we=this.raycast(le,me,this._exaggeration);return we!==null&&we?(o.ca(le,le,me,we),le[3]=le[2],le[2]*=Q,le):null}_setupProxiedCoordsForOrtho(k,T,B){if(["image","video","canvas"].includes(k.getSource().type))return this._setupProxiedCoordsForImageSource(k,T,B);this._findCoveringTileCache[k.id]=this._findCoveringTileCache[k.id]||{};const K=this.proxiedCoords[k.id]=[],Q=this.proxyCoords;for(let we=0;weRe.overscaledZ-Me.overscaledZ)}_setupProxiedCoordsForImageSource(k,T,B){if(!k.getSource().loaded())return;const K=this.proxiedCoords[k.id]=[],Q=this.proxyCoords,le=k.getSource(),me=le.tileID;if(!me)return;const we=new o.P(me.x,me.y)._div(1<(Ze.min.x=Math.min(Ze.min.x,Qe.x-we.x),Ze.min.y=Math.min(Ze.min.y,Qe.y-we.y),Ze.max.x=Math.max(Ze.max.x,Qe.x-we.x),Ze.max.y=Math.max(Ze.max.y,Qe.y-we.y),Ze),{min:new o.P(Number.MAX_VALUE,Number.MAX_VALUE),max:new o.P(-Number.MAX_VALUE,-Number.MAX_VALUE)}),Re=(Ze,Qe)=>{const ht=Ze.wrap+Ze.canonical.x/(1<Mt+Me.max.x||_t+btes+Me.max.y};for(let Ze=0;Zele.key===T.tileID.key);if(Q)return Q}if(T.tileID.key!==k.key){const Q=k.canonical.z-T.tileID.canonical.z;let le,me,we;K=o.Y();const Me=T.tileID.wrap-k.wrap<0?(le=o.a6>>Q,me=le*((T.tileID.canonical.x<=Ze){const Qe=k.canonical.z-Ze;T.getSource().reparseOverscaled?(me=Math.max(k.canonical.z+2,T.transform.tileZoom),le=new o.bQ(me,k.wrap,Ze,k.canonical.x>>Qe,k.canonical.y>>Qe)):Qe!==0&&(me=Ze,le=new o.bQ(me,k.wrap,Ze,k.canonical.x>>Qe,k.canonical.y>>Qe))}le.key!==k.key&&(Me.push(le.key),B=T.getTile(le))}const Re=Ze=>{Me.forEach(Qe=>{K[Qe]=Ze}),Me.length=0};for(me-=1;me>=we&&(!B||!B.hasData());me--){B&&Re(B.tileID.key);const Ze=le.calculateScaledKey(me);if(B=T.getTileByID(Ze),B&&B.hasData())break;const Qe=K[Ze];if(Qe===null)break;Qe===void 0?Me.push(Ze):B=T.getTileByID(Qe)}return Re(B?B.tileID.key:null),B&&B.hasData()?B:null}findDEMTileFor(k){return this.enabled?this._findTileCoveringTileID(k,this.sourceCache):null}prepareDrawTile(){this.renderedToTile=!0}_clearRenderCacheForTile(k,T){let B=this._tilesDirty[k];B||(B=this._tilesDirty[k]={}),B[T.key]=!0}}let Q2=null;const V_=[];function sx(L,k){return Q2?Q2.create(L,k):null}const zC=(L,k,T)=>({u_matrix:L,u_emissive_strength:k,u_ground_shadow_factor:T,u_opacity_multiplier:1}),U1=(L,k,T,B,K,Q=0)=>Object.assign(zC(L,k,K),o.cb(T,B,Q)),aj=(L,k,T,B)=>({u_matrix:L,u_world:T,u_emissive_strength:k,u_ground_shadow_factor:B,u_opacity_multiplier:1}),Pe=(L,k,T,B,K,Q,le=0)=>Object.assign(U1(L,k,T,B,Q,le),{u_world:K}),He=(L,k,T)=>({u_image:L,u_texel_size:k,u_first_pass:T?1:0}),pt=o.Y(),Tt=(L,k,T,B,K,Q,le)=>{const me=L.transform,we=me.projection.name==="globe",Me=we?o.cc(me.zoom,k.canonical)*me._pixelsPerMercatorPixel:o.cd(T,1,Q),Re={u_matrix:k.projMatrix,u_extrude_scale:Me,u_intensity:le,u_inv_rot_matrix:pt,u_merc_center:[0,0],u_tile_id:[0,0,0],u_zoom_transition:0,u_up_dir:[0,0,0]};if(we){Re.u_inv_rot_matrix=B,Re.u_merc_center=K,Re.u_tile_id=[k.canonical.x,k.canonical.y,1<({u_matrix:k,u_normalize_matrix:T,u_globe_matrix:B,u_merc_matrix:K,u_grid_matrix:Q,u_tl_parent:le,u_scale_parent:Re,u_fade_t:Ze.mix,u_opacity:Ze.opacity*Qe.paint.get("raster-opacity"),u_image0:0,u_image1:1,u_brightness_low:Qe.paint.get("raster-brightness-min"),u_brightness_high:Qe.paint.get("raster-brightness-max"),u_saturation_factor:o.cg(Qe.paint.get("raster-saturation")),u_contrast_factor:o.cf(Qe.paint.get("raster-contrast")),u_spin_weights:Es(Qe.paint.get("raster-hue-rotate")),u_perspective_transform:ht,u_raster_elevation:_t,u_zoom_transition:me,u_merc_center:we,u_cutoff_params:Me,u_colorization_mix:ql(o.ce,Mt,Qt),u_colorization_offset:po(o.ce,es,Qt),u_color_ramp:bt,u_color_ramp_size:o.ce,u_texture_offset:[ps/(Lt+2*ps),Lt/(Lt+2*ps)],u_texture_res:[Lt+2*ps,Lt+2*ps],u_emissive_strength:Hs,u_zbias_factor:is(L)});function Es(L){L*=Math.PI/180;const k=Math.sin(L),T=Math.cos(L);return[(2*T+1)/3,(-Math.sqrt(3)*k-T+1)/3,(Math.sqrt(3)*k-T+1)/3]}const Ds=o.Y(),qs=(L,k,T,B,K,Q,le,me,we,Me,Re,Ze,Qe,ht,_t,bt,Mt,es,Qt,Lt,ps,Hs,Fs,nn,$s)=>{const rn=K.transform,_n={u_is_size_zoom_constant:+(L==="constant"||L==="source"),u_is_size_feature_constant:+(L==="constant"||L==="camera"),u_size_t:k?k.uSizeT:0,u_size:k?k.uSize:0,u_camera_to_center_distance:rn.getCameraToCenterDistance(Lt),u_rotate_symbol:+T,u_aspect_ratio:rn.width/rn.height,u_fade_change:K.options.fadeDuration?K.symbolFadeChange:1,u_matrix:Q,u_label_plane_matrix:le,u_coord_matrix:me,u_is_text:+Me,u_is_sdf:+Re,u_elevation_from_sea:we?1:0,u_pitch_with_map:+B,u_texsize:Ze,u_texsize_icon:Qe,u_texture:0,u_texture_icon:1,u_tile_id:[0,0,0],u_zoom_transition:0,u_inv_rot_matrix:Ds,u_merc_center:[0,0],u_camera_forward:[0,0,0],u_ecef_origin:[0,0,0],u_tile_matrix:Ds,u_up_vector:[0,-1,0],u_color_adj_mat:Fs,u_icon_transition:nn||0,u_gamma_scale:Re?B?K.transform.getCameraToCenterDistance(Lt)*Math.cos(K.terrain?0:K.transform._pitch):1:0,u_device_pixel_ratio:o.e.devicePixelRatio,u_is_halo:1,u_scale_factor:$s||1,u_ground_shadow_factor:ps,u_inv_matrix:o.aP(o.Y(),le),u_normal_scale:Hs,u_lutTexture:o.ci.LUT,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],u_spp_zoom_fraction:0,u_opacity_multiplier:1};return Lt.name==="globe"&&(_n.u_tile_id=[_t.canonical.x,_t.canonical.y,1<<_t.canonical.z],_n.u_zoom_transition=bt,_n.u_inv_rot_matrix=es,_n.u_merc_center=Mt,_n.u_camera_forward=rn._camera.forward(),_n.u_ecef_origin=o.ch(rn.globeMatrix,_t.toUnwrapped()),_n.u_tile_matrix=rn.globeMatrix,_n.u_up_vector=Qt),_n},on=(L,k,T,B)=>({u_matrix:L,u_emissive_strength:k,u_opacity:T,u_color:B}),Xn=(L,k,T,B,K,Q,le,me,we)=>Object.assign(o.cj(K,Q,le,B,me,we),{u_matrix:L,u_emissive_strength:k,u_opacity:T}),Cr={fillExtrusion:o.cp,fillExtrusionPattern:o.co,fill:L=>({u_matrix:new o.a4(L),u_emissive_strength:new o.a3(L),u_ground_shadow_factor:new o.a5(L),u_opacity_multiplier:new o.a3(L)}),fillPattern:L=>({u_matrix:new o.a4(L),u_emissive_strength:new o.a3(L),u_image:new o.aY(L),u_texsize:new o.a2(L),u_pixel_coord_upper:new o.a2(L),u_pixel_coord_lower:new o.a2(L),u_tile_units_to_pixels:new o.a3(L),u_ground_shadow_factor:new o.a5(L),u_pattern_transition:new o.a3(L),u_opacity_multiplier:new o.a3(L)}),fillOutline:L=>({u_matrix:new o.a4(L),u_emissive_strength:new o.a3(L),u_world:new o.a2(L),u_ground_shadow_factor:new o.a5(L),u_opacity_multiplier:new o.a3(L)}),fillOutlinePattern:L=>({u_matrix:new o.a4(L),u_emissive_strength:new o.a3(L),u_world:new o.a2(L),u_image:new o.aY(L),u_texsize:new o.a2(L),u_pixel_coord_upper:new o.a2(L),u_pixel_coord_lower:new o.a2(L),u_tile_units_to_pixels:new o.a3(L),u_ground_shadow_factor:new o.a5(L),u_pattern_transition:new o.a3(L),u_opacity_multiplier:new o.a3(L)}),lineBlendComposite:L=>({u_image:new o.aY(L),u_opacity:new o.a3(L),u_blend_mode:new o.aY(L),u_max_density:new o.a3(L)}),lineBlendReduce:L=>({u_image:new o.aY(L),u_texel_size:new o.a2(L),u_first_pass:new o.aY(L)}),circle:o.cn,collisionBox:L=>({u_matrix:new o.a4(L),u_inv_rot_matrix:new o.a4(L),u_camera_to_center_distance:new o.a3(L),u_extrude_scale:new o.a2(L),u_zoom_transition:new o.a3(L),u_merc_center:new o.a2(L),u_tile_id:new o.a5(L)}),collisionCircle:L=>({u_matrix:new o.a4(L),u_inv_matrix:new o.a4(L),u_camera_to_center_distance:new o.a3(L),u_viewport_size:new o.a2(L)}),debug:o.cm,clippingMask:L=>({u_matrix:new o.a4(L)}),heatmap:L=>({u_extrude_scale:new o.a3(L),u_intensity:new o.a3(L),u_matrix:new o.a4(L),u_inv_rot_matrix:new o.a4(L),u_merc_center:new o.a2(L),u_tile_id:new o.a5(L),u_zoom_transition:new o.a3(L),u_up_dir:new o.a5(L)}),heatmapTexture:L=>({u_image:new o.aY(L),u_color_ramp:new o.aY(L),u_opacity:new o.a3(L)}),hillshade:L=>({u_matrix:new o.a4(L),u_image:new o.aY(L),u_latrange:new o.a2(L),u_light:new o.a2(L),u_shadow:new o.bY(L),u_highlight:new o.bY(L),u_emissive_strength:new o.a3(L),u_accent:new o.bY(L)}),hillshadePrepare:L=>({u_matrix:new o.a4(L),u_image:new o.aY(L),u_dimension:new o.a2(L),u_zoom:new o.a3(L)}),line:o.cl,linePattern:o.ck,raster:L=>({u_matrix:new o.a4(L),u_normalize_matrix:new o.a4(L),u_globe_matrix:new o.a4(L),u_merc_matrix:new o.a4(L),u_grid_matrix:new o.a_(L),u_tl_parent:new o.a2(L),u_scale_parent:new o.a3(L),u_fade_t:new o.a3(L),u_opacity:new o.a3(L),u_image0:new o.aY(L),u_image1:new o.aY(L),u_brightness_low:new o.a3(L),u_brightness_high:new o.a3(L),u_saturation_factor:new o.a3(L),u_contrast_factor:new o.a3(L),u_spin_weights:new o.a5(L),u_perspective_transform:new o.a2(L),u_raster_elevation:new o.a3(L),u_zoom_transition:new o.a3(L),u_merc_center:new o.a2(L),u_cutoff_params:new o.aZ(L),u_colorization_mix:new o.aZ(L),u_colorization_offset:new o.a3(L),u_color_ramp:new o.aY(L),u_color_ramp_size:new o.a3(L),u_texture_offset:new o.a2(L),u_texture_res:new o.a2(L),u_emissive_strength:new o.a3(L),u_zbias_factor:new o.a3(L)}),symbol:L=>({u_is_size_zoom_constant:new o.aY(L),u_is_size_feature_constant:new o.aY(L),u_size_t:new o.a3(L),u_size:new o.a3(L),u_camera_to_center_distance:new o.a3(L),u_rotate_symbol:new o.aY(L),u_aspect_ratio:new o.a3(L),u_fade_change:new o.a3(L),u_matrix:new o.a4(L),u_label_plane_matrix:new o.a4(L),u_coord_matrix:new o.a4(L),u_is_text:new o.aY(L),u_is_sdf:new o.aY(L),u_elevation_from_sea:new o.aY(L),u_pitch_with_map:new o.aY(L),u_texsize:new o.a2(L),u_texsize_icon:new o.a2(L),u_texture:new o.aY(L),u_texture_icon:new o.aY(L),u_gamma_scale:new o.a3(L),u_device_pixel_ratio:new o.a3(L),u_tile_id:new o.a5(L),u_zoom_transition:new o.a3(L),u_inv_rot_matrix:new o.a4(L),u_merc_center:new o.a2(L),u_camera_forward:new o.a5(L),u_tile_matrix:new o.a4(L),u_up_vector:new o.a5(L),u_ecef_origin:new o.a5(L),u_is_halo:new o.aY(L),u_icon_transition:new o.a3(L),u_color_adj_mat:new o.a4(L),u_scale_factor:new o.a3(L),u_ground_shadow_factor:new o.a5(L),u_inv_matrix:new o.a4(L),u_normal_scale:new o.a3(L),u_lutTexture:new o.aY(L),u_spp_fill_np_color:new o.aZ(L),u_spp_halo_np_color:new o.aZ(L),u_spp_opacity:new o.a3(L),u_spp_halo_width:new o.a3(L),u_spp_halo_blur:new o.a3(L),u_spp_emissive_strength:new o.a3(L),u_spp_occlusion_opacity:new o.a3(L),u_spp_z_offset:new o.a3(L),u_spp_translate_rotation:new o.a2(L),u_spp_zoom_fraction:new o.a3(L),u_opacity_multiplier:new o.a3(L)}),background:L=>({u_matrix:new o.a4(L),u_emissive_strength:new o.a3(L),u_opacity:new o.a3(L),u_color:new o.bY(L)}),backgroundPattern:L=>({u_matrix:new o.a4(L),u_emissive_strength:new o.a3(L),u_opacity:new o.a3(L),u_image:new o.aY(L),u_pattern_tl:new o.a2(L),u_pattern_br:new o.a2(L),u_texsize:new o.a2(L),u_pattern_size:new o.a2(L),u_pixel_coord_upper:new o.a2(L),u_pixel_coord_lower:new o.a2(L),u_pattern_units_to_pixels:new o.a2(L)}),skybox:L=>({u_matrix:new o.a4(L),u_sun_direction:new o.a5(L),u_cubemap:new o.aY(L),u_opacity:new o.a3(L),u_temporal_offset:new o.a3(L)}),skyboxGradient:L=>({u_matrix:new o.a4(L),u_color_ramp:new o.aY(L),u_center_direction:new o.a5(L),u_radius:new o.a3(L),u_opacity:new o.a3(L),u_temporal_offset:new o.a3(L)}),skyboxCapture:L=>({u_matrix_3f:new o.a_(L),u_sun_direction:new o.a5(L),u_sun_intensity:new o.a3(L),u_color_tint_r:new o.aZ(L),u_color_tint_m:new o.aZ(L),u_luminance:new o.a3(L)}),globeAtmosphere:L=>({u_frustum_tl:new o.a5(L),u_frustum_tr:new o.a5(L),u_frustum_br:new o.a5(L),u_frustum_bl:new o.a5(L),u_horizon:new o.a3(L),u_transition:new o.a3(L),u_fadeout_range:new o.a3(L),u_atmosphere_fog_color:new o.aZ(L),u_high_color:new o.aZ(L),u_space_color:new o.aZ(L),u_temporal_offset:new o.a3(L),u_horizon_angle:new o.a3(L)}),stars:L=>({u_matrix:new o.a4(L),u_up:new o.a5(L),u_right:new o.a5(L),u_intensity_multiplier:new o.a3(L)}),occlusion:L=>({u_matrix:new o.a4(L),u_anchorPos:new o.a5(L),u_screenSizePx:new o.a2(L),u_occluderSizePx:new o.a2(L),u_color:new o.aZ(L)})};var Js={terrainRaster:o.bc(`#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 vec3 unlit_base;vec3 emissive_base; #ifdef USE_MRT1_RGBA vec4 emissive_premult=u_emissive_texture_available > 0.5 ? texture(u_image1,v_pos0) : vec4(0.0);unlit_base=image_color.rgb-emissive_premult.rgb;emissive_base=emissive_premult.rgb; #else float emissive_strength=u_emissive_texture_available > 0.5 ? texture(u_image1,v_pos0).r : image_color.a;unlit_base=image_color.rgb*(1.0-emissive_strength);emissive_base=image_color.rgb*emissive_strength; #endif 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; #ifdef LIGHTING_3D_ALPHA_EMISSIVENESS #ifdef USE_MRT1_RGBA vec4 emissive_premult=u_emissive_texture_available > 0.5 ? texture(u_image1,v_pos0) : vec4(0.0);vec3 unlit_base=image_color.rgb-emissive_premult.rgb;color.rgb=apply_lighting(unlit_base,normal,lighting_factor)+emissive_premult.rgb;color.a=1.0; #else color=apply_lighting(image_color,normal,lighting_factor);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 #else color=apply_lighting(image_color,normal,lighting_factor); #endif #endif #else color=image_color; #endif #ifdef FOG color=fog_dither(fog_apply_from_vert(color,v_fog_opacity)); #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 v_fog_opacity=fog(fog_position(vec3(decodedPos,elevation))); #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:o.bc("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;}`),globeRaster:o.bc(`#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;FLIP_VIEWPORT_UV_Y(uv);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 #ifdef USE_MRT1_RGBA vec4 emissive_premult=u_emissive_texture_available > 0.5 ? texture(u_image1,v_pos0) : vec4(0.0);vec3 unlit_base=raster.rgb-emissive_premult.rgb;raster.rgb=apply_lighting_ground(vec4(unlit_base,1.0)).rgb+emissive_premult.rgb;color=vec4(clamp(raster.rgb,vec3(0),vec3(1))*antialias,antialias); #else 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); #endif #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 #ifdef USE_MRT1_RGBA vec4 emissive_premult=u_emissive_texture_available > 0.5 ? texture(u_image1,v_pos0) : vec4(0.0);vec3 unlit_base=color.rgb-emissive_premult.rgb;color.rgb=apply_lighting_ground(vec4(unlit_base,1.0)).rgb+emissive_premult.rgb;color.a=1.0; #else 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; #endif #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; #ifndef GLOBE_POLES uniform mat4 u_merc_matrix; #endif uniform float u_zoom_transition;uniform vec2 u_merc_center; #ifndef GLOBE_POLES uniform mat3 u_grid_matrix; #endif 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 }`)};(function(L){Q2=L;for(const k of V_.splice(0))k()})({create:(L,k)=>new OC(L,k)}),Object.assign(Cr,{terrainRaster:L=>({u_matrix:new o.a4(L),u_image0:new o.aY(L),u_image1:new o.aY(L),u_skirt_height:new o.a3(L),u_ground_shadow_factor:new o.a5(L),u_emissive_texture_available:new o.a3(L)}),globeRaster:L=>({u_proj_matrix:new o.a4(L),u_globe_matrix:new o.a4(L),u_normalize_matrix:new o.a4(L),u_merc_matrix:new o.a4(L),u_zoom_transition:new o.a3(L),u_merc_center:new o.a2(L),u_image0:new o.aY(L),u_image1:new o.aY(L),u_grid_matrix:new o.a_(L),u_skirt_height:new o.a3(L),u_far_z_cutoff:new o.a3(L),u_frustum_tl:new o.a5(L),u_frustum_tr:new o.a5(L),u_frustum_br:new o.a5(L),u_frustum_bl:new o.a5(L),u_globe_pos:new o.a5(L),u_globe_radius:new o.a3(L),u_viewport:new o.a2(L),u_emissive_texture_available:new o.a3(L)})});const lr={shaders:Js};class _r{constructor(k,T,B){this.screenBounds=k,this.cameraPoint=B.getCameraPoint(),this._screenRaycastCache={},this._cameraRaycastCache={},this.isAboveHorizon=T,this.screenGeometry=this.bufferedScreenGeometry(0),this.screenGeometryMercator=this._bufferedScreenMercator(0,B)}static createFromScreenPoints(k,T){let B,K;if(k instanceof o.P||typeof k[0]=="number"){const Q=o.P.convert(k);B=[Q],K=T.isPointAboveHorizon(Q)}else{const Q=o.P.convert(k[0]),le=o.P.convert(k[1]),me=Q.add(le)._div(2);B=[Q,le],K=o.cq(Q,le).every(we=>T.isPointAboveHorizon(we))&&T.isPointAboveHorizon(me)}return new _r(B,K,T)}isPointQuery(){return this.screenBounds.length===1}bufferedScreenGeometry(k){return o.cq(this.screenBounds[0],this.screenBounds.length===1?this.screenBounds[0]:this.screenBounds[1],k)}bufferedCameraGeometry(k){const T=this.screenBounds[0],B=this.screenBounds.length===1?this.screenBounds[0].add(new o.P(1,1)):this.screenBounds[1],K=o.cq(T,B,0,!1);return this.cameraPoint.y>B.y&&(this.cameraPoint.x>T.x&&this.cameraPoint.x=B.x?K[2]=this.cameraPoint:this.cameraPoint.x<=T.x&&(K[3]=this.cameraPoint)),o.cr(K,k)}bufferedCameraGeometryGlobe(k){const T=this.screenBounds[0],B=this.screenBounds.length===1?this.screenBounds[0].add(new o.P(1,1)):this.screenBounds[1],K=o.cq(T,B,k),Q=this.cameraPoint.clone(),le=+(Q.x>T.x)+ +(Q.x>B.x);switch(3*(+(Q.y>T.y)+ +(Q.y>B.y))+le){case 0:K[0]=Q,K[4]=Q.clone();break;case 1:K.splice(1,0,Q);break;case 2:K[1]=Q;break;case 3:K.splice(4,0,Q);break;case 5:K.splice(2,0,Q);break;case 6:K[3]=Q;break;case 7:K.splice(3,0,Q);break;case 8:K[2]=Q}return K}containsTile(k,T,B,K=0,Q){const le=Math.max(k.queryPadding,k.evaluateQueryRenderedFeaturePadding())/T._pixelsPerMercatorPixel+1,me=B?this._bufferedCameraMercator(le,T):this._bufferedScreenMercator(le,T);let we=k.tileID.wrap+(me.unwrapped?K:0);const Me=me.polygon.map(Mt=>o.cs(k.tileTransform,Mt,we));if(!o.ct(Me,0,0,o.a6,o.a6))return;we=k.tileID.wrap+(this.screenGeometryMercator.unwrapped?K:0);const Re=this.screenGeometryMercator.polygon.map(Mt=>o.cu(k.tileTransform,Mt,we)),Ze=Re.map(Mt=>new o.P(Mt[0],Mt[1])),Qe=o.cu(k.tileTransform,Q,we),ht=Re.map(Mt=>{const es=o.cv(Mt,Mt,Qe);return o.c9(es,es),new o.cw(Qe,es)}),_t=o.cd(k,1,T.zoom)*T._pixelsPerMercatorPixel;return{queryGeometry:this,tilespaceGeometry:Ze,tilespaceRays:ht,bufferedTilespaceGeometry:Me,bufferedTilespaceBounds:(bt=o.cx(Me),bt.min.x=o.b1(bt.min.x,0,o.a6),bt.min.y=o.b1(bt.min.y,0,o.a6),bt.max.x=o.b1(bt.max.x,0,o.a6),bt.max.y=o.b1(bt.max.y,0,o.a6),bt),tile:k,tileID:k.tileID,pixelToTileUnitsFactor:_t};var bt}_bufferedScreenMercator(k,T){const B=pa(k);if(this._screenRaycastCache[B])return this._screenRaycastCache[B];{let K;return K=T.projection.name==="globe"?this._projectAndResample(this.bufferedScreenGeometry(k),T):{polygon:this.bufferedScreenGeometry(k).map(Q=>T.pointCoordinate3D(Q)),unwrapped:!0},this._screenRaycastCache[B]=K,K}}_bufferedCameraMercator(k,T){const B=pa(k);if(this._cameraRaycastCache[B])return this._cameraRaycastCache[B];{let K;return K=T.projection.name==="globe"?this._projectAndResample(this.bufferedCameraGeometryGlobe(k),T):{polygon:this.bufferedCameraGeometry(k).map(Q=>T.pointCoordinate3D(Q)),unwrapped:!0},this._cameraRaycastCache[B]=K,K}}_projectAndResample(k,T){const B=function(Q,le){const me=o.X([],le.pixelMatrix,le.globeMatrix),we=[0,-o.cy,0,1],Me=[0,o.cy,0,1],Re=[0,0,0,1];o.c6(we,we,me),o.c6(Me,Me,me),o.c6(Re,Re,me);const Ze=new o.P(we[0]/we[3],we[1]/we[3]),Qe=new o.P(Me[0]/Me[3],Me[1]/Me[3]),ht=o.cz(Q,Ze)&&we[3]1?aa(Q.slice(0,Mt),le):[],Lt=Mtnew o.P(mr($s.x),$s.y)),Lt=Lt.map($s=>new o.P(mr($s.x),$s.y));const ps=[...Qt];ps.length===0&&ps.push(Lt.at(-1));const Hs=ps.at(-1),Fs=o.am(Hs.y,(Lt.length===0?Qt[0]:Lt[0]).y,es);let nn;return nn=ht?[new o.P(0,Fs),new o.P(0,0),new o.P(1,0),new o.P(1,Fs)]:[new o.P(1,Fs),new o.P(1,1),new o.P(0,1),new o.P(0,Fs)],ps.push(...nn),Lt.length===0?ps.push(Qt[0]):ps.push(...Lt),{polygon:ps.map($s=>new o.bT($s.x,$s.y)),unwrapped:!1}}(k,T);if(B)return B;const K=function(Q,le){let me=!1,we=-1/0,Me=0;for(let Ze=0;Zewe&&(we=Q[Ze].x,Me=Ze);for(let Ze=0;Ze.5&&(ht.x<_t.x?(ht.x+=1,Qe===0&&(Q.at(-1).x+=1)):(_t.x+=1,Qe+1===Q.length-1&&(Q[0].x+=1)),me=!0)}const Re=o.a7(le.center.lng);return me&&Re{Ze.x-=1}),{polygon:Q,unwrapped:me}}(aa(k,T).map(Q=>new o.P(mr(Q.x),Q.y)),T);return{polygon:K.polygon.map(Q=>new o.bT(Q.x,Q.y)),unwrapped:K.unwrapped}}}function aa(L,k){return o.cA(L,T=>{const B=k.pointCoordinate3D(T);T.x=B.x,T.y=B.y},1/256)}function mr(L){return L<0?1+L%1:L%1}function pa(L){return 100*L|0}class dr extends o.E{constructor(k,T,B,K){super(),this.id=k,this.dispatcher=B,this.setEventedParent(K),this.type="raster",this.minzoom=0,this.maxzoom=22,this.roundZoom=!0,this.scheme="xyz",this.tileSize=512,this._loaded=!1,this._options={type:"raster",...T},Object.assign(this,o.cB(T,["url","scheme","tileSize"]))}load(k){this._loaded=!1,this.fire(new o.h("dataloading",{dataType:"source"}));const T=this.map.getWorldview(),B=(Q,le)=>{this._tileJSONRequest=null,this._loaded=!0,Q?this.fire(new o.f(Q)):le&&(Object.assign(this,le),le.raster_layers&&(this.rasterLayers=le.raster_layers,this.rasterLayerIds=this.rasterLayers.map(me=>me.id)),this.tileBounds=o.cF.fromTileJSON(le),o.cK(le.tiles),this.fire(new o.h("data",{dataType:"source",sourceDataType:"metadata"})),this.fire(new o.h("data",{dataType:"source",sourceDataType:"content"}))),k&&k(Q)};this.provider=typeof this._options.provider=="string"?this._options.provider:void 0,this._tileProvider=void 0;const K=o.cD(this._options);return K instanceof Error?(this._loaded=!0,this.fire(new o.f(K)),void(k&&k())):this.provider&&!K?(this._loaded=!0,this.fire(new o.f(new Error(`TileProvider "${this.provider}" is not registered`))),void(k&&k())):void(this._tileJSONRequest=K?this.loadTileJSONWithProvider(K,B):o.cE(this._options,this.map._requestManager,null,T,B))}loadTileJSONWithProvider(k,T){this.provider=k.name;const B=new AbortController;return(async()=>{const{request:K,options:Q}=await o.cL(this._options,this.map._requestManager,B.signal);if(B.signal.aborted)return;const le=await o.cN(k.name,k.url);if(B.signal.aborted)return;const me=new le(Q);let we=null;if(me.load&&K&&(we=await me.load({request:K}),B.signal.aborted))return;this._tileProvider=me;const Me=o.cM(this._options,we,this.map._requestManager);Me instanceof Error?T(Me):T(null,Me)})().catch(K=>{B.signal.aborted||T(new Error(`Could not load tile provider ${k.name}`,{cause:K}))}),{cancel:()=>B.abort()}}loaded(){return this._loaded}onAdd(k){this.map=k,this.load()}reload(){this.cancelTileJSONRequest();const k=o.m(this.id,this.scope);this.load(()=>this.map.style.clearSource(k))}setTiles(k){return this._options.tiles=k,this.reload(),this}setUrl(k){return this.url=k,this._options.url=k,this.reload(),this}onRemove(k){this.cancelTileJSONRequest()}serialize(){return{...this._options}}hasTile(k){return!this.tileBounds||this.tileBounds.contains(k.canonical)}async loadTile(k,T){const B=o.e.devicePixelRatio>=2,K=this.map._requestManager.normalizeTileURL(k.tileID.canonical.url(this.tiles,this.scheme),B,this.tileSize),Q=new AbortController;if(k.request=Q,this._tileProvider)this.loadTileWithProvider(k,this._tileProvider,K,Q,T);else try{const le=await this.map._requestManager.transformRequest(K,o.R.Tile,Q.signal);if(Q.signal.aborted)return delete k.request,T(null);const{data:me,headers:we}=await o.a(le,Q.signal);if(delete k.request,k.aborted)return T(null);const Me=o.cI(we);this.map._refreshExpiredTiles&&k.setExpiryData(Me),k.setTexture(me,this.map.painter),k.state="loaded",o.cJ(this.dispatcher),T(null)}catch(le){if(delete k.request,Q.signal.aborted)return T(null);k.state="errored",T(le)}}async loadTileWithProvider(k,T,B,K,Q){const{z:le,x:me,y:we}=k.tileID.canonical;try{const Me=await this.map._requestManager.transformRequest(B,o.R.Tile,K.signal);if(K.signal.aborted)return Q(null);const Re=await T.loadTile({z:le,x:me,y:we},{request:Me,signal:K.signal});if(K.signal.aborted)return Q(null);if(Re==null){const Qe=new Error("Tile not found");return Qe.status=404,k.state="errored",Q(Qe)}if(Re.data==null)return k.state="loaded",Q(null);const Ze=Re.data instanceof ImageBitmap?Re.data:await createImageBitmap(new Blob([Re.data]));if(K.signal.aborted)return Q(null);k.setTexture(Ze,this.map.painter),k.state="loaded",this.map._refreshExpiredTiles&&k.setExpiryData({cacheControl:Re.cacheControl,expires:Re.expires}),Q(null)}catch(Me){if(K.signal.aborted)return Q(null);k.state="errored",Q(new Error(`Could not load tile from ${B}`,{cause:Me}))}finally{delete k.request}}abortTile(k,T){k.request&&(k.request.abort(),delete k.request),T&&T()}unloadTile(k,T){k.texture&&k.texture instanceof o.T?(k.destroy(!1),k.texture&&k.texture instanceof o.T&&this.map.painter.saveTileTexture(k.texture)):k.destroy(),T&&T()}hasTransition(){return!1}cancelTileJSONRequest(){this._tileJSONRequest&&(this._tileJSONRequest.cancel(),this._tileJSONRequest=null)}}function Ua(L,k,T,B,K,Q,le,me){const we=[L,k,1,T,B,1,K,Q,1],Me=[le,me,1],Re=o.cU([],we),[Ze,Qe,ht]=o.cT(Me,Me,Re);return o.cV(we,we,[Ze,0,0,0,Qe,0,0,0,ht])}function Ea(L,k,T,B,K,Q,le,me){const we=function(Me,Re,Ze,Qe,ht,_t,bt,Mt){const es=Ua(0,0,1,0,1,1,0,1),Qt=Ua(Me,Re,Ze,Qe,ht,_t,bt,Mt),Lt=o.cU([],es);return o.cV(Qt,Qt,Lt)}(L,k,T,B,K,Q,le,me);return[we[2]/we[8]/o.a6,we[5]/we[8]/o.a6]}function _o(L){return[L[0],Math.min(Math.max(L[1],-o.cP),o.cP)]}class Fi extends o.E{constructor(k,T,B,K){super(),this.id=k,this.dispatcher=B,this.coordinates=T.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(K),this.options=T,this._dirty=!1}async load(k,T){if(this._loaded=T||!1,this.fire(new o.h("dataloading",{dataType:"source"})),this.url=this.options.url,!this.url)return k&&(this.coordinates=k),this._loaded=!0,void this._finishLoading();const B=new AbortController;this._imageRequest=B;try{const K=await this.map._requestManager.transformRequest(this.url,o.R.Image,B.signal),{data:Q}=await o.a(K,B.signal);this._imageRequest=null,this._loaded=!0,this.image=Q,this._dirty=!0,this.width=this.image.width,this.height=this.image.height,k&&(this.coordinates=k),this._finishLoading()}catch(K){if(B.signal.aborted)return;this._imageRequest=null,this._loaded=!0,this.fire(new o.f(K))}}loaded(){return this._loaded}updateImage(k){return k.url?(this._imageRequest&&k.url!==this.options.url&&(this._imageRequest.abort(),this._imageRequest=null),this.options.url=k.url,this.load(k.coordinates,this._loaded),this):this}setTexture(k){if(!(k.handle instanceof WebGLTexture))throw new Error("The provided handle is not a WebGLTexture instance");return this.texture=new o.cO(this.map.painter.context,k.handle),this.width=k.dimensions[0],this.height=k.dimensions[1],this._dirty=!1,this._loaded=!0,this._finishLoading(),this}_finishLoading(){this.map&&(this.setCoordinates(this.coordinates),this.fire(new o.h("data",{dataType:"source",sourceDataType:"metadata"})))}onAdd(k){this.map=k,this.load()}onRemove(k){this._imageRequest&&(this._imageRequest.abort(),this._imageRequest=null),!this.texture||this.texture instanceof o.cO||this.texture.destroy(),this.boundsBuffer&&(this.boundsBuffer.destroy(),this.elevatedGlobeVertexBuffer&&this.elevatedGlobeVertexBuffer.destroy(),this.elevatedGlobeIndexBuffer&&this.elevatedGlobeIndexBuffer.destroy())}setCoordinates(k){if(this.coordinates=k,this._boundsArray=void 0,this._unsupportedCoords=!1,!k.length)return this;this.onNorthPole=!1,this.onSouthPole=!1;let T=k[0][1],B=k[0][1];for(const Q of k)Q[1]>B&&(B=Q[1]),Q[1]o.cP?this.onNorthPole=!0:K<-o.cP&&(this.onSouthPole=!0),!this.onNorthPole&&!this.onSouthPole){const Q=k.map(o.bT.fromLngLat);this.tileID=function(le){let me=1/0,we=1/0,Me=-1/0,Re=-1/0;for(const bt of le)me=Math.min(me,bt.x),we=Math.min(we,bt.y),Me=Math.max(Me,bt.x),Re=Math.max(Re,bt.y);const Ze=Math.max(Me-me,Re-we),Qe=Math.max(0,Math.floor(-Math.log2(Ze))),ht=Math.pow(2,Qe);let _t=Math.floor((me+Me)/2*ht);return _t>1&&(_t-=1),new o.bW(Qe,_t,Math.floor((we+Re)/2*ht))}(Q),this.minzoom=this.maxzoom=this.tileID.z}return this.fire(new o.h("data",{dataType:"source",sourceDataType:"content"})),this}_clear(){!this.texture||this.texture instanceof o.cO||(this.texture.destroy(),this._dirty=!0),this.texture=null,this._boundsArray=void 0,this._unsupportedCoords=!1}_prepareData(k){for(const Hs in this.tiles){const Fs=this.tiles[Hs];Fs.state!=="loaded"&&(Fs.state="loaded",Fs.texture=this.texture)}if(this._boundsArray||this.onNorthPole||this.onSouthPole||this._unsupportedCoords)return;const T=o.bq(new o.bW(0,0,0),this.map.transform.projection),B=[T.projection.project(this.coordinates[0][0],this.coordinates[0][1]),T.projection.project(this.coordinates[1][0],this.coordinates[1][1]),T.projection.project(this.coordinates[2][0],this.coordinates[2][1]),T.projection.project(this.coordinates[3][0],this.coordinates[3][1])];if(!function(Hs){const Fs=Hs[1].x-Hs[0].x,nn=Hs[1].y-Hs[0].y,$s=Hs[2].x-Hs[1].x,rn=Hs[2].y-Hs[1].y,_n=Hs[3].x-Hs[2].x,Mn=Hs[3].y-Hs[2].y,Yn=Hs[0].x-Hs[3].x,$n=Hs[0].y-Hs[3].y,zn=Fs*rn-$s*nn,Dr=$s*Mn-_n*rn,An=_n*$n-Yn*Mn,yr=Yn*nn-Fs*$n;return zn>0&&Dr>0&&An>0&&yr>0||zn<0&&Dr<0&&An<0&&yr<0}(B))return console.warn("Image source coordinates are defining non-convex area in the Mercator projection"),void(this._unsupportedCoords=!0);const K=o.bq(this.tileID,this.map.transform.projection),[Q,le,me,we]=this.coordinates.map(Hs=>{const Fs=K.projection.project(Hs[0],Hs[1]);return o.cs(K,Fs)._round()});this.perspectiveTransform=Ea(Q.x,Q.y,le.x,le.y,me.x,me.y,we.x,we.y);const Me=this._boundsArray=new o.bt;Me.emplaceBack(Q.x,Q.y,0,0),Me.emplaceBack(le.x,le.y,o.a6,0),Me.emplaceBack(we.x,we.y,0,o.a6),Me.emplaceBack(me.x,me.y,o.a6,o.a6),this.boundsBuffer&&(this.boundsBuffer.destroy(),this.elevatedGlobeVertexBuffer&&this.elevatedGlobeVertexBuffer.destroy(),this.elevatedGlobeIndexBuffer&&this.elevatedGlobeIndexBuffer.destroy()),this.boundsBuffer=k.createVertexBuffer(Me,Jc.members),this.boundsSegments=o.ad.simpleSegment(0,0,4,2);const Re=o.cS,Ze=Re+1,Qe=Re+1,ht=Ze*Qe,_t=Re*Re*2,bt=[],Mt=function(Hs){return[_o(Hs[0]),_o(Hs[1]),_o(Hs[2]),_o(Hs[3])]}(this.coordinates),[es,Qt,Lt,ps]=function(Hs){let Fs=Hs[0][0],nn=Fs,$s=Hs[0][1],rn=$s;for(let _n=1;_nnn&&(nn=Hs[_n][0]),Hs[_n][1]<$s?$s=Hs[_n][1]:Hs[_n][1]>rn&&(rn=Hs[_n][1]);return[Fs,$s,nn-Fs,rn-$s]}(Mt);{const Hs=new o.bt,[Fs,nn,$s,rn]=function(ea){let si=ea[0].x,Wr=si,Mr=ea[0].y,Gr=Mr;for(let Ga=1;GaWr&&(Wr=ea[Ga].x),ea[Ga].yGr&&(Gr=ea[Ga].y);return[si,Mr,Wr-si,Gr-Mr]}(B),_n=ea=>[(ea.x-Fs)/$s,(ea.y-nn)/rn],[Mn,Yn,$n,zn]=B.map(_n),Dr=function(ea,si,Wr,Mr,Gr,Ga,Vr,Za){const Oi=Ua(0,0,1,0,1,1,0,1),Do=Ua(ea,si,Wr,Mr,Gr,Ga,Vr,Za),so=o.cU([],Do);return o.cV(Oi,Oi,so)}(Mn[0],Mn[1],Yn[0],Yn[1],$n[0],$n[1],zn[0],zn[1]);this.elevatedGlobePerspectiveTransform=Ea(Mn[0],Mn[1],Yn[0],Yn[1],$n[0],$n[1],zn[0],zn[1]);const An=(ea,si)=>{bt.push(ea.lng);const Wr=Math.round((ea.lng-es)/Lt*o.a6),Mr=Math.round((ea.lat-Qt)/ps*o.a6),Gr=_n(si),Ga=o.cT([],[Gr[0],Gr[1],1],Dr),Vr=Math.round(Ga[0]/Ga[2]*o.a6),Za=Math.round(Ga[1]/Ga[2]*o.a6);Hs.emplaceBack(Wr,Mr,Vr,Za)},yr=B[3].x-B[0].x,sa=B[3].y-B[0].y,ka=B[2].x-B[1].x,Hr=B[2].y-B[1].y;for(let ea=0;ea{Fs.emplaceBack($s,rn,_n);const Mn=bt[$s],Yn=bt[rn],$n=bt[_n],zn=Math.min(Math.min(Mn,Yn),$n),Dr=Math.max(Math.max(Mn,Yn),$n)-zn;Dr>this.maxLongitudeTriangleSize&&(this.maxLongitudeTriangleSize=Dr),Hs.push(zn+Dr/2)};for(let $s=0;$szn);_n.sort(($n,zn)=>$s[$n]-$s[zn]);const Mn=[],Yn=new o.ae;for(let $n=0;$n<_n.length;$n++){const zn=_n[$n];Mn.push($s[zn]);const Dr=3*zn,An=Dr+1;Yn.emplaceBack(rn.uint16[Dr],rn.uint16[An],rn.uint16[An+1])}return[Mn,Yn]}(Hs,Fs),this.elevatedGlobeTrianglesCenterLongitudes=Hs,this.elevatedGlobeIndexBuffer=k.createIndexBuffer(Fs)}this.elevatedGlobeSegments=o.ad.simpleSegment(0,0,ht,_t),this.elevatedGlobeGridMatrix=new Float32Array([0,Lt/o.a6,0,ps/o.a6,0,0,Qt,es,0])}prepare(){const k=Object.keys(this.tiles).length!==0;if(this.tileID&&!k)return;const T=this.map.painter.context,B=T.gl;!this._dirty||this.texture instanceof o.cO||(this.texture?this.texture.update(this.image):(this.texture=new o.T(T,this.image,B.RGBA8),this.texture.bind(B.LINEAR,B.CLAMP_TO_EDGE)),this._dirty=!1),k&&this._prepareData(T)}loadTile(k,T){this.tileID&&this.tileID.equals(k.tileID.canonical)?(this.tiles[String(k.tileID.wrap)]=k,k.buckets={},T(null)):(k.state="errored",T(null))}serialize(){return{type:"image",url:this.options.url,coordinates:this.coordinates}}hasTransition(){return!1}getSegmentsForLongitude(k){const T=this.elevatedGlobeSegments;if(!this.elevatedGlobeTrianglesCenterLongitudes||!T)return null;const B=this.elevatedGlobeTrianglesCenterLongitudes;let K=(Q=k+180)+360*Math.round((B[0]-Q)/360);var Q;const le=new o.ad,me=(Ze,Qe)=>{le.segments.push({vertexOffset:0,primitiveOffset:Ze,vertexLength:T.segments[0].vertexLength,primitiveLength:Qe,sortKey:void 0,vaos:{}})},we=.51*this.maxLongitudeTriangleSize;if(Math.abs(B[0]-K)<=we){const Ze=o.cQ(B,0,B.length,K+we);return Ze===B.length||me(Ze,o.cR(B,Ze+1,B.length,K+360-we)-Ze),le}K{this._tileJSONRequest=null,this._loaded=!0,Q?(k&&console.warn(`Ensure that your requested language string is a valid BCP-47 code or list of codes. Found: ${k}`),T&&console.warn(`Requested worldview strings must be a valid ISO alpha-2 code. Found: ${T}`),this.fire(new o.f(Q))):le&&(this._setTileJSON(le),Ui.updateCrossSourceElevationGate&&this.map.style&&Ui.updateCrossSourceElevationGate(this.map.style),o.cK(le.tiles,this.map._requestManager._customAccessToken),this.fire(new o.h("data",{dataType:"source",sourceDataType:"metadata"})),this.fire(new o.h("data",{dataType:"source",sourceDataType:"content"}))),L&&L(Q)};this.provider=this._options.provider;const K=o.cD(this._options);return K instanceof Error?(this._loaded=!0,this.fire(new o.f(K)),void(L&&L())):this.provider&&!K?(this._loaded=!0,this.fire(new o.f(new Error(`TileProvider "${this.provider}" is not registered`))),void(L&&L())):void(this._tileJSONRequest=K?this.loadTileJSONWithProvider(K,B):o.cE(this._options,this.map._requestManager,k,T,B))}loadTileJSONWithProvider(L,k){this.provider=L.name;const T=new AbortController;return(async()=>{const{request:B,options:K}=await o.cL(this._options,this.map._requestManager,T.signal);if(T.signal.aborted)return;const Q=await this.dispatcher.send("loadTileProvider",{name:L.name,url:L.url,source:this.id,scope:this.scope,type:this.type,options:K,request:B},{signal:T.signal});if(T.signal.aborted)return;const le=Q?Q.find(we=>we!=null):null,me=o.cM(this._options,le,this.map._requestManager);me instanceof Error?k(me):k(null,me)})().catch(B=>{T.signal.aborted||k(B)}),{cancel:()=>T.abort()}}_setTileJSON(L){if(Object.assign(this,L),this.hasWorldviews=!!L.worldview_options,L.worldview_default&&(this.worldviewDefault=L.worldview_default),L.vector_layers){this.vectorLayers=L.vector_layers,this.vectorLayerIds=[],this.localizableLayerIds=new Set;for(const k of L.vector_layers)this.vectorLayerIds.push(k.id),L.worldview&&L.worldview[k.source]&&this.localizableLayerIds.add(k.id)}this.tileBounds=o.cF.fromTileJSON(L)}loaded(){return this._loaded}hasTile(L){return!this.tileBounds||this.tileBounds.contains(L.canonical)}onAdd(L){this.map=L,this.load()}reload(){this.cancelTileJSONRequest();const L=o.m(this.id,this.scope);this.load(()=>this.map.style.clearSource(L))}setTiles(L){return this._options.tiles=L,this.reload(),this}setUrl(L){return this.url=L,this._options.url=L,this.reload(),this}onRemove(L){this.cancelTileJSONRequest()}serialize(){return{...this._options}}async loadTile(L,k){const T=L.tileID.canonical.url(this.tiles,this.scheme),B=this.map._requestManager.normalizeTileURL(T),K=!L.actor||L.state==="expired";if(!K&&L.state==="loading")return void(L.reloadCallback=k);K&&(L.actor=this._tileWorkers[B]=this._tileWorkers[B]||this.dispatcher.getActor());const Q=new AbortController;L.request=Q;try{const le=await this.map._requestManager.transformRequest(B,o.R.Tile,Q.signal);if(Q.signal.aborted)return k(null);this.dispatchTile(L,B,T,le,Q,K,k)}catch(le){if(Q.signal.aborted)return k(null);k(le)}}dispatchTile(L,k,T,B,K,Q,le){const me=this.map.style?this.map.style.getLut(this.scope):null,we=me?{image:me.image.clone()}:null,Me=!(!this.map.style||!this.map.style._crossSourceElevationActive),Re=!(!this.map.style||!Me),Ze={request:B,data:void 0,uid:L.uid,tileID:L.tileID,tileZoom:L.tileZoom,zoom:L.tileID.overscaledZ,maxZoom:this.maxzoom,lut:we,tileSize:this.tileSize*L.tileID.overscaleFactor(),type:this.type,source:this.id,scope:this.scope,pixelRatio:o.e.devicePixelRatio,showCollisionBoxes:this.map.showCollisionBoxes,showElevationIdDebug:!!this.map.painter&&this.map.painter._debugParams.showElevationIdDebug,promoteId:this.promoteId,renderSourceType:L.renderSourceType,frcCoverage:(()=>{const ht=this.map.painter,_t=ht?ht.frcCoverageFadeRange:null;if(_t==null)return null;const bt=ht?ht.frcCoverageSnapshot:null,Mt=this.map.transform.zoom<_t[0],es=bt?bt.getTileOrParent(L.tileID.canonical):null,Qt=L.tileID.overscaledZ>=Math.ceil(_t[1]),Lt=bt&&Qt?bt.getFullCoverageMask(L.tileID.canonical):null;return{frcMask:Qt?Lt??null:null,resolved:Mt||bt!=null,polygons:es&&es.frcMask!==0?es.polygons:null,tileZoom:es&&es.frcMask!==0?es.tileId.z:null,sourceLayers:ht?ht.frcCoverageSourceLayers:["road","structure"]}})(),terrainEnabled:oh(this.map.style,this.map.transform),crossSourceElevationEnabled:Re,elevation:Ui.buildElevationRequestParams?Ui.buildElevationRequestParams(this.map,L,Me):null,brightness:this.map.style&&this.map.style.getBrightness()||0,extraShadowCaster:L.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.cG(T)&&(Ze.localizableLayerIds=this.localizableLayerIds),Ze.request.collectResourceTiming=this._collectResourceTiming,Q)if(this.dispatcher.ready||this.provider)L.request=L.actor.sendCancelable("loadTile",Ze,{},Qe.bind(this));else{const ht=o.cH.call({deduped:this._deduped},Ze,(_t,bt)=>{L.aborted||(_t||!bt?Qe.call(this,_t):(Ze.data={rawData:bt.rawData.slice(0),headers:bt.headers},L.actor&&(L.request=L.actor.sendCancelable("loadTile",Ze,{},Qe.bind(this)))))},!0);K.signal.addEventListener("abort",ht,{once:!0})}else L.request=L.actor.sendCancelable("reloadTile",Ze,{},Qe.bind(this));function Qe(ht,_t){return delete L.request,L.aborted?le(null):ht?le(ht):(_t&&_t.resourceTiming&&(L.resourceTiming=_t.resourceTiming),this.map._refreshExpiredTiles&&_t&&L.setExpiryData(o.cI(_t.headers)),void(function(){if(L.aborted)return le(null);L.loadVectorData(_t,this.map.painter),o.cJ(this.dispatcher),le(null,_t),L.reloadCallback&&(this.loadTile(L,L.reloadCallback),L.reloadCallback=null)}).call(this))}}abortTile(L){L.request&&(L.request.abort(),delete L.request),L.actor&&L.actor.notify("abortTile",{uid:L.uid,type:this.type,source:this.id,scope:this.scope})}unloadTile(L,k){L.actor&&L.actor.notify("removeTile",{uid:L.uid,type:this.type,source:this.id,scope:this.scope}),L.destroy()}hasTransition(){return!1}afterUpdate(){this._tileWorkers={}}cancelTileJSONRequest(){this._tileJSONRequest&&(this._tileJSONRequest.cancel(),this._tileJSONRequest=null)}},raster:dr,"raster-dem":class extends dr{constructor(L,k,T,B){super(L,k,T,B),this.type="raster-dem",this.maxzoom=22,this._options={type:"raster-dem",...k},this.encoding=k.encoding||"mapbox"}loadTileJSONWithProvider(L,k){this.provider=L.name;const T=new AbortController;return(async()=>{const{request:B,options:K}=await o.cL(this._options,this.map._requestManager,T.signal);if(T.signal.aborted)return;const Q=await this.dispatcher.send("loadTileProvider",{name:L.name,url:L.url,source:this.id,scope:this.scope,type:this.type,options:K,request:B},{signal:T.signal});if(T.signal.aborted)return;const le=Q?Q.find(we=>we!=null):null,me=o.cM(this._options,le,this.map._requestManager);me instanceof Error?k(me):k(null,me)})().catch(B=>{T.signal.aborted||k(B)}),{cancel:()=>T.abort()}}async loadTile(L,k){if(L.actor&&L.state!=="expired")return;const T=this.map._requestManager.normalizeTileURL(L.tileID.canonical.url(this.tiles,this.scheme),!1,this.tileSize);L.actor=this.dispatcher.getActor();const B=new AbortController;L.request=B;try{const K=await this.map._requestManager.transformRequest(T,o.R.Tile,B.signal);if(B.signal.aborted)return k(null);L.request=L.actor.sendCancelable("loadTile",{uid:L.uid,tileID:L.tileID,source:this.id,type:this.type,scope:this.scope,request:K,encoding:this.encoding},{},(function(Q,le){return delete L.request,L.aborted?k(null):Q?(L.state="errored",k(Q)):(le&&(this.map._refreshExpiredTiles&&L.setExpiryData(o.cI(le.headers)),le.borderReady||L.neighboringTiles||(L.neighboringTiles=this._getNeighboringTiles(L.tileID)),L.dem=le.dem,L.dem.onDeserialize(),L.needsHillshadePrepare=!0,L.needsDEMTextureUpload=!0),L.state="loaded",void k(null))}).bind(this))}catch(K){if(B.signal.aborted)return k(null);L.state="errored",k(K)}}abortTile(L,k){L.request&&(L.request.abort(),delete L.request),L.actor&&L.actor.notify("abortTile",{uid:L.uid,type:this.type,source:this.id,scope:this.scope}),k&&k()}_getNeighboringTiles(L){const k=L.canonical,T=Math.pow(2,k.z),B=(k.x-1+T)%T,K=k.x===0?L.wrap-1:L.wrap,Q=(k.x+1+T)%T,le=k.x+1===T?L.wrap+1:L.wrap,me={};return me[new o.bQ(L.overscaledZ,K,k.z,B,k.y).key]={backfilled:!1},me[new o.bQ(L.overscaledZ,le,k.z,Q,k.y).key]={backfilled:!1},k.y>0&&(me[new o.bQ(L.overscaledZ,K,k.z,B,k.y-1).key]={backfilled:!1},me[new o.bQ(L.overscaledZ,L.wrap,k.z,k.x,k.y-1).key]={backfilled:!1},me[new o.bQ(L.overscaledZ,le,k.z,Q,k.y-1).key]={backfilled:!1}),k.y+1k(null,T)).catch(T=>k(T)),this}getClusterChildren(L,k){return this.actor.send("geojson.getClusterChildren",{clusterId:L,source:this.id,scope:this.scope}).then(T=>k(null,T)).catch(T=>k(T)),this}getClusterLeaves(L,k,T,B){return this.actor.send("geojson.getClusterLeaves",{source:this.id,scope:this.scope,clusterId:L,limit:k,offset:T}).then(K=>B(null,K)).catch(K=>B(K)),this}async _updateWorkerData(L=!1){if(this._pendingLoad)return void(this._coalesce=!0);this.fire(new o.h("dataloading",{dataType:"source"})),this._loaded=!1;const k={append:L,...this.workerOptions};k.scope=this.scope;const T=this._data,B=new AbortController;this._pendingLoad=B;try{if(typeof T=="string"){if(k.request=await this.map._requestManager.transformRequest(o.e.resolveURL(T),o.R.Source,B.signal),B.signal.aborted)return this._pendingLoad=null,void(this._coalesce=!1);k.request.collectResourceTiming=this._collectResourceTiming}else k.data=JSON.stringify(T);const K=await this.actor.send(`${this.type}.loadData`,k,{signal:B.signal});this._loaded=!0,this._pendingLoad=null;const Q={dataType:"source",sourceDataType:this._metadataFired?"content":"metadata"};this._collectResourceTiming&&K&&K.resourceTiming&&K.resourceTiming[this.id]&&(Q.resourceTiming=K.resourceTiming[this.id]),L&&(this._partialReload=!0),this.fire(new o.h("data",Q)),this._partialReload=!1,this._metadataFired=!0}catch(K){if(B.signal.aborted)return this._pendingLoad=null,void(this._coalesce=!1);this._loaded=!0,this._pendingLoad=null,this.fire(new o.f(K))}this._coalesce&&(this._updateWorkerData(L),this._coalesce=!1)}loaded(){return this._loaded}reload(){const L=o.m(this.id,this.scope);this.map.style.clearSource(L),this._updateWorkerData()}loadTile(L,k){const T=L.actor?"reloadTile":"loadTile";L.actor=this.actor;const B=this.map.style?this.map.style.getLut(this.scope):null,K=B?{image:B.image.clone()}:null,Q=this._partialReload,le={type:this.type,uid:L.uid,tileID:L.tileID,tileZoom:L.tileZoom,zoom:L.tileID.overscaledZ,maxZoom:this.maxzoom,tileSize:this.tileSize,source:this.id,lut:K,scope:this.scope,pixelRatio:o.e.devicePixelRatio,showCollisionBoxes:this.map.showCollisionBoxes,showElevationIdDebug:!!this.map.painter&&this.map.painter._debugParams.showElevationIdDebug,promoteId:this.promoteId,brightness:this.map.style&&this.map.style.getBrightness()||0,extraShadowCaster:L.isExtraShadowCaster,scaleFactor:this.map.getScaleFactor(),partial:Q,worldview:this.map.getWorldview(),indoor:this.map.getIndoorTileOptions(this.id,this.scope)};L.request=this.actor.sendCancelable(T,le,{},(me,we)=>Q&&!we?(L.state="loaded",k(null)):(delete L.request,L.destroy(!1),L.aborted?k(null):me?k(me):(L.loadVectorData(we,this.map.painter,T==="reloadTile"),void k(null))))}abortTile(L){L.request&&(L.request.abort(),delete L.request),L.aborted=!0}unloadTile(L,k){this.actor.notify("removeTile",{uid:L.uid,type:this.type,source:this.id,scope:this.scope}),L.destroy()}onRemove(L){this._pendingLoad&&this._pendingLoad.abort()}serialize(){return{...this._options,type:this.type,data:this._data}}hasTransition(){return!1}},video:class extends Fi{constructor(L,k,T,B){super(L,k,T,B),this.roundZoom=!0,this.type="video",this.options=k}async load(){this._loaded=!1;const L=this.options,k=new AbortController;this._imageRequest=k;try{const T=await Promise.all(L.urls.map(async K=>(await this.map._requestManager.transformRequest(K,o.R.Source,k.signal)).url));if(k.signal.aborted)return;this.urls=T;const B=await o.cW(T);if(k.signal.aborted)return;this._imageRequest=null,this.video=B,this.video.loop=!0,this.video.setAttribute("playsinline",""),this.video.addEventListener("playing",()=>{this.map.triggerRepaint()}),this.map&&this.video.play(),this._finishLoading()}catch(T){if(k.signal.aborted)return;this.fire(new o.f(T))}finally{this._loaded=!0}}pause(){this.video&&this.video.pause()}play(){this.video&&this.video.play()}seek(L){if(this.video){const k=this.video.seekable;Lk.end(0)?this.fire(new o.f(new rs(`sources.${this.id}`,null,`Playback for this video can be set only between the ${k.start(0)} and ${k.end(0)}-second mark.`))):this.video.currentTime=L}}getVideo(){return this.video}onAdd(L){this.map||(this.map=L,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 L=this.map.painter.context,k=L.gl;this.texture?this.video.paused||(this.texture.bind(k.LINEAR,k.CLAMP_TO_EDGE),k.texSubImage2D(k.TEXTURE_2D,0,0,0,k.RGBA,k.UNSIGNED_BYTE,this.video)):(this.texture=new o.T(L,this.video,k.RGBA8),this.texture.bind(k.LINEAR,k.CLAMP_TO_EDGE),this.width=this.video.videoWidth,this.height=this.video.videoHeight),this._prepareData(L)}serialize(){return{type:"video",urls:this.options.urls,coordinates:this.coordinates}}hasTransition(){return this.video&&!this.video.paused}},image:Fi,canvas:class extends Fi{constructor(L,k,T,B){super(L,k,T,B),k.coordinates?Array.isArray(k.coordinates)&&k.coordinates.length===4&&!k.coordinates.some(K=>!Array.isArray(K)||K.length!==2||K.some(Q=>typeof Q!="number"))||this.fire(new o.f(new rs(`sources.${L}`,null,'"coordinates" property must be an array of 4 longitude/latitude array pairs'))):this.fire(new o.f(new rs(`sources.${L}`,null,'missing required property "coordinates"'))),k.animate&&typeof k.animate!="boolean"&&this.fire(new o.f(new rs(`sources.${L}`,null,'optional "animate" property must be a boolean value'))),k.canvas?typeof k.canvas=="string"||k.canvas instanceof HTMLCanvasElement||this.fire(new o.f(new rs(`sources.${L}`,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.f(new rs(`sources.${L}`,null,'missing required property "canvas"'))),this.options=k,this.animate=k.animate===void 0||k.animate}async 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.f(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(L){this.map=L,this.load(),this.canvas&&this.animate&&this.play()}onRemove(L){this.pause()}prepare(){let L=!1;if(this.canvas.width!==this.width&&(this.width=this.canvas.width,L=!0),this.canvas.height!==this.height&&(this.height=this.canvas.height,L=!0),this._hasInvalidDimensions()||Object.keys(this.tiles).length===0)return;const k=this.map.painter.context;this.texture?!L&&!this._playing||this.texture instanceof o.cO||this.texture.update(this.canvas,{premultiply:!0}):this.texture=new o.T(k,this.canvas,k.gl.RGBA8,{premultiply:!0}),this._prepareData(k)}serialize(){return{type:"canvas",coordinates:this.coordinates}}hasTransition(){return this._playing}_hasInvalidDimensions(){for(const L of[this.canvas.width,this.canvas.height])if(isNaN(L)||L<=0)return!0;return!1}},custom:class extends o.E{constructor(L,k,T,B){super(),this.id=L,this.type="custom",this._dataType="raster",this._dispatcher=T,this._implementation=k,this.setEventedParent(B),this.scheme="xyz",this.minzoom=0,this.maxzoom=22,this.tileSize=512,this._loaded=!1,this.roundZoom=!0,this._implementation||this.fire(new o.f(new Error(`Missing implementation for ${this.id} custom source`))),this._implementation.loadTile||this.fire(new o.f(new Error(`Missing loadTile implementation for ${this.id} custom source`))),this._implementation.bounds&&(this.tileBounds=new o.cF(this._implementation.bounds,this.minzoom,this.maxzoom));const K=k;K.update=this._update.bind(this),K.clearTiles=this._clearTiles.bind(this),K.coveringTiles=this._coveringTiles.bind(this),Object.assign(this,o.cB(k,["dataType","scheme","minzoom","maxzoom","tileSize","attribution","minTileCacheSize","maxTileCacheSize"]))}serialize(){return o.cB(this,["type","scheme","minzoom","maxzoom","tileSize","attribution"])}load(){this._loaded=!0,this.fire(new o.h("data",{dataType:"source",sourceDataType:"metadata"})),this.fire(new o.h("data",{dataType:"source",sourceDataType:"content"}))}loaded(){return this._loaded}onAdd(L){this.map=L,this._loaded=!1,this.fire(new o.h("dataloading",{dataType:"source"})),this._implementation.onAdd&&this._implementation.onAdd(L),this.load()}onRemove(L){this._implementation.onRemove&&this._implementation.onRemove(L)}hasTile(L){if(this._implementation.hasTile){const{x:k,y:T,z:B}=L.canonical;return this._implementation.hasTile({x:k,y:T,z:B})}return!this.tileBounds||this.tileBounds.contains(L.canonical)}async loadTile(L,k){const{x:T,y:B,z:K}=L.tileID.canonical,Q=new AbortController;L.request=Q;try{const le=await this._implementation.loadTile({x:T,y:B,z:K},{signal:Q.signal});if(delete L.request,L.aborted)return L.state="unloaded",k(null);if(le===void 0)return L.state="errored",k(null);if(le===null)return this.loadTileData(L,{width:this.tileSize,height:this.tileSize,data:null}),L.state="loaded",k(null);if(!function(me){return me instanceof ImageData||me instanceof HTMLCanvasElement||me instanceof ImageBitmap||me instanceof HTMLImageElement}(le))return L.state="errored",k(new Error(`Can't infer data type for ${this.id}, only raster data supported at the moment`));this.loadTileData(L,le),L.state="loaded",k(null)}catch(le){if(Q.signal.aborted)return;L.state="errored",k(le)}}loadTileData(L,k){L.setTexture(k,this.map.painter)}unloadTile(L,k){if(L.texture&&L.texture instanceof o.T?(L.destroy(!1),L.texture&&L.texture instanceof o.T&&this.map.painter.saveTileTexture(L.texture)):L.destroy(),this._implementation.unloadTile){const{x:T,y:B,z:K}=L.tileID.canonical;this._implementation.unloadTile({x:T,y:B,z:K})}k&&k()}abortTile(L,k){L.request&&(L.request.abort(),delete L.request),k&&k()}hasTransition(){return!1}_coveringTiles(){return this.map.transform.coveringTiles({tileSize:this.tileSize,minzoom:this.minzoom,maxzoom:this.maxzoom,roundZoom:this.roundZoom}).map(L=>({x:L.canonical.x,y:L.canonical.y,z:L.canonical.z}))}_clearTiles(){const L=o.m(this.id,this.scope);this.map.style.clearSource(L)}_update(){this.fire(new o.h("data",{dataType:"source",sourceDataType:"content"}))}}},lo=function(L,k,T,B){const K=Dc(k.type);if(!K)throw new Error(`Unknown source type "${k.type}"`);const Q=new K(L,k,T,B);if(Q.id!==L)throw new Error(`Expected Source id to be ${L} instead of ${Q.id}`);return o.aW(["load","abort","unload","serialize","prepare"],Q),Q},Dc=function(L){return Object.hasOwn(bl,L)?bl[L]:void 0};function mf([L,k],T,B,{scaled:K=!0}={}){const{tileSize:Q,buffer:le}=B,{x:me,y:we,z:Me}=T;if(!isFinite(me)||!isFinite(we)||!isFinite(Me))throw new Error("Invalid MRT header");const Re=2**Me,Ze=Re*o.a7(L),Qe=Re*o.a8(k);return function([ht,_t],bt,{scaled:Mt=!0}={}){if(!bt)throw new Error("bandView is undefined");const{data:es,tileSize:Qt,buffer:Lt,offset:ps,scale:Hs,dimension:Fs}=bt;if(ht<-Lt||ht>Qt+Lt||_t<-Lt||_t>Qt+Lt)throw new Error(`Point (${ht}, ${_t}) out of bounds for tileSize=${Qt}, buffer=${Lt}`);const nn=(_t+Lt)*(Qt+2*Lt)+(ht+Lt);if(new Uint32Array(es.buffer)[nn]===4294967295)return null;let $s=[];$s=Mt?[]:new bt.data.constructor(Fs);for(let rn=0;rn=Qe||Ze<0||Ze>=Qe)throw new Zl(`Invalid overzoom, ${we}/${le}/${me} is not a child of ${Q}/${B}/${K}.`);const ht=0|Math.log2(L),_t=Math.min(Me,ht),bt=Me-_t,Mt=L>>_t;return{offset:[(Re>>bt)*Mt,(Ze>>bt)*Mt],tileSize:Mt,deltaZ:Me}}o.c_.setPbf(o.c$);class mm extends Rx{constructor(k,T,B,K,Q){super(k,T,B,K,Q),this._workQueuePerLayer=new Map,this._fetchQueuePerLayer=new Map,this._taskQueue=new Map,this._isHeaderLoaded=!1,this._isLoadInProgress=!1,this.textureDescriptorPerLayer=new Map,this.texturePerLayer=new Map,this.parentTile=null,this.overzoomCoordsPerLayer=null}getLayers(){return this._mrt?Object.values(this._mrt.layers):[]}getLayer(k){return this._mrt&&this._mrt.getLayer(k)}setTexturePerLayer(k,T,B){const K=B.context,Q=K.gl;let le=this.texturePerLayer.get(k)||B.getTileTexture(T.width);le&&le instanceof o.T?le.update(T,{premultiply:!1}):(le=new o.T(K,T,Q.RGBA8,{premultiply:!1}),le.bind(Q.LINEAR,Q.CLAMP_TO_EDGE)),this.texturePerLayer.has(k)||this.texturePerLayer.set(k,le)}flushQueues(k){const T=this._workQueuePerLayer.get(k)||[],B=this._fetchQueuePerLayer.get(k)||[];for(;T.length;)T.pop()();for(;B.length;)B.pop()()}flushAllQueues(){for(const k of this._workQueuePerLayer.keys()){const T=this._workQueuePerLayer.get(k)||[];for(;T.length;)T.pop()()}for(const k of this._fetchQueuePerLayer.keys()){const T=this._fetchQueuePerLayer.get(k)||[];for(;T.length;)T.pop()()}}fetchHeader(k=16384,T){const B=this._mrt=new o.c_(30),K={...this.requestParams,headers:{Range:"bytes=0-"+(k-1)}};this.entireBuffer=null;const Q=new AbortController;return this.request=Q,o.d0(K,Q.signal).then(({data:le,headers:me})=>{try{const we=B.getHeaderLength(le);if(we>k)return void(this.request=this.fetchHeader(we,T));B.parseHeader(le),this._isHeaderLoaded=!0;let Me=0;for(const Re of Object.values(B.layers))Me=Math.max(Me,Re.dataIndex.at(-1).lastByte);le.byteLength>=Me&&(this.entireBuffer=le),T(null,this.entireBuffer||le,me)}catch(we){T(we)}}).catch(le=>{Q.signal.aborted||T(le)}),this.request}fetchBandForRender(k,T,B,K){this.fetchBand(k,T,B,Q=>{if(Q)return void K(Q);this.updateTextureDescriptor(k,T,B);const le=this.textureDescriptorPerLayer.get(T);K(null,le?le.img:null)})}fetchBand(k,T,B,K){const Q=this._mrt;if(!this._isHeaderLoaded||!Q)return void K(new Error("Tile header is not ready"));if(this.parentTile&&this.overzoomCoordsPerLayer)return void K(null,null);const le=this.actor;if(!le)return void K(new Error("Can't fetch tile band without an actor"));let me;const we=o.m(String(B),o.m(this.tileID.key,k));let Me=this._taskQueue.get(we);Me?Me.add(K):(Me=new Set,Me.add(K),this._taskQueue.set(we,Me));const Re=(_t,bt)=>{me.complete(_t,bt),_t?K(_t):(Me.forEach(Mt=>Mt(null,bt)),this._taskQueue.delete(we))},Ze=(_t,bt)=>{if(_t)return K(_t);let Mt,es=!1;if(T!==null){const Lt=this._workQueuePerLayer.get(T)||[];Lt.push(()=>{es=!0,Mt&&Mt.abort(),me.cancel()}),this._workQueuePerLayer.has(T)||this._workQueuePerLayer.set(T,Lt)}const Qt=()=>{es||(Mt=le.sendCancelable("decodeRasterArray",{type:"raster-array",source:this.source,scope:this.scope,tileID:this.tileID,uid:this.uid,buffer:bt,task:me},{},Re))};this.workerReady!==void 0?this.workerReady.then(Qt).catch(Lt=>K(Lt)):Qt()};let Qe;try{Qe=Q.getLayer(k)}catch(_t){if(this.parentTile&&this.overzoomCoordsPerLayer)return void K(new Error(`Layer '${k}' not found in parent tile MRT`));if(this.state==="reloading")return;throw _t}if(!Qe)return void K(new Error(`Unknown sourceLayer "${k}"`));if(Qe.hasDataForBand(B))return Me.forEach(_t=>_t(null,null)),void this._taskQueue.delete(we);const ht=Qe.getDataRange([B]);if(me=Q.createDecodingTask(ht),!me||me.tasks.length)if(T!==null&&this.flushQueues(T),this.entireBuffer)Ze(null,this.entireBuffer.slice(ht.firstByte,ht.lastByte+1));else{const _t={...this.requestParams,headers:{Range:`bytes=${ht.firstByte}-${ht.lastByte}`}},bt=new AbortController;if(o.d0(_t,bt.signal).then(({data:Mt})=>Ze(null,Mt)).catch(Mt=>{bt.signal.aborted||Ze(Mt)}),T!==null){const Mt=this._fetchQueuePerLayer.get(T)||[];Mt.push(()=>{bt.abort(),me.cancel()}),this._fetchQueuePerLayer.has(T)||this._fetchQueuePerLayer.set(T,Mt)}}}updateNeeded(k,T){return(!this.textureDescriptorPerLayer.get(k)||this.textureDescriptorPerLayer.get(k).band!==T||this.refreshedUponExpiration)&&this.state!=="errored"}updateTextureDescriptor(k,T,B){if(!this._mrt)return;let K;try{K=this._mrt.getLayer(k)}catch{return}if(!K||!K.hasBand(B)||!K.hasDataForBand(B))return;let{bytes:Q,tileSize:le,buffer:me,offset:we,scale:Me}=K.getBandView(B);if(this.parentTile&&this.overzoomCoordsPerLayer){const ht=this.overzoomCoordsPerLayer.get(k);ht&&(Q=this.cropBandData(Q,le,me,ht),le=ht.tileSize)}const Re=le+2*me,Ze=new o.b({width:Re,height:Re},Q),Qe=this.texturePerLayer.get(T);Qe&&Qe instanceof o.T&&Qe.update(Ze,{premultiply:!1}),this.textureDescriptorPerLayer.set(T,{layer:k,band:B,img:Ze,buffer:me,offset:we,tileSize:le,format:K.pixelFormat,mix:[Me,256*Me,65536*Me,16777216*Me]})}cropBandData(k,T,B,K){const{offset:Q,tileSize:le}=K,me=T+2*B,we=le+2*B;return function(Me,Re,Ze,Qe){const ht=function(ps){if(ps instanceof Uint8Array)return"uint8";if(ps instanceof Uint16Array)return"uint16";if(ps instanceof Uint32Array)return"uint32";throw new Error("Invalid array type")}(Me),_t=yo[ht];if(!_t)throw new Error(`Invalid data type "${ht}"`);const bt=Re[2]*Re[3],Mt=Re[1]*bt,es=Ze[2]*Ze[3],Qt=Ze[1]*es,Lt=new _t(Qt*Ze[0]);for(let ps=0;psnew mm(L,k,T,B,K);const To={RasterArrayTileSource:class extends dr{get partial(){return!this.map.style.imageManager.hasImageProviderForSource(this.id,this.scope)}constructor(L,k,T,B){super(L,k,T,B),this.type="raster-array",this.maxzoom=k.maxzoom!==void 0?k.maxzoom:22,this._loadTilePending={},this._loadTileLoaded={},this._pendingParentWaiters=new Map,this._options={type:"raster-array",...k}}onAdd(L){super.onAdd(L);const k=T=>{T.dataType==="source"&&T.sourceDataType==="metadata"&&(this.off("data",k),this._dataMaxzoom===void 0&&(this._dataMaxzoom=this.maxzoom))};this.on("data",k)}getDataMaxzoom(){return this._dataMaxzoom}collectOverzoomParentTileIDs(L,k){const T=[];for(const K in L){const Q=L[K];if(!Q)continue;const le=Q.parentTile;le&&L[le.tileID.key]&&T.push(le.tileID)}const B=this._dataMaxzoom;if(B!==void 0)for(const K of k){if(K.canonical.z<=B)continue;const Q=K.scaledTo(B);L[Q.key]&&T.push(Q)}return T}_narrowDataMaxzoom(L){const k=Math.max(this.minzoom,L-1);(this._dataMaxzoom===void 0||k0}_waitForParent(L,k){if(this._isParentReady(L))return void k(null);if(L.state==="errored")return void k(new Error("Parent tile failed to load"));const T=this._pendingParentWaiters.get(L.uid);if(T)return void T.push(k);this._pendingParentWaiters.set(L.uid,[k]);const B=K=>{if(K.dataType!=="source"||K.tile!==L)return;const Q=this._isParentReady(L);if(!Q&&L.state!=="errored")return;this.off("data",B);const le=this._pendingParentWaiters.get(L.uid)||[];this._pendingParentWaiters.delete(L.uid);const me=Q?null:new Error("Parent tile failed to load");for(const we of le)we(me)};this.on("data",B)}triggerRepaint(L){const k=this.map.painter._terrain,T=this.map.style.getSourceCache(this.id);k&&k.enabled&&T&&k._clearRenderCacheForTile(T.id,L.tileID),this.map.triggerRepaint()}_setupOverzoomTile(L,k){const T=this._dataMaxzoom!==void 0?this._dataMaxzoom:this.maxzoom,B=this.map.style.getSourceCache(this.id);if(!B)return void k(new Error("Source cache not found"));L._isLoadInProgress=!0;const K=L.tileID.scaledTo(T);let Q=B.getTile(K);for(;Q&&Q.parentTile;)Q=Q.parentTile;Q||(Q=B._addTile(K));const le=me=>{L._isLoadInProgress=!1,k(me)};this._waitForParent(Q,me=>{if(me||!L.setupOverzoom(Q))return L.state="errored",void le(me||new Error("Parent tile setup failed"));L.state="loaded",le(null)})}async loadTile(L,k){const T=L.tileID.canonical.z>(this._dataMaxzoom!==void 0?this._dataMaxzoom:this.maxzoom);if(L.state==="loaded"||L._isLoadInProgress)return void k(null);if(T)return void this._setupOverzoomTile(L,k);const B=this.map._requestManager.normalizeTileURL(L.tileID.canonical.url(this.tiles,this.scheme),!1,this.tileSize);L.source=this.id,L.scope=this.scope,this._workerReady===void 0&&(this._workerReady=this.dispatcher.send("ensureRasterArraySource",void 0).then(()=>{}),this._workerReady.catch(()=>{})),L.workerReady=this._workerReady,L.actor||(L.actor=this.dispatcher.getActor());const K=new AbortController;L.request=K;const Q=(le,me,we)=>{if(delete L.request,L.aborted)return k(null);if(le)return(le.status===404||typeof le.message=="string"&&le.message.includes("Not Found"))&&(this._narrowDataMaxzoom(L.tileID.canonical.z),this._dataMaxzoom!==void 0&&L.tileID.canonical.z>this._dataMaxzoom)?void this._setupOverzoomTile(L,k):(L.state="errored",k(le));if(this.map._refreshExpiredTiles&&me&&L.setExpiryData(o.cI(we)),this.partial&&L.state!=="expired")L.state="empty";else if(!this.partial){if(!me)return k(null);L.state="loaded",L._isHeaderLoaded=!0,L._mrt=me}k(null)};try{const le=await this.map._requestManager.transformRequest(B,o.R.Tile,K.signal);if(K.signal.aborted)return k(null);L.requestParams=le;const me={request:le,uid:L.uid,tileID:L.tileID,type:this.type,source:this.id,scope:this.scope,partial:this.partial};L.request=this.partial?L.fetchHeader(void 0,(we,Me,Re)=>{Q(we,Me,Re)}):L.actor.sendCancelable("loadTile",me,{},(we,Me)=>we?Q(we):Me?void Q(null,Me.mrt,Me.headers):Q(null,null))}catch(le){if(K.signal.aborted)return k(null);L.state="errored",k(le)}}abortTile(L){L.request&&(L.request.abort(),delete L.request),L.actor&&L.actor.notify("abortTile",{uid:L.uid,type:this.type,source:this.id,scope:this.scope})}unloadTile(L,k){const T=L.texturePerLayer;if(L.flushAllQueues(),T.size){L.destroy(!1);for(const B of T.values())this.map.painter.saveTileTexture(B)}else L.destroy()}prepareTile(L,k,T,B){L.tileID.canonical.z>(this._dataMaxzoom!==void 0?this._dataMaxzoom:this.maxzoom)&&(!L.parentTile||!L.overzoomCoordsPerLayer)||L._isHeaderLoaded&&(L.state!=="empty"&&(L.state="reloading"),L.fetchBandForRender(k,T,B,(K,Q)=>{K?(L.state="errored",this.fire(new o.f(K))):Q&&(L._isHeaderLoaded=!0,L.setTexturePerLayer(T,Q,this.map.painter),L.state="loaded"),this.triggerRepaint(L)}))}getInitialBand(L){if(!this.rasterLayers)return 0;const k=this.rasterLayers.find(({id:K})=>K===L),T=k&&k.fields,B=T&&T.bands&&T.bands;return B?B[0]:0}getTextureDescriptor(L,k,T){if(!L)return;const B=k.sourceLayer||this.rasterLayerIds&&this.rasterLayerIds[0];if(!B)return;let K=null;k instanceof o.cX?K=k.paint.get("raster-array-band"):k instanceof o.cY&&(K=k.paint.get("raster-particle-array-band"));const Q=K||this.getInitialBand(B);return Q==null||!L.textureDescriptorPerLayer.get(k.id)||L.updateNeeded(k.id,Q)&&!T?void 0:{...L.textureDescriptorPerLayer.get(k.id),texture:L.texturePerLayer.get(k.id)}}getImages(L,k){const T=new Map;for(const B of L)for(const K of k){const[Q,le]=K.split("/"),me=B.getLayer(Q);if(!me||!me.hasBand(le)||!me.hasDataForBand(le))continue;const{bytes:we,tileSize:Me,buffer:Re}=me.getBandView(le),Ze=Me+2*Re,Qe={data:new o.b({width:Ze,height:Ze},we),pixelRatio:2,sdf:!1,usvg:!1,version:0};T.set(K,Qe)}return T}queryRasterArrayValueByBandId(L,k,T){const B=k._mrt;return new Promise(K=>{const Q={},le=new Set;for(const[me,we]of Object.entries(B.layers)){if(T.layerName&&me!==T.layerName)continue;const Me={};Q[me]=Me;for(const{bands:Re}of we.dataIndex)for(const Ze of Re)T.bands&&!T.bands.includes(Ze)||(le.add(o.m(me,Ze)),k.fetchBand(me,null,Ze,Qe=>{o.e.frame(()=>{Me[Ze]=Qe?null:mf([L.lng,L.lat],B,we.getBandView(Ze)),le.delete(o.m(me,Ze)),le.size===0&&K(Q)})}))}le.size===0&&K(Q)})}_loadTileForQuery(L){if(this._loadTileLoaded[L.uid])return Promise.resolve(L._mrt);if(L.uid in this._loadTilePending)return this._loadTilePending[L.uid];const k=this._fetchTileForQuery(L);return this._loadTilePending[L.uid]=k,k}async _fetchTileForQuery(L){const k=this.map._requestManager.normalizeTileURL(L.tileID.canonical.url(this.tiles,this.scheme),!1,this.tileSize);try{const T={request:await this.map._requestManager.transformRequest(k,o.R.Tile),uid:L.uid,tileID:L.tileID,type:this.type,source:this.id,scope:this.scope,partial:!1},B=await L.actor.send("loadTile",T);if(!B)return null;const K=B.mrt;return this.map._refreshExpiredTiles&&L.setExpiryData(o.cI(B.headers)),L._mrt=K,L._isHeaderLoaded=!0,L.state="loaded",this._loadTileLoaded[L.uid]=!0,K}finally{delete this._loadTilePending[L.uid]}}async queryRasterArrayValueByAllBands(L,k,T){return await this._loadTileForQuery(k)?this.queryRasterArrayValueByBandId(L,k,T):null}queryRasterArrayValue(L,k){const T=o.cZ.convert(L),B=this.findLoadedParent(T);return B&&B._mrt?k.bands||!this.partial?this.queryRasterArrayValueByBandId(T,B,k):this.queryRasterArrayValueByAllBands(T,B,k):Promise.resolve(null)}findLoadedParent(L){const k=o.bT.fromLngLat(L,this.map.transform.tileSize),T=this.maxzoom+1,B=1<=B||le<0||le>=B)return null;const me=this.map.style.getSourceCache(this.id),we=new o.bQ(T,K,T,Q,le);return me.findLoadedParent(we,this.minzoom)}}},Xl=To,Uc={model:()=>vr().then(()=>br.ModelSource),"batched-model":()=>vr().then(()=>br.Tiled3dModelSource),"raster-array":()=>async function(){return Promise.resolve()}().then(()=>Xl.RasterArrayTileSource)};class Lf extends o.E{constructor(k,T,B,K){super(),this.id=k,this.type=T.type,this._options=T,this.minzoom=0,this.maxzoom=22,this.tileSize=512,this.setEventedParent(K)}hasTransition(){return!1}loaded(){return!1}onAdd(k){}onRemove(k){}loadTile(k,T){}serialize(){return this._options}}function ig(L,k,T=""){return`${T}:${k.id||""}:${k.layer.id}:${function(B){if("layerId"in B)return`layer:${B.layerId}`;{const{featuresetId:K,importId:Q}=B;return`featureset:${K}${Q?`:import:${Q}`:""}`}}(L.target)}`}function Qd(L,k,T,B=""){if(L.uniqueFeatureID){const K=ig(L,k,B);if(T.has(K))return!0;T.add(K)}return!1}function og(L,k,T,B,K=!1,Q=void 0){const le=k.sourceCache.transform,me=k.sourceCache.tilesIn(L,k.has3DLayers,K);me.sort(md);const we=[];for(const Me of me){const Re=Me.tile.queryRenderedFeatures(k,Me,T,B,le,K,Q);Object.keys(Re).length&&we.push({wrappedTileID:Me.tile.tileID.wrapped().key,queryResults:Re})}for(const Me in k.layers){const Re=k.layers[Me];if(Re.styleLayer){const Ze=Re.styleLayer.queryRenderedFeatures(L,k.sourceCache,B);Object.keys(Ze).length&&we.push({wrappedTileID:0,queryResults:Ze})}}return we.length===0?{}:function(Me){const Re={},Ze={};for(const Qe of Me){const ht=Qe.queryResults,_t=Qe.wrappedTileID,bt=Ze[_t]=Ze[_t]||{};for(const Mt in ht){const es=ht[Mt],Qt=bt[Mt]=bt[Mt]||{},Lt=Re[Mt]=Re[Mt]||[];for(const ps of es)Qt[ps.featureIndex]||(Qt[ps.featureIndex]=!0,Lt.push(ps))}}return Re}(we)}function Dh(L,k,T,B,K,Q){const le={},me=B.queryRenderedSymbols(L),we=[];for(const Me of Object.keys(me).map(Number))we.push(K[Me]);we.sort(md);for(const Me of we){const Re=Me.featureIndex.lookupSymbolFeatures(me[Me.bucketInstanceId],Me.bucketIndex,Me.sourceLayerIndex,k,T,Q);for(const Ze in Re){const Qe=le[Ze]=le[Ze]||[],ht=Re[Ze];ht.sort((_t,bt)=>{const Mt=Me.featureSortOrder;if(Mt){const es=Mt.indexOf(_t.featureIndex);return Mt.indexOf(bt.featureIndex)-es}return bt.featureIndex-_t.featureIndex});for(const _t of ht)Qe.push(_t)}}return le}function ff(L,k){const T=L.getRenderableIds().map(Q=>L.getTileByID(Q)),B=[],K={};for(let Q=0;Q0:B.type==="building"?K=!B.isHidden(k)&&B.paint.get("building-opacity")>0:B.type==="model"&&(K=!B.isHidden(k)&&B.paint.get("model-opacity").constantOr(1)>0),this.layersGotHidden=this.layersGotHidden||!K&&T.visible,T.visible=K}}updateZOffset(k,T){this.currentBuildingBuckets=[];for(const K of this.layers){const Q=K.layer,le=this.style.getLayerSourceCache(Q);let me=1;Q.type==="fill-extrusion"?me=K.visible?Q.paint.get("fill-extrusion-vertical-scale"):0:Q.type==="building"&&(me=K.visible?Q.paint.get("building-vertical-scale"):0);let we=le?le.getTile(T):null;if(!we&&le)for(const Me in le._tiles){const Re=le._tiles[Me];if(T.canonical.isChildOf(Re.tileID.canonical)){we=Re;break}}this.currentBuildingBuckets.push({bucket:we?we.getBucket(Q):null,tileID:we?we.tileID:T,verticalScale:me})}k.hasAnyZOffset=!1;let B=!1;for(let K=0;K{le in K&&(Q[le]=K[le])}),T}function op(L){L=L.slice();const k=Object.create(null);for(const T of L)k[T.id]=T;for(let T=0;T0?(K-le)/me:0;return this.points[Q].mult(1-we).add(this.points[T].mult(we))}}const bh=100;class vc{constructor(k,T){this.gridRightBoundary=0,this.gridBottomBoundary=0,this.clippedSymbols=new Map,this.reset(k,T)}reset(k,T){const B=k.width+200,K=k.height+200;B!==this.gridRightBoundary||K!==this.gridBottomBoundary?(this.grid=new o.d2(B,K,25),this.ignoredGrid=new o.d2(B,K,25)):(this.grid.clear(),this.ignoredGrid.clear()),this.transform=k,this.fogState=T,this.pitchfactor=Math.cos(k._pitch)*k.cameraToCenterDistance,this.screenRightBoundary=k.width+bh,this.screenBottomBoundary=k.height+bh,this.gridRightBoundary=B,this.gridBottomBoundary=K,this.clippedSymbols.clear()}clearClippedSymbolsForBucket(k){this.clippedSymbols.delete(k)}markSymbolAsClipped(k,T){let B=this.clippedSymbols.get(k);B||(B=new Set,this.clippedSymbols.set(k,B)),B.add(T)}placeCollisionBox(k,T,B,K,Q,le,me,we,Me,Re,Ze){let Qe=B.projectedAnchorX,ht=B.projectedAnchorY,_t=B.projectedAnchorZ;const bt=B.tileAnchorX,Mt=B.tileAnchorY,es=B.elevation,Qt=B.tileID,Lt=k.getProjection();if(es&&Qt){const[$n,zn,Dr]=Lt.upVector(Qt.canonical,B.tileAnchorX,B.tileAnchorY),An=Lt.upVectorScale(Qt.canonical,this.transform.center.lat,this.transform.worldSize).metersToTile;Qe+=$n*es*An,ht+=zn*es*An,_t+=Dr*es*An}const ps=k.projection.name==="globe",Hs=k.projection.name==="globe"?o.S(this.transform.zoom):0;if(Qt&&ps&&Hs<1&&!le){const $n=1<0,Lt),nn=Me*Fs.perspectiveRatio,$s=(B.x1*T+me.x-B.padding)*nn+Fs.point.x,rn=(B.y1*T+me.y-B.padding)*nn+Fs.point.y,_n=(B.x2*T+me.x+B.padding)*nn+Fs.point.x,Mn=(B.y2*T+me.y+B.padding)*nn+Fs.point.y,Yn=Fs.perspectiveRatio<=o.d9||Fs.occluded;return!this.isInsideGrid($s,rn,_n,Mn)||!we&&this.grid.hitTest($s,rn,_n,Mn,Ze)||Yn?{box:[],offscreen:!1,occluded:Fs.occluded}:{box:[$s,rn,_n,Mn],offscreen:this.isOffscreen($s,rn,_n,Mn),occluded:!1}}placeCollisionCircles(k,T,B,K,Q,le,me,we,Me,Re,Ze,Qe,ht,_t,bt,Mt){const es=[],Qt=this.transform.elevation,Lt=k.getProjection(),ps=k.elevationType==="road",Hs=!!Qt||ps,Fs=o.c2.getAtTileOffsetFunc(Mt,this.transform.center.lat,this.transform.worldSize,Lt),nn=new o.P(B.tileAnchorX,B.tileAnchorY),$s=new o.P(B.tileAnchorX,B.tileAnchorY);let{x:rn,y:_n,z:Mn}=Lt.projectTilePoint($s.x,$s.y,Mt.canonical),Yn=null;if(Hs){Yn=ps&&k.hdExt?k.hdExt.makeRoadSymbolElevationParams(k,k.text,K,Mt,Fs,Qt,Lt,this.transform.center.lat,this.transform.worldSize):{getElevation:Fs,elevation:Qt,elevationFeature:null};const[Ga,Vr,Za]=Yn.getElevation(nn,Qt,Yn.elevationFeature);rn+=Ga,_n+=Vr,Mn+=Za}const $n=Lt.name==="globe",zn=this.projectAndGetPerspectiveRatio(we,rn,_n,Mn,Mt,$n||!!Qt||this.transform.pitch>0,Lt),{perspectiveRatio:Dr}=zn,An=(Qe?me/Dr:me*Dr)/o.dg,yr=o.da(rn,_n,Mn,Me),sa=B.lineOffsetX*An,ka=B.lineOffsetY*An,Hr=o.av(k.layers[0].layout.get("text-max-angle")),ea=Math.cos(Hr),si=zn.signedDistanceFromCamera>0?o.db(An,le,sa,ka,ps&&B.flipState===1,yr,$s,B,Q,Me,{},Hs&&!Qe?Yn:null,Qe&&Hs,Lt,Mt,Qe,ea):null;let Wr=!1,Mr=!1,Gr=!0;if(si&&!zn.occluded){const Ga=.5*_t*Dr+bt,Vr=new o.P(-100,-100),Za=new o.P(this.screenRightBoundary,this.screenBottomBoundary),Oi=new hh,{first:Do,last:so}=si,Vl=Do.path.length;let bu=[];for(let no=Vl-1;no>=1;no--)bu.push(Do.path[no]);for(let no=1;no(Hs&&!$n&&(Yh=Yn.getElevation(whno[3]<=0)&&(bu=[]));let Ko=[];if(bu.length>0){let no=1/0,jd=-1/0,Yh=1/0,wh=-1/0;for(const Hl of bu)no=Math.min(no,Hl[0]),Yh=Math.min(Yh,Hl[1]),jd=Math.max(jd,Hl[0]),wh=Math.max(wh,Hl[1]);jd>=Vr.x&&no<=Za.x&&wh>=Vr.y&&Yh<=Za.y&&(Ko=[bu.map(Hl=>new o.P(Hl[0],Hl[1]))],(noZa.x||YhZa.y)&&(Ko=o.dc(Ko,Vr.x,Vr.y,Za.x,Za.y)))}for(const no of Ko){Oi.reset(no,.25*Ga);let jd=0;jd=Oi.length<=.5*Ga?1:Math.ceil(Oi.paddedLength/qc)+1;for(let Yh=0;Yh0?(o.c6(we,we,k),this.fogState&&Q&&me.name!=="globe"&&(Me=o.dd(this.fogState,T,B,K,Q.toUnwrapped(),this.transform)>o.dh)):o.de(we,we,k);const Re=we[3];return{point:new o.P((we[0]/Re+1)/2*this.transform.width+bh,(-we[1]/Re+1)/2*this.transform.height+bh),perspectiveRatio:Math.min(.5+this.transform.getCameraToCenterDistance(me)/Re*.5,1.5),signedDistanceFromCamera:Re,occluded:le&&we[2]>Re||Me}}isOffscreen(k,T,B,K){return B=this.screenRightBoundary||Kthis.screenBottomBoundary}isInsideGrid(k,T,B,K){return B>=0&&k=0&&TB.collisionGroupID===T}}return this.collisionGroups[k]}}function rx(L,k,T,B,K){const{horizontalAlign:Q,verticalAlign:le}=o.du(L),me=-(Q-.5)*k,we=-(le-.5)*T,Me=o.dv(L,B);return new o.P(me+Me[0]*K,we+Me[1]*K)}function Jd(L,k,T,B,K){const Q=new o.P(L,k);return T&&Q._rotate(B?K:-K),Q}function pf(L,k,T,B){const{leftJustifiedTextSymbolIndex:K,centerJustifiedTextSymbolIndex:Q,rightJustifiedTextSymbolIndex:le,verticalPlacedTextSymbolIndex:me,crossTileID:we}=T,Me=o.dw(k),Re=B===o.dt.vertical?me:Me==="left"?K:Me==="center"?Q:Me==="right"?le:-1;K>=0&&(L.text.placedSymbolArray.get(K).crossTileID=Re>=0&&K!==Re?0:we),Q>=0&&(L.text.placedSymbolArray.get(Q).crossTileID=Re>=0&&Q!==Re?0:we),le>=0&&(L.text.placedSymbolArray.get(le).crossTileID=Re>=0&&le!==Re?0:we),me>=0&&(L.text.placedSymbolArray.get(me).crossTileID=Re>=0&&me!==Re?0:we)}function Pd(L,k,T){const B=k===o.dt.horizontal||k===o.dt.horizontalOnly?k:0,K=k===o.dt.vertical?k:0,{leftJustifiedTextSymbolIndex:Q,centerJustifiedTextSymbolIndex:le,rightJustifiedTextSymbolIndex:me,verticalPlacedTextSymbolIndex:we}=T,Me=L.text.placedSymbolArray;Q>=0&&(Me.get(Q).placedOrientation=B),le>=0&&(Me.get(le).placedOrientation=B),me>=0&&(Me.get(me).placedOrientation=B),we>=0&&(Me.get(we).placedOrientation=K)}class Ql{constructor(k,T,B,K,Q,le,me){this.transform=k.clone(),this.projection=k.projection.name,me instanceof vc?(me.reset(this.transform,Q),this.collisionIndex=me):this.collisionIndex=new vc(this.transform,Q),this.buildingIndex=le,this.frontCutoffStart=0,this.placements={},this.opacities={},this.variableOffsets={},this.stale=!1,this.commitTime=0,this.fadeDuration=T,this.retainedQueryData={},this.collisionGroups=new Pp(B),this.collisionCircleArrays={},this.prevPlacement=K,K&&(K.prevPlacement=void 0),this.placedOrientations={},this.lastReplacementSourceUpdateTime=0}getBucketParts(k,T,B,K,Q=1){const le=B.getBucket(T),me=B.latestFeatureIndex;if(!le||!me||T.fqid!==le.layerIds[0])return;const we=le.layers[0].layout,Me=le.layers[0].paint,Re=B.collisionBoxArray,Ze=Math.pow(2,this.transform.zoom-B.tileID.overscaledZ),Qe=B.tileSize/o.a6,ht=B.tileID.toUnwrapped();this.transform.setProjection(le.projection);const _t=o.di(B.tileID,le.getProjection(),this.transform,this.projection),bt=we.get("text-pitch-alignment")==="map",Mt=we.get("text-rotation-alignment")==="map";T.compileFilter(T.options);const es=T.dynamicFilter(),Qt=T.dynamicFilterNeedsFeature(),Lt=T.dynamicFilterNeedsGeometry(),ps=this.transform.calculatePixelsToTileUnitsMatrix(B),Hs=o.dj(_t,B.tileID.canonical,bt,Mt,this.transform,le.getProjection(),ps);let Fs=null;const nn=le.getProjection().createInversionMatrix(this.transform,B.tileID.canonical);if(bt){const An=o.dk(_t,B.tileID.canonical,bt,Mt,this.transform,le.getProjection(),ps);Fs=o.X([],this.transform.labelPlaneMatrix,An)}let $s=null;es&&B.latestFeatureIndex&&($s={unwrappedTileID:ht,dynamicFilter:es,dynamicFilterNeedsFeature:Qt,needGeometry:Lt}),this.retainedQueryData[le.bucketInstanceId]=new nx(le.bucketInstanceId,me,le.sourceLayerIndex,le.index,B.tileID);const[rn,_n]=le.layers[0].layout.get("text-size-scale-range"),Mn=o.b1(Q,rn,_n),[Yn,$n]=we.get("icon-size-scale-range"),zn=o.b1(Q,Yn,$n),Dr={bucket:le,layout:we,paint:Me,posMatrix:_t,invMatrix:nn,mercatorCenter:[o.a7(this.transform.center.lng),o.a8(this.transform.center.lat)],textLabelPlaneMatrix:Hs,labelToScreenMatrix:Fs,clippingData:$s,scale:Ze,textPixelRatio:Qe,holdingForFade:B.holdingForFade(),collisionBoxArray:Re,partiallyEvaluatedTextSize:o.dl(le.textSizeData,this.transform.zoom,Mn),partiallyEvaluatedIconSize:o.dl(le.iconSizeData,this.transform.zoom,zn),collisionGroup:this.collisionGroups.get(le.sourceID),latestFeatureIndex:B.latestFeatureIndex};if(K)for(const An of le.sortKeyRanges){const{sortKey:yr,symbolInstanceStart:sa,symbolInstanceEnd:ka}=An;k.push({sortKey:yr,symbolInstanceStart:sa,symbolInstanceEnd:ka,parameters:Dr})}else k.push({symbolInstanceStart:0,symbolInstanceEnd:le.symbolInstances.length,parameters:Dr})}placeLayerBucketPart(k,T,B,K=1){const{bucket:Q,layout:le,paint:me,posMatrix:we,textLabelPlaneMatrix:Me,labelToScreenMatrix:Re,clippingData:Ze,textPixelRatio:Qe,mercatorCenter:ht,invMatrix:_t,holdingForFade:bt,collisionBoxArray:Mt,partiallyEvaluatedTextSize:es,partiallyEvaluatedIconSize:Qt,collisionGroup:Lt,latestFeatureIndex:ps}=k.parameters,Hs=le.get("text-optional"),Fs=le.get("icon-optional"),nn=le.get("text-allow-overlap"),$s=le.get("icon-allow-overlap"),rn=le.get("text-rotation-alignment")==="map",_n=le.get("icon-rotation-alignment")==="map",Mn=le.get("text-pitch-alignment")==="map",Yn=me.get("symbol-z-offset"),$n=le.get("symbol-elevation-reference")==="sea",zn=le.get("symbol-placement"),Dr=le.get("text-variable-anchor"),An=rn&&zn!=="point",yr=_n&&zn!=="point",sa=Dr&&Q.hasTextData(),ka=Q.hasIconTextFit()&&sa&&Q.hasIconData();this.transform.setProjection(Q.projection);const Hr=sa||An,ea=yr||ka;let si=nn&&($s||!Q.hasIconData()||Fs),Wr=$s&&(nn||!Q.hasTextData()||Hs);const Mr=!Yn.isConstant();!Q.collisionArrays&&Mt&&Q.deserializeCollisionBoxes(Mt);const Gr=(Vr,Za,Oi)=>{const{crossTileID:Do,numVerticalGlyphVertices:so}=Vr;let Vl=null;if(Ze&&Ze.dynamicFilterNeedsFeature||Mr){const _u=this.retainedQueryData[Q.bucketInstanceId],ld=ps.loadFeature({featureIndex:Vr.featureIndex,bucketIndex:_u.bucketIndex,sourceLayerIndex:_u.sourceLayerIndex,layoutVertexArrayOffset:0}),Fc=ld.properties?ld.properties.worldview:null;if(Q.localizable&&Q.worldview&&typeof Fc=="string")if(Fc==="all")ld.properties.$localized=!0;else{if(!Fc.split(",").includes(Q.worldview))return;ld.properties.$localized=!0,ld.properties.worldview=Q.worldview}Vl=Ze&&Ze.needGeometry?o.bx(ld,!0):ld}if(Ze&&!(0,Ze.dynamicFilter)({zoom:this.transform.zoom,pitch:this.transform.pitch,worldview:Q.worldview},Vl,this.retainedQueryData[Q.bucketInstanceId].tileID.canonical,new o.P(Vr.tileAnchorX,Vr.tileAnchorY),this.transform.calculateDistanceTileData(Ze.unwrappedTileID)))return this.placements[Do]=new Df(!1,!1,!1,!0),void T.add(Do);const bu=Yn.evaluate(Vl,{});if((Vr.zOffset||0)+(bu||0)>0&&this.frontCutoffStart>0){const _u=2*this.frontCutoffStart-1,ld=[Vr.tileAnchorX,Vr.tileAnchorY,0,1],Fc=o.c6(o.dr(),ld,we);if(Fc[1]/Fc[3]<_u)return this.placements[Do]=new Df(!1,!1,!1,!0),void T.add(Do)}if(T.has(Do))return;if(bt)return void(this.placements[Do]=new Df(!1,!1,!1));let qc=!1,Ko=!1,no=!0,jd=!1,Yh=!1,wh=null,Hl={box:null,offscreen:null,occluded:null},fm={box:null},bc=null,rc=null,Oh=null,Zh=0,Ld=0,_c=0;Oi.textFeatureIndex?Zh=Oi.textFeatureIndex:Vr.useRuntimeCollisionCircles&&(Zh=Vr.featureIndex),Oi.verticalTextFeatureIndex&&(Ld=Oi.verticalTextFeatureIndex);const Xh=_u=>{_u.tileID=this.retainedQueryData[Q.bucketInstanceId].tileID;const ld=this.transform.elevation;if(Q.elevationType==="road")_u.elevation=$n?bu:bu+o.c2.getAtTileOffset(_u.tileID,new o.P(_u.tileAnchorX,_u.tileAnchorY),ld,null);else{const Fc=Q.hdExt?Q.hdExt.elevationFeatures[Vr.elevationFeatureIndex]:void 0;_u.elevation=$n?bu:bu+o.c2.getAtTileOffset(_u.tileID,new o.P(_u.tileAnchorX,_u.tileAnchorY),ld,Fc)}_u.elevation+=Vr.zOffset},ug=Oi.textBox;if(ug){Xh(ug);const _u=Fc=>{let Qh=o.dt.horizontal;if(Q.allowVerticalPlacement&&!Fc&&this.prevPlacement){const ix=this.prevPlacement.placedOrientations[Do];ix&&(this.placedOrientations[Do]=ix,Qh=ix,Pd(Q,Qh,Vr))}return Qh},ld=(Fc,Qh)=>{if(Q.allowVerticalPlacement&&so>0&&Oi.verticalTextBox){for(const ix of Q.writingModes)if(ix===o.dt.vertical?(Hl=Qh(),fm=Hl):Hl=Fc(),Hl&&Hl.box&&Hl.box.length)break}else Hl=Fc()};if(Dr){let Fc=Dr;if(this.prevPlacement&&this.prevPlacement.variableOffsets[Do]){const Yu=this.prevPlacement.variableOffsets[Do];Fc.indexOf(Yu.anchor)>0&&(Fc=Fc.filter(Ri=>Ri!==Yu.anchor),Fc.unshift(Yu.anchor))}const Qh=(Yu,Ri,Nm)=>{const hg=Q.getSymbolInstanceTextSize(es,Vr,this.transform.zoom,Za),uj=(Yu.x2-Yu.x1)*hg+2*Yu.padding,hj=(Yu.y2-Yu.y1)*hg+2*Yu.padding,Ub=Vr.hasIconTextFit&&!$s?Ri:null;Ub&&Xh(Ub);let qb={box:[],offscreen:!1,occluded:!1};const nN=nn?2*Fc.length:Fc.length;for(let Vb=0;Vb=Fc.length,Vr,Za,Q,Nm,Ub,es,Qt);if(jy&&(qb=jy.placedGlyphBoxes,qb&&qb.box&&qb.box.length)){qc=!0,wh=jy.shift;break}}return qb};ld(()=>Qh(ug,Oi.iconBox,o.dt.horizontal),()=>{const Yu=Oi.verticalTextBox;return Yu&&Xh(Yu),Q.allowVerticalPlacement&&!(Hl&&Hl.box&&Hl.box.length)&&so>0&&Yu?Qh(Yu,Oi.verticalIconBox,o.dt.vertical):{box:null,offscreen:null,occluded:null}}),Hl&&(qc=Hl.box,no=Hl.offscreen,jd=Hl.occluded);const ix=_u(!(!Hl||!Hl.box));if(!qc&&this.prevPlacement){const Yu=this.prevPlacement.variableOffsets[Do];Yu&&(this.variableOffsets[Do]=Yu,pf(Q,Yu.anchor,Vr,ix))}}else{const Fc=(Qh,ix)=>{const Yu=Q.getSymbolInstanceTextSize(es,Vr,this.transform.zoom,Za),Ri=this.collisionIndex.placeCollisionBox(Q,Yu,Qh,ht,_t,Hr,new o.P(0,0),nn,Qe,we,Lt.predicate);return Ri&&Ri.box&&Ri.box.length&&(Pd(Q,ix,Vr),this.placedOrientations[Do]=ix),Ri};ld(()=>Fc(ug,o.dt.horizontal),()=>{const Qh=Oi.verticalTextBox;return Q.allowVerticalPlacement&&so>0&&Qh?(Xh(Qh),Fc(Qh,o.dt.vertical)):{box:null,offscreen:null,occluded:null}}),_u(!!(Hl&&Hl.box&&Hl.box.length))}}if(bc=Hl,qc=bc&&bc.box&&bc.box.length>0,no=bc&&bc.offscreen,jd=bc&&bc.occluded,Vr.useRuntimeCollisionCircles){const _u=Vr.centerJustifiedTextSymbolIndex>=0?Vr.centerJustifiedTextSymbolIndex:Vr.verticalPlacedTextSymbolIndex,ld=Q.text.placedSymbolArray.get(_u),Fc=o.ds(Q.textSizeData,es,ld),Qh=le.get("text-padding");rc=this.collisionIndex.placeCollisionCircles(Q,nn,ld,_u,Q.lineVertexArray,Q.glyphOffsetArray,Fc,we,Me,Re,B,Mn,Lt.predicate,Vr.collisionCircleDiameter*Fc/o.dg,Qh,this.retainedQueryData[Q.bucketInstanceId].tileID),qc=nn||rc.circles.length>0&&!rc.collisionDetected,no=no&&rc.offscreen,jd=rc.occluded}if(Oi.iconFeatureIndex&&(_c=Oi.iconFeatureIndex),Oi.iconBox){const _u=ld=>{Xh(ld);const Fc=Vr.hasIconTextFit&&wh?Jd(wh.x,wh.y,rn,Mn,this.transform.angle):new o.P(0,0),Qh=Q.getSymbolInstanceIconSize(Qt,this.transform.zoom,Vr.placedIconSymbolIndex);return this.collisionIndex.placeCollisionBox(Q,Qh,ld,ht,_t,ea,Fc,$s,Qe,we,Lt.predicate)};fm&&fm.box&&fm.box.length&&Oi.verticalIconBox?(Oh=_u(Oi.verticalIconBox),Ko=Oh.box.length>0):(Oh=_u(Oi.iconBox),Ko=Oh.box.length>0),no=no&&Oh.offscreen,Yh=Oh.occluded}const Z_=Hs||Vr.numHorizontalGlyphVertices===0&&so===0,t0=Fs||Vr.numIconVertices===0;if(Z_||t0?t0?Z_||(Ko=Ko&&qc):qc=Ko&&qc:Ko=qc=Ko&&qc,qc&&bc&&bc.box&&this.collisionIndex.insertCollisionBox(bc.box,le.get("text-ignore-placement"),Q.bucketInstanceId,fm&&fm.box&&Ld?Ld:Zh,Lt.ID),Ko&&Oh&&this.collisionIndex.insertCollisionBox(Oh.box,le.get("icon-ignore-placement"),Q.bucketInstanceId,_c,Lt.ID),rc&&(qc&&this.collisionIndex.insertCollisionCircles(rc.circles,le.get("text-ignore-placement"),Q.bucketInstanceId,Zh,Lt.ID),B)){const _u=Q.bucketInstanceId;let ld=this.collisionCircleArrays[_u];ld===void 0&&(ld=this.collisionCircleArrays[_u]=new Mp);for(let Fc=0;Fc=0;--Za){const Oi=Vr[Za];Gr(Q.symbolInstances.get(Oi),Oi,Q.collisionArrays[Oi])}Q.hasAnyZOffset&&o.w(`${Q.layerIds[0]} layer symbol-z-elevate: symbols are not sorted by elevation if symbol-z-order is evaluated to viewport-y`)}else if(Q.hasAnyZOffset){const Vr=Q.getSortedIndexesByZOffset();for(let Za=0;Za0){let Yn;return this.prevPlacement&&this.prevPlacement.variableOffsets[$s]&&this.prevPlacement.placements[$s]&&this.prevPlacement.placements[$s].text&&(Yn=this.prevPlacement.variableOffsets[$s].anchor),this.variableOffsets[$s]={textOffset:rn,width:le,height:me,anchor:k,textScale:we,prevAnchor:Yn},pf(es,k,bt,Qt),es.allowVerticalPlacement&&(Pd(es,Qt,bt),this.placedOrientations[$s]=Qt),{shift:_n,placedGlyphBoxes:Mn}}}commit(k){this.commitTime=k,this.zoomAtLastRecencyCheck=this.transform.zoom;const T=this.prevPlacement;let B=!1;this.prevZoomAdjustment=T?T.zoomAdjustment(this.transform.zoom):0;const K=T?T.symbolFadeChange(k):1,Q=T?T.opacities:{},le=T?T.variableOffsets:{},me=T?T.placedOrientations:{};for(const we in this.placements){const Me=this.placements[we],Re=Q[we];Re?(this.opacities[we]=new $m(Re,K,Me.text,Me.icon,null,Me.clipped),B=B||Me.text!==Re.text.placed||Me.icon!==Re.icon.placed):(this.opacities[we]=new $m(null,K,Me.text,Me.icon,Me.skipFade,Me.clipped),B=B||Me.text||Me.icon)}for(const we in Q){const Me=Q[we];if(!this.opacities[we]){const Re=new $m(Me,K,!1,!1);Re.isHidden()||(this.opacities[we]=Re,B=B||Me.text.placed||Me.icon.placed)}}for(const we in le)this.variableOffsets[we]||!this.opacities[we]||this.opacities[we].isHidden()||(this.variableOffsets[we]=le[we]);for(const we in me)this.placedOrientations[we]||!this.opacities[we]||this.opacities[we].isHidden()||(this.placedOrientations[we]=me[we]);B?this.lastPlacementChangeTime=k:typeof this.lastPlacementChangeTime!="number"&&(this.lastPlacementChangeTime=T?T.lastPlacementChangeTime:k)}updateLayerOpacities(k,T,B,K,Q=!1,le=1){K&&(this.lastReplacementSourceUpdateTime=K.updateTime);const me=new Set;for(const we of T){const Me=we.getBucket(k);if(Me&&we.latestFeatureIndex&&k.fqid===Me.layerIds[0]&&(this.updateBucketOpacities(Me,me,we,we.collisionBoxArray,B,K,we.tileID,k.scope),Me.elevationType==="offset"&&this.buildingIndex&&this.buildingIndex.updateZOffset(Me,we.tileID),Me.elevationType==="road"&&Me.hdExt&&Me.hdExt.updateRoadElevation(Me,we.tileID.canonical),Me.updateZOffset(),Q&&we.collisionBoxArray)){const Re=Me.layers[0].layout,[Ze,Qe]=Re.get("text-size-scale-range"),[ht,_t]=Re.get("icon-size-scale-range"),bt=o.b1(le,Ze,Qe),Mt=o.b1(le,ht,_t);Me.updateCollisionDebugBuffers(this.transform.zoom,we.collisionBoxArray,bt,Mt)}}}updateBucketOpacities(k,T,B,K,Q,le,me,we){k.hasTextData()&&k.text.opacityVertexArray.clear(),k.hasIconData()&&k.icon.opacityVertexArray.clear(),k.hasIconCollisionBoxData()&&k.iconCollisionBox.collisionVertexArray.clear(),k.hasTextCollisionBoxData()&&k.textCollisionBox.collisionVertexArray.clear();const Me=k.layers[0].layout,Re=k.layers[0].paint,Ze=!!k.layers[0].dynamicFilter(),Qe=new $m(null,0,!1,!1,!0),ht=Me.get("text-allow-overlap"),_t=Me.get("icon-allow-overlap"),bt=Me.get("text-variable-anchor"),Mt=Me.get("text-rotation-alignment")==="map",es=Me.get("text-pitch-alignment")==="map",Qt=Re.get("symbol-z-offset"),Lt=Me.get("symbol-elevation-reference")==="sea",ps=!Qt.isConstant(),Hs=new $m(null,0,ht&&(_t||!k.hasIconData()||Me.get("icon-optional")),_t&&(ht||!k.hasTextData()||Me.get("text-optional")),!0);!k.collisionArrays&&K&&(k.hasIconCollisionBoxData()||k.hasTextCollisionBoxData())&&k.deserializeCollisionBoxes(K);const Fs=($s,rn,_n)=>{for(let Mn=0;Mn0||Mn>0,si=$n>0,Wr=this.placedOrientations[Yn],Mr=Wr===o.dt.vertical,Gr=Wr===o.dt.horizontal||Wr===o.dt.horizontalOnly;!ea&&!si||Hr.isHidden()||nn++;let Ga=!1;if((ea||si)&&le)for(const Vr of k.activeReplacements){if(o.dm(Vr,Q,o.dn.Symbol,we)||Vr.min.x>zn||zn>Vr.max.x||Vr.min.y>Dr||Dr>Vr.max.y)continue;const Za=o.dp(zn,Dr,me.canonical,Vr.footprintTileId.canonical);if(Ga=o.dq(Za,Vr.footprint),Ga)break}if(Ga&&this.collisionIndex.markSymbolAsClipped(k.bucketInstanceId,rn.featureIndex),ea){const Vr=Ga?lg:H1(Hr.text);Fs(k.text,_n,Mr?lg:Vr),Fs(k.text,Mn,Gr?lg:Vr);const Za=Hr.text.isHidden(),{leftJustifiedTextSymbolIndex:Oi,centerJustifiedTextSymbolIndex:Do,rightJustifiedTextSymbolIndex:so,verticalPlacedTextSymbolIndex:Vl}=rn,bu=k.text.placedSymbolArray,qc=Za||Mr?1:0;Oi>=0&&(bu.get(Oi).hidden=qc),Do>=0&&(bu.get(Do).hidden=qc),so>=0&&(bu.get(so).hidden=qc),Vl>=0&&(bu.get(Vl).hidden=Za||Gr?1:0);const Ko=this.variableOffsets[Yn];Ko&&pf(k,Ko.anchor,rn,Wr);const no=this.placedOrientations[Yn];no&&(pf(k,"left",rn,no),Pd(k,no,rn))}if(si){const Vr=Ga?lg:H1(Hr.icon),{placedIconSymbolIndex:Za,verticalPlacedIconSymbolIndex:Oi}=rn,Do=k.icon.placedSymbolArray,so=Hr.icon.isHidden()?1:0;Za>=0&&(Fs(k.icon,$n,Mr?lg:Vr),Do.get(Za).hidden=so),Oi>=0&&(Fs(k.icon,rn.numVerticalIconVertices,Gr?lg:Vr),Do.get(Oi).hidden=so)}if(k.hasIconCollisionBoxData()||k.hasTextCollisionBoxData()){const Vr=k.collisionArrays[$s];if(Vr){let Za=new o.P(0,0),Oi=!0;if(Vr.textBox||Vr.verticalTextBox){if(bt){const so=this.variableOffsets[Yn];so?(Za=rx(so.anchor,so.width,so.height,so.textOffset,so.textScale),Mt&&Za._rotate(es?this.transform.angle:-this.transform.angle)):Oi=!1}Ze&&(Oi=!Hr.clipped),Vr.textBox&&Gd(k.textCollisionBox.collisionVertexArray,Hr.text.placed,!Oi||Mr,sa,Lt,Za.x,Za.y),Vr.verticalTextBox&&Gd(k.textCollisionBox.collisionVertexArray,Hr.text.placed,!Oi||Gr,sa,Lt,Za.x,Za.y)}const Do=Oi&&!!(!Gr&&Vr.verticalIconBox);Vr.iconBox&&Gd(k.iconCollisionBox.collisionVertexArray,Hr.icon.placed,Do,sa,Lt,rn.hasIconTextFit?Za.x:0,rn.hasIconTextFit?Za.y:0),Vr.verticalIconBox&&Gd(k.iconCollisionBox.collisionVertexArray,Hr.icon.placed,!Do,sa,Lt,rn.hasIconTextFit?Za.x:0,rn.hasIconTextFit?Za.y:0)}}}if(k.fullyClipped=nn===0,k.sortFeatures(this.transform.angle),this.retainedQueryData[k.bucketInstanceId]&&(this.retainedQueryData[k.bucketInstanceId].featureSortOrder=k.featureSortOrder),k.hasTextData()&&k.text.opacityVertexBuffer&&k.text.opacityVertexBuffer.updateData(k.text.opacityVertexArray),k.hasIconData()&&k.icon.opacityVertexBuffer&&k.icon.opacityVertexBuffer.updateData(k.icon.opacityVertexArray),k.hasIconCollisionBoxData()&&k.iconCollisionBox.collisionVertexBuffer&&k.iconCollisionBox.collisionVertexBuffer.updateData(k.iconCollisionBox.collisionVertexArray),k.hasTextCollisionBoxData()&&k.textCollisionBox.collisionVertexBuffer&&k.textCollisionBox.collisionVertexBuffer.updateData(k.textCollisionBox.collisionVertexArray),k.bucketInstanceId in this.collisionCircleArrays){const $s=this.collisionCircleArrays[k.bucketInstanceId];k.placementInvProjMatrix=$s.invProjMatrix,k.placementViewportMatrix=$s.viewportMatrix,k.collisionCircleArray=$s.circles,delete this.collisionCircleArrays[k.bucketInstanceId]}}symbolFadeChange(k){return this.fadeDuration===0?1:(k-this.commitTime)/this.fadeDuration+this.prevZoomAdjustment}zoomAdjustment(k){return Math.max(0,(this.transform.zoom-k)/1.5)}hasTransitions(k){return k-this.lastPlacementChangeTimek}isStale(){return this.stale}setStale(){this.stale=!0}}function Gd(L,k,T,B,K,Q,le){L.emplaceBack(k?1:0,T?1:0,Q||0,le||0,B,K?1:0),L.emplaceBack(k?1:0,T?1:0,Q||0,le||0,B,K?1:0),L.emplaceBack(k?1:0,T?1:0,Q||0,le||0,B,K?1:0),L.emplaceBack(k?1:0,T?1:0,Q||0,le||0,B,K?1:0)}const wd=Math.pow(2,25),Ff=Math.pow(2,24),Bx=Math.pow(2,17),q1=Math.pow(2,16),wm=Math.pow(2,9),$k=Math.pow(2,8),V1=Math.pow(2,1);function H1(L){if(L.opacity===0&&!L.placed)return 0;if(L.opacity===1&&L.placed)return 4294967295;const k=L.placed?1:0,T=Math.floor(127*L.opacity);return T*wd+k*Ff+T*Bx+k*q1+T*wm+k*$k+T*V1+k}const lg=0;class zb{constructor(k){this._sortAcrossTiles=k.layout.get("symbol-z-order")!=="viewport-y"&&k.layout.get("symbol-sort-key").constantOr(1)!==void 0,this._currentTileIndex=0,this._currentPartIndex=0,this._seenCrossTileIDs=new Set,this._bucketParts=[]}continuePlacement(k,T,B,K,Q,le){const me=this._bucketParts;for(;this._currentTileIndexwe.sortKey-Me.sortKey));this._currentPartIndex!this.isFullPlacementRequested()&&this._fadeDuration!==0&&o.e.now()-le>2;for(;this._currentPlacementIndex>=0;){const we=T[k[this._currentPlacementIndex]],Me=this.placement.collisionIndex.transform.zoom;if(we.type==="symbol"&&we.visibility!=="none"&&(!we.minzoom||we.minzoom<=Me)&&(!we.maxzoom||we.maxzoom>Me)){const Re=we,Ze=Re.layout.get("symbol-z-elevate"),Qe=Re.layout.get("symbol-sort-key").constantOr(1)!==void 0,ht=Re.layout.get("symbol-z-order"),_t=ht==="viewport-y"||ht==="auto"&&!(ht!=="viewport-y"&&Qe),bt=Re.layout.get("text-allow-overlap")||Re.layout.get("icon-allow-overlap")||Re.layout.get("text-ignore-placement")||Re.layout.get("icon-ignore-placement"),Mt=_t&&bt,es=this._inProgressLayer=this._inProgressLayer||new zb(Re),Qt=o.m(we.source,we.scope);if(es.continuePlacement(Ze||Mt?K[Qt]:B[Qt],this.placement,this._showCollisionBoxes,we,me,Q))return;delete this._inProgressLayer}this._currentPlacementIndex--}this._forceFullPlacement=!1,this._done=!0}commit(k){return this._retiredCI=this.placement.prevPlacement?this.placement.prevPlacement.collisionIndex:null,this.placement.commit(k),this.placement}}const J2=512/o.a6/2;class Uk{constructor(k,T,B){this.tileID=k,this.bucketInstanceId=B,this.index=new o.dx(T.length,16,Int32Array),this.keys=[],this.crossTileIDs=[];const K=k.canonical.x*o.a6,Q=k.canonical.y*o.a6;for(let le=0;leMt-es);for(const Mt of bt){const es=this.crossTileIDs[Mt];if(this.keys[Mt]===Re&&!B.has(es)){B.add(es),Me.crossTileID=es;break}}}}}class by{constructor(){this.maxCrossTileID=0}generate(){return++this.maxCrossTileID}}class _y{constructor(){this.indexes={},this.usedCrossTileIDs={},this.lng=0}handleWrapJump(k){const T=Math.round((k-this.lng)/360);if(T!==0)for(const B in this.indexes){const K=this.indexes[B],Q={};for(const le in K){const me=K[le];me.tileID=me.tileID.unwrapTo(me.tileID.wrap+T),Q[me.tileID.key]=me}this.indexes[B]=Q}this.lng=k}addBucket(k,T,B){if(this.indexes[k.overscaledZ]&&this.indexes[k.overscaledZ][k.key]){if(this.indexes[k.overscaledZ][k.key].bucketInstanceId===T.bucketInstanceId)return!1;this.removeBucketCrossTileIDs(k.overscaledZ,this.indexes[k.overscaledZ][k.key])}for(let Q=0;Qk.overscaledZ)for(const me in le){const we=le[me];we.tileID.isChildOf(k)&&we.findMatches(T.symbolInstances,k,K)}else{const me=le[k.scaledTo(Number(Q)).key];me&&me.findMatches(T.symbolInstances,k,K)}}for(let Q=0;Q{T[B]=!0});for(const B in this.layerIndexes)T[B]||delete this.layerIndexes[B]}}function Bb(L,k){const T=(k.right-k.left)/2,B=Math.abs(L.x-(k.left+T));if(B>=L.radius+T)return!1;const K=(k.bottom-k.top)/2,Q=Math.abs(L.y-(k.top+K));if(Q>=L.radius+K)return!1;if(B{if(!$x(this._geometries[me],Q))return!1;const we=this._geometryData[me];return we===void 0||!B(we)};return(Q.kind==="box"?this._grid.hitTest(Q.left+K,Q.top+K,Q.right+K,Q.bottom+K,le):this._grid.hitTestCircle(Q.x+K,Q.y+K,Q.radius,le))?"intersects":"does-not-intersect"}insert(k,T){const B=this._padding;let K=!1;for(const Q of k){if(!$x(Q,this._workingArea))continue;const le=this._geometries.length;this._geometries.push(Q),this._geometryData.push(T),Q.kind==="box"?this._grid.insert(le,Q.left+B,Q.top+B,Q.right+B,Q.bottom+B):this._grid.insertCircle(le,Q.x+B,Q.y+B,Q.radius),K=!0}return K}}function lp(L){return 2*L.styleLayerId+L.symbolIdOrigin}function H_(L,k){const T=L.get(lp(k.symbolId));if(!T)return!1;const B=T.get(k.symbolId.symbolId);return B!==void 0&&B.has(k.variantIdx)}function Xy(L,k){const T=lp(k.symbolId);let B=L.get(T);B||(B=new Map,L.set(T,B));let K=B.get(k.symbolId.symbolId);K||(K=new Set,B.set(k.symbolId.symbolId,K)),K.add(k.variantIdx)}class qk{constructor(){this._runStarted=!1,this._grid=null,this._timestamp=0,this._symbols=[],this._ignoredSymbolVariantIds=new Map,this._onlyIfPlacedReferencedIds=new Map,this._placedVariantIds=new Map,this._placedSymbolIds=new Map,this._processingSource=null,this._variantProcessingStarted=!1}startPlacement(k,T,B){if(this._runStarted)throw new Error("Attempt to start a placement run before finishing the previous one");this._runStarted=!0,this._grid?this._grid.clearAndResize(T,B):this._grid=new G1(T,B,100,32),this._timestamp=k,this._symbols=[],this._ignoredSymbolVariantIds.clear(),this._onlyIfPlacedReferencedIds.clear(),this._placedVariantIds.clear(),this._placedSymbolIds.clear()}_hasPlacedSymbol(k){const T=this._placedSymbolIds.get(lp(k));return T!==void 0&&T.has(k.symbolId)}_addPlacedSymbol(k){const T=lp(k);let B=this._placedSymbolIds.get(T);B||(B=new Set,this._placedSymbolIds.set(T,B)),B.add(k.symbolId)}startSymbolSourceProcessing(k){if(!this._runStarted)throw new Error("Attempt to start symbol source processing outside of a placement run");if(this._processingSource)throw new Error("Attempt to start a placement symbol source processing before finishing the previous one");this._processingSource=k}startSymbolVariantProcessing(k,T,B){const K=this._processingSource;if(!K)throw new Error("Attempt to start a symbol variant processing outside of symbol source processing");if(this._variantProcessingStarted)throw new Error("Attempt to begin a symbol variant processing before finishing the previous one");this._symbols.push({priority:T,source:K,variantId:k,geometry:[],placementRules:B});const Q=B.collisionRules;Q&&(Q.symbolVariantToIgnoreCollisionWith&&Xy(this._ignoredSymbolVariantIds,Q.symbolVariantToIgnoreCollisionWith),Q.onlyIfPlaced&&Xy(this._onlyIfPlacedReferencedIds,Q.onlyIfPlaced)),this._variantProcessingStarted=!0}addGeometry(k){if(!this._variantProcessingStarted)throw new Error("Attempt to add geometry outside of symbol variant processing");this._symbols.at(-1).geometry.push(k)}finishVariantProcessing(){if(!this._variantProcessingStarted)throw new Error("Attempt to finish a symbol variant processing that was not started");this._variantProcessingStarted=!1;const k=this._symbols.at(-1);k.geometry.length===0&&(k.priority.symbolVariantVisibility===o.dy.VARIANT_VISIBLE&&k.source.hideSymbolVariant(k.variantId,this._timestamp),this._symbols.pop())}finishSourceProcessing(){this._processingSource=null}finishPlacementRun(){if(!this._runStarted)throw new Error("Attempt to finish a placement run that was not started");this._runStarted=!1;const k=this._grid,T=this._timestamp;this._symbols.sort((B,K)=>function(Q,le){return Q.placementSubgroupOrder-le.placementSubgroupOrder||Q.symbolPlacementPriority-le.symbolPlacementPriority||Q.symbolVariantVisibility-le.symbolVariantVisibility||Q.symbolPlacementType-le.symbolPlacementType||Q.styleLayerOrder-le.styleLayerOrder||Q.symbolDisplayOrder-le.symbolDisplayOrder}(K.priority,B.priority));for(const B of this._symbols){const K=B.priority.symbolVariantVisibility===o.dy.VARIANT_VISIBLE;let Q=!0;if(this._hasPlacedSymbol(B.variantId.symbolId))Q=!1;else if(B.placementRules.collisionRules){const le=B.placementRules.collisionRules.onlyIfPlaced;if(le&&!H_(this._placedVariantIds,le))Q=!1;else{const me=B.placementRules.collisionRules.symbolVariantToIgnoreCollisionWith;k.intersects(B.geometry,K?0:1,we=>{return me!==void 0&&(Me=we).variantIdx===(Re=me).variantIdx&&Me.symbolId.styleLayerId===Re.symbolId.styleLayerId&&Me.symbolId.symbolIdOrigin===Re.symbolId.symbolIdOrigin&&Me.symbolId.symbolId===Re.symbolId.symbolId;var Me,Re})!=="does-not-intersect"&&(Q=!1)}}if(Q&&B.placementRules.insertIntoCollisionGrid){const le=H_(this._ignoredSymbolVariantIds,B.variantId)?B.variantId:void 0;k.insert(B.geometry,le)||(Q=!1)}Q&&(this._addPlacedSymbol(B.variantId.symbolId),H_(this._onlyIfPlacedReferencedIds,B.variantId)&&Xy(this._placedVariantIds,B.variantId)),K!==Q&&(Q?B.source.showSymbolVariant(B.variantId,T):B.source.hideSymbolVariant(B.variantId,T))}}}class oj{constructor(){this._nextIdByLayer=new Map}allocateRange(k,T){const B=this._nextIdByLayer.get(k)||0;return this._nextIdByLayer.set(k,B+T),B}releaseLayer(k){this._nextIdByLayer.delete(k)}}class Qy extends o.E{constructor(k){super(),this.requestManager=k,this.models=Object.create(null),this.models[""]=Object.create(null),this.modelUris=Object.create(null),this.modelUris[""]=Object.create(null),this.modelByURL=Object.create(null),this.numModelsLoading=Object.create(null)}async loadModel(k,T){try{const B=await this.requestManager.transformRequest(T,o.R.Model);return this.modelByURL[T]?(await vr(),br.loadModel?await br.loadModel(B.url,k,T):null):null}catch(B){if(B.status===404)return null;this.fire(new o.f(new Error(`Could not load model ${k} from ${T}`,{cause:B})))}}load(k,T,B={forceReload:!1}){this.models[T]||(this.models[T]=Object.create(null));const K=Object.keys(k),Q=[],le=[];for(const me of K){const we=k[me];this.hasURLBeenRequested(we)&&!B.forceReload||(this.modelByURL[we]={modelId:me,scope:T},Q.push(this.loadModel(me,we)),le.push(me)),this.models[T][me]||(this.models[T][me]={model:null,numReferences:1})}this.numModelsLoading[T]=(this.numModelsLoading[T]||0)+le.length,Promise.allSettled(Q).then(me=>{for(let we=0;we{this.fire(new o.f(new Error(`Could not load models: ${me.message}`)))})}isLoaded(){for(const k in this.numModelsLoading)if(this.numModelsLoading[k]>0)return!1;return!0}hasModel(k,T,B={exactIdMatch:!1}){return!!(B.exactIdMatch?this.getModel(k,T):this.getModelByURL(this.modelUris[T][k]))}getModel(k,T){return this.models[T]||(this.models[T]=Object.create(null)),this.models[T][k]?this.models[T][k].model:void 0}getModelByURL(k){if(!k)return null;const T=this.modelByURL[k];return T?this.models[T.scope][T.modelId].model:null}hasModelBeenAdded(k,T){return this.models[T]&&this.models[T][k]!==void 0}getModelURIs(k){return this.modelUris[k]||Object.create(null)}addModel(k,T,B){this.models[B]||(this.models[B]=Object.create(null)),this.modelUris[B]||(this.modelUris[B]=Object.create(null));const K=this.requestManager.normalizeModelURL(T);if((this.hasModel(k,B,{exactIdMatch:!0})||this.hasModelBeenAdded(k,B))&&this.modelUris[B][k]===K)this.models[B][k].numReferences++;else if(this.hasURLBeenRequested(K)){const{scope:Q,modelId:le}=this.modelByURL[K];this.models[Q][le].numReferences++}else this.modelUris[B][k]=K,this.load({[k]:this.modelUris[B][k]},B)}addModelURLs(k,T){this.models[T]||(this.models[T]=Object.create(null)),this.modelUris[T]||(this.modelUris[T]=Object.create(null));const B=this.modelUris[T];for(const K of Object.keys(k))B[K]=this.requestManager.normalizeModelURL(k[K])}reloadModels(k){this.load(this.modelUris[k],k,{forceReload:!0})}addModelsFromBucket(k,T){this.models[T]||(this.models[T]=Object.create(null)),this.modelUris[T]||(this.modelUris[T]=Object.create(null));const B=Object.create(null);for(const K of k)this.hasModel(K,T,{exactIdMatch:!0})||this.hasURLBeenRequested(K)?this.models[T][K].numReferences++:this.modelUris[T][K]&&!this.hasURLBeenRequested(K)?B[K]=this.modelUris[T][K]:!this.hasURLBeenRequested(K)&&xs(K,!1)&&(this.modelUris[T][K]=this.requestManager.normalizeModelURL(K),B[K]=this.modelUris[T][K]);this.load(B,T)}hasURLBeenRequested(k){return this.modelByURL[k]!==void 0}removeModel(k,T,B=!1,K=!1){if(this.models[T]&&this.models[T][k]&&(this.models[T][k].numReferences--,this.models[T][k].numReferences===0||K)){const Q=this.modelUris[T][k];B||delete this.modelUris[T][k],delete this.modelByURL[Q];const le=this.models[T][k].model;if(!le)return;delete this.models[T][k],le.destroy()}}destroy(){for(const k of Object.keys(this.models))for(const T of Object.keys(this.models[k])){const B=this.models[k][T].model;delete this.models[k][T],B&&B.destroy()}this.models=Object.create(null),this.models[""]=Object.create(null),this.modelUris=Object.create(null),this.modelUris[""]=Object.create(null),this.modelByURL=Object.create(null),this.numModelsLoading=Object.create(null)}listModels(k){return this.models[k]||(this.models[k]=Object.create(null)),Object.keys(this.models[k])}upload(k,T){this.models[T]||(this.models[T]=Object.create(null));for(const B in this.models[T])this.models[T][B].model&&this.models[T][B].model.upload(k.context)}}const cp=["RENDER_SHADOWS","NORMAL_OFFSET"],W1=new Set(["symbol","circle"]),Ux=class lGe{constructor(){this._queue=[],this._needsBuild=!0,this._idleHandle=null}needsBuild(){return this._needsBuild}buildQueue(k,T,B){this._idleHandle!=null&&typeof cancelIdleCallback<"u"&&cancelIdleCallback(this._idleHandle),this._idleHandle=null,this._queue=[],this._needsBuild=!1;const K=!!B.fog,Q=B.hasTerrain(),le=!(!B.projection||B.projection.name!=="globe"),me=Q||le,we=!(!B.directionalLight||!B.directionalLight.shadowsEnabled()),Me=B.map&&B.map.painter,Re=!Me||!Me.context.extParallelShaderCompile,Ze=!!Me&&(Me.emissiveMode==="mrt-fallback"||Me.emissiveMode==="mrt-full-rgba"),Qe=(ht,_t=[],bt={})=>{this._queue.push({programId:ht,params:{...bt.params,defines:_t,overrideFog:!!bt.fog,overrideTerrain:!!bt.terrain,overrideGlobe:!!bt.globe,overrideRtt:!!bt.rtt,precompiled:!0}})};for(const ht of k){if(ht.visibility==="none")continue;const _t=ht.getProgramIds();if(_t)for(const bt of _t){if(W1.has(bt))continue;const Mt=ht.getDefaultProgramParams(bt,T.zoom,B._styleColorTheme.lut);if(!Mt)continue;const es=Me?Me.getShaderSource(bt):null,Qt=me&&(!es||es.usedDefines.has("RENDER_TO_TEXTURE"));let Lt=Mt.defines;if(Ze&&Qt&&(Lt=(Lt||[]).concat("USE_MRT1"),Me.emissiveMode==="mrt-full-rgba"&&(Lt=(Lt||[]).concat("USE_MRT1_RGBA"))),Re){Qe(bt,Mt.defines,{params:Mt}),Qt&&Qe(bt,Lt,{params:Mt,rtt:!0});continue}const ps=K&&(!es||es.usedDefines.has("FOG")),Hs=Q&&!ht.isDraped()&&(!es||es.usedDefines.has("TERRAIN")),Fs=le&&(!es||es.usedDefines.has("GLOBE")),nn=we&&ht.hasElevation()&&(!es||es.usedDefines.has("RENDER_SHADOWS"));for(const $s of nn?[!1,!0]:[!1]){const rn=$s?(Mt.defines||[]).concat(cp):Mt.defines||[];for(const _n of Hs?[!1,!0]:[!1])for(const Mn of Fs?[!1,!0]:[!1])for(const Yn of ps?[!1,!0]:[!1])Qe(bt,rn,{params:Mt,fog:Yn,terrain:_n,globe:Mn})}Qt&&Qe(bt,Lt,{params:Mt,rtt:!0})}}if(Qe("clippingMask"),Q)for(const ht of[!1,!0])Qe("terrainRaster",ht?["TERRAIN_VERTEX_MORPHING"]:[],{terrain:!0,fog:K});if(!Re){if(k.some(ht=>ht.type==="hillshade")&&Qe("hillshadePrepare"),we)for(const ht of[!1,!0])for(const _t of[!1,!0]){const bt=[];ht&&bt.push("RENDER_CUTOFF"),bt.push("RENDER_SHADOWS"),_t&&bt.push("NORMAL_OFFSET"),Qe("groundShadow",bt),K&&Qe("groundShadow",bt,{fog:!0})}if(le){for(const ht of[[],["TERRAIN_VERTEX_MORPHING"],["GLOBE_POLES"]])for(const _t of[!1,!0]){const bt=[...ht,"PROJECTION_GLOBE_VIEW"];_t&&bt.push("CUSTOM_ANTIALIASING"),Qe("globeRaster",bt,{terrain:Q,globe:!0,fog:K})}for(const ht of[!1,!0]){const _t=ht?["PROJECTION_GLOBE_VIEW","FOG"]:["FOG"];Qe("globeAtmosphere",_t,{fog:!0,terrain:Q,globe:ht}),Qe("globeAtmosphere",[..._t,"ALPHA_PASS"],{fog:!0,terrain:Q,globe:ht})}Qe("stars",[],{fog:K,terrain:Q,globe:!0})}}}_executeBatch(k,T,B){if(B.map&&B.map.isMoving())return void(this._idleHandle=o.e.requestIdleCallback(me=>this._executeBatch(me,T,B)));T.context.sweepPendingPrograms();const K=T.context.extParallelShaderCompile?lGe.DEADLINE_MARGIN_KHR_MS:lGe.DEADLINE_MARGIN_SYNC_MS;let Q=0;for(;this._queue.length>0;){const me=this._queue.shift();if(!me||me.programId in Cr&&(T.style=B,T._fogVisible=!!me.params.overrideFog,T.getOrCreateProgram(me.programId,me.params),Q++,k.timeRemaining()<=K))break}const le=this._queue.length===0||k.timeRemaining()>K;Q>0&&le&&T.context.gl.flush(),this._idleHandle=this._queue.length>0||T.context._pendingPrograms.size>0?o.e.requestIdleCallback(me=>this._executeBatch(me,T,B)):null}processQueue(k,T){this._queue.length!==0&&(this._idleHandle!=null&&typeof cancelIdleCallback<"u"&&cancelIdleCallback(this._idleHandle),this._idleHandle=o.e.requestIdleCallback(B=>this._executeBatch(B,k,T)))}reset(){this._idleHandle!=null&&typeof cancelIdleCallback<"u"&&cancelIdleCallback(this._idleHandle),this._queue=[],this._idleHandle=null,this._needsBuild=!0}};Ux.DEADLINE_MARGIN_KHR_MS=5,Ux.DEADLINE_MARGIN_SYNC_MS=25;let dp=Ux;const K1=o.s.colorTheme,T3=new o.ag({data:new o.ah(K1.data)});function Vk(L){if(!L.metadata||!L.metadata.content_area)return;const k=o.e.devicePixelRatio,{left:T,top:B,width:K,height:Q}=L.metadata.content_area,le=T*k,me=B*k;return[le,me,le+K*k,me+Q*k]}function KT(L){if(L)return L.map(([k,T])=>[k*o.e.devicePixelRatio,T*o.e.devicePixelRatio])}class qv{constructor(k,T,B){this.id=k,this.scope=T,this.sourceCache=B,this.pendingRequests=new Set,this.missingRequests=new Set}addPendingRequest(k){this.missingRequests.has(k.name)||this.pendingRequests.has(k.name)||this.pendingRequests.add(k.name)}hasPendingRequests(){return this.pendingRequests.size>0}resolvePendingRequests(){const k=new Map;if(!this.sourceCache.loaded())return k;const T=this.sourceCache.getVisibleCoordinates();if(T.length===0)return k;const B=this.sourceCache.getSource();if(B.type!=="raster-array")return k;const K=T.map(le=>this.sourceCache.getTile(le)),Q=B.getImages(K,Array.from(this.pendingRequests));for(const[le,me]of Q)k.set(o.I.from({name:le,iconsetId:this.id}),me),this.pendingRequests.delete(le);for(const le of this.pendingRequests)this.missingRequests.add(le);return this.pendingRequests.clear(),k}}const Vv=(L,k)=>cm(L,k&&k.filter(T=>T.identifier!=="source.canvas")),W0=new Set(["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"]),G_=new Set(["setCenter","setZoom","setBearing","setPitch"]),cg=new Set(["background","sky","slot","custom","placement-group"]),K0={version:8,layers:[],sources:{}},Jy={duration:300,delay:0};class up extends o.E{constructor(k,T={}){super(),this.map=k,this.scope=T.scope||"",this.globalId=null,this.fragments=[],this.importDepth=T.importDepth||0,this.importsCache=T.importsCache||new Map,this.resolvedImports=T.resolvedImports||new Set,this.transition={...Jy},this._buildingIndex=new cu(this),this.crossTileSymbolIndex=new ij,this.globalPlacement=null,this.symbolIdRangeAllocator=new oj,this._groupOrders=null,this._groupOrdersVersion=-1,this._mergedOrder=[],this._mergedOrderVersion=0,this._drapedFirstOrder=[],this._mergedLayers=Object.create(null),this._mergedIndoor={},this._indoorEnabled=!1,this._mergedSourceCaches={},this._mergedOtherSourceCaches=Object.create(null),this._mergedSymbolSourceCaches=Object.create(null),this._mergedFillExtrusionSourceCaches=Object.create(null),this._mergedHdRoadCoverageSourceCaches=Object.create(null),this._hdCoverage=null,this._hdElevation=null,this._crossSourceElevationActive=!1,this._clipLayerPresent=!1,this._hasAppearances=!1,this._has3DLayers=!1,this._hasCircleLayers=!1,this._hasSymbolLayers=!1,this._importedAsBasemap=!1,this._changes=T.styleChanges||new O,this._hasDataDrivenEmissive=!1,this.indoorManager=null,this.dispatcher=T.dispatcher?T.dispatcher:new Ns(du(),this);const B={referrer:o.dA(),config:o.dT()};if(this.map.painter&&this.map.painter.context){const Q=this.map.painter.context.maxUniformBufferBindings,le=Math.floor(this.map.painter.context.maxUniformBlockSize/4);B.contextOptions={maxBindingPoints:Q,maxUniformBlockSizeDwords:le}}this.isRootStyle()&&this.dispatcher.broadcast("setGlobalParams",B),T.imageManager?this.imageManager=T.imageManager:(this.imageManager=new Ft(this.map._spriteFormat),this.imageManager.setEventedParent(this)),this.imageManager.addScope(this.scope),this.glyphManager=T.glyphManager?T.glyphManager:new o.dB(k._requestManager,T.localFontFamily?o.dC.all:T.localIdeographFontFamily?o.dC.ideographs:o.dC.none,T.localFontFamily||T.localIdeographFontFamily,T.fontstackCompositing),T.modelManager?this.modelManager=T.modelManager:(this.modelManager=new Qy(k._requestManager),this.modelManager.setEventedParent(this)),this._layers=Object.create(null),this._sourceCaches={},this._otherSourceCaches=Object.create(null),this._symbolSourceCaches=Object.create(null),this._fillExtrusionSourceCaches=Object.create(null),this._hdCoverage=null,this._hdElevation=null,this._crossSourceElevationActive=!1,this._loaded=!1,this._drapingLoaded=void 0,this._initialBroadcastDone=!1,this._programPrecompiler=this.map._precompilePrograms&&this.isRootStyle()?new dp:null,this._availableImages=[],this._availableModels={},this._order=[],this._markersNeedUpdate=!1,this.options=T.configOptions?T.configOptions:new Map,this._layerExpressionDependencies=T.layerExpressionDependencies?T.layerExpressionDependencies:new Map,this._config=T.config,this._styleColorTheme={lut:null,lutLoading:!1,lutLoadingCorrelationID:0,colorTheme:null,colorThemeOverride:T.colorThemeOverride},this._styleColorThemeForScope={},this._initialConfig=T.initialConfig;const K=this;this._rtlTextPluginCallback=up.registerForPluginStateChange(Q=>{K.dispatcher.send("syncRTLPluginState",{pluginStatus:Q.pluginStatus,pluginURL:Q.pluginURL}).then(le=>{if(o.dD(null),le.every(me=>me))for(const me in K._sourceCaches){const we=K._sourceCaches[me],Me=we.getSource().type;Me!=="vector"&&Me!=="geojson"||we.reload()}}).catch(le=>{o.dD(le)})}),this.on("data",Q=>{if(Q.dataType!=="source"||Q.sourceDataType!=="metadata")return;const le=this.getOwnSource(Q.sourceId);if(le&&le.vectorLayerIds)for(const me in this._layers){const we=this._layers[me];we.source===le.id&&this._validateLayer(we)}})}load(k){return k?(typeof k=="string"?this.loadURL(k):this.loadJSON(k),this):this}_getGlobalId(k){if(!k)return null;if(typeof k=="string"){if(o.cG(k))return k;const T=o.dE(k);if(!T.startsWith("http"))try{return new URL(T,location.href).toString()}catch{return T}return T}return`json://${o.dF(JSON.stringify(k))}`}_diffStyle(k,T,B){this.globalId=this._getGlobalId(k),Ih();const K=(Q,le)=>{try{le(null,this.setState(Q,B))}catch(me){le(me,!1)}};if(typeof k=="string"){const Q=this.map._requestManager.normalizeStyleURL(k),le=new AbortController;this._request={cancel:()=>le.abort()},(async()=>{const me=await this.map._requestManager.transformRequest(Q,o.R.Style,le.signal),{data:we}=await o.g(me,le.signal);this._request=null,K(we,T)})().catch(me=>{this._request=null,le.signal.aborted||this.fire(new o.f(me))})}else typeof k=="object"&&K(k,T)}loadURL(k,T={}){this.fire(new o.h("dataloading",{dataType:"style"}));const B=typeof T.validate=="boolean"?T.validate:!o.cG(k);B&&Ih(),this.globalId=this._getGlobalId(k),k=this.map._requestManager.normalizeStyleURL(k,T.accessToken),this.resolvedImports.add(k);const K=this.importsCache.get(k);if(K)return void this._load(K,B);const Q=new AbortController;this._request={cancel:()=>Q.abort()},(async()=>{const le=await this.map._requestManager.transformRequest(k,o.R.Style,Q.signal),{data:me}=await o.g(le,Q.signal);this._request=null,this.importsCache.set(k,me),this._load(me,B)})().catch(le=>{this._request=null,Q.signal.aborted||this.fire(new o.f(le))})}loadJSON(k,T={}){this.fire(new o.h("dataloading",{dataType:"style"}));const B=T.validate!==!1;B&&Ih(),this.globalId=this._getGlobalId(k),this._request=o.e.frame(()=>{this._request=null,this._load(k,B)})}loadEmpty(){this.fire(new o.h("dataloading",{dataType:"style"})),this._load(K0,!1)}_loadImports(k,T,B){if(this.importDepth>=4)return o.w("Style doesn't support nesting deeper than 5"),Promise.resolve();const K=[];for(const Q of k){const le=this._createFragmentStyle(Q),me=new Promise(Re=>{le.once("style.import.load",Re),le.once("error",Re)}).then(()=>{this.mergeAll(),this.fire(new o.h("data",{dataType:"style"}))});if(K.push(me),this.resolvedImports.has(Q.url)){le.loadEmpty();continue}const we=Q.data||this.importsCache.get(Q.url);we?(Q.data?(le.fire(new o.h("dataloading",{dataType:"style"})),le.globalId=le._getGlobalId(we),T&&Ih(),queueMicrotask(()=>{le._load(we,T)})):le.loadJSON(we,{validate:T}),this._isInternalStyle(we)&&(le.globalId=null)):Q.url?le.loadURL(Q.url,{validate:T}):le.loadEmpty();const Me={style:le,id:Q.id,config:Q.config};if(B){const Re=this.fragments.findIndex(({id:Ze})=>Ze===B);this.fragments=this.fragments.slice(0,Re).concat(Me).concat(this.fragments.slice(Re))}else this.fragments.push(Me)}return Promise.allSettled(K)}getImportGlobalIds(k=this,T=new Set){for(const B of k.fragments)B.style.globalId&&T.add(B.style.globalId),this.getImportGlobalIds(B.style,T);return[...T.values()]}_createFragmentStyle(k){const T=this.scope?o.m(k.id,this.scope):k.id;let B;const K=this._initialConfig&&this._initialConfig[T];(k.config||K)&&(B={...k.config,...K});const Q=new up(this.map,{scope:T,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:B,configOptions:this.options,colorThemeOverride:k["color-theme"],layerExpressionDependencies:this._layerExpressionDependencies});return Q.setEventedParent(this.map,{style:Q}),Q}_reloadImports(k=!1){this.mergeAll(),this._updateMapProjection(),k||this.updateConfigDependencies(),this._updateLayers(this._dependentLayerIds(T=>T.isIndoorDependent)),this.map._triggerCameraUpdate(this.camera),(!k||this.isRootStyle()||this.map.style._initialBroadcastDone)&&(k&&this.isRootStyle()?(this.forEachFragmentStyle(T=>{this.dispatcher.broadcast("setLayers",{layers:T._serializeLayers(T._order),scope:T.scope,options:T.options})}),this._initialBroadcastDone=!0):this.dispatcher.broadcast("setLayers",{layers:this._serializeLayers(this._order),scope:this.scope,options:this.options}))}_isInternalStyle(k){return this.isRootStyle()&&(k.fragment||!!k.schema&&k.fragment!==!1)}async _load(k,T){if(this._isInternalStyle(k)){const Q={id:"basemap",data:k,url:""},le={...K0,imports:[Q],...k.center?{center:k.center}:{},...k.bearing?{bearing:k.bearing}:{},...k.pitch?{pitch:k.pitch}:{},...k.zoom?{zoom:k.zoom}:{},...k.light?{light:k.light}:{}};return this._importedAsBasemap=!0,void this._load(le,T)}if(this.updateConfig(this._config,k.schema),T&&(await Ih(),!this.dispatcher.actors.length||Vv(this,_s(k))))return;this._loaded=!0;for(const Q in k.sources)this.addSource(Q,k.sources[Q],{validate:!1,isInitialLoad:!0});this.stylesheet=o.dG(k);const B=()=>{if(k.iconsets)for(const Me in k.iconsets)this.addIconset(Me,k.iconsets[Me]);k.sprite?this._loadIconset(k.sprite):(this.imageManager.setLoaded(!0,this.scope),this.dispatcher.broadcast("spriteLoaded",{scope:this.scope})),!this.glyphManager.url&&k.glyphs&&this.glyphManager.setURL(k.glyphs);const Q=op(this.stylesheet.layers);if(this._order=Q.map(Me=>Me.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 Me=this.stylesheet.lights[0];this.light=new Wh(Me.properties,Me.id)}else this.setLights(this.stylesheet.lights);this.light||(this.light=new Wh(this.stylesheet.light)),this._layers=Object.create(null);let le=!1;for(const Me of Q){const Re=o.dM(Me,this.scope,this._styleColorTheme.lut,this.options);this._layerExpressionDependencies.set(Re.fqid,new U(Re)),this._hasAppearances=this._hasAppearances||Re.getAppearances().length!==0,Re.setEventedParent(this,{layer:{id:Re.id}}),this._layers[Re.id]=Re,this._updateHdCoverageSourceCache(Re)&&(le=!0);const Ze=this.getOwnLayerSourceCache(Re),Qe=!!this.directionalLight&&this.directionalLight.shadowsEnabled();Ze&&Re.canCastShadows()&&Qe&&(Ze.castsShadows=!0)}if(le&&hm().then(()=>{if(!this.map)return;for(const Re in this._layers)this._updateHdCoverageSourceCache(this._layers[Re]);this.map.style.mergeAll();const Me=this.map.transform;for(const Re in this.map.style._mergedHdRoadCoverageSourceCaches){const Ze=this.map.style._mergedHdRoadCoverageSourceCaches[Re];Ze.used=!0,Me&&Ze.update(Me)}this.map._update()}),this.glyphManager.url){const Me=new Set;for(const Re in this._layers){const Ze=this._layers[Re];if(Ze.type==="symbol"&&Ze.layout){const Qe=Ze.layout.get("text-font");Qe&&Qe.value&&Qe.value.kind==="constant"&&Me.add(Qe.value.value.join(","))}}for(const Re of Me)this.glyphManager.prefetchRange(Re,0)}this.stylesheet.featuresets&&this.setFeaturesetSelectors(this.stylesheet.featuresets),this.stylesheet.models&&this.addModelURLs(this.stylesheet.models);const me=this.stylesheet.terrain;me&&(this.checkCanvasFingerprintNoise(),this.disableElevatedTerrain||this.terrainSetForDrapingOnly()||(this._startLiteLoad(),this._createTerrain(me,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.h("data",{dataType:"style"}));const we=this.isRootStyle();k.imports?this._loadImports(k.imports,T).then(()=>{this._reloadImports(!0),this.fire(new o.h(we?"style.load":"style.import.load"))}).catch(Me=>{this.fire(new o.f(new Error("Failed to load imports",Me))),this.fire(new o.h(we?"style.load":"style.import.load"))}):(this._reloadImports(!0),this.fire(new o.h(we?"style.load":"style.import.load")))};this._styleColorTheme.colorTheme=this.stylesheet["color-theme"];const K=this._styleColorTheme.colorThemeOverride?this._styleColorTheme.colorThemeOverride:this._styleColorTheme.colorTheme;if(K){const Q=this._evaluateColorThemeData(K);this._loadColorTheme(Q).then(()=>{B()}).catch(le=>{o.w(`Couldn't load color theme from the stylesheet: ${le}`),B()})}else this._styleColorTheme.lut=null,B()}isRootStyle(){return this.importDepth===0}hasAppearances(){return this._hasAppearances||this.fragments.some(k=>k.style.hasAppearances())}mergeAll(){let k,T,B,K,Q,le,me,we,Me,Re;const Ze={};this.terrain&&this.terrain.scope!==this.scope&&delete this.terrain,this.forEachFragmentStyle(Qe=>{if(Qe.stylesheet){if(Qe.disableElevatedTerrain&&(this.disableElevatedTerrain=!0),Qe.light!=null&&(k=Qe.light),Qe.stylesheet.lights)for(const ht of Qe.stylesheet.lights)ht.type==="ambient"&&Qe.ambientLight!=null&&(T=Qe.ambientLight),ht.type==="directional"&&Qe.directionalLight!=null&&(B=Qe.directionalLight);K=this._prioritizeTerrain(K,Qe.terrain,Qe.stylesheet.terrain),Qe.stylesheet.fog&&Qe.fog!=null&&(Q=Qe.fog),Qe.stylesheet.snow&&Qe.snow!=null&&(le=Qe.snow),Qe.stylesheet.rain&&Qe.rain!=null&&(me=Qe.rain),Qe.stylesheet.camera!=null&&(Re=Qe.stylesheet.camera),Qe.stylesheet.projection!=null&&(we=Qe.stylesheet.projection),Qe.stylesheet.transition!=null&&(Me=Qe.stylesheet.transition),Ze[Qe.scope]=Qe._styleColorTheme}}),this.light=k,this.ambientLight=T,this.directionalLight=B,this.fog=Q,this.snow=le,this.rain=me,this._styleColorThemeForScope=Ze,K===null?delete this.terrain:this.terrain=K,this.camera=Re||{"camera-projection":"perspective"},this.projection=we||{name:"mercator"},this.transition={...Jy,...Me},this.mergeSources(),this.mergeLayers(),this.mergeIndoor(),this._programPrecompiler&&this._programPrecompiler.reset()}forEachFragmentStyle(k){const T=B=>{for(const K of B.fragments)T(K.style);k(B)};T(this)}_prioritizeTerrain(k,T,B){const K=k&&k.drapeRenderMode===0;return B===null?T&&T.drapeRenderMode===0?T:K?k:null:T!=null&&(!k||K||T&&T.drapeRenderMode===1)?T:k}mergeTerrain(){let k;this.terrain&&this.terrain.scope!==this.scope&&delete this.terrain,this.forEachFragmentStyle(T=>{k=this._prioritizeTerrain(k,T.terrain,T.stylesheet.terrain)}),k===null?delete this.terrain:this.terrain=k,this._programPrecompiler&&this._programPrecompiler.reset()}mergeProjection(){let k;this.forEachFragmentStyle(T=>{T.stylesheet.projection!=null&&(k=T.stylesheet.projection)}),this.projection=k||{name:"mercator"},this._programPrecompiler&&this._programPrecompiler.reset()}mergeSources(){const k={},T=Object.create(null),B=Object.create(null),K=Object.create(null),Q=Object.create(null);this.forEachFragmentStyle(le=>{for(const me in le._sourceCaches){const we=o.m(me,le.scope);k[we]=le._sourceCaches[me]}for(const me in le._otherSourceCaches){const we=o.m(me,le.scope);T[we]=le._otherSourceCaches[me]}for(const me in le._symbolSourceCaches){const we=o.m(me,le.scope);B[we]=le._symbolSourceCaches[me]}for(const me in le._fillExtrusionSourceCaches){const we=o.m(me,le.scope);K[we]=le._fillExtrusionSourceCaches[me]}if(le._hdCoverage){const me=le._hdCoverage.coverageSourceCaches;for(const we in me)Q[o.m(we,le.scope)]=me[we]}}),this._mergedSourceCaches=k,this._mergedOtherSourceCaches=T,this._mergedSymbolSourceCaches=B,this._mergedFillExtrusionSourceCaches=K,this._mergedHdRoadCoverageSourceCaches=Q,Object.keys(Q).length>0&&!this._hdCoverage&&Ui.HdCoverageState&&(this._hdCoverage=new Ui.HdCoverageState),Ui.updateCrossSourceElevationGate&&Ui.updateCrossSourceElevationGate(this)}mergeIndoor(){this._mergedIndoor={},this.forEachFragmentStyle(k=>{if(k.stylesheet&&k.stylesheet.indoor)for(const T of Object.values(k.stylesheet.indoor)){const B=T,K=o.m(B.sourceId,k.scope);this._mergedIndoor[K]=new Set(B.sourceLayers||[])}}),this._updateIndoorEnabled()}_updateIndoorEnabled(){const k=this._indoorEnabled;if(this._indoorEnabled=!1,Object.keys(this._mergedIndoor).length>0)for(const T of this._mergedOrder){const B=this._mergedLayers[T];if(B.visibility!=="none"&&this._mergedIndoor[o.m(B.source,B.scope)]){this._indoorEnabled=!0;break}}!this._indoorEnabled||k||this.indoorManager||hm().then(()=>{this._initIndoorManager()})}_initIndoorManager(){if(!this.indoorManager&&Ui.IndoorManager&&this.isRootStyle()&&Object.keys(this._mergedIndoor).length!==0&&(this.indoorManager=new Ui.IndoorManager(this,this._loaded),this._loaded))for(const k of Object.keys(this._mergedIndoor)){const T=this._mergedSourceCaches[k]||this._mergedOtherSourceCaches[k];T&&T.reload()}}mergeLayers(){const k={},T=[],B=Object.create(null);this._mergedSlots=[],this._has3DLayers=!1,this._hasCircleLayers=!1,this._hasSymbolLayers=!1,this.forEachFragmentStyle(le=>{for(const me of le._order){const we=le._layers[me];if(we.type==="slot"){const Me=o.dH(me);if(k[Me])continue;k[Me]=[]}we.slot&&k[we.slot]?k[we.slot].push(we):T.push(we)}}),this._mergedOrder=[];let K=-1;const Q=(le=[])=>{for(const me of le)if(me.type==="slot"){const we=o.dH(me.id);k[we]&&Q(k[we]),this._mergedSlots.push(we)}else{const we=o.m(me.id,me.scope);this._mergedOrder.push(we),B[we]=me,me.is3D(!!this.terrain)&&(this._has3DLayers=!0,K=this._mergedOrder.length-1),me.type==="circle"&&(this._hasCircleLayers=!0),me.type==="symbol"&&(this._hasSymbolLayers=!0),me.type==="clip"&&(this._clipLayerPresent=!0)}};if(Q(T),this._has3DLayers){const le={};for(let me=0;mele[me]-le[we])}this._mergedLayers=B,this._mergedOrderVersion++,this.updateDrapeFirstLayers(),this._buildingIndex.processLayersChanged(),this._updateDataDrivenEmissiveStrength()}terrainSetForDrapingOnly(){return!!this.terrain&&this.terrain.drapeRenderMode===0}getCamera(){return this.stylesheet.camera}setCamera(k){return this.stylesheet.camera={...this.stylesheet.camera,...k},this.camera=this.stylesheet.camera,this}_evaluateColorThemeData(k){return k.data?function(T,B,K){const Q={...B};for(const me of Object.keys(K1))Q[me]===void 0&&(Q[me]=K1[me].default);const le=new o.af(T3,T,new Map(K));return le.setTransitionOrValue(Q,K),le.untransitioned().possiblyEvaluate(new o.aj(0,{worldview:void 0}))}(this.scope,k,this.options).get("data"):null}_loadColorTheme(k){this._styleColorTheme.lutLoading=!0,this._styleColorTheme.lutLoadingCorrelationID+=1;const T=this._styleColorTheme.lutLoadingCorrelationID;return new Promise((B,K)=>{const Q="data:image/png;base64,";if(!k||k.length===0)return this._styleColorTheme.lut=null,this._styleColorTheme.lutLoading=!1,void B();let le=k;le.startsWith(Q)||(le=Q+le);const me=o.I.from("mapbox-reserved-lut"),we=new Image;we.src=le,we.onerror=()=>{this._styleColorTheme.lutLoading=!1,K(new Error("Failed to load image data"))},we.onload=()=>{if(this._styleColorTheme.lutLoadingCorrelationID!==T)return void B();this._styleColorTheme.lutLoading=!1;const{width:Me,height:Re,data:Ze}=o.e.getImageData(we);if(Re>32)return void K(new Error("The height of the image must be less than or equal to 32 pixels."));if(Me!==Re*Re)return void K(new Error("The width of the image must be equal to the height squared."));this.getImage(me)&&this.removeImage(me),this.addImage(me,{data:new o.b({width:Me,height:Re},Ze),pixelRatio:1,sdf:!1,usvg:!1,version:0});const Qe=this.imageManager.getImage(me,this.scope);Qe?(this._styleColorTheme.lut={image:Qe.data,data:k},B()):K(new Error("Missing LUT image."))}})}getLut(k){const T=this._styleColorThemeForScope[k];return T?T.lut:null}setProjection(k){k?this.stylesheet.projection=k:delete this.stylesheet.projection,this.mergeProjection(),this._updateMapProjection()}applyProjectionUpdate(){this.map.transform.projection.requiresDraping&&this._startLiteLoad(),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(k){const T=new AbortController;this._spriteRequest=T,function(B,K,Q,le){let me,we,Me;const Re=o.e.devicePixelRatio>1?"@2x":"";function Ze(Qe){Me||Qe&&Q.aborted||(Qe&&(Me=Qe),function(){if(Me)le(Me);else if(me&&we){const ht=o.e.getImageData(we),_t={};for(const bt in me){const{width:Mt,height:es,x:Qt,y:Lt,sdf:ps,pixelRatio:Hs,stretchX:Fs,stretchY:nn,content:$s}=me[bt],rn=new o.b({width:Mt,height:es});o.b.copy(ht,rn,{x:Qt,y:Lt},{x:0,y:0},{width:Mt,height:es},null),_t[bt]={data:rn,pixelRatio:Hs!==void 0?Hs:1,sdf:ps!==void 0&&ps,stretchX:Fs,stretchY:nn,content:$s,usvg:!1,version:0}}le(null,_t)}}())}(async function(){const Qe=await K.transformRequest(K.normalizeSpriteURL(B,Re,".json"),o.R.SpriteJSON,Q),{data:ht}=await o.g(Qe,Q);Me||(me=ht)})().then(()=>Ze(void 0),Qe=>Ze(Qe)),async function(){const Qe=await K.transformRequest(K.normalizeSpriteURL(B,Re,".png"),o.R.SpriteImage,Q),{data:ht}=await o.a(Qe,Q);Me||(we=ht)}().then(()=>Ze(void 0),Qe=>Ze(Qe))}(k,this.map._requestManager,T.signal,(B,K)=>{if(this._spriteRequest=null,B)this.dispatcher.broadcast("spriteLoaded",{scope:this.scope}),this.fire(new o.f(B));else if(K){const Q=new Map;for(const le in K)Q.set(o.I.from(le),K[le]);this.addImages(Q,!0)}this.imageManager.setLoaded(!0,this.scope),this.fire(new o.h("data",{dataType:"style"}))})}addIconset(k,T){if(T.type==="sprite")return void this._loadSprite(T.url);const B=this.getOwnSourceCache(T.source);if(!B)return void this.fire(new o.f(new Error(`Source "${T.source}" as specified by iconset "${k}" does not exist and cannot be used as an iconset source`)));if(B.getSource().type!=="raster-array")return void this.fire(new o.f(new Error(`Source "${T.source}" as specified by iconset "${k}" is not a "raster-array" source and cannot be used as an iconset source`)));const K=new qv(k,this.scope,B);this.imageManager.addImageProvider(K,this.scope)}removeIconset(k){this.imageManager.removeImageProvider(k,this.scope)}_loadIconset(k){if(!o.cG(k)&&this.map._spriteFormat!=="icon_set"||this.map._spriteFormat==="raster")return void this._loadSprite(k);const T=this.map._spriteFormat==="auto",B=new AbortController;this._spriteRequest=B,async function(K,Q,le,me){try{const we=await Q.transformRequest(Q.normalizeIconsetURL(K),o.R.Iconset,le),{data:Me}=await o.d0(we,le),Re={},Ze=function(Qe){const ht={icons:[]};let _t;for(;_t=Qe.nextField(void 0);)_t===1&&ht.icons.push(Y(Qe,Qe.readVarint()+Qe.pos));return ht}(new o.c$(Me));for(const Qe of Ze.icons){const ht={version:1,pixelRatio:o.e.devicePixelRatio,content:Vk(Qe),stretchX:Qe.metadata?KT(Qe.metadata.stretch_x_areas):void 0,stretchY:Qe.metadata?KT(Qe.metadata.stretch_y_areas):void 0,sdf:!1,usvg:!0,icon:Qe};Re[Qe.name]=ht}me(null,Re)}catch(we){le.aborted||me(we)}}(k,this.map._requestManager,B.signal,(K,Q)=>{if(this._spriteRequest=null,K)T?this._loadSprite(k):(this.dispatcher.broadcast("spriteLoaded",{scope:this.scope}),this.fire(new o.f(K)));else if(Q){const le=new Map;for(const me in Q)le.set(o.I.from(me),Q[me]);this.addImages(le,!0)}this.imageManager.setLoaded(!0,this.scope),this.fire(new o.h("data",{dataType:"style"}))})}_validateLayer(k){const T=this.getOwnSource(k.source);if(!T)return;const B=k.sourceLayer;B&&(T.type==="geojson"||T.vectorLayerIds&&!T.vectorLayerIds.includes(B))&&this.fire(new o.f(new Error(`Source layer "${B}" does not exist on source "${T.id}" as specified by style layer "${k.id}"`)))}loaded(){if(!this._loaded||Object.keys(this._changes.getUpdatedSourceCaches()).length)return!1;for(const k in this._sourceCaches)if(!this._sourceCaches[k].loaded())return!1;if(!this.imageManager.isLoaded()||this.imageManager.hasPatternsInFlight()||!this.modelManager.isLoaded()||this._styleColorTheme.lutLoading||this._drapingLoaded===!1)return!1;for(const{style:k}of this.fragments)if(!k.loaded())return!1;return!0}_serializeImports(){if(this.stylesheet.imports)return this.stylesheet.imports.map((k,T)=>{const B=this.fragments[T];return B&&B.style&&(k.data=B.style.serialize()),k})}_serializeSources(){const k={};for(const T in this._sourceCaches){const B=this._sourceCaches[T].getSource();k[B.id]||(k[B.id]=B.serialize())}return k}_serializeLayers(k){const T=[];for(const B of k){const K=this._layers[B];K&&K.type!=="custom"&&T.push(K.serialize())}return T}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 k in this._sourceCaches)if(this._sourceCaches[k].hasTransition())return!0;for(const k in this._layers)if(this._layers[k].hasTransition())return!0;return!1}_updateDataDrivenEmissiveStrength(){for(const k in this._mergedLayers){const T=this._mergedLayers[k];if(T._transitionablePaint&&T._transitionablePaint._values){const B=T._transitionablePaint._values["line-emissive-strength"];if(B&&B.value&&B.value.isDataDriven())return void(this._hasDataDrivenEmissive=!0)}}this._hasDataDrivenEmissive=!1}hasDataDrivenEmissiveStrength(){return this._hasDataDrivenEmissive}get order(){return this.terrain?this._drapedFirstOrder:this._mergedOrder}_getOrder(k){return k?this.order:this._mergedOrder}isLayerDraped(k){return!!this.terrain&&k.isDraped(this.getLayerSourceCache(k))}_checkLoaded(){if(!this._loaded)throw new Error("Style is not done loading")}_checkLayer(k){const T=this.getOwnLayer(k);if(T)return T;this.fire(new o.f(new Error(`The layer '${k}' does not exist in the map's style.`)))}_checkSource(k){const T=this.getOwnSource(k);if(T)return T;this.fire(new o.f(new Error(`The source '${k}' does not exist in the map's style.`)))}_resolveLayerFragment(k){const T=this.getLayer(k);if(!T)return void this.fire(new o.f(new Error(`The layer '${k}' does not exist in the map's style.`)));const B=this.getFragmentStyle(T.scope);return B?{layer:T,fragment:B}:void 0}handleIdle(){const k=this.map.painter;k&&(k.context.sweepPendingPrograms(),this._programPrecompiler&&this._programPrecompiler.processQueue(k,this))}handleContextLost(){this._programPrecompiler&&this._programPrecompiler.reset()}update(k){if(!this._loaded)return;this.ambientLight&&this.ambientLight.recalculate(k),this.directionalLight&&this.directionalLight.recalculate(k);const T=this.calculateLightsBrightness();k.brightness=T||0;let B=!1;T!==this._brightness&&(this._brightness=T,B=!0),k.worldview!==this._worldview&&(this._worldview=k.worldview,B=!0),B&&this.dispatcher.broadcast("upsertRenderParams",{brightness:this._brightness,worldview:this._worldview});const K=this._changes.isDirty();let Q=!1;if(this._changes.isDirty()){const Me=this._changes.getLayerUpdatesByScope();for(const Re in Me){const{updatedIds:Ze,removedIds:Qe}=Me[Re];(Ze||Qe)&&(this._updateWorkerLayers(Re,Ze,Qe),Q=!0)}this.updateSourceCaches(),this._updateTilesForChangedImages(),this.updateLayers(k),this.light&&this.light.updateTransitions(k),this.ambientLight&&this.ambientLight.updateTransitions(k),this.directionalLight&&this.directionalLight.updateTransitions(k),this.fog&&this.fog.updateTransitions(k),this.snow&&this.snow.updateTransitions(k),this.rain&&this.rain.updateTransitions(k),this._changes.reset()}const le={};for(const Me in this._mergedSourceCaches){const Re=this._mergedSourceCaches[Me];le[Me]=Re.used,Re.used=!1,Re.tileCoverLift=0}const me={};for(const Me of this._mergedOrder){const Re=this._mergedLayers[Me];if((Re.visibility!=="none"||Re.hasTransition())&&Re.recalculate(k,this._availableImages),!Re.isHidden(k.zoom)){Re.mayUse("HD")&&(Re.prepare(),hm()),Re.mayUse("Standard")&&(Re.prepare(),vr()),Re.mayUse("Lite")&&(this.checkCanvasFingerprintNoise(),this.disableElevatedTerrain||this._startLiteLoad());const Ze=this.getLayerSourceCache(Re);Ze&&(Ze.used=!0,Ze.tileCoverLift=Math.max(Ze.tileCoverLift,Re.tileCoverLift()))}if(Re.source){const Ze=o.m(Re.source,Re.scope),Qe=this._mergedHdRoadCoverageSourceCaches[Ze];Qe&&!Qe.used&&(Qe.used=!0)}if(Re.type==="fill-extrusion"){const Ze=o.m(Re.source,Re.scope);if(Ze in this._mergedFillExtrusionSourceCaches){const Qe=Re.layout&&Re.layout.get("source-max-zoom");if(Qe!=null){const ht=me[Ze];me[Ze]=ht==null?Qe:Math.min(ht,Qe)}}}}if(this._programPrecompiler&&this._programPrecompiler.needsBuild()){const Me=this._mergedOrder.map(Re=>this._mergedLayers[Re]);this._programPrecompiler.buildQueue(Me,k,this)}for(const Me in this._mergedFillExtrusionSourceCaches)this._mergedFillExtrusionSourceCaches[Me].setMaxzoomOverride(me[Me]??null);this.terrain&&Q&&this.mergeLayers();const we=this.imageManager.getPendingImageProviders();for(const Me of we)Me.sourceCache.used=!0;for(const Me in le){const Re=this._mergedSourceCaches[Me];le[Me]!==Re.used&&Re.getSource().fire(new o.h("data",{sourceDataType:"visibility",dataType:"source",sourceId:Re.getSource().id}))}this.light&&this.light.recalculate(k),this.terrain&&this.terrain.recalculate(k),this.fog&&this.fog.recalculate(k),this.snow&&this.snow.recalculate(k),this.rain&&this.rain.recalculate(k),this.z=k.zoom,this._markersNeedUpdate&&(this._updateMarkersOpacity(),this._markersNeedUpdate=!1),this.imageManager.clearUpdatedImages(this.scope),K&&this.fire(new o.h("data",{dataType:"style"}))}updateImageProviders(){const k=this.imageManager.getPendingImageProviders();for(const T of k){const B=T.resolvePendingRequests(),K=this.getFragmentStyle(T.scope);K&&K.addImages(B)}}_updateTilesForChangedImages(){const k={};for(const T in this._mergedSourceCaches){const B=this._mergedSourceCaches[T].getSource().scope;k[B]=k[B]||this._changes.getUpdatedImages(B),k[B].length!==0&&this._mergedSourceCaches[T].reloadTilesForDependencies(["icons","patterns"],k[B])}for(const T in k)this._changes.resetUpdatedImages(T)}_updateWorkerLayers(k,T,B){const K=this.getFragmentStyle(k);K&&this.dispatcher.broadcast("updateLayers",{layers:T?K._serializeLayers(T):[],scope:k,removedIds:B||[],options:K.options})}setState(k,T){if(this._checkLoaded(),Vv(this,_s(k)))return!1;if((k=o.dG(k)).layers=op(k.layers),!Ic.diffStyles)throw new Error("Debug module not loaded; cannot diff style.");const B=Ic.diffStyles(this.serialize(),k).filter(le=>!G_.has(le.command));if(B.length===0)return!1;const K=B.filter(le=>!W0.has(le.command));if(K.length>0)throw new Error(`Unimplemented: ${K.map(le=>le.command).join(", ")}.`);const Q=[];return B.forEach(le=>{Q.push(this[le.command](...le.args))}),T&&Promise.all(Q).then(T).catch(T),this.stylesheet=k,this.mergeAll(),this.dispatcher.broadcast("setLayers",{layers:this._serializeLayers(this._order),scope:this.scope,options:this.options}),!0}_updateWorkerImages(k=!1){this._availableImages=this.imageManager.listImages(this.scope);const T={scope:this.scope,images:this._availableImages};k&&(T.isSpriteLoaded=!0),this.dispatcher.broadcast("setImages",T)}_updateWorkerModels(){this._availableModels=this.modelManager.getModelURIs(this.scope),this.dispatcher.broadcast("setModels",{scope:this.scope,models:this._availableModels})}addImages(k,T){if(k.size===0)return T&&this.dispatcher.broadcast("spriteLoaded",{scope:this.scope}),this;for(const[B,K]of k.entries()){if(this.getImage(B))return this.fire(new o.f(new Error(`An image with the name "${B.name}" already exists.`)));this.imageManager.addImage(B,this.scope,K),this._changes.updateImage(B,this.scope)}return this._updateWorkerImages(T),this.fire(new o.h("data",{dataType:"style"})),this}addImage(k,T){return this.getImage(k)?this.fire(new o.f(new Error(`An image with the name "${k.name}" already exists.`))):(this.imageManager.addImage(k,this.scope,T),this._changes.updateImage(k,this.scope),this._updateWorkerImages(),this.fire(new o.h("data",{dataType:"style"})),this)}updateImage(k,T,B=!1){this.imageManager.updateImage(k,this.scope,T),B&&(this._changes.updateImage(k,this.scope),this._updateWorkerImages(),this.fire(new o.h("data",{dataType:"style"})))}getImage(k){return this.imageManager.getImage(k,this.scope)}removeImage(k){return this.getImage(k)?(this.imageManager.removeImage(k,this.scope),this._changes.updateImage(k,this.scope),this._updateWorkerImages(),this.fire(new o.h("data",{dataType:"style"})),this):this.fire(new o.f(new Error("No image with this name exists.")))}listImages(){return this._checkLoaded(),this._availableImages.slice()}getActualScope(){return this._importedAsBasemap?"basemap":this.scope}addModelURLs(k){return this.modelManager.addModelURLs(k,this.getActualScope()),this._updateWorkerModels(),this.fire(new o.h("data",{dataType:"style"})),this}addModel(k,T,B={}){return this._checkLoaded(),this._validate(zl,`models.${k}`,T,null,B)||(this.modelManager.addModel(k,T,this.getActualScope()),this.fire(new o.h("data",{dataType:"style"}))),this}hasModel(k){return this.modelManager.hasModel(k,this.getActualScope())}removeModel(k){return this.hasModel(k)?(this.modelManager.removeModel(k,this.getActualScope(),!1,!0),this.fire(new o.h("data",{dataType:"style"})),this):this.fire(new o.f(new Error("No model with this ID exists.")))}listModels(){return this._checkLoaded(),this.modelManager.listModels(this.getActualScope())}addSource(k,T,B={}){if(this._checkLoaded(),this.getOwnSource(k)!==void 0)throw new Error(`There is already a source with ID "${k}".`);if(!T.type)throw new Error(`The type property must be defined, but only the following properties were given: ${Object.keys(T).join(", ")}.`);if(["vector","raster","geojson","video","image"].includes(T.type)&&this._validate(Xa,`sources.${k}`,T,null,B))return;this.map&&this.map._collectResourceTiming&&(T.collectResourceTiming=!0);const K=Object.hasOwn(Uc,T.type)&&!Dc(T.type),Q=K?new Lf(k,T,this.dispatcher,this):lo(k,T,this.dispatcher,this);Q.scope=this.scope;const le=we=>{we.setEventedParent(this,()=>({isSourceLoaded:this._isSourceCacheLoaded(we.id),source:we.serialize(),sourceId:we.id}))};le(Q);const me=we=>{const Me=(we===o.bS.Symbol?"symbol:":we===o.bS.FillExtrusion?"fill-extrusion:":"other:")+Q.id,Re=o.m(Me,this.scope),Ze=this._sourceCaches[Me]=new Ci(Re,Q,we);we===o.bS.Symbol?this._symbolSourceCaches[Q.id]=Ze:we===o.bS.FillExtrusion?this._fillExtrusionSourceCaches[Q.id]=Ze:this._otherSourceCaches[Q.id]=Ze,Ze.onAdd(this.map)};me(o.bS.Other),T.type!=="vector"&&T.type!=="geojson"||(me(o.bS.Symbol),T.type==="vector"&&me(o.bS.FillExtrusion)),Q.onAdd&&Q.onAdd(this.map),K&&async function(we){if(Dc(we))return;const Me=Uc[we];if(!Me)throw new Error(`Unknown source type "${we}"`);const Re=await Me();Re&&!Dc(we)&&function(Ze,Qe){bl[Ze]=Qe}(we,Re)}(T.type).then(()=>{const we=Dc(T.type),Me=this._otherSourceCaches[k];if(!Me||Me.getSource()!==Q)return;if(!we)return void this.fire(new o.f(new Error(`Could not load module for source type "${T.type}".`)));const Re=lo(k,T,this.dispatcher,this);Re.scope=this.scope,le(Re),Me.setSource(Re),Re.onAdd&&Re.onAdd(this.map),this._changes.setDirty()}),B.isInitialLoad||(this.mergeSources(),this._changes.setDirty())}removeSource(k){this._checkLoaded();const T=this.getOwnSource(k);if(!T)throw new Error("There is no source with this ID");for(const K in this._layers)if(this._layers[K].source===k)return this.fire(new o.f(new Error(`Source "${k}" cannot be removed while layer "${K}" is using it.`)));if(this.terrain&&this.terrain.scope===this.scope&&this.terrain.get().source===k)return this.fire(new o.f(new Error(`Source "${k}" cannot be removed while terrain is using it.`)));if(this.stylesheet.iconsets){const K=Object.entries(this.stylesheet.iconsets).find(([Q,le])=>le.type==="source"&&le.source===k);if(K)return this.fire(new o.f(new Error(`Source "${k}" cannot be removed while iconset "${K[0]}" is using it.`)))}const B=this.getOwnSourceCaches(k);for(const K of B){const Q=o.dH(K.id);delete this._sourceCaches[Q],this._changes.discardSourceCacheUpdate(K.id),K.fire(new o.h("data",{sourceDataType:"metadata",dataType:"source",sourceId:K.getSource().id})),K.setEventedParent(null),K.clearTiles()}return delete this._otherSourceCaches[k],delete this._symbolSourceCaches[k],delete this._fillExtrusionSourceCaches[k],this._hdCoverage&&delete this._hdCoverage.coverageSourceCaches[k],this.mergeSources(),T.setEventedParent(null),T.onRemove&&T.onRemove(this.map),this.dispatcher.broadcast("removeSource",{type:T.type,source:k,scope:T.scope}),this._changes.setDirty(),this}setGeoJSONSourceData(k,T){this._checkLoaded(),this.getOwnSource(k).setData(T),this._changes.setDirty()}getOwnSource(k){const T=this.getOwnSourceCache(k);return T&&T.getSource()}getOwnSources(){const k=[];for(const T in this._otherSourceCaches){const B=this.getOwnSourceCache(T);B&&k.push(B.getSource())}return k}areTilesLoaded(){const k=this._mergedSourceCaches;for(const T in k){const B=k[T]._tiles;for(const K in B){const Q=B[K];if(Q.state!=="loaded"&&Q.state!=="errored")return!1}}return!0}setLights(k){if(this._checkLoaded(),this._programPrecompiler&&this._programPrecompiler.reset(),!k)return delete this.ambientLight,void delete this.directionalLight;const T=this._getTransitionParameters();for(const Q of k){if(this._validate(Ba,"lights",Q))return;switch(Q.type){case"ambient":if(this.ambientLight){const le=this.ambientLight;le.set(Q),le.updateTransitions(T)}else this.ambientLight=new Ps(Q,xn(),this.scope,this.options);break;case"directional":if(this.directionalLight){const le=this.directionalLight;le.set(Q),le.updateTransitions(T)}else this.directionalLight=new Ps(Q,Pn(),this.scope,this.options)}}const B=Object.assign(T,{worldview:this.map.getWorldview()}),K=new o.aj(this.z||0,B);this.ambientLight&&this.ambientLight.recalculate(K),this.directionalLight&&this.directionalLight.recalculate(K),this._brightness=this.calculateLightsBrightness(),this.dispatcher.broadcast("upsertRenderParams",{brightness:this._brightness})}calculateLightsBrightness(){const k=this.directionalLight,T=this.ambientLight;if(!k||!T)return;const B=Qe=>.2126*(Qe[0]<=.03928?Qe[0]/12.92:Math.pow((Qe[0]+.055)/1.055,2.4))+.7152*(Qe[1]<=.03928?Qe[1]/12.92:Math.pow((Qe[1]+.055)/1.055,2.4))+.0722*(Qe[2]<=.03928?Qe[2]/12.92:Math.pow((Qe[2]+.055)/1.055,2.4)),K=k.properties.get("color").toNonPremultipliedRenderColor(null).toArray01(),Q=k.properties.get("intensity"),le=k.properties.get("direction"),me=1-o.b_(le.x,le.y,le.z)[2]/90,we=B(K)*Q*me,Me=T.properties.get("color").toNonPremultipliedRenderColor(null).toArray01(),Re=T.properties.get("intensity"),Ze=B(Me)*Re;return Number(((we+Ze)/2).toFixed(6))}getBrightness(){return this._brightness}getLights(){if(!this.enable3dLights())return null;const k=[];return this.directionalLight&&k.push(this.directionalLight.get()),this.ambientLight&&k.push(this.ambientLight.get()),k}enable3dLights(){return!!this.ambientLight&&!!this.directionalLight}getFragmentStyle(k){if(k==null||k===""&&this.isRootStyle())return this;if(o.dI(k)){const T=o.dJ(k),B=this.fragments.find(({id:Q})=>Q===T);if(!B)return;const K=o.dH(k);return B.style.getFragmentStyle(K)}{const T=this.fragments.find(({id:B})=>B===k);return T?T.style:void 0}}setFeaturesetSelectors(k){if(!k)return;const T=(B,K="")=>`${B}::${K}`;this._featuresetSelectors={};for(const B in k){const K={},Q=this._featuresetSelectors[B]=[];for(const le of k[B].selectors){if(le.featureNamespace){const we=this.getOwnLayer(le.layer);if(!we){o.w(`Layer is undefined for selector: ${le.layer}`);continue}const Me=T(we.source,we.sourceLayer);if(Me in K&&K[Me]!==le.featureNamespace){o.w(`"featureNamespace ${le.featureNamespace} of featureset ${B}'s selector is not associated to the same source, skip this selector`);continue}K[Me]=le.featureNamespace}let me;if(le.properties)for(const we in le.properties){const Me=o.c(le.properties[we]);Me.result==="success"&&(me=me||{},me[we]=Me.value)}Q.push({layerId:le.layer,namespace:le.featureNamespace,properties:me,uniqueFeatureID:le._uniqueFeatureID})}}}getFeaturesetDescriptors(k){const T=this.getFragmentStyle(k);if(!T||!T.stylesheet.featuresets)return[];const B=[];for(const K in T.stylesheet.featuresets)B.push({featuresetId:K,importId:T.scope?T.scope:void 0});return B}getFeaturesetLayers(k,T){const B=this.getFragmentStyle(T),K=B.stylesheet.featuresets;if(!K||!K[k])return this.fire(new o.f(new Error(`The featureset '${k}' does not exist in the map's style and cannot be queried.`))),[];const Q=[];for(const le of K[k].selectors){const me=B.getOwnLayer(le.layer);me&&Q.push(me)}return Q}getConfigProperty(k,T){const B=this.getFragmentStyle(k);if(!B)return null;const K=o.m(T,B.scope),Q=B.options.get(K),le=Q?Q.value||Q.default:null;return le?le.serialize():null}isIndoorEnabled(){return this._indoorEnabled}getIndoorSourceLayers(k,T){const B=o.m(k,T);return this._mergedIndoor[B]}setIndoorData(k,T){this.indoorManager&&this.indoorManager.setIndoorData(T)}updateIndoorDependentLayers(){this._updateLayers(this._dependentLayerIds(k=>k.isIndoorDependent)),this.map._styleDirty=!0,this.map.triggerRepaint()}setConfigProperty(k,T,B){const K=this.getFragmentStyle(k);if(!K)return;const Q=K.stylesheet.schema;if(!Q||!Q[T])return;const le=o.dK(B,Q[T]);if(le.result!=="success")return void Vv(this,le.value);const me=le.value.expression,we=o.m(T,K.scope),Me=K.options.get(we);if(!Me)return;let Re;const{minValue:Ze,maxValue:Qe,stepValue:ht,type:_t,values:bt}=Q[T],Mt=o.dK(Q[T].default,Q[T]);Mt.result==="success"&&(Re=Mt.value.expression),Re?(this.options.set(we,{...Me,value:me,default:Re,minValue:Ze,maxValue:Qe,stepValue:ht,type:_t,values:bt}),this.updateConfigDependencies(T)):this.fire(new o.f(new Error(`No schema defined for the config option "${T}" in the "${k}" fragment.`)))}getConfig(k){const T=this.getFragmentStyle(k);if(!T)return null;const B=T.stylesheet.schema;if(!B)return null;const K={};for(const Q in B){const le=o.m(Q,T.scope),me=T.options.get(le),we=me?me.value||me.default:null;K[Q]=we?we.serialize():null}return K}setConfig(k,T){const B=this.getFragmentStyle(k);B&&(B.updateConfig(T,B.stylesheet.schema),this.updateConfigDependencies())}getSchema(k){const T=this.getFragmentStyle(k);return T?T.stylesheet.schema:null}setSchema(k,T){const B=this.getFragmentStyle(k);B&&(B.stylesheet.schema=T,B.updateConfig(B._config,T),this.updateConfigDependencies())}updateConfig(k,T){if(this._config=k,k||T)if(T)for(const B in T){let K,Q;const le=o.dK(T[B].default,T[B]);if(le.result==="success"&&(K=le.value.expression),k&&k[B]!==void 0){const Qe=o.dK(k[B],T[B]);Qe.result==="success"&&(Q=Qe.value.expression)}const{minValue:me,maxValue:we,stepValue:Me,type:Re,values:Ze}=T[B];if(K){const Qe=o.m(B,this.scope);this.options.set(Qe,{default:K,value:Q,minValue:me,maxValue:we,stepValue:Me,type:Re,values:Ze})}else this.fire(new o.f(new Error(`No schema defined for config option "${B}".`)))}else this.fire(new o.f(new Error("Attempting to set config for a style without schema.")))}_updateLayers(k){for(const T of k){const B=this.getLayer(T);B&&(B.possiblyEvaluateVisibility(),this._updateLayer(B),this._changes.setDirty())}}_dependentLayerIds(k){const T=[];for(const[B,K]of this._layerExpressionDependencies)k(K)&&T.push(B);return T}updateConfigDependencies(k){this._updateLayers(this._dependentLayerIds(T=>k?T.hasConfigDependency(k):T.isConfigDependent)),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(T=>{const B=T._styleColorTheme.colorThemeOverride?T._styleColorTheme.colorThemeOverride:T._styleColorTheme.colorTheme;if(B){const K=T._evaluateColorThemeData(B);(!T._styleColorTheme.lut&&K!==""||T._styleColorTheme.lut&&K!==T._styleColorTheme.lut.data)&&T.setColorTheme(B)}}),this._updateIndoorEnabled(),this._changes.setDirty()}addLayer(k,T,B={}){this._checkLoaded();const K=k.id;if(this._layers[K])return void this.fire(new o.f(new Error(`Layer with id "${K}" already exists on this map`)));let Q;if(k.type==="custom"){if(Vv(this,o.dL(k)))return;Q=o.dM(k,this.scope,this._styleColorTheme.lut,this.options)}else{if(typeof k.source=="object"&&(this.addSource(K,k.source),k=o.dG(k),k=Object.assign(k,{source:K})),this._validate(Zo,`layers.${K}`,k,{arrayIndex:-1},B))return;Q=o.dM(k,this.scope,this._styleColorTheme.lut,this.options),this._validateLayer(Q),Q.setEventedParent(this,{layer:{id:K}})}this._layerExpressionDependencies.set(Q.fqid,new U(Q));let le=this._order.length;if(T){const Re=this._order.indexOf(T);if(Re===-1)return void this.fire(new o.f(new Error(`Layer with id "${T}" does not exist on this map.`)));Q.slot&&Q.slot!==this._layers[T].slot?o.w(`Layer with id "${T}" has a different slot. Layers can only be rearranged within the same slot.`):le=Re}this._order.splice(le,0,K),this._handleLayerOrderChange(),this._layers[K]=Q;const me=this.getOwnLayerSourceCache(Q),we=!!this.directionalLight&&this.directionalLight.shadowsEnabled();me&&Q.canCastShadows()&&we&&(me.castsShadows=!0);const Me=this._changes.getRemovedLayer(Q);if(Me&&Q.source&&me&&Q.type!=="custom"){this._changes.discardLayerRemoval(Q);const Re=o.m(Q.source,Q.scope);Me.type!==Q.type?this._changes.updateSourceCache(Re,"clear"):(this._changes.updateSourceCache(Re,"reload"),me.pause())}this._updateLayer(Q),Q.onAdd&&Q.onAdd(this.map),Q.scope=this.scope,this.mergeLayers()}moveLayer(k,T){this._checkLoaded();const B=this._checkLayer(k);if(!B||k===T)return;const K=this._order.indexOf(k);this._order.splice(K,1);let Q=this._order.length;if(T){const le=this._order.indexOf(T);if(le===-1)return void this.fire(new o.f(new Error(`Layer with id "${T}" does not exist on this map.`)));B.slot&&B.slot!==this._layers[T].slot?o.w(`Layer with id "${T}" has a different slot. Layers can only be rearranged within the same slot.`):Q=le}this._order.splice(Q,0,k),this._changes.setDirty(),this._handleLayerOrderChange(),this.mergeLayers()}removeLayer(k){this._checkLoaded();const T=this._checkLayer(k);if(!T)return;T.setEventedParent(null);const B=this._order.indexOf(k);this._order.splice(B,1),delete this._layers[k],this._changes.setDirty(),this._handleLayerOrderChange(),this._layerExpressionDependencies.delete(T.fqid),this._changes.removeLayer(T),this.symbolIdRangeAllocator.releaseLayer(T.runtimeLayerUID);const K=this.getOwnLayerSourceCache(T);if(K&&K.castsShadows){let Q=!1;for(const le in this._layers)if(this._layers[le].source===T.source&&this._layers[le].canCastShadows()){Q=!0;break}K.castsShadows=Q}T.onRemove&&T.onRemove(this.map),this.mergeLayers()}getOwnLayer(k){return this._layers[k]}hasLayer(k){return k in this._mergedLayers}hasLayerType(k){for(const T in this._layers)if(this._layers[T].type===k)return!0;return!1}setLayerZoomRange(k,T,B){this._checkLoaded();const K=this._checkLayer(k);K&&(K.minzoom===T&&K.maxzoom===B||(T!=null&&(K.minzoom=T),B!=null&&(K.maxzoom=B),this._updateLayer(K)))}getSlots(){return this._checkLoaded(),this._mergedSlots}setSlot(k,T){this._checkLoaded();const B=this._checkLayer(k);B&&B.slot!==T&&(B.slot=T,this._updateLayer(B))}setFilter(k,T,B={}){this._checkLoaded();const K=this._checkLayer(k);if(!K||o.O(K.filter,T))return;const Q=this._layerExpressionDependencies.get(K.fqid);if(T==null)return K.filter=void 0,Q&&Q.invalidateFilter(),void this._updateLayer(K);this._validate(vo,`layers.${K.id}.filter`,T,{layerType:K.type},B)||(K.filter=o.dG(T),Q&&Q.invalidateFilter(),this._updateLayer(K))}getFilter(k){const T=this._checkLayer(k);if(T)return o.dG(T.filter)}setLayoutProperty(k,T,B,K={}){this._checkLoaded();const Q=this._checkLayer(k);if(Q&&!o.O(Q.getLayoutProperty(T),B)){if(B!=null&&(!K||K.validate!==!1)&&Vv(Q,Ol.call(_s,{key:`layers.${k}.layout.${T}`,layerType:Q.type,objectKey:T,value:B,styleSpec:o.s,style:{glyphs:!0,sprite:!0}})))return;Q.setLayoutProperty(T,B),this._updateLayer(Q)}}getLayerProperty(k,T){const B=this._checkLayer(k);if(B){switch(T){case"minzoom":return B.minzoom;case"maxzoom":return B.maxzoom;case"filter":return this.getFilter(k);case"slot":return B.slot;case"appearances":return B.getAppearances().map(K=>K.serialize())}return B.isPaintProperty(T)?this.getPaintProperty(k,T):this.getLayoutProperty(k,T)}}setLayerProperty(k,T,B,K={}){this._checkLoaded();const Q=this._checkLayer(k);if(Q){switch(T){case"appearances":return Q.setAppearances(B),void this._updateLayer(Q);case"minzoom":return this.setLayerZoomRange(k,B);case"maxzoom":return this.setLayerZoomRange(k,null,B);case"filter":return this.setFilter(k,B,K);case"slot":return this.setSlot(k,B)}Q.isPaintProperty(T)?this.setPaintProperty(k,T,B,K):this.setLayoutProperty(k,T,B,K)}}getLayoutProperty(k,T){const B=this._checkLayer(k);if(B)return B.getLayoutProperty(T)}setPaintProperty(k,T,B,K={}){this._checkLoaded();const Q=this._checkLayer(k);Q&&(o.O(Q.getPaintProperty(T),B)||(B==null||K&&K.validate===!1||!Vv(Q,Zg.call(_s,{key:`layers.${k}.paint.${T}`,layerType:Q.type,objectKey:T,value:B,styleSpec:o.s})))&&(Q.setPaintProperty(T,B)&&this._updateLayer(Q),this._changes.updatePaintProperties(Q)))}getPaintProperty(k,T){const B=this._checkLayer(k);if(B)return B.getPaintProperty(T)}setFeatureState(k,T){if(this._checkLoaded(),"target"in k){if("featuresetId"in k.target){const{featuresetId:we,importId:Me}=k.target,Re=this.getFragmentStyle(Me),Ze=Re.getFeaturesetLayers(we);for(const{source:Qe,sourceLayer:ht}of Ze)Re.setFeatureState({id:k.id,source:Qe,sourceLayer:ht},T)}else if("layerId"in k.target){const we=this._resolveLayerFragment(k.target.layerId);we==null||we.fragment.setFeatureState({id:k.id,source:we.layer.source,sourceLayer:we.layer.sourceLayer},T)}return}const B=k.source,K=k.sourceLayer,Q=this._checkSource(B);if(!Q)return;const le=Q.type;if(le==="geojson"&&K)return void this.fire(new o.f(new Error("GeoJSON sources cannot have a sourceLayer parameter.")));if(le==="vector"&&!K)return void this.fire(new o.f(new Error("The sourceLayer parameter must be provided for vector source types.")));k.id===void 0&&this.fire(new o.f(new Error("The feature id parameter must be provided.")));const me=this.getOwnSourceCaches(B);for(const we of me)we.setFeatureState(K,k.id,T)}removeFeatureState(k,T){if(this._checkLoaded(),"target"in k){if("featuresetId"in k.target){const{featuresetId:we,importId:Me}=k.target,Re=this.getFragmentStyle(Me),Ze=Re.getFeaturesetLayers(we);for(const{source:Qe,sourceLayer:ht}of Ze)Re.removeFeatureState({id:k.id,source:Qe,sourceLayer:ht},T)}else if("layerId"in k.target){const we=this._resolveLayerFragment(k.target.layerId);we==null||we.fragment.removeFeatureState({id:k.id,source:we.layer.source,sourceLayer:we.layer.sourceLayer},T)}return}const B=k.source,K=this._checkSource(B);if(!K)return;const Q=K.type,le=Q==="vector"?k.sourceLayer:void 0;if(Q==="vector"&&!le)return void this.fire(new o.f(new Error("The sourceLayer parameter must be provided for vector source types.")));if(T&&typeof k.id!="string"&&typeof k.id!="number")return void this.fire(new o.f(new Error("A feature id is required to remove its specific state property.")));const me=this.getOwnSourceCaches(B);for(const we of me)we.removeFeatureState(le,k.id,T)}getFeatureState(k){if(this._checkLoaded(),"target"in k){let Q;if("featuresetId"in k.target){const{featuresetId:le,importId:me}=k.target,we=this.getFragmentStyle(me),Me=we.getFeaturesetLayers(le);for(const{source:Re,sourceLayer:Ze}of Me){const Qe=we.getFeatureState({id:k.id,source:Re,sourceLayer:Ze});if(Qe&&!Q)Q=Qe;else if(!o.O(Q,Qe))return void this.fire(new o.f(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 k.target){const le=this._resolveLayerFragment(k.target.layerId);Q=le==null?void 0:le.fragment.getFeatureState({id:k.id,source:le.layer.source,sourceLayer:le.layer.sourceLayer})}return Q}const T=k.source,B=k.sourceLayer,K=this._checkSource(T);if(K){if(K.type!=="vector"||B)return k.id===void 0&&this.fire(new o.f(new Error("The feature id parameter must be provided."))),this.getOwnSourceCaches(T)[0].getFeatureState(B,k.id);this.fire(new o.f(new Error("The sourceLayer parameter must be provided for vector source types.")))}}resetFeatureStates(k){if(this._checkLoaded(),"featuresetId"in k){const{featuresetId:T,importId:B}=k,K=this.getFragmentStyle(B);if(!K)return;const Q=K.getFeaturesetLayers(T);for(const{source:le,sourceLayer:me}of Q)K.removeFeatureState({source:le,sourceLayer:me})}else{const T=this._resolveLayerFragment(k.layerId);T==null||T.fragment.removeFeatureState({source:T.layer.source,sourceLayer:T.layer.sourceLayer})}}setTransition(k){return this.stylesheet.transition={...this.stylesheet.transition,...k},this.transition=this.stylesheet.transition,this}getTransition(){return{...this.stylesheet.transition}}setWorldview(k){k!==this._worldview&&(this._worldview=k,this.dispatcher.broadcast("upsertRenderParams",{worldview:this._worldview}),this.reloadSources())}serialize(){this._checkLoaded();const k=this.getTerrain(),T=k&&this.terrain&&this.terrain.scope===this.scope?k:this.stylesheet.terrain;return o.dN({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:T,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)},B=>B!==void 0)}_updateFilteredLayers(k){for(const T of Object.values(this._mergedLayers))k(T)&&this._updateLayer(T)}_updateLayer(k){this._changes.updateLayer(k);const T=this.getLayerSourceCache(k),B=o.m(k.source,k.scope),K=this._changes.getUpdatedSourceCaches();k.source&&!K[B]&&T&&T.getSource().type!=="raster"&&(this._changes.updateSourceCache(B,"reload"),T.pause()),k.invalidateCompiledFilter()}_flattenAndSortRenderedFeatures(k){const T=me=>this._mergedLayers[me].is3D(!!this.terrain),B=this.order,K={},Q=[];for(let me=B.length-1;me>=0;me--){const we=B[me];if(T(we)){K[we]=me;for(const Me of k){const Re=Me[we];if(Re)for(const Ze of Re)Q.push(Ze)}}}Q.sort((me,we)=>we.intersectionZ-me.intersectionZ);const le=[];for(let me=B.length-1;me>=0;me--){const we=B[me];if(T(we))for(let Me=Q.length-1;Me>=0;Me--){const Re=Q[Me].feature;if(Re.layer&&K[Re.layer.id]{if(cg.has(Re.type))return;const Ze=this.getOwnLayerSourceCache(Re),Qe=Q[Ze.id]=Q[Ze.id]||{sourceCache:Ze,layers:{},has3DLayers:!1};Re.is3D(!!this.terrain)&&(Qe.has3DLayers=!0),Qe.layers[Re.fqid]=Qe.layers[Re.fqid]||{styleLayer:Re,targets:[]},Qe.layers[Re.fqid].targets.push({filter:K})};if(T&&T.layers){if(!Array.isArray(T.layers))return this.fire(new o.f(new Error("parameters.layers must be an Array."))),[];for(const Re of T.layers){const Ze=this._layers[Re];if(!Ze)return this.fire(new o.f(new Error(`The layer '${Re}' does not exist in the map's style and cannot be queried for features.`))),[];le(Ze)}}else for(const Re in this._layers)le(this._layers[Re]);const me=this._queryRenderedFeatures(k,Q,B),we=this._flattenAndSortRenderedFeatures(me),Me=[];for(const Re of we)o.dO(Re.layer.id)===this.scope&&Me.push(Re);return Me}queryRenderedFeatureset(k,T,B){let K;T&&!Array.isArray(T)&&T.filter&&(this._validate(vo,"queryRenderedFeatures.filter",T.filter,null,T),K=o.bw(T.filter));const Q="mock",le=[];if(T&&T.target)le.push({...T,targetId:Q,filter:K});else{const Re=this.getFeaturesetDescriptors();for(const Ze of Re)le.push({targetId:Q,filter:K,target:Ze});for(const{style:Ze}of this.fragments){const Qe=Ze.getFeaturesetDescriptors();for(const ht of Qe)le.push({targetId:Q,filter:K,target:ht})}}const me=this.queryRenderedTargets(k,le,B),we=[],Me=new Set;for(const Re of me)for(const Ze of Re.variants[Q])Qd(Ze,Re,Me)||we.push(new o.dP(Re,Ze));return we}queryRenderedTargets(k,T,B){const K={},Q=(me,we,Me,Re)=>{const Ze=K[we.id]=K[we.id]||{sourceCache:we,layers:{},has3DLayers:!1};if(Ze.layers[me.fqid]=Ze.layers[me.fqid]||{styleLayer:me,targets:[]},me.is3D(!!this.terrain)&&(Ze.has3DLayers=!0),!Re)return Me.uniqueFeatureID=!1,void Ze.layers[me.fqid].targets.push(Me);Ze.layers[me.fqid].targets.push({...Me,namespace:Re.namespace,properties:Re.properties,uniqueFeatureID:Re.uniqueFeatureID})};for(const me of T)if("featuresetId"in me.target){const{featuresetId:we,importId:Me}=me.target,Re=this.getFragmentStyle(Me);if(!Re||!Re._featuresetSelectors)continue;const Ze=Re._featuresetSelectors[we];if(!Ze){this.fire(new o.f(new Error(`The featureset '${we}' does not exist in the map's style and cannot be queried for features.`)));continue}for(const Qe of Ze){const ht=Re.getOwnLayer(Qe.layerId);ht&&!cg.has(ht.type)&&Q(ht,Re.getOwnLayerSourceCache(ht),me,Qe)}}else if("layerId"in me.target){const{layerId:we}=me.target,Me=this.getLayer(we);if(!Me||cg.has(Me.type))continue;Q(Me,this.getLayerSourceCache(Me),me)}const le=this._queryRenderedFeatures(k,K,B);return this._flattenAndSortRenderedFeatures(le)}_queryRenderedFeatures(k,T,B){const K=[],Q=!!this.map._showQueryGeometry,le=_r.createFromScreenPoints(k,B);for(const me in T){const we=og(le,T[me],this._availableImages,B,Q,this.getActualScope());Object.keys(we).length&&K.push(we)}if(this.placement)for(const me in T){if(T[me].sourceCache._renderSourceType!==o.bS.Symbol)continue;const we=Dh(le.screenGeometry,T[me],this._availableImages,this.placement.collisionIndex,this.placement.retainedQueryData,this.map.getWorldview());Object.keys(we).length&&K.push(we)}return K}querySourceFeatures(k,T){const B=T&&T.filter;B&&this._validate(vo,"querySourceFeatures.filter",B,null,T);let K=[];const Q=this.getOwnSourceCaches(k);for(const le of Q)K=K.concat(ff(le,T));return K}getFlatLight(){return this.light.getLight()}setFlatLight(k,T,B={}){this._checkLoaded();const K=this.light.getLight();let Q=!1;for(const me in k)if(!o.O(k[me],K[me])){Q=!0;break}if(!Q)return;const le=this._getTransitionParameters();this.light.setLight(k,T,B),this.light.updateTransitions(le)}hasTerrain(){return!!this.terrain&&this.terrain.drapeRenderMode===1}getTerrain(){return this.hasTerrain()?this.terrain.get():null}_startLiteLoad(){this._drapingLoaded===void 0&&(this._drapingLoaded=!1,async function(){return Promise.resolve()}().then(()=>{this._drapingLoaded=!0,this.map._removed||this.dispatcher.actors.length===0||this.map.triggerRepaint()}))}setTerrainForDraping(){this._startLiteLoad(),this.setTerrain({source:"",exaggeration:0},0)}checkCanvasFingerprintNoise(){this.disableElevatedTerrain===void 0&&(this.disableElevatedTerrain=o.e.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(k,T=1){if(this._checkLoaded(),!k)return this.terrainSetForDrapingOnly()||(delete this.terrain,this.map.transform.projection.requiresDraping&&this.setTerrainForDraping()),T===0&&delete this.terrain,k===null?this.stylesheet.terrain=null:delete this.stylesheet.terrain,this._force3DLayerUpdate(),void(this._markersNeedUpdate=!0);this.checkCanvasFingerprintNoise();let B=k;const K=!("source"in k)||k.source==null;if(T===1){if(this._startLiteLoad(),this.disableElevatedTerrain)return;if("source"in B&&typeof B.source=="object"){const me="terrain-dem-src";this.addSource(me,B.source),B=o.dG(B),B=Object.assign(B,{source:me})}const Q={...B},le={};if(this.terrain&&K){Q.source=this.terrain.get().source;const me=this.terrain?this.getFragmentStyle(this.terrain.scope):null;me&&(le.style=me.serialize())}if(this._validate(io,"terrain",Q,le))return}if(!this.terrain||this.terrain.scope!==this.scope&&!K||this.terrain&&T!==this.terrain.drapeRenderMode){if(!B)return;this._createTerrain(B,T),this.fire(new o.h("data",{dataType:"style"}))}else{const Q=this.terrain,le=Q.get();for(const me of Object.keys(o.s.terrain))!Object.hasOwn(B,me)&&o.s.terrain[me].default&&(B[me]=o.s.terrain[me].default);for(const me in k)if(!o.O(k[me],le[me])){Q.set(k,this.options),this.stylesheet.terrain=k;const we=this._getTransitionParameters({duration:0});Q.updateTransitions(we),this.fire(new o.h("data",{dataType:"style"}));break}}this.mergeTerrain(),this.updateDrapeFirstLayers(),this._markersNeedUpdate=!0}_createFog(k){const T=this.fog=new gt(k,this.map.transform,this.scope,this.options);this.stylesheet.fog=T.get();const B=this._getTransitionParameters({duration:0});T.updateTransitions(B)}_createSnow(k){const T=this.snow=new jt(k,this.map.transform,this.scope,this.options);this.stylesheet.snow=T.get();const B=this._getTransitionParameters({duration:0});T.updateTransitions(B)}_createRain(k){const T=this.rain=new Rt(k,this.map.transform,this.scope,this.options);this.stylesheet.rain=T.get();const B=this._getTransitionParameters({duration:0});T.updateTransitions(B)}_updateMarkersOpacity(){this.map._markers.length!==0&&this.map._requestDomTask(()=>{for(const k of this.map._markers)k._evaluateOpacity()})}getFog(){return this.fog?this.fog.get():null}setFog(k){if(this._checkLoaded(),k)if(this.fog){const T=this.fog;if(!o.O(T.get(),k)){T.set(k,this.options),this.stylesheet.fog=T.get();const B=this._getTransitionParameters({duration:0});T.updateTransitions(B)}}else this._createFog(k);else delete this.fog,delete this.stylesheet.fog;this._markersNeedUpdate=!0,this._programPrecompiler&&this._programPrecompiler.reset()}getSnow(){return this.snow?this.snow.get():null}setSnow(k){if(this._checkLoaded(),!k)return delete this.snow,void delete this.stylesheet.snow;if(this.snow){const T=this.snow;if(!o.O(T.get(),k)){T.set(k,this.options),this.stylesheet.snow=T.get();const B=this._getTransitionParameters({duration:0});T.updateTransitions(B)}}else this._createSnow(k);this._markersNeedUpdate=!0}getRain(){return this.rain?this.rain.get():null}setRain(k){if(this._checkLoaded(),!k)return delete this.rain,void delete this.stylesheet.rain;if(this.rain){const T=this.rain;if(!o.O(T.get(),k)){T.set(k,this.options),this.stylesheet.rain=T.get();const B=this._getTransitionParameters({duration:0});T.updateTransitions(B)}}else this._createRain(k);this._markersNeedUpdate=!0}_reloadColorTheme(){const k=()=>{for(const K in this._layers)this._layers[K].lut=this._styleColorTheme.lut;for(const K in this._sourceCaches)this._sourceCaches[K].clearTiles()},T=this._styleColorTheme.colorThemeOverride?this._styleColorTheme.colorThemeOverride:this._styleColorTheme.colorTheme;if(!T)return this._styleColorTheme.lut=null,void k();const B=this._evaluateColorThemeData(T);this._loadColorTheme(B).then(()=>{this.fire(new o.h("colorthemeset")),k()}).catch(K=>{o.w(`Couldn't set color theme: ${K}`)})}setColorTheme(k){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=k,this._reloadColorTheme()}setImportColorTheme(k,T){const B=this.getFragmentStyle(k);B&&(B._styleColorTheme.colorThemeOverride=T,B._reloadColorTheme())}_getTransitionParameters(k){return{now:o.e.now(),transition:Object.assign(this.transition,k)}}updateDrapeFirstLayers(){if(!this.terrain)return;const k=[],T=[];for(const B of this._mergedOrder)this.isLayerDraped(this._mergedLayers[B])?k.push(B):T.push(B);this._drapedFirstOrder=[],this._drapedFirstOrder.push(...k),this._drapedFirstOrder.push(...T)}_createTerrain(k,T){const B=this.terrain=new Yy(k,T,this.scope,this.options,this.map.getWorldview());T===1&&(this.stylesheet.terrain=k),this.mergeTerrain(),this.updateDrapeFirstLayers(),this._force3DLayerUpdate();const K=this._getTransitionParameters({duration:0});B.updateTransitions(K);const Q=new o.aj(this.z||0,{...K,worldview:this.map.getWorldview()});B.recalculate(Q)}_force3DLayerUpdate(){for(const k in this._layers){const T=this._layers[k];T.type==="fill-extrusion"&&this._updateLayer(T)}}_forceSymbolLayerUpdate(){for(const k in this._layers){const T=this._layers[k];T.type==="symbol"&&this._updateLayer(T)}}_validate(k,T,B,K,Q={}){if(Q&&Q.validate===!1)return!1;const le={...this.serialize()};return Vv(this,k.call(_s,{key:T,style:le,value:B,styleSpec:o.s,...K}))}_remove(){this._programPrecompiler&&(this._programPrecompiler.reset(),this._programPrecompiler=null),this._request&&(this._request.cancel(),this._request=null),this._spriteRequest&&(this._spriteRequest.abort(),this._spriteRequest=null),o.dQ.off("pluginStateChange",this._rtlTextPluginCallback);for(const k in this._mergedLayers)this._mergedLayers[k].setEventedParent(null);for(const k in this._mergedSourceCaches){const T=this._mergedSourceCaches[k];T.clearTiles(),T.setEventedParent(null);const B=T.getSource();B&&B.onRemove&&B.onRemove(this.map)}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&&this.indoorManager.destroy(),this.isRootStyle()&&(this.imageManager.setEventedParent(null),this.modelManager.setEventedParent(null),this.modelManager.destroy(),this.dispatcher.remove())}clearSource(k){const T=this.getSourceCaches(k);for(const B of T)B.clearTiles()}clearSources(){for(const k in this._mergedSourceCaches)this._mergedSourceCaches[k].clearTiles()}clearLayers(){for(const k in this._mergedLayers){const T=this._mergedLayers[k];T._clear&&T._clear()}}reloadSource(k){const T=this.getSourceCaches(k);for(const B of T)B.resume(),B.reload()}reloadSources(){for(const k of this.getSources())k.reload&&k.reload()}reloadModels(){this.modelManager.reloadModels(""),this.forEachFragmentStyle(k=>{k.modelManager.reloadModels(k.scope)})}updateSources(k){let T;this.directionalLight&&(T=o.dR(this.directionalLight));const B=new Set,K=new Set,Q=new Set;for(const le in this._mergedLayers){const me=this._mergedLayers[le];me.type==="building"?B.add(me.source):me.type==="raster"&&me.paint&&me.paint.get("raster-elevation-reference")==="ground"&&Q.add(me.source),me.hasElevation()&&!K.has(me.source)&&K.add(me.source)}this.updateFrcCoverageFadeRange();for(const le in this._mergedSourceCaches){const me=this._mergedSourceCaches[le],we=K.has(me._source.id);me._isRasterElevatedOverTerrain=Q.has(me._source.id),B.has(me._source.id)&&(me._source.reparseOverscaled=!1),me.update(k,void 0,void 0,T,we)}this.updateFrcCoverage(),this.updateElevationCoverage()}_reloadSources(){for(const k in this._sourceCaches){const T=this._sourceCaches[k];T.resume(),T.reload()}}updateFrcCoverageFadeRange(){this.map.painter&&Ui.updateFrcCoverageFadeRange&&Ui.updateFrcCoverageFadeRange(this,this.map.painter)}updateFrcCoverage(){this._hdCoverage&&Ui.updateFrcCoverage&&Ui.updateFrcCoverage(this,this._hdCoverage)}updateElevationCoverage(){this.isRootStyle()&&Ui.setupAndUpdateElevationCoverage&&Ui.setupAndUpdateElevationCoverage(this)}_handleLayerOrderChange(){this._requestFullLabelPlacement(),this.fire(new o.h("neworder"))}_requestFullLabelPlacement(){this.pauseablePlacement||(this.pauseablePlacement=new ax),this.pauseablePlacement.requestFullPlacement()}_setLabelPlacementStale(){this.placement&&this.placement.setStale()}_updatePlacement(k,T,B,K,Q,le){this.pauseablePlacement||(this.pauseablePlacement=new ax);let me=!1,we=!1;const Me={},Re={},Ze=le==="global",Qe=Ze?[]:this._mergedOrder;Ze&&this._driveGlobalPlacement(k,Q);for(const Qt of Qe){const Lt=this._mergedLayers[Qt];if(Lt.type!=="symbol")continue;const ps=o.m(Lt.source,Lt.scope);let Hs=Me[ps];if(!Hs){const nn=this.getLayerSourceCache(Lt);if(!nn)continue;const $s=nn.getRenderableIds(!0).map(rn=>nn.getTileByID(rn));Re[ps]=$s.slice(),Hs=Me[ps]=$s.sort((rn,_n)=>_n.tileID.overscaledZ-rn.tileID.overscaledZ||(rn.tileID.isLessThan(_n.tileID)?-1:1))}const Fs=this.crossTileSymbolIndex.addLayer(Lt,Hs,k.center.lng,k.projection);me=me||Fs}this.crossTileSymbolIndex.pruneUnusedLayers(Qe);const ht=!!(this.placement&&!k.equals(this.placement.transform)),_t=!!(this.placement&&(this.placement.lastReplacementSourceUpdateTime!==0&&!Q||this.placement.lastReplacementSourceUpdateTime!==Q.updateTime)),bt=ht||_t||me,Mt=(bt||this.pauseablePlacement.isStale())&&B===0,es=this.pauseablePlacement.isDone()&&!this.placement.stillRecent(o.e.now(),k.zoom)&&B!==0;if((this.pauseablePlacement.isFullPlacementRequested()||!this.pauseablePlacement.placement||Mt||es)&&(this.pauseablePlacement=this.pauseablePlacement.startNewPlacement(k,Qe,T,B,K,this.placement,this.fog&&k.projection.supportsFog?this.fog.state:null,this._buildingIndex),this.map.painter)){const Qt=this.map.painter.maxFrontCutoffRawStart;if(Qt>0){const Lt=180*k.pitch/Math.PI;if(Lt>=15){const ps=Math.min(1,Math.max(0,(Lt-15)/5)),Hs=ps*ps*(3-2*ps);this.pauseablePlacement.placement.frontCutoffStart=-.5*(1-Hs)+Qt*Hs}}}if(this.pauseablePlacement.isDone()?bt&&B!==0&&this.pauseablePlacement.setStale():(this.pauseablePlacement.continuePlacement(Qe,this._mergedLayers,Me,Re,this.map.painter.scaleFactor),this.pauseablePlacement.isDone()&&(this.placement=this.pauseablePlacement.commit(o.e.now()),we=!0),me&&this.pauseablePlacement.setStale()),we||me){this._buildingIndex.onNewFrame(k.zoom);for(let Qt=0;Qtwe.getTileByID(Ze)),Re=this.isLayerClipped(me);me.placeSymbols(Q,Me,le,we,Re)}B.finishPlacementRun()}_releaseSymbolFadeTiles(){for(const k in this._sourceCaches)this._sourceCaches[k].releaseSymbolFadeTiles()}addImport(k,T){if(this._checkLoaded(),new Set(["__proto__","constructor","prototype"]).has(k.id))return void this.fire(new o.f(new Error(`Import id can't be "${k.id}".`)));const B=this.stylesheet.imports=this.stylesheet.imports||[];if(B.findIndex(({id:Q})=>Q===k.id)!==-1)return void this.fire(new o.f(new Error(`Import with id '${k.id}' already exists in the map's style.`)));if(!T)return B.push(k),this._loadImports([k],!0);const K=B.findIndex(({id:Q})=>Q===T);return K===-1&&this.fire(new o.f(new Error(`Import with id "${T}" does not exist on this map.`))),this.stylesheet.imports=B.slice(0,K).concat(k).concat(B.slice(K)),this._loadImports([k],!0,T)}updateImport(k,T){this._checkLoaded();const B=this.stylesheet.imports||[],K=this.getImportIndex(k);return K===-1?this:typeof T=="string"?(this.setImportUrl(k,T),this):(T.url&&T.url!==B[K].url&&this.setImportUrl(k,T.url),o.O(T.config,B[K].config)||this.setImportConfig(k,T.config,T.data.schema),o.O(T.data,B[K].data)||this.setImportData(k,T.data),this)}moveImport(k,T){this._checkLoaded();let B=this.stylesheet.imports||[];const K=this.getImportIndex(k);if(K===-1)return this;const Q=this.getImportIndex(T);if(Q===-1)return this;const le=B[K],me=this.fragments[K];return B=B.filter(({id:we})=>we!==k),this.fragments=this.fragments.filter(({id:we})=>we!==k),this.stylesheet.imports=B.slice(0,Q).concat(le).concat(B.slice(Q)),this.fragments=this.fragments.slice(0,Q).concat(me).concat(this.fragments.slice(Q)),this.mergeLayers(),this}setImportUrl(k,T){this._checkLoaded();const B=this.stylesheet.imports||[],K=this.getImportIndex(k);if(K===-1)return this;B[K].url=T;const Q=this.fragments[K];return Q.style=this._createFragmentStyle(B[K]),Q.style.on("style.import.load",()=>this.mergeAll()),Q.style.loadURL(T),this}setImportData(k,T){this._checkLoaded();const B=this.getImportIndex(k),K=this.stylesheet.imports||[];return B===-1?this:T?(this.fragments[B].style.setState(T),this._reloadImports(),this):(delete K[B].data,this.setImportUrl(k,K[B].url))}setImportConfig(k,T,B){this._checkLoaded();const K=this.getImportIndex(k),Q=this.stylesheet.imports||[];if(K===-1)return this;T?Q[K].config=T:delete Q[K].config;const le=this.fragments[K];B&&le.style.stylesheet&&(le.style.stylesheet.schema=B);const me=le.style.stylesheet&&le.style.stylesheet.schema;return le.config=T,le.style.updateConfig(T,me),this.updateConfigDependencies(),this}removeImport(k){this._checkLoaded();const T=this.stylesheet.imports||[],B=this.getImportIndex(k);B!==-1&&(T.splice(B,1),this.fragments[B].style._remove(),this.fragments.splice(B,1),this._reloadImports())}getImportIndex(k){const T=(this.stylesheet.imports||[]).findIndex(B=>B.id===k);return T===-1&&this.fire(new o.f(new Error(`Import '${k}' does not exist in the map's style and cannot be updated.`))),T}getLayer(k){return this._mergedLayers[k]}getSources(){const k=[];for(const T in this._mergedOtherSourceCaches){const B=this._mergedOtherSourceCaches[T];B&&k.push(B.getSource())}return k}getSource(k,T){const B=this.getSourceCache(k,T);return B&&B.getSource()}getLayerSource(k){const T=this.getLayerSourceCache(k);return T&&T.getSource()}getSourceCache(k,T){const B=o.m(k,T);return this._mergedOtherSourceCaches[B]}getLayerSourceCache(k){const T=o.m(k.source,k.scope);return k.type==="symbol"?this._mergedSymbolSourceCaches[T]:k.type==="fill-extrusion"?this._mergedFillExtrusionSourceCaches[T]||this._mergedOtherSourceCaches[T]:k.type==="fill"&&k.sourceLayer===o.bV&&this._mergedHdRoadCoverageSourceCaches[T]?this._mergedHdRoadCoverageSourceCaches[T]:this._mergedOtherSourceCaches[T]}getSourceCaches(k){return k==null?Object.values(this._mergedSourceCaches):[this._mergedOtherSourceCaches[k],this._mergedSymbolSourceCaches[k],this._mergedFillExtrusionSourceCaches[k],this._mergedHdRoadCoverageSourceCaches[k]].filter(Boolean)}updateSourceCaches(){const k=this._changes.getUpdatedSourceCaches();for(const T in k){const B=k[T];B==="reload"?this.reloadSource(T):B==="clear"&&this.clearSource(T)}}updateLayers(k){const T=this._changes.getUpdatedPaintProperties();for(const B of T){const K=this.getLayer(B);K&&K.updateTransitions(k)}}getGlyphsUrl(){return this.stylesheet.glyphs}setGlyphsUrl(k){this.stylesheet.glyphs=k,this.glyphManager.setURL(k)}getOwnSourceCache(k){return this._otherSourceCaches[k]}getOwnLayerSourceCache(k){return k.type==="symbol"?this._symbolSourceCaches[k.source]:k.type==="fill-extrusion"&&this._fillExtrusionSourceCaches[k.source]||this._otherSourceCaches[k.source]}getOwnSourceCaches(k){return[this._otherSourceCaches[k],this._symbolSourceCaches[k],this._fillExtrusionSourceCaches[k],this._hdCoverage&&this._hdCoverage.coverageSourceCaches[k]].filter(Boolean)}_updateHdCoverageSourceCache(k){return Ui.HdCoverageState&&Ui.updateHdCoverageSourceCache?(this._hdCoverage||(this._hdCoverage=new Ui.HdCoverageState),Ui.updateHdCoverageSourceCache(this,this._hdCoverage,k),!1):k.type==="fill"&&k.sourceLayer===o.bV}_isSourceCacheLoaded(k){const T=this.getOwnSourceCaches(k);return T.length===0?(this.fire(new o.f(new Error(`There is no source with ID '${k}'`))),!1):T.every(B=>B.loaded())}has3DLayers(){return this._has3DLayers}hasSymbolLayers(){return this._hasSymbolLayers}hasCircleLayers(){return this._hasCircleLayers}isLayerClipped(k,T){if(!this._clipLayerPresent&&k.type!=="fill-extrusion"&&k.type!=="building")return!1;const B=k.type==="fill-extrusion"&&(k.sourceLayer==="building"||k.sourceLayer==="procedural_buildings"),K=k.type==="building";if(k.is3D(!!this.terrain)){if(B||K||T&&T.type==="batched-model"||k.type==="model")return!0}else if(k.type==="symbol")return!0;return!1}_clearWorkerCaches(){this.dispatcher.broadcast("clearCaches")}getBOMObject(){}destroy(){this._clearWorkerCaches(),this.imageManager.imageAtlasCache.clear(),this.fragments.forEach(k=>{k.style._remove()}),this.terrainSetForDrapingOnly()&&(delete this.terrain,delete this.stylesheet.terrain)}async getImages(k,T){const B=new Promise((we,Me)=>{this.imageManager.getImages(T.icons.concat(T.patterns),T.scope,(Re,Ze)=>{Re?Me(Re):we(Ze)})});this._updateTilesForChangedImages();const K=T.icons.map(we=>o.I.toString(we)),Q=T.patterns.map(we=>o.I.toString(we)),le=we=>{we&&(we.setDependencies(T.tileID.key,"icons",K),we.setDependencies(T.tileID.key,"patterns",Q))},me=o.m(T.source,T.scope);return le(this._mergedOtherSourceCaches[me]),le(this._mergedSymbolSourceCaches[me]),(T.icons.some(we=>we.iconsetId)||T.patterns.some(we=>we.iconsetId))&&this.fire(new o.h("data",{dataType:"style"})),B}async rasterizeImages(k,T){return new Promise((B,K)=>{this.imageManager.rasterizeImages(T,(Q,le)=>{Q?K(Q):B(le)})})}async checkAtlasCache(k,T){const B=this.imageManager.imageAtlasCache.findCachedAtlas(T.descriptor);return B&&B.contentDescriptor?{iconPositions:B.iconPositions,patternPositions:B.patternPositions,sourceHash:B.contentDescriptor.hash}:null}async getGlyphs(k,T){return new Promise((B,K)=>{this.glyphManager.getGlyphs(T.stacks,(Q,le)=>{Q?K(Q):B(le)})})}}up.registerForPluginStateChange=o.dz;class Hv{constructor(){this.boundProgram=null,this.boundLayoutVertexBuffer=null,this.boundPaintVertexBuffers=[],this.boundIndexBuffer=null,this.boundVertexOffset=null,this.boundDynamicVertexBuffers=[],this.vao=null}bind(k,T,B,K,Q,le,me,we){this.context=k;let Me=this.boundPaintVertexBuffers.length!==K.length;for(let Ze=0;!Me&&Ze`#define ${Mt}`)).join(` `)}`,Re=[Me,o.dZ];for(const Mt of B.fragmentIncludes)Re.push(o.bb[Mt]);Re.push(B.fragmentSource);const Ze=Re.join(` `),Qe=[Me,o.d_];for(const Mt of B.vertexIncludes)Qe.push(o.bb[Mt]);this.forceManualRenderingForInstanceIDShaders=k.forceManualRenderingForInstanceIDShaders&&B.vertexSource.includes("gl_InstanceID"),this.forceManualRenderingForInstanceIDShaders&&Qe.push("uniform int u_instanceID;"),Qe.push(B.vertexSource);let ht=Qe.join(` `);this.forceManualRenderingForInstanceIDShaders&&(ht=ht.replaceAll("gl_InstanceID","u_instanceID"));const _t=we.createShader(we.FRAGMENT_SHADER);if(we.isContextLost())return this.failedToCreate=!0,void(this._pending=!1);we.shaderSource(_t,Ze),we.compileShader(_t),we.attachShader(this.program,_t);const bt=we.createShader(we.VERTEX_SHADER);if(we.isContextLost())return this.failedToCreate=!0,void(this._pending=!1);we.shaderSource(bt,ht),we.compileShader(bt),we.attachShader(this.program,bt),we.linkProgram(this.program),this._fragmentShader=_t,this._vertexShader=bt,k.extParallelShaderCompile?k._pendingPrograms.add(this):this._finalize()}_finalize(){if(!this._pending)return;this._pending=!1;const k=this._context,T=k.gl;k._pendingPrograms.delete(this);const B=o.e.now(),K=T.getProgramParameter(this.program,T.LINK_STATUS),Q=o.e.now()-B,le=k._compileStats;if(le.totalStallMs+=Q,Q>le.maxStallMs&&(le.maxStallMs=Q),Q>1){le.framesMissed+=Math.floor(60*Q/1e3);const Me=this.fixedDefines.join(",");le.stalls.push({name:`${this.name}${Me?"/":""}${Me}`,ms:Q,timestamp:B})}if(this._fragmentShader&&(K||o.w(`Fragment shader '${this.name}': ${T.getShaderInfoLog(this._fragmentShader)}`),T.deleteShader(this._fragmentShader),this._fragmentShader=null),this._vertexShader&&(K||o.w(`Vertex shader '${this.name}': ${T.getShaderInfoLog(this._vertexShader)}`),T.deleteShader(this._vertexShader),this._vertexShader=null),!K)return o.w(`Failed to link program '${this.name}': ${T.getProgramInfoLog(this.program)}`),void(this.failedToCreate=!0);this.fixedUniforms=this._fixedUniformsFn(k),this.fixedUniformsEntries=Object.entries(this.fixedUniforms),this.binderUniforms=this.configuration?this.configuration.getUniforms(k):[],this.forceManualRenderingForInstanceIDShaders&&(this.instancingUniforms=(Me=>({u_instanceID:new o.aY(Me)}))(k));const me=this.fixedDefines,we=this.name;(me.includes("TERRAIN")||me.includes("ELEVATED")||we.includes("symbol")||we.includes("circle"))&&(this.terrainUniforms=(Me=>({u_dem:new o.aY(Me),u_dem_prev:new o.aY(Me),u_dem_tl:new o.a2(Me),u_dem_scale:new o.a3(Me),u_dem_tl_prev:new o.a2(Me),u_dem_scale_prev:new o.a3(Me),u_dem_size:new o.a3(Me),u_dem_lerp:new o.a3(Me),u_exaggeration:new o.a3(Me),u_depth:new o.aY(Me),u_depth_size_inv:new o.a2(Me),u_depth_range_unpack:new o.a2(Me),u_occluder_half_size:new o.a3(Me),u_occlusion_depth_offset:new o.a3(Me),u_meter_to_dem:new o.a3(Me),u_label_plane_matrix_inv:new o.a4(Me)}))(k)),me.includes("GLOBE")&&(this.globeUniforms=(Me=>({u_tile_tl_up:new o.a5(Me),u_tile_tr_up:new o.a5(Me),u_tile_br_up:new o.a5(Me),u_tile_bl_up:new o.a5(Me),u_tile_up_scale:new o.a3(Me)}))(k)),me.includes("FOG")&&(this.fogUniforms=(Me=>({u_fog_matrix:new o.a4(Me),u_fog_range:new o.a2(Me),u_fog_color:new o.aZ(Me),u_fog_horizon_blend:new o.a3(Me),u_fog_vertical_limit:new o.a2(Me),u_fog_temporal_offset:new o.a3(Me),u_frustum_tl:new o.a5(Me),u_frustum_tr:new o.a5(Me),u_frustum_br:new o.a5(Me),u_frustum_bl:new o.a5(Me),u_globe_pos:new o.a5(Me),u_globe_radius:new o.a3(Me),u_globe_transition:new o.a3(Me),u_is_globe:new o.aY(Me),u_viewport:new o.a2(Me)}))(k)),me.includes("RENDER_CUTOFF")&&(this.cutoffUniforms=o.d$(k)),me.includes("LIGHTING_3D_MODE")&&(this.lightsUniforms=(Me=>({u_lighting_ambient_color:new o.a5(Me),u_lighting_directional_dir:new o.a5(Me),u_lighting_directional_color:new o.a5(Me),u_ground_radiance:new o.a5(Me)}))(k)),me.includes("RENDER_SHADOWS")&&(this.shadowUniforms=o.e0(k))}maybeFinalize(){if(!this._pending)return;const k=this._context.extParallelShaderCompile;k&&!this._context.gl.getProgramParameter(this.program,k.COMPLETION_STATUS_KHR)||this._finalize()}_ensureReady(){this._pending&&(this._finalize(),this._context.sweepPendingPrograms())}getAttributeLocation(k,T){this._ensureReady();let B=this.attributes[T];return B===void 0&&(B=this.attributes[T]=k.getAttribLocation(this.program,T)),B}_setUniformGroup(k,T,B){this._ensureReady();const K=this[T];if(!this.failedToCreate&&K){k.program.set(this.program);for(const Q in B){const le=K[Q];le&&le.set(this.program,Q,B[Q])}}}setTerrainUniformValues(k,T){this._setUniformGroup(k,"terrainUniforms",T)}setGlobeUniformValues(k,T){this._setUniformGroup(k,"globeUniforms",T)}setFogUniformValues(k,T){this._setUniformGroup(k,"fogUniforms",T)}setCutoffUniformValues(k,T){this._setUniformGroup(k,"cutoffUniforms",T)}setLightsUniformValues(k,T){this._setUniformGroup(k,"lightsUniforms",T)}setShadowUniformValues(k,T){this._setUniformGroup(k,"shadowUniforms",T)}_drawDebugWireframe(k,T,B,K,Q,le,me,we,Me,Re){const Ze=k.options.wireframe;if(Ze.terrain===!1&&Ze.layers2D===!1&&Ze.layers3D===!1)return;const Qe=k.context;if(!(!(!Ze.terrain||this.name!=="terrainRaster"&&this.name!=="globeRaster")||!(!Ze.layers2D||k._terrain&&k._terrain.renderingToTexture||!oa.includes(this.name))||!(!Ze.layers3D||!M3.includes(this.name))))return;const ht=Qe.gl,_t=k.wireframeDebugCache.getLinesFromTrianglesBuffer(k.frameCounter,Q,Qe);if(!_t)return;const bt=[...this.fixedDefines,"DEBUG_WIREFRAME"],Mt=k.getOrCreateProgram(this.name,{config:this.configuration,defines:bt});Mt._ensureReady(),Qe.program.set(Mt.program);const es=(ps,Hs,Fs)=>{if(Hs[ps]&&Fs[ps])for(const nn in Hs[ps])Fs[ps][nn]&&Fs[ps][nn].set(Fs.program,nn,Hs[ps][nn].current)};Me&&Me.setUniforms(Mt.program,Qe,Mt.binderUniforms,me,{zoom:we}),es("fixedUniforms",this,Mt),es("terrainUniforms",this,Mt),es("globeUniforms",this,Mt),es("fogUniforms",this,Mt),es("lightsUniforms",this,Mt),es("shadowUniforms",this,Mt),_t.bind(),Qe.setColorMode(new o.a1([ht.ONE,ht.ONE_MINUS_SRC_ALPHA,ht.ZERO,ht.ONE],o.C.transparent,[!0,!0,!0,!1])),Qe.setDepthMode(new o.Z(T.func===ht.LESS?ht.LEQUAL:T.func,o.Z.ReadOnly,T.range)),Qe.setStencilMode(o._.disabled);const Qt=3*le.primitiveLength*2,Lt=3*le.primitiveOffset*2*2;if(this.forceManualRenderingForInstanceIDShaders){const ps=Re||1;for(let Hs=0;Hs1?ht.drawElementsInstanced(ht.LINES,Qt,ht.UNSIGNED_SHORT,Lt,Re):ht.drawElements(ht.LINES,Qt,ht.UNSIGNED_SHORT,Lt);Q.bind(),Qe.program.set(this.program),Qe.setDepthMode(T),Qe.setStencilMode(B),Qe.setColorMode(K)}checkUniforms(k,T,B){if(this.fixedDefines.includes(T)){for(const K of Object.keys(B))if(!B[K].initialized)throw new Error(`Program '${this.name}', from draw '${k}': uniform ${K} not set but required by ${T} being defined`)}}draw(k,T,B,K,Q,le,me,we,Me,Re,Ze,Qe,ht,_t,bt,Mt){const es=k.context,Qt=es.gl;if(this._ensureReady(),this.failedToCreate)return;es.program.set(this.program),es.setDepthMode(B),es.setStencilMode(K),es.setColorMode(Q),es.setCullFace(le);for(const[$s,rn]of this.fixedUniformsEntries)rn.set(this.program,$s,me[$s]);_t&&_t.setUniforms(this.program,es,this.binderUniforms,Qe,{zoom:ht});const Lt={[Qt.POINTS]:1,[Qt.LINES]:2,[Qt.TRIANGLES]:3,[Qt.LINE_STRIP]:1}[T];this.checkUniforms(we,"RENDER_SHADOWS",this.shadowUniforms);const ps=bt||[],Hs=_t?_t.getPaintVertexBuffers():[],Fs=T===Qt.TRIANGLES&&Re,nn=Mt&&Mt>0?1:void 0;for(const $s of Ze.get()){const rn=$s.vaos||($s.vaos={});if((rn[we]||(rn[we]=new Hv)).bind(es,this,Me,Hs,Re,$s.vertexOffset,ps,nn),this.forceManualRenderingForInstanceIDShaders){const _n=Mt||1;for(let Mn=0;Mn<_n;++Mn)this.instancingUniforms.u_instanceID.set(this.program,"u_instanceID",Mn),Re?Qt.drawElements(T,$s.primitiveLength*Lt,Qt.UNSIGNED_SHORT,$s.primitiveOffset*Lt*2):Qt.drawArrays(T,$s.vertexOffset,$s.vertexLength)}else Mt&&Mt>1?Qt.drawElementsInstanced(T,$s.primitiveLength*Lt,Qt.UNSIGNED_SHORT,$s.primitiveOffset*Lt*2,Mt):Re?Qt.drawElements(T,$s.primitiveLength*Lt,Qt.UNSIGNED_SHORT,$s.primitiveOffset*Lt*2):Qt.drawArrays(T,$s.vertexOffset,$s.vertexLength);Fs&&this._drawDebugWireframe(k,B,K,Q,Re,$s,Qe,ht,_t,Mt)}}}class dg{constructor(k,T,B,K){this.id=dg.uniqueIdxCounter,dg.uniqueIdxCounter++,this.context=k;const Q=k.gl;this.buffer=Q.createBuffer(),this.dynamicDraw=!!B,this.context.unbindVAO(),k.bindElementBuffer.set(this.buffer),Q.bufferData(Q.ELEMENT_ARRAY_BUFFER,T.arrayBuffer,this.dynamicDraw?Q.DYNAMIC_DRAW:Q.STATIC_DRAW),this.dynamicDraw||K||T.destroy()}bind(){this.context.bindElementBuffer.set(this.buffer)}updateData(k){this.id=dg.uniqueIdxCounter,dg.uniqueIdxCounter++;const T=this.context.gl;this.context.unbindVAO(),this.bind(),T.bufferSubData(T.ELEMENT_ARRAY_BUFFER,0,k.arrayBuffer)}destroy(){this.buffer&&(this.context.gl.deleteBuffer(this.buffer),delete this.buffer)}}dg.uniqueIdxCounter=0;const Gv={Int8:"BYTE",Uint8:"UNSIGNED_BYTE",Int16:"SHORT",Uint16:"UNSIGNED_SHORT",Int32:"INT",Uint32:"UNSIGNED_INT",Float32:"FLOAT"};class qx{constructor(k,T,B,K,Q,le){this.length=T.length,this.attributes=B,this.itemSize=T.bytesPerElement,this.dynamicDraw=K,this.instanceCount=le,this.context=k;const me=k.gl;this.buffer=me.createBuffer(),k.bindVertexBuffer.set(this.buffer),me.bufferData(me.ARRAY_BUFFER,T.arrayBuffer,this.dynamicDraw?me.DYNAMIC_DRAW:me.STATIC_DRAW),this.dynamicDraw||Q||T.destroy()}bind(){this.context.bindVertexBuffer.set(this.buffer)}updateData(k){const T=this.context.gl;this.bind(),T.bufferSubData(T.ARRAY_BUFFER,0,k.arrayBuffer)}enableAttributes(k,T){for(const B of this.attributes){const K=T.getAttributeLocation(k,B.name);K!==-1&&k.enableVertexAttribArray(K)}}setVertexAttribPointers(k,T,B){for(const K of this.attributes){const Q=T.getAttributeLocation(k,K.name);if(Q!==-1){const le=K.offset+this.itemSize*(B||0);K.type==="Float32"||K.normalized?k.vertexAttribPointer(Q,K.components,k[Gv[K.type]],!!K.normalized,this.itemSize,le):k.vertexAttribIPointer(Q,K.components,k[Gv[K.type]],this.itemSize,le)}}}setVertexAttribDivisor(k,T,B){for(let K=0;K0&&k.vertexAttribDivisor(Q,B)}}destroy(){this.buffer&&(this.context.gl.deleteBuffer(this.buffer),delete this.buffer)}}class sN{constructor(k,T,B,K,Q){this.context=k,this.width=T,this.height=B;const le=this.framebuffer=k.gl.createFramebuffer();K>0&&(this.colorAttachment0=new Fr(k,le,0)),K>1&&(this.colorAttachment1=new Fr(k,le,1)),Q&&(this.depthAttachmentType=Q,this.depthAttachment=Q==="renderbuffer"?new Fk(k,le):new FC(k,le))}static createWithTexture(k,T,B,K,Q){const le=k.gl;if(k.activeTexture.set(le.TEXTURE1),k.viewport.set([0,0,B,K]),T&&T.width===B&&T.height===K)return le.bindTexture(le.TEXTURE_2D,T.colorAttachment0.get()),k.bindFramebuffer.set(T.framebuffer),T;T&&T.destroy();const me=k.extRenderToTextureHalfFloat||k.extColorBufferFloat?k.gl.RGBA16F:k.gl.RGBA8,we=new o.T(k,{width:B,height:K,data:null},me);we.bind(le.LINEAR,le.CLAMP_TO_EDGE);const Me=k.createFramebuffer(B,K,1,null);if(Me.format=me,Me.colorAttachment0.set(we.texture),Q){const Re=k.createRenderbuffer(le.DEPTH24_STENCIL8,B,K);k.bindFramebuffer.set(Me.framebuffer),le.framebufferRenderbuffer(le.FRAMEBUFFER,le.DEPTH_STENCIL_ATTACHMENT,le.RENDERBUFFER,Re),Me._stencilRbo=Re}return Me}createColorAttachment(k,T){T===0?this.colorAttachment0=new Fr(k,this.framebuffer,0):T===1&&(this.colorAttachment1=new Fr(k,this.framebuffer,1))}removeColorAttachment(k,T){const B=this.context.gl;let K;T===0?(K=this.colorAttachment0.get(),this.colorAttachment0=void 0):T===1&&(K=this.colorAttachment1.get(),this.colorAttachment1=void 0),K&&B.deleteTexture(K)}destroy(){const k=this.context.gl;if(this.colorAttachment0){const T=this.colorAttachment0.get();T&&k.deleteTexture(T)}if(this.colorAttachment1){const T=this.colorAttachment1.get();T&&k.deleteTexture(T)}if(this.depthAttachment&&this.depthAttachmentType)if(this.depthAttachmentType==="renderbuffer"){const T=this.depthAttachment.get();T&&k.deleteRenderbuffer(T)}else{const T=this.depthAttachment.get();T&&k.deleteTexture(T)}this._stencilRbo&&(k.deleteRenderbuffer(this._stencilRbo),this._stencilRbo=null),k.deleteFramebuffer(this.framebuffer)}}class jm{constructor(k,T){this.gl=k,this._pendingPrograms=new Set,this._compileStats={precompiled:0,onDemand:0,totalStallMs:0,maxStallMs:0,framesMissed:0,stalls:[]},this.clearColor=new Jg(this),this.clearDepth=new F1(this),this.clearStencil=new O1(this),this.colorMask=new z1(this),this.depthMask=new tj(this),this.stencilMask=new sj(this),this.stencilFunc=new $_(this),this.stencilOp=new Rk(this),this.stencilTest=new Db(this),this.depthRange=new $v(this),this.depthTest=new C3(this),this.depthFunc=new Z2(this),this.blend=new rp(this),this.blendFunc=new Dk(this),this.blendColor=new B1(this),this.blendEquation=new ex(this),this.cullFace=new ap(this),this.cullFaceSide=new Ox(this),this.frontFace=new Hd(this),this.program=new Uv(this),this.activeTexture=new RC(this),this.viewport=new GT(this),this.bindFramebuffer=new WT(this),this.bindRenderbuffer=new A3(this),this.bindTexture=new Fb(this),this.bindVertexBuffer=new Tp(this),this.bindElementBuffer=new V0(this),this.bindVertexArrayOES=new DC(this),this.pixelStoreUnpack=new E3(this),this.pixelStoreUnpackPremultiplyAlpha=new Ob(this),this.pixelStoreUnpackFlipY=new ip(this),this.options=T?{...T}:{},this.options.extTextureFilterAnisotropicForceOff||(this.extTextureFilterAnisotropic=k.getExtension("EXT_texture_filter_anisotropic")||k.getExtension("MOZ_EXT_texture_filter_anisotropic")||k.getExtension("WEBKIT_EXT_texture_filter_anisotropic"),this.extTextureFilterAnisotropic&&(this.extTextureFilterAnisotropicMax=k.getParameter(this.extTextureFilterAnisotropic.MAX_TEXTURE_MAX_ANISOTROPY_EXT))),this.extDebugRendererInfo=k.getExtension("WEBGL_debug_renderer_info"),this.extDebugRendererInfo&&(this.renderer=k.getParameter(this.extDebugRendererInfo.UNMASKED_RENDERER_WEBGL),this.vendor=k.getParameter(this.extDebugRendererInfo.UNMASKED_VENDOR_WEBGL)),this.forceManualRenderingForInstanceIDShaders=T&&!!T.forceManualRenderingForInstanceIDShaders||this.renderer&&this.renderer.includes("PowerVR"),this.options.extTextureFloatLinearForceOff||(this.extTextureFloatLinear=k.getExtension("OES_texture_float_linear")),this.extRenderToTextureHalfFloat=k.getExtension("EXT_color_buffer_half_float"),this.extColorBufferFloat=k.getExtension("EXT_color_buffer_float"),this.extTimerQuery=k.getExtension("EXT_disjoint_timer_query_webgl2"),this.maxTextureSize=k.getParameter(k.MAX_TEXTURE_SIZE),this.maxUniformBlockSize=Math.min(k.getParameter(k.MAX_UNIFORM_BLOCK_SIZE),32768),this.maxUniformBufferBindings=k.getParameter(k.MAX_UNIFORM_BUFFER_BINDINGS),this.extBlendFuncExtended=k.getExtension("WEBGL_blend_func_extended"),this.extParallelShaderCompile=k.getExtension("KHR_parallel_shader_compile")}sweepPendingPrograms(){if(this._pendingPrograms.size!==0)for(const k of this._pendingPrograms)k.maybeFinalize()}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(k,T,B){return new dg(this,k,T,B)}createVertexBuffer(k,T,B,K,Q){return new qx(this,k,T,B,K,Q)}createRenderbuffer(k,T,B){const K=this.gl,Q=K.createRenderbuffer();return this.bindRenderbuffer.set(Q),K.renderbufferStorage(K.RENDERBUFFER,k,T,B),this.bindRenderbuffer.set(null),Q}createFramebuffer(k,T,B,K){return new sN(this,k,T,B,K)}clear({color:k,depth:T,stencil:B,colorMask:K}){const Q=this.gl;let le=0;k&&(le|=Q.COLOR_BUFFER_BIT,this.clearColor.set(k.toNonPremultipliedRenderColor(null)),this.colorMask.set(K||[!0,!0,!0,!0])),T!==void 0&&(le|=Q.DEPTH_BUFFER_BIT,this.depthRange.set([0,1]),this.clearDepth.set(T),this.depthMask.set(!0)),B!==void 0&&(le|=Q.STENCIL_BUFFER_BIT,this.clearStencil.set(B),this.stencilMask.set(255)),Q.clear(le)}setCullFace(k){k.enable===!1?this.cullFace.set(!1):(this.cullFace.set(!0),this.cullFaceSide.set(k.mode),this.frontFace.set(k.frontFace))}setDepthMode(k){k.func!==this.gl.ALWAYS||k.mask?(this.depthTest.set(!0),this.depthFunc.set(k.func),this.depthMask.set(k.mask),this.depthRange.set(k.range)):this.depthTest.set(!1)}setStencilMode(k){k.test.func!==this.gl.ALWAYS||k.mask?(this.stencilTest.set(!0),this.stencilMask.set(k.mask),this.stencilOp.set([k.fail,k.depthFail,k.pass]),this.stencilFunc.set({func:k.test.func,ref:k.ref,mask:k.test.mask})):this.stencilTest.set(!1)}setColorMode(k){o.O(k.blendFunction,o.a1.Replace)?this.blend.set(!1):(this.blend.set(!0),this.blendFunc.set(k.blendFunction),this.blendColor.set(k.blendColor),k.blendEquation?this.blendEquation.set(k.blendEquation):this.blendEquation.setDefault()),this.colorMask.set(k.mask)}unbindVAO(){this.bindVertexArrayOES.set(null)}}const P3=o.Y();function YT(L){const k=L._camera.getWorldToCamera(L.worldSize,1),T=o.X([],k,L.globeMatrix);o.aP(T,T);const B=[0,0,0],K=[0,1,0,0];return o.c6(K,K,T),B[0]=K[0],B[1]=K[1],B[2]=K[2],o.c9(B,B),B}function A9({width:L,height:k,anchor:T,textOffset:B,textScale:K},Q){const{horizontalAlign:le,verticalAlign:me}=o.du(T),we=-(le-.5)*L,Me=-(me-.5)*k,Re=o.dv(T,B);return new o.P((we/K+Re[0])*Q,(Me/K+Re[1])*Q)}function E9(L,k,T,B,K,Q,le,me,we,Me){const Re=L.text.placedSymbolArray,Ze=L.text.dynamicLayoutVertexArray,Qe=L.icon.dynamicLayoutVertexArray,ht={},_t=L.getProjection(),bt=o.e1(le,_t,K),Mt=K.elevation,es=_t.upVectorScale(le.canonical,K.center.lat,K.worldSize).metersToTile;Ze.clear();for(let Qt=0;Qt=0&&(ht[Lt.associatedIconIndex]={x:Yn,y:$n,z:zn,angle:ka})}else o.e3(Fs,Ze)}if(Me){Qe.clear();const Qt=L.icon.placedSymbolArray;for(let Lt=0;Lt{let _c=[0,0,0];if(Ld){const Xh=L.style.directionalLight,ug=L.style.ambientLight;Xh&&ug&&(_c=o.aG(L.style,Xh,ug))}return _c},Ko=Ld=>{const _c=Math.floor(L.context.maxUniformBlockSize/4),Xh=Math.floor(_c/4);Ld.push(`MAX_UBO_SIZE_VEC4 ${Xh}u`)},no=Ld=>{rn.depthOcclusionForSymbolsAndCircles&&(T.hasOcclusionOpacityProperties||L.terrain)&&(Ld.push("DEPTH_D24"),Ld.push("DEPTH_OCCLUSION"))},jd=Ld=>{T.lut&&!Fs&&(T.lut.texture||(T.lut.texture=new o.e7(L.context,T.lut.image,[T.lut.image.height,T.lut.image.height,T.lut.image.height],nn.gl.RGBA8)),nn.activeTexture.set(nn.gl.TEXTURE0+o.ci.LUT),T.lut.texture&&T.lut.texture.bind(nn.gl.LINEAR,nn.gl.CLAMP_TO_EDGE),Ld.push("APPLY_LUT_ON_GPU"))},Yh=()=>{const Ld=_n&&T.layout.get("symbol-placement")!=="point",_c=[];no(_c),jd(_c);const Xh=Ld||so,ug=Gr.elevationType==="road",Z_=L.shadowRenderer,t0=ug&&Yn&&!!Z_&&Z_.enabled,dj=qc(t0),_u=ug&&Yn&&!L.terrain?yr:An,ld=T.paint.get("icon-image-cross-fade");L.terrainRenderModeElevated()&&Yn&&_c.push("PITCH_WITH_MAP_TERRAIN"),Ga&&(_c.push("PROJECTION_GLOBE_VIEW"),Xh&&_c.push("PROJECTED_POS_ON_VIEWPORT")),ld>0&&Gr.hasAnySecondaryIcon&&_c.push("ICON_TRANSITION"),!Gr.icon.zOffsetVertexBuffer||ug&&L.terrain||_c.push("Z_OFFSET"),es===0&&Qt===0&&Lt===0&&ps===1||_c.push("COLOR_ADJUSTMENT"),t0&&_c.push("RENDER_SHADOWS","NORMAL_OFFSET"),ug&&Yn&&!L.terrain&&Gr.icon.orientationVertexBuffer&&_c.push("ELEVATED_ROADS"),Ko(_c);const Fc=L.getOrCreateProgram("symbol",{defines:_c}),Qh=Mr.imageAtlasTexture?Mr.imageAtlasTexture.size:[0,0],ix=Gr.iconSizeData,Yu=o.dl(ix,rn.zoom),Ri=Yn||!rn.isOrthographic,Nm=o.e2(Za,Mr.tileID.canonical,Yn,_n,rn,Gr.getProjection(),Oi),hg=o.dk(Za,Mr.tileID.canonical,Yn,_n,rn,Gr.getProjection(),Oi),uj=Gr.icon.uboBinder&&Gr.icon.uboBinder.hasPerFeatureTranslate()?[0,0]:me,hj=L.translatePosMatrix(hg,Mr,uj,Me,!0),Ub=L.translatePosMatrix(Za,Mr,uj,Me),qb=Xh?P3:Nm,nN=_n&&!Yn&&!Ld;let Vb=si;!Hr&&!rn.mercatorFromTransition||_n||(Vb=YT(rn));const jy=Ga?Vb:si,Um=T.getColorAdjustmentMatrix(es,Qt,Lt,ps),co=qs(ix.kind,Yu,nN,Yn,L,Ub,qb,hj,Hs,!1,Gr.sdfIcons,Qh,[0,0],0,Wr,Vr,sa,Vl,jy,Gr.getProjection(),dj,bu,Um,ld,null),hp=Mr.imageAtlasTexture?Mr.imageAtlasTexture:null,qm=T.layout.get("icon-size").constantOr(0)!==1||Gr.iconsNeedLinear,SY=Gr.sdfIcons||L.options.rotating||L.options.zooming||qm||Ri?$s.LINEAR:$s.NEAREST,X_=Gr.sdfIcons&&T.paint.get("icon-halo-width").constantOr(1)!==0,J6=L.terrain&&Yn&&Ld?o.aP(o.Y(),Nm):P3;if(Ld&&Gr.icon){const zf=o.c2.getAtTileOffsetFunc(Wr,rn.center.lat,rn.worldSize,Gr.getProjection()),eR=o.dj(Za,Mr.tileID.canonical,Yn,_n,rn,Gr.getProjection(),Oi),B9=T.layout.get("icon-size-scale-range"),$9=o.b1(L.scaleFactor,B9[0],B9[1]);o.e6(Gr,Za,L,!1,eR,hg,Yn,bt,zf,Wr,$9)}return{program:Fc,buffers:Gr.icon,uniformValues:co,atlasTexture:hp,atlasTextureIcon:null,atlasInterpolation:SY,atlasInterpolationIcon:null,isSDF:Gr.sdfIcons,hasHalo:X_,depthMode:_u,tile:Mr,renderWithShadows:t0,labelPlaneMatrixInv:J6}},wh=()=>{const Ld=Mn&&T.layout.get("symbol-placement")!=="point",_c=[],Xh=Ld||ka||so,ug=Gr.elevationType==="road",Z_=L.shadowRenderer,t0=ug&&$n&&!!Z_&&Z_.enabled,dj=qc(t0),_u=ug&&$n&&!L.terrain?yr:An;L.terrainRenderModeElevated()&&$n&&_c.push("PITCH_WITH_MAP_TERRAIN"),Ga&&(_c.push("PROJECTION_GLOBE_VIEW"),Xh&&_c.push("PROJECTED_POS_ON_VIEWPORT")),!Gr.text.zOffsetVertexBuffer||ug&&L.terrain||_c.push("Z_OFFSET"),Gr.iconsInText&&_c.push("RENDER_TEXT_AND_SYMBOL"),t0&&_c.push("RENDER_SHADOWS","NORMAL_OFFSET"),ug&&$n&&!L.terrain&&Gr.text.orientationVertexBuffer&&_c.push("ELEVATED_ROADS"),no(_c),Ko(_c);const ld=L.getOrCreateProgram("symbol",{defines:_c});let Fc,Qh=[0,0],ix=null;const Yu=Gr.textSizeData;Gr.iconsInText&&(Qh=Mr.imageAtlasTexture?Mr.imageAtlasTexture.size:[0,0],ix=Mr.imageAtlasTexture?Mr.imageAtlasTexture:null,Fc=$n||!rn.isOrthographic||L.options.rotating||L.options.zooming||Yu.kind==="composite"||Yu.kind==="camera"?$s.LINEAR:$s.NEAREST);const Ri=Mr.glyphAtlasTexture?Mr.glyphAtlasTexture.size:[0,0],Nm=T.layout.get("text-size-scale-range"),hg=o.b1(L.scaleFactor,Nm[0],Nm[1]),uj=o.dl(Yu,rn.zoom,hg),hj=o.e2(Za,Mr.tileID.canonical,$n,Mn,rn,Gr.getProjection(),Oi),Ub=o.dk(Za,Mr.tileID.canonical,$n,Mn,rn,Gr.getProjection(),Oi),qb=Gr.text.uboBinder&&Gr.text.uboBinder.hasPerFeatureTranslate()?[0,0]:we,nN=L.translatePosMatrix(Ub,Mr,qb,Re,!0),Vb=L.translatePosMatrix(Za,Mr,qb,Re),jy=Xh?P3:hj,Um=Mn&&!$n&&!Ld;let co=si;!Hr&&!rn.mercatorFromTransition||Mn||(co=YT(rn));const hp=qs(Yu.kind,uj,Um,$n,L,Vb,jy,nN,Hs,!0,!0,Ri,Qh,0,Wr,Vr,sa,Vl,Ga?co:si,Gr.getProjection(),dj,bu,null,null,hg),qm=Mr.glyphAtlasTexture?Mr.glyphAtlasTexture:null,SY=$s.LINEAR,X_=T.paint.get("text-halo-width").constantOr(1)!==0,J6=L.terrain&&$n&&Ld?o.aP(o.Y(),hj):P3;if(Ld&&Gr.text){const zf=o.c2.getAtTileOffsetFunc(Wr,rn.center.lat,rn.worldSize,Gr.getProjection()),eR=o.dj(Za,Mr.tileID.canonical,$n,Mn,rn,Gr.getProjection(),Oi);o.e6(Gr,Za,L,!0,eR,Ub,$n,Mt,zf,Wr,hg)}return{program:ld,buffers:Gr.text,uniformValues:hp,atlasTexture:qm,atlasTextureIcon:ix,atlasInterpolation:SY,atlasInterpolationIcon:Fc,isSDF:!0,hasHalo:X_,depthMode:_u,tile:Mr,renderWithShadows:t0,labelPlaneMatrixInv:J6}},Hl=Gr.icon.segments.get().length,fm=Gr.text.segments.get().length,bc=Hl&&!le.onlyText?Yh():null,rc=fm&&!le.onlyIcons?wh():null,Oh=T.paint.get("icon-opacity").constantOr(1),Zh=T.paint.get("text-opacity").constantOr(1);if(zn&&Gr.canOverlap){Dr=!0;const Ld=Oh&&!le.onlyText?Gr.icon.segments.get():[],_c=Zh&&!le.onlyIcons?Gr.text.segments.get():[];for(const Xh of Ld)ea.push({segments:new o.ad([Xh]),sortKey:Xh.sortKey,state:bc});for(const Xh of _c)ea.push({segments:new o.ad([Xh]),sortKey:Xh.sortKey,state:rc})}else le.onlyText||ea.push({segments:Oh?Gr.icon.segments:new o.ad([]),sortKey:0,state:bc}),le.onlyIcons||ea.push({segments:Zh?Gr.text.segments:new o.ad([]),sortKey:0,state:rc})}Dr&&ea.sort((Wr,Mr)=>Wr.sortKey-Mr.sortKey);for(const Wr of ea){const Mr=Wr.state;if(Mr)if(L.terrain?L.terrain.setupElevationDraw(Mr.tile,Mr.program,{useDepthForOcclusion:rn.depthOcclusionForSymbolsAndCircles,labelPlaneMatrixInv:Mr.labelPlaneMatrixInv}):L.setupDepthForOcclusion(rn.depthOcclusionForSymbolsAndCircles,Mr.program),nn.activeTexture.set($s.TEXTURE0),Mr.atlasTexture&&Mr.atlasTexture.bind(Mr.atlasInterpolation,$s.CLAMP_TO_EDGE,!0),Mr.atlasTextureIcon&&(nn.activeTexture.set($s.TEXTURE1),Mr.atlasTextureIcon&&Mr.atlasTextureIcon.bind(Mr.atlasInterpolationIcon,$s.CLAMP_TO_EDGE,!0)),Mr.renderWithShadows&&L.shadowRenderer.setupShadows(Mr.tile.tileID.toUnwrapped(),Mr.program,"vector-tile"),L.uploadCommonLightUniforms(L.context,Mr.program),Mr.hasHalo){const Gr=Mr.uniformValues;Gr.u_is_halo=1,BC(Mr.buffers,Wr.segments,T,L,Mr.program,Mr.depthMode,K,Q,Gr,2),Gr.u_is_halo=0}else{if(Mr.isSDF){const Gr=Mr.uniformValues;Mr.hasHalo&&(Gr.u_is_halo=1,BC(Mr.buffers,Wr.segments,T,L,Mr.program,Mr.depthMode,K,Q,Gr,1)),Gr.u_is_halo=0}BC(Mr.buffers,Wr.segments,T,L,Mr.program,Mr.depthMode,K,Q,Mr.uniformValues,1)}}}function BC(L,k,T,B,K,Q,le,me,we,Me){const Re=B.context,Ze=Re.gl,Qe=[L.dynamicLayoutVertexBuffer,L.opacityVertexBuffer,L.iconTransitioningVertexBuffer,L.globeExtVertexBuffer,L.zOffsetVertexBuffer,L.orientationVertexBuffer];L.featureIdBuffer&&Qe.push(L.featureIdBuffer);const ht=L.uboBinder?null:L.programConfigurations.get(T.id);if(L.uboBinder){L.uboBinder.layer=T;const Mt=B.transform.zoom,es=B.style.getBrightness?B.style.getBrightness():null,Qt=L.uboBinder.getConstantUniformValues(Mt,es);we.u_spp_fill_np_color=Qt.fill_np_color,we.u_spp_halo_np_color=Qt.halo_np_color,we.u_spp_opacity=Qt.opacity,we.u_spp_halo_width=Qt.halo_width,we.u_spp_halo_blur=Qt.halo_blur,we.u_spp_emissive_strength=Qt.emissive_strength,we.u_spp_occlusion_opacity=Qt.occlusion_opacity,we.u_spp_z_offset=Qt.z_offset,we.u_spp_zoom_fraction=Mt-L.uboBinder._floorZoom;const Lt=T.paint.get(L.uboBinder.isText?"text-translate-anchor":"icon-translate-anchor"),ps=L.uboBinder.hasPerFeatureTranslate()&&Lt==="map"?B.transform.angle:0;we.u_spp_translate_rotation=[Math.cos(ps),Math.sin(ps)]}const{batchIndices:_t,batchSegments:bt}=L.getBatchGrouping(k);for(const Mt of _t){const es=bt.get(Mt);L.uboBinder&&L.uboBinder.bind(Re,K.program,Mt),K.draw(B,Ze.TRIANGLES,Q,le,me,o.$.disabled,we,T.id,L.layoutVertexBuffer,L.indexBuffer,es,T.paint,B.transform.zoom,ht,Qe,Me)}}function $C(L,k,T,B,K,Q){const le=T.paint.get("line-width"),me=T.paint.get("line-emissive-strength").isConstant(),we=T.paint.get("line-emissive-strength").constantOr(0),Me=T.paint.get("line-occlusion-opacity"),Re=T.layout.get("line-elevation-reference"),Ze=T.layout.get("line-width-unit")==="meters",Qe=Re==="sea",ht=!(!L.terrain||!L.terrain.enabled),_t=L.context,bt=_t.gl;if(T.hasElevatedBuckets&&L.transform.projection.name==="globe")return;const Mt=T.layout.get("line-cross-slope"),es=Mt!==void 0,Qt=Mt<1,Lt=K||L.colorModeForDrapableLayerRenderPass(me?we:null),ps=L.terrain&&L.terrain.renderingToTexture||Q,Hs=ps?1:o.e.devicePixelRatio,Fs=T.paint.get("line-dasharray"),nn=Fs.constantOr(1),$s=T.layout.get("line-cap"),rn=Fs.constantOr(null),_n=$s.constantOr(null),Mn=T.paint.get("line-pattern"),Yn=Mn.constantOr(1),$n=T.paint.get("line-pattern-cross-fade"),zn=Mn.constantOr(null),Dr=T.paint.get("line-opacity").constantOr(1);let An=!Yn&&Dr!==1||L.depthOcclusion&&Me>0&&Me<1;const yr=T.paint.get("line-gradient"),sa=T.paint.get("line-border-width").constantOr(1)!==0?T.paint.get("line-border-gradient"):null,ka=Yn?"linePattern":"line",Hr=o.ea(T);let ea;if(ps&&L.terrain&&L.terrain.clipOrMaskOverlapStencilType()&&(An=!1),Me!==0&&L.depthOcclusion){const Za=T.paint._values["line-opacity"];Za&&Za.value&&Za.value.kind==="constant"?ea=Za.value:o.w(`Occlusion opacity for layer ${T.id} is supported only when line-opacity isn't data-driven.`)}le.value.kind!=="constant"&&le.value.isLineProgressConstant===!1&&Hr.push("VARIABLE_LINE_WIDTH");const si=T.paint.get("line-emissive-strength");Yn||si.value.kind==="constant"||si.value.isLineProgressConstant!==!1||Hr.push("VARIABLE_LINE_EMISSIVE_STRENGTH"),L._debugParams.showElevationIdDebug&&Hr.push("DEBUG_ELEVATION_ID"),ps&&(L.emissiveMode!=="dual-source-blending"||me?L.isEmissiveMrtActive()&&(Hr.push("USE_MRT1"),L.emissiveMode==="mrt-full-rgba"&&Hr.push("USE_MRT1_RGBA")):Hr.push("DUAL_SOURCE_BLENDING"));const Wr={},Mr=[],Gr=(Za,Oi,Do,so,Vl,bu)=>{for(const qc of Za){const Ko=k.getTile(qc);if(Yn&&!Ko.patternsLoaded())continue;const no=Ko.getBucket(T);if(!no||no.elevationType!=="none"&&!Vl||no.elevationType==="none"&&Vl)continue;L.prepareDrawTile();const jd=[...Oi],Yh=no.elevationType==="road",wh=L.shadowRenderer,Hl=Yh&&!!wh&&wh.enabled;let fm=[0,0,0];if(Hl){const Ri=L.style.directionalLight,Nm=L.style.ambientLight;Ri&&Nm&&(fm=o.aG(L.style,Ri,Nm)),jd.push("RENDER_SHADOWS","NORMAL_OFFSET")}const bc=no.programConfigurations.get(T.id);let rc=!1;if(zn&&Ko.imageAtlas){const Ri=o.aH.from(zn),Nm=Ri.getPrimary().scaleSelf(Hs).toString(),hg=Ko.imageAtlas.patternPositions.get(Nm),uj=Ri.getSecondary(),hj=uj?Ko.imageAtlas.patternPositions.get(uj.scaleSelf(Hs).toString()):null;rc=!!hg&&!!hj,hg&&bc.setConstantPatternPositions(hg,hj)}$n>0&&(rc||bc.getPatternTransitionVertexBuffer("line-pattern"))&&jd.push("LINE_PATTERN_TRANSITION"),no.elevationGroundScaleVertexBuffer&&jd.push("ELEVATION_GROUND_SCALE");const Oh=L.isTileAffectedByFog(qc),Zh=L.getOrCreateProgram(ka,{config:bc,defines:jd,overrideFog:Oh});if(!Yn&&rn&&_n&&Ko.lineAtlas){const Ri=Ko.lineAtlas.getDash(rn,_n);Ri&&bc.setConstantPatternPositions(Ri)}Hl&&wh.setupShadows(Ko.tileID.toUnwrapped(),Zh,"vector-tile");let[Ld,_c]=T.paint.get("line-trim-offset");(_n==="round"||_n==="square")&&Ld!==_c&&(Ld===0&&(Ld-=1),_c===1&&(_c+=1));const Xh=ps?qc.projMatrix:null,ug=Ze?1/no.tileToMeter/o.cd(Ko,1,L.transform.zoom):1,Z_=Ze?1/no.tileToMeter/o.cd(Ko,1,Math.floor(L.transform.zoom)):1,t0=nn?T.paint._values["line-floorwidth"]:null;let dj;const _u=Ko.dashIdealZ;if(t0&&t0.value.kind==="constant"&&_u!==Ko.tileID.overscaledZ){const Ri=no.zoom;Ri in Wr||(Wr[Ri]=Math.max(.01,T.widthExpression().evaluate({zoom:Ri}))),dj=t0.value.value,t0.value.value=Wr[Ri]*Math.pow(2,_u-Ri)}const ld=Yn?o.eb(L,Ko,T,Xh,Hs,ug,Z_,[Ld,_c],fm,$n):o.ec(L,Ko,T,Xh,no.lineClipsArray.length,Hs,ug,Z_,[Ld,_c],fm),Fc=(Ri,Nm,hg,uj,hj,Ub)=>{let qb=Ri.texture;if(Nm!==Ri.version){let nN=256;if(hg){const Vb=k.getSource().maxzoom,jy=qc.canonical.z===Vb?Math.ceil(1<{Nm&&Nm.get().length!==0&&(ea!=null&&(ea.value=Dr*Me),hg!==void 0&&(ld.u_opacity_multiplier=hg),Zh.draw(L,bt.TRIANGLES,Do,Ri,Lt,o.$.disabled,ld,T.id,no.layoutVertexBuffer,no.indexBuffer,Nm,T.paint,L.transform.zoom,bc,[no.layoutVertexBuffer2,no.patternVertexBuffer,no.zOffsetVertexBuffer,no.elevationIdColVertexBuffer,no.elevationGroundScaleVertexBuffer]),hg!==void 0&&(ld.u_opacity_multiplier=1),ea!=null&&(ea.value=Dr))},Yu=Ri=>{Qh&&Qh.active&&Ui.drawLineFrcRenderLine?Ui.drawLineFrcRenderLine(no,Qh,Ri,ix):ix(Ri,no.segments)};if(An&&!Vl){const Ri=L.stencilModeForClipping(qc).ref;Ri===0&&ps&&_t.clear({stencil:0});const Nm={func:bt.EQUAL,mask:255};ld.u_alpha_discard_threshold=.8,Yu(new o._(Nm,Ri,255,bt.KEEP,bt.KEEP,bt.INVERT)),ld.u_alpha_discard_threshold=0,Yu(new o._(Nm,Ri,255,bt.KEEP,bt.KEEP,bt.KEEP))}else ld.u_alpha_discard_threshold=An&&Vl&&bu?.8:0,Yu(Vl?so:L.stencilModeForClipping(qc));Qh&&Ui.drawLineFrcFadePass&&Ui.drawLineFrcFadePass(L,no,qc,Qh,Vl,so,ix),dj!==void 0&&(t0.value.value=dj)}};let Ga=L.depthModeForSublayer(0,o.Z.ReadOnly);const Vr=new o.Z(L.depthOcclusion?bt.GREATER:bt.LEQUAL,o.Z.ReadOnly,L.depthRangeFor3D);if(T.hasNonElevatedBuckets){const Za=!ps&&L.terrain;Me!==0&&Za?o.w(`Occlusion opacity for layer ${T.id} is supported on terrain only if the layer has line-z-offset enabled.`):Za?o.w(`Cannot render non-elevated lines in immediate mode when terrain is enabled. Layer: ${T.id}.`):Gr(B,Hr,Ga,o._.disabled,!1,!0)}if(T.hasElevatedBuckets){Re==="hd-road-markup"?ht||(Ga=Vr,Hr.push("ELEVATED_ROADS")):(Hr.push("ELEVATED"),Ga=Vr,es&&Hr.push(Qt?"CROSS_SLOPE_HORIZONTAL":"CROSS_SLOPE_VERTICAL"),Qe&&Hr.push("ELEVATION_REFERENCE_SEA"));const Za=An?L.stencilModeFor3D():o._.disabled;Re!=="hd-road-markup"&&(L.forceTerrainMode=!0),Gr(B,Hr,Ga,Za,!0,!0),An&&Gr(B,Hr,Ga,Za,!0,!1),Re!=="hd-road-markup"&&(L.forceTerrainMode=!1)}Ui.drawLineFrcCoverageSecondPass&&Ui.drawLineFrcCoverageSecondPass(L,T,Mr),An&&(L.resetStencilClippingMasks(),ps&&_t.clear({stencil:0})),Me===0||L.depthOcclusion||ps||L.layersWithOcclusionOpacity.push(L.currentLayer)}class Y0{destroy(){this.fbo&&(this.fbo.destroy(),this.fbo=null),this.drapeFbo&&(this.drapeFbo.destroy(),this.drapeFbo=null)}}class ZT{constructor(k){this.pbo=k.createBuffer(),this.sync=null,this.fboA=null,this.fboB=null,this.maxDensity=0}destroy(k){this.sync&&(k.deleteSync(this.sync),this.sync=null),k.deleteBuffer(this.pbo),this.fboA&&(this.fboA.destroy(),this.fboA=null),this.fboB&&(this.fboB.destroy(),this.fboB=null)}}const I3={additive:{clearColor:new o.C(0,0,0,0),colorMode:o.a1.additiveAlphaWeighted,compositeUniformValue:1},multiply:{clearColor:new o.C(1,1,1,1),colorMode:o.a1.multiply,compositeUniformValue:0}};function $b(L){return!(!L.extRenderToTextureHalfFloat&&!L.extColorBufferFloat)}function Gk(L,k){return L==="additive"&&$b(k)?o.a1.additiveAlphaWeightedUnboundedAlpha:I3[L].colorMode}function lj(L,k,T){const B=L.context,K=B.gl;let Q=T.width,le=T.height,me=T.colorAttachment0.get();k.lineBlendDensityReadback||(k.lineBlendDensityReadback=new ZT(K));const we=k.lineBlendDensityReadback;let Me=0,Re=!0;for(;Q>1||le>1;){const ht=Math.max(1,Math.floor(Q/2)),_t=Math.max(1,Math.floor(le/2)),bt=Me===0?"fboA":"fboB";we[bt]=sN.createWithTexture(B,we[bt],ht,_t,!1);const Mt=we[bt];B.bindFramebuffer.set(Mt.framebuffer),B.viewport.set([0,0,ht,_t]),B.activeTexture.set(K.TEXTURE0),K.bindTexture(K.TEXTURE_2D,me),L.getOrCreateProgram("lineBlendReduce").draw(L,K.TRIANGLES,o.Z.disabled,o._.disabled,o.a1.unblended,o.$.disabled,He(0,[1/Q,1/le],Re),k.id,L.viewportBuffer,L.quadTriangleIndexBuffer,L.viewportSegments,k.paint,L.transform.zoom),Q=ht,le=_t,me=Mt.colorAttachment0.get(),Me=1-Me,Re=!1}const Ze=$b(B),Qe=Ze?16:4;we.sync&&(K.deleteSync(we.sync),we.sync=null),K.bindBuffer(K.PIXEL_PACK_BUFFER,we.pbo),K.bufferData(K.PIXEL_PACK_BUFFER,Qe,K.STREAM_READ),K.readPixels(0,0,1,1,K.RGBA,Ze?K.FLOAT:K.UNSIGNED_BYTE,0),K.bindBuffer(K.PIXEL_PACK_BUFFER,null),we.sync=K.fenceSync(K.SYNC_GPU_COMMANDS_COMPLETE,0),B.viewport.set([0,0,L.width,L.height])}function Wk(L,k,T){if(!$b(L.context))return;const B=k.lineBlendDensityReadback;B&&B.sync?(function(K,Q,le){if(K.sync&&Q.getSyncParameter(K.sync,Q.SYNC_STATUS)===Q.SIGNALED){if(Q.deleteSync(K.sync),K.sync=null,Q.bindBuffer(Q.PIXEL_PACK_BUFFER,K.pbo),$b(le)){const me=new Float32Array(4);Q.getBufferSubData(Q.PIXEL_PACK_BUFFER,0,me);const we=me[1];K.maxDensity=Math.max(2*(we>0?me[0]/we:0),1)}else K.maxDensity=1;Q.bindBuffer(Q.PIXEL_PACK_BUFFER,null)}}(B,L.context.gl,L.context),B.sync||(lj(L,k,T),L.style.map.triggerRepaint())):(lj(L,k,T),L.style.map.triggerRepaint())}function UC(L,k,T,B,K,Q){const le=L.context,me=le.gl,we=T==="additive"?1:k.paint.get("line-opacity").constantOr(1),Me=T==="additive"?function(Ze,Qe){const ht=Qe.paint.get("line-blend-additive-clamp");if(ht>0)return ht;const _t=Qe.lineBlendDensityReadback;return _t&&_t.maxDensity!==0?_t.maxDensity:null}(0,k):1;if(Me===null)return;le.bindFramebuffer.set(K),Q&&le.viewport.set([0,0,Q[0],Q[1]]),le.activeTexture.set(me.TEXTURE0),me.bindTexture(me.TEXTURE_2D,B.colorAttachment0.get());const Re=Gk(T,L.context);L.getOrCreateProgram("lineBlendComposite").draw(L,me.TRIANGLES,o.Z.disabled,o._.disabled,Re,o.$.disabled,((Ze,Qe,ht,_t)=>({u_image:0,u_opacity:Qe,u_blend_mode:ht,u_max_density:_t}))(0,we,I3[T].compositeUniformValue,Me),k.id,L.viewportBuffer,L.quadTriangleIndexBuffer,L.viewportSegments,k.paint,L.transform.zoom)}function qC(L,k,T,B){const{painter:K,sourceCache:Q,layer:le,coords:me,colorMode:we,elevationType:Me,terrainEnabled:Re,pass:Ze}=L,Qe=K.context.gl,ht=le.paint.get("fill-pattern"),_t=le.paint.get("fill-pattern-cross-fade"),bt=ht.constantOr(null);let Mt=Me;Me!=="road"||k&&!Re||(Mt="none");const es=Mt==="road",Qt=L.painter.shadowRenderer,Lt=es&&!!Qt&&Qt.enabled,ps=new o.Z(K.context.gl.LEQUAL,o.Z.ReadOnly,K.depthRangeFor3D);let Hs=[0,0,0];if(Lt){const rn=K.style.directionalLight,_n=K.style.ambientLight;rn&&_n&&(Hs=o.aG(K.style,rn,_n))}const Fs=ht&&ht.constantOr(1),nn=K.terrain&&K.terrain.renderingToTexture,$s=(rn,_n)=>{let Mn,Yn,$n,zn,Dr;_n?(Mn=Fs&&!le.getPaintProperty("fill-outline-color")?"fillOutlinePattern":"fillOutline",$n=Qe.LINES):(Mn=Fs?"fillPattern":"fill",$n=Qe.TRIANGLES);const An=[];for(const yr of me){const sa=Q.getTile(yr);if(Fs&&!sa.patternsLoaded())continue;const ka=sa.getBucket(le);if(!ka)continue;const Hr=k?ka.hdExt&&ka.hdExt.elevationBufferData:ka.bufferData;if(!Hr||Hr.isEmpty())continue;K.prepareDrawTile();const ea=Hr.programConfigurations.get(le.id),si=K.isTileAffectedByFog(yr),Wr=[],Mr=[];es&&(Wr.push("ELEVATED_ROADS"),Mr.push(Hr.elevatedLayoutVertexBuffer)),Lt&&Wr.push("RENDER_SHADOWS","NORMAL_OFFSET"),nn&&T&&(Wr.push("USE_MRT1"),K.emissiveMode==="mrt-full-rgba"&&Wr.push("USE_MRT1_RGBA")),Fs&&(K.context.activeTexture.set(Qe.TEXTURE0),sa.imageAtlasTexture&&sa.imageAtlasTexture.bind(Qe.LINEAR,Qe.CLAMP_TO_EDGE),ea.updatePaintBuffers());let Gr=!1;if(bt&&sa.imageAtlas){const Vl=sa.imageAtlas,bu=o.aH.from(bt),qc=bu.getPrimary().scaleSelf(o.e.devicePixelRatio).toString(),Ko=bu.getSecondary(),no=Vl.patternPositions.get(qc),jd=Ko?Vl.patternPositions.get(Ko.scaleSelf(o.e.devicePixelRatio).toString()):null;Gr=!!no&&!!jd,no&&ea.setConstantPatternPositions(no,jd)}_t>0&&(Gr||ea.getPatternTransitionVertexBuffer("fill-pattern"))&&Wr.push("FILL_PATTERN_TRANSITION");const Ga=K.getOrCreateProgram(Mn,{config:ea,overrideFog:si,defines:Wr}),Vr=K.translatePosMatrix(yr.projMatrix,sa,le.paint.get("fill-translate"),le.paint.get("fill-translate-anchor"));Lt&&Qt.setupShadows(sa.tileID.toUnwrapped(),Ga,"vector-tile");const Za=le.paint.get("fill-emissive-strength");if(_n){zn=Hr.lineIndexBuffer,Dr=Hr.lineSegments;const Vl=K.terrain&&K.terrain.renderingToTexture?K.terrain.drapeBufferSize:[Qe.drawingBufferWidth,Qe.drawingBufferHeight];Yn=Mn==="fillOutlinePattern"&&Fs?Pe(Vr,Za,K,sa,Vl,Hs,_t):aj(Vr,Za,Vl,Hs)}else zn=Hr.indexBuffer,Dr=Hr.triangleSegments,Yn=Fs?U1(Vr,Za,K,sa,Hs,_t):zC(Vr,Za,Hs);K.uploadCommonUniforms(K.context,Ga,yr.toUnwrapped());let Oi=rn;if((Me==="road"&&!Re||Me==="offset")&&(Oi=ps),!Dr||Dr.get&&Dr.get().length===0)continue;const Do=B||K.stencilModeForClipping(yr);let so="fallthrough";!_n&&Ui.drawFillFrcCoverageFirstPass&&(so=Ui.drawFillFrcCoverageFirstPass({painter:K,layer:le,bucket:ka,coord:yr,elevatedGeometry:k,program:Ga,programConfiguration:ea,uniformValues:Yn,drawMode:$n,depthMode:Oi,stencilMode:Do,colorMode:we,bufferData:Hr,indexBuffer:zn,segments:Dr,dynamicBuffers:Mr,polygonCoverageTiles:An})),so==="fallthrough"&&Ga.draw(K,$n,Oi,Do,we,o.$.disabled,Yn,le.id,Hr.layoutVertexBuffer,zn,Dr,le.paint,K.transform.zoom,ea,Mr)}!_n&&Ui.drawFillFrcCoverageSecondPass&&Ui.drawFillFrcCoverageSecondPass(K,le,An,$n,we)};K.renderPass===Ze&&$s(K.depthModeForSublayer(1,K.renderPass==="opaque"?o.Z.ReadWrite:o.Z.ReadOnly),!1),Mt==="none"&&K.renderPass==="translucent"&&le.paint.get("fill-antialias")&&$s(K.depthModeForSublayer(le.getPaintProperty("fill-outline-color")?2:0,o.Z.ReadOnly),!0)}function B6(L){return[L[0]*o.eg,L[1]*o.eg,L[2]*o.eg,0]}function L3(L,k,T,B,K,Q,le,me,we,Me){const Re=K.getSource(),Ze=B.globeSharedBuffers;if(!Ze)return;let Qe,ht,_t;if(T&&(Qe=K.getTile(T)),Re instanceof Fi?(ht=Re.texture,_t=o.c1(0,0,B.transform)):Qe&&T&&(ht=Qe.texture,_t=o.c1(T.canonical.z,T.canonical.x,B.transform)),!ht||!_t)return;k||(_t=o.aO(o.Y(),_t,[1,-1,1]));const bt=B.context,Mt=bt.gl,es=Q.paint.get("raster-resampling")==="nearest"?Mt.NEAREST:Mt.LINEAR,Qt=B.colorModeForDrapableLayerRenderPass(le),Lt=me.defines;Lt.push("GLOBE_POLES");const ps=new o.Z(Mt.LEQUAL,o.Z.ReadWrite,B.depthRangeFor3D),Hs=B.transform.expandedFarZProjMatrix,Fs=Float32Array.from(o.b5(o.b6(new o.bW(0,0,0))));B.terrain&&B.terrain.prepareDrawTile(),bt.activeTexture.set(Mt.TEXTURE0),ht.bind(es,Mt.CLAMP_TO_EDGE),bt.activeTexture.set(Mt.TEXTURE1),ht.bind(es,Mt.CLAMP_TO_EDGE),"useMipmap"in ht&&bt.extTextureFilterAnisotropic&&B.transform.pitch>20&&Mt.texParameterf(Mt.TEXTURE_2D,bt.extTextureFilterAnisotropic.TEXTURE_MAX_ANISOTROPY_EXT,bt.extTextureFilterAnisotropicMax);const[nn,$s,rn,_n]=T?Ze.getPoleBuffers(T.canonical.z,!1):Ze.getPoleBuffers(0,!0),Mn=L;let Yn;k?(Yn=nn,B.renderDefaultNorthPole=Mn!==0):(Yn=$s,B.renderDefaultSouthPole=Mn!==0);const $n=B6(me.mix),zn=((An,yr,sa,ka,Hr,ea,si,Wr,Mr,Gr,Ga,Vr,Za,Oi)=>ks(An,yr,sa,ka,new Float32Array(16),new Float32Array(9),[0,0],Hr,[0,0],[0,0,0,0],1,{opacity:1,mix:0},si,[0,0],Mr,2,Ga,Vr,Za,1,0,Oi))(B,Hs,Fs,_t,o.S(B.transform.zoom),0,Q,0,Mn,0,$n,me.offset,me.range,le),Dr=B.getOrCreateProgram("raster",{defines:Lt});B.uploadCommonUniforms(bt,Dr,null),Dr.draw(B,Mt.TRIANGLES,ps,Me,Qt,we,zn,Q.id,Yn,rn,_n)}function $6(L){if(L.isOrthographic)return[0,0,0,0];const k=L._nearZ,T=L.projection.farthestPixelDistance(L),B=T-k,K=.2*L.height,Q=k+K;return[k,T,(Q-K-k)/B,(Q-k)/B]}function XT(L,k,T,B){if(L)return k.type==="raster-array"?k.getTextureDescriptor(L,T,!0):{texture:L.texture,mix:B6(B.mix),offset:B.offset,buffer:0,tileSize:1}}const U6=o.df(new Float32Array(16)),VC={"dual-source-blending":"dual-source-blending","mrt-fallback":"mrt","mrt-full-rgba":"mrt-rgba"},T9=o.a$([{name:"a_pos_3f",components:3,type:"Float32"}]),{members:q6}=T9;function oe(L,k,T,B){L.emplaceBack(k,T,B)}class de{constructor(k){this.vertexArray=new o.eh,this.indices=new o.ae,oe(this.vertexArray,-1,-1,1),oe(this.vertexArray,1,-1,1),oe(this.vertexArray,-1,1,1),oe(this.vertexArray,1,1,1),oe(this.vertexArray,-1,-1,-1),oe(this.vertexArray,1,-1,-1),oe(this.vertexArray,-1,1,-1),oe(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=k.createVertexBuffer(this.vertexArray,q6),this.indexBuffer=k.createIndexBuffer(this.indices),this.segment=o.ad.simpleSegment(0,0,36,12)}}function Oe(L,k,T,B,K,Q){const le=L.context.gl,me=k.paint.get("sky-atmosphere-color"),we=k.paint.get("sky-atmosphere-halo-color"),Me=k.paint.get("sky-atmosphere-sun-intensity"),Re=((Ze,Qe,ht,_t,bt)=>({u_matrix_3f:Ze,u_sun_direction:Qe,u_sun_intensity:ht,u_color_tint_r:[_t.r,_t.g,_t.b,_t.a],u_color_tint_m:[bt.r,bt.g,bt.b,bt.a],u_luminance:5e-5}))(o.ek(o.el(),B),K,Me,me.toPremultipliedRenderColor(null),we.toPremultipliedRenderColor(null));le.framebufferTexture2D(le.FRAMEBUFFER,le.COLOR_ATTACHMENT0,le.TEXTURE_CUBE_MAP_POSITIVE_X+Q,k.skyboxTexture,0),T.draw(L,le.TRIANGLES,o.Z.disabled,o._.disabled,o.a1.unblended,o.$.frontCW,Re,"skyboxCapture",k.skyboxGeometry.vertexBuffer,k.skyboxGeometry.indexBuffer,k.skyboxGeometry.segment)}const et=o.a$([{type:"Float32",name:"a_pos",components:3},{type:"Float32",name:"a_uv",components:2}]);class dt{constructor(k){const T=new o.em;T.emplaceBack(-1,1,1,0,0),T.emplaceBack(1,1,1,1,0),T.emplaceBack(1,-1,1,1,1),T.emplaceBack(-1,-1,1,0,1);const B=new o.ae;B.emplaceBack(0,1,2),B.emplaceBack(2,3,0),this.vertexBuffer=k.createVertexBuffer(T,et.members),this.indexBuffer=k.createIndexBuffer(B),this.segments=o.ad.simpleSegment(0,0,4,2)}destroy(){this.vertexBuffer.destroy(),this.indexBuffer.destroy(),this.segments.destroy()}}const Ot=o.a$([{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 Ks{constructor(){this.colorModeAlphaBlendedWriteRGB=new o.a1([o.en,o.eo,o.en,o.eo],o.C.transparent,[!0,!0,!0,!1]),this.colorModeWriteAlpha=new o.a1([o.en,o.ep,o.en,o.ep],o.C.transparent,[!1,!1,!1,!0]),this.params={starsCount:16e3,sizeMultiplier:.15,sizeRange:100,intensityRange:200},this.updateNeeded=!0,this._painter=null,this._devtoolsFolder=null}update(k){this._painter=k;const T=k.context;if(!this.atmosphereBuffer||this.updateNeeded){this.updateNeeded=!1,this.atmosphereBuffer=new dt(T);let B=this.params;const K=B.sizeRange,Q=B.intensityRange,le=function(Ze){const Qe=o.bj(30),ht=[];for(let _t=0;_t{const $s=Q.projection.name==="globe"?["PROJECTION_GLOBE_VIEW","FOG"]:["FOG"];nn&&$s.push("ALPHA_PASS");const rn=k.getOrCreateProgram("globeAtmosphere",{defines:$s}),_n=((Yn,$n,zn,Dr,An,yr,sa,ka,Hr,ea,si,Wr)=>({u_frustum_tl:Yn,u_frustum_tr:$n,u_frustum_br:zn,u_frustum_bl:Dr,u_horizon:An,u_transition:yr,u_fadeout_range:sa,u_atmosphere_fog_color:ka.toArray01(),u_high_color:Hr.toArray01(),u_space_color:ea.toArray01(),u_temporal_offset:si,u_horizon_angle:Wr}))(Q.frustumCorners.TL,Q.frustumCorners.TR,Q.frustumCorners.BR,Q.frustumCorners.BL,Q.frustumCorners.horizon,me,Mt,Re,Qe,_t,Qt,Hs);k.uploadCommonUniforms(B,rn);const Mn=this.atmosphereBuffer;Mn&&rn.draw(k,K.TRIANGLES,le,o._.disabled,nn?this.colorModeWriteAlpha:this.colorModeAlphaBlendedWriteRGB,o.$.backCW,_n,nn?"atmosphere_glow_alpha":"atmosphere_glow",Mn.vertexBuffer,Mn.indexBuffer,Mn.segments)};Fs(!1),Fs(!0)}drawStars(k,T){const B=o.b1(T.properties.get("star-intensity"),0,1);if(B===0)return;const K=k.context,Q=K.gl,le=k.transform,me=k.getOrCreateProgram("stars"),we=o.be([]);o.bf(we,we,-le._pitch),o.bg(we,we,-le.angle),o.bf(we,we,o.av(le._center.lat)),o.et(we,we,-o.av(le._center.lng));const Me=o.bh(new Float32Array(16),we),Re=o.X([],le.starsProjMatrix,Me),Ze=o.ek([],Me),Qe=o.eu([],Ze);let ht=this.params.sizeMultiplier;const _t=[0,1,0];o.cT(_t,_t,Qe),o.dV(_t,_t,ht);const bt=[1,0,0];o.cT(bt,bt,Qe),o.dV(bt,bt,ht);const Mt=(es=_t,Qt=bt,Lt=B,{u_matrix:Float32Array.from(Re),u_up:es,u_right:Qt,u_intensity_multiplier:Lt});var es,Qt,Lt;k.uploadCommonUniforms(K,me),this.starsVx&&this.starsIdx&&me.draw(k,Q.TRIANGLES,o.Z.disabled,o._.disabled,this.colorModeAlphaBlendedWriteRGB,o.$.disabled,Mt,"atmosphere_stars",this.starsVx,this.starsIdx,this.starsSegments)}}class fr{}class $r{constructor(){this._storage=new Map}getLinesFromTrianglesBuffer(k,T,B){{const Ze=this._storage.get(T.id);if(Ze)return Ze.lastUsedFrameIdx=k,Ze.buf}const K=B.gl,Q=K.getBufferParameter(K.ELEMENT_ARRAY_BUFFER,K.BUFFER_SIZE),le=new ArrayBuffer(Q),me=new Int16Array(le);K.getBufferSubData(K.ELEMENT_ARRAY_BUFFER,0,new Int16Array(le));const we=new o.ev;for(let Ze=0;Ze30&&(B.buf.destroy(),this._storage.delete(T))}destroy(){for(const[k,T]of this._storage)T.buf.destroy(),this._storage.delete(k)}}class ui{constructor(){this.occluderSize=30,this.depthOffset=-1e-4}}const Pi={symbol:function(L,k,T,B,K){if(L.renderPass!=="translucent")return;const Q=o._.disabled,le=L.colorModeForRenderPass(),me=T.layout.get("text-variable-anchor"),we=T.layout.get("text-size-scale-range"),Me=o.b1(L.scaleFactor,we[0],we[1]);me&&function(Qe,ht,_t,bt,Mt,es,Qt,Lt){const ps=ht.transform,Hs=Mt==="map",Fs=es==="map";for(const nn of Qe){const $s=bt.getTile(nn),rn=$s.getBucket(_t);if(!rn||!rn.text||!rn.text.segments.get().length)continue;const _n=o.dl(rn.textSizeData,ps.zoom,Lt),Mn=o.e1(nn,rn.getProjection(),ps),Yn=ps.calculatePixelsToTileUnitsMatrix($s),$n=o.e2(Mn,$s.tileID.canonical,Fs,Hs,ps,rn.getProjection(),Yn),zn=rn.hasIconTextFit()&&rn.hasIconData();_n&&E9(rn,Hs,Fs,Qt,ps,$n,nn,Math.pow(2,ps.zoom-$s.tileID.overscaledZ),_n,zn)}}(B,L,T,k,T.layout.get("text-rotation-alignment"),T.layout.get("text-pitch-alignment"),K,Me);const Re=T.paint.get("icon-opacity").constantOr(1)!==0,Ze=T.paint.get("text-opacity").constantOr(1)!==0;T.layout.get("symbol-sort-key").constantOr(1)!==void 0&&(Re||Ze)?Hk(L,k,T,B,Q,le):(Re&&Hk(L,k,T,B,Q,le,{onlyIcons:!0}),Ze&&Hk(L,k,T,B,Q,le,{onlyText:!0})),k.map.showCollisionBoxes&&Ic.drawCollisionDebug&&(Ic.drawCollisionDebug(L,k,T,B,T.paint.get("text-translate"),T.paint.get("text-translate-anchor"),!0),Ic.drawCollisionDebug(L,k,T,B,T.paint.get("icon-translate"),T.paint.get("icon-translate-anchor"),!1))},circle:function(L,k,T,B){if(L.renderPass!=="translucent")return;const K=T.paint.get("circle-opacity"),Q=T.paint.get("circle-stroke-width"),le=T.paint.get("circle-stroke-opacity"),me=T.layout.get("circle-sort-key").constantOr(1)!==void 0,we=T.paint.get("circle-emissive-strength");if(K.constantOr(1)===0&&(Q.constantOr(1)===0||le.constantOr(1)===0))return;const Me=L.context,Re=Me.gl,Ze=L.transform,Qe=!(!L.terrain||!L.terrain.enabled),ht=T.layout.get("circle-elevation-reference"),_t=L.depthModeForSublayer(0,o.Z.ReadOnly),bt=new o.Z(L.context.gl.LEQUAL,o.Z.ReadOnly,L.depthRangeFor3D),Mt=ht==="none"||Qe?_t:bt,es=o._.disabled,Qt=L.colorModeForDrapableLayerRenderPass(we),Lt=Ze.projection.name==="globe",ps=[o.a7(Ze.center.lng),o.a8(Ze.center.lat)],Hs=[];for(let nn=0;nnnn.sortKey-$s.sortKey);const Fs={useDepthForOcclusion:Ze.depthOcclusionForSymbolsAndCircles};for(const nn of Hs){const{programConfiguration:$s,program:rn,layoutVertexBuffer:_n,dynamicBuffers:Mn,indexBuffer:Yn,uniformValues:$n,tile:zn}=nn.state,Dr=nn.segments;L.terrain&&L.terrain.setupElevationDraw(zn,rn,Fs),L.uploadCommonUniforms(Me,rn,zn.tileID.toUnwrapped()),rn.draw(L,Re.TRIANGLES,Mt,es,Qt,o.$.disabled,$n,T.id,_n,Yn,Dr,T.paint,Ze.zoom,$s,Mn)}},heatmap:function(L,k,T,B){if(T.paint.get("heatmap-opacity")!==0)if(L.renderPass==="offscreen"){const K=L.context,Q=K.gl,le=o._.disabled,me=new o.a1([Q.ONE,Q.ONE,Q.ONE,Q.ONE],o.C.transparent,[!0,!0,!0,!0]),we=L.transform.projection.name==="globe"?.5:.25;T.heatmapFbo=sN.createWithTexture(K,T.heatmapFbo,L.width*we,L.height*we),K.clear({color:o.C.transparent});const Me=L.transform,Re=Me.projection.name==="globe",Ze=Re?["PROJECTION_GLOBE_VIEW"]:[],Qe=Re?o.$.frontCCW:o.$.disabled,ht=[o.a7(Me.center.lng),o.a8(Me.center.lat)];for(let _t=0;_t({u_image:0,u_color_ramp:1,u_opacity:Ze.paint.get("heatmap-opacity")}))(0,Q),Q.id,K.viewportBuffer,K.quadTriangleIndexBuffer,K.viewportSegments,Q.paint,K.transform.zoom)}(L,T))},line:function(L,k,T,B){const K=T.paint.get("line-opacity"),Q=T.paint.get("line-width");if(K.constantOr(1)===0||Q.constantOr(1)===0)return;const le=T.paint.get("line-blend-mode"),me=L.terrain&&L.terrain.renderingToTexture;if(le==="default"||L.transform.projection.name==="globe")L.renderPass==="translucent"&&$C(L,k,T,B);else{if(me)return void function(we,Me,Re,Ze,Qe){if(we.renderPass!=="translucent")return;const ht=we.context,_t=ht.gl,bt=we.terrain;if(!bt)return;const Mt=ht.bindFramebuffer.current,es=we.isEmissiveMrtActive(),Qt=bt.drapeBufferSize[0],Lt=bt.drapeBufferSize[1];Re.lineBlendFbos||(Re.lineBlendFbos=new Y0),Re.lineBlendFbos.drapeFbo=sN.createWithTexture(ht,Re.lineBlendFbos.drapeFbo,Qt,Lt,!0),es&&_t.drawBuffers([_t.COLOR_ATTACHMENT0]),ht.clear({color:I3[Qe].clearColor,depth:1,stencil:0});const ps=we.currentStencilSource,Hs=we._tileClippingMaskIDs,Fs=we.nextStencilID;we.currentStencilSource=void 0,we._tileClippingMaskIDs={},we.nextStencilID=1;const nn=we._terrain;we._terrain=null,we._renderTileClippingMasks(Re,Me,Ze),$C(we,Me,Re,Ze,Gk(Qe,we.context),!0),we._terrain=nn,we.currentStencilSource=ps,we._tileClippingMaskIDs=Hs,we.nextStencilID=Fs,es&&_t.drawBuffers([_t.COLOR_ATTACHMENT0,_t.COLOR_ATTACHMENT1]);const $s=bt.drapeBufferSize,rn=Re.lineBlendFbos&&Re.lineBlendFbos.drapeFbo;rn&&(Qe==="additive"&&Wk(we,Re,rn),UC(we,Re,Qe,rn,Mt,$s))}(L,k,T,B,le);if(L.renderPass==="offscreen")return void function(we,Me,Re,Ze,Qe){const ht=we.context,_t=Math.ceil(we.width),bt=Math.ceil(we.height);Re.lineBlendFbos||(Re.lineBlendFbos=new Y0),Re.lineBlendFbos.fbo=sN.createWithTexture(ht,Re.lineBlendFbos.fbo,_t,bt,!0),ht.clear({color:I3[Qe].clearColor,depth:1,stencil:0});const Mt=we.currentStencilSource,es=we._tileClippingMaskIDs,Qt=we.nextStencilID;we.currentStencilSource=void 0,we._tileClippingMaskIDs={},we.nextStencilID=1,we._renderTileClippingMasks(Re,Me,Ze);const Lt=we.renderPass;we.renderPass="translucent",$C(we,Me,Re,Ze,Gk(Qe,we.context)),we.renderPass=Lt,we.currentStencilSource=Mt,we._tileClippingMaskIDs=es,we.nextStencilID=Qt,ht.viewport.set([0,0,we.width,we.height]),Qe==="additive"&&Wk(we,Re,Re.lineBlendFbos.fbo)}(L,k,T,B,le);if(L.renderPass==="translucent"){const we=T.lineBlendFbos&&T.lineBlendFbos.fbo;return void(we&&UC(L,T,le,we,null))}}},fill:function(L,k,T,B){const K=T.paint.get("fill-color"),Q=T.paint.get("fill-opacity");if(Q.constantOr(1)===0)return;const le=T.paint.get("fill-emissive-strength"),me=L.colorModeForDrapableLayerRenderPass(le),we=T.paint.get("fill-pattern"),Me=L.opaquePassEnabledForLayer()&&!we.constantOr(1)&&K.constantOr(o.C.transparent).a===1&&Q.constantOr(0)===1?"opaque":"translucent";let Re="none";T.layout.get("fill-elevation-reference")!=="none"?Re="road":T.paint.get("fill-z-offset").constantOr(1)!==0&&(Re="offset");const Ze=!(!L.terrain||!L.terrain.enabled),Qe={painter:L,sourceCache:k,layer:T,coords:B,colorMode:me,elevationType:Re,terrainEnabled:Ze,pass:Me};if(L.renderPass==="shadow")return void(L.shadowRenderer&&Re==="road"&&!Ze&&Ui.drawElevatedFillShadows&&Ui.drawElevatedFillShadows(Qe));const ht=L.isEmissiveMrtActive();if(Re!=="offset"){if(qC(Qe,!1,ht),Re==="road"){const _t=!Ze&&L.renderPass==="translucent";_t&&Ui.drawDepthPrepass&&Ui.drawDepthPrepass(L,k,T,B,"geometry"),qC(Qe,!0,ht,o._.disabled),_t&&Ui.drawElevatedStructures&&Ui.drawElevatedStructures(Qe)}}else qC(Qe,!1,ht,L.stencilModeFor3D())},"fill-extrusion":function(L,k,T,B){const K=T.paint.get("fill-extrusion-opacity"),Q=L.context,le=Q.gl,me=L.terrain,we=me&&me.renderingToTexture;if(K===0)return;const Me=L.isEmissiveMrtActive(),Re=L.conflationActive&&L.style.isLayerClipped(T,k.getSource()),Ze=L.style.order.indexOf(T.fqid);if(Re&&function(Qe,ht,_t,bt,Mt){for(const es of bt){const Qt=ht.getTile(es).getBucket(_t);Qt&&(Qt.updateReplacement(es,Qe.replacementSource,Mt),Qt.uploadCentroid(Qe.context))}}(L,k,T,B,Ze),me||Re)for(const Qe of B){const ht=k.getTile(Qe).getBucket(T);ht&&Ts(L.context,k,Qe,ht,T,me,Re)}if(L.renderPass==="shadow"&&L.shadowRenderer){if(me&&K<.65&&T._transitionablePaint._values["fill-extrusion-opacity"].value.expression instanceof o.ak)return;const Qe=L.shadowRenderer.getShadowPassDepthMode();Va(L,k,T,B,Qe,o._.disabled,o.a1.disabled,Re)}else if(L.renderPass==="translucent"){const Qe=!T.paint.get("fill-extrusion-pattern").constantOr(1),ht=T.paint.get("fill-extrusion-color").constantOr(o.C.white);if(!we&&ht.a!==0){const bt=new o.Z(L.context.gl.LEQUAL,o.Z.ReadWrite,L.depthRangeFor3D);K===1&&Qe?Va(L,k,T,B,bt,o._.disabled,o.a1.unblended,Re):(Va(L,k,T,B,bt,o._.disabled,o.a1.disabled,Re),Va(L,k,T,B,bt,L.stencilModeFor3D(),L.colorModeForRenderPass(),Re),L.resetStencilClippingMasks())}const _t=L.style.enable3dLights()&&Qe&&(!me&&L.transform.projection.name!=="globe"||we);if(_t&&!br.drawGroundEffect&&vr(),_t&&br.drawGroundEffect){const bt=T.paint.get("fill-extrusion-opacity"),Mt=T.paint.get("fill-extrusion-ambient-occlusion-intensity"),es=T.paint.get("fill-extrusion-ambient-occlusion-ground-radius"),Qt=T.paint.get("fill-extrusion-flood-light-intensity"),Lt=T.paint.get("fill-extrusion-flood-light-color-use-theme").constantOr("default")==="none",ps=T.paint.get("fill-extrusion-flood-light-color").toNonPremultipliedRenderColor(Lt?null:T.lut).toArray01().slice(0,3),Hs=Mt>0&&es>0,Fs=Qt>0,nn=new Je;nn.translate=T.paint.get("fill-extrusion-translate"),nn.translateAnchor=T.paint.get("fill-extrusion-translate-anchor"),nn.edgeRadius=T.layout.get("fill-extrusion-edge-radius"),nn.cutoffFadeRange=T.paint.get("fill-extrusion-cutoff-fade-range");const $s=rn=>{const _n=L.depthModeForSublayer(1,o.Z.ReadOnly,le.LEQUAL,!0),Mn=T.paint.get(rn?"fill-extrusion-ambient-occlusion-ground-attenuation":"fill-extrusion-flood-light-ground-attenuation"),Yn=o.am(.1,3,Mn),$n=L._showOverdrawInspector;if(!$n){const zn=new o._({func:le.ALWAYS,mask:255},255,255,le.KEEP,le.KEEP,le.REPLACE),Dr=new o.a1([le.ONE,le.ONE,le.ONE,le.ONE],o.C.transparent,[!1,!1,!1,!0],le.MIN);br.drawGroundEffect(nn,L,k,T,B,_n,zn,Dr,o.$.disabled,rn,"sdf",bt,Mt,es,Qt,ps,Yn,Re,!1)}{const zn=$n?o._.disabled:new o._({func:le.EQUAL,mask:255},255,255,le.KEEP,le.DECR,le.DECR),Dr=$n?L.colorModeForRenderPass():new o.a1([le.ONE_MINUS_DST_ALPHA,le.DST_ALPHA,le.ONE,le.ONE],o.C.transparent,[!0,!0,!0,!0]);br.drawGroundEffect(nn,L,k,T,B,_n,zn,Dr,o.$.disabled,rn,"color",bt,Mt,es,Qt,ps,Yn,Re,!1)}};if(we){const rn=()=>{const Mn=me.drapeBufferSize[0],Yn=me.drapeBufferSize[1];let $n=me.framebufferCopyTexture;return $n&&(!$n||$n.size[0]===Mn&&$n.size[1]===Yn)||($n&&$n.destroy(),$n=me.framebufferCopyTexture=new o.T(Q,new o.b({width:Mn,height:Yn}),le.RGBA8)),$n.bind(le.LINEAR,le.CLAMP_TO_EDGE),le.copyTexSubImage2D(le.TEXTURE_2D,0,0,0,0,0,Mn,Yn),$n},_n=(Mn,Yn,$n)=>{const zn=L.depthModeForSublayer(1,o.Z.ReadOnly,le.LEQUAL,!1),Dr=T.paint.get(Mn?"fill-extrusion-ambient-occlusion-ground-attenuation":"fill-extrusion-flood-light-ground-attenuation"),An=o.am(.1,3,Dr);{const yr=new o.a1([le.ONE,le.ONE,le.ONE,le.ONE],o.C.transparent,[!1,!1,!1,!0]);br.drawGroundEffect(nn,L,k,T,B,zn,o._.disabled,yr,o.$.disabled,Mn,"clear",bt,Mt,es,Qt,ps,An,Re,Yn)}{const yr=new o._({func:le.ALWAYS,mask:255},255,255,le.KEEP,le.KEEP,le.REPLACE),sa=new o.a1([le.ONE,le.ONE,le.ONE,le.ONE],o.C.transparent,[!1,!1,!1,!0],le.MIN);br.drawGroundEffect(nn,L,k,T,B,zn,yr,sa,o.$.disabled,Mn,"sdf",bt,Mt,es,Qt,ps,An,Re,Yn)}Me&&!Mn&&($n=rn());{const yr=Mn?le.ZERO:le.ONE_MINUS_DST_ALPHA,sa=new o._({func:le.EQUAL,mask:255},255,255,le.KEEP,le.DECR,le.DECR),ka=new o.a1([yr,le.DST_ALPHA,le.ONE_MINUS_DST_ALPHA,le.ZERO],o.C.transparent,[!0,!0,!0,!0]);br.drawGroundEffect(nn,L,k,T,B,zn,sa,ka,o.$.disabled,Mn,"color",bt,Mt,es,Qt,ps,An,Re,Yn)}if(!Me||Mn){const yr=new o.a1([le.ONE,le.ONE,le.ONE,Mn?le.ZERO:le.ONE],o.C.transparent,[!1,!1,!1,!0],Mn?le.FUNC_ADD:le.MAX);br.drawGroundEffect(nn,L,k,T,B,zn,o._.disabled,yr,o.$.disabled,Mn,"clear",bt,Mt,es,Qt,ps,An,Re,Yn,$n)}else{le.drawBuffers([le.NONE,le.COLOR_ATTACHMENT1]);const yr=new o._({func:le.EQUAL,mask:255},254,255,le.KEEP,le.DECR,le.DECR),sa=new o.a1([le.ONE,le.ONE,le.ONE,le.ONE],o.C.transparent,[!0,!1,!1,!1],le.MAX);br.drawGroundEffect(nn,L,k,T,B,zn,yr,sa,o.$.disabled,Mn,"emissive",bt,Mt,es,Qt,ps,An,Re,Yn,$n),le.drawBuffers([le.COLOR_ATTACHMENT0])}};if(Hs||Fs){let Mn;L.prepareDrawTile(),Me&&!Hs||(Mn=rn()),Hs&&_n(!0,!1,Mn),Fs&&_n(!1,!0,Mn)}}else Hs&&$s(!0),Fs&&$s(!1),(Hs||Fs)&&L.resetStencilClippingMasks()}}},hillshade:function(L,k,T,B){if(L.renderPass!=="offscreen"&&L.renderPass!=="translucent"||L.style.disableElevatedTerrain)return;const K=L.context,Q=L.terrain&&L.terrain.renderingToTexture,[le,me]=L.renderPass!=="translucent"||Q?[{},B]:L.stencilConfigForOverlap(B);for(const we of me){const Me=k.getTile(we);if(Me.needsHillshadePrepare&&L.renderPass==="offscreen")dh(L,Me,T);else if(L.renderPass==="translucent"){const Re=L.depthModeForSublayer(0,o.Z.ReadOnly),Ze=T.paint.get("hillshade-emissive-strength"),Qe=L.colorModeForDrapableLayerRenderPass(Ze),ht=Q&&L.terrain?L.terrain.stencilModeForRTTOverlap(we):le[we.overscaledZ];np(L,we,Me,T,Re,ht,Qe)}}K.viewport.set([0,0,L.width,L.height]),L.resetStencilClippingMasks()},raster:function(L,k,T,B,K,Q){if(L.renderPass!=="translucent")return;const le=T.paint.get("raster-opacity");if(le===0)return;const me=L.transform.projection.name==="globe",we=T.paint.get("raster-elevation"),Me=T.paint.get("raster-elevation-reference")==="ground",Re=we>0,Ze=L.terrain&&L.terrain.exaggeration()>0&&Re&&Me,Qe=Re&&me,ht=!me&&Ze;if(L.renderElevatedRasterBackface&&!Qe)return;const _t=L.context,bt=_t.gl,Mt=k.getSource(),es=function(Mn,Yn,$n,zn,Dr){const An=$n.paint.get("raster-color"),yr=Yn.type==="raster-array",sa=[],ka=$n.paint.get("raster-resampling"),Hr=$n.paint.get("raster-color-mix");let ea=$n.paint.get("raster-color-range");const si=[Hr[0],Hr[1],Hr[2],0],Wr=Hr[3];let Mr=ka==="nearest"?Dr.NEAREST:Dr.LINEAR;if(yr&&(sa.push("RASTER_ARRAY"),An||sa.push("RASTER_COLOR"),ka==="linear"&&sa.push("RASTER_ARRAY_LINEAR"),Mr=Dr.NEAREST,An&&$n.paint.get("raster-color-scale")==="log"&&sa.push("RASTER_COLOR_SCALE_LOG"),!ea&&Yn.rasterLayers)){const Gr=Yn.rasterLayers.find(({id:Ga})=>Ga===$n.sourceLayer);Gr&&Gr.fields&&Gr.fields.range&&(ea=Gr.fields.range)}if(ea=ea||[0,1],An){sa.push("RASTER_COLOR"),zn.activeTexture.set(Dr.TEXTURE2),$n.updateColorRamp(ea);let Gr=$n.colorRampTexture;Gr||(Gr=$n.colorRampTexture=new o.T(zn,$n.colorRamp,Dr.RGBA8)),Gr.bind(Mr,Dr.CLAMP_TO_EDGE)}return Mn.terrain&&Mn.terrain.renderingToTexture&&Mn.isEmissiveMrtActive()&&(sa.push("USE_MRT1"),Mn.emissiveMode==="mrt-full-rgba"&&sa.push("USE_MRT1_RGBA")),{mix:si,range:ea,offset:Wr,defines:sa,resampling:Mr}}(L,Mt,T,_t,bt);if(Mt instanceof Fi&&!B.length&&!me)return;const Qt=T.paint.get("raster-emissive-strength"),Lt=L.colorModeForDrapableLayerRenderPass(Qt),ps=L.terrain&&L.terrain.renderingToTexture,Hs=!L.options.moving,Fs=T.paint.get("raster-resampling")==="nearest"?bt.NEAREST:bt.LINEAR;if(Mt instanceof Fi&&!B.length&&(Mt.onNorthPole||Mt.onSouthPole)){const Mn=Re?L.stencilModeFor3D():o._.disabled;return void L3(we,!!Mt.onNorthPole,null,L,k,T,Qt,es,o.$.disabled,Mn)}if(!B.length)return;const[nn,$s]=Mt instanceof Fi||ps?[{},B]:L.stencilConfigForOverlap(B),rn=$s.at(-1).overscaledZ;Qe&&es.defines.push("PROJECTION_GLOBE_VIEW"),Re&&es.defines.push("RENDER_CUTOFF","ELEVATED"),Ze&&es.defines.push("ELEVATION_REFERENCE_GROUND");const _n=(Mn,Yn,$n)=>{for(const zn of Mn){const Dr=zn.toUnwrapped(),An=k.getTile(zn);if(ps&&(!An||!An.hasData()))continue;_t.activeTexture.set(bt.TEXTURE0);const yr=XT(An,Mt,T,es);if(!yr||!yr.texture)continue;const{texture:sa,mix:ka,offset:Hr,tileSize:ea,buffer:si}=yr;let Wr,Mr;ps?(Wr=o.Z.disabled,Mr=zn.projMatrix):Re?(Wr=new o.Z(bt.LEQUAL,o.Z.ReadWrite,L.depthRangeFor3D),Mr=me?L.transform.expandedFarZProjMatrix:L.transform.calculateProjMatrix(Dr,Hs)):(Wr=L.depthModeForSublayer(zn.overscaledZ-rn,le===1?o.Z.ReadWrite:o.Z.ReadOnly,bt.LESS),Mr=L.transform.calculateProjMatrix(Dr,Hs));const Gr=L.terrain&&ps?L.terrain.stencilModeForRTTOverlap(zn):nn[zn.overscaledZ],Ga=Q?0:T.paint.get("raster-fade-duration");An.registerFadeDuration(Ga);const Vr=k.findLoadedParent(zn,0),Za=Ed(An,Vr,k,L.transform,Ga);let Oi,Do;!Za.isFading&&An.refreshedUponExpiration&&(An.refreshedUponExpiration=!1),L.terrain&&L.terrain.prepareDrawTile(),_t.activeTexture.set(bt.TEXTURE0),sa.bind(Fs,bt.CLAMP_TO_EDGE),_t.activeTexture.set(bt.TEXTURE1),Vr?(Vr.texture&&Vr.texture.bind(Fs,bt.CLAMP_TO_EDGE),Oi=Math.pow(2,Vr.tileID.overscaledZ-An.tileID.overscaledZ),Do=[An.tileID.canonical.x*Oi%1,An.tileID.canonical.y*Oi%1]):sa.bind(Fs,bt.CLAMP_TO_EDGE),"useMipmap"in sa&&_t.extTextureFilterAnisotropic&&L.transform.pitch>20&&bt.texParameterf(bt.TEXTURE_2D,_t.extTextureFilterAnisotropic.TEXTURE_MAX_ANISOTROPY_EXT,_t.extTextureFilterAnisotropicMax);const so=L.transform;let Vl;const bu=Re?$6(so):[0,0,0,0];let qc,Ko,no,jd,Yh,wh=0;if(Qe&&Mt instanceof Fi&&Mt.coordinates.length>3)qc=Float32Array.from(o.b5(o.b6(new o.bW(0,0,0)))),Ko=Float32Array.from(so.globeMatrix),no=Float32Array.from(o.b7(so)),jd=[o.a7(so.center.lng),o.a8(so.center.lat)],Vl=Mt.elevatedGlobePerspectiveTransform,Yh=Mt.elevatedGlobeGridMatrix||new Float32Array(9);else if(Qe){const rc=o.b3(zn.canonical);wh=o.b4(rc.getCenter().lat),qc=Float32Array.from(o.b5(o.b6(zn.canonical))),Ko=Float32Array.from(so.globeMatrix),no=Float32Array.from(o.b7(so)),jd=[o.a7(so.center.lng),o.a8(so.center.lat)],Vl=[0,0],Yh=Float32Array.from(o.b8(zn.canonical,rc,wh,so.worldSize/so._pixelsPerMercatorPixel))}else Vl=Mt instanceof Fi?Mt.perspectiveTransform:[0,0],qc=new Float32Array(16),Ko=new Float32Array(9),no=new Float32Array(16),jd=[0,0],Yh=new Float32Array(9);const Hl=ks(L,Mr,qc,Ko,no,Yh,Do||[0,0],o.S(L.transform.zoom),jd,bu,Oi||1,Za,T,Vl,we,2,ka,Hr,es.range,ea,si,Qt),fm=L.isTileAffectedByFog(zn),bc=L.getOrCreateProgram("raster",{defines:es.defines,overrideFog:fm});if(L.uploadCommonUniforms(_t,bc,Dr),Mt instanceof Fi){const rc=Mt.elevatedGlobeVertexBuffer,Oh=Mt.elevatedGlobeIndexBuffer;if(ps||!me)Mt.boundsBuffer&&Mt.boundsSegments&&bc.draw(L,bt.TRIANGLES,Wr,o._.disabled,Lt,o.$.disabled,Hl,T.id,Mt.boundsBuffer,L.quadTriangleIndexBuffer,Mt.boundsSegments);else if(rc&&Oh){const Zh=so.zoom<=o.ef?Mt.elevatedGlobeSegments:Mt.getSegmentsForLongitude(so.center.lng);Zh&&bc.draw(L,bt.TRIANGLES,Wr,o._.disabled,Lt,Yn,Hl,T.id,rc,Oh,Zh)}}else if(Qe){Wr=new o.Z(bt.LEQUAL,o.Z.ReadOnly,L.depthRangeFor3D);const rc=L.globeSharedBuffers;if(rc){Ze&&(L.terrain.setupElevationDraw(An,bc),L.uploadCommonUniforms(_t,bc,An.tileID.toUnwrapped()));const[Oh,Zh,Ld]=rc.getGridBuffers(wh,!1),_c=bc.getAttributeLocation(bt,"a_texture_pos");_c!==-1&&bt.vertexAttribI4ui(_c,0,0,0,0),bc.draw(L,bt.TRIANGLES,Wr,$n||Gr,L.colorModeForRenderPass(),Yn,Hl,T.id,Oh,Zh,Ld)}}else if(ht)Wr=new o.Z(bt.LEQUAL,o.Z.ReadOnly,L.depthRangeFor3D),L.terrain.setupElevationDraw(An,bc),L.uploadCommonUniforms(_t,bc,An.tileID.toUnwrapped()),so.pitch>20&&bc.draw(L,bt.TRIANGLES,Wr,o._.disabled,o.a1.disabled,o.$.frontCCW,Hl,T.id,L.terrain.gridBuffer,L.terrain.gridIndexBuffer,L.terrain.gridSegments),bc.draw(L,bt.TRIANGLES,Wr,Gr,Lt,o.$.backCCW,Hl,T.id,L.terrain.gridBuffer,L.terrain.gridIndexBuffer,L.terrain.gridSegments);else{const{tileBoundsBuffer:rc,tileBoundsIndexBuffer:Oh,tileBoundsSegments:Zh}=L.getTileBoundsBuffers(An);bc.draw(L,bt.TRIANGLES,Wr,Gr,Lt,o.$.disabled,Hl,T.id,rc,Oh,Zh)}}if(!(Mt instanceof Fi)&&Qe)for(const zn of Mn){const Dr=zn.canonical.y===(1<nn.tileID)),ht&&(Me.activeTexture.set(Re.TEXTURE0),L.imageManager.bind(L.context,T.scope));const Fs=[];if(L.terrain&&L.terrain.renderingToTexture&&L.isEmissiveMrtActive()&&(Fs.push("USE_MRT1"),L.emissiveMode==="mrt-full-rgba"&&Fs.push("USE_MRT1_RGBA")),we){const nn=L.getOrCreateProgram(Lt,{overrideFog:!1,overrideRtt:!0,defines:Fs}),$s=U6,rn=new o.bQ(0,0,0,0,0),_n=ht?Xn($s,me,le,L,ht,T.scope,_t,we,{tileID:rn,tileSize:Qe}):on($s,me,le,K.toPremultipliedRenderColor(Q?null:T.lut));return void nn.draw(L,Re.TRIANGLES,es,Mt,Qt,o.$.disabled,_n,T.id,L.viewportBuffer,L.quadTriangleIndexBuffer,L.viewportSegments)}for(const nn of Hs){const $s=L.isTileAffectedByFog(nn),rn=L.getOrCreateProgram(Lt,{overrideFog:$s,defines:Fs}),_n=nn.toUnwrapped(),Mn=B?nn.projMatrix:L.transform.calculateProjMatrix(_n);L.prepareDrawTile();const Yn=k?k.getTile(nn):ps?ps[nn.key]:new Rx(nn,Qe,Ze.zoom,L),$n=ht?Xn(Mn,me,le,L,ht,T.scope,_t,we,{tileID:nn,tileSize:Qe}):on(Mn,me,le,K.toPremultipliedRenderColor(Q?null:T.lut));L.uploadCommonUniforms(Me,rn,_n);const{tileBoundsBuffer:zn,tileBoundsIndexBuffer:Dr,tileBoundsSegments:An}=L.getTileBoundsBuffers(Yn);rn.draw(L,Re.TRIANGLES,es,Mt,Qt,o.$.disabled,$n,T.id,zn,Dr,An)}},sky:function(L,k,T){const B=L._atmosphere?o.S(L.transform.zoom):1,K=T.paint.get("sky-opacity")*B;if(K===0)return;const Q=L.context,le=T.paint.get("sky-type"),me=new o.Z(Q.gl.LEQUAL,o.Z.ReadOnly,[0,1]),we=L.frameCounter/1e3%1;le==="atmosphere"?L.renderPass==="offscreen"?T.needsSkyboxCapture(L)&&(function(Me,Re){const Ze=Me.context,Qe=Ze.gl;let ht=Re.skyboxFbo;if(!ht){ht=Re.skyboxFbo=Ze.createFramebuffer(32,32,1,null),Re.skyboxGeometry=new de(Ze),Re.skyboxTexture=Ze.gl.createTexture(),Qe.bindTexture(Qe.TEXTURE_CUBE_MAP,Re.skyboxTexture),Qe.texParameteri(Qe.TEXTURE_CUBE_MAP,Qe.TEXTURE_WRAP_S,Qe.CLAMP_TO_EDGE),Qe.texParameteri(Qe.TEXTURE_CUBE_MAP,Qe.TEXTURE_WRAP_T,Qe.CLAMP_TO_EDGE),Qe.texParameteri(Qe.TEXTURE_CUBE_MAP,Qe.TEXTURE_MIN_FILTER,Qe.LINEAR),Qe.texParameteri(Qe.TEXTURE_CUBE_MAP,Qe.TEXTURE_MAG_FILTER,Qe.LINEAR);for(let es=0;es<6;++es)Qe.texImage2D(Qe.TEXTURE_CUBE_MAP_POSITIVE_X+es,0,Qe.RGBA,32,32,0,Qe.RGBA,Qe.UNSIGNED_BYTE,null)}Ze.bindFramebuffer.set(ht.framebuffer),Ze.viewport.set([0,0,32,32]);const _t=Re.getCenter(Me,!0),bt=Me.getOrCreateProgram("skyboxCapture"),Mt=new Float64Array(16);o.ei(Mt,.5*-Math.PI),Oe(Me,Re,bt,Mt,_t,0),o.ei(Mt,.5*Math.PI),Oe(Me,Re,bt,Mt,_t,1),o.ej(Mt,.5*-Math.PI),Oe(Me,Re,bt,Mt,_t,2),o.ej(Mt,.5*Math.PI),Oe(Me,Re,bt,Mt,_t,3),o.df(Mt),Oe(Me,Re,bt,Mt,_t,4),o.ei(Mt,Math.PI),Oe(Me,Re,bt,Mt,_t,5),Ze.viewport.set([0,0,Me.width,Me.height])}(L,T),T.markSkyboxValid(L)):L.renderPass==="sky"&&function(Me,Re,Ze,Qe,ht){const _t=Me.context,bt=_t.gl,Mt=Me.transform,es=Me.getOrCreateProgram("skybox");_t.activeTexture.set(bt.TEXTURE0),bt.bindTexture(bt.TEXTURE_CUBE_MAP,Re.skyboxTexture);const Qt=((Lt,ps,Hs,Fs,nn)=>({u_matrix:Lt,u_sun_direction:ps,u_cubemap:0,u_opacity:Fs,u_temporal_offset:nn}))(Mt.skyboxMatrix,Re.getCenter(Me,!1),0,Qe,ht);Me.uploadCommonUniforms(_t,es),es.draw(Me,bt.TRIANGLES,Ze,o._.disabled,Me.colorModeForRenderPass(),o.$.backCW,Qt,"skybox",Re.skyboxGeometry.vertexBuffer,Re.skyboxGeometry.indexBuffer,Re.skyboxGeometry.segment)}(L,T,me,K,we):le==="gradient"&&L.renderPass==="sky"&&function(Me,Re,Ze,Qe,ht){const _t=Me.context,bt=_t.gl,Mt=Me.transform,es=Me.getOrCreateProgram("skyboxGradient");Re.skyboxGeometry||(Re.skyboxGeometry=new de(_t)),_t.activeTexture.set(bt.TEXTURE0);let Qt=Re.colorRampTexture;Qt||(Qt=Re.colorRampTexture=new o.T(_t,Re.colorRamp,bt.RGBA8)),Qt.bind(bt.LINEAR,bt.CLAMP_TO_EDGE);const Lt=((ps,Hs,Fs,nn,$s)=>({u_matrix:ps,u_color_ramp:0,u_center_direction:Hs,u_radius:o.av(Fs),u_opacity:nn,u_temporal_offset:$s}))(Mt.skyboxMatrix,Re.getCenter(Me,!1),Re.paint.get("sky-gradient-radius"),Qe,ht);Me.uploadCommonUniforms(_t,es),es.draw(Me,bt.TRIANGLES,Ze,o._.disabled,Me.colorModeForRenderPass(),o.$.backCW,Lt,"skyboxGradient",Re.skyboxGeometry.vertexBuffer,Re.skyboxGeometry.indexBuffer,Re.skyboxGeometry.segment)}(L,T,me,K,we)},custom:function(L,k,T,B){const K=L.context,Q=T.implementation;if(!L.transform.projection.unsupportedLayers||!L.transform.projection.unsupportedLayers.includes("custom")||L.terrain&&(L.terrain.renderingToTexture||L.renderPass==="offscreen")&&T.isDraped(k)){if(L.renderPass==="offscreen"){const le=Q.prerender;if(le){if(L.setCustomLayerDefaults(),K.setColorMode(L.colorModeForRenderPass()),L.transform.projection.name==="globe"){const me=L.transform.pointMerc;le.call(Q,K.gl,L.transform.customLayerMatrix(),L.transform.getProjection(),L.transform.globeToMercatorMatrix(),o.S(L.transform.zoom),[me.x,me.y],L.transform.pixelsPerMeterRatio)}else le.call(Q,K.gl,L.transform.customLayerMatrix());K.setDirty(),L.setBaseState()}}else if(L.renderPass==="translucent"){if(L.terrain&&L.terrain.renderingToTexture){const me=Q.renderToTile;if(me){const we=B[0].canonical,Me={x:we.x+B[0].wrap*(Q.wrapTileId?0:1<k.getTileByID(me));for(const me of le)me.updateNeeded(L.id,Q)&&B.prepareTile(me,K,L.id,Q)}};async function Zi(L){if(await vr(),Object.assign(Pi,{model:br.drawModels}),Object.assign(gl,{model:br.prepare}),L&&!L._destroyed&&!L._shadowRenderer){const k=br.ShadowRenderer;k&&(L._shadowRenderer=new k(L))}}class Kh{constructor(k,T,B,K,Q,le){this._forceFullRgbaEmissive=!1,this.context=new jm(k,T),this._forceFullRgbaEmissive=le==="exact",this.transform=B,this._tileTextures={},this.frameCopies=[],this.loadTimeStamps=[],this.frcCoverageSnapshot=null,this.elevationCoverageSnapshot=null,this.elevationProvidersReady=void 0,this.frcCoverageFadeRange=null,this.frcCoverageSourceLayers=[],this.frcCoverageRenderer=Ui.FrcCoverageRenderer?new Ui.FrcCoverageRenderer:null,this._debugParams={averageFPS:0,fpsHistory:[],fpsWindow:30,continousRedraw:!1,enabledLayers:{},buildingsShowNormals:!1,buildingsDrawGroundAO:!0,buildingsDrawShadowPass:!0,buildingsDrawTranslucentPass:!0,showTerrainProxyTiles:!1,terrainSortTilesHiZFirst:!0,terrainDisableRenderCache:!1,forceEnablePrecipitation:!1,overrideSnowParams:!1,snowParamsOverride:null,snowRevealParamsOverride:null,snowVignetteParamsOverride:null,overrideRainParams:!1,rainParamsOverride:null,rainRevealParamsOverride:null,rainVignetteParamsOverride:null,overrideStarsParams:!1,starsParamsOverride:null,show3DModelFootprints:!1,showElevationIdDebug:!1,lodSwitchDistance:-1,lodSwitchFadeDuration:.5},this.occlusionParams=new ui,this.setup(),this.numSublayers=Ci.maxUnderzooming+Ci.maxOverzooming+1,this.depthEpsilon=1/Math.pow(2,16),this.deferredRenderGpuTimeQueries=[],this.gpuTimers={},this.frameCounter=0,this.frameTimeDelta=0,this.lastPaintStartTimeStamp=0,this._shadowCullCache=null,this._backgroundTiles={},this.conflationActive=!1,this.replacementSource=new o.ew,this.longestCutoffRange=0,this.minCutoffZoom=0,this._fogVisible=!1,this._cachedTileFogOpacities={},this._wireframeDebugCache=new $r,this.renderDefaultNorthPole=!0,this.renderDefaultSouthPole=!0,this.layersWithOcclusionOpacity=[];const me=new o.b({width:1,height:1},Uint8Array.of(0,0,0,0));this.emptyDepthTexture=new o.T(this.context,me,k.RGBA8),this._clippingActiveLastFrame=!1,this.scaleFactor=K,this.maxFrontCutoffRawStart=0,this.worldview=Q,this._forceEmissiveMode=!1,this.emissiveMode="constant"}updateTerrain(k,T){const B=!!k&&!!k.terrain&&this.transform.projection.supportsTerrain;var K;(B||this._terrain&&this._terrain.enabled)&&(this._terrain||(this._terrain=sx(this,k),this._terrain)?(this.transform.elevation=B?this._terrain:null,this._terrain.update(k,this.transform,T),this.transform.elevation&&!this._terrain.enabled&&(this.transform.elevation=null)):this._terrainRendererRetryPending||(this._terrainRendererRetryPending=!0,K=()=>{this._terrainRendererRetryPending=!1,this.style&&this.style.map&&this.style.map._update(!1)},Q2?K():V_.push(K)))}_updateFog(k){const T=k.fog;if(!T||this.transform.projection.name==="globe"||T.getOpacity(this.transform.pitch)<1||T.properties.get("horizon-blend")<.03)return void(this.transform.fogCullDistSq=null);const[B,K]=T.getRangeForProjection();if(B>K)return void(this.transform.fogCullDistSq=null);const Q=B+.78*(K-B);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(k){k&&!this._terrain&&(this._terrain=sx(this,this.style),this._terrain||console.warn("forceTerrainMode: Lite module not loaded yet, terrain renderer unavailable")),this._forceTerrainMode=k}get shadowRenderer(){return this._shadowRenderer&&this._shadowRenderer.enabled?this._shadowRenderer:null}get wireframeDebugCache(){return this._wireframeDebugCache}resize(k,T){if(this.width=k*o.e.devicePixelRatio,this.height=T*o.e.devicePixelRatio,this.context.viewport.set([0,0,this.width,this.height]),this.style)for(const B of this.style.order)this.style._mergedLayers[B].resize()}setup(){const k=this.context,T=new o.bD;T.emplaceBack(0,0),T.emplaceBack(o.a6,0),T.emplaceBack(0,o.a6),T.emplaceBack(o.a6,o.a6),this.tileExtentBuffer=k.createVertexBuffer(T,o.bF.members),this.tileExtentSegments=o.ad.simpleSegment(0,0,4,2);const B=new o.bD;B.emplaceBack(0,0),B.emplaceBack(o.a6,0),B.emplaceBack(0,o.a6),B.emplaceBack(o.a6,o.a6),this.debugBuffer=k.createVertexBuffer(B,o.bF.members),this.debugSegments=o.ad.simpleSegment(0,0,4,5);const K=new o.bD;K.emplaceBack(-1,-1),K.emplaceBack(1,-1),K.emplaceBack(-1,1),K.emplaceBack(1,1),this.viewportBuffer=k.createVertexBuffer(K,o.bF.members),this.viewportSegments=o.ad.simpleSegment(0,0,4,2);const Q=new o.bt;Q.emplaceBack(0,0,0,0),Q.emplaceBack(o.a6,0,o.a6,0),Q.emplaceBack(0,o.a6,0,o.a6),Q.emplaceBack(o.a6,o.a6,o.a6,o.a6),this.mercatorBoundsBuffer=k.createVertexBuffer(Q,Jc.members),this.mercatorBoundsSegments=o.ad.simpleSegment(0,0,4,2);const le=new o.ae;le.emplaceBack(0,1,2),le.emplaceBack(2,1,3),this.quadTriangleIndexBuffer=k.createIndexBuffer(le);const me=new o.bE;for(const Me of[0,1,3,2,0])me.emplaceBack(Me);this.debugIndexBuffer=k.createIndexBuffer(me),this.emptyTexture=new o.T(k,new o.b({width:1,height:1},Uint8Array.of(0,0,0,0)),k.gl.RGBA8),this.identityMat=o.Y();const we=this.context.gl;this.stencilClearMode=new o._({func:we.ALWAYS,mask:0},0,255,we.ZERO,we.ZERO,we.ZERO),this.loadTimeStamps.push(performance.now())}getMercatorTileBoundsBuffers(){return{tileBoundsBuffer:this.mercatorBoundsBuffer,tileBoundsIndexBuffer:this.quadTriangleIndexBuffer,tileBoundsSegments:this.mercatorBoundsSegments}}getTileBoundsBuffers(k){return k._makeTileBoundsBuffers(this.context,this.transform.projection),k._tileBoundsBuffer?{tileBoundsBuffer:k._tileBoundsBuffer,tileBoundsIndexBuffer:k._tileBoundsIndexBuffer,tileBoundsSegments:k._tileBoundsSegments}:this.getMercatorTileBoundsBuffers()}clearStencil(){const k=this.context.gl;this.nextStencilID=1,this.currentStencilSource=void 0,this._tileClippingMaskIDs={},this.getOrCreateProgram("clippingMask").draw(this,k.TRIANGLES,o.Z.disabled,this.stencilClearMode,o.a1.disabled,o.$.disabled,yu(this.identityMat),"$clipping",this.viewportBuffer,this.quadTriangleIndexBuffer,this.viewportSegments)}resetStencilClippingMasks(){this.terrain||(this.currentStencilSource=void 0,this._tileClippingMaskIDs={})}_renderTileClippingMasks(k,T,B){if(!T||this.currentStencilSource===T.id||!k.isTileClipped()||!B||B.length===0)return;if(this._tileClippingMaskIDs&&!this.terrain){let me=!1;for(const we of B)if(this._tileClippingMaskIDs[we.key]===void 0){me=!0;break}if(!me)return}this.currentStencilSource=T.id;const K=this.context,Q=K.gl;this.nextStencilID+B.length>256&&this.clearStencil(),K.setColorMode(o.a1.disabled),K.setDepthMode(o.Z.disabled);const le=this.getOrCreateProgram("clippingMask");this._tileClippingMaskIDs={};for(const me of B){const we=T.getTile(me),Me=this._tileClippingMaskIDs[me.key]=this.nextStencilID++,{tileBoundsBuffer:Re,tileBoundsIndexBuffer:Ze,tileBoundsSegments:Qe}=this.getTileBoundsBuffers(we);le.draw(this,Q.TRIANGLES,o.Z.disabled,new o._({func:Q.ALWAYS,mask:0},Me,255,Q.KEEP,Q.KEEP,Q.REPLACE),o.a1.disabled,o.$.disabled,yu(me.projMatrix),"$clipping",Re,Ze,Qe)}}stencilModeFor3D(){this.currentStencilSource=void 0,this.nextStencilID+1>256&&this.clearStencil();const k=this.nextStencilID++,T=this.context.gl;return new o._({func:T.NOTEQUAL,mask:255},k,255,T.KEEP,T.KEEP,T.REPLACE)}stencilModeForClipping(k){if(this.terrain)return this.terrain.stencilModeForRTTOverlap(k);const T=this.context.gl;return new o._({func:T.EQUAL,mask:255},this._tileClippingMaskIDs[k.key],0,T.KEEP,T.KEEP,T.REPLACE)}stencilConfigForOverlap(k){const T=this.context.gl,B=k.sort((le,me)=>me.overscaledZ-le.overscaledZ),K=B.at(-1).overscaledZ,Q=B[0].overscaledZ-K+1;if(Q>1){this.currentStencilSource=void 0,this.nextStencilID+Q>256&&this.clearStencil();const le={};for(let me=0;methis.style._getOrder(K);let le=Q(),me=!1,we=!1,Me=null,Re=0,Ze=!1;for(const An of le){const yr=B[An];yr.visibility!=="none"&&(yr.type==="circle"?me=!0:yr.type==="building"?(Me=yr,++Re):yr.type==="symbol"&&(yr.hasOcclusionOpacityProperties?we=!0:me=!0))}this.updateEmissiveMode();let Qe=le.map(An=>B[An]);const ht=this.style._mergedSourceCaches;this.imageManager=k.imageManager,this.modelManager=k.modelManager,this.symbolFadeChange=k.placement.symbolFadeChange(o.e.now()),this.imageManager.beginFrame();for(const An in ht){const yr=ht[An];yr.used&&(yr.prepare(this.context),yr.getSource().usedInConflation&&++Re)}let _t=!1;for(const An of Qe)An.isHidden(this.transform.zoom)||(An.type==="clip"&&(_t=!0),this.prepareLayer(An));const bt={},Mt={},es={},Qt={},Lt={};for(const An in ht){const yr=ht[An];bt[An]=yr.getVisibleCoordinates(),Mt[An]=bt[An].slice().reverse(),es[An]=yr.getVisibleCoordinates(!0).reverse(),Qt[An]=yr.getShadowCasterCoordinates(),Lt[An]=yr.sortCoordinatesByDistance(bt[An])}const ps=An=>{const yr=this.style.getLayerSourceCache(An);return yr&&yr.used?yr.getSource():null};if(Re||_t||this._clippingActiveLastFrame){const An=[],yr=[];let sa=0;for(const ka of Qe)this.isSourceForClippingOrConflation(ka,ps(ka))&&(An.push(ka),yr.push(sa)),sa++;if(An&&(_t||An.length>1)||this._clippingActiveLastFrame){_t=!1;const ka=[];for(let Hr=0;Hr0){const ka=ps(yr);ka&&(this.minCutoffZoom=Math.max(ka.minzoom,this.minCutoffZoom)),yr.minzoom&&(this.minCutoffZoom=Math.max(yr.minzoom,this.minCutoffZoom))}yr.is3D(K)&&(this.opaquePassCutoff===1/0&&(this.opaquePassCutoff=An),this._lastOcclusionLayer=An)}const Hs=this.style&&this.style.fog;Hs?(this._fogVisible=Hs.getOpacity(this.transform.pitch)!==0,this._fogVisible&&this.transform.projection.name!=="globe"&&(this._fogVisible=Hs.isVisibleOnFrustum(this.transform.cameraFrustum))):this._fogVisible=!1,this._cachedTileFogOpacities={},this.terrain&&(this.terrain.updateTileBinding(es),this.opaquePassCutoff=0,le=Q(),Qe=le.map(An=>B[An])),this.style.enable3dLights()&&!this._shadowRenderer&&Zi(this);const Fs=this._shadowRenderer;if(Fs){Fs.updateShadowParameters(this.transform,this.style.directionalLight,Qt);for(const An in ht)for(const yr of bt[An]){let sa={min:0,max:0};this.terrain&&(sa=this.terrain.getMinMaxForTile(yr)||sa),Fs.addShadowReceiver(yr.toUnwrapped(),sa.min,sa.max)}}this.transform.projection.name!=="globe"||this.globeSharedBuffers||(this.globeSharedBuffers=new o.ey(this.context)),this.style.fog&&this.transform.projection.supportsFog?(this._atmosphere||(this._atmosphere=new Ks),this._atmosphere.update(this)):this._atmosphere&&(this._atmosphere.destroy(),this._atmosphere=void 0);let nn=!(!this.style||!this.style.snow),$s=!(!this.style||!this.style.rain);if(nn&&!this._snow&&Ui.Snow&&(this._snow=new Ui.Snow),!nn&&this._snow&&(this._snow.destroy(),delete this._snow),$s&&!this._rain&&Ui.Rain&&(this._rain=new Ui.Rain),!$s&&this._rain&&(this._rain.destroy(),delete this._rain),this._snow&&this._snow.update(this),this._rain&&this._rain.update(this),Me&&(!this.buildingTileBorderManager&&Ui.BuildingTileBorderManager&&(this.buildingTileBorderManager=new Ui.BuildingTileBorderManager),this.buildingTileBorderManager)){const An=this.style.getLayerSourceCache(Me);this.buildingTileBorderManager.updateBorders(An,Me)}if(!o.ez(this.context.gl))return;this.renderPass="offscreen";for(const An of Qe){const yr=k.getLayerSourceCache(An);if(!An.hasOffscreenPass()||An.isHidden(this.transform.zoom))continue;const sa=yr?Mt[yr.id]:void 0;(An.type==="custom"||An.type==="raster"||An.type==="raster-particle"||An.isSky()||sa&&sa.length)&&this.renderLayer(this,yr,An,sa)}this.depthRangeFor3D=[0,1-(Qe.length+2)*this.numSublayers*this.depthEpsilon],this._shadowRenderer&&(this.renderPass="shadow",this._shadowRenderer.drawShadowPass(this.style,Qt)),this.context.bindFramebuffer.set(null),this.context.viewport.set([0,0,this.width,this.height]);const rn=this.transform.projection.name==="globe"||this.transform.isHorizonVisible(),_n=(()=>{if(T.showOverdrawInspector)return o.C.black;const An=this.style.fog;if(An&&this.transform.projection.supportsFog){const yr=this.style.getLut(An.scope);if(!rn){const sa=An.properties.get("color-use-theme")==="none",ka=An.properties.get("color").toNonPremultipliedRenderColor(sa?null:yr).toArray01();return new o.C(...ka)}if(rn){const sa=An.properties.get("space-color-use-theme")==="none",ka=An.properties.get("space-color").toNonPremultipliedRenderColor(sa?null:yr).toArray01();return new o.C(...ka)}}return o.C.transparent})();if(this.context.clear({color:_n,depth:1}),this.clearStencil(),this._showOverdrawInspector=T.showOverdrawInspector,this.renderPass="opaque",this.style.fog&&this.transform.projection.supportsFog&&this._atmosphere&&!this._showOverdrawInspector&&rn&&this._atmosphere.drawStars(this,this.style.fog),!this.terrain)for(this.currentLayer=le.length-1;this.currentLayer>=0;this.currentLayer--){const An=Qe[this.currentLayer],yr=k.getLayerSourceCache(An);if(An.isSky())continue;const sa=yr?(An.is3D(K)?Lt:Mt)[yr.id]:void 0;this._renderTileClippingMasks(An,yr,sa),this.renderLayer(this,yr,An,sa)}if(this.style.fog&&this.transform.projection.supportsFog&&this._atmosphere&&!this._showOverdrawInspector&&rn&&this._atmosphere.drawAtmosphereGlow(this,this.style.fog),this.renderPass="sky",(!this._atmosphere||o.S(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 sa=this.currentLayer;this.depthOcclusion=!0;for(const ka of this.layersWithOcclusionOpacity){this.currentLayer=ka;const Hr=Qe[this.currentLayer],ea=k.getLayerSourceCache(Hr),si=ea?Mt[ea.id]:void 0;this.terrain||this._renderTileClippingMasks(Hr,ea,ea?bt[ea.id]:void 0),this.renderLayer(this,ea,Hr,si)}this.depthOcclusion=!1,this.currentLayer=sa,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 An=null;Qe.forEach(yr=>{const sa=k.getLayerSourceCache(yr);sa&&!yr.isHidden(this.transform.zoom)&&sa.getVisibleCoordinates().length&&(!An||An.getSource().maxzoom0?T.pop():null}terrainRenderModeElevated(){return this.style&&this.style.hasTerrain()&&!!this.terrain&&!this.terrain.renderingToTexture||this.forceTerrainMode}linearFloatFilteringSupported(){return this.context.extTextureFloatLinear!=null}currentGlobalDefines(k,T,B,K,Q){const le=B===void 0?!!this._terrain&&this._terrain.renderingToTexture:B,me=K===void 0?this.terrainRenderModeElevated():K,we=Q===void 0?this.transform.projection.name==="globe":Q,Me=[];return this.style&&this.style.enable3dLights()&&(k==="globeRaster"||k==="terrainRaster"?(Me.push("LIGHTING_3D_MODE"),Me.push("LIGHTING_3D_ALPHA_EMISSIVENESS"),this.emissiveMode==="mrt-full-rgba"&&Me.push("USE_MRT1_RGBA")):le||Me.push("LIGHTING_3D_MODE")),me&&(Me.push("TERRAIN"),this.linearFloatFilteringSupported()&&Me.push("TERRAIN_DEM_FLOAT_FORMAT")),we&&Me.push("GLOBE"),!this._fogVisible||le||T!==void 0&&!T||Me.push("FOG"),le&&Me.push("RENDER_TO_TEXTURE"),this._showOverdrawInspector&&Me.push("OVERDRAW_INSPECTOR"),Me}getOrCreateProgram(k,T){this.cache=this.cache||{};const{defines:B,config:K,overrideFog:Q,overrideRtt:le,overrideTerrain:me,overrideGlobe:we,precompiled:Me}=T||{},Re=this.currentGlobalDefines(k,Q,le,me,we).concat(B||[]),Ze=this.getShaderSource(k),Qe=Ui.programUniforms,ht=br.programUniforms,_t=Cr[k]||Qe&&Qe[k]||ht&&ht[k],bt=tN.cacheKey(Ze,k,Re,K);return this.cache[bt]||(this.cache[bt]=new tN(this.context,k,Ze,K,_t,Re,Me)),this.cache[bt]}getShaderSource(k){const T=Ui.shaders,B=br.shaders,K=lr.shaders;return o.eA[k]||T&&T[k]||B&&B[k]||K&&K[k]}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 k=this.context.gl;this.context.cullFace.set(!1),this.context.viewport.set([0,0,this.width,this.height]),this.context.blendEquation.set(k.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(),this._destroyed=!0}prepareDrawTile(){this.terrain&&this.terrain.prepareDrawTile()}uploadCommonLightUniforms(k,T,B){if(this.style.enable3dLights()){const K=this.style.directionalLight,Q=this.style.ambientLight;if(K&&Q){const le=((me,we,Me,Re)=>{const Ze=me.properties.get("direction"),Qe=me.properties.get("color-use-theme")==="none",ht=me.properties.get("color").toNonPremultipliedRenderColor(Qe?null:Me.getLut(me.scope)).toArray01();let _t=me.properties.get("intensity");const bt=we.properties.get("color-use-theme")==="none",Mt=we.properties.get("color").toNonPremultipliedRenderColor(bt?null:Me.getLut(we.scope)).toArray01();let es=we.properties.get("intensity");const Qt=[Ze.x,Ze.y,Ze.z];Re&&(Re.ambientIntensity!==void 0&&(es=Re.ambientIntensity),Re.directionalIntensity!==void 0&&(_t=Re.directionalIntensity),Re.ambientColor!==void 0&&(Mt[0]=Re.ambientColor[0],Mt[1]=Re.ambientColor[1],Mt[2]=Re.ambientColor[2]),Re.directionalColor!==void 0&&(ht[0]=Re.directionalColor[0],ht[1]=Re.directionalColor[1],ht[2]=Re.directionalColor[2]));const Lt=o.dU(Mt,es),ps=o.dU(ht,_t);return{u_lighting_ambient_color:Lt,u_lighting_directional_dir:Qt,u_lighting_directional_color:ps,u_ground_radiance:eN(Qt,ps,Lt)}})(K,Q,this.style,B);T.setLightsUniformValues(k,le)}}}uploadCommonUniforms(k,T,B,K,Q,le){if(this.uploadCommonLightUniforms(k,T,le),this.terrain&&this.terrain.renderingToTexture)return;const me=this.style.fog;if(me){const we=me.getOpacity(this.transform.pitch),Me=((Re,Ze,Qe,ht,_t,bt,Mt,es,Qt,Lt,ps,Hs)=>{const Fs=Re.transform,nn=Ze.properties.get("color-use-theme")==="none",$s=Ze.properties.get("color").toNonPremultipliedRenderColor(nn?null:Re.style.getLut(Ze.scope)).toArray01();$s[3]=ht;const rn=Re.frameCounter/1e3%1,[_n,Mn]=Ze.properties.get("vertical-range");return{u_fog_matrix:Qe?Fs.calculateFogTileMatrix(Qe):Hs||Re.identityMat,u_fog_range:Ze.getRangeForProjection(),u_fog_color:$s,u_fog_horizon_blend:Ze.properties.get("horizon-blend"),u_fog_vertical_limit:[Math.min(_n,Mn),Mn],u_fog_temporal_offset:rn,u_frustum_tl:_t,u_frustum_tr:bt,u_frustum_br:Mt,u_frustum_bl:es,u_globe_pos:Qt,u_globe_radius:Lt,u_viewport:ps,u_globe_transition:o.S(Fs.zoom),u_is_globe:+(Fs.projection.name==="globe")}})(this,me,B,we,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.e.devicePixelRatio,this.transform.height*o.e.devicePixelRatio],K);T.setFogUniformValues(k,Me)}Q&&T.setCutoffUniformValues(k,Q.uniformValues)}setTileLoadedFlag(k){this.tileLoaded=k}saveCanvasCopy(){const k=this.canvasCopy();k&&(this.frameCopies.push(k),this.tileLoaded=!1)}canvasCopy(){const k=this.context.gl,T=k.createTexture();return k.bindTexture(k.TEXTURE_2D,T),k.copyTexImage2D(k.TEXTURE_2D,0,k.RGBA,0,0,k.drawingBufferWidth,k.drawingBufferHeight,0),T}getCanvasCopiesAndTimestamps(){return{canvasCopies:this.frameCopies,timeStamps:this.loadTimeStamps}}averageElevationNeedsEasing(){if(!this.transform._elevation)return!1;const k=this.style&&this.style.fog;return!!k&&k.getOpacity(this.transform.pitch)!==0}getBackgroundTiles(){const k=this._backgroundTiles,T=this._backgroundTiles={},B=this.transform.coveringTiles({tileSize:512});for(const K of B)T[K.key]=k[K.key]||new Rx(K,512,this.transform.tileZoom,this,void 0,this.worldview);return T}clearBackgroundTiles(){this._backgroundTiles={}}isSourceForClippingOrConflation(k,T){return!(!k.is3D(!(!this.terrain||!this.terrain.enabled))||k.type!=="clip"&&k.type!=="building"&&(k.minzoom&&k.minzoom>this.transform.zoom||(this.style._clipLayerPresent||k.sourceLayer!=="building"&&k.sourceLayer!=="procedural_buildings")&&(!T||T.type!=="batched-model")))}isTileAffectedByFog(k){if(!this.style||!this.style.fog)return!1;if(this.transform.projection.name==="globe")return!0;let T=this._cachedTileFogOpacities[k.key];return T||(this._cachedTileFogOpacities[k.key]=T=this.style.fog.getOpacityForTile(k)),T[0]>=o.au||T[1]>=o.au}setupDepthForOcclusion(k,T,B){const K=this.context,Q=K.gl,le=!!B;var me;B||(B={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}),K.activeTexture.set(Q.TEXTURE3),k&&this.depthFBO&&this.depthTexture?(this.depthTexture.bind(Q.NEAREST,Q.CLAMP_TO_EDGE),B.u_depth_size_inv=[1/this.depthFBO.width,1/this.depthFBO.height],B.u_depth_range_unpack=[2/((me=this.depthRangeFor3D)[1]-me[0]),-1-2*me[0]/(me[1]-me[0])],B.u_occluder_half_size=.5*this.occlusionParams.occluderSize,B.u_occlusion_depth_offset=this.occlusionParams.depthOffset):this.emptyDepthTexture.bind(Q.NEAREST,Q.CLAMP_TO_EDGE),K.activeTexture.set(Q.TEXTURE0),le||T.setTerrainUniformValues(K,B)}updateEmissiveMode(){if(this._forceEmissiveMode)return;const k=this.style.hasDataDrivenEmissiveStrength();this.emissiveMode=this._forceFullRgbaEmissive?"mrt-full-rgba":k?this.context.extBlendFuncExtended?"dual-source-blending":"mrt-fallback":"constant"}}function mh(L,k){let T=!1,B=null;const K=()=>{B=null,T&&(L(),B=setTimeout(K,k),T=!1)};return()=>(T=!0,B||K(),B)}const wy=/(#.+)?$/;class W_{constructor(k){this._hashName=k&&encodeURIComponent(k),o.aW(["_getCurrentHash","_onHashChange","_updateHash"],this),this._updateHash=mh(this._updateHashUnthrottled.bind(this),300)}addTo(k){return this._map=k,window.addEventListener("hashchange",this._onHashChange,!1),k.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 k=this._map;if(!k)return"";const T=Ur(k);if(this._hashName){const B=this._hashName;let K=!1;const Q=location.hash.slice(1).split("&").map(le=>{const me=le.split("=")[0];return me===B?(K=!0,`${me}=${T}`):le}).filter(le=>le);return K||Q.push(`${B}=${T}`),`#${Q.join("&")}`}return`#${T}`}_getCurrentHash(){const k=location.hash.replace("#","");if(this._hashName){let T;return k.split("&").map(B=>B.split("=")).forEach(B=>{B[0]===this._hashName&&(T=B)}),(T&&T[1]||"").split("/")}return k.split("/")}_onHashChange(){const k=this._map;if(!k)return!1;const T=this._getCurrentHash();if(T.length>=3&&!T.some(B=>isNaN(Number(B)))){const B=k.dragRotate.isEnabled()&&k.touchZoomRotate.isEnabled()?+(T[3]||0):k.getBearing();return k.jumpTo({center:[+T[2],+T[1]],zoom:+T[0],bearing:B,pitch:+(T[4]||0)}),!0}return!1}_updateHashUnthrottled(){history.replaceState(history.state,"",location.href.replace(wy,this.getHashString()))}}function Ur(L,k){const T=L.getCenter(),B=Math.round(100*L.getZoom())/100,K=Math.ceil((B*Math.LN2+Math.log(512/360/.5))/Math.LN10),Q=Math.pow(10,K),le=Math.round(T.lng*Q)/Q,me=Math.round(T.lat*Q)/Q,we=L.getBearing(),Me=L.getPitch();let Re=k?`/${le}/${me}/${B}`:`${B}/${me}/${le}`;return(we||Me)&&(Re+="/"+Math.round(10*we)/10),Me&&(Re+=`/${Math.round(Me)}`),Re}const Kn={linearity:.3,easing:o.eC(0,0,.3,1)},ia={deceleration:2500,maxSpeed:1400,...Kn},Qi={deceleration:20,maxSpeed:1400,...Kn},xl={deceleration:1e3,maxSpeed:360,...Kn},td={deceleration:1e3,maxSpeed:90,...Kn};class Cc{constructor(k){this._map=k,this.clear()}clear(){this._inertiaBuffer=[]}record(k){this._drainInertiaBuffer(),this._inertiaBuffer.push({time:o.e.now(),settings:k})}_drainInertiaBuffer(){const k=this._inertiaBuffer,T=o.e.now();for(;k.length>0&&T-k[0].time>160;)k.shift()}_onMoveEnd(k){if(this._map._prefersReducedMotion()||(this._drainInertiaBuffer(),this._inertiaBuffer.length<2))return;const T={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)T.zoom+=Q.zoomDelta||0,T.bearing+=Q.bearingDelta||0,T.pitch+=Q.pitchDelta||0,Q.panDelta&&T.pan._add(Q.panDelta),Q.around&&(T.around=Q.around),Q.pinchAround&&(T.pinchAround=Q.pinchAround);const B=this._inertiaBuffer.at(-1).time-this._inertiaBuffer[0].time,K={};if(T.pan.mag()){const Q=_h(T.pan.mag(),B,{...ia,...k||{}});K.offset=T.pan.mult(Q.amount/T.pan.mag()),K.center=this._map.transform.center,Id(K,Q)}if(T.zoom){const Q=_h(T.zoom,B,Qi);K.zoom=this._map.transform.zoom+Q.amount,Id(K,Q)}if(T.bearing){const Q=_h(T.bearing,B,xl);K.bearing=this._map.transform.bearing+o.b1(Q.amount,-179,179),Id(K,Q)}if(T.pitch){const Q=_h(T.pitch,B,td);K.pitch=this._map.transform.pitch+Q.amount,Id(K,Q)}if(K.zoom||K.bearing){const Q=T.pinchAround===void 0?T.around:T.pinchAround;K.around=Q?this._map.unproject(Q):this._map.getCenter()}return this.clear(),K.noMoveStart=!0,K}}function Id(L,k){(!L.duration||L.durationT.unproject(we)),me=Q.reduce((we,Me,Re,Ze)=>we.add(Me.div(Ze.length)),new o.P(0,0));super(k,{points:Q,point:me,lngLats:le,lngLat:T.unproject(me),originalEvent:B}),this._defaultPrevented=!1}}class Tr extends o.h{preventDefault(){this._defaultPrevented=!0}get defaultPrevented(){return this._defaultPrevented}constructor(k,T){super("wheel",{originalEvent:T}),this._defaultPrevented=!1}}class R3{constructor(k,T){this._map=k,this._clickTolerance=T.clickTolerance}reset(){this._mousedownPos=void 0}wheel(k){return this._firePreventable(new Tr(this._map,k))}mousedown(k,T){return this._mousedownPos=T,this._firePreventable(new Sl(k.type,this._map,k))}mouseup(k){this._map.fire(new Sl(k.type,this._map,k))}preclick(k){const T=new MouseEvent("preclick",k);this._map.fire(new Sl(T.type,this._map,T))}click(k,T){this._mousedownPos&&this._mousedownPos.dist(T)>=this._clickTolerance||(this.preclick(k),this._map.fire(new Sl(k.type,this._map,k)))}dblclick(k){return this._firePreventable(new Sl(k.type,this._map,k))}mouseover(k){this._map.fire(new Sl(k.type,this._map,k))}mouseout(k){this._map.fire(new Sl(k.type,this._map,k))}touchstart(k){return this._firePreventable(new xr(k.type,this._map,k))}touchmove(k){this._map.fire(new xr(k.type,this._map,k))}touchend(k){this._map.fire(new xr(k.type,this._map,k))}touchcancel(k){this._map.fire(new xr(k.type,this._map,k))}_firePreventable(k){if(this._map.fire(k),k.defaultPrevented)return{}}isEnabled(){return!0}isActive(){return!1}enable(){}disable(){}}class Ku{constructor(k){this._map=k}reset(){this._delayContextMenu=!1,this._contextMenuEvent=void 0}mousemove(k){this._map.fire(new Sl(k.type,this._map,k))}mousedown(){this._delayContextMenu=!0}mouseup(){this._delayContextMenu=!1,this._contextMenuEvent&&(this._map.fire(new Sl("contextmenu",this._map,this._contextMenuEvent)),delete this._contextMenuEvent)}contextmenu(k){this._delayContextMenu?this._contextMenuEvent=k:this._map.fire(new Sl(k.type,this._map,k)),this._map.listens("contextmenu")&&k.preventDefault()}isEnabled(){return!0}isActive(){return!1}enable(){}disable(){}}class Zs{constructor(k,T){this._map=k,this._el=k.getCanvasContainer(),this._container=k.getContainer(),this._clickTolerance=T.clickTolerance||1}isEnabled(){return!!this._enabled}isActive(){return!!this._active}enable(){this.isEnabled()||(this._enabled=!0)}disable(){this.isEnabled()&&(this._enabled=!1)}mousedown(k,T){this.isEnabled()&&k.shiftKey&&k.button===0&&(w(),this._startPos=this._lastPos=T,this._active=!0)}mousemoveWindow(k,T){if(!this._active)return;const B=T,K=this._startPos,Q=this._lastPos;if(!K||!Q||Q.equals(B)||!this._box&&B.dist(K){this._box&&(this._box.style.transform=`translate(${le}px,${we}px)`,this._box.style.width=me-le+"px",this._box.style.height=Me-we+"px")})}mouseupWindow(k,T){if(!this._active)return;const B=this._startPos,K=T;if(B&&k.button===0){if(this.reset(),E(),B.x!==K.x||B.y!==K.y)return this._map.fire(new o.h("boxzoomend",{originalEvent:k})),{cameraAnimation:Q=>Q.fitScreenCoordinates(B,K,this._map.getBearing(),{linear:!1})};this._fireEvent("boxzoomcancel",k)}}keydown(k){this._active&&k.keyCode===27&&(this.reset(),this._fireEvent("boxzoomcancel",k))}blur(){this.reset()}reset(){this._active=!1,this._container.classList.remove("mapboxgl-crosshair"),this._box&&(this._box.remove(),this._box=null),S(),delete this._startPos,delete this._lastPos}_fireEvent(k,T){return this._map.fire(new o.h(k,{originalEvent:T}))}}function M9(L,k){const T={};for(let B=0;Bthis.numTouches)&&(this.aborted=!0),this.aborted||(this.startTime===0&&(this.startTime=k.timeStamp),B.length===this.numTouches&&(this.centroid=function(K){const Q=new o.P(0,0);for(const le of K)Q._add(le);return Q.div(K.length)}(T),this.touches=M9(B,T)))}touchmove(k,T,B){if(this.aborted||!this.centroid)return;const K=M9(B,T);for(const Q in this.touches){const le=K[Q];(!le||le.dist(this.touches[Q])>30)&&(this.aborted=!0)}}touchend(k,T,B){if((!this.centroid||k.timeStamp-this.startTime>500)&&(this.aborted=!0),B.length===0){const K=!this.aborted&&this.centroid;if(this.reset(),K)return K}}}class V6{constructor(k){this.singleTap=new P9(k),this.numTaps=k.numTaps,this.reset()}reset(){this.lastTime=1/0,this.lastTap=void 0,this.count=0,this.singleTap.reset()}touchstart(k,T,B){this.singleTap.touchstart(k,T,B)}touchmove(k,T,B){this.singleTap.touchmove(k,T,B)}touchend(k,T,B){const K=this.singleTap.touchend(k,T,B);if(K){const Q=k.timeStamp-this.lastTime<500,le=!this.lastTap||this.lastTap.dist(K)<30;if(Q&&le||this.reset(),this.count++,this.lastTime=k.timeStamp,this.lastTap=K,this.count===this.numTaps)return this.reset(),K}}}class gY{constructor(){this._zoomIn=new V6({numTouches:1,numTaps:2}),this._zoomOut=new V6({numTouches:2,numTaps:1}),this.reset()}reset(){this._active=!1,this._zoomIn.reset(),this._zoomOut.reset()}touchstart(k,T,B){this._zoomIn.touchstart(k,T,B),this._zoomOut.touchstart(k,T,B)}touchmove(k,T,B){this._zoomIn.touchmove(k,T,B),this._zoomOut.touchmove(k,T,B)}touchend(k,T,B){const K=this._zoomIn.touchend(k,T,B),Q=this._zoomOut.touchend(k,T,B);return K?(this._active=!0,k.preventDefault(),setTimeout(()=>this.reset(),0),{cameraAnimation:le=>le.easeTo({duration:300,zoom:le.getZoom()+1,around:le.unproject(K)},{originalEvent:k})}):Q?(this._active=!0,k.preventDefault(),setTimeout(()=>this.reset(),0),{cameraAnimation:le=>le.easeTo({duration:300,zoom:le.getZoom()-1,around:le.unproject(Q)},{originalEvent:k})}):void 0}touchcancel(){this.reset()}enable(){this._enabled=!0}disable(){this._enabled=!1,this.reset()}isEnabled(){return this._enabled}isActive(){return this._active}}const foe=0,poe=2,QT={[foe]:1,[poe]:2},goe={Control:"ctrlKey",Alt:"altKey",Shift:"shiftKey",Meta:"metaKey"};class xY{constructor(k){this.reset(),this._clickTolerance=k.clickTolerance||1}blur(){this.reset()}reset(){this._active=!1,this._moved=!1,this._lastPoint=void 0,this._eventButton=void 0}_correctButton(k,T){return!1}_move(k,T){return{}}mousedown(k,T){if(this._lastPoint)return;const B=R(k);this._correctButton(k,B)&&(this._lastPoint=T,this._eventButton=B)}mousemoveWindow(k,T){const B=this._lastPoint;if(B){if(k.preventDefault(),this._eventButton!=null&&function(K,Q){const le=QT[Q];return K.buttons===void 0||(K.buttons&le)!==le}(k,this._eventButton))this.reset();else if(this._moved||!(T.dist(B)0&&(this._active=!0);const K=M9(B,T),Q=new o.P(0,0),le=new o.P(0,0);let me=0;for(const Me in K){const Re=K[Me],Ze=this._touches[Me];Ze&&(Q._add(Re),le._add(Re.sub(Ze)),me++,K[Me]=Re)}if(this._touches=K,me{this._alertContainer.classList.remove("mapboxgl-touch-pan-blocker-show"),this._alertContainer.removeAttribute("role")},500)}}class L9{constructor(){this.reset()}reset(){this._active=!1,this._firstTwoTouches=void 0}_start(k){}_move(k,T,B){return{}}touchstart(k,T,B){this._firstTwoTouches||B.length<2||(this._firstTwoTouches=[B[0].identifier,B[1].identifier],this._start([T[0],T[1]]))}touchmove(k,T,B){const K=this._firstTwoTouches;if(!K)return;k.preventDefault();const[Q,le]=K,me=D3(B,T,Q),we=D3(B,T,le);if(!me||!we)return;const Me=this._aroundCenter?null:me.add(we).div(2);return this._move([me,we],Me,k)}touchend(k,T,B){if(!this._firstTwoTouches)return;const[K,Q]=this._firstTwoTouches,le=D3(B,T,K),me=D3(B,T,Q);le&&me||(this._active&&E(),this.reset())}touchcancel(){this.reset()}enable(k){this._enabled=!0,this._aroundCenter=!!k&&k.around==="center"}disable(){this._enabled=!1,this.reset()}isEnabled(){return this._enabled}isActive(){return this._active}}function D3(L,k,T){for(let B=0;BMath.abs(L.x)}class boe extends L9{constructor(k){super(),this._map=k}reset(){super.reset(),this._valid=void 0,this._firstMove=void 0,this._lastPoints=void 0}_start(k){this._lastPoints=k,vY(k[0].sub(k[1]))&&(this._valid=!1)}_move(k,T,B){const K=this._lastPoints;if(!K)return;const Q=k[0].sub(K[0]),le=k[1].sub(K[1]);return this._map._cooperativeGestures&&!o.eD()&&B.touches.length<3||(this._valid=this.gestureBeginsVertically(Q,le,B.timeStamp),!this._valid)?void 0:(this._lastPoints=k,this._active=!0,{pitchDelta:(Q.y+le.y)/2*-.5})}gestureBeginsVertically(k,T,B){if(this._valid!==void 0)return this._valid;const K=k.mag()>=2,Q=T.mag()>=2;if(!K&&!Q)return;if(!K||!Q)return this._firstMove??(this._firstMove=B),B-this._firstMove<100&&void 0;const le=k.y>0==T.y>0;return vY(k)&&vY(T)&&le}}const _oe={panStep:100,bearingStep:15,pitchStep:10};class woe{constructor(){const k=_oe;this._panStep=k.panStep,this._bearingStep=k.bearingStep,this._pitchStep=k.pitchStep,this._bearingDisabled=!1,this._pitchDisabled=!1,this._panDisabled=!1,this._zoomDisabled=!1}blur(){this.reset()}reset(){this._active=!1}keydown(k){if(k.altKey||k.ctrlKey||k.metaKey||!this.isEnabled())return;let T=0,B=0,K=0,Q=0,le=0;switch(k.keyCode){case 61:case 107:case 171:case 187:T=1;break;case 189:case 109:case 173:T=-1;break;case 37:k.shiftKey?B=-1:(k.preventDefault(),Q=-1);break;case 39:k.shiftKey?B=1:(k.preventDefault(),Q=1);break;case 38:k.shiftKey?K=1:(k.preventDefault(),le=-1);break;case 40:k.shiftKey?K=-1:(k.preventDefault(),le=1);break;default:return}return this._bearingDisabled&&(B=0),this._pitchDisabled&&(K=0),this._panDisabled&&(Q=0,le=0),this._zoomDisabled&&(T=0),{cameraAnimation:me=>{const we=me.getZoom();me.easeTo({duration:300,easeId:"keyboardHandler",easing:OFe,zoom:T?Math.round(we)+T*(k.shiftKey?2:1):we,bearing:me.getBearing()+B*this._bearingStep,pitch:me.getPitch()+K*this._pitchStep,offset:[-Q*this._panStep,-le*this._panStep],center:me.getCenter()},{originalEvent:k})}}}enable(){this._enabled=!0}disable(){this._enabled=!1,this.reset()}isEnabled(){return this._enabled&&!(this._bearingDisabled&&this._pitchDisabled&&this._panDisabled&&this._zoomDisabled)}isActive(){return this._active}disableRotation(){this._pitchDisabled=!0,this._bearingDisabled=!0}enableRotation(){this._pitchDisabled=!1,this._bearingDisabled=!1}isRotationEnabled(){return!this._pitchDisabled&&!this._bearingDisabled}disablePan(){this._panDisabled=!0}enablePan(){this._panDisabled=!1}isPanEnabled(){return!this._panDisabled}disableZoom(){this._zoomDisabled=!0}enableZoom(){this._zoomDisabled=!1}isZoomEnabled(){return!this._zoomDisabled}disablePitch(){this._pitchDisabled=!0}enablePitch(){this._pitchDisabled=!1}isPitchEnabled(){return!this._pitchDisabled}disableBearing(){this._bearingDisabled=!0}enableBearing(){this._bearingDisabled=!1}isBearingEnabled(){return!this._bearingDisabled}}function OFe(L){return L*(2-L)}const bY=4.000244140625,zFe=1/450,e0=/(Mac|iPad)/i;class R9{constructor(k,T){this._map=k,this._el=k.getCanvasContainer(),this._handler=T,this._delta=0,this._lastDelta=0,this._defaultZoomRate=.01,this._wheelZoomRate=zFe,o.aW(["_onTimeout","_addScrollZoomBlocker","_showBlockerAlert"],this)}setZoomRate(k){this._defaultZoomRate=k}setWheelZoomRate(k){this._wheelZoomRate=k}isEnabled(){return!!this._enabled}isActive(){return this._active||this._finishTimeout!==void 0}isZooming(){return!!this._zooming}enable(k){this.isEnabled()||(this._enabled=!0,this._aroundCenter=!!k&&k.around==="center",this._map._cooperativeGestures&&this._addScrollZoomBlocker())}disable(){this.isEnabled()&&(this._enabled=!1,this._map._cooperativeGestures&&(clearTimeout(this._alertTimer),this._alertContainer.remove()))}wheel(k){if(!this.isEnabled())return;if(this._map._cooperativeGestures){if(!(k.ctrlKey||k.metaKey||this.isZooming()||o.eD()))return void this._showBlockerAlert();this._alertContainer.style.visibility!=="hidden"&&(this._alertContainer.style.visibility="hidden",clearTimeout(this._alertTimer))}let T=k.deltaMode===WheelEvent.DOM_DELTA_LINE?40*k.deltaY:k.deltaY;const B=o.e.now(),K=B-(this._lastWheelEventTime||0);this._lastWheelEventTime=B,T!==0&&T%bY===0?this._type="wheel":T!==0&&Math.abs(T)<4?this._type="trackpad":K>400?(this._type=null,this._lastValue=T,this._timeout=window.setTimeout(this._onTimeout,40,k)):this._type||(this._type=Math.abs(K*T)<200?"trackpad":"wheel",this._timeout&&(clearTimeout(this._timeout),this._timeout=null,T+=this._lastValue)),k.shiftKey&&T&&(T/=4),this._type&&(this._lastWheelEvent=k,this._delta-=T,this._active||this._start(k)),k.preventDefault()}_onTimeout(k){this._type="wheel",this._delta-=this._lastValue,this._active||this._start(k)}_start(k){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 T=I(this._el,k);this._aroundPoint=this._aroundCenter?this._map.transform.centerPoint:T,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 k=this._map.transform;this._type==="wheel"&&k.projection.wrap&&(k._center.lng>=180||k._center.lng<=-180)&&(this._prevEase=null,this._easing=null,this._lastWheelEvent=null,this._lastWheelEventTime=0);const T=()=>k._terrainEnabled()&&this._aroundCoord?k.computeZoomRelativeTo(this._aroundCoord):k.zoom;if(this._delta!==0){const Me=this._type==="wheel"&&Math.abs(this._delta)>bY?this._wheelZoomRate:this._defaultZoomRate;let Re=2/(1+Math.exp(-Math.abs(this._delta*Me)));this._delta<0&&Re!==0&&(Re=1/Re);const Ze=T(),Qe=Math.pow(2,Ze),ht=typeof this._targetZoom=="number"?k.zoomScale(this._targetZoom):Qe;this._targetZoom=Math.min(k.maxZoom,Math.max(k.minZoom,k.scaleZoom(ht*Re))),this._type==="wheel"&&(this._startZoom=Ze,this._easing=this._smoothOutEasing(200)),this._lastDelta=this._delta,this._delta=0}const B=typeof this._targetZoom=="number"?this._targetZoom:T(),K=this._startZoom,Q=this._easing;let le,me=!1;if(this._type==="wheel"&&K&&Q){const Me=Math.min((o.e.now()-this._lastWheelEventTime)/200,1),Re=Q(Me);le=o.am(K,B,Re),Me<1?this._frameId||(this._frameId=!0):me=!0}else le=B,me=!0;this._active=!0,me&&(this._active=!1,this._finishTimeout=window.setTimeout(()=>{this._zooming=!1,this._handler._triggerRenderFrame(),delete this._targetZoom,delete this._finishTimeout},200));let we=le-T();return we*this._lastDelta<0&&(we=0),{noInertia:!0,needsRenderFrame:!me,zoomDelta:we,around:this._aroundPoint,aroundCoord:this._aroundCoord,originalEvent:this._lastWheelEvent}}_smoothOutEasing(k){let T=o.eE;if(this._prevEase){const B=this._prevEase,K=(o.e.now()-B.start)/B.duration,Q=B.easing(K+.01)-B.easing(K),le=.27/Math.sqrt(Q*Q+1e-4)*.01,me=Math.sqrt(.0729-le*le);T=o.eC(le,me,.25,1)}return this._prevEase={start:o.e.now(),duration:k,easing:T},T}blur(){this.reset()}reset(){this._active=!1}_addScrollZoomBlocker(){this._map&&!this._alertContainer&&(this._alertContainer=g("div","mapboxgl-scroll-zoom-blocker",this._map._container),this._alertContainer.textContent=e0.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 eM{constructor(k,T){this._clickZoom=k,this._tapZoom=T}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 joe{constructor(){this.reset()}reset(){this._active=!1}blur(){this.reset()}dblclick(k,T){return k.preventDefault(),{cameraAnimation:B=>{B.easeTo({duration:300,zoom:B.getZoom()+(k.shiftKey?-1:1),around:B.unproject(T)},{originalEvent:k})}}}enable(){this._enabled=!0}disable(){this._enabled=!1,this.reset()}isEnabled(){return this._enabled}isActive(){return this._active}}class F3{constructor(){this._tap=new V6({numTouches:1,numTaps:1}),this.reset()}reset(){this._active=!1,this._swipePoint=void 0,this._swipeTouch=0,this._tapTime=0,this._tap.reset()}touchstart(k,T,B){this._swipePoint||(this._tapTime&&k.timeStamp-this._tapTime>500&&this.reset(),this._tapTime?B.length>0&&(this._swipePoint=T[0],this._swipeTouch=B[0].identifier):this._tap.touchstart(k,T,B))}touchmove(k,T,B){if(this._tapTime){if(this._swipePoint){if(B[0].identifier!==this._swipeTouch)return;const K=T[0],Q=K.y-this._swipePoint.y;return this._swipePoint=K,k.preventDefault(),this._active=!0,{zoomDelta:Q/128}}}else this._tap.touchmove(k,T,B)}touchend(k,T,B){this._tapTime?this._swipePoint&&B.length===0&&this.reset():this._tap.touchend(k,T,B)&&(this._tapTime=k.timeStamp)}touchcancel(){this.reset()}enable(){this._enabled=!0}disable(){this._enabled=!1,this.reset()}isEnabled(){return this._enabled}isActive(){return this._active}}class W6{constructor(k,T,B){this._el=k,this._mousePan=T,this._touchPan=B}enable(k){this._inertiaOptions=k||{},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 BFe{constructor(k,T,B){this._pitchWithRotate=k.pitchWithRotate,this._mouseRotate=T,this._mousePitch=B,this._pitchDisabled=!1,this._rotationDisabled=!1}enable(){this._rotationDisabled||this._mouseRotate.enable(),this._pitchWithRotate&&!this._pitchDisabled&&this._mousePitch.enable()}disable(){this._mouseRotate.disable(),this._mousePitch.disable()}isEnabled(){return this._pitchWithRotate?!this._rotationDisabled&&this._mouseRotate.isEnabled()||!this._pitchDisabled&&this._mousePitch.isEnabled():!this._rotationDisabled&&this._mouseRotate.isEnabled()}isActive(){return this._mouseRotate.isActive()||this._mousePitch.isActive()}disablePitch(){this._pitchDisabled=!0,this._mousePitch.disable()}enablePitch(){this._pitchDisabled=!1,this._pitchWithRotate&&this._mousePitch.enable()}isPitchEnabled(){return!this._pitchDisabled&&this._mousePitch.isEnabled()}disableRotation(){this._rotationDisabled=!0,this._mouseRotate.disable()}enableRotation(){this._rotationDisabled=!1,this._mouseRotate.enable()}isRotationEnabled(){return!this._rotationDisabled&&this._mouseRotate.isEnabled()}}class $Fe{constructor(k,T,B,K){this._el=k,this._touchZoom=T,this._touchRotate=B,this._tapDragZoom=K,this._rotationDisabled=!1,this._tapDragZoomDisabled=!1,this._enabled=!0}enable(k){this._touchZoom.enable(k),this._rotationDisabled||this._touchRotate.enable(k),this._tapDragZoomDisabled||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._tapDragZoomDisabled&&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()}isRotationEnabled(){return!this._rotationDisabled}disableTapDragZoom(){this._tapDragZoomDisabled=!0,this._tapDragZoom.disable()}enableTapDragZoom(){this._tapDragZoomDisabled=!1,this._touchZoom.isEnabled()&&this._tapDragZoom.enable()}isTapDragZoomEnabled(){return!this._tapDragZoomDisabled}}const D9=L=>L.zoom||L.drag||L.pitch||L.rotate;class UFe extends o.h{}class qFe{constructor(){this.constants=[1,1,.01],this.radius=0}setup(k,T){const B=o.cv([],T,k);this.radius=o.es(B[2]<0?o.eG([],B,this.constants):[B[0],B[1],0])}projectRay(k){o.eG(k,k,this.constants),o.c9(k,k),o.eH(k,k,this.constants);const T=o.dV([],k,this.radius);if(T[2]>0){const B=o.dV([],[0,0,1],o.dY(T,[0,0,1])),K=o.dV([],o.c9([],[T[0],T[1],0]),this.radius),Q=o.dW([],T,o.dV([],o.cv([],o.dW([],K,B),T),2));T[0]=Q[0],T[1]=Q[1]}return T}}function F9(L){return L.panDelta&&L.panDelta.mag()||L.zoomDelta||L.bearingDelta||L.pitchDelta}class VFe{constructor(k,T){this._map=k,this._el=this._map.getCanvasContainer(),this._handlers=[],this._handlersById={},this._changes=[],this._inertia=new Cc(k),this._bearingSnap=T.bearingSnap,this._previousActiveHandlers={},this._trackingEllipsoid=new qFe,this._dragOrigin=null,this._mouseBeingPressed=!1,this._activeTouchCount=0,this._eventsInProgress={},this._addDefaultHandlers(T),o.aW(["handleEvent","handleWindowEvent"],this);const B=this._el;this._listeners=[[B,"touchstart",{passive:!0}],[B,"touchmove",{passive:!1}],[B,"touchend",void 0],[B,"touchcancel",void 0],[B,"mousedown",void 0],[B,"mousemove",void 0],[B,"mouseup",void 0],[document,"mousemove",{capture:!0}],[document,"mouseup",void 0],[B,"mouseover",void 0],[B,"mouseout",void 0],[B,"dblclick",void 0],[B,"click",void 0],[B,"keydown",{capture:!1}],[B,"keyup",void 0],[B,"wheel",{passive:!1}],[B,"contextmenu",void 0],[window,"blur",void 0]];for(const[K,Q,le]of this._listeners){const me=K===document?this.handleWindowEvent:this.handleEvent;K.addEventListener(Q,me,le)}}destroy(){for(const[k,T,B]of this._listeners){const K=k===document?this.handleWindowEvent:this.handleEvent;k.removeEventListener(T,K,B)}}_addDefaultHandlers(k){const T=this._map,B=T.getCanvasContainer();this._add("mapEvent",new R3(T,k));const K=T.boxZoom=new Zs(T,k);this._add("boxZoom",K);const Q=new gY,le=new joe;T.doubleClickZoom=new eM(le,Q),this._add("tapZoom",Q),this._add("clickZoom",le);const me=new F3;this._add("tapDragZoom",me);const we=T.touchPitch=new boe(T);this._add("touchPitch",we);const Me=new H6(k),Re=new I9(k);T.dragRotate=new BFe(k,Me,Re),this._add("mouseRotate",Me,["mousePitch"]),this._add("mousePitch",Re,["mouseRotate"]);const Ze=new xoe(k),Qe=new yoe(T,k);T.dragPan=new W6(B,Ze,Qe),this._add("mousePan",Ze),this._add("touchPan",Qe,["touchZoom","touchRotate"]);const ht=new voe,_t=new G6;T.touchZoomRotate=new $Fe(B,_t,ht,me),this._add("touchRotate",ht,["touchPan","touchZoom"]),this._add("touchZoom",_t,["touchPan","touchRotate"]),this._add("blockableMapEvent",new Ku(T));const bt=T.scrollZoom=new R9(T,this);this._add("scrollZoom",bt,["mousePan"]);const Mt=T.keyboard=new woe;this._add("keyboard",Mt);for(const es of["boxZoom","doubleClickZoom","tapDragZoom","touchPitch","dragRotate","dragPan","touchZoomRotate","scrollZoom","keyboard"])k.interactive&&k[es]&&T[es].enable(k[es])}_add(k,T,B){this._handlers.push({handlerName:k,handler:T,allowed:B}),this._handlersById[k]=T}stop(k="never"){if(!this._updatingCamera&&!(k==="always"||k==="ifPointerDown"&&this._isPointerDown())){for(const{handler:T}of this._handlers)T.reset();this._inertia.clear(),this._fireEvents({},{},!1),this._changes=[],this._originalZoom=void 0}}isActive(){for(const{handler:k}of this._handlers)if(k.isActive())return!0;return!1}isZooming(){return!!this._eventsInProgress.zoom||this._map.scrollZoom.isZooming()}isRotating(){return!!this._eventsInProgress.rotate}isMoving(){return!!D9(this._eventsInProgress)||this.isZooming()}_isDragging(){return!!this._eventsInProgress.drag}_blockedByActive(k,T,B){for(const K in k)if(!(K===B||T&&T.includes(K)))return!0;return!1}handleWindowEvent(k){this.handleEvent(k,`${k.type}Window`)}_getMapTouches(k){const T=[];for(const B of k)this._el.contains(B.target)&&T.push(B);return T}_updatePointerLiveness(k){switch(k.type){case"mousedown":this._mouseBeingPressed=!0;break;case"mousemove":k.buttons===0&&(this._mouseBeingPressed=!1);break;case"mouseup":this._mouseBeingPressed=!1;break;case"touchstart":case"touchmove":case"touchend":case"touchcancel":this._activeTouchCount=k.touches?k.touches.length:0;break;case"blur":this._mouseBeingPressed=!1,this._activeTouchCount=0}}_isPointerDown(){return this._mouseBeingPressed||this._activeTouchCount>0}handleEvent(k,T){this._updatePointerLiveness(k),this._updatingCamera=!0;const B=k.type==="renderFrame",K=B?void 0:k,Q={needsRenderFrame:!1},le={},me={},we=k.touches?this._getMapTouches(k.touches):void 0,Me=we?P(this._el,we):B?void 0:I(this._el,k);for(const{handlerName:Qe,handler:ht,allowed:_t}of this._handlers){if(!ht.isEnabled())continue;let bt;this._blockedByActive(me,_t,Qe)?ht.reset():ht[T||k.type]&&(bt=ht[T||k.type](k,Me,we),this.mergeHandlerResult(Q,le,bt,Qe,K),bt&&bt.needsRenderFrame&&this._triggerRenderFrame()),(bt||ht.isActive())&&(me[Qe]=ht)}const Re={};for(const Qe in this._previousActiveHandlers)me[Qe]||(Re[Qe]=K);this._previousActiveHandlers=me,(Object.keys(Re).length||F9(Q))&&(this._changes.push([Q,le,Re]),this._triggerRenderFrame()),(Object.keys(me).length||F9(Q))&&this._map._stop({keepGesture:"always"}),this._updatingCamera=!1;const{cameraAnimation:Ze}=Q;Ze&&(this._inertia.clear(),this._fireEvents({},{},!0),this._changes=[],Ze(this._map))}mergeHandlerResult(k,T,B,K,Q){if(!B)return;Object.assign(k,B);const le={handlerName:K,originalEvent:B.originalEvent||Q};B.zoomDelta!==void 0&&(T.zoom=le),B.panDelta!==void 0&&(T.drag=le),B.pitchDelta!==void 0&&(T.pitch=le),B.bearingDelta!==void 0&&(T.rotate=le)}_applyChanges(){const k={},T={},B={};for(const[K,Q,le]of this._changes)K.panDelta&&(k.panDelta=(k.panDelta||new o.P(0,0))._add(K.panDelta)),K.zoomDelta&&(k.zoomDelta=(k.zoomDelta||0)+K.zoomDelta),K.bearingDelta&&(k.bearingDelta=(k.bearingDelta||0)+K.bearingDelta),K.pitchDelta&&(k.pitchDelta=(k.pitchDelta||0)+K.pitchDelta),K.around!==void 0&&(k.around=K.around),K.aroundCoord!==void 0&&(k.aroundCoord=K.aroundCoord),K.pinchAround!==void 0&&(k.pinchAround=K.pinchAround),K.noInertia&&(k.noInertia=K.noInertia),Object.assign(T,Q),Object.assign(B,le);this._updateMapTransform(k,T,B),this._changes=[]}_updateMapTransform(k,T,B){const K=this._map,Q=K.transform,le=Qt=>[Qt.x,Qt.y,Qt.z];if((()=>{const Qt=this._eventsInProgress.drag;return Qt&&!this._handlersById[Qt.handlerName].isActive()})()&&!F9(k)){const Qt=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"),Qt!==Q.zoom&&this._map._update(!0)}if(Q._isCameraConstrained&&K._stop({keepGesture:"always"}),!F9(k))return void this._fireEvents(T,B,!0);let{panDelta:me,zoomDelta:we,bearingDelta:Me,pitchDelta:Re,around:Ze,aroundCoord:Qe,pinchAround:ht}=k;Q._isCameraConstrained&&(we>0&&(we=0),Q._isCameraConstrained=!1),ht!==void 0&&(Ze=ht),(we||(Qt=>T[Qt]&&!this._eventsInProgress[Qt])("drag"))&&Ze&&(this._dragOrigin=le(Q.pointCoordinate3D(Ze)),this._originalZoom=Q.zoom,this._trackingEllipsoid.setup(Q._camera.position,this._dragOrigin)),Q.cameraElevationReference="sea",K._stop({keepGesture:"always"}),Ze=Ze||K.transform.centerPoint,Me&&(Q.bearing+=Me),Re&&(Q.pitch+=Re),Q._updateCameraState();const _t=[0,0,0];if(me)if(Q.projection.name==="mercator"){const Qt=this._trackingEllipsoid.projectRay(Q.screenPointToMercatorRay(Ze).dir),Lt=this._trackingEllipsoid.projectRay(Q.screenPointToMercatorRay(Ze.sub(me)).dir);_t[0]=Lt[0]-Qt[0],_t[1]=Lt[1]-Qt[1]}else{const Qt=Q.pointCoordinate(Ze);if(Q.projection.name==="globe"){me=me.rotate(-Q.angle);const Lt=Q._pixelsPerMercatorPixel/Q.worldSize;_t[0]=-me.x*o.eF(o.bs(Qt.y))*Lt,_t[1]=-me.y*o.eF(Q.center.lat)*Lt}else{const Lt=Q.pointCoordinate(Ze.sub(me));Qt&&Lt&&(_t[0]=Lt.x-Qt.x,_t[1]=Lt.y-Qt.y)}}const bt=Q.zoom,Mt=[0,0,0];if(we){const Qt=le(Qe||Q.pointCoordinate3D(Ze)),Lt={dir:o.c9([],o.cv([],Qt,Q._camera.position))};if(Lt.dir[2]<0){const ps=Q.zoomDeltaToMovement(Qt,we);o.dV(Mt,Lt.dir,ps)}}const es=o.dW(_t,_t,Mt);Q._translateCameraConstrained(es),we&&Math.abs(Q.zoom-bt)>1e-4&&Q.recenterOnTerrain(),Q.cameraElevationReference="ground",this._map._update(),k.noInertia||this._inertia.record(k),this._fireEvents(T,B,!0)}_fireEvents(k,T,B){const K=D9(this._eventsInProgress),Q=D9(k),le={};for(const Re in k){const{originalEvent:Ze}=k[Re];this._eventsInProgress[Re]||(le[`${Re}start`]=Ze),this._eventsInProgress[Re]=k[Re]}!K&&Q&&this._fireEvent("movestart",Q.originalEvent);for(const Re in le)this._fireEvent(Re,le[Re]);Q&&this._fireEvent("move",Q.originalEvent);for(const Re in k){const{originalEvent:Ze}=k[Re];this._fireEvent(Re,Ze)}const me={};let we;for(const Re in this._eventsInProgress){const{handlerName:Ze,originalEvent:Qe}=this._eventsInProgress[Re];this._handlersById[Ze].isActive()||(delete this._eventsInProgress[Re],we=T[Ze]||Qe,me[`${Re}end`]=we)}for(const Re in me)this._fireEvent(Re,me[Re]);const Me=D9(this._eventsInProgress);if(B&&(K||Q)&&!Me){this._updatingCamera=!0;const Re=this._inertia._onMoveEnd(this._map.dragPan._inertiaOptions),Ze=Qe=>Qe!==0&&-this._bearingSnap{this._frameId=void 0,this.handleEvent(new UFe("renderFrame",{timeStamp:k})),this._applyChanges()})}_triggerRenderFrame(){this._frameId===void 0&&(this._frameId=this._requestFrame())}}const O9="map.setFreeCameraOptions(...) and map.getFreeCameraOptions() are not yet supported for non-mercator projections.";class HFe extends o.E{constructor(k,T){super(),this._moving=!1,this._zooming=!1,this.transform=k,this._bearingSnap=T.bearingSnap,this._respectPrefersReducedMotion=T.respectPrefersReducedMotion!==!1,o.aW(["_renderFrameCallback"],this)}getCenter(){return new o.cZ(this.transform.center.lng,this.transform.center.lat)}setCenter(k,T){return this.jumpTo({center:k},T)}panBy(k,T,B){return k=o.P.convert(k).mult(-1),this.panTo(this.transform.center,{offset:k,...T},B)}panTo(k,T,B){return this.easeTo({center:k,...T},B)}getZoom(){return this.transform.zoom}setZoom(k,T){return this.jumpTo({zoom:k},T),this}zoomTo(k,T,B){return this.easeTo({zoom:k,...T},B)}zoomIn(k,T){return this.zoomTo(this.getZoom()+1,k,T),this}zoomOut(k,T){return this.zoomTo(this.getZoom()-1,k,T),this}getBearing(){return this.transform.bearing}setBearing(k,T){return this.jumpTo({bearing:k},T),this}getPadding(){return this.transform.padding}setPadding(k,T){return this.jumpTo({padding:k},T),this}rotateTo(k,T,B){return this.easeTo({bearing:k,...T},B)}resetNorth(k,T){return this.rotateTo(0,{duration:1e3,...k},T),this}resetNorthPitch(k,T){return this.easeTo({bearing:0,pitch:0,duration:1e3,...k},T),this}snapToNorth(k,T){return Math.abs(this.getBearing())k.aspect?B/(2*Math.tan(.5*k.fovX)*k.aspect):K/(2*Math.tan(.5*k.fovY)*k.aspect)}_cameraForBoundsOnGlobe(k,T,B,K,Q,le){const me=k.clone(),we=this._extendCameraOptions(le);me.bearing=K,me.pitch=Q;const Me=o.cZ.convert(T),Re=o.cZ.convert(B),Ze=.5*(Me.lat+Re.lat),Qe=.5*(Me.lng+Re.lng),ht=o.eJ(Ze,Qe),_t=o.c9([],ht),bt=o.c9([],o.eK([],_t,[0,1,0])),Mt=o.eK([],bt,_t),es=[bt[0],bt[1],bt[2],0,Mt[0],Mt[1],Mt[2],0,_t[0],_t[1],_t[2],0,0,0,0,1],Qt=[ht,o.eJ(Me.lat,Me.lng),o.eJ(Re.lat,Me.lng),o.eJ(Re.lat,Re.lng),o.eJ(Me.lat,Re.lng),o.eJ(Ze,Me.lng),o.eJ(Ze,Re.lng),o.eJ(Me.lat,Qe),o.eJ(Re.lat,Qe)];let Lt=o.eL.fromPoints(Qt.map(Hr=>[o.dY(bt,Hr),o.dY(Mt,Hr),o.dY(_t,Hr)]));const ps=o.bI([],Lt.center,es);o.eM(ps)===0&&o.eN(ps,0,0,1),o.c9(ps,ps),o.dV(ps,ps,o.cy),me.center=o.eO(ps);const Hs=me.getWorldToCameraMatrix(),Fs=o.aP(new Float64Array(16),Hs);Lt=o.eL.applyTransform(Lt,o.X([],Hs,es));const nn=this._extendAABB(Lt,me,we,K);if(!nn)return void o.w("Map cannot fit within canvas with the given bounds, padding, and/or offset.");Lt=nn,o.bI(ps,ps,Hs);const $s=.5*(Lt.max[2]-Lt.min[2]),rn=this._minimumAABBFrustumDistance(me,Lt),_n=o.dV([],[0,0,1],$s),Mn=o.dW(_n,ps,_n),Yn=rn+(me.pitch===0?0:o.eP(ps,Mn)),$n=me.globeCenterInViewSpace,zn=o.cv([],ps,[$n[0],$n[1],$n[2]]);o.c9(zn,zn),o.dV(zn,zn,Yn);const Dr=o.dW([],ps,zn);o.bI(Dr,Dr,Fs);const An=o.bk/o.cy,yr=o.es(Dr),sa=o.c4(Math.max(yr*An-o.bk,Number.EPSILON),0),ka=Math.min(me.zoomFromMercatorZAdjusted(sa),we.maxZoom);return ka>.5*(o.ef+o.b2)?(me.setProjection({name:"mercator"}),me.zoom=ka,this._cameraForBounds(me,T,B,K,Q,le)):{center:me.center,zoom:ka,bearing:K,pitch:Q}}_extendAABB(k,T,B,K){const Q=.5*((B.padding.left||0)+(B.padding.right||0)),le=.5*((B.padding.top||0)+(B.padding.bottom||0)),me=le,we=Q,Me=Q,Re=le,Ze=T.width-(we+Me),Qe=T.height-(me+Re),ht=o.cv([],k.max,k.min),_t=Math.min(Ze/ht[0],Qe/ht[1]),bt=Math.min(T.scaleZoom(T.scale*_t),B.maxZoom);if(isNaN(bt))return null;const Mt=T.scale/T.zoomScale(bt),es=new o.eL([k.min[0]-we*Mt,k.min[1]-Re*Mt,k.min[2]],[k.max[0]+Me*Mt,k.max[1]+me*Mt,k.max[2]]),Qt=(typeof B.offset.x=="number"&&typeof B.offset.y=="number"?new o.P(B.offset.x,B.offset.y):o.P.convert(B.offset)).rotate(-o.av(K));return es.center[0]-=Qt.x*Mt,es.center[1]+=Qt.y*Mt,es}queryTerrainElevation(k,T){const B=this.transform.elevation;return B?(T={exaggerated:!0,...T},B.getAtPoint(o.bT.fromLngLat(k),null,T.exaggerated)):null}_cameraForBounds(k,T,B,K,Q,le){if(k.projection.name==="globe")return this._cameraForBoundsOnGlobe(k,T,B,K,Q,le);const me=k.clone(),we=this._extendCameraOptions(le);me.bearing=K,me.pitch=Q;const Me=o.cZ.convert(T),Re=o.cZ.convert(B),Ze=new o.cZ(Me.lng,Re.lat),Qe=new o.cZ(Re.lng,Me.lat),ht=me.project(Me),_t=me.project(Re),bt=this.queryTerrainElevation(Me),Mt=this.queryTerrainElevation(Re),es=this.queryTerrainElevation(Ze),Qt=this.queryTerrainElevation(Qe),Lt=[[ht.x,ht.y,Math.min(bt||0,Mt||0,es||0,Qt||0)],[_t.x,_t.y,Math.max(bt||0,Mt||0,es||0,Qt||0)]];let ps=o.eL.fromPoints(Lt);const Hs=me.getWorldToCameraMatrix(),Fs=o.aP(new Float64Array(16),Hs);ps=o.eL.applyTransform(ps,Hs);const nn=this._extendAABB(ps,me,we,K);if(!nn)return void o.w("Map cannot fit within canvas with the given bounds, padding, and/or offset.");ps=nn;const $s=.5*o.cv([],ps.max,ps.min)[2],rn=this._minimumAABBFrustumDistance(me,ps),_n=[0,0,1,0];o.c6(_n,_n,Hs),o.eQ(_n,_n);const Mn=o.dV([],_n,rn+$s),Yn=o.dW([],ps.center,Mn);o.bI(ps.center,ps.center,Fs),o.bI(Yn,Yn,Fs);const $n=me.unproject(new o.P(ps.center[0],ps.center[1])),zn=o.eR(me.projection,$n),Dr=Math.pow(2,zn),An=Math.min(me._zoomFromMercatorZ(Yn[2]*me.pixelsPerMeter*Dr/me.worldSize),we.maxZoom);return me.mercatorFromTransition&&An<.5*(o.ef+o.b2)?(me.setProjection({name:"globe"}),me.zoom=An,this._cameraForBounds(me,T,B,K,Q,le)):{center:$n,zoom:An,bearing:K,pitch:Q}}fitBounds(k,T,B){const K=this.cameraForBounds(k,T);return this._fitInternal(K,T,B)}fitScreenCoordinates(k,T,B,K,Q){const le=o.P.convert(k),me=o.P.convert(T),we=new o.P(Math.min(le.x,me.x),Math.min(le.y,me.y)),Me=new o.P(Math.max(le.x,me.x),Math.max(le.y,me.y));if(this.transform.projection.name==="mercator"&&this.transform.anyCornerOffEdge(le,me))return this;const Re=this.transform.pointLocation3D(we),Ze=this.transform.pointLocation3D(Me),Qe=this.transform.pointLocation3D(new o.P(we.x,Me.y)),ht=this.transform.pointLocation3D(new o.P(Me.x,we.y)),_t=[Math.min(Re.lng,Ze.lng,Qe.lng,ht.lng),Math.min(Re.lat,Ze.lat,Qe.lat,ht.lat)],bt=[Math.max(Re.lng,Ze.lng,Qe.lng,ht.lng),Math.max(Re.lat,Ze.lat,Qe.lat,ht.lat)],Mt=K&&K.pitch?K.pitch:this.getPitch(),es=this._cameraForBounds(this.transform,_t,bt,B,Mt,K);return this._fitInternal(es,K,Q)}_fitInternal(k,T,B){return k?(T=Object.assign(k,T)).linear?this.easeTo(T,B):this.flyTo(T,B):this}jumpTo(k,T){this._stop({keepGesture:"ifPointerDown"});const B=k.preloadOnly?this.transform.clone():this.transform;let K=!1,Q=!1,le=!1;"zoom"in k&&B.zoom!==+k.zoom&&(K=!0,B.zoom=+k.zoom),k.center!==void 0&&(B.center=o.cZ.convert(k.center)),"bearing"in k&&B.bearing!==+k.bearing&&(Q=!0,B.bearing=+k.bearing),"pitch"in k&&B.pitch!==+k.pitch&&(le=!0,B.pitch=+k.pitch),"fov"in k&&(B.fov=+k.fov);const me=typeof k.padding=="number"?this._extendPadding(k.padding):k.padding;if(k.padding!=null&&!B.isPaddingEqual(me))if(k.retainPadding===!1){const we=B.clone();we.padding=me,B.setLocationAtPoint(B.center,we.centerPoint)}else B.padding=me;return k.preloadOnly?(this._preloadTiles(B),this):(this.fire(new o.h("movestart",T)).fire(new o.h("move",T)),K&&this.fire(new o.h("zoomstart",T)).fire(new o.h("zoom",T)).fire(new o.h("zoomend",T)),Q&&this.fire(new o.h("rotatestart",T)).fire(new o.h("rotate",T)).fire(new o.h("rotateend",T)),le&&this.fire(new o.h("pitchstart",T)).fire(new o.h("pitch",T)).fire(new o.h("pitchend",T)),this.fire(new o.h("moveend",T)))}getFreeCameraOptions(){return this.transform.projection.supportsFreeCamera||o.w(O9),this.transform.getFreeCameraOptions()}setFreeCameraOptions(k,T){const B=this.transform;if(!B.projection.supportsFreeCamera)return o.w(O9),this;this.stop();const K=B.zoom,Q=B.pitch,le=B.bearing;B.setFreeCameraOptions(k);const me=K!==B.zoom,we=Q!==B.pitch,Me=le!==B.bearing;return this.fire(new o.h("movestart",T)).fire(new o.h("move",T)),me&&this.fire(new o.h("zoomstart",T)).fire(new o.h("zoom",T)).fire(new o.h("zoomend",T)),Me&&this.fire(new o.h("rotatestart",T)).fire(new o.h("rotate",T)).fire(new o.h("rotateend",T)),we&&this.fire(new o.h("pitchstart",T)).fire(new o.h("pitch",T)).fire(new o.h("pitchend",T)),this.fire(new o.h("moveend",T)),this}easeTo(k,T){this._stop({easeId:k.easeId}),((k={offset:[0,0],duration:500,easing:o.eE,...k}).animate===!1||this._prefersReducedMotion(k))&&(k.duration=0);const B=this.transform,K=this.getZoom(),Q=this.getBearing(),le=this.getPitch(),me=this.getPadding(),we=this.getVerticalFieldOfView(),Me="zoom"in k?+k.zoom:K,Re="bearing"in k?this._normalizeBearing(k.bearing,Q):Q,Ze="pitch"in k?+k.pitch:le,Qe="fov"in k?+k.fov:we,ht=this._extendPadding(k.padding),_t=o.P.convert(k.offset);let bt,Mt,es;if(B.projection.name==="globe"){const $n=o.bT.fromLngLat(B.center),zn=_t.rotate(-B.angle);$n.x+=zn.x/B.worldSize,$n.y+=zn.y/B.worldSize;const Dr=$n.toLngLat(),An=o.cZ.convert(k.center||Dr);this._normalizeCenter(An),bt=B.centerPoint.add(zn),Mt=new o.P($n.x,$n.y).mult(B.worldSize),es=new o.P(o.a7(An.lng),o.a8(An.lat)).mult(B.worldSize).sub(Mt)}else{bt=B.centerPoint.add(_t);const $n=B.pointLocation(bt),zn=o.cZ.convert(k.center||$n);this._normalizeCenter(zn),Mt=B.project($n),es=B.project(zn).sub(Mt)}const Qt=B.zoomScale(Me-K);let Lt,ps;k.around&&(Lt=o.cZ.convert(k.around),ps=B.locationPoint(Lt));const Hs=this._zooming||Me!==K,Fs=this._rotating||Q!==Re,nn=this._pitching||Ze!==le,$s=Qe!==we,rn=!B.isPaddingEqual(ht),_n=k.retainPadding===!1?B.clone():B,Mn=$n=>zn=>{if(Hs&&($n.zoom=o.am(K,Me,zn)),Fs&&($n.bearing=o.am(Q,Re,zn)),nn&&($n.pitch=o.am(le,Ze,zn)),$s&&($n.fov=o.am(we,Qe,zn)),rn&&(_n.interpolatePadding(me,ht,zn),bt=_n.centerPoint.add(_t)),Lt)$n.setLocationAtPoint(Lt,ps);else{const Dr=$n.zoomScale($n.zoom-K),An=Me>K?Math.min(2,Qt):Math.max(.5,Qt),yr=Math.pow(An,1-zn),sa=$n.unproject(Mt.add(es.mult(zn*yr)).mult(Dr));$n.setLocationAtPoint($n.renderWorldCopies?sa.wrap():sa,bt)}return k.preloadOnly||this._fireMoveEvents(T),$n};if(k.preloadOnly){const $n=this._emulate(Mn,k.duration,B);return this._preloadTiles($n),this}const Yn={moving:this._moving,zooming:this._zooming,rotating:this._rotating,pitching:this._pitching};return this._zooming=Hs,this._rotating=Fs,this._pitching=nn,this._padding=rn,this._easeId=k.easeId,this._prepareEase(T,k.noMoveStart,Yn),this._ease(Mn(B),$n=>{B.cameraElevationReference==="sea"&&B.recenterOnTerrain(),this._afterEase(T,$n)},k),this}_prepareEase(k,T,B={}){this._moving=!0,this.transform.cameraElevationReference="sea",this.transform._orthographicProjectionAtLowPitch&&this.transform.pitch===0&&this.transform.projection.name!=="globe"&&(this.transform.cameraElevationReference="ground"),T||B.moving||this.fire(new o.h("movestart",k)),this._zooming&&!B.zooming&&this.fire(new o.h("zoomstart",k)),this._rotating&&!B.rotating&&this.fire(new o.h("rotatestart",k)),this._pitching&&!B.pitching&&this.fire(new o.h("pitchstart",k))}_fireMoveEvents(k){this.fire(new o.h("move",k)),this._zooming&&this.fire(new o.h("zoom",k)),this._rotating&&this.fire(new o.h("rotate",k)),this._pitching&&this.fire(new o.h("pitch",k))}_afterEase(k,T){if(this._easeId&&T&&this._easeId===T)return;this._easeId=void 0,this.transform.cameraElevationReference="ground";const B=this._zooming,K=this._rotating,Q=this._pitching;this._moving=!1,this._zooming=!1,this._rotating=!1,this._pitching=!1,this._padding=!1,B&&this.fire(new o.h("zoomend",k)),K&&this.fire(new o.h("rotateend",k)),Q&&this.fire(new o.h("pitchend",k)),this.fire(new o.h("moveend",k))}flyTo(k,T){if(this._prefersReducedMotion(k)){const Wr=o.cB(k,["center","zoom","bearing","pitch","fov","around","padding","retainPadding"]);return this.jumpTo(Wr,T)}this.stop(),k={offset:[0,0],speed:1.2,curve:1.42,easing:o.eE,...k};const B=this.transform,K=this.getZoom(),Q=this.getBearing(),le=this.getPitch(),me=this.getPadding(),we=this.getVerticalFieldOfView(),Me="zoom"in k?o.b1(+k.zoom,B.minZoom,B.maxZoom):K,Re="bearing"in k?this._normalizeBearing(k.bearing,Q):Q,Ze="pitch"in k?+k.pitch:le,Qe="fov"in k?+k.fov:we,ht=Qe!==we,_t=this._extendPadding(k.padding),bt=B.zoomScale(Me-K),Mt=o.P.convert(k.offset);let es=B.centerPoint.add(Mt);const Qt=B.pointLocation(es),Lt=o.cZ.convert(k.center||Qt);this._normalizeCenter(Lt);const ps=B.project(Qt),Hs=B.project(Lt).sub(ps);let Fs=k.curve;const nn=Math.max(B.width,B.height),$s=nn/bt,rn=Hs.mag();if("minZoom"in k){const Wr=o.b1(Math.min(k.minZoom,K,Me),B.minZoom,B.maxZoom),Mr=nn/B.zoomScale(Wr-K);Fs=Math.sqrt(Mr/rn*2)}const _n=Fs*Fs;function Mn(Wr){const Mr=($s*$s-nn*nn+(Wr?-1:1)*_n*_n*rn*rn)/(2*(Wr?$s:nn)*_n*rn);return Math.log(Math.sqrt(Mr*Mr+1)-Mr)}function Yn(Wr){return(Math.exp(Wr)-Math.exp(-Wr))/2}function $n(Wr){return(Math.exp(Wr)+Math.exp(-Wr))/2}const zn=Mn(0);let Dr=function(Wr){return $n(zn)/$n(zn+Fs*Wr)},An=function(Wr){return nn*(($n(zn)*(Yn(Mr=zn+Fs*Wr)/$n(Mr))-Yn(zn))/_n)/rn;var Mr},yr=(Mn(1)-zn)/Fs;if(Math.abs(rn)<1e-6||!isFinite(yr)){if(Math.abs(nn-$s)<1e-6)return this.easeTo(k,T);const Wr=$sk.maxDuration&&(k.duration=0);const sa=Q!==Re,ka=Ze!==le,Hr=!B.isPaddingEqual(_t),ea=k.retainPadding===!1?B.clone():B,si=Wr=>Mr=>{const Gr=Mr*yr,Ga=1/Dr(Gr);Wr.zoom=Mr===1?Me:K+Wr.scaleZoom(Ga),sa&&(Wr.bearing=o.am(Q,Re,Mr)),ka&&(Wr.pitch=o.am(le,Ze,Mr)),ht&&(Wr.fov=o.am(we,Qe,Mr)),Hr&&(ea.interpolatePadding(me,_t,Mr),es=ea.centerPoint.add(Mt));const Vr=Mr===1?Lt:Wr.unproject(ps.add(Hs.mult(An(Gr))).mult(Ga));return Wr.setLocationAtPoint(Wr.renderWorldCopies?Vr.wrap():Vr,es),Wr._updateCameraOnTerrain(),k.preloadOnly||this._fireMoveEvents(T),Wr};if(k.preloadOnly){const Wr=this._emulate(si,k.duration,B);return this._preloadTiles(Wr),this}return this._zooming=!0,this._rotating=sa,this._pitching=ka,this._padding=Hr,this._prepareEase(T,!1),this._ease(si(B),()=>this._afterEase(T),k),this}isEasing(){return!!this._easeFrameId}stop(){return this._stop()}_requestRenderFrame(k){}_cancelRenderFrame(k){}_stop({easeId:k,keepGesture:T}={}){if(this._easeFrameId&&(this._cancelRenderFrame(this._easeFrameId),this._easeFrameId=void 0,this._onEaseFrame=void 0),this._onEaseEnd){const K=this._onEaseEnd;this._onEaseEnd=void 0,K.call(this,k)}const B=this.handlers;return B&&B.stop(T),this}_ease(k,T,B){B.animate===!1||B.duration===0?(k(1),T()):(this._easeStart=o.e.now(),this._easeOptions=B,this._onEaseFrame=k,this._onEaseEnd=T,this._easeFrameId=this._requestRenderFrame(this._renderFrameCallback))}_renderFrameCallback(){const k=Math.min((o.e.now()-this._easeStart)/this._easeOptions.duration,1),T=this._onEaseFrame;T&&T(this._easeOptions.easing(k)),k<1?this._easeFrameId=this._requestRenderFrame(this._renderFrameCallback):this.stop()}_normalizeBearing(k,T){k=o.d7(k,-180,180);const B=Math.abs(k-T);return Math.abs(k-360-T)180?-360:B<-180?360:0}_prefersReducedMotion(k){return this._respectPrefersReducedMotion&&o.e.prefersReducedMotion&&!(k&&k.essential)}_emulate(k,T,B){const K=Math.ceil(15*T/1e3),Q=[],le=k(B.clone());for(let me=0;me<=K;me++){const we=le(me/K);Q.push(we.clone())}return Q}_preloadTiles(k,T){}}const Noe=/^(https?:|mailto:)/i;class tM{constructor(k={}){this.options=k,o.aW(["_toggleAttribution","_updateEditLink","_updateData","_updateCompact"],this)}getDefaultPosition(){return"bottom-right"}onAdd(k){const T=this.options&&this.options.compact,B=k._getUIString("AttributionControl.ToggleAttribution");this._map=k,this._container=g("div","mapboxgl-ctrl mapboxgl-ctrl-attrib"),this._compactButton=g("button","mapboxgl-ctrl-attrib-button",this._container),this._compactButton.type="button",this._compactButton.addEventListener("click",this._toggleAttribution),this._compactButton.setAttribute("aria-label",B);const K=g("span","mapboxgl-ctrl-icon",this._compactButton);return K.setAttribute("aria-hidden","true"),K.setAttribute("title",B),this._innerContainer=g("div","mapboxgl-ctrl-attrib-inner",this._container),T&&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),T===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 k=this._editLink;k||(k=this._editLink=this._container.querySelector(".mapbox-improve-map"));const T=[{key:"owner",value:this.styleOwner},{key:"id",value:this.styleId},{key:"access_token",value:this._map._requestManager._customAccessToken||o.eS.ACCESS_TOKEN}];if(k){const B=T.reduce((K,Q,le)=>(Q.value&&(K+=`${Q.key}=${Q.value}${leK.length-Q.length),k=k.filter((K,Q)=>{for(let le=Q+1;lefunction(Q){const le=new DOMParser().parseFromString(Q,"text/html");return Array.from(le.body.querySelectorAll("*")).reverse().forEach(me=>{const we=me.textContent||"";if(me.tagName!=="A")return void me.replaceWith(...me.childNodes);const Me=me.getAttribute("href");if(!Me||!Noe.test(Me))return void me.replaceWith(le.createTextNode(we));const Re=le.createElement("a");Re.href=Me,Re.textContent=we,Re.rel="noopener nofollow";const Ze=me.getAttribute("class");Ze&&(Re.className=Ze),me.replaceWith(Re)}),le.body.innerHTML}(K)).join(" | ");B!==this._attribHTML&&(this._attribHTML=B,k.length?(this._innerContainer.innerHTML=B,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 koe{constructor(){o.aW(["_updateLogo","_updateCompact"],this)}onAdd(k){this._map=k,this._container=g("div","mapboxgl-ctrl");const T=g("a","mapboxgl-ctrl-logo");return T.target="_blank",T.rel="noopener nofollow",T.href="https://www.mapbox.com/",T.setAttribute("aria-label",this._map._getUIString("LogoControl.Title")),T.setAttribute("rel","noopener nofollow"),this._container.appendChild(T),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(k){k&&k.sourceDataType!=="metadata"||(this._container.style.display=this._logoRequired()?"block":"none")}_logoRequired(){if(!this._map.style)return!0;const k=this._map.style._sourceCaches;if(Object.entries(k).length===0)return!0;for(const T in k){const B=k[T].getSource();if(Object.hasOwn(B,"mapbox_logo")&&!B.mapbox_logo)return!1}return!0}_updateCompact(){const k=this._container.children;if(k.length){const T=k[0];this._map.getCanvasContainer().offsetWidth<250?T.classList.add("mapboxgl-compact"):T.classList.remove("mapboxgl-compact")}}}class Of{constructor(){this._queue=[],this._id=0,this._cleared=!1,this._currentlyRunning=!1}add(k){const T=++this._id;return this._queue.push({callback:k,id:T,cancelled:!1}),T}remove(k){const T=this._currentlyRunning,B=T?this._queue.concat(T):this._queue;for(const K of B)if(K.id===k)return void(K.cancelled=!0)}run(k=0){const T=this._currentlyRunning=this._queue;this._queue=[];for(const B of T)if(!B.cancelled&&(B.callback(k),this._cleared))break;this._cleared=!1,this._currentlyRunning=!1}clear(){this._currentlyRunning&&(this._cleared=!0),this._queue=[]}}class sM{constructor(k){this.jumpTo(k)}getValue(k){if(k<=this._startTime)return this._start;if(k>=this._endTime)return this._end;const T=o.b$((k-this._startTime)/(this._endTime-this._startTime));return this._start*(1-T)+this._end*T}isEasing(k){return k>=this._startTime&&k<=this._endTime}jumpTo(k){this._startTime=-1/0,this._endTime=-1/0,this._start=k,this._end=k}easeTo(k,T,B){this._start=this.getValue(T),this._end=k,this._startTime=T,this._endTime=T+B}}const Soe={"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 K6 extends o.h{constructor(k,T,B,K){const{point:Q,lngLat:le,originalEvent:me,target:we}=k;super(k.type,{point:Q,lngLat:le,originalEvent:me,target:we}),this.preventDefault=()=>{k.preventDefault()},this.id=T,this.interaction=B,this.feature=K}}class z9{constructor(k){this.map=k,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(k,T){if(this.typeById.has(k))throw new Error(`Interaction id "${k}" already exists.`);const B=T.filter;let K=T.type;B&&this.filters.set(k,o.bw(B)),K==="mouseover"&&(K="mouseenter"),K==="mouseout"&&(K="mouseleave");const Q=this.interactionsByType.get(K)||new Map;K==="mouseenter"||K==="mouseleave"?(this.delegatedInteractions.size===0&&(this.map.on("mousemove",this.handleMove),this.map.on("mouseout",this.handleOut)),this.delegatedInteractions.set(k,T)):Q.size===0&&this.map.on(K,this.handleType),Q.size===0&&this.interactionsByType.set(K,Q),Q.set(k,T),this.typeById.set(k,K)}get(k){const T=this.typeById.get(k);if(!T)return;const B=this.interactionsByType.get(T);return B?B.get(k):void 0}remove(k){const T=this.typeById.get(k);if(!T)return;this.typeById.delete(k),this.filters.delete(k);const B=this.interactionsByType.get(T);B&&(B.delete(k),T==="mouseenter"||T==="mouseleave"?(this.delegatedInteractions.delete(k),this.delegatedInteractions.size===0&&(this.map.off("mousemove",this.handleMove),this.map.off("mouseout",this.handleOut))):B.size===0&&this.map.off(T,this.handleType))}queryTargets(k,T){const B=[];for(const[K,Q]of T)Q.target&&B.push({targetId:K,target:Q.target,filter:this.filters.get(K)});return this.map.style.queryRenderedTargets(k,B,this.map.transform)}handleMove(k){this.prevHoveredFeatures=this.hoveredFeatures,this.hoveredFeatures=new Map;const T=this.queryTargets(k.point,Array.from(this.delegatedInteractions).reverse());T.length&&(k.type="mouseenter",this.handleType(k,T));const B=new Map;for(const[K,{feature:Q}]of this.prevHoveredFeatures)this.hoveredFeatures.has(K)||B.set(Q.id,Q);B.size&&(k.type="mouseleave",this.handleType(k,Array.from(B.values())))}handleOut(k){const T=Array.from(this.hoveredFeatures.values()).map(({feature:B})=>B);T.length&&(k.type="mouseleave",this.handleType(k,T)),this.hoveredFeatures.clear()}handleType(k,T){const B=k.type==="mouseenter";if(B&&!this.interactionsByType.has(k.type))return void o.w("mouseenter interaction required for mouseleave to work.");const K=Array.from(this.interactionsByType.get(k.type)).reverse(),Q=!!T;T=T||this.queryTargets(k.point,K);let le=!1;const me=new Set;for(const we of T){for(const[Me,Re]of K){if(!Re.target)continue;const Ze=we.variants?we.variants[Me]:null;if(Ze){for(const Qe of Ze){if(Qd(Qe,we,me,Me))continue;const ht=new o.dP(we,Qe),_t=ig(Qe,we,Me);Q&&ht.id!==void 0&&(ht.state=this.map.getFeatureState(ht));const bt=B?this.prevHoveredFeatures.get(_t):null,Mt=new K6(k,Me,Re,ht),es=bt?bt.stop:Re.handler(Mt);if(B&&this.hoveredFeatures.set(_t,{feature:we,stop:es}),es!==!1){le=!0;break}}if(le)break}}if(le)break}if(!le)for(const[we,Me]of K){const{handler:Re,target:Ze}=Me;if(!Ze&&Re(new K6(k,we,Me,null))!==!1)break}}}function Y6(L,k){if(Array.isArray(L)&&Array.isArray(k)){const T=new Set(L),B=new Set(k);return T.size===B.size&&L.every(K=>B.has(K))}return o.O(L,k)}const Coe=/matrix.*\((.+)\)/,Aoe={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,fontstackCompositing:"client",transformRequest:null,accessToken:null,fadeDuration:300,respectPrefersReducedMotion:!0,crossSourceCollisions:!0,collectResourceTiming:!1,testMode:!1,precompilePrograms:!0,scaleFactor:1,emissiveColorPrecision:"approximate"},Z6={showCompass:!0,showZoom:!0,visualizePitch:!1};class _Y{constructor(k,T,B=!1){this._clickTolerance=10,this.element=T,this.mouseRotate=new H6({clickTolerance:k.dragRotate._mouseRotate._clickTolerance}),this.map=k,B&&(this.mousePitch=new I9({clickTolerance:k.dragRotate._mousePitch._clickTolerance})),o.aW(["mousedown","mousemove","mouseup","touchstart","touchmove","touchend","reset"],this),T.addEventListener("mousedown",this.mousedown),T.addEventListener("touchstart",this.touchstart,{passive:!1}),T.addEventListener("touchmove",this.touchmove),T.addEventListener("touchend",this.touchend),T.addEventListener("touchcancel",this.reset)}down(k,T){this.mouseRotate.mousedown(k,T),this.mousePitch&&this.mousePitch.mousedown(k,T),w()}move(k,T){const B=this.map,K=this.mouseRotate.mousemoveWindow(k,T),Q=K&&K.bearingDelta;if(Q&&B.setBearing(B.getBearing()+Q),this.mousePitch){const le=this.mousePitch.mousemoveWindow(k,T),me=le&&le.pitchDelta;me&&B.setPitch(B.getPitch()+me)}}off(){const k=this.element;k.removeEventListener("mousedown",this.mousedown),k.removeEventListener("touchstart",this.touchstart),k.removeEventListener("touchmove",this.touchmove),k.removeEventListener("touchend",this.touchend),k.removeEventListener("touchcancel",this.reset),this.offTemp()}offTemp(){S(),window.removeEventListener("mousemove",this.mousemove),window.removeEventListener("mouseup",this.mouseup)}mousedown(k){this.down({...k,button:k.button,type:k.type,ctrlKey:!0,preventDefault:()=>k.preventDefault()},I(this.element,k)),window.addEventListener("mousemove",this.mousemove),window.addEventListener("mouseup",this.mouseup)}mousemove(k){this.move(k,I(this.element,k))}mouseup(k){this.mouseRotate.mouseupWindow(k),this.mousePitch&&this.mousePitch.mouseupWindow(k),this.offTemp()}touchstart(k){k.targetTouches.length!==1?this.reset():(this._startPos=this._lastPos=P(this.element,k.targetTouches)[0],this.down({type:"mousedown",button:0,ctrlKey:!0,preventDefault:()=>k.preventDefault()},this._startPos))}touchmove(k){k.targetTouches.length!==1?this.reset():(this._lastPos=P(this.element,k.targetTouches)[0],this.move({buttons:1,preventDefault:()=>k.preventDefault()},this._lastPos))}touchend(k){k.targetTouches.length===0&&this._startPos&&this._lastPos&&this._startPos.dist(this._lastPos)T.width||k.y>T.height;T.locationPoint3D(B).distSqr(k)180;){const B=T.locationPoint3D(L);if(B.x>=0&&B.y>=0&&B.x<=T.width&&B.y<=T.height)break;L.lng>T.center.lng?L.lng-=360:L.lng+=360}return L}const X6={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%)"},jY=/\s+/,gf={rotation:0,rotationAlignment:"auto",pitchAlignment:"auto",occludedOpacity:.2,altitude:0};class Kk extends o.E{constructor(k,T){super(),(k instanceof HTMLElement||T)&&(k={element:k,...T}),o.aW(["_update","_onMove","_onUp","_addDragHandler","_onMapClick","_onKeyPress","_clearFadeTimer"],this);const{anchor:B="center",color:K="#3FB1CE",scale:Q=1,draggable:le=!1,clickTolerance:me=0,rotation:we=gf.rotation,rotationAlignment:Me=gf.rotationAlignment,pitchAlignment:Re=gf.pitchAlignment,occludedOpacity:Ze=gf.occludedOpacity,altitude:Qe=gf.altitude}=k||{};this._anchor=B,this._color=K,this._scale=Q,this._draggable=le,this._clickTolerance=me,this._rotation=we,this._rotationAlignment=Me,this._pitchAlignment=Re,this._occludedOpacity=Ze,this._altitude=Qe,this._state="inactive",this._isDragging=!1,this._pointerEvents=null,this._updateMoving=()=>this._update(!0),k&&k.element?(this._element=k.element,this._offset=o.P.convert(k&&k.offset||[0,0])):(this._defaultMarker=!0,this._element=this._createDefaultMarker(),this._offset=o.P.convert(k&&k.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",_t=>{_t.preventDefault()}),this._element.addEventListener("mousedown",_t=>{_t.preventDefault()});const ht=this._element.classList;for(const _t in X6)ht.remove(`mapboxgl-marker-anchor-${_t}`);ht.add(`mapboxgl-marker-anchor-${this._anchor}`),k&&k.className&&ht.add(...k.className.trim().split(jY)),this._popup=null}_createDefaultMarker(){const k=g("div"),T=x("svg",{display:"block",height:41*this._scale+"px",width:27*this._scale+"px",viewBox:"0 0 27 41"},k);this._svgElement=T;const B=x("radialGradient",{id:"shadowGradient"},x("defs",{},T));x("stop",{offset:"10%","stop-opacity":.4},B),x("stop",{offset:"100%","stop-opacity":.05},B);const K=x("ellipse",{cx:13.5,cy:34.8,rx:10.5,ry:5.25,fill:"url(#shadowGradient)"});return this._shadowElement=K,this._altitude===0&&T.insertBefore(K,T.firstChild),x("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"},T),x("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"},T),x("circle",{fill:"white",cx:13.5,cy:13.5,r:5.5},T),k}addTo(k){return k===this._map||(this.remove(),this._map=k,k.getCanvasContainer().appendChild(this._element),k.on("move",this._updateMoving),k.on("moveend",this._update),k.on("remove",this._clearFadeTimer),k._addMarker(this),this.setDraggable(this._draggable),this._update(),k.on("click",this._onMapClick)),this}remove(){const k=this._map;return k&&(k.off("click",this._onMapClick),k.off("move",this._updateMoving),k.off("moveend",this._update),k.off("mousedown",this._addDragHandler),k.off("touchstart",this._addDragHandler),k.off("mouseup",this._onUp),k.off("touchend",this._onUp),k.off("mousemove",this._onMove),k.off("touchmove",this._onMove),k.off("remove",this._clearFadeTimer),k._removeMarker(this),this._map=void 0),this._clearFadeTimer(),this._element.remove(),this._popup&&this._popup.remove(),this}getLngLat(){return this._lngLat}setLngLat(k){return this._lngLat=o.cZ.convert(k),this._pos=null,this._popup&&this._popup.setLngLat(this._lngLat),this._update(!0),this}setAltitude(k){if(k===this._altitude)return this;const T=this._altitude;return this._altitude=k||gf.altitude,this._defaultMarker&&T===0!=(this._altitude===0)&&(this._altitude===0?this._svgElement.insertBefore(this._shadowElement,this._svgElement.firstChild):this._shadowElement.remove()),this._update(),this}getAltitude(){return this._altitude}getElement(){return this._element}setPopup(k){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")),k){if(!("offset"in k.options)){const K=Math.sqrt(Math.pow(13.5,2)/2);k.options.offset=this._defaultMarker?{top:[0,0],"top-left":[0,0],"top-right":[0,0],bottom:[0,-38.1],"bottom-left":[K,-1*(38.1-13.5+K)],"bottom-right":[-K,-1*(38.1-13.5+K)],left:[13.5,-1*(38.1-13.5)],right:[-13.5,-1*(38.1-13.5)]}:this._offset}this._popup=k,k._marker=this,k._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(k){const T=k.code,B=k.charCode||k.keyCode;T!=="Space"&&T!=="Enter"&&B!==32&&B!==13||this.togglePopup()}_onMapClick(k){const T=k.originalEvent.target,B=this._element;this._popup&&(T===B||B.contains(T))&&this.togglePopup()}getPopup(){return this._popup}togglePopup(){const k=this._popup;return k?(k.isOpen()?(k.remove(),this._element.setAttribute("aria-expanded","false")):this._map&&(k.addTo(this._map),this._element.setAttribute("aria-expanded","true")),this):this}_behindTerrain(){const k=this._map,T=this._pos;if(!k||!T)return!1;const B=k.unproject(T,this._altitude),K=k.getFreeCameraOptions();if(!K.position)return!1;const Q=K.position.toLngLat();return Q.distanceTo(B)<.9*Q.distanceTo(this._lngLat)}_evaluateOpacity(){const k=this._map;if(!k)return;const T=this._pos;if(!T||T.x<0||T.x>k.transform.width||T.y<0||T.y>k.transform.height)return void this._clearFadeTimer();const B=k.unproject(T,this._altitude);let K;k._showingGlobe()&&o.f9(k.transform,this._lngLat)?K=0:(K=1-k._queryFogOpacity(B),k.transform._terrainEnabled()&&k.style&&k.style.hasTerrain()&&this._behindTerrain()&&(K*=this._occludedOpacity)),this._element.style.opacity=`${K}`;const Q=this._element.style.pointerEvents;(this._pointerEvents===null?Q==="":Q===this._pointerEvents)&&(this._pointerEvents=K>0?"auto":"none",this._element.style.pointerEvents=this._pointerEvents),this._popup&&this._popup._setOpacity(K),this._fadeTimer=null}_clearFadeTimer(){this._fadeTimer&&(clearTimeout(this._fadeTimer),this._fadeTimer=null)}_updateDOM(){const k=this._pos;if(!k||!this._map)return;const T=this._offset.mult(this._scale);this._element.style.transform=` translate(${k.x}px,${k.y}px) ${X6[this._anchor]} ${this._calculateXYTransform()} ${this._calculateZTransform()} translate(${T.x}px,${T.y}px) `}_calculateXYTransform(){const k=this._pos,T=this._map,B=this.getPitchAlignment();if(!T||!k||B!=="map")return"";if(!T._showingGlobe()){const we=T.getPitch();return we?`rotateX(${we}deg)`:""}const K=o.fa(o.fb(T.transform,this._lngLat)),Q=k.sub(o.fc(T.transform)),le=Math.abs(Q.x)+Math.abs(Q.y);if(le===0)return"";const me=K/le;return`rotateX(${-Q.y*me}deg) rotateY(${Q.x*me}deg)`}_calculateZTransform(){const k=this._pos,T=this._map;if(!T||!k)return"";let B=0;const K=this.getRotationAlignment();if(K==="map")if(T._showingGlobe()){const Q=T.project(new o.cZ(this._lngLat.lng,this._lngLat.lat+.001),this._altitude),le=T.project(new o.cZ(this._lngLat.lng,this._lngLat.lat-.001),this._altitude).sub(Q);B=o.fa(Math.atan2(le.y,le.x))-90}else B=-T.getBearing();else if(K==="horizon"){const Q=o.an(4,6,T.getZoom()),le=o.fc(T.transform);le.y+=Q*T.transform.height;const me=k.sub(le),we=o.fa(Math.atan2(me.y,me.x));B=(we>90?we-270:we+90)*(1-Q)}return B+=this._rotation,B?`rotateZ(${B}deg)`:""}_update(k){cancelAnimationFrame(this._updateFrameId);const T=this._map;T&&(T.transform.renderWorldCopies&&(this._lngLat=wY(this._lngLat,this._pos,T.transform)),this._pos=T.project(this._lngLat,this._altitude),k===!0?this._updateFrameId=requestAnimationFrame(()=>{this._element&&this._pos&&this._anchor&&(this._pos=this._pos.round(),this._updateDOM())}):this._pos=this._pos.round(),T._requestDomTask(()=>{this._map&&(this._element&&this._pos&&this._anchor&&this._updateDOM(),(T._showingGlobe()||T.style&&T.style.hasTerrain()||T.getFog())&&!this._fadeTimer&&(this._fadeTimer=window.setTimeout(this._evaluateOpacity.bind(this),60)))}))}getOffset(){return this._offset}setOffset(k){return this._offset=o.P.convert(k),this._update(),this}addClassName(k){return this._element.classList.add(k),this}removeClassName(k){return this._element.classList.remove(k),this}toggleClassName(k){return this._element.classList.toggle(k)}_onMove(k){const T=this._map;if(!T)return;const B=this._pointerdownPos,K=this._positionDelta;if(B&&K){if(!this._isDragging){const Q=this._clickTolerance||T._clickTolerance;if(k.point.dist(B)`mapboxgl-ctrl-geolocate-${L}`,K_=["waiting","active","active-error","background","background-error"].map(Wv),cj={positionOptions:{enableHighAccuracy:!1,maximumAge:0,timeout:6e3},fitBoundsOptions:{maxZoom:15},trackUserLocation:!1,showAccuracyCircle:!0,showUserLocation:!0,showUserHeading:!1,showButton:!0,followUserLocation:!0},O3={maxWidth:100,unit:"metric"},nM={kilometer:"km",meter:"m",mile:"mi",foot:"ft","nautical-mile":"nm"},kY=/\s+/,Ll={closeButton:!0,closeOnClick:!0,focusAfterOpen:!0,className:"",maxWidth:"240px",altitude:0},Y_=["a[href]","[tabindex]:not([tabindex='-1'])","[contenteditable]:not([contenteditable='false'])","button:not([disabled])","input:not([disabled])","select:not([disabled])","textarea:not([disabled])"].join(", ");function Q6(L=new o.P(0,0),k="bottom"){if(typeof L=="number"){const T=Math.round(Math.sqrt(.5*Math.pow(L,2)));switch(k){case"top":return new o.P(0,L);case"top-left":return new o.P(T,T);case"top-right":return new o.P(-T,T);case"bottom":return new o.P(0,-L);case"bottom-left":return new o.P(T,-T);case"bottom-right":return new o.P(-T,-T);case"left":return new o.P(L,0);case"right":return new o.P(-L,0)}return new o.P(0,0)}return L instanceof o.P||Array.isArray(L)?o.P.convert(L):o.P.convert(L[k]||[0,0])}const eu=typeof document<"u"?document.currentScript:null;return o.fd(eu&&eu.src&&o.fe(eu.src)?"cdn":"other"),{version:o.f8,supported:function(L){return!function(k){return typeof window<"u"&&typeof document<"u"?Object.hasOwn?typeof Worker>"u"?"Web Workers not supported":function(){const T=document.createElement("canvas");T.width=T.height=1;const B=T.getContext("2d");return!!B&&B.getImageData(0,0,1,1).width===T.width}()?function(T){return T?(u===void 0&&(u=h(!0)),u):(d===void 0&&(d=h(!1)),d)}(k)?"":"insufficient WebGL2 support":"insufficient Canvas/getImageData support":"Object.hasOwn not supported":"not a browser"}(L)},setRTLTextPlugin:o.fj,getRTLTextPluginStatus:o.fi,setSdkInfo:o.fh,addTileProvider:o.fg,Map:class extends HFe{constructor(L){o.eT.mark(o.eU.create);const k=L;if((L={...Aoe,...L}).minZoom!=null&&L.maxZoom!=null&&L.minZoom>L.maxZoom)throw new Error("maxZoom must be greater than or equal to minZoom");if(L.minPitch!=null&&L.maxPitch!=null&&L.minPitch>L.maxPitch)throw new Error("maxPitch must be greater than or equal to minPitch");if(L.minPitch!=null&&L.minPitch<0)throw new Error("minPitch must be greater than or equal to 0");if(L.maxPitch!=null&&L.maxPitch>85)throw new Error("maxPitch must be less than or equal to 85");super(new o.eV(L.minZoom,L.maxZoom,L.minPitch,L.maxPitch,L.renderWorldCopies,null,null),L),this._animationFrameProvider=L.animationFrameProvider,this._repaint=!!L.repaint,this._interactive=L.interactive,this._minTileCacheSize=L.minTileCacheSize,this._maxTileCacheSize=L.maxTileCacheSize,this._failIfMajorPerformanceCaveat=L.failIfMajorPerformanceCaveat,this._preserveDrawingBuffer=L.preserveDrawingBuffer,this._antialias=L.antialias,this._trackResize=L.trackResize,this._bearingSnap=L.bearingSnap,this._refreshExpiredTiles=L.refreshExpiredTiles,this._fadeDuration=L.fadeDuration,this._placementAlgorithm=L.placementAlgorithm||"default",this._isInitialLoad=!0,this._crossSourceCollisions=L.crossSourceCollisions,this._collectResourceTiming=L.collectResourceTiming,this._language=this._parseLanguage(L.language),this._worldview=L.worldview,this._renderTaskQueue=new Of,this._domRenderTaskQueue=new Of,this._controls=[],this._markers=[],this._popups=[],this._mapId=o.aw(),this._locale={...Soe,...L.locale},this._clickTolerance=L.clickTolerance,this._cooperativeGestures=L.cooperativeGestures,this._performanceMetricsCollection=L.performanceMetricsCollection,this._tessellationStep=L.tessellationStep,this._containerWidth=0,this._containerHeight=0,this._showParseStatus=!0,this._precompilePrograms=L.precompilePrograms,this._averageElevationLastSampledAt=-1/0,this._averageElevationExaggeration=0,this._averageElevation=new sM(0),this._interactionRange=[1/0,-1/0],this._visibilityHidden=0,this._useExplicitProjection=!1,this._frameId=0,this._emissiveColorPrecision=L.emissiveColorPrecision,this._scaleFactor=L.scaleFactor,this._requestManager=new o.eW(L.transformRequest,L.accessToken,L.testMode);const T=o.eX(L.accessToken||o.eS.ACCESS_TOKEN);if(T&&"atlas"in T&&typeof T.atlas=="number"&&(this._tokenExpiration=T.atlas),this._silenceAuthErrors=!!L.testMode,this._contextCreateOptions=L.contextCreateOptions?{...L.contextCreateOptions}:{},typeof L.container=="string"){const B=document.getElementById(L.container);if(!B)throw new Error(`Container '${L.container.toString()}' not found.`);this._container=B}else{if(!(L.container instanceof HTMLElement))throw new Error("Invalid type: 'container' must be a String or HTMLElement.");this._container=L.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."),L.maxBounds&&this.setMaxBounds(L.maxBounds),this._spriteFormat="auto",o.aW(["_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 VFe(this,L),this._localFontFamily=L.localFontFamily,this._localIdeographFontFamily=L.localIdeographFontFamily,this._fontstackCompositing=L.fontstackCompositing,(L.style||!L.testMode)&&this.setStyle(L.style||o.eS.DEFAULT_STYLE,{config:L.config,localFontFamily:this._localFontFamily,localIdeographFontFamily:this._localIdeographFontFamily,fontstackCompositing:this._fontstackCompositing}),L.projection&&this.setProjection(L.projection),L.hash&&(this._hash=new W_(typeof L.hash=="string"&&L.hash||void 0).addTo(this)),!this._hash||!this._hash._onHashChange()){k.center==null&&k.zoom==null||(this.transform._unmodified=!1),this.jumpTo({center:L.center,zoom:L.zoom,bearing:L.bearing,pitch:L.pitch});const B=L.bounds;B&&(this.resize(),this.fitBounds(B,{...L.fitBoundsOptions,duration:0}))}this.resize(),L.attributionControl&&this.addControl(new tM({customAttribution:L.customAttribution})),this._logoControl=new koe,this.addControl(this._logoControl,L.logoPosition),this.on("style.load",()=>{this.transform.unmodified&&this.jumpTo(this.style.stylesheet),this._postStyleLoadEvent(),this._postStyleWithAppearanceEvent()}),this.on("data",B=>{this._update(B.dataType==="style"),this.fire(new o.h(`${B.dataType}data`,B))}),this.on("dataloading",B=>{this.fire(new o.h(`${B.dataType}dataloading`,B))}),this._interactions=new z9(this)}_getMapId(){return this._mapId}addControl(L,k){if(k===void 0&&(k=L.getDefaultPosition?L.getDefaultPosition():"top-right"),!L||!L.onAdd)return this.fire(new o.f(new Error("Invalid argument to map.addControl(). Argument must be a control with onAdd and onRemove methods.")));const T=L.onAdd(this);this._controls.push(L);const B=this._controlPositions[k];return k.includes("bottom")?B.insertBefore(T,B.firstChild):B.appendChild(T),this}removeControl(L){if(!L||!L.onRemove)return this.fire(new o.f(new Error("Invalid argument to map.removeControl(). Argument must be a control with onAdd and onRemove methods.")));const k=this._controls.indexOf(L);return k>-1&&this._controls.splice(k,1),L.onRemove(this),this}hasControl(L){return this._controls.includes(L)}getContainer(){return this._container}getCanvasContainer(){return this._canvasContainer}getCanvas(){return this._canvas}resize(L){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 k=!this._moving;return k&&this.fire(new o.h("movestart",L)).fire(new o.h("move",L)),this.fire(new o.h("resize",L)),k&&this.fire(new o.h("moveend",L)),this}getBounds(){return this.transform.getBounds()}getMaxBounds(){return this.transform.getMaxBounds()||null}setMaxBounds(L){return this.transform.setMaxBounds(o.eI.convert(L)),this._update()}setMinZoom(L){if((L=L??-2)>=-2&&L<=this.transform.maxZoom)return this.transform.minZoom=L,this._update(),this.getZoom()=this.transform.minZoom)return this.transform.maxZoom=L,this._update(),this.getZoom()>L?this.setZoom(L):this.fire(new o.h("zoomstart")).fire(new o.h("zoom")).fire(new o.h("zoomend")),this;throw new Error("maxZoom must be greater than the current minZoom")}getMaxZoom(){return this.transform.maxZoom}setMinPitch(L){if((L=L??0)<0)throw new Error("minPitch must be greater than or equal to 0");if(L>=0&&L<=this.transform.maxPitch)return this.transform.minPitch=L,this._update(),this.getPitch()85)throw new Error("maxPitch must be less than or equal to 85");if(L>=this.transform.minPitch)return this.transform.maxPitch=L,this._update(),this.getPitch()>L?this.setPitch(L):this.fire(new o.h("pitchstart")).fire(new o.h("pitch")).fire(new o.h("pitchend")),this;throw new Error("maxPitch must be greater than or equal to minPitch")}getMaxPitch(){return this.transform.maxPitch}getScaleFactor(){return this._scaleFactor}setScaleFactor(L){return this._scaleFactor=L,this.painter.scaleFactor=L,this.style&&this.style._setLabelPlacementStale(),this.style._updateFilteredLayers(k=>k.type==="symbol"),this._update(!0),this}getRenderWorldCopies(){return this.transform.renderWorldCopies}setRenderWorldCopies(L){return this.transform.renderWorldCopies=L,this.transform.renderWorldCopies||this._forceMarkerAndPopupUpdate(!0),this._update()}getLanguage(){return this._language}_parseLanguage(L){return L==="auto"?navigator.language:Array.isArray(L)?L.length===0?void 0:L.map(k=>k==="auto"?navigator.language:k):L}setLanguage(L){const k=this._parseLanguage(L);if(!this.style||k===this._language)return this;this._language=k,this.style.reloadSources();for(const T of this._controls)T._setLanguage&&T._setLanguage(this._language);return this}getWorldview(){return this._worldview}setWorldview(L){return this.style&&L!==this._worldview?(this._worldview=L,this._styleDirty=!0,this.style.setWorldview(L),this):this}getProjection(){return this.transform.mercatorFromTransition?{name:"globe",center:[0,0]}:this.transform.getProjection()}_showingGlobe(){return this.transform.projection.name==="globe"}setProjection(L){return this._lazyInitEmptyStyle(),L?typeof L=="string"&&(L={name:L}):L=null,this._useExplicitProjection=!!L,this._prioritizeAndUpdateProjection(L,this.style.projection)}_updateProjectionTransition(){if(this.getProjection().name!=="globe")return;const L=this.transform,k=L.projection.name;let T;k==="globe"&&L.zoom>=o.b2?(L.setMercatorFromTransition(),T=!0):k==="mercator"&&L.zoom=o.b2?this.transform.setMercatorFromTransition():this.transform.setProjection(L),this.style.applyProjectionUpdate();const B=this.transform.getProjection().name==="mercator"&&T!==this.transform.mercatorFromTransition;return(k||B)&&(this.painter.clearBackgroundTiles(),this.style.clearSources(),this._update(!0),this._forceMarkerAndPopupUpdate(!0)),this}project(L,k){return this.transform.locationPoint3D(o.cZ.convert(L),k)}unproject(L,k){return this.transform.pointLocation3D(o.P.convert(L),k)}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(L,k,T){const B=K=>{let Q=[];if(Array.isArray(k)){const le=k.filter(me=>this.getLayer(me));Q=le.length?this.queryRenderedFeatures(K,{layers:le}):[]}else Q=this.queryRenderedFeatures(K,{target:k});return Q};if(L==="mouseenter"||L==="mouseover"){let K=!1;return{listener:T,targets:k,delegates:{mousemove:le=>{const me=B(le.point);me.length?K||(K=!0,T.call(this,new Sl(L,this,le.originalEvent,{features:me}))):K=!1},mouseout:()=>{K=!1}}}}if(L==="mouseleave"||L==="mouseout"){let K=!1;return{listener:T,targets:k,delegates:{mousemove:me=>{B(me.point).length?K=!0:K&&(K=!1,T.call(this,new Sl(L,this,me.originalEvent)))},mouseout:me=>{K&&(K=!1,T.call(this,new Sl(L,this,me.originalEvent)))}}}}{const K=Q=>{const le=B(Q.point);le.length&&(Q.features=le,T.call(this,Q),delete Q.features)};return{listener:T,targets:k,delegates:{[L]:K}}}}on(L,k,T){if(typeof k=="function"||T===void 0)return super.on(L,k);if(typeof k=="string"&&(k=[k]),!this._areTargetsValid(k))return this;const B=this._createDelegatedListener(L,k,T);this._delegatedListeners=this._delegatedListeners||{},this._delegatedListeners[L]=this._delegatedListeners[L]||[],this._delegatedListeners[L].push(B);for(const K in B.delegates)this.on(K,B.delegates[K]);return this}once(L,k,T){if(typeof k=="function"||T===void 0)return super.once(L,k);if(typeof k=="string"&&(k=[k]),!this._areTargetsValid(k))return this;const B=this._createDelegatedListener(L,k,T);for(const K in B.delegates)this.once(K,B.delegates[K]);return this}off(L,k,T){if(typeof k=="function"||T===void 0)return super.off(L,k);if(typeof k=="string"&&(k=[k]),!this._areTargetsValid(k))return this;const B=this._delegatedListeners?this._delegatedListeners[L]:void 0;return B&&(K=>{for(let Q=0;Q{if(T){const K=typeof T=="string"?T:T instanceof Error?T.message:T.error;o.w(`Unable to perform style diff: ${K}. Rebuilding the style from scratch.`),this._updateStyle(L,k)}else B&&this._update(!0)},()=>this._postStyleLoadEvent()),this):(this._localIdeographFontFamily=k.localIdeographFontFamily,this._localFontFamily=k.localFontFamily,this._fontstackCompositing=k.fontstackCompositing,this._updateStyle(L,k))}_getUIString(L){const k=this._locale[L];if(k==null)throw new Error(`Missing UI string '${L}'`);return k}_updateStyle(L,k){if(this.style&&(this.style.setEventedParent(null),this.style._remove(),this.style=void 0),L){const T={...k};k&&k.config&&(T.initialConfig=k.config,delete T.config),this.style=new up(this,T).load(L),this.style.setEventedParent(this,{style:this.style})}return this._updateTerrain(),this}_lazyInitEmptyStyle(){this.style||(this.style=new up(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(L){return L==null?(this.fire(new o.f(new Error("IDs can't be empty."))),!1):o.dI(L)?(this.fire(new o.f(new Error(`IDs can't contain special symbols: "${L}".`))),!1):L!=="__proto__"&&L!=="constructor"&&L!=="prototype"||(this.fire(new o.f(new Error(`IDs can't be "${L}".`))),!1)}_isTargetValid(L){return"featuresetId"in L?this._isValidId("importId"in L?L.importId:L.featuresetId):"layerId"in L&&this._isValidId(L.layerId)}_areTargetsValid(L){if(Array.isArray(L)){for(const k of L)if(!this._isValidId(k))return!1;return!0}return this._isTargetValid(L)}addSource(L,k){return this._isValidId(L)?(this._lazyInitEmptyStyle(),this.style.addSource(L,k),this._update(!0)):this}isSourceLoaded(L){return!!this._isValidId(L)&&!!this.style&&this.style._isSourceCacheLoaded(L)}areTilesLoaded(){return this.style.areTilesLoaded()}removeSource(L){return this._isValidId(L)?(this.style.removeSource(L),this._updateTerrain(),this._update(!0)):this}getSource(L){return this._isValidId(L)?this.style.getOwnSource(L):null}addImage(L,k,{pixelRatio:T=1,sdf:B=!1,stretchX:K,stretchY:Q,content:le}={}){this._lazyInitEmptyStyle();const me=o.I.from(L);if(k instanceof HTMLImageElement||ImageBitmap&&k instanceof ImageBitmap){const{width:we,height:Me,data:Re}=o.e.getImageData(k);this.style.addImage(me,{data:new o.b({width:we,height:Me},Re),pixelRatio:T,stretchX:K,stretchY:Q,content:le,sdf:B,version:0,usvg:!1})}else if(k.width===void 0||k.height===void 0)this.fire(new o.f(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:we,height:Me}=k,Re=k;this.style.addImage(me,{data:new o.b({width:we,height:Me},new Uint8Array(Re.data)),pixelRatio:T,stretchX:K,stretchY:Q,content:le,sdf:B,usvg:!1,version:0,userImage:Re}),Re.onAdd&&Re.onAdd(this,L)}}updateImage(L,k){this._lazyInitEmptyStyle();const T=o.I.from(L),B=this.style.getImage(T);if(!B)return void this.fire(new o.f(new Error("The map has no image with that id. If you are adding a new image use `map.addImage(...)` instead.")));const K=k instanceof HTMLImageElement||ImageBitmap&&k instanceof ImageBitmap?o.e.getImageData(k):k,{width:Q,height:le,data:me}=K;if(Q===void 0||le===void 0)return void this.fire(new o.f(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!==(B.usvg?B.icon.usvg_tree.width:B.data.width)||le!==(B.usvg?B.icon.usvg_tree.height:B.data.height))return void this.fire(new o.f(new Error(`The width and height of the updated image (${Q}, ${le}) must be that same as the previous version of the image (${B.data.width}, ${B.data.height})`)));const we=!(k instanceof HTMLImageElement||ImageBitmap&&k instanceof ImageBitmap);let Me=!1;B.usvg?(B.data=new o.b({width:Q,height:le},new Uint8Array(me)),B.usvg=!1,B.icon=void 0,Me=!0):B.data.replace(me,we),this.style.updateImage(T,B,Me)}hasImage(L){return L?!!this.style&&!!this.style.getImage(o.I.from(L)):(this.fire(new o.f(new Error("Missing required image id"))),!1)}removeImage(L){this.style.removeImage(o.I.from(L))}loadImage(L,k){(async()=>{const T=await this._requestManager.transformRequest(L,o.R.Image),{data:B}=await o.a(T);return B})().then(T=>k(null,T)).catch(k)}listImages(){return this.style.listImages().map(L=>L.name)}addModel(L,k){this._lazyInitEmptyStyle(),this.style.addModel(L,k)}hasModel(L){return L?this.style.hasModel(L):(this.fire(new o.f(new Error("Missing required model id"))),!1)}removeModel(L){this.style.removeModel(L)}listModels(){return this.style.listModels()}addLayer(L,k){return this._isValidId(L.id)?(this._lazyInitEmptyStyle(),this.style.addLayer(L,k),this._update(!0)):this}getSlot(L){const k=this.getLayer(L);return k&&k.slot||null}setSlot(L,k){return this.style.setSlot(L,k),this.style.mergeLayers(),this._update(!0)}addImport(L,k){return this._isValidId(L.id)?(this.style.addImport(L,k).catch(T=>this.fire(new o.f(new Error("Failed to add import",T)))),this):this}updateImport(L,k){return typeof k!="string"&&k.id!==L?(this.removeImport(L),this.addImport(k)):(this.style.updateImport(L,k),this._update(!0))}removeImport(L){return this.style.removeImport(L),this}moveImport(L,k){return this.style.moveImport(L,k),this._update(!0)}moveLayer(L,k){return this._isValidId(L)?(this.style.moveLayer(L,k),this._update(!0)):this}removeLayer(L){return this._isValidId(L)?(this.style.removeLayer(L),this._update(!0)):this}getLayer(L){if(!this._isValidId(L))return null;const k=this.style.getOwnLayer(L);return k?k.type==="custom"?k.implementation:k.serialize():void 0}getSlots(){return this.style.getSlots()}setLayerZoomRange(L,k,T){return this._isValidId(L)?(this.style.setLayerZoomRange(L,k,T),this._update(!0)):this}setFilter(L,k,T={}){return this._isValidId(L)?(this.style.setFilter(L,k,T),this._update(!0)):this}getFilter(L){return this._isValidId(L)?this.style.getFilter(L):null}setPaintProperty(L,k,T,B={}){return this._isValidId(L)?(this.style.setPaintProperty(L,k,T,B),this._update(!0)):this}getPaintProperty(L,k){return this._isValidId(L)?this.style.getPaintProperty(L,k):null}setLayoutProperty(L,k,T,B={}){return this._isValidId(L)?(this.style.setLayoutProperty(L,k,T,B),this._update(!0)):this}getLayoutProperty(L,k){return this._isValidId(L)?this.style.getLayoutProperty(L,k):null}getLayerProperty(L,k){return this._isValidId(L)?this.style.getLayerProperty(L,k):null}setLayerProperty(L,k,T,B={}){return this._isValidId(L)?(k==="appearances"&&this._postAddingAppearancesToStyleEvent(),this.style.setLayerProperty(L,k,T,B),this._update(!0)):this}getGlyphsUrl(){return this.style.getGlyphsUrl()}setGlyphsUrl(L){return this.style.setGlyphsUrl(L),this._update(!0)}getSchema(L){return this.style.getSchema(L)}setSchema(L,k){return this.style.setSchema(L,k),this._update(!0)}getConfig(L){return this.style.getConfig(L)}setConfig(L,k){return this.style.setConfig(L,k),this._update(!0)}getConfigProperty(L,k){return this.style.getConfigProperty(L,k)}setConfigProperty(L,k,T){return this.style.setConfigProperty(L,k,T),this._update(!0)}getFeaturesetDescriptors(L){return this.style.getFeaturesetDescriptors(L)}setLights(L){if(this._lazyInitEmptyStyle(),L&&L.length===1&&L[0].type==="flat"){const k=L[0];k.properties?this.style.setFlatLight(k.properties,k.id,{}):this.style.setFlatLight({},"flat")}else this.style.setLights(L),this.painter.terrain&&(this.painter.terrain.invalidateRenderCache=!0);return this._update(!0)}getLights(){const L=this.style.getLights()||[];return L.length===0&&L.push({id:this.style.light.id,type:"flat",properties:this.style.getFlatLight()}),L}setLight(L,k={}){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:L}])}getLight(){return console.log("The `map.getLight` function is deprecated, prefer using `map.getLights` instead."),this.style.getFlatLight()}setTerrain(L){return this._lazyInitEmptyStyle(),!L&&this.transform.projection.requiresDraping?this.style.setTerrainForDraping():this.style.setTerrain(L),this._averageElevationLastSampledAt=-1/0,this._update(!0)}getTerrain(){return this.style?this.style.getTerrain():null}setFog(L){return this._lazyInitEmptyStyle(),this.style.setFog(L),this._update(!0)}getFog(){return this.style?this.style.getFog():null}setSnow(L){return this._lazyInitEmptyStyle(),this.style.setSnow(L),this._update(!0)}getSnow(){return this.style?this.style.getSnow():null}setRain(L){return this._lazyInitEmptyStyle(),this.style.setRain(L),this._update(!0)}getRain(){return this.style?this.style.getRain():null}setColorTheme(L){return this._lazyInitEmptyStyle(),this.style.setColorTheme(L),this._update(!0)}setImportColorTheme(L,k){return this._lazyInitEmptyStyle(),this.style.setImportColorTheme(L,k),this._update(!0)}setCamera(L){return this.style.setCamera(L),this._triggerCameraUpdate(L)}getNearClipOffset(){return this.transform.nearClipOffset}setNearClipOffset(L){const k=this.transform.nearClipOffset!==L;return this.transform.nearClipOffset=L,this._update(k)}_triggerCameraUpdate(L){return this._update(this.transform.setOrthographicProjectionAtLowPitch(L["camera-projection"]==="orthographic"))}getCamera(){return this.style.camera}_queryFogOpacity(L){return this.style&&this.style.fog?this.style.fog.getOpacityAtLatLng(o.cZ.convert(L),this.transform):0}setFeatureState(L,k){return L.source&&!this._isValidId(L.source)?this:(this.style.setFeatureState(L,k),this._update())}removeFeatureState(L,k){return L.source&&!this._isValidId(L.source)?this:(this.style.removeFeatureState(L,k),this._update())}getFeatureState(L){return L.source&&!this._isValidId(L.source)?null:this.style.getFeatureState(L)}resetFeatureStates(L){return this.style.resetFeatureStates(L),this._update()}_selectIndoorFloor(L){this.style.indoorManager&&this.style.indoorManager.selectFloor(L)}_setIndoorActiveFloorsVisibility(L){this.style.indoorManager&&this.style.indoorManager.setActiveFloorsVisibility(L)}getIndoorTileOptions(L,k){return this.style&&this.style.isIndoorEnabled()&&this.style.indoorManager?this.style.indoorManager.getIndoorTileOptions(L,k):null}_updateContainerDimensions(){if(!this._container)return;const L=this._container.getBoundingClientRect().width||400,k=this._container.getBoundingClientRect().height||300;let T,B,K,Q=this._container;for(;Q&&(!B||!K);){const le=window.getComputedStyle(Q).transform;le&&le!=="none"&&(T=le.match(Coe)[1].split(", "),T[0]&&T[0]!=="0"&&T[0]!=="1"&&(B=T[0]),T[3]&&T[3]!=="0"&&T[3]!=="1"&&(K=T[3])),Q=Q.parentElement}this._containerWidth=B?Math.abs(L/B):L,this._containerHeight=K?Math.abs(k/K):k}_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 L=this._container;L.classList.add("mapboxgl-map"),(this._missingCSSCanary=g("div","mapboxgl-canary",L)).style.visibility="hidden",this._detectMissingCSS();const k=this._canvasContainer=g("div","mapboxgl-canvas-container",L);this._canvas=g("canvas","mapboxgl-canvas",k),this._interactive&&(k.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 T=this._controlContainer=g("div","mapboxgl-control-container",L),B=this._controlPositions={};["top-left","top","top-right","right","bottom-right","bottom","bottom-left","left"].forEach(K=>{B[K]=g("div",`mapboxgl-ctrl-${K}`,T)}),this._container.addEventListener("scroll",this._onMapScroll,!1)}_resizeCanvas(L,k){const T=o.e.devicePixelRatio||1;this._canvas.width=T*Math.ceil(L),this._canvas.height=T*Math.ceil(k),this._canvas.style.width=`${L}px`,this._canvas.style.height=`${k}px`}_addMarker(L){this._markers.push(L)}_removeMarker(L){const k=this._markers.indexOf(L);k!==-1&&this._markers.splice(k,1)}_addPopup(L){this._popups.push(L)}_removePopup(L){const k=this._popups.indexOf(L);k!==-1&&this._popups.splice(k,1)}_setupPainter(){const L={...c,failIfMajorPerformanceCaveat:this._failIfMajorPerformanceCaveat,preserveDrawingBuffer:this._preserveDrawingBuffer,antialias:this._antialias||!1},k=this._canvas.getContext("webgl2",L);k?(o.eY(k,!0),this.painter=new Kh(k,this._contextCreateOptions,this.transform,this._scaleFactor,this._worldview,this._emissiveColorPrecision),this.on("data",T=>{if(T.dataType==="source"){const B=this.transform.elevation?this.transform.elevation._source():null;B&&T.sourceCacheId===B.id&&this.style&&this.style._setLabelPlacementStale(),this.style&&T.sourceCacheId&&this.style._buildingIndex.hasLayerForSourceCache(T.sourceCacheId)&&this.style._requestFullLabelPlacement(),this.painter.setTileLoadedFlag(!0)}})):this.fire(new o.f(new Error("Failed to initialize WebGL")))}_contextLost(L){L.preventDefault(),this._frame&&(this._frame.cancel(),this._frame=null),this.style&&this.style.handleContextLost(),this.fire(new o.h("webglcontextlost",{originalEvent:L}))}_contextRestored(L){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.h("webglcontextrestored",{originalEvent:L}))}_onMapScroll(L){if(L.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(L){return this.style?(this._styleDirty=this._styleDirty||L,this._sourcesDirty=!0,this.triggerRepaint(),this):this}_requestRenderFrame(L){return this._update(),this._renderTaskQueue.add(L)}_cancelRenderFrame(L){this._renderTaskQueue.remove(L)}_requestDomTask(L){!this.loaded()||this.loaded()&&!this.isMoving()?L():this._domRenderTaskQueue.add(L)}_render(L){let k;this.fire(new o.h("renderstart")),++this._frameId;const T=this.painter.context.extTimerQuery,B=o.e.now(),K=this.painter.context.gl;if(this.listens("gpu-timing-frame")&&(k=K.createQuery(),K.beginQuery(T.TIME_ELAPSED_EXT,k)),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(L),this._domRenderTaskQueue.run(L),this._removed)return;this._updateProjectionTransition();const Q=this._isInitialLoad?0:this._fadeDuration;if(this.style&&this._styleDirty){this._styleDirty=!1;const we=this.transform.zoom,Me=this.transform.pitch,Re=o.e.now(),Ze=new o.aj(we,{now:Re,fadeDuration:Q,pitch:Me,transition:this._loaded?this.style.transition:{duration:0,delay:0},worldview:this._worldview});this.style.update(Ze)}this.style&&this.style.hasFogTransition()&&(this.style._markersNeedUpdate=!0,this._sourcesDirty=!0);let le=!1;if(this.style&&this._sourcesDirty?(this._sourcesDirty=!1,this.painter._updateFog(this.style),this._updateTerrain(),le=this._updateAverageElevation(B),this.style.updateSources(this.transform),this.style.updateImageProviders(),this.isMoving()||this._forceMarkerAndPopupUpdate()):le=this._updateAverageElevation(B),this.style&&(this._placementDirty=this.style._updatePlacement(this.painter.transform,this.showCollisionBoxes,Q,this._crossSourceCollisions,this.painter.replacementSource,this._placementAlgorithm)),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,paintStartTimeStamp:L}),this.fire(new o.h("render")),this.loaded()&&!this._loaded&&(this._loaded=!0,o.eT.mark(o.eU.load),this.fire(new o.h("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._placementDirty&&this.style._releaseSymbolFadeTiles(),k){const we=o.e.now()-B;K.endQuery(T.TIME_ELAPSED_EXT),setTimeout(()=>{const Me=K.getQueryParameter(k,K.QUERY_RESULT)/1e6;K.deleteQuery(k),this.fire(new o.h("gpu-timing-frame",{cpuTime:we,gpuTime:Me}))},50)}if(this.listens("gpu-timing-layer")){const we=this.painter.collectGpuTimers();setTimeout(()=>{const Me=this.painter.queryGpuTimers(we);this.fire(new o.h("gpu-timing-layer",{layerTimes:Me}))},50)}if(this.listens("gpu-timing-deferred-render")){const we=this.painter.collectDeferredRenderGpuQueries();setTimeout(()=>{const Me=this.painter.queryGpuTimeDeferredRender(we);this.fire(new o.h("gpu-timing-deferred-render",{gpuTime:Me}))},50)}const me=this._sourcesDirty||this._styleDirty||this._placementDirty||le;if(me||this._repaint)this.triggerRepaint();else{const we=this.idle();if(we&&(le=this._updateAverageElevation(B,!0)),le)this.triggerRepaint();else{if(this._triggerFrame(!1),we&&(this.fire(new o.h("idle")),this._isInitialLoad=!1,this.speedIndexTiming)){const Me=this._calculateSpeedIndex();this.fire(new o.h("speedindexcompleted",{speedIndex:Me})),this.speedIndexTiming=!1}we&&this.style&&this.style.handleIdle()}}!this._loaded||this._fullyLoaded||me||(this._fullyLoaded=!0,o.eT.mark(o.eU.fullLoad),this._performanceMetricsCollection&&o.eZ(this._requestManager._customAccessToken,{width:this.painter.width,height:this.painter.height,interactionRange:this._interactionRange,visibilityHidden:this._visibilityHidden,terrainEnabled:this.painter.style.hasTerrain(),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(L){for(const k of this._markers)L&&!this.getRenderWorldCopies()&&(k._lngLat=k._lngLat.wrap()),k._update();for(const k of this._popups)!L||this.getRenderWorldCopies()||k._trackPointer||(k._lngLat=k._lngLat.wrap()),k._update()}_updateAverageElevation(L,k=!1){const T=K=>(this.transform.averageElevation=K,this._update(!1),!0);if(!this.painter.averageElevationNeedsEasing())return this.transform.averageElevation!==0&&T(0);const B=this.transform.elevation&&this.transform.elevation.exaggeration()!==this._averageElevationExaggeration;if(B||(k||L-this._averageElevationLastSampledAt>500)&&!this._averageElevation.isEasing(L)){const K=this.transform.averageElevation;let Q=this.transform.sampleAverageElevation();this.transform.elevation!=null&&(this._averageElevationExaggeration=this.transform.elevation.exaggeration()),isNaN(Q)?Q=0:this._averageElevationLastSampledAt=L;const le=Math.abs(K-Q);if(le>1){if(this._isInitialLoad||B)return this._averageElevation.jumpTo(Q),T(Q);this._averageElevation.easeTo(Q,L,300)}else if(le>1e-4)return this._averageElevation.jumpTo(Q),T(Q)}return!!this._averageElevation.isEasing(L)&&T(this._averageElevation.getValue(L))}_isTokenExpired(){return this._tokenExpiration!=null&&Date.now()>this._tokenExpiration}_revokeAuth(){const L=this.painter.context.gl;o.eY(L,!1),this._logoControl instanceof koe&&this._logoControl._updateLogo(),L&&L.clear(L.DEPTH_BUFFER_BIT|L.COLOR_BUFFER_BIT|L.STENCIL_BUFFER_BIT),this._silenceAuthErrors||this.fire(new o.f(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(){o.e_(this._getMapId(),this._requestManager._skuToken,this._requestManager._customAccessToken,L=>{L&&(L.message!==o.e$&&L.status!==401||this._revokeAuth())}),this._isTokenExpired()&&this._revokeAuth(),o.f0(this._getMapId(),this._requestManager._skuToken,this._requestManager._customAccessToken,()=>{})}_postStyleLoadEvent(){this.style.globalId&&o.f1(this._requestManager._customAccessToken,{map:this,style:this.style.globalId,importedStyles:this.style.getImportGlobalIds()})}_postStyleWithAppearanceEvent(){this.style.globalId&&this.style.hasAppearances()&&o.f2(this._requestManager._customAccessToken)}_postAddingAppearancesToStyleEvent(){o.f3(this._requestManager._customAccessToken)}_updateTerrain(){const L=this._isDragging();this.painter.updateTerrain(this.style,L)}_calculateSpeedIndex(){const L=this.painter.canvasCopy(),k=this.painter.getCanvasCopiesAndTimestamps();k.timeStamps.push(performance.now());const T=this.painter.context.gl,B=T.createFramebuffer();function K(Q){T.framebufferTexture2D(T.FRAMEBUFFER,T.COLOR_ATTACHMENT0,T.TEXTURE_2D,Q,0);const le=new Uint8Array(T.drawingBufferWidth*T.drawingBufferHeight*4);return T.readPixels(0,0,T.drawingBufferWidth,T.drawingBufferHeight,T.RGBA,T.UNSIGNED_BYTE,le),le}return T.bindFramebuffer(T.FRAMEBUFFER,B),this._canvasPixelComparison(K(L),k.canvasCopies.map(K),k.timeStamps)}_canvasPixelComparison(L,k,T){let B=T[1]-T[0];const K=L.length/4;for(let Q=0;Q{const Q=!!this._renderNextFrame;this._frame=null,this._renderNextFrame=null,Q&&this._render(K)}));const T=K=>{const Q=!!this._renderNextFrame;this._renderNextFrame=null;try{Q&&this._render(K)}finally{this._frame=null}Q&&!this._removed&&Promise.resolve().then(()=>this._triggerFrame(!1))};let B=null;this._frame={cancel:()=>{B!==null&&k.cancelAnimationFrame(B)}};try{B=k.requestAnimationFrame(T)}catch(K){throw this._frame=null,K}}_preloadTiles(L){const k=this.style?this.style.getSourceCaches():[];return o.bU(k,(T,B)=>T._preloadTiles(L,B),()=>{this.triggerRepaint()}),this}_onWindowOnline(){this._update()}_onWindowResize(L){this._trackResize&&this.resize({originalEvent:L})._update()}_onVisibilityChange(){document.visibilityState==="hidden"&&this._visibilityHidden++}get showTileBoundaries(){return!!this._showTileBoundaries}set showTileBoundaries(L){this._showTileBoundaries!==L&&(this._showTileBoundaries=L,L&&Ih(),this._update())}get showParseStatus(){return!!this._showParseStatus}set showParseStatus(L){this._showParseStatus!==L&&(this._showParseStatus=L,this._update())}get showTerrainWireframe(){return!!this._showTerrainWireframe}set showTerrainWireframe(L){this._showTerrainWireframe!==L&&(this._showTerrainWireframe=L,this._update())}get showLayers2DWireframe(){return!!this._showLayers2DWireframe}set showLayers2DWireframe(L){this._showLayers2DWireframe!==L&&(this._showLayers2DWireframe=L,this._update())}get showLayers3DWireframe(){return!!this._showLayers3DWireframe}set showLayers3DWireframe(L){this._showLayers3DWireframe!==L&&(this._showLayers3DWireframe=L,this._update())}get showElevationIdDebug(){return!!this.painter&&this.painter._debugParams.showElevationIdDebug}set showElevationIdDebug(L){this.painter&&this.painter._debugParams.showElevationIdDebug!==L&&(this.painter._debugParams.showElevationIdDebug=L,this.style&&L?this.style._reloadSources():this._update())}get speedIndexTiming(){return!!this._speedIndexTiming}set speedIndexTiming(L){this._speedIndexTiming!==L&&(this._speedIndexTiming=L,this._update())}get showPadding(){return!!this._showPadding}set showPadding(L){this._showPadding!==L&&(this._showPadding=L,L&&Ih(),this._update())}get showCollisionBoxes(){return!!this._showCollisionBoxes}set showCollisionBoxes(L){this._showCollisionBoxes!==L&&(this._showCollisionBoxes=L,L&&Ih(),this.style&&L?this.style._reloadSources():this._update())}get showOverdrawInspector(){return!!this._showOverdrawInspector}set showOverdrawInspector(L){this._showOverdrawInspector!==L&&(this._showOverdrawInspector=L,this._update())}get repaint(){return!!this._repaint}set repaint(L){this._repaint!==L&&(this._repaint=L,this.triggerRepaint())}get vertices(){return!!this._vertices}set vertices(L){this._vertices=L,this._update()}get showTileAABBs(){return!!this._showTileAABBs}set showTileAABBs(L){this._showTileAABBs!==L&&(this._showTileAABBs=L,L&&this._update())}_setCacheLimits(L,k){o.f7(L,k)}get version(){return o.f8}},NavigationControl:class{constructor(L={}){this.options={...Z6,...L},this._container=g("div","mapboxgl-ctrl mapboxgl-ctrl-group"),this._container.addEventListener("contextmenu",k=>k.preventDefault()),this.options.showZoom&&(o.aW(["_setButtonTitle","_updateZoomButtons"],this),this._zoomInButton=this._createButton("mapboxgl-ctrl-zoom-in",k=>{this._map&&this._map.zoomIn({},{originalEvent:k})}),g("span","mapboxgl-ctrl-icon",this._zoomInButton).setAttribute("aria-hidden","true"),this._zoomOutButton=this._createButton("mapboxgl-ctrl-zoom-out",k=>{this._map&&this._map.zoomOut({},{originalEvent:k})}),g("span","mapboxgl-ctrl-icon",this._zoomOutButton).setAttribute("aria-hidden","true")),this.options.showCompass&&(o.aW(["_rotateCompassArrow"],this),this._compass=this._createButton("mapboxgl-ctrl-compass",k=>{const T=this._map;T&&(this.options.visualizePitch?T.resetNorthPitch({},{originalEvent:k}):T.resetNorth({},{originalEvent:k}))}),this._compassIcon=g("span","mapboxgl-ctrl-icon",this._compass),this._compassIcon.setAttribute("aria-hidden","true"))}_updateZoomButtons(){const L=this._map;if(!L)return;const k=L.getZoom(),T=k===L.getMaxZoom(),B=k===L.getMinZoom();this._zoomInButton.disabled=T,this._zoomOutButton.disabled=B,this._zoomInButton.setAttribute("aria-disabled",T.toString()),this._zoomOutButton.setAttribute("aria-disabled",B.toString())}_rotateCompassArrow(){const L=this._map;if(!L)return;const k=this.options.visualizePitch?`scale(${1/Math.pow(Math.cos(L.transform.pitch*(Math.PI/180)),.5)}) rotateX(${L.transform.pitch}deg) rotateZ(${L.transform.angle*(180/Math.PI)}deg)`:`rotate(${L.transform.angle*(180/Math.PI)}deg)`;L._requestDomTask(()=>{this._compassIcon&&(this._compassIcon.style.transform=k)})}onAdd(L){return this._map=L,this.options.showZoom&&(this._setButtonTitle(this._zoomInButton,"ZoomIn"),this._setButtonTitle(this._zoomOutButton,"ZoomOut"),L.on("zoom",this._updateZoomButtons),this._updateZoomButtons()),this.options.showCompass&&(this._setButtonTitle(this._compass,"ResetBearing"),this.options.visualizePitch&&L.on("pitch",this._rotateCompassArrow),L.on("rotate",this._rotateCompassArrow),this._rotateCompassArrow(),this._handler=new _Y(L,this._compass,this.options.visualizePitch)),this._container}onRemove(){const L=this._map;L&&(this._container.remove(),this.options.showZoom&&L.off("zoom",this._updateZoomButtons),this.options.showCompass&&(this.options.visualizePitch&&L.off("pitch",this._rotateCompassArrow),L.off("rotate",this._rotateCompassArrow),this._handler&&this._handler.off(),this._handler=void 0),this._map=void 0)}_createButton(L,k){const T=g("button",L,this._container);return T.type="button",T.addEventListener("click",k),T}_setButtonTitle(L,k){if(!this._map)return;const T=this._map._getUIString(`NavigationControl.${k}`);L.setAttribute("aria-label",T),L.firstElementChild&&L.firstElementChild.setAttribute("title",T)}},GeolocateControl:class extends o.E{constructor(L={}){super();const k=navigator.geolocation;this.options={geolocation:k,...cj,...L},o.aW(["_onSuccess","_onError","_onZoom","_finish","_setupUI","_updateCamera","_updateMarker","_updateMarkerRotation","_onDeviceOrientation"],this),this._updateMarkerRotationThrottled=mh(this._updateMarkerRotation,20),this._numberOfWatches=0}onAdd(L){return this._map=L,this._container=g("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(L){const k=(T=!!this.options.geolocation)=>{this._supportsGeolocation=T,L(T)};this._supportsGeolocation!==void 0?L(this._supportsGeolocation):navigator.permissions!==void 0?navigator.permissions.query({name:"geolocation"}).then(T=>k(T.state!=="denied")).catch(()=>k()):k()}_isOutOfMapMaxBounds(L){const k=this._map.getMaxBounds(),T=L.coords;return!!k&&(T.longitudek.getEast()||T.latitudek.getNorth())}_setWatchState(L){this._watchState=L;const k=this._geolocateButton.classList;k.remove(...K_);for(const T of NY[L])k.add(Wv(T))}_setButtonTitle(L){const k=this._map._getUIString(L);this._geolocateButton.setAttribute("aria-label",k),this._geolocateButton.firstElementChild&&this._geolocateButton.firstElementChild.setAttribute("title",k)}_setErrorState(){switch(this._watchState){case"WAITING_ACTIVE":case"ACTIVE_LOCK":this._setWatchState("ACTIVE_ERROR");break;case"BACKGROUND":this._setWatchState("BACKGROUND_ERROR")}}_onSuccess(L){if(this._map){if(this._clearRequestTimeout(),this._isOutOfMapMaxBounds(L))return this._setErrorState(),this.fire(new o.h("outofmaxbounds",L)),this._updateMarker(),void this._finish();if(this._lastKnownPosition=L,this.options.trackUserLocation)switch(this._watchState){case"WAITING_ACTIVE":case"ACTIVE_LOCK":case"ACTIVE_ERROR":this._setWatchState(this.options.followUserLocation?"ACTIVE_LOCK":"BACKGROUND");break;case"BACKGROUND":case"BACKGROUND_ERROR":this._setWatchState("BACKGROUND")}this.options.showUserLocation&&this._watchState!=="OFF"&&this._updateMarker(L),this.options.followUserLocation&&(!this.options.trackUserLocation||this._watchState==="ACTIVE_LOCK")&&this._updateCamera(L),this.options.showUserLocation&&this._userLocationDotMarker.removeClassName("mapboxgl-user-location-dot-stale"),this.fire(new o.h("geolocate",{coords:L.coords,timestamp:L.timestamp,...L.toJSON?{toJSON:L.toJSON.bind(L)}:{}})),this._finish()}}_updateCamera(L){const k=new o.cZ(L.coords.longitude,L.coords.latitude),T=L.coords.accuracy,B={bearing:this._map.getBearing(),...this.options.fitBoundsOptions};this._map.fitBounds(k.toBounds(T),B,{geolocateSource:!0})}_updateMarker(L){if(L){const k=new o.cZ(L.coords.longitude,L.coords.latitude);this.options.showAccuracyCircle?this._accuracyCircleMarker.setLngLat(k).addTo(this._map):this._accuracyCircleMarker.remove(),this._userLocationDotMarker.setLngLat(k).addTo(this._map),this._accuracy=L.coords.accuracy,this.options.showUserLocation&&this.options.showAccuracyCircle&&this._updateCircleRadius()}else this._userLocationDotMarker.remove(),this._accuracyCircleMarker.remove()}_updateCircleRadius(){const L=this._map.transform,k=o.c4(1,L._center.lat)*L.worldSize,T=Math.ceil(2*this._accuracy*k);this._circleElement.style.width=`${T}px`,this._circleElement.style.height=`${T}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(L){if(this._map){if(this._clearRequestTimeout(),this.options.trackUserLocation)if(L.code===1)this._setWatchState("OFF"),this._geolocateButton.disabled=!0,this._setButtonTitle("GeolocateControl.LocationNotAvailable"),this._geolocationWatchID!==void 0&&this._clearWatch();else{if(L.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.h("error",{code:L.code,message:L.message,PERMISSION_DENIED:L.PERMISSION_DENIED,POSITION_UNAVAILABLE:L.POSITION_UNAVAILABLE,TIMEOUT:L.TIMEOUT})),this._finish()}}_finish(){this._timeoutId&&clearTimeout(this._timeoutId),this._timeoutId=void 0}_startRequestTimeout(){this._clearRequestTimeout();const L=this.options.positionOptions.timeout;L&&(this._requestTimeoutId=window.setTimeout(()=>{this._onError({code:3,message:"Geolocation request timed out"})},L))}_clearRequestTimeout(){this._requestTimeoutId!==void 0&&(clearTimeout(this._requestTimeoutId),this._requestTimeoutId=void 0)}_setupUI(L){this._map!==void 0&&(this._container.addEventListener("contextmenu",k=>k.preventDefault()),this._geolocateButton=g("button","mapboxgl-ctrl-geolocate",this._container),g("span","mapboxgl-ctrl-icon",this._geolocateButton).setAttribute("aria-hidden","true"),this._geolocateButton.type="button",L===!1?(o.w("Geolocation support is not available so the GeolocateControl will be disabled."),this._geolocateButton.disabled=!0,this._setButtonTitle("GeolocateControl.LocationNotAvailable")):this._setButtonTitle("GeolocateControl.FindMyLocation"),this.options.trackUserLocation&&(this._geolocateButton.setAttribute("aria-pressed","false"),this._watchState="OFF"),this.options.showUserLocation&&(this._createUserLocationMarkers(),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",k=>{k.geolocateSource||this._watchState!=="ACTIVE_LOCK"||k.originalEvent&&k.originalEvent.type==="resize"||(this._setWatchState("BACKGROUND"),this.fire(new o.h("trackuserlocationend")))}),this.fire(new o.h("ready")))}_onDeviceOrientation(L){this._userLocationDotMarker&&(L.webkitCompassHeading?this._heading=L.webkitCompassHeading:L.absolute===!0&&(this._heading=-1*L.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._setWatchState("WAITING_ACTIVE"),this.fire(new o.h("trackuserlocationstart"));break;case"WAITING_ACTIVE":case"ACTIVE_LOCK":case"ACTIVE_ERROR":case"BACKGROUND_ERROR":this._numberOfWatches--,this._noTimeout=!1,this._setWatchState("OFF"),this.fire(new o.h("trackuserlocationend"));break;case"BACKGROUND":this._setWatchState("ACTIVE_LOCK"),this._lastKnownPosition&&this._updateCamera(this._lastKnownPosition),this.fire(new o.h("trackuserlocationstart"))}if(this._watchState==="OFF"&&this._geolocationWatchID!==void 0)this._clearWatch();else if(this._geolocationWatchID===void 0){let L;this._geolocateButton.classList.add(Wv("waiting")),this._geolocateButton.setAttribute("aria-pressed","true"),this._numberOfWatches++,this._numberOfWatches>1?(L={maximumAge:6e5,timeout:0},this._noTimeout=!0):(L=this.options.positionOptions,this._noTimeout=!1),this._geolocationWatchID=this.options.geolocation.watchPosition(this._onSuccess,this._onError,L),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(L){return this.options.followUserLocation=L??cj.followUserLocation,this.options.trackUserLocation&&this._watchState!=="OFF"&&(this.options.followUserLocation?this._watchState!=="BACKGROUND"&&this._watchState!=="BACKGROUND_ERROR"||(this._setWatchState("ACTIVE_LOCK"),this._lastKnownPosition&&this._updateCamera(this._lastKnownPosition),this.fire(new o.h("trackuserlocationstart"))):this._watchState!=="ACTIVE_LOCK"&&this._watchState!=="ACTIVE_ERROR"||(this._setWatchState("BACKGROUND"),this.fire(new o.h("trackuserlocationend")))),this}setShowAccuracyCircle(L){if(this.options.showAccuracyCircle=L??cj.showAccuracyCircle,!this._accuracyCircleMarker)return this;if(this.options.showAccuracyCircle){if(this.options.showUserLocation&&this._lastKnownPosition){const{longitude:k,latitude:T,accuracy:B}=this._lastKnownPosition.coords;this._accuracy=B,this._accuracyCircleMarker.setLngLat(new o.cZ(k,T)).addTo(this._map),this._updateCircleRadius()}}else this._accuracyCircleMarker.remove();return this}setShowUserHeading(L){return this.options.showUserHeading=L??cj.showUserHeading,this._setup?(this.options.showUserHeading?this._geolocationWatchID!==void 0&&this._addDeviceOrientationListener():(this._removeDeviceOrientationListener(),this._heading=void 0,this._userLocationDotMarker&&this._updateMarkerRotation()),this):this}setFitBoundsOptions(L){return this.options.fitBoundsOptions=L??cj.fitBoundsOptions,this}setShowUserLocation(L){return this.options.showUserLocation=L??cj.showUserLocation,this._setup?(this.options.showUserLocation?(this._userLocationDotMarker||(this._createUserLocationMarkers(),this._map.on("zoom",this._onZoom)),!this._lastKnownPosition||this._watchState!==void 0&&this._watchState==="OFF"||this._updateMarker(this._lastKnownPosition)):(this._userLocationDotMarker&&this._userLocationDotMarker.remove(),this._accuracyCircleMarker&&this._accuracyCircleMarker.remove()),this):this}_addDeviceOrientationListener(){const L=()=>{const T="ondeviceorientationabsolute"in window?"deviceorientationabsolute":"deviceorientation";window.addEventListener(T,this._onDeviceOrientation)},k=DeviceOrientationEvent;typeof(k==null?void 0:k.requestPermission)=="function"?k.requestPermission().then(T=>{T==="granted"?L():o.w("GeolocateControl: permission to use device orientation was denied, so the user heading arrow will not be shown.")}).catch(()=>{o.w("GeolocateControl: could not request device orientation permission. Enable the user heading from a user gesture (click/tap) so the browser can prompt for access.")}):L()}_removeDeviceOrientationListener(){window.removeEventListener("deviceorientation",this._onDeviceOrientation),window.removeEventListener("deviceorientationabsolute",this._onDeviceOrientation)}_createUserLocationMarkers(){this._dotElement=g("div","mapboxgl-user-location"),this._dotElement.appendChild(g("div","mapboxgl-user-location-dot")),this._dotElement.appendChild(g("div","mapboxgl-user-location-heading")),this._userLocationDotMarker=new Kk({element:this._dotElement,rotationAlignment:"map",pitchAlignment:"map"}),this._circleElement=g("div","mapboxgl-user-location-accuracy-circle"),this._accuracyCircleMarker=new Kk({element:this._circleElement,pitchAlignment:"map"})}_clearWatch(){this._clearRequestTimeout(),this.options.geolocation.clearWatch(this._geolocationWatchID),this._removeDeviceOrientationListener(),this._geolocationWatchID=void 0,this._geolocateButton.classList.remove(Wv("waiting")),this._geolocateButton.setAttribute("aria-pressed","false"),this.options.showUserLocation&&this._updateMarker(null)}},AttributionControl:tM,ScaleControl:class{constructor(L={}){this.options={...O3,...L},o.aW(["_update","_setScale","setUnit"],this)}getDefaultPosition(){return"bottom-left"}_update(){const L=this.options.maxWidth||100,k=this._map,T=k._containerHeight/2,B=k._containerWidth/2-L/2,K=k.unproject([B,T]),Q=k.unproject([B+L,T]),le=K.distanceTo(Q);if(this.options.unit==="imperial"){const me=3.2808*le;me>5280?this._setScale(L,me/5280,"mile"):this._setScale(L,me,"foot")}else this.options.unit==="nautical"?this._setScale(L,le/1852,"nautical-mile"):le>=1e3?this._setScale(L,le/1e3,"kilometer"):this._setScale(L,le,"meter")}_setScale(L,k,T){this._map._requestDomTask(()=>{const B=function(Q){const le=Math.pow(10,`${Math.floor(Q)}`.length-1);let me=Q/le;return me=me>=10?10:me>=5?5:me>=3?3:me>=2?2:me>=1?1:function(we){const Me=Math.pow(10,Math.ceil(-Math.log(we)/Math.LN10));return Math.round(we*Me)/Me}(me),le*me}(k),K=B/k;this._container.innerHTML=T!=="nautical-mile"?new Intl.NumberFormat(this._language,{style:"unit",unitDisplay:"short",unit:T}).format(B):`${B} ${nM[T]}`,this._container.style.width=L*K+"px"})}onAdd(L){return this._map=L,this._language=L.getLanguage(),this._container=g("div","mapboxgl-ctrl mapboxgl-ctrl-scale",L.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(L){this._language=L,this._update()}setUnit(L){this.options.unit=L,this._update()}},FullscreenControl:class{constructor(L={}){this._fullscreen=!1,L&&L.container&&(L.container instanceof HTMLElement?this._container=L.container:o.w("Full screen control 'container' must be a DOM element.")),o.aW(["_onClickFullscreen","_changeIcon"],this),"onfullscreenchange"in document?this._fullscreenchange="fullscreenchange":"onwebkitfullscreenchange"in document&&(this._fullscreenchange="webkitfullscreenchange")}onAdd(L){return this._map=L,this._container||(this._container=this._map.getContainer()),this._controlContainer=g("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 L=this._fullscreenButton=g("button","mapboxgl-ctrl-fullscreen",this._controlContainer);g("span","mapboxgl-ctrl-icon",L).setAttribute("aria-hidden","true"),L.type="button",this._updateTitle(),this._fullscreenButton.addEventListener("click",this._onClickFullscreen),document.addEventListener(this._fullscreenchange,this._changeIcon)}_updateTitle(){const L=this._getTitle();this._fullscreenButton.setAttribute("aria-label",L),this._fullscreenButton.firstElementChild&&this._fullscreenButton.firstElementChild.setAttribute("title",L)}_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.aW(["_onIndoorUpdate","_onStyleData","_scrollUp","_scrollDown","_toggleIndoor"],this),this._visibleFloorStart=0,this._lastSelectedFloorId=null}onAdd(L){return this._map=L,this._container=g("div","mapboxgl-ctrl mapboxgl-ctrl-group"),this._container.style.display="none",this._map.on("styledata",this._onStyleData),this._map.on("idle",this._onStyleData),this._updateConnection(),this._container}_onStyleData(){this._updateConnection()}_updateConnection(){if(this._map&&this._map.style&&this._map.style.indoorManager){const L=this._map.style.indoorManager;L.off("selector-update",this._onIndoorUpdate),L.on("selector-update",this._onIndoorUpdate),this._onIndoorUpdate(L.getControlState()),this._map.off("idle",this._onStyleData)}}_createButton(L,k){const T=g("button",L,this._container);return T.type="button",T.addEventListener("click",k),T}_setButtonTitle(L,k){L.setAttribute("aria-label",k),L.textContent=k}onRemove(){this._container&&this._container.remove(),this._map&&(this._map.off("styledata",this._onStyleData),this._map.off("idle",this._onStyleData),this._map.style&&this._map.style.indoorManager&&this._map.style.indoorManager.off("selector-update",this._onIndoorUpdate),this._map=null)}getDefaultPosition(){return"top-right"}_onIndoorUpdate(L){if(!L||!L.floors||L.floors.length===0)return this._model=L,void(this._container.style.display="none");const k=this._model;this._model=L,this._container.style.display="inline-block";const T=!k||k.floors.length!==L.floors.length||k.floors.some((B,K)=>B.id!==L.floors[K].id);if(T&&(this._visibleFloorStart=0,this._lastSelectedFloorId=null),L.selectedFloorId){if(L.selectedFloorId!==this._lastSelectedFloorId||T){const B=L.floors.findIndex(K=>K.id===L.selectedFloorId);if(B!==-1){const K=L.floors.length;let Q,le;K<=5?(Q=0,le=K-1):this._visibleFloorStart===0?(Q=0,le=3):this._visibleFloorStart>=K-3?(Q=K-3-1,le=K-1):(Q=this._visibleFloorStart,le=this._visibleFloorStart+3-1),Ble&&(this._visibleFloorStart=B-2)}}this._lastSelectedFloorId=L.selectedFloorId}this._render()}_render(){if(!this._container||!this._model||!this._model.floors)return;this._container.innerHTML="";const L=this._createButton("mapboxgl-ctrl-indoor-toggle",this._toggleIndoor);g("span","mapboxgl-ctrl-icon",L).setAttribute("aria-hidden","true"),this._model.activeFloorsVisible||L.classList.add("mapboxgl-ctrl-level-button-selected"),this._container.appendChild(L);const k=this._model.floors,T=k.length;if(T<=5)return void k.forEach(le=>this._createFloorButton(le));const B=this._visibleFloorStart===0,K=this._visibleFloorStart>=T-3;if(B)this._createFloorButton(k[0]);else{const le=this._createButton("mapboxgl-ctrl-arrow-up",this._scrollUp);g("span","mapboxgl-ctrl-icon",le).setAttribute("aria-hidden","true"),this._container.appendChild(le)}let Q=[];if(Q=B?k.slice(1,4):K?k.slice(this._visibleFloorStart-1,this._visibleFloorStart+3-1):k.slice(this._visibleFloorStart,this._visibleFloorStart+3),Q.forEach(le=>this._createFloorButton(le)),K)this._createFloorButton(k[T-1]);else{const le=this._createButton("mapboxgl-ctrl-arrow-down",this._scrollDown);g("span","mapboxgl-ctrl-icon",le).setAttribute("aria-hidden","true"),this._container.appendChild(le)}}_createFloorButton(L){const k=this._createButton("mapboxgl-ctrl-level-button",()=>{const Q=L.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))}),T=(L.name||"").trim(),B=L.zIndex.toString(),K=T?Array.from(T).slice(0,3).join(""):B;this._setButtonTitle(k,K),this._model&&this._model.activeFloorsVisible&&L.id===this._model.selectedFloorId&&k.classList.add("mapboxgl-ctrl-level-button-selected"),this._container&&this._container.appendChild(k)}_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 L=this._model&&this._model.floors||[];if(L.length>3){const k=L.length-3;this._visibleFloorStart===k-1&&(this._visibleFloorStart=k-2)}this._render()}}_scrollDown(){if(this._model&&this._model.floors){const L=this._model.floors.length-3;this._visibleFloorStartL&&(this._visibleFloorStart=L),this._render())}}},Popup:class extends o.E{constructor(L){super(),this.options=Object.assign(Object.create(Ll),L),this._altitude=this.options.altitude,o.aW(["_update","_onClose","remove","_onMouseEvent"],this),this._classList=new Set(L&&L.className?L.className.trim().split(kY):[])}addTo(L){return this._map&&this.remove(),this._map=L,this.options.closeOnClick&&L.on("preclick",this._onClose),this.options.closeOnMove&&L.on("move",this._onClose),L.on("remove",this.remove),this._update(),L._addPopup(this),this._focusFirstElement(),this._trackPointer?(L.on("mousemove",this._onMouseEvent),L.on("mouseup",this._onMouseEvent),L._canvasContainer.classList.add("mapboxgl-track-pointer")):L.on("move",this._update),this.fire(new o.h("open")),this}isOpen(){return!!this._map}remove(){this._content&&this._content.remove(),this._container&&(this._container.remove(),this._container=void 0);const L=this._map;return L&&(L.off("move",this._update),L.off("move",this._onClose),L.off("preclick",this._onClose),L.off("click",this._onClose),L.off("remove",this.remove),L.off("mousemove",this._onMouseEvent),L.off("mouseup",this._onMouseEvent),L.off("drag",this._onMouseEvent),L._canvasContainer&&L._canvasContainer.classList.remove("mapboxgl-track-pointer"),L._removePopup(this),this._map=void 0),this.fire(new o.h("close")),this}getLngLat(){return this._lngLat}setLngLat(L){this._lngLat=o.cZ.convert(L),this._pos=null,this._trackPointer=!1,this._update();const k=this._map;return k&&(k.on("move",this._update),k.off("mousemove",this._onMouseEvent),k._canvasContainer.classList.remove("mapboxgl-track-pointer")),this}getAltitude(){return this._altitude}setAltitude(L){return this._altitude=L,this._update(),this}trackPointer(){this._trackPointer=!0,this._pos=null,this._update();const L=this._map;return L&&(L.off("move",this._update),L.on("mousemove",this._onMouseEvent),L.on("drag",this._onMouseEvent),L._canvasContainer.classList.add("mapboxgl-track-pointer")),this}getElement(){return this._container}setText(L){return this.setDOMContent(document.createTextNode(L))}setHTML(L){const k=document.createDocumentFragment(),T=document.createElement("body");let B;for(T.innerHTML=L;B=T.firstChild,B;)k.appendChild(B);return this.setDOMContent(k)}getMaxWidth(){return this._container&&this._container.style.maxWidth}setMaxWidth(L){return this.options.maxWidth=L,this._update(),this}setDOMContent(L){let k=this._content;if(k)for(;k.hasChildNodes();)k.firstChild&&k.removeChild(k.firstChild);else k=this._content=g("div","mapboxgl-popup-content",this._container||void 0);if(k.appendChild(L),this.options.closeButton){const T=this._closeButton=g("button","mapboxgl-popup-close-button",k);T.type="button",T.setAttribute("aria-label","Close popup"),T.innerHTML='',T.addEventListener("click",this._onClose)}return this._update(),this._focusFirstElement(),this}addClassName(L){return this._classList.add(L),this._updateClassList(),this}removeClassName(L){return this._classList.delete(L),this._updateClassList(),this}setOffset(L){return this.options.offset=L,this._update(),this}toggleClassName(L){let k;return this._classList.delete(L)?k=!1:(this._classList.add(L),k=!0),this._updateClassList(),k}_onMouseEvent(L){this._update(L.point)}_getAnchor(L){if(this.options.anchor)return this.options.anchor;const k=this._map,T=this._container,B=this._pos;if(!k||!T||!B)return"bottom";const K=T.offsetWidth,Q=T.offsetHeight,le=B.xk.transform.width-K/2;if(B.y+Lk.transform.height-Q){if(le)return"bottom-left";if(me)return"bottom-right"}return le?"left":me?"right":"bottom"}_updateClassList(){const L=this._container;if(!L)return;const k=[...this._classList];k.push("mapboxgl-popup"),this._anchor&&k.push(`mapboxgl-popup-anchor-${this._anchor}`),this._trackPointer&&k.push("mapboxgl-popup-track-pointer"),L.className=k.join(" ")}_update(L){const k=this._map,T=this._content;if(!k||!this._lngLat&&!this._trackPointer||!T)return;let B=this._container;if(B||(B=this._container=g("div","mapboxgl-popup",k.getContainer()),this._tip=g("div","mapboxgl-popup-tip",B),B.appendChild(T)),this.options.maxWidth&&B.style.maxWidth!==this.options.maxWidth&&(B.style.maxWidth=this.options.maxWidth),k.transform.renderWorldCopies&&!this._trackPointer&&(this._lngLat=wY(this._lngLat,this._pos,k.transform)),!this._trackPointer||L){const K=this._pos=this._trackPointer&&L instanceof o.P?L:k.project(this._lngLat,this._altitude),Q=Q6(this.options.offset),le=this._anchor=this._getAnchor(Q.y),me=Q6(this.options.offset,le),we=K.add(me).round();k._requestDomTask(()=>{this._container&&le&&(this._container.style.transform=`${X6[le]} translate(${we.x}px,${we.y}px)`)})}if(!this._marker&&k._showingGlobe()){const K=o.f9(k.transform,this._lngLat)?0:1;this._setOpacity(K)}this._updateClassList()}_focusFirstElement(){if(!this.options.focusAfterOpen||!this._container)return;const L=this._container.querySelector(Y_);L&&L.focus()}_onClose(){this.remove()}_setOpacity(L){this._container&&(this._container.style.opacity=`${L}`),this._content&&(this._content.style.pointerEvents=L?"auto":"none")}},Marker:Kk,Style:up,LngLat:o.cZ,LngLatBounds:o.eI,Point:o.P,MercatorCoordinate:o.bT,FreeCameraOptions:o.ff,Evented:o.E,config:o.eS,prewarm:function(){du().acquire(ws)},clearPrewarmedResources:function(){const L=uh;L&&(L.isPreloaded()&&L.numActive()===1?(L.release(ws),uh=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.eS.ACCESS_TOKEN},set accessToken(L){o.ft(L)},get baseApiUrl(){return o.eS.API_URL},set baseApiUrl(L){o.fs(L)},get workerCount(){return Ms.workerCount},set workerCount(L){(function(k){Ms.workerCount=k})(L)},get maxParallelImageRequests(){return o.eS.MAX_PARALLEL_IMAGE_REQUESTS},set maxParallelImageRequests(L){o.fr(L)},clearStorage(L){o.fq(L)},get workerUrl(){return zt.workerUrl},set workerUrl(L){zt.workerUrl=L},get workerClass(){return zt.workerClass},set workerClass(L){zt.workerClass=L},get dracoUrl(){return o.fp()},set dracoUrl(L){o.fo(L)},get meshoptUrl(){return o.fn()},set meshoptUrl(L){o.fm(L)},get buildingGenUrl(){return o.fl()},set buildingGenUrl(L){o.fk(L)},setNow:o.e.setNow,restoreNow:o.e.restoreNow}});var l=a;return l})})(G7t);var FDs=G7t.exports;const ju=au(FDs),i0t={coming_soon:"#3B82F6",office_exclusive:"#6366F1",pre_market:"#06B6D4",active:"#10B981",price_improvement:"#F97316",under_contract:"#8B5CF6",sold:"#6B7280"},o0t={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 ODs(s){return s>=1e6?`$${(s/1e6).toFixed(1)}M`:`$${(s/1e3).toFixed(0)}K`}function zDs({listings:s,isLoading:t}){const n=Qn(),r=j.useRef(null),a=j.useRef(null),i=j.useRef([]),[l,o]=j.useState(""),[c,d]=j.useState(!0);return j.useEffect(()=>{(async()=>{d(!0);try{const{data:m}=await q.from("settings").select("value").eq("key","mapbox_public_token").maybeSingle();m!=null&&m.value&&o(m.value)}catch(m){console.error("Error fetching mapbox token:",m)}d(!1)})()},[]),j.useEffect(()=>{if(!r.current||!l||a.current)return;ju.accessToken=l;const h=s.filter(g=>g.latitude!=null&&g.longitude!=null);let m=[-98.5795,39.8283],f=4;if(h.length>0){const g=h.reduce((y,v)=>y+v.longitude,0)/h.length,x=h.reduce((y,v)=>y+v.latitude,0)/h.length;m=[g,x],f=h.length===1?12:10}return a.current=new ju.Map({container:r.current,style:"mapbox://styles/mapbox/light-v11",zoom:f,center:m}),a.current.addControl(new ju.NavigationControl,"top-right"),()=>{var g;(g=a.current)==null||g.remove(),a.current=null}},[l]),j.useEffect(()=>{if(!a.current||!l)return;i.current.forEach(m=>m.remove()),i.current=[];const h=s.filter(m=>m.latitude!=null&&m.longitude!=null);if(h.forEach(m=>{var S,C,E;const f=i0t[m.status]||"#10B981",g=((S=m.photos)==null?void 0:S.find(I=>I.is_primary))||((C=m.photos)==null?void 0:C[0]),y=window.location.hostname==="listings.relevelup.com"||window.location.hostname.startsWith("listings.")?`/${m.slug||m.id}`:`/public/listing/${m.slug||m.id}`,v=document.createElement("div");v.className="cursor-pointer",v.innerHTML=`
`;const b=new ju.Popup({offset:25,closeButton:!0,maxWidth:"280px"}).setHTML(`
${g!=null&&g.photo_url?``:""}
${ODs(m.price)}
${m.property_address||""}
${m.city}, ${m.state}
${o0t[m.status]||m.status} ${m.bedrooms?`${m.bedrooms} bed`:""} ${m.bathrooms?`${m.bathrooms} bath`:""}
${(E=m.agent)!=null&&E.name?`
Listed by ${m.agent.name}
`:""}
Click to view details →
`),w=new ju.Marker(v).setLngLat([m.longitude,m.latitude]).setPopup(b).addTo(a.current);i.current.push(w)}),h.length>1){const m=new ju.LngLatBounds;h.forEach(f=>m.extend([f.longitude,f.latitude])),a.current.fitBounds(m,{padding:60,maxZoom:13})}else h.length===1&&a.current.flyTo({center:[h[0].longitude,h[0].latitude],zoom:12})},[s,l]),j.useEffect(()=>(window.__navigateToPublicListing__=h=>{n(h)},()=>{delete window.__navigateToPublicListing__}),[n]),c||t?e.jsx(yn,{className:"w-full h-[500px] rounded-lg"}):!l||s.filter(h=>h.latitude!=null&&h.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(i0t).map(([h,m])=>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:m}}),e.jsx("span",{className:"text-xs text-gray-600",children:o0t[h]})]},h))}),e.jsx("div",{ref:r,className:"w-full h-[500px] rounded-lg shadow-lg border border-gray-200"})]})}const g7e={active:"Active",coming_soon:"Coming Soon",office_exclusive:"Office Exclusive",pre_market:"Pre-Market",price_improvement:"Price Improvement",under_contract:"Under Contract",sold:"Sold"},BDs={single_family:"Single Family",condo:"Condo",townhouse:"Townhouse",land:"Land",multi_family:"Multi-Family",luxury:"Luxury",commercial:"Commercial",other:"Other"},k$="#0d0d0d",l0t="#1a1a1a",Iu="#c9a84c",jM="#f0d78c";function K7t(){const[s,t]=j.useState(""),[n,r]=j.useState(!1),[a,i]=j.useState(!1),[l,o]=j.useState(!1),[c,d]=j.useState(-1),u=j.useRef(null),[h,m]=j.useState({status:"",propertyType:"",minPrice:"",maxPrice:""}),{data:f}=vDs(),g=j.useMemo(()=>{if(!f)return[];const O=s.trim().toLowerCase(),U=[...f.cities.map(V=>({label:V.label,value:V.city,type:"city",count:V.count})),...f.neighborhoods.map(V=>({label:V.label,value:V.neighborhood,type:"neighborhood",count:V.count})),...f.zips.map(V=>({label:`ZIP ${V.label}`,value:V.zip,type:"zip",count:V.count}))];return(O?U.filter(V=>V.label.toLowerCase().includes(O)||V.value.toLowerCase().includes(O)):U).slice(0,8)},[f,s]);j.useEffect(()=>{const O=U=>{u.current&&!u.current.contains(U.target)&&o(!1)};return document.addEventListener("mousedown",O),()=>document.removeEventListener("mousedown",O)},[]);const{data:x,isLoading:y}=yDs({city:s||void 0,status:h.status||void 0,propertyType:h.propertyType||void 0,minPrice:h.minPrice?Number(h.minPrice):void 0,maxPrice:h.maxPrice?Number(h.maxPrice):void 0}),v=O=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(O),b=()=>{m({status:"",propertyType:"",minPrice:"",maxPrice:""}),t("")},w=s||h.status||h.propertyType||h.minPrice||h.maxPrice,S=typeof window<"u"&&(window.location.hostname==="listings.relevelup.com"||window.location.hostname.startsWith("listings.")),C=O=>S?`/${O.slug||O.id}`:`/public/listing/${O.slug||O.id}`,{featured:E,restListings:I,luxeCount:P,cities:R,activeCount:D}=j.useMemo(()=>{const O=x||[],U=O.filter(_e=>_e.status==="active"),W=U.length>0?U:O,V=new Intl.DateTimeFormat("en-CA",{timeZone:"America/New_York",year:"numeric",month:"2-digit",day:"2-digit"}).format(new Date),[G,Y,X]=V.split("-").map(Number),ae=Math.floor(Date.UTC(G,Y-1,X)/864e5),ie=W.length>0?W[ae%W.length]:void 0,ne=O.filter(_e=>!ie||_e.id!==ie.id),te=Array.from(new Set(O.map(_e=>_e.city).filter(Boolean))).slice(0,8),J=O.filter(_e=>(_e.price||0)>=1e6).length,ce=U.length;return{featured:ie,restListings:ne,luxeCount:J,cities:te,activeCount:ce}},[x]);return e.jsxs(e.Fragment,{children:[e.jsxs(Ml,{children:[e.jsx("title",{children:"LevelUp Listings — Curated Homes for Sale"}),e.jsx("meta",{name:"description",content:"A curated collection of exclusive properties from LevelUp real estate agents. Discover luxury homes, coming soon listings, and market-defining architecture."}),e.jsx("link",{rel:"canonical",href:"https://listings.relevelup.com"}),e.jsx("meta",{property:"og:title",content:"LevelUp Listings — Curated Homes for Sale"}),e.jsx("meta",{property:"og:description",content:"A curated collection of exclusive properties from LevelUp real estate agents."}),e.jsx("meta",{property:"og:type",content:"website"}),e.jsx("meta",{property:"og:url",content:"https://listings.relevelup.com"}),e.jsx("meta",{name:"twitter:card",content:"summary_large_image"}),e.jsx("script",{type:"application/ld+json",children:JSON.stringify({"@context":"https://schema.org","@type":"WebSite",name:"LevelUp Listings",url:"https://listings.relevelup.com"})})]}),e.jsxs("div",{className:"min-h-screen text-white",style:{backgroundColor:k$,fontFamily:"'Fira Sans', system-ui, sans-serif"},children:[e.jsx("style",{children:` .lu-serif { font-family: 'DM Serif Display', Georgia, serif; font-weight: 400; letter-spacing: -0.01em; } .lu-eyebrow { font-family: 'Fira Sans', sans-serif; font-weight: 500; letter-spacing: 0.3em; text-transform: uppercase; font-size: 11px; } .lu-gold { color: ${Iu}; } .lu-gold-line { background: linear-gradient(90deg, transparent, ${Iu}, transparent); } .lu-card-hover { transition: transform .6s cubic-bezier(.2,.7,.2,1), box-shadow .6s; } .lu-card-hover:hover { transform: translateY(-6px); } .lu-img-zoom { transition: transform 1.2s cubic-bezier(.2,.7,.2,1); } .group:hover .lu-img-zoom { transform: scale(1.06); } .lu-hero-title { animation: luFadeUp 1.1s cubic-bezier(.2,.7,.2,1) both; } .lu-hero-sub { animation: luFadeUp 1.1s .15s cubic-bezier(.2,.7,.2,1) both; } .lu-hero-search { animation: luFadeUp 1.1s .3s cubic-bezier(.2,.7,.2,1) both; } .lu-hero-stats { animation: luFadeUp 1.1s .45s cubic-bezier(.2,.7,.2,1) both; } @keyframes luFadeUp { from { opacity: 0; transform: translateY(24px); } to { opacity: 1; transform: none; } } .lu-grain::after { content: ''; position: absolute; inset: 0; pointer-events: none; opacity: .18; background-image: url("data:image/svg+xml;utf8,"); } .lu-marquee { display: flex; gap: 3rem; animation: luMarquee 40s linear infinite; } @keyframes luMarquee { to { transform: translateX(-50%); } } .lu-input-dark { background: rgba(255,255,255,0.06) !important; border-color: rgba(201,168,76,0.25) !important; color: #fff !important; } .lu-input-dark::placeholder { color: rgba(255,255,255,0.5) !important; } `}),e.jsxs("header",{className:"sticky top-0 z-50 backdrop-blur-md",style:{backgroundColor:"rgba(13,13,13,0.75)",borderBottom:"1px solid rgba(201,168,76,0.15)"},children:[e.jsxs("div",{className:"max-w-7xl mx-auto px-6 py-4 flex items-center justify-between",children:[e.jsxs(wr,{to:"/",className:"flex items-center gap-3",children:[e.jsx("img",{src:TG,alt:"LevelUp",className:"h-7"}),e.jsx("span",{className:"hidden sm:inline-block h-5 w-px",style:{background:"rgba(255,255,255,0.2)"}}),e.jsx("span",{className:"hidden sm:inline lu-eyebrow lu-gold",children:"Listings"})]}),e.jsxs("nav",{className:"hidden md:flex items-center gap-8",children:[e.jsx("a",{href:"#featured",className:"text-sm text-white/80 hover:text-white transition",children:"Featured"}),e.jsx("a",{href:"#collection",className:"text-sm text-white/80 hover:text-white transition",children:"Collection"}),e.jsx("a",{href:"#map",className:"text-sm text-white/80 hover:text-white transition",children:"Map"}),e.jsx(wr,{to:"/home-value",className:"text-sm text-white/80 hover:text-white transition",children:"Home Value"}),e.jsx("a",{href:"https://relevelup.com",target:"_blank",rel:"noopener noreferrer",className:"text-sm px-4 py-2 rounded-full transition",style:{border:`1px solid ${Iu}`,color:Iu},children:"About LevelUp"})]}),e.jsx("button",{type:"button",onClick:()=>i(O=>!O),className:"md:hidden inline-flex items-center justify-center w-10 h-10 rounded-full",style:{border:`1px solid ${Iu}`,color:Iu},"aria-label":"Toggle menu","aria-expanded":a,children:a?e.jsx(gr,{className:"w-5 h-5"}):e.jsx(IE,{className:"w-5 h-5"})})]}),a&&e.jsx("div",{className:"md:hidden border-t",style:{borderColor:"rgba(201,168,76,0.15)"},children:e.jsxs("nav",{className:"max-w-7xl mx-auto px-6 py-4 flex flex-col gap-1",children:[e.jsx("a",{href:"#featured",onClick:()=>i(!1),className:"py-3 text-white/85 hover:text-white transition border-b",style:{borderColor:"rgba(255,255,255,0.06)"},children:"Featured"}),e.jsx("a",{href:"#collection",onClick:()=>i(!1),className:"py-3 text-white/85 hover:text-white transition border-b",style:{borderColor:"rgba(255,255,255,0.06)"},children:"Collection"}),e.jsx("a",{href:"#map",onClick:()=>i(!1),className:"py-3 text-white/85 hover:text-white transition border-b",style:{borderColor:"rgba(255,255,255,0.06)"},children:"Map"}),e.jsx(wr,{to:"/home-value",onClick:()=>i(!1),className:"py-3 text-white/85 hover:text-white transition border-b",style:{borderColor:"rgba(255,255,255,0.06)"},children:"Home Value"}),e.jsx("a",{href:"https://relevelup.com",target:"_blank",rel:"noopener noreferrer",onClick:()=>i(!1),className:"mt-3 text-center text-sm px-4 py-3 rounded-full",style:{border:`1px solid ${Iu}`,color:Iu},children:"About LevelUp"})]})})]}),e.jsxs("section",{className:"relative overflow-hidden lu-grain",style:{minHeight:"92vh"},children:[e.jsxs("div",{className:"absolute inset-0",children:[e.jsx("img",{src:DDs,alt:"Luxury home at dusk",className:"w-full h-full object-cover",style:{filter:"brightness(0.55) contrast(1.05)"}}),e.jsx("div",{className:"absolute inset-0",style:{background:"linear-gradient(180deg, rgba(13,13,13,0.55) 0%, rgba(13,13,13,0.25) 40%, rgba(13,13,13,0.9) 100%)"}})]}),e.jsxs("div",{className:"relative max-w-7xl mx-auto px-6 pt-24 md:pt-32 pb-16 flex flex-col justify-center",style:{minHeight:"92vh"},children:[e.jsxs("div",{className:"max-w-4xl",children:[e.jsxs("div",{className:"lu-hero-title flex items-center gap-3 mb-6",children:[e.jsx("span",{className:"h-px w-10",style:{background:Iu}}),e.jsx("span",{className:"lu-eyebrow lu-gold",children:"The LevelUp Collection"})]}),e.jsxs("h1",{className:"lu-serif lu-hero-title text-white text-5xl sm:text-6xl md:text-7xl lg:text-8xl leading-[1.02] mb-6",children:["Homes with a",e.jsx("br",{}),e.jsx("span",{className:"italic",style:{color:jM},children:"quiet"})," kind of luxury."]}),e.jsx("p",{className:"lu-hero-sub text-white/75 text-lg md:text-xl max-w-2xl mb-10 leading-relaxed",children:"A private, hand-picked collection of properties represented by LevelUp agents — from waterfront estates to architectural landmarks and everything in between."}),e.jsxs("div",{className:"lu-hero-search max-w-3xl",ref:u,children:[e.jsxs("div",{className:"flex items-stretch rounded-full overflow-hidden shadow-2xl relative",style:{background:"rgba(13,13,13,0.7)",border:`1px solid ${Iu}`,backdropFilter:"blur(12px)"},children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(Kr,{className:"absolute left-6 top-1/2 -translate-y-1/2 h-5 w-5",style:{color:Iu}}),e.jsx(pe,{placeholder:"City, neighborhood, or ZIP",value:s,onChange:O=>{t(O.target.value),o(!0),d(-1)},onFocus:()=>o(!0),onKeyDown:O=>{if(!(!l||g.length===0))if(O.key==="ArrowDown")O.preventDefault(),d(U=>Math.min(U+1,g.length-1));else if(O.key==="ArrowUp")O.preventDefault(),d(U=>Math.max(U-1,0));else if(O.key==="Enter"&&c>=0){O.preventDefault();const U=g[c];t(U.value),o(!1)}else O.key==="Escape"&&o(!1)},className:"pl-16 h-16 text-base md:text-lg border-0 bg-transparent text-white placeholder:text-white/50 focus-visible:ring-0 rounded-none"})]}),e.jsxs("button",{onClick:()=>r(!n),className:"hidden sm:flex items-center gap-2 px-6 border-l text-sm text-white/80 hover:text-white transition",style:{borderColor:"rgba(201,168,76,0.3)"},children:[e.jsx(JI,{className:"h-4 w-4"}),"Filters"]}),e.jsxs("button",{className:"px-8 flex items-center gap-2 font-medium transition hover:brightness-110",style:{background:Iu,color:k$},onClick:()=>o(!1),children:[e.jsx(Kr,{className:"h-5 w-5"}),e.jsx("span",{className:"hidden md:inline",children:"Search"})]})]}),l&&g.length>0&&e.jsxs("div",{className:"mt-2 rounded-2xl overflow-hidden shadow-2xl animate-fade-in",style:{background:"rgba(13,13,13,0.96)",border:"1px solid rgba(201,168,76,0.35)",backdropFilter:"blur(12px)"},children:[e.jsx("div",{className:"px-5 pt-3 pb-2 text-[10px] tracking-[0.2em] uppercase",style:{color:Iu},children:"Suggestions"}),e.jsx("ul",{className:"max-h-80 overflow-y-auto",children:g.map((O,U)=>e.jsx("li",{children:e.jsxs("button",{type:"button",onMouseEnter:()=>d(U),onClick:()=>{t(O.value),o(!1)},className:"w-full flex items-center justify-between gap-3 px-5 py-3 text-left transition",style:{background:c===U?"rgba(201,168,76,0.12)":"transparent"},children:[e.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[O.type==="city"&&e.jsx(ci,{className:"h-4 w-4 shrink-0",style:{color:Iu}}),O.type==="neighborhood"&&e.jsx(ji,{className:"h-4 w-4 shrink-0",style:{color:Iu}}),O.type==="zip"&&e.jsx(va,{className:"h-4 w-4 shrink-0",style:{color:Iu}}),e.jsx("span",{className:"text-white/90 truncate",children:O.label})]}),e.jsxs("span",{className:"text-xs text-white/50 shrink-0",children:[O.count," ",O.count===1?"listing":"listings"]})]})},`${O.type}-${O.value}-${U}`))})]}),l&&s.trim()&&g.length===0&&e.jsx("div",{className:"mt-2 rounded-2xl px-5 py-4 text-sm text-white/70",style:{background:"rgba(13,13,13,0.96)",border:"1px solid rgba(201,168,76,0.25)"},children:"No matches yet — try a nearby city or ZIP."}),n&&e.jsxs("div",{className:"mt-4 p-6 rounded-2xl grid sm:grid-cols-2 md:grid-cols-4 gap-4 animate-fade-in",style:{background:"rgba(26,26,26,0.9)",border:"1px solid rgba(201,168,76,0.25)"},children:[e.jsxs("div",{children:[e.jsx("label",{className:"lu-eyebrow text-white/60 mb-2 block",children:"Status"}),e.jsxs(ms,{value:h.status||"all",onValueChange:O=>m({...h,status:O==="all"?"":O}),children:[e.jsx(us,{className:"lu-input-dark",children:e.jsx(fs,{})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"all",children:"Any status"}),Object.entries(g7e).map(([O,U])=>e.jsx(Ge,{value:O,children:U},O))]})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"lu-eyebrow text-white/60 mb-2 block",children:"Type"}),e.jsxs(ms,{value:h.propertyType||"all",onValueChange:O=>m({...h,propertyType:O==="all"?"":O}),children:[e.jsx(us,{className:"lu-input-dark",children:e.jsx(fs,{})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"all",children:"Any type"}),Object.entries(BDs).map(([O,U])=>e.jsx(Ge,{value:O,children:U},O))]})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"lu-eyebrow text-white/60 mb-2 block",children:"Min Price"}),e.jsx(pe,{type:"number",placeholder:"No min",value:h.minPrice,onChange:O=>m({...h,minPrice:O.target.value}),className:"lu-input-dark"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"lu-eyebrow text-white/60 mb-2 block",children:"Max Price"}),e.jsx(pe,{type:"number",placeholder:"No max",value:h.maxPrice,onChange:O=>m({...h,maxPrice:O.target.value}),className:"lu-input-dark"})]}),w&&e.jsx("div",{className:"sm:col-span-2 md:col-span-4 flex justify-end",children:e.jsxs($,{variant:"ghost",size:"sm",onClick:b,className:"text-white/70 hover:text-white gap-1",children:[e.jsx(gr,{className:"h-4 w-4"})," Clear all"]})})]})]}),e.jsx("div",{className:"lu-hero-stats mt-14 grid grid-cols-3 gap-6 max-w-2xl",children:[{label:"Listings",value:((x==null?void 0:x.length)??0).toString()},{label:"Active Now",value:D.toString()},{label:"Luxury $1M+",value:P.toString()}].map(O=>e.jsxs("div",{children:[e.jsx("div",{className:"lu-serif text-4xl md:text-5xl",style:{color:jM},children:O.value}),e.jsx("div",{className:"lu-eyebrow text-white/60 mt-1",children:O.label})]},O.label))})]}),e.jsxs("div",{className:"absolute bottom-6 left-1/2 -translate-x-1/2 flex flex-col items-center gap-2 text-white/60",children:[e.jsx("span",{className:"lu-eyebrow",children:"Scroll"}),e.jsx(Tl,{className:"h-4 w-4 animate-bounce"})]})]})]}),R.length>0&&e.jsx("section",{className:"py-8 overflow-hidden",style:{background:l0t,borderTop:"1px solid rgba(201,168,76,0.15)",borderBottom:"1px solid rgba(201,168,76,0.15)"},children:e.jsx("div",{className:"lu-marquee whitespace-nowrap",children:[...R,...R,...R].map((O,U)=>e.jsxs("span",{className:"flex items-center gap-3 lu-serif text-2xl md:text-3xl text-white/40",children:[O,e.jsx("span",{className:"h-1.5 w-1.5 rounded-full",style:{background:Iu}})]},U))})}),E&&e.jsx("section",{id:"featured",className:"py-20 md:py-28",children:e.jsxs("div",{className:"max-w-7xl mx-auto px-6",children:[e.jsxs("div",{className:"flex items-end justify-between mb-10 md:mb-14",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-3 mb-4",children:[e.jsx(Nn,{className:"h-4 w-4",style:{color:Iu}}),e.jsx("span",{className:"lu-eyebrow lu-gold",children:"Today's Featured Residence"})]}),e.jsxs("h2",{className:"lu-serif text-4xl md:text-5xl lg:text-6xl",children:["Today's ",e.jsx("span",{className:"italic",style:{color:jM},children:"standout"}),"."]})]}),e.jsx("div",{className:"hidden md:block h-px flex-1 mx-8 lu-gold-line"})]}),e.jsx(wr,{to:C(E),className:"group block",children:e.jsxs("div",{className:"grid lg:grid-cols-5 gap-6 lg:gap-10 items-stretch",children:[e.jsxs("div",{className:"lg:col-span-3 relative overflow-hidden rounded-2xl aspect-[4/3] bg-black",children:[(()=>{var U,W;const O=((U=E.photos)==null?void 0:U.find(V=>V.is_primary))||((W=E.photos)==null?void 0:W[0]);return O?e.jsx("img",{src:O.photo_url,alt:E.property_address||E.city,className:"w-full h-full object-cover lu-img-zoom"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center",children:e.jsx(va,{className:"h-16 w-16 text-white/20"})})})(),e.jsx("div",{className:"absolute top-5 left-5 px-4 py-1.5 rounded-full lu-eyebrow",style:{background:Iu,color:k$},children:g7e[E.status]||"Featured"})]}),e.jsxs("div",{className:"lg:col-span-2 flex flex-col justify-center",children:[e.jsxs("div",{className:"lu-eyebrow text-white/60 mb-4 flex items-center gap-2",children:[e.jsx(ci,{className:"h-3.5 w-3.5",style:{color:Iu}}),E.city,E.state?`, ${E.state}`:""]}),E.property_address&&e.jsx("h3",{className:"lu-serif text-3xl md:text-4xl mb-4 leading-tight",children:E.property_address}),e.jsx("div",{className:"lu-serif text-5xl md:text-6xl mb-6",style:{color:jM},children:v(E.price)}),e.jsxs("div",{className:"flex items-center gap-6 text-white/70 mb-8",children:[E.bedrooms&&e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(l2,{className:"h-4 w-4",style:{color:Iu}}),E.bedrooms," bd"]}),E.bathrooms&&e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(T0,{className:"h-4 w-4",style:{color:Iu}}),E.bathrooms," ba"]}),E.square_footage&&e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(C_,{className:"h-4 w-4",style:{color:Iu}}),E.square_footage.toLocaleString()," sf"]})]}),E.description&&e.jsx("p",{className:"text-white/60 leading-relaxed mb-8 line-clamp-4",children:E.description}),e.jsxs("div",{className:"inline-flex items-center gap-3 lu-eyebrow group-hover:gap-5 transition-all",style:{color:Iu},children:["View Residence ",e.jsx(ei,{className:"h-4 w-4"})]})]})]})})]})}),e.jsx("section",{id:"collection",className:"py-20 md:py-28",style:{background:l0t},children:e.jsxs("div",{className:"max-w-7xl mx-auto px-6",children:[e.jsxs("div",{className:"text-center mb-14",children:[e.jsxs("div",{className:"flex items-center justify-center gap-3 mb-4",children:[e.jsx("span",{className:"h-px w-10",style:{background:Iu}}),e.jsx("span",{className:"lu-eyebrow lu-gold",children:"The Collection"}),e.jsx("span",{className:"h-px w-10",style:{background:Iu}})]}),e.jsxs("h2",{className:"lu-serif text-4xl md:text-5xl lg:text-6xl mb-4",children:["Every home, ",e.jsx("span",{className:"italic",style:{color:jM},children:"carefully considered"}),"."]}),e.jsx("p",{className:"text-white/60 max-w-2xl mx-auto",children:"Browse the full catalogue of LevelUp-represented properties. Filter, refine, and find the one that feels like yours."})]}),y?e.jsx("div",{className:"grid sm:grid-cols-2 lg:grid-cols-3 gap-8",children:[...Array(6)].map((O,U)=>e.jsxs("div",{className:"space-y-3",children:[e.jsx(yn,{className:"aspect-[4/5] bg-white/5"}),e.jsx(yn,{className:"h-6 w-32 bg-white/5"}),e.jsx(yn,{className:"h-4 w-full bg-white/5"})]},U))}):I.length>0?e.jsx("div",{className:"grid sm:grid-cols-2 lg:grid-cols-3 gap-x-8 gap-y-14",children:I.map(O=>{var W,V,G,Y,X;const U=((W=O.photos)==null?void 0:W.find(ae=>ae.is_primary))||((V=O.photos)==null?void 0:V[0]);return e.jsxs(wr,{to:C(O),className:"group lu-card-hover block",children:[e.jsxs("div",{className:"relative aspect-[4/5] overflow-hidden bg-black mb-5 rounded-lg",children:[U?e.jsx("img",{src:U.photo_url,alt:O.property_address||O.city,className:"w-full h-full object-cover lu-img-zoom"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center",children:e.jsx(va,{className:"h-12 w-12 text-white/20"})}),e.jsx("div",{className:"absolute inset-0 opacity-0 group-hover:opacity-100 transition-opacity",style:{background:"linear-gradient(180deg, transparent 40%, rgba(13,13,13,0.85) 100%)"}}),e.jsx("div",{className:"absolute top-4 left-4 px-3 py-1 lu-eyebrow rounded-full",style:{background:"rgba(13,13,13,0.75)",color:Iu,border:`1px solid ${Iu}`},children:g7e[O.status]}),e.jsxs("div",{className:"absolute bottom-4 left-4 right-4 flex items-center gap-4 text-white/90 text-sm opacity-0 group-hover:opacity-100 translate-y-2 group-hover:translate-y-0 transition-all",children:[O.bedrooms&&e.jsxs("span",{children:[O.bedrooms," bd"]}),O.bathrooms&&e.jsxs("span",{children:[O.bathrooms," ba"]}),O.square_footage&&e.jsxs("span",{children:[O.square_footage.toLocaleString()," sf"]})]})]}),e.jsxs("div",{children:[e.jsxs("div",{className:"lu-eyebrow text-white/50 mb-2 flex items-center gap-2",children:[e.jsx(ci,{className:"h-3 w-3",style:{color:Iu}}),O.city,O.state?`, ${O.state}`:""]}),e.jsx("div",{className:"lu-serif text-2xl md:text-3xl mb-1",style:{color:jM},children:v(O.price)}),O.property_address&&e.jsx("p",{className:"text-white/70 text-sm truncate",children:O.property_address}),((G=O.agent)==null?void 0:G.name)&&e.jsxs("p",{className:"text-white/40 text-xs mt-3 flex items-center gap-2",children:[e.jsx(ji,{className:"h-3 w-3"}),O.agent.name,(((Y=O.agent.brokerage)==null?void 0:Y.name)||O.agent.brokerage_name)&&e.jsxs("span",{className:"truncate",children:["· ",((X=O.agent.brokerage)==null?void 0:X.name)||O.agent.brokerage_name]})]})]})]},O.id)})}):e.jsxs("div",{className:"text-center py-20",children:[e.jsx("div",{className:"w-20 h-20 mx-auto mb-6 rounded-full flex items-center justify-center",style:{border:`1px solid ${Iu}`},children:e.jsx(va,{className:"h-8 w-8",style:{color:Iu}})}),e.jsx("h3",{className:"lu-serif text-2xl mb-2",children:"No listings match yet"}),e.jsx("p",{className:"text-white/60 mb-6",children:"Adjust your search — or check back soon for new arrivals."}),w&&e.jsx($,{onClick:b,style:{background:Iu,color:k$},className:"hover:brightness-110",children:"Clear filters"})]})]})}),x&&x.length>0&&e.jsx("section",{id:"map",className:"py-20 md:py-28",children:e.jsxs("div",{className:"max-w-7xl mx-auto px-6",children:[e.jsx("div",{className:"flex flex-col md:flex-row md:items-end md:justify-between gap-4 mb-10",children:e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-3 mb-4",children:[e.jsx("span",{className:"h-px w-10",style:{background:Iu}}),e.jsx("span",{className:"lu-eyebrow lu-gold",children:"Explore"})]}),e.jsxs("h2",{className:"lu-serif text-4xl md:text-5xl",children:["Every listing, ",e.jsx("span",{className:"italic",style:{color:jM},children:"on the map"}),"."]})]})}),e.jsx("div",{className:"rounded-2xl overflow-hidden",style:{border:"1px solid rgba(201,168,76,0.2)"},children:e.jsx(zDs,{listings:x,isLoading:y})})]})}),e.jsxs("section",{className:"relative py-24 md:py-32 overflow-hidden lu-grain",children:[e.jsx("div",{className:"absolute inset-0",style:{background:`radial-gradient(ellipse at center, rgba(201,168,76,0.15) 0%, ${k$} 70%)`}}),e.jsxs("div",{className:"relative max-w-4xl mx-auto px-6 text-center",children:[e.jsxs("div",{className:"flex items-center justify-center gap-3 mb-6",children:[e.jsx("span",{className:"h-px w-10",style:{background:Iu}}),e.jsx("span",{className:"lu-eyebrow lu-gold",children:"For Agents"}),e.jsx("span",{className:"h-px w-10",style:{background:Iu}})]}),e.jsxs("h2",{className:"lu-serif text-4xl md:text-6xl mb-6 leading-tight",children:["Your listings deserve a",e.jsx("br",{}),e.jsx("span",{className:"italic",style:{color:jM},children:"stage this good"}),"."]}),e.jsx("p",{className:"text-white/70 text-lg mb-10 max-w-2xl mx-auto",children:"Join LevelUp and get every listing published to this collection — with a cinematic microsite, lead capture, and marketing tools that do the heavy lifting."}),e.jsxs("a",{href:"https://relevelup.com",target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-3 px-8 py-4 rounded-full font-medium transition hover:brightness-110",style:{background:Iu,color:k$},children:["Explore LevelUp",e.jsx(ei,{className:"h-4 w-4"})]})]})]}),e.jsx("footer",{className:"py-14",style:{background:"#080808",borderTop:"1px solid rgba(201,168,76,0.15)"},children:e.jsxs("div",{className:"max-w-7xl mx-auto px-6 flex flex-col md:flex-row items-center justify-between gap-6",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("img",{src:TG,alt:"LevelUp",className:"h-6"}),e.jsx("span",{className:"h-4 w-px bg-white/20"}),e.jsx("span",{className:"lu-eyebrow lu-gold",children:"Listings"})]}),e.jsxs("p",{className:"text-white/40 text-sm",children:["© ",new Date().getFullYear()," LevelUp. All rights reserved."]}),e.jsx("a",{href:"https://relevelup.com",target:"_blank",rel:"noopener noreferrer",className:"text-white/60 hover:text-white text-sm transition",children:"relevelup.com →"})]})})]}),e.jsx(XRs,{}),e.jsx(QRs,{})]})}const $Ds=j.lazy(()=>ri(()=>import("./PublicHomeValue-JaRfp-R-.js"),[]));function UDs(){const s=fu(),t=window.location.hostname;if(!(t==="listings.relevelup.com"||t.startsWith("listings.")))return null;const r=s.pathname.slice(1);return!r||r===""?e.jsx(K7t,{}):r==="home-value"||r==="whats-my-home-worth"?e.jsx(j.Suspense,{fallback:e.jsx("div",{}),children:e.jsx($Ds,{})}):r.startsWith("public/")?null:e.jsx(ast,{slugOverride:r})}const qDs=j.lazy(()=>ri(()=>import("./CommercialMarketplace-CQAi-I7r.js"),[]));function VDs(){const t=fu().pathname.slice(1);return t?t.startsWith("public/")?null:e.jsx(ast,{slugOverride:t}):e.jsx(j.Suspense,{fallback:e.jsx("div",{className:"min-h-screen bg-[#0a0d12]"}),children:e.jsx(qDs,{})})}function WLe({card:s,variant:t}){const n=s.brokerage_display_name||s.brokerage_logo_url,r=s.team_name||s.team_logo_url;if(!n&&!r)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 ${n&&r?"divide-y divide-current/10":""}`,children:[n&&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})]}),r&&e.jsxs("div",{className:`flex flex-col items-center gap-1.5 w-full ${n?"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 Y7t=s=>tt({queryKey:["agent-card-public",s],queryFn:async()=>{if(!s)throw new Error("No slug provided");const{data:t,error:n}=await q.from("agent_cards").select("*").eq("slug",s).eq("is_published",!0).single();if(n)throw n;const{data:r}=await q.from("profiles").select("name, email, phone, brokerage_id").eq("id",t.user_id).single();let a=null;if(r!=null&&r.brokerage_id){const{data:o}=await q.from("brokerages").select("name").eq("id",r.brokerage_id).single();a=(o==null?void 0:o.name)||null}let i=null;try{const{data:o}=await q.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 q.storage.from("avatars").list(`${t.user_id}`);if(c&&c.length>0){const{data:d}=q.storage.from("avatars").getPublicUrl(`${t.user_id}/${c[0].name}`);i=`${d.publicUrl}?t=${Date.now()}`}}}catch{}const l={...r||{name:null,email:null,phone:null,brokerage_id:null},email:t.display_email||(r==null?void 0:r.email)||null};return{...t,social_links:t.social_links||[],profile:l,brokerage_name:t.brokerage_display_name||a,avatar_url:i}},enabled:!!s}),HDs=()=>tt({queryKey:["agent-cards-admin"],queryFn:async()=>{const{data:s,error:t}=await q.from("agent_cards").select("*").order("created_at",{ascending:!1});if(t)throw t;return s}}),GDs=s=>tt({queryKey:["agent-card",s],queryFn:async()=>{if(!s)return null;const{data:t,error:n}=await q.from("agent_cards").select("*").eq("user_id",s).maybeSingle();if(n)throw n;return t},enabled:!!s}),Z7t=()=>{const s=Vt();return ft({mutationFn:async t=>{const{data:n,error:r}=await q.from("agent_cards").insert(t).select().single();if(r)throw r;return n},onSuccess:()=>{s.invalidateQueries({queryKey:["agent-cards-admin"]}),s.invalidateQueries({queryKey:["agent-card"]}),re.success("Agent card created")},onError:t=>re.error(t.message)})},X7t=()=>{const s=Vt();return ft({mutationFn:async({id:t,...n})=>{const{data:r,error:a}=await q.from("agent_cards").update(n).eq("id",t).select().single();if(a)throw a;return r},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["agent-cards-admin"]}),s.invalidateQueries({queryKey:["agent-card"]}),re.success("Agent card updated")},onError:t=>re.error(t.message)})},Nu=async(s,t,n,r)=>{const a=new URLSearchParams(window.location.search);await q.from("agent_card_interactions").insert({card_id:s,interaction_type:t,interaction_detail:n||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:{}})},WDs=async(s,t)=>{const{error:n}=await q.from("agent_card_leads").insert({card_id:s,...t});if(n)throw n},Q7t=s=>tt({queryKey:["agent-card-analytics",s],queryFn:async()=>{if(!s)return null;const{data:t,error:n}=await q.from("agent_card_interactions").select("interaction_type, interaction_detail, created_at").eq("card_id",s).order("created_at",{ascending:!1}).limit(500);if(n)throw n;const{data:r,error:a}=await q.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:r||[],interactions:t||[]}},enabled:!!s});function KLe({open:s,onOpenChange:t,cardId:n,type:r,agentName:a}){const[i,l]=j.useState(""),[o,c]=j.useState(""),[d,u]=j.useState(""),[h,m]=j.useState(""),[f,g]=j.useState(""),[x,y]=j.useState(!1),v=async b=>{if(b.preventDefault(),!i.trim()){re.error("Please enter your name");return}y(!0);try{await WDs(n,{lead_type:r,name:i.trim(),email:o.trim()||void 0,phone:d.trim()||void 0,message:f.trim()||void 0,intent:h||void 0}),Nu(n,"lead_submitted",r),q.functions.invoke("card-lead-notify",{body:{cardId:n,leadType:r,name:i.trim(),email:o.trim()||void 0,phone:d.trim()||void 0,message:f.trim()||void 0,intent:h||void 0}}).catch(w=>console.error("Card lead notify failed:",w)),re.success(r==="booking"?"Request sent! They'll be in touch soon.":r==="connect"?"Info shared! They'll be in touch soon.":"Referral submitted! Thank you."),t(!1),l(""),c(""),u(""),m(""),g("")}catch{re.error("Something went wrong. Please try again.")}finally{y(!1)}};return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Os,{className:"sm:max-w-md rounded-2xl",children:[e.jsxs(Us,{children:[e.jsx(Bs,{children:r==="booking"?"Book a Call":r==="connect"?"Connect with Me":"Refer a Friend"}),e.jsx(Ir,{children:r==="booking"?`Let ${a} know you'd like to connect.`:r==="connect"?`Share your info and ${a} will reach out.`:`Know someone who could use ${a}'s help?`})]}),e.jsxs("form",{onSubmit:v,className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"lead-name",children:"Name *"}),e.jsx(pe,{id:"lead-name",value:i,onChange:b=>l(b.target.value),placeholder:"Your name",required:!0})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"lead-phone",children:"Phone"}),e.jsx(pe,{id:"lead-phone",type:"tel",value:d,onChange:b=>u(b.target.value),placeholder:"(555) 123-4567"})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"lead-email",children:"Email"}),e.jsx(pe,{id:"lead-email",type:"email",value:o,onChange:b=>c(b.target.value),placeholder:"you@example.com"})]}),r==="booking"&&e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"lead-intent",children:"I'm looking to..."}),e.jsxs(ms,{value:h,onValueChange:m,children:[e.jsx(us,{children:e.jsx(fs,{placeholder:"Select one"})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"buy",children:"Buy a home"}),e.jsx(Ge,{value:"sell",children:"Sell my home"}),e.jsx(Ge,{value:"both",children:"Buy & Sell"}),e.jsx(Ge,{value:"other",children:"Something else"})]})]})]}),r!=="connect"&&e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"lead-message",children:r==="referral"?"Tell us about them":"Message (optional)"}),e.jsx(pe,{id:"lead-message",value:f,onChange:b=>g(b.target.value),placeholder:r==="referral"?"Their name, phone, situation...":"Anything you'd like us to know"})]}),e.jsx($,{type:"submit",className:"w-full rounded-2xl",disabled:x,children:x?"Sending...":"Submit"})]})]})})}const KDs=s=>tt({queryKey:["card-blocks",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await q.from("card_blocks").select("*").eq("card_id",s).eq("is_visible",!0).order("sort_order",{ascending:!0});if(n)throw n;return t||[]},enabled:!!s}),YDs=s=>tt({queryKey:["card-blocks-all",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await q.from("card_blocks").select("*").eq("card_id",s).order("sort_order",{ascending:!0});if(n)throw n;return t||[]},enabled:!!s}),ZDs=()=>{const s=Vt();return ft({mutationFn:async t=>{const{data:n,error:r}=await q.from("card_blocks").insert(t).select().single();if(r)throw r;return n},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["card-blocks",n.card_id]}),s.invalidateQueries({queryKey:["card-blocks-all",n.card_id]}),re.success("Block added")},onError:t=>re.error(t.message)})},XDs=()=>{const s=Vt();return ft({mutationFn:async({id:t,...n})=>{const{data:r,error:a}=await q.from("card_blocks").update(n).eq("id",t).select().single();if(a)throw a;return r},onSuccess:()=>{s.invalidateQueries({queryKey:["card-blocks"]}),s.invalidateQueries({queryKey:["card-blocks-all"]}),re.success("Block updated")},onError:t=>re.error(t.message)})},QDs=()=>{const s=Vt();return ft({mutationFn:async t=>{const{error:n}=await q.from("card_blocks").delete().eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["card-blocks"]}),s.invalidateQueries({queryKey:["card-blocks-all"]}),re.success("Block removed")},onError:t=>re.error(t.message)})};function JDs(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 eFs(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 tFs={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 sFs({block:s,variant:t}){const n=s.config;if(!n.video_url)return null;const r=n.video_url.includes("mediadelivery.net")||n.video_url.includes("bunnycdn.com"),a=eFs(n.video_url),i=r||!!a,l=r?JDs(n.video_url):a||n.video_url;return e.jsx("div",{className:tFs[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:n.video_url,controls:!0,className:"w-full",preload:"metadata"})})}const nFs={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 rFs({block:s,variant:t}){const r=s.config.testimonials||[],[a,i]=j.useState(0);if(r.length===0)return null;const l=nFs[t],o=r[a];return e.jsxs("div",{className:l.container,children:[e.jsxs("div",{className:l.card,children:[e.jsx(x2,{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})]})]}),r.length>1&&e.jsxs("div",{className:"flex items-center justify-center gap-3 mt-3",children:[e.jsx("button",{onClick:()=>i(c=>(c-1+r.length)%r.length),className:l.nav,children:e.jsx(Cd,{className:"h-4 w-4"})}),e.jsx("div",{className:"flex gap-1.5",children:r.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)%r.length),className:l.nav,children:e.jsx(Di,{className:"h-4 w-4"})})]})]})}const aFs={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 iFs({block:s,variant:t}){const r=s.config.tags||[];if(r.length===0)return null;const a=aFs[t];return e.jsx("div",{className:a.container,children:r.map((i,l)=>e.jsx("span",{className:a.tag,children:i},l))})}const oFs={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 lFs({block:s,cardId:t,variant:n}){const a=s.config.links||[];if(a.length===0)return null;const i=oFs[n];return e.jsx("div",{className:i.container,children:a.map((l,o)=>e.jsxs("a",{href:l.url,target:"_blank",rel:"noopener noreferrer",onClick:()=>Nu(t,"button_click",`custom_link_${l.label}`),className:i.link,children:[e.jsx("span",{children:l.label}),e.jsx(kr,{className:`h-4 w-4 ${i.icon}`})]},o))})}const cGe={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 cFs({path:s,color:t,size:n=20}){return e.jsx("svg",{viewBox:"0 0 24 24",width:n,height:n,fill:t,children:e.jsx("path",{d:s})})}const dFs={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 uFs({block:s,cardId:t,variant:n}){const a=s.config.platforms||[],i=dFs[n];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=cGe[l.platform.toLowerCase()];return!c||!l.url?null:e.jsx("a",{href:l.url,target:"_blank",rel:"noopener noreferrer",onClick:()=>Nu(t,"button_click",`social_${l.platform}`),className:i.linkClass,title:c.label,children:e.jsx(cFs,{path:c.icon,color:c.color})},o)})})]})}function YLe({cardId:s,variant:t}){const{data:n}=KDs(s);if(!n||n.length===0)return null;const r=n.filter(l=>l.block_type==="social_media"&&l.is_visible),a=n.filter(l=>l.block_type!=="social_media"),i=r.length>0?{...r[0],config:{platforms:r.flatMap(l=>l.config.platforms||[])}}:null;return n.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(sFs,{block:l,variant:t},l.id);case"testimonials":return e.jsx(rFs,{block:l,variant:t},l.id);case"specialties":return e.jsx(iFs,{block:l,variant:t},l.id);case"custom_links":return e.jsx(lFs,{block:l,cardId:s,variant:t},l.id);default:return null}}),i&&e.jsx(uFs,{block:i,cardId:s,variant:t})]})}async function hFs(s){try{const t=await fetch(s);if(!t.ok)return null;const n=await t.blob(),r=n.type||"image/jpeg";return new Promise(a=>{const i=new FileReader;i.onloadend=()=>{const o=i.result.split(",")[1];a({base64:o,mimeType:r})},i.onerror=()=>a(null),i.readAsDataURL(n)})}catch{return null}}function mFs(s){const t=s.trim().split(/\s+/);if(t.length<=1)return{first:t[0]||"",last:""};const n=t.pop();return{first:t.join(" "),last:n}}async function ZLe(s){const{first:t,last:n}=mFs(s.name),r=["BEGIN:VCARD","VERSION:3.0",`FN:${s.name}`,`N:${n};${t};;;`];if(s.phone&&r.push(`TEL;TYPE=CELL:${s.phone}`),s.email&&r.push(`EMAIL;TYPE=INTERNET:${s.email}`),s.brokerage&&r.push(`ORG:${s.brokerage}`),r.push(`URL:${s.cardUrl}`),s.avatarUrl){const o=await hFs(s.avatarUrl);if(o){const d={"image/jpeg":"JPEG","image/jpg":"JPEG","image/png":"PNG","image/gif":"GIF","image/webp":"JPEG"}[o.mimeType]||"JPEG";r.push(`PHOTO;ENCODING=b;TYPE=${d}:${o.base64}`)}}r.push("END:VCARD");const a=new Blob([r.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),re.success("Contact saved!")}function fFs({card:s}){var v;const[t,n]=j.useState(!1),[r,a]=j.useState("booking"),i=((v=s.profile)==null?void 0:v.name)||"Agent",l=i.split(" ").map(b=>b[0]).join("").toUpperCase().slice(0,2),o=(b,w)=>{Nu(s.id,"button_click",b),w()},c=()=>o("call",()=>{var b;(b=s.profile)!=null&&b.phone?window.location.href=`tel:${s.profile.phone}`:re.error("Phone number not available")}),d=()=>o("text",()=>{var b;(b=s.profile)!=null&&b.phone?window.location.href=`sms:${s.profile.phone}`:re.error("Phone number not available")}),u=()=>o("email",()=>{var b;(b=s.profile)!=null&&b.email?window.location.href=`mailto:${s.profile.email}`:re.error("Email not available")}),h=()=>{s.booking_url?o("book",()=>window.open(s.booking_url,"_blank")):(a("booking"),n(!0),Nu(s.id,"button_click","book"))},m=()=>{var b,w;Nu(s.id,"contact_saved"),ZLe({name:i,phone:(b=s.profile)==null?void 0:b.phone,email:(w=s.profile)==null?void 0:w.email,brokerage:s.brokerage_name,avatarUrl:s.avatar_url,cardUrl:window.location.href})},f=async()=>{Nu(s.id,"share_event");const b=`https://cards.relevelup.com/${s.slug}`,w="Here's my contact card — save it so we can stay in touch.";if(navigator.share)try{await navigator.share({title:`${i}`,text:w,url:b})}catch{}else await navigator.clipboard.writeText(b),re.success("Link copied!")},g=()=>{a("referral"),n(!0),Nu(s.id,"button_click","refer")},x=()=>{a("connect"),n(!0),Nu(s.id,"button_click","connect")},y={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(Oa,{className:"h-28 w-28 mx-auto mb-4 ring-4 ring-white shadow-lg",children:[e.jsx(Li,{src:s.avatar_url||void 0,alt:i}),e.jsx(za,{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($,{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(Da,{className:"h-5 w-5"}),e.jsx("span",{className:"text-xs font-medium",children:"Call"})]}),e.jsxs($,{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(eo,{className:"h-5 w-5"}),e.jsx("span",{className:"text-xs font-medium",children:"Text"})]}),e.jsxs($,{onClick:u,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(mn,{className:"h-5 w-5"}),e.jsx("span",{className:"text-xs font-medium",children:"Email"})]})]}),e.jsxs($,{onClick:h,className:"w-full h-12 text-base font-semibold rounded-2xl shadow-sm mb-6",variant:"outline",children:[e.jsx(Ta,{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(Ja,{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(WLe,{card:s,variant:"standard"}),e.jsx(YLe,{cardId:s.id,variant:"standard"}),e.jsxs("div",{className:"space-y-2 mb-6",children:[s.show_save_contact&&e.jsxs($,{variant:"ghost",onClick:m,className:"w-full justify-start h-12 rounded-2xl text-slate-700 hover:bg-slate-100",children:[e.jsx(di,{className:"h-4 w-4 mr-3 text-primary"}),"Save Contact"]}),s.show_leave_review&&s.review_source_url&&e.jsxs($,{variant:"ghost",onClick:()=>{Nu(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(Ja,{className:"h-4 w-4 mr-3 text-amber-500"}),"Leave a Review"]}),s.show_refer_friend&&e.jsxs($,{variant:"ghost",onClick:g,className:"w-full justify-start h-12 rounded-2xl text-slate-700 hover:bg-slate-100",children:[e.jsx(Zn,{className:"h-4 w-4 mr-3 text-primary"}),"Refer a Friend"]}),e.jsxs($,{variant:"ghost",onClick:x,className:"w-full justify-start h-12 rounded-2xl text-slate-700 hover:bg-slate-100",children:[e.jsx(sc,{className:"h-4 w-4 mr-3 text-primary"}),"Connect with Me"]}),e.jsxs($,{variant:"ghost",onClick:f,className:"w-full justify-start h-12 rounded-2xl text-slate-700 hover:bg-slate-100",children:[e.jsx(zd,{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((b,w)=>e.jsx("a",{href:b.url,target:"_blank",rel:"noopener noreferrer",onClick:()=>Nu(s.id,"button_click",`social_${b.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:y[b.platform.toLowerCase()]||"🔗"},w))}),e.jsx("div",{className:"text-center",children:e.jsx("p",{className:"text-xs text-slate-400",children:"Powered by LevelUp"})})]}),e.jsx(KLe,{open:t,onOpenChange:n,cardId:s.id,type:r,agentName:i})]})}function pFs({card:s}){var v;const[t,n]=j.useState(!1),[r,a]=j.useState("booking"),i=((v=s.profile)==null?void 0:v.name)||"Agent",l=i.split(" ").map(b=>b[0]).join("").toUpperCase().slice(0,2),o=(b,w)=>{Nu(s.id,"button_click",b),w()},c=()=>o("call",()=>{var b;(b=s.profile)!=null&&b.phone?window.location.href=`tel:${s.profile.phone}`:re.error("Phone number not available")}),d=()=>o("text",()=>{var b;(b=s.profile)!=null&&b.phone?window.location.href=`sms:${s.profile.phone}`:re.error("Phone number not available")}),u=()=>o("email",()=>{var b;(b=s.profile)!=null&&b.email?window.location.href=`mailto:${s.profile.email}`:re.error("Email not available")}),h=()=>{s.booking_url?o("book",()=>window.open(s.booking_url,"_blank")):(a("booking"),n(!0),Nu(s.id,"button_click","book"))},m=()=>{var b,w;Nu(s.id,"contact_saved"),ZLe({name:i,phone:(b=s.profile)==null?void 0:b.phone,email:(w=s.profile)==null?void 0:w.email,brokerage:s.brokerage_name,avatarUrl:s.avatar_url,cardUrl:window.location.href})},f=async()=>{Nu(s.id,"share_event");const b=`https://cards.relevelup.com/${s.slug}`,w="Here's my contact card — save it so we can stay in touch.";if(navigator.share)try{await navigator.share({title:`${i}`,text:w,url:b})}catch{}else await navigator.clipboard.writeText(b),re.success("Link copied!")},g=()=>{a("referral"),n(!0),Nu(s.id,"button_click","refer")},x=()=>{a("connect"),n(!0),Nu(s.id,"button_click","connect")},y={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(Oa,{className:"h-32 w-32 mx-auto mb-5 ring-2 ring-[#c9a84c]/40 shadow-2xl",children:[e.jsx(Li,{src:s.avatar_url||void 0,alt:i}),e.jsx(za,{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:Da,label:"Call",handler:c},{icon:eo,label:"Text",handler:d},{icon:mn,label:"Email",handler:u}].map(({icon:b,label:w,handler:S})=>e.jsxs("button",{onClick:S,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(b,{className:"h-5 w-5 text-[#c9a84c]"}),e.jsx("span",{className:"text-xs font-medium text-[#e2e8f0]",children:w})]},w))}),e.jsxs("button",{onClick:h,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(Ta,{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(Ja,{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(WLe,{card:s,variant:"luxury"}),e.jsx(YLe,{cardId:s.id,variant:"luxury"}),e.jsxs("div",{className:"space-y-1 mb-6",children:[s.show_save_contact&&e.jsxs("button",{onClick:m,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(di,{className:"h-4 w-4 text-[#c9a84c]"})," Save Contact"]}),s.show_leave_review&&s.review_source_url&&e.jsxs("button",{onClick:()=>{Nu(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(Ja,{className:"h-4 w-4 text-[#c9a84c]"})," Leave a Review"]}),s.show_refer_friend&&e.jsxs("button",{onClick:g,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(Zn,{className:"h-4 w-4 text-[#c9a84c]"})," Refer a Friend"]}),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(sc,{className:"h-4 w-4 text-[#c9a84c]"})," Connect with Me"]}),e.jsxs("button",{onClick:f,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(zd,{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((b,w)=>e.jsx("a",{href:b.url,target:"_blank",rel:"noopener noreferrer",onClick:()=>Nu(s.id,"button_click",`social_${b.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:y[b.platform.toLowerCase()]||"🔗"},w))}),e.jsx("div",{className:"text-center",children:e.jsx("p",{className:"text-xs text-[#4a5568]",children:"Powered by LevelUp"})})]}),e.jsx(KLe,{open:t,onOpenChange:n,cardId:s.id,type:r,agentName:i})]})}function gFs({card:s}){var w,S,C,E;const[t,n]=j.useState(!1),[r,a]=j.useState("booking"),i=((w=s.profile)==null?void 0:w.name)||"Agent",l=i.split(" ").map(I=>I[0]).join("").toUpperCase().slice(0,2),o={accent:((S=s.bold_theme_colors)==null?void 0:S.accent)||"#ff5722",dark:((C=s.bold_theme_colors)==null?void 0:C.dark)||"#1a1a2e",button:((E=s.bold_theme_colors)==null?void 0:E.button)||"#ff5722"},c=(I,P)=>{const R=parseInt(I.replace("#",""),16),D=Math.max(0,(R>>16)-P),O=Math.max(0,(R>>8&255)-P),U=Math.max(0,(R&255)-P);return`#${(D<<16|O<<8|U).toString(16).padStart(6,"0")}`};c(o.accent,25),c(o.dark,-20),c(o.button,25);const d=(I,P)=>{Nu(s.id,"button_click",I),P()},u=()=>d("call",()=>{var I;(I=s.profile)!=null&&I.phone?window.location.href=`tel:${s.profile.phone}`:re.error("Phone number not available")}),h=()=>d("text",()=>{var I;(I=s.profile)!=null&&I.phone?window.location.href=`sms:${s.profile.phone}`:re.error("Phone number not available")}),m=()=>d("email",()=>{var I;(I=s.profile)!=null&&I.email?window.location.href=`mailto:${s.profile.email}`:re.error("Email not available")}),f=()=>{s.booking_url?d("book",()=>window.open(s.booking_url,"_blank")):(a("booking"),n(!0),Nu(s.id,"button_click","book"))},g=()=>{var I,P;Nu(s.id,"contact_saved"),ZLe({name:i,phone:(I=s.profile)==null?void 0:I.phone,email:(P=s.profile)==null?void 0:P.email,brokerage:s.brokerage_name,avatarUrl:s.avatar_url,cardUrl:window.location.href})},x=async()=>{Nu(s.id,"share_event");const I=`https://cards.relevelup.com/${s.slug}`,P="Here's my contact card — save it so we can stay in touch.";if(navigator.share)try{await navigator.share({title:`${i}`,text:P,url:I})}catch{}else await navigator.clipboard.writeText(I),re.success("Link copied!")},y=()=>{a("referral"),n(!0),Nu(s.id,"button_click","refer")},v=()=>{a("connect"),n(!0),Nu(s.id,"button_click","connect")},b={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(Oa,{className:"h-28 w-28 mx-auto mb-4 shadow-2xl",style:{boxShadow:`0 0 0 4px ${o.accent}`},children:[e.jsx(Li,{src:s.avatar_url||void 0,alt:i}),e.jsx(za,{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:Da,label:"Call",handler:u},{icon:eo,label:"Text",handler:h},{icon:mn,label:"Email",handler:m}].map(({icon:I,label:P,handler:R})=>e.jsxs("button",{onClick:R,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(I,{className:"h-5 w-5"}),e.jsx("span",{className:"text-xs",children:P})]},P))}),e.jsxs("button",{onClick:f,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(Ta,{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(Ja,{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(WLe,{card:s,variant:"bold"}),e.jsx(YLe,{cardId:s.id,variant:"bold"}),e.jsxs("div",{className:"space-y-1 mb-6",children:[s.show_save_contact&&e.jsxs("button",{onClick:g,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(di,{className:"h-4 w-4",style:{color:o.accent}})," Save Contact"]}),s.show_leave_review&&s.review_source_url&&e.jsxs("button",{onClick:()=>{Nu(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(Ja,{className:"h-4 w-4",style:{color:o.accent}})," 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-2xl hover:bg-gray-100 transition-colors text-sm font-bold",style:{color:o.dark},children:[e.jsx(Zn,{className:"h-4 w-4",style:{color:o.accent}})," Refer a Friend"]}),e.jsxs("button",{onClick:v,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(sc,{className:"h-4 w-4",style:{color:o.accent}})," Connect with Me"]}),e.jsxs("button",{onClick:x,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(zd,{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((I,P)=>e.jsx("a",{href:I.url,target:"_blank",rel:"noopener noreferrer",onClick:()=>Nu(s.id,"button_click",`social_${I.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:b[I.platform.toLowerCase()]||"🔗"},P))})]}),e.jsx("div",{className:"text-center py-6",children:e.jsx("p",{className:"text-xs text-white/50",children:"Powered by LevelUp"})})]}),e.jsx(KLe,{open:t,onOpenChange:n,cardId:s.id,type:r,agentName:i})]})}function xFs({card:s}){var v;const[t,n]=j.useState(!1),[r,a]=j.useState("booking"),i=((v=s.profile)==null?void 0:v.name)||"Agent",l=i.split(" ").map(b=>b[0]).join("").toUpperCase().slice(0,2),o=(b,w)=>{Nu(s.id,"button_click",b),w()},c=()=>o("call",()=>{var b;(b=s.profile)!=null&&b.phone?window.location.href=`tel:${s.profile.phone}`:re.error("Phone number not available")}),d=()=>o("text",()=>{var b;(b=s.profile)!=null&&b.phone?window.location.href=`sms:${s.profile.phone}`:re.error("Phone number not available")}),u=()=>o("email",()=>{var b;(b=s.profile)!=null&&b.email?window.location.href=`mailto:${s.profile.email}`:re.error("Email not available")}),h=()=>{s.booking_url?o("book",()=>window.open(s.booking_url,"_blank")):(a("booking"),n(!0),Nu(s.id,"button_click","book"))},m=()=>{var b,w;Nu(s.id,"contact_saved"),ZLe({name:i,phone:(b=s.profile)==null?void 0:b.phone,email:(w=s.profile)==null?void 0:w.email,brokerage:s.brokerage_name,avatarUrl:s.avatar_url,cardUrl:window.location.href})},f=async()=>{Nu(s.id,"share_event");const b=`https://cards.relevelup.com/${s.slug}`,w="Here's my contact card — save it so we can stay in touch.";if(navigator.share)try{await navigator.share({title:`${i}`,text:w,url:b})}catch{}else await navigator.clipboard.writeText(b),re.success("Link copied!")},g=()=>{a("referral"),n(!0),Nu(s.id,"button_click","refer")},x=()=>{a("connect"),n(!0),Nu(s.id,"button_click","connect")},y={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(Oa,{className:"h-28 w-28 mx-auto mb-4 ring-4 ring-white shadow-lg",children:[e.jsx(Li,{src:s.avatar_url||void 0,alt:i}),e.jsx(za,{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:Da,label:"Call",handler:c},{icon:eo,label:"Text",handler:d},{icon:mn,label:"Email",handler:u}].map(({icon:b,label:w,handler:S})=>e.jsxs("button",{onClick:S,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(b,{className:"h-5 w-5 text-[#1b3a4b]"}),e.jsx("span",{className:"text-xs font-semibold text-[#1b3a4b]",children:w})]},w))}),e.jsxs("button",{onClick:h,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(Ta,{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(Ja,{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(WLe,{card:s,variant:"classic"}),e.jsx(YLe,{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:m,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(di,{className:"h-4 w-4 text-[#5a7a6f]"})," Save Contact"]}),s.show_leave_review&&s.review_source_url&&e.jsxs("button",{onClick:()=>{Nu(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(Ja,{className:"h-4 w-4 text-[#d4a843]"})," Leave a Review"]}),s.show_refer_friend&&e.jsxs("button",{onClick:g,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(Zn,{className:"h-4 w-4 text-[#5a7a6f]"})," Refer a Friend"]}),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(sc,{className:"h-4 w-4 text-[#5a7a6f]"})," Connect with Me"]}),e.jsxs("button",{onClick:f,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(zd,{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((b,w)=>e.jsx("a",{href:b.url,target:"_blank",rel:"noopener noreferrer",onClick:()=>Nu(s.id,"button_click",`social_${b.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:y[b.platform.toLowerCase()]||"🔗"},w))}),e.jsx("div",{className:"text-center",children:e.jsx("p",{className:"text-xs text-[#a0aec0]",children:"Powered by LevelUp"})})]}),e.jsx(KLe,{open:t,onOpenChange:n,cardId:s.id,type:r,agentName:i})]})}function ist({card:s}){switch(s.theme){case"luxury":return e.jsx(pFs,{card:s});case"bold":return e.jsx(gFs,{card:s});case"classic":return e.jsx(xFs,{card:s});case"standard":default:return e.jsx(fFs,{card:s})}}function yFs(){const s=fu();j.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(vFs,{slug:t})}function vFs({slug:s}){return e.jsx(bFs,{slug:s})}function bFs({slug:s}){var i;const{data:t,isLoading:n,error:r}=Y7t(s);if(j.useEffect(()=>{t!=null&&t.id&&Nu(t.id,"card_view")},[t==null?void 0:t.id]),n)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(yn,{className:"h-28 w-28 rounded-full"}),e.jsx(yn,{className:"h-6 w-48"}),e.jsx(yn,{className:"h-4 w-36"})]}),e.jsx(yn,{className:"h-12 w-full"}),e.jsx(yn,{className:"h-12 w-full"})]})});if(r||!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(Ml,{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(ist,{card:t})]})}function J7t({presentationId:s,ctaLabel:t,agentName:n,prefillName:r,prefillEmail:a,prefillPhone:i}){const[l,o]=j.useState(r||""),[c,d]=j.useState(a||""),[u,h]=j.useState(i||""),[m,f]=j.useState(""),[g,x]=j.useState(""),[y,v]=j.useState(!1),[b,w]=j.useState(!1),S=async C=>{if(C.preventDefault(),!l.trim()){re.error("Please enter your name");return}v(!0);try{const{error:E}=await q.from("smart_presentation_leads").insert({presentation_id:s,name:l.trim(),email:c.trim()||null,phone:u.trim()||null,intent:m||null,message:g.trim()||null});if(E)throw E;try{await q.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{}q.functions.invoke("presentation-lead-notify",{body:{presentationId:s,name:l.trim(),email:c.trim()||void 0,phone:u.trim()||void 0,intent:m||void 0,message:g.trim()||void 0}}).catch(I=>console.error("Presentation lead notify failed:",I)),w(!0)}catch{re.error("Something went wrong. Please try again.")}finally{v(!1)}};return b?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(la,{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:n?`${n} will be in touch soon.`:"We'll be in touch soon."})]}):e.jsxs("form",{onSubmit:S,className:"space-y-4 max-w-md mx-auto",children:[e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"pres-lead-name",children:"Name *"}),e.jsx(pe,{id:"pres-lead-name",value:l,onChange:C=>o(C.target.value),placeholder:"Your name",required:!0})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"pres-lead-phone",children:"Phone"}),e.jsx(pe,{id:"pres-lead-phone",type:"tel",value:u,onChange:C=>h(C.target.value),placeholder:"(555) 123-4567"})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"pres-lead-email",children:"Email"}),e.jsx(pe,{id:"pres-lead-email",type:"email",value:c,onChange:C=>d(C.target.value),placeholder:"you@example.com"})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"pres-lead-intent",children:"I'm looking to..."}),e.jsxs(ms,{value:m,onValueChange:f,children:[e.jsx(us,{children:e.jsx(fs,{placeholder:"Select one"})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"buy",children:"Buy a home"}),e.jsx(Ge,{value:"sell",children:"Sell my home"}),e.jsx(Ge,{value:"both",children:"Buy & Sell"}),e.jsx(Ge,{value:"other",children:"Something else"})]})]})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"pres-lead-message",children:"Message (optional)"}),e.jsx(pe,{id:"pres-lead-message",value:g,onChange:C=>x(C.target.value),placeholder:"Anything you'd like us to know"})]}),e.jsx($,{type:"submit",className:"w-full text-lg py-6 rounded-xl bg-blue-600 hover:bg-blue-700 text-white shadow-lg",disabled:y,children:y?"Sending...":t})]})}function _Fs(){const s=fu();j.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(wFs,{shareToken:t})}function wFs({shareToken:s}){var g;const[t,n]=j.useState(null),[r,a]=j.useState(!0),[i,l]=j.useState(0),[o,c]=j.useState(!1);j.useEffect(()=>{d()},[s]);const d=async()=>{const{data:x,error:y}=await q.from("smart_presentations").select("*").eq("share_token",s).eq("status","published").single();if(y||!x){c(!0),a(!1);return}const{data:v}=await q.from("profiles").select("name, email, phone, avatar_url, title, brokerage_id").eq("id",x.owner_user_id).single();let b;if(v!=null&&v.brokerage_id){const{data:S}=await q.from("brokerages").select("name").eq("id",v.brokerage_id).single();b=(S==null?void 0:S.name)||void 0}let w=null;if(x.contact_id){const{data:S}=await q.from("innercircle_contacts").select("first_name, last_name, email, phone").eq("id",x.contact_id).single();w=S}n({...x,owner_name:v==null?void 0:v.name,owner_email:v==null?void 0:v.email,owner_phone:v==null?void 0:v.phone,owner_avatar:v==null?void 0:v.avatar_url,owner_title:(v==null?void 0:v.title)||void 0,brokerage_name:b,contact_name:w?[w.first_name,w.last_name].filter(Boolean).join(" "):void 0,contact_email:(w==null?void 0:w.email)||void 0,contact_phone:(w==null?void 0:w.phone)||void 0}),a(!1);try{await q.rpc("log_presentation_view",{p_presentation_id:x.id,p_section_index:0,p_cta_clicked:!1,p_ip_hash:null,p_user_agent:navigator.userAgent,p_referrer:document.referrer||null})}catch{}},u=async()=>{if(t){try{await q.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")}},h=x=>{const y=x.match(/(?:youtube\.com\/watch\?v=|youtu\.be\/)([a-zA-Z0-9_-]+)/);if(y)return`https://www.youtube.com/embed/${y[1]}?rel=0`;if(x.includes("iframe.mediadelivery.net/play/")){const w=x.replace("/play/","/embed/"),S=w.includes("?")?"&":"?";return`${w}${S}responsive=true`}if(x.includes("iframe.mediadelivery.net")){const w=x.includes("?")?"&":"?";return`${x}${w}responsive=true`}const v=x.match(/loom\.com\/share\/([a-zA-Z0-9]+)/);if(v)return`https://www.loom.com/embed/${v[1]}`;const b=x.match(/video\.bunnycdn\.com\/play\/(\d+)\/([a-f0-9-]+)/);return b?`https://iframe.mediadelivery.net/embed/${b[1]}/${b[2]}?responsive=true`:x};if(r)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(yn,{className:"h-12 w-3/4 mx-auto"}),e.jsx(yn,{className:"h-64 w-full"}),e.jsx(yn,{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(x=>x.is_visible!==!1),f=m[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:[f!=null&&f.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:h(f.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"})}):f!=null&&f.image_url?e.jsx("div",{className:"rounded-xl overflow-hidden shadow-lg",children:e.jsx("img",{src:f.image_url,alt:f.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:f==null?void 0:f.icon}),e.jsx("h3",{className:"text-xl font-semibold text-gray-800",children:f==null?void 0:f.title}),e.jsx("p",{className:"text-gray-500 mt-1 text-sm",children:f==null?void 0:f.description})]}),(f==null?void 0:f.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:f.text}})]}),e.jsx("div",{className:"md:col-span-2 space-y-3",children:m.map((x,y)=>e.jsx("button",{onClick:()=>l(y),className:Pt("w-full text-left p-4 rounded-xl border transition-all",i===y?"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(y+1).padStart(2,"0"),"."]}),e.jsxs("div",{children:[e.jsx("span",{className:"mr-2",children:x.icon}),e.jsx("span",{className:"font-semibold text-gray-900",children:x.title}),e.jsx("p",{className:"text-xs text-gray-500 mt-0.5",children:x.description})]})]})},y))})]}),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?"}),(g=t.cta_url)!=null&&g.trim()?e.jsxs($,{size:"lg",onClick:u,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(kr,{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(J7t,{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 jFs(){const{user:s}=vs(),t=Sa(),{data:n}=Hw();return tt({queryKey:["open-houses",t,n==null?void 0:n.teamId,n==null?void 0:n.role],queryFn:async()=>{const{data:r,error:a}=await q.from("open_houses").select("*").eq("agent_id",t).order("event_date",{ascending:!1});if(a)throw a;let i=r||[];if((n==null?void 0:n.role)==="team_leader"&&n.teamId){const{data:l,error:o}=await q.rpc("get_team_open_houses",{_user_id:t});if(!o&&l){const c=[...new Set(l.map(h=>h.agent_id))],d={};if(c.length>0){const{data:h}=await q.from("profiles").select("id, name").in("id",c);h==null||h.forEach(m=>{m.name&&(d[m.id]=m.name)})}const u=l.map(h=>({...h,agent_name:d[h.agent_id]||void 0}));i=[...i,...u]}}return i.sort((l,o)=>o.event_date.localeCompare(l.event_date)),i},enabled:!!s&&!!t})}function aSr(s){const{user:t}=vs();return tt({queryKey:["open-house",s],queryFn:async()=>{const{data:n,error:r}=await q.from("open_houses").select("*").eq("id",s).single();if(r)throw r;return n},enabled:!!t&&!!s})}function eBt(s){const{user:t}=vs(),n=Vt();return j.useEffect(()=>{if(!s)return;const r=`visitors-${s}-${Math.random().toString(36).slice(2,10)}`,a=q.channel(r).on("postgres_changes",{event:"*",schema:"public",table:"open_house_visitors",filter:`open_house_id=eq.${s}`},()=>{n.invalidateQueries({queryKey:["open-house-visitors",s]}),n.invalidateQueries({queryKey:["open-houses"]})}).subscribe();return()=>{q.removeChannel(a)}},[s,n]),tt({queryKey:["open-house-visitors",s],queryFn:async()=>{const{data:r,error:a}=await q.from("open_house_visitors").select("*").eq("open_house_id",s).order("created_at",{ascending:!1});if(a)throw a;return r},enabled:!!t&&!!s})}function NFs(){const s=Vt(),t=Sa();return ft({mutationFn:async n=>{const{data:r,error:a}=await q.from("open_houses").insert({...n,agent_id:t}).select().single();if(a)throw a;return r},onSuccess:()=>{s.invalidateQueries({queryKey:["open-houses"]}),_a({title:"Open house created!"})},onError:n=>{_a({title:"Error",description:n.message,variant:"destructive"})}})}function tBt(){const s=Vt();return ft({mutationFn:async({id:t,...n})=>{const{error:r}=await q.from("open_houses").update(n).eq("id",t);if(r)throw r},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["open-houses"]}),s.invalidateQueries({queryKey:["open-house",n.id]})}})}function kFs(){const s=Vt();return ft({mutationFn:async t=>{const{error:n}=await q.from("open_houses").delete().eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["open-houses"]}),_a({title:"Open house deleted"})}})}function sBt(s){return tt({queryKey:["public-open-house",s],queryFn:async()=>{const{data:t,error:n}=await q.from("open_houses").select("*, profiles:agent_id(name, avatar_url, title, email, phone)").eq("slug",s).eq("is_active",!0).single();if(n)throw n;let r=null;if(t.agent_id){const{data:a}=await q.from("agent_cards").select("slug").eq("user_id",t.agent_id).eq("is_published",!0).maybeSingle();a&&(r=a.slug)}return{...t,agent_card_slug:r}},enabled:!!s})}function SFs(s){const{user:t}=vs();return tt({queryKey:["survey-questions",s],queryFn:async()=>{const{data:n,error:r}=await q.from("open_house_survey_questions").select("*").eq("open_house_id",s).order("sort_order");if(r)throw r;return n},enabled:!!t&&!!s})}function CFs(s){return tt({queryKey:["public-survey-questions",s],queryFn:async()=>{const{data:t,error:n}=await q.from("open_house_survey_questions").select("*").eq("open_house_id",s).eq("is_active",!0).order("sort_order");if(n)throw n;return t},enabled:!!s})}function AFs(){return ft({mutationFn:async s=>{const{error:t}=await q.from("open_house_survey_responses").insert(s);if(t)throw t}})}function EFs(s){const{user:t}=vs();return tt({queryKey:["survey-responses",s],queryFn:async()=>{const{data:n,error:r}=await q.from("open_house_survey_questions").select("*").eq("open_house_id",s).order("sort_order");if(r)throw r;const a=(n||[]).map(o=>o.id);if(a.length===0)return{questions:[],responses:[]};const{data:i,error:l}=await q.from("open_house_survey_responses").select("*").in("question_id",a).order("created_at",{ascending:!1});if(l)throw l;return{questions:n,responses:i||[]}},enabled:!!t&&!!s})}function TFs(){const s=Vt();return ft({mutationFn:async t=>{const{data:n,error:r}=await q.from("open_house_survey_questions").insert(t).select().single();if(r)throw r;return n},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["survey-questions",n.open_house_id]})}})}function MFs(){const s=Vt();return ft({mutationFn:async({id:t,open_house_id:n,...r})=>{const{error:a}=await q.from("open_house_survey_questions").update(r).eq("id",t);if(a)throw a},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["survey-questions",n.open_house_id]})}})}function PFs(){const s=Vt();return ft({mutationFn:async({id:t,open_house_id:n})=>{const{error:r}=await q.from("open_house_survey_questions").delete().eq("id",t);if(r)throw r},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["survey-questions",n.open_house_id]})}})}function IFs(){const s=Vt();return ft({mutationFn:async t=>{const{error:n}=await q.rpc("seed_default_survey_questions",{_open_house_id:t});if(n)throw n},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["survey-questions",n]})}})}function LFs(){return ft({mutationFn:async s=>{const t=crypto.randomUUID(),{error:n}=await q.from("open_house_visitors").insert({...s,id:t});if(n)throw n;return{id:t}}})}function RFs(){return ft({mutationFn:async({visitor_id:s,...t})=>{const{error:n}=await q.from("open_house_visitors").update(t).eq("id",s);if(n)throw n}})}function DFs(){return ft({mutationFn:async s=>{await q.rpc("increment_open_house_scan",{_slug:s})}})}async function nBt(s){const{data:t,error:n}=await q.from("open_house_rooms").select("*").eq("open_house_id",s).order("sort_order");if(n)throw n;const r=t||[];if(r.length===0)return[];const a=r.map(c=>c.id),{data:i,error:l}=await q.from("open_house_room_media").select("*").in("room_id",a).order("sort_order");if(l)throw l;const o={};return(i||[]).forEach(c=>{var u;const d=c;(o[u=d.room_id]||(o[u]=[])).push(d)}),r.map(c=>({...c,media:o[c.id]||[]}))}function FFs(s){const{user:t}=vs();return tt({queryKey:["open-house-rooms",s],queryFn:()=>nBt(s),enabled:!!t&&!!s})}function OFs(s){return tt({queryKey:["public-open-house-rooms",s],queryFn:()=>nBt(s),enabled:!!s})}function zFs(){const s=Vt();return ft({mutationFn:async t=>{const{data:n,error:r}=await q.from("open_house_rooms").insert(t).select().single();if(r)throw r;return n},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["open-house-rooms",n.open_house_id]})}})}function BFs(){const s=Vt();return ft({mutationFn:async({id:t,open_house_id:n,...r})=>{const{error:a}=await q.from("open_house_rooms").update(r).eq("id",t);if(a)throw a},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["open-house-rooms",n.open_house_id]})}})}function $Fs(){const s=Vt();return ft({mutationFn:async({id:t,open_house_id:n})=>{const{error:r}=await q.from("open_house_rooms").delete().eq("id",t);if(r)throw r},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["open-house-rooms",n.open_house_id]})}})}function UFs(){const s=Vt();return ft({mutationFn:async({open_house_id:t,...n})=>{const{data:r,error:a}=await q.from("open_house_room_media").insert(n).select().single();if(a)throw a;return r},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["open-house-rooms",n.open_house_id]})}})}function qFs(){const s=Vt();return ft({mutationFn:async({id:t,open_house_id:n})=>{const{error:r}=await q.from("open_house_room_media").delete().eq("id",t);if(r)throw r},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["open-house-rooms",n.open_house_id]})}})}function VFs(){const s=Vt();return ft({mutationFn:async({open_house_id:t,orderedIds:n})=>{for(let r=0;r{const r=["open-house-rooms",t];await s.cancelQueries({queryKey:r});const a=s.getQueryData(r);if(a){const i=new Map(a.map(o=>[o.id,o])),l=n.map((o,c)=>({...i.get(o),sort_order:c})).filter(Boolean);s.setQueryData(r,l)}return{prev:a,key:r}},onError:(t,n,r)=>{r!=null&&r.prev&&s.setQueryData(r.key,r.prev)},onSettled:(t,n,r)=>{s.invalidateQueries({queryKey:["open-house-rooms",r.open_house_id]})}})}function HFs(){const s=Vt();return ft({mutationFn:async({open_house_id:t,room_id:n,orderedIds:r})=>{for(let a=0;a{const a=["open-house-rooms",t];await s.cancelQueries({queryKey:a});const i=s.getQueryData(a);return i&&s.setQueryData(a,i.map(l=>{if(l.id!==n)return l;const o=new Map(l.media.map(c=>[c.id,c]));return{...l,media:r.map((c,d)=>{const u=o.get(c);return u?{...u,sort_order:d}:null}).filter(Boolean)}})),{prev:i,key:a}},onError:(t,n,r)=>{r!=null&&r.prev&&s.setQueryData(r.key,r.prev)},onSettled:(t,n,r)=>{s.invalidateQueries({queryKey:["open-house-rooms",r.open_house_id]})}})}function GFs(s){const{user:t}=vs();return tt({queryKey:["open-house-leads",s],queryFn:async()=>{const{data:n,error:r}=await q.from("open_house_leads").select("*").eq("open_house_id",s).order("created_at",{ascending:!1});if(r)throw r;return n||[]},enabled:!!t&&!!s})}function WFs(){const s=Vt();return ft({mutationFn:async({id:t,status:n,open_house_id:r})=>{const{error:a}=await q.from("open_house_leads").update({status:n}).eq("id",t);if(a)throw a;return{open_house_id:r}},onSuccess:t=>{s.invalidateQueries({queryKey:["open-house-leads",t.open_house_id]})}})}var KFs=Object.defineProperty,PL=(s,t)=>KFs(s,"name",{value:t,configurable:!0}),ost="Switch",[YFs,iSr]=tp(ost),[ZFs,lst]=YFs(ost);function rBt(s){const{__scopeSwitch:t,checked:n,children:r,defaultChecked:a,disabled:i,form:l,name:o,onCheckedChange:c,required:d,value:u="on",internal_do_not_use_render:h}=s,[m,f]=fy({prop:n,defaultProp:a??!1,onChange:c,caller:ost}),[g,x]=j.useState(null),[y,v]=j.useState(null),b=j.useRef(!1),[w,S]=j.useReducer(I=>I+1,0),C=g?!!l||!!g.closest("form"):!0,E={checked:m,setChecked:f,disabled:i,control:g,setControl:x,name:o,form:l,value:u,hasConsumerStoppedPropagationRef:b,userInteractionCount:w,onUserInteraction:S,required:d,defaultChecked:a,isFormControl:C,bubbleInput:y,setBubbleInput:v};return e.jsx(ZFs,{scope:t,...E,children:iBt(h)?h(E):r})}PL(rBt,"SwitchProvider");var XFs="SwitchTrigger",QFs=j.forwardRef(PL(function({__scopeSwitch:t,onClick:n,...r},a){const{control:i,form:l,value:o,disabled:c,checked:d,required:u,setControl:h,setChecked:m,hasConsumerStoppedPropagationRef:f,onUserInteraction:g,isFormControl:x,bubbleInput:y}=lst(XFs,t),v=Vo(a,h),b=j.useRef(d);return j.useEffect(()=>{const w=l?i==null?void 0:i.ownerDocument.getElementById(l):i==null?void 0:i.form;if(w instanceof HTMLFormElement){const S=PL(()=>m(b.current),"reset");return w.addEventListener("reset",S),()=>w.removeEventListener("reset",S)}},[i,l,m]),e.jsx(Ei.button,{type:"button",role:"switch","aria-checked":d,"aria-required":u,"data-state":cst(d),"data-disabled":c?"":void 0,disabled:c,value:o,...r,ref:v,onClick:Ra(n,w=>{g(),m(S=>!S),y&&x&&(f.current=w.isPropagationStopped(),f.current||w.stopPropagation())})})},"SwitchTrigger")),aBt=j.forwardRef(PL(function(t,n){const{__scopeSwitch:r,name:a,checked:i,defaultChecked:l,required:o,disabled:c,value:d,onCheckedChange:u,form:h,...m}=t;return e.jsx(rBt,{__scopeSwitch:r,checked:i,defaultChecked:l,disabled:c,required:o,onCheckedChange:u,name:a,form:h,value:d,internal_do_not_use_render:({isFormControl:f})=>e.jsxs(e.Fragment,{children:[e.jsx(QFs,{...m,ref:n,__scopeSwitch:r}),f&&e.jsx(sOs,{__scopeSwitch:r})]})})},"Switch")),JFs="SwitchThumb",eOs=j.forwardRef(PL(function(t,n){const{__scopeSwitch:r,...a}=t,i=lst(JFs,r);return e.jsx(Ei.span,{"data-state":cst(i.checked),"data-disabled":i.disabled?"":void 0,...a,ref:n})},"SwitchThumb")),tOs="SwitchBubbleInput",sOs=j.forwardRef(PL(function({__scopeSwitch:t,onClick:n,...r},a){const{control:i,hasConsumerStoppedPropagationRef:l,userInteractionCount:o,checked:c,defaultChecked:d,required:u,disabled:h,name:m,value:f,form:g,bubbleInput:x,setBubbleInput:y}=lst(tOs,t),v=Vo(a,y),b=XW(i),w=j.useRef(!1),S=j.useRef(c),C=j.useRef(o);j.useEffect(()=>{const I=x;if(!I)return;const P=window.HTMLInputElement.prototype,D=Object.getOwnPropertyDescriptor(P,"checked").set,O=o!==C.current;C.current=o;const U=S.current!==c;S.current=c;const W=!(O&&l.current);if(U&&D){w.current=!O;const V=new Event("click",{bubbles:W});D.call(I,c),I.dispatchEvent(V),w.current=!1}},[x,c,l,o]);const E=j.useRef(c);return e.jsx(Ei.input,{type:"checkbox","aria-hidden":!0,defaultChecked:d??E.current,required:u,disabled:h,name:m,value:f,form:g,...r,tabIndex:-1,ref:v,onClick:Ra(n,I=>{w.current&&I.stopPropagation()}),style:{...r.style,...b,position:"absolute",pointerEvents:"none",opacity:0,margin:0,transform:"translateX(-100%)"}})},"SwitchBubbleInput"));function iBt(s){return typeof s=="function"}PL(iBt,"isFunction");function cst(s){return s?"checked":"unchecked"}PL(cst,"getState");const Sn=j.forwardRef(({className:s,...t},n)=>e.jsx(aBt,{className:Pt("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:n,children:e.jsx(eOs,{className:Pt("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")})}));Sn.displayName=aBt.displayName;const nOs=["Excellent","Good","Neutral","Bad","Very Bad"],rOs=[5,4,3,2,1];function aOs({questions:s,visitorId:t,onComplete:n,onSkip:r}){const a=AFs(),[i,l]=j.useState({}),o=s.filter(m=>m.question_type==="rating"),c=s.filter(m=>m.question_type!=="rating"),d=(m,f)=>{l(g=>({...g,[m]:{rating_value:f}}))},u=(m,f)=>{l(g=>({...g,[m]:{text_value:f}}))},h=async()=>{const m=Object.entries(i).filter(([,f])=>f.rating_value!=null||f.text_value&&f.text_value.trim()).map(([f,g])=>{var x;return{visitor_id:t,question_id:f,rating_value:g.rating_value??null,text_value:((x=g.text_value)==null?void 0:x.trim())||null}});if(m.length>0)try{await a.mutateAsync(m)}catch{}n()};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:r,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"}),nOs.map(m=>e.jsx("div",{className:"w-12 text-center",children:e.jsx("span",{className:"text-[10px] text-slate-400 leading-tight block",children:m})},m))]}),o.map(m=>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:m.question_text}),rOs.map(f=>{var g;return e.jsx("div",{className:"w-12 flex justify-center",children:e.jsx("button",{type:"button",onClick:()=>d(m.id,f),className:`w-6 h-6 rounded-full border-2 transition-all ${((g=i[m.id])==null?void 0:g.rating_value)===f?"bg-slate-900 border-slate-900":"border-slate-300 hover:border-slate-500"}`})},f)})]},m.id))]}),c.map(m=>{var f;return e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium text-slate-700 block mb-1",children:m.question_text}),e.jsx(Rs,{value:((f=i[m.id])==null?void 0:f.text_value)||"",onChange:g=>u(m.id,g.target.value),placeholder:"Your thoughts...",className:"h-16 text-sm resize-none rounded-xl border-slate-200"})]},m.id)}),e.jsx($,{onClick:h,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(kt,{className:"h-5 w-5 animate-spin"}):"Submit Feedback"})]})}function dGe(s){return/iframe\.mediadelivery\.net\/embed\//.test(s)}function iOs({rooms:s}){var h;const[t,n]=j.useState(((h=s[0])==null?void 0:h.id)||""),[r,a]=j.useState(null),i=s.find(m=>m.id===t)||s[0],l=r!==null?i==null?void 0:i.media[r]:null,o=(i==null?void 0:i.media.length)??0,c=()=>a(null),d=()=>a(m=>m===null||o===0?m:(m-1+o)%o),u=()=>a(m=>m===null||o===0?m:(m+1)%o);return j.useEffect(()=>{if(r===null)return;const m=f=>{f.key==="Escape"?c():f.key==="ArrowLeft"?d():f.key==="ArrowRight"&&u()};return window.addEventListener("keydown",m),()=>window.removeEventListener("keydown",m)},[r,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(m=>e.jsxs("button",{onClick:()=>n(m.id),className:Pt("px-4 py-2 rounded-full text-sm font-medium whitespace-nowrap transition",t===m.id?"bg-white text-slate-900":"bg-white/5 text-white/70 hover:bg-white/10"),children:[m.name,e.jsx("span",{className:"ml-1.5 text-xs opacity-60",children:m.media.length})]},m.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((m,f)=>e.jsx("button",{onClick:()=>a(f),className:"relative aspect-[4/3] rounded-xl overflow-hidden bg-white/5 group",children:m.kind==="video"?e.jsxs(e.Fragment,{children:[dGe(m.url)?e.jsx("div",{className:"absolute inset-0 bg-slate-900"}):e.jsx("video",{src:m.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(ua,{className:"h-5 w-5 text-slate-900"})})})]}):e.jsx("img",{src:m.url,alt:i.name,className:"w-full h-full object-cover group-hover:scale-105 transition-transform duration-500"})},m.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," — ",(r??0)+1," / ",o]}),e.jsx("button",{onClick:m=>{m.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:m=>{m.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(Cd,{className:"h-6 w-6"})}),l.kind==="video"?dGe(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:m=>m.stopPropagation()},l.url):e.jsx("video",{src:l.url,controls:!0,autoPlay:!0,className:"max-w-full max-h-full rounded-lg",onClick:m=>m.stopPropagation()},l.url):e.jsx("img",{src:l.url,alt:"",className:"max-w-full max-h-full rounded-lg cursor-default",onClick:m=>m.stopPropagation()}),o>1&&e.jsx("button",{onClick:m=>{m.stopPropagation(),u()},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(Di,{className:"h-6 w-6"})})]})]}):null}function oOs({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,u)=>{t.push({type:"media",roomId:c.id,roomName:c.name,url:d.url,kind:d.kind,index:u,total:c.media.length})})});const n=j.useRef(null),[r,a]=j.useState(0);j.useEffect(()=>{const c=n.current;if(!c)return;let d=0;const u=()=>{cancelAnimationFrame(d),d=requestAnimationFrame(()=>{const h=Math.round(c.scrollLeft/c.clientWidth);a(h)})};return c.addEventListener("scroll",u,{passive:!0}),()=>{c.removeEventListener("scroll",u),cancelAnimationFrame(d)}},[]);const i=c=>{const d=n.current;d&&d.scrollTo({left:c*d.clientWidth,behavior:"smooth"})};if(!t.length)return null;const l=(o=t[r])==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(h=>h.roomId===c.id),u=l===c.id;return e.jsx("button",{onClick:()=>i(d),className:Pt("px-3.5 py-1.5 rounded-full text-xs font-medium whitespace-nowrap transition",u?"bg-white text-slate-900":"bg-white/10 text-white/80"),children:c.name},c.id)})})}),e.jsx("div",{ref:n,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"?dGe(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,r-1)),disabled:r===0,className:"flex items-center gap-1 text-sm text-white/70 disabled:opacity-30",children:[e.jsx(Cd,{className:"h-4 w-4"})," Prev"]}),e.jsxs("span",{className:"text-xs text-white/50",children:[r+1," / ",t.length]}),e.jsxs("button",{onClick:()=>i(Math.min(t.length-1,r+1)),disabled:r===t.length-1,className:"flex items-center gap-1 text-sm text-white/70 disabled:opacity-30",children:["Next ",e.jsx(Di,{className:"h-4 w-4"})]})]})]})}const x7e={question:{label:"Ask a Question",title:"Ask the agent",placeholder:"What would you like to know about the home?",icon:eo},showing:{label:"Schedule a Showing",title:"Request a private showing",placeholder:"Anything specific to focus on during the showing? (optional)",icon:Ta},disclosure:{label:"Request Disclosures",title:"Request seller disclosures",placeholder:"Any specific documents? (optional)",icon:Jr},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:ru}},lOs=["Seller's Property Disclosure","HOA Documents & Bylaws","Inspection Reports","Title / CC&Rs","Utility & Tax History"];function cOs(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 dOs({openHouse:s,visitorId:t,visitorName:n,visitorEmail:r,visitorPhone:a,previewMode:i=!1}){var Fe;const l=s.profiles,o=((Fe=l==null?void 0:l.name)==null?void 0:Fe.split(" ").map(ke=>ke[0]).join("").slice(0,2))||"?",c=s.brand_color_override||null,[d,u]=j.useState(null),[h,m]=j.useState(""),[f,g]=j.useState(r||""),[x,y]=j.useState(a||""),[v,b]=j.useState(!1),[w,S]=j.useState(null),[C,E]=j.useState(""),[I,P]=j.useState(""),[R,D]=j.useState(""),[O,U]=j.useState([]),[W,V]=j.useState(""),[G,Y]=j.useState(""),[X,ae]=j.useState(""),[ie,ne]=j.useState(""),te=cOs(s.price),J=s.tour_mode==="rooms",{data:ce=[]}=OFs(J?s.id:void 0),_e=[s.enable_question&&"question",s.enable_showing&&"showing",s.enable_disclosures&&"disclosure",s.enable_offer&&"offer"].filter(Boolean),he=ke=>{u(ke),m(""),E(""),P(""),D(""),U([]),V(""),Y(""),ae(""),ne("")},ue=()=>{u(null)},ve=ke=>{U(Ve=>Ve.includes(ke)?Ve.filter(je=>je!==ke):[...Ve,ke])},Ee=ke=>ke==="showing"?{preferred_date:C||null,preferred_time:I||null,alternate_date:R||null}:ke==="disclosure"?{requested_documents:O}:ke==="offer"?{offer_amount:W||null,financing:G||null,timeline:X||null,pre_approved:ie||null}:{},Se=d?d==="showing"?!!C:d==="question"?h.trim().length>0:!0:!1,Le=async()=>{if(d){if(i){_a({title:"Preview mode",description:"Lead not sent — this is just a preview."}),S(d),setTimeout(()=>{u(null),S(null)},1500);return}b(!0);try{const ke=Ee(d),{error:Ve}=await q.from("open_house_leads").insert({open_house_id:s.id,visitor_id:t,action_type:d,payload:{message:h.trim()||null,email:f.trim()||null,phone:x.trim()||null,visitor_name:n,...ke}});if(Ve)throw Ve;q.functions.invoke("send-virtual-open-house-lead",{body:{open_house_id:s.id,visitor_id:t,action_type:d,message:h.trim()||null,visitor_name:n,visitor_email:f.trim()||null,visitor_phone:x.trim()||null,extras:ke}}).catch(()=>{}),S(d),_a({title:"Sent!",description:"The agent has been notified."}),setTimeout(()=>{ue(),S(null)},1400)}catch(ke){_a({title:"Something went wrong",description:ke.message,variant:"destructive"})}finally{b(!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(ci,{className:"h-3.5 w-3.5"}),s.city,s.state?`, ${s.state}`:""," ",s.zip]}),te&&e.jsx("p",{className:"text-3xl font-bold text-white mt-3",children:te}),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(l2,{className:"h-4 w-4"}),s.beds," bd"]}),s.baths!=null&&e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(T0,{className:"h-4 w-4"}),s.baths," ba"]}),s.sqft!=null&&e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(C_,{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(Oa,{className:"h-12 w-12 ring-2 ring-white/20",style:c?{boxShadow:`0 0 0 2px ${c}`}:void 0,children:[e.jsx(Li,{src:l.avatar_url||"",alt:l.name||""}),e.jsx(za,{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(Da,{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(mn,{className:"h-4 w-4"})})]})]}),J&&ce.length>0&&e.jsxs("div",{className:"mt-8",children:[e.jsx(iOs,{rooms:ce}),e.jsx(oOs,{rooms:ce})]}),_e.length>0&&e.jsx("div",{className:"mt-5 grid grid-cols-1 sm:grid-cols-2 gap-3",children:_e.map(ke=>{const Ve=x7e[ke],je=Ve.icon;return e.jsxs("button",{onClick:()=>he(ke),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(je,{className:"h-5 w-5"})}),e.jsx("span",{className:"font-medium text-sm",children:Ve.label})]},ke)})}),e.jsx("p",{className:"text-center text-white/30 text-xs mt-8",children:"Powered by LevelUp Virtual Open House"})]}),e.jsx(Wy,{open:!!d,onOpenChange:ke=>!ke&&ue(),children:e.jsx(py,{side:"bottom",className:"rounded-t-2xl max-h-[92vh] overflow-y-auto",children:d&&e.jsxs(e.Fragment,{children:[e.jsxs(D0,{className:"text-left",children:[e.jsx(F0,{children:x7e[d].title}),e.jsxs($B,{children:[(l==null?void 0:l.name)||"The agent"," will be notified by email."]})]}),w===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(qr,{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(ee,{className:"text-xs",children:"Email"}),e.jsx(pe,{type:"email",value:f,onChange:ke=>g(ke.target.value),placeholder:"you@example.com",className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs",children:"Phone"}),e.jsx(pe,{type:"tel",value:x,onChange:ke=>y(ke.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(ee,{className:"text-xs",children:"Preferred date *"}),e.jsx(pe,{type:"date",value:C,onChange:ke=>E(ke.target.value),className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs",children:"Preferred time"}),e.jsx(pe,{type:"time",value:I,onChange:ke=>P(ke.target.value),className:"mt-1"})]})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs",children:"Alternate date (optional)"}),e.jsx(pe,{type:"date",value:R,onChange:ke=>D(ke.target.value),className:"mt-1"})]})]}),d==="disclosure"&&e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs",children:"Which documents? (select all that apply)"}),e.jsx("div",{className:"mt-2 space-y-2",children:lOs.map(ke=>e.jsxs("label",{className:"flex items-center gap-2 text-sm cursor-pointer",children:[e.jsx(ai,{checked:O.includes(ke),onCheckedChange:()=>ve(ke)}),e.jsx("span",{children:ke})]},ke))})]}),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(ee,{className:"text-xs",children:"Estimated offer"}),e.jsx(pe,{value:W,onChange:ke=>V(ke.target.value),placeholder:"$",className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs",children:"Financing"}),e.jsxs(ms,{value:G,onValueChange:Y,children:[e.jsx(us,{className:"mt-1",children:e.jsx(fs,{placeholder:"Select..."})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"Cash",children:"Cash"}),e.jsx(Ge,{value:"Conventional",children:"Conventional"}),e.jsx(Ge,{value:"FHA",children:"FHA"}),e.jsx(Ge,{value:"VA",children:"VA"}),e.jsx(Ge,{value:"Other",children:"Other"})]})]})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs",children:"Timeline"}),e.jsxs(ms,{value:X,onValueChange:ae,children:[e.jsx(us,{className:"mt-1",children:e.jsx(fs,{placeholder:"Select..."})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"ASAP",children:"ASAP"}),e.jsx(Ge,{value:"30 days",children:"30 days"}),e.jsx(Ge,{value:"60 days",children:"60 days"}),e.jsx(Ge,{value:"90+ days",children:"90+ days"})]})]})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs",children:"Pre-approved?"}),e.jsxs(ms,{value:ie,onValueChange:ne,children:[e.jsx(us,{className:"mt-1",children:e.jsx(fs,{placeholder:"Select..."})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"Yes",children:"Yes"}),e.jsx(Ge,{value:"No",children:"No"}),e.jsx(Ge,{value:"In progress",children:"In progress"})]})]})]})]})]}),e.jsxs("div",{children:[e.jsxs(ee,{className:"text-xs",children:["Message",d==="question"?" *":" (optional)"]}),e.jsx(Rs,{value:h,onChange:ke=>m(ke.target.value),placeholder:x7e[d].placeholder,rows:4,className:"mt-1"})]}),e.jsx($,{onClick:Le,disabled:v||!Se,className:"w-full h-12 text-white hover:opacity-90",style:c?{backgroundColor:c}:void 0,children:v?e.jsx(kt,{className:"h-4 w-4 animate-spin"}):"Send to agent"})]})]})})})]})}const uOs=H2({first_name:vl().trim().min(1,"First name is required").max(50),last_name:vl().trim().max(50).optional(),email:vl().trim().email("Please enter a valid email").max(255).optional().or(yx("")),phone:vl().trim().max(20).optional().or(yx(""))}),hOs=[{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 oBt({slug:s}={}){var ze;const t=Wi(),n=s||t.slug,[r]=gc(),a=r.get("kiosk")==="1"||r.get("mode")==="kiosk",i=8,{data:l,isLoading:o,error:c}=sBt(n),d=LFs(),u=RFs(),h=DFs(),m=j.useRef(!1),[f,g]=j.useState("welcome"),[x,y]=j.useState(null),[v,b]=j.useState({first_name:"",last_name:"",email:"",phone:"",visitor_address:""}),[w,S]=j.useState(""),[C,E]=j.useState(!1),[I,P]=j.useState(!1),[R,D]=j.useState(""),[O,U]=j.useState(""),[W,V]=j.useState(i),G=j.useCallback(()=>{y(null),b({first_name:"",last_name:"",email:"",phone:"",visitor_address:""}),S(""),E(!1),P(!1),D(""),U(""),V(i),g(a?"info":"welcome")},[a]),Y=j.useCallback(($e,ct)=>{l!=null&&l.id&&q.functions.invoke("guestbook-lead-notify",{body:{open_house_id:l.id,visitor_id:$e,first_name:ct.first_name??v.first_name,last_name:ct.last_name??v.last_name,email:ct.email??v.email,phone:ct.phone??v.phone,visitor_intent:ct.visitor_intent??w,message:ct.message,wants_market_updates:ct.wants_market_updates??C,has_agent:ct.has_agent??I,working_with_agent_name:ct.working_with_agent_name??R,visitor_address:ct.visitor_address??v.visitor_address}}).catch(Xe=>console.error("Guest book lead notify failed:",Xe))},[l==null?void 0:l.id,v,w,C,I,R]);j.useEffect(()=>{if(!a||f!=="done")return;V(i);const $e=setInterval(()=>{V(ct=>ct<=1?(clearInterval($e),G(),0):ct-1)},1e3);return()=>clearInterval($e)},[a,f,G]),j.useEffect(()=>{if(!a)return;g(ct=>ct==="welcome"?"info":ct);let $e=null;return(async()=>{var ct,Xe;try{$e=await((Xe=(ct=navigator.wakeLock)==null?void 0:ct.request)==null?void 0:Xe.call(ct,"screen"))}catch{}})(),()=>{var ct;try{(ct=$e==null?void 0:$e.release)==null||ct.call($e)}catch{}}},[a]);const X=j.useCallback(()=>{var ct;const $e=document.documentElement;document.fullscreenElement||(ct=$e.requestFullscreen||$e.webkitRequestFullscreen)==null||ct.call($e).catch(()=>{})},[]),{data:ae,isLoading:ie}=CFs(l==null?void 0:l.id),ne=!!(l!=null&&l.enable_survey),te=(l==null?void 0:l.ask_visitor_intent)!==!1,J=(l==null?void 0:l.ask_visitor_address)===!0;j.useEffect(()=>{if(!n||!(l!=null&&l.id)||m.current)return;const $e=`oh_scan_${l.id}`;if(sessionStorage.getItem($e)){m.current=!0;return}m.current=!0,sessionStorage.setItem($e,"1"),h.mutate(n)},[n,l==null?void 0:l.id]),j.useEffect(()=>{f==="pending_survey"&&(ie||g(ne&&((ae==null?void 0:ae.length)??0)>0?"survey":"done"))},[f,ie,ne,ae]);const ce=$e=>{if(!$e)return"";const[ct,Xe]=$e.split(":"),it=parseInt(ct),at=it>=12?"PM":"AM";return`${it>12?it-12:it||12}:${Xe} ${at}`},_e=async()=>{U("");const $e=uOs.safeParse(v);if(!$e.success){U($e.error.issues[0].message);return}if(!v.email&&!v.phone){U("Please provide either an email or phone number");return}const ct=(l==null?void 0:l.kind)==="virtual";let Xe=null;if(!x&&(l!=null&&l.id))try{const it=await d.mutateAsync({open_house_id:l.id,first_name:v.first_name.trim(),last_name:v.last_name.trim()||void 0,email:v.email.trim()||void 0,phone:v.phone.trim()||void 0,visitor_address:J&&v.visitor_address.trim()?v.visitor_address.trim():void 0,wants_market_updates:C,has_agent:I,working_with_agent_name:I&&R.trim()?R.trim():void 0,partial_signin:ct?!1:te});Xe=it.id,y(it.id)}catch{if(ct){U("We could not start the virtual tour. Please try again.");return}}if(ct){te?g("intent"):(Xe&&Y(Xe,{}),g("done"));return}if(!te){Xe&&Y(Xe,{}),ne?!ie&&ae&&ae.length>0?g("survey"):g("pending_survey"):g("done");return}g("intent")},he=async $e=>{S($e);try{let ct=x;if(ct?await u.mutateAsync({visitor_id:ct,visitor_intent:$e,wants_market_updates:C,has_agent:I,working_with_agent_name:I&&R.trim()?R.trim():null,partial_signin:!1}):(ct=(await d.mutateAsync({open_house_id:l.id,first_name:v.first_name.trim(),last_name:v.last_name.trim()||void 0,email:v.email.trim()||void 0,phone:v.phone.trim()||void 0,visitor_address:J&&v.visitor_address.trim()?v.visitor_address.trim():void 0,visitor_intent:$e,wants_market_updates:C,has_agent:I,working_with_agent_name:I&&R.trim()?R.trim():void 0,partial_signin:!1})).id,y(ct)),ct&&Y(ct,{visitor_intent:$e,wants_market_updates:C,has_agent:I,working_with_agent_name:I&&R.trim()?R.trim():null}),(l==null?void 0:l.kind)==="virtual"){g("done");return}ne?!ie&&ae&&ae.length>0?g("survey"):g("pending_survey"):g("done")}catch{U("Something went wrong. Please try again.")}};if(o)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(c||!l)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(va,{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 ue=l.profiles,ve=((ze=ue==null?void 0:ue.name)==null?void 0:ze.split(" ").map($e=>$e[0]).join("").slice(0,2))||"?",Ee=l.event_type==="community",Se=l.kind==="virtual",Le=typeof window<"u"&&new URLSearchParams(window.location.search).get("preview")==="1";if(Se&&(Le||f==="done"))return!Le&&!x?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(Ml,{children:[e.jsxs("title",{children:["Virtual Tour | ",l.property_address]}),e.jsx("meta",{name:"description",content:`Take a virtual tour of ${l.property_address}`}),e.jsx("meta",{name:"robots",content:"noindex, nofollow"})]}),Le&&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(dOs,{openHouse:l,visitorId:Le?"preview":x,visitorName:Le?"Preview Visitor":`${v.first_name} ${v.last_name}`.trim(),visitorEmail:Le?"":v.email,visitorPhone:Le?"":v.phone,previewMode:Le})]});const ke=`${Se?"Virtual Open House":Ee?"Community Event":"Open House"} — ${l.property_address}`,je=[[l.city,l.state].filter(Boolean).join(", "),l.event_date?en(new Date(l.event_date+"T00:00:00"),"EEE, MMM d"):null,ue!=null&&ue.name?`Hosted by ${ue.name}`:null].filter(Boolean).join(" · "),Ae=l.photo_url||"",Ce=Ae&&Ae.includes("/storage/v1/object/public/")?Ae.replace("/object/public/","/render/image/public/")+"?width=1200&height=630&resize=cover":Ae||"https://dashboard.relevelup.com/og-image.png",qe=typeof window<"u"?window.location.href:`https://guestbook.relevelup.com/${n}`;return e.jsxs(e.Fragment,{children:[e.jsxs(Ml,{children:[e.jsx("title",{children:ke}),e.jsx("meta",{name:"description",content:je||`Sign in to ${l.property_address}`}),e.jsx("meta",{property:"og:type",content:"website"}),e.jsx("meta",{property:"og:title",content:ke}),e.jsx("meta",{property:"og:description",content:je||`Sign in to ${l.property_address}`}),e.jsx("meta",{property:"og:image",content:Ce}),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:qe}),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:ke}),e.jsx("meta",{name:"twitter:description",content:je||`Sign in to ${l.property_address}`}),e.jsx("meta",{name:"twitter:image",content:Ce}),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(Oa,{className:"h-16 w-16 mx-auto mb-3 ring-2 ring-white/20",children:[e.jsx(Li,{src:(ue==null?void 0:ue.avatar_url)||"",alt:(ue==null?void 0:ue.name)||""}),e.jsx(za,{className:"bg-white/10 text-white text-lg",children:ve})]}),e.jsx("p",{className:"text-white/60 text-sm",children:ue==null?void 0:ue.name}),(ue==null?void 0:ue.title)&&e.jsx("p",{className:"text-white/40 text-xs",children:ue.title})]}),e.jsxs("div",{className:"bg-white rounded-2xl shadow-2xl overflow-hidden",children:[l.photo_url&&e.jsxs("div",{className:"relative h-44 sm:h-52 overflow-hidden",children:[e.jsx("img",{src:l.photo_url,alt:l.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:l.property_address}),e.jsxs("div",{className:"flex flex-wrap gap-3 mt-1.5 text-white/70 text-xs",children:[l.city&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(ci,{className:"h-3 w-3"}),l.city,l.state?`, ${l.state}`:""," ",l.zip]}),!Se&&e.jsxs(e.Fragment,{children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Ta,{className:"h-3 w-3"}),en(new Date(l.event_date+"T00:00:00"),"MMM d, yyyy")]}),l.start_time&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(da,{className:"h-3 w-3"}),ce(l.start_time),l.end_time?` – ${ce(l.end_time)}`:""]})]})]})]})]}),!l.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:Ee?e.jsx(ji,{className:"h-5 w-5 text-white"}):e.jsx(va,{className:"h-5 w-5 text-white"})}),e.jsxs("div",{children:[e.jsx("h1",{className:"text-white font-bold text-lg leading-tight",children:l.property_address}),e.jsxs("div",{className:"flex flex-wrap gap-3 mt-2 text-white/60 text-xs",children:[l.city&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(ci,{className:"h-3 w-3"}),l.city,l.state?`, ${l.state}`:""," ",l.zip]}),!Se&&e.jsxs(e.Fragment,{children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Ta,{className:"h-3 w-3"}),en(new Date(l.event_date+"T00:00:00"),"MMM d, yyyy")]}),l.start_time&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(da,{className:"h-3 w-3"}),ce(l.start_time),l.end_time?` – ${ce(l.end_time)}`:""]})]})]})]})]})}),e.jsxs("div",{className:"p-6",children:[f==="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:l.agent_greeting||"Please sign in below."})]}),e.jsxs($,{onClick:()=>g("info"),className:"w-full h-14 text-base bg-slate-900 hover:bg-slate-800 text-white rounded-xl",children:["Sign In ",e.jsx(ei,{className:"h-5 w-5 ml-2"})]}),e.jsx("p",{className:"text-xs text-slate-400",children:"Quick & easy — takes 30 seconds"})]}),f==="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:()=>g("welcome"),className:"text-slate-400 hover:text-slate-600",children:e.jsx(qa,{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(ee,{className:"text-slate-600 text-xs",children:"First Name *"}),e.jsx(pe,{value:v.first_name,onChange:$e=>b(ct=>({...ct,first_name:$e.target.value})),placeholder:"First",className:"mt-1 h-12 rounded-xl border-slate-200 text-base",autoFocus:!0})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-slate-600 text-xs",children:"Last Name"}),e.jsx(pe,{value:v.last_name,onChange:$e=>b(ct=>({...ct,last_name:$e.target.value})),placeholder:"Last",className:"mt-1 h-12 rounded-xl border-slate-200 text-base"})]})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-slate-600 text-xs",children:"Email"}),e.jsx(pe,{type:"email",value:v.email,onChange:$e=>b(ct=>({...ct,email:$e.target.value})),placeholder:"your@email.com",className:"mt-1 h-12 rounded-xl border-slate-200 text-base"})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-slate-600 text-xs",children:"Phone"}),e.jsx(pe,{type:"tel",value:v.phone,onChange:$e=>b(ct=>({...ct,phone:$e.target.value})),placeholder:"(555) 123-4567",className:"mt-1 h-12 rounded-xl border-slate-200 text-base"})]}),J&&e.jsxs("div",{children:[e.jsx(ee,{className:"text-slate-600 text-xs",children:"Your Home Address"}),e.jsx(pe,{value:v.visitor_address,onChange:$e=>b(ct=>({...ct,visitor_address:$e.target.value})),placeholder:"Street, City, State ZIP",className:"mt-1 h-12 rounded-xl border-slate-200 text-base",autoComplete:"street-address"})]}),e.jsxs("label",{className:"flex items-center gap-2 cursor-pointer pt-1",children:[e.jsx("input",{type:"checkbox",checked:C,onChange:$e=>E($e.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:I?"Yes":"No"}),e.jsx(Sn,{checked:I,onCheckedChange:P})]})]}),I&&e.jsx(pe,{value:R,onChange:$e=>D($e.target.value),placeholder:"Agent's name",className:"mt-1 h-10 rounded-xl border-slate-200 text-sm"})]}),O&&e.jsx("p",{className:"text-destructive text-sm",children:O}),e.jsxs($,{onClick:_e,className:"w-full h-14 text-base bg-slate-900 hover:bg-slate-800 text-white rounded-xl",children:["Continue ",e.jsx(ei,{className:"h-5 w-5 ml-2"})]})]}),f==="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:()=>g("info"),className:"text-slate-400 hover:text-slate-600",children:e.jsx(qa,{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:hOs.map($e=>e.jsxs("button",{onClick:()=>he($e.value),disabled:d.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:$e.emoji}),e.jsx("span",{className:"text-sm font-medium text-slate-700 group-hover:text-slate-900",children:$e.label})]},$e.value))}),O&&e.jsx("p",{className:"text-destructive text-sm text-center",children:O})]}),f==="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..."})]}),f==="survey"&&x&&ae&&e.jsx(aOs,{questions:ae,visitorId:x,onComplete:()=>g("done"),onSkip:()=>g("done")}),f==="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(qr,{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, ",v.first_name,". ",Ee?"Enjoy the event!":"Enjoy the open house!"]})]}),(l==null?void 0:l.disclosure_pdf_url)&&e.jsxs("a",{href:`https://docs.google.com/gview?url=${encodeURIComponent(l.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(Jr,{className:"h-4 w-4"}),"View Seller's Disclosures"]}),(ue==null?void 0:ue.name)&&e.jsxs("p",{className:"text-sm text-slate-400",children:["Your host today: ",e.jsx("strong",{className:"text-slate-600",children:ue.name})]}),a&&e.jsxs("div",{className:"pt-4 space-y-3",children:[e.jsx($,{onClick:G,className:"w-full h-14 text-base font-semibold rounded-xl",children:"Sign in next visitor"}),e.jsxs("p",{className:"text-xs text-slate-400",children:["Ready for the next visitor in ",W,"s…"]})]})]})]})]}),e.jsx("p",{className:"text-center text-white/30 text-xs mt-6",children:"Powered by LevelUp Guest Book"}),a&&e.jsxs("div",{className:"fixed top-3 right-3 flex items-center gap-2 z-50",children:[e.jsxs("span",{className:"inline-flex items-center gap-1.5 rounded-full bg-white/10 backdrop-blur-sm text-white/80 text-[11px] px-2.5 py-1 border border-white/10",children:[e.jsx(dV,{className:"h-3 w-3"})," Tablet Mode"]}),e.jsx("button",{onClick:X,className:"inline-flex items-center gap-1 rounded-full bg-white/10 backdrop-blur-sm text-white/80 text-[11px] px-2.5 py-1 border border-white/10 hover:bg-white/20",title:"Enter full screen",children:e.jsx(BJ,{className:"h-3 w-3"})})]})]})})]})}function mOs(s){return tt({queryKey:["open-house-rsvps",s],queryFn:async()=>{const{data:t,error:n}=await q.from("open_house_rsvps").select("*").eq("open_house_id",s).order("created_at",{ascending:!1});if(n)throw n;return t||[]},enabled:!!s})}function fOs(){const s=Vt();return ft({mutationFn:async t=>{const{error:n}=await q.from("open_house_rsvps").insert({open_house_id:t.open_house_id,first_name:t.first_name,last_name:t.last_name||null,email:t.email||null,phone:t.phone||null,has_agent:t.has_agent??!1,working_with_agent_name:t.working_with_agent_name||null,message:t.message||null});if(n)throw n;return null},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["open-house-rsvps",n.open_house_id]})}})}function pOs(s){const t=Vt();return ft({mutationFn:async n=>{const{error:r}=await q.from("open_house_rsvps").delete().eq("id",n);if(r)throw r},onSuccess:()=>t.invalidateQueries({queryKey:["open-house-rsvps",s]})})}function gOs(s){const t=Vt();return ft({mutationFn:async({id:n,checkedIn:r})=>{const{error:a}=await q.from("open_house_rsvps").update({checked_in_at:r?new Date().toISOString():null}).eq("id",n);if(a)throw a},onSuccess:()=>t.invalidateQueries({queryKey:["open-house-rsvps",s]})})}const xOs=H2({first_name:vl().trim().min(1,"First name is required").max(50),last_name:vl().trim().max(50).optional(),email:vl().trim().email("Please enter a valid email").max(255),phone:vl().trim().max(20).optional().or(yx("")),message:vl().trim().max(500).optional().or(yx(""))}),y7e=s=>{if(!s)return"";const[t,n]=s.split(":"),r=parseInt(t,10),a=r>=12?"PM":"AM";return`${r>12?r-12:r||12}:${n} ${a}`},yOs=s=>{if(!s)return null;const[t,n,r]=s.split(/[-/T]/).map(Number);return!t||!n||!r?null:new Date(t,n-1,r)};function lBt({slug:s}={}){const t=Wi(),n=s||t.slug,{data:r,isLoading:a,error:i}=sBt(n),l=fOs(),[o,c]=j.useState({first_name:"",last_name:"",email:"",phone:"",message:""}),[d,u]=j.useState(!1),[h,m]=j.useState(""),[f,g]=j.useState(""),[x,y]=j.useState(!1),v=j.useMemo(()=>yOs(r==null?void 0:r.event_date),[r==null?void 0:r.event_date]),b=j.useMemo(()=>{const P=r==null?void 0:r.photo_url;return P?P.includes("/storage/v1/object/public/")?P.replace("/object/public/","/render/image/public/")+"?width=1600&quality=80":P:""},[r]),w=r==null?void 0:r.profiles,S=[r==null?void 0:r.city,r==null?void 0:r.state].filter(Boolean).join(", "),C=async()=>{g("");const P=xOs.safeParse(o);if(!P.success){g(P.error.issues[0].message);return}try{await l.mutateAsync({open_house_id:r.id,first_name:o.first_name.trim(),last_name:o.last_name.trim()||void 0,email:o.email.trim(),phone:o.phone.trim()||void 0,has_agent:d,working_with_agent_name:d&&h.trim()?h.trim():void 0,message:o.message.trim()||void 0}),y(!0)}catch(R){g((R==null?void 0:R.message)||"Something went wrong. Please try again.")}},E=j.useMemo(()=>{if(!r||!v)return"";const P=V=>String(V).padStart(2,"0"),R=`${v.getFullYear()}${P(v.getMonth()+1)}${P(v.getDate())}`,D=(r.start_time||"12:00").slice(0,5).replace(":","")+"00",O=(r.end_time||"14:00").slice(0,5).replace(":","")+"00",U=encodeURIComponent(`Open House — ${r.property_address}`),W=encodeURIComponent([r.property_address,S,r.zip].filter(Boolean).join(", "));return`https://calendar.google.com/calendar/render?action=TEMPLATE&text=${U}&dates=${R}T${D}/${R}T${O}&location=${W}`},[r,v,S]);if(a)return e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-[#0f1c22]",children:e.jsx("div",{className:"h-10 w-10 rounded-full border-2 border-white/20 border-t-white animate-spin"})});if(i||!r)return e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-[#0f1c22] p-6 text-center",children:e.jsxs("div",{className:"text-white/80",children:[e.jsx(va,{className:"h-8 w-8 mx-auto mb-3 opacity-50"}),e.jsx("h1",{className:"text-xl font-semibold mb-1",children:"Open house not found"}),e.jsx("p",{className:"text-sm text-white/50",children:"This RSVP link may have expired."})]})});const I=`https://www.google.com/maps/search/?api=1&query=${encodeURIComponent([r.property_address,S,r.zip].filter(Boolean).join(", "))}`;return e.jsxs("div",{className:"min-h-screen bg-[#f6f2ee]",children:[e.jsxs(Ml,{children:[e.jsx("title",{children:`RSVP — Open House at ${r.property_address}`}),e.jsx("meta",{name:"description",content:`Reserve your spot for the open house at ${r.property_address}${v?` on ${en(v,"EEEE, MMMM d")}`:""}.`})]}),e.jsxs("header",{className:"relative",children:[e.jsxs("div",{className:"relative h-[46vh] min-h-[320px] w-full overflow-hidden bg-[#1b3a4b]",children:[b&&e.jsx("img",{src:b,alt:r.property_address,className:"absolute inset-0 h-full w-full object-cover"}),e.jsx("div",{className:"absolute inset-0 bg-gradient-to-t from-[#0f1c22] via-[#0f1c22]/55 to-[#0f1c22]/25"}),e.jsx("div",{className:"absolute inset-x-0 bottom-0 p-6 sm:p-10",children:e.jsxs("div",{className:"mx-auto max-w-3xl",children:[e.jsx("p",{className:"text-[11px] uppercase tracking-[0.35em] text-[#d4b978] mb-3",children:"Open House"}),e.jsx("h1",{className:"font-serif text-3xl sm:text-4xl font-bold text-white leading-tight",children:r.property_address}),S&&e.jsxs("p",{className:"mt-1 text-white/70",children:[S," ",r.zip||""]}),e.jsxs("div",{className:"mt-4 flex flex-wrap gap-x-5 gap-y-2 text-sm text-white/85",children:[v&&e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(Ta,{className:"h-4 w-4 text-[#d4b978]"}),en(v,"EEEE, MMMM d, yyyy")]}),r.start_time&&e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(da,{className:"h-4 w-4 text-[#d4b978]"}),y7e(r.start_time),r.end_time?` – ${y7e(r.end_time)}`:""]})]})]})})]}),e.jsx("div",{className:"h-1 bg-gradient-to-r from-[#b8975a] via-[#d4b978] to-[#b8975a]"})]}),e.jsxs("main",{className:"mx-auto max-w-3xl px-5 py-8 sm:py-12 space-y-8",children:[(r.price||r.beds||r.baths||r.sqft)&&e.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-3",children:[r.price?e.jsx(Bce,{icon:e.jsx(va,{className:"h-4 w-4"}),label:"Price",value:`$${Number(r.price).toLocaleString()}`}):null,r.beds?e.jsx(Bce,{icon:e.jsx(T4,{className:"h-4 w-4"}),label:"Beds",value:String(r.beds)}):null,r.baths?e.jsx(Bce,{icon:e.jsx(T0,{className:"h-4 w-4"}),label:"Baths",value:String(r.baths)}):null,r.sqft?e.jsx(Bce,{icon:e.jsx(R4,{className:"h-4 w-4"}),label:"Sq Ft",value:Number(r.sqft).toLocaleString()}):null]}),r.property_description&&e.jsx("p",{className:"text-[15px] leading-relaxed text-[#3a4a51] whitespace-pre-line",children:r.property_description}),e.jsx("section",{id:"rsvp",className:"rounded-2xl bg-white shadow-[0_10px_40px_rgba(15,28,34,0.08)] overflow-hidden",children:x?e.jsxs("div",{className:"p-8 sm:p-12 text-center",children:[e.jsx("div",{className:"mx-auto mb-4 flex h-14 w-14 items-center justify-center rounded-full bg-emerald-500/10",children:e.jsx(qr,{className:"h-7 w-7 text-emerald-600"})}),e.jsx("h2",{className:"font-serif text-2xl font-semibold text-[#1b3a4b]",children:"You're on the list!"}),e.jsxs("p",{className:"mt-2 text-[#5b6b72]",children:["We'll see you ",v?en(v,"EEEE, MMMM d"):"soon",r.start_time?` at ${y7e(r.start_time)}`:"",". A confirmation reminder will land in your inbox before the event."]}),e.jsxs("div",{className:"mt-6 flex flex-wrap justify-center gap-3",children:[E&&e.jsx($,{asChild:!0,className:"bg-[#1b3a4b] hover:bg-[#25505f]",children:e.jsxs("a",{href:E,target:"_blank",rel:"noreferrer",children:[e.jsx(jv,{className:"mr-2 h-4 w-4"}),"Add to calendar"]})}),e.jsx($,{asChild:!0,variant:"outline",children:e.jsxs("a",{href:I,target:"_blank",rel:"noreferrer",children:[e.jsx(ci,{className:"mr-2 h-4 w-4"}),"Get directions"]})})]})]}):e.jsxs("div",{className:"p-6 sm:p-8",children:[e.jsx("h2",{className:"font-serif text-2xl font-semibold text-[#1b3a4b]",children:"Reserve your spot"}),e.jsx("p",{className:"mt-1 text-sm text-[#5b6b72]",children:"Let us know you're coming and we'll save you a spot and send a reminder."}),e.jsxs("div",{className:"mt-6 grid gap-4 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{htmlFor:"rsvp-first",children:"First name *"}),e.jsx(pe,{id:"rsvp-first",value:o.first_name,onChange:P=>c(R=>({...R,first_name:P.target.value})),className:"h-11"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{htmlFor:"rsvp-last",children:"Last name"}),e.jsx(pe,{id:"rsvp-last",value:o.last_name,onChange:P=>c(R=>({...R,last_name:P.target.value})),className:"h-11"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{htmlFor:"rsvp-email",children:"Email *"}),e.jsx(pe,{id:"rsvp-email",type:"email",value:o.email,onChange:P=>c(R=>({...R,email:P.target.value})),className:"h-11"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{htmlFor:"rsvp-phone",children:"Phone"}),e.jsx(pe,{id:"rsvp-phone",type:"tel",value:o.phone,onChange:P=>c(R=>({...R,phone:P.target.value})),className:"h-11"})]})]}),e.jsxs("div",{className:"mt-4 rounded-xl border border-[#e4dcd3] bg-[#faf7f4] p-4",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium text-[#1b3a4b]",children:"Are you working with an agent?"}),e.jsx("p",{className:"text-xs text-[#7a888e]",children:"So we can respect your existing representation."})]}),e.jsx(Sn,{checked:d,onCheckedChange:u})]}),d&&e.jsx(pe,{value:h,onChange:P=>m(P.target.value),placeholder:"Your agent's name (optional)",className:"mt-3 h-10 bg-white"})]}),e.jsxs("div",{className:"mt-4 space-y-1.5",children:[e.jsx(ee,{htmlFor:"rsvp-msg",children:"Anything you'd like us to know?"}),e.jsx(Rs,{id:"rsvp-msg",rows:3,value:o.message,onChange:P=>c(R=>({...R,message:P.target.value})),className:"resize-y"})]}),f&&e.jsx("p",{className:"mt-3 text-sm text-destructive",children:f}),e.jsx($,{onClick:C,disabled:l.isPending,className:"mt-6 h-12 w-full bg-gradient-to-r from-[#1b3a4b] to-[#406E71] text-base hover:opacity-95",children:l.isPending?"Reserving…":e.jsxs(e.Fragment,{children:["RSVP for this open house",e.jsx(ei,{className:"ml-2 h-4 w-4"})]})}),e.jsx("p",{className:"mt-3 text-center text-xs text-[#8b979c]",children:"We'll only use your info to follow up about this property."})]})}),(w==null?void 0:w.name)&&e.jsxs("section",{className:"rounded-2xl bg-white/70 border border-[#e4dcd3] p-5 flex items-center gap-4",children:[e.jsxs(Oa,{className:"h-14 w-14",children:[e.jsx(Li,{src:w.avatar_url||void 0,alt:w.name}),e.jsx(za,{children:w.name.slice(0,1)})]}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-[11px] uppercase tracking-[0.25em] text-[#a08a5f]",children:"Hosted by"}),e.jsx("p",{className:"font-semibold text-[#1b3a4b]",children:w.name}),w.title&&e.jsx("p",{className:"text-sm text-[#5b6b72]",children:w.title}),e.jsxs("div",{className:"mt-1 flex flex-wrap gap-x-4 text-sm text-[#406E71]",children:[w.phone&&e.jsx("a",{href:`tel:${w.phone}`,children:w.phone}),w.email&&e.jsx("a",{href:`mailto:${w.email}`,className:"truncate",children:w.email})]})]})]}),e.jsx("div",{className:"text-center",children:e.jsxs("a",{href:I,target:"_blank",rel:"noreferrer",className:"inline-flex items-center gap-1.5 text-sm text-[#406E71] hover:underline",children:[e.jsx(ci,{className:"h-4 w-4"}),"Get directions to ",r.property_address]})})]})]})}function Bce({icon:s,label:t,value:n}){return e.jsxs("div",{className:"rounded-xl bg-white border border-[#e9e2da] px-4 py-3",children:[e.jsxs("div",{className:"flex items-center gap-1.5 text-[11px] uppercase tracking-wider text-[#9aa5aa]",children:[s,t]}),e.jsx("div",{className:"mt-1 text-lg font-semibold text-[#1b3a4b]",children:n})]})}function oSr(s){const{user:t}=vs();return tt({queryKey:["cohost-tokens",s],queryFn:async()=>{const{data:n,error:r}=await q.from("open_house_cohost_tokens").select("*").eq("open_house_id",s).order("created_at",{ascending:!1});if(r)throw r;return n},enabled:!!t&&!!s})}function lSr(){const s=Vt(),{user:t}=vs();return ft({mutationFn:async({openHouseId:n,label:r})=>{const{data:a,error:i}=await q.from("open_house_cohost_tokens").insert({open_house_id:n,label:r||null,created_by:t.id,expires_at:new Date(Date.now()+864e5).toISOString()}).select().single();if(i)throw i;return a},onSuccess:(n,r)=>{s.invalidateQueries({queryKey:["cohost-tokens",r.openHouseId]})}})}function cSr(){const s=Vt();return ft({mutationFn:async({id:t,openHouseId:n})=>{const{error:r}=await q.from("open_house_cohost_tokens").update({is_active:!1}).eq("id",t);if(r)throw r},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["cohost-tokens",n.openHouseId]})}})}function vOs(s){return tt({queryKey:["cohost-validate",s],queryFn:async()=>{const{data:t,error:n}=await q.from("open_house_cohost_tokens").select("*, open_houses(*)").eq("token",s).eq("is_active",!0).single();if(n)throw n;if(t.expires_at&&new Date(t.expires_at)-1&&s.splice(n,1)}const X4=(s,t,n)=>n>t?t:n{};const IL={},cBt=s=>/^-?(?:\d+(?:\.\d+)?|\.\d+)$/u.test(s),dBt=s=>typeof s=="object"&&s!==null,uBt=s=>/^0[^.\s]+$/u.test(s);function hBt(s){let t;return()=>(t===void 0&&(t=s()),t)}const ak=s=>s,Yae=(...s)=>s.reduce((t,n)=>r=>n(t(r))),rse=(s,t,n)=>{const r=t-s;return r?(n-s)/r:1};class fst{constructor(){this.subscriptions=[]}add(t){return mst(this.subscriptions,t),()=>REe(this.subscriptions,t)}notify(t,n,r){const a=this.subscriptions.length;if(a)if(a===1)this.subscriptions[0](t,n,r);else for(let i=0;is*1e3,WN=s=>s/1e3,mBt=(s,t)=>t?s*(1e3/t):0,fBt=(s,t,n)=>(((1-3*n+3*t)*s+(3*n-6*t))*s+3*t)*s,_Os=1e-7,wOs=12;function jOs(s,t,n,r,a){let i,l,o=0;do l=t+(n-t)/2,i=fBt(l,r,a)-s,i>0?n=l:t=l;while(Math.abs(i)>_Os&&++ojOs(i,0,1,s,n);return i=>i===0||i===1?i:fBt(a(i),t,r)}const pBt=s=>t=>t<=.5?s(2*t)/2:(2-s(2*(1-t)))/2,gBt=s=>t=>1-s(1-t),xBt=Zae(.33,1.53,.69,.99),pst=gBt(xBt),yBt=pBt(pst),vBt=s=>s>=1?1:(s*=2)<1?.5*pst(s):.5*(2-Math.pow(2,-10*(s-1))),gst=s=>1-Math.sin(Math.acos(s)),bBt=gBt(gst),_Bt=pBt(gst),NOs=Zae(.42,0,1,1),kOs=Zae(0,0,.58,1),wBt=Zae(.42,0,.58,1),SOs=s=>Array.isArray(s)&&typeof s[0]!="number",jBt=s=>Array.isArray(s)&&typeof s[0]=="number",COs={linear:ak,easeIn:NOs,easeInOut:wBt,easeOut:kOs,circIn:gst,circInOut:_Bt,circOut:bBt,backIn:pst,backInOut:yBt,backOut:xBt,anticipate:vBt},AOs=s=>typeof s=="string",c0t=s=>{if(jBt(s)){QLe(s.length===4);const[t,n,r,a]=s;return Zae(t,n,r,a)}else if(AOs(s))return COs[s];return s},$ce=["setup","read","resolveKeyframes","preUpdate","update","preRender","render","postRender"];function EOs(s){let t=new Set,n=new Set,r=!1,a=!1;const i=new WeakSet;let l={delta:0,timestamp:0,isProcessing:!1};function o(d){i.has(d)&&(c.schedule(d),s()),d(l)}const c={schedule:(d,u=!1,h=!1)=>{const f=h&&r?t:n;return u&&i.add(d),f.add(d),d},cancel:d=>{n.delete(d),i.delete(d)},process:d=>{if(l=d,r){a=!0;return}r=!0;const u=t;t=n,n=u,t.forEach(o),t.clear(),r=!1,a&&(a=!1,c.process(d))}};return c}const TOs=40;function NBt(s,t){let n=!1,r=!0;const a={delta:0,timestamp:0,isProcessing:!1},i=()=>n=!0,l=$ce.reduce((w,S)=>(w[S]=EOs(i),w),{}),{setup:o,read:c,resolveKeyframes:d,preUpdate:u,update:h,preRender:m,render:f,postRender:g}=l,x=()=>{const w=IL.useManualTiming,S=w?a.timestamp:performance.now();n=!1,w||(a.delta=r?1e3/60:Math.max(Math.min(S-a.timestamp,TOs),1)),a.timestamp=S,a.isProcessing=!0,o.process(a),c.process(a),d.process(a),u.process(a),h.process(a),m.process(a),f.process(a),g.process(a),a.isProcessing=!1,n&&t&&(r=!1,s(x))},y=()=>{n=!0,r=!0,a.isProcessing||s(x)};return{schedule:$ce.reduce((w,S)=>{const C=l[S];return w[S]=(E,I=!1,P=!1)=>(n||y(),C.schedule(E,I,P)),w},{}),cancel:w=>{for(let S=0;S<$ce.length;S++)l[$ce[S]].cancel(w)},state:a,steps:l}}const{schedule:Sf,cancel:LL,state:ab,steps:v7e}=NBt(typeof requestAnimationFrame<"u"?requestAnimationFrame:ak,!0);let t3e;function MOs(){t3e=void 0}const v_={now:()=>(t3e===void 0&&v_.set(ab.isProcessing||IL.useManualTiming?ab.timestamp:performance.now()),t3e),set:s=>{t3e=s,queueMicrotask(MOs)}},kBt=s=>t=>typeof t=="string"&&t.startsWith(s),SBt=kBt("--"),POs=kBt("var(--"),xst=s=>POs(s)?IOs.test(s.split("/*")[0].trim()):!1,IOs=/var\(--(?:[\w-]+\s*|[\w-]+\s*,(?:\s*[^)(\s]|\s*\((?:[^)(]|\([^)(]*\))*\))+\s*)\)$/iu;function d0t(s){return typeof s!="string"?!1:s.split("/*")[0].includes("var(--")}const iK={test:s=>typeof s=="number",parse:parseFloat,transform:s=>s},ase={...iK,transform:s=>X4(0,1,s)},Uce={...iK,default:1},_ee=s=>Math.round(s*1e5)/1e5,yst=/-?(?:\d+(?:\.\d+)?|\.\d+)/gu;function LOs(s){return s==null}const ROs=/^(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))$/iu,vst=(s,t)=>n=>!!(typeof n=="string"&&ROs.test(n)&&n.startsWith(s)||t&&!LOs(n)&&Object.prototype.hasOwnProperty.call(n,t)),CBt=(s,t,n)=>r=>{if(typeof r!="string")return r;const[a,i,l,o]=r.match(yst);return{[s]:parseFloat(a),[t]:parseFloat(i),[n]:parseFloat(l),alpha:o!==void 0?parseFloat(o):1}},DOs=s=>X4(0,255,s),b7e={...iK,transform:s=>Math.round(DOs(s))},u8={test:vst("rgb","red"),parse:CBt("red","green","blue"),transform:({red:s,green:t,blue:n,alpha:r=1})=>"rgba("+b7e.transform(s)+", "+b7e.transform(t)+", "+b7e.transform(n)+", "+_ee(ase.transform(r))+")"};function FOs(s){let t="",n="",r="",a="";return s.length>5?(t=s.substring(1,3),n=s.substring(3,5),r=s.substring(5,7),a=s.substring(7,9)):(t=s.substring(1,2),n=s.substring(2,3),r=s.substring(3,4),a=s.substring(4,5),t+=t,n+=n,r+=r,a+=a),{red:parseInt(t,16),green:parseInt(n,16),blue:parseInt(r,16),alpha:a?parseInt(a,16)/255:1}}const uGe={test:vst("#"),parse:FOs,transform:u8.transform},Xae=s=>({test:t=>typeof t=="string"&&t.endsWith(s)&&t.split(" ").length===1,parse:parseFloat,transform:t=>`${t}${s}`}),vA=Xae("deg"),B4=Xae("%"),Bo=Xae("px"),OOs=Xae("vh"),zOs=Xae("vw"),u0t={...B4,parse:s=>B4.parse(s)/100,transform:s=>B4.transform(s*100)},QU={test:vst("hsl","hue"),parse:CBt("hue","saturation","lightness"),transform:({hue:s,saturation:t,lightness:n,alpha:r=1})=>"hsla("+Math.round(s)+", "+B4.transform(_ee(t))+", "+B4.transform(_ee(n))+", "+_ee(ase.transform(r))+")"},Ry={test:s=>u8.test(s)||uGe.test(s)||QU.test(s),parse:s=>u8.test(s)?u8.parse(s):QU.test(s)?QU.parse(s):uGe.parse(s),transform:s=>typeof s=="string"?s:s.hasOwnProperty("red")?u8.transform(s):QU.transform(s),getAnimatableNone:s=>{const t=Ry.parse(s);return t.alpha=0,Ry.transform(t)}},BOs=/(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))/giu;function $Os(s){var t,n;return isNaN(s)&&typeof s=="string"&&(((t=s.match(yst))==null?void 0:t.length)||0)+(((n=s.match(BOs))==null?void 0:n.length)||0)>0}const ABt="number",EBt="color",UOs="var",qOs="var(",h0t="${}",VOs=/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 MG(s){const t=s.toString(),n=[],r={color:[],number:[],var:[]},a=[];let i=0;const o=t.replace(VOs,c=>(Ry.test(c)?(r.color.push(i),a.push(EBt),n.push(Ry.parse(c))):c.startsWith(qOs)?(r.var.push(i),a.push(UOs),n.push(c)):(r.number.push(i),a.push(ABt),n.push(parseFloat(c))),++i,h0t)).split(h0t);return{values:n,split:o,indexes:r,types:a}}function HOs(s){return MG(s).values}function TBt({split:s,types:t}){const n=s.length;return r=>{let a="";for(let i=0;itypeof s=="number"?0:Ry.test(s)?Ry.getAnimatableNone(s):s,KOs=(s,t)=>typeof s=="number"?t!=null&&t.trim().endsWith("/")?s:0:WOs(s);function YOs(s){const t=MG(s);return TBt(t)(t.values.map((r,a)=>KOs(r,t.split[a])))}const oC={test:$Os,parse:HOs,createTransformer:GOs,getAnimatableNone:YOs};function _7e(s,t,n){return n<0&&(n+=1),n>1&&(n-=1),n<1/6?s+(t-s)*6*n:n<1/2?t:n<2/3?s+(t-s)*(2/3-n)*6:s}function ZOs({hue:s,saturation:t,lightness:n,alpha:r}){s/=360,t/=100,n/=100;let a=0,i=0,l=0;if(!t)a=i=l=n;else{const o=n<.5?n*(1+t):n+t-n*t,c=2*n-o;a=_7e(c,o,s+1/3),i=_7e(c,o,s),l=_7e(c,o,s-1/3)}return{red:Math.round(a*255),green:Math.round(i*255),blue:Math.round(l*255),alpha:r}}function DEe(s,t){return n=>n>0?t:s}const Nf=(s,t,n)=>s+(t-s)*n,w7e=(s,t,n)=>{const r=s*s,a=n*(t*t-r)+r;return a<0?0:Math.sqrt(a)},XOs=[uGe,u8,QU],QOs=s=>XOs.find(t=>t.test(s));function m0t(s){const t=QOs(s);if(!t)return!1;let n=t.parse(s);return t===QU&&(n=ZOs(n)),n}const f0t=(s,t)=>{const n=m0t(s),r=m0t(t);if(!n||!r)return DEe(s,t);const a={...n};return i=>(a.red=w7e(n.red,r.red,i),a.green=w7e(n.green,r.green,i),a.blue=w7e(n.blue,r.blue,i),a.alpha=Nf(n.alpha,r.alpha,i),u8.transform(a))},hGe=new Set(["none","hidden"]);function JOs(s,t){return hGe.has(s)?n=>n<=0?s:t:n=>n>=1?t:s}function e8s(s,t){return n=>Nf(s,t,n)}function bst(s){return typeof s=="number"?e8s:typeof s=="string"?xst(s)?DEe:Ry.test(s)?f0t:n8s:Array.isArray(s)?MBt:typeof s=="object"?Ry.test(s)?f0t:t8s:DEe}function MBt(s,t){const n=[...s],r=n.length,a=s.map((i,l)=>bst(i)(i,t[l]));return i=>{for(let l=0;l{for(const i in r)n[i]=r[i](a);return n}}function s8s(s,t){const n=[],r={color:0,var:0,number:0};for(let a=0;a{const n=oC.createTransformer(t),r=MG(s),a=MG(t);return r.indexes.var.length===a.indexes.var.length&&r.indexes.color.length===a.indexes.color.length&&r.indexes.number.length>=a.indexes.number.length?hGe.has(s)&&!a.values.length||hGe.has(t)&&!r.values.length?JOs(s,t):Yae(MBt(s8s(r,a),a.values),n):DEe(s,t)};function PBt(s,t,n){return typeof s=="number"&&typeof t=="number"&&typeof n=="number"?Nf(s,t,n):bst(s)(s,t)}const r8s=s=>{const t=({timestamp:n})=>s(n);return{start:(n=!0)=>Sf.update(t,n),stop:()=>LL(t),now:()=>ab.isProcessing?ab.timestamp:v_.now()}},IBt=(s,t,n=10)=>{let r="";const a=Math.max(Math.round(t/n),2);for(let i=0;i=FEe?1/0:t}function a8s(s,t=100,n){const r=n({...s,keyframes:[0,t]}),a=Math.min(_st(r),FEe);return{type:"keyframes",ease:i=>r.next(a*i).value/t,duration:WN(a)}}const fx={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 mGe(s,t){return s*Math.sqrt(1-t*t)}const i8s=12;function o8s(s,t,n){let r=n;for(let a=1;a{const u=d*l,h=u*s,m=u-n,f=mGe(d,l),g=Math.exp(-h);return j7e-m/f*g},i=d=>{const h=d*l*s,m=h*n+n,f=Math.pow(l,2)*Math.pow(d,2)*s,g=Math.exp(-h),x=mGe(Math.pow(d,2),l);return(-a(d)+j7e>0?-1:1)*((m-f)*g)/x}):(a=d=>{const u=Math.exp(-d*s),h=(d-n)*s+1;return-j7e+u*h},i=d=>{const u=Math.exp(-d*s),h=(n-d)*(s*s);return u*h});const o=5/s,c=o8s(a,i,o);if(s=v2(s),isNaN(c))return{stiffness:fx.stiffness,damping:fx.damping,duration:s};{const d=Math.pow(c,2)*r;return{stiffness:d,damping:l*2*Math.sqrt(r*d),duration:s}}}const c8s=["duration","bounce"],d8s=["stiffness","damping","mass"];function p0t(s,t){return t.some(n=>s[n]!==void 0)}function u8s(s){let t={velocity:fx.velocity,stiffness:fx.stiffness,damping:fx.damping,mass:fx.mass,isResolvedFromDuration:!1,...s};if(!p0t(s,d8s)&&p0t(s,c8s))if(t.velocity=0,s.visualDuration){const n=s.visualDuration,r=2*Math.PI/(n*1.2),a=r*r,i=2*X4(.05,1,1-(s.bounce||0))*Math.sqrt(a);t={...t,mass:fx.mass,stiffness:a,damping:i}}else{const n=l8s({...s,velocity:0});t={...t,...n,mass:fx.mass},t.isResolvedFromDuration=!0}return t}function OEe(s=fx.visualDuration,t=fx.bounce){const n=typeof s!="object"?{visualDuration:s,keyframes:[0,1],bounce:t}:s;let{restSpeed:r,restDelta:a}=n;const i=n.keyframes[0],l=n.keyframes[n.keyframes.length-1],o={done:!1,value:i},{stiffness:c,damping:d,mass:u,duration:h,velocity:m,isResolvedFromDuration:f}=u8s({...n,velocity:-WN(n.velocity||0)}),g=m||0,x=d/(2*Math.sqrt(c*u)),y=l-i,v=WN(Math.sqrt(c/u)),b=Math.abs(y)<5;r||(r=b?fx.restSpeed.granular:fx.restSpeed.default),a||(a=b?fx.restDelta.granular:fx.restDelta.default);let w,S,C,E,I,P;if(x<1)C=mGe(v,x),E=(g+x*v*y)/C,w=D=>{const O=Math.exp(-x*v*D);return l-O*(E*Math.sin(C*D)+y*Math.cos(C*D))},I=x*v*E+y*C,P=x*v*y-E*C,S=D=>Math.exp(-x*v*D)*(I*Math.sin(C*D)+P*Math.cos(C*D));else if(x===1){w=O=>l-Math.exp(-v*O)*(y+(g+v*y)*O);const D=g+v*y;S=O=>Math.exp(-v*O)*(v*D*O-g)}else{const D=v*Math.sqrt(x*x-1);w=V=>{const G=Math.exp(-x*v*V),Y=Math.min(D*V,300);return l-G*((g+x*v*y)*Math.sinh(Y)+D*y*Math.cosh(Y))/D};const O=(g+x*v*y)/D,U=x*v*O-y*D,W=x*v*y-O*D;S=V=>{const G=Math.exp(-x*v*V),Y=Math.min(D*V,300);return G*(U*Math.sinh(Y)+W*Math.cosh(Y))}}const R={calculatedDuration:f&&h||null,velocity:D=>v2(S(D)),next:D=>{if(!f&&x<1){const U=Math.exp(-x*v*D),W=Math.sin(C*D),V=Math.cos(C*D),G=l-U*(E*W+y*V),Y=v2(U*(I*W+P*V));return o.done=Math.abs(Y)<=r&&Math.abs(l-G)<=a,o.value=o.done?l:G,o}const O=w(D);if(f)o.done=D>=h;else{const U=v2(S(D));o.done=Math.abs(U)<=r&&Math.abs(l-O)<=a}return o.value=o.done?l:O,o},toString:()=>{const D=Math.min(_st(R),FEe),O=IBt(U=>R.next(D*U).value,D,30);return D+"ms "+O},toTransition:()=>{}};return R}OEe.applyToOptions=s=>{const t=a8s(s,100,OEe);return s.ease=t.ease,s.duration=v2(t.duration),s.type="keyframes",s};const h8s=5;function LBt(s,t,n){const r=Math.max(t-h8s,0);return mBt(n-s(r),t-r)}function fGe({keyframes:s,velocity:t=0,power:n=.8,timeConstant:r=325,bounceDamping:a=10,bounceStiffness:i=500,modifyTarget:l,min:o,max:c,restDelta:d=.5,restSpeed:u}){const h=s[0],m={done:!1,value:h},f=P=>o!==void 0&&Pc,g=P=>o===void 0?c:c===void 0||Math.abs(o-P)-x*Math.exp(-P/r),w=P=>v+b(P),S=P=>{const R=b(P),D=w(P);m.done=Math.abs(R)<=d,m.value=m.done?v:D};let C,E;const I=P=>{f(m.value)&&(C=P,E=OEe({keyframes:[m.value,g(m.value)],velocity:LBt(w,P,m.value),damping:a,stiffness:i,restDelta:d,restSpeed:u}))};return I(0),{calculatedDuration:null,next:P=>{let R=!1;return!E&&C===void 0&&(R=!0,S(P),I(P)),C!==void 0&&P>=C?E.next(P-C):(!R&&S(P),m)}}}function m8s(s,t,n){const r=[],a=n||IL.mix||PBt,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=m8s(t,r,a),c=o.length,d=u=>{if(l&&u1)for(;hd(X4(s[0],s[i-1],u)):d}function p8s(s,t){const n=s[s.length-1];for(let r=1;r<=t;r++){const a=rse(0,t,r);s.push(Nf(n,1,a))}}function g8s(s){const t=[0];return p8s(t,s.length-1),t}function x8s(s,t){return s.map(n=>n*t)}function y8s(s,t){return s.map(()=>t||wBt).splice(0,s.length-1)}function wee({duration:s=300,keyframes:t,times:n,ease:r="easeInOut"}){const a=SOs(r)?r.map(c0t):c0t(r),i={done:!1,value:t[0]},l=x8s(n&&n.length===t.length?n:g8s(t),s),o=f8s(l,t,{ease:Array.isArray(a)?a:y8s(t,a)});return{calculatedDuration:s,next:c=>(i.value=o(c),i.done=c>=s,i)}}const v8s=s=>s!==null;function JLe(s,{repeat:t,repeatType:n="loop"},r,a=1){const i=s.filter(v8s),o=a<0||t&&n!=="loop"&&t%2===1?0:i.length-1;return!o||r===void 0?i[o]:r}const b8s={decay:fGe,inertia:fGe,tween:wee,keyframes:wee,spring:OEe};function RBt(s){typeof s.type=="string"&&(s.type=b8s[s.type])}class wst{constructor(){this.updateFinished()}get finished(){return this._finished}updateFinished(){this._finished=new Promise(t=>{this.resolve=t})}notifyFinished(){this.resolve()}then(t,n){return this.finished.then(t,n)}}const _8s=s=>s/100;class zEe extends wst{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 r,a;const{motionValue:n}=this.options;n&&n.updatedAt!==v_.now()&&this.tick(v_.now()),this.isStopped=!0,this.state!=="idle"&&(this.teardown(),(a=(r=this.options).onStop)==null||a.call(r))},this.options=t,this.initAnimation(),this.play(),t.autoplay===!1&&this.pause()}initAnimation(){const{options:t}=this;RBt(t);const{type:n=wee,repeat:r=0,repeatDelay:a=0,repeatType:i,velocity:l=0}=t;let{keyframes:o}=t;const c=n||wee;c!==wee&&typeof o[0]!="number"&&(this.mixKeyframes=Yae(_8s,PBt(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=_st(d));const{calculatedDuration:u}=d;this.calculatedDuration=u,this.resolvedDuration=u+a,this.totalDuration=this.resolvedDuration*(r+1)-a,this.generator=d}updateTime(t){const n=Math.round(t-this.startTime)*this.playbackSpeed;this.holdTime!==null?this.currentTime=this.holdTime:this.currentTime=n}tick(t,n=!1){const{generator:r,totalDuration:a,mixKeyframes:i,mirroredGenerator:l,resolvedDuration:o,calculatedDuration:c}=this;if(this.startTime===null)return r.next(0);const{delay:d=0,keyframes:u,repeat:h,repeatType:m,repeatDelay:f,type:g,onUpdate:x,finalKeyframe:y}=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)),n?this.currentTime=t:this.updateTime(t);const v=this.currentTime-d*(this.playbackSpeed>=0?1:-1),b=this.playbackSpeed>=0?v<0:v>a;this.currentTime=Math.max(v,0),this.state==="finished"&&this.holdTime===null&&(this.currentTime=a);let w=this.currentTime,S=r;if(h){const P=Math.min(this.currentTime,a)/o;let R=Math.floor(P),D=P%1;!D&&P>=1&&(D=1),D===1&&R--,R=Math.min(R,h+1),!!(R%2)&&(m==="reverse"?(D=1-D,f&&(D-=f/o)):m==="mirror"&&(S=l)),w=X4(0,1,D)*o}let C;b?(this.delayState.value=u[0],C=this.delayState):C=S.next(w),i&&!b&&(C.value=i(C.value));let{done:E}=C;!b&&c!==null&&(E=this.playbackSpeed>=0?this.currentTime>=a:this.currentTime<=0);const I=this.holdTime===null&&(this.state==="finished"||this.state==="running"&&E);return I&&g!==fGe&&(C.value=JLe(u,this.options,y,this.speed)),x&&x(C.value),I&&this.finish(),C}then(t,n){return this.finished.then(t,n)}get duration(){return WN(this.calculatedDuration)}get iterationDuration(){const{delay:t=0}=this.options||{};return this.duration+WN(t)}get time(){return WN(this.currentTime)}set time(t){t=v2(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 n=this.generator.next(t).value;return LBt(r=>this.generator.next(r).value,t,n)}get speed(){return this.playbackSpeed}set speed(t){const n=this.playbackSpeed!==t;n&&this.driver&&this.updateTime(v_.now()),this.playbackSpeed=t,n&&this.driver&&(this.time=WN(this.currentTime))}play(){var a,i;if(this.isStopped)return;const{driver:t=r8s,startTime:n}=this.options;this.driver||(this.driver=t(l=>this.tick(l))),(i=(a=this.options).onPlay)==null||i.call(a);const r=this.driver.now();this.state==="finished"?(this.updateFinished(),this.startTime=r):this.holdTime!==null?this.startTime=r-this.holdTime:this.startTime||(this.startTime=n??r),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(v_.now()),this.holdTime=this.currentTime}complete(){this.state!=="running"&&this.play(),this.state="finished",this.holdTime=null}finish(){var t,n;this.notifyFinished(),this.teardown(),this.state="finished",(n=(t=this.options).onComplete)==null||n.call(t)}cancel(){var t,n;this.holdTime=null,this.startTime=0,this.tick(0),this.teardown(),(n=(t=this.options).onCancel)==null||n.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 n;return this.options.allowFlatten&&(this.options.type="keyframes",this.options.ease="linear",this.initAnimation()),(n=this.driver)==null||n.stop(),t.observe(this)}}function w8s(s){for(let t=1;ts*180/Math.PI,pGe=s=>{const t=h8(Math.atan2(s[1],s[0]));return gGe(t)},j8s={x:4,y:5,translateX:4,translateY:5,scaleX:0,scaleY:3,scale:s=>(Math.abs(s[0])+Math.abs(s[3]))/2,rotate:pGe,rotateZ:pGe,skewX:s=>h8(Math.atan(s[1])),skewY:s=>h8(Math.atan(s[2])),skew:s=>(Math.abs(s[1])+Math.abs(s[2]))/2},gGe=s=>(s=s%360,s<0&&(s+=360),s),g0t=pGe,x0t=s=>Math.sqrt(s[0]*s[0]+s[1]*s[1]),y0t=s=>Math.sqrt(s[4]*s[4]+s[5]*s[5]),N8s={x:12,y:13,z:14,translateX:12,translateY:13,translateZ:14,scaleX:x0t,scaleY:y0t,scale:s=>(x0t(s)+y0t(s))/2,rotateX:s=>gGe(h8(Math.atan2(s[6],s[5]))),rotateY:s=>gGe(h8(Math.atan2(-s[2],s[0]))),rotateZ:g0t,rotate:g0t,skewX:s=>h8(Math.atan(s[4])),skewY:s=>h8(Math.atan(s[1])),skew:s=>(Math.abs(s[1])+Math.abs(s[4]))/2};function xGe(s){return s.includes("scale")?1:0}function yGe(s,t){if(!s||s==="none")return xGe(t);const n=s.match(/^matrix3d\(([-\d.e\s,]+)\)$/u);let r,a;if(n)r=N8s,a=n;else{const o=s.match(/^matrix\(([-\d.e\s,]+)\)$/u);r=j8s,a=o}if(!a)return xGe(t);const i=r[t],l=a[1].split(",").map(S8s);return typeof i=="function"?i(l):l[i]}const k8s=(s,t)=>{const{transform:n="none"}=getComputedStyle(s);return yGe(n,t)};function S8s(s){return parseFloat(s.trim())}const oK=["transformPerspective","x","y","z","translateX","translateY","translateZ","scale","scaleX","scaleY","rotate","rotateX","rotateY","rotateZ","skew","skewX","skewY"],lK=new Set([...oK,"pathRotation"]),v0t=s=>s===iK||s===Bo,C8s=new Set(["x","y","z"]),A8s=oK.filter(s=>!C8s.has(s));function E8s(s){const t=[];return A8s.forEach(n=>{const r=s.getValue(n);r!==void 0&&(t.push([n,r.get()]),r.set(n.startsWith("scale")?1:0))}),t}const vI={width:({x:s},{paddingLeft:t="0",paddingRight:n="0",boxSizing:r})=>{const a=s.max-s.min;return r==="border-box"?a:a-parseFloat(t)-parseFloat(n)},height:({y:s},{paddingTop:t="0",paddingBottom:n="0",boxSizing:r})=>{const a=s.max-s.min;return r==="border-box"?a:a-parseFloat(t)-parseFloat(n)},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})=>yGe(t,"x"),y:(s,{transform:t})=>yGe(t,"y")};vI.translateX=vI.x;vI.translateY=vI.y;const u7=new Set;let vGe=!1,bGe=!1,_Ge=!1;function DBt(){if(bGe){const s=Array.from(u7).filter(r=>r.needsMeasurement),t=new Set(s.map(r=>r.element)),n=new Map;t.forEach(r=>{const a=E8s(r);a.length&&(n.set(r,a),r.render())}),s.forEach(r=>r.measureInitialState()),t.forEach(r=>{r.render();const a=n.get(r);a&&a.forEach(([i,l])=>{var o;(o=r.getValue(i))==null||o.set(l)})}),s.forEach(r=>r.measureEndState()),s.forEach(r=>{r.suspendedScrollY!==void 0&&window.scrollTo(0,r.suspendedScrollY)})}bGe=!1,vGe=!1,u7.forEach(s=>s.complete(_Ge)),u7.clear()}function FBt(){u7.forEach(s=>{s.readKeyframes(),s.needsMeasurement&&(bGe=!0)})}function T8s(){_Ge=!0,FBt(),DBt(),_Ge=!1}class jst{constructor(t,n,r,a,i,l=!1){this.state="pending",this.isAsync=!1,this.needsMeasurement=!1,this.unresolvedKeyframes=[...t],this.onComplete=n,this.name=r,this.motionValue=a,this.element=i,this.isAsync=l}scheduleResolve(){this.state="scheduled",this.isAsync?(u7.add(this),vGe||(vGe=!0,Sf.read(FBt),Sf.resolveKeyframes(DBt))):(this.readKeyframes(),this.complete())}readKeyframes(){const{unresolvedKeyframes:t,name:n,element:r,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(r&&n){const o=r.readValue(n,l);o!=null&&(t[0]=o)}t[0]===void 0&&(t[0]=l),a&&i===void 0&&a.set(t[0])}w8s(t)}setFinalKeyframe(){}measureInitialState(){}renderEndStyles(){}measureEndState(){}complete(t=!1){this.state="complete",this.onComplete(this.unresolvedKeyframes,this.finalKeyframe,t),u7.delete(this)}cancel(){this.state==="scheduled"&&(u7.delete(this),this.state="pending")}resume(){this.state==="pending"&&this.scheduleResolve()}}const M8s=s=>s.startsWith("--");function OBt(s,t,n){M8s(t)?s.style.setProperty(t,n):s.style[t]=n}const P8s={};function zBt(s,t){const n=hBt(s);return()=>P8s[t]??n()}const I8s=zBt(()=>window.ScrollTimeline!==void 0,"scrollTimeline"),BBt=zBt(()=>{try{document.createElement("div").animate({opacity:0},{easing:"linear(0, 1)"})}catch{return!1}return!0},"linearEasing"),uQ=([s,t,n,r])=>`cubic-bezier(${s}, ${t}, ${n}, ${r})`,b0t={linear:"linear",ease:"ease",easeIn:"ease-in",easeOut:"ease-out",easeInOut:"ease-in-out",circIn:uQ([0,.65,.55,1]),circOut:uQ([.55,0,1,.45]),backIn:uQ([.31,.01,.66,-.59]),backOut:uQ([.33,1.53,.69,.99])};function $Bt(s,t){if(s)return typeof s=="function"?BBt()?IBt(s,t):"ease-out":jBt(s)?uQ(s):Array.isArray(s)?s.map(n=>$Bt(n,t)||b0t.easeOut):b0t[s]}function L8s(s,t,n,{delay:r=0,duration:a=300,repeat:i=0,repeatType:l="loop",ease:o="easeOut",times:c}={},d=void 0){const u={[t]:n};c&&(u.offset=c);const h=$Bt(o,a);Array.isArray(h)&&(u.easing=h);const m={delay:r,duration:a,easing:Array.isArray(h)?"linear":h,fill:"both",iterations:i+1,direction:l==="reverse"?"alternate":"normal"};return d&&(m.pseudoElement=d),s.animate(u,m)}function UBt(s){return typeof s=="function"&&"applyToOptions"in s}function R8s({type:s,...t}){return UBt(s)&&BBt()?s.applyToOptions(t):(t.duration??(t.duration=300),t.ease??(t.ease="easeOut"),t)}class qBt extends wst{constructor(t){if(super(),this.finishedTime=null,this.isStopped=!1,this.manualStartTime=null,!t)return;const{element:n,name:r,keyframes:a,pseudoElement:i,allowFlatten:l=!1,finalKeyframe:o,onComplete:c}=t;this.isPseudoElement=!!i,this.allowFlatten=l,this.options=t,QLe(typeof t.type!="string");const d=R8s(t);this.animation=L8s(n,r,a,d,i),d.autoplay===!1&&this.animation.pause(),this.animation.onfinish=()=>{if(this.finishedTime=this.time,!i){const u=JLe(a,this.options,o,this.speed);this.updateMotionValue&&this.updateMotionValue(u),OBt(n,r,u),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,n;(n=(t=this.animation).finish)==null||n.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 n,r,a;const t=(n=this.options)==null?void 0:n.element;!this.isPseudoElement&&(t!=null&&t.isConnected)&&((a=(r=this.animation).commitStyles)==null||a.call(r))}get duration(){var n,r;const t=((r=(n=this.animation.effect)==null?void 0:n.getComputedTiming)==null?void 0:r.call(n).duration)||0;return WN(Number(t))}get iterationDuration(){const{delay:t=0}=this.options||{};return this.duration+WN(t)}get time(){return WN(Number(this.animation.currentTime)||0)}set time(t){const n=this.finishedTime!==null;this.manualStartTime=null,this.finishedTime=null,this.animation.currentTime=v2(t),n&&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:n,rangeEnd:r,observe:a}){var i;return this.allowFlatten&&((i=this.animation.effect)==null||i.updateTiming({easing:"linear"})),this.animation.onfinish=null,t&&I8s()?(this.animation.timeline=t,n&&(this.animation.rangeStart=n),r&&(this.animation.rangeEnd=r),ak):a(this)}}const VBt={anticipate:vBt,backInOut:yBt,circInOut:_Bt};function D8s(s){return s in VBt}function F8s(s){typeof s.ease=="string"&&D8s(s.ease)&&(s.ease=VBt[s.ease])}const N7e=10;class O8s extends qBt{constructor(t){F8s(t),RBt(t),super(t),t.startTime!==void 0&&t.autoplay!==!1&&(this.startTime=t.startTime),this.options=t}updateMotionValue(t){const{motionValue:n,onUpdate:r,onComplete:a,element:i,...l}=this.options;if(!n)return;if(t!==void 0){n.set(t);return}const o=new zEe({...l,autoplay:!1}),c=Math.max(N7e,v_.now()-this.startTime),d=X4(0,N7e,c-N7e),u=o.sample(c).value,{name:h}=this.options;i&&h&&OBt(i,h,u),n.setWithVelocity(o.sample(Math.max(0,c-d)).value,u,d),o.stop()}}const _0t=(s,t)=>t==="zIndex"?!1:!!(typeof s=="number"||Array.isArray(s)||typeof s=="string"&&(oC.test(s)||s==="0")&&!s.startsWith("url("));function z8s(s){const t=s[0];if(s.length===1)return!0;for(let n=0;nObject.hasOwnProperty.call(Element.prototype,"animate"));function H8s(s){var h;const{motionValue:t,name:n,repeatDelay:r,repeatType:a,damping:i,type:l,keyframes:o}=s,c=(h=t==null?void 0:t.owner)==null?void 0:h.current;if(!(c instanceof HTMLElement)&&!(c instanceof SVGElement))return!1;const{onUpdate:d,transformTemplate:u}=t.owner.getProps();return V8s()&&n&&(HBt.has(n)||q8s.has(n)&&U8s(o))&&(n!=="transform"||!u)&&!d&&!r&&a!=="mirror"&&i!==0&&l!=="inertia"}const G8s=40;class W8s extends wst{constructor({autoplay:t=!0,delay:n=0,type:r="keyframes",repeat:a=0,repeatDelay:i=0,repeatType:l="loop",keyframes:o,name:c,motionValue:d,element:u,...h}){var g;super(),this.stop=()=>{var x,y;this._animation&&(this._animation.stop(),(x=this.stopTimeline)==null||x.call(this)),(y=this.keyframeResolver)==null||y.cancel()},this.createdAt=v_.now();const m={autoplay:t,delay:n,type:r,repeat:a,repeatDelay:i,repeatType:l,name:c,motionValue:d,element:u,...h},f=(u==null?void 0:u.KeyframeResolver)||jst;this.keyframeResolver=new f(o,(x,y,v)=>this.onKeyframesResolved(x,y,m,!v),c,d,u),(g=this.keyframeResolver)==null||g.scheduleResolve()}onKeyframesResolved(t,n,r,a){var v,b;this.keyframeResolver=void 0;const{name:i,type:l,velocity:o,delay:c,isHandoff:d,onUpdate:u}=r;this.resolvedAt=v_.now();let h=!0;B8s(t,i,l,o)||(h=!1,(IL.instantAnimations||!c)&&(u==null||u(JLe(t,r,n))),t[0]=t[t.length-1],wGe(r),r.repeat=0);const f={startTime:a?this.resolvedAt?this.resolvedAt-this.createdAt>G8s?this.resolvedAt:this.createdAt:this.createdAt:void 0,finalKeyframe:n,...r,keyframes:t},g=h&&!d&&H8s(f),x=(b=(v=f.motionValue)==null?void 0:v.owner)==null?void 0:b.current;let y;if(g)try{y=new O8s({...f,element:x})}catch{y=new zEe(f)}else y=new zEe(f);y.finished.then(()=>{this.notifyFinished()}).catch(ak),this.pendingTimeline&&(this.stopTimeline=y.attachTimeline(this.pendingTimeline),this.pendingTimeline=void 0),this._animation=y}get finished(){return this._animation?this.animation.finished:this._finished}then(t,n){return this.finished.finally(t).then(()=>{})}get animation(){var t;return this._animation||((t=this.keyframeResolver)==null||t.resume(),T8s()),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 GBt(s,t,n,r=0,a=1){const i=Array.from(s).sort((d,u)=>d.sortNodePosition(u)).indexOf(t),l=s.size,o=(l-1)*r;return typeof n=="function"?n(i,l):a===1?i*r:o-i*r}const w0t=30,K8s=s=>!isNaN(parseFloat(s));class Y8s{constructor(t,n={}){this.canTrackVelocity=null,this.events={},this.updateAndNotify=r=>{var i;const a=v_.now();if(this.updatedAt!==a&&this.setPrevFrameValue(),this.prev=this.current,this.setCurrent(r),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=n.owner}setCurrent(t){this.current=t,this.updatedAt=v_.now(),this.canTrackVelocity===null&&t!==void 0&&(this.canTrackVelocity=K8s(this.current))}setPrevFrameValue(t=this.current){this.prevFrameValue=t,this.prevUpdatedAt=this.updatedAt}onChange(t){return this.on("change",t)}on(t,n){this.events[t]||(this.events[t]=new fst);const r=this.events[t].add(n);return t==="change"?()=>{r(),Sf.read(()=>{this.events.change.getSize()||this.stop()})}:r}clearListeners(){for(const t in this.events)this.events[t].clear()}attach(t,n){this.passiveEffect=t,this.stopPassiveEffect=n}set(t){this.passiveEffect?this.passiveEffect(t,this.updateAndNotify):this.updateAndNotify(t)}setWithVelocity(t,n,r){this.set(n),this.prev=void 0,this.prevFrameValue=t,this.prevUpdatedAt=this.updatedAt-r}jump(t,n=!0){this.updateAndNotify(t),this.prev=t,this.prevUpdatedAt=this.prevFrameValue=void 0,n&&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=v_.now();if(!this.canTrackVelocity||this.prevFrameValue===void 0||t-this.updatedAt>w0t)return 0;const n=Math.min(this.updatedAt-this.prevUpdatedAt,w0t);return mBt(parseFloat(this.current)-parseFloat(this.prevFrameValue),n)}start(t){return this.stop(),new Promise(n=>{this.hasAnimated=!0,this.animation=t(n),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,n;(t=this.dependents)==null||t.clear(),(n=this.events.destroy)==null||n.notify(),this.clearListeners(),this.stop(),this.stopPassiveEffect&&this.stopPassiveEffect()}}function PG(s,t){return new Y8s(s,t)}function WBt(s,t){if(s!=null&&s.inherit&&t){const{inherit:n,...r}=s;return{...t,...r}}return s}function Nst(s,t){const n=(s==null?void 0:s[t])??(s==null?void 0:s.default)??s;return n!==s?WBt(n,s):n}const Z8s={type:"spring",stiffness:500,damping:25,restSpeed:10},X8s=s=>({type:"spring",stiffness:550,damping:s===0?2*Math.sqrt(550):30,restSpeed:10}),Q8s={type:"keyframes",duration:.8},J8s={type:"keyframes",ease:[.25,.1,.35,1],duration:.3},ezs=(s,{keyframes:t})=>t.length>2?Q8s:lK.has(s)?s.startsWith("scale")?X8s(t[1]):Z8s:J8s,tzs=new Set(["when","delay","delayChildren","staggerChildren","staggerDirection","repeat","repeatType","repeatDelay","from","elapsed"]);function szs(s){for(const t in s)if(!tzs.has(t))return!0;return!1}const kst=(s,t,n,r={},a,i)=>l=>{const o=Nst(r,s)||{},c=o.delay||r.delay||0;let{elapsed:d=0}=r;d=d-v2(c);const u={keyframes:Array.isArray(n)?n:[null,n],ease:"easeOut",velocity:t.getVelocity(),...o,delay:-d,onUpdate:m=>{t.set(m),o.onUpdate&&o.onUpdate(m)},onComplete:()=>{l(),o.onComplete&&o.onComplete()},name:s,motionValue:t,element:i?void 0:a};szs(o)||Object.assign(u,ezs(s,u)),u.duration&&(u.duration=v2(u.duration)),u.repeatDelay&&(u.repeatDelay=v2(u.repeatDelay)),u.from!==void 0&&(u.keyframes[0]=u.from);let h=!1;if((u.type===!1||u.duration===0&&!u.repeatDelay)&&(wGe(u),u.delay===0&&(h=!0)),(IL.instantAnimations||IL.skipAnimations||a!=null&&a.shouldSkipAnimations||o.skipAnimations)&&(h=!0,wGe(u),u.delay=0),u.allowFlatten=!o.type&&!o.ease,h&&!i&&t.get()!==void 0){const m=JLe(u.keyframes,o);if(m!==void 0){Sf.update(()=>{u.onUpdate(m),u.onComplete()});return}}return o.isSync?new zEe(u):new W8s(u)},nzs=/^var\(--(?:([\w-]+)|([\w-]+), ?([a-zA-Z\d ()%#.,-]+))\)/u;function rzs(s){const t=nzs.exec(s);if(!t)return[,];const[,n,r,a]=t;return[`--${n??r}`,a]}function KBt(s,t,n=1){const[r,a]=rzs(s);if(!r)return;const i=window.getComputedStyle(t).getPropertyValue(r);if(i){const l=i.trim();return cBt(l)?parseFloat(l):l}return xst(a)?KBt(a,t,n+1):a}function j0t(s){const t=[{},{}];return s==null||s.values.forEach((n,r)=>{t[0][r]=n.get(),t[1][r]=n.getVelocity()}),t}function Sst(s,t,n,r){if(typeof t=="function"){const[a,i]=j0t(r);t=t(n!==void 0?n:s.custom,a,i)}if(typeof t=="string"&&(t=s.variants&&s.variants[t]),typeof t=="function"){const[a,i]=j0t(r);t=t(n!==void 0?n:s.custom,a,i)}return t}function h7(s,t,n){const r=s.getProps();return Sst(r,t,n!==void 0?n:r.custom,s)}const YBt=new Set(["width","height","top","left","right","bottom",...oK]),jGe=s=>Array.isArray(s);function azs(s,t,n){s.hasValue(t)?s.getValue(t).set(n):s.addValue(t,PG(n))}function izs(s){return jGe(s)?s[s.length-1]||0:s}function ozs(s,t){const n=h7(s,t);let{transitionEnd:r={},transition:a={},...i}=n||{};i={...i,...r};for(const l in i){const o=izs(i[l]);azs(s,l,o)}}const pb=s=>!!(s&&s.getVelocity);function lzs(s){return!!(pb(s)&&s.add)}function NGe(s,t){const n=s.getValue("willChange");if(lzs(n))return n.add(t);if(!n&&IL.WillChange){const r=new IL.WillChange("auto");s.addValue("willChange",r),r.add(t)}}function Cst(s){return s.replace(/([A-Z])/g,t=>`-${t.toLowerCase()}`)}const czs="framerAppearId",ZBt="data-"+Cst(czs);function XBt(s){return s.props[ZBt]}function dzs({protectedKeys:s,needsAnimating:t},n){const r=s.hasOwnProperty(n)&&t[n]!==!0;return t[n]=!1,r}function QBt(s,t,{delay:n=0,transitionOverride:r,type:a}={}){let{transition:i,transitionEnd:l,...o}=t;const c=s.getDefaultTransition();i=i?WBt(i,c):c;const d=i==null?void 0:i.reduceMotion,u=i==null?void 0:i.skipAnimations;r&&(i=r);const h=[],m=a&&s.animationState&&s.animationState.getState()[a],f=i==null?void 0:i.path;f&&f.animateVisualElement(s,o,i,n,h);for(const g in o){const x=s.getValue(g,s.latestValues[g]??null),y=o[g];if(y===void 0||m&&dzs(m,g))continue;const v={delay:n,...Nst(i||{},g)};u&&(v.skipAnimations=!0);const b=x.get();if(b!==void 0&&!x.isAnimating()&&!Array.isArray(y)&&y===b&&!v.velocity){Sf.update(()=>x.set(y));continue}let w=!1;if(window.MotionHandoffAnimation){const E=XBt(s);if(E){const I=window.MotionHandoffAnimation(E,g,Sf);I!==null&&(v.startTime=I,w=!0)}}NGe(s,g);const S=d??s.shouldReduceMotion;x.start(kst(g,x,y,S&&YBt.has(g)?{type:!1}:v,s,w));const C=x.animation;C&&h.push(C)}if(l){const g=()=>Sf.update(()=>{l&&ozs(s,l)});h.length?Promise.all(h).then(g):g()}return h}function kGe(s,t,n={}){var c;const r=h7(s,t,n.type==="exit"?(c=s.presenceContext)==null?void 0:c.custom:void 0);let{transition:a=s.getDefaultTransition()||{}}=r||{};n.transitionOverride&&(a=n.transitionOverride);const i=r?()=>Promise.all(QBt(s,r,n)):()=>Promise.resolve(),l=s.variantChildren&&s.variantChildren.size?(d=0)=>{const{delayChildren:u=0,staggerChildren:h,staggerDirection:m}=a;return uzs(s,t,d,u,h,m,n)}:()=>Promise.resolve(),{when:o}=a;if(o){const[d,u]=o==="beforeChildren"?[i,l]:[l,i];return d().then(()=>u())}else return Promise.all([i(),l(n.delay)])}function uzs(s,t,n=0,r=0,a=0,i=1,l){const o=[];for(const c of s.variantChildren)c.notify("AnimationStart",t),o.push(kGe(c,t,{...l,delay:n+(typeof r=="function"?0:r)+GBt(s.variantChildren,c,r,a,i)}).then(()=>c.notify("AnimationComplete",t)));return Promise.all(o)}function hzs(s,t,n={}){s.notify("AnimationStart",t);let r;if(Array.isArray(t)){const a=t.map(i=>kGe(s,i,n));r=Promise.all(a)}else if(typeof t=="string")r=kGe(s,t,n);else{const a=typeof t=="function"?h7(s,t,n.custom):t;r=Promise.all(QBt(s,a,n))}return r.then(()=>{s.notify("AnimationComplete",t)})}const mzs={test:s=>s==="auto",parse:s=>s},JBt=s=>t=>t.test(s),e9t=[iK,Bo,B4,vA,zOs,OOs,mzs],N0t=s=>e9t.find(JBt(s));function fzs(s){return typeof s=="number"?s===0:s!==null?s==="none"||s==="0"||uBt(s):!0}const pzs=new Set(["brightness","contrast","saturate","opacity"]);function gzs(s){const[t,n]=s.slice(0,-1).split("(");if(t==="drop-shadow")return s;const[r]=n.match(yst)||[];if(!r)return s;const a=n.replace(r,"");let i=pzs.has(t)?1:0;return r!==n&&(i*=100),t+"("+i+a+")"}const xzs=/\b([a-z-]*)\(.*?\)/gu,SGe={...oC,getAnimatableNone:s=>{const t=s.match(xzs);return t?t.map(gzs).join(" "):s}},CGe={...oC,getAnimatableNone:s=>{const t=oC.parse(s);return oC.createTransformer(s)(t.map(r=>typeof r=="number"?0:typeof r=="object"?{...r,alpha:1}:r))}},k0t={...iK,transform:Math.round},yzs={rotate:vA,pathRotation:vA,rotateX:vA,rotateY:vA,rotateZ:vA,scale:Uce,scaleX:Uce,scaleY:Uce,scaleZ:Uce,skew:vA,skewX:vA,skewY:vA,distance:Bo,translateX:Bo,translateY:Bo,translateZ:Bo,x:Bo,y:Bo,z:Bo,perspective:Bo,transformPerspective:Bo,opacity:ase,originX:u0t,originY:u0t,originZ:Bo},BEe={borderWidth:Bo,borderTopWidth:Bo,borderRightWidth:Bo,borderBottomWidth:Bo,borderLeftWidth:Bo,borderRadius:Bo,borderTopLeftRadius:Bo,borderTopRightRadius:Bo,borderBottomRightRadius:Bo,borderBottomLeftRadius:Bo,width:Bo,maxWidth:Bo,height:Bo,maxHeight:Bo,top:Bo,right:Bo,bottom:Bo,left:Bo,inset:Bo,insetBlock:Bo,insetBlockStart:Bo,insetBlockEnd:Bo,insetInline:Bo,insetInlineStart:Bo,insetInlineEnd:Bo,padding:Bo,paddingTop:Bo,paddingRight:Bo,paddingBottom:Bo,paddingLeft:Bo,paddingBlock:Bo,paddingBlockStart:Bo,paddingBlockEnd:Bo,paddingInline:Bo,paddingInlineStart:Bo,paddingInlineEnd:Bo,margin:Bo,marginTop:Bo,marginRight:Bo,marginBottom:Bo,marginLeft:Bo,marginBlock:Bo,marginBlockStart:Bo,marginBlockEnd:Bo,marginInline:Bo,marginInlineStart:Bo,marginInlineEnd:Bo,fontSize:Bo,backgroundPositionX:Bo,backgroundPositionY:Bo,...yzs,zIndex:k0t,fillOpacity:ase,strokeOpacity:ase,numOctaves:k0t},vzs={...BEe,color:Ry,backgroundColor:Ry,outlineColor:Ry,fill:Ry,stroke:Ry,borderColor:Ry,borderTopColor:Ry,borderRightColor:Ry,borderBottomColor:Ry,borderLeftColor:Ry,filter:SGe,WebkitFilter:SGe,mask:CGe,WebkitMask:CGe},t9t=s=>vzs[s],bzs=new Set([SGe,CGe]);function s9t(s,t){let n=t9t(s);return bzs.has(n)||(n=oC),n.getAnimatableNone?n.getAnimatableNone(t):void 0}const _zs=new Set(["auto","none","0"]);function wzs(s,t,n){let r=0,a;for(;r{t.getValue(c).set(d)}),this.resolveNoneKeyframes()}}const Ast=["borderTopLeftRadius","borderTopRightRadius","borderBottomRightRadius","borderBottomLeftRadius"];function Est(s,t,n){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(r=>r!=null)}const AGe=(s,t)=>t&&typeof s=="number"?t.transform(s):s;function s3e(s){return dBt(s)&&"offsetHeight"in s&&!("ownerSVGElement"in s)}const{schedule:Tst}=NBt(queueMicrotask,!1),hS={x:!1,y:!1};function n9t(){return hS.x||hS.y}function Nzs(s){return s==="x"||s==="y"?hS[s]?null:(hS[s]=!0,()=>{hS[s]=!1}):hS.x||hS.y?null:(hS.x=hS.y=!0,()=>{hS.x=hS.y=!1})}function r9t(s,t){const n=Est(s),r=new AbortController,a={passive:!0,...t,signal:r.signal};return[n,a,()=>r.abort()]}function kzs(s){return!(s.pointerType==="touch"||n9t())}function Szs(s,t,n={}){const[r,a,i]=r9t(s,n);return r.forEach(l=>{let o=!1,c=!1,d;const u=()=>{l.removeEventListener("pointerleave",g)},h=y=>{d&&(d(y),d=void 0),u()},m=y=>{o=!1,window.removeEventListener("pointerup",m),window.removeEventListener("pointercancel",m),c&&(c=!1,h(y))},f=()=>{o=!0,window.addEventListener("pointerup",m,a),window.addEventListener("pointercancel",m,a)},g=y=>{if(y.pointerType!=="touch"){if(o){c=!0;return}h(y)}},x=y=>{if(!kzs(y))return;c=!1;const v=t(l,y);typeof v=="function"&&(d=v,l.addEventListener("pointerleave",g,a))};l.addEventListener("pointerenter",x,a),l.addEventListener("pointerdown",f,a)}),i}const a9t=(s,t)=>t?s===t?!0:a9t(s,t.parentElement):!1,Mst=s=>s.pointerType==="mouse"?typeof s.button!="number"||s.button<=0:s.isPrimary!==!1,Czs=new Set(["BUTTON","INPUT","SELECT","TEXTAREA","A"]);function Azs(s){return Czs.has(s.tagName)||s.isContentEditable===!0}const Ezs=new Set(["INPUT","SELECT","TEXTAREA"]);function Tzs(s){return Ezs.has(s.tagName)||s.isContentEditable===!0}const n3e=new WeakSet;function S0t(s){return t=>{t.key==="Enter"&&s(t)}}function k7e(s,t){s.dispatchEvent(new PointerEvent("pointer"+t,{isPrimary:!0,bubbles:!0}))}const Mzs=(s,t)=>{const n=s.currentTarget;if(!n)return;const r=S0t(()=>{if(n3e.has(n))return;k7e(n,"down");const a=S0t(()=>{k7e(n,"up")}),i=()=>k7e(n,"cancel");n.addEventListener("keyup",a,t),n.addEventListener("blur",i,t)});n.addEventListener("keydown",r,t),n.addEventListener("blur",()=>n.removeEventListener("keydown",r),t)};function C0t(s){return Mst(s)&&!n9t()}const A0t=new WeakSet;function Pzs(s,t,n={}){const[r,a,i]=r9t(s,n),l=o=>{const c=o.currentTarget;if(!C0t(o)||A0t.has(o))return;n3e.add(c),n.stopPropagation&&A0t.add(o);const d=t(c,o),u={...a,capture:!0},h=(g,x)=>{window.removeEventListener("pointerup",m,u),window.removeEventListener("pointercancel",f,u),n3e.has(c)&&n3e.delete(c),C0t(g)&&typeof d=="function"&&d(g,{success:x})},m=g=>{h(g,c===window||c===document||n.useGlobalTarget||a9t(c,g.target))},f=g=>{h(g,!1)};window.addEventListener("pointerup",m,u),window.addEventListener("pointercancel",f,u)};return r.forEach(o=>{(n.useGlobalTarget?window:o).addEventListener("pointerdown",l,a),s3e(o)&&(o.addEventListener("focus",d=>Mzs(d,a)),!Azs(o)&&!o.hasAttribute("tabindex")&&(o.tabIndex=0))}),i}function Pst(s){return dBt(s)&&"ownerSVGElement"in s}const r3e=new WeakMap;let KM;const i9t=(s,t,n)=>(r,a)=>a&&a[0]?a[0][s+"Size"]:Pst(r)&&"getBBox"in r?r.getBBox()[t]:r[n],Izs=i9t("inline","width","offsetWidth"),Lzs=i9t("block","height","offsetHeight");function Rzs({target:s,borderBoxSize:t}){var n;(n=r3e.get(s))==null||n.forEach(r=>{r(s,{get width(){return Izs(s,t)},get height(){return Lzs(s,t)}})})}function Dzs(s){s.forEach(Rzs)}function Fzs(){typeof ResizeObserver>"u"||(KM=new ResizeObserver(Dzs))}function Ozs(s,t){KM||Fzs();const n=Est(s);return n.forEach(r=>{let a=r3e.get(r);a||(a=new Set,r3e.set(r,a)),a.add(t),KM==null||KM.observe(r)}),()=>{n.forEach(r=>{const a=r3e.get(r);a==null||a.delete(t),a!=null&&a.size||KM==null||KM.unobserve(r)})}}const a3e=new Set;let JU;function zzs(){JU=()=>{const s={get width(){return window.innerWidth},get height(){return window.innerHeight}};a3e.forEach(t=>t(s))},window.addEventListener("resize",JU)}function Bzs(s){return a3e.add(s),JU||zzs(),()=>{a3e.delete(s),!a3e.size&&typeof JU=="function"&&(window.removeEventListener("resize",JU),JU=void 0)}}function E0t(s,t){return typeof s=="function"?Bzs(s):Ozs(s,t)}function $zs(s){return Pst(s)&&s.tagName==="svg"}const Uzs=[...e9t,Ry,oC],qzs=s=>Uzs.find(JBt(s)),T0t=()=>({translate:0,scale:1,origin:0,originPoint:0}),eq=()=>({x:T0t(),y:T0t()}),M0t=()=>({min:0,max:0}),h0=()=>({x:M0t(),y:M0t()}),Vzs=new WeakMap;function e6e(s){return s!==null&&typeof s=="object"&&typeof s.start=="function"}function ise(s){return typeof s=="string"||Array.isArray(s)}const Ist=["animate","whileInView","whileFocus","whileHover","whileTap","whileDrag","exit"],Lst=["initial",...Ist];function t6e(s){return e6e(s.animate)||Lst.some(t=>ise(s[t]))}function o9t(s){return!!(t6e(s)||s.variants)}function Hzs(s,t,n){for(const r in t){const a=t[r],i=n[r];if(pb(a))s.addValue(r,a);else if(pb(i))s.addValue(r,PG(a,{owner:s}));else if(i!==a)if(s.hasValue(r)){const l=s.getValue(r);l.liveStyle===!0?l.jump(a):l.hasAnimated||l.set(a)}else{const l=s.getStaticValue(r);s.addValue(r,PG(l!==void 0?l:a,{owner:s}))}}for(const r in n)t[r]===void 0&&s.removeValue(r);return t}const EGe={current:null},l9t={current:!1},Gzs=typeof window<"u";function Wzs(){if(l9t.current=!0,!!Gzs)if(window.matchMedia){const s=window.matchMedia("(prefers-reduced-motion)"),t=()=>EGe.current=s.matches;s.addEventListener("change",t),t()}else EGe.current=!1}const P0t=["AnimationStart","AnimationComplete","Update","BeforeLayoutMeasure","LayoutMeasure","LayoutAnimationStart","LayoutAnimationComplete"];let $Ee={};function c9t(s){$Ee=s}function Kzs(){return $Ee}class Yzs{scrapeMotionValuesFromProps(t,n,r){return{}}constructor({parent:t,props:n,presenceContext:r,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=jst,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 f=v_.now();this.renderScheduledAtthis.bindToMotionValue(i,a)),this.reducedMotionConfig==="never"?this.shouldReduceMotion=!1:this.reducedMotionConfig==="always"?this.shouldReduceMotion=!0:(l9t.current||Wzs(),this.shouldReduceMotion=EGe.current),this.shouldSkipAnimations=this.skipAnimationsConfig??!1,(r=this.parent)==null||r.addChild(this),this.update(this.props,this.presenceContext),this.hasBeenMounted=!0}unmount(){var t;this.projection&&this.projection.unmount(),LL(this.notifyUpdate),LL(this.render),this.valueSubscriptions.forEach(n=>n()),this.valueSubscriptions.clear(),this.removeFromVariantTree&&this.removeFromVariantTree(),(t=this.parent)==null||t.removeChild(this);for(const n in this.events)this.events[n].clear();for(const n in this.features){const r=this.features[n];r&&(r.unmount(),r.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,n){if(this.valueSubscriptions.has(t)&&this.valueSubscriptions.get(t)(),n.accelerate&&HBt.has(t)&&this.current instanceof HTMLElement){const{factory:l,keyframes:o,times:c,ease:d,duration:u}=n.accelerate,h=new qBt({element:this.current,name:t,keyframes:o,times:c,ease:d,duration:v2(u)}),m=l(h);this.valueSubscriptions.set(t,()=>{m(),h.cancel()});return}const r=lK.has(t);r&&this.onBindTransform&&this.onBindTransform();const a=n.on("change",l=>{this.latestValues[t]=l,this.props.onUpdate&&Sf.preRender(this.notifyUpdate),r&&this.projection&&(this.projection.isTransformDirty=!0),this.scheduleRender()});let i;typeof window<"u"&&window.MotionCheckAppearSync&&(i=window.MotionCheckAppearSync(this,t,n)),this.valueSubscriptions.set(t,()=>{a(),i&&i()})}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 $Ee){const n=$Ee[t];if(!n)continue;const{isEnabled:r,Feature:a}=n;if(!this.features[t]&&a&&r(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):h0()}getStaticValue(t){return this.latestValues[t]}setStaticValue(t,n){this.latestValues[t]=n}update(t,n){(t.transformTemplate||this.props.transformTemplate)&&this.scheduleRender(),this.prevProps=this.props,this.props=t,this.prevPresenceContext=this.presenceContext,this.presenceContext=n;for(let r=0;rn.variantChildren.delete(t)}addValue(t,n){const r=this.values.get(t);n!==r&&(r&&this.removeValue(t),this.bindToMotionValue(t,n),this.values.set(t,n),this.latestValues[t]=n.get())}removeValue(t){this.values.delete(t);const n=this.valueSubscriptions.get(t);n&&(n(),this.valueSubscriptions.delete(t)),delete this.latestValues[t],this.removeValueFromRenderState(t,this.renderState)}hasValue(t){return this.values.has(t)}getValue(t,n){if(this.props.values&&this.props.values[t])return this.props.values[t];let r=this.values.get(t);return r===void 0&&n!==void 0&&(r=PG(n===null?void 0:n,{owner:this}),this.addValue(t,r)),r}readValue(t,n){let r=this.latestValues[t]!==void 0||!this.current?this.latestValues[t]:this.getBaseTargetFromProps(this.props,t)??this.readValueFromInstance(this.current,t,this.options);return r!=null&&(typeof r=="string"&&(cBt(r)||uBt(r))?r=parseFloat(r):!qzs(r)&&oC.test(n)&&(r=s9t(t,n)),this.setBaseTarget(t,pb(r)?r.get():r)),pb(r)?r.get():r}setBaseTarget(t,n){this.baseTarget[t]=n}getBaseTarget(t){var i;const{initial:n}=this.props;let r;if(typeof n=="string"||typeof n=="object"){const l=Sst(this.props,n,(i=this.presenceContext)==null?void 0:i.custom);l&&(r=l[t])}if(n&&r!==void 0)return r;const a=this.getBaseTargetFromProps(this.props,t);return a!==void 0&&!pb(a)?a:this.initialValues[t]!==void 0&&r===void 0?void 0:this.baseTarget[t]}on(t,n){return this.events[t]||(this.events[t]=new fst),this.events[t].add(n)}notify(t,...n){this.events[t]&&this.events[t].notify(...n)}scheduleRenderMicrotask(){Tst.render(this.render)}}class d9t extends Yzs{constructor(){super(...arguments),this.KeyframeResolver=jzs}sortInstanceNodePosition(t,n){return t.compareDocumentPosition(n)&2?1:-1}getBaseTargetFromProps(t,n){const r=t.style;return r?r[n]:void 0}removeValueFromRenderState(t,{vars:n,style:r}){delete n[t],delete r[t]}handleChildMotionValue(){this.childSubscription&&(this.childSubscription(),delete this.childSubscription);const{children:t}=this.props;pb(t)&&(this.childSubscription=t.on("change",n=>{this.current&&(this.current.textContent=`${n}`)}))}}class d6{constructor(t){this.isMounted=!1,this.node=t}update(){}}function u9t({top:s,left:t,right:n,bottom:r}){return{x:{min:t,max:n},y:{min:s,max:r}}}function Zzs({x:s,y:t}){return{top:t.min,right:s.max,bottom:t.max,left:s.min}}function Xzs(s,t){if(!t)return s;const n=t({x:s.left,y:s.top}),r=t({x:s.right,y:s.bottom});return{top:n.y,left:n.x,bottom:r.y,right:r.x}}function S7e(s){return s===void 0||s===1}function TGe({scale:s,scaleX:t,scaleY:n}){return!S7e(s)||!S7e(t)||!S7e(n)}function FO(s){return TGe(s)||h9t(s)||s.z||s.rotate||s.rotateX||s.rotateY||s.skewX||s.skewY}function h9t(s){return I0t(s.x)||I0t(s.y)}function I0t(s){return s&&s!=="0%"}function UEe(s,t,n){const r=s-n,a=t*r;return n+a}function L0t(s,t,n,r,a){return a!==void 0&&(s=UEe(s,a,r)),UEe(s,n,r)+t}function MGe(s,t=0,n=1,r,a){s.min=L0t(s.min,t,n,r,a),s.max=L0t(s.max,t,n,r,a)}function m9t(s,{x:t,y:n}){MGe(s.x,t.translate,t.scale,t.originPoint),MGe(s.y,n.translate,n.scale,n.originPoint)}const R0t=.999999999999,D0t=1.0000000000001;function Qzs(s,t,n,r=!1){var o;const a=n.length;if(!a)return;t.x=t.y=1;let i,l;for(let c=0;cR0t&&(t.x=1),t.yR0t&&(t.y=1)}function a4(s,t){s.min+=t,s.max+=t}function F0t(s,t,n,r,a=.5){const i=Nf(s.min,s.max,a);MGe(s,t,n,i,r)}function O0t(s,t){return typeof s=="string"?parseFloat(s)/100*(t.max-t.min):s}function i3e(s,t,n){const r=n??s;F0t(s.x,O0t(t.x,r.x),t.scaleX,t.scale,t.originX),F0t(s.y,O0t(t.y,r.y),t.scaleY,t.scale,t.originY)}function f9t(s,t){return u9t(Xzs(s.getBoundingClientRect(),t))}function Jzs(s,t,n){const r=f9t(s,n),{scroll:a}=t;return a&&(a4(r.x,a.offset.x),a4(r.y,a.offset.y)),r}const e7s={x:"translateX",y:"translateY",z:"translateZ",transformPerspective:"perspective"},t7s=oK.length;function s7s(s,t,n){let r="",a=!0;for(let l=0;l{if(!t.target)return s;if(typeof s=="string")if(Bo.test(s))s=parseFloat(s);else return s;const n=z0t(s,t.target.x),r=z0t(s,t.target.y);return`${n}% ${r}%`}},n7s={correct:(s,{treeScale:t,projectionDelta:n})=>{const r=s,a=oC.parse(s);if(a.length>5)return r;const i=oC.createTransformer(s),l=typeof a[0]!="number"?1:0,o=n.x.scale*t.x,c=n.y.scale*t.y;a[0+l]/=o,a[1+l]/=c;const d=Nf(o,c,.5);return typeof a[2+l]=="number"&&(a[2+l]/=d),typeof a[3+l]=="number"&&(a[3+l]/=d),i(a)}},PGe={borderRadius:{...MZ,applyTo:[...Ast]},borderTopLeftRadius:MZ,borderTopRightRadius:MZ,borderBottomLeftRadius:MZ,borderBottomRightRadius:MZ,boxShadow:n7s};function g9t(s,{layout:t,layoutId:n}){return lK.has(s)||s.startsWith("origin")||(t||n!==void 0)&&(!!PGe[s]||s==="opacity")}function Dst(s,t,n){var l;const r=s.style,a=t==null?void 0:t.style,i={};if(!r)return i;for(const o in r)(pb(r[o])||a&&pb(a[o])||g9t(o,s)||((l=n==null?void 0:n.getValue(o))==null?void 0:l.liveStyle)!==void 0)&&(i[o]=r[o]);return i}function r7s(s){return window.getComputedStyle(s)}class a7s extends d9t{constructor(){super(...arguments),this.type="html",this.renderInstance=p9t}mount(t){QLe(!!t.style),super.mount(t)}readValueFromInstance(t,n){var r;if(lK.has(n))return(r=this.projection)!=null&&r.isProjecting?xGe(n):k8s(t,n);{const a=r7s(t),i=(SBt(n)?a.getPropertyValue(n):a[n])||0;return typeof i=="string"?i.trim():i}}measureInstanceViewportBox(t,{transformPagePoint:n}){return f9t(t,n)}build(t,n,r){Rst(t,n,r.transformTemplate)}scrapeMotionValuesFromProps(t,n,r){return Dst(t,n,r)}}const i7s={offset:"stroke-dashoffset",array:"stroke-dasharray"},o7s={offset:"strokeDashoffset",array:"strokeDasharray"};function l7s(s,t,n=1,r=0,a=!0){s.pathLength=1;const i=a?i7s:o7s;s[i.offset]=`${-r}`,s[i.array]=`${t} ${n}`}const c7s=["offsetDistance","offsetPath","offsetRotate","offsetAnchor"];function x9t(s,{attrX:t,attrY:n,attrScale:r,pathLength:a,pathSpacing:i=1,pathOffset:l=0,...o},c,d,u){if(Rst(s,o,d),c){s.style.viewBox&&(s.attrs.viewBox=s.style.viewBox);return}s.attrs=s.style,s.style={};const{attrs:h,style:m}=s;h.transform&&(m.transform=h.transform,delete h.transform),(m.transform||h.transformOrigin)&&(m.transformOrigin=h.transformOrigin??"50% 50%",delete h.transformOrigin),m.transform&&(m.transformBox=(u==null?void 0:u.transformBox)??"fill-box",delete h.transformBox);for(const f of c7s)h[f]!==void 0&&(m[f]=h[f],delete h[f]);t!==void 0&&(h.x=t),n!==void 0&&(h.y=n),r!==void 0&&(h.scale=r),a!==void 0&&l7s(h,a,i,l,!1)}const y9t=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"]),v9t=s=>typeof s=="string"&&s.toLowerCase()==="svg";function d7s(s,t,n,r){p9t(s,t,void 0,r);for(const a in t.attrs)s.setAttribute(y9t.has(a)?a:Cst(a),t.attrs[a])}function b9t(s,t,n){const r=Dst(s,t,n);for(const a in s)if(pb(s[a])||pb(t[a])){const i=oK.indexOf(a)!==-1?"attr"+a.charAt(0).toUpperCase()+a.substring(1):a;r[i]=s[a]}return r}class u7s extends d9t{constructor(){super(...arguments),this.type="svg",this.isSVGTag=!1,this.measureInstanceViewportBox=h0}getBaseTargetFromProps(t,n){return t[n]}readValueFromInstance(t,n){if(lK.has(n)){const r=t9t(n);return r&&r.default||0}return n=y9t.has(n)?n:Cst(n),t.getAttribute(n)}scrapeMotionValuesFromProps(t,n,r){return b9t(t,n,r)}build(t,n,r){x9t(t,n,this.isSVGTag,r.transformTemplate,r.style)}renderInstance(t,n,r,a){d7s(t,n,r,a)}mount(t){this.isSVGTag=v9t(t.tagName),super.mount(t)}}const h7s=Lst.length;function _9t(s){if(!s)return;if(!s.isControllingVariants){const n=s.parent?_9t(s.parent)||{}:{};return s.props.initial!==void 0&&(n.initial=s.props.initial),n}const t={};for(let n=0;nPromise.all(t.map(({animation:n,options:r})=>hzs(s,n,r)))}function g7s(s){let t=p7s(s),n=B0t(),r=!0,a=!1;const i=d=>(u,h)=>{var f;const m=h7(s,h,d==="exit"?(f=s.presenceContext)==null?void 0:f.custom:void 0);if(m){const{transition:g,transitionEnd:x,...y}=m;u={...u,...y,...x}}return u};function l(d){t=d(s)}function o(d){const{props:u}=s,h=_9t(s.parent)||{},m=[],f=new Set;let g={},x=1/0;for(let v=0;vx&&C,D=!1;const O=Array.isArray(S)?S:[S];let U=O.reduce(i(b),{});E===!1&&(U={});const{prevResolvedValues:W={}}=w,V={...W,...U},G=ae=>{R=!0,f.has(ae)&&(D=!0,f.delete(ae)),w.needsAnimating[ae]=!0;const ie=s.getValue(ae);ie&&(ie.liveStyle=!1)};for(const ae in V){const ie=U[ae],ne=W[ae];if(g.hasOwnProperty(ae))continue;let te=!1;jGe(ie)&&jGe(ne)?te=!w9t(ie,ne)||P:te=ie!==ne,te?ie!=null?G(ae):f.add(ae):ie!==void 0&&f.has(ae)?G(ae):w.protectedKeys[ae]=!0}w.prevProp=S,w.prevResolvedValues=U,w.isActive&&(g={...g,...U}),(r||a)&&s.blockInitialAnimation&&(R=!1);const Y=I&&P;R&&(!Y||D)&&m.push(...O.map(ae=>{const ie={type:b};if(typeof ae=="string"&&(r||a)&&!Y&&s.manuallyAnimateOnMount&&s.parent){const{parent:ne}=s,te=h7(ne,ae);if(ne.enteringChildren&&te){const{delayChildren:J}=te.transition||{};ie.delay=GBt(ne.enteringChildren,s,J)}}return{animation:ae,options:ie}}))}if(f.size){const v={};if(typeof u.initial!="boolean"){const b=h7(s,Array.isArray(u.initial)?u.initial[0]:u.initial);b&&b.transition&&(v.transition=b.transition)}f.forEach(b=>{const w=s.getBaseTarget(b),S=s.getValue(b);S&&(S.liveStyle=!0),v[b]=w??null}),m.push({animation:v})}let y=!!m.length;return r&&(u.initial===!1||u.initial===u.animate)&&!s.manuallyAnimateOnMount&&(y=!1),r=!1,a=!1,y?t(m):Promise.resolve()}function c(d,u){var m;if(n[d].isActive===u)return Promise.resolve();(m=s.variantChildren)==null||m.forEach(f=>{var g;return(g=f.animationState)==null?void 0:g.setActive(d,u)}),n[d].isActive=u;const h=o(d);for(const f in n)n[f].protectedKeys={};return h}return{animateChanges:o,setActive:c,setAnimateFunction:l,getState:()=>n,reset:()=>{n=B0t(),a=!0}}}function x7s(s,t){return typeof t=="string"?t!==s:Array.isArray(t)?!w9t(t,s):!1}function xR(s=!1){return{isActive:s,protectedKeys:{},needsAnimating:{},prevResolvedValues:{}}}function B0t(){return{animate:xR(!0),whileInView:xR(),whileHover:xR(),whileTap:xR(),whileDrag:xR(),whileFocus:xR(),exit:xR()}}function IGe(s,t){s.min=t.min,s.max=t.max}function sS(s,t){IGe(s.x,t.x),IGe(s.y,t.y)}function $0t(s,t){s.translate=t.translate,s.scale=t.scale,s.originPoint=t.originPoint,s.origin=t.origin}const j9t=1e-4,y7s=1-j9t,v7s=1+j9t,N9t=.01,b7s=0-N9t,_7s=0+N9t;function b_(s){return s.max-s.min}function w7s(s,t,n){return Math.abs(s-t)<=n}function U0t(s,t,n,r=.5){s.origin=r,s.originPoint=Nf(t.min,t.max,s.origin),s.scale=b_(n)/b_(t),s.translate=Nf(n.min,n.max,s.origin)-s.originPoint,(s.scale>=y7s&&s.scale<=v7s||isNaN(s.scale))&&(s.scale=1),(s.translate>=b7s&&s.translate<=_7s||isNaN(s.translate))&&(s.translate=0)}function jee(s,t,n,r){U0t(s.x,t.x,n.x,r?r.originX:void 0),U0t(s.y,t.y,n.y,r?r.originY:void 0)}function q0t(s,t,n,r=0){const a=r?Nf(n.min,n.max,r):n.min;s.min=a+t.min,s.max=s.min+b_(t)}function j7s(s,t,n,r){q0t(s.x,t.x,n.x,r==null?void 0:r.x),q0t(s.y,t.y,n.y,r==null?void 0:r.y)}function V0t(s,t,n,r=0){const a=r?Nf(n.min,n.max,r):n.min;s.min=t.min-a,s.max=s.min+b_(t)}function qEe(s,t,n,r){V0t(s.x,t.x,n.x,r==null?void 0:r.x),V0t(s.y,t.y,n.y,r==null?void 0:r.y)}function H0t(s,t,n,r,a){return s-=t,s=UEe(s,1/n,r),a!==void 0&&(s=UEe(s,1/a,r)),s}function N7s(s,t=0,n=1,r=.5,a,i=s,l=s){if(B4.test(t)&&(t=parseFloat(t),t=Nf(l.min,l.max,t/100)-l.min),typeof t!="number")return;let o=Nf(i.min,i.max,r);s===i&&(o-=t),s.min=H0t(s.min,t,n,o,a),s.max=H0t(s.max,t,n,o,a)}function G0t(s,t,[n,r,a],i,l){N7s(s,t[n],t[r],t[a],t.scale,i,l)}const k7s=["x","scaleX","originX"],S7s=["y","scaleY","originY"];function W0t(s,t,n,r){G0t(s.x,t,k7s,n?n.x:void 0,r?r.x:void 0),G0t(s.y,t,S7s,n?n.y:void 0,r?r.y:void 0)}function K0t(s){return s.translate===0&&s.scale===1}function k9t(s){return K0t(s.x)&&K0t(s.y)}function Y0t(s,t){return s.min===t.min&&s.max===t.max}function C7s(s,t){return Y0t(s.x,t.x)&&Y0t(s.y,t.y)}function Z0t(s,t){return Math.round(s.min)===Math.round(t.min)&&Math.round(s.max)===Math.round(t.max)}function S9t(s,t){return Z0t(s.x,t.x)&&Z0t(s.y,t.y)}function X0t(s){return b_(s.x)/b_(s.y)}function Q0t(s,t){return s.translate===t.translate&&s.scale===t.scale&&s.originPoint===t.originPoint}function j5(s){return[s("x"),s("y")]}function A7s(s,t,n){let r="";const a=s.x.translate/t.x,i=s.y.translate/t.y,l=(n==null?void 0:n.z)||0;if((a||i||l)&&(r=`translate3d(${a}px, ${i}px, ${l}px) `),(t.x!==1||t.y!==1)&&(r+=`scale(${1/t.x}, ${1/t.y}) `),n){const{transformPerspective:d,rotate:u,pathRotation:h,rotateX:m,rotateY:f,skewX:g,skewY:x}=n;d&&(r=`perspective(${d}px) ${r}`),u&&(r+=`rotate(${u}deg) `),h&&(r+=`rotate(${h}deg) `),m&&(r+=`rotateX(${m}deg) `),f&&(r+=`rotateY(${f}deg) `),g&&(r+=`skewX(${g}deg) `),x&&(r+=`skewY(${x}deg) `)}const o=s.x.scale*t.x,c=s.y.scale*t.y;return(o!==1||c!==1)&&(r+=`scale(${o}, ${c})`),r||"none"}const E7s=Ast.length,J0t=s=>typeof s=="string"?parseFloat(s):s,evt=s=>typeof s=="number"||Bo.test(s);function T7s(s,t,n,r,a,i){a?(s.opacity=Nf(0,n.opacity??1,M7s(r)),s.opacityExit=Nf(t.opacity??1,0,P7s(r))):i&&(s.opacity=Nf(t.opacity??1,n.opacity??1,r));for(let l=0;lrt?1:n(rse(s,t,r))}function I7s(s,t,n){const r=pb(s)?s:PG(s);return r.start(kst("",r,t,n)),r.animation}function ose(s,t,n,r={passive:!0}){return s.addEventListener(t,n,r),()=>s.removeEventListener(t,n,r)}const L7s=(s,t)=>s.depth-t.depth;class R7s{constructor(){this.children=[],this.isDirty=!1}add(t){mst(this.children,t),this.isDirty=!0}remove(t){REe(this.children,t),this.isDirty=!0}forEach(t){this.isDirty&&this.children.sort(L7s),this.isDirty=!1,this.children.forEach(t)}}function D7s(s,t){const n=v_.now(),r=({timestamp:a})=>{const i=a-n;i>=t&&(LL(r),s(i-t))};return Sf.setup(r,!0),()=>LL(r)}function o3e(s){return pb(s)?s.get():s}class F7s{constructor(){this.members=[]}add(t){mst(this.members,t);for(let n=this.members.length-1;n>=0;n--){const r=this.members[n];if(r===t||r===this.lead||r===this.prevLead)continue;const a=r.instance;(!a||a.isConnected===!1)&&!r.snapshot&&(REe(this.members,r),r.unmount())}t.scheduleRender()}remove(t){if(REe(this.members,t),t===this.prevLead&&(this.prevLead=void 0),t===this.lead){const n=this.members[this.members.length-1];n&&this.promote(n)}}relegate(t){var n;for(let r=this.members.indexOf(t)-1;r>=0;r--){const a=this.members[r];if(a.isPresent!==!1&&((n=a.instance)==null?void 0:n.isConnected)!==!1)return this.promote(a),!0}return!1}promote(t,n){var a;const r=this.lead;if(t!==r&&(this.prevLead=r,this.lead=t,t.show(),r)){r.updateSnapshot(),t.scheduleRender();const{layoutDependency:i}=r.options,{layoutDependency:l}=t.options;(i===void 0||i!==l)&&(t.resumeFrom=r,n&&(r.preserveOpacity=!0),r.snapshot&&(t.snapshot=r.snapshot,t.snapshot.latestValues=r.animationValues||r.latestValues),(a=t.root)!=null&&a.isUpdating&&(t.isLayoutDirty=!0)),t.options.crossfade===!1&&r.hide()}}exitAnimationComplete(){this.members.forEach(t=>{var n,r,a,i,l;(r=(n=t.options).onExitComplete)==null||r.call(n),(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 l3e={hasAnimatedSinceResize:!0,hasEverUpdated:!1},C7e=["","X","Y","Z"],O7s=1e3;let z7s=0;function A7e(s,t,n,r){const{latestValues:a}=t;a[s]&&(n[s]=a[s],t.setStaticValue(s,0),r&&(r[s]=0))}function A9t(s){if(s.hasCheckedOptimisedAppear=!0,s.root===s)return;const{visualElement:t}=s.options;if(!t)return;const n=XBt(t);if(window.MotionHasOptimisedAnimation(n,"transform")){const{layout:a,layoutId:i}=s.options;window.MotionCancelOptimisedAnimation(n,"transform",Sf,!(a||i))}const{parent:r}=s;r&&!r.hasCheckedOptimisedAppear&&A9t(r)}function E9t({attachResizeListener:s,defaultParent:t,measureScroll:n,checkIsScrollRoot:r,resetTransform:a}){return class{constructor(l={},o=t==null?void 0:t()){this.id=z7s++,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(U7s),this.nodes.forEach(K7s),this.nodes.forEach(Y7s),this.nodes.forEach(q7s)},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;Sf.read(()=>{h=window.innerWidth}),s(l,()=>{const f=window.innerWidth;f!==h&&(h=f,this.root.updateBlockedByResize=!0,u&&u(),u=D7s(m,250),l3e.hasAnimatedSinceResize&&(l3e.hasAnimatedSinceResize=!1,this.nodes.forEach(rvt)))})}o&&this.root.registerSharedNode(o,this),this.options.animate!==!1&&d&&(o||c)&&this.addEventListener("didUpdate",({delta:u,hasLayoutChanged:h,hasRelativeLayoutChanged:m,layout:f})=>{if(this.isTreeAnimationBlocked()){this.target=void 0,this.relativeTarget=void 0;return}const g=this.options.transition||d.getDefaultTransition()||eBs,{onLayoutAnimationStart:x,onLayoutAnimationComplete:y}=d.getProps(),v=!this.targetLayout||!S9t(this.targetLayout,f),b=!h&&m;if(this.options.layoutRoot||this.resumeFrom||b||h&&(v||!this.currentAnimation)){this.resumeFrom&&(this.resumingFrom=this.resumeFrom,this.resumingFrom.resumingFrom=void 0);const w={...Nst(g,"layout"),onPlay:x,onComplete:y};(d.shouldReduceMotion||this.options.layoutRoot)&&(w.delay=0,w.type=!1),this.startAnimation(w),this.setAnimationOrigin(u,b,w.path)}else h||rvt(this),this.isLead()&&this.options.onExitComplete&&this.options.onExitComplete();this.targetLayout=f})}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(),LL(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(Z7s),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&&A9t(this),!this.root.isUpdating&&this.root.startUpdate(),this.isLayoutDirty)return;this.isLayoutDirty=!0;for(let u=0;u{this.isLayoutDirty?this.root.didUpdate():this.root.checkUpdateFailed()})}updateSnapshot(){this.snapshot||!this.instance||(this.snapshot=this.measure(),this.snapshot&&!b_(this.snapshot.measuredBox.x)&&!b_(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 I=E/1e3,P=C==null?void 0:C(I);P?(m.x.translate=P.x,m.x.scale=Nf(l.x.scale,1,I),m.x.origin=l.x.origin,m.x.originPoint=l.x.originPoint,m.y.translate=P.y,m.y.scale=Nf(l.y.scale,1,I),m.y.origin=l.y.origin,m.y.originPoint=l.y.originPoint):(avt(m.x,l.x,I),avt(m.y,l.y,I)),this.setTargetDelta(m),this.relativeTarget&&this.relativeTargetOrigin&&this.layout&&this.relativeParent&&this.relativeParent.layout&&(qEe(f,this.layout.layoutBox,this.relativeParent.layout.layoutBox,this.options.layoutAnchor||void 0),Q7s(this.relativeTarget,this.relativeTargetOrigin,f,I),S&&C7s(this.relativeTarget,S)&&(this.isProjectionDirty=!1),S||(S=h0()),sS(S,this.relativeTarget)),y&&(this.animationValues=h,T7s(h,u,this.latestValues,I,w,b)),P&&P.rotate!==void 0&&(this.animationValues||(this.animationValues=h),this.animationValues.pathRotation=P.rotate),this.root.scheduleUpdateProjection(),this.scheduleRender(),this.animationProgress=I},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&&(LL(this.pendingAnimation),this.pendingAnimation=void 0),this.pendingAnimation=Sf.update(()=>{l3e.hasAnimatedSinceResize=!0,this.motionValue||(this.motionValue=PG(0)),this.motionValue.jump(0,!1),this.currentAnimation=I7s(this.motionValue,[0,1e3],{...l,velocity:0,isSync:!0,onUpdate:u=>{this.mixTargetDelta(u),l.onUpdate&&l.onUpdate(u)},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(O7s),this.currentAnimation.stop()),this.completeAnimation()}applyTransformsToTarget(){const l=this.getLead();let{targetWithTransforms:o,target:c,layout:d,latestValues:u}=l;if(!(!o||!c||!d)){if(this!==l&&this.layout&&d&&T9t(this.options.animationType,this.layout.layoutBox,d.layoutBox)){c=this.target||h0();const h=b_(this.layout.layoutBox.x);c.x.min=l.target.x.min,c.x.max=c.x.min+h;const m=b_(this.layout.layoutBox.y);c.y.min=l.target.y.min,c.y.max=c.y.min+m}sS(o,c),i3e(o,u),jee(this.projectionDeltaWithTransform,this.layoutCorrected,o,u)}}registerSharedNode(l,o){this.sharedNodes.has(l)||this.sharedNodes.set(l,new F7s),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&&A7e("z",l,d,this.animationValues);for(let u=0;u{var o;return(o=l.currentAnimation)==null?void 0:o.stop()}),this.root.nodes.forEach(svt),this.root.sharedNodes.clear()}}}function B7s(s){s.updateLayout()}function $7s(s){var n;const t=((n=s.resumeFrom)==null?void 0:n.snapshot)||s.snapshot;if(s.isLead()&&s.layout&&t&&s.hasListeners("didUpdate")){const{layoutBox:r,measuredBox:a}=s.layout,{animationType:i}=s.options,l=t.source!==s.layout.source;if(i==="size")j5(h=>{const m=l?t.measuredBox[h]:t.layoutBox[h],f=b_(m);m.min=r[h].min,m.max=m.min+f});else if(i==="x"||i==="y"){const h=i==="x"?"y":"x";IGe(l?t.measuredBox[h]:t.layoutBox[h],r[h])}else T9t(i,t.layoutBox,r)&&j5(h=>{const m=l?t.measuredBox[h]:t.layoutBox[h],f=b_(r[h]);m.max=m.min+f,s.relativeTarget&&!s.currentAnimation&&(s.isProjectionDirty=!0,s.relativeTarget[h].max=s.relativeTarget[h].min+f)});const o=eq();jee(o,r,t.layoutBox);const c=eq();l?jee(c,s.applyTransform(a,!0),t.measuredBox):jee(c,r,t.layoutBox);const d=!k9t(o);let u=!1;if(!s.resumeFrom){const h=s.getClosestProjectingParent();if(h&&!h.resumeFrom){const{snapshot:m,layout:f}=h;if(m&&f){const g=s.options.layoutAnchor||void 0,x=h0();qEe(x,t.layoutBox,m.layoutBox,g);const y=h0();qEe(y,r,f.layoutBox,g),S9t(x,y)||(u=!0),h.options.layoutRoot&&(s.relativeTarget=y,s.relativeTargetOrigin=x,s.relativeParent=h)}}}s.notifyListeners("didUpdate",{layout:r,snapshot:t,delta:c,layoutDelta:o,hasLayoutChanged:d,hasRelativeLayoutChanged:u})}else if(s.isLead()){const{onExitComplete:r}=s.options;r&&r()}s.options.transition=void 0}function U7s(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 q7s(s){s.isProjectionDirty=s.isSharedProjectionDirty=s.isTransformDirty=!1}function V7s(s){s.clearSnapshot()}function svt(s){s.clearMeasurements()}function H7s(s){s.isLayoutDirty=!0,s.updateLayout()}function nvt(s){s.isLayoutDirty=!1}function G7s(s){s.isAnimationBlocked&&s.layout&&!s.isLayoutDirty&&(s.snapshot=s.layout,s.isLayoutDirty=!0)}function W7s(s){const{visualElement:t}=s.options;t&&t.getProps().onBeforeLayoutMeasure&&t.notify("BeforeLayoutMeasure"),s.resetTransform()}function rvt(s){s.finishAnimation(),s.targetDelta=s.relativeTarget=s.target=void 0,s.isProjectionDirty=!0}function K7s(s){s.resolveTargetDelta()}function Y7s(s){s.calcProjection()}function Z7s(s){s.resetSkewAndRotation()}function X7s(s){s.removeLeadSnapshot()}function avt(s,t,n){s.translate=Nf(t.translate,0,n),s.scale=Nf(t.scale,1,n),s.origin=t.origin,s.originPoint=t.originPoint}function ivt(s,t,n,r){s.min=Nf(t.min,n.min,r),s.max=Nf(t.max,n.max,r)}function Q7s(s,t,n,r){ivt(s.x,t.x,n.x,r),ivt(s.y,t.y,n.y,r)}function J7s(s){return s.animationValues&&s.animationValues.opacityExit!==void 0}const eBs={duration:.45,ease:[.4,0,.1,1]},ovt=s=>typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().includes(s),lvt=ovt("applewebkit/")&&!ovt("chrome/")?Math.round:ak;function cvt(s){s.min=lvt(s.min),s.max=lvt(s.max)}function tBs(s){cvt(s.x),cvt(s.y)}function T9t(s,t,n){return s==="position"||s==="preserve-aspect"&&!w7s(X0t(t),X0t(n),.2)}function sBs(s){var t;return s!==s.root&&((t=s.scroll)==null?void 0:t.wasRoot)}const nBs=E9t({attachResizeListener:(s,t)=>ose(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}),E7e={current:void 0},M9t=E9t({measureScroll:s=>({x:s.scrollLeft,y:s.scrollTop}),defaultParent:()=>{if(!E7e.current){const s=new nBs({});s.mount(window),s.setOptions({layoutScroll:!0}),E7e.current=s}return E7e.current},resetTransform:(s,t)=>{s.style.transform=t!==void 0?t:"none"},checkIsScrollRoot:s=>window.getComputedStyle(s).position==="fixed"}),Fst=j.createContext({transformPagePoint:s=>s,isStatic:!1,reducedMotion:"never"});function dvt(s,t){if(typeof s=="function")return s(t);s!=null&&(s.current=t)}function rBs(...s){return t=>{let n=!1;const r=s.map(a=>{const i=dvt(a,t);return!n&&typeof i=="function"&&(n=!0),i});if(n)return()=>{for(let a=0;a{const{width:f,height:g,top:x,left:y,right:v,bottom:b,direction:w}=c.current;if(t||i===!1||!o.current||!f||!g)return;const S=w==="rtl",C=n==="left"?S?`right: ${v}`:`left: ${y}`:S?`left: ${y}`:`right: ${v}`,E=r==="bottom"?`bottom: ${b}`:`top: ${x}`;o.current.dataset.motionPopId=l;const I=document.createElement("style");d&&(I.nonce=d);const P=a??document.head;return P.appendChild(I),I.sheet&&I.sheet.insertRule(` [data-motion-pop-id="${l}"] { position: absolute !important; width: ${f}px !important; height: ${g}px !important; ${C}px !important; ${E}px !important; } `),()=>{var R;(R=o.current)==null||R.removeAttribute("data-motion-pop-id"),P.contains(I)&&P.removeChild(I)}},[t]),e.jsx(iBs,{isPresent:t,childRef:o,sizeRef:c,pop:i,children:i===!1?s:j.cloneElement(s,{ref:h})})}const lBs=({children:s,initial:t,isPresent:n,onExitComplete:r,custom:a,presenceAffectsLayout:i,mode:l,anchorX:o,anchorY:c,root:d})=>{const u=ust(cBs),h=j.useId(),m=j.useRef(n),f=j.useRef(r);hst(()=>{m.current=n,f.current=r});let g=!0,x=j.useMemo(()=>(g=!1,{id:h,initial:t,isPresent:n,custom:a,onExitComplete:y=>{u.set(y,!0);for(const v of u.values())if(!v)return;r&&r()},register:y=>(u.set(y,!1),()=>{var v;u.delete(y),!m.current&&!u.size&&((v=f.current)==null||v.call(f))})}),[n,u,r]);return i&&g&&(x={...x}),j.useMemo(()=>{u.forEach((y,v)=>u.set(v,!1))},[n]),j.useEffect(()=>{!n&&!u.size&&r&&r()},[n]),s=e.jsx(oBs,{pop:l==="popLayout",isPresent:n,anchorX:o,anchorY:c,root:d,children:s}),e.jsx(XLe.Provider,{value:x,children:s})};function cBs(){return new Map}function P9t(s=!0){const t=j.useContext(XLe);if(t===null)return[!0,null];const{isPresent:n,onExitComplete:r,register:a}=t,i=j.useId();j.useEffect(()=>{if(s)return a(i)},[s]);const l=j.useCallback(()=>s&&r&&r(i),[i,r,s]);return!n&&r?[!1,l]:[!0]}const qce=s=>s.key||"";function uvt(s){const t=[];return j.Children.forEach(s,n=>{j.isValidElement(n)&&t.push(n)}),t}const cK=({children:s,custom:t,initial:n=!0,onExitComplete:r,presenceAffectsLayout:a=!0,mode:i="sync",propagate:l=!1,anchorX:o="left",anchorY:c="top",root:d})=>{const[u,h]=P9t(l),m=j.useMemo(()=>uvt(s),[s]),f=l&&!u?[]:m.map(qce),g=j.useRef(!0),x=j.useRef(m),y=ust(()=>new Map),v=j.useRef(new Set),[b,w]=j.useState(m),[S,C]=j.useState(m);hst(()=>{g.current=!1,x.current=m;for(let P=0;P{const R=qce(P),D=l&&!u?!1:m===S||f.includes(R),O=()=>{if(v.current.has(R))return;if(y.has(R))v.current.add(R),y.set(R,!0);else return;let U=!0;y.forEach(W=>{W||(U=!1)}),U&&(I==null||I(),C(x.current),l&&(h==null||h()),r&&r())};return e.jsx(lBs,{isPresent:D,initial:!g.current||n?void 0:!1,custom:t,presenceAffectsLayout:a,mode:i,root:d,onExitComplete:D?void 0:O,anchorX:o,anchorY:c,children:P},R)})})},I9t=j.createContext({strict:!1}),hvt={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 mvt=!1;function dBs(){if(mvt)return;const s={};for(const t in hvt)s[t]={isEnabled:n=>hvt[t].some(r=>!!n[r])};c9t(s),mvt=!0}function L9t(){return dBs(),Kzs()}function uBs(s){const t=L9t();for(const n in s)t[n]={...t[n],...s[n]};c9t(t)}const hBs=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 VEe(s){return s.startsWith("while")||s.startsWith("drag")&&s!=="draggable"||s.startsWith("layout")||s.startsWith("onTap")||s.startsWith("onPan")||s.startsWith("onLayout")||hBs.has(s)}let R9t=s=>!VEe(s);function mBs(s){typeof s=="function"&&(R9t=t=>t.startsWith("on")?!VEe(t):s(t))}try{mBs(require("@emotion/is-prop-valid").default)}catch{}function fBs(s,t,n){const r={};for(const a in s)a==="values"&&typeof s.values=="object"||pb(s[a])||(R9t(a)||n===!0&&VEe(a)||!t&&!VEe(a)||s.draggable&&a.startsWith("onDrag"))&&(r[a]=s[a]);return r}const s6e=j.createContext({});function pBs(s,t){if(t6e(s)){const{initial:n,animate:r}=s;return{initial:n===!1||ise(n)?n:void 0,animate:ise(r)?r:void 0}}return s.inherit!==!1?t:{}}function gBs(s){const{initial:t,animate:n}=pBs(s,j.useContext(s6e));return j.useMemo(()=>({initial:t,animate:n}),[fvt(t),fvt(n)])}function fvt(s){return Array.isArray(s)?s.join(" "):s}const Ost=()=>({style:{},transform:{},transformOrigin:{},vars:{}});function D9t(s,t,n){for(const r in t)!pb(t[r])&&!g9t(r,n)&&(s[r]=t[r])}function xBs({transformTemplate:s},t){return j.useMemo(()=>{const n=Ost();return Rst(n,t,s),Object.assign({},n.vars,n.style)},[t])}function yBs(s,t){const n=s.style||{},r={};return D9t(r,n,s),Object.assign(r,xBs(s,t)),r}function vBs(s,t){const n={},r=yBs(s,t);return s.drag&&s.dragListener!==!1&&(n.draggable=!1,r.userSelect=r.WebkitUserSelect=r.WebkitTouchCallout="none",r.touchAction=s.drag===!0?"none":`pan-${s.drag==="x"?"y":"x"}`),s.tabIndex===void 0&&(s.onTap||s.onTapStart||s.whileTap)&&(n.tabIndex=0),n.style=r,n}const F9t=()=>({...Ost(),attrs:{}});function bBs(s,t,n,r){const a=j.useMemo(()=>{const i=F9t();return x9t(i,t,v9t(r),s.transformTemplate,s.style),{...i.attrs,style:{...i.style}}},[t]);if(s.style){const i={};D9t(i,s.style,s),a.style={...i,...a.style}}return a}const _Bs=["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 zst(s){return typeof s!="string"||s.includes("-")?!1:!!(_Bs.indexOf(s)>-1||/[A-Z]/u.test(s))}function wBs(s,t,n,{latestValues:r},a,i=!1,l){const c=(l??zst(s)?bBs:vBs)(t,r,a,s),d=fBs(t,typeof s=="string",i),u=s!==j.Fragment?{...d,...c,ref:n}:{},{children:h}=t,m=j.useMemo(()=>pb(h)?h.get():h,[h]);return j.createElement(s,{...u,children:m})}function jBs({scrapeMotionValuesFromProps:s,createRenderState:t},n,r,a){return{latestValues:NBs(n,r,a,s),renderState:t()}}function NBs(s,t,n,r){const a={},i=r(s,{});for(const m in i)a[m]=o3e(i[m]);let{initial:l,animate:o}=s;const c=t6e(s),d=o9t(s);t&&d&&!c&&s.inherit!==!1&&(l===void 0&&(l=t.initial),o===void 0&&(o=t.animate));let u=n?n.initial===!1:!1;u=u||l===!1;const h=u?o:l;if(h&&typeof h!="boolean"&&!e6e(h)){const m=Array.isArray(h)?h:[h];for(let f=0;f(t,n)=>{const r=j.useContext(s6e),a=j.useContext(XLe),i=()=>jBs(s,t,r,a);return n?i():ust(i)},kBs=O9t({scrapeMotionValuesFromProps:Dst,createRenderState:Ost}),SBs=O9t({scrapeMotionValuesFromProps:b9t,createRenderState:F9t}),CBs=Symbol.for("motionComponentSymbol");function ABs(s,t,n){const r=j.useRef(n);j.useInsertionEffect(()=>{r.current=n});const a=j.useRef(null);return j.useCallback(i=>{var o;i&&((o=s.onMount)==null||o.call(s,i)),t&&(i?t.mount(i):t.unmount());const l=r.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])}const z9t=j.createContext({});function bU(s){return s&&typeof s=="object"&&Object.prototype.hasOwnProperty.call(s,"current")}function EBs(s,t,n,r,a,i){var w,S;const{visualElement:l}=j.useContext(s6e),o=j.useContext(I9t),c=j.useContext(XLe),d=j.useContext(Fst),u=d.reducedMotion,h=d.skipAnimations,m=j.useRef(null),f=j.useRef(!1);r=r||o.renderer,!m.current&&r&&(m.current=r(s,{visualState:t,parent:l,props:n,presenceContext:c,blockInitialAnimation:c?c.initial===!1:!1,reducedMotionConfig:u,skipAnimations:h,isSVG:i}),f.current&&m.current&&(m.current.manuallyAnimateOnMount=!0));const g=m.current,x=j.useContext(z9t);g&&!g.projection&&a&&(g.type==="html"||g.type==="svg")&&TBs(m.current,n,a,x);const y=j.useRef(!1);j.useInsertionEffect(()=>{g&&y.current&&g.update(n,c)});const v=n[ZBt],b=j.useRef(!!v&&typeof window<"u"&&!((w=window.MotionHandoffIsComplete)!=null&&w.call(window,v))&&((S=window.MotionHasOptimisedAnimation)==null?void 0:S.call(window,v)));return hst(()=>{f.current=!0,g&&(y.current=!0,window.MotionIsMounted=!0,g.updateFeatures(),g.scheduleRenderMicrotask(),b.current&&g.animationState&&g.animationState.animateChanges())}),j.useEffect(()=>{g&&(!b.current&&g.animationState&&g.animationState.animateChanges(),b.current&&(queueMicrotask(()=>{var C;(C=window.MotionHandoffMarkAsComplete)==null||C.call(window,v)}),b.current=!1),g.enteringChildren=void 0)}),g}function TBs(s,t,n,r){const{layoutId:a,layout:i,drag:l,dragConstraints:o,layoutScroll:c,layoutRoot:d,layoutAnchor:u,layoutCrossfade:h}=t;s.projection=new n(s.latestValues,t["data-framer-portal-id"]?void 0:B9t(s.parent)),s.projection.setOptions({layoutId:a,layout:i,alwaysMeasureLayout:!!l||o&&bU(o),visualElement:s,animationType:typeof i=="string"?i:"both",initialPromotionConfig:r,crossfade:h,layoutScroll:c,layoutRoot:d,layoutAnchor:u})}function B9t(s){if(s)return s.options.allowProjection!==!1?s.projection:B9t(s.parent)}function T7e(s,{forwardMotionProps:t=!1,type:n}={},r,a){r&&uBs(r);const i=n?n==="svg":zst(s),l=i?SBs:kBs;function o(d,u){let h;const m={...j.useContext(Fst),...d,layoutId:MBs(d)},{isStatic:f}=m,g=gBs(d),x=l(d,f);if(!f&&typeof window<"u"){PBs();const y=IBs(m);h=y.MeasureLayout,g.visualElement=EBs(s,x,m,a,y.ProjectionNode,i)}return e.jsxs(s6e.Provider,{value:g,children:[h&&g.visualElement?e.jsx(h,{visualElement:g.visualElement,...m}):null,wBs(s,d,ABs(x,g.visualElement,u),x,f,t,i)]})}o.displayName=`motion.${typeof s=="string"?s:`create(${s.displayName??s.name??""})`}`;const c=j.forwardRef(o);return c[CBs]=s,c}function MBs({layoutId:s}){const t=j.useContext(dst).id;return t&&s!==void 0?t+"-"+s:s}function PBs(s,t){j.useContext(I9t).strict}function IBs(s){const t=L9t(),{drag:n,layout:r}=t;if(!n&&!r)return{};const a={...n,...r};return{MeasureLayout:n!=null&&n.isEnabled(s)||r!=null&&r.isEnabled(s)?a.MeasureLayout:void 0,ProjectionNode:a.ProjectionNode}}function LBs(s,t){if(typeof Proxy>"u")return T7e;const n=new Map,r=(i,l)=>T7e(i,l,s,t),a=(i,l)=>r(i,l);return new Proxy(a,{get:(i,l)=>l==="create"?r:(n.has(l)||n.set(l,T7e(l,void 0,s,t)),n.get(l))})}const RBs=(s,t)=>t.isSVG??zst(s)?new u7s(t):new a7s(t,{allowProjection:s!==j.Fragment});class DBs extends d6{constructor(t){super(t),t.animationState||(t.animationState=g7s(t))}updateAnimationControlsSubscription(){const{animate:t}=this.node.getProps();e6e(t)&&(this.unmountControls=t.subscribe(this.node))}mount(){this.updateAnimationControlsSubscription()}update(){const{animate:t}=this.node.getProps(),{animate:n}=this.node.prevProps||{};t!==n&&this.updateAnimationControlsSubscription()}unmount(){var t;this.node.animationState.reset(),(t=this.unmountControls)==null||t.call(this)}}let FBs=0;class OBs extends d6{constructor(){super(...arguments),this.id=FBs++,this.isExitComplete=!1}update(){var i;if(!this.node.presenceContext)return;const{isPresent:t,onExitComplete:n}=this.node.presenceContext,{isPresent:r}=this.node.prevPresenceContext||{};if(!this.node.animationState||t===r)return;if(t&&r===!1){if(this.isExitComplete){const{initial:l,custom:o}=this.node.getProps();if(typeof l=="string"||typeof l=="object"&&l!==null&&!Array.isArray(l)){const c=h7(this.node,l,o);if(c){const{transition:d,transitionEnd:u,...h}=c;for(const m in h)(i=this.node.getValue(m))==null||i.jump(h[m])}}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);n&&!t&&a.then(()=>{this.isExitComplete=!0,n(this.id)})}mount(){const{register:t,onExitComplete:n}=this.node.presenceContext||{};n&&n(this.id),t&&(this.unmount=t(this.id))}unmount(){}}const zBs={animation:{Feature:DBs},exit:{Feature:OBs}};function Qae(s){return{point:{x:s.pageX,y:s.pageY}}}const BBs=s=>t=>Mst(t)&&s(t,Qae(t));function Nee(s,t,n,r){return ose(s,t,BBs(n),r)}const $9t=({current:s})=>s?s.ownerDocument.defaultView:null,pvt=(s,t)=>Math.abs(s-t);function $Bs(s,t){const n=pvt(s.x,t.x),r=pvt(s.y,t.y);return Math.sqrt(n**2+r**2)}const gvt=new Set(["auto","scroll"]);class U9t{constructor(t,n,{transformPagePoint:r,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=g=>{this.handleScroll(g.target)},this.onWindowScroll=()=>{this.handleScroll(window)},this.updatePoint=()=>{if(!(this.lastMoveEvent&&this.lastMoveEventInfo))return;this.lastRawMoveEventInfo&&(this.lastMoveEventInfo=Vce(this.lastRawMoveEventInfo,this.transformPagePoint));const g=M7e(this.lastMoveEventInfo,this.history),x=this.startEvent!==null,y=$Bs(g.offset,{x:0,y:0})>=this.distanceThreshold;if(!x&&!y)return;const{point:v}=g,{timestamp:b}=ab;this.history.push({...v,timestamp:b});const{onStart:w,onMove:S}=this.handlers;x||(w&&w(this.lastMoveEvent,g),this.startEvent=this.lastMoveEvent),S&&S(this.lastMoveEvent,g)},this.handlePointerMove=(g,x)=>{this.lastMoveEvent=g,this.lastRawMoveEventInfo=x,this.lastMoveEventInfo=Vce(x,this.transformPagePoint),Sf.update(this.updatePoint,!0)},this.handlePointerUp=(g,x)=>{this.end();const{onEnd:y,onSessionEnd:v,resumeAnimation:b}=this.handlers;if((this.dragSnapToOrigin||!this.startEvent)&&b&&b(),!(this.lastMoveEvent&&this.lastMoveEventInfo))return;const w=M7e(g.type==="pointercancel"?this.lastMoveEventInfo:Vce(x,this.transformPagePoint),this.history);this.startEvent&&y&&y(g,w),v&&v(g,w)},!Mst(t))return;this.dragSnapToOrigin=i,this.handlers=n,this.transformPagePoint=r,this.distanceThreshold=l,this.contextWindow=a||window;const c=Qae(t),d=Vce(c,this.transformPagePoint),{point:u}=d,{timestamp:h}=ab;this.history=[{...u,timestamp:h}];const{onSessionStart:m}=n;m&&m(t,M7e(d,this.history));const f={passive:!0,capture:!0};this.removeListeners=Yae(Nee(this.contextWindow,"pointermove",this.handlePointerMove,f),Nee(this.contextWindow,"pointerup",this.handlePointerUp,f),Nee(this.contextWindow,"pointercancel",this.handlePointerUp,f)),o&&this.startScrollTracking(o)}startScrollTracking(t){let n=t.parentElement;for(;n;){const r=getComputedStyle(n);(gvt.has(r.overflowX)||gvt.has(r.overflowY))&&this.scrollPositions.set(n,{x:n.scrollLeft,y:n.scrollTop}),n=n.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 n=this.scrollPositions.get(t);if(!n)return;const r=t===window,a=r?{x:window.scrollX,y:window.scrollY}:{x:t.scrollLeft,y:t.scrollTop},i={x:a.x-n.x,y:a.y-n.y};i.x===0&&i.y===0||(r?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),Sf.update(this.updatePoint,!0))}updateHandlers(t){this.handlers=t}end(){this.removeListeners&&this.removeListeners(),this.removeScrollListeners&&this.removeScrollListeners(),this.scrollPositions.clear(),LL(this.updatePoint)}}function Vce(s,t){return t?{point:t(s.point)}:s}function xvt(s,t){return{x:s.x-t.x,y:s.y-t.y}}function M7e({point:s},t){return{point:s,delta:xvt(s,q9t(t)),offset:xvt(s,UBs(t)),velocity:qBs(t,.1)}}function UBs(s){return s[0]}function q9t(s){return s[s.length-1]}function qBs(s,t){if(s.length<2)return{x:0,y:0};let n=s.length-1,r=null;const a=q9t(s);for(;n>=0&&(r=s[n],!(a.timestamp-r.timestamp>v2(t)));)n--;if(!r)return{x:0,y:0};r===s[0]&&s.length>2&&a.timestamp-r.timestamp>v2(t)*2&&(r=s[1]);const i=WN(a.timestamp-r.timestamp);if(i===0)return{x:0,y:0};const l={x:(a.x-r.x)/i,y:(a.y-r.y)/i};return l.x===1/0&&(l.x=0),l.y===1/0&&(l.y=0),l}function VBs(s,{min:t,max:n},r){return t!==void 0&&sn&&(s=r?Nf(n,s,r.max):Math.min(s,n)),s}function yvt(s,t,n){return{min:t!==void 0?s.min+t:void 0,max:n!==void 0?s.max+n-(s.max-s.min):void 0}}function HBs(s,{top:t,left:n,bottom:r,right:a}){return{x:yvt(s.x,n,a),y:yvt(s.y,t,r)}}function vvt(s,t){let n=t.min-s.min,r=t.max-s.max;return t.max-t.minr?n=rse(t.min,t.max-r,s.min):r>a&&(n=rse(s.min,s.max-a,t.min)),X4(0,1,n)}function KBs(s,t){const n={};return t.min!==void 0&&(n.min=t.min-s.min),t.max!==void 0&&(n.max=t.max-s.min),n}const LGe=.35;function YBs(s=LGe){return s===!1?s=0:s===!0&&(s=LGe),{x:bvt(s,"left","right"),y:bvt(s,"top","bottom")}}function bvt(s,t,n){return{min:_vt(s,t),max:_vt(s,n)}}function _vt(s,t){return typeof s=="number"?s:s[t]||0}const ZBs=new WeakMap;class XBs{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=h0(),this.latestPointerEvent=null,this.latestPanInfo=null,this.visualElement=t}start(t,{snapToCursor:n=!1,distanceThreshold:r}={}){const{presenceContext:a}=this.visualElement;if(a&&a.isPresent===!1)return;const i=h=>{n&&this.snapToCursor(Qae(h).point),this.stopAnimation()},l=(h,m)=>{const{drag:f,dragPropagation:g,onDragStart:x}=this.getProps();if(f&&!g&&(this.openDragLock&&this.openDragLock(),this.openDragLock=Nzs(f),!this.openDragLock))return;this.latestPointerEvent=h,this.latestPanInfo=m,this.isDragging=!0,this.currentDirection=null,this.resolveConstraints(),this.visualElement.projection&&(this.visualElement.projection.isAnimationBlocked=!0,this.visualElement.projection.target=void 0),j5(v=>{let b=this.getAxisMotionValue(v).get()||0;if(B4.test(b)){const{projection:w}=this.visualElement;if(w&&w.layout){const S=w.layout.layoutBox[v];S&&(b=b_(S)*(parseFloat(b)/100))}}this.originPoint[v]=b}),x&&Sf.update(()=>x(h,m),!1,!0),NGe(this.visualElement,"transform");const{animationState:y}=this.visualElement;y&&y.setActive("whileDrag",!0)},o=(h,m)=>{this.latestPointerEvent=h,this.latestPanInfo=m;const{dragPropagation:f,dragDirectionLock:g,onDirectionLock:x,onDrag:y}=this.getProps();if(!f&&!this.openDragLock)return;const{offset:v}=m;if(g&&this.currentDirection===null){this.currentDirection=JBs(v),this.currentDirection!==null&&x&&x(this.currentDirection);return}this.updateAxis("x",m.point,v),this.updateAxis("y",m.point,v),this.visualElement.render(),y&&Sf.update(()=>y(h,m),!1,!0)},c=(h,m)=>{this.latestPointerEvent=h,this.latestPanInfo=m,this.stop(h,m),this.latestPointerEvent=null,this.latestPanInfo=null},d=()=>{const{dragSnapToOrigin:h}=this.getProps();(h||this.constraints)&&this.startAnimation({x:0,y:0})},{dragSnapToOrigin:u}=this.getProps();this.panSession=new U9t(t,{onSessionStart:i,onStart:l,onMove:o,onSessionEnd:c,resumeAnimation:d},{transformPagePoint:this.visualElement.getTransformPagePoint(),dragSnapToOrigin:u,distanceThreshold:r,contextWindow:$9t(this.visualElement),element:this.visualElement.current})}stop(t,n){const r=t||this.latestPointerEvent,a=n||this.latestPanInfo,i=this.isDragging;if(this.cancel(),!i||!a||!r)return;const{velocity:l}=a;this.startAnimation(l);const{onDragEnd:o}=this.getProps();o&&Sf.postRender(()=>o(r,a))}cancel(){this.isDragging=!1;const{projection:t,animationState:n}=this.visualElement;t&&(t.isAnimationBlocked=!1),this.endPanSession();const{dragPropagation:r}=this.getProps();!r&&this.openDragLock&&(this.openDragLock(),this.openDragLock=null),n&&n.setActive("whileDrag",!1)}endPanSession(){this.panSession&&this.panSession.end(),this.panSession=void 0}updateAxis(t,n,r){const{drag:a}=this.getProps();if(!r||!Hce(t,a,this.currentDirection))return;const i=this.getAxisMotionValue(t);let l=this.originPoint[t]+r[t];this.constraints&&this.constraints[t]&&(l=VBs(l,this.constraints[t],this.elastic[t])),i.set(l)}resolveConstraints(){var i;const{dragConstraints:t,dragElastic:n}=this.getProps(),r=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&&bU(t)?this.constraints||(this.constraints=this.resolveRefConstraints()):t&&r?this.constraints=HBs(r.layoutBox,t):this.constraints=!1,this.elastic=YBs(n),a!==this.constraints&&!bU(t)&&r&&this.constraints&&!this.hasMutatedConstraints&&j5(l=>{this.constraints!==!1&&this.getAxisMotionValue(l)&&(this.constraints[l]=KBs(r.layoutBox[l],this.constraints[l]))})}resolveRefConstraints(){const{dragConstraints:t,onMeasureDragConstraints:n}=this.getProps();if(!t||!bU(t))return!1;const r=t.current,{projection:a}=this.visualElement;if(!a||!a.layout)return!1;a.root&&(a.root.scroll=void 0,a.root.updateScroll());const i=Jzs(r,a.root,this.visualElement.getTransformPagePoint());let l=GBs(a.layout.layoutBox,i);if(n){const o=n(Zzs(l));this.hasMutatedConstraints=!!o,o&&(l=u9t(o))}return l}startAnimation(t){const{drag:n,dragMomentum:r,dragElastic:a,dragTransition:i,dragSnapToOrigin:l,onDragTransitionEnd:o}=this.getProps(),c=this.constraints||{},d=j5(u=>{if(!Hce(u,n,this.currentDirection))return;let h=c&&c[u]||{};(l===!0||l===u)&&(h={min:0,max:0});const m=a?200:1e6,f=a?40:1e7,g={type:"inertia",velocity:r?t[u]:0,bounceStiffness:m,bounceDamping:f,timeConstant:750,restDelta:1,restSpeed:10,...i,...h};return this.startAxisValueAnimation(u,g)});return Promise.all(d).then(o)}startAxisValueAnimation(t,n){const r=this.getAxisMotionValue(t);return NGe(this.visualElement,t),r.start(kst(t,r,0,n,this.visualElement,!1))}stopAnimation(){j5(t=>this.getAxisMotionValue(t).stop())}getAxisMotionValue(t){const n=`_drag${t.toUpperCase()}`,a=this.visualElement.getProps()[n];return a||this.visualElement.getValue(t,this.visualElement.latestValues[t]??0)}snapToCursor(t){j5(n=>{const{drag:r}=this.getProps();if(!Hce(n,r,this.currentDirection))return;const{projection:a}=this.visualElement,i=this.getAxisMotionValue(n);if(a&&a.layout){const{min:l,max:o}=a.layout.layoutBox[n],c=i.get()||0;i.set(t[n]-Nf(l,o,.5)+c)}})}scalePositionWithinConstraints(){if(!this.visualElement.current)return;const{drag:t,dragConstraints:n}=this.getProps(),{projection:r}=this.visualElement;if(!bU(n)||!r||!this.constraints)return;this.stopAnimation();const a={x:0,y:0};j5(l=>{const o=this.getAxisMotionValue(l);if(o&&this.constraints!==!1){const c=o.get();a[l]=WBs({min:c,max:c},this.constraints[l])}});const{transformTemplate:i}=this.visualElement.getProps();this.visualElement.current.style.transform=i?i({},""):"none",r.root&&r.root.updateScroll(),r.updateLayout(),this.constraints=!1,this.resolveConstraints(),j5(l=>{if(!Hce(l,t,null))return;const o=this.getAxisMotionValue(l),{min:c,max:d}=this.constraints[l];o.set(Nf(c,d,a[l]))}),this.visualElement.render()}addListeners(){if(!this.visualElement.current)return;ZBs.set(this.visualElement,this);const t=this.visualElement.current,n=Nee(t,"pointerdown",d=>{const{drag:u,dragListener:h=!0}=this.getProps(),m=d.target,f=m!==t&&Tzs(m);u&&h&&!f&&this.start(d)});let r;const a=()=>{const{dragConstraints:d}=this.getProps();bU(d)&&d.current&&(this.constraints=this.resolveRefConstraints(),r||(r=QBs(t,d.current,()=>this.scalePositionWithinConstraints())))},{projection:i}=this.visualElement,l=i.addEventListener("measure",a);i&&!i.layout&&(i.root&&i.root.updateScroll(),i.updateLayout()),Sf.read(a);const o=ose(window,"resize",()=>this.scalePositionWithinConstraints()),c=i.addEventListener("didUpdate",({delta:d,hasLayoutChanged:u})=>{this.isDragging&&u&&(j5(h=>{const m=this.getAxisMotionValue(h);m&&(this.originPoint[h]+=d[h].translate,m.set(m.get()+d[h].translate))}),this.visualElement.render())});return()=>{o(),n(),l(),c&&c(),r&&r()}}getProps(){const t=this.visualElement.getProps(),{drag:n=!1,dragDirectionLock:r=!1,dragPropagation:a=!1,dragConstraints:i=!1,dragElastic:l=LGe,dragMomentum:o=!0}=t;return{...t,drag:n,dragDirectionLock:r,dragPropagation:a,dragConstraints:i,dragElastic:l,dragMomentum:o}}}function wvt(s){let t=!0;return()=>{if(t){t=!1;return}s()}}function QBs(s,t,n){const r=E0t(s,wvt(n)),a=E0t(t,wvt(n));return()=>{r(),a()}}function Hce(s,t,n){return(t===!0||t===s)&&(n===null||n===s)}function JBs(s,t=10){let n=null;return Math.abs(s.y)>t?n="y":Math.abs(s.x)>t&&(n="x"),n}class e9s extends d6{constructor(t){super(t),this.removeGroupControls=ak,this.removeListeners=ak,this.controls=new XBs(t)}mount(){const{dragControls:t}=this.node.getProps();t&&(this.removeGroupControls=t.subscribe(this.controls)),this.removeListeners=this.controls.addListeners()||ak}update(){const{dragControls:t}=this.node.getProps(),{dragControls:n}=this.node.prevProps||{};t!==n&&(this.removeGroupControls(),t&&(this.removeGroupControls=t.subscribe(this.controls)))}unmount(){this.removeGroupControls(),this.removeListeners(),this.controls.isDragging||this.controls.endPanSession()}}const P7e=s=>(t,n)=>{s&&Sf.update(()=>s(t,n),!1,!0)};class t9s extends d6{constructor(){super(...arguments),this.removePointerDownListener=ak}onPointerDown(t){this.session=new U9t(t,this.createPanHandlers(),{transformPagePoint:this.node.getTransformPagePoint(),contextWindow:$9t(this.node)})}createPanHandlers(){const{onPanSessionStart:t,onPanStart:n,onPan:r,onPanEnd:a}=this.node.getProps();return{onSessionStart:P7e(t),onStart:P7e(n),onMove:P7e(r),onEnd:(i,l)=>{delete this.session,a&&Sf.postRender(()=>a(i,l))}}}mount(){this.removePointerDownListener=Nee(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 I7e=!1;class s9s extends j.Component{componentDidMount(){const{visualElement:t,layoutGroup:n,switchLayoutGroup:r,layoutId:a}=this.props,{projection:i}=t;i&&(n.group&&n.group.add(i),r&&r.register&&a&&r.register(i),I7e&&i.root.didUpdate(),i.addEventListener("animationComplete",()=>{this.safeToRemove()}),i.setOptions({...i.options,layoutDependency:this.props.layoutDependency,onExitComplete:()=>this.safeToRemove()})),l3e.hasEverUpdated=!0}getSnapshotBeforeUpdate(t){const{layoutDependency:n,visualElement:r,drag:a,isPresent:i}=this.props,{projection:l}=r;return l&&(l.isPresent=i,t.layoutDependency!==n&&l.setOptions({...l.options,layoutDependency:n}),I7e=!0,a||t.layoutDependency!==n||n===void 0||t.isPresent!==i?l.willUpdate():this.safeToRemove(),t.isPresent!==i&&(i?l.promote():l.relegate()||Sf.postRender(()=>{const o=l.getStack();(!o||!o.members.length)&&this.safeToRemove()}))),null}componentDidUpdate(){const{visualElement:t,layoutAnchor:n}=this.props,{projection:r}=t;r&&(r.options.layoutAnchor=n,r.root.didUpdate(),Tst.postRender(()=>{!r.currentAnimation&&r.isLead()&&this.safeToRemove()}))}componentWillUnmount(){const{visualElement:t,layoutGroup:n,switchLayoutGroup:r}=this.props,{projection:a}=t;I7e=!0,a&&(a.scheduleCheckAfterUnmount(),n&&n.group&&n.group.remove(a),r&&r.deregister&&r.deregister(a))}safeToRemove(){const{safeToRemove:t}=this.props;t&&t()}render(){return null}}function V9t(s){const[t,n]=P9t(),r=j.useContext(dst);return e.jsx(s9s,{...s,layoutGroup:r,switchLayoutGroup:j.useContext(z9t),isPresent:t,safeToRemove:n})}const n9s={pan:{Feature:t9s},drag:{Feature:e9s,ProjectionNode:M9t,MeasureLayout:V9t}};function jvt(s,t,n){const{props:r}=s;s.animationState&&r.whileHover&&s.animationState.setActive("whileHover",n==="Start");const a="onHover"+n,i=r[a];i&&Sf.postRender(()=>i(t,Qae(t)))}class r9s extends d6{mount(){const{current:t}=this.node;t&&(this.unmount=Szs(t,(n,r)=>(jvt(this.node,r,"Start"),a=>jvt(this.node,a,"End"))))}unmount(){}}class a9s extends d6{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=Yae(ose(this.node.current,"focus",()=>this.onFocus()),ose(this.node.current,"blur",()=>this.onBlur()))}unmount(){}}function Nvt(s,t,n){const{props:r}=s;if(s.current instanceof HTMLButtonElement&&s.current.disabled)return;s.animationState&&r.whileTap&&s.animationState.setActive("whileTap",n==="Start");const a="onTap"+(n==="End"?"":n),i=r[a];i&&Sf.postRender(()=>i(t,Qae(t)))}class i9s extends d6{mount(){const{current:t}=this.node;if(!t)return;const{globalTapTarget:n,propagate:r}=this.node.props;this.unmount=Pzs(t,(a,i)=>(Nvt(this.node,i,"Start"),(l,{success:o})=>Nvt(this.node,l,o?"End":"Cancel")),{useGlobalTarget:n,stopPropagation:(r==null?void 0:r.tap)===!1})}unmount(){}}const RGe=new WeakMap,L7e=new WeakMap,o9s=s=>{const t=RGe.get(s.target);t&&t(s)},l9s=s=>{s.forEach(o9s)};function c9s({root:s,...t}){const n=s||document;L7e.has(n)||L7e.set(n,{});const r=L7e.get(n),a=JSON.stringify(t);return r[a]||(r[a]=new IntersectionObserver(l9s,{root:s,...t})),r[a]}function d9s(s,t,n){const r=c9s(t);return RGe.set(s,n),r.observe(s),()=>{RGe.delete(s),r.unobserve(s)}}const u9s={some:0,all:1};class h9s extends d6{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:n,margin:r,amount:a="some",once:i}=t,l={root:n?n.current:void 0,rootMargin:r,threshold:typeof a=="number"?a:u9s[a]},o=d=>{const{isIntersecting:u}=d;if(this.isInView===u||(this.isInView=u,i&&!u&&this.hasEnteredView))return;u&&(this.hasEnteredView=!0),this.node.animationState&&this.node.animationState.setActive("whileInView",u);const{onViewportEnter:h,onViewportLeave:m}=this.node.getProps(),f=u?h:m;f&&f(d)};this.stopObserver=d9s(this.node.current,l,o)}mount(){this.startObserver()}update(){if(typeof IntersectionObserver>"u")return;const{props:t,prevProps:n}=this.node;["amount","margin","root"].some(m9s(t,n))&&this.startObserver()}unmount(){var t;(t=this.stopObserver)==null||t.call(this),this.hasEnteredView=!1,this.isInView=!1}}function m9s({viewport:s={}},{viewport:t={}}={}){return n=>s[n]!==t[n]}const f9s={inView:{Feature:h9s},tap:{Feature:i9s},focus:{Feature:a9s},hover:{Feature:r9s}},p9s={layout:{ProjectionNode:M9t,MeasureLayout:V9t}},g9s={...zBs,...f9s,...n9s,...p9s},Br=LBs(g9s,RBs),x9s={some:0,all:1};function y9s(s,t,{root:n,margin:r,amount:a="some"}={}){const i=Est(s),l=new WeakMap,o=d=>{d.forEach(u=>{const h=l.get(u.target);if(u.isIntersecting!==!!h)if(u.isIntersecting){const m=t(u.target,u);typeof m=="function"?l.set(u.target,m):c.unobserve(u.target)}else typeof h=="function"&&(h(u),l.delete(u.target))})},c=new IntersectionObserver(o,{root:n,rootMargin:r,threshold:typeof a=="number"?a:x9s[a]});return i.forEach(d=>c.observe(d)),()=>c.disconnect()}function v9s(s,{root:t,margin:n,amount:r,once:a=!1,initial:i=!1}={}){const[l,o]=j.useState(i);return j.useEffect(()=>{if(!s.current||a&&l)return;const c=()=>(o(!0),a?void 0:()=>o(!1)),d={root:t&&t.current||void 0,margin:n,amount:r};return y9s(s.current,c,d)},[t,s,n,a,r]),l}function b9s(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 kvt(s){return s.visitor_intent==="buying"&&!s.has_agent}function _9s({token:s}={}){var f;const t=Wi(),n=s||t.token,{data:r,isLoading:a,isError:i}=vOs(n);Vt();const l=(f=r==null?void 0:r.open_houses)==null?void 0:f.id,{data:o}=tt({queryKey:["cohost-visitors",n,l],queryFn:async()=>{const{data:g,error:x}=await q.rpc("get_cohost_visitors",{_token:n});if(x)throw x;return g||[]},enabled:!!n&&!!l,refetchInterval:15e3});if(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||!r)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 c=r.open_houses,d=(o==null?void 0:o.length)||0,u=(o==null?void 0:o.filter(g=>g.visitor_intent==="buying").length)||0,h=(o==null?void 0:o.filter(kvt).length)||0,m=g=>{if(!g)return"";const[x,y]=g.split(":"),v=parseInt(x);return`${v>12?v-12:v||12}:${y} ${v>=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:c.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(Zn,{className:"h-4 w-4"}),e.jsx("span",{className:"font-bold text-white",children:d})]}),e.jsxs("div",{className:"flex items-center gap-1.5 text-orange-400",children:[e.jsx(nh,{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",children:[e.jsx(va,{className:"h-4 w-4"}),e.jsx("span",{className:"font-bold text-white",children:u})]})]})]}),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:en(new Date(c.event_date+"T00:00:00"),"EEEE, MMMM d, yyyy")}),c.start_time&&e.jsxs("span",{children:[m(c.start_time),c.end_time?` – ${m(c.end_time)}`:""]})]}),e.jsx(uo,{className:"flex-1 p-4 sm:p-6",children:o!=null&&o.length?e.jsx("div",{className:"space-y-2 max-w-3xl mx-auto",children:e.jsx(cK,{children:o.map((g,x)=>{var b;const y=b9s(g.visitor_intent),v=kvt(g);return e.jsxs(Br.div,{initial:{opacity:0,x:-40,scale:.95},animate:{opacity:1,x:0,scale:1},transition:{duration:.4,delay:x*.05},className:`flex items-center gap-4 p-4 rounded-xl border ${v?"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 ${v?"bg-gradient-to-br from-orange-500 to-amber-500 text-white":"bg-white/10 text-white/80"}`,children:(b=g.first_name[0])==null?void 0:b.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:[g.first_name," ",g.last_name||""]}),v&&e.jsx(Be,{className:"bg-orange-500/20 text-orange-300 border-orange-500/40 text-[10px] px-1.5 py-0",children:"🔥 HOT"}),g.has_agent&&e.jsx(Be,{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(Be,{variant:"outline",className:`text-[10px] px-1.5 py-0 ${y.color}`,children:[y.emoji," ",y.label]}),e.jsx("span",{className:"text-white/30 text-xs",children:en(new Date(g.created_at),"h:mm a")})]})]})]},g.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(Nb,{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 w9s(){const t=fu().pathname.slice(1);if(j.useEffect(()=>(document.body.classList.add("guestbook-page"),()=>{document.body.classList.remove("guestbook-page")}),[]),t.startsWith("live/")){const n=t.slice(5);if(n)return e.jsx(_9s,{token:n})}if(t.startsWith("rsvp/")){const n=t.slice(5);if(n)return e.jsx(lBt,{slug:n})}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(oBt,{slug:t})}function j9s({dealData:s,agentProfile:t,welcomeMessage:n,isWon:r,branding:a}){var d;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.logo_url)||null,o=(a==null?void 0:a.cover_photo_url)||null,c=(a==null?void 0:a.tagline)||"Your Real Estate Concierge";return e.jsxs("div",{className:"relative overflow-hidden",children:[e.jsxs("div",{className:"relative px-4 pt-10 pb-20",children:[o&&e.jsx("div",{className:"absolute inset-0",style:{backgroundImage:`url(${o})`,backgroundSize:"cover",backgroundPosition:"center",filter:"var(--portal-hero-filter-mobile)"}}),e.jsx("div",{className:"absolute inset-0",style:{background:o?"var(--portal-hero-scrim-mobile)":"radial-gradient(ellipse 100% 70% at 50% 0%, hsl(var(--portal-gold) / 0.12), transparent 60%), linear-gradient(180deg, hsl(0 0% 7%), hsl(0 0% 4%))"}}),e.jsx("div",{className:"absolute inset-0 opacity-[0.05]",style:{backgroundImage:"radial-gradient(circle at 25% 25%, hsl(var(--portal-gold)) 1px, transparent 1px)",backgroundSize:"32px 32px"}}),e.jsxs("div",{className:"relative text-center max-w-lg mx-auto",children:[l&&e.jsx(Br.div,{initial:{opacity:0,y:-8},animate:{opacity:1,y:0},transition:{duration:.5},className:"mb-6 flex justify-center",children:e.jsx("div",{className:"rounded-xl px-4 py-2.5",style:{background:"hsl(0 0% 100% / 0.06)",backdropFilter:"blur(8px)",border:"1px solid hsl(var(--portal-gold) / 0.2)"},children:e.jsx("img",{src:l,alt:"Brand",className:"h-9 max-w-[160px] object-contain"})})}),t&&e.jsxs(Br.div,{initial:{opacity:0,y:8},animate:{opacity:1,y:0},transition:{duration:.5,delay:.05},className:"mb-6",children:[t.avatar_url?e.jsx("div",{className:"w-20 h-20 mx-auto mb-3 relative",children:e.jsx("div",{className:"absolute inset-0 rounded-full",style:{background:"var(--portal-gradient-gold)",padding:"2px"},children:e.jsx("img",{src:t.avatar_url,alt:t.name,className:"w-full h-full rounded-full object-cover",style:{background:"hsl(var(--portal-surface))"}})})}):e.jsx("div",{className:"w-20 h-20 mx-auto mb-3 rounded-full flex items-center justify-center portal-serif text-3xl",style:{background:"hsl(var(--portal-surface-2))",border:"1px solid hsl(var(--portal-gold) / 0.3)",color:"var(--portal-hero-accent)"},children:((d=t.name)==null?void 0:d.charAt(0))||"?"}),e.jsx("p",{className:"portal-serif text-lg",style:{color:"var(--portal-hero-ink)"},children:t.name}),e.jsx("p",{className:"text-[10px] mt-1 tracking-[0.22em] uppercase",style:{color:"var(--portal-hero-ink-dim)"},children:c})]}),e.jsxs(Br.div,{initial:{opacity:0,y:8},animate:{opacity:1,y:0},transition:{duration:.6,delay:.1},children:[e.jsxs("div",{className:"inline-flex items-center gap-1.5 rounded-full px-3 py-1 text-[10px] tracking-[0.2em] uppercase mb-4",style:{background:"hsl(var(--portal-gold) / 0.08)",border:"1px solid hsl(var(--portal-gold) / 0.25)",color:"var(--portal-hero-accent)"},children:[e.jsx(va,{className:"w-3 h-3"}),(s==null?void 0:s.deal_type)==="listing"?"Sale":(s==null?void 0:s.deal_type)==="buy-side"?"Purchase":"Transaction",r&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"opacity-50",children:"·"}),"Complete"]})]}),e.jsx("h1",{className:"portal-serif text-[2.5rem] leading-[1.05] mb-3",style:{color:"var(--portal-hero-ink)"},children:(s==null?void 0:s.deal_name)||"Your Transaction"}),e.jsx("div",{className:"portal-hairline w-24 mx-auto mb-4"}),i&&e.jsxs("div",{className:"flex items-center justify-center gap-1.5 text-sm",style:{color:"var(--portal-hero-ink-muted)"},children:[e.jsx(ci,{className:"w-3.5 h-3.5",style:{color:"var(--portal-hero-accent)"}}),e.jsx("span",{children:i})]}),n&&e.jsxs("p",{className:"mt-6 text-sm leading-relaxed max-w-md mx-auto italic portal-serif",style:{color:"var(--portal-hero-ink-muted)",fontSize:"1.05rem"},children:["“",n,"”"]})]})]})]}),t&&e.jsx("div",{className:"max-w-lg mx-auto px-4 -mt-10 relative z-10",children:e.jsx("div",{className:"rounded-2xl p-3",style:{background:"hsl(var(--portal-surface))",border:"1px solid hsl(var(--portal-gold) / 0.2)",boxShadow:"var(--portal-shadow-tile)"},children:e.jsxs("div",{className:"flex items-center justify-center gap-2",children:[t.phone&&e.jsxs("a",{href:`tel:${t.phone}`,className:"flex-1 flex items-center justify-center gap-2 px-3 py-2.5 rounded-xl transition-colors",style:{background:"hsl(var(--portal-gold) / 0.06)",color:"var(--portal-hero-accent)",border:"1px solid hsl(var(--portal-gold) / 0.15)"},children:[e.jsx(Da,{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:"flex-1 flex items-center justify-center gap-2 px-3 py-2.5 rounded-xl transition-colors",style:{background:"hsl(var(--portal-gold) / 0.06)",color:"var(--portal-hero-accent)",border:"1px solid hsl(var(--portal-gold) / 0.15)"},children:[e.jsx(mn,{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:"flex-1 flex items-center justify-center gap-2 px-3 py-2.5 rounded-xl transition-colors",style:{background:"hsl(var(--portal-gold) / 0.06)",color:"var(--portal-hero-accent)",border:"1px solid hsl(var(--portal-gold) / 0.15)"},children:[e.jsx(Th,{className:"w-4 h-4"}),e.jsx("span",{className:"text-sm font-medium",children:"Text"})]})]})})})]})}function H9t({targetCloseDate:s,actualCloseDate:t,clientName:n}){if(t||!s)return null;const r=s.split(/[-/T]/),a=new Date(Number(r[0]),Number(r[1])-1,Number(r[2])),l=mk(a,new Date);if(z4(a)&&!Nv(a))return null;const o=Nv(a),c=o?"0":String(Math.max(0,l)),d=Math.max(4,Math.min(100,(60-Math.min(60,l))/60*100));return e.jsxs("div",{className:"portal-tile p-8 text-center",children:[e.jsx("p",{className:"portal-eyebrow mb-4",children:o?"The Moment Has Arrived":"Countdown to Closing"}),o?e.jsxs(e.Fragment,{children:[e.jsx("h3",{className:"portal-serif text-5xl mb-2",style:{color:"hsl(var(--portal-gold))"},children:"Closing Day"}),e.jsxs("p",{className:"text-sm mt-3",style:{color:"hsl(var(--portal-ink-muted))"},children:["Congratulations",n?`, ${n.split(" ")[0]}`:"","."]})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-baseline justify-center gap-3",children:[e.jsx(Br.span,{initial:{opacity:0,y:8},animate:{opacity:1,y:0},transition:{duration:.6},className:"portal-serif tabular-nums leading-none",style:{fontSize:"5.5rem",color:"hsl(var(--portal-gold))",textShadow:"0 0 40px hsl(var(--portal-gold) / 0.4)"},children:c}),e.jsx("span",{className:"portal-serif",style:{fontSize:"1.5rem",color:"hsl(var(--portal-ink-muted))"},children:l===1?"day":"days"})]}),e.jsx("div",{className:"portal-hairline w-16 mx-auto my-4"}),e.jsx("p",{className:"text-xs tracking-[0.2em] uppercase",style:{color:"hsl(var(--portal-ink-muted))"},children:"Until you hold the keys"}),e.jsx("div",{className:"mt-6 mx-auto max-w-[260px]",children:e.jsx("div",{className:"h-[2px] rounded-full overflow-hidden",style:{background:"hsl(var(--portal-gold) / 0.15)"},children:e.jsx(Br.div,{initial:{width:0},animate:{width:`${d}%`},transition:{duration:1.2,ease:"easeOut"},className:"h-full rounded-full",style:{background:"var(--portal-gradient-gold)",boxShadow:"0 0 12px hsl(var(--portal-gold) / 0.6)"}})})})]})]})}function G9t({journeyStages:s,currentIndex:t}){return s.length===0?null:e.jsxs("div",{children:[e.jsx("p",{className:"portal-eyebrow mb-2",children:"The Journey"}),e.jsx("h2",{className:"portal-serif text-2xl mb-6",style:{color:"hsl(var(--portal-ink))"},children:"Your path to the keys"}),e.jsx("div",{className:"relative",children:s.map((n,r)=>{const a=rt;return e.jsxs(Br.div,{initial:{opacity:0,x:-6},animate:{opacity:1,x:0},transition:{duration:.35,delay:r*.05},className:"flex items-start gap-4 relative",children:[r{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",{children:[e.jsx("p",{className:"portal-eyebrow mb-2",children:"Right Now"}),e.jsx("h4",{className:"portal-serif text-3xl mb-2 portal-gold-underline",style:{color:"hsl(var(--portal-ink))"},children:s.label}),e.jsx("p",{className:"text-sm leading-relaxed mt-4",style:{color:"hsl(var(--portal-ink-muted))"},children:s.description}),t&&e.jsxs("div",{className:"mt-5 rounded-xl p-4",style:{background:"hsl(var(--portal-surface-2))",border:"1px solid hsl(var(--portal-gold) / 0.15)"},children:[e.jsx("p",{className:"portal-eyebrow mb-2",children:"Note From Your Agent"}),e.jsxs("p",{className:"text-sm leading-relaxed portal-serif italic",style:{color:"hsl(var(--portal-ink))",fontSize:"1rem"},children:["“",t,"”"]})]}),n&&e.jsxs("div",{className:"mt-5 rounded-xl p-4",style:{background:"linear-gradient(135deg, hsl(var(--portal-gold) / 0.08), hsl(var(--portal-gold) / 0.02))",border:"1px solid hsl(var(--portal-gold) / 0.25)"},children:[e.jsx("p",{className:"portal-eyebrow mb-2",children:"What’s Next"}),e.jsx("p",{className:"text-sm leading-relaxed",style:{color:"hsl(var(--portal-ink))"},children:n})]}),r&&e.jsx("div",{className:"mt-5 rounded-xl overflow-hidden aspect-video relative group",style:{background:"hsl(var(--portal-bg))",border:"1px solid hsl(var(--portal-gold) / 0.2)"},children:e.jsx("iframe",{src:a(r)||r,className:"w-full h-full",allow:"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture",allowFullScreen:!0,title:"Next step video"})})]})}function Ch(s){const t=s.split(/[-/T]/);if(t.length>=3){const n=Number(t[0]);return n>99?new Date(n,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 Svt(s){const t=s.trim();if(!t)return;const n=t.split(/[-/]/).filter(Boolean);if(n.length<3)return;const r=n.map(c=>Number(c));if(r.some(c=>Number.isNaN(c)))return;r[0];let a,i,l;if(n[0].length===4)[l,a,i]=r,a=a-1;else if([a,i,l]=r,a=a-1,n[2].length===2)l=l<=49?2e3+l:1900+l;else if(n[2].length!==4)return;const o=new Date(l,a,i);if(!(o.getFullYear()!==l||o.getMonth()!==a||o.getDate()!==i))return o}const N9s=[{key:"contract_date",label:"Contract Accepted",icon:JN},{key:"earnest_money_due_date",label:"Earnest Money",icon:ru},{key:"inspection_date",label:"Inspection",icon:Kr},{key:"inspection_contingency_date",label:"Inspection Deadline",icon:Jr},{key:"appraisal_date",label:"Appraisal",icon:va},{key:"loan_approval_date",label:"Loan Approval",icon:qq},{key:"title_docs_due_date",label:"Title & Disclosures",icon:Jr},{key:"final_walkthrough_date",label:"Final Walkthrough",icon:KI},{key:"target_close_date",label:"Target Close",icon:Ta}];function k9s(s,t){const n=en(t,"yyyyMMdd");return`https://calendar.google.com/calendar/render?${new URLSearchParams({action:"TEMPLATE",text:s,dates:`${n}/${n}`,details:"Added from your Client Portal"}).toString()}`}function S9s(s,t){const n=en(t,"yyyyMMdd");return`data:text/calendar;charset=utf-8,${encodeURIComponent(`BEGIN:VCALENDAR VERSION:2.0 BEGIN:VEVENT DTSTART;VALUE=DATE:${n} DTEND;VALUE=DATE:${n} SUMMARY:${s} DESCRIPTION:Added from your Client Portal END:VEVENT END:VCALENDAR`)}`}function K9t({deal:s,portal:t,targetCloseDate:n,contractDate:r,inspectionDate:a,appraisalDate:i,actualCloseDate:l}){const o={...s||{},contract_date:(s==null?void 0:s.contract_date)??r??null,inspection_date:(s==null?void 0:s.inspection_date)??(t==null?void 0:t.inspection_date)??a??null,appraisal_date:(s==null?void 0:s.appraisal_date)??(t==null?void 0:t.appraisal_date)??i??null,target_close_date:(s==null?void 0:s.target_close_date)??n??null},c=(s==null?void 0:s.actual_close_date)??l??null,d=Array.isArray(s==null?void 0:s.completed_key_dates)?s.completed_key_dates:[],u=N9s.map(f=>f.key==="target_close_date"&&c?{...f,label:"Closed",date:c,done:!0}:{...f,date:o[f.key],done:d.includes(f.key)}).filter(f=>!!f.date);if(u.length===0)return null;const h=(f,g,x)=>{const y=Ch(g);if(x==="google")window.open(k9s(f,y),"_blank");else{const v=S9s(f,y),b=document.createElement("a");b.href=v,b.download=`${f.replace(/\s+/g,"-").toLowerCase()}.ics`,b.click()}},m=u.filter(f=>f.done).length;return e.jsxs("div",{children:[e.jsx("p",{className:"portal-eyebrow mb-2",children:"Milestones"}),e.jsxs("div",{className:"flex items-baseline justify-between gap-3 mb-5 flex-wrap",children:[e.jsx("h2",{className:"portal-serif text-2xl",style:{color:"hsl(var(--portal-ink))"},children:"Key dates"}),e.jsxs("span",{className:"text-[11px] tracking-[0.18em] uppercase",style:{color:"hsl(var(--portal-ink-dim))"},children:[m," of ",u.length," complete"]})]}),e.jsxs("div",{className:"space-y-4 relative",children:[e.jsx("div",{className:"absolute left-[10px] top-2 bottom-2 w-[1px]",style:{background:"hsl(var(--portal-gold) / 0.18)"}}),u.map(({label:f,date:g,done:x,icon:y})=>{const v=Ch(g),b=z4(v)&&!Nv(v),w=Nv(v),S=!b&&!w,C=x?"Completed":w?"Today":b?"In progress":"Upcoming";return e.jsxs("div",{className:"flex items-start gap-3 relative",children:[e.jsx("div",{className:"w-[21px] h-[21px] rounded-full mt-0.5 flex-shrink-0 relative z-10 flex items-center justify-center",style:{background:x?"hsl(var(--portal-gold))":w?"hsl(var(--portal-gold) / 0.25)":"hsl(var(--portal-surface-2))",border:"1px solid hsl(var(--portal-gold) / 0.7)",boxShadow:w?"0 0 12px hsl(var(--portal-gold) / 0.5)":"none"},children:x?e.jsx(la,{className:"w-3 h-3",style:{color:"hsl(var(--portal-surface))"}}):e.jsx(y,{className:"w-3 h-3",style:{color:"hsl(var(--portal-gold))"}})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-[10px] tracking-[0.22em] uppercase",style:{color:"hsl(var(--portal-ink-dim))"},children:f}),e.jsx("p",{className:"portal-serif mt-0.5",style:{fontSize:"1.15rem",color:x?"hsl(var(--portal-ink-muted))":"hsl(var(--portal-ink))"},children:en(v,"MMM d, yyyy")}),e.jsx("span",{className:"inline-block mt-1 text-[9px] tracking-[0.2em] uppercase px-2 py-0.5 rounded-full",style:{color:x||w?"hsl(var(--portal-gold))":"hsl(var(--portal-ink-dim))",border:`1px solid hsl(var(--portal-gold) / ${x||w?.5:.18})`},children:C})]}),S&&e.jsxs("div",{className:"flex items-center gap-1 mt-1",children:[e.jsx("button",{onClick:()=>h(f,g,"google"),className:"p-1.5 rounded transition-colors",style:{color:"hsl(var(--portal-ink-dim))"},onMouseEnter:E=>{E.currentTarget.style.color="hsl(var(--portal-gold))"},onMouseLeave:E=>{E.currentTarget.style.color="hsl(var(--portal-ink-dim))"},title:"Add to Google Calendar",children:e.jsx(jv,{className:"w-3.5 h-3.5"})}),e.jsx("button",{onClick:()=>h(f,g,"apple"),className:"text-[9px] tracking-widest px-1.5 py-1 rounded",style:{color:"hsl(var(--portal-ink-dim))"},title:"Download .ics",children:".ICS"})]})]},f)})]})]})}function Y9t({documents:s}){const t=r=>r<1024?`${r} B`:r<1048576?`${(r/1024).toFixed(0)} KB`:`${(r/1048576).toFixed(1)} MB`,n=async r=>{const{data:a}=await q.storage.from("deal-files").createSignedUrl(r.storage_path,300);a!=null&&a.signedUrl&&window.open(a.signedUrl,"_blank")};return e.jsxs("div",{children:[e.jsx("p",{className:"portal-eyebrow mb-2",children:"Paperwork"}),e.jsx("h2",{className:"portal-serif text-2xl mb-5",style:{color:"hsl(var(--portal-ink))"},children:"Documents"}),e.jsx("div",{className:"space-y-2",children:s.map(r=>e.jsxs("button",{onClick:()=>n(r),className:"w-full flex items-center gap-3 p-3 rounded-xl transition-all text-left group",style:{background:"hsl(var(--portal-surface-2))",border:"1px solid hsl(var(--portal-gold) / 0.08)"},onMouseEnter:a=>{a.currentTarget.style.borderColor="hsl(var(--portal-gold) / 0.35)"},onMouseLeave:a=>{a.currentTarget.style.borderColor="hsl(var(--portal-gold) / 0.08)"},children:[e.jsx("div",{className:"w-10 h-10 rounded-lg flex items-center justify-center flex-shrink-0",style:{background:"hsl(var(--portal-gold) / 0.08)",border:"1px solid hsl(var(--portal-gold) / 0.2)"},children:e.jsx(Jr,{className:"w-4 h-4",style:{color:"hsl(var(--portal-gold))"}})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm portal-serif truncate",style:{color:"hsl(var(--portal-ink))",fontSize:"1rem"},children:r.file_name}),e.jsx("p",{className:"text-[10px] tracking-widest uppercase mt-0.5",style:{color:"hsl(var(--portal-ink-dim))"},children:t(r.file_size)})]}),e.jsx(di,{className:"w-4 h-4 flex-shrink-0",style:{color:"hsl(var(--portal-gold) / 0.5)"}})]},r.id))})]})}function Z9t({slug:s,wrapper:t}){const n=Qn(),[r,a]=j.useState(null),{data:i=[]}=tt({queryKey:["portal-signature-requests",s],enabled:!!s,queryFn:async()=>{const{data:u,error:h}=await q.functions.invoke("forms-portal-public",{body:{action:"list",slug:s}});return h?[]:(u==null?void 0:u.envelopes)||[]}}),l=i.filter(u=>u.my_turn),o=i.filter(u=>!u.my_turn&&u.status!=="completed");if(!l.length&&!o.length)return null;const c=async u=>{a(u);try{const{data:h,error:m}=await q.functions.invoke("forms-portal-public",{body:{action:"sign_link",slug:s,envelope_id:u}});if(m||h!=null&&h.error)throw new Error((h==null?void 0:h.error)||"Could not open the document");n(h.path)}catch(h){re.error((h==null?void 0:h.message)||"Could not open the document")}finally{a(null)}},d=e.jsxs("div",{children:[e.jsx("p",{className:"portal-eyebrow mb-2",children:"Needs you"}),e.jsx("h2",{className:"portal-serif text-2xl mb-5",style:{color:"hsl(var(--portal-ink))"},children:"Documents to sign"}),e.jsxs("div",{className:"space-y-2",children:[l.map(u=>e.jsxs("button",{onClick:()=>c(u.id),disabled:r===u.id,className:"w-full flex items-center gap-3 p-3 rounded-xl transition-all text-left",style:{background:"hsl(var(--portal-gold) / 0.1)",border:"1px solid hsl(var(--portal-gold) / 0.4)"},children:[e.jsx("div",{className:"w-10 h-10 rounded-lg flex items-center justify-center flex-shrink-0",style:{background:"hsl(var(--portal-gold) / 0.14)",border:"1px solid hsl(var(--portal-gold) / 0.3)"},children:r===u.id?e.jsx(kt,{className:"w-4 h-4 animate-spin",style:{color:"hsl(var(--portal-gold))"}}):e.jsx(wf,{className:"w-4 h-4",style:{color:"hsl(var(--portal-gold))"}})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm portal-serif truncate",style:{color:"hsl(var(--portal-ink))",fontSize:"1rem"},children:u.title}),e.jsx("p",{className:"text-[10px] tracking-widest uppercase mt-0.5",style:{color:"hsl(var(--portal-gold))"},children:"Tap to review & sign"})]})]},u.id)),o.map(u=>e.jsxs("div",{className:"w-full flex items-center gap-3 p-3 rounded-xl",style:{background:"hsl(var(--portal-surface-2))",border:"1px solid hsl(var(--portal-gold) / 0.08)"},children:[e.jsx("div",{className:"w-10 h-10 rounded-lg flex items-center justify-center flex-shrink-0",style:{background:"hsl(var(--portal-gold) / 0.06)"},children:u.my_status==="signed"?e.jsx(qr,{className:"w-4 h-4",style:{color:"hsl(var(--portal-ink-muted))"}}):e.jsx(da,{className:"w-4 h-4",style:{color:"hsl(var(--portal-ink-muted))"}})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm portal-serif truncate",style:{color:"hsl(var(--portal-ink-muted))",fontSize:"1rem"},children:u.title}),e.jsx("p",{className:"text-[10px] tracking-widest uppercase mt-0.5",style:{color:"hsl(var(--portal-ink-dim))"},children:u.my_status==="signed"?"You signed — waiting on others":"Waiting on another signer"})]})]},u.id))]})]});return t?t(d):d}function X9t({updates:s}){const t=n=>{var r,a;if(n.includes("youtube.com/watch")){const i=new URL(n).searchParams.get("v");return i?`https://www.youtube.com/embed/${i}`:null}if(n.includes("youtu.be/")){const i=(r=n.split("youtu.be/")[1])==null?void 0:r.split("?")[0];return i?`https://www.youtube.com/embed/${i}`:null}if(n.includes("loom.com/share/")){const i=(a=n.split("loom.com/share/")[1])==null?void 0:a.split("?")[0];return i?`https://www.loom.com/embed/${i}`:null}return n};return e.jsxs("div",{children:[e.jsx("p",{className:"portal-eyebrow mb-2",children:"Dispatch"}),e.jsx("h2",{className:"portal-serif text-2xl mb-5",style:{color:"hsl(var(--portal-ink))"},children:"Updates from your agent"}),e.jsx("div",{className:"space-y-6",children:s.map((n,r)=>e.jsx("div",{className:r>0?"pt-6":"",style:r>0?{borderTop:"1px solid hsl(var(--portal-gold) / 0.1)"}:void 0,children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"w-8 h-8 rounded-full flex items-center justify-center flex-shrink-0 mt-0.5",style:{background:n.is_stage_change?"hsl(var(--portal-gold) / 0.15)":"hsl(var(--portal-surface-3))",border:"1px solid hsl(var(--portal-gold) / 0.25)"},children:n.is_stage_change?e.jsx(By,{className:"w-3.5 h-3.5",style:{color:"hsl(var(--portal-gold))"}}):e.jsx(qy,{className:"w-3.5 h-3.5",style:{color:"hsl(var(--portal-gold))"}})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-baseline justify-between gap-2",children:[e.jsx("h3",{className:"portal-serif",style:{fontSize:r===0?"1.4rem":"1.15rem",color:"hsl(var(--portal-ink))"},children:n.title}),e.jsx("span",{className:"text-[10px] tracking-[0.2em] uppercase flex-shrink-0",style:{color:"hsl(var(--portal-ink-dim))"},children:en(new Date(n.created_at),"MMM d")})]}),n.content&&e.jsx("p",{className:`text-sm mt-2 leading-relaxed ${r===0?"italic portal-serif":""}`,style:{color:"hsl(var(--portal-ink-muted))",fontSize:r===0?"1rem":"0.875rem"},children:r===0?`“${n.content}”`:n.content}),n.video_url&&e.jsx("div",{className:"mt-3 rounded-xl overflow-hidden aspect-video",style:{background:"hsl(var(--portal-bg))",border:"1px solid hsl(var(--portal-gold) / 0.15)"},children:e.jsx("iframe",{src:t(n.video_url)||n.video_url,className:"w-full h-full",allow:"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture",allowFullScreen:!0,title:n.title})})]})]})},n.id))})]})}const dK=[{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"}],C9s=[{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 A9s(s){return tt({queryKey:["vendors","brokerage",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await q.from("vendors").select("*").eq("owner_type","brokerage").eq("owner_brokerage_id",s).order("sort_order",{ascending:!0}).order("name",{ascending:!0});if(n)throw n;return t||[]},enabled:!!s})}function E9s(){const s=Sa(),{brokerageId:t}=vs();return tt({queryKey:["vendors","library",s,t],queryFn:async()=>{if(!s)return{vendors:[],selections:[]};let n=q.from("vendors").select("*");t?n=n.or(`and(owner_type.eq.agent,owner_user_id.eq.${s}),and(owner_type.eq.brokerage,owner_brokerage_id.eq.${t})`):n=n.eq("owner_type","agent").eq("owner_user_id",s);const[{data:r,error:a},{data:i,error:l}]=await Promise.all([n.order("sort_order",{ascending:!0}).order("name",{ascending:!0}),q.from("agent_vendor_selections").select("*").eq("agent_user_id",s)]);if(a)throw a;if(l)throw l;return{vendors:r||[],selections:i||[]}},enabled:!!s})}function T9s(){const s=Vt();return ft({mutationFn:async t=>{if(t.id){const{id:n,created_at:r,...a}=t,{data:i,error:l}=await q.from("vendors").update(a).eq("id",n).select().single();if(l)throw l;return i}else{const{data:n,error:r}=await q.from("vendors").insert(t).select().single();if(r)throw r;return n}},onSuccess:()=>s.invalidateQueries({queryKey:["vendors"]})})}function Q9t(){const s=Vt();return ft({mutationFn:async t=>{const{error:n}=await q.from("vendors").delete().eq("id",t);if(n)throw n},onSuccess:()=>s.invalidateQueries({queryKey:["vendors"]})})}function M9s(){const s=Sa(),t=Vt();return ft({mutationFn:async({vendorId:n,isVisible:r})=>{if(!s)throw new Error("No user");const{data:a}=await q.from("agent_vendor_selections").select("id").eq("agent_user_id",s).eq("vendor_id",n).maybeSingle();if(a){const{error:i}=await q.from("agent_vendor_selections").update({is_visible:r}).eq("id",a.id);if(i)throw i}else{const{error:i}=await q.from("agent_vendor_selections").insert({agent_user_id:s,vendor_id:n,is_visible:r});if(i)throw i}},onSuccess:()=>t.invalidateQueries({queryKey:["vendors"]})})}function J9t(s){return tt({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 t=s.owner_user_id,{data:n}=await q.from("profiles").select("brokerage_id").eq("id",t).maybeSingle(),r=n==null?void 0:n.brokerage_id,a=q.from("vendors").select("*").eq("is_active",!0),i=r?a.or(`and(owner_type.eq.agent,owner_user_id.eq.${t}),and(owner_type.eq.brokerage,owner_brokerage_id.eq.${r})`):a.eq("owner_type","agent").eq("owner_user_id",t),[{data:l,error:o},{data:c},{data:d}]=await Promise.all([i.order("sort_order",{ascending:!0}).order("name",{ascending:!0}),q.from("agent_vendor_selections").select("vendor_id, display_order, is_visible").eq("agent_user_id",t),q.from("portal_vendor_overrides").select("vendor_id, is_visible").eq("portal_id",s.id)]);if(o)throw o;const u=new Map;(c||[]).forEach(f=>u.set(f.vendor_id,{display_order:f.display_order,is_visible:f.is_visible}));const h=new Map;return(d||[]).forEach(f=>h.set(f.vendor_id,f.is_visible)),(l||[]).filter(f=>{if(h.get(f.id)===!1)return!1;const g=u.get(f.id);return!(g&&g.is_visible===!1&&!f.is_required)}).map(f=>{var g;return{...f,display_order:((g=u.get(f.id))==null?void 0:g.display_order)??f.sort_order??0}}).sort((f,g)=>(f.display_order||0)-(g.display_order||0))},enabled:!!(s!=null&&s.id)&&!!(s!=null&&s.owner_user_id)})}async function Cvt(s){try{await q.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 e$t(s,t){return tt({queryKey:["vendor-clicks",s,t],queryFn:async()=>{if(!t)return{};const{data:n}=await q.from("vendors").select("id").eq(s==="agent"?"owner_user_id":"owner_brokerage_id",t).eq("owner_type",s),r=(n||[]).map(l=>l.id);if(r.length===0)return{};const{data:a}=await q.from("vendor_clicks").select("vendor_id").in("vendor_id",r),i={};return(a||[]).forEach(l=>{i[l.vendor_id]=(i[l.vendor_id]||0)+1}),i},enabled:!!t})}function t$t({portalId:s,ownerUserId:t,currentStage:n,brandingColor:r,layout:a="list"}){const{data:i=[],isLoading:l}=J9t({id:s,owner_user_id:t});if(l||i.length===0)return null;const o=i.filter(b=>!b.stage_filter||b.stage_filter.length===0||!n?!0:b.stage_filter.includes(n));if(o.length===0)return null;const c=r||"#406E71",d=(b,w)=>{switch(w){case"book":return b.booking_url;case"website":return b.website;case"call":return b.phone?`tel:${b.phone.replace(/[^\d+]/g,"")}`:null;case"email":case"quote":return b.email?`mailto:${b.email}`:null}},u=b=>{const w=d(b,b.action_type);Cvt({vendorId:b.id,portalId:s,agentUserId:t,actionTaken:b.action_type}),w&&window.open(w,b.action_type==="call"||b.action_type==="email"||b.action_type==="quote"?"_self":"_blank")},h=b=>{const w=d(b,b.action_type);return[{action:"website",label:"Website",icon:e.jsx(dl,{className:"w-3.5 h-3.5"})},{action:"email",label:"Email",icon:e.jsx(mn,{className:"w-3.5 h-3.5"})},{action:"call",label:"Call",icon:e.jsx(Da,{className:"w-3.5 h-3.5"})},{action:"book",label:"Book",icon:e.jsx(Ta,{className:"w-3.5 h-3.5"})}].filter(C=>C.action!==b.action_type).map(C=>{const E=d(b,C.action);return!E||E===w?null:e.jsxs("button",{onClick:()=>{Cvt({vendorId:b.id,portalId:s,agentUserId:t,actionTaken:C.action}),window.open(E,C.action==="call"||C.action==="email"?"_self":"_blank")},className:"inline-flex items-center gap-1 text-slate-500 hover:text-slate-700 hover:underline",title:C.label,children:[C.icon,e.jsx("span",{className:"text-xs",children:C.label})]},C.action)}).filter(Boolean)},m=b=>{switch(b.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"}},f=b=>{switch(b.action_type){case"book":return e.jsx(Ta,{className:"w-3.5 h-3.5"});case"call":return e.jsx(Da,{className:"w-3.5 h-3.5"});case"email":case"quote":return e.jsx(mn,{className:"w-3.5 h-3.5"});case"website":return e.jsx(dl,{className:"w-3.5 h-3.5"})}},g=b=>{var w;return((w=dK.find(S=>S.value===b))==null?void 0:w.label)||b},x=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(Nn,{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"})]})]}),y=o.some(b=>b.disclosure_text)&&e.jsx("div",{className:"mt-4 pt-3 border-t border-slate-100 space-y-1",children:o.filter(b=>b.disclosure_text).map(b=>e.jsxs("p",{className:"text-[10px] text-slate-400",children:[e.jsxs("span",{className:"font-medium",children:[b.company||b.name,":"]})," ",b.disclosure_text]},b.id))});if(a==="grid")return e.jsxs(Ne,{className:"p-5 sm:p-6 rounded-2xl border-slate-200/80 shadow-sm bg-white/70 backdrop-blur",children:[x,e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-3",children:o.map(b=>e.jsxs("div",{className:"group flex flex-col p-4 rounded-xl border border-slate-200/70 bg-white hover:shadow-md hover:-translate-y-0.5 transition-all",children:[e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"w-12 h-12 rounded-lg bg-slate-50 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-base font-semibold text-slate-500",children:(b.company||b.name).charAt(0)})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"font-semibold 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}),e.jsx("span",{className:"inline-block mt-1 text-[10px] font-medium px-1.5 py-0.5 rounded",style:{backgroundColor:`${c}12`,color:c},children:g(b.category)})]})]}),b.description&&e.jsx("p",{className:"text-xs text-slate-500 mt-3 line-clamp-2",children:b.description}),e.jsxs("div",{className:"mt-auto pt-4 flex flex-col gap-2",children:[e.jsxs($,{size:"sm",onClick:()=>u(b),style:{backgroundColor:c},className:"text-white hover:opacity-90 w-full",children:[f(b),e.jsx("span",{className:"ml-1.5 text-xs",children:m(b)})]}),h(b).length>0&&e.jsx("div",{className:"flex flex-wrap items-center justify-center gap-3",children:h(b)})]})]},b.id))}),y]});const v=o.reduce((b,w)=>((b[w.category]=b[w.category]||[]).push(w),b),{});return e.jsxs(Ne,{className:"p-5 rounded-2xl border-slate-200/80 shadow-sm",children:[x,e.jsx("div",{className:"space-y-4",children:Object.entries(v).map(([b,w])=>e.jsxs("div",{children:[e.jsx("p",{className:"text-[11px] uppercase tracking-wide text-slate-400 font-medium mb-2",children:g(b)}),e.jsx("div",{className:"space-y-2",children:w.map(S=>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: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-sm font-semibold text-slate-500",children:S.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:S.company||S.name}),S.company&&S.name&&e.jsx("p",{className:"text-xs text-slate-500 truncate",children:S.name}),S.description&&e.jsx("p",{className:"text-xs text-slate-500 truncate mt-0.5",children:S.description})]}),e.jsxs($,{size:"sm",onClick:()=>u(S),style:{backgroundColor:c},className:"text-white hover:opacity-90 shrink-0",children:[f(S),e.jsx("span",{className:"ml-1.5 text-xs",children:m(S)})]})]},S.id))})]},b))}),y]})}function P9s(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 I9s(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 n=s.match(/loom\.com\/share\/([\w-]+)/);return n?`https://www.loom.com/embed/${n[1]}`:(s.match(/\.(mp4|webm|mov)(\?|$)/i),s)}function s$t({portalId:s,portalSlug:t,ownerUserId:n,rewardText:r,ctaHeadline:a,agentName:i,clientName:l,reviewUrl:o,hubVideoUrl:c}){const[d,u]=j.useState(!1),h=j.useRef(!1),m=P9s(t);j.useEffect(()=>{h.current||(h.current=!0,q.from("portal_referral_clicks").insert({portal_id:s,owner_user_id:n,click_type:"card_view",user_agent:navigator.userAgent.slice(0,500)}).then(()=>{}))},[s,n]);const f=async E=>{await q.from("portal_referral_clicks").insert({portal_id:s,owner_user_id:n,click_type:E,user_agent:navigator.userAgent.slice(0,500)})},g=()=>`${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: ${m}`,x=async()=>{await navigator.clipboard.writeText(m),u(!0),f("copy_link"),setTimeout(()=>u(!1),2e3)},y=()=>{f("share_sms");const E=encodeURIComponent(g());window.location.href=`sms:?&body=${E}`},v=()=>{f("share_email");const E=encodeURIComponent("A referral you'll thank me for"),I=encodeURIComponent(g());window.location.href=`mailto:?subject=${E}&body=${I}`},b=()=>{f("open_form"),window.open(m,"_blank")},w=a||"Know someone buying or selling?",S=c?I9s(c):null,C=S==null?void 0:S.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."})]}),S&&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(Nn,{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:C?e.jsx("video",{src:S,controls:!0,className:"w-full h-full",playsInline:!0}):e.jsx("iframe",{src:S,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(ul,{className:"w-3 h-3"}),"Referral Program"]}),e.jsx("h3",{className:"text-xl font-bold leading-tight mb-2 font-serif",children:w}),r&&e.jsxs("p",{className:"text-sm text-white/85 mb-1",children:[e.jsx("span",{className:"font-semibold text-white",children:"Your reward:"})," ",r]}),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:b,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(ei,{className:"w-4 h-4"})]}),e.jsxs("div",{className:"mt-4 grid grid-cols-3 gap-2",children:[e.jsxs("button",{onClick:y,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(Th,{className:"w-3.5 h-3.5"}),"Text"]}),e.jsxs("button",{onClick:v,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(mn,{className:"w-3.5 h-3.5"}),"Email"]}),e.jsxs("button",{onClick:x,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(la,{className:"w-3.5 h-3.5"}):e.jsx(Ha,{className:"w-3.5 h-3.5"}),d?"Copied":"Copy"]})]})]})]}),o&&e.jsx("a",{href:o,target:"_blank",rel:"noopener noreferrer",onClick:()=>f("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(ei,{className:"w-4 h-4 text-slate-400"})]})})]})}function n$t(s){return tt({queryKey:["portal-messages",s],queryFn:async()=>{const{data:t,error:n}=await q.from("portal_messages").select("*").eq("portal_id",s).order("created_at",{ascending:!0});if(n)throw n;return t||[]},enabled:!!s,refetchInterval:3e4})}function r$t(){const s=Vt();return ft({mutationFn:async({portalId:t,senderType:n,senderName:r,body:a,deviceFingerprint:i,portalUrl:l})=>{const{data:o,error:c}=await q.from("portal_messages").insert({portal_id:t,sender_type:n,sender_name:r||null,body:a.trim(),device_fingerprint:i||null,...n==="agent"?{read_at:new Date().toISOString()}:{}}).select().single();if(c)throw c;try{await q.functions.invoke("portal-message-notify",{body:{message_id:o.id,portal_url:l}})}catch(d){console.error("portal-message-notify failed",d)}return o},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["portal-messages",n.portalId]}),s.invalidateQueries({queryKey:["portal-unread-messages"]}),s.invalidateQueries({queryKey:["portal-conversations"]})}})}function L9s(){const s=Vt();return ft({mutationFn:async t=>{const{error:n}=await q.from("portal_messages").update({read_at:new Date().toISOString()}).eq("portal_id",t).eq("sender_type","client").is("read_at",null);if(n)throw n},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["portal-messages",n]}),s.invalidateQueries({queryKey:["portal-unread-messages"]}),s.invalidateQueries({queryKey:["portal-conversations"]})}})}function a$t(){const s=Sa();return tt({queryKey:["portal-conversations",s],queryFn:async()=>{const{data:t,error:n}=await q.from("client_portals").select("id, slug, client_name, client_email, archived_at").eq("owner_user_id",s).is("archived_at",null);if(n)throw n;if(!t||t.length===0)return[];const r=t.map(c=>c.id),a=[],i=100,l=1e3;for(let c=0;c{const d=o.get(c.id)||[];return{portalId:c.id,slug:c.slug,clientName:c.client_name,clientEmail:c.client_email,lastMessage:d.length?d[d.length-1]:null,unreadCount:d.filter(u=>u.sender_type==="client"&&!u.read_at).length,messageCount:d.length}}).sort((c,d)=>{var m,f;const u=((m=c.lastMessage)==null?void 0:m.created_at)||"",h=((f=d.lastMessage)==null?void 0:f.created_at)||"";return u===h?(c.clientName||"").localeCompare(d.clientName||""):h.localeCompare(u)})},enabled:!!s,refetchInterval:3e4})}function i$t({portalId:s,clientName:t,agentName:n,agentAvatar:r,deviceFingerprint:a}){const{data:i,isLoading:l}=n$t(s),o=r$t(),[c,d]=j.useState(""),u=`portal_msg_name_${s}`,[h,m]=j.useState(()=>localStorage.getItem(u)||t||""),f=j.useRef(null);j.useEffect(()=>{var y;(y=f.current)==null||y.scrollIntoView({block:"nearest"})},[i==null?void 0:i.length]);const g=async()=>{const y=c.trim();if(!y)return;const v=(h||t||"").trim();if(!v){re.error("Please add your name first");return}try{localStorage.setItem(u,v),await o.mutateAsync({portalId:s,senderType:"client",senderName:v,body:y,deviceFingerprint:a,portalUrl:window.location.href}),d(""),re.success("Message sent")}catch(b){re.error((b==null?void 0:b.message)||"Could not send your message")}},x="hsl(var(--portal-gold))";return e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2 mb-4",children:[e.jsx(eo,{className:"w-4 h-4",style:{color:x}}),e.jsx("h2",{className:"portal-serif",style:{fontSize:"1.35rem",color:"hsl(var(--portal-ink))"},children:"Messages"})]}),e.jsx("div",{className:"portal-hairline mb-4"}),e.jsxs("div",{className:"space-y-3 max-h-[340px] overflow-y-auto pr-1",children:[l&&e.jsx("div",{className:"flex justify-center py-6",children:e.jsx(kt,{className:"w-4 h-4 animate-spin",style:{color:x}})}),!l&&(!i||i.length===0)&&e.jsxs("p",{className:"text-sm",style:{color:"hsl(var(--portal-ink-muted))"},children:["Have a question for ",n||"your agent","? Send a message below — they'll be notified right away."]}),i==null?void 0:i.map(y=>{const v=y.sender_type==="agent";return e.jsx("div",{className:`flex ${v?"justify-start":"justify-end"}`,children:e.jsxs("div",{className:"max-w-[85%] rounded-2xl px-4 py-3",style:{background:v?"hsl(var(--portal-surface-2))":"hsl(var(--portal-gold) / 0.12)",border:`1px solid ${v?"hsl(var(--portal-gold) / 0.12)":"hsl(var(--portal-gold) / 0.28)"}`},children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[v&&r&&e.jsx("img",{src:r,alt:n||"Agent",className:"w-5 h-5 rounded-full object-cover"}),e.jsxs("span",{className:"text-[11px] uppercase tracking-[0.14em]",style:{color:"hsl(var(--portal-ink-dim))"},children:[v?n||"Your agent":y.sender_name||"You"," ·"," ",en(new Date(y.created_at),"MMM d, h:mm a")]})]}),e.jsx("p",{className:"text-sm whitespace-pre-wrap leading-relaxed",style:{color:"hsl(var(--portal-ink))"},children:y.body})]})},y.id)}),e.jsx("div",{ref:f})]}),e.jsxs("div",{className:"mt-4 space-y-2",children:[!t&&e.jsx("input",{value:h,onChange:y=>m(y.target.value),placeholder:"Your name",className:"w-full rounded-xl px-3 py-2 text-sm outline-none",style:{background:"hsl(var(--portal-surface-2))",border:"1px solid hsl(var(--portal-gold) / 0.18)",color:"hsl(var(--portal-ink))"}}),e.jsx("textarea",{value:c,onChange:y=>d(y.target.value),rows:3,placeholder:`Write a message to ${n||"your agent"}...`,className:"w-full rounded-xl px-3 py-2 text-sm outline-none resize-none",style:{background:"hsl(var(--portal-surface-2))",border:"1px solid hsl(var(--portal-gold) / 0.18)",color:"hsl(var(--portal-ink))"}}),e.jsxs("button",{onClick:g,disabled:o.isPending||!c.trim(),className:"w-full flex items-center justify-center gap-2 rounded-xl py-2.5 text-sm font-medium transition-opacity disabled:opacity-50",style:{background:"hsl(var(--portal-gold) / 0.16)",border:"1px solid hsl(var(--portal-gold) / 0.35)",color:x},children:[o.isPending?e.jsx(kt,{className:"w-4 h-4 animate-spin"}):e.jsx(Yr,{className:"w-4 h-4"}),"Send message"]})]})]})}function R9s(s){return s==="buy-side"?"Home Search in Progress":s==="listing"?"Your Home Is On The Market":"Active Phase"}function D9s(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 F9s={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. 🎉"}},o$t=["Lead","Consultation","Agreement Signed","Active","Under Contract","Closing","Closed Won"];function n6e(s){return o$t.map(t=>{if(t==="Active")return{key:"Active",label:R9s(s),description:D9s(s)};const n=F9s[t];return{key:t,label:n.label,description:n.description}})}function HEe(s){if(!s)return 0;const t=o$t.indexOf(s);return t>=0?t:0}function O9s({portal:s,linkedPortal:t,activePortal:n,activeTab:r,onTabChange:a,agentProfile:i,branding:l,updates:o,documents:c}){var G,Y,X;const d=(l==null?void 0:l.cover_photo_url)||null,u=(l==null?void 0:l.logo_url)||null,h=(l==null?void 0:l.tagline)||"Your Real Estate Concierge",m=n==null?void 0:n.deal_pipeline,f=m==null?void 0:m.deal_pipeline_stages,g=f==null?void 0:f.is_won_stage,x=m==null?void 0:m.deal_type,y=n==null?void 0:n.stage_mapping;let v=n6e(x);y&&y.length>0&&(v=y.map((ae,ie)=>{var ne,te;return{key:`custom-${ie}`,label:ae.label||((ne=v[ie])==null?void 0:ne.label)||`Stage ${ie+1}`,description:ae.description||((te=v[ie])==null?void 0:te.description)||"",video_url:ae.video_url||void 0}}));const b=y&&y.length>0?Math.min(HEe(f==null?void 0:f.name),v.length-1):HEe(f==null?void 0:f.name),w=v[b],S=w==null?void 0:w.video_url,C=g&&n.show_post_close_tips!==!1&&n.referral_enabled!==!1,E=m!=null&&m.property_address?`${m.property_address}, ${m.city||""}, ${m.state||""}`.replace(/,\s*,/g,",").replace(/,\s*$/,""):null,I=!!t,P=(G=s==null?void 0:s.deal_pipeline)==null?void 0:G.deal_type,R=(Y=t==null?void 0:t.deal_pipeline)==null?void 0:Y.deal_type,D=ae=>ae==="listing"?"Your Sale":ae==="buy-side"?"Your Purchase":"Transaction",O=v.length>1?Math.round((b+1)/v.length*100):0,{data:U=[]}=J9t({id:n==null?void 0:n.id,owner_user_id:n==null?void 0:n.owner_user_id}),W=U.some(ae=>!ae.stage_filter||ae.stage_filter.length===0||!(f!=null&&f.name)?!0:ae.stage_filter.includes(f.name)),V=()=>{var ae;(ae=document.getElementById("trusted-vendors"))==null||ae.scrollIntoView({behavior:"smooth",block:"start"})};return e.jsxs("div",{className:"min-h-screen relative",style:{background:"var(--portal-gradient-noir)"},children:[e.jsx("div",{className:"pointer-events-none absolute inset-x-0 top-0 h-[600px] opacity-70",style:{background:"radial-gradient(ellipse 70% 100% at 50% 0%, hsl(var(--portal-gold) / 0.08), transparent 60%)"}}),e.jsxs("div",{className:"relative max-w-[1400px] mx-auto px-8 py-8",children:[e.jsxs(Br.div,{initial:{opacity:0,y:-6},animate:{opacity:1,y:0},transition:{duration:.4},className:"flex items-center justify-between mb-8",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[u?e.jsx("div",{className:"rounded-lg px-3 py-1.5",style:{background:"hsl(0 0% 100% / 0.04)",border:"1px solid hsl(var(--portal-gold) / 0.2)"},children:e.jsx("img",{src:u,alt:"Brand",className:"h-8 max-w-[140px] object-contain"})}):e.jsx("div",{className:"w-10 h-10 rounded-lg flex items-center justify-center portal-serif text-xl",style:{background:"var(--portal-gradient-gold)",color:"hsl(var(--portal-bg))"},children:"✦"}),e.jsxs("div",{children:[e.jsx("p",{className:"portal-eyebrow",children:"Private Client Portal"}),e.jsx("p",{className:"portal-serif mt-0.5",style:{fontSize:"1.1rem",color:"hsl(var(--portal-ink))"},children:n!=null&&n.client_name?`Welcome, ${n.client_name.split(" ")[0]}`:"Your transaction"})]})]}),e.jsxs("div",{className:"flex items-center gap-2 text-[10px] tracking-[0.22em] uppercase",style:{color:"hsl(var(--portal-ink-dim))"},children:[e.jsx(Mf,{className:"w-3 h-3",style:{color:"hsl(var(--portal-gold))"}}),"Secure & Encrypted"]})]}),e.jsxs(Br.div,{initial:{opacity:0,y:12},animate:{opacity:1,y:0},transition:{duration:.6,ease:"easeOut"},className:"relative overflow-hidden rounded-3xl mb-8",style:{minHeight:380,border:"1px solid hsl(var(--portal-gold) / 0.25)",boxShadow:"var(--portal-shadow-luxe)"},children:[d?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"absolute inset-0",style:{backgroundImage:`url(${d})`,backgroundSize:"cover",backgroundPosition:"center",filter:"var(--portal-hero-filter)"}}),e.jsx("div",{className:"absolute inset-0",style:{background:"var(--portal-hero-scrim)"}})]}):e.jsx("div",{className:"absolute inset-0",style:{background:"var(--portal-hero-fallback)"}}),e.jsx("div",{className:"absolute top-0 left-0 right-0 h-[1px]",style:{background:"linear-gradient(90deg, transparent, hsl(var(--portal-gold) / 0.6), transparent)"}}),e.jsxs("div",{className:"relative grid grid-cols-3 gap-8 p-12",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 rounded-full px-3 py-1 text-[10px] tracking-[0.22em] uppercase mb-6 self-start",style:{background:"hsl(0 0% 0% / 0.28)",backdropFilter:"blur(6px)",border:"1px solid var(--portal-hero-accent)",color:"var(--portal-hero-accent)"},children:[e.jsx(va,{className:"w-3 h-3"}),x==="listing"?"Sale":x==="buy-side"?"Purchase":"Transaction",g&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"opacity-50 mx-1",children:"·"}),"Complete"]})]}),e.jsx("h1",{className:"portal-serif leading-[0.95] mb-4",style:{fontSize:"4.5rem",color:"var(--portal-hero-ink)",textShadow:"var(--portal-hero-text-shadow)"},children:(m==null?void 0:m.deal_name)||"Your Transaction"}),e.jsx("div",{className:"portal-hairline w-32 mb-5"}),E&&e.jsxs("div",{className:"flex items-center gap-2",style:{color:"var(--portal-hero-ink-muted)",textShadow:"var(--portal-hero-text-shadow)"},children:[e.jsx(ci,{className:"w-4 h-4",style:{color:"var(--portal-hero-accent)"}}),e.jsx("span",{className:"text-base",children:E})]}),(n==null?void 0:n.welcome_message)&&e.jsxs("p",{className:"mt-6 portal-serif italic leading-relaxed max-w-2xl",style:{color:"var(--portal-hero-ink-muted)",fontSize:"1.15rem",textShadow:"var(--portal-hero-text-shadow)"},children:["“",n.welcome_message,"”"]})]}),e.jsxs("div",{className:"flex flex-col items-center justify-center",children:[e.jsx(z9s,{pct:O}),e.jsx("p",{className:"portal-eyebrow mt-4",style:{color:"var(--portal-hero-accent)"},children:"Journey Progress"}),e.jsxs("p",{className:"portal-serif mt-1",style:{fontSize:"1.1rem",color:"var(--portal-hero-ink)",textShadow:"var(--portal-hero-text-shadow)"},children:["Stage ",b+1," of ",v.length]})]})]}),e.jsx("div",{className:"absolute bottom-0 left-0 right-0 h-[1px]",style:{background:"linear-gradient(90deg, transparent, hsl(var(--portal-gold) / 0.4), transparent)"}})]}),I&&e.jsx("div",{className:"inline-flex gap-1 rounded-xl p-1 mb-8",style:{background:"hsl(var(--portal-surface))",border:"1px solid hsl(var(--portal-gold) / 0.15)"},children:["primary","linked"].map(ae=>{const ie=ae==="primary"?P:R,ne=r===ae;return e.jsx("button",{onClick:()=>a(ae),className:"portal-serif px-5 py-2 rounded-lg transition-all",style:{fontSize:"1rem",background:ne?"hsl(var(--portal-surface-3))":"transparent",color:ne?"hsl(var(--portal-gold))":"hsl(var(--portal-ink-muted))",borderBottom:ne?"1px solid hsl(var(--portal-gold))":"1px solid transparent"},children:D(ie)},ae)})}),e.jsxs(Br.div,{initial:"hidden",animate:"show",variants:{hidden:{},show:{transition:{staggerChildren:.06}}},className:"grid grid-cols-12 gap-5",children:[e.jsx("aside",{className:"col-span-3 space-y-5",children:e.jsxs("div",{className:"sticky top-6 space-y-5",children:[e.jsxs(s5,{children:[e.jsxs("div",{className:"text-center pt-2 pb-1",children:[i!=null&&i.avatar_url?e.jsx("div",{className:"w-24 h-24 mx-auto relative",children:e.jsx("div",{className:"absolute inset-0 rounded-full",style:{background:"var(--portal-gradient-gold)",padding:"2px"},children:e.jsx("img",{src:i.avatar_url,alt:i.name,className:"w-full h-full rounded-full object-cover",style:{background:"hsl(var(--portal-surface))"}})})}):e.jsx("div",{className:"w-24 h-24 rounded-full mx-auto flex items-center justify-center portal-serif text-3xl",style:{background:"hsl(var(--portal-surface-2))",border:"1px solid hsl(var(--portal-gold) / 0.4)",color:"hsl(var(--portal-gold))"},children:((X=i==null?void 0:i.name)==null?void 0:X.charAt(0))||"?"}),e.jsx("h3",{className:"mt-4 portal-serif",style:{fontSize:"1.5rem",color:"hsl(var(--portal-ink))"},children:i==null?void 0:i.name}),e.jsx("div",{className:"portal-hairline w-12 mx-auto my-2"}),e.jsx("p",{className:"text-[10px] tracking-[0.22em] uppercase",style:{color:"hsl(var(--portal-ink-dim))"},children:h})]}),e.jsxs("div",{className:"mt-5 space-y-2",children:[(i==null?void 0:i.phone)&&e.jsx(R7e,{href:`tel:${i.phone}`,icon:Da,label:"Call",sub:i.phone}),(i==null?void 0:i.phone)&&e.jsx(R7e,{href:`sms:${i.phone}`,icon:Th,label:"Text message"}),(i==null?void 0:i.email)&&e.jsx(R7e,{href:`mailto:${i.email}`,icon:mn,label:"Email",sub:i.email})]})]}),e.jsxs(s5,{children:[e.jsx("p",{className:"portal-eyebrow mb-4",children:"At a Glance"}),e.jsxs("div",{className:"space-y-4",children:[(m==null?void 0:m.target_close_date)&&e.jsx(D7e,{icon:Ta,label:"Target close",value:Avt(m.target_close_date)}),(m==null?void 0:m.contract_date)&&e.jsx(D7e,{icon:da,label:"Under contract",value:Avt(m.contract_date)}),e.jsx(D7e,{icon:Tl,label:"Progress",value:`${O}%`})]})]})]})}),e.jsxs("main",{className:"col-span-6 space-y-5",children:[C&&e.jsx(s$t,{portalId:n.id,portalSlug:n.slug,ownerUserId:n.owner_user_id,rewardText:n.referral_reward_text,ctaHeadline:n.referral_cta_headline,agentName:i==null?void 0:i.name,clientName:n.client_name,reviewUrl:n.review_url,hubVideoUrl:n.homeowner_hub_video_url}),e.jsx(H9t,{targetCloseDate:m==null?void 0:m.target_close_date,actualCloseDate:m==null?void 0:m.actual_close_date,clientName:n.client_name}),w&&e.jsx(s5,{children:e.jsx(W9t,{currentStage:w,nextStepText:n.next_step_text,nextStepVideoUrl:S||n.next_step_video_url})}),e.jsx(s5,{children:e.jsx(G9t,{journeyStages:v,currentIndex:b})}),o&&o.length>0&&e.jsx(s5,{children:e.jsx(X9t,{updates:o})}),(n==null?void 0:n.id)&&e.jsx(s5,{children:e.jsx(i$t,{portalId:n.id,clientName:n.client_name,agentName:i==null?void 0:i.name,agentAvatar:i==null?void 0:i.avatar_url})})]}),e.jsxs("aside",{className:"col-span-3 space-y-5",children:[e.jsx(s5,{children:e.jsx(K9t,{deal:m,portal:n})}),(n==null?void 0:n.slug)&&e.jsx(Z9t,{slug:n.slug,wrapper:ae=>e.jsx(s5,{children:ae})}),c&&c.length>0&&e.jsx(s5,{children:e.jsx(Y9t,{documents:c})}),W&&e.jsx(s5,{children:e.jsxs("button",{onClick:V,className:"w-full flex items-center gap-3 rounded-xl px-3 py-3 transition-all text-left group",style:{background:"hsl(var(--portal-gold) / 0.06)",border:"1px solid hsl(var(--portal-gold) / 0.2)"},onMouseEnter:ae=>{ae.currentTarget.style.background="hsl(var(--portal-gold) / 0.12)"},onMouseLeave:ae=>{ae.currentTarget.style.background="hsl(var(--portal-gold) / 0.06)"},children:[e.jsx("div",{className:"w-10 h-10 rounded-lg flex items-center justify-center shrink-0",style:{background:"hsl(var(--portal-gold) / 0.15)",color:"hsl(var(--portal-gold))"},children:e.jsx(oV,{className:"w-4 h-4"})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"portal-serif",style:{fontSize:"1.05rem",color:"hsl(var(--portal-ink))"},children:"Trusted Vendors"}),e.jsx("p",{className:"text-[10px] tracking-[0.2em] uppercase mt-0.5",style:{color:"hsl(var(--portal-ink-dim))"},children:"My hand-picked network"})]}),e.jsx(Tl,{className:"w-4 h-4",style:{color:"hsl(var(--portal-gold))"}})]})}),e.jsxs("div",{className:"text-center pt-2 space-y-2",children:[e.jsx("div",{className:"portal-hairline w-12 mx-auto"}),e.jsx("p",{className:"text-[10px] tracking-[0.25em] uppercase",style:{color:"hsl(var(--portal-ink-dim))"},children:"Powered by ReLevelUp"})]})]})]}),(n==null?void 0:n.id)&&(n==null?void 0:n.owner_user_id)&&e.jsx("div",{id:"trusted-vendors",className:"mt-8 scroll-mt-10",children:e.jsx(t$t,{portalId:n.id,ownerUserId:n.owner_user_id,currentStage:f==null?void 0:f.name,brandingColor:"hsl(var(--portal-gold))",layout:"grid"})})]})]})}function s5({children:s}){return e.jsx(Br.div,{variants:{hidden:{opacity:0,y:10},show:{opacity:1,y:0,transition:{duration:.45,ease:"easeOut"}}},className:"portal-tile p-6",children:s})}function R7e({href:s,icon:t,label:n,sub:r}){return e.jsxs("a",{href:s,className:"flex items-center gap-3 rounded-xl px-3 py-2.5 transition-all",style:{background:"hsl(var(--portal-gold) / 0.05)",border:"1px solid hsl(var(--portal-gold) / 0.12)"},onMouseEnter:a=>{a.currentTarget.style.background="hsl(var(--portal-gold) / 0.1)",a.currentTarget.style.borderColor="hsl(var(--portal-gold) / 0.3)"},onMouseLeave:a=>{a.currentTarget.style.background="hsl(var(--portal-gold) / 0.05)",a.currentTarget.style.borderColor="hsl(var(--portal-gold) / 0.12)"},children:[e.jsx("div",{className:"w-9 h-9 rounded-lg flex items-center justify-center shrink-0",style:{background:"hsl(var(--portal-gold) / 0.15)",color:"hsl(var(--portal-gold))"},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 portal-serif",style:{color:"hsl(var(--portal-ink))",fontSize:"1rem"},children:n}),r&&e.jsx("p",{className:"text-[10px] tracking-[0.15em] uppercase truncate mt-0.5",style:{color:"hsl(var(--portal-ink-dim))"},children:r})]})]})}function D7e({icon:s,label:t,value: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:{background:"hsl(var(--portal-gold) / 0.1)",color:"hsl(var(--portal-gold))"},children:e.jsx(s,{className:"w-4 h-4"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-[10px] tracking-[0.2em] uppercase",style:{color:"hsl(var(--portal-ink-dim))"},children:t}),e.jsx("p",{className:"portal-serif truncate",style:{fontSize:"1.05rem",color:"hsl(var(--portal-ink))"},children:n})]})]})}function z9s({pct:s}){const a=2*Math.PI*78,i=a-s/100*a;return e.jsxs("div",{className:"relative",style:{width:170,height:170},children:[e.jsxs("svg",{width:170,height:170,className:"-rotate-90",children:[e.jsx("defs",{children:e.jsxs("linearGradient",{id:"portal-progress-gold",x1:"0%",y1:"0%",x2:"100%",y2:"100%",children:[e.jsx("stop",{offset:"0%",stopColor:"var(--portal-hero-accent)"}),e.jsx("stop",{offset:"100%",stopColor:"var(--portal-hero-ink)"})]})}),e.jsx("circle",{cx:170/2,cy:170/2,r:78,stroke:"hsl(0 0% 100% / 0.22)",strokeWidth:2,fill:"none"}),e.jsx(Br.circle,{cx:170/2,cy:170/2,r:78,stroke:"url(#portal-progress-gold)",strokeWidth:3,strokeLinecap:"round",fill:"none",initial:{strokeDashoffset:a},animate:{strokeDashoffset:i},transition:{duration:1.4,ease:"easeOut"},strokeDasharray:a,style:{filter:"drop-shadow(0 0 6px hsl(0 0% 0% / 0.45))"}})]}),e.jsxs("div",{className:"absolute inset-0 flex flex-col items-center justify-center",children:[e.jsx("span",{className:"portal-serif tabular-nums leading-none",style:{fontSize:"3rem",color:"var(--portal-hero-ink)",textShadow:"var(--portal-hero-text-shadow)"},children:s}),e.jsx("span",{className:"text-[10px] tracking-[0.25em] uppercase mt-1",style:{color:"var(--portal-hero-ink-dim)",textShadow:"var(--portal-hero-text-shadow)"},children:"percent"})]})]})}function Avt(s){const t=s.split(/[-/T]/),n=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(n)}function B9s({portal:s,dealData:t,agentProfile:n,customQuestions:r,deviceFingerprint:a,onComplete:i}){var y,v;const[l,o]=j.useState({first_name:((y=s.client_name)==null?void 0:y.split(" ")[0])||"",last_name:((v=s.client_name)==null?void 0:v.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]=j.useState({}),[u,h]=j.useState(!1),m=ft({mutationFn:async()=>{const{error:b}=await q.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:u&&l.spouse_first_name||null,spouse_last_name:u&&l.spouse_last_name||null,spouse_email:u&&l.spouse_email||null,spouse_phone:u&&l.spouse_phone||null});if(b)throw b},onSuccess:i,onError:b=>{console.error("[PortalOnboarding] Submit failed:",b),re.error("Something went wrong. Please try again.")}}),f=t!=null&&t.property_address?`${t.property_address}, ${t.city||""}, ${t.state||""}`:null,g="mt-1 rounded-xl bg-white text-slate-900 placeholder:text-slate-400 border-slate-200 focus-visible:ring-slate-400",x="mt-1 w-full rounded-xl border border-slate-200 bg-white text-slate-900 placeholder:text-slate-400 px-3 py-2 text-sm focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-slate-400";return e.jsx("div",{className:"max-w-md mx-auto px-4 py-10",children:e.jsxs("div",{className:"bg-white rounded-2xl shadow-xl ring-1 ring-slate-200 p-6 sm:p-8",children:[e.jsxs("div",{className:"text-center mb-8",children:[(n==null?void 0:n.avatar_url)&&e.jsx("img",{src:n.avatar_url,alt:n.name,className:"w-16 h-16 rounded-full border-2 border-slate-200 mx-auto mb-3 object-cover"}),e.jsx("h1",{className:"text-2xl font-bold text-slate-900",children:"Welcome to Your Portal"}),f&&e.jsxs("div",{className:"flex items-center justify-center gap-1 text-slate-500 text-sm mt-1",children:[e.jsx(ci,{className:"w-3.5 h-3.5"}),e.jsx("span",{children:f.replace(/,\s*,/g,",").replace(/,\s*$/,"")})]}),e.jsx("p",{className:"text-sm text-slate-600 mt-2",children:"Please fill in your details to access your transaction portal."})]}),e.jsxs("form",{onSubmit:b=>{b.preventDefault(),m.mutate()},className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs font-medium text-slate-700",children:"First Name *"}),e.jsx(pe,{required:!0,value:l.first_name,onChange:b=>o(w=>({...w,first_name:b.target.value})),className:g,placeholder:"John"})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs font-medium text-slate-700",children:"Last Name"}),e.jsx(pe,{value:l.last_name,onChange:b=>o(w=>({...w,last_name:b.target.value})),className:g,placeholder:"Doe"})]})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs font-medium text-slate-700",children:"Email"}),e.jsx(pe,{type:"email",value:l.email,onChange:b=>o(w=>({...w,email:b.target.value})),className:g,placeholder:"john@example.com"})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs font-medium text-slate-700",children:"Phone"}),e.jsx(pe,{type:"tel",value:l.phone,onChange:b=>o(w=>({...w,phone:b.target.value})),className:g,placeholder:"(555) 123-4567"})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs font-medium text-slate-700",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(w=>({...w,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(ee,{className:"text-xs font-medium text-slate-700",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(w=>({...w,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))})]}),r.map(b=>e.jsxs("div",{children:[e.jsxs(ee,{className:"text-xs font-medium text-slate-700",children:[b.question_text," ",b.is_required&&"*"]}),b.field_type==="text"&&e.jsx(pe,{required:b.is_required,value:c[b.id]||"",onChange:w=>d(S=>({...S,[b.id]:w.target.value})),className:g}),b.field_type==="textarea"&&e.jsx("textarea",{required:b.is_required,value:c[b.id]||"",onChange:w=>d(S=>({...S,[b.id]:w.target.value})),className:`${x} min-h-[80px]`}),b.field_type==="dropdown"&&e.jsxs("select",{required:b.is_required,value:c[b.id]||"",onChange:w=>d(S=>({...S,[b.id]:w.target.value})),className:`${x} h-10`,children:[e.jsx("option",{value:"",children:"Select..."}),(b.options||[]).map(w=>e.jsx("option",{value:w,children:w},w))]}),b.field_type==="toggle"&&e.jsx("div",{className:"mt-1.5 flex gap-2",children:["Yes","No"].map(w=>e.jsx("button",{type:"button",onClick:()=>d(S=>({...S,[b.id]:w})),className:`px-3.5 py-1.5 rounded-full text-xs font-medium border transition-colors ${c[b.id]===w?"bg-slate-800 text-white border-slate-800":"bg-white text-slate-600 border-slate-200"}`,children:w},w))})]},b.id)),e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs font-medium text-slate-700",children:"Notes for your agent"}),e.jsx("textarea",{value:l.notes,onChange:b=>o(w=>({...w,notes:b.target.value})),className:`${x} min-h-[60px]`,placeholder:"Anything you'd like your agent to know..."})]}),s.allow_spouse&&e.jsxs("div",{children:[e.jsx("button",{type:"button",onClick:()=>h(!u),className:"text-sm text-blue-600 hover:text-blue-700 font-medium",children:u?"− Remove spouse/partner":"+ Add spouse/partner"}),u&&e.jsxs("div",{className:"mt-3 p-4 bg-slate-50 rounded-xl border border-slate-200 space-y-3",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs font-medium text-slate-700",children:"First Name"}),e.jsx(pe,{value:l.spouse_first_name,onChange:b=>o(w=>({...w,spouse_first_name:b.target.value})),className:g})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs font-medium text-slate-700",children:"Last Name"}),e.jsx(pe,{value:l.spouse_last_name,onChange:b=>o(w=>({...w,spouse_last_name:b.target.value})),className:g})]})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs font-medium text-slate-700",children:"Email"}),e.jsx(pe,{type:"email",value:l.spouse_email,onChange:b=>o(w=>({...w,spouse_email:b.target.value})),className:g})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs font-medium text-slate-700",children:"Phone"}),e.jsx(pe,{type:"tel",value:l.spouse_phone,onChange:b=>o(w=>({...w,spouse_phone:b.target.value})),className:g})]})]})]}),e.jsx($,{type:"submit",disabled:m.isPending||!l.first_name,className:"w-full h-12 rounded-full text-sm font-semibold bg-slate-900 hover:bg-slate-800",children:m.isPending?"Submitting...":"Access My Portal"})]})]})})}function $9s(s,t){const n=(r,a)=>a!=null&&a!==""?a:r!=null&&r!==""?r:null;return{logo_url:n(s==null?void 0:s.logo_url,t==null?void 0:t.logo_url),cover_photo_url:n(s==null?void 0:s.cover_photo_url,t==null?void 0:t.cover_photo_url),brand_color:n(s==null?void 0:s.brand_color,t==null?void 0:t.brand_color),accent_color:n(s==null?void 0:s.accent_color,t==null?void 0:t.accent_color),tagline:n(s==null?void 0:s.tagline,t==null?void 0:t.tagline),welcome_message:n(s==null?void 0:s.welcome_message,t==null?void 0:t.welcome_message),portal_theme:n(s==null?void 0:s.portal_theme,t==null?void 0:t.portal_theme)||"noir"}}function l$t(){const s=Sa();return tt({queryKey:["agent-portal-branding",s],queryFn:async()=>{if(!s)return null;const{data:t,error:n}=await q.from("agent_portal_branding").select("*").eq("user_id",s).maybeSingle();if(n)throw n;return t},enabled:!!s})}function U9s(s){return tt({queryKey:["agent-portal-branding-public",s],queryFn:async()=>{if(!s)return null;const{data:t,error:n}=await q.from("agent_portal_branding").select("logo_url, cover_photo_url, brand_color, accent_color, tagline, welcome_message, portal_theme").eq("user_id",s).maybeSingle();if(n)throw n;return t},enabled:!!s})}function q9s(){const s=Sa(),t=Vt();return ft({mutationFn:async n=>{if(!s)throw new Error("Not authenticated");const{data:r,error:a}=await q.from("agent_portal_branding").upsert({user_id:s,...n},{onConflict:"user_id"}).select().single();if(a)throw a;return r},onSuccess:()=>{t.invalidateQueries({queryKey:["agent-portal-branding",s]}),t.invalidateQueries({queryKey:["agent-portal-branding-public",s]})}})}async function c$t(s,t,n){var o;const r=((o=t.name.split(".").pop())==null?void 0:o.toLowerCase())||"png",a=`${s}/${n}-${Date.now()}.${r}`,{error:i}=await q.storage.from("portal-branding").upload(a,t,{upsert:!0,cacheControl:"3600"});if(i)throw i;const{data:l}=q.storage.from("portal-branding").getPublicUrl(a);return l.publicUrl}function V9s(s,t){return tt({queryKey:["client-portal-public",s],queryFn:async()=>{if(!s)return null;const{data:n,error:r}=await q.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, earnest_money_due_date, inspection_date, inspection_contingency_date, appraisal_date, loan_approval_date, title_docs_due_date, final_walkthrough_date, completed_key_dates, 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(r)throw r;return n},enabled:t})}function H9s(s){return tt({queryKey:["client-portal-by-id",s],queryFn:async()=>{if(!s)return null;const{data:t,error:n}=await q.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, earnest_money_due_date, inspection_date, inspection_contingency_date, appraisal_date, loan_approval_date, title_docs_due_date, final_walkthrough_date, completed_key_dates, 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(n)throw n;return t},enabled:!!s})}function d$t({slug:s}){var ie,ne,te,J,ce,_e;const[t,n]=j.useState(!1),[r,a]=j.useState("primary"),[i]=j.useState(()=>{const he=`portal_fp_${s}`;let ue=localStorage.getItem(he);return ue||(ue=localStorage.getItem("portal_fp"),ue?localStorage.setItem(he,ue):(ue=crypto.randomUUID(),localStorage.setItem(he,ue),localStorage.setItem("portal_fp",ue))),ue});j.useEffect(()=>(document.body.classList.add("client-portal-page"),()=>document.body.classList.remove("client-portal-page")),[]);const{data:l,isLoading:o,error:c}=V9s(s,!0),d=l==null?void 0:l.linked_portal_id,{data:u}=H9s(d),h=(ie=l==null?void 0:l.deal_pipeline)==null?void 0:ie.owner_user_id,{data:m}=tt({queryKey:["portal-stages",h],queryFn:async()=>{const{data:he,error:ue}=await q.from("deal_pipeline_stages").select("*").eq("owner_user_id",h).order("sort_order",{ascending:!0});if(ue)throw ue;return he},enabled:!!h}),{data:f}=tt({queryKey:["portal-agent",h],queryFn:async()=>{const{data:he,error:ue}=await q.from("profiles").select("id, name, avatar_url, phone, email").eq("id",h).single();if(ue)throw ue;return he},enabled:!!h}),{data:g}=U9s(h),x=r==="linked"&&u?u:l,y=x==null?void 0:x.id,v=$9s(g,x==null?void 0:x.branding_override),b=v.portal_theme==="azure"?"azure":"noir";j.useEffect(()=>{const he=`portal-theme-${b}`;return document.body.classList.add(he),()=>document.body.classList.remove(he)},[b]);const{data:w}=tt({queryKey:["portal-updates-public",y],queryFn:async()=>{const{data:he,error:ue}=await q.from("portal_updates").select("*").eq("portal_id",y).order("created_at",{ascending:!1});if(ue)throw ue;return he},enabled:!!y}),S=(ne=x==null?void 0:x.deal_pipeline)==null?void 0:ne.id,{data:C}=tt({queryKey:["portal-documents",S],queryFn:async()=>{const{data:he,error:ue}=await q.from("deal_files").select("*").eq("deal_id",S).eq("visible_on_portal",!0).order("created_at",{ascending:!1});if(ue)throw ue;return he},enabled:!!S}),E=l==null?void 0:l.id,I=E?`portal_onboarded_${E}_${i}`:null,P=I?localStorage.getItem(I)==="1":!1,{data:R,isLoading:D}=tt({queryKey:["portal-onboarding-check",E,i],queryFn:async()=>{const{data:he,error:ue}=await q.from("portal_onboarding_submissions").select("id").eq("portal_id",E).eq("device_fingerprint",i).maybeSingle();if(ue)throw ue;return he&&I&&localStorage.setItem(I,"1"),he},enabled:!!E&&!!(l!=null&&l.require_onboarding)&&!P,staleTime:5*60*1e3}),O=!!(l!=null&&l.require_onboarding)&&!P&&!R&&!t,{data:U}=tt({queryKey:["portal-custom-questions-public",h],queryFn:async()=>{const{data:he,error:ue}=await q.from("portal_custom_questions").select("*").eq("owner_user_id",h).eq("is_active",!0).order("sort_order",{ascending:!0});if(ue)throw ue;return he},enabled:!!h&&O}),W=P||!!R||t||!(l!=null&&l.require_onboarding);if(o||l!=null&&l.require_onboarding&&!P&&D)return e.jsx("div",{className:"min-h-screen flex items-center justify-center",style:{background:"hsl(var(--portal-bg))"},children:e.jsx(kt,{className:"w-6 h-6 animate-spin",style:{color:"hsl(var(--portal-gold))"}})});if(c||!l)return e.jsx("div",{className:"min-h-screen flex items-center justify-center p-6",style:{background:"var(--portal-gradient-noir)"},children:e.jsxs("div",{className:"text-center max-w-md",children:[e.jsx("div",{className:"w-16 h-16 rounded-full flex items-center justify-center mx-auto mb-6",style:{background:"hsl(var(--portal-surface-2))",border:"1px solid hsl(var(--portal-gold) / 0.3)"},children:e.jsx(Mf,{className:"w-6 h-6",style:{color:"hsl(var(--portal-gold))"}})}),e.jsx("h1",{className:"portal-serif text-4xl mb-3",style:{color:"hsl(var(--portal-ink))"},children:"Portal Not Available"}),e.jsx("div",{className:"portal-hairline mx-auto w-24 mb-4"}),e.jsx("p",{className:"text-sm",style:{color:"hsl(var(--portal-ink-muted))"},children:"This portal is no longer active or doesn't exist."})]})});if(!W){const he=l==null?void 0:l.deal_pipeline;return e.jsx("div",{className:"min-h-screen bg-gradient-to-b from-slate-50 to-slate-100",children:e.jsx(B9s,{portal:l,dealData:he,agentProfile:f,customQuestions:U||[],deviceFingerprint:i,onComplete:()=>{I&&localStorage.setItem(I,"1"),n(!0)}})})}const V=(te=l==null?void 0:l.deal_pipeline)==null?void 0:te.deal_type,G=(J=u==null?void 0:u.deal_pipeline)==null?void 0:J.deal_type,Y=!!u,X=he=>he==="listing"?"Your Sale":he==="buy-side"?"Your Purchase":"Transaction",ae=he=>he==="listing"?e.jsx(va,{className:"w-3.5 h-3.5"}):e.jsx(S_,{className:"w-3.5 h-3.5"});return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"hidden lg:block",children:e.jsx(O9s,{portal:l,linkedPortal:u,activePortal:x,activeTab:r,onTabChange:a,agentProfile:f,branding:v,updates:w,documents:C})}),e.jsxs("div",{className:"lg:hidden min-h-screen pb-16",style:{background:"var(--portal-gradient-noir)"},children:[e.jsx(j9s,{dealData:x==null?void 0:x.deal_pipeline,agentProfile:f,welcomeMessage:(x==null?void 0:x.welcome_message)||v.welcome_message,isWon:(_e=(ce=x==null?void 0:x.deal_pipeline)==null?void 0:ce.deal_pipeline_stages)==null?void 0:_e.is_won_stage,branding:v}),e.jsxs("div",{className:"max-w-lg mx-auto px-4 space-y-5 mt-8",children:[Y&&e.jsx("div",{className:"flex gap-1 rounded-xl p-1",style:{background:"hsl(var(--portal-surface-2))",border:"1px solid hsl(var(--portal-gold) / 0.15)"},children:["primary","linked"].map(he=>{const ue=r===he,ve=he==="primary"?V:G;return e.jsxs("button",{onClick:()=>a(he),className:"flex-1 flex items-center justify-center gap-1.5 rounded-lg py-2.5 text-sm font-medium transition-all portal-serif",style:{background:ue?"hsl(var(--portal-surface-3))":"transparent",color:ue?"hsl(var(--portal-gold))":"hsl(var(--portal-ink-muted))",boxShadow:ue?"0 1px 0 hsl(var(--portal-gold) / 0.3) inset":"none"},children:[ae(ve),e.jsx("span",{style:{fontSize:"1rem"},children:X(ve)})]},he)})}),e.jsx(G9s,{portal:x,updates:w,documents:C,agentProfile:f}),y&&e.jsx("div",{className:"rounded-2xl p-5",style:{background:"hsl(var(--portal-surface))",border:"1px solid hsl(var(--portal-gold) / 0.14)"},children:e.jsx(i$t,{portalId:y,clientName:x==null?void 0:x.client_name,agentName:f==null?void 0:f.name,agentAvatar:f==null?void 0:f.avatar_url,deviceFingerprint:i})}),e.jsxs("div",{className:"text-center pt-8 pb-2 space-y-3",children:[e.jsx("div",{className:"portal-hairline w-16 mx-auto"}),e.jsxs("div",{className:"flex items-center justify-center gap-1.5",style:{color:"hsl(var(--portal-ink-dim))"},children:[e.jsx(Mf,{className:"w-3 h-3"}),e.jsx("span",{className:"text-[10px] tracking-[0.2em] uppercase",children:"Secure Client Portal"})]}),f&&e.jsxs("p",{className:"text-xs",style:{color:"hsl(var(--portal-ink-muted))"},children:["Curated by ",e.jsx("span",{className:"portal-serif",style:{color:"hsl(var(--portal-gold))",fontSize:"0.95rem"},children:f.name})]})]})]})]})]})}function G9s({portal:s,updates:t,documents:n,agentProfile:r}){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 u=n6e(c);d&&d.length>0&&(u=d.map((x,y)=>{var v,b;return{key:`custom-${y}`,label:x.label||((v=u[y])==null?void 0:v.label)||`Stage ${y+1}`,description:x.description||((b=u[y])==null?void 0:b.description)||"",video_url:x.video_url||void 0}}));const h=d&&d.length>0?Math.min(HEe(l==null?void 0:l.name),u.length-1):HEe(l==null?void 0:l.name),m=u[h],f=m==null?void 0:m.video_url,g=o&&s.show_post_close_tips!==!1&&s.referral_enabled!==!1;return e.jsxs(e.Fragment,{children:[g&&e.jsx(s$t,{portalId:s.id,portalSlug:s.slug,ownerUserId:s.owner_user_id,rewardText:s.referral_reward_text,ctaHeadline:s.referral_cta_headline,agentName:r==null?void 0:r.name,clientName:s.client_name,reviewUrl:s.review_url,hubVideoUrl:s.homeowner_hub_video_url}),e.jsx(H9t,{targetCloseDate:i==null?void 0:i.target_close_date,actualCloseDate:i==null?void 0:i.actual_close_date,clientName:s.client_name}),e.jsx(G9t,{journeyStages:u,currentIndex:h}),m&&e.jsx(W9t,{currentStage:m,nextStepText:s.next_step_text,nextStepVideoUrl:f||s.next_step_video_url}),e.jsx(K9t,{deal:i,portal:s}),(s==null?void 0:s.slug)&&e.jsx(Z9t,{slug:s.slug}),n&&n.length>0&&e.jsx(Y9t,{documents:n}),(s==null?void 0:s.id)&&(s==null?void 0:s.owner_user_id)&&e.jsx(t$t,{portalId:s.id,ownerUserId:s.owner_user_id,currentStage:l==null?void 0:l.name}),t&&t.length>0&&e.jsx(X9t,{updates:t})]})}function u$t({slug:s}){const t=Wi(),n=s||t.slug,[r,a]=j.useState(!1),[i,l]=j.useState(!1),[o,c]=j.useState(""),[d,u]=j.useState(""),[h,m]=j.useState(""),[f,g]=j.useState(""),[x,y]=j.useState(""),[v,b]=j.useState("buying"),[w,S]=j.useState("");j.useEffect(()=>(document.body.classList.add("client-portal-page"),()=>document.body.classList.remove("client-portal-page")),[]);const{data:C,isLoading:E,error:I}=tt({queryKey:["portal-referral-target",n],queryFn:async()=>{if(!n)return null;const{data:D,error:O}=await q.from("client_portals").select(` id, slug, owner_user_id, client_name, referral_enabled, referral_reward_text, referral_cta_headline, is_enabled `).eq("slug",n).eq("is_enabled",!0).maybeSingle();if(O)throw O;return D},enabled:!!n}),{data:P}=tt({queryKey:["portal-referral-agent",C==null?void 0:C.owner_user_id],queryFn:async()=>{const{data:D}=await q.from("profiles").select("id, name, avatar_url").eq("id",C.owner_user_id).single();return D},enabled:!!(C!=null&&C.owner_user_id)}),R=async D=>{if(D.preventDefault(),!C||!h.trim()){re.error("Please enter your friend's name");return}if(!f.trim()&&!x.trim()){re.error("Please add at least an email or phone for your friend");return}a(!0);try{const{error:O}=await q.from("portal_referrals").insert({portal_id:C.id,owner_user_id:C.owner_user_id,referrer_name:o.trim()||C.client_name||null,referrer_email:d.trim()||null,friend_name:h.trim(),friend_email:f.trim()||null,friend_phone:x.trim()||null,friend_interest:v,friend_message:w.trim()||null});if(O)throw O;l(!0)}catch(O){re.error(O.message||"Could not submit referral")}finally{a(!1)}};return E?e.jsx("div",{className:"min-h-screen bg-gradient-to-b from-slate-50 to-white flex items-center justify-center",children:e.jsx(yn,{className:"h-96 w-full max-w-lg rounded-2xl mx-4"})}):I||!C||!C.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(la,{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 ",(P==null?void 0:P.name)||"your agent",". They'll reach out to"," ",e.jsx("span",{className:"font-semibold text-slate-800",children:h})," 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(qa,{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:[P!=null&&P.avatar_url?e.jsx("img",{src:P.avatar_url,alt:P.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(ul,{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(ul,{className:"w-3 h-3"})," Referral"]}),e.jsx("h1",{className:"text-2xl font-bold tracking-tight mb-1 font-serif",children:C.referral_cta_headline||"Refer a Friend"}),e.jsxs("p",{className:"text-sm text-white/70",children:["Send ",(P==null?void 0:P.name)||"your agent"," someone you trust."]}),C.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:C.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:R,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(ee,{htmlFor:"friend_name",className:"text-sm",children:["Their name ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx(pe,{id:"friend_name",value:h,onChange:D=>m(D.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(ee,{htmlFor:"friend_email",className:"text-sm",children:"Email"}),e.jsx(pe,{id:"friend_email",type:"email",value:f,onChange:D=>g(D.target.value),placeholder:"jane@email.com",className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"friend_phone",className:"text-sm",children:"Phone"}),e.jsx(pe,{id:"friend_phone",type:"tel",value:x,onChange:D=>y(D.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(ee,{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(D=>e.jsx("button",{type:"button",onClick:()=>b(D.v),className:`rounded-lg border px-3 py-2 text-sm font-medium transition-colors ${v===D.v?"bg-[#406E71] text-white border-[#406E71]":"bg-white text-slate-600 border-slate-200 hover:border-slate-300"}`,children:D.l},D.v))})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"friend_message",className:"text-sm",children:"A note (optional)"}),e.jsx("textarea",{id:"friend_message",value:w,onChange:D=>S(D.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(ee,{htmlFor:"referrer_name",className:"text-sm",children:"Your name"}),e.jsx(pe,{id:"referrer_name",value:o,onChange:D=>c(D.target.value),placeholder:C.client_name||"Your name",className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"referrer_email",className:"text-sm",children:"Your email"}),e.jsx(pe,{id:"referrer_email",type:"email",value:d,onChange:D=>u(D.target.value),placeholder:"So we can thank you!",className:"mt-1"})]})]})]}),e.jsxs("button",{type:"submit",disabled:r,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:[r?e.jsx(kt,{className:"w-4 h-4 animate-spin"}):e.jsx(ul,{className:"w-4 h-4"}),r?"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 W9s(){const t=fu().pathname.slice(1).replace(/\/$/,"");if(j.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 n=t.match(/^([^/]+)\/refer$/);return n?e.jsx(u$t,{slug:n[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(d$t,{slug:t})}function K9s(s){const t=[],n=r=>{r&&!t.includes(r)&&t.push(r)};for(const r of s.filter(Boolean)){n(r);try{const a=new URL(r),i=a.searchParams.get("u");i&&/\/functions\/v1\/trestle-media/i.test(a.pathname)&&n(i)}catch{}}return t}function GEe({photos:s,alt:t="",className:n="w-full h-full",imgClassName:r="w-full h-full object-cover",iconClassName:a="w-8 h-8"}){const i=j.useMemo(()=>K9s(Array.isArray(s)?s:[]),[s]),[l,o]=j.useState(0);return j.useEffect(()=>{o(0)},[i.join("|")]),!i.length||l>=i.length?e.jsx("div",{className:`${n} bg-muted flex items-center justify-center text-muted-foreground`,children:e.jsx(va,{className:`${a} opacity-40`})}):e.jsx("div",{className:`${n} overflow-hidden bg-muted`,children:e.jsx("img",{src:i[l],alt:t,className:r,onError:()=>o(c=>c+1)})})}function h$t({comp:s,open:t,onClose:n}){var d;const[r,a]=j.useState(0);if(!s)return null;const i=Array.isArray(s.photos)?s.photos.filter(Boolean):[],l=s.soldPrice||s.price,o=s.sqft&&l?Math.round(l/s.sqft):null,c=u=>{if(!u)return null;const[h,m,f]=u.split(/[-/T]/);return h?`${m}/${f}/${h}`:null};return e.jsx(zs,{open:t,onOpenChange:u=>{u||n()},children:e.jsxs(Os,{className:"max-w-4xl max-h-[90vh] overflow-y-auto p-0",children:[e.jsxs(Us,{className:"px-6 pt-6 pb-2",children:[e.jsx(Bs,{className:"text-xl",children:s.address}),e.jsxs("div",{className:"text-sm text-muted-foreground flex items-center gap-1",children:[e.jsx(ci,{className:"w-3.5 h-3.5"}),s.city,", ",s.state," ",s.zip]})]}),i.length>0?e.jsxs("div",{className:"px-6",children:[e.jsx(GEe,{photos:i.slice(r),className:"rounded-lg aspect-[16/10]"}),i.length>1&&e.jsx("div",{className:"flex gap-2 mt-2 overflow-x-auto pb-2",children:i.slice(0,24).map((u,h)=>e.jsx("button",{onClick:()=>a(h),className:`flex-none w-20 h-16 rounded overflow-hidden border-2 transition ${h===r?"border-primary":"border-transparent opacity-70 hover:opacity-100"}`,children:e.jsx(GEe,{photos:[u],iconClassName:"w-5 h-5"})},h))})]}):e.jsx("div",{className:"px-6",children:e.jsx("div",{className:"rounded-lg bg-muted aspect-[16/10] flex items-center justify-center text-muted-foreground",children:e.jsx(va,{className:"w-12 h-12 opacity-40"})})}),e.jsxs("div",{className:"px-6 pt-4 flex items-center justify-between flex-wrap gap-2",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"text-3xl font-bold flex items-center gap-1",children:[e.jsx(ru,{className:"w-6 h-6 text-muted-foreground"}),(l||0).toLocaleString()]}),o&&e.jsxs("div",{className:"text-xs text-muted-foreground",children:["$",o,"/sqft"]})]}),e.jsxs("div",{className:"flex flex-col items-end gap-1",children:[e.jsx(Be,{variant:"outline",children:s.status}),s.daysOnMarket!=null&&e.jsxs("span",{className:"text-xs text-muted-foreground",children:[s.daysOnMarket," DOM"]})]})]}),(s.listDate||s.statusChangeDate||s.soldDate)&&e.jsxs("div",{className:"px-6 pt-4",children:[e.jsx("div",{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground mb-2",children:"Timeline"}),e.jsxs("div",{className:"grid grid-cols-3 gap-2",children:[e.jsx(F7e,{label:"Active",date:c(s.listDate),active:!0}),e.jsx(F7e,{label:"Pending",date:/Pending|Contingent|Under Contract|Backup/i.test(String(s.status||""))?c(s.statusChangeDate):null,active:/Pending|Contingent|Under Contract|Backup/i.test(String(s.status||""))}),e.jsx(F7e,{label:"Closed",date:c(s.soldDate)||(/Closed|Sold/i.test(String(s.status||""))?c(s.statusChangeDate):null),active:/Closed|Sold/i.test(String(s.status||""))})]})]}),e.jsxs("div",{className:"px-6 pt-4 grid grid-cols-2 md:grid-cols-4 gap-3",children:[e.jsx(Gce,{icon:e.jsx(l2,{className:"w-4 h-4"}),label:"Beds",value:s.bedrooms??"—"}),e.jsx(Gce,{icon:e.jsx(T0,{className:"w-4 h-4"}),label:"Baths",value:s.bathrooms??"—"}),e.jsx(Gce,{icon:e.jsx(R4,{className:"w-4 h-4"}),label:"SqFt",value:((d=s.sqft)==null?void 0:d.toLocaleString())??"—"}),e.jsx(Gce,{icon:e.jsx(Ta,{className:"w-4 h-4"}),label:"Year Built",value:s.yearBuilt??"—"})]}),e.jsxs("div",{className:"px-6 pt-4 grid sm:grid-cols-2 gap-x-6 gap-y-2 text-sm",children:[e.jsx(J1,{label:"MLS #",value:s.mlsNumber}),e.jsx(J1,{label:"Property Type",value:s.propertySubType||s.propertyType}),e.jsx(J1,{label:"Lot Size",value:s.lotSize}),e.jsx(J1,{label:"Garage",value:s.garageSpaces}),e.jsx(J1,{label:"Stories",value:s.stories}),e.jsx(J1,{label:"HOA",value:s.hoaFee?`$${s.hoaFee}/${(s.hoaFrequency||"mo").toLowerCase()}`:null}),e.jsx(J1,{label:"Tax (annual)",value:s.taxAmount?`$${s.taxAmount.toLocaleString()}`:null}),e.jsx(J1,{label:"Heating",value:s.heating}),e.jsx(J1,{label:"Cooling",value:s.cooling}),e.jsx(J1,{label:"Parking",value:s.parking}),e.jsx(J1,{label:"Elementary",value:s.elementarySchool}),e.jsx(J1,{label:"Middle",value:s.middleSchool}),e.jsx(J1,{label:"High",value:s.highSchool}),e.jsx(J1,{label:"Listed By",value:s.listAgentFullName}),e.jsx(J1,{label:"Office",value:s.listOfficeName})]}),s.description&&e.jsxs("div",{className:"px-6 pt-4",children:[e.jsx("div",{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground mb-1",children:"Description"}),e.jsx("p",{className:"text-sm leading-relaxed whitespace-pre-wrap",children:s.description})]}),e.jsx("div",{className:"px-6 py-4"})]})})}function Gce({icon:s,label:t,value:n}){return e.jsxs("div",{className:"rounded-lg border bg-card p-3",children:[e.jsxs("div",{className:"flex items-center gap-1.5 text-xs text-muted-foreground",children:[s,t]}),e.jsx("div",{className:"text-lg font-semibold mt-0.5",children:n})]})}function J1({label:s,value:t}){return t==null||t===""||t===0?null:e.jsxs("div",{className:"flex justify-between border-b border-dashed py-1",children:[e.jsx("span",{className:"text-muted-foreground",children:s}),e.jsx("span",{className:"font-medium text-right ml-3 truncate",children:String(t)})]})}function F7e({label:s,date:t,active:n}){return e.jsxs("div",{className:`rounded-lg border p-2 text-center ${n?"bg-primary/5 border-primary/30":"bg-muted/30"}`,children:[e.jsx("div",{className:"text-[10px] uppercase tracking-wide text-muted-foreground",children:s}),e.jsx("div",{className:`text-sm font-medium mt-0.5 ${t?"":"text-muted-foreground/60"}`,children:t||"—"})]})}function Wce({to:s,durationMs:t=1400,prefix:n="",suffix:r="",className:a,delayMs:i=0}){const[l,o]=j.useState(0),c=j.useRef(null);return j.useEffect(()=>{if(!Number.isFinite(s))return;let d=0;const u=0,h=f=>1-Math.pow(1-f,3),m=setTimeout(()=>{const f=g=>{d||(d=g);const x=g-d,y=Math.min(1,x/t);o(Math.round(u+(s-u)*h(y))),y<1&&(c.current=requestAnimationFrame(f))};c.current=requestAnimationFrame(f)},i);return()=>{clearTimeout(m),c.current&&cancelAnimationFrame(c.current)}},[s,t,i]),e.jsxs("span",{className:a,children:[n,l.toLocaleString(),r]})}function Y9s({low:s,likely:t,high:n,defaultMortgage:r=0,defaultCommissionPct:a=6,defaultClosingPct:i=1}){const[l,o]=j.useState(t),[c,d]=j.useState(r),[u,h]=j.useState(a),[m,f]=j.useState(i),{commission:g,closing:x,net:y}=j.useMemo(()=>{const w=Math.round(l*u/100),S=Math.round(l*m/100);return{commission:w,closing:S,net:Math.max(0,l-w-S-(c||0))}},[l,u,m,c]),v=w=>`$${w.toLocaleString()}`,b=n>s?(l-s)/(n-s)*100:50;return e.jsxs(Ne,{className:"overflow-hidden border-primary/20",children:[e.jsxs("div",{className:"bg-gradient-to-br from-primary/5 to-primary/10 px-6 pt-6 pb-4 border-b border-primary/10",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx(Yl,{className:"w-4 h-4 text-primary"}),e.jsx("span",{className:"text-xs uppercase tracking-widest font-semibold text-primary",children:"Your Price Story"})]}),e.jsx("h2",{className:"text-2xl md:text-3xl font-bold",children:"What if you priced it at…"}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:"Drag the price. Watch your estimated walk-away update in real-time."})]}),e.jsxs(Ie,{className:"p-6 space-y-6",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-end justify-between mb-3",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:"List price"}),e.jsx("span",{className:"text-3xl font-bold tabular-nums",children:v(l)})]}),e.jsxs("div",{className:"relative",children:[e.jsx(kx,{value:[l],min:s,max:n,step:1e3,onValueChange:([w])=>o(w)}),e.jsxs("div",{className:"flex justify-between text-[10px] text-muted-foreground mt-2",children:[e.jsx("span",{children:v(s)}),e.jsxs("span",{children:["Suggested ",v(t)]}),e.jsx("span",{children:v(n)})]})]}),e.jsx("div",{className:"mt-2 h-1.5 rounded-full bg-muted overflow-hidden",children:e.jsx("div",{className:"h-full bg-gradient-to-r from-emerald-500 via-primary to-amber-500 transition-all",style:{width:`${Math.min(100,Math.max(0,b))}%`}})})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-3 gap-3",children:[e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs",children:"Mortgage payoff"}),e.jsx(pe,{type:"number",inputMode:"numeric",value:c||"",placeholder:"$0",onChange:w=>d(Number(w.target.value)||0)})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs",children:"Commission %"}),e.jsx(pe,{type:"number",step:"0.25",value:u,onChange:w=>h(Number(w.target.value)||0)})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs",children:"Closing costs %"}),e.jsx(pe,{type:"number",step:"0.25",value:m,onChange:w=>f(Number(w.target.value)||0)})]})]}),e.jsxs("div",{className:"rounded-xl border bg-card overflow-hidden",children:[e.jsxs("div",{className:"px-5 py-4 grid grid-cols-2 gap-y-2 text-sm",children:[e.jsx("span",{className:"text-muted-foreground",children:"Sale price"}),e.jsx("span",{className:"text-right tabular-nums font-medium",children:v(l)}),e.jsxs("span",{className:"text-muted-foreground",children:["Commission (",u,"%)"]}),e.jsxs("span",{className:"text-right tabular-nums text-rose-600",children:["−",v(g)]}),e.jsxs("span",{className:"text-muted-foreground",children:["Closing (",m,"%)"]}),e.jsxs("span",{className:"text-right tabular-nums text-rose-600",children:["−",v(x)]}),c>0&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"text-muted-foreground",children:"Mortgage payoff"}),e.jsxs("span",{className:"text-right tabular-nums text-rose-600",children:["−",v(c)]})]})]}),e.jsxs("div",{className:"bg-gradient-to-r from-emerald-500/10 to-primary/10 px-5 py-4 border-t flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(l7,{className:"w-5 h-5 text-emerald-600"}),e.jsx("span",{className:"font-semibold",children:"Your estimated walk-away"})]}),e.jsx("span",{className:"text-2xl font-bold tabular-nums text-emerald-700",children:v(y)})]})]}),e.jsx("p",{className:"text-[11px] text-muted-foreground leading-relaxed",children:"This is a rough estimate to help you think through pricing. Actual proceeds depend on title fees, prorations, repairs, and other items your agent will walk through in detail."})]})]})}function m$t({tokenOverride:s}={}){var Le,Fe,ke,Ve,je,Ae,Ce,qe,ze,$e,ct,Xe;const t=Wi(),n=s??t.token,[r,a]=j.useState(null),[i,l]=j.useState(null),[o,c]=j.useState([]),[d,u]=j.useState(!0),[h,m]=j.useState(""),[f,g]=j.useState(""),[x,y]=j.useState(""),[v,b]=j.useState(!1),[w,S]=j.useState(!1),[C,E]=j.useState(null),[I,P]=j.useState(null),[R,D]=j.useState(!1),{toast:O}=Bi();j.useEffect(()=>{n&&(async()=>{const{data:it}=await q.from("cmas").select("*").eq("share_token",n).eq("status","shared").maybeSingle();if(!it){u(!1);return}a(it);const[{data:at},{data:Ke}]=await Promise.all([q.from("cma_comps").select("*").eq("cma_id",it.id).order("position"),q.from("profiles").select("id,name,email,phone,avatar_url,brokerage_name,website_url,title,bio").eq("id",it.agent_id).maybeSingle()]);c((at||[]).filter(xt=>xt.selected)),l(Ke);const nt=localStorage.getItem("cma_visitor_token")||crypto.randomUUID();localStorage.setItem("cma_visitor_token",nt),await q.from("cma_views").insert({cma_id:it.id,visitor_token:nt,user_agent:navigator.userAgent}),u(!1)})()},[n]);const U=async it=>{if(!r)return;const at=localStorage.getItem("cma_visitor_token")||"";await q.from("cma_views").insert({cma_id:r.id,visitor_token:at,reactions:{[it]:!0}}),q.functions.invoke("cma-reply-notify",{body:{shareToken:n,reaction:it,visitorToken:at}}).catch(()=>{}),O({title:"Thanks — your agent just got notified ✨"})},W=!(r!=null&&r.contact_id),V=async()=>{if(!r||!h.trim())return;if(W&&(!f.trim()||!x.trim())){O({title:"Please add your name and email",variant:"destructive"});return}b(!0);const it=localStorage.getItem("cma_visitor_token")||"",{data:at,error:Ke}=await q.functions.invoke("cma-reply-notify",{body:{shareToken:n,message:h,visitorToken:it,viewerName:f.trim()||void 0,viewerEmail:x.trim()||void 0}});if(b(!1),Ke||!(at!=null&&at.success)){O({title:"Could not send",description:(Ke==null?void 0:Ke.message)||(at==null?void 0:at.error),variant:"destructive"});return}m(""),S(!0),O({title:"Message sent to your agent"})},G=j.useMemo(()=>{const it=o.map(at=>{const Ke=at.snapshot,nt=(Ke==null?void 0:Ke.soldPrice)||(Ke==null?void 0:Ke.price);return nt&&(Ke!=null&&Ke.sqft)?nt/Ke.sqft:null}).filter(at=>!!at).sort((at,Ke)=>at-Ke);return it.length?Math.round(it[Math.floor(it.length/2)]):null},[o]);if(d)return e.jsx("div",{className:"min-h-screen flex items-center justify-center",children:e.jsx(kt,{className:"w-8 h-8 animate-spin"})});if(!r)return e.jsx("div",{className:"min-h-screen flex items-center justify-center text-center p-6",children:e.jsxs("div",{children:[e.jsx(va,{className:"w-12 h-12 mx-auto text-muted-foreground mb-4"}),e.jsx("h1",{className:"text-xl font-semibold",children:"CMA not found"}),e.jsx("p",{className:"text-muted-foreground",children:"This report may have been removed or unpublished."})]})});const Y=r.subject||{},X=(Le=r.settings)==null?void 0:Le.personalVideo,ae=(Fe=Y.photos)==null?void 0:Fe[0],ie=r.contact_first_name?r.contact_first_name:null,ne=((i==null?void 0:i.name)||"A").split(" ").map(it=>it[0]).slice(0,2).join("").toUpperCase(),te=i!=null&&i.phone?`tel:${String(i.phone).replace(/[^\d+]/g,"")}`:null,J=i!=null&&i.email?`mailto:${i.email}`:null,ce=i!=null&&i.phone?`sms:${String(i.phone).replace(/[^\d+]/g,"")}`:null,_e=r.price_low??null,he=r.price_likely??null,ue=r.price_high??null,ve=_e&&he&&ue,Ee=he&&Y.sqft?Math.round(he/Y.sqft):null,Se=Ee&&G?Math.round((Ee-G)/G*100):null;return e.jsxs("div",{className:"min-h-screen bg-background pb-28 md:pb-0",children:[i&&e.jsx("div",{className:"border-b bg-card sticky top-0 z-40 backdrop-blur supports-[backdrop-filter]:bg-card/80",children:e.jsxs("div",{className:"container mx-auto max-w-6xl px-4 md:px-6 py-3 flex items-center gap-3",children:[i.avatar_url?e.jsx("img",{src:i.avatar_url,alt:i.name,className:"w-10 h-10 rounded-full object-cover ring-2 ring-primary/20"}):e.jsx("div",{className:"w-10 h-10 rounded-full bg-primary/10 flex items-center justify-center font-semibold text-primary text-sm",children:ne}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"font-semibold leading-tight truncate text-sm",children:i.name}),(i.title||i.brokerage_name)&&e.jsxs("div",{className:"text-[11px] text-muted-foreground flex items-center gap-1 truncate",children:[i.brokerage_name&&e.jsx(ji,{className:"w-3 h-3 shrink-0"}),e.jsx("span",{className:"truncate",children:[i.title,i.brokerage_name].filter(Boolean).join(" · ")})]})]}),e.jsxs("div",{className:"hidden md:flex items-center gap-2",children:[te&&e.jsx($,{variant:"outline",size:"sm",asChild:!0,children:e.jsxs("a",{href:te,children:[e.jsx(Da,{className:"w-4 h-4 mr-1"}),"Call"]})}),J&&e.jsx($,{variant:"outline",size:"sm",asChild:!0,children:e.jsxs("a",{href:J,children:[e.jsx(mn,{className:"w-4 h-4 mr-1"}),"Email"]})})]})]})}),e.jsxs("div",{className:"relative overflow-hidden",children:[ae?e.jsxs("div",{className:"absolute inset-0",children:[e.jsx("img",{src:ae,alt:Y.address,className:"w-full h-full object-cover scale-110 animate-[kenburns_18s_ease-out_infinite_alternate]",style:{animation:"kenburns 22s ease-in-out infinite alternate"}}),e.jsx("div",{className:"absolute inset-0 bg-gradient-to-br from-slate-950/85 via-slate-900/75 to-primary/60"}),e.jsx("div",{className:"absolute inset-0 bg-gradient-to-t from-background via-background/20 to-transparent"})]}):e.jsx("div",{className:"absolute inset-0 bg-gradient-to-br from-primary/30 via-primary/10 to-background"}),e.jsx("style",{children:` @keyframes kenburns { 0% { transform: scale(1.08) translate(0, 0); } 100% { transform: scale(1.18) translate(-1.5%, -1%); } } `}),e.jsx("div",{className:"relative container mx-auto max-w-6xl px-4 md:px-8 pt-12 md:pt-20 pb-16 md:pb-24",children:e.jsxs("div",{className:"grid md:grid-cols-5 gap-8 items-center",children:[e.jsxs("div",{className:`${X!=null&&X.url?"md:col-span-3":"md:col-span-5"} text-white animate-fade-in`,children:[e.jsxs(Be,{className:"mb-4 bg-white/15 text-white border-white/20 backdrop-blur-sm hover:bg-white/20",children:[e.jsx(Nn,{className:"w-3 h-3 mr-1"}),ie?`Prepared for ${ie}`:r.buyer_mode?"Your Buyer Analysis":"Your Market Analysis"]}),e.jsx("h1",{className:"text-3xl md:text-5xl lg:text-6xl font-bold leading-[1.05] tracking-tight",children:Y.address}),e.jsxs("p",{className:"text-white/70 mt-2 text-base md:text-lg flex items-center gap-2",children:[e.jsx(ci,{className:"w-4 h-4"}),Y.city,", ",Y.state," ",Y.zip]}),ve&&e.jsxs("div",{className:"mt-8 md:mt-10",children:[e.jsx("p",{className:"text-xs uppercase tracking-[0.2em] text-white/60 mb-2",children:"Estimated Value"}),e.jsx("div",{className:"flex items-baseline gap-4 flex-wrap",children:e.jsx("div",{className:"text-5xl md:text-7xl font-bold tabular-nums",children:e.jsx(Wce,{to:he,prefix:"$",durationMs:1600,delayMs:250})})}),e.jsxs("div",{className:"mt-4 flex items-center gap-3 md:gap-6 text-sm text-white/80",children:[e.jsxs("div",{children:[e.jsx("span",{className:"block text-[11px] uppercase tracking-wider text-white/50",children:"Low"}),e.jsx("span",{className:"tabular-nums font-medium",children:e.jsx(Wce,{to:_e,prefix:"$",delayMs:500})})]}),e.jsx("div",{className:"h-8 w-px bg-white/20"}),e.jsxs("div",{children:[e.jsx("span",{className:"block text-[11px] uppercase tracking-wider text-white/50",children:"Likely"}),e.jsx("span",{className:"tabular-nums font-medium",children:e.jsx(Wce,{to:he,prefix:"$",delayMs:650})})]}),e.jsx("div",{className:"h-8 w-px bg-white/20"}),e.jsxs("div",{children:[e.jsx("span",{className:"block text-[11px] uppercase tracking-wider text-white/50",children:"High"}),e.jsx("span",{className:"tabular-nums font-medium",children:e.jsx(Wce,{to:ue,prefix:"$",delayMs:800})})]})]})]})]}),(X==null?void 0:X.url)&&e.jsx("div",{className:"md:col-span-2 animate-scale-in",children:e.jsxs("button",{onClick:()=>D(!0),className:"group relative w-full aspect-[4/5] md:aspect-[4/5] rounded-2xl overflow-hidden shadow-2xl ring-1 ring-white/20 bg-black",children:[X.thumb?e.jsx("img",{src:X.thumb,alt:"",className:"w-full h-full object-cover"}):e.jsx("video",{src:X.url,className:"w-full h-full object-cover",muted:!0,playsInline:!0,preload:"metadata"}),e.jsx("div",{className:"absolute inset-0 bg-gradient-to-t from-black/60 to-black/10 group-hover:from-black/40 transition-colors"}),e.jsxs("div",{className:"absolute inset-0 flex flex-col items-center justify-center text-white",children:[e.jsx("div",{className:"w-16 h-16 md:w-20 md:h-20 rounded-full bg-white/95 text-primary flex items-center justify-center shadow-2xl group-hover:scale-110 transition-transform",children:e.jsx(Bu,{className:"w-7 h-7 md:w-8 md:h-8 ml-1",fill:"currentColor"})}),e.jsxs("p",{className:"mt-4 text-sm font-medium tracking-wide",children:["A message from ",((ke=i==null?void 0:i.name)==null?void 0:ke.split(" ")[0])||"your agent"]})]})]})})]})})]}),R&&(X==null?void 0:X.url)&&e.jsx("div",{className:"fixed inset-0 z-50 bg-black/90 flex items-center justify-center p-4 animate-fade-in",onClick:()=>D(!1),children:e.jsxs("div",{className:"relative w-full max-w-4xl",onClick:it=>it.stopPropagation(),children:[e.jsx("video",{src:X.url,controls:!0,autoPlay:!0,className:"w-full rounded-xl"}),e.jsx($,{variant:"ghost",className:"absolute -top-12 right-0 text-white hover:bg-white/10",onClick:()=>D(!1),children:"Close"})]})}),e.jsxs("div",{className:"container mx-auto max-w-6xl px-4 md:px-8 py-10 md:py-16 space-y-10 md:space-y-14",children:[e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-3 md:gap-4 -mt-20 md:-mt-24 relative z-10",children:[{label:"Beds",value:Y.bedrooms??"—"},{label:"Baths",value:Y.bathrooms??"—"},{label:"Sq Ft",value:((Ve=Y.sqft)==null?void 0:Ve.toLocaleString())??"—"},{label:"Year Built",value:Y.yearBuilt??"—"}].map((it,at)=>e.jsx(Ne,{className:"shadow-lg animate-fade-in",style:{animationDelay:`${at*80}ms`},children:e.jsxs(Ie,{className:"p-4 md:p-6 text-center",children:[e.jsx("div",{className:"text-2xl md:text-3xl font-bold",children:it.value}),e.jsx("div",{className:"text-xs text-muted-foreground mt-1 uppercase tracking-wider",children:it.label})]})},at))}),((Ae=(je=r.settings)==null?void 0:je.priceOverride)==null?void 0:Ae.enabled)&&((qe=(Ce=r.settings)==null?void 0:Ce.priceOverride)==null?void 0:qe.note)&&e.jsx(Ne,{className:"border-primary/30 bg-gradient-to-br from-primary/5 to-transparent",children:e.jsxs(Ie,{className:"p-6 md:p-8",children:[e.jsx("p",{className:"text-xs uppercase tracking-widest text-primary font-semibold mb-2",children:"A note from your agent"}),e.jsx("p",{className:"text-base md:text-lg leading-relaxed whitespace-pre-wrap text-foreground/90",children:r.settings.priceOverride.note})]})}),ve&&e.jsx(Y9s,{low:_e,likely:he,high:ue}),G&&Ee&&e.jsxs("div",{className:"grid md:grid-cols-3 gap-4",children:[e.jsx(Ne,{className:"md:col-span-2",children:e.jsxs(Ie,{className:"p-6 md:p-8",children:[e.jsx("p",{className:"text-xs uppercase tracking-widest text-primary font-semibold mb-2",children:"Why this price"}),e.jsx("h2",{className:"text-2xl md:text-3xl font-bold mb-3",children:"The market is talking."}),e.jsxs("p",{className:"text-muted-foreground leading-relaxed",children:["Based on ",e.jsxs("strong",{className:"text-foreground",children:[o.length," comparable ",o.length===1?"home":"homes"]})," in ",Y.city,", the median sale rate is ",e.jsxs("strong",{className:"text-foreground",children:["$",G,"/sqft"]}),". Applied to your home's ",(ze=Y.sqft)==null?void 0:ze.toLocaleString()," sqft, the comps support a value near ",e.jsxs("strong",{className:"text-foreground",children:["$",(G*(Y.sqft||0)).toLocaleString()]}),". Your agent's suggested price reflects local nuance and condition."]})]})}),e.jsx(Ne,{className:"bg-gradient-to-br from-primary/10 to-primary/5 border-primary/20",children:e.jsxs(Ie,{className:"p-6 md:p-8 h-full flex flex-col justify-center",children:[e.jsx("p",{className:"text-xs uppercase tracking-widest text-muted-foreground mb-1",children:"Your home"}),e.jsxs("div",{className:"text-3xl font-bold tabular-nums",children:["$",Ee,e.jsx("span",{className:"text-base font-normal text-muted-foreground",children:"/sqft"})]}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-3",children:["Neighborhood avg: ",e.jsxs("span",{className:"font-medium text-foreground",children:["$",G,"/sqft"]})]}),Se!==null&&Se!==0&&e.jsxs("p",{className:`text-sm font-medium mt-1 ${Se>0?"text-emerald-600":"text-rose-600"}`,children:[Se>0?"▲":"▼"," ",Math.abs(Se),"% ",Se>0?"above":"below"," the median"]})]})})]}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-baseline justify-between mb-4",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-xs uppercase tracking-widest text-primary font-semibold",children:"Homes like yours"}),e.jsx("h2",{className:"text-2xl md:text-3xl font-bold",children:"The Comparables"})]}),e.jsxs(Be,{variant:"outline",className:"text-xs",children:[o.length," comps"]})]}),e.jsx("div",{className:"grid md:grid-cols-2 lg:grid-cols-3 gap-4",children:o.map((it,at)=>{var xt;const Ke=it.snapshot,nt=Ke.soldPrice||Ke.price;return e.jsxs(Ne,{className:`overflow-hidden cursor-pointer transition-all duration-300 hover:shadow-xl hover:-translate-y-1 animate-fade-in ${I===at?"ring-2 ring-primary":""}`,style:{animationDelay:`${at*60}ms`},onClick:()=>E(at),onMouseEnter:()=>P(at),onMouseLeave:()=>P(null),children:[e.jsxs("div",{className:"relative",children:[e.jsx(GEe,{photos:Ke.photos,className:"w-full h-44"}),e.jsxs(Be,{className:"absolute top-2 left-2 bg-black/70 text-white border-0 backdrop-blur-sm",children:["#",at+1]}),e.jsx(Be,{variant:"outline",className:"absolute top-2 right-2 bg-white/95 border-0",children:Ke.status})]}),e.jsxs(Ie,{className:"p-4",children:[e.jsx("div",{className:"font-semibold leading-tight truncate",children:Ke.address}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[Ke.city,", ",Ke.state]}),e.jsx("div",{className:"flex justify-between items-center mt-3 text-sm",children:e.jsxs("span",{className:"text-muted-foreground",children:[Ke.bedrooms??"?","bd · ",Ke.bathrooms??"?","ba · ",((xt=Ke.sqft)==null?void 0:xt.toLocaleString())??"?"," sqft"]})}),e.jsxs("div",{className:"flex justify-between items-center mt-3 pt-3 border-t",children:[e.jsxs("span",{className:"text-xl font-bold tabular-nums",children:["$",nt==null?void 0:nt.toLocaleString()]}),Ke.sqft&&nt?e.jsxs("span",{className:"text-xs text-muted-foreground tabular-nums",children:["$",Math.round(nt/Ke.sqft),"/sqft"]}):null]})]})]},at)})})]}),e.jsx(h$t,{comp:C!==null?($e=o[C])==null?void 0:$e.snapshot:null,open:C!==null,onClose:()=>E(null)}),e.jsx(Ne,{className:"border-primary/20 bg-gradient-to-br from-primary/5 via-background to-background overflow-hidden",children:e.jsxs(Ie,{className:"p-6 md:p-8 space-y-5",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-xs uppercase tracking-widest text-primary font-semibold mb-1",children:"Your turn"}),e.jsxs("h2",{className:"text-2xl md:text-3xl font-bold",children:["What do you think",ie?`, ${ie}`:"","?"]}),e.jsxs("p",{className:"text-sm text-muted-foreground mt-1",children:["One tap. ",((ct=i==null?void 0:i.name)==null?void 0:ct.split(" ")[0])||"Your agent"," hears you instantly."]})]}),e.jsx("div",{className:"flex flex-wrap gap-2",children:[{kind:"love",icon:Jo,label:"I love this price"},{kind:"fair",icon:Vy,label:"Seems fair"},{kind:"lower",icon:rC,label:"I'd price lower"},{kind:"higher",icon:Yl,label:"I'd price higher"},{kind:"ready_to_list",icon:wb,label:"Ready to list"},{kind:"want_walkthrough",icon:Ca,label:"Want a walkthrough"},{kind:"need_time",icon:Ta,label:"Need more time"},{kind:"have_questions",icon:s4,label:"I have questions"}].map(({kind:it,icon:at,label:Ke})=>e.jsxs($,{variant:"outline",className:"bg-card hover:bg-primary hover:text-primary-foreground hover:scale-105 transition-all",onClick:()=>U(it),children:[e.jsx(at,{className:"w-4 h-4 mr-2"}),Ke]},it))}),e.jsxs("div",{className:"pt-4 border-t",children:[e.jsxs("p",{className:"text-sm font-medium mb-2 flex items-center gap-1",children:[e.jsx(Th,{className:"w-4 h-4"}),"Ask your agent a question"]}),w?e.jsxs("div",{className:"rounded-md bg-emerald-50 border border-emerald-200 p-4 text-sm text-emerald-800 animate-fade-in",children:["✓ Sent! ",((Xe=i==null?void 0:i.name)==null?void 0:Xe.split(" ")[0])||"Your agent"," was notified and will get back to you shortly."]}):e.jsxs(e.Fragment,{children:[W&&e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-2 mb-2",children:[e.jsx("input",{className:"border rounded-md p-2 text-sm bg-background",placeholder:"Your name",value:f,onChange:it=>g(it.target.value)}),e.jsx("input",{type:"email",className:"border rounded-md p-2 text-sm bg-background",placeholder:"Your email",value:x,onChange:it=>y(it.target.value)})]}),e.jsx("textarea",{className:"w-full border rounded-md p-3 text-sm min-h-[100px] bg-background",placeholder:"What questions do you have about this analysis?",value:h,onChange:it=>m(it.target.value)}),e.jsx($,{onClick:V,disabled:!h.trim()||v,className:"mt-2",children:v?"Sending…":"Send to agent"})]})]})]})}),i&&e.jsx(Ne,{className:"overflow-hidden border-primary/20",children:e.jsx("div",{className:"bg-gradient-to-br from-primary/10 to-primary/5 p-6 md:p-10",children:e.jsxs("div",{className:"flex flex-col md:flex-row gap-6 items-start",children:[i.avatar_url?e.jsx("img",{src:i.avatar_url,alt:i.name,className:"w-24 h-24 md:w-32 md:h-32 rounded-2xl object-cover ring-4 ring-background shadow-lg"}):e.jsx("div",{className:"w-24 h-24 md:w-32 md:h-32 rounded-2xl bg-primary/20 flex items-center justify-center text-3xl font-bold text-primary ring-4 ring-background shadow-lg",children:ne}),e.jsxs("div",{className:"flex-1",children:[e.jsx("p",{className:"text-xs uppercase tracking-widest text-muted-foreground",children:"Prepared by"}),e.jsx("h2",{className:"text-2xl md:text-3xl font-bold mt-1",children:i.name}),(i.title||i.brokerage_name)&&e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:[i.title,i.brokerage_name].filter(Boolean).join(" · ")}),i.bio&&e.jsx("p",{className:"text-sm text-muted-foreground mt-3 leading-relaxed",children:i.bio}),e.jsxs("div",{className:"flex flex-wrap gap-2 mt-4",children:[te&&e.jsx($,{asChild:!0,children:e.jsxs("a",{href:te,children:[e.jsx(Da,{className:"w-4 h-4 mr-2"}),i.phone]})}),J&&e.jsx($,{variant:"outline",asChild:!0,children:e.jsxs("a",{href:J,children:[e.jsx(mn,{className:"w-4 h-4 mr-2"}),"Email"]})}),i.website_url&&e.jsx($,{variant:"outline",asChild:!0,children:e.jsxs("a",{href:i.website_url,target:"_blank",rel:"noreferrer",children:[e.jsx(dl,{className:"w-4 h-4 mr-2"}),"Website"]})})]})]})]})})})]}),i&&(te||ce||J)&&e.jsxs("div",{className:"md:hidden fixed bottom-0 left-0 right-0 bg-card/95 backdrop-blur border-t shadow-2xl z-50 px-3 py-3 flex gap-2",style:{paddingBottom:"calc(0.75rem + env(safe-area-inset-bottom))"},children:[te&&e.jsx($,{className:"flex-1",asChild:!0,children:e.jsxs("a",{href:te,children:[e.jsx(Da,{className:"w-4 h-4 mr-1.5"}),"Call"]})}),ce&&e.jsx($,{variant:"outline",className:"flex-1",asChild:!0,children:e.jsxs("a",{href:ce,children:[e.jsx(Th,{className:"w-4 h-4 mr-1.5"}),"Text"]})}),J&&e.jsx($,{variant:"outline",className:"flex-1",asChild:!0,children:e.jsxs("a",{href:J,children:[e.jsx(mn,{className:"w-4 h-4 mr-1.5"}),"Email"]})})]})]})}function Z9s(){const t=fu().pathname.slice(1).replace(/\/$/,"");return!t||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:"CMA Portal"}),e.jsx("p",{className:"text-slate-500",children:"Open your CMA link to view your personalized market analysis."})]})}):e.jsx(m$t,{tokenOverride:t})}const DGe="levelup_affiliate_ref",X9s=30,Q9s=()=>{const[s]=gc();j.useEffect(()=>{const t=s.get("ref");if(t){const n={code:t.toUpperCase(),timestamp:Date.now()};localStorage.setItem(DGe,JSON.stringify(n)),console.log("[Affiliate] Stored referral code:",t)}},[s])},J9s=()=>{try{const s=localStorage.getItem(DGe);if(!s)return null;const t=JSON.parse(s),n=X9s*24*60*60*1e3;return Date.now()-t.timestamp>n?(localStorage.removeItem(DGe),console.log("[Affiliate] Referral code expired"),null):t.code}catch{return null}},WEe="/assets/levelup-logo-header-_ZX7DvlA.png",e$s="/assets/scale-your-team-ku4MPatU.png";function t$s({open:s,onOpenChange:t}){return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Os,{className:"max-w-3xl max-h-[90vh] overflow-hidden",children:[e.jsx(Us,{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(ji,{className:"h-5 w-5 text-[#4a6b6d]"})}),e.jsxs("div",{children:[e.jsx(Bs,{children:"Schedule a Brokerage Interest Meeting"}),e.jsx(Ir,{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 Jae="/assets/mission_control-BJ-Kz8rX.png",r6e="/assets/crm-CsLftmB2.png",a6e="/assets/deal_pipeline-XYgypvwv.png",i6e="/assets/staging_studio-5iLDjnv0.png",o6e="/assets/coaching-CSQEA81I.png",l6e="/assets/marketing_studio-Brx1ZOnN.png",s$s=[{key:"dashboard",label:"Agent Command Center",caption:"Your entire day — smart queue, calendar and pipeline in one view.",src:Jae},{key:"crm",label:"CRM & Contact Hub",caption:"Contacts, tags, follow-ups and deal history, always one click away.",src:r6e},{key:"pipeline",label:"Deal Pipeline",caption:"Every active deal with tasks, forms and commission tracking built in.",src:a6e},{key:"staging",label:"Staging Studio",caption:"AI photo staging — MLS-ready before/afters in minutes.",src:i6e},{key:"coaching",label:"Coaching",caption:"Book live coaching sessions with Google Meet created automatically.",src:o6e},{key:"marketing",label:"Marketing Studio",caption:"Templates, social posts, reels and print — all branded to you.",src:l6e}];function n$s({slot:s}){return e.jsxs("figure",{className:"rounded-2xl overflow-hidden border border-white/10 bg-white/5 backdrop-blur-sm shadow-2xl",children:[e.jsxs("div",{className:"flex items-center gap-1.5 px-3 py-2 border-b border-white/10",children:[e.jsx("span",{className:"h-2.5 w-2.5 rounded-full bg-red-400/80"}),e.jsx("span",{className:"h-2.5 w-2.5 rounded-full bg-amber-400/80"}),e.jsx("span",{className:"h-2.5 w-2.5 rounded-full bg-green-400/80"}),e.jsx("span",{className:"ml-3 text-[11px] rounded px-2 py-0.5 bg-white/10 text-white/70",children:"dashboard.relevelup.com"})]}),s.src?e.jsx("img",{src:s.src,alt:`LevelUp ${s.label} screenshot`,className:"w-full h-auto block",loading:"lazy"}):e.jsxs("div",{className:"w-full aspect-[16/10] flex flex-col items-center justify-center gap-3 bg-white/5",children:[e.jsx(Nn,{className:"h-8 w-8 text-white/40"}),e.jsx("p",{className:"text-sm font-medium text-white/60",children:s.label}),e.jsx("p",{className:"text-xs px-6 text-center text-white/40",children:"Screenshot placeholder"})]}),e.jsxs("figcaption",{className:"px-4 py-3 text-sm text-white/80",children:[e.jsx("span",{className:"font-semibold text-white",children:s.label})," — ",s.caption]})]})}const aN={individual_agent:{name:"Individual Agent",price:"$39",period:"/month",description:"Perfect for independent agents ready to level up",features:["Full dashboard access","300+ professional templates","Academy training library","Community & networking","Live events & workshops","Social media content","Newsletter resources","Email support"],trial:"7-day free trial"},brokerage_over_25:{name:"Brokerage",subtitle:"Unlimited Agents",price:"$499",period:"/month",description:"Scale your brokerage without limits",features:["Everything in Individual, plus:","Unlimited agents","Brokerage manager dashboard","Exclusive brokerage resources","Team performance analytics","Agent onboarding tools","Resource sharing","Priority support"]}},r$s=[{icon:tf,title:"Academy Training",description:"Access a library of on-demand video training covering lead generation, marketing, technology, and more."},{icon:Yc,title:"300+ Templates",description:"Professional Canva templates for social media, flyers, postcards, and marketing materials."},{icon:Ta,title:"Live Events",description:"Weekly live training sessions, workshops, and Q&A events with industry experts."},{icon:Th,title:"Agent Community",description:"Connect with fellow agents, share wins, ask questions, and network in our private community."},{icon:Jr,title:"Resource Kits",description:"Downloadable toolkits with scripts, checklists, guides, and everything you need to close more deals."},{icon:ul,title:"Social Swag",description:"Fresh social media content and designs updated regularly to help you stand out online."}],a$s=[{category:"Marketing Studio",icon:xm,items:["Weekly Reels scripts","Social Post Generator","300+ Canva templates","Marketing Calendar","Postcard Direct Mail","Listing Music Videos","Social Swag drops"]},{category:"Lead Generation",icon:rh,items:["Custom lead websites","Open House Guest Book","RSVP pages","Resource landing pages","Listing Revival™","FSBO Breakthrough","Attract system"]},{category:"CRM & Deals",icon:Ev,items:["Agent OS CRM","Deal pipeline","Forms & e-signatures","Client portal","Smart follow-up queue","Lead ponds for teams","Google Business reviews"]},{category:"AI & Media",icon:sy,items:["AI Staging Studio","Video library & sharing","Screen recording","Virtual backgrounds","AI blog writer","YouTube → Blog","Ask AI assistant"]},{category:"Growth & Coaching",icon:of,items:["Academy courses","Live weekly coaching","Coaching programs","1:1 coaching booking","Private community","Live events & workshops"]},{category:"Brokerage Tools",icon:ji,items:["Manager dashboard","Team analytics","Agent onboarding","Office form libraries","Listing Exchange","Brand kits","Recruiting pipeline"]}],i$s=[{icon:Zn,title:"Contact Management",description:"Organize your sphere into relationship tiers—Top 25, Past Clients, Referral Partners, and more."},{icon:Nn,title:"Smart Touchpoint Plans",description:"Automated action plans that tell you exactly who to contact and how, based on relationship type."},{icon:Da,title:"One-Tap Actions",description:"Call, text, or email contacts directly with pre-written scripts tailored to each relationship."},{icon:Fg,title:"Birthday & Anniversary Alerts",description:"Never miss an important date—get reminders for birthdays and home anniversaries."},{icon:ci,title:"Pop-by Map",description:"See all your contacts on a map and plan efficient pop-by routes in your area."},{icon:Wl,title:"Momentum Tracking",description:"Track your touch streaks, weekly goals, and relationship health scores."},{icon:Jo,title:"Relationship Health",description:"Visual dashboard showing which contacts need attention based on last touch date."},{icon:eg,title:"Daily Action Cards",description:"Wake up to a prioritized list of exactly who to reach out to today."}],o$s=[{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."}],l$s=()=>{const{user:s,loading:t}=vs(),n=Qn(),[r]=gc();j.useEffect(()=>{const I=window.location.host==="listings.relevelup.com",P=window.location.pathname==="/";if(I&&P){n("/public/listings",{replace:!0});return}},[n]);const[a,i]=j.useState(null),[l,o]=j.useState(null),[c,d]=j.useState(!1),[u,h]=j.useState(""),[m,f]=j.useState(""),[g,x]=j.useState(""),[y,v]=j.useState(!1),[b,w]=j.useState(!1),S=(I,P=!1)=>{o({tier:I,skipTrial:P}),d(!0)};Q9s(),j.useEffect(()=>{const I=window.location.host==="listings.relevelup.com",P=location.pathname.startsWith("/public/");!t&&s&&!I&&!P&&n("/dashboard")},[s,t,n,location.pathname]),j.useEffect(()=>{r.get("canceled")==="true"&&re.error("Checkout was canceled. Feel free to try again when you're ready!")},[r]);const C=async(I,P=!1)=>{if(!u){re.error("Please enter your email address");return}if(!m.trim()){re.error("Please enter your full name");return}v(!0),i(I+(P?"_direct":""));const R=J9s();try{const{data:D,error:O}=await q.functions.invoke("create-checkout",{body:{tier:I,email:u,name:m.trim(),couponCode:g.trim()||void 0,skipTrial:P,referralCode:R}});if(O)throw O;if(D!=null&&D.url)window.open(D.url,"_blank","noopener,noreferrer"),re.success("Checkout opened in a new tab");else throw new Error("No checkout URL returned")}catch(D){console.error("Checkout error:",D),re.error(D.message||"Failed to start checkout. Please try again.")}finally{v(!1),i(null),d(!1),o(null)}},E=()=>{l&&C(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:WEe,alt:"LevelUp",className:"h-8 md:h-10"})}),e.jsxs("div",{className:"flex items-center gap-2 md:gap-4",children:[e.jsx($,{variant:"ghost",className:"text-white/90 hover:text-white hover:bg-white/10 hidden sm:inline-flex",onClick:()=>{var I;return(I=document.getElementById("features"))==null?void 0:I.scrollIntoView({behavior:"smooth"})},children:"Features"}),e.jsx($,{variant:"ghost",className:"text-white/90 hover:text-white hover:bg-white/10 hidden sm:inline-flex",onClick:()=>{var I;return(I=document.getElementById("pricing"))==null?void 0:I.scrollIntoView({behavior:"smooth"})},children:"Pricing"}),e.jsx($,{variant:"ghost",className:"text-white/90 hover:text-white hover:bg-white/10 hidden sm:inline-flex",onClick:()=>n("/blog"),children:"Blog"}),e.jsx($,{onClick:()=>n("/auth"),className:"bg-white text-[#4a6b6d] hover:bg-gray-100 font-medium shadow-md",children:"Sign In"})]})]})}),e.jsxs("section",{className:"relative overflow-hidden bg-[#0f2530]",children:[e.jsx("style",{children:` @keyframes hero-float { 0%,100% { transform: translateY(0px); } 50% { transform: translateY(-12px); } } @keyframes hero-float-slow { 0%,100% { transform: translateY(0px); } 50% { transform: translateY(-8px); } } @keyframes hero-glow { 0%,100% { opacity: 0.55; } 50% { opacity: 0.9; } } `}),e.jsx("div",{className:"absolute inset-0 bg-gradient-to-b from-[#122c3a] via-[#16384a] to-[#0f2530]"}),e.jsx("div",{className:"absolute -top-40 left-1/2 -translate-x-1/2 h-[560px] w-[900px] rounded-full bg-[#4aa8a0]/25 blur-[140px] animate-[hero-glow_7s_ease-in-out_infinite]"}),e.jsx("div",{className:"absolute top-1/3 -left-40 h-[420px] w-[420px] rounded-full bg-[#2a6f8a]/20 blur-[120px]"}),e.jsx("div",{className:"absolute top-1/4 -right-40 h-[420px] w-[420px] rounded-full bg-[#c9a84c]/10 blur-[120px]"}),e.jsx("div",{className:"absolute inset-0 opacity-[0.12] bg-[linear-gradient(to_right,rgba(255,255,255,0.5)_1px,transparent_1px),linear-gradient(to_bottom,rgba(255,255,255,0.5)_1px,transparent_1px)] bg-[size:56px_56px] [mask-image:radial-gradient(ellipse_75%_65%_at_50%_35%,black,transparent)]"}),e.jsx("div",{className:"absolute inset-x-0 bottom-0 h-40 bg-gradient-to-t from-[#0f2530] to-transparent"}),e.jsxs("div",{className:"container mx-auto px-4 relative",children:[e.jsxs("div",{className:"max-w-5xl mx-auto text-center pt-20 md:pt-28 pb-10 space-y-8",children:[e.jsx("div",{className:"flex justify-center animate-fade-in",children:e.jsxs("span",{className:"inline-flex items-center gap-2 rounded-full border border-white/15 bg-white/5 backdrop-blur-sm px-4 py-1.5 text-xs md:text-sm font-semibold tracking-wide text-white/85 shadow-lg",children:[e.jsx(Nn,{className:"h-3.5 w-3.5 text-[#7fd4cc]"}),"The Agent Operating System — coaching, CRM & marketing in one"]})}),e.jsxs("h1",{className:"text-4xl sm:text-5xl md:text-7xl font-sans font-bold tracking-tight text-white leading-[1.05] animate-fade-in",children:["The tools you need",e.jsx("br",{className:"hidden sm:block"})," to get it done.",e.jsx("span",{className:"block mt-3 bg-gradient-to-r from-[#8fe0d6] via-[#5cc0b6] to-[#e6c878] bg-clip-text text-transparent",children:"The platform to keep it going."})]}),e.jsx("p",{className:"text-base md:text-xl text-white/65 max-w-2xl mx-auto leading-relaxed animate-fade-in",children:"Weekly coaching, a smart CRM, done-for-you marketing and AI tools — everything a modern agent runs on, in one login."}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-4 justify-center items-center pt-2 animate-fade-in",children:[e.jsxs($,{size:"lg",onClick:()=>{var I;return(I=document.getElementById("free-trial"))==null?void 0:I.scrollIntoView({behavior:"smooth"})},className:"px-8 py-7 text-lg font-semibold bg-white text-[#122c3a] hover:bg-white/90 shadow-[0_0_40px_-8px_rgba(140,220,210,0.6)] transition-all hover:scale-105 group rounded-full",children:["Start Your Free Trial",e.jsx(ei,{className:"ml-2 w-5 h-5 group-hover:translate-x-1 transition-transform"})]}),e.jsx($,{size:"lg",variant:"outline",onClick:()=>{var I;return(I=document.getElementById("features"))==null?void 0:I.scrollIntoView({behavior:"smooth"})},className:"px-8 py-7 text-lg font-semibold border-2 border-white/40 text-white bg-white/5 backdrop-blur-sm hover:bg-white hover:text-[#122c3a] rounded-full",children:"See What's Included"})]}),e.jsxs("div",{className:"flex flex-wrap items-center justify-center gap-x-8 gap-y-3 pt-2 text-sm text-white/55 animate-fade-in",children:[e.jsxs("span",{className:"inline-flex items-center gap-2",children:[e.jsx(Ja,{className:"h-4 w-4 text-[#e6c878] fill-[#e6c878]"})," Built with agents' direct input"]}),e.jsxs("span",{className:"inline-flex items-center gap-2",children:[e.jsx(eg,{className:"h-4 w-4 text-[#7fd4cc]"})," New tools added every month"]}),e.jsxs("span",{className:"inline-flex items-center gap-2",children:[e.jsx(Mf,{className:"h-4 w-4 text-white/60"})," Cancel anytime"]})]})]}),e.jsxs("div",{className:"relative max-w-5xl mx-auto pb-20 md:pb-28 px-2",children:[e.jsx("div",{className:"absolute inset-x-8 top-10 bottom-0 rounded-[40px] bg-gradient-to-b from-[#4aa8a0]/30 to-transparent blur-2xl","aria-hidden":!0}),e.jsxs("div",{className:"relative animate-[hero-float-slow_8s_ease-in-out_infinite]",children:[e.jsxs("figure",{className:"rounded-2xl overflow-hidden border border-white/15 bg-[#0d1f29]/80 backdrop-blur-md shadow-[0_40px_80px_-20px_rgba(0,0,0,0.7)]",children:[e.jsxs("div",{className:"flex items-center gap-1.5 px-4 py-2.5 border-b border-white/10 bg-white/5",children:[e.jsx("span",{className:"h-2.5 w-2.5 rounded-full bg-red-400/80"}),e.jsx("span",{className:"h-2.5 w-2.5 rounded-full bg-amber-400/80"}),e.jsx("span",{className:"h-2.5 w-2.5 rounded-full bg-green-400/80"}),e.jsx("span",{className:"ml-3 text-[11px] rounded px-2 py-0.5 bg-white/10 text-white/70",children:"dashboard.relevelup.com"})]}),e.jsx("img",{src:Jae,alt:"LevelUp Agent Command Center dashboard",className:"w-full h-auto block"})]}),e.jsxs("div",{className:"hidden md:flex absolute -left-10 top-24 items-center gap-3 rounded-2xl border border-white/15 bg-[#122c3a]/90 backdrop-blur-md px-4 py-3 shadow-2xl animate-[hero-float_6s_ease-in-out_infinite]",children:[e.jsx("span",{className:"flex h-9 w-9 items-center justify-center rounded-xl bg-[#4aa8a0]/20",children:e.jsx(Yl,{className:"h-5 w-5 text-[#7fd4cc]"})}),e.jsxs("span",{children:[e.jsx("span",{className:"block text-sm font-semibold text-white",children:"Smart Queue ready"}),e.jsx("span",{className:"block text-xs text-white/55",children:"5 follow-ups due today"})]})]}),e.jsxs("div",{className:"hidden md:flex absolute -right-10 top-1/2 items-center gap-3 rounded-2xl border border-white/15 bg-[#122c3a]/90 backdrop-blur-md px-4 py-3 shadow-2xl animate-[hero-float_7s_ease-in-out_infinite_1s]",children:[e.jsx("span",{className:"flex h-9 w-9 items-center justify-center rounded-xl bg-[#e6c878]/15",children:e.jsx(tf,{className:"h-5 w-5 text-[#e6c878]"})}),e.jsxs("span",{children:[e.jsx("span",{className:"block text-sm font-semibold text-white",children:"Weekly Reels delivered"}),e.jsx("span",{className:"block text-xs text-white/55",children:"Fresh scripts every Monday"})]})]}),e.jsxs("div",{className:"hidden md:flex absolute left-8 -bottom-6 items-center gap-3 rounded-2xl border border-white/15 bg-[#122c3a]/90 backdrop-blur-md px-4 py-3 shadow-2xl animate-[hero-float_6.5s_ease-in-out_infinite_0.5s]",children:[e.jsx("span",{className:"flex h-9 w-9 items-center justify-center rounded-xl bg-white/10",children:e.jsx(Ta,{className:"h-5 w-5 text-white/80"})}),e.jsxs("span",{children:[e.jsx("span",{className:"block text-sm font-semibold text-white",children:"Coaching booked"}),e.jsx("span",{className:"block text-xs text-white/55",children:"Meet link added automatically"})]})]})]})]})]})]}),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($,{size:"lg",variant:"outline",onClick:()=>{var I;return(I=document.getElementById("brokerage"))==null?void 0:I.scrollIntoView({behavior:"smooth"})},className:"border-[#4a6b6d] text-[#4a6b6d] hover:bg-[#4a6b6d]/5",children:[e.jsx(ji,{className:"mr-2 h-5 w-5"}),"Brokerage Partnership"]}),e.jsxs($,{size:"lg",onClick:()=>{var I;return(I=document.getElementById("pricing"))==null?void 0:I.scrollIntoView({behavior:"smooth"})},className:"bg-[#4a6b6d] hover:bg-[#3d5a5c]",children:[e.jsx(sl,{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.jsxs("span",{className:"inline-flex items-center gap-2 px-4 py-1.5 rounded-full bg-[#4a6b6d]/10 text-[#4a6b6d] text-sm font-semibold mb-5",children:[e.jsx(L4,{className:"w-4 h-4"}),"40+ tools & counting"]}),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:r$s.map((I,P)=>e.jsxs(Ne,{className:"group relative overflow-hidden border hover:border-[#4a6b6d]/50 transition-all duration-300 hover:shadow-lg bg-background",children:[e.jsxs(Ct,{children:[e.jsx("div",{className:"w-14 h-14 rounded-2xl bg-[#4a6b6d]/10 flex items-center justify-center mb-4",children:e.jsx(I.icon,{className:"w-7 h-7 text-[#4a6b6d]"})}),e.jsx(At,{className:"text-xl font-sans",children:I.title})]}),e.jsx(Ie,{children:e.jsx("p",{className:"text-muted-foreground leading-relaxed",children:I.description})})]},P))}),e.jsxs("div",{className:"mt-14 max-w-6xl mx-auto rounded-3xl bg-gradient-to-br from-[#1e3a4c] via-[#2a4f5f] to-[#3d6b6b] p-8 md:p-12 relative overflow-hidden shadow-2xl",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:"relative",children:[e.jsxs("div",{className:"text-center mb-10",children:[e.jsx("h3",{className:"text-2xl md:text-3xl font-bold text-white font-sans",children:"...and that's just the beginning"}),e.jsx("p",{className:"text-white/60 mt-2",children:"Dozens of purpose-built tools, all included with membership."})]}),e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-x-10 gap-y-8",children:a$s.map(I=>e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2.5 mb-4",children:[e.jsx("span",{className:"flex h-8 w-8 items-center justify-center rounded-lg bg-white/10",children:e.jsx(I.icon,{className:"h-4 w-4 text-white"})}),e.jsx("span",{className:"text-sm font-bold uppercase tracking-wider text-white/90",children:I.category})]}),e.jsx("ul",{className:"space-y-2.5",children:I.items.map(P=>e.jsxs("li",{className:"flex items-center gap-2.5 text-white/70 text-sm",children:[e.jsx(la,{className:"h-3.5 w-3.5 text-emerald-300 shrink-0"}),P]},P))})]},I.category))}),e.jsxs("p",{className:"text-center text-white/50 text-sm mt-10 flex items-center justify-center gap-2",children:[e.jsx(Nn,{className:"h-4 w-4"}),"New tools added every month — membership keeps getting more valuable."]})]})]})]})}),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.jsxs("div",{className:"container mx-auto px-4 relative",children:[e.jsxs("div",{className:"text-center max-w-3xl mx-auto mb-14",children:[e.jsx("span",{className:"text-sm font-semibold tracking-[0.15em] uppercase text-white/70",children:"See it in action"}),e.jsx("h2",{className:"text-3xl md:text-5xl font-bold text-white mt-4 tracking-tight font-sans",children:"A real platform, not another course"}),e.jsx("p",{className:"text-white/60 mt-4 max-w-2xl mx-auto text-lg",children:"This is what members open every morning."})]}),e.jsx("div",{className:"grid md:grid-cols-2 gap-8 md:gap-10 max-w-6xl mx-auto",children:s$s.map(I=>e.jsx(n$s,{slot:I},I.key))})]})]}),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(Nn,{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:i$s.map((I,P)=>e.jsxs(Ne,{className:"group relative overflow-hidden border-0 bg-white/10 backdrop-blur-sm hover:bg-white/20 transition-all duration-300",children:[e.jsxs(Ct,{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(I.icon,{className:"w-6 h-6 text-white"})}),e.jsx(At,{className:"text-lg font-semibold text-white",children:I.title})]}),e.jsx(Ie,{children:e.jsx("p",{className:"text-white/70 text-sm leading-relaxed",children:I.description})})]},P))}),e.jsx("div",{className:"text-center mt-12",children:e.jsxs($,{size:"lg",onClick:()=>{var I;return(I=document.getElementById("pricing"))==null?void 0:I.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(ei,{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(ji,{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((I,P)=>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(la,{className:"w-4 h-4 text-[#4a6b6d]"})}),e.jsx("span",{className:"text-foreground",children:I})]},P))}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-3 mt-4",children:[e.jsxs($,{size:"lg",onClick:()=>{var I;return(I=document.getElementById("pricing"))==null?void 0:I.scrollIntoView({behavior:"smooth"})},className:"bg-[#4a6b6d] hover:bg-[#3d5a5c]",children:["See Brokerage Plans",e.jsx(Di,{className:"ml-2 w-5 h-5"})]}),e.jsxs($,{size:"lg",variant:"outline",onClick:()=>w(!0),className:"border-[#4a6b6d] text-[#4a6b6d] hover:bg-[#4a6b6d]/10",children:[e.jsx(Ta,{className:"mr-2 w-5 h-5"}),"Schedule Info Session"]})]})]}),e.jsx("div",{className:"relative hidden md:block",children:e.jsx("img",{src:e$s,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:o$s.map((I,P)=>e.jsx(Ne,{className:"bg-muted/30 border-0",children:e.jsxs(Ie,{className:"pt-8",children:[e.jsx("div",{className:"flex gap-1 mb-4",children:[1,2,3,4,5].map(R=>e.jsx(Ja,{className:"w-5 h-5 fill-yellow-400 text-yellow-400"},R))}),e.jsxs("p",{className:"text-lg mb-6 italic text-muted-foreground",children:['"',I.quote,'"']}),e.jsxs("div",{children:[e.jsx("p",{className:"font-semibold",children:I.name}),e.jsx("p",{className:"text-sm text-muted-foreground",children:I.role})]})]})},P))})]})}),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($,{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:()=>S("individual_agent"),children:["Start Free Trial",e.jsx(ei,{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-2 gap-8 max-w-4xl mx-auto",children:[e.jsxs(Ne,{className:"relative flex flex-col border hover:border-[#4a6b6d]/50 transition-all hover:shadow-xl bg-background",children:[e.jsxs(Ct,{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(sl,{className:"w-5 h-5 text-[#4a6b6d]"})}),e.jsx(At,{className:"text-xl font-sans",children:aN.individual_agent.name})]}),e.jsxs("div",{className:"flex items-baseline gap-1 mt-4",children:[e.jsx("span",{className:"text-5xl font-bold",children:aN.individual_agent.price}),e.jsx("span",{className:"text-muted-foreground text-lg",children:aN.individual_agent.period})]}),e.jsx(Gn,{className:"text-base mt-2",children:aN.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(da,{className:"w-4 h-4"}),aN.individual_agent.trial]})]}),e.jsx(Ie,{className:"flex-1 pt-0",children:e.jsx("ul",{className:"space-y-3",children:aN.individual_agent.features.map((I,P)=>e.jsxs("li",{className:"flex items-center gap-3",children:[e.jsx(la,{className:"w-5 h-5 text-[#4a6b6d] flex-shrink-0"}),e.jsx("span",{children:I})]},P))})}),e.jsxs(wEe,{className:"flex flex-col gap-3 pt-4",children:[e.jsx($,{className:"w-full py-6 text-lg bg-[#4a6b6d] hover:bg-[#3d5a5c]",onClick:()=>S("individual_agent"),children:"Start Free Trial"}),e.jsx($,{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:()=>S("individual_agent",!0),children:"Skip Trial, Subscribe Now"})]})]}),e.jsxs(Ne,{className:"relative flex flex-col border-2 border-[#4a6b6d] shadow-2xl 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(Ct,{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(ji,{className:"w-5 h-5 text-[#4a6b6d]"})}),e.jsxs("div",{children:[e.jsx(At,{className:"text-xl font-sans",children:aN.brokerage_over_25.name}),e.jsx("span",{className:"text-sm text-muted-foreground",children:aN.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:aN.brokerage_over_25.price}),e.jsx("span",{className:"text-muted-foreground text-lg",children:aN.brokerage_over_25.period})]}),e.jsx(Gn,{className:"text-base mt-2",children:aN.brokerage_over_25.description})]}),e.jsx(Ie,{className:"flex-1 pt-0",children:e.jsx("ul",{className:"space-y-3",children:aN.brokerage_over_25.features.map((I,P)=>e.jsxs("li",{className:"flex items-center gap-3",children:[e.jsx(la,{className:"w-5 h-5 text-[#4a6b6d] flex-shrink-0"}),e.jsx("span",{children:I})]},P))})}),e.jsx(wEe,{className:"pt-4",children:e.jsx($,{className:"w-full py-6 text-lg shadow-lg bg-[#4a6b6d] hover:bg-[#3d5a5c]",onClick:()=>S("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(Mf,{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(Ne,{className:"border-[#4a6b6d]/20 bg-[#4a6b6d]/[0.03]",children:e.jsxs(Ie,{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(ji,{className:"w-5 h-5 text-[#4a6b6d]"})}),e.jsx("p",{className:"text-foreground font-medium leading-relaxed",children:"LevelUp serves all brokerages."})]})}),e.jsx(Ne,{className:"border-[#4a6b6d]/20 bg-[#4a6b6d]/[0.03]",children:e.jsxs(Ie,{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(pc,{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(Ne,{className:"border-[#4a6b6d]/20 bg-[#4a6b6d]/[0.03]",children:e.jsxs(Ie,{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(y2,{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(Ne,{className:"border-[#4a6b6d]/20 bg-[#4a6b6d]/[0.03]",children:e.jsxs(Ie,{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(Jr,{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($,{size:"lg",onClick:()=>{var I;return(I=document.getElementById("pricing"))==null?void 0:I.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(ei,{className:"ml-2 w-5 h-5"})]}),e.jsx($,{size:"lg",onClick:()=>n("/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:WEe,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:"/blog",className:"text-white/60 hover:text-white transition-colors text-sm",children:"Blog"}),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(t$s,{open:b,onOpenChange:w}),e.jsx(zs,{open:c,onOpenChange:d,children:e.jsxs(Os,{className:"sm:max-w-md",children:[e.jsxs(Us,{children:[e.jsx(Bs,{className:"text-xl font-sans font-semibold",children:"Enter your details to get started"}),e.jsx(Ir,{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":"Subscribe to Brokerage"})]}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{children:[e.jsxs(ee,{htmlFor:"dialog-name",children:["Full Name ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx(pe,{id:"dialog-name",type:"text",placeholder:"John Smith",value:m,onChange:I=>f(I.target.value),className:"mt-1",required:!0})]}),e.jsxs("div",{children:[e.jsxs(ee,{htmlFor:"dialog-email",children:["Email Address ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx(pe,{id:"dialog-email",type:"email",placeholder:"you@example.com",value:u,onChange:I=>h(I.target.value),className:"mt-1",required:!0})]}),e.jsxs("div",{children:[e.jsxs(ee,{htmlFor:"dialog-coupon",children:["Discount Code ",e.jsx("span",{className:"text-muted-foreground",children:"(Optional)"})]}),e.jsx(pe,{id:"dialog-coupon",type:"text",placeholder:"Enter discount code",value:g,onChange:I=>x(I.target.value),className:"mt-1"})]})]}),e.jsx($,{className:"w-full py-6 text-lg bg-[#4a6b6d] hover:bg-[#3d5a5c]",onClick:E,disabled:y,children:y?"Loading...":"Continue to Checkout"})]})})]})},Evt=()=>e.jsxs(e.Fragment,{children:[e.jsxs(Ml,{children:[e.jsx("title",{children:"Privacy Policy | LevelUp"}),e.jsx("meta",{name:"description",content:"How LevelUp collects, uses, shares and retains data — including the LevelUp Hub MCP connector for ChatGPT."})]}),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: September 16, 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:'LevelUp ("we," "our," or "us") provides a real estate business platform for agents, teams and brokerages. This policy explains what we collect, why, who receives it, how long we keep it and the controls you have. It covers the LevelUp web app, our public pages, our SMS program and the LevelUp Hub MCP connector that members can connect to ChatGPT and other AI clients.'}),e.jsx("p",{className:"mt-3",children:"Members store information about other people (their contacts, leads and open-house visitors) in LevelUp. For that information the member is the controller and LevelUp processes it on their behalf."})]}),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:"Depending on which features a member uses, we handle:"}),e.jsxs("ul",{className:"list-disc pl-6 mt-2 space-y-1",children:[e.jsxs("li",{children:[e.jsx("strong",{className:"text-foreground",children:"Account and profile:"})," name, email, phone, password credentials, title, brokerage, license number and state, website, headshot and logo images, brand colors, taglines and any brokerage compliance line."]}),e.jsxs("li",{children:[e.jsx("strong",{className:"text-foreground",children:"Billing:"})," subscription status, plan, and transaction records handled by our payment processor (we do not store full card numbers)."]}),e.jsxs("li",{children:[e.jsx("strong",{className:"text-foreground",children:"Contacts and relationship data"})," a member enters or imports: names, emails, phones, mailing addresses, lead source, free-text notes, and optional personal fields such as birthday, home and wedding anniversary, spouse name, spouse email and spouse birthday, company and job title."]}),e.jsxs("li",{children:[e.jsx("strong",{className:"text-foreground",children:"Deals, tasks and interaction history:"})," pipeline stage, prices, commissions, bonuses, key dates, tasks, and logged calls, texts, emails, pop-bys and notes."]}),e.jsxs("li",{children:[e.jsx("strong",{className:"text-foreground",children:"Listings and media:"})," listing details, photos, videos and agent/brokerage attribution, including listings published to the shared Listing Exchange."]}),e.jsxs("li",{children:[e.jsx("strong",{className:"text-foreground",children:"Guest Book visitors:"})," the name, contact details and any survey answers a visitor submits at an open house sign-in page."]}),e.jsxs("li",{children:[e.jsx("strong",{className:"text-foreground",children:"Landing page and website leads:"})," the fields a visitor submits on a member's published landing page, property website or home-value page."]}),e.jsxs("li",{children:[e.jsx("strong",{className:"text-foreground",children:"Generated marketing and campaign data:"})," drafts and records created by our marketing tools (email, social, print, FSBO and Listing Revival), plus the leads and engagement events those campaigns capture."]}),e.jsxs("li",{children:[e.jsx("strong",{className:"text-foreground",children:"MCP audit logs:"})," for each connector tool call we record the member id, tool name, a truncated snapshot of the tool inputs, the outcome, an error label, the duration and the calling client id."]}),e.jsxs("li",{children:[e.jsx("strong",{className:"text-foreground",children:"Technical and usage data:"})," log data, device and browser information, and feature usage needed to run and secure the service."]})]})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"3. How We Use Information"}),e.jsxs("ul",{className:"list-disc pl-6 mt-2 space-y-1",children:[e.jsx("li",{children:"Provide, maintain and improve the platform and the features a member turns on."}),e.jsx("li",{children:"Perform the actions a member asks for, including through a connected AI client."}),e.jsx("li",{children:"Generate marketing copy and assets when a member explicitly requests generation."}),e.jsx("li",{children:"Process payments and send transactional and support messages."}),e.jsx("li",{children:"Secure the service: authentication, rate limiting, audit trails, abuse investigation and support."}),e.jsx("li",{children:"Meet legal, tax and record-keeping obligations."})]}),e.jsx("p",{className:"mt-3",children:"We do not sell personal information, and we do not use member contact data to train AI models."})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"4. LevelUp Hub MCP Connector (ChatGPT and other AI clients)"}),e.jsxs("p",{children:["Members can optionally connect LevelUp Hub to an AI client such as ",e.jsx("strong",{children:"ChatGPT (OpenAI)"})," ","using the Model Context Protocol. The connector is off until a member connects it and signs in through OAuth, and it can be revoked at any time from the AI client."]}),e.jsxs("p",{className:"mt-3",children:["Once connected, the client can call LevelUp tools ",e.jsx("strong",{children:"as that member"})," and receives whatever a called tool returns — which may include profile and branding data, contacts and their relationship fields, deals and tasks, listings and photos, Guest Book visitors, landing-page leads, and campaign records. OpenAI's handling of that data is governed by OpenAI's own terms and privacy policy."]}),e.jsx("p",{className:"mt-3",children:'The connector does not send email, SMS, direct mail or social posts. Tools that "activate" a campaign only change its status inside LevelUp and publish its page; outbound delivery is always a separate action the member takes in the app. Publishing, activating, merging and deleting require an explicit confirmation step, and open houses, landing pages and property sites are created as unpublished drafts unless the member asks otherwise.'}),e.jsxs("p",{className:"mt-3",children:["Full details are on the"," ",e.jsx(wr,{to:"/mcp-data-use",className:"text-primary hover:underline",children:"MCP data use"})," ","page."]})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"5. AI Content Generation"}),e.jsxs("p",{children:["When a member asks for generated copy (listing descriptions, emails, social posts, print collateral, campaign letters), the request is sent to the ",e.jsx("strong",{children:"Lovable AI Gateway"})," and the model provider behind it. That request contains the property details supplied for the task and a brand block with the agent's name, brokerage, phone, email, website, license and any compliance line. Contact records, visitor lists and lead lists are not sent for generation. Nothing is sent to a model provider for read-only tools or for ordinary use of the app."]})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"6. Who Receives Information"}),e.jsxs("ul",{className:"list-disc pl-6 mt-2 space-y-1",children:[e.jsxs("li",{children:[e.jsx("strong",{className:"text-foreground",children:"Infrastructure providers"})," that host our application, database, storage and email/SMS delivery."]}),e.jsxs("li",{children:[e.jsx("strong",{className:"text-foreground",children:"Payment processor"})," for subscriptions and purchases."]}),e.jsxs("li",{children:[e.jsx("strong",{className:"text-foreground",children:"The AI client a member connects"})," (OpenAI/ChatGPT or another MCP client), as described in section 4."]}),e.jsxs("li",{children:[e.jsx("strong",{className:"text-foreground",children:"The Lovable AI Gateway and its model provider"}),", only for generation requests, as described in section 5."]}),e.jsxs("li",{children:[e.jsx("strong",{className:"text-foreground",children:"Third-party services a member connects"})," — for example Google (calendar and sign-in), Gmail, Meta/Facebook and Instagram, YouTube, Canva, Stripe, and CRM imports such as BoldTrail or Lofty — and only when that integration is invoked. Each is governed by its own privacy policy."]}),e.jsxs("li",{children:[e.jsx("strong",{className:"text-foreground",children:"The public"}),", for pages a member publishes: open house sign-in pages, landing pages, property websites and public listing pages."]}),e.jsxs("li",{children:[e.jsx("strong",{className:"text-foreground",children:"Other LevelUp members"}),", for listings a member publishes to the shared Listing Exchange (listing details, photos and agent/brokerage attribution). Contacts, leads and pipeline data are never shared this way."]}),e.jsxs("li",{children:[e.jsx("strong",{className:"text-foreground",children:"Brokerage managers, team leaders, assigned assistants and coaches"}),", limited to the data their role is granted."]}),e.jsxs("li",{children:[e.jsx("strong",{className:"text-foreground",children:"LevelUp administrators"}),", who may act on behalf of a member for support and setup; those actions are recorded in the audit log with the target member."]}),e.jsxs("li",{children:[e.jsx("strong",{className:"text-foreground",children:"Legal recipients"}),", where disclosure is required by law or needed to protect rights and safety."]})]}),e.jsx("p",{className:"mt-3",children:"We do not sell, rent or trade personal information."})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"7. Retention"}),e.jsxs("ul",{className:"list-disc pl-6 mt-2 space-y-1",children:[e.jsx("li",{children:"Account, contact, deal, listing, campaign, visitor and lead records are kept for as long as the account is active, until the member deletes them, or until the account is deleted."}),e.jsx("li",{children:"MCP audit log entries are kept for security and support purposes. They are not purged automatically on a fixed schedule; they can be removed on request."}),e.jsx("li",{children:"Short-lived rate-limit counters expire within minutes."}),e.jsx("li",{children:"Billing and tax records are kept as long as the law requires."}),e.jsx("li",{children:"Backups are cycled on our provider's schedule, so deleted data can persist in backups for a limited period after deletion."})]}),e.jsxs("p",{className:"mt-3",children:["We do not promise an automatic timed purge that we do not operate; see"," ",e.jsx(wr,{to:"/data-deletion",className:"text-primary hover:underline",children:"Data Deletion"})," ","for how requests are handled."]})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"8. Your Choices and Rights"}),e.jsxs("ul",{className:"list-disc pl-6 mt-2 space-y-1",children:[e.jsx("li",{children:"Access, correct or delete records from within the app."}),e.jsx("li",{children:"Connect or disconnect any integration, including the MCP connector, at any time."}),e.jsx("li",{children:"Review connector activity in the MCP activity log."}),e.jsx("li",{children:"Mark a contact as opted out of marketing email, and opt out of SMS by replying STOP."}),e.jsxs("li",{children:["Request access, correction, export or deletion by emailing ",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:"9. Data Security"}),e.jsx("p",{children:"We use access controls, row-level database security scoped to each member, OAuth-based authentication for connectors, per-member rate limiting and audit logging. No method of transmission or storage is completely secure."})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"10. SMS / Text Messaging Program (LevelUp Account & Lead Alerts)"}),e.jsx("p",{children:"If you opt in, we use your mobile number to send SMS account notifications, real-time lead alerts, service updates and support messages related to your LevelUp account."}),e.jsx("p",{className:"mt-3",children:"No mobile information will be shared with third parties or affiliates for marketing or promotional purposes. Text messaging originator opt-in data and consent will not be shared with any third parties, except with the vendors and aggregators that deliver the messages on our behalf."}),e.jsx("p",{className:"mt-3",children:"Message frequency varies. Message and data rates may apply. Reply STOP to opt out and HELP for help."})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"11. LevelUp SmartSign (Property Information by Text)"}),e.jsxs("p",{children:["LevelUp SmartSign is operated by ",e.jsx("strong",{children:"LevelUp Consulting Group"}),". Consumers text a property code displayed on a real estate sign to ",e.jsx("strong",{children:"859-413-5013"})," to request information about that property. LevelUp is the sender of these messages; independent real estate agents do not send messages through the SmartSign number. This program is separate from the LevelUp account and lead alert SMS program described in section 10, and consent to one is not consent to the other."]}),e.jsxs("p",{className:"mt-3",children:[e.jsx("strong",{className:"text-foreground",children:"What we collect:"})," your mobile phone number, the property code you text, the content of your messages, and the details of your inquiry (such as the property you asked about, your questions, and any name or showing preference you provide)."]}),e.jsxs("p",{className:"mt-3",children:[e.jsx("strong",{className:"text-foreground",children:"How we use it:"})," to respond to your inquiry with listing information, answer questions about the property, assist with showing requests, provide support, keep records of your messaging preferences and opt-outs, and meet legal and carrier requirements."]}),e.jsxs("p",{className:"mt-3",children:[e.jsx("strong",{className:"text-foreground",children:"Service providers:"})," messaging providers — including ",e.jsx("strong",{children:"Telnyx"})," — and our hosting and database providers process this information solely to deliver and operate the service on our behalf."]}),e.jsxs("p",{className:"mt-3",children:[e.jsx("strong",{className:"text-foreground",children:"Sharing with an agent:"})," we ask for your separate, specific permission before sharing your inquiry or contact details with a named agent. We identify the actual agent and brokerage first. If you agree, we share your name, phone number and property inquiry with that agent so they can respond to your request. This consumer-requested handoff is not a transfer of your SMS consent: the agent does not receive permission to send you marketing texts, and your LevelUp SmartSign consent does not carry over to them. Agreeing to an agent contacting you also does not enroll you in LevelUp marketing."]}),e.jsxs("p",{className:"mt-3",children:[e.jsx("strong",{className:"text-foreground",children:"Marketing is separate:"})," requesting property information does not enroll you in promotional or marketing texts. Marketing texts require a separate affirmative opt-in, and you can stop them at any time by replying STOP."]}),e.jsxs("p",{className:"mt-3",children:[e.jsx("strong",{className:"text-foreground",children:"No sale or sharing for third-party marketing:"})," we do not sell your information, and no mobile information, SMS opt-in data or consent is shared with third parties or affiliates for their own promotional or marketing purposes. The only recipients are the service providers that deliver the service on our behalf, and — with your separate permission — the specific agent you asked to hear from."]}),e.jsxs("p",{className:"mt-3",children:["Message frequency varies. Message and data rates may apply. Reply STOP to opt out or HELP for help. See the"," ",e.jsx(wr,{to:"/sms-opt-in",className:"text-primary hover:underline",children:"SMS opt-in page"})," ","and"," ",e.jsx(wr,{to:"/terms-of-service",className:"text-primary hover:underline",children:"Terms of Service"})," ","for program details."]})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"12. Children"}),e.jsx("p",{children:"LevelUp is a business tool and is not directed to children under 16."})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"13. Changes to This Policy"}),e.jsx("p",{children:'We will update this page when our practices change and revise the "Last updated" date above.'})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"14. Contact Us"}),e.jsxs("p",{children:["Questions about this policy:"," ",e.jsx("a",{href:"mailto:support@relevelup.com",className:"text-primary hover:underline",children:"support@relevelup.com"}),"."]})]})]})]})})]}),c$s=()=>e.jsxs(e.Fragment,{children:[e.jsxs(Ml,{children:[e.jsx("title",{children:"Canva Support | LevelUp Hub"}),e.jsx("meta",{name:"description",content:"How to connect or disconnect your Canva account to LevelUp Hub and find the designs you've imported. Public support page for Canva users."})]}),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("div",{className:"mb-10",children:e.jsxs("div",{className:"flex items-center gap-3 mb-4",children:[e.jsx("div",{className:"w-10 h-10 rounded-lg bg-primary/10 flex items-center justify-center",children:e.jsx(Mc,{className:"w-5 h-5 text-primary"})}),e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl sm:text-3xl font-bold text-foreground leading-tight",children:"LevelUp Hub — Canva Support"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"LevelUp Hub is a real estate business platform for agents, teams and brokerages. Members can connect their own Canva account and bring their designs into LevelUp."})]})]})}),e.jsxs("div",{className:"prose prose-sm max-w-none text-muted-foreground space-y-10",children:[e.jsxs("section",{children:[e.jsxs("h2",{className:"text-xl font-semibold text-foreground flex items-center gap-2",children:[e.jsx(g2,{className:"w-5 h-5 text-primary"})," Connect your Canva account"]}),e.jsxs("ol",{className:"list-decimal pl-6 mt-3 space-y-2",children:[e.jsxs("li",{children:["Sign in to LevelUp Hub and open your ",e.jsx("strong",{className:"text-foreground",children:"Integrations"})," page."]}),e.jsxs("li",{children:["Find the ",e.jsx("strong",{className:"text-foreground",children:"Canva"})," tile and click"," ",e.jsx("strong",{className:"text-foreground",children:"Connect Canva"}),"."]}),e.jsx("li",{children:"A Canva window opens asking you to approve the connection. LevelUp requests read-only access to your designs so it can list them and save copies you choose."}),e.jsx("li",{children:"After you approve, the window closes and your Integrations page shows your Canva account as connected."})]}),e.jsx("p",{className:"mt-3 text-sm",children:`You can also start this from inside LevelUp tools — for example the postcard or social post editors have an "Import from Canva" button that will ask you to connect first if you haven't yet.`})]}),e.jsxs("section",{children:[e.jsxs("h2",{className:"text-xl font-semibold text-foreground flex items-center gap-2",children:[e.jsx(bd,{className:"w-5 h-5 text-primary"})," Import designs from Canva"]}),e.jsxs("ol",{className:"list-decimal pl-6 mt-3 space-y-2",children:[e.jsx("li",{children:"In the import window, search or browse your Canva designs and select the ones you want."}),e.jsx("li",{children:"Choose which pages or files to bring in and pick a format where the option is shown."}),e.jsx("li",{children:"LevelUp saves a copy of each selected page or file into your LevelUp media, associated with your account and the tool you imported it for."}),e.jsx("li",{children:"You can then use those copies in the feature you imported them into, or open the design in Canva to edit it."})]}),e.jsx("p",{className:"mt-3 text-sm",children:'To open a design in Canva for editing, use the "Design with Canva" action in your Integrations page — it opens your design on canva.com in a new tab.'})]}),e.jsxs("section",{children:[e.jsxs("h2",{className:"text-xl font-semibold text-foreground flex items-center gap-2",children:[e.jsx(Mc,{className:"w-5 h-5 text-primary"})," Finding your imported designs"]}),e.jsxs("ul",{className:"list-disc pl-6 mt-3 space-y-2",children:[e.jsx("li",{children:"Imported images for social posts appear in your LevelUp media library, alongside files you uploaded directly."}),e.jsx("li",{children:"Imported postcard fronts and letter pages appear inside the mail tool where you imported them, listed with your saved designs."}),e.jsx("li",{children:"Your Canva connection and the design browsing inside LevelUp are per agent — only your signed-in account can connect your Canva account and browse your designs."})]})]}),e.jsxs("section",{children:[e.jsxs("h2",{className:"text-xl font-semibold text-foreground flex items-center gap-2",children:[e.jsx(o7,{className:"w-5 h-5 text-primary"})," Disconnect your Canva account"]}),e.jsxs("ol",{className:"list-decimal pl-6 mt-3 space-y-2",children:[e.jsxs("li",{children:["Open your ",e.jsx("strong",{className:"text-foreground",children:"Integrations"})," page in LevelUp Hub."]}),e.jsxs("li",{children:["On the Canva tile, click ",e.jsx("strong",{className:"text-foreground",children:"Disconnect"})," and confirm."]}),e.jsx("li",{children:"LevelUp tells Canva to revoke its access to your account and removes the saved connection, including the access and refresh tokens, from its records."}),e.jsx("li",{children:"You can reconnect at any time by following the connect steps above. Designs you already imported remain in the LevelUp tools where you saved them; nothing new can be imported until you reconnect."})]}),e.jsxs("p",{className:"mt-3 text-sm",children:[e.jsx(bm,{className:"w-4 h-4 inline mr-1.5 -mt-0.5 text-primary"}),"You can also remove access from the Canva side at any time: in Canva, go to"," ",e.jsx("strong",{className:"text-foreground",children:"Settings → Connected apps"}),", find LevelUp Hub and remove it."]})]}),e.jsxs("section",{children:[e.jsxs("h2",{className:"text-xl font-semibold text-foreground flex items-center gap-2",children:[e.jsx(mn,{className:"w-5 h-5 text-primary"})," Need help?"]}),e.jsxs("p",{className:"mt-3",children:["Contact the LevelUp team at"," ",e.jsx("a",{href:"mailto:hello@relevelup.com",className:"text-primary hover:underline font-medium",children:"hello@relevelup.com"})," ","and we'll help you connect, import or disconnect."]})]}),e.jsx("section",{children:e.jsxs("ul",{className:"list-disc pl-6 space-y-1 text-sm",children:[e.jsx("li",{children:e.jsxs(wr,{to:"/privacy-policy",className:"text-primary hover:underline inline-flex items-center gap-1",children:["Privacy Policy ",e.jsx(kr,{className:"w-3 h-3"})]})}),e.jsx("li",{children:e.jsxs(wr,{to:"/terms-of-service",className:"text-primary hover:underline inline-flex items-center gap-1",children:["Terms of Service ",e.jsx(kr,{className:"w-3 h-3"})]})})]})})]}),e.jsxs("p",{className:"mt-12 text-xs text-muted-foreground flex items-center gap-1.5",children:[e.jsx(qr,{className:"w-3.5 h-3.5"}),"LevelUp Hub · hello@relevelup.com"]})]})})]}),Tvt=()=>e.jsxs(e.Fragment,{children:[e.jsxs(Ml,{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: September 16, 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 (LevelUp Account & Lead Alerts)"}),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, you agree to the following terms:"}),e.jsx("p",{className:"mt-2",children:"You consent to receive recurring SMS/MMS messages from LevelUp, including account notifications, real-time lead alerts, service updates, and customer support communications. Message frequency varies. Message and data rates may apply. Consent is not a condition of purchase."}),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:["No mobile information will be shared with third parties or affiliates for marketing or promotional purposes. Text messaging originator opt-in data and consent will not be shared with any 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. LevelUp SmartSign SMS Terms"}),e.jsxs("p",{children:[e.jsx("strong",{children:"LevelUp SmartSign"})," is operated by ",e.jsx("strong",{children:"LevelUp Consulting Group"}),". Consumers text a property code displayed on a real estate sign to ",e.jsx("strong",{children:"859-413-5013"})," to request information about that property. LevelUp is the sender of these messages; independent real estate agents do not send messages through the SmartSign number. This program is separate from the LevelUp account and lead alert SMS program in section 11."]}),e.jsxs("ul",{className:"list-disc pl-6 mt-3 space-y-1",children:[e.jsxs("li",{children:[e.jsx("strong",{className:"text-foreground",children:"Requested property responses:"})," texting a property code is a request for SMS responses about that property and your inquiry. LevelUp may reply with listing information, answers to your property questions, and help with showing requests."]}),e.jsxs("li",{children:[e.jsx("strong",{className:"text-foreground",children:"Marketing is separate:"})," promotional texts about property updates and similar homes require a separate affirmative opt-in. Requesting property information does not subscribe you to marketing. ",e.jsx("strong",{children:"Consent is not a condition of purchase."})]}),e.jsxs("li",{children:[e.jsx("strong",{className:"text-foreground",children:"Agent contact is separate:"})," before sharing your contact details with a named agent and brokerage, LevelUp asks your permission separately. That permission does not enroll you in LevelUp marketing and does not transfer your LevelUp SMS consent to the agent."]}),e.jsxs("li",{children:[e.jsx("strong",{className:"text-foreground",children:"Message frequency varies."})," Message and data rates may apply."]}),e.jsxs("li",{children:[e.jsx("strong",{className:"text-foreground",children:"Opt out:"})," reply ",e.jsx("strong",{children:"STOP"})," to any message to stop further messages. Reply ",e.jsx("strong",{children:"HELP"})," for help."]}),e.jsxs("li",{children:[e.jsx("strong",{className:"text-foreground",children:"Carrier liability:"})," carriers are not liable for delayed or undelivered messages."]})]}),e.jsxs("p",{className:"mt-3",children:["Support: ",e.jsx("a",{href:"mailto:support@relevelup.com",className:"text-primary hover:underline",children:"support@relevelup.com"}),". How we handle SmartSign information is described in our"," ",e.jsx("a",{href:"/privacy-policy",className:"text-primary hover:underline",children:"Privacy Policy"}),". Program details and example disclosures are on the"," ",e.jsx("a",{href:"/sms-opt-in",className:"text-primary hover:underline",children:"SMS opt-in page"}),"."]})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"13. 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"})]})]})]})]})})]}),d$s=()=>e.jsxs(e.Fragment,{children:[e.jsxs(Ml,{children:[e.jsx("title",{children:"Data Deletion | LevelUp"}),e.jsx("meta",{name:"description",content:"How to request deletion of your LevelUp data, and what is deleted or retained."})]}),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: August 25, 2026"}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"Delete records yourself"}),e.jsx("p",{children:"Most data can be removed directly in the app: contacts, deals, tasks, listings, open houses, landing pages, campaigns and uploaded media can each be deleted from their page. Disconnecting an integration (including the ChatGPT / MCP connector) immediately stops further access."})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"Request account or bulk deletion"}),e.jsxs("p",{children:["Email"," ",e.jsx("a",{href:"mailto:support@relevelup.com",className:"text-primary hover:underline",children:"support@relevelup.com"})," ",'with the subject "Data Deletion Request" and include your full name, the email address on the account and what you want deleted (the whole account, or specific categories such as MCP audit logs or Guest Book sign-ins). We verify the request against the account before acting on it.']})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"What account deletion removes"}),e.jsxs("ul",{className:"list-disc pl-6 mt-2 space-y-1",children:[e.jsx("li",{children:"Account and profile data, branding assets and connected-integration tokens."}),e.jsx("li",{children:"Contacts and their relationship fields, notes, tags and interaction logs."}),e.jsx("li",{children:"Deals, tasks, listings, uploaded media and generated marketing/campaign records."}),e.jsx("li",{children:"Guest Book open houses and the visitor sign-ins captured on them."}),e.jsx("li",{children:"Landing pages, property websites and the leads submitted through them, including FSBO and Listing Revival campaign leads."}),e.jsx("li",{children:"MCP audit log entries for your account."})]}),e.jsx("p",{className:"mt-3",children:"These records are deleted when we process the request. There is no automatic scheduled purge running in the background — deletion happens on account deletion or on a verified request."})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"Category-specific notes"}),e.jsxs("ul",{className:"list-disc pl-6 mt-2 space-y-1",children:[e.jsxs("li",{children:[e.jsx("strong",{className:"text-foreground",children:"MCP audit logs"})," (member id, tool name, truncated tool inputs, outcome, duration, client id) are retained for security and support and are not purged on a timer. They are removed with the account, or earlier on request."]}),e.jsxs("li",{children:[e.jsx("strong",{className:"text-foreground",children:"Campaign leads and Guest Book sign-ins"})," are records about other people that the member controls. A visitor or lead who wants their own record removed should ask the agent they signed in with, or email us and we will route it to that member and remove it."]}),e.jsxs("li",{children:[e.jsx("strong",{className:"text-foreground",children:"Content already shared"})," — for example a listing published to the Listing Exchange and saved by another member, or a page a third party archived — may persist outside our control after deletion."]})]})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"What we retain"}),e.jsxs("ul",{className:"list-disc pl-6 mt-2 space-y-1",children:[e.jsx("li",{children:"Billing and transaction records required for financial and tax reporting."}),e.jsx("li",{children:"Records we must keep to comply with a legal obligation or to resolve a dispute."}),e.jsx("li",{children:"Anonymized or aggregated data that cannot identify you."}),e.jsx("li",{children:"Backup copies, until the backup cycle rotates them out after deletion."})]})]}),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:"You can also revoke our access from Meta directly:"}),e.jsxs("ol",{className:"list-decimal pl-6 mt-2 space-y-1",children:[e.jsx("li",{children:"Open Facebook Settings & Privacy → Settings"}),e.jsx("li",{children:'Click "Apps and Websites"'}),e.jsx("li",{children:'Find LevelUp and click "Remove"'})]})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"Timing"}),e.jsx("p",{children:"We aim to complete verified deletion requests within 30 days and will email you when it is done. If a request needs more time or is partly refused (for example where we must keep billing records), we will tell you why."})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"Related"}),e.jsxs("p",{children:["See the ",e.jsx(wr,{to:"/privacy-policy",className:"text-primary hover:underline",children:"Privacy Policy"})," and the"," ",e.jsx(wr,{to:"/mcp-data-use",className:"text-primary hover:underline",children:"MCP data use"})," page, or contact"," ",e.jsx("a",{href:"mailto:support@relevelup.com",className:"text-primary hover:underline",children:"support@relevelup.com"}),"."]})]})]})]})})]}),Mvt=()=>e.jsxs(e.Fragment,{children:[e.jsxs(Ml,{children:[e.jsx("title",{children:"MCP & ChatGPT Data Use | LevelUp"}),e.jsx("meta",{name:"description",content:"What the LevelUp Hub MCP connector shares with ChatGPT: data categories, purposes, recipients, retention and member controls."}),e.jsx("link",{rel:"canonical",href:"https://dashboard.relevelup.com/mcp-data-use"})]}),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-2",children:"LevelUp Hub MCP — data use"}),e.jsx("p",{className:"text-sm text-muted-foreground mb-8",children:"Last updated: August 25, 2026"}),e.jsxs("div",{className:"prose prose-sm max-w-none text-muted-foreground space-y-6",children:[e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"What this connector is"}),e.jsxs("p",{children:["LevelUp Hub publishes an MCP (Model Context Protocol) server. When a LevelUp member connects it to an AI client such as ChatGPT, that client can call LevelUp tools ",e.jsx("strong",{children:"as that member"}),", using an OAuth sign-in the member completes and can revoke. The connector is optional and off until the member connects it."]})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"Data the tools can reach"}),e.jsxs("ul",{className:"list-disc pl-6 mt-2 space-y-1",children:[e.jsx("li",{children:"Profile and branding: name, email, phone, title, brokerage, license number and state, website, headshot and logo images, brand colors and any brokerage compliance line."}),e.jsx("li",{children:"Contacts (Agent OS / Inner Circle): names, emails, phones, addresses, lead source, notes, and the optional relationship fields a member chooses to store (birthday, home and wedding anniversary, spouse name/email/birthday, company, job title)."}),e.jsx("li",{children:"Deals, tasks and interaction logs: pipeline stage, prices, commissions, key dates, task text, and logged calls, texts, emails, pop-bys and notes."}),e.jsx("li",{children:"Listings and media: the member's listings plus listings other members published to the shared Listing Exchange, with photos, videos and agent/brokerage attribution."}),e.jsx("li",{children:"Guest Book open houses and their visitor sign-ins."}),e.jsx("li",{children:"Landing pages, property websites and the leads submitted through them."}),e.jsx("li",{children:"Marketing and campaign records generated through the tools (email, social, print, FSBO and Listing Revival drafts)."}),e.jsx("li",{children:"MCP audit logs: for every tool call we record the member id, tool name, a truncated snapshot of the tool inputs, the outcome, an error label, the duration and the calling client id."})]})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"Why"}),e.jsxs("ul",{className:"list-disc pl-6 mt-2 space-y-1",children:[e.jsx("li",{children:"To answer the member's own questions about their business and to perform the actions they ask for."}),e.jsx("li",{children:"To draft marketing copy and assets when the member explicitly requests generation."}),e.jsx("li",{children:"To secure the connector: authentication, per-member rate limiting, abuse investigation and support."})]})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"Who receives data"}),e.jsxs("ul",{className:"list-disc pl-6 mt-2 space-y-1",children:[e.jsxs("li",{children:[e.jsx("strong",{children:"LevelUp"})," and its hosting/database provider — where the data already lives."]}),e.jsxs("li",{children:[e.jsx("strong",{children:"The connected AI client (OpenAI / ChatGPT, or another MCP client the member connects)"})," — it receives whatever a called tool returns, and it is governed by that client's own privacy terms."]}),e.jsxs("li",{children:[e.jsx("strong",{children:"The Lovable AI Gateway and the model provider behind it"})," — only when a member requests copy generation, and only the property details and brand/contact block needed for that request. Nothing is sent there for read-only tools."]}),e.jsxs("li",{children:[e.jsx("strong",{children:"The public"})," — only for pages the member publishes (open house sign-in pages, landing pages, property websites). Drafts are not published."]}),e.jsxs("li",{children:[e.jsx("strong",{children:"Other LevelUp members"})," — only for listings a member chose to publish to the Listing Exchange."]}),e.jsxs("li",{children:[e.jsx("strong",{children:"LevelUp administrators"})," — an administrator may act on behalf of a member for support; those calls are recorded in the audit log with the target member."]})]}),e.jsx("p",{className:"mt-3",children:'The connector does not send email, SMS, direct mail or social posts. Tools that "activate" a campaign only change its status inside LevelUp and publish its page; outbound delivery is always a separate, member-initiated action in the app.'})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"Retention"}),e.jsx("p",{children:"Records created or edited through the connector follow the same retention as the rest of the member's LevelUp account: they are kept until the member deletes them or the account is deleted. MCP audit log entries are kept for security and support purposes and are not automatically purged on a fixed schedule; a member or administrator can ask us to remove them. Short-lived rate-limit counters expire on their own within minutes."})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"Member controls"}),e.jsxs("ul",{className:"list-disc pl-6 mt-2 space-y-1",children:[e.jsx("li",{children:"Connect or disconnect the connector at any time from the AI client; revoking access stops all tool calls."}),e.jsx("li",{children:"Actions that publish, activate, merge or delete require an explicit confirmation step; without it the tool returns a preview and changes nothing."}),e.jsx("li",{children:"Open houses, landing pages and property sites are created as unpublished drafts unless the member asks for them to be published."}),e.jsx("li",{children:"Review every call in the member's MCP activity log, and edit or delete the underlying records in the app."}),e.jsxs("li",{children:["Request deletion or export by writing to ",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:"More"}),e.jsxs("p",{children:["See the ",e.jsx(wr,{to:"/privacy-policy",className:"text-primary hover:underline",children:"Privacy Policy"})," and"," ",e.jsx(wr,{to:"/data-deletion",className:"text-primary hover:underline",children:"Data Deletion"})," pages, or contact"," ",e.jsx("a",{href:"mailto:support@relevelup.com",className:"text-primary hover:underline",children:"support@relevelup.com"}),"."]})]})]})]})})]}),Pvt="I agree to receive recurring SMS/MMS messages from LevelUp, including account notifications, real-time lead alerts, service updates, and customer support communications. Message frequency varies. Message and data rates may apply. Reply STOP to opt out and HELP for help. Consent is not a condition of purchase.",u$s="I agree to receive recurring automated promotional texts from LevelUp SmartSign about property updates and similar homes. Consent is not a condition of purchase. Message frequency varies. Message and data rates may apply. Reply STOP to opt out or HELP for help.",h$s=H2({name:vl().trim().max(200).optional().or(yx("")),phone:vl().trim().min(10,"Enter a valid mobile number").max(30).regex(/^[+\d\s()\-.]+$/,"Enter a valid mobile number"),email:vl().trim().email("Enter a valid email").max(320).optional().or(yx(""))}),m$s=H2({name:vl().trim().min(1,"Name is required").max(200),phone:vl().trim().min(10,"Enter a valid mobile number").max(30).regex(/^[+\d\s()\-.]+$/,"Enter a valid mobile number"),email:vl().trim().email("Enter a valid email").max(320).optional().or(yx(""))});function f$s(){const[s,t]=j.useState(""),[n,r]=j.useState(""),[a,i]=j.useState(""),[l,o]=j.useState(!1),[c,d]=j.useState(!1),[u,h]=j.useState(!1),[m,f]=j.useState(!1),g=Qn(),[x,y]=j.useState(""),[v,b]=j.useState(""),[w,S]=j.useState(""),[C,E]=j.useState(!1),[I,P]=j.useState(!1),[R,D]=j.useState(!1),O=async W=>{var X;if(W.preventDefault(),!C){re.error("Please check the marketing consent box to enroll.");return}const V=h$s.safeParse({name:x,phone:v,email:w});if(!V.success){re.error(((X=V.error.issues[0])==null?void 0:X.message)??"Please check your inputs.");return}P(!0);const{data:G,error:Y}=await q.functions.invoke("smartsign-marketing-optin",{body:{name:V.data.name||null,phone:V.data.phone,email:V.data.email||null,consent:!0,source_url:window.location.href}});if(P(!1),Y||!(G!=null&&G.ok)){re.error("We could not record your opt-in. Please try again.");return}D(!0),re.success("Your SmartSign marketing opt-in was recorded.")},U=async W=>{var Y;if(W.preventDefault(),!l){re.error("Please check the consent box to opt in.");return}const V=m$s.safeParse({name:s,phone:n,email:a});if(!V.success){re.error(((Y=V.error.issues[0])==null?void 0:Y.message)??"Please check your inputs.");return}d(!0);const{error:G}=await q.from("sms_opt_in_consents").insert({name:V.data.name,phone:V.data.phone,email:V.data.email||null,consent_text:Pvt,source:"web_form",user_agent:navigator.userAgent.slice(0,500)});if(d(!1),G){re.error("Something went wrong. Please try again.");return}h(!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(Ml,{children:[e.jsx("title",{children:"SMS Opt-In & LevelUp SmartSign | LevelUp"}),e.jsx("meta",{name:"description",content:"LevelUp SmartSign: text a property code to 859-413-5013 for property information. Also opt in to LevelUp account and lead alert texts. Message frequency varies, msg & data rates may apply, reply STOP to opt out or HELP for help."}),e.jsx("link",{rel:"canonical",href:"https://dashboard.relevelup.com/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(eo,{className:"w-7 h-7"})}),e.jsx("h1",{className:"text-3xl md:text-4xl font-bold tracking-tight",children:"LevelUp — SMS Programs"}),e.jsxs("p",{className:"text-muted-foreground mt-3 max-w-xl mx-auto",children:["LevelUp runs two separate text messaging programs. ",e.jsx("strong",{children:"LevelUp SmartSign"})," ","lets home shoppers text a property code from a real estate sign to get information about that property. ",e.jsx("strong",{children:"LevelUp Account & Lead Alerts"})," sends LevelUp members notifications about their own account. Each has its own number and its own consent."]})]}),e.jsxs(Ne,{className:"p-6 md:p-8 mb-8",children:[e.jsxs("div",{className:"flex items-center gap-3 mb-3",children:[e.jsx("div",{className:"inline-flex items-center justify-center w-10 h-10 rounded-xl bg-primary/10 text-primary",children:e.jsx(see,{className:"w-5 h-5"})}),e.jsxs("div",{children:[e.jsx("h2",{className:"text-xl font-semibold leading-tight",children:"LevelUp SmartSign"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Property information by text · Operated by LevelUp Consulting Group"})]})]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"LevelUp SmartSign lets you request information about a home by texting the property code shown on the real estate sign. LevelUp responds with listing information, answers questions about the property, and can help with showing requests. LevelUp is the sender of these messages — independent real estate agents do not send messages through the LevelUp SmartSign number."}),e.jsxs("div",{className:"mt-5 rounded-lg border border-primary/30 bg-primary/5 p-4",children:[e.jsx("p",{className:"text-base font-semibold text-foreground",children:"Text the property code shown on the sign to 859-413-5013 to request information about that property from LevelUp SmartSign."}),e.jsxs("p",{className:"mt-3 text-xs leading-relaxed text-muted-foreground",children:["By texting a property code, you request SMS responses from LevelUp SmartSign about that property and your inquiry. Message frequency varies. Message and data rates may apply. Reply STOP to opt out or HELP for help. Requesting property information does not subscribe you to marketing updates. See our"," ",e.jsx(wr,{to:"/privacy-policy",className:"text-primary underline underline-offset-2",children:"Privacy Policy"})," ","and"," ",e.jsx(wr,{to:"/terms-of-service",className:"text-primary underline underline-offset-2",children:"Terms of Service"}),"."]})]}),e.jsxs("div",{className:"mt-6",children:[e.jsx("p",{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground mb-2",children:"Example sign — illustration only"}),e.jsxs("div",{className:"rounded-xl border-2 border-dashed border-primary/40 bg-background p-5 text-center",children:[e.jsx("p",{className:"text-[11px] font-semibold uppercase tracking-[0.2em] text-primary",children:"LevelUp SmartSign"}),e.jsx("p",{className:"mt-3 text-sm font-medium text-foreground",children:"Text"}),e.jsx("p",{className:"text-3xl font-bold tracking-tight text-foreground",children:"1234"}),e.jsx("p",{className:"text-sm font-medium text-foreground",children:"to"}),e.jsx("p",{className:"text-2xl font-bold tracking-tight text-primary",children:"859-413-5013"}),e.jsx("p",{className:"mt-3 text-[11px] leading-relaxed text-muted-foreground",children:"Msg frequency varies. Msg & data rates may apply. Reply STOP to opt out, HELP for help. Requesting property info does not subscribe you to marketing."})]}),e.jsxs("p",{className:"mt-2 text-xs text-muted-foreground",children:[e.jsx("strong",{children:"1234 is an example property code used for illustration only."})," It is not an active listing and texting it will not return property information. Real property codes appear on the physical sign at the property."]})]}),e.jsxs("div",{className:"mt-8 space-y-4",children:[e.jsx("h3",{className:"text-base font-semibold text-foreground",children:"Three separate choices — each one is its own decision"}),e.jsxs("div",{className:"rounded-lg border bg-muted/30 p-4",children:[e.jsx("p",{className:"text-sm font-semibold text-foreground",children:"1. Property information you requested"}),e.jsx("p",{className:"mt-1.5 text-sm text-muted-foreground",children:"When you text a property code, you are asking LevelUp SmartSign to reply about that property and your inquiry. That is all it does. It does not automatically enroll you in promotional or marketing updates. Reply STOP at any time to stop messages, or HELP for help."})]}),e.jsxs("div",{className:"rounded-lg border bg-muted/30 p-4",children:[e.jsx("p",{className:"text-sm font-semibold text-foreground",children:"2. Optional LevelUp SmartSign marketing updates"}),e.jsx("p",{className:"mt-1.5 text-sm text-muted-foreground",children:"Marketing texts require a separate, affirmative choice that you make on purpose. They are never bundled with a property inquiry and are never combined with permission for an agent to contact you."}),R?e.jsxs("div",{className:"mt-4 rounded-md border border-primary/30 bg-primary/5 p-4",children:[e.jsx("p",{className:"text-sm font-semibold text-foreground",children:"Your marketing opt-in has been recorded."}),e.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:"We saved your number, the exact disclosure you agreed to, and the time of your consent. You can reply STOP to any message to opt out, or HELP for help."})]}):e.jsxs("form",{onSubmit:O,className:"mt-4 space-y-4",children:[e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"mkt-name",children:"Full name (optional)"}),e.jsx(pe,{id:"mkt-name",value:x,onChange:W=>y(W.target.value),maxLength:200,autoComplete:"name",className:"mt-1.5"})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"mkt-phone",children:"Mobile number"}),e.jsx(pe,{id:"mkt-phone",type:"tel",value:v,onChange:W=>b(W.target.value),maxLength:30,placeholder:"(555) 123-4567",autoComplete:"tel",className:"mt-1.5"})]})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"mkt-email",children:"Email (optional)"}),e.jsx(pe,{id:"mkt-email",type:"email",value:w,onChange:W=>S(W.target.value),maxLength:320,autoComplete:"email",className:"mt-1.5"})]}),e.jsx("div",{className:"rounded-md border bg-background p-3",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(ai,{id:"mkt-consent",checked:C,onCheckedChange:W=>E(W===!0),className:"mt-0.5"}),e.jsx(ee,{htmlFor:"mkt-consent",className:"text-xs leading-relaxed font-normal cursor-pointer",children:u$s})]})}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"This box is optional and starts unchecked. Leaving it unchecked changes nothing. This consent is only for LevelUp SmartSign marketing texts — it is not account or lead alerts, and it is not permission for an agent to contact you."}),e.jsx($,{type:"submit",disabled:!C||I,size:"sm",children:I?"Saving…":"Opt in to SmartSign marketing texts"})]})]}),e.jsxs("div",{className:"rounded-lg border bg-muted/30 p-4",children:[e.jsx("p",{className:"text-sm font-semibold text-foreground",children:"3. Permission for an agent to contact you"}),e.jsx("p",{className:"mt-1.5 text-sm text-muted-foreground",children:"Before your contact details are shared with anyone, LevelUp identifies the actual agent and brokerage and asks you separately:"}),e.jsx("p",{className:"mt-2 rounded-md border bg-background p-3 text-xs leading-relaxed text-muted-foreground",children:'"Would you like [Agent Name] at [Brokerage] to contact you about [Property]? If you agree, LevelUp will share your name, phone number, and property inquiry with this agent to respond to your request."'}),e.jsx("p",{className:"mt-2 text-xs text-muted-foreground",children:'Agreeing to an agent contacting you does not enroll you in LevelUp marketing texts and does not transfer your LevelUp SMS consent to that agent. A single checkbox or an ambiguous "YES" is never used for both purposes.'})]})]})]}),e.jsxs("div",{className:"mb-6 rounded-lg border border-primary/30 bg-primary/5 p-4",children:[e.jsx("p",{className:"text-sm font-semibold text-foreground",children:"A separate program: LevelUp Account & Lead Alerts"}),e.jsx("p",{className:"text-sm mt-1 text-muted-foreground",children:"The form below is for LevelUp members (real estate agents) who want account notifications and lead alerts about their own LevelUp account. It is a different program from LevelUp SmartSign, uses a different number, and consent to one is never consent to the other. SMS notifications are optional — you may use LevelUp without providing a mobile number or consenting to text messages."})]}),m?e.jsxs(Ne,{className:"p-8 text-center",children:[e.jsx(qr,{className:"w-14 h-14 text-primary mx-auto mb-4"}),e.jsx("h2",{className:"text-2xl font-semibold mb-2",children:"No text messages — you're all set"}),e.jsx("p",{className:"text-muted-foreground",children:"You declined SMS notifications. No mobile number or consent was recorded, and you can continue using LevelUp normally."}),e.jsx($,{className:"mt-6",onClick:()=>g("/auth"),children:"Continue to LevelUp"})]}):u?e.jsxs(Ne,{className:"p-8 text-center",children:[e.jsx(qr,{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:["You'll now receive SMS account notifications and real-time lead alerts from LevelUp. Reply ",e.jsx("strong",{children:"STOP"})," at any time to opt out, or ",e.jsx("strong",{children:"HELP"})," for assistance."]})]}):e.jsx(Ne,{className:"p-6 md:p-8",children:e.jsxs("form",{onSubmit:U,className:"space-y-5",children:[e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"name",children:"Full Name (only if you opt in to SMS)"}),e.jsx(pe,{id:"name",value:s,onChange:W=>t(W.target.value),maxLength:200,autoComplete:"name",className:"mt-1.5"})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"phone",children:"Mobile Number (only if you opt in to SMS)"}),e.jsx(pe,{id:"phone",type:"tel",value:n,onChange:W=>r(W.target.value),maxLength:30,placeholder:"(555) 123-4567",autoComplete:"tel",className:"mt-1.5"})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"email",children:"Email (optional)"}),e.jsx(pe,{id:"email",type:"email",value:a,onChange:W=>i(W.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(ai,{id:"consent",checked:l,onCheckedChange:W=>o(W===!0),className:"mt-0.5"}),e.jsx(ee,{htmlFor:"consent",className:"text-sm leading-relaxed font-normal cursor-pointer",children:Pvt})]})}),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(wr,{to:"/terms-of-service",className:"text-primary underline underline-offset-2",children:"SMS Terms & Conditions"})," ","and"," ",e.jsx(wr,{to:"/privacy-policy",className:"text-primary underline underline-offset-2",children:"Privacy Policy"}),"."]}),e.jsxs("p",{children:[e.jsx("strong",{children:"Message types:"})," account notifications, real-time lead alerts, 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:"No mobile information will be shared with third parties or affiliates for marketing or promotional purposes. Text messaging originator opt-in data and consent will not be shared with any third parties."})]}),e.jsx($,{type:"submit",disabled:!l||c,className:"w-full",size:"lg",children:c?"Submitting…":"Opt in to SMS"}),e.jsx($,{type:"button",variant:"outline",size:"lg",className:"w-full",disabled:c,onClick:()=>f(!0),children:"Skip SMS / Continue without text alerts"}),e.jsx("p",{className:"text-xs text-center text-muted-foreground",children:"Skipping records no consent and does not limit your access to LevelUp."}),e.jsxs("div",{className:"flex items-center justify-center gap-2 text-xs text-muted-foreground pt-2",children:[e.jsx(bm,{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 · Questions? Email"," ",e.jsx("a",{href:"mailto:support@relevelup.com",className:"text-primary hover:underline",children:"support@relevelup.com"})]})})]})]})}const c6e="/assets/levelup-logo-horizontal-DEFNc0ms.png",p$s=H2({email:vl().email("Invalid email address"),password:vl().min(6,"Password must be at least 6 characters")}),f$t="https://dashboard.relevelup.com",Kce="/oauth-connect",g$s=`${f$t}/profile?reset=true`,c3e="levelupOAuthRouteHistory";function Ivt(s){return s.startsWith("/")&&!s.startsWith("//")&&!s.includes("://")}function x$s(s){const t=Date.now(),n=15e3;try{const i=[...JSON.parse(sessionStorage.getItem(c3e)??"[]").filter(o=>t-o.ato.route));return i.length>=6&&l.has("auth")&&l.has("consent")}catch{return sessionStorage.setItem(c3e,JSON.stringify([{route:s,at:t}])),!1}}function y$s(){sessionStorage.removeItem(c3e)}const v$s=()=>{const{signIn:s,user:t,loading:n}=vs(),r=(t==null?void 0:t.id)??null,a=Qn(),[i]=gc(),l=i.get("authorization_id")??"",o=i.get("next")??"",[c,d]=j.useState(!1),[u,h]=j.useState({}),[m,f]=j.useState(""),[g,x]=j.useState(!1),[y,v]=j.useState(!1),[b,w]=j.useState(null),[S,C]=j.useState(null),[E,I]=j.useState(!1),[P,R]=j.useState(!1),[D,O]=j.useState(()=>{if(i.get("paused")!=="1")return null;let Y="";try{Y=sessionStorage.getItem("accountPausedReason")||""}catch{}return Y?`Your account is paused. ${Y}`:"Your account is paused. Please contact LevelUp support to reactivate it."}),U=j.useRef(!1);j.useEffect(()=>{if(l&&window.location.hostname==="tile-portal.lovable.app"){const Y=new URL("/auth",f$t);Y.searchParams.set("next",`${Kce}?authorization_id=${encodeURIComponent(l)}`),window.location.replace(Y.toString());return}if(l){const Y=`${Kce}?authorization_id=${encodeURIComponent(l)}`;sessionStorage.setItem("redirectAfterLogin",Y);return}o&&Ivt(o)&&sessionStorage.setItem("redirectAfterLogin",o)},[l,o]),j.useEffect(()=>{if(n||!r||U.current)return;const Y=l?`${Kce}?authorization_id=${encodeURIComponent(l)}`:sessionStorage.getItem("redirectAfterLogin")||"/dashboard";if(!Ivt(Y)){sessionStorage.removeItem("redirectAfterLogin"),U.current=!0,a("/dashboard",{replace:!0});return}const X=Y.startsWith(Kce)||Y.startsWith("/oauth/consent")||Y.startsWith("/.lovable/oauth/consent");if(X&&x$s("auth")){w("We couldn't complete the OAuth sign-in handoff because the browser kept bouncing between sign-in and consent. Please refresh this page and try Connect again.");return}U.current=!0,X||(y$s(),sessionStorage.removeItem("redirectAfterLogin")),a(Y,{replace:!0})},[l,n,a,r]);const W=async Y=>{Y.preventDefault(),h({}),O(null),C(null),I(!1),d(!0);const X=new FormData(Y.currentTarget),ae=X.get("email"),ie=X.get("password");try{p$s.parse({email:ae,password:ie}),await s(ae,ie)}catch(ne){if(ne instanceof iTs){const te={};ne.issues.forEach(J=>{J.path[0]&&(te[J.path[0]]=J.message)}),h(te)}else if(ne instanceof Error&&ne.name==="AccountPaused")O(ne.message);else if(ae)try{const{data:te}=await q.functions.invoke("account-activation-status",{body:{email:ae}});te!=null&&te.needsActivation&&C(ae)}catch{}}finally{d(!1)}},V=async()=>{if(S){R(!0);try{const{data:Y,error:X}=await q.functions.invoke("send-password-reset",{body:{email:S,variant:"activation"}});if(X)throw X;if((Y==null?void 0:Y.sent)===!1)throw new Error("We couldn't send the activation email. Please try again in a moment or contact support.");I(!0),re.success("Activation email sent! Check your inbox.")}catch(Y){re.error(Y instanceof Error?Y.message:"Failed to send activation email")}finally{R(!1)}}},G=async()=>{if(!m){re.error("Please enter your email address");return}x(!0);try{const{data:Y,error:X}=await q.functions.invoke("send-password-reset",{body:{email:m.trim().toLowerCase(),redirectTo:g$s}});if(X)throw X;if((Y==null?void 0:Y.sent)===!1){re.error("We couldn't find a LevelUp account for that email. Double-check the address, or email hello@relevelup.com and we'll help.");return}re.success("Password reset email sent! Check your inbox."),v(!1),f("")}catch(Y){re.error(Y instanceof Error?Y.message:"Failed to send reset email")}finally{x(!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(wr,{to:"/",className:"inline-flex items-center gap-2 text-sm text-white/80 hover:text-white transition-colors",children:[e.jsx(qa,{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:c6e,alt:"LevelUp",className:"h-12 w-auto"})})}),e.jsxs(Ne,{className:"border-0 shadow-2xl bg-white/95 backdrop-blur-sm",children:[e.jsxs(Ct,{className:"space-y-1 text-center pb-4",children:[e.jsx(At,{className:"text-3xl font-bold text-[#2a4347]",style:{fontFamily:"'Libre Baskerville', serif"},children:"Welcome Back"}),e.jsx(Gn,{className:"text-gray-600",children:b||"Sign in to access your dashboard"})]}),e.jsxs(Ie,{children:[D&&e.jsxs("div",{className:"mb-4 rounded-lg border border-amber-300 bg-amber-50 p-4 text-left",children:[e.jsx("p",{className:"text-sm font-semibold text-amber-900",children:"Account paused"}),e.jsx("p",{className:"mt-1 text-sm text-amber-800",children:D}),e.jsx("a",{href:"mailto:support@relevelup.com",className:"mt-2 inline-block text-sm font-medium text-amber-900 underline",children:"Contact support"})]}),S&&e.jsxs("div",{className:"mb-4 rounded-lg border border-[#4a6b6d]/30 bg-[#f2f7f7] p-4 text-left",children:[e.jsx("p",{className:"text-sm font-semibold text-[#2a4347]",children:"You haven't set a password yet"}),e.jsx("p",{className:"mt-1 text-sm text-gray-700",children:E?`We just emailed ${S} a link to set your password and sign in. Check your inbox (and spam folder).`:`Your LevelUp account for ${S} is ready — it just needs a password. We'll email you a link to set one.`}),!E&&e.jsx($,{type:"button",onClick:V,disabled:P,className:"mt-3 bg-[#4a6b6d] hover:bg-[#3d5a5c] text-white",children:P?"Sending...":"Email me a set-password link"})]}),e.jsxs("form",{onSubmit:W,className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"signin-email",className:"text-gray-700",children:"Email"}),e.jsx(pe,{id:"signin-email",name:"email",type:"email",placeholder:"your@email.com",required:!0,className:"border-gray-300 focus:border-[#4a6b6d] focus:ring-[#4a6b6d]"}),u.email&&e.jsx("p",{className:"text-sm text-red-600",children:u.email})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"signin-password",className:"text-gray-700",children:"Password"}),e.jsx(pe,{id:"signin-password",name:"password",type:"password",required:!0,className:"border-gray-300 focus:border-[#4a6b6d] focus:ring-[#4a6b6d]"}),u.password&&e.jsx("p",{className:"text-sm text-red-600",children:u.password})]}),e.jsx($,{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:c,children:c?"Signing in...":"Sign In"}),e.jsxs(zs,{open:y,onOpenChange:v,children:[e.jsx(jl,{asChild:!0,children:e.jsx($,{variant:"link",className:"w-full text-sm text-[#4a6b6d] hover:text-[#3d5a5c]",children:"Forgot password?"})}),e.jsxs(Os,{className:"bg-white",children:[e.jsxs(Us,{children:[e.jsx(Bs,{className:"text-[#2a4347]",style:{fontFamily:"'Libre Baskerville', serif"},children:"Reset Password"}),e.jsx(Ir,{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(ee,{htmlFor:"reset-email",className:"text-gray-700",children:"Email"}),e.jsx(pe,{id:"reset-email",type:"email",placeholder:"your@email.com",value:m,onChange:Y=>f(Y.target.value),className:"border-gray-300 focus:border-[#4a6b6d] focus:ring-[#4a6b6d]"})]}),e.jsx($,{onClick:G,className:"w-full bg-[#4a6b6d] hover:bg-[#3d5a5c] text-white",disabled:g,children:g?"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(wr,{to:"/",className:"text-white hover:underline font-medium",children:"View Plans"})]})]})})]})]})},Lvt=()=>q.auth.oauth,b$s="https://dashboard.relevelup.com",_$s="/oauth-connect",d3e="levelupOAuthRouteHistory",w$s="https://relzejiswnotikjgvjhz.supabase.co/auth/v1",j$s="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InJlbHplamlzd25vdGlramd2amh6Iiwicm9sZSI6ImFub24iLCJpYXQiOjE3NjE5NTAzNDQsImV4cCI6MjA3NzUyNjM0NH0.dzIkIr_oFSbFE3oWS0ktIr83iKHHkZxt40Gc7SpC_mM";function N$s(s){return s.startsWith("/")&&!s.startsWith("//")&&!s.includes("://")}function k$s(s){const t=Date.now(),n=15e3;try{const i=[...JSON.parse(sessionStorage.getItem(d3e)??"[]").filter(o=>t-o.ato.route));return i.length>=6&&l.has("auth")&&l.has("consent")}catch{return sessionStorage.setItem(d3e,JSON.stringify([{route:s,at:t}])),!1}}function S$s(){sessionStorage.removeItem(d3e)}async function Rvt(s,t,n){const r=await fetch(`${w$s}${s}`,{...n,headers:{Authorization:`Bearer ${t}`,apikey:j$s,"Content-Type":"application/json",...(n==null?void 0:n.headers)??{}}}),a=await r.json().catch(()=>null);return r.ok?{data:a,error:null}:{data:null,error:{message:(a==null?void 0:a.msg)??(a==null?void 0:a.message)??(a==null?void 0:a.error_description)??(a==null?void 0:a.error)??"Authorization request failed."}}}function O7e(){var x;const{user:s,session:t,loading:n}=vs(),r=(s==null?void 0:s.id)??null,a=(t==null?void 0:t.access_token)??null,[i]=gc(),l=i.get("authorization_id")??"",[o,c]=j.useState(null),[d,u]=j.useState(null),[h,m]=j.useState(!1);j.useEffect(()=>{let y=!0;return(async()=>{if(!l){u("Missing authorization_id");return}const v=`${_$s}?authorization_id=${encodeURIComponent(l)}`;if(window.location.hostname==="tile-portal.lovable.app"){window.location.href=`${b$s}${v}`;return}if(n)return;if(!r){if(k$s("consent")){u("We couldn't complete the OAuth sign-in handoff because the browser kept bouncing between sign-in and consent. Please refresh this page and try Connect again.");return}N$s(v)&&sessionStorage.setItem("redirectAfterLogin",v),window.location.replace(`/auth?next=${encodeURIComponent(v)}`);return}if(!a)return;S$s(),sessionStorage.removeItem("redirectAfterLogin");const b=Lvt(),{data:w,error:S}=b?await b.getAuthorizationDetails(l):await Rvt(`/oauth/authorizations/${encodeURIComponent(l)}`,a);if(!y)return;if(S){u(S.message);return}const C=(w==null?void 0:w.redirect_url)??(w==null?void 0:w.redirect_to);if(C&&!(w!=null&&w.client)){window.location.href=C;return}c(w)})(),()=>{y=!1}},[a,l,n,r]);async function f(y){if(!(t!=null&&t.access_token)){u("Your sign-in session is not ready yet. Please refresh and try again.");return}m(!0);const v=Lvt(),{data:b,error:w}=v?y?await v.approveAuthorization(l,{skipBrowserRedirect:!0}):await v.denyAuthorization(l,{skipBrowserRedirect:!0}):await Rvt(`/oauth/authorizations/${encodeURIComponent(l)}/consent`,t.access_token,{method:"POST",body:JSON.stringify({action:y?"approve":"deny"})});if(w){m(!1),u(w.message);return}const S=(b==null?void 0:b.redirect_url)??(b==null?void 0:b.redirect_to);if(!S){m(!1),u("No redirect returned by the authorization server.");return}window.location.href=S}if(d)return e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-background p-4",children:e.jsx(Ne,{className:"w-full max-w-md",children:e.jsxs(Ct,{children:[e.jsx(At,{children:"Authorization error"}),e.jsx(Gn,{children:d})]})})});if(!o)return e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-background",children:e.jsx(kt,{className:"h-8 w-8 animate-spin text-primary"})});const g=((x=o.client)==null?void 0:x.name)??"An app";return e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-background p-4",children:e.jsxs(Ne,{className:"w-full max-w-md",children:[e.jsxs(Ct,{children:[e.jsxs(At,{children:["Connect ",g," to LevelUp"]}),e.jsxs(Gn,{children:[g," is requesting access to use LevelUp tools on your behalf. You can revoke access at any time."]})]}),e.jsxs(Ie,{className:"flex gap-3 justify-end",children:[e.jsx($,{variant:"outline",disabled:h,onClick:()=>f(!1),children:"Deny"}),e.jsx($,{disabled:h,onClick:()=>f(!0),children:h?e.jsx(kt,{className:"h-4 w-4 animate-spin"}):"Approve"})]})]})})}const C$s="https://chatgpt.com/plugins/plugin_asdk_app_6a7b9baf757081918ac4ab6fcbdb2639?q=levelup",Dvt="https://relzejiswnotikjgvjhz.supabase.co/functions/v1/mcp",A$s="https://tile-portal.lovable.app/mcp-oauth-bridge.html",E$s=[{label:"Open the ChatGPT Store",description:"Use the button below to open the LevelUp plugin page in the ChatGPT Store."},{label:"Install the plugin",description:"Tap Install. ChatGPT Plus, Pro, or Team is required to use plugins."},{label:"Sign in to LevelUp",description:"ChatGPT will open a LevelUp consent page. Sign in with your LevelUp account and tap Approve."},{label:"Start chatting",description:"Ask ChatGPT to 'list my upcoming LevelUp trainings' or 'summarize my contacts'."}],T$s=[{label:"Open ChatGPT",description:"You need ChatGPT Plus, Pro, or Team to add custom MCP connectors."},{label:"Add a new connector",description:"Settings → Connectors → Add. Choose 'Custom / MCP Server'."},{label:"Fill in the basics",description:"Name it LevelUp and add a short description like 'Tools for the LevelUp real estate platform.'"},{label:"Paste the server URL",description:"Paste the MCP server URL below into the Server URL field. Do not paste the tile-portal bridge URL."},{label:"Confirm OAuth",description:"Authentication should be OAuth. Check the 'I understand' box, then tap Create."},{label:"Sign in to LevelUp",description:"ChatGPT will open a LevelUp consent page. Sign in with your LevelUp account and tap Approve."},{label:"Start chatting",description:"Ask ChatGPT to 'list my upcoming LevelUp trainings' or 'summarize my contacts'."}];function M$s(){const[s,t]=j.useState(!1),n=async()=>{try{await navigator.clipboard.writeText(Dvt),t(!0),re.success("MCP URL copied to clipboard"),setTimeout(()=>t(!1),2e3)}catch{re.error("Could not copy URL")}};return e.jsx(Vs,{children:e.jsxs("div",{className:"space-y-6 p-4 md:p-8 max-w-3xl mx-auto",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-3 rounded-lg bg-primary/10",children:e.jsx(M4,{className:"h-6 w-6 text-primary"})}),e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold tracking-tight",children:"Connect ChatGPT to LevelUp"}),e.jsx("p",{className:"text-muted-foreground",children:"Install the official LevelUp plugin from the ChatGPT Store."})]})]}),e.jsxs(Ne,{className:"border-primary/20 bg-primary/5",children:[e.jsxs(Ct,{children:[e.jsxs(At,{className:"flex items-center gap-2",children:[e.jsx(Nn,{className:"h-5 w-5 text-primary"}),"Install from the ChatGPT Store"]}),e.jsx(Gn,{children:"The easiest way to connect. Tap the button below, then install the LevelUp plugin in ChatGPT."})]}),e.jsx(Ie,{children:e.jsx($,{asChild:!0,size:"lg",className:"w-full sm:w-auto",children:e.jsxs("a",{href:C$s,target:"_blank",rel:"noopener noreferrer",children:[e.jsx(kr,{className:"h-4 w-4 mr-2"}),"Open LevelUp in the ChatGPT Store"]})})})]}),e.jsxs(Ne,{children:[e.jsxs(Ct,{children:[e.jsx(At,{children:"Quick steps"}),e.jsx(Gn,{children:"Share these steps with any agent who wants to connect via the plugin store."})]}),e.jsx(Ie,{children:e.jsx("ol",{className:"space-y-4",children:E$s.map((r,a)=>e.jsxs("li",{className:"flex gap-3",children:[e.jsx("span",{className:"flex h-6 w-6 shrink-0 items-center justify-center rounded-full bg-primary/10 text-xs font-medium text-primary",children:a+1}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:r.label}),e.jsx("p",{className:"text-sm text-muted-foreground",children:r.description})]})]},a))})})]}),e.jsxs(Ne,{children:[e.jsxs(Ct,{children:[e.jsx(At,{children:"Manual MCP setup"}),e.jsx(Gn,{children:"Only use this if you are adding LevelUp as a custom MCP server instead of installing the store plugin."})]}),e.jsxs(Ie,{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("code",{className:"flex-1 block rounded-md bg-muted px-3 py-2 text-sm break-all",children:Dvt}),e.jsx($,{variant:"outline",size:"icon",onClick:n,"aria-label":"Copy MCP URL",children:s?e.jsx(Nc,{className:"h-4 w-4 text-green-600"}):e.jsx(Ha,{className:"h-4 w-4"})})]}),e.jsx("div",{className:"rounded-lg border border-destructive/30 bg-destructive/5 p-4 text-sm",children:e.jsxs("div",{className:"flex gap-3",children:[e.jsx(wl,{className:"h-5 w-5 text-destructive shrink-0 mt-0.5"}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"font-semibold text-destructive",children:"Do not use the bridge URL as the Server URL."}),e.jsx("p",{className:"text-muted-foreground",children:"If ChatGPT shows “does not implement OAuth,” it means this wrong URL was pasted:"}),e.jsx("code",{className:"block rounded-md bg-background px-3 py-2 break-all text-xs",children:A$s}),e.jsx("p",{className:"text-muted-foreground",children:"Delete that plugin attempt and create a new one with the MCP server URL above."})]})]})}),e.jsx("ol",{className:"space-y-4",children:T$s.map((r,a)=>e.jsxs("li",{className:"flex gap-3",children:[e.jsx("span",{className:"flex h-6 w-6 shrink-0 items-center justify-center rounded-full bg-primary/10 text-xs font-medium text-primary",children:a+1}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:r.label}),e.jsx("p",{className:"text-sm text-muted-foreground",children:r.description})]})]},a))})]})]}),e.jsxs(Ne,{children:[e.jsxs(Ct,{children:[e.jsx(At,{children:"What ChatGPT can see"}),e.jsx(Gn,{children:"The connector acts as you. Before connecting, review exactly which data it can reach, who receives it, how long it is kept and how to disconnect."})]}),e.jsxs(Ie,{className:"flex flex-wrap gap-4 text-sm",children:[e.jsx("a",{href:"/mcp-data-use",className:"text-primary underline underline-offset-4",children:"MCP data use"}),e.jsx("a",{href:"/privacy-policy",className:"text-primary underline underline-offset-4",children:"Privacy Policy"}),e.jsx("a",{href:"/data-deletion",className:"text-primary underline underline-offset-4",children:"Data deletion"})]})]}),e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(kr,{className:"h-4 w-4"}),e.jsx("span",{children:"Publishing, activating, merging and deleting always ask you to confirm first, and new open houses and pages start as unpublished drafts."})]})]})})}const P$s=()=>{const[s]=gc(),t=s.get("tier"),n=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(Ne,{className:"max-w-lg w-full",children:[e.jsxs(Ct,{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(Nc,{className:"w-10 h-10 text-green-500"})}),e.jsx(At,{className:"text-2xl",children:"Welcome to LevelUp!"}),e.jsx(Gn,{className:"text-lg",children:"Your subscription has been activated successfully."})]}),e.jsxs(Ie,{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(mn,{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."})]}),n?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."})})]})]})})},I$s=()=>{const{user:s}=vs(),[t,n]=j.useState(!1),[r,a]=j.useState(null),[i,l]=j.useState(""),o=async u=>{var h;if(!(s!=null&&s.email)){re.error("Please sign in to upgrade");return}n(!0),a(u);try{const{data:m,error:f}=await q.functions.invoke("create-checkout",{body:{tier:u,email:s.email,name:((h=s.user_metadata)==null?void 0:h.full_name)||s.email,userId:s.id,couponCode:i.trim()||void 0,skipTrial:!0}});if(f)throw f;if(m!=null&&m.url)window.open(m.url,"_blank","noopener,noreferrer"),re.success("Checkout opened in a new tab");else throw new Error("No checkout URL returned")}catch(m){console.error("Checkout error:",m),re.error(m.message||"Failed to start checkout. Please try again.")}finally{n(!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, plus:","Unlimited agent seats","Brokerage admin dashboard","Team performance analytics","Custom branding options","Priority support","Agent onboarding tools","Brokerage-wide announcements"];return e.jsx(Vs,{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(ee,{htmlFor:"coupon",className:"text-sm font-medium",children:"Have a discount code?"}),e.jsx(pe,{id:"coupon",placeholder:"Enter discount code",value:i,onChange:u=>l(u.target.value),className:"mt-1"})]}),e.jsxs("div",{className:"grid md:grid-cols-2 gap-6 mb-8 max-w-4xl mx-auto",children:[e.jsxs(Ne,{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(Ct,{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(Zn,{className:"h-7 w-7 text-primary"})}),e.jsx(At,{className:"text-xl",children:"Individual Agent"}),e.jsx(Gn,{children:"Perfect for solo agents ready to level up"})]}),e.jsxs(Ie,{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((u,h)=>e.jsxs("li",{className:"flex items-start gap-2 text-sm",children:[e.jsx(la,{className:"h-4 w-4 text-primary mt-0.5 shrink-0"}),e.jsx("span",{children:u})]},h))}),e.jsxs($,{className:"w-full",size:"lg",onClick:()=>o("individual_agent"),disabled:t,children:[t&&r==="individual_agent"?e.jsx(kt,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Nn,{className:"h-4 w-4 mr-2"}),"Get Started"]})]})]}),e.jsxs(Ne,{className:"border-2 border-purple-500/20 hover:border-purple-500/50 transition-colors",children:[e.jsxs(Ct,{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(ji,{className:"h-7 w-7 text-purple-600"})}),e.jsx(At,{className:"text-xl",children:"Brokerage"}),e.jsx(Gn,{children:"Unlimited agents — everything in Individual, plus brokerage tools"})]}),e.jsxs(Ie,{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:d.map((u,h)=>e.jsxs("li",{className:"flex items-start gap-2 text-sm",children:[e.jsx(la,{className:"h-4 w-4 text-purple-600 mt-0.5 shrink-0"}),e.jsx("span",{children:u})]},h))}),e.jsxs($,{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&&r==="brokerage_over_25"?e.jsx(kt,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(ji,{className:"h-4 w-4 mr-2"}),"Get Started"]})]})]})]}),e.jsx(Ne,{className:"bg-muted/50",children:e.jsxs(Ie,{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(Da,{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(mn,{className:"h-4 w-4"}),e.jsx("span",{children:"support@relevelup.com"})]})]})]})})]})})},L$s=()=>{const{user:s,loading:t,isBrokerageManager:n,brokerageId:r}=vs(),a=Qn(),[i,l]=j.useState(""),[o,c]=j.useState(!1),[d,u]=j.useState(!1);j.useEffect(()=>{!t&&!s&&a("/auth")},[s,t,a]),j.useEffect(()=>{!t&&s&&r&&a("/profile?setup=true")},[s,t,r,a]);const h=async()=>{if(!i.trim()){re.error("Please enter a brokerage name");return}const{data:m}=await q.auth.getSession(),f=m.session;if(!s||!f){re.error("Please sign in again to create your brokerage."),a("/auth");return}c(!0);try{console.log("[SetupBrokerage] Creating brokerage…",{hasUser:!!s,hasSession:!!f,userId:s==null?void 0:s.id});const{data:g,error:x}=await q.functions.invoke("create-brokerage",{body:{name:i.trim()}});if(console.log("[SetupBrokerage] create-brokerage response",{data:g,error:x}),x)throw x;if(!(g!=null&&g.ok))throw new Error((g==null?void 0:g.error)||"Failed to create brokerage");c(!1),u(!0),re.success("Brokerage created! Setting up your account..."),setTimeout(()=>{a("/profile?setup=true")},2e3)}catch(g){console.error("Error creating brokerage:",g),re.error(g.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(Ne,{className:"max-w-lg w-full",children:[e.jsxs(Ct,{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(kt,{className:"w-10 h-10 text-primary animate-spin"})}),e.jsx(At,{className:"text-2xl",children:"Setting Up Your Brokerage"}),e.jsx(Gn,{className:"text-lg",children:"We're assigning you as the brokerage manager and preparing your dashboard..."})]}),e.jsxs(Ie,{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-center gap-2 text-muted-foreground",children:[e.jsx(Nc,{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(kt,{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(Ne,{className:"max-w-lg w-full",children:[e.jsxs(Ct,{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(ji,{className:"w-10 h-10 text-primary"})}),e.jsx(At,{className:"text-2xl",children:"Set Up Your Brokerage"}),e.jsx(Gn,{className:"text-lg",children:"Create your brokerage to start managing your team"})]}),e.jsxs(Ie,{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"brokerage-name",children:"Brokerage Name"}),e.jsx(pe,{id:"brokerage-name",placeholder:"Enter your brokerage name",value:i,onChange:m=>l(m.target.value),onKeyDown:m=>m.key==="Enter"&&h()}),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(Zn,{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(Nc,{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(Nc,{className:"w-4 h-4 text-green-500"}),"Access exclusive brokerage resources"]}),e.jsxs("li",{className:"flex items-center gap-2",children:[e.jsx(Nc,{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(Nc,{className:"w-4 h-4 text-green-500"}),"Share resources with your agents"]})]})]}),e.jsxs($,{onClick:h,className:"w-full",disabled:o||!i.trim(),children:[o?"Creating...":"Create Brokerage",e.jsx(ei,{className:"w-4 h-4 ml-2"})]})]})]})})},Fvt=()=>{const s=Qn(),[t,n]=j.useState("verifying"),[r,a]=j.useState("");j.useEffect(()=>{(async()=>{try{const{data:{session:o},error:c}=await q.auth.getSession();if(c)throw c;if(o!=null&&o.user){const{data:d}=await q.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"),n("already_claimed");return}console.log("User logged in successfully:",o.user.email),n("success");try{await q.functions.invoke("trial-claim-hook",{body:{userId:o.user.id}})}catch(u){console.log("Trial claim hook (non-critical):",u)}setTimeout(()=>{s("/profile?setup=true")},1500)}else setTimeout(()=>{n("already_claimed")},2e3)}catch(o){console.error("Claim error:",o),n("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(Ne,{className:"w-full max-w-md",children:[e.jsxs(Ct,{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(At,{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(Gn,{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"&&r]})]}),(t==="already_claimed"||t==="error")&&e.jsx(Ie,{children:e.jsx($,{onClick:i,className:"w-full",children:"Go to Login"})})]})})},Yce="https://dashboard.relevelup.com",Ovt=()=>{const[s,t]=j.useState(!1),n=j.useMemo(()=>new URLSearchParams(window.location.search),[]),r=j.useMemo(()=>n.get("link"),[n]),a=j.useMemo(()=>n.get("type")||"recovery",[n]),i=j.useMemo(()=>{switch(a){case"claim":return{title:"Claim Your Account",cta:"Continue to Claim Account",doc:"Claim Your LevelUp Account"};case"magiclink":return{title:"Sign In to LevelUp",cta:"Continue to Sign In",doc:"Sign In to LevelUp"};case"email_change":return{title:"Confirm Your Email",cta:"Continue to Confirm Email",doc:"Confirm Your Email"};default:return{title:"Reset Your Password",cta:"Continue to Reset Password",doc:"Reset Your Password"}}},[a]),l=j.useMemo(()=>{if(!r)return!1;try{const g=new URL(r);return g.hostname.endsWith(".supabase.co")&&g.pathname.startsWith("/auth/v1/verify")}catch{return!1}},[r]);j.useEffect(()=>{document.title=i.doc},[i]);const[o,c]=j.useState(null),[d,u]=j.useState("idle"),h=j.useMemo(()=>{if(!r)return null;try{return new URL(r).searchParams.get("email")}catch{return null}},[r]),m=async()=>{var g;u("sending");try{const x=h||((g=window.prompt("Enter the email address on your LevelUp account:"))==null?void 0:g.trim());if(!x){u("idle");return}const{error:y}=await q.functions.invoke("send-password-reset",{body:{email:x,variant:a==="recovery"?"reset":"activation"}});u(y?"failed":"sent")}catch{u("failed")}},f=async()=>{if(!(!l||!r)){if(t(!0),c(null),window.location.origin!==Yce&&window.location.hostname!=="localhost"){window.location.href=`${Yce}${window.location.pathname}${window.location.search}`;return}try{const g=new URL(r),x=g.searchParams.get("token")||g.searchParams.get("token_hash"),y=g.searchParams.get("type")||(a==="claim"?"invite":a);if(x){const{error:v}=await q.auth.verifyOtp({token_hash:x,type:y});if(!v){const b=g.searchParams.get("redirect_to");let w=y==="recovery"?"/profile?reset=true":"/dashboard";if(b)try{const S=new URL(b);w=`${S.pathname}${S.search}`}catch{}window.location.replace(`${Yce}${w}`);return}t(!1),c("This link is invalid or has already been used. Please request a new email.");return}}catch{}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:c6e,alt:"LevelUp",className:"h-12 w-auto"})})}),e.jsxs(Ne,{className:"border-0 shadow-2xl bg-white/95 backdrop-blur-sm",children:[e.jsxs(Ct,{className:"text-center",children:[e.jsx(At,{className:"text-2xl font-bold text-[#2a4347]",style:{fontFamily:"'Libre Baskerville', serif"},children:i.title}),e.jsx(Gn,{className:"text-gray-600 pt-2",children:o||(l?"Click the button below to continue securely.":"This link is invalid or has expired. Please request a new email from the sign-in page.")})]}),e.jsxs(Ie,{className:"space-y-4",children:[l&&!o?e.jsx($,{onClick:f,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…":i.cta}):d==="sent"?e.jsx("div",{className:"rounded-lg bg-emerald-50 border border-emerald-200 p-4 text-center text-sm text-emerald-800",children:"A fresh link is on its way — check your inbox in the next minute or two."}):e.jsxs(e.Fragment,{children:[e.jsx($,{onClick:m,disabled:d==="sending",className:"w-full bg-[#4a6b6d] hover:bg-[#3d5a5c] text-white font-semibold py-6 text-lg shadow-lg hover:shadow-xl",children:d==="sending"?"Sending…":"Email me a fresh link"}),d==="failed"&&e.jsx("p",{className:"text-xs text-center text-red-600",children:"We couldn't send that just now. Please try again in a moment."}),e.jsx($,{variant:"outline",onClick:()=>window.location.href=`${Yce}/auth`,className:"w-full py-6 text-base",children:"Go to Sign In"})]}),e.jsx("p",{className:"text-xs text-center text-gray-500 pt-2",children:"For your security, these links expire and can only be used once."})]})]})]})})]})},Zce="https://dashboard.relevelup.com",R$s=()=>{const s=j.useMemo(()=>new URLSearchParams(window.location.search).get("a")||"",[]),[t,n]=j.useState(null),[r,a]=j.useState(!0),[i,l]=j.useState(!1),[o,c]=j.useState(null);j.useEffect(()=>{document.title="Activate Your LevelUp Account"},[]),j.useEffect(()=>{let h=!1;return(async()=>{if(!s){c("This link is missing information. Please use the button in your LevelUp email."),a(!1);return}const{data:f,error:g}=await q.functions.invoke("activation-link",{body:{action:"info",ref:s}});h||(g||!(f!=null&&f.ok)?c("We could not recognize this link. Please use the button in your latest LevelUp email."):n({email:f.email,name:f.name,brokerage_name:f.brokerage_name}),a(!1))})(),()=>{h=!0}},[s]);const d=async()=>{if(l(!0),c(null),window.location.origin!==Zce&&window.location.hostname!=="localhost"){window.location.href=`${Zce}${window.location.pathname}${window.location.search}`;return}try{const{data:h,error:m}=await q.functions.invoke("activation-link",{body:{action:"start",ref:s}});if(m||!(h!=null&&h.ok)||!h.token_hash)throw new Error("link_failed");const{error:f}=await q.auth.verifyOtp({token_hash:h.token_hash,type:h.type==="invite"?"invite":"recovery"});if(f)throw f;window.location.replace(`${Zce}/profile?reset=true&activation=1`)}catch{l(!1),c("Something went wrong signing you in. Please try again in a moment.")}},u=((t==null?void 0:t.name)||"").trim().split(/\s+/)[0];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:c6e,alt:"LevelUp",className:"h-12 w-auto"})})}),e.jsxs(Ne,{className:"border-0 shadow-2xl bg-white/95 backdrop-blur-sm",children:[e.jsxs(Ct,{className:"text-center",children:[e.jsx(At,{className:"text-2xl font-bold text-[#2a4347]",style:{fontFamily:"'Libre Baskerville', serif"},children:u?`Welcome, ${u}`:"Activate Your Account"}),e.jsx(Gn,{className:"text-gray-600 pt-2",children:r?"Loading your account…":o||(t!=null&&t.brokerage_name?`${t.brokerage_name} provides LevelUp for you. Sign in below to set your password.`:"Sign in below to set your password and get started.")})]}),e.jsxs(Ie,{className:"space-y-4",children:[t&&e.jsxs("div",{className:"rounded-lg bg-gray-50 border border-gray-200 p-4 text-center",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-gray-500",children:"Your login email"}),e.jsx("p",{className:"text-base font-semibold text-[#2a4347] break-all",children:t.email})]}),t?e.jsx($,{onClick:d,disabled:i,className:"w-full bg-[#4a6b6d] hover:bg-[#3d5a5c] text-white font-semibold py-6 text-lg shadow-lg hover:shadow-xl",children:i?"Signing you in…":"Sign me in"}):r?null:e.jsx($,{onClick:()=>window.location.href=`${Zce}/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:"No password needed — we'll sign you in and let you choose one."})]})]})]})})]})},D$s=()=>{const s=Qn(),[t]=gc(),[n,r]=j.useState(t.get("code")||""),[a,i]=j.useState(""),[l,o]=j.useState(""),[c,d]=j.useState(""),[u,h]=j.useState(!1),[m,f]=j.useState(!1),[g,x]=j.useState(!1),[y,v]=j.useState(!1),[b,w]=j.useState(null),[S,C]=j.useState(null),[E,I]=j.useState(null),[P,R]=j.useState(null);j.useEffect(()=>{const W=t.get("code");W&&(r(W),D(W))},[t]);const D=async W=>{x(!0);const{data:V,error:G}=await q.from("invite_codes").select("id, code, max_uses, uses_count, expires_at, is_active, brokerage_id, trial_days").eq("code",W.toUpperCase().trim()).single();if(G||!V){re.error("Invalid invite code"),x(!1);return}if(!V.is_active){re.error("This invite code is no longer active"),x(!1);return}if(V.max_uses&&V.uses_count>=V.max_uses){re.error("This invite code has reached its maximum uses"),x(!1);return}if(V.expires_at&&new Date(V.expires_at){W.preventDefault(),D(n)},U=async W=>{var V;if(W.preventDefault(),!c.trim()){re.error("Please enter your name");return}if(l.length<6){re.error("Password must be at least 6 characters");return}f(!0);try{const G="https://dashboard.relevelup.com/",{data:Y,error:X}=await q.auth.signUp({email:a.trim(),password:l,options:{emailRedirectTo:G,data:{name:c.trim()}}});if(X){X.message.includes("already registered")?re.error("This email is already registered. Please sign in instead."):re.error(X.message);return}if(Y.user){await q.rpc("add_default_signup_tag",{user_id:Y.user.id});const ae=n.toUpperCase().trim();S?await q.functions.invoke("assign-brokerage",{body:{userId:Y.user.id,brokerageId:S,inviteCode:ae}}):P?await q.functions.invoke("assign-brokerage",{body:{userId:Y.user.id,trialDays:P,inviteCode:ae}}):await q.functions.invoke("assign-brokerage",{body:{userId:Y.user.id,grandfathered:!0,inviteCode:ae}}),b&&await q.from("invite_codes").update({uses_count:((V=(await q.from("invite_codes").select("uses_count").eq("id",b).single()).data)==null?void 0:V.uses_count)+1}).eq("id",b),re.success("Account created! You can now access the dashboard."),s("/dashboard")}}catch(G){console.error("Signup error:",G),re.error("An unexpected error occurred")}finally{f(!1)}};return e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-background p-4",children:e.jsxs(Ne,{className:"w-full max-w-md",children:[e.jsxs(Ct,{className:"text-center",children:[e.jsx(At,{className:"text-2xl font-bold text-primary",children:E?`Join ${E}`:"Join LevelUp"}),e.jsx(Gn,{children:y?E?`Create your account to join ${E}`:"Create your account to get started":"Enter your invite code to continue"})]}),e.jsx(Ie,{children:y?e.jsxs("form",{onSubmit:U,className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"name",children:"Full Name"}),e.jsx(pe,{id:"name",type:"text",placeholder:"John Doe",value:c,onChange:W=>d(W.target.value),required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"email",children:"Email"}),e.jsx(pe,{id:"email",type:"email",placeholder:"you@example.com",value:a,onChange:W=>i(W.target.value),required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"password",children:"Password"}),e.jsxs("div",{className:"relative",children:[e.jsx(pe,{id:"password",type:u?"text":"password",placeholder:"••••••••",value:l,onChange:W=>o(W.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:()=>h(!u),children:u?e.jsx($g,{className:"h-4 w-4"}):e.jsx(Ca,{className:"h-4 w-4"})})]})]}),e.jsx($,{type:"submit",className:"w-full",disabled:m,children:m?e.jsxs(e.Fragment,{children:[e.jsx(kt,{className:"mr-2 h-4 w-4 animate-spin"}),"Creating Account..."]}):"Create Account"})]}):e.jsxs("form",{onSubmit:O,className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"inviteCode",children:"Invite Code"}),e.jsx(pe,{id:"inviteCode",type:"text",placeholder:"Enter your invite code",value:n,onChange:W=>r(W.target.value),required:!0,autoFocus:!0})]}),e.jsx($,{type:"submit",className:"w-full",disabled:g,children:g?e.jsxs(e.Fragment,{children:[e.jsx(kt,{className:"mr-2 h-4 w-4 animate-spin"}),"Verifying..."]}):"Verify Code"})]})})]})})},eie=()=>{const{user:s,isCoach:t}=vs();return tt({queryKey:["my-coach-profile",s==null?void 0:s.id],enabled:!!s&&t,queryFn:async()=>{const{data:n,error:r}=await q.from("coaches").select("*").eq("user_id",s.id).maybeSingle();if(r)throw r;return n}})},F$s=()=>{const{data:s}=eie();return tt({queryKey:["coach-roster",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await q.from("coaching_assignments").select("*").eq("coach_id",s.id).order("started_at",{ascending:!1});if(n)throw n;const r=t||[];if(r.length===0)return[];const a=r.map(o=>o.agent_id),{data:i}=await q.from("profiles").select("id, name, email, avatar_url").in("id",a),l=new Map((i||[]).map(o=>[o.id,o]));return r.map(o=>({...o,agent:l.get(o.agent_id)||null}))}})},Bst=()=>{const{user:s}=vs();return tt({queryKey:["my-coaching-assignment",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await q.from("coaching_assignments").select("*").eq("agent_id",s.id).eq("status","active").order("started_at",{ascending:!1}).limit(1);if(n)throw n;const r=(t||[])[0];if(!r)return null;const{data:a}=await q.from("coaches").select("*").eq("id",r.coach_id).maybeSingle();let i=null;if(a!=null&&a.user_id){const{data:l}=await q.from("profiles").select("id, name, email, avatar_url").eq("id",a.user_id).maybeSingle();i=l}return{...r,coach:a,coachProfile:i}}})},O$s=s=>tt({queryKey:["coaching-assignment",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await q.from("coaching_assignments").select("*").eq("id",s).maybeSingle();if(n)throw n;if(!t)return null;const{data:r}=await q.from("profiles").select("id, name, email, avatar_url").eq("id",t.agent_id).maybeSingle();return{...t,agent:r}}}),$st=s=>tt({queryKey:["coaching-sessions",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await q.from("coaching_sessions").select("*").eq("assignment_id",s).order("scheduled_at",{ascending:!1});if(n)throw n;return t||[]}}),Ust=s=>tt({queryKey:["coaching-action-items",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await q.from("coaching_action_items").select("*").eq("assignment_id",s).order("due_date",{ascending:!0,nullsFirst:!1});if(n)throw n;return t||[]}}),z$s=[{key:"onboarding",label:"Onboarding"},{key:"active",label:"Active"},{key:"thriving",label:"Thriving"},{key:"at_risk",label:"At Risk"},{key:"graduated",label:"Graduated"}];function B$s(){const s=Qn(),{data:t,isLoading:n}=eie(),{data:r=[],isLoading:a}=F$s();if(n)return e.jsx(Vs,{title:"Coaching",children:e.jsx("div",{className:"p-8",children:"Loading…"})});if(!t)return e.jsx(Vs,{title:"Coaching",children:e.jsxs("div",{className:"max-w-2xl mx-auto p-8 text-center",children:[e.jsx(of,{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."})]})});z$s.map(l=>({...l,items:r.filter(o=>(o.pipeline_stage||"active")===l.key)}));const i=r.filter(l=>l.status==="active").length;return e.jsx(Vs,{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(Nn,{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(z7e,{icon:of,label:"Active agents",value:i}),e.jsx(z7e,{icon:Kc,label:"This month",value:"—"}),e.jsx(z7e,{icon:nh,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($,{size:"sm",variant:"outline",onClick:()=>s("/coaching/waitlist"),children:"Waitlist"}),e.jsx($,{size:"sm",variant:"outline",onClick:()=>s("/coaching/settings"),children:"Profile Settings"}),e.jsx($,{size:"sm",variant:"outline",onClick:()=>s("/coaching/billing"),children:"Billing & Packages"})]})]}),a?e.jsx("div",{className:"text-muted-foreground",children:"Loading roster…"}):r.length===0?e.jsx(Ne,{children:e.jsx(Ie,{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:r.map(l=>{var o,c,d,u;return e.jsx(Ne,{className:"cursor-pointer hover:shadow-lg transition-all hover:-translate-y-0.5",onClick:()=>s(`/coaching/agent/${l.id}`),children:e.jsx(Ie,{className:"p-5",children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsxs(Oa,{className:"h-14 w-14",children:[e.jsx(Li,{src:((o=l.agent)==null?void 0:o.avatar_url)||void 0}),e.jsx(za,{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(ei,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:(u=l.agent)==null?void 0:u.email}),e.jsxs("div",{className:"flex items-center gap-2 mt-3",children:[e.jsx(Be,{variant:"secondary",className:"capitalize",children:(l.pipeline_stage||"active").replace("_"," ")}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:["Started ",mu(new Date(l.started_at),{addSuffix:!0})]})]})]})]})})},l.id)})})]})]})})}function z7e({icon:s,label:t,value:n}){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:n}),e.jsx("div",{className:"text-xs text-white/70 mt-1",children:t})]})]})}function p$t({assignmentId:s}){const{user:t}=vs(),n=Vt(),[r,a]=j.useState(""),[i,l]=j.useState(!1),o=j.useRef(null),{data:c=[]}=tt({queryKey:["coaching-messages",s],enabled:!!s,queryFn:async()=>{const{data:u,error:h}=await q.from("coaching_messages").select("*").eq("assignment_id",s).order("created_at",{ascending:!0});if(h)throw h;return u||[]}});j.useEffect(()=>{if(!s)return;const u=q.channel(`coaching-messages-${s}`).on("postgres_changes",{event:"INSERT",schema:"public",table:"coaching_messages",filter:`assignment_id=eq.${s}`},()=>n.invalidateQueries({queryKey:["coaching-messages",s]})).subscribe();return()=>{q.removeChannel(u)}},[s,n]),j.useEffect(()=>{var u;(u=o.current)==null||u.scrollTo({top:o.current.scrollHeight,behavior:"smooth"})},[c]);const d=async()=>{const u=r.trim();if(!u||!t)return;l(!0);const{error:h}=await q.from("coaching_messages").insert({assignment_id:s,sender_id:t.id,body:u});l(!1),h||a("")};return e.jsxs(Ne,{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(u=>{const h=u.sender_id===(t==null?void 0:t.id);return e.jsxs("div",{className:Pt("flex gap-2",h?"justify-end":"justify-start"),children:[!h&&e.jsx(Oa,{className:"h-8 w-8 mt-1",children:e.jsx(za,{className:"text-xs",children:(u.sender_id||"?").charAt(0).toUpperCase()})}),e.jsxs("div",{className:Pt("max-w-[75%] rounded-2xl px-3 py-2 text-sm",h?"bg-[#406E71] text-white rounded-br-sm":"bg-muted rounded-bl-sm"),children:[e.jsx("p",{className:"whitespace-pre-wrap break-words",children:u.body}),e.jsx("p",{className:Pt("text-[10px] mt-1",h?"text-white/70":"text-muted-foreground"),children:mu(new Date(u.created_at),{addSuffix:!0})})]})]},u.id)})}),e.jsx(Ie,{className:"border-t p-3",children:e.jsxs("div",{className:"flex gap-2 items-end",children:[e.jsx(Rs,{value:r,onChange:u=>a(u.target.value),onKeyDown:u=>{u.key==="Enter"&&!u.shiftKey&&(u.preventDefault(),d())},placeholder:"Type a message…",rows:1,className:"resize-none min-h-[40px]"}),e.jsx($,{onClick:d,disabled:i||!r.trim(),size:"icon",className:"bg-[#406E71] hover:bg-[#2a4c64]",children:e.jsx(Yr,{className:"h-4 w-4"})})]})})]})}var $$s=Object.defineProperty,IT=(s,t)=>$$s(s,"name",{value:t,configurable:!0}),g$t="Progress",qst=100,[U$s,uSr]=tp(g$t),[q$s,V$s]=U$s(g$t),H$s=j.forwardRef(IT(function(t,n){const{__scopeProgress:r,value:a=null,max:i,getValueLabel:l=x$t,...o}=t;(i||i===0)&&!FGe(i)&&console.error(y$t(`${i}`,"Progress"));const c=FGe(i)?i:qst;a!==null&&!OGe(a,c)&&console.error(v$t(`${a}`,"Progress"));const d=OGe(a,c)?a:null,u=lse(d)?l(d,c):void 0;return e.jsx(q$s,{scope:r,value:d,max:c,children:e.jsx(Ei.div,{"aria-valuemax":c,"aria-valuemin":0,"aria-valuenow":lse(d)?d:void 0,"aria-valuetext":u,role:"progressbar","data-state":Vst(d,c),"data-value":d??void 0,"data-max":c,...o,ref:n})})},"Progress")),G$s="ProgressIndicator",W$s=j.forwardRef(IT(function(t,n){const{__scopeProgress:r,...a}=t,i=V$s(G$s,r);return e.jsx(Ei.div,{"data-state":Vst(i.value,i.max),"data-value":i.value??void 0,"data-max":i.max,...a,ref:n})},"ProgressIndicator"));function x$t(s,t){return`${Math.round(s/t*100)}%`}IT(x$t,"defaultGetValueLabel");function Vst(s,t){return s==null?"indeterminate":s===t?"complete":"loading"}IT(Vst,"getProgressState");function lse(s){return typeof s=="number"}IT(lse,"isNumber");function FGe(s){return lse(s)&&!isNaN(s)&&s>0}IT(FGe,"isValidMaxNumber");function OGe(s,t){return lse(s)&&!isNaN(s)&&s<=t&&s>=0}IT(OGe,"isValidValueNumber");function y$t(s,t){return`Invalid prop \`max\` of value \`${s}\` supplied to \`${t}\`. Only numbers greater than 0 are valid max values. Defaulting to \`${qst}\`.`}IT(y$t,"getInvalidMaxError");function v$t(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 ${qst} if no \`max\` prop is set) - \`null\` or \`undefined\` if the progress is indeterminate. Defaulting to \`null\`.`}IT(v$t,"getInvalidValueError");var b$t=H$s,K$s=W$s;const Yi=j.forwardRef(({className:s,value:t,...n},r)=>e.jsx(b$t,{ref:r,className:Pt("relative h-4 w-full overflow-hidden rounded-full bg-secondary",s),...n,children:e.jsx(K$s,{className:"h-full w-full flex-1 bg-primary transition-all",style:{transform:`translateX(-${100-(t||0)}%)`}})}));Yi.displayName=b$t.displayName;function _$t({agentUserId:s}){const t=new Date().getFullYear(),n=`${t}-01-01`,r=`${t}-12-31`,{data:a=[]}=tt({queryKey:["coaching-kpi-txns",s,t],enabled:!!s,queryFn:async()=>{const{data:x,error:y}=await q.from("scorecard_transactions").select("id, sale_price, commission_amount, close_date, is_win").eq("owner_user_id",s).gte("close_date",n).lte("close_date",r);if(y)throw y;return x||[]}}),{data:i}=tt({queryKey:["coaching-kpi-goal",s,t],enabled:!!s,queryFn:async()=>{const{data:x}=await q.from("scorecard_goals").select("*").eq("owner_user_id",s).eq("year",t).maybeSingle();return x}}),l=a.filter(x=>x.is_win),o=l.length,c=l.reduce((x,y)=>x+(Number(y.sale_price)||0),0),d=l.reduce((x,y)=>x+(Number(y.commission_amount)||0),0),u=i,h=(u==null?void 0:u.transactions_goal)||0,m=(u==null?void 0:u.volume_goal)||0,f=(u==null?void 0:u.gci_goal)||0,g=x=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(x);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(Yl,{className:"h-5 w-5"})," ",t," KPIs"]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-3",children:[e.jsx(B7e,{icon:Rm,label:"Transactions",value:o.toString(),goal:h,current:o,suffix:h?`/ ${h}`:""}),e.jsx(B7e,{icon:Yl,label:"Volume",value:g(c),goal:m,current:c,suffix:m?`of ${g(m)}`:""}),e.jsx(B7e,{icon:ru,label:"GCI",value:g(d),goal:f,current:d,suffix:f?`of ${g(f)}`:""})]}),o===0&&e.jsx(Ne,{children:e.jsxs(Ie,{className:"p-4 text-sm text-muted-foreground text-center",children:["No transactions logged for ",t," yet."]})})]})}function B7e({icon:s,label:t,value:n,goal:r,current:a,suffix:i}){const l=r>0?Math.min(100,a/r*100):0;return e.jsx(Ne,{children:e.jsxs(Ie,{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:n}),r>0&&e.jsxs("div",{className:"mt-2 space-y-1",children:[e.jsx(Yi,{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 w$t({assignmentId:s,canEdit:t}){const n=Vt(),[r,a]=j.useState(!1),[i,l]=j.useState(null),{data:o=[]}=tt({queryKey:["coaching-goals",s],enabled:!!s,queryFn:async()=>{const{data:d,error:u}=await q.from("coaching_goals").select("*").eq("assignment_id",s).order("created_at",{ascending:!1});if(u)throw u;return d||[]}}),c=()=>n.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(rh,{className:"h-5 w-5"})," Goals"]}),t&&e.jsxs($,{size:"sm",onClick:()=>{l(null),a(!0)},children:[e.jsx(dn,{className:"h-4 w-4 mr-1"})," New Goal"]})]}),o.length===0?e.jsx(Ne,{children:e.jsx(Ie,{className:"p-6 text-center text-muted-foreground",children:"No goals yet."})}):o.map(d=>{const u=Number(d.target_value||0),h=Number(d.current_value||0),m=u>0?Math.min(100,h/u*100):0;return e.jsx(Ne,{children:e.jsxs(Ie,{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(Be,{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($,{variant:"ghost",size:"icon",onClick:()=>{l(d),a(!0)},children:e.jsx(gi,{className:"h-4 w-4"})})]}),u>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:[h.toLocaleString()," / ",u.toLocaleString()," ",d.target_metric||""]}),e.jsxs("span",{children:[m.toFixed(0),"%"]})]}),e.jsx(Yi,{value:m})]}),d.due_date&&e.jsxs("p",{className:"text-xs text-muted-foreground mt-2",children:["Due ",en(new Date(d.due_date),"PP")]})]})},d.id)}),t&&e.jsx(Y$s,{open:r,onOpenChange:a,assignmentId:s,goal:i,onSaved:c})]})}function Y$s({open:s,onOpenChange:t,assignmentId:n,goal:r,onSaved:a}){var S,C;const[i,l]=j.useState((r==null?void 0:r.title)||""),[o,c]=j.useState((r==null?void 0:r.description)||""),[d,u]=j.useState((r==null?void 0:r.target_metric)||""),[h,m]=j.useState(((S=r==null?void 0:r.target_value)==null?void 0:S.toString())||""),[f,g]=j.useState(((C=r==null?void 0:r.current_value)==null?void 0:C.toString())||"0"),[x,y]=j.useState((r==null?void 0:r.due_date)||""),[v,b]=j.useState(!1);j.useState(()=>{var E,I;l((r==null?void 0:r.title)||""),c((r==null?void 0:r.description)||""),u((r==null?void 0:r.target_metric)||""),m(((E=r==null?void 0:r.target_value)==null?void 0:E.toString())||""),g(((I=r==null?void 0:r.current_value)==null?void 0:I.toString())||"0"),y((r==null?void 0:r.due_date)||"")});const w=async()=>{if(!i.trim())return;b(!0);const E={assignment_id:n,title:i,description:o||null,target_metric:d||null,target_value:h?Number(h):null,current_value:f?Number(f):0,due_date:x||null},{error:I}=r!=null&&r.id?await q.from("coaching_goals").update(E).eq("id",r.id):await q.from("coaching_goals").insert(E);if(b(!1),I)return re.error(I.message);re.success(r!=null&&r.id?"Goal updated":"Goal created"),a==null||a(),t(!1)};return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Os,{children:[e.jsx(Us,{children:e.jsx(Bs,{children:r!=null&&r.id?"Edit Goal":"New Goal"})}),e.jsxs("div",{className:"space-y-3",children:[e.jsx(pe,{placeholder:"Title",value:i,onChange:E=>l(E.target.value)}),e.jsx(Rs,{placeholder:"Description (optional)",rows:2,value:o,onChange:E=>c(E.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(pe,{placeholder:"transactions",value:d,onChange:E=>u(E.target.value)})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-muted-foreground",children:"Target"}),e.jsx(pe,{type:"number",value:h,onChange:E=>m(E.target.value)})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-muted-foreground",children:"Current"}),e.jsx(pe,{type:"number",value:f,onChange:E=>g(E.target.value)})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-muted-foreground",children:"Due date"}),e.jsx(pe,{type:"date",value:x,onChange:E=>y(E.target.value)})]})]}),e.jsxs(Ar,{children:[e.jsx($,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsx($,{onClick:w,disabled:v,children:r!=null&&r.id?"Save":"Create"})]})]})})}function j$t({assignmentId:s}){const t=Vt(),{user:n}=vs(),r=j.useRef(null),[a,i]=j.useState(!1),{data:l=[]}=tt({queryKey:["coaching-files",s],enabled:!!s,queryFn:async()=>{const{data:h,error:m}=await q.from("coaching_shared_files").select("*").eq("assignment_id",s).order("created_at",{ascending:!1});if(m)throw m;return h||[]}}),o=()=>t.invalidateQueries({queryKey:["coaching-files",s]}),c=async h=>{var f;const m=(f=h.target.files)==null?void 0:f[0];if(!(!m||!n)){i(!0);try{const g=`${s}/${Date.now()}-${m.name}`,{error:x}=await q.storage.from("coaching-files").upload(g,m);if(x)throw x;const{error:y}=await q.from("coaching_shared_files").insert({assignment_id:s,uploaded_by:n.id,file_url:g,file_name:m.name,file_size_bytes:m.size,mime_type:m.type});if(y)throw y;re.success("File uploaded"),o()}catch(g){re.error(g.message||"Upload failed")}finally{i(!1),r.current&&(r.current.value="")}}},d=async h=>{const{data:m,error:f}=await q.storage.from("coaching-files").createSignedUrl(h.file_url,60);if(f||!m)return re.error("Could not get download link");window.open(m.signedUrl,"_blank")},u=async h=>{await fo("Delete this file?")&&(await q.storage.from("coaching-files").remove([h.file_url]),await q.from("coaching_shared_files").delete().eq("id",h.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($,{size:"sm",onClick:()=>{var h;return(h=r.current)==null?void 0:h.click()},disabled:a,children:[e.jsx(ni,{className:"h-4 w-4 mr-1"})," ",a?"Uploading…":"Upload"]}),e.jsx("input",{ref:r,type:"file",hidden:!0,onChange:c})]}),l.length===0?e.jsx(Ne,{children:e.jsx(Ie,{className:"p-6 text-center text-muted-foreground",children:"No files yet."})}):e.jsx("div",{className:"space-y-2",children:l.map(h=>e.jsx(Ne,{children:e.jsxs(Ie,{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(Jr,{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:h.file_name}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[h.file_size_bytes?`${(h.file_size_bytes/1024).toFixed(0)} KB · `:"",en(new Date(h.created_at),"PP")]})]}),e.jsx($,{variant:"ghost",size:"icon",onClick:()=>d(h),children:e.jsx(di,{className:"h-4 w-4"})}),h.uploaded_by===(n==null?void 0:n.id)&&e.jsx($,{variant:"ghost",size:"icon",onClick:()=>u(h),children:e.jsx(Wn,{className:"h-4 w-4"})})]})},h.id))})]})}function Z$s(){var m,f,g,x;const{id:s}=Wi(),t=Qn(),n=Vt(),{data:r,isLoading:a}=O$s(s),{data:i=[]}=$st(s),{data:l=[]}=Ust(s),[o,c]=j.useState(!1),[d,u]=j.useState(!1);if(a)return e.jsx(Vs,{title:"Coaching",children:e.jsx("div",{className:"p-8",children:"Loading…"})});if(!r)return e.jsx(Vs,{title:"Coaching",children:e.jsx("div",{className:"p-8",children:"Assignment not found."})});const h=r;return e.jsxs(Vs,{title:"Coaching",children:[e.jsxs("div",{className:"p-4 md:p-8 max-w-6xl mx-auto space-y-6",children:[e.jsxs($,{variant:"ghost",size:"sm",onClick:()=>t("/coaching"),children:[e.jsx(qa,{className:"h-4 w-4 mr-2"})," Back to roster"]}),e.jsxs(Ne,{className:"overflow-hidden",children:[e.jsx("div",{className:"h-24 bg-gradient-to-br from-[#2a4c64] to-[#406E71]"}),e.jsx(Ie,{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(Oa,{className:"h-24 w-24 ring-4 ring-background",children:[e.jsx(Li,{src:((m=h.agent)==null?void 0:m.avatar_url)||void 0}),e.jsx(za,{className:"text-2xl",children:(((f=h.agent)==null?void 0:f.name)||"?").charAt(0)})]}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("h1",{className:"text-2xl font-bold",children:((g=h.agent)==null?void 0:g.name)||"Unknown"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:(x=h.agent)==null?void 0:x.email}),e.jsxs("div",{className:"flex items-center gap-2 mt-2",children:[e.jsx(Be,{variant:"secondary",className:"capitalize",children:(h.pipeline_stage||"active").replace("_"," ")}),e.jsx(Be,{variant:"outline",className:"capitalize",children:h.status})]})]}),e.jsx("div",{className:"flex gap-2",children:e.jsx(Q$s,{value:h.pipeline_stage||"active",onChange:async y=>{await q.from("coaching_assignments").update({pipeline_stage:y}).eq("id",h.id),n.invalidateQueries({queryKey:["coaching-assignment",h.id]}),n.invalidateQueries({queryKey:["coach-roster"]})}})})]})})]}),e.jsx(X$s,{assignment:h}),e.jsxs(ha,{defaultValue:"sessions",children:[e.jsxs(ma,{className:"w-full flex flex-wrap justify-start h-auto",children:[e.jsxs(Zt,{value:"sessions",children:[e.jsx(Ta,{className:"h-4 w-4 mr-2"}),"Sessions"]}),e.jsxs(Zt,{value:"actions",children:[e.jsx(Ev,{className:"h-4 w-4 mr-2"}),"Actions"]}),e.jsxs(Zt,{value:"goals",children:[e.jsx(rh,{className:"h-4 w-4 mr-2"}),"Goals"]}),e.jsxs(Zt,{value:"kpis",children:[e.jsx(Yl,{className:"h-4 w-4 mr-2"}),"KPIs"]}),e.jsxs(Zt,{value:"messages",children:[e.jsx(eo,{className:"h-4 w-4 mr-2"}),"Messages"]}),e.jsxs(Zt,{value:"files",children:[e.jsx(_b,{className:"h-4 w-4 mr-2"}),"Files"]}),e.jsxs(Zt,{value:"notes",children:[e.jsx(Jr,{className:"h-4 w-4 mr-2"}),"Private Notes"]})]}),e.jsxs(Xt,{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($,{size:"sm",onClick:()=>c(!0),children:[e.jsx(dn,{className:"h-4 w-4 mr-1"})," New Session"]})]}),i.length===0?e.jsx(Ne,{children:e.jsx(Ie,{className:"p-6 text-muted-foreground text-center",children:"No sessions yet."})}):e.jsx("div",{className:"space-y-3",children:i.map(y=>e.jsx(Ne,{children:e.jsx(Ie,{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:en(new Date(y.scheduled_at),"PPp")}),e.jsx(Be,{variant:"outline",className:"capitalize",children:y.status}),y.template&&e.jsx(Be,{variant:"secondary",children:y.template}),y.zoom_join_url&&e.jsx("a",{href:y.zoom_join_url,target:"_blank",rel:"noopener noreferrer",className:"text-xs text-primary underline",children:"Join Zoom"})]}),y.agenda&&e.jsxs("p",{className:"text-sm mb-1",children:[e.jsx("span",{className:"text-muted-foreground",children:"Agent's agenda:"})," ",y.agenda]}),y.summary&&e.jsx("p",{className:"text-sm text-muted-foreground whitespace-pre-wrap",children:y.summary}),y.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(pc,{className:"h-3 w-3"})," Private"]}),e.jsx("p",{className:"whitespace-pre-wrap",children:y.private_notes})]})]})})})},y.id))})]}),e.jsxs(Xt,{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($,{size:"sm",onClick:()=>u(!0),children:[e.jsx(dn,{className:"h-4 w-4 mr-1"})," Add"]})]}),l.length===0?e.jsx(Ne,{children:e.jsx(Ie,{className:"p-6 text-muted-foreground text-center",children:"No action items yet."})}):e.jsx("div",{className:"space-y-2",children:l.map(y=>e.jsx(Ne,{children:e.jsxs(Ie,{className:"p-3 flex items-center gap-3",children:[e.jsx(ai,{checked:y.status==="done",onCheckedChange:async v=>{await q.from("coaching_action_items").update({status:v?"done":"open",completed_at:v?new Date().toISOString():null}).eq("id",y.id),n.invalidateQueries({queryKey:["coaching-action-items",h.id]})}}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:y.status==="done"?"line-through text-muted-foreground":"font-medium",children:y.title}),y.description&&e.jsx("div",{className:"text-xs text-muted-foreground",children:y.description})]}),y.due_date&&e.jsx(Be,{variant:"outline",children:en(new Date(y.due_date),"MMM d")}),e.jsx(Be,{variant:"secondary",className:"capitalize",children:y.priority})]})},y.id))})]}),e.jsx(Xt,{value:"goals",children:e.jsx(w$t,{assignmentId:h.id,canEdit:!0})}),e.jsx(Xt,{value:"kpis",children:h.agent_id&&e.jsx(_$t,{agentUserId:h.agent_id})}),e.jsx(Xt,{value:"messages",children:e.jsx(p$t,{assignmentId:h.id})}),e.jsx(Xt,{value:"files",children:e.jsx(j$t,{assignmentId:h.id})}),e.jsx(Xt,{value:"notes",className:"space-y-4",children:e.jsx(Ne,{children:e.jsx(Ie,{className:"p-6 text-muted-foreground",children:"Private notes per session live under the Sessions tab. General-relationship notes coming soon."})})})]})]}),e.jsx(J$s,{open:o,onOpenChange:c,assignmentId:h.id,onSaved:()=>n.invalidateQueries({queryKey:["coaching-sessions",h.id]})}),e.jsx(eUs,{open:d,onOpenChange:u,assignmentId:h.id,onSaved:()=>n.invalidateQueries({queryKey:["coaching-action-items",h.id]})})]})}function X$s({assignment:s}){const t=Vt(),[n,r]=j.useState(s.sessions_per_month==null?"":String(s.sessions_per_month)),[a,i]=j.useState(!1),l=async()=>{i(!0);const o=n.trim()===""?null:Math.max(1,parseInt(n,10)||1),{error:c}=await q.from("coaching_assignments").update({sessions_per_month:o}).eq("id",s.id);if(i(!1),c)return re.error(c.message);re.success("Session allowance updated"),t.invalidateQueries({queryKey:["coaching-assignment",s.id]})};return e.jsx(Ne,{children:e.jsxs(Ie,{className:"p-4 flex flex-wrap items-end gap-3",children:[e.jsxs("div",{className:"flex-1 min-w-[220px]",children:[e.jsxs("div",{className:"font-medium flex items-center gap-2",children:[e.jsx(Ta,{className:"h-4 w-4"})," Monthly session allowance"]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Leave blank to use your coach default. This agent books these on their My Coach page."})]}),e.jsx(pe,{type:"number",min:1,max:31,placeholder:"Default",value:n,onChange:o=>r(o.target.value),className:"w-28"}),e.jsxs($,{size:"sm",variant:"outline",onClick:l,disabled:a,children:[e.jsx(tl,{className:"h-4 w-4 mr-1"})," Save"]})]})})}function Q$s({value:s,onChange:t}){return e.jsxs(ms,{value:s,onValueChange:t,children:[e.jsx(us,{className:"w-40",children:e.jsx(fs,{})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"onboarding",children:"Onboarding"}),e.jsx(Ge,{value:"active",children:"Active"}),e.jsx(Ge,{value:"thriving",children:"Thriving"}),e.jsx(Ge,{value:"at_risk",children:"At Risk"}),e.jsx(Ge,{value:"graduated",children:"Graduated"})]})]})}function J$s({open:s,onOpenChange:t,assignmentId:n,onSaved:r}){const[a,i]=j.useState(()=>new Date().toISOString().slice(0,16)),[l,o]=j.useState(60),[c,d]=j.useState("weekly_1on1"),[u,h]=j.useState(""),[m,f]=j.useState(""),[g,x]=j.useState(!1),[y,v]=j.useState(!0),[b,w]=j.useState(null),[S,C]=j.useState(!1),E=async()=>{C(!0);const{data:P,error:R}=await q.functions.invoke("coaching-prep-brief",{body:{assignmentId:n}});if(C(!1),R||P!=null&&P.error)return re.error((P==null?void 0:P.error)||(R==null?void 0:R.message)||"Failed to generate brief");w(P.brief||"No brief returned.")},I=async()=>{x(!0);const{data:P,error:R}=await q.from("coaching_sessions").insert({assignment_id:n,scheduled_at:new Date(a).toISOString(),duration_minutes:l,template:c,summary:u,private_notes:m,status:"completed"}).select("id").maybeSingle();if(R)return x(!1),re.error(R.message);if(re.success("Session saved"),y&&u.trim()&&(P!=null&&P.id)){const{error:D}=await q.functions.invoke("coaching-send-recap",{body:{sessionId:P.id}});D?re.error("Saved, but recap email failed: "+D.message):re.success("Recap emailed to agent")}x(!1),r==null||r(),t(!1),h(""),f(""),w(null)};return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Os,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(Us,{children:e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx(Bs,{children:"New Session"}),e.jsxs($,{size:"sm",variant:"outline",onClick:E,disabled:S,children:[S?e.jsx(kt,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(Nn,{className:"h-4 w-4 mr-1"}),"Pre-session brief"]})]})}),e.jsxs("div",{className:"space-y-3",children:[b&&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(Nn,{className:"h-3 w-3"})," AI Brief"]}),b]}),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(pe,{type:"datetime-local",value:a,onChange:P=>i(P.target.value)})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium",children:"Duration (min)"}),e.jsx(pe,{type:"number",value:l,onChange:P=>o(Number(P.target.value))})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium",children:"Template"}),e.jsxs(ms,{value:c,onValueChange:d,children:[e.jsx(us,{children:e.jsx(fs,{})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"weekly_1on1",children:"Weekly 1:1"}),e.jsx(Ge,{value:"grow",children:"GROW Model"}),e.jsx(Ge,{value:"goal_review",children:"Goal Review"}),e.jsx(Ge,{value:"breakthrough",children:"Breakthrough Session"})]})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium",children:"Summary (agent sees this)"}),e.jsx(Rs,{rows:4,value:u,onChange:P=>h(P.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(pc,{className:"h-3 w-3"})," Private notes (only you)"]}),e.jsx(Rs,{rows:3,value:m,onChange:P=>f(P.target.value),placeholder:"Your private observations…"})]}),e.jsxs("label",{className:"flex items-center gap-2 text-sm pt-1",children:[e.jsx(ai,{checked:y,onCheckedChange:P=>v(!!P)}),e.jsx(Yr,{className:"h-3.5 w-3.5 text-muted-foreground"}),"Email recap to agent on save"]})]}),e.jsxs(Ar,{children:[e.jsx($,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsxs($,{onClick:I,disabled:g,children:[e.jsx(tl,{className:"h-4 w-4 mr-1"})," Save Session"]})]})]})})}function eUs({open:s,onOpenChange:t,assignmentId:n,onSaved:r}){const[a,i]=j.useState(""),[l,o]=j.useState(""),[c,d]=j.useState(""),[u,h]=j.useState("medium"),[m,f]=j.useState(!1),g=async()=>{if(!a.trim())return;f(!0);const{error:x}=await q.from("coaching_action_items").insert({assignment_id:n,title:a,description:l||null,due_date:c||null,priority:u});if(f(!1),x)return re.error(x.message);re.success("Action item added"),r==null||r(),t(!1),i(""),o(""),d("")};return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Os,{children:[e.jsx(Us,{children:e.jsx(Bs,{children:"New Action Item"})}),e.jsxs("div",{className:"space-y-3",children:[e.jsx(pe,{placeholder:"Title",value:a,onChange:x=>i(x.target.value)}),e.jsx(Rs,{rows:3,placeholder:"Description (optional)",value:l,onChange:x=>o(x.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(pe,{type:"date",value:c,onChange:x=>d(x.target.value)})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium",children:"Priority"}),e.jsxs(ms,{value:u,onValueChange:h,children:[e.jsx(us,{children:e.jsx(fs,{})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"low",children:"Low"}),e.jsx(Ge,{value:"medium",children:"Medium"}),e.jsx(Ge,{value:"high",children:"High"})]})]})]})]})]}),e.jsxs(Ar,{children:[e.jsx($,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsx($,{onClick:g,disabled:m,children:"Add"})]})]})})}function zGe({value:s,size:t=16,onChange:n}){return e.jsx("div",{className:"flex items-center gap-0.5",children:[1,2,3,4,5].map(r=>e.jsx("button",{type:"button",onClick:()=>n==null?void 0:n(r),disabled:!n,className:n?"cursor-pointer":"cursor-default",children:e.jsx(Ja,{style:{width:t,height:t},className:r<=s?"fill-yellow-400 text-yellow-400":"text-muted-foreground/40"})},r))})}function tUs({coachId:s}){const[t,n]=j.useState([]),[r,a]=j.useState(!0);j.useEffect(()=>{(async()=>{const{data:l}=await q.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(h=>h.agent_id),{data:d}=await q.from("profiles").select("id, name, avatar_url").in("id",c),u=new Map((d||[]).map(h=>[h.id,h]));o.forEach(h=>h.profile=u.get(h.agent_id))}n(o),a(!1)})()},[s]);const i=t.length?t.reduce((l,o)=>l+o.rating,0)/t.length:0;return r||!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(zGe,{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(Ne,{children:e.jsx(Ie,{className:"p-4",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsxs(Oa,{className:"h-9 w-9",children:[e.jsx(Li,{src:((o=l.profile)==null?void 0:o.avatar_url)||void 0}),e.jsx(za,{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(zGe,{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 sUs({coachId:s,assignmentId:t}){const{user:n}=vs(),[r,a]=j.useState(null),[i,l]=j.useState(0),[o,c]=j.useState(""),[d,u]=j.useState(""),[h,m]=j.useState(!1);j.useEffect(()=>{n&&(async()=>{const{data:g}=await q.from("coaching_reviews").select("*").eq("coach_id",s).eq("agent_id",n.id).maybeSingle();g&&(a(g),l(g.rating),c(g.title||""),u(g.body||""))})()},[n,s]);const f=async()=>{if(!n)return;if(!i)return re.error("Pick a rating");m(!0);const g={coach_id:s,agent_id:n.id,assignment_id:t||null,rating:i,title:o||null,body:d||null},{error:x}=r?await q.from("coaching_reviews").update(g).eq("id",r.id):await q.from("coaching_reviews").insert(g);if(m(!1),x)return re.error(x.message);re.success("Thanks for your review!"),a({...g,id:r==null?void 0:r.id})};return e.jsx(Ne,{children:e.jsxs(Ie,{className:"p-5 space-y-3",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"font-semibold",children:r?"Your review":"Leave a review"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Help other agents find a great coach."})]}),e.jsx(zGe,{value:i,size:28,onChange:l}),e.jsx(pe,{placeholder:"Title (optional)",value:o,onChange:g=>c(g.target.value)}),e.jsx(Rs,{rows:4,placeholder:"What was your experience like?",value:d,onChange:g=>u(g.target.value)}),e.jsx($,{onClick:f,disabled:h,className:"bg-[#406E71] hover:bg-[#2a4c64]",children:h?"Saving…":r?"Update review":"Submit review"})]})})}const Xce=async s=>{var r,a;const{data:t,error:n}=await q.functions.invoke("coaching-booking",{body:s});if(n){const i=(r=n==null?void 0:n.context)!=null&&r.text?await n.context.text():n.message;let l=i;try{l=((a=JSON.parse(i))==null?void 0:a.error)||i}catch{}throw new Error(l)}if(t!=null&&t.error)throw new Error(t.error);return t},$7e=s=>en(s,"yyyy-MM-dd"),zvt=s=>{const[t,n]=s.split(":").map(Number),r=t>=12?"PM":"AM";return`${t%12||12}:${String(n).padStart(2,"0")} ${r}`};function nUs({assignmentId:s,upcoming:t=[]}){const n=Vt(),[r,a]=j.useState(null),[i,l]=j.useState(null),[o,c]=j.useState(null),[d,u]=j.useState(""),[h,m]=j.useState(!1),{data:f,isLoading:g}=tt({queryKey:["coaching-booking-context",s],queryFn:()=>Xce({action:"context"})});j.useEffect(()=>{var ae;!r&&((ae=f==null?void 0:f.booking_types)!=null&&ae.length)&&a(f.booking_types[0].id)},[f,r]);const x=j.useMemo(()=>new Date,[]),[y,v]=j.useState(()=>Xm(new Date)),b=(f==null?void 0:f.max_advance_days)||30,w=j.useMemo(()=>Tm(Mg(x),b-1),[x,b]),S=j.useMemo(()=>{const ae=Xm(y);return ae{const ae=yw(y);return ae>w?w:ae},[y,w]),E=Math.max(0,fb(C,S)+1),{data:I={},isFetching:P}=tt({queryKey:["coaching-availability",r,$7e(S),E],enabled:!!r&&E>0,queryFn:async()=>(await Xce({action:"availability",booking_type_id:r,start:$7e(S),days:E})).availability||{}}),R=j.useMemo(()=>{const ae=Xm(y),ie=yw(y).getDate(),ne=ae.getDay(),te=Array.from({length:ne},()=>null);for(let J=0;JObject.entries(I).filter(([,ae])=>ae.length>0),[I]),O=i?I[i]||[]:[],U=P,W=j.useMemo(()=>{const ae=[{label:"Morning",items:[]},{label:"Afternoon",items:[]},{label:"Evening",items:[]}];for(const ie of O){const ne=Number(ie.split(":")[0]);ne<12?ae[0].items.push(ie):ne<17?ae[1].items.push(ie):ae[2].items.push(ie)}return ae.filter(ie=>ie.items.length>0)},[O]),V=(f==null?void 0:f.booking_types.find(ae=>ae.id===r))||null,G=((f==null?void 0:f.sessions_remaining)??0)<=0,Y=async()=>{if(!(!r||!i||!o)){m(!0);try{await Xce({action:"book",booking_type_id:r,date:i,time:o,agenda:d||null}),re.success("Session booked — check your Zoom link below."),c(null),u(""),n.invalidateQueries({queryKey:["coaching-booking-context",s]}),n.invalidateQueries({queryKey:["coaching-availability"]}),n.invalidateQueries({queryKey:["coaching-sessions",s]})}catch(ae){re.error(ae.message||"Could not book that session")}finally{m(!1)}}},X=async ae=>{if(await fo("Cancel this coaching session?"))try{await Xce({action:"cancel",session_id:ae}),re.success("Session cancelled"),n.invalidateQueries({queryKey:["coaching-booking-context",s]}),n.invalidateQueries({queryKey:["coaching-sessions",s]})}catch(ie){re.error(ie.message||"Could not cancel")}};return g?e.jsx(Ne,{children:e.jsxs(Ie,{className:"p-8 flex items-center justify-center text-muted-foreground gap-2",children:[e.jsx(kt,{className:"h-4 w-4 animate-spin"})," Loading your coach's calendar…"]})}):f!=null&&f.scheduler_ready?e.jsxs("div",{className:"space-y-4",children:[e.jsx(Ne,{children:e.jsxs(Ie,{className:"p-4 flex flex-wrap items-center justify-between gap-3",children:[e.jsxs("div",{className:"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(Kc,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{children:[e.jsxs("div",{className:"font-medium",children:[f.sessions_remaining," of ",f.sessions_limit," sessions left this month"]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Your allowance resets on the 1st."})]})]}),G&&e.jsx(Be,{variant:"secondary",children:"All booked up"})]})}),t.length>0&&e.jsx(Ne,{children:e.jsxs(Ie,{className:"p-4 space-y-3",children:[e.jsx("h3",{className:"font-semibold",children:"Upcoming sessions"}),t.map(ae=>e.jsxs("div",{className:"flex flex-wrap items-center gap-3 p-3 rounded-lg border",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"font-medium",children:en(new Date(ae.scheduled_at),"EEE, MMM d · p")}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[ae.duration_minutes||30," minutes"]})]}),ae.zoom_join_url&&e.jsx($,{size:"sm",variant:"outline",asChild:!0,children:e.jsxs("a",{href:ae.zoom_join_url,target:"_blank",rel:"noopener noreferrer",children:[e.jsx(ua,{className:"h-4 w-4 mr-1"})," Join"]})}),e.jsxs($,{size:"sm",variant:"ghost",onClick:()=>X(ae.id),children:[e.jsx(ku,{className:"h-4 w-4 mr-1"})," Cancel"]})]},ae.id))]})}),e.jsx(Ne,{children:e.jsxs(Ie,{className:"p-4 md:p-6 space-y-5",children:[e.jsxs("div",{children:[e.jsx(ee,{className:"mb-2 block",children:"Session type"}),e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-2",children:f.booking_types.map(ae=>e.jsxs("button",{onClick:()=>{a(ae.id),c(null)},className:`text-left p-3 rounded-lg border transition-colors ${r===ae.id?"border-primary bg-primary/5":"hover:bg-muted/50"}`,children:[e.jsx("div",{className:"font-medium",children:ae.name}),e.jsxs("div",{className:"text-xs text-muted-foreground flex items-center gap-1 mt-1",children:[e.jsx(da,{className:"h-3 w-3"})," ",ae.duration_minutes," min"]}),ae.description&&e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:ae.description})]},ae.id))})]}),e.jsxs("div",{className:"grid gap-5 lg:grid-cols-[minmax(0,1fr)_minmax(0,1fr)]",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx(ee,{className:"block",children:"Pick a day"}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx($,{size:"icon",variant:"ghost",className:"h-7 w-7",disabled:qae(y,x),onClick:()=>v(Mv(y,-1)),"aria-label":"Previous month",children:e.jsx(Cd,{className:"h-4 w-4"})}),e.jsx("span",{className:"text-sm font-medium w-28 text-center",children:en(y,"MMMM yyyy")}),e.jsx($,{size:"icon",variant:"ghost",className:"h-7 w-7",disabled:Xm(Mv(y,1))>w,onClick:()=>v(Mv(y,1)),"aria-label":"Next month",children:e.jsx(Di,{className:"h-4 w-4"})})]})]}),e.jsx("div",{className:"grid grid-cols-7 gap-1 mb-1",children:["S","M","T","W","T","F","S"].map((ae,ie)=>e.jsx("div",{className:"text-[11px] text-muted-foreground text-center py-1",children:ae},ie))}),e.jsx("div",{className:"grid grid-cols-7 gap-1",children:R.map((ae,ie)=>{if(!ae)return e.jsx("div",{},`b${ie}`);const ne=$7e(ae),te=(I[ne]||[]).length,ce=ae>=Mg(x)&&ae<=w&&te>0,_e=i===ne;return e.jsxs("button",{disabled:!ce,onClick:()=>{l(ne),c(null)},className:`aspect-square rounded-lg border text-sm flex flex-col items-center justify-center gap-1 transition-colors ${_e?"border-primary bg-primary text-primary-foreground":ce?"border-primary/30 bg-primary/5 hover:bg-primary/10 font-medium":"border-transparent text-muted-foreground/50 cursor-not-allowed"}`,title:ce?`${te} opening${te===1?"":"s"}`:"No openings",children:[e.jsx("span",{className:"leading-none",children:en(ae,"d")}),e.jsx("span",{className:`h-1.5 w-1.5 rounded-full ${_e?"bg-primary-foreground":ce?"bg-primary":"bg-transparent"}`})]},ne)})}),e.jsx("div",{className:"mt-3 flex items-center gap-2 text-xs text-muted-foreground",children:P?e.jsxs(e.Fragment,{children:[e.jsx(kt,{className:"h-3 w-3 animate-spin"})," Loading your coach's openings…"]}):e.jsxs(e.Fragment,{children:[e.jsx(Nn,{className:"h-3 w-3 text-primary"}),D.length===0?"No openings this month — try the next month.":`${D.length} day${D.length===1?"":"s"} with openings this month`]})})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"mb-2 block",children:i?`Available times · ${en(new Date(`${i}T12:00:00`),"EEE, MMM d")}`:"Available times"}),i?U?e.jsxs("div",{className:"text-sm text-muted-foreground flex items-center gap-2",children:[e.jsx(kt,{className:"h-4 w-4 animate-spin"})," Checking availability…"]}):O.length===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:"No openings on this day — try another date."}):e.jsx("div",{className:"space-y-3 max-h-[320px] overflow-y-auto pr-1",children:W.map(ae=>e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] uppercase tracking-wide text-muted-foreground mb-1",children:ae.label}),e.jsx("div",{className:"grid grid-cols-3 gap-2",children:ae.items.map(ie=>e.jsx("button",{onClick:()=>c(ie),className:`py-2 rounded-lg border text-sm transition-colors ${o===ie?"border-primary bg-primary/10 font-medium":"hover:bg-muted/50"}`,children:zvt(ie)},ie))})]},ae.label))}):e.jsx("div",{className:"rounded-lg border border-dashed p-6 text-sm text-muted-foreground text-center",children:"Select a highlighted day to see open times."}),!P&&D.length>0&&e.jsx("div",{className:"mt-3 flex flex-wrap gap-2",children:D.slice(0,3).map(([ae,ie])=>e.jsxs($,{size:"sm",variant:"outline",onClick:()=>{l(ae),c(null)},children:[en(new Date(`${ae}T12:00:00`),"EEE MMM d")," · ",ie.length," open"]},ae))})]})]}),o&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"agenda",children:"What do you want to work on? (optional)"}),e.jsx(Rs,{id:"agenda",rows:3,value:d,onChange:ae=>u(ae.target.value),placeholder:"Share context so your coach can prep."})]}),e.jsxs($,{onClick:Y,disabled:h||G,className:"bg-[#406E71] hover:bg-[#2a4c64]",children:[h?e.jsx(kt,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(qr,{className:"h-4 w-4 mr-1"}),"Book ",V==null?void 0:V.name," — ",i&&en(new Date(`${i}T12:00:00`),"MMM d")," at ",zvt(o)]}),G&&e.jsx("p",{className:"text-xs text-muted-foreground",children:"You've used your sessions for this month. Message your coach if you need more."})]})]})})]}):e.jsx(Ne,{children:e.jsx(Ie,{className:"p-8 text-center text-muted-foreground",children:"Your coach hasn't opened their coaching calendar yet. Check back soon."})})}function rUs(){const{user:s}=vs(),{isMember:t,pkg:n}=jC(),{data:r}=tt({queryKey:["coaching-prep-member",s==null?void 0:s.id,n==null?void 0:n.id],enabled:!!(s!=null&&s.id)&&!!(n!=null&&n.id),queryFn:async()=>{const[{data:l},{data:o},{data:c}]=await Promise.all([q.from("coaching_onboarding_forms").select("submitted_at").eq("user_id",s.id).maybeSingle(),q.from("coaching_prep_checklist_items").select("*").eq("package_id",n.id).eq("is_active",!0).order("sort_order"),q.from("coaching_prep_checklist_state").select("item_id").eq("user_id",s.id)]),d=new Set((c||[]).map(u=>u.item_id));return{submitted:!!(l!=null&&l.submitted_at),items:(o||[]).map(u=>({...u,done:d.has(u.id)}))}}});if(!t||!(n!=null&&n.includes_coaching))return null;const a=(r==null?void 0:r.items)||[],i=a.filter(l=>l.done).length;return e.jsxs(Ne,{children:[e.jsxs(Ct,{className:"flex flex-row items-center justify-between gap-2 space-y-0",children:[e.jsxs(At,{className:"text-base flex items-center gap-2",children:[e.jsx(zg,{className:"h-4 w-4 text-primary"})," Coaching prep"]}),a.length>0&&e.jsxs(Be,{variant:"secondary",children:[i,"/",a.length," done"]})]}),e.jsxs(Ie,{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3 rounded-lg border border-border/60 p-3",children:[e.jsxs("div",{className:"text-sm",children:[e.jsx("div",{className:"font-medium",children:"Onboarding questionnaire"}),e.jsx("div",{className:"text-muted-foreground text-xs",children:r!=null&&r.submitted?"Submitted — your coach has it.":"Complete this before session one."})]}),e.jsx($,{asChild:!0,size:"sm",variant:r!=null&&r.submitted?"outline":"default",children:e.jsx(wr,{to:"/coaching/onboarding",children:r!=null&&r.submitted?"Review":"Start"})})]}),a.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"What we're setting up for you"}),a.map(l=>e.jsxs("div",{className:"flex items-start gap-2 text-sm",children:[l.done?e.jsx(qr,{className:"h-4 w-4 mt-0.5 text-primary"}):e.jsx(Og,{className:"h-4 w-4 mt-0.5 text-muted-foreground/50"}),e.jsxs("span",{children:[e.jsx("span",{className:l.done?"text-muted-foreground line-through":"",children:l.title}),l.description&&e.jsx("span",{className:"block text-xs text-muted-foreground",children:l.description})]})]},l.id))]})]})]})}function aUs(){var m,f,g,x,y,v;const{user:s}=vs(),{data:t,isLoading:n,refetch:r}=Bst(),a=Vt(),i=t==null?void 0:t.id,{data:l=[]}=$st(i),{data:o=[]}=Ust(i);if(j.useEffect(()=>{new URLSearchParams(window.location.search).get("subscribed")==="1"&&q.functions.invoke("coaching-verify-checkout").then(()=>{r(),a.invalidateQueries({queryKey:["my-coaching-assignment"]})})},[r,a]),n)return e.jsx(Vs,{title:"My Coach",children:e.jsx("div",{className:"p-8",children:"Loading…"})});if(!t)return e.jsx(Vs,{title:"My Coach",children:e.jsxs("div",{className:"max-w-2xl mx-auto p-8 text-center",children:[e.jsx(of,{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(b=>b.status!=="done"),u=o.length-d.length,h=l.filter(b=>b.status!=="cancelled"&&new Date(b.scheduled_at).getTime()>Date.now());return e.jsx(Vs,{title:"My Coach",children:e.jsxs("div",{className:"p-4 md:p-8 max-w-5xl mx-auto space-y-6",children:[e.jsx(Ne,{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(Oa,{className:"h-24 w-24 ring-4 ring-white/20",children:[e.jsx(Li,{src:((m=c.coachProfile)==null?void 0:m.avatar_url)||void 0}),e.jsx(za,{className:"text-2xl bg-white/20 text-white",children:(((f=c.coachProfile)==null?void 0:f.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(Nn,{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:((g=c.coachProfile)==null?void 0:g.name)||"Your Coach"}),((x=c.coach)==null?void 0:x.headline)&&e.jsx("p",{className:"text-white/80 mt-1",children:c.coach.headline}),e.jsxs("div",{className:"flex gap-2 mt-3",children:[((y=c.coach)==null?void 0:y.is_certified)&&e.jsx(Be,{className:"bg-yellow-400/20 text-yellow-100 border-yellow-300/30",children:"LevelUp Certified"}),e.jsx(Be,{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(U7e,{icon:Ev,label:"Open action items",value:d.length}),e.jsx(U7e,{icon:rh,label:"Completed",value:u}),e.jsx(U7e,{icon:Ta,label:"Sessions",value:l.length})]}),e.jsx(rUs,{}),((v=c.coach)==null?void 0:v.id)&&e.jsx(sUs,{coachId:c.coach.id,assignmentId:i}),e.jsxs(ha,{defaultValue:"book",children:[e.jsxs(ma,{className:"flex flex-wrap h-auto w-full justify-start",children:[e.jsxs(Zt,{value:"book",children:[e.jsx(jv,{className:"h-4 w-4 mr-1 md:mr-2"}),e.jsx("span",{className:"hidden sm:inline",children:"Book"})]}),e.jsxs(Zt,{value:"actions",children:[e.jsx(Ev,{className:"h-4 w-4 mr-1 md:mr-2"}),e.jsx("span",{className:"hidden sm:inline",children:"Actions"})]}),e.jsxs(Zt,{value:"sessions",children:[e.jsx(Ta,{className:"h-4 w-4 mr-1 md:mr-2"}),e.jsx("span",{className:"hidden sm:inline",children:"Recaps"})]}),e.jsxs(Zt,{value:"goals",children:[e.jsx(rh,{className:"h-4 w-4 mr-1 md:mr-2"}),e.jsx("span",{className:"hidden sm:inline",children:"Goals"})]}),e.jsxs(Zt,{value:"kpis",children:[e.jsx(Yl,{className:"h-4 w-4 mr-1 md:mr-2"}),e.jsx("span",{className:"hidden sm:inline",children:"KPIs"})]}),e.jsxs(Zt,{value:"messages",children:[e.jsx(eo,{className:"h-4 w-4 mr-1 md:mr-2"}),e.jsx("span",{className:"hidden sm:inline",children:"Messages"})]}),e.jsxs(Zt,{value:"files",children:[e.jsx(_b,{className:"h-4 w-4 mr-1 md:mr-2"}),e.jsx("span",{className:"hidden sm:inline",children:"Files"})]})]}),e.jsx(Xt,{value:"book",children:e.jsx(nUs,{assignmentId:i,upcoming:h})}),e.jsx(Xt,{value:"actions",className:"space-y-2",children:o.length===0?e.jsx(Ne,{children:e.jsx(Ie,{className:"p-6 text-center text-muted-foreground",children:"Your coach hasn't assigned any action items yet."})}):o.map(b=>e.jsx(Ne,{children:e.jsxs(Ie,{className:"p-3 flex items-center gap-3",children:[e.jsx(ai,{checked:b.status==="done",onCheckedChange:async w=>{await q.from("coaching_action_items").update({status:w?"done":"open",completed_at:w?new Date().toISOString():null}).eq("id",b.id),a.invalidateQueries({queryKey:["coaching-action-items",i]})}}),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(Be,{variant:"outline",children:en(new Date(b.due_date),"MMM d")}),e.jsx(Be,{variant:"secondary",className:"capitalize",children:b.priority})]})},b.id))}),e.jsx(Xt,{value:"sessions",className:"space-y-3",children:l.length===0?e.jsx(Ne,{children:e.jsx(Ie,{className:"p-6 text-center text-muted-foreground",children:"No sessions logged yet."})}):l.map(b=>e.jsx(Ne,{children:e.jsxs(Ie,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx("span",{className:"font-medium",children:en(new Date(b.scheduled_at),"PPp")}),e.jsx(Be,{variant:"outline",className:"capitalize",children:b.status})]}),b.summary?e.jsx("p",{className:"text-sm whitespace-pre-wrap",children:b.summary}):e.jsx("p",{className:"text-sm text-muted-foreground italic",children:"Recap coming soon."})]})},b.id))}),e.jsx(Xt,{value:"goals",children:e.jsx(w$t,{assignmentId:i,canEdit:!1})}),e.jsx(Xt,{value:"kpis",children:s&&e.jsx(_$t,{agentUserId:s.id})}),e.jsx(Xt,{value:"messages",children:e.jsx(p$t,{assignmentId:i})}),e.jsx(Xt,{value:"files",children:e.jsx(j$t,{assignmentId:i})})]})]})})}function U7e({icon:s,label:t,value:n}){return e.jsx(Ne,{children:e.jsxs(Ie,{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:n}),e.jsx("div",{className:"text-xs text-muted-foreground mt-1",children:t})]})]})})}const Bvt="coaching_access",q7e=s=>((s==null?void 0:s.name)||(s==null?void 0:s.email)||"?").trim().slice(0,2).toUpperCase(),V7e=s=>!!s.expires_at&&new Date(s.expires_at).getTime()<=Date.now();function iUs(){const s=Vt(),[t,n]=j.useState(""),[r,a]=j.useState([]),[i,l]=j.useState(!1),[o,c]=j.useState(null),[d,u]=j.useState(""),{data:h=[],isLoading:m}=tt({queryKey:["coaching-entitlements"],queryFn:async()=>{const{data:D,error:O}=await q.from("feature_entitlements").select("id, user_id, enabled, expires_at, tier, notes, enabled_at").eq("feature_key",Bvt).order("enabled_at",{ascending:!1});if(O)throw O;return D||[]}}),{data:f=[]}=tt({queryKey:["coaching-assigned-agents"],queryFn:async()=>{const{data:D,error:O}=await q.from("coaching_assignments").select("agent_id, coach_id, status").eq("status","active");if(O)throw O;return D||[]}}),g=j.useMemo(()=>{const D=new Set;return h.forEach(O=>D.add(O.user_id)),f.forEach(O=>D.add(O.agent_id)),Array.from(D)},[h,f]),{data:x={}}=tt({queryKey:["coaching-access-profiles",g.join(",")],enabled:g.length>0,queryFn:async()=>{const D={};for(let O=0;O{D[W.id]=W})}return D}});j.useEffect(()=>{const D=t.trim();if(D.length<2){a([]),l(!1);return}l(!0);const O=setTimeout(async()=>{const{data:U}=await q.from("profiles").select("id, name, email, avatar_url").or(`email.ilike.%${D}%,name.ilike.%${D}%`).limit(12);a(U||[]),l(!1)},250);return()=>clearTimeout(O)},[t]);const y=j.useMemo(()=>{const D=new Map;return h.forEach(O=>D.set(O.user_id,O)),D},[h]),v=j.useMemo(()=>new Set(f.map(D=>D.agent_id)),[f]),b=()=>{s.invalidateQueries({queryKey:["coaching-entitlements"]}),s.invalidateQueries({queryKey:["coaching-access-profiles"]}),s.invalidateQueries({queryKey:["coaching-access"]})},w=async(D,O={})=>{var V;const{data:U}=await q.auth.getUser(),{error:W}=await q.from("feature_entitlements").upsert({user_id:D,feature_key:Bvt,enabled:O.enabled??!0,expires_at:O.expires_at??null,notes:O.notes??null,tier:O.tier??null,enabled_by:((V=U==null?void 0:U.user)==null?void 0:V.id)??null,enabled_at:new Date().toISOString(),updated_at:new Date().toISOString()},{onConflict:"user_id,feature_key"});return W?(re.error(W.message),!1):(b(),!0)},S=async D=>{await w(D.id)&&re.success(`Coaching access granted to ${D.name||D.email}`),n(""),a([])},C=async(D,O)=>{const{error:U}=await q.from("feature_entitlements").update({enabled:O,updated_at:new Date().toISOString()}).eq("id",D.id);if(U)return re.error(U.message);re.success(O?"Access enabled":"Access paused"),b()},E=async D=>{if(!await fo({title:"Revoke coaching access?",description:`${D.profile.name||D.profile.email||"This member"} will lose access to the coaching area unless they're assigned to a coach.`,confirmText:"Revoke access",destructive:!0}))return;const{error:U}=await q.from("feature_entitlements").delete().eq("id",D.entitlement.id);if(U)return re.error(U.message);re.success("Coaching access revoked"),b()},I=j.useMemo(()=>{const D=d.trim().toLowerCase(),O=h.map(U=>({entitlement:U,profile:x[U.user_id]}));return D?O.filter(({profile:U})=>`${(U==null?void 0:U.name)||""} ${(U==null?void 0:U.email)||""}`.toLowerCase().includes(D)):O},[h,x,d]),P=h.filter(D=>D.enabled&&!V7e(D)).length,R=f.filter(D=>!y.has(D.agent_id));return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-3 gap-3",children:[e.jsx(H7e,{icon:bm,label:"Granted access",value:P,hint:"Standalone entitlements"}),e.jsx(H7e,{icon:Zn,label:"Coached members",value:v.size,hint:"Active coach assignments"}),e.jsx(H7e,{icon:Nn,label:"Total with access",value:new Set([...h.filter(D=>D.enabled&&!V7e(D)).map(D=>D.user_id),...v]).size,hint:"Unique members"})]}),e.jsx(Ne,{children:e.jsxs(Ie,{className:"p-4 space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(KI,{className:"h-5 w-5 text-primary"}),e.jsx("h2",{className:"text-lg font-semibold",children:"Grant Coaching Access"})]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Give any member access to the coaching area — meeting notes, one-on-one scheduling and their coach workspace — even before a coach is assigned."}),e.jsxs("div",{className:"relative",children:[e.jsx(Kr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(pe,{className:"pl-9",placeholder:"Search members by name or email…",value:t,onChange:D=>n(D.target.value)})]}),t.trim().length>=2&&e.jsx("div",{className:"border rounded-lg divide-y max-h-80 overflow-auto",children:i?e.jsxs("div",{className:"p-3 text-sm text-muted-foreground flex items-center gap-2",children:[e.jsx(kt,{className:"h-4 w-4 animate-spin"})," Searching…"]}):r.length===0?e.jsx("div",{className:"p-3 text-sm text-muted-foreground",children:"No members found"}):r.map(D=>{const O=y.get(D.id),U=v.has(D.id);return e.jsxs("div",{className:"flex items-center gap-3 p-2.5 hover:bg-muted/40",children:[e.jsxs(Oa,{className:"h-8 w-8",children:[e.jsx(Li,{src:D.avatar_url||void 0}),e.jsx(za,{className:"text-xs",children:q7e(D)})]}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"font-medium truncate",children:D.name||D.email}),e.jsx("div",{className:"text-xs text-muted-foreground truncate",children:D.email})]}),O?e.jsx(Be,{variant:"outline",className:"shrink-0",children:"Already granted"}):U?e.jsxs(Be,{variant:"outline",className:"shrink-0",children:[e.jsx(bd,{className:"h-3 w-3 mr-1"}),"Has coach"]}):e.jsxs("div",{className:"flex gap-1.5 shrink-0",children:[e.jsx($,{size:"sm",variant:"outline",onClick:()=>c({profile:D}),children:"Options"}),e.jsxs($,{size:"sm",className:"bg-[#406E71] hover:bg-[#2a4c64]",onClick:()=>S(D),children:[e.jsx(sc,{className:"h-4 w-4 mr-1"})," Grant"]})]})]},D.id)})})]})}),e.jsx(Ne,{children:e.jsxs(Ie,{className:"p-4 space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx(bm,{className:"h-5 w-5 text-primary"}),e.jsx("h2",{className:"text-lg font-semibold",children:"Members with granted access"}),e.jsx(Be,{variant:"outline",children:h.length}),e.jsx("div",{className:"ml-auto w-full sm:w-64",children:e.jsx(pe,{placeholder:"Filter list…",value:d,onChange:D=>u(D.target.value)})})]}),m?e.jsxs("div",{className:"p-6 text-sm text-muted-foreground flex items-center gap-2",children:[e.jsx(kt,{className:"h-4 w-4 animate-spin"})," Loading…"]}):I.length===0?e.jsx("div",{className:"p-8 text-center text-sm text-muted-foreground border rounded-lg",children:"No standalone grants yet. Search above to give a member access."}):e.jsx("div",{className:"border rounded-lg divide-y",children:I.map(({entitlement:D,profile:O})=>{const U=V7e(D);return e.jsxs("div",{className:"flex items-center gap-3 p-3 flex-wrap",children:[e.jsxs(Oa,{className:"h-9 w-9",children:[e.jsx(Li,{src:(O==null?void 0:O.avatar_url)||void 0}),e.jsx(za,{className:"text-xs",children:q7e(O)})]}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"font-medium truncate",children:(O==null?void 0:O.name)||(O==null?void 0:O.email)||D.user_id}),e.jsx("div",{className:"text-xs text-muted-foreground truncate",children:O==null?void 0:O.email}),e.jsxs("div",{className:"flex items-center gap-2 mt-1 flex-wrap",children:[U?e.jsx(Be,{className:"bg-rose-500/15 text-rose-700 border-rose-300/40",children:"Expired"}):D.enabled?e.jsx(Be,{className:"bg-emerald-500/15 text-emerald-700 border-emerald-300/40",children:"Active"}):e.jsx(Be,{variant:"outline",children:"Paused"}),v.has(D.user_id)&&e.jsxs(Be,{variant:"outline",children:[e.jsx(bd,{className:"h-3 w-3 mr-1"}),"Has coach"]}),D.tier&&e.jsx(Be,{variant:"outline",children:D.tier}),D.expires_at&&e.jsxs("span",{className:"text-xs text-muted-foreground inline-flex items-center gap-1",children:[e.jsx(Au,{className:"h-3 w-3"}),U?"Expired":"Expires"," ",new Date(D.expires_at).toLocaleDateString()]})]}),D.notes&&e.jsx("p",{className:"text-xs text-muted-foreground mt-1 italic truncate",children:D.notes})]}),e.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[e.jsx(Sn,{checked:D.enabled&&!U,onCheckedChange:W=>C(D,W)}),e.jsx($,{size:"sm",variant:"outline",onClick:()=>c({profile:O||{id:D.user_id,name:null,email:null},entitlement:D}),children:"Edit"}),e.jsx($,{size:"sm",variant:"ghost",className:"text-rose-600 hover:bg-rose-50",onClick:()=>E({profile:O||{id:D.user_id,name:null,email:null},entitlement:D}),children:e.jsx(gr,{className:"h-4 w-4"})})]})]},D.id)})})]})}),e.jsx(Ne,{children:e.jsxs(Ie,{className:"p-4 space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Zn,{className:"h-5 w-5 text-primary"}),e.jsx("h2",{className:"text-lg font-semibold",children:"Access through a coach assignment"}),e.jsx(Be,{variant:"outline",children:R.length})]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"These members already reach coaching because they're assigned to a coach — no entitlement needed."}),R.length===0?e.jsx("div",{className:"p-6 text-center text-sm text-muted-foreground border rounded-lg",children:"No active assignments."}):e.jsx("div",{className:"flex flex-wrap gap-2",children:R.map(D=>{const O=x[D.agent_id];return e.jsxs("div",{className:"flex items-center gap-2 border rounded-full pl-1 pr-3 py-1",children:[e.jsxs(Oa,{className:"h-6 w-6",children:[e.jsx(Li,{src:(O==null?void 0:O.avatar_url)||void 0}),e.jsx(za,{className:"text-[10px]",children:q7e(O)})]}),e.jsx("span",{className:"text-sm",children:(O==null?void 0:O.name)||(O==null?void 0:O.email)||D.agent_id})]},D.agent_id)})})]})}),e.jsx(oUs,{state:o,onClose:()=>c(null),onSave:async D=>{if(!o)return;await w(o.profile.id,D)&&(re.success("Coaching access saved"),c(null))}})]})}function H7e({icon:s,label:t,value:n,hint:r}){return e.jsx(Ne,{children:e.jsxs(Ie,{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:n}),e.jsx("div",{className:"text-sm font-medium",children:t}),e.jsx("div",{className:"text-xs text-muted-foreground",children:r})]})]})})}function oUs({state:s,onClose:t,onSave:n}){const[r,a]=j.useState(""),[i,l]=j.useState(""),[o,c]=j.useState(""),[d,u]=j.useState(!0),[h,m]=j.useState(!1);j.useEffect(()=>{if(!s)return;const g=s.entitlement;a(g!=null&&g.expires_at?g.expires_at.slice(0,10):""),l((g==null?void 0:g.notes)||""),c((g==null?void 0:g.tier)||""),u(g?g.enabled:!0)},[s]);const f=async()=>{m(!0),await n({expires_at:r?new Date(`${r}T23:59:59`).toISOString():null,notes:i.trim()||null,tier:o.trim()||null,enabled:d}),m(!1)};return e.jsx(zs,{open:!!s,onOpenChange:g=>!g&&t(),children:e.jsxs(Os,{children:[e.jsx(Us,{children:e.jsx(Bs,{children:s!=null&&s.entitlement?"Edit coaching access":"Grant coaching access"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"text-sm",children:[e.jsx("div",{className:"font-medium",children:(s==null?void 0:s.profile.name)||(s==null?void 0:s.profile.email)}),e.jsx("div",{className:"text-xs text-muted-foreground",children:s==null?void 0:s.profile.email})]}),e.jsxs("div",{className:"flex items-center justify-between border rounded-lg p-3",children:[e.jsxs("div",{children:[e.jsx(ee,{children:"Access enabled"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Turn off to pause without removing the grant."})]}),e.jsx(Sn,{checked:d,onCheckedChange:u})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Expires on (optional)"}),e.jsx(pe,{type:"date",value:r,onChange:g=>a(g.target.value)}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Leave blank for ongoing access."})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Tier / plan label (optional)"}),e.jsx(pe,{value:o,onChange:g=>c(g.target.value),placeholder:"e.g. Premium, Beta, Comp"})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Internal notes"}),e.jsx(Rs,{value:i,onChange:g=>l(g.target.value),rows:3,placeholder:"Why this member has access…"})]})]}),e.jsxs(Ar,{children:[e.jsx($,{variant:"outline",onClick:t,children:"Cancel"}),e.jsx($,{onClick:f,disabled:h,className:"bg-[#406E71] hover:bg-[#2a4c64]",children:h?"Saving…":"Save access"})]})]})})}function lUs(){const s=Vt(),[t,n]=j.useState(""),[r,a]=j.useState("active"),{data:i=[]}=tt({queryKey:["admin-coaches-lite"],queryFn:async()=>{const{data:f,error:g}=await q.from("coaches").select("id, user_id");if(g)throw g;const x=(f||[]).map(b=>b.user_id);if(!x.length)return[];const{data:y}=await q.from("profiles").select("id, name, email").in("id",x),v=new Map((y||[]).map(b=>[b.id,b]));return(f||[]).map(b=>{var w,S;return{id:b.id,label:((w=v.get(b.user_id))==null?void 0:w.name)||((S=v.get(b.user_id))==null?void 0:S.email)||b.user_id}})}}),{data:l=[],isLoading:o}=tt({queryKey:["admin-coaching-assignments"],queryFn:async()=>{const{data:f,error:g}=await q.from("coaching_assignments").select("*").order("created_at",{ascending:!1});if(g)throw g;const x=[...new Set((f||[]).map(b=>b.agent_id))],{data:y}=x.length?await q.from("profiles").select("id, name, email").in("id",x):{data:[]},v=new Map((y||[]).map(b=>[b.id,b]));return(f||[]).map(b=>({...b,agent:v.get(b.agent_id)}))}}),c=f=>{var g;return((g=i.find(x=>x.id===f))==null?void 0:g.label)||"—"},d=j.useMemo(()=>{const f=t.trim().toLowerCase();return l.filter(g=>{var x,y;return r!=="all"&&g.status!==r?!1:f?(((x=g.agent)==null?void 0:x.name)||"").toLowerCase().includes(f)||(((y=g.agent)==null?void 0:y.email)||"").toLowerCase().includes(f)||c(g.coach_id).toLowerCase().includes(f):!0})},[l,t,r,i]),u=()=>{s.invalidateQueries({queryKey:["admin-coaching-assignments"]}),s.invalidateQueries({queryKey:["coach-roster"]})},h=async(f,g)=>{var v,b;if(g===f.coach_id||!await fo({title:"Switch coach?",description:`${((v=f.agent)==null?void 0:v.name)||((b=f.agent)==null?void 0:b.email)} will move from ${c(f.coach_id)} to ${c(g)}. Session history stays with the assignment.`,confirmText:"Switch coach"}))return;const{error:y}=await q.from("coaching_assignments").update({coach_id:g}).eq("id",f.id);if(y)return re.error(y.message);re.success("Coach switched"),u()},m=async(f,g)=>{var y,v;if(g==="ended"&&!await fo({title:"End assignment?",description:`${((y=f.agent)==null?void 0:y.name)||((v=f.agent)==null?void 0:v.email)} will lose access to the coaching workspace unless they have standalone access.`,confirmText:"End assignment",destructive:!0}))return;const{error:x}=await q.from("coaching_assignments").update({status:g,ended_at:g==="ended"?new Date().toISOString():null}).eq("id",f.id);if(x)return re.error(x.message);re.success(g==="ended"?"Assignment ended":"Assignment reactivated"),u()};return e.jsx(Ne,{children:e.jsxs(Ie,{className:"p-4 space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Zn,{className:"h-5 w-5 text-primary"}),e.jsx("h2",{className:"text-lg font-semibold",children:"Coach assignments"}),e.jsx(Be,{variant:"secondary",className:"ml-auto",children:d.length})]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Switch an agent to a different coach, end an assignment, or reactivate a past one."}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-2",children:[e.jsx(pe,{placeholder:"Search by agent or coach…",value:t,onChange:f=>n(f.target.value)}),e.jsxs(ms,{value:r,onValueChange:f=>a(f),children:[e.jsx(us,{className:"sm:w-40",children:e.jsx(fs,{})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"active",children:"Active"}),e.jsx(Ge,{value:"ended",children:"Ended"}),e.jsx(Ge,{value:"all",children:"All"})]})]})]}),o?e.jsx("div",{className:"text-sm text-muted-foreground",children:"Loading…"}):d.length===0?e.jsx("div",{className:"text-sm text-muted-foreground py-6 text-center",children:"No assignments found."}):e.jsx("div",{className:"divide-y border rounded-md",children:d.map(f=>{var g,x,y;return e.jsxs("div",{className:"p-3 flex flex-col md:flex-row md:items-center gap-3",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"font-medium truncate",children:((g=f.agent)==null?void 0:g.name)||((x=f.agent)==null?void 0:x.email)||f.agent_id}),e.jsxs("div",{className:"text-xs text-muted-foreground truncate",children:[(y=f.agent)==null?void 0:y.email," · ",f.pipeline_stage||"onboarding",f.status==="ended"&&" · ended"]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(gJ,{className:"h-4 w-4 text-muted-foreground shrink-0"}),e.jsxs(ms,{value:f.coach_id,onValueChange:v=>h(f,v),children:[e.jsx(us,{className:"w-full md:w-56 h-9",children:e.jsx(fs,{})}),e.jsx(hs,{children:i.map(v=>e.jsx(Ge,{value:v.id,children:v.label},v.id))})]}),f.status==="active"?e.jsxs($,{variant:"outline",size:"sm",onClick:()=>m(f,"ended"),children:[e.jsx(mV,{className:"h-4 w-4 mr-1"})," End"]}):e.jsxs($,{variant:"outline",size:"sm",onClick:()=>m(f,"active"),children:[e.jsx(Ex,{className:"h-4 w-4 mr-1"})," Reactivate"]})]})]},f.id)})})]})})}function cUs(){const s=Vt(),[t,n]=j.useState(""),[r,a]=j.useState([]),[i,l]=j.useState(null),{data:o=[],isLoading:c}=tt({queryKey:["admin-coaches"],queryFn:async()=>{const{data:h,error:m}=await q.from("coaches").select("*").order("created_at",{ascending:!1});if(m)throw m;if(!(h!=null&&h.length))return[];const f=h.map(y=>y.user_id),{data:g}=await q.from("profiles").select("id, name, email, avatar_url").in("id",f),x=new Map((g||[]).map(y=>[y.id,y]));return h.map(y=>({...y,profile:x.get(y.user_id)}))}});j.useEffect(()=>{const h=t.trim();if(h.length<2){a([]);return}const m=setTimeout(async()=>{const{data:f}=await q.from("profiles").select("id, email, name, avatar_url").or(`email.ilike.%${h}%,name.ilike.%${h}%`).limit(10);a(f||[])},250);return()=>clearTimeout(m)},[t]);const d=async h=>{const{error:m}=await q.functions.invoke("manage-user-roles",{body:{userId:h.id,role:"coach",action:"add"}});if(m)return re.error(m.message);const{error:f}=await q.from("coaches").insert({user_id:h.id});if(f&&!String(f.message).includes("duplicate"))return re.error(f.message);re.success(`${h.name||h.email} is now a coach`),n(""),a([]),s.invalidateQueries({queryKey:["admin-coaches"]})},u=async(h,m)=>{const{error:f}=await q.from("coaches").update({is_certified:m}).eq("id",h);if(f)return re.error(f.message);re.success(m?"Marked Certified":"Removed certification"),s.invalidateQueries({queryKey:["admin-coaches"]})};return e.jsxs(Vs,{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(of,{className:"h-7 w-7 text-primary"}),e.jsx("h1",{className:"text-2xl font-bold",children:"LevelUp Coaching"})]}),e.jsxs(ha,{defaultValue:"coaches",className:"space-y-6",children:[e.jsxs(ma,{className:"flex-wrap h-auto",children:[e.jsx(Zt,{value:"coaches",children:"Coaches"}),e.jsx(Zt,{value:"assignments",children:"Assignments"}),e.jsx(Zt,{value:"access",children:"Coaching Access"}),e.jsx(Zt,{value:"applications",children:"Applications"}),e.jsx(Zt,{value:"settings",children:"Settings"})]}),e.jsx(Xt,{value:"assignments",className:"space-y-6",children:e.jsx(lUs,{})}),e.jsx(Xt,{value:"access",className:"space-y-6",children:e.jsx(iUs,{})}),e.jsx(Xt,{value:"applications",className:"space-y-6",children:e.jsx(hUs,{})}),e.jsx(Xt,{value:"settings",className:"space-y-6",children:e.jsx(dUs,{})}),e.jsxs(Xt,{value:"coaches",className:"space-y-6",children:[e.jsx(Ne,{children:e.jsxs(Ie,{className:"p-4 space-y-3",children:[e.jsx(pe,{placeholder:"Search by user email or name…",value:t,onChange:h=>n(h.target.value)}),t.trim().length>=2&&e.jsx("div",{className:"border rounded-md divide-y max-h-72 overflow-auto",children:r.length===0?e.jsx("div",{className:"p-3 text-sm text-muted-foreground",children:"No users found"}):r.map(h=>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:h.name||h.email}),e.jsx("div",{className:"text-xs text-muted-foreground truncate",children:h.email})]}),e.jsxs($,{size:"sm",onClick:()=>d(h),children:[e.jsx(dn,{className:"h-4 w-4 mr-1"})," Make Coach"]})]},h.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(Ne,{children:e.jsx(Ie,{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(h=>{var m,f,g;return e.jsx(Ne,{children:e.jsxs(Ie,{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:((m=h.profile)==null?void 0:m.name)||((f=h.profile)==null?void 0:f.email)||h.user_id}),e.jsx("div",{className:"text-xs text-muted-foreground",children:(g=h.profile)==null?void 0:g.email}),e.jsxs("div",{className:"flex gap-2 mt-2 flex-wrap",children:[h.is_certified&&e.jsxs(Be,{className:"bg-yellow-500/15 text-yellow-700 border-yellow-300/40",children:[e.jsx(Nn,{className:"h-3 w-3 mr-1"}),"Certified"]}),h.accepting_clients&&e.jsx(Be,{variant:"outline",children:"Accepting clients"})]})]}),e.jsxs($,{size:"sm",variant:"outline",onClick:()=>l(h.id),children:[e.jsx(sc,{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(Sn,{checked:h.is_certified,onCheckedChange:x=>u(h.id,x)})]})]})},h.id)})})]})]})]})]}),e.jsx(uUs,{coachId:i,onClose:()=>l(null)})]})}function dUs(){const[s,t]=j.useState("1500"),[n,r]=j.useState(!1),[a,i]=j.useState(!1);j.useEffect(()=>{(async()=>{const{data:c}=await q.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 re.error("Enter a value between 0 and 5000 bps (0–50%)");r(!0);const{error:d}=await q.from("settings").upsert({key:"coaching_platform_fee_bps",value:String(c)});if(r(!1),d)return re.error(d.message);re.success("Platform fee updated")};if(!a)return null;const o=(parseInt(s,10)/100).toFixed(2);return e.jsx(Ne,{children:e.jsxs(Ie,{className:"p-4 space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Rw,{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(ee,{children:"Fee (bps)"}),e.jsx(pe,{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($,{onClick:l,disabled:n,className:"bg-[#406E71] hover:bg-[#2a4c64] self-end",children:n?"Saving…":"Save"})]})]})})}function uUs({coachId:s,onClose:t}){const[n,r]=j.useState(""),[a,i]=j.useState([]),[l,o]=j.useState(!1),c=Vt();j.useEffect(()=>{if(!s){r(""),i([]);return}},[s]),j.useEffect(()=>{const u=n.trim();if(u.length<2){i([]);return}o(!0);const h=setTimeout(async()=>{const{data:m}=await q.from("profiles").select("id, name, email").or(`email.ilike.%${u}%,name.ilike.%${u}%`).limit(15);i(m||[]),o(!1)},250);return()=>clearTimeout(h)},[n]);const d=async u=>{const{error:h}=await q.from("coaching_assignments").insert({coach_id:s,agent_id:u,status:"active",source:"admin",pipeline_stage:"onboarding"});if(h)return re.error(h.message);re.success("Agent assigned"),c.invalidateQueries({queryKey:["coach-roster"]}),t()};return e.jsx(zs,{open:!!s,onOpenChange:u=>!u&&t(),children:e.jsxs(Os,{children:[e.jsx(Us,{children:e.jsx(Bs,{children:"Assign Agent"})}),e.jsx(pe,{placeholder:"Search agents by name or email…",value:n,onChange:u=>r(u.target.value),autoFocus:!0}),e.jsx("div",{className:"space-y-1 max-h-72 overflow-auto border rounded-md",children:n.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(u=>e.jsxs("button",{onClick:()=>d(u.id),className:"w-full text-left p-2 hover:bg-muted",children:[e.jsx("div",{className:"font-medium",children:u.name||u.email}),e.jsx("div",{className:"text-xs text-muted-foreground",children:u.email})]},u.id))}),e.jsx(Ar,{children:e.jsx($,{variant:"outline",onClick:t,children:"Close"})})]})})}function hUs(){const s=Vt(),[t,n]=j.useState("pending"),[r,a]=j.useState(null),{data:i=[],isLoading:l}=tt({queryKey:["coach-applications",t],queryFn:async()=>{let u=q.from("coach_applications").select("*").order("created_at",{ascending:!1});t!=="all"&&(u=u.eq("status",t));const{data:h,error:m}=await u;if(m)throw m;return h||[]}}),{data:o=0}=tt({queryKey:["coach-applications-pending-count"],queryFn:async()=>{const{count:u}=await q.from("coach_applications").select("id",{count:"exact",head:!0}).eq("status","pending");return u||0}}),c=async(u,h)=>{const{error:m}=await q.from("coach_applications").update({status:h,reviewed_at:new Date().toISOString()}).eq("id",u);if(m)return re.error(m.message);re.success(`Marked ${h}`),s.invalidateQueries({queryKey:["coach-applications"]}),s.invalidateQueries({queryKey:["coach-applications-pending-count"]}),a(null)},d=u=>u==="approved"?e.jsxs(Be,{className:"bg-emerald-500/15 text-emerald-700 border-emerald-300/40",children:[e.jsx(la,{className:"h-3 w-3 mr-1"}),"Approved"]}):u==="rejected"?e.jsxs(Be,{className:"bg-rose-500/15 text-rose-700 border-rose-300/40",children:[e.jsx(gr,{className:"h-3 w-3 mr-1"}),"Rejected"]}):e.jsxs(Be,{className:"bg-yellow-500/15 text-yellow-700 border-yellow-300/40",children:[e.jsx(da,{className:"h-3 w-3 mr-1"}),"Pending"]});return e.jsxs(Ne,{children:[e.jsxs(Ie,{className:"p-4 space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx(Gz,{className:"h-5 w-5 text-primary"}),e.jsx("h2",{className:"text-lg font-semibold",children:"Coach Applications"}),o>0&&e.jsxs(Be,{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(u=>e.jsx($,{size:"sm",variant:t===u?"default":"outline",onClick:()=>n(u),className:t===u?"bg-[#406E71] hover:bg-[#2a4c64]":"",children:u.charAt(0).toUpperCase()+u.slice(1)},u))})]}),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(u=>e.jsx("button",{onClick:()=>a(u),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:u.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(mn,{className:"h-3 w-3"}),u.email]}),u.brokerage&&e.jsxs("span",{children:["· ",u.brokerage]}),u.years_experience&&e.jsxs("span",{children:["· ",u.years_experience," yrs"]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[d(u.status),e.jsx("span",{className:"text-xs text-muted-foreground",children:new Date(u.created_at).toLocaleDateString()})]})]})},u.id))})]}),e.jsx(zs,{open:!!r,onOpenChange:u=>!u&&a(null),children:e.jsx(Os,{className:"max-w-2xl max-h-[85vh] overflow-y-auto",children:r&&e.jsxs(e.Fragment,{children:[e.jsx(Us,{children:e.jsxs(Bs,{className:"flex items-center gap-3",children:[r.full_name,d(r.status)]})}),e.jsxs("div",{className:"space-y-4 text-sm",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsx(S$,{icon:mn,label:"Email",value:r.email,link:`mailto:${r.email}`}),r.phone&&e.jsx(S$,{icon:Da,label:"Phone",value:r.phone,link:`tel:${r.phone}`}),r.brokerage&&e.jsx(S$,{label:"Brokerage",value:r.brokerage}),r.years_experience&&e.jsx(S$,{label:"Years",value:r.years_experience}),r.website_url&&e.jsx(S$,{icon:kr,label:"Website",value:r.website_url,link:r.website_url}),r.linkedin_url&&e.jsx(S$,{icon:kr,label:"LinkedIn",value:r.linkedin_url,link:r.linkedin_url})]}),r.specialties&&e.jsx(G7e,{label:"Specialties",children:r.specialties}),e.jsx(G7e,{label:"Why they want to coach",children:r.why_coach}),r.results_story&&e.jsx(G7e,{label:"Results story",children:r.results_story}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs font-semibold uppercase text-muted-foreground",children:"Admin notes"}),e.jsx(Rs,{defaultValue:r.admin_notes||"",rows:3,onBlur:async u=>{const h=u.target.value;h!==(r.admin_notes||"")&&(await q.from("coach_applications").update({admin_notes:h}).eq("id",r.id),s.invalidateQueries({queryKey:["coach-applications"]}))},placeholder:"Internal notes (saved on blur)…"})]})]}),e.jsxs(Ar,{className:"gap-2 flex-wrap",children:[r.status!=="rejected"&&e.jsxs($,{variant:"outline",onClick:()=>c(r.id,"rejected"),className:"text-rose-600 border-rose-200 hover:bg-rose-50",children:[e.jsx(gr,{className:"h-4 w-4 mr-1"})," Reject"]}),r.status!=="pending"&&e.jsxs($,{variant:"outline",onClick:()=>c(r.id,"pending"),children:[e.jsx(da,{className:"h-4 w-4 mr-1"})," Move to pending"]}),r.status!=="approved"&&e.jsxs($,{onClick:()=>c(r.id,"approved"),className:"bg-emerald-600 hover:bg-emerald-700",children:[e.jsx(la,{className:"h-4 w-4 mr-1"})," Approve"]})]})]})})})]})}function S$({icon:s,label:t,value:n,link:r}){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"}),n]});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:r?e.jsx("a",{href:r,target:"_blank",rel:"noreferrer",className:"text-[#406E71] hover:underline break-all",children:a}):a})]})}function G7e({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 mUs(){const s=Qn(),{data:t}=eie(),n=Vt(),[r,a]=j.useState(!1),[i,l]=j.useState(!1),[o,c]=j.useState(null),{data:d,refetch:u}=tt({queryKey:["coach-stripe-status",t==null?void 0:t.id],enabled:!!t,queryFn:async()=>{const{data:y}=await q.functions.invoke("coach-stripe-status");return y}}),{data:h=[]}=tt({queryKey:["coach-packages",t==null?void 0:t.id],enabled:!!t,queryFn:async()=>{const{data:y}=await q.from("coaching_packages").select("*").eq("coach_id",t.id).order("sort_order");return y||[]}});j.useEffect(()=>{const y=new URLSearchParams(window.location.search);(y.get("onboarded")||y.get("refresh"))&&u()},[u]);const m=async()=>{var w,S;a(!0);const{data:y,error:v}=await q.functions.invoke("coach-stripe-connect");a(!1);let b=y==null?void 0:y.error;if(!b&&v)try{const C=await((S=(w=v==null?void 0:v.context)==null?void 0:w.json)==null?void 0:S.call(w));b=(C==null?void 0:C.error)||v.message}catch{b=v.message}if(b)return re.error(b,{duration:1e4});y!=null&&y.url&&(window.location.href=y.url)},f=d||{},g=!!(t!=null&&t.use_platform_stripe),x=g||f.connected&&f.charges_enabled;return e.jsx(Vs,{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($,{variant:"ghost",size:"icon",onClick:()=>s("/coaching"),children:e.jsx(qa,{className:"h-5 w-5"})}),e.jsx("h1",{className:"text-2xl font-bold",children:"Billing & Packages"})]}),e.jsx(Ne,{children:e.jsxs(Ie,{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(Cv,{className:"h-5 w-5"})," Stripe Connect"]}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:g?"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."})]}),x?e.jsxs(Be,{className:"bg-emerald-500/15 text-emerald-700 border-emerald-300/40 flex items-center gap-1",children:[e.jsx(qr,{className:"h-3 w-3"})," ",g?"Using LevelUp billing":"Connected"]}):f.connected?e.jsxs(Be,{variant:"secondary",className:"flex items-center gap-1",children:[e.jsx(ll,{className:"h-3 w-3"})," Setup incomplete"]}):e.jsx(Be,{variant:"outline",children:"Not connected"})]}),!g&&e.jsxs($,{onClick:m,disabled:r,className:"bg-[#406E71] hover:bg-[#2a4c64]",children:[x?"Update Stripe details":f.connected?"Finish Stripe setup":"Connect Stripe",e.jsx(kr,{className:"h-4 w-4 ml-1"})]})]})}),e.jsx(Ne,{children:e.jsxs(Ie,{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($,{size:"sm",onClick:()=>{c(null),l(!0)},disabled:!x,children:[e.jsx(dn,{className:"h-4 w-4 mr-1"})," New Package"]})]}),!x&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"Connect Stripe before creating packages."}),h.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:h.map(y=>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:[y.name,y.is_active&&y.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:["$",(y.price_cents/100).toFixed(0)," / ",y.billing_interval,!y.is_active&&" · Inactive"]})]}),e.jsx($,{variant:"ghost",size:"icon",onClick:()=>{c(y),l(!0)},children:e.jsx(gi,{className:"h-4 w-4"})}),e.jsx($,{variant:"ghost",size:"icon",onClick:async()=>{await fo("Delete this package?")&&(await q.from("coaching_packages").delete().eq("id",y.id),n.invalidateQueries({queryKey:["coach-packages",t==null?void 0:t.id]}))},children:e.jsx(Wn,{className:"h-4 w-4"})})]},y.id))})]})}),e.jsx(fUs,{open:i,onOpenChange:l,coachId:t==null?void 0:t.id,pkg:o,onSaved:()=>n.invalidateQueries({queryKey:["coach-packages",t==null?void 0:t.id]})})]})})}function fUs({open:s,onOpenChange:t,coachId:n,pkg:r,onSaved:a}){const[i,l]=j.useState(""),[o,c]=j.useState(""),[d,u]=j.useState(""),[h,m]=j.useState("month"),[f,g]=j.useState(!0),[x,y]=j.useState(!0),[v,b]=j.useState(!1);j.useEffect(()=>{s&&(l((r==null?void 0:r.name)||""),c((r==null?void 0:r.description)||""),u(r?(r.price_cents/100).toString():""),m((r==null?void 0:r.billing_interval)||"month"),g((r==null?void 0:r.is_active)??!0),y((r==null?void 0:r.accepting_clients)??!0))},[s,r]);const w=async()=>{if(!i.trim()||!d)return re.error("Name and price required");b(!0);const S={coach_id:n,name:i,description:o||null,price_cents:Math.round(Number(d)*100),billing_interval:h,is_active:f,accepting_clients:x},{error:C}=r!=null&&r.id?await q.from("coaching_packages").update(S).eq("id",r.id):await q.from("coaching_packages").insert(S);if(b(!1),C)return re.error(C.message);re.success("Saved"),a==null||a(),t(!1)};return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Os,{children:[e.jsx(Us,{children:e.jsx(Bs,{children:r!=null&&r.id?"Edit Package":"New Package"})}),e.jsxs("div",{className:"space-y-3",children:[e.jsx(pe,{placeholder:"Name (e.g. Accelerator)",value:i,onChange:S=>l(S.target.value)}),e.jsx(Rs,{rows:3,placeholder:"What's included",value:o,onChange:S=>c(S.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(pe,{type:"number",value:d,onChange:S=>u(S.target.value)})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-muted-foreground",children:"Interval"}),e.jsxs(ms,{value:h,onValueChange:m,children:[e.jsx(us,{children:e.jsx(fs,{})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"month",children:"Monthly"}),e.jsx(Ge,{value:"year",children:"Yearly"}),e.jsx(Ge,{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:f,onChange:S=>g(S.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:x,onChange:S=>y(S.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(Ar,{children:[e.jsx($,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsx($,{onClick:w,disabled:v,children:r!=null&&r.id?"Save":"Create"})]})]})})}function $vt({kind:s,value:t,onChange:n}){const r=j.useRef(null),[a,i]=j.useState(!1),[l,o]=j.useState(!1),[c,d]=j.useState(null),u=j.useRef(null),h=j.useRef(null),m=j.useRef(null),f=j.useRef([]),[g,x]=j.useState(!1),y=s==="photo"?"image/*":"video/*",v=s==="photo"?10*1024*1024:200*1024*1024,b=async(P,R)=>{var G;const{data:D}=await q.auth.getUser(),O=(G=D.user)==null?void 0:G.id;if(!O)return re.error("Not signed in");if(P.size>v)return re.error(`File too large. Max ${s==="photo"?"10MB":"200MB"}.`);i(!0);const U=`${O}/${s}-${Date.now()}.${R}`,{error:W}=await q.storage.from("coach-media").upload(U,P,{upsert:!0,contentType:P.type||(s==="photo"?"image/jpeg":"video/webm")});if(W)return i(!1),re.error(W.message);const{data:V}=await q.storage.from("coach-media").createSignedUrl(U,60*60*24*365*10);i(!1),V!=null&&V.signedUrl&&(n(V.signedUrl),re.success("Uploaded"),d(null))},w=async P=>{const R=P.name.split(".").pop()||(s==="photo"?"jpg":"webm");await b(P,R)},S=async()=>{try{const P=await navigator.mediaDevices.getUserMedia({video:!0,audio:!0});h.current=P,x(!0),setTimeout(()=>{u.current&&(u.current.srcObject=P,u.current.play())},50);const R=new MediaRecorder(P,{mimeType:"video/webm"});f.current=[],R.ondataavailable=D=>D.data.size>0&&f.current.push(D.data),R.onstop=()=>{const D=new Blob(f.current,{type:"video/webm"});d(D),P.getTracks().forEach(O=>O.stop())},m.current=R,R.start(),o(!0)}catch(P){re.error(P.message||"Could not access camera")}},C=()=>{var P;(P=m.current)==null||P.stop(),o(!1)},E=()=>{var P;(P=h.current)==null||P.getTracks().forEach(R=>R.stop()),x(!1),o(!1),d(null)},I=async()=>{c&&(await b(c,"webm"),E())};return j.useEffect(()=>()=>{var P;return(P=h.current)==null?void 0:P.getTracks().forEach(R=>R.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:r,type:"file",accept:y,className:"hidden",onChange:P=>{var D;const R=(D=P.target.files)==null?void 0:D[0];R&&w(R),P.target.value=""}}),e.jsxs($,{type:"button",variant:"outline",size:"sm",disabled:a,onClick:()=>{var P;return(P=r.current)==null?void 0:P.click()},children:[a?e.jsx(kt,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(ni,{className:"h-4 w-4 mr-1"}),s==="photo"?"Upload photo":"Upload video"]}),s==="video"&&e.jsxs($,{type:"button",variant:"outline",size:"sm",onClick:S,disabled:a||g,children:[e.jsx(Cx,{className:"h-4 w-4 mr-1"})," Record intro"]}),t&&e.jsxs($,{type:"button",variant:"ghost",size:"sm",onClick:()=>n(""),children:[e.jsx(Wn,{className:"h-4 w-4 mr-1"})," Remove"]})]}),g&&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:u,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($,{type:"button",size:"sm",onClick:C,className:"bg-red-600 hover:bg-red-700",children:[e.jsx(C_,{className:"h-4 w-4 mr-1"})," Stop"]}),!c&&!l&&e.jsxs($,{type:"button",size:"sm",onClick:()=>{var P;return(P=m.current)==null?void 0:P.start()},children:[e.jsx(ua,{className:"h-4 w-4 mr-1"})," Start"]}),c&&e.jsxs(e.Fragment,{children:[e.jsxs($,{type:"button",size:"sm",onClick:I,disabled:a,className:"bg-[#406E71] hover:bg-[#2a4c64]",children:[a?e.jsx(kt,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(ni,{className:"h-4 w-4 mr-1"}),"Use this recording"]}),e.jsx($,{type:"button",size:"sm",variant:"outline",onClick:()=>{d(null),S()},children:"Re-record"})]}),e.jsx($,{type:"button",size:"sm",variant:"ghost",onClick:E,children:"Cancel"})]})]})]})}function N$t(){const{user:s}=vs(),t=Vt(),n=tt({queryKey:["booking-settings",s==null?void 0:s.id],queryFn:async()=>{const{data:y,error:v}=await q.from("agent_booking_settings").select("*").eq("user_id",s.id).maybeSingle();if(v)throw v;return y},enabled:!!s}),r=tt({queryKey:["booking-types",s==null?void 0:s.id],queryFn:async()=>{const{data:y,error:v}=await q.from("agent_booking_types").select("*").eq("user_id",s.id).order("sort_order");if(v)throw v;return y},enabled:!!s}),a=tt({queryKey:["availability-slots",s==null?void 0:s.id],queryFn:async()=>{const{data:y,error:v}=await q.from("agent_availability_slots").select("*").eq("user_id",s.id).order("day_of_week").order("start_time");if(v)throw v;return y},enabled:!!s}),i=tt({queryKey:["blocked-dates",s==null?void 0:s.id],queryFn:async()=>{const{data:y,error:v}=await q.from("agent_blocked_dates").select("*").eq("user_id",s.id).order("blocked_date");if(v)throw v;return y},enabled:!!s}),l=tt({queryKey:["bookings",s==null?void 0:s.id],queryFn:async()=>{const{data:y,error:v}=await q.from("bookings").select("*, booking_type:agent_booking_types(*)").eq("agent_user_id",s.id).order("booking_date",{ascending:!1});if(v)throw v;return y},enabled:!!s}),o=ft({mutationFn:async()=>{const{data:y,error:v}=await q.from("agent_booking_settings").insert({user_id:s.id,slug:""}).select().single();if(v)throw v;const b=[{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:w}=await q.from("agent_booking_types").insert(b.map(E=>({...E,user_id:s.id})));if(w)throw w;const S=[1,2,3,4,5].map(E=>({user_id:s.id,day_of_week:E,start_time:"09:00",end_time:"17:00"})),{error:C}=await q.from("agent_availability_slots").insert(S);if(C)throw C;return y},onSuccess:()=>{t.invalidateQueries({queryKey:["booking-settings"]}),t.invalidateQueries({queryKey:["booking-types"]}),t.invalidateQueries({queryKey:["availability-slots"]}),re.success("Scheduler set up successfully!")},onError:y=>re.error(y.message)}),c=ft({mutationFn:async y=>{const{error:v}=await q.from("agent_booking_settings").update(y).eq("user_id",s.id);if(v)throw v},onSuccess:()=>{t.invalidateQueries({queryKey:["booking-settings"]}),re.success("Settings updated")},onError:y=>re.error(y.message)}),d=ft({mutationFn:async y=>{const v={...y,user_id:s.id};if(y.id){const{error:b}=await q.from("agent_booking_types").update(v).eq("id",y.id);if(b)throw b}else{const{error:b}=await q.from("agent_booking_types").insert(v);if(b)throw b}},onSuccess:()=>{t.invalidateQueries({queryKey:["booking-types"]}),re.success("Booking type saved")},onError:y=>re.error(y.message)}),u=ft({mutationFn:async y=>{const{error:v}=await q.from("agent_booking_types").delete().eq("id",y);if(v)throw v},onSuccess:()=>{t.invalidateQueries({queryKey:["booking-types"]}),re.success("Booking type deleted")},onError:y=>re.error(y.message)}),h=ft({mutationFn:async y=>{const v={...y,user_id:s.id};if(y.id){const{error:b}=await q.from("agent_availability_slots").update(v).eq("id",y.id);if(b)throw b}else{const{error:b}=await q.from("agent_availability_slots").insert(v);if(b)throw b}},onSuccess:()=>{t.invalidateQueries({queryKey:["availability-slots"]})},onError:y=>re.error(y.message)}),m=ft({mutationFn:async y=>{const{error:v}=await q.from("agent_availability_slots").delete().eq("id",y);if(v)throw v},onSuccess:()=>{t.invalidateQueries({queryKey:["availability-slots"]})},onError:y=>re.error(y.message)}),f=ft({mutationFn:async y=>{const{blocked_date:v,end_date:b,reason:w}=y,S=D=>{const[O,U,W]=D.split("-").map(Number);return new Date(O,U-1,W)},C=D=>`${D.getFullYear()}-${String(D.getMonth()+1).padStart(2,"0")}-${String(D.getDate()).padStart(2,"0")}`,E=S(v),I=b?S(b):E;if(I366)throw new Error("Range too large (max 1 year)");const{error:R}=await q.from("agent_blocked_dates").upsert(P,{onConflict:"user_id,blocked_date",ignoreDuplicates:!0});if(R)throw R;return P.length},onSuccess:y=>{t.invalidateQueries({queryKey:["blocked-dates"]}),re.success(y&&y>1?`${y} dates blocked`:"Date blocked")},onError:y=>re.error(y.message)}),g=ft({mutationFn:async y=>{const{error:v}=await q.from("agent_blocked_dates").delete().eq("id",y);if(v)throw v},onSuccess:()=>{t.invalidateQueries({queryKey:["blocked-dates"]})},onError:y=>re.error(y.message)}),x=ft({mutationFn:async({id:y,reason:v})=>{const{error:b}=await q.from("bookings").update({status:"cancelled",cancelled_at:new Date().toISOString(),cancel_reason:v}).eq("id",y);if(b)throw b;await q.functions.invoke("agent-booking",{body:{action:"cancel",booking_id:y}}).catch(w=>console.error("Google calendar cleanup failed:",w))},onSuccess:()=>{t.invalidateQueries({queryKey:["bookings"]}),re.success("Booking cancelled")},onError:y=>re.error(y.message)});return{settings:n.data,bookingTypes:r.data??[],availability:a.data??[],blockedDates:i.data??[],bookings:l.data??[],isLoading:n.isLoading,initializeSettings:o,updateSettings:c,upsertBookingType:d,deleteBookingType:u,upsertAvailability:h,deleteAvailability:m,addBlockedDate:f,removeBlockedDate:g,cancelBooking:x}}const Uvt=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];function k$t({slots:s,onSave:t,onDelete:n}){const[r,a]=j.useState(null),[i,l]=j.useState("09:00"),[o,c]=j.useState("17:00"),d=Uvt.map((h,m)=>s.filter(f=>f.day_of_week===m)),u=()=>{r!==null&&(t({day_of_week:r,start_time:i,end_time:o,is_active:!0}),a(null),l("09:00"),c("17:00"))};return e.jsxs(Ne,{children:[e.jsxs(Ct,{children:[e.jsxs(At,{className:"flex items-center gap-2",children:[e.jsx(da,{className:"h-5 w-5"}),"Weekly Availability"]}),e.jsx(Gn,{children:"Set your available hours for each day"})]}),e.jsx(Ie,{className:"space-y-2",children:Uvt.map((h,m)=>{const f=d[m];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:h})}),e.jsxs("div",{className:"flex-1 space-y-1",children:[f.length===0?e.jsx("p",{className:"text-sm text-muted-foreground py-1",children:"Unavailable"}):f.map(g=>{var x,y;return e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(pe,{type:"time",className:"w-28 h-8 text-sm",defaultValue:(x=g.start_time)==null?void 0:x.slice(0,5),onBlur:v=>t({id:g.id,start_time:v.target.value})}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"to"}),e.jsx(pe,{type:"time",className:"w-28 h-8 text-sm",defaultValue:(y=g.end_time)==null?void 0:y.slice(0,5),onBlur:v=>t({id:g.id,end_time:v.target.value})}),e.jsx(Sn,{checked:g.is_active,onCheckedChange:v=>t({id:g.id,is_active:v})}),e.jsx($,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>n(g.id),children:e.jsx(Wn,{className:"h-3.5 w-3.5 text-muted-foreground"})})]},g.id)}),r===m?e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(pe,{type:"time",className:"w-28 h-8 text-sm",value:i,onChange:g=>l(g.target.value)}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"to"}),e.jsx(pe,{type:"time",className:"w-28 h-8 text-sm",value:o,onChange:g=>c(g.target.value)}),e.jsx($,{size:"sm",className:"h-8",onClick:u,children:"Add"}),e.jsx($,{variant:"ghost",size:"sm",className:"h-8",onClick:()=>a(null),children:"Cancel"})]}):e.jsxs($,{variant:"ghost",size:"sm",className:"h-7 text-xs text-muted-foreground",onClick:()=>a(m),children:[e.jsx(dn,{className:"h-3 w-3 mr-1"})," Add hours"]})]})]},h)})})]})}function qvt(s){const[t,n,r]=s.split("-").map(Number);return en(new Date(t,n-1,r),"MMM d, yyyy")}function pUs(s){const t=[...s].sort((a,i)=>a.blocked_date.localeCompare(i.blocked_date)),n=[],r=a=>{const[i,l,o]=a.split("-").map(Number),c=new Date(i,l-1,o+1);return`${c.getFullYear()}-${String(c.getMonth()+1).padStart(2,"0")}-${String(c.getDate()).padStart(2,"0")}`};for(const a of t){const i=n[n.length-1];i&&r(i.end)===a.blocked_date&&(i.reason??"")===(a.reason??"")?(i.end=a.blocked_date,i.ids.push(a.id)):n.push({start:a.blocked_date,end:a.blocked_date,reason:a.reason,ids:[a.id]})}return n}function S$t({blockedDates:s,onAdd:t,onRemove:n}){const[r,a]=j.useState(!1),[i,l]=j.useState(""),[o,c]=j.useState(""),[d,u]=j.useState(""),h=()=>{i&&(t({blocked_date:i,end_date:o||void 0,reason:d||void 0}),a(!1),l(""),c(""),u(""))};return e.jsxs(Ne,{children:[e.jsxs(Ct,{className:"flex flex-row items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs(At,{className:"flex items-center gap-2",children:[e.jsx(Tq,{className:"h-5 w-5"}),"Blocked Dates"]}),e.jsx(Gn,{children:"Block a single day or a full date range (vacations, holidays, etc.)"})]}),e.jsxs($,{size:"sm",variant:"outline",onClick:()=>a(!0),children:[e.jsx(dn,{className:"h-4 w-4 mr-1"})," Block Dates"]})]}),e.jsxs(Ie,{children:[r&&e.jsxs("div",{className:"flex flex-wrap items-center gap-2 mb-3 p-3 rounded-lg border bg-muted/30",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(pe,{type:"date",value:i,onChange:m=>l(m.target.value),className:"w-40"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"to"}),e.jsx(pe,{type:"date",value:o,min:i||void 0,onChange:m=>c(m.target.value),className:"w-40",placeholder:"Optional"})]}),e.jsx(pe,{placeholder:"Reason (optional)",value:d,onChange:m=>u(m.target.value),className:"flex-1 min-w-[180px]"}),e.jsx($,{size:"sm",onClick:h,children:"Add"}),e.jsx($,{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:pUs(s).map(m=>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.jsxs("span",{children:[qvt(m.start),m.end!==m.start&&` – ${qvt(m.end)}`]}),m.ids.length>1&&e.jsxs("span",{className:"text-xs text-muted-foreground",children:["(",m.ids.length," days)"]}),m.reason&&e.jsxs("span",{className:"text-muted-foreground",children:["(",m.reason,")"]}),e.jsx("button",{onClick:()=>m.ids.forEach(n),className:"ml-1 text-muted-foreground hover:text-destructive",children:e.jsx(gr,{className:"h-3.5 w-3.5"})})]},m.ids[0]))})]})]})}function gUs(){const{settings:s,bookingTypes:t,availability:n,blockedDates:r,isLoading:a,initializeSettings:i,updateSettings:l,upsertBookingType:o,deleteBookingType:c,upsertAvailability:d,deleteAvailability:u,addBlockedDate:h,removeBlockedDate:m}=N$t(),[f,g]=j.useState("1-on-1 Coaching Session"),[x,y]=j.useState(45),v=j.useMemo(()=>t.filter(w=>w.is_coaching_only),[t]);if(a)return e.jsx(Ne,{children:e.jsxs(Ie,{className:"p-6 flex items-center gap-2 text-muted-foreground",children:[e.jsx(kt,{className:"h-4 w-4 animate-spin"})," Loading your calendar…"]})});if(!s)return e.jsxs(Ne,{children:[e.jsxs(Ct,{children:[e.jsxs(At,{className:"flex items-center gap-2",children:[e.jsx(Au,{className:"h-5 w-5"})," Coaching calendar"]}),e.jsx(Gn,{children:"Set up your scheduler once, then open availability for the members assigned to you."})]}),e.jsx(Ie,{children:e.jsxs($,{onClick:()=>i.mutate(),disabled:i.isPending,children:[i.isPending&&e.jsx(kt,{className:"h-4 w-4 mr-2 animate-spin"}),"Set up my calendar"]})})]});const b=()=>{f.trim()&&(o.mutate({name:f.trim(),description:"Private coaching session",duration_minutes:x,color:"#406E71",icon:"Video",is_active:!0,qualification_enabled:!1,is_coaching_only:!0,sort_order:99}),g("1-on-1 Coaching Session"),y(45))};return e.jsxs("div",{className:"space-y-4",children:[e.jsxs(Ne,{children:[e.jsxs(Ct,{children:[e.jsxs(At,{className:"flex items-center gap-2",children:[e.jsx(ua,{className:"h-5 w-5"})," Coaching session types"]}),e.jsx(Gn,{children:"Only assigned members can book these. They stay hidden from your public booking page."})]}),e.jsxs(Ie,{className:"space-y-3",children:[v.length===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:"No coaching session type yet — add one below so members can book you."}):v.map(w=>e.jsxs("div",{className:"flex flex-wrap items-center gap-3 rounded-lg border p-3",children:[e.jsx(pe,{className:"h-9 max-w-[240px]",defaultValue:w.name,onBlur:S=>S.target.value!==w.name&&o.mutate({id:w.id,name:S.target.value})}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(pe,{type:"number",min:10,max:240,step:5,className:"h-9 w-20",defaultValue:w.duration_minutes,onBlur:S=>o.mutate({id:w.id,duration_minutes:parseInt(S.target.value)||30})}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"min"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Sn,{checked:w.is_active,onCheckedChange:S=>o.mutate({id:w.id,is_active:S})}),e.jsx("span",{className:"text-sm text-muted-foreground",children:w.is_active?"Bookable":"Paused"})]}),e.jsx(Be,{variant:"secondary",children:"Coaching only"}),e.jsx($,{variant:"ghost",size:"sm",className:"ml-auto h-8 w-8 p-0",onClick:async()=>{await fo({title:"Delete session type?",description:`"${w.name}" will no longer be bookable.`,confirmText:"Delete",destructive:!0})&&c.mutate(w.id)},children:e.jsx(Wn,{className:"h-3.5 w-3.5 text-muted-foreground"})})]},w.id)),e.jsxs("div",{className:"flex flex-wrap items-end gap-2 pt-2 border-t",children:[e.jsxs("div",{className:"flex-1 min-w-[200px]",children:[e.jsx(ee,{className:"text-xs",children:"New session type"}),e.jsx(pe,{value:f,onChange:w=>g(w.target.value),className:"h-9"})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs",children:"Minutes"}),e.jsx(pe,{type:"number",min:10,max:240,step:5,className:"h-9 w-24",value:x,onChange:w=>y(parseInt(w.target.value)||30)})]}),e.jsxs($,{onClick:b,disabled:o.isPending,children:[e.jsx(dn,{className:"h-4 w-4 mr-1"})," Add"]})]})]})]}),e.jsx(k$t,{slots:n,onSave:w=>d.mutate(w),onDelete:w=>u.mutate(w)}),e.jsx(S$t,{blockedDates:r,onAdd:w=>h.mutate(w),onRemove:w=>m.mutate(w)}),e.jsxs(Ne,{children:[e.jsxs(Ct,{children:[e.jsx(At,{children:"Scheduling rules"}),e.jsx(Gn,{children:"Applies to coaching bookings on your calendar."})]}),e.jsxs(Ie,{className:"grid gap-4 sm:grid-cols-3",children:[e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs",children:"Buffer between sessions (min)"}),e.jsx(pe,{type:"number",min:0,max:120,step:5,className:"h-9",defaultValue:s.buffer_minutes,onBlur:w=>l.mutate({buffer_minutes:parseInt(w.target.value)||0})})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs",children:"Minimum notice (hours)"}),e.jsx(pe,{type:"number",min:0,max:168,className:"h-9",defaultValue:s.min_notice_hours,onBlur:w=>l.mutate({min_notice_hours:parseInt(w.target.value)||0})})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs",children:"Bookable up to (days out)"}),e.jsx(pe,{type:"number",min:1,max:365,className:"h-9",defaultValue:s.max_advance_days,onBlur:w=>l.mutate({max_advance_days:parseInt(w.target.value)||30})})]})]})]})]})}async function PZ(s,t){const n=s==="agent"?"agent-google-calendar":"coach-google-calendar",{data:r,error:a}=await q.functions.invoke(n,{body:t});if(a){let i=a.message;try{const l=a.context;if(l!=null&&l.json){const o=await l.json();o!=null&&o.error&&(i=o.error)}}catch{}throw new Error(i)}if(r!=null&&r.error)throw new Error(r.error);return r}function C$t(s=!0,t="coach"){const n=Vt(),r=tt({queryKey:["google-calendar-connection",t],enabled:s,queryFn:async()=>await PZ(t,{action:"status"})}),a=()=>n.invalidateQueries({queryKey:["google-calendar-connection",t]}),i=ft({mutationFn:async()=>{const d=await PZ(t,{action:"start",origin:window.location.origin}),u=d==null?void 0:d.authorizationUrl;if(!u)throw new Error("Google did not return an authorization link.");try{sessionStorage.setItem("googleCalendarReturnTo",window.location.pathname),sessionStorage.setItem("googleCalendarScope",t)}catch{}window.location.assign(u),await new Promise(h=>setTimeout(h,4e3))},onSuccess:a}),l=ft({mutationFn:()=>PZ(t,{action:"disconnect"}),onSuccess:a}),o=ft({mutationFn:d=>PZ(t,{action:"settings",...d}),onSuccess:a}),c=ft({mutationFn:()=>PZ(t,{action:"refresh_calendars"}),onSuccess:a});return{status:r,connect:i,disconnect:l,updateSettings:o,refreshCalendars:c}}function A$t({scope:s="coach"}){const{status:t,connect:n,disconnect:r,updateSettings:a,refreshCalendars:i}=C$t(!0,s),l=s==="agent";j.useEffect(()=>{const d=new URLSearchParams(window.location.search),u=d.get("google_calendar");if(!u)return;u==="connected"?(re.success("Google Calendar connected"),t.refetch()):re.error(d.get("google_calendar_error")||"Google connection failed."),d.delete("google_calendar"),d.delete("google_calendar_error");const h=d.toString();window.history.replaceState({},"",window.location.pathname+(h?`?${h}`:""))},[]);const o=t.data,c=t.error;return e.jsxs(Ne,{children:[e.jsx(Ct,{children:e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsxs(At,{className:"flex items-center gap-2",children:[e.jsx(bb,{className:"h-5 w-5"})," Google Calendar"]}),e.jsx(Gn,{children:l?"Hide times you're already booked on Google, and push every new booking straight onto your calendar.":"Hide times you're already booked on Google, and push new coaching sessions straight onto your calendar."})]}),(o==null?void 0:o.connected)&&e.jsxs(Be,{className:"bg-emerald-600 hover:bg-emerald-600 shrink-0",children:[e.jsx(qr,{className:"h-3.5 w-3.5 mr-1"})," Connected"]})]})}),e.jsxs(Ie,{className:"space-y-4",children:[t.isLoading&&e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(kt,{className:"h-4 w-4 animate-spin"})," Checking your connection…"]}),c&&e.jsxs("div",{className:"flex items-start gap-2 rounded-lg border border-destructive/40 bg-destructive/5 p-3 text-sm",children:[e.jsx(ll,{className:"h-4 w-4 mt-0.5 text-destructive shrink-0"}),e.jsx("span",{children:c.message})]}),o&&!o.configured&&e.jsxs("div",{className:"flex items-start gap-2 rounded-lg border border-amber-400/50 bg-amber-50 dark:bg-amber-950/20 p-3 text-sm",children:[e.jsx(ll,{className:"h-4 w-4 mt-0.5 text-amber-600 shrink-0"}),e.jsx("span",{children:"Google Calendar isn't switched on for LevelUp yet. Once an admin finishes the one-time Google setup, you'll be able to connect right here."})]}),(o==null?void 0:o.configured)&&!o.connected&&e.jsxs("div",{className:"space-y-3",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Not connected. Your availability comes only from the hours you set in LevelUp."}),e.jsxs($,{onClick:()=>n.mutate(void 0,{onSuccess:()=>re.success("Google Calendar connected"),onError:d=>re.error(d.message)}),disabled:n.isPending,className:"bg-[#406E71] hover:bg-[#2a4c64]",children:[n.isPending?e.jsx(kt,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(bb,{className:"h-4 w-4 mr-2"}),n.isPending?"Connecting…":"Connect Google Calendar"]}),n.isError&&e.jsx("p",{className:"text-sm text-destructive",children:n.error.message})]}),(o==null?void 0:o.connected)&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"rounded-lg border bg-muted/30 p-3 text-sm",children:[e.jsx("div",{className:"font-medium",children:o.account_email||"Google account"}),o.connected_at&&e.jsxs("div",{className:"text-muted-foreground text-xs",children:["Connected ",new Date(o.connected_at).toLocaleDateString()]})]}),e.jsxs("div",{className:"flex items-center justify-between gap-3 rounded-lg border p-3",children:[e.jsxs("div",{children:[e.jsx(ee,{className:"text-sm",children:"Two-way sync"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:l?"Block busy times and add new bookings to Google.":"Block busy times and add booked sessions to Google."})]}),e.jsx(Sn,{checked:o.sync_enabled,onCheckedChange:d=>a.mutate({sync_enabled:d},{onError:u=>re.error(u.message)})})]}),l&&e.jsxs("div",{className:"flex items-center justify-between gap-3 rounded-lg border p-3",children:[e.jsxs("div",{children:[e.jsx(ee,{className:"text-sm",children:"Invite the guest"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Send a Google invite when they leave an email address."})]}),e.jsx(Sn,{checked:o.invite_guest!==!1,onCheckedChange:d=>a.mutate({invite_guest:d},{onError:u=>re.error(u.message)})})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{className:"text-xs",children:"Calendar to use"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(ms,{value:o.selected_calendar_id||"primary",onValueChange:d=>a.mutate({calendar_id:d},{onError:u=>re.error(u.message)}),children:[e.jsx(us,{className:"h-9",children:e.jsx(fs,{placeholder:"Primary calendar"})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"primary",children:"Primary calendar"}),o.calendars.filter(d=>!d.primary).map(d=>e.jsx(Ge,{value:d.id,children:d.summary||d.id},d.id))]})]}),e.jsx($,{variant:"outline",size:"icon",className:"h-9 w-9 shrink-0",onClick:()=>i.mutate(void 0,{onSuccess:()=>re.success("Calendars refreshed"),onError:d=>re.error(d.message)}),disabled:i.isPending,children:e.jsx(ro,{className:`h-4 w-4 ${i.isPending?"animate-spin":""}`})})]})]}),e.jsxs("div",{className:"flex flex-wrap gap-2 pt-1",children:[e.jsxs($,{variant:"outline",size:"sm",onClick:()=>n.mutate(void 0,{onSuccess:()=>re.success("Google Calendar reconnected"),onError:d=>re.error(d.message)}),disabled:n.isPending,children:[n.isPending?e.jsx(kt,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(ro,{className:"h-4 w-4 mr-2"}),"Reconnect"]}),e.jsxs($,{variant:"ghost",size:"sm",className:"text-destructive",disabled:r.isPending,onClick:async()=>{await fo({title:"Disconnect Google Calendar?",description:"Busy times will stop hiding and new sessions won't be added to Google.",confirmText:"Disconnect",destructive:!0})&&r.mutate(void 0,{onSuccess:()=>re.success("Google Calendar disconnected"),onError:u=>re.error(u.message)})},children:[e.jsx(o7,{className:"h-4 w-4 mr-2"})," Disconnect"]})]})]})]})]})}function xUs(){const s=Qn(),{data:t,isLoading:n}=eie(),r=Vt(),[a,i]=j.useState(""),[l,o]=j.useState(""),[c,d]=j.useState(""),[u,h]=j.useState(""),[m,f]=j.useState(""),[g,x]=j.useState(!1),[y,v]=j.useState([]),[b,w]=j.useState(""),[S,C]=j.useState(2),[E,I]=j.useState(!1);j.useEffect(()=>{if(!t)return;const U=t;i(U.slug||""),o(U.headline||""),d(U.bio||""),h(U.photo_url||""),f(U.intro_video_url||""),x(!!U.accepting_clients),v(U.specialties||[]),C(U.default_sessions_per_month??2)},[t]);const P=async()=>{if(!t)return;I(!0);const{error:U}=await q.from("coaches").update({slug:a.trim()||null,headline:l||null,bio:c||null,photo_url:u||null,intro_video_url:m||null,accepting_clients:g,specialties:y,default_sessions_per_month:S}).eq("id",t.id);if(I(!1),U)return re.error(U.message);re.success("Profile saved"),r.invalidateQueries({queryKey:["my-coach-profile"]})},R=()=>{const U=b.trim();if(U){if(y.includes(U))return w("");v([...y,U]),w("")}};if(n)return e.jsx(Vs,{title:"Coach Settings",children:e.jsx("div",{className:"p-8",children:"Loading…"})});if(!t)return e.jsx(Vs,{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 D=t,O=D.slug?`${window.location.origin}/coaches/${D.slug}`:null;return e.jsx(Vs,{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($,{variant:"ghost",size:"icon",onClick:()=>s("/coaching"),children:e.jsx(qa,{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($,{variant:"outline",size:"sm",onClick:()=>window.open(O,"_blank"),children:[e.jsx(kr,{className:"h-4 w-4 mr-1"})," View public"]}),e.jsxs($,{onClick:P,disabled:E,className:"bg-[#406E71] hover:bg-[#2a4c64]",children:[e.jsx(tl,{className:"h-4 w-4 mr-1"})," ",E?"Saving…":"Save"]})]})]}),D.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(Ne,{children:e.jsxs(Ie,{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(Sn,{checked:g,onCheckedChange:x})]}),e.jsxs("div",{children:[e.jsx(ee,{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(pe,{value:a,onChange:U=>i(U.target.value.toLowerCase().replace(/[^a-z0-9-]/g,"")),placeholder:"your-name"})]})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Headline"}),e.jsx(pe,{value:l,onChange:U=>o(U.target.value),placeholder:"e.g. Helping new agents close their first 10 deals",maxLength:140})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Bio"}),e.jsx(Rs,{rows:6,value:c,onChange:U=>d(U.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(ee,{children:"Profile photo"}),e.jsx($vt,{kind:"photo",value:u,onChange:h})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Intro video"}),e.jsx($vt,{kind:"video",value:m,onChange:f})]})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Specialties"}),e.jsx("div",{className:"flex flex-wrap gap-2 mb-2",children:y.map(U=>e.jsxs(Be,{variant:"secondary",className:"gap-1",children:[U,e.jsx("button",{onClick:()=>v(y.filter(W=>W!==U)),children:e.jsx(gr,{className:"h-3 w-3"})})]},U))}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(pe,{value:b,onChange:U=>w(U.target.value),placeholder:"Add a specialty…",onKeyDown:U=>{U.key==="Enter"&&(U.preventDefault(),R())}}),e.jsx($,{type:"button",variant:"outline",onClick:R,children:e.jsx(dn,{className:"h-4 w-4"})})]})]})]})}),e.jsx(Ne,{children:e.jsxs(Ie,{className:"p-6 space-y-4",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-lg font-semibold",children:"Coaching calendar"}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Open availability right here — assigned members book you from their ",e.jsx("strong",{children:"My Coach → Book"})," tab. These session types never show on your public booking page."]})]}),e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-end gap-4",children:[e.jsxs("div",{className:"flex-1",children:[e.jsx(ee,{children:"Sessions each agent can book per month"}),e.jsx(pe,{type:"number",min:1,max:31,value:S,onChange:U=>C(Math.max(1,parseInt(U.target.value)||1)),className:"max-w-[140px]"}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"You can override this for individual agents on their workspace page."})]}),e.jsx($,{variant:"outline",onClick:()=>s("/mission-control/scheduler"),children:"Open full Scheduler"})]})]})}),e.jsx(A$t,{}),e.jsx(gUs,{}),e.jsx(Ne,{children:e.jsx(Ie,{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($,{variant:"outline",onClick:()=>s("/coaching/billing"),children:"Go to Billing"})]})})}),e.jsx(yUs,{coachId:D.id})]})})}function yUs({coachId:s}){const[t,n]=j.useState("");Vt();const{data:r=[],refetch:a}=tt({queryKey:["coach-invites",s],queryFn:async()=>{const{data:c}=await q.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 re.error("Email required");const{error:d}=await q.from("coaching_invites").insert({coach_id:s,email:c});if(d)return re.error(d.message);n(""),re.success("Invite created"),a()},l=c=>{const d=`${window.location.origin}/auth?coach_invite=${c}`;navigator.clipboard.writeText(d),re.success("Link copied")},o=async c=>{await fo("Revoke this invite?")&&(await q.from("coaching_invites").delete().eq("id",c),a())};return e.jsx(Ne,{children:e.jsxs(Ie,{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(Ad,{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(pe,{placeholder:"agent@email.com",value:t,onChange:c=>n(c.target.value),onKeyDown:c=>c.key==="Enter"&&i()}),e.jsxs($,{onClick:i,children:[e.jsx(dn,{className:"h-4 w-4 mr-1"})," Create"]})]}),e.jsxs("div",{className:"space-y-2",children:[r.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($,{variant:"ghost",size:"icon",onClick:()=>l(c.token),children:e.jsx(Ha,{className:"h-4 w-4"})}),e.jsx($,{variant:"ghost",size:"icon",onClick:()=>o(c.id),children:e.jsx(Wn,{className:"h-4 w-4"})})]},c.id)),r.length===0&&e.jsx("div",{className:"text-sm text-muted-foreground text-center py-4",children:"No invites yet."})]})]})})}const vUs="google_calendar";function bUs(){const[s,t]=j.useState("Finishing your Google Calendar connection…"),n=j.useRef(!1);return j.useEffect(()=>{if(n.current)return;n.current=!0;const r=new URLSearchParams(window.location.search),a=(()=>{try{return!!window.opener&&!window.opener.closed}catch{return!1}})(),i=(()=>{try{return sessionStorage.getItem("googleCalendarReturnTo")||"/coaching/settings"}catch{return"/coaching/settings"}})(),l=(u,h)=>{try{sessionStorage.removeItem("googleCalendarReturnTo")}catch{}const m=new URL(i,window.location.origin);m.searchParams.set("google_calendar",u),h&&m.searchParams.set("google_calendar_error",h),window.location.replace(m.toString())},o=(u,h)=>{var m;if(a){(m=window.opener)==null||m.postMessage({type:u,connectorId:vUs,reason:h},window.location.origin),u==="appUserConnectorOAuthComplete"&&window.close();return}l(u==="appUserConnectorOAuthComplete"?"connected":"failed",h)};if(r.get("success")!=="true"){const u=r.get("error")||"Google did not complete the connection.";t(u),o("appUserConnectorOAuthFailed",u);return}const c=r.get("code");if(!c){const u=r.get("offline_access_allowed")==="false"?"This connection cannot be used yet: a workspace admin must enable offline access on the Google Calendar App User Connector client.":"Google finished, but no exchange code was returned.";t(u),o("appUserConnectorOAuthFailed",u);return}const d=(()=>{try{return sessionStorage.getItem("googleCalendarScope")==="agent"?"agent":"coach"}catch{return"coach"}})();q.functions.invoke(d==="agent"?"agent-google-calendar":"coach-google-calendar",{body:{action:"complete",code:c}}).then(({data:u,error:h})=>{if(h)throw h;if(u!=null&&u.error)throw new Error(u.error);t("Connected! You can close this window."),o("appUserConnectorOAuthComplete")}).catch(u=>{const h=(u==null?void 0:u.message)||"Could not finish the connection.";t(h),o("appUserConnectorOAuthFailed",h)})},[]),e.jsx("div",{className:"min-h-screen flex items-center justify-center p-8 text-center",children:e.jsxs("div",{className:"space-y-3 max-w-sm",children:[e.jsx(kt,{className:"h-6 w-6 animate-spin mx-auto text-[#406E71]"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:s})]})})}const Qce=[{value:"pending",label:"Pending",tone:"bg-amber-100 text-amber-800"},{value:"invited",label:"Invited",tone:"bg-blue-100 text-blue-800"},{value:"converted",label:"Converted",tone:"bg-emerald-100 text-emerald-800"},{value:"declined",label:"Declined",tone:"bg-rose-100 text-rose-800"},{value:"archived",label:"Archived",tone:"bg-slate-100 text-slate-700"}];function _Us(){const s=Qn(),t=Vt(),{data:n,isLoading:r}=eie(),[a,i]=j.useState("pending"),[l,o]=j.useState(""),[c,d]=j.useState(null),[u,h]=j.useState(!1),[m,f]=j.useState(""),[g,x]=j.useState(!1),[y,v]=j.useState(""),{data:b=[],isLoading:w}=tt({queryKey:["coaching-waitlist",n==null?void 0:n.id],enabled:!!(n!=null&&n.id),queryFn:async()=>{const{data:D,error:O}=await q.from("coaching_waitlist").select("*").eq("coach_id",n.id).order("created_at",{ascending:!1});if(O)throw O;return D||[]}}),S=j.useMemo(()=>b.filter(D=>{if(a!=="all"&&D.status!==a)return!1;if(l){const O=l.toLowerCase();return(D.name||"").toLowerCase().includes(O)||(D.email||"").toLowerCase().includes(O)||(D.brokerage||"").toLowerCase().includes(O)}return!0}),[b,a,l]),C=j.useMemo(()=>{const D={all:b.length};for(const O of Qce)D[O.value]=0;for(const O of b)D[O.status]=(D[O.status]||0)+1;return D},[b]),E=async(D,O)=>{const{error:U}=await q.from("coaching_waitlist").update(O).eq("id",D);if(U)return re.error(U.message);t.invalidateQueries({queryKey:["coaching-waitlist",n==null?void 0:n.id]}),(c==null?void 0:c.id)===D&&d(W=>({...W,...O}))},I=async D=>{if(!await fo("Remove this person from the waitlist?"))return;const{error:O}=await q.from("coaching_waitlist").delete().eq("id",D);if(O)return re.error(O.message);re.success("Removed"),t.invalidateQueries({queryKey:["coaching-waitlist",n==null?void 0:n.id]}),d(null)},P=async()=>{if(!c)return;const{data:D,error:O}=await q.functions.invoke("coaching-waitlist-invite",{body:{waitlistId:c.id,message:m}});if(O||D!=null&&D.error)return re.error((D==null?void 0:D.error)||(O==null?void 0:O.message)||"Could not send invite");re.success(`Invite sent to ${c.name}`),h(!1),f(""),t.invalidateQueries({queryKey:["coaching-waitlist",n==null?void 0:n.id]})},R=async()=>{if(!n)return;const{data:D,error:O}=await q.functions.invoke("coaching-waitlist-invite",{body:{coachId:n.id,notifyAll:!0,message:y}});if(O||D!=null&&D.error)return re.error((D==null?void 0:D.error)||(O==null?void 0:O.message)||"Could not notify");re.success(`Notified ${(D==null?void 0:D.count)||0} agents`),x(!1),v(""),t.invalidateQueries({queryKey:["coaching-waitlist",n==null?void 0:n.id]})};return r?e.jsx(Vs,{title:"Waitlist",children:e.jsx("div",{className:"p-8",children:"Loading…"})}):n?e.jsxs(Vs,{title:"Coaching Waitlist",children:[e.jsxs("div",{className:"p-4 md:p-8 max-w-7xl mx-auto space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3 flex-wrap",children:[e.jsxs("div",{children:[e.jsxs($,{variant:"ghost",size:"sm",className:"mb-2 -ml-2",onClick:()=>s("/coaching"),children:[e.jsx(qa,{className:"h-4 w-4 mr-1"})," Back to Coaching"]}),e.jsxs("h1",{className:"text-2xl font-bold flex items-center gap-2",children:[e.jsx(zg,{className:"h-6 w-6 text-[#406E71]"}),"Waitlist"]}),e.jsx("p",{className:"text-muted-foreground text-sm mt-1",children:"Agents waiting for a spot to open up with you."})]}),e.jsxs($,{variant:"outline",onClick:()=>x(!0),disabled:!C.pending,title:C.pending?"":"No pending applicants",children:[e.jsx(Kz,{className:"h-4 w-4 mr-2"}),"Notify all pending (",C.pending||0,")"]})]}),e.jsxs("div",{className:"flex gap-2 flex-wrap",children:[e.jsxs("button",{onClick:()=>i("all"),className:`px-3 py-1.5 rounded-full text-sm border ${a==="all"?"bg-[#406E71] text-white border-[#406E71]":"bg-white hover:bg-muted"}`,children:["All (",C.all,")"]}),Qce.map(D=>e.jsxs("button",{onClick:()=>i(D.value),className:`px-3 py-1.5 rounded-full text-sm border ${a===D.value?"bg-[#406E71] text-white border-[#406E71]":"bg-white hover:bg-muted"}`,children:[D.label," (",C[D.value]||0,")"]},D.value))]}),e.jsx(pe,{placeholder:"Search by name, email, brokerage…",value:l,onChange:D=>o(D.target.value),className:"max-w-md"}),w?e.jsx("div",{className:"text-muted-foreground",children:"Loading…"}):S.length===0?e.jsx(Ne,{children:e.jsx(Ie,{className:"p-10 text-center text-muted-foreground",children:"No entries here yet."})}):e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:S.map(D=>{const O=Qce.find(U=>U.value===D.status);return e.jsx(Ne,{className:"cursor-pointer hover:shadow-md transition-shadow",onClick:()=>d(D),children:e.jsxs(Ie,{className:"p-4",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"font-semibold truncate",children:D.name}),e.jsx("div",{className:"text-xs text-muted-foreground truncate",children:D.email}),D.brokerage&&e.jsx("div",{className:"text-xs text-muted-foreground truncate",children:D.brokerage})]}),e.jsx(Be,{className:(O==null?void 0:O.tone)||"",children:(O==null?void 0:O.label)||D.status})]}),e.jsxs("div",{className:"flex items-center justify-between mt-3 text-xs text-muted-foreground",children:[e.jsxs("span",{children:["Joined ",mu(new Date(D.created_at),{addSuffix:!0})]}),D.preferred_package&&e.jsxs("span",{className:"truncate ml-2",children:["→ ",D.preferred_package]})]})]})},D.id)})})]}),e.jsx(zs,{open:!!c,onOpenChange:D=>!D&&d(null),children:e.jsx(Os,{className:"max-w-lg max-h-[90vh] overflow-y-auto",children:c&&e.jsxs(e.Fragment,{children:[e.jsxs(Us,{children:[e.jsx(Bs,{children:c.name}),e.jsxs(Ir,{children:["Joined ",mu(new Date(c.created_at),{addSuffix:!0})]})]}),e.jsxs("div",{className:"space-y-3 text-sm",children:[e.jsx(IZ,{label:"Email",value:c.email}),e.jsx(IZ,{label:"Phone",value:c.phone}),e.jsx(IZ,{label:"Brokerage",value:c.brokerage}),e.jsx(IZ,{label:"Years",value:c.years_in_business}),e.jsx(IZ,{label:"Preferred package",value:c.preferred_package}),c.biggest_challenge&&e.jsxs("div",{children:[e.jsx("div",{className:"text-xs font-medium text-muted-foreground",children:"Biggest challenge"}),e.jsx("p",{className:"whitespace-pre-wrap",children:c.biggest_challenge})]}),c.message&&e.jsxs("div",{children:[e.jsx("div",{className:"text-xs font-medium text-muted-foreground",children:"Message"}),e.jsx("p",{className:"whitespace-pre-wrap",children:c.message})]}),c.invited_at&&e.jsxs("div",{className:"text-xs text-blue-700",children:["Invite sent ",mu(new Date(c.invited_at),{addSuffix:!0})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-xs font-medium text-muted-foreground mb-1",children:"Status"}),e.jsxs(ms,{value:c.status,onValueChange:D=>E(c.id,{status:D}),children:[e.jsx(us,{children:e.jsx(fs,{})}),e.jsx(hs,{children:Qce.map(D=>e.jsx(Ge,{value:D.value,children:D.label},D.value))})]})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-xs font-medium text-muted-foreground mb-1",children:"Private notes"}),e.jsx(Rs,{rows:3,defaultValue:c.coach_notes||"",onBlur:D=>{D.target.value!==(c.coach_notes||"")&&E(c.id,{coach_notes:D.target.value})}})]})]}),e.jsxs(Ar,{className:"flex-wrap gap-2",children:[e.jsxs($,{variant:"outline",className:"text-destructive",onClick:()=>I(c.id),children:[e.jsx(Wn,{className:"h-4 w-4 mr-1"})," Remove"]}),e.jsx($,{variant:"outline",asChild:!0,children:e.jsxs("a",{href:`mailto:${c.email}`,children:[e.jsx(mn,{className:"h-4 w-4 mr-1"})," Email directly"]})}),e.jsxs($,{className:"bg-[#406E71] hover:bg-[#2a4c64]",onClick:()=>{f(""),h(!0)},children:[e.jsx(Yr,{className:"h-4 w-4 mr-1"})," Invite to subscribe"]})]})]})})}),e.jsx(zs,{open:u,onOpenChange:h,children:e.jsxs(Os,{children:[e.jsxs(Us,{children:[e.jsx(Bs,{children:"Invite to subscribe"}),e.jsxs(Ir,{children:["We'll email ",c==null?void 0:c.name," a link to your coaching page so they can pick a package."]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium",children:"Personal note (optional)"}),e.jsx(Rs,{rows:4,placeholder:"Hey! A spot just opened up and I'd love to work with you…",value:m,onChange:D=>f(D.target.value)})]}),e.jsxs(Ar,{children:[e.jsx($,{variant:"outline",onClick:()=>h(!1),children:"Cancel"}),e.jsxs($,{className:"bg-[#406E71] hover:bg-[#2a4c64]",onClick:P,children:[e.jsx(Yr,{className:"h-4 w-4 mr-1"})," Send invite"]})]})]})}),e.jsx(zs,{open:g,onOpenChange:x,children:e.jsxs(Os,{children:[e.jsxs(Us,{children:[e.jsx(Bs,{children:"Notify all pending applicants"}),e.jsx(Ir,{children:"Send everyone with status “Pending” an email letting them know spots are opening up. They'll each be marked “Invited”."})]}),e.jsx(Rs,{rows:4,placeholder:"Good news — I just opened up new coaching spots…",value:y,onChange:D=>v(D.target.value)}),e.jsxs(Ar,{children:[e.jsx($,{variant:"outline",onClick:()=>x(!1),children:"Cancel"}),e.jsxs($,{className:"bg-[#406E71] hover:bg-[#2a4c64]",onClick:R,children:[e.jsx(Kz,{className:"h-4 w-4 mr-1"})," Send to ",C.pending||0," agents"]})]})]})})]}):e.jsx(Vs,{title:"Waitlist",children:e.jsx("div",{className:"p-8 text-center text-muted-foreground",children:"You need a coach profile to view this page."})})}function IZ({label:s,value:t}){return t?e.jsxs("div",{className:"flex justify-between gap-3 border-b pb-1",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:s}),e.jsx("span",{className:"text-right",children:t})]}):null}function wUs(){const{data:s=[],isLoading:t}=tt({queryKey:["coaches-directory"],queryFn:async()=>{const{data:n,error:r}=await q.from("coaches").select("id, slug, headline, bio, specialties, photo_url, is_certified, accepting_clients, user_id").not("slug","is",null);if(r)throw r;const a=(n||[]).map(o=>o.user_id);if(a.length===0)return[];const{data:i}=await q.from("profiles").select("id, name, avatar_url").in("id",a),l=new Map((i||[]).map(o=>[o.id,o]));return(n||[]).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(Nn,{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(qr,{className:"h-4 w-4 text-yellow-300"})," Vetted by LevelUp"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Kl,{className:"h-4 w-4 text-yellow-300"})," Top-producer experience"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ja,{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(n=>{var i,l;const r=((i=n.profile)==null?void 0:i.name)||"Coach",a=n.photo_url||((l=n.profile)==null?void 0:l.avatar_url);return e.jsx(wr,{to:`/coaches/${n.slug||n.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:r,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:r.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:[n.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(Nn,{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 ${n.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 ${n.accepting_clients?"bg-white":"bg-amber-500"}`}),n.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:r}),n.headline&&e.jsx("p",{className:"text-sm text-yellow-200/90 font-medium mt-1 line-clamp-1",children:n.headline}),n.bio&&e.jsx("p",{className:"text-[13px] text-white/80 mt-2 line-clamp-2 leading-relaxed",children:n.bio}),n.specialties&&n.specialties.length>0&&e.jsx("div",{className:"flex flex-wrap gap-1.5 mt-3",children:n.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(ei,{className:"h-4 w-4"})})]})]})]})})},n.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(Nn,{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(qr,{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(qr,{className:"h-4 w-4 text-yellow-300"})," Recurring revenue"]}),e.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[e.jsx(qr,{className:"h-4 w-4 text-yellow-300"})," Certified status"]})]})]}),e.jsxs("div",{className:"mt-8 md:mt-0",children:[e.jsxs(wr,{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(ei,{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."})]})]})]})]})]})}const jUs=H2({name:vl().trim().min(1,"Name required").max(120),email:vl().trim().email("Invalid email").max(255),phone:vl().trim().max(40).optional().or(yx("")),brokerage:vl().trim().max(160).optional().or(yx("")),years_in_business:vl().max(40).optional().or(yx("")),biggest_challenge:vl().trim().max(1e3).optional().or(yx("")),preferred_package:vl().max(120).optional().or(yx("")),message:vl().trim().max(1500).optional().or(yx(""))});function NUs({open:s,onOpenChange:t,coachId:n,coachName:r,packages:a=[]}){const{user:i}=vs(),[l,o]=j.useState(!1),[c,d]=j.useState({name:"",email:(i==null?void 0:i.email)||"",phone:"",brokerage:"",years_in_business:"",biggest_challenge:"",preferred_package:"",message:""}),u=(m,f)=>d(g=>({...g,[m]:f})),h=async()=>{var g;const m=jUs.safeParse(c);if(!m.success){re.error(((g=m.error.issues[0])==null?void 0:g.message)||"Please check your entries");return}o(!0);const{error:f}=await q.from("coaching_waitlist").insert({coach_id:n,agent_user_id:(i==null?void 0:i.id)||null,name:c.name.trim(),email:c.email.trim().toLowerCase(),phone:c.phone||null,brokerage:c.brokerage||null,years_in_business:c.years_in_business||null,biggest_challenge:c.biggest_challenge||null,preferred_package:c.preferred_package||null,message:c.message||null,status:"pending"});if(o(!1),f){re.error(f.message||"Could not join waitlist");return}re.success(`You're on the waitlist${r?` for ${r}`:""}. We'll be in touch when a spot opens.`),t(!1),d({...c,biggest_challenge:"",message:""})};return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Os,{className:"max-w-lg max-h-[90vh] overflow-y-auto",children:[e.jsxs(Us,{children:[e.jsxs(Bs,{children:["Join the waitlist",r?` — ${r}`:""]}),e.jsx(Ir,{children:"Tell us a bit about you. The coach will reach out as soon as a spot opens."})]}),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(ee,{children:"Name *"}),e.jsx(pe,{value:c.name,onChange:m=>u("name",m.target.value)})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Email *"}),e.jsx(pe,{type:"email",value:c.email,onChange:m=>u("email",m.target.value)})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(ee,{children:"Phone"}),e.jsx(pe,{value:c.phone,onChange:m=>u("phone",m.target.value)})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Brokerage"}),e.jsx(pe,{value:c.brokerage,onChange:m=>u("brokerage",m.target.value)})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(ee,{children:"Years in business"}),e.jsxs(ms,{value:c.years_in_business,onValueChange:m=>u("years_in_business",m),children:[e.jsx(us,{children:e.jsx(fs,{placeholder:"Select…"})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"< 1 year",children:"Less than 1 year"}),e.jsx(Ge,{value:"1-3 years",children:"1-3 years"}),e.jsx(Ge,{value:"4-7 years",children:"4-7 years"}),e.jsx(Ge,{value:"8-15 years",children:"8-15 years"}),e.jsx(Ge,{value:"15+ years",children:"15+ years"})]})]})]}),a.length>0&&e.jsxs("div",{children:[e.jsx(ee,{children:"Preferred package"}),e.jsxs(ms,{value:c.preferred_package,onValueChange:m=>u("preferred_package",m),children:[e.jsx(us,{children:e.jsx(fs,{placeholder:"Any"})}),e.jsx(hs,{children:a.map(m=>e.jsx(Ge,{value:m.name,children:m.name},m.id))})]})]})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Biggest challenge right now"}),e.jsx(Rs,{rows:2,value:c.biggest_challenge,onChange:m=>u("biggest_challenge",m.target.value)})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Anything else?"}),e.jsx(Rs,{rows:2,value:c.message,onChange:m=>u("message",m.target.value)})]})]}),e.jsxs(Ar,{children:[e.jsx($,{variant:"outline",onClick:()=>t(!1),disabled:l,children:"Cancel"}),e.jsx($,{className:"bg-[#406E71] hover:bg-[#2a4c64]",onClick:h,disabled:l,children:l?"Submitting…":"Join Waitlist"})]})]})})}function kUs(){var x;const{slug:s}=Wi(),t=Qn(),{user:n}=vs(),[r,a]=j.useState(null),[i,l]=j.useState(!1),{data:o,isLoading:c}=tt({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=q.from("coaches").select("*"),{data:b}=y?await v.eq("id",s).maybeSingle():await v.eq("slug",s).maybeSingle();if(!b)return null;const[{data:w},{data:S}]=await Promise.all([q.from("profiles").select("id, name, avatar_url").eq("id",b.user_id).maybeSingle(),q.from("coaching_packages").select("*").eq("coach_id",b.id).eq("is_active",!0).order("sort_order")]);return{coach:b,profile:w,packages:S||[]}}}),d=async y=>{if(!n){re.error("Please sign in to subscribe"),t(`/auth?redirect=/coaches/${s}`);return}a(y);const{data:v,error:b}=await q.functions.invoke("create-coaching-checkout",{body:{packageId:y}});if(a(null),b||v!=null&&v.error){re.error((v==null?void 0:v.error)||(b==null?void 0:b.message)||"Checkout failed");return}v!=null&&v.url&&(window.location.href=v.url)};if(c)return e.jsx("div",{className:"p-12 text-center",children:"Loading…"});if(!(o!=null&&o.coach))return e.jsx("div",{className:"p-12 text-center",children:"Coach not found."});const{coach:u,profile:h,packages:m}=o,f=u,g=(y,v)=>{const b=(y/100).toLocaleString("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0});return v==="one_time"?b:`${b} / ${v}`};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($,{variant:"ghost",size:"sm",className:"text-white/80 hover:text-white hover:bg-white/10 mb-6",onClick:()=>t("/coaches"),children:[e.jsx(qa,{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(Oa,{className:"h-28 w-28 ring-4 ring-white/20",children:[e.jsx(Li,{src:f.photo_url||(h==null?void 0:h.avatar_url)}),e.jsx(za,{className:"text-3xl bg-white/20",children:((h==null?void 0:h.name)||"C").charAt(0)})]}),e.jsxs("div",{className:"flex-1",children:[f.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(Nn,{className:"h-3 w-3"})," LevelUp Certified"]}),e.jsx("h1",{className:"text-3xl md:text-4xl font-bold",children:(h==null?void 0:h.name)||"Coach"}),f.headline&&e.jsx("p",{className:"text-white/80 text-lg mt-2",children:f.headline}),((x=f.specialties)==null?void 0:x.length)>0&&e.jsx("div",{className:"flex flex-wrap gap-2 mt-4",children:f.specialties.map(y=>e.jsx(Be,{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:[f.intro_video_url&&e.jsx("div",{className:"aspect-video rounded-xl overflow-hidden bg-black",children:e.jsx("video",{src:f.intro_video_url,controls:!0,className:"w-full h-full"})}),f.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:f.bio})]}),e.jsx(tUs,{coachId:f.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"}),m.length===0?e.jsx(Ne,{children:e.jsx(Ie,{className:"p-6 text-sm text-muted-foreground text-center",children:"No packages available yet."})}):m.map(y=>{const v=y.accepting_clients===!1;return e.jsx(Ne,{className:`border-2 transition-colors ${v?"border-amber-200 bg-amber-50/30":"hover:border-[#406E71]"}`,children:e.jsxs(Ie,{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}),v&&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:g(y.price_cents,y.billing_interval)}),v?e.jsxs("div",{className:"mt-4 space-y-2",children:[e.jsx("div",{className:"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."}),e.jsxs($,{variant:"outline",className:"w-full",onClick:()=>l(!0),children:[e.jsx(zg,{className:"h-4 w-4 mr-1"})," Join Waitlist"]})]}):e.jsxs($,{className:"w-full mt-4 bg-[#406E71] hover:bg-[#2a4c64]",onClick:()=>d(y.id),disabled:r===y.id,children:[r===y.id?"Loading…":"Get Started",e.jsx(la,{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."}),e.jsxs($,{variant:"ghost",size:"sm",className:"w-full text-muted-foreground",onClick:()=>l(!0),children:[e.jsx(zg,{className:"h-4 w-4 mr-1"})," Join the waitlist instead"]})]})]}),e.jsx(NUs,{open:i,onOpenChange:l,coachId:f.id,coachName:h==null?void 0:h.name,packages:m.map(y=>({id:y.id,name:y.name}))})]})}const SUs=H2({full_name:vl().trim().min(2,"Please enter your full name").max(100),email:vl().trim().email("Enter a valid email").max(255),phone:vl().trim().max(40).optional().or(yx("")),brokerage:vl().trim().max(150).optional().or(yx("")),years_experience:vl().trim().max(40).optional().or(yx("")),specialties:vl().trim().max(500).optional().or(yx("")),why_coach:vl().trim().min(20,"Tell us a bit more — at least 20 characters").max(2e3),results_story:vl().trim().max(2e3).optional().or(yx("")),website_url:vl().trim().max(300).optional().or(yx("")),linkedin_url:vl().trim().max(300).optional().or(yx(""))});function CUs(){const s=Qn(),[t,n]=j.useState(!1),[r,a]=j.useState(!1),[i,l]=j.useState({full_name:"",email:"",phone:"",brokerage:"",years_experience:"",specialties:"",why_coach:"",results_story:"",website_url:"",linkedin_url:""}),o=(d,u)=>l(h=>({...h,[d]:u})),c=async d=>{var m;d.preventDefault();const u=SUs.safeParse(i);if(!u.success){const f=(m=Object.values(u.error.flatten().fieldErrors)[0])==null?void 0:m[0];return re.error(f||"Please check the form and try again")}n(!0);const{error:h}=await q.from("coach_applications").insert(u.data);if(n(!1),h)return re.error(h.message||"Could not submit application");a(!0),window.scrollTo({top:0,behavior:"smooth"})};return r?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(qr,{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($,{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(wr,{to:"/coaches",className:"inline-flex items-center gap-2 text-white/70 hover:text-white text-sm mb-8",children:[e.jsx(qa,{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(Nn,{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(Zn,{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(Yl,{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(Rm,{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(qr,{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(Kl,{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(Ja,{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(n5,{label:"Full name *",children:e.jsx(pe,{value:i.full_name,onChange:d=>o("full_name",d.target.value),required:!0,maxLength:100})}),e.jsx(n5,{label:"Email *",children:e.jsx(pe,{type:"email",value:i.email,onChange:d=>o("email",d.target.value),required:!0,maxLength:255})}),e.jsx(n5,{label:"Phone",children:e.jsx(pe,{value:i.phone,onChange:d=>o("phone",d.target.value),maxLength:40})}),e.jsx(n5,{label:"Current brokerage",children:e.jsx(pe,{value:i.brokerage,onChange:d=>o("brokerage",d.target.value),maxLength:150})}),e.jsx(n5,{label:"Years in real estate",children:e.jsx(pe,{value:i.years_experience,onChange:d=>o("years_experience",d.target.value),placeholder:"e.g. 8",maxLength:40})}),e.jsx(n5,{label:"Coaching specialties",children:e.jsx(pe,{value:i.specialties,onChange:d=>o("specialties",d.target.value),placeholder:"Lead gen, listings, luxury, teams…",maxLength:500})}),e.jsx(n5,{label:"Website",children:e.jsx(pe,{value:i.website_url,onChange:d=>o("website_url",d.target.value),placeholder:"https://",maxLength:300})}),e.jsx(n5,{label:"LinkedIn",children:e.jsx(pe,{value:i.linkedin_url,onChange:d=>o("linkedin_url",d.target.value),placeholder:"https://linkedin.com/in/",maxLength:300})})]}),e.jsx(n5,{label:"Why do you want to coach with LevelUp? *",children:e.jsx(Rs,{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(n5,{label:"Tell us about results you've created — for yourself or other agents.",children:e.jsx(Rs,{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($,{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 n5({label:s,children:t}){return e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{className:"text-sm font-semibold text-[#1c3447]",children:s}),t]})}const Hst="/assets/testimonial-avatar-1-BsCQFauB.jpg",Gst="/assets/testimonial-avatar-2-B6VPVc2t.jpg",Wst="/assets/testimonial-avatar-3-GuEFwYUE.jpg",Kst="/assets/testimonial-avatar-4-98iKMtkB.jpg",Yst="/assets/testimonial-avatar-5-ZsZfyxMX.jpg",AUs=[Hst,Gst,Wst,Kst,Yst],EUs=[{key:"dashboard",label:"Agent Command Center",caption:"Your entire day — smart queue, calendar and pipeline in one view.",src:Jae},{key:"crm",label:"CRM & Contact Hub",caption:"Contacts, tags, follow-ups and deal history, always one click away.",src:r6e},{key:"pipeline",label:"Deal Pipeline",caption:"Every active deal with tasks, forms and commission tracking built in.",src:a6e},{key:"staging",label:"Staging Studio",caption:"AI photo staging — MLS-ready before/afters in minutes.",src:i6e},{key:"coaching",label:"Coaching",caption:"Book live coaching sessions with Google Meet created automatically.",src:o6e},{key:"marketing",label:"Marketing Studio",caption:"Templates, social posts, reels and print — all branded to you.",src:l6e}];function TUs({slot:s}){return e.jsxs("figure",{className:"rounded-2xl overflow-hidden border border-white/10 bg-white/5 backdrop-blur-sm shadow-2xl",children:[e.jsxs("div",{className:"flex items-center gap-1.5 px-3 py-2 border-b border-white/10",children:[e.jsx("span",{className:"h-2.5 w-2.5 rounded-full bg-red-400/80"}),e.jsx("span",{className:"h-2.5 w-2.5 rounded-full bg-amber-400/80"}),e.jsx("span",{className:"h-2.5 w-2.5 rounded-full bg-green-400/80"}),e.jsx("span",{className:"ml-3 text-[11px] rounded px-2 py-0.5 bg-white/10 text-white/70",children:"dashboard.relevelup.com"})]}),s.src?e.jsx("img",{src:s.src,alt:`LevelUp ${s.label} screenshot`,className:"w-full h-auto block",loading:"lazy"}):e.jsxs("div",{className:"w-full aspect-[16/10] flex flex-col items-center justify-center gap-3 bg-white/5",children:[e.jsx(Nn,{className:"h-8 w-8 text-white/40"}),e.jsx("p",{className:"text-sm font-medium text-white/60",children:s.label})]}),e.jsxs("figcaption",{className:"px-4 py-3 text-sm text-white/80",children:[e.jsx("span",{className:"font-semibold text-white",children:s.label})," — ",s.caption]})]})}const MUs=H2({name:vl().trim().min(2,"Name must be at least 2 characters").max(100),email:vl().trim().email("Please enter a valid email address").max(255),phone:vl().trim().min(10,"Please enter a valid phone number").max(20).optional().or(yx("")),brokerage:vl().trim().max(200).optional().or(yx(""))}),PUs=[{icon:tf,title:"Academy Training",description:"Access a library of on-demand video training covering lead generation, marketing, technology, and more."},{icon:Yc,title:"300+ Templates",description:"Professional Canva templates for social media, flyers, postcards, and marketing materials."},{icon:Ta,title:"Live Events",description:"Weekly live training sessions, workshops, and Q&A events with industry experts."},{icon:Th,title:"Agent Community",description:"Connect with fellow agents, share wins, ask questions, and network in our private community."},{icon:Jr,title:"Resource Kits",description:"Downloadable toolkits with scripts, checklists, guides, and everything you need to close more deals."},{icon:ul,title:"Social Swag",description:"Fresh social media content and designs updated regularly to help you stand out online."}],IUs=[{category:"Marketing Studio",icon:xm,items:["Weekly Reels scripts","Social Post Generator","300+ Canva templates","Marketing Calendar","Postcard Direct Mail","Listing Music Videos","Social Swag drops"]},{category:"Lead Generation",icon:rh,items:["Custom lead websites","Open House Guest Book","RSVP pages","Resource landing pages","Listing Revival™","FSBO Breakthrough","Attract system"]},{category:"CRM & Deals",icon:Ev,items:["Agent OS CRM","Deal pipeline","Forms & e-signatures","Client portal","Smart follow-up queue","Lead ponds for teams","Google Business reviews"]},{category:"AI & Media",icon:sy,items:["AI Staging Studio","Video library & sharing","Screen recording","Virtual backgrounds","AI blog writer","YouTube → Blog","Ask AI assistant"]},{category:"Growth & Coaching",icon:of,items:["Academy courses","Live weekly coaching","Coaching programs","1:1 coaching booking","Private community","Live events & workshops"]},{category:"Brokerage Tools",icon:ji,items:["Manager dashboard","Team analytics","Agent onboarding","Office form libraries","Listing Exchange","Brand kits","Recruiting pipeline"]}],LUs=[{icon:Zn,title:"Contact Management",description:"Organize your sphere into relationship tiers—Top 25, Past Clients, Referral Partners, and more."},{icon:Nn,title:"Smart TouchPlans",description:"Automated action plans that tell you exactly who to contact and how, based on relationship type."},{icon:Da,title:"One-Tap Actions",description:"Call, text, or email contacts directly with pre-written scripts tailored to each relationship."},{icon:Fg,title:"Birthday Alerts",description:"Never miss an important date—get reminders for birthdays and home anniversaries."},{icon:ci,title:"Pop-by Map",description:"See all your contacts on a map and plan efficient pop-by routes in your area."},{icon:Wl,title:"Momentum Tracking",description:"Track your touch streaks, weekly goals, and relationship health scores."},{icon:Jo,title:"Relationship Health",description:"Visual dashboard showing which contacts need attention based on last touch date."},{icon:eg,title:"Daily Action Cards",description:"Wake up to a prioritized list of exactly who to reach out to today."}],RUs=[{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."}],Jce="bg-[url('data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNjAiIGhlaWdodD0iNjAiIHZpZXdCb3g9IjAgMCA2MCA2MCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48ZyBmaWxsPSJub25lIiBmaWxsLXJ1bGU9ImV2ZW5vZGQiPjxnIGZpbGw9IiNmZmZmZmYiIGZpbGwtb3BhY2l0eT0iMC40Ij48cGF0aCBkPSJNMzYgMzRoLTJ2LTRoMnY0em0wLTZ2LTRoLTJ2NGgyem0tNiA2aC0ydi00aDJ2NHptMC02di00aC0ydjRoMnoiLz48L2c+PC9nPjwvc3ZnPg==')]",DUs=()=>{const s=Qn(),[t,n]=j.useState(!1),[r,a]=j.useState({name:"",email:"",phone:"",brokerage:""}),[i,l]=j.useState({}),o=async d=>{var h,m;d.preventDefault(),l({});const u=MUs.safeParse(r);if(!u.success){const f={};u.error.issues.forEach(g=>{g.path[0]&&(f[g.path[0]]=g.message)}),l(f);return}n(!0);try{const f=typeof window<"u"&&localStorage.getItem("levelup_referral_code")||void 0,{data:g,error:x}=await q.functions.invoke("create-trial-signup",{body:{name:r.name.trim(),email:r.email.trim().toLowerCase(),phone:((h=r.phone)==null?void 0:h.trim())||void 0,brokerage:((m=r.brokerage)==null?void 0:m.trim())||void 0,referral_code:f}});if(x){console.error("Trial signup error:",x),re.error(x.message||"Something went wrong. Please try again.");return}if(g!=null&&g.error){re.error(g.error);return}re.success("🎉 Welcome aboard! Check your email to claim your account."),typeof window<"u"&&window.oaiq&&window.oaiq("measure","trial_started",{type:"plan_enrollment"}),typeof window<"u"&&window.fbq&&window.fbq("track","Lead",{content_name:"Trial Signup",value:0,currency:"USD"}),s("/trial/success")}catch(f){console.error("Trial signup error:",f),re.error("Something went wrong. Please try again.")}finally{n(!1)}},c=()=>{var d;(d=document.getElementById("trial-form"))==null||d.scrollIntoView({behavior:"smooth",block:"center"})};return e.jsxs(e.Fragment,{children:[e.jsxs(Ml,{children:[e.jsx("title",{children:"LevelUp — Start Your Free Trial | Real Growth. Real Tools. Real Results."}),e.jsx("meta",{name:"description",content:"Try LevelUp free — the all-in-one platform for real estate agents: coaching, done-for-you marketing, CRM, lead sites, social studio, and 40+ tools built to help you scale."}),e.jsx("link",{rel:"canonical",href:"https://dashboard.relevelup.com/trial"}),e.jsx("meta",{property:"og:title",content:"LevelUp — Start Your Free Trial | Real Growth. Real Tools. Real Results."}),e.jsx("meta",{property:"og:description",content:"Try LevelUp free — coaching, done-for-you marketing, CRM, lead sites, social studio, and 40+ tools built to help you scale."}),e.jsx("meta",{property:"og:type",content:"website"}),e.jsx("meta",{property:"og:url",content:"https://dashboard.relevelup.com/trial"}),e.jsx("meta",{property:"og:image",content:"https://relzejiswnotikjgvjhz.supabase.co/storage/v1/object/public/email-assets/trial-og.png"}),e.jsx("meta",{property:"og:image:width",content:"1200"}),e.jsx("meta",{property:"og:image:height",content:"630"}),e.jsx("meta",{name:"twitter:card",content:"summary_large_image"}),e.jsx("meta",{name:"twitter:image",content:"https://relzejiswnotikjgvjhz.supabase.co/storage/v1/object/public/email-assets/trial-og.png"}),e.jsx("script",{children:"!function(f,b,e,v,n,t,s){if(f.fbq)return;n=f.fbq=function(){n.callMethod?n.callMethod.apply(n,arguments):n.queue.push(arguments)};if(!f._fbq)f._fbq=n;n.push=n;n.loaded=!0;n.version='2.0';n.queue=[];t=b.createElement(e);t.async=!0;t.src=v;s=b.getElementsByTagName(e)[0];s.parentNode.insertBefore(t,s)}(window,document,'script','https://connect.facebook.net/en_US/fbevents.js'); fbq('init', '1388750291887997'); fbq('track', 'PageView');"})]}),e.jsx("noscript",{dangerouslySetInnerHTML:{__html:''}}),e.jsxs("div",{className:"min-h-screen bg-background overflow-hidden",children:[e.jsx("style",{children:` @keyframes hero-float { 0%,100% { transform: translateY(0px); } 50% { transform: translateY(-12px); } } @keyframes hero-glow { 0%,100% { opacity: 0.55; } 50% { opacity: 0.9; } } `}),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:WEe,alt:"LevelUp",className:"h-8 md:h-10"})}),e.jsxs("div",{className:"flex items-center gap-2 md:gap-4",children:[e.jsx($,{variant:"ghost",className:"text-white/90 hover:text-white hover:bg-white/10 hidden sm:inline-flex",onClick:()=>{var d;return(d=document.getElementById("features"))==null?void 0:d.scrollIntoView({behavior:"smooth"})},children:"Features"}),e.jsx($,{onClick:()=>s("/auth"),className:"bg-white text-[#4a6b6d] hover:bg-gray-100 font-medium shadow-md",children:"Sign In"})]})]})}),e.jsxs("section",{className:"relative overflow-hidden bg-[#0f2530]",children:[e.jsx("div",{className:"absolute inset-0 bg-gradient-to-b from-[#122c3a] via-[#16384a] to-[#0f2530]"}),e.jsx("div",{className:"absolute -top-40 left-1/2 -translate-x-1/2 h-[560px] w-[900px] rounded-full bg-[#4aa8a0]/25 blur-[140px] animate-[hero-glow_7s_ease-in-out_infinite]"}),e.jsx("div",{className:"absolute top-1/3 -left-40 h-[420px] w-[420px] rounded-full bg-[#2a6f8a]/20 blur-[120px]"}),e.jsx("div",{className:"absolute top-1/4 -right-40 h-[420px] w-[420px] rounded-full bg-[#c9a84c]/10 blur-[120px]"}),e.jsx("div",{className:"absolute inset-0 opacity-[0.12] bg-[linear-gradient(to_right,rgba(255,255,255,0.5)_1px,transparent_1px),linear-gradient(to_bottom,rgba(255,255,255,0.5)_1px,transparent_1px)] bg-[size:56px_56px] [mask-image:radial-gradient(ellipse_75%_65%_at_50%_35%,black,transparent)]"}),e.jsx("div",{className:"absolute inset-x-0 bottom-0 h-40 bg-gradient-to-t from-[#0f2530] to-transparent"}),e.jsx("div",{className:"container mx-auto px-4 relative",children:e.jsxs("div",{className:"grid lg:grid-cols-2 gap-12 items-center pt-28 md:pt-36 pb-20 md:pb-28",children:[e.jsxs("div",{className:"space-y-8 text-center lg:text-left",children:[e.jsx("div",{className:"flex justify-center lg:justify-start animate-fade-in",children:e.jsxs("span",{className:"inline-flex items-center gap-2 rounded-full border border-white/15 bg-white/5 backdrop-blur-sm px-4 py-1.5 text-xs md:text-sm font-semibold tracking-wide text-white/85 shadow-lg",children:[e.jsx(Nn,{className:"h-3.5 w-3.5 text-[#7fd4cc]"}),"7-Day Free Trial • No Credit Card Required"]})}),e.jsxs("h1",{className:"text-4xl sm:text-5xl md:text-6xl font-sans font-bold tracking-tight text-white leading-[1.05] animate-fade-in",children:["Take LevelUp for a"," ",e.jsx("span",{className:"bg-gradient-to-r from-[#8fe0d6] via-[#5cc0b6] to-[#e6c878] bg-clip-text text-transparent italic",children:"Free Test Drive"})]}),e.jsx("p",{className:"text-base md:text-xl text-white/65 max-w-xl mx-auto lg:mx-0 leading-relaxed animate-fade-in",children:"Weekly coaching, a smart CRM, done-for-you marketing and AI tools — everything a modern agent runs on, in one login."}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-4 justify-center lg:justify-start animate-fade-in",children:[e.jsxs("div",{className:"flex items-center gap-2 text-white/80",children:[e.jsx(qr,{className:"h-5 w-5 text-[#7fd4cc]"}),e.jsx("span",{children:"No credit card required"})]}),e.jsxs("div",{className:"flex items-center gap-2 text-white/80",children:[e.jsx(qr,{className:"h-5 w-5 text-[#7fd4cc]"}),e.jsx("span",{children:"Full access to all features"})]})]}),e.jsxs("div",{className:"flex items-center gap-4 justify-center lg:justify-start pt-2 animate-fade-in",children:[e.jsx("div",{className:"flex -space-x-3",children:AUs.map((d,u)=>e.jsx("img",{src:d,alt:`Agent ${u+1}`,className:"w-10 h-10 rounded-full border-2 border-white/20 object-cover"},u))}),e.jsxs("div",{children:[e.jsx("div",{className:"flex gap-0.5",children:[1,2,3,4,5].map(d=>e.jsx(Ja,{className:"h-4 w-4 fill-[#e6c878] text-[#e6c878]"},d))}),e.jsx("p",{className:"text-sm text-white/60",children:"Trusted by 3,000+ agents"})]})]}),e.jsxs("div",{className:"flex flex-wrap items-center justify-center lg:justify-start gap-x-6 gap-y-2 text-sm text-white/50 animate-fade-in",children:[e.jsxs("span",{className:"inline-flex items-center gap-2",children:[e.jsx(Mf,{className:"h-4 w-4 text-white/60"})," Cancel anytime"]}),e.jsxs("span",{className:"inline-flex items-center gap-2",children:[e.jsx(eg,{className:"h-4 w-4 text-[#7fd4cc]"})," Set up in 2 minutes"]})]})]}),e.jsxs("div",{id:"trial-form",className:"lg:pl-8 relative",children:[e.jsx("div",{className:"absolute -inset-6 rounded-[32px] bg-[#4aa8a0]/20 blur-2xl","aria-hidden":!0}),e.jsx(Ne,{className:"relative bg-white shadow-[0_40px_80px_-20px_rgba(0,0,0,0.7)] border-0 animate-[hero-float_7s_ease-in-out_infinite]",children:e.jsxs(Ie,{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(qg,{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(ee,{htmlFor:"name",children:"Full Name *"}),e.jsx(pe,{id:"name",type:"text",placeholder:"John Smith",value:r.name,onChange:d=>a({...r,name:d.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(ee,{htmlFor:"email",children:"Email Address *"}),e.jsx(pe,{id:"email",type:"email",placeholder:"john@example.com",value:r.email,onChange:d=>a({...r,email:d.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(ee,{htmlFor:"phone",children:"Phone Number"}),e.jsx(pe,{id:"phone",type:"tel",placeholder:"(555) 123-4567",value:r.phone,onChange:d=>a({...r,phone:d.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(ee,{htmlFor:"brokerage",children:"Brokerage Name"}),e.jsx(pe,{id:"brokerage",type:"text",placeholder:"Your brokerage or team name",value:r.brokerage,onChange:d=>a({...r,brokerage:d.target.value})}),i.brokerage&&e.jsx("p",{className:"text-sm text-destructive",children:i.brokerage})]}),e.jsx($,{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(kt,{className:"mr-2 h-5 w-5 animate-spin"}),"Creating Your Account..."]}):e.jsxs(e.Fragment,{children:["Start My Free Trial",e.jsx(ei,{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.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 ${Jce}`})}),e.jsxs("div",{className:"container mx-auto px-4 relative",children:[e.jsxs("div",{className:"text-center max-w-3xl mx-auto mb-14",children:[e.jsx("span",{className:"text-sm font-semibold tracking-[0.15em] uppercase text-white/70",children:"See it in action"}),e.jsx("h2",{className:"text-3xl md:text-5xl font-bold text-white mt-4 tracking-tight font-sans",children:"A real platform, not another course"}),e.jsx("p",{className:"text-white/60 mt-4 max-w-2xl mx-auto text-lg",children:"This is what you'll open on day one of your trial."})]}),e.jsx("div",{className:"grid md:grid-cols-2 gap-8 md:gap-10 max-w-6xl mx-auto",children:EUs.map(d=>e.jsx(TUs,{slot:d},d.key))}),e.jsx("div",{className:"text-center mt-12",children:e.jsxs($,{size:"lg",onClick:c,className:"px-8 py-7 text-lg font-semibold bg-white text-[#122c3a] hover:bg-white/90 shadow-2xl transition-all hover:scale-105 rounded-full",children:["Try It Free for 7 Days",e.jsx(ei,{className:"ml-2 w-5 h-5"})]})})]})]}),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.jsxs("span",{className:"inline-flex items-center gap-2 px-4 py-1.5 rounded-full bg-[#4a6b6d]/10 text-[#4a6b6d] text-sm font-semibold mb-5",children:[e.jsx(L4,{className:"w-4 h-4"}),"40+ tools & counting"]}),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:PUs.map((d,u)=>e.jsxs(Ne,{className:"group relative overflow-hidden border hover:border-[#4a6b6d]/50 transition-all duration-300 hover:shadow-lg bg-background",children:[e.jsxs(Ct,{children:[e.jsx("div",{className:"w-14 h-14 rounded-2xl bg-[#4a6b6d]/10 flex items-center justify-center mb-4",children:e.jsx(d.icon,{className:"w-7 h-7 text-[#4a6b6d]"})}),e.jsx(At,{className:"text-xl font-sans",children:d.title})]}),e.jsx(Ie,{children:e.jsx("p",{className:"text-muted-foreground leading-relaxed",children:d.description})})]},u))}),e.jsxs("div",{className:"mt-14 max-w-6xl mx-auto rounded-3xl bg-gradient-to-br from-[#1e3a4c] via-[#2a4f5f] to-[#3d6b6b] p-8 md:p-12 relative overflow-hidden shadow-2xl",children:[e.jsx("div",{className:"absolute inset-0 opacity-10",children:e.jsx("div",{className:`absolute inset-0 ${Jce}`})}),e.jsxs("div",{className:"relative",children:[e.jsxs("div",{className:"text-center mb-10",children:[e.jsx("h3",{className:"text-2xl md:text-3xl font-bold text-white font-sans",children:"...and that's just the beginning"}),e.jsx("p",{className:"text-white/60 mt-2",children:"Dozens of purpose-built tools — all included in your free trial."})]}),e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-x-10 gap-y-8",children:IUs.map(d=>e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2.5 mb-4",children:[e.jsx("span",{className:"flex h-8 w-8 items-center justify-center rounded-lg bg-white/10",children:e.jsx(d.icon,{className:"h-4 w-4 text-white"})}),e.jsx("span",{className:"text-sm font-bold uppercase tracking-wider text-white/90",children:d.category})]}),e.jsx("ul",{className:"space-y-2.5",children:d.items.map(u=>e.jsxs("li",{className:"flex items-center gap-2.5 text-white/70 text-sm",children:[e.jsx(la,{className:"h-3.5 w-3.5 text-emerald-300 shrink-0"}),u]},u))})]},d.category))}),e.jsxs("p",{className:"text-center text-white/50 text-sm mt-10 flex items-center justify-center gap-2",children:[e.jsx(Nn,{className:"h-4 w-4"}),"New tools added every month — membership keeps getting more valuable."]})]})]})]})}),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 ${Jce}`})}),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(Nn,{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:LUs.map((d,u)=>e.jsxs(Ne,{className:"group relative overflow-hidden border-0 bg-white/10 backdrop-blur-sm hover:bg-white/20 transition-all duration-300",children:[e.jsxs(Ct,{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(d.icon,{className:"w-6 h-6 text-white"})}),e.jsx(At,{className:"text-lg font-semibold text-white",children:d.title})]}),e.jsx(Ie,{children:e.jsx("p",{className:"text-white/70 text-sm leading-relaxed",children:d.description})})]},u))})]})]}),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:RUs.map((d,u)=>e.jsx(Ne,{className:"border hover:shadow-lg transition-shadow",children:e.jsxs(Ie,{className:"p-6",children:[e.jsx("div",{className:"flex gap-1 mb-4",children:[1,2,3,4,5].map(h=>e.jsx(Ja,{className:"h-4 w-4 fill-yellow-400 text-yellow-400"},h))}),e.jsxs("p",{className:"text-muted-foreground mb-4 italic",children:['"',d.quote,'"']}),e.jsxs("div",{children:[e.jsx("p",{className:"font-semibold",children:d.name}),e.jsx("p",{className:"text-sm text-muted-foreground",children:d.role})]})]})},u))})]})}),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(Mf,{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(eg,{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(Zn,{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(Ne,{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 ${Jce}`})}),e.jsxs(Ie,{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($,{onClick:c,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(ei,{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:TG,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:"© 2026 LevelUp Consulting Group. All rights reserved."})]})})})]})]})},FUs=()=>{const s=Qn();return e.jsxs(e.Fragment,{children:[e.jsx(Ml,{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:WEe,alt:"LevelUp",className:"h-8 md:h-10"})}),e.jsx($,{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(Ne,{className:"max-w-lg w-full bg-white shadow-2xl border-0",children:e.jsxs(Ie,{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(qr,{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(Ax,{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(mn,{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($,{onClick:()=>s("/auth"),className:"bg-[#4a6b6d] hover:bg-[#3d5a5c]",children:["Go to Sign In",e.jsx(ei,{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:TG,alt:"LevelUp",className:"h-8"}),e.jsxs("p",{className:"text-sm text-white/40",children:["© ",new Date().getFullYear()," LevelUp Consulting Group. All rights reserved."]})]})})})]})]})},OUs="https://us06web.zoom.us/meeting/register/7Ybq3ZIkRn2_RLkkv_uY8A",ede="ld-open-house-invite-dismissed";function E$t({pageKey:s,headline:t="Not ready to join the LevelUp family yet?",delayMs:n=15e3}){const[r,a]=j.useState(!1);j.useEffect(()=>{if(localStorage.getItem(`${ede}-${s}`))return;let o=null;const c=d=>{d.clientY<=0&&!localStorage.getItem(`${ede}-${s}`)&&a(!0)};return o=setTimeout(()=>{localStorage.getItem(`${ede}-${s}`)||a(!0)},n),document.addEventListener("mouseleave",c),()=>{o&&clearTimeout(o),document.removeEventListener("mouseleave",c)}},[s,n]);const i=()=>{a(!1),localStorage.setItem(`${ede}-${s}`,"1")};return e.jsx(zs,{open:r,onOpenChange:l=>!l&&i(),children:e.jsx(Os,{className:"laborday-theme max-w-md border-0 p-0 overflow-hidden bg-transparent",overlayClassName:"bg-black/70 backdrop-blur-sm",children:e.jsxs("div",{className:"relative text-white",style:{background:"linear-gradient(150deg, hsl(var(--ld-navy)) 0%, hsl(var(--ld-navy-deep)) 100%)"},children:[e.jsx("div",{className:"h-2 w-full",style:{background:"repeating-linear-gradient(90deg, hsl(var(--ld-red)) 0px, hsl(var(--ld-red)) 24px, hsl(var(--ld-cream)) 24px, hsl(var(--ld-cream)) 48px, hsl(var(--ld-navy)) 48px, hsl(var(--ld-navy)) 72px)"}}),e.jsx("button",{onClick:i,className:"absolute right-3 top-5 rounded-full p-1.5 text-white/70 hover:bg-white/10 hover:text-white transition-colors","aria-label":"Close",children:e.jsx(gr,{className:"h-4 w-4"})}),e.jsxs("div",{className:"p-6 pt-8 text-center",children:[e.jsx("div",{className:"mx-auto mb-4 flex h-14 w-14 items-center justify-center rounded-full bg-white/10 ring-1 ring-white/20",children:e.jsx(ua,{className:"h-6 w-6 ld-gold-text"})}),e.jsxs(Us,{children:[e.jsx(Bs,{className:"text-xl font-bold leading-tight text-white",children:t}),e.jsxs(Ir,{className:"text-white/80 mt-3 text-sm leading-relaxed",children:["Join us for our next"," ",e.jsx("span",{className:"font-semibold ld-gold-text",children:"LevelUp Live Open House"})," ","and get an inside look at our agent growth platform."]})]}),e.jsxs("div",{className:"mt-5 inline-flex items-center gap-2 rounded-full bg-white/10 px-4 py-2 text-sm font-medium text-white ring-1 ring-white/15",children:[e.jsx(Ta,{className:"h-4 w-4 ld-gold-text"}),"Every Friday at 1:00 PM ET"]}),e.jsxs("div",{className:"mt-6 flex flex-col gap-3",children:[e.jsx($,{asChild:!0,size:"lg",className:"w-full bg-accent text-accent-foreground hover:bg-accent/90 font-bold",children:e.jsxs("a",{href:OUs,target:"_blank",rel:"noreferrer",className:"gap-2",children:["Register for the Open House",e.jsx(kr,{className:"h-4 w-4"})]})}),e.jsx($,{variant:"ghost",onClick:i,className:"w-full text-white/70 hover:bg-white/10 hover:text-white",children:"Maybe later"})]}),e.jsx("p",{className:"mt-4 text-xs text-white/50",children:"No pressure — you can always come back to this offer."})]})]})})})}const T$t=Date.UTC(2026,8,12,3,59,59),W7e="Friday, September 11 at 11:59 PM ET",K7e=300,tde=39*12,zUs=[{key:"dashboard",label:"Agent Command Center",caption:"Your entire day — smart queue, calendar and pipeline in one view.",src:Jae},{key:"crm",label:"CRM & Contact Hub",caption:"Contacts, tags, follow-ups and deal history, always one click away.",src:r6e},{key:"pipeline",label:"Deal Pipeline",caption:"Every active deal with tasks, forms and commission tracking built in.",src:a6e},{key:"staging",label:"Staging Studio",caption:"AI photo staging — MLS-ready before/afters in minutes.",src:i6e},{key:"coaching",label:"Coaching",caption:"Book live coaching sessions with Google Meet created automatically.",src:o6e},{key:"marketing",label:"Marketing Studio",caption:"Templates, social posts, reels and print — all branded to you.",src:l6e}],BUs=[{name:"Valerie Harp",meta:"Local Guide · Real Estate Agent",when:"4 months ago",text:"Level Up has been an absolute game changer for my real estate business. The platform is incredibly easy to use and by far one of the most user-friendly systems I've worked with. Everything is streamlined, intuitive, and designed with agents in mind."},{name:"Robert Larente",meta:"Real Estate Agent",when:"5 months ago",text:"I'm fortunate that my Broker started providing LevelUp membership a few years ago. Originally I used it for kvCore/Bold CRM training. But with the amazing amount of resources that Jeremy and his crew keep adding, I'm quickly canceling my subscriptions to other service providers."},{name:"Tom Lois",meta:"Real Estate Agent",when:"5 months ago",text:"Jeremy and his team at LevelUp continue to upgrade, update, and uplift agents with their meaningful content and insight. Whether you're a newbie or a seasoned agent, this program is for you! Try it — you'll REALLY like it!"},{name:"Michael Smith",meta:"Local Guide · Real Estate Agent",when:"7 months ago",text:"Great value in the material, ideas, etc. shared by the LevelUp team. They consistently provide implementable examples of ways to impact your real estate business. Not just theory, but real ideas/tasks that can be quickly implemented."},{name:"Pamela Nichols",meta:"Local Guide · Real Estate Agent",when:"4 months ago",text:"I'm loving this platform and all the excellent quick and easy information to use! It has been the easiest thing I've ever used to care for my database! I love the quick videos — quick and to the point!"},{name:"Tracy VanderWall",meta:"Local Guide · Broker/Owner",when:"7 months ago",text:"Best investment my brokerage has made! The value of this platform is AMAZING! The entire LEVELUP Team is wonderful!"},{name:"Bill Burns",meta:"Local Guide · Broker",when:"5 months ago",text:"Jeremy and his team are amazing! Level Up can next level your brokerage!"},{name:"Anissa, REMAX Executives",meta:"Real Estate Agent",when:"6 months ago",text:"So far this has helped me tremendously! Keeps me more organized and motivated to stay on top of these leads that get lost in the daily mix."}],$Us="https://www.google.com/search?q=levelup+consulting+group#lrd=0x8842f50045c4bd33:0xc9b99b5330a91b3f,1,,,,",M$t=[{icon:Zn,title:"1:1 & Group Coaching",desc:"Book live coaching sessions with Jeremy and the LevelUp team — Google Meet created automatically, tracked on your calendar.",value:1200},{icon:c7,title:"Full CRM & Contact Hub",desc:"Contacts, tags, smart follow-ups, lead ponds and team assignments — your database finally organized.",value:600},{icon:wb,title:"Deal Pipeline",desc:"Track every transaction from offer to closing with tasks, forms and commission math built in.",value:480},{icon:Cx,title:"Staging Studio",desc:"AI virtual staging with MLS-ready before/after photos — no photographer or stager needed.",value:1200},{icon:Yc,title:"Marketing & Social Studio",desc:"300+ branded templates, social posts, postcards and the weekly Reels engine.",value:720},{icon:dl,title:"Lead Sites",desc:"SEO-optimized neighborhood and listing websites that rank on Google and capture leads 24/7.",value:960},{icon:of,title:"Academy Training",desc:"On-demand video training on lead gen, marketing and tech — live weekly sessions too.",value:588},{icon:m_,title:"Forms & E-Signature",desc:"Upload any PDF, map fields, send for signature — done from one place.",value:300},{icon:ua,title:"Weekly Reels & Video Tools",desc:"Personalized Instagram scripts delivered every Monday, plus screen recording and virtual backgrounds.",value:468},{icon:eo,title:"Reviews Engine",desc:"Collect Google and video reviews with a single link — your reputation on autopilot.",value:240},{icon:Nn,title:"ChatGPT App + 30 AI Tools",desc:"Your entire business controllable from ChatGPT — create contacts, open houses, marketing assets and more.",value:500},{icon:Ta,title:"My Calendar & Booking",desc:"Agent-first calendar with time zones, Google Calendar sync and self-serve booking links.",value:144}],Vvt=M$t.reduce((s,t)=>s+t.value,0),UUs=[{q:"What happens after the first year?",a:"Your rate is locked in. As long as your subscription stays active, you renew at $300/year — forever. No surprises, no bump to the regular price."},{q:"Is this the full platform or a stripped-down version?",a:"The full platform. Everything an Individual Agent member gets: coaching, CRM, deal pipeline, Staging Studio, Marketing Studio, lead sites, Academy, forms with e-signature, reviews, Weekly Reels, Listing Exchange and the ChatGPT app."},{q:"How do I manage or cancel my subscription?",a:"Right from your profile. Your billing lives in your LevelUp account settings with a Stripe customer portal — change cards, see invoices or cancel anytime without calling anyone."},{q:"Is there a free trial with this offer?",a:"No trial on this one — you're charged $300 today and get a full 12 months. That's how we're able to offer the lowest rate we've ever run."},{q:"I'm already a monthly member. Can I switch?",a:"Yes — use the button with the same email on your account and Stripe will match you. If anything looks off after checkout, reach out and we'll sort it immediately."},{q:"Who is LevelUp for?",a:"Solo agents and team agents who want one system for their database, marketing, deals and growth coaching — whether you're brand new or a seasoned producer."}];function P$t(s){const[t,n]=j.useState(()=>Date.now());j.useEffect(()=>{const i=setInterval(()=>n(Date.now()),1e3);return()=>clearInterval(i)},[]);const r=Math.max(0,s-t),a=Math.floor(r/1e3);return{expired:r<=0,d:Math.floor(a/86400),h:Math.floor(a%86400/3600),m:Math.floor(a%3600/60),sec:a%60}}function Hvt({dark:s=!1}){const{d:t,h:n,m:r,sec:a,expired:i}=P$t(T$t);if(i)return null;const l=[{v:t,l:"Days"},{v:n,l:"Hours"},{v:r,l:"Min"},{v:a,l:"Sec"}];return e.jsx("div",{className:"flex items-center gap-2 sm:gap-3",children:l.map(o=>e.jsxs("div",{className:`${s?"ld-glass":"bg-card border"} rounded-xl px-3 py-2 sm:px-4 sm:py-3 text-center min-w-[60px] sm:min-w-[72px]`,children:[e.jsx("div",{className:`text-2xl sm:text-3xl font-bold tabular-nums ${s?"text-white":"text-foreground"}`,children:String(o.v).padStart(2,"0")}),e.jsx("div",{className:`text-[10px] uppercase tracking-widest ${s?"text-white/60":"text-muted-foreground"}`,children:o.l})]},o.l))})}function Gvt(){return e.jsx("div",{className:"flex gap-0.5","aria-label":"5 out of 5 stars",children:Array.from({length:5}).map((s,t)=>e.jsx(Ja,{className:"h-4 w-4 fill-accent text-accent"},t))})}function qUs({slot:s,dark:t=!0}){return e.jsxs("figure",{className:`ld-shot overflow-hidden border ${t?"ld-glass":"bg-card border-border"}`,children:[e.jsxs("div",{className:`flex items-center gap-1.5 px-3 py-2 border-b ${t?"border-white/10":"border-border"}`,children:[e.jsx("span",{className:"h-2.5 w-2.5 rounded-full bg-red-400/80"}),e.jsx("span",{className:"h-2.5 w-2.5 rounded-full bg-amber-400/80"}),e.jsx("span",{className:"h-2.5 w-2.5 rounded-full bg-green-400/80"}),e.jsx("span",{className:`ml-3 text-[11px] rounded px-2 py-0.5 ${t?"bg-white/10 text-white/70":"bg-muted text-muted-foreground"}`,children:"dashboard.relevelup.com"})]}),s.src?e.jsx("img",{src:s.src,alt:`LevelUp ${s.label} screenshot`,className:"w-full h-auto block",loading:"lazy"}):e.jsxs("div",{className:`w-full aspect-[16/10] flex flex-col items-center justify-center gap-3 ${t?"bg-white/5":"bg-muted"}`,children:[e.jsx(Nn,{className:`h-8 w-8 ${t?"text-white/40":"text-muted-foreground/50"}`}),e.jsx("p",{className:`text-sm font-medium ${t?"text-white/60":"text-muted-foreground"}`,children:s.label}),e.jsx("p",{className:`text-xs px-6 text-center ${t?"text-white/40":"text-muted-foreground/70"}`,children:"Screenshot placeholder"})]}),e.jsxs("figcaption",{className:`px-4 py-3 text-sm ${t?"text-white/80":"text-muted-foreground"}`,children:[e.jsx("span",{className:`font-semibold ${t?"text-white":"text-foreground"}`,children:s.label})," — ",s.caption]})]})}function VUs(){const{expired:s}=P$t(T$t),[t,n]=j.useState(""),[r,a]=j.useState(""),[i,l]=j.useState(!1),[o,c]=j.useState(0),d=j.useMemo(()=>[Hst,Gst,Wst,Kst,Yst],[]),u=tde-K7e,h=async()=>{if(!r.trim()||!r.includes("@")){re.error("Enter your email to claim the offer.");return}l(!0);try{const{data:m,error:f}=await q.functions.invoke("create-checkout",{body:{tier:"individual_annual",email:r.trim(),name:t.trim()||void 0,skipTrial:!0}});if(f){const g=f instanceof Tae?await f.context.text():f.message;throw new Error(g||"Checkout failed to start")}if(m!=null&&m.url){window.location.href=m.url;return}throw new Error("No checkout URL returned")}catch(m){console.error("Labor Day checkout error:",m),re.error(m.message||"Could not start checkout. Please try again."),l(!1)}};return e.jsxs("div",{className:"laborday-theme min-h-screen bg-background",children:[e.jsxs(Ml,{children:[e.jsx("title",{children:"Labor Day Sale — LevelUp for $300/Year (Save $168) | LevelUp Consulting Group"}),e.jsx("meta",{name:"description",content:`Labor Day only: get the full LevelUp agent growth platform — coaching, CRM, deal pipeline, Staging Studio, marketing and more — for $300/year instead of $39/month. Locked in for as long as you stay a member. Ends ${W7e}.`}),e.jsx("meta",{property:"og:title",content:"Labor Day Sale — LevelUp for $300/Year"}),e.jsx("meta",{property:"og:description",content:"Coaching, CRM, deal pipeline, Staging Studio, marketing studio and more. $300/year, locked in. Ends Sept 11 at midnight."}),e.jsx("meta",{property:"og:type",content:"website"}),e.jsx("meta",{name:"twitter:card",content:"summary_large_image"}),e.jsx("link",{rel:"preconnect",href:"https://fonts.googleapis.com"}),e.jsx("link",{rel:"preconnect",href:"https://fonts.gstatic.com",crossOrigin:"anonymous"}),e.jsx("link",{href:"https://fonts.googleapis.com/css2?family=Archivo+Black&display=swap",rel:"stylesheet"}),e.jsx("script",{type:"application/ld+json",children:JSON.stringify({"@context":"https://schema.org","@type":"Offer",name:"LevelUp Individual Agent — Labor Day Annual",price:"300.00",priceCurrency:"USD",availabilityEnds:"2026-09-11T23:59:59-04:00",seller:{"@type":"Organization",name:"LevelUp Consulting Group"}})})]}),!s&&e.jsxs("div",{className:"fixed bottom-0 inset-x-0 z-50 md:hidden bg-foreground/95 backdrop-blur border-t border-white/10 px-4 py-3 flex items-center justify-between gap-3",style:{backgroundColor:"hsl(var(--ld-navy-deep) / 0.96)"},children:[e.jsxs("div",{className:"text-white",children:[e.jsx("div",{className:"text-xs text-white/60 uppercase tracking-wider",children:"Labor Day"}),e.jsxs("div",{className:"font-bold",children:["$300",e.jsx("span",{className:"text-sm font-normal text-white/70",children:"/year"})," ",e.jsxs("span",{className:"text-xs line-through text-white/50 ml-1",children:["$",tde]})]})]}),e.jsx($,{asChild:!0,className:"bg-accent text-accent-foreground hover:bg-accent/90 font-semibold",children:e.jsx("a",{href:"#claim",children:"Claim Offer"})})]}),e.jsxs("header",{className:"ld-dark relative overflow-hidden",children:[e.jsx("div",{className:"ld-flagbar absolute top-0 inset-x-0 z-10"}),e.jsx("div",{className:"ld-stars absolute inset-0 opacity-[0.10] pointer-events-none"}),e.jsxs("div",{className:"relative max-w-6xl mx-auto px-6 pt-12 pb-20 md:pb-28",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("img",{src:TG,alt:"LevelUp Consulting Group",className:"h-9 md:h-11 w-auto"}),e.jsxs("div",{className:"hidden sm:flex items-center gap-2 text-white/70 text-sm",children:[e.jsx("div",{className:"flex -space-x-2",children:d.map((m,f)=>e.jsx("img",{src:m,alt:"",className:"h-7 w-7 rounded-full border-2 border-white/20 object-cover"},f))}),e.jsx("span",{children:"3,000+ agents"})]})]}),e.jsxs("div",{className:"mt-16 md:mt-24 text-center max-w-4xl mx-auto",children:[e.jsxs("div",{className:"mb-10",children:[e.jsx("span",{className:"ld-stamp text-xs sm:text-sm",children:"★ Labor Day Sale ★"}),e.jsxs("p",{className:"mt-4 text-white/60 text-xs sm:text-sm uppercase tracking-[0.2em] font-semibold",children:["Ends ",W7e]})]}),e.jsxs("h1",{className:"ld-display text-4xl sm:text-6xl lg:text-7xl text-white leading-[1.05] uppercase",children:["Everything you need to grow your business.",e.jsx("span",{className:"block mt-4 ld-gold-text",children:"One payment of $300."})]}),e.jsx("div",{className:"mt-6 flex items-center justify-center gap-2 text-accent","aria-hidden":!0,children:Array.from({length:5}).map((m,f)=>e.jsx(Ja,{className:"h-4 w-4 fill-accent text-accent"},f))}),e.jsxs("p",{className:"mt-6 text-lg md:text-xl text-white/75 max-w-2xl mx-auto leading-relaxed",children:["Coaching, a full agent growth platform, CRM, deal pipeline, Staging Studio, marketing studio and more —"," ",e.jsxs("span",{className:"text-white font-semibold",children:["normally $39/month ($",tde,"/year)"]}),". This week only, get a full year for"," ",e.jsx("span",{className:"text-white font-semibold",children:"$300"}),", locked in for as long as you're a member."]}),e.jsxs("div",{className:"mt-10 flex flex-col items-center gap-4",children:[e.jsx(Hvt,{dark:!0}),e.jsx("p",{className:"text-xs uppercase tracking-widest text-white/50",children:"Offer disappears when the clock hits zero"})]}),e.jsxs("form",{id:"claim",onSubmit:m=>{m.preventDefault(),h()},className:"mt-8 mx-auto max-w-xl ld-glass rounded-2xl p-4 sm:p-5",children:[s?e.jsxs("div",{className:"text-center py-2",children:[e.jsx("p",{className:"text-white font-semibold text-lg",children:"This Labor Day offer has ended."}),e.jsx("p",{className:"text-white/60 text-sm mt-1 mb-4",children:"You can still join LevelUp with a free 7-day trial."}),e.jsx($,{asChild:!0,size:"lg",className:"bg-accent text-accent-foreground hover:bg-accent/90 font-semibold w-full sm:w-auto",children:e.jsxs("a",{href:"/trial",children:["Start a Free Trial ",e.jsx(ei,{className:"ml-2 h-4 w-4"})]})})]}):e.jsxs("div",{className:"flex flex-col sm:flex-row gap-3",children:[e.jsx(pe,{value:t,onChange:m=>n(m.target.value),placeholder:"Your name",className:"bg-white/10 border-white/20 text-white placeholder:text-white/50 h-12",autoComplete:"name"}),e.jsx(pe,{value:r,onChange:m=>a(m.target.value),type:"email",placeholder:"Your email",className:"bg-white/10 border-white/20 text-white placeholder:text-white/50 h-12",autoComplete:"email",required:!0}),e.jsx($,{type:"submit",disabled:i,size:"lg",className:"bg-accent text-accent-foreground hover:bg-accent/90 font-bold h-12 px-6 whitespace-nowrap",children:i?e.jsx(kt,{className:"h-5 w-5 animate-spin"}):e.jsxs(e.Fragment,{children:["Lock in $300/yr ",e.jsx(ei,{className:"ml-2 h-5 w-5"})]})})]}),!s&&e.jsxs("p",{className:"text-white/50 text-xs mt-3 flex items-center justify-center gap-1.5",children:[e.jsx(pc,{className:"h-3 w-3"})," Secure Stripe checkout · Manage or cancel anytime from your profile"]})]}),e.jsxs("p",{className:"mt-6 text-white/70 text-sm",children:["Trusted by ",e.jsx("span",{className:"font-bold text-white",children:"3,000+ agents"})," to run and grow their business"]})]})]})]}),e.jsx("section",{className:"py-20 md:py-28 px-6",children:e.jsxs("div",{className:"max-w-6xl mx-auto",children:[e.jsxs("div",{className:"text-center mb-14",children:[e.jsx("span",{className:"text-sm font-semibold tracking-[0.15em] uppercase text-primary",children:"Everything included"}),e.jsx("h2",{className:"text-3xl md:text-5xl font-bold mt-4 tracking-tight",children:"One membership. The entire platform."}),e.jsxs("p",{className:"text-muted-foreground mt-4 max-w-2xl mx-auto",children:["This isn't a teaser tier. You get every tool LevelUp members use daily — worth $",Vvt.toLocaleString(),"/year at market rates."]})]}),e.jsxs("div",{className:"grid sm:grid-cols-2 lg:grid-cols-3 gap-5",children:[M$t.map(m=>e.jsxs("div",{className:"bg-card border rounded-2xl p-6 flex flex-col gap-3 hover:shadow-lg transition-shadow",children:[e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsx("div",{className:"h-11 w-11 rounded-xl bg-primary/10 flex items-center justify-center",children:e.jsx(m.icon,{className:"h-5 w-5 text-primary"})}),e.jsxs("span",{className:"text-xs font-semibold text-muted-foreground bg-muted rounded-full px-2.5 py-1",children:["$",m.value.toLocaleString(),"/yr value"]})]}),e.jsx("h3",{className:"font-bold text-lg",children:m.title}),e.jsx("p",{className:"text-sm text-muted-foreground leading-relaxed",children:m.desc})]},m.title)),e.jsxs("div",{className:"bg-foreground text-background rounded-2xl p-6 flex flex-col justify-center items-center text-center gap-2",style:{backgroundColor:"hsl(var(--ld-navy))",color:"white"},children:[e.jsx("div",{className:"text-sm uppercase tracking-widest text-white/60",children:"Total value"}),e.jsxs("div",{className:"text-4xl font-bold",children:["$",Vvt.toLocaleString(),e.jsx("span",{className:"text-lg font-normal text-white/60",children:"/yr"})]}),e.jsxs("div",{className:"text-white/70 text-sm",children:["Your Labor Day price: ",e.jsx("span",{className:"font-bold text-white",children:"$300/yr"})]})]})]})]})}),e.jsx("section",{className:"ld-dark py-20 md:py-28 px-6",children:e.jsxs("div",{className:"max-w-6xl mx-auto",children:[e.jsxs("div",{className:"text-center mb-14",children:[e.jsx("span",{className:"text-sm font-semibold tracking-[0.15em] uppercase text-accent",children:"See it in action"}),e.jsx("h2",{className:"text-3xl md:text-5xl font-bold text-white mt-4 tracking-tight",children:"A real platform, not another course"}),e.jsx("p",{className:"text-white/60 mt-4 max-w-2xl mx-auto",children:"This is what members open every morning."})]}),e.jsx("div",{className:"grid md:grid-cols-2 gap-8 md:gap-10",children:zUs.map(m=>e.jsx(qUs,{slot:m},m.key))})]})}),e.jsx("div",{className:"ld-divider pb-4","aria-hidden":!0,children:e.jsx("span",{children:"★★★"})}),e.jsx("section",{className:"py-20 md:py-28 px-6",children:e.jsxs("div",{className:"max-w-6xl mx-auto",children:[e.jsxs("div",{className:"text-center mb-12",children:[e.jsxs("div",{className:"inline-flex items-center gap-3 bg-card border rounded-full px-5 py-2.5 mb-6",children:[e.jsxs("svg",{viewBox:"0 0 24 24",className:"h-5 w-5","aria-hidden":!0,children:[e.jsx("path",{fill:"#4285F4",d:"M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92a5.06 5.06 0 0 1-2.2 3.32v2.77h3.57c2.08-1.92 3.27-4.74 3.27-8.1z"}),e.jsx("path",{fill:"#34A853",d:"M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.98.66-2.23 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84C3.99 20.53 7.7 23 12 23z"}),e.jsx("path",{fill:"#FBBC05",d:"M5.84 14.1a7.16 7.16 0 0 1 0-4.2V7.06H2.18a11 11 0 0 0 0 9.88l3.66-2.84z"}),e.jsx("path",{fill:"#EA4335",d:"M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1 7.7 1 3.99 3.47 2.18 7.06l3.66 2.84c.87-2.6 3.3-4.52 6.16-4.52z"})]}),e.jsx("span",{className:"font-semibold",children:"5.0"}),e.jsx(Gvt,{}),e.jsx("span",{className:"text-muted-foreground text-sm",children:"on Google"})]}),e.jsx("h2",{className:"text-3xl md:text-5xl font-bold tracking-tight",children:"Why 3,000+ agents trust LevelUp"}),e.jsx("p",{className:"text-muted-foreground mt-4 max-w-2xl mx-auto",children:"Real reviews from real agents, pulled from our Google Business profile."})]}),e.jsx("div",{className:"grid sm:grid-cols-2 lg:grid-cols-4 gap-5",children:BUs.map(m=>e.jsxs("blockquote",{className:"bg-card border rounded-2xl p-5 flex flex-col gap-3",children:[e.jsx(Gvt,{}),e.jsxs("p",{className:"text-sm text-foreground/90 leading-relaxed flex-1",children:['"',m.text,'"']}),e.jsxs("footer",{children:[e.jsx("div",{className:"font-semibold text-sm",children:m.name}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[m.meta," · ",m.when]})]})]},m.name))}),e.jsx("div",{className:"text-center mt-8",children:e.jsx("a",{href:$Us,target:"_blank",rel:"noreferrer",className:"text-sm font-medium text-primary hover:underline",children:"Read all reviews on Google →"})})]})}),e.jsx("section",{className:"pb-20 md:pb-28 px-6",children:e.jsxs("div",{className:"max-w-4xl mx-auto",children:[e.jsx("div",{className:"text-center mb-12",children:e.jsx("h2",{className:"text-3xl md:text-5xl font-bold tracking-tight",children:"The math is simple"})}),e.jsxs("div",{className:"grid md:grid-cols-2 gap-6",children:[e.jsxs("div",{className:"bg-card border rounded-3xl p-8",children:[e.jsx("h3",{className:"font-bold text-xl text-muted-foreground",children:"Regular Monthly"}),e.jsxs("div",{className:"mt-4 flex items-baseline gap-2",children:[e.jsx("span",{className:"text-5xl font-bold text-muted-foreground",children:"$39"}),e.jsx("span",{className:"text-muted-foreground",children:"/month"})]}),e.jsxs("ul",{className:"mt-6 space-y-3 text-sm text-muted-foreground",children:[e.jsxs("li",{className:"flex gap-2",children:[e.jsx(gr,{className:"h-4 w-4 mt-0.5 shrink-0"})," $",tde," per year"]}),e.jsxs("li",{className:"flex gap-2",children:[e.jsx(gr,{className:"h-4 w-4 mt-0.5 shrink-0"})," Price can change at renewal"]}),e.jsxs("li",{className:"flex gap-2",children:[e.jsx(la,{className:"h-4 w-4 mt-0.5 shrink-0 text-primary"})," Full platform access"]})]})]}),e.jsxs("div",{className:"relative rounded-3xl p-8 text-white overflow-hidden",style:{background:"linear-gradient(150deg, hsl(var(--ld-navy)), hsl(var(--ld-navy-deep)))"},children:[e.jsxs("div",{className:"absolute top-4 right-4 bg-accent text-accent-foreground text-xs font-bold uppercase tracking-wider rounded-full px-3 py-1",children:["Save $",u]}),e.jsx("h3",{className:"font-bold text-xl",children:"Labor Day Annual"}),e.jsxs("div",{className:"mt-4 flex items-baseline gap-2",children:[e.jsxs("span",{className:"text-5xl font-bold",children:["$",K7e]}),e.jsx("span",{className:"text-white/70",children:"/year"})]}),e.jsx("p",{className:"text-accent font-semibold text-sm mt-1",children:"That's just $25/month"}),e.jsxs("ul",{className:"mt-6 space-y-3 text-sm text-white/85",children:[e.jsxs("li",{className:"flex gap-2",children:[e.jsx(la,{className:"h-4 w-4 mt-0.5 shrink-0 text-accent"})," $",K7e," per year — save $",u," vs monthly"]}),e.jsxs("li",{className:"flex gap-2",children:[e.jsx(Uq,{className:"h-4 w-4 mt-0.5 shrink-0 text-accent"})," Rate locked in for as long as you're a member"]}),e.jsxs("li",{className:"flex gap-2",children:[e.jsx(la,{className:"h-4 w-4 mt-0.5 shrink-0 text-accent"})," Full platform access — everything included"]}),e.jsxs("li",{className:"flex gap-2",children:[e.jsx(Mf,{className:"h-4 w-4 mt-0.5 shrink-0 text-accent"})," Manage or cancel anytime from your profile"]})]}),e.jsx($,{asChild:!0,size:"lg",className:"mt-8 w-full bg-accent text-accent-foreground hover:bg-accent/90 font-bold",children:e.jsx("a",{href:"#claim",children:"Claim the $300/yr rate"})})]})]})]})}),e.jsx("section",{className:"pb-20 md:pb-28 px-6",children:e.jsxs("div",{className:"max-w-3xl mx-auto",children:[e.jsx("h2",{className:"text-3xl md:text-4xl font-bold tracking-tight text-center mb-10",children:"Questions agents ask"}),e.jsx("div",{className:"space-y-3",children:UUs.map((m,f)=>e.jsxs("div",{className:"bg-card border rounded-2xl overflow-hidden",children:[e.jsxs("button",{onClick:()=>c(o===f?null:f),className:"w-full flex items-center justify-between gap-4 px-6 py-4 text-left font-semibold",children:[m.q,e.jsx("span",{className:`transition-transform ${o===f?"rotate-45":""} text-muted-foreground text-xl leading-none`,children:"+"})]}),o===f&&e.jsx("p",{className:"px-6 pb-5 text-sm text-muted-foreground leading-relaxed",children:m.a})]},f))})]})}),e.jsx("div",{className:"ld-divider pb-14","aria-hidden":!0,children:e.jsx("span",{children:"★★★"})}),e.jsxs("section",{className:"ld-dark relative overflow-hidden py-20 md:py-28 px-6",children:[e.jsx("div",{className:"ld-stars absolute inset-0 opacity-[0.08] pointer-events-none"}),e.jsx("div",{className:"ld-flagbar absolute bottom-0 inset-x-0"}),e.jsxs("div",{className:"relative max-w-3xl mx-auto text-center",children:[e.jsx("h2",{className:"ld-display text-3xl md:text-5xl text-white uppercase",children:"This is the lowest rate we've ever run."}),e.jsx("p",{className:"text-white/70 mt-5 text-lg",children:"When the timer hits zero, the $300/year rate is gone. Lock it in now and keep it for as long as you're a member."}),e.jsx("div",{className:"mt-8 flex justify-center",children:e.jsx(Hvt,{dark:!0})}),e.jsx($,{asChild:!0,size:"lg",className:"mt-10 bg-accent text-accent-foreground hover:bg-accent/90 font-bold text-lg px-10 py-6",children:e.jsxs("a",{href:"#claim",children:["Get LevelUp for $300/year ",e.jsx(ei,{className:"ml-2 h-5 w-5"})]})}),e.jsxs("p",{className:"text-white/40 text-xs mt-4 flex items-center justify-center gap-1.5",children:[e.jsx(pc,{className:"h-3 w-3"})," Secure Stripe checkout · Ends ",W7e]}),e.jsxs("p",{className:"text-white/50 text-sm mt-10",children:["© ",new Date().getFullYear()," LevelUp Consulting Group"]})]})]}),e.jsx(E$t,{pageKey:"individual-labor-day-2026",headline:"Not ready to join the LevelUp family yet?"})]})}const I$t=Date.UTC(2026,8,12,3,59,59),Y7e="Friday, September 11 at 11:59 PM ET",hQ=399,u3e=499,Wvt=(u3e-hQ)*12,HUs=[{key:"dashboard",label:"Agent Command Center",caption:"Every agent's day — smart queue, calendar and pipeline in one view.",src:Jae},{key:"crm",label:"CRM & Contact Hub",caption:"Contacts, tags, follow-ups and deal history for every agent.",src:r6e},{key:"pipeline",label:"Deal Pipeline",caption:"Every transaction with tasks, forms and commission tracking built in.",src:a6e},{key:"staging",label:"Staging Studio",caption:"AI photo staging — MLS-ready before/afters in minutes.",src:i6e},{key:"coaching",label:"Coaching",caption:"Live coaching sessions your agents book themselves.",src:o6e},{key:"marketing",label:"Marketing Studio",caption:"Templates, social posts, reels and print — all branded.",src:l6e}],GUs=[{name:"Tracy VanderWall",meta:"Local Guide · Broker/Owner",when:"7 months ago",text:"Best investment my brokerage has made! The value of this platform is AMAZING! The entire LEVELUP Team is wonderful!"},{name:"Bill Burns",meta:"Local Guide · Broker",when:"5 months ago",text:"Jeremy and his team are amazing! Level Up can next level your brokerage!"},{name:"Robert Larente",meta:"Real Estate Agent",when:"5 months ago",text:"I'm fortunate that my Broker started providing LevelUp membership a few years ago. Originally I used it for kvCore/Bold CRM training. But with the amazing amount of resources that Jeremy and his crew keep adding, I'm quickly canceling my subscriptions to other service providers."},{name:"Valerie Harp",meta:"Local Guide · Real Estate Agent",when:"4 months ago",text:"Level Up has been an absolute game changer for my real estate business. The platform is incredibly easy to use and by far one of the most user-friendly systems I've worked with. Everything is streamlined, intuitive, and designed with agents in mind."},{name:"Tom Lois",meta:"Real Estate Agent",when:"5 months ago",text:"Jeremy and his team at LevelUp continue to upgrade, update, and uplift agents with their meaningful content and insight. Whether you're a newbie or a seasoned agent, this program is for you! Try it — you'll REALLY like it!"},{name:"Michael Smith",meta:"Local Guide · Real Estate Agent",when:"7 months ago",text:"Great value in the material, ideas, etc. shared by the LevelUp team. They consistently provide implementable examples of ways to impact your real estate business. Not just theory, but real ideas/tasks that can be quickly implemented."},{name:"Pamela Nichols",meta:"Local Guide · Real Estate Agent",when:"4 months ago",text:"I'm loving this platform and all the excellent quick and easy information to use! It has been the easiest thing I've ever used to care for my database! I love the quick videos — quick and to the point!"},{name:"Anissa, REMAX Executives",meta:"Real Estate Agent",when:"6 months ago",text:"So far this has helped me tremendously! Keeps me more organized and motivated to stay on top of these leads that get lost in the daily mix."}],WUs="https://www.google.com/search?q=levelup+consulting+group#lrd=0x8842f50045c4bd33:0xc9b99b5330a91b3f,1,,,,",KUs=[{icon:jb,title:"Live Weekly Trainings",desc:"Every agent joins live weekly training sessions with Jeremy and the LevelUp team — plus the full on-demand Academy."},{icon:c7,title:"Full CRM & Contact Hub",desc:"Contacts, tags, smart follow-ups, lead ponds and team assignments — every agent's database finally organized."},{icon:wb,title:"Deal Pipeline",desc:"Transactions from offer to closing with tasks, forms and commission math built in."},{icon:Cx,title:"Staging Studio",desc:"AI virtual staging with MLS-ready before/after photos for every listing."},{icon:Yc,title:"Marketing & Social Studio",desc:"300+ branded templates, social posts, postcards and the weekly Reels engine."},{icon:dl,title:"Lead Sites",desc:"SEO-optimized websites that rank on Google and capture leads 24/7."},{icon:of,title:"Academy Training",desc:"On-demand video training on lead gen, marketing and tech."},{icon:m_,title:"Forms & E-Signature",desc:"Upload any PDF, map fields, send for signature — done from one place."},{icon:ua,title:"Weekly Reels & Video Tools",desc:"Personalized Instagram scripts every Monday, plus screen recording and virtual backgrounds."}],YUs=[{icon:ji,title:"Your Own Brokerage Hub",desc:"Brand profiles, announcements and resources pushed to every agent from one place."},{icon:m_,title:"Brokerage Form Library",desc:"Publish your official forms office-wide — agents use them read-only or copy to customize."},{icon:sc,title:"Recruiting Pipeline",desc:"Customizable recruiting stages to attract and track your next agents."},{icon:xm,title:"Office-Wide Communication",desc:"Broadcasts, brokerage content and resource libraries your agents actually use."}],ZUs=[{q:"What does 'unlimited agents' actually mean?",a:"Every agent in your brokerage gets a full LevelUp membership — coaching, CRM, deal pipeline, Staging Studio, Marketing Studio, lead sites, Academy, forms with e-signature, reviews, Weekly Reels and the ChatGPT app. No per-seat fees, no caps, no tiers to unlock."},{q:"Is the $399/mo rate really locked in?",a:"Yes. As long as your subscription stays active, you renew at $399/month — even when the standard brokerage rate goes back to $499/month. No surprises, no bump after year one."},{q:"What happens after I pay?",a:"You'll land on a setup screen where you name your brokerage, set your branding, and start inviting agents. Agents accept their invite and have full access within minutes."},{q:"What if we add or lose agents during the year?",a:"Nothing changes on your bill. The rate is flat $399/month for the whole brokerage whether you have 10 agents or 100. Add and remove agents freely from your brokerage dashboard."},{q:"Is there a contract or trial?",a:"No long-term contract and no trial on this one — you're charged $399 today and billed monthly. Manage or cancel anytime from your profile's Stripe customer portal."},{q:"Is this really the last brokerage offer this year?",a:"Yes. This is our final brokerage partnership promotion of 2026. When the clock hits zero on September 11, this rate is gone."}];function L$t(s){const[t,n]=j.useState(()=>Date.now());j.useEffect(()=>{const i=setInterval(()=>n(Date.now()),1e3);return()=>clearInterval(i)},[]);const r=Math.max(0,s-t),a=Math.floor(r/1e3);return{expired:r<=0,d:Math.floor(a/86400),h:Math.floor(a%86400/3600),m:Math.floor(a%3600/60),sec:a%60}}function Kvt({dark:s=!1}){const{d:t,h:n,m:r,sec:a,expired:i}=L$t(I$t);if(i)return null;const l=[{v:t,l:"Days"},{v:n,l:"Hours"},{v:r,l:"Min"},{v:a,l:"Sec"}];return e.jsx("div",{className:"flex items-center gap-2 sm:gap-3",children:l.map(o=>e.jsxs("div",{className:`${s?"ld-glass":"bg-card border"} rounded-xl px-3 py-2 sm:px-4 sm:py-3 text-center min-w-[60px] sm:min-w-[72px]`,children:[e.jsx("div",{className:`text-2xl sm:text-3xl font-bold tabular-nums ${s?"text-white":"text-foreground"}`,children:String(o.v).padStart(2,"0")}),e.jsx("div",{className:`text-[10px] uppercase tracking-widest ${s?"text-white/60":"text-muted-foreground"}`,children:o.l})]},o.l))})}function Yvt(){return e.jsx("div",{className:"flex gap-0.5","aria-label":"5 out of 5 stars",children:Array.from({length:5}).map((s,t)=>e.jsx(Ja,{className:"h-4 w-4 fill-accent text-accent"},t))})}function XUs({slot:s,dark:t=!0}){return e.jsxs("figure",{className:`ld-shot overflow-hidden border ${t?"ld-glass":"bg-card border-border"}`,children:[e.jsxs("div",{className:`flex items-center gap-1.5 px-3 py-2 border-b ${t?"border-white/10":"border-border"}`,children:[e.jsx("span",{className:"h-2.5 w-2.5 rounded-full bg-red-400/80"}),e.jsx("span",{className:"h-2.5 w-2.5 rounded-full bg-amber-400/80"}),e.jsx("span",{className:"h-2.5 w-2.5 rounded-full bg-green-400/80"}),e.jsx("span",{className:`ml-3 text-[11px] rounded px-2 py-0.5 ${t?"bg-white/10 text-white/70":"bg-muted text-muted-foreground"}`,children:"dashboard.relevelup.com"})]}),s.src?e.jsx("img",{src:s.src,alt:`LevelUp ${s.label} screenshot`,className:"w-full h-auto block",loading:"lazy"}):e.jsxs("div",{className:`w-full aspect-[16/10] flex flex-col items-center justify-center gap-3 ${t?"bg-white/5":"bg-muted"}`,children:[e.jsx(Nn,{className:`h-8 w-8 ${t?"text-white/40":"text-muted-foreground/50"}`}),e.jsx("p",{className:`text-sm font-medium ${t?"text-white/60":"text-muted-foreground"}`,children:s.label})]}),e.jsxs("figcaption",{className:`px-4 py-3 text-sm ${t?"text-white/80":"text-muted-foreground"}`,children:[e.jsx("span",{className:`font-semibold ${t?"text-white":"text-foreground"}`,children:s.label})," — ",s.caption]})]})}function QUs(){const{expired:s}=L$t(I$t),[t,n]=j.useState(""),[r,a]=j.useState(""),[i,l]=j.useState(!1),[o,c]=j.useState(0),d=j.useMemo(()=>[Hst,Gst,Wst,Kst,Yst],[]),u=async()=>{if(!r.trim()||!r.includes("@")){re.error("Enter your email to claim the offer.");return}l(!0);try{const{data:h,error:m}=await q.functions.invoke("create-checkout",{body:{tier:"brokerage_labor_day",email:r.trim(),name:t.trim()||void 0,skipTrial:!0}});if(m){const f=m instanceof Tae?await m.context.text():m.message;throw new Error(f||"Checkout failed to start")}if(h!=null&&h.url){window.location.href=h.url;return}throw new Error("No checkout URL returned")}catch(h){console.error("Brokerage Labor Day checkout error:",h),re.error(h.message||"Could not start checkout. Please try again."),l(!1)}};return e.jsxs("div",{className:"laborday-theme min-h-screen bg-background",children:[e.jsxs(Ml,{children:[e.jsx("title",{children:"Labor Day Brokerage Special — LevelUp for $399/mo, Unlimited Agents | LevelUp Consulting Group"}),e.jsx("meta",{name:"description",content:`Last brokerage offer of 2026: give every agent in your brokerage a full LevelUp membership — live weekly trainings, CRM, marketing and more — for $399/mo instead of $499/mo. Rate locked. Ends ${Y7e}.`}),e.jsx("meta",{property:"og:title",content:"Labor Day Brokerage Special — $399/mo for Your Entire Brokerage"}),e.jsx("meta",{property:"og:description",content:"Unlimited agents, full memberships, live weekly trainings. $399/mo instead of $499/mo, locked in. Last brokerage offer of 2026 — ends Sept 11 at midnight."}),e.jsx("meta",{property:"og:type",content:"website"}),e.jsx("meta",{name:"twitter:card",content:"summary_large_image"}),e.jsx("link",{rel:"preconnect",href:"https://fonts.googleapis.com"}),e.jsx("link",{rel:"preconnect",href:"https://fonts.gstatic.com",crossOrigin:"anonymous"}),e.jsx("link",{href:"https://fonts.googleapis.com/css2?family=Archivo+Black&display=swap",rel:"stylesheet"}),e.jsx("script",{type:"application/ld+json",children:JSON.stringify({"@context":"https://schema.org","@type":"Offer",name:"LevelUp Brokerage Partner — Labor Day Offer",price:"399.00",priceCurrency:"USD",availabilityEnds:"2026-09-11T23:59:59-04:00",seller:{"@type":"Organization",name:"LevelUp Consulting Group"}})})]}),!s&&e.jsxs("div",{className:"fixed bottom-0 inset-x-0 z-50 md:hidden bg-foreground/95 backdrop-blur border-t border-white/10 px-4 py-3 flex items-center justify-between gap-3",style:{backgroundColor:"hsl(var(--ld-navy-deep) / 0.96)"},children:[e.jsxs("div",{className:"text-white",children:[e.jsx("div",{className:"text-xs text-white/60 uppercase tracking-wider",children:"Brokerage Labor Day"}),e.jsxs("div",{className:"font-bold",children:["$",hQ,e.jsx("span",{className:"text-sm font-normal text-white/70",children:"/mo"})," ",e.jsxs("span",{className:"text-xs line-through text-white/50 ml-1",children:["$",u3e]})]})]}),e.jsx($,{asChild:!0,className:"bg-accent text-accent-foreground hover:bg-accent/90 font-semibold",children:e.jsx("a",{href:"#claim",children:"Claim Offer"})})]}),e.jsxs("header",{className:"ld-dark relative overflow-hidden",children:[e.jsx("div",{className:"ld-flagbar absolute top-0 inset-x-0 z-10"}),e.jsx("div",{className:"ld-stars absolute inset-0 opacity-[0.10] pointer-events-none"}),e.jsxs("div",{className:"relative max-w-6xl mx-auto px-6 pt-12 pb-20 md:pb-28",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("img",{src:TG,alt:"LevelUp Consulting Group",className:"h-9 md:h-11 w-auto"}),e.jsxs("div",{className:"hidden sm:flex items-center gap-2 text-white/70 text-sm",children:[e.jsx("div",{className:"flex -space-x-2",children:d.map((h,m)=>e.jsx("img",{src:h,alt:"",className:"h-7 w-7 rounded-full border-2 border-white/20 object-cover"},m))}),e.jsx("span",{children:"3,000+ agents"})]})]}),e.jsxs("div",{className:"mt-16 md:mt-24 text-center max-w-4xl mx-auto",children:[e.jsxs("div",{className:"mb-10",children:[e.jsx("span",{className:"ld-stamp text-xs sm:text-sm",children:"★ Labor Day Brokerage Special ★"}),e.jsxs("p",{className:"mt-4 text-white/60 text-xs sm:text-sm uppercase tracking-[0.2em] font-semibold",children:["Last brokerage offer of 2026 · Ends ",Y7e]})]}),e.jsxs("h1",{className:"ld-display text-4xl sm:text-6xl lg:text-7xl text-white leading-[1.05] uppercase",children:["Every agent in your brokerage. Full membership.",e.jsx("span",{className:"block mt-4 ld-gold-text",children:"$399/mo — not $499."})]}),e.jsx("div",{className:"mt-6 flex items-center justify-center gap-2 text-accent","aria-hidden":!0,children:Array.from({length:5}).map((h,m)=>e.jsx(Ja,{className:"h-4 w-4 fill-accent text-accent"},m))}),e.jsxs("p",{className:"mt-6 text-lg md:text-xl text-white/75 max-w-2xl mx-auto leading-relaxed",children:["Live weekly trainings, a full agent growth platform, CRM, marketing studio and more —"," ",e.jsx("span",{className:"text-white font-semibold",children:"for every agent in your brokerage"}),". Normally"," ",e.jsx("span",{className:"text-white font-semibold",children:"$499/month"}),". Partner this week for"," ",e.jsx("span",{className:"text-white font-semibold",children:"$399/month"}),", locked in for as long as you're a partner."]}),e.jsxs("div",{className:"mt-10 flex flex-col items-center gap-4",children:[e.jsx(Kvt,{dark:!0}),e.jsx("p",{className:"text-xs uppercase tracking-widest text-white/50",children:"Offer disappears when the clock hits zero"})]}),e.jsxs("form",{id:"claim",onSubmit:h=>{h.preventDefault(),u()},className:"mt-8 mx-auto max-w-xl ld-glass rounded-2xl p-4 sm:p-5",children:[s?e.jsxs("div",{className:"text-center py-2",children:[e.jsx("p",{className:"text-white font-semibold text-lg",children:"This Labor Day brokerage offer has ended."}),e.jsx("p",{className:"text-white/60 text-sm mt-1 mb-4",children:"You can still partner with LevelUp at the standard brokerage rate."}),e.jsx($,{asChild:!0,size:"lg",className:"bg-accent text-accent-foreground hover:bg-accent/90 font-semibold w-full sm:w-auto",children:e.jsxs("a",{href:"/pricing",children:["See Brokerage Plans ",e.jsx(ei,{className:"ml-2 h-4 w-4"})]})})]}):e.jsxs("div",{className:"flex flex-col sm:flex-row gap-3",children:[e.jsx(pe,{value:t,onChange:h=>n(h.target.value),placeholder:"Your name",className:"bg-white/10 border-white/20 text-white placeholder:text-white/50 h-12",autoComplete:"name"}),e.jsx(pe,{value:r,onChange:h=>a(h.target.value),type:"email",placeholder:"Your email",className:"bg-white/10 border-white/20 text-white placeholder:text-white/50 h-12",autoComplete:"email",required:!0}),e.jsx($,{type:"submit",disabled:i,size:"lg",className:"bg-accent text-accent-foreground hover:bg-accent/90 font-bold h-12 px-6 whitespace-nowrap",children:i?e.jsx(kt,{className:"h-5 w-5 animate-spin"}):e.jsxs(e.Fragment,{children:["Partner at $399/mo ",e.jsx(ei,{className:"ml-2 h-5 w-5"})]})})]}),!s&&e.jsxs("p",{className:"text-white/50 text-xs mt-3 flex items-center justify-center gap-1.5",children:[e.jsx(pc,{className:"h-3 w-3"})," Secure Stripe checkout · Set up your brokerage right after payment"]})]}),e.jsxs("p",{className:"mt-6 text-white/70 text-sm",children:["Trusted by ",e.jsx("span",{className:"font-bold text-white",children:"3,000+ agents"})," and the brokerages they work for"]})]})]})]}),e.jsx("section",{className:"py-20 md:py-28 px-6",children:e.jsxs("div",{className:"max-w-6xl mx-auto",children:[e.jsxs("div",{className:"text-center mb-14",children:[e.jsx("span",{className:"text-sm font-semibold tracking-[0.15em] uppercase text-primary",children:"What your agents get"}),e.jsx("h2",{className:"text-3xl md:text-5xl font-bold mt-4 tracking-tight",children:"A full membership for every agent. No per-seat fees."}),e.jsx("p",{className:"text-muted-foreground mt-4 max-w-2xl mx-auto",children:"Individually, this membership costs $39/month per agent. As a brokerage partner, every agent gets it — all included in one flat rate."})]}),e.jsx("div",{className:"grid sm:grid-cols-2 lg:grid-cols-3 gap-5",children:KUs.map(h=>e.jsxs("div",{className:"bg-card border rounded-2xl p-6 flex flex-col gap-3 hover:shadow-lg transition-shadow",children:[e.jsx("div",{className:"h-11 w-11 rounded-xl bg-primary/10 flex items-center justify-center",children:e.jsx(h.icon,{className:"h-5 w-5 text-primary"})}),e.jsx("h3",{className:"font-bold text-lg",children:h.title}),e.jsx("p",{className:"text-sm text-muted-foreground leading-relaxed",children:h.desc})]},h.title))})]})}),e.jsx("section",{className:"ld-dark py-20 md:py-28 px-6",children:e.jsxs("div",{className:"max-w-6xl mx-auto",children:[e.jsxs("div",{className:"text-center mb-14",children:[e.jsx("span",{className:"text-sm font-semibold tracking-[0.15em] uppercase text-accent",children:"For the brokerage"}),e.jsx("h2",{className:"text-3xl md:text-5xl font-bold text-white mt-4 tracking-tight",children:"Tools that make your office run itself"}),e.jsx("p",{className:"text-white/60 mt-4 max-w-2xl mx-auto",children:"You get more than agent seats — you get brokerage-level controls."})]}),e.jsx("div",{className:"grid sm:grid-cols-2 lg:grid-cols-4 gap-5",children:YUs.map(h=>e.jsxs("div",{className:"ld-glass rounded-2xl p-6 flex flex-col gap-3",children:[e.jsx("div",{className:"h-11 w-11 rounded-xl bg-white/10 flex items-center justify-center",children:e.jsx(h.icon,{className:"h-5 w-5 text-accent"})}),e.jsx("h3",{className:"font-bold text-lg text-white",children:h.title}),e.jsx("p",{className:"text-sm text-white/70 leading-relaxed",children:h.desc})]},h.title))})]})}),e.jsx("section",{className:"py-20 md:py-28 px-6",children:e.jsxs("div",{className:"max-w-6xl mx-auto",children:[e.jsxs("div",{className:"text-center mb-14",children:[e.jsx("span",{className:"text-sm font-semibold tracking-[0.15em] uppercase text-primary",children:"See it in action"}),e.jsx("h2",{className:"text-3xl md:text-5xl font-bold mt-4 tracking-tight",children:"A real platform, not another training course"}),e.jsx("p",{className:"text-muted-foreground mt-4 max-w-2xl mx-auto",children:"This is what your agents open every morning."})]}),e.jsx("div",{className:"grid md:grid-cols-2 gap-8 md:gap-10",children:HUs.map(h=>e.jsx(XUs,{slot:h,dark:!1},h.key))})]})}),e.jsx("div",{className:"ld-divider pb-4","aria-hidden":!0,children:e.jsx("span",{children:"★★★"})}),e.jsx("section",{className:"py-20 md:py-28 px-6",children:e.jsxs("div",{className:"max-w-6xl mx-auto",children:[e.jsxs("div",{className:"text-center mb-12",children:[e.jsxs("div",{className:"inline-flex items-center gap-3 bg-card border rounded-full px-5 py-2.5 mb-6",children:[e.jsxs("svg",{viewBox:"0 0 24 24",className:"h-5 w-5","aria-hidden":!0,children:[e.jsx("path",{fill:"#4285F4",d:"M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92a5.06 5.06 0 0 1-2.2 3.32v2.77h3.57c2.08-1.92 3.27-4.74 3.27-8.1z"}),e.jsx("path",{fill:"#34A853",d:"M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.98.66-2.23 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84C3.99 20.53 7.7 23 12 23z"}),e.jsx("path",{fill:"#FBBC05",d:"M5.84 14.1a7.16 7.16 0 0 1 0-4.2V7.06H2.18a11 11 0 0 0 0 9.88l3.66-2.84z"}),e.jsx("path",{fill:"#EA4335",d:"M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1 7.7 1 3.99 3.47 2.18 7.06l3.66 2.84c.87-2.6 3.3-4.52 6.16-4.52z"})]}),e.jsx("span",{className:"font-semibold",children:"5.0"}),e.jsx(Yvt,{}),e.jsx("span",{className:"text-muted-foreground text-sm",children:"on Google"})]}),e.jsx("h2",{className:"text-3xl md:text-5xl font-bold tracking-tight",children:"Brokers and agents agree"}),e.jsx("p",{className:"text-muted-foreground mt-4 max-w-2xl mx-auto",children:"Real reviews from our Google Business profile — including the brokers who made the call."})]}),e.jsx("div",{className:"grid sm:grid-cols-2 lg:grid-cols-4 gap-5",children:GUs.map(h=>e.jsxs("blockquote",{className:"bg-card border rounded-2xl p-5 flex flex-col gap-3",children:[e.jsx(Yvt,{}),e.jsxs("p",{className:"text-sm text-foreground/90 leading-relaxed flex-1",children:['"',h.text,'"']}),e.jsxs("footer",{children:[e.jsx("div",{className:"font-semibold text-sm",children:h.name}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[h.meta," · ",h.when]})]})]},h.name))}),e.jsx("div",{className:"text-center mt-8",children:e.jsx("a",{href:WUs,target:"_blank",rel:"noreferrer",className:"text-sm font-medium text-primary hover:underline",children:"Read all reviews on Google →"})})]})}),e.jsx("section",{className:"pb-20 md:pb-28 px-6",children:e.jsxs("div",{className:"max-w-4xl mx-auto",children:[e.jsx("div",{className:"text-center mb-12",children:e.jsx("h2",{className:"text-3xl md:text-5xl font-bold tracking-tight",children:"Live in three steps"})}),e.jsx("div",{className:"grid md:grid-cols-3 gap-6",children:[{n:"1",title:"Partner & pay",desc:"Claim the $399/mo rate with secure Stripe checkout. Charged today, billed monthly."},{n:"2",title:"Set up your brokerage",desc:"Name your brokerage, add your branding and configure your office — minutes, not days."},{n:"3",title:"Invite your agents",desc:"Send invites and every agent gets their full membership. They can start this week."}].map(h=>e.jsxs("div",{className:"bg-card border rounded-2xl p-6 text-center",children:[e.jsx("div",{className:"mx-auto h-12 w-12 rounded-full bg-primary/10 flex items-center justify-center text-primary font-bold text-xl",children:h.n}),e.jsx("h3",{className:"font-bold text-lg mt-4",children:h.title}),e.jsx("p",{className:"text-sm text-muted-foreground mt-2 leading-relaxed",children:h.desc})]},h.n))})]})}),e.jsx("section",{className:"pb-20 md:pb-28 px-6",children:e.jsxs("div",{className:"max-w-4xl mx-auto",children:[e.jsxs("div",{className:"text-center mb-12",children:[e.jsx("h2",{className:"text-3xl md:text-5xl font-bold tracking-tight",children:"Do the math"}),e.jsxs("p",{className:"text-muted-foreground mt-4 max-w-2xl mx-auto",children:["25 agents × $39/mo memberships = $975/mo of value. You pay a flat $",hQ,"."]})]}),e.jsxs("div",{className:"grid md:grid-cols-2 gap-6",children:[e.jsxs("div",{className:"bg-card border rounded-3xl p-8",children:[e.jsx("h3",{className:"font-bold text-xl text-muted-foreground",children:"Standard Brokerage Plan"}),e.jsxs("div",{className:"mt-4 flex items-baseline gap-2",children:[e.jsxs("span",{className:"text-5xl font-bold text-muted-foreground",children:["$",u3e]}),e.jsx("span",{className:"text-muted-foreground",children:"/month"})]}),e.jsxs("ul",{className:"mt-6 space-y-3 text-sm text-muted-foreground",children:[e.jsxs("li",{className:"flex gap-2",children:[e.jsx(gr,{className:"h-4 w-4 mt-0.5 shrink-0"})," $",(u3e*12).toLocaleString()," per year"]}),e.jsxs("li",{className:"flex gap-2",children:[e.jsx(gr,{className:"h-4 w-4 mt-0.5 shrink-0"})," Standard rate — no lock-in"]}),e.jsxs("li",{className:"flex gap-2",children:[e.jsx(la,{className:"h-4 w-4 mt-0.5 shrink-0 text-primary"})," Unlimited agents, full memberships"]})]})]}),e.jsxs("div",{className:"relative rounded-3xl p-8 text-white overflow-hidden",style:{background:"linear-gradient(150deg, hsl(var(--ld-navy)), hsl(var(--ld-navy-deep)))"},children:[e.jsxs("div",{className:"absolute top-4 right-4 bg-accent text-accent-foreground text-xs font-bold uppercase tracking-wider rounded-full px-3 py-1",children:["Save $",Wvt.toLocaleString(),"/yr"]}),e.jsx("h3",{className:"font-bold text-xl",children:"Labor Day Partner Rate"}),e.jsxs("div",{className:"mt-4 flex items-baseline gap-2",children:[e.jsxs("span",{className:"text-5xl font-bold",children:["$",hQ]}),e.jsx("span",{className:"text-white/70",children:"/month"})]}),e.jsx("p",{className:"text-accent font-semibold text-sm mt-1",children:"25 agents = under $16/agent/mo"}),e.jsxs("ul",{className:"mt-6 space-y-3 text-sm text-white/85",children:[e.jsxs("li",{className:"flex gap-2",children:[e.jsx(la,{className:"h-4 w-4 mt-0.5 shrink-0 text-accent"})," $",(hQ*12).toLocaleString()," per year — save $",Wvt.toLocaleString()," vs standard"]}),e.jsxs("li",{className:"flex gap-2",children:[e.jsx(Uq,{className:"h-4 w-4 mt-0.5 shrink-0 text-accent"})," Rate locked for as long as you're a partner"]}),e.jsxs("li",{className:"flex gap-2",children:[e.jsx(la,{className:"h-4 w-4 mt-0.5 shrink-0 text-accent"})," Unlimited agents — every one gets a full membership"]}),e.jsxs("li",{className:"flex gap-2",children:[e.jsx(Mf,{className:"h-4 w-4 mt-0.5 shrink-0 text-accent"})," Manage or cancel anytime from your profile"]})]}),e.jsx($,{asChild:!0,size:"lg",className:"mt-8 w-full bg-accent text-accent-foreground hover:bg-accent/90 font-bold",children:e.jsx("a",{href:"#claim",children:"Partner at $399/mo"})})]})]})]})}),e.jsx("section",{className:"pb-20 md:pb-28 px-6",children:e.jsxs("div",{className:"max-w-3xl mx-auto",children:[e.jsx("h2",{className:"text-3xl md:text-4xl font-bold tracking-tight text-center mb-10",children:"Questions brokers ask"}),e.jsx("div",{className:"space-y-3",children:ZUs.map((h,m)=>e.jsxs("div",{className:"bg-card border rounded-2xl overflow-hidden",children:[e.jsxs("button",{onClick:()=>c(o===m?null:m),className:"w-full flex items-center justify-between gap-4 px-6 py-4 text-left font-semibold",children:[h.q,e.jsx("span",{className:`transition-transform ${o===m?"rotate-45":""} text-muted-foreground text-xl leading-none`,children:"+"})]}),o===m&&e.jsx("p",{className:"px-6 pb-5 text-sm text-muted-foreground leading-relaxed",children:h.a})]},m))})]})}),e.jsx("div",{className:"ld-divider pb-14","aria-hidden":!0,children:e.jsx("span",{children:"★★★"})}),e.jsxs("section",{className:"ld-dark relative overflow-hidden py-20 md:py-28 px-6",children:[e.jsx("div",{className:"ld-stars absolute inset-0 opacity-[0.08] pointer-events-none"}),e.jsx("div",{className:"ld-flagbar absolute bottom-0 inset-x-0"}),e.jsxs("div",{className:"relative max-w-3xl mx-auto text-center",children:[e.jsx("h2",{className:"ld-display text-3xl md:text-5xl text-white uppercase",children:"The last brokerage offer of 2026."}),e.jsx("p",{className:"text-white/70 mt-5 text-lg",children:"When the timer hits zero, the $399/mo partner rate is gone. Lock it in now and give every agent in your brokerage a full membership."}),e.jsx("div",{className:"mt-8 flex justify-center",children:e.jsx(Kvt,{dark:!0})}),e.jsx($,{asChild:!0,size:"lg",className:"mt-10 bg-accent text-accent-foreground hover:bg-accent/90 font-bold text-lg px-10 py-6",children:e.jsxs("a",{href:"#claim",children:["Partner with LevelUp — $399/mo ",e.jsx(ei,{className:"ml-2 h-5 w-5"})]})}),e.jsxs("p",{className:"text-white/40 text-xs mt-4 flex items-center justify-center gap-1.5",children:[e.jsx(pc,{className:"h-3 w-3"})," Secure Stripe checkout · Ends ",Y7e]}),e.jsxs("p",{className:"text-white/50 text-sm mt-10",children:["© ",new Date().getFullYear()," LevelUp Consulting Group"]})]})]}),e.jsx(E$t,{pageKey:"brokerage-labor-day-2026",headline:"Not ready to partner with LevelUp yet?"})]})}const JUs=["Unlimited access to all marketing templates","Complete Academy training library","AI-powered tools and resources","Lead site & Listing Exchange access","Deal pipeline & scorecard tracking","Community forums and support"],eqs=["Everything in Individual, plus:","Unlimited agent seats","Brokerage admin dashboard","Team performance analytics","Agent onboarding tools","Priority support"],tqs=()=>{const{user:s,loading:t}=vs(),n=Qn(),[r]=gc(),a=r.get("plan"),i=a==="individual"?"individual_agent":a==="brokerage"?"brokerage_over_25":a,[l,o]=j.useState(!1),[c,d]=j.useState(null),[u,h]=j.useState(""),m=x=>{const y=`/upgrade?plan=${x}`;n(`/auth?next=${encodeURIComponent(y)}`)},f=async x=>{var y;if(!(s!=null&&s.email)){m(x);return}o(!0),d(x);try{const{data:v,error:b}=await q.functions.invoke("create-checkout",{body:{tier:x,email:s.email,name:((y=s.user_metadata)==null?void 0:y.full_name)||s.email,userId:s.id,couponCode:u.trim()||void 0,skipTrial:!0}});if(b)throw b;if(v!=null&&v.url)window.location.href=v.url;else throw new Error("No checkout URL returned")}catch(v){console.error("Checkout error:",v),re.error(v.message||"Failed to start checkout. Please try again."),o(!1),d(null)}},g=(x,y,v,b,w,S,C)=>e.jsxs(Ne,{className:`relative border-2 transition-colors ${C?"border-primary shadow-lg":"border-amber-500/30"} ${i===x?"ring-2 ring-primary ring-offset-2":""}`,children:[i===x&&e.jsx(Be,{className:"absolute -top-3 left-1/2 -translate-x-1/2 bg-primary text-primary-foreground",children:"Recommended for you"}),e.jsxs(Ie,{className:"p-6 text-center space-y-4",children:[e.jsx("div",{className:`mx-auto h-12 w-12 rounded-full flex items-center justify-center ${C?"bg-primary/10":"bg-amber-500/10"}`,children:S}),e.jsxs("div",{children:[e.jsx("h3",{className:"font-semibold text-xl",children:y}),e.jsxs("p",{className:`text-3xl font-bold mt-1 ${C?"text-primary":"text-amber-600"}`,children:[v,e.jsx("span",{className:"text-sm font-normal text-muted-foreground",children:"/mo"})]}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:b})]}),e.jsx("ul",{className:"text-sm space-y-1.5 text-left text-muted-foreground",children:w.map(E=>e.jsxs("li",{className:"flex items-start gap-2",children:[e.jsx(la,{className:`h-4 w-4 mt-0.5 shrink-0 ${C?"text-primary":"text-amber-600"}`}),e.jsx("span",{children:E})]},E))}),e.jsx($,{className:"w-full",variant:C?"default":"outline",disabled:l||t,onClick:()=>f(x),children:l&&c===x?e.jsxs(e.Fragment,{children:[e.jsx(kt,{className:"h-4 w-4 mr-2 animate-spin"}),"Opening secure checkout…"]}):s?e.jsxs(e.Fragment,{children:[e.jsx(Nn,{className:"h-4 w-4 mr-2"}),"Upgrade to ",y]}):e.jsxs(e.Fragment,{children:[e.jsx(ZI,{className:"h-4 w-4 mr-2"}),"Sign in & upgrade to ",y]})})]})]});return e.jsx("div",{className:"min-h-screen bg-gradient-to-b from-[#f4f7fa] to-white",children:e.jsxs("div",{className:"container max-w-5xl py-10 px-4",children:[e.jsxs("div",{className:"text-center mb-10",children:[e.jsx("img",{src:c6e,alt:"LevelUp",className:"h-10 mx-auto mb-8"}),e.jsx(Be,{variant:"outline",className:"mb-4 border-primary/40 text-primary",children:"Upgrade your membership"}),e.jsx("h1",{className:"text-3xl sm:text-4xl font-bold mb-3 text-[#2a4c64]",children:"Keep your momentum going"}),e.jsx("p",{className:"text-muted-foreground text-lg max-w-2xl mx-auto",children:s?"Choose your plan below — payment connects to your existing account and everything you set up stays right where you left it.":"Whether you're on a free trial or it just ended, sign in with your existing LevelUp account, choose your plan, and your payment connects right to it — nothing gets lost or duplicated."})]}),e.jsxs("div",{className:"max-w-md mx-auto mb-8",children:[e.jsx(ee,{htmlFor:"upgrade-coupon",className:"text-sm font-medium",children:"Have a discount code?"}),e.jsx(pe,{id:"upgrade-coupon",placeholder:"Enter code (optional)",value:u,onChange:x=>h(x.target.value),className:"mt-1.5"})]}),e.jsxs("div",{className:"grid md:grid-cols-2 gap-6 max-w-4xl mx-auto",children:[g("individual_agent","Individual Agent","$39","Perfect for solo agents ready to level up",JUs,e.jsx(Zn,{className:"h-6 w-6 text-primary"}),!0),g("brokerage_over_25","Brokerage","$499","For teams and brokerages",eqs,e.jsx(ji,{className:"h-6 w-6 text-amber-600"}),!1)]}),e.jsxs("div",{className:"mt-10 bg-white/70 border rounded-xl p-5 max-w-2xl mx-auto space-y-3",children:[e.jsx("p",{className:"text-sm font-medium text-center",children:"Questions before you upgrade? We're happy to help:"}),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 text-sm",children:[e.jsx(Da,{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 text-sm",children:[e.jsx(mn,{className:"h-4 w-4"}),e.jsx("span",{children:"support@relevelup.com"})]})]})]}),e.jsx("p",{className:"text-center text-xs text-muted-foreground mt-8",children:"Secure checkout powered by Stripe. Your existing account, listings, and settings are preserved."})]})})},sqs=H2({viewerName:vl().min(1,"Name is required").max(100,"Name must be less than 100 characters"),viewerEmail:vl().email("Please enter a valid email").max(255,"Email must be less than 255 characters"),viewerPhone:vl().max(20,"Phone must be less than 20 characters").optional(),message:vl().min(1,"Message is required").max(1e3,"Message must be less than 1000 characters")});function nqs({shareToken:s,agentName:t,hasContact:n}){const[r,a]=j.useState(!1),[i,l]=j.useState(!1),[o,c]=j.useState(null),d=NLe({resolver:kLe(sqs),defaultValues:{viewerName:"",viewerEmail:"",viewerPhone:"",message:""}}),u=async h=>{a(!0),c(null);try{const{data:m,error:f}=await q.functions.invoke("video-reply-notify",{body:{shareToken:s,viewerName:h.viewerName,viewerEmail:h.viewerEmail,viewerPhone:h.viewerPhone||void 0,message:h.message}});if(f)throw new Error(f.message);if(!(m!=null&&m.success))throw new Error((m==null?void 0:m.error)||"Failed to send reply");l(!0)}catch(m){console.error("Failed to submit reply:",m),c(m.message||"Something went wrong. Please try again.")}finally{a(!1)}};return i?e.jsx(Ne,{className:"border-2 border-primary/20 bg-gradient-to-br from-primary/5 to-primary/10",children:e.jsxs(Ie,{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(qr,{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(Ne,{children:[e.jsxs(Ct,{className:"pb-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx(Th,{className:"h-5 w-5 text-primary"}),e.jsx(At,{className:"text-lg",children:"Reply to this video"})]}),e.jsx(Gn,{children:n?`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(Ie,{children:e.jsx(ELe,{...d,children:e.jsxs("form",{onSubmit:d.handleSubmit(u),className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsx(jg,{control:d.control,name:"viewerName",render:({field:h})=>e.jsxs(Up,{children:[e.jsx(qp,{children:"Your Name *"}),e.jsx(Vp,{children:e.jsx(pe,{placeholder:"John Smith",...h})}),e.jsx(y_,{})]})}),e.jsx(jg,{control:d.control,name:"viewerEmail",render:({field:h})=>e.jsxs(Up,{children:[e.jsx(qp,{children:"Email *"}),e.jsx(Vp,{children:e.jsx(pe,{type:"email",placeholder:"john@example.com",...h})}),e.jsx(y_,{})]})})]}),!n&&e.jsx(jg,{control:d.control,name:"viewerPhone",render:({field:h})=>e.jsxs(Up,{children:[e.jsx(qp,{children:"Phone (optional)"}),e.jsx(Vp,{children:e.jsx(pe,{type:"tel",placeholder:"(555) 123-4567",...h})}),e.jsx(y_,{})]})}),e.jsx(jg,{control:d.control,name:"message",render:({field:h})=>e.jsxs(Up,{children:[e.jsx(qp,{children:"Message *"}),e.jsx(Vp,{children:e.jsx(Rs,{placeholder:n?"Thanks for the video! I had a question about...":"I'm interested in learning more about...",className:"min-h-[100px] resize-none",...h})}),e.jsx(y_,{})]})}),o&&e.jsx("p",{className:"text-sm text-destructive",children:o}),e.jsx($,{type:"submit",className:"w-full gap-2",disabled:r,children:r?e.jsxs(e.Fragment,{children:[e.jsx(kt,{className:"h-4 w-4 animate-spin"}),"Sending..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Yr,{className:"h-4 w-4"}),"Send Message"]})})]})})})]})}const rqs=()=>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(Ja,{className:"absolute top-[5%] left-[8%] w-6 h-6 text-blue-600/30 fill-blue-600/20"}),e.jsx(Ja,{className:"absolute top-[15%] left-[20%] w-4 h-4 text-blue-600/25 fill-blue-600/15"}),e.jsx(Ja,{className:"absolute top-[8%] left-[28%] w-5 h-5 text-blue-600/30 fill-blue-600/20"}),e.jsx(Ja,{className:"absolute top-[25%] left-[12%] w-4 h-4 text-blue-600/20 fill-blue-600/10"}),e.jsx(Ja,{className:"absolute top-[20%] right-[15%] w-5 h-5 text-red-500/25 fill-red-500/15 animate-pulse"}),e.jsx(TE,{className:"absolute bottom-[20%] right-[10%] w-12 h-12 text-blue-600/15 rotate-12"})]}),aqs=()=>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(Nn,{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(Ja,{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(Nn,{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(Ja,{className:"absolute bottom-[25%] left-[10%] w-6 h-6 text-blue-500/25 fill-blue-500/15 animate-pulse"}),e.jsx(Ja,{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(TE,{className:"absolute top-[8%] left-[5%] w-10 h-10 text-red-500/20 rotate-12"})]}),iqs=()=>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(HS,{className:"w-20 h-20 text-pink-400 rotate-12"})}),e.jsx("div",{className:"absolute top-[2%] right-[8%] opacity-15",children:e.jsx(HS,{className:"w-16 h-16 text-rose-400 -rotate-12"})}),e.jsx("div",{className:"absolute bottom-[15%] left-[8%] opacity-15",children:e.jsx(HS,{className:"w-14 h-14 text-purple-400 rotate-45"})}),e.jsx("div",{className:"absolute bottom-[20%] right-[5%] opacity-20",children:e.jsx(HS,{className:"w-16 h-16 text-pink-300 -rotate-6"})}),e.jsx(Jo,{className:"absolute top-[15%] left-[30%] w-5 h-5 text-rose-300/40 fill-rose-300/20 animate-pulse"}),e.jsx(Jo,{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(Jo,{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"})]}),oqs=()=>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(Rm,{className:"absolute top-[8%] left-[12%] w-12 h-12 text-blue-600/15"}),e.jsx(Ja,{className:"absolute top-[15%] left-[22%] w-5 h-5 text-amber-500/25 fill-amber-500/15"}),e.jsx(Rm,{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(Ja,{className:"absolute bottom-[25%] left-[15%] w-6 h-6 text-blue-500/20 fill-blue-500/10 animate-pulse"}),e.jsx(Ja,{className:"absolute top-[20%] right-[22%] w-5 h-5 text-indigo-400/20 fill-indigo-400/10 animate-pulse",style:{animationDelay:"0.5s"}})]}),lqs=()=>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(HS,{className:"absolute top-[20%] left-[32%] w-7 h-7 text-purple-400/30"}),e.jsx(HS,{className:"absolute top-[12%] right-[28%] w-6 h-6 text-pink-400/30"}),e.jsx(Lq,{className:"absolute top-[18%] left-[52%] w-5 h-5 text-sky-400/35"})]}),cqs=()=>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(Vz,{className:"absolute top-[5%] left-[10%] w-16 h-16 text-orange-400/25"}),e.jsx(Vz,{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(Nn,{className:"absolute top-[8%] left-[55%] w-6 h-6 text-purple-400/35 animate-pulse"}),e.jsx(Nn,{className:"absolute bottom-[28%] right-[25%] w-5 h-5 text-orange-400/30 animate-pulse",style:{animationDelay:"0.5s"}})]}),dqs=()=>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(sL,{className:"absolute bottom-[8%] left-[5%] w-20 h-20 text-green-600/18"}),e.jsx(sL,{className:"absolute bottom-[12%] right-[8%] w-16 h-16 text-emerald-600/15"}),e.jsx(sL,{className:"absolute bottom-[10%] left-[28%] w-12 h-12 text-green-500/12"}),e.jsx(t2,{className:"absolute top-[5%] left-[15%] w-10 h-10 text-sky-300/30 animate-pulse"}),e.jsx(t2,{className:"absolute top-[10%] right-[20%] w-8 h-8 text-blue-300/25 animate-pulse",style:{animationDelay:"0.3s"}}),e.jsx(t2,{className:"absolute top-[18%] left-[45%] w-6 h-6 text-sky-200/25 animate-pulse",style:{animationDelay:"0.6s"}}),e.jsx(t2,{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(Ja,{className:"absolute top-[3%] left-[50%] -translate-x-1/2 w-10 h-10 text-amber-400/35 fill-amber-400/25"})]}),uqs=()=>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(Jo,{className:"absolute top-[8%] left-[55%] w-6 h-6 text-red-400/22 fill-red-400/12"}),e.jsx(Jo,{className:"absolute top-[20%] right-[25%] w-5 h-5 text-orange-400/22 fill-orange-400/12"})]}),hqs=()=>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(Ja,{className:"absolute top-[5%] left-[15%] w-12 h-12 text-yellow-400/35 fill-yellow-400/25 animate-pulse"}),e.jsx(Ja,{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(Ja,{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(Ja,{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(Nn,{className:"absolute top-[3%] left-[50%] w-10 h-10 text-yellow-400/40"}),e.jsx(Ax,{className:"absolute bottom-[18%] left-[10%] w-12 h-12 text-purple-400/18 rotate-12"}),e.jsx(Ax,{className:"absolute bottom-[20%] right-[12%] w-10 h-10 text-amber-400/15 -rotate-12"})]}),mqs=()=>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(Ja,{className:"absolute top-[8%] left-[50%] -translate-x-1/2 w-14 h-14 text-yellow-400/28 fill-yellow-400/18"}),e.jsx(Nn,{className:"absolute top-[5%] left-[20%] w-7 h-7 text-blue-400/35"}),e.jsx(Nn,{className:"absolute top-[10%] right-[18%] w-6 h-6 text-sky-400/30"})]}),fqs=()=>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(yE,{className:"absolute top-[5%] left-[10%] w-16 h-16 text-green-500/25"}),e.jsx(yE,{className:"absolute top-[8%] right-[12%] w-12 h-12 text-emerald-500/20"}),e.jsx(yE,{className:"absolute bottom-[18%] left-[12%] w-14 h-14 text-green-400/22"}),e.jsx(yE,{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"})]})]})]}),pqs=()=>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(Ja,{className:"absolute top-[5%] left-[42%] w-10 h-10 text-amber-400/30 fill-amber-400/20"}),e.jsx(Ja,{className:"absolute top-[15%] right-[25%] w-7 h-7 text-yellow-400/25 fill-yellow-400/15"}),e.jsx(Rm,{className:"absolute bottom-[20%] right-[12%] w-12 h-12 text-blue-500/18"}),e.jsx(Rm,{className:"absolute top-[18%] left-[28%] w-8 h-8 text-indigo-400/15"}),e.jsx(TE,{className:"absolute top-[8%] left-[60%] w-10 h-10 text-indigo-400/18"})]}),gqs=()=>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(Fg,{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(Ax,{className:"absolute top-[8%] left-[45%] w-10 h-10 text-purple-400/22 rotate-12"}),e.jsx(ul,{className:"absolute bottom-[18%] right-[15%] w-12 h-12 text-rose-400/18"})]}),xqs=()=>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(Jo,{className:"absolute top-[5%] left-[10%] w-16 h-16 text-rose-400/28 fill-rose-400/18"}),e.jsx(Jo,{className:"absolute top-[8%] right-[12%] w-14 h-14 text-pink-400/25 fill-pink-400/15"}),e.jsx(Jo,{className:"absolute bottom-[15%] left-[12%] w-12 h-12 text-red-400/22 fill-red-400/12"}),e.jsx(Jo,{className:"absolute bottom-[18%] right-[10%] w-13 h-13 text-rose-300/25 fill-rose-300/15"}),e.jsx(Jo,{className:"absolute top-[15%] left-[30%] w-6 h-6 text-pink-300/35 fill-pink-300/20 animate-pulse"}),e.jsx(Jo,{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(Jo,{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(Jo,{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"})]}),yqs=()=>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(rk,{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(rk,{className:"absolute top-[15%] left-[18%] w-10 h-10 text-yellow-400/30"}),e.jsx(Nn,{className:"absolute top-[10%] left-[42%] w-7 h-7 text-amber-400/35"}),e.jsx(rk,{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"})]}),vqs=()=>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(va,{className:"absolute top-[8%] left-[10%] w-14 h-14 text-teal-500/22"}),e.jsx(va,{className:"absolute bottom-[15%] right-[8%] w-16 h-16 text-emerald-500/18"}),e.jsx(S_,{className:"absolute top-[12%] right-[18%] w-10 h-10 text-amber-400/25"}),e.jsx(S_,{className:"absolute bottom-[22%] left-[22%] w-8 h-8 text-yellow-400/22"}),e.jsx(Jo,{className:"absolute top-[18%] left-[40%] w-6 h-6 text-rose-400/22 fill-rose-400/12"}),e.jsx(Jo,{className:"absolute top-[22%] right-[35%] w-5 h-5 text-teal-400/20 fill-teal-400/10"}),e.jsx(Nn,{className:"absolute top-[5%] left-[55%] w-8 h-8 text-teal-400/30"}),e.jsx(Ax,{className:"absolute bottom-[20%] left-[48%] w-10 h-10 text-cyan-400/18 rotate-12"})]}),bqs=()=>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(Ax,{className:"absolute top-[5%] left-[12%] w-14 h-14 text-emerald-400/25 rotate-12"}),e.jsx(Ax,{className:"absolute top-[8%] right-[10%] w-12 h-12 text-teal-400/22 -rotate-12"}),e.jsx(S_,{className:"absolute bottom-[18%] left-[18%] w-12 h-12 text-amber-400/25"}),e.jsx(va,{className:"absolute bottom-[15%] right-[12%] w-14 h-14 text-teal-500/18"}),e.jsx(Nn,{className:"absolute top-[15%] left-[42%] w-10 h-10 text-emerald-400/35"}),e.jsx(Nn,{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"})]}),_qs=()=>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(S_,{className:"absolute bottom-[12%] left-[50%] -translate-x-1/2 w-24 h-24 text-amber-400/25 rotate-45"}),e.jsx(S_,{className:"absolute top-[10%] left-[12%] w-10 h-10 text-yellow-400/30"}),e.jsx(S_,{className:"absolute top-[12%] right-[15%] w-9 h-9 text-amber-300/25"}),e.jsx(va,{className:"absolute top-[8%] left-[42%] w-12 h-12 text-teal-500/18"}),e.jsx(Ax,{className:"absolute bottom-[22%] right-[18%] w-12 h-12 text-orange-400/18 rotate-12"}),e.jsx(Nn,{className:"absolute top-[5%] right-[35%] w-8 h-8 text-yellow-400/35"}),e.jsx(Ja,{className:"absolute top-[18%] left-[28%] w-6 h-6 text-amber-400/25 fill-amber-400/15"})]}),wqs=()=>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(va,{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(S_,{className:"absolute top-[10%] right-[12%] w-10 h-10 text-amber-400/28"}),e.jsx(Jo,{className:"absolute top-[8%] left-[18%] w-8 h-8 text-rose-400/25 fill-rose-400/15"}),e.jsx(Nn,{className:"absolute top-[12%] left-[45%] w-8 h-8 text-teal-400/30"}),e.jsx(d2,{className:"absolute top-[15%] right-[28%] w-10 h-10 text-emerald-400/20"})]}),Zvt=()=>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"})]}),jqs=()=>e.jsxs("div",{className:"absolute inset-0 overflow-hidden pointer-events-none",children:[e.jsx(Jo,{className:"absolute top-6 left-[12%] w-4 h-4 text-rose-300/50 fill-rose-300/30 animate-pulse"}),e.jsx(Jo,{className:"absolute top-10 right-[18%] w-3 h-3 text-pink-300/50 fill-pink-300/30 animate-pulse delay-150"}),e.jsx(Jo,{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(Jo,{className:"absolute top-14 right-[35%] w-3.5 h-3.5 text-pink-300/40 fill-pink-300/20 animate-pulse delay-200"})]}),Nqs=()=>e.jsxs("div",{className:"absolute inset-0 overflow-hidden pointer-events-none",children:[e.jsx(d2,{className:"absolute top-5 left-[10%] w-4 h-4 text-blue-400/50 animate-pulse"}),e.jsx(Nn,{className:"absolute top-10 right-[15%] w-3 h-3 text-amber-400/50 animate-pulse delay-100"}),e.jsx(va,{className:"absolute top-8 left-[38%] w-3 h-3 text-teal-300/40 animate-pulse delay-200"})]}),kqs=()=>e.jsxs("div",{className:"absolute inset-0 overflow-hidden pointer-events-none",children:[e.jsx(P4,{className:"absolute top-5 left-[12%] w-4 h-4 text-amber-500/50 animate-pulse"}),e.jsx(Kq,{className:"absolute top-10 right-[15%] w-3 h-3 text-rose-400/50 animate-pulse delay-100"}),e.jsx(P4,{className:"absolute top-8 left-[40%] w-3 h-3 text-amber-400/40 animate-pulse delay-200"})]}),LZ=()=>e.jsxs("div",{className:"absolute inset-0 overflow-hidden pointer-events-none",children:[e.jsx(Nn,{className:"absolute top-5 left-[10%] w-4 h-4 text-emerald-400/50 animate-pulse"}),e.jsx(Ax,{className:"absolute top-10 right-[12%] w-5 h-5 text-amber-400/50 animate-pulse delay-150"}),e.jsx(Nn,{className:"absolute top-8 left-[45%] w-3 h-3 text-sky-400/40 animate-pulse delay-300"})]}),Xvt=()=>e.jsxs("div",{className:"absolute inset-0 overflow-hidden pointer-events-none",children:[e.jsx(va,{className:"absolute top-6 left-[12%] w-4 h-4 text-teal-400/40 animate-pulse"}),e.jsx(Nn,{className:"absolute top-10 right-[15%] w-3 h-3 text-emerald-400/50 animate-pulse delay-100"}),e.jsx(va,{className:"absolute top-4 right-[40%] w-3 h-3 text-cyan-400/30 animate-pulse delay-200"})]}),BGe=[{id:"default",name:"Classic",description:"Clean, professional look for any occasion",icon:e.jsx(Nn,{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(Jo,{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(jqs,{})},{id:"thinking_of_you",name:"Thinking of You",description:"Let them know they're on your mind",icon:e.jsx(vJ,{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(LZ,{})},{id:"check_in",name:"Check-in",description:"Touch base with your contacts",icon:e.jsx(P4,{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(kqs,{})},{id:"market_update",name:"Market Update",description:"Share real estate market insights",icon:e.jsx(Wl,{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(Zn,{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(LZ,{})},{id:"congratulations",name:"Congratulations",description:"Celebrate their achievements",icon:e.jsx(Rm,{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(Zvt,{})},{id:"welcome_neighborhood",name:"Welcome to the Neighborhood",description:"Greet new neighbors",icon:e.jsx(ci,{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(Xvt,{})},{id:"just_because",name:"Just Because",description:"No reason needed to connect",icon:e.jsx(Kq,{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(LZ,{})},{id:"birthday",name:"Birthday",description:"Celebrate their special day",icon:e.jsx(Fg,{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(gqs,{})},{id:"valentines_day",name:"Valentine's Day",description:"Show appreciation on this special day",icon:e.jsx(Jo,{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(xqs,{})},{id:"groundhog_day",name:"Groundhog Day",description:"A fun seasonal greeting",icon:e.jsx(rk,{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(yqs,{})},{id:"new_years",name:"New Year's Day",description:"Ring in the new year",icon:e.jsx(Ja,{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(hqs,{})},{id:"easter",name:"Easter",description:"Celebrate the spring season",icon:e.jsx(Lq,{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(lqs,{})},{id:"mothers_day",name:"Mother's Day",description:"Celebrate the amazing moms",icon:e.jsx(HS,{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(iqs,{})},{id:"fathers_day",name:"Father's Day",description:"Celebrate the amazing dads",icon:e.jsx(Rm,{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(oqs,{})},{id:"memorial_day",name:"Memorial Day",description:"Honor those who served",icon:e.jsx(TE,{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(rqs,{})},{id:"independence_day",name:"4th of July",description:"Celebrate Independence Day",icon:e.jsx(nh,{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(aqs,{})},{id:"labor_day",name:"Labor Day",description:"Celebrate the workers",icon:e.jsx(Rm,{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(pqs,{})},{id:"halloween",name:"Halloween",description:"Spooky seasonal greetings",icon:e.jsx(Vz,{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(cqs,{})},{id:"thanksgiving",name:"Thanksgiving",description:"Express gratitude this season",icon:e.jsx(Jo,{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(uqs,{})},{id:"christmas",name:"Christmas",description:"Spread holiday cheer",icon:e.jsx(sL,{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(dqs,{})},{id:"hanukkah",name:"Hanukkah",description:"Celebrate the Festival of Lights",icon:e.jsx(Nn,{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(mqs,{})},{id:"st_patricks_day",name:"St. Patrick's Day",description:"Celebrate the luck of the Irish",icon:e.jsx(yE,{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(fqs,{})},{id:"home_anniversary",name:"Home Anniversary",description:"Celebrate their home ownership milestone",icon:e.jsx(va,{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(vqs,{})},{id:"under_contract",name:"Under Contract",description:"Celebrate this exciting milestone",icon:e.jsx(Ax,{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(bqs,{})},{id:"just_listed",name:"Just Listed",description:"Announce a new listing",icon:e.jsx(Ta,{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(Xvt,{})},{id:"just_sold",name:"Just Sold",description:"Celebrate a successful sale",icon:e.jsx(ru,{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(LZ,{})},{id:"price_reduction",name:"Price Reduction",description:"Notify about a price change",icon:e.jsx(rC,{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(d2,{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(Nqs,{})},{id:"closing_day",name:"Closing Day",description:"Celebrate their closing day",icon:e.jsx(S_,{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(_qs,{})},{id:"move_in_day",name:"Move-in Day",description:"Welcome them to their new home",icon:e.jsx(va,{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(wqs,{})},{id:"offer_accepted",name:"Offer Accepted",description:"Celebrate their accepted offer",icon:e.jsx(Vy,{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(LZ,{})},{id:"pre_approval",name:"Pre-Approval Congrats",description:"Congratulate on pre-approval",icon:e.jsx(Rm,{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(Zvt,{})}],Sqs=[{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 Cqs(s){return BGe.filter(t=>t.category===s)}function kV(s){return BGe.find(t=>t.id===s)||BGe[0]}function Qvt(){const{shareToken:s,recipientToken:t}=Wi(),[n,r]=j.useState(null),[a,i]=j.useState(null),[l,o]=j.useState(null),[c,d]=j.useState(!0),[u,h]=j.useState(null),[m,f]=j.useState(!0),g=j.useRef(null),x=j.useRef(0),y=j.useRef(0),v=(()=>{const U=new URLSearchParams(window.location.search);return t||U.get("rt")||null})(),b=j.useCallback((U,W=!1)=>{if(!v||U<=0)return;const V=Math.max(1,Math.round(U));if(V<=y.current)return;const Y=`https://relzejiswnotikjgvjhz.supabase.co/functions/v1/track-video-share?t=${encodeURIComponent(v)}&e=watch&ws=${V}`;W&&navigator.sendBeacon?navigator.sendBeacon(Y):fetch(Y,{method:"GET",keepalive:W}).catch(()=>{}),y.current=Math.max(y.current,V)},[v]);j.useEffect(()=>{var ae;if(!m||!(n!=null&&n.playback_url)||!v)return;let U=!1;const W=()=>{x.current>0&&b(x.current,!0)},V=()=>{document.visibilityState==="hidden"&&W()},G=()=>{W()},Y=()=>{var ne;if(U||!g.current||!((ne=window.playerjs)!=null&&ne.Player))return;const ie=new window.playerjs.Player(g.current);ie.on("timeupdate",te=>{const J=Math.floor(Number((te==null?void 0:te.seconds)??0));!Number.isFinite(J)||J<=0||(x.current=Math.max(x.current,J))}),ie.on("pause",()=>{x.current>0&&b(x.current)}),ie.on("ended",()=>{x.current>0&&b(x.current,!0)})},X=document.querySelector('script[data-bunny-playerjs="true"]');if((ae=window.playerjs)!=null&&ae.Player)Y();else if(X)X.addEventListener("load",Y,{once:!0});else{const ie=document.createElement("script");ie.src="https://assets.mediadelivery.net/playerjs/playerjs-latest.min.js",ie.async=!0,ie.defer=!0,ie.dataset.bunnyPlayerjs="true",ie.onload=Y,document.body.appendChild(ie)}return document.addEventListener("visibilitychange",V),window.addEventListener("beforeunload",G),()=>{U=!0,document.removeEventListener("visibilitychange",V),window.removeEventListener("beforeunload",G),W()}},[m,n==null?void 0:n.playback_url,v,b]),j.useEffect(()=>{x.current=0,y.current=0},[v,s]),j.useEffect(()=>{const U=()=>{['[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(Y=>{document.querySelectorAll(Y).forEach(X=>{X.style.display="none"})})};U();const W=[setTimeout(U,500),setTimeout(U,1500),setTimeout(U,3e3)],V=new MutationObserver(U);return V.observe(document.body,{childList:!0,subtree:!0}),()=>{W.forEach(clearTimeout),V.disconnect()}},[]),j.useEffect(()=>{(async()=>{if(!s){h("Invalid share link"),d(!1);return}const{data:W,error:V}=await q.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(V||!W){h("Video not found or has been removed"),d(!1);return}r(W);try{await q.rpc("log_video_view",{p_video_id:W.id,p_user_agent:navigator.userAgent,p_referrer:document.referrer||null})}catch(G){console.warn("Failed to log video view:",G)}if(W.owner_user_id){const{data:G}=await q.from("profiles").select("id, name, email, phone").eq("id",W.owner_user_id).single();if(G){i(G);try{const{data:Y}=await q.storage.from("avatars").list(`${W.owner_user_id}`);if(Y&&Y.length>0){const{data:X}=q.storage.from("avatars").getPublicUrl(`${W.owner_user_id}/${Y[0].name}`);o(X.publicUrl)}}catch{}}}d(!1)})()},[s]);const w=U=>{if(!U)return"0:00";const W=Math.floor(U/60),V=U%60;return`${W}:${V.toString().padStart(2,"0")}`},S=U=>U.includes("iframe.mediadelivery.net/play/")?U.replace("/play/","/embed/")+"?autoplay=true&responsive=true":U,C=U=>{if(!U)return"?";const W=U.split(" ");return W.length>=2?`${W[0][0]}${W[1][0]}`.toUpperCase():U.substring(0,2).toUpperCase()},E=kV((n==null?void 0:n.page_template)||"default"),I=(n==null?void 0:n.recipient_name)||null,P=E.headerText(I),D=`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(kt,{className:"h-8 w-8 animate-spin text-primary"})});if(u||!n)return e.jsx("div",{className:"min-h-screen bg-background flex items-center justify-center p-4",children:e.jsx(Ne,{className:"max-w-md w-full",children:e.jsxs(Ie,{className:"py-12 text-center",children:[e.jsx(ua,{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:u||"This video is no longer available."})]})})});const O=E.id!=="default";return e.jsxs(e.Fragment,{children:[e.jsxs(Ml,{children:[e.jsx("title",{children:P}),e.jsx("meta",{name:"description",content:E.subText}),e.jsx("meta",{property:"og:title",content:P}),e.jsx("meta",{property:"og:description",content:E.subText}),e.jsx("meta",{property:"og:type",content:"video.other"}),e.jsx("meta",{property:"og:url",content:D}),n.preview_url&&e.jsx("meta",{property:"og:image",content:n.preview_url}),!n.preview_url&&n.thumbnail_url&&e.jsx("meta",{property:"og:image",content:n.thumbnail_url}),n.playback_url&&e.jsxs(e.Fragment,{children:[e.jsx("meta",{property:"og:video",content:n.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:P}),e.jsx("meta",{name:"twitter:description",content:E.subText}),n.preview_url&&e.jsx("meta",{name:"twitter:image",content:n.preview_url}),n.playback_url&&e.jsxs(e.Fragment,{children:[e.jsx("meta",{name:"twitter:player",content:n.playback_url}),e.jsx("meta",{name:"twitter:player:width",content:"1280"}),e.jsx("meta",{name:"twitter:player:height",content:"720"})]})]}),e.jsxs("div",{className:Pt("min-h-screen flex items-center justify-center p-4 bg-gradient-to-b relative",E.gradientClasses),children:[O&&E.decorativeElement,e.jsxs("div",{className:"max-w-2xl w-full space-y-6 relative z-10",children:[O&&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:Pt("w-14 h-14 rounded-full flex items-center justify-center shadow-sm",E.accentColor==="primary"&&"bg-primary/10 text-primary",E.accentColor==="amber"&&"bg-amber-100 text-amber-600 dark:bg-amber-900/50 dark:text-amber-400",E.accentColor==="teal"&&"bg-teal-100 text-teal-600 dark:bg-teal-900/50 dark:text-teal-400",E.accentColor==="rose"&&"bg-rose-100 text-rose-600 dark:bg-rose-900/50 dark:text-rose-400",E.accentColor==="emerald"&&"bg-emerald-100 text-emerald-600 dark:bg-emerald-900/50 dark:text-emerald-400",E.accentColor==="yellow"&&"bg-yellow-100 text-yellow-600 dark:bg-yellow-900/50 dark:text-yellow-400",E.accentColor==="pink"&&"bg-pink-100 text-pink-600 dark:bg-pink-900/50 dark:text-pink-400",E.accentColor==="blue"&&"bg-blue-100 text-blue-600 dark:bg-blue-900/50 dark:text-blue-400",E.accentColor==="red"&&"bg-red-100 text-red-600 dark:bg-red-900/50 dark:text-red-400",E.accentColor==="orange"&&"bg-orange-100 text-orange-600 dark:bg-orange-900/50 dark:text-orange-400",E.accentColor==="green"&&"bg-green-100 text-green-600 dark:bg-green-900/50 dark:text-green-400",E.accentColor==="violet"&&"bg-violet-100 text-violet-600 dark:bg-violet-900/50 dark:text-violet-400",E.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:E.icon})})}),e.jsx("h1",{className:"text-2xl sm:text-3xl font-bold mb-2",children:P}),e.jsx("p",{className:"text-muted-foreground",children:E.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(Oa,{className:"h-14 w-14 border-2 border-primary/20",children:[e.jsx(Li,{src:l||void 0,alt:a.name||"Agent"}),e.jsx(za,{className:"bg-primary/10 text-primary font-semibold",children:C(a.name)})]}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:O?"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($,{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(Da,{className:"h-4 w-4"})})}),a.email&&e.jsx($,{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(mn,{className:"h-4 w-4"})})})]})]}),e.jsx(Ne,{className:"overflow-hidden shadow-lg",children:m&&n.playback_url?e.jsx("div",{className:"relative w-full",style:{paddingBottom:"56.25%"},children:e.jsx("iframe",{ref:g,src:S(n.playback_url),title:n.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:()=>f(!0),children:[n.preview_url||n.thumbnail_url?e.jsx("img",{src:n.preview_url||n.thumbnail_url||"",alt:n.title?`${n.title} video preview`:"Video message preview",className:"w-full h-full object-cover",onError:U=>{var V;U.currentTarget.style.display="none";const W=(V=U.currentTarget.parentElement)==null?void 0:V.querySelector(".video-fallback");W&&(W.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:n.preview_url||n.thumbnail_url?"none":"flex"},children:e.jsx(ua,{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(Bu,{className:"h-10 w-10 text-primary ml-1"})})}),n.duration_seconds&&e.jsx("div",{className:"absolute bottom-3 right-3 bg-black/70 text-white text-sm px-2 py-1 rounded",children:w(n.duration_seconds)})]})}),!O&&e.jsxs("div",{className:"text-center",children:[e.jsx("h1",{className:"text-2xl font-bold",children:n.title||"Video Message"}),e.jsx("p",{className:"text-muted-foreground mt-2",children:m?"Enjoy the video!":"Click to play the video"})]}),!m&&e.jsx("div",{className:"flex justify-center",children:e.jsxs($,{size:"lg",onClick:()=>f(!0),className:"gap-2",children:[e.jsx(Bu,{className:"h-5 w-5"}),"Watch Video"]})}),e.jsx(nqs,{shareToken:s,agentName:(a==null?void 0:a.name)||null,hasContact:!!n.contact_id})]})]})]})}function Aqs(){return j.useEffect(()=>(document.body.classList.add("video-landing-page"),()=>{document.body.classList.remove("video-landing-page")}),[]),e.jsx(Iet,{})}function Eqs(){const{token:s}=Wi();return j.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(kt,{className:"h-5 w-5 animate-spin"}),e.jsx("span",{children:"Loading video preview…"})]})})}const Tqs=[{key:"residential",title:"Residential",tagline:"Homes, condos, land & luxury",path:"/mission-control/listings/new/residential",icon:va,points:["Standard listing details","Listing Exchange & referrals","Single-property site & marketing"]},{key:"commercial",title:"Commercial",tagline:"Investment, office, retail, industrial & land",path:"/mission-control/listings/new/commercial",icon:ji,points:["Pitch Mode to win the assignment","Institutional-grade microsite","Gated OM & investor tracking"],featured:!0}];function Mqs(){const s=Qn(),{search:t}=fu();return e.jsx("div",{className:"min-h-screen bg-background",children:e.jsxs("div",{className:"mx-auto max-w-5xl px-4 py-10",children:[e.jsxs($,{variant:"ghost",size:"sm",className:"mb-6 -ml-2",onClick:()=>s("/mission-control/listings"),children:[e.jsx(qa,{className:"mr-2 h-4 w-4"})," Listing Exchange"]}),e.jsxs("div",{className:"mb-10",children:[e.jsx("p",{className:"text-xs font-medium uppercase tracking-[0.2em] text-muted-foreground",children:"New listing"}),e.jsx("h1",{className:"mt-2 text-3xl font-semibold tracking-tight md:text-4xl",children:"What are you marketing?"}),e.jsx("p",{className:"mt-2 max-w-xl text-muted-foreground",children:"Choose the workflow that fits. Commercial unlocks Pitch Mode, investment metrics and the Commercial Launch marketing workspace."})]}),e.jsx("div",{className:"grid gap-5 md:grid-cols-2",children:Tqs.map(n=>{const r=n.icon;return e.jsxs("button",{onClick:()=>s(`${n.path}${t}`),className:`group relative overflow-hidden rounded-2xl border p-7 text-left transition-all hover:-translate-y-0.5 hover:shadow-xl ${n.featured?"border-primary/40 bg-gradient-to-br from-primary/[0.07] to-transparent":"bg-card"}`,children:[n.featured&&e.jsxs("span",{className:"absolute right-5 top-5 inline-flex items-center gap-1 rounded-full border border-primary/30 bg-primary/10 px-2.5 py-1 text-[10px] font-semibold uppercase tracking-wider text-primary",children:[e.jsx(Nn,{className:"h-3 w-3"})," Commercial Launch"]}),e.jsx("div",{className:"mb-5 flex h-12 w-12 items-center justify-center rounded-xl border bg-background",children:e.jsx(r,{className:"h-6 w-6"})}),e.jsx("h2",{className:"text-xl font-semibold",children:n.title}),e.jsx("p",{className:"mt-1 text-sm text-muted-foreground",children:n.tagline}),e.jsx("ul",{className:"mt-5 space-y-2 text-sm text-muted-foreground",children:n.points.map(a=>e.jsxs("li",{className:"flex items-start gap-2",children:[e.jsx("span",{className:"mt-[7px] h-1 w-1 shrink-0 rounded-full bg-foreground/40"}),a]},a))}),e.jsxs("span",{className:"mt-6 inline-flex items-center gap-1 text-sm font-medium text-primary",children:["Continue ",e.jsx(ei,{className:"h-4 w-4 transition-transform group-hover:translate-x-0.5"})]})]},n.key)})})]})})}const R$t=()=>{const{user:s}=vs();return tt({queryKey:["managed-agent-ids",s==null?void 0:s.id],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await q.from("team_members").select("team_id").eq("user_id",s.id).eq("role","team_leader");if(n)throw n;const r=(t||[]).map(l=>l.team_id).filter(Boolean);if(!r.length)return[s.id];const{data:a,error:i}=await q.from("team_members").select("user_id").in("team_id",r);if(i)throw i;return Array.from(new Set([s.id,...(a||[]).map(l=>l.user_id).filter(Boolean)]))},enabled:!!s,staleTime:5*60*1e3})},D$t=s=>{const{user:t}=vs(),{data:n}=R$t();return!t||!s?!1:t.id===s?!0:(n||[]).includes(s)},F$t=()=>tt({queryKey:["listing-exchange-enabled"],queryFn:async()=>{const{data:s,error:t}=await q.from("feature_flags").select("enabled").eq("key","listing_exchange_enabled").maybeSingle();if(t)throw t;return(s==null?void 0:s.enabled)??!1}}),O$t=s=>{const{user:t,brokerageId:n}=vs();return tt({queryKey:["listings",s,n],queryFn:async()=>{let r=q.from("listings").select(` *, photos:listing_photos(*), commercial:commercial_listing_details(*), agent:profiles!listings_agent_id_fkey(id, name, email, brokerage_id, brokerage:brokerages(name)) `).eq("is_approved",!0).eq("is_public",!0).or("lifecycle_stage.is.null,lifecycle_stage.neq.pitch");s!=null&&s.listingClass&&(r=r.eq("listing_class",s.listingClass)),s!=null&&s.status?r=r.eq("status",s.status):r=r.neq("status","sold"),s!=null&&s.propertyType&&(r=r.eq("property_type",s.propertyType)),s!=null&&s.city&&(r=r.ilike("city",`%${s.city}%`)),s!=null&&s.minPrice&&(r=r.gte("price",s.minPrice)),s!=null&&s.maxPrice&&(r=r.lte("price",s.maxPrice)),s!=null&&s.openToReferrals&&(r=r.eq("open_to_referrals",!0));const{data:a,error:i}=await r;if(i)throw i;let l=a||[];if(n){const{data:o}=await q.from("profiles").select("id").eq("brokerage_id",n);if(o&&o.length>0){const c=o.map(h=>h.id);let d=q.from("listings").select(` *, photos:listing_photos(*), commercial:commercial_listing_details(*), 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).eq("site_only",!1).in("agent_id",c).or("lifecycle_stage.is.null,lifecycle_stage.neq.pitch");s!=null&&s.listingClass&&(d=d.eq("listing_class",s.listingClass)),s!=null&&s.status?d=d.eq("status",s.status):d=d.neq("status","sold"),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:u}=await d;if(u){const h=new Set(l.map(f=>f.id)),m=u.filter(f=>!h.has(f.id));l=[...l,...m]}}}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.map(o=>Xst(Zst(o)))}})};function Zst(s){return s&&Array.isArray(s.commercial)&&(s.commercial=s.commercial[0]??null),s}function Xst(s){return Array.isArray(s==null?void 0:s.photos)&&(s.photos=[...s.photos].sort((t,n)=>(t.sort_order??0)-(n.sort_order??0)||(n.is_primary?1:0)-(t.is_primary?1:0))),s}const Qst=()=>{const{user:s}=vs(),{data:t,isLoading:n}=R$t(),r=t&&t.length?t:s?[s.id]:[];return tt({queryKey:["my-listings",s==null?void 0:s.id,r.slice().sort().join(",")],queryFn:async()=>{if(!s)return[];const{data:a,error:i}=await q.from("listings").select(` *, photos:listing_photos(*), commercial:commercial_listing_details(*) `).in("agent_id",r).order("created_at",{ascending:!1});if(i)throw i;return a.map(l=>Xst(Zst(l)))},enabled:!!s&&!n})},tie=s=>{const{user:t}=vs();return tt({queryKey:["listing",s],queryFn:async()=>{const{data:n,error:r}=await q.from("listings").select(` *, photos:listing_photos(*), commercial:commercial_listing_details(*), 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(r)throw r;return t&&await q.from("listing_views").insert({listing_id:s,viewer_id:t.id}),Xst(Zst(n))},enabled:!!s})},z$t=()=>{const s=Vt(),{user:t}=vs();return ft({mutationFn:async n=>{if(!t)throw new Error("Not authenticated");const{data:r,error:a}=await q.from("listings").insert({...n,agent_id:t.id}).select().single();if(a)throw a;return r},onSuccess:()=>{s.invalidateQueries({queryKey:["listings"]}),s.invalidateQueries({queryKey:["my-listings"]})}})},Pqs=()=>{const s=Vt();return ft({mutationFn:async({agentId:t,...n})=>{const{data:r,error:a}=await q.from("listings").insert({...n,agent_id:t}).select().single();if(a)throw a;return r},onSuccess:()=>{s.invalidateQueries({queryKey:["listings"]}),s.invalidateQueries({queryKey:["my-listings"]}),s.invalidateQueries({queryKey:["brokerage-listings"]})}})},B$t=()=>{const s=Vt();return ft({mutationFn:async({id:t,...n})=>{const r=n.is_public===!0?{...n,is_approved:!0}:{...n},{data:a,error:i}=await q.from("listings").update(r).eq("id",t).select().single();if(i)throw i;return a},onSuccess:t=>{s.invalidateQueries({queryKey:["listings"]}),s.invalidateQueries({queryKey:["my-listings"]}),s.invalidateQueries({queryKey:["listing",t.id]})}})},$$t=()=>{const s=Vt();return ft({mutationFn:async t=>{const{error:n}=await q.from("listings").delete().eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["listings"]}),s.invalidateQueries({queryKey:["my-listings"]})}})},U$t=()=>{const s=Vt();return ft({mutationFn:async({listingId:t,photoUrl:n,isPrimary:r=!1})=>{const{data:a,error:i}=await q.from("listing_photos").insert({listing_id:t,photo_url:n,is_primary:r}).select().single();if(i)throw i;return a},onSuccess:t=>{s.invalidateQueries({queryKey:["listing",t.listing_id]}),s.invalidateQueries({queryKey:["my-listings"]})}})},q$t=()=>{const s=Vt();return ft({mutationFn:async({photoId:t,listingId:n})=>{const{error:r}=await q.from("listing_photos").delete().eq("id",t);if(r)throw r;return n},onSuccess:t=>{s.invalidateQueries({queryKey:["listing",t]}),s.invalidateQueries({queryKey:["my-listings"]})}})},V$t=()=>{const s=Vt();return ft({mutationFn:async({photos:t})=>{var i;const n=t.map(l=>q.from("listing_photos").update({sort_order:l.sort_order,is_primary:l.is_primary}).eq("id",l.id)),a=(i=(await Promise.all(n)).find(l=>l.error))==null?void 0:i.error;if(a)throw a;return t},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["listing"]}),s.invalidateQueries({queryKey:["my-listings"]})}})},H$t=()=>{const s=Vt();return ft({mutationFn:async({photoId:t,listingId:n})=>{const{error:r}=await q.from("listing_photos").update({is_primary:!1}).eq("listing_id",n);if(r)throw r;const{error:a}=await q.from("listing_photos").update({is_primary:!0}).eq("id",t);if(a)throw a;return n},onSuccess:t=>{s.invalidateQueries({queryKey:["listing",t]}),s.invalidateQueries({queryKey:["my-listings"]})}})},Iqs=()=>{const{user:s}=vs();return tt({queryKey:["saved-listings",s==null?void 0:s.id],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await q.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(n)throw n;return t},enabled:!!s})},G$t=()=>{const s=Vt(),{user:t}=vs();return ft({mutationFn:async n=>{if(!t)throw new Error("Not authenticated");const{data:r}=await q.from("listing_saves").select("id").eq("listing_id",n).eq("agent_id",t.id).maybeSingle();return r?(await q.from("listing_saves").delete().eq("id",r.id),{saved:!1}):(await q.from("listing_saves").insert({listing_id:n,agent_id:t.id}),{saved:!0})},onSuccess:()=>{s.invalidateQueries({queryKey:["saved-listings"]}),s.invalidateQueries({queryKey:["listings"]})}})},W$t=s=>{const{user:t}=vs();return tt({queryKey:["listing-saved",s,t==null?void 0:t.id],queryFn:async()=>{if(!t)return!1;const{data:n}=await q.from("listing_saves").select("id").eq("listing_id",s).eq("agent_id",t.id).maybeSingle();return!!n},enabled:!!t&&!!s})},Lqs=()=>{const s=Vt(),{user:t}=vs();return ft({mutationFn:async n=>{if(!t)throw new Error("Not authenticated");const{data:r}=await q.from("listing_follows").select("id").eq("listing_id",n).eq("agent_id",t.id).maybeSingle();return r?(await q.from("listing_follows").delete().eq("id",r.id),{following:!1}):(await q.from("listing_follows").insert({listing_id:n,agent_id:t.id}),{following:!0})},onSuccess:()=>{s.invalidateQueries({queryKey:["listing-following"]})}})},Rqs=s=>{const{user:t}=vs();return tt({queryKey:["listing-following",s,t==null?void 0:t.id],queryFn:async()=>{if(!t)return!1;const{data:n}=await q.from("listing_follows").select("id").eq("listing_id",s).eq("agent_id",t.id).maybeSingle();return!!n},enabled:!!t&&!!s})},Dqs=()=>{const{user:s}=vs();return ft({mutationFn:async({listingId:t,shareType:n})=>{if(!s)throw new Error("Not authenticated");const{error:r}=await q.from("listing_shares").insert({listing_id:t,sharing_agent_id:s.id,share_type:n});if(r)throw r}})},Fqs=()=>{const{user:s}=vs();return tt({queryKey:["my-referrals",s==null?void 0:s.id],queryFn:async()=>{if(!s)return{sent:[],received:[]};const[t,n]=await Promise.all([q.from("listing_referrals").select(` *, listing:listings(*,photos:listing_photos(*)) `).eq("sender_agent_id",s.id).order("created_at",{ascending:!1}),q.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:n.data||[]}},enabled:!!s})},Oqs=()=>{const s=Vt(),{user:t}=vs();return ft({mutationFn:async({listingId:n,listingAgentId:r,buyerName:a,buyerType:i,notes:l})=>{if(!t)throw new Error("Not authenticated");const{data:o,error:c}=await q.from("listing_referrals").insert({listing_id:n,sender_agent_id:t.id,listing_agent_id:r,buyer_name:a,buyer_type:i,notes:l}).select().single();if(c)throw c;return o},onSuccess:()=>{s.invalidateQueries({queryKey:["my-referrals"]})}})},zqs=()=>tt({queryKey:["listing-leaderboard"],queryFn:async()=>{const{data:s}=await q.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 n=Array.from(t.entries()).map(([l,o])=>({agentId:l,...o})).sort((l,o)=>o.count-l.count).slice(0,10),{data:r}=await q.from("listings").select("agent_id, agent:profiles!listings_agent_id_fkey(name)").eq("is_approved",!0),a=new Map;r==null||r.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:n,topListers:i}}}),Bqs=()=>{const{user:s,brokerageId:t}=vs();return tt({queryKey:["brokerage-listings",t],queryFn:async()=>{if(!s||!t)return[];const{data:n}=await q.from("profiles").select("id").eq("brokerage_id",t);if(!n||n.length===0)return[];const r=n.map(l=>l.id),{data:a,error:i}=await q.from("listings").select(` *, photos:listing_photos(*), commercial:commercial_listing_details(*), agent:profiles!listings_agent_id_fkey(id, name, email, brokerage_id, brokerage:brokerages(name)) `).in("agent_id",r).eq("is_approved",!0).order("created_at",{ascending:!1});if(i)throw i;return a},enabled:!!s&&!!t})},Z7e=q,gp=s=>s===""||s==null?null:Number(String(s).replace(/[^0-9.\-]/g,"")),$qs={property_address:"",city:"",state:"",submarket:"",opportunity_title:"",description:"",deal_type:"sale",commercial_type:"office",asking_price:"",lease_rate:"",lease_rate_unit:"sf_year",lease_type:"",building_sf:"",available_sf:"",lot_acres:"",units:"",floors:"",year_built:"",parking_spaces:"",zoning:"",occupancy_pct:"",tenancy:"",noi:"",cap_rate:"",gross_income:"",operating_expenses:"",broker_coop_pct:"",call_for_offers_at:"",is_confidential:!1,hide_address:!1,requires_nda:!1,om_gate_mode:"email",opportunity_zone:!1,is_public:!1,allow_sharing:!0,share_with_brokerage:!1,open_to_referrals:!0,open_to_social_promotion:!0,show_on_lead_site:!0,site_only:!1};function Jvt({label:s,placeholder:t,items:n,onChange:r}){return e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:s}),n.map((a,i)=>e.jsxs("div",{className:"flex gap-2",children:[e.jsx(pe,{value:a,placeholder:t,onChange:l=>r(n.map((o,c)=>c===i?l.target.value:o))}),e.jsx($,{type:"button",variant:"ghost",size:"icon",onClick:()=>r(n.filter((l,o)=>o!==i)),children:e.jsx(gr,{className:"h-4 w-4"})})]},i)),e.jsxs($,{type:"button",variant:"outline",size:"sm",onClick:()=>r([...n,""]),children:[e.jsx(dn,{className:"mr-1.5 h-3.5 w-3.5"})," Add"]})]})}function X7e({label:s,description:t,columns:n,rows:r,onChange:a}){return e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(ee,{children:s}),t&&e.jsx("p",{className:"text-xs text-muted-foreground",children:t})]}),r.map((i,l)=>e.jsxs("div",{className:"flex flex-wrap items-end gap-2 rounded-lg border p-3",children:[n.map(o=>e.jsxs("div",{className:"min-w-[120px] flex-1 space-y-1",children:[e.jsx(ee,{className:"text-[11px] uppercase tracking-wide text-muted-foreground",children:o.label}),e.jsx(pe,{value:i[o.key]??"",placeholder:o.placeholder,onChange:c=>a(r.map((d,u)=>u===l?{...d,[o.key]:c.target.value}:d))})]},o.key)),e.jsx($,{type:"button",variant:"ghost",size:"icon",onClick:()=>a(r.filter((o,c)=>c!==l)),children:e.jsx(gr,{className:"h-4 w-4"})})]},l)),e.jsxs($,{type:"button",variant:"outline",size:"sm",onClick:()=>a([...r,{}]),children:[e.jsx(dn,{className:"mr-1.5 h-3.5 w-3.5"})," Add row"]})]})}const Uqs=[{key:"radius_1",label:"1 mile"},{key:"radius_3",label:"3 miles"},{key:"radius_5",label:"5 miles"}],qqs=[{key:"population",label:"Population"},{key:"households",label:"Households"},{key:"avg_income",label:"Avg income"},{key:"daytime_pop",label:"Daytime pop."}];function ebt(){const{listingId:s}=Wi(),t=Qn(),{user:n,loading:r}=vs(),a=!!s,{data:i,isLoading:l}=tie(s||""),{data:o}=B7t(s);z$t();const c=B$t(),d=$7t(),u=U7t(),[h,m]=j.useState(null),[f,g]=j.useState($qs),[x,y]=j.useState([""]),[v,b]=j.useState([]),[w,S]=j.useState([]),[C,E]=j.useState([]),[I,P]=j.useState([]),[R,D]=j.useState({}),[O,U]=j.useState(!1),[W,V]=j.useState([]),[G,Y]=j.useState([]),X=!a||!!(n!=null&&n.id)&&(i==null?void 0:i.agent_id)===n.id;j.useEffect(()=>{!a||r||l||!i||X||(re.error("Only the listing agent can edit this commercial listing"),t(`/mission-control/listings/${i.id}/commercial`,{replace:!0}))},[r,i,a,X,l,t]);const ae=ue=>{if(!(ue!=null&&ue.length))return;const ve=Array.from(ue);V(Ee=>[...Ee,...ve]),Y(Ee=>[...Ee,...ve.map(Se=>URL.createObjectURL(Se))])},ie=ue=>{URL.revokeObjectURL(G[ue]),V(ve=>ve.filter((Ee,Se)=>Se!==ue)),Y(ve=>ve.filter((Ee,Se)=>Se!==ue))},ne=async ue=>{if(!W.length)return;const{count:ve}=await Z7e.from("listing_photos").select("id",{count:"exact",head:!0}).eq("listing_id",ue),Ee=ve??0;for(let Se=0;Seg(Ee=>({...Ee,[ue]:ve}));j.useEffect(()=>{!a||!i||(m(i.lifecycle_stage==="pitch"?"pitch":"assignment"),g(ue=>({...ue,property_address:i.property_address??"",city:i.city??"",state:i.state??"",description:i.description??"",year_built:i.year_built?String(i.year_built):"",is_public:!!i.is_public,allow_sharing:i.allow_sharing??!0,share_with_brokerage:i.share_with_brokerage??!1,open_to_referrals:i.open_to_referrals??!0,open_to_social_promotion:i.open_to_social_promotion??!0,show_on_lead_site:i.show_on_lead_site??!0,site_only:!i.is_public&&(i.show_on_lead_site??!1)&&!i.allow_sharing})))},[a,i]),j.useEffect(()=>{var ue;o&&(g(ve=>({...ve,submarket:o.submarket??"",opportunity_title:o.opportunity_title??"",deal_type:o.deal_type??"sale",commercial_type:o.commercial_type??"office",asking_price:o.asking_price!=null?String(o.asking_price):"",lease_rate:o.lease_rate!=null?String(o.lease_rate):"",lease_rate_unit:o.lease_rate_unit??"sf_year",lease_type:o.lease_type??"",building_sf:o.building_sf!=null?String(o.building_sf):"",available_sf:o.available_sf!=null?String(o.available_sf):"",lot_acres:o.lot_acres!=null?String(o.lot_acres):"",units:o.units!=null?String(o.units):"",floors:o.floors!=null?String(o.floors):"",parking_spaces:o.parking_spaces!=null?String(o.parking_spaces):"",zoning:o.zoning??"",occupancy_pct:o.occupancy_pct!=null?String(o.occupancy_pct):"",tenancy:o.tenancy??"",noi:o.noi!=null?String(o.noi):"",cap_rate:o.cap_rate!=null?String(o.cap_rate):"",gross_income:o.gross_income!=null?String(o.gross_income):"",operating_expenses:o.operating_expenses!=null?String(o.operating_expenses):"",broker_coop_pct:o.broker_coop_pct!=null?String(o.broker_coop_pct):"",call_for_offers_at:o.call_for_offers_at?o.call_for_offers_at.slice(0,10):"",is_confidential:!!o.is_confidential,hide_address:!!o.hide_address,requires_nda:!!o.requires_nda,om_gate_mode:o.om_gate_mode??"email",opportunity_zone:!!o.opportunity_zone})),y((ue=o.investment_highlights)!=null&&ue.length?o.investment_highlights:[""]),b(o.property_highlights??[]),S((o.spaces??[]).map(ve=>({...ve,sf:(ve==null?void 0:ve.sf)!=null?String(ve.sf):""}))),E((o.tenants??[]).map(ve=>({...ve,sf:(ve==null?void 0:ve.sf)!=null?String(ve.sf):""}))),P(o.traffic_counts??[]),D(o.demographics??{}))},[o]);const J=f.deal_type==="lease"||f.deal_type==="sale_or_lease",ce=f.deal_type!=="lease",_e=j.useMemo(()=>({deal_type:f.deal_type,commercial_type:f.commercial_type,opportunity_title:f.opportunity_title||null,submarket:f.submarket||null,asking_price:gp(f.asking_price),lease_rate:gp(f.lease_rate),lease_rate_unit:f.lease_rate_unit,lease_type:f.lease_type||null,building_sf:gp(f.building_sf),available_sf:gp(f.available_sf),lot_acres:gp(f.lot_acres),units:gp(f.units),floors:gp(f.floors),parking_spaces:gp(f.parking_spaces),zoning:f.zoning||null,occupancy_pct:gp(f.occupancy_pct),tenancy:f.tenancy||null,noi:gp(f.noi),cap_rate:gp(f.cap_rate),gross_income:gp(f.gross_income),operating_expenses:gp(f.operating_expenses),broker_coop_pct:gp(f.broker_coop_pct),call_for_offers_at:f.call_for_offers_at?new Date(f.call_for_offers_at).toISOString():null,is_confidential:f.is_confidential,hide_address:f.hide_address,requires_nda:f.requires_nda,om_gate_mode:f.om_gate_mode,opportunity_zone:f.opportunity_zone,investment_highlights:x.map(ue=>ue.trim()).filter(Boolean),spaces:w.filter(ue=>Object.values(ue).some(ve=>String(ve??"").trim())),tenants:C.filter(ue=>Object.values(ue).some(ve=>String(ve??"").trim())),traffic_counts:I.filter(ue=>String(ue.road??"").trim()||String(ue.count??"").trim()),demographics:Object.fromEntries(Object.entries(R).filter(([,ue])=>Object.values(ue??{}).some(ve=>String(ve??"").trim()))),property_highlights:v.map(ue=>ue.trim()).filter(Boolean),price_per_sf:gp(f.asking_price)&&gp(f.building_sf)?Math.round(gp(f.asking_price)/gp(f.building_sf)*100)/100:null,price_per_unit:gp(f.asking_price)&&gp(f.units)?Math.round(gp(f.asking_price)/gp(f.units)):null}),[f,x,v,w,C,I,R]),he=async()=>{if(a&&!X){re.error("Only the listing agent can edit this commercial listing");return}if(!f.city||!f.state){re.error("City and state are required");return}if(!a&&!h){re.error("Choose whether you already have the assignment");return}U(!0);try{let ue=s;const ve={property_address:f.property_address||null,city:f.city,state:f.state,neighborhood:f.submarket||null,price:gp(f.asking_price)??0,property_type:"commercial",description:f.description||null,year_built:gp(f.year_built),square_footage:gp(f.building_sf)},Ee=h==="pitch",Se=Ee?{is_public:!1,allow_sharing:!1,share_with_brokerage:!1,open_to_referrals:!1,open_to_social_promotion:!1,show_on_lead_site:!1}:{is_public:f.site_only?!1:f.is_public,allow_sharing:f.site_only?!1:f.allow_sharing,share_with_brokerage:f.site_only?!1:f.share_with_brokerage,open_to_referrals:f.open_to_referrals,open_to_social_promotion:f.site_only?!1:f.open_to_social_promotion,show_on_lead_site:f.site_only?!0:f.show_on_lead_site},Le=!Ee&&(Se.is_public||Se.show_on_lead_site||Se.allow_sharing)?"active":"coming_soon";if(a&&ue)await c.mutateAsync({id:ue,...ve,...Se,...Le==="active"?{status:"active"}:{}});else{const Fe=await Z7e.from("listings").insert({...ve,...Se,agent_id:n.id,listing_class:"commercial",lifecycle_stage:Ee?"pitch":"won",status:Le}).select().single();if(Fe.error)throw Fe.error;ue=Fe.data.id,Ee&&await u.mutateAsync({listingId:ue,values:{launch_plan:z7t}})}await d.mutateAsync({listingId:ue,values:_e}),await ne(ue),re.success(a?"Commercial listing updated":"Commercial listing created"),t(`/mission-control/listings/${ue}/commercial`)}catch(ue){console.error(ue),re.error(ue.message||"Could not save listing")}finally{U(!1)}};return a&&(r||l||!i||!X)?e.jsx("div",{className:"flex min-h-[50vh] items-center justify-center",children:e.jsx(kt,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):!a&&!h?e.jsx("div",{className:"min-h-screen bg-background",children:e.jsxs("div",{className:"mx-auto max-w-4xl px-4 py-10",children:[e.jsxs($,{variant:"ghost",size:"sm",className:"-ml-2 mb-6",onClick:()=>t("/mission-control/listings/new"),children:[e.jsx(qa,{className:"mr-2 h-4 w-4"})," Back"]}),e.jsx("p",{className:"text-xs font-medium uppercase tracking-[0.2em] text-muted-foreground",children:"Commercial Launch"}),e.jsx("h1",{className:"mt-2 text-3xl font-semibold tracking-tight md:text-4xl",children:"Where are you in the deal?"}),e.jsx("p",{className:"mt-2 max-w-xl text-muted-foreground",children:"Pitch Mode keeps everything private while you compete for the assignment. Win it and the same record becomes your live Commercial Launch — nothing gets re-entered."}),e.jsxs("div",{className:"mt-8 grid gap-5 md:grid-cols-2",children:[e.jsxs("button",{onClick:()=>m("assignment"),className:"group rounded-2xl border bg-card p-7 text-left transition-all hover:-translate-y-0.5 hover:shadow-xl",children:[e.jsx(Kl,{className:"mb-4 h-6 w-6"}),e.jsx("h2",{className:"text-lg font-semibold",children:"I already have the assignment"}),e.jsx("p",{className:"mt-1 text-sm text-muted-foreground",children:"Go straight to building the launch: microsite, OM gating, investor tracking and reporting."})]}),e.jsxs("button",{onClick:()=>m("pitch"),className:"group rounded-2xl border border-primary/40 bg-gradient-to-br from-primary/[0.07] to-transparent p-7 text-left transition-all hover:-translate-y-0.5 hover:shadow-xl",children:[e.jsx(rh,{className:"mb-4 h-6 w-6 text-primary"}),e.jsx("h2",{className:"text-lg font-semibold",children:"I'm pitching this property"}),e.jsx("p",{className:"mt-1 text-sm text-muted-foreground",children:"Private Pitch Workspace with owner intel, positioning, a proposed launch plan and a seller-facing preview of exactly what happens the day they hire you."})]})]})]})}):e.jsxs("div",{className:"min-h-screen bg-background pb-28",children:[e.jsxs("div",{className:"mx-auto max-w-4xl px-4 py-8",children:[e.jsxs($,{variant:"ghost",size:"sm",className:"-ml-2 mb-6",onClick:()=>t(a?`/mission-control/listings/${s}/commercial`:"/mission-control/listings"),children:[e.jsx(qa,{className:"mr-2 h-4 w-4"})," Back"]}),e.jsxs("div",{className:"mb-8 flex items-start gap-3",children:[e.jsx("div",{className:"flex h-11 w-11 items-center justify-center rounded-xl border bg-card",children:e.jsx(ji,{className:"h-5 w-5"})}),e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-semibold tracking-tight md:text-3xl",children:a?"Edit commercial listing":h==="pitch"?"New pitch":"New commercial listing"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:h==="pitch"?"Private until you win it — never shown in the Exchange or on the public web.":"Only the fields that matter for this deal type are required."})]})]}),e.jsxs("div",{className:"space-y-6",children:[e.jsxs(Ne,{children:[e.jsxs(Ct,{children:[e.jsx(At,{className:"text-base",children:"The opportunity"}),e.jsx(Gn,{children:"How this deal is positioned to the market."})]}),e.jsxs(Ie,{className:"grid gap-4 md:grid-cols-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Deal type"}),e.jsxs(ms,{value:f.deal_type,onValueChange:ue=>te("deal_type",ue),children:[e.jsx(us,{children:e.jsx(fs,{})}),e.jsx(hs,{children:Object.entries(ML).map(([ue,ve])=>e.jsx(Ge,{value:ue,children:ve},ue))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Property type"}),e.jsxs(ms,{value:f.commercial_type,onValueChange:ue=>te("commercial_type",ue),children:[e.jsx(us,{children:e.jsx(fs,{})}),e.jsx(hs,{children:Object.entries(c6).map(([ue,ve])=>e.jsx(Ge,{value:ue,children:ve},ue))})]})]}),e.jsxs("div",{className:"space-y-2 md:col-span-2",children:[e.jsxs(ee,{children:["Opportunity name ",e.jsx("span",{className:"text-muted-foreground",children:"(optional)"})]}),e.jsx(pe,{value:f.opportunity_title,placeholder:"e.g. Gateway Logistics Center",onChange:ue=>te("opportunity_title",ue.target.value)}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Used instead of the street address on confidential offerings."})]}),e.jsxs("div",{className:"space-y-2 md:col-span-2",children:[e.jsx(ee,{children:"Property story"}),e.jsx(Rs,{rows:5,value:f.description,placeholder:"The narrative an investor, tenant or owner should read first.",onChange:ue=>te("description",ue.target.value)})]})]})]}),e.jsxs(Ne,{children:[e.jsx(Ct,{children:e.jsx(At,{className:"text-base",children:"Location"})}),e.jsxs(Ie,{className:"grid gap-4 md:grid-cols-2",children:[e.jsxs("div",{className:"space-y-2 md:col-span-2",children:[e.jsx(ee,{children:"Street address"}),e.jsx(pe,{value:f.property_address,onChange:ue=>te("property_address",ue.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"City *"}),e.jsx(pe,{value:f.city,onChange:ue=>te("city",ue.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"State *"}),e.jsx(pe,{value:f.state,maxLength:2,onChange:ue=>te("state",ue.target.value.toUpperCase())})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Submarket"}),e.jsx(pe,{value:f.submarket,placeholder:"e.g. North Loop",onChange:ue=>te("submarket",ue.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Zoning"}),e.jsx(pe,{value:f.zoning,onChange:ue=>te("zoning",ue.target.value)})]})]})]}),e.jsxs(Ne,{children:[e.jsx(Ct,{children:e.jsx(At,{className:"text-base",children:"Pricing"})}),e.jsxs(Ie,{className:"grid gap-4 md:grid-cols-2",children:[ce&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Asking price"}),e.jsx(pe,{value:f.asking_price,placeholder:"4750000",onChange:ue=>te("asking_price",ue.target.value)})]}),J&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Lease rate"}),e.jsx(pe,{value:f.lease_rate,placeholder:"24.50",onChange:ue=>te("lease_rate",ue.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Rate basis"}),e.jsxs(ms,{value:f.lease_rate_unit,onValueChange:ue=>te("lease_rate_unit",ue),children:[e.jsx(us,{children:e.jsx(fs,{})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"sf_year",children:"Per SF / year"}),e.jsx(Ge,{value:"sf_month",children:"Per SF / month"}),e.jsx(Ge,{value:"month",children:"Per month"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Lease structure"}),e.jsxs(ms,{value:f.lease_type||"none",onValueChange:ue=>te("lease_type",ue==="none"?"":ue),children:[e.jsx(us,{children:e.jsx(fs,{placeholder:"Select"})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"none",children:"Not specified"}),kDs.map(ue=>e.jsx(Ge,{value:ue,children:ue},ue))]})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Broker co-op (%)"}),e.jsx(pe,{value:f.broker_coop_pct,placeholder:"2.5",onChange:ue=>te("broker_coop_pct",ue.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Call for offers"}),e.jsx(pe,{type:"date",value:f.call_for_offers_at,onChange:ue=>te("call_for_offers_at",ue.target.value)})]})]})]}),e.jsxs(Ne,{children:[e.jsx(Ct,{children:e.jsx(At,{className:"text-base",children:"Building & site"})}),e.jsxs(Ie,{className:"grid gap-4 md:grid-cols-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Building SF"}),e.jsx(pe,{value:f.building_sf,onChange:ue=>te("building_sf",ue.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Available SF"}),e.jsx(pe,{value:f.available_sf,onChange:ue=>te("available_sf",ue.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Lot acres"}),e.jsx(pe,{value:f.lot_acres,onChange:ue=>te("lot_acres",ue.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Units"}),e.jsx(pe,{value:f.units,onChange:ue=>te("units",ue.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Floors"}),e.jsx(pe,{value:f.floors,onChange:ue=>te("floors",ue.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Parking spaces"}),e.jsx(pe,{value:f.parking_spaces,onChange:ue=>te("parking_spaces",ue.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Year built"}),e.jsx(pe,{value:f.year_built,onChange:ue=>te("year_built",ue.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Tenancy"}),e.jsxs(ms,{value:f.tenancy||"none",onValueChange:ue=>te("tenancy",ue==="none"?"":ue),children:[e.jsx(us,{children:e.jsx(fs,{placeholder:"Select"})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"none",children:"Not specified"}),e.jsx(Ge,{value:"single",children:"Single tenant"}),e.jsx(Ge,{value:"multi",children:"Multi-tenant"}),e.jsx(Ge,{value:"vacant",children:"Vacant"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Occupancy (%)"}),e.jsx(pe,{value:f.occupancy_pct,onChange:ue=>te("occupancy_pct",ue.target.value)})]})]})]}),e.jsxs(Ne,{children:[e.jsxs(Ct,{children:[e.jsx(At,{className:"text-base",children:"Investment metrics"}),e.jsx(Gn,{children:"Only what you enter is shown on the microsite."})]}),e.jsxs(Ie,{className:"grid gap-4 md:grid-cols-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"NOI"}),e.jsx(pe,{value:f.noi,onChange:ue=>te("noi",ue.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Cap rate (%)"}),e.jsx(pe,{value:f.cap_rate,onChange:ue=>te("cap_rate",ue.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Gross income"}),e.jsx(pe,{value:f.gross_income,onChange:ue=>te("gross_income",ue.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Operating expenses"}),e.jsx(pe,{value:f.operating_expenses,onChange:ue=>te("operating_expenses",ue.target.value)})]}),e.jsxs("div",{className:"flex items-center justify-between rounded-lg border p-3 md:col-span-2",children:[e.jsxs("div",{children:[e.jsx(ee,{children:"Opportunity Zone"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Highlight qualified OZ tax treatment."})]}),e.jsx(Sn,{checked:f.opportunity_zone,onCheckedChange:ue=>te("opportunity_zone",ue)})]})]})]}),e.jsxs(Ne,{children:[e.jsxs(Ct,{children:[e.jsx(At,{className:"text-base",children:"Highlights"}),e.jsx(Gn,{children:"3–6 reasons this opportunity matters. These headline the microsite."})]}),e.jsxs(Ie,{className:"space-y-6",children:[e.jsx(Jvt,{label:"Investment highlights",placeholder:"e.g. 12-year NNN lease to investment-grade tenant",items:x,onChange:y}),e.jsx(Jvt,{label:"Property highlights",placeholder:"e.g. 32' clear height, 14 dock doors",items:v,onChange:b})]})]}),e.jsxs(Ne,{children:[e.jsxs(Ct,{children:[e.jsx(At,{className:"text-base",children:"Spaces, tenants & market data"}),e.jsx(Gn,{children:"Everything here is optional — the microsite only renders the sections you fill in."})]}),e.jsxs(Ie,{className:"space-y-8",children:[e.jsx(X7e,{label:"Available spaces",description:"Suites or spaces available for lease.",columns:[{key:"suite",label:"Suite",placeholder:"Suite 200"},{key:"sf",label:"SF",placeholder:"4,200"},{key:"rate",label:"Rate",placeholder:"$28.00 NNN"},{key:"availability",label:"Availability",placeholder:"Immediate"},{key:"use",label:"Use",placeholder:"Office"}],rows:w,onChange:S}),e.jsx(X7e,{label:"Rent roll / tenants",description:"Shown on investment offerings to demonstrate income stability.",columns:[{key:"name",label:"Tenant",placeholder:"Anchor tenant"},{key:"sf",label:"SF",placeholder:"12,000"},{key:"lease_expiry",label:"Lease expiry",placeholder:"2031"},{key:"rent",label:"Rent",placeholder:"$18.50/SF"},{key:"notes",label:"Notes",placeholder:"Two 5-yr options"}],rows:C,onChange:E}),e.jsx(X7e,{label:"Traffic counts",columns:[{key:"road",label:"Road",placeholder:"US-98"},{key:"count",label:"Vehicles / day",placeholder:"42,500 VPD"}],rows:I,onChange:P}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(ee,{children:"Demographics"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"1 / 3 / 5-mile radius cards on the microsite."})]}),Uqs.map(ue=>e.jsxs("div",{className:"flex flex-wrap items-end gap-2 rounded-lg border p-3",children:[e.jsx("p",{className:"w-16 text-sm font-medium",children:ue.label}),qqs.map(ve=>{var Ee;return e.jsxs("div",{className:"min-w-[120px] flex-1 space-y-1",children:[e.jsx(ee,{className:"text-[11px] uppercase tracking-wide text-muted-foreground",children:ve.label}),e.jsx(pe,{value:((Ee=R[ue.key])==null?void 0:Ee[ve.key])??"",onChange:Se=>D({...R,[ue.key]:{...R[ue.key]??{},[ve.key]:Se.target.value}})})]},ve.key)})]},ue.key))]})]})]}),e.jsxs(Ne,{children:[e.jsxs(Ct,{children:[e.jsx(At,{className:"text-base",children:"Photography"}),e.jsx(Gn,{children:"Cinematic exterior, aerial and interior imagery drives the microsite hero and gallery."})]}),e.jsxs(Ie,{className:"space-y-3",children:[e.jsxs("label",{className:"flex cursor-pointer items-center justify-center rounded-lg border border-dashed px-4 py-8 text-sm text-muted-foreground hover:bg-muted/40",children:[e.jsx(dn,{className:"mr-2 h-4 w-4"}),"Add photos",e.jsx("input",{type:"file",accept:"image/*",multiple:!0,className:"hidden",onChange:ue=>ae(ue.target.files)})]}),G.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"grid grid-cols-3 gap-2 sm:grid-cols-4",children:G.map((ue,ve)=>e.jsxs("div",{className:"group relative aspect-[4/3] overflow-hidden rounded-md border",children:[e.jsx("img",{src:ue,alt:`Commercial photo ${ve+1}`,className:"h-full w-full object-cover"}),e.jsx("button",{type:"button",onClick:()=>ie(ve),className:"absolute right-1 top-1 rounded-full bg-background/90 p-1 opacity-0 transition group-hover:opacity-100","aria-label":"Remove photo",children:e.jsx(gr,{className:"h-3 w-3"})})]},ue))}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[G.length," photo",G.length===1?"":"s"," upload when you save."]})]})]})]}),h!=="pitch"&&e.jsxs(Ne,{children:[e.jsxs(Ct,{children:[e.jsx(At,{className:"text-base",children:"Distribution & sharing"}),e.jsx(Gn,{children:"Choose where this opportunity appears. You control the Listing Exchange, your own website, and the public commercial marketplace independently."})]}),e.jsxs(Ie,{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between rounded-lg border p-3",children:[e.jsxs("div",{children:[e.jsx(ee,{children:"My website only"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Hide from the Listing Exchange, other agents and the public marketplace."})]}),e.jsx(Sn,{checked:f.site_only,onCheckedChange:ue=>g(ve=>({...ve,site_only:ue,is_public:ue?!1:ve.is_public,show_on_lead_site:ue?!0:ve.show_on_lead_site,share_with_brokerage:ue?!1:ve.share_with_brokerage}))})]}),e.jsxs("div",{className:"flex items-center justify-between rounded-lg border p-3",children:[e.jsxs("div",{children:[e.jsx(ee,{children:"Publish publicly"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Go live on commercial.relevelup.com to capture leads."})]}),e.jsx(Sn,{checked:f.is_public,disabled:f.site_only,onCheckedChange:ue=>te("is_public",ue)})]}),e.jsxs("div",{className:"flex items-center justify-between rounded-lg border p-3",children:[e.jsxs("div",{children:[e.jsx(ee,{children:"Show on my website"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Feature it on your own lead site."})]}),e.jsx(Sn,{checked:f.show_on_lead_site,onCheckedChange:ue=>te("show_on_lead_site",ue)})]}),e.jsxs("div",{className:"flex items-center justify-between rounded-lg border p-3",children:[e.jsxs("div",{children:[e.jsx(ee,{children:"Allow sharing"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Other LevelUp agents can share it from the Exchange."})]}),e.jsx(Sn,{checked:f.allow_sharing,disabled:f.site_only,onCheckedChange:ue=>te("allow_sharing",ue)})]}),e.jsxs("div",{className:"flex items-center justify-between rounded-lg border p-3",children:[e.jsxs("div",{children:[e.jsx(ee,{children:"Share with my brokerage"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Visible to agents inside your brokerage."})]}),e.jsx(Sn,{checked:f.share_with_brokerage,disabled:f.site_only,onCheckedChange:ue=>te("share_with_brokerage",ue)})]}),e.jsxs("div",{className:"flex items-center justify-between rounded-lg border p-3",children:[e.jsxs("div",{children:[e.jsx(ee,{children:"Open to referrals"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Accept tenant / buyer referrals from other agents."})]}),e.jsx(Sn,{checked:f.open_to_referrals,onCheckedChange:ue=>te("open_to_referrals",ue)})]}),e.jsxs("div",{className:"flex items-center justify-between rounded-lg border p-3",children:[e.jsxs("div",{children:[e.jsx(ee,{children:"Social promotion"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Other agents may promote it on social media."})]}),e.jsx(Sn,{checked:f.open_to_social_promotion,disabled:f.site_only,onCheckedChange:ue=>te("open_to_social_promotion",ue)})]})]})]}),e.jsxs(Ne,{children:[e.jsx(Ct,{children:e.jsx(At,{className:"text-base",children:"Confidentiality & document gating"})}),e.jsxs(Ie,{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between rounded-lg border p-3",children:[e.jsxs("div",{children:[e.jsx(ee,{children:"Confidential offering"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Teaser presentation, no address, search engines blocked."})]}),e.jsx(Sn,{checked:f.is_confidential,onCheckedChange:ue=>te("is_confidential",ue)})]}),e.jsxs("div",{className:"flex items-center justify-between rounded-lg border p-3",children:[e.jsxs("div",{children:[e.jsx(ee,{children:"Hide street address"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Show city / submarket only."})]}),e.jsx(Sn,{checked:f.hide_address,onCheckedChange:ue=>te("hide_address",ue)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Offering Memorandum access"}),e.jsxs(ms,{value:f.om_gate_mode,onValueChange:ue=>te("om_gate_mode",ue),children:[e.jsx(us,{children:e.jsx(fs,{})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"open",children:"Open download"}),e.jsx(Ge,{value:"email",children:"Require name, email & company"}),e.jsx(Ge,{value:"nda",children:"Require confidentiality acknowledgement"})]})]})]})]})]})]})]}),e.jsx("div",{className:"fixed inset-x-0 bottom-0 border-t bg-background/95 backdrop-blur",children:e.jsxs("div",{className:"mx-auto flex max-w-4xl items-center justify-between gap-3 px-4 py-3",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:h==="pitch"?"Saved privately — nothing publishes until you win.":"Not published until you launch."}),e.jsxs($,{onClick:he,disabled:O,children:[O&&e.jsx(kt,{className:"mr-2 h-4 w-4 animate-spin"}),a?"Save changes":"Create & continue"]})]})})]})}function d6e(s){return tt({queryKey:["listing-documents",s],queryFn:async()=>{const{data:t,error:n}=await q.from("listing_documents").select("*").eq("listing_id",s).order("sort_order",{ascending:!0}).order("created_at",{ascending:!0});if(n)throw n;return t},enabled:!!s})}function K$t(){const{user:s}=vs(),t=Vt();return ft({mutationFn:async({listingId:n,file:r,docKind:a,gateLevel:i,title:l})=>{if(!(s!=null&&s.id))throw new Error("Not authenticated");const o=r.name.split(".").pop(),c=`${s.id}/${n}/${crypto.randomUUID()}.${o}`,{error:d}=await q.storage.from("listing-documents").upload(c,r,{contentType:r.type||void 0});if(d)throw d;const{data:u,error:h}=await q.from("listing_documents").insert({listing_id:n,owner_user_id:s.id,file_name:r.name,file_size:r.size,file_type:r.type||null,storage_path:c,...a?{doc_kind:a}:{},...i?{gate_level:i}:{},...l?{title:l}:{}}).select().single();if(h)throw h;return u},onSuccess:(n,r)=>{t.invalidateQueries({queryKey:["listing-documents",r.listingId]})}})}function Y$t(){const s=Vt();return ft({mutationFn:async({id:t,storage_path:n,listingId:r})=>{await q.storage.from("listing-documents").remove([n]);const{error:a}=await q.from("listing_documents").delete().eq("id",t);if(a)throw a;return r},onSuccess:t=>{s.invalidateQueries({queryKey:["listing-documents",t]})}})}function Vqs(){const s=Vt();return ft({mutationFn:async({id:t,listingId:n,values:r})=>{const{error:a}=await q.from("listing_documents").update(r).eq("id",t);if(a)throw a;return n},onSuccess:t=>{s.invalidateQueries({queryKey:["listing-documents",t]})}})}function Hqs(){const s=Vt();return ft({mutationFn:async({id:t,visible:n,listingId:r})=>{const{error:a}=await q.from("listing_documents").update({visible_on_exchange:n}).eq("id",t);if(a)throw a;return r},onSuccess:t=>{s.invalidateQueries({queryKey:["listing-documents",t]})}})}async function Jst(s){const{data:t,error:n}=await q.storage.from("listing-documents").createSignedUrl(s,3600);if(n)throw n;return t.signedUrl}function Gqs(){for(var s=arguments.length,t=new Array(s),n=0;nr=>{t.forEach(a=>a(r))},t)}const u6e=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u";function uK(s){const t=Object.prototype.toString.call(s);return t==="[object Window]"||t==="[object global]"}function ent(s){return"nodeType"in s}function Kw(s){var t,n;return s?uK(s)?s:ent(s)&&(t=(n=s.ownerDocument)==null?void 0:n.defaultView)!=null?t:window:window}function tnt(s){const{Document:t}=Kw(s);return s instanceof t}function sie(s){return uK(s)?!1:s instanceof Kw(s).HTMLElement}function Z$t(s){return s instanceof Kw(s).SVGElement}function hK(s){return s?uK(s)?s.document:ent(s)?tnt(s)?s:sie(s)||Z$t(s)?s.ownerDocument:document:document:document}const Q4=u6e?j.useLayoutEffect:j.useEffect;function snt(s){const t=j.useRef(s);return Q4(()=>{t.current=s}),j.useCallback(function(){for(var n=arguments.length,r=new Array(n),a=0;a{s.current=setInterval(r,a)},[]),n=j.useCallback(()=>{s.current!==null&&(clearInterval(s.current),s.current=null)},[]);return[t,n]}function cse(s,t){t===void 0&&(t=[s]);const n=j.useRef(s);return Q4(()=>{n.current!==s&&(n.current=s)},t),n}function nie(s,t){const n=j.useRef();return j.useMemo(()=>{const r=s(n.current);return n.current=r,r},[...t])}function KEe(s){const t=snt(s),n=j.useRef(null),r=j.useCallback(a=>{a!==n.current&&(t==null||t(a,n.current)),n.current=a},[]);return[n,r]}function $Ge(s){const t=j.useRef();return j.useEffect(()=>{t.current=s},[s]),t.current}let Q7e={};function rie(s,t){return j.useMemo(()=>{if(t)return t;const n=Q7e[s]==null?0:Q7e[s]+1;return Q7e[s]=n,s+"-"+n},[s,t])}function X$t(s){return function(t){for(var n=arguments.length,r=new Array(n>1?n-1:0),a=1;a{const o=Object.entries(l);for(const[c,d]of o){const u=i[c];u!=null&&(i[c]=u+s*d)}return i},{...t})}}const SV=X$t(1),dse=X$t(-1);function Kqs(s){return"clientX"in s&&"clientY"in s}function nnt(s){if(!s)return!1;const{KeyboardEvent:t}=Kw(s.target);return t&&s instanceof t}function Yqs(s){if(!s)return!1;const{TouchEvent:t}=Kw(s.target);return t&&s instanceof t}function UGe(s){if(Yqs(s)){if(s.touches&&s.touches.length){const{clientX:t,clientY:n}=s.touches[0];return{x:t,y:n}}else if(s.changedTouches&&s.changedTouches.length){const{clientX:t,clientY:n}=s.changedTouches[0];return{x:t,y:n}}}return Kqs(s)?{x:s.clientX,y:s.clientY}:null}const RL=Object.freeze({Translate:{toString(s){if(!s)return;const{x:t,y:n}=s;return"translate3d("+(t?Math.round(t):0)+"px, "+(n?Math.round(n):0)+"px, 0)"}},Scale:{toString(s){if(!s)return;const{scaleX:t,scaleY:n}=s;return"scaleX("+t+") scaleY("+n+")"}},Transform:{toString(s){if(s)return[RL.Translate.toString(s),RL.Scale.toString(s)].join(" ")}},Transition:{toString(s){let{property:t,duration:n,easing:r}=s;return t+" "+n+"ms "+r}}}),tbt="a,frame,iframe,input:not([type=hidden]):not(:disabled),select:not(:disabled),textarea:not(:disabled),button:not(:disabled),*[tabindex]";function Zqs(s){return s.matches(tbt)?s:s.querySelector(tbt)}const Xqs={display:"none"};function Qqs(s){let{id:t,value:n}=s;return Gt.createElement("div",{id:t,style:Xqs},n)}function Jqs(s){let{id:t,announcement:n,ariaLiveType:r="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 Gt.createElement("div",{id:t,style:a,role:"status","aria-live":r,"aria-atomic":!0},n)}function eVs(){const[s,t]=j.useState("");return{announce:j.useCallback(r=>{r!=null&&t(r)},[]),announcement:s}}const Q$t=j.createContext(null);function tVs(s){const t=j.useContext(Q$t);j.useEffect(()=>{if(!t)throw new Error("useDndMonitor must be used within a children of ");return t(s)},[s,t])}function sVs(){const[s]=j.useState(()=>new Set),t=j.useCallback(r=>(s.add(r),()=>s.delete(r)),[s]);return[j.useCallback(r=>{let{type:a,event:i}=r;s.forEach(l=>{var o;return(o=l[a])==null?void 0:o.call(l,i)})},[s]),t]}const nVs={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. `},rVs={onDragStart(s){let{active:t}=s;return"Picked up draggable item "+t.id+"."},onDragOver(s){let{active:t,over:n}=s;return n?"Draggable item "+t.id+" was moved over droppable area "+n.id+".":"Draggable item "+t.id+" is no longer over a droppable area."},onDragEnd(s){let{active:t,over:n}=s;return n?"Draggable item "+t.id+" was dropped over droppable area "+n.id:"Draggable item "+t.id+" was dropped."},onDragCancel(s){let{active:t}=s;return"Dragging was cancelled. Draggable item "+t.id+" was dropped."}};function aVs(s){let{announcements:t=rVs,container:n,hiddenTextDescribedById:r,screenReaderInstructions:a=nVs}=s;const{announce:i,announcement:l}=eVs(),o=rie("DndLiveRegion"),[c,d]=j.useState(!1);if(j.useEffect(()=>{d(!0)},[]),tVs(j.useMemo(()=>({onDragStart(h){let{active:m}=h;i(t.onDragStart({active:m}))},onDragMove(h){let{active:m,over:f}=h;t.onDragMove&&i(t.onDragMove({active:m,over:f}))},onDragOver(h){let{active:m,over:f}=h;i(t.onDragOver({active:m,over:f}))},onDragEnd(h){let{active:m,over:f}=h;i(t.onDragEnd({active:m,over:f}))},onDragCancel(h){let{active:m,over:f}=h;i(t.onDragCancel({active:m,over:f}))}}),[i,t])),!c)return null;const u=Gt.createElement(Gt.Fragment,null,Gt.createElement(Qqs,{id:r,value:a.draggable}),Gt.createElement(Jqs,{id:o,announcement:l}));return n?wv.createPortal(u,n):u}var x0;(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"})(x0||(x0={}));function YEe(){}function IG(s,t){return j.useMemo(()=>({sensor:s,options:t??{}}),[s,t])}function h6e(){for(var s=arguments.length,t=new Array(s),n=0;n[...t].filter(r=>r!=null),[...t])}const gC=Object.freeze({x:0,y:0});function J$t(s,t){return Math.sqrt(Math.pow(s.x-t.x,2)+Math.pow(s.y-t.y,2))}function eUt(s,t){let{data:{value:n}}=s,{data:{value:r}}=t;return n-r}function iVs(s,t){let{data:{value:n}}=s,{data:{value:r}}=t;return r-n}function sbt(s){let{left:t,top:n,height:r,width:a}=s;return[{x:t,y:n},{x:t+a,y:n},{x:t,y:n+r},{x:t+a,y:n+r}]}function tUt(s,t){if(!s||s.length===0)return null;const[n]=s;return n[t]}function nbt(s,t,n){return t===void 0&&(t=s.left),n===void 0&&(n=s.top),{x:t+s.width*.5,y:n+s.height*.5}}const m6e=s=>{let{collisionRect:t,droppableRects:n,droppableContainers:r}=s;const a=nbt(t,t.left,t.top),i=[];for(const l of r){const{id:o}=l,c=n.get(o);if(c){const d=J$t(nbt(c),a);i.push({id:o,data:{droppableContainer:l,value:d}})}}return i.sort(eUt)},oVs=s=>{let{collisionRect:t,droppableRects:n,droppableContainers:r}=s;const a=sbt(t),i=[];for(const l of r){const{id:o}=l,c=n.get(o);if(c){const d=sbt(c),u=a.reduce((m,f,g)=>m+J$t(d[g],f),0),h=Number((u/4).toFixed(4));i.push({id:o,data:{droppableContainer:l,value:h}})}}return i.sort(eUt)};function lVs(s,t){const n=Math.max(t.top,s.top),r=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-r,o=i-n;if(r{let{collisionRect:t,droppableRects:n,droppableContainers:r}=s;const a=[];for(const i of r){const{id:l}=i,o=n.get(l);if(o){const c=lVs(o,t);c>0&&a.push({id:l,data:{droppableContainer:i,value:c}})}}return a.sort(iVs)};function dVs(s,t,n){return{...s,scaleX:t&&n?t.width/n.width:1,scaleY:t&&n?t.height/n.height:1}}function sUt(s,t){return s&&t?{x:s.left-t.left,y:s.top-t.top}:gC}function uVs(s){return function(n){for(var r=arguments.length,a=new Array(r>1?r-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}),{...n})}}const hVs=uVs(1);function mVs(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 fVs(s,t,n){const r=mVs(t);if(!r)return s;const{scaleX:a,scaleY:i,x:l,y:o}=r,c=s.left-l-(1-a)*parseFloat(n),d=s.top-o-(1-i)*parseFloat(n.slice(n.indexOf(" ")+1)),u=a?s.width/a:s.width,h=i?s.height/i:s.height;return{width:u,height:h,top:d,right:c+u,bottom:d+h,left:c}}const pVs={ignoreTransform:!1};function mK(s,t){t===void 0&&(t=pVs);let n=s.getBoundingClientRect();if(t.ignoreTransform){const{transform:d,transformOrigin:u}=Kw(s).getComputedStyle(s);d&&(n=fVs(n,d,u))}const{top:r,left:a,width:i,height:l,bottom:o,right:c}=n;return{top:r,left:a,width:i,height:l,bottom:o,right:c}}function rbt(s){return mK(s,{ignoreTransform:!0})}function gVs(s){const t=s.innerWidth,n=s.innerHeight;return{top:0,left:0,right:t,bottom:n,width:t,height:n}}function xVs(s,t){return t===void 0&&(t=Kw(s).getComputedStyle(s)),t.position==="fixed"}function yVs(s,t){t===void 0&&(t=Kw(s).getComputedStyle(s));const n=/(auto|scroll|overlay)/;return["overflow","overflowX","overflowY"].some(a=>{const i=t[a];return typeof i=="string"?n.test(i):!1})}function f6e(s,t){const n=[];function r(a){if(t!=null&&n.length>=t||!a)return n;if(tnt(a)&&a.scrollingElement!=null&&!n.includes(a.scrollingElement))return n.push(a.scrollingElement),n;if(!sie(a)||Z$t(a)||n.includes(a))return n;const i=Kw(s).getComputedStyle(a);return a!==s&&yVs(a,i)&&n.push(a),xVs(a,i)?n:r(a.parentNode)}return s?r(s):n}function nUt(s){const[t]=f6e(s,1);return t??null}function J7e(s){return!u6e||!s?null:uK(s)?s:ent(s)?tnt(s)||s===hK(s).scrollingElement?window:sie(s)?s:null:null}function rUt(s){return uK(s)?s.scrollX:s.scrollLeft}function aUt(s){return uK(s)?s.scrollY:s.scrollTop}function qGe(s){return{x:rUt(s),y:aUt(s)}}var fv;(function(s){s[s.Forward=1]="Forward",s[s.Backward=-1]="Backward"})(fv||(fv={}));function iUt(s){return!u6e||!s?!1:s===document.scrollingElement}function oUt(s){const t={x:0,y:0},n=iUt(s)?{height:window.innerHeight,width:window.innerWidth}:{height:s.clientHeight,width:s.clientWidth},r={x:s.scrollWidth-n.width,y:s.scrollHeight-n.height},a=s.scrollTop<=t.y,i=s.scrollLeft<=t.x,l=s.scrollTop>=r.y,o=s.scrollLeft>=r.x;return{isTop:a,isLeft:i,isBottom:l,isRight:o,maxScroll:r,minScroll:t}}const vVs={x:.2,y:.2};function bVs(s,t,n,r,a){let{top:i,left:l,right:o,bottom:c}=n;r===void 0&&(r=10),a===void 0&&(a=vVs);const{isTop:d,isBottom:u,isLeft:h,isRight:m}=oUt(s),f={x:0,y:0},g={x:0,y:0},x={height:t.height*a.y,width:t.width*a.x};return!d&&i<=t.top+x.height?(f.y=fv.Backward,g.y=r*Math.abs((t.top+x.height-i)/x.height)):!u&&c>=t.bottom-x.height&&(f.y=fv.Forward,g.y=r*Math.abs((t.bottom-x.height-c)/x.height)),!m&&o>=t.right-x.width?(f.x=fv.Forward,g.x=r*Math.abs((t.right-x.width-o)/x.width)):!h&&l<=t.left+x.width&&(f.x=fv.Backward,g.x=r*Math.abs((t.left+x.width-l)/x.width)),{direction:f,speed:g}}function _Vs(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:n,right:r,bottom:a}=s.getBoundingClientRect();return{top:t,left:n,right:r,bottom:a,width:s.clientWidth,height:s.clientHeight}}function lUt(s){return s.reduce((t,n)=>SV(t,qGe(n)),gC)}function wVs(s){return s.reduce((t,n)=>t+rUt(n),0)}function jVs(s){return s.reduce((t,n)=>t+aUt(n),0)}function NVs(s,t){if(t===void 0&&(t=mK),!s)return;const{top:n,left:r,bottom:a,right:i}=t(s);nUt(s)&&(a<=0||i<=0||n>=window.innerHeight||r>=window.innerWidth)&&s.scrollIntoView({block:"center",inline:"center"})}const kVs=[["x",["left","right"],wVs],["y",["top","bottom"],jVs]];let rnt=class{constructor(t,n){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 r=f6e(n),a=lUt(r);this.rect={...t},this.width=t.width,this.height=t.height;for(const[i,l,o]of kVs)for(const c of l)Object.defineProperty(this,c,{get:()=>{const d=o(r),u=a[i]-d;return this.rect[c]+u},enumerable:!0});Object.defineProperty(this,"rect",{enumerable:!1})}};class kee{constructor(t){this.target=void 0,this.listeners=[],this.removeAll=()=>{this.listeners.forEach(n=>{var r;return(r=this.target)==null?void 0:r.removeEventListener(...n)})},this.target=t}add(t,n,r){var a;(a=this.target)==null||a.addEventListener(t,n,r),this.listeners.push([t,n,r])}}function SVs(s){const{EventTarget:t}=Kw(s);return s instanceof t?s:hK(s)}function eBe(s,t){const n=Math.abs(s.x),r=Math.abs(s.y);return typeof t=="number"?Math.sqrt(n**2+r**2)>t:"x"in t&&"y"in t?n>t.x&&r>t.y:"x"in t?n>t.x:"y"in t?r>t.y:!1}var EN;(function(s){s.Click="click",s.DragStart="dragstart",s.Keydown="keydown",s.ContextMenu="contextmenu",s.Resize="resize",s.SelectionChange="selectionchange",s.VisibilityChange="visibilitychange"})(EN||(EN={}));function abt(s){s.preventDefault()}function CVs(s){s.stopPropagation()}var Qu;(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"})(Qu||(Qu={}));const cUt={start:[Qu.Space,Qu.Enter],cancel:[Qu.Esc],end:[Qu.Space,Qu.Enter,Qu.Tab]},AVs=(s,t)=>{let{currentCoordinates:n}=t;switch(s.code){case Qu.Right:return{...n,x:n.x+25};case Qu.Left:return{...n,x:n.x-25};case Qu.Down:return{...n,y:n.y+25};case Qu.Up:return{...n,y:n.y-25}}};class p6e{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:n}}=t;this.props=t,this.listeners=new kee(hK(n)),this.windowListeners=new kee(Kw(n)),this.handleKeyDown=this.handleKeyDown.bind(this),this.handleCancel=this.handleCancel.bind(this),this.attach()}attach(){this.handleStart(),this.windowListeners.add(EN.Resize,this.handleCancel),this.windowListeners.add(EN.VisibilityChange,this.handleCancel),setTimeout(()=>this.listeners.add(EN.Keydown,this.handleKeyDown))}handleStart(){const{activeNode:t,onStart:n}=this.props,r=t.node.current;r&&NVs(r),n(gC)}handleKeyDown(t){if(nnt(t)){const{active:n,context:r,options:a}=this.props,{keyboardCodes:i=cUt,coordinateGetter:l=AVs,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}=r.current,u=d?{x:d.left,y:d.top}:gC;this.referenceCoordinates||(this.referenceCoordinates=u);const h=l(t,{active:n,context:r.current,currentCoordinates:u});if(h){const m=dse(h,u),f={x:0,y:0},{scrollableAncestors:g}=r.current;for(const x of g){const y=t.code,{isTop:v,isRight:b,isLeft:w,isBottom:S,maxScroll:C,minScroll:E}=oUt(x),I=_Vs(x),P={x:Math.min(y===Qu.Right?I.right-I.width/2:I.right,Math.max(y===Qu.Right?I.left:I.left+I.width/2,h.x)),y:Math.min(y===Qu.Down?I.bottom-I.height/2:I.bottom,Math.max(y===Qu.Down?I.top:I.top+I.height/2,h.y))},R=y===Qu.Right&&!b||y===Qu.Left&&!w,D=y===Qu.Down&&!S||y===Qu.Up&&!v;if(R&&P.x!==h.x){const O=x.scrollLeft+m.x,U=y===Qu.Right&&O<=C.x||y===Qu.Left&&O>=E.x;if(U&&!m.y){x.scrollTo({left:O,behavior:o});return}U?f.x=x.scrollLeft-O:f.x=y===Qu.Right?x.scrollLeft-C.x:x.scrollLeft-E.x,f.x&&x.scrollBy({left:-f.x,behavior:o});break}else if(D&&P.y!==h.y){const O=x.scrollTop+m.y,U=y===Qu.Down&&O<=C.y||y===Qu.Up&&O>=E.y;if(U&&!m.x){x.scrollTo({top:O,behavior:o});return}U?f.y=x.scrollTop-O:f.y=y===Qu.Down?x.scrollTop-C.y:x.scrollTop-E.y,f.y&&x.scrollBy({top:-f.y,behavior:o});break}}this.handleMove(t,SV(dse(h,this.referenceCoordinates),f))}}}handleMove(t,n){const{onMove:r}=this.props;t.preventDefault(),r(n)}handleEnd(t){const{onEnd:n}=this.props;t.preventDefault(),this.detach(),n()}handleCancel(t){const{onCancel:n}=this.props;t.preventDefault(),this.detach(),n()}detach(){this.listeners.removeAll(),this.windowListeners.removeAll()}}p6e.activators=[{eventName:"onKeyDown",handler:(s,t,n)=>{let{keyboardCodes:r=cUt,onActivation:a}=t,{active:i}=n;const{code:l}=s.nativeEvent;if(r.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 ibt(s){return!!(s&&"distance"in s)}function obt(s){return!!(s&&"delay"in s)}class ant{constructor(t,n,r){var a;r===void 0&&(r=SVs(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=n;const{event:i}=t,{target:l}=i;this.props=t,this.events=n,this.document=hK(l),this.documentListeners=new kee(this.document),this.listeners=new kee(r),this.windowListeners=new kee(Kw(l)),this.initialCoordinates=(a=UGe(i))!=null?a:gC,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:n,bypassActivationConstraint:r}}}=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(EN.Resize,this.handleCancel),this.windowListeners.add(EN.DragStart,abt),this.windowListeners.add(EN.VisibilityChange,this.handleCancel),this.windowListeners.add(EN.ContextMenu,abt),this.documentListeners.add(EN.Keydown,this.handleKeydown),n){if(r!=null&&r({event:this.props.event,activeNode:this.props.activeNode,options:this.props.options}))return this.handleStart();if(obt(n)){this.timeoutId=setTimeout(this.handleStart,n.delay),this.handlePending(n);return}if(ibt(n)){this.handlePending(n);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,n){const{active:r,onPending:a}=this.props;a(r,t,this.initialCoordinates,n)}handleStart(){const{initialCoordinates:t}=this,{onStart:n}=this.props;t&&(this.activated=!0,this.documentListeners.add(EN.Click,CVs,{capture:!0}),this.removeTextSelection(),this.documentListeners.add(EN.SelectionChange,this.removeTextSelection),n(t))}handleMove(t){var n;const{activated:r,initialCoordinates:a,props:i}=this,{onMove:l,options:{activationConstraint:o}}=i;if(!a)return;const c=(n=UGe(t))!=null?n:gC,d=dse(a,c);if(!r&&o){if(ibt(o)){if(o.tolerance!=null&&eBe(d,o.tolerance))return this.handleCancel();if(eBe(d,o.distance))return this.handleStart()}if(obt(o)&&eBe(d,o.tolerance))return this.handleCancel();this.handlePending(o,d);return}t.cancelable&&t.preventDefault(),l(c)}handleEnd(){const{onAbort:t,onEnd:n}=this.props;this.detach(),this.activated||t(this.props.active),n()}handleCancel(){const{onAbort:t,onCancel:n}=this.props;this.detach(),this.activated||t(this.props.active),n()}handleKeydown(t){t.code===Qu.Esc&&this.handleCancel()}removeTextSelection(){var t;(t=this.document.getSelection())==null||t.removeAllRanges()}}const EVs={cancel:{name:"pointercancel"},move:{name:"pointermove"},end:{name:"pointerup"}};class fK extends ant{constructor(t){const{event:n}=t,r=hK(n.target);super(t,EVs,r)}}fK.activators=[{eventName:"onPointerDown",handler:(s,t)=>{let{nativeEvent:n}=s,{onActivation:r}=t;return!n.isPrimary||n.button!==0?!1:(r==null||r({event:n}),!0)}}];const TVs={move:{name:"mousemove"},end:{name:"mouseup"}};var VGe;(function(s){s[s.RightClick=2]="RightClick"})(VGe||(VGe={}));class MVs extends ant{constructor(t){super(t,TVs,hK(t.event.target))}}MVs.activators=[{eventName:"onMouseDown",handler:(s,t)=>{let{nativeEvent:n}=s,{onActivation:r}=t;return n.button===VGe.RightClick?!1:(r==null||r({event:n}),!0)}}];const tBe={cancel:{name:"touchcancel"},move:{name:"touchmove"},end:{name:"touchend"}};class PVs extends ant{constructor(t){super(t,tBe)}static setup(){return window.addEventListener(tBe.move.name,t,{capture:!1,passive:!1}),function(){window.removeEventListener(tBe.move.name,t)};function t(){}}}PVs.activators=[{eventName:"onTouchStart",handler:(s,t)=>{let{nativeEvent:n}=s,{onActivation:r}=t;const{touches:a}=n;return a.length>1?!1:(r==null||r({event:n}),!0)}}];var See;(function(s){s[s.Pointer=0]="Pointer",s[s.DraggableRect=1]="DraggableRect"})(See||(See={}));var ZEe;(function(s){s[s.TreeOrder=0]="TreeOrder",s[s.ReversedTreeOrder=1]="ReversedTreeOrder"})(ZEe||(ZEe={}));function IVs(s){let{acceleration:t,activator:n=See.Pointer,canScroll:r,draggingRect:a,enabled:i,interval:l=5,order:o=ZEe.TreeOrder,pointerCoordinates:c,scrollableAncestors:d,scrollableAncestorRects:u,delta:h,threshold:m}=s;const f=RVs({delta:h,disabled:!i}),[g,x]=Wqs(),y=j.useRef({x:0,y:0}),v=j.useRef({x:0,y:0}),b=j.useMemo(()=>{switch(n){case See.Pointer:return c?{top:c.y,bottom:c.y,left:c.x,right:c.x}:null;case See.DraggableRect:return a}},[n,a,c]),w=j.useRef(null),S=j.useCallback(()=>{const E=w.current;if(!E)return;const I=y.current.x*v.current.x,P=y.current.y*v.current.y;E.scrollBy(I,P)},[]),C=j.useMemo(()=>o===ZEe.TreeOrder?[...d].reverse():d,[o,d]);j.useEffect(()=>{if(!i||!d.length||!b){x();return}for(const E of C){if((r==null?void 0:r(E))===!1)continue;const I=d.indexOf(E),P=u[I];if(!P)continue;const{direction:R,speed:D}=bVs(E,P,b,t,m);for(const O of["x","y"])f[O][R[O]]||(D[O]=0,R[O]=0);if(D.x>0||D.y>0){x(),w.current=E,g(S,l),y.current=D,v.current=R;return}}y.current={x:0,y:0},v.current={x:0,y:0},x()},[t,S,r,x,i,l,JSON.stringify(b),JSON.stringify(f),g,d,C,u,JSON.stringify(m)])}const LVs={x:{[fv.Backward]:!1,[fv.Forward]:!1},y:{[fv.Backward]:!1,[fv.Forward]:!1}};function RVs(s){let{delta:t,disabled:n}=s;const r=$Ge(t);return nie(a=>{if(n||!r||!a)return LVs;const i={x:Math.sign(t.x-r.x),y:Math.sign(t.y-r.y)};return{x:{[fv.Backward]:a.x[fv.Backward]||i.x===-1,[fv.Forward]:a.x[fv.Forward]||i.x===1},y:{[fv.Backward]:a.y[fv.Backward]||i.y===-1,[fv.Forward]:a.y[fv.Forward]||i.y===1}}},[n,t,r])}function DVs(s,t){const n=t!=null?s.get(t):void 0,r=n?n.node.current:null;return nie(a=>{var i;return t==null?null:(i=r??a)!=null?i:null},[r,t])}function FVs(s,t){return j.useMemo(()=>s.reduce((n,r)=>{const{sensor:a}=r,i=a.activators.map(l=>({eventName:l.eventName,handler:t(l.handler,r)}));return[...n,...i]},[]),[s,t])}var use;(function(s){s[s.Always=0]="Always",s[s.BeforeDragging=1]="BeforeDragging",s[s.WhileDragging=2]="WhileDragging"})(use||(use={}));var HGe;(function(s){s.Optimized="optimized"})(HGe||(HGe={}));const lbt=new Map;function OVs(s,t){let{dragging:n,dependencies:r,config:a}=t;const[i,l]=j.useState(null),{frequency:o,measure:c,strategy:d}=a,u=j.useRef(s),h=y(),m=cse(h),f=j.useCallback(function(v){v===void 0&&(v=[]),!m.current&&l(b=>b===null?v:b.concat(v.filter(w=>!b.includes(w))))},[m]),g=j.useRef(null),x=nie(v=>{if(h&&!n)return lbt;if(!v||v===lbt||u.current!==s||i!=null){const b=new Map;for(let w of s){if(!w)continue;if(i&&i.length>0&&!i.includes(w.id)&&w.rect.current){b.set(w.id,w.rect.current);continue}const S=w.node.current,C=S?new rnt(c(S),S):null;w.rect.current=C,C&&b.set(w.id,C)}return b}return v},[s,i,n,h,c]);return j.useEffect(()=>{u.current=s},[s]),j.useEffect(()=>{h||f()},[n,h]),j.useEffect(()=>{i&&i.length>0&&l(null)},[JSON.stringify(i)]),j.useEffect(()=>{h||typeof o!="number"||g.current!==null||(g.current=setTimeout(()=>{f(),g.current=null},o))},[o,h,f,...r]),{droppableRects:x,measureDroppableContainers:f,measuringScheduled:i!=null};function y(){switch(d){case use.Always:return!1;case use.BeforeDragging:return n;default:return!n}}}function dUt(s,t){return nie(n=>s?n||(typeof t=="function"?t(s):s):null,[t,s])}function zVs(s,t){return dUt(s,t)}function BVs(s){let{callback:t,disabled:n}=s;const r=snt(t),a=j.useMemo(()=>{if(n||typeof window>"u"||typeof window.MutationObserver>"u")return;const{MutationObserver:i}=window;return new i(r)},[r,n]);return j.useEffect(()=>()=>a==null?void 0:a.disconnect(),[a]),a}function g6e(s){let{callback:t,disabled:n}=s;const r=snt(t),a=j.useMemo(()=>{if(n||typeof window>"u"||typeof window.ResizeObserver>"u")return;const{ResizeObserver:i}=window;return new i(r)},[n]);return j.useEffect(()=>()=>a==null?void 0:a.disconnect(),[a]),a}function $Vs(s){return new rnt(mK(s),s)}function cbt(s,t,n){t===void 0&&(t=$Vs);const[r,a]=j.useState(null);function i(){a(c=>{if(!s)return null;if(s.isConnected===!1){var d;return(d=c??n)!=null?d:null}const u=t(s);return JSON.stringify(c)===JSON.stringify(u)?c:u})}const l=BVs({callback(c){if(s)for(const d of c){const{type:u,target:h}=d;if(u==="childList"&&h instanceof HTMLElement&&h.contains(s)){i();break}}}}),o=g6e({callback:i});return Q4(()=>{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]),r}function UVs(s){const t=dUt(s);return sUt(s,t)}const dbt=[];function qVs(s){const t=j.useRef(s),n=nie(r=>s?r&&r!==dbt&&s&&t.current&&s.parentNode===t.current.parentNode?r:f6e(s):dbt,[s]);return j.useEffect(()=>{t.current=s},[s]),n}function VVs(s){const[t,n]=j.useState(null),r=j.useRef(s),a=j.useCallback(i=>{const l=J7e(i.target);l&&n(o=>o?(o.set(l,qGe(l)),new Map(o)):null)},[]);return j.useEffect(()=>{const i=r.current;if(s!==i){l(i);const o=s.map(c=>{const d=J7e(c);return d?(d.addEventListener("scroll",a,{passive:!0}),[d,qGe(d)]):null}).filter(c=>c!=null);n(o.length?new Map(o):null),r.current=s}return()=>{l(s),l(i)};function l(o){o.forEach(c=>{const d=J7e(c);d==null||d.removeEventListener("scroll",a)})}},[a,s]),j.useMemo(()=>s.length?t?Array.from(t.values()).reduce((i,l)=>SV(i,l),gC):lUt(s):gC,[s,t])}function ubt(s,t){t===void 0&&(t=[]);const n=j.useRef(null);return j.useEffect(()=>{n.current=null},t),j.useEffect(()=>{const r=s!==gC;r&&!n.current&&(n.current=s),!r&&n.current&&(n.current=null)},[s]),n.current?dse(s,n.current):gC}function HVs(s){j.useEffect(()=>{if(!u6e)return;const t=s.map(n=>{let{sensor:r}=n;return r.setup==null?void 0:r.setup()});return()=>{for(const n of t)n==null||n()}},s.map(t=>{let{sensor:n}=t;return n}))}function GVs(s,t){return j.useMemo(()=>s.reduce((n,r)=>{let{eventName:a,handler:i}=r;return n[a]=l=>{i(l,t)},n},{}),[s,t])}function uUt(s){return j.useMemo(()=>s?gVs(s):null,[s])}const hbt=[];function WVs(s,t){t===void 0&&(t=mK);const[n]=s,r=uUt(n?Kw(n):null),[a,i]=j.useState(hbt);function l(){i(()=>s.length?s.map(c=>iUt(c)?r:new rnt(t(c),c)):hbt)}const o=g6e({callback:l});return Q4(()=>{o==null||o.disconnect(),l(),s.forEach(c=>o==null?void 0:o.observe(c))},[s]),a}function KVs(s){if(!s)return null;if(s.children.length>1)return s;const t=s.children[0];return sie(t)?t:s}function YVs(s){let{measure:t}=s;const[n,r]=j.useState(null),a=j.useCallback(d=>{for(const{target:u}of d)if(sie(u)){r(h=>{const m=t(u);return h?{...h,width:m.width,height:m.height}:m});break}},[t]),i=g6e({callback:a}),l=j.useCallback(d=>{const u=KVs(d);i==null||i.disconnect(),u&&(i==null||i.observe(u)),r(u?t(u):null)},[t,i]),[o,c]=KEe(l);return j.useMemo(()=>({nodeRef:o,rect:n,setRef:c}),[n,o,c])}const ZVs=[{sensor:fK,options:{}},{sensor:p6e,options:{}}],XVs={current:{}},h3e={draggable:{measure:rbt},droppable:{measure:rbt,strategy:use.WhileDragging,frequency:HGe.Optimized},dragOverlay:{measure:mK}};class Cee extends Map{get(t){var n;return t!=null&&(n=super.get(t))!=null?n:void 0}toArray(){return Array.from(this.values())}getEnabled(){return this.toArray().filter(t=>{let{disabled:n}=t;return!n})}getNodeFor(t){var n,r;return(n=(r=this.get(t))==null?void 0:r.node.current)!=null?n:void 0}}const QVs={activatorEvent:null,active:null,activeNode:null,activeNodeRect:null,collisions:null,containerNodeRect:null,draggableNodes:new Map,droppableRects:new Map,droppableContainers:new Cee,over:null,dragOverlay:{nodeRef:{current:null},rect:null,setRef:YEe},scrollableAncestors:[],scrollableAncestorRects:[],measuringConfiguration:h3e,measureDroppableContainers:YEe,windowRect:null,measuringScheduled:!1},JVs={activatorEvent:null,activators:[],active:null,activeNodeRect:null,ariaDescribedById:{draggable:""},dispatch:YEe,draggableNodes:new Map,over:null,measureDroppableContainers:YEe},x6e=j.createContext(JVs),hUt=j.createContext(QVs);function eHs(){return{draggable:{active:null,initialCoordinates:{x:0,y:0},nodes:new Map,translate:{x:0,y:0}},droppable:{containers:new Cee}}}function tHs(s,t){switch(t.type){case x0.DragStart:return{...s,draggable:{...s.draggable,initialCoordinates:t.initialCoordinates,active:t.active}};case x0.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 x0.DragEnd:case x0.DragCancel:return{...s,draggable:{...s.draggable,active:null,initialCoordinates:{x:0,y:0},translate:{x:0,y:0}}};case x0.RegisterDroppable:{const{element:n}=t,{id:r}=n,a=new Cee(s.droppable.containers);return a.set(r,n),{...s,droppable:{...s.droppable,containers:a}}}case x0.SetDroppableDisabled:{const{id:n,key:r,disabled:a}=t,i=s.droppable.containers.get(n);if(!i||r!==i.key)return s;const l=new Cee(s.droppable.containers);return l.set(n,{...i,disabled:a}),{...s,droppable:{...s.droppable,containers:l}}}case x0.UnregisterDroppable:{const{id:n,key:r}=t,a=s.droppable.containers.get(n);if(!a||r!==a.key)return s;const i=new Cee(s.droppable.containers);return i.delete(n),{...s,droppable:{...s.droppable,containers:i}}}default:return s}}function sHs(s){let{disabled:t}=s;const{active:n,activatorEvent:r,draggableNodes:a}=j.useContext(x6e),i=$Ge(r),l=$Ge(n==null?void 0:n.id);return j.useEffect(()=>{if(!t&&!r&&i&&l!=null){if(!nnt(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 u of[c.current,d.current]){if(!u)continue;const h=Zqs(u);if(h){h.focus();break}}})}},[r,t,a,l,i]),null}function nHs(s,t){let{transform:n,...r}=t;return s!=null&&s.length?s.reduce((a,i)=>i({transform:a,...r}),n):n}function rHs(s){return j.useMemo(()=>({draggable:{...h3e.draggable,...s==null?void 0:s.draggable},droppable:{...h3e.droppable,...s==null?void 0:s.droppable},dragOverlay:{...h3e.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 aHs(s){let{activeNode:t,measure:n,initialRect:r,config:a=!0}=s;const i=j.useRef(!1),{x:l,y:o}=typeof a=="boolean"?{x:a,y:a}:a;Q4(()=>{if(!l&&!o||!t){i.current=!1;return}if(i.current||!r)return;const d=t==null?void 0:t.node.current;if(!d||d.isConnected===!1)return;const u=n(d),h=sUt(u,r);if(l||(h.x=0),o||(h.y=0),i.current=!0,Math.abs(h.x)>0||Math.abs(h.y)>0){const m=nUt(d);m&&m.scrollBy({top:h.y,left:h.x})}},[t,l,o,r,n])}const mUt=j.createContext({...gC,scaleX:1,scaleY:1});var mP;(function(s){s[s.Uninitialized=0]="Uninitialized",s[s.Initializing=1]="Initializing",s[s.Initialized=2]="Initialized"})(mP||(mP={}));const y6e=j.memo(function(t){var n,r,a,i;let{id:l,accessibility:o,autoScroll:c=!0,children:d,sensors:u=ZVs,collisionDetection:h=cVs,measuring:m,modifiers:f,...g}=t;const x=j.useReducer(tHs,void 0,eHs),[y,v]=x,[b,w]=sVs(),[S,C]=j.useState(mP.Uninitialized),E=S===mP.Initialized,{draggable:{active:I,nodes:P,translate:R},droppable:{containers:D}}=y,O=I!=null?P.get(I):null,U=j.useRef({initial:null,translated:null}),W=j.useMemo(()=>{var cs;return I!=null?{id:I,data:(cs=O==null?void 0:O.data)!=null?cs:XVs,rect:U}:null},[I,O]),V=j.useRef(null),[G,Y]=j.useState(null),[X,ae]=j.useState(null),ie=cse(g,Object.values(g)),ne=rie("DndDescribedBy",l),te=j.useMemo(()=>D.getEnabled(),[D]),J=rHs(m),{droppableRects:ce,measureDroppableContainers:_e,measuringScheduled:he}=OVs(te,{dragging:E,dependencies:[R.x,R.y],config:J.droppable}),ue=DVs(P,I),ve=j.useMemo(()=>X?UGe(X):null,[X]),Ee=Ys(),Se=zVs(ue,J.draggable.measure);aHs({activeNode:I!=null?P.get(I):null,config:Ee.layoutShiftCompensation,initialRect:Se,measure:J.draggable.measure});const Le=cbt(ue,J.draggable.measure,Se),Fe=cbt(ue?ue.parentElement:null),ke=j.useRef({activatorEvent:null,active:null,activeNode:ue,collisionRect:null,collisions:null,droppableRects:ce,draggableNodes:P,draggingNode:null,draggingNodeRect:null,droppableContainers:D,over:null,scrollableAncestors:[],scrollAdjustedTranslate:null}),Ve=D.getNodeFor((n=ke.current.over)==null?void 0:n.id),je=YVs({measure:J.dragOverlay.measure}),Ae=(r=je.nodeRef.current)!=null?r:ue,Ce=E?(a=je.rect)!=null?a:Le:null,qe=!!(je.nodeRef.current&&je.rect),ze=UVs(qe?null:Le),$e=uUt(Ae?Kw(Ae):null),ct=qVs(E?Ve??ue:null),Xe=WVs(ct),it=nHs(f,{transform:{x:R.x-ze.x,y:R.y-ze.y,scaleX:1,scaleY:1},activatorEvent:X,active:W,activeNodeRect:Le,containerNodeRect:Fe,draggingNodeRect:Ce,over:ke.current.over,overlayNodeRect:je.rect,scrollableAncestors:ct,scrollableAncestorRects:Xe,windowRect:$e}),at=ve?SV(ve,R):null,Ke=VVs(ct),nt=ubt(Ke),xt=ubt(Ke,[Le]),rt=SV(it,nt),Yt=Ce?hVs(Ce,it):null,qt=W&&Yt?h({active:W,collisionRect:Yt,droppableRects:ce,droppableContainers:te,pointerCoordinates:at}):null,ts=tUt(qt,"id"),[ys,Bt]=j.useState(null),Ft=qe?it:SV(it,xt),rs=dVs(Ft,(i=ys==null?void 0:ys.rect)!=null?i:null,Le),St=j.useRef(null),Xs=j.useCallback((cs,js)=>{let{sensor:kn,options:Ws}=js;if(V.current==null)return;const On=P.get(V.current);if(!On)return;const ds=cs.nativeEvent,gn=new kn({active:V.current,activeNode:On,event:ds,options:Ws,context:ke,onAbort(hr){if(!P.get(hr))return;const{onDragAbort:qn}=ie.current,hn={id:hr};qn==null||qn(hn),b({type:"onDragAbort",event:hn})},onPending(hr,Er,qn,hn){if(!P.get(hr))return;const{onDragPending:vn}=ie.current,xs={id:hr,constraint:Er,initialCoordinates:qn,offset:hn};vn==null||vn(xs),b({type:"onDragPending",event:xs})},onStart(hr){const Er=V.current;if(Er==null)return;const qn=P.get(Er);if(!qn)return;const{onDragStart:hn}=ie.current,Fn={activatorEvent:ds,active:{id:Er,data:qn.data,rect:U}};wv.unstable_batchedUpdates(()=>{hn==null||hn(Fn),C(mP.Initializing),v({type:x0.DragStart,initialCoordinates:hr,active:Er}),b({type:"onDragStart",event:Fn}),Y(St.current),ae(ds)})},onMove(hr){v({type:x0.DragMove,coordinates:hr})},onEnd:As(x0.DragEnd),onCancel:As(x0.DragCancel)});St.current=gn;function As(hr){return async function(){const{active:qn,collisions:hn,over:Fn,scrollAdjustedTranslate:vn}=ke.current;let xs=null;if(qn&&vn){const{cancelDrop:Lr}=ie.current;xs={activatorEvent:ds,active:qn,collisions:hn,delta:vn,over:Fn},hr===x0.DragEnd&&typeof Lr=="function"&&await Promise.resolve(Lr(xs))&&(hr=x0.DragCancel)}V.current=null,wv.unstable_batchedUpdates(()=>{v({type:hr}),C(mP.Uninitialized),Bt(null),Y(null),ae(null),St.current=null;const Lr=hr===x0.DragEnd?"onDragEnd":"onDragCancel";if(xs){const Or=ie.current[Lr];Or==null||Or(xs),b({type:Lr,event:xs})}})}}},[P]),vt=j.useCallback((cs,js)=>(kn,Ws)=>{const On=kn.nativeEvent,ds=P.get(Ws);if(V.current!==null||!ds||On.dndKit||On.defaultPrevented)return;const gn={active:ds};cs(kn,js.options,gn)===!0&&(On.dndKit={capturedBy:js.sensor},V.current=Ws,Xs(kn,js))},[P,Xs]),gs=FVs(u,vt);HVs(u),Q4(()=>{Le&&S===mP.Initializing&&C(mP.Initialized)},[Le,S]),j.useEffect(()=>{const{onDragMove:cs}=ie.current,{active:js,activatorEvent:kn,collisions:Ws,over:On}=ke.current;if(!js||!kn)return;const ds={active:js,activatorEvent:kn,collisions:Ws,delta:{x:rt.x,y:rt.y},over:On};wv.unstable_batchedUpdates(()=>{cs==null||cs(ds),b({type:"onDragMove",event:ds})})},[rt.x,rt.y]),j.useEffect(()=>{const{active:cs,activatorEvent:js,collisions:kn,droppableContainers:Ws,scrollAdjustedTranslate:On}=ke.current;if(!cs||V.current==null||!js||!On)return;const{onDragOver:ds}=ie.current,gn=Ws.get(ts),As=gn&&gn.rect.current?{id:gn.id,rect:gn.rect.current,data:gn.data,disabled:gn.disabled}:null,hr={active:cs,activatorEvent:js,collisions:kn,delta:{x:On.x,y:On.y},over:As};wv.unstable_batchedUpdates(()=>{Bt(As),ds==null||ds(hr),b({type:"onDragOver",event:hr})})},[ts]),Q4(()=>{ke.current={activatorEvent:X,active:W,activeNode:ue,collisionRect:Yt,collisions:qt,droppableRects:ce,draggableNodes:P,draggingNode:Ae,draggingNodeRect:Ce,droppableContainers:D,over:ys,scrollableAncestors:ct,scrollAdjustedTranslate:rt},U.current={initial:Ce,translated:Yt}},[W,ue,qt,Yt,P,Ae,Ce,ce,D,ys,ct,rt]),IVs({...Ee,delta:R,draggingRect:Yt,pointerCoordinates:at,scrollableAncestors:ct,scrollableAncestorRects:Xe});const Ss=j.useMemo(()=>({active:W,activeNode:ue,activeNodeRect:Le,activatorEvent:X,collisions:qt,containerNodeRect:Fe,dragOverlay:je,draggableNodes:P,droppableContainers:D,droppableRects:ce,over:ys,measureDroppableContainers:_e,scrollableAncestors:ct,scrollableAncestorRects:Xe,measuringConfiguration:J,measuringScheduled:he,windowRect:$e}),[W,ue,Le,X,qt,Fe,je,P,D,ce,ys,_e,ct,Xe,J,he,$e]),Is=j.useMemo(()=>({activatorEvent:X,activators:gs,active:W,activeNodeRect:Le,ariaDescribedById:{draggable:ne},dispatch:v,draggableNodes:P,over:ys,measureDroppableContainers:_e}),[X,gs,W,Le,v,ne,P,ys,_e]);return Gt.createElement(Q$t.Provider,{value:w},Gt.createElement(x6e.Provider,{value:Is},Gt.createElement(hUt.Provider,{value:Ss},Gt.createElement(mUt.Provider,{value:rs},d)),Gt.createElement(sHs,{disabled:(o==null?void 0:o.restoreFocus)===!1})),Gt.createElement(aVs,{...o,hiddenTextDescribedById:ne}));function Ys(){const cs=(G==null?void 0:G.autoScrollEnabled)===!1,js=typeof c=="object"?c.enabled===!1:c===!1,kn=E&&!cs&&!js;return typeof c=="object"?{...c,enabled:kn}:{enabled:kn}}}),iHs=j.createContext(null),mbt="button",oHs="Draggable";function lHs(s){let{id:t,data:n,disabled:r=!1,attributes:a}=s;const i=rie(oHs),{activators:l,activatorEvent:o,active:c,activeNodeRect:d,ariaDescribedById:u,draggableNodes:h,over:m}=j.useContext(x6e),{role:f=mbt,roleDescription:g="draggable",tabIndex:x=0}=a??{},y=(c==null?void 0:c.id)===t,v=j.useContext(y?mUt:iHs),[b,w]=KEe(),[S,C]=KEe(),E=GVs(l,t),I=cse(n);Q4(()=>(h.set(t,{id:t,key:i,node:b,activatorNode:S,data:I}),()=>{const R=h.get(t);R&&R.key===i&&h.delete(t)}),[h,t]);const P=j.useMemo(()=>({role:f,tabIndex:x,"aria-disabled":r,"aria-pressed":y&&f===mbt?!0:void 0,"aria-roledescription":g,"aria-describedby":u.draggable}),[r,f,x,y,g,u.draggable]);return{active:c,activatorEvent:o,activeNodeRect:d,attributes:P,isDragging:y,listeners:r?void 0:E,node:b,over:m,setNodeRef:w,setActivatorNodeRef:C,transform:v}}function cHs(){return j.useContext(hUt)}const dHs="Droppable",uHs={timeout:25};function hHs(s){let{data:t,disabled:n=!1,id:r,resizeObserverConfig:a}=s;const i=rie(dHs),{active:l,dispatch:o,over:c,measureDroppableContainers:d}=j.useContext(x6e),u=j.useRef({disabled:n}),h=j.useRef(!1),m=j.useRef(null),f=j.useRef(null),{disabled:g,updateMeasurementsFor:x,timeout:y}={...uHs,...a},v=cse(x??r),b=j.useCallback(()=>{if(!h.current){h.current=!0;return}f.current!=null&&clearTimeout(f.current),f.current=setTimeout(()=>{d(Array.isArray(v.current)?v.current:[v.current]),f.current=null},y)},[y]),w=g6e({callback:b,disabled:g||!l}),S=j.useCallback((P,R)=>{w&&(R&&(w.unobserve(R),h.current=!1),P&&w.observe(P))},[w]),[C,E]=KEe(S),I=cse(t);return j.useEffect(()=>{!w||!C.current||(w.disconnect(),h.current=!1,w.observe(C.current))},[C,w]),j.useEffect(()=>(o({type:x0.RegisterDroppable,element:{id:r,key:i,disabled:n,node:C,rect:m,data:I}}),()=>o({type:x0.UnregisterDroppable,key:i,id:r})),[r]),j.useEffect(()=>{n!==u.current.disabled&&(o({type:x0.SetDroppableDisabled,id:r,key:i,disabled:n}),u.current.disabled=n)},[r,i,n,o]),{active:l,rect:m,isOver:(c==null?void 0:c.id)===r,node:C,over:c,setNodeRef:E}}function v6e(s,t,n){const r=s.slice();return r.splice(n<0?r.length+n:n,0,r.splice(t,1)[0]),r}function mHs(s,t){return s.reduce((n,r,a)=>{const i=t.get(r);return i&&(n[a]=i),n},Array(s.length))}function sde(s){return s!==null&&s>=0}function fHs(s,t){if(s===t)return!0;if(s.length!==t.length)return!1;for(let n=0;n{var t;let{rects:n,activeNodeRect:r,activeIndex:a,overIndex:i,index:l}=s;const o=(t=n[a])!=null?t:r;if(!o)return null;const c=gHs(n,l,a);if(l===a){const d=n[i];return d?{x:aa&&l<=i?{x:-o.width-c,y:0,...nde}:l=i?{x:o.width+c,y:0,...nde}:{x:0,y:0,...nde}};function gHs(s,t,n){const r=s[t],a=s[t-1],i=s[t+1];return!r||!a&&!i?0:n{let{rects:t,activeIndex:n,overIndex:r,index:a}=s;const i=v6e(t,r,n),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}},rde={scaleX:1,scaleY:1},xHs=s=>{var t;let{activeIndex:n,activeNodeRect:r,index:a,rects:i,overIndex:l}=s;const o=(t=i[n])!=null?t:r;if(!o)return null;if(a===n){const d=i[l];return d?{x:0,y:nn&&a<=l?{x:0,y:-o.height-c,...rde}:a=l?{x:0,y:o.height+c,...rde}:{x:0,y:0,...rde}};function yHs(s,t,n){const r=s[t],a=s[t-1],i=s[t+1];return r?nr.map(E=>typeof E=="object"&&"id"in E?E.id:E),[r]),g=l!=null,x=l?f.indexOf(l.id):-1,y=d?f.indexOf(d.id):-1,v=j.useRef(f),b=!fHs(f,v.current),w=y!==-1&&x===-1||b,S=pHs(i);Q4(()=>{b&&g&&u(f)},[b,f,g,u]),j.useEffect(()=>{v.current=f},[f]);const C=j.useMemo(()=>({activeIndex:x,containerId:h,disabled:S,disableTransforms:w,items:f,overIndex:y,useDragOverlay:m,sortedRects:mHs(f,c),strategy:a}),[x,h,S.draggable,S.droppable,w,f,y,c,m,a]);return Gt.createElement(pUt.Provider,{value:C},t)}const vHs=s=>{let{id:t,items:n,activeIndex:r,overIndex:a}=s;return v6e(n,r,a).indexOf(t)},bHs=s=>{let{containerId:t,isSorting:n,wasDragging:r,index:a,items:i,newIndex:l,previousItems:o,previousContainerId:c,transition:d}=s;return!d||!r||o!==i&&a===l?!1:n?!0:l!==a&&t===c},_Hs={duration:200,easing:"ease"},gUt="transform",wHs=RL.Transition.toString({property:gUt,duration:0,easing:"linear"}),jHs={roleDescription:"sortable"};function NHs(s){let{disabled:t,index:n,node:r,rect:a}=s;const[i,l]=j.useState(null),o=j.useRef(n);return Q4(()=>{if(!t&&n!==o.current&&r.current){const c=a.current;if(c){const d=mK(r.current,{ignoreTransform:!0}),u={x:c.left-d.left,y:c.top-d.top,scaleX:c.width/d.width,scaleY:c.height/d.height};(u.x||u.y)&&l(u)}}n!==o.current&&(o.current=n)},[t,n,r,a]),j.useEffect(()=>{i&&l(null)},[i]),i}function _6e(s){let{animateLayoutChanges:t=bHs,attributes:n,disabled:r,data:a,getNewIndex:i=vHs,id:l,strategy:o,resizeObserverConfig:c,transition:d=_Hs}=s;const{items:u,containerId:h,activeIndex:m,disabled:f,disableTransforms:g,sortedRects:x,overIndex:y,useDragOverlay:v,strategy:b}=j.useContext(pUt),w=kHs(r,f),S=u.indexOf(l),C=j.useMemo(()=>({sortable:{containerId:h,index:S,items:u},...a}),[h,a,S,u]),E=j.useMemo(()=>u.slice(u.indexOf(l)),[u,l]),{rect:I,node:P,isOver:R,setNodeRef:D}=hHs({id:l,data:C,disabled:w.droppable,resizeObserverConfig:{updateMeasurementsFor:E,...c}}),{active:O,activatorEvent:U,activeNodeRect:W,attributes:V,setNodeRef:G,listeners:Y,isDragging:X,over:ae,setActivatorNodeRef:ie,transform:ne}=lHs({id:l,data:C,attributes:{...jHs,...n},disabled:w.draggable}),te=Gqs(D,G),J=!!O,ce=J&&!g&&sde(m)&&sde(y),_e=!v&&X,he=_e&&ce?ne:null,ve=ce?he??(o??b)({rects:x,activeNodeRect:W,activeIndex:m,overIndex:y,index:S}):null,Ee=sde(m)&&sde(y)?i({id:l,items:u,activeIndex:m,overIndex:y}):S,Se=O==null?void 0:O.id,Le=j.useRef({activeId:Se,items:u,newIndex:Ee,containerId:h}),Fe=u!==Le.current.items,ke=t({active:O,containerId:h,isDragging:X,isSorting:J,id:l,index:S,items:u,newIndex:Le.current.newIndex,previousItems:Le.current.items,previousContainerId:Le.current.containerId,transition:d,wasDragging:Le.current.activeId!=null}),Ve=NHs({disabled:!ke,index:S,node:P,rect:I});return j.useEffect(()=>{J&&Le.current.newIndex!==Ee&&(Le.current.newIndex=Ee),h!==Le.current.containerId&&(Le.current.containerId=h),u!==Le.current.items&&(Le.current.items=u)},[J,Ee,h,u]),j.useEffect(()=>{if(Se===Le.current.activeId)return;if(Se!=null&&Le.current.activeId==null){Le.current.activeId=Se;return}const Ae=setTimeout(()=>{Le.current.activeId=Se},50);return()=>clearTimeout(Ae)},[Se]),{active:O,activeIndex:m,attributes:V,data:C,rect:I,index:S,newIndex:Ee,items:u,isOver:R,isSorting:J,isDragging:X,listeners:Y,node:P,overIndex:y,over:ae,setNodeRef:te,setActivatorNodeRef:ie,setDroppableNodeRef:D,setDraggableNodeRef:G,transform:Ve??ve,transition:je()};function je(){if(Ve||Fe&&Le.current.newIndex===S)return wHs;if(!(_e&&!nnt(U)||!d)&&(J||ke))return RL.Transition.toString({...d,property:gUt})}}function kHs(s,t){var n,r;return typeof s=="boolean"?{draggable:s,droppable:!1}:{draggable:(n=s==null?void 0:s.draggable)!=null?n:t.draggable,droppable:(r=s==null?void 0:s.droppable)!=null?r:t.droppable}}function XEe(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 SHs=[Qu.Down,Qu.Right,Qu.Up,Qu.Left],xUt=(s,t)=>{let{context:{active:n,collisionRect:r,droppableRects:a,droppableContainers:i,over:l,scrollableAncestors:o}}=t;if(SHs.includes(s.code)){if(s.preventDefault(),!n||!r)return;const c=[];i.getEnabled().forEach(h=>{if(!h||h!=null&&h.disabled)return;const m=a.get(h.id);if(m)switch(s.code){case Qu.Down:r.topm.top&&c.push(h);break;case Qu.Left:r.left>m.left&&c.push(h);break;case Qu.Right:r.left1&&(u=d[1].id),u!=null){const h=i.get(n.id),m=i.get(u),f=m?a.get(m.id):null,g=m==null?void 0:m.node.current;if(g&&f&&h&&m){const y=f6e(g).some((E,I)=>o[I]!==E),v=yUt(h,m),b=CHs(h,m),w=y||!v?{x:0,y:0}:{x:b?r.width-f.width:0,y:b?r.height-f.height:0},S={x:f.left,y:f.top};return w.x&&w.y?S:dse(S,w)}}}};function yUt(s,t){return!XEe(s)||!XEe(t)?!1:s.data.current.sortable.containerId===t.data.current.sortable.containerId}function CHs(s,t){return!XEe(s)||!XEe(t)||!yUt(s,t)?!1:s.data.current.sortable.indexn(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(gr,{className:"h-3 w-3"})}),t?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(Ja,{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 vUt({photos:s,uploading:t,onUpload:n,onRemove:r,onReorder:a,onSetPrimary:i}){var h,m;const l=h6e(IG(fK,{activationConstraint:{distance:5}})),o=[...s].sort((f,g)=>(f.sort_order??0)-(g.sort_order??0)),c=((h=o.find(f=>f.is_primary))==null?void 0:h.id)??null,d=c??((m=o[0])==null?void 0:m.id),u=f=>{var E;const{active:g,over:x}=f;if(!x||g.id===x.id)return;const y=o.findIndex(I=>I.id===g.id),v=o.findIndex(I=>I.id===x.id),b=[...o],[w]=b.splice(y,1);b.splice(v,0,w);const S=c??((E=b[0])==null?void 0:E.id),C=b.map((I,P)=>({...I,sort_order:P,is_primary:I.id===S}));a(C)};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(y6e,{sensors:l,collisionDetection:m6e,onDragEnd:u,children:e.jsx(b6e,{items:o.map(f=>f.id),strategy:aie,children:e.jsxs("div",{className:"grid grid-cols-3 sm:grid-cols-4 gap-4",children:[o.map(f=>e.jsx(AHs,{photo:f,isPrimary:f.id===d,onRemove:r,onSetPrimary:i},f.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(kt,{className:"h-8 w-8 animate-spin"}):e.jsxs(e.Fragment,{children:[e.jsx(ni,{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:f=>n(f.target.files),disabled:t})]})]})})})]})}function w6e({open:s,onOpenChange:t,listingId:n,listingSlug:r,listingTitle:a,isCommercial:i=!1}){const{user:l}=vs(),[o,c]=j.useState(null),[d,u]=j.useState(!1),[h,m]=j.useState(!1);j.useEffect(()=>{(async()=>{if(!(!s||!l)){u(!0);try{const{data:v,error:b}=await q.from("listing_shares").select("id, share_token, click_count, lead_count").eq("listing_id",n).eq("sharing_agent_id",l.id).order("created_at",{ascending:!1}).limit(1).maybeSingle();if(b)throw b;if(v&&v.share_token)c(v);else if(v&&!v.share_token){const{data:w,error:S}=await q.from("listing_shares").update({share_type:"referral_link"}).eq("id",v.id).select("id, share_token, click_count, lead_count").single();if(S)throw S;c(w)}else{const{data:w,error:S}=await q.from("listing_shares").insert({listing_id:n,sharing_agent_id:l.id,share_type:"referral_link"}).select("id, share_token, click_count, lead_count").single();if(S)throw S;c(w)}}catch(v){console.error("Error creating share link:",v),re.error("Failed to generate share link")}finally{u(!1)}}})()},[s,l,n]);const f=o!=null&&o.share_token?`${i?ADs:"https://listings.relevelup.com"}/${r||n}?ref=${o.share_token}`:"",g=async()=>{try{await navigator.clipboard.writeText(f),m(!0),re.success("Link copied to clipboard!"),setTimeout(()=>m(!1),2e3)}catch{re.error("Failed to copy link")}},x=y=>{const v=encodeURIComponent(f),b=encodeURIComponent(`Check out this listing: ${a}`);switch(y){case"email":window.open(`mailto:?subject=${b}&body=${v}`);break;case"text":window.open(`sms:?body=${b}%20${v}`);break;case"facebook":window.open(`https://www.facebook.com/sharer/sharer.php?u=${v}`,"_blank");break}};return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Os,{className:"sm:max-w-md",children:[e.jsxs(Us,{children:[e.jsxs(Bs,{className:"flex items-center gap-2",children:[e.jsx(Nn,{className:"h-5 w-5 text-amber-500"}),"Share & Earn Leads"]}),e.jsx(Ir,{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(ee,{children:"Your Referral Link"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(pe,{value:d?"Generating...":f,readOnly:!0,className:"font-mono text-sm"}),e.jsx($,{onClick:g,disabled:d||!f,variant:h?"default":"outline",children:h?e.jsx(la,{className:"h-4 w-4"}):e.jsx(Ha,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Share via"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs($,{variant:"outline",className:"flex-1",onClick:()=>x("email"),disabled:d,children:[e.jsx(mn,{className:"h-4 w-4 mr-2"}),"Email"]}),e.jsxs($,{variant:"outline",className:"flex-1",onClick:()=>x("text"),disabled:d,children:[e.jsx(eo,{className:"h-4 w-4 mr-2"}),"Text"]}),e.jsxs($,{variant:"outline",className:"flex-1",onClick:()=>x("facebook"),disabled:d,children:[e.jsx(Qp,{className:"h-4 w-4 mr-2"}),"Facebook"]})]})]}),o&&(o.click_count>0||o.lead_count>0)&&e.jsxs("div",{className:"pt-4 border-t",children:[e.jsx(ee,{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(Ca,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs",children:"Clicks"})]}),e.jsx("p",{className:"text-2xl font-bold",children:o.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(Zn,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs",children:"Leads"})]}),e.jsx("p",{className:"text-2xl font-bold text-primary",children:o.lead_count})]})]})]})]})]})})}var EHs=Object.defineProperty,QEe=Object.getOwnPropertySymbols,bUt=Object.prototype.hasOwnProperty,_Ut=Object.prototype.propertyIsEnumerable,fbt=(s,t,n)=>t in s?EHs(s,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):s[t]=n,GGe=(s,t)=>{for(var n in t||(t={}))bUt.call(t,n)&&fbt(s,n,t[n]);if(QEe)for(var n of QEe(t))_Ut.call(t,n)&&fbt(s,n,t[n]);return s},WGe=(s,t)=>{var n={};for(var r in s)bUt.call(s,r)&&t.indexOf(r)<0&&(n[r]=s[r]);if(s!=null&&QEe)for(var r of QEe(s))t.indexOf(r)<0&&_Ut.call(s,r)&&(n[r]=s[r]);return n};/** * @license QR Code generator library (TypeScript) * Copyright (c) Project Nayuki. * SPDX-License-Identifier: MIT */var Y7;(s=>{const t=class wu{constructor(c,d,u,h){if(this.version=c,this.errorCorrectionLevel=d,this.modules=[],this.isFunction=[],cwu.MAX_VERSION)throw new RangeError("Version value out of range");if(h<-1||h>7)throw new RangeError("Mask value out of range");this.size=c*4+17;let m=[];for(let g=0;g7)throw new RangeError("Invalid value");let g,x;for(g=u;;g++){const w=wu.getNumDataCodewords(g,d)*8,S=l.getTotalBits(c,g);if(S<=w){x=S;break}if(g>=h)throw new RangeError("Data too long")}for(const w of[wu.Ecc.MEDIUM,wu.Ecc.QUARTILE,wu.Ecc.HIGH])f&&x<=wu.getNumDataCodewords(g,w)*8&&(d=w);let y=[];for(const w of c){n(w.mode.modeBits,4,y),n(w.numChars,w.mode.numCharCountBits(g),y);for(const S of w.getData())y.push(S)}a(y.length==x);const v=wu.getNumDataCodewords(g,d)*8;a(y.length<=v),n(0,Math.min(4,v-y.length),y),n(0,(8-y.length%8)%8,y),a(y.length%8==0);for(let w=236;y.lengthb[S>>>3]|=w<<7-(S&7)),new wu(g,d,b,m)}getModule(c,d){return 0<=c&&c>>9)*1335;const h=(d<<10|u)^21522;a(h>>>15==0);for(let m=0;m<=5;m++)this.setFunctionModule(8,m,r(h,m));this.setFunctionModule(8,7,r(h,6)),this.setFunctionModule(8,8,r(h,7)),this.setFunctionModule(7,8,r(h,8));for(let m=9;m<15;m++)this.setFunctionModule(14-m,8,r(h,m));for(let m=0;m<8;m++)this.setFunctionModule(this.size-1-m,8,r(h,m));for(let m=8;m<15;m++)this.setFunctionModule(8,this.size-15+m,r(h,m));this.setFunctionModule(8,this.size-8,!0)}drawVersion(){if(this.version<7)return;let c=this.version;for(let u=0;u<12;u++)c=c<<1^(c>>>11)*7973;const d=this.version<<12|c;a(d>>>18==0);for(let u=0;u<18;u++){const h=r(d,u),m=this.size-11+u%3,f=Math.floor(u/3);this.setFunctionModule(m,f,h),this.setFunctionModule(f,m,h)}}drawFinderPattern(c,d){for(let u=-4;u<=4;u++)for(let h=-4;h<=4;h++){const m=Math.max(Math.abs(h),Math.abs(u)),f=c+h,g=d+u;0<=f&&f{(w!=x-m||C>=g)&&b.push(S[w])});return a(b.length==f),b}drawCodewords(c){if(c.length!=Math.floor(wu.getNumRawDataModules(this.version)/8))throw new RangeError("Invalid argument");let d=0;for(let u=this.size-1;u>=1;u-=2){u==6&&(u=5);for(let h=0;h>>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(g,x),f||(c+=this.finderPenaltyCountPatterns(x)*wu.PENALTY_N3),f=this.modules[m][y],g=1);c+=this.finderPenaltyTerminateAndCount(f,g,x)*wu.PENALTY_N3}for(let m=0;m5&&c++):(this.finderPenaltyAddHistory(g,x),f||(c+=this.finderPenaltyCountPatterns(x)*wu.PENALTY_N3),f=this.modules[y][m],g=1);c+=this.finderPenaltyTerminateAndCount(f,g,x)*wu.PENALTY_N3}for(let m=0;mf+(g?1:0),d);const u=this.size*this.size,h=Math.ceil(Math.abs(d*20-u*10)/u)-1;return a(0<=h&&h<=9),c+=h*wu.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 u=[6];for(let h=this.size-7;u.lengthwu.MAX_VERSION)throw new RangeError("Version number out of range");let d=(16*c+128)*c+64;if(c>=2){const u=Math.floor(c/7)+2;d-=(25*u-10)*u-55,c>=7&&(d-=36)}return a(208<=d&&d<=29648),d}static getNumDataCodewords(c,d){return Math.floor(wu.getNumRawDataModules(c)/8)-wu.ECC_CODEWORDS_PER_BLOCK[d.ordinal][c]*wu.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 h=0;h0);for(const h of c){const m=h^u.shift();u.push(0),d.forEach((f,g)=>u[g]^=wu.reedSolomonMultiply(f,m))}return u}static reedSolomonMultiply(c,d){if(c>>>8||d>>>8)throw new RangeError("Byte out of range");let u=0;for(let h=7;h>=0;h--)u=u<<1^(u>>>7)*285,u^=(d>>>h&1)*c;return a(u>>>8==0),u}finderPenaltyCountPatterns(c){const d=c[1];a(d<=this.size*3);const u=d>0&&c[2]==d&&c[3]==d*3&&c[4]==d&&c[5]==d;return(u&&c[0]>=d*4&&c[6]>=d?1:0)+(u&&c[6]>=d*4&&c[0]>=d?1:0)}finderPenaltyTerminateAndCount(c,d,u){return c&&(this.finderPenaltyAddHistory(d,u),d=0),d+=this.size,this.finderPenaltyAddHistory(d,u),this.finderPenaltyCountPatterns(u)}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 n(o,c,d){if(c<0||c>31||o>>>c)throw new RangeError("Value out of range");for(let u=c-1;u>=0;u--)d.push(o>>>u&1)}function r(o,c){return(o>>>c&1)!=0}function a(o){if(!o)throw new Error("Assertion error")}const i=class dx{constructor(c,d,u){if(this.mode=c,this.numChars=d,this.bitData=u,d<0)throw new RangeError("Invalid argument");this.bitData=u.slice()}static makeBytes(c){let d=[];for(const u of c)n(u,8,d);return new dx(dx.Mode.BYTE,c.length,d)}static makeNumeric(c){if(!dx.isNumeric(c))throw new RangeError("String contains non-numeric characters");let d=[];for(let u=0;u=1<{(t=>{const n=class{constructor(a,i){this.ordinal=a,this.formatBits=i}};n.LOW=new n(0,1),n.MEDIUM=new n(1,0),n.QUARTILE=new n(2,3),n.HIGH=new n(3,2),t.Ecc=n})(s.QrCode||(s.QrCode={}))})(Y7||(Y7={}));(s=>{(t=>{const n=class{constructor(a,i){this.modeBits=a,this.numBitsCharCount=i}numCharCountBits(a){return this.numBitsCharCount[Math.floor((a+7)/17)]}};n.NUMERIC=new n(1,[10,12,14]),n.ALPHANUMERIC=new n(2,[9,11,13]),n.BYTE=new n(4,[8,16,16]),n.KANJI=new n(8,[8,10,12]),n.ECI=new n(7,[0,0,0]),t.Mode=n})(s.QrSegment||(s.QrSegment={}))})(Y7||(Y7={}));var tq=Y7;/** * @license qrcode.react * Copyright (c) Paul O'Shannessy * SPDX-License-Identifier: ISC */var THs={L:tq.QrCode.Ecc.LOW,M:tq.QrCode.Ecc.MEDIUM,Q:tq.QrCode.Ecc.QUARTILE,H:tq.QrCode.Ecc.HIGH},wUt=128,jUt="L",NUt="#FFFFFF",kUt="#000000",SUt=!1,CUt=1,MHs=4,PHs=0,IHs=.1;function AUt(s,t=0){const n=[];return s.forEach(function(r,a){let i=null;r.forEach(function(l,o){if(!l&&i!==null){n.push(`M${i+t} ${a+t}h${o-i}v1H${i+t}z`),i=null;return}if(o===r.length-1){if(!l)return;i===null?n.push(`M${o+t},${a+t} h1v1H${o+t}z`):n.push(`M${i+t},${a+t} h${o+1-i}v1H${i+t}z`);return}l&&i===null&&(i=o)})}),n.join("")}function EUt(s,t){return s.slice().map((n,r)=>r=t.y+t.h?n:n.map((a,i)=>i=t.x+t.w?a:!1))}function LHs(s,t,n,r){if(r==null)return null;const a=s.length+n*2,i=Math.floor(t*IHs),l=a/t,o=(r.width||i)*l,c=(r.height||i)*l,d=r.x==null?s.length/2-o/2:r.x*l,u=r.y==null?s.length/2-c/2:r.y*l,h=r.opacity==null?1:r.opacity;let m=null;if(r.excavate){let g=Math.floor(d),x=Math.floor(u),y=Math.ceil(o+d-g),v=Math.ceil(c+u-x);m={x:g,y:x,w:y,h:v}}const f=r.crossOrigin;return{x:d,y:u,h:c,w:o,excavation:m,opacity:h,crossOrigin:f}}function RHs(s,t){return t!=null?Math.max(Math.floor(t),0):s?MHs:PHs}function TUt({value:s,level:t,minVersion:n,includeMargin:r,marginSize:a,imageSettings:i,size:l,boostLevel:o}){let c=Gt.useMemo(()=>{const g=(Array.isArray(s)?s:[s]).reduce((x,y)=>(x.push(...tq.QrSegment.makeSegments(y)),x),[]);return tq.QrCode.encodeSegments(g,THs[t],n,void 0,void 0,o)},[s,t,n,o]);const{cells:d,margin:u,numCells:h,calculatedImageSettings:m}=Gt.useMemo(()=>{let f=c.getModules();const g=RHs(r,a),x=f.length+g*2,y=LHs(f,l,g,i);return{cells:f,margin:g,numCells:x,calculatedImageSettings:y}},[c,l,i,r,a]);return{qrcode:c,margin:u,cells:d,numCells:h,calculatedImageSettings:m}}var DHs=function(){try{new Path2D().addPath(new Path2D)}catch{return!1}return!0}(),MUt=Gt.forwardRef(function(t,n){const r=t,{value:a,size:i=wUt,level:l=jUt,bgColor:o=NUt,fgColor:c=kUt,includeMargin:d=SUt,minVersion:u=CUt,boostLevel:h,marginSize:m,imageSettings:f}=r,x=WGe(r,["value","size","level","bgColor","fgColor","includeMargin","minVersion","boostLevel","marginSize","imageSettings"]),{style:y}=x,v=WGe(x,["style"]),b=f==null?void 0:f.src,w=Gt.useRef(null),S=Gt.useRef(null),C=Gt.useCallback(V=>{w.current=V,typeof n=="function"?n(V):n&&(n.current=V)},[n]),[E,I]=Gt.useState(!1),{margin:P,cells:R,numCells:D,calculatedImageSettings:O}=TUt({value:a,level:l,minVersion:u,boostLevel:h,includeMargin:d,marginSize:m,imageSettings:f,size:i});Gt.useEffect(()=>{if(w.current!=null){const V=w.current,G=V.getContext("2d");if(!G)return;let Y=R;const X=S.current,ae=O!=null&&X!==null&&X.complete&&X.naturalHeight!==0&&X.naturalWidth!==0;ae&&O.excavation!=null&&(Y=EUt(R,O.excavation));const ie=window.devicePixelRatio||1;V.height=V.width=i*ie;const ne=i/D*ie;G.scale(ne,ne),G.fillStyle=o,G.fillRect(0,0,D,D),G.fillStyle=c,DHs?G.fill(new Path2D(AUt(Y,P))):R.forEach(function(te,J){te.forEach(function(ce,_e){ce&&G.fillRect(_e+P,J+P,1,1)})}),O&&(G.globalAlpha=O.opacity),ae&&G.drawImage(X,O.x+P,O.y+P,O.w,O.h)}}),Gt.useEffect(()=>{I(!1)},[b]);const U=GGe({height:i,width:i},y);let W=null;return b!=null&&(W=Gt.createElement("img",{src:b,key:b,style:{display:"none"},onLoad:()=>{I(!0)},ref:S,crossOrigin:O==null?void 0:O.crossOrigin})),Gt.createElement(Gt.Fragment,null,Gt.createElement("canvas",GGe({style:U,height:i,width:i,ref:C,role:"img"},v)),W)});MUt.displayName="QRCodeCanvas";var fk=Gt.forwardRef(function(t,n){const r=t,{value:a,size:i=wUt,level:l=jUt,bgColor:o=NUt,fgColor:c=kUt,includeMargin:d=SUt,minVersion:u=CUt,boostLevel:h,title:m,marginSize:f,imageSettings:g}=r,x=WGe(r,["value","size","level","bgColor","fgColor","includeMargin","minVersion","boostLevel","title","marginSize","imageSettings"]),{margin:y,cells:v,numCells:b,calculatedImageSettings:w}=TUt({value:a,level:l,minVersion:u,boostLevel:h,includeMargin:d,marginSize:f,imageSettings:g,size:i});let S=v,C=null;g!=null&&w!=null&&(w.excavation!=null&&(S=EUt(v,w.excavation)),C=Gt.createElement("image",{href:g.src,height:w.h,width:w.w,x:w.x+y,y:w.y+y,preserveAspectRatio:"none",opacity:w.opacity,crossOrigin:w.crossOrigin}));const E=AUt(S,y);return Gt.createElement("svg",GGe({height:i,width:i,viewBox:`0 0 ${b} ${b}`,ref:n,role:"img"},x),!!m&&Gt.createElement("title",null,m),Gt.createElement("path",{fill:o,d:`M0,0 h${b}v${b}H0z`,shapeRendering:"crispEdges"}),Gt.createElement("path",{fill:c,d:E,shapeRendering:"crispEdges"}),C)});fk.displayName="QRCodeSVG";function PUt({open:s,onOpenChange:t,url:n,title:r,fileBase:a}){const i=j.useRef(null),o=`${(h=>h.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")||"listing")(a||r||"listing")}-qr`,c=()=>{var m;const h=(m=i.current)==null?void 0:m.querySelector("svg");return h?new XMLSerializer().serializeToString(h):null},d=()=>{const h=c();if(!h)return;const m=new Blob([h],{type:"image/svg+xml;charset=utf-8"}),f=document.createElement("a");f.href=URL.createObjectURL(m),f.download=`${o}.svg`,f.click(),URL.revokeObjectURL(f.href)},u=(h=1024)=>{const m=c();if(!m)return;const f=new Image,g=new Blob([m],{type:"image/svg+xml;charset=utf-8"}),x=URL.createObjectURL(g);f.onload=()=>{const y=document.createElement("canvas");y.width=h,y.height=h;const v=y.getContext("2d");v&&(v.fillStyle="#ffffff",v.fillRect(0,0,h,h),v.drawImage(f,0,0,h,h),URL.revokeObjectURL(x),y.toBlob(b=>{if(!b)return;const w=document.createElement("a");w.href=URL.createObjectURL(b),w.download=`${o}.png`,w.click(),URL.revokeObjectURL(w.href)},"image/png"))},f.src=x};return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Os,{className:"sm:max-w-md",children:[e.jsxs(Us,{children:[e.jsx(Bs,{children:"Listing QR Code"}),e.jsx(Ir,{children:"Scans straight to the public listing page — great for flyers, signs, and open houses."})]}),e.jsxs("div",{className:"flex flex-col items-center gap-4",children:[e.jsx("div",{ref:i,className:"rounded-xl bg-white p-4 shadow-sm border",children:e.jsx(fk,{value:n,size:220,level:"H",includeMargin:!0})}),e.jsx("p",{className:"text-xs text-muted-foreground break-all text-center",children:n})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-3 gap-2 pt-2",children:[e.jsxs($,{onClick:()=>u(),className:"gap-2",children:[e.jsx(di,{className:"h-4 w-4"}),"PNG"]}),e.jsxs($,{variant:"outline",onClick:d,className:"gap-2",children:[e.jsx(di,{className:"h-4 w-4"}),"SVG"]}),e.jsxs($,{variant:"outline",onClick:async()=>{await navigator.clipboard.writeText(n),re.success("Link copied")},className:"gap-2",children:[e.jsx(Ha,{className:"h-4 w-4"}),"Copy link"]})]})]})})}var FHs=Object.defineProperty,IUt=(s,t)=>FHs(s,"name",{value:t,configurable:!0}),pbt="horizontal",OHs=["horizontal","vertical"],zHs=j.forwardRef(IUt(function(t,n){const{decorative:r,orientation:a=pbt,...i}=t,l=LUt(a)?a:pbt,c=r?{role:"none"}:{"aria-orientation":l==="vertical"?l:void 0,role:"separator"};return e.jsx(Ei.div,{"data-orientation":l,...c,...i,ref:n})},"Separator"));function LUt(s){return OHs.includes(s)}IUt(LUt,"isValidOrientation");var RUt=zHs;const Gc=j.forwardRef(({className:s,orientation:t="horizontal",decorative:n=!0,...r},a)=>e.jsx(RUt,{ref:a,decorative:n,orientation:t,className:Pt("shrink-0 bg-border",t==="horizontal"?"h-[1px] w-full":"h-full w-[1px]",s),...r}));Gc.displayName=RUt.displayName;const Yw=()=>tt({queryKey:["relationship-types"],queryFn:async()=>{const{data:s,error:t}=await q.from("relationship_types").select("*").order("sort_order");if(t)throw t;return s}}),DUt=()=>{const s=Sa(),t=1e3;return tt({queryKey:["innercircle-contacts-lite",s],queryFn:async()=>{const n=[];let r=0;for(;;){const{data:a,error:i}=await q.from("innercircle_contacts").select("id, first_name, last_name, email, phone, address, city, state, zip, zip_code, birthday, home_anniversary, wedding_anniversary, created_at").eq("owner_user_id",s).order("created_at",{ascending:!1}).range(r,r+t-1);if(i)throw i;const l=a??[];if(n.push(...l),l.length{const t=Sa(),n=1e3,r=async a=>{const i=[];let l=0;for(;;){const{data:o,error:c}=await a.range(l,l+n-1);if(c)throw c;const d=o??[];if(i.push(...d),d.length{let a=q.from("innercircle_contacts").select("*").eq("owner_user_id",t).order("created_at",{ascending:!1}).order("first_name");const i=await r(a);if(i.length===0)return i;const l=i.map(f=>f.id),o=Array.from(new Set(i.map(f=>f.lead_source_id).filter(f=>!!f))),c=(f,g=250)=>{const x=[];for(let y=0;y{const{data:g,error:x}=await q.from("innercircle_contact_tags").select("id, contact_id, relationship_type_id, relationship_type:relationship_types(*)").in("contact_id",f);if(x)throw x;return g??[]})),Promise.all(c(o).map(async f=>{const{data:g,error:x}=await q.from("lead_sources").select("id, name").in("id",f);if(x)throw x;return g??[]}))]),h=new Map;d.flat().forEach(f=>{const g=h.get(f.contact_id)??[];g.push(f),h.set(f.contact_id,g)});const m=new Map(u.flat().map(f=>[f.id,f]));return i.map(f=>({...f,lead_source_ref:f.lead_source_id?m.get(f.lead_source_id)??null:null,tags:h.get(f.id)??[]}))},enabled:!!t,staleTime:10*60*1e3})},BHs=s=>tt({queryKey:["innercircle-contact",s],queryFn:async()=>{const{data:t,error:n}=await q.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(n)throw n;return t},enabled:!!s}),FUt=()=>{const s=Sa();return tt({queryKey:["innercircle-contact-counts",s],queryFn:async()=>{const{data:t,error:n}=await q.from("innercircle_contacts").select(` id, tags:innercircle_contact_tags(relationship_type_id) `);if(n)throw n;const r={};return t==null||t.forEach(a=>{var i;(i=a.tags)==null||i.forEach(l=>{r[l.relationship_type_id]=(r[l.relationship_type_id]||0)+1})}),r},enabled:!!s})},j6e=()=>{const s=Vt(),t=Sa();return ft({mutationFn:async n=>{const{tagIds:r,...a}=n,i={...a,birthday:a.birthday||null,home_anniversary:a.home_anniversary||null,spouse_birthday:a.spouse_birthday||null,owner_user_id:t},{data:l,error:o}=await q.from("innercircle_contacts").insert(i).select().single();if(o)throw o;if(r&&r.length>0){const{error:c}=await q.from("innercircle_contact_tags").insert(r.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"]}),_a({title:"Contact created successfully"})},onError:n=>{_a({title:"Error creating contact",description:n.message,variant:"destructive"})}})},int=()=>{const s=Vt();return ft({mutationFn:async({id:t,...n})=>{const{tagIds:r,tags:a,...i}=n,l=["birthday","home_anniversary","spouse_birthday","wedding_anniversary","last_contacted_at","next_touch_date"],o={...i};for(const u of Object.keys(o)){const h=o[u];(h===""||typeof h=="string"&&l.includes(u)&&h.trim()==="")&&(o[u]=null)}const{data:c,error:d}=await q.from("innercircle_contacts").update(o).eq("id",t).select().single();if(d)throw d;if(r!==void 0&&(await q.from("innercircle_contact_tags").delete().eq("contact_id",t),r.length>0)){const{error:u}=await q.from("innercircle_contact_tags").insert(r.map(h=>({contact_id:t,relationship_type_id:h})));if(u)throw u}return c},onSuccess:()=>{s.invalidateQueries({queryKey:["innercircle-contacts"]}),s.invalidateQueries({queryKey:["innercircle-contact"]}),s.invalidateQueries({queryKey:["innercircle-contact-counts"]}),_a({title:"Contact updated successfully"})},onError:t=>{_a({title:"Error updating contact",description:t.message,variant:"destructive"})}})},OUt=()=>{const s=Vt();return ft({mutationFn:async({contactId:t,spouseContactId:n})=>{if(n){const{error:r}=await q.from("innercircle_contacts").update({spouse_contact_id:n}).eq("id",t);if(r)throw r;const{error:a}=await q.from("innercircle_contacts").update({spouse_contact_id:t}).eq("id",n);if(a)throw a}else{const{data:r}=await q.from("innercircle_contacts").select("spouse_contact_id").eq("id",t).single(),a=r==null?void 0:r.spouse_contact_id,{error:i}=await q.from("innercircle_contacts").update({spouse_contact_id:null}).eq("id",t);if(i)throw i;if(a){const{error:l}=await q.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"]}),_a({title:"Spouse link updated"})},onError:t=>{_a({title:"Error linking spouse",description:t.message,variant:"destructive"})}})},zUt=()=>{const s=Vt();return ft({mutationFn:async t=>{const{error:n}=await q.from("innercircle_contacts").delete().eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["innercircle-contacts"]}),s.invalidateQueries({queryKey:["innercircle-contact-counts"]}),_a({title:"Contact deleted successfully"})},onError:t=>{_a({title:"Error deleting contact",description:t.message,variant:"destructive"})}})},$Hs=()=>{const s=Vt();return ft({mutationFn:async({ids:t,onProgress:n})=>{let a=0;for(let i=0;i{s.invalidateQueries({queryKey:["innercircle-contacts"]}),s.invalidateQueries({queryKey:["innercircle-contact-counts"]}),s.invalidateQueries({queryKey:["all-contact-custom-tags"]})}})},iie=()=>tt({queryKey:["action-types"],queryFn:async()=>{const{data:s,error:t}=await q.from("action_types").select("*").order("sort_order");if(t)throw t;return s}}),UHs=s=>tt({queryKey:["action-scripts",s],queryFn:async()=>{let t=q.from("action_scripts").select("*, action_type:action_types(*)");const{data:n,error:r}=await t;if(r)throw r;return n}}),qHs=()=>tt({queryKey:["touchpoint-plans"],queryFn:async()=>{const{data:s,error:t}=await q.from("touchpoint_plans").select(` *, items:touchpoint_plan_items( *, action_type:action_types(*), default_script:action_scripts(*) ) `).order("name");if(t)throw t;return s}}),VHs=()=>{const s=Vt(),t=Sa();return ft({mutationFn:async({name:n,description:r})=>{const{data:a,error:i}=await q.from("touchpoint_plans").insert({name:n,description:r,owner_user_id:t,active:!0,is_template:!1}).select().single();if(i)throw i;return a},onSuccess:()=>{s.invalidateQueries({queryKey:["touchpoint-plans"]}),_a({title:"Plan created successfully"})},onError:n=>{_a({title:"Error creating plan",description:n.message,variant:"destructive"})}})},HHs=()=>{const s=Vt(),t=Sa();return ft({mutationFn:async({sourcePlanId:n,newName:r})=>{const{data:a,error:i}=await q.from("touchpoint_plans").select(` *, items:touchpoint_plan_items(*) `).eq("id",n).single();if(i)throw i;if(!a)throw new Error("Source plan not found");const{data:l,error:o}=await q.from("touchpoint_plans").insert({name:r,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(u=>({plan_id:l.id,month_number:u.month_number,action_type_id:u.action_type_id,default_script_id:u.default_script_id,notes:u.notes})),{error:d}=await q.from("touchpoint_plan_items").insert(c);if(d)throw d}return l},onSuccess:()=>{s.invalidateQueries({queryKey:["touchpoint-plans"]}),_a({title:"Plan duplicated successfully",description:"You can now edit your copy of this plan."})},onError:n=>{_a({title:"Error duplicating plan",description:n.message,variant:"destructive"})}})},GHs=()=>{const s=Vt();return ft({mutationFn:async({id:t,name:n,description:r})=>{const{data:a,error:i}=await q.from("touchpoint_plans").update({name:n,description:r}).eq("id",t).select().single();if(i)throw i;return a},onSuccess:()=>{s.invalidateQueries({queryKey:["touchpoint-plans"]}),_a({title:"Plan updated successfully"})}})},WHs=()=>{const s=Vt();return ft({mutationFn:async t=>{const{error:n}=await q.from("touchpoint_plans").delete().eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["touchpoint-plans"]}),_a({title:"Plan deleted successfully"})}})},KHs=()=>{const s=Vt();return ft({mutationFn:async({planId:t,items:n})=>{if(await q.from("touchpoint_plan_items").delete().eq("plan_id",t),n.length>0){const{error:r}=await q.from("touchpoint_plan_items").insert(n.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(r)throw r}},onSuccess:()=>{s.invalidateQueries({queryKey:["touchpoint-plans"]}),_a({title:"Plan schedule updated"})}})},YHs=()=>{const s=Vt();return ft({mutationFn:async({actionTypeId:t,title:n,scriptBody:r,emailSubject:a,tone:i})=>{const{data:{user:l}}=await q.auth.getUser(),{data:o,error:c}=await q.from("action_scripts").insert({action_type_id:t,title:n,script_body:r,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"]}),_a({title:"Script created successfully"})},onError:t=>{_a({title:"Error creating script",description:t.message,variant:"destructive"})}})},ZHs=()=>{const s=Sa();return tt({queryKey:["user-plan-enrollments",s],queryFn:async()=>{const{data:t,error:n}=await q.from("user_plan_enrollments").select(` *, plan:touchpoint_plans(*), relationship_type:relationship_types(*) `);if(n)throw n;return t},enabled:!!s})},XHs=()=>{const s=Vt(),t=Sa();return ft({mutationFn:async({planId:n,relationshipTypeId:r,active:a})=>{const{data:i}=await q.from("user_plan_enrollments").select("id").eq("plan_id",n).eq("relationship_type_id",r).maybeSingle();if(i){const{error:l}=await q.from("user_plan_enrollments").update({active:a}).eq("id",i.id);if(l)throw l}else if(a){const{error:l}=await q.from("user_plan_enrollments").insert({owner_user_id:t,plan_id:n,relationship_type_id:r,active:!0,start_date:new Date().toISOString().split("T")[0]});if(l)throw l}},onSuccess:()=>{s.invalidateQueries({queryKey:["user-plan-enrollments"]}),_a({title:"Plan enrollment updated"})}})},pK=(s=7)=>{const t=Sa();return tt({queryKey:["contact-touch-logs",t,s],queryFn:async()=>{const n=new Date;n.setDate(n.getDate()-s);const{data:r,error:a}=await q.from("contact_touch_logs").select(` *, contact:innercircle_contacts(*), action_type:action_types(*) `).eq("owner_user_id",t).gte("completed_at",n.toISOString()).order("completed_at",{ascending:!1});if(a)throw a;return r},enabled:!!t})},BUt=()=>{const s=Sa();return tt({queryKey:["contacts-last-touch",s],queryFn:async()=>{const{data:t,error:n}=await q.from("contact_touch_logs").select("contact_id, completed_at").eq("owner_user_id",s).order("completed_at",{ascending:!1});if(n)throw n;const r={};return t==null||t.forEach(a=>{r[a.contact_id]||(r[a.contact_id]=a.completed_at)}),r},enabled:!!s})},QHs=(s=90)=>{const{data:t}=z_(),{data:n}=BUt();if(!t||!n)return{contacts:[],count:0};const r=new Date;r.setDate(r.getDate()-s);const a=t.filter(i=>{const l=n[i.id];return l?new Date(l){const s=Vt(),t=Sa();return ft({mutationFn:async({contactId:n,actionTypeId:r,scriptUsedId:a,notes:i,completedAt:l})=>{const{data:o,error:c}=await q.from("contact_touch_logs").insert({owner_user_id:t,contact_id:n,action_type_id:r,script_used_id:a,notes:i,completed_at:l||new Date().toISOString()}).select().single();if(c)throw c;return o},onSuccess:async(n,r)=>{var a,i;s.invalidateQueries({queryKey:["contact-touch-logs"]}),s.invalidateQueries({queryKey:["contacts-last-touch"]}),s.invalidateQueries({queryKey:["today-actions"]}),s.invalidateQueries({queryKey:["popby-logs"]}),_a({title:"Action completed!"});try{const[l,o]=await Promise.all([q.from("innercircle_contacts").select("email").eq("id",r.contactId).single(),q.from("action_types").select("name").eq("id",r.actionTypeId).single()]),c=(a=l.data)==null?void 0:a.email,d=((i=o.data)==null?void 0:i.name)||"Touch";/pop[\s-]?by/i.test(d)&&q.from("popby_logs").insert({owner_user_id:t,contact_id:r.contactId,notes:r.notes??null,completed_at:r.completedAt||n.completed_at}).then(()=>{s.invalidateQueries({queryKey:["popby-logs"]})}),c&&q.functions.invoke("boldtrail-sync",{body:{action:"push_touch",contact_email:c,touch_type:d,touch_notes:r.notes||null,touch_date:r.completedAt||n.completed_at}}).catch(()=>{})}catch{}}})},$Ut="agentos_weekly_touch_goal",gbt=20,UUt=()=>{if(typeof window>"u")return gbt;const s=localStorage.getItem($Ut);if(s){const t=parseInt(s,10);if(!isNaN(t)&&t>0)return t}return gbt},JHs=s=>{localStorage.setItem($Ut,s.toString())},k6e=()=>{const{data:s}=pK(7),t=new Date;t.setHours(0,0,0,0);const n=new Date(t);n.setDate(t.getDate()-t.getDay());const r=(s==null?void 0:s.filter(l=>new Date(l.completed_at)>=n).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=UUt();return{actionsThisWeek:r,weeklyGoal:i,streak:a,progress:Math.min(r/i*100,100)}},eGs=()=>{const s=Sa();return tt({queryKey:["contact-plan-cycles",s],queryFn:async()=>{const{data:t,error:n}=await q.from("contact_plan_cycles").select(` *, contact:innercircle_contacts(*), plan:touchpoint_plans( *, items:touchpoint_plan_items( *, action_type:action_types(*), default_script:action_scripts(*) ) ) `);if(n)throw n;return t},enabled:!!s})},tGs=()=>{const s=Vt();return Sa(),ft({mutationFn:async()=>{var c;const{data:t}=await q.from("user_plan_enrollments").select("*").eq("active",!0);if(!t||t.length===0)return;const{data:n}=await q.auth.getUser(),r=(c=n==null?void 0:n.user)==null?void 0:c.id;if(!r)return;const{data:a}=await q.from("innercircle_contacts").select(` id, tags:innercircle_contact_tags(relationship_type_id) `).eq("owner_user_id",r);if(!a)return;const{data:i}=await q.from("contact_plan_cycles").select("contact_id, plan_id"),l=new Set((i==null?void 0:i.map(d=>`${d.contact_id}-${d.plan_id}`))||[]),o=[];for(const d of a)for(const u of d.tags||[]){const h=t.find(m=>m.relationship_type_id===u.relationship_type_id);h&&!l.has(`${d.id}-${h.plan_id}`)&&o.push({contact_id:d.id,plan_id:h.plan_id,relationship_type_id:u.relationship_type_id})}if(o.length>0){const{error:d}=await q.from("contact_plan_cycles").insert(o);if(d)throw d}return o.length},onSuccess:t=>{s.invalidateQueries({queryKey:["contact-plan-cycles"]}),t&&t>0&&_a({title:`${t} contact(s) enrolled in plans`})}})},ont=()=>{const s=Sa(),{data:t}=eGs(),{data:n}=pK(30);return tt({queryKey:["today-actions",s,t==null?void 0:t.length,n==null?void 0:n.length],queryFn:async()=>{var g;if(!t||t.length===0)return[];const{data:r}=await q.from("contact_snoozes").select("contact_id").gte("snoozed_until",new Date().toISOString()),a=new Set((r==null?void 0:r.map(x=>x.contact_id))||[]),i=new Date,l=[],o=new Date(i.getFullYear(),i.getMonth(),1),c=new Set((n==null?void 0:n.filter(x=>new Date(x.completed_at)>=o).map(x=>`${x.contact_id}-${x.action_type_id}`))||[]);for(const x of t){if(!((g=x.plan)!=null&&g.items)||x.plan.items.length===0||!x.contact||a.has(x.contact_id))continue;const y=new Date(x.cycle_start_date),b=Math.floor((i.getTime()-y.getTime())/(30.44*24*60*60*1e3))%12+1,w=x.plan.items.find(S=>S.month_number===b);if(w&&w.action_type){const S=`${x.contact_id}-${w.action_type_id}`;if(!c.has(S)){const{data:C}=await q.from("relationship_types").select("name").eq("id",x.relationship_type_id).single();l.push({contact:x.contact,actionType:w.action_type,script:w.default_script||void 0,planName:x.plan.name,relationshipTypeName:(C==null?void 0:C.name)||"",monthNumber:b})}}}const d=5,u=i.getDate(),h=l.sort((x,y)=>x.contact.first_name.localeCompare(y.contact.first_name)),m=(u-1)%Math.max(1,h.length);return[...h.slice(m),...h.slice(0,m)].slice(0,d)},enabled:!!s&&!!t})};function sGs(){const{user:s}=vs(),{limitFor:t,isRestricted:n}=jC(),r=n?t("mass_email"):null,{data:a=0,refetch:i}=tt({queryKey:["mass-email-usage",s==null?void 0:s.id],enabled:!!(s!=null&&s.id)&&!!r,staleTime:60*1e3,queryFn:async()=>{const o=new Date;o.setDate(1),o.setHours(0,0,0,0);const{count:c}=await q.from("bulk_email_sends").select("id",{count:"exact",head:!0}).eq("user_id",s.id).gte("sent_at",o.toISOString());return c||0}}),l=r===null?1/0:Math.max(0,r-a);return{limit:r,used:a,remaining:l,wouldExceed:o=>r!==null&&o>l,refetch:i}}function nGs({onSelect:s}){const{user:t}=vs(),[n,r]=j.useState("root"),[a,i]=j.useState(null),{data:l=[],isLoading:o}=tt({queryKey:["agent-email-template-categories"],queryFn:async()=>{const{data:v,error:b}=await q.from("email_template_categories").select("*").order("sort_order");if(b)throw b;return v}}),{data:c=[],isLoading:d}=tt({queryKey:["agent-email-templates",a],enabled:n==="category"&&!!a,queryFn:async()=>{const{data:v,error:b}=await q.from("agent_email_templates").select("*").eq("is_active",!0).eq("category_id",a).order("sort_order");if(b)throw b;return v}}),{data:u=[],isLoading:h}=tt({queryKey:["picker-campaign-templates",t==null?void 0:t.id],enabled:!!t,queryFn:async()=>{const{data:v,error:b}=await q.from("campaign_templates").select("id,name,subject,body_html,is_shared,user_id,updated_at").or(`user_id.eq.${t.id},is_shared.eq.true`).order("updated_at",{ascending:!1});if(b)throw b;return v}}),m=u.filter(v=>v.user_id===(t==null?void 0:t.id)&&!v.is_shared),f=u.filter(v=>v.is_shared),g=l.find(v=>v.id===a);if(o)return e.jsx("div",{className:"flex items-center justify-center py-6",children:e.jsx(kt,{className:"h-5 w-5 animate-spin text-muted-foreground"})});const x=v=>{s({title:v.name,subject:v.subject,body:v.body_html})};if(n==="root")return e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"text-xs font-medium text-muted-foreground px-1 mb-1.5",children:"Your templates"}),e.jsxs("button",{onClick:()=>r("my"),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("div",{className:"h-8 w-8 rounded-md bg-primary/10 text-primary flex items-center justify-center",children:e.jsx(sl,{className:"h-4 w-4"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-sm",children:"My Saved Templates"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[m.length," template",m.length===1?"":"s"," you've created"]})]})]}),e.jsx(Di,{className:"h-4 w-4 text-muted-foreground shrink-0"})]}),e.jsxs("button",{onClick:()=>r("shared"),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("div",{className:"h-8 w-8 rounded-md bg-blue-500/10 text-blue-600 dark:text-blue-400 flex items-center justify-center",children:e.jsx(dl,{className:"h-4 w-4"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-sm",children:"Shared Library"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[f.length," team template",f.length===1?"":"s"]})]})]}),e.jsx(Di,{className:"h-4 w-4 text-muted-foreground shrink-0"})]})]}),l.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"text-xs font-medium text-muted-foreground px-1 mb-1.5",children:"Quick scripts by category"}),e.jsx("div",{className:"max-h-[200px] overflow-y-auto space-y-1 pr-1",children:l.map(v=>e.jsxs("button",{onClick:()=>{i(v.id),r("category")},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:v.icon}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-sm",children:v.name}),v.description&&e.jsx("p",{className:"text-xs text-muted-foreground line-clamp-1",children:v.description})]})]}),e.jsx(Di,{className:"h-4 w-4 text-muted-foreground shrink-0"})]},v.id))})]})]});const y=e.jsxs("button",{onClick:()=>{r("root"),i(null)},className:"flex items-center gap-1 text-sm text-muted-foreground hover:text-foreground transition-colors",children:[e.jsx(Cd,{className:"h-3.5 w-3.5"}),"Back"]});return n==="my"?e.jsxs("div",{className:"space-y-2",children:[y,e.jsxs("p",{className:"text-xs font-medium flex items-center gap-1.5",children:[e.jsx(sl,{className:"h-3.5 w-3.5"})," My Saved Templates"]}),h?e.jsx("div",{className:"flex items-center justify-center py-6",children:e.jsx(kt,{className:"h-5 w-5 animate-spin text-muted-foreground"})}):m.length===0?e.jsxs("div",{className:"text-center py-6 space-y-2",children:[e.jsx(Nn,{className:"h-6 w-6 text-muted-foreground mx-auto"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"You haven't created any templates yet."}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Create beautiful templates in ",e.jsx("span",{className:"font-medium",children:"Email Templates"})," in the sidebar — they'll appear here."]})]}):e.jsx(uo,{className:"max-h-[280px]",children:e.jsx("div",{className:"space-y-1",children:m.map(v=>e.jsxs("button",{onClick:()=>x(v),className:"w-full p-2.5 rounded-lg border hover:bg-accent transition-colors text-left",children:[e.jsx("p",{className:"font-medium text-sm truncate",children:v.name}),e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5 line-clamp-1",children:v.subject||"(no subject)"})]},v.id))})})]}):n==="shared"?e.jsxs("div",{className:"space-y-2",children:[y,e.jsxs("p",{className:"text-xs font-medium flex items-center gap-1.5",children:[e.jsx(dl,{className:"h-3.5 w-3.5"})," Shared Library"]}),h?e.jsx("div",{className:"flex items-center justify-center py-6",children:e.jsx(kt,{className:"h-5 w-5 animate-spin text-muted-foreground"})}):f.length===0?e.jsx("p",{className:"text-sm text-muted-foreground py-4 text-center",children:"No shared templates yet."}):e.jsx(uo,{className:"max-h-[280px]",children:e.jsx("div",{className:"space-y-1",children:f.map(v=>e.jsxs("button",{onClick:()=>x(v),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 truncate",children:v.name}),e.jsx(Be,{variant:"secondary",className:"text-[10px] shrink-0",children:"Shared"})]}),e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5 line-clamp-1",children:v.subject||"(no subject)"})]},v.id))})})]}):e.jsxs("div",{className:"space-y-2",children:[y,e.jsxs("p",{className:"text-xs font-medium flex items-center gap-1.5",children:[e.jsx("span",{children:g==null?void 0:g.icon})," ",g==null?void 0:g.name]}),d?e.jsx("div",{className:"flex items-center justify-center py-6",children:e.jsx(kt,{className:"h-5 w-5 animate-spin text-muted-foreground"})}):c.length===0?e.jsx("p",{className:"text-sm text-muted-foreground py-4 text-center",children:"No templates in this category"}):e.jsx(uo,{className:"max-h-[280px]",children:e.jsx("div",{className:"space-y-1",children:c.map(v=>e.jsxs("button",{onClick:()=>s(v),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:v.title}),v.tone&&e.jsx(Be,{variant:"secondary",className:"text-[10px] shrink-0",children:v.tone})]}),e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5 line-clamp-1",children:v.subject})]},v.id))})})]})}function u6(){var a;const{user:s}=vs(),{data:t,isLoading:n}=tt({queryKey:["mass-email-settings",s==null?void 0:s.id],enabled:!!s,staleTime:60*1e3,queryFn:async()=>{var d,u,h,m;const[i,l]=await Promise.all([q.from("mass_email_settings").select("reply_to_email, display_name").eq("user_id",s.id).maybeSingle(),q.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())||((u=c==null?void 0:c.email)==null?void 0:u.trim())||s.email||null,display_name:((h=o==null?void 0:o.display_name)==null?void 0:h.trim())||((m=c==null?void 0:c.name)==null?void 0:m.trim())||null}}});return{isReady:!!((a=t==null?void 0:t.reply_to_email)!=null&&a.trim()),isLoading:n,settings:t}}function oie(){const{user:s}=vs();return tt({queryKey:["verified-sender-check",s==null?void 0:s.id],enabled:!!s,staleTime:3e4,queryFn:async()=>{const[t,n]=await Promise.all([q.from("user_verified_senders").select("id, email, status").eq("user_id",s.id),q.from("gmail_integrations").select("gmail_email, is_active").eq("user_id",s.id).eq("is_active",!0).maybeSingle()]),r=t.data||[],a=r.filter(l=>l.status==="verified"),i=r.filter(l=>l.status==="pending");return{hasVerifiedSes:a.length>0,hasPendingSes:i.length>0,hasAnySender:r.length>0,hasGmail:!!n.data,verifiedEmails:a.map(l=>l.email),pendingEmails:i.map(l=>l.email)}}})}function S6e({open:s,onOpenChange:t,hasPending:n,pendingEmails:r}){const a=Qn();return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Os,{className:"sm:max-w-md",children:[e.jsxs(Us,{children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx("div",{className:"h-9 w-9 rounded-full bg-amber-500/10 text-amber-600 flex items-center justify-center",children:e.jsx(ll,{className:"h-5 w-5"})}),e.jsx(Bs,{children:"Verify your sending email first"})]}),e.jsx(Ir,{className:"pt-2",children:`Before you can send emails through Amazon, your "from" address needs to be verified so inboxes trust it and it doesn't land in spam.`})]}),n&&r&&r.length>0?e.jsxs("div",{className:"rounded-lg border bg-amber-500/5 p-3 space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm font-medium text-amber-700",children:[e.jsx(da,{className:"h-4 w-4"})," Waiting for you to click Amazon's link"]}),r.map(i=>e.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[e.jsx(mn,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"truncate",children:i})]},i)),e.jsx("p",{className:"text-xs text-muted-foreground pt-1",children:"Check that inbox (and your spam folder) for an email from Amazon Web Services and click the verification link."})]}):e.jsx("div",{className:"rounded-lg border bg-muted/40 p-3 text-sm text-muted-foreground",children:"It only takes a minute — add your email address on the Integrations page, then click the verification link Amazon sends you."}),e.jsxs(Ar,{className:"gap-2 sm:gap-2",children:[e.jsx($,{variant:"outline",onClick:()=>t(!1),children:"Not now"}),e.jsxs($,{onClick:()=>{t(!1),a("/mission-control/integrations")},children:[e.jsx(kr,{className:"h-4 w-4 mr-1"}),n?"Manage senders":"Verify my email"]})]})]})})}function C6e(){const{user:s}=vs(),t=Vt(),{data:n,isLoading:r}=tt({queryKey:["contact-intake-page",s==null?void 0:s.id],queryFn:async()=>{if(!(s!=null&&s.id))return null;const{data:d,error:u}=await q.from("contact_intake_pages").select("*").eq("user_id",s.id).maybeSingle();if(u)throw u;return d},enabled:!!(s!=null&&s.id)}),a=ft({mutationFn:async d=>{if(!(s!=null&&s.id))throw new Error("Not authenticated");const{data:u,error:h}=await q.from("contact_intake_pages").insert({user_id:s.id,slug:d.toLowerCase().replace(/[^a-z0-9-]/g,"-")}).select().single();if(h)throw h;return u},onSuccess:()=>{t.invalidateQueries({queryKey:["contact-intake-page"]}),re.success("Connect page created!")},onError:d=>{var u;(u=d.message)!=null&&u.includes("duplicate")?re.error("That slug is already taken. Try another."):re.error("Failed to create page")}}),i=ft({mutationFn:async d=>{if(!(n!=null&&n.id))throw new Error("No intake page");const{error:u}=await q.from("contact_intake_pages").update({...d,updated_at:new Date().toISOString()}).eq("id",n.id);if(u)throw u},onSuccess:()=>{t.invalidateQueries({queryKey:["contact-intake-page"]}),re.success("Page updated!")},onError:()=>re.error("Failed to update page")}),{data:l=[],isLoading:o}=tt({queryKey:["contact-intake-submissions",s==null?void 0:s.id],queryFn:async()=>{if(!(s!=null&&s.id))return[];const{data:d,error:u}=await q.from("contact_intake_submissions").select("*").eq("agent_user_id",s.id).order("created_at",{ascending:!1}).limit(100);if(u)throw u;return d},enabled:!!(s!=null&&s.id)}),c=ft({mutationFn:async d=>{if(!(n!=null&&n.id))throw new Error("No intake page. Create your Connect page first.");const{data:u,error:h}=await q.from("contact_intake_tokens").insert({contact_id:d,intake_page_id:n.id}).select("token").single();if(h)throw h;return`${window.location.origin}/connect/${n.slug}?t=${u.token}`}});return{intakePage:n,isLoading:r,createPage:a,updatePage:i,submissions:l,loadingSubmissions:o,generateUpdateLink:c}}function qUt({value:s,onChange:t,userId:n,placeholder:r}){const[a,i]=j.useState(!1),[l,o]=j.useState([]),[c,d]=j.useState(!1),[u,h]=j.useState(0),m=j.useRef(null),f=j.useRef(null);j.useEffect(()=>{const x=y=>{m.current&&!m.current.contains(y.target)&&i(!1)};return document.addEventListener("mousedown",x),()=>document.removeEventListener("mousedown",x)},[]),j.useEffect(()=>{f.current&&clearTimeout(f.current);const x=s.trim();if(!n||x.length<1||x.includes("@")&&x.indexOf("@")>0&&/\S+@\S+\.\S+/.test(x)){o([]);return}return f.current=setTimeout(async()=>{d(!0);const y=`%${x}%`,v=q,{data:b,error:w}=await v.from("innercircle_contacts").select("id, first_name, last_name, email").eq("owner_user_id",n).not("email","is",null).or(`first_name.ilike.${y},last_name.ilike.${y},email.ilike.${y}`).order("first_name",{ascending:!0}).limit(8);d(!1),!w&&b&&(o(b),h(0),i(b.length>0))},180),()=>{f.current&&clearTimeout(f.current)}},[s,n]);const g=x=>{x.email&&(t(x.email),i(!1))};return e.jsxs("div",{ref:m,className:"relative",children:[e.jsx(pe,{id:"gmail-to",value:s,onChange:x=>t(x.target.value),onFocus:()=>l.length>0&&i(!0),onKeyDown:x=>{!a||l.length===0||(x.key==="ArrowDown"?(x.preventDefault(),h(y=>Math.min(y+1,l.length-1))):x.key==="ArrowUp"?(x.preventDefault(),h(y=>Math.max(y-1,0))):x.key==="Enter"?(x.preventDefault(),g(l[u])):x.key==="Escape"&&i(!1))},placeholder:r||"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(kt,{className:"h-3 w-3 animate-spin"})," Searching..."]}):l.map((x,y)=>{const v=[x.first_name,x.last_name].filter(Boolean).join(" ")||"(No name)";return e.jsxs("button",{type:"button",onMouseEnter:()=>h(y),onClick:()=>g(x),className:`w-full flex items-center gap-2 px-3 py-2 text-left text-sm border-b last:border-b-0 ${y===u?"bg-accent":"bg-popover"}`,children:[e.jsx(sl,{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:v}),e.jsx("div",{className:"text-xs text-muted-foreground truncate",children:x.email})]})]},x.id)})})]})}function rGs(){const{user:s}=vs(),{data:t,isLoading:n}=tt({queryKey:["email-signature",s==null?void 0:s.id],enabled:!!(s!=null&&s.id),staleTime:5*60*1e3,queryFn:async()=>{const{data:a,error:i}=await q.from("profiles").select("email_signature, use_email_signature").eq("id",s.id).maybeSingle();if(i)throw i;return a}}),r=((t==null?void 0:t.email_signature)||"").trim();return{signatureHtml:r,hasSignature:r.length>0,signatureEnabledByDefault:!!(t!=null&&t.use_email_signature)&&r.length>0,isLoading:n}}function aGs(s,t){if(!t||s.includes(t))return s;const n=`
${t}
`;return/<\/body>/i.test(s)?s.replace(/<\/body>/i,`${n}`):`${s}${n}`}function iGs(s){if(!/<[a-z][\s\S]*>/i.test(s)||typeof window>"u")return s;const t=s.replace(/<\s*(br|\/p|\/div|\/li|\/h[1-6]|\/tr)\s*[^>]*>/gi,` `).replace(/<\s*li\b[^>]*>/gi,"• ").replace(/<\s*(p|div|h[1-6]|tr)\b[^>]*>/gi,""),n=document.createElement("div");return n.innerHTML=t,(n.textContent||n.innerText||"").replace(/\u00a0/g," ").replace(/\n{3,}/g,` `).trim()}const sBe=25*1024*1024,xbt=Math.floor(6.5*1024*1024),oGs=750*1024,iN=50,lGs=["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 ade(s){return s<1024?s+" B":s<1024*1024?(s/1024).toFixed(1)+" KB":(s/(1024*1024)).toFixed(1)+" MB"}function cGs(s){return new Promise((t,n)=>{const r=new FileReader;r.onload=()=>{const a=r.result;t(a.split(",")[1])},r.onerror=n,r.readAsDataURL(s)})}function dGs(s){if(!s)return"";const t=s.trim();return t.split(/\s+/)[0]||t}function yj(s,t){const n=dGs(t.first_name),r=t.last_name||"";let a=s.replace(/\{\{first_name\}\}/gi,n).replace(/\{\{last_name\}\}/gi,r).replace(/\{\{full_name\}\}/gi,`${n} ${r}`.trim());return t.updateLink&&(a=a.replace(/\{\{update_link\}\}/gi,t.updateLink)),a}function Ak({open:s,onOpenChange:t,contact:n,bulkContacts:r,defaultSubject:a="",defaultBody:i="",gmailEmail:l,onSendComplete:o,sendSource:c,logTouchpoint:d=!0}){const{user:u}=vs(),h=Vt(),{isReady:m,settings:f}=u6(),{data:g}=oie(),[x,y]=j.useState(!1),{intakePage:v}=C6e(),b=v?`https://contacts.relevelup.com/${v.slug}`:null,w=!!r&&r.length>0,S=sGs(),C=m,E=w?r:n?[n]:[],I=E[0],P=w?Math.ceil(E.length/iN):1,R=w&&E.length>iN,[D,O]=j.useState((I==null?void 0:I.email)||""),[U,W]=j.useState(a),[V,G]=j.useState(i),[Y,X]=j.useState(!1),[ae,ie]=j.useState(!1),[ne,te]=j.useState([]),J=j.useRef(new Map),[ce,_e]=j.useState(a),[he,ue]=j.useState(i),[ve,Ee]=j.useState(!1),[Se,Le]=j.useState("composing"),[Fe,ke]=j.useState(0),[Ve,je]=j.useState(0),[Ae,Ce]=j.useState(0),[qe,ze]=j.useState(0),$e=j.useRef(!1),ct=j.useRef(0),[Xe,it]=j.useState(!0),{signatureHtml:at,hasSignature:Ke}=rGs(),[nt,xt]=j.useState(!0),[rt,Yt]=j.useState(null),qt=Jn=>{let Sr=5381;for(let Un=0;Un>>0;return Sr.toString(36)},ts=w?`bulk-${E.length}-${qt(E.map(Jn=>Jn.id||Jn.email||"").join("|"))}`:(I==null?void 0:I.id)||"adhoc",ys=qt(`${a||""}::${(i||"").slice(0,400)}`),Bt=`levelup:email-draft:${ts}:${ys}`,[Ft,rs]=j.useState(!1),St=j.useRef(!1),Xs=()=>{try{localStorage.removeItem(Bt)}catch{}rs(!1)};j.useEffect(()=>{s&&xt(Ke)},[s,Ke]),j.useEffect(()=>{if(s){const Jn=/<[a-z][\s\S]*>/i.test(i),Sr=Jn?iGs(i):i;Ys.current=Jn?{plain:Sr,html:i}:null,O((I==null?void 0:I.email)||""),_e(a),ue(Sr),W(yj(a,I||{first_name:""})),G(yj(Sr,I||{first_name:""})),ie(!a&&!i),Ee(!1),Ws(Un=>Un+1),te([]),J.current=new Map,Le("composing"),ke(0),je(0),Ce(0),ze(0),$e.current=!1,ct.current=0,Yt(null);try{const Un=localStorage.getItem(Bt);if(Un){const ur=JSON.parse(Un),Pa=(ur==null?void 0:ur.savedAt)&&Date.now()-ur.savedAt<14*24*60*60*1e3,ii=(ur==null?void 0:ur.rawSubject)||(ur==null?void 0:ur.rawBody)||(ur==null?void 0:ur.html);Pa&&ii&&(ur.to&&O(ur.to),_e(ur.rawSubject||""),ue(ur.rawBody||""),W(yj(ur.rawSubject||"",I||{first_name:""})),G(yj(ur.rawBody||"",I||{first_name:""})),ur.html&&(Ys.current={plain:ur.rawBody||"",html:ur.html}),ie(!1),Ws($i=>$i+1),rs(!0))}}catch{}St.current=!0}else St.current=!1},[s,I,a,i]),j.useEffect(()=>{if(!s||!St.current||Se!=="composing")return;const Jn=Ys.current,Sr={to:D,rawSubject:ce,rawBody:he,html:Jn&&he===Jn.plain?Jn.html:null,savedAt:Date.now()},Un=()=>{try{if(!ce&&!he)return;localStorage.setItem(Bt,JSON.stringify({...Sr,savedAt:Date.now(),html:Ys.current&&he===Ys.current.plain?Ys.current.html:null}))}catch{}},ur=setTimeout(Un,600);return window.addEventListener("blur",Un),document.addEventListener("visibilitychange",Un),()=>{clearTimeout(ur),window.removeEventListener("blur",Un),document.removeEventListener("visibilitychange",Un)}},[s,D,ce,he,Se,Bt]);const vt=async Jn=>{const Sr=Jn.target.files;if(!Sr)return;const Un=ne.reduce((ii,$i)=>ii+$i.size,0),ur=[];let Pa=Un;for(const ii of Array.from(Sr)){if(!lGs.includes(ii.type)){re.error(`${ii.name}: Unsupported file type`);continue}if(Pa+ii.size>sBe){re.error(`Total attachments exceed ${ade(sBe)} limit`);break}try{const $i=await cGs(ii);ur.push({name:ii.name,type:ii.type,size:ii.size,data:$i}),Pa+=ii.size}catch{re.error(`Failed to read ${ii.name}`)}}te(ii=>[...ii,...ur]),Jn.target.value=""},gs=Jn=>{const Sr=ne[Jn];Sr&&J.current.delete(`${Sr.name}::${Sr.size}`),te(Un=>Un.filter((ur,Pa)=>Pa!==Jn))},Ss=async()=>{if(ne.length===0||!u)return{inline:[],paths:[]};const Jn=[],Sr=[];for(const Un of ne){const ur=`${Un.name}::${Un.size}`,Pa=J.current.get(ur);if(Pa){Sr.push(Pa);continue}if(Un.size<=oGs){Jn.push(Un);continue}const ii=Un.name.replace(/[^a-zA-Z0-9._-]/g,"_"),$i=`${u.id}/${Date.now()}-${ii}`,Rn=atob(Un.data),xa=new Uint8Array(Rn.length);for(let ho=0;ho{if(!/<[a-z][\s\S]*>/i.test(Jn)||typeof window>"u")return Jn;const Sr=Jn.replace(/<\s*(br|\/p|\/div|\/li|\/h[1-6]|\/tr)\s*[^>]*>/gi,` `).replace(/<\s*li\b[^>]*>/gi,"• ").replace(/<\s*(p|div|h[1-6]|tr)\b[^>]*>/gi,""),Un=document.createElement("div");return Un.innerHTML=Sr,(Un.textContent||Un.innerText||"").replace(/\u00a0/g," ").replace(/\n{3,}/g,` `).trim()},Ys=j.useRef(null),cs=Ys.current&&he===Ys.current.plain?Ys.current.html:null,js=j.useRef(null),[kn,Ws]=j.useState(0),On=()=>{const Jn=js.current,Sr=Ys.current;!Jn||!Sr||(Ys.current={plain:Sr.plain,html:Jn.innerHTML})},ds=Jn=>{const Sr=/<[a-z][\s\S]*>/i.test(Jn.body),Un=Sr?Is(Jn.body):Jn.body;Ys.current=Sr?{plain:Un,html:Jn.body}:null,_e(Jn.subject),ue(Un),W(yj(Jn.subject,I||{first_name:""})),G(yj(Un,I||{first_name:""})),ie(!1),Ws(ur=>ur+1)},gn=Jn=>{let Sr=Jn.replace(/\[([^\]]+)\]\((https?:\/\/[^\s)]+|mailto:[^\s)]+)\)/g,(Un,ur,Pa)=>`${ur}`);return Sr=Sr.replace(/(^|[\s(])((?:https?:\/\/|www\.)[^\s<)]+)/g,(Un,ur,Pa)=>{const ii=Pa.startsWith("http")?Pa:`https://${Pa}`;return`${ur}${Pa}`}),Sr},As=Jn=>/<\s*(p|div|span|table|tr|td|img|br|h[1-6]|a|body|html|section|article|ul|ol|li)\b/i.test(Jn)?Jn:Jn.split(/\n\n+/).map(Sr=>`

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

`).join(""),hr=(Jn,Sr)=>{const Un="https://relzejiswnotikjgvjhz.supabase.co/functions/v1/bulk-email-track";let ur=Jn.replace(/]*?)href=(["'])(.*?)\2([^>]*)>/gi,(ii,$i,Rn,xa,Ya)=>{if(!xa||/^(mailto:|tel:|#)/i.test(xa)||xa.includes("/bulk-email-track")||xa.includes("/ses-campaign-track"))return ii;const ho=`${Un}?s=${Sr}&t=click&u=${encodeURIComponent(xa)}`;return``});const Pa=``;return/<\/body>/i.test(ur)?ur=ur.replace(/<\/body>/i,`${Pa}`):ur=`${ur}${Pa}`,ur},Er=async Jn=>{if(!(Jn!=null&&Jn.email))return re.error("Please enter a recipient email"),!1;const Sr=Jn||{first_name:""},Un=yj(ce,Sr),ur=Ys.current,Pa=ur&&he===ur.plain,ii=yj(Pa?ur.html:he,Sr);let $i=Pa?ii:As(ii);nt&&at&&($i=aGs($i,yj(at,Sr)));const Rn=u&&Jn.id?crypto.randomUUID():null;Rn&&($i=hr($i,Rn));try{if(u&&Jn.email){const ho=new Date(Date.now()-6e5).toISOString(),{data:Pc}=await q.from("bulk_email_sends").select("id").eq("user_id",u.id).eq("contact_email",Jn.email).eq("subject",Un).gte("sent_at",ho).limit(1);if(Pc&&Pc.length>0)return console.log(`Skipping duplicate send to ${Jn.email} (same subject within 10 min)`),re.info(`Skipped ${Jn.first_name||Jn.email} — already sent this in the last 10 min`),!0}const{inline:xa,paths:Ya}=await Ss();if(C){const ho=(f==null?void 0:f.display_name)||"ReLevelUp",Pc=`${ho.toLowerCase().replace(/[^a-z]/g,".")}@send.relevelup.com`,$d=`${ho} <${Pc}>`;let Nl=Ya[0];if(!Nl&&xa.length>0&&u){const Xr=xa[0],Eo=Xr.name.replace(/[^a-zA-Z0-9._-]/g,"_"),Ph=`${u.id}/${Date.now()}-${Eo}`,ih=atob(Xr.data),ao=new Uint8Array(ih.length);for(let xc=0;xc({name:$d,type:Nl,data:Ho})),attachment_paths:Ya,skip_signature:!0}});if(Pc)throw Pc;if(!(ho!=null&&ho.success))throw new Error((ho==null?void 0:ho.error)||"Failed to send")}if(u&&Jn.id&&Rn&&(await q.from("bulk_email_sends").insert({id:Rn,user_id:u.id,contact_id:Jn.id,contact_email:Jn.email,subject:Un,source:c||(C?"ses_bulk":"sphere_gaps")}),d))try{await q.from("contact_touch_logs").insert({owner_user_id:u.id,contact_id:Jn.id,action_type_id:"9a88a47c-cb2a-4401-a2b5-111a76b19f9d",notes:`Mass Email: ${Un}`,completed_at:new Date().toISOString()})}catch(ho){console.warn("touch log insert failed",ho)}return!0}catch(xa){return console.error("Send error:",xa),re.error("Failed to send to "+Jn.first_name+": "+(xa instanceof Error?xa.message:"Unknown error")),!1}},qn=()=>{const Jn=Fe*iN;return E.slice(Jn,Jn+iN)},hn=async(Jn=0,Sr=Xe)=>{if(!U||!V){re.error("Please fill in subject and message");return}X(!0),Le("sending");let Un=Math.max(0,Math.min(Jn,E.length)),ur=!1;for(;UnYa+1):Ce(Ya=>Ya+1),Rn<$i-1&&await new Promise(Ya=>setTimeout(Ya,150))}if(h.invalidateQueries({queryKey:["bulk-email-sends"]}),h.invalidateQueries({queryKey:["contact-touch-logs"]}),h.invalidateQueries({queryKey:["contacts-last-touch"]}),ur||$e.current||Un>=E.length)break;if(!Sr){X(!1),Le("batch_complete");return}if(ze(0),await new Promise(Rn=>setTimeout(Rn,1500)),$e.current){ur=!0;break}}X(!1),!ur&&!$e.current&&Xs(),Le(ur||$e.current?"batch_complete":"all_done")},Fn=async()=>{var Sr;if(!U||!V){re.error("Please fill in subject and message");return}const Jn=w?(r==null?void 0:r.length)||0:1;if(S.wouldExceed(Jn)){re.error(`Your package includes ${(Sr=S.limit)==null?void 0:Sr.toLocaleString()} emails per month. You have ${S.remaining.toLocaleString()} left — request an upgrade for unlimited sending.`);return}if(C&&g&&!g.hasVerifiedSes&&!g.hasGmail){y(!0);return}if(!w){const Un=I||{id:"",first_name:"",last_name:"",email:D.trim()};if(!Un.email){re.error("Please enter a recipient email");return}X(!0);try{await Er(Un)&&(h.invalidateQueries({queryKey:["bulk-email-sends"]}),Xs(),re.success("Email sent successfully!"),t(!1),o==null||o())}finally{X(!1)}return}$e.current=!1,ct.current=0,await hn(0)},vn=async()=>{$e.current=!1,ze(0),await hn(ct.current,!1)},xs=async()=>{$e.current=!1,it(!0),ze(0),await hn(ct.current,!0)},Lr=()=>{if(Y){$e.current=!0;return}t(!1),o==null||o()},Or=Fe*iN;Math.min(Or+iN,E.length);const ca=w&&E.length>0?Math.round((Ve+Ae)/E.length*100):0;return e.jsxs(zs,{open:s,onOpenChange:Lr,children:[e.jsxs(Os,{className:"sm:max-w-[600px] max-h-[90vh] overflow-y-auto",onPointerDownOutside:Jn=>{(ce||he)&&Jn.preventDefault()},onInteractOutside:Jn=>{(ce||he)&&Jn.preventDefault()},onEscapeKeyDown:Jn=>{(ce||he)&&Jn.preventDefault()},children:[e.jsxs(Us,{children:[e.jsxs(Bs,{className:"flex items-center gap-2",children:[e.jsx(mn,{className:`h-5 w-5 ${C?"text-orange-500":"text-red-500"}`}),w?`Send to ${E.length} Contacts`:"Compose Email"]}),C?e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Sending via ",e.jsx("span",{className:"font-medium",children:"Mass Email"})," (reply-to: ",f==null?void 0:f.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,w&&Se==="composing"&&e.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:["Composing email for ",e.jsxs("span",{className:"font-medium",children:[E.length," contacts"]}),". You'll review each personalized email before sending."]})]}),Ft&&Se==="composing"&&e.jsxs("div",{className:"flex items-center justify-between gap-2 rounded-lg border border-primary/30 bg-primary/5 px-3 py-2 text-xs",children:[e.jsx("span",{children:"We brought back the email you were writing."}),e.jsx($,{type:"button",variant:"ghost",size:"sm",className:"h-6 px-2 text-xs",onClick:()=>{Xs(),_e(""),ue(""),W(""),G(""),Ys.current=null,Ws(Jn=>Jn+1)},children:"Start fresh"})]}),Se==="sending"&&e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"text-center space-y-2",children:[e.jsx(kt,{className:"h-8 w-8 animate-spin mx-auto text-primary"}),e.jsxs("p",{className:"font-medium",children:["Sending batch ",Fe+1," of ",P,"..."]}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[qe," of ",qn().length," in this batch"]}),Xe&&P>1&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Auto-continuing through all ",P," batches — keep this window open."]})]}),e.jsx(Yi,{value:qe/Math.max(qn().length,1)*100,className:"h-2"}),e.jsxs("div",{className:"flex justify-between text-xs text-muted-foreground",children:[e.jsxs("span",{children:["Overall: ",Ve+Ae," / ",E.length]}),e.jsxs("span",{children:[Ve," sent • ",Ae," failed"]})]}),e.jsx($,{variant:"outline",size:"sm",className:"w-full",onClick:()=>{$e.current=!0},children:"Stop Sending"})]}),Se==="batch_complete"&&e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"text-center space-y-2",children:[e.jsx(qr,{className:"h-8 w-8 text-emerald-500 mx-auto"}),e.jsxs("p",{className:"font-medium",children:["Sending paused after batch ",Fe+1]}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[Ve," sent, ",Ae," failed so far"]})]}),e.jsx(Yi,{value:ca,className:"h-2"}),e.jsxs("p",{className:"text-xs text-center text-muted-foreground",children:[E.length-Ve-Ae," contacts remaining (",Math.max(P-Fe-1,0)," batches left)"]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx($,{variant:"outline",className:"flex-1",onClick:Lr,children:"Done for Now"}),e.jsxs($,{className:"flex-1 gap-2",onClick:xs,children:[e.jsx(Yr,{className:"h-4 w-4"}),"Resume Sending"]})]}),e.jsxs($,{variant:"ghost",size:"sm",className:"w-full",onClick:vn,children:["Send just the next ",Math.min(iN,Math.max(E.length-(Ve+Ae),0))," contacts"]})]}),Se==="all_done"&&e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"text-center space-y-2",children:[e.jsx(qr,{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:[Ve," emails sent successfully",Ae>0&&e.jsxs("span",{className:"text-destructive",children:[" • ",Ae," failed"]})]})]}),e.jsx($,{className:"w-full",onClick:Lr,children:"Close"})]}),Se==="composing"&&e.jsxs("div",{className:"space-y-4",children:[ae?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(Jr,{className:"h-4 w-4"})," Choose a Template"]}),e.jsxs($,{variant:"ghost",size:"sm",onClick:()=>ie(!1),className:"h-7 px-2 text-xs",children:[e.jsx(gr,{className:"h-3 w-3 mr-1"})," Write from scratch"]})]}),e.jsx(nGs,{onSelect:ds})]}):e.jsxs($,{variant:"outline",size:"sm",className:"gap-2",onClick:()=>ie(!0),children:[e.jsx(Jr,{className:"h-4 w-4"}),"Browse Templates"]}),e.jsx(Gc,{}),!w&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{htmlFor:"gmail-to",children:"To"}),e.jsx(qUt,{value:D,onChange:O,userId:u==null?void 0:u.id})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{htmlFor:"gmail-subject",children:"Subject"}),e.jsx(pe,{id:"gmail-subject",value:U,onChange:Jn=>{W(Jn.target.value),_e(Jn.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(ee,{htmlFor:"gmail-body",children:"Message"}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx(Be,{variant:"outline",className:"text-[10px] cursor-pointer hover:bg-accent",onClick:()=>{G(Jn=>Jn+"{{first_name}}"),ue(Jn=>Jn+"{{first_name}}")},children:"{{first_name}}"}),e.jsx(Be,{variant:"outline",className:"text-[10px] cursor-pointer hover:bg-accent",onClick:()=>{G(Jn=>Jn+"{{last_name}}"),ue(Jn=>Jn+"{{last_name}}")},children:"{{last_name}}"}),b&&e.jsx(Be,{variant:"outline",className:"text-[10px] cursor-pointer hover:bg-primary/10 border-primary/40 text-primary",onClick:()=>{const Jn=` When you get a sec, can you share your latest contact info with me? It only takes about a minute: ${b} `;G(Sr=>Sr+Jn),ue(Sr=>Sr+Jn)},title:"Insert your Connect Page link",children:"+ Connect Page"})]})]}),cs&&!ve?e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"overflow-hidden rounded-xl border bg-background",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2 border-b bg-muted/40 px-3 py-2",children:[e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx($,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0 font-bold",onMouseDown:Jn=>Jn.preventDefault(),onClick:()=>document.execCommand("bold"),title:"Bold",children:"B"}),e.jsx($,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0 italic",onMouseDown:Jn=>Jn.preventDefault(),onClick:()=>document.execCommand("italic"),title:"Italic",children:"I"}),e.jsx($,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0 underline",onMouseDown:Jn=>Jn.preventDefault(),onClick:()=>document.execCommand("underline"),title:"Underline",children:"U"}),e.jsx($,{type:"button",variant:"ghost",size:"sm",className:"h-7 px-2 text-xs",onMouseDown:Jn=>Jn.preventDefault(),onClick:()=>{const Jn=window.prompt("Link address (https://...)");Jn&&document.execCommand("createLink",!1,Jn)},title:"Add link",children:"Link"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("p",{className:"text-[11px] font-medium text-muted-foreground",children:"Click the email below to edit it"}),e.jsx($,{type:"button",variant:"ghost",size:"sm",className:"h-7 px-2 text-[11px] text-muted-foreground",onClick:()=>Ee(!0),children:"Plain text"})]})]}),e.jsx("div",{ref:js,contentEditable:!0,suppressContentEditableWarning:!0,onInput:On,onBlur:On,className:"max-h-[420px] overflow-y-auto p-1 outline-none focus-visible:ring-2 focus-visible:ring-ring/40 [&_img]:max-w-full",dangerouslySetInnerHTML:{__html:cs}},kn)]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Edit any text right here — ","{{first_name}}"," and ","{{last_name}}"," are swapped in for each person when it sends."]})]}):e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx($,{type:"button",variant:"outline",size:"sm",className:"h-7 px-2 text-xs",onClick:()=>{const Jn=document.getElementById("gmail-body"),Sr=Jn?V.slice(Jn.selectionStart,Jn.selectionEnd):"",Un=window.prompt("Link text (what the reader sees)",Sr||"Click here");if(!Un)return;let ur=window.prompt("Link address (https://...)","https://");if(!ur)return;ur=ur.trim(),/^(https?:\/\/|mailto:)/i.test(ur)||(ur=`https://${ur}`);const Pa=`[${Un}](${ur})`,ii=Jn?Jn.selectionStart:V.length,$i=Jn?Jn.selectionEnd:V.length,Rn=V.slice(0,ii)+Pa+V.slice($i);G(Rn),ue(Rn)},children:"Insert link"}),e.jsx("span",{className:"text-[11px] text-muted-foreground",children:"Web addresses you type become clickable automatically"})]}),e.jsx(Rs,{id:"gmail-body",value:V,onChange:Jn=>{G(Jn.target.value),ue(Jn.target.value)},placeholder:"Write your message...",rows:10,className:"resize-y"})]}),w&&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:"flex items-center justify-between rounded-md border bg-muted/30 px-3 py-2",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-xs font-medium",children:"Include my email signature"}),e.jsx("p",{className:"text-[11px] text-muted-foreground",children:Ke?"Your saved signature is added to the bottom of this email.":"Add a signature in Profile settings to use this."})]}),e.jsx(Sn,{checked:nt&&Ke,onCheckedChange:xt,disabled:!Ke})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs($,{type:"button",variant:"outline",size:"sm",className:"gap-2",onClick:()=>{var Jn;return(Jn=document.getElementById("gmail-attachments"))==null?void 0:Jn.click()},disabled:Y,children:[e.jsx(QI,{className:"h-4 w-4"}),"Attach Files"]}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:["PDF, images, Word, Excel (max ",ade(sBe)," 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:vt})]}),ne.length>0&&e.jsx("div",{className:"flex flex-wrap gap-2",children:ne.map((Jn,Sr)=>e.jsxs(Be,{variant:"secondary",className:"gap-1.5 pl-2 pr-1 py-1",children:[e.jsx(QI,{className:"h-3 w-3"}),e.jsx("span",{className:"max-w-[140px] truncate text-xs",children:Jn.name}),e.jsxs("span",{className:"text-[10px] text-muted-foreground",children:["(",ade(Jn.size),")"]}),e.jsx("button",{type:"button",onClick:()=>gs(Sr),className:"ml-0.5 rounded-full p-0.5 hover:bg-muted",children:e.jsx(gr,{className:"h-3 w-3"})})]},Sr))}),C&&ne.some(Jn=>Jn.size>xbt)&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Files over ",ade(xbt)," will be sent as secure download links."]})]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[e.jsx($,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),w?e.jsxs($,{onClick:()=>{Yt(E[0]||null),Le("reviewing")},disabled:!U||!V,className:"gap-2",children:["Review Emails",e.jsx(ei,{className:"h-4 w-4"})]}):e.jsxs($,{onClick:Fn,disabled:Y||!U||!V||!D.trim(),className:"gap-2",children:[Y?e.jsx(kt,{className:"h-4 w-4 animate-spin"}):e.jsx(Yr,{className:"h-4 w-4"}),Y?"Sending...":"Send Email"]})]})]}),Se==="reviewing"&&w&&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."]}),R&&e.jsxs("div",{className:"rounded-md border border-amber-500/30 bg-amber-500/5 px-2.5 py-2 space-y-2",children:[e.jsxs("p",{className:"text-xs text-amber-600",children:["📦 ",E.length," contacts will be sent in ",P," batches of up to ",iN,"."]}),e.jsxs("label",{className:"flex items-start gap-2 text-xs cursor-pointer",children:[e.jsx("input",{type:"checkbox",className:"mt-0.5 accent-current",checked:Xe,onChange:Jn=>it(Jn.target.checked)}),e.jsxs("span",{children:[e.jsx("span",{className:"font-medium",children:"Send all batches automatically"}),e.jsx("span",{className:"block text-muted-foreground",children:"Runs straight through every batch — no need to click Continue. Keep this window open; you can stop anytime."})]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs(ee,{children:["Recipients (",E.length,")"]}),e.jsx("div",{className:"bg-muted p-1.5 rounded-md space-y-0.5 max-h-32 overflow-y-auto",children:E.map(Jn=>e.jsxs("div",{className:`text-sm px-2 py-1 rounded cursor-pointer transition-colors ${(rt==null?void 0:rt.id)===Jn.id?"bg-primary/10 text-primary font-medium":"text-muted-foreground hover:bg-accent hover:text-foreground"}`,onClick:()=>Yt(Jn),children:[Jn.first_name," ",Jn.last_name," — ",Jn.email]},Jn.id))})]}),rt&&e.jsxs("div",{className:"border rounded-xl 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(mn,{className:"h-3.5 w-3.5"}),"Preview for ",rt.first_name," ",rt.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:"})," ",rt.email]}),e.jsxs("p",{children:[e.jsx("span",{className:"text-muted-foreground text-xs",children:"Subject:"})," ",yj(ce,rt)]})]}),e.jsx(Gc,{}),cs?e.jsx("div",{className:"rounded-lg border bg-background max-h-72 overflow-y-auto [&_img]:max-w-full",dangerouslySetInnerHTML:{__html:yj(cs,rt)}}):e.jsx("div",{className:"text-sm whitespace-pre-wrap bg-background rounded p-2.5 max-h-40 overflow-y-auto border",children:yj(he,rt)})]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[e.jsxs($,{variant:"outline",onClick:()=>{Le("composing"),Yt(null)},children:[e.jsx(qa,{className:"h-4 w-4 mr-1"}),"Back to Edit"]}),e.jsxs($,{onClick:Fn,disabled:Y,className:"gap-2",children:[Y?e.jsx(kt,{className:"h-4 w-4 animate-spin"}):e.jsx(Yr,{className:"h-4 w-4"}),R?`Send First ${iN}`:`Send to ${E.length}`]})]})]})]}),e.jsx(S6e,{open:x,onOpenChange:y,hasPending:!!(g!=null&&g.hasPendingSes),pendingEmails:g==null?void 0:g.pendingEmails})]})}function uGs(s){return new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(s)}const hGs={single_family:"Single Family Home",condo:"Condo",townhouse:"Townhouse",land:"Land",multi_family:"Multi-Family",luxury:"Luxury Home",commercial:"Commercial",other:"Property"};function VUt({open:s,onOpenChange:t,listing:n}){const{user:r}=vs(),{data:a=[],isLoading:i}=z_(),{data:l=[]}=Yw(),[o,c]=j.useState(""),[d,u]=j.useState("all"),[h,m]=j.useState(new Set),[f,g]=j.useState(!1),[x,y]=j.useState(null);j.useEffect(()=>{s||(c(""),u("all"),m(new Set),g(!1))},[s]),j.useEffect(()=>{!s||!r||(async()=>{const{data:P}=await q.from("gmail_integrations").select("gmail_email").eq("user_id",r.id).maybeSingle();y((P==null?void 0:P.gmail_email)||null)})()},[s,r]);const v=j.useMemo(()=>a.filter(P=>P.email),[a]),b=j.useMemo(()=>{let P=v;if(d!=="all"&&(P=P.filter(R=>{var D;return(D=R.tags)==null?void 0:D.some(O=>O.relationship_type_id===d)})),o.trim()){const R=o.toLowerCase();P=P.filter(D=>`${D.first_name||""} ${D.last_name||""}`.toLowerCase().includes(R)||(D.email||"").toLowerCase().includes(R))}return P},[v,o,d]),w=()=>{h.size===b.length?m(new Set):m(new Set(b.map(P=>P.id)))},S=P=>{const R=new Set(h);R.has(P)?R.delete(P):R.add(P),m(R)},C=j.useMemo(()=>v.filter(P=>h.has(P.id)).map(P=>({id:P.id,first_name:P.first_name||"there",last_name:P.last_name,email:P.email})),[v,h]),{defaultSubject:E,defaultBody:I}=j.useMemo(()=>{var te,J,ce,_e;const P=n.property_address||`${n.city}, ${n.state}`,R=uGs(n.price),D=hGs[n.property_type]||"home",O=n.bedrooms?`${n.bedrooms} bed`:"",U=n.bathrooms?`${n.bathrooms} bath`:"",W=n.square_footage?`${n.square_footage.toLocaleString()} sqft`:"",V=[O,U,W].filter(Boolean).join(" • "),G=`https://listings.relevelup.com/${n.slug||n.id}`,Y=((J=(te=n.photos)==null?void 0:te.find(he=>he.is_primary))==null?void 0:J.photo_url)||((_e=(ce=n.photos)==null?void 0:ce[0])==null?void 0:_e.photo_url)||"",ae={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"}[n.status]||"New Listing",ie=`${ae}: ${P} — ${R}`,ne=`

Hi {{first_name}},

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

${Y?` ${P} `:""}
${ae}

${R}

${P}

${n.city}, ${n.state}

${V?`

${V} • ${D}

`:""} 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:ie,defaultBody:ne}},[n]);return f?e.jsx(Ak,{open:f,onOpenChange:P=>{g(P),P||t(!1)},bulkContacts:C,defaultSubject:E,defaultBody:I,gmailEmail:x}):e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Os,{className:"sm:max-w-[640px] max-h-[90vh] flex flex-col",children:[e.jsxs(Us,{children:[e.jsxs(Bs,{className:"flex items-center gap-2",children:[e.jsx(Nn,{className:"h-5 w-5 text-amber-500"}),"Email this listing to your sphere"]}),e.jsx(Ir,{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(Kr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(pe,{placeholder:"Search contacts...",value:o,onChange:P=>c(P.target.value),className:"pl-9"})]}),e.jsxs(ms,{value:d,onValueChange:u,children:[e.jsx(us,{className:"sm:w-[180px]",children:e.jsx(fs,{placeholder:"Filter by tag"})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"all",children:"All contacts"}),l.map(P=>e.jsx(Ge,{value:P.id,children:P.name},P.id))]})]})]}),e.jsxs("div",{className:"flex items-center justify-between text-sm border-y py-2",children:[e.jsxs("button",{type:"button",onClick:w,className:"flex items-center gap-2 text-primary hover:underline",children:[e.jsx(ai,{checked:b.length>0&&h.size===b.length,className:"pointer-events-none"}),e.jsx("span",{children:h.size===b.length&&b.length>0?"Deselect all":`Select all (${b.length})`})]}),e.jsxs(Be,{variant:"secondary",className:"gap-1",children:[e.jsx(Zn,{className:"h-3 w-3"}),h.size," selected"]})]}),e.jsx(uo,{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(kt,{className:"h-5 w-5 animate-spin mr-2"}),"Loading your contacts..."]}):b.length===0?e.jsx("div",{className:"text-center py-12 text-muted-foreground text-sm",children:v.length===0?"No contacts with email addresses yet.":"No contacts match your search."}):e.jsx("div",{className:"space-y-1 py-2",children:b.map(P=>e.jsxs("label",{className:"flex items-center gap-3 p-2 rounded-md hover:bg-muted/50 cursor-pointer",children:[e.jsx(ai,{checked:h.has(P.id),onCheckedChange:()=>S(P.id)}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("p",{className:"text-sm font-medium truncate",children:[P.first_name," ",P.last_name]}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:P.email})]}),P.tags&&P.tags.length>0&&e.jsx("div",{className:"flex gap-1 flex-wrap justify-end max-w-[40%]",children:P.tags.slice(0,2).map(R=>{var D;return e.jsx(Be,{variant:"outline",className:"text-[10px] px-1.5 py-0",children:(D=R.relationship_type)==null?void 0:D.name},R.id)})})]},P.id))})}),e.jsx(Gc,{}),e.jsxs("div",{className:"flex justify-between items-center gap-3",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:x?`Sending from ${x}`:"Connect Gmail in Settings to send"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx($,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsxs($,{onClick:()=>g(!0),disabled:h.size===0,className:"gap-2",children:[e.jsx(mn,{className:"h-4 w-4"}),"Compose Email (",h.size,")"]})]})]})]})})}const mGs="#2a4c64",fGs="#B8965A";function A6e(){const{user:s}=vs();return tt({queryKey:["agent-brand",s==null?void 0:s.id],enabled:!!s,staleTime:5*60*1e3,queryFn:async()=>{const t=s.id,[n,r,a,i]=await Promise.all([q.from("profiles").select("name, email, phone, avatar_url, website_url, title, brokerage_name, brokerage_id").eq("id",t).maybeSingle(),q.from("lead_sites").select("brand_color, accent_color, agent_license_number, brokerage_license_number, license_state, brokerage_legal_name, team_logo_url, is_active, created_at").eq("agent_id",t).order("created_at",{ascending:!0}).limit(5),q.from("agent_cards").select("brokerage_display_name, brokerage_logo_url, team_logo_url, title, positioning_statement, display_email").eq("user_id",t).maybeSingle(),q.from("agent_brand_profiles").select("*").eq("user_id",t).maybeSingle()]),l=n.data||{},o=r.data||[],c=o.find(v=>v.is_active)||o[0]||{},d=a.data||{},u=i.data||{};let h=null;if(l.brokerage_id){const{data:v}=await q.from("brokerage_brand_profiles").select("primary_color, accent_color, logo_url, lock_colors, lock_logo").eq("brokerage_id",l.brokerage_id).maybeSingle();h=v||null}const m=!!(h!=null&&h.lock_colors),f=(...v)=>v.map(b=>typeof b=="string"&&b.trim()?b.trim():null).find(Boolean)||null,g=m?f(h==null?void 0:h.primary_color,u.brand_color,c.brand_color):f(u.brand_color,h==null?void 0:h.primary_color,c.brand_color),x=m?f(h==null?void 0:h.accent_color,u.accent_color,c.accent_color):f(u.accent_color,h==null?void 0:h.accent_color,c.accent_color);let y=l.brokerage_name||d.brokerage_display_name||c.brokerage_legal_name||null;if(!y&&l.brokerage_id){const{data:v}=await q.from("brokerages").select("name").eq("id",l.brokerage_id).maybeSingle();y=(v==null?void 0:v.name)||null}return{name:l.name||s.email||"Your Name",headshotUrl:u.headshot_url||l.avatar_url||null,brokerageName:y,brokerageLogoUrl:(h!=null&&h.lock_logo?h==null?void 0:h.logo_url:u.logo_url)||u.logo_url||d.brokerage_logo_url||d.team_logo_url||c.team_logo_url||(h==null?void 0:h.logo_url)||null,licenseNumber:u.license_number||c.agent_license_number||null,licenseState:u.license_state||c.license_state||null,phone:l.phone||null,email:d.display_email||l.email||s.email||null,website:u.website_url||l.website_url||null,brandColor:g||mGs,accentColor:x||fGs,tagline:u.tagline||d.positioning_statement||l.title||d.title||null}}})}const ybt=[{key:"just_listed",label:"Just Listed",ribbon:"JUST LISTED"},{key:"price_improvement",label:"Price Drop",ribbon:"PRICE IMPROVEMENT"},{key:"under_contract",label:"Under Contract",ribbon:"UNDER CONTRACT"},{key:"sold",label:"Sold",ribbon:"JUST SOLD"},{key:"open_house",label:"Open House",ribbon:"OPEN HOUSE"}],pGs=[{key:"onyx",label:"Onyx & Gold",base:"#0F172A",accent:"#D4AF37"},{key:"navy",label:"Classic Navy",base:"#2a4c64",accent:"#B8965A"},{key:"noir",label:"Modern Noir",base:"#111111",accent:"#F5F5F5"}],JEe=s=>{switch(s){case"price_improvement":return"price_improvement";case"under_contract":return"under_contract";case"sold":return"sold";default:return"just_listed"}},gGs=s=>{if(!s)return"";const t=s.replace(/\D/g,""),n=t.length===11&&t.startsWith("1")?t.slice(1):t;return n.length!==10?s:`${n.slice(0,3)}-${n.slice(3,6)}-${n.slice(6)}`},ide=s=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(s),vbt=async s=>new Promise((t,n)=>{const r=new Image;r.crossOrigin="anonymous",r.referrerPolicy="no-referrer",r.onload=()=>t(r),r.onerror=n,r.src=s}),bbt=(s,t,n,r,a,i)=>{const l=Math.max(a/t.naturalWidth,i/t.naturalHeight),o=a/l,c=i/l,d=(t.naturalWidth-o)/2,u=(t.naturalHeight-c)/2;s.drawImage(t,d,u,o,c,n,r,a,i)},mQ=(s,t,n)=>{if(s.measureText(t).width<=n)return t;let r=t;for(;r.length>3&&s.measureText(`${r}…`).width>n;)r=r.slice(0,-1);return`${r.trim()}…`},xGs=(s,t,n,r)=>{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<=n||!l)l=c;else if(i.push(l),l=o,i.length===r)break}return l&&i.length{let i=n;for(const l of t)s.fillText(l,i,r),i+=s.measureText(l).width+a},vGs=s=>{const t=s.replace("#",""),n=t.length===3?t.split("").map(a=>a+a).join(""):t,r=parseInt(n,16);return Number.isNaN(r)?{r:15,g:23,b:42}:{r:r>>16&255,g:r>>8&255,b:r&255}},NM=(s,t)=>{const{r:n,g:r,b:a}=vGs(s);return`rgba(${n},${r},${a},${t})`};function lnt({listingId:s,open:t,onOpenChange:n,initialStatus:r}){var _e,he;const a=Qn(),{data:i}=tie(s||""),{data:l}=A6e(),[o,c]=j.useState(null),[d,u]=j.useState({base:null,accent:null}),[h,m]=j.useState(!1),[f,g]=j.useState(!1),[x,y]=j.useState(null),[v,b]=j.useState(null),[w,S]=j.useState(r||"just_listed"),[C,E]=j.useState("brand"),[I,P]=j.useState(""),[R,D]=j.useState(!1),O=j.useMemo(()=>((i==null?void 0:i.photos)||[]).slice().sort((ue,ve)=>ue.is_primary&&!ve.is_primary?-1:!ue.is_primary&&ve.is_primary?1:(ue.sort_order??0)-(ve.sort_order??0)),[i==null?void 0:i.photos]),U=j.useMemo(()=>({key:"brand",label:"My Brand Kit",base:d.base||(l==null?void 0:l.brandColor)||"#2a4c64",accent:d.accent||(l==null?void 0:l.accentColor)||"#B8965A"}),[d.base,d.accent,l==null?void 0:l.brandColor,l==null?void 0:l.accentColor]),W=j.useMemo(()=>[U,...pGs],[U]),V=W.find(ue=>ue.key===C)||U,G=((_e=ybt.find(ue=>ue.key===w))==null?void 0:_e.ribbon)||"JUST LISTED",Y=v||((he=O[0])==null?void 0:he.photo_url)||null,X=gGs((o==null?void 0:o.phone)||(l==null?void 0:l.phone)),ae=[i!=null&&i.bedrooms?`${i.bedrooms} BD`:null,i!=null&&i.bathrooms?`${i.bathrooms} BA`:null,i!=null&&i.square_footage?`${i.square_footage.toLocaleString()} SF`:null].filter(Boolean);j.useEffect(()=>{var ve;if(!t)return;S(r||JEe(i==null?void 0:i.status));const ue=((ve=O[0])==null?void 0:ve.photo_url)||null;b(Ee=>Ee||ue)},[t,i==null?void 0:i.id,O.length]),j.useEffect(()=>{t||(y(null),b(null),D(!1),u({base:null,accent:null}))},[t]),j.useEffect(()=>{let ue=!1;if(!(!t||!(i!=null&&i.agent_id)))return(async()=>{var Ae,Ce,qe,ze;const[ve,Ee,Se]=await Promise.all([q.from("profiles").select("name, phone, phone_e164, avatar_url, brokerage:brokerages!profiles_brokerage_id_fkey(name)").eq("id",i.agent_id).maybeSingle(),q.from("agent_brand_profiles").select("brand_color, accent_color").eq("user_id",i.agent_id).maybeSingle(),q.from("lead_sites").select("brand_color, accent_color, is_active, created_at").eq("agent_id",i.agent_id).order("created_at",{ascending:!0}).limit(5)]);if(ue)return;const Le=ve.data;c({name:(Le==null?void 0:Le.name)||((Ae=i.agent)==null?void 0:Ae.name)||"Agent",phone:(Le==null?void 0:Le.phone)||(Le==null?void 0:Le.phone_e164)||null,avatar_url:(Le==null?void 0:Le.avatar_url)||null,brokerage:((Ce=Le==null?void 0:Le.brokerage)==null?void 0:Ce.name)||((ze=(qe=i.agent)==null?void 0:qe.brokerage)==null?void 0:ze.name)||null});const Fe=Ee.data||null,ke=Se.data||[],Ve=ke.find($e=>$e.is_active)||ke[0]||{},je=$e=>typeof $e=="string"&&$e.trim()?$e.trim():null;u({base:je(Fe==null?void 0:Fe.brand_color)||je(Ve.brand_color),accent:je(Fe==null?void 0:Fe.accent_color)||je(Ve.accent_color)})})(),()=>{ue=!0}},[t,i==null?void 0:i.agent_id]),j.useEffect(()=>{if(!t||!i||R)return;const ue=[i.city,i.state].filter(Boolean).join(", "),ve=ae.join(" · "),Ee=ide(i.price),Se=X?`call or text ${X}`:"send me a message",Le=(i.city||"").replace(/[^a-zA-Z]/g,""),Fe={just_listed:`✨ JUST LISTED in ${ue||"town"}!`,price_improvement:`📉 PRICE IMPROVEMENT in ${ue||"town"}!`,under_contract:`🤝 UNDER CONTRACT in ${ue||"town"}!`,sold:`🎉 JUST SOLD in ${ue||"town"}!`,open_house:`🚪 OPEN HOUSE in ${ue||"town"}!`},ke={just_listed:`Want a private tour? ${Se}.`,price_improvement:`This one won't last at the new number — ${Se}.`,under_contract:`Looking for something similar? ${Se}.`,sold:`Thinking about making a move? ${Se}.`,open_house:`Stop by or ${Se} for details.`},Ve={just_listed:"#JustListed",price_improvement:"#PriceImprovement",under_contract:"#UnderContract",sold:"#JustSold",open_house:"#OpenHouse"},je=[Fe[w],i.property_address||"",[ve,Ee].filter(Boolean).join(" · "),i.description?i.description.split(/\n+/)[0].slice(0,180):"",ke[w],[Ve[w],Le?`#${Le}RealEstate`:"","#RealEstate","#DreamHome"].filter(Boolean).join(" ")].filter(Boolean);P(je.join(` `))},[t,i==null?void 0:i.id,w,X,R]);const ie=j.useCallback(async()=>{if(!i)return;const ue=(o==null?void 0:o.name)||(l==null?void 0:l.name)||"Agent",ve=(o==null?void 0:o.brokerage)||(l==null?void 0:l.brokerageName)||null;m(!0);try{const Ee=document.createElement("canvas");Ee.width=1080,Ee.height=1080;const Se=Ee.getContext("2d");if(!Se)throw new Error("Canvas unavailable");if(Se.fillStyle=V.base,Se.fillRect(0,0,1080,1080),Y)try{const ze=await vbt(Y);bbt(Se,ze,0,0,1080,1080)}catch{}const Le=Se.createLinearGradient(0,0,0,1080);Le.addColorStop(0,NM(V.base,.6)),Le.addColorStop(.34,NM(V.base,.18)),Le.addColorStop(.62,NM(V.base,.5)),Le.addColorStop(1,NM(V.base,.98)),Se.fillStyle=Le,Se.fillRect(0,0,1080,1080),Se.fillStyle=V.accent,Se.fillRect(56,62,72,3),Se.font="600 22px Arial, sans-serif",yGs(Se,G,146,72,8),(w==="sold"||w==="under_contract")&&(Se.save(),Se.fillStyle=NM(V.accent,.92),Se.fillRect(0,430,1080,96),Se.fillStyle=V.base,Se.font="700 46px Arial, sans-serif",Se.textAlign="center",Se.textBaseline="middle",Se.fillText(w==="sold"?"SOLD":"UNDER CONTRACT",540,479),Se.restore(),Se.textAlign="left"),Se.save(),Se.shadowColor="rgba(0,0,0,0.55)",Se.shadowBlur=24,Se.shadowOffsetY=4,Se.fillStyle="#F8FAFC",Se.font="600 64px Georgia, serif",Se.textBaseline="top";const Fe=xGs(Se,i.property_address||`${i.city||""}, ${i.state||""}`.trim(),952,2);let ke=Fe.length>1?590:654;Fe.forEach(ze=>{Se.fillText(ze,64,ke),ke+=70}),Se.restore();const Ve=[i.city,i.state].filter(Boolean).join(", ")+(i.neighborhood?` · ${i.neighborhood}`:"");Se.fillStyle="rgba(248,250,252,0.9)",Se.font="600 26px Arial, sans-serif",Se.fillText(mQ(Se,Ve.toUpperCase(),952),64,ke+8),Se.fillStyle=V.accent,Se.font="700 56px Arial, sans-serif";const je=w==="sold"?`SOLD · ${ide(i.price)}`:w==="price_improvement"?`NOW ${ide(i.price)}`:ide(i.price);Se.fillText(je,64,ke+58),ae.length>0&&(Se.fillStyle="rgba(248,250,252,0.86)",Se.font="600 22px Arial, sans-serif",Se.fillText(mQ(Se,ae.join(" · "),400),620,ke+78));const Ae=Se.createLinearGradient(0,880,0,1080);Ae.addColorStop(0,NM(V.base,.96)),Ae.addColorStop(1,V.base),Se.fillStyle=Ae,Se.fillRect(0,880,1080,200),Se.fillStyle=V.accent,Se.fillRect(0,880,1080,3),Se.save(),Se.beginPath(),Se.arc(124,980,60,0,Math.PI*2),Se.closePath(),Se.fillStyle=NM(V.accent,.18),Se.fill(),Se.lineWidth=6,Se.strokeStyle=V.accent,Se.stroke(),Se.clip();const Ce=(o==null?void 0:o.avatar_url)||(l==null?void 0:l.headshotUrl)||null;let qe=!1;if(Ce)try{const ze=await vbt(Ce);bbt(Se,ze,64,920,120,120),qe=!0}catch{qe=!1}qe||(Se.fillStyle=V.accent,Se.font="700 48px Arial, sans-serif",Se.textAlign="center",Se.textBaseline="middle",Se.fillText(ue.charAt(0).toUpperCase(),124,982)),Se.restore(),Se.textAlign="left",Se.textBaseline="alphabetic",Se.fillStyle="#F8FAFC",Se.font="600 38px Georgia, serif",Se.fillText(mQ(Se,ue,X?430:820),212,970),ve&&(Se.fillStyle=V.accent,Se.font="600 20px Arial, sans-serif",Se.fillText(mQ(Se,ve.toUpperCase(),X?430:820),212,1008)),X&&(Se.textAlign="right",Se.fillStyle=NM(V.accent,.9),Se.font="600 16px Arial, sans-serif",Se.fillText("CALL · TEXT",1016,958),Se.fillStyle="#F8FAFC",Se.font="600 38px Arial, sans-serif",Se.fillText(X,1016,1008)),y(Ee.toDataURL("image/png"))}catch(Ee){console.error("Generate graphic error",Ee),re.error("Could not generate graphic")}finally{m(!1)}},[i,o,l,V,Y,G,w,ae,X]);j.useEffect(()=>{if(!t||!i)return;const ue=setTimeout(()=>{ie()},300);return()=>clearTimeout(ue)},[t,i==null?void 0:i.id,o==null?void 0:o.name,v,w,C,l==null?void 0:l.brandColor]);const ne=async ue=>(await fetch(ue)).blob(),te=async()=>{if(!x)return;const ue=document.createElement("a");ue.href=x,ue.download=`${w}-${(i==null?void 0:i.slug)||(i==null?void 0:i.id)||"graphic"}.png`,ue.click(),re.success("Downloaded!")},J=async()=>{try{await navigator.clipboard.writeText(I),re.success("Caption copied")}catch{re.error("Copy not supported in this browser")}},ce=async()=>{var ue;if(x){g(!0);try{const{data:ve}=await q.auth.getUser(),Ee=(ue=ve.user)==null?void 0:ue.id;if(!Ee)throw new Error("Not signed in");const Se=await ne(x),Le=`listing-social/${Ee}/${crypto.randomUUID()}.png`,{error:Fe}=await q.storage.from("agent-uploads").upload(Le,Se,{contentType:"image/png",upsert:!0});if(Fe)throw Fe;const{data:ke}=q.storage.from("agent-uploads").getPublicUrl(Le);sessionStorage.setItem("social-studio-seed",JSON.stringify({mediaUrl:ke.publicUrl,mediaType:"image",caption:I,source:"listing",sourceRef:i==null?void 0:i.id})),n(!1),a("/social-studio"),re.success("Draft ready in Social Studio")}catch(ve){console.error("Push to Social Studio failed",ve),re.error("Could not send to Social Studio")}finally{g(!1)}}};return e.jsx(zs,{open:t,onOpenChange:n,children:e.jsx(Os,{className:"!max-w-[900px] !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(Us,{className:"px-5 pt-5 pb-3 shrink-0",children:[e.jsxs(Bs,{className:"flex items-center gap-2 pr-8",children:[e.jsx(Nn,{className:"h-5 w-5 text-amber-500 shrink-0"}),e.jsx("span",{className:"truncate",children:"Share this listing"})]}),e.jsx(Ir,{className:"text-xs",children:"Square 1080×1080 graphic in your brand colors — ready for Instagram, Facebook and LinkedIn."})]}),e.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto px-5 pb-3 space-y-4",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"flex flex-wrap gap-1.5",children:ybt.map(ue=>e.jsx($,{type:"button",size:"sm",variant:w===ue.key?"default":"outline",className:"h-7 text-xs",onClick:()=>S(ue.key),children:ue.label},ue.key))}),e.jsx("div",{className:"flex flex-wrap gap-1.5",children:W.map(ue=>e.jsxs("button",{type:"button",onClick:()=>E(ue.key),className:`flex items-center gap-2 rounded-full border px-2.5 py-1 text-xs transition ${C===ue.key?"border-primary ring-2 ring-primary/25":"border-border hover:border-muted-foreground/50"}`,children:[e.jsxs("span",{className:"flex",children:[e.jsx("span",{className:"h-3.5 w-3.5 rounded-l-full",style:{background:ue.base}}),e.jsx("span",{className:"h-3.5 w-3.5 rounded-r-full",style:{background:ue.accent}})]}),ue.label]},ue.key))})]}),e.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"relative mx-auto flex aspect-square w-full max-w-[360px] items-center justify-center overflow-hidden rounded-lg",style:{background:V.base},children:[x?e.jsx("img",{src:x,alt:"Social graphic preview",className:"h-full w-full object-cover"}):e.jsx("div",{className:"text-xs text-white/70",children:"Preparing preview…"}),h&&e.jsxs("div",{className:"absolute inset-0 flex flex-col items-center justify-center gap-2 bg-black/60 text-white/90",children:[e.jsx(kt,{className:"h-7 w-7 animate-spin"}),e.jsx("p",{className:"text-xs",children:"Crafting your graphic…"})]})]}),O.length>1&&e.jsxs("div",{className:"mt-3",children:[e.jsx("p",{className:"mb-2 text-xs text-muted-foreground",children:"Choose photo"}),e.jsx("div",{className:"flex gap-2 pb-2",style:{overflowX:"auto",overflowY:"hidden",WebkitOverflowScrolling:"touch"},children:O.map(ue=>e.jsx("button",{type:"button",onClick:()=>b(ue.photo_url),className:`relative h-14 w-14 shrink-0 overflow-hidden rounded-md border-2 transition ${v===ue.photo_url?"border-amber-500 ring-2 ring-amber-500/30":"border-transparent hover:border-muted-foreground/40"}`,children:e.jsx("img",{src:ue.photo_url,alt:"",className:"h-full w-full object-cover"})},ue.id))})]})]}),e.jsxs("div",{className:"flex flex-col",children:[e.jsxs("div",{className:"mb-2 flex items-center justify-between",children:[e.jsx("p",{className:"text-xs font-medium text-muted-foreground",children:"Post text"}),e.jsxs($,{type:"button",variant:"ghost",size:"sm",className:"h-7 gap-1.5 text-xs",onClick:J,children:[e.jsx(Ha,{className:"h-3.5 w-3.5"})," Copy"]})]}),e.jsx(Rs,{value:I,onChange:ue=>{P(ue.target.value),D(!0)},rows:14,className:"min-h-[260px] text-sm",placeholder:"Your caption…"})]})]})]}),e.jsxs("div",{className:"flex shrink-0 flex-wrap justify-end gap-2 border-t bg-background px-5 pb-5 pt-3",children:[e.jsx($,{variant:"ghost",size:"sm",onClick:()=>n(!1),children:"Not now"}),e.jsx($,{variant:"outline",size:"sm",onClick:()=>void ie(),disabled:h||!i,className:"gap-1.5",children:"Regenerate"}),e.jsxs($,{variant:"outline",size:"sm",onClick:te,disabled:!x,className:"gap-1.5",children:[e.jsx(di,{className:"h-3.5 w-3.5"})," Download"]}),e.jsxs($,{size:"sm",onClick:ce,disabled:!x||f,className:"gap-1.5",children:[f?e.jsx(kt,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(qg,{className:"h-3.5 w-3.5"}),"Push to Social Studio"]})]})]})})})}function bGs({listing:s,canEdit:t}){const n=Qn(),{data:r,isLoading:a}=EDs(s.id),i=U7t(),l=q7t(),[o,c]=j.useState({owner_name:"",owner_company:"",owner_email:"",owner_phone:"",decision_maker_notes:"",pitch_date:"",positioning:"",pricing_strategy:"",pitch_notes:"",competitors:""}),[d,u]=j.useState(z7t),[h,m]=j.useState("");j.useEffect(()=>{r&&(c({owner_name:r.owner_name??"",owner_company:r.owner_company??"",owner_email:r.owner_email??"",owner_phone:r.owner_phone??"",decision_maker_notes:r.decision_maker_notes??"",pitch_date:r.pitch_date?String(r.pitch_date).slice(0,10):"",positioning:r.positioning??"",pricing_strategy:r.pricing_strategy??"",pitch_notes:r.pitch_notes??"",competitors:r.competitors??""}),Array.isArray(r.launch_plan)&&r.launch_plan.length&&u(r.launch_plan))},[r]);const f=r!=null&&r.preview_token?`${window.location.origin}/commercial-pitch/${r.preview_token}`:null,g=async()=>{await i.mutateAsync({listingId:s.id,values:{...o,pitch_date:o.pitch_date||null,launch_plan:d.filter(v=>{var b;return(b=v.label)==null?void 0:b.trim()})}}),re.success("Pitch saved")},x=async()=>{await l.mutateAsync({listingId:s.id,stage:"won"}),re.success("Assignment won — welcome to Launch"),n(`/mission-control/listings/${s.id}/commercial`)},y=async()=>{await l.mutateAsync({listingId:s.id,stage:"lost",lostReason:h}),re("Marked as lost opportunity"),n("/mission-control/listings")};return a?e.jsx("div",{className:"flex justify-center py-20",children:e.jsx(kt,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):t?e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"grid gap-6 lg:grid-cols-3",children:[e.jsxs("div",{className:"space-y-6 lg:col-span-2",children:[e.jsxs(Ne,{children:[e.jsxs(Ct,{children:[e.jsx(At,{className:"text-base",children:"Owner & decision makers"}),e.jsx(Gn,{children:"Who actually signs the listing agreement."})]}),e.jsxs(Ie,{className:"grid gap-4 md:grid-cols-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Owner name"}),e.jsx(pe,{value:o.owner_name,onChange:v=>c({...o,owner_name:v.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Entity / company"}),e.jsx(pe,{value:o.owner_company,onChange:v=>c({...o,owner_company:v.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Email"}),e.jsx(pe,{type:"email",value:o.owner_email,onChange:v=>c({...o,owner_email:v.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Phone"}),e.jsx(pe,{value:o.owner_phone,onChange:v=>c({...o,owner_phone:v.target.value})})]}),e.jsxs("div",{className:"space-y-2 md:col-span-2",children:[e.jsx(ee,{children:"Decision-maker intel"}),e.jsx(Rs,{rows:3,value:o.decision_maker_notes,onChange:v=>c({...o,decision_maker_notes:v.target.value}),placeholder:"Motivations, timing, partners, tax position, who influences the decision…"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Pitch date"}),e.jsx(pe,{type:"date",value:o.pitch_date,onChange:v=>c({...o,pitch_date:v.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Competing brokers"}),e.jsx(pe,{value:o.competitors,onChange:v=>c({...o,competitors:v.target.value})})]})]})]}),e.jsxs(Ne,{children:[e.jsxs(Ct,{children:[e.jsx(At,{className:"text-base",children:"Positioning & pricing strategy"}),e.jsx(Gn,{children:"The argument you're making for how this asset goes to market."})]}),e.jsxs(Ie,{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Proposed positioning"}),e.jsx(Rs,{rows:4,value:o.positioning,onChange:v=>c({...o,positioning:v.target.value}),placeholder:"Buyer profile, story, comparable trades, why this asset wins attention…"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Pricing strategy"}),e.jsx(Rs,{rows:4,value:o.pricing_strategy,onChange:v=>c({...o,pricing_strategy:v.target.value}),placeholder:"Recommended ask, cap-rate rationale, call-for-offers timing…"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Private pitch notes"}),e.jsx(Rs,{rows:3,value:o.pitch_notes,onChange:v=>c({...o,pitch_notes:v.target.value}),placeholder:"Never shown to the owner."})]})]})]}),e.jsxs(Ne,{children:[e.jsxs(Ct,{children:[e.jsx(At,{className:"text-base",children:"Proposed launch plan"}),e.jsx(Gn,{children:"Shown on the owner-facing preview — this is what they buy."})]}),e.jsxs(Ie,{className:"space-y-3",children:[d.map((v,b)=>e.jsxs("div",{className:"rounded-lg border p-3",children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsx(pe,{value:v.label,placeholder:"Milestone",onChange:w=>u(d.map((S,C)=>C===b?{...S,label:w.target.value}:S))}),e.jsx($,{variant:"ghost",size:"icon",onClick:()=>u(d.filter((w,S)=>S!==b)),children:e.jsx(gr,{className:"h-4 w-4"})})]}),e.jsx(Rs,{className:"mt-2",rows:2,value:v.detail??"",placeholder:"What happens in this step",onChange:w=>u(d.map((S,C)=>C===b?{...S,detail:w.target.value}:S))})]},b)),e.jsxs($,{variant:"outline",size:"sm",onClick:()=>u([...d,{label:"",detail:""}]),children:[e.jsx(dn,{className:"mr-1.5 h-3.5 w-3.5"})," Add step"]})]})]})]}),e.jsxs("div",{className:"space-y-6",children:[e.jsxs(Ne,{className:"border-primary/30 bg-gradient-to-br from-primary/[0.06] to-transparent",children:[e.jsxs(Ct,{children:[e.jsx(At,{className:"text-base",children:"Owner preview"}),e.jsx(Gn,{children:"A private, seller-facing page showing exactly what happens the day they hire you."})]}),e.jsx(Ie,{className:"space-y-3",children:f?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"flex items-center gap-2 rounded-lg border bg-background px-3 py-2",children:e.jsx("span",{className:"truncate text-xs text-muted-foreground",children:f})}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs($,{variant:"outline",size:"sm",className:"flex-1",onClick:()=>{navigator.clipboard.writeText(f),re.success("Link copied")},children:[e.jsx(Ha,{className:"mr-1.5 h-3.5 w-3.5"})," Copy"]}),e.jsxs($,{size:"sm",className:"flex-1",onClick:()=>window.open(f,"_blank"),children:[e.jsx(kr,{className:"mr-1.5 h-3.5 w-3.5"})," Open"]})]})]}):e.jsx("p",{className:"text-sm text-muted-foreground",children:"Save the pitch to generate the private preview link."})})]}),e.jsxs(Ne,{children:[e.jsx(Ct,{children:e.jsx(At,{className:"text-base",children:"Outcome"})}),e.jsxs(Ie,{className:"space-y-3",children:[e.jsxs(kc,{children:[e.jsx(jx,{asChild:!0,children:e.jsxs($,{className:"w-full",children:[e.jsx(Kl,{className:"mr-2 h-4 w-4"})," Won listing"]})}),e.jsxs(cc,{children:[e.jsxs(dc,{children:[e.jsx(hc,{children:"Convert this pitch into a Commercial Launch?"}),e.jsx(mc,{children:"Everything you've entered carries over. The listing moves into the Launch stage where you can publish the microsite, gate the OM and start tracking investor activity."})]}),e.jsxs(uc,{children:[e.jsx(fc,{children:"Cancel"}),e.jsx(tc,{onClick:x,children:"Yes — we won it"})]})]})]}),e.jsxs(kc,{children:[e.jsx(jx,{asChild:!0,children:e.jsxs($,{variant:"outline",className:"w-full",children:[e.jsx(ku,{className:"mr-2 h-4 w-4"})," Lost opportunity"]})}),e.jsxs(cc,{children:[e.jsxs(dc,{children:[e.jsx(hc,{children:"Mark as lost?"}),e.jsx(mc,{children:"Kept private in your archive so you can learn from it."})]}),e.jsx(pe,{placeholder:"Reason (optional)",value:h,onChange:v=>m(v.target.value)}),e.jsxs(uc,{children:[e.jsx(fc,{children:"Cancel"}),e.jsx(tc,{onClick:y,children:"Mark lost"})]})]})]})]})]})]})]}),e.jsx("div",{className:"sticky bottom-4 flex justify-end",children:e.jsxs($,{onClick:g,disabled:i.isPending,size:"lg",className:"shadow-lg",children:[i.isPending?e.jsx(kt,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(tl,{className:"mr-2 h-4 w-4"}),"Save pitch"]})})]}):e.jsx(Ne,{children:e.jsxs(Ct,{children:[e.jsx(At,{className:"text-base",children:"Private pitch workspace"}),e.jsx(Gn,{children:"Only the listing agent can view or update pitch strategy and owner information."})]})})}function _Gs({listingId:s}){const{data:t=[],isLoading:n}=d6e(s),r=K$t(),a=Y$t(),i=Vqs(),l=j.useRef(null),[o,c]=j.useState("om"),[d,u]=j.useState("email"),h=async f=>{if(f!=null&&f.length)try{for(const g of Array.from(f))await r.mutateAsync({listingId:s,file:g,docKind:o,gateLevel:d});re.success("Document uploaded")}catch(g){re.error(g.message||"Upload failed")}finally{l.current&&(l.current.value="")}},m=async f=>{try{window.open(await Jst(f),"_blank")}catch{re.error("Could not open document")}};return e.jsx("div",{className:"space-y-6",children:e.jsxs(Ne,{children:[e.jsxs(Ct,{children:[e.jsx(At,{className:"text-base",children:"Deal room"}),e.jsx(Gn,{children:"Offering memorandum, financials and diligence files. Everything is stored privately and released through expiring secure links only."})]}),e.jsxs(Ie,{className:"space-y-4",children:[e.jsxs("div",{className:"grid gap-3 sm:grid-cols-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{className:"text-xs font-medium text-muted-foreground",children:"Document type"}),e.jsxs(ms,{value:o,onValueChange:f=>c(f),children:[e.jsx(us,{children:e.jsx(fs,{})}),e.jsx(hs,{children:Object.entries(aGe).map(([f,g])=>e.jsx(Ge,{value:f,children:g},f))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{className:"text-xs font-medium text-muted-foreground",children:"Access"}),e.jsxs(ms,{value:d,onValueChange:f=>u(f),children:[e.jsx(us,{children:e.jsx(fs,{})}),e.jsx(hs,{children:Object.entries(Qyt).map(([f,g])=>e.jsx(Ge,{value:f,children:g},f))})]})]}),e.jsxs("div",{className:"flex items-end",children:[e.jsxs($,{className:"w-full",onClick:()=>{var f;return(f=l.current)==null?void 0:f.click()},disabled:r.isPending,children:[r.isPending?e.jsx(kt,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(ni,{className:"mr-2 h-4 w-4"}),"Upload"]}),e.jsx("input",{ref:l,type:"file",multiple:!0,className:"hidden",onChange:f=>h(f.target.files)})]})]}),n?e.jsx("div",{className:"flex justify-center py-10",children:e.jsx(kt,{className:"h-5 w-5 animate-spin text-muted-foreground"})}):t.length===0?e.jsxs("div",{className:"rounded-xl border border-dashed py-12 text-center",children:[e.jsx(Jr,{className:"mx-auto mb-3 h-7 w-7 text-muted-foreground"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"No documents yet. Upload the OM to activate gated requests."})]}):e.jsx("div",{className:"divide-y rounded-xl border",children:t.map(f=>e.jsxs("div",{className:"flex flex-wrap items-center gap-3 p-4",children:[e.jsx("div",{className:"flex h-10 w-10 items-center justify-center rounded-lg border bg-muted/40",children:e.jsx(Jr,{className:"h-5 w-5"})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"truncate text-sm font-medium",children:f.title||f.file_name}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[(f.file_size/1024/1024).toFixed(2)," MB · ",f.download_count??0," downloads"]})]}),e.jsx(Be,{variant:"secondary",children:aGe[f.doc_kind||"other"]}),e.jsxs(ms,{value:f.gate_level||"email",onValueChange:g=>i.mutate({id:f.id,listingId:s,values:{gate_level:g}}),children:[e.jsxs(us,{className:"w-[190px]",children:[f.gate_level==="public"?e.jsx(di,{className:"mr-2 h-3.5 w-3.5"}):f.gate_level==="nda"?e.jsx(bm,{className:"mr-2 h-3.5 w-3.5"}):e.jsx(pc,{className:"mr-2 h-3.5 w-3.5"}),e.jsx(fs,{})]}),e.jsx(hs,{children:Object.entries(Qyt).map(([g,x])=>e.jsx(Ge,{value:g,children:x},g))})]}),e.jsx($,{variant:"outline",size:"sm",onClick:()=>m(f.storage_path),children:"Preview"}),e.jsx($,{variant:"ghost",size:"icon",onClick:()=>a.mutate({id:f.id,storage_path:f.storage_path,listingId:s}),children:e.jsx(Wn,{className:"h-4 w-4"})})]},f.id))})]})]})})}const wGs={om_request:"OM request",tour_request:"Tour request",investor_inquiry:"Investor inquiry",loi_intent:"LOI intent",inquiry:"Inquiry",showing_request:"Tour request",general:"Inquiry"};function jGs({listingId:s}){const{data:t=[],isLoading:n}=nst(s),{data:r=[]}=sst(s),a=j.useMemo(()=>{const o={};for(const c of r)c.lead_id&&(o[c.lead_id]=(o[c.lead_id]??0)+(e0t[c.event_type]??1));return o},[r]),i=j.useMemo(()=>[...t].map(o=>({...o,score:(a[o.id]??0)+(e0t[o.lead_type]??5)})).sort((o,c)=>c.score-o.score),[t,a]),l=i.filter(o=>o.score>=12);return n?e.jsx("div",{className:"flex justify-center py-20",children:e.jsx(kt,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):e.jsxs("div",{className:"space-y-6",children:[l.length>0&&e.jsxs(Ne,{className:"border-amber-500/30 bg-amber-500/[0.04]",children:[e.jsxs(Ct,{children:[e.jsx(At,{className:"text-base",children:"High-interest prospects"}),e.jsx(Gn,{children:"Ranked by document access, tour requests and repeat engagement."})]}),e.jsx(Ie,{className:"grid gap-3 md:grid-cols-2",children:l.slice(0,6).map(o=>{const c=t0t(o.score);return e.jsxs("div",{className:"rounded-xl border bg-background p-4",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"truncate font-medium",children:[o.first_name,o.last_name].filter(Boolean).join(" ")||o.email}),e.jsx("p",{className:"truncate text-xs text-muted-foreground",children:o.company||iGe[o.investor_role||"other"]})]}),e.jsx(Be,{variant:"outline",className:c.tone,children:c.label})]}),e.jsxs("div",{className:"mt-3 flex gap-2",children:[e.jsx($,{asChild:!0,size:"sm",variant:"outline",children:e.jsxs("a",{href:`mailto:${o.email}`,children:[e.jsx(mn,{className:"mr-1.5 h-3.5 w-3.5"})," Email"]})}),o.phone&&e.jsx($,{asChild:!0,size:"sm",variant:"ghost",children:e.jsxs("a",{href:`tel:${o.phone}`,children:[e.jsx(Da,{className:"mr-1.5 h-3.5 w-3.5"})," Call"]})})]})]},o.id)})})]}),e.jsxs(Ne,{children:[e.jsxs(Ct,{children:[e.jsx(At,{className:"text-base",children:"Investors & inquiries"}),e.jsx(Gn,{children:"Every prospect is written into your LevelUp CRM automatically."})]}),e.jsx(Ie,{children:i.length===0?e.jsxs("div",{className:"rounded-xl border border-dashed py-14 text-center",children:[e.jsx(Zn,{className:"mx-auto mb-3 h-7 w-7 text-muted-foreground"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"No inquiries yet. Publish the microsite and start distribution."})]}):e.jsx("div",{className:"divide-y rounded-xl border",children:i.map(o=>{const c=t0t(o.score);return e.jsxs("div",{className:"flex flex-wrap items-center gap-3 p-4",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("p",{className:"truncate text-sm font-medium",children:[[o.first_name,o.last_name].filter(Boolean).join(" ")||o.email,o.company&&e.jsxs("span",{className:"text-muted-foreground",children:[" · ",o.company]})]}),e.jsxs("p",{className:"truncate text-xs text-muted-foreground",children:[o.email,o.phone?` · ${o.phone}`:""," · ",new Date(o.created_at).toLocaleDateString()]}),o.message&&e.jsxs("p",{className:"mt-1 line-clamp-2 text-xs text-muted-foreground",children:['"',o.message,'"']})]}),o.investor_role&&e.jsx(Be,{variant:"secondary",children:iGe[o.investor_role]??o.investor_role}),e.jsx(Be,{variant:"outline",children:wGs[o.lead_type]??o.lead_type}),e.jsx(Be,{variant:"outline",className:c.tone,children:c.label}),e.jsx($,{asChild:!0,size:"sm",variant:"outline",children:e.jsx("a",{href:`mailto:${o.email}`,children:"Reply"})})]},o.id)})})})]})]})}const NGs={page_view:"Viewed the microsite",gallery_view:"Opened the gallery",om_request:"Requested the Offering Memorandum",om_download:"Downloaded the Offering Memorandum",doc_download:"Downloaded a document",tour_request:"Requested a tour",inquiry:"Submitted an inquiry",contact_click:"Clicked to contact the broker",share_click:"Opened a shared link",map_view:"Explored the location"};function kGs({listing:s}){const{data:t=[],isLoading:n}=sst(s.id),{data:r=[]}=nst(s.id),[a,i]=j.useState(""),[l,o]=j.useState(""),[c,d]=j.useState(!1),u=async f=>{d(!0);try{const{data:g,error:x}=await q.functions.invoke("commercial-seller-report",{body:{action:f?"send":"generate",listingId:s.id,days:7,narrative:l||null,recipients:a.split(/[,\s]+/).map(y=>y.trim()).filter(Boolean)}});if(x)throw x;if(g!=null&&g.error)throw new Error(g.error);re.success(f?"Activity report sent to your owner":"Weekly report generated")}catch(g){re.error(g.message||"Could not build the report")}finally{d(!1)}},h=j.useMemo(()=>{const f=y=>{const v=Array.isArray(y)?y:[y];return t.filter(b=>v.includes(b.event_type)).length},g=new Set(t.map(y=>y.session_id).filter(Boolean)),x=new Map;return t.forEach(y=>y.session_id&&x.set(y.session_id,(x.get(y.session_id)??0)+1)),{views:f("page_view")||s.view_count||0,unique:g.size,repeat:[...x.values()].filter(y=>y>3).length,omRequests:f(["om_request","om_download"]),downloads:f(["doc_download","om_download"]),tours:f("tour_request"),inquiries:r.length,shares:s.share_count??0}},[t,r,s]),m=[{label:"Microsite views",value:h.views,icon:Ca},{label:"Unique visitors",value:h.unique,icon:Zn},{label:"Repeat visitors",value:h.repeat,icon:af},{label:"OM requests",value:h.omRequests,icon:NJ},{label:"Document downloads",value:h.downloads,icon:di},{label:"Tour requests",value:h.tours,icon:af},{label:"Total inquiries",value:h.inquiries,icon:Zn},{label:"Shares",value:h.shares,icon:zd}];return e.jsxs("div",{className:"space-y-6",children:[e.jsx("div",{className:"grid gap-px overflow-hidden rounded-xl border bg-border sm:grid-cols-2 lg:grid-cols-4",children:m.map(f=>e.jsxs("div",{className:"bg-card px-5 py-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground",children:[e.jsx(f.icon,{className:"h-3.5 w-3.5"}),e.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-[0.16em]",children:f.label})]}),e.jsx("p",{className:"mt-1.5 text-2xl font-semibold tabular-nums",children:f.value})]},f.label))}),e.jsxs(Ne,{children:[e.jsxs(Ct,{children:[e.jsx(At,{className:"text-base",children:"Send the weekly owner report"}),e.jsx(Gn,{children:"Last 7 days of activity, packaged as a branded report the owner can read in their inbox."})]}),e.jsxs(Ie,{className:"space-y-4",children:[e.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Owner email(s)"}),e.jsx(pe,{placeholder:"owner@example.com, asset.manager@example.com",value:a,onChange:f=>i(f.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Broker note (optional)"}),e.jsx(Rs,{rows:2,placeholder:"What you did this week and what happens next.",value:l,onChange:f=>o(f.target.value)})]})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs($,{onClick:()=>u(!0),disabled:c,children:[c?e.jsx(kt,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(mn,{className:"mr-2 h-4 w-4"}),"Send report"]}),e.jsx($,{variant:"outline",onClick:()=>u(!1),disabled:c,children:"Save without sending"})]})]})]}),e.jsxs(Ne,{children:[e.jsxs(Ct,{children:[e.jsx(At,{className:"text-base",children:"Owner activity report"}),e.jsx(Gn,{children:"Everything below is what your owner sees in the weekly activity report — proof the asset is being worked."})]}),e.jsx(Ie,{children:n?e.jsx("div",{className:"flex justify-center py-10",children:e.jsx(kt,{className:"h-5 w-5 animate-spin text-muted-foreground"})}):t.length===0?e.jsxs("div",{className:"rounded-xl border border-dashed py-14 text-center",children:[e.jsx(af,{className:"mx-auto mb-3 h-7 w-7 text-muted-foreground"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Activity appears here the moment the microsite goes live and prospects engage."})]}):e.jsx("div",{className:"space-y-1",children:t.slice(0,40).map(f=>e.jsxs("div",{className:"flex items-center justify-between gap-3 rounded-lg px-3 py-2 hover:bg-muted/50",children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-3",children:[e.jsx("span",{className:"h-1.5 w-1.5 shrink-0 rounded-full bg-primary/60"}),e.jsx("p",{className:"truncate text-sm",children:NGs[f.event_type]??f.event_type}),f.lead_id&&e.jsx(Be,{variant:"secondary",className:"shrink-0",children:"Identified"})]}),e.jsx("p",{className:"shrink-0 text-xs text-muted-foreground",children:new Date(f.created_at).toLocaleString(void 0,{month:"short",day:"numeric",hour:"numeric",minute:"2-digit"})})]},f.id))})})]})]})}function SGs({listing:s,details:t,publicUrl:n}){var g,x;const r=Qn(),[a,i]=j.useState(!1),l=s.photos??[],[o,c]=j.useState(0),d=(g=l[o])==null?void 0:g.photo_url,u=[...(t==null?void 0:t.investment_highlights)??[],...(t==null?void 0:t.property_highlights)??[]].filter(Boolean),h=(t==null?void 0:t.spaces)??[],m=(t==null?void 0:t.tenants)??[],f=s.agent;return e.jsxs(Vs,{title:"Commercial Listing",children:[e.jsxs("div",{className:"mx-auto max-w-6xl px-4 py-6",children:[e.jsxs($,{variant:"ghost",size:"sm",className:"-ml-2 mb-4",onClick:()=>r("/mission-control/listings"),children:[e.jsx(qa,{className:"mr-2 h-4 w-4"})," Listing Exchange"]}),e.jsx("div",{className:"overflow-hidden rounded-2xl border bg-muted",children:d?e.jsx("img",{src:d,alt:iL(s,t),className:"h-[300px] w-full object-cover md:h-[440px]"}):e.jsxs("div",{className:"flex h-[240px] w-full items-center justify-center text-muted-foreground",children:[e.jsx(Mc,{className:"mr-2 h-5 w-5"})," No photos yet"]})}),l.length>1&&e.jsx("div",{className:"mt-3 flex gap-2 overflow-x-auto pb-1",children:l.map((y,v)=>e.jsx("button",{onClick:()=>c(v),className:`h-16 w-24 shrink-0 overflow-hidden rounded-lg border-2 ${v===o?"border-primary":"border-transparent"}`,children:e.jsx("img",{src:y.photo_url,alt:"",className:"h-full w-full object-cover"})},y.id??v))}),e.jsxs("div",{className:"mt-6 flex flex-wrap items-start justify-between gap-4",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"mb-2 flex flex-wrap items-center gap-2",children:[e.jsxs(Be,{variant:"outline",className:"border-primary/30 bg-primary/10 text-primary",children:[e.jsx(ji,{className:"mr-1 h-3 w-3"})," Commercial"]}),(t==null?void 0:t.deal_type)&&e.jsx(Be,{variant:"secondary",children:ML[t.deal_type]}),(t==null?void 0:t.commercial_type)&&e.jsx(Be,{variant:"secondary",children:c6[t.commercial_type]}),(t==null?void 0:t.is_confidential)&&e.jsxs(Be,{variant:"outline",children:[e.jsx(pc,{className:"mr-1 h-3 w-3"})," Confidential"]})]}),e.jsx("h1",{className:"text-2xl font-semibold tracking-tight md:text-3xl",children:iL(s,t)}),e.jsxs("p",{className:"flex items-center gap-1 text-muted-foreground",children:[e.jsx(ci,{className:"h-4 w-4"})," ",Kae(s,t)]}),e.jsx("p",{className:"mt-2 text-2xl font-semibold",children:EG(t,s.price)})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.is_public&&e.jsxs($,{variant:"outline",onClick:()=>window.open(n,"_blank"),children:[e.jsx(kr,{className:"mr-2 h-4 w-4"})," View microsite"]}),s.allow_sharing&&e.jsxs($,{onClick:()=>i(!0),children:[e.jsx(zd,{className:"mr-2 h-4 w-4"})," Share link"]})]})]}),e.jsx("div",{className:"mt-6",children:e.jsx(H7t,{details:t})}),e.jsxs("div",{className:"mt-6 grid gap-6 lg:grid-cols-3",children:[e.jsxs("div",{className:"space-y-6 lg:col-span-2",children:[s.description&&e.jsxs(Ne,{children:[e.jsx(Ct,{children:e.jsx(At,{className:"text-base",children:"About this property"})}),e.jsx(Ie,{className:"whitespace-pre-line text-sm text-muted-foreground",children:s.description})]}),u.length>0&&e.jsxs(Ne,{children:[e.jsx(Ct,{children:e.jsx(At,{className:"text-base",children:"Highlights"})}),e.jsx(Ie,{className:"space-y-2",children:u.map((y,v)=>e.jsxs("div",{className:"flex items-start gap-2 text-sm",children:[e.jsx(Nn,{className:"mt-0.5 h-4 w-4 shrink-0 text-primary"}),e.jsx("span",{children:y})]},v))})]}),h.length>0&&e.jsxs(Ne,{children:[e.jsx(Ct,{children:e.jsx(At,{className:"text-base",children:"Available spaces"})}),e.jsx(Ie,{className:"space-y-2 text-sm",children:h.map((y,v)=>e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2 border-b pb-2 last:border-0",children:[e.jsx("span",{className:"font-medium",children:y.suite||`Space ${v+1}`}),e.jsx("span",{className:"text-muted-foreground",children:[bE(y.sf),y.rate,y.use,y.availability].filter(Boolean).join(" · ")})]},v))})]}),m.length>0&&e.jsxs(Ne,{children:[e.jsx(Ct,{children:e.jsx(At,{className:"text-base",children:"Tenant roster"})}),e.jsx(Ie,{className:"space-y-2 text-sm",children:m.map((y,v)=>e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2 border-b pb-2 last:border-0",children:[e.jsx("span",{className:"font-medium",children:y.name||`Tenant ${v+1}`}),e.jsx("span",{className:"text-muted-foreground",children:[bE(y.sf),y.rent,y.lease_expiry].filter(Boolean).join(" · ")})]},v))})]})]}),e.jsxs("div",{className:"space-y-6",children:[e.jsxs(Ne,{children:[e.jsx(Ct,{children:e.jsx(At,{className:"text-base",children:"Listing agent"})}),e.jsxs(Ie,{className:"space-y-3 text-sm",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:(f==null?void 0:f.name)||"LevelUp Member"}),((x=f==null?void 0:f.brokerage)==null?void 0:x.name)&&e.jsx("p",{className:"text-muted-foreground",children:f.brokerage.name})]}),(f==null?void 0:f.email)&&e.jsxs($,{variant:"outline",className:"w-full",onClick:()=>window.open(`mailto:${f.email}`),children:[e.jsx(mn,{className:"mr-2 h-4 w-4"})," Email agent"]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Only the listing agent can update this listing."})]})]}),s.open_to_referrals&&e.jsxs(Ne,{children:[e.jsx(Ct,{children:e.jsx(At,{className:"text-base",children:"Open to referrals"})}),e.jsx(Ie,{className:"text-sm text-muted-foreground",children:"The listing agent welcomes buyer or tenant referrals on this opportunity."})]})]})]})]}),e.jsx(w6e,{open:a,onOpenChange:i,listingId:s.id,listingSlug:s.slug??null,listingTitle:iL(s,t),isCommercial:!0})]})}function CGs(){const{listingId:s=""}=Wi(),t=Qn(),{user:n}=vs(),[r,a]=gc(),{data:i,isLoading:l}=tie(s),{data:o}=B7t(s),{data:c=[]}=d6e(s),{data:d=[]}=sst(s),{data:u=[]}=nst(s),h=$7t(),m=q7t(),f=TDs(),g=U$t(),x=q$t(),y=V$t(),v=H$t(),[b,w]=j.useState(!1),[S,C]=j.useState(!1),[E,I]=j.useState(!1),[P,R]=j.useState(!1),[D,O]=j.useState(!1),U=r.get("tab")||"overview",W=J=>a({tab:J},{replace:!0}),V=i?`${window.location.origin}/public/listing/${i.slug||i.id}`:"",G=j.useMemo(()=>{var J;return CDs(o,{photoCount:((J=i==null?void 0:i.photos)==null?void 0:J.length)??0,hasOm:c.some(ce=>ce.doc_kind==="om"),isPublic:!!(i!=null&&i.is_public)})},[o,i,c]),Y=async J=>{var ce;if(!(!J||!i)){w(!0);try{for(const _e of Array.from(J)){const he=_e.name.split(".").pop(),ue=`${n==null?void 0:n.id}/${i.id}/${Date.now()}-${Math.random().toString(36).slice(2)}.${he}`,{error:ve}=await q.storage.from("listing-photos").upload(ue,_e);if(ve)throw ve;const{data:{publicUrl:Ee}}=q.storage.from("listing-photos").getPublicUrl(ue);await g.mutateAsync({listingId:i.id,photoUrl:Ee,isPrimary:!((ce=i.photos)!=null&&ce.length)})}re.success("Photos uploaded")}catch(_e){re.error(_e.message||"Upload failed")}finally{w(!1)}}};if(l)return e.jsx(Vs,{title:"Commercial Launch",children:e.jsx("div",{className:"flex min-h-[50vh] items-center justify-center",children:e.jsx(kt,{className:"h-6 w-6 animate-spin text-muted-foreground"})})});if(!i)return e.jsx(Vs,{title:"Commercial Launch",children:e.jsx("div",{className:"flex min-h-[50vh] items-center justify-center text-muted-foreground",children:"Listing not found"})});const X=i.lifecycle_stage==="pitch",ae=i.lifecycle_stage??"won",ie=m7e.findIndex(J=>J.key===ae),ne=iL(i,o),te=!!(n!=null&&n.id)&&i.agent_id===n.id;return te?e.jsx(Vs,{title:"Commercial Launch",children:e.jsxs("div",{className:"bg-background",children:[e.jsx("div",{className:"border-b bg-gradient-to-b from-muted/40 to-background",children:e.jsxs("div",{className:"mx-auto max-w-7xl px-4 py-6",children:[e.jsxs($,{variant:"ghost",size:"sm",className:"-ml-2 mb-4",onClick:()=>t("/mission-control/listings"),children:[e.jsx(qa,{className:"mr-2 h-4 w-4"})," Listing Exchange"]}),e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-4",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"mb-2 flex flex-wrap items-center gap-2",children:[e.jsxs(Be,{variant:"outline",className:"border-primary/30 bg-primary/10 text-primary",children:[e.jsx(ji,{className:"mr-1 h-3 w-3"})," Commercial Launch"]}),(o==null?void 0:o.deal_type)&&e.jsx(Be,{variant:"secondary",children:ML[o.deal_type]}),(o==null?void 0:o.commercial_type)&&e.jsx(Be,{variant:"secondary",children:c6[o.commercial_type]}),X&&e.jsxs(Be,{className:"bg-amber-500/15 text-amber-600 hover:bg-amber-500/15",children:[e.jsx(rh,{className:"mr-1 h-3 w-3"})," Pitch — private"]}),(o==null?void 0:o.is_confidential)&&e.jsxs(Be,{variant:"outline",children:[e.jsx(pc,{className:"mr-1 h-3 w-3"})," Confidential"]})]}),e.jsx("h1",{className:"text-2xl font-semibold tracking-tight md:text-3xl",children:ne}),e.jsx("p",{className:"text-muted-foreground",children:Kae(i,o)}),e.jsx("p",{className:"mt-2 text-xl font-semibold",children:EG(o,i.price)})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[!te&&e.jsxs(Be,{variant:"outline",className:"self-center",children:[e.jsx(pc,{className:"mr-1 h-3 w-3"})," View only — listing agent controls updates"]}),te&&e.jsxs($,{variant:"outline",onClick:()=>t(`/mission-control/listings/${i.id}/commercial/edit`),children:[e.jsx(gi,{className:"mr-2 h-4 w-4"})," Edit details"]}),te&&!X&&!i.is_public&&e.jsxs($,{onClick:()=>{f.mutate({listingId:i.id,values:{is_public:!0,allow_sharing:!0,status:"active"}}),ae==="won"&&m.mutate({listingId:i.id,stage:"launched"})},children:[e.jsx(kr,{className:"mr-2 h-4 w-4"})," Publish & go live"]}),!X&&i.is_public&&e.jsxs($,{variant:"outline",onClick:()=>window.open(V,"_blank"),children:[e.jsx(kr,{className:"mr-2 h-4 w-4"})," View microsite"]})]})]}),!X&&e.jsx("div",{className:"mt-6 flex flex-wrap items-center gap-2",children:m7e.filter(J=>J.key!=="pitch").map((J,ce)=>{const _e=m7e.findIndex(ve=>ve.key===J.key),he=_e===ie,ue=_ete&&m.mutate({listingId:i.id,stage:J.key}),className:`flex items-center gap-2 rounded-full border px-3.5 py-1.5 text-xs font-medium transition-colors ${he?"border-primary bg-primary text-primary-foreground":ue?"border-primary/30 bg-primary/10 text-primary":"text-muted-foreground hover:bg-muted"} ${te?"":"cursor-default"}`,children:[ue&&e.jsx(la,{className:"h-3 w-3"})," ",J.label,ce<4&&e.jsx("span",{className:"ml-1 opacity-40",children:"›"})]},J.key)})})]})}),e.jsx("div",{className:"mx-auto max-w-7xl px-4 py-8",children:X?e.jsx(bGs,{listing:i,canEdit:te}):e.jsxs(ha,{value:te||["overview","marketing"].includes(U)?U:"overview",onValueChange:W,children:[e.jsxs(ma,{className:"mb-6 flex w-full flex-wrap justify-start",children:[e.jsx(Zt,{value:"overview",children:"Overview"}),e.jsx(Zt,{value:"marketing",children:"Marketing"}),te&&e.jsx(Zt,{value:"investors",children:"Investors & Leads"}),te&&e.jsx(Zt,{value:"reporting",children:"Reporting"}),te&&e.jsx(Zt,{value:"documents",children:"Documents"}),te&&e.jsx(Zt,{value:"settings",children:"Settings"})]}),e.jsxs(Xt,{value:"overview",className:"space-y-6",children:[e.jsx(H7t,{details:o}),e.jsxs("div",{className:"grid gap-6 lg:grid-cols-3",children:[e.jsxs(Ne,{className:"lg:col-span-2",children:[e.jsxs(Ct,{children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(At,{className:"text-base",children:"Launch readiness"}),e.jsx(Gn,{children:"Everything an institutional-quality launch needs."})]}),e.jsxs("span",{className:"text-2xl font-semibold tabular-nums",children:[G.score,"%"]})]}),e.jsx(Yi,{value:G.score,className:"mt-3"})]}),e.jsx(Ie,{className:"space-y-2",children:e3e.map(J=>{const ce=G.done.includes(J.key);return e.jsxs("button",{disabled:!te,onClick:()=>te&&h.mutate({listingId:i.id,values:{launch_checklist:{...(o==null?void 0:o.launch_checklist)??{},[J.key]:!ce}}}),className:"flex w-full items-start gap-3 rounded-lg px-3 py-2.5 text-left transition-colors hover:bg-muted/60",children:[e.jsx("span",{className:`mt-0.5 flex h-5 w-5 shrink-0 items-center justify-center rounded-full border ${ce?"border-primary bg-primary text-primary-foreground":""}`,children:ce&&e.jsx(la,{className:"h-3 w-3"})}),e.jsxs("span",{children:[e.jsx("span",{className:`block text-sm font-medium ${ce?"text-muted-foreground line-through":""}`,children:J.label}),e.jsx("span",{className:"block text-xs text-muted-foreground",children:J.detail})]})]},J.key)})})]}),e.jsxs("div",{className:"space-y-6",children:[e.jsxs(Ne,{children:[e.jsx(Ct,{children:e.jsx(At,{className:"text-base",children:"Quick actions"})}),e.jsxs(Ie,{className:"grid gap-2",children:[e.jsxs($,{variant:"outline",className:"justify-start",onClick:()=>C(!0),children:[e.jsx(zd,{className:"mr-2 h-4 w-4"})," Share link"]}),e.jsxs($,{variant:"outline",className:"justify-start",onClick:()=>I(!0),children:[e.jsx(Jp,{className:"mr-2 h-4 w-4"})," Signage QR code"]}),te&&e.jsxs($,{variant:"outline",className:"justify-start",onClick:()=>R(!0),children:[e.jsx(mn,{className:"mr-2 h-4 w-4"})," Email brokers & investors"]}),te&&e.jsxs($,{variant:"outline",className:"justify-start",onClick:()=>O(!0),children:[e.jsx(Nn,{className:"mr-2 h-4 w-4"})," Generate social post"]}),te&&e.jsxs($,{variant:"outline",className:"justify-start",onClick:()=>W("documents"),children:[e.jsx(pc,{className:"mr-2 h-4 w-4"})," Manage gated OM"]})]})]}),(o==null?void 0:o.call_for_offers_at)&&e.jsxs(Ne,{className:"border-amber-500/30 bg-amber-500/[0.05]",children:[e.jsx(Ct,{className:"pb-2",children:e.jsx(At,{className:"text-sm",children:"Call for offers"})}),e.jsx(Ie,{children:e.jsxs("p",{className:"flex items-center gap-2 text-lg font-semibold",children:[e.jsx(Au,{className:"h-4 w-4"}),new Date(o.call_for_offers_at).toLocaleDateString(void 0,{month:"long",day:"numeric",year:"numeric"})]})})]}),e.jsxs(Ne,{children:[e.jsx(Ct,{children:e.jsx(At,{className:"text-base",children:"Recent engagement"})}),e.jsxs(Ie,{className:"space-y-2",children:[d.slice(0,6).map(J=>e.jsxs("div",{className:"flex items-center justify-between gap-2 text-sm",children:[e.jsx("span",{className:"truncate capitalize",children:J.event_type.replace(/_/g," ")}),e.jsx("span",{className:"shrink-0 text-xs text-muted-foreground",children:new Date(J.created_at).toLocaleDateString(void 0,{month:"short",day:"numeric"})})]},J.id)),d.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"No activity yet."}),e.jsxs("p",{className:"pt-2 text-xs text-muted-foreground",children:[u.length," inquiries captured"]})]})]})]})]})]}),e.jsxs(Xt,{value:"marketing",className:"space-y-6",children:[e.jsxs(Ne,{children:[e.jsxs(Ct,{children:[e.jsx(At,{className:"text-base",children:"Photography"}),e.jsx(Gn,{children:"The first image becomes the cinematic microsite hero."})]}),e.jsx(Ie,{children:te?e.jsx(vUt,{photos:i.photos??[],uploading:b,onUpload:Y,onRemove:J=>x.mutate({photoId:J,listingId:i.id}),onReorder:J=>y.mutate({photos:J.map(ce=>({id:ce.id,sort_order:ce.sort_order,is_primary:ce.is_primary}))}),onSetPrimary:J=>v.mutate({photoId:J,listingId:i.id})}):e.jsxs("div",{className:"grid grid-cols-2 gap-3 md:grid-cols-4",children:[(i.photos??[]).map(J=>e.jsx("img",{src:J.photo_url,alt:ne,className:"aspect-[4/3] w-full rounded-lg object-cover",loading:"lazy"},J.id)),!(i.photos??[]).length&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"No photos yet."})]})})]}),e.jsx("div",{className:"grid gap-4 md:grid-cols-2 lg:grid-cols-4",children:[{icon:dl,title:"Property microsite",body:"Institutional-grade public page with gated OM.",action:()=>window.open(V,"_blank"),cta:"Preview"},{icon:Jp,title:"Signage QR",body:"On-site sign that routes to the microsite.",action:()=>I(!0),cta:"Create"},...te?[{icon:mn,title:"Broker & investor email",body:"Send to targeted segments of your database.",action:()=>R(!0),cta:"Compose"},{icon:Nn,title:"Social & LinkedIn",body:"Branded launch graphics and copy.",action:()=>O(!0),cta:"Generate"}]:[]].map(J=>e.jsxs(Ne,{className:"flex flex-col",children:[e.jsxs(Ct,{className:"pb-3",children:[e.jsx(J.icon,{className:"mb-2 h-5 w-5"}),e.jsx(At,{className:"text-sm",children:J.title}),e.jsx(Gn,{className:"text-xs",children:J.body})]}),e.jsx(Ie,{className:"mt-auto",children:e.jsx($,{size:"sm",variant:"outline",className:"w-full",onClick:J.action,children:J.cta})})]},J.title))})]}),te&&e.jsx(Xt,{value:"investors",children:e.jsx(jGs,{listingId:i.id})}),te&&e.jsx(Xt,{value:"reporting",children:e.jsx(kGs,{listing:i})}),te&&e.jsx(Xt,{value:"documents",children:e.jsx(_Gs,{listingId:i.id})}),te&&e.jsx(Xt,{value:"settings",className:"space-y-6",children:e.jsxs(Ne,{children:[e.jsxs(Ct,{children:[e.jsx(At,{className:"text-base",children:"Visibility"}),e.jsx(Gn,{children:"Control who can see this offering."})]}),e.jsxs(Ie,{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between rounded-lg border p-3",children:[e.jsxs("div",{children:[e.jsx(ee,{children:"Publish public microsite"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Makes the commercial microsite live at a shareable URL."})]}),e.jsx(Sn,{checked:!!i.is_public,onCheckedChange:J=>{f.mutate({listingId:i.id,values:{is_public:J,allow_sharing:J?!0:i.allow_sharing}}),J&&ae==="won"&&m.mutate({listingId:i.id,stage:"launched"})}})]}),e.jsxs("div",{className:"flex items-center justify-between rounded-lg border p-3",children:[e.jsxs("div",{children:[e.jsx(ee,{children:"Share inside my brokerage"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Visible to agents in your brokerage on the Exchange."})]}),e.jsx(Sn,{checked:!!i.share_with_brokerage,onCheckedChange:J=>f.mutate({listingId:i.id,values:{share_with_brokerage:J}})})]}),e.jsxs("div",{className:"flex items-center justify-between rounded-lg border p-3",children:[e.jsxs("div",{children:[e.jsx(ee,{children:"Confidential offering"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Teaser mode, address hidden, search engines blocked."})]}),e.jsx(Sn,{checked:!!(o!=null&&o.is_confidential),onCheckedChange:J=>h.mutate({listingId:i.id,values:{is_confidential:J}})})]}),e.jsxs("div",{className:"flex items-center justify-between rounded-lg border p-3",children:[e.jsxs("div",{children:[e.jsx(ee,{children:"Hide street address"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Show city / submarket only."})]}),e.jsx(Sn,{checked:!!(o!=null&&o.hide_address),onCheckedChange:J=>h.mutate({listingId:i.id,values:{hide_address:J}})})]}),V&&e.jsxs("div",{className:"flex items-center gap-2 rounded-lg border bg-muted/40 px-3 py-2",children:[e.jsx("span",{className:"truncate text-xs text-muted-foreground",children:V}),e.jsx($,{variant:"ghost",size:"icon",onClick:()=>{navigator.clipboard.writeText(V),re.success("Copied")},children:e.jsx(Ha,{className:"h-3.5 w-3.5"})})]})]})]})})]})}),e.jsx(w6e,{open:S,onOpenChange:C,listingId:i.id,listingSlug:i.slug,listingTitle:ne,isCommercial:!0}),e.jsx(PUt,{open:E,onOpenChange:I,url:V,title:ne,fileBase:i.slug||i.id}),e.jsx(VUt,{open:P,onOpenChange:R,listing:i}),e.jsx(lnt,{open:D,onOpenChange:O,listingId:i.id})]})}):X?e.jsx(Vs,{title:"Commercial Launch",children:e.jsx("div",{className:"flex min-h-[50vh] items-center justify-center text-muted-foreground",children:"This opportunity is private to the listing agent."})}):e.jsx(SGs,{listing:i,details:o,publicUrl:V})}function AGs(){var m,f,g;const{token:s=""}=Wi(),{data:t,isLoading:n,error:r}=tt({queryKey:["commercial-pitch-preview",s],queryFn:async()=>{const{data:x,error:y}=await q.functions.invoke("commercial-pitch-preview",{body:{token:s}});if(y)throw y;if(x!=null&&x.error)throw new Error(x.error);return x},enabled:!!s});if(n)return e.jsx("div",{className:"flex min-h-screen items-center justify-center bg-[#0b0f14]",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-2 border-white/20 border-t-white/70"})});if(r||!(t!=null&&t.listing))return e.jsx("div",{className:"flex min-h-screen items-center justify-center bg-[#0b0f14] px-6 text-center text-white/60",children:"This preview link is no longer active."});const{listing:a,details:i,pitch:l}=t,o=a.agent,c=(f=(m=a.photos)==null?void 0:m[0])==null?void 0:f.photo_url,d=rst(i).slice(0,4),u=l.launch_plan??[],h=[{icon:dl,label:"Dedicated property microsite",detail:"An institutional-grade page built for this asset alone."},{icon:Jr,label:"Offering Memorandum & teaser",detail:"Gated, tracked and released only to qualified prospects."},{icon:mn,label:"Targeted broker & investor email",detail:"Direct outreach to buyers, brokers and 1031 capital."},{icon:Jp,label:"Signage, QR & social distribution",detail:"On-site and digital presence working together."},{icon:Wl,label:"Weekly owner activity reporting",detail:"Views, OM requests, downloads, tours and prospect interest."},{icon:bm,label:"Confidentiality controls",detail:"Address, financials and documents released on your terms."}];return e.jsxs("div",{className:"min-h-screen bg-[#0b0f14] text-white antialiased",children:[e.jsxs(Ml,{children:[e.jsxs("title",{children:["Marketing proposal — ",iL(a,i)]}),e.jsx("meta",{name:"robots",content:"noindex,nofollow"})]}),e.jsxs("section",{className:"relative min-h-[70vh] overflow-hidden",children:[c?e.jsx("img",{src:c,alt:"",className:"absolute inset-0 h-full w-full object-cover"}):e.jsx("div",{className:"absolute inset-0 bg-gradient-to-br from-[#12202b] to-[#0b0f14]"}),e.jsx("div",{className:"absolute inset-0 bg-gradient-to-t from-[#0b0f14] via-[#0b0f14]/70 to-[#0b0f14]/40"}),e.jsxs("div",{className:"relative mx-auto flex min-h-[70vh] max-w-6xl flex-col justify-end px-6 pb-14 pt-24 md:px-10",children:[e.jsxs("p",{className:"text-[10px] font-semibold uppercase tracking-[0.24em] text-white/45",children:["Private marketing proposal",l.owner_name?` prepared for ${l.owner_name}`:""]}),e.jsx("h1",{className:"mt-4 max-w-3xl font-serif text-4xl leading-[1.05] md:text-6xl",children:iL(a,i)}),e.jsxs("p",{className:"mt-4 flex items-center gap-2 text-sm uppercase tracking-[0.2em] text-white/55",children:[e.jsx(ci,{className:"h-4 w-4"})," ",Kae(a,i)]}),e.jsxs("div",{className:"mt-6 flex flex-wrap gap-2.5",children:[e.jsx("span",{className:"rounded-full border border-white/25 px-3.5 py-1 text-[10px] font-semibold uppercase tracking-[0.22em]",children:ML[(i==null?void 0:i.deal_type)??"sale"]}),(i==null?void 0:i.commercial_type)&&e.jsx("span",{className:"rounded-full border border-white/15 bg-white/5 px-3.5 py-1 text-[10px] font-semibold uppercase tracking-[0.22em] text-white/70",children:c6[i.commercial_type]})]})]})]}),d.length>0&&e.jsx("div",{className:"grid grid-cols-2 gap-px border-y border-white/10 bg-white/10 md:grid-cols-4",children:d.map(x=>e.jsxs("div",{className:"bg-[#0b0f14] px-6 py-7",children:[e.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-[0.2em] text-white/40",children:x.label}),e.jsx("p",{className:"mt-2 text-2xl font-semibold tabular-nums",children:x.value})]},x.label))}),(l.positioning||l.pricing_strategy)&&e.jsxs("section",{className:"mx-auto max-w-6xl px-6 py-20 md:px-10",children:[e.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-[0.24em] text-white/40",children:"Recommendation"}),e.jsx("h2",{className:"mt-3 font-serif text-3xl md:text-4xl",children:"How we take this asset to market"}),e.jsxs("div",{className:"mt-10 grid gap-10 md:grid-cols-2",children:[l.positioning&&e.jsxs("div",{children:[e.jsx("h3",{className:"text-sm font-semibold uppercase tracking-[0.16em] text-white/50",children:"Positioning"}),e.jsx("p",{className:"mt-4 whitespace-pre-line text-lg leading-relaxed text-white/75",children:l.positioning})]}),l.pricing_strategy&&e.jsxs("div",{children:[e.jsx("h3",{className:"text-sm font-semibold uppercase tracking-[0.16em] text-white/50",children:"Pricing strategy"}),e.jsx("p",{className:"mt-4 whitespace-pre-line text-lg leading-relaxed text-white/75",children:l.pricing_strategy}),e.jsx("p",{className:"mt-6 text-2xl font-semibold",children:EG(i,a.price)})]})]})]}),u.length>0&&e.jsx("section",{className:"border-t border-white/10",children:e.jsxs("div",{className:"mx-auto max-w-6xl px-6 py-20 md:px-10",children:[e.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-[0.24em] text-white/40",children:"The plan"}),e.jsx("h2",{className:"mt-3 font-serif text-3xl md:text-4xl",children:"What happens the day you hire us"}),e.jsx("div",{className:"mt-12 space-y-8",children:u.map((x,y)=>e.jsxs("div",{className:"flex gap-6 border-t border-white/10 pt-6",children:[e.jsx("span",{className:"font-serif text-2xl text-white/25 tabular-nums",children:String(y+1).padStart(2,"0")}),e.jsxs("div",{children:[e.jsx("p",{className:"text-lg font-medium",children:x.label}),x.detail&&e.jsx("p",{className:"mt-1.5 text-white/60",children:x.detail})]})]},y))})]})}),e.jsx("section",{className:"border-t border-white/10",children:e.jsxs("div",{className:"mx-auto max-w-6xl px-6 py-20 md:px-10",children:[e.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-[0.24em] text-white/40",children:"Distribution"}),e.jsx("h2",{className:"mt-3 font-serif text-3xl md:text-4xl",children:"Where your property shows up"}),e.jsx("div",{className:"mt-12 grid gap-4 md:grid-cols-3",children:h.map(x=>e.jsxs("div",{className:"rounded-2xl border border-white/10 bg-white/[0.03] p-7",children:[e.jsx(x.icon,{className:"mb-4 h-5 w-5 text-white/70"}),e.jsx("p",{className:"font-medium",children:x.label}),e.jsx("p",{className:"mt-1.5 text-sm text-white/55",children:x.detail})]},x.label))})]})}),o&&e.jsx("section",{className:"border-t border-white/10 bg-white/[0.02]",children:e.jsxs("div",{className:"mx-auto flex max-w-6xl flex-col items-start gap-6 px-6 py-16 md:flex-row md:items-center md:justify-between md:px-10",children:[e.jsxs("div",{className:"flex items-center gap-5",children:[o.avatar_url&&e.jsx("img",{src:o.avatar_url,alt:o.name,className:"h-20 w-20 rounded-full object-cover ring-1 ring-white/15"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-[0.22em] text-white/40",children:"Prepared by"}),e.jsx("p",{className:"mt-2 font-serif text-2xl",children:o.name}),e.jsx("p",{className:"text-sm text-white/55",children:((g=o.brokerage)==null?void 0:g.name)||o.brokerage_name})]})]}),e.jsxs("div",{className:"flex gap-3 text-sm text-white/70",children:[o.email&&e.jsx("a",{className:"rounded-full border border-white/20 px-5 py-2 hover:bg-white/10",href:`mailto:${o.email}`,children:"Email"}),o.phone&&e.jsx("a",{className:"rounded-full border border-white/20 px-5 py-2 hover:bg-white/10",href:`tel:${o.phone}`,children:"Call"})]})]})}),e.jsx("footer",{className:"py-10 text-center text-xs text-white/35",children:"Confidential — prepared exclusively for the property owner."})]})}const EGs={office_exclusive:"Office Exclusive",coming_soon:"Coming Soon",pre_market:"Pre-Market",active:"Active"},TGs=s=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(s||0);function MGs(){var J;const[s]=gc(),t=s.get("r"),n=s.get("m"),[r,a]=j.useState(null),[i,l]=j.useState(null),[o,c]=j.useState(!0),[d,u]=j.useState(0),[h,m]=j.useState(!1),[f,g]=j.useState(""),[x,y]=j.useState(""),[v,b]=j.useState(""),[w,S]=j.useState(""),[C,E]=j.useState("tour"),[I,P]=j.useState(!1),[R,D]=j.useState(!1),O=async()=>{if(!f.trim()||!x.trim()){re.error("Please enter your name and email");return}P(!0);try{const _e=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/private-listing-lead",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({r:t,m:n,name:f.trim(),email:x.trim(),phone:v.trim()||null,message:w.trim()||null,intent:C})}),he=await _e.json();if(!_e.ok||!(he!=null&&he.success))throw new Error((he==null?void 0:he.error)||"Could not send");D(!0),re.success("Sent! The agent will be in touch shortly.")}catch(ce){re.error((ce==null?void 0:ce.message)||"Could not send")}finally{P(!1)}};if(j.useEffect(()=>{if(!t||!n){l("Invalid link"),c(!1);return}const ce=`https://relzejiswnotikjgvjhz.supabase.co/functions/v1/private-listing-view?r=${encodeURIComponent(t)}&m=${encodeURIComponent(n)}`;fetch(ce).then(_e=>_e.json()).then(_e=>{_e.error?l("This private listing link is no longer valid."):a({listing:_e.listing,agent:_e.agent})}).catch(()=>l("Unable to load listing.")).finally(()=>c(!1))},[t,n]),o)return e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-slate-50",children:e.jsx("div",{className:"text-slate-500",children:"Loading…"})});if(i||!r)return e.jsxs(e.Fragment,{children:[e.jsx(Ml,{children:e.jsx("meta",{name:"robots",content:"noindex,nofollow,noarchive"})}),e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-slate-50 px-6 text-center",children:e.jsxs("div",{children:[e.jsx(pc,{className:"h-10 w-10 text-slate-400 mx-auto mb-3"}),e.jsx("h1",{className:"text-xl font-semibold text-slate-900",children:"Private listing unavailable"}),e.jsx("p",{className:"text-slate-600 mt-2",children:i||"This link has expired or was not shared with you."})]})})]});const{listing:U,agent:W}=r,V=(J=U.photos)!=null&&J.length?U.photos:[],G=V[0],Y=EGs[U.status]||U.status,X=(W==null?void 0:W.sender_name)||(W==null?void 0:W.name)||"Your Agent",ae=(W==null?void 0:W.sender_email)||null,ie=encodeURIComponent(`Interested in ${U.address}`),ne=encodeURIComponent(`Hi ${X}, I'd love to learn more about ${U.address}, ${U.city}. Thanks!`),te=W!=null&&W.booking_slug?`https://dashboard.relevelup.com/book/${W.booking_slug}`:null;return e.jsxs(e.Fragment,{children:[e.jsxs(Ml,{children:[e.jsxs("title",{children:["Private Listing · ",U.address]}),e.jsx("meta",{name:"robots",content:"noindex,nofollow,noarchive,nosnippet"}),e.jsx("meta",{name:"googlebot",content:"noindex,nofollow,noarchive,nosnippet"})]}),e.jsxs("div",{className:"min-h-screen bg-gradient-to-b from-slate-50 to-white",children:[e.jsxs("div",{className:"bg-gradient-to-r from-indigo-600 to-indigo-500 text-white text-center text-xs sm:text-sm py-2 px-4 flex items-center justify-center gap-2",children:[e.jsx(pc,{className:"h-3.5 w-3.5"}),e.jsxs("span",{className:"font-medium tracking-wide uppercase",children:["Private listing · Shared by ",X]})]}),e.jsxs("div",{className:"relative",children:[G?e.jsx("button",{type:"button",className:"block w-full",onClick:()=>{u(0),m(!0)},children:e.jsx("img",{src:G,alt:U.address,className:"w-full h-[42vh] md:h-[60vh] object-cover"})}):e.jsx("div",{className:"w-full h-[42vh] md:h-[60vh] bg-slate-200 flex items-center justify-center text-slate-400",children:"No photos available"}),e.jsx("div",{className:"absolute top-4 left-4",children:e.jsx(Be,{className:"bg-indigo-600 text-white border-0 text-xs px-2.5 py-1 shadow",children:Y})}),V.length>1&&e.jsxs("div",{className:"absolute bottom-4 right-4 bg-black/60 text-white text-xs px-2.5 py-1 rounded-full",children:[V.length," photos"]})]}),e.jsxs("div",{className:"max-w-5xl mx-auto px-4 sm:px-6 -mt-10 relative z-10",children:[e.jsx(Ne,{className:"shadow-xl border-slate-200",children:e.jsxs(Ie,{className:"p-6 sm:p-8",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-start sm:justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl sm:text-3xl font-bold text-slate-900",children:U.address}),e.jsxs("p",{className:"text-slate-600 mt-1 flex items-center gap-1.5",children:[e.jsx(ci,{className:"h-4 w-4"}),U.city,", ",U.state," ",U.zip]})]}),e.jsx("div",{className:"text-right",children:e.jsx("p",{className:"text-3xl sm:text-4xl font-bold text-indigo-600",children:TGs(U.price)})})]}),e.jsxs("div",{className:"grid grid-cols-3 gap-3 mt-6",children:[U.bedrooms?e.jsxs("div",{className:"bg-slate-50 rounded-lg p-3 text-center",children:[e.jsx(l2,{className:"h-5 w-5 mx-auto text-slate-500 mb-1"}),e.jsx("p",{className:"text-lg font-semibold text-slate-900",children:U.bedrooms}),e.jsx("p",{className:"text-xs text-slate-500",children:"Beds"})]}):null,U.bathrooms?e.jsxs("div",{className:"bg-slate-50 rounded-lg p-3 text-center",children:[e.jsx(T0,{className:"h-5 w-5 mx-auto text-slate-500 mb-1"}),e.jsx("p",{className:"text-lg font-semibold text-slate-900",children:U.bathrooms}),e.jsx("p",{className:"text-xs text-slate-500",children:"Baths"})]}):null,U.sqft?e.jsxs("div",{className:"bg-slate-50 rounded-lg p-3 text-center",children:[e.jsx(C_,{className:"h-5 w-5 mx-auto text-slate-500 mb-1"}),e.jsx("p",{className:"text-lg font-semibold text-slate-900",children:U.sqft.toLocaleString()}),e.jsx("p",{className:"text-xs text-slate-500",children:"Sq Ft"})]}):null]}),U.description&&e.jsxs("div",{className:"mt-8",children:[e.jsx("h2",{className:"text-lg font-semibold text-slate-900 mb-2",children:"About this property"}),e.jsx("p",{className:"text-slate-700 leading-relaxed whitespace-pre-line",children:U.description})]}),V.length>1&&e.jsxs("div",{className:"mt-8",children:[e.jsx("h2",{className:"text-lg font-semibold text-slate-900 mb-3",children:"Photos"}),e.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 gap-2",children:V.slice(0,9).map((ce,_e)=>e.jsx("button",{type:"button",onClick:()=>{u(_e),m(!0)},className:"aspect-[4/3] overflow-hidden rounded-lg bg-slate-100",children:e.jsx("img",{src:ce,alt:"",className:"w-full h-full object-cover hover:scale-105 transition"})},_e))})]})]})}),e.jsxs(Ne,{className:"mt-6 shadow-lg border-slate-200 overflow-hidden",children:[e.jsxs("div",{className:"bg-gradient-to-r from-indigo-600 to-indigo-500 px-6 py-4 text-white",children:[e.jsx("h2",{className:"text-lg font-semibold",children:"Request more info or a private tour"}),e.jsxs("p",{className:"text-indigo-100 text-sm",children:[X," will get back to you personally."]})]}),e.jsx(Ie,{className:"p-6 sm:p-8",children:R?e.jsxs("div",{className:"flex flex-col items-center text-center py-6",children:[e.jsx(qr,{className:"h-12 w-12 text-emerald-500 mb-3"}),e.jsx("h3",{className:"text-lg font-semibold text-slate-900",children:"Message sent"}),e.jsxs("p",{className:"text-slate-600 mt-1",children:[X," just got your request and will reach out shortly."]})]}):e.jsxs("div",{className:"space-y-4",children:[e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-3 gap-2",children:[{id:"tour",label:"Private tour"},{id:"info",label:"More info"},{id:"offer",label:"Make an offer"}].map(ce=>e.jsx("button",{type:"button",onClick:()=>E(ce.id),className:`px-3 py-2 rounded-lg border text-sm font-medium transition ${C===ce.id?"bg-indigo-600 text-white border-indigo-600":"bg-white text-slate-700 border-slate-200 hover:border-indigo-300"}`,children:ce.label},ce.id))}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"pl-name",children:"Your name *"}),e.jsx(pe,{id:"pl-name",value:f,onChange:ce=>g(ce.target.value),placeholder:"Jane Doe",maxLength:120})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"pl-email",children:"Email *"}),e.jsx(pe,{id:"pl-email",type:"email",value:x,onChange:ce=>y(ce.target.value),placeholder:"you@email.com",maxLength:255})]})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"pl-phone",children:"Phone (optional)"}),e.jsx(pe,{id:"pl-phone",value:v,onChange:ce=>b(ce.target.value),placeholder:"(555) 555-5555",maxLength:40})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"pl-msg",children:"Message (optional)"}),e.jsx(Rs,{id:"pl-msg",value:w,onChange:ce=>S(ce.target.value),placeholder:`I'd love to see ${U.address}…`,rows:4,maxLength:2e3})]}),e.jsx($,{onClick:O,disabled:I,className:"w-full bg-indigo-600 hover:bg-indigo-700 h-11 text-base",children:I?"Sending…":"Send to "+X.split(" ")[0]}),e.jsx("p",{className:"text-xs text-slate-500 text-center",children:"By submitting, you agree to be contacted about this property."})]})})]}),e.jsx(Ne,{className:"mt-6 mb-12 shadow-lg border-slate-200",children:e.jsxs(Ie,{className:"p-6 sm:p-8",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row items-center sm:items-start gap-5",children:[W!=null&&W.avatar_url?e.jsx("img",{src:W.avatar_url,alt:X,className:"h-20 w-20 rounded-full object-cover ring-2 ring-indigo-100"}):e.jsx("div",{className:"h-20 w-20 rounded-full bg-indigo-100 flex items-center justify-center text-indigo-600 text-2xl font-bold",children:X.charAt(0)}),e.jsxs("div",{className:"flex-1 text-center sm:text-left",children:[e.jsx("p",{className:"text-xs uppercase tracking-wider text-slate-500",children:"Shared by"}),e.jsx("h3",{className:"text-xl font-bold text-slate-900",children:X}),(W==null?void 0:W.brokerage_name)&&e.jsx("p",{className:"text-slate-600 text-sm",children:W.brokerage_name}),e.jsx("p",{className:"text-slate-600 text-sm mt-2",children:"Want a private tour or more info? Reach out — I'm happy to help."})]})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-3 gap-2 mt-6",children:[ae&&e.jsx($,{asChild:!0,className:"bg-indigo-600 hover:bg-indigo-700",children:e.jsxs("a",{href:`mailto:${ae}?subject=${ie}&body=${ne}`,children:[e.jsx(mn,{className:"h-4 w-4 mr-1.5"}),"Email"]})}),(W==null?void 0:W.phone)&&e.jsx($,{asChild:!0,variant:"outline",children:e.jsxs("a",{href:`tel:${W.phone}`,children:[e.jsx(Da,{className:"h-4 w-4 mr-1.5"}),W.phone]})}),te&&e.jsx($,{asChild:!0,variant:"outline",children:e.jsxs("a",{href:te,target:"_blank",rel:"noreferrer",children:[e.jsx(Au,{className:"h-4 w-4 mr-1.5"}),"Book a tour"]})})]})]})})]}),h&&V.length>0&&e.jsxs("div",{className:"fixed inset-0 z-50 bg-black/95 flex items-center justify-center",children:[e.jsx("button",{className:"absolute top-4 right-4 text-white p-2 hover:bg-white/10 rounded-full",onClick:()=>m(!1),"aria-label":"Close",children:e.jsx(gr,{className:"h-6 w-6"})}),e.jsx("button",{className:"absolute left-4 text-white p-2 hover:bg-white/10 rounded-full",onClick:()=>u(ce=>(ce-1+V.length)%V.length),"aria-label":"Previous",children:e.jsx(Cd,{className:"h-8 w-8"})}),e.jsx("img",{src:V[d],alt:"",className:"max-w-[90vw] max-h-[85vh] object-contain"}),e.jsx("button",{className:"absolute right-4 text-white p-2 hover:bg-white/10 rounded-full",onClick:()=>u(ce=>(ce+1)%V.length),"aria-label":"Next",children:e.jsx(Di,{className:"h-8 w-8"})}),e.jsxs("p",{className:"absolute bottom-4 left-1/2 -translate-x-1/2 text-white/80 text-sm",children:[d+1," / ",V.length]})]})]})]})}function PGs(){var i;const{slug:s}=Wi(),{data:t,isLoading:n,error:r}=Y7t(s);if(j.useEffect(()=>(document.body.classList.add("agent-card-page"),()=>{document.body.classList.remove("agent-card-page")}),[]),j.useEffect(()=>{t!=null&&t.id&&Nu(t.id,"card_view")},[t==null?void 0:t.id]),n)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(yn,{className:"h-28 w-28 rounded-full"}),e.jsx(yn,{className:"h-6 w-48"}),e.jsx(yn,{className:"h-4 w-36"})]}),e.jsx(yn,{className:"h-12 w-full"}),e.jsx(yn,{className:"h-12 w-full"})]})});if(r||!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(Ml,{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(ist,{card:t})]})}const IGs="https://images.unsplash.com/photo-1507525428034-b723cf961d3e?w=1600&q=80",LGs="https://images.unsplash.com/photo-1616486338812-3dadae4b4ace?w=1600&q=80",RGs="https://images.unsplash.com/photo-1500534314209-a25ddb2bd429?w=1600&q=80",DGs="https://images.unsplash.com/photo-1600585154340-be6161a56a0c?w=1600&q=80",FGs="https://images.unsplash.com/photo-1519741497674-611481863552?w=1600&q=80",OGs="https://images.unsplash.com/photo-1494526585095-c41746248156?w=1600&q=80",m3e={"minimal-mono":{key:"minimal-mono",label:"Minimal Mono",description:"Clean paper white, restrained.",bg:"#f7f7f5",surface:"#ffffff",border:"#e6e5e0",text:"#111111",textMuted:"#6b6b6b",accent:"#111111",accentText:"#ffffff",headingFont:'"Fraunces", ui-serif, Georgia, serif',bodyFont:'"Inter", system-ui, sans-serif',swatch:["#f7f7f5","#111111","#6b6b6b","#e6e5e0"],defaultCover:OGs},"warm-coastal":{key:"warm-coastal",label:"Warm Coastal",description:"Sand and soft teal.",bg:"linear-gradient(180deg,#faf6ef 0%,#f2ece1 100%)",surface:"#ffffff",border:"#e6dfd1",text:"#2b2a26",textMuted:"#7a746a",accent:"#2f7a7d",accentText:"#ffffff",headingFont:'"Cormorant Garamond", ui-serif, Georgia, serif',bodyFont:'"Karla", system-ui, sans-serif',swatch:["#faf6ef","#2f7a7d","#c9b99a","#2b2a26"],defaultCover:IGs},"deep-luxe":{key:"deep-luxe",label:"Deep Luxe",description:"Charcoal with gold.",bg:"linear-gradient(180deg,#161616 0%,#0d0d0d 100%)",surface:"#1e1e1e",border:"#2c2c2c",text:"#f5f0e0",textMuted:"#a49a80",accent:"#c9a84c",accentText:"#111111",headingFont:'"Instrument Serif", ui-serif, Georgia, serif',bodyFont:'"Work Sans", system-ui, sans-serif',swatch:["#0d0d0d","#c9a84c","#f5f0e0","#2c2c2c"],defaultCover:LGs},sunset:{key:"sunset",label:"Sunset",description:"Peach into magenta.",bg:"linear-gradient(160deg,#ffe4d1 0%,#ffc9b0 40%,#f2a1c5 100%)",surface:"#ffffff",border:"#f6d5ce",text:"#2a1a2f",textMuted:"#7a5a70",accent:"#d84a7a",accentText:"#ffffff",headingFont:'"Sora", system-ui, sans-serif',bodyFont:'"Manrope", system-ui, sans-serif',swatch:["#ffe4d1","#ffc9b0","#f2a1c5","#d84a7a"],defaultCover:RGs},editorial:{key:"editorial",label:"Editorial",description:"Ink black on paper white.",bg:"#f5f3ee",surface:"#ffffff",border:"#d9d6ce",text:"#0d0d0d",textMuted:"#5a564d",accent:"#0d0d0d",accentText:"#f5f3ee",headingFont:'"DM Serif Display", ui-serif, Georgia, serif',bodyFont:'"Fira Sans", system-ui, sans-serif',swatch:["#f5f3ee","#0d0d0d","#d9d6ce","#5a564d"],defaultCover:DGs},playful:{key:"playful",label:"Playful",description:"Blush and lavender.",bg:"linear-gradient(180deg,#fdf3f7 0%,#efe5ff 100%)",surface:"#ffffff",border:"#ecd7e6",text:"#3a2450",textMuted:"#7c6a94",accent:"#9b72cf",accentText:"#ffffff",headingFont:'"Outfit", system-ui, sans-serif',bodyFont:'"Figtree", system-ui, sans-serif',swatch:["#fdf3f7","#efe5ff","#c9a0dc","#9b72cf"],defaultCover:FGs}},zGs=["#111111","#2f7a7d","#c9a84c","#d84a7a","#3b6fa0","#9b72cf","#e85d3a","#4a6741"];function HUt(s){return s&&s in m3e?m3e[s]:m3e["minimal-mono"]}function BGs(s,t){const n=t||s.accent;return{background:s.bg,color:s.text,fontFamily:s.bodyFont,"--c-bg":s.bg,"--c-surface":s.surface,"--c-border":s.border,"--c-text":s.text,"--c-text-muted":s.textMuted,"--c-accent":n,"--c-accent-text":s.accentText,"--c-heading-font":s.headingFont,"--c-body-font":s.bodyFont}}function GUt({slugOverride:s}={}){var Ss;const{slug:t}=Wi(),n=s||t,[r]=gc(),a=r.get("t"),[i,l]=j.useState(!0),[o,c]=j.useState(null),[d,u]=j.useState(null),h=j.useRef(null),m=j.useRef(null),[f,g]=j.useState(null),[x,y]=j.useState(null),[v,b]=j.useState(!1),[w,S]=j.useState(!1),[C,E]=j.useState(0),[I,P]=j.useState(!1),[R,D]=j.useState(""),[O,U]=j.useState(""),[W,V]=j.useState(""),[G,Y]=j.useState(""),[X,ae]=j.useState(""),[ie,ne]=j.useState(""),[te,J]=j.useState(""),[ce,_e]=j.useState(""),[he,ue]=j.useState(""),[ve,Ee]=j.useState(""),[Se,Le]=j.useState(""),[Fe,ke]=j.useState(""),[Ve,je]=j.useState(""),[Ae,Ce]=j.useState([]),[qe,ze]=j.useState([]),[$e,ct]=j.useState(""),[Xe,it]=j.useState(""),[at,Ke]=j.useState(""),[nt,xt]=j.useState([]);j.useEffect(()=>{rt()},[n,a]);const rt=async()=>{if(!n)return;l(!0);const{data:Is,error:Ys}=await q.from("contact_intake_pages").select("*").eq("slug",n).eq("is_active",!0).maybeSingle();if(Ys||!Is){P(!0),l(!1);return}u(Is),m.current=Is;const{data:cs}=await q.from("profiles").select("name, avatar_url, title, phone, email, brokerage_id").eq("id",Is.user_id).single();if(cs){let js;if(cs.brokerage_id){const{data:On}=await q.from("brokerages").select("name").eq("id",cs.brokerage_id).single();js=(On==null?void 0:On.name)||void 0}let kn=cs.avatar_url||null;if(!kn){const{data:On}=q.storage.from("avatars").getPublicUrl(`${Is.user_id}/avatar.jpg`);On!=null&&On.publicUrl&&(kn=`${On.publicUrl}?t=${Date.now()}`)}const Ws={...cs,avatar_url:kn,brokerage_name:js};c(Ws),h.current=Ws}if(a)try{console.log("[ConnectPage] Resolving token:",a,"for page:",Is.id);const{data:js,error:kn}=await q.functions.invoke("process-intake-submissions",{body:{action:"resolve_token",token:a,page_id:Is.id}});if(console.log("[ConnectPage] Resolve result:",{resolved:js,resolveErr:kn}),!kn&&(js!=null&&js.contact_id)){y(js.contact_id);const Ws=js.contact;Ws&&(g(Ws),D(Ws.first_name||""),U(Ws.last_name||""),V(Ws.email||""),Y(Ws.phone||""),ae(Ws.address||""),ne(Ws.city||""),J(Ws.state||""),_e(Ws.zip||""),ue(Ws.birthday||""),Ee(Ws.home_anniversary||""))}}catch(js){console.error("Failed to resolve token:",js)}l(!1)},Yt=async()=>{var Is,Ys;if(!R.trim()){re.error("Please enter your first name");return}if(!n){re.error("Invalid page. Please refresh.");return}S(!0);try{let cs=(Is=m.current)==null?void 0:Is.id,js=(Ys=m.current)==null?void 0:Ys.user_id;if(!cs||!js){const{data:On}=await q.from("contact_intake_pages").select("id, user_id").eq("slug",n).eq("is_active",!0).maybeSingle();if(!On){re.error("This page is no longer active. Please contact the agent directly."),S(!1);return}cs=On.id,js=On.user_id}const kn={intake_page_id:cs,agent_user_id:js,existing_contact_id:x,first_name:R.trim(),last_name:O.trim()||null,email:W.trim()||null,phone:G.trim()||null,address:X.trim()||null,city:ie.trim()||null,state:te.trim()||null,zip:ce.trim()||null,birthday:he||null,home_anniversary:ve||null,real_estate_interest:Se||null,message:Fe.trim()||null,life_events:{spouse_name:Ve.trim()||null,kids:Ae.filter(On=>On.name.trim()),pets:qe.filter(On=>On.name.trim()),favorite_spots:$e.trim()||null,dream_neighborhood:Xe.trim()||null,wedding_anniversary:at||null},referrals:nt.filter(On=>On.name.trim()&&On.contact.trim())},{error:Ws}=await q.from("contact_intake_submissions").insert(kn);if(console.log("[ConnectPage] Insert result:",{error:Ws}),Ws)throw Ws;a&&await q.from("contact_intake_tokens").update({used_at:new Date().toISOString()}).eq("token",a);try{const On=[R.trim(),O.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:js,contactName:On,contactEmail:W.trim()||null,contactPhone:G.trim()||null,slug:n})})}catch(On){console.warn("Connect page notification failed (non-blocking):",On)}b(!0)}catch(cs){console.error(cs),re.error("Something went wrong. Please try again.")}finally{S(!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(kt,{className:"h-8 w-8 animate-spin text-slate-400"})});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.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(v)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(Ml,{children:e.jsxs("title",{children:["Thank You | ",o==null?void 0:o.name]})}),e.jsxs(Br.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(Br.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(qr,{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(Jo,{className:"h-3.5 w-3.5"}),e.jsx("span",{children:"Powered by ReLevelUp"})]})]})]});const qt=!!a&&!!f,ts=(d==null?void 0:d.show_little_things)??!0,ys=[{title:qt?"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 mb-1.5",style:{color:"var(--c-text-muted)"},children:"First Name *"}),e.jsx("input",{type:"text",value:R,onChange:Is=>D(Is.target.value),placeholder:"Jane",className:"connect-input",required:!0})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium mb-1.5",style:{color:"var(--c-text-muted)"},children:"Last Name"}),e.jsx("input",{type:"text",value:O,onChange:Is=>U(Is.target.value),placeholder:"Smith",className:"connect-input"})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium mb-1.5",style:{color:"var(--c-text-muted)"},children:"Email"}),e.jsx("input",{type:"email",value:W,onChange:Is=>V(Is.target.value),placeholder:"jane@email.com",className:"connect-input"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium mb-1.5",style:{color:"var(--c-text-muted)"},children:"Phone"}),e.jsx("input",{type:"tel",value:G,onChange:Is=>Y(Is.target.value),placeholder:"(555) 123-4567",className:"connect-input"})]})]})},{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 mb-1.5",style:{color:"var(--c-text-muted)"},children:"Street Address"}),e.jsx("input",{type:"text",value:X,onChange:Is=>ae(Is.target.value),placeholder:"123 Main St",className:"connect-input"})]}),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 mb-1.5",style:{color:"var(--c-text-muted)"},children:"City"}),e.jsx("input",{type:"text",value:ie,onChange:Is=>ne(Is.target.value),placeholder:"Austin",className:"connect-input"})]}),e.jsxs("div",{className:"col-span-1",children:[e.jsx("label",{className:"block text-sm font-medium mb-1.5",style:{color:"var(--c-text-muted)"},children:"State"}),e.jsx("input",{type:"text",value:te,onChange:Is=>J(Is.target.value),placeholder:"TX",maxLength:2,className:"connect-input"})]}),e.jsxs("div",{className:"col-span-2",children:[e.jsx("label",{className:"block text-sm font-medium mb-1.5",style:{color:"var(--c-text-muted)"},children:"Zip"}),e.jsx("input",{type:"text",value:ce,onChange:Is=>_e(Is.target.value),placeholder:"78701",className:"connect-input"})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium mb-1.5",style:{color:"var(--c-text-muted)"},children:"Birthday"}),e.jsx("input",{type:"date",value:he,onChange:Is=>ue(Is.target.value),className:"connect-input"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium mb-1.5",style:{color:"var(--c-text-muted)"},children:"Home Anniversary"}),e.jsx("input",{type:"date",value:ve,onChange:Is=>Ee(Is.target.value),className:"connect-input"})]})]})]})},...ts?[{title:"The Little Things",subtitle:"Optional — helps me remember what matters to you.",fields:e.jsxs("div",{className:"space-y-5",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium mb-1.5",style:{color:"var(--c-text-muted)"},children:"Spouse / partner's name"}),e.jsx("input",{type:"text",value:Ve,onChange:Is=>je(Is.target.value),placeholder:"Alex",className:"connect-input"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium mb-1.5",style:{color:"var(--c-text-muted)"},children:"Wedding anniversary"}),e.jsx("input",{type:"date",value:at,onChange:Is=>Ke(Is.target.value),className:"connect-input"})]}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-1.5",children:[e.jsx("label",{className:"block text-sm font-medium",style:{color:"var(--c-text-muted)"},children:"Kids"}),e.jsxs("button",{type:"button",onClick:()=>Ce(Is=>[...Is,{name:"",age:""}]),className:"text-xs inline-flex items-center gap-1",style:{color:"var(--c-accent)"},children:[e.jsx(dn,{className:"h-3 w-3"})," Add"]})]}),e.jsxs("div",{className:"space-y-2",children:[Ae.length===0&&e.jsx("p",{className:"text-xs",style:{color:"var(--c-text-muted)"},children:"None to add? Skip this."}),Ae.map((Is,Ys)=>e.jsxs("div",{className:"flex gap-2 items-center",children:[e.jsx("input",{type:"text",value:Is.name,onChange:cs=>Ce(js=>js.map((kn,Ws)=>Ws===Ys?{...kn,name:cs.target.value}:kn)),placeholder:"Child's name",className:"connect-input min-w-0",style:{flex:"1 1 0%"}}),e.jsx("input",{type:"text",value:Is.age,onChange:cs=>Ce(js=>js.map((kn,Ws)=>Ws===Ys?{...kn,age:cs.target.value}:kn)),placeholder:"Age",className:"connect-input shrink-0",style:{width:"5rem"}}),e.jsx("button",{type:"button",onClick:()=>Ce(cs=>cs.filter((js,kn)=>kn!==Ys)),className:"p-2 rounded-md hover:bg-black/5 shrink-0","aria-label":"Remove",children:e.jsx(gr,{className:"h-3.5 w-3.5",style:{color:"var(--c-text-muted)"}})})]},Ys))]})]}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-1.5",children:[e.jsx("label",{className:"block text-sm font-medium",style:{color:"var(--c-text-muted)"},children:"Pets"}),e.jsxs("button",{type:"button",onClick:()=>ze(Is=>[...Is,{name:"",kind:""}]),className:"text-xs inline-flex items-center gap-1",style:{color:"var(--c-accent)"},children:[e.jsx(dn,{className:"h-3 w-3"})," Add"]})]}),e.jsxs("div",{className:"space-y-2",children:[qe.length===0&&e.jsx("p",{className:"text-xs",style:{color:"var(--c-text-muted)"},children:"None to add? Skip this."}),qe.map((Is,Ys)=>e.jsxs("div",{className:"flex gap-2 items-center",children:[e.jsx("input",{type:"text",value:Is.name,onChange:cs=>ze(js=>js.map((kn,Ws)=>Ws===Ys?{...kn,name:cs.target.value}:kn)),placeholder:"Pet's name",className:"connect-input min-w-0",style:{flex:"1 1 0%"}}),e.jsx("input",{type:"text",value:Is.kind,onChange:cs=>ze(js=>js.map((kn,Ws)=>Ws===Ys?{...kn,kind:cs.target.value}:kn)),placeholder:"Dog, cat…",className:"connect-input shrink-0",style:{width:"7rem"}}),e.jsx("button",{type:"button",onClick:()=>ze(cs=>cs.filter((js,kn)=>kn!==Ys)),className:"p-2 rounded-md hover:bg-black/5 shrink-0","aria-label":"Remove",children:e.jsx(gr,{className:"h-3.5 w-3.5",style:{color:"var(--c-text-muted)"}})})]},Ys))]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium mb-1.5",style:{color:"var(--c-text-muted)"},children:"Favorite local spots"}),e.jsx("input",{type:"text",value:$e,onChange:Is=>ct(Is.target.value),placeholder:"That coffee shop on Main, Town Lake…",className:"connect-input"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium mb-1.5",style:{color:"var(--c-text-muted)"},children:"Dream neighborhood"}),e.jsx("input",{type:"text",value:Xe,onChange:Is=>it(Is.target.value),placeholder:"Where you'd love to live someday",className:"connect-input"})]}),e.jsxs("div",{className:"rounded-xl p-4",style:{background:"color-mix(in srgb, var(--c-accent) 8%, transparent)"},children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",style:{color:"var(--c-text)"},children:"Know someone who'd love an agent like me?"}),e.jsx("p",{className:"text-xs",style:{color:"var(--c-text-muted)"},children:"Refer a friend — up to 3."})]}),nt.length<3&&e.jsxs("button",{type:"button",onClick:()=>xt(Is=>[...Is,{name:"",contact:""}]),className:"text-xs inline-flex items-center gap-1 px-2 py-1 rounded-md",style:{background:"var(--c-accent)",color:"var(--c-accent-text)"},children:[e.jsx(dn,{className:"h-3 w-3"})," Add"]})]}),e.jsx("div",{className:"space-y-2",children:nt.map((Is,Ys)=>e.jsxs("div",{className:"flex gap-2 items-center",children:[e.jsx("input",{type:"text",value:Is.name,onChange:cs=>xt(js=>js.map((kn,Ws)=>Ws===Ys?{...kn,name:cs.target.value}:kn)),placeholder:"Their name",className:"connect-input min-w-0",style:{flex:"1 1 0%"}}),e.jsx("input",{type:"text",value:Is.contact,onChange:cs=>xt(js=>js.map((kn,Ws)=>Ws===Ys?{...kn,contact:cs.target.value}:kn)),placeholder:"Phone or email",className:"connect-input min-w-0",style:{flex:"1 1 0%"}}),e.jsx("button",{type:"button",onClick:()=>xt(cs=>cs.filter((js,kn)=>kn!==Ys)),className:"p-2 rounded-md hover:bg-black/5","aria-label":"Remove",children:e.jsx(gr,{className:"h-3.5 w-3.5",style:{color:"var(--c-text-muted)"}})})]},Ys))})]})]})}]:[],{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(Is=>e.jsxs("button",{type:"button",onClick:()=>Le(Se===Is.value?"":Is.value),className:`p-3.5 rounded-xl border-2 text-left transition-all ${Se===Is.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:Is.label}),e.jsx("span",{className:"block text-xs text-slate-500 mt-0.5",children:Is.desc})]},Is.value))})]}),e.jsxs("div",{children:[e.jsxs("label",{className:"block text-sm font-medium mb-1.5",style:{color:"var(--c-text-muted)"},children:["Anything else you'd like to share? ",e.jsx("span",{className:"text-slate-400 font-normal",children:"(optional)"})]}),e.jsx("textarea",{value:Fe,onChange:Is=>ke(Is.target.value),placeholder:"Feel free to drop a note...",rows:3,className:"connect-input resize-none"})]})]})}],Bt=ys.length,Ft=HUt(d==null?void 0:d.theme),rs=BGs(Ft,(d==null?void 0:d.accent_color)||null),St=(d==null?void 0:d.cover_image_url)||Ft.defaultCover,Xs=(d==null?void 0:d.headline)||"Let's stay connected",vt=(d==null?void 0:d.subheadline)||(o!=null&&o.brokerage_name?`${o==null?void 0:o.name} · ${o.brokerage_name}`:(o==null?void 0:o.name)||""),gs=["deep-luxe"].includes((d==null?void 0:d.theme)||"");return e.jsxs("div",{className:"min-h-screen connect-shell",style:rs,children:[e.jsxs(Ml,{children:[e.jsxs("title",{children:["Connect with ",(o==null?void 0:o.name)||"Agent"]}),e.jsx("meta",{name:"description",content:`${Xs} — ${(o==null?void 0:o.name)||"your agent"}`}),St&&e.jsx("meta",{property:"og:image",content:St}),e.jsx("meta",{property:"og:title",content:`Connect with ${(o==null?void 0:o.name)||"me"}`}),e.jsx("meta",{property:"og:description",content:Xs}),e.jsx("meta",{name:"twitter:card",content:"summary_large_image"})]}),e.jsx("style",{children:` .connect-shell { font-family: var(--c-body-font); color: var(--c-text); } .connect-shell h1, .connect-shell h2 { font-family: var(--c-heading-font); } .connect-input { width: 100%; padding: 0.75rem 1rem; border-radius: 0.75rem; border: 1px solid var(--c-border); background: var(--c-surface); color: var(--c-text); font-family: var(--c-body-font); font-size: 0.95rem; transition: border-color 150ms, box-shadow 150ms; } .connect-input::placeholder { color: var(--c-text-muted); opacity: 0.7; } .connect-input:focus { outline: none; border-color: var(--c-accent); box-shadow: 0 0 0 3px color-mix(in srgb, var(--c-accent) 25%, transparent); } `}),e.jsxs("div",{className:"relative w-full overflow-hidden",style:{height:"clamp(200px, 30vh, 320px)"},children:[e.jsx(Br.img,{src:St,alt:"",initial:{scale:1.08},animate:{scale:1},transition:{duration:1.4,ease:"easeOut"},className:"absolute inset-0 w-full h-full object-cover"}),e.jsx("div",{className:"absolute inset-0",style:{background:"linear-gradient(180deg, rgba(0,0,0,0) 20%, rgba(0,0,0,0.55) 100%)"}}),e.jsxs("div",{className:"absolute inset-x-0 bottom-0 p-6 pb-16 text-center",children:[e.jsx(Br.h1,{initial:{opacity:0,y:12},animate:{opacity:1,y:0},transition:{delay:.15,duration:.6},style:{color:"#fff",fontFamily:Ft.headingFont,fontWeight:500,letterSpacing:"-0.01em"},className:"text-3xl sm:text-4xl leading-tight",children:Xs}),vt&&e.jsx(Br.p,{initial:{opacity:0},animate:{opacity:.9},transition:{delay:.35,duration:.6},style:{color:"#fff"},className:"text-sm mt-2",children:vt})]})]}),e.jsxs("div",{className:"max-w-lg mx-auto px-4 pb-12 -mt-12 relative",children:[e.jsxs(Br.div,{initial:{opacity:0,y:12},animate:{opacity:1,y:0},transition:{delay:.25},className:"text-center mb-6",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 shadow-xl",style:{border:"4px solid var(--c-surface)"}}):e.jsx("div",{className:"w-24 h-24 rounded-full mx-auto flex items-center justify-center shadow-xl",style:{background:Ft.accent,color:Ft.accentText,border:"4px solid var(--c-surface)"},children:e.jsx("span",{className:"text-3xl font-bold",children:((Ss=o==null?void 0:o.name)==null?void 0:Ss.charAt(0))||"?"})}),(o==null?void 0:o.title)&&e.jsx("p",{className:"text-sm mt-3",style:{color:"var(--c-text-muted)"},children:o.title}),((o==null?void 0:o.phone)||(o==null?void 0:o.email))&&e.jsxs("div",{className:"flex items-center justify-center gap-2 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 transition-opacity hover:opacity-80",style:{background:"color-mix(in srgb, var(--c-accent) 12%, transparent)",color:"var(--c-accent)"},"aria-label":"Call agent",children:e.jsx(Da,{className:"h-4 w-4"})}),(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 transition-opacity hover:opacity-80",style:{background:"color-mix(in srgb, var(--c-accent) 12%, transparent)",color:"var(--c-accent)"},"aria-label":"Email agent",children:e.jsx(mn,{className:"h-4 w-4"})})]})]}),e.jsx(Br.p,{initial:{opacity:0},animate:{opacity:1},transition:{delay:.35},className:"text-center mb-6 px-2 leading-relaxed text-sm",style:{color:"var(--c-text-muted)"},children:(d==null?void 0:d.welcome_message)||"I'd love to stay in touch — just a few quick details."}),e.jsx("div",{className:"flex gap-1.5 mb-6 px-2",children:Array.from({length:Bt}).map((Is,Ys)=>e.jsx("div",{className:"h-1 flex-1 rounded-full transition-all duration-500",style:{background:Ys<=C?"var(--c-accent)":"color-mix(in srgb, var(--c-text) 12%, transparent)"}},Ys))}),e.jsxs(Br.div,{initial:{opacity:0,y:12},animate:{opacity:1,y:0},transition:{delay:.4},className:"rounded-2xl p-6 sm:p-8",style:{background:"var(--c-surface)",border:"1px solid var(--c-border)",boxShadow:gs?"0 20px 40px -20px rgba(0,0,0,0.5)":"0 20px 40px -20px rgba(0,0,0,0.15)"},children:[e.jsx(cK,{mode:"wait",children:e.jsxs(Br.div,{initial:{opacity:0,x:20},animate:{opacity:1,x:0},exit:{opacity:0,x:-20},transition:{duration:.25},children:[e.jsxs("div",{className:"mb-6",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Nn,{className:"h-4 w-4",style:{color:"var(--c-accent)"}}),e.jsx("h2",{className:"text-lg font-semibold",style:{color:"var(--c-text)"},children:ys[C].title})]}),ys[C].subtitle&&e.jsx("p",{className:"text-xs mt-1 ml-6",style:{color:"var(--c-text-muted)"},children:ys[C].subtitle})]}),ys[C].fields]},C)}),e.jsxs("div",{className:"flex justify-between mt-8",children:[C>0?e.jsx("button",{type:"button",onClick:()=>E(Is=>Is-1),className:"px-5 py-2.5 text-sm font-medium transition-opacity hover:opacity-70",style:{color:"var(--c-text-muted)"},children:"Back"}):e.jsx("div",{}),C{if(C===0&&!R.trim()){re.error("Please enter your first name");return}E(Is=>Is+1)},className:"px-6 py-2.5 text-sm font-medium rounded-xl transition-transform hover:scale-[1.02] shadow-sm",style:{background:"var(--c-accent)",color:"var(--c-accent-text)"},children:"Continue"}):e.jsx("button",{type:"button",onClick:()=>Yt(),disabled:w,className:"px-6 py-2.5 text-sm font-medium rounded-xl transition-transform hover:scale-[1.02] shadow-sm disabled:opacity-50 flex items-center gap-2",style:{background:"var(--c-accent)",color:"var(--c-accent-text)"},children:w?e.jsxs(e.Fragment,{children:[e.jsx(kt,{className:"h-4 w-4 animate-spin"}),"Sending..."]}):"Submit"})]}),C>0&&CE(Is=>Is+1),className:"text-xs transition-opacity hover:opacity-80",style:{color:"var(--c-text-muted)"},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",style:{color:"var(--c-text-muted)"},children:[e.jsx(Jo,{className:"h-3 w-3"}),e.jsx("span",{children:"Powered by ReLevelUp"})]})})]})]})}const gK=()=>({trackEngagement:j.useCallback(async(t,n,r,a="view")=>{try{const{data:{user:i}}=await q.auth.getUser();if(!i)return;await q.from("content_engagement_logs").insert({user_id:i.id,resource_type:t,resource_id:n,resource_title:r,action_type:a})}catch(i){console.error("Error tracking engagement:",i)}},[])});function RZ({banners:s,autoPlayInterval:t=5e3,className:n}){const[r,a]=j.useState(0),[i,l]=j.useState(!1),{trackEngagement:o}=gK(),c=j.useCallback(f=>{o("newsletter",f.id,f.title,"click_link")},[o]),d=j.useCallback(()=>{a(f=>(f+1)%s.length)},[s.length]),u=j.useCallback(()=>{a(f=>(f-1+s.length)%s.length)},[s.length]),h=j.useCallback(f=>{a(f)},[]);if(j.useEffect(()=>{if(s.length<=1||i)return;const f=setInterval(d,t);return()=>clearInterval(f)},[s.length,i,t,d]),!s||s.length===0)return null;const m=s[r];return e.jsxs("div",{className:Pt("relative w-full overflow-hidden rounded-xl",n),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:m.image_url,alt:m.title,className:"w-full h-full object-cover rounded-t-xl"}),s.length>1&&e.jsxs(e.Fragment,{children:[e.jsx($,{variant:"ghost",size:"icon",className:Pt("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:u,children:e.jsx(Cd,{className:"h-6 w-6"})}),e.jsx($,{variant:"ghost",size:"icon",className:Pt("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(Di,{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((f,g)=>e.jsx("button",{onClick:()=>h(g),className:Pt("w-2 h-2 rounded-full transition-all duration-300",g===r?"bg-white w-6":"bg-white/50 hover:bg-white/70"),"aria-label":`Go to slide ${g+1}`},g))})]}),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:m.title}),m.description&&e.jsx("p",{className:"text-xs text-background/70 truncate",children:m.description})]}),m.link_url&&e.jsx("a",{href:m.link_url,target:"_blank",rel:"noopener noreferrer",className:"shrink-0",onClick:()=>c(m),children:e.jsx($,{size:"sm",className:"bg-primary text-primary-foreground font-semibold transition-colors hover:bg-background hover:text-foreground",children:m.link_text||"Learn More"})})]})]})}const $Gs=["reserved","scheduled_for_charge","paid","payment_failed","completed"],LG=s=>!!s&&(s.access_override||$Gs.includes(s.status)),Cg=(s,t="usd")=>new Intl.NumberFormat("en-US",{style:"currency",currency:t.toUpperCase(),maximumFractionDigits:s%100===0?0:2}).format(s/100),hse=s=>{if(!s||s<=0)return"full program";const t=Math.round(s/4.345);return t>=1?`full ${t}-month program`:`full ${s}-week program`},KGe=(s,t="usd",n)=>`One-time payment: ${Cg(s,t)} for the ${hse(n)}`,cnt=[{key:"full_name",label:"Full name",step:0},{key:"phone",label:"Mobile number",step:0},{key:"instagram_handle",label:"Instagram handle",step:0},{key:"city",label:"Primary city / market",step:0},{key:"service_areas",label:"Neighborhoods or areas served",step:0},{key:"years_experience",label:"Years in real estate",step:0},{key:"specialty",label:"Specialty or niche",step:0},{key:"target_audience",label:"Who they want to reach",step:1},{key:"video_comfort",label:"Comfort on camera",step:1},{key:"posting_frequency",label:"Current posting frequency",step:1},{key:"content_style",label:"Content style",step:1},{key:"personal_interests",label:"Interests / hobbies",step:1},{key:"primary_goal",label:"#1 goal for the program",step:2},{key:"topics_to_avoid",label:"Topics to avoid",step:2},{key:"timezone",label:"Time zone",step:2},{key:"consent_public_profile",label:"Content-sharing consent",step:2}],mse=s=>{var n;const t=((n=s==null?void 0:s.sales_copy)==null?void 0:n.intake)||{};return{intro:typeof t.intro=="string"?t.intro:"",hidden:Array.isArray(t.hidden)?t.hidden:[],required:Array.isArray(t.required)?t.required:[],custom:Array.isArray(t.custom)?t.custom:[]}},UGs=(s,t)=>!s.hidden.includes(t),_bt=(s,t)=>s.required.includes(t)&&!s.hidden.includes(t),sh=(s,t=!1)=>s?new Intl.DateTimeFormat("en-US",{timeZone:"America/New_York",month:"short",day:"numeric",year:"numeric",...t?{hour:"numeric",minute:"2-digit",timeZoneName:"short"}:{}}).format(new Date(s)):null,E6e=s=>{const t=Date.now(),n=s!=null&&s.enrollment_open_at?new Date(s.enrollment_open_at).getTime():null,r=s!=null&&s.enrollment_close_at?new Date(s.enrollment_close_at).getTime():null;return{notOpenYet:!!n&&n>t,closed:!!r&&rtt({queryKey:["programs"],queryFn:async()=>{const{data:s,error:t}=await q.from("programs").select("*").eq("status","published").order("is_featured",{ascending:!1}).order("sort_order",{ascending:!0});if(t)throw t;return s||[]}}),dnt=s=>tt({queryKey:["program",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await q.from("programs").select("*").eq("slug",s).maybeSingle();if(n)throw n;return t||null}}),KUt=s=>tt({queryKey:["program-seats",s],enabled:!!s,refetchInterval:6e4,queryFn:async()=>{const{data:t,error:n}=await q.rpc("program_seats_remaining",{_program_id:s});if(n)throw n;return t??0}}),unt=()=>{const{user:s}=vs();return tt({queryKey:["program-enrollments",s==null?void 0:s.id],enabled:!!(s!=null&&s.id),queryFn:async()=>{const{data:t,error:n}=await q.from("program_enrollments").select("*").eq("user_id",s.id);if(n)throw n;return t||[]}})},hnt=s=>{const{data:t=[],...n}=unt();return{...n,data:s&&t.find(r=>r.program_id===s)||null}},qGs=()=>{const{user:s}=vs(),t=Vt();return ft({mutationFn:async n=>{const{data:r,error:a}=await q.from("program_intake_responses").upsert({...n,user_id:s.id},{onConflict:"program_id,user_id"}).select("*").single();if(a)throw a;return r},onSuccess:()=>t.invalidateQueries({queryKey:["program-intake"]}),onError:n=>re.error(n.message||"Could not save your answers")})},YUt=s=>{const{user:t}=vs();return tt({queryKey:["program-intake",s,t==null?void 0:t.id],enabled:!!s&&!!(t!=null&&t.id),queryFn:async()=>{const{data:n,error:r}=await q.from("program_intake_responses").select("*").eq("program_id",s).eq("user_id",t.id).maybeSingle();if(r)throw r;return n}})},VGs=()=>{const s=Vt();return ft({mutationFn:async t=>{const{data:n,error:r}=await q.rpc("program_claim_seat",{_program_id:t});if(r)throw r;return n},onSuccess:()=>{s.invalidateQueries({queryKey:["program-enrollments"]}),s.invalidateQueries({queryKey:["program-seats"]})}})},HGs=(s,t)=>{const{user:n}=vs(),r=t||(n==null?void 0:n.id);return tt({queryKey:["program-workspace",s,r],enabled:!!s&&!!r,queryFn:async()=>{const a=r,[i,l,o,c,d,u,h,m,f,g,x]=await Promise.all([q.from("program_weeks").select("*").eq("program_id",s).order("week_number"),q.from("program_lessons").select("*").eq("program_id",s).order("sort_order"),q.from("program_resources").select("*").eq("program_id",s).order("sort_order"),q.from("program_events").select("*").eq("program_id",s).order("starts_at"),q.from("program_announcements").select("*").eq("program_id",s).order("published_at",{ascending:!1}),q.from("program_lesson_completions").select("*").eq("program_id",s).eq("user_id",a),q.from("program_weekly_progress").select("*").eq("program_id",s).eq("user_id",a).order("week_number"),q.from("program_video_logs").select("*").eq("program_id",s).eq("user_id",a).order("posted_at",{ascending:!1}),q.from("program_badge_awards").select("*").eq("program_id",s).eq("user_id",a),q.from("program_profile_analyses").select("*").eq("program_id",s).eq("user_id",a).maybeSingle(),q.from("program_member_resources").select("*").eq("program_id",s).eq("user_id",a).order("sort_order")]);return{weeks:i.data||[],lessons:l.data||[],resources:o.data||[],myResources:x.data||[],events:c.data||[],announcements:d.data||[],completions:u.data||[],progress:h.data||[],videoLogs:m.data||[],badges:f.data||[],analysis:g.data||null}}})},GGs=s=>{const{user:t}=vs(),n=Vt();return ft({mutationFn:async({lessonId:r,done:a})=>{if(a){const{error:i}=await q.from("program_lesson_completions").insert({lesson_id:r,program_id:s,user_id:t.id});if(i&&!i.message.includes("duplicate"))throw i}else{const{error:i}=await q.from("program_lesson_completions").delete().eq("lesson_id",r).eq("user_id",t.id);if(i)throw i}},onSuccess:()=>n.invalidateQueries({queryKey:["program-workspace"]}),onError:r=>re.error(r.message||"Could not update progress")})},WGs=s=>{const{user:t}=vs(),n=Vt();return ft({mutationFn:async r=>{const{error:a}=await q.from("program_video_logs").insert({...r,program_id:s,user_id:t.id});if(a)throw a},onSuccess:()=>{re.success("Video logged — nice work"),n.invalidateQueries({queryKey:["program-workspace"]})},onError:r=>re.error(r.message||"Could not log the video")})},KGs=s=>{const{user:t}=vs(),n=Vt();return ft({mutationFn:async r=>{const{error:a}=await q.from("program_weekly_progress").upsert({...r,program_id:s,user_id:t.id},{onConflict:"program_id,user_id,week_number"});if(a)throw a},onSuccess:()=>{re.success("Weekly check-in saved"),n.invalidateQueries({queryKey:["program-workspace"]})},onError:r=>re.error(r.message||"Could not save your check-in")})},YGs=s=>{const{user:t}=vs(),n=Vt();return ft({mutationFn:async({eventId:r,optIn:a})=>{const{error:i}=await q.from("program_event_attendance").upsert({event_id:r,program_id:s,user_id:t.id,reminder_opt_in:a},{onConflict:"event_id,user_id"});if(i)throw i},onSuccess:()=>n.invalidateQueries({queryKey:["program-workspace"]}),onError:r=>re.error(r.message||"Could not update your RSVP")})},ZGs=s=>tt({queryKey:["program-discount-codes",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await q.from("program_discount_codes").select("*").eq("program_id",s).order("created_at",{ascending:!1});if(n)throw n;return t||[]}}),XGs=s=>{const t=Vt();return ft({mutationFn:async n=>{const r={program_id:s,code:(n.code||"").trim().toUpperCase(),label:n.label||null,percent_off:n.percent_off??null,amount_off_cents:n.amount_off_cents??null,max_redemptions:n.max_redemptions??null,starts_at:n.starts_at||null,expires_at:n.expires_at||null,is_active:n.is_active??!0};if(n.id){const{error:a}=await q.from("program_discount_codes").update(r).eq("id",n.id);if(a)throw a}else{const{error:a}=await q.from("program_discount_codes").insert(r);if(a)throw a}},onSuccess:()=>{re.success("Discount code saved"),t.invalidateQueries({queryKey:["program-discount-codes"]})},onError:n=>{var r;return re.error((r=n.message)!=null&&r.includes("duplicate")?"That code already exists for this program":n.message||"Could not save the code")}})},QGs=()=>{const s=Vt();return ft({mutationFn:async t=>{const{error:n}=await q.from("program_discount_codes").delete().eq("id",t);if(n)throw n},onSuccess:()=>{re.success("Discount code deleted"),s.invalidateQueries({queryKey:["program-discount-codes"]})},onError:t=>re.error(t.message||"Could not delete the code")})},JGs=()=>ft({mutationFn:async({enrollmentId:s,code:t})=>{const{data:n,error:r}=await q.rpc("program_apply_discount",{_enrollment_id:s,_code:t});if(r)throw r;const a=n;if(!(a!=null&&a.ok))throw new Error((a==null?void 0:a.error)||"That code could not be applied");return a}}),eWs=()=>ft({mutationFn:async s=>{const{error:t}=await q.rpc("program_clear_discount",{_enrollment_id:s});if(t)throw t}}),tWs=s=>tt({queryKey:["admin-program-events",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await q.from("program_events").select("*").eq("program_id",s).order("starts_at",{ascending:!0});if(n)throw n;return t||[]}}),sWs=s=>{const t=Vt();return ft({mutationFn:async n=>{const r={program_id:s,title:(n.title||"").trim(),description:n.description||null,event_kind:n.event_kind||"mastermind",starts_at:n.starts_at,duration_minutes:n.duration_minutes??60,speaker:n.speaker||null,meeting_link:n.meeting_link||null,replay_url:n.replay_url||null,is_published:n.is_published??!0};if(n.id){const{error:a}=await q.from("program_events").update(r).eq("id",n.id);if(a)throw a}else{const{error:a}=await q.from("program_events").insert(r);if(a)throw a}},onSuccess:()=>{re.success("Session saved"),t.invalidateQueries({queryKey:["admin-program-events"]}),t.invalidateQueries({queryKey:["program-workspace"]})},onError:n=>re.error(n.message||"Could not save the session")})},nWs=()=>{const s=Vt();return ft({mutationFn:async t=>{const{error:n}=await q.from("program_events").delete().eq("id",t);if(n)throw n},onSuccess:()=>{re.success("Session removed"),s.invalidateQueries({queryKey:["admin-program-events"]}),s.invalidateQueries({queryKey:["program-workspace"]})},onError:t=>re.error(t.message||"Could not remove the session")})},rWs=s=>tt({queryKey:["admin-program-lessons",s],enabled:!!s,queryFn:async()=>{const[t,n]=await Promise.all([q.from("program_lessons").select("*").eq("program_id",s).order("sort_order"),q.from("program_weeks").select("id, week_number, title").eq("program_id",s).order("week_number")]);if(t.error)throw t.error;return{lessons:t.data||[],weeks:n.data||[]}}}),aWs=s=>{const t=Vt();return ft({mutationFn:async n=>{const r={program_id:s,week_id:n.week_id||null,title:(n.title||"").trim(),summary:n.summary||null,duration_minutes:n.duration_minutes??null,video_url:n.video_url||null,worksheet_url:n.worksheet_url||null,action_assignment:n.action_assignment||null,status:n.status||"published",publish_at:n.publish_at||null,sort_order:n.sort_order??0};if(n.id){const{error:a}=await q.from("program_lessons").update(r).eq("id",n.id);if(a)throw a}else{const{error:a}=await q.from("program_lessons").insert(r);if(a)throw a}},onSuccess:()=>{re.success("Video saved"),t.invalidateQueries({queryKey:["admin-program-lessons"]}),t.invalidateQueries({queryKey:["program-workspace"]})},onError:n=>re.error(n.message||"Could not save the video")})},iWs=()=>{const s=Vt();return ft({mutationFn:async t=>{const{error:n}=await q.from("program_lessons").delete().eq("id",t);if(n)throw n},onSuccess:()=>{re.success("Video removed"),s.invalidateQueries({queryKey:["admin-program-lessons"]}),s.invalidateQueries({queryKey:["program-workspace"]})},onError:t=>re.error(t.message||"Could not remove the video")})},ZUt=s=>{if(!s)return null;const t=s.match(/(?:youtu\.be\/|youtube\.com\/(?:watch\?v=|embed\/|live\/|shorts\/))([\w-]{6,})/);if(t)return`https://www.youtube.com/embed/${t[1]}`;const n=s.match(/vimeo\.com\/(?:video\/)?(\d+)/);if(n)return`https://player.vimeo.com/video/${n[1]}`;const r=s.match(/loom\.com\/(?:share|embed)\/([\w-]+)/);return r?`https://www.loom.com/embed/${r[1]}`:null},Aee=s=>!!s&&/\.(mp4|webm|mov|m4v)(\?|$)/i.test(s),XUt=[{value:"pdf",label:"PDF"},{value:"document",label:"Document"},{value:"checklist",label:"Checklist"},{value:"template_link",label:"Template"},{value:"video",label:"Video"},{value:"external",label:"Link"}],xK="event-images",lie=s=>{if(s.file_path){const{data:t}=q.storage.from(xK).getPublicUrl(s.file_path);return t.publicUrl}return s.url||null},Eee=async(s,t="open")=>{if(!s.file_path){const c=s.url;c&&window.open(c,"_blank","noopener,noreferrer");return}const{data:n,error:r}=await q.storage.from(xK).download(s.file_path);if(r||!n){const c=lie(s);c&&window.open(c,"_blank","noopener,noreferrer");return}const a=s.file_path.split("/").pop()||s.title||"resource",i=a.toLowerCase().endsWith(".pdf")||n.type==="application/pdf",l=i?new Blob([n],{type:"application/pdf"}):n,o=URL.createObjectURL(l);if(t==="open"&&i){if(!window.open(o,"_blank","noopener,noreferrer")){const d=document.createElement("a");d.href=o,d.download=a,d.click()}}else{const c=document.createElement("a");c.href=o,c.download=a,document.body.appendChild(c),c.click(),c.remove()}setTimeout(()=>URL.revokeObjectURL(o),6e4)},QUt=s=>tt({queryKey:["admin-program-resources",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await q.from("program_resources").select("*").eq("program_id",s).order("sort_order");if(n)throw n;return t||[]}}),oWs=s=>{const t=Vt();return ft({mutationFn:async n=>{const r={program_id:s,title:(n.title||"").trim(),description:n.description||null,category:(n.category||"Resources").trim()||"Resources",resource_kind:n.resource_kind||"pdf",url:n.url||null,file_path:n.file_path||null,status:n.status||"published",sort_order:n.sort_order??0};if(n.id){const{error:a}=await q.from("program_resources").update(r).eq("id",n.id);if(a)throw a}else{const{error:a}=await q.from("program_resources").insert(r);if(a)throw a}},onSuccess:()=>{re.success("Resource saved"),t.invalidateQueries({queryKey:["admin-program-resources"]}),t.invalidateQueries({queryKey:["program-workspace"]})},onError:n=>re.error(n.message||"Could not save the resource")})},lWs=()=>{const s=Vt();return ft({mutationFn:async t=>{t.file_path&&await q.storage.from(xK).remove([t.file_path]);const{error:n}=await q.from("program_resources").delete().eq("id",t.id);if(n)throw n},onSuccess:()=>{re.success("Resource removed"),s.invalidateQueries({queryKey:["admin-program-resources"]}),s.invalidateQueries({queryKey:["program-workspace"]})},onError:t=>re.error(t.message||"Could not remove the resource")})},cWs=(s,t)=>tt({queryKey:["admin-program-member-resources",s,t],enabled:!!s&&!!t,queryFn:async()=>{const{data:n,error:r}=await q.from("program_member_resources").select("*").eq("program_id",s).eq("user_id",t).order("sort_order");if(r)throw r;return n||[]}}),dWs=(s,t)=>{const n=Vt(),{user:r}=vs();return ft({mutationFn:async a=>{const i={program_id:s,user_id:t,uploaded_by:(r==null?void 0:r.id)??null,title:(a.title||"").trim(),description:a.description||null,category:(a.category||"Personal").trim()||"Personal",resource_kind:a.resource_kind||"pdf",url:a.url||null,file_path:a.file_path||null,status:a.status||"published",sort_order:a.sort_order??0};if(a.id){const{error:l}=await q.from("program_member_resources").update(i).eq("id",a.id);if(l)throw l}else{const{error:l}=await q.from("program_member_resources").insert(i);if(l)throw l}},onSuccess:()=>{re.success("Personal resource saved"),n.invalidateQueries({queryKey:["admin-program-member-resources"]}),n.invalidateQueries({queryKey:["program-workspace"]})},onError:a=>re.error(a.message||"Could not save the resource")})},uWs=()=>{const s=Vt();return ft({mutationFn:async t=>{t.file_path&&await q.storage.from(xK).remove([t.file_path]);const{error:n}=await q.from("program_member_resources").delete().eq("id",t.id);if(n)throw n},onSuccess:()=>{re.success("Personal resource removed"),s.invalidateQueries({queryKey:["admin-program-member-resources"]}),s.invalidateQueries({queryKey:["program-workspace"]})},onError:t=>re.error(t.message||"Could not remove the resource")})},hWs=s=>{const{user:t}=vs();return tt({queryKey:["program-interest",s,t==null?void 0:t.id],enabled:!!s&&!!(t!=null&&t.id),queryFn:async()=>{const{data:n,error:r}=await q.from("program_interest").select("*").eq("program_id",s).eq("user_id",t.id).maybeSingle();if(r)throw r;return n||null}})},mWs=s=>{const t=Vt(),{user:n}=vs();return ft({mutationFn:async r=>{if(!(n!=null&&n.id)||!s)throw new Error("You need to be signed in.");if(r){const{error:a}=await q.from("program_interest").upsert({program_id:s,user_id:n.id,source:"program_detail"},{onConflict:"program_id,user_id"});if(a)throw a}else{const{error:a}=await q.from("program_interest").delete().eq("program_id",s).eq("user_id",n.id);if(a)throw a}return r},onSuccess:r=>{re.success(r?"You're on the list — we'll email you when enrollment opens.":"Removed from the notify list"),t.invalidateQueries({queryKey:["program-interest"]}),t.invalidateQueries({queryKey:["admin-program-interest"]})},onError:r=>re.error(r.message||"Could not update your notify preference")})},fWs=s=>tt({queryKey:["admin-program-interest",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await q.from("program_interest").select("*").eq("program_id",s).order("created_at",{ascending:!1});if(n)throw n;const r=t||[];if(!r.length)return[];const a=Array.from(new Set(r.map(o=>o.user_id))),{data:i}=await q.from("profiles").select("id, name, email, phone, brokerage_name").in("id",a),l=new Map((i||[]).map(o=>[o.id,o]));return r.map(o=>{const c=l.get(o.user_id)||{};return{...o,full_name:c.name??null,email:c.email??null,phone:c.phone??null,brokerage:c.brokerage_name??null}})}}),pWs=s=>{if(!s)return null;const t=new Intl.DateTimeFormat("en-CA",{timeZone:"America/New_York",year:"numeric",month:"2-digit",day:"2-digit"}),n=r=>{const[a,i,l]=t.format(r).split(/[-/T]/).map(Number);return Date.UTC(a,i-1,l)};return Math.round((n(new Date(s))-n(new Date))/864e5)},gWs=()=>{const{data:s=[]}=WUt(),{data:t=[]}=unt(),n=new Set(t.filter(LG).map(a=>a.program_id)),r=s.filter(a=>n.has(a.id));return r.length===0?null:e.jsx("div",{className:"mb-6 space-y-3",children:r.map(a=>{const i=pWs(a.kickoff_at),l=i===null?null:i>1?`Kicks off in ${i} days`:i===1?"Kicks off tomorrow":i===0?"Kicks off today":"In progress";return e.jsxs("div",{className:"flex flex-col gap-4 rounded-2xl border border-primary/30 bg-gradient-to-r from-primary/12 via-primary/5 to-background p-5 sm:flex-row sm:items-center sm:justify-between",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx("div",{className:"flex h-12 w-12 shrink-0 items-center justify-center rounded-xl bg-primary/15",children:e.jsx(qg,{className:"h-6 w-6 text-primary"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("h3",{className:"text-lg font-semibold leading-tight",children:a.name}),l&&e.jsx(Be,{variant:"secondary",children:l})]}),e.jsxs("p",{className:"mt-0.5 text-sm text-muted-foreground",children:[a.kickoff_at?`Starts ${sh(a.kickoff_at)} · `:"","Your program dashboard is live — lessons, resources and sessions inside."]})]})]}),e.jsx($,{asChild:!0,size:"lg",className:"shrink-0",children:e.jsxs(wr,{to:`/programs/${a.slug}/workspace`,children:["Open program dashboard",e.jsx(ei,{className:"ml-1.5 h-4 w-4"})]})})]},a.id)})})},xWs={url:"/exp-agent-advantage.webp"};function yWs({className:s}){const{isMember:t,program:n,packageName:r}=jC();return!t||!((n==null?void 0:n.name)||"").toLowerCase().includes("exp")?null:e.jsxs(Ne,{className:Pt("relative overflow-hidden border border-border/60 bg-gradient-to-r from-card via-card to-muted/40 p-6 mb-6",s),children:[e.jsx("div",{className:"pointer-events-none absolute -right-10 -top-10 h-40 w-40 rounded-full bg-primary/5 blur-3xl"}),e.jsx("div",{className:"pointer-events-none absolute -bottom-10 -left-10 h-40 w-40 rounded-full bg-accent/5 blur-3xl"}),e.jsxs("div",{className:"relative flex flex-col items-center gap-4 text-center sm:flex-row sm:gap-6 sm:text-left",children:[e.jsx("div",{className:"flex shrink-0 items-center justify-center rounded-xl border border-border bg-background p-4 shadow-sm",children:e.jsx("img",{src:xWs.url,alt:"eXp Agent Advantage — powered by LevelUp",className:"h-14 w-auto object-contain dark:invert dark:brightness-95 sm:h-16"})}),e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center justify-center gap-2 sm:justify-start",children:[e.jsx(Nn,{className:"h-4 w-4 text-primary","aria-hidden":"true"}),e.jsx("span",{className:"text-xs font-semibold uppercase tracking-wider text-primary",children:"Partnership Benefit"})]}),e.jsx("h2",{className:"mt-1 text-lg font-semibold text-foreground sm:text-xl",children:"Welcome to your eXp Agent Advantage dashboard"}),e.jsxs("p",{className:"mt-1 max-w-2xl text-sm text-muted-foreground",children:["You are enrolled in the ",r||"eXp"," partnership. Everything below is included with your membership — coaching, tools, and resources built exclusively for eXp Luxury agents."]})]})]})]})}function vWs({className:s}){var E,I,P;const{user:t}=vs(),{isMember:n,program:r,pkg:a,packageName:i}=jC(),l=j.useMemo(()=>!n||!(a!=null&&a.includes_coaching)?!1:((r==null?void 0:r.name)||"").toLowerCase().includes("exp"),[n,a,r]),{data:o}=Bst(),c=o==null?void 0:o.id,{data:d=[]}=$st(c),{data:u=[]}=Ust(c),{data:h}=tt({queryKey:["exp-coaching-prep",t==null?void 0:t.id,a==null?void 0:a.id],enabled:!!(t!=null&&t.id)&&!!(a!=null&&a.id)&&l,queryFn:async()=>{const[{data:R},{data:D},{data:O}]=await Promise.all([q.from("coaching_onboarding_forms").select("submitted_at").eq("user_id",t.id).maybeSingle(),q.from("coaching_prep_checklist_items").select("id, title, sort_order").eq("package_id",a.id).eq("is_active",!0).order("sort_order"),q.from("coaching_prep_checklist_state").select("item_id").eq("user_id",t.id)]),U=new Set((O||[]).map(W=>W.item_id));return{submitted:!!(R!=null&&R.submitted_at),items:(D||[]).map(W=>({...W,done:U.has(W.id)}))}}});if(!l)return null;const m=((E=o==null?void 0:o.coachProfile)==null?void 0:E.name)||"Your LevelUp Coach",f=((I=o==null?void 0:o.coachProfile)==null?void 0:I.avatar_url)||void 0,g=(P=o==null?void 0:o.coach)==null?void 0:P.headline,y=d.filter(R=>R.status!=="cancelled"&&new Date(R.scheduled_at).getTime()>Date.now()).sort((R,D)=>new Date(R.scheduled_at).getTime()-new Date(D.scheduled_at).getTime())[0],v=u.filter(R=>R.status!=="done"),b=u.length-v.length,w=(h==null?void 0:h.items)||[],S=w.filter(R=>R.done).length,C=w.length?Math.round(S/w.length*100):0;return e.jsxs(Ne,{className:Pt("overflow-hidden border-border/60 mb-6",s),children:[e.jsxs("div",{className:"relative bg-gradient-to-br from-[#2a4c64] via-[#33586f] to-[#406E71] p-6 text-white",children:[e.jsx("div",{className:"pointer-events-none absolute -right-16 -top-24 h-64 w-64 rounded-full bg-white/10 blur-3xl"}),e.jsx("div",{className:"pointer-events-none absolute -bottom-24 -left-10 h-56 w-56 rounded-full bg-[#c8a24a]/20 blur-3xl"}),e.jsxs("div",{className:"relative flex flex-col gap-5 md:flex-row md:items-center",children:[e.jsxs(Oa,{className:"h-16 w-16 ring-4 ring-white/20 md:h-20 md:w-20",children:[e.jsx(Li,{src:f,alt:m}),e.jsx(za,{className:"bg-white/20 text-xl text-white",children:m.charAt(0)})]}),e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2 text-white/75",children:[e.jsx(Nn,{className:"h-4 w-4","aria-hidden":"true"}),e.jsx("span",{className:"text-xs font-semibold uppercase tracking-[0.18em]",children:i?`${i} Coaching`:"Included Coaching"})]}),e.jsx("h2",{className:"mt-1 text-2xl font-bold leading-tight",children:m}),e.jsx("p",{className:"mt-1 max-w-xl text-sm text-white/80",children:g||"1:1 accountability coaching included with your eXp Agent Advantage membership."})]}),e.jsxs("div",{className:"flex flex-col gap-2 md:items-end",children:[e.jsx($,{asChild:!0,className:"bg-white text-[#2a4c64] hover:bg-white/90",children:e.jsxs(wr,{to:"/my-coach",children:[e.jsx(jv,{className:"mr-2 h-4 w-4"})," Book a session"]})}),e.jsx($,{asChild:!0,variant:"outline",className:"border-white/40 bg-white/10 text-white hover:bg-white/20 hover:text-white",children:e.jsxs(wr,{to:"/my-coach",children:[e.jsx(eo,{className:"mr-2 h-4 w-4"})," Message coach"]})})]})]})]}),e.jsxs("div",{className:"grid gap-4 p-5 md:grid-cols-3",children:[e.jsxs("div",{className:"rounded-xl border border-border/60 bg-muted/30 p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:[e.jsx(ua,{className:"h-3.5 w-3.5"})," Next session"]}),y?e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"mt-2 text-lg font-semibold text-foreground",children:en(new Date(y.scheduled_at),"EEE, MMM d")}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[en(new Date(y.scheduled_at),"h:mm a"),y.title?` · ${y.title}`:""]}),y.meeting_url&&e.jsx($,{asChild:!0,size:"sm",variant:"outline",className:"mt-3",children:e.jsx("a",{href:y.meeting_url,target:"_blank",rel:"noreferrer",children:"Join meeting"})})]}):e.jsxs(e.Fragment,{children:[e.jsxs("p",{className:"mt-2 text-sm text-muted-foreground",children:["Nothing on the calendar yet — grab a time with ",m.split(" ")[0],"."]}),e.jsx($,{asChild:!0,size:"sm",className:"mt-3",children:e.jsx(wr,{to:"/my-coach",children:"Schedule now"})})]})]}),e.jsxs("div",{className:"rounded-xl border border-border/60 bg-muted/30 p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:[e.jsx(Ev,{className:"h-3.5 w-3.5"})," Action items"]}),e.jsxs("div",{className:"mt-2 flex items-baseline gap-2",children:[e.jsx("span",{className:"text-2xl font-bold text-foreground",children:v.length}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"open"}),b>0&&e.jsxs(Be,{variant:"secondary",className:"ml-auto",children:[b," done"]})]}),e.jsxs("ul",{className:"mt-2 space-y-1",children:[v.slice(0,3).map(R=>e.jsxs("li",{className:"flex items-start gap-2 text-sm text-muted-foreground",children:[e.jsx(Og,{className:"mt-1 h-3 w-3 shrink-0"}),e.jsx("span",{className:"line-clamp-1",children:R.title||R.description})]},R.id)),v.length===0&&e.jsx("li",{className:"text-sm text-muted-foreground",children:"You're all caught up."})]})]}),e.jsxs("div",{className:"rounded-xl border border-border/60 bg-muted/30 p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:[e.jsx(zg,{className:"h-3.5 w-3.5"})," Coaching prep"]}),h!=null&&h.submitted?w.length>0?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"mt-2 flex items-center justify-between text-sm",children:[e.jsxs("span",{className:"font-semibold text-foreground",children:[S,"/",w.length," complete"]}),e.jsxs("span",{className:"text-muted-foreground",children:[C,"%"]})]}),e.jsx(Yi,{value:C,className:"mt-2 h-2"}),e.jsx("ul",{className:"mt-3 space-y-1",children:w.slice(0,3).map(R=>e.jsxs("li",{className:"flex items-start gap-2 text-sm",children:[R.done?e.jsx(qr,{className:"mt-0.5 h-3.5 w-3.5 shrink-0 text-primary"}):e.jsx(Og,{className:"mt-0.5 h-3.5 w-3.5 shrink-0 text-muted-foreground/50"}),e.jsx("span",{className:Pt("line-clamp-1",R.done?"text-muted-foreground line-through":"text-foreground"),children:R.title})]},R.id))})]}):e.jsxs("p",{className:"mt-2 flex items-start gap-2 text-sm text-muted-foreground",children:[e.jsx(of,{className:"mt-0.5 h-4 w-4 shrink-0"})," Questionnaire submitted — your coach is building your plan."]}):e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"mt-2 text-sm text-muted-foreground",children:"Complete your onboarding questionnaire before session one."}),e.jsx($,{asChild:!0,size:"sm",className:"mt-3",children:e.jsx(wr,{to:"/coaching/onboarding",children:"Start questionnaire"})})]})]})]})]})}function bWs(s){return"EST"}function fse(s){const n=new Intl.DateTimeFormat("en-US",{hour:"numeric",minute:"2-digit",hour12:!0,timeZone:"America/New_York"}).format(s),r=bWs();return`${n} ${r}`}function m8(s){const t=new Date,n=new Date(s),r=Pyt(n,-15),a=Pyt(n,30);return t>a?"ended":RS(t,{start:n,end:a})?"live":RS(t,{start:r,end:n})?"starting_soon":"upcoming"}function mnt(s){const t=m8(s);return t==="starting_soon"||t==="live"}const _Ws=mnt,wWs=({events:s,registrations:t,onNavigateToEvents:n})=>{const[r,a]=j.useState(new Date);j.useEffect(()=>{const f=setInterval(()=>{a(new Date)},3e4);return()=>clearInterval(f)},[]);const i=s.filter(f=>mnt(f.event_date));if(i.length===0)return null;const l=i[0],o=m8(l.event_date),c=t.find(f=>f.event_id===l.id),d=(c==null?void 0:c.zoom_join_url)||l.zoom_link,u=!!c,h=o==="live",m=h?{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 ${m.container} border`,children:[e.jsx("div",{className:`absolute inset-0 bg-gradient-to-r ${m.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 ${m.indicator} opacity-75`}),e.jsx("span",{className:`relative flex h-3 w-3 rounded-full ${m.indicator}`})]}),e.jsx("div",{className:`flex items-center gap-2 ${m.text} font-bold text-sm uppercase tracking-wider`,children:h?e.jsxs(e.Fragment,{children:[e.jsx(Nb,{className:"h-4 w-4"}),"Live Now"]}):e.jsxs(e.Fragment,{children:[e.jsx(da,{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:h?`Started at ${fse(new Date(l.event_date))}`:`Starts at ${fse(new Date(l.event_date))}`})]}),e.jsx("div",{className:"flex items-center gap-2",children:u?e.jsxs($,{onClick:()=>window.open(d,"_blank"),className:`${m.button} text-white gap-2`,children:[e.jsx(kr,{className:"h-4 w-4"}),h?"Join Now":"Join When Live"]}):e.jsxs($,{variant:"outline",onClick:n,className:`${m.outlineButton} gap-2`,children:[e.jsx(Zn,{className:"h-4 w-4"}),"Register & Join"]})})]})})]})};function yy(){const{user:s}=vs(),{data:t,isLoading:n}=tt({queryKey:["gmail-integration",s==null?void 0:s.id],enabled:!!(s!=null&&s.id),queryFn:async()=>{const{data:m,error:f}=await q.from("gmail_integrations").select("*").eq("user_id",s.id).maybeSingle();if(f)throw f;return m}}),{data:r,isLoading:a}=tt({queryKey:["user-verified-ses-sender",s==null?void 0:s.id],enabled:!!s,staleTime:60*1e3,queryFn:async()=>{const{data:m}=await q.from("user_verified_senders").select("email, status").eq("user_id",s.id).eq("status","verified").order("verified_at",{ascending:!1}).limit(1).maybeSingle();return m}}),i=!!(t!=null&&t.is_active),l=!!t&&!t.is_active,o=(t==null?void 0:t.gmail_email)||null,c=!!(r!=null&&r.email),d=(r==null?void 0:r.email)||null;return{isGmailConnected:i,gmailNeedsReconnect:l,gmailEmail:o,hasVerifiedSes:c,sesEmail:d,canSendEmail:i||c,sendMethod:i?"gmail":c?"mass_email":"none",isLoading:n||a}}function jWs(){var C;const{user:s}=vs(),{isGmailConnected:t,hasVerifiedSes:n,isLoading:r}=yy(),a=jC(),i=a.isMember&&!!((C=a.pkg)!=null&&C.includes_coaching),l=a.isMember&&!i,[o,c]=j.useState(!1),[d,u]=j.useState(!1);j.useEffect(()=>{s!=null&&s.id&&q.from("onboarding_checklist_dismissed").select("id").eq("user_id",s.id).maybeSingle().then(({data:E})=>{c(!!E),u(!0)})},[s==null?void 0:s.id]);const{data:h,isLoading:m}=tt({queryKey:["new-agent-onboarding",s==null?void 0:s.id],enabled:!!(s!=null&&s.id),staleTime:3e4,queryFn:async()=>{const[E,I,P,R,D,O]=await Promise.all([q.from("profiles").select("avatar_url, phone, bio, name").eq("id",s.id).maybeSingle(),q.from("innercircle_contacts").select("id",{count:"exact",head:!0}).eq("owner_user_id",s.id),q.from("event_registrations").select("id",{count:"exact",head:!0}).eq("user_id",s.id),q.from("community_posts").select("id",{count:"exact",head:!0}).eq("user_id",s.id),q.from("events").select("id, title, event_date, image_url").eq("is_published",!0).gte("event_date",new Date().toISOString()).or("title.ilike.%onboarding%,title.ilike.%new member%,title.ilike.%welcome%,description.ilike.%new member onboarding%").order("event_date",{ascending:!0}).limit(1).maybeSingle(),q.from("coaching_assignments").select("id").eq("agent_id",s.id).eq("status","active").limit(1)]),U=(O.data||[]).map(ie=>ie.id);let W=!1;if(U.length){const{count:ie}=await q.from("coaching_sessions").select("id",{count:"exact",head:!0}).in("assignment_id",U);W=(ie||0)>0}const V=E.data,G=!!(V!=null&&V.avatar_url&&(V!=null&&V.phone)&&(V!=null&&V.bio)),Y=I.count||0,X=(P.count||0)>0,ae=R.count||0;return{profile:V,profileComplete:G,contactsCount:Y,contactsComplete:Y>=5,eventsRegistered:X,communityComplete:ae>0,nextOnboardingEvent:D.data||null,coachingBooked:W}}}),f=t||n,g=[{id:"profile",complete:!!(h!=null&&h.profileComplete)},{id:"email",complete:f},{id:"contacts",complete:!!(h!=null&&h.contactsComplete)},{id:"event",complete:!!(h!=null&&h.eventsRegistered)},{id:"community",complete:!!(h!=null&&h.communityComplete)}],x=l?g.filter(E=>E.id!=="community"&&E.id!=="event"):g;i&&x.push({id:"coaching",complete:!!(h!=null&&h.coachingBooked)});const y=x.filter(E=>E.complete).length,v=x.length;return{steps:x,completedCount:y,totalCount:v,allComplete:y===v,dismissed:o,dismiss:async()=>{s!=null&&s.id&&(c(!0),await q.from("onboarding_checklist_dismissed").insert({user_id:s.id}))},reopen:async()=>{s!=null&&s.id&&(c(!1),await q.from("onboarding_checklist_dismissed").delete().eq("user_id",s.id))},data:h,isGmailConnected:t,hasVerifiedSes:n,loading:m||r||!d||a.isLoading}}const NWs={profile:{title:"Complete Your Profile",description:"Add your headshot, phone, and short bio so contacts recognize you.",icon:sl,accent:"from-[#2a4c64] to-[#406E71]",cta:"Edit Profile"},email:{title:"Set Up Email Sending",description:"Connect Gmail (recommended) or verify a Mass Email sender to send from your address.",icon:mn,accent:"from-[#406E71] to-[#5b9ea1]",cta:"Connect Email"},contacts:{title:"Add Your First Contacts",description:"Import your database or add contacts one at a time to start building your Inner Circle.",icon:Zn,accent:"from-[#c9a84c] to-[#e8c76f]",cta:"Add Contacts"},event:{title:"Register for New Member Onboarding",description:"Join our live LevelUp onboarding session to hit the ground running.",icon:Ta,accent:"from-[#8b5cf6] to-[#a78bfa]",cta:"Register"},community:{title:"Say Hi in the Community",description:"Introduce yourself and connect with other LevelUp agents.",icon:eo,accent:"from-[#ec4899] to-[#f472b6]",cta:"Visit Community"},coaching:{title:"Schedule Your Coaching Session",description:"Book your first 1:1 session with your LevelUp coach.",icon:of,accent:"from-[#0ea5e9] to-[#38bdf8]",cta:"Book Session"}};function kWs(){var x,y;const s=Qn(),{user:t}=vs(),{steps:n,completedCount:r,totalCount:a,allComplete:i,dismissed:l,dismiss:o,data:c,loading:d}=jWs(),[u,h]=j.useState(!0);if(d||l||i)return null;const m=(((x=c==null?void 0:c.profile)==null?void 0:x.name)||((y=t==null?void 0:t.user_metadata)==null?void 0:y.name)||"there").split(" ")[0],f=r/a*100,g=async v=>{switch(v){case"profile":s("/profile");break;case"email":s("/mission-control/integrations");break;case"contacts":s("/mission-control/contacts");break;case"event":{const b=c==null?void 0:c.nextOnboardingEvent;if(!b){s("/events");return}if(!(t!=null&&t.id))return;const{error:w}=await q.from("event_registrations").insert({user_id:t.id,event_id:b.id});w&&!String(w.message).toLowerCase().includes("duplicate")?(re.error("Could not register — opening events page."),s("/events")):re.success(`You're registered for ${b.title}!`);break}case"community":s("/community");break;case"coaching":s("/my-coach");break}};return e.jsxs(Ne,{className:"mb-6 overflow-hidden border-0 shadow-lg",children:[e.jsxs("div",{className:"relative bg-gradient-to-br from-[#2a4c64] via-[#345a75] to-[#406E71] p-6 md:p-8 text-white",children:[e.jsx("button",{onClick:o,className:"absolute top-4 right-4 p-1.5 rounded-full hover:bg-white/10 transition","aria-label":"Dismiss",children:e.jsx(gr,{className:"h-4 w-4"})}),e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx("div",{className:"hidden sm:flex h-12 w-12 rounded-xl bg-white/15 backdrop-blur items-center justify-center shrink-0",children:e.jsx(Nn,{className:"h-6 w-6 text-[#f5f0e0]"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("h2",{className:"text-xl md:text-2xl font-bold",children:["Welcome to LevelUp, ",m,"! 👋"]}),e.jsx("p",{className:"text-white/80 mt-1 text-sm md:text-base",children:"Let's get you set up in under 10 minutes."}),e.jsxs("div",{className:"mt-4 max-w-md",children:[e.jsxs("div",{className:"flex items-center justify-between text-xs mb-1.5 text-white/90",children:[e.jsxs("span",{className:"font-medium",children:[r," of ",a," complete"]}),e.jsxs("span",{children:[a-r," steps left"]})]}),e.jsx(Yi,{value:f,className:"h-2 bg-white/20 [&>div]:bg-[#f5f0e0]"})]}),e.jsxs("div",{className:"mt-5 flex flex-wrap items-center gap-3",children:[e.jsxs($,{onClick:()=>h(!0),className:"bg-[#f5f0e0] text-[#2a4c64] hover:bg-white font-semibold",children:["Continue Setup ",e.jsx(ei,{className:"h-4 w-4 ml-1.5"})]}),e.jsx("button",{onClick:()=>h(v=>!v),className:"text-sm text-white/80 hover:text-white flex items-center gap-1",children:u?e.jsxs(e.Fragment,{children:["Hide steps ",e.jsx(v1,{className:"h-4 w-4"})]}):e.jsxs(e.Fragment,{children:["Show steps ",e.jsx(Tl,{className:"h-4 w-4"})]})})]})]})]})]}),u&&e.jsx(Ie,{className:"p-4 md:p-6 bg-gradient-to-b from-background to-muted/30",children:e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:n.map(v=>{const b=NWs[v.id],w=b.icon;return e.jsx("div",{className:Pt("relative rounded-xl border p-4 transition-all group",v.complete?"bg-muted/40 border-muted":"bg-card hover:shadow-md hover:border-primary/40 cursor-pointer"),onClick:()=>!v.complete&&g(v.id),children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:Pt("h-10 w-10 rounded-lg flex items-center justify-center shrink-0 bg-gradient-to-br text-white",v.complete?"from-emerald-500 to-emerald-600":b.accent),children:v.complete?e.jsx(qr,{className:"h-5 w-5"}):e.jsx(w,{className:"h-5 w-5"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsx("h3",{className:Pt("font-semibold text-sm",v.complete&&"text-muted-foreground line-through"),children:b.title})}),e.jsx("p",{className:Pt("text-xs text-muted-foreground mt-1 leading-relaxed",v.complete&&"line-through"),children:b.description}),v.id==="event"&&!v.complete&&(c==null?void 0:c.nextOnboardingEvent)&&e.jsxs("div",{className:"mt-2 text-xs font-medium text-primary",children:[new Date(c.nextOnboardingEvent.event_date).toLocaleDateString("en-US",{weekday:"short",month:"short",day:"numeric",hour:"numeric",minute:"2-digit",timeZone:"America/New_York"})," ","ET"]}),!v.complete&&e.jsxs($,{size:"sm",variant:"ghost",className:"mt-2 h-7 px-2 -ml-2 text-primary hover:text-primary hover:bg-primary/10",onClick:S=>{S.stopPropagation(),g(v.id)},children:[b.cta," ",e.jsx(ei,{className:"h-3 w-3 ml-1"})]})]}),v.complete&&e.jsx("span",{className:"text-xs font-medium text-emerald-600 shrink-0",children:"✓ Done"})]})},v.id)})})})]})}function SWs(s){return tt({queryKey:["brokerage-content-categories",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await q.from("brokerage_content_categories").select("*").eq("brokerage_id",s).order("sort_order");if(n)throw n;return t},enabled:!!s})}function CWs(s,t){return tt({queryKey:["brokerage-content",s,t],queryFn:async()=>{if(!s)return[];let n=q.from("brokerage_content").select("*, category:brokerage_content_categories(*)").eq("brokerage_id",s).order("created_at",{ascending:!1});t&&(n=n.eq("category_id",t));const{data:r,error:a}=await n;if(a)throw a;return r},enabled:!!s})}function AWs(s,t=4){return tt({queryKey:["brokerage-content-recent",s,t],queryFn:async()=>{if(!s)return[];const{data:n,error:r}=await q.from("brokerage_content").select("*, category:brokerage_content_categories(*)").eq("brokerage_id",s).order("created_at",{ascending:!1}).limit(t);if(r)throw r;return n},enabled:!!s})}function EWs(s){const t=Vt();return ft({mutationFn:async n=>{const{data:r,error:a}=await q.from("brokerage_content").insert(n).select().single();if(a)throw a;return r},onSuccess:()=>{t.invalidateQueries({queryKey:["brokerage-content"]}),t.invalidateQueries({queryKey:["brokerage-content-recent"]})}})}function TWs(){const s=Vt();return ft({mutationFn:async t=>{const{error:n}=await q.from("brokerage_content").delete().eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["brokerage-content"]}),s.invalidateQueries({queryKey:["brokerage-content-recent"]})}})}function MWs(s){const t=Vt();return ft({mutationFn:async n=>{const{data:r,error:a}=await q.from("brokerage_content_categories").insert({...n,brokerage_id:s}).select().single();if(a)throw a;return r},onSuccess:()=>{t.invalidateQueries({queryKey:["brokerage-content-categories"]})}})}function PWs(){const s=Vt();return ft({mutationFn:async t=>{const{error:n}=await q.from("brokerage_content_categories").delete().eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["brokerage-content-categories"]})}})}function IWs(s){const t=Vt();return ft({mutationFn:async()=>{const n=[{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:r}=await q.from("brokerage_content_categories").upsert(n,{onConflict:"brokerage_id,name"});if(r)throw r},onSuccess:()=>{t.invalidateQueries({queryKey:["brokerage-content-categories"]})}})}const LWs={video:Bu,pdf:Jr,link:bd,event:Ta,graphic:Yc},RWs={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 DWs(s){if(!s)return null;try{const t=new URL(s),n=t.hostname.replace("www.","");let r=null;if(n==="youtube.com"||n==="m.youtube.com"?r=t.searchParams.get("v"):n==="youtu.be"&&(r=t.pathname.slice(1)),r)return`https://img.youtube.com/vi/${r}/hqdefault.jpg`}catch{}return null}function FWs(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 OWs({item:s}){const t=Qn(),n=LWs[s.content_type]||bd,r=RWs[s.content_type]||"",[a,i]=j.useState(null),l=s.thumbnail_url||(s.content_type==="graphic"&&s.file_url?s.file_url:null)||(s.content_type==="video"?DWs(s.url):null);j.useEffect(()=>{l||!s.url||s.content_type!=="video"||!FWs(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(Ne,{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(n,{className:"h-8 w-8 text-muted-foreground/30"})}),e.jsxs(Ie,{className:"p-3",children:[e.jsx("div",{className:"flex items-center gap-1.5 mb-1.5",children:e.jsxs(Be,{variant:"secondary",className:`text-[10px] px-1.5 py-0 ${r}`,children:[e.jsx(n,{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:en(new Date(s.event_date),"MMM d · h:mm a")})]})]})}function zWs(){const{brokerageId:s}=vs(),t=Qn(),{data:n=[],isLoading:r}=AWs(s,4);return!s||r||n.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(ji,{className:"h-5 w-5 text-primary"}),e.jsx("h3",{className:"text-lg font-semibold text-foreground",children:"Brokerage Content"})]}),e.jsxs($,{variant:"ghost",size:"sm",onClick:()=>t("/brokerage-content"),className:"gap-1 text-muted-foreground hover:text-foreground",children:["View All ",e.jsx(ei,{className:"h-4 w-4"})]})]}),e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4",children:n.map(a=>e.jsx(OWs,{item:a},a.id))})]})}const JUt=({className:s,variant:t="default"})=>e.jsx(Be,{variant:"outline",className:Pt("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"}),BWs={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"},$Ws={coming_soon:"Coming Soon",office_exclusive:"Office Exclusive",pre_market:"Pre-Market",active:"Active",under_contract:"Under Contract",sold:"Sold",withdrawn:"Withdrawn"};function UWs(s){return s>=1e6?`$${(s/1e6).toFixed(1)}M`:`$${(s/1e3).toFixed(0)}K`}function qWs(){const s=Qn(),{data:t,isLoading:n}=F$t(),{data:r,isLoading:a}=O$t({status:void 0,propertyType:void 0,sortBy:"newest"}),i=(r==null?void 0:r.filter(u=>u.is_approved&&u.is_public))||[],l=i.filter(u=>u.is_featured),o=i.filter(u=>!u.is_featured),c=[...l,...o].slice(0,6),d=n||a;return!d&&!t?null:d?e.jsx(Ne,{className:"bg-gradient-to-br from-emerald-500/5 via-emerald-500/10 to-emerald-500/5 border-emerald-500/20",children:e.jsx(Ie,{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(JUt,{})]}),e.jsxs($,{variant:"ghost",size:"sm",onClick:()=>s("/mission-control/listings"),className:"gap-1 text-muted-foreground hover:text-foreground",children:["View All ",e.jsx(ei,{className:"h-4 w-4"})]})]}),c.length===0?e.jsx(Ne,{className:"bg-muted/30 border-dashed",children:e.jsx(Ie,{className:"flex items-center justify-center py-8",children:e.jsxs("div",{className:"text-center",children:[e.jsx(va,{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($,{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(u=>{var m,f;const h=((m=u.photos)==null?void 0:m.find(g=>g.is_primary))||((f=u.photos)==null?void 0:f[0]);return e.jsxs("div",{onClick:()=>s(`/mission-control/listings/${u.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:[h!=null&&h.photo_url?e.jsx("img",{src:h.photo_url,alt:`${u.city}, ${u.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(va,{className:"h-8 w-8 text-muted-foreground/50"})}),u.is_featured&&e.jsx("div",{className:"absolute top-1.5 left-1.5",children:e.jsxs(Be,{className:"gap-1 bg-amber-500 text-white border-0 text-[10px] px-1.5 py-0.5",children:[e.jsx(Ja,{className:"h-2.5 w-2.5 fill-current"}),"Featured"]})}),e.jsx("div",{className:"absolute top-1.5 right-1.5",children:e.jsx(Be,{className:`text-[10px] px-1.5 py-0.5 ${BWs[u.status]}`,children:$Ws[u.status]})})]}),e.jsxs("div",{className:"p-2",children:[e.jsx("p",{className:"font-bold text-sm text-foreground",children:UWs(u.price)}),e.jsxs("p",{className:"text-xs text-muted-foreground truncate",children:[u.city,", ",u.state]}),(u.bedrooms||u.bathrooms)&&e.jsxs("p",{className:"text-[10px] text-muted-foreground mt-0.5",children:[u.bedrooms&&`${u.bedrooms} bed`,u.bedrooms&&u.bathrooms&&" · ",u.bathrooms&&`${u.bathrooms} bath`]})]})]},u.id)})})]})}function eqt(s=10,t){return tt({queryKey:["event-leaderboard",s,t],queryFn:async()=>{const{data:n}=await q.from("user_roles").select("user_id").eq("role","admin"),r=new Set((n==null?void 0:n.map(m=>m.user_id))||[]);let a=null;if(t){const{data:m}=await q.from("profiles").select("id").eq("brokerage_id",t);a=new Set((m==null?void 0:m.map(f=>f.id))||[])}const{data:i,error:l}=await q.from("agent_attendance_stats").select("user_id, total_points, total_events_attended, current_streak").order("total_points",{ascending:!1}).limit(s+r.size+50);if(l)throw l;if(!i||i.length===0)return[];let o=i.filter(m=>!r.has(m.user_id));a&&(o=o.filter(m=>a.has(m.user_id)));const c=o.slice(0,s),d=c.map(m=>m.user_id),{data:u}=await q.from("profiles").select("id, name").in("id",d),h=new Map((u==null?void 0:u.map(m=>[m.id,{name:m.name}]))||[]);return c.map(m=>({user_id:m.user_id,total_points:m.total_points,total_events_attended:m.total_events_attended,current_streak:m.current_streak,profile:h.get(m.user_id)||null}))}})}function tqt(s){return tt({queryKey:["user-attendance-stats",s],queryFn:async()=>{if(!s)return null;const{data:t,error:n}=await q.from("agent_attendance_stats").select("*").eq("user_id",s).single();if(n&&n.code!=="PGRST116")throw n;return t},enabled:!!s})}function sqt(s){return tt({queryKey:["user-badges",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await q.from("agent_badges").select("*").eq("user_id",s).order("earned_at",{ascending:!1});if(n)throw n;return t},enabled:!!s})}function nqt(s,t){return tt({queryKey:["user-rank",s,t],queryFn:async()=>{if(!s)return null;const{data:n}=await q.from("agent_attendance_stats").select("total_points").eq("user_id",s).single();if(!n)return null;const{data:r}=await q.from("user_roles").select("user_id").eq("role","admin"),a=new Set((r==null?void 0:r.map(c=>c.user_id))||[]),{data:i,error:l}=await q.from("agent_attendance_stats").select("user_id, total_points").gt("total_points",n.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 q.from("profiles").select("id").eq("brokerage_id",t),d=new Set((c==null?void 0:c.map(u=>u.id))||[]);o=o.filter(u=>d.has(u.user_id))}return o.length+1},enabled:!!s})}function VWs(){const{user:s,brokerageId:t,isAdmin:n}=vs();Qn();const r=!!t,[a,i]=j.useState("brokerage"),l=()=>{if(n)return null;if(r)return a==="global"?null:t},{data:o,isLoading:c}=eqt(5,l()),{data:d}=tqt(s==null?void 0:s.id),{data:u}=nqt(s==null?void 0:s.id,l()),{data:h}=sqt(s==null?void 0:s.id),m=n||r,f=()=>n?"Agent Leaderboard":r?a==="global"?"All LevelUp":"My Brokerage":"My Points";if(c)return e.jsxs(Ne,{children:[e.jsx(Ct,{className:"pb-2",children:e.jsxs(At,{className:"text-base flex items-center gap-2",children:[e.jsx(Kl,{className:"h-4 w-4 text-yellow-500"}),f()]})}),e.jsx(Ie,{children:e.jsx("div",{className:"space-y-2",children:[...Array(m?5:3)].map((x,y)=>e.jsx(yn,{className:"h-10 w-full"},y))})})]});const g=x=>x===0?e.jsx(Kl,{className:"h-4 w-4 text-yellow-500 mx-auto"}):x===1?e.jsx("span",{className:"text-sm font-medium text-gray-400",children:"2"}):x===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:x+1});if(m){const x=(o==null?void 0:o.slice(0,5))||[];return e.jsxs(Ne,{children:[e.jsxs(Ct,{className:"pb-2",children:[e.jsxs(At,{className:"text-base flex items-center gap-2",children:[e.jsx(Kl,{className:"h-4 w-4 text-yellow-500"}),f()]}),!n&&r&&e.jsxs("div",{className:"flex gap-1 mt-2",children:[e.jsx($,{variant:a==="brokerage"?"default":"outline",size:"sm",className:"text-xs h-7 flex-1",onClick:()=>i("brokerage"),children:"My Brokerage"}),e.jsx($,{variant:a==="global"?"default":"outline",size:"sm",className:"text-xs h-7 flex-1",onClick:()=>i("global"),children:"All LevelUp"})]})]}),e.jsxs(Ie,{children:[!n&&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:["#",u||"-"]})]}),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:[x.map((y,v)=>{var b,w,S;return e.jsxs("div",{className:`flex items-center gap-2 p-2 rounded-lg ${y.user_id===(s==null?void 0:s.id)?"bg-primary/10 border border-primary/20":v===0?"bg-yellow-500/10":""}`,children:[e.jsx("div",{className:"w-5 text-center",children:g(v)}),e.jsx(Oa,{className:"h-6 w-6",children:e.jsx(za,{className:"text-xs",children:((w=(b=y.profile)==null?void 0:b.name)==null?void 0:w.charAt(0))||"?"})}),e.jsx("span",{className:"flex-1 text-sm font-medium truncate",children:((S=y.profile)==null?void 0:S.name)||"Unknown"}),e.jsx("span",{className:"text-sm font-bold text-primary",children:y.total_points})]},y.user_id)}),x.length===0&&e.jsx("div",{className:"text-center text-muted-foreground py-2 text-sm",children:"No data yet"})]}),e.jsxs(wr,{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(ul,{className:"h-4 w-4"}),"Spend Points in Reward Store",e.jsx(Di,{className:"h-4 w-4"})]})]})]})}return e.jsxs(Ne,{children:[e.jsx(Ct,{className:"pb-2",children:e.jsxs(At,{className:"text-base flex items-center gap-2",children:[e.jsx(Kl,{className:"h-4 w-4 text-yellow-500"}),"My Points"]})}),e.jsx(Ie,{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(nh,{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," 🔥"]})]}),h&&h.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(Rm,{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:[h.slice(0,4).map(x=>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:x.badge_name},x.id)),h.length>4&&e.jsxs("span",{className:"text-xs text-muted-foreground px-2 py-1",children:["+",h.length-4," more"]})]})]}),e.jsxs(wr,{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(ul,{className:"h-4 w-4"}),"Spend Points in Reward Store",e.jsx(Di,{className:"h-4 w-4"})]})]}):e.jsxs("div",{className:"text-center text-muted-foreground py-4 text-sm",children:[e.jsx(Ja,{className:"h-8 w-8 mx-auto mb-2 text-muted-foreground/50"}),e.jsx("p",{children:"Attend events to earn points!"}),e.jsxs(wr,{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(ul,{className:"h-4 w-4"}),"Visit Reward Store",e.jsx(Di,{className:"h-4 w-4"})]})]})})]})}const HB=()=>tt({queryKey:["lead-sources"],queryFn:async()=>{const{data:s,error:t}=await q.from("lead_sources").select("*").eq("is_active",!0).order("sort_order");if(t)throw t;return s}}),fnt=()=>{const s=Vt(),{user:t}=vs();return ft({mutationFn:async n=>{const{data:r}=await q.from("lead_sources").select("id, name").eq("is_active",!0).ilike("name",n.trim()),a=(r||[]).find(o=>o.name.toLowerCase()===n.trim().toLowerCase()&&!0);if(a)throw new Error(`Lead source "${a.name}" already exists`);const{data:i,error:l}=await q.from("lead_sources").insert({name:n,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"]}),re.success("Lead source added")},onError:n=>{re.error("Failed to add lead source"),console.error(n)}})},HWs=()=>{const s=Vt();return ft({mutationFn:async({id:t,name:n})=>{const{error:r}=await q.from("lead_sources").update({name:n}).eq("id",t);if(r)throw r},onSuccess:()=>{s.invalidateQueries({queryKey:["lead-sources"]}),re.success("Lead source updated")},onError:t=>{re.error(t.message||"Failed to update lead source")}})},GWs=()=>{const s=Vt();return ft({mutationFn:async t=>{const{error:n}=await q.from("lead_sources").update({is_active:!1}).eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["lead-sources"]}),re.success("Lead source removed")},onError:t=>{re.error(t.message||"Failed to remove lead source")}})},pnt=(s,t)=>{const{user:n,isAdmin:r}=vs(),a=r&&t?t:n==null?void 0:n.id;return tt({queryKey:["scorecard-transactions",s,a],queryFn:async()=>{let i=q.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})},gnt=s=>{const{user:t,isAdmin:n}=vs(),r=n&&s?s:t==null?void 0:t.id;return tt({queryKey:["scorecard-transactions-all",r],queryFn:async()=>{const{data:a,error:i}=await q.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",r).order("close_date",{ascending:!1});if(i)throw i;return a},enabled:!!r})},T6e=()=>{const s=Vt(),{user:t}=vs();return ft({mutationFn:async n=>{const{data:r,error:a}=await q.from("scorecard_transactions").insert({...n,owner_user_id:t.id}).select().single();if(a)throw a;return r},onSuccess:()=>{s.invalidateQueries({queryKey:["scorecard-transactions"]}),s.invalidateQueries({queryKey:["scorecard-transactions-all"]}),re.success("Transaction added")},onError:n=>{re.error("Failed to add transaction"),console.error(n)}})},WWs=()=>{const s=Vt();return ft({mutationFn:async({id:t,...n})=>{const{data:r,error:a}=await q.from("scorecard_transactions").update(n).eq("id",t).select().single();if(a)throw a;return r},onSuccess:()=>{s.invalidateQueries({queryKey:["scorecard-transactions"]}),s.invalidateQueries({queryKey:["scorecard-transactions-all"]}),re.success("Transaction updated")},onError:t=>{re.error("Failed to update transaction"),console.error(t)}})},KWs=()=>{const s=Vt();return ft({mutationFn:async t=>{const{error:n}=await q.from("scorecard_transactions").delete().eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["scorecard-transactions"]}),s.invalidateQueries({queryKey:["scorecard-transactions-all"]}),re.success("Transaction deleted")},onError:t=>{re.error("Failed to delete transaction"),console.error(t)}})},rqt=(s,t)=>{const{user:n,isAdmin:r}=vs(),a=r&&t?t:n==null?void 0:n.id;return tt({queryKey:["scorecard-goals",s,a],queryFn:async()=>{const{data:i,error:l}=await q.from("scorecard_goals").select("*").eq("owner_user_id",a).eq("year",s).maybeSingle();if(l)throw l;return i},enabled:!!a})},YWs=()=>{const s=Vt(),{user:t}=vs();return ft({mutationFn:async n=>{const{data:r,error:a}=await q.from("scorecard_goals").upsert({...n,owner_user_id:t.id},{onConflict:"owner_user_id,year"}).select().single();if(a)throw a;return r},onSuccess:(n,r)=>{s.invalidateQueries({queryKey:["scorecard-goals",r.year]}),re.success("Goals saved")},onError:n=>{re.error("Failed to save goals"),console.error(n)}})},M6e=()=>{const{user:s}=vs();return tt({queryKey:["scorecard-settings",s==null?void 0:s.id],queryFn:async()=>{const{data:t,error:n}=await q.from("scorecard_settings").select("*").eq("user_id",s.id).maybeSingle();if(n)throw n;return t},enabled:!!(s!=null&&s.id)})},ZWs=()=>{const s=Vt(),{user:t}=vs();return ft({mutationFn:async n=>{const{data:r,error:a}=await q.from("scorecard_settings").upsert({...n,user_id:t.id},{onConflict:"user_id"}).select().single();if(a)throw a;return r},onSuccess:()=>{s.invalidateQueries({queryKey:["scorecard-settings"]}),re.success("Settings saved")},onError:n=>{re.error("Failed to save settings"),console.error(n)}})},aqt=(s,t)=>{const{data:n,isLoading:r}=pnt(s,t),{data:a,isLoading:i}=gnt(t),{data:l}=M6e(),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 u=d.filter(C=>C.transaction_type==="buyer").length,h=d.filter(C=>C.transaction_type==="seller").length,m=d.reduce((C,E)=>C+Number(E.sale_price),0),f=d.reduce((C,E)=>C+(Number(E.commission_amount)||0),0),g=d.reduce((C,E)=>{const I=Number(E.commission_amount)||0;if(!I)return C;let P=I;return E.brokerage_split_pct&&(P-=I*(E.brokerage_split_pct/100)),E.team_split_pct&&(P-=I*(E.team_split_pct/100)),E.franchise_fee_pct&&(P-=I*(E.franchise_fee_pct/100)),E.referral_fee_pct&&(P-=I*(E.referral_fee_pct/100)),E.transaction_fee&&(P-=E.transaction_fee),C+Math.max(0,P)},0),x={};d.forEach(C=>{var I;const E=((I=C.lead_source)==null?void 0:I.name)||"Unknown";x[E]=(x[E]||0)+1});const y=Object.entries(x).map(([C,E])=>({name:C,count:E})).sort((C,E)=>E.count-C.count),v=y[0]||null,b={};d.forEach(C=>{const E=Ch(C.close_date).toLocaleString("default",{month:"short"});b[E]=(b[E]||0)+1});const S=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"].map(C=>({month:C,count:b[C]||0}));return{totalTransactions:d.length,buyerCount:u,sellerCount:h,totalVolume:m,averagePrice:d.length>0?m/d.length:0,totalCommission:o?f:0,totalNetToAgent:o?g:0,topLeadSource:v,transactionsByMonth:S,leadSourceBreakdown:y}};return{yearStats:c(n),lifetimeStats:c(a),isLoading:r||i,showCommission:o}},XWs=()=>{const{isAdmin:s}=vs();return tt({queryKey:["agents-with-transactions"],queryFn:async()=>{const{data:t,error:n}=await q.from("scorecard_transactions").select("owner_user_id").order("owner_user_id");if(n)throw n;const r=[...new Set(t.map(l=>l.owner_user_id))],{data:a,error:i}=await q.from("profiles").select("id, name, email").in("id",r);if(i)throw i;return a},enabled:s})},fP={recency:40,touchpoints:30,transactions:20},wbt={warm:70,cooling:40};function QWs(s){return s===null?0:s<=14?fP.recency:s<=30?fP.recency*.85:s<=60?fP.recency*.65:s<=90?fP.recency*.4:s<=180?fP.recency*.2:fP.recency*.05}function JWs(s){const t=Math.min(s/12,1);return Math.round(fP.touchpoints*t)}function eKs(s){return s?fP.transactions:0}function tKs(){return 0}function sKs(s){return s>=wbt.warm?"warm":s>=wbt.cooling?"cooling":"at-risk"}function cie(){const{data:s,isLoading:t}=z_(),{data:n}=BUt(),{data:r}=pK(365),{data:a}=gnt(),i=j.useMemo(()=>{if(!s)return[];const o=new Date,c=d8(o,12),d={};r==null||r.forEach(h=>{new Date(h.completed_at)>=c&&(d[h.contact_id]=(d[h.contact_id]||0)+1)});const u=new Set((a==null?void 0:a.filter(h=>h.contact_id).map(h=>h.contact_id))||[]);return s.map(h=>{const m=(n==null?void 0:n[h.id])||null,f=m?mk(o,new Date(m)):null,g=d[h.id]||0,x=u.has(h.id),y=QWs(f),v=JWs(g),b=eKs(x),w=tKs(),S=Math.round(y+v+b+w),C={score:S,status:sKs(S),breakdown:{recency:Math.round(y),touchpoints:Math.round(v),transactions:Math.round(b),referrals:Math.round(w)},lastTouchDate:m,daysSinceTouch:f,touchCountLast12Months:g,hasTransaction:x};return{...h,relationshipScore:C}})},[s,n,r,a]),l=j.useMemo(()=>{const o=i.filter(m=>m.relationshipScore.status==="warm").length,c=i.filter(m=>m.relationshipScore.status==="cooling").length,d=i.filter(m=>m.relationshipScore.status==="at-risk").length,u=i.length,h=u>0?Math.round(i.reduce((m,f)=>m+f.relationshipScore.score,0)/u):0;return{warm:o,cooling:c,atRisk:d,total:u,averageScore:h}},[i]);return{contactsWithScores:i,stats:l,isLoading:t}}function nKs(s){const{contactsWithScores:t,isLoading:n}=cie(),r=j.useMemo(()=>t.find(a=>a.id===s),[t,s]);return{score:r==null?void 0:r.relationshipScore,isLoading:n}}function iqt(){const s=Qn(),{stats:t,contactsWithScores:n,isLoading:r}=cie();if(r)return e.jsxs(Ne,{children:[e.jsx(Ct,{className:"pb-2",children:e.jsx(yn,{className:"h-5 w-40"})}),e.jsxs(Ie,{className:"space-y-4",children:[e.jsx(yn,{className:"h-20 w-full"}),e.jsx(yn,{className:"h-16 w-full"})]})]});if(t.total===0)return e.jsxs(Ne,{children:[e.jsx(Ct,{className:"pb-2",children:e.jsxs(At,{className:"text-lg flex items-center gap-2",children:[e.jsx(Zn,{className:"h-5 w-5"}),"Relationship Health"]})}),e.jsxs(Ie,{children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Add contacts to see your relationship health scores."}),e.jsx($,{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=n.filter(c=>c.relationshipScore.status==="at-risk").sort((c,d)=>c.relationshipScore.score-d.relationshipScore.score).slice(0,3);return e.jsxs(Ne,{children:[e.jsxs(Ct,{className:"pb-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(At,{className:"text-lg flex items-center gap-2",children:[e.jsx(Yl,{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(Ie,{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(Yi,{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(Yi,{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(Yi,{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(rC,{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(Di,{className:"h-3 w-3"})]})]},c.id))})]}),e.jsxs($,{variant:"outline",size:"sm",className:"w-full",onClick:()=>s("/mission-control/contacts?filter=at-risk"),children:["View All At-Risk Contacts",e.jsx(Di,{className:"h-4 w-4 ml-1"})]})]})]})}const rKs=()=>{const s=Number(new Intl.DateTimeFormat("en-US",{hour:"numeric",hour12:!1,timeZone:"America/New_York"}).format(new Date));return s<12?"Good morning":s<17?"Good afternoon":"Good evening"},aKs=()=>new Intl.DateTimeFormat("en-US",{weekday:"long",month:"long",day:"numeric",timeZone:"America/New_York"}).format(new Date);function iKs({value:s,goal:t}){const n=Math.min(t>0?s/t*100:0,100),r=30,a=2*Math.PI*r;return e.jsxs("div",{className:"relative h-[86px] w-[86px] shrink-0",children:[e.jsxs("svg",{viewBox:"0 0 72 72",className:"h-full w-full -rotate-90",children:[e.jsx("circle",{cx:"36",cy:"36",r,fill:"none",strokeWidth:"7",className:"stroke-current opacity-20"}),e.jsx("circle",{cx:"36",cy:"36",r,fill:"none",strokeWidth:"7",strokeLinecap:"round",stroke:"hsl(var(--hub-glow))",strokeDasharray:a,strokeDashoffset:a-a*n/100,style:{transition:"stroke-dashoffset .6s ease"}})]}),e.jsxs("div",{className:"absolute inset-0 flex flex-col items-center justify-center leading-none",children:[e.jsx("span",{className:"text-lg font-bold",children:s}),e.jsxs("span",{className:"text-[10px] hub-ink-muted",children:["of ",t]})]})]})}function oKs({name:s,eventsThisWeek:t=0}){const n=Qn(),{user:r}=vs(),{data:a}=ont(),{data:i}=DUt(),l=k6e(),{hasAccess:o,hasAssignment:c}=qzt(),{hasFeature:d}=jC(),{data:u}=tt({queryKey:["hub-active-listings",r==null?void 0:r.id],enabled:!!(r!=null&&r.id),queryFn:async()=>{const{count:w,error:S}=await q.from("listings").select("id",{count:"exact",head:!0}).eq("agent_id",r.id);return S?0:w||0}}),h=j.useMemo(()=>{if(!i)return 0;const w=Date.now()-7*24*60*60*1e3;return i.filter(S=>S.created_at&&new Date(S.created_at).getTime()>=w).length},[i]),m=(a==null?void 0:a.length)||0,f=(l==null?void 0:l.streak)||0,g=(l==null?void 0:l.actionsThisWeek)||0,x=(l==null?void 0:l.weeklyGoal)||20,y=[m>0?`${m} ${m===1?"person":"people"} to reach out to`:"no follow-ups queued",t>0?`${t} ${t===1?"event":"events"} coming up`:null].filter(Boolean).join(" • "),v=[{label:"New leads (7d)",value:h,to:"/mission-control/contacts"},{label:"Follow-ups due",value:m,to:"/mission-control"},...d("listing_exchange")?[{label:"My listings",value:u??0,to:"/mission-control/listings"}]:[],{label:"Day streak",value:f,to:"/mission-control",icon:nh}],b=[{label:"Add Contact",icon:sc,to:"/mission-control/contacts?new=true"},...d("social")?[{label:"Create Post",icon:zd,to:"/social-swag-2"}]:[],...d("presentations")?[{label:"Listing Presentation",icon:jb,to:"/mission-control/listing-presentations"}]:[],...o?[{label:"Book Coaching",icon:Au,to:c?"/my-coach":"/coaching"}]:[],{label:"Ask AI",icon:Nn,to:"/ask-ai"}];return e.jsxs("section",{className:"hub-ink relative overflow-hidden rounded-2xl p-5 sm:p-7 mb-6",children:[e.jsxs("div",{className:"relative flex flex-col gap-6 lg:flex-row lg:items-start lg:justify-between",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"text-xs uppercase tracking-wider hub-ink-muted",children:aKs()}),e.jsxs("h1",{className:"mt-1 text-2xl sm:text-3xl font-bold",children:[rKs(),", ",s]}),e.jsx("p",{className:"mt-1 text-sm hub-ink-muted",children:y?`Today: ${y}.`:"You're all clear today — go create some momentum."}),e.jsx("div",{className:"mt-5 grid grid-cols-2 gap-2 sm:grid-cols-4",children:v.map(w=>e.jsxs("button",{onClick:()=>n(w.to),className:"hub-glass rounded-xl px-3 py-2.5 text-left transition-colors",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[w.icon&&e.jsx(w.icon,{className:"h-4 w-4",style:{color:"hsl(var(--hub-glow))"}}),e.jsx("span",{className:"text-xl font-bold",children:w.value})]}),e.jsx("p",{className:"mt-0.5 text-[11px] hub-ink-muted",children:w.label})]},w.label))})]}),e.jsxs("div",{className:"hub-glass flex items-center gap-4 rounded-2xl px-4 py-3 lg:self-center",children:[e.jsx(iKs,{value:g,goal:x}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-sm font-semibold",children:"Weekly touches"}),e.jsx("p",{className:"text-xs hub-ink-muted",children:g>=x?"Goal crushed 🎉":`${x-g} to hit your goal`}),e.jsxs("button",{onClick:()=>n("/mission-control"),className:"mt-2 inline-flex items-center gap-1 text-xs font-medium underline-offset-2 hover:underline",children:["Open Agent OS ",e.jsx(ei,{className:"h-3 w-3"})]})]})]})]}),e.jsx("div",{className:"hub-scroll relative mt-5 flex gap-2 overflow-x-auto pb-1",children:b.map(w=>e.jsxs("button",{onClick:()=>n(w.to),className:"hub-glass flex shrink-0 items-center gap-2 rounded-full px-3.5 py-2 text-sm font-medium transition-colors",children:[e.jsx(w.icon,{className:"h-4 w-4",style:{color:"hsl(var(--hub-glow))"}}),w.label]},w.label))})]})}const sq=24*60*60*1e3,lKs=s=>{if(!s)return null;const t=String(s).split(/[-/T]/);if(t.length<3)return null;const n=parseInt(t[1],10)-1,r=parseInt(t[2],10);return isNaN(n)||isNaN(r)?null:{month:n,day:r}},ode=s=>{const t=lKs(s);if(!t)return null;const n=new Date,r=new Date(n.getFullYear(),n.getMonth(),n.getDate());let a=new Date(n.getFullYear(),t.month,t.day);return a.getTime()s!==null&&s>=0&&s<=t,dKs=s=>s===0?"today":s===1?"tomorrow":`in ${s} days`,uKs={hot_lead_listings:{reason:"Viewing your listings repeatedly",action:"Call now",priority:20},listing_email_click:{reason:"Clicked a listing in your email",action:"Call",priority:21},listing_email_open:{reason:"Opened your listing email",action:"Text",priority:24},open_house_visitor:{reason:"Visited your open house",action:"Follow up",priority:22},email_clicked:{reason:"Clicked a link in your email",action:"Call",priority:23},active_email_thread:{reason:"Active email conversation",action:"Reply",priority:23},email_opened:{reason:"Opened your recent email",action:"Text",priority:26},long_term_homeowner:{reason:"Owned their home 7+ years",action:"Send equity check-in",priority:28},birthday_soon:{reason:"Birthday coming up",action:"Send wishes",priority:12},home_anniversary_soon:{reason:"Home anniversary coming up",action:"Send wishes",priority:13}},hKs=(s=5)=>{const t=Sa(),{data:n,isLoading:r}=ont(),{data:a,isLoading:i}=z_(),l=tt({queryKey:["smart-queue",t,n==null?void 0:n.length,a==null?void 0:a.length],queryFn:async()=>{var I;const o=[],c=new Set,d=P=>{var R;!((R=P.contact)!=null&&R.id)||c.has(P.contact.id)||(c.add(P.contact.id),o.push(P))};if((n||[]).forEach((P,R)=>{var D;d({key:`plan-${P.contact.id}-${R}`,contact:P.contact,kind:"plan",actionLabel:((D=P.actionType)==null?void 0:D.name)||"Touch",reason:P.planName?`${P.planName}${P.relationshipTypeName?` · ${P.relationshipTypeName}`:""}`:"Scheduled touch",priority:0,planAction:P})}),o.length>=s)return o.slice(0,s);const u=a||[],h=new Map(u.map(P=>[P.id,P])),[{data:m},{data:f},{data:g}]=await Promise.all([q.from("contact_snoozes").select("contact_id").gte("snoozed_until",new Date().toISOString()),q.from("contact_touch_logs").select("contact_id").eq("owner_user_id",t).gte("completed_at",new Date(Date.now()-14*sq).toISOString()),q.from("contact_touch_logs").select("contact_id").eq("owner_user_id",t).gte("completed_at",new Date(Date.now()-90*sq).toISOString())]),x=new Set([...(m||[]).map(P=>P.contact_id),...(f||[]).map(P=>P.contact_id)]),y=new Set((g||[]).map(P=>P.contact_id)),v=P=>!x.has(P)&&!c.has(P);for(const P of u){if(!v(P.id))continue;const D=[{days:ode(P.birthday),label:"Birthday"},{days:ode(P.home_anniversary),label:"Home anniversary"},{days:ode(P.wedding_anniversary),label:"Wedding anniversary"},{days:ode(P.spouse_birthday),label:`${P.spouse_name||"Spouse"}'s birthday`}].find(O=>cKs(O.days,7));D&&d({key:`milestone-${P.id}`,contact:P,kind:"milestone",actionLabel:"Send wishes",reason:`${D.label} ${dKs(D.days)}`,priority:D.days===0?1:5+D.days})}const{data:b}=await q.from("contact_signals").select("contact_id, signal_type, title, weight, detected_at").eq("owner_user_id",t).or(`expires_at.is.null,expires_at.gt.${new Date().toISOString()}`).order("weight",{ascending:!1}).order("detected_at",{ascending:!1}).limit(200);for(const P of b||[]){const R=h.get(P.contact_id);if(!R||!v(P.contact_id))continue;const D=uKs[P.signal_type]||{reason:P.title||"Recent activity",action:"Follow up",priority:27};d({key:`signal-${P.contact_id}`,contact:R,kind:"signal",actionLabel:D.action,reason:D.reason,priority:D.priority})}const{data:w}=await q.from("deal_pipeline").select("contact_id, deal_name, property_address, updated_at").eq("owner_user_id",t).is("actual_close_date",null).not("contact_id","is",null).order("updated_at",{ascending:!0}).limit(50);for(const P of w||[]){const R=h.get(P.contact_id);!R||!v(P.contact_id)||d({key:`deal-${P.contact_id}`,contact:R,kind:"deal",actionLabel:"Check in",reason:`Open deal with no contact in 2 weeks${P.property_address?` · ${P.property_address}`:""}`,priority:30})}const S=Date.now()-3*sq;for(const P of u)v(P.id)&&(y.has(P.id)||new Date(P.created_at).getTime()v(P.id)&&!y.has(P.id)&&new Date(P.created_at).getTime()P.id.localeCompare(R.id));if(E.length>0){const P=new Date().getDate()*7%E.length;for(let R=0;RP.priority-R.priority).slice(0,s)},enabled:!!t&&!r&&!i});return{...l,isLoading:l.isLoading||r||i}},mKs=()=>{const s=Sa(),t=Vt();return ft({mutationFn:async n=>{const r=new Date(Date.now()+14*sq).toISOString(),{error:a}=await q.from("contact_snoozes").insert({contact_id:n,owner_user_id:s,snoozed_until:r});if(a)throw a},onSuccess:()=>{t.invalidateQueries({queryKey:["smart-queue"]}),t.invalidateQueries({queryKey:["today-actions"]}),_a({title:"Snoozed for 14 days"})},onError:n=>_a({title:"Could not snooze",description:n.message,variant:"destructive"})})},fKs=s=>(s||"?").split(" ").map(t=>t[0]).slice(0,2).join("").toUpperCase(),pKs={plan:{icon:bb,tint:"var(--nav-crm)"},milestone:{icon:Fg,tint:"var(--nav-events)"},signal:{icon:nh,tint:"var(--nav-marketing)"},deal:{icon:Sx,tint:"var(--nav-listings)"},new:{icon:Nn,tint:"var(--nav-apps)"},cold:{icon:t2,tint:"var(--nav-more)"}};function gKs(){const s=Qn(),{data:t,isLoading:n}=hKs(5),r=mKs(),a=k6e(),i=(a==null?void 0:a.actionsThisWeek)||0,l=(a==null?void 0:a.weeklyGoal)||20,o=t||[];return e.jsxs("section",{className:"hub-card p-5",children:[e.jsxs("div",{className:"mb-4 flex items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsxs("h2",{className:"flex items-center gap-2 text-lg font-semibold text-foreground",children:[e.jsx("span",{className:"flex h-8 w-8 items-center justify-center rounded-full",style:{background:"hsl(var(--nav-crm) / 0.12)"},children:e.jsx(rh,{className:"h-4 w-4",style:{color:"hsl(var(--nav-crm))"}})}),"Today's Top 5"]}),e.jsx("p",{className:"mt-1 text-sm text-muted-foreground",children:o.length>0?"Picked for you from your plans, milestones and live activity.":"Your queue is clear."})]}),e.jsxs($,{variant:"ghost",size:"sm",className:"gap-1",onClick:()=>s("/mission-control"),children:["Agent OS ",e.jsx(Di,{className:"h-4 w-4"})]})]}),n?e.jsx("div",{className:"space-y-2",children:[0,1,2].map(c=>e.jsx(yn,{className:"h-16 w-full rounded-xl"},c))}):o.length===0?e.jsxs("div",{className:"rounded-xl border border-dashed border-border bg-muted/30 p-6 text-center",children:[e.jsx(qr,{className:"mx-auto mb-2 h-7 w-7 text-muted-foreground/50"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Nothing due today. Add a new contact to your database to keep the pipeline full."}),e.jsxs($,{size:"sm",variant:"outline",className:"mt-3 gap-1.5",onClick:()=>s("/mission-control/contacts?new=true"),children:[e.jsx(sc,{className:"h-3.5 w-3.5"})," Add Contact"]})]}):e.jsx(jk,{delayDuration:200,children:e.jsx("div",{className:"space-y-2",children:o.map(c=>{const d=c.contact,u=d.first_name?`${d.first_name} ${d.last_name||""}`.trim():d.name||"Contact",h=pKs[c.kind],m=h.icon;return e.jsxs("div",{className:"group flex items-center gap-3 rounded-xl border border-border p-3 transition-colors hover:bg-muted/40",children:[e.jsx("span",{className:"flex h-10 w-10 shrink-0 items-center justify-center rounded-full text-sm font-semibold",style:{background:`hsl(${h.tint} / 0.12)`,color:`hsl(${h.tint})`},children:fKs(u)}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"truncate text-sm font-medium text-foreground",children:u}),e.jsxs("div",{className:"mt-0.5 flex flex-wrap items-center gap-1.5",children:[e.jsxs(Be,{variant:"secondary",className:"gap-1 text-[10px]",style:{background:`hsl(${h.tint} / 0.12)`,color:`hsl(${h.tint})`},children:[e.jsx(m,{className:"h-3 w-3"}),c.actionLabel]}),e.jsx("span",{className:"truncate text-xs text-muted-foreground",children:c.reason})]})]}),e.jsxs("div",{className:"flex shrink-0 items-center gap-1",children:[e.jsx(xKs,{contact:d,onOpen:()=>s(`/mission-control/contacts/${d.id}`)}),e.jsxs(ly,{children:[e.jsx(cy,{asChild:!0,children:e.jsx($,{size:"icon",variant:"ghost",className:"h-8 w-8 text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100 focus-visible:opacity-100","aria-label":"Not now",disabled:r.isPending,onClick:()=>r.mutate(d.id),children:e.jsx(gr,{className:"h-4 w-4"})})}),e.jsx(Nx,{children:"Not now — hide for 14 days"})]})]})]},c.key)})})}),e.jsxs("div",{className:"mt-4 border-t border-border pt-4",children:[e.jsxs("div",{className:"mb-2 flex items-center justify-between text-sm",children:[e.jsx("span",{className:"font-medium text-foreground",children:"Weekly goal"}),e.jsxs("span",{className:"text-muted-foreground",children:[e.jsx("span",{className:"font-semibold text-primary",children:i})," / ",l," touches"]})]}),e.jsx(Yi,{value:Math.min(i/l*100,100),className:"h-2"})]})]})}function xKs({contact:s,onOpen:t}){const n=(s==null?void 0:s.phone)||(s==null?void 0:s.mobile_phone),r=s==null?void 0:s.email;return e.jsxs(e.Fragment,{children:[n&&e.jsx($,{asChild:!0,size:"icon",variant:"ghost",className:"h-8 w-8","aria-label":"Call",children:e.jsx("a",{href:`tel:${n}`,onClick:a=>a.stopPropagation(),children:e.jsx(Da,{className:"h-4 w-4"})})}),n&&e.jsx($,{asChild:!0,size:"icon",variant:"ghost",className:"h-8 w-8","aria-label":"Text",children:e.jsx("a",{href:`sms:${n}`,onClick:a=>a.stopPropagation(),children:e.jsx(eo,{className:"h-4 w-4"})})}),r&&e.jsx($,{asChild:!0,size:"icon",variant:"ghost",className:"h-8 w-8","aria-label":"Email",children:e.jsx("a",{href:`mailto:${r}`,onClick:a=>a.stopPropagation(),children:e.jsx(mn,{className:"h-4 w-4"})})}),e.jsx($,{size:"icon",variant:"ghost",className:"h-8 w-8","aria-label":"Open contact",onClick:t,children:e.jsx(Di,{className:"h-4 w-4"})})]})}const yKs=s=>{const t=i=>new Intl.DateTimeFormat("en-US",{month:"short",day:"numeric",timeZone:"America/New_York"}).format(i),n=t(new Date),r=t(new Date(Date.now()+864e5)),a=t(s);return a===n?"Today":a===r?"Tomorrow":a};function vKs({events:s,registrations:t}){const n=Qn(),{data:r}=Bst(),{data:a}=tt({queryKey:["hub-upcoming-sessions",r==null?void 0:r.id],enabled:!!(r!=null&&r.id),queryFn:async()=>{const{data:l,error:o}=await q.from("coaching_sessions").select("id, scheduled_at, zoom_join_url, status, agenda").eq("assignment_id",r.id).gte("scheduled_at",new Date().toISOString()).neq("status","cancelled").order("scheduled_at",{ascending:!0}).limit(3);return o?[]:l||[]}}),i=j.useMemo(()=>{const l=(s||[]).map(c=>{const d=t==null?void 0:t.find(u=>u.event_id===c.id);return{id:`event-${c.id}`,title:c.title,subtitle:"LevelUp Event",date:new Date(c.event_date),kind:"event",live:_Ws(c.event_date),joinUrl:d?d.zoom_join_url||c.zoom_link:null,onClick:()=>n("/events")}}),o=(a||[]).map(c=>({id:`session-${c.id}`,title:"Coaching Session",subtitle:"Coaching",date:new Date(c.scheduled_at),kind:"coaching",joinUrl:c.zoom_join_url||null,onClick:()=>n("/coaching")}));return[...l,...o].sort((c,d)=>c.date.getTime()-d.date.getTime()).slice(0,5)},[s,t,a,n]);return e.jsxs("section",{className:"hub-card p-5",children:[e.jsxs("div",{className:"mb-4 flex items-center justify-between",children:[e.jsxs("h2",{className:"flex items-center gap-2 text-lg font-semibold text-foreground",children:[e.jsx("span",{className:"flex h-8 w-8 items-center justify-center rounded-full",style:{background:"hsl(var(--nav-events) / 0.14)"},children:e.jsx(Kc,{className:"h-4 w-4",style:{color:"hsl(var(--nav-events))"}})}),"Up Next"]}),e.jsxs($,{variant:"ghost",size:"sm",className:"gap-1",onClick:()=>n("/events"),children:["All ",e.jsx(Di,{className:"h-4 w-4"})]})]}),i.length===0?e.jsxs("div",{className:"rounded-xl border border-dashed border-border bg-muted/30 p-6 text-center",children:[e.jsx(Kc,{className:"mx-auto mb-2 h-7 w-7 text-muted-foreground/50"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Nothing scheduled yet."}),e.jsx($,{size:"sm",variant:"outline",className:"mt-3",onClick:()=>n("/events"),children:"Browse Events"})]}):e.jsx("ol",{className:"relative space-y-1",children:i.map(l=>e.jsx("li",{children:e.jsxs("button",{onClick:l.onClick,className:"group flex w-full items-start gap-3 rounded-xl p-2.5 text-left transition-colors hover:bg-muted/50",children:[e.jsx("span",{className:"mt-0.5 flex h-9 w-9 shrink-0 items-center justify-center rounded-lg",style:{background:l.kind==="coaching"?"hsl(var(--nav-academy) / 0.14)":"hsl(var(--nav-events) / 0.14)"},children:l.live?e.jsx(Nb,{className:"h-4 w-4 text-destructive"}):l.kind==="coaching"?e.jsx(of,{className:"h-4 w-4",style:{color:"hsl(var(--nav-academy))"}}):e.jsx(ua,{className:"h-4 w-4",style:{color:"hsl(var(--nav-events))"}})}),e.jsxs("span",{className:"min-w-0 flex-1",children:[e.jsx("span",{className:"block truncate text-sm font-medium text-foreground group-hover:text-primary",children:l.title}),e.jsxs("span",{className:"block text-xs text-muted-foreground",children:[l.live?"Live now":`${yKs(l.date)} · ${fse(l.date)}`," ·"," ",l.subtitle]})]}),l.joinUrl&&e.jsxs($,{size:"sm",variant:l.live?"destructive":"secondary",className:"h-7 shrink-0 gap-1 px-2 text-xs",onClick:o=>{o.stopPropagation(),window.open(l.joinUrl,"_blank")},children:[e.jsx(kr,{className:"h-3 w-3"})," Join"]})]})},l.id))})]})}const jbt=s=>s>=1e6?`$${(s/1e6).toFixed(1)}M`:s>=1e3?`$${Math.round(s/1e3)}K`:`$${s}`;function bKs(){const s=Qn(),{data:t,isLoading:n}=tt({queryKey:["hub-pipeline-snapshot"],queryFn:async()=>{const{data:r,error:a}=await q.from("deal_pipeline").select("id, expected_price, sale_price, stage:deal_pipeline_stages(id, name, color, is_won_stage, is_lost_stage)");if(a)throw a;const i=(r||[]).filter(u=>{var h,m;return!((h=u.stage)!=null&&h.is_won_stage)&&!((m=u.stage)!=null&&m.is_lost_stage)}),l=(r||[]).filter(u=>{var h;return(h=u.stage)==null?void 0:h.is_won_stage}),o=i.reduce((u,h)=>u+Number(h.expected_price||0),0),c=l.reduce((u,h)=>u+Number(h.sale_price||h.expected_price||0),0),d={};return i.forEach(u=>{var m,f,g;const h=((m=u.stage)==null?void 0:m.id)||"none";d[h]||(d[h]={name:((f=u.stage)==null?void 0:f.name)||"Unassigned",color:((g=u.stage)==null?void 0:g.color)||null,count:0}),d[h].count+=1}),{openCount:i.length,wonCount:l.length,volume:o,wonVolume:c,stages:Object.values(d).sort((u,h)=>h.count-u.count).slice(0,4)}}});return e.jsxs("section",{className:"hub-card flex flex-col p-5",children:[e.jsxs("div",{className:"mb-3 flex items-center justify-between",children:[e.jsxs("h3",{className:"flex items-center gap-2 text-base font-semibold text-foreground",children:[e.jsx("span",{className:"flex h-8 w-8 items-center justify-center rounded-full",style:{background:"hsl(var(--nav-listings) / 0.14)"},children:e.jsx(h2,{className:"h-4 w-4",style:{color:"hsl(var(--nav-listings))"}})}),"Pipeline"]}),e.jsxs($,{variant:"ghost",size:"sm",className:"gap-1",onClick:()=>s("/mission-control/pipeline"),children:["Open ",e.jsx(Di,{className:"h-4 w-4"})]})]}),n?e.jsxs("div",{className:"space-y-2",children:[e.jsx(yn,{className:"h-12 w-full"}),e.jsx(yn,{className:"h-16 w-full"})]}):!t||t.openCount+t.wonCount===0?e.jsxs("div",{className:"flex flex-1 flex-col items-center justify-center rounded-xl border border-dashed border-border bg-muted/30 p-5 text-center",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"No deals yet. Start tracking your buyers and sellers."}),e.jsx($,{size:"sm",variant:"outline",className:"mt-3",onClick:()=>s("/mission-control/pipeline"),children:"Create a Deal"})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"rounded-xl bg-muted/40 p-3",children:[e.jsx("p",{className:"text-2xl font-bold text-foreground",children:t.openCount}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Open deals"})]}),e.jsxs("div",{className:"rounded-xl bg-muted/40 p-3",children:[e.jsx("p",{className:"text-2xl font-bold text-foreground",children:jbt(t.volume)}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Pipeline volume"})]})]}),e.jsx("div",{className:"mt-4 space-y-2",children:t.stages.map(r=>e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"h-2 w-2 shrink-0 rounded-full",style:{background:r.color||"hsl(var(--primary))"}}),e.jsx("span",{className:"min-w-0 flex-1 truncate text-sm text-muted-foreground",children:r.name}),e.jsx("span",{className:"text-sm font-medium text-foreground",children:r.count})]},r.name))}),t.wonCount>0&&e.jsxs("p",{className:"mt-4 border-t border-border pt-3 text-xs text-muted-foreground",children:[e.jsx("span",{className:"font-semibold text-foreground",children:t.wonCount})," closed ·"," ",e.jsx("span",{className:"font-semibold text-foreground",children:jbt(t.wonVolume)})," volume"]})]})]})}function _Ks(){const s=Qn(),{user:t}=vs(),{hasFeature:n}=jC(),{data:r}=tt({queryKey:["hub-jump-back-in",t==null?void 0:t.id],enabled:!!(t!=null&&t.id),queryFn:async()=>{const i=[],l=q,o=async u=>{try{const h=await u();return(h==null?void 0:h.data)||[]}catch{return[]}},[c,d]=await Promise.all([o(()=>l.from("listing_presentations").select("id, title, updated_at").eq("owner_user_id",t.id).order("updated_at",{ascending:!1}).limit(2)),o(()=>l.from("listings").select("id, property_address, updated_at").eq("agent_id",t.id).order("updated_at",{ascending:!1}).limit(2))]);return c.forEach(u=>i.push({id:`preso-${u.id}`,label:u.title||"Listing Presentation",sub:"Presentation Studio",icon:jb,hue:"--nav-listings",to:`/apps/listing-presentation-studio/${u.id}`})),d.forEach(u=>i.push({id:`listing-${u.id}`,label:u.property_address||"Listing",sub:"My Listings",icon:va,hue:"--nav-websites",to:`/mission-control/listings/${u.id}`})),i.push({id:"marketing",label:"Create a post",sub:"Marketing Studio",icon:xm,hue:"--nav-marketing",to:"/marketing-studio"}),i.slice(0,8)}}),a=(r||[]).filter(i=>{const l=zOt(i.to);return!l||n(l)});return a.length<=1?null:e.jsxs("section",{className:"mb-8",children:[e.jsxs("div",{className:"mb-3 flex items-center gap-2",children:[e.jsx(da,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("h3",{className:"text-sm font-semibold uppercase tracking-wide text-muted-foreground",children:"Jump back in"})]}),e.jsx("div",{className:"hub-scroll flex gap-3 overflow-x-auto pb-1",children:a.map(i=>e.jsxs("button",{onClick:()=>s(i.to),className:"hub-card group flex w-[230px] shrink-0 items-center gap-3 p-3 text-left",children:[e.jsx("span",{className:"flex h-10 w-10 shrink-0 items-center justify-center rounded-xl",style:{background:`hsl(var(${i.hue}) / 0.14)`},children:e.jsx(i.icon,{className:"h-5 w-5",style:{color:`hsl(var(${i.hue}))`}})}),e.jsxs("span",{className:"min-w-0 flex-1",children:[e.jsx("span",{className:"block truncate text-sm font-medium text-foreground group-hover:text-primary",children:i.label}),e.jsx("span",{className:"block text-xs text-muted-foreground",children:i.sub})]}),e.jsx(ei,{className:"h-4 w-4 shrink-0 text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100"})]},i.id))})]})}function wKs({videos:s,kits:t,templates:n,services:r}){const a=Qn(),i=[{id:"videos",label:"Academy",icon:tf,hue:"--nav-academy",items:s,viewAll:"/academy",emptyText:"No new videos yet."},{id:"kits",label:"Resource Kits",icon:_b,hue:"--nav-apps",items:t,viewAll:"/toolbox",emptyText:"No resource kits yet."},{id:"templates",label:"Templates",icon:GI,hue:"--nav-marketing",items:n,viewAll:"/templates",emptyText:"No new templates yet.",fit:"contain"},{id:"services",label:"Services",icon:Nn,hue:"--nav-crm",items:r,viewAll:"/additional-services",emptyText:"No additional services yet."}],[l,o]=j.useState(i[0].id),c=i.find(d=>d.id===l)||i[0];return e.jsxs("section",{className:"mb-10",children:[e.jsxs("div",{className:"mb-4 flex flex-wrap items-center justify-between gap-3",children:[e.jsx("h3",{className:"text-lg font-semibold text-foreground",children:"Fresh for you"}),e.jsxs($,{variant:"ghost",size:"sm",className:"gap-1 text-muted-foreground hover:text-foreground",onClick:()=>a(c.viewAll),children:["View All ",e.jsx(ei,{className:"h-4 w-4"})]})]}),e.jsx("div",{className:"hub-scroll mb-4 flex gap-2 overflow-x-auto pb-1",children:i.map(d=>{const u=d.id===c.id;return e.jsxs("button",{onClick:()=>o(d.id),className:`flex shrink-0 items-center gap-2 rounded-full border px-3.5 py-1.5 text-sm font-medium transition-colors ${u?"border-transparent text-foreground":"border-border text-muted-foreground hover:text-foreground"}`,style:u?{background:`hsl(var(${d.hue}) / 0.14)`}:void 0,children:[e.jsx(d.icon,{className:"h-4 w-4",style:{color:`hsl(var(${d.hue}))`}}),d.label,d.items.length>0&&e.jsx("span",{className:"rounded-full bg-muted px-1.5 text-[11px] text-muted-foreground",children:d.items.length})]},d.id)})}),c.items.length===0?e.jsxs("div",{className:"rounded-2xl border border-dashed border-border bg-muted/30 p-8 text-center",children:[e.jsx(c.icon,{className:"mx-auto mb-2 h-7 w-7 text-muted-foreground/50"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:c.emptyText})]}):e.jsx("div",{className:"grid grid-cols-2 gap-4 md:grid-cols-4",children:c.items.map(d=>e.jsxs("button",{onClick:d.onOpen,className:"hub-card group overflow-hidden text-left",children:[e.jsxs("div",{className:"relative aspect-[3/2] overflow-hidden bg-muted/50",children:[d.image?e.jsx("img",{src:d.image,alt:d.title,loading:"lazy",className:`h-full w-full ${c.fit==="contain"?"object-contain":"object-cover"} transition-transform duration-300 group-hover:scale-105`}):e.jsx("div",{className:"flex h-full w-full items-center justify-center",children:e.jsx(c.icon,{className:"h-8 w-8 text-muted-foreground/40"})}),d.meta&&e.jsx("span",{className:"absolute bottom-2 right-2 rounded bg-foreground/75 px-1.5 py-0.5 text-xs text-background",children:d.meta})]}),e.jsx("div",{className:"p-3",children:e.jsx("h4",{className:"line-clamp-2 text-sm font-medium text-foreground group-hover:text-primary",children:d.title})})]},d.id))})]})}const jKs=()=>{var ne;const{user:s,isAdmin:t}=vs(),n=Qn(),{hasFeature:r}=jC(),[a,i]=j.useState([]),[l,o]=j.useState([]),[c,d]=j.useState([]),[u,h]=j.useState([]),[m,f]=j.useState([]),[g,x]=j.useState([]),[y,v]=j.useState(new Set),[b,w]=j.useState([]),[S,C]=j.useState([]),[E,I]=j.useState([]),[P,R]=j.useState(null),[D,O]=j.useState(!0);j.useEffect(()=>{U()},[s]);const U=async()=>{var te,J,ce,_e,he;try{const[ue,ve,Ee,Se,Le,Fe,ke,Ve,je,Ae,Ce]=await Promise.all([q.from("user_tags").select("tag").eq("user_id",s==null?void 0:s.id),q.from("app_tiles").select("*").order("name"),q.from("user_favorites").select("app_id").eq("user_id",s==null?void 0:s.id),q.from("events").select("*").order("event_date",{ascending:!0}),q.from("event_registrations").select("event_id, zoom_join_url").eq("user_id",s==null?void 0:s.id),q.from("canva_templates").select("id, name, preview_image_url, publish_date").order("publish_date",{ascending:!1}).limit(4),q.from("resource_kits").select("id, name, description, featured_image_url, publish_date").eq("is_published",!0).order("publish_date",{ascending:!1}).limit(4),q.from("academy_videos").select("id, title, description, thumbnail_url, duration, publish_date").eq("is_published",!0).order("publish_date",{ascending:!1}).limit(4),q.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),q.from("dashboard_banners").select("id, title, description, image_url, link_url, link_text, placement, section_after").eq("is_active",!0).order("sort_order"),q.from("profiles").select("name").eq("id",s==null?void 0:s.id).single()]);(te=Ce.data)!=null&&te.name&&R(Ce.data.name);const qe=((J=ue.data)==null?void 0:J.map(at=>at.tag))||[],ze=new Set(((ce=Ee.data)==null?void 0:ce.map(at=>at.app_id))||[]);v(ze);const ct=(((_e=ve.data)==null?void 0:_e.filter(at=>!at.required_tags||at.required_tags.length===0?!0:at.required_tags.some(Ke=>qe.includes(Ke))))||[]).sort((at,Ke)=>at.name==="LevelUp Members Portal"?-1:Ke.name==="LevelUp Members Portal"?1:0);i(ct.slice(0,6));const Xe=((he=Se.data)==null?void 0:he.filter(at=>m8(at.event_date)!=="ended"))||[];o(Xe.slice(0,4)),w(Le.data||[]),d(Fe.data||[]),h(ke.data||[]),f(Ve.data||[]),x(je.data||[]);const it=Ae.data||[];C(it.filter(at=>at.placement==="top")),I(it.filter(at=>at.placement==="between"))}catch(ue){console.error("Error loading dashboard:",ue),re.error("Failed to load dashboard data")}finally{O(!1)}},W=async te=>{var ce,_e,he;if(te.target_url.startsWith("/")){q.from("activity_logs").insert({user_id:s==null?void 0:s.id,app_id:te.app_id,app_name:te.name,user_agent:navigator.userAgent}).then(()=>{}),n(te.target_url);return}const J=window.open("about:blank","_blank");try{await q.from("activity_logs").insert({user_id:s==null?void 0:s.id,app_id:te.app_id,app_name:te.name,user_agent:navigator.userAgent});let{data:ue}=await q.auth.getSession();(ce=ue.session)!=null&&ce.access_token||(ue=(await q.auth.refreshSession()).data);const ve=(_e=ue==null?void 0:ue.session)==null?void 0:_e.access_token;if(!ve){J==null||J.close(),re.error("Your session expired — please sign in again to launch this app.");return}const{data:Ee,error:Se}=await q.functions.invoke("sso-launch",{body:{app_id:te.app_id},headers:{Authorization:`Bearer ${ve}`}});if(Se)throw Se;Ee!=null&&Ee.redirect_url?J&&!J.closed?(J.location.href=Ee.redirect_url,(he=J.focus)==null||he.call(J)):window.location.assign(Ee.redirect_url):(J==null||J.close(),re.error("Launch link unavailable"))}catch(ue){J==null||J.close(),console.error("Error launching app:",ue),re.error("Failed to launch app")}},V={"Newsletter Pro":"newsletter","Social AutoPilot":"social","Staging Studio":"marketing_studio",SigFlow:"marketing_studio","Agent Review":"marketing_studio",AgentReview:"marketing_studio"},G=a.filter(te=>{const J=V[te.name]||V[te.app_id];return!J||r(J)}),Y=te=>E.filter(J=>J.section_after===te),X=(P||((ne=s==null?void 0:s.user_metadata)==null?void 0:ne.name)||"there").split(" ")[0],ae=Date.now()+7*24*60*60*1e3,ie=l.filter(te=>new Date(te.event_date).getTime()<=ae).length;return e.jsxs(Vs,{title:"Dashboard",children:[r("learn")&&e.jsx(wWs,{events:l,registrations:b,onNavigateToEvents:()=>n("/events")}),e.jsx(gWs,{}),e.jsx(yWs,{}),e.jsx(vWs,{}),e.jsx(oKs,{name:X,eventsThisWeek:ie}),e.jsx(kWs,{}),e.jsxs("div",{className:"grid grid-cols-1 gap-4 mb-6 lg:grid-cols-3",children:[e.jsx("div",{className:"lg:col-span-2",children:e.jsx(gKs,{})}),r("learn")&&e.jsx(vKs,{events:l,registrations:b})]}),e.jsxs("div",{className:"grid grid-cols-1 gap-4 mb-8 lg:grid-cols-3",children:[e.jsx(iqt,{}),r("deals")&&e.jsx(bKs,{}),r("learn")&&e.jsx(VWs,{})]}),e.jsx(_Ks,{}),S.length>0&&e.jsx("div",{className:"mb-8",children:e.jsx(RZ,{banners:S})}),e.jsx(zWs,{}),D?e.jsx("div",{className:"mb-10 grid grid-cols-2 gap-4 md:grid-cols-4",children:[0,1,2,3].map(te=>e.jsx("div",{className:"h-44 rounded-2xl bg-muted/40 animate-pulse"},te))}):e.jsx(wKs,{videos:(r("learn")?m:[]).map(te=>({id:te.id,title:te.title,image:te.thumbnail_url,meta:te.duration,onOpen:()=>n(`/academy/${te.id}`)})),kits:(r("learn")?u:[]).map(te=>({id:te.id,title:te.name,image:te.featured_image_url,onOpen:()=>n(`/toolbox/${te.id}`)})),templates:(r("marketing_studio")?c:[]).map(te=>({id:te.id,title:te.name,image:te.preview_image_url,onOpen:()=>n("/templates")})),services:g.map(te=>({id:te.id,title:te.name,image:te.preview_image_url,onOpen:()=>window.open(te.signup_link_url,"_blank")}))}),Y("academy").length>0&&e.jsx("div",{className:"mb-10",children:e.jsx(RZ,{banners:Y("academy")})}),r("listing_exchange")&&e.jsx("div",{className:"mb-10",children:e.jsx(qWs,{})}),G.length>0&&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:"Your Apps"}),e.jsxs($,{variant:"ghost",size:"sm",onClick:()=>n("/apps"),className:"gap-1 text-muted-foreground hover:text-foreground",children:["View All ",e.jsx(ei,{className:"h-4 w-4"})]})]}),G.length===0?e.jsx(Ne,{className:"bg-muted/30 border-dashed",children:e.jsx(Ie,{className:"flex items-center justify-center py-12",children:e.jsxs("div",{className:"text-center",children:[e.jsx(M0,{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:G.map(te=>{const J=y.has(te.id);return e.jsxs("div",{onClick:()=>W(te),className:"hub-card group flex items-start gap-4 p-5 cursor-pointer",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:te.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:te.name}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1 line-clamp-2",children:te.description})]}),J&&e.jsx(M0,{className:"h-5 w-5 text-primary fill-current flex-shrink-0"})]},te.id)})})]}),Y("templates").length>0&&e.jsx("div",{className:"mb-10",children:e.jsx(RZ,{banners:Y("templates")})}),Y("events").length>0&&e.jsx("div",{className:"mb-10",children:e.jsx(RZ,{banners:Y("events")})}),Y("toolbox").length>0&&e.jsx("div",{className:"mb-10",children:e.jsx(RZ,{banners:Y("toolbox")})})]})},NKs=[{key:"contacts",label:"Contacts",icon:Da,description:"View, add, and edit contacts"},{key:"pipeline",label:"Deal Pipeline",icon:YI,description:"View, add, and move deals"},{key:"client_portal",label:"Client Portals",icon:_b,description:"Manage client portals on deals"},{key:"videos",label:"Videos",icon:ua,description:"View and upload videos"},{key:"listings",label:"Listings",icon:va,description:"View, create, and edit listings"},{key:"scorecard",label:"Scorecard",icon:zg,description:"View and add transactions"},{key:"popbys",label:"Pop-bys",icon:ci,description:"View and log pop-bys"},{key:"digital_card",label:"Digital Card",icon:Cv,description:"Create and edit digital business card"},{key:"guest_book",label:"Guest Book",icon:Xf,description:"Manage open house guest books"},{key:"presentations",label:"Presentations",icon:jb,description:"Create and manage smart presentations"}];function kKs(){var I;const{user:s}=vs(),[t,n]=j.useState([]),[r,a]=j.useState(!0),[i,l]=j.useState(!1),[o,c]=j.useState(!1),[d,u]=j.useState(null),[h,m]=j.useState({email:"",name:"",password:""}),[f,g]=j.useState("create"),[x,y]=j.useState(!1),[v,b]=j.useState(null);j.useEffect(()=>{s&&w()},[s]);const w=async()=>{if(s){a(!0);try{const{data:P,error:R}=await q.from("agent_assistant_assignments").select("id, assistant_id, permissions, created_at").eq("agent_id",s.id);if(R)throw R;if(P&&P.length>0){const D=P.map(W=>W.assistant_id),{data:O}=await q.from("profiles").select("id, name, email").in("id",D),U=P.map(W=>{const V=O==null?void 0:O.find(G=>G.id===W.assistant_id);return{...W,permissions:W.permissions,assistant_profile:V?{name:V.name||"",email:V.email||""}:void 0}});n(U)}else n([])}catch(P){console.error("Error loading assistants:",P)}finally{a(!1)}}},S=async()=>{if(s){if(f==="link"){if(!h.email.trim()){re.error("Please enter the assistant's email");return}y(!0);try{const{data:{session:P}}=await q.auth.getSession();if(!P)throw new Error("Not authenticated");const{data:R,error:D}=await q.from("profiles").select("id, name, email").eq("email",h.email.trim().toLowerCase()).single();if(D||!R){re.error("No account found with that email. Try creating a new assistant instead.");return}const{data:O}=await q.from("agent_assistant_assignments").select("id").eq("agent_id",s.id).eq("assistant_id",R.id);if(O&&O.length>0){re.error("This assistant is already assigned to you");return}const U=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/manage-user-roles",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${P.access_token}`},body:JSON.stringify({userId:R.id,role:"assistant",action:"add",agentId:s.id})}),W=await U.json();if(!U.ok)throw new Error(W.error||"Failed to assign assistant role");const{error:V}=await q.from("agent_assistant_assignments").insert({agent_id:s.id,assistant_id:R.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(V)throw V;re.success(`${R.name||R.email} linked as your assistant`),l(!1),m({email:"",name:"",password:""}),w()}catch(P){console.error("Error linking assistant:",P),re.error(P.message||"Failed to link assistant")}finally{y(!1)}return}if(!h.email.trim()||!h.name.trim()||!h.password.trim()){re.error("Please fill in all fields");return}if(h.password.length<6){re.error("Password must be at least 6 characters");return}y(!0);try{const{data:{session:P}}=await q.auth.getSession();if(!P)throw new Error("Not authenticated");const R=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/create-user",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${P.access_token}`},body:JSON.stringify({email:h.email.trim(),password:h.password,name:h.name.trim(),purpose:"assistant"})}),D=await R.json();if(!R.ok)throw new Error(D.error||"Failed to create assistant account");const O=D.userId||D.id;if(!O)throw new Error("No user ID returned");const U=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/manage-user-roles",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${P.access_token}`},body:JSON.stringify({userId:O,role:"assistant",action:"add",agentId:s.id})}),W=await U.json();if(!U.ok)throw new Error(W.error||"Failed to assign assistant role");const{error:V}=await q.from("agent_assistant_assignments").insert({agent_id:s.id,assistant_id:O,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(V)throw V;re.success(`Assistant account created for ${h.name.trim()}`),l(!1),m({email:"",name:"",password:""}),w()}catch(P){console.error("Error adding assistant:",P),re.error(P.message||"Failed to add assistant")}finally{y(!1)}}},C=async()=>{if(!(!d||!s))try{const{data:{session:P}}=await q.auth.getSession();if(!P)throw new Error("Not authenticated");const{error:R}=await q.from("agent_assistant_assignments").delete().eq("id",d.id);if(R)throw R;const{data:D}=await q.from("agent_assistant_assignments").select("id").eq("assistant_id",d.assistant_id);(!D||D.length===0)&&await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/manage-user-roles",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${P.access_token}`},body:JSON.stringify({userId:d.assistant_id,role:"assistant",action:"remove"})}),re.success("Assistant removed"),c(!1),u(null),w()}catch(P){console.error("Error removing assistant:",P),re.error(P.message||"Failed to remove assistant")}},E=async(P,R,D)=>{b(P);try{const O=t.find(V=>V.id===P);if(!O)return;const U={...O.permissions,[R]:D},{error:W}=await q.from("agent_assistant_assignments").update({permissions:U}).eq("id",P);if(W)throw W;n(V=>V.map(G=>G.id===P?{...G,permissions:U}:G))}catch(O){console.error("Error updating permissions:",O),re.error("Failed to update permissions")}finally{b(null)}};return r?e.jsxs(Ne,{children:[e.jsx(Ct,{children:e.jsxs(At,{className:"flex items-center gap-2",children:[e.jsx(Zn,{className:"h-5 w-5"}),"My Assistants"]})}),e.jsx(Ie,{children:e.jsx("div",{className:"flex items-center justify-center py-4",children:e.jsx(kt,{className:"h-6 w-6 animate-spin text-muted-foreground"})})})]}):e.jsxs(e.Fragment,{children:[e.jsxs(Ne,{children:[e.jsx(Ct,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs(At,{className:"flex items-center gap-2",children:[e.jsx(Zn,{className:"h-5 w-5"}),"My Assistants"]}),e.jsx(Gn,{children:"Add assistants to help manage your Agent OS"})]}),e.jsxs($,{size:"sm",onClick:()=>{g("create"),l(!0)},children:[e.jsx(dn,{className:"h-4 w-4 mr-1"}),"Add Assistant"]})]})}),e.jsx(Ie,{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(P=>{var R,D,O,U;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(Oa,{className:"h-10 w-10",children:e.jsx(za,{children:((D=(R=P.assistant_profile)==null?void 0:R.name)==null?void 0:D.split(" ").map(W=>W[0]).join("").toUpperCase())||"A"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:((O=P.assistant_profile)==null?void 0:O.name)||"Unknown"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:((U=P.assistant_profile)==null?void 0:U.email)||""})]}),e.jsxs(Be,{variant:"secondary",className:"ml-2",children:[e.jsx(Mf,{className:"h-3 w-3 mr-1"}),"Assistant"]})]}),e.jsx($,{variant:"ghost",size:"sm",className:"text-destructive hover:text-destructive",onClick:()=>{u(P),c(!0)},children:e.jsx(Wn,{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:NKs.map(W=>{const V=W.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(V,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",children:W.label}),e.jsx("p",{className:"text-xs text-muted-foreground",children:W.description})]})]}),e.jsx(Sn,{checked:P.permissions[W.key]||!1,onCheckedChange:G=>E(P.id,W.key,G),disabled:v===P.id})]},W.key)})})]})]},P.id)})})})]}),e.jsx(zs,{open:i,onOpenChange:l,children:e.jsxs(Os,{children:[e.jsxs(Us,{children:[e.jsx(Bs,{children:"Add Assistant"}),e.jsx(Ir,{children:f==="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($,{variant:f==="create"?"default":"outline",size:"sm",onClick:()=>g("create"),children:[e.jsx(dn,{className:"h-3 w-3 mr-1"}),"Create New"]}),e.jsxs($,{variant:f==="link"?"default":"outline",size:"sm",onClick:()=>g("link"),children:[e.jsx(Ad,{className:"h-3 w-3 mr-1"}),"Link Existing"]})]}),e.jsxs("div",{className:"space-y-4 py-2",children:[f==="create"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"assistant-name",children:"Name"}),e.jsx(pe,{id:"assistant-name",value:h.name,onChange:P=>m({...h,name:P.target.value}),placeholder:"Assistant's full name"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"assistant-email",children:"Email"}),e.jsx(pe,{id:"assistant-email",type:"email",value:h.email,onChange:P=>m({...h,email:P.target.value}),placeholder:"assistant@email.com"})]}),f==="create"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"assistant-password",children:"Temporary Password"}),e.jsx(pe,{id:"assistant-password",type:"password",value:h.password,onChange:P=>m({...h,password:P.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(Ar,{children:[e.jsx($,{variant:"outline",onClick:()=>l(!1),children:"Cancel"}),e.jsxs($,{onClick:S,disabled:x,children:[x&&e.jsx(kt,{className:"h-4 w-4 mr-2 animate-spin"}),f==="create"?"Create Assistant":"Link Assistant"]})]})]})}),e.jsx(kc,{open:o,onOpenChange:c,children:e.jsxs(cc,{children:[e.jsxs(dc,{children:[e.jsx(hc,{children:"Remove Assistant?"}),e.jsxs(mc,{children:["This will remove ",(I=d==null?void 0:d.assistant_profile)==null?void 0:I.name,"'s access to your Agent OS. Their account will remain active but they won't be able to manage your data."]})]}),e.jsxs(uc,{children:[e.jsx(fc,{children:"Cancel"}),e.jsx(tc,{onClick:C,className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Remove"})]})]})})]})}function rb(s){this.content=s}rb.prototype={constructor:rb,find:function(s){for(var t=0;t>1}};rb.from=function(s){if(s instanceof rb)return s;var t=[];if(s)for(var n in s)t.push(n,s[n]);return new rb(t)};function oqt(s,t,n){for(let r=0;;r++){if(r==s.childCount||r==t.childCount)return s.childCount==t.childCount?null:n;let a=s.child(r),i=t.child(r);if(a==i){n+=a.nodeSize;continue}if(!a.sameMarkup(i))return n;if(a.isText&&a.text!=i.text){let l=a.text,o=i.text,c=0;for(;l[c]==o[c];c++)n++;return c&&c0&&m>0&&d[h-1]==u[m-1];)h--,m--,n--,r--;return h&&m&&h=56320&&s<57344}function dqt(s){return s>=55296&&s<56320}let hi=class t_{constructor(t,n){if(this.content=t,this.size=n||0,n==null)for(let r=0;rt&&r(c,a+o,i||null,l)!==!1&&c.content.size){let u=o+1;c.nodesBetween(Math.max(0,t-u),Math.min(c.content.size,n-u),r,a+u)}o=d}}descendants(t){this.nodesBetween(0,this.size,t)}textBetween(t,n,r,a){let i="",l=!0;return this.nodesBetween(t,n,(o,c)=>{let d=o.isText?o.text.slice(Math.max(t,c)-c,n-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)&&r&&(l?l=!1:i+=r),i+=d},0),i}append(t){if(!t.size)return this;if(!this.size)return t;let n=this.lastChild,r=t.firstChild,a=this.content.slice(),i=0;for(n.isText&&n.sameMarkup(r)&&(a[a.length-1]=n.withText(n.text+r.text),i=1);it)for(let i=0,l=0;lt&&((ln)&&(o.isText?o=o.cut(Math.max(0,t-l),Math.min(o.text.length,n-l)):o=o.cut(Math.max(0,t-l-1),Math.min(o.content.size,n-l-1))),r.push(o),a+=o.nodeSize),l=c}return new t_(r,a)}cutByIndex(t,n){return t==n?t_.empty:t==0&&n==this.content.length?this:new t_(this.content.slice(t,n))}replaceChild(t,n){let r=this.content[t];if(r==n)return this;let a=this.content.slice(),i=this.size+n.nodeSize-r.nodeSize;return a[t]=n,new t_(a,i)}addToStart(t){return new t_([t].concat(this.content),this.size+t.nodeSize)}addToEnd(t){return new t_(this.content.concat(t),this.size+t.nodeSize)}eq(t){if(this.content.length!=t.content.length)return!1;for(let n=0;nthis.size||t<0)throw new RangeError(`Position ${t} outside of fragment (${this})`);for(let n=0,r=0;;n++){let a=this.child(n),i=r+a.nodeSize;if(i>=t)return i==t?lde(n+1,i):lde(n,r);r=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,n){if(!n)return t_.empty;if(!Array.isArray(n))throw new RangeError("Invalid input for Fragment.fromJSON");return t_.fromArray(n.map(t.nodeFromJSON))}static fromArray(t){if(!t.length)return t_.empty;let n,r=0;for(let a=0;athis.type.rank&&(n||(n=t.slice(0,a)),n.push(this),r=!0),n&&n.push(i)}}return n||(n=t.slice()),r||n.push(this),n}removeFromSet(t){for(let n=0;nr.type.rank-a.type.rank),n}};kf.none=[];class pse extends Error{}class Ki{constructor(t,n,r){this.content=t,this.openStart=n,this.openEnd=r}get size(){return this.content.size-this.openStart-this.openEnd}insertAt(t,n){let r=hqt(this.content,t+this.openStart,n,this.openStart+1,this.openEnd+1);return r&&new Ki(r,this.openStart,this.openEnd)}removeBetween(t,n){return new Ki(uqt(this.content,t+this.openStart,n+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,n){if(!n)return Ki.empty;let r=n.openStart||0,a=n.openEnd||0;if(typeof r!="number"||typeof a!="number")throw new RangeError("Invalid input for Slice.fromJSON");return new Ki(hi.fromJSON(t,n.content),r,a)}static maxOpen(t,n=!0){let r=0,a=0;for(let i=t.firstChild;i&&!i.isLeaf&&(n||!i.type.spec.isolating);i=i.firstChild)r++;for(let i=t.lastChild;i&&!i.isLeaf&&(n||!i.type.spec.isolating);i=i.lastChild)a++;return new Ki(t,r,a)}}Ki.empty=new Ki(hi.empty,0,0);function uqt(s,t,n){let{index:r,offset:a}=s.findIndex(t),i=s.maybeChild(r),{index:l,offset:o}=s.findIndex(n);if(a==t||i.isText){if(o!=n&&!s.child(l).isText)throw new RangeError("Removing non-flat range");return s.cut(0,t).append(s.cut(n))}if(r!=l)throw new RangeError("Removing non-flat range");return s.replaceChild(r,i.copy(uqt(i.content,t-a-1,n-a-1)))}function hqt(s,t,n,r,a,i){let{index:l,offset:o}=s.findIndex(t),c=s.maybeChild(l);if(o==t||c.isText)return i&&r<=0&&a<=0&&!i.canReplace(l,l,n)?null:s.cut(0,t).append(n).append(s.cut(t));let d=hqt(c.content,t-o-1,n,l==0?r-1:0,l==s.childCount-1?a-1:0,c);return d&&s.replaceChild(l,c.copy(d))}function SKs(s,t,n){if(n.openStart>s.depth)throw new pse("Inserted content deeper than insertion position");if(s.depth-n.openStart!=t.depth-n.openEnd)throw new pse("Inconsistent open depths");return mqt(s,t,n,0)}function mqt(s,t,n,r){let a=s.index(r),i=s.node(r);if(a==t.index(r)&&r=0&&s.isText&&s.sameMarkup(t[n])?t[n]=s.withText(t[n].text+s.text):t.push(s)}function Tee(s,t,n,r){let a=(t||s).node(n),i=0,l=t?t.index(n):a.childCount;s&&(i=s.index(n),s.depth>n?i++:s.textOffset&&(m7(s.nodeAfter,r),i++));for(let o=i;oa&&ZGe(s,t,a+1),l=r.depth>a&&ZGe(n,r,a+1),o=[];return Tee(null,s,a,o),i&&l&&t.index(a)==n.index(a)?(fqt(i,l),m7(f7(i,pqt(s,t,n,r,a+1)),o)):(i&&m7(f7(i,tTe(s,t,a+1)),o),Tee(t,n,a,o),l&&m7(f7(l,tTe(n,r,a+1)),o)),Tee(r,null,a,o),new hi(o)}function tTe(s,t,n){let r=[];if(Tee(null,s,n,r),s.depth>n){let a=ZGe(s,t,n+1);m7(f7(a,tTe(s,t,n+1)),r)}return Tee(t,null,n,r),new hi(r)}function CKs(s,t){let n=t.depth-s.openStart,a=t.node(n).copy(s.content);for(let i=n-1;i>=0;i--)a=t.node(i).copy(hi.from(a));return{start:a.resolveNoCache(s.openStart+n),end:a.resolveNoCache(a.content.size-s.openEnd-n)}}class gse{constructor(t,n,r){this.pos=t,this.path=n,this.parentOffset=r,this.depth=n.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,n=this.index(this.depth);if(n==t.childCount)return null;let r=this.pos-this.path[this.path.length-1],a=t.child(n);return r?t.child(n).cut(r):a}get nodeBefore(){let t=this.index(this.depth),n=this.pos-this.path[this.path.length-1];return n?this.parent.child(t).cut(0,n):t==0?null:this.parent.child(t-1)}posAtIndex(t,n){n=this.resolveDepth(n);let r=this.path[n*3],a=n==0?0:this.path[n*3-1]+1;for(let i=0;i0;n--)if(this.start(n)<=t&&this.end(n)>=t)return n;return 0}blockRange(t=this,n){if(t.pos=0;r--)if(t.pos<=this.end(r)&&(!n||n(this.node(r))))return new sTe(this,t,r);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&&n<=t.content.size))throw new RangeError("Position "+n+" out of range");let r=[],a=0,i=n;for(let l=t;;){let{index:o,offset:c}=l.content.findIndex(i),d=i-c;if(r.push(l,o,a+c),!d||(l=l.child(o),l.isText))break;i=d-1,a+=c+1}return new gse(n,r,i)}static resolveCached(t,n){let r=Nbt.get(t);if(r)for(let i=0;it&&this.nodesBetween(t,n,i=>(r.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()+")"),gqt(this.marks,t)}contentMatchAt(t){let n=this.type.contentMatch.matchFragment(this.content,0,t);if(!n)throw new Error("Called contentMatchAt on a node with invalid content");return n}canReplace(t,n,r=hi.empty,a=0,i=r.childCount){let l=this.contentMatchAt(t).matchFragment(r,a,i),o=l&&l.matchFragment(this.content,n);if(!o||!o.validEnd)return!1;for(let c=a;cn.type.name)}`);this.content.forEach(n=>n.check())}toJSON(){let t={type:this.type.name};for(let n 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(n=>n.toJSON())),t}static fromJSON(t,n){if(!n)throw new RangeError("Invalid input for Node.fromJSON");let r;if(n.marks){if(!Array.isArray(n.marks))throw new RangeError("Invalid mark data for Node.fromJSON");r=n.marks.map(t.markFromJSON)}if(n.type=="text"){if(typeof n.text!="string")throw new RangeError("Invalid text node in JSON");return t.text(n.text,r)}let a=hi.fromJSON(t,n.content);return t.nodeType(n.type).create(n.attrs,a,r)}};oL.prototype.text=void 0;class nTe extends oL{constructor(t,n,r,a){if(super(t,n,null,a),!r)throw new RangeError("Empty text nodes are not allowed");this.text=r}toString(){return this.type.spec.toDebugString?this.type.spec.toDebugString(this):gqt(this.marks,JSON.stringify(this.text))}get textContent(){return this.text}textBetween(t,n){return this.text.slice(t,n)}get nodeSize(){return this.text.length}mark(t){return t==this.marks?this:new nTe(this.type,this.attrs,this.text,t)}withText(t){return t==this.text?this:new nTe(this.type,this.attrs,t,this.marks)}cut(t=0,n=this.text.length){return t==0&&n==this.text.length?this:this.withText(this.text.slice(t,n))}eq(t){return this.sameMarkup(t)&&this.text==t.text}toJSON(){let t=super.toJSON();return t.text=this.text,t}}function gqt(s,t){for(let n=s.length-1;n>=0;n--)t=s[n].type.name+"("+t+")";return t}function kbt(s,t,n,r){for(let a in t)if(!(a in s))throw new RangeError(`Unsupported attribute ${a} for ${n} of type ${r}`);for(let a in s)s[a].validate&&s[a].validate(t[a])}class Z7{constructor(t){this.validEnd=t,this.next=[],this.wrapCache=[]}static parse(t,n){let r=new MKs(t,n);if(r.next==null)return Z7.empty;let a=xqt(r);r.next&&r.err("Unexpected trailing text");let i=OKs(FKs(a));return zKs(i,r),i}matchType(t){for(let n=0;nd.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 n(r){t.push(r);for(let a=0;a{let i=a+(r.validEnd?"*":" ")+" ";for(let l=0;l"+t.indexOf(r.next[l].next);return i}).join(` `)}}Z7.empty=new Z7(!0);class MKs{constructor(t,n){this.string=t,this.nodeTypes=n,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 xqt(s){let t=[];do t.push(PKs(s));while(s.eat("|"));return t.length==1?t[0]:{type:"choice",exprs:t}}function PKs(s){let t=[];do t.push(IKs(s));while(s.next&&s.next!=")"&&s.next!="|");return t.length==1?t[0]:{type:"seq",exprs:t}}function IKs(s){let t=DKs(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=LKs(s,t);else break;return t}function Sbt(s){/\D/.test(s.next)&&s.err("Expected number, got '"+s.next+"'");let t=Number(s.next);return s.pos++,t}function LKs(s,t){let n=Sbt(s),r=n;return s.eat(",")&&(s.next!="}"?r=Sbt(s):r=-1),s.eat("}")||s.err("Unclosed braced range"),{type:"range",min:n,max:r,expr:t}}function RKs(s,t){let n=s.nodeTypes,r=n[t];if(r)return[r];let a=[];for(let i in n){let l=n[i];l.isInGroup(t)&&a.push(l)}return a.length==0&&s.err("No node type or group '"+t+"' found"),a}function DKs(s){if(s.eat("(")){let t=xqt(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=RKs(s,s.next).map(n=>(s.inline==null?s.inline=n.isInline:s.inline!=n.isInline&&s.err("Mixing inline and block content"),{type:"name",value:n}));return s.pos++,t.length==1?t[0]:{type:"choice",exprs:t}}}function FKs(s){let t=[[]];return a(i(s,0),n()),t;function n(){return t.push([])-1}function r(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=n())}else if(l.type=="star"){let c=n();return r(o,c),a(i(l.expr,c),c),[r(c)]}else if(l.type=="plus"){let c=n();return a(i(l.expr,o),c),a(i(l.expr,c),c),[r(c)]}else{if(l.type=="opt")return[r(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 u=0;u{d||a.push([o,d=[]]),d.indexOf(u)==-1&&d.push(u)})})});let i=t[r.join(",")]=new Z7(r.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:bqt(this.attrs,t)}create(t=null,n,r){if(this.isText)throw new Error("NodeType.create can't construct text nodes");return new oL(this,this.computeAttrs(t),hi.from(n),kf.setFrom(r))}createChecked(t=null,n,r){return n=hi.from(n),this.checkContent(n),new oL(this,this.computeAttrs(t),n,kf.setFrom(r))}createAndFill(t=null,n,r){if(t=this.computeAttrs(t),n=hi.from(n),n.size){let l=this.contentMatch.fillBefore(n);if(!l)return null;n=l.append(n)}let a=this.contentMatch.matchFragment(n),i=a&&a.fillBefore(hi.empty,!0);return i?new oL(this,t,n.append(i),kf.setFrom(r)):null}validContent(t){let n=this.contentMatch.matchFragment(t);if(!n||!n.validEnd)return!1;for(let r=0;r-1}allowsMarks(t){if(this.markSet==null)return!0;for(let n=0;nr[i]=new wqt(i,n,l));let a=n.spec.topNode||"doc";if(!r[a])throw new RangeError("Schema is missing its top node type ('"+a+"')");if(!r.text)throw new RangeError("Every schema needs a 'text' type");for(let i in r.text.attrs)throw new RangeError("The text node type should not have attributes");return r}};function BKs(s,t,n){let r=n.split("|");return a=>{let i=a===null?"null":typeof a;if(r.indexOf(i)<0)throw new RangeError(`Expected value of type ${r} for attribute ${t} on type ${s}, got ${i}`)}}class $Ks{constructor(t,n,r){this.hasDefault=Object.prototype.hasOwnProperty.call(r,"default"),this.default=r.default,this.validate=typeof r.validate=="string"?BKs(t,n,r.validate):r.validate}get isRequired(){return!this.hasDefault}}class P6e{constructor(t,n,r,a){this.name=t,this.rank=n,this.schema=r,this.spec=a,this.attrs=_qt(t,a.attrs),this.excluded=null;let i=vqt(this.attrs);this.instance=i?new kf(this,i):null}create(t=null){return!t&&this.instance?this.instance:new kf(this,bqt(this.attrs,t))}static compile(t,n){let r=Object.create(null),a=0;return t.forEach((i,l)=>r[i]=new P6e(i,a++,n,l)),r}removeFromSet(t){for(var n=0;n-1}}let jqt=class{constructor(t){this.linebreakReplacement=null,this.cached=Object.create(null);let n=this.spec={};for(let a in t)n[a]=t[a];n.nodes=rb.from(t.nodes),n.marks=rb.from(t.marks||{}),this.nodes=Abt.compile(this.spec.nodes,this),this.marks=P6e.compile(this.spec.marks,this);let r=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=r[l]||(r[l]=Z7.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?Ebt(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==""?[]:Ebt(this,l.split(" "))}this.nodeFromJSON=a=>oL.fromJSON(this,a),this.markFromJSON=a=>kf.fromJSON(this,a),this.topNodeType=this.nodes[this.spec.topNode||"doc"],this.cached.wrappings=Object.create(null)}node(t,n=null,r,a){if(typeof t=="string")t=this.nodeType(t);else if(t instanceof Abt){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(n,r,a)}text(t,n){let r=this.nodes.text;return new nTe(r,r.defaultAttrs,t,kf.setFrom(n))}mark(t,n){return typeof t=="string"&&(t=this.marks[t]),t.create(n)}nodeType(t){let n=this.nodes[t];if(!n)throw new RangeError("Unknown node type: "+t);return n}};function Ebt(s,t){let n=[];for(let r=0;r-1)&&n.push(l=c)}if(!l)throw new SyntaxError("Unknown mark type: '"+t[r]+"'")}return n}function UKs(s){return s.tag!=null}function qKs(s){return s.style!=null}let Mee=class QGe{constructor(t,n){this.schema=t,this.rules=n,this.tags=[],this.styles=[];let r=this.matchedStyles=[];n.forEach(a=>{if(UKs(a))this.tags.push(a);else if(qKs(a)){let i=/[^=]*/.exec(a.style)[0];r.indexOf(i)<0&&r.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,n={}){let r=new Mbt(this,n,!1);return r.addAll(t,kf.none,n.from,n.to),r.finish()}parseSlice(t,n={}){let r=new Mbt(this,n,!0);return r.addAll(t,kf.none,n.from,n.to),Ki.maxOpen(r.finish())}matchTag(t,n,r){for(let a=r?this.tags.indexOf(r)+1:0;at.length&&(o.charCodeAt(t.length)!=61||o.slice(t.length+1)!=n))){if(l.getAttrs){let c=l.getAttrs(n);if(c===!1)continue;l.attrs=c||void 0}return l}}}static schemaRules(t){let n=[];function r(a){let i=a.priority==null?50:a.priority,l=0;for(;l{r(l=Pbt(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=>{r(l=Pbt(l)),l.node||l.ignore||l.mark||(l.node=a)})}return n}static fromSchema(t){return t.cached.domParser||(t.cached.domParser=new QGe(t,QGe.schemaRules(t)))}};const Nqt={address:!0,article:!0,aside:!0,blockquote:!0,body:!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},VKs={head:!0,noscript:!0,object:!0,script:!0,style:!0,title:!0},kqt={ol:!0,ul:!0},xse=1,JGe=2,Pee=4;function Tbt(s,t,n){return t!=null?(t?xse:0)|(t==="full"?JGe:0):s&&s.whitespace=="pre"?xse|JGe:n&~Pee}class cde{constructor(t,n,r,a,i,l){this.type=t,this.attrs=n,this.marks=r,this.solid=a,this.options=l,this.content=[],this.activeMarks=kf.none,this.match=i||(l&Pee?null:t.contentMatch)}findWrapping(t){if(!this.match){if(!this.type)return[];let n=this.type.contentMatch.fillBefore(hi.from(t));if(n)this.match=this.type.contentMatch.matchFragment(n);else{let r=this.type.contentMatch,a;return(a=r.findWrapping(t.type))?(this.match=r,a):null}}return this.match.findWrapping(t.type)}finish(t){if(!(this.options&xse)){let r=this.content[this.content.length-1],a;if(r&&r.isText&&(a=/[ \t\r\n\u000c]+$/.exec(r.text))){let i=r;r.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 n=hi.from(this.content);return!t&&this.match&&(n=n.append(this.match.fillBefore(hi.empty,!0))),this.type?this.type.create(this.attrs,n,this.marks):n}inlineContext(t){return this.type?this.type.inlineContent:this.content.length?this.content[0].isInline:t.parentNode&&!Nqt.hasOwnProperty(t.parentNode.nodeName.toLowerCase())}}class Mbt{constructor(t,n,r){this.parser=t,this.options=n,this.isOpen=r,this.open=0,this.localPreserveWS=!1;let a=n.topNode,i,l=Tbt(null,n.preserveWhitespace,0)|(r?Pee:0);a?i=new cde(a.type,a.attrs,kf.none,!0,n.topMatch||a.type.contentMatch,l):r?i=new cde(null,null,kf.none,!0,null,l):i=new cde(t.schema.topNodeType,null,kf.none,!0,null,l),this.nodes=[i],this.find=n.findPositions,this.needsBlock=!1}get top(){return this.nodes[this.open]}addDOM(t,n){t.nodeType==3?this.addTextNode(t,n):t.nodeType==1&&this.addElement(t,n)}addTextNode(t,n){let r=t.nodeValue,a=this.top,i=a.options&JGe?"full":this.localPreserveWS||(a.options&xse)>0,{schema:l}=this.parser;if(i==="full"||a.inlineContext(t)||/[^ \t\r\n\u000c]/.test(r)){if(i)if(i==="full")r=r.replace(/\r\n?/g,` `);else if(l.linebreakReplacement&&/[\r\n]/.test(r)&&this.top.findWrapping(l.linebreakReplacement.create())){let o=r.split(/\r?\n|\r/);for(let c=0;c!c.clearMark(d)):n=n.concat(this.parser.schema.marks[c.mark].create(c.attrs)),c.consuming===!1)o=c;else break}}return n}addElementByRule(t,n,r,a){let i,l;if(n.node)if(l=this.parser.schema.nodes[n.node],l.isLeaf)this.insertNode(l.create(n.attrs),r,t.nodeName=="BR")||this.leafFallback(t,r);else{let c=this.enter(l,n.attrs||null,r,n.preserveWhitespace);c&&(i=!0,r=c)}else{let c=this.parser.schema.marks[n.mark];r=r.concat(c.create(n.attrs))}let o=this.top;if(l&&l.isLeaf)this.findInside(t);else if(a)this.addElement(t,r,a);else if(n.getContent)this.findInside(t),n.getContent(t,this.parser.schema).forEach(c=>this.insertNode(c,r,!1));else{let c=t;typeof n.contentElement=="string"?c=t.querySelector(n.contentElement):typeof n.contentElement=="function"?c=n.contentElement(t):n.contentElement&&(c=n.contentElement),this.findAround(t,c,!0),this.addAll(c,r),this.findAround(t,c,!1)}i&&this.sync(o)&&this.open--}addAll(t,n,r,a){let i=r||0;for(let l=r?t.childNodes[r]:t.firstChild,o=a==null?null:t.childNodes[a];l!=o;l=l.nextSibling,++i)this.findAtPoint(t,i),this.addDOM(l,n);this.findAtPoint(t,i)}findPlace(t,n,r){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(r)break;o+=2}}if(!a)return null;this.sync(i);for(let l=0;l(l.type?l.type.allowsMarkType(d.type):Ibt(d.type,t))?(c=d.addToSet(c),!1):!0),this.nodes.push(new cde(t,n,c,a,null,o)),this.open++,r}closeExtra(t=!1){let n=this.nodes.length-1;if(n>this.open){for(;n>this.open;n--)this.nodes[n-1].content.push(this.nodes[n].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 n=this.open;n>=0;n--){if(this.nodes[n]==t)return this.open=n,!0;this.localPreserveWS&&(this.nodes[n].options|=xse)}return!1}get currentPos(){this.closeExtra();let t=0;for(let n=this.open;n>=0;n--){let r=this.nodes[n].content;for(let a=r.length-1;a>=0;a--)t+=r[a].nodeSize;n&&t++}return t}findAtPoint(t,n){if(this.find)for(let r=0;r-1)return t.split(/\s*\|\s*/).some(this.matchesContext,this);let n=t.split("/"),r=this.options.context,a=!this.isOpen&&(!r||r.parent.type==this.nodes[0].type),i=-(r?r.depth+1:0)+(a?0:1),l=(o,c)=>{for(;o>=0;o--){let d=n[o];if(d==""){if(o==n.length-1||o==0)continue;for(;c>=i;c--)if(l(o-1,c))return!0;return!1}else{let u=c>0||c==0&&a?this.nodes[c].type:r&&c>=i?r.node(c-i).type:null;if(!u||u.name!=d&&!u.isInGroup(d))return!1;c--}}return!0};return l(n.length-1,this.open)}textblockFromContext(){let t=this.options.context;if(t)for(let n=t.depth;n>=0;n--){let r=t.node(n).contentMatchAt(t.indexAfter(n)).defaultType;if(r&&r.isTextblock&&r.defaultAttrs)return r}for(let n in this.parser.schema.nodes){let r=this.parser.schema.nodes[n];if(r.isTextblock&&r.defaultAttrs)return r}}}function HKs(s){for(let t=s.firstChild,n=null;t;t=t.nextSibling){let r=t.nodeType==1?t.nodeName.toLowerCase():null;r&&kqt.hasOwnProperty(r)&&n?(n.appendChild(t),t=n):r=="li"?n=t:r&&(n=null)}}function GKs(s,t){return(s.matches||s.msMatchesSelector||s.webkitMatchesSelector||s.mozMatchesSelector).call(s,t)}function Pbt(s){let t={};for(let n in s)t[n]=s[n];return t}function Ibt(s,t){let n=t.schema.nodes;for(let r in n){let a=n[r];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,n);i&&((i.contentDOM||i.dom).appendChild(r),r=i.dom)}return r}serializeMark(t,n,r={}){let a=this.marks[t.type.name];return a&&f3e(dde(r),a(t,n),null,t.attrs)}static renderSpec(t,n,r=null,a){return typeof n=="string"?{dom:t.createTextNode(n)}:f3e(t,n,r,a)}static fromSchema(t){return t.cached.domSerializer||(t.cached.domSerializer=new GB(this.nodesFromSchema(t),this.marksFromSchema(t)))}static nodesFromSchema(t){let n=Lbt(t.nodes);return n.text||(n.text=r=>r.text),n}static marksFromSchema(t){return Lbt(t.marks)}}function Lbt(s){let t={};for(let n in s){let r=s[n].spec.toDOM;r&&(t[n]=r)}return t}function dde(s){return s.document||window.document}const Rbt=new WeakMap;function WKs(s){let t=Rbt.get(s);return t===void 0&&Rbt.set(s,t=KKs(s)),t}function KKs(s){let t=null;function n(r){if(r&&typeof r=="object")if(Array.isArray(r))if(typeof r[0]=="string")t||(t=[]),t.push(r);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&&(n=a.slice(0,l),a=a.slice(l+1));let o,c=n?s.createElementNS(n,a):s.createElement(a),d=t[1],u=1;if(d&&typeof d=="object"&&d.nodeType==null&&!Array.isArray(d)){u=2;for(let h in d)if(d[h]!=null){let m=h.indexOf(" ");m>0?c.setAttributeNS(h.slice(0,m),h.slice(m+1),d[h]):h=="style"&&c.style?c.style.cssText=d[h]:c.setAttribute(h,d[h])}}for(let h=u;hu)throw new RangeError("Content hole must be the only child of its parent node");return{dom:c,contentDOM:c}}else if(typeof m=="string")c.appendChild(s.createTextNode(m));else{let{dom:f,contentDOM:g}=f3e(s,m,n,r);if(c.appendChild(f),g){if(o)throw new RangeError("Multiple content holes");o=g}}}return{dom:c,contentDOM:o}}const Sqt=65535,Cqt=Math.pow(2,16);function YKs(s,t){return s+t*Cqt}function Dbt(s){return s&Sqt}function ZKs(s){return(s-(s&Sqt))/Cqt}const Aqt=1,Eqt=2,p3e=4,Tqt=8;class eWe{constructor(t,n,r){this.pos=t,this.delInfo=n,this.recover=r}get deleted(){return(this.delInfo&Tqt)>0}get deletedBefore(){return(this.delInfo&(Aqt|p3e))>0}get deletedAfter(){return(this.delInfo&(Eqt|p3e))>0}get deletedAcross(){return(this.delInfo&p3e)>0}}class Xj{constructor(t,n=!1){if(this.ranges=t,this.inverted=n,!t.length&&Xj.empty)return Xj.empty}recover(t){let n=0,r=Dbt(t);if(!this.inverted)for(let a=0;at)break;let d=this.ranges[o+i],u=this.ranges[o+l],h=c+d;if(t<=h){let m=d?t==c?-1:t==h?1:n:n,f=c+a+(m<0?0:u);if(r)return f;let g=t==(n<0?c:h)?null:YKs(o/3,t-c),x=0;return d&&(x|=t==c?Eqt:t==h?Aqt:p3e,(n<0?t!=c:t!=h)&&(x|=Tqt)),new eWe(f,x,g)}a+=u-d}return r?t+a:new eWe(t+a,0,null)}touches(t,n){let r=0,a=Dbt(n),i=this.inverted?2:1,l=this.inverted?1:2;for(let o=0;ot)break;let d=this.ranges[o+i],u=c+d;if(t<=u&&o==a*3)return!0;r+=this.ranges[o+l]-d}return!1}forEach(t){let n=this.inverted?2:1,r=this.inverted?1:2;for(let a=0,i=0;a=0;n--){let a=t.getMirror(n);this.appendMap(t._maps[n].invert(),a!=null&&a>n?r-a-1:void 0)}}invert(){let t=new yse;return t.appendMappingInverted(this),t}map(t,n=1){if(this.mirror)return this._map(t,n,!0);for(let r=this.from;ri&&c!l.isAtom||!o.type.allowsMarkType(this.mark.type)?l:l.mark(this.mark.addToSet(l.marks)),a),n.openStart,n.openEnd);return $y.fromReplace(t,this.from,this.to,i)}invert(){return new y4(this.from,this.to,this.mark)}map(t){let n=t.mapResult(this.from,1),r=t.mapResult(this.to,-1);return n.deleted&&r.deleted||n.pos>=r.pos?null:new bI(n.pos,r.pos,this.mark)}merge(t){return t instanceof bI&&t.mark.eq(this.mark)&&this.from<=t.to&&this.to>=t.from?new bI(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,n){if(typeof n.from!="number"||typeof n.to!="number")throw new RangeError("Invalid input for AddMarkStep.fromJSON");return new bI(n.from,n.to,t.markFromJSON(n.mark))}}P1.jsonID("addMark",bI);class y4 extends P1{constructor(t,n,r){super(),this.from=t,this.to=n,this.mark=r}apply(t){let n=t.slice(this.from,this.to),r=new Ki(xnt(n.content,a=>a.mark(this.mark.removeFromSet(a.marks)),t),n.openStart,n.openEnd);return $y.fromReplace(t,this.from,this.to,r)}invert(){return new bI(this.from,this.to,this.mark)}map(t){let n=t.mapResult(this.from,1),r=t.mapResult(this.to,-1);return n.deleted&&r.deleted||n.pos>=r.pos?null:new y4(n.pos,r.pos,this.mark)}merge(t){return t instanceof y4&&t.mark.eq(this.mark)&&this.from<=t.to&&this.to>=t.from?new y4(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,n){if(typeof n.from!="number"||typeof n.to!="number")throw new RangeError("Invalid input for RemoveMarkStep.fromJSON");return new y4(n.from,n.to,t.markFromJSON(n.mark))}}P1.jsonID("removeMark",y4);class _I extends P1{constructor(t,n){super(),this.pos=t,this.mark=n}apply(t){let n=t.nodeAt(this.pos);if(!n)return $y.fail("No node at mark step's position");let r=n.type.create(n.attrs,null,this.mark.addToSet(n.marks));return $y.fromReplace(t,this.pos,this.pos+1,new Ki(hi.from(r),0,n.isLeaf?0:1))}invert(t){let n=t.nodeAt(this.pos);if(n){let r=this.mark.addToSet(n.marks);if(r.length==n.marks.length){for(let a=0;ar.pos?null:new Pv(n.pos,r.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,n){if(typeof n.from!="number"||typeof n.to!="number"||typeof n.gapFrom!="number"||typeof n.gapTo!="number"||typeof n.insert!="number")throw new RangeError("Invalid input for ReplaceAroundStep.fromJSON");return new Pv(n.from,n.to,n.gapFrom,n.gapTo,Ki.fromJSON(t,n.slice),n.insert,!!n.structure)}}P1.jsonID("replaceAround",Pv);function tWe(s,t,n){let r=s.resolve(t),a=n-t,i=r.depth;for(;a>0&&i>0&&r.indexAfter(i)==r.node(i).childCount;)i--,a--;if(a>0){let l=r.node(i).maybeChild(r.indexAfter(i));for(;a>0;){if(!l||l.isLeaf)return!0;l=l.firstChild,a--}}return!1}function XKs(s,t,n,r){let a=[],i=[],l,o;s.doc.nodesBetween(t,n,(c,d,u)=>{if(!c.isInline)return;let h=c.marks;if(!r.isInSet(h)&&u.type.allowsMarkType(r.type)){let m=Math.max(d,t),f=Math.min(d+c.nodeSize,n),g=r.addToSet(h);for(let x=0;xs.step(c)),i.forEach(c=>s.step(c))}function QKs(s,t,n,r){let a=[],i=0;s.doc.nodesBetween(t,n,(l,o)=>{if(!l.isInline)return;i++;let c=null;if(r instanceof P6e){let d=l.marks,u;for(;u=r.isInSet(d);)(c||(c=[])).push(u),d=u.removeFromSet(d)}else r?r.isInSet(l.marks)&&(c=[r]):c=l.marks;if(c&&c.length){let d=Math.min(o+l.nodeSize,n);for(let u=0;us.step(new y4(l.from,l.to,l.style)))}function ynt(s,t,n,r=n.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 JKs(s,t,n){return(t==0||s.canReplace(t,s.childCount))&&(n==s.childCount||s.canReplace(0,n))}function yK(s){let n=s.parent.content.cutByIndex(s.startIndex,s.endIndex);for(let r=s.depth,a=0,i=0;;--r){let l=s.$from.node(r),o=s.$from.index(r)+a,c=s.$to.indexAfter(r)-i;if(rn;g--)x||r.index(g)>0?(x=!0,u=hi.from(r.node(g).copy(u)),h++):c--;let m=hi.empty,f=0;for(let g=i,x=!1;g>n;g--)x||a.after(g+1)=0;l--){if(r.size){let o=n[l].type.contentMatch.matchFragment(r);if(!o||!o.validEnd)throw new RangeError("Wrapper type given to Transform.wrap does not form valid content of its parent wrapper")}r=hi.from(n[l].type.create(n[l].attrs,r))}let a=t.start,i=t.end;s.step(new Pv(a,i,a,i,new Ki(r,0,0),n.length,!0))}function rYs(s,t,n,r,a){if(!r.isTextblock)throw new RangeError("Type given to setBlockType should be a textblock");let i=s.steps.length;s.doc.nodesBetween(t,n,(l,o)=>{let c=typeof a=="function"?a(l):a;if(l.isTextblock&&!l.hasMarkup(r,c)&&aYs(s.doc,s.mapping.slice(i).map(o),r)){let d=null;if(r.schema.linebreakReplacement){let f=r.whitespace=="pre",g=!!r.contentMatch.matchType(r.schema.linebreakReplacement);f&&!g?d=!1:!f&&g&&(d=!0)}d===!1&&Pqt(s,l,o,i),ynt(s,s.mapping.slice(i).map(o,1),r,void 0,d===null);let u=s.mapping.slice(i),h=u.map(o,1),m=u.map(o+l.nodeSize,1);return s.step(new Pv(h,m,h+1,m-1,new Ki(hi.from(r.create(c,null,l.marks)),0,0),1,!0)),d===!0&&Mqt(s,l,o,i),!1}})}function Mqt(s,t,n,r){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(r).map(n+1+i+l.index);s.replaceWith(c,c+1,t.type.schema.linebreakReplacement.create())}}})}function Pqt(s,t,n,r){t.forEach((a,i)=>{if(a.type==a.type.schema.linebreakReplacement){let l=s.mapping.slice(r).map(n+1+i);s.replaceWith(l,l+1,t.type.schema.text(` `))}})}function aYs(s,t,n){let r=s.resolve(t),a=r.index();return r.parent.canReplaceWith(a,a+1,n)}function iYs(s,t,n,r,a){let i=s.doc.nodeAt(t);if(!i)throw new RangeError("No node at given position");n||(n=i.type);let l=n.create(r,null,a||i.marks);if(i.isLeaf)return s.replaceWith(t,t+i.nodeSize,l);if(!n.validContent(i.content))throw new RangeError("Invalid content for node type "+n.name);s.step(new Pv(t,t+i.nodeSize,t+1,t+i.nodeSize-1,new Ki(hi.from(l),0,0),1,!0))}function HE(s,t,n=1,r){let a=s.resolve(t),i=a.depth-n,l=r&&r[r.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,u=n-2;d>i;d--,u--){let h=a.node(d),m=a.index(d);if(h.type.spec.isolating)return!1;let f=h.content.cutByIndex(m,h.childCount),g=r&&r[u+1];g&&(f=f.replaceChild(0,g.type.create(g.attrs)));let x=r&&r[u]||h;if(!h.canReplace(m+1,h.childCount)||!x.type.validContent(f))return!1}let o=a.indexAfter(i),c=r&&r[0];return a.node(i).canReplaceWith(o,o,c?c.type:a.node(i+1).type)}function oYs(s,t,n=1,r){let a=s.doc.resolve(t),i=hi.empty,l=hi.empty;for(let o=a.depth,c=a.depth-n,d=n-1;o>c;o--,d--){i=hi.from(a.node(o).copy(i));let u=r&&r[d];l=hi.from(u?u.type.create(u.attrs,l):a.node(o).copy(l))}s.step(new Dy(t,t,new Ki(i.append(l),n,n),!0))}function h6(s,t){let n=s.resolve(t),r=n.index();return Iqt(n.nodeBefore,n.nodeAfter)&&n.parent.canReplace(r,r+1)}function lYs(s,t){t.content.size||s.type.compatibleContent(t.type);let n=s.contentMatchAt(s.childCount),{linebreakReplacement:r}=s.type.schema;for(let a=0;a0?(i=r.node(a+1),o++,l=r.node(a).maybeChild(o)):(i=r.node(a).maybeChild(o-1),l=r.node(a+1)),i&&!i.isTextblock&&Iqt(i,l)&&r.node(a).canReplace(o,o+1))return t;if(a==0)break;t=n<0?r.before(a):r.after(a)}}function cYs(s,t,n){let r=null,{linebreakReplacement:a}=s.doc.type.schema,i=s.doc.resolve(t-n),l=i.node().type;if(a&&l.inlineContent){let u=l.whitespace=="pre",h=!!l.contentMatch.matchType(a);u&&!h?r=!1:!u&&h&&(r=!0)}let o=s.steps.length;if(r===!1){let u=s.doc.resolve(t+n);Pqt(s,u.node(),u.before(),o)}l.inlineContent&&ynt(s,t+n-1,l,i.node().contentMatchAt(i.index()),r==null);let c=s.mapping.slice(o),d=c.map(t-n);if(s.step(new Dy(d,c.map(t+n,-1),Ki.empty,!0)),r===!0){let u=s.doc.resolve(d);Mqt(s,u.node(),u.before(),s.steps.length)}return s}function dYs(s,t,n){let r=s.resolve(t);if(r.parent.canReplaceWith(r.index(),r.index(),n))return t;if(r.parentOffset==0)for(let a=r.depth-1;a>=0;a--){let i=r.index(a);if(r.node(a).canReplaceWith(i,i,n))return r.before(a+1);if(i>0)return null}if(r.parentOffset==r.parent.content.size)for(let a=r.depth-1;a>=0;a--){let i=r.indexAfter(a);if(r.node(a).canReplaceWith(i,i,n))return r.after(a+1);if(i=0;l--){let o=l==r.depth?0:r.pos<=(r.start(l+1)+r.end(l+1))/2?-1:1,c=r.index(l)+(o>0?1:0),d=r.node(l),u=!1;if(i==1)u=d.canReplace(c,c,a);else{let h=d.contentMatchAt(c).findWrapping(a.firstChild.type);u=h&&d.canReplaceWith(c,c,h[0])}if(u)return o==0?r.pos:o<0?r.before(l+1):r.after(l+1)}return null}function L6e(s,t,n=t,r=Ki.empty){if(t==n&&!r.size)return null;let a=s.resolve(t),i=s.resolve(n);return Rqt(a,i,r)?new Dy(t,n,r):new uYs(a,i,r).fit()}function Rqt(s,t,n){return!n.openStart&&!n.openEnd&&s.start()==t.start()&&s.parent.canReplace(s.index(),t.index(),n.content)}class uYs{constructor(t,n,r){this.$from=t,this.$to=n,this.unplaced=r,this.frontier=[],this.placed=hi.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=hi.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(),n=this.placed.size-this.depth-this.$from.depth,r=this.$from,a=this.close(t<0?this.$to:r.doc.resolve(t));if(!a)return null;let i=this.placed,l=r.depth,o=a.depth;for(;l&&o&&i.childCount==1;)i=i.firstChild.content,l--,o--;let c=new Ki(i,l,o);return t>-1?new Pv(r.pos,t,this.$to.pos,this.$to.end(),c,n):c.size||r.pos!=this.$to.pos?new Dy(r.pos,a.pos,c):null}findFittable(){let t=this.unplaced.openStart;for(let n=this.unplaced.content,r=0,a=this.unplaced.openEnd;r1&&(a=0),i.type.spec.isolating&&a<=r){t=r;break}n=i.content}for(let n=1;n<=2;n++)for(let r=n==1?t:this.unplaced.openStart;r>=0;r--){let a,i=null;r?(i=Obt(this.unplaced.content,r-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],u,h=null;if(n==1&&(l?d.matchType(l.type)||(h=d.fillBefore(hi.from(l),!1)):i&&c.compatibleContent(i.type)))return{sliceDepth:r,frontierDepth:o,parent:i,inject:h};if(n==2&&l&&(u=d.findWrapping(l.type)))return{sliceDepth:r,frontierDepth:o,parent:i,wrap:u};if(i&&d.matchType(i.type))break}}}openMore(){let{content:t,openStart:n,openEnd:r}=this.unplaced;return zbt(t,-1)<=n?!1:(this.unplaced.size>1&&zbt(t,1)>r&&r++,this.unplaced=new Ki(t,n+1,r),!0)}dropNode(){let{content:t,openStart:n,openEnd:r}=this.unplaced,a=Obt(t,n);if(a.childCount<=1&&n>0){let i=t.size-n<=n+a.size;this.unplaced=new Ki(fQ(t,n-1,1),n-1,i?n-1:r)}else this.unplaced=new Ki(fQ(t,n,1),n,r)}placeNodes({sliceDepth:t,frontierDepth:n,parent:r,inject:a,wrap:i}){for(;this.depth>n;)this.closeFrontierNode();if(i)for(let x=0;x1||c==0||x.content.size)&&(h=y,u.push(Dqt(x.mark(m.allowedMarks(x.marks)),d==1?c:0,d==o.childCount?f:-1)))}let g=d==o.childCount;g||(f=-1),this.placed=pQ(this.placed,n,hi.from(u)),this.frontier[n].match=h,g&&f<0&&r&&r.type==this.frontier[this.depth].type&&this.frontier.length>1&&this.closeFrontierNode();for(let x=0,y=o;x1&&a==this.$to.end(--r);)++a;return a}findCloseLevel(t){e:for(let n=Math.min(this.depth,t.depth);n>=0;n--){let{match:r,type:a}=this.frontier[n],i=n=0;o--){let{match:c,type:d}=this.frontier[o],u=aBe(t,o,d,c,!0);if(!u||u.childCount)continue e}return{depth:n,fit:l,move:i?t.doc.resolve(t.after(n+1)):t}}}}close(t){let n=this.findCloseLevel(t);if(!n)return null;for(;this.depth>n.depth;)this.closeFrontierNode();n.fit.childCount&&(this.placed=pQ(this.placed,n.depth,n.fit)),t=n.move;for(let r=n.depth+1;r<=t.depth;r++){let a=t.node(r),i=a.type.contentMatch.fillBefore(a.content,!0,t.index(r));this.openFrontierNode(a.type,a.attrs,i)}return t}openFrontierNode(t,n=null,r){let a=this.frontier[this.depth];a.match=a.match.matchType(t),this.placed=pQ(this.placed,this.depth,hi.from(t.create(n,r))),this.frontier.push({type:t,match:t.contentMatch})}closeFrontierNode(){let n=this.frontier.pop().match.fillBefore(hi.empty,!0);n.childCount&&(this.placed=pQ(this.placed,this.frontier.length,n))}}function fQ(s,t,n){return t==0?s.cutByIndex(n,s.childCount):s.replaceChild(0,s.firstChild.copy(fQ(s.firstChild.content,t-1,n)))}function pQ(s,t,n){return t==0?s.append(n):s.replaceChild(s.childCount-1,s.lastChild.copy(pQ(s.lastChild.content,t-1,n)))}function Obt(s,t){for(let n=0;n1&&(r=r.replaceChild(0,Dqt(r.firstChild,t-1,r.childCount==1?n-1:0))),t>0&&(r=s.type.contentMatch.fillBefore(r).append(r),n<=0&&(r=r.append(s.type.contentMatch.matchFragment(r).fillBefore(hi.empty,!0)))),s.copy(r)}function aBe(s,t,n,r,a){let i=s.node(t),l=a?s.indexAfter(t):s.index(t);if(l==i.childCount&&!n.compatibleContent(i.type))return null;let o=r.fillBefore(i.content,!0,l);return o&&!hYs(n,i.content,l)?o:null}function hYs(s,t,n){for(let r=n;r0;m--,f--){let g=a.node(m).type.spec;if(g.defining||g.definingAsContext||g.isolating)break;l.indexOf(m)>-1?o=m:a.before(m)==f&&l.splice(1,0,-m)}let c=l.indexOf(o),d=[],u=r.openStart;for(let m=r.content,f=0;;f++){let g=m.firstChild;if(d.push(g),f==r.openStart)break;m=g.content}for(let m=u-1;m>=0;m--){let f=d[m],g=mYs(f.type);if(g&&!f.sameMarkup(a.node(Math.abs(o)-1)))u=m;else if(g||!f.type.isTextblock)break}for(let m=r.openStart;m>=0;m--){let f=(m+u+1)%(r.openStart+1),g=d[f];if(g)for(let x=0;x=0&&(s.replace(t,n,r),!(s.steps.length>h));m--){let f=l[m];f<0||(t=a.before(f),n=i.after(f))}}function Fqt(s,t,n,r,a){if(tr){let i=a.contentMatchAt(0),l=i.fillBefore(s).append(s);s=l.append(i.matchFragment(l).fillBefore(hi.empty,!0))}return s}function pYs(s,t,n,r){if(!r.isInline&&t==n&&s.doc.resolve(t).parent.content.size){let a=dYs(s.doc,t,r.type);a!=null&&(t=n=a)}s.replaceRange(t,n,new Ki(hi.from(r),0,0))}function gYs(s,t,n){let r=s.doc.resolve(t),a=s.doc.resolve(n);if(r.parent.isTextblock&&a.parent.isTextblock&&r.start()!=a.start()&&r.parentOffset==0&&a.parentOffset==0){let l=r.sharedDepth(n),o=!1;for(let c=r.depth;c>l;c--)r.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=r.depth;c>0&&t==r.start(c);c--)t=r.before(c);for(let c=a.depth;c>0&&n==a.start(c);c--)n=a.before(c);r=s.doc.resolve(t),a=s.doc.resolve(n)}}let i=Oqt(r,a);for(let l=0;l0&&(c||r.node(o-1).canReplace(r.index(o-1),a.indexAfter(o-1))))return s.delete(r.before(o),a.after(o))}for(let l=1;l<=r.depth&&l<=a.depth;l++)if(t-r.start(l)==r.depth-l&&n>r.end(l)&&a.end(l)-n!=a.depth-l&&r.start(l-1)==a.start(l-1)&&r.node(l-1).canReplace(r.index(l-1),a.index(l-1)))return s.delete(r.before(l),n);s.delete(t,n)}function Oqt(s,t){let n=[],r=Math.min(s.depth,t.depth);for(let a=r;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)&&n.push(a)}return n}class CV extends P1{constructor(t,n,r){super(),this.pos=t,this.attr=n,this.value=r}apply(t){let n=t.nodeAt(this.pos);if(!n)return $y.fail("No node at attribute step's position");let r=Object.create(null);for(let i in n.attrs)r[i]=n.attrs[i];r[this.attr]=this.value;let a=n.type.create(r,null,n.marks);return $y.fromReplace(t,this.pos,this.pos+1,new Ki(hi.from(a),0,n.isLeaf?0:1))}getMap(){return Xj.empty}invert(t){return new CV(this.pos,this.attr,t.nodeAt(this.pos).attrs[this.attr])}map(t){let n=t.mapResult(this.pos,1);return n.deletedAfter?null:new CV(n.pos,this.attr,this.value)}toJSON(){return{stepType:"attr",pos:this.pos,attr:this.attr,value:this.value}}static fromJSON(t,n){if(typeof n.pos!="number"||typeof n.attr!="string")throw new RangeError("Invalid input for AttrStep.fromJSON");return new CV(n.pos,n.attr,n.value)}}P1.jsonID("attr",CV);class vse extends P1{constructor(t,n){super(),this.attr=t,this.value=n}apply(t){let n=Object.create(null);for(let a in t.attrs)n[a]=t.attrs[a];n[this.attr]=this.value;let r=t.type.create(n,t.content,t.marks);return $y.ok(r)}getMap(){return Xj.empty}invert(t){return new vse(this.attr,t.attrs[this.attr])}map(t){return this}toJSON(){return{stepType:"docAttr",attr:this.attr,value:this.value}}static fromJSON(t,n){if(typeof n.attr!="string")throw new RangeError("Invalid input for DocAttrStep.fromJSON");return new vse(n.attr,n.value)}}P1.jsonID("docAttr",vse);let RG=class extends Error{};RG=function s(t){let n=Error.call(this,t);return n.__proto__=s.prototype,n};RG.prototype=Object.create(Error.prototype);RG.prototype.constructor=RG;RG.prototype.name="TransformError";let bnt=class{constructor(t){this.doc=t,this.steps=[],this.docs=[],this.mapping=new yse}get before(){return this.docs.length?this.docs[0]:this.doc}step(t){let n=this.maybeStep(t);if(n.failed)throw new RG(n.failed);return this}maybeStep(t){let n=t.apply(this.doc);return n.failed||this.addStep(t,n.doc),n}get docChanged(){return this.steps.length>0}changedRange(){let t=1e9,n=-1e9;for(let r=0;r{t=Math.min(t,o),n=Math.max(n,c)})}return t==1e9?null:{from:t,to:n}}addStep(t,n){this.docs.push(this.doc),this.steps.push(t),this.mapping.appendMap(t.getMap()),this.doc=n}replace(t,n=t,r=Ki.empty){let a=L6e(this.doc,t,n,r);return a&&this.step(a),this}replaceWith(t,n,r){return this.replace(t,n,new Ki(hi.from(r),0,0))}delete(t,n){return this.replace(t,n,Ki.empty)}insert(t,n){return this.replaceWith(t,t,n)}replaceRange(t,n,r){return fYs(this,t,n,r),this}replaceRangeWith(t,n,r){return pYs(this,t,n,r),this}deleteRange(t,n){return gYs(this,t,n),this}lift(t,n){return eYs(this,t,n),this}join(t,n=1){return cYs(this,t,n),this}wrap(t,n){return nYs(this,t,n),this}setBlockType(t,n=t,r,a=null){return rYs(this,t,n,r,a),this}setNodeMarkup(t,n,r=null,a){return iYs(this,t,n,r,a),this}setNodeAttribute(t,n,r){return this.step(new CV(t,n,r)),this}setDocAttribute(t,n){return this.step(new vse(t,n)),this}addNodeMark(t,n){return this.step(new _I(t,n)),this}removeNodeMark(t,n){let r=this.doc.nodeAt(t);if(!r)throw new RangeError("No node at position "+t);if(n instanceof kf)n.isInSet(r.marks)&&this.step(new X7(t,n));else{let a=r.marks,i,l=[];for(;i=n.isInSet(a);)l.push(new X7(t,i)),a=i.removeFromSet(a);for(let o=l.length-1;o>=0;o--)this.step(l[o])}return this}split(t,n=1,r){return oYs(this,t,n,r),this}addMark(t,n,r){return XKs(this,t,n,r),this}removeMark(t,n,r){return QKs(this,t,n,r),this}clearIncompatible(t,n,r){return ynt(this,t,n,r),this}};const iBe=Object.create(null);class oc{constructor(t,n,r){this.$anchor=t,this.$head=n,this.ranges=r||[new zqt(t.min(n),t.max(n))]}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 n=0;n=0;i--){let l=n<0?_U(t.node(0),t.node(i),t.before(i+1),t.index(i),n,r):_U(t.node(0),t.node(i),t.after(i+1),t.index(i)+1,n,r);if(l)return l}return null}static near(t,n=1){return this.findFrom(t,n)||this.findFrom(t,-n)||new b2(t.node(0))}static atStart(t){return _U(t,t,0,0,1)||new b2(t)}static atEnd(t){return _U(t,t,t.content.size,t.childCount,-1)||new b2(t)}static fromJSON(t,n){if(!n||!n.type)throw new RangeError("Invalid input for Selection.fromJSON");let r=iBe[n.type];if(!r)throw new RangeError(`No selection type ${n.type} defined`);return r.fromJSON(t,n)}static jsonID(t,n){if(t in iBe)throw new RangeError("Duplicate use of selection JSON ID "+t);return iBe[t]=n,n.prototype.jsonID=t,n}getBookmark(){return Al.between(this.$anchor,this.$head).getBookmark()}}oc.prototype.visible=!0;class zqt{constructor(t,n){this.$from=t,this.$to=n}}let Bbt=!1;function $bt(s){!Bbt&&!s.parent.inlineContent&&(Bbt=!0,console.warn("TextSelection endpoint not pointing into a node with inline content ("+s.parent.type.name+")"))}class Al extends oc{constructor(t,n=t){$bt(t),$bt(n),super(t,n)}get $cursor(){return this.$anchor.pos==this.$head.pos?this.$head:null}map(t,n){let r=t.resolve(n.map(this.head));if(!r.parent.inlineContent)return oc.near(r);let a=t.resolve(n.map(this.anchor));return new Al(a.parent.inlineContent?a:r,r)}replace(t,n=Ki.empty){if(super.replace(t,n),n==Ki.empty){let r=this.$from.marksAcross(this.$to);r&&t.ensureMarks(r)}}eq(t){return t instanceof Al&&t.anchor==this.anchor&&t.head==this.head}getBookmark(){return new R6e(this.anchor,this.head)}toJSON(){return{type:"text",anchor:this.anchor,head:this.head}}static fromJSON(t,n){if(typeof n.anchor!="number"||typeof n.head!="number")throw new RangeError("Invalid input for TextSelection.fromJSON");return new Al(t.resolve(n.anchor),t.resolve(n.head))}static create(t,n,r=n){let a=t.resolve(n);return new this(a,r==n?a:t.resolve(r))}static between(t,n,r){let a=t.pos-n.pos;if((!r||a)&&(r=a>=0?1:-1),!n.parent.inlineContent){let i=oc.findFrom(n,r,!0)||oc.findFrom(n,-r,!0);if(i)n=i.$head;else return oc.near(n,r)}return t.parent.inlineContent||(a==0?t=n:(t=(oc.findFrom(t,-r,!0)||oc.findFrom(t,r,!0)).$anchor,t.pos0?0:1);a>0?l=0;l+=a){let o=t.child(l);if(o.isAtom){if(!i&&El.isSelectable(o))return El.create(s,n-(a<0?o.nodeSize:0))}else{let c=_U(s,o,n+a,a<0?o.childCount:0,a,i);if(c)return c}n+=o.nodeSize*a}return null}function Ubt(s,t,n){let r=s.steps.length-1;if(r{l==null&&(l=u)}),s.setSelection(oc.near(s.doc.resolve(l),n))}const qbt=1,ude=2,Vbt=4;class yYs extends bnt{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|=ude,this}ensureMarks(t){return kf.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&ude)>0}addStep(t,n){super.addStep(t,n),this.updated=this.updated&~ude,this.storedMarks=null}setTime(t){return this.time=t,this}replaceSelection(t){return this.selection.replace(this,t),this}replaceSelectionWith(t,n=!0){let r=this.selection;return n&&(t=t.mark(this.storedMarks||(r.empty?r.$from.marks():r.$from.marksAcross(r.$to)||kf.none))),r.replaceWith(this,t),this}deleteSelection(){return this.selection.replace(this),this}insertText(t,n,r){let a=this.doc.type.schema;if(n==null)return t?this.replaceSelectionWith(a.text(t),!0):this.deleteSelection();{if(r==null&&(r=n),!t)return this.deleteRange(n,r);let i=this.storedMarks;if(!i){let l=this.doc.resolve(n);i=r==n?l.marks():l.marksAcross(this.doc.resolve(r))}return this.replaceRangeWith(n,r,a.text(t,i)),!this.selection.empty&&this.selection.to==n+t.length&&this.setSelection(oc.near(this.selection.$to)),this}}setMeta(t,n){return this.meta[typeof t=="string"?t:t.key]=n,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|=Vbt,this}get scrolledIntoView(){return(this.updated&Vbt)>0}}function Hbt(s,t){return!t||!s?s:s.bind(t)}class gQ{constructor(t,n,r){this.name=t,this.init=Hbt(n.init,r),this.apply=Hbt(n.apply,r)}}const vYs=[new gQ("doc",{init(s){return s.doc||s.schema.topNodeType.createAndFill()},apply(s){return s.doc}}),new gQ("selection",{init(s,t){return s.selection||oc.atStart(t.doc)},apply(s){return s.selection}}),new gQ("storedMarks",{init(s){return s.storedMarks||null},apply(s,t,n,r){return r.selection.$cursor?s.storedMarks:null}}),new gQ("scrollToSelection",{init(){return 0},apply(s,t){return s.scrolledIntoView?t+1:t}})];class oBe{constructor(t,n){this.schema=t,this.plugins=[],this.pluginsByKey=Object.create(null),this.fields=vYs.slice(),n&&n.forEach(r=>{if(this.pluginsByKey[r.key])throw new RangeError("Adding different instances of a keyed plugin ("+r.key+")");this.plugins.push(r),this.pluginsByKey[r.key]=r,r.spec.state&&this.fields.push(new gQ(r.key,r.spec.state,r))})}}class nq{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,n=-1){for(let r=0;rr.toJSON())),t&&typeof t=="object")for(let r in t){if(r=="doc"||r=="selection")throw new RangeError("The JSON fields `doc` and `selection` are reserved");let a=t[r],i=a.spec.state;i&&i.toJSON&&(n[r]=i.toJSON.call(a,this[a.key]))}return n}static fromJSON(t,n,r){if(!n)throw new RangeError("Invalid input for EditorState.fromJSON");if(!t.schema)throw new RangeError("Required config field 'schema' missing");let a=new oBe(t.schema,t.plugins),i=new nq(a);return a.fields.forEach(l=>{if(l.name=="doc")i.doc=oL.fromJSON(t.schema,n.doc);else if(l.name=="selection")i.selection=oc.fromJSON(i.doc,n.selection);else if(l.name=="storedMarks")n.storedMarks&&(i.storedMarks=n.storedMarks.map(t.schema.markFromJSON));else{if(r)for(let o in r){let c=r[o],d=c.spec.state;if(c.key==l.name&&d&&d.fromJSON&&Object.prototype.hasOwnProperty.call(n,o)){i[l.name]=d.fromJSON.call(c,t,n[o],i);return}}i[l.name]=l.init(t,i)}}),i}}function Bqt(s,t,n){for(let r in s){let a=s[r];a instanceof Function?a=a.bind(t):r=="handleDOMEvents"&&(a=Bqt(a,t,{})),n[r]=a}return n}class $0{constructor(t){this.spec=t,this.props={},t.props&&Bqt(t.props,this,this.props),this.key=t.key?t.key.key:$qt("plugin")}getState(t){return t[this.key]}}const lBe=Object.create(null);function $qt(s){return s in lBe?s+"$"+ ++lBe[s]:(lBe[s]=0,s+"$")}class I1{constructor(t="key"){this.key=$qt(t)}get(t){return t.config.pluginsByKey[this.key]}getState(t){return t[this.key]}}const lb=function(s){for(var t=0;;t++)if(s=s.previousSibling,!s)return t},DG=function(s){let t=s.assignedSlot||s.parentNode;return t&&t.nodeType==11?t.host:t};let sWe=null;const EA=function(s,t,n){let r=sWe||(sWe=document.createRange());return r.setEnd(s,n??s.nodeValue.length),r.setStart(s,t||0),r},bYs=function(){sWe=null},Q7=function(s,t,n,r){return n&&(Gbt(s,t,n,r,-1)||Gbt(s,t,n,r,1))},_Ys=/^(img|br|input|textarea|hr)$/i;function Gbt(s,t,n,r,a){for(var i;;){if(s==n&&t==r)return!0;if(t==(a<0?0:p1(s))){let l=s.parentNode;if(!l||!Fl(l)||die(s)||_Ys.test(s.nodeName)||s.contentEditable=="false")return!1;t=lb(s)+(a<0?0:1),s=l}else if(Fl(s)){let l=s.childNodes[t+(a<0?-1:0)];if(Fl(l)&&l.contentEditable=="false")if(!((i=l.pmViewDesc)===null||i===void 0)&&i.ignoreForSelection)t+=a;else return!1;else s=l,t=a<0?p1(s):0}else return!1}}function p1(s){return s.nodeType==3?s.nodeValue.length:s.childNodes.length}function Fl(s){return s.nodeType==1}function S0(s){return s.nodeType==3}function J7(s,t){return t?s.contains(Fl(t)?t:t.parentNode):!1}function wYs(s,t){for(;;){if(S0(s)&&t)return s;if(Fl(s)&&t>0){if(s.contentEditable=="false")return null;s=s.childNodes[t-1],t=p1(s)}else if(s.parentNode&&!die(s))t=lb(s),s=s.parentNode;else return null}}function jYs(s,t){for(;;){if(S0(s)&&t2),TN=FG||(J4?/Mac/.test(J4.platform):!1),Vqt=J4?/Win/.test(J4.platform):!1,_E=/Android \d/.test(m6),F6e=!!Wbt&&"webkitFontSmoothing"in Wbt.documentElement.style,CYs=F6e?+(/\bAppleWebKit\/(\d+)/.exec(navigator.userAgent)||[0,0])[1]:0;function AYs(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 J3(s,t){return typeof s=="number"?s:s[t]}function EYs(s){let t=s.getBoundingClientRect(),n=t.width/s.offsetWidth||1,r=t.height/s.offsetHeight||1;return{left:t.left,right:t.left+s.clientWidth*n,top:t.top,bottom:t.top+s.clientHeight*r}}function Kbt(s,t,n){if(!iWe(t)&&t.left==0)return;let r=s.someProp("scrollThreshold")||0,a=s.someProp("scrollMargin")||5,i=s.dom.ownerDocument;for(let l=n||s.dom;l;){if(!Fl(l)){l=DG(l);continue}let o=l==i.body,c=o?AYs(i):EYs(l),d=0,u=0;if(t.topc.bottom-J3(r,"bottom")&&(u=t.bottom-t.top>c.bottom-c.top?t.top+J3(a,"top")-c.top:t.bottom-c.bottom+J3(a,"bottom")),t.leftc.right-J3(r,"right")&&(d=t.right-c.right+J3(a,"right")),d||u)if(o)i.defaultView.scrollBy(d,u);else{let m=l.scrollLeft,f=l.scrollTop;u&&(l.scrollTop+=u),d&&(l.scrollLeft+=d);let g=l.scrollLeft-m,x=l.scrollTop-f;t={left:t.left-g,top:t.top-x,right:t.right-g,bottom:t.bottom-x}}let h=o?"fixed":getComputedStyle(l).position;if(/^(fixed|sticky)$/.test(h))break;l=h=="absolute"?l.offsetParent:DG(l)}}function TYs(s){let t=s.dom.getBoundingClientRect(),n=Math.max(0,t.top),r,a;for(let i=(t.left+t.right)/2,l=n+1;l=n-20){r=o,a=c.top;break}}return{refDOM:r,refTop:a,stack:Hqt(s.dom)}}function Hqt(s){let t=[],n=s.ownerDocument;for(let r=s;r&&(t.push({dom:r,top:r.scrollTop,left:r.scrollLeft}),s!=n);r=DG(r));return t}function MYs({refDOM:s,refTop:t,stack:n}){let r=s?s.getBoundingClientRect().top:0;Gqt(n,r==0?0:r-t)}function Gqt(s,t){for(let n=0;n=o){l=Math.max(g.bottom,l),o=Math.min(g.top,o);let x=g.left>t.left?g.left-t.left:g.right=(g.left+g.right)/2?1:0));continue}}else g.top>t.top&&!c&&g.left<=t.left&&g.right>=t.left&&(c=u,d={left:Math.max(g.left,Math.min(g.right,t.left)),top:g.top});!n&&(t.left>=g.right&&t.top>=g.top||t.left>=g.left&&t.top>=g.bottom)&&(i=h+1)}}return!n&&c&&(n=c,a=d,r=0),n&&S0(n)?IYs(n,a):!n||r?{node:s,offset:i}:Wqt(n,a)}function IYs(s,t){let n=s.nodeValue.length,r=document.createRange(),a;for(let i=0;i=(l.left+l.right)/2?1:0)};break}}return r.detach(),a||{node:s,offset:0}}function wnt(s,t){return s.left>=t.left-1&&s.left<=t.right+1&&s.top>=t.top-1&&s.top<=t.bottom+1}function LYs(s,t){let n=s.parentNode;return n&&/^li$/i.test(n.nodeName)&&t.left(l.left+l.right)/2?1:-1}return s.docView.posFromDOM(r,a,i)}function DYs(s,t,n,r){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(Fl(o.dom)&&(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>r.left||c.top>r.top?a=o.posBefore:(!l&&c.right-1?a:s.docView.posFromDOM(t,n,-1)}function Kqt(s,t,n){let r=s.childNodes.length;if(r&&n.topt.top&&a++}let d;F6e&&a&&Fl(r)&&Fl(d=r.childNodes[a-1])&&d.contentEditable=="false"&&d.getBoundingClientRect().top>=t.top&&a--,r==s.dom&&a==r.childNodes.length-1&&Fl(r.lastChild)&&t.top>r.lastChild.getBoundingClientRect().bottom?o=s.state.doc.content.size:(a==0||!Fl(r)||r.childNodes[a-1].nodeName!="BR")&&(o=DYs(s,r,a,t))}o==null&&(o=RYs(s,l,t));let c=s.docView.nearestDesc(l,!0);return{pos:o,inside:c?c.posAtStart-c.border:-1}}function iWe(s){return s.top=0&&a==r.nodeValue.length?(c--,u=1):n<0?c--:d++,DZ(YM(EA(r,c,d),u),u<0)}if(!s.state.doc.resolve(t-(i||0)).parent.inlineContent){if(i==null&&a&&(n<0||a==p1(r))){let c=r.childNodes[a-1];if(Fl(c))return cBe(c.getBoundingClientRect(),!1)}if(i==null&&a=0)}if(i==null&&a&&(n<0||a==p1(r))){let c=r.childNodes[a-1],d=S0(c)?EA(c,p1(c)-(l?0:1)):Fl(c)&&(c.nodeName!="BR"||!c.nextSibling)?c:null;if(d)return DZ(YM(d,1),!1)}if(i==null&&a=0)}function DZ(s,t){if(s.width==0)return s;let n=t?s.left:s.right;return{top:s.top,bottom:s.bottom,left:n,right:n}}function cBe(s,t){if(s.height==0)return s;let n=t?s.top:s.bottom;return{top:n,bottom:n,left:s.left,right:s.right}}function Zqt(s,t,n){let r=s.state,a=s.root.activeElement;r!=t&&s.updateState(t),a!=s.dom&&s.focus();try{return n()}finally{r!=t&&s.updateState(r),a!=s.dom&&a&&a.focus()}}function zYs(s,t,n){let r=t.selection,a=n=="up"?r.$from:r.$to;return Zqt(s,t,()=>{let{node:i}=s.docView.domFromPos(a.pos,n=="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=Yqt(s,a.pos,1);for(let o=i.firstChild;o;o=o.nextSibling){let c;if(Fl(o))c=o.getClientRects();else if(S0(o))c=EA(o,0,o.nodeValue.length).getClientRects();else continue;for(let d=0;du.top+1&&(n=="up"?l.top-u.top>(u.bottom-l.top)*2:u.bottom-l.bottom>(l.bottom-u.top)*2))return!1}}return!0})}const BYs=/[\u0590-\u08ac]/;function $Ys(s,t,n){let{$head:r}=t.selection;if(!r.parent.isTextblock)return!1;let a=r.parentOffset,i=!a,l=a==r.parent.content.size,o=s.domSelection();return o?!BYs.test(r.parent.textContent)||!o.modify?n=="left"||n=="backward"?i:l:Zqt(s,t,()=>{let{focusNode:c,focusOffset:d,anchorNode:u,anchorOffset:h}=s.domSelectionRange(),m=o.caretBidiLevel;o.modify("move",n,"character");let f=r.depth?s.docView.domAfterPos(r.before()):s.dom,{focusNode:g,focusOffset:x}=s.domSelectionRange(),y=g&&!J7(f,g)||c==g&&d==x;try{o.collapse(u,h),c&&(c!=u||d!=h)&&o.extend&&o.extend(c,d)}catch{}return m!=null&&(o.caretBidiLevel=m),y}):r.pos==r.start()||r.pos==r.end()}let Ybt=null,Zbt=null,Xbt=!1;function UYs(s,t,n){return Ybt==t&&Zbt==n?Xbt:(Ybt=t,Zbt=n,Xbt=n=="up"||n=="down"?zYs(s,t,n):$Ys(s,t,n))}const ik=0,Qbt=1,f8=2,lC=3;class uie{constructor(t,n,r,a){this.parent=t,this.children=n,this.dom=r,this.contentDOM=a,this.dirty=ik,r.pmViewDesc=this}matchesWidget(t){return!1}matchesMark(t){return!1}matchesNode(t,n,r){return!1}matchesHack(t){return!1}parseRule(t){return null}stopEvent(t){return!1}get size(){let t=0;for(let n=0;nlb(this.contentDOM);else if(this.contentDOM&&this.contentDOM!=this.dom&&this.dom.contains(this.contentDOM))a=!!(t.compareDocumentPosition(this.contentDOM)&4);else if(this.dom.firstChild){if(n==0)for(let i=t;;i=i.parentNode){if(i==this.dom){a=!1;break}if(i.previousSibling)break}if(a==null&&n==t.childNodes.length)for(let i=t;;i=i.parentNode){if(i==this.dom){a=!0;break}if(i.nextSibling)break}}return a??r>0?this.posAtEnd:this.posAtStart}nearestDesc(t,n=!1){for(let r=!0,a=t;a;a=a.parentNode){let i=this.getDesc(a),l;if(i&&(!n||i.node))if(r&&(l=i.nodeDOM)&&!(Fl(l)?J7(l,t):l==t))r=!1;else return i}}getDesc(t){let n=t.pmViewDesc;for(let r=n;r;r=r.parent)if(r==this)return n}posFromDOM(t,n,r){for(let a=t;a;a=a.parentNode){let i=this.getDesc(a);if(i)return i.localPosFromDOM(t,n,r)}return-1}descAt(t){for(let n=0,r=0;nt){a=t-i;break}i=o}if(a)return this.children[r].domFromPos(a-this.children[r].border,n);for(;r>0;r--){let i=this.children[r-1];if(i.size||!(i instanceof Qqt||i instanceof Xqt&&i.side>=0))break}if(n<=0){let i,l=!0;for(;i=r?this.children[r-1]:null,!(!i||i.dom.parentNode==this.contentDOM);r--,l=!1);return i&&n&&l&&!i.border&&!i.domAtom?i.domFromPos(i.size,n):{node:this.contentDOM,offset:i?lb(i.dom)+1:0}}else{let i,l=!0;for(;i=r=u&&n<=d-c.border&&c.node&&c.contentDOM&&this.contentDOM.contains(c.contentDOM))return c.parseRange(t,n,u);t=l;for(let h=o;h>0;h--){let m=this.children[h-1];if(m.size&&m.dom.parentNode==this.contentDOM&&!m.emptyChildAt(1)){a=lb(m.dom)+1;break}t-=m.size}a==-1&&(a=0)}if(a>-1&&(d>n||o==this.children.length-1)){n=d;for(let u=o+1;ug&&ln){let g=o;o=c,c=g}let f=document.createRange();f.setEnd(c.node,c.offset),f.setStart(o.node,o.offset),d.removeAllRanges(),d.addRange(f)}}ignoreMutation(t){return!this.contentDOM&&t.type!="selection"}get contentLost(){return this.contentDOM&&this.contentDOM!=this.dom&&!this.dom.contains(this.contentDOM)}markDirty(t,n){for(let r=0,a=0;a=r:tr){let o=r+i.border,c=l-i.border;if(t>=o&&n<=c){this.dirty=t==r||n==l?f8:Qbt,t==o&&n==c&&(i.contentLost||i.dom.parentNode!=this.contentDOM)?i.dirty=lC:i.markDirty(t-o,n-o);return}else i.dirty=i.dom==i.contentDOM&&i.dom.parentNode==this.contentDOM&&!i.children.length?f8:lC}r=l}this.dirty=f8}markParentsDirty(){let t=1;for(let n=this.parent;n;n=n.parent,t++){let r=t==1?f8:Qbt;n.dirty{if(!i)return a;if(i.parent)return i.parent.posBeforeChild(i)})),!n.type.spec.raw){let o=Fl(l)?l:document.createElement("span");o!=l&&o.appendChild(l),o.hasAttribute("contenteditable")||(o.contentEditable="false"),o.classList.add("ProseMirror-widget")}super(t,[],l,null),this.widget=n,this.widget=n,i=this}matchesWidget(t){return this.dirty==ik&&t.type.eq(this.widget.type)}parseRule(){return{ignore:!0}}stopEvent(t){let n=this.widget.spec.stopEvent;return n?n(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 qYs extends uie{constructor(t,n,r,a){super(t,[],n,null),this.textDOM=r,this.text=a}get size(){return this.text.length}localPosFromDOM(t,n){return t!=this.textDOM?this.posAtStart+(n?this.size:0):this.posAtStart+n}domFromPos(t){return{node:this.textDOM,offset:t}}ignoreMutation(t){return t.type==="characterData"&&t.target.nodeValue==t.oldValue}}class cL extends uie{constructor(t,n,r,a,i){super(t,[],r,a),this.mark=n,this.spec=i}static create(t,n,r,a){let i=a.nodeViews[n.type.name],l=i&&i(n,a,r);return(!l||!l.dom)&&(l=GB.renderSpec(document,n.type.spec.toDOM(n,r),null,n.attrs)),new cL(t,n,l.dom,l.contentDOM||l.dom,l)}parseRule(){return this.dirty&lC||this.mark.type.spec.reparseInView?null:{mark:this.mark.type.name,attrs:this.mark.attrs,contentElement:this.contentDOM}}matchesMark(t){return this.dirty!=lC&&this.mark.eq(t)}markDirty(t,n){if(super.markDirty(t,n),this.dirty!=ik){let r=this.parent;for(;!r.node;)r=r.parent;r.dirty0&&(i=lWe(i,0,t,r));for(let o=0;o{if(!c)return l;if(c.parent)return c.parent.posBeforeChild(c)},r,a),u=d&&d.dom,h=d&&d.contentDOM;if(n.isText){if(!u)u=document.createTextNode(n.text);else if(!S0(u))throw new RangeError("Text must be rendered as a DOM text node")}else u||({dom:u,contentDOM:h}=GB.renderSpec(document,n.type.spec.toDOM(n),null,n.attrs));!h&&!n.isText&&u.nodeName!="BR"&&(u.hasAttribute("contenteditable")||(u.contentEditable="false"),n.type.spec.draggable&&(u.draggable=!0));let m=u;return u=tVt(u,r,n),d?c=new VYs(t,n,r,a,u,h||null,m,d):n.isText?new O6e(t,n,r,a,u,m):new dL(t,n,r,a,u,h||null,m)}parseRule(t){if(this.node.type.spec.reparseInView)return null;let n={node:this.node.type.name,attrs:this.node.attrs};if(this.node.type.whitespace=="pre"&&(n.preserveWhitespace="full"),!this.contentDOM)n.getContent=()=>this.node.content;else if(!this.contentLost)n.contentElement=this.contentDOM;else{for(let r=this.children.length-1;r>=0;r--){let a=this.children[r];if(this.dom.contains(a.dom.parentNode)){n.contentElement=a.dom.parentNode;break}}if(!n.contentElement){let r=t&&t.find(a=>Fl(a)&&t.indexOf(a.parentNode)<0&&this.dom.contains(a));r?n.contentElement=r:n.getContent=()=>hi.empty}}return n}matchesNode(t,n,r){return this.dirty==ik&&t.eq(this.node)&&rTe(n,this.outerDeco)&&r.eq(this.innerDeco)}get size(){return this.node.nodeSize}get border(){return this.node.isLeaf?0:1}updateChildren(t,n){let r=this.node.inlineContent,a=n,i=t.composing?this.localCompositionInfo(t,n):null,l=i&&i.pos>-1?i:null,o=i&&i.pos<0,c=new GYs(this,l&&l.node,t),d=this.node.inlineContent,u=d&&this.node.isBlock;YYs(this.node,this.innerDeco,(h,m,f)=>{h.spec.marks?c.syncToMarks(h.spec.marks,r,t,m):h.type.side>=0&&!f&&c.syncToMarks(m==this.node.childCount?kf.none:this.node.child(m).marks,r,t,m),c.placeWidget(h,t,a)},(h,m,f,g)=>{c.syncToMarks(h.marks,r,t,g),u&&h.isAtom&&!h.isText&&c.addHackNode("IMG",c.top);let x;c.findNodeMatch(h,m,f,g)||o&&t.state.selection.from>a&&t.state.selection.to-1&&c.updateNodeAt(h,m,f,x,t)||c.updateNextNode(h,m,f,t,g,a)||c.addNode(h,m,f,t,a),a+=h.nodeSize,d&&(u=h.isAtom&&!h.isText)}),c.syncToMarks([],r,t,0),this.node.isTextblock&&c.addTextblockHacks(),c.destroyRest(),(c.changed||this.dirty==f8)&&(l&&this.protectLocalComposition(t,l),Jqt(this.contentDOM,this.children,t),FG&&ZYs(this.dom))}localCompositionInfo(t,n){let{from:r,to:a}=t.state.selection;if(!(t.state.selection instanceof Al)||rn+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=XYs(this.node.content,l,r-n,a-n);return o<0?null:{node:i,pos:o,text:l}}else return{node:i,pos:-1,text:""}}protectLocalComposition(t,{node:n,pos:r,text:a}){if(this.getDesc(n))return;let i=n;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 qYs(this,i,n,a);t.input.compositionNodes.push(l),this.children=lWe(this.children,r,r+a.length,t,l)}update(t,n,r,a){return this.dirty==lC||!t.sameMarkup(this.node)?!1:(this.updateInner(t,n,r,a),!0)}updateInner(t,n,r,a){this.updateOuterDeco(n),this.node=t,this.innerDeco=r,this.contentDOM&&this.updateChildren(a,this.posAtStart),this.dirty=ik}updateOuterDeco(t){if(rTe(t,this.outerDeco))return;let n=!Fl(this.nodeDOM),r=this.dom;this.dom=eVt(this.dom,this.nodeDOM,oWe(this.outerDeco,this.node,n),oWe(t,this.node,n)),this.dom!=r&&(r.pmViewDesc=void 0,this.dom.pmViewDesc=this),this.outerDeco=t}selectNode(){Fl(this.nodeDOM)&&(this.nodeDOM.classList.add("ProseMirror-selectednode"),(this.contentDOM||!this.node.type.spec.draggable)&&(this.nodeDOM.draggable=!0))}deselectNode(){Fl(this.nodeDOM)&&(this.nodeDOM.classList.remove("ProseMirror-selectednode"),(this.contentDOM||!this.node.type.spec.draggable)&&this.nodeDOM.removeAttribute("draggable"))}get domAtom(){return this.node.isAtom}}function Jbt(s,t,n,r,a){tVt(r,t,s);let i=new dL(void 0,s,t,n,r,r,r);return i.contentDOM&&i.updateChildren(a,0),i}class O6e extends dL{constructor(t,n,r,a,i,l){super(t,n,r,a,i,null,l)}parseRule(){let t=this.nodeDOM.parentNode;for(;t&&t!=this.dom&&!t.pmIsDeco;)t=t.parentNode;return{skip:t||!0}}update(t,n,r,a){return this.dirty==lC||this.dirty!=ik&&!this.inParent()||!t.sameMarkup(this.node)?!1:(this.updateOuterDeco(n),(this.dirty!=ik||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=ik,!0)}inParent(){let t=this.parent.contentDOM;for(let n=this.nodeDOM;n;n=n.parentNode)if(n==t)return!0;return!1}domFromPos(t){return{node:this.nodeDOM,offset:t}}localPosFromDOM(t,n,r){return t==this.nodeDOM?this.posAtStart+Math.min(n,this.node.text.length):super.localPosFromDOM(t,n,r)}ignoreMutation(t){return t.type!="characterData"&&t.type!="selection"}slice(t,n,r){let a=this.node.cut(t,n),i=document.createTextNode(a.text);return new O6e(this.parent,a,this.outerDeco,this.innerDeco,i,i)}markDirty(t,n){super.markDirty(t,n),this.dom!=this.nodeDOM&&(t==0||n==this.nodeDOM.nodeValue.length)&&(this.dirty=lC)}get domAtom(){return!1}isText(t){return this.node.text==t}}class Qqt extends uie{parseRule(){return{ignore:!0}}matchesHack(t){return this.dirty==ik&&this.dom.nodeName==t}get domAtom(){return!0}get ignoreForCoords(){return this.dom.nodeName=="IMG"}}class VYs extends dL{constructor(t,n,r,a,i,l,o,c){super(t,n,r,a,i,l,o),this.spec=c}update(t,n,r,a){if(this.dirty==lC)return!1;if(this.spec.update&&(this.node.type==t.type||this.spec.multiType)){let i=this.spec.update(t,n,r);return i&&this.updateInner(t,n,r,a),i}else return!this.contentDOM&&!t.isLeaf?!1:super.update(t,n,r,a)}selectNode(){this.spec.selectNode?this.spec.selectNode():super.selectNode()}deselectNode(){this.spec.deselectNode?this.spec.deselectNode():super.deselectNode()}setSelection(t,n,r,a){this.spec.setSelection?this.spec.setSelection(t,n,r.root):super.setSelection(t,n,r,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 Jqt(s,t,n){let r=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 u=cL.create(this.top,t[l],n,r);this.top.children.splice(this.index,0,u),this.top=u,this.changed=!0}this.index=0,l++}}findNodeMatch(t,n,r,a){let i=-1,l;if(a>=this.preMatch.index&&(l=this.preMatch.matches[a-this.preMatch.index]).parent==this.top&&l.matchesNode(t,n,r))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(r){let d=n.children[r-1];if(d instanceof cL)n=d,r=d.children.length;else{o=d,r--;break}}else{if(n==t)break e;r=n.parent.children.indexOf(n),n=n.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 KYs(s,t){return s.type.side-t.type.side}function YYs(s,t,n,r){let a=t.locals(s),i=0;if(a.length==0){for(let d=0;di;)o.push(a[l++]);let g=i+m.nodeSize;if(m.isText){let y=g;l!y.inline):o.slice();r(m,x,t.forChild(i,m),f),i=g}}function ZYs(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 XYs(s,t,n,r){for(let a=0,i=0;a=n){if(i>=r&&c.slice(r-t.length-o,r-o)==t)return r-t.length;let d=o=0&&d+t.length+o>=n)return o+d;if(n==r&&c.length>=r+t.length-o&&c.slice(r-o,r-o+t.length)==t)return r}}return-1}function lWe(s,t,n,r,a){let i=[];for(let l=0,o=0;l=n||u<=t?i.push(c):(dn&&i.push(c.slice(n-d,c.size,r)))}return i}function jnt(s,t=null){let n=s.domSelectionRange(),r=s.state.doc;if(!n.focusNode)return null;let a=s.docView.nearestDesc(n.focusNode),i=a&&a.size==0,l=s.docView.posFromDOM(n.focusNode,n.focusOffset,1);if(l<0)return null;let o=r.resolve(l),c,d;if(D6e(n)){for(c=l;a&&!a.node;)a=a.parent;if(a&&a.node.isAtom&&El.isSelectable(a.node)&&a.parent&&!(a.node.isInline&&NYs(n.focusNode,n.focusOffset,a.dom))){let h=a.posBefore;d=new El(l==h?o:r.resolve(h))}else if(_2&&t=="key"&&l>s.state.selection.to&&Fl(n.focusNode)&&n.focusOffset==n.focusNode.childNodes.length&&a&&a.posAtStart>s.state.selection.to)for(let h=n.focusNode;;h=h.parentNode){if(getComputedStyle(h).overflow!="visible"){d=oc.findFrom(r.resolve(a.posAtStart),1);break}if(h==a.dom||h.nextSibling||!h.parentNode||!Fl(h.parentNode))break}}else{if(n instanceof s.dom.ownerDocument.defaultView.Selection&&n.rangeCount>1){let h=l,m=l;for(let f=0;f{(n.anchorNode!=r||n.anchorOffset!=a)&&(t.removeEventListener("selectionchange",s.input.hideSelectionGuard),setTimeout(()=>{(!sVt(s)||s.state.selection.visible)&&s.dom.classList.remove("ProseMirror-hideselection")},20))})}function JYs(s){let t=s.domSelection();if(!t)return;let n=s.cursorWrapper.dom,r=n.nodeName=="IMG";r?t.collapse(n.parentNode,lb(n)+1):t.collapse(n,0),!r&&!s.state.selection.visible&&Fw&&lL<=11&&(n.disabled=!0,n.disabled=!1)}function nVt(s,t){if(t instanceof El){let n=s.docView.descAt(t.from);n!=s.lastSelectedViewDesc&&(r1t(s),n&&n.selectNode(),s.lastSelectedViewDesc=n)}else r1t(s)}function r1t(s){s.lastSelectedViewDesc&&(s.lastSelectedViewDesc.parent&&s.lastSelectedViewDesc.deselectNode(),s.lastSelectedViewDesc=void 0)}function Nnt(s,t,n,r){return s.someProp("createSelectionBetween",a=>a(s,t,n))||Al.between(t,n,r)}function a1t(s){return s.editable&&!s.hasFocus()?!1:rVt(s)}function rVt(s){let t=s.domSelectionRange();if(!t.anchorNode)return!1;try{return J7(s.dom,t.anchorNode)&&(s.editable||J7(s.dom,t.focusNode))}catch{return!1}}function eZs(s){let t=s.docView.domFromPos(s.state.selection.anchor,0),n=s.domSelectionRange();return Q7(t.node,t.offset,n.anchorNode,n.anchorOffset)}function cWe(s,t){let{$anchor:n,$head:r}=s.selection,a=t>0?n.max(r):n.min(r),i=a.parent.inlineContent?a.depth?s.doc.resolve(t>0?a.after():a.before()):null:a;return i&&oc.findFrom(i,t)}function pP(s,t){return s.dispatch(s.state.tr.setSelection(t).scrollIntoView()),!0}function i1t(s,t,n){let r=s.state.selection;if(r instanceof Al)if(n.indexOf("s")>-1){let{$head:a}=r,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 pP(s,new Al(r.$anchor,l))}else if(r.empty){if(s.endOfTextblock(t>0?"forward":"backward")){let a=cWe(s.state,t);return a&&a instanceof El?pP(s,a):!1}else if(!(TN&&n.indexOf("m")>-1)){let a=r.$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?El.isSelectable(i)?pP(s,new El(t<0?s.state.doc.resolve(a.pos-i.nodeSize):a)):pP(s,new Al(s.state.doc.resolve(t<0?o:o+i.nodeSize))):!1}}else return!1;else{if(r instanceof El&&r.node.isInline)return pP(s,new Al(t>0?r.$to:r.$from));{let a=cWe(s.state,t);return a?pP(s,a):!1}}}function Lee(s,t){let n=s.pmViewDesc;return n?n.size==0&&(t<0||s.nextSibling||s.nodeName!="BR"):Fl(s)&&s.contentEditable=="false"}function A$(s,t){return t<0?tZs(s):sZs(s)}function tZs(s){let t=s.domSelectionRange(),n=t.focusNode,r=t.focusOffset;if(!n)return;let a,i,l=!1;for(_2&&Fl(n)&&r0){if(!Fl(n))break;let o=n.childNodes[r-1];if(Lee(o,-1))a=n,i=--r;else if(S0(o))n=o,r=n.nodeValue.length;else break}else{if(aVt(n))break;{let o=n.previousSibling;for(;o&&Lee(o,-1);)a=n.parentNode,i=lb(o),o=o.previousSibling;if(o)n=o,r=p1(n);else{if(n=n.parentNode,n==s.dom)break;r=0}}}l?dWe(s,n,r):a&&dWe(s,a,i)}function sZs(s){let t=s.domSelectionRange(),n=t.focusNode,r=t.focusOffset;if(!n)return;let a=p1(n),i,l;for(;;)if(r{s.state==a&&GE(s)},50)}function o1t(s,t){let n=s.state.doc.resolve(t);if(!(gb||Vqt)&&n.parent.inlineContent){let a=s.coordsAtPos(t);if(t>n.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 l1t(s,t,n){let r=s.state.selection;if(r instanceof Al&&!r.empty||n.indexOf("s")>-1||TN&&n.indexOf("m")>-1)return!1;let{$from:a,$to:i}=r;if(!a.parent.inlineContent||s.endOfTextblock(t<0?"up":"down")){let l=cWe(s.state,t);if(l&&l instanceof El)return pP(s,l)}if(!a.parent.inlineContent){let l=t<0?a:i,o=r instanceof b2?oc.near(l,t):oc.findFrom(l,t);return o?pP(s,o):!1}return!1}function c1t(s,t){if(!(s.state.selection instanceof Al))return!0;let{$head:n,$anchor:r,empty:a}=s.state.selection;if(!n.sameParent(r))return!0;if(!a)return!1;if(s.endOfTextblock(t>0?"forward":"backward"))return!0;let i=!n.textOffset&&(t<0?n.nodeBefore:n.nodeAfter);if(i&&!i.isText){let l=s.state.tr;return t<0?l.delete(n.pos-i.nodeSize,n.pos):l.delete(n.pos,n.pos+i.nodeSize),s.dispatch(l),!0}return!1}function d1t(s,t,n){s.domObserver.stop(),t.contentEditable=n,s.domObserver.start()}function aZs(s){if(!A1||s.state.selection.$head.parentOffset>0)return!1;let{focusNode:t,focusOffset:n}=s.domSelectionRange();if(t&&Fl(t)&&n==0&&t.firstChild&&Fl(t.firstChild)&&t.firstChild.contentEditable=="false"){let r=t.firstChild;d1t(s,r,"true"),setTimeout(()=>d1t(s,r,"false"),20)}return!1}function iZs(s){let t="";return s.ctrlKey&&(t+="c"),s.metaKey&&(t+="m"),s.altKey&&(t+="a"),s.shiftKey&&(t+="s"),t}function oZs(s,t){let n=t.keyCode,r=iZs(t);if(n==8||TN&&n==72&&r=="c")return c1t(s,-1)||A$(s,-1);if(n==46&&!t.shiftKey||TN&&n==68&&r=="c")return c1t(s,1)||A$(s,1);if(n==13||n==27)return!0;if(n==37||TN&&n==66&&r=="c"){let a=n==37?o1t(s,s.state.selection.from)=="ltr"?-1:1:-1;return i1t(s,a,r)||A$(s,a)}else if(n==39||TN&&n==70&&r=="c"){let a=n==39?o1t(s,s.state.selection.from)=="ltr"?1:-1:1;return i1t(s,a,r)||A$(s,a)}else{if(n==38||TN&&n==80&&r=="c")return l1t(s,-1,r)||A$(s,-1);if(n==40||TN&&n==78&&r=="c")return aZs(s)||l1t(s,1,r)||A$(s,1);if(r==(TN?"m":"c")&&(n==66||n==73||n==89||n==90))return!0}return!1}function knt(s,t){s.someProp("transformCopied",f=>{t=f(t,s)});let n=[],{content:r,openStart:a,openEnd:i}=t;for(;a>1&&i>1&&r.childCount==1&&r.firstChild.childCount==1;){a--,i--;let f=r.firstChild;n.push(f.type.name,f.attrs!=f.type.defaultAttrs?f.attrs:null),r=f.content}let l=s.someProp("clipboardSerializer")||GB.fromSchema(s.state.schema),o=uVt(),c=o.createElement("div");c.appendChild(l.serializeFragment(r,{document:o}));let d=c.firstChild,u,h=0;for(;d&&Fl(d)&&(u=dVt[d.nodeName.toLowerCase()]);){for(let f=u.length-1;f>=0;f--){let g=o.createElement(u[f]);for(;c.firstChild;)g.appendChild(c.firstChild);c.appendChild(g),h++}d=c.firstChild}d&&Fl(d)&&d.setAttribute("data-pm-slice",`${a} ${i}${h?` -${h}`:""} ${JSON.stringify(n)}`);let m=s.someProp("clipboardTextSerializer",f=>f(t,s))||t.content.textBetween(0,t.content.size,` `);return{dom:c,text:m,slice:t}}function iVt(s,t,n,r,a){let i=a.parent.type.spec.code,l,o;if(!n&&!t)return null;let c=!!t&&(r||i||!n);if(c){if(s.someProp("transformPastedText",m=>{t=m(t,i||r,s)}),i)return o=new Ki(hi.from(s.state.schema.text(t.replace(/\r\n?/g,` `))),0,0),s.someProp("transformPasted",m=>{o=m(o,s,!0)}),o;let h=s.someProp("clipboardTextParser",m=>m(t,a,r,s));if(h)o=h;else{let m=a.marks(),{schema:f}=s.state,g=GB.fromSchema(f);l=document.createElement("div"),t.split(/(?:\r\n?|\n)+/).forEach(x=>{let y=l.appendChild(document.createElement("p"));x&&y.appendChild(g.serializeNode(f.text(x,m)))})}}else s.someProp("transformPastedHTML",h=>{n=h(n,s)}),l=uZs(n),F6e&&hZs(l);let d=l&&l.querySelector("[data-pm-slice]"),u=d&&/^(\d+) (\d+)(?: -(\d+))? (.*)/.exec(d.getAttribute("data-pm-slice")||"");if(u&&u[3])for(let h=+u[3];h>0;h--){let m=l.firstChild;for(;m&&!Fl(m);)m=m.nextSibling;if(!m)break;l=m}if(o||(o=(s.someProp("clipboardParser")||s.someProp("domParser")||Mee.fromSchema(s.state.schema)).parseSlice(l,{preserveWhitespace:!!(c||u),context:a,ruleFromNode(m){return m.nodeName=="BR"&&!m.nextSibling&&m.parentNode&&!lZs.test(m.parentNode.nodeName)?{ignore:!0}:null}})),u)o=mZs(u1t(o,+u[1],+u[2]),u[4]);else if(o=Ki.maxOpen(cZs(o.content,a),!0),o.openStart||o.openEnd){let h=0,m=0;for(let f=o.content.firstChild;h{o=h(o,s,c)}),o}const lZs=/^(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 cZs(s,t){if(s.childCount<2)return s;for(let n=t.depth;n>=0;n--){let a=t.node(n).contentMatchAt(t.index(n)),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&&lVt(c,i,o,l[l.length-1],0))l[l.length-1]=d;else{l.length&&(l[l.length-1]=cVt(l[l.length-1],i.length));let u=oVt(o,c);l.push(u),a=a.matchType(u.type),i=c}}),l)return hi.from(l)}return s}function oVt(s,t,n=0){for(let r=t.length-1;r>=n;r--)s=t[r].create(null,hi.from(s));return s}function lVt(s,t,n,r,a){if(a1&&(i=0),a=n&&(o=t<0?l.contentMatchAt(0).fillBefore(o,i<=a).append(o):o.append(l.contentMatchAt(l.childCount).fillBefore(hi.empty,!0))),s.replaceChild(t<0?0:s.childCount-1,l.copy(o))}function u1t(s,t,n){return tn})}return FZ.createHTML(s)}function uZs(s){let t=/^(\s*]*>)*/.exec(s);t&&(s=s.slice(t[0].length));let n=uVt(),r=n.body,a=/<([a-z][^>\s]+)/i.exec(s),i;if((i=a&&dVt[a[1].toLowerCase()])&&(s=i.map(l=>"<"+l+">").join("")+s+i.map(l=>"").reverse().join("")),r.innerHTML=dZs(s),i)for(let l=0;l=0;o-=2){let c=n.nodes[r[o]];if(!c||c.hasRequiredAttrs())break;try{a=hi.from(c.create(r[o+1],a))}catch{break}i++,l++}return new Ki(a,i,l)}const R_={},D_={},fZs={touchstart:!0,touchmove:!0};class pZs{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 gZs(s){for(let t in R_){let n=R_[t];s.dom.addEventListener(t,s.input.eventHandlers[t]=r=>{yZs(s,r)&&!Snt(s,r)&&(s.editable||!(r.type in D_))&&n(s,r)},fZs[t]?{passive:!0}:void 0)}A1&&s.dom.addEventListener("input",()=>null),hWe(s)}function wE(s,t){s.input.lastSelectionOrigin=t,s.input.lastSelectionTime=Date.now()}function xZs(s){s.input.mouseDown&&s.input.mouseDown.done(),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 hWe(s){s.someProp("handleDOMEvents",t=>{for(let n in t)s.input.eventHandlers[n]||s.dom.addEventListener(n,s.input.eventHandlers[n]=r=>Snt(s,r))})}function Snt(s,t){return s.someProp("handleDOMEvents",n=>{let r=n[t.type];return r?r(s,t)||t.defaultPrevented:!1})}function yZs(s,t){if(!t.bubbles)return!0;if(t.defaultPrevented)return!1;for(let n=t.target;n!=s.dom;n=n.parentNode)if(!n||n.nodeType==11||n.pmViewDesc&&n.pmViewDesc.stopEvent(t))return!1;return!0}function vZs(s,t){!Snt(s,t)&&R_[t.type]&&(s.editable||!(t.type in D_))&&R_[t.type](s,t)}D_.keydown=(s,t)=>{let n=t;if(s.input.shiftKey=n.keyCode==16||n.shiftKey,!pVt(s)&&(s.input.lastKeyCode=n.keyCode,s.input.lastKeyCodeTime=Date.now(),!(_E&&gb&&n.keyCode==13)))if(n.keyCode!=229&&s.domObserver.forceFlush(),FG&&n.keyCode==13&&!n.ctrlKey&&!n.altKey&&!n.metaKey){let r=Date.now();s.input.lastIOSEnter=r,s.input.lastIOSEnterFallbackTimeout=setTimeout(()=>{s.input.lastIOSEnter==r&&(s.someProp("handleKeyDown",a=>a(s,XO(13,"Enter"))),s.input.lastIOSEnter=0)},200)}else s.someProp("handleKeyDown",r=>r(s,n))||oZs(s,n)?n.preventDefault():wE(s,"key")};D_.keyup=(s,t)=>{t.keyCode==16&&(s.input.shiftKey=!1)};D_.keypress=(s,t)=>{let n=t;if(pVt(s)||!n.charCode||n.ctrlKey&&!n.altKey||TN&&n.metaKey)return;if(s.someProp("handleKeyPress",a=>a(s,n))){n.preventDefault();return}let r=s.state.selection;if(!(r instanceof Al)||!r.$from.sameParent(r.$to)){let a=String.fromCharCode(n.charCode),i=()=>s.state.tr.insertText(a).scrollIntoView();!/[\r\n]/.test(a)&&!s.someProp("handleTextInput",l=>l(s,r.$from.pos,r.$to.pos,a,i))&&s.dispatch(i()),n.preventDefault()}};function hie(s){return{left:s.clientX,top:s.clientY}}function bZs(s,t){let n=t.x-s.clientX,r=t.y-s.clientY;return n*n+r*r<100}function Cnt(s,t,n,r,a){if(r==-1)return!1;let i=s.state.doc.resolve(r);for(let l=i.depth+1;l>0;l--)if(s.someProp(t,o=>l>i.depth?o(s,n,i.nodeAfter,i.before(l),a,!0):o(s,n,i.node(l),i.before(l),a,!1)))return!0;return!1}function mie(s,t,n){if(s.focused||s.focus(),s.state.selection.eq(t))return;let r=s.state.tr.setSelection(t);r.setMeta("pointer",!0),s.dispatch(r)}function _Zs(s,t){if(t==-1)return!1;let n=s.state.doc.resolve(t),r=n.nodeAfter;return r&&r.isAtom&&El.isSelectable(r)?(mie(s,new El(n)),!0):!1}function wZs(s,t){if(t==-1)return!1;let n=s.state.selection,r,a;n instanceof El&&(r=n.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(El.isSelectable(o)){r&&n.$from.depth>0&&l>=n.$from.depth&&i.before(n.$from.depth+1)==n.$from.pos?a=i.before(n.$from.depth):a=i.before(l);break}}return a!=null?(mie(s,El.create(s.state.doc,a)),!0):!1}function jZs(s,t,n,r,a){return Cnt(s,"handleClickOn",t,n,r)||s.someProp("handleClick",i=>i(s,t,r))||(a?wZs(s,n):_Zs(s,n))}function NZs(s,t,n,r){return Cnt(s,"handleDoubleClickOn",t,n,r)||s.someProp("handleDoubleClick",a=>a(s,t,r))}function kZs(s,t,n,r){return Cnt(s,"handleTripleClickOn",t,n,r)||s.someProp("handleTripleClick",a=>a(s,t,r))||SZs(s,n,r)}function SZs(s,t,n){if(n.button!=0)return!1;let r=hVt(s,t,!0),a=s.state.doc;return r?(mie(s,r),r instanceof Al&&a.eq(s.state.doc)&&(s.input.mouseDown=new AZs(s,r)),!0):!1}function hVt(s,t,n){let r=s.state.doc;if(t==-1)return r.inlineContent?Al.create(r,0,r.content.size):null;let a=r.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)return Al.create(r,o+1,o+1+l.content.size);if(n&&El.isSelectable(l))return El.create(r,o)}return null}function Ant(s){return aTe(s)}const mVt=TN?"metaKey":"ctrlKey";R_.mousedown=(s,t)=>{let n=t;s.input.shiftKey=n.shiftKey;let r=Ant(s),a=Date.now(),i="singleClick";a-s.input.lastClick.time<500&&bZs(n,s.input.lastClick)&&!n[mVt]&&s.input.lastClick.button==n.button&&(s.input.lastClick.type=="singleClick"?i="doubleClick":s.input.lastClick.type=="doubleClick"&&(i="tripleClick")),s.input.lastClick={time:a,x:n.clientX,y:n.clientY,type:i,button:n.button},s.input.mouseDown&&s.input.mouseDown.done();let l=s.posAtCoords(hie(n));l&&(i=="singleClick"?s.input.mouseDown=new CZs(s,l,n,!!r):(i=="doubleClick"?NZs:kZs)(s,l.pos,l.inside,n)?n.preventDefault():wE(s,"pointer"))};class fVt{constructor(t){this.view=t,this.mightDrag=null,t.root.addEventListener("mouseup",this.up=this.up.bind(this)),t.root.addEventListener("mousemove",this.move=this.move.bind(this))}up(t){this.done()}move(t){t.buttons==0&&this.done()}done(){this.view.root.removeEventListener("mouseup",this.up),this.view.root.removeEventListener("mousemove",this.move),this.view.input.mouseDown==this&&(this.view.input.mouseDown=null)}delaySelUpdate(){return!1}}class CZs extends fVt{constructor(t,n,r,a){super(t),this.pos=n,this.event=r,this.flushed=a,this.delayedSelectionSync=!1,this.startDoc=t.state.doc,this.selectNode=!!r[mVt],this.allowDefault=r.shiftKey;let i,l;if(n.inside>-1)i=t.state.doc.nodeAt(n.inside),l=n.inside;else{let u=t.state.doc.resolve(n.pos);i=u.parent,l=u.depth?u.before():0}const o=a?null:r.target,c=o?t.docView.nearestDesc(o,!0):null;this.target=c&&Fl(c.nodeDOM)?c.nodeDOM:null;let{selection:d}=t.state;r.button==0&&(i.type.spec.draggable&&i.type.spec.selectable!==!1||d instanceof El&&d.from<=l&&d.to>l)&&(this.mightDrag={node:i,pos:l,addAttr:!!(this.target&&!this.target.draggable),setUneditable:!!(this.target&&_2&&!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()),wE(t,"pointer")}done(){super.done(),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(()=>{this.view.isDestroyed||GE(this.view)})}up(t){if(this.done(),!this.view.dom.contains(t.target))return;let n=this.pos;this.view.state.doc!=this.startDoc&&(n=this.view.posAtCoords(hie(t))),this.updateAllowDefault(t),this.allowDefault||!n?wE(this.view,"pointer"):jZs(this.view,n.pos,n.inside,t,this.selectNode)?t.preventDefault():t.button==0&&(this.flushed||A1&&this.mightDrag&&!this.mightDrag.node.isAtom||gb&&!this.view.state.selection.visible&&Math.min(Math.abs(n.pos-this.view.state.selection.from),Math.abs(n.pos-this.view.state.selection.to))<=2)?(mie(this.view,oc.near(this.view.state.doc.resolve(n.pos))),t.preventDefault()):wE(this.view,"pointer")}move(t){this.updateAllowDefault(t),wE(this.view,"pointer"),super.move(t)}updateAllowDefault(t){!this.allowDefault&&(Math.abs(this.event.x-t.clientX)>4||Math.abs(this.event.y-t.clientY)>4)&&(this.allowDefault=!0)}delaySelUpdate(){return this.allowDefault?(this.delayedSelectionSync=!0,!0):!1}}class AZs extends fVt{constructor(t,n){super(t),this.startSelection=n,this.startDoc=t.state.doc}move(t){if(t.buttons==0||this.view.isDestroyed||!this.view.state.doc.eq(this.startDoc)){this.done();return}t.preventDefault(),wE(this.view,"pointer");let n=this.view.posAtCoords(hie(t)),r=n&&hVt(this.view,n.inside,!1);if(!r)return;let{doc:a}=this.view.state,i=this.startSelection,[l,o]=r.from{s.input.lastTouch=Date.now(),Ant(s),wE(s,"pointer")};R_.touchmove=s=>{s.input.lastTouch=Date.now(),wE(s,"pointer")};R_.contextmenu=s=>Ant(s);function pVt(s,t){return s.composing?!0:A1&&Math.abs(Date.now()-s.input.compositionEndedAt)<500?(s.input.compositionEndedAt=-2e8,!0):!1}const EZs=_E?5e3:-1;D_.compositionstart=D_.compositionupdate=s=>{if(!s.composing){s.domObserver.flush();let{state:t}=s,n=t.selection.$to;if(t.selection instanceof Al&&t.selection.empty&&(t.storedMarks||!n.textOffset&&n.parentOffset&&n.nodeBefore.marks.some(r=>r.type.spec.inclusive===!1)||gb&&Vqt&&TZs(s)))s.markCursor=s.state.storedMarks||n.marks(),aTe(s,!0),s.markCursor=null;else if(aTe(s,!t.selection.empty),_2&&t.selection.empty&&n.parentOffset&&!n.textOffset&&n.nodeBefore.marks.length){let r=s.domSelectionRange();for(let a=r.focusNode,i=r.focusOffset;a&&Fl(a)&&i!=0;){let l=i<0?a.lastChild:a.childNodes[i-1];if(!l)break;if(S0(l)){let o=s.domSelection();o&&o.collapse(l,l.nodeValue.length);break}else a=l,i=-1}}s.input.composing=!0}gVt(s,EZs)};function TZs(s){let{focusNode:t,focusOffset:n}=s.domSelectionRange();if(!t||!Fl(t)||n>=t.childNodes.length)return!1;let r=t.childNodes[n];return Fl(r)&&r.contentEditable=="false"}D_.compositionend=(s,t)=>{s.composing&&(s.input.composing=!1,s.input.compositionEndedAt=Date.now(),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++,gVt(s,20))};function gVt(s,t){clearTimeout(s.input.composingTimeout),t>-1&&(s.input.composingTimeout=setTimeout(()=>aTe(s),t))}function xVt(s){for(s.composing&&(s.input.composing=!1,s.input.compositionEndedAt=Date.now());s.input.compositionNodes.length>0;)s.input.compositionNodes.pop().markParentsDirty()}function MZs(s){let t=s.domSelectionRange();if(!t.focusNode)return null;let n=wYs(t.focusNode,t.focusOffset),r=jYs(t.focusNode,t.focusOffset);if(n&&r&&n!=r){let a=r.pmViewDesc,i=s.domObserver.lastChangedTextNode;if(n==i||r==i)return i;if(!a||!a.isText(r.nodeValue))return r;if(s.input.compositionNode==r){let l=n.pmViewDesc;if(!(!l||!l.isText(n.nodeValue)))return r}}return n||r}function aTe(s,t=!1){if(!(_E&&s.domObserver.flushingSoon>=0)){if(s.domObserver.forceFlush(),xVt(s),t||s.docView&&s.docView.dirty){let n=jnt(s),r=s.state.selection;return n&&!n.eq(r)?s.dispatch(s.state.tr.setSelection(n)):(s.markCursor||t)&&!r.$from.node(r.$from.sharedDepth(r.to)).inlineContent?s.dispatch(s.state.tr.deleteSelection()):s.updateState(s.state),!0}return!1}}function PZs(s,t){if(!s.dom.parentNode)return;let n=s.dom.parentNode.appendChild(document.createElement("div"));n.appendChild(t),n.style.cssText="position: fixed; left: -10000px; top: 10px";let r=getSelection(),a=document.createRange();a.selectNodeContents(t),s.dom.blur(),r.removeAllRanges(),r.addRange(a),setTimeout(()=>{n.parentNode&&n.parentNode.removeChild(n),s.focus()},50)}const bse=Fw&&lL<15||FG&&CYs<604;R_.copy=D_.cut=(s,t)=>{let n=t,r=s.state.selection,a=n.type=="cut";if(r.empty)return;let i=bse?null:n.clipboardData,l=r.content(),{dom:o,text:c}=knt(s,l);i?(n.preventDefault(),i.clearData(),i.setData("text/html",o.innerHTML),i.setData("text/plain",c)):PZs(s,o),a&&s.dispatch(s.state.tr.deleteSelection().scrollIntoView().setMeta("uiEvent","cut"))};function IZs(s){return s.openStart==0&&s.openEnd==0&&s.content.childCount==1?s.content.firstChild:null}function LZs(s,t){if(!s.dom.parentNode)return;let n=s.input.shiftKey||s.state.selection.$from.parent.type.spec.code,r=s.dom.parentNode.appendChild(document.createElement(n?"textarea":"div"));n||(r.contentEditable="true"),r.style.cssText="position: fixed; left: -10000px; top: 10px",r.focus();let a=s.input.shiftKey&&s.input.lastKeyCode!=45;setTimeout(()=>{s.focus(),r.parentNode&&r.parentNode.removeChild(r),n?_se(s,r.value,null,a,t):_se(s,r.textContent,r.innerHTML,a,t)},50)}function _se(s,t,n,r,a){let i=iVt(s,t,n,r,s.state.selection.$from);if(s.someProp("handlePaste",c=>c(s,a,i||Ki.empty)))return!0;if(!i)return!1;let l=IZs(i),o=l?s.state.tr.replaceSelectionWith(l,r):s.state.tr.replaceSelection(i);return s.dispatch(o.scrollIntoView().setMeta("paste",!0).setMeta("uiEvent","paste")),!0}function yVt(s){let t=s.getData("text/plain")||s.getData("Text");if(t)return t;let n=s.getData("text/uri-list");return n?n.replace(/\r?\n/g," "):""}D_.paste=(s,t)=>{let n=t;if(s.composing&&!_E)return;let r=bse?null:n.clipboardData,a=s.input.shiftKey&&s.input.lastKeyCode!=45;r&&_se(s,yVt(r),r.getData("text/html"),a,n)?n.preventDefault():LZs(s,n)};class vVt{constructor(t,n,r){this.slice=t,this.move=n,this.node=r}}const RZs=TN?"altKey":"ctrlKey";function bVt(s,t){let n;return s.someProp("dragCopies",r=>{n=n||r(t)}),n!=null?!n:!t[RZs]}R_.dragstart=(s,t)=>{let n=t,r=s.input.mouseDown;if(r&&r.done(),!n.dataTransfer)return;let a=s.state.selection,i=a.empty?null:s.posAtCoords(hie(n)),l;if(!(i&&i.pos>=a.from&&i.pos<=(a instanceof El?a.to-1:a.to))){if(r&&r.mightDrag)l=El.create(s.state.doc,r.mightDrag.pos);else if(n.target&&Fl(n.target)){let h=s.docView.nearestDesc(n.target,!0);h&&h.node.type.spec.draggable&&h!=s.docView&&(l=El.create(s.state.doc,h.posBefore))}}let o=(l||s.state.selection).content(),{dom:c,text:d,slice:u}=knt(s,o);(!n.dataTransfer.files.length||!gb||qqt>120)&&n.dataTransfer.clearData(),n.dataTransfer.setData(bse?"Text":"text/html",c.innerHTML),n.dataTransfer.effectAllowed="copyMove",bse||n.dataTransfer.setData("text/plain",d),s.dragging=new vVt(u,bVt(s,n),l)};R_.dragend=s=>{let t=s.dragging;window.setTimeout(()=>{s.dragging==t&&(s.dragging=null)},50)};D_.dragover=D_.dragenter=(s,t)=>t.preventDefault();D_.drop=(s,t)=>{try{DZs(s,t,s.dragging)}finally{s.dragging=null}};function DZs(s,t,n){if(!t.dataTransfer)return;let r=s.posAtCoords(hie(t));if(!r)return;let a=s.state.doc.resolve(r.pos),i=n&&n.slice;i?s.someProp("transformPasted",f=>{i=f(i,s,!1)}):i=iVt(s,yVt(t.dataTransfer),bse?null:t.dataTransfer.getData("text/html"),!1,a);let l=!!(n&&bVt(s,t));if(s.someProp("handleDrop",f=>f(s,t,i||Ki.empty,l))){t.preventDefault();return}if(!i)return;t.preventDefault();let o=i?Lqt(s.state.doc,a.pos,i):a.pos;o==null&&(o=a.pos);let c=s.state.tr;if(l){let{node:f}=n;f?f.replace(c):c.deleteSelection()}let d=c.mapping.map(o),u=i.openStart==0&&i.openEnd==0&&i.content.childCount==1,h=c.doc;if(u?c.replaceRangeWith(d,d,i.content.firstChild):c.replaceRange(d,d,i),c.doc.eq(h))return;let m=c.doc.resolve(d);if(u&&El.isSelectable(i.content.firstChild)&&m.nodeAfter&&m.nodeAfter.sameMarkup(i.content.firstChild))c.setSelection(new El(m));else{let f=c.mapping.map(o);c.mapping.maps[c.mapping.maps.length-1].forEach((g,x,y,v)=>f=v),c.setSelection(Nnt(s,m,c.doc.resolve(f)))}s.focus(),s.dispatch(c.setMeta("uiEvent","drop"))}R_.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())&&GE(s)},20))};R_.blur=(s,t)=>{let n=t;s.focused&&(s.domObserver.stop(),s.dom.classList.remove("ProseMirror-focused"),s.domObserver.start(),n.relatedTarget&&s.dom.contains(n.relatedTarget)&&s.domObserver.currentSelection.clear(),s.focused=!1)};R_.beforeinput=(s,t)=>{if(_E&&t.inputType=="deleteContentBackward"){s.domObserver.flushSoon();let{domChangeCount:r}=s.input;setTimeout(()=>{if(s.input.domChangeCount!=r||(s.dom.blur(),s.focus(),s.someProp("handleKeyDown",i=>i(s,XO(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 D_)R_[s]=D_[s];function wse(s,t){if(s==t)return!0;for(let n in s)if(s[n]!==t[n])return!1;for(let n in t)if(!(n in s))return!1;return!0}class iTe{constructor(t,n){this.toDOM=t,this.spec=n||p7,this.side=this.spec.side||0}map(t,n,r,a){let{pos:i,deleted:l}=t.mapResult(n.from+a,this.side<0?-1:1);return l?null:new __(i-r,i-r,this)}valid(){return!0}eq(t){return this==t||t instanceof iTe&&(this.spec.key&&this.spec.key==t.spec.key||this.toDOM==t.toDOM&&wse(this.spec,t.spec))}destroy(t){this.spec.destroy&&this.spec.destroy(t)}}class uL{constructor(t,n){this.attrs=t,this.spec=n||p7}map(t,n,r,a){let i=t.map(n.from+a,this.spec.inclusiveStart?-1:1)-r,l=t.map(n.to+a,this.spec.inclusiveEnd?1:-1)-r;return i>=l?null:new __(i,l,this)}valid(t,n){return n.from=t&&(!i||i(o.spec))&&r.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,n-o,r,a+o,i)}}map(t,n,r){return this==d1||t.maps.length==0?this:this.mapInner(t,n,0,0,r||p7)}mapInner(t,n,r,a,i){let l;for(let o=0;o{let d=c+r,u;if(u=wVt(n,o,d)){for(a||(a=this.children.slice());io&&h.to=t){this.children[o]==t&&(r=this.children[o+2]);break}let i=t+1,l=i+n.content.size;for(let o=0;oi&&c.type instanceof uL){let d=Math.max(i,c.from)-i,u=Math.min(l,c.to)-i;da.map(t,n,p7));return AP.from(r)}forChild(t,n){if(n.isLeaf)return vx.empty;let r=[];for(let a=0;an instanceof vx)?t:t.reduce((n,r)=>n.concat(r instanceof vx?r:r.members),[]))}}forEachSet(t){for(let n=0;n{let y=x-g-(f-m);for(let v=0;vb+u-h)continue;let w=o[v]+u-h;f>=w?o[v+1]=m<=w?-2:-1:m>=u&&y&&(o[v]+=y,o[v+1]+=y)}h+=y}),u=n.maps[d].map(u,-1)}let c=!1;for(let d=0;d=r.content.size){c=!0;continue}let m=n.map(s[d+1]+i,-1),f=m-a,{index:g,offset:x}=r.content.findIndex(h),y=r.maybeChild(g);if(y&&x==h&&x+y.nodeSize==f){let v=o[d+2].mapInner(n,y,u+1,s[d]+i+1,l);v!=d1?(o[d]=h,o[d+1]=f,o[d+2]=v):(o[d+1]=-2,c=!0)}else c=!0}if(c){let d=OZs(o,s,t,n,a,i,l),u=oTe(d,r,0,l);t=u.local;for(let h=0;hn&&l.to{let d=wVt(s,o,c+n);if(d){i=!0;let u=oTe(d,o,n+c+1,r);u!=d1&&a.push(c,c+o.nodeSize,u)}});let l=_Vt(i?jVt(s):s,-n).sort(g7);for(let o=0;o0;)t++;s.splice(t,0,n)}function uBe(s){let t=[];return s.someProp("decorations",n=>{let r=n(s.state);r&&r!=d1&&t.push(r)}),s.cursorWrapper&&t.push(vx.create(s.state.doc,[s.cursorWrapper.deco])),AP.from(t)}const zZs={childList:!0,characterData:!0,characterDataOldValue:!0,attributes:!0,attributeOldValue:!0,subtree:!0},BZs=Fw&&lL<=11;class $Zs{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 UZs{constructor(t,n){this.view=t,this.handleDOMChange=n,this.queue=[],this.flushingSoon=-1,this.observer=null,this.currentSelection=new $Zs,this.onCharData=null,this.suppressingSelectionUpdates=!1,this.lastChangedTextNode=null,this.observer=window.MutationObserver&&new window.MutationObserver(r=>{for(let a=0;aa.type=="childList"&&a.removedNodes.length||a.type=="characterData"&&a.oldValue.length>a.target.nodeValue.length)?this.flushSoon():A1&&t.composing&&r.some(a=>a.type=="childList"&&a.target.nodeName=="TR")?(t.input.badSafariComposition=!0,this.flushSoon()):this.flush()}),BZs&&(this.onCharData=r=>{this.queue.push({target:r.target,type:"characterData",oldValue:r.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,zZs)),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 n=0;nthis.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(a1t(this.view)){if(this.suppressingSelectionUpdates)return GE(this.view);if(Fw&&lL<=11&&!this.view.state.selection.empty){let t=this.view.domSelectionRange();if(t.focusNode&&Q7(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 n=new Set,r;for(let i=t.focusNode;i;i=DG(i))n.add(i);for(let i=t.anchorNode;i;i=DG(i))if(n.has(i)){r=i;break}let a=r&&this.view.docView.nearestDesc(r);if(a&&a.ignoreMutation({type:"selection",target:S0(r)?r.parentNode:r}))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 n=this.pendingRecords();n.length&&(this.queue=[]);let r=t.domSelectionRange(),a=!this.suppressingSelectionUpdates&&!this.currentSelection.eq(r)&&a1t(t)&&!this.ignoreSelectionChange(r),i=-1,l=-1,o=!1,c=[];if(t.editable)for(let u=0;uu.nodeName=="BR")&&(t.input.lastKeyCode==8||t.input.lastKeyCode==46||gb&&(t.composing||t.input.compositionEndedAt>Date.now()-50)&&n.some(u=>u.type=="childList"&&u.removedNodes.length))){for(let u of c)if(u.nodeName=="BR"&&u.parentNode){let h=u.nextSibling;for(;h&&Fl(h);){if(h.contentEditable=="false"){u.parentNode.removeChild(u);break}h=h.firstChild}}}else if(_2&&c.length){let u=c.filter(h=>h.nodeName=="BR");if(u.length==2){let[h,m]=u;h.parentNode&&h.parentNode.parentNode==m.parentNode?m.remove():h.remove()}else{let{focusNode:h}=this.currentSelection;for(let m of u){let f=m.parentNode;f&&f.nodeName=="LI"&&(!h||HZs(t,h)!=f)&&m.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),qZs(t)),t.input.badSafariComposition&&(t.input.badSafariComposition=!1,GZs(t,c)),this.handleDOMChange(i,l,o,c),t.docView&&t.docView.dirty?t.updateState(t.state):this.currentSelection.eq(r)||GE(t),this.currentSelection.set(r))}registerMutation(t,n){if(n.indexOf(t.target)>-1)return null;let r=this.view.docView.nearestDesc(t.target);if(t.type=="attributes"&&(r==this.view.docView||t.attributeName=="contenteditable"||t.attributeName=="style"&&!t.oldValue&&!t.target.getAttribute("style"))||!r||r.ignoreMutation(t))return null;if(t.type=="childList"){for(let u=0;ui;v--){let b=a.childNodes[v-1],w=b.pmViewDesc;if(b.nodeName=="BR"&&!w){l=v;break}if(!w||w.size)break}let m=s.state.doc,f=s.someProp("domParser")||Mee.fromSchema(s.state.schema),g=m.resolve(o),x=null,y=f.parse(a,{topNode:g.parent,topMatch:g.parent.contentMatchAt(g.index()),topOpen:!0,from:i,to:l,preserveWhitespace:g.parent.type.whitespace=="pre"?"full":!0,findPositions:u,ruleFromNode:KZs(r),context:g});if(u&&u[0].pos!=null){let v=u[0].pos,b=u[1]&&u[1].pos;b==null&&(b=v),x={anchor:v+o,head:b+o}}return{doc:y,sel:x,from:o,to:c}}const KZs=s=>t=>{let n=t.pmViewDesc;if(n)return n.parseRule(s);if(t.nodeName=="BR"&&t.parentNode){if(A1&&/^(ul|ol)$/i.test(t.parentNode.nodeName)){let r=document.createElement("div");return r.appendChild(document.createElement("li")),{skip:r}}else if(t.parentNode.lastChild==t||A1&&/^(tr|table)$/i.test(t.parentNode.nodeName))return{ignore:!0}}else if(t.nodeName=="IMG"&&t.getAttribute("mark-placeholder"))return{ignore:!0};return null},YZs=/^(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 ZZs(s,t,n,r,a){let i=s.input.compositionPendingChanges||(s.composing?s.input.compositionID:0);if(s.input.compositionPendingChanges=0,t<0){let I=s.input.lastSelectionTime>Date.now()-50?s.input.lastSelectionOrigin:null,P=jnt(s,I);if(P&&!s.state.selection.eq(P)){if(gb&&_E&&s.input.lastKeyCode===13&&Date.now()-100D(s,XO(13,"Enter"))))return;let R=s.state.tr.setSelection(P);I=="pointer"?R.setMeta("pointer",!0):I=="key"&&R.scrollIntoView(),i&&R.setMeta("composition",i),s.dispatch(R)}return}let l=s.state.doc.resolve(t),o=l.sharedDepth(n);t=l.before(o+1),n=s.state.doc.resolve(n).after(o+1);let c=s.state.selection,d=WZs(s,t,n,a),u=s.state.doc,h=u.slice(d.from,d.to),m,f;s.input.lastKeyCode===8&&Date.now()-100Date.now()-225||_E)&&a.some(I=>Fl(I)&&!YZs.test(I.nodeName))&&(!g||g.endA>=g.endB)&&s.someProp("handleKeyDown",I=>I(s,XO(13,"Enter")))){s.input.lastIOSEnter=0;return}if(!g)if(r&&c instanceof Al&&!c.empty&&c.$head.sameParent(c.$anchor)&&!s.composing&&!(d.sel&&d.sel.anchor!=d.sel.head))g={start:c.from,endA:c.to,endB:c.to};else{if(d.sel){let I=g1t(s,s.state.doc,d.sel);if(I&&!I.eq(s.state.selection)){let P=s.state.tr.setSelection(I);i&&P.setMeta("composition",i),s.dispatch(P)}}return}s.state.selection.froms.state.selection.from&&g.start<=s.state.selection.from+2&&s.state.selection.from>=d.from?g.start=s.state.selection.from:g.endA=s.state.selection.to-2&&s.state.selection.to<=d.to&&(g.endB+=s.state.selection.to-g.endA,g.endA=s.state.selection.to)),Fw&&lL<=11&&g.endB==g.start+1&&g.endA==g.start&&g.start>d.from&&d.doc.textBetween(g.start-d.from-1,g.start-d.from+1)=="  "&&(g.start--,g.endA--,g.endB--);let x=d.doc.resolveNoCache(g.start-d.from),y=d.doc.resolveNoCache(g.endB-d.from),v=u.resolve(g.start),b=x.sameParent(y)&&x.parent.inlineContent&&v.end()>=g.endA;if((FG&&s.input.lastIOSEnter>Date.now()-225&&(!b||a.some(I=>I.nodeName=="DIV"||I.nodeName=="P"))||!b&&JZs(d.doc,x.pos,y.pos))&&s.someProp("handleKeyDown",I=>I(s,XO(13,"Enter")))){s.input.lastIOSEnter=0;return}if(s.state.selection.anchor>g.start&&QZs(u,g.start,g.endA,x,y)&&s.someProp("handleKeyDown",I=>I(s,XO(8,"Backspace")))){_E&&gb&&s.domObserver.suppressSelectionUpdates();return}gb&&g.endB==g.start&&(s.input.lastChromeDelete=Date.now()),_E&&!b&&x.start()!=y.start()&&y.parentOffset==0&&x.depth==y.depth&&d.sel&&d.sel.anchor==d.sel.head&&d.sel.head==g.endA&&(g.endB-=2,y=d.doc.resolveNoCache(g.endB-d.from),setTimeout(()=>{s.someProp("handleKeyDown",function(I){return I(s,XO(13,"Enter"))})},20));let w=g.start,S=g.endA,C=I=>{let P=I||s.state.tr.replace(w,S,d.doc.slice(g.start-d.from,g.endB-d.from));if(d.sel){let R=g1t(s,P.doc,d.sel);R&&!(gb&&s.composing&&R.empty&&(g.start!=g.endB||s.input.lastChromeDeleteGE(s),20));let I=C(s.state.tr.delete(w,S)),P=u.resolve(g.start).marksAcross(u.resolve(g.endA));P&&I.ensureMarks(P),s.dispatch(I)}else if(g.endA==g.endB&&(E=XZs(x.parent.content.cut(x.parentOffset,y.parentOffset),v.parent.content.cut(v.parentOffset,g.endA-v.start())))){let I=C(s.state.tr);E.type=="add"?I.addMark(w,S,E.mark):I.removeMark(w,S,E.mark),s.dispatch(I)}else if(x.parent.child(x.index()).isText&&x.index()==y.index()-(y.textOffset?0:1)){let I=x.parent.textBetween(x.parentOffset,y.parentOffset),P=()=>C(s.state.tr.insertText(I,w,S));s.someProp("handleTextInput",R=>R(s,w,S,I,P))||s.dispatch(P())}else s.dispatch(C());else s.dispatch(C())}function g1t(s,t,n){return Math.max(n.anchor,n.head)>t.content.size?null:Nnt(s,t.resolve(n.anchor),t.resolve(n.head))}function XZs(s,t){let n=s.firstChild.marks,r=t.firstChild.marks,a=n,i=r,l,o,c;for(let u=0;uu.mark(o.addToSet(u.marks));else if(a.length==0&&i.length==1)o=i[0],l="remove",c=u=>u.mark(o.removeFromSet(u.marks));else return null;let d=[];for(let u=0;un||hBe(l,!0,!1){i.isTextblock&&l>=t&&l0&&(t||s.indexAfter(r)==s.node(r).childCount);)r--,a++,t=!1;if(n){let i=s.node(r).maybeChild(s.indexAfter(r));for(;i&&!i.isLeaf;)i=i.firstChild,a++}return a}function eXs(s,t,n,r,a){let i=s.findDiffStart(t,n),l=n+s.size,o=n+t.size;if(i==null)return null;let{a:c,b:d}=s.findDiffEnd(t,l,o);if(a=="end"){let u=Math.max(0,i-Math.min(c,d));r-=c+u-i}if(c=c?i-r:0;i-=u,d=i+(d-c),c=i}else if(d=d?i-r:0;i-=u,c=i+(c-d),d=i}return{start:i,endA:c,endB:d}}class NVt{constructor(t,n){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 pZs,this.prevDirectPlugins=[],this.pluginViews=[],this.requiresGeckoHackNode=!1,this.dragging=null,this._props=n,this.state=n.state,this.directPlugins=n.plugins||[],this.directPlugins.forEach(_1t),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=v1t(this),y1t(this),this.nodeViews=b1t(this),this.docView=Jbt(this.state.doc,x1t(this),uBe(this),this.dom,this),this.domObserver=new UZs(this,(r,a,i,l)=>ZZs(this,r,a,i,l)),this.domObserver.start(),gZs(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 n in t)this._props[n]=t[n];this._props.state=this.state}return this._props}update(t){t.handleDOMEvents!=this._props.handleDOMEvents&&hWe(this);let n=this._props;this._props=t,t.plugins&&(t.plugins.forEach(_1t),this.directPlugins=t.plugins),this.updateStateInner(t.state,n)}setProps(t){let n={};for(let r in this._props)n[r]=this._props[r];n.state=this.state;for(let r in t)n[r]=t[r];this.update(n)}updateState(t){this.updateStateInner(t,this._props)}updateStateInner(t,n){var r;let a=this.state,i=!1,l=!1;t.storedMarks&&this.composing&&(xVt(this),l=!0),this.state=t;let o=a.plugins!=t.plugins||this._props.plugins!=n.plugins;if(o||this._props.plugins!=n.plugins||this._props.nodeViews!=n.nodeViews){let f=b1t(this);sXs(f,this.nodeViews)&&(this.nodeViews=f,i=!0)}(o||n.handleDOMEvents!=this._props.handleDOMEvents)&&hWe(this),this.editable=v1t(this),y1t(this);let c=uBe(this),d=x1t(this),u=a.plugins!=t.plugins&&!a.doc.eq(t.doc)?"reset":t.scrollToSelection>a.scrollToSelection?"to selection":"preserve",h=i||!this.docView.matchesNode(t.doc,d,c);(h||!t.selection.eq(a.selection))&&(l=!0);let m=u=="preserve"&&l&&this.dom.style.overflowAnchor==null&&TYs(this);if(l){this.domObserver.stop();let f=h&&(Fw||gb)&&!this.composing&&!a.selection.empty&&!t.selection.empty&&tXs(a.selection,t.selection);if(h){let x=gb?this.trackWrites=this.domSelectionRange().focusNode:null;this.composing&&(this.input.compositionNode=MZs(this)),(i||!this.docView.update(t.doc,d,c,this))&&(this.docView.updateOuterDeco(d),this.docView.destroy(),this.docView=Jbt(t.doc,d,c,this.dom,this)),x&&(!this.trackWrites||!this.dom.contains(this.trackWrites))&&(f=!0)}let g=this.input.mouseDown;f||!(g&&this.domObserver.currentSelection.eq(this.domSelectionRange())&&eZs(this)&&g.delaySelUpdate())?GE(this,f):(nVt(this,t.selection),this.domObserver.setCurSelection()),this.domObserver.start()}this.updatePluginViews(a),!((r=this.dragging)===null||r===void 0)&&r.node&&!a.doc.eq(t.doc)&&this.updateDraggedNode(this.dragging,a),u=="reset"?this.dom.scrollTop=0:u=="to selection"?this.scrollToSelection():m&&MYs(m)}scrollToSelection(){let t=this.domSelectionRange().focusNode;if(!(!t||!J7(this.dom,t))){if(!this.someProp("handleScrollToSelection",n=>n(this)))if(this.state.selection instanceof El){let n=this.docView.domAfterPos(this.state.selection.from);Fl(n)&&Kbt(this,n.getBoundingClientRect(),t)}else Kbt(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 n=0;n0&&in.ownerDocument.getSelection()),this._root=n}return t||document}updateRoot(){this._root=null}posAtCoords(t){return FYs(this,t)}coordsAtPos(t,n=1){return Yqt(this,t,n)}domAtPos(t,n=0){return this.docView.domFromPos(t,n)}nodeDOM(t){let n=this.docView.descAt(t);return n?n.nodeDOM:null}posAtDOM(t,n,r=-1){let a=this.docView.posFromDOM(t,n,r);if(a==null)throw new RangeError("DOM position not inside the editor");return a}endOfTextblock(t,n){return UYs(this,n||this.state,t)}pasteHTML(t,n){return _se(this,"",t,!1,n||new ClipboardEvent("paste"))}pasteText(t,n){return _se(this,t,null,!0,n||new ClipboardEvent("paste"))}serializeForClipboard(t){return knt(this,t)}destroy(){this.docView&&(xZs(this),this.destroyPluginViews(),this.mounted?(this.docView.update(this.state.doc,[],uBe(this),this),this.dom.textContent=""):this.dom.parentNode&&this.dom.parentNode.removeChild(this.dom),this.docView.destroy(),this.docView=null,bYs())}get isDestroyed(){return this.docView==null}dispatchEvent(t){return vZs(this,t)}domSelectionRange(){let t=this.dom.isConnected!==!1&&this.domSelection();return t?A1&&this.root.nodeType===11&&kYs(this.dom.ownerDocument)==this.dom&&VZs(this,t)||t:{focusNode:null,focusOffset:0,anchorNode:null,anchorOffset:0}}domSelection(){return this.root.getSelection()}}NVt.prototype.dispatch=function(s){let t=this._props.dispatchTransaction;t?t.call(this,s):this.updateState(this.state.apply(s))};function x1t(s){let t=Object.create(null);return t.class="ProseMirror",t.contenteditable=String(s.editable),s.someProp("attributes",n=>{if(typeof n=="function"&&(n=n(s.state)),n)for(let r in n)r=="class"?t.class+=" "+n[r]:r=="style"?t.style=(t.style?t.style+";":"")+n[r]:!t[r]&&r!="contenteditable"&&r!="nodeName"&&(t[r]=String(n[r]))}),t.translate||(t.translate="no"),[__.node(0,s.state.doc.content.size,t)]}function y1t(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:__.widget(s.state.selection.from,t,{raw:!0,marks:s.markCursor})}}else s.cursorWrapper=null}function v1t(s){return!s.someProp("editable",t=>t(s.state)===!1)}function tXs(s,t){let n=Math.min(s.$anchor.sharedDepth(s.head),t.$anchor.sharedDepth(t.head));return s.$anchor.start(n)!=t.$anchor.start(n)}function b1t(s){let t=Object.create(null);function n(r){for(let a in r)Object.prototype.hasOwnProperty.call(t,a)||(t[a]=r[a])}return s.someProp("nodeViews",n),s.someProp("markViews",n),t}function sXs(s,t){let n=0,r=0;for(let a in s){if(s[a]!=t[a])return!0;n++}for(let a in t)r++;return n!=r}function _1t(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 DL={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:"'"},lTe={48:")",49:"!",50:"@",51:"#",52:"$",53:"%",54:"^",55:"&",56:"*",57:"(",59:":",61:"+",173:"_",186:":",187:"+",188:"<",189:"_",190:">",191:"?",192:"~",219:"{",220:"|",221:"}",222:'"'},nXs=typeof navigator<"u"&&/Mac/.test(navigator.platform),rXs=typeof navigator<"u"&&/MSIE \d|Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(navigator.userAgent);for(var cb=0;cb<10;cb++)DL[48+cb]=DL[96+cb]=String(cb);for(var cb=1;cb<=24;cb++)DL[cb+111]="F"+cb;for(var cb=65;cb<=90;cb++)DL[cb]=String.fromCharCode(cb+32),lTe[cb]=String.fromCharCode(cb);for(var mBe in DL)lTe.hasOwnProperty(mBe)||(lTe[mBe]=DL[mBe]);function aXs(s){var t=nXs&&s.metaKey&&s.shiftKey&&!s.ctrlKey&&!s.altKey||rXs&&s.shiftKey&&s.key&&s.key.length==1||s.key=="Unidentified",n=!t&&s.key||(s.shiftKey?lTe:DL)[s.keyCode]||s.key||"Unidentified";return n=="Esc"&&(n="Escape"),n=="Del"&&(n="Delete"),n=="Left"&&(n="ArrowLeft"),n=="Up"&&(n="ArrowUp"),n=="Right"&&(n="ArrowRight"),n=="Down"&&(n="ArrowDown"),n}const iXs=typeof navigator<"u"&&/Mac|iP(hone|[oa]d)/.test(navigator.platform),oXs=typeof navigator<"u"&&/Win/.test(navigator.platform);function lXs(s){let t=s.split(/-(?!$)/),n=t[t.length-1];n=="Space"&&(n=" ");let r,a,i,l;for(let o=0;os.selection.empty?!1:(t&&t(s.tr.deleteSelection().scrollIntoView()),!0);function kVt(s,t){let{$cursor:n}=s.selection;return!n||(t?!t.endOfTextblock("backward",s):n.parentOffset>0)?null:n}const SVt=(s,t,n)=>{let r=kVt(s,n);if(!r)return!1;let a=Int(r);if(!a){let l=r.blockRange(),o=l&&yK(l);return o==null?!1:(t&&t(s.tr.lift(l,o).scrollIntoView()),!0)}let i=a.nodeBefore;if(RVt(s,a,t,-1))return!0;if(r.parent.content.size==0&&(OG(i,"end")||El.isSelectable(i)))for(let l=r.depth;;l--){let o=L6e(s.doc,r.before(l),r.after(l),Ki.empty);if(o&&o.slice.size1)break}return i.isAtom&&a.depth==r.depth-1?(t&&t(s.tr.delete(a.pos-i.nodeSize,a.pos).scrollIntoView()),!0):!1},uXs=(s,t,n)=>{let r=kVt(s,n);if(!r)return!1;let a=Int(r);return a?CVt(s,a,t):!1},hXs=(s,t,n)=>{let r=EVt(s,n);if(!r)return!1;let a=Lnt(r);return a?CVt(s,a,t):!1};function CVt(s,t,n){let r=t.nodeBefore,a=r,i=t.pos-1;for(;!a.isTextblock;i--){if(a.type.spec.isolating)return!1;let u=a.lastChild;if(!u)return!1;a=u}let l=t.nodeAfter,o=l,c=t.pos+1;for(;!o.isTextblock;c++){if(o.type.spec.isolating)return!1;let u=o.firstChild;if(!u)return!1;o=u}let d=L6e(s.doc,i,c,Ki.empty);if(!d||d.from!=i||d instanceof Dy&&d.slice.size>=c-i)return!1;if(n){let u=s.tr.step(d);u.setSelection(Al.create(u.doc,i)),n(u.scrollIntoView())}return!0}function OG(s,t,n=!1){for(let r=s;r;r=t=="start"?r.firstChild:r.lastChild){if(r.isTextblock)return!0;if(n&&r.childCount!=1)return!1}return!1}const AVt=(s,t,n)=>{let{$head:r,empty:a}=s.selection,i=r;if(!a)return!1;if(r.parent.isTextblock){if(n?!n.endOfTextblock("backward",s):r.parentOffset>0)return!1;i=Int(r)}let l=i&&i.nodeBefore;return!l||!El.isSelectable(l)?!1:(t&&t(s.tr.setSelection(El.create(s.doc,i.pos-l.nodeSize)).scrollIntoView()),!0)};function Int(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 EVt(s,t){let{$cursor:n}=s.selection;return!n||(t?!t.endOfTextblock("forward",s):n.parentOffset{let r=EVt(s,n);if(!r)return!1;let a=Lnt(r);if(!a)return!1;let i=a.nodeAfter;if(RVt(s,a,t,1))return!0;if(r.parent.content.size==0&&(OG(i,"start")||El.isSelectable(i))){let l=L6e(s.doc,r.before(),r.after(),Ki.empty);if(l&&l.slice.size{let{$head:r,empty:a}=s.selection,i=r;if(!a)return!1;if(r.parent.isTextblock){if(n?!n.endOfTextblock("forward",s):r.parentOffset=0;t--){let n=s.node(t);if(s.index(t)+1{let n=s.selection,r=n instanceof El,a;if(r){if(n.node.isTextblock||!h6(s.doc,n.from))return!1;a=n.from}else if(a=I6e(s.doc,n.from,-1),a==null)return!1;if(t){let i=s.tr.join(a);r&&i.setSelection(El.create(i.doc,a-s.doc.resolve(a).nodeBefore.nodeSize)),t(i.scrollIntoView())}return!0},fXs=(s,t)=>{let n=s.selection,r;if(n instanceof El){if(n.node.isTextblock||!h6(s.doc,n.to))return!1;r=n.to}else if(r=I6e(s.doc,n.to,1),r==null)return!1;return t&&t(s.tr.join(r).scrollIntoView()),!0},pXs=(s,t)=>{let{$from:n,$to:r}=s.selection,a=n.blockRange(r),i=a&&yK(a);return i==null?!1:(t&&t(s.tr.lift(a,i).scrollIntoView()),!0)},PVt=(s,t)=>{let{$head:n,$anchor:r}=s.selection;return!n.parent.type.spec.code||!n.sameParent(r)?!1:(t&&t(s.tr.insertText(` `).scrollIntoView()),!0)};function Rnt(s){for(let t=0;t{let{$head:n,$anchor:r}=s.selection;if(!n.parent.type.spec.code||!n.sameParent(r))return!1;let a=n.node(-1),i=n.indexAfter(-1),l=Rnt(a.contentMatchAt(i));if(!l||!a.canReplaceWith(i,i,l))return!1;if(t){let o=n.after(),c=s.tr.replaceWith(o,o,l.createAndFill());c.setSelection(oc.near(c.doc.resolve(o),1)),t(c.scrollIntoView())}return!0},IVt=(s,t)=>{let n=s.selection,{$from:r,$to:a}=n;if(n instanceof b2||r.parent.inlineContent||a.parent.inlineContent)return!1;let i=Rnt(a.parent.contentMatchAt(a.indexAfter()));if(!i||!i.isTextblock)return!1;if(t){let l=(!r.parentOffset&&a.index(){let{$cursor:n}=s.selection;if(!n||n.parent.content.size)return!1;if(n.depth>1&&n.after()!=n.end(-1)){let i=n.before();if(HE(s.doc,i))return t&&t(s.tr.split(i).scrollIntoView()),!0}let r=n.blockRange(),a=r&&yK(r);return a==null?!1:(t&&t(s.tr.lift(r,a).scrollIntoView()),!0)};function xXs(s){return(t,n)=>{if(t.selection instanceof El&&t.selection.node.isBlock){let{$from:f}=t.selection;return!f.parentOffset||!HE(t.doc,f.pos)?!1:(n&&n(t.tr.split(f.pos).scrollIntoView()),!0)}if(!t.selection.$from.depth)return!1;let r=t.tr;!t.selection.empty&&(t.selection instanceof Al||t.selection instanceof b2)&&r.deleteSelection();let{$from:a}=r.selection,i=r.steps.length,l=[],o,c,d=!1,u=!1;for(let f=a.depth;;f--)if(a.node(f).isBlock){d=a.end(f)==a.pos+(a.depth-f),u=a.start(f)==a.pos-(a.depth-f),c=Rnt(a.node(f-1).contentMatchAt(a.indexAfter(f-1))),l.unshift(d&&c?{type:c}:null),o=f;break}else{if(f==1)return!1;l.unshift(null)}let h=a.pos,m=HE(r.doc,h,l.length,l);if(m||(l[0]=c?{type:c}:null,m=HE(r.doc,h,l.length,l)),!m)return!1;if(r.split(h,l.length,l),!d&&u&&a.node(o).type!=c){let f=r.mapping.slice(i),g=f.map(a.before(o)),x=r.doc.resolve(g);c&&a.node(o-1).canReplaceWith(x.index(),x.index()+1,c)&&r.setNodeMarkup(f.map(a.before(o)),c)}return n&&n(r.scrollIntoView()),!0}}const yXs=xXs(),vXs=(s,t)=>{let{$from:n,to:r}=s.selection,a,i=n.sharedDepth(r);return i==0?!1:(a=n.before(i),t&&t(s.tr.setSelection(El.create(s.doc,a))),!0)};function bXs(s,t,n){let r=t.nodeBefore,a=t.nodeAfter,i=t.index();return!r||!a||!r.type.compatibleContent(a.type)?!1:!r.content.size&&t.parent.canReplace(i-1,i)?(n&&n(s.tr.delete(t.pos-r.nodeSize,t.pos).scrollIntoView()),!0):!t.parent.canReplace(i,i+1)||!(a.isTextblock||h6(s.doc,t.pos))?!1:(n&&n(s.tr.join(t.pos).scrollIntoView()),!0)}function RVt(s,t,n,r){let a=t.nodeBefore,i=t.nodeAfter,l,o,c=a.type.spec.isolating||i.type.spec.isolating;if(!c&&bXs(s,t,n))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(n){let f=t.pos+i.nodeSize,g=hi.empty;for(let v=l.length-1;v>=0;v--)g=hi.from(l[v].create(null,g));g=hi.from(a.copy(g));let x=s.tr.step(new Pv(t.pos-1,f,t.pos,f,new Ki(g,1,0),l.length,!0)),y=x.doc.resolve(f+2*l.length);y.nodeAfter&&y.nodeAfter.type==a.type&&h6(x.doc,y.pos)&&x.join(y.pos),n(x.scrollIntoView())}return!0}let u=i.type.spec.isolating||r>0&&c?null:oc.findFrom(t,1),h=u&&u.$from.blockRange(u.$to),m=h&&yK(h);if(m!=null&&m>=t.depth)return n&&n(s.tr.lift(h,m).scrollIntoView()),!0;if(d&&OG(i,"start",!0)&&OG(a,"end")){let f=a,g=[];for(;g.push(f),!f.isTextblock;)f=f.lastChild;let x=i,y=1;for(;!x.isTextblock;x=x.firstChild)y++;if(f.canReplace(f.childCount,f.childCount,x.content)){if(n){let v=hi.empty;for(let w=g.length-1;w>=0;w--)v=hi.from(g[w].copy(v));let b=s.tr.step(new Pv(t.pos-g.length,t.pos+i.nodeSize,t.pos+y,t.pos+i.nodeSize-y,new Ki(v,g.length,0),0,!0));n(b.scrollIntoView())}return!0}}return!1}function DVt(s){return function(t,n){let r=t.selection,a=s<0?r.$from:r.$to,i=a.depth;for(;a.node(i).isInline;){if(!i)return!1;i--}return a.node(i).isTextblock?(n&&n(t.tr.setSelection(Al.create(t.doc,s<0?a.start(i):a.end(i)))),!0):!1}}const _Xs=DVt(-1),wXs=DVt(1);function jXs(s,t=null){return function(n,r){let{$from:a,$to:i}=n.selection,l=a.blockRange(i),o=l&&vnt(l,s,t);return o?(r&&r(n.tr.wrap(l,o).scrollIntoView()),!0):!1}}function w1t(s,t=null){return function(n,r){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 u=n.doc.resolve(d),h=u.index();a=u.parent.canReplaceWith(h,h+1,s)}})}if(!a)return!1;if(r){let i=n.tr;for(let l=0;l=2&&t.$from.node(t.depth-1).type.compatibleContent(n)&&t.startIndex==0){if(t.$from.index(t.depth-1)==0)return!1;let c=l.resolve(t.start-2);i=new sTe(c,c,t.depth),t.endIndex=0;u--)i=hi.from(n[u].type.create(n[u].attrs,i));s.step(new Pv(t.start-(r?2:0),t.end,t.start,t.end,new Ki(i,0,0),n.length,!0));let l=0;for(let u=0;ul.childCount>0&&l.firstChild.type==s);return i?n?r.node(i.depth-1).type==s?AXs(t,n,s,i):EXs(t,n,i):!0:!1}}function AXs(s,t,n,r){let a=s.tr,i=r.end,l=r.$to.end(r.depth);ix;g--)f-=a.child(g).nodeSize,r.delete(f-1,f+1);let i=r.doc.resolve(n.start),l=i.nodeAfter;if(r.mapping.map(n.end)!=n.start+i.nodeAfter.nodeSize)return!1;let o=n.startIndex==0,c=n.endIndex==a.childCount,d=i.node(-1),u=i.index(-1);if(!d.canReplace(u+(o?0:1),u+1,l.content.append(c?hi.empty:hi.from(a))))return!1;let h=i.pos,m=h+l.nodeSize;return r.step(new Pv(h-(o?1:0),m+(c?1:0),h+1,m-1,new Ki((o?hi.empty:hi.from(a.copy(hi.empty))).append(c?hi.empty:hi.from(a.copy(hi.empty))),o?0:1,c?0:1),o?0:1)),t(r.scrollIntoView()),!0}function TXs(s){return function(t,n){let{$from:r,$to:a}=t.selection,i=r.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(n){let d=c.lastChild&&c.lastChild.type==o.type,u=hi.from(d?s.create():null),h=new Ki(hi.from(s.create(null,hi.from(o.type.create(null,u)))),d?3:1,0),m=i.start,f=i.end;n(t.tr.step(new Pv(m-(d?3:1),f,m,f,h,1,!0)).scrollIntoView())}return!0}}function z6e(s){const{state:t,transaction:n}=s;let{selection:r}=n,{doc:a}=n,{storedMarks:i}=n;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 r},get doc(){return a},get tr(){return r=n.selection,a=n.doc,i=n.storedMarks,n}}}let B6e=class{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:n,state:r}=this,{view:a}=n,{tr:i}=r,l=this.buildProps(i);return Object.fromEntries(Object.entries(t).map(([o,c])=>[o,(...u)=>{const h=c(...u)(l);return!i.getMeta("preventDispatch")&&!this.hasCustomState&&a.dispatch(i),h}]))}get chain(){return()=>this.createChain()}get can(){return()=>this.createCan()}createChain(t,n=!0){const{rawCommands:r,editor:a,state:i}=this,{view:l}=a,o=[],c=!!t,d=t||i.tr,u=()=>(!c&&n&&!d.getMeta("preventDispatch")&&!this.hasCustomState&&l.dispatch(d),o.every(m=>m===!0)),h={...Object.fromEntries(Object.entries(r).map(([m,f])=>[m,(...x)=>{const y=this.buildProps(d,n),v=f(...x)(y);return o.push(v),h}])),run:u};return h}createCan(t){const{rawCommands:n,state:r}=this,a=!1,i=t||r.tr,l=this.buildProps(i,a);return{...Object.fromEntries(Object.entries(n).map(([c,d])=>[c,(...u)=>d(...u)({...l,dispatch:void 0})])),chain:()=>this.createChain(i,a)}}buildProps(t,n=!0){const{rawCommands:r,editor:a,state:i}=this,{view:l}=a,o={tr:t,editor:a,view:l,state:z6e({state:i,transaction:t}),dispatch:n?()=>{}:void 0,chain:()=>this.createChain(t,n),can:()=>this.createCan(t),get commands(){return Object.fromEntries(Object.entries(r).map(([c,d])=>[c,(...u)=>d(...u)(o)]))}};return o}},MXs=class{constructor(){this.callbacks={}}on(t,n){return this.callbacks[t]||(this.callbacks[t]=[]),this.callbacks[t].push(n),this}emit(t,...n){const r=this.callbacks[t];return r&&r.forEach(a=>a.apply(this,n)),this}off(t,n){const r=this.callbacks[t];return r&&(n?this.callbacks[t]=r.filter(a=>a!==n):delete this.callbacks[t]),this}once(t,n){const r=(...a)=>{this.off(t,r),n.apply(this,a)};return this.on(t,r)}removeAllListeners(){this.callbacks={}}};function Uo(s,t,n){return s.config[t]===void 0&&s.parent?Uo(s.parent,t,n):typeof s.config[t]=="function"?s.config[t].bind({...n,parent:s.parent?Uo(s.parent,t,n):null}):s.config[t]}function $6e(s){const t=s.filter(a=>a.type==="extension"),n=s.filter(a=>a.type==="node"),r=s.filter(a=>a.type==="mark");return{baseExtensions:t,nodeExtensions:n,markExtensions:r}}function FVt(s){const t=[],{nodeExtensions:n,markExtensions:r}=$6e(s),a=[...n,...r],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=Uo(l,"addGlobalAttributes",o);if(!c)return;c().forEach(u=>{u.types.forEach(h=>{Object.entries(u.attributes).forEach(([m,f])=>{t.push({type:h,name:m,attribute:{...i,...f}})})})})}),a.forEach(l=>{const o={name:l.name,options:l.options,storage:l.storage},c=Uo(l,"addAttributes",o);if(!c)return;const d=c();Object.entries(d).forEach(([u,h])=>{const m={...i,...h};typeof(m==null?void 0:m.default)=="function"&&(m.default=m.default()),m!=null&&m.isRequired&&(m==null?void 0:m.default)===void 0&&delete m.default,t.push({type:l.name,name:u,attribute:m})})}),t}function Lv(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 ep(...s){return s.filter(t=>!!t).reduce((t,n)=>{const r={...t};return Object.entries(n).forEach(([a,i])=>{if(a==="__proto__"){Object.defineProperty(r,a,{configurable:!0,enumerable:!0,value:i,writable:!0});return}if(!r[a]){r[a]=i;return}if(a==="class"){const o=i?String(i).split(" "):[],c=r[a]?r[a].split(" "):[],d=o.filter(u=>!c.includes(u));r[a]=[...c,...d].join(" ")}else if(a==="style"){const o=i?i.split(";").map(u=>u.trim()).filter(Boolean):[],c=r[a]?r[a].split(";").map(u=>u.trim()).filter(Boolean):[],d=new Map;c.forEach(u=>{const[h,m]=u.split(":").map(f=>f.trim());d.set(h,m)}),o.forEach(u=>{const[h,m]=u.split(":").map(f=>f.trim());d.set(h,m)}),r[a]=Array.from(d.entries()).map(([u,h])=>`${u}: ${h}`).join("; ")}else r[a]=i}),r},{})}function mWe(s,t){return t.filter(n=>n.type===s.type.name).filter(n=>n.attribute.rendered).map(n=>n.attribute.renderHTML?n.attribute.renderHTML(s.attrs)||{}:{[n.name]:s.attrs[n.name]}).reduce((n,r)=>ep(n,r),{})}function OVt(s){return typeof s=="function"}function Nd(s,t=void 0,...n){return OVt(s)?t?s.bind(t)(...n):s(...n):s}function PXs(s={}){return Object.keys(s).length===0&&s.constructor===Object}function IXs(s){return typeof s!="string"?s:s.match(/^[+-]?(?:\d*\.)?\d+$/)?Number(s):s==="true"?!0:s==="false"?!1:s}function j1t(s,t){return"style"in s?s:{...s,getAttrs:n=>{const r=s.getAttrs?s.getAttrs(n):s.attrs;if(r===!1)return!1;const a=t.reduce((i,l)=>{const o=l.attribute.parseHTML?l.attribute.parseHTML(n):IXs(n.getAttribute(l.name));return o==null?i:{...i,[l.name]:o}},{});return{...r,...a}}}}function N1t(s){return Object.fromEntries(Object.entries(s).filter(([t,n])=>t==="attrs"&&PXs(n)?!1:n!=null))}function LXs(s,t){var n;const r=FVt(s),{nodeExtensions:a,markExtensions:i}=$6e(s),l=(n=a.find(d=>Uo(d,"topNode")))===null||n===void 0?void 0:n.name,o=Object.fromEntries(a.map(d=>{const u=r.filter(v=>v.type===d.name),h={name:d.name,options:d.options,storage:d.storage,editor:t},m=s.reduce((v,b)=>{const w=Uo(b,"extendNodeSchema",h);return{...v,...w?w(d):{}}},{}),f=N1t({...m,content:Nd(Uo(d,"content",h)),marks:Nd(Uo(d,"marks",h)),group:Nd(Uo(d,"group",h)),inline:Nd(Uo(d,"inline",h)),atom:Nd(Uo(d,"atom",h)),selectable:Nd(Uo(d,"selectable",h)),draggable:Nd(Uo(d,"draggable",h)),code:Nd(Uo(d,"code",h)),whitespace:Nd(Uo(d,"whitespace",h)),linebreakReplacement:Nd(Uo(d,"linebreakReplacement",h)),defining:Nd(Uo(d,"defining",h)),isolating:Nd(Uo(d,"isolating",h)),attrs:Object.fromEntries(u.map(v=>{var b;return[v.name,{default:(b=v==null?void 0:v.attribute)===null||b===void 0?void 0:b.default}]}))}),g=Nd(Uo(d,"parseHTML",h));g&&(f.parseDOM=g.map(v=>j1t(v,u)));const x=Uo(d,"renderHTML",h);x&&(f.toDOM=v=>x({node:v,HTMLAttributes:mWe(v,u)}));const y=Uo(d,"renderText",h);return y&&(f.toText=y),[d.name,f]})),c=Object.fromEntries(i.map(d=>{const u=r.filter(y=>y.type===d.name),h={name:d.name,options:d.options,storage:d.storage,editor:t},m=s.reduce((y,v)=>{const b=Uo(v,"extendMarkSchema",h);return{...y,...b?b(d):{}}},{}),f=N1t({...m,inclusive:Nd(Uo(d,"inclusive",h)),excludes:Nd(Uo(d,"excludes",h)),group:Nd(Uo(d,"group",h)),spanning:Nd(Uo(d,"spanning",h)),code:Nd(Uo(d,"code",h)),attrs:Object.fromEntries(u.map(y=>{var v;return[y.name,{default:(v=y==null?void 0:y.attribute)===null||v===void 0?void 0:v.default}]}))}),g=Nd(Uo(d,"parseHTML",h));g&&(f.parseDOM=g.map(y=>j1t(y,u)));const x=Uo(d,"renderHTML",h);return x&&(f.toDOM=y=>x({mark:y,HTMLAttributes:mWe(y,u)})),[d.name,f]}));return new jqt({topNode:l,nodes:o,marks:c})}function pBe(s,t){return t.nodes[s]||t.marks[s]||null}function k1t(s,t){return Array.isArray(t)?t.some(n=>(typeof n=="string"?n:n.name)===s.name):t}function Fnt(s,t){const n=GB.fromSchema(t).serializeFragment(s),a=document.implementation.createHTMLDocument().createElement("div");return a.appendChild(n),a.innerHTML}const RXs=(s,t=500)=>{let n="";const r=s.parentOffset;return s.parent.nodesBetween(Math.max(0,r-t),r,(a,i,l,o)=>{var c,d;const u=((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%";n+=a.isAtom&&!a.isText?u:u.slice(0,Math.max(0,r-i))}),n};function Ont(s){return Object.prototype.toString.call(s)==="[object RegExp]"}class U6e{constructor(t){this.find=t.find,this.handler=t.handler}}const DXs=(s,t)=>{if(Ont(t))return t.exec(s);const n=t(s);if(!n)return null;const r=[n.text];return r.index=n.index,r.input=s,r.data=n.data,n.replaceWith&&(n.text.includes(n.replaceWith)||console.warn('[tiptap warn]: "inputRuleMatch.replaceWith" must be part of "inputRuleMatch.text".'),r.push(n.replaceWith)),r};function hde(s){var t;const{editor:n,from:r,to:a,text:i,rules:l,plugin:o}=s,{view:c}=n;if(c.composing)return!1;const d=c.state.doc.resolve(r);if(d.parent.type.spec.code||!((t=d.nodeBefore||d.nodeAfter)===null||t===void 0)&&t.marks.find(m=>m.type.spec.code))return!1;let u=!1;const h=RXs(d)+i;return l.forEach(m=>{if(u)return;const f=DXs(h,m.find);if(!f)return;const g=c.state.tr,x=z6e({state:c.state,transaction:g}),y={from:r-(f[0].length-i.length),to:a},{commands:v,chain:b,can:w}=new B6e({editor:n,state:x});m.handler({state:x,range:y,match:f,commands:v,chain:b,can:w})===null||!g.steps.length||(g.setMeta(o,{transform:g,from:r,to:a,text:i}),c.dispatch(g),u=!0)}),u}function FXs(s){const{editor:t,rules:n}=s,r=new $0({state:{init(){return null},apply(a,i,l){const o=a.getMeta(r);if(o)return o;const c=a.getMeta("applyInputRules");return!!c&&setTimeout(()=>{let{text:u}=c;typeof u=="string"?u=u:u=Fnt(hi.from(u),l.schema);const{from:h}=c,m=h+u.length;hde({editor:t,from:h,to:m,text:u,rules:n,plugin:r})}),a.selectionSet||a.docChanged?null:i}},props:{handleTextInput(a,i,l,o){return hde({editor:t,from:i,to:l,text:o,rules:n,plugin:r})},handleDOMEvents:{compositionend:a=>(setTimeout(()=>{const{$cursor:i}=a.state.selection;i&&hde({editor:t,from:i.pos,to:i.pos,text:"",rules:n,plugin:r})}),!1)},handleKeyDown(a,i){if(i.key!=="Enter")return!1;const{$cursor:l}=a.state.selection;return l?hde({editor:t,from:l.pos,to:l.pos,text:` `,rules:n,plugin:r}):!1}},isInputRules:!0});return r}function OXs(s){return Object.prototype.toString.call(s).slice(8,-1)}function mde(s){return OXs(s)!=="Object"?!1:s.constructor===Object&&Object.getPrototypeOf(s)===Object.prototype}function q6e(s,t){const n={...s};return mde(s)&&mde(t)&&Object.keys(t).forEach(r=>{mde(t[r])&&mde(s[r])?n[r]=q6e(s[r],t[r]):n[r]=t[r]}),n}class xC{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=Nd(Uo(this,"addOptions",{name:this.name}))),this.storage=Nd(Uo(this,"addStorage",{name:this.name,options:this.options}))||{}}static create(t={}){return new xC(t)}configure(t={}){const n=this.extend({...this.config,addOptions:()=>q6e(this.options,t)});return n.name=this.name,n.parent=this.parent,n}extend(t={}){const n=new xC(t);return n.parent=this,this.child=n,n.name=t.name?t.name:n.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: "${n.name}".`),n.options=Nd(Uo(n,"addOptions",{name:n.name})),n.storage=Nd(Uo(n,"addStorage",{name:n.name,options:n.options})),n}static handleExit({editor:t,mark:n}){const{tr:r}=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)===n.name))return!1;const c=l.find(d=>(d==null?void 0:d.type.name)===n.name);return c&&r.removeStoredMark(c),r.insertText(" ",a.pos),t.view.dispatch(r),!0}return!1}}function zXs(s){return typeof s=="number"}class zVt{constructor(t){this.find=t.find,this.handler=t.handler}}const BXs=(s,t,n)=>{if(Ont(t))return[...s.matchAll(t)];const r=t(s,n);return r?r.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 $Xs(s){const{editor:t,state:n,from:r,to:a,rule:i,pasteEvent:l,dropEvent:o}=s,{commands:c,chain:d,can:u}=new B6e({editor:t,state:n}),h=[];return n.doc.nodesBetween(r,a,(f,g)=>{if(!f.isTextblock||f.type.spec.code)return;const x=Math.max(r,g),y=Math.min(a,g+f.content.size),v=f.textBetween(x-g,y-g,void 0,"");BXs(v,i.find,l).forEach(w=>{if(w.index===void 0)return;const S=x+w.index+1,C=S+w[0].length,E={from:n.tr.mapping.map(S),to:n.tr.mapping.map(C)},I=i.handler({state:n,range:E,match:w,commands:c,chain:d,can:u,pasteEvent:l,dropEvent:o});h.push(I)})}),h.every(f=>f!==null)}let fde=null;const UXs=s=>{var t;const n=new ClipboardEvent("paste",{clipboardData:new DataTransfer});return(t=n.clipboardData)===null||t===void 0||t.setData("text/html",s),n};function qXs(s){const{editor:t,rules:n}=s;let r=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:u,from:h,to:m,rule:f,pasteEvt:g})=>{const x=u.tr,y=z6e({state:u,transaction:x});if(!(!$Xs({editor:t,state:y,from:Math.max(h-1,0),to:m.b-1,rule:f,pasteEvent:g,dropEvent:o})||!x.steps.length)){try{o=typeof DragEvent<"u"?new DragEvent("drop"):null}catch{o=null}return l=typeof ClipboardEvent<"u"?new ClipboardEvent("paste"):null,x}};return n.map(u=>new $0({view(h){const m=g=>{var x;r=!((x=h.dom.parentElement)===null||x===void 0)&&x.contains(g.target)?h.dom.parentElement:null,r&&(fde=t)},f=()=>{fde&&(fde=null)};return window.addEventListener("dragstart",m),window.addEventListener("dragend",f),{destroy(){window.removeEventListener("dragstart",m),window.removeEventListener("dragend",f)}}},props:{handleDOMEvents:{drop:(h,m)=>{if(i=r===h.dom.parentElement,o=m,!i){const f=fde;f!=null&&f.isEditable&&setTimeout(()=>{const g=f.state.selection;g&&f.commands.deleteRange({from:g.from,to:g.to})},10)}return!1},paste:(h,m)=>{var f;const g=(f=m.clipboardData)===null||f===void 0?void 0:f.getData("text/html");return l=m,a=!!(g!=null&&g.includes("data-pm-slice")),!1}}},appendTransaction:(h,m,f)=>{const g=h[0],x=g.getMeta("uiEvent")==="paste"&&!a,y=g.getMeta("uiEvent")==="drop"&&!i,v=g.getMeta("applyPasteRules"),b=!!v;if(!x&&!y&&!b)return;if(b){let{text:C}=v;typeof C=="string"?C=C:C=Fnt(hi.from(C),f.schema);const{from:E}=v,I=E+C.length,P=UXs(C);return c({rule:u,state:f,from:E,to:{b:I},pasteEvt:P})}const w=m.doc.content.findDiffStart(f.doc.content),S=m.doc.content.findDiffEnd(f.doc.content);if(!(!zXs(w)||!S||w===S.b))return c({rule:u,state:f,from:w,to:S,pasteEvt:l})}}))}function VXs(s){const t=s.filter((n,r)=>s.indexOf(n)!==r);return Array.from(new Set(t))}class rq{constructor(t,n){this.splittableMarks=[],this.editor=n,this.extensions=rq.resolve(t),this.schema=LXs(this.extensions,n),this.setupExtensions()}static resolve(t){const n=rq.sort(rq.flatten(t)),r=VXs(n.map(a=>a.name));return r.length&&console.warn(`[tiptap warn]: Duplicate extension names found: [${r.map(a=>`'${a}'`).join(", ")}]. This can lead to issues.`),n}static flatten(t){return t.map(n=>{const r={name:n.name,options:n.options,storage:n.storage},a=Uo(n,"addExtensions",r);return a?[n,...this.flatten(a())]:n}).flat(10)}static sort(t){return t.sort((r,a)=>{const i=Uo(r,"priority")||100,l=Uo(a,"priority")||100;return i>l?-1:i{const r={name:n.name,options:n.options,storage:n.storage,editor:this.editor,type:pBe(n.name,this.schema)},a=Uo(n,"addCommands",r);return a?{...t,...a()}:t},{})}get plugins(){const{editor:t}=this,n=rq.sort([...this.extensions].reverse()),r=[],a=[],i=n.map(l=>{const o={name:l.name,options:l.options,storage:l.storage,editor:t,type:pBe(l.name,this.schema)},c=[],d=Uo(l,"addKeyboardShortcuts",o);let u={};if(l.type==="mark"&&Uo(l,"exitable",o)&&(u.ArrowRight=()=>xC.handleExit({editor:t,mark:l})),d){const x=Object.fromEntries(Object.entries(d()).map(([y,v])=>[y,()=>v({editor:t})]));u={...u,...x}}const h=dXs(u);c.push(h);const m=Uo(l,"addInputRules",o);k1t(l,t.options.enableInputRules)&&m&&r.push(...m());const f=Uo(l,"addPasteRules",o);k1t(l,t.options.enablePasteRules)&&f&&a.push(...f());const g=Uo(l,"addProseMirrorPlugins",o);if(g){const x=g();c.push(...x)}return c}).flat();return[FXs({editor:t,rules:r}),...qXs({editor:t,rules:a}),...i]}get attributes(){return FVt(this.extensions)}get nodeViews(){const{editor:t}=this,{nodeExtensions:n}=$6e(this.extensions);return Object.fromEntries(n.filter(r=>!!Uo(r,"addNodeView")).map(r=>{const a=this.attributes.filter(c=>c.type===r.name),i={name:r.name,options:r.options,storage:r.storage,editor:t,type:Lv(r.name,this.schema)},l=Uo(r,"addNodeView",i);if(!l)return[];const o=(c,d,u,h,m)=>{const f=mWe(c,a);return l()({node:c,view:d,getPos:u,decorations:h,innerDecorations:m,editor:t,extension:r,HTMLAttributes:f})};return[r.name,o]}))}setupExtensions(){this.extensions.forEach(t=>{var n;this.editor.extensionStorage[t.name]=t.storage;const r={name:t.name,options:t.options,storage:t.storage,editor:this.editor,type:pBe(t.name,this.schema)};t.type==="mark"&&(!((n=Nd(Uo(t,"keepOnSplit",r)))!==null&&n!==void 0)||n)&&this.splittableMarks.push(t.name);const a=Uo(t,"onBeforeCreate",r),i=Uo(t,"onCreate",r),l=Uo(t,"onUpdate",r),o=Uo(t,"onSelectionUpdate",r),c=Uo(t,"onTransaction",r),d=Uo(t,"onFocus",r),u=Uo(t,"onBlur",r),h=Uo(t,"onDestroy",r);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),u&&this.editor.on("blur",u),h&&this.editor.on("destroy",h)})}}class Tb{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=Nd(Uo(this,"addOptions",{name:this.name}))),this.storage=Nd(Uo(this,"addStorage",{name:this.name,options:this.options}))||{}}static create(t={}){return new Tb(t)}configure(t={}){const n=this.extend({...this.config,addOptions:()=>q6e(this.options,t)});return n.name=this.name,n.parent=this.parent,n}extend(t={}){const n=new Tb({...this.config,...t});return n.parent=this,this.child=n,n.name=t.name?t.name:n.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: "${n.name}".`),n.options=Nd(Uo(n,"addOptions",{name:n.name})),n.storage=Nd(Uo(n,"addStorage",{name:n.name,options:n.options})),n}}function BVt(s,t,n){const{from:r,to:a}=t,{blockSeparator:i=` `,textSerializers:l={}}=n||{};let o="";return s.nodesBetween(r,a,(c,d,u,h)=>{var m;c.isBlock&&d>r&&(o+=i);const f=l==null?void 0:l[c.type.name];if(f)return u&&(o+=f({node:c,pos:d,parent:u,index:h,range:t})),!1;c.isText&&(o+=(m=c==null?void 0:c.text)===null||m===void 0?void 0:m.slice(Math.max(r,d)-d,a-d))}),o}function $Vt(s){return Object.fromEntries(Object.entries(s.nodes).filter(([,t])=>t.spec.toText).map(([t,n])=>[t,n.spec.toText]))}const HXs=Tb.create({name:"clipboardTextSerializer",addOptions(){return{blockSeparator:void 0}},addProseMirrorPlugins(){return[new $0({key:new I1("clipboardTextSerializer"),props:{clipboardTextSerializer:()=>{const{editor:s}=this,{state:t,schema:n}=s,{doc:r,selection:a}=t,{ranges:i}=a,l=Math.min(...i.map(u=>u.$from.pos)),o=Math.max(...i.map(u=>u.$to.pos)),c=$Vt(n);return BVt(r,{from:l,to:o},{...this.options.blockSeparator!==void 0?{blockSeparator:this.options.blockSeparator}:{},textSerializers:c})}}})]}}),GXs=()=>({editor:s,view:t})=>(requestAnimationFrame(()=>{var n;s.isDestroyed||(t.dom.blur(),(n=window==null?void 0:window.getSelection())===null||n===void 0||n.removeAllRanges())}),!0),WXs=(s=!1)=>({commands:t})=>t.setContent("",s),KXs=()=>({state:s,tr:t,dispatch:n})=>{const{selection:r}=t,{ranges:a}=r;return n&&a.forEach(({$from:i,$to:l})=>{s.doc.nodesBetween(i.pos,l.pos,(o,c)=>{if(o.type.isText)return;const{doc:d,mapping:u}=t,h=d.resolve(u.map(c)),m=d.resolve(u.map(c+o.nodeSize)),f=h.blockRange(m);if(!f)return;const g=yK(f);if(o.type.isTextblock){const{defaultType:x}=h.parent.contentMatchAt(h.index());t.setNodeMarkup(f.start,x)}(g||g===0)&&t.lift(f,g)})}),!0},YXs=s=>t=>s(t),ZXs=()=>({state:s,dispatch:t})=>IVt(s,t),XXs=(s,t)=>({editor:n,tr:r})=>{const{state:a}=n,i=a.doc.slice(s.from,s.to);r.deleteRange(s.from,s.to);const l=r.mapping.map(t);return r.insert(l,i.content),r.setSelection(new Al(r.doc.resolve(Math.max(l-1,0)))),!0},QXs=()=>({tr:s,dispatch:t})=>{const{selection:n}=s,r=n.$anchor.node();if(r.content.size>0)return!1;const a=s.selection.$anchor;for(let i=a.depth;i>0;i-=1)if(a.node(i).type===r.type){if(t){const o=a.before(i),c=a.after(i);s.delete(o,c).scrollIntoView()}return!0}return!1},JXs=s=>({tr:t,state:n,dispatch:r})=>{const a=Lv(s,n.schema),i=t.selection.$anchor;for(let l=i.depth;l>0;l-=1)if(i.node(l).type===a){if(r){const c=i.before(l),d=i.after(l);t.delete(c,d).scrollIntoView()}return!0}return!1},eQs=s=>({tr:t,dispatch:n})=>{const{from:r,to:a}=s;return n&&t.delete(r,a),!0},tQs=()=>({state:s,dispatch:t})=>Pnt(s,t),sQs=()=>({commands:s})=>s.keyboardShortcut("Enter"),nQs=()=>({state:s,dispatch:t})=>gXs(s,t);function cTe(s,t,n={strict:!0}){const r=Object.keys(t);return r.length?r.every(a=>n.strict?t[a]===s[a]:Ont(t[a])?t[a].test(s[a]):t[a]===s[a]):!0}function UVt(s,t,n={}){return s.find(r=>r.type===t&&cTe(Object.fromEntries(Object.keys(n).map(a=>[a,r.attrs[a]])),n))}function S1t(s,t,n={}){return!!UVt(s,t,n)}function znt(s,t,n){var r;if(!s||!t)return;let a=s.parent.childAfter(s.parentOffset);if((!a.node||!a.node.marks.some(u=>u.type===t))&&(a=s.parent.childBefore(s.parentOffset)),!a.node||!a.node.marks.some(u=>u.type===t)||(n=n||((r=a.node.marks[0])===null||r===void 0?void 0:r.attrs),!UVt([...a.node.marks],t,n)))return;let l=a.index,o=s.start()+a.offset,c=l+1,d=o+a.node.nodeSize;for(;l>0&&S1t([...s.parent.child(l-1).marks],t,n);)l-=1,o-=s.parent.child(l).nodeSize;for(;c({tr:n,state:r,dispatch:a})=>{const i=f6(s,r.schema),{doc:l,selection:o}=n,{$from:c,from:d,to:u}=o;if(a){const h=znt(c,i,t);if(h&&h.from<=d&&h.to>=u){const m=Al.create(l,h.from,h.to);n.setSelection(m)}}return!0},aQs=s=>t=>{const n=typeof s=="function"?s(t):s;for(let r=0;r({editor:n,view:r,tr:a,dispatch:i})=>{t={scrollIntoView:!0,...t};const l=()=>{(dTe()||C1t())&&r.dom.focus(),requestAnimationFrame(()=>{n.isDestroyed||(r.focus(),iQs()&&!dTe()&&!C1t()&&r.dom.focus({preventScroll:!0}))})};if(r.hasFocus()&&s===null||s===!1)return!0;if(i&&s===null&&!qVt(n.state.selection))return l(),!0;const o=VVt(a.doc,s)||n.state.selection,c=n.state.selection.eq(o);return i&&(c||a.setSelection(o),c&&a.storedMarks&&a.setStoredMarks(a.storedMarks),l()),!0},lQs=(s,t)=>n=>s.every((r,a)=>t(r,{...n,index:a})),cQs=(s,t)=>({tr:n,commands:r})=>r.insertContentAt({from:n.selection.from,to:n.selection.to},s,t),HVt=s=>{const t=s.childNodes;for(let n=t.length-1;n>=0;n-=1){const r=t[n];r.nodeType===3&&r.nodeValue&&/^(\n\s\s|\n)$/.test(r.nodeValue)?s.removeChild(r):r.nodeType===1&&HVt(r)}return s};function pde(s){const t=`${s}`,n=new window.DOMParser().parseFromString(t,"text/html").body;return HVt(n)}function jse(s,t,n){if(s instanceof oL||s instanceof hi)return s;n={slice:!0,parseOptions:{},...n};const r=typeof s=="object"&&s!==null,a=typeof s=="string";if(r)try{if(Array.isArray(s)&&s.length>0)return hi.fromArray(s.map(o=>t.nodeFromJSON(o)));const l=t.nodeFromJSON(s);return n.errorOnInvalidContent&&l.check(),l}catch(i){if(n.errorOnInvalidContent)throw new Error("[tiptap error]: Invalid JSON content",{cause:i});return console.warn("[tiptap warn]: Invalid content.","Passed value:",s,"Error:",i),jse("",t,n)}if(a){if(n.errorOnInvalidContent){let l=!1,o="";const c=new jqt({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(n.slice?Mee.fromSchema(c).parseSlice(pde(s),n.parseOptions):Mee.fromSchema(c).parse(pde(s),n.parseOptions),n.errorOnInvalidContent&&l)throw new Error("[tiptap error]: Invalid HTML content",{cause:new Error(`Invalid element found: ${o}`)})}const i=Mee.fromSchema(t);return n.slice?i.parseSlice(pde(s),n.parseOptions).content:i.parse(pde(s),n.parseOptions)}return jse("",t,n)}function dQs(s,t,n){const r=s.steps.length-1;if(r{l===0&&(l=u)}),s.setSelection(oc.near(s.doc.resolve(l),n))}const uQs=s=>!("type"in s),hQs=(s,t,n)=>({tr:r,dispatch:a,editor:i})=>{var l;if(a){n={parseOptions:i.options.parseOptions,updateSelection:!0,applyInputRules:!1,applyPasteRules:!1,...n};let o;const c=y=>{i.emit("contentError",{editor:i,error:y,disableCollaboration:()=>{i.storage.collaboration&&(i.storage.collaboration.isDisabled=!0)}})},d={preserveWhitespace:"full",...n.parseOptions};if(!n.errorOnInvalidContent&&!i.options.enableContentCheck&&i.options.emitContentError)try{jse(t,i.schema,{parseOptions:d,errorOnInvalidContent:!0})}catch(y){c(y)}try{o=jse(t,i.schema,{parseOptions:d,errorOnInvalidContent:(l=n.errorOnInvalidContent)!==null&&l!==void 0?l:i.options.enableContentCheck})}catch(y){return c(y),!1}let{from:u,to:h}=typeof s=="number"?{from:s,to:s}:{from:s.from,to:s.to},m=!0,f=!0;if((uQs(o)?o:[o]).forEach(y=>{y.check(),m=m?y.isText&&y.marks.length===0:!1,f=f?y.isBlock:!1}),u===h&&f){const{parent:y}=r.doc.resolve(u);y.isTextblock&&!y.type.spec.code&&!y.childCount&&(u-=1,h+=1)}let x;if(m){if(Array.isArray(t))x=t.map(y=>y.text||"").join("");else if(t instanceof hi){let y="";t.forEach(v=>{v.text&&(y+=v.text)}),x=y}else typeof t=="object"&&t&&t.text?x=t.text:x=t;r.insertText(x,u,h)}else x=o,r.replaceWith(u,h,x);n.updateSelection&&dQs(r,r.steps.length-1,-1),n.applyInputRules&&r.setMeta("applyInputRules",{from:u,text:x}),n.applyPasteRules&&r.setMeta("applyPasteRules",{from:u,text:x})}return!0},mQs=()=>({state:s,dispatch:t})=>mXs(s,t),fQs=()=>({state:s,dispatch:t})=>fXs(s,t),pQs=()=>({state:s,dispatch:t})=>SVt(s,t),gQs=()=>({state:s,dispatch:t})=>TVt(s,t),xQs=()=>({state:s,dispatch:t,tr:n})=>{try{const r=I6e(s.doc,s.selection.$from.pos,-1);return r==null?!1:(n.join(r,2),t&&t(n),!0)}catch{return!1}},yQs=()=>({state:s,dispatch:t,tr:n})=>{try{const r=I6e(s.doc,s.selection.$from.pos,1);return r==null?!1:(n.join(r,2),t&&t(n),!0)}catch{return!1}},vQs=()=>({state:s,dispatch:t})=>uXs(s,t),bQs=()=>({state:s,dispatch:t})=>hXs(s,t);function GVt(){return typeof navigator<"u"?/Mac/.test(navigator.platform):!1}function _Qs(s){const t=s.split(/-(?!$)/);let n=t[t.length-1];n==="Space"&&(n=" ");let r,a,i,l;for(let o=0;o({editor:t,view:n,tr:r,dispatch:a})=>{const i=_Qs(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(()=>{n.someProp("handleKeyDown",d=>d(n,o))});return c==null||c.steps.forEach(d=>{const u=d.map(r.mapping);u&&a&&r.maybeStep(u)}),!0};function Nse(s,t,n={}){const{from:r,to:a,empty:i}=s.selection,l=t?Lv(t,s.schema):null,o=[];s.doc.nodesBetween(r,a,(h,m)=>{if(h.isText)return;const f=Math.max(r,m),g=Math.min(a,m+h.nodeSize);o.push({node:h,from:f,to:g})});const c=a-r,d=o.filter(h=>l?l.name===h.node.type.name:!0).filter(h=>cTe(h.node.attrs,n,{strict:!1}));return i?!!d.length:d.reduce((h,m)=>h+m.to-m.from,0)>=c}const jQs=(s,t={})=>({state:n,dispatch:r})=>{const a=Lv(s,n.schema);return Nse(n,a,t)?pXs(n,r):!1},NQs=()=>({state:s,dispatch:t})=>LVt(s,t),kQs=s=>({state:t,dispatch:n})=>{const r=Lv(s,t.schema);return CXs(r)(t,n)},SQs=()=>({state:s,dispatch:t})=>PVt(s,t);function V6e(s,t){return t.nodes[s]?"node":t.marks[s]?"mark":null}function A1t(s,t){const n=typeof t=="string"?[t]:t;return Object.keys(s).reduce((r,a)=>(n.includes(a)||(r[a]=s[a]),r),{})}const CQs=(s,t)=>({tr:n,state:r,dispatch:a})=>{let i=null,l=null;const o=V6e(typeof s=="string"?s:s.name,r.schema);return o?(o==="node"&&(i=Lv(s,r.schema)),o==="mark"&&(l=f6(s,r.schema)),a&&n.selection.ranges.forEach(c=>{r.doc.nodesBetween(c.$from.pos,c.$to.pos,(d,u)=>{i&&i===d.type&&n.setNodeMarkup(u,void 0,A1t(d.attrs,t)),l&&d.marks.length&&d.marks.forEach(h=>{l===h.type&&n.addMark(u,u+d.nodeSize,l.create(A1t(h.attrs,t)))})})}),!0):!1},AQs=()=>({tr:s,dispatch:t})=>(t&&s.scrollIntoView(),!0),EQs=()=>({tr:s,dispatch:t})=>{if(t){const n=new b2(s.doc);s.setSelection(n)}return!0},TQs=()=>({state:s,dispatch:t})=>AVt(s,t),MQs=()=>({state:s,dispatch:t})=>MVt(s,t),PQs=()=>({state:s,dispatch:t})=>vXs(s,t),IQs=()=>({state:s,dispatch:t})=>wXs(s,t),LQs=()=>({state:s,dispatch:t})=>_Xs(s,t);function fWe(s,t,n={},r={}){return jse(s,t,{slice:!1,parseOptions:n,errorOnInvalidContent:r.errorOnInvalidContent})}const RQs=(s,t=!1,n={},r={})=>({editor:a,tr:i,dispatch:l,commands:o})=>{var c,d;const{doc:u}=i;if(n.preserveWhitespace!=="full"){const h=fWe(s,a.schema,n,{errorOnInvalidContent:(c=r.errorOnInvalidContent)!==null&&c!==void 0?c:a.options.enableContentCheck});return l&&i.replaceWith(0,u.content.size,h).setMeta("preventUpdate",!t),!0}return l&&i.setMeta("preventUpdate",!t),o.insertContentAt({from:0,to:u.content.size},s,{parseOptions:n,errorOnInvalidContent:(d=r.errorOnInvalidContent)!==null&&d!==void 0?d:a.options.enableContentCheck})};function WVt(s,t){const n=f6(t,s.schema),{from:r,to:a,empty:i}=s.selection,l=[];i?(s.storedMarks&&l.push(...s.storedMarks),l.push(...s.selection.$head.marks())):s.doc.nodesBetween(r,a,c=>{l.push(...c.marks)});const o=l.find(c=>c.type.name===n.name);return o?{...o.attrs}:{}}function DQs(s,t){const n=new bnt(s);return t.forEach(r=>{r.steps.forEach(a=>{n.step(a)})}),n}function FQs(s){for(let t=0;t{n(a)&&r.push({node:a,pos:i})}),r}function KVt(s,t){for(let n=s.depth;n>0;n-=1){const r=s.node(n);if(t(r))return{pos:n>0?s.before(n):0,start:s.start(n),depth:n,node:r}}}function Bnt(s){return t=>KVt(t.$from,s)}function zQs(s,t){const n={from:0,to:s.content.size};return BVt(s,n,t)}function BQs(s,t){const n=Lv(t,s.schema),{from:r,to:a}=s.selection,i=[];s.doc.nodesBetween(r,a,o=>{i.push(o)});const l=i.reverse().find(o=>o.type.name===n.name);return l?{...l.attrs}:{}}function YVt(s,t){const n=V6e(typeof t=="string"?t:t.name,s.schema);return n==="node"?BQs(s,t):n==="mark"?WVt(s,t):{}}function $Qs(s,t=JSON.stringify){const n={};return s.filter(r=>{const a=t(r);return Object.prototype.hasOwnProperty.call(n,a)?!1:n[a]=!0})}function UQs(s){const t=$Qs(s);return t.length===1?t:t.filter((n,r)=>!t.filter((i,l)=>l!==r).some(i=>n.oldRange.from>=i.oldRange.from&&n.oldRange.to<=i.oldRange.to&&n.newRange.from>=i.newRange.from&&n.newRange.to<=i.newRange.to))}function qQs(s){const{mapping:t,steps:n}=s,r=[];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}=n[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),u=t.slice(i).map(c),h=t.invert().map(d,-1),m=t.invert().map(u);r.push({oldRange:{from:h,to:m},newRange:{from:d,to:u}})})}),UQs(r)}function $nt(s,t,n){const r=[];return s===t?n.resolve(s).marks().forEach(a=>{const i=n.resolve(s),l=znt(i,a.type);l&&r.push({mark:a,...l})}):n.nodesBetween(s,t,(a,i)=>{!a||(a==null?void 0:a.nodeSize)===void 0||r.push(...a.marks.map(l=>({from:i,to:i+a.nodeSize,mark:l})))}),r}function g3e(s,t,n){return Object.fromEntries(Object.entries(n).filter(([r])=>{const a=s.find(i=>i.type===t&&i.name===r);return a?a.attribute.keepOnSplit:!1}))}function pWe(s,t,n={}){const{empty:r,ranges:a}=s.selection,i=t?f6(t,s.schema):null;if(r)return!!(s.storedMarks||s.selection.$from.marks()).filter(h=>i?i.name===h.type.name:!0).find(h=>cTe(h.attrs,n,{strict:!1}));let l=0;const o=[];if(a.forEach(({$from:h,$to:m})=>{const f=h.pos,g=m.pos;s.doc.nodesBetween(f,g,(x,y)=>{if(!x.isText&&!x.marks.length)return;const v=Math.max(f,y),b=Math.min(g,y+x.nodeSize),w=b-v;l+=w,o.push(...x.marks.map(S=>({mark:S,from:v,to:b})))})}),l===0)return!1;const c=o.filter(h=>i?i.name===h.mark.type.name:!0).filter(h=>cTe(h.mark.attrs,n,{strict:!1})).reduce((h,m)=>h+m.to-m.from,0),d=o.filter(h=>i?h.mark.type!==i&&h.mark.type.excludes(i):!0).reduce((h,m)=>h+m.to-m.from,0);return(c>0?c+d:c)>=l}function VQs(s,t,n={}){if(!t)return Nse(s,null,n)||pWe(s,null,n);const r=V6e(t,s.schema);return r==="node"?Nse(s,t,n):r==="mark"?pWe(s,t,n):!1}function E1t(s,t){const{nodeExtensions:n}=$6e(t),r=n.find(l=>l.name===s);if(!r)return!1;const a={name:r.name,options:r.options,storage:r.storage},i=Nd(Uo(r,"group",a));return typeof i!="string"?!1:i.split(" ").includes("list")}function Unt(s,{checkChildren:t=!0,ignoreWhitespace:n=!1}={}){var r;if(n){if(s.type.name==="hardBreak")return!0;if(s.isText)return/^\s*$/m.test((r=s.text)!==null&&r!==void 0?r:"")}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&&(Unt(i,{ignoreWhitespace:n,checkChildren:t})||(a=!1))}),a}return!1}function HQs(s){return s instanceof El}function GQs(s,t,n){var r;const{selection:a}=t;let i=null;if(qVt(a)&&(i=a.$cursor),i){const o=(r=s.storedMarks)!==null&&r!==void 0?r:i.marks();return!!n.isInSet(o)||!o.some(c=>c.type.excludes(n))}const{ranges:l}=a;return l.some(({$from:o,$to:c})=>{let d=o.depth===0?s.doc.inlineContent&&s.doc.type.allowsMarkType(n):!1;return s.doc.nodesBetween(o.pos,c.pos,(u,h,m)=>{if(d)return!1;if(u.isInline){const f=!m||m.type.allowsMarkType(n),g=!!n.isInSet(u.marks)||!u.marks.some(x=>x.type.excludes(n));d=f&&g}return!d}),d})}const WQs=(s,t={})=>({tr:n,state:r,dispatch:a})=>{const{selection:i}=n,{empty:l,ranges:o}=i,c=f6(s,r.schema);if(a)if(l){const d=WVt(r,c);n.addStoredMark(c.create({...d,...t}))}else o.forEach(d=>{const u=d.$from.pos,h=d.$to.pos;r.doc.nodesBetween(u,h,(m,f)=>{const g=Math.max(f,u),x=Math.min(f+m.nodeSize,h);m.marks.find(v=>v.type===c)?m.marks.forEach(v=>{c===v.type&&n.addMark(g,x,c.create({...v.attrs,...t}))}):n.addMark(g,x,c.create(t))})});return GQs(r,n,c)},KQs=(s,t)=>({tr:n})=>(n.setMeta(s,t),!0),YQs=(s,t={})=>({state:n,dispatch:r,chain:a})=>{const i=Lv(s,n.schema);let l;return n.selection.$anchor.sameParent(n.selection.$head)&&(l=n.selection.$anchor.parent.attrs),i.isTextblock?a().command(({commands:o})=>w1t(i,{...l,...t})(n)?!0:o.clearNodes()).command(({state:o})=>w1t(i,{...l,...t})(o,r)).run():(console.warn('[tiptap warn]: Currently "setNode()" only supports text block nodes.'),!1)},ZQs=s=>({tr:t,dispatch:n})=>{if(n){const{doc:r}=t,a=g8(s,0,r.content.size),i=El.create(r,a);t.setSelection(i)}return!0},XQs=s=>({tr:t,dispatch:n})=>{if(n){const{doc:r}=t,{from:a,to:i}=typeof s=="number"?{from:s,to:s}:s,l=Al.atStart(r).from,o=Al.atEnd(r).to,c=g8(a,l,o),d=g8(i,l,o),u=Al.create(r,c,d);t.setSelection(u)}return!0},QQs=s=>({state:t,dispatch:n})=>{const r=Lv(s,t.schema);return TXs(r)(t,n)};function T1t(s,t){const n=s.storedMarks||s.selection.$to.parentOffset&&s.selection.$from.marks();if(n){const r=n.filter(a=>t==null?void 0:t.includes(a.type.name));s.tr.ensureMarks(r)}}const JQs=({keepMarks:s=!0}={})=>({tr:t,state:n,dispatch:r,editor:a})=>{const{selection:i,doc:l}=t,{$from:o,$to:c}=i,d=a.extensionManager.attributes,u=g3e(d,o.node().type.name,o.node().attrs);if(i instanceof El&&i.node.isBlock)return!o.parentOffset||!HE(l,o.pos)?!1:(r&&(s&&T1t(n,a.extensionManager.splittableMarks),t.split(o.pos).scrollIntoView()),!0);if(!o.parent.isBlock)return!1;const h=c.parentOffset===c.parent.content.size,m=o.depth===0?void 0:FQs(o.node(-1).contentMatchAt(o.indexAfter(-1)));let f=h&&m?[{type:m,attrs:u}]:void 0,g=HE(t.doc,t.mapping.map(o.pos),1,f);if(!f&&!g&&HE(t.doc,t.mapping.map(o.pos),1,m?[{type:m}]:void 0)&&(g=!0,f=m?[{type:m,attrs:u}]:void 0),r){if(g&&(i instanceof Al&&t.deleteSelection(),t.split(t.mapping.map(o.pos),1,f),m&&!h&&!o.parentOffset&&o.parent.type!==m)){const x=t.mapping.map(o.before()),y=t.doc.resolve(x);o.node(-1).canReplaceWith(y.index(),y.index()+1,m)&&t.setNodeMarkup(t.mapping.map(o.before()),m)}s&&T1t(n,a.extensionManager.splittableMarks),t.scrollIntoView()}return g},eJs=(s,t={})=>({tr:n,state:r,dispatch:a,editor:i})=>{var l;const o=Lv(s,r.schema),{$from:c,$to:d}=r.selection,u=r.selection.node;if(u&&u.isBlock||c.depth<2||!c.sameParent(d))return!1;const h=c.node(-1);if(h.type!==o)return!1;const m=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 v=hi.empty;const b=c.index(-1)?1:c.index(-2)?2:3;for(let P=c.depth-b;P>=c.depth-3;P-=1)v=hi.from(c.node(P).copy(v));const w=c.indexAfter(-1){if(I>-1)return!1;P.isTextblock&&P.content.size===0&&(I=R+1)}),I>-1&&n.setSelection(Al.near(n.doc.resolve(I))),n.scrollIntoView()}return!0}const f=d.pos===c.end()?h.contentMatchAt(0).defaultType:null,g={...g3e(m,h.type.name,h.attrs),...t},x={...g3e(m,c.node().type.name,c.node().attrs),...t};n.delete(c.pos,d.pos);const y=f?[{type:o,attrs:g},{type:f,attrs:x}]:[{type:o,attrs:g}];if(!HE(n.doc,c.pos,2))return!1;if(a){const{selection:v,storedMarks:b}=r,{splittableMarks:w}=i.extensionManager,S=b||v.$to.parentOffset&&v.$from.marks();if(n.split(c.pos,2,y).scrollIntoView(),!S||!a)return!0;const C=S.filter(E=>w.includes(E.type.name));n.ensureMarks(C)}return!0},gBe=(s,t)=>{const n=Bnt(l=>l.type===t)(s.selection);if(!n)return!0;const r=s.doc.resolve(Math.max(0,n.pos-1)).before(n.depth);if(r===void 0)return!0;const a=s.doc.nodeAt(r);return n.node.type===(a==null?void 0:a.type)&&h6(s.doc,n.pos)&&s.join(n.pos),!0},xBe=(s,t)=>{const n=Bnt(l=>l.type===t)(s.selection);if(!n)return!0;const r=s.doc.resolve(n.start).after(n.depth);if(r===void 0)return!0;const a=s.doc.nodeAt(r);return n.node.type===(a==null?void 0:a.type)&&h6(s.doc,r)&&s.join(r),!0},tJs=(s,t,n,r={})=>({editor:a,tr:i,state:l,dispatch:o,chain:c,commands:d,can:u})=>{const{extensions:h,splittableMarks:m}=a.extensionManager,f=Lv(s,l.schema),g=Lv(t,l.schema),{selection:x,storedMarks:y}=l,{$from:v,$to:b}=x,w=v.blockRange(b),S=y||x.$to.parentOffset&&x.$from.marks();if(!w)return!1;const C=Bnt(E=>E1t(E.type.name,h))(x);if(w.depth>=1&&C&&w.depth-C.depth<=1){if(C.node.type===f)return d.liftListItem(g);if(E1t(C.node.type.name,h)&&f.validContent(C.node.content)&&o)return c().command(()=>(i.setNodeMarkup(C.pos,f),!0)).command(()=>gBe(i,f)).command(()=>xBe(i,f)).run()}return!n||!S||!o?c().command(()=>u().wrapInList(f,r)?!0:d.clearNodes()).wrapInList(f,r).command(()=>gBe(i,f)).command(()=>xBe(i,f)).run():c().command(()=>{const E=u().wrapInList(f,r),I=S.filter(P=>m.includes(P.type.name));return i.ensureMarks(I),E?!0:d.clearNodes()}).wrapInList(f,r).command(()=>gBe(i,f)).command(()=>xBe(i,f)).run()},sJs=(s,t={},n={})=>({state:r,commands:a})=>{const{extendEmptyMarkRange:i=!1}=n,l=f6(s,r.schema);return pWe(r,l,t)?a.unsetMark(l,{extendEmptyMarkRange:i}):a.setMark(l,t)},nJs=(s,t,n={})=>({state:r,commands:a})=>{const i=Lv(s,r.schema),l=Lv(t,r.schema),o=Nse(r,i,n);let c;return r.selection.$anchor.sameParent(r.selection.$head)&&(c=r.selection.$anchor.parent.attrs),o?a.setNode(l,c):a.setNode(i,{...c,...n})},rJs=(s,t={})=>({state:n,commands:r})=>{const a=Lv(s,n.schema);return Nse(n,a,t)?r.lift(a):r.wrapIn(a,t)},aJs=()=>({state:s,dispatch:t})=>{const n=s.plugins;for(let r=0;r=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},iJs=()=>({tr:s,dispatch:t})=>{const{selection:n}=s,{empty:r,ranges:a}=n;return r||t&&a.forEach(i=>{s.removeMark(i.$from.pos,i.$to.pos)}),!0},oJs=(s,t={})=>({tr:n,state:r,dispatch:a})=>{var i;const{extendEmptyMarkRange:l=!1}=t,{selection:o}=n,c=f6(s,r.schema),{$from:d,empty:u,ranges:h}=o;if(!a)return!0;if(u&&l){let{from:m,to:f}=o;const g=(i=d.marks().find(y=>y.type===c))===null||i===void 0?void 0:i.attrs,x=znt(d,c,g);x&&(m=x.from,f=x.to),n.removeMark(m,f,c)}else h.forEach(m=>{n.removeMark(m.$from.pos,m.$to.pos,c)});return n.removeStoredMark(c),!0},lJs=(s,t={})=>({tr:n,state:r,dispatch:a})=>{let i=null,l=null;const o=V6e(typeof s=="string"?s:s.name,r.schema);return o?(o==="node"&&(i=Lv(s,r.schema)),o==="mark"&&(l=f6(s,r.schema)),a&&n.selection.ranges.forEach(c=>{const d=c.$from.pos,u=c.$to.pos;let h,m,f,g;n.selection.empty?r.doc.nodesBetween(d,u,(x,y)=>{i&&i===x.type&&(f=Math.max(y,d),g=Math.min(y+x.nodeSize,u),h=y,m=x)}):r.doc.nodesBetween(d,u,(x,y)=>{y=d&&y<=u&&(i&&i===x.type&&n.setNodeMarkup(y,void 0,{...x.attrs,...t}),l&&x.marks.length&&x.marks.forEach(v=>{if(l===v.type){const b=Math.max(y,d),w=Math.min(y+x.nodeSize,u);n.addMark(b,w,l.create({...v.attrs,...t}))}}))}),m&&(h!==void 0&&n.setNodeMarkup(h,void 0,{...m.attrs,...t}),l&&m.marks.length&&m.marks.forEach(x=>{l===x.type&&n.addMark(f,g,l.create({...x.attrs,...t}))}))}),!0):!1},cJs=(s,t={})=>({state:n,dispatch:r})=>{const a=Lv(s,n.schema);return jXs(a,t)(n,r)},dJs=(s,t={})=>({state:n,dispatch:r})=>{const a=Lv(s,n.schema);return NXs(a,t)(n,r)};var uJs=Object.freeze({__proto__:null,blur:GXs,clearContent:WXs,clearNodes:KXs,command:YXs,createParagraphNear:ZXs,cut:XXs,deleteCurrentNode:QXs,deleteNode:JXs,deleteRange:eQs,deleteSelection:tQs,enter:sQs,exitCode:nQs,extendMarkRange:rQs,first:aQs,focus:oQs,forEach:lQs,insertContent:cQs,insertContentAt:hQs,joinBackward:pQs,joinDown:fQs,joinForward:gQs,joinItemBackward:xQs,joinItemForward:yQs,joinTextblockBackward:vQs,joinTextblockForward:bQs,joinUp:mQs,keyboardShortcut:wQs,lift:jQs,liftEmptyBlock:NQs,liftListItem:kQs,newlineInCode:SQs,resetAttributes:CQs,scrollIntoView:AQs,selectAll:EQs,selectNodeBackward:TQs,selectNodeForward:MQs,selectParentNode:PQs,selectTextblockEnd:IQs,selectTextblockStart:LQs,setContent:RQs,setMark:WQs,setMeta:KQs,setNode:YQs,setNodeSelection:ZQs,setTextSelection:XQs,sinkListItem:QQs,splitBlock:JQs,splitListItem:eJs,toggleList:tJs,toggleMark:sJs,toggleNode:nJs,toggleWrap:rJs,undoInputRule:aJs,unsetAllMarks:iJs,unsetMark:oJs,updateAttributes:lJs,wrapIn:cJs,wrapInList:dJs});const hJs=Tb.create({name:"commands",addCommands(){return{...uJs}}}),mJs=Tb.create({name:"drop",addProseMirrorPlugins(){return[new $0({key:new I1("tiptapDrop"),props:{handleDrop:(s,t,n,r)=>{this.editor.emit("drop",{editor:this.editor,event:t,slice:n,moved:r})}}})]}}),fJs=Tb.create({name:"editable",addProseMirrorPlugins(){return[new $0({key:new I1("editable"),props:{editable:()=>this.editor.options.editable}})]}}),pJs=new I1("focusEvents"),gJs=Tb.create({name:"focusEvents",addProseMirrorPlugins(){const{editor:s}=this;return[new $0({key:pJs,props:{handleDOMEvents:{focus:(t,n)=>{s.isFocused=!0;const r=s.state.tr.setMeta("focus",{event:n}).setMeta("addToHistory",!1);return t.dispatch(r),!1},blur:(t,n)=>{s.isFocused=!1;const r=s.state.tr.setMeta("blur",{event:n}).setMeta("addToHistory",!1);return t.dispatch(r),!1}}}})]}}),xJs=Tb.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:u,$anchor:h}=c,{pos:m,parent:f}=h,g=h.parent.isTextblock&&m>0?o.doc.resolve(m-1):h,x=g.parent.type.spec.isolating,y=h.pos-h.parentOffset,v=x&&g.parent.childCount===1?y===h.pos:oc.atStart(d).from===m;return!u||!f.type.isTextblock||f.textContent.length||!v||v&&h.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()]),r={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={...r},i={...r,"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 dTe()||GVt()?i:a},addProseMirrorPlugins(){return[new $0({key:new I1("clearDocument"),appendTransaction:(s,t,n)=>{if(s.some(x=>x.getMeta("composition")))return;const r=s.some(x=>x.docChanged)&&!t.doc.eq(n.doc),a=s.some(x=>x.getMeta("preventClearDocument"));if(!r||a)return;const{empty:i,from:l,to:o}=t.selection,c=oc.atStart(t.doc).from,d=oc.atEnd(t.doc).to;if(i||!(l===c&&o===d)||!Unt(n.doc))return;const m=n.tr,f=z6e({state:n,transaction:m}),{commands:g}=new B6e({editor:this.editor,state:f});if(g.clearNodes(),!!m.steps.length)return m}})]}}),yJs=Tb.create({name:"paste",addProseMirrorPlugins(){return[new $0({key:new I1("tiptapPaste"),props:{handlePaste:(s,t,n)=>{this.editor.emit("paste",{editor:this.editor,event:t,slice:n})}}})]}}),vJs=Tb.create({name:"tabindex",addProseMirrorPlugins(){return[new $0({key:new I1("tabindex"),props:{attributes:()=>this.editor.isEditable?{tabindex:"0"}:{}}})]}});class QO{get name(){return this.node.type.name}constructor(t,n,r=!1,a=null){this.currentNode=null,this.actualDepth=null,this.isBlock=r,this.resolvedPos=t,this.editor=n,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 n=this.from,r=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}n=this.from+1,r=this.to-1}this.editor.commands.insertContentAt({from:n,to:r},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),n=this.resolvedPos.doc.resolve(t);return new QO(n,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 QO(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 QO(t,this.editor)}get children(){const t=[];return this.node.content.forEach((n,r)=>{const a=n.isBlock&&!n.isTextblock,i=n.isAtom&&!n.isText,l=this.pos+r+(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 QO(o,this.editor,a,a?n:null);a&&(c.actualDepth=this.depth+1),t.push(new QO(o,this.editor,a,a?n:null))}),t}get firstChild(){return this.children[0]||null}get lastChild(){const t=this.children;return t[t.length-1]||null}closest(t,n={}){let r=null,a=this.parent;for(;a&&!r;){if(a.node.type.name===t)if(Object.keys(n).length>0){const i=a.node.attrs,l=Object.keys(n);for(let o=0;o{r&&a.length>0||(l.node.type.name===t&&i.every(c=>n[c]===l.node.attrs[c])&&a.push(l),!(r&&a.length>0)&&(a=a.concat(l.querySelectorAll(t,n,r))))}),a}setAttribute(t){const{tr:n}=this.editor.state;n.setNodeMarkup(this.from,void 0,{...this.node.attrs,...t}),this.editor.view.dispatch(n)}}const bJs=`.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 _Js(s,t,n){const r=document.querySelector("style[data-tiptap-style]");if(r!==null)return r;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 wJs extends MXs{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:n})=>{throw n},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:n,slice:r,moved:a})=>this.options.onDrop(n,r,a)),this.on("paste",({event:n,slice:r})=>this.options.onPaste(n,r)),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=_Js(bJs,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,n=!0){this.setOptions({editable:t}),n&&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,n){const r=OVt(n)?n(t,[...this.state.plugins]):[...this.state.plugins,t],a=this.state.reconfigure({plugins:r});return this.view.updateState(a),a}unregisterPlugin(t){if(this.isDestroyed)return;const n=this.state.plugins;let r=n;if([].concat(t).forEach(i=>{const l=typeof i=="string"?`${i}$`:i.key;r=r.filter(o=>!o.key.startsWith(l))}),n.length===r.length)return;const a=this.state.reconfigure({plugins:r});return this.view.updateState(a),a}createExtensionManager(){var t,n;const a=[...this.options.enableCoreExtensions?[fJs,HXs.configure({blockSeparator:(n=(t=this.options.coreExtensionOptions)===null||t===void 0?void 0:t.clipboardTextSerializer)===null||n===void 0?void 0:n.blockSeparator}),hJs,gJs,xJs,vJs,mJs,yJs].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 rq(a,this)}createCommandManager(){this.commandManager=new B6e({editor:this})}createSchema(){this.schema=this.extensionManager.schema}createView(){var t;let n;try{n=fWe(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()}}),n=fWe(this.options.content,this.schema,this.options.parseOptions,{errorOnInvalidContent:!1})}const r=VVt(n,this.options.autofocus);this.view=new NVt(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:nq.create({doc:n,selection:r||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 n=this.capturedTransaction;return this.capturedTransaction=null,n}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 n=this.state.apply(t),r=!this.state.selection.eq(n.selection);this.emit("beforeTransaction",{editor:this,transaction:t,nextState:n}),this.view.updateState(n),this.emit("transaction",{editor:this,transaction:t}),r&&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 YVt(this.state,t)}isActive(t,n){const r=typeof t=="string"?t:null,a=typeof t=="string"?n:t;return VQs(this.state,r,a)}getJSON(){return this.state.doc.toJSON()}getHTML(){return Fnt(this.state.doc.content,this.schema)}getText(t){const{blockSeparator:n=` `,textSerializers:r={}}=t||{};return zQs(this.state.doc,{blockSeparator:n,textSerializers:{...$Vt(this.schema),...r}})}get isEmpty(){return Unt(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,n){var r;return((r=this.$doc)===null||r===void 0?void 0:r.querySelector(t,n))||null}$nodes(t,n){var r;return((r=this.$doc)===null||r===void 0?void 0:r.querySelectorAll(t,n))||null}$pos(t){const n=this.state.doc.resolve(t);return new QO(n,this)}get $doc(){return this.$pos(0)}}function zG(s){return new U6e({find:s.find,handler:({state:t,range:n,match:r})=>{const a=Nd(s.getAttributes,void 0,r);if(a===!1||a===null)return null;const{tr:i}=t,l=r[r.length-1],o=r[0];if(l){const c=o.search(/\S/),d=n.from+o.indexOf(l),u=d+l.length;if($nt(n.from,n.to,t.doc).filter(f=>f.mark.type.excluded.find(x=>x===s.type&&x!==f.mark.type)).filter(f=>f.to>d).length)return null;un.from&&i.delete(n.from+c,d);const m=n.from+c+l.length;i.addMark(n.from+c,m,s.type.create(a||{})),i.removeStoredMark(s.type)}}})}function ZVt(s){return new U6e({find:s.find,handler:({state:t,range:n,match:r})=>{const a=Nd(s.getAttributes,void 0,r)||{},{tr:i}=t,l=n.from;let o=n.to;const c=s.type.create(a);if(r[1]){const d=r[0].lastIndexOf(r[1]);let u=l+d;u>o?u=o:o=u+r[1].length;const h=r[0][r[0].length-1];i.insertText(h,l+r[0].length-1),i.replaceWith(u,o,c)}else if(r[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 gWe(s){return new U6e({find:s.find,handler:({state:t,range:n,match:r})=>{const a=t.doc.resolve(n.from),i=Nd(s.getAttributes,void 0,r)||{};if(!a.node(-1).canReplaceWith(a.index(-1),a.indexAfter(-1),s.type))return null;t.tr.delete(n.from,n.to).setBlockType(n.from,n.from,s.type,i)}})}function kse(s){return new U6e({find:s.find,handler:({state:t,range:n,match:r,chain:a})=>{const i=Nd(s.getAttributes,void 0,r)||{},l=t.tr.delete(n.from,n.to),c=l.doc.resolve(n.from).blockRange(),d=c&&vnt(c,s.type,i);if(!d)return null;if(l.wrap(c,d),s.keepMarks&&s.editor){const{selection:h,storedMarks:m}=t,{splittableMarks:f}=s.editor.extensionManager,g=m||h.$to.parentOffset&&h.$from.marks();if(g){const x=g.filter(y=>f.includes(y.type.name));l.ensureMarks(x)}}if(s.keepAttributes){const h=s.type.name==="bulletList"||s.type.name==="orderedList"?"listItem":"taskList";a().updateAttributes(h,i).run()}const u=l.doc.resolve(n.from-1).nodeBefore;u&&u.type===s.type&&h6(l.doc,n.from-1)&&(!s.joinPredicate||s.joinPredicate(r,u))&&l.join(n.from-1)}})}let Rv=class xWe{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=Nd(Uo(this,"addOptions",{name:this.name}))),this.storage=Nd(Uo(this,"addStorage",{name:this.name,options:this.options}))||{}}static create(t={}){return new xWe(t)}configure(t={}){const n=this.extend({...this.config,addOptions:()=>q6e(this.options,t)});return n.name=this.name,n.parent=this.parent,n}extend(t={}){const n=new xWe(t);return n.parent=this,this.child=n,n.name=t.name?t.name:n.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: "${n.name}".`),n.options=Nd(Uo(n,"addOptions",{name:n.name})),n.storage=Nd(Uo(n,"addStorage",{name:n.name,options:n.options})),n}};function eB(s){return new zVt({find:s.find,handler:({state:t,range:n,match:r,pasteEvent:a})=>{const i=Nd(s.getAttributes,void 0,r,a);if(i===!1||i===null)return null;const{tr:l}=t,o=r[r.length-1],c=r[0];let d=n.to;if(o){const u=c.search(/\S/),h=n.from+c.indexOf(o),m=h+o.length;if($nt(n.from,n.to,t.doc).filter(g=>g.mark.type.excluded.find(y=>y===s.type&&y!==g.mark.type)).filter(g=>g.to>h).length)return null;mn.from&&l.delete(n.from+u,h),d=n.from+u+o.length,l.addMark(n.from+u,d,s.type.create(i||{})),l.removeStoredMark(s.type)}}})}function jJs(s,t){const{selection:n}=s,{$from:r}=n;if(n instanceof El){const i=r.index();return r.parent.canReplaceWith(i,i+1,t)}let a=r.depth;for(;a>=0;){const i=r.index(a);if(r.node(a).contentMatchAt(i).matchType(t))return!0;a-=1}return!1}function NJs(s){return new zVt({find:s.find,handler({match:t,chain:n,range:r,pasteEvent:a}){const i=Nd(s.getAttributes,void 0,t,a),l=Nd(s.getContent,void 0,i);if(i===!1||i===null)return null;const o={type:s.type.name,attrs:i};l&&(o.content=l),t.input&&n().deleteRange(r).insertContentAt(r.from,o)}})}function kJs(s){return s&&s.__esModule&&Object.prototype.hasOwnProperty.call(s,"default")?s.default:s}var XVt={exports:{}},yBe={};/** * @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 M1t;function SJs(){if(M1t)return yBe;M1t=1;var s=Gt;function t(h,m){return h===m&&(h!==0||1/h===1/m)||h!==h&&m!==m}var n=typeof Object.is=="function"?Object.is:t,r=s.useState,a=s.useEffect,i=s.useLayoutEffect,l=s.useDebugValue;function o(h,m){var f=m(),g=r({inst:{value:f,getSnapshot:m}}),x=g[0].inst,y=g[1];return i(function(){x.value=f,x.getSnapshot=m,c(x)&&y({inst:x})},[h,f,m]),a(function(){return c(x)&&y({inst:x}),h(function(){c(x)&&y({inst:x})})},[h]),l(f),f}function c(h){var m=h.getSnapshot;h=h.value;try{var f=m();return!n(h,f)}catch{return!0}}function d(h,m){return m()}var u=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?d:o;return yBe.useSyncExternalStore=s.useSyncExternalStore!==void 0?s.useSyncExternalStore:u,yBe}XVt.exports=SJs();var qnt=XVt.exports;const CJs=(...s)=>t=>{s.forEach(n=>{typeof n=="function"?n(t):n&&(n.current=t)})},AJs=({contentComponent:s})=>{const t=qnt.useSyncExternalStore(s.subscribe,s.getSnapshot,s.getServerSnapshot);return Gt.createElement(Gt.Fragment,null,Object.values(t))};function EJs(){const s=new Set;let t={};return{subscribe(n){return s.add(n),()=>{s.delete(n)}},getSnapshot(){return t},getServerSnapshot(){return t},setRenderer(n,r){t={...t,[n]:G6t.createPortal(r.reactElement,r.element,n)},s.forEach(a=>a())},removeRenderer(n){const r={...t};delete r[n],t=r,s.forEach(a=>a())}}}class TJs extends Gt.Component{constructor(t){var n;super(t),this.editorContentRef=Gt.createRef(),this.initialized=!1,this.state={hasContentComponentInitialized:!!(!((n=t.editor)===null||n===void 0)&&n.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 n=this.editorContentRef.current;n.append(...t.options.element.childNodes),t.setOptions({element:n}),t.contentComponent=EJs(),this.state.hasContentComponentInitialized||(this.unsubscribeToContentComponent=t.contentComponent.subscribe(()=>{this.setState(r=>r.hasContentComponentInitialized?r:{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 n=document.createElement("div");n.append(...t.options.element.childNodes),t.setOptions({element:n})}render(){const{editor:t,innerRef:n,...r}=this.props;return Gt.createElement(Gt.Fragment,null,Gt.createElement("div",{ref:CJs(n,this.editorContentRef),...r}),(t==null?void 0:t.contentComponent)&&Gt.createElement(AJs,{contentComponent:t.contentComponent}))}}const MJs=j.forwardRef((s,t)=>{const n=Gt.useMemo(()=>Math.floor(Math.random()*4294967295).toString(),[s.editor]);return Gt.createElement(TJs,{key:n,innerRef:t,...s})}),H6e=Gt.memo(MJs);var PJs=function s(t,n){if(t===n)return!0;if(t&&n&&typeof t=="object"&&typeof n=="object"){if(t.constructor!==n.constructor)return!1;var r,a,i;if(Array.isArray(t)){if(r=t.length,r!=n.length)return!1;for(a=r;a--!==0;)if(!s(t[a],n[a]))return!1;return!0}if(t instanceof Map&&n instanceof Map){if(t.size!==n.size)return!1;for(a of t.entries())if(!n.has(a[0]))return!1;for(a of t.entries())if(!s(a[1],n.get(a[0])))return!1;return!0}if(t instanceof Set&&n instanceof Set){if(t.size!==n.size)return!1;for(a of t.entries())if(!n.has(a[0]))return!1;return!0}if(ArrayBuffer.isView(t)&&ArrayBuffer.isView(n)){if(r=t.length,r!=n.length)return!1;for(a=r;a--!==0;)if(t[a]!==n[a])return!1;return!0}if(t.constructor===RegExp)return t.source===n.source&&t.flags===n.flags;if(t.valueOf!==Object.prototype.valueOf)return t.valueOf()===n.valueOf();if(t.toString!==Object.prototype.toString)return t.toString()===n.toString();if(i=Object.keys(t),r=i.length,r!==Object.keys(n).length)return!1;for(a=r;a--!==0;)if(!Object.prototype.hasOwnProperty.call(n,i[a]))return!1;for(a=r;a--!==0;){var l=i[a];if(!(l==="_owner"&&t.$$typeof)&&!s(t[l],n[l]))return!1}return!0}return t!==t&&n!==n},IJs=kJs(PJs),QVt={exports:{}},vBe={};/** * @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 P1t;function LJs(){if(P1t)return vBe;P1t=1;var s=Gt,t=qnt;function n(d,u){return d===u&&(d!==0||1/d===1/u)||d!==d&&u!==u}var r=typeof Object.is=="function"?Object.is:n,a=t.useSyncExternalStore,i=s.useRef,l=s.useEffect,o=s.useMemo,c=s.useDebugValue;return vBe.useSyncExternalStoreWithSelector=function(d,u,h,m,f){var g=i(null);if(g.current===null){var x={hasValue:!1,value:null};g.current=x}else x=g.current;g=o(function(){function v(E){if(!b){if(b=!0,w=E,E=m(E),f!==void 0&&x.hasValue){var I=x.value;if(f(I,E))return S=I}return S=E}if(I=S,r(w,E))return I;var P=m(E);return f!==void 0&&f(I,P)?I:(w=E,S=P)}var b=!1,w,S,C=h===void 0?null:h;return[function(){return v(u())},C===null?void 0:function(){return v(C())}]},[u,h,m,f]);var y=a(d,g[0],g[1]);return l(function(){x.hasValue=!0,x.value=y},[y]),c(y),y},vBe}QVt.exports=LJs();var RJs=QVt.exports;const DJs=typeof window<"u"?j.useLayoutEffect:j.useEffect;class FJs{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 n=()=>{this.transactionNumber+=1,this.subscribers.forEach(a=>a())},r=this.editor;return r.on("transaction",n),()=>{r.off("transaction",n)}}}}function OJs(s){var t;const[n]=j.useState(()=>new FJs(s.editor)),r=RJs.useSyncExternalStoreWithSelector(n.subscribe,n.getSnapshot,n.getServerSnapshot,s.selector,(t=s.equalityFn)!==null&&t!==void 0?t:IJs);return DJs(()=>n.watch(s.editor),[s.editor,n]),j.useDebugValue(r),r}const zJs=!1,yWe=typeof window>"u",BJs=yWe||!!(typeof window<"u"&&window.next);class Vnt{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(n=>n())}getInitialEditor(){return this.options.current.immediatelyRender===void 0?yWe||BJs?null:this.createEditor():(this.options.current.immediatelyRender,this.options.current.immediatelyRender?this.createEditor():null)}createEditor(){const t={...this.options.current,onBeforeCreate:(...r)=>{var a,i;return(i=(a=this.options.current).onBeforeCreate)===null||i===void 0?void 0:i.call(a,...r)},onBlur:(...r)=>{var a,i;return(i=(a=this.options.current).onBlur)===null||i===void 0?void 0:i.call(a,...r)},onCreate:(...r)=>{var a,i;return(i=(a=this.options.current).onCreate)===null||i===void 0?void 0:i.call(a,...r)},onDestroy:(...r)=>{var a,i;return(i=(a=this.options.current).onDestroy)===null||i===void 0?void 0:i.call(a,...r)},onFocus:(...r)=>{var a,i;return(i=(a=this.options.current).onFocus)===null||i===void 0?void 0:i.call(a,...r)},onSelectionUpdate:(...r)=>{var a,i;return(i=(a=this.options.current).onSelectionUpdate)===null||i===void 0?void 0:i.call(a,...r)},onTransaction:(...r)=>{var a,i;return(i=(a=this.options.current).onTransaction)===null||i===void 0?void 0:i.call(a,...r)},onUpdate:(...r)=>{var a,i;return(i=(a=this.options.current).onUpdate)===null||i===void 0?void 0:i.call(a,...r)},onContentError:(...r)=>{var a,i;return(i=(a=this.options.current).onContentError)===null||i===void 0?void 0:i.call(a,...r)},onDrop:(...r)=>{var a,i;return(i=(a=this.options.current).onDrop)===null||i===void 0?void 0:i.call(a,...r)},onPaste:(...r)=>{var a,i;return(i=(a=this.options.current).onPaste)===null||i===void 0?void 0:i.call(a,...r)}};return new wJs(t)}getEditor(){return this.editor}getServerSnapshot(){return null}subscribe(t){return this.subscriptions.add(t),()=>{this.subscriptions.delete(t)}}static compareOptions(t,n){return Object.keys(t).every(r=>["onCreate","onBeforeCreate","onDestroy","onUpdate","onTransaction","onFocus","onBlur","onSelectionUpdate","onContentError","onDrop","onPaste"].includes(r)?!0:r==="extensions"&&t.extensions&&n.extensions?t.extensions.length!==n.extensions.length?!1:t.extensions.every((a,i)=>{var l;return a===((l=n.extensions)===null||l===void 0?void 0:l[i])}):t[r]===n[r])}onRender(t){return()=>(this.isComponentMounted=!0,clearTimeout(this.scheduledDestructionTimeout),this.editor&&!this.editor.isDestroyed&&t.length===0?Vnt.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((r,a)=>r===t[a]))return}this.editor&&!this.editor.isDestroyed&&this.editor.destroy(),this.setEditor(this.createEditor()),this.previousDeps=t}scheduleDestroy(){const t=this.instanceId,n=this.editor;this.scheduledDestructionTimeout=setTimeout(()=>{if(this.isComponentMounted&&this.instanceId===t){n&&n.setOptions(this.options.current);return}n&&!n.isDestroyed&&(n.destroy(),this.instanceId===t&&this.setEditor(null))},1)}}function G6e(s={},t=[]){const n=j.useRef(s);n.current=s;const[r]=j.useState(()=>new Vnt(n)),a=qnt.useSyncExternalStore(r.subscribe,r.getEditor,r.getServerSnapshot);return j.useDebugValue(a),j.useEffect(r.onRender(t)),OJs({editor:a,selector:({transactionNumber:i})=>s.shouldRerenderOnTransaction===!1?null:s.immediatelyRender&&i===0?0:i+1}),a}const $Js=j.createContext({editor:null});$Js.Consumer;const UJs=j.createContext({onDragStart:void 0}),qJs=()=>j.useContext(UJs);Gt.forwardRef((s,t)=>{const{onDragStart:n}=qJs(),r=s.as||"div";return Gt.createElement(r,{...s,ref:t,"data-node-view-wrapper":"",onDragStart:n,style:{whiteSpace:"normal",...s.style}})});const VJs=/^\s*>\s$/,HJs=Rv.create({name:"blockquote",addOptions(){return{HTMLAttributes:{}}},content:"block+",group:"block",defining:!0,parseHTML(){return[{tag:"blockquote"}]},renderHTML({HTMLAttributes:s}){return["blockquote",ep(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[kse({find:VJs,type:this.type})]}}),GJs=/(?:^|\s)(\*\*(?!\s+\*\*)((?:[^*]+))\*\*(?!\s+\*\*))$/,WJs=/(?:^|\s)(\*\*(?!\s+\*\*)((?:[^*]+))\*\*(?!\s+\*\*))/g,KJs=/(?:^|\s)(__(?!\s+__)((?:[^_]+))__(?!\s+__))$/,YJs=/(?:^|\s)(__(?!\s+__)((?:[^_]+))__(?!\s+__))/g,ZJs=xC.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",ep(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[zG({find:GJs,type:this.type}),zG({find:KJs,type:this.type})]},addPasteRules(){return[eB({find:WJs,type:this.type}),eB({find:YJs,type:this.type})]}}),XJs="listItem",I1t="textStyle",L1t=/^\s*([-+*])\s$/,QJs=Rv.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",ep(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(XJs,this.editor.getAttributes(I1t)).run():s.toggleList(this.name,this.options.itemTypeName,this.options.keepMarks)}},addKeyboardShortcuts(){return{"Mod-Shift-8":()=>this.editor.commands.toggleBulletList()}},addInputRules(){let s=kse({find:L1t,type:this.type});return(this.options.keepMarks||this.options.keepAttributes)&&(s=kse({find:L1t,type:this.type,keepMarks:this.options.keepMarks,keepAttributes:this.options.keepAttributes,getAttributes:()=>this.editor.getAttributes(I1t),editor:this.editor})),[s]}}),JJs=/(^|[^`])`([^`]+)`(?!`)/,een=/(^|[^`])`([^`]+)`(?!`)/g,ten=xC.create({name:"code",addOptions(){return{HTMLAttributes:{}}},excludes:"_",code:!0,exitable:!0,parseHTML(){return[{tag:"code"}]},renderHTML({HTMLAttributes:s}){return["code",ep(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[zG({find:JJs,type:this.type})]},addPasteRules(){return[eB({find:een,type:this.type})]}}),sen=/^```([a-z]+)?[\s\n]$/,nen=/^~~~([a-z]+)?[\s\n]$/,ren=Rv.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:n}=this.options,i=[...((t=s.firstElementChild)===null||t===void 0?void 0:t.classList)||[]].filter(l=>l.startsWith(n)).map(l=>l.replace(n,""))[0];return i||null},rendered:!1}}},parseHTML(){return[{tag:"pre",preserveWhitespace:"full"}]},renderHTML({node:s,HTMLAttributes:t}){return["pre",ep(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,n=t.pos===1;return!s||t.parent.type.name!==this.name?!1:n||!t.parent.textContent.length?this.editor.commands.clearNodes():!1},Enter:({editor:s})=>{if(!this.options.exitOnTripleEnter)return!1;const{state:t}=s,{selection:n}=t,{$from:r,empty:a}=n;if(!a||r.parent.type!==this.type)return!1;const i=r.parentOffset===r.parent.nodeSize-2,l=r.parent.textContent.endsWith(` `);return!i||!l?!1:s.chain().command(({tr:o})=>(o.delete(r.pos-2,r.pos),!0)).exitCode().run()},ArrowDown:({editor:s})=>{if(!this.options.exitOnArrowDown)return!1;const{state:t}=s,{selection:n,doc:r}=t,{$from:a,empty:i}=n;if(!i||a.parent.type!==this.type||!(a.parentOffset===a.parent.nodeSize-2))return!1;const o=a.after();return o===void 0?!1:r.nodeAt(o)?s.commands.command(({tr:d})=>(d.setSelection(oc.near(r.resolve(o))),!0)):s.commands.exitCode()}}},addInputRules(){return[gWe({find:sen,type:this.type,getAttributes:s=>({language:s[1]})}),gWe({find:nen,type:this.type,getAttributes:s=>({language:s[1]})})]},addProseMirrorPlugins(){return[new $0({key:new I1("codeBlockVSCodeHandler"),props:{handlePaste:(s,t)=>{if(!t.clipboardData||this.editor.isActive(this.type.name))return!1;const n=t.clipboardData.getData("text/plain"),r=t.clipboardData.getData("vscode-editor-data"),a=r?JSON.parse(r):void 0,i=a==null?void 0:a.mode;if(!n||!i)return!1;const{tr:l,schema:o}=s.state,c=o.text(n.replace(/\r\n?/g,` `));return l.replaceSelectionWith(this.type.create({language:i},c)),l.selection.$from.parent.type!==this.type&&l.setSelection(Al.near(l.doc.resolve(Math.max(0,l.selection.from-2)))),l.setMeta("paste",!0),s.dispatch(l),!0}}})]}}),aen=Rv.create({name:"doc",topNode:!0,content:"block+"});function ien(s={}){return new $0({view(t){return new oen(t,s)}})}class oen{constructor(t,n){var r;this.editorView=t,this.cursorPos=null,this.element=null,this.timeout=-1,this.lastDragEvent=null,this.width=(r=n.width)!==null&&r!==void 0?r:1,this.color=n.color===!1?void 0:n.color||"black",this.class=n.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.setCursor(null),this.handlers.forEach(({name:t,handler:n})=>this.editorView.dom.removeEventListener(t,n))}update(t,n){if(this.cursorPos!=null&&n.doc!=t.state.doc)if(this.lastDragEvent){let r=this.computeTarget(this.lastDragEvent);r==this.cursorPos?this.updateOverlay():this.setCursor(r)}else 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),n=!t.parent.inlineContent,r,a=this.editorView.dom,i=a.getBoundingClientRect(),l=i.width/a.offsetWidth,o=i.height/a.offsetHeight;if(n){let h=t.nodeBefore,m=t.nodeAfter;if(h||m){let f=this.editorView.nodeDOM(this.cursorPos-(h?h.nodeSize:0));if(f){let g=f.getBoundingClientRect(),x=h?g.bottom:g.top;h&&m&&(x=(x+this.editorView.nodeDOM(this.cursorPos).getBoundingClientRect().top)/2);let y=this.width/2*o;r={left:g.left,right:g.right,top:x-y,bottom:x+y}}}}if(!r){let h=this.editorView.coordsAtPos(this.cursorPos),m=this.width/2*l;r={left:h.left-m,right:h.left+m,top:h.top,bottom:h.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",n),this.element.classList.toggle("prosemirror-dropcursor-inline",!n);let d,u;if(!c||c==document.body&&getComputedStyle(c).position=="static")d=-pageXOffset,u=-pageYOffset;else{let h=c.getBoundingClientRect(),m=h.width/c.offsetWidth,f=h.height/c.offsetHeight;d=h.left-c.scrollLeft*m,u=h.top-c.scrollTop*f}this.element.style.left=(r.left-d)/l+"px",this.element.style.top=(r.top-u)/o+"px",this.element.style.width=(r.right-r.left)/l+"px",this.element.style.height=(r.bottom-r.top)/o+"px"}scheduleRemoval(t){clearTimeout(this.timeout),this.timeout=setTimeout(()=>this.setCursor(null),t)}computeTarget(t){let n=this.editorView.posAtCoords({left:t.clientX,top:t.clientY}),r=n&&n.inside>=0&&this.editorView.state.doc.nodeAt(n.inside),a=r&&r.type.spec.disableDropCursor,i=typeof a=="function"?a(this.editorView,n,t):a;if(!n||i)return null;let l=n.pos;if(this.editorView.dragging&&this.editorView.dragging.slice){let o=Lqt(this.editorView.state.doc,l,this.editorView.dragging.slice);o!=null&&(l=o)}return l}dragover(t){if(!this.editorView.editable)return;this.lastDragEvent=t;let n=this.computeTarget(t);n!=null&&(this.setCursor(n),this.scheduleRemoval(5e3))}dragend(){this.scheduleRemoval(20)}drop(){this.scheduleRemoval(20)}dragleave(t){this.editorView.dom.contains(t.relatedTarget)||this.setCursor(null)}}const len=Tb.create({name:"dropCursor",addOptions(){return{color:"currentColor",width:1,class:void 0}},addProseMirrorPlugins(){return[ien(this.options)]}});class bx extends oc{constructor(t){super(t,t)}map(t,n){let r=t.resolve(n.map(this.head));return bx.valid(r)?new bx(r):oc.near(r)}content(){return Ki.empty}eq(t){return t instanceof bx&&t.head==this.head}toJSON(){return{type:"gapcursor",pos:this.head}}static fromJSON(t,n){if(typeof n.pos!="number")throw new RangeError("Invalid input for GapCursor.fromJSON");return new bx(t.resolve(n.pos))}getBookmark(){return new Hnt(this.anchor)}static valid(t){let n=t.parent;if(n.inlineContent||!cen(t)||!den(t))return!1;let r=n.type.spec.allowGapCursor;if(r!=null)return r;let a=n.contentMatchAt(t.index()).defaultType;return a&&a.isTextblock}static findGapCursorFrom(t,n,r=!1){e:for(;;){if(!r&&bx.valid(t))return t;let a=t.pos,i=null;for(let l=t.depth;;l--){let o=t.node(l);if(n>0?t.indexAfter(l)0){i=o.child(n>0?t.indexAfter(l):t.index(l)-1);break}else if(l==0)return null;a+=n;let c=t.doc.resolve(a);if(bx.valid(c))return c}for(;;){let l=n>0?i.firstChild:i.lastChild;if(!l){if(i.isAtom&&!i.isText&&!El.isSelectable(i)){t=t.doc.resolve(a+i.nodeSize*n),r=!1;continue e}break}i=l,a+=n;let o=t.doc.resolve(a);if(bx.valid(o))return o}return null}}}bx.prototype.visible=!1;bx.findFrom=bx.findGapCursorFrom;oc.jsonID("gapcursor",bx);class Hnt{constructor(t){this.pos=t}map(t){return new Hnt(t.map(this.pos))}resolve(t){let n=t.resolve(this.pos);return bx.valid(n)?new bx(n):oc.near(n)}}function JVt(s){return s.isAtom||s.spec.isolating||s.spec.createGapCursor}function cen(s){for(let t=s.depth;t>=0;t--){let n=s.index(t),r=s.node(t);if(n==0){if(r.type.spec.isolating)return!0;continue}for(let a=r.child(n-1);;a=a.lastChild){if(a.childCount==0&&!a.inlineContent||JVt(a.type))return!0;if(a.inlineContent)return!1}}return!0}function den(s){for(let t=s.depth;t>=0;t--){let n=s.indexAfter(t),r=s.node(t);if(n==r.childCount){if(r.type.spec.isolating)return!0;continue}for(let a=r.child(n);;a=a.firstChild){if(a.childCount==0&&!a.inlineContent||JVt(a.type))return!0;if(a.inlineContent)return!1}}return!0}function uen(){return new $0({props:{decorations:pen,createSelectionBetween(s,t,n){return t.pos==n.pos&&bx.valid(n)?new bx(n):null},handleClick:men,handleKeyDown:hen,handleDOMEvents:{beforeinput:fen}}})}const hen=Mnt({ArrowLeft:gde("horiz",-1),ArrowRight:gde("horiz",1),ArrowUp:gde("vert",-1),ArrowDown:gde("vert",1)});function gde(s,t){const n=s=="vert"?t>0?"down":"up":t>0?"right":"left";return function(r,a,i){let l=r.selection,o=t>0?l.$to:l.$from,c=l.empty;if(l instanceof Al){if(!i.endOfTextblock(n)||o.depth==0)return!1;c=!1,o=r.doc.resolve(t>0?o.after():o.before())}let d=bx.findGapCursorFrom(o,t,c);return d?(a&&a(r.tr.setSelection(new bx(d))),!0):!1}}function men(s,t,n){if(!s||!s.editable)return!1;let r=s.state.doc.resolve(t);if(!bx.valid(r))return!1;let a=s.posAtCoords({left:n.clientX,top:n.clientY});return a&&a.inside>-1&&El.isSelectable(s.state.doc.nodeAt(a.inside))?!1:(s.dispatch(s.state.tr.setSelection(new bx(r))),!0)}function fen(s,t){if(t.inputType!="insertCompositionText"||!(s.state.selection instanceof bx))return!1;let{$from:n}=s.state.selection,r=n.parent.contentMatchAt(n.index()).findWrapping(s.state.schema.nodes.text);if(!r)return!1;let a=hi.empty;for(let l=r.length-1;l>=0;l--)a=hi.from(r[l].createAndFill(null,a));let i=s.state.tr.replace(n.pos,n.pos,new Ki(a,0,0));return i.setSelection(Al.near(i.doc.resolve(n.pos+1))),s.dispatch(i),!1}function pen(s){if(!(s.selection instanceof bx))return null;let t=document.createElement("div");return t.className="ProseMirror-gapcursor",vx.create(s.doc,[__.widget(s.selection.head,t,{key:"gapcursor"})])}const gen=Tb.create({name:"gapCursor",addProseMirrorPlugins(){return[uen()]},extendNodeSchema(s){var t;const n={name:s.name,options:s.options,storage:s.storage};return{allowGapCursor:(t=Nd(Uo(s,"allowGapCursor",n)))!==null&&t!==void 0?t:null}}}),xen=Rv.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",ep(this.options.HTMLAttributes,s)]},renderText(){return` `},addCommands(){return{setHardBreak:()=>({commands:s,chain:t,state:n,editor:r})=>s.first([()=>s.exitCode(),()=>s.command(()=>{const{selection:a,storedMarks:i}=n;if(a.$from.parent.type.spec.isolating)return!1;const{keepMarks:l}=this.options,{splittableMarks:o}=r.extensionManager,c=i||a.$to.parentOffset&&a.$from.marks();return t().insertContent({type:this.name}).command(({tr:d,dispatch:u})=>{if(u&&c&&l){const h=c.filter(m=>o.includes(m.type.name));d.ensureMarks(h)}return!0}).run()})])}},addKeyboardShortcuts(){return{"Mod-Enter":()=>this.editor.commands.setHardBreak(),"Shift-Enter":()=>this.editor.commands.setHardBreak()}}}),yen=Rv.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]}`,ep(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=>gWe({find:new RegExp(`^(#{${Math.min(...this.options.levels)},${s}})\\s$`),type:this.type,getAttributes:{level:s}}))}});var uTe=200,Iv=function(){};Iv.prototype.append=function(t){return t.length?(t=Iv.from(t),!this.length&&t||t.length=n?Iv.empty:this.sliceInner(Math.max(0,t),Math.min(this.length,n))};Iv.prototype.get=function(t){if(!(t<0||t>=this.length))return this.getInner(t)};Iv.prototype.forEach=function(t,n,r){n===void 0&&(n=0),r===void 0&&(r=this.length),n<=r?this.forEachInner(t,n,r,0):this.forEachInvertedInner(t,n,r,0)};Iv.prototype.map=function(t,n,r){n===void 0&&(n=0),r===void 0&&(r=this.length);var a=[];return this.forEach(function(i,l){return a.push(t(i,l))},n,r),a};Iv.from=function(t){return t instanceof Iv?t:t&&t.length?new eHt(t):Iv.empty};var eHt=function(s){function t(r){s.call(this),this.values=r}s&&(t.__proto__=s),t.prototype=Object.create(s&&s.prototype),t.prototype.constructor=t;var n={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<=uTe)return new t(this.values.concat(a.flatten()))},t.prototype.leafPrepend=function(a){if(this.length+a.length<=uTe)return new t(a.flatten().concat(this.values))},n.length.get=function(){return this.values.length},n.depth.get=function(){return 0},Object.defineProperties(t.prototype,n),t}(Iv);Iv.empty=new eHt([]);var ven=function(s){function t(n,r){s.call(this),this.left=n,this.right=r,this.length=n.length+r.length,this.depth=Math.max(n.depth,r.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(r){return ro&&this.right.forEachInner(r,Math.max(a-o,0),Math.min(this.length,i)-o,l+o)===!1)return!1},t.prototype.forEachInvertedInner=function(r,a,i,l){var o=this.left.length;if(a>o&&this.right.forEachInvertedInner(r,a-o,Math.max(i,o)-o,l+o)===!1||i=i?this.right.slice(r-i,a-i):this.left.slice(r,i).append(this.right.slice(0,a-i))},t.prototype.leafAppend=function(r){var a=this.right.leafAppend(r);if(a)return new t(this.left,a)},t.prototype.leafPrepend=function(r){var a=this.left.leafPrepend(r);if(a)return new t(a,this.right)},t.prototype.appendInner=function(r){return this.left.depth>=Math.max(this.right.depth,r.depth)+1?new t(this.left,new t(this.right,r)):new t(this,r)},t}(Iv);const ben=500;class qS{constructor(t,n){this.items=t,this.eventCount=n}popEvent(t,n){if(this.eventCount==0)return null;let r=this.items.length;for(;;r--)if(this.items.get(r-1).selection){--r;break}let a,i;n&&(a=this.remapping(r,this.items.length),i=a.maps.length);let l=t.tr,o,c,d=[],u=[];return this.items.forEach((h,m)=>{if(!h.step){a||(a=this.remapping(r,m+1),i=a.maps.length),i--,u.push(h);return}if(a){u.push(new kM(h.map));let f=h.step.map(a.slice(i)),g;f&&l.maybeStep(f).doc&&(g=l.mapping.maps[l.mapping.maps.length-1],d.push(new kM(g,void 0,void 0,d.length+u.length))),i--,g&&a.appendMap(g,i)}else l.maybeStep(h.step);if(h.selection)return o=a?h.selection.map(a.slice(i)):h.selection,c=new qS(this.items.slice(0,r).append(u.reverse().concat(d)),this.eventCount-1),!1},this.items.length,0),{remaining:c,transform:l,selection:o}}addTransform(t,n,r,a){let i=[],l=this.eventCount,o=this.items,c=!a&&o.length?o.get(o.length-1):null;for(let u=0;uwen&&(o=_en(o,d),l-=d),new qS(o.append(i),l)}remapping(t,n){let r=new yse;return this.items.forEach((a,i)=>{let l=a.mirrorOffset!=null&&i-a.mirrorOffset>=t?r.maps.length-a.mirrorOffset:void 0;r.appendMap(a.map,l)},t,n),r}addMaps(t){return this.eventCount==0?this:new qS(this.items.append(t.map(n=>new kM(n))),this.eventCount)}rebased(t,n){if(!this.eventCount)return this;let r=[],a=Math.max(0,this.items.length-n),i=t.mapping,l=t.steps.length,o=this.eventCount;this.items.forEach(m=>{m.selection&&o--},a);let c=n;this.items.forEach(m=>{let f=i.getMirror(--c);if(f==null)return;l=Math.min(l,f);let g=i.maps[f];if(m.step){let x=t.steps[f].invert(t.docs[f]),y=m.selection&&m.selection.map(i.slice(c+1,f));y&&o++,r.push(new kM(g,x,y))}else r.push(new kM(g))},a);let d=[];for(let m=n;mben&&(h=h.compress(this.items.length-r.length)),h}emptyItemCount(){let t=0;return this.items.forEach(n=>{n.step||t++}),t}compress(t=this.items.length){let n=this.remapping(0,t),r=n.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(n.slice(r)),d=c&&c.getMap();if(r--,d&&n.appendMap(d,r),c){let u=l.selection&&l.selection.map(n.slice(r));u&&i++;let h=new kM(d.invert(),c,u),m,f=a.length-1;(m=a.length&&a[f].merge(h))?a[f]=m:a.push(h)}}else l.map&&r--},this.items.length,0),new qS(Iv.from(a.reverse()),i)}}qS.empty=new qS(Iv.empty,0);function _en(s,t){let n;return s.forEach((r,a)=>{if(r.selection&&t--==0)return n=a,!1}),s.slice(n)}let kM=class tHt{constructor(t,n,r,a){this.map=t,this.step=n,this.selection=r,this.mirrorOffset=a}merge(t){if(this.step&&t.step&&!t.selection){let n=t.step.merge(this.step);if(n)return new tHt(n.getMap().invert(),n,this.selection)}}};class gP{constructor(t,n,r,a,i){this.done=t,this.undone=n,this.prevRanges=r,this.prevTime=a,this.prevComposition=i}}const wen=20;function jen(s,t,n,r){let a=n.getMeta(x7),i;if(a)return a.historyState;n.getMeta(Sen)&&(s=new gP(s.done,s.undone,null,0,-1));let l=n.getMeta("appendedTransaction");if(n.steps.length==0)return s;if(l&&l.getMeta(x7))return l.getMeta(x7).redo?new gP(s.done.addTransform(n,void 0,r,x3e(t)),s.undone,R1t(n.mapping.maps),s.prevTime,s.prevComposition):new gP(s.done,s.undone.addTransform(n,void 0,r,x3e(t)),null,s.prevTime,s.prevComposition);if(n.getMeta("addToHistory")!==!1&&!(l&&l.getMeta("addToHistory")===!1)){let o=n.getMeta("composition"),c=s.prevTime==0||!l&&s.prevComposition!=o&&(s.prevTime<(n.time||0)-r.newGroupDelay||!Nen(n,s.prevRanges)),d=l?bBe(s.prevRanges,n.mapping):R1t(n.mapping.maps);return new gP(s.done.addTransform(n,c?t.selection.getBookmark():void 0,r,x3e(t)),qS.empty,d,n.time,o??s.prevComposition)}else return(i=n.getMeta("rebased"))?new gP(s.done.rebased(n,i),s.undone.rebased(n,i),bBe(s.prevRanges,n.mapping),s.prevTime,s.prevComposition):new gP(s.done.addMaps(n.mapping.maps),s.undone.addMaps(n.mapping.maps),bBe(s.prevRanges,n.mapping),s.prevTime,s.prevComposition)}function Nen(s,t){if(!t)return!1;if(!s.docChanged)return!0;let n=!1;return s.mapping.maps[0].forEach((r,a)=>{for(let i=0;i=t[i]&&(n=!0)}),n}function R1t(s){let t=[];for(let n=s.length-1;n>=0&&t.length==0;n--)s[n].forEach((r,a,i,l)=>t.push(i,l));return t}function bBe(s,t){if(!s)return null;let n=[];for(let r=0;r{let a=x7.getState(n);if(!a||(s?a.undone:a.done).eventCount==0)return!1;if(r){let i=ken(a,n,s);i&&r(t?i.scrollIntoView():i)}return!0}}const nHt=sHt(!1,!0),rHt=sHt(!0,!0),Aen=Tb.create({name:"history",addOptions(){return{depth:100,newGroupDelay:500}},addCommands(){return{undo:()=>({state:s,dispatch:t})=>nHt(s,t),redo:()=>({state:s,dispatch:t})=>rHt(s,t)}},addProseMirrorPlugins(){return[Cen(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()}}}),Een=Rv.create({name:"horizontalRule",addOptions(){return{HTMLAttributes:{}}},group:"block",parseHTML(){return[{tag:"hr"}]},renderHTML({HTMLAttributes:s}){return["hr",ep(this.options.HTMLAttributes,s)]},addCommands(){return{setHorizontalRule:()=>({chain:s,state:t})=>{if(!jJs(t,t.schema.nodes[this.name]))return!1;const{selection:n}=t,{$from:r,$to:a}=n,i=s();return r.parentOffset===0?i.insertContentAt({from:Math.max(r.pos-1,0),to:a.pos},{type:this.name}):HQs(n)?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,u=d.end();if(d.nodeAfter)d.nodeAfter.isTextblock?l.setSelection(Al.create(l.doc,d.pos+1)):d.nodeAfter.isBlock?l.setSelection(El.create(l.doc,d.pos)):l.setSelection(Al.create(l.doc,d.pos));else{const h=(c=d.parent.type.contentMatch.defaultType)===null||c===void 0?void 0:c.create();h&&(l.insert(u,h),l.setSelection(Al.create(l.doc,u+1)))}l.scrollIntoView()}return!0}).run()}}},addInputRules(){return[ZVt({find:/^(?:---|—-|___\s|\*\*\*\s)$/,type:this.type})]}}),Ten=/(?:^|\s)(\*(?!\s+\*)((?:[^*]+))\*(?!\s+\*))$/,Men=/(?:^|\s)(\*(?!\s+\*)((?:[^*]+))\*(?!\s+\*))/g,Pen=/(?:^|\s)(_(?!\s+_)((?:[^_]+))_(?!\s+_))$/,Ien=/(?:^|\s)(_(?!\s+_)((?:[^_]+))_(?!\s+_))/g,Len=xC.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",ep(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[zG({find:Ten,type:this.type}),zG({find:Pen,type:this.type})]},addPasteRules(){return[eB({find:Men,type:this.type}),eB({find:Ien,type:this.type})]}}),Ren=Rv.create({name:"listItem",addOptions(){return{HTMLAttributes:{},bulletListTypeName:"bulletList",orderedListTypeName:"orderedList"}},content:"paragraph block*",defining:!0,parseHTML(){return[{tag:"li"}]},renderHTML({HTMLAttributes:s}){return["li",ep(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)}}}),Den="listItem",F1t="textStyle",O1t=/^(\d+)\.\s$/,Fen=Rv.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,...n}=s;return t===1?["ol",ep(this.options.HTMLAttributes,n),0]:["ol",ep(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(Den,this.editor.getAttributes(F1t)).run():s.toggleList(this.name,this.options.itemTypeName,this.options.keepMarks)}},addKeyboardShortcuts(){return{"Mod-Shift-7":()=>this.editor.commands.toggleOrderedList()}},addInputRules(){let s=kse({find:O1t,type:this.type,getAttributes:t=>({start:+t[1]}),joinPredicate:(t,n)=>n.childCount+n.attrs.start===+t[1]});return(this.options.keepMarks||this.options.keepAttributes)&&(s=kse({find:O1t,type:this.type,keepMarks:this.options.keepMarks,keepAttributes:this.options.keepAttributes,getAttributes:t=>({start:+t[1],...this.editor.getAttributes(F1t)}),joinPredicate:(t,n)=>n.childCount+n.attrs.start===+t[1],editor:this.editor})),[s]}}),Oen=Rv.create({name:"paragraph",priority:1e3,addOptions(){return{HTMLAttributes:{}}},group:"block",content:"inline*",parseHTML(){return[{tag:"p"}]},renderHTML({HTMLAttributes:s}){return["p",ep(this.options.HTMLAttributes,s),0]},addCommands(){return{setParagraph:()=>({commands:s})=>s.setNode(this.name)}},addKeyboardShortcuts(){return{"Mod-Alt-0":()=>this.editor.commands.setParagraph()}}}),zen=/(?:^|\s)(~~(?!\s+~~)((?:[^~]+))~~(?!\s+~~))$/,Ben=/(?:^|\s)(~~(?!\s+~~)((?:[^~]+))~~(?!\s+~~))/g,$en=xC.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",ep(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[zG({find:zen,type:this.type})]},addPasteRules(){return[eB({find:Ben,type:this.type})]}}),Uen=Rv.create({name:"text",group:"inline"}),W6e=Tb.create({name:"starterKit",addExtensions(){const s=[];return this.options.bold!==!1&&s.push(ZJs.configure(this.options.bold)),this.options.blockquote!==!1&&s.push(HJs.configure(this.options.blockquote)),this.options.bulletList!==!1&&s.push(QJs.configure(this.options.bulletList)),this.options.code!==!1&&s.push(ten.configure(this.options.code)),this.options.codeBlock!==!1&&s.push(ren.configure(this.options.codeBlock)),this.options.document!==!1&&s.push(aen.configure(this.options.document)),this.options.dropcursor!==!1&&s.push(len.configure(this.options.dropcursor)),this.options.gapcursor!==!1&&s.push(gen.configure(this.options.gapcursor)),this.options.hardBreak!==!1&&s.push(xen.configure(this.options.hardBreak)),this.options.heading!==!1&&s.push(yen.configure(this.options.heading)),this.options.history!==!1&&s.push(Aen.configure(this.options.history)),this.options.horizontalRule!==!1&&s.push(Een.configure(this.options.horizontalRule)),this.options.italic!==!1&&s.push(Len.configure(this.options.italic)),this.options.listItem!==!1&&s.push(Ren.configure(this.options.listItem)),this.options.orderedList!==!1&&s.push(Fen.configure(this.options.orderedList)),this.options.paragraph!==!1&&s.push(Oen.configure(this.options.paragraph)),this.options.strike!==!1&&s.push($en.configure(this.options.strike)),this.options.text!==!1&&s.push(Uen.configure(this.options.text)),s}}),qen="aaa1rp3bb0ott3vie4c1le2ogado5udhabi7c0ademy5centure6ountant0s9o1tor4d0s1ult4e0g1ro2tna4f0l1rica5g0akhan5ency5i0g1rbus3force5tel5kdn3l0ibaba4pay4lfinanz6state5y2sace3tom5m0azon4ericanexpress7family11x2fam3ica3sterdam8nalytics7droid5quan4z2o0l2partments8p0le4q0uarelle8r0ab1mco4chi3my2pa2t0e3s0da2ia2sociates9t0hleta5torney7u0ction5di0ble3o3spost5thor3o0s4w0s2x0a2z0ure5ba0by2idu3namex4d1k2r0celona5laycard4s5efoot5gains6seball5ketball8uhaus5yern5b0c1t1va3cg1n2d1e0ats2uty4er2rlin4st0buy5t2f1g1h0arti5i0ble3d1ke2ng0o3o1z2j1lack0friday9ockbuster8g1omberg7ue3m0s1w2n0pparibas9o0ats3ehringer8fa2m1nd2o0k0ing5sch2tik2on4t1utique6x2r0adesco6idgestone9oadway5ker3ther5ussels7s1t1uild0ers6siness6y1zz3v1w1y1z0h3ca0b1fe2l0l1vinklein9m0era3p2non3petown5ital0one8r0avan4ds2e0er0s4s2sa1e1h1ino4t0ering5holic7ba1n1re3c1d1enter4o1rn3f0a1d2g1h0anel2nel4rity4se2t2eap3intai5ristmas6ome4urch5i0priani6rcle4sco3tadel4i0c2y3k1l0aims4eaning6ick2nic1que6othing5ud3ub0med6m1n1o0ach3des3ffee4llege4ogne5m0mbank4unity6pany2re3uter5sec4ndos3struction8ulting7tact3ractors9oking4l1p2rsica5untry4pon0s4rses6pa2r0edit0card4union9icket5own3s1uise0s6u0isinella9v1w1x1y0mru3ou3z2dad1nce3ta1e1ing3sun4y2clk3ds2e0al0er2s3gree4livery5l1oitte5ta3mocrat6ntal2ist5si0gn4v2hl2iamonds6et2gital5rect0ory7scount3ver5h2y2j1k1m1np2o0cs1tor4g1mains5t1wnload7rive4tv2ubai3pont4rban5vag2r2z2earth3t2c0o2deka3u0cation8e1g1mail3erck5nergy4gineer0ing9terprises10pson4quipment8r0icsson6ni3s0q1tate5t1u0rovision8s2vents5xchange6pert3osed4ress5traspace10fage2il1rwinds6th3mily4n0s2rm0ers5shion4t3edex3edback6rrari3ero6i0delity5o2lm2nal1nce1ial7re0stone6mdale6sh0ing5t0ness6j1k1lickr3ghts4r2orist4wers5y2m1o0o0d1tball6rd1ex2sale4um3undation8x2r0ee1senius7l1ogans4ntier7tr2ujitsu5n0d2rniture7tbol5yi3ga0l0lery3o1up4me0s3p1rden4y2b0iz3d0n2e0a1nt0ing5orge5f1g0ee3h1i0ft0s3ves2ing5l0ass3e1obal2o4m0ail3bh2o1x2n1odaddy5ld0point6f2odyear5g0le4p1t1v2p1q1r0ainger5phics5tis4een3ipe3ocery4up4s1t1u0cci3ge2ide2tars5ru3w1y2hair2mburg5ngout5us3bo2dfc0bank7ealth0care8lp1sinki6re1mes5iphop4samitsu7tachi5v2k0t2m1n1ockey4ldings5iday5medepot5goods5s0ense7nda3rse3spital5t0ing5t0els3mail5use3w2r1sbc3t1u0ghes5yatt3undai7ibm2cbc2e1u2d1e0ee3fm2kano4l1m0amat4db2mo0bilien9n0c1dustries8finiti5o2g1k1stitute6urance4e4t0ernational10uit4vestments10o1piranga7q1r0ish4s0maili5t0anbul7t0au2v3jaguar4va3cb2e0ep2tzt3welry6io2ll2m0p2nj2o0bs1urg4t1y2p0morgan6rs3uegos4niper7kaufen5ddi3e0rryhotels6properties14fh2g1h1i0a1ds2m1ndle4tchen5wi3m1n1oeln3matsu5sher5p0mg2n2r0d1ed3uokgroup8w1y0oto4z2la0caixa5mborghini8er3nd0rover6xess5salle5t0ino3robe5w0yer5b1c1ds2ease3clerc5frak4gal2o2xus4gbt3i0dl2fe0insurance9style7ghting6ke2lly3mited4o2ncoln4k2ve1ing5k1lc1p2oan0s3cker3us3l1ndon4tte1o3ve3pl0financial11r1s1t0d0a3u0ndbeck6xe1ury5v1y2ma0drid4if1son4keup4n0agement7go3p1rket0ing3s4riott5shalls7ttel5ba2c0kinsey7d1e0d0ia3et2lbourne7me1orial6n0u2rck0msd7g1h1iami3crosoft7l1ni1t2t0subishi9k1l0b1s2m0a2n1o0bi0le4da2e1i1m1nash3ey2ster5rmon3tgage6scow4to0rcycles9v0ie4p1q1r1s0d2t0n1r2u0seum3ic4v1w1x1y1z2na0b1goya4me2vy3ba2c1e0c1t0bank4flix4work5ustar5w0s2xt0direct7us4f0l2g0o2hk2i0co2ke1on3nja3ssan1y5l1o0kia3rton4w0ruz3tv4p1r0a1w2tt2u1yc2z2obi1server7ffice5kinawa6layan0group9lo3m0ega4ne1g1l0ine5oo2pen3racle3nge4g0anic5igins6saka4tsuka4t2vh3pa0ge2nasonic7ris2s1tners4s1y3y2ccw3e0t2f0izer5g1h0armacy6d1ilips5one2to0graphy6s4ysio5ics1tet2ures6d1n0g1k2oneer5zza4k1l0ace2y0station9umbing5s3m1n0c2ohl2ker3litie5rn2st3r0axi3ess3ime3o0d0uctions8f1gressive8mo2perties3y5tection8u0dential9s1t1ub2w0c2y2qa1pon3uebec3st5racing4dio4e0ad1lestate6tor2y4cipes5d0umbrella9hab3ise0n3t2liance6n0t0als5pair3ort3ublican8st0aurant8view0s5xroth6ich0ardli6oh3l1o1p2o0cks3deo3gers4om3s0vp3u0gby3hr2n2w0e2yukyu6sa0arland6fe0ty4kura4le1on3msclub4ung5ndvik0coromant12ofi4p1rl2s1ve2xo3b0i1s2c0b1haeffler7midt4olarships8ol3ule3warz5ience5ot3d1e0arch3t2cure1ity6ek2lect4ner3rvices6ven3w1x0y3fr2g1h0angrila6rp3ell3ia1ksha5oes2p0ping5uji3w3i0lk2na1gles5te3j1k0i0n2y0pe4l0ing4m0art3ile4n0cf3o0ccer3ial4ftbank4ware6hu2lar2utions7ng1y2y2pa0ce3ort2t3r0l2s1t0ada2ples4r1tebank4farm7c0group6ockholm6rage3e3ream4udio2y3yle4u0cks3pplies3y2ort5rf1gery5zuki5v1watch4iss4x1y0dney4stems6z2tab1ipei4lk2obao4rget4tamotors6r2too4x0i3c0i2d0k2eam2ch0nology8l1masek5nnis4va3f1g1h0d1eater2re6iaa2ckets5enda4ps2res2ol4j0maxx4x2k0maxx5l1m0all4n1o0day3kyo3ols3p1ray3shiba5tal3urs3wn2yota3s3r0ade1ing4ining5vel0ers0insurance16ust3v2t1ube2i1nes3shu4v0s2w1z2ua1bank3s2g1k1nicom3versity8o2ol2ps2s1y1z2va0cations7na1guard7c1e0gas3ntures6risign5mögensberater2ung14sicherung10t2g1i0ajes4deo3g1king4llas4n1p1rgin4sa1ion4va1o3laanderen9n1odka3lvo3te1ing3o2yage5u2wales2mart4ter4ng0gou5tch0es6eather0channel12bcam3er2site5d0ding5ibo2r3f1hoswho6ien2ki2lliamhill9n0dows4e1ners6me2oodside6rk0s2ld3w2s1tc1f3xbox3erox4ihuan4n2xx2yz3yachts4hoo3maxun5ndex5e1odobashi7ga2kohama6u0tube6t1un3za0ppos4ra3ero3ip2m1one3uerich6w2",Ven="ελ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",vWe="numeric",bWe="ascii",_We="alpha",Ree="asciinumeric",xQ="alphanumeric",wWe="domain",aHt="emoji",Hen="scheme",Gen="slashscheme",wBe="whitespace";function Wen(s,t){return s in t||(t[s]=[]),t[s]}function x8(s,t,n){t[vWe]&&(t[Ree]=!0,t[xQ]=!0),t[bWe]&&(t[Ree]=!0,t[_We]=!0),t[Ree]&&(t[xQ]=!0),t[_We]&&(t[xQ]=!0),t[xQ]&&(t[wWe]=!0),t[aHt]&&(t[wWe]=!0);for(const r in t){const a=Wen(r,n);a.indexOf(s)<0&&a.push(s)}}function Ken(s,t){const n={};for(const r in t)t[r].indexOf(s)>=0&&(n[r]=!0);return n}function ww(s=null){this.j={},this.jr=[],this.jd=null,this.t=s}ww.groups={};ww.prototype={accepts(){return!!this.t},go(s){const t=this,n=t.j[s];if(n)return n;for(let r=0;rs.ta(t,n,r,a),lx=(s,t,n,r,a)=>s.tr(t,n,r,a),z1t=(s,t,n,r,a)=>s.ts(t,n,r,a),_i=(s,t,n,r,a)=>s.tt(t,n,r,a),bA="WORD",jWe="UWORD",iHt="ASCIINUMERICAL",oHt="ALPHANUMERICAL",Sse="LOCALHOST",NWe="TLD",kWe="UTLD",y3e="SCHEME",jU="SLASH_SCHEME",Gnt="NUM",SWe="WS",Wnt="NL",Dee="OPENBRACE",Fee="CLOSEBRACE",hTe="OPENBRACKET",mTe="CLOSEBRACKET",fTe="OPENPAREN",pTe="CLOSEPAREN",gTe="OPENANGLEBRACKET",xTe="CLOSEANGLEBRACKET",yTe="FULLWIDTHLEFTPAREN",vTe="FULLWIDTHRIGHTPAREN",bTe="LEFTCORNERBRACKET",_Te="RIGHTCORNERBRACKET",wTe="LEFTWHITECORNERBRACKET",jTe="RIGHTWHITECORNERBRACKET",NTe="FULLWIDTHLESSTHAN",kTe="FULLWIDTHGREATERTHAN",STe="AMPERSAND",CTe="APOSTROPHE",ATe="ASTERISK",xP="AT",ETe="BACKSLASH",TTe="BACKTICK",MTe="CARET",y8="COLON",Knt="COMMA",PTe="DOLLAR",N5="DOT",ITe="EQUALS",Ynt="EXCLAMATION",_N="HYPHEN",Oee="PERCENT",LTe="PIPE",RTe="PLUS",DTe="POUND",zee="QUERY",Znt="QUOTE",lHt="FULLWIDTHMIDDLEDOT",Xnt="SEMI",k5="SLASH",Bee="TILDE",FTe="UNDERSCORE",cHt="EMOJI",OTe="SYM";var dHt=Object.freeze({__proto__:null,ALPHANUMERICAL:oHt,AMPERSAND:STe,APOSTROPHE:CTe,ASCIINUMERICAL:iHt,ASTERISK:ATe,AT:xP,BACKSLASH:ETe,BACKTICK:TTe,CARET:MTe,CLOSEANGLEBRACKET:xTe,CLOSEBRACE:Fee,CLOSEBRACKET:mTe,CLOSEPAREN:pTe,COLON:y8,COMMA:Knt,DOLLAR:PTe,DOT:N5,EMOJI:cHt,EQUALS:ITe,EXCLAMATION:Ynt,FULLWIDTHGREATERTHAN:kTe,FULLWIDTHLEFTPAREN:yTe,FULLWIDTHLESSTHAN:NTe,FULLWIDTHMIDDLEDOT:lHt,FULLWIDTHRIGHTPAREN:vTe,HYPHEN:_N,LEFTCORNERBRACKET:bTe,LEFTWHITECORNERBRACKET:wTe,LOCALHOST:Sse,NL:Wnt,NUM:Gnt,OPENANGLEBRACKET:gTe,OPENBRACE:Dee,OPENBRACKET:hTe,OPENPAREN:fTe,PERCENT:Oee,PIPE:LTe,PLUS:RTe,POUND:DTe,QUERY:zee,QUOTE:Znt,RIGHTCORNERBRACKET:_Te,RIGHTWHITECORNERBRACKET:jTe,SCHEME:y3e,SEMI:Xnt,SLASH:k5,SLASH_SCHEME:jU,SYM:OTe,TILDE:Bee,TLD:NWe,UNDERSCORE:FTe,UTLD:kWe,UWORD:jWe,WORD:bA,WS:SWe});const eA=/[a-z]/,OZ=new RegExp("\\p{L}","u"),jBe=new RegExp("\\p{Emoji}","u"),tA=/\d/,NBe=/\s/,B1t="\r",kBe=` `,Yen="️",Zen="‍",SBe="";let xde=null,yde=null;function Xen(s=[]){const t={};ww.groups=t;const n=new ww;xde==null&&(xde=$1t(qen)),yde==null&&(yde=$1t(Ven)),_i(n,"'",CTe),_i(n,"{",Dee),_i(n,"}",Fee),_i(n,"[",hTe),_i(n,"]",mTe),_i(n,"(",fTe),_i(n,")",pTe),_i(n,"<",gTe),_i(n,">",xTe),_i(n,"(",yTe),_i(n,")",vTe),_i(n,"「",bTe),_i(n,"」",_Te),_i(n,"『",wTe),_i(n,"』",jTe),_i(n,"<",NTe),_i(n,">",kTe),_i(n,"&",STe),_i(n,"*",ATe),_i(n,"@",xP),_i(n,"`",TTe),_i(n,"^",MTe),_i(n,":",y8),_i(n,",",Knt),_i(n,"$",PTe),_i(n,".",N5),_i(n,"=",ITe),_i(n,"!",Ynt),_i(n,"-",_N),_i(n,"%",Oee),_i(n,"|",LTe),_i(n,"+",RTe),_i(n,"#",DTe),_i(n,"?",zee),_i(n,'"',Znt),_i(n,"/",k5),_i(n,";",Xnt),_i(n,"~",Bee),_i(n,"_",FTe),_i(n,"\\",ETe),_i(n,"・",lHt);const r=lx(n,tA,Gnt,{[vWe]:!0});lx(r,tA,r);const a=lx(r,eA,iHt,{[Ree]:!0}),i=lx(r,OZ,oHt,{[xQ]:!0}),l=lx(n,eA,bA,{[bWe]:!0});lx(l,tA,a),lx(l,eA,l),lx(a,tA,a),lx(a,eA,a);const o=lx(n,OZ,jWe,{[_We]:!0});lx(o,eA),lx(o,tA,i),lx(o,OZ,o),lx(i,tA,i),lx(i,eA),lx(i,OZ,i);const c=_i(n,kBe,Wnt,{[wBe]:!0}),d=_i(n,B1t,SWe,{[wBe]:!0}),u=lx(n,NBe,SWe,{[wBe]:!0});_i(n,SBe,u),_i(d,kBe,c),_i(d,SBe,u),lx(d,NBe,u),_i(u,B1t),_i(u,kBe),lx(u,NBe,u),_i(u,SBe,u);const h=lx(n,jBe,cHt,{[aHt]:!0});_i(h,"#"),lx(h,jBe,h),_i(h,Yen,h);const m=_i(h,Zen);_i(m,"#"),lx(m,jBe,h);const f=[[eA,l],[tA,a]],g=[[eA,null],[OZ,o],[tA,i]];for(let x=0;xx[0]>y[0]?1:-1);for(let x=0;x=0?b[wWe]=!0:eA.test(y)?tA.test(y)?b[Ree]=!0:b[bWe]=!0:b[vWe]=!0,z1t(n,y,y,b)}return z1t(n,"localhost",Sse,{ascii:!0}),n.jd=new ww(OTe),{start:n,tokens:Object.assign({groups:t},dHt)}}function uHt(s,t){const n=Qen(t.replace(/[A-Z]/g,o=>o.toLowerCase())),r=n.length,a=[];let i=0,l=0;for(;l=0&&(h+=n[l].length,m++),d+=n[l].length,i+=n[l].length,l++;i-=h,l-=m,d-=h,a.push({t:u.t,v:t.slice(i-d,i),s:i-d,e:i})}return a}function Qen(s){const t=[],n=s.length;let r=0;for(;r56319||r+1===n||(i=s.charCodeAt(r+1))<56320||i>57343?s[r]:s.slice(r,r+2);t.push(l),r+=l.length}return t}function SM(s,t,n,r,a){let i;const l=t.length;for(let o=0;o=0;)i++;if(i>0){t.push(n.join(""));for(let l=parseInt(s.substring(r,r+i),10);l>0;l--)n.pop();r+=i}else n.push(s[r]),r++}return t}const Cse={defaultProtocol:"http",events:null,format:U1t,formatHref:U1t,nl2br:!1,tagName:"a",target:null,rel:null,validate:!0,truncate:1/0,className:null,attributes:null,ignoreTags:[],render:null};function Qnt(s,t=null){let n=Object.assign({},Cse);s&&(n=Object.assign(n,s instanceof Qnt?s.o:s));const r=n.ignoreTags,a=[];for(let i=0;in?r.substring(0,n)+"…":r},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=Cse.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,n=this.toHref(s.get("defaultProtocol")),r=s.get("formatHref",n,this),a=s.get("tagName",n,t),i=this.toFormattedString(s),l={},o=s.get("className",n,t),c=s.get("target",n,t),d=s.get("rel",n,t),u=s.getObj("attributes",n,t),h=s.getObj("events",n,t);return l.href=r,o&&(l.class=o),c&&(l.target=c),d&&(l.rel=d),u&&Object.assign(l,u),{tagName:a,attributes:l,content:i,eventListeners:h}}};function K6e(s,t){class n extends hHt{constructor(a,i){super(a,i),this.t=s}}for(const r in t)n.prototype[r]=t[r];return n.t=s,n}const Jen=K6e("email",{isLink:!0,toHref(){return"mailto:"+this.toString()}}),q1t=K6e("text"),etn=K6e("nl"),vde=K6e("url",{isLink:!0,toHref(s=Cse.defaultProtocol){return this.hasProtocol()?this.v:`${s}://${this.v}`},hasProtocol(){const s=this.tk;return s.length>=2&&s[0].t!==Sse&&s[1].t===y8}}),oN=s=>new ww(s);function ttn({groups:s}){const t=s.domain.concat([STe,ATe,xP,ETe,TTe,MTe,PTe,ITe,_N,Gnt,Oee,LTe,RTe,DTe,k5,OTe,Bee,FTe]),n=[CTe,y8,Knt,N5,Ynt,Oee,zee,Znt,Xnt,gTe,xTe,Dee,Fee,mTe,hTe,fTe,pTe,yTe,vTe,bTe,_Te,wTe,jTe,NTe,kTe],r=[STe,CTe,ATe,ETe,TTe,MTe,PTe,ITe,_N,Dee,Fee,Oee,LTe,RTe,DTe,zee,k5,OTe,Bee,FTe],a=oN(),i=_i(a,Bee);tu(i,r,i),tu(i,s.domain,i);const l=oN(),o=oN(),c=oN();tu(a,s.domain,l),tu(a,s.scheme,o),tu(a,s.slashscheme,c),tu(l,r,i),tu(l,s.domain,l);const d=_i(l,xP);_i(i,xP,d),_i(o,xP,d),_i(c,xP,d);const u=_i(i,N5);tu(u,r,i),tu(u,s.domain,i);const h=oN();tu(d,s.domain,h),tu(h,s.domain,h);const m=_i(h,N5);tu(m,s.domain,h);const f=oN(Jen);tu(m,s.tld,f),tu(m,s.utld,f),_i(d,Sse,f);const g=_i(h,_N);_i(g,_N,g),tu(g,s.domain,h),tu(f,s.domain,h),_i(f,N5,m),_i(f,_N,g);const x=_i(l,_N),y=_i(l,N5);_i(x,_N,x),tu(x,s.domain,l),tu(y,r,i),tu(y,s.domain,l);const v=oN(vde);tu(y,s.tld,v),tu(y,s.utld,v),tu(v,s.domain,l),tu(v,r,i),_i(v,N5,y),_i(v,_N,x),_i(v,xP,d);const b=_i(v,y8),w=oN(vde);tu(b,s.numeric,w);const S=oN(vde),C=oN();tu(S,t,S),tu(S,n,C),tu(C,t,S),tu(C,n,C),_i(v,k5,S),_i(w,k5,S);const E=_i(o,y8),I=_i(c,y8),P=_i(I,k5),R=_i(P,k5);tu(o,s.domain,l),_i(o,N5,y),_i(o,_N,x),tu(c,s.domain,l),_i(c,N5,y),_i(c,_N,x),tu(E,s.domain,S),_i(E,k5,S),_i(E,zee,S),tu(R,s.domain,S),tu(R,t,S),_i(R,k5,S);const D=[[Dee,Fee],[hTe,mTe],[fTe,pTe],[gTe,xTe],[yTe,vTe],[bTe,_Te],[wTe,jTe],[NTe,kTe]];for(let O=0;O=0&&m++,a++,u++;if(m<0)a-=u,a0&&(i.push(CBe(q1t,t,l)),l=[]),a-=m,u-=m;const f=h.t,g=n.slice(a-u,a);i.push(CBe(f,t,g))}}return l.length>0&&i.push(CBe(q1t,t,l)),i}function CBe(s,t,n){const r=n[0].s,a=n[n.length-1].e,i=t.slice(r,a);return new s(i,n)}const ntn=typeof console<"u"&&console&&console.warn||(()=>{}),rtn="until manual call of linkify.init(). Register all schemes and plugins before invoking linkify the first time.",bp={scanner:null,parser:null,tokenQueue:[],pluginQueue:[],customSchemes:[],initialized:!1};function atn(){return ww.groups={},bp.scanner=null,bp.parser=null,bp.tokenQueue=[],bp.pluginQueue=[],bp.customSchemes=[],bp.initialized=!1,bp}function V1t(s,t=!1){if(bp.initialized&&ntn(`linkifyjs: already initialized - will not register custom scheme "${s}" ${rtn}`),!/^[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`);bp.customSchemes.push([s,t])}function itn(){bp.scanner=Xen(bp.customSchemes);for(let s=0;s{const a=t.some(d=>d.docChanged)&&!n.doc.eq(r.doc),i=t.some(d=>d.getMeta("preventAutolink"));if(!a||i)return;const{tr:l}=r,o=DQs(n.doc,[...t]);if(qQs(o).forEach(({newRange:d})=>{const u=OQs(r.doc,d,f=>f.isTextblock);let h,m;if(u.length>1)h=u[0],m=r.doc.textBetween(h.pos,h.pos+h.node.nodeSize,void 0," ");else if(u.length){const f=r.doc.textBetween(d.from,d.to," "," ");if(!ltn.test(f))return;h=u[0],m=r.doc.textBetween(h.pos,d.to,void 0," ")}if(h&&m){const f=m.split(otn).filter(Boolean);if(f.length<=0)return!1;const g=f[f.length-1],x=h.pos+m.lastIndexOf(g);if(!g)return!1;const y=Jnt(g).map(v=>v.toObject(s.defaultProtocol));if(!dtn(y))return!1;y.filter(v=>v.isLink).map(v=>({...v,from:x+v.start+1,to:x+v.end+1})).filter(v=>r.schema.marks.code?!r.doc.rangeHasMark(v.from,v.to,r.schema.marks.code):!0).filter(v=>s.validate(v.value)).filter(v=>s.shouldAutoLink(v.value)).forEach(v=>{$nt(v.from,v.to,r.doc).some(b=>b.mark.type===s.type)||l.addMark(v.from,v.to,s.type.create({href:v.href}))})}}),!!l.steps.length)return l}})}function htn(s){return new $0({key:new I1("handleClickLink"),props:{handleClick:(t,n,r)=>{var a,i;if(r.button!==0||!t.editable)return!1;let l=r.target;const o=[];for(;l.nodeName!=="DIV";)o.push(l),l=l.parentNode;if(!o.find(m=>m.nodeName==="A"))return!1;const c=YVt(t.state,s.type.name),d=r.target,u=(a=d==null?void 0:d.href)!==null&&a!==void 0?a:c.href,h=(i=d==null?void 0:d.target)!==null&&i!==void 0?i:c.target;return d&&u?(window.open(u,h),!0):!1}}})}function mtn(s){return new $0({key:new I1("handlePasteLink"),props:{handlePaste:(t,n,r)=>{const{state:a}=t,{selection:i}=a,{empty:l}=i;if(l)return!1;let o="";r.content.forEach(d=>{o+=d.textContent});const c=mHt(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 yR(s,t){const n=["http","https","ftp","ftps","mailto","tel","callto","sms","cid","xmpp"];return t&&t.forEach(r=>{const a=typeof r=="string"?r:r.scheme;a&&n.push(a)}),!s||s.replace(ctn,"").match(new RegExp(`^(?:(?:${n.join("|")}):|[^a-z]|[a-z0-9+.-]+(?:[^a-z+.-:]|$))`,"i"))}const Y6e=xC.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"){V1t(s);return}V1t(s.scheme,s.optionalSlashes)})},onDestroy(){atn()},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)=>!!yR(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:n=>!!yR(n,this.options.protocols),protocols:this.options.protocols,defaultProtocol:this.options.defaultProtocol})?!1:null}}]},renderHTML({HTMLAttributes:s}){return this.options.isAllowedUri(s.href,{defaultValidate:t=>!!yR(t,this.options.protocols),protocols:this.options.protocols,defaultProtocol:this.options.defaultProtocol})?["a",ep(this.options.HTMLAttributes,s),0]:["a",ep(this.options.HTMLAttributes,{...s,href:""}),0]},addCommands(){return{setLink:s=>({chain:t})=>{const{href:n}=s;return this.options.isAllowedUri(n,{defaultValidate:r=>!!yR(r,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:n}=s;return this.options.isAllowedUri(n,{defaultValidate:r=>!!yR(r,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[eB({find:s=>{const t=[];if(s){const{protocols:n,defaultProtocol:r}=this.options,a=mHt(s).filter(i=>i.isLink&&this.options.isAllowedUri(i.value,{defaultValidate:l=>!!yR(l,n),protocols:n,defaultProtocol:r}));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:n}=this.options;return this.options.autolink&&s.push(utn({type:this.type,defaultProtocol:this.options.defaultProtocol,validate:r=>this.options.isAllowedUri(r,{defaultValidate:a=>!!yR(a,t),protocols:t,defaultProtocol:n}),shouldAutoLink:this.options.shouldAutoLink})),this.options.openOnClick===!0&&s.push(htn({type:this.type})),this.options.linkOnPaste&&s.push(mtn({editor:this.editor,defaultProtocol:this.options.defaultProtocol,type:this.type})),s}}),Z6e=Tb.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(n=>t.updateAttributes(n,{textAlign:s})).every(n=>n):!1,unsetTextAlign:()=>({commands:s})=>this.options.types.map(t=>s.resetAttributes(t,"textAlign")).every(t=>t),toggleTextAlign:s=>({editor:t,commands:n})=>this.options.alignments.includes(s)?t.isActive({textAlign:s})?n.unsetTextAlign():n.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")}}}),ftn=s=>{if(!s.children.length)return;const t=s.querySelectorAll("span");t&&t.forEach(n=>{var r,a;const i=n.getAttribute("style"),l=(a=(r=n.parentElement)===null||r===void 0?void 0:r.closest("span"))===null||a===void 0?void 0:a.getAttribute("style");n.setAttribute("style",`${l};${i}`)})},trt=xC.create({name:"textStyle",priority:101,addOptions(){return{HTMLAttributes:{},mergeNestedSpanStyles:!1}},parseHTML(){return[{tag:"span",getAttrs:s=>s.hasAttribute("style")?(this.options.mergeNestedSpanStyles&&ftn(s),{}):!1}]},renderHTML({HTMLAttributes:s}){return["span",ep(this.options.HTMLAttributes,s),0]},addCommands(){return{removeEmptyTextStyle:()=>({tr:s})=>{const{selection:t}=s;return s.doc.nodesBetween(t.from,t.to,(n,r)=>{if(n.isTextblock)return!0;n.marks.filter(a=>a.type===this.type).some(a=>Object.values(a.attrs).some(i=>!!i))||s.removeMark(r,r+n.nodeSize,this.type)}),!0}}}}),ptn=/(?:^|\s)(!\[(.+|:?)]\((\S+)(?:(?:\s+)["'](\S+)["'])?\))$/,fHt=Rv.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",ep(this.options.HTMLAttributes,s)]},addCommands(){return{setImage:s=>({commands:t})=>t.insertContent({type:this.name,attrs:s})}},addInputRules(){return[ZVt({find:ptn,type:this.type,getAttributes:s=>{const[,,t,n,r]=s;return{src:n,alt:t,title:r}}})]}});let CWe,AWe;if(typeof WeakMap<"u"){let s=new WeakMap;CWe=t=>s.get(t),AWe=(t,n)=>(s.set(t,n),n)}else{const s=[];let n=0;CWe=r=>{for(let a=0;a(n==10&&(n=0),s[n++]=r,s[n++]=a)}var _x=class{constructor(s,t,n,r){this.width=s,this.height=t,this.map=n,this.problems=r}findCell(s){for(let t=0;t=n){(i||(i=[])).push({type:"overlong_rowspan",pos:u,n:v-w});break}const S=a+w*t;for(let C=0;Cr&&(i+=d.attrs.colspan)}}for(let l=0;l1&&(n=!0)}t==-1?t=i:t!=i&&(t=Math.max(t,i))}return t}function ytn(s,t,n){s.problems||(s.problems=[]);const r={};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 btn(s){for(let t=s.depth;t>0;t--){const n=s.node(t).type.spec.tableRole;if(n==="cell"||n==="header_cell")return s.node(t)}return null}function NC(s){const t=s.selection.$head;for(let n=t.depth;n>0;n--)if(t.node(n).type.spec.tableRole=="row")return!0;return!1}function X6e(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 n=tB(t.$head)||_tn(t.$head);if(n)return n;throw new RangeError(`No cell found around position ${t.head}`)}function _tn(s){for(let t=s.nodeAfter,n=s.pos;t;t=t.firstChild,n++){const r=t.type.spec.tableRole;if(r=="cell"||r=="header_cell")return s.doc.resolve(n)}for(let t=s.nodeBefore,n=s.pos;t;t=t.lastChild,n--){const r=t.type.spec.tableRole;if(r=="cell"||r=="header_cell")return s.doc.resolve(n-t.nodeSize)}}function EWe(s){return s.parent.type.spec.tableRole=="row"&&!!s.nodeAfter}function wtn(s){return s.node(0).resolve(s.pos+s.nodeAfter.nodeSize)}function srt(s,t){return s.depth==t.depth&&s.pos>=t.start(-1)&&s.pos<=t.end(-1)}function pHt(s,t,n){const r=s.node(-1),a=_x.get(r),i=s.start(-1),l=a.nextCell(s.pos-i,t,n);return l==null?null:s.node(0).resolve(i+l)}function sB(s,t,n=1){const r={...s,colspan:s.colspan-n};return r.colwidth&&(r.colwidth=r.colwidth.slice(),r.colwidth.splice(t,n),r.colwidth.some(a=>a>0)||(r.colwidth=null)),r}function gHt(s,t,n=1){const r={...s,colspan:s.colspan+n};if(r.colwidth){r.colwidth=r.colwidth.slice();for(let a=0;au!=n.pos-i);c.unshift(n.pos-i);const d=c.map(u=>{const h=r.nodeAt(u);if(!h)throw new RangeError(`No cell with offset ${u} found`);const m=i+u+1;return new zqt(o.resolve(m),o.resolve(m+h.content.size))});super(d[0].$from,d[0].$to,d),this.$anchorCell=t,this.$headCell=n}map(t,n){const r=t.resolve(n.map(this.$anchorCell.pos)),a=t.resolve(n.map(this.$headCell.pos));if(EWe(r)&&EWe(a)&&srt(r,a)){const i=this.$anchorCell.node(-1)!=r.node(-1);return i&&this.isRowSelection()?_A.rowSelection(r,a):i&&this.isColSelection()?_A.colSelection(r,a):new _A(r,a)}return Al.between(r,a)}content(){const t=this.$anchorCell.node(-1),n=_x.get(t),r=this.$anchorCell.start(-1),a=n.rectBetween(this.$anchorCell.pos-r,this.$headCell.pos-r),i={},l=[];for(let c=a.top;c0||y>0){let v=g.attrs;if(x>0&&(v=sB(v,0,x)),y>0&&(v=sB(v,v.colspan-y,y)),f.lefta.bottom){const v={...g.attrs,rowspan:Math.min(f.bottom,a.bottom)-Math.max(f.top,a.top)};f.top0)return!1;const r=t+this.$anchorCell.nodeAfter.attrs.rowspan,a=n+this.$headCell.nodeAfter.attrs.rowspan;return Math.max(r,a)==this.$headCell.node(-1).childCount}static colSelection(t,n=t){const r=t.node(-1),a=_x.get(r),i=t.start(-1),l=a.findCell(t.pos-i),o=a.findCell(n.pos-i),c=t.node(0);return l.top<=o.top?(l.top>0&&(t=c.resolve(i+a.map[l.left])),o.bottom0&&(n=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)==n.width}eq(t){return t instanceof _A&&t.$anchorCell.pos==this.$anchorCell.pos&&t.$headCell.pos==this.$headCell.pos}static rowSelection(t,n=t){const r=t.node(-1),a=_x.get(r),i=t.start(-1),l=a.findCell(t.pos-i),o=a.findCell(n.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&&(n=c.resolve(i+a.map[o.top*a.width])),l.right{t.push(__.node(r,r+n.nodeSize,{class:"selectedCell"}))}),vx.create(s.doc,t)}function Stn({$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--,r--);return n==r&&/row|table/.test(s.node(a).type.spec.tableRole)}function Ctn({$from:s,$to:t}){let n,r;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"){n=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"){r=i;break}}return n!==r&&t.parentOffset===0}function Atn(s,t,n){const r=(t||s).selection,a=(t||s).doc;let i,l;if(r instanceof El&&(l=r.node.type.spec.tableRole)){if(l=="cell"||l=="header_cell")i=Jf.create(a,r.from);else if(l=="row"){const o=a.resolve(r.from+1);i=Jf.rowSelection(o,o)}else if(!n){const o=_x.get(r.node),c=r.from+1,d=c+o.map[o.width*o.height-1];i=Jf.create(a,c+1,d)}}else r instanceof Al&&Stn(r)?i=Al.create(a,r.from):r instanceof Al&&Ctn(r)&&(i=Al.create(a,r.$from.start(),r.$from.end()));return i&&(t||(t=s.tr)).setSelection(i),t}const Etn=new I1("fix-tables");function yHt(s,t,n,r){const a=s.childCount,i=t.childCount;e:for(let l=0,o=0;l{a.type.spec.tableRole=="table"&&(n=Ttn(s,a,i,n))};return t?t.doc!=s.doc&&yHt(t.doc,s.doc,0,r):s.doc.descendants(r),n}function Ttn(s,t,n,r){const a=_x.get(t);if(!a.problems)return r;r||(r=s.tr);const i=[];for(let c=0;c0){let f="cell";u.firstChild&&(f=u.firstChild.type.spec.tableRole);const g=[];for(let y=0;y0?-1:0;jtn(t,r,a+i)&&(i=a==0||a==t.width?null:0);for(let l=0;l0&&a0&&t.map[o-1]==c||a0?-1:0;Rtn(t,r,a+o)&&(o=a==0||a==t.height?null:0);for(let d=0,u=t.width*a;d0&&a0&&h==t.map[u-t.width]){const m=n.nodeAt(h).attrs;s.setNodeMarkup(s.mapping.slice(o).map(h+r),null,{...m,rowspan:m.rowspan-1}),d+=m.colspan-1}else if(a0&&n[i]==n[i-1]||r.right0&&n[a]==n[a-s]||r.bottom0){const u=c+1+d.content.size,h=H1t(d)?c+1:u;i.replaceWith(h+r.tableStart,u+r.tableStart,o)}i.setSelection(new Jf(i.doc.resolve(c+r.tableStart))),t(i)}return!0}function W1t(s,t){const n=E1(s.schema);return $tn(({node:r})=>n[r.type.spec.tableRole])(s,t)}function $tn(s){return(t,n)=>{const r=t.selection;let a,i;if(r instanceof Jf){if(r.$anchorCell.pos!=r.$headCell.pos)return!1;a=r.$anchorCell.nodeAfter,i=r.$anchorCell.pos}else{var l;if(a=btn(r.$from),!a)return!1;i=(l=tB(r.$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(n){let o=a.attrs;const c=[],d=o.colwidth;o.rowspan>1&&(o={...o,rowspan:1}),o.colspan>1&&(o={...o,colspan:1});const u=c3(t),h=t.tr;for(let f=0;f{l.attrs[s]!==t&&i.setNodeMarkup(o,null,{...l.attrs,[s]:t})}):i.setNodeMarkup(a.pos,null,{...a.nodeAfter.attrs,[s]:t}),r(i)}return!0}}function qtn(s){return function(t,n){if(!NC(t))return!1;if(n){const r=E1(t.schema),a=c3(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 f=m+i.tableStart,g=l.doc.nodeAt(f);g&&l.setNodeMarkup(f,h,g.attrs)}),r(l)}return!0}}Ase("row",{useDeprecatedLogic:!0});Ase("column",{useDeprecatedLogic:!0});const Vtn=Ase("cell",{useDeprecatedLogic:!0});function Htn(s,t){if(t<0){const n=s.nodeBefore;if(n)return s.pos-n.nodeSize;for(let r=s.index(-1)-1,a=s.before();r>=0;r--){const i=s.node(-1).child(r),l=i.lastChild;if(l)return a-1-l.nodeSize;a-=i.nodeSize}}else{if(s.index()0;r--)if(n.node(r).type.spec.tableRole=="table")return t&&t(s.tr.delete(n.before(r),n.after(r)).scrollIntoView()),!0;return!1}function bde(s,t){const n=s.selection;if(!(n instanceof Jf))return!1;if(t){const r=s.tr,a=E1(s.schema).cell.createAndFill().content;n.forEachCell((i,l)=>{i.content.eq(a)||r.replace(r.mapping.map(l+1),r.mapping.map(l+i.nodeSize-1),new Ki(a,0,0))}),r.docChanged&&t(r)}return!0}function Wtn(s){if(s.size===0)return null;let{content:t,openStart:n,openEnd:r}=s;for(;t.childCount==1&&(n>0&&r>0||t.child(0).type.spec.tableRole=="table");)n--,r--,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(hi.empty),n[a]r&&(m=m.type.createChecked(sB(m.attrs,m.attrs.colspan,u+m.attrs.colspan-r),m.content)),d.push(m),u+=m.attrs.colspan;for(let f=1;fa&&(h=h.type.create({...h.attrs,rowspan:Math.max(1,a-h.attrs.rowspan)},h.content)),c.push(h)}i.push(hi.from(c))}n=i,t=a}return{width:s,height:t,rows:n}}function Ztn(s,t,n,r,a,i,l){const o=s.doc.type.schema,c=E1(o);let d,u;if(a>t.width)for(let h=0,m=0;ht.height){const h=[];for(let g=0,x=(t.height-1)*t.width;g=t.width?!1:n.nodeAt(t.map[x+g]).type==c.header_cell;h.push(y?u||(u=c.header_cell.createAndFill()):d||(d=c.cell.createAndFill()))}const m=c.row.create(null,hi.from(h)),f=[];for(let g=t.height;g{if(!a)return!1;const i=n.selection;if(i instanceof Jf)return v3e(n,r,oc.near(i.$headCell,t));if(s!="horiz"&&!i.empty)return!1;const l=wHt(a,s,t);if(l==null)return!1;if(s=="horiz")return v3e(n,r,oc.near(n.doc.resolve(i.head+t),t));{const o=n.doc.resolve(l),c=pHt(o,s,t);let d;return c?d=oc.near(c,1):t<0?d=oc.near(n.doc.resolve(o.before(-1)),-1):d=oc.near(n.doc.resolve(o.after(-1)),1),v3e(n,r,d)}}}function wde(s,t){return(n,r,a)=>{if(!a)return!1;const i=n.selection;let l;if(i instanceof Jf)l=i;else{const c=wHt(a,s,t);if(c==null)return!1;l=new Jf(n.doc.resolve(c))}const o=pHt(l.$headCell,s,t);return o?v3e(n,r,new Jf(l.$anchorCell,o)):!1}}function Qtn(s,t){const n=s.state.doc,r=tB(n.resolve(t));return r?(s.dispatch(s.state.tr.setSelection(new Jf(r))),!0):!1}function Jtn(s,t,n){if(!NC(s.state))return!1;let r=Wtn(n);const a=s.state.selection;if(a instanceof Jf){r||(r={width:1,height:1,rows:[hi.from(TWe(E1(s.state.schema).cell,n))]});const i=a.$anchorCell.node(-1),l=a.$anchorCell.start(-1),o=_x.get(i).rectBetween(a.$anchorCell.pos-l,a.$headCell.pos-l);return r=Ytn(r,o.right-o.left,o.bottom-o.top),Q1t(s.state,s.dispatch,l,o,r),!0}else if(r){const i=X6e(s.state),l=i.start(-1);return Q1t(s.state,s.dispatch,l,_x.get(i.node(-1)).findCell(i.pos-l),r),!0}else return!1}function esn(s,t){var n;if(t.button!=0||t.ctrlKey||t.metaKey)return;const r=J1t(s,t.target);let a;if(t.shiftKey&&s.state.selection instanceof Jf)i(s.state.selection.$anchorCell,t),t.preventDefault();else if(t.shiftKey&&r&&(a=tB(s.state.selection.$anchor))!=null&&((n=ABe(s,t))===null||n===void 0?void 0:n.pos)!=a.pos)i(a,t),t.preventDefault();else if(!r)return;function i(c,d){let u=ABe(s,d);const h=EP.getState(s.state)==null;if(!u||!srt(c,u))if(h)u=c;else return;const m=new Jf(c,u);if(h||!s.state.selection.eq(m)){const f=s.state.tr.setSelection(m);h&&f.setMeta(EP,c.pos),s.dispatch(f)}}function l(){s.root.removeEventListener("mouseup",l),s.root.removeEventListener("dragstart",l),s.root.removeEventListener("mousemove",o),EP.getState(s.state)!=null&&s.dispatch(s.state.tr.setMeta(EP,-1))}function o(c){const d=c,u=EP.getState(s.state);let h;if(u!=null)h=s.state.doc.resolve(u);else if(J1t(s,d.target)!=r&&(h=ABe(s,t),!h))return l();h&&i(h,d)}s.root.addEventListener("mouseup",l),s.root.addEventListener("dragstart",l),s.root.addEventListener("mousemove",o)}function wHt(s,t,n){if(!(s.state.selection instanceof Al))return null;const{$head:r}=s.state.selection;for(let a=r.depth-1;a>=0;a--){const i=r.node(a);if((n<0?r.index(a):r.indexAfter(a))!=(n<0?0:i.childCount))return null;if(i.type.spec.tableRole=="cell"||i.type.spec.tableRole=="header_cell"){const l=r.before(a),o=t=="vert"?n>0?"down":"up":n>0?"right":"left";return s.endOfTextblock(o)?l:null}}return null}function J1t(s,t){for(;t&&t!=s.dom;t=t.parentNode)if(t.nodeName=="TD"||t.nodeName=="TH")return t;return null}function ABe(s,t){const n=s.posAtCoords({left:t.clientX,top:t.clientY});if(!n)return null;let{inside:r,pos:a}=n;return r>=0&&tB(s.state.doc.resolve(r))||tB(s.state.doc.resolve(a))}var tsn=class{constructor(t,n){this.node=t,this.defaultCellMinWidth=n,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",`${n}px`),this.colgroup=this.table.appendChild(document.createElement("colgroup")),MWe(t,this.colgroup,this.table,n),this.contentDOM=this.table.appendChild(document.createElement("tbody"))}update(t){return t.type!=this.node.type?!1:(this.node=t,MWe(t,this.colgroup,this.table,this.defaultCellMinWidth),!0)}ignoreMutation(t){return t.type=="attributes"&&(t.target==this.table||this.colgroup.contains(t.target))}};function MWe(s,t,n,r,a,i){let l=0,o=!0,c=t.firstChild;const d=s.firstChild;if(d){for(let h=0,m=0;hnew r(h,n,m)),new nsn(-1,!1)},apply(l,o){return o.apply(l)}},props:{attributes:l=>{const o=Qj.getState(l);return o&&o.activeHandle>-1?{class:"resize-cursor"}:{}},handleDOMEvents:{mousemove:(l,o)=>{rsn(l,o,s,a)},mouseleave:l=>{asn(l)},mousedown:(l,o)=>{isn(l,o,t,n)}},decorations:l=>{const o=Qj.getState(l);if(o&&o.activeHandle>-1)return usn(l,o.activeHandle)},nodeViews:{}}});return i}var nsn=class b3e{constructor(t,n){this.activeHandle=t,this.dragging=n}apply(t){const n=this,r=t.getMeta(Qj);if(r&&r.setHandle!=null)return new b3e(r.setHandle,!1);if(r&&r.setDragging!==void 0)return new b3e(n.activeHandle,r.setDragging);if(n.activeHandle>-1&&t.docChanged){let a=t.mapping.map(n.activeHandle,-1);return EWe(t.doc.resolve(a))||(a=-1),new b3e(a,n.dragging)}return n}};function rsn(s,t,n,r){if(!s.editable)return;const a=Qj.getState(s.state);if(a&&!a.dragging){const i=lsn(t.target);let l=-1;if(i){const{left:o,right:c}=i.getBoundingClientRect();t.clientX-o<=n?l=e_t(s,t,"left",n):c-t.clientX<=n&&(l=e_t(s,t,"right",n))}if(l!=a.activeHandle){if(!r&&l!==-1){const o=s.state.doc.resolve(l),c=o.node(-1),d=_x.get(c),u=o.start(-1);if(d.colCount(o.pos-u)+o.nodeAfter.attrs.colspan-1==d.width-1)return}jHt(s,l)}}}function asn(s){if(!s.editable)return;const t=Qj.getState(s.state);t&&t.activeHandle>-1&&!t.dragging&&jHt(s,-1)}function isn(s,t,n,r){var a;if(!s.editable)return!1;const i=(a=s.dom.ownerDocument.defaultView)!==null&&a!==void 0?a:window,l=Qj.getState(s.state);if(!l||l.activeHandle==-1||l.dragging)return!1;const o=s.state.doc.nodeAt(l.activeHandle),c=osn(s,l.activeHandle,o.attrs);s.dispatch(s.state.tr.setMeta(Qj,{setDragging:{startX:t.clientX,startWidth:c}}));function d(h){i.removeEventListener("mouseup",d),i.removeEventListener("mousemove",u);const m=Qj.getState(s.state);m!=null&&m.dragging&&(csn(s,m.activeHandle,t_t(m.dragging,h,n)),s.dispatch(s.state.tr.setMeta(Qj,{setDragging:null})))}function u(h){if(!h.which)return d(h);const m=Qj.getState(s.state);if(m&&m.dragging){const f=t_t(m.dragging,h,n);s_t(s,m.activeHandle,f,r)}}return s_t(s,l.activeHandle,c,r),i.addEventListener("mouseup",d),i.addEventListener("mousemove",u),t.preventDefault(),!0}function osn(s,t,{colspan:n,colwidth:r}){const a=r&&r[r.length-1];if(a)return a;const i=s.domAtPos(t);let l=i.node.childNodes[i.offset].offsetWidth,o=n;if(r)for(let c=0;c{const r=s.nodes[n];r.spec.tableRole&&(t[r.spec.tableRole]=r)}),s.cached.tableNodeTypes=t,t}function gsn(s,t,n,r,a){const i=psn(s),l=[],o=[];for(let d=0;d{const{selection:t}=s.state;if(!xsn(t))return!1;let n=0;const r=KVt(t.ranges[0].$from,i=>i.type.name==="table");return r==null||r.node.descendants(i=>{if(i.type.name==="table")return!1;["tableCell","tableHeader"].includes(i.type.name)&&(n+=1)}),n===t.ranges.length?(s.commands.deleteTable(),!0):!1},ysn=Rv.create({name:"table",addOptions(){return{HTMLAttributes:{},resizable:!1,renderWrapper:!1,handleWidth:5,cellMinWidth:25,View:msn,lastColumnResizable:!0,allowTableNodeSelection:!1}},content:"tableRow+",tableRole:"table",isolating:!0,group:"block",parseHTML(){return[{tag:"table"}]},renderHTML({node:s,HTMLAttributes:t}){const{colgroup:n,tableWidth:r,tableMinWidth:a}=fsn(s,this.options.cellMinWidth),i=["table",ep(this.options.HTMLAttributes,t,{style:r?`width: ${r}`:`min-width: ${a}`}),n,["tbody",0]];return this.options.renderWrapper?["div",{class:"tableWrapper"},i]:i},addCommands(){return{insertTable:({rows:s=3,cols:t=3,withHeaderRow:n=!0}={})=>({tr:r,dispatch:a,editor:i})=>{const l=gsn(i.schema,s,t,n);if(a){const o=r.selection.from+1;r.replaceSelectionWith(l).scrollIntoView().setSelection(Al.near(r.doc.resolve(o)))}return!0},addColumnBefore:()=>({state:s,dispatch:t})=>Mtn(s,t),addColumnAfter:()=>({state:s,dispatch:t})=>Ptn(s,t),deleteColumn:()=>({state:s,dispatch:t})=>Ltn(s,t),addRowBefore:()=>({state:s,dispatch:t})=>Dtn(s,t),addRowAfter:()=>({state:s,dispatch:t})=>Ftn(s,t),deleteRow:()=>({state:s,dispatch:t})=>ztn(s,t),deleteTable:()=>({state:s,dispatch:t})=>Gtn(s,t),mergeCells:()=>({state:s,dispatch:t})=>G1t(s,t),splitCell:()=>({state:s,dispatch:t})=>W1t(s,t),toggleHeaderColumn:()=>({state:s,dispatch:t})=>Ase("column")(s,t),toggleHeaderRow:()=>({state:s,dispatch:t})=>Ase("row")(s,t),toggleHeaderCell:()=>({state:s,dispatch:t})=>Vtn(s,t),mergeOrSplit:()=>({state:s,dispatch:t})=>G1t(s,t)?!0:W1t(s,t),setCellAttribute:(s,t)=>({state:n,dispatch:r})=>Utn(s,t)(n,r),goToNextCell:()=>({state:s,dispatch:t})=>Y1t(1)(s,t),goToPreviousCell:()=>({state:s,dispatch:t})=>Y1t(-1)(s,t),fixTables:()=>({state:s,dispatch:t})=>(t&&vHt(s),!0),setCellSelection:s=>({tr:t,dispatch:n})=>{if(n){const r=Jf.create(t.doc,s.anchorCell,s.headCell);t.setSelection(r)}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:jde,"Mod-Backspace":jde,Delete:jde,"Mod-Delete":jde}},addProseMirrorPlugins(){return[...this.options.resizable&&this.editor.isEditable?[ssn({handleWidth:this.options.handleWidth,cellMinWidth:this.options.cellMinWidth,defaultCellMinWidth:this.options.cellMinWidth,View:this.options.View,lastColumnResizable:this.options.lastColumnResizable})]:[],hsn({allowTableNodeSelection:this.options.allowTableNodeSelection})]},extendNodeSchema(s){const t={name:s.name,options:s.options,storage:s.storage};return{tableRole:Nd(Uo(s,"tableRole",t))}}}),vsn=Rv.create({name:"tableRow",addOptions(){return{HTMLAttributes:{}}},content:"(tableCell | tableHeader)*",tableRole:"row",parseHTML(){return[{tag:"tr"}]},renderHTML({HTMLAttributes:s}){return["tr",ep(this.options.HTMLAttributes,s),0]}}),bsn=Rv.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(r=>parseInt(r,10)):null}}}},tableRole:"cell",isolating:!0,parseHTML(){return[{tag:"td"}]},renderHTML({HTMLAttributes:s}){return["td",ep(this.options.HTMLAttributes,s),0]}}),_sn=Rv.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(r=>parseInt(r,10)):null}}}},tableRole:"header_cell",isolating:!0,parseHTML(){return[{tag:"th"}]},renderHTML({HTMLAttributes:s}){return["th",ep(this.options.HTMLAttributes,s),0]}});function Ek({content:s,onChange:t,placeholder:n="Enter content...",minHeight:r="150px",compact:a=!1}){const[i,l]=j.useState(!1),[o,c]=j.useState(""),[d,u]=j.useState(!0),h=G6e({extensions:[W6e,Y6e.configure({openOnClick:!1,HTMLAttributes:{class:"text-primary underline"}}),Z6e.configure({types:["heading","paragraph"]}),trt,fHt.extend({addAttributes(){var x;return{...(x=this.parent)==null?void 0:x.call(this),width:{default:null},height:{default:null},style:{default:null}}}}).configure({inline:!0,allowBase64:!0}),ysn.extend({addAttributes(){var x;return{...(x=this.parent)==null?void 0:x.call(this),style:{default:null},width:{default:null},cellpadding:{default:null},cellspacing:{default:null},border:{default:null}}}}).configure({resizable:!1}),vsn.extend({addAttributes(){var x;return{...(x=this.parent)==null?void 0:x.call(this),style:{default:null}}}}),bsn.extend({addAttributes(){var x;return{...(x=this.parent)==null?void 0:x.call(this),style:{default:null},width:{default:null},colspan:{default:1},rowspan:{default:1},valign:{default:null}}}}),_sn.extend({addAttributes(){var x;return{...(x=this.parent)==null?void 0:x.call(this),style:{default:null},width:{default:null},colspan:{default:1},rowspan:{default:1}}}})],content:s,onUpdate:({editor:x})=>{t(x.getHTML())},editorProps:{attributes:{class:"outline-none","data-placeholder":n},handlePaste:(x,y)=>{var b;const v=(b=y.clipboardData)==null?void 0:b.items;if(!v)return!1;for(const w of Array.from(v))if(w.type.startsWith("image/")){y.preventDefault();const S=w.getAsFile();if(!S)continue;const C=new FileReader;return C.onload=E=>{var P;const I=(P=E.target)==null?void 0:P.result;x.dispatch(x.state.tr.replaceSelectionWith(x.state.schema.nodes.image.create({src:I})))},C.readAsDataURL(S),!0}return!1}}});j.useEffect(()=>{h&&s!==h.getHTML()&&h.commands.setContent(s)},[s,h]);const m=()=>{if(!h)return;const x=h.getAttributes("link").href||"",y=h.getAttributes("link").target;c(x),u(y==="_blank"),l(!0)},f=()=>{h&&(o===""?h.chain().focus().extendMarkRange("link").unsetLink().run():h.chain().focus().extendMarkRange("link").setLink({href:o,target:d?"_blank":null,rel:d?"noopener noreferrer nofollow":null}).run(),l(!1),c(""))},g=()=>{h&&h.chain().focus().extendMarkRange("link").unsetLink().run()};return h?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($,{type:"button",variant:"ghost",size:"sm",onClick:()=>h.chain().focus().toggleHeading({level:1}).run(),className:h.isActive("heading",{level:1})?"bg-muted":"",title:"Heading 1",children:e.jsx(Bq,{className:"h-4 w-4"})}),e.jsx($,{type:"button",variant:"ghost",size:"sm",onClick:()=>h.chain().focus().toggleHeading({level:2}).run(),className:h.isActive("heading",{level:2})?"bg-muted":"",title:"Heading 2",children:e.jsx(Hz,{className:"h-4 w-4"})}),e.jsx("div",{className:"w-px h-6 bg-border mx-1"}),e.jsx($,{type:"button",variant:"ghost",size:"sm",onClick:()=>h.chain().focus().toggleBold().run(),className:h.isActive("bold")?"bg-muted":"",title:"Bold",children:e.jsx(AE,{className:"h-4 w-4"})}),e.jsx($,{type:"button",variant:"ghost",size:"sm",onClick:()=>h.chain().focus().toggleItalic().run(),className:h.isActive("italic")?"bg-muted":"",title:"Italic",children:e.jsx(ME,{className:"h-4 w-4"})}),e.jsx("div",{className:"w-px h-6 bg-border mx-1"}),e.jsx($,{type:"button",variant:"ghost",size:"sm",onClick:()=>h.chain().focus().toggleBulletList().run(),className:h.isActive("bulletList")?"bg-muted":"",title:"Bullet List",children:e.jsx(P0,{className:"h-4 w-4"})}),e.jsx($,{type:"button",variant:"ghost",size:"sm",onClick:()=>h.chain().focus().toggleOrderedList().run(),className:h.isActive("orderedList")?"bg-muted":"",title:"Numbered List",children:e.jsx(p2,{className:"h-4 w-4"})}),e.jsx("div",{className:"w-px h-6 bg-border mx-1"}),e.jsx($,{type:"button",variant:"ghost",size:"sm",onClick:()=>h.chain().focus().setTextAlign("left").run(),className:h.isActive({textAlign:"left"})?"bg-muted":"",title:"Align Left",children:e.jsx(BI,{className:"h-4 w-4"})}),e.jsx($,{type:"button",variant:"ghost",size:"sm",onClick:()=>h.chain().focus().setTextAlign("center").run(),className:h.isActive({textAlign:"center"})?"bg-muted":"",title:"Align Center",children:e.jsx(zI,{className:"h-4 w-4"})}),e.jsx($,{type:"button",variant:"ghost",size:"sm",onClick:()=>h.chain().focus().setTextAlign("right").run(),className:h.isActive({textAlign:"right"})?"bg-muted":"",title:"Align Right",children:e.jsx($I,{className:"h-4 w-4"})}),e.jsx("div",{className:"w-px h-6 bg-border mx-1"}),e.jsx($,{type:"button",variant:"ghost",size:"sm",onClick:m,className:h.isActive("link")?"bg-muted":"",title:"Add Link",children:e.jsx(Ad,{className:"h-4 w-4"})}),h.isActive("link")&&e.jsx($,{type:"button",variant:"ghost",size:"sm",onClick:g,title:"Remove Link",children:e.jsx(Ad,{className:"h-4 w-4"})}),e.jsx("div",{className:"w-px h-6 bg-border mx-1"}),e.jsx($,{type:"button",variant:"ghost",size:"sm",onClick:()=>h.chain().focus().undo().run(),disabled:!h.can().undo(),title:"Undo",children:e.jsx(BE,{className:"h-4 w-4"})}),e.jsx($,{type:"button",variant:"ghost",size:"sm",onClick:()=>h.chain().focus().redo().run(),disabled:!h.can().redo(),title:"Redo",children:e.jsx(OE,{className:"h-4 w-4"})})]}),e.jsx(H6e,{editor:h,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:r}})]}),e.jsx(zs,{open:i,onOpenChange:l,children:e.jsxs(Os,{className:"sm:max-w-md",children:[e.jsx(Us,{children:e.jsx(Bs,{children:"Insert Link"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"link-url",children:"URL"}),e.jsx(pe,{id:"link-url",value:o,onChange:x=>c(x.target.value),placeholder:"https://example.com"})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Sn,{id:"link-new-tab",checked:d,onCheckedChange:u}),e.jsx(ee,{htmlFor:"link-new-tab",children:"Open in new tab"})]})]}),e.jsxs(Ar,{children:[e.jsx($,{type:"button",variant:"outline",onClick:()=>l(!1),children:"Cancel"}),e.jsx($,{type:"button",onClick:f,children:o?"Apply Link":"Remove Link"})]})]})})]}):null}var nrt={x:0,y:0,width:0,height:0,unit:"px"},E$=(s,t,n)=>Math.min(Math.max(s,t),n),wsn=(...s)=>s.filter(t=>t&&typeof t=="string").join(" "),a_t=(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 jsn(s,t,n,r){let a=S5(s,n,r);return s.width&&(a.height=a.width/t),s.height&&(a.width=a.height*t),a.y+a.height>r&&(a.height=r-a.y,a.width=a.height*t),a.x+a.width>n&&(a.width=n-a.x,a.height=a.width/t),s.unit==="%"?yP(a,n,r):a}function Nsn(s,t,n){let r=S5(s,t,n);return r.x=(t-r.width)/2,r.y=(n-r.height)/2,s.unit==="%"?yP(r,t,n):r}function yP(s,t,n){return s.unit==="%"?{...nrt,...s,unit:"%"}:{unit:"%",x:s.x?s.x/t*100:0,y:s.y?s.y/n*100:0,width:s.width?s.width/t*100:0,height:s.height?s.height/n*100:0}}function S5(s,t,n){return!s.unit||s.unit==="px"?{...nrt,...s,unit:"px"}:{unit:"px",x:s.x?s.x*t/100:0,y:s.y?s.y*n/100:0,width:s.width?s.width*t/100:0,height:s.height?s.height*n/100:0}}function i_t(s,t,n,r,a,i=0,l=0,o=r,c=a){let d={...s},u=Math.min(i,r),h=Math.min(l,a),m=Math.min(o,r),f=Math.min(c,a);t&&(t>1?(u=l?l*t:u,h=u/t,m=o*t):(h=i?i/t:h,u=h*t,f=c/t)),d.y<0&&(d.height=Math.max(d.height+d.y,h),d.y=0),d.x<0&&(d.width=Math.max(d.width+d.x,u),d.x=0);let g=r-(d.x+d.width);g<0&&(d.x=Math.min(d.x,r-u),d.width+=g);let x=a-(d.y+d.height);if(x<0&&(d.y=Math.min(d.y,a-h),d.height+=x),d.widthm&&((n==="sw"||n=="nw")&&(d.x-=m-d.width),d.width=m),d.height>f&&((n==="nw"||n=="ne")&&(d.y-=f-d.height),d.height=f),t){let y=d.width/d.height;if(yt){let v=Math.max(d.height*t,u);(n==="sw"||n=="nw")&&(d.x-=v-d.width),d.width=v}}return d}function ksn(s,t,n,r){let a={...s};return t==="ArrowLeft"?r==="nw"?(a.x-=n,a.y-=n,a.width+=n,a.height+=n):r==="w"?(a.x-=n,a.width+=n):r==="sw"?(a.x-=n,a.width+=n,a.height+=n):r==="ne"?(a.y+=n,a.width-=n,a.height-=n):r==="e"?a.width-=n:r==="se"&&(a.width-=n,a.height-=n):t==="ArrowRight"&&(r==="nw"?(a.x+=n,a.y+=n,a.width-=n,a.height-=n):r==="w"?(a.x+=n,a.width-=n):r==="sw"?(a.x+=n,a.width-=n,a.height-=n):r==="ne"?(a.y-=n,a.width+=n,a.height+=n):r==="e"?a.width+=n:r==="se"&&(a.width+=n,a.height+=n)),t==="ArrowUp"?r==="nw"?(a.x-=n,a.y-=n,a.width+=n,a.height+=n):r==="n"?(a.y-=n,a.height+=n):r==="ne"?(a.y-=n,a.width+=n,a.height+=n):r==="sw"?(a.x+=n,a.width-=n,a.height-=n):r==="s"?a.height-=n:r==="se"&&(a.width-=n,a.height-=n):t==="ArrowDown"&&(r==="nw"?(a.x+=n,a.y+=n,a.width-=n,a.height-=n):r==="n"?(a.y+=n,a.height-=n):r==="ne"?(a.y+=n,a.width-=n,a.height-=n):r==="sw"?(a.x-=n,a.width+=n,a.height+=n):r==="s"?a.height+=n:r==="se"&&(a.width+=n,a.height+=n)),a}var T$={capture:!0,passive:!1},Ssn=0,px,Csn=(px=class extends j.PureComponent{constructor(){super(...arguments);Nr(this,"docMoveBound",!1);Nr(this,"mouseDownOnCrop",!1);Nr(this,"dragStarted",!1);Nr(this,"evData",{startClientX:0,startClientY:0,startCropX:0,startCropY:0,clientX:0,clientY:0,isResize:!0});Nr(this,"componentRef",j.createRef());Nr(this,"mediaRef",j.createRef());Nr(this,"resizeObserver");Nr(this,"initChangeCalled",!1);Nr(this,"instanceId",`rc-${Ssn++}`);Nr(this,"state",{cropIsActive:!1,newCropIsBeingDrawn:!1});Nr(this,"onCropPointerDown",n=>{let{crop:r,disabled:a}=this.props,i=this.getBox();if(!r)return;let l=S5(r,i.width,i.height);if(a)return;n.cancelable&&n.preventDefault(),this.bindDocMove(),this.componentRef.current.focus({preventScroll:!0});let o=n.target.dataset.ord,c=!!o,d=n.clientX,u=n.clientY,h=l.x,m=l.y;if(o){let f=n.clientX-i.x,g=n.clientY-i.y,x=0,y=0;o==="ne"||o=="e"?(x=f-(l.x+l.width),y=g-l.y,h=l.x,m=l.y+l.height):o==="se"||o==="s"?(x=f-(l.x+l.width),y=g-(l.y+l.height),h=l.x,m=l.y):o==="sw"||o=="w"?(x=f-l.x,y=g-(l.y+l.height),h=l.x+l.width,m=l.y):(o==="nw"||o=="n")&&(x=f-l.x,y=g-l.y,h=l.x+l.width,m=l.y+l.height),d=h+i.x+x,u=m+i.y+y}this.evData={startClientX:d,startClientY:u,startCropX:h,startCropY:m,clientX:n.clientX,clientY:n.clientY,isResize:c,ord:o},this.mouseDownOnCrop=!0,this.setState({cropIsActive:!0})});Nr(this,"onComponentPointerDown",n=>{let{crop:r,disabled:a,locked:i,keepSelection:l,onChange:o}=this.props,c=this.getBox();if(a||i||l&&r)return;n.cancelable&&n.preventDefault(),this.bindDocMove(),this.componentRef.current.focus({preventScroll:!0});let d=n.clientX-c.x,u=n.clientY-c.y,h={unit:"px",x:d,y:u,width:0,height:0};this.evData={startClientX:n.clientX,startClientY:n.clientY,startCropX:d,startCropY:u,clientX:n.clientX,clientY:n.clientY,isResize:!0},this.mouseDownOnCrop=!0,o(S5(h,c.width,c.height),yP(h,c.width,c.height)),this.setState({cropIsActive:!0,newCropIsBeingDrawn:!0})});Nr(this,"onDocPointerMove",n=>{let{crop:r,disabled:a,onChange:i,onDragStart:l}=this.props,o=this.getBox();if(a||!r||!this.mouseDownOnCrop)return;n.cancelable&&n.preventDefault(),this.dragStarted||(this.dragStarted=!0,l&&l(n));let{evData:c}=this;c.clientX=n.clientX,c.clientY=n.clientY;let d;d=c.isResize?this.resizeCrop():this.dragCrop(),a_t(r,d)||i(S5(d,o.width,o.height),yP(d,o.width,o.height))});Nr(this,"onComponentKeyDown",n=>{let{crop:r,disabled:a,onChange:i,onComplete:l}=this.props;if(a)return;let o=n.key,c=!1;if(!r)return;let d=this.getBox(),u=this.makePixelCrop(d),h=(navigator.platform.match("Mac")?n.metaKey:n.ctrlKey)?px.nudgeStepLarge:n.shiftKey?px.nudgeStepMedium:px.nudgeStep;if(o==="ArrowLeft"?(u.x-=h,c=!0):o==="ArrowRight"?(u.x+=h,c=!0):o==="ArrowUp"?(u.y-=h,c=!0):o==="ArrowDown"&&(u.y+=h,c=!0),c){n.cancelable&&n.preventDefault(),u.x=E$(u.x,0,d.width-u.width),u.y=E$(u.y,0,d.height-u.height);let m=S5(u,d.width,d.height),f=yP(u,d.width,d.height);i(m,f),l&&l(m,f)}});Nr(this,"onHandlerKeyDown",(n,r)=>{let{aspect:a=0,crop:i,disabled:l,minWidth:o=0,minHeight:c=0,maxWidth:d,maxHeight:u,onChange:h,onComplete:m}=this.props,f=this.getBox();if(l||!i)return;if(n.key==="ArrowUp"||n.key==="ArrowDown"||n.key==="ArrowLeft"||n.key==="ArrowRight")n.stopPropagation(),n.preventDefault();else return;let g=(navigator.platform.match("Mac")?n.metaKey:n.ctrlKey)?px.nudgeStepLarge:n.shiftKey?px.nudgeStepMedium:px.nudgeStep,x=i_t(ksn(S5(i,f.width,f.height),n.key,g,r),a,r,f.width,f.height,o,c,d,u);if(!a_t(i,x)){let y=yP(x,f.width,f.height);h(x,y),m&&m(x,y)}});Nr(this,"onDocPointerDone",n=>{let{crop:r,disabled:a,onComplete:i,onDragEnd:l}=this.props,o=this.getBox();this.unbindDocMove(),!(a||!r)&&this.mouseDownOnCrop&&(this.mouseDownOnCrop=!1,this.dragStarted=!1,l&&l(n),i&&i(S5(r,o.width,o.height),yP(r,o.width,o.height)),this.setState({cropIsActive:!1,newCropIsBeingDrawn:!1}))});Nr(this,"onDragFocus",()=>{var n;(n=this.componentRef.current)==null||n.scrollTo(0,0)})}get document(){return document}getBox(){let n=this.mediaRef.current;if(!n)return{x:0,y:0,width:0,height:0};let{x:r,y:a,width:i,height:l}=n.getBoundingClientRect();return{x:r,y:a,width:i,height:l}}componentDidUpdate(n){let{crop:r,onComplete:a}=this.props;if(a&&!n.crop&&r){let{width:i,height:l}=this.getBox();i&&l&&a(S5(r,i,l),yP(r,i,l))}}componentWillUnmount(){this.resizeObserver&&this.resizeObserver.disconnect(),this.unbindDocMove()}bindDocMove(){this.docMoveBound||(this.docMoveBound=(this.document.addEventListener("pointermove",this.onDocPointerMove,T$),this.document.addEventListener("pointerup",this.onDocPointerDone,T$),this.document.addEventListener("pointercancel",this.onDocPointerDone,T$),!0))}unbindDocMove(){this.docMoveBound&&(this.docMoveBound=(this.document.removeEventListener("pointermove",this.onDocPointerMove,T$),this.document.removeEventListener("pointerup",this.onDocPointerDone,T$),this.document.removeEventListener("pointercancel",this.onDocPointerDone,T$),!1))}getCropStyle(){let{crop:n}=this.props;if(n)return{top:`${n.y}${n.unit}`,left:`${n.x}${n.unit}`,width:`${n.width}${n.unit}`,height:`${n.height}${n.unit}`}}dragCrop(){let{evData:n}=this,r=this.getBox(),a=this.makePixelCrop(r),i=n.clientX-n.startClientX,l=n.clientY-n.startClientY;return a.x=E$(n.startCropX+i,0,r.width-a.width),a.y=E$(n.startCropY+l,0,r.height-a.height),a}getPointRegion(n,r,a,i){let{evData:l}=this,o=l.clientX-n.x,c=l.clientY-n.y,d;d=i&&r?r==="nw"||r==="n"||r==="ne":c1?l?[l,l/r]:[o*r,o]:o?[o*r,o]:[l,l/r]}resizeCrop(){let{evData:n}=this,{aspect:r=0,maxWidth:a,maxHeight:i}=this.props,l=this.getBox(),[o,c]=this.resolveMinDimensions(l,r,this.props.minWidth,this.props.minHeight),d=this.makePixelCrop(l),u=this.getPointRegion(l,n.ord,o,c),h=n.ord||u,m=n.clientX-n.startClientX,f=n.clientY-n.startClientY;(o&&h==="nw"||h==="w"||h==="sw")&&(m=Math.min(m,-o)),(c&&h==="nw"||h==="n"||h==="ne")&&(f=Math.min(f,-c));let g={unit:"px",x:0,y:0,width:0,height:0};u==="ne"?(g.x=n.startCropX,g.width=m,r?(g.height=g.width/r,g.y=n.startCropY-g.height):(g.height=Math.abs(f),g.y=n.startCropY-g.height)):u==="se"?(g.x=n.startCropX,g.y=n.startCropY,g.width=m,r?g.height=g.width/r:g.height=f):u==="sw"?(g.x=n.startCropX+m,g.y=n.startCropY,g.width=Math.abs(m),r?g.height=g.width/r:g.height=f):u==="nw"&&(g.x=n.startCropX+m,g.width=Math.abs(m),r?(g.height=g.width/r,g.y=n.startCropY-g.height):(g.height=Math.abs(f),g.y=n.startCropY+f));let x=i_t(g,r,u,l.width,l.height,o,c,a,i);return r||px.xyOrds.indexOf(h)>-1?d=x:px.xOrds.indexOf(h)>-1?(d.x=x.x,d.width=x.width):px.yOrds.indexOf(h)>-1&&(d.y=x.y,d.height=x.height),d.x=E$(d.x,0,l.width-d.width),d.y=E$(d.y,0,l.height-d.height),d}renderCropSelection(){let{ariaLabels:n=px.defaultProps.ariaLabels,disabled:r,locked:a,renderSelectionAddon:i,ruleOfThirds:l,crop:o}=this.props,c=this.getCropStyle();if(o)return Gt.createElement("div",{style:c,className:"ReactCrop__crop-selection",onPointerDown:this.onCropPointerDown,"aria-label":n.cropArea,tabIndex:0,onKeyDown:this.onComponentKeyDown,role:"group"},!r&&!a&&Gt.createElement("div",{className:"ReactCrop__drag-elements",onFocus:this.onDragFocus},Gt.createElement("div",{className:"ReactCrop__drag-bar ord-n","data-ord":"n"}),Gt.createElement("div",{className:"ReactCrop__drag-bar ord-e","data-ord":"e"}),Gt.createElement("div",{className:"ReactCrop__drag-bar ord-s","data-ord":"s"}),Gt.createElement("div",{className:"ReactCrop__drag-bar ord-w","data-ord":"w"}),Gt.createElement("div",{className:"ReactCrop__drag-handle ord-nw","data-ord":"nw",tabIndex:0,"aria-label":n.nwDragHandle,onKeyDown:d=>this.onHandlerKeyDown(d,"nw"),role:"button"}),Gt.createElement("div",{className:"ReactCrop__drag-handle ord-n","data-ord":"n",tabIndex:0,"aria-label":n.nDragHandle,onKeyDown:d=>this.onHandlerKeyDown(d,"n"),role:"button"}),Gt.createElement("div",{className:"ReactCrop__drag-handle ord-ne","data-ord":"ne",tabIndex:0,"aria-label":n.neDragHandle,onKeyDown:d=>this.onHandlerKeyDown(d,"ne"),role:"button"}),Gt.createElement("div",{className:"ReactCrop__drag-handle ord-e","data-ord":"e",tabIndex:0,"aria-label":n.eDragHandle,onKeyDown:d=>this.onHandlerKeyDown(d,"e"),role:"button"}),Gt.createElement("div",{className:"ReactCrop__drag-handle ord-se","data-ord":"se",tabIndex:0,"aria-label":n.seDragHandle,onKeyDown:d=>this.onHandlerKeyDown(d,"se"),role:"button"}),Gt.createElement("div",{className:"ReactCrop__drag-handle ord-s","data-ord":"s",tabIndex:0,"aria-label":n.sDragHandle,onKeyDown:d=>this.onHandlerKeyDown(d,"s"),role:"button"}),Gt.createElement("div",{className:"ReactCrop__drag-handle ord-sw","data-ord":"sw",tabIndex:0,"aria-label":n.swDragHandle,onKeyDown:d=>this.onHandlerKeyDown(d,"sw"),role:"button"}),Gt.createElement("div",{className:"ReactCrop__drag-handle ord-w","data-ord":"w",tabIndex:0,"aria-label":n.wDragHandle,onKeyDown:d=>this.onHandlerKeyDown(d,"w"),role:"button"})),i&&Gt.createElement("div",{className:"ReactCrop__selection-addon",onPointerDown:d=>d.stopPropagation()},i(this.state)),l&&Gt.createElement(Gt.Fragment,null,Gt.createElement("div",{className:"ReactCrop__rule-of-thirds-hz"}),Gt.createElement("div",{className:"ReactCrop__rule-of-thirds-vt"})))}makePixelCrop(n){return S5({...nrt,...this.props.crop||{}},n.width,n.height)}render(){let{aspect:n,children:r,circularCrop:a,className:i,crop:l,disabled:o,locked:c,style:d,ruleOfThirds:u}=this.props,{cropIsActive:h,newCropIsBeingDrawn:m}=this.state,f=l?this.renderCropSelection():null,g=wsn("ReactCrop",i,h&&"ReactCrop--active",o&&"ReactCrop--disabled",c&&"ReactCrop--locked",m&&"ReactCrop--new-crop",l&&n&&"ReactCrop--fixed-aspect",l&&a&&"ReactCrop--circular-crop",l&&u&&"ReactCrop--rule-of-thirds",!this.dragStarted&&l&&!l.width&&!l.height&&"ReactCrop--invisible-crop",a&&"ReactCrop--no-animate");return Gt.createElement("div",{ref:this.componentRef,className:g,style:d},Gt.createElement("div",{ref:this.mediaRef,className:"ReactCrop__child-wrapper",onPointerDown:this.onComponentPointerDown},r),l?Gt.createElement("svg",{className:"ReactCrop__crop-mask",width:"100%",height:"100%"},Gt.createElement("defs",null,Gt.createElement("mask",{id:`hole-${this.instanceId}`},Gt.createElement("rect",{width:"100%",height:"100%",fill:"white"}),a?Gt.createElement("ellipse",{cx:`${l.x+l.width/2}${l.unit}`,cy:`${l.y+l.height/2}${l.unit}`,rx:`${l.width/2}${l.unit}`,ry:`${l.height/2}${l.unit}`,fill:"black"}):Gt.createElement("rect",{x:`${l.x}${l.unit}`,y:`${l.y}${l.unit}`,width:`${l.width}${l.unit}`,height:`${l.height}${l.unit}`,fill:"black"}))),Gt.createElement("rect",{fill:"black",fillOpacity:.5,width:"100%",height:"100%",mask:`url(#hole-${this.instanceId})`})):void 0,f)}},Nr(px,"xOrds",["e","w"]),Nr(px,"yOrds",["n","s"]),Nr(px,"xyOrds",["nw","ne","se","sw"]),Nr(px,"nudgeStep",1),Nr(px,"nudgeStepMedium",10),Nr(px,"nudgeStepLarge",100),Nr(px,"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"}}),px);function Asn(s,t,n){return Nsn(jsn({unit:"%",width:90},n,s,t),s,t)}const rrt=({open:s,onClose:t,imageSrc:n,onCropComplete:r,aspectRatio:a=1})=>{const i=j.useRef(null),[l,o]=j.useState(),[c,d]=j.useState(),[u,h]=j.useState(1),[m,f]=j.useState(0),g=j.useCallback(v=>{const{width:b,height:w}=v.currentTarget;o(Asn(b,w,a))},[a]),x=j.useCallback(async()=>{const v=i.current;if(!v||!c)return;const b=document.createElement("canvas"),w=b.getContext("2d");if(!w)return;const S=v.naturalWidth/v.width,C=v.naturalHeight/v.height,E=400;b.width=E,b.height=E,w.imageSmoothingQuality="high";const I=c.x*S,P=c.y*C,R=c.width*S,D=c.height*C,O=m*Math.PI/180,U=b.width/2,W=b.height/2;return w.save(),w.translate(U,W),w.rotate(O),w.scale(u,u),w.translate(-U,-W),w.drawImage(v,I,P,R,D,0,0,E,E),w.restore(),new Promise((V,G)=>{b.toBlob(Y=>{Y?V(Y):G(new Error("Canvas is empty"))},"image/jpeg",.95)})},[c,u,m]),y=async()=>{try{const v=await x();v&&(r(v),t())}catch(v){console.error("Error cropping image:",v)}};return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Os,{className:"max-w-lg",children:[e.jsx(Us,{children:e.jsx(Bs,{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(Csn,{crop:l,onChange:(v,b)=>o(b),onComplete:v=>d(v),aspect:a,circularCrop:!0,className:"max-h-[400px]",children:e.jsx("img",{ref:i,src:n,alt:"Crop preview",style:{transform:`scale(${u}) rotate(${m}deg)`,maxHeight:"400px",width:"auto"},onLoad:g})})}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(yV,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(kx,{value:[u],min:.5,max:3,step:.1,onValueChange:([v])=>h(v),className:"flex-1"}),e.jsx(nL,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(e7,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(kx,{value:[m],min:-180,max:180,step:1,onValueChange:([v])=>f(v),className:"flex-1"}),e.jsxs("span",{className:"text-sm text-muted-foreground w-12",children:[m,"°"]})]})]})]}),e.jsxs(Ar,{children:[e.jsx($,{variant:"outline",onClick:t,children:"Cancel"}),e.jsx($,{onClick:y,children:"Save Photo"})]})]})})},o_t="I agree to receive recurring SMS/MMS text messages from LevelUp, including new lead alerts, account notifications, service updates, and customer support. Message frequency varies. Message and data rates may apply. Reply STOP to opt out and HELP for help. Consent is not a condition of purchase.";function Esn(s){const t=s.replace(/\D/g,"");return s.trim().startsWith("+")?t.length>=8?`+${t}`:null:t.length===10?`+1${t}`:t.length===11&&t.startsWith("1")?`+${t}`:null}function Tsn(){const{user:s}=vs(),{toast:t}=Bi(),[n,r]=j.useState(!0),[a,i]=j.useState(!1),[l,o]=j.useState(""),[c,d]=j.useState(!1),[u,h]=j.useState(!1),[m,f]=j.useState(null),[g,x]=j.useState(!1);j.useEffect(()=>{s!=null&&s.id&&(async()=>{const{data:b}=await q.from("profiles").select("phone, phone_e164, sms_consent, sms_consent_at").eq("id",s.id).maybeSingle(),w=b;w&&(o(w.phone_e164||w.phone||""),h(!!w.sms_consent),d(!!w.sms_consent),f(w.sms_consent_at||null)),r(!1)})()},[s==null?void 0:s.id]);const y=async()=>{const b=Esn(l);if(!b){t({title:"Invalid number",description:"Enter a valid mobile number, e.g. (555) 123-4567.",variant:"destructive"});return}if(!c){t({title:"Consent required",description:"Please check the consent box to opt in to text messages.",variant:"destructive"});return}i(!0);const{error:w}=await q.from("profiles").update({phone_e164:b,sms_consent:!0,sms_consent_at:new Date().toISOString(),sms_consent_text:o_t,sms_consent_source:"profile_page",sms_opted_out_at:null}).eq("id",s.id);if(i(!1),w){t({title:"Error",description:w.message,variant:"destructive"});return}h(!0),f(new Date().toISOString()),t({title:"You're opted in",description:"You'll now receive text alerts for new leads and account notifications."})},v=async()=>{i(!0);const{error:b}=await q.from("profiles").update({sms_consent:!1,sms_opted_out_at:new Date().toISOString()}).eq("id",s.id);if(i(!1),b){t({title:"Error",description:b.message,variant:"destructive"});return}h(!1),d(!1),t({title:"Opted out",description:"You will no longer receive text messages from LevelUp."})};return e.jsxs(Ne,{children:[e.jsxs(Ct,{children:[e.jsxs(At,{className:"flex items-center gap-2",children:[e.jsx(eo,{className:"h-5 w-5"}),"Text Message (SMS) Alerts",u&&e.jsx(Be,{variant:"secondary",children:"Opted in"})]}),e.jsx(Gn,{children:"Get a text the moment a new lead comes in, plus important account notifications."})]}),e.jsx(Ie,{className:"space-y-4",children:n?e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(kt,{className:"h-4 w-4 animate-spin"})," Loading…"]}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"rounded-lg border border-primary/30 bg-primary/5 p-3",children:e.jsx("p",{className:"text-sm font-medium",children:"SMS is completely optional. It is not required to create an account, save your profile, purchase, access, or use LevelUp. You may leave this blank or decline."})}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"sms-mobile",children:"Mobile Number (optional)"}),e.jsx(pe,{id:"sms-mobile",type:"tel",value:l,onChange:b=>o(b.target.value),placeholder:"(555) 123-4567",maxLength:30,autoComplete:"tel"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Only needed if you choose to opt in. Must be a mobile number that can receive text messages."})]}),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(ai,{id:"sms-consent",checked:c,onCheckedChange:b=>d(b===!0),disabled:u,className:"mt-0.5"}),e.jsx(ee,{htmlFor:"sms-consent",className:"text-sm font-normal leading-relaxed cursor-pointer",children:o_t})]})}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Message types: new lead alerts, account notifications, service updates, customer support. Frequency varies. Msg & data rates may apply. Reply STOP to opt out, HELP for help. No mobile information will be shared with third parties or affiliates for marketing purposes."}),u&&m&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Consent recorded on ",new Date(m).toLocaleString("en-US",{timeZone:"America/New_York"}),"."]}),g&&!u&&e.jsx("p",{className:"text-xs text-muted-foreground",children:"You chose not to enroll in text alerts. Nothing was saved and your account is unaffected."}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs($,{onClick:y,disabled:a||u&&!l,children:[a&&e.jsx(kt,{className:"mr-2 h-4 w-4 animate-spin"}),u?"Update Number":"Opt in to SMS"]}),u?e.jsx($,{variant:"outline",onClick:v,disabled:a,children:"Opt out"}):e.jsx($,{variant:"outline",type:"button",disabled:a,onClick:()=>{o(""),d(!1),x(!0),t({title:"SMS skipped",description:"No consent was recorded. You can keep using LevelUp normally."})},children:"Skip SMS / Continue without text alerts"})]})]})})]})}const l_t="#2a4c64",c_t="#B8965A",d_t="Inter",u_t="Inter";function NU(s){if(typeof s!="string")return null;const t=s.trim();return t.length?t:null}function sw(s,t=null){for(const[n,r]of s){const a=NU(r);if(a)return{value:a,source:n}}return{value:t,source:"default"}}function Msn(s){const t=s.agent??{},n=s.brokerage??{},r=s.legacy??{},a=!!n.lock_colors,i=!!n.lock_logo,l=(E,I,P)=>a?[["brokerage",I],["agent",E],["legacy",P]]:[["agent",E],["brokerage",I],["legacy",P]],o=sw(l(t.brand_color,n.primary_color,r.brand_color),l_t),c=sw(l(t.accent_color,n.accent_color,r.accent_color),c_t),d=sw([["brokerage",n.secondary_color]]),u=i?[["brokerage",n.logo_url],["agent",t.logo_url],["legacy",r.brokerage_logo_url||r.team_logo_url]]:[["agent",t.logo_url],["legacy",r.team_logo_url],["brokerage",n.logo_url],["legacy",r.brokerage_logo_url]],h=sw(u),m=sw([["brokerage",n.logo_url],["legacy",r.brokerage_logo_url]]),f=sw([["agent",t.headshot_url],["legacy",r.avatar_url]]),g=sw([["agent",t.tagline],["legacy",r.tagline||r.title]]),x=sw([["agent",t.preferred_font],["brokerage",n.heading_font]],d_t),y=sw([["brokerage",n.body_font]],u_t),v=sw([["agent",t.license_number],["legacy",r.license_number]]),b=sw([["agent",t.license_state],["legacy",r.license_state],["brokerage",n.license_state]]),w=sw([["agent",t.website_url],["legacy",r.website_url]]),S=sw([["brokerage",n.legal_name],["legacy",r.brokerage_name]]),C=sw([["brokerage",n.compliance_line]]);return{agent_name:NU(r.name),brokerage_name:S.value,brand_color:o.value??l_t,secondary_color:d.value,accent_color:c.value??c_t,heading_font:x.value??d_t,body_font:y.value??u_t,logo_url:h.value,logo_dark_url:NU(n.logo_dark_url),brokerage_logo_url:m.value,icon_mark_url:NU(n.icon_mark_url),headshot_url:f.value,tagline:g.value,license_number:v.value,license_state:b.value,website_url:w.value,email:NU(r.email),phone:NU(r.phone),compliance_line:C.value,show_equal_housing:!!n.show_equal_housing,show_realtor_logo:!!n.show_realtor_logo,locked:{colors:a,logo:i},sources:{brand_color:o.source,accent_color:c.source,secondary_color:d.source,logo_url:h.source,brokerage_logo_url:m.source,headshot_url:f.source,tagline:g.source,heading_font:x.source,body_font:y.source,license_number:v.source,license_state:b.source,website_url:w.source,brokerage_name:S.source,compliance_line:C.source}}}function Psn(){const{user:s}=vs();return tt({queryKey:["agent-brand-profile",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await q.from("agent_brand_profiles").select("*").eq("user_id",s.id).maybeSingle();if(n)throw n;return t??null}})}function Isn(){const{user:s}=vs(),t=Vt();return ft({mutationFn:async n=>{if(!s)throw new Error("Not signed in");const{data:r,error:a}=await q.from("agent_brand_profiles").upsert({user_id:s.id,...n},{onConflict:"user_id"}).select().single();if(a)throw a;return r},onSuccess:()=>{t.invalidateQueries({queryKey:["agent-brand-profile",s==null?void 0:s.id]}),t.invalidateQueries({queryKey:["brand-kit",s==null?void 0:s.id]})}})}function Lsn(s){return tt({queryKey:["brokerage-brand-profile",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await q.from("brokerage_brand_profiles").select("*").eq("brokerage_id",s).maybeSingle();if(n)throw n;return t??null}})}function Rsn(s){const{user:t}=vs(),n=Vt();return ft({mutationFn:async r=>{if(!s)throw new Error("No brokerage selected");const{data:a,error:i}=await q.from("brokerage_brand_profiles").upsert({brokerage_id:s,updated_by:(t==null?void 0:t.id)??null,...r},{onConflict:"brokerage_id"}).select().single();if(i)throw i;return a},onSuccess:()=>{n.invalidateQueries({queryKey:["brokerage-brand-profile",s]}),n.invalidateQueries({queryKey:["brand-kit"]})}})}function NHt(){const{user:s}=vs();return tt({queryKey:["brand-kit",s==null?void 0:s.id],enabled:!!s,staleTime:6e4,queryFn:async()=>{var m;const t=s.id,[n,r,a,i]=await Promise.all([q.from("profiles").select("name, email, phone, avatar_url, website_url, title, brokerage_name, brokerage_id").eq("id",t).maybeSingle(),q.from("agent_brand_profiles").select("*").eq("user_id",t).maybeSingle(),q.from("agent_cards").select("brokerage_display_name, brokerage_logo_url, team_logo_url, display_email, title, positioning_statement").eq("user_id",t).maybeSingle(),q.from("lead_sites").select("brand_color, accent_color, agent_license_number, license_state, brokerage_legal_name, team_logo_url, is_active, created_at").eq("agent_id",t).order("created_at",{ascending:!0}).limit(5)]),l=n.data??{},o=a.data??{},c=i.data??[],d=c.find(f=>f.is_active)??c[0]??{};let u=null,h=null;if(l.brokerage_id){const[f,g]=await Promise.all([q.from("brokerage_brand_profiles").select("*").eq("brokerage_id",l.brokerage_id).maybeSingle(),q.from("brokerages").select("name").eq("id",l.brokerage_id).maybeSingle()]);u=f.data??null,h=((m=g.data)==null?void 0:m.name)??null}return Msn({agent:r.data??null,brokerage:u,legacy:{name:l.name??null,email:o.display_email||l.email||s.email||null,phone:l.phone??null,avatar_url:l.avatar_url??null,website_url:l.website_url??null,title:l.title??null,brokerage_name:l.brokerage_name||o.brokerage_display_name||d.brokerage_legal_name||h,brokerage_logo_url:o.brokerage_logo_url??null,team_logo_url:o.team_logo_url||d.team_logo_url||null,brand_color:d.brand_color??null,accent_color:d.accent_color??null,license_number:d.agent_license_number??null,license_state:d.license_state??null,tagline:o.positioning_statement??null}})}})}async function kHt(s,t,n){var l;const r=((l=t.name.split(".").pop())==null?void 0:l.toLowerCase())||"png",a=`${s}/brand-${n}-${Date.now()}.${r}`,{error:i}=await q.storage.from("card-logos").upload(a,t,{upsert:!0,cacheControl:"3600"});if(i)throw i;return q.storage.from("card-logos").getPublicUrl(a).data.publicUrl}const Dsn=["Inter","Playfair Display","Montserrat","Poppins","Lora","Work Sans"];function Fsn(){const{user:s}=vs(),{toast:t}=Bi(),{data:n,isLoading:r}=Psn(),{data:a}=NHt(),i=Isn(),l=j.useRef(null),[o,c]=j.useState(!1),[d,u]=j.useState({brand_color:"",accent_color:"",logo_url:"",tagline:"",preferred_font:"",license_number:"",license_state:"",website_url:""});j.useEffect(()=>{n&&u({brand_color:n.brand_color||"",accent_color:n.accent_color||"",logo_url:n.logo_url||"",tagline:n.tagline||"",preferred_font:n.preferred_font||"",license_number:n.license_number||"",license_state:n.license_state||"",website_url:n.website_url||""})},[n]);const h=!!(a!=null&&a.locked.colors),m=!!(a!=null&&a.locked.logo),f=(y,v)=>u(b=>({...b,[y]:v})),g=async y=>{if(s){c(!0);try{const v=await kHt(s.id,y,"logo");f("logo_url",v),t({title:"Logo uploaded"})}catch(v){t({title:"Upload failed",description:v.message,variant:"destructive"})}finally{c(!1)}}},x=async()=>{try{await i.mutateAsync({brand_color:d.brand_color||null,accent_color:d.accent_color||null,logo_url:d.logo_url||null,tagline:d.tagline||null,preferred_font:d.preferred_font||null,license_number:d.license_number||null,license_state:d.license_state||null,website_url:d.website_url||null}),t({title:"Brand kit saved"})}catch(y){t({title:"Could not save",description:y.message,variant:"destructive"})}};return e.jsxs(Ne,{children:[e.jsxs(Ct,{children:[e.jsxs(At,{className:"flex items-center gap-2",children:[e.jsx(Yc,{className:"h-5 w-5"}),"Brand Kit"]}),e.jsx(Gn,{children:"Used by AI tools (ChatGPT via the LevelUp connector), flyers, presentations and your public pages. Anything you leave blank falls back to your brokerage's brand, then LevelUp defaults."})]}),e.jsx(Ie,{className:"space-y-6",children:r?e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground text-sm",children:[e.jsx(kt,{className:"h-4 w-4 animate-spin"})," Loading…"]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ee,{className:"flex items-center gap-2",children:["Brand color",h&&e.jsxs(Be,{variant:"secondary",className:"gap-1",children:[e.jsx(pc,{className:"h-3 w-3"})," Set by brokerage"]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(pe,{type:"color",className:"h-10 w-14 p-1",value:d.brand_color||(a==null?void 0:a.brand_color)||"#2a4c64",disabled:h,onChange:y=>f("brand_color",y.target.value)}),e.jsx(pe,{value:d.brand_color,placeholder:(a==null?void 0:a.brand_color)||"#2a4c64",disabled:h,onChange:y=>f("brand_color",y.target.value)})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Accent color"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(pe,{type:"color",className:"h-10 w-14 p-1",value:d.accent_color||(a==null?void 0:a.accent_color)||"#B8965A",disabled:h,onChange:y=>f("accent_color",y.target.value)}),e.jsx(pe,{value:d.accent_color,placeholder:(a==null?void 0:a.accent_color)||"#B8965A",disabled:h,onChange:y=>f("accent_color",y.target.value)})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ee,{className:"flex items-center gap-2",children:["Personal / team logo",m&&e.jsxs(Be,{variant:"secondary",className:"gap-1",children:[e.jsx(pc,{className:"h-3 w-3"})," Brokerage logo required"]})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[d.logo_url&&e.jsx("img",{src:d.logo_url,alt:"Your logo",className:"h-12 w-auto rounded border bg-background p-1"}),e.jsx("input",{ref:l,type:"file",accept:"image/*",className:"hidden",onChange:y=>{var v;return((v=y.target.files)==null?void 0:v[0])&&g(y.target.files[0])}}),e.jsxs($,{type:"button",variant:"outline",disabled:o||m,onClick:()=>{var y;return(y=l.current)==null?void 0:y.click()},children:[o?e.jsx(kt,{className:"h-4 w-4 animate-spin"}):e.jsx(ni,{className:"h-4 w-4"}),e.jsx("span",{className:"ml-2",children:"Upload logo"})]}),d.logo_url&&e.jsx($,{type:"button",variant:"ghost",onClick:()=>f("logo_url",""),disabled:m,children:"Remove"})]})]}),e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"brand-tagline",children:"Tagline"}),e.jsx(pe,{id:"brand-tagline",value:d.tagline,placeholder:(a==null?void 0:a.tagline)||"Your positioning statement",onChange:y=>f("tagline",y.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"brand-font",children:"Preferred font"}),e.jsx(pe,{id:"brand-font",list:"brand-font-options",value:d.preferred_font,placeholder:(a==null?void 0:a.heading_font)||"Inter",onChange:y=>f("preferred_font",y.target.value)}),e.jsx("datalist",{id:"brand-font-options",children:Dsn.map(y=>e.jsx("option",{value:y},y))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"brand-license",children:"License number"}),e.jsx(pe,{id:"brand-license",value:d.license_number,placeholder:(a==null?void 0:a.license_number)||"DRE #01234567",onChange:y=>f("license_number",y.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"brand-license-state",children:"License state"}),e.jsx(pe,{id:"brand-license-state",value:d.license_state,placeholder:(a==null?void 0:a.license_state)||"CA",onChange:y=>f("license_state",y.target.value)})]}),e.jsxs("div",{className:"space-y-2 sm:col-span-2",children:[e.jsx(ee,{htmlFor:"brand-website",children:"Website"}),e.jsx(pe,{id:"brand-website",value:d.website_url,placeholder:(a==null?void 0:a.website_url)||"https://yoursite.com",onChange:y=>f("website_url",y.target.value)})]})]}),(a==null?void 0:a.compliance_line)&&e.jsxs("div",{className:"rounded-md border bg-muted/40 p-3 text-sm text-muted-foreground",children:[e.jsx("span",{className:"font-medium text-foreground",children:"Required disclaimer from your brokerage: "}),a.compliance_line]}),e.jsxs($,{onClick:x,disabled:i.isPending,children:[i.isPending?e.jsx(kt,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(tl,{className:"mr-2 h-4 w-4"}),"Save brand kit"]})]})})]})}const EBe="id, name, address, notes, created_at, locked_style, share_token, share_enabled, share_headline, share_message, share_views";function wSr(s,t){const[n,r]=j.useState(null);return j.useEffect(()=>{let a=!1;if(!t){r(null);return}if(t.startsWith("http")||t.startsWith("data:")){r(t);return}return q.storage.from(s).createSignedUrl(t,60*60).then(({data:i})=>{a||r((i==null?void 0:i.signedUrl)??null)}),()=>{a=!0}},[s,t]),n}function Osn(){var o,c,d;const{user:s}=vs(),t=Vt(),n=tt({queryKey:["staging-credits",s==null?void 0:s.id],enabled:!!(s!=null&&s.id),staleTime:3e4,queryFn:async()=>{const{data:u,error:h}=await q.functions.invoke("staging-credits-sync");if(h)throw h;return{credits:(u==null?void 0:u.credits)??null,unlimited:!!(u!=null&&u.unlimited),unlimitedReason:(u==null?void 0:u.unlimitedReason)??null}}}),r=((o=n.data)==null?void 0:o.credits)??null,a=!!((c=n.data)!=null&&c.unlimited),i=r?Math.max(r.monthly_included-r.monthly_used,0):0,l=i+((r==null?void 0:r.purchased_balance)??0);return{credits:r,unlimited:a,unlimitedReason:((d=n.data)==null?void 0:d.unlimitedReason)??null,remainingMonthly:i,purchased:(r==null?void 0:r.purchased_balance)??0,total:l,legacyPlan:(r==null?void 0:r.legacy_plan)??null,isLoading:n.isLoading,refresh:()=>t.invalidateQueries({queryKey:["staging-credits"]})}}function jSr(){return tt({queryKey:["staging-credit-packs"],staleTime:5*6e4,queryFn:async()=>{const{data:s,error:t}=await q.from("staging_credit_packs").select("id, key, name, credits, price_cents, sort_order").eq("is_active",!0).order("sort_order");if(t)throw t;return s??[]}})}function NSr(){const{user:s}=vs(),t=Vt(),n=tt({queryKey:["staging-projects",s==null?void 0:s.id],enabled:!!(s!=null&&s.id),queryFn:async()=>{const{data:o,error:c}=await q.from("staging_projects").select(EBe).eq("user_id",s.id).order("created_at",{ascending:!1});if(c)throw c;return o??[]}}),r=ft({mutationFn:async o=>{const{data:c,error:d}=await q.from("staging_projects").insert({user_id:s.id,name:o.name,address:o.address??null}).select(EBe).single();if(d)throw d;return c},onSuccess:()=>t.invalidateQueries({queryKey:["staging-projects"]})}),a=ft({mutationFn:async o=>{const{error:c}=await q.from("staging_projects").update({name:o.name,address:o.address??null}).eq("id",o.id);if(c)throw c},onSuccess:()=>t.invalidateQueries({queryKey:["staging-projects"]})}),i=ft({mutationFn:async o=>{await q.from("staging_images").update({project_id:null}).eq("project_id",o);const{error:c}=await q.from("staging_projects").delete().eq("id",o);if(c)throw c},onSuccess:()=>{t.invalidateQueries({queryKey:["staging-projects"]}),t.invalidateQueries({queryKey:["staging-images"]})}}),l=ft({mutationFn:async o=>{const{id:c,...d}=o,{data:u,error:h}=await q.from("staging_projects").update(d).eq("id",c).select(EBe).single();if(h)throw h;return u},onSuccess:()=>t.invalidateQueries({queryKey:["staging-projects"]})});return{projects:n.data??[],isLoading:n.isLoading,createProject:r,renameProject:a,deleteProject:i,updateProject:l}}function kSr(){return ft({mutationFn:async s=>{if(s.length===0)return[];const{data:t,error:n}=await q.functions.invoke("staging-analyze",{body:{images:s}});if(n)throw n;return(t==null?void 0:t.results)??[]}})}function SSr(s){const{user:t}=vs(),n=Vt(),r=tt({queryKey:["staging-images",t==null?void 0:t.id,s??"all"],enabled:!!(t!=null&&t.id),queryFn:async()=>{let o=q.from("staging_images").select("*").eq("user_id",t.id).order("created_at",{ascending:!1}).limit(300);s&&(o=o.eq("project_id",s));const{data:c,error:d}=await o;if(d)throw d;return c??[]}}),a=ft({mutationFn:async o=>{const{data:c,error:d}=await q.from("staging_images").delete().eq("id",o).select("id");if(d)throw d;if(!(c!=null&&c.length))throw new Error("This photo could not be deleted.")},onSuccess:()=>n.invalidateQueries({queryKey:["staging-images"]})}),i=ft({mutationFn:async o=>{const{data:c,error:d}=await q.from("staging_images").update({is_favorite:!o.is_favorite}).eq("id",o.id).select("id");if(d)throw d;if(!(c!=null&&c.length))throw new Error("This photo could not be updated.")},onSuccess:()=>n.invalidateQueries({queryKey:["staging-images"]})}),l=ft({mutationFn:async({id:o,projectId:c})=>{const{data:d,error:u}=await q.from("staging_images").update({project_id:c}).eq("id",o).select("id");if(u)throw u;if(!(d!=null&&d.length))throw new Error("This photo could not be moved.")},onSuccess:()=>n.invalidateQueries({queryKey:["staging-images"]})});return{images:r.data??[],isLoading:r.isLoading,remove:a,toggleFavorite:i,assignProject:l}}function CSr(){const s=Vt();return ft({mutationFn:async t=>{const{data:n,error:r}=await q.functions.invoke("staging-generate",{body:t});if(r){let a=r.message;try{const i=r.context;if(i){const l=await i.json();a=(l==null?void 0:l.message)||(l==null?void 0:l.error)||a}}catch{}throw new Error(a)}if(n!=null&&n.error)throw new Error(n.message||n.error);return{image:n.image,generatedUrl:n.generatedUrl}},onSuccess:()=>{s.invalidateQueries({queryKey:["staging-images"]}),s.invalidateQueries({queryKey:["staging-credits"]})}})}async function ASr(s){return new Promise((t,n)=>{const r=new FileReader;r.onload=()=>t(r.result),r.onerror=n,r.readAsDataURL(s)})}function zsn(){try{return window.open("","_blank")}catch{return null}}function Bsn(s,t){var n;if(s&&!s.closed)try{s.location.href=t,(n=s.focus)==null||n.call(s);return}catch{}window.location.assign(t)}function $sn(s){try{s&&!s.closed&&s.close()}catch{}}async function Usn(s,t){if(s instanceof Tae)try{const n=await s.context.text();try{const r=JSON.parse(n),a=(r==null?void 0:r.error)??(r==null?void 0:r.message);if(typeof a=="string"&&a.trim())return a}catch{if(n.trim())return n.trim().slice(0,300)}}catch{}return s instanceof Error&&s.message?s.message:t}function qsn(){var i;const s=Osn(),[t,n]=j.useState(!1);if(s.isLoading)return null;const r=s.unlimited&&s.unlimitedReason==="plan",a=async()=>{if(t)return;const l=zsn();n(!0);try{const{data:o,error:c}=await q.functions.invoke("staging-portal");if(c)throw c;if(!(o!=null&&o.url))throw new Error("No billing portal available");Bsn(l,o.url)}catch(o){$sn(l);const c=await Usn(o,"We could not open your billing portal. Contact support and we will sort it out.");console.error("[staging-portal]",c,o),re.error(c)}finally{n(!1)}};return e.jsxs(Ne,{children:[e.jsxs(Ct,{children:[e.jsxs(At,{className:"flex items-center gap-2",children:[e.jsx(Nn,{className:"h-5 w-5"}),"Staging Studio Billing"]}),e.jsx(Gn,{children:"Manage the plan and credits that power your AI photo staging"})]}),e.jsxs(Ie,{className:"space-y-4",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsx(Be,{variant:r?"default":"secondary",children:s.legacyPlan?`${s.legacyPlan} plan`:"Included with LevelUp"}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[r?"Unlimited staged photos each month":`${s.remainingMonthly} of ${((i=s.credits)==null?void 0:i.monthly_included)??0} photos left this month`,!r&&s.purchased>0&&` · ${s.purchased} pack credits`]})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs($,{variant:"outline",size:"sm",onClick:a,disabled:t,children:[t?e.jsx(kt,{className:"mr-1.5 h-3.5 w-3.5 animate-spin"}):e.jsx(Cv,{className:"mr-1.5 h-3.5 w-3.5"}),"Manage billing"]}),e.jsx($,{variant:"ghost",size:"sm",asChild:!0,children:e.jsxs(wr,{to:"/apps/staging-studio/credits",children:["Credits & history ",e.jsx(kr,{className:"ml-1.5 h-3.5 w-3.5"})]})})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:s.legacyPlan?"Cancel, update your card or change plans in the billing portal. Changes apply to your Staging Studio credits automatically.":"If you ever bought a Staging Studio plan or credit packs, open the billing portal to update your card, change plans or cancel."})]})]})}const h_t=["image/png","image/jpeg","image/jpg","image/svg+xml","image/webp"],Vsn=5*1024*1024;function Hsn({userId:s,value:t,onChange:n,persistToProfile:r=!0,label:a="Brokerage logo",description:i="PNG, JPG, SVG or WebP — up to 5MB. Used on your website and marketing.",className:l}){const o=j.useRef(null),[c,d]=j.useState(!1),[u,h]=j.useState(!1),m=async g=>{if(!h_t.includes(g.type)){re.error("Please upload a PNG, JPG, SVG or WebP file");return}if(g.size>Vsn){re.error("Please choose a logo under 5MB");return}d(!0);try{const x=(g.name.split(".").pop()||"png").toLowerCase(),y=`${s}/brokerage-logo-${Date.now()}.${x}`,{error:v}=await q.storage.from("card-logos").upload(y,g,{cacheControl:"3600",upsert:!0,contentType:g.type});if(v)throw v;const{data:b}=q.storage.from("card-logos").getPublicUrl(y),w=b.publicUrl;r&&await q.from("profiles").update({brokerage_logo_url:w}).eq("id",s),n(w),re.success("Brokerage logo uploaded")}catch(x){re.error((x==null?void 0:x.message)||"Upload failed")}finally{d(!1)}},f=async()=>{r&&await q.from("profiles").update({brokerage_logo_url:null}).eq("id",s),n(null)};return e.jsxs("div",{className:Pt("space-y-2",l),children:[e.jsx(ee,{children:a}),e.jsxs("div",{onDragOver:g=>{g.preventDefault(),h(!0)},onDragLeave:()=>h(!1),onDrop:g=>{var y;g.preventDefault(),h(!1);const x=(y=g.dataTransfer.files)==null?void 0:y[0];x&&m(x)},onClick:()=>{var g;return!c&&((g=o.current)==null?void 0:g.click())},className:Pt("flex cursor-pointer items-center gap-4 rounded-xl border border-dashed p-4 transition-colors",u?"border-primary bg-primary/5":"border-border hover:bg-muted/50"),children:[e.jsx("div",{className:"flex h-16 w-24 shrink-0 items-center justify-center overflow-hidden rounded-lg bg-muted",children:t?e.jsx("img",{src:t,alt:"Brokerage logo",className:"h-full w-full object-contain p-1"}):e.jsx(ji,{className:"h-6 w-6 text-muted-foreground"})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"text-sm font-medium",children:c?"Uploading…":t?"Logo added":"Drag & drop your brokerage logo"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:i})]}),e.jsxs("div",{className:"flex shrink-0 items-center gap-2",children:[e.jsxs($,{type:"button",variant:"outline",size:"sm",disabled:c,onClick:g=>{var x;g.stopPropagation(),(x=o.current)==null||x.click()},children:[c?e.jsx(kt,{className:"h-4 w-4 animate-spin"}):e.jsx(ni,{className:"h-4 w-4"}),e.jsx("span",{className:"ml-2",children:t?"Replace":"Upload"})]}),t&&!c&&e.jsx($,{type:"button",variant:"ghost",size:"icon",onClick:g=>{g.stopPropagation(),f()},children:e.jsx(Wn,{className:"h-4 w-4 text-muted-foreground"})})]})]}),e.jsx("input",{ref:o,type:"file",accept:h_t.join(","),className:"hidden",onChange:g=>{var y;const x=(y=g.target.files)==null?void 0:y[0];x&&m(x),g.target.value=""}})]})}const Gsn=()=>{const{user:s}=vs(),{toast:t}=Bi(),[n,r]=j.useState(!1),[a,i]=j.useState(!1),[l,o]=j.useState(null);j.useEffect(()=>{s&&c()},[s]);const c=async()=>{r(!0);try{const{data:h}=await q.from("profiles").select("subscription_status, subscription_product_id, subscription_end_date, is_grandfathered").eq("id",s==null?void 0:s.id).single();h&&o({status:h.subscription_status||"none",productId:h.subscription_product_id,endDate:h.subscription_end_date,isGrandfathered:h.is_grandfathered||!1})}catch(h){console.error("Error loading subscription:",h)}finally{r(!1)}},d=async()=>{i(!0);try{const{data:{session:h}}=await q.auth.getSession();if(!h)throw new Error("Not authenticated");const{data:m,error:f}=await q.functions.invoke("customer-portal",{headers:{Authorization:`Bearer ${h.access_token}`}});if(f)throw f;m!=null&&m.url&&window.open(m.url,"_blank")}catch(h){console.error("Error opening customer portal:",h),t({title:"Error",description:h.message||"Failed to open billing portal",variant:"destructive"})}finally{i(!1)}},u=()=>{if(l!=null&&l.isGrandfathered)return e.jsx(Be,{className:"bg-green-500",children:"Active"});switch(l==null?void 0:l.status){case"active":return e.jsx(Be,{className:"bg-green-500",children:"Active"});case"trialing":return e.jsx(Be,{className:"bg-blue-500",children:"Trial"});case"past_due":return e.jsx(Be,{variant:"destructive",children:"Past Due"});case"canceled":return e.jsx(Be,{variant:"secondary",children:"Canceled"});default:return e.jsx(Be,{variant:"outline",children:"No Subscription"})}};return n?e.jsxs(Ne,{children:[e.jsx(Ct,{children:e.jsxs(At,{className:"flex items-center gap-2",children:[e.jsx(Cv,{className:"h-5 w-5"}),"Subscription"]})}),e.jsx(Ie,{children:e.jsx("div",{className:"flex items-center justify-center py-4",children:e.jsx(kt,{className:"h-6 w-6 animate-spin text-muted-foreground"})})})]}):e.jsxs(Ne,{children:[e.jsxs(Ct,{children:[e.jsxs(At,{className:"flex items-center gap-2",children:[e.jsx(Cv,{className:"h-5 w-5"}),"Subscription"]}),e.jsx(Gn,{children:"Manage your subscription and billing"})]}),e.jsxs(Ie,{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:u()})]}),(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 membership is active and included with your account. To update or manage billing, 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($,{onClick:d,variant:"outline",disabled:a,children:[a?e.jsx(kt,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(kr,{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."})]})]})},Wsn=()=>{const{user:s}=vs(),t=Qn(),{toast:n}=Bi(),[r]=gc(),a=r.get("setup")==="true",i=r.get("reset")==="true",l=i&&r.get("activation")==="1",{isSupported:o,isSubscribed:c,isLoading:d,subscribe:u,unsubscribe:h}=p7t(),[m,f]=j.useState(!1),[g,x]=j.useState(""),[y,v]=j.useState(null),[b,w]=j.useState(!1),[S,C]=j.useState(!1),[E,I]=j.useState(""),[P,R]=j.useState({name:"",email:"",phone:"",title:"",bio:"",areas_served:"",years_experience:"",brokerage_name:"",instagram_url:"",facebook_url:"",linkedin_url:"",google_business_url:"",zillow_profile_url:"",realtor_profile_url:"",specialties:"",email_signature:"",use_email_signature:!1}),[D,O]=j.useState(!1),[U,W]=j.useState(!1),[V,G]=j.useState(!1),[Y,X]=j.useState(!1),[ae,ie]=j.useState(!1),[ne,te]=j.useState({newPassword:"",confirmPassword:""});j.useEffect(()=>{s&&J()},[s]),j.useEffect(()=>{i&&s&&setTimeout(()=>{var ke;(ke=document.getElementById("change-password-section"))==null||ke.scrollIntoView({behavior:"smooth",block:"center"})},500)},[i,s]);const J=async()=>{var ke,Ve,je,Ae;if(!(s!=null&&s.id)){console.log("No user ID available yet");return}try{console.log("Loading profile for user:",s.id);const{data:Ce,error:qe}=await q.from("profiles").select("name, email, phone, digest_opt_out, event_invite_opt_out, title, bio, areas_served, years_experience, brokerage_id, brokerage_name, brokerage_logo_url, instagram_url, facebook_url, linkedin_url, google_business_url, zillow_profile_url, realtor_profile_url, specialties, email_signature, use_email_signature, brokerages(name)").eq("id",s.id).maybeSingle();if(qe)throw console.error("Profile query error:",qe),qe;if(Ce){console.log("Profile loaded successfully:",Ce);const $e=((ke=Ce.brokerages)==null?void 0:ke.name)||"";O(!!Ce.brokerage_id),R({name:Ce.name||"",email:Ce.email||"",phone:Ce.phone||"",title:Ce.title||"",bio:Ce.bio||"",areas_served:Ce.areas_served||"",years_experience:((Ve=Ce.years_experience)==null?void 0:Ve.toString())||"",brokerage_name:Ce.brokerage_id?$e:Ce.brokerage_name||"",instagram_url:Ce.instagram_url||"",facebook_url:Ce.facebook_url||"",linkedin_url:Ce.linkedin_url||"",google_business_url:Ce.google_business_url||"",zillow_profile_url:Ce.zillow_profile_url||"",realtor_profile_url:Ce.realtor_profile_url||"",specialties:Ce.specialties||"",email_signature:Ce.email_signature||"",use_email_signature:Ce.use_email_signature||!1}),W(Ce.digest_opt_out||!1),X(Ce.event_invite_opt_out||!1),v(Ce.brokerage_logo_url||null)}else console.warn("No profile found for user"),R({name:((je=s.user_metadata)==null?void 0:je.name)||((Ae=s.email)==null?void 0:Ae.split("@")[0])||"",email:s.email||"",phone:"",title:"",bio:"",areas_served:"",years_experience:"",brokerage_name:"",instagram_url:"",facebook_url:"",linkedin_url:"",google_business_url:"",zillow_profile_url:"",realtor_profile_url:"",specialties:"",email_signature:"",use_email_signature:!1});const{data:ze}=await q.storage.from("avatars").list(`${s.id}`);if(ze&&ze.length>0){const{data:$e}=q.storage.from("avatars").getPublicUrl(`${s.id}/${ze[0].name}`);x($e.publicUrl)}}catch(Ce){console.error("Error loading profile:",Ce),n({title:"Error",description:Ce.message||"Failed to load profile",variant:"destructive"})}},ce=ke=>{var Ae;const Ve=(Ae=ke.target.files)==null?void 0:Ae[0];if(!Ve)return;const je=new FileReader;je.onloadend=()=>{I(je.result),C(!0)},je.readAsDataURL(Ve),ke.target.value=""},_e=async ke=>{if(s){w(!0);try{const{data:Ve}=await q.storage.from("avatars").list(`${s.id}`),je=(Ve??[]).filter(ct=>/^avatar[.-]/i.test(ct.name));je.length>0&&await q.storage.from("avatars").remove(je.map(ct=>`${s.id}/${ct.name}`));const Ce=`${s.id}/avatar.jpg`,{error:qe}=await q.storage.from("avatars").upload(Ce,ke,{upsert:!0,contentType:"image/jpeg"});if(qe)throw qe;const{data:ze}=q.storage.from("avatars").getPublicUrl(Ce),$e=ze.publicUrl;x(`${$e}?t=${Date.now()}`),await q.from("profiles").update({avatar_url:$e}).eq("id",s.id),n({title:"Success",description:"Profile photo updated successfully"})}catch(Ve){console.error("Error uploading avatar:",Ve),n({title:"Error",description:Ve.message||"Failed to upload photo",variant:"destructive"})}finally{w(!1)}}},he=async()=>{if(!P.name.trim()||!P.email.trim()){n({title:"Error",description:"Name and email are required",variant:"destructive"});return}f(!0);try{const ke=P.email.trim().toLowerCase(),Ve=((s==null?void 0:s.email)||"").toLowerCase(),je=!!ke&&ke!==Ve;if(je){const{data:Ce,error:qe}=await q.functions.invoke("update-own-email",{body:{newEmail:ke}}),ze=qe||(Ce==null?void 0:Ce.error);if(ze)throw new Error(typeof ze=="string"?ze:"Could not update your login email. Please try a different address.")}const{error:Ae}=await q.from("profiles").update({name:P.name.trim(),email:ke,phone:P.phone.trim()||null,title:P.title.trim()||null,bio:P.bio.trim()||null,areas_served:P.areas_served.trim()||null,years_experience:P.years_experience?parseInt(P.years_experience):null,...D?{}:{brokerage_name:P.brokerage_name.trim()||null},instagram_url:P.instagram_url.trim()||null,facebook_url:P.facebook_url.trim()||null,linkedin_url:P.linkedin_url.trim()||null,google_business_url:P.google_business_url.trim()||null,zillow_profile_url:P.zillow_profile_url.trim()||null,realtor_profile_url:P.realtor_profile_url.trim()||null,specialties:P.specialties.trim()||null,email_signature:P.email_signature||"",use_email_signature:P.use_email_signature}).eq("id",s==null?void 0:s.id);if(Ae)throw Ae;n({title:"Success",description:je?"Profile updated. Your login email is now "+ke:"Profile updated successfully"})}catch(ke){console.error("Error updating profile:",ke),n({title:"Error",description:ke.message||"Failed to update profile",variant:"destructive"})}finally{f(!1)}},ue=async()=>{if(!ne.newPassword){n({title:"Error",description:"Please enter a new password",variant:"destructive"});return}if(ne.newPassword.length<6){n({title:"Error",description:"Password must be at least 6 characters",variant:"destructive"});return}if(ne.newPassword!==ne.confirmPassword){n({title:"Error",description:"Passwords do not match",variant:"destructive"});return}f(!0);try{const{error:ke}=await q.auth.updateUser({password:ne.newPassword});if(ke)throw ke;n({title:"Success",description:"Password updated successfully"}),te({newPassword:"",confirmPassword:""}),a&&setTimeout(()=>t("/dashboard"),1e3)}catch(ke){console.error("Error updating password:",ke),n({title:"Error",description:ke.message||"Failed to update password",variant:"destructive"})}finally{f(!1)}},ve=[P.name,P.email,P.phone,P.title,P.bio,P.areas_served,P.brokerage_name,g],Ee=ve.filter(ke=>ke.trim()).length,Se=Math.round(Ee/ve.length*100),Le=P.name.split(" ").filter(Boolean).map(ke=>ke[0]).join("").toUpperCase().slice(0,2)||"U",Fe=ke=>{var Ve;(Ve=document.getElementById(ke))==null||Ve.scrollIntoView({behavior:"smooth",block:"start"})};return e.jsx(Vs,{title:a?"Complete Your Profile":l?"Welcome to LevelUp":i?"Reset Your Password":"Profile Settings",description:a?"Welcome! Please complete your profile setup":l?"Choose a password below and your account is active":i?"Please set a new password for your account":"Manage your account information and password",children:e.jsxs("div",{className:"profile-workspace mx-auto max-w-7xl",children:[e.jsxs("div",{className:"profile-shell",children:[e.jsx("aside",{className:"profile-summary",children:e.jsxs("div",{className:"profile-summary-inner",children:[e.jsxs("div",{className:"relative",children:[e.jsxs(Oa,{className:"profile-avatar",children:[e.jsx(Li,{src:g}),e.jsx(za,{children:Le})]}),e.jsx("input",{type:"file",id:"avatar-upload",accept:"image/*",className:"hidden",onChange:ce,disabled:b}),e.jsx($,{type:"button",size:"icon",className:"profile-avatar-button",onClick:()=>{var ke;return(ke=document.getElementById("avatar-upload"))==null?void 0:ke.click()},disabled:b,"aria-label":"Change profile photo",children:b?e.jsx(kt,{className:"h-4 w-4 animate-spin"}):e.jsx(Cx,{className:"h-4 w-4"})})]}),e.jsxs("div",{className:"mt-6 text-center",children:[e.jsx("h2",{className:"profile-name",children:P.name||"Your profile"}),e.jsx("p",{className:"profile-role",children:P.title||"Real estate professional"}),P.brokerage_name&&e.jsx("p",{className:"profile-brokerage",children:P.brokerage_name})]}),e.jsxs("div",{className:"profile-completion",children:[e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{children:"Profile strength"}),e.jsxs("strong",{children:[Se,"%"]})]}),e.jsx("div",{className:"profile-progress","aria-label":`Profile ${Se}% complete`,children:e.jsx("span",{style:{width:`${Se}%`}})}),e.jsx("p",{children:Se===100?"Your professional profile is complete.":"Complete your details to strengthen your presence across LevelUp."})]}),e.jsxs("nav",{className:"profile-section-nav","aria-label":"Profile sections",children:[e.jsxs($,{variant:"ghost",onClick:()=>Fe("profile-details"),children:[e.jsx(cP,{className:"h-4 w-4"})," Profile details"]}),e.jsxs($,{variant:"ghost",onClick:()=>Fe("profile-brand"),children:[e.jsx(Yc,{className:"h-4 w-4"})," Brand & signature"]}),e.jsxs($,{variant:"ghost",onClick:()=>Fe("change-password-section"),children:[e.jsx(bm,{className:"h-4 w-4"})," Account security"]}),e.jsxs($,{variant:"ghost",onClick:()=>Fe("profile-notifications"),children:[e.jsx(QS,{className:"h-4 w-4"})," Notifications"]}),e.jsxs($,{variant:"ghost",onClick:()=>Fe("profile-billing"),children:[e.jsx(Jq,{className:"h-4 w-4"})," Billing"]})]}),e.jsxs($,{className:"profile-save",onClick:he,disabled:m,children:[m?e.jsx(kt,{className:"h-4 w-4 animate-spin"}):e.jsx(tl,{className:"h-4 w-4"}),"Save profile"]})]})}),e.jsxs("main",{className:"profile-content",children:[e.jsxs("header",{className:"profile-page-heading",children:[e.jsx("p",{className:"profile-eyebrow",children:"Your professional presence"}),e.jsx("h1",{children:a?"Complete your profile":l?"Welcome to LevelUp":i?"Reset your password":"Personal details"}),e.jsx("p",{children:a?"Add the details clients and collaborators should know about you.":"Keep your identity, brand, and account preferences current in one place."})]}),e.jsxs("div",{className:"space-y-6",children:[e.jsxs(Ne,{id:"profile-details",children:[e.jsxs(Ct,{children:[e.jsx(At,{children:"Personal Information"}),e.jsx(Gn,{children:"Update your profile details"})]}),e.jsxs(Ie,{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"name",children:"Name"}),e.jsx(pe,{id:"name",value:P.name,onChange:ke=>R({...P,name:ke.target.value}),maxLength:100})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"email",children:"Email"}),e.jsx(pe,{id:"email",type:"email",value:P.email,onChange:ke=>R({...P,email:ke.target.value}),maxLength:255}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Changing this also updates the email you use to sign in."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"phone",children:"Phone Number"}),e.jsx(pe,{id:"phone",type:"tel",value:P.phone,onChange:ke=>R({...P,phone:ke.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(ee,{htmlFor:"title",children:"Job Title"}),e.jsx(pe,{id:"title",value:P.title,onChange:ke=>R({...P,title:ke.target.value}),placeholder:"e.g., Broker Associate, Team Lead",maxLength:100})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"bio",children:"Bio"}),e.jsx(Rs,{id:"bio",value:P.bio,onChange:ke=>R({...P,bio:ke.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(ee,{htmlFor:"areas_served",children:"Areas Served"}),e.jsx(pe,{id:"areas_served",value:P.areas_served,onChange:ke=>R({...P,areas_served:ke.target.value}),placeholder:"e.g., Downtown, Suburbs"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"years_experience",children:"Years Experience"}),e.jsx(pe,{id:"years_experience",type:"number",min:"0",value:P.years_experience,onChange:ke=>R({...P,years_experience:ke.target.value}),placeholder:"e.g., 5"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ee,{htmlFor:"brokerage_name",children:["Brokerage ",D&&e.jsx("span",{className:"text-xs text-muted-foreground",children:"(managed)"})]}),e.jsx(pe,{id:"brokerage_name",value:P.brokerage_name,onChange:ke=>R({...P,brokerage_name:ke.target.value}),placeholder:"e.g., Keller Williams Realty",disabled:D,maxLength:150}),e.jsx("p",{className:"text-xs text-muted-foreground",children:D?"Your brokerage is managed by your office and can't be changed here.":"Used as your brokerage name across ReelFlow, branding, and email signatures."})]}),s&&e.jsx(Hsn,{userId:s.id,value:y,onChange:v,description:"PNG, JPG, SVG or WebP up to 5MB. Used on your agent website, marketing and email signatures."}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Social Links"}),e.jsxs("div",{className:"grid grid-cols-1 gap-3",children:[e.jsx(pe,{value:P.linkedin_url,onChange:ke=>R({...P,linkedin_url:ke.target.value}),placeholder:"LinkedIn URL"}),e.jsx(pe,{value:P.instagram_url,onChange:ke=>R({...P,instagram_url:ke.target.value}),placeholder:"Instagram URL"}),e.jsx(pe,{value:P.facebook_url,onChange:ke=>R({...P,facebook_url:ke.target.value}),placeholder:"Facebook URL"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"AI Search & Verified Profiles"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Adding these helps ChatGPT, Perplexity, Google and other AI assistants confirm who you are and recommend you for local searches."}),e.jsxs("div",{className:"grid grid-cols-1 gap-3",children:[e.jsx(pe,{value:P.google_business_url,onChange:ke=>R({...P,google_business_url:ke.target.value}),placeholder:"Google Business Profile URL"}),e.jsx(pe,{value:P.zillow_profile_url,onChange:ke=>R({...P,zillow_profile_url:ke.target.value}),placeholder:"Zillow agent profile URL"}),e.jsx(pe,{value:P.realtor_profile_url,onChange:ke=>R({...P,realtor_profile_url:ke.target.value}),placeholder:"Realtor.com profile URL"}),e.jsx(pe,{value:P.specialties,onChange:ke=>R({...P,specialties:ke.target.value}),placeholder:"Specialties (e.g. Waterfront homes, Acreage & farms, First-time buyers)"})]})]}),e.jsxs($,{onClick:he,disabled:m,className:"profile-inline-save",children:[e.jsx(tl,{className:"mr-2 h-4 w-4"}),"Save Changes"]})]})]}),e.jsxs(Ne,{id:"profile-brand",children:[e.jsxs(Ct,{children:[e.jsxs(At,{className:"flex items-center gap-2",children:[e.jsx(wf,{className:"h-5 w-5"}),"Email Signature"]}),e.jsx(Gn,{children:"Add a signature that will be appended to emails sent via Gmail"})]}),e.jsxs(Ie,{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:P.use_email_signature?"Your signature will be added to every email sent via Gmail":"Signature is currently disabled"})]}),e.jsx(Sn,{checked:P.use_email_signature,onCheckedChange:ke=>R({...P,use_email_signature:ke})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Signature"}),e.jsx(Ek,{content:P.email_signature,onChange:ke=>R({...P,email_signature:ke}),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($,{onClick:he,disabled:m,children:[e.jsx(tl,{className:"mr-2 h-4 w-4"}),"Save Signature"]})]})]}),e.jsx("div",{className:"profile-embedded-section",children:e.jsx(Fsn,{})}),e.jsxs(Ne,{id:"change-password-section",children:[e.jsxs(Ct,{children:[e.jsx(At,{children:a||l?"Set Your Password":"Change Password"}),e.jsx(Gn,{children:a||l?"Create a secure password for your account":"Update your password to keep your account secure"})]}),e.jsxs(Ie,{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"newPassword",children:"New Password"}),e.jsx(pe,{id:"newPassword",type:"password",value:ne.newPassword,onChange:ke=>te({...ne,newPassword:ke.target.value}),placeholder:"Min 6 characters"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"confirmPassword",children:"Confirm Password"}),e.jsx(pe,{id:"confirmPassword",type:"password",value:ne.confirmPassword,onChange:ke=>te({...ne,confirmPassword:ke.target.value}),placeholder:"Re-enter your new password"})]}),e.jsxs($,{onClick:ue,disabled:m,children:[e.jsx(tl,{className:"mr-2 h-4 w-4"}),a?"Complete Setup":"Update Password"]}),a&&e.jsx($,{variant:"outline",onClick:()=>t("/dashboard"),className:"ml-2",children:"Skip for Now"})]})]}),e.jsxs(Ne,{id:"profile-notifications",children:[e.jsxs(Ct,{children:[e.jsxs(At,{className:"flex items-center gap-2",children:[c?e.jsx(qy,{className:"h-5 w-5"}):e.jsx(XS,{className:"h-5 w-5"}),"Push Notifications"]}),e.jsx(Gn,{children:"Receive browser notifications when new content is added"})]}),e.jsx(Ie,{children:o?e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:c?"Notifications enabled":"Notifications disabled"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:c?"You'll receive notifications about new templates, videos, and events":"Enable to get notified about new content"})]}),e.jsx(Sn,{checked:c,onCheckedChange:ke=>{ke?u():h()},disabled:d})]}):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.jsx("div",{className:"profile-embedded-section",children:e.jsx(Tsn,{})}),e.jsxs(Ne,{children:[e.jsxs(Ct,{children:[e.jsxs(At,{className:"flex items-center gap-2",children:[U?e.jsx(XI,{className:"h-5 w-5"}):e.jsx(mn,{className:"h-5 w-5"}),"Email Preferences"]}),e.jsx(Gn,{children:"Manage your email subscription settings"})]}),e.jsxs(Ie,{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:U?"You won't receive weekly digest emails":"Receive a weekly summary of new content, events, and your progress"})]}),e.jsx(Sn,{checked:!U,onCheckedChange:async ke=>{G(!0);try{const{error:Ve}=await q.from("profiles").update({digest_opt_out:!ke}).eq("id",s==null?void 0:s.id);if(Ve)throw Ve;W(!ke),n({title:ke?"Subscribed":"Unsubscribed",description:ke?"You will now receive weekly digest emails":"You will no longer receive weekly digest emails"})}catch(Ve){n({title:"Error",description:Ve.message||"Failed to update preference",variant:"destructive"})}finally{G(!1)}},disabled:V})]}),e.jsxs("div",{className:"flex items-center justify-between pt-4 mt-4 border-t",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:"Event Invite Emails"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:Y?"You won't receive event invite emails (weekly digest is unaffected)":"Get invited to LevelUp live trainings and special events"})]}),e.jsx(Sn,{checked:!Y,onCheckedChange:async ke=>{ie(!0);try{const{error:Ve}=await q.from("profiles").update({event_invite_opt_out:!ke}).eq("id",s==null?void 0:s.id);if(Ve)throw Ve;X(!ke),n({title:ke?"Subscribed":"Unsubscribed",description:ke?"You will now receive event invite emails":"You will no longer receive event invite emails"})}catch(Ve){n({title:"Error",description:Ve.message||"Failed to update preference",variant:"destructive"})}finally{ie(!1)}},disabled:ae})]})]})]}),e.jsx("div",{className:"profile-embedded-section",children:e.jsx(kKs,{})}),e.jsx("div",{id:"profile-billing",className:"profile-embedded-section",children:e.jsx(Gsn,{})}),e.jsx("div",{className:"profile-embedded-section",children:e.jsx(qsn,{})})]})]})]}),e.jsx(rrt,{open:S,onClose:()=>C(!1),imageSrc:E,onCropComplete:_e,aspectRatio:1})]})})};var Ksn=Object.defineProperty,Ysn=(s,t)=>Ksn(s,"name",{value:t,configurable:!0}),Zsn=j.forwardRef(Ysn(function(t,n){const{ratio:r=1/1,style:a,...i}=t;return e.jsx("div",{style:{position:"relative",width:"100%",paddingBottom:`${100/r}%`},"data-radix-aspect-ratio-wrapper":"",children:e.jsx(Ei.div,{...i,ref:n,style:{...a,position:"absolute",top:0,right:0,bottom:0,left:0}})})},"AspectRatio")),Xsn=Zsn;const Qsn=Xsn;function Jsn(){const{user:s}=vs(),t=Vt(),[n,r]=j.useState(!1),[a,i]=j.useState(!1),{data:l,isLoading:o}=tt({queryKey:["calendar-token",s==null?void 0:s.id],queryFn:async()=>{const{data:g,error:x}=await q.from("profiles").select("calendar_token").eq("id",s==null?void 0:s.id).single();if(x)throw x;return g},enabled:!!s&&a}),c=ft({mutationFn:async()=>{const g=new Uint8Array(12);crypto.getRandomValues(g);const x=btoa(String.fromCharCode(...g)).replace(/\+/g,"x").replace(/\//g,"y").replace(/=/g,"").substring(0,16),{error:y}=await q.from("profiles").update({calendar_token:x}).eq("id",s==null?void 0:s.id);if(y)throw y;return x},onSuccess:()=>{t.invalidateQueries({queryKey:["calendar-token",s==null?void 0:s.id]}),re.success("Calendar subscription URL generated!")},onError:g=>{re.error("Failed to generate calendar URL: "+g.message)}}),d=l!=null&&l.calendar_token?`https://dashboard.relevelup.com/api/calendar/${l.calendar_token}.ics`:null,u=async()=>{d&&(await navigator.clipboard.writeText(d),r(!0),re.success("Calendar URL copied to clipboard!"),setTimeout(()=>r(!1),2e3))},h=()=>{d&&(window.location.href=d.replace("https://","webcal://"))},m=()=>{if(d){const g=d.replace("https://","webcal://"),x=`https://calendar.google.com/calendar/r?cid=${encodeURIComponent(g)}`;window.open(x,"_blank")}},f=()=>{if(d){const g=`https://outlook.live.com/calendar/0/addfromweb?url=${encodeURIComponent(d)}&name=Level%20Up%20Events`;window.open(g,"_blank")}};return e.jsxs(zs,{open:a,onOpenChange:i,children:[e.jsx(jl,{asChild:!0,children:e.jsxs($,{variant:"outline",className:"gap-2",children:[e.jsx(Ta,{className:"h-4 w-4"}),"Subscribe to Calendar"]})}),e.jsxs(Os,{className:"sm:max-w-md",children:[e.jsxs(Us,{children:[e.jsxs(Bs,{className:"flex items-center gap-2",children:[e.jsx(Ta,{className:"h-5 w-5 text-primary"}),"Subscribe to Events Calendar"]}),e.jsx(Ir,{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(kt,{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(pe,{value:d,readOnly:!0,className:"text-xs font-mono"}),e.jsx($,{variant:"outline",size:"icon",onClick:u,children:n?e.jsx(la,{className:"h-4 w-4 text-green-500"}):e.jsx(Ha,{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($,{variant:"outline",className:"w-full justify-start gap-2",onClick:h,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(kr,{className:"h-3 w-3 ml-auto opacity-50"})]}),e.jsxs($,{variant:"outline",className:"w-full justify-start gap-2",onClick:m,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(kr,{className:"h-3 w-3 ml-auto opacity-50"})]}),e.jsxs($,{variant:"outline",className:"w-full justify-start gap-2",onClick:f,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(kr,{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($,{onClick:()=>c.mutate(),disabled:c.isPending,className:"w-full",children:c.isPending?e.jsxs(e.Fragment,{children:[e.jsx(kt,{className:"h-4 w-4 mr-2 animate-spin"}),"Generating..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Ta,{className:"h-4 w-4 mr-2"}),"Generate Calendar URL"]})})]})})]})]})}const enn={first_timer:Ja,regular:PE,dedicated:Rm,veteran:Kl,streak_master:nh,century:Kl},tnn={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 m_t(s){return s===1?e.jsx(Kl,{className:"h-5 w-5 text-yellow-500"}):s===2?e.jsx(PE,{className:"h-5 w-5 text-gray-400"}):s===3?e.jsx(Rm,{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 SHt({showUserStats:s=!0,compact:t=!1,brokerageId:n,title:r="Event Leaderboard"}){const{user:a}=vs(),{data:i,isLoading:l}=eqt(t?5:10,n),{data:o}=tqt(a==null?void 0:a.id),{data:c}=nqt(a==null?void 0:a.id),{data:d}=sqt(a==null?void 0:a.id);return l?e.jsxs(Ne,{children:[e.jsx(Ct,{children:e.jsxs(At,{className:"flex items-center gap-2",children:[e.jsx(Kl,{className:"h-5 w-5 text-yellow-500"}),r]})}),e.jsx(Ie,{children:e.jsx("div",{className:"space-y-3",children:[...Array(5)].map((u,h)=>e.jsx(yn,{className:"h-12 w-full"},h))})})]}):e.jsxs(Ne,{children:[e.jsx(Ct,{className:"pb-3",children:e.jsxs(At,{className:"flex items-center gap-2",children:[e.jsx(Kl,{className:"h-5 w-5 text-yellow-500"}),r]})}),e.jsxs(Ie,{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(Be,{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(nh,{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(u=>{const h=enn[u.badge_type]||Ja;return e.jsxs(Be,{variant:"outline",className:`text-xs ${tnn[u.badge_type]||""}`,title:u.badge_description||"",children:[e.jsx(h,{className:"h-3 w-3 mr-1"}),u.badge_name]},u.id)}),d.length>4&&e.jsxs(Be,{variant:"outline",className:"text-xs",children:["+",d.length-4," more"]})]})]}),e.jsxs(ha,{defaultValue:"points",className:"w-full",children:[e.jsxs(ma,{className:"w-full mb-3",children:[e.jsx(Zt,{value:"points",className:"flex-1",children:"By Points"}),e.jsx(Zt,{value:"events",className:"flex-1",children:"By Events"})]}),e.jsx(Xt,{value:"points",className:"mt-0",children:e.jsxs("div",{className:"space-y-2",children:[i==null?void 0:i.map((u,h)=>{var m,f,g;return e.jsxs("div",{className:`flex items-center gap-3 p-2 rounded-lg ${u.user_id===(a==null?void 0:a.id)?"bg-primary/5 border border-primary/10":""} ${h===0?"bg-yellow-500/5":""}`,children:[e.jsx("div",{className:"w-6 flex justify-center",children:m_t(h+1)}),e.jsx(Oa,{className:"h-8 w-8",children:e.jsx(za,{className:"text-xs",children:((f=(m=u.profile)==null?void 0:m.name)==null?void 0:f.charAt(0))||"?"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"font-medium text-sm truncate",children:[((g=u.profile)==null?void 0:g.name)||"Unknown",u.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:[u.total_events_attended," events"]})]}),e.jsxs("div",{className:"text-right",children:[e.jsx("div",{className:"font-bold text-primary",children:u.total_points}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"pts"})]})]},u.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(Xt,{value:"events",className:"mt-0",children:e.jsx("div",{className:"space-y-2",children:[...i||[]].sort((u,h)=>h.total_events_attended-u.total_events_attended).map((u,h)=>{var m,f,g;return e.jsxs("div",{className:`flex items-center gap-3 p-2 rounded-lg ${u.user_id===(a==null?void 0:a.id)?"bg-primary/5 border border-primary/10":""} ${h===0?"bg-yellow-500/5":""}`,children:[e.jsx("div",{className:"w-6 flex justify-center",children:m_t(h+1)}),e.jsx(Oa,{className:"h-8 w-8",children:e.jsx(za,{className:"text-xs",children:((f=(m=u.profile)==null?void 0:m.name)==null?void 0:f.charAt(0))||"?"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"font-medium text-sm truncate",children:[((g=u.profile)==null?void 0:g.name)||"Unknown",u.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:[u.total_points," points"]})]}),e.jsxs("div",{className:"text-right",children:[e.jsx("div",{className:"font-bold",children:u.total_events_attended}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"events"})]})]},u.user_id)})})})]})]})]})}function snn(){const s=Qn(),{user:t,isAdmin:n}=vs(),r=Vt(),[a,i]=j.useState(!1),[l,o]=j.useState(!1),{data:c,isLoading:d}=tt({queryKey:["public-events"],queryFn:async()=>{const{data:E,error:I}=await q.from("events").select("*").order("event_date",{ascending:!0});if(I)throw I;return E}}),{data:u}=tt({queryKey:["my-registrations"],queryFn:async()=>{if(!t)return[];const{data:E,error:I}=await q.from("event_registrations").select("event_id, zoom_join_url").eq("user_id",t.id);if(I)throw I;return E},enabled:!!t}),{data:h}=tt({queryKey:["event-registration-counts"],queryFn:async()=>{let E=[],I=0;const P=1e3;for(;;){const{data:D,error:O}=await q.from("event_registrations").select("event_id").range(I,I+P-1);if(O)throw O;if(!D||D.length===0||(E=E.concat(D),D.length{R[D.event_id]=(R[D.event_id]||0)+1}),R}}),m=ft({mutationFn:async E=>{await q.auth.refreshSession();const{data:I,error:P}=await q.functions.invoke("zoom-register",{body:{event_id:E}});if(P)throw P;if(I!=null&&I.error)throw new Error(I.error);return I},onSuccess:E=>{r.invalidateQueries({queryKey:["my-registrations"]}),r.invalidateQueries({queryKey:["event-registration-counts"]}),E!=null&&E.join_url?re.success("Successfully registered! You'll receive a Zoom confirmation email."):re.success("Successfully registered for the event!")},onError:E=>{re.error("Failed to register: "+E.message)}}),f=ft({mutationFn:async E=>{const{data:I,error:P}=await q.functions.invoke("zoom-unregister",{body:{event_id:E}});if(P)throw P;if(I!=null&&I.error)throw new Error(I.error);return I},onSuccess:()=>{r.invalidateQueries({queryKey:["my-registrations"]}),r.invalidateQueries({queryKey:["event-registration-counts"]}),re.success("Registration cancelled and removed from Zoom")},onError:E=>{re.error("Failed to cancel: "+E.message)}}),g=E=>u==null?void 0:u.some(I=>I.event_id===E),x=E=>{const I=u==null?void 0:u.find(P=>P.event_id===E);return I==null?void 0:I.zoom_join_url},y=E=>E.capacity?((h==null?void 0:h[E.id])||0)>=E.capacity:!1,v=(c==null?void 0:c.filter(E=>m8(E.event_date)!=="ended"))||[],b=(c==null?void 0:c.filter(E=>m8(E.event_date)==="ended"))||[],w=v.filter(E=>m8(E.event_date)==="live").length,S=v.filter(E=>g(E.id)).length,C=l?b:b.slice(0,6);return e.jsx(Vs,{title:"Events",children:e.jsxs("div",{className:"mx-auto max-w-6xl space-y-6",children:[e.jsx("section",{className:"hub-ink relative overflow-hidden rounded-2xl p-5 sm:p-6",children:e.jsxs("div",{className:"relative flex flex-col gap-5",children:[e.jsxs("div",{className:"flex flex-col gap-4 lg:flex-row lg:items-start lg:justify-between",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-xs uppercase tracking-wider hub-ink-muted",children:"LevelUp Live"}),e.jsx("h1",{className:"mt-1 text-2xl font-bold sm:text-3xl",children:"Events"}),e.jsx("p",{className:"mt-1 text-sm hub-ink-muted",children:w>0?"An event is live right now — jump in.":v.length>0?`Next up: ${v[0].title}`:"No upcoming events scheduled — replays are below."})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(Jsn,{}),n&&e.jsxs("button",{onClick:()=>s("/admin/events"),className:"hub-glass inline-flex items-center gap-2 rounded-full px-4 py-2 text-sm font-medium transition-colors",children:[e.jsx(Sd,{className:"h-4 w-4",style:{color:"hsl(var(--hub-glow))"}}),"Manage Events"]})]})]}),e.jsx("div",{className:"grid grid-cols-2 gap-2 sm:grid-cols-4",children:[{label:"Upcoming",value:v.length,icon:Ta},{label:"You're registered",value:S,icon:la},{label:"Live now",value:w,icon:Nb},{label:"Past events",value:b.length,icon:Lw}].map(E=>e.jsxs("div",{className:"hub-glass rounded-xl px-3 py-2.5",children:[e.jsx("span",{className:"text-xl font-bold",children:E.value}),e.jsxs("p",{className:"mt-0.5 flex items-center gap-1 text-[11px] hub-ink-muted",children:[e.jsx(E.icon,{className:"h-3 w-3"}),E.label]})]},E.label))})]})}),e.jsxs("div",{className:`grid grid-cols-1 gap-6 ${n?"lg:grid-cols-3":""}`,children:[e.jsxs("div",{className:`space-y-6 ${n?"lg:col-span-2":""}`,children:[d?e.jsx("div",{className:"grid gap-6 md:grid-cols-2",children:[0,1].map(E=>e.jsx("div",{className:"h-72 animate-pulse rounded-2xl border bg-muted/40"},E))}):v.length===0?e.jsx(Ne,{className:"rounded-2xl border-dashed py-12 text-center",children:e.jsxs(Ie,{className:"space-y-2",children:[e.jsx(Ta,{className:"mx-auto h-10 w-10 text-muted-foreground"}),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:v.map(E=>{const I=m8(E.event_date),P=mnt(E.event_date),R=I==="live",D=I==="starting_soon";return e.jsxs(Ne,{className:`group flex flex-col overflow-hidden rounded-2xl cursor-pointer transition-all hover:shadow-lg ${R?"border-red-500 ring-2 ring-red-500/20":D?"border-amber-500 ring-2 ring-amber-500/20":"hover:border-primary/50"}`,onClick:()=>s(`/events/${E.id}`),children:[P&&e.jsxs("div",{className:`${R?"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"})]}),R?e.jsxs(e.Fragment,{children:[e.jsx(Nb,{className:"h-3.5 w-3.5"}),"LIVE NOW"]}):e.jsxs(e.Fragment,{children:[e.jsx(da,{className:"h-3.5 w-3.5"}),"STARTING SOON"]})]}),E.image_url&&e.jsxs(Qsn,{ratio:16/9,className:"overflow-hidden relative bg-neutral-900",children:[e.jsx("img",{src:E.image_url,alt:"","aria-hidden":"true",className:"absolute inset-0 w-full h-full object-cover blur-2xl scale-110 opacity-60"}),e.jsx("img",{src:E.image_url,alt:E.title,className:"relative w-full h-full object-contain transition-transform group-hover:scale-[1.03]"})]}),e.jsxs(Ct,{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("span",{className:"inline-flex items-center gap-1 rounded-full bg-primary/10 px-2.5 py-1 text-[11px] font-semibold text-primary",children:[e.jsx(Ta,{className:"h-3 w-3"}),new Intl.DateTimeFormat("en-US",{month:"short",day:"numeric",timeZone:"America/New_York"}).format(new Date(E.event_date))]}),g(E.id)&&e.jsxs("span",{className:"inline-flex items-center gap-1 rounded-full bg-emerald-500/10 px-2.5 py-1 text-[11px] font-semibold text-emerald-600 dark:text-emerald-400",children:[e.jsx(la,{className:"h-3 w-3"}),"Registered"]})]}),e.jsx(At,{className:"line-clamp-2 pt-1",children:E.title}),E.description&&e.jsx(Gn,{className:"line-clamp-2",children:E.description.replace(/<[^>]*>/g,"")})]}),e.jsxs(Ie,{className:"flex-1 space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(Ta,{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(E.event_date))]}),e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(da,{className:"h-4 w-4"}),fse(new Date(E.event_date))]}),e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(Zn,{className:"h-4 w-4"}),(h==null?void 0:h[E.id])||0," registered",E.capacity&&` / ${E.capacity} spots`]})]}),e.jsx(wEe,{className:"flex gap-2",onClick:O=>O.stopPropagation(),children:g(E.id)?e.jsxs(e.Fragment,{children:[e.jsxs($,{variant:"outline",className:"flex-1",onClick:()=>f.mutate(E.id),disabled:f.isPending,children:[e.jsx(gr,{className:"h-4 w-4 mr-2"}),"Cancel"]}),e.jsxs($,{className:"flex-1",onClick:()=>window.open(x(E.id)||E.zoom_link,"_blank"),children:[e.jsx(kr,{className:"h-4 w-4 mr-2"}),"Join Zoom"]})]}):e.jsx($,{className:"w-full",onClick:()=>m.mutate(E.id),disabled:m.isPending||y(E),children:y(E)?"Event Full":e.jsxs(e.Fragment,{children:[e.jsx(la,{className:"h-4 w-4 mr-2"}),"Register"]})})})]},E.id)})}),b.length>0&&e.jsxs(Ne,{className:"rounded-2xl",children:[e.jsxs("button",{type:"button",onClick:()=>i(E=>!E),className:"flex w-full items-center justify-between gap-3 px-5 py-4 text-left",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"flex h-9 w-9 items-center justify-center rounded-xl bg-muted",children:e.jsx(Lw,{className:"h-4 w-4 text-muted-foreground"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-semibold",children:"Past Events"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[b.length," previous ",b.length===1?"session":"sessions"," — open one to watch the replay"]})]})]}),e.jsx(Tl,{className:`h-4 w-4 text-muted-foreground transition-transform ${a?"rotate-180":""}`})]}),a&&e.jsxs("div",{className:"border-t",children:[e.jsx("ul",{className:"divide-y",children:C.map(E=>e.jsx("li",{children:e.jsxs("button",{type:"button",onClick:()=>s(`/events/${E.id}`),className:"flex w-full items-center gap-3 px-5 py-3 text-left transition-colors hover:bg-muted/50",children:[e.jsxs("div",{className:"flex w-12 shrink-0 flex-col items-center rounded-lg border bg-muted/40 py-1",children:[e.jsx("span",{className:"text-[10px] font-semibold uppercase text-muted-foreground",children:new Intl.DateTimeFormat("en-US",{month:"short",timeZone:"America/New_York"}).format(new Date(E.event_date))}),e.jsx("span",{className:"text-sm font-bold leading-none",children:new Intl.DateTimeFormat("en-US",{day:"numeric",timeZone:"America/New_York"}).format(new Date(E.event_date))})]}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"truncate text-sm font-medium",children:E.title}),e.jsx("p",{className:"text-xs text-muted-foreground",children:new Intl.DateTimeFormat("en-US",{year:"numeric",month:"long",day:"numeric",timeZone:"America/New_York"}).format(new Date(E.event_date))})]}),e.jsx(tf,{className:"h-4 w-4 shrink-0 text-muted-foreground"})]})},E.id))}),b.length>6&&e.jsx("div",{className:"border-t px-5 py-3",children:e.jsx($,{variant:"ghost",size:"sm",className:"w-full",onClick:()=>o(E=>!E),children:l?"Show less":`Show all ${b.length}`})})]})]})]}),n&&e.jsx("div",{className:"lg:col-span-1",children:e.jsx(SHt,{showUserStats:!0})})]})]})})}const TBe=[{value:"all",label:"All Roles",icon:Zn},{value:"newest",label:"Newest Members",icon:da},{value:"brokerage_manager",label:"Brokerage Managers",icon:dee},{value:"admin",label:"Admins",icon:Mf}];function nnn({open:s,onOpenChange:t,resourceType:n,resourceId:r,resourceTitle:a}){var Le,Fe;const{user:i,isAdmin:l,isBrokerageManager:o}=vs(),[c,d]=j.useState([]),[u,h]=j.useState([]),[m,f]=j.useState([]),[g,x]=j.useState([]),[y,v]=j.useState(""),[b,w]=j.useState(""),[S,C]=j.useState(""),[E,I]=j.useState(!1),[P,R]=j.useState(!1),[D,O]=j.useState("agents"),[U,W]=j.useState("all"),[V,G]=j.useState({}),Y=l||o;j.useEffect(()=>{s&&i&&(l?X():ae())},[s,i,l]),j.useEffect(()=>{s||(f([]),x([]),v(""),w(""),C(""),O("agents"),W("all"))},[s]);const X=async()=>{if(i){I(!0);try{const{data:ke,error:Ve}=await q.from("brokerages").select("id, name").order("name");if(Ve)throw Ve;const je=1e3,Ae={};let Ce=0,qe=!0;for(;qe;){const{data:ct,error:Xe}=await q.from("profiles").select("brokerage_id").range(Ce*je,(Ce+1)*je-1);if(Xe)throw Xe;ct==null||ct.forEach(it=>{it.brokerage_id&&(Ae[it.brokerage_id]=(Ae[it.brokerage_id]||0)+1)}),qe=(ct==null?void 0:ct.length)===je,Ce++}h((ke==null?void 0:ke.map(ct=>({...ct,agent_count:Ae[ct.id]||0})))||[]);const ze=[];for(Ce=0,qe=!0;qe;){const{data:ct,error:Xe}=await q.from("profiles").select("id, name, email, brokerage_id, created_at, brokerages(name)").neq("id",i.id).order("name").range(Ce*je,(Ce+1)*je-1);if(Xe)throw Xe;ct&&ze.push(...ct),qe=(ct==null?void 0:ct.length)===je,Ce++}const $e={};for(Ce=0,qe=!0;qe;){const{data:ct,error:Xe}=await q.from("user_roles").select("user_id, role").range(Ce*je,(Ce+1)*je-1);if(Xe)throw Xe;ct==null||ct.forEach(it=>{$e[it.user_id]||($e[it.user_id]=[]),$e[it.user_id].push(it.role)}),qe=(ct==null?void 0:ct.length)===je,Ce++}G($e),d(ze.map(ct=>{var Xe;return{id:ct.id,name:ct.name,email:ct.email,brokerage_name:((Xe=ct.brokerages)==null?void 0:Xe.name)||"No Brokerage",roles:$e[ct.id]||[],created_at:ct.created_at}}))}catch(ke){console.error("Error loading data:",ke),re.error("Failed to load agents and brokerages")}finally{I(!1)}}},ae=async()=>{if(i){I(!0);try{const{data:ke}=await q.from("profiles").select("brokerage_id").eq("id",i.id).single();if(!(ke!=null&&ke.brokerage_id)){re.error("You must be part of a brokerage to share resources"),t(!1);return}const{data:Ve,error:je}=await q.from("profiles").select("id, name, email").eq("brokerage_id",ke.brokerage_id).neq("id",i.id).order("name");if(je)throw je;d(Ve||[])}catch(ke){console.error("Error loading agents:",ke),re.error("Failed to load agents")}finally{I(!1)}}},ie=c.filter(ke=>{var je;const Ve=ke.name.toLowerCase().includes(y.toLowerCase())||ke.email.toLowerCase().includes(y.toLowerCase())||((je=ke.brokerage_name)==null?void 0:je.toLowerCase().includes(y.toLowerCase()));if(l&&U!=="all"&&U!=="newest"){const Ae=V[ke.id]||[];return Ve&&Ae.includes(U)}return Ve}).sort((ke,Ve)=>U==="newest"?(Ve.created_at||"").localeCompare(ke.created_at||""):0),ne=u.filter(ke=>ke.name.toLowerCase().includes(b.toLowerCase())),te=()=>{m.length===ie.length?f([]):f(ie.map(ke=>ke.id))},J=()=>{g.length===ne.length?x([]):x(ne.map(ke=>ke.id))},ce=ke=>{if(!Y){f([ke]);return}f(Ve=>Ve.includes(ke)?Ve.filter(je=>je!==ke):[...Ve,ke])},_e=ke=>{x(Ve=>Ve.includes(ke)?Ve.filter(je=>je!==ke):[...Ve,ke])},he=async()=>{if(!(m.length>0||g.length>0)){re.error("Please select at least one agent or brokerage to share with");return}R(!0);try{const{data:Ve,error:je}=await q.functions.invoke("send-share-notification",{body:{recipientIds:m,brokerageIds:g,resourceType:n,resourceId:r,resourceTitle:a,message:S.trim()||void 0}});if(je)throw je;const Ae=(Ve==null?void 0:Ve.sharesCreated)||m.length;re.success(`Shared with ${Ae} agent${Ae!==1?"s":""}`),t(!1)}catch(Ve){console.error("Error sharing resource:",Ve),re.error("Failed to share resource")}finally{R(!1)}},ue=ke=>ke.split(" ").map(Ve=>Ve[0]).join("").toUpperCase().slice(0,2),ve=ke=>{const Ve=V[ke]||[];return Ve.includes("admin")?e.jsx(Be,{variant:"secondary",className:"text-[10px] px-1.5 py-0",children:"Admin"}):Ve.includes("brokerage_manager")?e.jsx(Be,{variant:"outline",className:"text-[10px] px-1.5 py-0",children:"Manager"}):null},Ee=m.length+g.length,Se=U!=="all"&&U!=="newest"?ie.length:null;return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Os,{className:"sm:max-w-lg max-h-[90vh] overflow-hidden flex flex-col",children:[e.jsxs(Us,{className:"flex-shrink-0",children:[e.jsxs(Bs,{className:"flex items-center gap-2",children:[e.jsx(Yr,{className:"h-5 w-5 text-primary"}),"Share Resource"]}),e.jsxs(Ir,{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(ha,{value:D,onValueChange:O,className:"flex-1 flex flex-col overflow-hidden",children:[e.jsxs(ma,{className:"grid w-full grid-cols-2 flex-shrink-0",children:[e.jsxs(Zt,{value:"agents",className:"flex items-center gap-2",children:[e.jsx(Zn,{className:"h-4 w-4"}),e.jsx("span",{children:"Agents"}),m.length>0&&e.jsx(Be,{variant:"default",className:"h-5 min-w-5 px-1.5 text-xs",children:m.length})]}),e.jsxs(Zt,{value:"brokerages",className:"flex items-center gap-2",children:[e.jsx(ji,{className:"h-4 w-4"}),e.jsx("span",{children:"Brokerages"}),g.length>0&&e.jsx(Be,{variant:"default",className:"h-5 min-w-5 px-1.5 text-xs",children:g.length})]})]}),e.jsxs(Xt,{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(Kr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(pe,{placeholder:"Search by name, email, or brokerage...",value:y,onChange:ke=>v(ke.target.value),className:"pl-9"})]}),e.jsxs(ms,{value:U,onValueChange:W,children:[e.jsxs(us,{className:"w-[180px]",children:[e.jsx(Iw,{className:"h-4 w-4 mr-2 text-muted-foreground"}),e.jsx(fs,{placeholder:"Filter by role"})]}),e.jsx(hs,{children:TBe.map(ke=>e.jsx(Ge,{value:ke.value,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ke.icon,{className:"h-4 w-4"}),e.jsx("span",{children:ke.label})]})},ke.value))})]})]}),e.jsxs("div",{className:"flex items-center justify-between px-1 flex-shrink-0",children:[e.jsxs($,{variant:"ghost",size:"sm",onClick:te,className:"text-xs h-8",disabled:ie.length===0,children:[e.jsx(Zn,{className:"h-3.5 w-3.5 mr-1.5"}),m.length===ie.length&&ie.length>0?"Deselect All":"Select All"]}),e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[Se!==null&&e.jsxs("span",{className:"text-primary font-medium",children:[Se," ",(Le=TBe.find(ke=>ke.value===U))==null?void 0:Le.label]}),e.jsxs("span",{className:"font-medium",children:[m.length," selected"]})]})]}),e.jsx(uo,{className:"h-[300px] border rounded-lg",children:E?e.jsx("div",{className:"flex items-center justify-center h-[200px]",children:e.jsx(kt,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):ie.length===0?e.jsxs("div",{className:"flex flex-col items-center justify-center h-[200px] text-muted-foreground",children:[e.jsx(Zn,{className:"h-8 w-8 mb-2 opacity-50"}),e.jsx("p",{className:"text-sm",children:U!=="all"?`No ${(Fe=TBe.find(ke=>ke.value===U))==null?void 0:Fe.label.toLowerCase()} found`:"No agents found"})]}):e.jsx("div",{className:"p-2 space-y-1",children:ie.map(ke=>e.jsxs("div",{className:`flex items-center gap-3 p-2.5 rounded-lg cursor-pointer hover:bg-accent/50 transition-colors ${m.includes(ke.id)?"bg-accent":""}`,onClick:()=>ce(ke.id),children:[e.jsx(ai,{checked:m.includes(ke.id),onCheckedChange:()=>ce(ke.id),className:"flex-shrink-0"}),e.jsx(Oa,{className:"h-9 w-9 flex-shrink-0",children:e.jsx(za,{className:"text-xs bg-primary/10 text-primary",children:ue(ke.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:ke.name}),ve(ke.id)]}),e.jsxs("p",{className:"text-xs text-muted-foreground truncate",children:[ke.email,ke.brokerage_name&&e.jsxs("span",{className:"ml-1 opacity-75",children:["• ",ke.brokerage_name]})]})]})]},ke.id))})})]}),e.jsxs(Xt,{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(Kr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(pe,{placeholder:"Search brokerages...",value:b,onChange:ke=>w(ke.target.value),className:"pl-9"})]}),e.jsxs("div",{className:"flex items-center justify-between px-1 flex-shrink-0",children:[e.jsxs($,{variant:"ghost",size:"sm",onClick:J,className:"text-xs h-8",disabled:ne.length===0,children:[e.jsx(ji,{className:"h-3.5 w-3.5 mr-1.5"}),g.length===ne.length&&ne.length>0?"Deselect All":"Select All"]}),e.jsxs("span",{className:"text-xs text-muted-foreground font-medium",children:[g.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(uo,{className:"h-[250px] border rounded-lg",children:E?e.jsx("div",{className:"flex items-center justify-center h-[180px]",children:e.jsx(kt,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):ne.length===0?e.jsxs("div",{className:"flex flex-col items-center justify-center h-[180px] text-muted-foreground",children:[e.jsx(ji,{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:ne.map(ke=>e.jsxs("div",{className:`flex items-center gap-3 p-2.5 rounded-lg cursor-pointer hover:bg-accent/50 transition-colors ${g.includes(ke.id)?"bg-accent":""}`,onClick:()=>_e(ke.id),children:[e.jsx(ai,{checked:g.includes(ke.id),onCheckedChange:()=>_e(ke.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(ji,{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:ke.name}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[ke.agent_count," agent",ke.agent_count!==1?"s":""]})]})]},ke.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(Kr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(pe,{placeholder:"Search agents...",value:y,onChange:ke=>v(ke.target.value),className:"pl-9"})]}),Y&&e.jsxs("div",{className:"flex items-center justify-between px-1 flex-shrink-0",children:[e.jsxs($,{variant:"ghost",size:"sm",onClick:te,className:"text-xs h-8",disabled:ie.length===0,children:[e.jsx(Zn,{className:"h-3.5 w-3.5 mr-1.5"}),m.length===ie.length&&ie.length>0?"Deselect All":"Select All"]}),e.jsxs("span",{className:"text-xs text-muted-foreground font-medium",children:[m.length," selected"]})]}),e.jsx(uo,{className:"h-[300px] border rounded-lg",children:E?e.jsx("div",{className:"flex items-center justify-center h-[200px]",children:e.jsx(kt,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):ie.length===0?e.jsxs("div",{className:"flex flex-col items-center justify-center h-[200px] text-muted-foreground",children:[e.jsx(Zn,{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:ie.map(ke=>e.jsxs("div",{className:`flex items-center gap-3 p-2.5 rounded-lg cursor-pointer hover:bg-accent/50 transition-colors ${m.includes(ke.id)?"bg-accent":""}`,onClick:()=>ce(ke.id),children:[e.jsx(ai,{checked:m.includes(ke.id),onCheckedChange:()=>ce(ke.id),className:"flex-shrink-0"}),e.jsx(Oa,{className:"h-9 w-9 flex-shrink-0",children:e.jsx(za,{className:"text-xs bg-primary/10 text-primary",children:ue(ke.name)})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium truncate",children:ke.name}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:ke.email})]})]},ke.id))})})]}),e.jsxs("div",{className:"space-y-2 flex-shrink-0",children:[e.jsx(ee,{htmlFor:"message",className:"text-sm font-medium",children:"Add a message (optional)"}),e.jsx(Rs,{id:"message",placeholder:"I thought you might find this useful...",value:S,onChange:ke=>C(ke.target.value),rows:2,className:"resize-none"})]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-2 flex-shrink-0",children:[e.jsx($,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsx($,{onClick:he,disabled:Ee===0||P,children:P?e.jsxs(e.Fragment,{children:[e.jsx(kt,{className:"h-4 w-4 mr-2 animate-spin"}),"Sharing..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Yr,{className:"h-4 w-4 mr-2"}),"Share"]})})]})]})]})})}function vK({resourceType:s,resourceId:t,resourceTitle:n,variant:r="outline",size:a="sm",className:i=""}){const[l,o]=j.useState(!1),{user:c}=vs();return c?e.jsxs(e.Fragment,{children:[e.jsxs($,{variant:r,size:a,onClick:()=>o(!0),className:i,children:[e.jsx(zd,{className:"h-4 w-4 mr-2"}),"Share"]}),e.jsx(nnn,{open:l,onOpenChange:o,resourceType:s,resourceId:t,resourceTitle:n})]}):null}function rnn(){const{eventId:s}=Wi(),t=Qn(),{user:n}=vs(),[r,a]=j.useState(null),[i,l]=j.useState(null),[o,c]=j.useState(0),[d,u]=j.useState(!0),[h,m]=j.useState(!1);j.useEffect(()=>{s&&f()},[s,n]);const f=async()=>{try{const{data:w,error:S}=await q.from("events").select("*").eq("id",s).single();if(S)throw S;a(w);const{count:C}=await q.from("event_registrations").select("*",{count:"exact",head:!0}).eq("event_id",s);if(c(C||0),n){const{data:E}=await q.from("event_registrations").select("id, zoom_join_url").eq("event_id",s).eq("user_id",n.id).maybeSingle();l(E)}}catch(w){console.error("Error loading event:",w),re.error("Failed to load event"),t("/events")}finally{u(!1)}},g=async()=>{if(!(!n||!r)){m(!0);try{const{error:w}=await q.auth.refreshSession();if(w){console.error("Session refresh failed:",w),re.error("Your session has expired. Please log in again.");return}if(i){const{error:S}=await q.functions.invoke("zoom-unregister",{body:{event_id:r.id}});if(S)throw S;re.success("Successfully cancelled registration"),l(null),c(C=>C-1)}else{const{data:S,error:C}=await q.functions.invoke("zoom-register",{body:{event_id:r.id}});if(C)throw C;re.success("Successfully registered for event!"),l({id:S.registration_id,zoom_join_url:S.zoom_join_url}),c(E=>E+1)}}catch(w){console.error("Registration error:",w),re.error(i?"Failed to cancel registration":"Failed to register for event")}finally{m(!1)}}},x=w=>{var S,C,E;if(w.includes("iframe.mediadelivery.net")||w.includes("video.bunnycdn.com")){const I=w.match(/embed\/(\d+)\/([a-f0-9-]+)/);if(I)return`https://iframe.mediadelivery.net/embed/${I[1]}/${I[2]}?autoplay=false&preload=true`}if(w.includes("youtube.com")||w.includes("youtu.be")){const I=w.includes("youtu.be")?(S=w.split("youtu.be/")[1])==null?void 0:S.split("?")[0]:(C=w.split("v=")[1])==null?void 0:C.split("&")[0];if(I)return`https://www.youtube.com/embed/${I}`}if(w.includes("vimeo.com")){const I=(E=w.split("vimeo.com/")[1])==null?void 0:E.split("?")[0];if(I)return`https://player.vimeo.com/video/${I}`}return w};if(d)return e.jsx(Vs,{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(!r)return e.jsx(Vs,{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($,{onClick:()=>t("/events"),className:"mt-4",children:"Back to Events"})]})});const y=z4(new Date(r.event_date)),v=r.capacity&&o>=r.capacity,b=(i==null?void 0:i.zoom_join_url)||r.zoom_link;return e.jsx(Vs,{title:r.title,children:e.jsxs("div",{className:"max-w-4xl mx-auto",children:[e.jsxs($,{variant:"ghost",className:"mb-6 gap-2",onClick:()=>t("/events"),children:[e.jsx(qa,{className:"h-4 w-4"}),"Back to Events"]}),r.image_url&&e.jsxs("div",{className:"relative aspect-video rounded-xl overflow-hidden mb-6",children:[e.jsx("img",{src:r.image_url,alt:r.title,className:"w-full h-full object-cover"}),y&&e.jsx("div",{className:"absolute inset-0 bg-black/50 flex items-center justify-center",children:e.jsx(Be,{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:r.title}),e.jsx(vK,{resourceType:"event",resourceId:r.id,resourceTitle:r.title})]}),r.description&&e.jsx("div",{className:"prose prose-sm max-w-none text-muted-foreground dark:prose-invert",dangerouslySetInnerHTML:{__html:r.description}})]}),r.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(tf,{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:x(r.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(Ne,{children:e.jsxs(Ie,{className:"p-6 space-y-4",children:[e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(Ta,{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(r.event_date))}),e.jsx("p",{className:"text-sm text-muted-foreground",children:fse(new Date(r.event_date))})]})]}),r.capacity&&e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(Zn,{className:"h-5 w-5 text-primary mt-0.5"}),e.jsxs("div",{children:[e.jsxs("p",{className:"font-medium",children:[o," / ",r.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(Nc,{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:[!y&&e.jsx(e.Fragment,{children:i?e.jsxs(e.Fragment,{children:[e.jsxs($,{className:"w-full gap-2",onClick:()=>window.open(b,"_blank"),children:[e.jsx(kr,{className:"h-4 w-4"}),"Join Event"]}),e.jsxs($,{variant:"outline",className:"w-full",onClick:g,disabled:h,children:[h?e.jsx(kt,{className:"h-4 w-4 animate-spin mr-2"}):null,"Cancel Registration"]})]}):e.jsx($,{className:"w-full gap-2",onClick:g,disabled:h||(v??!1),children:h?e.jsx(kt,{className:"h-4 w-4 animate-spin"}):v?"Event Full":"Register Now"})}),y&&i&&e.jsxs($,{variant:"outline",className:"w-full gap-2",onClick:()=>window.open(r.zoom_link,"_blank"),children:[e.jsx(kr,{className:"h-4 w-4"}),"View Recording"]})]})]})})})]})]})})}const ann=[{to:"/apps",label:"Home",end:!0},{to:"/apps/my-apps",label:"My Apps"},{to:"/apps/browse",label:"Browse Apps"},{to:"/apps/workflows",label:"Workflows",adminOnly:!0},{to:"/apps/connected",label:"Connected Apps"}];function inn(){const{isAdmin:s}=vs(),t=ann.filter(n=>!n.adminOnly||s);return e.jsx("div",{className:"-mx-4 px-4 sm:mx-0 sm:px-0 overflow-x-auto scrollbar-hide",children:e.jsx("nav",{className:"inline-flex gap-1 bg-muted/60 p-1 rounded-xl min-w-max",children:t.map(n=>e.jsx(dP,{to:n.to,end:n.end,className:({isActive:r})=>Pt("px-4 py-2 rounded-lg text-sm font-medium whitespace-nowrap transition-colors",r?"bg-card text-foreground shadow-sm":"text-muted-foreground hover:text-foreground"),children:n.label},n.to))})})}const zTe=[{id:"market-listing",title:"Market a Listing",blurb:"Presentations, copy, pages and video",icon:va,color:"bg-violet-500/15 text-violet-600"},{id:"follow-up",title:"Follow Up With My Database",blurb:"Emails, cards, mail and check-ins",icon:mn,color:"bg-emerald-500/15 text-emerald-600"},{id:"social-content",title:"Create Social Content",blurb:"Reels, posts and captions",icon:xm,color:"bg-rose-500/15 text-rose-600"},{id:"open-house",title:"Host an Open House",blurb:"Promote, sign in and follow up",icon:d2,color:"bg-sky-500/15 text-sky-600"},{id:"new-business",title:"Generate New Business",blurb:"Leads, expireds and by-owner sellers",icon:Yl,color:"bg-amber-500/15 text-amber-600"},{id:"brand",title:"Build My Brand",blurb:"Your card, site, reviews and presence",icon:Yc,color:"bg-teal-500/15 text-teal-600"}];zTe.reduce((s,t)=>({...s,[t.id]:t}),{});const onn=[{id:"listings",label:"Listings"},{id:"database",label:"Database & Follow-Up"},{id:"leads",label:"Leads & Conversion"},{id:"social",label:"Social & Content"},{id:"open-houses",label:"Open Houses"},{id:"brand",label:"Brand & Presence"},{id:"ai",label:"AI Assistants"}],CHt=[{id:"scheduler",name:"LevelUp Scheduler",description:"Share your booking link, sync Google Calendar and let clients book you",icon:Au,path:"/mission-control/scheduler",color:"bg-blue-500/15 text-blue-600",isNew:!0,goals:["follow-up","new-business","brand"],categories:["database","leads","brand"],keywords:["scheduler","calendar","booking link","book a meeting","appointments","calendly","availability"]},{id:"quickvid",name:"QuickVid",description:"Record and share personalized video messages",icon:ua,path:"/mission-control/video/record",color:"bg-rose-500/15 text-rose-600",popular:!0,goals:["follow-up","social-content","open-house"],categories:["database","social","open-houses"],keywords:["video","record a video","send a video","video email","screen record"]},{id:"smart-card",name:"Smart Card",description:"Your digital business card in one shareable link",icon:Cv,path:"/mission-control/my-card",color:"bg-sky-500/15 text-sky-600",goals:["brand"],categories:["brand"],keywords:["business card","digital card","share my info","contact card"]},{id:"smart-presentations",name:"Smart Presentations",description:"Beautiful listing and buyer presentations",icon:jb,path:"/mission-control/presentations",color:"bg-amber-500/15 text-amber-600",goals:["market-listing","brand"],categories:["listings","brand"],keywords:["buyer presentation","listing presentation","pitch","slides"]},{id:"landing-pages",name:"Landing Pages",description:"Custom landing pages that capture leads",icon:Jr,path:"/mission-control/landing-pages",color:"bg-emerald-500/15 text-emerald-600",goals:["market-listing","new-business","open-house"],categories:["listings","leads","open-houses"],keywords:["landing page","capture leads","promote an open house","single property site"]},{id:"guest-book",name:"Guest Book",description:"Digital open house sign-in that captures visitors",icon:Xf,path:"/mission-control/guest-book",color:"bg-orange-500/15 text-orange-600",popular:!0,goals:["open-house","new-business"],categories:["open-houses","leads"],keywords:["open house sign in","sign-in sheet","visitors","host an open house"]},{id:"card-studio",name:"Card Studio",description:"Animated cards for birthdays and milestones",icon:Nn,path:"/mission-control/card-studio",color:"bg-pink-500/15 text-pink-600",goals:["follow-up","social-content"],categories:["database","social"],keywords:["birthday card","anniversary","greeting","thank you card"]},{id:"direct-mail",name:"Direct Mail",description:"Send professional postcards to your contacts",icon:mn,path:"/mission-control/direct-mail",color:"bg-indigo-500/15 text-indigo-600",adminOnly:!0,beta:!0,goals:["follow-up","open-house"],categories:["database","open-houses"],keywords:["postcard","mailer","farming","direct mail"]},{id:"reelflow",name:"ReelFlow",description:"Turn property photos into cinematic reels with AI",icon:rf,path:"/admin/beta/homereel",color:"bg-violet-500/15 text-violet-600",beta:!0,isNew:!0,goals:["market-listing","social-content"],categories:["listings","social","ai"],keywords:["create a reel","video from photos","instagram","cinematic"]},{id:"mass-emails",name:"Mass Emails",description:"Send bulk email campaigns to your contacts",icon:Yr,path:"/admin/email-campaigns",color:"bg-teal-500/15 text-teal-600",beta:!0,goals:["follow-up","open-house"],categories:["database","open-houses"],keywords:["email my database","bulk email","campaign","blast","invite"]},{id:"listing-studio",name:"Listing Studio",description:"AI MLS descriptions, luxury copy and open house blurbs",icon:wf,path:"/mission-control/listing-studio",color:"bg-fuchsia-500/15 text-fuchsia-600",isNew:!0,goals:["market-listing","social-content"],categories:["listings","social","ai"],keywords:["mls description","write listing copy","captions","ai writing"]},{id:"website-apps",name:"Website Apps",description:"Drop-in conversion widgets for your website",icon:Yq,path:"/website-apps",color:"bg-cyan-500/15 text-cyan-600",isNew:!0,goals:["new-business","brand"],categories:["leads","brand"],keywords:["website widget","video greeter","lead magnet","pop up"]},{id:"newsletter-pro",name:"Newsletter Pro",description:"Branded newsletters for your database",icon:nk,path:"/newsletters",color:"bg-yellow-500/15 text-yellow-600",goals:["follow-up"],categories:["database"],keywords:["newsletter","monthly email","market update"]},{id:"weekly-reels",name:"Weekly Reels",description:"5 personalized Reel scripts every Monday morning",icon:rf,path:"/weekly-reels",color:"bg-orange-500/15 text-orange-600",isNew:!0,requiresWeeklyReels:!0,goals:["social-content"],categories:["social","ai"],keywords:["reel scripts","instagram","content ideas","social posts"]},{id:"cma",name:"CMA Reports",description:"Interactive CMAs with live comps you can share",icon:Wl,path:"/mission-control/cma",color:"bg-blue-500/15 text-blue-600",isNew:!0,requiresLeadSiteMLS:!0,goals:["market-listing","new-business"],categories:["listings","leads"],keywords:["cma","comps","home value","pricing"]},{id:"listing-presentation-studio",name:"Listing Presentation Studio",description:"A branded 12-page seller presentation in minutes",icon:jb,path:"/apps/listing-presentation-studio",color:"bg-emerald-500/15 text-emerald-600",isNew:!0,popular:!0,goals:["market-listing"],categories:["listings"],keywords:["make a listing presentation","seller presentation","pdf","pre-listing"]},{id:"listing-revival",name:"Listing Revival",description:"Turn expired listings into appointments",icon:Nn,path:"/apps/listing-revival",color:"bg-amber-500/15 text-amber-600",isNew:!0,goals:["new-business"],categories:["leads","listings","ai"],keywords:["expired listing","expired","withdrawn","revival letter"]},{id:"fsbo-breakthrough",name:"By-Owner Breakthrough",description:"Convert FSBO sellers with letters, guides and pages",icon:va,path:"/apps/fsbo-breakthrough",color:"bg-[#5b8a5c]/15 text-[#5b8a5c]",isNew:!0,goals:["new-business"],categories:["leads","ai"],keywords:["fsbo","for sale by owner","by owner","convert fsbo"]},{id:"staging-studio",name:"Staging Studio",description:"Virtually stage, declutter and brighten listing photos",icon:iV,path:"/apps/staging-studio",color:"bg-[#406E71]/15 text-[#406E71]",isNew:!0,featureFlag:"staging_studio_enabled",goals:["market-listing"],categories:["listings","ai"],keywords:["virtual staging","staging","twilight","declutter","sky replacement","landscaping","photo"]}],f_t=CHt.reduce((s,t)=>({...s,[t.id]:t}),{}),lnn={agent_review:{goals:[],categories:[],keywords:[]},sigflow:{goals:["brand","follow-up"],categories:["brand","database"],keywords:["email signature","signature","branding"]},social_autopilot:{goals:["social-content","brand"],categories:["social","brand"],keywords:["social posts","schedule posts","autopilot","facebook","instagram"]}},cnn={AgentReview:"Replaced by the new built-in Reviews app"};function dnn(s){return lnn[s]??{goals:[],categories:[],keywords:[]}}const art=[{id:"new-listing-launch",title:"New Listing Launch",description:"Everything you need to take a new listing to market.",outcome:"A listing that is presented, promoted and seen",namePrompt:"What listing is this for?",namePlaceholder:"520 Harlan Drive",icon:va,color:"bg-violet-500/15 text-violet-600",steps:[{key:"presentation",title:"Build the listing presentation",detail:"Create your branded seller presentation.",toolId:"listing-presentation-studio"},{key:"copy",title:"Write the listing copy",detail:"Generate the MLS description and marketing copy.",toolId:"listing-studio"},{key:"page",title:"Create the property page",detail:"Publish a landing page for the listing.",toolId:"landing-pages"},{key:"reel",title:"Make a reel",detail:"Turn the photos into a cinematic video.",toolId:"reelflow"},{key:"email",title:"Email your database",detail:"Announce the listing to your contacts.",toolId:"mass-emails"},{key:"video",title:"Send a personal video",detail:"Record a quick note for your top contacts.",toolId:"quickvid"}]},{id:"open-house-success",title:"Open House Success Kit",description:"Plan, promote, capture visitors, and follow up.",outcome:"A full open house with every visitor captured",namePrompt:"Which open house is this for?",namePlaceholder:"Sunday open house — 12 Oak St",icon:d2,color:"bg-sky-500/15 text-sky-600",steps:[{key:"page",title:"Build the open house page",detail:"Create a page with the date, time and details.",toolId:"landing-pages"},{key:"invite",title:"Invite your database",detail:"Send the invitation email.",toolId:"mass-emails"},{key:"signin",title:"Set up sign-in",detail:"Turn on the digital guest book for the event.",toolId:"guest-book"},{key:"followup",title:"Follow up with visitors",detail:"Send a personal video to everyone who came.",toolId:"quickvid"}]},{id:"database-touchpoint",title:"Database Touchpoint",description:"Get a valuable message in front of your whole database.",outcome:"Your sphere hears from you this month",namePrompt:"What month or theme is this for?",namePlaceholder:"August market update",icon:Zn,color:"bg-emerald-500/15 text-emerald-600",steps:[{key:"pick",title:"Pick your message",detail:"Start from a newsletter or market update.",toolId:"newsletter-pro"},{key:"personal",title:"Add a personal touch",detail:"Record a short video intro.",toolId:"quickvid"},{key:"send",title:"Send it out",detail:"Deliver it to your contacts.",toolId:"mass-emails"},{key:"cards",title:"Celebrate milestones",detail:"Send cards to anyone with a milestone this month.",toolId:"card-studio"}]}],nB=art.reduce((s,t)=>({...s,[t.id]:t}),{});function unn({goal:s,onSelect:t}){const n=s.icon;return e.jsxs("button",{type:"button",onClick:()=>t(s),className:"group text-left bg-card border border-border rounded-2xl p-5 transition-all hover:border-primary/40 hover:shadow-md focus:outline-none focus-visible:ring-2 focus-visible:ring-primary",children:[e.jsx("div",{className:Pt("w-12 h-12 rounded-xl flex items-center justify-center mb-4",s.color),children:e.jsx(n,{className:"h-6 w-6"})}),e.jsx("h3",{className:"font-semibold text-foreground group-hover:text-primary transition-colors",children:s.title}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:s.blurb})]})}function hnn({item:s,isFavorite:t,onOpen:n,onToggleFavorite:r}){const a=typeof s.icon=="string"?null:s.icon,i=!!s.lockedFeature,l=i?{label:"Upgrade",className:"bg-muted text-muted-foreground"}:s.isNew?{label:"New",className:"bg-primary/10 text-primary"}:s.beta?{label:"Beta",className:"bg-amber-500/15 text-amber-600"}:s.popular?{label:"Popular",className:"bg-emerald-500/15 text-emerald-600"}:s.kind==="app"&&s.deprecated?{label:"Going away soon",className:"bg-amber-500/15 text-amber-700"}:s.kind==="app"?{label:"Connected",className:"bg-muted text-muted-foreground"}:null;return e.jsxs("div",{role:"button",tabIndex:0,onClick:()=>n(s),onKeyDown:o=>{(o.key==="Enter"||o.key===" ")&&(o.preventDefault(),n(s))},className:Pt("group h-full text-left bg-card border border-border rounded-2xl p-5 flex flex-col gap-3 cursor-pointer transition-all hover:border-primary/40 hover:shadow-md focus:outline-none focus-visible:ring-2 focus-visible:ring-primary",i&&"opacity-80"),children:[e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:Pt("flex-shrink-0 w-12 h-12 rounded-xl flex items-center justify-center text-2xl",s.color),children:i?e.jsx(pc,{className:"h-5 w-5"}):a?e.jsx(a,{className:"h-6 w-6"}):e.jsx("span",{children:s.icon})}),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-foreground group-hover:text-primary transition-colors",children:s.name}),l&&e.jsx("span",{className:Pt("text-[11px] font-medium px-2 py-0.5 rounded-full",l.className),children:l.label})]}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1 line-clamp-2",children:s.description})]}),e.jsx("button",{type:"button","aria-label":t?`Remove ${s.name} from favorites`:`Add ${s.name} to favorites`,onClick:o=>{o.stopPropagation(),r(s)},className:Pt("flex-shrink-0 p-2 -m-1 rounded-lg transition-colors",t?"text-primary":"text-muted-foreground/40 hover:text-primary"),children:e.jsx(M0,{className:Pt("h-5 w-5",t&&"fill-current")})})]}),e.jsx("div",{className:"mt-auto pt-1",children:e.jsx("span",{className:"text-sm font-medium text-primary",children:i?"Request access →":"Open →"})})]})}function y7({items:s,isFavorite:t,onOpen:n,onToggleFavorite:r}){return e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4",children:s.map(a=>e.jsx(hnn,{item:a,isFavorite:t(a),onOpen:n,onToggleFavorite:r},a.key))})}const mnn="bg-primary/10 text-primary";function fie(){const{user:s,isAdmin:t}=vs(),n=jC(),r=Qn(),{hasAccess:a}=_Le(),{isFeatureEnabled:i}=Rae(),[l,o]=j.useState([]),[c,d]=j.useState(!0),[u,h]=j.useState(new Set),[m,f]=j.useState(new Set),[g,x]=j.useState(!1),[y,v]=j.useState([]),[b,w]=j.useState(""),S=j.useCallback(async()=>{if(s!=null&&s.id)try{const[{data:G},{data:Y},{data:X},{data:ae},{data:ie},{data:ne},{data:te}]=await Promise.all([q.from("user_tags").select("tag").eq("user_id",s.id),q.from("app_tiles").select("*").order("name"),q.from("user_favorites").select("app_id").eq("user_id",s.id),q.from("user_tool_favorites").select("tool_id").eq("user_id",s.id),q.from("lead_sites").select("id, mls_provider_id, no_mls_mode, is_active").eq("agent_id",s.id),q.from("activity_logs").select("app_id, app_name, launched_at").eq("user_id",s.id).order("launched_at",{ascending:!1}).limit(40),q.from("profiles").select("name").eq("id",s.id).maybeSingle()]),J=(G||[]).map(ve=>ve.tag);x((ie||[]).some(ve=>ve.is_active&&ve.mls_provider_id&&!ve.no_mls_mode)),h(new Set((X||[]).map(ve=>ve.app_id))),f(new Set((ae||[]).map(ve=>ve.tool_id)));const ce=(Y||[]).filter(ve=>ve.app_id==="newsletter_studio"?!1:!ve.required_tags||ve.required_tags.length===0?!0:ve.required_tags.some(Ee=>J.includes(Ee)));o(ce.sort((ve,Ee)=>ve.name==="LevelUp Members Portal"?-1:Ee.name==="LevelUp Members Portal"?1:0));const _e=new Set,he=[];for(const ve of ne||[])if(!(!ve.app_id||_e.has(ve.app_id))&&(_e.add(ve.app_id),he.push({appId:ve.app_id,name:ve.app_name,at:ve.launched_at}),he.length>=8))break;v(he);const ue=te==null?void 0:te.name;w(ue?ue.trim().split(" ")[0]:"")}catch(G){console.error("Error loading app catalog:",G),re.error("Failed to load apps")}finally{d(!1)}},[s==null?void 0:s.id]);j.useEffect(()=>{S()},[S]);const C=j.useMemo(()=>{const G=ie=>{if(!n.isRestricted)return null;const ne=zCs(ie);return ne&&!n.hasFeature(ne)?ne:null},Y=CHt.filter(ie=>!(ie.adminOnly&&!t||ie.requiresLeadSiteMLS&&!g&&!t||ie.requiresWeeklyReels&&!a||ie.featureFlag&&!i(ie.featureFlag)&&!t)).map(ie=>({key:`tool:${ie.id}`,kind:"tool",id:ie.id,name:ie.name,description:ie.description,icon:ie.icon,color:ie.color,isNew:ie.isNew,beta:ie.beta,popular:ie.popular,goals:ie.goals,categories:ie.categories,keywords:ie.keywords,lockedFeature:G(ie.id),tool:ie})),X={AgentReview:"marketing_studio",SigFlow:"marketing_studio",Staging_Studio:"marketing_studio",social_autopilot:"social",newsletter_studio:"newsletter"},ae=l.map(ie=>{const ne=dnn(ie.app_id),te=X[ie.app_id];return{key:`app:${ie.app_id}`,kind:"app",id:ie.app_id,name:ie.name,description:ie.description,icon:ie.icon,color:mnn,goals:ne.goals,categories:ne.categories,keywords:ne.keywords,lockedFeature:n.isRestricted&&te&&!n.hasFeature(te)?te:null,deprecated:!!cnn[ie.app_id],tile:ie}});return[...Y,...ae]},[l,t,g,a,i,n.isRestricted,n.features]),E=j.useCallback(G=>{var Y;return G.kind==="tool"?m.has(G.id):u.has(((Y=G.tile)==null?void 0:Y.id)??"")},[m,u]),I=j.useMemo(()=>C.filter(E),[C,E]),P=j.useMemo(()=>{const G=new Map(C.map(Y=>[Y.id,Y]));return y.map(Y=>G.get(Y.appId)).filter(Boolean)},[C,y]),R=j.useMemo(()=>C.filter(G=>G.kind==="app"),[C]),D=j.useCallback(async(G,Y)=>{try{await q.from("activity_logs").insert({user_id:s==null?void 0:s.id,app_id:G,app_name:Y,user_agent:navigator.userAgent})}catch{}},[s==null?void 0:s.id]),O=j.useCallback(async G=>{var X;if(G.target_url.startsWith("/")){await D(G.app_id,G.name),r(G.target_url);return}try{const ae=new URL(G.target_url);if(new Set([window.location.hostname,"dashboard.relevelup.com"]).has(ae.hostname)){await D(G.app_id,G.name),r(ae.pathname+ae.search+ae.hash);return}}catch{}const Y=window.open("about:blank","_blank");try{const{data:ae,error:ie}=await q.auth.getSession();if(ie||!ae.session){Y==null||Y.close(),re.error("Session expired. Please refresh the page and try again.");return}await D(G.app_id,G.name);const{data:ne,error:te}=await q.functions.invoke("sso-launch",{body:{app_id:G.app_id},headers:{Authorization:`Bearer ${ae.session.access_token}`}});if(te)throw te;ne!=null&&ne.redirect_url?Y&&!Y.closed?(Y.location.href=ne.redirect_url,(X=Y.focus)==null||X.call(Y)):window.location.assign(ne.redirect_url):(Y==null||Y.close(),re.error("Launch link unavailable"))}catch(ae){Y==null||Y.close(),console.error("Error launching app:",ae),re.error("Failed to launch app. Please try again.")}},[D,r]),U=j.useCallback(G=>{if(G.lockedFeature){r(`/upgrade/${G.lockedFeature}`);return}if(G.kind==="app"&&G.tile){O(G.tile);return}G.tool&&(D(G.tool.id,G.tool.name),r(G.tool.path))},[O,D,r]),W=j.useCallback(async G=>{var te;if(!(s!=null&&s.id))return;const Y=E(G),X=G.kind==="tool"?"user_tool_favorites":"user_favorites",ae=G.kind==="tool"?"tool_id":"app_id",ie=G.kind==="tool"?G.id:(te=G.tile)==null?void 0:te.id;if(!ie)return;const ne=G.kind==="tool"?f:h;ne(J=>{const ce=new Set(J);return Y?ce.delete(ie):ce.add(ie),ce});try{if(Y){const{error:J}=await q.from(X).delete().eq("user_id",s.id).eq(ae,ie);if(J)throw J}else{const{error:J}=await q.from(X).insert({user_id:s.id,[ae]:ie});if(J)throw J}}catch(J){console.error("Error toggling favorite:",J),re.error("Failed to update favorites"),ne(ce=>{const _e=new Set(ce);return Y?_e.add(ie):_e.delete(ie),_e})}},[E,s==null?void 0:s.id]),V=j.useCallback((G,Y=C)=>{const X=G.trim().toLowerCase();if(!X)return Y;const ae=X.split(/\s+/);return Y.filter(ie=>{if(ie.deprecated)return!1;const ne=[ie.name,ie.description,...ie.keywords,...ie.categories,...ie.goals].join(" ").toLowerCase();return ae.every(te=>ne.includes(te))||ne.includes(X)})},[C]);return{loading:c,items:C,favoriteItems:I,recentItems:P,connectedItems:R,recent:y,firstName:b,isFavorite:E,toggleFavorite:W,openItem:U,search:V,reload:S}}function MBe(s){return{id:s.id,workflow_id:s.workflow_id,run_name:s.run_name,status:s.status==="completed"?"completed":"in_progress",step_state:s.step_state??{},completed_at:s.completed_at,last_activity_at:s.last_activity_at,created_at:s.created_at}}function Q6e(s){const t=nB[s.workflow_id],n=(t==null?void 0:t.steps.length)??0,r=t?t.steps.filter(a=>s.step_state[a.key]).length:Object.keys(s.step_state).length;return{touched:r,total:n,pct:n?Math.round(r/n*100):0}}function J6e(){const{user:s}=vs(),[t,n]=j.useState([]),[r,a]=j.useState(!0),i=j.useCallback(async()=>{if(s!=null&&s.id)try{const{data:m,error:f}=await q.from("workflow_runs").select("*").eq("user_id",s.id).order("last_activity_at",{ascending:!1});if(f)throw f;n((m||[]).map(MBe))}catch(m){console.error("Error loading workflow runs:",m)}finally{a(!1)}},[s==null?void 0:s.id]);j.useEffect(()=>{i()},[i]);const l=j.useCallback(async(m,f)=>{var g;if(!(s!=null&&s.id))return null;try{const{data:x,error:y}=await q.from("workflow_runs").insert({user_id:s.id,workflow_id:m,run_name:f.trim()||((g=nB[m])==null?void 0:g.title)||"Untitled"}).select("*").single();if(y)throw y;const v=MBe(x);return n(b=>[v,...b]),v}catch(x){return console.error("Error starting workflow:",x),re.error("Could not start this workflow"),null}},[s==null?void 0:s.id]),o=j.useCallback(async(m,f)=>{const g={...f,last_activity_at:new Date().toISOString()};n(y=>y.map(v=>v.id===m?MBe({...v,...g}):v));const{error:x}=await q.from("workflow_runs").update(g).eq("id",m);x&&(console.error("Error updating workflow run:",x),re.error("Could not save your progress"))},[]),c=j.useCallback(async(m,f,g)=>{const x={...m.step_state};g?x[f]=g:delete x[f];const y=nB[m.workflow_id],v=y?y.steps.every(b=>x[b.key]):!1;await o(m.id,{step_state:x,status:v?"completed":"in_progress",completed_at:v?new Date().toISOString():null}),v&&m.status!=="completed"&&re.success("Workflow complete — nice work!")},[o]),d=j.useCallback((m,f)=>o(m.id,{run_name:f.trim()}),[o]),u=j.useCallback(m=>o(m.id,{status:"in_progress",completed_at:null}),[o]),h=j.useCallback(async m=>{n(g=>g.filter(x=>x.id!==m));const{error:f}=await q.from("workflow_runs").delete().eq("id",m);f&&(console.error("Error deleting workflow run:",f),re.error("Could not delete this workflow"))},[]);return{runs:t,loading:r,activeRuns:t.filter(m=>m.status==="in_progress"),completedRuns:t.filter(m=>m.status==="completed"),startRun:l,setStep:c,renameRun:d,reopenRun:u,deleteRun:h,reload:i}}function fnn(){const s=Number(new Intl.DateTimeFormat("en-US",{timeZone:"America/New_York",hour:"numeric",hour12:!1}).format(new Date));return s<12?"Good morning":s<18?"Good afternoon":"Good evening"}function pnn(){const s=Qn(),{items:t,firstName:n,recentItems:r,favoriteItems:a,isFavorite:i,toggleFavorite:l,openItem:o,search:c}=fie(),{isAdmin:d}=vs(),{activeRuns:u}=J6e(),h=d?u:[],[m,f]=j.useState(""),g=j.useMemo(()=>m.trim()?c(m).slice(0,8):[],[m,c]),x=j.useMemo(()=>{const v=new Set(r.map(S=>S.id)),b=[],w=S=>{for(const C of S){if(b.length>=4)break;b.some(E=>E.key===C.key)||b.push(C)}};return w(a.filter(S=>!v.has(S.id))),w(t.filter(S=>S.isNew&&!v.has(S.id))),w(t.filter(S=>S.popular&&!v.has(S.id))),b},[t,a,r]),y=v=>s(`/apps/browse?goal=${v.id}`);return e.jsxs("div",{className:"space-y-8",children:[e.jsxs("div",{children:[e.jsxs("h1",{className:"text-2xl sm:text-3xl font-bold text-foreground",children:[fnn(),n?`, ${n}`:""]}),e.jsx("p",{className:"text-muted-foreground mt-1",children:"What do you want to accomplish today?"}),e.jsxs("div",{className:"relative mt-5 max-w-2xl",children:[e.jsx(Kr,{className:"absolute left-4 top-1/2 -translate-y-1/2 h-5 w-5 text-muted-foreground"}),e.jsx(pe,{value:m,onChange:v=>f(v.target.value),onKeyDown:v=>{v.key==="Enter"&&m.trim()&&s(`/apps/browse?q=${encodeURIComponent(m.trim())}`)},placeholder:"Search apps or tell us what you want to do…",className:"pl-12 h-14 text-base rounded-2xl"})]}),m.trim()&&e.jsx("div",{className:"mt-4 max-w-2xl bg-card border border-border rounded-2xl divide-y divide-border overflow-hidden",children:g.length===0?e.jsxs("p",{className:"p-4 text-sm text-muted-foreground",children:["Nothing matched “",m,"”. Try “open house”, “email my database” or “reel”."]}):g.map(v=>{const b=typeof v.icon=="string"?null:v.icon;return e.jsxs("button",{type:"button",onClick:()=>o(v),className:"w-full flex items-center gap-3 p-4 text-left hover:bg-muted/50 transition-colors",children:[e.jsx("span",{className:Pt("w-10 h-10 rounded-lg flex items-center justify-center text-xl flex-shrink-0",v.color),children:b?e.jsx(b,{className:"h-5 w-5"}):v.icon}),e.jsxs("span",{className:"min-w-0",children:[e.jsx("span",{className:"block font-medium text-foreground",children:v.name}),e.jsx("span",{className:"block text-sm text-muted-foreground truncate",children:v.description})]})]},v.key)})})]}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-3 gap-8",children:[e.jsxs("div",{className:"lg:col-span-2 space-y-8",children:[e.jsxs("section",{children:[e.jsx("h2",{className:"text-lg font-semibold text-foreground mb-4",children:"Start with a goal"}),e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:zTe.map(v=>e.jsx(unn,{goal:v,onSelect:y},v.id))})]}),(h.length>0||r.length>0)&&e.jsxs("section",{children:[e.jsxs("h2",{className:"text-lg font-semibold text-foreground mb-4 flex items-center gap-2",children:[e.jsx(da,{className:"h-4 w-4 text-muted-foreground"})," Continue working"]}),h.length>0&&e.jsx("div",{className:"space-y-3 mb-4",children:h.slice(0,2).map(v=>{const b=nB[v.workflow_id],w=Q6e(v);return e.jsxs("button",{type:"button",onClick:()=>s(`/apps/workflows/${v.id}`),className:"w-full text-left bg-card border border-border rounded-2xl p-4 hover:border-primary/40 transition-colors",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"font-medium text-foreground truncate",children:v.run_name}),e.jsxs("p",{className:"text-sm text-muted-foreground truncate",children:[b==null?void 0:b.title," · Step ",Math.min(w.touched+1,w.total)," of ",w.total]})]}),e.jsx(ei,{className:"h-4 w-4 text-primary flex-shrink-0"})]}),e.jsx("div",{className:"h-1.5 rounded-full bg-muted overflow-hidden mt-3",children:e.jsx("div",{className:"h-full bg-primary",style:{width:`${w.pct}%`}})})]},v.id)})}),r.length>0&&e.jsx("div",{className:"flex gap-3 overflow-x-auto pb-2 -mx-4 px-4 sm:mx-0 sm:px-0 scrollbar-hide",children:r.slice(0,6).map(v=>{const b=typeof v.icon=="string"?null:v.icon;return e.jsxs("button",{type:"button",onClick:()=>o(v),className:"flex-shrink-0 w-44 bg-card border border-border rounded-2xl p-4 text-left hover:border-primary/40 transition-colors",children:[e.jsx("span",{className:Pt("w-10 h-10 rounded-lg flex items-center justify-center text-xl mb-3",v.color),children:b?e.jsx(b,{className:"h-5 w-5"}):v.icon}),e.jsx("span",{className:"block font-medium text-sm text-foreground truncate",children:v.name}),e.jsx("span",{className:"block text-xs text-muted-foreground",children:"Open again"})]},v.key)})})]})]}),x.length>0&&e.jsxs("aside",{className:"space-y-4",children:[e.jsxs("h2",{className:"text-lg font-semibold text-foreground flex items-center gap-2",children:[e.jsx(Nn,{className:"h-4 w-4 text-primary"})," Recommended for you"]}),e.jsx("div",{className:"space-y-3",children:x.map(v=>{const b=typeof v.icon=="string"?null:v.icon;return e.jsxs("button",{type:"button",onClick:()=>o(v),className:"w-full flex items-start gap-3 bg-card border border-border rounded-2xl p-4 text-left hover:border-primary/40 transition-colors",children:[e.jsx("span",{className:Pt("w-10 h-10 rounded-lg flex items-center justify-center text-xl flex-shrink-0",v.color),children:b?e.jsx(b,{className:"h-5 w-5"}):v.icon}),e.jsxs("span",{className:"min-w-0",children:[e.jsx("span",{className:"block font-medium text-foreground",children:v.name}),e.jsx("span",{className:"block text-sm text-muted-foreground line-clamp-2",children:v.description})]})]},v.key)})}),e.jsx($,{variant:"outline",className:"w-full",onClick:()=>s("/apps/browse"),children:"Browse all apps"})]})]}),a.length>0&&e.jsxs("section",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-4",children:[e.jsx("h2",{className:"text-lg font-semibold text-foreground",children:"Your favorites"}),e.jsx($,{variant:"ghost",size:"sm",onClick:()=>s("/apps/my-apps"),children:"View all"})]}),e.jsx(y7,{items:a.slice(0,6),isFavorite:i,onOpen:o,onToggleFavorite:l})]})]})}function AHt({workflow:s,activeRun:t,onStart:n,onResume:r}){const a=s.icon,i=t?Q6e(t):null;return e.jsxs("div",{className:"bg-card border border-border rounded-2xl p-5 flex flex-col gap-4 h-full",children:[e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:Pt("w-12 h-12 rounded-xl flex items-center justify-center flex-shrink-0",s.color),children:e.jsx(a,{className:"h-6 w-6"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("h3",{className:"font-semibold text-foreground",children:s.title}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:s.description})]})]}),e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[e.jsx(qr,{className:"h-3.5 w-3.5"}),e.jsxs("span",{children:[s.steps.length," steps · ",s.outcome]})]}),t&&i?e.jsxs("div",{className:"mt-auto space-y-3",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between text-xs text-muted-foreground mb-1",children:[e.jsx("span",{className:"truncate pr-2",children:t.run_name}),e.jsxs("span",{className:"flex-shrink-0",children:["Step ",Math.min(i.touched+1,i.total)," of ",i.total]})]}),e.jsx("div",{className:"h-2 rounded-full bg-muted overflow-hidden",children:e.jsx("div",{className:"h-full bg-primary transition-all",style:{width:`${i.pct}%`}})})]}),e.jsxs($,{className:"w-full",onClick:()=>r(t),children:["Continue ",e.jsx(ei,{className:"h-4 w-4 ml-1"})]})]}):e.jsx("div",{className:"mt-auto",children:e.jsxs($,{className:"w-full",onClick:()=>n(s),children:["Start Workflow ",e.jsx(ei,{className:"h-4 w-4 ml-1"})]})})]})}function EHt({workflow:s,onClose:t,onStart:n}){const[r,a]=j.useState(""),[i,l]=j.useState(!1);j.useEffect(()=>{a(""),l(!1)},[s==null?void 0:s.id]);const o=async()=>{s&&(l(!0),await n(s,r.trim()||s.title),l(!1))};return e.jsx(zs,{open:!!s,onOpenChange:c=>!c&&t(),children:e.jsxs(Os,{className:"sm:max-w-md",children:[e.jsxs(Us,{children:[e.jsx(Bs,{children:s==null?void 0:s.title}),e.jsxs(Ir,{children:[s==null?void 0:s.steps.length," steps · your progress saves automatically so you can come back any time."]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"workflow-run-name",children:s==null?void 0:s.namePrompt}),e.jsx(pe,{id:"workflow-run-name",value:r,onChange:c=>a(c.target.value),placeholder:s==null?void 0:s.namePlaceholder,onKeyDown:c=>{c.key==="Enter"&&o()},autoFocus:!0}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"This is just so you recognize it later. You can change it any time."})]}),e.jsxs(Ar,{children:[e.jsx($,{variant:"outline",onClick:t,disabled:i,children:"Cancel"}),e.jsx($,{onClick:o,disabled:i,children:i?"Starting…":"Start workflow"})]})]})})}function gnn(){const s=Qn(),[t,n]=gc(),{items:r,isFavorite:a,toggleFavorite:i,openItem:l,search:o}=fie(),{isAdmin:c}=vs(),{activeRuns:d,startRun:u}=J6e(),h=t.get("goal"),m=t.get("category")??null,[f,g]=j.useState(t.get("q")??""),[x,y]=j.useState(null);j.useEffect(()=>{g(t.get("q")??"")},[t]);const v=(E,I)=>{const P=new URLSearchParams(t);I?P.set(E,I):P.delete(E),n(P,{replace:!0})},b=()=>{const E=new URLSearchParams(t);E.delete("category"),E.delete("goal"),E.delete("q"),n(E,{replace:!0}),g("")},w=j.useMemo(()=>{let E=r;return h&&(E=E.filter(I=>I.goals.includes(h))),m&&(E=E.filter(I=>I.categories.includes(m))),f.trim()&&(E=o(f,E)),E},[r,h,m,f,o]),S=j.useMemo(()=>h||m||f.trim()?null:zTe.map(E=>({goal:E,apps:r.filter(I=>I.goals.includes(E.id))})).filter(E=>E.apps.length>0),[r,h,m,f]),C=h?zTe.find(E=>E.id===h):null;return e.jsxs("div",{className:"space-y-8",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold text-foreground",children:"Browse apps"}),e.jsx("p",{className:"text-muted-foreground mt-1",children:"Every LevelUp app in one place, grouped by what it helps you get done."})]}),e.jsxs("div",{className:"relative max-w-2xl",children:[e.jsx(Kr,{className:"absolute left-4 top-1/2 -translate-y-1/2 h-5 w-5 text-muted-foreground"}),e.jsx(pe,{value:f,onChange:E=>{g(E.target.value),v("q",E.target.value||null)},placeholder:"Search apps or tell us what you want to do…",className:"pl-12 h-12 rounded-2xl"})]}),e.jsx("div",{className:"-mx-4 px-4 sm:mx-0 sm:px-0 overflow-x-auto scrollbar-hide",children:e.jsxs("div",{className:"inline-flex gap-2 min-w-max pb-1",children:[e.jsx("button",{type:"button",onClick:b,className:Pt("px-4 py-2 rounded-full text-sm font-medium border transition-colors whitespace-nowrap",!m&&!h&&!f.trim()?"bg-primary text-primary-foreground border-primary":"bg-card text-muted-foreground border-border hover:text-foreground"),children:"All"}),onn.map(E=>e.jsx("button",{type:"button",onClick:()=>v("category",m===E.id?null:E.id),className:Pt("px-4 py-2 rounded-full text-sm font-medium border transition-colors whitespace-nowrap",m===E.id?"bg-primary text-primary-foreground border-primary":"bg-card text-muted-foreground border-border hover:text-foreground"),children:E.label},E.id))]})}),C&&e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("span",{className:"text-sm text-muted-foreground",children:"Showing apps for"}),e.jsxs("button",{type:"button",onClick:()=>v("goal",null),className:"text-sm font-medium px-3 py-1.5 rounded-full bg-primary/10 text-primary",children:[C.title," ✕"]})]}),c&&!f.trim()&&!m&&e.jsxs("section",{children:[e.jsx("h2",{className:"text-lg font-semibold text-foreground mb-4",children:"Popular workflows"}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:art.map(E=>e.jsx(AHt,{workflow:E,activeRun:d.find(I=>I.workflow_id===E.id),onStart:y,onResume:I=>s(`/apps/workflows/${I.id}`)},E.id))})]}),S?S.map(({goal:E,apps:I})=>e.jsxs("section",{children:[e.jsx("h2",{className:"text-lg font-semibold text-foreground mb-4",children:E.title}),e.jsx(y7,{items:I,isFavorite:a,onOpen:l,onToggleFavorite:i})]},E.id)):w.length>0?e.jsx(y7,{items:w,isFavorite:a,onOpen:l,onToggleFavorite:i}):e.jsxs("div",{className:"text-center py-16 bg-card border border-border rounded-2xl",children:[e.jsx(Kr,{className:"h-10 w-10 text-muted-foreground mx-auto mb-3"}),e.jsx("p",{className:"font-medium text-foreground",children:"No apps matched that"}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:"Try a simpler phrase, like “open house” or “email”."})]}),e.jsx(EHt,{workflow:x,onClose:()=>y(null),onStart:async(E,I)=>{const P=await u(E.id,I);y(null),P&&s(`/apps/workflows/${P.id}`)}})]})}function xnn(){const s=Qn(),{favoriteItems:t,recentItems:n,connectedItems:r,isFavorite:a,toggleFavorite:i,openItem:l}=fie(),o=t.length===0&&n.length===0;return e.jsxs("div",{className:"space-y-8",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold text-foreground",children:"My apps"}),e.jsx("p",{className:"text-muted-foreground mt-1",children:"Your favorites and what you've used recently."})]}),o&&e.jsxs("div",{className:"text-center py-16 bg-card border border-border rounded-2xl",children:[e.jsx(M0,{className:"h-10 w-10 text-muted-foreground mx-auto mb-3"}),e.jsx("p",{className:"font-medium text-foreground",children:"Nothing saved yet"}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1 max-w-sm mx-auto",children:"Tap the bookmark on any app to pin it here for quick access."}),e.jsx($,{className:"mt-4",onClick:()=>s("/apps/browse"),children:"Browse apps"})]}),t.length>0&&e.jsxs("section",{children:[e.jsxs("h2",{className:"text-lg font-semibold text-foreground mb-4 flex items-center gap-2",children:[e.jsx(M0,{className:"h-4 w-4 text-primary"})," Favorites"]}),e.jsx(y7,{items:t,isFavorite:a,onOpen:l,onToggleFavorite:i})]}),n.length>0&&e.jsxs("section",{children:[e.jsxs("h2",{className:"text-lg font-semibold text-foreground mb-4 flex items-center gap-2",children:[e.jsx(da,{className:"h-4 w-4 text-muted-foreground"})," Recently used"]}),e.jsx(y7,{items:n,isFavorite:a,onOpen:l,onToggleFavorite:i})]}),r.length>0&&e.jsxs("section",{children:[e.jsxs("h2",{className:"text-lg font-semibold text-foreground mb-4 flex items-center gap-2",children:[e.jsx(Uj,{className:"h-4 w-4 text-muted-foreground"})," Activated for your account"]}),e.jsx(y7,{items:r,isFavorite:a,onOpen:l,onToggleFavorite:i})]})]})}function ynn(){const{connectedItems:s,isFavorite:t,toggleFavorite:n,openItem:r}=fie();return e.jsxs("div",{className:"space-y-8",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold text-foreground",children:"Connected apps"}),e.jsx("p",{className:"text-muted-foreground mt-1",children:"Partner apps that are activated for your LevelUp account. Open one and you're signed in automatically."})]}),s.length===0?e.jsxs("div",{className:"text-center py-16 bg-card border border-border rounded-2xl",children:[e.jsx(bd,{className:"h-10 w-10 text-muted-foreground mx-auto mb-3"}),e.jsx("p",{className:"font-medium text-foreground",children:"No connected apps yet"}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1 max-w-sm mx-auto",children:"Connected apps appear here once they're activated for your account."})]}):e.jsx(y7,{items:s,isFavorite:t,onOpen:r,onToggleFavorite:n})]})}function vnn(){const s=Qn(),{activeRuns:t,completedRuns:n,startRun:r,reopenRun:a,deleteRun:i}=J6e(),[l,o]=j.useState(null);return e.jsxs("div",{className:"space-y-8",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold text-foreground",children:"Workflows"}),e.jsx("p",{className:"text-muted-foreground mt-1",children:"Step-by-step playbooks that walk you through the whole job. Your progress saves as you go."})]}),t.length>0&&e.jsxs("section",{children:[e.jsx("h2",{className:"text-lg font-semibold text-foreground mb-4",children:"In progress"}),e.jsx("div",{className:"space-y-3",children:t.map(c=>{const d=nB[c.workflow_id],u=Q6e(c);return e.jsxs("div",{className:"bg-card border border-border rounded-2xl p-4 flex items-center gap-4",children:[e.jsxs("button",{type:"button",onClick:()=>s(`/apps/workflows/${c.id}`),className:"flex-1 min-w-0 text-left",children:[e.jsx("p",{className:"font-medium text-foreground truncate",children:c.run_name}),e.jsxs("p",{className:"text-sm text-muted-foreground truncate",children:[d==null?void 0:d.title," · Step ",Math.min(u.touched+1,u.total)," of ",u.total]}),e.jsx("div",{className:"h-1.5 rounded-full bg-muted overflow-hidden mt-3",children:e.jsx("div",{className:"h-full bg-primary",style:{width:`${u.pct}%`}})})]}),e.jsx($,{onClick:()=>s(`/apps/workflows/${c.id}`),children:"Continue"})]},c.id)})})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-lg font-semibold text-foreground mb-4",children:"Start a workflow"}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:art.map(c=>e.jsx(AHt,{workflow:c,onStart:o,onResume:d=>s(`/apps/workflows/${d.id}`)},c.id))})]}),n.length>0&&e.jsxs("section",{children:[e.jsxs("h2",{className:"text-lg font-semibold text-foreground mb-4 flex items-center gap-2",children:[e.jsx(qr,{className:"h-4 w-4 text-emerald-600"})," Completed"]}),e.jsx("div",{className:"space-y-2",children:n.map(c=>{var d;return e.jsxs("div",{className:"bg-card border border-border rounded-xl p-4 flex items-center gap-3",children:[e.jsxs("button",{type:"button",onClick:()=>s(`/apps/workflows/${c.id}`),className:"flex-1 min-w-0 text-left",children:[e.jsx("p",{className:"font-medium text-foreground truncate",children:c.run_name}),e.jsx("p",{className:"text-sm text-muted-foreground truncate",children:(d=nB[c.workflow_id])==null?void 0:d.title})]}),e.jsxs($,{variant:"ghost",size:"sm",onClick:()=>a(c),children:[e.jsx(Ex,{className:"h-4 w-4 mr-1"})," Reopen"]}),e.jsx($,{variant:"ghost",size:"icon","aria-label":"Delete workflow",onClick:()=>i(c.id),children:e.jsx(Wn,{className:"h-4 w-4 text-muted-foreground"})})]},c.id)})})]}),e.jsx(EHt,{workflow:l,onClose:()=>o(null),onStart:async(c,d)=>{const u=await r(c.id,d);o(null),u&&s(`/apps/workflows/${u.id}`)}})]})}function bnn(){const{runId:s}=Wi(),t=Qn(),{runs:n,loading:r,setStep:a,renameRun:i,reopenRun:l,deleteRun:o}=J6e(),{items:c,openItem:d}=fie(),[u,h]=j.useState(!1),[m,f]=j.useState(""),g=j.useMemo(()=>n.find(w=>w.id===s),[n,s]),x=g?nB[g.workflow_id]:void 0;if(r)return e.jsx("p",{className:"text-muted-foreground",children:"Loading…"});if(!g||!x)return e.jsxs("div",{className:"text-center py-16 bg-card border border-border rounded-2xl",children:[e.jsx("p",{className:"font-medium text-foreground",children:"This workflow isn't available"}),e.jsx($,{className:"mt-4",onClick:()=>t("/apps/workflows"),children:"Back to workflows"})]});const y=Q6e(g),v=x.icon,b=w=>{if(!w)return;const S=c.find(E=>E.kind==="tool"&&E.id===w);if(S){d(S);return}const C=f_t[w];C&&t(C.path)};return e.jsxs("div",{className:"space-y-6 max-w-3xl",children:[e.jsxs("button",{type:"button",onClick:()=>t("/apps/workflows"),className:"inline-flex items-center gap-1 text-sm text-muted-foreground hover:text-foreground",children:[e.jsx(qa,{className:"h-4 w-4"})," All workflows"]}),e.jsxs("div",{className:"bg-card border border-border rounded-2xl p-5",children:[e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx("div",{className:Pt("w-12 h-12 rounded-xl flex items-center justify-center flex-shrink-0",x.color),children:e.jsx(v,{className:"h-6 w-6"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[u?e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(pe,{value:m,onChange:w=>f(w.target.value),autoFocus:!0,onKeyDown:w=>{w.key==="Enter"&&(i(g,m),h(!1))}}),e.jsx($,{size:"sm",onClick:()=>{i(g,m),h(!1)},children:"Save"})]}):e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h1",{className:"text-xl font-bold text-foreground truncate",children:g.run_name}),e.jsx("button",{type:"button","aria-label":"Rename workflow",onClick:()=>{f(g.run_name),h(!0)},className:"text-muted-foreground hover:text-foreground",children:e.jsx(gi,{className:"h-4 w-4"})})]}),e.jsxs("p",{className:"text-sm text-muted-foreground mt-1",children:[x.title," · ",x.description]})]})]}),e.jsxs("div",{className:"mt-5",children:[e.jsxs("div",{className:"flex items-center justify-between text-sm text-muted-foreground mb-2",children:[e.jsxs("span",{children:[y.touched," of ",y.total," steps done"]}),e.jsxs("span",{children:[y.pct,"%"]})]}),e.jsx("div",{className:"h-2 rounded-full bg-muted overflow-hidden",children:e.jsx("div",{className:"h-full bg-primary transition-all",style:{width:`${y.pct}%`}})})]}),g.status==="completed"&&e.jsxs("div",{className:"mt-4 flex items-center justify-between gap-3 rounded-xl bg-emerald-500/10 p-3",children:[e.jsxs("p",{className:"text-sm font-medium text-emerald-700 flex items-center gap-2",children:[e.jsx(qr,{className:"h-4 w-4"})," Workflow complete"]}),e.jsx($,{variant:"outline",size:"sm",onClick:()=>l(g),children:"Reopen"})]})]}),e.jsx("ol",{className:"space-y-3",children:x.steps.map((w,S)=>{const C=g.step_state[w.key],E=w.toolId?f_t[w.toolId]:void 0,I=C==="done",P=C==="skipped";return e.jsx("li",{className:Pt("bg-card border rounded-2xl p-4 sm:p-5 transition-colors",I?"border-emerald-500/40":P?"border-border opacity-70":"border-border"),children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx("div",{className:Pt("w-9 h-9 rounded-full flex items-center justify-center flex-shrink-0 text-sm font-semibold",I?"bg-emerald-500 text-white":P?"bg-muted text-muted-foreground":"bg-primary/10 text-primary"),children:I?e.jsx(la,{className:"h-4 w-4"}):S+1}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:Pt("font-medium text-foreground",(I||P)&&"line-through decoration-muted-foreground/40"),children:w.title}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:w.detail}),E&&e.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:["Uses ",E.name]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2 mt-3",children:[E&&e.jsxs($,{size:"sm",onClick:()=>b(w.toolId),children:["Open ",E.name," ",e.jsx(kr,{className:"h-3.5 w-3.5 ml-1"})]}),e.jsxs($,{size:"sm",variant:I?"secondary":"outline",onClick:()=>a(g,w.key,I?null:"done"),children:[e.jsx(la,{className:"h-3.5 w-3.5 mr-1"}),I?"Done":"Mark done"]}),e.jsxs($,{size:"sm",variant:"ghost",onClick:()=>a(g,w.key,P?null:"skipped"),children:[e.jsx(nee,{className:"h-3.5 w-3.5 mr-1"}),P?"Un-skip":"Skip"]})]})]})]})},w.key)})}),e.jsx("div",{className:"pt-2",children:e.jsxs($,{variant:"ghost",size:"sm",className:"text-muted-foreground",onClick:()=>{o(g.id),t("/apps/workflows")},children:[e.jsx(Wn,{className:"h-4 w-4 mr-1"})," Delete this workflow"]})})]})}const _nn=()=>{const{isAdmin:s}=vs();return e.jsx(Vs,{children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(inn,{}),e.jsxs(vG,{children:[e.jsx(ss,{index:!0,element:e.jsx(pnn,{})}),e.jsx(ss,{path:"browse",element:e.jsx(gnn,{})}),e.jsx(ss,{path:"my-apps",element:e.jsx(xnn,{})}),e.jsx(ss,{path:"connected",element:e.jsx(ynn,{})}),s&&e.jsx(ss,{path:"workflows",element:e.jsx(vnn,{})}),s&&e.jsx(ss,{path:"workflows/:runId",element:e.jsx(bnn,{})}),e.jsx(ss,{path:"*",element:e.jsx(Fd,{to:"/apps",replace:!0})})]})]})})},wnn=()=>{var w;const s=Qn(),{isAdmin:t}=vs(),[n,r]=j.useState(""),[a,i]=j.useState("all"),[l,o]=j.useState("all"),[c,d]=j.useState("grid"),{data:u=[]}=tt({queryKey:["template-categories"],queryFn:async()=>{const{data:S,error:C}=await q.from("template_categories").select("*").order("name");if(C)throw C;return S}}),{data:h=[]}=tt({queryKey:["template-types"],queryFn:async()=>{const{data:S,error:C}=await q.from("template_types").select("*").order("name");if(C)throw C;return S}}),{data:m=[],isLoading:f}=tt({queryKey:["canva-templates",t],queryFn:async()=>{const{data:S,error:C}=await q.from("canva_templates").select(` *, category:template_categories(id, name), type:template_types(id, name) `).order("publish_date",{ascending:!1});if(C)throw C;const{data:E,error:I}=await q.from("template_links").select("*").order("sort_order");if(I)throw I;const P=async G=>{let X=0;const ae=[];for(;;){const{data:ie,error:ne}=await G().range(X,X+1e3-1);if(ne)throw ne;if(!ie||ie.length===0||(ae.push(...ie),ie.length<1e3))break;X+=1e3}return ae},R=await P(()=>q.from("template_likes").select("template_id")),D=await P(()=>q.from("template_comments").select("template_id")),O=new Map;R.forEach(G=>{O.set(G.template_id,(O.get(G.template_id)||0)+1)});const U=new Map;D.forEach(G=>{U.set(G.template_id,(U.get(G.template_id)||0)+1)});const W=new Map;return t&&(await P(()=>q.from("content_engagement_logs").select("resource_id").eq("resource_type","template").eq("action_type","view"))).forEach(Y=>{W.set(Y.resource_id,(W.get(Y.resource_id)||0)+1)}),(S||[]).map(G=>({...G,links:(E||[]).filter(Y=>Y.template_id===G.id)||[],likesCount:O.get(G.id)||0,commentsCount:U.get(G.id)||0,viewsCount:W.get(G.id)||0}))}}),g=m.filter(S=>{var P;const C=S.name.toLowerCase().includes(n.toLowerCase())||((P=S.description)==null?void 0:P.toLowerCase().includes(n.toLowerCase())),E=a==="all"||S.category_id===a,I=l==="all"||S.type_id===l;return C&&E&&I}),x=()=>{r(""),i("all"),o("all")},y=n||a!=="all"||l!=="all",v=(w=[...m].sort((S,C)=>new Date(C.publish_date||C.created_at).getTime()-new Date(S.publish_date||S.created_at).getTime())[0])==null?void 0:w.id,b=S=>{s(`/templates/${S}`)};return e.jsx(Vs,{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"})]}),!f&&m.filter(S=>S.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(Ja,{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:m.filter(S=>S.is_featured).slice(0,4).map(S=>e.jsxs(Ne,{className:"group overflow-hidden hover:shadow-lg transition-all duration-200 cursor-pointer relative",onClick:()=>b(S.id),children:[e.jsxs("div",{className:"aspect-[3/2] relative overflow-hidden bg-muted",children:[S.id===v&&e.jsx(Be,{className:"absolute top-2 left-2 z-10 font-bold border-0 hover:opacity-90",style:{backgroundColor:"#e8c369",color:"#3d2f0a"},children:"NEW!"}),S.preview_image_url?e.jsx("img",{src:S.preview_image_url,alt:S.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(Ie,{className:"p-3",children:[e.jsx("h3",{className:"font-semibold text-foreground line-clamp-1 text-sm",children:S.name}),S.description&&e.jsx("p",{className:"text-xs text-muted-foreground line-clamp-2 mt-1",children:Vte(S.description)})]})]},S.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(Kr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(pe,{placeholder:"Search templates...",value:n,onChange:S=>r(S.target.value),className:"pl-9"})]}),e.jsxs(ms,{value:a,onValueChange:i,children:[e.jsx(us,{className:"w-full sm:w-48",children:e.jsx(fs,{placeholder:"All Categories"})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"all",children:"All Categories"}),u.map(S=>e.jsx(Ge,{value:S.id,children:S.name},S.id))]})]}),e.jsxs(ms,{value:l,onValueChange:o,children:[e.jsx(us,{className:"w-full sm:w-48",children:e.jsx(fs,{placeholder:"All Types"})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"all",children:"All Types"}),h.map(S=>e.jsx(Ge,{value:S.id,children:S.name},S.id))]})]}),e.jsxs("div",{className:"flex gap-2",children:[y&&e.jsx($,{variant:"outline",size:"sm",onClick:x,children:"Clear Filters"}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx($,{variant:c==="grid"?"secondary":"outline",size:"icon",onClick:()=>d("grid"),className:"rounded-full",children:e.jsx(Qf,{className:"h-4 w-4"})}),e.jsx($,{variant:c==="list"?"secondary":"outline",size:"icon",onClick:()=>d("list"),className:"rounded-full",children:e.jsx(P0,{className:"h-4 w-4"})})]})]})]}),e.jsxs("div",{className:"text-sm text-muted-foreground",children:[g.length," template",g.length!==1?"s":""," found"]}),f&&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((S,C)=>e.jsx(Ne,{children:e.jsxs(Ie,{className:"p-4",children:[e.jsx(yn,{className:"aspect-[4/3] w-full rounded-lg mb-4"}),e.jsx(yn,{className:"h-5 w-3/4 mb-2"}),e.jsx(yn,{className:"h-4 w-full mb-4"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(yn,{className:"h-5 w-16"}),e.jsx(yn,{className:"h-5 w-20"})]})]})},C))}),!f&&g.length===0&&e.jsxs("div",{className:"text-center py-12",children:[e.jsx("div",{className:"text-muted-foreground mb-4",children:y?"No templates match your filters":"No templates available yet"}),y&&e.jsx($,{variant:"outline",onClick:x,children:"Clear Filters"})]}),!f&&g.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:g.map(S=>e.jsxs(Ne,{className:`group overflow-hidden hover:shadow-lg transition-all duration-200 cursor-pointer ${c==="list"?"flex flex-row":""}`,onClick:()=>b(S.id),children:[e.jsxs("div",{className:`relative overflow-hidden bg-muted ${c==="list"?"w-48 shrink-0":"aspect-[3/2]"}`,children:[S.id===v&&e.jsx(Be,{className:"absolute top-2 left-2 z-10 font-bold border-0 hover:opacity-90",style:{backgroundColor:"#e8c369",color:"#3d2f0a"},children:"NEW!"}),S.preview_image_url?e.jsx("img",{src:S.preview_image_url,alt:S.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"}),S.links.length>1&&e.jsx("div",{className:"absolute top-2 right-2",children:e.jsxs(Be,{variant:"secondary",className:"gap-1 bg-background/90 backdrop-blur-sm !text-secondary",children:[e.jsx(Ad,{className:"h-3 w-3"}),S.links.length]})})]}),e.jsxs(Ie,{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:S.name}),S.description&&e.jsx("p",{className:"text-sm text-muted-foreground line-clamp-2 mb-3 flex-1",children:Vte(S.description)}),e.jsxs("div",{className:"flex flex-wrap gap-2 mb-3",children:[S.category&&e.jsx(Be,{variant:"secondary",className:"text-xs",children:S.category.name}),S.type&&e.jsx(Be,{variant:"outline",className:"text-xs",children:S.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(Vy,{className:"h-3.5 w-3.5"}),S.likesCount]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Th,{className:"h-3.5 w-3.5"}),S.commentsCount]}),t&&e.jsxs("span",{className:"flex items-center gap-1",title:"Total views (admin only)",children:[e.jsx(Ca,{className:"h-3.5 w-3.5"}),S.viewsCount]})]}),e.jsxs($,{size:"sm",className:"w-full gap-2",onClick:C=>{C.stopPropagation(),b(S.id)},children:[e.jsx(kr,{className:"h-4 w-4"}),"View Template"]})]})]},S.id))})]})})},jnn=()=>{const{templateId:s}=Wi(),t=Qn(),{user:n,isAdmin:r}=vs(),{toast:a}=Bi(),i=Vt(),{trackEngagement:l}=gK(),[o,c]=j.useState(""),{data:d,isLoading:u}=tt({queryKey:["template-detail",s],queryFn:async()=>{const{data:S,error:C}=await q.from("canva_templates").select(` *, category:template_categories(id, name), type:template_types(id, name) `).eq("id",s).single();if(C)throw C;const{data:E}=await q.from("template_links").select("*").eq("template_id",s).order("sort_order"),{data:I}=await q.from("template_guides").select("*").eq("template_id",s).order("sort_order");return{...S,links:E||[],guides:I||[]}},enabled:!!s}),{data:h=[]}=tt({queryKey:["template-linked-toolkits",s],queryFn:async()=>{const{data:S,error:C}=await q.from("resource_kit_templates").select("kit_id, resource_kits:kit_id(id, name, featured_image_url)").eq("template_id",s);if(C)throw C;return(S||[]).map(E=>E.resource_kits).filter(Boolean)},enabled:!!s});j.useEffect(()=>{d&&l("template",d.id,d.name,"view")},[d==null?void 0:d.id]);const{data:m=[]}=tt({queryKey:["template-likes",s],queryFn:async()=>{const{data:S,error:C}=await q.from("template_likes").select("*").eq("template_id",s);if(C)throw C;return S},enabled:!!s}),{data:f=[]}=tt({queryKey:["template-comments",s],queryFn:async()=>{const{data:S,error:C}=await q.from("template_comments").select("*").eq("template_id",s).order("created_at",{ascending:!1});if(C)throw C;const E=[...new Set(S.map(R=>R.user_id))],{data:I}=await q.from("profiles").select("id, name").in("id",E),P=new Map((I==null?void 0:I.map(R=>[R.id,R.name]))||[]);return S.map(R=>({...R,user_name:P.get(R.user_id)||"Unknown User"}))},enabled:!!s}),g=ft({mutationFn:async S=>{const{error:C}=await q.from("template_comments").insert({template_id:s,user_id:n.id,content:S});if(C)throw C},onSuccess:()=>{i.invalidateQueries({queryKey:["template-comments",s]}),c(""),a({title:"Comment added!"})},onError:S=>{a({title:"Error adding comment",description:S.message,variant:"destructive"})}}),x=ft({mutationFn:async S=>{const{error:C}=await q.from("template_comments").delete().eq("id",S);if(C)throw C},onSuccess:()=>{i.invalidateQueries({queryKey:["template-comments",s]}),a({title:"Comment deleted"})}}),y=ft({mutationFn:async()=>{const S=m.find(C=>C.user_id===(n==null?void 0:n.id));if(S){const{error:C}=await q.from("template_likes").delete().eq("id",S.id);if(C)throw C}else{const{error:C}=await q.from("template_likes").insert({template_id:s,user_id:n.id});if(C)throw C}},onSuccess:()=>{i.invalidateQueries({queryKey:["template-likes",s]})}}),v=m.some(S=>S.user_id===(n==null?void 0:n.id)),b=S=>S.split(" ").map(C=>C[0]).join("").toUpperCase().slice(0,2),w=S=>{S.preventDefault(),!(!o.trim()||!n)&&g.mutate(o.trim())};return u?e.jsx(Vs,{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(Vs,{title:d.name,children:e.jsxs("div",{className:"space-y-6 max-w-5xl mx-auto",children:[e.jsx($,{variant:"ghost",size:"sm",asChild:!0,className:"gap-2",children:e.jsxs(wr,{to:"/templates",children:[e.jsx(qa,{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(Be,{variant:"secondary",children:d.category.name}),d.type&&e.jsx(Be,{variant:"outline",children:d.type.name})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[r&&e.jsx($,{variant:"outline",className:"gap-2 rounded-full",asChild:!0,children:e.jsxs(wr,{to:`/admin/templates?edit=${d.id}`,children:[e.jsx(gi,{className:"h-4 w-4"}),e.jsx("span",{children:"Edit"})]})}),e.jsx(vK,{resourceType:"template",resourceId:d.id,resourceTitle:d.name,size:"default",className:"rounded-full"}),e.jsxs($,{variant:v?"default":"outline",className:"gap-2 rounded-full",onClick:()=>y.mutate(),disabled:!n||y.isPending,children:[e.jsx(Vy,{className:`h-4 w-4 ${v?"fill-current":""}`}),m.length," ",m.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(Ne,{children:e.jsxs(Ie,{className:"pt-6",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 mb-4",children:[e.jsx(Ad,{className:"h-4 w-4"}),d.links.length===1?"Template Link":"Template Links"]}),e.jsx("div",{className:"grid gap-2",children:d.links.map(S=>e.jsxs($,{variant:"outline",className:"w-full justify-between gap-2 h-auto py-3",onClick:()=>{l("template",d.id,d.name,"click_canva"),window.open(S.canva_share_link,"_blank")},children:[e.jsx("span",{className:"font-medium",children:S.title}),e.jsx(kr,{className:"h-4 w-4 text-muted-foreground"})]},S.id))})]})}),d.video_url&&e.jsx(Ne,{children:e.jsx(Ie,{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(Ne,{children:e.jsxs(Ie,{className:"pt-6",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 mb-4",children:[e.jsx(Jr,{className:"h-4 w-4"}),"Guide Files"]}),e.jsx("div",{className:"grid gap-2",children:d.guides.map(S=>e.jsxs($,{variant:"outline",className:"w-full justify-between gap-2 h-auto py-3",onClick:()=>{l("template",d.id,d.name,"click_pdf"),window.open(S.file_url,"_blank")},children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Jr,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"font-medium",children:S.name}),S.file_size&&e.jsxs("span",{className:"text-xs text-muted-foreground",children:["(",(S.file_size/1024).toFixed(0)," KB)"]})]}),e.jsx(di,{className:"h-4 w-4 text-muted-foreground"})]},S.id))})]})}),h.length>0&&e.jsx(Ne,{children:e.jsxs(Ie,{className:"pt-6",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 mb-4",children:[e.jsx(vm,{className:"h-4 w-4"}),"Related Toolkits"]}),e.jsx("div",{className:"grid gap-2",children:h.map(S=>e.jsxs($,{variant:"outline",className:"w-full justify-start gap-3 h-auto py-3",onClick:()=>t(`/toolbox/${S.id}`),children:[S.featured_image_url?e.jsx("img",{src:S.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(vm,{className:"h-4 w-4 text-muted-foreground"})}),e.jsx("span",{className:"font-medium",children:S.name})]},S.id))})]})}),e.jsx(Gc,{}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 text-lg",children:[e.jsx(Th,{className:"h-5 w-5"}),"Comments (",f.length,")"]}),n?e.jsxs("form",{onSubmit:w,className:"flex gap-2",children:[e.jsx(Rs,{placeholder:"Add a comment...",value:o,onChange:S=>c(S.target.value),className:"min-h-[80px] resize-none flex-1"}),e.jsx($,{type:"submit",size:"icon",className:"h-10 w-10",disabled:!o.trim()||g.isPending,children:e.jsx(Yr,{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:f.length===0?e.jsx(Ne,{children:e.jsx(Ie,{className:"py-8 text-center",children:e.jsx("p",{className:"text-muted-foreground",children:"No comments yet. Be the first to share your thoughts!"})})}):f.map(S=>e.jsx(Ne,{children:e.jsx(Ie,{className:"pt-4 pb-4",children:e.jsxs("div",{className:"flex gap-3",children:[e.jsx(Oa,{className:"h-10 w-10 flex-shrink-0",children:e.jsx(za,{className:"text-sm",children:b(S.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:S.user_name}),e.jsx("span",{className:"text-sm text-muted-foreground",children:mu(new Date(S.created_at),{addSuffix:!0})}),S.user_id===(n==null?void 0:n.id)&&e.jsx($,{variant:"ghost",size:"icon",className:"h-6 w-6 ml-auto",onClick:()=>x.mutate(S.id),children:e.jsx(Wn,{className:"h-3 w-3 text-muted-foreground"})})]}),e.jsx("p",{className:"text-sm whitespace-pre-wrap",children:S.content})]})]})})},S.id))})]})]})}):e.jsx(Vs,{title:"Templates",children:e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(Ad,{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($,{asChild:!0,className:"mt-4",children:e.jsx(wr,{to:"/templates",children:"Back to Templates"})})]})})},p_t=({program:s,enrolled:t})=>{const{notOpenYet:n,closed:r,opensLabel:a}=E6e(s);return e.jsxs(Ne,{className:"group overflow-hidden border-border/60 transition-all hover:border-primary/40 hover:shadow-lg",children:[e.jsxs("div",{className:"relative aspect-[16/9] overflow-hidden bg-muted",children:[s.cover_image_url?e.jsx("img",{src:s.cover_image_url,alt:`${s.name} program cover`,loading:"lazy",className:"h-full w-full object-cover transition-transform duration-500 group-hover:scale-105"}):e.jsx("div",{className:"flex h-full w-full items-center justify-center bg-gradient-to-br from-primary/15 via-background to-accent/20",children:e.jsx(Nn,{className:"h-10 w-10 text-primary/60"})}),e.jsxs("div",{className:"absolute left-3 top-3 flex gap-2",children:[s.is_featured&&e.jsx(Be,{className:"shadow-sm",children:"Featured"}),t&&e.jsxs(Be,{variant:"secondary",className:"shadow-sm",children:[e.jsx(qr,{className:"mr-1 h-3 w-3"})," Enrolled"]})]})]}),e.jsxs(Ie,{className:"space-y-4 p-5",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("h2",{className:"text-lg font-semibold leading-tight",children:s.name}),s.subtitle&&e.jsx("p",{className:"text-sm text-muted-foreground",children:s.subtitle})]}),e.jsxs("div",{className:"flex flex-wrap gap-x-4 gap-y-1.5 text-xs text-muted-foreground",children:[e.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[e.jsx(da,{className:"h-3.5 w-3.5"}),s.duration_weeks," weeks"]}),s.kickoff_at&&e.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[e.jsx(Kc,{className:"h-3.5 w-3.5"}),"Starts ",sh(s.kickoff_at)]}),e.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[e.jsx(Zn,{className:"h-3.5 w-3.5"}),s.capacity," seats"]})]}),e.jsxs("div",{className:"flex items-center justify-between border-t border-border/60 pt-4",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-lg font-semibold",children:s.payment_mode==="free"?"Included":Cg(s.price_cents,s.currency)}),n?e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Enrollment opens ",a]}):s.payment_mode!=="free"?e.jsxs("p",{className:"text-xs text-muted-foreground",children:["One-time payment for the ",hse(s.duration_weeks)," — no subscription",s.charge_at?` · charged ${sh(s.charge_at)}`:""]}):null]}),e.jsx($,{asChild:!0,size:"sm",children:e.jsxs(wr,{to:t?`/programs/${s.slug}/workspace`:`/programs/${s.slug}`,children:[t?"Open program":n?"Preview details":"View details",e.jsx(ei,{className:"ml-1.5 h-4 w-4"})]})})]})]})]})},Nnn=()=>{const{data:s=[],isLoading:t}=WUt(),{data:n=[]}=unt(),r=new Set(n.filter(l=>LG(l)).map(l=>l.program_id)),a=s.filter(l=>r.has(l.id)),i=s.filter(l=>!r.has(l.id));return e.jsx(Vs,{children:e.jsxs("div",{className:"mx-auto w-full max-w-6xl space-y-10 p-4 md:p-8",children:[e.jsxs("header",{className:"space-y-3",children:[e.jsx("p",{className:"text-xs font-semibold uppercase tracking-[0.2em] text-primary",children:"LevelUp Programs"}),e.jsx("h1",{className:"text-3xl font-bold tracking-tight md:text-4xl",children:"Go deeper than the membership"}),e.jsx("p",{className:"max-w-2xl text-muted-foreground",children:"Time-bound coaching programs, masterminds and challenges built to move one specific part of your business forward — with a real cohort, a real roadmap and real accountability."})]}),t?e.jsx("div",{className:"grid gap-6 md:grid-cols-2 lg:grid-cols-3",children:[0,1,2].map(l=>e.jsx(yn,{className:"h-80 rounded-xl"},l))}):e.jsxs(e.Fragment,{children:[a.length>0&&e.jsxs("section",{className:"space-y-4",children:[e.jsx("h2",{className:"text-sm font-semibold uppercase tracking-wider text-muted-foreground",children:"Your programs"}),e.jsx("div",{className:"grid gap-6 md:grid-cols-2 lg:grid-cols-3",children:a.map(l=>e.jsx(p_t,{program:l,enrolled:!0},l.id))})]}),e.jsxs("section",{className:"space-y-4",children:[a.length>0&&e.jsx("h2",{className:"text-sm font-semibold uppercase tracking-wider text-muted-foreground",children:"Open for enrollment"}),i.length===0&&a.length===0?e.jsx(Ne,{className:"border-dashed",children:e.jsxs(Ie,{className:"flex flex-col items-center gap-3 p-12 text-center",children:[e.jsx(Nn,{className:"h-8 w-8 text-muted-foreground"}),e.jsx("p",{className:"font-medium",children:"No programs are open right now"}),e.jsx("p",{className:"max-w-md text-sm text-muted-foreground",children:"New cohorts are announced inside the Hub. Check back soon — seats are limited when they open."})]})}):e.jsx("div",{className:"grid gap-6 md:grid-cols-2 lg:grid-cols-3",children:i.map(l=>e.jsx(p_t,{program:l,enrolled:!1},l.id))})]})]})]})})},knn=s=>{const t=s.match(/(?:youtube\.com\/(?:watch\?v=|embed\/|shorts\/|live\/)|youtu\.be\/)([A-Za-z0-9_-]{11})/);if(t)return`https://www.youtube.com/embed/${t[1]}?autoplay=1&rel=0&modestbranding=1`;const n=s.match(/vimeo\.com\/(?:video\/)?(\d+)/);if(n)return`https://player.vimeo.com/video/${n[1]}?autoplay=1`;const r=s.match(/loom\.com\/(?:share|embed)\/([A-Za-z0-9]+)/);return r?`https://www.loom.com/embed/${r[1]}`:null},Snn=({url:s,headline:t,posterUrl:n})=>{const[r,a]=j.useState(!1),i=(s||"").trim();if(!i)return null;const l=knn(i),o=!l&&/\.(mp4|webm|mov|m4v)(\?|$)/i.test(i);return!l&&!o?null:e.jsxs("section",{className:"space-y-3",children:[e.jsx("div",{className:"relative overflow-hidden rounded-2xl border border-border/60 bg-black shadow-lg",children:e.jsx("div",{className:"aspect-video w-full",children:r?o?e.jsx("video",{src:i,controls:!0,autoPlay:!0,className:"h-full w-full",playsInline:!0}):e.jsx("iframe",{src:l,title:t||"Program promo video",className:"h-full w-full",allow:"accelerometer; autoplay; clipboard-write; encrypted-media; picture-in-picture; fullscreen",allowFullScreen:!0}):e.jsxs("button",{type:"button",onClick:()=>a(!0),className:"group relative h-full w-full","aria-label":"Play program promo video",children:[n?e.jsx("img",{src:n,alt:"",className:"h-full w-full object-cover opacity-70 transition group-hover:opacity-60"}):e.jsx("div",{className:"h-full w-full bg-gradient-to-br from-primary/30 via-black to-accent/30"}),e.jsxs("span",{className:"absolute inset-0 flex flex-col items-center justify-center gap-3",children:[e.jsx(tf,{className:"h-16 w-16 text-white/90 transition group-hover:scale-110"}),e.jsx("span",{className:"rounded-full bg-white/10 px-4 py-1 text-xs font-medium uppercase tracking-widest text-white/90 backdrop-blur",children:"Watch the program video"})]})]})})}),t&&e.jsx("p",{className:"text-center text-sm font-medium text-muted-foreground",children:t})]})};var Cnn=Object.defineProperty,pie=(s,t)=>Cnn(s,"name",{value:t,configurable:!0}),irt="Collapsible",[Ann,THt]=tp(irt),[Enn,ort]=Ann(irt),Tnn=j.forwardRef(pie(function(t,n){const{__scopeCollapsible:r,open:a,defaultOpen:i,disabled:l,onOpenChange:o,...c}=t,[d,u]=fy({prop:a,defaultProp:i??!1,onChange:o,caller:irt});return e.jsx(Enn,{scope:r,disabled:l,contentId:my(),open:d,onOpenToggle:j.useCallback(()=>u(h=>!h),[u]),children:e.jsx(Ei.div,{"data-state":eRe(d),"data-disabled":l?"":void 0,...c,ref:n})})},"Collapsible")),Mnn="CollapsibleTrigger",MHt=j.forwardRef(pie(function(t,n){const{__scopeCollapsible:r,...a}=t,i=ort(Mnn,r);return e.jsx(Ei.button,{type:"button","aria-controls":i.open?i.contentId:void 0,"aria-expanded":i.open||!1,"data-state":eRe(i.open),"data-disabled":i.disabled?"":void 0,disabled:i.disabled,...a,ref:n,onClick:Ra(t.onClick,i.onOpenToggle)})},"CollapsibleTrigger")),PHt="CollapsibleContent",IHt=j.forwardRef(pie(function(t,n){const{forceMount:r,...a}=t,i=ort(PHt,t.__scopeCollapsible);return e.jsx(xy,{present:r||i.open,children:({present:l})=>e.jsx(Pnn,{...a,ref:n,present:l})})},"CollapsibleContent")),Pnn=j.forwardRef(pie(function(t,n){const{__scopeCollapsible:r,present:a,children:i,...l}=t,o=ort(PHt,r),[c,d]=j.useState(a),u=j.useRef(null),h=Vo(n,u),m=j.useRef(0),f=m.current,g=j.useRef(0),x=g.current,y=o.open||c,v=j.useRef(y),b=j.useRef(void 0);return j.useEffect(()=>{const w=requestAnimationFrame(()=>v.current=!1);return()=>cancelAnimationFrame(w)},[]),Ef(()=>{const w=u.current;if(w){b.current=b.current||{transitionDuration:w.style.transitionDuration,animationName:w.style.animationName},w.style.transitionDuration="0s",w.style.animationName="none";const S=w.getBoundingClientRect();m.current=S.height,g.current=S.width,v.current||(w.style.transitionDuration=b.current.transitionDuration,w.style.animationName=b.current.animationName),d(a)}},[o.open,a]),e.jsx(Ei.div,{"data-state":eRe(o.open),"data-disabled":o.disabled?"":void 0,id:o.contentId,hidden:!y,...l,ref:h,style:{"--radix-collapsible-content-height":f?`${f}px`:void 0,"--radix-collapsible-content-width":x?`${x}px`:void 0,...t.style},children:y&&i})},"CollapsibleContentImpl"));function eRe(s){return s?"open":"closed"}pie(eRe,"getState");var LHt=Tnn,Inn=MHt,Lnn=IHt,Rnn=Object.defineProperty,w2=(s,t)=>Rnn(s,"name",{value:t,configurable:!0}),d3="Accordion",Dnn=["Home","End","ArrowDown","ArrowUp","ArrowLeft","ArrowRight"],[lrt,Fnn,Onn]=LB(d3),[tRe,ESr]=tp(d3,[Onn,THt]),crt=THt(),znn=j.forwardRef(w2(function(t,n){const{type:r,...a}=t,i=a,l=a;return e.jsx(lrt.Provider,{scope:t.__scopeAccordion,children:r==="multiple"?e.jsx(qnn,{...l,ref:n}):e.jsx(Unn,{...i,ref:n})})},"Accordion")),[RHt,Bnn]=tRe(d3),[DHt,$nn]=tRe(d3,{collapsible:!1}),Unn=j.forwardRef(w2(function(t,n){const{value:r,defaultValue:a,onValueChange:i=w2(()=>{},"onValueChange"),collapsible:l=!1,...o}=t,[c,d]=fy({prop:r,defaultProp:a??"",onChange:i,caller:d3});return e.jsx(RHt,{scope:t.__scopeAccordion,value:j.useMemo(()=>c?[c]:[],[c]),onItemOpen:d,onItemClose:j.useCallback(()=>l&&d(""),[l,d]),children:e.jsx(DHt,{scope:t.__scopeAccordion,collapsible:l,children:e.jsx(FHt,{...o,ref:n})})})},"AccordionImplSingle")),qnn=j.forwardRef(w2(function(t,n){const{value:r,defaultValue:a,onValueChange:i=w2(()=>{},"onValueChange"),...l}=t,[o,c]=fy({prop:r,defaultProp:a??[],onChange:i,caller:d3}),d=j.useCallback(h=>c((m=[])=>[...m,h]),[c]),u=j.useCallback(h=>c((m=[])=>m.filter(f=>f!==h)),[c]);return e.jsx(RHt,{scope:t.__scopeAccordion,value:o,onItemOpen:d,onItemClose:u,children:e.jsx(DHt,{scope:t.__scopeAccordion,collapsible:!0,children:e.jsx(FHt,{...l,ref:n})})})},"AccordionImplMultiple")),[Vnn,sRe]=tRe(d3),FHt=j.forwardRef(w2(function(t,n){const{__scopeAccordion:r,disabled:a,dir:i,orientation:l="vertical",...o}=t,c=j.useRef(null),d=Vo(c,n),u=Fnn(r),m=l3(i)==="ltr",f=Ra(t.onKeyDown,g=>{var R;if(!Dnn.includes(g.key))return;const x=g.target,y=u().filter(D=>{var O;return!((O=D.ref.current)!=null&&O.disabled)}),v=y.findIndex(D=>D.ref.current===x),b=y.length;if(v===-1)return;g.preventDefault();let w=v;const S=0,C=b-1,E=w2(()=>{w=v+1,w>C&&(w=S)},"moveNext"),I=w2(()=>{w=v-1,w{m?o.onItemOpen(a):o.onItemClose(a)}})})},"AccordionItem")),Wnn="AccordionHeader",Knn=j.forwardRef(w2(function(t,n){const{__scopeAccordion:r,...a}=t,i=sRe(d3,r),l=drt(Wnn,r);return e.jsx(Ei.h3,{"data-orientation":i.orientation,"data-state":urt(l.open),"data-disabled":l.disabled?"":void 0,...a,ref:n})},"AccordionHeader")),g_t="AccordionTrigger",Ynn=j.forwardRef(w2(function(t,n){const{__scopeAccordion:r,...a}=t,i=sRe(d3,r),l=drt(g_t,r),o=$nn(g_t,r),c=crt(r);return e.jsx(lrt.ItemSlot,{scope:r,children:e.jsx(Inn,{"aria-disabled":l.open&&!o.collapsible||void 0,"data-orientation":i.orientation,id:l.triggerId,...c,...a,ref:n})})},"AccordionTrigger")),Znn="AccordionContent",Xnn=j.forwardRef(w2(function(t,n){const{__scopeAccordion:r,...a}=t,i=sRe(d3,r),l=drt(Znn,r),o=crt(r);return e.jsx(Lnn,{role:"region","aria-labelledby":l.triggerId,"data-orientation":i.orientation,...o,...a,ref:n,style:{"--radix-accordion-content-height":"var(--radix-collapsible-content-height)","--radix-accordion-content-width":"var(--radix-collapsible-content-width)",...t.style}})},"AccordionContent"));function urt(s){return s?"open":"closed"}w2(urt,"getState");var Qnn=znn,Jnn=Gnn,ern=Knn,OHt=Ynn,zHt=Xnn;const WB=Qnn,p6=j.forwardRef(({className:s,...t},n)=>e.jsx(Jnn,{ref:n,className:Pt("border-b",s),...t}));p6.displayName="AccordionItem";const g6=j.forwardRef(({className:s,children:t,...n},r)=>e.jsx(ern,{className:"flex",children:e.jsxs(OHt,{ref:r,className:Pt("flex flex-1 items-center justify-between py-4 font-medium transition-all hover:underline [&[data-state=open]>svg]:rotate-180",s),...n,children:[t,e.jsx(Tl,{className:"h-4 w-4 shrink-0 transition-transform duration-200"})]})}));g6.displayName=OHt.displayName;const x6=j.forwardRef(({className:s,children:t,...n},r)=>e.jsx(zHt,{ref:r,className:"overflow-hidden text-sm transition-all data-[state=closed]:animate-accordion-up data-[state=open]:animate-accordion-down",...n,children:e.jsx("div",{className:Pt("pb-4 pt-0",s),children:t})}));x6.displayName=zHt.displayName;const trn=({programId:s,opensLabel:t})=>{const{data:n,isLoading:r}=hWs(s),a=mWs(s),i=!!n;return e.jsxs("div",{className:"flex flex-col gap-3 rounded-xl border border-primary/30 bg-primary/5 p-4 sm:flex-row sm:items-center sm:justify-between",children:[e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(QS,{className:"mt-0.5 h-4 w-4 shrink-0 text-primary"}),e.jsxs("div",{className:"space-y-0.5 text-sm",children:[e.jsx("p",{className:"font-semibold",children:i?"You're on the notify list":"Want a heads-up when enrollment opens?"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:i?`We'll email you the moment seats go live${t?` (${t})`:""}.`:`Seats are limited — we'll email you the moment enrollment opens${t?` ${t}`:""}.`})]})]}),e.jsxs($,{variant:i?"outline":"default",size:"sm",disabled:r||a.isPending,onClick:()=>a.mutate(!i),className:"shrink-0",children:[a.isPending?e.jsx(kt,{className:"mr-2 h-4 w-4 animate-spin"}):i?e.jsx(la,{className:"mr-2 h-4 w-4"}):e.jsx(QS,{className:"mr-2 h-4 w-4"}),i?"You're on the list":"Notify me"]})]})},srn=()=>{const{slug:s}=Wi(),{data:t,isLoading:n}=dnt(s),{data:r}=KUt(t==null?void 0:t.id),{data:a}=hnt(t==null?void 0:t.id),i=LG(a),l=(t==null?void 0:t.sales_copy)||{},o=l.outcomes||[],c=l.included||[],d=l.for_who||[],u=l.not_for||[],h=l.faqs||[],m=l.phases||[];if(n)return e.jsx(Vs,{children:e.jsxs("div",{className:"mx-auto max-w-5xl space-y-6 p-8",children:[e.jsx(yn,{className:"h-64 w-full rounded-xl"}),e.jsx(yn,{className:"h-40 w-full rounded-xl"})]})});if(!t)return e.jsx(Vs,{children:e.jsxs("div",{className:"mx-auto max-w-2xl p-12 text-center",children:[e.jsx("h1",{className:"text-2xl font-bold",children:"Program not found"}),e.jsx("p",{className:"mt-2 text-muted-foreground",children:"This program may have been closed or unpublished."}),e.jsx($,{asChild:!0,className:"mt-6",children:e.jsx(wr,{to:"/programs",children:"Back to Programs"})})]})});const f=typeof r=="number"&&r<=0&&!i,{notOpenYet:g,closed:x,opensLabel:y}=E6e(t),v=!i&&(f||x||g),b=i?"Open your program":g?`Enrollment opens ${sh(t.enrollment_open_at)}`:f?"Cohort is full":x?"Enrollment closed":t.payment_mode==="delayed"?"Reserve my seat":"Enroll now",w=i?`/programs/${t.slug}/workspace`:`/programs/${t.slug}/enroll`;return e.jsxs(Vs,{children:[e.jsxs(Ml,{children:[e.jsx("title",{children:`${t.name} | LevelUp Programs`}),e.jsx("meta",{name:"description",content:(t.short_description||t.subtitle||t.name).slice(0,155)})]}),e.jsxs("div",{className:"mx-auto w-full max-w-5xl space-y-12 p-4 md:p-8",children:[e.jsxs("section",{className:"overflow-hidden rounded-2xl border border-border/60 bg-card",children:[e.jsx("div",{className:"relative",children:t.promo_video_url?e.jsx(Snn,{url:t.promo_video_url,headline:t.promo_video_headline,posterUrl:t.hero_image_url||t.cover_image_url}):t.hero_image_url||t.cover_image_url?e.jsx("img",{src:t.hero_image_url||t.cover_image_url,alt:`${t.name} hero`,className:"h-56 w-full object-cover md:h-72"}):e.jsx("div",{className:"h-40 w-full bg-gradient-to-br from-primary/20 via-background to-accent/20 md:h-56"})}),e.jsxs("div",{className:"space-y-6 p-6 md:p-8",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs(Be,{variant:"secondary",children:[t.duration_weeks,"-week program"]}),typeof r=="number"&&!i&&e.jsx(Be,{variant:r<=10?"destructive":"outline",children:r>0?`${r} of ${t.capacity} seats left`:"Full"}),i&&e.jsxs(Be,{children:[e.jsx(qr,{className:"mr-1 h-3 w-3"})," You're enrolled"]})]}),e.jsx("h1",{className:"text-3xl font-bold tracking-tight md:text-4xl",children:t.name}),t.subtitle&&e.jsx("p",{className:"text-lg text-muted-foreground",children:t.subtitle}),t.tagline&&e.jsx("p",{className:"text-sm font-medium text-primary",children:t.tagline})]}),e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2 lg:grid-cols-4",children:[e.jsxs("div",{className:"rounded-lg border border-border/60 p-3",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Investment"}),e.jsx("p",{className:"mt-1 font-semibold",children:t.payment_mode==="free"?"Included":Cg(t.price_cents,t.currency)}),t.payment_mode!=="free"&&e.jsxs("p",{className:"mt-1 text-xs text-muted-foreground",children:["One-time payment for the ",hse(t.duration_weeks)," — not a subscription"]})]}),e.jsxs("div",{className:"rounded-lg border border-border/60 p-3",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Kickoff"}),e.jsx("p",{className:"mt-1 font-semibold",children:sh(t.kickoff_at,!0)||"To be announced"})]}),e.jsxs("div",{className:"rounded-lg border border-border/60 p-3",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Weekly commitment"}),e.jsxs("p",{className:"mt-1 font-semibold",children:[t.weekly_video_goal," videos / week"]})]}),e.jsxs("div",{className:"rounded-lg border border-border/60 p-3",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Cohort size"}),e.jsxs("p",{className:"mt-1 font-semibold",children:[t.capacity," agents"]})]})]}),t.payment_mode==="delayed"&&t.charge_at&&!i&&e.jsxs("div",{className:"flex items-start gap-3 rounded-lg border border-primary/30 bg-primary/5 p-4",children:[e.jsx(Cv,{className:"mt-0.5 h-4 w-4 shrink-0 text-primary"}),e.jsxs("div",{className:"space-y-1 text-sm",children:[e.jsxs("p",{children:[e.jsxs("span",{className:"font-semibold",children:[KGe(t.price_cents,t.currency,t.duration_weeks),"."]})," ","We save your card today and charge it once on"," ",e.jsx("span",{className:"font-semibold",children:sh(t.charge_at)}),". Cancel any time before then and you won't be billed."]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"No recurring billing, no monthly installments, and no automatic renewal."})]})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsx($,{asChild:!v,size:"lg",disabled:v,children:v?e.jsx("span",{children:b}):e.jsxs(wr,{to:w,children:[b,e.jsx(ei,{className:"ml-2 h-4 w-4"})]})}),e.jsx($,{asChild:!0,variant:"ghost",size:"lg",children:e.jsx(wr,{to:"/programs",children:"All programs"})})]}),g&&!i&&e.jsxs(e.Fragment,{children:[e.jsxs("p",{className:"inline-flex items-center gap-1.5 text-xs text-muted-foreground",children:[e.jsx(Kc,{className:"h-3.5 w-3.5"}),"Enrollment opens ",y]}),e.jsx(trn,{programId:t.id,opensLabel:y})]})]})]}),t.description&&e.jsxs("section",{className:"space-y-3",children:[e.jsx("h2",{className:"text-xl font-semibold",children:"What this program is"}),e.jsx("div",{className:"whitespace-pre-line text-muted-foreground",children:t.description})]}),o.length>0&&e.jsxs("section",{className:"space-y-4",children:[e.jsx("h2",{className:"text-xl font-semibold",children:"What you'll walk away with"}),e.jsx("div",{className:"grid gap-3 sm:grid-cols-2",children:o.map((S,C)=>e.jsxs("div",{className:"flex items-start gap-3 rounded-lg border border-border/60 p-4",children:[e.jsx(qr,{className:"mt-0.5 h-4 w-4 shrink-0 text-primary"}),e.jsx("p",{className:"text-sm",children:S})]},C))})]}),m.length>0&&e.jsxs("section",{className:"space-y-4",children:[e.jsxs("h2",{className:"text-xl font-semibold",children:["How the ",t.duration_weeks," weeks flow"]}),e.jsx("div",{className:"grid gap-4 md:grid-cols-3",children:m.map((S,C)=>e.jsx(Ne,{className:"border-border/60",children:e.jsxs(Ie,{className:"space-y-2 p-5",children:[e.jsxs("p",{className:"text-xs font-semibold uppercase tracking-wider text-primary",children:["Phase ",C+1]}),e.jsx("h3",{className:"font-semibold",children:S.title}),e.jsx("p",{className:"text-sm text-muted-foreground",children:S.detail})]})},C))})]}),c.length>0&&e.jsxs("section",{className:"space-y-4",children:[e.jsx("h2",{className:"text-xl font-semibold",children:"What's included"}),e.jsx("ul",{className:"grid gap-2 sm:grid-cols-2",children:c.map((S,C)=>e.jsxs("li",{className:"flex items-start gap-2.5 text-sm",children:[e.jsx(Nn,{className:"mt-0.5 h-4 w-4 shrink-0 text-primary"}),S]},C))})]}),(d.length>0||u.length>0)&&e.jsxs("section",{className:"grid gap-6 md:grid-cols-2",children:[d.length>0&&e.jsx(Ne,{className:"border-border/60",children:e.jsxs(Ie,{className:"space-y-3 p-5",children:[e.jsx("h3",{className:"font-semibold",children:"This is for you if…"}),e.jsx("ul",{className:"space-y-2 text-sm text-muted-foreground",children:d.map((S,C)=>e.jsxs("li",{className:"flex gap-2",children:[e.jsx(qr,{className:"mt-0.5 h-4 w-4 shrink-0 text-primary"}),S]},C))})]})}),u.length>0&&e.jsx(Ne,{className:"border-border/60",children:e.jsxs(Ie,{className:"space-y-3 p-5",children:[e.jsx("h3",{className:"font-semibold",children:"This isn't for you if…"}),e.jsx("ul",{className:"space-y-2 text-sm text-muted-foreground",children:u.map((S,C)=>e.jsxs("li",{className:"flex gap-2",children:[e.jsx(da,{className:"mt-0.5 h-4 w-4 shrink-0"}),S]},C))})]})})]}),h.length>0&&e.jsxs("section",{className:"space-y-4",children:[e.jsx("h2",{className:"text-xl font-semibold",children:"Questions"}),e.jsx(WB,{type:"single",collapsible:!0,className:"rounded-xl border border-border/60 px-4",children:h.map((S,C)=>e.jsxs(p6,{value:`faq-${C}`,children:[e.jsx(g6,{className:"text-left text-sm font-medium",children:S.q}),e.jsx(x6,{className:"text-sm text-muted-foreground",children:S.a})]},C))})]}),e.jsxs("section",{className:"rounded-2xl border border-border/60 bg-muted/40 p-6 text-center md:p-10",children:[e.jsx(ua,{className:"mx-auto h-8 w-8 text-primary"}),e.jsx("h2",{className:"mt-4 text-2xl font-bold",children:l.closing_headline||"Ready to commit?"}),e.jsx("p",{className:"mx-auto mt-2 max-w-xl text-muted-foreground",children:l.closing_body||`Seats are capped at ${t.capacity} so every member gets attention. Reserve yours and we'll take it from there.`}),e.jsxs("div",{className:"mt-6 flex flex-wrap items-center justify-center gap-3",children:[e.jsx($,{asChild:!v,size:"lg",disabled:v,children:v?e.jsx("span",{children:b}):e.jsxs(wr,{to:w,children:[b,e.jsx(ei,{className:"ml-2 h-4 w-4"})]})}),typeof r=="number"&&r>0&&!i&&e.jsxs("span",{className:"inline-flex items-center gap-1.5 text-sm text-muted-foreground",children:[e.jsx(Zn,{className:"h-4 w-4"}),r," seats remaining"]})]}),!i&&(g?e.jsxs("p",{className:"mt-3 inline-flex items-center gap-1.5 text-xs text-muted-foreground",children:[e.jsx(Kc,{className:"h-3.5 w-3.5"}),"Enrollment opens ",y]}):t.enrollment_close_at?e.jsxs("p",{className:"mt-3 inline-flex items-center gap-1.5 text-xs text-muted-foreground",children:[e.jsx(Kc,{className:"h-3.5 w-3.5"}),"Enrollment closes ",sh(t.enrollment_close_at)]}):null)]})]})]})},Nde=["Your business","Your content","Your goals","Reserve your seat"],nrn=()=>{const{slug:s}=Wi(),t=Qn(),[n,r]=gc(),{user:a}=vs(),{data:i,isLoading:l}=dnt(s),{data:o}=KUt(i==null?void 0:i.id),{data:c,refetch:d}=hnt(i==null?void 0:i.id),{data:u}=YUt(i==null?void 0:i.id),h=qGs(),m=VGs(),f=JGs(),g=eWs(),[x,y]=j.useState(0),[v,b]=j.useState(!1),[w,S]=j.useState(!1),[C,E]=j.useState(!1),[I,P]=j.useState(!1),[R,D]=j.useState(""),[O,U]=j.useState(null),W=j.useRef({}),[V,G]=j.useState({}),Y=j.useRef(!1),X=(ze,$e)=>{W.current={...W.current,[ze]:$e},G(W.current)};j.useEffect(()=>{Y.current||(u?(W.current={...u},G(W.current),Y.current=!0):a&&(W.current={email:a.email,...W.current},G(W.current)))},[u,a]),j.useEffect(()=>{const ze=c;!i||!(ze!=null&&ze.discount_code)||O||U({code:ze.discount_code,discount_cents:ze.discount_cents||0,amount_cents:ze.amount_cents??i.price_cents,original_cents:i.price_cents})},[c,i,O]);const ae=O?O.amount_cents:(i==null?void 0:i.price_cents)??0,ie=j.useMemo(()=>mse(i),[i]),ne=ze=>UGs(ie,ze),te=ze=>_bt(ie,ze)?e.jsx("span",{className:"text-destructive",children:" *"}):null,J=(ze,$e)=>{const ct={...W.current.extra||{},[ze]:$e};X("extra",ct)},ce=ze=>ie.custom.filter(($e,ct)=>ct%3===ze),_e=ze=>{const $e=ce(ze);if(!$e.length)return null;const ct=V.extra||{};return e.jsx("div",{className:"space-y-4",children:$e.map(Xe=>e.jsxs("div",{className:"space-y-2",children:[Xe.type==="checkbox"?e.jsxs("div",{className:"flex items-start gap-3 rounded-lg border border-border/60 p-4",children:[e.jsx(ai,{id:Xe.id,checked:!!ct[Xe.id],onCheckedChange:it=>J(Xe.id,!!it)}),e.jsxs(ee,{htmlFor:Xe.id,className:"text-sm font-normal leading-relaxed",children:[Xe.label,Xe.required&&e.jsx("span",{className:"text-destructive",children:" *"})]})]}):e.jsxs(e.Fragment,{children:[e.jsxs(ee,{htmlFor:Xe.id,children:[Xe.label,Xe.required&&e.jsx("span",{className:"text-destructive",children:" *"})]}),Xe.type==="long_text"?e.jsx(Rs,{id:Xe.id,rows:3,value:ct[Xe.id]||"",onChange:it=>J(Xe.id,it.target.value)}):Xe.type==="select"?e.jsxs(ms,{value:ct[Xe.id]||"",onValueChange:it=>J(Xe.id,it),children:[e.jsx(us,{children:e.jsx(fs,{placeholder:"Select"})}),e.jsx(hs,{children:(Xe.options||[]).map(it=>e.jsx(Ge,{value:it,children:it},it))})]}):e.jsx(pe,{id:Xe.id,value:ct[Xe.id]||"",onChange:it=>J(Xe.id,it.target.value)})]}),Xe.help&&e.jsx("p",{className:"text-xs text-muted-foreground",children:Xe.help})]},Xe.id))})},he=ze=>{const $e=W.current,ct=Ke=>Ke==null||Ke===""||Ke===!1,Xe=cnt.find(Ke=>Ke.step===ze&&_bt(ie,Ke.key)&&ct(Ke.key==="timezone"?$e.timezone||(i==null?void 0:i.timezone):$e[Ke.key]));if(Xe)return Xe.label;const it=$e.extra||{},at=ce(ze).find(Ke=>Ke.required&&ct(it[Ke.id]));return at?at.label:null},ue=()=>{if(x<=2){const ze=he(x);if(ze)return re.error(`Please answer: ${ze}`)}y(ze=>ze+1)},ve=async()=>{if(!(!i||!R.trim()))try{let ze=c==null?void 0:c.id;(!ze||(c==null?void 0:c.status)==="canceled")&&(ze=await m.mutateAsync(i.id));const $e=await f.mutateAsync({enrollmentId:ze,code:R});U($e),D(""),await d(),re.success(`Code applied — you save ${Cg($e.discount_cents,i.currency)}`)}catch(ze){re.error(ze.message||"That code could not be applied")}},Ee=async()=>{if(!(c!=null&&c.id))return U(null);try{await g.mutateAsync(c.id),U(null),await d()}catch(ze){re.error(ze.message||"Could not remove the code")}},Se=n.get("setup"),Le=n.get("session_id"),Fe=j.useRef(!1);j.useEffect(()=>{Se!=="success"||!Le||!(c!=null&&c.id)||Fe.current||(Fe.current=!0,S(!0),(async()=>{const{data:ze,error:$e}=await q.functions.invoke("program-enroll",{body:{action:"verify",enrollment_id:c.id,session_id:Le}});if(S(!1),$e||ze!=null&&ze.error||(ze==null?void 0:ze.success)===!1){re.error((ze==null?void 0:ze.error)||($e==null?void 0:$e.message)||"We could not confirm your card");return}await d(),n.delete("setup"),n.delete("session_id"),r(n,{replace:!0}),re.success("Your seat is confirmed")})())},[Se,Le,c==null?void 0:c.id]),j.useEffect(()=>{Se==="cancelled"&&re.info("Checkout cancelled — your seat is held for a short while.")},[Se]);const ke=j.useMemo(()=>c&&["reserved","scheduled_for_charge","paid","completed"].includes(c.status),[c]),Ve=async()=>{if(i){if(!C||i.payment_mode!=="free"&&!I){re.error("Please confirm the checkboxes to continue");return}b(!0);try{let ze=c==null?void 0:c.id;(!ze||(c==null?void 0:c.status)==="canceled")&&(ze=await m.mutateAsync(i.id)),await h.mutateAsync({...W.current,id:void 0,program_id:i.id,enrollment_id:ze,created_at:void 0,updated_at:void 0,user_id:void 0});const{data:$e,error:ct}=await q.functions.invoke("program-enroll",{body:{action:"setup",enrollment_id:ze}});if(ct||$e!=null&&$e.error)throw new Error(($e==null?void 0:$e.error)||(ct==null?void 0:ct.message));if($e!=null&&$e.free){await d(),re.success("You're in"),t(`/programs/${i.slug}/workspace`);return}$e!=null&&$e.url&&(window.location.href=$e.url)}catch(ze){re.error(ze.message||"Could not start enrollment")}finally{b(!1)}}};if(l)return e.jsx(Vs,{children:e.jsxs("div",{className:"mx-auto max-w-2xl space-y-4 p-8",children:[e.jsx(yn,{className:"h-10 w-1/2"}),e.jsx(yn,{className:"h-64 w-full rounded-xl"})]})});if(!i)return e.jsx(Vs,{children:e.jsxs("div",{className:"mx-auto max-w-xl p-12 text-center",children:[e.jsx("h1",{className:"text-2xl font-bold",children:"Program not found"}),e.jsx($,{asChild:!0,className:"mt-6",children:e.jsx(wr,{to:"/programs",children:"Back to Programs"})})]})});if(LG(c)&&ke&&Se!=="success")return e.jsx(Vs,{children:e.jsxs("div",{className:"mx-auto max-w-xl space-y-4 p-12 text-center",children:[e.jsx(qr,{className:"mx-auto h-10 w-10 text-primary"}),e.jsxs("h1",{className:"text-2xl font-bold",children:["You're enrolled in ",i.name]}),e.jsx("p",{className:"text-muted-foreground",children:(c==null?void 0:c.status)==="paid"?"Your payment is complete.":`Your card is saved. Nothing is charged until ${sh(c==null?void 0:c.charge_scheduled_at)||"the program start date"}.`}),e.jsx($,{asChild:!0,size:"lg",children:e.jsx(wr,{to:`/programs/${i.slug}/workspace`,children:"Open your program workspace"})})]})});const je=typeof o=="number"&&o<=0,{notOpenYet:Ae,closed:Ce,opensLabel:qe}=E6e(i);return Ae||Ce?e.jsx(Vs,{children:e.jsxs("div",{className:"mx-auto w-full max-w-xl space-y-4 p-8 text-center",children:[e.jsx("h1",{className:"text-2xl font-bold",children:Ae?"Enrollment is not open yet":"Enrollment is closed"}),e.jsx("p",{className:"text-muted-foreground",children:Ae?`Enrollment for ${i.name} opens ${qe}. Come back then to reserve your seat.`:`Enrollment for ${i.name} has closed. Watch the Hub for the next cohort.`}),e.jsx($,{asChild:!0,children:e.jsx(wr,{to:`/programs/${i.slug}`,children:"Back to program details"})})]})}):e.jsx(Vs,{children:e.jsxs("div",{className:"mx-auto w-full max-w-3xl space-y-6 p-4 md:p-8",children:[e.jsx($,{asChild:!0,variant:"ghost",size:"sm",className:"-ml-2",children:e.jsxs(wr,{to:`/programs/${i.slug}`,children:[e.jsx(qa,{className:"mr-1.5 h-4 w-4"})," Back to program"]})}),e.jsxs("header",{className:"space-y-2",children:[e.jsx("p",{className:"text-xs font-semibold uppercase tracking-[0.2em] text-primary",children:"Enrollment"}),e.jsx("h1",{className:"text-2xl font-bold md:text-3xl",children:i.name}),e.jsx("p",{className:"text-sm text-muted-foreground",children:i.payment_mode==="delayed"&&i.charge_at?`${KGe(i.price_cents,i.currency,i.duration_weeks)}. Your card is saved today and charged once on ${sh(i.charge_at)} — no recurring billing.`:"Complete the short intake and checkout to secure your seat."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between text-xs text-muted-foreground",children:[e.jsx("span",{className:"font-medium text-foreground",children:Nde[x]}),e.jsxs("span",{children:["Step ",x+1," of ",Nde.length]})]}),e.jsx(Yi,{value:(x+1)/Nde.length*100})]}),w&&e.jsx(Ne,{className:"border-primary/40 bg-primary/5",children:e.jsxs(Ie,{className:"flex items-center gap-3 p-4 text-sm",children:[e.jsx(kt,{className:"h-4 w-4 animate-spin text-primary"}),"Confirming your card with Stripe…"]})}),e.jsx(Ne,{children:e.jsxs(Ie,{className:"space-y-5 p-6",children:[x===0&&ie.intro&&e.jsx("p",{className:"rounded-lg border border-border/60 bg-muted/30 p-4 text-sm text-muted-foreground",children:ie.intro}),x===0&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[ne("full_name")&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ee,{htmlFor:"full_name",children:["Full name",te("full_name")]}),e.jsx(pe,{id:"full_name",value:V.full_name||"",onChange:ze=>X("full_name",ze.target.value)})]}),ne("phone")&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ee,{htmlFor:"phone",children:["Mobile number",te("phone")]}),e.jsx(pe,{id:"phone",value:V.phone||"",onChange:ze=>X("phone",ze.target.value)})]}),ne("instagram_handle")&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ee,{htmlFor:"instagram_handle",children:["Instagram handle",te("instagram_handle")]}),e.jsx(pe,{id:"instagram_handle",placeholder:"@yourhandle",value:V.instagram_handle||"",onChange:ze=>X("instagram_handle",ze.target.value)})]}),ne("city")&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ee,{htmlFor:"city",children:["Primary city / market",te("city")]}),e.jsx(pe,{id:"city",value:V.city||"",onChange:ze=>X("city",ze.target.value)})]})]}),ne("service_areas")&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ee,{htmlFor:"service_areas",children:["Neighborhoods or areas you serve",te("service_areas")]}),e.jsx(Rs,{id:"service_areas",rows:2,value:V.service_areas||"",onChange:ze=>X("service_areas",ze.target.value)})]}),e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[ne("years_experience")&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ee,{children:["Years in real estate",te("years_experience")]}),e.jsxs(ms,{value:V.years_experience||"",onValueChange:ze=>X("years_experience",ze),children:[e.jsx(us,{children:e.jsx(fs,{placeholder:"Select"})}),e.jsx(hs,{children:["Less than 1","1-3","4-7","8-15","15+"].map(ze=>e.jsx(Ge,{value:ze,children:ze},ze))})]})]}),ne("specialty")&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ee,{htmlFor:"specialty",children:["Specialty or niche",te("specialty")]}),e.jsx(pe,{id:"specialty",value:V.specialty||"",onChange:ze=>X("specialty",ze.target.value)})]})]}),_e(0)]}),x===1&&e.jsxs(e.Fragment,{children:[ne("target_audience")&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ee,{htmlFor:"target_audience",children:["Who are you trying to reach?",te("target_audience")]}),e.jsx(Rs,{id:"target_audience",rows:2,placeholder:"First-time buyers, move-up sellers, investors…",value:V.target_audience||"",onChange:ze=>X("target_audience",ze.target.value)})]}),e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[ne("video_comfort")&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ee,{children:["How comfortable are you on camera?",te("video_comfort")]}),e.jsxs(ms,{value:V.video_comfort||"",onValueChange:ze=>X("video_comfort",ze),children:[e.jsx(us,{children:e.jsx(fs,{placeholder:"Select"})}),e.jsx(hs,{children:["Terrified","Nervous but willing","Getting comfortable","Very comfortable"].map(ze=>e.jsx(Ge,{value:ze,children:ze},ze))})]})]}),ne("posting_frequency")&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ee,{children:["How often do you post today?",te("posting_frequency")]}),e.jsxs(ms,{value:V.posting_frequency||"",onValueChange:ze=>X("posting_frequency",ze),children:[e.jsx(us,{children:e.jsx(fs,{placeholder:"Select"})}),e.jsx(hs,{children:["Never","Rarely","Weekly","A few times a week","Daily"].map(ze=>e.jsx(Ge,{value:ze,children:ze},ze))})]})]})]}),ne("content_style")&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ee,{htmlFor:"content_style",children:["What content style feels like you?",te("content_style")]}),e.jsx(Rs,{id:"content_style",rows:2,placeholder:"Educational, funny, behind-the-scenes, luxury-polished…",value:V.content_style||"",onChange:ze=>X("content_style",ze.target.value)})]}),ne("personal_interests")&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ee,{htmlFor:"personal_interests",children:["Interests or hobbies we can weave in",te("personal_interests")]}),e.jsx(Rs,{id:"personal_interests",rows:2,value:V.personal_interests||"",onChange:ze=>X("personal_interests",ze.target.value)})]}),_e(1)]}),x===2&&e.jsxs(e.Fragment,{children:[ne("primary_goal")&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ee,{htmlFor:"primary_goal",children:["Your #1 goal for this program",te("primary_goal")]}),e.jsx(Rs,{id:"primary_goal",rows:3,value:V.primary_goal||"",onChange:ze=>X("primary_goal",ze.target.value)})]}),ne("topics_to_avoid")&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ee,{htmlFor:"topics_to_avoid",children:["Anything you don't want to talk about",te("topics_to_avoid")]}),e.jsx(Rs,{id:"topics_to_avoid",rows:2,value:V.topics_to_avoid||"",onChange:ze=>X("topics_to_avoid",ze.target.value)})]}),ne("timezone")&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ee,{children:["Your time zone",te("timezone")]}),e.jsxs(ms,{value:V.timezone||i.timezone,onValueChange:ze=>X("timezone",ze),children:[e.jsx(us,{children:e.jsx(fs,{placeholder:"Select"})}),e.jsx(hs,{children:["America/New_York","America/Chicago","America/Denver","America/Phoenix","America/Los_Angeles","Pacific/Honolulu"].map(ze=>e.jsx(Ge,{value:ze,children:ze.replace("America/","").replace("_"," ")},ze))})]})]}),_e(2),ne("consent_public_profile")&&e.jsxs("div",{className:"flex items-start gap-3 rounded-lg border border-border/60 p-4",children:[e.jsx(ai,{id:"consent_public_profile",checked:!!V.consent_public_profile,onCheckedChange:ze=>X("consent_public_profile",!!ze)}),e.jsx(ee,{htmlFor:"consent_public_profile",className:"text-sm font-normal leading-relaxed",children:"I'm okay with my content being reviewed and shared as an example inside the cohort."})]})]}),x===3&&e.jsxs("div",{className:"space-y-5",children:[e.jsxs("div",{className:"rounded-lg border border-border/60 p-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-sm text-muted-foreground",children:i.name}),e.jsx("span",{className:"font-semibold",children:i.payment_mode==="free"?"Included":O?e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-sm font-normal text-muted-foreground line-through",children:Cg(O.original_cents,i.currency)}),Cg(ae,i.currency)]}):Cg(i.price_cents,i.currency)})]}),i.payment_mode!=="free"&&e.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:KGe(ae,i.currency,i.duration_weeks)}),i.payment_mode!=="free"&&e.jsx("div",{className:"mt-3 border-t border-border/60 pt-3",children:O?e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2 rounded-md bg-primary/5 px-3 py-2 text-sm",children:[e.jsxs("span",{className:"inline-flex items-center gap-2",children:[e.jsx(Ap,{className:"h-3.5 w-3.5 text-primary"}),"Code ",e.jsx("span",{className:"font-mono font-semibold",children:O.code})," applied — you save ",Cg(O.discount_cents,i.currency)]}),e.jsxs($,{variant:"ghost",size:"sm",onClick:Ee,disabled:g.isPending,children:[e.jsx(gr,{className:"mr-1 h-3.5 w-3.5"})," Remove"]})]}):e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"discount_code",className:"text-xs text-muted-foreground",children:"Have a discount code?"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(pe,{id:"discount_code",placeholder:"Enter code",className:"font-mono uppercase",value:R,onChange:ze=>D(ze.target.value.toUpperCase()),onKeyDown:ze=>{ze.key==="Enter"&&(ze.preventDefault(),ve())}}),e.jsx($,{variant:"outline",onClick:ve,disabled:!R.trim()||f.isPending||m.isPending,children:f.isPending||m.isPending?e.jsx(kt,{className:"h-4 w-4 animate-spin"}):"Apply"})]})]})}),i.payment_mode==="delayed"&&e.jsxs("div",{className:"mt-3 flex items-start gap-2.5 border-t border-border/60 pt-3 text-sm",children:[e.jsx(Cv,{className:"mt-0.5 h-4 w-4 shrink-0 text-primary"}),e.jsxs("span",{children:["Charged once on"," ",e.jsx("span",{className:"font-semibold",children:sh(i.charge_at||i.kickoff_at)||"the program start date"}),". No recurring billing, installments, or renewal. Cancel any time before then at no cost."]})]}),typeof o=="number"&&e.jsx("p",{className:"mt-3 text-xs text-muted-foreground",children:o>0?`${o} of ${i.capacity} seats left`:"This cohort is full"})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(ai,{id:"terms",checked:C,onCheckedChange:ze=>E(!!ze)}),e.jsx(ee,{htmlFor:"terms",className:"text-sm font-normal leading-relaxed",children:"I agree to the program terms, including the attendance and participation expectations, and understand seats are limited."})]}),i.payment_mode!=="free"&&e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(ai,{id:"charge",checked:I,onCheckedChange:ze=>P(!!ze)}),e.jsx(ee,{htmlFor:"charge",className:"text-sm font-normal leading-relaxed",children:i.payment_mode==="delayed"?`I authorize LevelUp to charge my saved card one time — ${Cg(ae,i.currency)} for the ${hse(i.duration_weeks)} — on ${sh(i.charge_at||i.kickoff_at)||"the program start date"} unless I cancel before then. I understand this is not a subscription and will not renew.`:`I authorize LevelUp to charge my card one time — ${Cg(ae,i.currency)} for the ${hse(i.duration_weeks)} — today. This is not a subscription and will not renew.`})]})]}),e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[e.jsx(bm,{className:"h-3.5 w-3.5"}),"Card details are handled by Stripe — LevelUp never sees or stores them."]})]}),e.jsxs("div",{className:"flex items-center justify-between border-t border-border/60 pt-5",children:[e.jsxs($,{variant:"ghost",onClick:()=>y(ze=>Math.max(0,ze-1)),disabled:x===0||v,children:[e.jsx(qa,{className:"mr-1.5 h-4 w-4"})," Back"]}),xString(s).padStart(2,"0"),IBe=s=>s.toISOString().replace(/[-:]/g,"").split(".")[0]+"Z",rrn=({program:s,intakeComplete:t})=>{const n=s!=null&&s.kickoff_at?new Date(s.kickoff_at).getTime():null,[r,a]=j.useState(()=>Date.now());j.useEffect(()=>{const d=setInterval(()=>a(Date.now()),1e3);return()=>clearInterval(d)},[]);const i=j.useMemo(()=>{if(!n)return null;const d=Math.max(n-r,0);return{days:Math.floor(d/864e5),hours:Math.floor(d%864e5/36e5),minutes:Math.floor(d%36e5/6e4),seconds:Math.floor(d%6e4/1e3),done:d===0}},[n,r]);if(!n||!i)return null;const l=new Intl.DateTimeFormat("en-US",{weekday:"long",month:"long",day:"numeric",hour:"numeric",minute:"2-digit",timeZoneName:"short",timeZone:"America/New_York"}).format(new Date(n)),o=()=>{const d=new Date(n),u=new Date(n+90*6e4),h=["BEGIN:VCALENDAR","VERSION:2.0","PRODID:-//LevelUp//Programs//EN","BEGIN:VEVENT",`UID:kickoff-${s.id}@levelup`,`DTSTAMP:${IBe(new Date)}`,`DTSTART:${IBe(d)}`,`DTEND:${IBe(u)}`,`SUMMARY:${s.name} — Kickoff Call`,`DESCRIPTION:The official kickoff for ${s.name}. Bring a phone and a story.`,"END:VEVENT","END:VCALENDAR"].join(`\r `),m=URL.createObjectURL(new Blob([h],{type:"text/calendar"})),f=document.createElement("a");f.href=m,f.download="program-kickoff.ics",f.click(),URL.revokeObjectURL(m)},c=[{label:"Days",value:i.days},{label:"Hours",value:PBe(i.hours)},{label:"Minutes",value:PBe(i.minutes)},{label:"Seconds",value:PBe(i.seconds)}];return e.jsxs(Ne,{className:"relative overflow-hidden border-primary/25",children:[e.jsx("div",{className:"absolute inset-0 bg-gradient-to-br from-primary/15 via-background to-secondary/10"}),s.hero_image_url&&e.jsx("img",{src:s.hero_image_url,alt:"",className:"pointer-events-none absolute inset-0 h-full w-full object-cover opacity-10"}),e.jsxs(Ie,{className:"relative space-y-6 p-6 md:p-9",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs(Be,{className:"gap-1.5",children:[e.jsx(Nn,{className:"h-3.5 w-3.5"})," Your seat is confirmed"]}),e.jsxs(Be,{variant:"outline",className:"gap-1.5",children:[e.jsx(da,{className:"h-3.5 w-3.5"})," ",l]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("h2",{className:"text-2xl font-bold tracking-tight md:text-3xl",children:i.done?"We're live — let's go":`${s.name} kicks off soon`}),e.jsx("p",{className:"max-w-2xl text-sm text-muted-foreground md:text-base",children:i.done?"The kickoff call is starting. Head to your sessions below to join.":"Everything unlocks on kickoff day. Until then, get your setup dialed in so week one is pure momentum."})]}),e.jsx("div",{className:"grid max-w-xl grid-cols-4 gap-2 md:gap-3",children:c.map(d=>e.jsxs("div",{className:"rounded-xl border bg-background/80 px-2 py-4 text-center backdrop-blur-sm",children:[e.jsx("div",{className:"text-2xl font-bold tabular-nums tracking-tight md:text-4xl",children:d.value}),e.jsx("div",{className:"mt-1 text-[10px] uppercase tracking-widest text-muted-foreground md:text-xs",children:d.label})]},d.label))}),e.jsx("div",{className:"flex flex-wrap gap-3",children:e.jsxs($,{onClick:o,size:"lg",children:[e.jsx(jv,{className:"mr-2 h-4 w-4"})," Add kickoff to calendar"]})}),e.jsx("div",{className:"grid gap-3 sm:grid-cols-3",children:[{title:"Intake complete",body:t?"We've got what we need to tailor your coaching.":"Finish your intake so your coach knows your market and goals.",done:!!t},{title:"Kickoff on the calendar",body:"One click above adds it to Google, Apple or Outlook.",done:!1},{title:"Set up your shooting kit",body:"Phone, clip mic, tripod. That is genuinely all you need.",done:!1}].map(d=>e.jsxs("div",{className:"rounded-xl border bg-background/70 p-4 backdrop-blur-sm",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm font-semibold",children:[e.jsx(qr,{className:`h-4 w-4 ${d.done?"text-primary":"text-muted-foreground/40"}`}),d.title]}),e.jsx("p",{className:"mt-1.5 text-xs leading-relaxed text-muted-foreground",children:d.body})]},d.title))})]})]})},LBe=s=>s.toISOString().replace(/[-:]/g,"").split(".")[0]+"Z",arn=(s,t)=>{const n=new Date(s.starts_at),r=new Date(n.getTime()+(s.duration_minutes||60)*6e4),a=["BEGIN:VCALENDAR","VERSION:2.0","PRODID:-//LevelUp//Programs//EN","BEGIN:VEVENT",`UID:${s.id}@levelup`,`DTSTAMP:${LBe(new Date)}`,`DTSTART:${LBe(n)}`,`DTEND:${LBe(r)}`,`SUMMARY:${t} — ${s.title}`,`DESCRIPTION:${(s.description||"").replace(/\n/g,"\\n")}${s.meeting_link?`\\n\\nJoin: ${s.meeting_link}`:""}`,...s.meeting_link?[`LOCATION:${s.meeting_link}`]:[],"END:VEVENT","END:VCALENDAR"].join(`\r `),i=URL.createObjectURL(new Blob([a],{type:"text/calendar"})),l=document.createElement("a");l.href=i,l.download=`${s.title.replace(/[^a-z0-9]+/gi,"-").toLowerCase()}.ics`,l.click(),URL.revokeObjectURL(i)},irn={pdf:Jr,document:ek,checklist:Ev,template_link:m2,video:rf,external:bd},orn=()=>{var ce;const{slug:s}=Wi(),[t]=gc(),{isAdmin:n}=vs(),r=n?t.get("as"):null,a=t.get("name")||"this member",i=n&&(t.get("preview")==="1"||!!r),{data:l,isLoading:o}=dnt(s),{data:c}=hnt(l==null?void 0:l.id),{data:d,isLoading:u}=HGs(l==null?void 0:l.id,r),h=GGs(l==null?void 0:l.id),m=WGs(l==null?void 0:l.id),f=KGs(l==null?void 0:l.id),g=YGs(l==null?void 0:l.id),{data:x}=YUt(l==null?void 0:l.id),y=!!(l!=null&&l.kickoff_at)&&new Date(l.kickoff_at).getTime()>Date.now(),[v,b]=j.useState(!1),[w,S]=j.useState({title:"",instagram_url:""}),[C,E]=j.useState({}),[I,P]=j.useState(null),R=j.useMemo(()=>{if(!(l!=null&&l.kickoff_at))return 1;const _e=Math.floor((Date.now()-new Date(l.kickoff_at).getTime())/864e5);return Math.min(Math.max(Math.floor(_e/7)+1,1),l.duration_weeks)},[l]),D=new Set(((d==null?void 0:d.completions)||[]).map(_e=>_e.lesson_id)),O=(d==null?void 0:d.lessons)||[],U=O.length?Math.round(D.size/O.length*100):0,W=((d==null?void 0:d.videoLogs)||[]).filter(_e=>_e.week_number===R).length,V=((d==null?void 0:d.videoLogs)||[]).length,G=(l==null?void 0:l.weekly_video_goal)||3,Y=j.useMemo(()=>{const _e=new Map;((d==null?void 0:d.videoLogs)||[]).forEach(ue=>_e.set(ue.week_number,(_e.get(ue.week_number)||0)+1));let he=0;for(let ue=R;ue>=1;ue--)if((_e.get(ue)||0)>=G)he++;else if(ue!==R)break;return he},[d==null?void 0:d.videoLogs,R,G]);if(o||u)return e.jsx(Vs,{children:e.jsxs("div",{className:"mx-auto max-w-6xl space-y-6 p-8",children:[e.jsx(yn,{className:"h-28 w-full rounded-xl"}),e.jsx(yn,{className:"h-64 w-full rounded-xl"})]})});if(!l)return e.jsx(Vs,{children:e.jsxs("div",{className:"mx-auto max-w-xl p-12 text-center",children:[e.jsx("h1",{className:"text-2xl font-bold",children:"Program not found"}),e.jsx($,{asChild:!0,className:"mt-6",children:e.jsx(wr,{to:"/programs",children:"Back to Programs"})})]})});if(!LG(c)&&!i)return e.jsx(Vs,{children:e.jsxs("div",{className:"mx-auto max-w-xl space-y-4 p-12 text-center",children:[e.jsx("h1",{className:"text-2xl font-bold",children:"You're not enrolled yet"}),e.jsxs("p",{className:"text-muted-foreground",children:["Reserve your seat in ",l.name," to unlock the roadmap, lessons and mastermind sessions."]}),e.jsx($,{asChild:!0,size:"lg",children:e.jsx(wr,{to:`/programs/${l.slug}`,children:"View the program"})})]})});const X=((d==null?void 0:d.events)||[]).filter(_e=>new Date(_e.starts_at)>=new Date),ae=((d==null?void 0:d.events)||[]).filter(_e=>new Date(_e.starts_at)_e.is_pinned),te=[...(d==null?void 0:d.myResources)||[],...(d==null?void 0:d.resources)||[]].reduce((_e,he)=>{const ue=he.user_id?`Just for you · ${he.category}`:he.category;return(_e[ue]||(_e[ue]=[])).push(he),_e},{}),J=((d==null?void 0:d.progress)||[]).find(_e=>_e.week_number===R)||{};return e.jsx(Vs,{children:e.jsx("div",{className:"program-theme-neon relative min-h-screen",children:e.jsxs("div",{className:"relative mx-auto w-full max-w-6xl space-y-8 p-4 md:p-8",children:[i&&(r||!LG(c))&&e.jsx(Ne,{className:"border-primary/40 bg-primary/5",children:e.jsxs(Ie,{className:"flex flex-wrap items-center justify-between gap-3 p-4 text-sm",children:[e.jsx("span",{children:r?e.jsxs(e.Fragment,{children:[e.jsx("strong",{children:"Admin view"})," — you're seeing ",a,"'s dashboard exactly as they see it (progress, check-ins, videos and personal resources). It's read-only: avoid logging videos or check-ins here."]}):e.jsxs(e.Fragment,{children:[e.jsx("strong",{children:"Admin preview"})," — this is exactly what an enrollee sees. Your own progress, check-ins and video logs are empty because you're not enrolled."]})}),e.jsx($,{variant:"outline",size:"sm",asChild:!0,children:e.jsx(wr,{to:"/admin/programs",children:"Back to Programs admin"})})]})}),e.jsxs("header",{className:"space-y-3",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs(Be,{variant:"secondary",children:["Week ",R," of ",l.duration_weeks]}),(c==null?void 0:c.status)==="scheduled_for_charge"&&c.charge_scheduled_at&&e.jsxs(Be,{variant:"outline",children:["Billing ",sh(c.charge_scheduled_at)]}),(c==null?void 0:c.status)==="payment_failed"&&e.jsx(Be,{variant:"destructive",children:"Payment issue"})]}),e.jsx("p",{className:"neon-eyebrow font-semibold",children:"LevelUp Program"}),e.jsx("h1",{className:"neon-title w-fit text-4xl font-black uppercase tracking-tight md:text-5xl",children:l.name}),l.subtitle&&e.jsx("p",{className:"text-muted-foreground",children:l.subtitle})]}),y&&e.jsx(rrn,{program:l,intakeComplete:!!x}),e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2 lg:grid-cols-4",children:[e.jsx(Ne,{className:"neon-topline",children:e.jsxs(Ie,{className:"space-y-1.5 p-5",children:[e.jsxs("div",{className:"flex items-center gap-2 text-xs uppercase tracking-[0.16em] text-muted-foreground",children:[e.jsx(rh,{className:"h-3.5 w-3.5 text-primary"})," This week"]}),e.jsxs("p",{className:"neon-stat text-3xl font-black",children:[W,e.jsxs("span",{className:"text-base font-normal text-muted-foreground",children:[" / ",G]})]}),e.jsx(Yi,{value:Math.min(W/G*100,100),className:"h-1.5"})]})}),e.jsx(Ne,{className:"neon-topline",children:e.jsxs(Ie,{className:"space-y-1.5 p-5",children:[e.jsxs("div",{className:"flex items-center gap-2 text-xs uppercase tracking-[0.16em] text-muted-foreground",children:[e.jsx(rf,{className:"h-3.5 w-3.5 text-primary"})," Videos posted"]}),e.jsx("p",{className:"neon-stat text-3xl font-black",children:V}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"since kickoff"})]})}),e.jsx(Ne,{className:"neon-topline",children:e.jsxs(Ie,{className:"space-y-1.5 p-5",children:[e.jsxs("div",{className:"flex items-center gap-2 text-xs uppercase tracking-[0.16em] text-muted-foreground",children:[e.jsx(nh,{className:"h-3.5 w-3.5 text-primary"})," Streak"]}),e.jsxs("p",{className:"neon-stat text-3xl font-black",children:[Y," wk"]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"hitting your goal"})]})}),e.jsx(Ne,{className:"neon-topline",children:e.jsxs(Ie,{className:"space-y-1.5 p-5",children:[e.jsxs("div",{className:"flex items-center gap-2 text-xs uppercase tracking-[0.16em] text-muted-foreground",children:[e.jsx(Yl,{className:"h-3.5 w-3.5 text-primary"})," Curriculum"]}),e.jsxs("p",{className:"neon-stat text-3xl font-black",children:[U,"%"]}),e.jsx(Yi,{value:U,className:"h-1.5"})]})})]}),e.jsxs("div",{className:"flex flex-wrap gap-3",children:[e.jsxs(zs,{open:v,onOpenChange:b,children:[e.jsx(jl,{asChild:!0,children:e.jsxs($,{children:[e.jsx(dn,{className:"mr-1.5 h-4 w-4"})," Log a video"]})}),e.jsxs(Os,{children:[e.jsx(Us,{children:e.jsx(Bs,{children:"Log a posted video"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"v-title",children:"What was it about?"}),e.jsx(pe,{id:"v-title",value:w.title,onChange:_e=>S(he=>({...he,title:_e.target.value}))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"v-url",children:"Instagram link (optional)"}),e.jsx(pe,{id:"v-url",placeholder:"https://instagram.com/reel/…",value:w.instagram_url,onChange:_e=>S(he=>({...he,instagram_url:_e.target.value}))})]})]}),e.jsx(Ar,{children:e.jsx($,{onClick:async()=>{await m.mutateAsync({week_number:R,...w}),S({title:"",instagram_url:""}),b(!1)},children:"Log video"})})]})]}),((ce=X[0])==null?void 0:ce.meeting_link)&&e.jsx($,{variant:"outline",asChild:!0,children:e.jsxs("a",{href:X[0].meeting_link,target:"_blank",rel:"noreferrer",children:[e.jsx(tf,{className:"mr-1.5 h-4 w-4"})," Join next session"]})})]}),ie.length>0&&e.jsx(Ne,{className:"border-primary/30 bg-primary/5",children:e.jsx(Ie,{className:"space-y-3 p-5",children:ie.map(_e=>e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(xm,{className:"mt-0.5 h-4 w-4 shrink-0 text-primary"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:_e.title}),_e.body&&e.jsx("p",{className:"text-sm text-muted-foreground",children:_e.body})]})]},_e.id))})}),e.jsxs(ha,{defaultValue:"roadmap",children:[e.jsxs(ma,{className:"flex w-full flex-wrap justify-start",children:[e.jsx(Zt,{value:"roadmap",children:"Roadmap"}),e.jsx(Zt,{value:"lessons",children:"Lessons"}),e.jsx(Zt,{value:"checkin",children:"Weekly check-in"}),e.jsx(Zt,{value:"events",children:"Sessions"}),e.jsx(Zt,{value:"resources",children:"Resources"}),e.jsx(Zt,{value:"profile",children:"Profile review"})]}),e.jsxs(Xt,{value:"roadmap",className:"mt-6 space-y-4",children:[((d==null?void 0:d.weeks)||[]).length===0&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"The roadmap will appear here before kickoff."}),((d==null?void 0:d.weeks)||[]).map(_e=>{const he=_e.release_at&&new Date(_e.release_at)>new Date;return e.jsx(Ne,{className:he?"opacity-60":_e.week_number===R?"border-primary/50":"",children:e.jsxs(Ie,{className:"space-y-2 p-5",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs(Be,{variant:"outline",children:["Week ",_e.week_number]}),e.jsx("span",{className:"text-xs uppercase tracking-wide text-muted-foreground",children:_e.phase}),_e.week_number===R&&e.jsx(Be,{children:"Current"}),he&&e.jsxs("span",{className:"inline-flex items-center gap-1 text-xs text-muted-foreground",children:[e.jsx(da,{className:"h-3 w-3"})," Unlocks ",sh(_e.release_at)]})]}),e.jsx("h3",{className:"font-semibold",children:_e.title}),_e.learning_goal&&e.jsx("p",{className:"text-sm text-muted-foreground",children:_e.learning_goal}),!he&&Array.isArray(_e.tasks)&&_e.tasks.length>0&&e.jsx("ul",{className:"mt-2 space-y-1.5",children:_e.tasks.map((ue,ve)=>e.jsxs("li",{className:"flex items-start gap-2 text-sm",children:[e.jsx(qr,{className:"mt-0.5 h-3.5 w-3.5 shrink-0 text-primary"}),typeof ue=="string"?ue:ue.label]},ve))})]})},_e.id)})]}),e.jsxs(Xt,{value:"lessons",className:"mt-6 space-y-3",children:[O.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"Lessons unlock as the program progresses."}),O.map(_e=>{const he=ZUt(_e.video_url),ue=I===_e.id;return e.jsx(Ne,{children:e.jsxs(Ie,{className:"space-y-4 p-5",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-4",children:[e.jsx(ai,{checked:D.has(_e.id),onCheckedChange:ve=>h.mutate({lessonId:_e.id,done:!!ve}),"aria-label":`Mark ${_e.title} complete`}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"font-medium",children:_e.title}),_e.summary&&e.jsx("p",{className:"text-sm text-muted-foreground",children:_e.summary}),_e.action_assignment&&e.jsxs("p",{className:"mt-1 text-xs text-primary",children:["Action: ",_e.action_assignment]})]}),_e.duration_minutes&&e.jsxs("span",{className:"inline-flex items-center gap-1 text-xs text-muted-foreground",children:[e.jsx(da,{className:"h-3 w-3"})," ",_e.duration_minutes," min"]}),e.jsxs("div",{className:"flex gap-2",children:[_e.video_url&&(he||Aee(_e.video_url))&&e.jsxs($,{size:"sm",variant:"outline",onClick:()=>P(ue?null:_e.id),children:[e.jsx(tf,{className:"mr-1.5 h-3.5 w-3.5"})," ",ue?"Close":"Watch"]}),_e.video_url&&!he&&!Aee(_e.video_url)&&e.jsx($,{size:"sm",variant:"outline",asChild:!0,children:e.jsxs("a",{href:_e.video_url,target:"_blank",rel:"noreferrer",children:[e.jsx(tf,{className:"mr-1.5 h-3.5 w-3.5"})," Watch"]})}),_e.worksheet_url&&e.jsx($,{size:"sm",variant:"ghost",asChild:!0,children:e.jsxs("a",{href:_e.worksheet_url,target:"_blank",rel:"noreferrer",children:[e.jsx(di,{className:"mr-1.5 h-3.5 w-3.5"})," Worksheet"]})})]})]}),ue&&he&&e.jsx("div",{className:"overflow-hidden rounded-lg border border-border/60",children:e.jsx("iframe",{src:he,title:_e.title,className:"aspect-video w-full",allow:"accelerometer; autoplay; clipboard-write; encrypted-media; picture-in-picture",allowFullScreen:!0})}),ue&&!he&&Aee(_e.video_url)&&e.jsx("div",{className:"overflow-hidden rounded-lg border border-border/60 bg-black",children:e.jsx("video",{src:_e.video_url,controls:!0,autoPlay:!0,className:"aspect-video w-full"})})]})},_e.id)})]}),e.jsx(Xt,{value:"checkin",className:"mt-6",children:e.jsx(Ne,{children:e.jsxs(Ie,{className:"space-y-5 p-6",children:[e.jsxs("div",{children:[e.jsxs("h3",{className:"font-semibold",children:["Week ",R," check-in"]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Two minutes of honesty here is what makes the next week better."})]}),e.jsx("div",{className:"grid gap-4 sm:grid-cols-3",children:[["videos_planned","Videos planned"],["videos_recorded","Videos recorded"],["videos_posted","Videos posted"]].map(([_e,he])=>e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:_e,children:he}),e.jsx(pe,{id:_e,type:"number",min:0,defaultValue:J[_e]??"",onChange:ue=>E(ve=>({...ve,[_e]:Number(ue.target.value)}))})]},_e))}),[["biggest_win","Biggest win"],["biggest_challenge","Biggest challenge"],["what_to_improve","What you’ll change next week"]].map(([_e,he])=>e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:_e,children:he}),e.jsx(Rs,{id:_e,rows:2,defaultValue:J[_e]??"",onChange:ue=>E(ve=>({...ve,[_e]:ue.target.value}))})]},_e)),e.jsx($,{onClick:()=>f.mutate({week_number:R,goal_videos:G,...C}),children:"Save check-in"})]})})}),e.jsxs(Xt,{value:"events",className:"mt-6 space-y-4",children:[X.length===0&&ae.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"Sessions will be scheduled before kickoff."}),X.map(_e=>e.jsx(Ne,{className:"border-primary/30",children:e.jsxs(Ie,{className:"flex flex-wrap items-center gap-4 p-5",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(Be,{variant:"secondary",className:"capitalize",children:String(_e.event_kind).replace("_"," ")}),e.jsxs("span",{className:"inline-flex items-center gap-1 text-xs text-muted-foreground",children:[e.jsx(Kc,{className:"h-3 w-3"})," ",sh(_e.starts_at,!0)]})]}),e.jsx("p",{className:"mt-1.5 font-medium",children:_e.title}),_e.speaker&&e.jsxs("p",{className:"text-sm text-muted-foreground",children:["with ",_e.speaker]}),_e.description&&e.jsx("p",{className:"mt-1 text-sm text-muted-foreground",children:_e.description})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx($,{size:"sm",variant:"outline",onClick:()=>g.mutate({eventId:_e.id,optIn:!0}),children:"Remind me"}),e.jsxs($,{size:"sm",variant:"ghost",onClick:()=>arn(_e,l.name),children:[e.jsx(Kc,{className:"mr-1.5 h-3.5 w-3.5"})," Add to calendar"]}),_e.meeting_link&&e.jsx($,{size:"sm",asChild:!0,children:e.jsxs("a",{href:_e.meeting_link,target:"_blank",rel:"noreferrer",children:["Join ",e.jsx(kr,{className:"ml-1.5 h-3.5 w-3.5"})]})})]})]})},_e.id)),ae.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("h3",{className:"pt-2 text-sm font-semibold uppercase tracking-wider text-muted-foreground",children:"Replays"}),ae.map(_e=>e.jsx(Ne,{children:e.jsxs(Ie,{className:"flex flex-wrap items-center gap-4 p-5",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"font-medium",children:_e.title}),e.jsx("p",{className:"text-xs text-muted-foreground",children:sh(_e.starts_at,!0)})]}),_e.replay_url?e.jsx($,{size:"sm",variant:"outline",asChild:!0,children:e.jsxs("a",{href:_e.replay_url,target:"_blank",rel:"noreferrer",children:[e.jsx(tf,{className:"mr-1.5 h-3.5 w-3.5"})," Watch replay"]})}):e.jsx("span",{className:"text-xs text-muted-foreground",children:"Replay coming soon"})]})},_e.id))]})]}),e.jsxs(Xt,{value:"resources",className:"mt-6 space-y-8",children:[Object.keys(te).length===0&&e.jsx(Ne,{className:"border-dashed",children:e.jsxs(Ie,{className:"flex flex-col items-center gap-2 p-12 text-center",children:[e.jsx(Jr,{className:"h-8 w-8 text-muted-foreground"}),e.jsx("p",{className:"font-medium",children:"Your resource library is being built"}),e.jsx("p",{className:"max-w-md text-sm text-muted-foreground",children:"Worksheets, scripts and swipe files will appear here as the program unlocks."})]})}),Object.entries(te).map(([_e,he])=>e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("h3",{className:"text-sm font-semibold uppercase tracking-[0.18em] text-muted-foreground",children:_e}),e.jsx("span",{className:"h-px flex-1 bg-border"}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[he.length," item",he.length===1?"":"s"]})]}),e.jsx("div",{className:"grid gap-4 md:grid-cols-2 xl:grid-cols-3",children:he.map(ue=>{const ve=lie(ue),Ee=irn[ue.resource_kind]||Jr;return e.jsxs("div",{role:"button",tabIndex:0,onClick:()=>ve&&Eee(ue),onKeyDown:Se=>{ve&&(Se.key==="Enter"||Se.key===" ")&&(Se.preventDefault(),Eee(ue))},className:"group relative flex cursor-pointer flex-col gap-3 overflow-hidden rounded-2xl border border-border/60 bg-card p-5 transition-all hover:-translate-y-0.5 hover:border-primary/50 hover:shadow-lg",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsx("div",{className:"flex h-11 w-11 items-center justify-center rounded-xl bg-primary/10 text-primary",children:e.jsx(Ee,{className:"h-5 w-5"})}),e.jsx(Be,{variant:"secondary",className:"capitalize",children:String(ue.resource_kind).replace("_"," ")})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"font-semibold leading-snug",children:ue.title}),ue.description&&e.jsx("p",{className:"line-clamp-3 text-sm text-muted-foreground",children:ue.description})]}),e.jsxs("div",{className:"mt-auto flex items-center gap-4",children:[e.jsxs("span",{className:"inline-flex items-center gap-1.5 text-sm font-medium text-primary",children:[e.jsx(kr,{className:"h-3.5 w-3.5"})," Open"]}),ue.file_path&&e.jsxs("button",{type:"button",onClick:Se=>{Se.stopPropagation(),Eee(ue,"download")},className:"inline-flex items-center gap-1.5 text-sm font-medium text-muted-foreground hover:text-primary",children:[e.jsx(di,{className:"h-3.5 w-3.5"})," Download"]})]})]},ue.id)})})]},_e))]}),e.jsx(Xt,{value:"profile",className:"mt-6",children:e.jsx(Ne,{children:e.jsxs(Ie,{className:"space-y-4 p-6",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Tf,{className:"h-5 w-5 text-primary"}),e.jsx("h3",{className:"font-semibold",children:"Your profile review"})]}),!(d!=null&&d.analysis)||d.analysis.status==="not_submitted"?e.jsx("p",{className:"text-sm text-muted-foreground",children:"Your Instagram review hasn't been submitted yet. Your coach will request screenshots during onboarding week."}):d.analysis.status==="in_review"?e.jsx("p",{className:"text-sm text-muted-foreground",children:"Your profile is in review — you'll get a notification when the report is ready."}):e.jsxs("div",{className:"space-y-4",children:[d.analysis.scores&&Object.keys(d.analysis.scores).length>0&&e.jsx("div",{className:"grid gap-3 sm:grid-cols-2",children:Object.entries(d.analysis.scores).map(([_e,he])=>e.jsxs("div",{className:"space-y-1 rounded-lg border border-border/60 p-3",children:[e.jsxs("div",{className:"flex justify-between text-sm",children:[e.jsx("span",{className:"capitalize",children:_e.replace(/_/g," ")}),e.jsxs("span",{className:"font-semibold",children:[he,"/10"]})]}),e.jsx(Yi,{value:Number(he)*10,className:"h-1.5"})]},_e))}),Array.isArray(d.analysis.top_priorities)&&d.analysis.top_priorities.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-sm font-semibold",children:"Top priorities"}),e.jsx("ul",{className:"space-y-1.5",children:d.analysis.top_priorities.map((_e,he)=>e.jsxs("li",{className:"flex items-start gap-2 text-sm",children:[e.jsx(Rm,{className:"mt-0.5 h-3.5 w-3.5 shrink-0 text-primary"}),typeof _e=="string"?_e:_e.label]},he))})]}),d.analysis.member_notes&&e.jsx("div",{className:"rounded-lg border border-border/60 bg-muted/30 p-4 text-sm leading-relaxed whitespace-pre-line",children:d.analysis.member_notes}),d.analysis.report_url&&e.jsx($,{variant:"outline",asChild:!0,children:e.jsxs("a",{href:d.analysis.report_url,target:"_blank",rel:"noreferrer",children:[e.jsx(di,{className:"mr-1.5 h-4 w-4"})," Download full report"]})})]})]})})})]})]})})})},mi=j.forwardRef(({className:s,...t},n)=>e.jsx("div",{className:"relative w-full overflow-auto",children:e.jsx("table",{ref:n,className:Pt("w-full caption-bottom text-sm",s),...t})}));mi.displayName="Table";const fi=j.forwardRef(({className:s,...t},n)=>e.jsx("thead",{ref:n,className:Pt("[&_tr]:border-b",s),...t}));fi.displayName="TableHeader";const pi=j.forwardRef(({className:s,...t},n)=>e.jsx("tbody",{ref:n,className:Pt("[&_tr:last-child]:border-0",s),...t}));pi.displayName="TableBody";const lrn=j.forwardRef(({className:s,...t},n)=>e.jsx("tfoot",{ref:n,className:Pt("border-t bg-muted/50 font-medium [&>tr]:last:border-b-0",s),...t}));lrn.displayName="TableFooter";const En=j.forwardRef(({className:s,...t},n)=>e.jsx("tr",{ref:n,className:Pt("border-b transition-colors data-[state=selected]:bg-muted hover:bg-muted/50",s),...t}));En.displayName="TableRow";const Dt=j.forwardRef(({className:s,...t},n)=>e.jsx("th",{ref:n,className:Pt("h-12 px-4 text-left align-middle font-medium text-muted-foreground [&:has([role=checkbox])]:pr-0",s),...t}));Dt.displayName="TableHead";const wt=j.forwardRef(({className:s,...t},n)=>e.jsx("td",{ref:n,className:Pt("p-4 align-middle [&:has([role=checkbox])]:pr-0",s),...t}));wt.displayName="TableCell";const crn=j.forwardRef(({className:s,...t},n)=>e.jsx("caption",{ref:n,className:Pt("mt-4 text-sm text-muted-foreground",s),...t}));crn.displayName="TableCaption";const kde=s=>{if(!s)return"";const t=new Date(s),n=r=>String(r).padStart(2,"0");return`${t.getFullYear()}-${n(t.getMonth()+1)}-${n(t.getDate())}T${n(t.getHours())}:${n(t.getMinutes())}`},Sde=s=>s?new Date(s).toISOString():null,RBe=s=>({name:s.name||"",slug:s.slug||"",subtitle:s.subtitle||"",tagline:s.tagline||"",short_description:s.short_description||"",description:s.description||"",price_cents:s.price_cents??0,currency:s.currency||"usd",capacity:s.capacity??0,duration_weeks:s.duration_weeks??13,weekly_video_goal:s.weekly_video_goal??3,payment_mode:s.payment_mode||"delayed",payment_grace_days:s.payment_grace_days??3,timezone:s.timezone||"America/New_York",accent_color:s.accent_color||"",cover_image_url:s.cover_image_url||"",hero_image_url:s.hero_image_url||"",promo_video_url:s.promo_video_url||"",promo_video_headline:s.promo_video_headline||"",enrollment_open_at:kde(s.enrollment_open_at),enrollment_close_at:kde(s.enrollment_close_at),kickoff_at:kde(s.kickoff_at),charge_at:kde(s.charge_at),status:s.status||"draft",is_public:!!s.is_public,is_featured:!!s.is_featured,sort_order:s.sort_order??0}),drn=({program:s,onSaved:t})=>{const[n,r]=j.useState(()=>RBe(s)),[a,i]=j.useState(!1),[l,o]=j.useState(!1),[c,d]=j.useState(null),u=j.useRef(null),h=j.useRef(null);j.useEffect(()=>{r(RBe(s)),i(!1)},[s.id,s.updated_at]);const m=(y,v)=>{r(b=>({...b,[y]:v})),i(!0)},f=async(y,v)=>{if(!y.type.startsWith("image/")){re.error("Please choose an image file");return}if(y.size>8*1024*1024){re.error("Image must be under 8MB");return}d(v);try{const b=y.name.split(".").pop()||"jpg",w=`programs/${s.id}/${v}-${Date.now()}.${b}`,{error:S}=await q.storage.from("event-images").upload(w,y,{cacheControl:"31536000",upsert:!0});if(S)throw S;const{data:C}=q.storage.from("event-images").getPublicUrl(w);m(v==="cover"?"cover_image_url":"hero_image_url",C.publicUrl),re.success(`${v==="cover"?"Cover":"Hero"} image uploaded — remember to save`)}catch(b){re.error(b.message||"Upload failed")}finally{d(null)}},g=async()=>{if(!n.name.trim())return re.error("Program name is required");if(!n.slug.trim())return re.error("Slug is required");o(!0);try{const y={name:n.name.trim(),slug:n.slug.trim().toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,""),subtitle:n.subtitle||null,tagline:n.tagline||null,short_description:n.short_description||null,description:n.description||null,price_cents:Math.max(0,Math.round(n.price_cents)),currency:n.currency||"usd",capacity:Math.max(0,Math.round(n.capacity)),duration_weeks:Math.max(1,Math.round(n.duration_weeks)),weekly_video_goal:Math.max(0,Math.round(n.weekly_video_goal)),payment_mode:n.payment_mode,payment_grace_days:Math.max(0,Math.round(n.payment_grace_days)),timezone:n.timezone||"America/New_York",accent_color:n.accent_color||null,cover_image_url:n.cover_image_url||null,hero_image_url:n.hero_image_url||null,promo_video_url:n.promo_video_url.trim()||null,promo_video_headline:n.promo_video_headline.trim()||null,enrollment_open_at:Sde(n.enrollment_open_at),enrollment_close_at:Sde(n.enrollment_close_at),kickoff_at:Sde(n.kickoff_at),charge_at:Sde(n.charge_at),status:n.status,is_public:n.is_public,is_featured:n.is_featured,sort_order:Math.round(n.sort_order)},{error:v}=await q.from("programs").update(y).eq("id",s.id);if(v)throw v;re.success("Program saved"),i(!1),t()}catch(y){re.error(y.message||"Could not save the program")}finally{o(!1)}},x=({kind:y,label:v,hint:b})=>{const w=y==="cover"?n.cover_image_url:n.hero_image_url,S=y==="cover"?u:h;return e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:v}),e.jsxs("div",{className:"flex flex-wrap items-start gap-4",children:[e.jsx("div",{className:"relative h-28 w-48 shrink-0 overflow-hidden rounded-lg border border-border bg-muted/40",children:w?e.jsxs(e.Fragment,{children:[e.jsx("img",{src:w,alt:`${v} preview`,className:"h-full w-full object-cover"}),e.jsx("button",{type:"button",onClick:()=>m(y==="cover"?"cover_image_url":"hero_image_url",""),className:"absolute right-1.5 top-1.5 rounded-full bg-background/90 p-1 text-foreground shadow","aria-label":`Remove ${v}`,children:e.jsx(gr,{className:"h-3.5 w-3.5"})})]}):e.jsxs("div",{className:"flex h-full w-full flex-col items-center justify-center gap-1 text-muted-foreground",children:[e.jsx(Av,{className:"h-5 w-5"}),e.jsx("span",{className:"text-xs",children:"No image"})]})}),e.jsxs("div",{className:"min-w-[220px] flex-1 space-y-2",children:[e.jsx("input",{ref:S,type:"file",accept:"image/*",className:"hidden",onChange:C=>{var I;const E=(I=C.target.files)==null?void 0:I[0];E&&f(E,y),C.target.value=""}}),e.jsxs($,{type:"button",variant:"outline",size:"sm",onClick:()=>{var C;return(C=S.current)==null?void 0:C.click()},disabled:c===y,children:[c===y?e.jsx(kt,{className:"mr-1.5 h-4 w-4 animate-spin"}):e.jsx(ni,{className:"mr-1.5 h-4 w-4"}),"Upload image"]}),e.jsx(pe,{placeholder:"…or paste an image URL",value:w,onChange:C=>m(y==="cover"?"cover_image_url":"hero_image_url",C.target.value)}),e.jsx("p",{className:"text-xs text-muted-foreground",children:b})]})]})]})};return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"sticky top-0 z-10 -mx-1 flex flex-wrap items-center justify-between gap-3 rounded-lg border border-border bg-background/95 px-4 py-3 backdrop-blur",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:a?"You have unsaved changes.":"All changes saved."}),e.jsxs("div",{className:"flex gap-2",children:[a&&e.jsx($,{variant:"ghost",onClick:()=>{r(RBe(s)),i(!1)},children:"Discard"}),e.jsxs($,{onClick:g,disabled:l||!a,children:[l?e.jsx(kt,{className:"mr-1.5 h-4 w-4 animate-spin"}):e.jsx(tl,{className:"mr-1.5 h-4 w-4"}),"Save changes"]})]})]}),e.jsx(Ne,{children:e.jsxs(Ie,{className:"space-y-5 p-6",children:[e.jsx("h3",{className:"text-sm font-semibold uppercase tracking-wide text-muted-foreground",children:"Basics"}),e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Program name"}),e.jsx(pe,{value:n.name,onChange:y=>m("name",y.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Slug (public URL)"}),e.jsx(pe,{value:n.slug,onChange:y=>m("slug",y.target.value)}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["/programs/",n.slug||"slug"]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Subtitle"}),e.jsx(pe,{value:n.subtitle,onChange:y=>m("subtitle",y.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Tagline"}),e.jsx(pe,{value:n.tagline,onChange:y=>m("tagline",y.target.value)})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Short description (cards & previews)"}),e.jsx(Rs,{rows:2,value:n.short_description,onChange:y=>m("short_description",y.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Full program description (sales page)"}),e.jsx(Rs,{rows:8,value:n.description,onChange:y=>m("description",y.target.value)})]})]})}),e.jsx(Ne,{children:e.jsxs(Ie,{className:"space-y-6 p-6",children:[e.jsx("h3",{className:"text-sm font-semibold uppercase tracking-wide text-muted-foreground",children:"Imagery & branding"}),e.jsx(x,{kind:"cover",label:"Program cover image",hint:"Shown on the Programs list and enrollment cards. 1200×630 works great."}),e.jsx(x,{kind:"hero",label:"Hero banner (optional)",hint:"Wide banner used at the top of the program sales page."}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Promo video URL (optional)"}),e.jsx(pe,{placeholder:"https://youtu.be/… , Vimeo, or a direct .mp4 link",value:n.promo_video_url,onChange:y=>m("promo_video_url",y.target.value)}),e.jsx(pe,{placeholder:"Video headline (e.g. Watch: what 90 days inside Reel Estate looks like)",value:n.promo_video_headline,onChange:y=>m("promo_video_headline",y.target.value)}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Plays in a cinematic player near the top of the program signup page."})]}),e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Accent color"}),e.jsx(pe,{placeholder:"#406E71",value:n.accent_color,onChange:y=>m("accent_color",y.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Sort order"}),e.jsx(pe,{type:"number",value:n.sort_order,onChange:y=>m("sort_order",Number(y.target.value))})]})]})]})}),e.jsx(Ne,{children:e.jsxs(Ie,{className:"space-y-5 p-6",children:[e.jsx("h3",{className:"text-sm font-semibold uppercase tracking-wide text-muted-foreground",children:"Pricing & seats"}),e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2 lg:grid-cols-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"One-time price (USD)"}),e.jsx(pe,{type:"number",min:0,step:"1",value:n.price_cents/100,onChange:y=>m("price_cents",Math.round(Number(y.target.value)*100))}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Charged one time for the full program — never recurring."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Seats (capacity)"}),e.jsx(pe,{type:"number",min:0,value:n.capacity,onChange:y=>m("capacity",Number(y.target.value))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Billing mode"}),e.jsxs(ms,{value:n.payment_mode,onValueChange:y=>m("payment_mode",y),children:[e.jsx(us,{children:e.jsx(fs,{})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"delayed",children:"Save card, charge once later"}),e.jsx(Ge,{value:"immediate",children:"Charge once at checkout"}),e.jsx(Ge,{value:"free",children:"Free / included"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Charge date (one-time)"}),e.jsx(pe,{type:"datetime-local",value:n.charge_at,onChange:y=>m("charge_at",y.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Payment grace days"}),e.jsx(pe,{type:"number",min:0,value:n.payment_grace_days,onChange:y=>m("payment_grace_days",Number(y.target.value))}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Days of access kept after a failed charge before access is paused."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Currency"}),e.jsx(pe,{value:n.currency,onChange:y=>m("currency",y.target.value)})]})]})]})}),e.jsx(Ne,{children:e.jsxs(Ie,{className:"space-y-5 p-6",children:[e.jsx("h3",{className:"text-sm font-semibold uppercase tracking-wide text-muted-foreground",children:"Schedule & structure"}),e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2 lg:grid-cols-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Enrollment opens"}),e.jsx(pe,{type:"datetime-local",value:n.enrollment_open_at,onChange:y=>m("enrollment_open_at",y.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Enrollment closes"}),e.jsx(pe,{type:"datetime-local",value:n.enrollment_close_at,onChange:y=>m("enrollment_close_at",y.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Kickoff"}),e.jsx(pe,{type:"datetime-local",value:n.kickoff_at,onChange:y=>m("kickoff_at",y.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Length (weeks)"}),e.jsx(pe,{type:"number",min:1,value:n.duration_weeks,onChange:y=>m("duration_weeks",Number(y.target.value))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Videos per week goal"}),e.jsx(pe,{type:"number",min:0,value:n.weekly_video_goal,onChange:y=>m("weekly_video_goal",Number(y.target.value))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Timezone"}),e.jsx(pe,{value:n.timezone,onChange:y=>m("timezone",y.target.value)})]})]})]})}),e.jsx(Ne,{children:e.jsxs(Ie,{className:"space-y-5 p-6",children:[e.jsx("h3",{className:"text-sm font-semibold uppercase tracking-wide text-muted-foreground",children:"Visibility"}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Status"}),e.jsxs(ms,{value:n.status,onValueChange:y=>m("status",y),children:[e.jsx(us,{className:"sm:max-w-xs",children:e.jsx(fs,{})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"draft",children:"Draft (hidden)"}),e.jsx(Ge,{value:"published",children:"Published (members can enroll)"}),e.jsx(Ge,{value:"archived",children:"Archived"})]})]})]}),e.jsxs("div",{className:"flex items-center justify-between gap-4 border-t border-border/60 pt-4",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:"Featured"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Pin this program to the top."})]}),e.jsx(Sn,{checked:n.is_featured,onCheckedChange:y=>m("is_featured",y)})]}),e.jsxs("div",{className:"flex items-center justify-between gap-4 border-t border-border/60 pt-4",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:"Visible to all members"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Turn off to keep it invite-only via a direct link."})]}),e.jsx(Sn,{checked:n.is_public,onCheckedChange:y=>m("is_public",y)})]})]})}),e.jsx("div",{className:"flex justify-end pb-4",children:e.jsxs($,{onClick:g,disabled:l||!a,size:"lg",children:[l?e.jsx(kt,{className:"mr-1.5 h-4 w-4 animate-spin"}):e.jsx(tl,{className:"mr-1.5 h-4 w-4"}),"Save changes"]})})]})},x_t={title:"",description:"",category:"Personal",resource_kind:"pdf",url:"",file_path:"",status:"published",sort_order:0},urn=({programId:s,userId:t,memberName:n})=>{const{data:r=[],isLoading:a}=cWs(s,t),i=dWs(s,t),l=uWs(),[o,c]=j.useState(!1),[d,u]=j.useState({...x_t}),[h,m]=j.useState(!1),f=j.useRef(null),g=()=>{u({...x_t,sort_order:r.length}),c(!0)},x=b=>{u({id:b.id,title:b.title,description:b.description||"",category:b.category||"Personal",resource_kind:b.resource_kind,url:b.url||"",file_path:b.file_path||"",status:b.status,sort_order:b.sort_order}),c(!0)},y=async b=>{if(!(!b||!s||!t)){if(b.size>50*1024*1024)return re.error("File must be under 50MB");m(!0);try{const w=b.name.split(".").pop()||"pdf",S=`programs/${s}/members/${t}/${Date.now()}-${Math.random().toString(36).slice(2,8)}.${w}`,{error:C}=await q.storage.from(xK).upload(S,b,{contentType:b.type||"application/pdf",upsert:!1});if(C)throw C;u(E=>({...E,file_path:S,url:"",title:E.title||b.name.replace(/\.[^.]+$/,""),resource_kind:b.type==="application/pdf"?"pdf":E.resource_kind})),re.success("File uploaded")}catch(w){re.error(w.message||"Upload failed")}finally{m(!1),f.current&&(f.current.value="")}}},v=async()=>{if(!d.title.trim())return re.error("Give the resource a title");if(!d.file_path&&!d.url.trim())return re.error("Upload a file or paste a link");await i.mutateAsync({...d,sort_order:Number(d.sort_order)||0}),c(!1)};return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex flex-wrap items-end justify-between gap-3",children:[e.jsxs("div",{children:[e.jsxs("p",{className:"flex items-center gap-1.5 font-medium",children:[e.jsx(pc,{className:"h-4 w-4 text-primary"})," Personal resources"]}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Only ",n||"this member"," can see these — they appear in a “Just for you” section on their program dashboard."]})]}),e.jsxs($,{size:"sm",onClick:g,disabled:!t,children:[e.jsx(dn,{className:"mr-1.5 h-4 w-4"})," Add for this member"]})]}),a?e.jsx("p",{className:"text-sm text-muted-foreground",children:"Loading…"}):r.length===0?e.jsx(Ne,{className:"border-dashed",children:e.jsx(Ie,{className:"p-6 text-center text-sm text-muted-foreground",children:"No personal resources yet. Upload their custom plan, feedback doc or scripts."})}):e.jsx("div",{className:"space-y-2",children:r.map(b=>e.jsx(Ne,{className:"border-border/60",children:e.jsxs(Ie,{className:"flex flex-wrap items-start justify-between gap-3 p-4",children:[e.jsxs("div",{className:"min-w-0 space-y-1.5",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("p",{className:"font-medium",children:b.title}),e.jsx(Be,{variant:"secondary",children:b.category}),e.jsx(Be,{variant:"outline",className:"capitalize",children:b.resource_kind.replace("_"," ")}),b.status!=="published"&&e.jsx(Be,{variant:"outline",className:"capitalize",children:b.status})]}),b.description&&e.jsx("p",{className:"max-w-xl text-sm text-muted-foreground",children:b.description}),lie(b)&&e.jsxs("button",{type:"button",onClick:()=>Eee(b),className:"inline-flex items-center gap-1 text-xs text-primary hover:underline",children:[e.jsx(kr,{className:"h-3 w-3"})," Open"]})]}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx($,{variant:"ghost",size:"icon",onClick:()=>x(b),children:e.jsx(gi,{className:"h-4 w-4"})}),e.jsx($,{variant:"ghost",size:"icon",onClick:async()=>{await fo(`Remove "${b.title}"?`)&&l.mutate(b)},children:e.jsx(Wn,{className:"h-4 w-4 text-destructive"})})]})]})},b.id))}),e.jsx(zs,{open:o,onOpenChange:c,children:e.jsxs(Os,{className:"max-w-lg",children:[e.jsx(Us,{children:e.jsx(Bs,{children:d.id?"Edit personal resource":"New personal resource"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Title"}),e.jsx(pe,{value:d.title,onChange:b=>u({...d,title:b.target.value}),placeholder:"Your 90-day content plan"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Description"}),e.jsx(Rs,{rows:2,value:d.description,onChange:b=>u({...d,description:b.target.value})})]}),e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Category"}),e.jsx(pe,{value:d.category,onChange:b=>u({...d,category:b.target.value}),placeholder:"Personal"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Type"}),e.jsxs(ms,{value:d.resource_kind,onValueChange:b=>u({...d,resource_kind:b}),children:[e.jsx(us,{children:e.jsx(fs,{})}),e.jsx(hs,{children:XUt.map(b=>e.jsx(Ge,{value:b.value,children:b.label},b.value))})]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"File"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs($,{type:"button",variant:"outline",size:"sm",disabled:h,onClick:()=>{var b;return(b=f.current)==null?void 0:b.click()},children:[h?e.jsx(kt,{className:"mr-1.5 h-4 w-4 animate-spin"}):e.jsx(ni,{className:"mr-1.5 h-4 w-4"}),d.file_path?"Replace file":"Upload file"]}),d.file_path&&e.jsx("span",{className:"truncate text-xs text-muted-foreground",children:d.file_path.split("/").pop()})]}),e.jsx("input",{ref:f,type:"file",hidden:!0,onChange:b=>{var w;return y((w=b.target.files)==null?void 0:w[0])}})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"…or link"}),e.jsx(pe,{value:d.url,onChange:b=>u({...d,url:b.target.value,file_path:""}),placeholder:"https://…"})]}),e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Status"}),e.jsxs(ms,{value:d.status,onValueChange:b=>u({...d,status:b}),children:[e.jsx(us,{children:e.jsx(fs,{})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"published",children:"Published"}),e.jsx(Ge,{value:"draft",children:"Draft"}),e.jsx(Ge,{value:"archived",children:"Archived"})]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Sort order"}),e.jsx(pe,{type:"number",value:d.sort_order,onChange:b=>u({...d,sort_order:b.target.value})})]})]})]}),e.jsxs(Ar,{children:[e.jsx($,{variant:"ghost",onClick:()=>c(!1),children:"Cancel"}),e.jsxs($,{onClick:v,disabled:i.isPending||h,children:[i.isPending&&e.jsx(kt,{className:"mr-1.5 h-4 w-4 animate-spin"})," Save"]})]})]})})]})},hrn=({program:s,enrollment:t,open:n,onOpenChange:r,onUpdated:a})=>{var G,Y,X,ae,ie,ne,te,J,ce,_e;const i=t==null?void 0:t.user_id,[l,o]=j.useState((t==null?void 0:t.admin_notes)||""),[c,d]=j.useState(!1),[u,h]=j.useState(""),[m,f]=j.useState(!1),[g,x]=j.useState(!1),y=j.useRef(null),{data:v,isLoading:b,refetch:w}=tt({queryKey:["admin-program-agent",s.id,i],enabled:n&&!!i,queryFn:async()=>{const[he,ue,ve,Ee,Se,Le,Fe,ke]=await Promise.all([q.from("program_weekly_progress").select("*").eq("program_id",s.id).eq("user_id",i).order("week_number"),q.from("program_video_logs").select("*").eq("program_id",s.id).eq("user_id",i).order("posted_at",{ascending:!1}),q.from("program_lesson_completions").select("*").eq("program_id",s.id).eq("user_id",i),q.from("program_badge_awards").select("*").eq("program_id",s.id).eq("user_id",i),q.from("program_intake_responses").select("*").eq("program_id",s.id).eq("user_id",i).maybeSingle(),q.from("program_event_attendance").select("*").eq("program_id",s.id).eq("user_id",i),q.from("program_lessons").select("id").eq("program_id",s.id),q.from("program_profile_analyses").select("*").eq("program_id",s.id).eq("user_id",i).maybeSingle()]);return{weekly:he.data||[],videos:ue.data||[],completions:ve.data||[],badges:Ee.data||[],intake:Se.data,attendance:Le.data||[],lessonCount:(Fe.data||[]).length,analysis:ke.data}}});j.useEffect(()=>{var he;h(((he=v==null?void 0:v.analysis)==null?void 0:he.member_notes)||"")},[(G=v==null?void 0:v.analysis)==null?void 0:G.id]);const S=j.useMemo(()=>{var ve;const he=mse(s),ue=((ve=v==null?void 0:v.intake)==null?void 0:ve.extra)||{};return he.custom.map(Ee=>({label:Ee.label,value:typeof ue[Ee.id]=="boolean"?ue[Ee.id]?"Yes":"No":ue[Ee.id]||""})).filter(Ee=>!!Ee.value)},[s,v==null?void 0:v.intake]),C=async he=>i?q.from("program_profile_analyses").upsert({program_id:s.id,user_id:i,enrollment_id:(t==null?void 0:t.id)||null,...he},{onConflict:"program_id,user_id"}):{error:{message:"Missing agent"}},E=async he=>{if(he.type!=="application/pdf")return re.error("Please choose a PDF file");if(he.size>25*1024*1024)return re.error("PDF must be under 25MB");x(!0);try{const ue=`programs/${s.id}/reviews/${i}-${Date.now()}.pdf`,{error:ve}=await q.storage.from("event-images").upload(ue,he,{contentType:"application/pdf",upsert:!0});if(ve)throw ve;const{data:Ee}=q.storage.from("event-images").getPublicUrl(ue),{error:Se}=await C({report_url:Ee.publicUrl,status:"ready",reviewed_at:new Date().toISOString()});if(Se)throw Se;re.success("Profile review uploaded"),await w()}catch(ue){re.error(ue.message||"Upload failed")}finally{x(!1)}},I=async()=>{const{error:he}=await C({report_url:null,status:"in_review"});if(he)return re.error(he.message);re.success("Review removed"),await w()},P=async()=>{f(!0);const{error:he}=await C({member_notes:u});if(f(!1),he)return re.error(he.message);re.success("Review notes saved"),await w()},R=async()=>{if(!t)return;d(!0);const{error:he}=await q.from("program_enrollments").update({admin_notes:l}).eq("id",t.id);if(d(!1),he)return re.error(he.message);re.success("Notes saved"),a()},D=((v==null?void 0:v.videos)||[]).filter(he=>he.posted).length,O=(s.weekly_video_goal||0)*(s.duration_weeks||0),U=v!=null&&v.lessonCount?Math.round(((v==null?void 0:v.completions.length)||0)/v.lessonCount*100):0,W=O?Math.min(100,Math.round(D/O*100)):0,V=((v==null?void 0:v.attendance)||[]).filter(he=>he.attended).length;return e.jsx(Wy,{open:n,onOpenChange:r,children:e.jsxs(py,{className:"w-full overflow-y-auto sm:max-w-2xl",children:[e.jsxs(D0,{className:"mb-4",children:[e.jsxs(F0,{children:[((Y=t==null?void 0:t.profile)==null?void 0:Y.name)||"Agent"," · ",s.name]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:(X=t==null?void 0:t.profile)==null?void 0:X.email}),i&&e.jsx($,{variant:"outline",size:"sm",className:"mt-3 w-fit",asChild:!0,children:e.jsxs("a",{href:`/programs/${s.slug}/workspace?preview=1&as=${i}&name=${encodeURIComponent(((ae=t==null?void 0:t.profile)==null?void 0:ae.name)||((ie=t==null?void 0:t.profile)==null?void 0:ie.email)||"this member")}`,target:"_blank",rel:"noreferrer",children:[e.jsx(kr,{className:"mr-2 h-4 w-4"}),"Open their dashboard"]})})]}),t?b?e.jsx(yn,{className:"h-64 w-full rounded-xl"}):e.jsxs("div",{className:"space-y-4 pb-8",children:[e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2",children:[e.jsx(Ne,{children:e.jsxs(Ie,{className:"p-4",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Status"}),e.jsx(Be,{className:"mt-1 capitalize",children:String(t.status).replace(/_/g," ")}),e.jsxs("p",{className:"mt-2 text-xs text-muted-foreground",children:[Cg(t.amount_cents,t.currency)," ·"," ",t.charged_at?`Charged ${sh(t.charged_at)}`:`Charge ${sh(t.charge_scheduled_at)||"not set"}`]})]})}),e.jsx(Ne,{children:e.jsxs(Ie,{className:"p-4",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Last activity"}),e.jsx("p",{className:"mt-1 text-sm font-medium",children:sh(t.last_activity_at,!0)||"No activity yet"}),e.jsxs("p",{className:"mt-2 text-xs text-muted-foreground",children:["Enrolled ",sh(t.created_at)]})]})})]}),e.jsx(Ne,{children:e.jsxs(Ie,{className:"space-y-4 p-5",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"mb-1 flex items-center justify-between text-sm",children:[e.jsx("span",{className:"font-medium",children:"Videos posted"}),e.jsxs("span",{className:"text-muted-foreground",children:[D," / ",O||"—"]})]}),e.jsx(Yi,{value:W})]}),e.jsxs("div",{children:[e.jsxs("div",{className:"mb-1 flex items-center justify-between text-sm",children:[e.jsx("span",{className:"font-medium",children:"Curriculum completed"}),e.jsxs("span",{className:"text-muted-foreground",children:[(v==null?void 0:v.completions.length)||0," / ",(v==null?void 0:v.lessonCount)||0]})]}),e.jsx(Yi,{value:U})]}),e.jsxs("div",{className:"flex flex-wrap gap-4 border-t border-border/60 pt-4 text-sm",children:[e.jsxs("span",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Live sessions attended: "}),V]}),e.jsxs("span",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Badges: "}),(v==null?void 0:v.badges.length)||0]}),e.jsxs("span",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Weeks reported: "}),(v==null?void 0:v.weekly.length)||0]})]})]})}),e.jsx(Ne,{children:e.jsxs(Ie,{className:"p-5",children:[e.jsx("p",{className:"mb-3 text-sm font-semibold",children:"Weekly progress"}),((v==null?void 0:v.weekly.length)||0)===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:"No weekly check-ins yet."}):e.jsx("div",{className:"space-y-3",children:v.weekly.map(he=>e.jsxs("div",{className:"rounded-lg border border-border/60 p-3 text-sm",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("span",{className:"font-medium",children:["Week ",he.week_number]}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[he.videos_posted,"/",he.goal_videos||s.weekly_video_goal," posted ·"," ",he.stories_posted," stories"]})]}),he.biggest_win&&e.jsxs("p",{className:"mt-1 text-muted-foreground",children:["Win: ",he.biggest_win]}),he.biggest_challenge&&e.jsxs("p",{className:"text-muted-foreground",children:["Challenge: ",he.biggest_challenge]})]},he.id))})]})}),e.jsx(Ne,{children:e.jsxs(Ie,{className:"p-5",children:[e.jsx("p",{className:"mb-3 text-sm font-semibold",children:"Video log"}),((v==null?void 0:v.videos.length)||0)===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:"No videos logged yet."}):e.jsx("div",{className:"space-y-2",children:v.videos.slice(0,25).map(he=>e.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[e.jsx(ua,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}),e.jsx("span",{className:"truncate",children:he.title||"Untitled video"}),e.jsxs("span",{className:"ml-auto shrink-0 text-xs text-muted-foreground",children:["Wk ",he.week_number," · ",sh(he.posted_at)]}),he.instagram_url&&e.jsx("a",{href:he.instagram_url,target:"_blank",rel:"noreferrer",className:"shrink-0 text-muted-foreground hover:text-foreground","aria-label":"Open post",children:e.jsx(kr,{className:"h-3.5 w-3.5"})})]},he.id))})]})}),(v==null?void 0:v.intake)&&e.jsx(Ne,{children:e.jsxs(Ie,{className:"space-y-1 p-5 text-sm",children:[e.jsx("p",{className:"mb-2 text-sm font-semibold",children:"Intake answers"}),[["Full name",v.intake.full_name],["Email",v.intake.email],["Phone",v.intake.phone],["Instagram",v.intake.instagram_handle],["City / market",v.intake.city],["Areas served",v.intake.service_areas],["Years in real estate",v.intake.years_experience],["Specialty",v.intake.specialty],["Target audience",v.intake.target_audience],["On camera",v.intake.video_comfort],["Posts today",v.intake.posting_frequency],["Content style",v.intake.content_style],["Interests",v.intake.personal_interests],["#1 goal",v.intake.primary_goal],["Topics to avoid",v.intake.topics_to_avoid],["Time zone",v.intake.timezone]].filter(([,he])=>!!he).map(([he,ue])=>e.jsxs("p",{children:[e.jsxs("span",{className:"text-muted-foreground",children:[he,": "]}),ue]},he)),S.map(({label:he,value:ue})=>e.jsxs("p",{children:[e.jsxs("span",{className:"text-muted-foreground",children:[he,": "]}),ue]},he)),e.jsxs("p",{className:"pt-1 text-xs text-muted-foreground",children:["Content-sharing consent: ",v.intake.consent_public_profile?"Yes":"No"]})]})}),e.jsx(Ne,{children:e.jsx(Ie,{className:"p-5",children:e.jsx(urn,{programId:s.id,userId:i,memberName:(ne=t==null?void 0:t.profile)==null?void 0:ne.name})})}),e.jsx(Ne,{children:e.jsxs(Ie,{className:"space-y-3 p-5",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-semibold",children:"Profile review PDF"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Upload this agent's personalized profile review. They see it in their workspace."})]}),((te=v==null?void 0:v.analysis)==null?void 0:te.status)&&e.jsx(Be,{variant:"secondary",className:"capitalize",children:String(v.analysis.status).replace(/_/g," ")})]}),(J=v==null?void 0:v.analysis)!=null&&J.report_url?e.jsxs("div",{className:"flex flex-wrap items-center gap-2 rounded-lg border border-border/60 p-3 text-sm",children:[e.jsx(Jr,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"truncate",children:"Review uploaded"}),e.jsxs("a",{href:v.analysis.report_url,target:"_blank",rel:"noreferrer",className:"ml-auto inline-flex items-center gap-1 text-primary hover:underline",children:["View ",e.jsx(kr,{className:"h-3.5 w-3.5"})]})]}):e.jsx("p",{className:"text-sm text-muted-foreground",children:"No review uploaded yet."}),e.jsx("input",{ref:y,type:"file",accept:"application/pdf",className:"hidden",onChange:he=>{var ve;const ue=(ve=he.target.files)==null?void 0:ve[0];ue&&E(ue),he.target.value=""}}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs($,{size:"sm",variant:"outline",onClick:()=>{var he;return(he=y.current)==null?void 0:he.click()},disabled:g,children:[e.jsx(ni,{className:"mr-1.5 h-3.5 w-3.5"}),g?"Uploading…":(ce=v==null?void 0:v.analysis)!=null&&ce.report_url?"Replace PDF":"Upload PDF"]}),((_e=v==null?void 0:v.analysis)==null?void 0:_e.report_url)&&e.jsx($,{size:"sm",variant:"ghost",onClick:I,children:"Remove"})]}),e.jsxs("div",{className:"space-y-2 pt-1",children:[e.jsx(ee,{children:"Review summary shown to the agent (optional)"}),e.jsx(Rs,{rows:3,value:u,onChange:he=>h(he.target.value),placeholder:"Top 3 priorities, quick wins, what to fix first…"}),e.jsx("div",{className:"flex justify-end",children:e.jsx($,{size:"sm",variant:"outline",onClick:P,disabled:m,children:"Save review notes"})})]})]})}),e.jsx(Ne,{children:e.jsxs(Ie,{className:"space-y-3 p-5",children:[e.jsx(ee,{children:"Coach notes (internal)"}),e.jsx(Rs,{rows:4,value:l,onChange:he=>o(he.target.value)}),e.jsx("div",{className:"flex justify-end",children:e.jsx($,{size:"sm",onClick:R,disabled:c,children:"Save notes"})})]})})]}):null]})})},y_t={code:"",label:"",kind:"percent",percent_off:"20",amount_off:"",max_redemptions:"",starts_at:"",expires_at:"",is_active:!0},v_t=s=>{if(!s)return"";const t=new Date(s),n=t.getTimezoneOffset();return new Date(t.getTime()-n*6e4).toISOString().slice(0,16)},mrn=({program:s})=>{const{data:t=[],isLoading:n}=ZGs(s.id),r=XGs(s.id),a=QGs(),[i,l]=j.useState(!1),[o,c]=j.useState({...y_t}),d=()=>{c({...y_t}),l(!0)},u=g=>{c({id:g.id,code:g.code,label:g.label||"",kind:g.percent_off!=null?"percent":"amount",percent_off:g.percent_off!=null?String(g.percent_off):"",amount_off:g.amount_off_cents!=null?String(g.amount_off_cents/100):"",max_redemptions:g.max_redemptions!=null?String(g.max_redemptions):"",starts_at:v_t(g.starts_at),expires_at:v_t(g.expires_at),is_active:g.is_active}),l(!0)},h=j.useMemo(()=>{const g=o.kind==="percent"?Math.floor(s.price_cents*Number(o.percent_off||0)/100):Math.round(Number(o.amount_off||0)*100),x=Math.min(Math.max(g,0),s.price_cents);return{discount:x,final:s.price_cents-x}},[o,s.price_cents]),m=async()=>{if(!o.code.trim())return re.error("Give the code a name, e.g. FOUNDER50");await r.mutateAsync({id:o.id,code:o.code,label:o.label||null,percent_off:o.kind==="percent"?Number(o.percent_off)||0:null,amount_off_cents:o.kind==="amount"?Math.round(Number(o.amount_off||0)*100):null,max_redemptions:o.max_redemptions?Number(o.max_redemptions):null,starts_at:o.starts_at?new Date(o.starts_at).toISOString():null,expires_at:o.expires_at?new Date(o.expires_at).toISOString():null,is_active:o.is_active}),l(!1)},f=g=>{const x=g.percent_off!=null?Math.floor(s.price_cents*Number(g.percent_off)/100):g.amount_off_cents||0,y=Math.max(s.price_cents-Math.min(x,s.price_cents),0);return{off:g.percent_off!=null?`${Number(g.percent_off)}% off`:`${Cg(g.amount_off_cents||0,s.currency)} off`,final:Cg(y,s.currency)}};return e.jsxs("div",{className:"space-y-4",children:[e.jsx(Ne,{children:e.jsxs(Ie,{className:"flex flex-wrap items-center justify-between gap-4 p-5",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:"Discount codes"}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Enrollees can enter a code on the final enrollment step. The discount is applied to the one-time ",Cg(s.price_cents,s.currency)," charge."]})]}),e.jsxs(zs,{open:i,onOpenChange:l,children:[e.jsx(jl,{asChild:!0,children:e.jsxs($,{onClick:d,children:[e.jsx(dn,{className:"mr-1.5 h-4 w-4"})," New code"]})}),e.jsxs(Os,{className:"max-h-[85vh] overflow-y-auto",children:[e.jsx(Us,{children:e.jsx(Bs,{children:o.id?"Edit discount code":"Create a discount code"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Code"}),e.jsx(pe,{placeholder:"FOUNDER50",value:o.code,onChange:g=>c({...o,code:g.target.value.toUpperCase()})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Internal label (optional)"}),e.jsx(pe,{placeholder:"Founding cohort",value:o.label,onChange:g=>c({...o,label:g.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Discount type"}),e.jsxs(ms,{value:o.kind,onValueChange:g=>c({...o,kind:g}),children:[e.jsx(us,{children:e.jsx(fs,{})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"percent",children:"Percent off"}),e.jsx(Ge,{value:"amount",children:"Dollar amount off"})]})]})]}),o.kind==="percent"?e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Percent off"}),e.jsx(pe,{type:"number",min:1,max:100,value:o.percent_off,onChange:g=>c({...o,percent_off:g.target.value})})]}):e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Amount off (USD)"}),e.jsx(pe,{type:"number",min:0,value:o.amount_off,onChange:g=>c({...o,amount_off:g.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Max redemptions (blank = unlimited)"}),e.jsx(pe,{type:"number",min:1,value:o.max_redemptions,onChange:g=>c({...o,max_redemptions:g.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Active from (optional)"}),e.jsx(pe,{type:"datetime-local",value:o.starts_at,onChange:g=>c({...o,starts_at:g.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Expires (optional)"}),e.jsx(pe,{type:"datetime-local",value:o.expires_at,onChange:g=>c({...o,expires_at:g.target.value})})]})]}),e.jsxs("div",{className:"flex items-center justify-between rounded-lg border border-border/60 p-4",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",children:"Code is active"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Turn off to stop new redemptions instantly."})]}),e.jsx(Sn,{checked:o.is_active,onCheckedChange:g=>c({...o,is_active:g})})]}),e.jsxs("div",{className:"rounded-lg border border-primary/30 bg-primary/5 p-4 text-sm",children:[e.jsx("p",{className:"font-medium",children:"Enrollee sees"}),e.jsxs("p",{className:"mt-1 text-muted-foreground",children:[Cg(s.price_cents,s.currency)," →"," ",e.jsx("span",{className:"font-semibold text-foreground",children:Cg(h.final,s.currency)})," ","(",Cg(h.discount,s.currency)," off) — charged one time."]})]})]}),e.jsx(Ar,{children:e.jsxs($,{onClick:m,disabled:r.isPending,children:[r.isPending&&e.jsx(kt,{className:"mr-1.5 h-4 w-4 animate-spin"}),o.id?"Save changes":"Create code"]})})]})]})]})}),n?e.jsx(yn,{className:"h-40 w-full rounded-xl"}):t.length===0?e.jsx(Ne,{className:"border-dashed",children:e.jsxs(Ie,{className:"flex flex-col items-center gap-3 p-12 text-center",children:[e.jsx(Ap,{className:"h-8 w-8 text-muted-foreground"}),e.jsx("p",{className:"font-medium",children:"No discount codes yet"}),e.jsx("p",{className:"max-w-md text-sm text-muted-foreground",children:"Create a code for early birds, brokerage partners or a founding cohort. Codes are entered by the enrollee at checkout and change the one-time price."})]})}):e.jsx(Ne,{children:e.jsx(Ie,{className:"overflow-x-auto p-0",children:e.jsxs(mi,{children:[e.jsx(fi,{children:e.jsxs(En,{children:[e.jsx(Dt,{children:"Code"}),e.jsx(Dt,{children:"Discount"}),e.jsx(Dt,{children:"Price after"}),e.jsx(Dt,{children:"Used"}),e.jsx(Dt,{children:"Window"}),e.jsx(Dt,{children:"Status"}),e.jsx(Dt,{className:"text-right",children:"Actions"})]})}),e.jsx(pi,{children:t.map(g=>{const x=f(g);return e.jsxs(En,{children:[e.jsxs(wt,{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"font-mono font-semibold",children:g.code}),e.jsx($,{variant:"ghost",size:"icon",className:"h-6 w-6",onClick:()=>{navigator.clipboard.writeText(g.code),re.success("Code copied")},children:e.jsx(Ha,{className:"h-3.5 w-3.5"})})]}),g.label&&e.jsx("p",{className:"text-xs text-muted-foreground",children:g.label})]}),e.jsx(wt,{className:"whitespace-nowrap",children:e.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[e.jsx(Rw,{className:"h-3.5 w-3.5 text-muted-foreground"}),x.off]})}),e.jsx(wt,{className:"font-medium",children:x.final}),e.jsxs(wt,{children:[g.times_redeemed,g.max_redemptions?` / ${g.max_redemptions}`:""]}),e.jsxs(wt,{className:"text-xs text-muted-foreground",children:[g.starts_at?`From ${sh(g.starts_at)}`:"Anytime",g.expires_at?` · until ${sh(g.expires_at)}`:""]}),e.jsx(wt,{children:e.jsx(Be,{variant:g.is_active?"default":"secondary",children:g.is_active?"Active":"Paused"})}),e.jsx(wt,{className:"text-right",children:e.jsxs("div",{className:"flex justify-end gap-1",children:[e.jsx($,{variant:"outline",size:"sm",onClick:()=>u(g),children:"Edit"}),e.jsx($,{variant:"ghost",size:"icon",onClick:async()=>{await fo(`Delete ${g.code}?`)&&a.mutate(g.id)},children:e.jsx(Wn,{className:"h-4 w-4 text-destructive"})})]})})]},g.id)})})]})})})]})},r5=({ok:s,label:t,detail:n})=>e.jsxs("div",{className:"flex items-start gap-3 border-b border-border/50 py-3 last:border-0",children:[s?e.jsx(qr,{className:"mt-0.5 h-4 w-4 shrink-0 text-primary"}):e.jsx(wl,{className:"mt-0.5 h-4 w-4 shrink-0 text-amber-500"}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-sm font-medium",children:t}),n&&e.jsx("p",{className:"text-xs text-muted-foreground",children:n})]})]}),frn=({program:s})=>{var c,d;const{data:t,isLoading:n}=tt({queryKey:["admin-program-content-counts",s.id],queryFn:async()=>{const[u,h,m,f,g]=await Promise.all([q.from("program_weeks").select("id, week_number, title").eq("program_id",s.id),q.from("program_lessons").select("id, title").eq("program_id",s.id),q.from("program_resources").select("id, title").eq("program_id",s.id),q.from("program_events").select("id, title, starts_at").eq("program_id",s.id),q.from("program_announcements").select("id, title").eq("program_id",s.id)]);return{weeks:u.data||[],lessons:h.data||[],resources:m.data||[],events:f.data||[],announcements:g.data||[]}}}),{notOpenYet:r,closed:a,opensLabel:i}=E6e(s),l=`/programs/${s.slug}`,o=[{icon:Nn,title:"1 · Sales page",body:`${s.name} — hero image, ${s.subtitle?"subtitle":"no subtitle"}, description, price, dates, seats left and FAQ.`,href:l,cta:"Preview sales page"},{icon:sV,title:"2 · Enrollment intake",body:"4 steps: business profile, content style, goals, then the seat + payment summary with the discount-code field.",href:`${l}/enroll`,cta:"Preview enrollment flow"},{icon:Cv,title:"3 · Checkout",body:s.payment_mode==="free"?"Free program — seat is confirmed instantly, no card collected.":s.payment_mode==="delayed"?`Stripe collects and saves the card today. The single ${Cg(s.price_cents,s.currency)} charge runs on ${sh(s.charge_at||s.kickoff_at)||"the charge date (not set)"}.`:`Stripe charges ${Cg(s.price_cents,s.currency)} once at checkout.`},{icon:mn,title:"4 · Emails",body:"Confirmation right after enrollment, then payment receipt (or a payment-failed action email) when the one-time charge runs."},{icon:Yq,title:"5 · Program workspace",body:`Their home base: progress dashboard, ${s.duration_weeks}-week roadmap, lessons, resources, events, weekly check-ins and video logging (${s.weekly_video_goal}/week goal).`,href:`${l}/workspace?preview=1`,cta:"Preview workspace as an enrollee"}];return e.jsxs("div",{className:"space-y-6",children:[e.jsx(Ne,{children:e.jsxs(Ie,{className:"flex flex-wrap items-center justify-between gap-4 p-5",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:"What enrollees see"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Walk the exact member journey end to end. Workspace preview opens in read-only admin mode — it does not create an enrollment."})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx($,{variant:"outline",asChild:!0,children:e.jsxs("a",{href:l,target:"_blank",rel:"noreferrer",children:["Sales page ",e.jsx(kr,{className:"ml-1.5 h-3.5 w-3.5"})]})}),e.jsx($,{asChild:!0,children:e.jsxs("a",{href:`${l}/workspace?preview=1`,target:"_blank",rel:"noreferrer",children:["Workspace preview ",e.jsx(kr,{className:"ml-1.5 h-3.5 w-3.5"})]})})]})]})}),(s.status!=="published"||r||a)&&e.jsx(Ne,{className:"border-amber-500/40 bg-amber-500/5",children:e.jsxs(Ie,{className:"flex items-start gap-3 p-5 text-sm",children:[e.jsx(wl,{className:"mt-0.5 h-4 w-4 shrink-0 text-amber-500"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:"Members can't enroll right now"}),e.jsx("p",{className:"text-muted-foreground",children:s.status!=="published"?`This program is ${s.status} — it isn't listed on the member Programs page yet.`:r?`Enrollment opens ${i}. CTAs are disabled until then.`:"Enrollment has closed for this cohort."})]})]})}),e.jsxs("div",{className:"grid gap-4 lg:grid-cols-2",children:[e.jsx(Ne,{children:e.jsxs(Ie,{className:"space-y-3 p-5",children:[e.jsx("p",{className:"text-xs font-semibold uppercase tracking-wider text-muted-foreground",children:"The enrollee journey"}),e.jsx("div",{className:"space-y-4",children:o.map(u=>e.jsxs("div",{className:"flex gap-3",children:[e.jsx("div",{className:"mt-0.5 flex h-8 w-8 shrink-0 items-center justify-center rounded-lg bg-primary/10",children:e.jsx(u.icon,{className:"h-4 w-4 text-primary"})}),e.jsxs("div",{className:"min-w-0 space-y-1",children:[e.jsx("p",{className:"text-sm font-medium",children:u.title}),e.jsx("p",{className:"text-sm text-muted-foreground",children:u.body}),u.href&&e.jsx($,{variant:"link",size:"sm",className:"h-auto p-0",asChild:!0,children:e.jsxs("a",{href:u.href,target:"_blank",rel:"noreferrer",children:[u.cta," ",e.jsx(kr,{className:"ml-1 h-3 w-3"})]})})]})]},u.title))})]})}),e.jsx(Ne,{children:e.jsxs(Ie,{className:"p-5",children:[e.jsx("p",{className:"text-xs font-semibold uppercase tracking-wider text-muted-foreground",children:"Premium-experience checklist"}),n?e.jsx(yn,{className:"mt-4 h-64 w-full rounded-lg"}):e.jsxs("div",{className:"mt-2",children:[e.jsx(r5,{ok:!!s.cover_image_url,label:"Cover image",detail:s.cover_image_url?"Set":"Missing — cards look empty on the Programs page"}),e.jsx(r5,{ok:!!s.hero_image_url,label:"Hero image on the sales page",detail:s.hero_image_url?"Set":"Missing — sales page falls back to a gradient"}),e.jsx(r5,{ok:!!s.short_description&&!!s.description,label:"Short + full description",detail:s.short_description&&s.description?"Both written":"Fill both in Details & pricing so the sales page reads well"}),e.jsx(r5,{ok:s.payment_mode==="free"||s.price_cents>0,label:"One-time price",detail:s.payment_mode==="free"?"Free / included":Cg(s.price_cents,s.currency)}),e.jsx(r5,{ok:!!s.kickoff_at&&(s.payment_mode==="free"||!!s.charge_at),label:"Kickoff and charge dates",detail:`Kickoff ${sh(s.kickoff_at)||"not set"} · charge ${sh(s.charge_at)||"not set"}`}),e.jsx(r5,{ok:((t==null?void 0:t.weeks.length)||0)>0,label:"Weekly roadmap",detail:`${(t==null?void 0:t.weeks.length)||0} of ${s.duration_weeks} weeks built`}),e.jsx(r5,{ok:((t==null?void 0:t.lessons.length)||0)>0,label:"Lessons",detail:`${(t==null?void 0:t.lessons.length)||0} lessons — the workspace Curriculum tab is empty without these`}),e.jsx(r5,{ok:((t==null?void 0:t.resources.length)||0)>0,label:"Resources / downloads",detail:`${(t==null?void 0:t.resources.length)||0} resources`}),e.jsx(r5,{ok:((t==null?void 0:t.events.length)||0)>0,label:"Live calls on the calendar",detail:`${(t==null?void 0:t.events.length)||0} events${(d=(c=t==null?void 0:t.events)==null?void 0:c[0])!=null&&d.starts_at?` · next ${sh(t.events[0].starts_at)}`:""}`}),e.jsx(r5,{ok:((t==null?void 0:t.announcements.length)||0)>0,label:"Welcome announcement",detail:`${(t==null?void 0:t.announcements.length)||0} announcements — a day-one welcome post makes the workspace feel alive`})]})]})})]}),t&&e.jsx(Ne,{children:e.jsx(Ie,{className:"grid gap-4 p-5 sm:grid-cols-2 lg:grid-cols-5",children:[{icon:Kc,label:"Weeks",value:t.weeks.length},{icon:Jr,label:"Lessons",value:t.lessons.length},{icon:Jr,label:"Resources",value:t.resources.length},{icon:Kc,label:"Events",value:t.events.length},{icon:xm,label:"Announcements",value:t.announcements.length}].map((u,h)=>e.jsxs("div",{className:"rounded-lg border border-border/60 p-4",children:[e.jsx(u.icon,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("p",{className:"mt-2 text-2xl font-bold",children:u.value}),e.jsx("p",{className:"text-xs text-muted-foreground",children:u.label})]},h))})}),e.jsx(Be,{variant:"outline",className:"text-xs",children:"Tip: preview in an incognito window as a test member to see the real enrollment flow end to end."})]})},prn=["Step 1 · Your business","Step 2 · Your content","Step 3 · Your goals"],grn={short_text:"Short answer",long_text:"Paragraph",select:"Dropdown",checkbox:"Yes / no checkbox"},xrn=({program:s,onSaved:t})=>{const[n,r]=j.useState(()=>mse(s)),[a,i]=j.useState(!1),[l,o]=j.useState(!1);j.useEffect(()=>{r(mse(s)),i(!1)},[s.id,s.updated_at]);const c=y=>{r(v=>({...v,...y})),i(!0)},d=(y,v)=>{const b=v?n.hidden.filter(S=>S!==y):[...new Set([...n.hidden,y])],w=v?n.required:n.required.filter(S=>S!==y);c({hidden:b,required:w})},u=(y,v)=>{c({required:v?[...new Set([...n.required,y])]:n.required.filter(b=>b!==y)})},h=()=>{const y={id:`q_${Date.now().toString(36)}`,label:"",type:"short_text",required:!1,options:[]};c({custom:[...n.custom,y]})},m=(y,v)=>c({custom:n.custom.map(b=>b.id===y?{...b,...v}:b)}),f=y=>c({custom:n.custom.filter(v=>v.id!==y)}),g=(y,v)=>{const b=[...n.custom],w=y+v;w<0||w>=b.length||([b[y],b[w]]=[b[w],b[y]],c({custom:b}))},x=async()=>{if(n.custom.find(w=>!w.label.trim()))return re.error("Every custom question needs a label");o(!0);const v={...s.sales_copy||{},intake:n},{error:b}=await q.from("programs").update({sales_copy:v}).eq("id",s.id);if(o(!1),b)return re.error(b.message);i(!1),re.success("Intake form saved"),t==null||t()};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",{children:[e.jsx("p",{className:"text-sm font-semibold",children:"Intake form"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Controls the questions each agent answers during enrollment."})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx($,{variant:"outline",size:"sm",asChild:!0,children:e.jsxs("a",{href:`/programs/${s.slug}/enroll`,target:"_blank",rel:"noreferrer",children:[e.jsx(kr,{className:"mr-1.5 h-3.5 w-3.5"})," Preview form"]})}),e.jsxs($,{size:"sm",onClick:x,disabled:!a||l,children:[e.jsx(tl,{className:"mr-1.5 h-3.5 w-3.5"}),l?"Saving…":"Save intake form"]})]})]}),e.jsxs(Ne,{children:[e.jsx(Ct,{className:"pb-3",children:e.jsx(At,{className:"text-sm",children:"Intro message"})}),e.jsx(Ie,{children:e.jsx(Rs,{rows:3,placeholder:"Shown at the top of the intake — e.g. “Answer a few questions so we can personalize your 90 days.”",value:n.intro||"",onChange:y=>c({intro:y.target.value})})})]}),[0,1,2].map(y=>e.jsxs(Ne,{children:[e.jsx(Ct,{className:"pb-3",children:e.jsx(At,{className:"text-sm",children:prn[y]})}),e.jsxs(Ie,{className:"space-y-2",children:[e.jsxs("div",{className:"hidden grid-cols-[1fr,auto,auto] gap-4 pb-1 text-xs uppercase tracking-wide text-muted-foreground sm:grid",children:[e.jsx("span",{children:"Question"}),e.jsx("span",{className:"w-16 text-center",children:"Show"}),e.jsx("span",{className:"w-16 text-center",children:"Required"})]}),cnt.filter(v=>v.step===y).map(v=>{const b=!n.hidden.includes(v.key);return e.jsxs("div",{className:"grid grid-cols-[1fr,auto,auto] items-center gap-4 rounded-lg border border-border/60 px-3 py-2",children:[e.jsx("span",{className:"text-sm",children:v.label}),e.jsx("div",{className:"flex w-16 justify-center",children:e.jsx(Sn,{checked:b,onCheckedChange:w=>d(v.key,w),"aria-label":`Show ${v.label}`})}),e.jsx("div",{className:"flex w-16 justify-center",children:e.jsx(Sn,{checked:n.required.includes(v.key),disabled:!b,onCheckedChange:w=>u(v.key,w),"aria-label":`Require ${v.label}`})})]},v.key)})]})]},y)),e.jsxs(Ne,{children:[e.jsxs(Ct,{className:"flex-row items-center justify-between space-y-0 pb-3",children:[e.jsxs(At,{className:"text-sm",children:["Custom questions"," ",e.jsx(Be,{variant:"secondary",className:"ml-1",children:n.custom.length})]}),e.jsxs($,{size:"sm",variant:"outline",onClick:h,children:[e.jsx(dn,{className:"mr-1.5 h-3.5 w-3.5"})," Add question"]})]}),e.jsxs(Ie,{className:"space-y-3",children:[n.custom.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"No custom questions yet. Add program-specific questions here — answers appear on each agent's dashboard."}),n.custom.map((y,v)=>e.jsxs("div",{className:"space-y-3 rounded-lg border border-border/60 p-4",children:[e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx("div",{className:"flex flex-col pt-1.5",children:e.jsx("button",{type:"button",className:"text-muted-foreground hover:text-foreground",onClick:()=>g(v,-1),"aria-label":"Move up",children:e.jsx(Ug,{className:"h-4 w-4"})})}),e.jsxs("div",{className:"grid flex-1 gap-3 sm:grid-cols-[2fr,1fr]",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{className:"text-xs",children:"Question"}),e.jsx(pe,{value:y.label,placeholder:"What is your biggest content roadblock?",onChange:b=>m(y.id,{label:b.target.value})})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{className:"text-xs",children:"Answer type"}),e.jsxs(ms,{value:y.type,onValueChange:b=>m(y.id,{type:b}),children:[e.jsx(us,{children:e.jsx(fs,{})}),e.jsx(hs,{children:Object.entries(grn).map(([b,w])=>e.jsx(Ge,{value:b,children:w},b))})]})]})]}),e.jsx($,{size:"icon",variant:"ghost",onClick:()=>f(y.id),"aria-label":"Delete question",children:e.jsx(Wn,{className:"h-4 w-4 text-destructive"})})]}),y.type==="select"&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{className:"text-xs",children:"Options (one per line)"}),e.jsx(Rs,{rows:3,value:(y.options||[]).join(` `),onChange:b=>m(y.id,{options:b.target.value.split(` `).map(w=>w.trim()).filter(Boolean)})})]}),e.jsxs("div",{className:"grid gap-3 sm:grid-cols-[1fr,auto]",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{className:"text-xs",children:"Helper text (optional)"}),e.jsx(pe,{value:y.help||"",onChange:b=>m(y.id,{help:b.target.value})})]}),e.jsxs("div",{className:"flex items-center gap-2 pt-6",children:[e.jsx(Sn,{checked:!!y.required,onCheckedChange:b=>m(y.id,{required:b}),"aria-label":"Required"}),e.jsx("span",{className:"text-sm",children:"Required"})]})]})]},y.id))]})]})]})},j1=LHt,N1=MHt,k1=IHt,yrn=[Sx,Jr,rh],vrn=["Business profile","Content style","Goals & consent"],brn=({fieldKey:s})=>s.includes("phone")?e.jsx(Da,{className:"h-3.5 w-3.5"}):s.includes("email")?e.jsx(mn,{className:"h-3.5 w-3.5"}):s.includes("instagram")?e.jsx(Tf,{className:"h-3.5 w-3.5"}):s.includes("city")||s.includes("area")?e.jsx(ci,{className:"h-3.5 w-3.5"}):s.includes("timezone")?e.jsx(da,{className:"h-3.5 w-3.5"}):s.includes("consent")?s.includes("true")?e.jsx(qr,{className:"h-3.5 w-3.5"}):e.jsx(ku,{className:"h-3.5 w-3.5"}):e.jsx(sl,{className:"h-3.5 w-3.5"}),b_t=(s,t)=>s==null||s===""?"—":typeof s=="boolean"?s?e.jsxs("span",{className:"inline-flex items-center gap-1 text-emerald-600",children:[e.jsx(qr,{className:"h-3.5 w-3.5"})," Yes"]}):e.jsxs("span",{className:"inline-flex items-center gap-1 text-muted-foreground",children:[e.jsx(ku,{className:"h-3.5 w-3.5"})," No"]}):String(s),_rn=({program:s})=>{const[t,n]=j.useState(""),[r,a]=j.useState(new Set),{data:i=[],isLoading:l}=tt({queryKey:["admin-program-intakes",s.id],queryFn:async()=>{const{data:h,error:m}=await q.from("program_intake_responses").select("*").eq("program_id",s.id).order("created_at",{ascending:!1});if(m)throw m;return h||[]}}),o=mse(s),c=cnt.filter(h=>!o.hidden.includes(h.key)),d=i.filter(h=>{const m=t.toLowerCase();return m?String(h.full_name||"").toLowerCase().includes(m)||String(h.email||"").toLowerCase().includes(m)||String(h.city||"").toLowerCase().includes(m)||Object.values(h).some(f=>String(f).toLowerCase().includes(m)):!0}),u=h=>{const m=new Set(r);m.has(h)?m.delete(h):m.add(h),a(m)};return l?e.jsx(yn,{className:"h-96 w-full rounded-xl"}):i.length===0?e.jsx(Ne,{className:"border-dashed",children:e.jsxs(Ie,{className:"p-12 text-center text-sm text-muted-foreground",children:[e.jsx(Jr,{className:"mx-auto mb-3 h-6 w-6"}),e.jsx("p",{children:"No intake responses yet."}),e.jsx("p",{className:"mt-1 text-xs",children:"Responses appear here once members complete the enrollment intake form."})]})}):e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-semibold",children:"Intake responses"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[d.length," of ",i.length," response",i.length===1?"":"s"," · every field from the enrollment intake form"]})]}),e.jsxs("div",{className:"relative w-full sm:w-64",children:[e.jsx(Kr,{className:"absolute left-2.5 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(pe,{placeholder:"Search responses…",value:t,onChange:h=>n(h.target.value),className:"pl-9"})]})]}),d.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"No responses match your search."}),e.jsx("div",{className:"space-y-3",children:d.map(h=>{const m=r.has(h.id),f=sh(h.created_at,!0);return e.jsx(Ne,{className:"overflow-hidden",children:e.jsxs(j1,{open:m,onOpenChange:()=>u(h.id),children:[e.jsx(N1,{asChild:!0,children:e.jsxs(Ct,{className:"flex cursor-pointer flex-row items-center justify-between gap-3 bg-muted/30 px-5 py-3 hover:bg-muted/50",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"flex h-9 w-9 items-center justify-center rounded-full bg-primary/10",children:e.jsx(sl,{className:"h-4 w-4 text-primary"})}),e.jsxs("div",{children:[e.jsxs(At,{className:"text-sm font-semibold",children:[h.full_name||"Unnamed member",h.city&&e.jsxs("span",{className:"ml-2 font-normal text-muted-foreground",children:["· ",h.city]})]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[h.email,h.email&&h.phone&&" · ",h.phone]})]})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("div",{className:"hidden text-right sm:block",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Submitted"}),e.jsx("p",{className:"text-xs font-medium",children:f})]}),e.jsx($,{variant:"ghost",size:"icon",className:"h-8 w-8 shrink-0",children:e.jsx(Tl,{className:`h-4 w-4 transition-transform ${m?"rotate-180":""}`})})]})]})}),e.jsx(k1,{children:e.jsxs(Ie,{className:"space-y-5 p-5",children:[[0,1,2].map(g=>{const x=c.filter(v=>v.step===g),y=yrn[g];return x.length===0?null:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2 border-b border-border/40 pb-2",children:[e.jsx("div",{className:"flex h-6 w-6 items-center justify-center rounded-md bg-primary/10",children:e.jsx(y,{className:"h-3.5 w-3.5 text-primary"})}),e.jsx("p",{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:vrn[g]})]}),e.jsx("div",{className:"grid gap-3 sm:grid-cols-2 lg:grid-cols-3",children:x.map(v=>{const b=h[v.key];return b==null||b===""?null:e.jsxs("div",{className:"rounded-lg border border-border/50 p-3",children:[e.jsxs("div",{className:"mb-1 flex items-center gap-1.5 text-xs text-muted-foreground",children:[e.jsx(brn,{fieldKey:v.key}),v.label]}),e.jsx("p",{className:"text-sm font-medium",children:b_t(b,v.key)})]},v.key)})})]},g)}),o.custom&&o.custom.length>0&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2 border-b border-border/40 pb-2",children:[e.jsx("div",{className:"flex h-6 w-6 items-center justify-center rounded-md bg-primary/10",children:e.jsx(Jr,{className:"h-3.5 w-3.5 text-primary"})}),e.jsx("p",{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:"Custom questions"})]}),e.jsx("div",{className:"grid gap-3 sm:grid-cols-2",children:o.custom.map(g=>{var y;const x=(y=h.extra)==null?void 0:y[g.id];return x==null||x===""?null:e.jsxs("div",{className:"rounded-lg border border-border/50 p-3",children:[e.jsx("p",{className:"mb-1 text-xs text-muted-foreground",children:g.label}),e.jsx("p",{className:"text-sm font-medium",children:b_t(x,g.id)})]},g.id)})})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2 pt-2 text-xs text-muted-foreground",children:[e.jsx(Ta,{className:"h-3.5 w-3.5"}),"Submitted ",f,h.timezone&&e.jsxs("span",{className:"ml-2",children:["· Timezone: ",h.timezone]})]})]})})]})},h.id)})})]})},wrn=[{value:"kickoff",label:"Kickoff call"},{value:"mastermind",label:"Mastermind"},{value:"workshop",label:"Workshop / training"},{value:"office_hours",label:"Office hours / Q&A"},{value:"other",label:"Other"}],jrn=s=>{if(!s)return"";const t=new Date(s),n=t.getTimezoneOffset();return new Date(t.getTime()-n*6e4).toISOString().slice(0,16)},__t={title:"",description:"",event_kind:"mastermind",starts_at:"",duration_minutes:60,speaker:"",meeting_link:"",replay_url:"",is_published:!0},Nrn=({programId:s})=>{const{data:t=[],isLoading:n}=tWs(s),r=sWs(s),a=nWs(),[i,l]=j.useState(!1),[o,c]=j.useState({...__t}),d=()=>{c({...__t}),l(!0)},u=y=>{c({id:y.id,title:y.title,description:y.description||"",event_kind:y.event_kind,starts_at:jrn(y.starts_at),duration_minutes:y.duration_minutes,speaker:y.speaker||"",meeting_link:y.meeting_link||"",replay_url:y.replay_url||"",is_published:y.is_published}),l(!0)},h=async()=>{if(!o.title.trim())return re.error("Give the session a title");if(!o.starts_at)return re.error("Pick a date and time");await r.mutateAsync({...o,starts_at:new Date(o.starts_at).toISOString(),duration_minutes:Number(o.duration_minutes)||60}),l(!1)},m=Date.now(),f=t.filter(y=>new Date(y.starts_at).getTime()>=m),g=t.filter(y=>new Date(y.starts_at).getTime()e.jsx(Ne,{className:"border-border/60",children:e.jsxs(Ie,{className:"flex flex-wrap items-start justify-between gap-4 p-5",children:[e.jsxs("div",{className:"min-w-0 space-y-1.5",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("p",{className:"font-medium",children:y.title}),e.jsx(Be,{variant:"secondary",className:"capitalize",children:y.event_kind.replace("_"," ")}),!y.is_published&&e.jsx(Be,{variant:"outline",children:"Hidden"})]}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[sh(y.starts_at,!0)," · ",y.duration_minutes," min",y.speaker?` · ${y.speaker}`:""]}),y.description&&e.jsx("p",{className:"max-w-2xl text-sm text-muted-foreground",children:y.description}),e.jsxs("div",{className:"flex flex-wrap gap-3 pt-1 text-xs",children:[y.meeting_link?e.jsxs(e.Fragment,{children:[e.jsxs("a",{className:"inline-flex items-center gap-1 text-primary hover:underline",href:y.meeting_link,target:"_blank",rel:"noreferrer",children:[e.jsx(kr,{className:"h-3 w-3"})," Join link"]}),e.jsxs("button",{className:"inline-flex items-center gap-1 text-muted-foreground hover:text-foreground",onClick:()=>{navigator.clipboard.writeText(y.meeting_link),re.success("Join link copied")},children:[e.jsx(Ha,{className:"h-3 w-3"})," Copy"]})]}):e.jsx("span",{className:"text-muted-foreground",children:"No meeting link yet"}),y.replay_url&&e.jsxs("a",{className:"inline-flex items-center gap-1 text-primary hover:underline",href:y.replay_url,target:"_blank",rel:"noreferrer",children:[e.jsx(ua,{className:"h-3 w-3"})," Replay"]})]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx($,{variant:"outline",size:"sm",onClick:()=>u(y),children:e.jsx(gi,{className:"h-3.5 w-3.5"})}),e.jsx($,{variant:"outline",size:"sm",onClick:async()=>{await fo(`Remove "${y.title}"?`)&&a.mutate(y.id)},children:e.jsx(Wn,{className:"h-3.5 w-3.5"})})]})]})});return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex flex-wrap items-end justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:"Live sessions"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Add your Zoom (or Meet / Teams) sessions here. Enrolled members see them in the Sessions tab with the join button, RSVP reminders and an add-to-calendar link."})]}),e.jsxs($,{onClick:d,children:[e.jsx(dn,{className:"mr-1.5 h-4 w-4"})," Add session"]})]}),n?e.jsx("p",{className:"text-sm text-muted-foreground",children:"Loading sessions…"}):t.length===0?e.jsx(Ne,{className:"border-dashed",children:e.jsxs(Ie,{className:"flex flex-col items-center gap-3 p-12 text-center",children:[e.jsx(Au,{className:"h-8 w-8 text-muted-foreground"}),e.jsx("p",{className:"font-medium",children:"No live sessions scheduled"}),e.jsx("p",{className:"max-w-md text-sm text-muted-foreground",children:"Paste your recurring Zoom link once for each call — kickoff, weekly masterminds, workshops and office hours."})]})}):e.jsxs(e.Fragment,{children:[e.jsxs("section",{className:"space-y-3",children:[e.jsxs("h3",{className:"text-xs font-semibold uppercase tracking-wider text-muted-foreground",children:["Upcoming (",f.length,")"]}),f.length===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:"Nothing upcoming."}):f.map(y=>e.jsx(x,{e:y},y.id))]}),g.length>0&&e.jsxs("section",{className:"space-y-3",children:[e.jsxs("h3",{className:"text-xs font-semibold uppercase tracking-wider text-muted-foreground",children:["Past (",g.length,") — add replay links so members can catch up"]}),g.map(y=>e.jsx(x,{e:y},y.id))]})]}),e.jsx(zs,{open:i,onOpenChange:l,children:e.jsxs(Os,{className:"max-h-[85vh] max-w-2xl overflow-y-auto",children:[e.jsx(Us,{children:e.jsx(Bs,{children:o.id?"Edit session":"Add a live session"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Title"}),e.jsx(pe,{placeholder:"Week 1 Mastermind — Content that converts",value:o.title,onChange:y=>c({...o,title:y.target.value})})]}),e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Type"}),e.jsxs(ms,{value:o.event_kind,onValueChange:y=>c({...o,event_kind:y}),children:[e.jsx(us,{children:e.jsx(fs,{})}),e.jsx(hs,{children:wrn.map(y=>e.jsx(Ge,{value:y.value,children:y.label},y.value))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Host / speaker"}),e.jsx(pe,{value:o.speaker,onChange:y=>c({...o,speaker:y.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Starts (your local time)"}),e.jsx(pe,{type:"datetime-local",value:o.starts_at,onChange:y=>c({...o,starts_at:y.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Length (minutes)"}),e.jsx(pe,{type:"number",value:o.duration_minutes,onChange:y=>c({...o,duration_minutes:y.target.value})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Zoom / meeting link"}),e.jsx(pe,{placeholder:"https://us02web.zoom.us/j/1234567890?pwd=…",value:o.meeting_link,onChange:y=>c({...o,meeting_link:y.target.value})}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Members only see this after they're enrolled. A recurring Zoom link can be reused on every session."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Replay link (after the call)"}),e.jsx(pe,{placeholder:"YouTube, Vimeo, Loom or Zoom cloud recording URL",value:o.replay_url,onChange:y=>c({...o,replay_url:y.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"What we'll cover"}),e.jsx(Rs,{rows:3,value:o.description,onChange:y=>c({...o,description:y.target.value})})]}),e.jsxs("div",{className:"flex items-center justify-between rounded-lg border border-border/60 p-4",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",children:"Visible to members"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Turn off to draft a session privately."})]}),e.jsx(Sn,{checked:o.is_published,onCheckedChange:y=>c({...o,is_published:y})})]})]}),e.jsx(Ar,{children:e.jsxs($,{onClick:h,disabled:r.isPending,children:[r.isPending&&e.jsx(kt,{className:"mr-1.5 h-4 w-4 animate-spin"}),o.id?"Save session":"Add session"]})})]})})]})},w_t={title:"",summary:"",week_id:"none",duration_minutes:"",video_url:"",worksheet_url:"",action_assignment:"",status:"published",sort_order:0},krn=({programId:s})=>{const{data:t,isLoading:n}=rWs(s),r=(t==null?void 0:t.lessons)||[],a=(t==null?void 0:t.weeks)||[],{data:i=[]}=QUt(s),l=aWs(s),o=iWs(),[c,d]=j.useState(!1),[u,h]=j.useState({...w_t}),[m,f]=j.useState(!1),g=j.useRef(null),x=async C=>{if(g.current&&(g.current.value=""),!!C){if(!C.type.startsWith("video/"))return re.error("Please choose a video file");if(C.size>500*1024*1024)return re.error("Video must be under 500MB");f(!0);try{const E=C.name.split(".").pop()||"mp4",I=`lessons/${crypto.randomUUID()}.${E}`,{error:P}=await q.storage.from("program-assets").upload(I,C,{contentType:C.type,upsert:!1});if(P)throw P;const{data:R,error:D}=await q.storage.from("program-assets").createSignedUrl(I,60*60*24*365*5);if(D||!(R!=null&&R.signedUrl))throw D||new Error("Could not sign video URL");h(O=>({...O,video_url:R.signedUrl})),re.success("Video uploaded")}catch(E){re.error((E==null?void 0:E.message)||"Upload failed")}finally{f(!1)}}},y=()=>{h({...w_t,sort_order:r.length}),d(!0)},v=C=>{h({id:C.id,title:C.title,summary:C.summary||"",week_id:C.week_id||"none",duration_minutes:C.duration_minutes??"",video_url:C.video_url||"",worksheet_url:C.worksheet_url||"",action_assignment:C.action_assignment||"",status:C.status,sort_order:C.sort_order}),d(!0)},b=async()=>{if(!u.title.trim())return re.error("Give the video a title");await l.mutateAsync({...u,week_id:u.week_id==="none"?null:u.week_id,duration_minutes:u.duration_minutes===""?null:Number(u.duration_minutes),sort_order:Number(u.sort_order)||0}),d(!1)},w=C=>{const E=a.find(I=>I.id===C);return E?`Week ${E.week_number}`:"Unassigned"},S=ZUt(u.video_url);return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex flex-wrap items-end justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:"On-demand videos"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Your program's video library. Paste a YouTube, Vimeo or Loom link and it plays inline in the member workspace, grouped by week, with completion tracking."})]}),e.jsxs($,{onClick:y,children:[e.jsx(dn,{className:"mr-1.5 h-4 w-4"})," Add video"]})]}),n?e.jsx("p",{className:"text-sm text-muted-foreground",children:"Loading library…"}):r.length===0?e.jsx(Ne,{className:"border-dashed",children:e.jsxs(Ie,{className:"flex flex-col items-center gap-3 p-12 text-center",children:[e.jsx(rf,{className:"h-8 w-8 text-muted-foreground"}),e.jsx("p",{className:"font-medium",children:"No on-demand videos yet"}),e.jsx("p",{className:"max-w-md text-sm text-muted-foreground",children:"Add training videos members can watch any time — assign each one to a week to build the roadmap."})]})}):e.jsx("div",{className:"space-y-3",children:r.map(C=>e.jsx(Ne,{className:"border-border/60",children:e.jsxs(Ie,{className:"flex flex-wrap items-start justify-between gap-4 p-5",children:[e.jsxs("div",{className:"min-w-0 space-y-1.5",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("p",{className:"font-medium",children:C.title}),e.jsx(Be,{variant:"secondary",children:w(C.week_id)}),C.status!=="published"&&e.jsx(Be,{variant:"outline",className:"capitalize",children:C.status}),C.duration_minutes?e.jsxs("span",{className:"text-xs text-muted-foreground",children:[C.duration_minutes," min"]}):null]}),C.summary&&e.jsx("p",{className:"max-w-2xl text-sm text-muted-foreground",children:C.summary}),e.jsxs("div",{className:"flex flex-wrap gap-3 pt-1 text-xs",children:[C.video_url?e.jsxs("a",{className:"inline-flex items-center gap-1 text-primary hover:underline",href:C.video_url,target:"_blank",rel:"noreferrer",children:[e.jsx(kr,{className:"h-3 w-3"})," Video"]}):e.jsx("span",{className:"text-muted-foreground",children:"No video link"}),C.worksheet_url&&e.jsxs("a",{className:"inline-flex items-center gap-1 text-primary hover:underline",href:C.worksheet_url,target:"_blank",rel:"noreferrer",children:[e.jsx(kr,{className:"h-3 w-3"})," Worksheet"]})]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx($,{variant:"outline",size:"sm",onClick:()=>v(C),children:e.jsx(gi,{className:"h-3.5 w-3.5"})}),e.jsx($,{variant:"outline",size:"sm",onClick:async()=>{await fo(`Remove "${C.title}"?`)&&o.mutate(C.id)},children:e.jsx(Wn,{className:"h-3.5 w-3.5"})})]})]})},C.id))}),e.jsx(zs,{open:c,onOpenChange:d,children:e.jsxs(Os,{className:"max-h-[85vh] max-w-2xl overflow-y-auto",children:[e.jsx(Us,{children:e.jsx(Bs,{children:u.id?"Edit video":"Add an on-demand video"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Title"}),e.jsx(pe,{placeholder:"How to script a 30-second listing reel",value:u.title,onChange:C=>h({...u,title:C.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Video link"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(pe,{placeholder:"https://youtu.be/… , Vimeo or Loom URL",value:u.video_url,onChange:C=>h({...u,video_url:C.target.value})}),e.jsxs($,{type:"button",variant:"outline",className:"shrink-0",disabled:m,onClick:()=>{var C;return(C=g.current)==null?void 0:C.click()},children:[m?e.jsx(kt,{className:"mr-1.5 h-4 w-4 animate-spin"}):e.jsx(ni,{className:"mr-1.5 h-4 w-4"}),m?"Uploading…":"Upload"]}),e.jsx("input",{ref:g,type:"file",accept:"video/*",className:"hidden",onChange:C=>{var E;return x((E=C.target.files)==null?void 0:E[0])}})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Paste a YouTube / Vimeo / Loom link, or upload an MP4 (up to 500MB) hosted by LevelUp."}),u.video_url&&!S&&!Aee(u.video_url)&&e.jsx("p",{className:"text-xs text-muted-foreground",children:`We can't embed this link — members will get an "Open video" button instead.`})]}),S&&e.jsx("div",{className:"overflow-hidden rounded-lg border border-border/60",children:e.jsx("iframe",{src:S,title:"Video preview",className:"aspect-video w-full",allow:"accelerometer; autoplay; clipboard-write; encrypted-media; picture-in-picture",allowFullScreen:!0})}),!S&&Aee(u.video_url)&&e.jsx("div",{className:"overflow-hidden rounded-lg border border-border/60 bg-black",children:e.jsx("video",{src:u.video_url,controls:!0,className:"aspect-video w-full",preload:"metadata"})}),e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Week"}),e.jsxs(ms,{value:u.week_id,onValueChange:C=>h({...u,week_id:C}),children:[e.jsx(us,{children:e.jsx(fs,{})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"none",children:"Unassigned (library)"}),a.map(C=>e.jsxs(Ge,{value:C.id,children:["Week ",C.week_number," — ",C.title]},C.id))]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Length (minutes)"}),e.jsx(pe,{type:"number",value:u.duration_minutes,onChange:C=>h({...u,duration_minutes:C.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Status"}),e.jsxs(ms,{value:u.status,onValueChange:C=>h({...u,status:C}),children:[e.jsx(us,{children:e.jsx(fs,{})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"published",children:"Published (visible)"}),e.jsx(Ge,{value:"draft",children:"Draft (hidden)"}),e.jsx(Ge,{value:"archived",children:"Archived"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Order"}),e.jsx(pe,{type:"number",value:u.sort_order,onChange:C=>h({...u,sort_order:C.target.value})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Summary"}),e.jsx(Rs,{rows:3,value:u.summary,onChange:C=>h({...u,summary:C.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Worksheet / download link"}),i.length>0&&e.jsxs(ms,{value:"",onValueChange:C=>{const E=i.find(P=>P.id===C),I=E?lie(E):null;I?h({...u,worksheet_url:I}):re.error("That resource has no file or link yet")},children:[e.jsx(us,{children:e.jsx(fs,{placeholder:"Choose an uploaded program resource…"})}),e.jsx(hs,{children:i.map(C=>e.jsx(Ge,{value:C.id,children:C.title},C.id))})]}),e.jsx(pe,{placeholder:"Or paste a link",value:u.worksheet_url,onChange:C=>h({...u,worksheet_url:C.target.value})}),u.worksheet_url&&e.jsxs("a",{href:u.worksheet_url,target:"_blank",rel:"noreferrer",className:"inline-flex items-center gap-1 text-xs text-primary hover:underline",children:[e.jsx(kr,{className:"h-3 w-3"})," Preview worksheet"]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Action assignment"}),e.jsx(Rs,{rows:2,placeholder:"Post one reel using this hook before your next mastermind.",value:u.action_assignment,onChange:C=>h({...u,action_assignment:C.target.value})})]})]}),e.jsx(Ar,{children:e.jsxs($,{onClick:b,disabled:l.isPending,children:[l.isPending&&e.jsx(kt,{className:"mr-1.5 h-4 w-4 animate-spin"}),u.id?"Save video":"Add video"]})})]})})]})},j_t={title:"",description:"",category:"Resources",resource_kind:"pdf",url:"",file_path:"",status:"published",sort_order:0},Srn=({programId:s})=>{const{data:t=[],isLoading:n}=QUt(s),r=oWs(s),a=lWs(),[i,l]=j.useState(!1),[o,c]=j.useState({...j_t}),[d,u]=j.useState(!1),h=j.useRef(null),m=Array.from(new Set(t.map(v=>v.category))).filter(Boolean),f=()=>{c({...j_t,sort_order:t.length}),l(!0)},g=v=>{c({id:v.id,title:v.title,description:v.description||"",category:v.category||"Resources",resource_kind:v.resource_kind,url:v.url||"",file_path:v.file_path||"",status:v.status,sort_order:v.sort_order}),l(!0)},x=async v=>{if(!(!v||!s)){if(v.size>50*1024*1024)return re.error("File must be under 50MB");u(!0);try{const b=v.name.split(".").pop()||"pdf",w=`programs/${s}/resources/${Date.now()}-${Math.random().toString(36).slice(2,8)}.${b}`,{error:S}=await q.storage.from(xK).upload(w,v,{contentType:v.type||"application/pdf",upsert:!1});if(S)throw S;c(C=>({...C,file_path:w,url:"",title:C.title||v.name.replace(/\.[^.]+$/,""),resource_kind:v.type==="application/pdf"?"pdf":C.resource_kind})),re.success("File uploaded")}catch(b){re.error(b.message||"Upload failed")}finally{u(!1),h.current&&(h.current.value="")}}},y=async()=>{if(!o.title.trim())return re.error("Give the resource a title");if(!o.file_path&&!o.url.trim())return re.error("Upload a file or paste a link");await r.mutateAsync({...o,sort_order:Number(o.sort_order)||0}),l(!1)};return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex flex-wrap items-end justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:"Resources"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Upload PDFs, worksheets and checklists — or link to Canva/Google templates. Enrollees see them grouped by category in their program dashboard."})]}),e.jsxs($,{onClick:f,children:[e.jsx(dn,{className:"mr-1.5 h-4 w-4"})," Add resource"]})]}),n?e.jsx("p",{className:"text-sm text-muted-foreground",children:"Loading resources…"}):t.length===0?e.jsx(Ne,{className:"border-dashed",children:e.jsxs(Ie,{className:"flex flex-col items-center gap-3 p-12 text-center",children:[e.jsx(Jr,{className:"h-8 w-8 text-muted-foreground"}),e.jsx("p",{className:"font-medium",children:"No resources yet"}),e.jsx("p",{className:"max-w-md text-sm text-muted-foreground",children:"Add the swipe files, scripts and worksheets that make this program feel premium."})]})}):e.jsx("div",{className:"space-y-3",children:t.map(v=>{const b=lie(v);return e.jsx(Ne,{className:"border-border/60",children:e.jsxs(Ie,{className:"flex flex-wrap items-start justify-between gap-4 p-5",children:[e.jsxs("div",{className:"min-w-0 space-y-1.5",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("p",{className:"font-medium",children:v.title}),e.jsx(Be,{variant:"secondary",children:v.category}),e.jsx(Be,{variant:"outline",className:"capitalize",children:v.resource_kind.replace("_"," ")}),v.status!=="published"&&e.jsx(Be,{variant:"outline",className:"capitalize",children:v.status})]}),v.description&&e.jsx("p",{className:"max-w-2xl text-sm text-muted-foreground",children:v.description}),b&&e.jsxs("button",{type:"button",onClick:()=>Eee(v),className:"inline-flex items-center gap-1 text-xs text-primary hover:underline",children:[e.jsx(kr,{className:"h-3 w-3"})," Open"]})]}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx($,{variant:"ghost",size:"icon",onClick:()=>g(v),children:e.jsx(gi,{className:"h-4 w-4"})}),e.jsx($,{variant:"ghost",size:"icon",onClick:async()=>{await fo(`Remove "${v.title}"?`)&&a.mutate(v)},children:e.jsx(Wn,{className:"h-4 w-4 text-destructive"})})]})]})},v.id)})}),e.jsx(zs,{open:i,onOpenChange:l,children:e.jsxs(Os,{className:"max-w-lg",children:[e.jsx(Us,{children:e.jsx(Bs,{children:o.id?"Edit resource":"Add resource"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Title"}),e.jsx(pe,{value:o.title,onChange:v=>c({...o,title:v.target.value}),placeholder:"90-Day Content Calendar"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Description"}),e.jsx(Rs,{rows:2,value:o.description,onChange:v=>c({...o,description:v.target.value}),placeholder:"What this is and how to use it"})]}),e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Category"}),e.jsx(pe,{value:o.category,onChange:v=>c({...o,category:v.target.value}),placeholder:"Getting started",list:"program-resource-categories"}),e.jsx("datalist",{id:"program-resource-categories",children:m.map(v=>e.jsx("option",{value:v},v))})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Type"}),e.jsxs(ms,{value:o.resource_kind,onValueChange:v=>c({...o,resource_kind:v}),children:[e.jsx(us,{children:e.jsx(fs,{})}),e.jsx(hs,{children:XUt.map(v=>e.jsx(Ge,{value:v.value,children:v.label},v.value))})]})]})]}),e.jsxs("div",{className:"space-y-2 rounded-lg border p-3",children:[e.jsx(ee,{children:"File"}),e.jsx("input",{ref:h,type:"file",className:"hidden",accept:".pdf,.doc,.docx,.xls,.xlsx,.ppt,.pptx,.csv,.zip,image/*",onChange:v=>{var b;return x((b=v.target.files)==null?void 0:b[0])}}),o.file_path?e.jsxs("div",{className:"flex items-center justify-between gap-2 text-sm",children:[e.jsx("span",{className:"truncate",children:o.file_path.split("/").pop()}),e.jsx($,{variant:"ghost",size:"sm",onClick:()=>c({...o,file_path:""}),children:"Remove"})]}):e.jsxs($,{variant:"outline",size:"sm",onClick:()=>{var v;return(v=h.current)==null?void 0:v.click()},disabled:d,children:[d?e.jsx(kt,{className:"mr-1.5 h-4 w-4 animate-spin"}):e.jsx(ni,{className:"mr-1.5 h-4 w-4"}),"Upload PDF or document"]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Or paste an external link instead (Canva, Google Doc, Notion…)."}),e.jsx(pe,{value:o.url,onChange:v=>c({...o,url:v.target.value,file_path:""}),placeholder:"https://…",disabled:!!o.file_path})]}),e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Status"}),e.jsxs(ms,{value:o.status,onValueChange:v=>c({...o,status:v}),children:[e.jsx(us,{children:e.jsx(fs,{})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"published",children:"Published (visible)"}),e.jsx(Ge,{value:"draft",children:"Draft (hidden)"}),e.jsx(Ge,{value:"archived",children:"Archived"})]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Sort order"}),e.jsx(pe,{type:"number",value:o.sort_order,onChange:v=>c({...o,sort_order:v.target.value})})]})]})]}),e.jsxs(Ar,{children:[e.jsx($,{variant:"outline",onClick:()=>l(!1),children:"Cancel"}),e.jsxs($,{onClick:y,disabled:r.isPending||d,children:[r.isPending&&e.jsx(kt,{className:"mr-1.5 h-4 w-4 animate-spin"})," Save resource"]})]})]})})]})},Crn=({programId:s})=>{const{data:t=[],isLoading:n}=fWs(s),r=j.useMemo(()=>{const l=Date.now()-6048e5;return t.filter(o=>new Date(o.created_at).getTime()>=l).length},[t]),a=t.map(l=>l.email).filter(Boolean).join(", "),i=()=>{const l=`Name,Email,Phone,Brokerage,Joined `,o=t.map(u=>[u.full_name,u.email,u.phone,u.brokerage,u.created_at].map(h=>`"${(h??"").toString().replace(/"/g,'""')}"`).join(",")).join(` `),c=URL.createObjectURL(new Blob([l+o],{type:"text/csv"})),d=document.createElement("a");d.href=c,d.download="program-interest.csv",d.click(),URL.revokeObjectURL(c)};return n?e.jsx(yn,{className:"h-64 w-full rounded-xl"}):e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid gap-4 sm:grid-cols-3",children:[e.jsx(Ne,{children:e.jsxs(Ie,{className:"flex items-center gap-3 p-4",children:[e.jsx(QS,{className:"h-5 w-5 text-primary"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:t.length}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"On the notify list"})]})]})}),e.jsx(Ne,{children:e.jsxs(Ie,{className:"flex items-center gap-3 p-4",children:[e.jsx(Zn,{className:"h-5 w-5 text-primary"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:r}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Signed up in last 7 days"})]})]})}),e.jsx(Ne,{children:e.jsx(Ie,{className:"flex items-center gap-3 p-4",children:e.jsxs(Be,{variant:"secondary",children:[t.filter(l=>l.notified_at).length," notified"]})})})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs($,{variant:"outline",size:"sm",disabled:!a,onClick:()=>{navigator.clipboard.writeText(a),re.success("Emails copied")},children:[e.jsx(Ha,{className:"mr-2 h-4 w-4"})," Copy emails"]}),e.jsxs($,{variant:"outline",size:"sm",disabled:!t.length,onClick:i,children:[e.jsx(di,{className:"mr-2 h-4 w-4"})," Export CSV"]})]}),t.length===0?e.jsx("p",{className:"rounded-lg border border-dashed p-8 text-center text-sm text-muted-foreground",children:"Nobody has asked to be notified yet."}):e.jsx("div",{className:"rounded-lg border",children:e.jsxs(mi,{children:[e.jsx(fi,{children:e.jsxs(En,{children:[e.jsx(Dt,{children:"Member"}),e.jsx(Dt,{children:"Email"}),e.jsx(Dt,{children:"Phone"}),e.jsx(Dt,{children:"Brokerage"}),e.jsx(Dt,{children:"Joined"})]})}),e.jsx(pi,{children:t.map(l=>e.jsxs(En,{children:[e.jsx(wt,{className:"font-medium",children:l.full_name||"—"}),e.jsx(wt,{children:l.email||"—"}),e.jsx(wt,{children:l.phone||"—"}),e.jsx(wt,{children:l.brokerage||"—"}),e.jsx(wt,{className:"text-muted-foreground",children:sh(l.created_at)})]},l.id))})]})})]})},N_t={name:"",slug:"",subtitle:"",short_description:"",description:"",price_cents:0,capacity:50,duration_weeks:13,weekly_video_goal:3,payment_mode:"delayed",status:"draft",kickoff_at:"",charge_at:"",enrollment_close_at:"",cover_image_url:""},Arn=()=>{const s=Vt(),[t,n]=j.useState(null),[r,a]=j.useState(!1),[i,l]=j.useState({...N_t}),[o,c]=j.useState(!1),[d,u]=j.useState(!1),[h,m]=j.useState(null),{data:f=[],isLoading:g}=tt({queryKey:["admin-programs"],queryFn:async()=>{const{data:P,error:R}=await q.from("programs").select("*").order("created_at",{ascending:!1});if(R)throw R;return P||[]}}),x=f.find(P=>P.id===t)||f[0]||null,{data:y=[]}=tt({queryKey:["admin-program-enrollments",x==null?void 0:x.id],enabled:!!(x!=null&&x.id),queryFn:async()=>{const{data:P,error:R}=await q.from("program_enrollments").select("*").eq("program_id",x.id).order("created_at",{ascending:!1});if(R)throw R;const D=(P||[]).map(W=>W.user_id),{data:O}=D.length?await q.from("profiles").select("id, name, email").in("id",D):{data:[]},U=new Map((O||[]).map(W=>[W.id,W]));return(P||[]).map(W=>({...W,profile:U.get(W.user_id)}))}}),{data:v=[]}=tt({queryKey:["admin-program-intakes",x==null?void 0:x.id],enabled:!!(x!=null&&x.id),queryFn:async()=>{const{data:P,error:R}=await q.from("program_intake_responses").select("*").eq("program_id",x.id);if(R)throw R;return P||[]}}),{data:b=[]}=tt({queryKey:["admin-program-audit",x==null?void 0:x.id],enabled:!!(x!=null&&x.id),queryFn:async()=>{const{data:P,error:R}=await q.from("program_audit_logs").select("*").eq("program_id",x.id).order("created_at",{ascending:!1}).limit(100);if(R)throw R;return P||[]}}),w=async()=>{c(!0);try{const P={...i,slug:i.slug||i.name.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,""),kickoff_at:i.kickoff_at||null,charge_at:i.charge_at||null,enrollment_close_at:i.enrollment_close_at||null},{error:R}=await q.from("programs").insert(P);if(R)throw R;re.success("Program created"),a(!1),l({...N_t}),s.invalidateQueries({queryKey:["admin-programs"]})}catch(P){re.error(P.message||"Could not create the program")}finally{c(!1)}},S=async P=>{if(!x)return;const{error:R}=await q.from("programs").update(P).eq("id",x.id);if(R)return re.error(R.message);s.invalidateQueries({queryKey:["admin-programs"]})},C=async(P,R)=>{const{error:D}=await q.from("program_enrollments").update(R).eq("id",P);if(D)return re.error(D.message);re.success("Enrollment updated"),s.invalidateQueries({queryKey:["admin-program-enrollments"]})},E=async P=>{u(!0);const{data:R,error:D}=await q.functions.invoke("program-charge-due",{body:P?{enrollment_id:P}:{}});if(u(!1),D||R!=null&&R.error)return re.error((R==null?void 0:R.error)||(D==null?void 0:D.message));re.success(`Processed ${(R==null?void 0:R.processed)??0} charge(s)`),s.invalidateQueries({queryKey:["admin-program-enrollments"]})},I=P=>P==="paid"||P==="completed"?"default":P==="payment_failed"?"destructive":"secondary";return e.jsx(Vs,{children:e.jsxs("div",{className:"mx-auto w-full max-w-7xl space-y-6 p-4 md:p-8",children:[e.jsxs("header",{className:"flex flex-wrap items-end justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold tracking-tight",children:"Programs"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Manage cohorts, enrollments, delayed billing and program content."})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs($,{variant:"outline",onClick:()=>E(),disabled:d,children:[d?e.jsx(kt,{className:"mr-1.5 h-4 w-4 animate-spin"}):e.jsx(Cv,{className:"mr-1.5 h-4 w-4"}),"Run due charges"]}),e.jsxs(zs,{open:r,onOpenChange:a,children:[e.jsx(jl,{asChild:!0,children:e.jsxs($,{children:[e.jsx(dn,{className:"mr-1.5 h-4 w-4"})," New program"]})}),e.jsxs(Os,{className:"max-h-[85vh] overflow-y-auto",children:[e.jsx(Us,{children:e.jsx(Bs,{children:"Create a program"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Name"}),e.jsx(pe,{value:i.name,onChange:P=>l({...i,name:P.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Slug (URL)"}),e.jsx(pe,{placeholder:"reel-estate-90",value:i.slug,onChange:P=>l({...i,slug:P.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Subtitle"}),e.jsx(pe,{value:i.subtitle,onChange:P=>l({...i,subtitle:P.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Description"}),e.jsx(Rs,{rows:4,value:i.description,onChange:P=>l({...i,description:P.target.value})})]}),e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"One-time price (USD)"}),e.jsx(pe,{type:"number",value:i.price_cents/100,onChange:P=>l({...i,price_cents:Math.round(Number(P.target.value)*100)})}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Charged one time for the full program — never recurring."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Seats"}),e.jsx(pe,{type:"number",value:i.capacity,onChange:P=>l({...i,capacity:Number(P.target.value)})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Weeks"}),e.jsx(pe,{type:"number",value:i.duration_weeks,onChange:P=>l({...i,duration_weeks:Number(P.target.value)})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Videos per week"}),e.jsx(pe,{type:"number",value:i.weekly_video_goal,onChange:P=>l({...i,weekly_video_goal:Number(P.target.value)})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Billing"}),e.jsxs(ms,{value:i.payment_mode,onValueChange:P=>l({...i,payment_mode:P}),children:[e.jsx(us,{children:e.jsx(fs,{})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"delayed",children:"Save card, charge later"}),e.jsx(Ge,{value:"immediate",children:"Charge at checkout"}),e.jsx(Ge,{value:"free",children:"Free / included"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Kickoff"}),e.jsx(pe,{type:"datetime-local",value:i.kickoff_at,onChange:P=>l({...i,kickoff_at:P.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Charge date"}),e.jsx(pe,{type:"datetime-local",value:i.charge_at,onChange:P=>l({...i,charge_at:P.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Enrollment closes"}),e.jsx(pe,{type:"datetime-local",value:i.enrollment_close_at,onChange:P=>l({...i,enrollment_close_at:P.target.value})})]})]})]}),e.jsx(Ar,{children:e.jsxs($,{onClick:w,disabled:o||!i.name,children:[o&&e.jsx(kt,{className:"mr-1.5 h-4 w-4 animate-spin"})," Create"]})})]})]})]})]}),g?e.jsx(yn,{className:"h-40 w-full rounded-xl"}):f.length===0?e.jsx(Ne,{className:"border-dashed",children:e.jsx(Ie,{className:"p-12 text-center text-sm text-muted-foreground",children:"No programs yet. Create your first cohort to get started."})}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"flex flex-wrap gap-2",children:f.map(P=>e.jsxs($,{variant:(x==null?void 0:x.id)===P.id?"default":"outline",size:"sm",onClick:()=>n(P.id),children:[P.name,e.jsx(Be,{variant:"secondary",className:"ml-2 capitalize",children:P.status})]},P.id))}),x&&e.jsxs(ha,{defaultValue:"overview",children:[e.jsxs(ma,{className:"flex w-full flex-wrap justify-start",children:[e.jsx(Zt,{value:"overview",children:"Overview"}),e.jsx(Zt,{value:"details",children:"Details & pricing"}),e.jsx(Zt,{value:"sessions",children:"Live sessions"}),e.jsx(Zt,{value:"videos",children:"On-demand videos"}),e.jsx(Zt,{value:"resources",children:"Resources"}),e.jsx(Zt,{value:"intake-form",children:"Intake form"}),e.jsx(Zt,{value:"discounts",children:"Discount codes"}),e.jsx(Zt,{value:"experience",children:"Enrollee experience"}),e.jsx(Zt,{value:"interest",children:"Interest list"}),e.jsxs(Zt,{value:"enrollments",children:["Enrollments (",y.length,")"]}),e.jsxs(Zt,{value:"intake",children:["Intake (",v.length,")"]}),e.jsx(Zt,{value:"audit",children:"Audit"})]}),e.jsxs(Xt,{value:"overview",className:"mt-6 space-y-4",children:[e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2 lg:grid-cols-4",children:[e.jsx(Ne,{children:e.jsxs(Ie,{className:"p-5",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Seats filled"}),e.jsxs("p",{className:"mt-1 text-2xl font-bold",children:[y.filter(P=>["reserved","scheduled_for_charge","paid","completed"].includes(P.status)).length,e.jsxs("span",{className:"text-base font-normal text-muted-foreground",children:[" / ",x.capacity]})]})]})}),e.jsx(Ne,{children:e.jsxs(Ie,{className:"p-5",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Paid"}),e.jsx("p",{className:"mt-1 text-2xl font-bold",children:y.filter(P=>P.status==="paid").length})]})}),e.jsx(Ne,{children:e.jsxs(Ie,{className:"p-5",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Failed payments"}),e.jsx("p",{className:"mt-1 text-2xl font-bold",children:y.filter(P=>P.status==="payment_failed").length})]})}),e.jsx(Ne,{children:e.jsxs(Ie,{className:"p-5",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Projected revenue (one-time)"}),e.jsx("p",{className:"mt-1 text-2xl font-bold",children:Cg(y.filter(P=>["scheduled_for_charge","paid","completed"].includes(P.status)).reduce((P,R)=>P+(R.amount_cents||0),0),x.currency)})]})})]}),e.jsx(Ne,{children:e.jsxs(Ie,{className:"space-y-5 p-6",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:"Publish this program"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Published programs appear on the member Programs page."})]}),e.jsx(Sn,{checked:x.status==="published",onCheckedChange:P=>S({status:P?"published":"draft"})})]}),e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-4 border-t border-border/60 pt-5",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:"Feature it"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Pins the program to the top."})]}),e.jsx(Sn,{checked:x.is_featured,onCheckedChange:P=>S({is_featured:P})})]}),e.jsxs("div",{className:"grid gap-4 border-t border-border/60 pt-5 sm:grid-cols-3 text-sm",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-muted-foreground",children:"One-time price"}),e.jsx("p",{className:"font-medium",children:Cg(x.price_cents,x.currency)})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-muted-foreground",children:"Kickoff"}),e.jsx("p",{className:"font-medium",children:sh(x.kickoff_at)||"Not set"})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-muted-foreground",children:"Charge date"}),e.jsx("p",{className:"font-medium",children:sh(x.charge_at)||"Not set"})]})]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Edit pricing, seats, description, dates and images in the"," ",e.jsx("strong",{children:"Details"})," tab."]})]})})]}),e.jsx(Xt,{value:"details",className:"mt-6",children:e.jsx(drn,{program:x,onSaved:()=>s.invalidateQueries({queryKey:["admin-programs"]})})}),e.jsx(Xt,{value:"sessions",className:"mt-6",children:e.jsx(Nrn,{programId:x.id})}),e.jsx(Xt,{value:"videos",className:"mt-6",children:e.jsx(krn,{programId:x.id})}),e.jsx(Xt,{value:"resources",className:"mt-6",children:e.jsx(Srn,{programId:x.id})}),e.jsx(Xt,{value:"discounts",className:"mt-6",children:e.jsx(mrn,{program:x})}),e.jsx(Xt,{value:"intake-form",className:"mt-6",children:e.jsx(xrn,{program:x,onSaved:()=>s.invalidateQueries({queryKey:["admin-programs"]})})}),e.jsx(Xt,{value:"experience",className:"mt-6",children:e.jsx(frn,{program:x})}),e.jsx(Xt,{value:"interest",className:"mt-6",children:e.jsx(Crn,{programId:x.id})}),e.jsx(Xt,{value:"enrollments",className:"mt-6",children:e.jsx(Ne,{children:e.jsx(Ie,{className:"overflow-x-auto p-0",children:e.jsxs(mi,{children:[e.jsx(fi,{children:e.jsxs(En,{children:[e.jsx(Dt,{children:"Member"}),e.jsx(Dt,{children:"Status"}),e.jsx(Dt,{children:"Charge date"}),e.jsx(Dt,{children:"Amount"}),e.jsx(Dt,{children:"Access"}),e.jsx(Dt,{className:"text-right",children:"Actions"})]})}),e.jsxs(pi,{children:[y.length===0&&e.jsx(En,{children:e.jsxs(wt,{colSpan:6,className:"py-10 text-center text-sm text-muted-foreground",children:[e.jsx(Zn,{className:"mx-auto mb-2 h-5 w-5"}),"No enrollments yet"]})}),y.map(P=>{var R,D;return e.jsxs(En,{children:[e.jsx(wt,{children:e.jsxs("button",{type:"button",className:"text-left hover:underline",onClick:()=>m(P),children:[e.jsx("p",{className:"font-medium",children:((R=P.profile)==null?void 0:R.name)||"Unknown"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:(D=P.profile)==null?void 0:D.email})]})}),e.jsxs(wt,{children:[e.jsx(Be,{variant:I(P.status),className:"capitalize",children:String(P.status).replace(/_/g," ")}),P.last_payment_error&&e.jsx("p",{className:"mt-1 max-w-[200px] truncate text-xs text-destructive",children:P.last_payment_error})]}),e.jsx(wt,{className:"text-sm",children:sh(P.charge_scheduled_at)||"—"}),e.jsx(wt,{className:"text-sm",children:Cg(P.amount_cents,P.currency)}),e.jsx(wt,{children:e.jsx(Sn,{checked:P.access_override,onCheckedChange:O=>C(P.id,{access_override:O})})}),e.jsxs(wt,{className:"space-x-2 text-right",children:[["scheduled_for_charge","payment_failed"].includes(P.status)&&e.jsxs($,{size:"sm",variant:"outline",onClick:()=>E(P.id),disabled:d,children:[e.jsx(ro,{className:"mr-1.5 h-3.5 w-3.5"})," Charge now"]}),!["canceled","refunded"].includes(P.status)&&e.jsx($,{size:"sm",variant:"ghost",onClick:()=>C(P.id,{status:"canceled",canceled_at:new Date().toISOString()}),children:"Cancel"})]})]},P.id)})]})]})})})}),e.jsx(Xt,{value:"intake",className:"mt-6",children:e.jsx(_rn,{program:x})}),e.jsx(Xt,{value:"audit",className:"mt-6",children:e.jsx(Ne,{children:e.jsxs(Ie,{className:"space-y-2 p-5 text-sm",children:[b.length===0&&e.jsx("p",{className:"text-muted-foreground",children:"No activity yet."}),b.map(P=>e.jsxs("div",{className:"flex flex-wrap items-center gap-2 border-b border-border/40 py-2 last:border-0",children:[e.jsx(Be,{variant:"outline",className:"capitalize",children:String(P.action).replace(/_/g," ")}),e.jsx("span",{className:"text-muted-foreground",children:P.actor_label||"system"}),e.jsx("span",{className:"ml-auto text-xs text-muted-foreground",children:sh(P.created_at,!0)})]},P.id))]})})})]}),x&&e.jsx(hrn,{program:x,enrollment:h,open:!!h,onOpenChange:P=>!P&&m(null),onUpdated:()=>s.invalidateQueries({queryKey:["admin-program-enrollments"]})})]})]})})},Ern=()=>{const{user:s}=vs(),[t,n]=j.useState(""),[r,a]=j.useState("all"),{data:i=[]}=tt({queryKey:["academy-categories"],queryFn:async()=>{const{data:m,error:f}=await q.from("academy_categories").select("*").order("sort_order",{ascending:!0});if(f)throw f;return m}}),{data:l=[],isLoading:o}=tt({queryKey:["academy-videos"],queryFn:async()=>{const{data:m,error:f}=await q.from("academy_videos").select(` *, category:academy_categories(id, name) `).eq("is_published",!0).order("publish_date",{ascending:!1});if(f)throw f;const{data:g,error:x}=await q.from("academy_resources").select("*").order("sort_order");if(x)throw x;return m.map(v=>({...v,resources:(g==null?void 0:g.filter(b=>b.video_id===v.id))||[]}))}}),{data:c=[]}=tt({queryKey:["academy-video-likes"],queryFn:async()=>{const{data:m,error:f}=await q.from("academy_video_likes").select("video_id, user_id");if(f)throw f;return m}}),d=l.filter(m=>{var x;const f=t===""||m.title.toLowerCase().includes(t.toLowerCase())||((x=m.description)==null?void 0:x.toLowerCase().includes(t.toLowerCase())),g=r==="all"||m.category_id===r;return f&&g}),u=m=>c.filter(f=>f.video_id===m).length,h=m=>c.some(f=>f.video_id===m&&f.user_id===(s==null?void 0:s.id));return e.jsx(Vs,{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(Kr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(pe,{placeholder:"Search videos...",value:t,onChange:m=>n(m.target.value),className:"pl-10"})]})}),e.jsx(ha,{value:r,onValueChange:a,children:e.jsxs(ma,{className:"w-full justify-start flex-wrap h-auto gap-2 bg-transparent p-0",children:[e.jsx(Zt,{value:"all",className:"data-[state=active]:bg-primary data-[state=active]:text-primary-foreground",children:"All Videos"}),i.map(m=>e.jsx(Zt,{value:m.id,className:"data-[state=active]:bg-primary data-[state=active]:text-primary-foreground",children:m.name},m.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(Ne,{children:e.jsxs(Ie,{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(ua,{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(m=>e.jsx(wr,{to:`/academy/${m.id}`,children:e.jsxs(Ne,{className:"overflow-hidden cursor-pointer hover:shadow-lg transition-shadow group h-full",children:[e.jsxs("div",{className:"relative aspect-video bg-muted",children:[m.thumbnail_url?e.jsx("img",{src:m.thumbnail_url,alt:m.title,className:"w-full h-full object-cover"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center",children:e.jsx(ua,{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(Bu,{className:"h-8 w-8 text-primary-foreground ml-1"})})}),m.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(da,{className:"h-3 w-3"}),m.duration]})]}),e.jsxs(Ct,{className:"pb-2",children:[e.jsx("div",{className:"flex items-start justify-between gap-2",children:e.jsx(At,{className:"text-lg line-clamp-2",children:m.title})}),m.category&&e.jsx(Be,{variant:"secondary",className:"w-fit",children:m.category.name})]}),e.jsxs(Ie,{className:"pt-0",children:[m.description&&e.jsx(Gn,{className:"line-clamp-2",children:m.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(Vy,{className:`h-4 w-4 ${h(m.id)?"fill-primary text-primary":""}`}),u(m.id)]}),m.resources&&m.resources.length>0&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Jr,{className:"h-4 w-4"}),m.resources.length]})]})]})]})},m.id))})]})})};function BHt({resourceType:s,resourceId:t}){const{data:n=[]}=tt({queryKey:["linked-templates",s,t],queryFn:async()=>{if(s==="academy_video"){const{data:r,error:a}=await q.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(r||[]).map(i=>i.canva_templates).filter(Boolean)}else{const{data:r,error:a}=await q.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(r||[]).map(i=>i.canva_templates).filter(Boolean)}},enabled:!!t});return n.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(Yc,{className:"h-4 w-4"}),"Related Templates"]}),e.jsx("div",{className:"flex flex-wrap gap-2",children:n.map(r=>e.jsx(wr,{to:`/templates/${r.id}`,children:e.jsxs(Be,{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(Yc,{className:"h-3 w-3"}),r.name]})},r.id))})]})}const Trn=(s,t)=>{if(t==="bunny_stream"){let n=s.replace("iframe.mediadelivery.net","player.mediadelivery.net");return n.includes("?")||(n+="?autoplay=false&loop=false&muted=false&preload=true&responsive=true"),n}if(t==="youtube"){const n=/(?:youtube\.com\/(?:watch\?v=|embed\/)|youtu\.be\/)([a-zA-Z0-9_-]{11})/,r=s.match(n);if(r)return`https://www.youtube.com/embed/${r[1]}`}if(t==="vimeo"){const n=/vimeo\.com\/(?:video\/)?(\d+)/,r=s.match(n);if(r)return`https://player.vimeo.com/video/${r[1]}`}if(t==="loom"){const n=/loom\.com\/share\/([a-zA-Z0-9]+)/,r=s.match(n);if(r)return`https://www.loom.com/embed/${r[1]}`}return s},Mrn=()=>{const{videoId:s}=Wi();Qn();const{user:t,isAdmin:n}=vs(),{toast:r}=Bi(),a=Vt(),{trackEngagement:i}=gK(),[l,o]=j.useState(""),{data:c,isLoading:d}=tt({queryKey:["academy-video",s],queryFn:async()=>{const{data:w,error:S}=await q.from("academy_videos").select(` *, category:academy_categories(id, name) `).eq("id",s).eq("is_published",!0).single();if(S)throw S;const{data:C}=await q.from("academy_resources").select("*").eq("video_id",s).order("sort_order");return{...w,resources:C||[]}},enabled:!!s});j.useEffect(()=>{c&&i("academy_video",c.id,c.title,"view")},[c==null?void 0:c.id]);const{data:u=[]}=tt({queryKey:["academy-video-likes",s],queryFn:async()=>{const{data:w,error:S}=await q.from("academy_video_likes").select("*").eq("video_id",s);if(S)throw S;return w},enabled:!!s}),{data:h=[]}=tt({queryKey:["academy-video-comments",s],queryFn:async()=>{const{data:w,error:S}=await q.from("academy_video_comments").select("*").eq("video_id",s).order("created_at",{ascending:!1});if(S)throw S;const C=[...new Set(w.map(P=>P.user_id))],{data:E}=await q.from("profiles").select("id, name").in("id",C),I=new Map((E==null?void 0:E.map(P=>[P.id,P.name]))||[]);return w.map(P=>({...P,user_name:I.get(P.user_id)||"Unknown User"}))},enabled:!!s}),m=ft({mutationFn:async w=>{const{error:S}=await q.from("academy_video_comments").insert({video_id:s,user_id:t.id,content:w});if(S)throw S},onSuccess:()=>{a.invalidateQueries({queryKey:["academy-video-comments",s]}),o(""),r({title:"Comment added!"})},onError:w=>{r({title:"Error adding comment",description:w.message,variant:"destructive"})}}),f=ft({mutationFn:async w=>{const{error:S}=await q.from("academy_video_comments").delete().eq("id",w);if(S)throw S},onSuccess:()=>{a.invalidateQueries({queryKey:["academy-video-comments",s]}),r({title:"Comment deleted"})}}),g=ft({mutationFn:async()=>{const w=u.find(S=>S.user_id===(t==null?void 0:t.id));if(w){const{error:S}=await q.from("academy_video_likes").delete().eq("id",w.id);if(S)throw S}else{const{error:S}=await q.from("academy_video_likes").insert({video_id:s,user_id:t.id});if(S)throw S}},onSuccess:()=>{a.invalidateQueries({queryKey:["academy-video-likes",s]})}}),x=u.some(w=>w.user_id===(t==null?void 0:t.id)),y=w=>{switch(w==null?void 0:w.toLowerCase()){case"pdf":return"📄";case"pptx":case"ppt":return"📊";case"xlsx":case"xls":return"📈";case"docx":case"doc":return"📝";case"zip":return"📦";default:return"📁"}},v=w=>w.split(" ").map(S=>S[0]).join("").toUpperCase().slice(0,2),b=w=>{w.preventDefault(),!(!l.trim()||!t)&&m.mutate(l.trim())};return d?e.jsx(Vs,{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(Vs,{title:c.title,children:e.jsxs("div",{className:"space-y-6 max-w-5xl mx-auto",children:[e.jsx($,{variant:"ghost",size:"sm",asChild:!0,className:"gap-2",children:e.jsxs(wr,{to:"/academy",children:[e.jsx(qa,{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:Trn(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(ua,{className:"h-16 w-16 opacity-50"}),e.jsx($,{variant:"secondary",asChild:!0,children:e.jsxs("a",{href:c.video_url,target:"_blank",rel:"noopener noreferrer",className:"gap-2",children:[e.jsx(kr,{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(Be,{variant:"secondary",children:c.category.name})]}),e.jsxs("div",{className:"flex gap-2",children:[n&&e.jsx($,{variant:"outline",className:"gap-2 rounded-full",asChild:!0,children:e.jsxs(wr,{to:`/admin/academy?edit=${c.id}`,children:[e.jsx(gi,{className:"h-4 w-4"}),e.jsx("span",{children:"Edit"})]})}),e.jsx(vK,{resourceType:"academy_video",resourceId:c.id,resourceTitle:c.title}),e.jsxs($,{variant:x?"default":"outline",className:"gap-2 w-fit",onClick:()=>g.mutate(),disabled:!t||g.isPending,children:[e.jsx(Vy,{className:`h-4 w-4 ${x?"fill-current":""}`}),u.length," ",u.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(Ne,{children:e.jsxs(Ie,{className:"pt-6",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 mb-4",children:[e.jsx(Jr,{className:"h-4 w-4"}),"Resources"]}),e.jsx("div",{className:"grid gap-2",children:c.resources.map(w=>e.jsxs("a",{href:w.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:y(w.file_type)}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-medium truncate",children:w.title}),e.jsx("p",{className:"text-xs text-muted-foreground uppercase",children:w.file_type})]}),e.jsx(di,{className:"h-4 w-4 text-muted-foreground"})]},w.id))})]})}),e.jsx(BHt,{resourceType:"academy_video",resourceId:c.id}),e.jsx(Gc,{}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 text-lg",children:[e.jsx(Th,{className:"h-5 w-5"}),"Comments (",h.length,")"]}),t?e.jsxs("form",{onSubmit:b,className:"flex gap-2",children:[e.jsx(Rs,{placeholder:"Add a comment...",value:l,onChange:w=>o(w.target.value),className:"min-h-[80px] resize-none flex-1"}),e.jsx($,{type:"submit",size:"icon",className:"h-10 w-10",disabled:!l.trim()||m.isPending,children:e.jsx(Yr,{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(Ne,{children:e.jsx(Ie,{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(w=>e.jsx(Ne,{children:e.jsx(Ie,{className:"pt-4 pb-4",children:e.jsxs("div",{className:"flex gap-3",children:[e.jsx(Oa,{className:"h-10 w-10 flex-shrink-0",children:e.jsx(za,{className:"text-sm",children:v(w.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:w.user_name}),e.jsx("span",{className:"text-sm text-muted-foreground",children:mu(new Date(w.created_at),{addSuffix:!0})}),w.user_id===(t==null?void 0:t.id)&&e.jsx($,{variant:"ghost",size:"icon",className:"h-6 w-6 ml-auto",onClick:()=>f.mutate(w.id),children:e.jsx(Wn,{className:"h-3 w-3 text-muted-foreground"})})]}),e.jsx("p",{className:"text-sm whitespace-pre-wrap",children:w.content})]})]})})},w.id))})]})]})}):e.jsx(Vs,{title:"Academy",children:e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(ua,{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($,{asChild:!0,className:"mt-4",children:e.jsx(wr,{to:"/academy",children:"Back to Academy"})})]})})},M$="https://dashboard.relevelup.com",Prn=(s,t)=>{if(t==="bunny_stream"){let n=s.replace("iframe.mediadelivery.net","player.mediadelivery.net");return n.includes("?")||(n+="?autoplay=false&loop=false&muted=false&preload=true&responsive=true"),n}if(t==="youtube"){const n=s.match(/(?:youtube\.com\/(?:watch\?v=|embed\/)|youtu\.be\/)([a-zA-Z0-9_-]{11})/);if(n)return`https://www.youtube.com/embed/${n[1]}`}if(t==="vimeo"){const n=s.match(/vimeo\.com\/(?:video\/)?(\d+)/);if(n)return`https://player.vimeo.com/video/${n[1]}`}if(t==="loom"){const n=s.match(/loom\.com\/share\/([a-zA-Z0-9]+)/);if(n)return`https://www.loom.com/embed/${n[1]}`}return s},Irn=[{icon:tf,title:"100+ Training Videos",desc:"On-demand LevelUp Academy content covering lead gen, listings, buyer conversion, marketing, and more."},{icon:eg,title:"Marketing Studio & Tools",desc:"AI-powered marketing tools, listing videos, landing pages, and social content — done for you."},{icon:Zn,title:"Coaching & Community",desc:"Live coaching sessions, private community, and a network of top-performing agents."},{icon:Kl,title:"Business Scorecard",desc:"Track your deals, GCI, and pipeline in one dashboard built for real estate."}];function Lrn(){var i;const{slug:s}=Wi(),{data:t,isLoading:n,error:r}=tt({queryKey:["public-academy-video",s],queryFn:async()=>{if(!s)return null;const{data:l,error:o}=await q.from("academy_videos").select("id, title, description, video_url, video_type, thumbnail_url, duration, category:academy_categories(name)").eq("public_slug",s).eq("is_public",!0).maybeSingle();if(o)throw o;return l},enabled:!!s});j.useEffect(()=>{if(t&&s){q.rpc("increment_academy_public_view",{_slug:s}),document.title=`${t.title} | LevelUp Academy`;const l=(t.description||"").replace(/<[^>]+>/g,"").slice(0,155),o=document.querySelector('meta[name="description"]');o&&o.setAttribute("content",l||"Free training preview from LevelUp Academy.");const c=`https://relzejiswnotikjgvjhz.supabase.co/functions/v1/academy-og?slug=${encodeURIComponent(s)}&mode=image`;let d=document.querySelector('meta[property="og:image"]');d||(d=document.createElement("meta"),d.setAttribute("property","og:image"),document.head.appendChild(d)),d.setAttribute("content",c)}},[t,s]);const a=j.useMemo(()=>t?Prn(t.video_url,t.video_type):"",[t]);return n?e.jsx("div",{className:"min-h-screen bg-[#0d1b26] flex items-center justify-center",children:e.jsx("div",{className:"h-10 w-10 animate-spin rounded-full border-4 border-[#5a9ea1] border-t-transparent"})}):r||!t?e.jsxs("div",{className:"min-h-screen bg-[#0d1b26] flex flex-col items-center justify-center text-center px-6",children:[e.jsx("div",{className:"text-[#e8ecf1] text-2xl font-semibold mb-2",children:"This preview isn't available"}),e.jsx("p",{className:"text-[#8ba1b3] mb-6",children:"The link may have expired or is no longer public."}),e.jsx("a",{href:M$,children:e.jsx($,{className:"bg-[#406E71] hover:bg-[#4d8285] text-white",children:"Go to LevelUp"})})]}):e.jsxs("div",{className:"min-h-screen bg-[#0a1520] text-[#e8ecf1] overflow-x-hidden",children:[e.jsxs("div",{className:"pointer-events-none fixed inset-0 z-0",children:[e.jsx("div",{className:"absolute -top-40 -left-40 w-[600px] h-[600px] rounded-full bg-[#406E71]/20 blur-3xl"}),e.jsx("div",{className:"absolute top-1/2 -right-40 w-[500px] h-[500px] rounded-full bg-[#2a4c64]/30 blur-3xl"}),e.jsx("div",{className:"absolute bottom-0 left-1/3 w-[400px] h-[400px] rounded-full bg-[#406E71]/10 blur-3xl"})]}),e.jsx("header",{className:"relative z-10 border-b border-white/5 backdrop-blur-sm bg-[#0a1520]/70",children:e.jsxs("div",{className:"max-w-7xl mx-auto px-6 py-5 flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"w-9 h-9 rounded-lg bg-gradient-to-br from-[#406E71] to-[#2a4c64] flex items-center justify-center",children:e.jsx(Nn,{className:"w-5 h-5 text-white"})}),e.jsxs("div",{children:[e.jsx("div",{className:"font-bold text-lg tracking-tight",children:"LevelUp"}),e.jsx("div",{className:"text-[10px] uppercase tracking-widest text-[#5a9ea1] -mt-1",children:"Academy"})]})]}),e.jsx("a",{href:M$,children:e.jsx($,{variant:"ghost",className:"text-[#e8ecf1] hover:bg-white/5 hover:text-white",children:"Sign In"})})]})}),e.jsxs("section",{className:"relative z-10 max-w-6xl mx-auto px-6 pt-12 pb-16",children:[e.jsxs("div",{className:"text-center mb-8 space-y-4",children:[e.jsxs(Be,{className:"bg-[#406E71]/20 text-[#7ec0c3] border-[#406E71]/40 hover:bg-[#406E71]/30",children:[e.jsx(tf,{className:"w-3 h-3 mr-1.5"}),"Free Training Preview"]}),((i=t.category)==null?void 0:i.name)&&e.jsx("div",{className:"text-xs uppercase tracking-[0.2em] text-[#5a9ea1]",children:t.category.name}),e.jsx("h1",{className:"text-3xl md:text-5xl lg:text-6xl font-bold tracking-tight leading-[1.1] max-w-4xl mx-auto",children:t.title}),t.duration&&e.jsx("div",{className:"text-[#8ba1b3] text-sm",children:t.duration})]}),e.jsxs("div",{className:"relative rounded-2xl overflow-hidden shadow-2xl ring-1 ring-white/10 bg-black",children:[e.jsx("div",{className:"absolute -inset-px rounded-2xl bg-gradient-to-r from-[#406E71]/50 via-transparent to-[#2a4c64]/50 blur-xl -z-10"}),e.jsx("div",{className:"aspect-video",children:e.jsx("iframe",{src:a,title:t.title,className:"w-full h-full",allow:"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture",allowFullScreen:!0})})]}),t.description&&e.jsx("div",{className:"mt-10 max-w-3xl mx-auto text-[#c5d3de] text-lg leading-relaxed prose prose-invert prose-headings:text-white prose-a:text-[#7ec0c3]",dangerouslySetInnerHTML:{__html:t.description}})]}),e.jsx("section",{className:"relative z-10 max-w-4xl mx-auto px-6 pb-16",children:e.jsxs("div",{className:"relative rounded-3xl overflow-hidden p-10 md:p-14 text-center bg-gradient-to-br from-[#2a4c64] via-[#1d3a4f] to-[#0d1b26] ring-1 ring-white/10",children:[e.jsx("div",{className:"absolute top-0 right-0 w-64 h-64 bg-[#406E71]/30 rounded-full blur-3xl"}),e.jsxs("div",{className:"relative",children:[e.jsx(qg,{className:"w-10 h-10 mx-auto mb-4 text-[#7ec0c3]"}),e.jsxs("h2",{className:"text-3xl md:text-4xl font-bold mb-3",children:["This is just ",e.jsx("span",{className:"text-[#7ec0c3]",children:"one"})," of hundreds."]}),e.jsx("p",{className:"text-[#c5d3de] text-lg mb-8 max-w-2xl mx-auto",children:"LevelUp members get unlimited access to the full Academy, AI marketing tools, coaching, and everything you need to grow your real estate business."}),e.jsxs("div",{className:"flex flex-col sm:flex-row items-center justify-center gap-3",children:[e.jsx("a",{href:M$,className:"w-full sm:w-auto",children:e.jsxs($,{size:"lg",className:"w-full sm:w-auto bg-[#f5f0e0] hover:bg-white text-[#0d1b26] font-semibold text-base h-12 px-8 shadow-xl",children:["Start Free Trial",e.jsx(ei,{className:"w-4 h-4 ml-2"})]})}),e.jsx("a",{href:M$,className:"w-full sm:w-auto",children:e.jsx($,{size:"lg",variant:"outline",className:"w-full sm:w-auto bg-transparent border-white/20 text-white hover:bg-white/10 hover:text-white h-12 px-8",children:"Join LevelUp"})})]}),e.jsx("p",{className:"text-xs text-[#7a8a99] mt-5",children:"No credit card required to preview the platform"})]})]})}),e.jsxs("section",{className:"relative z-10 max-w-6xl mx-auto px-6 pb-20",children:[e.jsxs("div",{className:"text-center mb-10",children:[e.jsx("div",{className:"text-xs uppercase tracking-[0.25em] text-[#5a9ea1] mb-2",children:"What's inside"}),e.jsx("h3",{className:"text-2xl md:text-3xl font-bold",children:"Built for agents who want more"})]}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:Irn.map(l=>e.jsx("div",{className:"group relative rounded-2xl p-6 bg-white/[0.03] hover:bg-white/[0.06] ring-1 ring-white/5 hover:ring-[#406E71]/40 transition-all",children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx("div",{className:"shrink-0 w-11 h-11 rounded-xl bg-gradient-to-br from-[#406E71] to-[#2a4c64] flex items-center justify-center",children:e.jsx(l.icon,{className:"w-5 h-5 text-white"})}),e.jsxs("div",{children:[e.jsx("div",{className:"font-semibold text-white mb-1",children:l.title}),e.jsx("div",{className:"text-[#8ba1b3] text-sm leading-relaxed",children:l.desc})]})]})},l.title))})]}),e.jsx("section",{className:"relative z-10 max-w-4xl mx-auto px-6 pb-24",children:e.jsxs("div",{className:"rounded-2xl border border-white/10 p-8 md:p-10 bg-[#0d1b26]/60 backdrop-blur",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-center gap-x-8 gap-y-3 text-sm text-[#c5d3de] mb-6",children:[e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(qr,{className:"w-4 h-4 text-[#7ec0c3]"})," Trusted by top producers"]}),e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(qr,{className:"w-4 h-4 text-[#7ec0c3]"})," New training weekly"]}),e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(qr,{className:"w-4 h-4 text-[#7ec0c3]"})," Cancel anytime"]})]}),e.jsx("div",{className:"text-center",children:e.jsx("a",{href:M$,children:e.jsxs($,{size:"lg",className:"bg-[#406E71] hover:bg-[#4d8285] text-white h-12 px-10 shadow-lg",children:["Get Started at LevelUp",e.jsx(ei,{className:"w-4 h-4 ml-2"})]})})})]})}),e.jsxs("footer",{className:"relative z-10 border-t border-white/5 py-6 text-center text-xs text-[#5a6a7a]",children:["© ",new Date().getFullYear()," LevelUp · ",e.jsx("a",{href:M$,className:"hover:text-[#7ec0c3]",children:"dashboard.relevelup.com"})]})]})}function Rrn(){const s=Qn(),[t,n]=j.useState(""),{data:r,isLoading:a}=tt({queryKey:["resource-kits-published"],queryFn:async()=>{const{data:f,error:g}=await q.from("resource_kits").select("*").eq("is_published",!0).order("publish_date",{ascending:!1});if(g)throw g;return f}}),{data:i}=tt({queryKey:["resource-kit-files-all"],queryFn:async()=>{const{data:f,error:g}=await q.from("resource_kit_files").select("*").order("sort_order",{ascending:!0});if(g)throw g;return f}}),{data:l}=tt({queryKey:["resource-kit-likes-all"],queryFn:async()=>{const{data:f,error:g}=await q.from("resource_kit_likes").select("kit_id");if(g)throw g;return f}}),{data:o}=tt({queryKey:["resource-kit-comments-all"],queryFn:async()=>{const{data:f,error:g}=await q.from("resource_kit_comments").select("kit_id");if(g)throw g;return f}}),c=r==null?void 0:r.filter(f=>{var g;return f.name.toLowerCase().includes(t.toLowerCase())||((g=f.description)==null?void 0:g.toLowerCase().includes(t.toLowerCase()))}),d=f=>(i==null?void 0:i.filter(g=>g.kit_id===f))||[],u=f=>(l==null?void 0:l.filter(g=>g.kit_id===f).length)||0,h=f=>(o==null?void 0:o.filter(g=>g.kit_id===f).length)||0,m=f=>{s(`/toolbox/${f}`)};return e.jsx(Vs,{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(Kr,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(pe,{placeholder:"Search resource kits...",value:t,onChange:f=>n(f.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((f,g)=>e.jsx(Ne,{children:e.jsxs(Ie,{className:"p-4",children:[e.jsx(yn,{className:"aspect-[4/3] w-full rounded-lg mb-4"}),e.jsx(yn,{className:"h-5 w-3/4 mb-2"}),e.jsx(yn,{className:"h-4 w-full mb-4"}),e.jsx(yn,{className:"h-4 w-2/3"})]})},g))}):(c==null?void 0:c.length)===0?e.jsxs(Ne,{className:"p-12 text-center",children:[e.jsx(vm,{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(f=>{const g=d(f.id).length,x=u(f.id),y=h(f.id);return e.jsxs(Ne,{className:"group overflow-hidden cursor-pointer hover:shadow-lg transition-all duration-200",onClick:()=>m(f.id),children:[e.jsx("div",{className:"relative overflow-hidden bg-muted aspect-[3/2]",children:f.featured_image_url?e.jsx("img",{src:f.featured_image_url,alt:f.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(vm,{className:"h-16 w-16 text-muted-foreground"})})}),e.jsxs(Ie,{className:"p-4",children:[e.jsx("h3",{className:"font-semibold text-foreground line-clamp-1 mb-1",children:f.name}),f.description&&e.jsx("p",{className:"text-sm text-muted-foreground line-clamp-2 mb-3",children:Vte(f.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(Jr,{className:"h-4 w-4"}),g," file",g!==1?"s":""]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Vy,{className:"h-3.5 w-3.5"}),x]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Th,{className:"h-3.5 w-3.5"}),y]})]})]})]})]},f.id)})})]})})}const Drn=()=>{const{kitId:s}=Wi(),{user:t,isAdmin:n}=vs(),{toast:r}=Bi(),a=Vt(),{trackEngagement:i}=gK(),[l,o]=j.useState(""),{data:c,isLoading:d}=tt({queryKey:["resource-kit-detail",s],queryFn:async()=>{const{data:w,error:S}=await q.from("resource_kits").select("*").eq("id",s).eq("is_published",!0).single();if(S)throw S;const{data:C}=await q.from("resource_kit_files").select("*").eq("kit_id",s).order("sort_order"),{data:E}=await q.from("resource_kit_links").select("*").eq("kit_id",s).order("sort_order");return{...w,files:C||[],links:E||[]}},enabled:!!s});j.useEffect(()=>{c&&i("toolbox",c.id,c.name,"view")},[c==null?void 0:c.id]);const{data:u=[]}=tt({queryKey:["resource-kit-likes",s],queryFn:async()=>{const{data:w,error:S}=await q.from("resource_kit_likes").select("*").eq("kit_id",s);if(S)throw S;return w},enabled:!!s}),{data:h=[]}=tt({queryKey:["resource-kit-comments",s],queryFn:async()=>{const{data:w,error:S}=await q.from("resource_kit_comments").select("*").eq("kit_id",s).order("created_at",{ascending:!1});if(S)throw S;const C=[...new Set(w.map(P=>P.user_id))],{data:E}=await q.from("profiles").select("id, name").in("id",C),I=new Map((E==null?void 0:E.map(P=>[P.id,P.name]))||[]);return w.map(P=>({...P,user_name:I.get(P.user_id)||"Unknown User"}))},enabled:!!s}),m=ft({mutationFn:async w=>{const{error:S}=await q.from("resource_kit_comments").insert({kit_id:s,user_id:t.id,content:w});if(S)throw S},onSuccess:()=>{a.invalidateQueries({queryKey:["resource-kit-comments",s]}),o(""),r({title:"Comment added!"})},onError:w=>{r({title:"Error adding comment",description:w.message,variant:"destructive"})}}),f=ft({mutationFn:async w=>{const{error:S}=await q.from("resource_kit_comments").delete().eq("id",w);if(S)throw S},onSuccess:()=>{a.invalidateQueries({queryKey:["resource-kit-comments",s]}),r({title:"Comment deleted"})}}),g=ft({mutationFn:async()=>{const w=u.find(S=>S.user_id===(t==null?void 0:t.id));if(w){const{error:S}=await q.from("resource_kit_likes").delete().eq("id",w.id);if(S)throw S}else{const{error:S}=await q.from("resource_kit_likes").insert({kit_id:s,user_id:t.id});if(S)throw S}},onSuccess:()=>{a.invalidateQueries({queryKey:["resource-kit-likes",s]})}}),x=u.some(w=>w.user_id===(t==null?void 0:t.id)),y=w=>w.split(" ").map(S=>S[0]).join("").toUpperCase().slice(0,2),v=w=>w?w<1024?w+" B":w<1024*1024?(w/1024).toFixed(1)+" KB":(w/(1024*1024)).toFixed(1)+" MB":"",b=w=>{w.preventDefault(),!(!l.trim()||!t)&&m.mutate(l.trim())};return d?e.jsx(Vs,{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(Vs,{title:c.name,children:e.jsxs("div",{className:"space-y-6 max-w-5xl mx-auto",children:[e.jsx($,{variant:"ghost",size:"sm",asChild:!0,className:"gap-2",children:e.jsxs(wr,{to:"/toolbox",children:[e.jsx(qa,{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:[n&&e.jsx($,{variant:"outline",className:"gap-2 rounded-full",asChild:!0,children:e.jsxs(wr,{to:`/admin/toolbox?edit=${c.id}`,children:[e.jsx(gi,{className:"h-4 w-4"}),e.jsx("span",{children:"Edit"})]})}),e.jsx(vK,{resourceType:"resource_kit",resourceId:c.id,resourceTitle:c.name,size:"default",className:"rounded-full"}),e.jsxs($,{variant:x?"default":"outline",className:"gap-2 rounded-full",onClick:()=>g.mutate(),disabled:!t||g.isPending,children:[e.jsx(Vy,{className:`h-4 w-4 ${x?"fill-current":""}`}),u.length," ",u.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(Ne,{children:e.jsxs(Ie,{className:"pt-6",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 mb-4",children:[e.jsx(Jr,{className:"h-4 w-4"}),"Included Resources (",c.files.length,")"]}),e.jsx("div",{className:"grid gap-2",children:c.files.map(w=>e.jsxs("a",{href:w.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(Jr,{className:"h-4 w-4 text-primary"})}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium text-sm",children:w.name}),w.file_size&&e.jsx("div",{className:"text-xs text-muted-foreground",children:v(w.file_size)})]})]}),e.jsx(di,{className:"h-4 w-4 text-muted-foreground group-hover:text-primary transition-colors"})]},w.id))})]})}),c.links&&c.links.length>0&&e.jsx(Ne,{children:e.jsxs(Ie,{className:"pt-6",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 mb-4",children:[e.jsx(kr,{className:"h-4 w-4"}),"Canva Templates (",c.links.length,")"]}),e.jsx("div",{className:"grid gap-2",children:c.links.map(w=>e.jsxs("a",{href:w.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(kr,{className:"h-4 w-4 text-purple-600"})}),e.jsx("div",{className:"font-medium text-sm",children:w.title})]}),e.jsx("span",{className:"text-xs text-muted-foreground group-hover:text-primary transition-colors",children:"Open in Canva"})]},w.id))})]})}),e.jsx(BHt,{resourceType:"resource_kit",resourceId:c.id}),e.jsx(Gc,{}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 text-lg",children:[e.jsx(Th,{className:"h-5 w-5"}),"Comments (",h.length,")"]}),t?e.jsxs("form",{onSubmit:b,className:"flex gap-2",children:[e.jsx(Rs,{placeholder:"Add a comment...",value:l,onChange:w=>o(w.target.value),className:"min-h-[80px] resize-none flex-1"}),e.jsx($,{type:"submit",size:"icon",className:"h-10 w-10",disabled:!l.trim()||m.isPending,children:e.jsx(Yr,{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(Ne,{children:e.jsx(Ie,{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(w=>e.jsx(Ne,{children:e.jsx(Ie,{className:"pt-4 pb-4",children:e.jsxs("div",{className:"flex gap-3",children:[e.jsx(Oa,{className:"h-10 w-10 flex-shrink-0",children:e.jsx(za,{className:"text-sm",children:y(w.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:w.user_name}),e.jsx("span",{className:"text-sm text-muted-foreground",children:mu(new Date(w.created_at),{addSuffix:!0})}),w.user_id===(t==null?void 0:t.id)&&e.jsx($,{variant:"ghost",size:"icon",className:"h-6 w-6 ml-auto",onClick:()=>f.mutate(w.id),children:e.jsx(Wn,{className:"h-3 w-3 text-muted-foreground"})})]}),e.jsx("p",{className:"text-sm whitespace-pre-wrap",children:w.content})]})]})})},w.id))})]})]})}):e.jsx(Vs,{title:"Toolbox",children:e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(vm,{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($,{asChild:!0,className:"mt-4",children:e.jsx(wr,{to:"/toolbox",children:"Back to Toolbox"})})]})})},Frn=()=>{const s=Qn(),[t,n]=j.useState(""),[r,a]=j.useState("grid"),{data:i=[],isLoading:l}=tt({queryKey:["social-swag"],queryFn:async()=>{const{data:d,error:u}=await q.from("social_swag").select("*").eq("is_published",!0).order("publish_date",{ascending:!1});if(u)throw u;const{data:h,error:m}=await q.from("social_swag_links").select("*").order("sort_order");if(m)throw m;const{data:f}=await q.from("social_swag_likes").select("swag_id"),{data:g}=await q.from("social_swag_comments").select("swag_id"),x=new Map;f==null||f.forEach(b=>{x.set(b.swag_id,(x.get(b.swag_id)||0)+1)});const y=new Map;return g==null||g.forEach(b=>{y.set(b.swag_id,(y.get(b.swag_id)||0)+1)}),(d||[]).map(b=>({...b,links:(h||[]).filter(w=>w.swag_id===b.id)||[],likesCount:x.get(b.id)||0,commentsCount:y.get(b.id)||0}))}}),o=i.filter(d=>{var h;return d.title.toLowerCase().includes(t.toLowerCase())||((h=d.description)==null?void 0:h.toLowerCase().includes(t.toLowerCase()))}),c=d=>{s(`/social-swag/${d}`)};return e.jsx(Vs,{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(Kr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(pe,{placeholder:"Search social swag...",value:t,onChange:d=>n(d.target.value),className:"pl-9"})]}),e.jsxs("div",{className:"flex gap-2",children:[t&&e.jsx($,{variant:"outline",size:"sm",onClick:()=>n(""),children:"Clear"}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx($,{variant:r==="grid"?"secondary":"outline",size:"icon",onClick:()=>a("grid"),className:"rounded-full",children:e.jsx(Qf,{className:"h-4 w-4"})}),e.jsx($,{variant:r==="list"?"secondary":"outline",size:"icon",onClick:()=>a("list"),className:"rounded-full",children:e.jsx(P0,{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: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(8)].map((d,u)=>e.jsx(Ne,{children:e.jsxs(Ie,{className:"p-4",children:[e.jsx(yn,{className:"aspect-[4/3] w-full rounded-lg mb-4"}),e.jsx(yn,{className:"h-5 w-3/4 mb-2"}),e.jsx(yn,{className:"h-4 w-full mb-4"})]})},u))}),!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($,{variant:"outline",onClick:()=>n(""),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(d=>e.jsxs(Ne,{className:`group overflow-hidden hover:shadow-lg transition-all duration-200 cursor-pointer ${r==="list"?"flex flex-row":""}`,onClick:()=>c(d.id),children:[e.jsxs("div",{className:`relative overflow-hidden bg-muted ${r==="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(Be,{variant:"secondary",className:"gap-1 bg-background/90 backdrop-blur-sm",children:[e.jsx(Ad,{className:"h-3 w-3"}),d.links.length]})})]}),e.jsxs(Ie,{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: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(Vy,{className:"h-3.5 w-3.5"}),d.likesCount]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Th,{className:"h-3.5 w-3.5"}),d.commentsCount]})]}),e.jsxs($,{size:"sm",className:"w-full gap-2",onClick:u=>{u.stopPropagation(),c(d.id)},children:[e.jsx(kr,{className:"h-4 w-4"}),"View Details"]})]})]},d.id))})]})})};var Ac=function(){return Ac=Object.assign||function(t){for(var n,r=1,a=arguments.length;r1&&(c||!d),h=t>1&&(d||!c),m=function(){r&&i(r)},f=function(){a&&i(a)};return e.jsx(gan,{displayMonth:s.displayMonth,hideNext:u,hidePrevious:h,nextMonth:a,previousMonth:r,onPreviousClick:m,onNextClick:f})}function xan(s){var t,n=sp(),r=n.classNames,a=n.disableNavigation,i=n.styles,l=n.captionLayout,o=n.components,c=(t=o==null?void 0:o.CaptionLabel)!==null&&t!==void 0?t:qHt,d;return a?d=e.jsx(c,{id:s.id,displayMonth:s.displayMonth}):l==="dropdown"?d=e.jsx(k_t,{displayMonth:s.displayMonth,id:s.id}):l==="dropdown-buttons"?d=e.jsxs(e.Fragment,{children:[e.jsx(k_t,{displayMonth:s.displayMonth,displayIndex:s.displayIndex,id:s.id}),e.jsx(S_t,{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(S_t,{displayMonth:s.displayMonth,id:s.id})]}),e.jsx("div",{className:r.caption,style:i.caption,children:d})}function yan(s){var t=sp(),n=t.footer,r=t.styles,a=t.classNames.tfoot;return n?e.jsx("tfoot",{className:a,style:r.tfoot,children:e.jsx("tr",{children:e.jsx("td",{colSpan:8,children:n})})}):e.jsx(e.Fragment,{})}function van(s,t,n){for(var r=n?fT(new Date):C1(new Date,{locale:s,weekStartsOn:t}),a=[],i=0;i<7;i++){var l=Tm(r,i);a.push(l)}return a}function ban(){var s=sp(),t=s.classNames,n=s.styles,r=s.showWeekNumber,a=s.locale,i=s.weekStartsOn,l=s.ISOWeek,o=s.formatters.formatWeekdayName,c=s.labels.labelWeekday,d=van(a,i,l);return e.jsxs("tr",{style:n.head_row,className:t.head_row,children:[r&&e.jsx("td",{style:n.head_cell,className:t.head_cell}),d.map(function(u,h){return e.jsx("th",{scope:"col",className:t.head_cell,style:n.head_cell,"aria-label":c(u,{locale:a}),children:o(u,{locale:a})},h)})]})}function _an(){var s,t=sp(),n=t.classNames,r=t.styles,a=t.components,i=(s=a==null?void 0:a.HeadRow)!==null&&s!==void 0?s:ban;return e.jsx("thead",{style:r.head,className:n.head,children:e.jsx(i,{})})}function wan(s){var t=sp(),n=t.locale,r=t.formatters.formatDay;return e.jsx(e.Fragment,{children:r(s.date,{locale:n})})}var hrt=j.createContext(void 0);function jan(s){if(!gie(s.initialProps)){var t={selected:void 0,modifiers:{disabled:[]}};return e.jsx(hrt.Provider,{value:t,children:s.children})}return e.jsx(Nan,{initialProps:s.initialProps,children:s.children})}function Nan(s){var t=s.initialProps,n=s.children,r=t.selected,a=t.min,i=t.max,l=function(d,u,h){var m,f;(m=t.onDayClick)===null||m===void 0||m.call(t,d,u,h);var g=!!(u.selected&&a&&(r==null?void 0:r.length)===a);if(!g){var x=!!(!u.selected&&i&&(r==null?void 0:r.length)===i);if(!x){var y=r?$Ht([],r):[];if(u.selected){var v=y.findIndex(function(b){return nf(d,b)});y.splice(v,1)}else y.push(d);(f=t.onSelect)===null||f===void 0||f.call(t,y,d,u,h)}}},o={disabled:[]};r&&o.disabled.push(function(d){var u=i&&r.length>i-1,h=r.some(function(m){return nf(m,d)});return!!(u&&!h)});var c={selected:r,onDayClick:l,modifiers:o};return e.jsx(hrt.Provider,{value:c,children:n})}function mrt(){var s=j.useContext(hrt);if(!s)throw new Error("useSelectMultiple must be used within a SelectMultipleProvider");return s}function kan(s,t){var n=t||{},r=n.from,a=n.to;return r&&a?nf(a,s)&&nf(r,s)?void 0:nf(a,s)?{from:a,to:void 0}:nf(r,s)?void 0:O4(r,s)?{from:s,to:a}:{from:r,to:s}:a?O4(s,a)?{from:a,to:s}:{from:s,to:a}:r?iC(s,r)?{from:s,to:r}:{from:r,to:s}:{from:s,to:void 0}}var frt=j.createContext(void 0);function San(s){if(!xie(s.initialProps)){var t={selected:void 0,modifiers:{range_start:[],range_end:[],range_middle:[],disabled:[]}};return e.jsx(frt.Provider,{value:t,children:s.children})}return e.jsx(Can,{initialProps:s.initialProps,children:s.children})}function Can(s){var t=s.initialProps,n=s.children,r=t.selected,a=r||{},i=a.from,l=a.to,o=t.min,c=t.max,d=function(f,g,x){var y,v;(y=t.onDayClick)===null||y===void 0||y.call(t,f,g,x);var b=kan(f,r);(v=t.onSelect)===null||v===void 0||v.call(t,b,f,g,x)},u={range_start:[],range_end:[],range_middle:[],disabled:[]};if(i?(u.range_start=[i],l?(u.range_end=[l],nf(i,l)||(u.range_middle=[{after:i,before:l}])):u.range_end=[i]):l&&(u.range_start=[l],u.range_end=[l]),o&&(i&&!l&&u.disabled.push({after:J4e(i,o-1),before:Tm(i,o-1)}),i&&l&&u.disabled.push({after:i,before:Tm(i,o-1)}),!i&&l&&u.disabled.push({after:J4e(l,o-1),before:Tm(l,o-1)})),c){if(i&&!l&&(u.disabled.push({before:Tm(i,-c+1)}),u.disabled.push({after:Tm(i,c-1)})),i&&l){var h=fb(l,i)+1,m=c-h;u.disabled.push({before:J4e(i,m)}),u.disabled.push({after:Tm(l,m)})}!i&&l&&(u.disabled.push({before:Tm(l,-c+1)}),u.disabled.push({after:Tm(l,c-1)}))}return e.jsx(frt.Provider,{value:{selected:r,onDayClick:d,modifiers:u},children:n})}function prt(){var s=j.useContext(frt);if(!s)throw new Error("useSelectRange must be used within a SelectRangeProvider");return s}function _3e(s){return Array.isArray(s)?$Ht([],s):s!==void 0?[s]:[]}function Aan(s){var t={};return Object.entries(s).forEach(function(n){var r=n[0],a=n[1];t[r]=_3e(a)}),t}var yC;(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"})(yC||(yC={}));var Ean=yC.Selected,sA=yC.Disabled,Tan=yC.Hidden,Man=yC.Today,DBe=yC.RangeEnd,FBe=yC.RangeMiddle,OBe=yC.RangeStart,Pan=yC.Outside;function Ian(s,t,n){var r,a=(r={},r[Ean]=_3e(s.selected),r[sA]=_3e(s.disabled),r[Tan]=_3e(s.hidden),r[Man]=[s.today],r[DBe]=[],r[FBe]=[],r[OBe]=[],r[Pan]=[],r);return s.fromDate&&a[sA].push({before:s.fromDate}),s.toDate&&a[sA].push({after:s.toDate}),gie(s)?a[sA]=a[sA].concat(t.modifiers[sA]):xie(s)&&(a[sA]=a[sA].concat(n.modifiers[sA]),a[OBe]=n.modifiers[OBe],a[FBe]=n.modifiers[FBe],a[DBe]=n.modifiers[DBe]),a}var GHt=j.createContext(void 0);function Lan(s){var t=sp(),n=mrt(),r=prt(),a=Ian(t,n,r),i=Aan(t.modifiers),l=Ac(Ac({},a),i);return e.jsx(GHt.Provider,{value:l,children:s.children})}function WHt(){var s=j.useContext(GHt);if(!s)throw new Error("useModifiers must be used within a ModifiersProvider");return s}function Ran(s){return!!(s&&typeof s=="object"&&"before"in s&&"after"in s)}function Dan(s){return!!(s&&typeof s=="object"&&"from"in s)}function Fan(s){return!!(s&&typeof s=="object"&&"after"in s)}function Oan(s){return!!(s&&typeof s=="object"&&"before"in s)}function zan(s){return!!(s&&typeof s=="object"&&"dayOfWeek"in s)}function Ban(s,t){var n,r=t.from,a=t.to;if(r&&a){var i=fb(a,r)<0;i&&(n=[a,r],r=n[0],a=n[1]);var l=fb(s,r)>=0&&fb(a,s)>=0;return l}return a?nf(a,s):r?nf(r,s):!1}function $an(s){return Ctt(s)}function Uan(s){return Array.isArray(s)&&s.every(Ctt)}function qan(s,t){return t.some(function(n){if(typeof n=="boolean")return n;if($an(n))return nf(s,n);if(Uan(n))return n.includes(s);if(Dan(n))return Ban(s,n);if(zan(n))return n.dayOfWeek.includes(s.getDay());if(Ran(n)){var r=fb(n.before,s),a=fb(n.after,s),i=r>0,l=a<0,o=O4(n.before,n.after);return o?l&&i:i||l}return Fan(n)?fb(s,n.after)>0:Oan(n)?fb(n.before,s)>0:typeof n=="function"?n(s):!1})}function grt(s,t,n){var r=Object.keys(t).reduce(function(i,l){var o=t[l];return qan(s,o)&&i.push(l),i},[]),a={};return r.forEach(function(i){return a[i]=!0}),n&&!qae(s,n)&&(a.outside=!0),a}function Van(s,t){for(var n=Xm(s[0]),r=yw(s[s.length-1]),a,i,l=n;l<=r;){var o=grt(l,t),c=!o.disabled&&!o.hidden;if(!c){l=Tm(l,1);continue}if(o.selected)return l;o.today&&!i&&(i=l),a||(a=l),l=Tm(l,1)}return i||a}var Han=365;function KHt(s,t){var n=t.moveBy,r=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,u=a.toDate,h=a.locale,m={day:Tm,week:c8,month:Mv,year:mPs,startOfWeek:function(y){return a.ISOWeek?fT(y):C1(y,{locale:h,weekStartsOn:c})},endOfWeek:function(y){return a.ISOWeek?Pzt(y):DLe(y,{locale:h,weekStartsOn:c})}},f=m[n](s,r==="after"?1:-1);r==="before"&&d?f=fPs([d,f]):r==="after"&&u&&(f=pPs([u,f]));var g=!0;if(i){var x=grt(f,i);g=!x.disabled&&!x.hidden}return g?f:o.count>Han?o.lastFocused:KHt(f,{moveBy:n,direction:r,context:a,modifiers:i,retry:Ac(Ac({},o),{count:o.count+1})})}var YHt=j.createContext(void 0);function Gan(s){var t=yie(),n=WHt(),r=j.useState(),a=r[0],i=r[1],l=j.useState(),o=l[0],c=l[1],d=Van(t.displayMonths,n),u=a??(o&&t.isDateDisplayed(o))?o:d,h=function(){c(a),i(void 0)},m=function(y){i(y)},f=sp(),g=function(y,v){if(a){var b=KHt(a,{moveBy:y,direction:v,context:f,modifiers:n});nf(a,b)||(t.goToDate(b,a),m(b))}},x={focusedDay:a,focusTarget:u,blur:h,focus:m,focusDayAfter:function(){return g("day","after")},focusDayBefore:function(){return g("day","before")},focusWeekAfter:function(){return g("week","after")},focusWeekBefore:function(){return g("week","before")},focusMonthBefore:function(){return g("month","before")},focusMonthAfter:function(){return g("month","after")},focusYearBefore:function(){return g("year","before")},focusYearAfter:function(){return g("year","after")},focusStartOfWeek:function(){return g("startOfWeek","before")},focusEndOfWeek:function(){return g("endOfWeek","after")}};return e.jsx(YHt.Provider,{value:x,children:s.children})}function xrt(){var s=j.useContext(YHt);if(!s)throw new Error("useFocusContext must be used within a FocusProvider");return s}function Wan(s,t){var n=WHt(),r=grt(s,n,t);return r}var yrt=j.createContext(void 0);function Kan(s){if(!nRe(s.initialProps)){var t={selected:void 0};return e.jsx(yrt.Provider,{value:t,children:s.children})}return e.jsx(Yan,{initialProps:s.initialProps,children:s.children})}function Yan(s){var t=s.initialProps,n=s.children,r=function(i,l,o){var c,d,u;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}(u=t.onSelect)===null||u===void 0||u.call(t,i,i,l,o)},a={selected:t.selected,onDayClick:r};return e.jsx(yrt.Provider,{value:a,children:n})}function ZHt(){var s=j.useContext(yrt);if(!s)throw new Error("useSelectSingle must be used within a SelectSingleProvider");return s}function Zan(s,t){var n=sp(),r=ZHt(),a=mrt(),i=prt(),l=xrt(),o=l.focusDayAfter,c=l.focusDayBefore,d=l.focusWeekAfter,u=l.focusWeekBefore,h=l.blur,m=l.focus,f=l.focusMonthBefore,g=l.focusMonthAfter,x=l.focusYearBefore,y=l.focusYearAfter,v=l.focusStartOfWeek,b=l.focusEndOfWeek,w=function(X){var ae,ie,ne,te;nRe(n)?(ae=r.onDayClick)===null||ae===void 0||ae.call(r,s,t,X):gie(n)?(ie=a.onDayClick)===null||ie===void 0||ie.call(a,s,t,X):xie(n)?(ne=i.onDayClick)===null||ne===void 0||ne.call(i,s,t,X):(te=n.onDayClick)===null||te===void 0||te.call(n,s,t,X)},S=function(X){var ae;m(s),(ae=n.onDayFocus)===null||ae===void 0||ae.call(n,s,t,X)},C=function(X){var ae;h(),(ae=n.onDayBlur)===null||ae===void 0||ae.call(n,s,t,X)},E=function(X){var ae;(ae=n.onDayMouseEnter)===null||ae===void 0||ae.call(n,s,t,X)},I=function(X){var ae;(ae=n.onDayMouseLeave)===null||ae===void 0||ae.call(n,s,t,X)},P=function(X){var ae;(ae=n.onDayPointerEnter)===null||ae===void 0||ae.call(n,s,t,X)},R=function(X){var ae;(ae=n.onDayPointerLeave)===null||ae===void 0||ae.call(n,s,t,X)},D=function(X){var ae;(ae=n.onDayTouchCancel)===null||ae===void 0||ae.call(n,s,t,X)},O=function(X){var ae;(ae=n.onDayTouchEnd)===null||ae===void 0||ae.call(n,s,t,X)},U=function(X){var ae;(ae=n.onDayTouchMove)===null||ae===void 0||ae.call(n,s,t,X)},W=function(X){var ae;(ae=n.onDayTouchStart)===null||ae===void 0||ae.call(n,s,t,X)},V=function(X){var ae;(ae=n.onDayKeyUp)===null||ae===void 0||ae.call(n,s,t,X)},G=function(X){var ae;switch(X.key){case"ArrowLeft":X.preventDefault(),X.stopPropagation(),n.dir==="rtl"?o():c();break;case"ArrowRight":X.preventDefault(),X.stopPropagation(),n.dir==="rtl"?c():o();break;case"ArrowDown":X.preventDefault(),X.stopPropagation(),d();break;case"ArrowUp":X.preventDefault(),X.stopPropagation(),u();break;case"PageUp":X.preventDefault(),X.stopPropagation(),X.shiftKey?x():f();break;case"PageDown":X.preventDefault(),X.stopPropagation(),X.shiftKey?y():g();break;case"Home":X.preventDefault(),X.stopPropagation(),v();break;case"End":X.preventDefault(),X.stopPropagation(),b();break}(ae=n.onDayKeyDown)===null||ae===void 0||ae.call(n,s,t,X)},Y={onClick:w,onFocus:S,onBlur:C,onKeyDown:G,onKeyUp:V,onMouseEnter:E,onMouseLeave:I,onPointerEnter:P,onPointerLeave:R,onTouchCancel:D,onTouchEnd:O,onTouchMove:U,onTouchStart:W};return Y}function Xan(){var s=sp(),t=ZHt(),n=mrt(),r=prt(),a=nRe(s)?t.selected:gie(s)?n.selected:xie(s)?r.selected:void 0;return a}function Qan(s){return Object.values(yC).includes(s)}function Jan(s,t){var n=[s.classNames.day];return Object.keys(t).forEach(function(r){var a=s.modifiersClassNames[r];if(a)n.push(a);else if(Qan(r)){var i=s.classNames["day_".concat(r)];i&&n.push(i)}}),n}function ein(s,t){var n=Ac({},s.styles.day);return Object.keys(t).forEach(function(r){var a;n=Ac(Ac({},n),(a=s.modifiersStyles)===null||a===void 0?void 0:a[r])}),n}function tin(s,t,n){var r,a,i,l=sp(),o=xrt(),c=Wan(s,t),d=Zan(s,c),u=Xan(),h=!!(l.onDayClick||l.mode!=="default");j.useEffect(function(){var E;c.outside||o.focusedDay&&h&&nf(o.focusedDay,s)&&((E=n.current)===null||E===void 0||E.focus())},[o.focusedDay,s,n,h,c.outside]);var m=Jan(l,c).join(" "),f=ein(l,c),g=!!(c.outside&&!l.showOutsideDays||c.hidden),x=(i=(a=l.components)===null||a===void 0?void 0:a.DayContent)!==null&&i!==void 0?i:wan,y=e.jsx(x,{date:s,displayMonth:t,activeModifiers:c}),v={style:f,className:m,children:y,role:"gridcell"},b=o.focusTarget&&nf(o.focusTarget,s)&&!c.outside,w=o.focusedDay&&nf(o.focusedDay,s),S=Ac(Ac(Ac({},v),(r={disabled:c.disabled,role:"gridcell"},r["aria-selected"]=c.selected,r.tabIndex=w||b?0:-1,r)),d),C={isButton:h,isHidden:g,activeModifiers:c,selectedDays:u,buttonProps:S,divProps:v};return C}function sin(s){var t=j.useRef(null),n=tin(s.date,s.displayMonth,t);return n.isHidden?e.jsx("div",{role:"gridcell"}):n.isButton?e.jsx(BTe,Ac({name:"day",ref:t},n.buttonProps)):e.jsx("div",Ac({},n.divProps))}function nin(s){var t=s.number,n=s.dates,r=sp(),a=r.onWeekNumberClick,i=r.styles,l=r.classNames,o=r.locale,c=r.labels.labelWeekNumber,d=r.formatters.formatWeekNumber,u=d(Number(t),{locale:o});if(!a)return e.jsx("span",{className:l.weeknumber,style:i.weeknumber,children:u});var h=c(Number(t),{locale:o}),m=function(f){a(t,n,f)};return e.jsx(BTe,{name:"week-number","aria-label":h,className:l.weeknumber,style:i.weeknumber,onClick:m,children:u})}function rin(s){var t,n,r=sp(),a=r.styles,i=r.classNames,l=r.showWeekNumber,o=r.components,c=(t=o==null?void 0:o.Day)!==null&&t!==void 0?t:sin,d=(n=o==null?void 0:o.WeekNumber)!==null&&n!==void 0?n:nin,u;return l&&(u=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:[u,s.dates.map(function(h){return e.jsx("td",{className:i.cell,style:a.cell,role:"presentation",children:e.jsx(c,{displayMonth:s.displayMonth,date:h})},bIs(h))})]})}function C_t(s,t,n){for(var r=n!=null&&n.ISOWeek?Pzt(t):DLe(t,n),a=n!=null&&n.ISOWeek?fT(s):C1(s,n),i=fb(r,a),l=[],o=0;o<=i;o++)l.push(Tm(a,o));var c=l.reduce(function(d,u){var h=n!=null&&n.ISOWeek?Ett(u):Mtt(u,n),m=d.find(function(f){return f.weekNumber===h});return m?(m.dates.push(u),d):(d.push({weekNumber:h,dates:[u]}),d)},[]);return c}function ain(s,t){var n=C_t(Xm(s),yw(s),t);if(t!=null&&t.useFixedWeeks){var r=wIs(s,t);if(r<6){var a=n[n.length-1],i=a.dates[a.dates.length-1],l=c8(i,6-r),o=C_t(c8(i,1),l,t);n.push.apply(n,o)}}return n}function iin(s){var t,n,r,a=sp(),i=a.locale,l=a.classNames,o=a.styles,c=a.hideHead,d=a.fixedWeeks,u=a.components,h=a.weekStartsOn,m=a.firstWeekContainsDate,f=a.ISOWeek,g=ain(s.displayMonth,{useFixedWeeks:!!d,ISOWeek:f,locale:i,weekStartsOn:h,firstWeekContainsDate:m}),x=(t=u==null?void 0:u.Head)!==null&&t!==void 0?t:_an,y=(n=u==null?void 0:u.Row)!==null&&n!==void 0?n:rin,v=(r=u==null?void 0:u.Footer)!==null&&r!==void 0?r:yan;return e.jsxs("table",{id:s.id,className:l.table,style:o.table,role:"grid","aria-labelledby":s["aria-labelledby"],children:[!c&&e.jsx(x,{}),e.jsx("tbody",{className:l.tbody,style:o.tbody,children:g.map(function(b){return e.jsx(y,{displayMonth:s.displayMonth,dates:b.dates,weekNumber:b.weekNumber},b.weekNumber)})}),e.jsx(v,{displayMonth:s.displayMonth})]})}function oin(){return!!(typeof window<"u"&&window.document&&window.document.createElement)}var lin=oin()?j.useLayoutEffect:j.useEffect,zBe=!1,cin=0;function A_t(){return"react-day-picker-".concat(++cin)}function din(s){var t,n=s??(zBe?A_t():null),r=j.useState(n),a=r[0],i=r[1];return lin(function(){a===null&&i(A_t())},[]),j.useEffect(function(){zBe===!1&&(zBe=!0)},[]),(t=s??a)!==null&&t!==void 0?t:void 0}function uin(s){var t,n,r=sp(),a=r.dir,i=r.classNames,l=r.styles,o=r.components,c=yie().displayMonths,d=din(r.id?"".concat(r.id,"-").concat(s.displayIndex):void 0),u=r.id?"".concat(r.id,"-grid-").concat(s.displayIndex):void 0,h=[i.month],m=l.month,f=s.displayIndex===0,g=s.displayIndex===c.length-1,x=!f&&!g;a==="rtl"&&(t=[f,g],g=t[0],f=t[1]),f&&(h.push(i.caption_start),m=Ac(Ac({},m),l.caption_start)),g&&(h.push(i.caption_end),m=Ac(Ac({},m),l.caption_end)),x&&(h.push(i.caption_between),m=Ac(Ac({},m),l.caption_between));var y=(n=o==null?void 0:o.Caption)!==null&&n!==void 0?n:xan;return e.jsxs("div",{className:h.join(" "),style:m,children:[e.jsx(y,{id:d,displayMonth:s.displayMonth,displayIndex:s.displayIndex}),e.jsx(iin,{id:u,"aria-labelledby":d,displayMonth:s.displayMonth})]},s.displayIndex)}function hin(s){var t=sp(),n=t.classNames,r=t.styles;return e.jsx("div",{className:n.months,style:r.months,children:s.children})}function min(s){var t,n,r=s.initialProps,a=sp(),i=xrt(),l=yie(),o=j.useState(!1),c=o[0],d=o[1];j.useEffect(function(){a.initialFocus&&i.focusTarget&&(c||(i.focus(i.focusTarget),d(!0)))},[a.initialFocus,c,i.focus,i.focusTarget,i]);var u=[a.classNames.root,a.className];a.numberOfMonths>1&&u.push(a.classNames.multiple_months),a.showWeekNumber&&u.push(a.classNames.with_weeknumber);var h=Ac(Ac({},a.styles.root),a.style),m=Object.keys(r).filter(function(g){return g.startsWith("data-")}).reduce(function(g,x){var y;return Ac(Ac({},g),(y={},y[x]=r[x],y))},{}),f=(n=(t=r.components)===null||t===void 0?void 0:t.Months)!==null&&n!==void 0?n:hin;return e.jsx("div",Ac({className:u.join(" "),style:h,dir:a.dir,id:a.id,nonce:r.nonce,title:r.title,lang:r.lang},m,{children:e.jsx(f,{children:l.displayMonths.map(function(g,x){return e.jsx(uin,{displayIndex:x,displayMonth:g},x)})})}))}function fin(s){var t=s.children,n=Orn(s,["children"]);return e.jsx(nan,{initialProps:n,children:e.jsx(man,{children:e.jsx(Kan,{initialProps:n,children:e.jsx(jan,{initialProps:n,children:e.jsx(San,{initialProps:n,children:e.jsx(Lan,{children:e.jsx(Gan,{children:t})})})})})})})}function pin(s){return e.jsx(fin,Ac({},s,{children:e.jsx(min,{initialProps:s})}))}function D2({className:s,classNames:t,showOutsideDays:n=!0,...r}){return e.jsx(pin,{showOutsideDays:n,className:Pt("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",caption_dropdowns:"flex gap-2 items-center justify-center",vhidden:"sr-only",nav:"space-x-1 flex items-center",nav_button:Pt(gG({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:Pt(gG({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",dropdown:"h-8 rounded-md border border-input bg-background px-2 py-1 text-sm ring-offset-background focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2",...t},components:{IconLeft:({...a})=>e.jsx(Cd,{className:"h-4 w-4"}),IconRight:({...a})=>e.jsx(Di,{className:"h-4 w-4"})},...r})}D2.displayName="Calendar";var gin=Object.defineProperty,y6=(s,t)=>gin(s,"name",{value:t,configurable:!0}),vrt="Popover",[XHt,TSr]=tp(vrt,[i3]),brt=i3(),[xin,bK]=XHt(vrt),yin=y6(s=>{const{__scopePopover:t,children:n,open:r,defaultOpen:a,onOpenChange:i,modal:l=!1}=s,o=brt(t),c=j.useRef(null),[d,u]=j.useState(!1),[h,m]=fy({prop:r,defaultProp:a??!1,onChange:i,caller:vrt});return e.jsx(Cae,{...o,children:e.jsx(xin,{scope:t,contentId:my(),triggerRef:c,open:h,onOpenChange:m,onOpenToggle:j.useCallback(()=>m(f=>!f),[m]),hasCustomAnchor:d,onCustomAnchorAdd:j.useCallback(()=>u(!0),[]),onCustomAnchorRemove:j.useCallback(()=>u(!1),[]),modal:l,children:n})})},"Popover"),vin="PopoverTrigger",bin=j.forwardRef(y6(function(t,n){const{__scopePopover:r,...a}=t,i=bK(vin,r),l=brt(r),o=Vo(n,i.triggerRef),c=e.jsx(Ei.button,{type:"button","aria-haspopup":"dialog","aria-expanded":i.open,"aria-controls":i.open?i.contentId:void 0,"data-state":_rt(i.open),...a,ref:o,onClick:Ra(t.onClick,i.onOpenToggle)});return i.hasCustomAnchor?c:e.jsx(Aae,{asChild:!0,...l,children:c})},"PopoverTrigger")),QHt="PopoverPortal",[_in,win]=XHt(QHt,{forceMount:void 0}),jin=y6(s=>{const{__scopePopover:t,forceMount:n,children:r,container:a}=s,i=bK(QHt,t);return e.jsx(_in,{scope:t,forceMount:n,children:e.jsx(xy,{present:n||i.open,children:e.jsx(_ae,{asChild:!0,container:a,children:r})})})},"PopoverPortal"),Ese="PopoverContent",Nin=j.forwardRef(y6(function(t,n){const r=win(Ese,t.__scopePopover),{forceMount:a=r.forceMount,...i}=t,l=bK(Ese,t.__scopePopover);return e.jsx(xy,{present:a||l.open,children:l.modal?e.jsx(Sin,{...i,ref:n}):e.jsx(Cin,{...i,ref:n})})},"PopoverContent")),kin=pC("PopoverContent.RemoveScroll"),Sin=j.forwardRef(y6(function(t,n){const r=bK(Ese,t.__scopePopover),a=j.useRef(null),i=Vo(n,a),l=j.useRef(!1);return j.useEffect(()=>{const o=a.current;if(o)return KIe(o)},[]),e.jsx(jae,{as:kin,allowPinchZoom:!0,children:e.jsx(JHt,{...t,ref:i,trapFocus:r.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:Ra(t.onCloseAutoFocus,o=>{var c;o.preventDefault(),l.current||(c=r.triggerRef.current)==null||c.focus()}),onPointerDownOutside:Ra(t.onPointerDownOutside,o=>{const c=o.detail.originalEvent,d=c.button===0&&c.ctrlKey===!0,u=c.button===2||d;l.current=u},{checkForDefaultPrevented:!1}),onFocusOutside:Ra(t.onFocusOutside,o=>o.preventDefault(),{checkForDefaultPrevented:!1})})})},"PopoverContentModal")),Cin=j.forwardRef(y6(function(t,n){const r=bK(Ese,t.__scopePopover),a=j.useRef(!1),i=j.useRef(!1);return e.jsx(JHt,{...t,ref:n,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:l=>{var o,c;(o=t.onCloseAutoFocus)==null||o.call(t,l),l.defaultPrevented||(a.current||(c=r.triggerRef.current)==null||c.focus(),l.preventDefault()),a.current=!1,i.current=!1},onInteractOutside:l=>{var d,u;(d=t.onInteractOutside)==null||d.call(t,l),l.defaultPrevented||(a.current=!0,l.detail.originalEvent.type==="pointerdown"&&(i.current=!0));const o=l.target;((u=r.triggerRef.current)==null?void 0:u.contains(o))&&l.preventDefault(),l.detail.originalEvent.type==="focusin"&&i.current&&l.preventDefault()}})},"PopoverContentNonModal")),JHt=j.forwardRef(y6(function(t,n){const{__scopePopover:r,trapFocus:a,onOpenAutoFocus:i,onCloseAutoFocus:l,disableOutsidePointerEvents:o,onEscapeKeyDown:c,onPointerDownOutside:d,onFocusOutside:u,onInteractOutside:h,...m}=t,f=bK(Ese,r),g=brt(r);return GW(),e.jsx(GIe,{asChild:!0,loop:!0,trapped:a,onMountAutoFocus:i,onUnmountAutoFocus:l,children:e.jsx(RB,{asChild:!0,disableOutsidePointerEvents:o,onInteractOutside:h,onEscapeKeyDown:c,onPointerDownOutside:d,onFocusOutside:u,onDismiss:()=>f.onOpenChange(!1),deferPointerDownOutside:!0,children:e.jsx(Eae,{"data-state":_rt(f.open),role:"dialog",id:f.contentId,...g,...m,ref:n,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)"}})})})},"PopoverContentImpl"));function _rt(s){return s?"open":"closed"}y6(_rt,"getState");var Ain=yin,Ein=bin,Tin=jin,eGt=Nin;const Yd=Ain,Zd=Ein,Bd=j.forwardRef(({className:s,align:t="center",sideOffset:n=4,...r},a)=>e.jsx(Tin,{children:e.jsx(eGt,{ref:a,align:t,sideOffset:n,className:Pt("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),...r})}));Bd.displayName=eGt.displayName;async function Tse(s){if(s instanceof Tae)try{const t=await s.context.text();try{const n=JSON.parse(t),r=(n==null?void 0:n.error)??(n==null?void 0:n.message);if(typeof r=="string"&&r.trim())return r}catch{if(t.trim())return t.trim()}}catch{}return s instanceof Error&&s.message?s.message:"Something went wrong. Please try again."}const Min=DB("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"}}),Mse=j.forwardRef(({className:s,variant:t,...n},r)=>e.jsx("div",{ref:r,role:"alert",className:Pt(Min({variant:t}),s),...n}));Mse.displayName="Alert";const Pin=j.forwardRef(({className:s,...t},n)=>e.jsx("h5",{ref:n,className:Pt("mb-1 font-medium leading-none tracking-tight",s),...t}));Pin.displayName="AlertTitle";const Pse=j.forwardRef(({className:s,...t},n)=>e.jsx("div",{ref:n,className:Pt("text-sm [&_p]:leading-relaxed",s),...t}));Pse.displayName="AlertDescription";function Iin({open:s,onOpenChange:t,imageUrl:n,imageId:r,defaultCaption:a="",swagItemId:i,reelId:l}){const o=Vt(),{user:c}=vs(),d=(c==null?void 0:c.id)??null,[u,h]=j.useState(a),[m,f]=j.useState([]),[g,x]=j.useState(null),[y,v]=j.useState("now"),[b,w]=j.useState(Myt(Oyt(new Date),1)),[S,C]=j.useState("12"),[E,I]=j.useState("00"),[P,R]=j.useState("PM");j.useEffect(()=>{if(s){h(a),v("now"),f([]);const he=Myt(Oyt(new Date),1);w(he);const ue=he.getHours();C(String(ue>12?ue-12:ue===0?12:ue)),I("00"),R(ue>=12?"PM":"AM")}},[s,a]);const D=()=>{if(!b)return null;let he=parseInt(S);const ue=parseInt(E);return P==="PM"&&he!==12&&(he+=12),P==="AM"&&he===12&&(he=0),Uzt($zt(b,he),ue)},{data:O,isLoading:U}=tt({queryKey:["social-accounts-for-post",d],queryFn:async()=>{const{data:{user:he}}=await q.auth.getUser();if(!he)return[];const{data:ue,error:ve}=await q.from("social_accounts").select("*").eq("user_id",he.id).eq("is_active",!0).order("platform",{ascending:!0});if(ve)throw ve;return console.log("Fetched social accounts for posting:",ue),ue},enabled:s,staleTime:0}),W=ft({mutationFn:async({accountId:he,platform:ue})=>{x(he);const{data:ve,error:Ee}=await q.functions.invoke("social-post",{body:{platform:ue,accountId:he,imageUrl:n,caption:u}});if(Ee)throw new Error(await Tse(Ee));if(ve!=null&&ve.error)throw new Error(ve.error);return ve},onSuccess:he=>{const ue=he.platform==="facebook"?"Facebook":he.platform==="instagram"?"Instagram":he.platform==="linkedin"?"LinkedIn":"Google Business";re.success(`Posted to ${ue}!`)},onError:he=>{re.error(`Failed to post: ${he.message}`)},onSettled:()=>{x(null)}}),V=ft({mutationFn:async({accountId:he,platform:ue,scheduledFor:ve})=>{const{data:{user:Ee}}=await q.auth.getUser();if(!Ee)throw new Error("Not authenticated");const{error:Se}=await q.from("scheduled_posts").insert({user_id:Ee.id,social_account_id:he,platform:ue,image_url:n,caption:u,swag_item_id:i||null,reel_id:l||null,scheduled_for:ve.toISOString(),status:"scheduled"});if(Se)throw Se;return{platform:ue}},onSuccess:he=>{const ue=he.platform==="facebook"?"Facebook":he.platform==="instagram"?"Instagram":"LinkedIn";re.success(`Post scheduled for ${ue}!`)},onError:he=>{re.error(`Failed to schedule: ${he.message}`)}}),G=async()=>{if(m.length===0){re.error("Please select at least one account");return}if(y==="schedule"){const he=D();if(!he||he<=new Date){re.error("Please select a future date and time");return}for(const ue of m){const ve=O==null?void 0:O.find(Ee=>Ee.id===ue);ve&&await V.mutateAsync({accountId:ue,platform:ve.platform,scheduledFor:he})}o.invalidateQueries({queryKey:["scheduled-posts",d]}),re.success(`${m.length} post(s) scheduled for ${en(he,"PPp")}`)}else for(const he of m){const ue=O==null?void 0:O.find(ve=>ve.id===he);ue&&await W.mutateAsync({accountId:he,platform:ue.platform})}o.invalidateQueries({queryKey:["scheduled-posts",d]}),h(""),f([]),t(!1)},Y=he=>{f(ue=>ue.includes(he)?ue.filter(ve=>ve!==he):[...ue,he])},X=(O==null?void 0:O.filter(he=>he.platform==="facebook"))||[],ae=(O==null?void 0:O.filter(he=>he.platform==="instagram"))||[],ie=(O==null?void 0:O.filter(he=>he.platform==="linkedin"))||[],ne=(O==null?void 0:O.filter(he=>he.platform==="google_business"))||[],te=((O==null?void 0:O.length)||0)>0,J=W.isPending||V.isPending,ce=Array.from({length:12},(he,ue)=>String(ue+1)),_e=["00","15","30","45"];return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Os,{className:"sm:max-w-lg max-h-[90vh] overflow-y-auto",children:[e.jsxs(Us,{children:[e.jsx(Bs,{children:"Create Social Post"}),e.jsx(Ir,{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:n,alt:"Post preview",className:"h-full w-full object-cover"})}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"caption",children:"Caption"}),e.jsx(Rs,{id:"caption",placeholder:"Write a caption for your post...",value:u,onChange:he=>h(he.target.value),rows:3}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[u.length,"/2200 characters"]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx(ee,{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:()=>v("now"),className:Pt("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:()=>v("schedule"),className:Pt("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(da,{className:"h-4 w-4"}),"Schedule for"]}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-3",children:[e.jsxs(Yd,{children:[e.jsx(Zd,{asChild:!0,children:e.jsxs($,{variant:"outline",className:Pt("justify-start text-left font-normal flex-1",!b&&"text-muted-foreground"),children:[e.jsx(Ta,{className:"mr-2 h-4 w-4"}),b?en(b,"PPP"):e.jsx("span",{children:"Pick a date"})]})}),e.jsx(Bd,{className:"w-auto p-0",align:"start",children:e.jsx(D2,{mode:"single",selected:b,onSelect:w,disabled:he=>hee.jsx(Ge,{value:he,children:he},he))})]}),e.jsx("span",{className:"text-muted-foreground",children:":"}),e.jsxs(ms,{value:E,onValueChange:I,children:[e.jsx(us,{className:"w-[70px]",children:e.jsx(fs,{})}),e.jsx(hs,{children:_e.map(he=>e.jsx(Ge,{value:he,children:he},he))})]}),e.jsxs(ms,{value:P,onValueChange:he=>R(he),children:[e.jsx(us,{className:"w-[70px]",children:e.jsx(fs,{})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"AM",children:"AM"}),e.jsx(Ge,{value:"PM",children:"PM"})]})]})]})]}),b&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Post will be published on ",en(D()||new Date,"PPP 'at' p")]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx(ee,{children:"Post to"}),U&&e.jsx("div",{className:"flex items-center justify-center py-4",children:e.jsx(kt,{className:"h-6 w-6 animate-spin"})}),!U&&!te&&e.jsxs(Mse,{children:[e.jsx(ll,{className:"h-4 w-4"}),e.jsxs(Pse,{className:"flex flex-col gap-2",children:[e.jsx("span",{children:"No social accounts connected yet."}),e.jsxs(wr,{to:"/social-connections",className:"inline-flex items-center gap-1.5 text-primary hover:underline font-medium",children:[e.jsx(Sd,{className:"h-3.5 w-3.5"}),"Connect your Facebook, Instagram & LinkedIn"]})]})]}),X.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(Qp,{className:"h-4 w-4 text-blue-600"})," Facebook"]}),X.map(he=>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(ai,{checked:m.includes(he.id),onCheckedChange:()=>Y(he.id),disabled:g===he.id}),e.jsxs(Oa,{className:"h-8 w-8",children:[e.jsx(Li,{src:he.profile_picture_url||""}),e.jsx(za,{children:e.jsx(Qp,{className:"h-4 w-4"})})]}),e.jsx("span",{className:"flex-1 text-sm font-medium",children:he.page_name||he.platform_username}),g===he.id&&e.jsx(kt,{className:"h-4 w-4 animate-spin"})]},he.id))]}),ae.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(Tf,{className:"h-4 w-4 text-pink-600"})," Instagram"]}),ae.map(he=>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(ai,{checked:m.includes(he.id),onCheckedChange:()=>Y(he.id),disabled:g===he.id}),e.jsxs(Oa,{className:"h-8 w-8",children:[e.jsx(Li,{src:he.profile_picture_url||""}),e.jsx(za,{children:e.jsx(Tf,{className:"h-4 w-4"})})]}),e.jsxs("span",{className:"flex-1 text-sm font-medium",children:["@",he.platform_username]}),g===he.id&&e.jsx(kt,{className:"h-4 w-4 animate-spin"})]},he.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(hy,{className:"h-4 w-4 text-blue-700"})," LinkedIn"]}),ie.map(he=>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(ai,{checked:m.includes(he.id),onCheckedChange:()=>Y(he.id),disabled:g===he.id}),e.jsxs(Oa,{className:"h-8 w-8",children:[e.jsx(Li,{src:he.profile_picture_url||""}),e.jsx(za,{children:e.jsx(hy,{className:"h-4 w-4"})})]}),e.jsx("span",{className:"flex-1 text-sm font-medium",children:he.platform_username}),g===he.id&&e.jsx(kt,{className:"h-4 w-4 animate-spin"})]},he.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(ci,{className:"h-4 w-4 text-red-600"})," Google Business"]}),ne.map(he=>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(ai,{checked:m.includes(he.id),onCheckedChange:()=>Y(he.id),disabled:g===he.id}),e.jsxs(Oa,{className:"h-8 w-8",children:[e.jsx(Li,{src:he.profile_picture_url||""}),e.jsx(za,{children:e.jsx(ci,{className:"h-4 w-4"})})]}),e.jsx("span",{className:"flex-1 text-sm font-medium",children:he.page_name||he.platform_username}),g===he.id&&e.jsx(kt,{className:"h-4 w-4 animate-spin"})]},he.id))]})]})]}),e.jsxs(Ar,{children:[e.jsx($,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsxs($,{onClick:G,disabled:m.length===0||J,className:"gap-2",children:[J?e.jsx(kt,{className:"h-4 w-4 animate-spin"}):y==="schedule"?e.jsx(Ta,{className:"h-4 w-4"}):e.jsx(Yr,{className:"h-4 w-4"}),y==="schedule"?`Schedule ${m.length} post${m.length!==1?"s":""}`:`Post to ${m.length} account${m.length!==1?"s":""}`]})]})]})})}function Lin(){const{user:s}=vs(),t=(s==null?void 0:s.id)??null,n=Vt(),[r,a]=j.useState(void 0),[i,l]=j.useState("all"),[o,c]=j.useState(null),[d,u]=j.useState(""),[h,m]=j.useState(void 0),[f,g]=j.useState("12"),[x,y]=j.useState("00"),[v,b]=j.useState("PM"),{data:w=[],isLoading:S}=tt({queryKey:["scheduled-posts",t],enabled:!!t,queryFn:async()=>{const{data:ne,error:te}=await q.from("scheduled_posts").select(` *, social_accounts ( page_name, platform_username, profile_picture_url ) `).eq("user_id",t).order("scheduled_for",{ascending:!1});if(te)throw te;return ne}}),C=w.filter(ne=>{if(i!=="all"&&ne.status!==i)return!1;if(r&&ne.scheduled_for){const te=new Date(ne.scheduled_for);if(!nf(te,r))return!1}return!0}),E=w.filter(ne=>ne.scheduled_for).map(ne=>Mg(new Date(ne.scheduled_for))),I=ft({mutationFn:async ne=>{const{error:te}=await q.from("scheduled_posts").update({caption:ne.caption,scheduled_for:ne.scheduled_for}).eq("id",ne.id);if(te)throw te},onSuccess:()=>{re.success("Post updated!"),n.invalidateQueries({queryKey:["scheduled-posts",t]}),c(null)},onError:ne=>{re.error(`Failed to update: ${ne.message}`)}}),P=ft({mutationFn:async ne=>{const{error:te}=await q.from("scheduled_posts").update({status:"cancelled"}).eq("id",ne);if(te)throw te},onSuccess:()=>{re.success("Post cancelled"),n.invalidateQueries({queryKey:["scheduled-posts",t]})},onError:ne=>{re.error(`Failed to cancel: ${ne.message}`)}}),R=ft({mutationFn:async ne=>{const{error:te}=await q.from("scheduled_posts").delete().eq("id",ne);if(te)throw te},onSuccess:()=>{re.success("Post deleted"),n.invalidateQueries({queryKey:["scheduled-posts",t]})},onError:ne=>{re.error(`Failed to delete: ${ne.message}`)}}),D=ft({mutationFn:async ne=>{const{data:te,error:J}=await q.functions.invoke("social-post",{body:{platform:ne.platform,accountId:ne.social_account_id,imageUrl:ne.image_url,caption:ne.caption}});if(J)throw new Error(await Tse(J));if(te!=null&&te.error)throw new Error(te.error);return await q.from("scheduled_posts").update({status:"posted",posted_at:new Date().toISOString(),post_id:te.postId}).eq("id",ne.id),te},onSuccess:ne=>{const te=ne.platform==="facebook"?"Facebook":ne.platform==="instagram"?"Instagram":"LinkedIn";re.success(`Posted to ${te}!`),n.invalidateQueries({queryKey:["scheduled-posts",t]})},onError:ne=>{re.error(`Failed to post: ${ne.message}`)}}),O=ne=>{if(c(ne),u(ne.caption||""),ne.scheduled_for){const te=new Date(ne.scheduled_for);m(te);const J=te.getHours();g(String(J>12?J-12:J===0?12:J)),y(String(te.getMinutes()).padStart(2,"0")),b(J>=12?"PM":"AM")}},U=()=>{if(!o||!h)return;let ne=parseInt(f);const te=parseInt(x);v==="PM"&&ne!==12&&(ne+=12),v==="AM"&&ne===12&&(ne=0);const J=Uzt($zt(h,ne),te);I.mutate({id:o.id,caption:d,scheduled_for:J.toISOString()})},W=ne=>{switch(ne){case"facebook":return e.jsx(Qp,{className:"h-4 w-4 text-blue-600"});case"instagram":return e.jsx(Tf,{className:"h-4 w-4 text-pink-600"});case"linkedin":return e.jsx(hy,{className:"h-4 w-4 text-blue-700"});default:return null}},V=ne=>{switch(ne){case"scheduled":return e.jsxs(Be,{variant:"secondary",className:"gap-1",children:[e.jsx(da,{className:"h-3 w-3"}),"Scheduled"]});case"posted":return e.jsxs(Be,{variant:"default",className:"gap-1 bg-green-600",children:[e.jsx(Nc,{className:"h-3 w-3"}),"Posted"]});case"failed":return e.jsxs(Be,{variant:"destructive",className:"gap-1",children:[e.jsx(ku,{className:"h-3 w-3"}),"Failed"]});case"cancelled":return e.jsxs(Be,{variant:"outline",className:"gap-1 text-muted-foreground",children:[e.jsx(ll,{className:"h-3 w-3"}),"Cancelled"]});default:return e.jsx(Be,{variant:"outline",children:ne})}},G=Array.from({length:12},(ne,te)=>String(te+1)),Y=["00","15","30","45"],X=w.filter(ne=>ne.status==="scheduled").length,ae=w.filter(ne=>ne.status==="posted").length,ie=w.filter(ne=>ne.status==="scheduled"&&ne.scheduled_for&&jIs(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(Ne,{className:"p-4",children:[e.jsx("div",{className:"text-2xl font-bold",children:X}),e.jsx("div",{className:"text-sm text-muted-foreground",children:"Scheduled"})]}),e.jsxs(Ne,{className:"p-4",children:[e.jsx("div",{className:"text-2xl font-bold",children:ie}),e.jsx("div",{className:"text-sm text-muted-foreground",children:"Upcoming"})]}),e.jsxs(Ne,{className:"p-4",children:[e.jsx("div",{className:"text-2xl font-bold",children:ae}),e.jsx("div",{className:"text-sm text-muted-foreground",children:"Posted"})]}),e.jsxs(Ne,{className:"p-4",children:[e.jsx("div",{className:"text-2xl font-bold",children:w.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(Ne,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-4",children:[e.jsx(Kc,{className:"h-5 w-5"}),e.jsx("h3",{className:"font-semibold",children:"Calendar"})]}),e.jsx(D2,{mode:"single",selected:r,onSelect:a,className:Pt("pointer-events-auto"),modifiers:{hasPost:E},modifiersStyles:{hasPost:{fontWeight:"bold",backgroundColor:"hsl(var(--primary) / 0.1)",borderRadius:"50%"}}}),r&&e.jsx($,{variant:"ghost",size:"sm",onClick:()=>a(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(Iw,{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($,{variant:i===ne?"default":"outline",size:"sm",onClick:()=>l(ne),className:"capitalize",children:ne},ne))})]}),S&&e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(kt,{className:"h-8 w-8 animate-spin text-muted-foreground"})}),!S&&C.length===0&&e.jsxs(Ne,{className:"p-8 text-center",children:[e.jsx(Ta,{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:r?`No posts scheduled for ${en(r,"PPP")}`:"Schedule a post from Social Swag to get started!"})]}),e.jsx("div",{className:"space-y-4",children:C.map(ne=>{var te,J;return e.jsx(Ne,{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(Ie,{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:[W(ne.platform),e.jsx("span",{className:"font-medium",children:((te=ne.social_accounts)==null?void 0:te.page_name)||((J=ne.social_accounts)==null?void 0:J.platform_username)||"Unknown"}),V(ne.status)]}),e.jsxs("div",{className:"flex items-center gap-1",children:[ne.status==="scheduled"&&e.jsxs(jk,{children:[e.jsxs(ly,{children:[e.jsx(cy,{asChild:!0,children:e.jsx($,{variant:"ghost",size:"icon",onClick:()=>O(ne),children:e.jsx(gi,{className:"h-4 w-4"})})}),e.jsx(Nx,{children:"Edit post"})]}),e.jsxs(ly,{children:[e.jsx(cy,{asChild:!0,children:e.jsx($,{variant:"ghost",size:"icon",onClick:()=>D.mutate(ne),disabled:D.isPending,children:D.isPending?e.jsx(kt,{className:"h-4 w-4 animate-spin"}):e.jsx(Yr,{className:"h-4 w-4"})})}),e.jsx(Nx,{children:"Post now"})]}),e.jsxs(kc,{children:[e.jsx(jx,{asChild:!0,children:e.jsx($,{variant:"ghost",size:"icon",className:"text-destructive",children:e.jsx(Wn,{className:"h-4 w-4"})})}),e.jsxs(cc,{children:[e.jsxs(dc,{children:[e.jsx(hc,{children:"Cancel this scheduled post?"}),e.jsx(mc,{children:"This will cancel the post. You can delete it entirely or keep it in your history."})]}),e.jsxs(uc,{children:[e.jsx(fc,{children:"Keep"}),e.jsx(tc,{onClick:()=>P.mutate(ne.id),className:"bg-amber-600 hover:bg-amber-700",children:"Cancel Post"}),e.jsx(tc,{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(kc,{children:[e.jsx(jx,{asChild:!0,children:e.jsx($,{variant:"ghost",size:"icon",className:"text-destructive",children:e.jsx(Wn,{className:"h-4 w-4"})})}),e.jsxs(cc,{children:[e.jsxs(dc,{children:[e.jsx(hc,{children:"Delete this post?"}),e.jsx(mc,{children:"This will permanently remove this post from your history."})]}),e.jsxs(uc,{children:[e.jsx(fc,{children:"Cancel"}),e.jsx(tc,{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(da,{className:"h-3 w-3"}),ne.status==="posted"&&ne.posted_at?`Posted ${en(new Date(ne.posted_at),"PPp")}`:ne.scheduled_for?`Scheduled for ${en(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(zs,{open:!!o,onOpenChange:ne=>!ne&&c(null),children:e.jsxs(Os,{className:"max-w-lg",children:[e.jsxs(Us,{children:[e.jsx(Bs,{children:"Edit Scheduled Post"}),e.jsx(Ir,{children:"Update the caption or reschedule this post"})]}),o&&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:o.image_url,alt:"Post preview",className:"h-full w-full object-cover"})}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Caption"}),e.jsx(Rs,{value:d,onChange:ne=>u(ne.target.value),rows:3})]}),e.jsxs("div",{className:"space-y-3 p-4 border rounded-lg",children:[e.jsx(ee,{children:"Schedule for"}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-3",children:[e.jsxs(Yd,{children:[e.jsx(Zd,{asChild:!0,children:e.jsxs($,{variant:"outline",className:Pt("justify-start text-left font-normal flex-1",!h&&"text-muted-foreground"),children:[e.jsx(Ta,{className:"mr-2 h-4 w-4"}),h?en(h,"PPP"):"Pick a date"]})}),e.jsx(Bd,{className:"w-auto p-0",align:"start",children:e.jsx(D2,{mode:"single",selected:h,onSelect:m,disabled:ne=>nee.jsx(Ge,{value:ne,children:ne},ne))})]}),e.jsx("span",{className:"text-muted-foreground",children:":"}),e.jsxs(ms,{value:x,onValueChange:y,children:[e.jsx(us,{className:"w-[70px]",children:e.jsx(fs,{})}),e.jsx(hs,{children:Y.map(ne=>e.jsx(Ge,{value:ne,children:ne},ne))})]}),e.jsxs(ms,{value:v,onValueChange:ne=>b(ne),children:[e.jsx(us,{className:"w-[70px]",children:e.jsx(fs,{})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"AM",children:"AM"}),e.jsx(Ge,{value:"PM",children:"PM"})]})]})]})]})]})]}),e.jsxs(Ar,{children:[e.jsx($,{variant:"outline",onClick:()=>c(null),children:"Cancel"}),e.jsxs($,{onClick:U,disabled:I.isPending,children:[I.isPending?e.jsx(kt,{className:"h-4 w-4 animate-spin mr-2"}):null,"Save Changes"]})]})]})})]})}function Cde(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 tGt={exports:{}};/*! JSZip v3.10.2 - 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(n){s.exports=n()})(function(){return function n(r,a,i){function l(d,u){if(!a[d]){if(!r[d]){var h=typeof Cde=="function"&&Cde;if(!u&&h)return h(d,!0);if(o)return o(d,!0);var m=new Error("Cannot find module '"+d+"'");throw m.code="MODULE_NOT_FOUND",m}var f=a[d]={exports:{}};r[d][0].call(f.exports,function(g){var x=r[d][1][g];return l(x||g)},f,f.exports,n,r,a,i)}return a[d].exports}for(var o=typeof Cde=="function"&&Cde,c=0;c>2,f=(3&d)<<4|u>>4,g=1>6:64,x=2>4,u=(15&m)<<4|(f=o.indexOf(c.charAt(x++)))>>2,h=(3&f)<<6|(g=o.indexOf(c.charAt(x++))),b[y++]=d,f!==64&&(b[y++]=u),g!==64&&(b[y++]=h);return b}},{"./support":30,"./utils":32}],2:[function(n,r,a){var i=n("./external"),l=n("./stream/DataWorker"),o=n("./stream/Crc32Probe"),c=n("./stream/DataLengthProbe");function d(u,h,m,f,g){this.compressedSize=u,this.uncompressedSize=h,this.crc32=m,this.compression=f,this.compressedContent=g}d.prototype={getContentWorker:function(){var u=new l(i.Promise.resolve(this.compressedContent)).pipe(this.compression.uncompressWorker()).pipe(new c("data_length")),h=this;return u.on("end",function(){if(this.streamInfo.data_length!==h.uncompressedSize)throw new Error("Bug : uncompressed data size mismatch")}),u},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(u,h,m){return u.pipe(new o).pipe(new c("uncompressedSize")).pipe(h.compressWorker(m)).pipe(new c("compressedSize")).withStreamInfo("compression",h)},r.exports=d},{"./external":6,"./stream/Crc32Probe":25,"./stream/DataLengthProbe":26,"./stream/DataWorker":27}],3:[function(n,r,a){var i=n("./stream/GenericWorker");a.STORE={magic:"\0\0",compressWorker:function(){return new i("STORE compression")},uncompressWorker:function(){return new i("STORE decompression")}},a.DEFLATE=n("./flate")},{"./flate":7,"./stream/GenericWorker":28}],4:[function(n,r,a){var i=n("./utils"),l=function(){for(var o,c=[],d=0;d<256;d++){o=d;for(var u=0;u<8;u++)o=1&o?3988292384^o>>>1:o>>>1;c[d]=o}return c}();r.exports=function(o,c){return o!==void 0&&o.length?i.getTypeOf(o)!=="string"?function(d,u,h,m){var f=l,g=m+h;d^=-1;for(var x=m;x>>8^f[255&(d^u[x])];return-1^d}(0|c,o,o.length,0):function(d,u,h,m){var f=l,g=m+h;d^=-1;for(var x=m;x>>8^f[255&(d^u.charCodeAt(x))];return-1^d}(0|c,o,o.length,0):0}},{"./utils":32}],5:[function(n,r,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(n,r,a){var i=null;i=typeof Promise<"u"?Promise:n("lie"),r.exports={Promise:i}},{lie:37}],7:[function(n,r,a){var i=typeof Uint8Array<"u"&&typeof Uint16Array<"u"&&typeof Uint32Array<"u",l=n("pako"),o=n("./utils"),c=n("./stream/GenericWorker"),d=i?"uint8array":"array";function u(h,m){c.call(this,"FlateWorker/"+h),this._pako=null,this._pakoAction=h,this._pakoOptions=m,this.meta={}}a.magic="\b\0",o.inherits(u,c),u.prototype.processChunk=function(h){this.meta=h.meta,this._pako===null&&this._createPako(),this._pako.push(o.transformTo(d,h.data),!1)},u.prototype.flush=function(){c.prototype.flush.call(this),this._pako===null&&this._createPako(),this._pako.push([],!0)},u.prototype.cleanUp=function(){c.prototype.cleanUp.call(this),this._pako=null},u.prototype._createPako=function(){this._pako=new l[this._pakoAction]({raw:!0,level:this._pakoOptions.level||-1});var h=this;this._pako.onData=function(m){h.push({data:m,meta:h.meta})}},a.compressWorker=function(h){return new u("Deflate",h)},a.uncompressWorker=function(){return new u("Inflate",{})}},{"./stream/GenericWorker":28,"./utils":32,pako:38}],8:[function(n,r,a){function i(f,g){var x,y="";for(x=0;x>>=8;return y}function l(f,g,x,y,v,b){var w,S,C=f.file,E=f.compression,I=b!==d.utf8encode,P=o.transformTo("string",b(C.name)),R=o.transformTo("string",d.utf8encode(C.name)),D=C.comment,O=o.transformTo("string",b(D)),U=o.transformTo("string",d.utf8encode(D)),W=R.length!==C.name.length,V=U.length!==D.length,G="",Y="",X="",ae=C.dir,ie=C.date,ne={crc32:0,compressedSize:0,uncompressedSize:0};g&&!x||(ne.crc32=f.crc32,ne.compressedSize=f.compressedSize,ne.uncompressedSize=f.uncompressedSize);var te=0;g&&(te|=8),I||!W&&!V||(te|=2048);var J=0,ce=0;ae&&(J|=16),v==="UNIX"?(ce=798,J|=function(he,ue){var ve=he;return he||(ve=ue?16893:33204),(65535&ve)<<16}(C.unixPermissions,ae)):(ce=20,J|=function(he){return 63&(he||0)}(C.dosPermissions)),w=ie.getUTCHours(),w<<=6,w|=ie.getUTCMinutes(),w<<=5,w|=ie.getUTCSeconds()/2,S=ie.getUTCFullYear()-1980,S<<=4,S|=ie.getUTCMonth()+1,S<<=5,S|=ie.getUTCDate(),W&&(Y=i(1,1)+i(u(P),4)+R,G+="up"+i(Y.length,2)+Y),V&&(X=i(1,1)+i(u(O),4)+U,G+="uc"+i(X.length,2)+X);var _e="";return _e+=` \0`,_e+=i(te,2),_e+=E.magic,_e+=i(w,2),_e+=i(S,2),_e+=i(ne.crc32,4),_e+=i(ne.compressedSize,4),_e+=i(ne.uncompressedSize,4),_e+=i(P.length,2),_e+=i(G.length,2),{fileRecord:h.LOCAL_FILE_HEADER+_e+P+G,dirRecord:h.CENTRAL_FILE_HEADER+i(ce,2)+_e+i(O.length,2)+"\0\0\0\0"+i(J,4)+i(y,4)+P+G+O}}var o=n("../utils"),c=n("../stream/GenericWorker"),d=n("../utf8"),u=n("../crc32"),h=n("../signature");function m(f,g,x,y){c.call(this,"ZipFileWorker"),this.bytesWritten=0,this.zipComment=g,this.zipPlatform=x,this.encodeFileName=y,this.streamFiles=f,this.accumulate=!1,this.contentBuffer=[],this.dirRecords=[],this.currentSourceOffset=0,this.entriesCount=0,this.currentFile=null,this._sources=[]}o.inherits(m,c),m.prototype.push=function(f){var g=f.meta.percent||0,x=this.entriesCount,y=this._sources.length;this.accumulate?this.contentBuffer.push(f):(this.bytesWritten+=f.data.length,c.prototype.push.call(this,{data:f.data,meta:{currentFile:this.currentFile,percent:x?(g+100*(x-y-1))/x:100}}))},m.prototype.openedSource=function(f){this.currentSourceOffset=this.bytesWritten,this.currentFile=f.file.name;var g=this.streamFiles&&!f.file.dir;if(g){var x=l(f,g,!1,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);this.push({data:x.fileRecord,meta:{percent:0}})}else this.accumulate=!0},m.prototype.closedSource=function(f){this.accumulate=!1;var g=this.streamFiles&&!f.file.dir,x=l(f,g,!0,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);if(this.dirRecords.push(x.dirRecord),g)this.push({data:function(y){return h.DATA_DESCRIPTOR+i(y.crc32,4)+i(y.compressedSize,4)+i(y.uncompressedSize,4)}(f),meta:{percent:100}});else for(this.push({data:x.fileRecord,meta:{percent:0}});this.contentBuffer.length;)this.push(this.contentBuffer.shift());this.currentFile=null},m.prototype.flush=function(){for(var f=this.bytesWritten,g=0;g=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))}},r.exports=l},{"../utils":32}],19:[function(n,r,a){var i=n("./Uint8ArrayReader");function l(o){i.call(this,o)}n("../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},r.exports=l},{"../utils":32,"./Uint8ArrayReader":21}],20:[function(n,r,a){var i=n("./DataReader");function l(o){i.call(this,o)}n("../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},r.exports=l},{"../utils":32,"./DataReader":18}],21:[function(n,r,a){var i=n("./ArrayReader");function l(o){i.call(this,o)}n("../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},r.exports=l},{"../utils":32,"./ArrayReader":17}],22:[function(n,r,a){var i=n("../utils"),l=n("../support"),o=n("./ArrayReader"),c=n("./StringReader"),d=n("./NodeBufferReader"),u=n("./Uint8ArrayReader");r.exports=function(h){var m=i.getTypeOf(h);return i.checkSupport(m),m!=="string"||l.uint8array?m==="nodebuffer"?new d(h):l.uint8array?new u(i.transformTo("uint8array",h)):new o(i.transformTo("array",h)):new c(h)}},{"../support":30,"../utils":32,"./ArrayReader":17,"./NodeBufferReader":19,"./StringReader":20,"./Uint8ArrayReader":21}],23:[function(n,r,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(n,r,a){var i=n("./GenericWorker"),l=n("../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})},r.exports=o},{"../utils":32,"./GenericWorker":28}],25:[function(n,r,a){var i=n("./GenericWorker"),l=n("../crc32");function o(){i.call(this,"Crc32Probe"),this.withStreamInfo("crc32",0)}n("../utils").inherits(o,i),o.prototype.processChunk=function(c){this.streamInfo.crc32=l(c.data,this.streamInfo.crc32||0),this.push(c)},r.exports=o},{"../crc32":4,"../utils":32,"./GenericWorker":28}],26:[function(n,r,a){var i=n("../utils"),l=n("./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)},r.exports=o},{"../utils":32,"./GenericWorker":28}],27:[function(n,r,a){var i=n("../utils"),l=n("./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(u){d.dataIsReady=!0,d.data=u,d.max=u&&u.length||0,d.type=i.getTypeOf(u),d.isPaused||d._tickAndRepeat()},function(u){d.error(u)})}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}})},r.exports=o},{"../utils":32,"./GenericWorker":28}],28:[function(n,r,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}},r.exports=i},{}],29:[function(n,r,a){var i=n("../utils"),l=n("./ConvertWorker"),o=n("./GenericWorker"),c=n("../base64"),d=n("../support"),u=n("../external"),h=null;if(d.nodestream)try{h=n("../nodejs/NodejsStreamOutputAdapter")}catch{}function m(g,x){return new u.Promise(function(y,v){var b=[],w=g._internalType,S=g._outputType,C=g._mimeType;g.on("data",function(E,I){b.push(E),x&&x(I)}).on("error",function(E){b=[],v(E)}).on("end",function(){try{var E=function(I,P,R){switch(I){case"blob":return i.newBlob(i.transformTo("arraybuffer",P),R);case"base64":return c.encode(P);default:return i.transformTo(I,P)}}(S,function(I,P){var R,D=0,O=null,U=0;for(R=0;R"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=!!n("readable-stream").Readable}catch{a.nodestream=!1}},{"readable-stream":16}],31:[function(n,r,a){for(var i=n("./utils"),l=n("./support"),o=n("./nodejsUtils"),c=n("./stream/GenericWorker"),d=new Array(256),u=0;u<256;u++)d[u]=252<=u?6:248<=u?5:240<=u?4:224<=u?3:192<=u?2:1;d[254]=d[254]=1;function h(){c.call(this,"utf-8 decode"),this.leftOver=null}function m(){c.call(this,"utf-8 encode")}a.utf8encode=function(f){return l.nodebuffer?o.newBufferFrom(f,"utf-8"):function(g){var x,y,v,b,w,S=g.length,C=0;for(b=0;b>>6:(y<65536?x[w++]=224|y>>>12:(x[w++]=240|y>>>18,x[w++]=128|y>>>12&63),x[w++]=128|y>>>6&63),x[w++]=128|63&y);return x}(f)},a.utf8decode=function(f){return l.nodebuffer?i.transformTo("nodebuffer",f).toString("utf-8"):function(g){var x,y,v,b,w=g.length,S=new Array(2*w);for(x=y=0;x>10&1023,S[y++]=56320|1023&v)}return S.length!==y&&(S.subarray?S=S.subarray(0,y):S.length=y),i.applyFromCharCode(S)}(f=i.transformTo(l.uint8array?"uint8array":"array",f))},i.inherits(h,c),h.prototype.processChunk=function(f){var g=i.transformTo(l.uint8array?"uint8array":"array",f.data);if(this.leftOver&&this.leftOver.length){if(l.uint8array){var x=g;(g=new Uint8Array(x.length+this.leftOver.length)).set(this.leftOver,0),g.set(x,this.leftOver.length)}else g=this.leftOver.concat(g);this.leftOver=null}var y=function(b,w){var S;for((w=w||b.length)>b.length&&(w=b.length),S=w-1;0<=S&&(192&b[S])==128;)S--;return S<0||S===0?w:S+d[b[S]]>w?S:w}(g),v=g;y!==g.length&&(l.uint8array?(v=g.subarray(0,y),this.leftOver=g.subarray(y,g.length)):(v=g.slice(0,y),this.leftOver=g.slice(y,g.length))),this.push({data:a.utf8decode(v),meta:f.meta})},h.prototype.flush=function(){this.leftOver&&this.leftOver.length&&(this.push({data:a.utf8decode(this.leftOver),meta:{}}),this.leftOver=null)},a.Utf8DecodeWorker=h,i.inherits(m,c),m.prototype.processChunk=function(f){this.push({data:a.utf8encode(f.data),meta:f.meta})},a.Utf8EncodeWorker=m},{"./nodejsUtils":14,"./stream/GenericWorker":28,"./support":30,"./utils":32}],32:[function(n,r,a){var i=n("./support"),l=n("./base64"),o=n("./nodejsUtils"),c=n("./external");function d(x){return x}function u(x,y){for(var v=0;v>8;this.dir=!!(16&this.externalFileAttributes),f==0&&(this.dosPermissions=63&this.externalFileAttributes),f==3&&(this.unixPermissions=this.externalFileAttributes>>16&65535),this.dir||this.fileNameStr.slice(-1)!=="/"||(this.dir=!0)},parseZIP64ExtraField:function(){if(this.extraFields[1]){var f=i(this.extraFields[1].value);this.uncompressedSize===l.MAX_VALUE_32BITS&&(this.uncompressedSize=f.readInt(8)),this.compressedSize===l.MAX_VALUE_32BITS&&(this.compressedSize=f.readInt(8)),this.localHeaderOffset===l.MAX_VALUE_32BITS&&(this.localHeaderOffset=f.readInt(8)),this.diskNumberStart===l.MAX_VALUE_32BITS&&(this.diskNumberStart=f.readInt(4))}},readExtraFields:function(f){var g,x,y,v=f.index+this.extraFieldsLength;for(this.extraFields||(this.extraFields={});f.index+4>>6:(f<65536?m[y++]=224|f>>>12:(m[y++]=240|f>>>18,m[y++]=128|f>>>12&63),m[y++]=128|f>>>6&63),m[y++]=128|63&f);return m},a.buf2binstring=function(h){return u(h,h.length)},a.binstring2buf=function(h){for(var m=new i.Buf8(h.length),f=0,g=m.length;f>10&1023,b[g++]=56320|1023&x)}return u(b,g)},a.utf8border=function(h,m){var f;for((m=m||h.length)>h.length&&(m=h.length),f=m-1;0<=f&&(192&h[f])==128;)f--;return f<0||f===0?m:f+c[h[f]]>m?f:m}},{"./common":41}],43:[function(n,r,a){r.exports=function(i,l,o,c){for(var d=65535&i|0,u=i>>>16&65535|0,h=0;o!==0;){for(o-=h=2e3>>1:l>>>1;o[c]=l}return o}();r.exports=function(l,o,c,d){var u=i,h=d+c;l^=-1;for(var m=d;m>>8^u[255&(l^o[m])];return-1^l}},{}],46:[function(n,r,a){var i,l=n("../utils/common"),o=n("./trees"),c=n("./adler32"),d=n("./crc32"),u=n("./messages"),h=0,m=4,f=0,g=-2,x=-1,y=4,v=2,b=8,w=9,S=286,C=30,E=19,I=2*S+1,P=15,R=3,D=258,O=D+R+1,U=42,W=113,V=1,G=2,Y=3,X=4;function ae(je,Ae){return je.msg=u[Ae],Ae}function ie(je){return(je<<1)-(4je.avail_out&&(Ce=je.avail_out),Ce!==0&&(l.arraySet(je.output,Ae.pending_buf,Ae.pending_out,Ce,je.next_out),je.next_out+=Ce,Ae.pending_out+=Ce,je.total_out+=Ce,je.avail_out-=Ce,Ae.pending-=Ce,Ae.pending===0&&(Ae.pending_out=0))}function J(je,Ae){o._tr_flush_block(je,0<=je.block_start?je.block_start:-1,je.strstart-je.block_start,Ae),je.block_start=je.strstart,te(je.strm)}function ce(je,Ae){je.pending_buf[je.pending++]=Ae}function _e(je,Ae){je.pending_buf[je.pending++]=Ae>>>8&255,je.pending_buf[je.pending++]=255&Ae}function he(je,Ae){var Ce,qe,ze=je.max_chain_length,$e=je.strstart,ct=je.prev_length,Xe=je.nice_match,it=je.strstart>je.w_size-O?je.strstart-(je.w_size-O):0,at=je.window,Ke=je.w_mask,nt=je.prev,xt=je.strstart+D,rt=at[$e+ct-1],Yt=at[$e+ct];je.prev_length>=je.good_match&&(ze>>=2),Xe>je.lookahead&&(Xe=je.lookahead);do if(at[(Ce=Ae)+ct]===Yt&&at[Ce+ct-1]===rt&&at[Ce]===at[$e]&&at[++Ce]===at[$e+1]){$e+=2,Ce++;do;while(at[++$e]===at[++Ce]&&at[++$e]===at[++Ce]&&at[++$e]===at[++Ce]&&at[++$e]===at[++Ce]&&at[++$e]===at[++Ce]&&at[++$e]===at[++Ce]&&at[++$e]===at[++Ce]&&at[++$e]===at[++Ce]&&$eit&&--ze!=0);return ct<=je.lookahead?ct:je.lookahead}function ue(je){var Ae,Ce,qe,ze,$e,ct,Xe,it,at,Ke,nt=je.w_size;do{if(ze=je.window_size-je.lookahead-je.strstart,je.strstart>=nt+(nt-O)){for(l.arraySet(je.window,je.window,nt,nt,0),je.match_start-=nt,je.strstart-=nt,je.block_start-=nt,Ae=Ce=je.hash_size;qe=je.head[--Ae],je.head[Ae]=nt<=qe?qe-nt:0,--Ce;);for(Ae=Ce=nt;qe=je.prev[--Ae],je.prev[Ae]=nt<=qe?qe-nt:0,--Ce;);ze+=nt}if(je.strm.avail_in===0)break;if(ct=je.strm,Xe=je.window,it=je.strstart+je.lookahead,at=ze,Ke=void 0,Ke=ct.avail_in,at=R)for($e=je.strstart-je.insert,je.ins_h=je.window[$e],je.ins_h=(je.ins_h<=R&&(je.ins_h=(je.ins_h<=R)if(qe=o._tr_tally(je,je.strstart-je.match_start,je.match_length-R),je.lookahead-=je.match_length,je.match_length<=je.max_lazy_match&&je.lookahead>=R){for(je.match_length--;je.strstart++,je.ins_h=(je.ins_h<=R&&(je.ins_h=(je.ins_h<=R&&je.match_length<=je.prev_length){for(ze=je.strstart+je.lookahead-R,qe=o._tr_tally(je,je.strstart-1-je.prev_match,je.prev_length-R),je.lookahead-=je.prev_length-1,je.prev_length-=2;++je.strstart<=ze&&(je.ins_h=(je.ins_h<je.pending_buf_size-5&&(Ce=je.pending_buf_size-5);;){if(je.lookahead<=1){if(ue(je),je.lookahead===0&&Ae===h)return V;if(je.lookahead===0)break}je.strstart+=je.lookahead,je.lookahead=0;var qe=je.block_start+Ce;if((je.strstart===0||je.strstart>=qe)&&(je.lookahead=je.strstart-qe,je.strstart=qe,J(je,!1),je.strm.avail_out===0)||je.strstart-je.block_start>=je.w_size-O&&(J(je,!1),je.strm.avail_out===0))return V}return je.insert=0,Ae===m?(J(je,!0),je.strm.avail_out===0?Y:X):(je.strstart>je.block_start&&(J(je,!1),je.strm.avail_out),V)}),new Se(4,4,8,4,ve),new Se(4,5,16,8,ve),new Se(4,6,32,32,ve),new Se(4,4,16,16,Ee),new Se(8,16,32,32,Ee),new Se(8,16,128,128,Ee),new Se(8,32,128,256,Ee),new Se(32,128,258,1024,Ee),new Se(32,258,258,4096,Ee)],a.deflateInit=function(je,Ae){return Ve(je,Ae,b,15,8,0)},a.deflateInit2=Ve,a.deflateReset=ke,a.deflateResetKeep=Fe,a.deflateSetHeader=function(je,Ae){return je&&je.state?je.state.wrap!==2?g:(je.state.gzhead=Ae,f):g},a.deflate=function(je,Ae){var Ce,qe,ze,$e;if(!je||!je.state||5>8&255),ce(qe,qe.gzhead.time>>16&255),ce(qe,qe.gzhead.time>>24&255),ce(qe,qe.level===9?2:2<=qe.strategy||qe.level<2?4:0),ce(qe,255&qe.gzhead.os),qe.gzhead.extra&&qe.gzhead.extra.length&&(ce(qe,255&qe.gzhead.extra.length),ce(qe,qe.gzhead.extra.length>>8&255)),qe.gzhead.hcrc&&(je.adler=d(je.adler,qe.pending_buf,qe.pending,0)),qe.gzindex=0,qe.status=69):(ce(qe,0),ce(qe,0),ce(qe,0),ce(qe,0),ce(qe,0),ce(qe,qe.level===9?2:2<=qe.strategy||qe.level<2?4:0),ce(qe,3),qe.status=W);else{var ct=b+(qe.w_bits-8<<4)<<8;ct|=(2<=qe.strategy||qe.level<2?0:qe.level<6?1:qe.level===6?2:3)<<6,qe.strstart!==0&&(ct|=32),ct+=31-ct%31,qe.status=W,_e(qe,ct),qe.strstart!==0&&(_e(qe,je.adler>>>16),_e(qe,65535&je.adler)),je.adler=1}if(qe.status===69)if(qe.gzhead.extra){for(ze=qe.pending;qe.gzindex<(65535&qe.gzhead.extra.length)&&(qe.pending!==qe.pending_buf_size||(qe.gzhead.hcrc&&qe.pending>ze&&(je.adler=d(je.adler,qe.pending_buf,qe.pending-ze,ze)),te(je),ze=qe.pending,qe.pending!==qe.pending_buf_size));)ce(qe,255&qe.gzhead.extra[qe.gzindex]),qe.gzindex++;qe.gzhead.hcrc&&qe.pending>ze&&(je.adler=d(je.adler,qe.pending_buf,qe.pending-ze,ze)),qe.gzindex===qe.gzhead.extra.length&&(qe.gzindex=0,qe.status=73)}else qe.status=73;if(qe.status===73)if(qe.gzhead.name){ze=qe.pending;do{if(qe.pending===qe.pending_buf_size&&(qe.gzhead.hcrc&&qe.pending>ze&&(je.adler=d(je.adler,qe.pending_buf,qe.pending-ze,ze)),te(je),ze=qe.pending,qe.pending===qe.pending_buf_size)){$e=1;break}$e=qe.gzindexze&&(je.adler=d(je.adler,qe.pending_buf,qe.pending-ze,ze)),$e===0&&(qe.gzindex=0,qe.status=91)}else qe.status=91;if(qe.status===91)if(qe.gzhead.comment){ze=qe.pending;do{if(qe.pending===qe.pending_buf_size&&(qe.gzhead.hcrc&&qe.pending>ze&&(je.adler=d(je.adler,qe.pending_buf,qe.pending-ze,ze)),te(je),ze=qe.pending,qe.pending===qe.pending_buf_size)){$e=1;break}$e=qe.gzindexze&&(je.adler=d(je.adler,qe.pending_buf,qe.pending-ze,ze)),$e===0&&(qe.status=103)}else qe.status=103;if(qe.status===103&&(qe.gzhead.hcrc?(qe.pending+2>qe.pending_buf_size&&te(je),qe.pending+2<=qe.pending_buf_size&&(ce(qe,255&je.adler),ce(qe,je.adler>>8&255),je.adler=0,qe.status=W)):qe.status=W),qe.pending!==0){if(te(je),je.avail_out===0)return qe.last_flush=-1,f}else if(je.avail_in===0&&ie(Ae)<=ie(Ce)&&Ae!==m)return ae(je,-5);if(qe.status===666&&je.avail_in!==0)return ae(je,-5);if(je.avail_in!==0||qe.lookahead!==0||Ae!==h&&qe.status!==666){var Xe=qe.strategy===2?function(it,at){for(var Ke;;){if(it.lookahead===0&&(ue(it),it.lookahead===0)){if(at===h)return V;break}if(it.match_length=0,Ke=o._tr_tally(it,0,it.window[it.strstart]),it.lookahead--,it.strstart++,Ke&&(J(it,!1),it.strm.avail_out===0))return V}return it.insert=0,at===m?(J(it,!0),it.strm.avail_out===0?Y:X):it.last_lit&&(J(it,!1),it.strm.avail_out===0)?V:G}(qe,Ae):qe.strategy===3?function(it,at){for(var Ke,nt,xt,rt,Yt=it.window;;){if(it.lookahead<=D){if(ue(it),it.lookahead<=D&&at===h)return V;if(it.lookahead===0)break}if(it.match_length=0,it.lookahead>=R&&0it.lookahead&&(it.match_length=it.lookahead)}if(it.match_length>=R?(Ke=o._tr_tally(it,1,it.match_length-R),it.lookahead-=it.match_length,it.strstart+=it.match_length,it.match_length=0):(Ke=o._tr_tally(it,0,it.window[it.strstart]),it.lookahead--,it.strstart++),Ke&&(J(it,!1),it.strm.avail_out===0))return V}return it.insert=0,at===m?(J(it,!0),it.strm.avail_out===0?Y:X):it.last_lit&&(J(it,!1),it.strm.avail_out===0)?V:G}(qe,Ae):i[qe.level].func(qe,Ae);if(Xe!==Y&&Xe!==X||(qe.status=666),Xe===V||Xe===Y)return je.avail_out===0&&(qe.last_flush=-1),f;if(Xe===G&&(Ae===1?o._tr_align(qe):Ae!==5&&(o._tr_stored_block(qe,0,0,!1),Ae===3&&(ne(qe.head),qe.lookahead===0&&(qe.strstart=0,qe.block_start=0,qe.insert=0))),te(je),je.avail_out===0))return qe.last_flush=-1,f}return Ae!==m?f:qe.wrap<=0?1:(qe.wrap===2?(ce(qe,255&je.adler),ce(qe,je.adler>>8&255),ce(qe,je.adler>>16&255),ce(qe,je.adler>>24&255),ce(qe,255&je.total_in),ce(qe,je.total_in>>8&255),ce(qe,je.total_in>>16&255),ce(qe,je.total_in>>24&255)):(_e(qe,je.adler>>>16),_e(qe,65535&je.adler)),te(je),0=Ce.w_size&&($e===0&&(ne(Ce.head),Ce.strstart=0,Ce.block_start=0,Ce.insert=0),at=new l.Buf8(Ce.w_size),l.arraySet(at,Ae,Ke-Ce.w_size,Ce.w_size,0),Ae=at,Ke=Ce.w_size),ct=je.avail_in,Xe=je.next_in,it=je.input,je.avail_in=Ke,je.next_in=0,je.input=Ae,ue(Ce);Ce.lookahead>=R;){for(qe=Ce.strstart,ze=Ce.lookahead-(R-1);Ce.ins_h=(Ce.ins_h<>>=R=P>>>24,w-=R,(R=P>>>16&255)===0)G[u++]=65535&P;else{if(!(16&R)){if(!(64&R)){P=S[(65535&P)+(b&(1<>>=R,w-=R),w<15&&(b+=V[c++]<>>=R=P>>>24,w-=R,!(16&(R=P>>>16&255))){if(!(64&R)){P=C[(65535&P)+(b&(1<>>=R,w-=R,(R=u-h)>3,b&=(1<<(w-=D<<3))-1,i.next_in=c,i.next_out=u,i.avail_in=c>>24&255)+(U>>>8&65280)+((65280&U)<<8)+((255&U)<<24)}function b(){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 w(U){var W;return U&&U.state?(W=U.state,U.total_in=U.total_out=W.total=0,U.msg="",W.wrap&&(U.adler=1&W.wrap),W.mode=g,W.last=0,W.havedict=0,W.dmax=32768,W.head=null,W.hold=0,W.bits=0,W.lencode=W.lendyn=new i.Buf32(x),W.distcode=W.distdyn=new i.Buf32(y),W.sane=1,W.back=-1,m):f}function S(U){var W;return U&&U.state?((W=U.state).wsize=0,W.whave=0,W.wnext=0,w(U)):f}function C(U,W){var V,G;return U&&U.state?(G=U.state,W<0?(V=0,W=-W):(V=1+(W>>4),W<48&&(W&=15)),W&&(W<8||15=X.wsize?(i.arraySet(X.window,W,V-X.wsize,X.wsize,0),X.wnext=0,X.whave=X.wsize):(G<(Y=X.wsize-X.wnext)&&(Y=G),i.arraySet(X.window,W,V-G,Y,X.wnext),(G-=Y)?(i.arraySet(X.window,W,V-G,G,0),X.wnext=G,X.whave=X.wsize):(X.wnext+=Y,X.wnext===X.wsize&&(X.wnext=0),X.whave>>8&255,V.check=o(V.check,$e,2,0),J=te=0,V.mode=2;break}if(V.flags=0,V.head&&(V.head.done=!1),!(1&V.wrap)||(((255&te)<<8)+(te>>8))%31){U.msg="incorrect header check",V.mode=30;break}if((15&te)!=8){U.msg="unknown compression method",V.mode=30;break}if(J-=4,je=8+(15&(te>>>=4)),V.wbits===0)V.wbits=je;else if(je>V.wbits){U.msg="invalid window size",V.mode=30;break}V.dmax=1<>8&1),512&V.flags&&($e[0]=255&te,$e[1]=te>>>8&255,V.check=o(V.check,$e,2,0)),J=te=0,V.mode=3;case 3:for(;J<32;){if(ie===0)break e;ie--,te+=G[X++]<>>8&255,$e[2]=te>>>16&255,$e[3]=te>>>24&255,V.check=o(V.check,$e,4,0)),J=te=0,V.mode=4;case 4:for(;J<16;){if(ie===0)break e;ie--,te+=G[X++]<>8),512&V.flags&&($e[0]=255&te,$e[1]=te>>>8&255,V.check=o(V.check,$e,2,0)),J=te=0,V.mode=5;case 5:if(1024&V.flags){for(;J<16;){if(ie===0)break e;ie--,te+=G[X++]<>>8&255,V.check=o(V.check,$e,2,0)),J=te=0}else V.head&&(V.head.extra=null);V.mode=6;case 6:if(1024&V.flags&&(ie<(he=V.length)&&(he=ie),he&&(V.head&&(je=V.head.extra_len-V.length,V.head.extra||(V.head.extra=new Array(V.head.extra_len)),i.arraySet(V.head.extra,G,X,he,je)),512&V.flags&&(V.check=o(V.check,G,he,X)),ie-=he,X+=he,V.length-=he),V.length))break e;V.length=0,V.mode=7;case 7:if(2048&V.flags){if(ie===0)break e;for(he=0;je=G[X+he++],V.head&&je&&V.length<65536&&(V.head.name+=String.fromCharCode(je)),je&&he>9&1,V.head.done=!0),U.adler=V.check=0,V.mode=12;break;case 10:for(;J<32;){if(ie===0)break e;ie--,te+=G[X++]<>>=7&J,J-=7&J,V.mode=27;break}for(;J<3;){if(ie===0)break e;ie--,te+=G[X++]<>>=1)){case 0:V.mode=14;break;case 1:if(D(V),V.mode=20,W!==6)break;te>>>=2,J-=2;break e;case 2:V.mode=17;break;case 3:U.msg="invalid block type",V.mode=30}te>>>=2,J-=2;break;case 14:for(te>>>=7&J,J-=7&J;J<32;){if(ie===0)break e;ie--,te+=G[X++]<>>16^65535)){U.msg="invalid stored block lengths",V.mode=30;break}if(V.length=65535&te,J=te=0,V.mode=15,W===6)break e;case 15:V.mode=16;case 16:if(he=V.length){if(ie>>=5,J-=5,V.ndist=1+(31&te),te>>>=5,J-=5,V.ncode=4+(15&te),te>>>=4,J-=4,286>>=3,J-=3}for(;V.have<19;)V.lens[ct[V.have++]]=0;if(V.lencode=V.lendyn,V.lenbits=7,Ce={bits:V.lenbits},Ae=d(0,V.lens,0,19,V.lencode,0,V.work,Ce),V.lenbits=Ce.bits,Ae){U.msg="invalid code lengths set",V.mode=30;break}V.have=0,V.mode=19;case 19:for(;V.have>>16&255,Le=65535&ze,!((Ee=ze>>>24)<=J);){if(ie===0)break e;ie--,te+=G[X++]<>>=Ee,J-=Ee,V.lens[V.have++]=Le;else{if(Le===16){for(qe=Ee+2;J>>=Ee,J-=Ee,V.have===0){U.msg="invalid bit length repeat",V.mode=30;break}je=V.lens[V.have-1],he=3+(3&te),te>>>=2,J-=2}else if(Le===17){for(qe=Ee+3;J>>=Ee)),te>>>=3,J-=3}else{for(qe=Ee+7;J>>=Ee)),te>>>=7,J-=7}if(V.have+he>V.nlen+V.ndist){U.msg="invalid bit length repeat",V.mode=30;break}for(;he--;)V.lens[V.have++]=je}}if(V.mode===30)break;if(V.lens[256]===0){U.msg="invalid code -- missing end-of-block",V.mode=30;break}if(V.lenbits=9,Ce={bits:V.lenbits},Ae=d(u,V.lens,0,V.nlen,V.lencode,0,V.work,Ce),V.lenbits=Ce.bits,Ae){U.msg="invalid literal/lengths set",V.mode=30;break}if(V.distbits=6,V.distcode=V.distdyn,Ce={bits:V.distbits},Ae=d(h,V.lens,V.nlen,V.ndist,V.distcode,0,V.work,Ce),V.distbits=Ce.bits,Ae){U.msg="invalid distances set",V.mode=30;break}if(V.mode=20,W===6)break e;case 20:V.mode=21;case 21:if(6<=ie&&258<=ne){U.next_out=ae,U.avail_out=ne,U.next_in=X,U.avail_in=ie,V.hold=te,V.bits=J,c(U,_e),ae=U.next_out,Y=U.output,ne=U.avail_out,X=U.next_in,G=U.input,ie=U.avail_in,te=V.hold,J=V.bits,V.mode===12&&(V.back=-1);break}for(V.back=0;Se=(ze=V.lencode[te&(1<>>16&255,Le=65535&ze,!((Ee=ze>>>24)<=J);){if(ie===0)break e;ie--,te+=G[X++]<>Fe)])>>>16&255,Le=65535&ze,!(Fe+(Ee=ze>>>24)<=J);){if(ie===0)break e;ie--,te+=G[X++]<>>=Fe,J-=Fe,V.back+=Fe}if(te>>>=Ee,J-=Ee,V.back+=Ee,V.length=Le,Se===0){V.mode=26;break}if(32&Se){V.back=-1,V.mode=12;break}if(64&Se){U.msg="invalid literal/length code",V.mode=30;break}V.extra=15&Se,V.mode=22;case 22:if(V.extra){for(qe=V.extra;J>>=V.extra,J-=V.extra,V.back+=V.extra}V.was=V.length,V.mode=23;case 23:for(;Se=(ze=V.distcode[te&(1<>>16&255,Le=65535&ze,!((Ee=ze>>>24)<=J);){if(ie===0)break e;ie--,te+=G[X++]<>Fe)])>>>16&255,Le=65535&ze,!(Fe+(Ee=ze>>>24)<=J);){if(ie===0)break e;ie--,te+=G[X++]<>>=Fe,J-=Fe,V.back+=Fe}if(te>>>=Ee,J-=Ee,V.back+=Ee,64&Se){U.msg="invalid distance code",V.mode=30;break}V.offset=Le,V.extra=15&Se,V.mode=24;case 24:if(V.extra){for(qe=V.extra;J>>=V.extra,J-=V.extra,V.back+=V.extra}if(V.offset>V.dmax){U.msg="invalid distance too far back",V.mode=30;break}V.mode=25;case 25:if(ne===0)break e;if(he=_e-ne,V.offset>he){if((he=V.offset-he)>V.whave&&V.sane){U.msg="invalid distance too far back",V.mode=30;break}ue=he>V.wnext?(he-=V.wnext,V.wsize-he):V.wnext-he,he>V.length&&(he=V.length),ve=V.window}else ve=Y,ue=ae-V.offset,he=V.length;for(neI?(R=ue[ve+y[W]],J[ce+y[W]]):(R=96,0),b=1<>ae)+(w-=b)]=P<<24|R<<16|D|0,w!==0;);for(b=1<>=1;if(b!==0?(te&=b-1,te+=b):te=0,W++,--_e[U]==0){if(U===G)break;U=h[m+y[W]]}if(Y>>7)]}function ce(ze,$e){ze.pending_buf[ze.pending++]=255&$e,ze.pending_buf[ze.pending++]=$e>>>8&255}function _e(ze,$e,ct){ze.bi_valid>v-ct?(ze.bi_buf|=$e<>v-ze.bi_valid,ze.bi_valid+=ct-v):(ze.bi_buf|=$e<>>=1,ct<<=1,0<--$e;);return ct>>>1}function ve(ze,$e,ct){var Xe,it,at=new Array(y+1),Ke=0;for(Xe=1;Xe<=y;Xe++)at[Xe]=Ke=Ke+ct[Xe-1]<<1;for(it=0;it<=$e;it++){var nt=ze[2*it+1];nt!==0&&(ze[2*it]=ue(at[nt]++,nt))}}function Ee(ze){var $e;for($e=0;$e>1;1<=ct;ct--)Fe(ze,at,ct);for(it=xt;ct=ze.heap[1],ze.heap[1]=ze.heap[ze.heap_len--],Fe(ze,at,1),Xe=ze.heap[1],ze.heap[--ze.heap_max]=ct,ze.heap[--ze.heap_max]=Xe,at[2*it]=at[2*ct]+at[2*Xe],ze.depth[it]=(ze.depth[ct]>=ze.depth[Xe]?ze.depth[ct]:ze.depth[Xe])+1,at[2*ct+1]=at[2*Xe+1]=it,ze.heap[1]=it++,Fe(ze,at,1),2<=ze.heap_len;);ze.heap[--ze.heap_max]=ze.heap[1],function(Yt,qt){var ts,ys,Bt,Ft,rs,St,Xs=qt.dyn_tree,vt=qt.max_code,gs=qt.stat_desc.static_tree,Ss=qt.stat_desc.has_stree,Is=qt.stat_desc.extra_bits,Ys=qt.stat_desc.extra_base,cs=qt.stat_desc.max_length,js=0;for(Ft=0;Ft<=y;Ft++)Yt.bl_count[Ft]=0;for(Xs[2*Yt.heap[Yt.heap_max]+1]=0,ts=Yt.heap_max+1;ts>=7;it>>=1)if(1&rt&&nt.dyn_ltree[2*xt]!==0)return l;if(nt.dyn_ltree[18]!==0||nt.dyn_ltree[20]!==0||nt.dyn_ltree[26]!==0)return o;for(xt=32;xt>>3,(at=ze.static_len+3+7>>>3)<=it&&(it=at)):it=at=ct+5,ct+4<=it&&$e!==-1?qe(ze,$e,ct,Xe):ze.strategy===4||at===it?(_e(ze,2+(Xe?1:0),3),ke(ze,O,U)):(_e(ze,4+(Xe?1:0),3),function(nt,xt,rt,Yt){var qt;for(_e(nt,xt-257,5),_e(nt,rt-1,5),_e(nt,Yt-4,4),qt=0;qt>>8&255,ze.pending_buf[ze.d_buf+2*ze.last_lit+1]=255&$e,ze.pending_buf[ze.l_buf+ze.last_lit]=255&ct,ze.last_lit++,$e===0?ze.dyn_ltree[2*ct]++:(ze.matches++,$e--,ze.dyn_ltree[2*(V[ct]+h+1)]++,ze.dyn_dtree[2*J($e)]++),ze.last_lit===ze.lit_bufsize-1},a._tr_align=function(ze){_e(ze,2,3),he(ze,w,O),function($e){$e.bi_valid===16?(ce($e,$e.bi_buf),$e.bi_buf=0,$e.bi_valid=0):8<=$e.bi_valid&&($e.pending_buf[$e.pending++]=255&$e.bi_buf,$e.bi_buf>>=8,$e.bi_valid-=8)}(ze)}},{"../utils/common":41}],53:[function(n,r,a){r.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(n,r,a){(function(i){(function(l,o){if(!l.setImmediate){var c,d,u,h,m=1,f={},g=!1,x=l.document,y=Object.getPrototypeOf&&Object.getPrototypeOf(l);y=y&&y.setTimeout?y:l,c={}.toString.call(l.process)==="[object process]"?function(S){process.nextTick(function(){b(S)})}:function(){if(l.postMessage&&!l.importScripts){var S=!0,C=l.onmessage;return l.onmessage=function(){S=!1},l.postMessage("","*"),l.onmessage=C,S}}()?(h="setImmediate$"+Math.random()+"$",l.addEventListener?l.addEventListener("message",w,!1):l.attachEvent("onmessage",w),function(S){l.postMessage(h+S,"*")}):l.MessageChannel?((u=new MessageChannel).port1.onmessage=function(S){b(S.data)},function(S){u.port2.postMessage(S)}):x&&"onreadystatechange"in x.createElement("script")?(d=x.documentElement,function(S){var C=x.createElement("script");C.onreadystatechange=function(){b(S),C.onreadystatechange=null,d.removeChild(C),C=null},d.appendChild(C)}):function(S){setTimeout(b,0,S)},y.setImmediate=function(S){typeof S!="function"&&(S=new Function(""+S));for(var C=new Array(arguments.length-1),E=0;E"u"?i===void 0?this:i:self)}).call(this,typeof Sp<"u"?Sp:typeof self<"u"?self:typeof window<"u"?window:{})},{}]},{},[10])(10)})})(tGt);var Rin=tGt.exports;const sGt=au(Rin);function BBe(s,t=400,n=75){return s&&`${s.replace("/storage/v1/object/public/","/storage/v1/render/image/public/")}?width=${t}&quality=${n}&resize=contain`}const nGt=({embedded:s=!1,onCompose:t}={})=>{const{isAdmin:n}=vs(),[r,a]=j.useState(null),[i,l]=j.useState(null),[o,c]=j.useState("all"),[d,u]=j.useState(new Set),[h,m]=j.useState(!1),[f,g]=j.useState(!1),[x,y]=j.useState("images"),[v,b]=j.useState(null),{data:w=[],isLoading:S}=tt({queryKey:["social-swag-2"],queryFn:async()=>{const{data:J,error:ce}=await q.from("social_swag_2").select("*").order("month",{ascending:!1}).order("sort_order");if(ce)throw ce;return J}}),{data:C=[]}=tt({queryKey:["social-swag-2-months"],queryFn:async()=>{const{data:J,error:ce}=await q.from("social_swag_2_months").select("*").order("month",{ascending:!1});if(ce)throw ce;return J}}),{data:E=[]}=tt({queryKey:["social-swag-2-reels"],queryFn:async()=>{const{data:J,error:ce}=await q.from("social_swag_2_reels").select("*").order("month",{ascending:!1});if(ce)throw ce;return J}}),{data:I=[]}=tt({queryKey:["my-social-accounts-count"],queryFn:async()=>{const{data:J,error:ce}=await q.from("social_accounts").select("id, platform").eq("is_active",!0);if(ce)throw ce;return J||[]}}),P=I.length>0,R=j.useMemo(()=>o==="all"?null:E.find(J=>J.month===o)||null,[o,E]),D=j.useMemo(()=>[...new Set(w.map(ce=>ce.month))].sort((ce,_e)=>_e.localeCompare(ce)),[w]);j.useEffect(()=>{D.length>0&&o==="all"&&c(D[0])},[D,o]);const O=J=>{try{const ce=Ltt(J,"yyyy-MM",new Date);return en(ce,"MMMM yyyy")}catch{return J}},U=j.useMemo(()=>o==="all"?w:w.filter(J=>J.month===o),[o,w]),W=j.useMemo(()=>{var J;return o==="all"?null:((J=C.find(ce=>ce.month===o))==null?void 0:J.canva_link)||null},[o,C]),V=async J=>{try{await navigator.clipboard.writeText(J),re.success("Caption copied to clipboard!")}catch{re.error("Failed to copy caption")}},G=async(J,ce)=>{try{const he=await(await fetch(J)).blob(),ue=/iPhone|iPad|iPod|Android/i.test(navigator.userAgent),ve=navigator.canShare&&navigator.canShare({files:[new File([he],"test.jpg",{type:"image/jpeg"})]});if(ue&&ve){const Ee=new File([he],`social-swag-${ce}.jpg`,{type:"image/jpeg"});await navigator.share({files:[Ee],title:"Social Swag Image"}),re.success("Image ready to save!")}else{const Ee=window.URL.createObjectURL(he),Se=document.createElement("a");Se.href=Ee,Se.download=`social-swag-${ce}.jpg`,document.body.appendChild(Se),Se.click(),document.body.removeChild(Se),window.URL.revokeObjectURL(Ee),re.success("Image downloaded!")}}catch(_e){_e.name!=="AbortError"&&re.error("Failed to download image")}},Y=J=>{u(ce=>{const _e=new Set(ce);return _e.has(J)?_e.delete(J):_e.add(J),_e})},X=()=>{u(new Set(U.map(J=>J.id)))},ae=()=>{u(new Set),m(!1)},ie=async()=>{const J=U.filter(ce=>d.has(ce.id));if(J.length===0){re.error("No images selected");return}g(!0),re.info(`Preparing ${J.length} images for download...`);try{const ce=new sGt,_e=[...J].sort((Se,Le)=>Se.sort_order-Le.sort_order);for(let Se=0;Se<_e.length;Se++){const Le=_e[Se];try{const Fe=await fetch(Le.image_url),ke=await Fe.blob(),Ve=Fe.headers.get("content-type")||"image/jpeg",je=Ve.includes("png")?"png":Ve.includes("webp")?"webp":"jpg",Ae=`${Se+1}.${je}`;ce.file(Ae,ke)}catch{console.error("Failed to fetch image:",Le.id)}}const he=o!=="all"?O(o):"Social Swag",ue=await ce.generateAsync({type:"blob"}),ve=window.URL.createObjectURL(ue),Ee=document.createElement("a");Ee.href=ve,Ee.download=`${he}.zip`,document.body.appendChild(Ee),Ee.click(),document.body.removeChild(Ee),window.URL.revokeObjectURL(ve),re.success(`Downloaded ${_e.length} images as "${he}.zip"!`)}catch(ce){console.error("Failed to create ZIP:",ce),re.error("Failed to create download package")}g(!1),ae()},ne=J=>{h?Y(J.id):a(J)},te=({children:J})=>s?e.jsx(e.Fragment,{children:J}):e.jsx(Vs,{title:"Social Swag 2.0",children:J});return e.jsx(te,{children:e.jsxs("div",{className:"space-y-8",children:[!s&&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(Be,{variant:"secondary",className:"bg-white/20 text-white border-0 backdrop-blur-sm",children:[e.jsx(Nn,{className:"h-3 w-3 mr-1"}),"New content monthly"]}),e.jsxs(Be,{variant:"secondary",className:"bg-white/20 text-white border-0 backdrop-blur-sm",children:[e.jsx(Mc,{className:"h-3 w-3 mr-1"}),w.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(ha,{defaultValue:"gallery",className:"space-y-6",children:[!s&&e.jsxs(ma,{className:"grid w-full max-w-md grid-cols-2",children:[e.jsxs(Zt,{value:"gallery",className:"gap-2",children:[e.jsx(Mc,{className:"h-4 w-4"}),"Gallery"]}),e.jsxs(Zt,{value:"scheduled",className:"gap-2",children:[e.jsx(Kc,{className:"h-4 w-4"}),"Scheduled"]})]}),e.jsxs(Xt,{value:"gallery",className:"space-y-6",children:[P?e.jsx(Ne,{className:"border rounded-xl",children:e.jsx(Ie,{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($,{variant:"outline",size:"sm",asChild:!0,className:"gap-2",children:e.jsx(wr,{to:"/mission-control/integrations",children:"Manage Accounts"})})]})})}):e.jsx(Ne,{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(Ie,{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(Qp,{className:"h-5 w-5 text-blue-600"})}),e.jsx("div",{className:"p-2 rounded-full bg-pink-500/10",children:e.jsx(Tf,{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($,{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(wr,{to:"/social-connections",children:[e.jsx(bd,{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:D.map(J=>e.jsx("button",{onClick:()=>c(J),className:Pt("px-4 py-2 rounded-full text-sm font-medium transition-all",o===J?"bg-primary text-primary-foreground shadow-sm":"bg-muted text-muted-foreground hover:text-foreground"),children:O(J)},J))}),o!=="all"&&(W?e.jsxs("a",{href:W,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 ",O(o)," 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 ",O(o)," 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:()=>{y("images"),ae()},className:Pt("flex items-center gap-2 px-4 py-2 rounded-full text-sm font-medium transition-all",x==="images"?"bg-background text-foreground shadow-sm":"text-muted-foreground hover:text-foreground"),children:[e.jsx(Mc,{className:"h-4 w-4"}),"Images"]}),e.jsxs("button",{onClick:()=>{y("reels"),ae()},className:Pt("flex items-center gap-2 px-4 py-2 rounded-full text-sm font-medium transition-all",x==="reels"?"bg-background text-foreground shadow-sm":"text-muted-foreground hover:text-foreground"),children:[e.jsx(rf,{className:"h-4 w-4"}),"Reels"]})]}),x==="images"&&e.jsx("div",{className:"flex flex-wrap items-center gap-3",children:h?e.jsxs(e.Fragment,{children:[e.jsxs($,{variant:"outline",size:"sm",onClick:X,className:"gap-2",children:["Select All (",U.length,")"]}),e.jsxs($,{variant:"outline",size:"sm",onClick:ae,className:"gap-2",children:[e.jsx(gr,{className:"h-4 w-4"}),"Cancel"]}),d.size>0&&e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs($,{size:"sm",onClick:ie,disabled:f,className:"gap-2",children:[e.jsx(di,{className:"h-4 w-4"}),f?"Downloading...":`Download ${d.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($,{variant:"outline",size:"sm",onClick:()=>m(!0),className:"gap-2",children:[e.jsx(la,{className:"h-4 w-4"}),"Select Images"]})})]}),S&&e.jsx("div",{className:"text-center py-12 text-muted-foreground",children:"Loading..."}),!S&&x==="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:U.map(J=>{const ce=d.has(J.id);return e.jsx(Ne,{className:Pt("group cursor-pointer overflow-hidden border-0 shadow-md hover:shadow-xl transition-all duration-300 rounded-2xl",h&&ce&&"ring-2 ring-primary ring-offset-2"),onClick:()=>ne(J),children:e.jsxs("div",{className:"relative aspect-[4/5] overflow-hidden",children:[e.jsx("img",{src:BBe(J.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"}),J.post_date&&!h&&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:en(new Date(J.post_date+"T00:00:00"),"MMM d")})}),h&&e.jsx("div",{className:Pt("absolute top-2 right-2 w-6 h-6 rounded-full border-2 flex items-center justify-center transition-all",ce?"bg-primary border-primary text-primary-foreground":"bg-white/80 border-muted-foreground/50"),children:ce&&e.jsx(la,{className:"h-4 w-4"})}),!h&&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"})})]})},J.id)})}),U.length===0&&e.jsxs("div",{className:"text-center py-12",children:[e.jsx(Mc,{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."})]})]}),!S&&x==="reels"&&e.jsx(e.Fragment,{children:R?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(Ne,{className:"group overflow-hidden rounded-2xl cursor-pointer transition-all duration-300 hover:shadow-xl hover:scale-[1.02]",onClick:()=>l(R),children:e.jsxs("div",{className:"relative aspect-[9/16] overflow-hidden",children:[e.jsx("img",{src:BBe(R.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(Be,{variant:"secondary",className:"bg-black/50 text-white border-0 backdrop-blur-sm text-xs",children:[e.jsx(rf,{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(rf,{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(zs,{open:!!r,onOpenChange:()=>a(null),children:e.jsx(Os,{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-muted",children:e.jsx("div",{className:"aspect-[4/5]",children:e.jsx("img",{src:BBe(r.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(Ta,{className:"h-4 w-4"}),en(new Date(r.created_at),"MMMM d, yyyy")]}),r.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(Ta,{className:"h-3.5 w-3.5"}),"Post on ",en(new Date(r.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:r.caption})})]}),e.jsxs("div",{className:"flex flex-col gap-3 mt-6",children:[e.jsxs($,{onClick:()=>{if(t){t({mediaUrl:r.image_url,mediaType:"image",caption:r.caption,swagItemId:r.id}),a(null);return}b({imageUrl:r.image_url,imageId:r.id,caption:r.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(Yr,{className:"h-4 w-4"}),"Create Post"]}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-3",children:[e.jsxs($,{variant:"outline",onClick:()=>V(r.caption),className:"flex-1 gap-2",children:[e.jsx(Ha,{className:"h-4 w-4"}),"Copy Caption"]}),e.jsxs($,{variant:"outline",onClick:()=>G(r.image_url,r.id),className:"flex-1 gap-2",children:[e.jsx(di,{className:"h-4 w-4"}),"Download"]})]})]})]})]})})})}),e.jsx(zs,{open:!!i,onOpenChange:()=>l(null),children:e.jsx(Os,{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:i&&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:i.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(rf,{className:"h-4 w-4"}),"Monthly Reel"]}),i.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:i.caption})})]}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-3 mt-6",children:[i.caption&&e.jsxs($,{onClick:()=>V(i.caption||""),className:"flex-1 gap-2",children:[e.jsx(Ha,{className:"h-4 w-4"}),"Copy Caption"]}),i.canva_link&&e.jsxs($,{variant:"outline",onClick:()=>window.open(i.canva_link,"_blank"),className:"flex-1 gap-2",children:[e.jsx(kr,{className:"h-4 w-4"}),"Open in Canva"]})]})]})]})})})}),e.jsx(Iin,{open:!!v,onOpenChange:J=>!J&&b(null),imageUrl:(v==null?void 0:v.imageUrl)||"",imageId:(v==null?void 0:v.imageId)||"",defaultCaption:(v==null?void 0:v.caption)||"",swagItemId:v==null?void 0:v.imageId})]}),e.jsx(Xt,{value:"scheduled",children:e.jsx(Lin,{})})]})]})})};async function hL(s){var r,a;const{data:t,error:n}=await q.functions.invoke("canva-mail-studio",{body:s});if(n){let i=n.message;try{const l=await((a=(r=n.context)==null?void 0:r.json)==null?void 0:a.call(r));l!=null&&l.error&&(i=l.error)}catch{}throw new Error(i)}if(t!=null&&t.error)throw new Error(t.error);return t}function wrt(){return tt({queryKey:["canva-agent-status"],queryFn:()=>hL({action:"status"})})}class $Be extends Error{constructor(){super("Canva connection was cancelled — nothing was connected.")}}function rGt(){const s=Vt();return ft({mutationFn:async t=>{const n=window.open("about:blank","canva-connect","width=620,height=760");let r=!1;try{r=!!(await hL({action:"status"})).connected}catch{}let a,i;try{({authUrl:a,state:i}=await hL({action:"start",...t!=null&&t.client?{client:t.client}:{}}))}catch(l){throw n==null||n.close(),l}if(localStorage.setItem("canva_oauth_state",i),localStorage.setItem("canva_oauth_mode","agent"),localStorage.removeItem("canva_code_verifier"),!n){window.location.assign(a);return}n.location.href=a,await new Promise((l,o)=>{const c=h=>{if(h.origin!==window.location.origin)return;const m=h.data;(m==null?void 0:m.type)==="canva-oauth-success"&&(u(),l()),(m==null?void 0:m.type)==="canva-oauth-error"&&(u(),o(new Error(m.message||"Canva connection failed")))},d=setInterval(async()=>{if(n.closed){u();try{(await hL({action:"status"})).connected&&!r?l():o(new $Be)}catch{o(new $Be)}}},800),u=()=>{clearInterval(d),window.removeEventListener("message",c)};window.addEventListener("message",c)})},onSuccess:()=>re.success("Canva connected"),onSettled:()=>s.invalidateQueries({queryKey:["canva-agent-status"]}),onError:t=>t instanceof $Be?re.info(t.message):re.error(t.message)})}function aGt(){const s=Vt();return ft({mutationFn:()=>hL({action:"disconnect"}),onSuccess:()=>{re.success("Canva disconnected"),s.invalidateQueries({queryKey:["canva-agent-status"]}),s.removeQueries({queryKey:["canva-agent-designs"]})},onError:t=>re.error(t.message)})}function Din(s,t){return rFt({queryKey:["canva-agent-designs",t],enabled:s,initialPageParam:null,queryFn:({pageParam:n})=>hL({action:"list_designs",query:t,continuation:n}),getNextPageParam:n=>n.continuation})}function Fin(s){return tt({queryKey:["canva-agent-design",s],enabled:!!s,queryFn:()=>hL({action:"get_design",design_id:s})})}function Oin(){const s=Vt();return ft({mutationFn:t=>hL({action:"import_design",design_id:t.designId,workflow:t.workflow,format:t.format,pages:t.pages,width:t.width,height:t.height}),onSuccess:()=>s.invalidateQueries({queryKey:["canva-imports"]}),onError:t=>re.error(t.message)})}const zin={postcard:"https://www.canva.com/create/postcards/",letter:"https://www.canva.com/create/letterheads/",library:"https://www.canva.com/",image:"https://www.canva.com/",social:"https://www.canva.com/create/social-media-graphics/"};function iGt({open:s,onOpenChange:t,mode:n="postcard",workflow:r="mail_studio",exportSize:a,onImported:i}){var O,U,W,V,G,Y,X,ae;const l=wrt(),o=rGt(),c=aGt(),d=!!((O=l.data)!=null&&O.connected),[u,h]=j.useState(""),[m,f]=j.useState(""),[g,x]=j.useState(null),[y,v]=j.useState([]),b=Din(s&&d,m),w=Fin(g),S=Oin(),[C,E]=j.useState("jpg");j.useEffect(()=>{s||(x(null),v([]))},[s]),j.useEffect(()=>{const ie=setTimeout(()=>f(u.trim()),400);return()=>clearTimeout(ie)},[u]),j.useEffect(()=>{w.data&&v(w.data.pages.length===1?[w.data.pages[0].index]:[])},[w.data]);const I=ie=>{if(n==="postcard"||n==="image"){v([ie]);return}v(ne=>ne.includes(ie)?ne.filter(te=>te!==ie):[...ne,ie].sort((te,J)=>te-J))},P=async()=>{if(!g||!y.length)return;const ie=await S.mutateAsync({designId:g,workflow:r,pages:y,format:n==="letter"?"pdf":n==="social"?C:"png",...n!=="letter"&&a?a:{}}).catch(()=>null);ie&&(await i(ie),t(!1))},R=(((U=b.data)==null?void 0:U.pages)||[]).flatMap(ie=>ie.designs),D=((W=w.data)==null?void 0:W.pages.length)||0;return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Os,{className:"max-h-[88vh] max-w-3xl overflow-y-auto",children:[e.jsxs(Us,{children:[e.jsx(Bs,{children:g?((V=w.data)==null?void 0:V.design.title)||"Choose pages":"Import from Canva"}),e.jsx(Ir,{children:d?g?n==="postcard"?"Choose the page to print on the front. thanks.io prints the back from your message, so a back page isn’t used.":n==="image"?"Choose the page to place in your design.":n==="letter"?"Choose the pages to mail. They’re saved as one PDF.":n==="social"?"Choose the pages to add to your media library. Nothing is posted until you schedule or publish it yourself.":"Choose the pages to save to LevelUp.":"Search your designs. Edit in Canva, then come back and refresh to bring in the latest version.":"Connect your own Canva account once, then bring your designs into LevelUp."})]}),l.isLoading&&e.jsx(kt,{className:"mx-auto h-5 w-5 animate-spin"}),l.error&&e.jsx("p",{className:"text-sm text-destructive",children:l.error.message}),l.data&&!l.data.configured&&e.jsx("p",{className:"rounded border border-dashed p-6 text-center text-sm text-muted-foreground",children:"The Canva connection isn't set up for LevelUp yet. Ask an admin to finish the Canva app setup."}),((G=l.data)==null?void 0:G.configured)&&!d&&e.jsxs("div",{className:"space-y-3 py-4 text-center",children:[l.data.needs_reconnect&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"Your Canva connection needs to be renewed."}),e.jsxs($,{onClick:()=>o.mutate({}),disabled:o.isPending,children:[o.isPending?e.jsx(kt,{className:"mr-1 h-4 w-4 animate-spin"}):e.jsx(bd,{className:"mr-1 h-4 w-4"}),"Connect Canva"]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"A Canva window opens so you can approve read-only access to your designs."})]}),d&&!g&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2 text-xs text-muted-foreground",children:[e.jsxs("span",{children:["Connected",(Y=l.data)!=null&&Y.display_name?` as ${l.data.display_name}`:""]}),e.jsxs("div",{className:"flex gap-1",children:[e.jsxs($,{variant:"ghost",size:"sm",onClick:()=>b.refetch(),disabled:b.isFetching,children:[e.jsx(ro,{className:`mr-1 h-3.5 w-3.5 ${b.isFetching?"animate-spin":""}`}),"Refresh"]}),e.jsx($,{variant:"ghost",size:"sm",asChild:!0,children:e.jsxs("a",{href:zin[n],target:"_blank",rel:"noreferrer",children:[e.jsx(kr,{className:"mr-1 h-3.5 w-3.5"}),"New design in Canva"]})}),e.jsxs($,{variant:"ghost",size:"sm",onClick:()=>c.mutate(),disabled:c.isPending,children:[e.jsx($E,{className:"mr-1 h-3.5 w-3.5"}),"Disconnect"]})]})]}),e.jsxs("div",{className:"relative",children:[e.jsx(Kr,{className:"absolute left-2.5 top-2.5 h-4 w-4 text-muted-foreground"}),e.jsx(pe,{value:u,onChange:ie=>h(ie.target.value),placeholder:"Search your Canva designs",className:"pl-8"})]}),b.isLoading&&e.jsx(kt,{className:"mx-auto h-5 w-5 animate-spin"}),b.error&&e.jsx("p",{className:"text-sm text-destructive",children:b.error.message}),!b.isLoading&&!b.error&&R.length===0&&e.jsx("p",{className:"rounded border border-dashed p-6 text-center text-sm text-muted-foreground",children:m?"No designs match that search.":"No designs found in your Canva account yet."}),e.jsx("div",{className:"grid gap-3 sm:grid-cols-3",children:R.map(ie=>e.jsxs("div",{className:"overflow-hidden rounded-lg border bg-card",children:[e.jsx("button",{type:"button",onClick:()=>x(ie.id),className:"block w-full text-left transition hover:opacity-90",children:ie.thumbnail?e.jsx("img",{src:ie.thumbnail,alt:ie.title,className:"h-28 w-full object-cover"}):e.jsx("div",{className:"h-28 w-full bg-muted"})}),e.jsxs("div",{className:"flex items-center justify-between gap-1 p-2",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"truncate text-xs font-medium",children:ie.title}),ie.page_count&&ie.page_count>1&&e.jsxs("p",{className:"text-[11px] text-muted-foreground",children:[ie.page_count," pages"]})]}),ie.edit_url&&e.jsx("a",{href:ie.edit_url,target:"_blank",rel:"noreferrer",className:"shrink-0 text-muted-foreground hover:text-primary",title:"Edit in Canva",children:e.jsx(kr,{className:"h-3.5 w-3.5"})})]})]},ie.id))}),b.hasNextPage&&e.jsxs($,{variant:"outline",size:"sm",className:"mx-auto flex",onClick:()=>b.fetchNextPage(),disabled:b.isFetchingNextPage,children:[b.isFetchingNextPage&&e.jsx(kt,{className:"mr-1 h-4 w-4 animate-spin"}),"Load more"]})]}),d&&g&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[e.jsxs($,{variant:"ghost",size:"sm",onClick:()=>x(null),children:[e.jsx(qa,{className:"mr-1 h-4 w-4"}),"All designs"]}),e.jsxs("div",{className:"flex gap-1",children:[e.jsxs($,{variant:"ghost",size:"sm",onClick:()=>w.refetch(),disabled:w.isFetching,children:[e.jsx(ro,{className:`mr-1 h-3.5 w-3.5 ${w.isFetching?"animate-spin":""}`}),"Refresh"]}),((X=w.data)==null?void 0:X.design.edit_url)&&e.jsx($,{variant:"outline",size:"sm",asChild:!0,children:e.jsxs("a",{href:w.data.design.edit_url,target:"_blank",rel:"noreferrer",children:[e.jsx(kr,{className:"mr-1 h-3.5 w-3.5"}),"Edit in Canva"]})})]})]}),w.isLoading&&e.jsx(kt,{className:"mx-auto h-5 w-5 animate-spin"}),w.error&&e.jsx("p",{className:"text-sm text-destructive",children:w.error.message}),n==="postcard"&&D>1&&e.jsxs("p",{className:"flex items-start gap-1.5 rounded-md bg-muted p-2 text-xs text-muted-foreground",children:[e.jsx(wl,{className:"mt-0.5 h-3.5 w-3.5 shrink-0"}),"This design has ",D," pages. Only the page you choose is printed on the front."]}),e.jsx("div",{className:"grid grid-cols-2 gap-3 sm:grid-cols-4",children:(((ae=w.data)==null?void 0:ae.pages)||[]).map(ie=>{const ne=y.includes(ie.index);return e.jsxs("button",{type:"button",onClick:()=>I(ie.index),"aria-pressed":ne,className:`relative overflow-hidden rounded-lg border-2 text-left transition ${ne?"border-primary shadow-md":"border-border hover:border-primary/50"}`,children:[ie.thumbnail?e.jsx("img",{src:ie.thumbnail,alt:`Page ${ie.index}`,className:"h-28 w-full bg-muted object-contain"}):e.jsxs("div",{className:"flex h-28 w-full items-center justify-center bg-muted text-xs text-muted-foreground",children:["Page ",ie.index]}),e.jsxs("div",{className:"flex items-center justify-between p-1.5 text-xs",children:[e.jsxs("span",{children:["Page ",ie.index]}),ne&&e.jsxs(Be,{className:"h-5 gap-0.5 px-1.5 text-[10px]",children:[e.jsx(la,{className:"h-3 w-3"}),n==="postcard"?"Front":"Selected"]})]})]},ie.index)})}),e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2 border-t pt-3",children:[n==="social"&&e.jsx("div",{className:"flex items-center gap-1 text-xs",children:["jpg","png"].map(ie=>e.jsx($,{type:"button",size:"sm",variant:C===ie?"default":"outline",className:"h-7 px-2",onClick:()=>E(ie),children:ie.toUpperCase()},ie))}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[n==="social"?`${C.toUpperCase()}, up to 8 MB per image${C==="png"?" (Instagram needs JPG)":" — works on every platform"}.`:n==="letter"?"Saved as an 8.5×11 PDF.":a?`Exported at ${a.width}×${a.height} px.`:"Exported as full-quality PNG."," A permanent copy is saved in LevelUp."]}),e.jsx($,{onClick:P,disabled:!y.length||S.isPending,children:S.isPending?e.jsxs(e.Fragment,{children:[e.jsx(kt,{className:"mr-1 h-4 w-4 animate-spin"}),"Bringing it over…"]}):n==="postcard"?"Use as front":n==="image"?"Use this page":`Bring in ${y.length||""} page${y.length===1?"":"s"}`})]})]})]})})}const E_t={facebook:{id:"facebook",label:"Facebook Page",icon:Qp,dot:"bg-blue-500",chip:"bg-blue-500/10 text-blue-600 border-blue-500/20",captionLimit:63206,supportsVideo:!0,requiresMedia:!1},instagram:{id:"instagram",label:"Instagram",icon:Tf,dot:"bg-pink-500",chip:"bg-pink-500/10 text-pink-600 border-pink-500/20",captionLimit:2200,supportsVideo:!0,requiresMedia:!0},linkedin:{id:"linkedin",label:"LinkedIn",icon:hy,dot:"bg-sky-600",chip:"bg-sky-600/10 text-sky-700 border-sky-600/20",captionLimit:3e3,supportsVideo:!1,requiresMedia:!1},google_business:{id:"google_business",label:"Google Business",icon:ci,dot:"bg-emerald-600",chip:"bg-emerald-600/10 text-emerald-700 border-emerald-600/20",captionLimit:1500,supportsVideo:!1,requiresMedia:!1}},$4=s=>E_t[s]??E_t.facebook,Bin=[{label:"Morning · 8:00 AM",hour:8,minute:0},{label:"Lunch · 12:00 PM",hour:12,minute:0},{label:"Afternoon · 3:00 PM",hour:15,minute:0},{label:"Evening · 7:00 PM",hour:19,minute:0}],T_t="agent-uploads",$in="social-studio",Uin=200*1024*1024,M_t=s=>typeof s=="number"?new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(s):"";function qin({onSelect:s}){const{user:t}=vs(),n=j.useRef(null),[r,a]=j.useState(!1),[i,l]=j.useState(!1),o=Vt(),{data:c=[]}=tt({queryKey:["studio-uploads",t==null?void 0:t.id],enabled:!!(t!=null&&t.id),queryFn:async()=>{const{data:m,error:f}=await q.from("social_media_assets").select("*").eq("user_id",t.id).order("created_at",{ascending:!1}).limit(60);if(f)throw f;return m??[]}}),{data:d=[]}=tt({queryKey:["studio-swag"],queryFn:async()=>{const{data:m,error:f}=await q.from("social_swag_2").select("id, image_url, caption, month").order("month",{ascending:!1}).order("sort_order").limit(120);if(f)throw f;return m??[]}}),{data:u=[]}=tt({queryKey:["studio-listings",t==null?void 0:t.id],enabled:!!(t!=null&&t.id),queryFn:async()=>{const{data:m,error:f}=await q.from("listings").select("id, property_address, city, state, price, bedrooms, bathrooms, square_footage, status, listing_photos(photo_url, sort_order, is_primary)").eq("agent_id",t.id).order("created_at",{ascending:!1}).limit(40);if(f)throw f;return m??[]}}),h=async m=>{if(!(t!=null&&t.id))return;if(m.size>Uin){re.error("That file is over 200MB. Please pick a smaller one.");return}const f=m.type.startsWith("video/");a(!0);try{const g=m.name.split(".").pop()||(f?"mp4":"jpg"),x=`${$in}/${t.id}/${crypto.randomUUID()}.${g}`,{error:y}=await q.storage.from(T_t).upload(x,m,{cacheControl:"3600",upsert:!1,contentType:m.type});if(y)throw y;const{data:v}=q.storage.from(T_t).getPublicUrl(x),b=v.publicUrl;await q.from("social_media_assets").insert({user_id:t.id,storage_path:x,public_url:b,media_type:f?"video":"image",file_name:m.name,file_size:m.size}),s({mediaUrl:b,mediaType:f?"video":"image",source:"upload"}),re.success("Media uploaded")}catch(g){console.error(g),re.error("Upload failed. Please try again.")}finally{a(!1),n.current&&(n.current.value="")}};return e.jsxs(ha,{defaultValue:"upload",className:"space-y-4",children:[e.jsxs(ma,{className:"grid grid-cols-3 w-full",children:[e.jsxs(Zt,{value:"upload",className:"gap-2",children:[e.jsx(ni,{className:"h-4 w-4"}),"Upload"]}),e.jsxs(Zt,{value:"swag",className:"gap-2",children:[e.jsx(Nn,{className:"h-4 w-4"}),"Gallery"]}),e.jsxs(Zt,{value:"listings",className:"gap-2",children:[e.jsx(va,{className:"h-4 w-4"}),"Listings"]})]}),e.jsxs(Xt,{value:"upload",className:"space-y-4",children:[e.jsx("input",{ref:n,type:"file",accept:"image/*,video/*",className:"hidden",onChange:m=>{var f;return((f=m.target.files)==null?void 0:f[0])&&h(m.target.files[0])}}),e.jsx(Ne,{className:"border-dashed border-2",children:e.jsxs(Ie,{className:"p-6 flex flex-col items-center text-center gap-3",children:[e.jsx(Mc,{className:"h-8 w-8 text-muted-foreground"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:"Upload a photo or video"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"JPG, PNG or MP4 up to 200MB"})]}),e.jsxs($,{onClick:()=>{var m;return(m=n.current)==null?void 0:m.click()},disabled:r,className:"gap-2",children:[r?e.jsx(kt,{className:"h-4 w-4 animate-spin"}):e.jsx(ni,{className:"h-4 w-4"}),r?"Uploading…":"Choose file"]}),e.jsxs($,{variant:"outline",onClick:()=>l(!0),className:"gap-2",children:[e.jsx(Yc,{className:"h-4 w-4"}),"Import from Canva"]}),e.jsx(iGt,{open:i,onOpenChange:l,mode:"social",workflow:"social_studio",onImported:m=>{o.invalidateQueries({queryKey:["studio-uploads",t==null?void 0:t.id]});const f=m.files[0];f!=null&&f.preview_url&&s({mediaUrl:f.preview_url,mediaType:"image",source:"upload"}),re.success(m.files.length>1?`${m.files.length} Canva pages added to your media library`:"Canva design added to your media library")}})]})}),c.length>0&&e.jsx(uo,{className:"h-56",children:e.jsx("div",{className:"grid grid-cols-3 gap-2 pr-3",children:c.map(m=>e.jsxs("button",{type:"button",onClick:()=>s({mediaUrl:m.public_url,mediaType:m.media_type,source:"upload"}),className:"relative overflow-hidden rounded-lg border hover:ring-2 hover:ring-primary transition",children:[m.media_type==="video"?e.jsx("video",{src:m.public_url,className:"h-24 w-full object-cover"}):e.jsx("img",{src:m.public_url,alt:m.file_name??"",loading:"lazy",className:"h-24 w-full object-cover"}),m.media_type==="video"&&e.jsx(Be,{className:"absolute bottom-1 left-1 text-[10px]",children:"Video"})]},m.id))})})]}),e.jsx(Xt,{value:"swag",children:e.jsx(uo,{className:"h-72",children:e.jsx("div",{className:"grid grid-cols-3 gap-2 pr-3",children:d.map(m=>e.jsx("button",{type:"button",onClick:()=>s({mediaUrl:m.image_url,mediaType:"image",caption:m.caption??"",source:"swag",sourceRef:m.id}),className:"overflow-hidden rounded-lg border hover:ring-2 hover:ring-primary transition",children:e.jsx("img",{src:m.image_url,alt:"",loading:"lazy",className:"h-24 w-full object-cover"})},m.id))})})}),e.jsx(Xt,{value:"listings",children:e.jsx(uo,{className:"h-72",children:e.jsxs("div",{className:"space-y-3 pr-3",children:[u.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"You don't have any listings yet."}),u.map(m=>{const f=[...m.listing_photos??[]].sort((x,y)=>Number(y.is_primary)-Number(x.is_primary)||x.sort_order-y.sort_order),g=[`${m.property_address??""}`.trim(),`${m.city}, ${m.state}`,M_t(m.price),[m.bedrooms?`${m.bedrooms} bed`:null,m.bathrooms?`${m.bathrooms} bath`:null,m.square_footage?`${m.square_footage.toLocaleString()} sq ft`:null].filter(Boolean).join(" · "),"DM me for a private tour."].filter(Boolean).join(` `);return e.jsx(Ne,{children:e.jsxs(Ie,{className:"p-3 space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-sm font-medium truncate",children:m.property_address||`${m.city}, ${m.state}`}),e.jsx("p",{className:"text-xs text-muted-foreground",children:M_t(m.price)})]}),e.jsx(Be,{variant:"secondary",className:"capitalize",children:String(m.status).replace(/_/g," ")})]}),f.length>0?e.jsx("div",{className:"grid grid-cols-4 gap-2",children:f.slice(0,8).map((x,y)=>e.jsx("button",{type:"button",onClick:()=>s({mediaUrl:x.photo_url,mediaType:"image",caption:g,source:"listing",sourceRef:m.id}),className:"overflow-hidden rounded-md border hover:ring-2 hover:ring-primary transition",children:e.jsx("img",{src:x.photo_url,alt:"",loading:"lazy",className:"h-16 w-full object-cover"})},y))}):e.jsx("p",{className:"text-xs text-muted-foreground",children:"No photos on this listing yet."})]})},m.id)})]})})})]})}function Vin({platform:s,accountName:t,avatarUrl:n,caption:r,mediaUrl:a,mediaType:i}){const l=$4(s),o=l.icon,c=s==="instagram",d=a?i==="video"?e.jsx("video",{src:a,className:c?"w-full aspect-square object-cover":"w-full max-h-80 object-cover",controls:!0,playsInline:!0}):e.jsx("img",{src:a,alt:"Post preview",loading:"lazy",className:c?"w-full aspect-square object-cover":"w-full max-h-80 object-cover"}):null;return e.jsxs(Ne,{className:"overflow-hidden",children:[e.jsxs("div",{className:"flex items-center gap-3 p-3 border-b",children:[e.jsxs(Oa,{className:"h-9 w-9",children:[e.jsx(Li,{src:n??void 0,alt:t}),e.jsx(za,{children:t.slice(0,2).toUpperCase()})]}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"text-sm font-semibold truncate",children:t}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[l.label," · just now"]})]}),e.jsx(o,{className:"h-4 w-4 text-muted-foreground"})]}),c?e.jsxs(e.Fragment,{children:[d,e.jsxs("div",{className:"p-3 space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-4 text-muted-foreground",children:[e.jsx(Jo,{className:"h-5 w-5"}),e.jsx(Th,{className:"h-5 w-5"}),e.jsx(Yr,{className:"h-5 w-5"})]}),e.jsxs("p",{className:"text-sm whitespace-pre-wrap break-words",children:[e.jsx("span",{className:"font-semibold mr-1",children:t}),r]})]})]}):e.jsxs(e.Fragment,{children:[r&&e.jsx("p",{className:"p-3 text-sm whitespace-pre-wrap break-words",children:r}),d,e.jsxs("div",{className:"flex items-center gap-5 p-3 text-muted-foreground border-t",children:[e.jsxs("span",{className:"flex items-center gap-1 text-xs",children:[e.jsx(Vy,{className:"h-4 w-4"})," Like"]}),e.jsxs("span",{className:"flex items-center gap-1 text-xs",children:[e.jsx(Th,{className:"h-4 w-4"})," Comment"]}),e.jsxs("span",{className:"flex items-center gap-1 text-xs",children:[e.jsx(eee,{className:"h-4 w-4"})," Share"]})]})]})]})}function jrt(){const{user:s}=vs();return tt({queryKey:["studio-accounts",s==null?void 0:s.id],enabled:!!(s!=null&&s.id),queryFn:async()=>{const{data:t,error:n}=await q.from("social_accounts").select("id, platform, platform_username, page_name, profile_picture_url, is_active").eq("user_id",s.id).eq("is_active",!0).order("platform");if(n)throw n;return t??[]}})}function Hin(s){const{user:t}=vs();return tt({queryKey:["studio-posts",t==null?void 0:t.id,"all"],enabled:!!(t!=null&&t.id),queryFn:async()=>{let n=q.from("social_posts").select("*, social_post_targets(*)").eq("user_id",t.id).order("created_at",{ascending:!1}).limit(500);const{data:r,error:a}=await n;if(a)throw a;return r??[]}})}function oGt(){const s=Vt();return()=>{s.invalidateQueries({queryKey:["studio-posts"]}),s.invalidateQueries({queryKey:["studio-accounts"]})}}const Gin="America/New_York",lGt="levelup.calendar.timezone";function v7(s){if(!s)return!1;try{return new Intl.DateTimeFormat("en-US",{timeZone:s}),!0}catch{return!1}}function Win(){try{const s=localStorage.getItem(lGt);if(v7(s))return s}catch{}return null}let w3e=Win();function LT(){return w3e||vie()}function P_t(s){w3e=v7(s)?s:vie();try{localStorage.setItem(lGt,w3e)}catch{}return w3e}function vie(){const s=Intl.DateTimeFormat().resolvedOptions().timeZone;return v7(s)?s:Gin}function mL(s,t=new Date){try{const n=new Intl.DateTimeFormat("en-US",{timeZone:s,timeZoneName:"short"}).formatToParts(t).find(r=>r.type==="timeZoneName");return(n==null?void 0:n.value)||""}catch{return""}}function UBe(s,t=new Date){try{return new Intl.DateTimeFormat("en-US",{timeZone:s,hour:"numeric",minute:"2-digit"}).format(t)}catch{return""}}const cGt=[{value:"America/New_York",label:"Eastern — New York"},{value:"America/Detroit",label:"Eastern — Detroit"},{value:"America/Indiana/Indianapolis",label:"Eastern — Indianapolis"},{value:"America/Chicago",label:"Central — Chicago"},{value:"America/Denver",label:"Mountain — Denver"},{value:"America/Phoenix",label:"Mountain (no DST) — Phoenix"},{value:"America/Los_Angeles",label:"Pacific — Los Angeles"},{value:"America/Anchorage",label:"Alaska — Anchorage"},{value:"Pacific/Honolulu",label:"Hawaii — Honolulu"},{value:"America/Toronto",label:"Eastern — Toronto"},{value:"America/Vancouver",label:"Pacific — Vancouver"},{value:"America/Puerto_Rico",label:"Atlantic — Puerto Rico"}];function Kin(){var r;let s=[];try{s=((r=Intl.supportedValuesOf)==null?void 0:r.call(Intl,"timeZone"))||[]}catch{s=[]}const t=cGt.map(a=>a.value),n=s.filter(a=>!t.includes(a));return[...t,...n]}function Yin(s,t){const n=(s||"").split("@")[0].replace(/[^a-z0-9]+/gi,"-").toLowerCase(),r=(t||"").slice(0,6);return`${n||"agent"}-${r}`.replace(/^-+|-+$/g,"")||`agent-${Date.now()}`}function _K(){const{user:s}=vs(),t=Vt(),n=tt({queryKey:["calendar-timezone",s==null?void 0:s.id],enabled:!!s,staleTime:5*6e4,queryFn:async()=>{const{data:i,error:l}=await q.from("agent_booking_settings").select("timezone").eq("user_id",s.id).maybeSingle();if(l)throw l;return(i==null?void 0:i.timezone)||null}});j.useEffect(()=>{n.data&&v7(n.data)&&P_t(n.data)},[n.data]);const r=v7(n.data)?n.data:LT()||vie(),a=ft({mutationFn:async i=>{if(!v7(i))throw new Error("That timezone isn't recognized");const{data:l,error:o}=await q.from("agent_booking_settings").update({timezone:i}).eq("user_id",s.id).select("id");if(o)throw o;if(!l||l.length===0){const{error:c}=await q.from("agent_booking_settings").insert({user_id:s.id,slug:Yin(s.email,s.id),timezone:i,is_active:!1});if(c)throw c}return P_t(i),i},onSuccess:i=>{t.setQueryData(["calendar-timezone",s==null?void 0:s.id],i),t.invalidateQueries({queryKey:["booking-settings"]}),t.invalidateQueries({queryKey:["my-calendar"]}),re.success("Calendar timezone updated")},onError:i=>re.error(i.message||"Could not update timezone")});return{timezone:r,isLoading:n.isLoading,update:a}}function dGt({open:s,onOpenChange:t}){const{timezone:n,update:r}=_K(),[a,i]=j.useState(n),[l,o]=j.useState("");j.useEffect(()=>{s&&(i(n),o(""))},[s,n]);const c=vie(),d=j.useMemo(()=>{const h=l.trim().toLowerCase();return h?Kin().filter(m=>m.toLowerCase().includes(h.replace(/\s+/g,"_"))).slice(0,40):[]},[l]),u=()=>{r.mutate(a,{onSuccess:()=>t(!1)})};return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Os,{className:"max-w-lg max-h-[85vh] overflow-y-auto",children:[e.jsxs(Us,{children:[e.jsxs(Bs,{className:"flex items-center gap-2",children:[e.jsx(IN,{className:"h-4 w-4 text-primary"}),"Calendar settings"]}),e.jsx(Ir,{children:"Pick the timezone your calendar, appointments and bookings display in."})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"rounded-xl border bg-muted/40 px-4 py-3",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Currently showing"}),e.jsxs("p",{className:"text-sm font-medium mt-0.5",children:[a.replace(/_/g," ")," ",e.jsxs("span",{className:"text-muted-foreground",children:["· ",UBe(a)," ",mL(a)]})]})]}),c!==a&&e.jsxs($,{type:"button",variant:"outline",size:"sm",className:"w-full justify-start gap-2",onClick:()=>i(c),children:[e.jsx(ci,{className:"h-4 w-4"}),"Use my device timezone (",c.replace(/_/g," "),")"]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{className:"text-sm font-medium",children:"Common timezones"}),e.jsx("div",{className:"grid gap-1.5",children:cGt.map(h=>e.jsxs("button",{type:"button",onClick:()=>i(h.value),className:Pt("flex items-center justify-between rounded-lg border px-3 py-2 text-left text-sm transition-colors",a===h.value?"border-primary bg-primary/5 font-medium":"hover:bg-muted/60"),children:[e.jsx("span",{children:h.label}),e.jsx(Be,{variant:"secondary",className:"text-[10px]",children:UBe(h.value)})]},h.value))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"tz-search",className:"text-sm font-medium",children:"Search all timezones"}),e.jsx(pe,{id:"tz-search",value:l,onChange:h=>o(h.target.value),placeholder:"e.g. Denver, London, Sao Paulo"}),d.length>0&&e.jsx("div",{className:"max-h-52 overflow-y-auto rounded-lg border divide-y",children:d.map(h=>e.jsxs("button",{type:"button",onClick:()=>i(h),className:Pt("flex w-full items-center justify-between px-3 py-2 text-left text-sm transition-colors",a===h?"bg-primary/5 font-medium":"hover:bg-muted/60"),children:[e.jsx("span",{children:h.replace(/_/g," ")}),e.jsx("span",{className:"text-xs text-muted-foreground",children:UBe(h)})]},h))})]})]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[e.jsx($,{variant:"ghost",onClick:()=>t(!1),children:"Cancel"}),e.jsxs($,{onClick:u,disabled:r.isPending||a===n,children:[r.isPending&&e.jsx(kt,{className:"mr-2 h-4 w-4 animate-spin"}),"Save timezone"]})]})]})})}const i4=s=>String(s).padStart(2,"0");function bie(s){return v7(s)?s:LT()}function Nrt(s,t){const n=new Intl.DateTimeFormat("en-US",{timeZone:t,year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit",hour12:!1}),r={};for(const a of n.formatToParts(s))a.type!=="literal"&&(r[a.type]=Number(a.value));return r.hour===24&&(r.hour=0),r}function I_t(s,t){const n=Nrt(s,t);return Date.UTC(n.year,n.month-1,n.day,n.hour,n.minute,n.second)-s.getTime()}function $Te(s,t){const n=bie(t),[r,a="00:00"]=s.split("T"),[i,l,o]=r.split("-").map(Number),[c,d]=a.split(":").map(Number),u=Date.UTC(i,(l||1)-1,o||1,c||0,d||0,0);let h=new Date(u-I_t(new Date(u),n));return h=new Date(u-I_t(h,n)),h}function uGt(s,t){const n=bie(t),r=typeof s=="string"?new Date(s):s,a=Nrt(r,n);return`${a.year}-${i4(a.month)}-${i4(a.day)}T${i4(a.hour)}:${i4(a.minute)}`}function Zin(s,t){const n=bie(t),r=typeof s=="string"?new Date(s):s,a=Nrt(r,n);return`${a.year}-${a.month-1}-${a.day}`}function hGt(s,t,n){const r=typeof s=="string"?new Date(s):s;return new Intl.DateTimeFormat("en-US",{timeZone:bie(t),...n}).format(r)}function mGt(s,t){return hGt(s,t,{month:"short",day:"numeric",hour:"numeric",minute:"2-digit",timeZoneName:"short"})}function Xin(s,t){return hGt(s,t,{hour:"numeric",minute:"2-digit"})}function Qin(s,t,n,r){const a=bie(n),i=r&&r.includes("T")?r.split("T")[0]:uGt(new Date,a).split("T")[0];let l=`${i}T${i4(s)}:${i4(t)}`;if($Te(l,a).getTime()<=Date.now()){const[o,c,d]=i.split("-").map(Number),u=new Date(Date.UTC(o,c-1,d+1));l=`${u.getUTCFullYear()}-${i4(u.getUTCMonth()+1)}-${i4(u.getUTCDate())}T${i4(s)}:${i4(t)}`}return l}const Ade=s=>s.page_name||s.platform_username||$4(s.platform).label;function Jin({seed:s,editingPost:t,onSaved:n,onCancelEdit:r}){const{user:a}=vs(),{data:i=[],isLoading:l}=jrt(),{timezone:o}=_K(),[c,d]=j.useState(!1),u=ue=>uGt(ue,o),[h,m]=j.useState(""),[f,g]=j.useState(null),[x,y]=j.useState("text"),[v,b]=j.useState("manual"),[w,S]=j.useState([]),[C,E]=j.useState({}),[I,P]=j.useState(!1),[R,D]=j.useState(!1),[O,U]=j.useState(""),[W,V]=j.useState(null);j.useEffect(()=>{s&&(s.mediaUrl&&(g(s.mediaUrl),y(s.mediaType??"image")),s.caption!==void 0&&m(s.caption),s.source&&b(s.source),s.scheduledFor&&(D(!0),U(u(s.scheduledFor))))},[s]),j.useEffect(()=>{var ve;if(!t)return;m(t.caption??""),g(((ve=t.media_urls)==null?void 0:ve[0])??null),y(t.media_type),b(t.source??"manual"),S(t.social_post_targets.map(Ee=>Ee.social_account_id));const ue={};t.social_post_targets.forEach(Ee=>{Ee.caption_override&&(ue[Ee.social_account_id]=Ee.caption_override)}),E(ue),P(Object.keys(ue).length>0),t.scheduled_for&&(D(!0),U(u(new Date(t.scheduled_for))))},[t]);const G=j.useMemo(()=>i.filter(ue=>w.includes(ue.id)),[i,w]),Y=ue=>{var ve;return I&&((ve=C[ue])!=null&&ve.trim())?C[ue]:h},X=j.useMemo(()=>{const ue=[];return G.forEach(ve=>{const Ee=$4(ve.platform),Se=Y(ve.id);Ee.requiresMedia&&!f&&ue.push(`${Ee.label} requires a photo or video.`),!Ee.supportsVideo&&x==="video"&&ue.push(`${Ee.label} can't publish video from LevelUp yet.`),ve.platform==="instagram"&&x==="image"&&/\.png(\?|$)/i.test(f??"")&&ue.push("Instagram only accepts JPG images — pick a JPG version."),Se.length>Ee.captionLimit&&ue.push(`${Ee.label} caption is over the ${Ee.captionLimit.toLocaleString()} character limit.`)}),Array.from(new Set(ue))},[G,f,x,h,C,I]),ae=()=>{m(""),g(null),y("text"),b("manual"),S([]),E({}),P(!1),D(!1),U("")},ie=ue=>{g(ue.mediaUrl),y(ue.mediaType),b(ue.source),ue.caption&&!h.trim()&&m(ue.caption)},ne=ue=>S(ve=>ve.includes(ue)?ve.filter(Ee=>Ee!==ue):[...ve,ue]),te=async ue=>{if(a!=null&&a.id){if(ue!=="draft"&&w.length===0){re.error("Choose at least one account to post to.");return}if(ue!=="draft"&&!h.trim()&&!f){re.error("Add a caption or media before publishing.");return}if(ue==="schedule"&&!O){re.error("Pick a date and time to schedule.");return}if(ue!=="draft"&&X.length>0){re.error(X[0]);return}V(ue);try{const ve={user_id:a.id,caption:h.trim()||null,media_type:x,media_urls:f?[f]:[],source:v,status:ue==="draft"?"draft":ue==="schedule"?"scheduled":"publishing",scheduled_for:ue==="schedule"?$Te(O,o).toISOString():null,timezone:o};let Ee=(t==null?void 0:t.id)??null;if(Ee){const{error:Se}=await q.from("social_posts").update(ve).eq("id",Ee);if(Se)throw Se;await q.from("social_post_targets").delete().eq("post_id",Ee)}else{const{data:Se,error:Le}=await q.from("social_posts").insert(ve).select("id").single();if(Le)throw Le;Ee=Se.id}if(w.length>0){const Se=G.map(Fe=>{var ke;return{post_id:Ee,user_id:a.id,social_account_id:Fe.id,platform:Fe.platform,caption_override:I&&((ke=C[Fe.id])!=null&&ke.trim())?C[Fe.id].trim():null,status:"pending"}}),{error:Le}=await q.from("social_post_targets").insert(Se);if(Le)throw Le}if(ue==="now"){const{data:Se,error:Le}=await q.functions.invoke("social-publish-post",{body:{post_id:Ee}});if(Le)throw Le;const Fe=Se==null?void 0:Se.status;Fe==="failed"?re.error("Publishing failed. Check the Queue tab for details."):Fe==="partial"?re.warning("Some accounts failed. Check the Queue tab to retry."):re.success("Posted to your accounts.")}else re.success(ue==="draft"?"Draft saved":"Post scheduled");t||ae(),n==null||n()}catch(ve){console.error(ve),re.error((ve==null?void 0:ve.message)??"Something went wrong saving your post.")}finally{V(null)}}},J=(ue,ve)=>{D(!0),U(Qin(ue,ve,o,O))},ce=mL(o),_e=vie(),he=_e!==o;return e.jsxs("div",{className:"grid gap-6 lg:grid-cols-[minmax(0,1fr)_380px]",children:[e.jsxs("div",{className:"space-y-6",children:[t&&e.jsx(Mse,{children:e.jsxs(Pse,{className:"flex items-center justify-between gap-3",children:[e.jsx("span",{children:"Editing a saved post."}),e.jsxs($,{variant:"ghost",size:"sm",onClick:r,className:"gap-1",children:[e.jsx(gr,{className:"h-4 w-4"})," Cancel"]})]})}),e.jsxs(Ne,{children:[e.jsx(Ct,{className:"pb-3",children:e.jsx(At,{className:"text-base",children:"1. Choose your media"})}),e.jsxs(Ie,{className:"space-y-4",children:[f&&e.jsxs("div",{className:"relative w-full max-w-xs overflow-hidden rounded-lg border",children:[x==="video"?e.jsx("video",{src:f,className:"w-full",controls:!0,playsInline:!0}):e.jsx("img",{src:f,alt:"Selected media",className:"w-full object-cover"}),e.jsx($,{variant:"secondary",size:"icon",className:"absolute top-2 right-2 h-8 w-8",onClick:()=>{g(null),y("text")},children:e.jsx(Wn,{className:"h-4 w-4"})})]}),e.jsx(qin,{onSelect:ie})]})]}),e.jsxs(Ne,{children:[e.jsx(Ct,{className:"pb-3",children:e.jsx(At,{className:"text-base",children:"2. Write your caption"})}),e.jsxs(Ie,{className:"space-y-4",children:[e.jsx(Rs,{value:h,onChange:ue=>m(ue.target.value),rows:6,placeholder:"What do you want to share with your audience?"}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("span",{className:"text-xs text-muted-foreground",children:[h.length," characters"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ee,{htmlFor:"per-platform",className:"text-xs",children:"Customize per platform"}),e.jsx(Sn,{id:"per-platform",checked:I,onCheckedChange:P})]})]}),I&&G.length>0&&e.jsxs(ha,{defaultValue:G[0].id,className:"pt-2",children:[e.jsx(ma,{className:"flex-wrap h-auto",children:G.map(ue=>e.jsx(Zt,{value:ue.id,className:"text-xs",children:Ade(ue)},ue.id))}),G.map(ue=>e.jsx(Xt,{value:ue.id,className:"pt-3",children:e.jsx(Rs,{rows:5,value:C[ue.id]??"",placeholder:`Leave blank to use the main caption for ${$4(ue.platform).label}`,onChange:ve=>E(Ee=>({...Ee,[ue.id]:ve.target.value}))})},ue.id))]})]})]}),e.jsxs(Ne,{children:[e.jsx(Ct,{className:"pb-3",children:e.jsx(At,{className:"text-base",children:"3. Pick your accounts"})}),e.jsxs(Ie,{className:"space-y-3",children:[l&&e.jsx(kt,{className:"h-4 w-4 animate-spin text-muted-foreground"}),!l&&i.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"No connected accounts yet. Connect Facebook, Instagram, LinkedIn or Google Business in Social settings."}),e.jsx("div",{className:"grid gap-2 sm:grid-cols-2",children:i.map(ue=>{const ve=$4(ue.platform),Ee=ve.icon,Se=w.includes(ue.id);return e.jsxs("button",{type:"button",onClick:()=>ne(ue.id),className:`flex items-center gap-3 rounded-lg border p-3 text-left transition ${Se?"border-primary bg-primary/5":"hover:bg-muted/50"}`,children:[e.jsxs(Oa,{className:"h-9 w-9",children:[e.jsx(Li,{src:ue.profile_picture_url??void 0}),e.jsx(za,{children:Ade(ue).slice(0,2).toUpperCase()})]}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"text-sm font-medium truncate",children:Ade(ue)}),e.jsxs("p",{className:"text-xs text-muted-foreground flex items-center gap-1",children:[e.jsx(Ee,{className:"h-3 w-3"})," ",ve.label]})]}),Se&&e.jsx(la,{className:"h-4 w-4 text-primary"})]},ue.id)})})]})]}),e.jsxs(Ne,{children:[e.jsx(Ct,{className:"pb-3",children:e.jsx(At,{className:"text-base",children:"4. Publish or schedule"})}),e.jsxs(Ie,{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"schedule-toggle",children:"Schedule for later"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Otherwise it goes out right away."})]}),e.jsx(Sn,{id:"schedule-toggle",checked:R,onCheckedChange:D})]}),R&&e.jsxs("div",{className:"space-y-3",children:[e.jsx(pe,{type:"datetime-local",value:O,onChange:ue=>U(ue.target.value)}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2 text-xs text-muted-foreground",children:[e.jsx(IN,{className:"h-3.5 w-3.5"}),e.jsxs("span",{children:["Times are in ",e.jsx("span",{className:"font-medium text-foreground",children:o.replace(/_/g," ")}),ce?` (${ce})`:""]}),e.jsx("button",{type:"button",className:"underline underline-offset-2 hover:text-foreground",onClick:()=>d(!0),children:"Change"})]}),O&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Goes out ",e.jsx("span",{className:"font-medium text-foreground",children:mGt($Te(O,o),o)})]}),he&&e.jsxs("p",{className:"text-xs text-amber-600",children:["Your device is set to ",_e.replace(/_/g," ")," — posts still go out on your ",ce||"saved"," schedule."]}),e.jsx("div",{className:"flex flex-wrap gap-2",children:Bin.map(ue=>e.jsx($,{type:"button",variant:"outline",size:"sm",onClick:()=>J(ue.hour,ue.minute),children:ue.label},ue.label))})]}),X.length>0&&e.jsxs(Mse,{variant:"destructive",children:[e.jsx(wl,{className:"h-4 w-4"}),e.jsx(Pse,{children:e.jsx("ul",{className:"list-disc pl-4 space-y-1",children:X.map(ue=>e.jsx("li",{children:ue},ue))})})]}),e.jsx(Gc,{}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs($,{variant:"outline",onClick:()=>te("draft"),disabled:!!W,className:"gap-2",children:[W==="draft"?e.jsx(kt,{className:"h-4 w-4 animate-spin"}):e.jsx(tl,{className:"h-4 w-4"}),"Save draft"]}),R?e.jsxs($,{onClick:()=>te("schedule"),disabled:!!W,className:"gap-2",children:[W==="schedule"?e.jsx(kt,{className:"h-4 w-4 animate-spin"}):e.jsx(Au,{className:"h-4 w-4"}),"Schedule post"]}):e.jsxs($,{onClick:()=>te("now"),disabled:!!W,className:"gap-2",children:[W==="now"?e.jsx(kt,{className:"h-4 w-4 animate-spin"}):e.jsx(Yr,{className:"h-4 w-4"}),"Post now"]})]})]})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("h3",{className:"text-sm font-semibold",children:"Live preview"}),e.jsxs(Be,{variant:"secondary",children:[G.length," selected"]})]}),G.length===0?e.jsx(Ne,{children:e.jsx(Ie,{className:"p-6 text-sm text-muted-foreground",children:"Select an account to see exactly how your post will look."})}):e.jsx("div",{className:"space-y-4",children:G.map(ue=>e.jsx(Vin,{platform:ue.platform,accountName:Ade(ue),avatarUrl:ue.profile_picture_url,caption:Y(ue.id),mediaUrl:f,mediaType:x},ue.id))})]}),e.jsx(dGt,{open:c,onOpenChange:d})]})}const eon=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],L_t={scheduled:"bg-primary/10 text-primary border-primary/20",publishing:"bg-amber-500/10 text-amber-700 border-amber-500/20",published:"bg-emerald-500/10 text-emerald-700 border-emerald-500/20",partial:"bg-amber-500/10 text-amber-700 border-amber-500/20",failed:"bg-destructive/10 text-destructive border-destructive/20",draft:"bg-muted text-muted-foreground border-border"};function ton({posts:s,onCreateAt:t,onOpenPost:n}){const{timezone:r}=_K(),a=mL(r),[i,l]=j.useState(()=>{const h=new Date;return new Date(h.getFullYear(),h.getMonth(),1)}),o=j.useMemo(()=>{const h=new Date(i);return h.setDate(1-h.getDay()),Array.from({length:42},(m,f)=>{const g=new Date(h);return g.setDate(h.getDate()+f),g})},[i]),c=j.useMemo(()=>{const h=new Map;return s.forEach(m=>{const f=m.scheduled_for??m.published_at;if(!f)return;const g=Zin(f,r);h.set(g,[...h.get(g)??[],m])}),h},[s,r]),d=new Date,u=h=>h.toDateString()===d.toDateString();return e.jsx(Ne,{children:e.jsxs(Ie,{className:"p-4 space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-lg font-semibold",children:i.toLocaleDateString("en-US",{month:"long",year:"numeric"})}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["All times ",a||r.replace(/_/g," ")]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx($,{variant:"outline",size:"sm",onClick:()=>l(new Date(d.getFullYear(),d.getMonth(),1)),children:"Today"}),e.jsx($,{variant:"outline",size:"icon",className:"h-8 w-8",onClick:()=>l(new Date(i.getFullYear(),i.getMonth()-1,1)),children:e.jsx(Cd,{className:"h-4 w-4"})}),e.jsx($,{variant:"outline",size:"icon",className:"h-8 w-8",onClick:()=>l(new Date(i.getFullYear(),i.getMonth()+1,1)),children:e.jsx(Di,{className:"h-4 w-4"})})]})]}),e.jsx("div",{className:"grid grid-cols-7 gap-px text-center text-xs font-medium text-muted-foreground",children:eon.map(h=>e.jsx("div",{className:"py-1",children:h},h))}),e.jsx("div",{className:"grid grid-cols-7 gap-px bg-border rounded-lg overflow-hidden",children:o.map(h=>{const m=`${h.getFullYear()}-${h.getMonth()}-${h.getDate()}`,f=c.get(m)??[],g=h.getMonth()!==i.getMonth();return e.jsxs("div",{className:`group relative min-h-[104px] bg-background p-1.5 ${g?"opacity-50":""}`,children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:`text-xs ${u(h)?"flex h-5 w-5 items-center justify-center rounded-full bg-primary text-primary-foreground":"text-muted-foreground"}`,children:h.getDate()}),e.jsx("button",{type:"button","aria-label":"Create post",onClick:()=>{const x=new Date(h);x.setHours(9,0,0,0),t(x)},className:"opacity-0 group-hover:opacity-100 transition text-muted-foreground hover:text-foreground",children:e.jsx(dn,{className:"h-3.5 w-3.5"})})]}),e.jsxs("div",{className:"mt-1 space-y-1",children:[f.slice(0,3).map(x=>{var v;const y=x.scheduled_for??x.published_at;return e.jsxs("button",{type:"button",onClick:()=>n(x),className:`w-full rounded border px-1.5 py-1 text-left text-[10px] leading-tight ${L_t[x.status]??L_t.draft}`,children:[e.jsx("span",{className:"font-medium",children:Xin(y,r)})," ",e.jsx("span",{className:"truncate",children:((v=x.caption)==null?void 0:v.slice(0,24))||"Media post"}),e.jsx("span",{className:"mt-1 flex gap-1",children:x.social_post_targets.slice(0,4).map(b=>e.jsx("span",{className:`h-1.5 w-1.5 rounded-full ${$4(b.platform).dot}`},b.id))})]},x.id)}),f.length>3&&e.jsxs(Be,{variant:"secondary",className:"text-[10px]",children:["+",f.length-3," more"]})]})]},m)})})]})})}const son=s=>{switch(s){case"published":case"success":return{label:"Published",variant:"default",icon:qr};case"partial":return{label:"Partly published",variant:"secondary",icon:wl};case"failed":return{label:"Failed",variant:"destructive",icon:wl};case"publishing":case"pending":return{label:"Publishing",variant:"secondary",icon:kt};case"scheduled":return{label:"Scheduled",variant:"outline",icon:Au};default:return{label:"Draft",variant:"outline",icon:gi}}};function R_t({posts:s,accounts:t,onEdit:n,onChanged:r,emptyLabel:a}){const[i,l]=j.useState(null),{timezone:o}=_K(),c=h=>t.find(m=>m.id===h),d=async h=>{l(h.id);try{await q.from("social_posts").update({status:"publishing",scheduled_for:null,error_message:null}).eq("id",h.id),await q.from("social_post_targets").update({status:"pending"}).eq("post_id",h.id).in("status",["cancelled","failed"]);const{data:m,error:f}=await q.functions.invoke("social-publish-post",{body:{post_id:h.id}});if(f)throw f;const g=m==null?void 0:m.status;g==="failed"?re.error("Publishing failed. See the error details below."):g==="partial"?re.warning("Some accounts failed."):re.success("Published."),r()}catch(m){re.error((m==null?void 0:m.message)??"Could not publish this post.")}finally{l(null)}},u=async h=>{l(h.id);try{const{error:m}=await q.from("social_posts").delete().eq("id",h.id);if(m)throw m;re.success("Post deleted"),r()}catch(m){re.error((m==null?void 0:m.message)??"Could not delete this post.")}finally{l(null)}};return s.length===0?e.jsx(Ne,{children:e.jsx(Ie,{className:"p-8 text-center text-sm text-muted-foreground",children:a??"Nothing here yet."})}):e.jsx("div",{className:"space-y-3",children:s.map(h=>{var y,v;const f=h.status==="failed"&&!!((y=h.error_message)!=null&&y.startsWith("Missed its scheduled time"))?{label:"Didn't send",variant:"destructive",icon:wl}:son(h.status),g=f.icon,x=h.scheduled_for??h.published_at??h.created_at;return e.jsx(Ne,{children:e.jsx(Ie,{className:"p-4",children:e.jsxs("div",{className:"flex gap-4",children:[((v=h.media_urls)==null?void 0:v[0])&&(h.media_type==="video"?e.jsx("video",{src:h.media_urls[0],className:"h-20 w-20 rounded-lg object-cover shrink-0"}):e.jsx("img",{src:h.media_urls[0],alt:"",loading:"lazy",className:"h-20 w-20 rounded-lg object-cover shrink-0"})),e.jsxs("div",{className:"min-w-0 flex-1 space-y-2",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs(Be,{variant:f.variant,className:"gap-1",children:[e.jsx(g,{className:`h-3 w-3 ${f.label==="Publishing"?"animate-spin":""}`}),f.label]}),e.jsx("span",{className:"text-xs text-muted-foreground",children:mGt(x,h.timezone||o)})]}),e.jsx("p",{className:"text-sm line-clamp-2 whitespace-pre-wrap",children:h.caption||"Media only post"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:h.social_post_targets.map(b=>{const w=$4(b.platform),S=w.icon,C=c(b.social_account_id),E=b.status==="published",I=b.status==="failed";return e.jsxs("div",{className:`flex items-center gap-2 rounded-full border px-2.5 py-1 text-xs ${I?"border-destructive/30 bg-destructive/5 text-destructive":w.chip}`,children:[e.jsxs(Oa,{className:"h-4 w-4",children:[e.jsx(Li,{src:(C==null?void 0:C.profile_picture_url)??void 0}),e.jsx(za,{className:"text-[8px]",children:e.jsx(S,{className:"h-2.5 w-2.5"})})]}),e.jsx("span",{className:"max-w-[140px] truncate",children:(C==null?void 0:C.page_name)||(C==null?void 0:C.platform_username)||w.label}),E&&b.permalink&&e.jsx("a",{href:b.permalink,target:"_blank",rel:"noopener noreferrer","aria-label":"View post",children:e.jsx(kr,{className:"h-3 w-3"})}),I&&e.jsx(wl,{className:"h-3 w-3"})]},b.id)})}),h.error_message&&e.jsx("div",{className:"rounded-md border border-destructive/20 bg-destructive/5 p-2",children:e.jsx("p",{className:"text-xs text-destructive",children:h.error_message})}),h.social_post_targets.some(b=>b.status==="failed")&&e.jsx("div",{className:"rounded-md border border-destructive/20 bg-destructive/5 p-2 space-y-1",children:h.social_post_targets.filter(b=>b.status==="failed").map(b=>e.jsxs("p",{className:"text-xs text-destructive",children:[e.jsxs("span",{className:"font-medium",children:[$4(b.platform).label,":"]})," ",b.error_message||"Publishing failed."]},b.id))})]}),e.jsxs("div",{className:"flex flex-col gap-2 shrink-0",children:[e.jsxs($,{variant:"outline",size:"sm",className:"gap-1",onClick:()=>n(h),children:[e.jsx(gi,{className:"h-3.5 w-3.5"})," Edit"]}),h.status!=="published"&&e.jsxs($,{size:"sm",className:"gap-1",disabled:i===h.id,onClick:()=>d(h),children:[i===h.id?e.jsx(kt,{className:"h-3.5 w-3.5 animate-spin"}):h.status==="failed"||h.status==="partial"?e.jsx(ro,{className:"h-3.5 w-3.5"}):e.jsx(Yr,{className:"h-3.5 w-3.5"}),h.status==="failed"||h.status==="partial"?"Retry":"Post now"]}),e.jsxs($,{variant:"ghost",size:"sm",className:"gap-1 text-muted-foreground",disabled:i===h.id,onClick:()=>u(h),children:[e.jsx(Wn,{className:"h-3.5 w-3.5"})," Delete"]})]})]})})},h.id)})})}const non=()=>{const[s,t]=j.useState("compose"),[n,r]=j.useState(null),[a,i]=j.useState(null);j.useEffect(()=>{const x=sessionStorage.getItem("social-studio-seed");if(x){sessionStorage.removeItem("social-studio-seed");try{const y=JSON.parse(x);(y!=null&&y.mediaUrl||y!=null&&y.caption)&&(r(y),t("compose"))}catch{}}},[]);const{data:l=[]}=jrt(),{data:o=[],isLoading:c}=Hin(),d=oGt(),u=j.useMemo(()=>o.filter(x=>x.status==="scheduled"||x.status==="draft"||x.status==="publishing").sort((x,y)=>new Date(x.scheduled_for??x.created_at).getTime()-new Date(y.scheduled_for??y.created_at).getTime()),[o]),h=j.useMemo(()=>o.filter(x=>["published","partial","failed","cancelled"].includes(x.status)),[o]),m=h.filter(x=>x.status==="failed"||x.status==="partial").length,f=(x,y=null)=>{r(x),i(y),t("compose")},g=x=>{f({mediaUrl:x.mediaUrl,mediaType:x.mediaType,caption:x.caption,source:"swag",sourceRef:x.swagItemId??x.reelId})};return e.jsx(Vs,{title:"Social Studio",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(Ne,{className:"overflow-hidden border-none bg-gradient-to-br from-primary/10 via-background to-background",children:e.jsxs(Ie,{className:"p-6 flex flex-col gap-5 md:flex-row md:items-center md:justify-between",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs(Be,{variant:"secondary",className:"gap-1",children:[e.jsx(Nn,{className:"h-3 w-3"})," Social Studio"]}),e.jsx("h1",{className:"text-2xl font-semibold tracking-tight",children:"Post everywhere, from one place"}),e.jsx("p",{className:"text-sm text-muted-foreground max-w-xl",children:"Write once, preview each network, and publish or schedule to every connected account."})]}),e.jsxs("div",{className:"flex flex-col items-start gap-3 md:items-end",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[l.length===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:"No accounts connected yet"}):e.jsx("div",{className:"flex -space-x-2",children:l.slice(0,6).map(x=>e.jsxs(Oa,{className:"h-8 w-8 border-2 border-background",title:x.page_name??x.platform,children:[e.jsx(Li,{src:x.profile_picture_url??void 0}),e.jsx(za,{className:"text-[10px]",children:$4(x.platform).label.slice(0,2)})]},x.id))}),e.jsx($,{variant:"outline",size:"sm",asChild:!0,className:"gap-2",children:e.jsxs(wr,{to:"/social-connections",children:[e.jsx(sC,{className:"h-4 w-4"})," Manage accounts"]})})]}),e.jsxs($,{className:"gap-2",onClick:()=>f(null),children:[e.jsx(_p,{className:"h-4 w-4"})," New post"]})]})]})}),e.jsx("div",{className:"grid gap-3 sm:grid-cols-3",children:[{label:"Connected accounts",value:l.length,icon:L4},{label:"Scheduled & drafts",value:u.length,icon:Kc},{label:"Published",value:h.filter(x=>x.status==="published").length,icon:qr}].map(({label:x,value:y,icon:v})=>e.jsx(Ne,{children:e.jsxs(Ie,{className:"p-4 flex items-center gap-3",children:[e.jsx("div",{className:"rounded-lg bg-primary/10 p-2",children:e.jsx(v,{className:"h-4 w-4 text-primary"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xl font-semibold leading-none",children:y}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:x})]})]})},x))}),e.jsxs(ha,{value:s,onValueChange:t,className:"space-y-6",children:[e.jsxs(ma,{className:"flex-wrap h-auto",children:[e.jsxs(Zt,{value:"compose",className:"gap-2",children:[e.jsx(_p,{className:"h-4 w-4"}),"Compose"]}),e.jsxs(Zt,{value:"calendar",className:"gap-2",children:[e.jsx(Kc,{className:"h-4 w-4"}),"Calendar"]}),e.jsxs(Zt,{value:"queue",className:"gap-2",children:[e.jsx(Yr,{className:"h-4 w-4"}),"Queue",u.length>0&&e.jsx(Be,{variant:"secondary",className:"ml-1",children:u.length})]}),e.jsxs(Zt,{value:"history",className:"gap-2",children:[e.jsx(qr,{className:"h-4 w-4"}),"History",m>0&&e.jsx(Be,{variant:"destructive",className:"ml-1",children:m})]}),e.jsxs(Zt,{value:"gallery",className:"gap-2",children:[e.jsx(Nn,{className:"h-4 w-4"}),"Swag gallery"]})]}),e.jsx(Xt,{value:"compose",children:e.jsx(Jin,{seed:n,editingPost:a,onSaved:()=>{d(),i(null),r(null)},onCancelEdit:()=>{i(null),r(null)}})}),e.jsx(Xt,{value:"calendar",children:e.jsx(ton,{posts:o,onCreateAt:x=>f({scheduledFor:x}),onOpenPost:x=>f(null,x)})}),e.jsx(Xt,{value:"queue",children:e.jsx(R_t,{posts:u,accounts:l,onEdit:x=>f(null,x),onChanged:d,emptyLabel:c?"Loading your posts…":"Nothing scheduled yet. Compose a post to get started."})}),e.jsx(Xt,{value:"history",children:e.jsx(R_t,{posts:h,accounts:l,onEdit:x=>f(null,x),onChanged:d,emptyLabel:"Your published posts will show up here."})}),e.jsx(Xt,{value:"gallery",children:e.jsx(nGt,{embedded:!0,onCompose:g})})]})]})})},ron=[{id:"branding-bar",title:"Branding Bar Studio",description:"Drop in any image — get a branded version with your headshot, logo, and contact info.",icon:Mc,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:va,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:sl,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:Wl,comingSoon:!0,color:"from-orange-500 to-red-500"},{id:"milestones",title:"Client Milestones",description:"Closing day, home anniversaries, birthdays, referral thank-yous.",icon:Fg,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:t2,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:LE,comingSoon:!0,color:"from-amber-500 to-yellow-500"}];function aon(){return e.jsx(Vs,{title:"Marketing Studio",children:e.jsxs("div",{className:"container max-w-6xl py-8 space-y-6",children:[e.jsxs(Ml,{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(Be,{variant:"secondary",className:"mb-2 gap-1",children:[e.jsx(Nn,{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($,{variant:"outline",asChild:!0,children:e.jsxs(wr,{to:"/marketing-studio/brand-kit",children:[e.jsx(Yc,{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:ron.map(s=>{const t=s.icon,n=e.jsxs(Ne,{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(Ie,{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(Be,{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(wr,{to:s.to,className:"block",children:n},s.id):e.jsx("div",{children:n},s.id)})})]})})}function _ie(){const s=Sa();return tt({queryKey:["marketing-brand-presets",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await q.from("marketing_brand_presets").select("*").eq("user_id",s).order("is_default",{ascending:!1}).order("created_at",{ascending:!0});if(n)throw n;return t||[]},enabled:!!s})}function ion(){const{data:s,...t}=_ie();return{data:(s==null?void 0:s.find(n=>n.is_default))??(s==null?void 0:s[0])??null,...t}}function oon(){const s=Sa(),t=Vt();return ft({mutationFn:async n=>{if(!s)throw new Error("Not signed in");if(n.is_default&&await q.from("marketing_brand_presets").update({is_default:!1}).eq("user_id",s),n.id){const{id:r,...a}=n,{data:i,error:l}=await q.from("marketing_brand_presets").update(a).eq("id",r).eq("user_id",s).select().single();if(l)throw l;return i}else{const{data:r,error:a}=await q.from("marketing_brand_presets").insert({...n,user_id:s}).select().single();if(a)throw a;return r}},onSuccess:()=>t.invalidateQueries({queryKey:["marketing-brand-presets",s]})})}function lon(){const s=Sa(),t=Vt();return ft({mutationFn:async n=>{const{error:r}=await q.from("marketing_brand_presets").delete().eq("id",n);if(r)throw r},onSuccess:()=>t.invalidateQueries({queryKey:["marketing-brand-presets",s]})})}async function con(s,t,n){var o;const r=((o=t.name.split(".").pop())==null?void 0:o.toLowerCase())||"png",a=`${s}/${n}-${Date.now()}.${r}`,{error:i}=await q.storage.from("marketing-studio-uploads").upload(a,t,{upsert:!0,cacheControl:"3600"});if(i)throw i;const{data:l}=await q.storage.from("marketing-studio-uploads").createSignedUrl(a,60*60*24*365*5);return(l==null?void 0:l.signedUrl)??""}function don({preset:s,onSaved:t,onCancel:n}){var x;const r=Sa(),a=oon(),i=lon(),l=j.useRef(null),o=j.useRef(null),[c,d]=j.useState(null),[u,h]=j.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"});j.useEffect(()=>{s||(async()=>{if(!r)return;const{supabase:y}=await ri(async()=>{const{supabase:b}=await Promise.resolve().then(()=>Vks);return{supabase:b}},void 0),{data:v}=await y.from("profiles").select("name, email, phone, avatar_url, website_url, title, brokerage_id").eq("id",r).maybeSingle();v&&h(b=>({...b,display_name:b.display_name||(v.name??""),email:b.email||(v.email??""),phone:b.phone||(v.phone??""),headshot_url:b.headshot_url||(v.avatar_url??""),website_url:b.website_url||(v.website_url??""),tagline:b.tagline||(v.title??"")}))})()},[r]);const m=async(y,v)=>{if(r){d(y);try{const b=await con(r,v,y);h(w=>({...w,[y==="headshot"?"headshot_url":"brokerage_logo_url"]:b}))}catch(b){re.error(b.message||"Upload failed")}finally{d(null)}}},f=async()=>{try{const y=await a.mutateAsync({id:s==null?void 0:s.id,...u});re.success("Brand preset saved"),t==null||t(y)}catch(y){re.error(y.message||"Save failed")}},g=async()=>{s!=null&&s.id&&await fo("Delete this brand preset?")&&(await i.mutateAsync(s.id),re.success("Preset deleted"),n==null||n())};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(ee,{children:"Preset name"}),e.jsx(pe,{value:u.name,onChange:y=>h({...u,name:y.target.value}),placeholder:"Personal, Team, Luxury..."})]}),e.jsxs("div",{className:"flex items-end gap-3 pb-1",children:[e.jsx(Sn,{checked:u.is_default,onCheckedChange:y=>h({...u,is_default:y})}),e.jsx(ee,{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(ee,{children:"Display name"}),e.jsx(pe,{value:u.display_name,onChange:y=>h({...u,display_name:y.target.value})})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Phone"}),e.jsx(pe,{value:u.phone,onChange:y=>h({...u,phone:y.target.value})})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Email"}),e.jsx(pe,{value:u.email,onChange:y=>h({...u,email:y.target.value})})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"License #"}),e.jsx(pe,{value:u.license_number,onChange:y=>h({...u,license_number:y.target.value})})]}),e.jsxs("div",{className:"md:col-span-2",children:[e.jsx(ee,{children:"Tagline"}),e.jsx(pe,{value:u.tagline,onChange:y=>h({...u,tagline:y.target.value}),placeholder:"Helping families find home"})]}),e.jsxs("div",{className:"md:col-span-2",children:[e.jsx(ee,{children:"Website"}),e.jsx(pe,{value:u.website_url,onChange:y=>h({...u,website_url:y.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(ee,{children:"Headshot"}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs(Oa,{className:"h-16 w-16",children:[e.jsx(Li,{src:u.headshot_url||void 0}),e.jsx(za,{children:((x=u.display_name)==null?void 0:x[0])??"A"})]}),e.jsxs($,{type:"button",variant:"outline",size:"sm",onClick:()=>{var y;return(y=l.current)==null?void 0:y.click()},disabled:c==="headshot",children:[c==="headshot"?e.jsx(kt,{className:"h-4 w-4 animate-spin"}):e.jsx(ni,{className:"h-4 w-4 mr-1"}),"Upload"]}),e.jsx("input",{ref:l,type:"file",accept:"image/*",hidden:!0,onChange:y=>{var v;return((v=y.target.files)==null?void 0:v[0])&&m("headshot",y.target.files[0])}})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{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:u.brokerage_logo_url?e.jsx("img",{src:u.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($,{type:"button",variant:"outline",size:"sm",onClick:()=>{var y;return(y=o.current)==null?void 0:y.click()},disabled:c==="logo",children:[c==="logo"?e.jsx(kt,{className:"h-4 w-4 animate-spin"}):e.jsx(ni,{className:"h-4 w-4 mr-1"}),"Upload"]}),e.jsx("input",{ref:o,type:"file",accept:"image/*",hidden:!0,onChange:y=>{var v;return((v=y.target.files)==null?void 0:v[0])&&m("logo",y.target.files[0])}})]})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(ee,{children:"Brand color"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("input",{type:"color",value:u.brand_color,onChange:y=>h({...u,brand_color:y.target.value}),className:"h-10 w-14 rounded cursor-pointer border"}),e.jsx(pe,{value:u.brand_color,onChange:y=>h({...u,brand_color:y.target.value})})]})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Accent color"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("input",{type:"color",value:u.accent_color,onChange:y=>h({...u,accent_color:y.target.value}),className:"h-10 w-14 rounded cursor-pointer border"}),e.jsx(pe,{value:u.accent_color,onChange:y=>h({...u,accent_color:y.target.value})})]})]})]}),e.jsxs("div",{className:"flex justify-between pt-2",children:[e.jsx("div",{children:(s==null?void 0:s.id)&&e.jsxs($,{variant:"ghost",size:"sm",onClick:g,className:"text-destructive",children:[e.jsx(Wn,{className:"h-4 w-4 mr-1"})," Delete"]})}),e.jsxs("div",{className:"flex gap-2",children:[n&&e.jsx($,{variant:"outline",onClick:n,children:"Cancel"}),e.jsxs($,{onClick:f,disabled:a.isPending,children:[a.isPending&&e.jsx(kt,{className:"h-4 w-4 mr-1 animate-spin"}),"Save preset"]})]})]})]})}function uon(){const{data:s,isLoading:t}=_ie(),[n,r]=j.useState(null);return e.jsx(Vs,{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(Ml,{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(wr,{to:"/marketing-studio",className:"text-sm text-muted-foreground inline-flex items-center gap-1 hover:underline",children:[e.jsx(qa,{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($,{onClick:()=>r("new"),className:"w-full sm:w-auto",children:[e.jsx(dn,{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(Ne,{className:"border-dashed",children:e.jsxs(Ie,{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($,{onClick:()=>r("new"),children:[e.jsx(dn,{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(Ne,{className:"overflow-hidden",children:[e.jsx("div",{className:"h-3",style:{background:`linear-gradient(90deg, ${a.brand_color}, ${a.accent_color})`}}),e.jsxs(Ct,{className:"pb-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(At,{className:"text-lg flex items-center gap-2",children:[a.name,a.is_default&&e.jsxs(Be,{variant:"secondary",className:"gap-1",children:[e.jsx(Ja,{className:"h-3 w-3"})," Default"]})]}),e.jsx($,{size:"sm",variant:"ghost",onClick:()=>r(a),children:e.jsx(gi,{className:"h-4 w-4"})})]}),e.jsx(Gn,{children:a.display_name})]}),e.jsxs(Ie,{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(zs,{open:n!==null,onOpenChange:a=>!a&&r(null),children:e.jsxs(Os,{className:"max-w-2xl max-h-[90vh] overflow-y-auto w-[calc(100vw-2rem)] sm:w-full",children:[e.jsx(Us,{children:e.jsx(Bs,{children:n==="new"?"New brand preset":"Edit brand preset"})}),e.jsx(don,{preset:n==="new"?null:n,onSaved:()=>r(null),onCancel:()=>r(null)})]})})]})})}const LWe=[{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"}],hon=s=>LWe.find(t=>t.id===s)??LWe[0];function mon(s){if(!s)return"#ffffff";const t=s.replace("#","");if(t.length!==6)return"#ffffff";const n=parseInt(t.slice(0,2),16),r=parseInt(t.slice(2,4),16),a=parseInt(t.slice(4,6),16);return(n*299+r*587+a*114)/1e3>=150?"#0f172a":"#ffffff"}function fon({value:s,onChange:t,mediaType:n}){const r=LWe.filter(a=>a.appliesTo.includes(n));return e.jsx("div",{className:"grid grid-cols-2 gap-2",children:r.map(a=>e.jsxs("button",{type:"button",onClick:()=>t(a.id),className:Pt("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(pon,{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 pon({style:s}){const t="#cbd5e1",n="#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:n}}),s.position==="top"&&e.jsx("div",{className:"absolute left-0 right-0 top-0",style:{height:`${s.heightRatio*100}%`,background:n}}),s.position==="corner-br"&&e.jsx("div",{className:"absolute bottom-2 right-2 w-1/3 h-1/3 rounded",style:{background:n,opacity:.85}}),s.position==="side-right"&&e.jsx("div",{className:"absolute top-0 bottom-0 right-0",style:{width:`${s.heightRatio*100}%`,background:n}}),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:n}}),e.jsx("div",{className:"absolute left-0 right-0 bottom-0",style:{height:`${s.heightRatio*100}%`,background:n}})]})]})}/* * Konva JavaScript Framework v10.7.0 * http://konvajs.org/ * Licensed under the MIT * Date: @@date * * Original work Copyright (C) 2011 - 2013 by Eric Rowell (KineticJS) * Modified work Copyright (C) 2014 - present by Anton Lavrenov (Konva) * * @license */const gon=Math.PI/180;function xon(){return typeof window<"u"&&({}.toString.call(window)==="[object Window]"||{}.toString.call(window)==="[object global]")}const aq=typeof global<"u"?global:typeof window<"u"?window:typeof WorkerGlobalScope<"u"?self:{},Qo={_global:aq,version:"10.7.0",isBrowser:xon(),isUnminified:/param/.test((function(s){}).toString()),dblClickWindow:400,getAngle(s){return Qo.angleDeg?s*gon:s},enableTrace:!1,pointerEventsEnabled:!0,autoDrawEnabled:!0,hitOnDragEnabled:!1,capturePointerEventsEnabled:!1,_renderBackend:"web",legacyTextRendering:!1,pixelRatio:typeof window<"u"&&window.devicePixelRatio||1,dragDistance:3,angleDeg:!0,showWarnings:!0,dragButtons:[0,1],isDragging(){return Qo.DD.isDragging},isTransforming(){var s,t;return(t=(s=Qo.Transformer)===null||s===void 0?void 0:s.isTransforming())!==null&&t!==void 0?t:!1},isDragReady(){return!!Qo.DD.node},releaseCanvasOnDestroy:!0,document:aq.document,_injectGlobal(s){typeof aq.Konva<"u"&&console.error("Several Konva instances detected. It is not recommended to use multiple Konva instances in the same environment."),aq.Konva=s}},fGt=new Set,Yg=(s,t=!1)=>{Qo[s.prototype.getClassName()]=s,t&&fGt.add(s)};Qo._injectGlobal(Qo);const yon=`Konva.js unsupported environment. Looks like you are trying to use Konva.js in Node.js environment (or in a Web Worker), 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"; `,D_t=()=>{if(typeof document>"u")throw new Error(yon)};class _0{constructor(t){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 _0(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 n=this.m;return{x:n[0]*t.x+n[2]*t.y+n[4],y:n[1]*t.x+n[3]*t.y+n[5]}}_getTransformedRect(t){const[n,r,a,i,l,o]=this.m,c=t.x,d=t.y,u=t.x+t.width,h=t.y+t.height,m=[n*c+a*d+l,n*u+a*d+l,n*u+a*h+l,n*c+a*h+l],f=[r*c+i*d+o,r*u+i*d+o,r*u+i*h+o,r*c+i*h+o],g=Math.min(m[0],m[1],m[2],m[3]),x=Math.min(f[0],f[1],f[2],f[3]);return{x:g,y:x,width:Math.max(m[0],m[1],m[2],m[3])-g,height:Math.max(f[0],f[1],f[2],f[3])-x}}translate(t,n){return this.m[4]+=this.m[0]*t+this.m[2]*n,this.m[5]+=this.m[1]*t+this.m[3]*n,this}scale(t,n){return this.m[0]*=t,this.m[1]*=t,this.m[2]*=n,this.m[3]*=n,this}rotate(t){const n=Math.cos(t),r=Math.sin(t),a=this.m[0]*n+this.m[2]*r,i=this.m[1]*n+this.m[3]*r,l=this.m[0]*-r+this.m[2]*n,o=this.m[1]*-r+this.m[3]*n;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,n){const r=this.m[0]+this.m[2]*n,a=this.m[1]+this.m[3]*n,i=this.m[2]+this.m[0]*t,l=this.m[3]+this.m[1]*t;return this.m[0]=r,this.m[1]=a,this.m[2]=i,this.m[3]=l,this}multiply(t){const n=this.m[0]*t.m[0]+this.m[2]*t.m[1],r=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]=n,this.m[1]=r,this.m[2]=a,this.m[3]=i,this.m[4]=l,this.m[5]=o,this}isInvertible(){return this.m[0]*this.m[3]-this.m[1]*this.m[2]!==0}invert(){const t=1/(this.m[0]*this.m[3]-this.m[1]*this.m[2]),n=this.m[3]*t,r=-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]=n,this.m[1]=r,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],n=this.m[1],r=this.m[2],a=this.m[3],i=this.m[4],l=this.m[5],o=t*a-n*r,c={x:i,y:l,rotation:0,scaleX:0,scaleY:0,skewX:0,skewY:0};if(t!=0||n!=0){const d=Math.sqrt(t*t+n*n);c.rotation=n>0?Math.acos(t/d):-Math.acos(t/d),c.scaleX=d,c.scaleY=o/d,c.skewX=o&&(t*r+n*a)/o,c.skewY=0}else if(r!=0||a!=0){const d=Math.sqrt(r*r+a*a);c.rotation=Math.PI/2-(a>0?Math.acos(-r/d):-Math.acos(r/d)),c.scaleX=o/d,c.scaleY=d,c.skewX=0,c.skewY=o&&(t*r+n*a)/o}return c.rotation=er._getRotation(c.rotation),c}}const von="[object Array]",bon="[object Number]",_on="[object String]",won="[object Boolean]",jon=Math.PI/180,pGt=180/Math.PI,qBe="#",Non="",kon="0",Son="Konva warning: ",F_t="Konva error: ",Con={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,134,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,250,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,221],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:[112,128,144],slategrey:[112,128,144],snow:[255,250,250],springgreen:[0,255,127],steelblue:[70,130,180],tan:[210,180,140],teal:[0,128,128],thistle:[216,191,216],transparent:[0,0,0,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,50]};let zZ=null;const Aon=typeof window<"u"?window:{},VBe=new WeakMap,Eon=(s,t)=>{typeof s.requestAnimationFrame=="function"?s.requestAnimationFrame(t):typeof requestAnimationFrame<"u"?requestAnimationFrame(t):setTimeout(t,16)},O_t=new Map,gGt=Object.getPrototypeOf(Int8Array),z_t=s=>{const t=s.trim();return t.indexOf(",")===-1?t.split(/\s*\/\s*|\s+/):t.split(/\s*,\s*/)},xGt="[+-]?(?:\\d+\\.?\\d*|\\.\\d+)(?:e[+-]?\\d+)?",Ton=new RegExp(`^(${xGt})(%?)$`,"i"),vR=(s,t)=>{const n=Ton.exec(s);if(!n)return NaN;const r=n[2]?Number(n[1])/100*t:Number(n[1]);return Math.min(Math.max(r,0),t)},Ede=/^#[0-9a-f]+$/i,Mon=new RegExp(`^(${xGt})(deg|grad|rad|turn)?$`,"i"),Pon={deg:1,grad:.9,rad:pGt,turn:360};function BZ(s,t){return Math.min(Math.max(s||0,0),t)}const er={_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)===von},_isNumber(s){return Object.prototype.toString.call(s)===bon&&!isNaN(s)&&isFinite(s)},_isString(s){return Object.prototype.toString.call(s)===_on},_isBoolean(s){return Object.prototype.toString.call(s)===won},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,t){const n=t&&!t.closed&&t||Aon;let r=VBe.get(n);r||(r=[],VBe.set(n,r),Eon(n,function(){VBe.delete(n),r.forEach(function(a){a()})})),r.push(s)},createCanvasElement(){D_t();const s=document.createElement("canvas");try{s.style=s.style||{}}catch{}return s},createImageElement(){return D_t(),document.createElement("img")},_urlToImage(s,t,n){const r=er.createImageElement();r.onload=function(){t(r)},r.onerror=a=>{n==null||n(a instanceof Error?a:new Error("Unable to load image."))},r.src=s},_rgbToHex(s,t,n){return((1<<24)+(s<<16)+(t<<8)+n).toString(16).slice(1)},_hexToRgb(s){s=s.replace(qBe,Non);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=kon+s;return qBe+s},isCanvasFarblingActive(){if(zZ!==null)return zZ;if(typeof document>"u")return zZ=!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 n=t.getImageData(0,0,10,10).data;let r=!1;for(let a=0;a<100;a++)if(n[a*4]!==40||n[a*4+1]!==40||n[a*4+2]!==40||n[a*4+3]!==255){r=!0;break}return zZ=r,this.releaseCanvas(s),zZ},getHitColor(){const s=()=>Math.random()*256|0;return this.getHitColorKey(s(),s(),s())},getHitColorKey(s,t,n){const r=this.isCanvasFarblingActive()?5:3,a=i=>Math.round(i/r)*r;return qBe+this._rgbToHex(a(s),a(t),a(n))},getSnappedHexColor(s){const{r:t,g:n,b:r}=this._hexToRgb(s);return this.getHitColorKey(t,n,r)},getRGB(s){var t;const{r:n=0,g:r=0,b:a=0}=(t=er.colorToRGBA(s))!==null&&t!==void 0?t:{};return{r:n,g:r,b:a}},colorToRGBA(s){s=(s||"").trim()||"black";const t=er._namedColorToRBA(s)||er._hex3ColorToRGBA(s)||er._hex4ColorToRGBA(s)||er._hex6ColorToRGBA(s)||er._hex8ColorToRGBA(s)||er._rgbColorToRGBA(s)||er._hslColorToRGBA(s);if(t&&[t.r,t.g,t.b,t.a].every(er._isNumber))return t},_namedColorToRBA(s){const t=Con[s.toLowerCase()];return t?{r:t[0],g:t[1],b:t[2],a:t.length>3?t[3]:1}:null},_rgbColorToRGBA(s){const t=/^rgba?\(([^)]*)\)$/i.exec(s);if(!t)return;const n=z_t(t[1]);if(!(n.length<3||n.length>4))return{r:vR(n[0],255),g:vR(n[1],255),b:vR(n[2],255),a:n.length>3?vR(n[3],1):1}},_hex8ColorToRGBA(s){if(s.length===9&&Ede.test(s))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.length===7&&Ede.test(s))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.length===5&&Ede.test(s))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.length===4&&Ede.test(s))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){const t=/^hsla?\(([^)]*)\)$/i.exec(s);if(!t)return;const n=z_t(t[1]);if(n.length<3||n.length>4)return;const r=Mon.exec(n[0]);if(!r)return;const a=r[2],i=Number(r[1])*(a?Pon[a.toLowerCase()]:1);if(!isFinite(i))return;const l=(i%360+360)%360/360,o=vR(n[1],100)/100,c=vR(n[2],100)/100,d=n.length>3?vR(n[3],1):1,u=c<.5?c*(1+o):c+o-c*o,h=2*c-u,m=[0,0,0];for(let f=0;f<3;f++){let g=l+.3333333333333333*-(f-1);g<0&&g++,g>1&&g--;let x;6*g<1?x=h+(u-h)*6*g:2*g<1?x=u:3*g<2?x=h+(u-h)*(2/3-g)*6:x=h,m[f]=x*255}return{r:Math.round(m[0]),g:Math.round(m[1]),b:Math.round(m[2]),a:d}},_getPointsRect(s){let t=1/0,n=1/0,r=-1/0,a=-1/0;for(let i=0;is.x+s.width||t.x+t.widths.y+s.height||t.y+t.heighttypeof t=="object")?s.map(er._cloneValue):s.slice():er._isPlainObject(s)?er.cloneObject(s):s instanceof gGt?s.slice():s},cloneArray(s){return s.slice(0)},degToRad(s){return s*jon},radToDeg(s){return s*pGt},_getRotation(s){return Qo.angleDeg?er.radToDeg(s):s},_capitalize(s){const t=O_t.get(s);if(t!==void 0)return t;const n=s.charAt(0).toUpperCase()+s.slice(1);return O_t.set(s,n),n},throw(s){throw new Error(F_t+s)},error(s){console.error(F_t+s)},warn(s){Qo.showWarnings&&console.warn(Son+s)},_batchEvents(s,t){if(!s)return t();let n=!1,r=!0;try{s(()=>{if(n||!r){er.warn("eventBatchFunc must call its argument exactly once, synchronously.");return}n=!0,t()})}finally{r=!1,n||er.warn("eventBatchFunc must call its argument synchronously.")}},each(s,t){for(const n in s)t(n,s[n])},_inRange(s,t,n){return t<=s&&s1?(l=n,o=r,c=(n-a)*(n-a)+(r-i)*(r-i)):(l=s+u*(n-s),o=t+u*(r-t),c=(l-a)*(l-a)+(o-i)*(o-i))}return[l,o,c]},_getProjectionToLine(s,t,n){const r=er.cloneObject(s);let a=Number.MAX_VALUE;return t.forEach(function(i,l){if(!n&&l===t.length-1)return;const o=t[(l+1)%t.length],c=er._getProjectionToSegment(i.x,i.y,o.x,o.y,s.x,s.y),d=c[0],u=c[1],h=c[2];ht.length){const l=t;t=s,s=l}for(let l=0;l=0?"pointer":s.indexOf("touch")>=0?"touch":"mouse"},_getFirstPointerId(s){var t;return s.touches?s.changedTouches[0].identifier:(t=s.pointerId)!==null&&t!==void 0?t:999},releaseCanvas(...s){Qo.releaseCanvasOnDestroy&&s.forEach(t=>{t.width=0,t.height=0})},_cornerRadii(s,t,n){const r=Math.min(t,n)/2;if(typeof s=="number"){const a=BZ(s,r);return[a,a,a,a]}return[BZ(s[0],r),BZ(s[1],r),BZ(s[2],r),BZ(s[3],r)]},drawRoundedRectPath(s,t,n,r){let a=t<0?t:0,i=n<0?n:0;t=Math.abs(t),n=Math.abs(n);const[l,o,c,d]=er._cornerRadii(r,t,n);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+n-c),s.arc(a+t-c,i+n-c,c,0,Math.PI/2,!1),s.lineTo(a+d,i+n),s.arc(a+d,i+n-d,d,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,n,r,a){r=Math.abs(r);for(let i=0;itypeof u=="number"?Math.floor(u):u)),i+=Ron+d.join(Lon)+Don)):(i+=o.property,t||(i+=zon+o.val)),i+=Fon;return i}clearTrace(){this.traceArr=[]}_trace(t){let n=this.traceArr,r;n.push(t),r=n.length,r>=$on&&n.shift()}reset(){const t=this.getCanvas().getPixelRatio();this.setTransform(1*t,0,0,1*t,0,0)}getCanvas(){return this.canvas}clear(t){const n=this.getCanvas();t?this.clearRect(t.x||0,t.y||0,t.width||0,t.height||0):this.clearRect(0,0,n.getWidth()/n.pixelRatio,n.getHeight()/n.pixelRatio)}_drawDeviceBuffer(t){const{x:n,y:r,width:a,height:i}=t._isolationRect;this.setTransform(1,0,0,1,0,0),this.imageSmoothingEnabled=!1,this.drawImage(t._canvas,0,0,a,i,n,r,a,i)}_applyLineCap(t){const n=t.attrs.lineCap;n&&this.setAttr("lineCap",n)}_getOpacity(t){if(!this._opacityRoot)return t.getAbsoluteOpacity();let n=t.opacity(),r=t.parent;for(;r&&r!==this._opacityRoot;)n*=r.opacity(),r=r.parent;return n}_applyOpacity(t){const n=this._getOpacity(t);n!==1&&this.setAttr("globalAlpha",n)}_applyLineJoin(t){const n=t.attrs.lineJoin;n&&this.setAttr("lineJoin",n)}_applyMiterLimit(t){const n=t.attrs.miterLimit;n!=null&&this.setAttr("miterLimit",n)}setAttr(t,n){this._context[t]=n}arc(t,n,r,a,i,l){this._context.arc(t,n,r,a,i,l)}arcTo(t,n,r,a,i){this._context.arcTo(t,n,r,a,i)}beginPath(){this._context.beginPath()}bezierCurveTo(t,n,r,a,i,l){this._context.bezierCurveTo(t,n,r,a,i,l)}clearRect(t,n,r,a){this._context.clearRect(t,n,r,a)}clip(...t){this._context.clip.apply(this._context,t)}closePath(){this._context.closePath()}createImageData(t,n){const r=arguments;if(r.length===2)return this._context.createImageData(t,n);if(r.length===1)return this._context.createImageData(t)}createLinearGradient(t,n,r,a){return this._context.createLinearGradient(t,n,r,a)}createPattern(t,n){return this._context.createPattern(t,n)}createRadialGradient(t,n,r,a,i,l){return this._context.createRadialGradient(t,n,r,a,i,l)}drawImage(t,n,r,a,i,l,o,c,d){const u=arguments,h=this._context;u.length===3?h.drawImage(t,n,r):u.length===5?h.drawImage(t,n,r,a,i):u.length===9&&h.drawImage(t,n,r,a,i,l,o,c,d)}ellipse(t,n,r,a,i,l,o,c){this._context.ellipse(t,n,r,a,i,l,o,c)}isPointInPath(t,n,r,a){return r?this._context.isPointInPath(r,t,n,a):this._context.isPointInPath(t,n,a)}fill(...t){this._context.fill.apply(this._context,t)}fillRect(t,n,r,a){this._context.fillRect(t,n,r,a)}strokeRect(t,n,r,a){this._context.strokeRect(t,n,r,a)}fillText(t,n,r,a){a?this._context.fillText(t,n,r,a):this._context.fillText(t,n,r)}measureText(t){return this._context.measureText(t)}getImageData(t,n,r,a){return this._context.getImageData(t,n,r,a)}lineTo(t,n){this._context.lineTo(t,n)}moveTo(t,n){this._context.moveTo(t,n)}rect(t,n,r,a){this._context.rect(t,n,r,a)}roundRect(t,n,r,a,i){this._context.roundRect(t,n,r,a,i)}putImageData(t,n,r){this._context.putImageData(t,n,r)}quadraticCurveTo(t,n,r,a){this._context.quadraticCurveTo(t,n,r,a)}restore(){this._context.restore()}rotate(t){this._context.rotate(t)}save(){this._context.save()}scale(t,n){this._context.scale(t,n)}setLineDash(t){this._context.setLineDash(t)}getLineDash(){return this._context.getLineDash()}setTransform(t,n,r,a,i,l){this._context.setTransform(t,n,r,a,i,l)}stroke(t){t?this._context.stroke(t):this._context.stroke()}strokeText(t,n,r,a){this._context.strokeText(t,n,r,a)}transform(t,n,r,a,i,l){this._context.transform(t,n,r,a,i,l)}translate(t,n){this._context.translate(t,n)}_enableTrace(){let t=this,n=B_t.length,r=this.setAttr,a,i;const l=function(o){let c=t[o],d;t[o]=function(){return i=Ion(Array.prototype.slice.call(arguments,0)),d=c.apply(t,arguments),t._trace({method:o,args:i}),d}};for(a=0;a0&&m>0||(d=u=0,h=m=1);const f=this._isolationCanvas||(this._isolationCanvas=new b7({width:0,height:0,pixelRatio:this.pixelRatio}));if(f.widthMath.min(C,Math.ceil((S4*n.width*n.height;t._isolationLowFrames=r?t._isolationLowFrames+1:0,t._isolationLowFrames>=10?this._releaseIsolationCanvas():(n.width=n.height=0,t._trimIsolationCanvas())}_releaseIsolationCanvas(){const t=this._isolationCanvas;t&&(t._releaseIsolationCanvas(),er.releaseCanvas(t._canvas),this._isolationCanvas=void 0)}setSize(t,n){this._releaseIsolationCanvas(),super.setSize(t,n)}constructor(t={width:0,height:0,willReadFrequently:!1}){super(t),this._isolationPeak={width:0,height:0},this._isolationLowFrames=0,this.context=new qon(this,{willReadFrequently:t.willReadFrequently}),this.setSize(t.width,t.height)}}class Srt extends krt{constructor(t={width:0,height:0}){super(t),this.hitCanvas=!0,this.context=new Von(this),this.context.imageSmoothingEnabled=!1,this.setSize(t.width,t.height)}}const ph={get isDragging(){let s=!1;return ph._dragElements.forEach(t=>{t.dragStatus==="dragging"&&(s=!0)}),s},get node(){let s;for(const t of ph._dragElements.values()){if(t.dragStatus==="dragging")return t.node;s=t.node}return s},_dragElements:new Map,_listenToWindow(s){const t=a=>ph._endDragBefore(a,s),n=a=>ph._batchEvents(()=>ph._drag(a,s),s),r=a=>ph._batchEvents(()=>ph._endDragAfter(a));s.addEventListener("mouseup",t,!0),s.addEventListener("touchend",t,!0),s.addEventListener("touchcancel",t,!0),s.addEventListener("mousemove",n),s.addEventListener("touchmove",n),s.addEventListener("mouseup",r,!1),s.addEventListener("touchend",r,!1),s.addEventListener("touchcancel",r,!1)},_batchEvents(s,t){if(!ph._dragElements.size)return;const n=new Set;for(const{node:a}of ph._dragElements.values()){const i=a.getStage();if(!i||t&&i._getOwnerWindow()!==t)continue;const l=i.eventBatchFunc();l&&n.add(l)}let r=s;for(const a of n){const i=r;r=()=>er._batchEvents(a,i)}r()},_drag(s,t){const n=[],r=new Set;ph._dragElements.forEach((a,i)=>{const{node:l}=a,o=l.getStage();if(t&&o._getOwnerWindow()!==t||(r.has(o)||(o.setPointersPositions(s),r.add(o)),a.pointerEventType&&a.pointerEventType!==o._pointerEventType))return;a.pointerId===void 0&&(a.pointerId=er._getFirstPointerId(s),a.pointerEventType=o._pointerEventType,a.dragStatus==="dragging"&&o._cancelClick(a.pointerId,a.pointerEventType));const c=o._changedPointerPositions.find(d=>d.id===a.pointerId);if(c){if(a.dragStatus!=="dragging"){const d=l.dragDistance();if(Math.max(Math.abs(c.x-a.startPointerPos.x),Math.abs(c.y-a.startPointerPos.y)){a.getStage()&&a.fire("dragmove",{type:"dragmove",target:a,evt:s},!0)})},_endDragBefore(s,t,n){const r=[],a=new Set;ph._dragElements.forEach((i,l)=>{const{node:o}=i;if(n&&i!==n&&i.pointerId!==n.pointerId)return;const c=o.getStage();if(s&&!a.has(c)&&(!t||c._getOwnerWindow()===t)&&(c.setPointersPositions(s),a.add(c)),!(!n&&(s&&i.pointerEventType&&i.pointerEventType!==er._getEventType(s.type)||!(i.pointerId===void 0||c._changedPointerPositions.some(u=>u.id===i.pointerId)))))if(i.dragStatus==="ready")ph._dragElements.delete(l);else{c._cancelClick(i.pointerId,i.pointerEventType),i.dragStatus="stopped";const d=o.getLayer()||c;d&&r.indexOf(d)===-1&&r.push(d)}}),r.forEach(i=>{i.draw()})},_endDragAfter(s,t){ph._dragElements.forEach((n,r)=>{n.dragStatus!=="stopped"||t&&n!==t&&n.pointerId!==t.pointerId||(n.node.fire("dragend",{type:"dragend",target:n.node,evt:s},!0),n.dragStatus!=="dragging"&&ph._dragElements.delete(r))})}},BG=new Map,yGt=Qo._global.PointerEvent!==void 0;function Tde(s,t){const n=BG.get(s);return n&&(!t||n.stage===t)?n.shape:void 0}function vGt(s,t,n){s._fire(t,{evt:new PointerEvent(t,{pointerId:n}),pointerId:n})}function bGt(s,t){var n;return((n=BG.get(s))===null||n===void 0?void 0:n.shape)===t}function _Gt(s,t){var n;AV(s);const r=t.getStage();if(r&&(BG.set(s,{shape:t,stage:r}),yGt)){try{(n=r.content)===null||n===void 0||n.setPointerCapture(s)}catch{}vGt(t,"gotpointercapture",s)}}function Hon(s){BG.forEach(({shape:t,stage:n},r)=>{(t===s||n===s)&&AV(r)})}function AV(s,t){var n;const r=BG.get(s);if(!r||t&&r.shape!==t)return;const{shape:a,stage:i}=r;if(BG.delete(s),yGt){try{(n=i.content)===null||n===void 0||n.releasePointerCapture(s)}catch{}vGt(a,"lostpointercapture",s)}}function v6(s){return er._isString(s)?'"'+s+'"':Object.prototype.toString.call(s)==="[object Number]"||er._isBoolean(s)?s:Object.prototype.toString.call(s)}function Crt(s){return s>255?255:s<0?0:Math.round(s)}function Ti(){if(Qo.isUnminified)return function(s,t){return er._isNumber(s)||er.warn(v6(s)+' is a not valid value for "'+t+'" attribute. The value should be a number.'),s}}function aRe(s){if(Qo.isUnminified)return function(t,n){let r=er._isNumber(t),a=er._isArray(t)&&t.length==s;return!r&&!a&&er.warn(v6(t)+' is a not valid value for "'+n+'" attribute. The value should be a number or Array('+s+")"),t}}function Art(){if(Qo.isUnminified)return function(s,t){return er._isNumber(s)||s==="auto"||er.warn(v6(s)+' is a not valid value for "'+t+'" attribute. The value should be a number or "auto".'),s}}function KB(){if(Qo.isUnminified)return function(s,t){return er._isString(s)||er.warn(v6(s)+' is a not valid value for "'+t+'" attribute. The value should be a string.'),s}}function wGt(){if(Qo.isUnminified)return function(s,t){const n=er._isString(s),r=Object.prototype.toString.call(s)==="[object CanvasGradient]"||s&&s.addColorStop;return n||r||er.warn(v6(s)+' is a not valid value for "'+t+'" attribute. The value should be a string or a native gradient.'),s}}function Gon(){if(Qo.isUnminified)return function(s,t){return s instanceof gGt||(er._isArray(s)?s.forEach(function(n){er._isNumber(n)||er.warn('"'+t+'" attribute has non numeric element '+n+". Make sure that all elements are numbers.")}):er.warn(v6(s)+' is a not valid value for "'+t+'" attribute. The value should be a array of numbers.')),s}}function kC(){if(Qo.isUnminified)return function(s,t){return s===!0||s===!1||er.warn(v6(s)+' is a not valid value for "'+t+'" attribute. The value should be a boolean.'),s}}function Won(s){if(Qo.isUnminified)return function(t,n){return t==null||er.isObject(t)||er.warn(v6(t)+' is a not valid value for "'+n+'" attribute. The value should be an object with properties '+s),t}}const UZ="get",qZ="set",Tn={addGetterSetter(s,t,n,r,a){Tn.addGetter(s,t,n),Tn.addSetter(s,t,r,a),Tn.addOverloadedGetterSetter(s,t)},addGetter(s,t,n){const r=UZ+er._capitalize(t),a=Array.isArray(n),i=function(){const l=this.attrs[t];return l===void 0?a?n.slice():n:l};i._def=n,s.prototype[r]=s.prototype[r]||i},addSetter(s,t,n,r){const a=qZ+er._capitalize(t);s.prototype[a]||Tn.overWriteSetter(s,t,n,r)},overWriteSetter(s,t,n,r){const a=qZ+er._capitalize(t);s.prototype[a]=function(i){return n&&i!==void 0&&i!==null&&(i=n.call(this,i,t)),this._setAttr(t,i),r&&r.call(this),this}},addComponentsGetterSetter(s,t,n,r,a){const i=n.length,l=er._capitalize,o=UZ+l(t),c=qZ+l(t),d=n.map(m=>t+l(m)),u=d.map(m=>UZ+l(m));s.prototype[o]=function(){const m={};for(let f=0;f{this._setAttr(t+l(g),void 0)}),this._fireChangeEvent(t,f,m),a&&a.call(this),this},Tn.addOverloadedGetterSetter(s,t)},addOverloadedGetterSetter(s,t){const n=er._capitalize(t),r=qZ+n,a=UZ+n,i=function(){return arguments.length?(this[r](arguments[0]),this):this[a]()};s.prototype[t]=i},backCompat(s,t){er.each(t,function(n,r){const a=s.prototype[r],i=UZ+er._capitalize(n),l=qZ+er._capitalize(n);function o(){return er.error('"'+n+'" method is deprecated and will be removed soon. Use ""'+r+'" instead.'),a.apply(this,arguments)}s.prototype[n]=o,s.prototype[i]=o,s.prototype[l]=o})},afterSetFilter(){this._filterUpToDate=!1}};function Kon(s){const t=[],n=/(\w+)\(([^)]*)\)/g;let r;for(;(r=n.exec(s))!==null;){const[,a,i]=r;if(!["blur","brightness","contrast","grayscale","sepia","invert"].includes(a)){er.warn(`CSS filter "${a}" is not supported in fallback mode. Consider using function filters for better compatibility.`);continue}const l=i.trim()===""?a==="blur"?0:1:parseFloat(i)/(i.includes("%")?100:1);t.push({name:a,value:l})}return function(a,i=1){var l;for(const{name:o,value:c}of t){if(["grayscale","sepia","invert"].includes(o)){const h=Math.min(1,Math.max(0,c)),m=a.data;for(let f=0;f0?XM._pendingAfterCascade.push(t):t()}clearCache(){return this._releaseCanvasCache(),this._clearSelfAndDescendantCache(),this._requestDraw(),this}cache(t){const n=t||{};let r={};if(n.x===void 0||n.y===void 0||n.width===void 0||n.height===void 0){const x=this._isUnderCache;this._isUnderCache=!0,r=this.getClientRect({skipTransform:!0,relativeTo:this.getParent()||void 0}),this._isUnderCache=x}let a=n.x===void 0?Math.floor(r.x):n.x,i=n.y===void 0?Math.floor(r.y):n.y,l=Math.ceil(n.width||r.x+r.width-a),o=Math.ceil(n.height||r.y+r.height-i),c=n.pixelRatio,d=n.offset||0,u=n.drawBorder||!1,h=n.hitCanvasPixelRatio||1;if(l<=0||o<=0||!isFinite(a+i+l+o))return er.error(`Can not cache the node. Its size is 0 or its bounds are not finite numbers (${a}, ${i}, ${l}x${o}). Caching is skipped.`),this;l+=d*2,o+=d*2,a-=d,i-=d;const m=new b7({pixelRatio:c,width:l,height:o}),f=new b7({pixelRatio:c,width:0,height:0,willReadFrequently:!0}),g=m.getContext();m.isCache=!0,this._releaseCanvasCache(),this._filterUpToDate=!1,n.imageSmoothingEnabled===!1&&(m.getContext()._context.imageSmoothingEnabled=!1,f.getContext()._context.imageSmoothingEnabled=!1),g.save(),g.translate(-a,-i),this._isUnderCache=!0,this._clearSelfAndDescendantCache(yQ);try{this.drawScene(m,this)}catch(x){throw er.releaseCanvas(m._canvas),x}finally{this._isUnderCache=!1,this._clearSelfAndDescendantCache(yQ),g.restore(),m._releaseIsolationCanvas()}return u&&(g.save(),g.beginPath(),g.rect(0,0,l,o),g.closePath(),g.setAttr("strokeStyle","red"),g.setAttr("lineWidth",5),g.stroke(),g.restore()),this._canvasCache={scene:m,filter:f,hit:null,hitConfig:{pixelRatio:h,width:l,height:o},x:a,y:i},this._clearSelfAndDescendantCache(),this._requestDraw(),this}_getCachedHitCanvas(t){if(t===this)return null;const n=this._getCanvasCache();if(!n)return null;if(n.hit)return n.hit;const r=new Srt(n.hitConfig);r.isCache=!0;const a=r.getContext();return a.save(),a.translate(-n.x,-n.y),this.drawHit(r,this),a.restore(),n.hit=r,r}isCached(){return!!this._canvasCache}getClientRect(t){throw new Error('abstract "getClientRect" method call')}_getCachedSceneRect(t){const n=t._forDrawing&&!this._isUnderCache&&this._getCanvasCache();if(!n)return;const r={x:n.x,y:n.y,width:n.scene.width/n.scene.pixelRatio,height:n.scene.height/n.scene.pixelRatio};return t.skipTransform?r:this._transformedRect(r,t.relativeTo)}_transformedRect(t,n){return this.getAbsoluteTransform(n)._getTransformedRect(t)}_drawCachedSceneCanvas(t){t.save(),t._applyOpacity(this),t._applyGlobalCompositeOperation(this);const n=this._getCanvasCache();t.translate(n.x,n.y);const r=this._getCachedSceneCanvas(),a=r.pixelRatio;t.drawImage(r._canvas,0,0,r.width/a,r.height/a),t.restore()}_drawCachedHitCanvas(t,n){const r=this._getCanvasCache();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(),n=this._getCanvasCache(),r=n.scene,a=n.filter,i=a.getContext(),l,o,c,d;if(!t||t.length===0)return r;if(this._filterUpToDate)return a;let u=!0;for(let m=0;mg===void 0?f:`${Number(g)*h}${x}`);return i.clear(),i.save(),i.setAttr("filter",m),i.drawImage(r._canvas,0,0,r.getWidth()/h,r.getHeight()/h),i.restore(),this._filterUpToDate=!0,a}try{for(l=t.length,i.clear(),i.drawImage(r._canvas,0,0,r.getWidth()/h,r.getHeight()/h),o=i.getImageData(0,0,a.getWidth(),a.getHeight()),c=0;c{this.isAncestorOf(t.node)&&ph._dragElements.delete(n)}),this._remove(),this}_clearCaches(){this._clearSelfAndDescendantCache(wA),this._clearSelfAndDescendantCache(yQ),this._clearSelfAndDescendantCache(q_t),this._clearSelfAndDescendantCache(FWe),this._clearSelfAndDescendantCache(RWe)}_remove(){const t=this.getParent();t&&t.children&&(t.children.splice(this.index,1),t._setChildrenIndices(),this.parent=null),this._clearCaches()}destroy(){return this._fire("destroy",{target:this}),Hon(this),this.remove(),this.clearCache(),this}getAttr(t){const n="get"+er._capitalize(t);return er._isFunction(this[n])?this[n]():this.attrs[t]}getAncestors(){let t=this.getParent(),n=[];for(;t;)n.push(t),t=t.getParent();return n}getAttrs(){return this.attrs||{}}setAttrs(t){return this._batchTransformChanges(()=>{let n,r;if(!t)return this;for(n in t)n!==Zon&&(r=$_t+er._capitalize(n),er._isFunction(this[r])?this[r](t[n]):this._setAttr(n,t[n]))}),this}isListening(){return this._getCache(RWe,this._isListening)}_isListening(t){if(!this.listening())return!1;const r=this.getParent();return r&&r!==t&&this!==t?r._isListening(t):!0}isVisible(){return this._getCache(FWe,this._isVisible)}_isVisible(t){if(!this.visible())return!1;const r=this.getParent();return r&&r!==t&&this!==t?r._isVisible(t):!0}shouldDrawHit(t){return t?this._isVisible(t)&&this._isListening(t):this.isListening()&&this.isVisible()}show(){return this.visible(!0),this}hide(){return this.visible(!1),this}getZIndex(){return this.index||0}getAbsoluteZIndex(){let t=this.getDepth(),n=this,r=0,a,i,l,o;function c(u){for(a=[],i=u.length,l=0;l0&&a[0].getDepth()<=t&&c(a)}const d=this.getStage();return n.nodeType!==aln&&d&&c(d.children),r}getDepth(){let t=0,n=this.parent;for(;n;)t++,n=n.parent;return t}_batchTransformChanges(t){if(this._batchingTransformChange){t();return}this._batchingTransformChange=!0;try{t()}finally{this._batchingTransformChange=!1,this._needClearTransformCache&&(this._needClearTransformCache=!1,this._clearCache(ZM),this._clearSelfAndDescendantCache(wA))}}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 n=t.getPointerPosition();if(!n)return null;const r=this.getAbsoluteTransform().copy();return r.invert(),r.point(n)}getAbsolutePosition(t){const n=this.getAbsoluteTransform(t).getMatrix(),r=new _0,a=this.offset();return r.m=n.slice(),r.translate(a.x,a.y),r.getTranslation()}setAbsolutePosition(t){const{x:n,y:r,...a}=this._clearTransform();this.attrs.x=n,this.attrs.y=r,this._clearCache(ZM);const i=this._getAbsoluteTransform().copy(),l=i.isInvertible();i.invert(),i.translate(t.x,t.y);const{x:o,y:c}=i.getTranslation();return this._setTransform(a),l?this.setPosition({x:this.attrs.x+o,y:this.attrs.y+c}):er.warn("Cannot set the absolute position: the absolute transform is not invertible (an ancestor has a zero scale)."),this._clearCache(ZM),this._clearSelfAndDescendantCache(wA),this}_setTransform(t){let n;for(n in t)this.attrs[n]=t[n]}_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 n=t.x,r=t.y,a=this.x(),i=this.y();return n!==void 0&&(a+=n),r!==void 0&&(i+=r),this.setPosition({x:a,y:i}),this}rotate(t){return this.rotation(this.rotation()+t),this}moveToTop(){if(!this.parent)return er.warn("Node has no parent. moveToTop function is ignored."),!1;const t=this.index,n=this.parent.children.length;return t0?(this.parent.children.splice(t,1),this.parent.children.splice(t-1,0,this),this.parent._setChildrenIndices(),!0):!1}moveToBottom(){if(!this.parent)return er.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 er.warn("Node has no parent. zIndex parameter is ignored."),this;(t<0||t>=this.parent.children.length)&&er.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 n=this.index;return this.parent.children.splice(n,1),this.parent.children.splice(t,0,this),this.parent._setChildrenIndices(),this}getAbsoluteOpacity(){return this._getCache(yQ,this._getAbsoluteOpacity)}_getAbsoluteOpacity(){let t=this.opacity();const n=this.getParent();return n&&!n._isUnderCache&&(t*=n.getAbsoluteOpacity()),t}moveTo(t){return this.getParent()!==t&&(this._remove(),t.add(this)),this}toObject(){var t;const n=this.getAttrs();let r,a,i;const l={attrs:{},className:this.getClassName()};for(r in n)a=n[r],i=er.isObject(a)&&!er._isPlainObject(a)&&!er._isArray(a),!i&&(((t=this["get"+er._capitalize(r)])===null||t===void 0?void 0:t._def)!==a||r==="brightness"||r==="threshold")&&(l.attrs[r]=r==="filters"&&er._isArray(a)?a.filter(o=>typeof o=="string"):er.isObject(a)?er._prepareToStringify(a):a);return l}toJSON(){return JSON.stringify(this.toObject())}getParent(){return this.parent}findAncestors(t,n,r){const a=[];n&&this._isMatch(t)&&a.push(this);let i=this.parent;for(;i;){if(i===r)return a;i._isMatch(t)&&a.push(i),i=i.parent}return a}isAncestorOf(t){return!1}findAncestor(t,n,r){return this.findAncestors(t,n,r)[0]}_isMatch(t){if(!t)return!1;if(typeof t=="function")return t(this);let n=t.replace(/ /g,"").split(","),r=n.length,a,i;for(a=0;a{try{const{callback:a,...i}=t||{};er._urlToImage(this.toDataURL(i),function(l){n(l),a==null||a(l)},r)}catch(a){r(a)}})}toBlob(t){return new Promise((n,r)=>{try{this.toCanvas(t).toBlob(a=>{var i;if(!a){r(new Error("Konva: toBlob() failed, the canvas was not encoded"));return}n(a),(i=t==null?void 0:t.callback)===null||i===void 0||i.call(t,a)},t==null?void 0:t.mimeType,t==null?void 0:t.quality)}catch(a){r(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():Qo.dragDistance}_off(t,n,r){let a=this.eventListeners[t],i,l,o;for(i=0;i=0)||ph._dragElements.has(this._id))return;let a=!1;ph._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 n=ph._dragElements.get(this._id),r=n&&n.dragStatus==="dragging",a=n&&n.dragStatus==="ready";r?this.stopDrag():a&&ph._dragElements.delete(this._id)}}_dragCleanup(){this.off("mousedown.konva"),this.off("touchstart.konva")}isClientRectOnScreen(t={x:0,y:0}){const n=this.getStage();if(!n)return!1;const r={x:-t.x,y:-t.y,width:n.width()+2*t.x,height:n.height()+2*t.y};return er.haveIntersection(r,this.getClientRect())}static create(t,n){return er._isString(t)&&(t=JSON.parse(t)),this._createNode(t,n)}static _createNode(t,n){let r=XM.prototype.getClassName.call(t),a=t.children,i,l,o;if(n&&(t.attrs.container=n),!Qo[r]){const d=a?"Group":"Shape";er.warn('Can not find a node with class name "'+r+`". Fallback to "${d}".`),r=d}const c=Qo[r];if(i=new c(t.attrs),a)for(l=a.length,o=0;o0}removeChildren(){return this.children.forEach(t=>{t.parent=null,t.index=0,t.remove()}),this.children=[],this._requestDraw(),this}destroyChildren(){return this.children.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 r=0;r0?n[0]:void 0}_generalFind(t,n){const r=[];return this._descendants(a=>{const i=a._isMatch(t);return i&&r.push(a),!!(i&&n)}),r}_descendants(t){let n=!1;for(const r of this.children){if(n=t(r),n)return!0;if(r.hasChildren()&&(n=r._descendants(t),n))return!0}return!1}toObject(){const t=zi.prototype.toObject.call(this);return t.children=[],this.children.forEach(n=>{t.children.push(n.toObject())}),t}isAncestorOf(t){let n=t.getParent();for(;n;){if(n._id===this._id)return!0;n=n.getParent()}return!1}clone(t){const n=zi.prototype.clone.call(this,t);return this.children.forEach(function(r){n.add(r.clone())}),n}getAllIntersections(t){const n=[];return this.find("Shape").forEach(r=>{r.isVisible()&&r.intersects(t)&&n.push(r)}),n}_clearSelfAndDescendantCache(t){var n;const r=t===void 0||t==="absoluteTransform";r&&zi._absTransformCascadeDepth++;try{if(super._clearSelfAndDescendantCache(t),t==="absoluteTransform"&&this.isCached())return;(n=this.children)===null||n===void 0||n.forEach(function(a){a._clearSelfAndDescendantCache(t)})}finally{if(r&&--zi._absTransformCascadeDepth===0){const a=zi._pendingAfterCascade;if(a.length){zi._pendingAfterCascade=[];for(let i=0;i{const t=er._getEventType(s);if(t==="pointer")return Qo.pointerEventsEnabled&&HBe.pointer;if(t==="touch")return HBe.touch;if(t==="mouse")return HBe.mouse};function H_t(s={}){return(s.clipFunc||s.clipWidth||s.clipHeight)&&er.warn("Stage does not support clipping. Please use clip for Layers or Groups."),s}const fln="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);",$ee=[],G_t=new WeakSet,W_t=s=>{!s||G_t.has(s)||(G_t.add(s),ph._listenToWindow(s),s.document.addEventListener("visibilitychange",()=>{$ee.forEach(t=>{t.batchDraw()})}))};let wie=class extends j2{constructor(t){super(H_t(t)),this._pointerPositions=[],this._changedPointerPositions=[],this._pointerStates=new Map,this._lastClicks={},this._buildDOM(),this._bindContentEvents(),$ee.push(this),this.on("widthChange.konva heightChange.konva",this._resizeDOM),this.on("visibleChange.konva",this._checkVisibility),this.on("clipWidthChange.konva clipHeightChange.konva clipFuncChange.konva",()=>{H_t(this.attrs)}),this._checkVisibility()}_validateAdd(t){const n=t.getType()==="Layer",r=t.getType()==="FastLayer";n||r||er.throw("You may only add layers to the stage.")}_checkVisibility(){if(!this.content)return;const t=this.visible()?"":"none";this.content.style.display=t}_getOwnerWindow(){var t;const n=this.content||this.container();return((t=n==null?void 0:n.ownerDocument)===null||t===void 0?void 0:t.defaultView)||(Qo.isBrowser?window:null)}setContainer(t){if(typeof t===cln){let n;if(t.charAt(0)==="."){const r=t.slice(1);t=document.getElementsByClassName(r)[0]}else t.charAt(0)!=="#"?n=t:n=t.slice(1),t=document.getElementById(n);if(!t)throw"Can not find container in document with id "+n}return this._setAttr("container",t),this.content&&(this.content.parentElement&&this.content.parentElement.removeChild(this.content),t.appendChild(this.content),W_t(this._getOwnerWindow())),this}shouldDrawHit(){return!0}clear(){const t=this.children,n=t.length;for(let r=0;r-1&&$ee.splice(r,1),er.releaseCanvas(this.bufferHitCanvas._canvas),this}getPointerPosition(){const t=this._pointerPositions[0]||this._changedPointerPositions[0];return t?{x:t.x,y:t.y}:(er.warn(fln),null)}_getPointerById(t){return this._pointerPositions.find(n=>n.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 n=new b7({width:t.width,height:t.height,pixelRatio:t.pixelRatio||1}),r=n.getContext()._context,a=this.children;return(t.x||t.y)&&r.translate(-1*t.x,-1*t.y),a.forEach(function(i){if(!i.isVisible())return;const l=i._toKonvaCanvas(t);r.drawImage(l._canvas,t.x,t.y,l.getWidth()/l.getPixelRatio(),l.getHeight()/l.getPixelRatio()),er.releaseCanvas(l._canvas)}),n}getIntersection(t){if(!t)return null;const n=this.children,r=n.length,a=r-1;for(let i=a;i>=0;i--){const l=n[i].getIntersection(t);if(l)return l}return null}_resizeDOM(){const t=this.width(),n=this.height();this.content&&(this.content.style.width=t+V_t,this.content.style.height=n+V_t),this.children.forEach(r=>{r._setSize({width:t,height:n}),r.draw()})}add(t,...n){if(arguments.length>1){for(let a=0;ahln&&er.warn("The stage has "+r+" 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(),Qo.isBrowser&&this.content.appendChild(t.canvas._canvas),this}getParent(){return null}getLayer(){return null}hasPointerCapture(t){return bGt(t,this)}setPointerCapture(t){_Gt(t,this)}releaseCapture(t){AV(t,this)}getLayers(){return this.getChildren()}_bindContentEvents(){Qo.isBrowser&&mln.forEach(([t,n])=>{this.content.addEventListener(t,r=>{this._batchEvents(()=>this[n](r))},{passive:!1})})}_batchEvents(t){er._batchEvents(this.eventBatchFunc(),t)}_pointerenter(t){this.setPointersPositions(t);const n=bR(t.type);n&&this._fire(n.pointerenter,{evt:t,target:this,currentTarget:this})}_pointerover(t){this.setPointersPositions(t);const n=bR(t.type);n&&this._fire(n.pointerover,{evt:t,target:this,currentTarget:this})}_pointerEventsEnabled(){if(Qo.hitOnDragEnabled)return!0;for(const{node:t,dragStatus:n}of ph._dragElements.values())if(n==="dragging"&&t.getStage()===this)return!1;return!this.getLayers().some(t=>{var n;return(n=Qo.Transformer)===null||n===void 0?void 0:n._isLayerTransforming(t)})}_cancelClick(t,n){const r=n?[n]:["mouse","touch","pointer"];for(const a of r){const i=this._pointerStates.get(`${a}:${t}`);i&&(i.clickStartShape=void 0,i.relatedPointer&&(i.relatedPointer.clickStartShape=void 0))}}_pointerleave(t){var n,r;const a=bR(t.type),i=er._getEventType(t.type);if(!a)return;this.setPointersPositions(t);const l=(n=this._changedPointerPositions[0])===null||n===void 0?void 0:n.id,o=`${i}:${l}`,c=this._pointerStates.get(o),d=((r=c==null?void 0:c.targetShape)===null||r===void 0?void 0:r.getStage())===this?c.targetShape:void 0,u=this._pointerEventsEnabled()||t.pointerType==="touch"&&!(c!=null&&c.downPosition);u&&((c==null?void 0:c.clickStartShape)!==void 0?c.targetShape=void 0:this._pointerStates.delete(o)),d&&u?(d._fireAndBubble(a.pointerout,{evt:t,pointerId:l}),d._fireAndBubble(a.pointerleave,{evt:t,pointerId:l}),this._fire(a.pointerleave,{evt:t,target:this,currentTarget:this})):u&&(this._fire(a.pointerleave,{evt:t,target:this,currentTarget:this}),this._fire(a.pointerout,{evt:t,target:this,currentTarget:this})),this.pointerPos=null,this._pointerPositions=[],this._changedPointerPositions=[],this._pointerEventType=void 0}_pointerdown(t){const n=bR(t.type),r=er._getEventType(t.type);if(!n)return;this.setPointersPositions(t);let a=!1;this._changedPointerPositions.forEach(i=>{var l;const o=this.getIntersection(i),c=`${r}:${i.id}`,d={targetShape:(l=this._pointerStates.get(c))===null||l===void 0?void 0:l.targetShape,clickStartShape:o&&o.isListening()?o:null,lastClick:this._lastClicks[r],downPosition:i,pointerType:t.pointerType};if(this._pointerStates.delete(c),r!=="pointer")for(const[h,m]of[...this._pointerStates].reverse()){if(!h.startsWith("pointer:")||!m.downPosition||r==="touch"&&m.relatedPointer)continue;if(r==="mouse"?m.pointerType!=="touch":m.pointerType==="touch"&&m.downPosition.x===i.x&&m.downPosition.y===i.y){d.relatedPointer=m,m.relatedPointer=d,m.clickStartShape===void 0&&(d.clickStartShape=void 0);break}}this._pointerStates.set(c,d);for(const h of ph._dragElements.values())h.dragStatus==="dragging"&&(h.pointerId===void 0||h.pointerEventType===r&&h.pointerId===i.id||h.pointerEventType==="mouse"&&r==="pointer"&&d.pointerType!=="touch")&&h.node.getStage()===this&&(h.pointerId===void 0&&r!=="pointer"&&(h.pointerId=i.id,h.pointerEventType=r),this._cancelClick(i.id,r));if(!o||!o.isListening())return;Qo.capturePointerEventsEnabled&&o.setPointerCapture(i.id),o._fireAndBubble(n.pointerdown,{evt:t,pointerId:i.id}),a=!0;const u=t.type.indexOf("touch")>=0;o.preventDefault()&&t.cancelable&&u&&t.preventDefault()}),a||this._fire(n.pointerdown,{evt:t,target:this,currentTarget:this,pointerId:this._changedPointerPositions[0].id})}_pointermove(t){const n=bR(t.type),r=er._getEventType(t.type);if(!n)return;const a=t.type.indexOf("touch")>=0||t.pointerType==="touch";if(t.cancelable&&a){for(const{node:c,dragStatus:d}of ph._dragElements.values())if(d==="dragging"&&c.getStage()===this&&c.preventDefault()){t.preventDefault();break}}if(this.setPointersPositions(t),!this._pointerEventsEnabled())return;const l={};let o=!1;this._changedPointerPositions.forEach(c=>{var d;const u=`${r}:${c.id}`;let h=this._pointerStates.get(u);h||(h={},this._pointerStates.set(u,h));const m=Tde(c.id)||this.getIntersection(c),f=h.targetShape===m||((d=h.targetShape)===null||d===void 0?void 0:d.getStage())===this?h.targetShape:void 0,g=c.id,x={evt:t,pointerId:g},y=f!==m;h.targetShape=m&&m.isListening()?m:void 0,y&&f&&(f._fireAndBubble(n.pointerout,{...x},m),f._fireAndBubble(n.pointerleave,{...x},m)),m&&m.isListening()?(o=!0,y&&(m._fireAndBubble(n.pointerover,{...x},f),m._fireAndBubble(n.pointerenter,{...x},f)),l[m._id]||(l[m._id]=!0,m._fireAndBubble(n.pointermove,{...x}))):f&&this._fire(n.pointerover,{evt:t,target:this,currentTarget:this,pointerId:g})}),o||this._fire(n.pointermove,{evt:t,target:this,currentTarget:this,pointerId:this._changedPointerPositions[0].id})}_pointerup(t){const n=bR(t.type),r=er._getEventType(t.type);if(!n)return;this.setPointersPositions(t);const a={};let i=!1;this._changedPointerPositions.forEach(l=>{var o;const c=`${r}:${l.id}`,d=this._pointerStates.get(c),u=(d==null?void 0:d.clickStartShape)!==void 0,h=d==null?void 0:d.clickStartShape;d!=null&&d.targetShape&&r!=="touch"?this._pointerStates.set(c,{targetShape:d.targetShape}):this._pointerStates.delete(c);const m=Tde(l.id)||this.getIntersection(l),f=m&&a[m._id];m&&(m.releaseCapture(l.id),a[m._id]=!0);const g=l.id,x={evt:t,pointerId:g},y=m&&m.isListening()?m:null,v=this._lastClicks[r],b=u&&(!y||h===y),w=b&&v&&(d==null?void 0:d.lastClick)===v&&v.shape===y&&Date.now()-v.time{var a;const i=er._getEventType(t.type),l=`${i}:${r.id}`;this._cancelClick(r.id,i);const o=(a=this._pointerStates.get(l))===null||a===void 0?void 0:a.targetShape;o&&i!=="touch"?this._pointerStates.set(l,{targetShape:o}):this._pointerStates.delete(l);const c=Tde(r.id)||this.getIntersection(r),d={evt:t,pointerId:r.id};c?(n&&c._fireAndBubble(n.pointercancel,{...d}),c._fireAndBubble(iq,{...d})):n&&this._fire(n.pointercancel,{...d,target:this,currentTarget:this}),AV(r.id),n&&i==="touch"&&(o==null?void 0:o.getStage())===this&&(o._fireAndBubble(n.pointerout,{...d}),o._fireAndBubble(n.pointerleave,{...d}))})}_lostpointercapture(t){Tde(t.pointerId,this)&&AV(t.pointerId)}setPointersPositions(t){const n=this._getContentPosition();let r=null,a=null;t=t||window.event,t.touches!==void 0?(this._pointerEventType="touch",this._pointerPositions=[],this._changedPointerPositions=[],Array.prototype.forEach.call(t.touches,i=>{this._pointerPositions.push({id:i.identifier,x:(i.clientX-n.left)/n.scaleX,y:(i.clientY-n.top)/n.scaleY})}),Array.prototype.forEach.call(t.changedTouches||t.touches,i=>{this._changedPointerPositions.push({id:i.identifier,x:(i.clientX-n.left)/n.scaleX,y:(i.clientY-n.top)/n.scaleY})})):(this._pointerEventType=t.pointerId===void 0?"mouse":"pointer",r=(t.clientX-n.left)/n.scaleX,a=(t.clientY-n.top)/n.scaleY,this.pointerPos={x:r,y:a},this._pointerPositions=[{x:r,y:a,id:er._getFirstPointerId(t)}],this._changedPointerPositions=[{x:r,y:a,id:er._getFirstPointerId(t)}])}_setPointerPosition(t){er.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.bufferHitCanvas=new Srt({pixelRatio:1,width:0,height:0}),!Qo.isBrowser)return;const t=this.container();if(!t)throw"Stage has no container. A container is required.";t.innerHTML="",this.content=t.ownerDocument.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),W_t(this._getOwnerWindow()),this._resizeDOM()}cache(){return er.warn("Cache function is not allowed for stage. You may use cache only for layers, groups and shapes."),this}clearCache(){return this}batchDraw(){var t;return(t=this.children)===null||t===void 0||t.forEach(function(n){n.batchDraw()}),this}};wie.prototype.nodeType=lln;Yg(wie);Tn.addGetterSetter(wie,"container");Tn.addGetterSetter(wie,"eventBatchFunc");const IGt="hasShadow",LGt="hasFill",RGt="hasStroke",DGt="shadowRGBA",FGt="patternImage",OGt="linearGradient",zGt="radialGradient";let Lde;function GBe(){return Lde||(Lde=er.createCanvasElement().getContext("2d"),Lde)}const Uee={};function BGt(s){const t=this.attrs.fillRule;t?s.fill(t):s.fill()}function $Gt(s){s.stroke()}function pln(){this._clearCache(IGt)}function gln(){this._clearCache(LGt)}function xln(){this._clearCache(RGt)}function yln(){this._clearCache(DGt)}function vln(){this._clearCache(FGt)}function bln(){this._clearCache(OGt)}function _ln(){this._clearCache(zGt)}let li=class UGt extends zi{constructor(t){super(t);let n,r=0;for(;n=er.getHitColor(),!(n&&!(n in Uee));)if(r++,r>=1e4){er.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."),n=er.getRandomColor();break}this.colorKey=n,Uee[n]=this}getContext(){return er.warn("shape.getContext() method is deprecated. Please do not use it."),this.getLayer().getContext()}getCanvas(){return er.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(IGt,this._hasShadow)}_hasShadow(){return this.shadowEnabled()&&this.shadowOpacity()!==0&&!!(this.shadowColor()||this.shadowBlur()||this.shadowOffsetX()||this.shadowOffsetY())}_getFillPattern(){return this._getCache(FGt,this.__getFillPattern)}__getFillPattern(){if(this.fillPatternImage()){const n=GBe().createPattern(this.fillPatternImage(),this.fillPatternRepeat()||"repeat");if(n&&n.setTransform){const r=new _0;r.translate(this.fillPatternX(),this.fillPatternY()),r.rotate(Qo.getAngle(this.fillPatternRotation())),r.scale(this.fillPatternScaleX(),this.fillPatternScaleY()),r.translate(-1*this.fillPatternOffsetX(),-1*this.fillPatternOffsetY());const a=r.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);n.setTransform(i)}return n}}_getLinearGradient(){return this._getCache(OGt,this.__getLinearGradient)}__getLinearGradient(){const t=this.fillLinearGradientColorStops();if(t){const n=GBe(),r=this.fillLinearGradientStartPoint(),a=this.fillLinearGradientEndPoint(),i=n.createLinearGradient(r.x,r.y,a.x,a.y);for(let l=0;l0}destroy(){return zi.prototype.destroy.call(this),delete Uee[this.colorKey],delete this.colorKey,this}_useBufferCanvas(t,n=this.getAbsoluteOpacity()){var r;if(!((r=this.attrs.perfectDrawEnabled)!==null&&r!==void 0?r:!0))return!1;const i=t||this.hasFill(),l=this.hasStroke(),o=!this._isUnderCache&&n!==1;if(i&&l&&o)return!0;const c=this.hasShadow(),d=this.shadowForStrokeEnabled();return!!(i&&l&&c&&d)}setStrokeHitEnabled(t){er.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.attrs.selfRectFunc;if(t)return{...t.call(this,this)};const n=this.size();return{x:this._centroid?-n.width/2:0,y:this._centroid?-n.height/2:0,width:n.width,height:n.height}}_getSelfRectForDrawing(){return this.getSelfRect()}getClientRect(t={}){const n=this._getCachedSceneRect(t);if(n)return n;const r=t.skipTransform,a=t.relativeTo,i=t._forDrawing,l=i?this.strokeScaleEnabled()?new _0()._getTransformedRect(this._getSelfRectForDrawing()):this._transformedRect(this._getSelfRectForDrawing(),a):this.getSelfRect(),c=!t.skipStroke&&this.hasStroke()?i?this._getStrokePadding()*2:this.strokeWidth():0;let d=c,u=c,h;if(!i&&c&&!this.strokeScaleEnabled()){let f=this;for(;f&&!f.isCached()&&!f._isUnderCache;)f=f.parent;const[g,x,y,v]=this.getAbsoluteTransform(f).getMatrix(),b=Math.abs(g*v-x*y);if(b)d*=Math.hypot(y,v)/b,u*=Math.hypot(g,x)/b;else if(!r&&(d=u=0,h=f?f.getAbsoluteTransform().copy():new _0,a)){const w=a.getAbsoluteTransform(),[S,C,E,I]=w.getMatrix();h=S*I-C*E?w.copy().invert().multiply(h):new _0}}let m={x:l.x-d/2,y:l.y-u/2,width:l.width+d,height:l.height+u};if(i&&this.strokeScaleEnabled()&&(m=this._transformedRect(m,a)),!t.skipShadow&&this.hasShadow()){const f=i?this.getAbsoluteScale():{x:1,y:1},g=this.shadowOffsetX()*f.x,x=this.shadowOffsetY()*f.y,y=this.shadowBlur()*(i?2*Math.min(Math.abs(f.x),Math.abs(f.y)):1);m.x+=Math.min(0,g)-y,m.y+=Math.min(0,x)-y,m.width+=Math.abs(g)+y*2,m.height+=Math.abs(x)+y*2}if(i)return m;if(!r){const f=this._transformedRect(m,a);if(h){const[g,x,y,v]=h.getMatrix(),b=c*Math.hypot(g,y)/2,w=c*Math.hypot(x,v)/2;f.x-=b,f.y-=w,f.width+=b*2,f.height+=w*2}return f}return m}_getStrokePadding(t=this.miterLimit()||10){return this.attrs.sceneFunc&&(t=this.miterLimit()||10),Math.abs(this.strokeWidth())/2*Math.max(this.lineCap()==="square"?Math.SQRT2:1,(this.lineJoin()||"miter")==="miter"?t:1)}drawScene(t,n){const r=this.getLayer(),a=t||r.getCanvas(),i=a.getContext(),l=this._getCanvasCache(),o=this.getSceneFunc(),c=this.hasShadow(),d=n===this;if(!(n?this._isVisible(n):this.isVisible())&&!d)return this;if(l){i.save();const u=this.getAbsoluteTransform(n).getMatrix();return i.transform(u[0],u[1],u[2],u[3],u[4],u[5]),this._drawCachedSceneCanvas(i),i.restore(),this}if(!o)return this;i.save();try{if(a.width&&a.height&&this._useBufferCanvas(void 0,i._getOpacity(this))){const u=!!i._opacityRoot||!!this.attrs.selfRectFunc&&this.getSelfRect===UGt.prototype.getSelfRect||!this.attrs.sceneFunc&&!this.attrs.charRenderFunc&&fGt.has(this.constructor),h=a._prepareIsolationCanvas(u?this.getClientRect({_forDrawing:!0,relativeTo:n,skipShadow:!0}):void 0),m=h.getContext();m.save(),m._applyLineJoin(this),m._applyMiterLimit(this);const f=this.getAbsoluteTransform(n).getMatrix();m.transform(f[0],f[1],f[2],f[3],f[4],f[5]),o.call(this,m,this),m.restore(),c&&i._applyShadow(this),d||(i._applyOpacity(this),i._applyGlobalCompositeOperation(this)),i._drawDeviceBuffer(h)}else{if(i._applyLineJoin(this),i._applyMiterLimit(this),!d){const u=this.getAbsoluteTransform(n).getMatrix();i.transform(u[0],u[1],u[2],u[3],u[4],u[5]),i._applyOpacity(this),i._applyGlobalCompositeOperation(this)}c&&i._applyShadow(this),o.call(this,i,this)}}catch(u){throw a._releaseIsolationCanvas(),u}finally{i.restore()}return this}drawHit(t,n){if(!this.shouldDrawHit(n))return this;const r=this.getLayer(),a=t||r.hitCanvas,i=a&&a.getContext(),l=this.hitFunc()||this.sceneFunc(),o=this._getCachedHitCanvas(n);if(this.colorKey||er.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()"),o){i.save();const d=this.getAbsoluteTransform(n).getMatrix();return i.transform(d[0],d[1],d[2],d[3],d[4],d[5]),this._drawCachedHitCanvas(i,o),i.restore(),this}if(!l)return this;if(i.save(),i._applyLineJoin(this),i._applyMiterLimit(this),!(this===n)){const d=this.getAbsoluteTransform(n).getMatrix();i.transform(d[0],d[1],d[2],d[3],d[4],d[5])}try{l.call(this,i,this)}finally{i.restore()}return this}drawHitFromCache(t=0){const n=this._getCachedSceneCanvas(),r=this._getCachedHitCanvas(),a=r.getContext(),i=r.getWidth(),l=r.getHeight();a.clear(),a.drawImage(n._canvas,0,0,i/r.pixelRatio,l/r.pixelRatio);try{const o=a.getImageData(0,0,i,l),c=o.data,d=c.length,u=er._hexToRgb(this.colorKey);for(let h=0;ht?(c[h]=u.r,c[h+1]=u.g,c[h+2]=u.b,c[h+3]=255):c[h+3]=0;a.putImageData(o,0,0)}catch(o){er.error("Unable to draw hit graph from cached scene canvas. "+o.message)}return this}hasPointerCapture(t){return bGt(t,this)}setPointerCapture(t){_Gt(t,this)}releaseCapture(t){AV(t,this)}};li.prototype._fillFunc=BGt;li.prototype._strokeFunc=$Gt;li.prototype._fillFuncHit=BGt;li.prototype._strokeFuncHit=$Gt;li.prototype._centroid=!1;li.prototype.nodeType="Shape";Yg(li);li.prototype.on("shadowColorChange.konva shadowBlurChange.konva shadowOffsetXChange.konva shadowOffsetYChange.konva shadowOpacityChange.konva shadowEnabledChange.konva",pln);li.prototype.on("shadowColorChange.konva shadowOpacityChange.konva shadowEnabledChange.konva",yln);li.prototype.on("fillEnabledChange.konva fillChange.konva fillPatternImageChange.konva fillLinearGradientColorStopsChange.konva fillRadialGradientColorStopsChange.konva",gln);li.prototype.on("strokeEnabledChange.konva strokeWidthChange.konva strokeChange.konva strokeLinearGradientColorStopsChange.konva",xln);li.prototype.on("fillPriorityChange.konva fillPatternImageChange.konva fillPatternRepeatChange.konva fillPatternScaleXChange.konva fillPatternScaleYChange.konva fillPatternOffsetXChange.konva fillPatternOffsetYChange.konva fillPatternXChange.konva fillPatternYChange.konva fillPatternRotationChange.konva",vln);li.prototype.on("fillPriorityChange.konva fillLinearGradientColorStopsChange.konva fillLinearGradientStartPointXChange.konva fillLinearGradientStartPointYChange.konva fillLinearGradientEndPointXChange.konva fillLinearGradientEndPointYChange.konva",bln);li.prototype.on("fillPriorityChange.konva fillRadialGradientColorStopsChange.konva fillRadialGradientStartPointXChange.konva fillRadialGradientStartPointYChange.konva fillRadialGradientEndPointXChange.konva fillRadialGradientEndPointYChange.konva fillRadialGradientStartRadiusChange.konva fillRadialGradientEndRadiusChange.konva",_ln);Tn.addGetterSetter(li,"stroke",void 0,wGt());Tn.addGetterSetter(li,"strokeWidth",2,Ti());Tn.addGetterSetter(li,"fillAfterStrokeEnabled",!1);Tn.addGetterSetter(li,"hitStrokeWidth","auto",Art());Tn.addGetterSetter(li,"strokeHitEnabled",!0,kC());Tn.addGetterSetter(li,"perfectDrawEnabled",!0,kC());Tn.addGetterSetter(li,"shadowForStrokeEnabled",!0,kC());Tn.addGetterSetter(li,"lineJoin");Tn.addGetterSetter(li,"lineCap");Tn.addGetterSetter(li,"miterLimit");Tn.addGetterSetter(li,"sceneFunc");Tn.addGetterSetter(li,"hitFunc");Tn.addGetterSetter(li,"selfRectFunc");Tn.addGetterSetter(li,"dash");Tn.addGetterSetter(li,"dashOffset",0,Ti());Tn.addGetterSetter(li,"shadowColor",void 0,KB());Tn.addGetterSetter(li,"shadowBlur",0,Ti());Tn.addGetterSetter(li,"shadowOpacity",1,Ti());Tn.addComponentsGetterSetter(li,"shadowOffset",["x","y"]);Tn.addGetterSetter(li,"shadowOffsetX",0,Ti());Tn.addGetterSetter(li,"shadowOffsetY",0,Ti());Tn.addGetterSetter(li,"fillPatternImage");Tn.addGetterSetter(li,"fill",void 0,wGt());Tn.addGetterSetter(li,"fillPatternX",0,Ti());Tn.addGetterSetter(li,"fillPatternY",0,Ti());Tn.addGetterSetter(li,"fillLinearGradientColorStops");Tn.addGetterSetter(li,"strokeLinearGradientColorStops");Tn.addGetterSetter(li,"fillRadialGradientStartRadius",0);Tn.addGetterSetter(li,"fillRadialGradientEndRadius",0);Tn.addGetterSetter(li,"fillRadialGradientColorStops");Tn.addGetterSetter(li,"fillPatternRepeat","repeat");Tn.addGetterSetter(li,"fillEnabled",!0);Tn.addGetterSetter(li,"strokeEnabled",!0);Tn.addGetterSetter(li,"shadowEnabled",!0);Tn.addGetterSetter(li,"dashEnabled",!0);Tn.addGetterSetter(li,"strokeScaleEnabled",!0);Tn.addGetterSetter(li,"fillPriority","color");Tn.addComponentsGetterSetter(li,"fillPatternOffset",["x","y"]);Tn.addGetterSetter(li,"fillPatternOffsetX",0,Ti());Tn.addGetterSetter(li,"fillPatternOffsetY",0,Ti());Tn.addComponentsGetterSetter(li,"fillPatternScale",["x","y"]);Tn.addGetterSetter(li,"fillPatternScaleX",1,Ti());Tn.addGetterSetter(li,"fillPatternScaleY",1,Ti());Tn.addComponentsGetterSetter(li,"fillLinearGradientStartPoint",["x","y"]);Tn.addComponentsGetterSetter(li,"strokeLinearGradientStartPoint",["x","y"]);Tn.addGetterSetter(li,"fillLinearGradientStartPointX",0);Tn.addGetterSetter(li,"strokeLinearGradientStartPointX",0);Tn.addGetterSetter(li,"fillLinearGradientStartPointY",0);Tn.addGetterSetter(li,"strokeLinearGradientStartPointY",0);Tn.addComponentsGetterSetter(li,"fillLinearGradientEndPoint",["x","y"]);Tn.addComponentsGetterSetter(li,"strokeLinearGradientEndPoint",["x","y"]);Tn.addGetterSetter(li,"fillLinearGradientEndPointX",0);Tn.addGetterSetter(li,"strokeLinearGradientEndPointX",0);Tn.addGetterSetter(li,"fillLinearGradientEndPointY",0);Tn.addGetterSetter(li,"strokeLinearGradientEndPointY",0);Tn.addComponentsGetterSetter(li,"fillRadialGradientStartPoint",["x","y"]);Tn.addGetterSetter(li,"fillRadialGradientStartPointX",0);Tn.addGetterSetter(li,"fillRadialGradientStartPointY",0);Tn.addComponentsGetterSetter(li,"fillRadialGradientEndPoint",["x","y"]);Tn.addGetterSetter(li,"fillRadialGradientEndPointX",0);Tn.addGetterSetter(li,"fillRadialGradientEndPointY",0);Tn.addGetterSetter(li,"fillPatternRotation",0);Tn.addGetterSetter(li,"fillRule",void 0,KB());Tn.backCompat(li,{dashArray:"dash",getDashArray:"getDash",setDashArray:"setDash",drawFunc:"sceneFunc",getDrawFunc:"getSceneFunc",setDrawFunc:"setSceneFunc",drawHitFunc:"hitFunc",getDrawHitFunc:"getHitFunc",setDrawHitFunc:"setHitFunc"});const wln="beforeDraw",jln="draw",Nln=10,K_t=256;function Y_t(s,t){return s[t+3]>=128?Uee[er.getHitColorKey(s[t],s[t+1],s[t+2])]:void 0}let YB=class extends j2{constructor(t){super(t),this.canvas=new b7,this.hitCanvas=new Srt({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 n=this.getStage();return n&&n.content&&(n.content.removeChild(this.getNativeCanvasElement()),t{this._waitingForDraw=!1,this.draw()},(t=this.getStage())===null||t===void 0?void 0:t._getOwnerWindow())),this}getIntersection(t){if(!this.isListening()||!this.isVisible())return null;const n=this._getIntersection(t);if(n.shape)return n.shape;if(!n.antialiased)return null;const r=this.hitCanvas.pixelRatio,a=Math.floor(t.x*r),i=Math.floor(t.y*r),l=h=>this.hitCanvas.context.getImageData(a-h,i-h,h*2+1,h*2+1).data;let o=Nln,c=o*2+1,d=l(o),u=d[(o*c+o)*4+3];for(let h=1;h<=K_t;h++){h>o&&(o=Math.min(K_t,o*2),c=o*2+1,d=l(o));let m=0;for(let f=-h;f<=h;f++){const g=Math.abs(f)===h?1:h*2;for(let x=-h;x<=h;x+=g){const y=((f+o)*c+x+o)*4,v=Y_t(d,y);if(v)return v;m=Math.max(m,d[y+3])}}if(m<=u&&m!==255)return null;u=m}return null}_getIntersection(t){if(!this.hitCanvas.width||!this.hitCanvas.height)return{};const n=this.hitCanvas.pixelRatio,r=this.hitCanvas.context.getImageData(Math.floor(t.x*n),Math.floor(t.y*n),1,1).data,a=Y_t(r,0);return a?{shape:a}:r[3]>0?{antialiased:!0}:{}}drawScene(t,n){const r=this.getLayer(),a=t||r&&r.getCanvas();return this._fire(wln,{node:this}),this.clearBeforeDraw()&&a.getContext().clear(),j2.prototype.drawScene.call(this,a,n),a._trimIsolationCanvas(),this._fire(jln,{node:this}),this}shouldDrawHit(t){var n;if(!super.shouldDrawHit(t))return!1;if(t||Qo.hitOnDragEnabled)return!0;let r=!1;return ph._dragElements.forEach(a=>{a.dragStatus==="dragging"&&(a.node===this.getStage()||a.node.getLayer()===this)&&(r=!0)}),!r&&!(!((n=Qo.Transformer)===null||n===void 0)&&n._isLayerTransforming(this))}drawHit(t,n){const r=this.getLayer(),a=t||r&&r.hitCanvas;return!t&&r&&(r._syncHitCanvasSize(),r.clearBeforeDraw()&&r.getHitCanvas().getContext().clear()),j2.prototype.drawHit.call(this,a,n),this}enableHitGraph(){return this.hitGraphEnabled(!0),this}disableHitGraph(){return this.hitGraphEnabled(!1),this}setHitGraphEnabled(t){er.warn("hitGraphEnabled method is deprecated. Please use layer.listening() instead."),this.listening(t)}getHitGraphEnabled(t){return er.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 this.getCanvas()._releaseIsolationCanvas(),er.releaseCanvas(this.getNativeCanvasElement(),this.getHitCanvas()._canvas),super.destroy()}};YB.prototype.nodeType="Layer";Yg(YB);Tn.addGetterSetter(YB,"imageSmoothingEnabled",!0);Tn.addGetterSetter(YB,"clearBeforeDraw",!0);Tn.addOverloadedGetterSetter(YB,"hitGraphEnabled");class Ert extends YB{constructor(t){super(t),this.listening(!1),er.warn('Konva.FastLayer is deprecated. Please use "new Konva.Layer({ listening: false })" instead.')}}Ert.prototype.nodeType="FastLayer";Yg(Ert);let rB=class extends j2{_validateAdd(t){const n=t.getType();n!=="Group"&&n!=="Shape"&&er.throw("You may only add groups and shapes to groups.")}_drawChildNodes(t,n,r){if(t!=="drawScene"||!this.isolated()||r===this)return super._drawChildNodes(t,n,r);if(!n.width||!n.height)return;const a=n.getContext(),i=n._prepareIsolationCanvas(this.getClientRect({_forDrawing:!0,relativeTo:r})),l=i.getContext();l._opacityRoot=this,a.save();try{super._drawChildNodes(t,i,r),a._applyOpacity(this),a._drawDeviceBuffer(i)}catch(o){throw n._releaseIsolationCanvas(),o}finally{a.restore(),l._opacityRoot=void 0}}};Tn.addGetterSetter(rB,"isolated",!1,kC());rB.prototype.nodeType="Group";Yg(rB);var WBe;const KBe=!((WBe=aq.performance)===null||WBe===void 0)&&WBe.now?()=>aq.performance.now():Date.now;class $N{constructor(t,n){this.id=$N.animIdCounter++,this.frame={time:0,timeDiff:0,lastTime:KBe(),frameRate:0},this.func=t,this.setLayers(n)}setLayers(t){return this.layers=t?[].concat(t):[],this}getLayers(){return this.layers}addLayer(t){const n=this.layers,r=n.length;for(let a=0;a{this.animations.has(n)&&(n._updateFrameObject(KBe()),!(n.func&&n.func.call(n,n.frame)===!1)&&n.layers.forEach(r=>r&&t.add(r)))}),t.forEach(n=>n.batchDraw())}static _animationLoop(){const t=$N;t.animations.size?(t._runFrames(),er.requestAnimFrame(t._animationLoop)):t.animRunning=!1}static _handleAnimation(){this.animRunning||(this.animRunning=!0,er.requestAnimFrame(this._animationLoop))}}$N.animations=new Set;$N.animIdCounter=0;$N.animRunning=!1;const kln={node:1,duration:1,easing:1,onFinish:1,onUpdate:1,onReset:1,yoyo:1},Sln=1,Z_t=2,X_t=3,Q_t=["fill","stroke","shadowColor"];let Cln=0;function Rde(s){return er.colorToRGBA(s)||er.throw('can not tween the color "'+s+'", because it is not a valid color.')}function J_t(s,t){return{r:t.r-s.r,g:t.g-s.g,b:t.b-s.b,a:t.a-s.a}}function ewt(s,t,n){return"rgba("+Math.round(s.r+t.r*n)+","+Math.round(s.g+t.g*n)+","+Math.round(s.b+t.b*n)+","+(s.a+t.a*n)+")"}class Aln{constructor(t,n,r,a,i,l,o){this.prop=t,this.propFunc=n,this.begin=a,this._pos=a,this.duration=l,this._change=0,this.prevPos=0,this.yoyo=o,this._time=0,this._position=0,this._startTime=0,this._finish=0,this.func=r,this._change=i-this.begin,this.pause()}fire(t){const n=this[t];n&&n()}setTime(t){t>this.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=Z_t,this._startTime=this.getTimer()-this._time,this.fire("onPlay"),this.onEnterFrame()}reverse(){this.state=X_t,this._time=this.duration-this._time,this._startTime=this.getTimer()-this._time,this.fire("onReverse"),this.onEnterFrame()}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===Z_t?this.setTime(t):this.state===X_t&&this.setTime(this.duration-t)}pause(){this.state=Sln,this.fire("onPause")}getTimer(){return Date.now()}}class _g{constructor(t){const n=this,r=t.node,a=r._id,i=t.easing||qee.Linear,l=!!t.yoyo;let o,c;typeof t.duration>"u"?o=.3:t.duration===0?o=.001:o=t.duration,this.node=r,this._id=Cln++;const d=r.getLayer()||(r instanceof Qo.Stage?r.getLayers():null);d||er.error("Tween constructor have `node` that is not in a layer. Please add node into layer first."),this.anim=new $N(function(){n.tween.onEnterFrame()},d),this.tween=new Aln(c,function(u){n._tweenFunc(u)},i,0,1,o*1e3,l),this._addListeners(),_g.attrs[a]||(_g.attrs[a]={}),_g.attrs[a][this._id]||(_g.attrs[a][this._id]={}),_g.tweens[a]||(_g.tweens[a]={});for(c in t)kln[c]===void 0&&this._addAttr(c,t[c]);this.reset(),this.onFinish=t.onFinish,this.onReset=t.onReset,this.onUpdate=t.onUpdate}_addAttr(t,n){if(er._isPlainObject(n)){for(const h in n)this._addAttr(t+er._capitalize(h),n[h]);return}const r=this.node,a=r._id;let i,l,o,c;const d=_g.tweens[a][t];d!==void 0&&delete _g.attrs[a][d][t];let u=r.getAttr(t);if(er._isArray(n)||er._isArray(u))if(i=[],c=u,o=n,u=er._isArray(u)?u.slice():new Array(n.length).fill(u||0),er._isArray(n)||(n=new Array(u.length).fill(n)),l=Math.max(n.length,u.length),t==="points"&&n.length!==u.length&&(n.length>u.length?u=er._prepareArrayForTween(u,n,r.closed()):n=er._prepareArrayForTween(n,u,r.closed())),t.endsWith("ColorStops"))for(let h=0;hthis.destroy(),r=()=>{this.node.off(t).on(t,n),this.anim.start()};this.tween.onPlay=r,this.tween.onReverse=r,this.tween.onPause=()=>{this.node.off(t),this.anim.stop()};const a=(i,l)=>{var o;const c=(o=_g.attrs[this.node._id])===null||o===void 0?void 0:o[this._id];if(c){for(const d in c)c[d][i]!==void 0&&this.node.setAttr(d,c[d][i]);l==null||l.call(this)}};this.tween.onFinish=()=>a("trueEnd",this.onFinish),this.tween.onReset=()=>a("trueStart",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(){var t;const n=this.node._id,r=this._id,a=(t=_g.attrs[n])===null||t===void 0?void 0:t[r],i=_g.tweens[n];if(this.pause(),this.anim&&this.anim.stop(),a){if(i){for(const l in a)delete i[l];Object.keys(i).length===0&&delete _g.tweens[n]}delete _g.attrs[n][r],Object.keys(_g.attrs[n]).length===0&&delete _g.attrs[n]}}}_g.attrs={};_g.tweens={};zi.prototype.to=function(s){const t=s.onFinish,n=new _g({...s,node:this,onFinish(){n.destroy(),t&&t()}});return n.play(),n};const qee={BackEaseIn(s,t,n,r){return n*(s/=r)*s*((1.70158+1)*s-1.70158)+t},BackEaseOut(s,t,n,r){return n*((s=s/r-1)*s*((1.70158+1)*s+1.70158)+1)+t},BackEaseInOut(s,t,n,r){let a=1.70158;return(s/=r/2)<1?n/2*(s*s*(((a*=1.525)+1)*s-a))+t:n/2*((s-=2)*s*(((a*=1.525)+1)*s+a)+2)+t},ElasticEaseIn(s,t,n,r,a,i){let l=0;return s===0?t:(s/=r)===1?t+n:(i||(i=r*.3),!a||a=o?o:(c%o+o)%o,u=Math.cos(Math.min(d,Math.PI)),h=1,m=Math.sin(Math.min(Math.max(Math.PI,d),3*Math.PI/2)),f=Math.sin(Math.min(d,Math.PI/2)),g=u*(u>0?r:a),x=h*a,y=m*(m>0?r:a),v=f*(f>0?a:r);return{x:g,y:i?-1*v:y,width:x-g,height:v-y}}}RT.prototype._centroid=!0;RT.prototype.className="Arc";RT.prototype._attrsAffectingSize=["innerRadius","outerRadius","angle","clockwise"];Yg(RT,!0);Tn.addGetterSetter(RT,"innerRadius",0,Ti());Tn.addGetterSetter(RT,"outerRadius",0,Ti());Tn.addGetterSetter(RT,"angle",0,Ti());Tn.addGetterSetter(RT,"clockwise",!1,kC());const twt=[-.07652652113349734,.07652652113349734,-.22778585114164507,.22778585114164507,-.37370608871541955,.37370608871541955,-.5108670019508271,.5108670019508271,-.636053680726515,.636053680726515,-.7463319064601508,.7463319064601508,-.8391169718222188,.8391169718222188,-.912234428251326,.912234428251326,-.9639719272779138,.9639719272779138,-.9931285991850949,.9931285991850949],Eln=[.15275338713072584,.15275338713072584,.14917298647260374,.14917298647260374,.14209610931838204,.14209610931838204,.13168863844917664,.13168863844917664,.11819453196151841,.11819453196151841,.10193011981724044,.10193011981724044,.08327674157670475,.08327674157670475,.06267204833410907,.06267204833410907,.04060142980038694,.04060142980038694,.017614007139152118,.017614007139152118],BWe=(s,t,n)=>{const r=n/2;let a=0;for(let i=0;iBWe([s[0],s[0]+2/3*(s[1]-s[0]),s[2]+2/3*(s[1]-s[2]),s[2]],[t[0],t[0]+2/3*(t[1]-t[0]),t[2]+2/3*(t[1]-t[2]),t[2]],n);function Tln(s,t,n){const r=1-n,a=r*r,i=2*r*n,l=n*n,o=a*(3*(s[1]-s[0]))+i*(3*(s[2]-s[1]))+l*(3*(s[3]-s[2])),c=a*(3*(t[1]-t[0]))+i*(3*(t[2]-t[1]))+l*(3*(t[3]-t[2]));return Math.sqrt(o*o+c*c)}const nwt=(s,t,n)=>{let r=1,a=s/t,i=(s-n(a))/t,l=0;for(;r>.001;){const o=n(a+i),c=Math.abs(s-o)/t;if(c500)break}return a},rwt=(s,t,n,r)=>{const a=1-r;return a*a*s+2*a*r*t+r*r*n},qGt=(s,t,n,r,a,i)=>{const l=[];for(const o of[[s,n,a],[t,r,i]]){const c=(o[0]-o[1])/(o[0]-2*o[1]+o[2]);c>0&&c<1&&l.push(rwt(s,n,a,c),rwt(t,r,i,c))}return l},awt=(s,t,n,r,a)=>{const i=1-a;return i*i*i*s+3*i*i*a*t+3*i*a*a*n+a*a*a*r},Trt=(s,t,n,r,a,i,l,o)=>{const c=[];for(const d of[[s,n,a,l],[t,r,i,o]]){const u=-3*d[0]+9*d[1]-9*d[2]+3*d[3],h=6*d[0]-12*d[1]+6*d[2],m=-3*d[0]+3*d[1],f=h*h-4*u*m;if(f<0)continue;const g=-(h+(h<0?-1:1)*Math.sqrt(f))/2;for(const x of[g/u,m/g])x>0&&x<1&&c.push(awt(s,n,a,l,x),awt(t,r,i,o,x))}return c};function $We(s,t,n,r,a,i,l){const o=Math.sqrt(Math.pow(n-s,2)+Math.pow(r-t,2)),c=Math.sqrt(Math.pow(a-n,2)+Math.pow(i-r,2)),d=o+c;if(d===0)return[n,r,n,r];const u=l*o/d,h=l*c/d,m=n-u*(a-s),f=r-u*(i-t),g=n+h*(a-s),x=r+h*(i-t);return[m,f,g,x]}function iwt(s,t){const n=s.length,r=[];for(let a=2;a4}_eachTensionSegment(t,n){const r=this.points(),a=r.length,i=this.closed(),l=this.getTensionPoints(),o=l.length;let c=r[0],d=r[1],u=i?0:4;for(i||(t(c,d,l[0],l[1],l[2],l[3]),c=l[2],d=l[3]);ut.quadraticCurveTo(d,u,h,m),(o,c,d,u,h,m,f,g)=>t.bezierCurveTo(d,u,h,m,f,g));else if(i)for(l=2;ln.push(o,c,...qGt(r,a,i,l,o,c)),(r,a,i,l,o,c,d,u)=>n.push(d,u,...Trt(r,a,i,l,o,c,d,u))),t=n}else this.bezier()&&(t=[t[0],t[1],...Mln(t)]);return er._getPointsRect(t)}};u3.prototype.className="Line";u3.prototype._attrsAffectingSize=["points","bezier","tension","closed"];Yg(u3,!0);Tn.addGetterSetter(u3,"closed",!1);Tn.addGetterSetter(u3,"bezier",!1);Tn.addGetterSetter(u3,"tension",0,Ti());Tn.addGetterSetter(u3,"points",[],Gon());const Pln={m:2,l:2,h:1,v:1,c:6,s:4,q:4,t:2,a:7,z:0},YBe=Math.PI*2;let WS=class s_ extends li{constructor(t){super(t),this.dataArray=[],this.pathLength=0,this._readDataAttribute(),this.on("dataChange.konva",function(){this._readDataAttribute()})}_readDataAttribute(){this.dataArray=s_.parsePathData(this.data()),this.pathLength=s_.getPathLength(this.dataArray)}_sceneFunc(t){const n=this.dataArray;t.beginPath();let r=!1;for(let a=0;a{if(((x-o)*Math.sign(c)%YBe+YBe)%YBe0&&t<=c;)c-=n[--o].pathLength;for(t-=c;on[o].pathLength;){const m=n[o].pathLength;t-=m,c+=m,++o}if(r&&oBWe([u.start.x,h[0],h[2],h[4]],[u.start.y,h[1],h[3],h[5]],m)),u.start.x,u.start.y,h[0],h[1],h[2],h[3],h[4],h[5]);case"Q":return s_.getPointOnQuadraticBezier(nwt(t,u.pathLength,m=>swt([u.start.x,h[0],h[2]],[u.start.y,h[1],h[3]],m)),u.start.x,u.start.y,h[0],h[1],h[2],h[3]);case"A":return s_.getPointOnEllipticalArc(h[0],h[1],h[2],h[3],h[2]===h[3]?h[4]+h[5]*t/u.pathLength:s_._walkArc(h,t).theta,h[6])}return null}static getPointOnLine(t,n,r,a,i,l,o){l=l??n,o=o??r;const c=this.getLineLength(n,r,a,i);if(c<1e-10)return{x:n,y:r};if(a===n)return{x:l,y:o+(i>r?t:-t)};const d=(i-r)/(a-n),u=Math.sqrt(t*t/(1+d*d))*(a1&&(C[0]==="0"||C[0]==="1");)y.push(+C[0]),v++,C=C.slice(1);const E=parseFloat(C);y.push(isNaN(E)?0:E),v>=0&&(v=(v+1)%7)}let b=0;for(;b=n)return{theta:h+(g-h)*((n-m)/y),length:n};m+=y,u=x,h=g}return{theta:h,length:m}}static calcLength(t,n,r,a){const i=s_;switch(r){case"L":return i.getLineLength(t,n,a[0],a[1]);case"C":return BWe([t,a[0],a[2],a[4]],[n,a[1],a[3],a[5]],1);case"Q":return swt([t,a[0],a[2]],[n,a[1],a[3]],1);case"A":return i._walkArc(a,1/0).length}return 0}static convertEndpointToCenterParameterization(t,n,r,a,i,l,o,c,d){const u=d*(Math.PI/180),h=Math.cos(u)*(t-r)/2+Math.sin(u)*(n-a)/2,m=-1*Math.sin(u)*(t-r)/2+Math.cos(u)*(n-a)/2,f=h*h/(o*o)+m*m/(c*c);f>1&&(o*=Math.sqrt(f),c*=Math.sqrt(f));let g=Math.sqrt((o*o*(c*c)-o*o*(m*m)-c*c*(h*h))/(o*o*(m*m)+c*c*(h*h)));i===l&&(g*=-1),isNaN(g)&&(g=0);const x=g*o*m/c,y=g*-c*h/o,v=(t+r)/2+Math.cos(u)*x-Math.sin(u)*y,b=(n+a)/2+Math.sin(u)*x+Math.cos(u)*y,w=function(D){return Math.sqrt(D[0]*D[0]+D[1]*D[1])},S=function(D,O){return(D[0]*O[0]+D[1]*O[1])/(w(D)*w(O))},C=function(D,O){return(D[0]*O[1]=1&&(R=0),l===0&&R>0&&(R=R-2*Math.PI),l===1&&R<0&&(R=R+2*Math.PI),[v,b,o,c,E,R,u,l]}};WS.prototype.className="Path";WS.prototype._attrsAffectingSize=["data"];Yg(WS,!0);Tn.addGetterSetter(WS,"data");class b6 extends u3{_getStrokePadding(){return super._getStrokePadding(this.pointerAtBeginning()||this.pointerAtEnding()?this.miterLimit()||10:void 0)}_sceneFunc(t){super._sceneFunc(t);const n=this.points(),r=n.length;if(r<4)return;const a=this.pointerLength(),i=this.pointerWidth();this.pointerAtEnding()&&(t.save(),t.beginPath(),t.translate(n[r-2],n[r-1]),t.rotate(this._getPointerAngle(!1)),t.moveTo(0,0),t.lineTo(-a,i/2),t.lineTo(-a,-i/2),t.closePath(),t.restore(),this.__fillStroke(t)),this.pointerAtBeginning()&&(t.save(),t.beginPath(),t.translate(n[0],n[1]),t.rotate(this._getPointerAngle(!0)),t.moveTo(0,0),t.lineTo(-a,i/2),t.lineTo(-a,-i/2),t.closePath(),t.restore(),this.__fillStroke(t))}_getPointerAngle(t){const n=this.points(),r=n.length,a=this.tension()!==0&&r>4,i=a?this.getTensionPoints():n,l=t?n[0]:n[r-2],o=t?n[1]:n[r-1];let c=0,d=0;if(a&&t)c=l-(i[0]+i[2])/2,d=o-(i[1]+i[3])/2;else if(a){const h=i[i.length-4],m=i[i.length-3],f=i[i.length-2],g=i[i.length-1],x=WS.calcLength(h,m,"Q",[f,g,l,o]),y=WS.getPointOnQuadraticBezier(x?Math.max(0,1-this.pointerLength()/x):0,h,m,f,g,l,o);c=l-y.x,d=o-y.y}for(let h=t?0:i.length-2;!c&&!d&&h>=0&&h{this._requestDraw()},this.on("imageChange.konva",n=>{this._removeImageLoad(n.oldVal),this._setImageLoad()}),this._setImageLoad()}_setImageLoad(){var t;const n=this.image();n!=null&&n.complete&&n.src||(n==null?void 0:n.readyState)>=2||(t=n==null?void 0:n.addEventListener)===null||t===void 0||t.call(n,"videoWidth"in n?"loadeddata":"load",this._loadListener)}_removeImageLoad(t){var n;(n=t==null?void 0:t.removeEventListener)===null||n===void 0||n.call(t,"videoWidth"in t?"loadeddata":"load",this._loadListener)}destroy(){return this._removeImageLoad(this.image()),super.destroy(),this}_useBufferCanvas(t,n=this.getAbsoluteOpacity()){if(this.attrs.perfectDrawEnabled===!1)return!1;const r=!!this.cornerRadius(),a=this.hasShadow();return r&&a?!0:super._useBufferCanvas(!0,n)}_getStrokePadding(){return super._getStrokePadding(this.strokeScaleEnabled()?1:void 0)}_sceneFunc(t){const n=this.getWidth(),r=this.getHeight(),a=this.cornerRadius(),i=this.attrs.image;if((this.hasFill()||this.hasStroke()||a)&&(t.beginPath(),a?er.drawRoundedRectPath(t,n,r,a):t.rect(0,0,n,r),t.closePath(),t.fillStrokeShape(this)),i){a&&t.clip();const l=this.attrs.cropWidth,o=this.attrs.cropHeight;l&&o?t.drawImage(i,this.cropX(),this.cropY(),l,o,0,0,n,r):t.drawImage(i,0,0,n,r)}}_hitFunc(t){const n=this.width(),r=this.height(),a=this.cornerRadius();t.beginPath(),a?er.drawRoundedRectPath(t,n,r,a):t.rect(0,0,n,r),t.closePath(),t.fillStrokeShape(this)}getWidth(){var t,n,r;const a=this.image();return(r=(n=(t=this.attrs.width)!==null&&t!==void 0?t:a==null?void 0:a.videoWidth)!==null&&n!==void 0?n:a==null?void 0:a.width)!==null&&r!==void 0?r:0}getHeight(){var t,n,r;const a=this.image();return(r=(n=(t=this.attrs.height)!==null&&t!==void 0?t:a==null?void 0:a.videoHeight)!==null&&n!==void 0?n:a==null?void 0:a.height)!==null&&r!==void 0?r:0}static fromURL(t,n,r=null){const a=er.createImageElement();a.onload=()=>{a.onload=a.onerror=null,n(new VGt({image:a}))},a.onerror=r,a.crossOrigin="Anonymous",a.src=t}};SC.prototype.className="Image";SC.prototype._attrsAffectingSize=["image"];Yg(SC,!0);Tn.addGetterSetter(SC,"cornerRadius",0,aRe(4));Tn.addGetterSetter(SC,"image");Tn.addComponentsGetterSetter(SC,"crop",["x","y","width","height"]);Tn.addGetterSetter(SC,"cropX",0,Ti());Tn.addGetterSetter(SC,"cropY",0,Ti());Tn.addGetterSetter(SC,"cropWidth",0,Ti());Tn.addGetterSetter(SC,"cropHeight",0,Ti());const owt=typeof Intl<"u"&&Intl.Segmenter?new Intl.Segmenter(void 0,{granularity:"grapheme"}):null;function Vee(s){return s/15}function jQ(s){return owt?Array.from(owt.segment(s),t=>t.segment):s.match(new RegExp("\\p{RI}\\p{RI}|\\P{M}(?:\\p{M}|\\p{Emoji_Modifier}|\\uFE0F|\\u200D\\P{M})*|\\p{M}+","gu"))||[]}const P$="auto",lwt="center",HGt="inherit",I$="justify",Iln="Change.konva",GGt="2d",Lln="-",WGt="left",Rln="text",Dln="Text",Fln="top",Oln="bottom",cwt="middle",KGt="normal",zln="px ",ZBe=" ",dwt="right",uwt="rtl",Bln="word",$ln="char",hwt="none",XBe="…",YGt=["direction","fontFamily","fontSize","fontStyle","fontVariant","padding","align","verticalAlign","lineHeight","text","width","height","wrap","ellipsis","letterSpacing"];let VZ=null;function Uln(){if(VZ!==null)return VZ;VZ=!1;let s;try{s=er.createCanvasElement(),s.width=10,s.height=10;const t=s.getContext(GGt);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 n=t.getImageData(0,0,10,10).data;for(let r=3;r0){VZ=!0;break}}}catch{}finally{s&&er.releaseCanvas(s)}return VZ}function qln(s){return s.split(",").map(t=>{t=t.trim();const n=t.indexOf(" ")>=0,r=t.indexOf('"')>=0||t.indexOf("'")>=0;return n&&!r&&(t=`"${t}"`),t}).join(", ")}let Dde;function j3e(){return Dde||(Dde=er.createCanvasElement().getContext(GGt),Dde)}function Vln(s){this._partialFillStyle&&s.setAttr("fillStyle",this._partialFillStyle),s.fillText(this._partialText,this._partialTextX,this._partialTextY)}function Hln(s){s.setAttr("miterLimit",2),this._partialStrokeStyle&&s.setAttr("strokeStyle",this._partialStrokeStyle),s.strokeText(this._partialText,this._partialTextX,this._partialTextY)}function Gln(s){return s=s||{},s.fill||s.fillLinearGradientColorStops||s.fillRadialGradientColorStops||s.fillPatternImage?s:{...s,fill:"black"}}let cf=class extends li{constructor(t){super(Gln(t)),this._partialTextX=0,this._partialTextY=0,this._baselineShift=0,this._setTextData()}_sceneFunc(t){var n,r;const a=this.textArr,i=a.length;if(!this.text())return;let l=this.padding(),o=this.fontSize(),c=this.lineHeight()*o,d=this.direction(),u=this.align(),h=this.getWidth(),m=this.letterSpacing(),f=this.charRenderFunc(),g=this.textDecoration(),x=g.indexOf("underline")!==-1,y=g.indexOf("line-through")!==-1,v,b=c/2,w=cwt;if(!Qo.legacyTextRendering){const I=this.measureSize("M");w="alphabetic";const P=(n=I.fontBoundingBoxAscent)!==null&&n!==void 0?n:I.actualBoundingBoxAscent,R=(r=I.fontBoundingBoxDescent)!==null&&r!==void 0?r:I.actualBoundingBoxDescent;b=(P-R)/2+c/2}if(d!==HGt?t.setAttr("direction",d):d=t.direction,t.setAttr("font",this._getContextFont()),t.setAttr("textBaseline",w),t.setAttr("textAlign",WGt),t.translate(l,this._getTextTop()),f){const I=t._getFillStyle(this);I!==void 0&&(t.fillStyle=I),this.hasStroke()&&t._applyStrokeStyle(this)}const S=f?t.fillStyle:void 0,C=f?t.strokeStyle:void 0;let E=0;for(v=0;v1&&(b+=c)}}_getTextTop(){const t=this.padding(),n=this.getHeight()-this.textArr.length*this.lineHeight()*this.fontSize()-t*2,r=this.verticalAlign();return r===cwt?t+n/2:r===Oln?t+n:t}_getUnderlineOffset(){var t;return(t=this.underlineOffset())!==null&&t!==void 0?t:Math.round(this.fontSize()/(Qo.legacyTextRendering?2:4))}getSelfRect(){const t=super.getSelfRect(),n=this.textArr.length;if(!n||this.textDecoration().indexOf("underline")===-1)return t;const r=this.fontSize(),a=this.lineHeight()*r;let i=this._getTextTop()+n*a-a/2;return Qo.legacyTextRendering||(i+=this._baselineShift),i+=this._getUnderlineOffset()+Vee(r)/2,t.height=Math.max(t.y+t.height,i)-t.y,t}_getSelfRectForDrawing(){const t=this.getSelfRect(),n=this.fontSize(),r=this.padding(),a=this.lineHeight()*n,i=this.getWidth()-r*2,l=this.align(),o=this.textArr.length*a,c=this._getTextTop();let d=t.x,u=t.x+t.width;for(const{text:f,width:g}of this.textArr){const x=r+(l===dwt?i-g:l===lwt?(i-g)/2:0),y=Math.min(0,this.letterSpacing())*f.length;d=Math.min(d,x+y),u=Math.max(u,x+g-y)}const h=this.textDecoration().includes("underline"),m=Math.min(t.y,c+(h?Math.min(0,this._getUnderlineOffset()):0));return{x:d-n,y:m-n,width:u-d+n*2,height:Math.max(t.y+t.height,c+o)-m+n*2}}_hitFunc(t){const n=this.getWidth(),r=this.getHeight();t.beginPath(),t.rect(0,0,n,r),t.closePath(),t.fillStrokeShape(this)}setText(t){const n=er._isString(t)?t:t==null?"":t+"";return this._setAttr(Rln,n),this}getWidth(){return this.attrs.width===P$||this.attrs.width===void 0?this.getTextWidth()+this.padding()*2:this.attrs.width}getHeight(){return this.attrs.height===P$||this.attrs.height===void 0?this.fontSize()*this.textArr.length*this.lineHeight()+this.padding()*2:this.attrs.height}getTextWidth(){return this.textWidth}getTextHeight(){return er.warn("text.getTextHeight() method is deprecated. Use text.height() - for full height and text.fontSize() - for one line height."),this.textHeight}measureSize(t){var n,r,a,i,l,o,c,d,u,h,m;let f=j3e(),g=this.fontSize(),x;f.save(),f.font=this._getContextFont(),x=f.measureText(t),f.restore();const y=g/100;return{actualBoundingBoxAscent:(n=x.actualBoundingBoxAscent)!==null&&n!==void 0?n:71.58203125*y,actualBoundingBoxDescent:(r=x.actualBoundingBoxDescent)!==null&&r!==void 0?r:0,actualBoundingBoxLeft:(a=x.actualBoundingBoxLeft)!==null&&a!==void 0?a:-7.421875*y,actualBoundingBoxRight:(i=x.actualBoundingBoxRight)!==null&&i!==void 0?i:75.732421875*y,alphabeticBaseline:(l=x.alphabeticBaseline)!==null&&l!==void 0?l:0,emHeightAscent:(o=x.emHeightAscent)!==null&&o!==void 0?o:100*y,emHeightDescent:(c=x.emHeightDescent)!==null&&c!==void 0?c:-20*y,fontBoundingBoxAscent:(d=x.fontBoundingBoxAscent)!==null&&d!==void 0?d:91*y,fontBoundingBoxDescent:(u=x.fontBoundingBoxDescent)!==null&&u!==void 0?u:21*y,hangingBaseline:(h=x.hangingBaseline)!==null&&h!==void 0?h:72.80000305175781*y,ideographicBaseline:(m=x.ideographicBaseline)!==null&&m!==void 0?m:-21*y,width:x.width,height:g}}_getContextFont(){return this.fontStyle()+ZBe+this.fontVariant()+ZBe+(this.fontSize()+zln)+qln(this.fontFamily())}_addTextLine(t){this.align()===I$&&(t=t.trim());const r=this._getTextWidth(t);return this.textArr.push({text:t,width:r,lastInParagraph:!1})}_getTextWidth(t,n){const r=this.letterSpacing(),a=r?r*(n??jQ(t).length):0;return j3e().measureText(t).width+a}_setTextData(){let t=this.text().split(` `),n=+this.fontSize(),r=this.lineHeight()*n,a=this.attrs.width,i=this.attrs.height,l=a!==P$&&a!==void 0,o=i!==P$&&i!==void 0,c=this.padding(),d=a-c*2,u=i-c*2,h=0,m=this.wrap(),f=m!==hwt,g=m!==$ln&&f,x=this.ellipsis();const y=this.measureSize("M");this._baselineShift=(y.fontBoundingBoxAscent-y.fontBoundingBoxDescent)/2,this.textArr=[];const v=j3e();v.font=this._getContextFont(),v.fontKerning=this.direction()!==uwt&&(this.letterSpacing()!==0||this.align()===I$||this.charRenderFunc())?"none":"auto";const b=x?this._getTextWidth(XBe):0;for(let w=0,S=t.length;wd){const I=jQ(C),P=I.length;let R=0;const D=W=>I.slice(R,W).join(""),O=W=>W===ZBe||W===Lln,U=Math.max(1,Math.ceil(P*d/E));for(;Ru?b:0,V=X=>!(this._getTextWidth(D(X),X-R)+W>d);let G=R,Y=Math.min(P,R+U);for(;V(Y)&&(G=Y,Y!==P);)Y=Math.min(P,Y+(Y-R));for(;Y-G>1;){const X=G+Y>>>1;V(X)?G=X:Y=X}if(G===R)break;if(G===P){this._addTextLine(D(P)),h+=r,o&&h+r>u&&w=R&&!O(I[X]);)X--;X>=R&&(G=X+1)}if(this._addTextLine(D(G).trimRight()),h+=r,this._shouldHandleEllipsis(h)){this._tryToAddEllipsisToLastLine();break}for(R=G;Ru&&wu)break}this.textHeight=n,this.textWidth=this.textArr.reduce((w,S)=>Math.max(w,S.width),0)}_shouldHandleEllipsis(t){const n=+this.fontSize(),r=this.lineHeight()*n,a=this.attrs.height,i=a!==P$&&a!==void 0,l=this.padding(),o=a-l*2;return!(this.wrap()!==hwt)||i&&t+r>o}_tryToAddEllipsisToLastLine(){const t=this.attrs.width,n=t!==P$&&t!==void 0,r=this.padding(),a=t-r*2,i=this.ellipsis(),l=this.textArr[this.textArr.length-1];if(!l||!i)return;let o=l.text+XBe;if(n){const c=jQ(l.text);for(;c.length&&this._getTextWidth(o)>a;)c.pop(),o=c.join("")+XBe;this._getTextWidth(o)>a&&(o="")}l.text=o,l.width=this._getTextWidth(o)}getStrokeScaleEnabled(){return!0}_getStrokePadding(){return super._getStrokePadding(2)}_useBufferCanvas(t,n=this.getAbsoluteOpacity()){if(this.attrs.perfectDrawEnabled===!1)return!1;const r=this.textDecoration().indexOf("underline")!==-1||this.textDecoration().indexOf("line-through")!==-1,a=this.hasShadow();return r&&a||a&&n!==1&&Uln()?!0:super._useBufferCanvas(t,n)}};cf.prototype._fillFunc=Vln;cf.prototype._strokeFunc=Hln;cf.prototype.className=Dln;cf.prototype._attrsAffectingSize=YGt.filter(s=>s!=="width"&&s!=="height").concat(["textDecoration","underlineOffset"]);Yg(cf,!0);cf.prototype.on(YGt.map(s=>s+Iln).join(" "),function(){this._setTextData()});Tn.overWriteSetter(cf,"width",Art());Tn.overWriteSetter(cf,"height",Art());Tn.addGetterSetter(cf,"direction",HGt);Tn.addGetterSetter(cf,"fontFamily","Arial");Tn.addGetterSetter(cf,"fontSize",12,Ti());Tn.addGetterSetter(cf,"fontStyle",KGt);Tn.addGetterSetter(cf,"fontVariant",KGt);Tn.addGetterSetter(cf,"padding",0,Ti());Tn.addGetterSetter(cf,"align",WGt);Tn.addGetterSetter(cf,"verticalAlign",Fln);Tn.addGetterSetter(cf,"lineHeight",1,Ti());Tn.addGetterSetter(cf,"wrap",Bln);Tn.addGetterSetter(cf,"ellipsis",!1,kC());Tn.addGetterSetter(cf,"letterSpacing",0,Ti());Tn.addGetterSetter(cf,"text","",KB());Tn.addGetterSetter(cf,"textDecoration","");Tn.addGetterSetter(cf,"underlineOffset",void 0,Ti());Tn.addGetterSetter(cf,"charRenderFunc",void 0);const Wln=[...cf.prototype._attrsAffectingSize,"width","height","pointerDirection","pointerWidth","pointerHeight"],mwt=Wln.map(s=>s+"Change.konva").join(" "),Kln="none",N3e="up",UWe="right",qWe="down",k3e="left";let Mrt=class extends rB{constructor(t){super(t),this._sync=this._sync.bind(this),this.on("add.konva",function(n){n.child.off(mwt,this._sync).on(mwt,this._sync),this._sync()})}getText(){return this.find("Text")[0]}getTag(){return this.find("Tag")[0]}getWidth(){return this.getText().width()}getHeight(){return this.getText().height()}_sync(){let t=this.getText(),n=this.getTag(),r,a,i,l,o,c,d;if(t&&n){switch(r=t.width(),a=t.height(),i=n.pointerDirection(),l=n.pointerWidth(),d=n.pointerHeight(),o=0,c=0,i){case N3e:o=r/2,c=-1*d;break;case UWe:o=r+l,c=a/2;break;case qWe:o=r/2,c=a+d;break;case k3e:o=-1*l,c=a/2;break}n.setAttrs({x:-1*o,y:-1*c,width:r,height:a}),t.setAttrs({x:-1*o,y:-1*c})}}};Mrt.prototype.className="Label";Yg(Mrt);class ZB extends li{_sceneFunc(t){const n=this.width(),r=this.height(),a=this.pointerDirection(),i=this.pointerWidth(),l=this.pointerHeight(),o=this.cornerRadius(),[c,d,u,h]=er._cornerRadii(o,n,r);t.beginPath(),t.moveTo(c,0),a===N3e&&(t.lineTo((n-i)/2,0),t.lineTo(n/2,-1*l),t.lineTo((n+i)/2,0)),t.lineTo(n-d,0),t.arc(n-d,d,d,Math.PI*3/2,0,!1),a===UWe&&(t.lineTo(n,(r-l)/2),t.lineTo(n+i,r/2),t.lineTo(n,(r+l)/2)),t.lineTo(n,r-u),t.arc(n-u,r-u,u,0,Math.PI/2,!1),a===qWe&&(t.lineTo((n+i)/2,r),t.lineTo(n/2,r+l),t.lineTo((n-i)/2,r)),t.lineTo(h,r),t.arc(h,r-h,h,Math.PI/2,Math.PI,!1),a===k3e&&(t.lineTo(0,(r+l)/2),t.lineTo(-1*i,r/2),t.lineTo(0,(r-l)/2)),t.lineTo(0,c),t.arc(c,c,c,Math.PI,Math.PI*3/2,!1),t.closePath(),t.fillStrokeShape(this)}getSelfRect(){const t=this.pointerWidth(),n=this.pointerHeight(),r=this.pointerDirection(),a=this.width(),i=this.height();return r===N3e||r===qWe?{x:Math.min(0,(a-t)/2),y:r===N3e?-n:0,width:Math.max(a,t),height:i+n}:r===k3e||r===UWe?{x:r===k3e?-t:0,y:Math.min(0,(i-n)/2),width:a+t,height:Math.max(i,n)}:{x:0,y:0,width:a,height:i}}}ZB.prototype.className="Tag";Yg(ZB,!0);Tn.addGetterSetter(ZB,"pointerDirection",Kln);Tn.addGetterSetter(ZB,"pointerWidth",0,Ti());Tn.addGetterSetter(ZB,"pointerHeight",0,Ti());Tn.addGetterSetter(ZB,"cornerRadius",0,aRe(4));let jie=class extends li{_getStrokePadding(){return super._getStrokePadding(this.strokeScaleEnabled()?1:void 0)}_sceneFunc(t){const n=this.cornerRadius(),r=this.width(),a=this.height();t.beginPath(),n?er.drawRoundedRectPath(t,r,a,n):t.rect(0,0,r,a),t.closePath(),t.fillStrokeShape(this)}};jie.prototype.className="Rect";Yg(jie,!0);Tn.addGetterSetter(jie,"cornerRadius",0,aRe(4));class w6 extends li{_sceneFunc(t){const n=this._getPoints(),r=this.radius(),a=this.sides(),i=this.cornerRadius();if(n.length){if(t.beginPath(),i)er.drawRoundedPolygonPath(t,n,a,r,i);else{t.moveTo(n[0].x,n[0].y);for(let l=1;l{n=Math.min(n,l.x),r=Math.max(r,l.x),a=Math.min(a,l.y),i=Math.max(i,l.y)}),{x:n,y:a,width:r-n,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)}}w6.prototype.className="RegularPolygon";w6.prototype._centroid=!0;w6.prototype._attrsAffectingSize=["radius","sides"];Yg(w6,!0);Tn.addGetterSetter(w6,"radius",0,Ti());Tn.addGetterSetter(w6,"sides",0,Ti());Tn.addGetterSetter(w6,"cornerRadius",0,aRe(4));const fwt=Math.PI*2;class XB extends li{_getStrokePadding(){return super._getStrokePadding(1)}_sceneFunc(t){const n=Math.abs(this.innerRadius()),r=Math.abs(this.outerRadius());t.beginPath(),t.arc(0,0,n,0,fwt,!1),t.moveTo(r,0),t.arc(0,0,r,fwt,0,!0),t.closePath(),t.fillStrokeShape(this)}getSelfRect(){const t=Math.max(Math.abs(this.innerRadius()),Math.abs(this.outerRadius()));return{x:-t,y:-t,width:t*2,height:t*2}}getWidth(){return Math.abs(this.outerRadius())*2}getHeight(){return Math.abs(this.outerRadius())*2}setWidth(t){this.outerRadius(t/2)}setHeight(t){this.outerRadius(t/2)}}XB.prototype.className="Ring";XB.prototype._centroid=!0;XB.prototype._attrsAffectingSize=["innerRadius","outerRadius"];Yg(XB,!0);Tn.addGetterSetter(XB,"innerRadius",0,Ti());Tn.addGetterSetter(XB,"outerRadius",0,Ti());class h3 extends li{constructor(t){super(t),this._updated=!0,this.anim=new $N(()=>{const n=this._updated;return this._updated=!1,n}),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())})}_getFrame(){var t,n;const r=this.animation(),a=(t=this.animations())===null||t===void 0?void 0:t[r],i=this.frameIndex(),l=i*4;if(!a||!Number.isInteger(i)||l<0||l+4>a.length)return;const o=((n=this.frameOffsets())===null||n===void 0?void 0:n[r])||[];return{x:a[l],y:a[l+1],width:a[l+2],height:a[l+3],offsetX:o[i*2]||0,offsetY:o[i*2+1]||0}}_getStrokePadding(){return super._getStrokePadding(this.strokeScaleEnabled()?1:void 0)}_sceneFunc(t){const n=this._getFrame();if(!n)return;const{x:r,y:a,width:i,height:l,offsetX:o,offsetY:c}=n,d=this.image();(this.hasFill()||this.hasStroke())&&(t.beginPath(),t.rect(o,c,i,l),t.closePath(),t.fillStrokeShape(this)),d&&t.drawImage(d,r,a,i,l,o,c,i,l)}_hitFunc(t){const{x:n,y:r,width:a,height:i}=this.getSelfRect();t.beginPath(),t.rect(n,r,a,i),t.closePath(),t.fillShape(this)}getSelfRect(){const t=this._getFrame();return t?{x:t.offsetX,y:t.offsetY,width:t.width,height:t.height}:{x:0,y:0,width:0,height:0}}_useBufferCanvas(t,n=this.getAbsoluteOpacity()){return super._useBufferCanvas(!0,n)}_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)}destroy(){return this.stop(),super.destroy()}isRunning(){return this.anim.isRunning()}_updateIndex(){var t;const n=this.frameIndex(),r=(t=this.animations())===null||t===void 0?void 0:t[this.animation()],a=r?r.length/4:0;this.frameIndex(nr?null:WS.getPointAtLengthOfDataArray(t,this.dataArray,n)}_readDataAttribute(){this.dataArray=WS.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 n=this.textDecoration(),r=this.fill(),a=this.fontSize(),i=this.glyphInfo,l=n.indexOf("underline")!==-1,o=n.indexOf("line-through")!==-1;l&&t.beginPath();for(let c=0;c=1){const r=n[0].p0;t.moveTo(r.x,r.y)}for(let r=0;r0)try{y=n(t[x-1],t[x])*this.fontSize()}catch{}r.push({char:t[x],width:this._getTextSize(t[x]).width,kern:y}),a+=r[x].width+y}const{width:i,height:l}=this._getTextSize(this.attrs.text);if(this.textWidth=a,this.textHeight=l,this.glyphInfo=[],!this.attrs.data)return null;const o=this.letterSpacing(),c=this.align(),d=c==="justify"?this.text().split(" ").length-1:0,u=Math.max(0,a-i),h=Math.max(this.textWidth+(t.length-1)*o,0);let m=0;c==="center"&&(m=Math.max(0,this.pathLength/2-h/2)),c==="right"&&(m=Math.max(0,this.pathLength-h));let f=m;const g=this.dataArray.some((x,y)=>y>0&&x.command==="M")?void 0:{index:0,offset:0};for(let x=0;xthis.pathLength&&w-this.pathLength<=u?this.pathLength:w,g);if(!S)return;const C=WS.getLineLength(y.x,y.y,S.x,S.y),E=Math.atan2(S.y-y.y,S.x-y.x);this.glyphInfo.push({text:t[x],rotation:E,p0:y,p1:S,width:C}),f+=b}}getSelfRect(){if(!this.glyphInfo.length)return{x:0,y:0,width:0,height:0};const t=[];this.glyphInfo.forEach(function(a){t.push(a.p0.x),t.push(a.p0.y),t.push(a.p1.x),t.push(a.p1.y)});const n=er._getPointsRect(t),r=this.fontSize();return{x:n.x-r/2,y:n.y-r/2,width:n.width+r,height:n.height+r}}getStrokeScaleEnabled(){return!0}_getSelfRectForDrawing(){const t=this.getSelfRect(),n=this.fontSize();return{x:t.x-n,y:t.y-n,width:t.width+n*2,height:t.height+n*2}}}Wg.prototype._fillFunc=XGt;Wg.prototype._strokeFunc=QGt;Wg.prototype._fillFuncHit=XGt;Wg.prototype._strokeFuncHit=QGt;Wg.prototype.className="TextPath";Wg.prototype._attrsAffectingSize=["text","fontSize","data","align","letterSpacing","kerningFunc","fontFamily","fontStyle","fontVariant","direction"];Yg(Wg,!0);Wg.prototype.on("dataChange.konva",function(){this._readDataAttribute(),this._setTextData()});Wg.prototype.on(Wg.prototype._attrsAffectingSize.filter(s=>s!=="data").map(s=>s+"Change.konva").join(" "),function(){this._setTextData()});Tn.addGetterSetter(Wg,"data");Tn.addGetterSetter(Wg,"fontFamily","Arial");Tn.addGetterSetter(Wg,"fontSize",12,Ti());Tn.addGetterSetter(Wg,"fontStyle",ZGt);Tn.addGetterSetter(Wg,"align","left");Tn.addGetterSetter(Wg,"letterSpacing",0,Ti());Tn.addGetterSetter(Wg,"textBaseline","middle");Tn.addGetterSetter(Wg,"fontVariant",ZGt);Tn.addGetterSetter(Wg,"text",Yln);Tn.addGetterSetter(Wg,"textDecoration","");Tn.addGetterSetter(Wg,"kerningFunc",void 0);Tn.addGetterSetter(Wg,"direction","inherit");const VWe="tr-konva",Zln=["resizeEnabledChange","rotateAnchorOffsetChange","rotateAnchorAngleChange","rotateEnabledChange","enabledAnchorsChange","anchorSizeChange","borderEnabledChange","shouldOverdrawWholeAreaChange","borderStrokeChange","borderStrokeWidthChange","borderDashChange","anchorStrokeChange","anchorStrokeWidthChange","anchorFillChange","anchorCornerRadiusChange","ignoreStrokeChange","anchorStyleFuncChange","paddingChange"].map(s=>s+`.${VWe}`).join(" "),QBe="nodesRect",Xln=["widthChange","heightChange","scaleXChange","scaleYChange","skewXChange","skewYChange","rotationChange","offsetXChange","offsetYChange","transformsEnabledChange","strokeWidthChange","strokeChange","selfRectFuncChange","strokeLinearGradientColorStopsChange","strokeScaleEnabledChange","strokeEnabledChange","draggableChange"],Qln={"top-left":-45,"top-center":0,"top-right":45,"middle-right":-90,"middle-left":90,"bottom-left":-135,"bottom-center":180,"bottom-right":135},Jln="ontouchstart"in Qo._global;function ecn(s,t,n){if(s==="rotater")return n;t+=er.degToRad(Qln[s]||0);const r=(er.radToDeg(t)%360+360)%360;return er._inRange(r,315+22.5,360)||er._inRange(r,0,22.5)?"ns-resize":er._inRange(r,45-22.5,45+22.5)?"nesw-resize":er._inRange(r,90-22.5,90+22.5)?"ew-resize":er._inRange(r,135-22.5,135+22.5)?"nwse-resize":er._inRange(r,180-22.5,180+22.5)?"ns-resize":er._inRange(r,225-22.5,225+22.5)?"nesw-resize":er._inRange(r,270-22.5,270+22.5)?"ew-resize":er._inRange(r,315-22.5,315+22.5)?"nwse-resize":(er.error("Transformer has unknown angle for cursor detection: "+r),"pointer")}const UTe=["top-left","top-center","top-right","middle-right","middle-left","bottom-left","bottom-center","bottom-right"];function tcn(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 scn(s,t,n){const r=n.x+(s.x-n.x)*Math.cos(t)-(s.y-n.y)*Math.sin(t),a=n.y+(s.x-n.x)*Math.sin(t)+(s.y-n.y)*Math.cos(t);return{...s,rotation:s.rotation+t,x:r,y:a}}function ncn(s,t){const n=tcn(s);return scn(s,t,n)}function rcn(s,t,n){let r=t,a=n;for(let i=0;i0&&(c=Math.min(c,(n-o)/i)),a<0?c=Math.min(c,-l/a):a>0&&(c=Math.min(c,(t-l)/a));const d=l+a*c,u=o+i*c,h=s.rotateAnchorOffset()+s.padding();return{edgeX:d,edgeY:u,endX:d+a*h,endY:u+i*h}}const S3e=new Set;let Hu=class extends rB{static _isLayerTransforming(t){for(const n of S3e)if(n.getLayer()===t||n._nodes.some(r=>r.getLayer()===t))return!0;return!1}constructor(t){super(t),this._movingAnchorName=null,this._anchors={},this._transforming=!1,this._fitting=!1,this._transformWindow=null,this._elementsCreated=!1,this._updateScheduled=!1,this._createElements(),this._handleMouseMove=this._handleMouseMove.bind(this),this._handleMouseUp=this._handleMouseUp.bind(this),this.update=this.update.bind(this),this.on(Zln,n=>{n.type==="ignoreStrokeChange"&&this._resetTransformCache(),this.update()}),this.on(`rotationChange.${VWe}`,()=>this._clearCache(QBe)),this.getNode()&&this.update()}attachTo(t){return this.setNode(t),this}setNode(t){return er.warn("tr.setNode(shape), tr.node(shape) and tr.attachTo(shape) methods are deprecated. Please use tr.nodes(nodesArray) instead."),this.setNodes([t])}getNode(){return this._nodes&&this._nodes[0]}_getEventNamespace(){return VWe+this._id}setNodes(t=[]){this._nodes&&this._nodes.length&&this.detach();const n=new Set(t);for(const a of n)a.isAncestorOf(this)&&(er.error("Konva.Transformer cannot be an a child of the node you are trying to attach"),n.delete(a));const r=Array.from(n).filter(a=>{for(let i=a.getParent();i;i=i.getParent())if(n.has(i))return!1;return!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=()=>{var l;if(this._fitting){(l=this._nodeRectCache)===null||l===void 0||l.delete(a);return}this.nodes().length===1&&this.useSingleNodeRotation()&&this.rotation(this.nodes()[0].getAbsoluteRotation()),this._resetTransformCache(a),this.isDragging()||this._scheduleUpdate()};if(a._attrsAffectingSize.length){const l=a._attrsAffectingSize.map(o=>o+"Change."+this._getEventNamespace()).join(" ");a.on(l,i)}a.on(Xln.map(l=>l+`.${this._getEventNamespace()}`).join(" "),i),a.on(`absoluteTransformChange.${this._getEventNamespace()}`,i),a.on(`destroy.${this._getEventNamespace()}`,()=>{this.setNodes(this._nodes.filter(l=>l!==a))}),this._proxyDrag(a)}),this._resetTransformCache(),this._elementsCreated&&this.update(),this}_proxyDrag(t){let n;t.on(`dragstart.${this._getEventNamespace()}`,r=>{n=t.getAbsolutePosition(),!this.isDragging()&&t!==this._back&&this.startDrag(r,!1)}),t.on(`dragmove.${this._getEventNamespace()}`,r=>{if(!n)return;const a=t.getAbsolutePosition(),i=a.x-n.x,l=a.y-n.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(r)}),n=null})}getNodes(){return this._nodes||[]}getActiveAnchor(){return this._movingAnchorName}detach(){var t;this._nodes&&this._nodes.forEach(n=>{n.off("."+this._getEventNamespace())}),this._nodes=[],this._resetTransformCache(),(t=this.getLayer())===null||t===void 0||t.batchDraw()}_resetTransformCache(t){var n,r;t?(n=this._nodeRectCache)===null||n===void 0||n.delete(t):(r=this._nodeRectCache)===null||r===void 0||r.clear(),this._clearCache(QBe),this._clearCache("transform"),this._clearSelfAndDescendantCache("absoluteTransform")}_getNodeRect(){return this._getCache(QBe,this.__getNodeRect)}__getNodeRect(){var t;if(!this.getNode())return{x:-1e8,y:-1e8,width:0,height:0,rotation:0};const r=Qo.getAngle(this.rotation()),a=this.ignoreStroke(),i=new _0;i.rotate(-r);const l=this._nodeRectCache||(this._nodeRectCache=new Map);let o=1/0,c=1/0,d=-1/0,u=-1/0;for(const m of this.nodes()){const f=m instanceof li&&m.getSelfRect===li.prototype.getSelfRect&&!m.attrs.selfRectFunc&&!m._hasCachedAncestor(),g=f?m.width():0,x=f?m.height():0;f&&((t=m._attrsVersion)!==null&&t!==void 0||(m._attrsVersion=0));let y=f?l.get(m):void 0;if(!y||y.rotation!==r||y.ignoreStroke!==a||y.version!==m._attrsVersion||y.width!==g||y.height!==x){let v=m.getAbsoluteTransform();const[b,w,S,C]=v.getMatrix(),E=b*C-w*S===0,I=m.getClientRect({skipTransform:!E,skipShadow:!0,skipStroke:a}),P=[{x:I.x,y:I.y},{x:I.x+I.width,y:I.y},{x:I.x+I.width,y:I.y+I.height},{x:I.x,y:I.y+I.height}];E&&(v=new _0),y={rotation:r,ignoreStroke:a,width:g,height:x,version:m._attrsVersion||0,minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0};for(const R of P){const D=i.point(v.point(R));y.minX=Math.min(y.minX,D.x),y.minY=Math.min(y.minY,D.y),y.maxX=Math.max(y.maxX,D.x),y.maxY=Math.max(y.maxY,D.y)}f&&l.set(m,y)}o=Math.min(o,y.minX),c=Math.min(c,y.minY),d=Math.max(d,y.maxX),u=Math.max(u,y.maxY)}i.invert();const h=i.point({x:o,y:c});return{x:h.x,y:h.y,width:d-o,height:u-c,rotation:Qo.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(),UTe.forEach(t=>{this._createAnchor(t)}),this._createAnchor("rotater"),this._elementsCreated=!0}_createAnchor(t){const n=new jie({stroke:"rgb(0, 161, 255)",fill:"white",strokeWidth:1,name:t+" _anchor",dragDistance:0,draggable:!0,hitStrokeWidth:Jln?10:"auto"});this._anchors[t]=n;const r=this;n.on("mousedown touchstart",function(a){r._handleMouseDown(a)}),n.on("dragstart",a=>{n.stopDrag(),a.cancelBubble=!0}),n.on("dragend",a=>{a.cancelBubble=!0}),n.on("mouseenter",()=>{if(this.isTransforming())return;const a=Qo.getAngle(this.rotation()),i=this.rotateAnchorCursor(),l=ecn(t,a,i);n.getStage().content&&(n.getStage().content.style.cursor=l),this._cursorChange=!0}),n.on("mouseout",()=>{this._cursorChange=!1,!this.isTransforming()&&n.getStage().content&&(n.getStage().content.style.cursor="")}),this.add(n)}_createBack(){const t=new li({name:"back",width:0,height:0,sceneFunc(n,r){const a=r.getParent();if(!a.borderEnabled())return;const i=a.padding(),l=r.width(),o=r.height();if(n.beginPath(),n.rect(-i,-i,l+i*2,o+i*2),a.rotateEnabled()&&a.rotateLineVisible()){const c=pwt(a,l,o);n.moveTo(c.edgeX,c.edgeY),n.lineTo(c.endX,c.endY)}n.fillStrokeShape(r)},hitFunc:(n,r)=>{if(!this.shouldOverdrawWholeArea())return;const a=this.padding();n.beginPath(),n.rect(-a,-a,r.width()+a*2,r.height()+a*2),n.fillStrokeShape(r)}});this._back=t,this.add(t),this._proxyDrag(t),t.on("dragstart",n=>{n.cancelBubble=!0}),t.on("dragmove",n=>{n.cancelBubble=!0}),t.on("dragend",n=>{n.cancelBubble=!0}),this.on("dragmove",n=>{this.update()})}_handleMouseDown(t){var n,r;if(t.evt.button!==void 0&&!Qo.dragButtons.includes(t.evt.button)||this._transforming)return;this._movingAnchorName=t.target.name().split(" ")[0];const a=this._getNodeRect(),i=a.width,l=a.height,o=Math.sqrt(Math.pow(i,2)+Math.pow(l,2));this.sin=Math.abs(l/o),this.cos=Math.abs(i/o);const c=(n=this.getStage())===null||n===void 0?void 0:n._getOwnerWindow();this._transformWindow=c||null,c&&(c.addEventListener("mousemove",this._handleMouseMove),c.addEventListener("touchmove",this._handleMouseMove),c.addEventListener("mouseup",this._handleMouseUp,!0),c.addEventListener("touchend",this._handleMouseUp,!0),c.addEventListener("touchcancel",this._handleMouseUp,!0)),this._transforming=!0,this._pointerId=(r=t.pointerId)!==null&&r!==void 0?r:er._getFirstPointerId(t.evt);const d=t.target.getAbsolutePosition(),u=t.target.getStage()._getPointerById(this._pointerId);this._anchorDragOffset={x:u.x-d.x,y:u.y-d.y},S3e.add(this),this._fire("transformstart",{evt:t.evt,target:this.getNode()}),this._nodes.forEach(h=>{h._fire("transformstart",{evt:t.evt,target:h})})}_handleMouseMove(t){var n;(n=this.getStage())===null||n===void 0||n._batchEvents(()=>this._moveTransform(t))}_moveTransform(t){let n,r,a;const i=this._anchors[this._movingAnchorName],l=i.getStage();l.setPointersPositions(t);const o=l._getPointerById(this._pointerId);if(!o)return;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 u=i.getAbsolutePosition();if(d.x===u.x&&d.y===u.y)return;if(this._movingAnchorName==="rotater"){const w=this._getNodeRect();n=i.x()-w.width/2,r=-i.y()+w.height/2;const S=er.degToRad(this.rotateAnchorAngle());let C=Math.atan2(-r,n)+Math.PI/2-S;const I=Qo.getAngle(this.rotation())+C,P=Qo.getAngle(this.rotationSnapTolerance()),D=rcn(this.rotationSnaps(),I,P)-w.rotation,O=ncn(w,D);this._fitNodesInto(O,t);return}const h=this.shiftBehavior();let m;h==="inverted"?m=this.keepRatio()&&!t.shiftKey:h==="none"?m=this.keepRatio():m=this.keepRatio()||t.shiftKey;let f=this.centeredScaling()||t.altKey,g=!1;if(this._movingAnchorName==="top-left"){if(m){g=!0;const w=f?{x:this.width()/2,y:this.height()/2}:{x:this._anchors["bottom-right"].x(),y:this._anchors["bottom-right"].y()};a=Math.sqrt(Math.pow(w.x-i.x(),2)+Math.pow(w.y-i.y(),2));const S=this._anchors["top-left"].x()>w.x?-1:1,C=this._anchors["top-left"].y()>w.y?-1:1;n=a*this.cos*S,r=a*this.sin*C,this._anchors["top-left"].x(w.x-n),this._anchors["top-left"].y(w.y-r)}}else if(this._movingAnchorName==="top-center")this._anchors["top-left"].y(i.y());else if(this._movingAnchorName==="top-right"){if(m){g=!0;const w=f?{x:this.width()/2,y:this.height()/2}:{x:this._anchors["bottom-left"].x(),y:this._anchors["bottom-left"].y()};a=Math.sqrt(Math.pow(i.x()-w.x,2)+Math.pow(w.y-i.y(),2));const S=this._anchors["top-right"].x()w.y?-1:1;n=a*this.cos*S,r=a*this.sin*C,this._anchors["top-right"].x(w.x+n),this._anchors["top-right"].y(w.y-r)}var x=i.position();this._anchors["top-left"].y(x.y),this._anchors["bottom-right"].x(x.x)}else if(this._movingAnchorName==="middle-left")this._anchors["top-left"].x(i.x());else if(this._movingAnchorName==="middle-right")this._anchors["bottom-right"].x(i.x());else if(this._movingAnchorName==="bottom-left"){if(m){g=!0;const w=f?{x:this.width()/2,y:this.height()/2}:{x:this._anchors["top-right"].x(),y:this._anchors["top-right"].y()};a=Math.sqrt(Math.pow(w.x-i.x(),2)+Math.pow(i.y()-w.y,2));const S=w.xr.id===this._pointerId))||(n?n._batchEvents(()=>this._removeEvents(t)):this._removeEvents(t))}getAbsoluteTransform(t){const n=this.getTransform();return t?t.getAbsoluteTransform().copy().invert().multiply(n):n}_removeEvents(t){var n,r;if(this._transforming){this._transforming=!1;const a=(n=this.getStage())===null||n===void 0?void 0:n.content;a&&!this._cursorChange&&(a.style.cursor="");const i=this._transformWindow;this._transformWindow=null,i&&(i.removeEventListener("mousemove",this._handleMouseMove),i.removeEventListener("touchmove",this._handleMouseMove),i.removeEventListener("mouseup",this._handleMouseUp,!0),i.removeEventListener("touchend",this._handleMouseUp,!0),i.removeEventListener("touchcancel",this._handleMouseUp,!0));const l=this.getNode();S3e.delete(this),this._fire("transformend",{evt:t,target:l}),(r=this.getLayer())===null||r===void 0||r.batchDraw(),l&&this._nodes.forEach(o=>{var c;o._fire("transformend",{evt:t,target:o}),(c=o.getLayer())===null||c===void 0||c.batchDraw()}),this._movingAnchorName=null}}_fitNodesInto(t,n,r=!1){this._fitting=!0;try{return this._doFitNodesInto(t,n,r)}finally{this._fitting=!1}}_doFitNodesInto(t,n,r=!1){const a=this._getNodeRect(),i=1;if(!a.width||!a.height||er._inRange(t.width,-this.padding()*2-i,i)||er._inRange(t.height,-this.padding()*2-i,i)){this.update();return}const l=new _0;l.rotate(Qo.getAngle(this.rotation()));const o=r?0:this.padding()*2;let c=null,d=null;if(this._movingAnchorName&&t.width<0&&this._movingAnchorName.indexOf("left")>=0){const v=l.point({x:-o,y:0});t.x+=v.x,t.y+=v.y,t.width+=o,c={axis:"width",from:"left",to:"right",offset:v}}else if(this._movingAnchorName&&t.width<0&&this._movingAnchorName.indexOf("right")>=0){const v=l.point({x:o,y:0});t.width+=o,c={axis:"width",from:"right",to:"left",offset:v}}if(this._movingAnchorName&&t.height<0&&this._movingAnchorName.indexOf("top")>=0){const v=l.point({x:0,y:-o});t.x+=v.x,t.y+=v.y,t.height+=o,d={axis:"height",from:"top",to:"bottom",offset:v}}else if(this._movingAnchorName&&t.height<0&&this._movingAnchorName.indexOf("bottom")>=0){const v=l.point({x:0,y:o});t.height+=o,d={axis:"height",from:"bottom",to:"top",offset:v}}if(this.boundBoxFunc()){const v=this.boundBoxFunc()(a,t);v?t=v:er.warn("boundBoxFunc returned falsy. You should return new bound rect from it!")}for(const v of[c,d])v&&t[v.axis]<0&&this._movingAnchorName&&(this._movingAnchorName=this._movingAnchorName.replace(v.from,v.to),this._anchorDragOffset.x-=v.offset.x,this._anchorDragOffset.y-=v.offset.y);const u=1e7,h=new _0;h.translate(a.x,a.y),h.rotate(a.rotation),h.scale(a.width/u,a.height/u);const m=new _0,f=t.width/u,g=t.height/u;this.flipEnabled()===!1?(m.translate(t.x,t.y),m.rotate(t.rotation),m.translate(t.width<0?t.width:0,t.height<0?t.height:0),m.scale(Math.abs(f),Math.abs(g))):(m.translate(t.x,t.y),m.rotate(t.rotation),m.scale(f,g));const x=m.multiply(h.invert()),y=new Set;this._nodes.forEach(v=>{if(!v.getStage())return;const b=v.getParent().getAbsoluteTransform(),w=v.getTransform().copy();w.translate(v.offsetX(),v.offsetY());const S=new _0;S.multiply(b.copy().invert()).multiply(x).multiply(b).multiply(w);const C=S.decompose();v.setAttrs(C);const E=v.getLayer();E&&y.add(E)}),this.rotation(er._getRotation(t.rotation)),this._nodes.forEach(v=>{this._fire("transform",{evt:n,target:v}),v._fire("transform",{evt:n,target:v})}),this._resetTransformCache(),this.update(),y.add(this.getLayer()),y.forEach(v=>v&&v.batchDraw())}_scheduleUpdate(){this._updateScheduled||(this._updateScheduled=!0,zi._runAfterAbsTransformCascade(()=>{var t;this._updateScheduled=!1,!(!(!((t=this._nodes)===null||t===void 0)&&t.length)||this._fitting||this.isDragging())&&this._update()}))}forceUpdate(){this._resetTransformCache(),this.update()}update(){this._lastNodeRect=void 0,this._update()}_update(){var t;const n=this._getNodeRect();this._updateElements(n);const r=this.nodes().some(i=>i.draggable());this._back.draggable()!==r&&this._back.draggable(r);const a=this.anchorStyleFunc();a&&Object.values(this._anchors).forEach(i=>a(i)),(t=this.getLayer())===null||t===void 0||t.batchDraw()}_updateElements(t){const n=this._lastNodeRect;if(n&&!this.anchorStyleFunc()&&t.x===n.x&&t.y===n.y&&t.width===n.width&&t.height===n.height&&t.rotation===n.rotation)return;this._lastNodeRect={...t};const r=t.width,a=t.height,i=this.enabledAnchors(),l=this.resizeEnabled(),o=this.padding(),c=this.anchorSize();Object.values(this._anchors).forEach(h=>{h.setAttrs({width:c,height:c,offsetX:c/2,offsetY:c/2,stroke:this.anchorStroke(),strokeWidth:this.anchorStrokeWidth(),fill:this.anchorFill(),cornerRadius:this.anchorCornerRadius()})}),this._anchors["top-left"].setAttrs({x:0,y:0,offsetX:c/2+o,offsetY:c/2+o,visible:l&&i.indexOf("top-left")>=0}),this._anchors["top-center"].setAttrs({x:r/2,y:0,offsetY:c/2+o,visible:l&&i.indexOf("top-center")>=0}),this._anchors["top-right"].setAttrs({x:r,y:0,offsetX:c/2-o,offsetY:c/2+o,visible:l&&i.indexOf("top-right")>=0}),this._anchors["middle-left"].setAttrs({x:0,y:a/2,offsetX:c/2+o,visible:l&&i.indexOf("middle-left")>=0}),this._anchors["middle-right"].setAttrs({x:r,y:a/2,offsetX:c/2-o,visible:l&&i.indexOf("middle-right")>=0}),this._anchors["bottom-left"].setAttrs({x:0,y:a,offsetX:c/2+o,offsetY:c/2-o,visible:l&&i.indexOf("bottom-left")>=0}),this._anchors["bottom-center"].setAttrs({x:r/2,y:a,offsetY:c/2-o,visible:l&&i.indexOf("bottom-center")>=0}),this._anchors["bottom-right"].setAttrs({x:r,y:a,offsetX:c/2-o,offsetY:c/2-o,visible:l&&i.indexOf("bottom-right")>=0});const u=pwt(this,r,a);this._anchors.rotater.setAttrs({x:u.endX,y:u.endY,visible:this.rotateEnabled()}),this._back.setAttrs({width:r,height:a,visible:this.borderEnabled()||this.shouldOverdrawWholeArea(),stroke:this.borderStroke(),strokeWidth:this.borderStrokeWidth(),dash:this.borderDash(),x:0,y:0})}isTransforming(){return this._transforming}stopTransform(){this._transforming&&this._removeEvents()}destroy(){return this.getStage()&&this._cursorChange&&this.getStage().content&&(this.getStage().content.style.cursor=""),rB.prototype.destroy.call(this),this.detach(),this._removeEvents(),this}add(...t){return this._elementsCreated?(er.error("You cannot add external nodes to the Transformer. Use tr.nodes([node]) instead."),this):super.add(...t)}toObject(){return zi.prototype.toObject.call(this)}clone(t){return zi.prototype.clone.call(this,t)}getClientRect(t){return this.nodes().length>0?super.getClientRect(t):{x:0,y:0,width:0,height:0}}};Hu.isTransforming=()=>S3e.size>0;function acn(s){return s instanceof Array||er.warn("enabledAnchors value should be an array"),s instanceof Array&&s.forEach(function(t){UTe.indexOf(t)===-1&&er.warn("Unknown anchor name: "+t+". Available names are: "+UTe.join(", "))}),s||[]}Hu.prototype.className="Transformer";Yg(Hu);Tn.addGetterSetter(Hu,"enabledAnchors",UTe,acn);Tn.addGetterSetter(Hu,"flipEnabled",!0,kC());Tn.addGetterSetter(Hu,"resizeEnabled",!0);Tn.addGetterSetter(Hu,"anchorSize",10,Ti());Tn.addGetterSetter(Hu,"rotateEnabled",!0);Tn.addGetterSetter(Hu,"rotateLineVisible",!0);Tn.addGetterSetter(Hu,"rotationSnaps",[]);Tn.addGetterSetter(Hu,"rotateAnchorOffset",50,Ti());Tn.addGetterSetter(Hu,"rotateAnchorAngle",0,Ti());Tn.addGetterSetter(Hu,"rotateAnchorCursor","crosshair");Tn.addGetterSetter(Hu,"rotationSnapTolerance",5,Ti());Tn.addGetterSetter(Hu,"borderEnabled",!0);Tn.addGetterSetter(Hu,"anchorStroke","rgb(0, 161, 255)");Tn.addGetterSetter(Hu,"anchorStrokeWidth",1,Ti());Tn.addGetterSetter(Hu,"anchorFill","white");Tn.addGetterSetter(Hu,"anchorCornerRadius",0,Ti());Tn.addGetterSetter(Hu,"borderStroke","rgb(0, 161, 255)");Tn.addGetterSetter(Hu,"borderStrokeWidth",1,Ti());Tn.addGetterSetter(Hu,"borderDash");Tn.addGetterSetter(Hu,"keepRatio",!0);Tn.addGetterSetter(Hu,"shiftBehavior","default");Tn.addGetterSetter(Hu,"centeredScaling",!1);Tn.addGetterSetter(Hu,"ignoreStroke",!1);Tn.addGetterSetter(Hu,"padding",0,Ti());Tn.addGetterSetter(Hu,"nodes");Tn.addGetterSetter(Hu,"node");Tn.addGetterSetter(Hu,"boundBoxFunc");Tn.addGetterSetter(Hu,"anchorDragBoundFunc");Tn.addGetterSetter(Hu,"anchorStyleFunc");Tn.addGetterSetter(Hu,"shouldOverdrawWholeArea",!1);Tn.addGetterSetter(Hu,"useSingleNodeRotation",!0);Tn.backCompat(Hu,{lineEnabled:"borderEnabled",rotateHandlerOffset:"rotateAnchorOffset",enabledHandlers:"enabledAnchors"});class DT extends li{_sceneFunc(t){t.beginPath(),t.arc(0,0,Math.abs(this.radius()),0,Qo.getAngle(this.angle()),this.clockwise()),t.lineTo(0,0),t.closePath(),t.fillStrokeShape(this)}getWidth(){return Math.abs(this.radius())*2}getHeight(){return Math.abs(this.radius())*2}setWidth(t){this.radius(t/2)}setHeight(t){this.radius(t/2)}}DT.prototype.className="Wedge";DT.prototype._centroid=!0;DT.prototype._attrsAffectingSize=["radius"];Yg(DT,!0);Tn.addGetterSetter(DT,"radius",0,Ti());Tn.addGetterSetter(DT,"angle",0,Ti());Tn.addGetterSetter(DT,"clockwise",!1);Tn.backCompat(DT,{angleDeg:"angle",getAngleDeg:"getAngle",setAngleDeg:"setAngle"});/* StackBlur - a fast almost Gaussian Blur For Canvas Version: 0.5 Author: Mario Klingemann Contact: mario@quasimondo.com Website: http://www.quasimondo.com/StackBlurForCanvas Twitter: @quasimondo In case you find this class useful - especially in commercial projects - I am not totally unhappy for a small donation to my PayPal account mario@quasimondo.de Or support me on flattr: https://flattr.com/thing/72791/StackBlur-a-fast-almost-Gaussian-Blur-Effect-for-CanvasJavascript Copyright (c) 2010 Mario Klingemann Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * @license MIT */function gwt(){this.r=0,this.g=0,this.b=0,this.a=0,this.next=null}const icn=[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],ocn=[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 nA(s,t){return t===255?s:s*t/255}const JGt=180;function lcn(s,t){const n=s.data,r=s.width,a=s.height;let i,l,o,c,d,u,h,m,f,g,x,y,v,b,w,S,C,E,I,P;const R=t+t+1,D=r-1,O=a-1,U=t+1,W=U*(U+1)/2,V=new gwt,G=t<=JGt?icn[t]/2**ocn[t]:1/(U*U);let Y=null,X=V,ae=null,ie=null;for(let ne=1;ne0?(I=255/I,n[i]=Math.floor(c*G)*I,n[i+1]=Math.floor(d*G)*I,n[i+2]=Math.floor(u*G)*I):n[i]=n[i+1]=n[i+2]=0,c-=m,d-=f,u-=g,h-=x,m-=ae.r,f-=ae.g,g-=ae.b,x-=ae.a,i=ne+((i=J+U)0&&lcn(t,r)};Tn.addGetterSetter(zi,"blurRadius",0,Ti(),Tn.afterSetFilter);const dcn=function(s){const t=this.brightness()*255,n=s.data,r=n.length;for(let a=0;a255?255:a,i=i<0?0:i>255?255:i,l=l<0?0:l>255?255:l,n[o]=a,n[o+1]=i,n[o+2]=l};Tn.addGetterSetter(zi,"contrast",0,Ti(),Tn.afterSetFilter);const mcn=function(s){var t,n,r,a,i,l,o,c,d;const u=s.data,h=s.width,m=s.height,f=Math.min(1,Math.max(0,(n=(t=this.embossStrength)===null||t===void 0?void 0:t.call(this))!==null&&n!==void 0?n:.5)),g=Math.min(1,Math.max(0,(a=(r=this.embossWhiteLevel)===null||r===void 0?void 0:r.call(this))!==null&&a!==void 0?a:.5)),y=(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,v=!!((d=(c=this.embossBlend)===null||c===void 0?void 0:c.call(this))!==null&&d!==void 0&&d),b=f*10,w=g*255,S=y*Math.PI/180,C=Math.cos(S),E=Math.sin(S),I=128/1020*b,P=new Float32Array(h*m);for(let U=0,W=0;WU<0?0:U>255?255:U;for(let U=0;Ua&&(a=i),c=t[w+1],co&&(o=c),h=t[w+2],hu&&(u=h);a===r&&(a=255,r=0),o===l&&(o=255,l=0),u===d&&(u=255,d=0);let f,g,x,y,v,b;if(m>0)f=a+m*(255-a),g=r-m*(r-0),x=o+m*(255-o),y=l-m*(l-0),v=u+m*(255-u),b=d-m*(d-0);else{const w=(a+r)*.5;f=a+m*(a-w),g=r+m*(r-w);const S=(o+l)*.5;x=o+m*(o-S),y=l+m*(l-S);const C=(u+d)*.5;v=u+m*(u-C),b=d+m*(d-C)}for(let w=0;wd?m:d;const f=l,g=i,x=360/g*Math.PI/180;for(let y=0;yd?m:d;const f=l,g=i,x=0;let y,v;for(u=0;ut&&(w=b,S=0,C=-1),a=0;a=0&&f=0&&g=0&&f=0&&g=255*4?255:0}return l}function Ccn(s,t,n){const r=[.1111111111111111,.1111111111111111,.1111111111111111,.1111111111111111,.1111111111111111,.1111111111111111,.1111111111111111,.1111111111111111,.1111111111111111],a=Math.round(Math.sqrt(r.length)),i=Math.floor(a/2),l=[];for(let o=0;o=0&&f=0&&gMath.min(1,Math.max(0,s)),Tn.afterSetFilter);const Lcn=function(s){const t=s.data,n=t.length;for(let r=0;r=128&&(n[r]=255-a,n[r+1]=255-i,n[r+2]=255-l)}return s},Dcn=function(s){const t=this.threshold()*255,n=s.data,r=n.length;for(let a=0;afr||dt[Ks]!==Ot[fr]){var $r=` `+dt[Ks].replace(" at new "," at ");return oe.displayName&&$r.includes("")&&($r=$r.replace("",oe.displayName)),$r}while(1<=Ks&&0<=fr);break}}}finally{Ho=!1,Error.prepareStackTrace=Oe}return(oe=oe?oe.displayName||oe.name:"")?Nl(oe):""}var Xr=Object.prototype.hasOwnProperty,Eo=[],Ph=-1;function ih(oe){return{current:oe}}function ao(oe){0>Ph||(oe.current=Eo[Ph],Eo[Ph]=null,Ph--)}function ta(oe,de){Ph++,Eo[Ph]=oe.current,oe.current=de}var xc={},fl=ih(xc),Co=ih(!1),pu=xc;function nc(oe,de){var Oe=oe.type.contextTypes;if(!Oe)return xc;var et=oe.stateNode;if(et&&et.__reactInternalMemoizedUnmaskedChildContext===de)return et.__reactInternalMemoizedMaskedChildContext;var dt={},Ot;for(Ot in Oe)dt[Ot]=de[Ot];return et&&(oe=oe.stateNode,oe.__reactInternalMemoizedUnmaskedChildContext=de,oe.__reactInternalMemoizedMaskedChildContext=dt),dt}function ad(oe){return oe=oe.childContextTypes,oe!=null}function zr(){ao(Co),ao(fl)}function Hi(oe,de,Oe){if(fl.current!==xc)throw Error(l(168));ta(fl,de),ta(Co,Oe)}function Bc(oe,de,Oe){var et=oe.stateNode;if(de=de.childContextTypes,typeof et.getChildContext!="function")return Oe;et=et.getChildContext();for(var dt in et)if(!(dt in de))throw Error(l(108,P(oe)||"Unknown",dt));return i({},Oe,et)}function $c(oe){return oe=(oe=oe.stateNode)&&oe.__reactInternalMemoizedMergedChildContext||xc,pu=fl.current,ta(fl,oe),ta(Co,Co.current),!0}function yc(oe,de,Oe){var et=oe.stateNode;if(!et)throw Error(l(169));Oe?(oe=Bc(oe,de,pu),et.__reactInternalMemoizedMergedChildContext=oe,ao(Co),ao(fl),ta(fl,oe)):ao(Co),ta(Co,Oe)}var Ul=Math.clz32?Math.clz32:Yo,rg=Math.log,Lx=Math.LN2;function Yo(oe){return oe>>>=0,oe===0?32:31-(rg(oe)/Lx|0)|0}var Ic=64,Ih=4194304;function cm(oe){switch(oe&-oe){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 oe&4194240;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return oe&130023424;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 1073741824;default:return oe}}function Xc(oe,de){var Oe=oe.pendingLanes;if(Oe===0)return 0;var et=0,dt=oe.suspendedLanes,Ot=oe.pingedLanes,Ks=Oe&268435455;if(Ks!==0){var fr=Ks&~dt;fr!==0?et=cm(fr):(Ot&=Ks,Ot!==0&&(et=cm(Ot)))}else Ks=Oe&~dt,Ks!==0?et=cm(Ks):Ot!==0&&(et=cm(Ot));if(et===0)return 0;if(de!==0&&de!==et&&!(de&dt)&&(dt=et&-et,Ot=de&-de,dt>=Ot||dt===16&&(Ot&4194240)!==0))return de;if(et&4&&(et|=Oe&16),de=oe.entangledLanes,de!==0)for(oe=oe.entanglements,de&=et;0Oe;Oe++)de.push(oe);return de}function ko(oe,de,Oe){oe.pendingLanes|=de,de!==536870912&&(oe.suspendedLanes=0,oe.pingedLanes=0),oe=oe.eventTimes,de=31-Ul(de),oe[de]=Oe}function qi(oe,de){var Oe=oe.pendingLanes&~de;oe.pendingLanes=de,oe.suspendedLanes=0,oe.pingedLanes=0,oe.expiredLanes&=de,oe.mutableReadLanes&=de,oe.entangledLanes&=de,de=oe.entanglements;var et=oe.eventTimes;for(oe=oe.expirationTimes;0>=Ks,dt-=Ks,sr=1<<32-Ul(de)+dt|Oe<Id?(_h=Cc,Cc=null):_h=Cc.sibling;var Sl=Zi(Ur,Cc,ia[Id],Qi);if(Sl===null){Cc===null&&(Cc=_h);break}oe&&Cc&&Sl.alternate===null&&de(Ur,Cc),Kn=Ot(Sl,Kn,Id),td===null?xl=Sl:td.sibling=Sl,td=Sl,Cc=_h}if(Id===ia.length)return Oe(Ur,Cc),tn&&vr(Ur,Id),xl;if(Cc===null){for(;IdId?(_h=Cc,Cc=null):_h=Cc.sibling;var xr=Zi(Ur,Cc,Sl.value,Qi);if(xr===null){Cc===null&&(Cc=_h);break}oe&&Cc&&xr.alternate===null&&de(Ur,Cc),Kn=Ot(xr,Kn,Id),td===null?xl=xr:td.sibling=xr,td=xr,Cc=_h}if(Sl.done)return Oe(Ur,Cc),tn&&vr(Ur,Id),xl;if(Cc===null){for(;!Sl.done;Id++,Sl=ia.next())Sl=gl(Ur,Sl.value,Qi),Sl!==null&&(Kn=Ot(Sl,Kn,Id),td===null?xl=Sl:td.sibling=Sl,td=Sl);return tn&&vr(Ur,Id),xl}for(Cc=et(Ur,Cc);!Sl.done;Id++,Sl=ia.next())Sl=Kh(Cc,Ur,Id,Sl.value,Qi),Sl!==null&&(oe&&Sl.alternate!==null&&Cc.delete(Sl.key===null?Id:Sl.key),Kn=Ot(Sl,Kn,Id),td===null?xl=Sl:td.sibling=Sl,td=Sl);return oe&&Cc.forEach(function(Tr){return de(Ur,Tr)}),tn&&vr(Ur,Id),xl}function W_(Ur,Kn,ia,Qi){if(typeof ia=="object"&&ia!==null&&ia.type===u&&ia.key===null&&(ia=ia.props.children),typeof ia=="object"&&ia!==null){switch(ia.$$typeof){case c:e:{for(var xl=ia.key,td=Kn;td!==null;){if(td.key===xl){if(xl=ia.type,xl===u){if(td.tag===7){Oe(Ur,td.sibling),Kn=dt(td,ia.props.children),Kn.return=Ur,Ur=Kn;break e}}else if(td.elementType===xl||typeof xl=="object"&&xl!==null&&xl.$$typeof===w&&iu(xl)===td.type){Oe(Ur,td.sibling),Kn=dt(td,ia.props),Kn.ref=Il(Ur,td,ia),Kn.return=Ur,Ur=Kn;break e}Oe(Ur,td);break}else de(Ur,td);td=td.sibling}ia.type===u?(Kn=lj(ia.props.children,Ur.mode,Qi,ia.key),Kn.return=Ur,Ur=Kn):(Qi=Gk(ia.type,ia.key,ia.props,null,Ur.mode,Qi),Qi.ref=Il(Ur,Kn,ia),Qi.return=Ur,Ur=Qi)}return Ks(Ur);case d:e:{for(td=ia.key;Kn!==null;){if(Kn.key===td)if(Kn.tag===4&&Kn.stateNode.containerInfo===ia.containerInfo&&Kn.stateNode.implementation===ia.implementation){Oe(Ur,Kn.sibling),Kn=dt(Kn,ia.children||[]),Kn.return=Ur,Ur=Kn;break e}else{Oe(Ur,Kn);break}else de(Ur,Kn);Kn=Kn.sibling}Kn=qC(ia,Ur.mode,Qi),Kn.return=Ur,Ur=Kn}return Ks(Ur);case w:return td=ia._init,W_(Ur,Kn,td(ia._payload),Qi)}if(G(ia))return mh(Ur,Kn,ia,Qi);if(E(ia))return wy(Ur,Kn,ia,Qi);Ed(Ur,ia)}return typeof ia=="string"&&ia!==""||typeof ia=="number"?(ia=""+ia,Kn!==null&&Kn.tag===6?(Oe(Ur,Kn.sibling),Kn=dt(Kn,ia),Kn.return=Ur,Ur=Kn):(Oe(Ur,Kn),Kn=UC(ia,Ur.mode,Qi),Kn.return=Ur,Ur=Kn),Ks(Ur)):Oe(Ur,Kn)}return W_}var Cn=Ut(!0),ar=Ut(!1),ra=ih(null),Zr=null,Aa=null,xi=null;function Ia(){xi=Aa=Zr=null}function el(oe,de,Oe){Le?(ta(ra,de._currentValue),de._currentValue=Oe):(ta(ra,de._currentValue2),de._currentValue2=Oe)}function zo(oe){var de=ra.current;ao(ra),Le?oe._currentValue=de:oe._currentValue2=de}function Lc(oe,de,Oe){for(;oe!==null;){var et=oe.alternate;if((oe.childLanes&de)!==de?(oe.childLanes|=de,et!==null&&(et.childLanes|=de)):et!==null&&(et.childLanes&de)!==de&&(et.childLanes|=de),oe===Oe)break;oe=oe.return}}function Mu(oe,de){Zr=oe,xi=Aa=null,oe=oe.dependencies,oe!==null&&oe.firstContext!==null&&(oe.lanes&de&&(tx=!0),oe.firstContext=null)}function ou(oe){var de=Le?oe._currentValue:oe._currentValue2;if(xi!==oe)if(oe={context:oe,memoizedValue:de,next:null},Aa===null){if(Zr===null)throw Error(l(308));Aa=oe,Zr.dependencies={lanes:0,firstContext:oe}}else Aa=Aa.next=oe;return de}var um=null;function Td(oe){um===null?um=[oe]:um.push(oe)}function gu(oe,de,Oe,et){var dt=de.interleaved;return dt===null?(Oe.next=Oe,Td(de)):(Oe.next=dt.next,dt.next=Oe),de.interleaved=Oe,Qc(oe,et)}function Qc(oe,de){oe.lanes|=de;var Oe=oe.alternate;for(Oe!==null&&(Oe.lanes|=de),Oe=oe,oe=oe.return;oe!==null;)oe.childLanes|=de,Oe=oe.alternate,Oe!==null&&(Oe.childLanes|=de),Oe=oe,oe=oe.return;return Oe.tag===3?Oe.stateNode:null}var id=!1;function lh(oe){oe.updateQueue={baseState:oe.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,interleaved:null,lanes:0},effects:null}}function If(oe,de){oe=oe.updateQueue,de.updateQueue===oe&&(de.updateQueue={baseState:oe.baseState,firstBaseUpdate:oe.firstBaseUpdate,lastBaseUpdate:oe.lastBaseUpdate,shared:oe.shared,effects:oe.effects})}function Ud(oe,de){return{eventTime:oe,lane:de,tag:0,payload:null,callback:null,next:null}}function od(oe,de,Oe){var et=oe.updateQueue;if(et===null)return null;if(et=et.shared,Ql&2){var dt=et.pending;return dt===null?de.next=de:(de.next=dt.next,dt.next=de),et.pending=de,Qc(oe,Oe)}return dt=et.interleaved,dt===null?(de.next=de,Td(et)):(de.next=dt.next,dt.next=de),et.interleaved=de,Qc(oe,Oe)}function Lh(oe,de,Oe){if(de=de.updateQueue,de!==null&&(de=de.shared,(Oe&4194240)!==0)){var et=de.lanes;et&=oe.pendingLanes,Oe|=et,de.lanes=Oe,dm(oe,Oe)}}function Gu(oe,de){var Oe=oe.updateQueue,et=oe.alternate;if(et!==null&&(et=et.updateQueue,Oe===et)){var dt=null,Ot=null;if(Oe=Oe.firstBaseUpdate,Oe!==null){do{var Ks={eventTime:Oe.eventTime,lane:Oe.lane,tag:Oe.tag,payload:Oe.payload,callback:Oe.callback,next:null};Ot===null?dt=Ot=Ks:Ot=Ot.next=Ks,Oe=Oe.next}while(Oe!==null);Ot===null?dt=Ot=de:Ot=Ot.next=de}else dt=Ot=de;Oe={baseState:et.baseState,firstBaseUpdate:dt,lastBaseUpdate:Ot,shared:et.shared,effects:et.effects},oe.updateQueue=Oe;return}oe=Oe.lastBaseUpdate,oe===null?Oe.firstBaseUpdate=de:oe.next=de,Oe.lastBaseUpdate=de}function qd(oe,de,Oe,et){var dt=oe.updateQueue;id=!1;var Ot=dt.firstBaseUpdate,Ks=dt.lastBaseUpdate,fr=dt.shared.pending;if(fr!==null){dt.shared.pending=null;var $r=fr,ui=$r.next;$r.next=null,Ks===null?Ot=ui:Ks.next=ui,Ks=$r;var Pi=oe.alternate;Pi!==null&&(Pi=Pi.updateQueue,fr=Pi.lastBaseUpdate,fr!==Ks&&(fr===null?Pi.firstBaseUpdate=ui:fr.next=ui,Pi.lastBaseUpdate=$r))}if(Ot!==null){var gl=dt.baseState;Ks=0,Pi=ui=$r=null,fr=Ot;do{var Zi=fr.lane,Kh=fr.eventTime;if((et&Zi)===Zi){Pi!==null&&(Pi=Pi.next={eventTime:Kh,lane:0,tag:fr.tag,payload:fr.payload,callback:fr.callback,next:null});e:{var mh=oe,wy=fr;switch(Zi=de,Kh=Oe,wy.tag){case 1:if(mh=wy.payload,typeof mh=="function"){gl=mh.call(Kh,gl,Zi);break e}gl=mh;break e;case 3:mh.flags=mh.flags&-65537|128;case 0:if(mh=wy.payload,Zi=typeof mh=="function"?mh.call(Kh,gl,Zi):mh,Zi==null)break e;gl=i({},gl,Zi);break e;case 2:id=!0}}fr.callback!==null&&fr.lane!==0&&(oe.flags|=64,Zi=dt.effects,Zi===null?dt.effects=[fr]:Zi.push(fr))}else Kh={eventTime:Kh,lane:Zi,tag:fr.tag,payload:fr.payload,callback:fr.callback,next:null},Pi===null?(ui=Pi=Kh,$r=gl):Pi=Pi.next=Kh,Ks|=Zi;if(fr=fr.next,fr===null){if(fr=dt.shared.pending,fr===null)break;Zi=fr,fr=Zi.next,Zi.next=null,dt.lastBaseUpdate=Zi,dt.shared.pending=null}}while(!0);if(Pi===null&&($r=gl),dt.baseState=$r,dt.firstBaseUpdate=ui,dt.lastBaseUpdate=Pi,de=dt.shared.interleaved,de!==null){dt=de;do Ks|=dt.lane,dt=dt.next;while(dt!==de)}else Ot===null&&(dt.shared.lanes=0);V1|=Ks,oe.lanes=Ks,oe.memoizedState=gl}}function hd(oe,de,Oe){if(oe=de.effects,de.effects=null,oe!==null)for(de=0;deOe?Oe:4,oe(!0);var et=Dx.transition;Dx.transition={};try{oe(!1),de()}finally{Zo=Oe,Dx.transition=et}}function Db(){return uf().memoizedState}function $v(oe,de,Oe){var et=W1(oe);if(Oe={lane:et,action:Oe,hasEagerState:!1,eagerState:null,next:null},Z2(oe))rp(de,Oe);else if(Oe=gu(oe,de,Oe,et),Oe!==null){var dt=cp();Ux(Oe,oe,et,dt),Dk(Oe,de,et)}}function C3(oe,de,Oe){var et=W1(oe),dt={lane:et,action:Oe,hasEagerState:!1,eagerState:null,next:null};if(Z2(oe))rp(de,dt);else{var Ot=oe.alternate;if(oe.lanes===0&&(Ot===null||Ot.lanes===0)&&(Ot=de.lastRenderedReducer,Ot!==null))try{var Ks=de.lastRenderedState,fr=Ot(Ks,Oe);if(dt.hasEagerState=!0,dt.eagerState=fr,jt(fr,Ks)){var $r=de.interleaved;$r===null?(dt.next=dt,Td(de)):(dt.next=$r.next,$r.next=dt),de.interleaved=dt;return}}catch{}finally{}Oe=gu(oe,de,dt,et),Oe!==null&&(dt=cp(),Ux(Oe,oe,et,dt),Dk(Oe,de,et))}}function Z2(oe){var de=oe.alternate;return oe===Sc||de!==null&&de===Sc}function rp(oe,de){fa=xu=!0;var Oe=oe.pending;Oe===null?de.next=de:(de.next=Oe.next,Oe.next=de),oe.pending=de}function Dk(oe,de,Oe){if(Oe&4194240){var et=de.lanes;et&=oe.pendingLanes,Oe|=et,de.lanes=Oe,dm(oe,Oe)}}var B1={readContext:ou,useCallback:ed,useContext:ed,useEffect:ed,useImperativeHandle:ed,useInsertionEffect:ed,useLayoutEffect:ed,useMemo:ed,useReducer:ed,useRef:ed,useState:ed,useDebugValue:ed,useDeferredValue:ed,useTransition:ed,useMutableSource:ed,useSyncExternalStore:ed,useId:ed,unstable_isNewReconciler:!1},ex={readContext:ou,useCallback:function(oe,de){return yh().memoizedState=[oe,de===void 0?null:de],oe},useContext:ou,useEffect:Qg,useImperativeHandle:function(oe,de,Oe){return Oe=Oe!=null?Oe.concat([oe]):null,ch(4194308,4,F1.bind(null,de,oe),Oe)},useLayoutEffect:function(oe,de){return ch(4194308,4,oe,de)},useInsertionEffect:function(oe,de){return ch(4,2,oe,de)},useMemo:function(oe,de){var Oe=yh();return de=de===void 0?null:de,oe=oe(),Oe.memoizedState=[oe,de],oe},useReducer:function(oe,de,Oe){var et=yh();return de=Oe!==void 0?Oe(de):de,et.memoizedState=et.baseState=de,oe={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:oe,lastRenderedState:de},et.queue=oe,oe=oe.dispatch=$v.bind(null,Sc,oe),[et.memoizedState,oe]},useRef:function(oe){var de=yh();return oe={current:oe},de.memoizedState=oe},useState:vh,useDebugValue:z1,useDeferredValue:function(oe){return yh().memoizedState=oe},useTransition:function(){var oe=vh(!1),de=oe[0];return oe=Rk.bind(null,oe[1]),yh().memoizedState=oe,[de,oe]},useMutableSource:function(){},useSyncExternalStore:function(oe,de,Oe){var et=Sc,dt=yh();if(tn){if(Oe===void 0)throw Error(l(407));Oe=Oe()}else{if(Oe=de(),Gd===null)throw Error(l(349));Wu&30||Rb(et,de,Oe)}dt.memoizedState=Oe;var Ot={value:Oe,getSnapshot:de};return dt.queue=Ot,Qg(Bm.bind(null,et,Ot,oe),[oe]),et.flags|=2048,Ui(9,ej.bind(null,et,Ot,Oe,de),void 0,null),Oe},useId:function(){var oe=yh(),de=Gd.identifierPrefix;if(tn){var Oe=br,et=sr;Oe=(et&~(1<<32-Ul(et)-1)).toString(32)+Oe,de=":"+de+"R"+Oe,Oe=Ao++,0Uk&&(de.flags|=128,et=!0,Cr(dt,!1),de.lanes=4194304)}else{if(!et)if(oe=Zy(Ot),oe!==null){if(de.flags|=128,et=!0,oe=oe.updateQueue,oe!==null&&(de.updateQueue=oe,de.flags|=4),Cr(dt,!0),dt.tail===null&&dt.tailMode==="hidden"&&!Ot.alternate&&!tn)return Js(de),null}else 2*Xd()-dt.renderingStartTime>Uk&&Oe!==1073741824&&(de.flags|=128,et=!0,Cr(dt,!1),de.lanes=4194304);dt.isBackwards?(Ot.sibling=de.child,de.child=Ot):(oe=dt.last,oe!==null?oe.sibling=Ot:de.child=Ot,dt.last=Ot)}return dt.tail!==null?(de=dt.tail,dt.rendering=de,dt.tail=de.sibling,dt.renderingStartTime=Xd(),de.sibling=null,oe=ya.current,ta(ya,et?oe&1|2:oe&1),de):(Js(de),null);case 22:case 23:return G_(),Oe=de.memoizedState!==null,oe!==null&&oe.memoizedState!==null!==Oe&&(de.flags|=8192),Oe&&de.mode&1?Bx&1073741824&&(Js(de),Fe&&de.subtreeFlags&6&&(de.flags|=8192)):Js(de),null;case 24:return null;case 25:return null}throw Error(l(156,de.tag))}function _r(oe,de){switch(Ht(de),de.tag){case 1:return ad(de.type)&&zr(),oe=de.flags,oe&65536?(de.flags=oe&-65537|128,de):null;case 3:return Ep(),ao(Co),ao(fl),Xg(),oe=de.flags,oe&65536&&!(oe&128)?(de.flags=oe&-65537|128,de):null;case 5:return Rx(de),null;case 13:if(ao(ya),oe=de.memoizedState,oe!==null&&oe.dehydrated!==null){if(de.alternate===null)throw Error(l(340));oo()}return oe=de.flags,oe&65536?(de.flags=oe&-65537|128,de):null;case 19:return ao(ya),null;case 4:return Ep(),null;case 10:return zo(de.type._context),null;case 22:case 23:return G_(),null;case 24:return null;default:return null}}var aa=!1,mr=!1,pa=typeof WeakSet=="function"?WeakSet:Set,dr=null;function Ua(oe,de){var Oe=oe.ref;if(Oe!==null)if(typeof Oe=="function")try{Oe(null)}catch(et){jm(oe,de,et)}else Oe.current=null}function Ea(oe,de,Oe){try{Oe()}catch(et){jm(oe,de,et)}}var _o=!1;function Fi(oe,de){for(ie(oe.containerInfo),dr=de;dr!==null;)if(oe=dr,de=oe.child,(oe.subtreeFlags&1028)!==0&&de!==null)de.return=oe,dr=de;else for(;dr!==null;){oe=dr;try{var Oe=oe.alternate;if(oe.flags&1024)switch(oe.tag){case 0:case 11:case 15:break;case 1:if(Oe!==null){var et=Oe.memoizedProps,dt=Oe.memoizedState,Ot=oe.stateNode,Ks=Ot.getSnapshotBeforeUpdate(oe.elementType===oe.type?et:Hd(oe.type,et),dt);Ot.__reactInternalSnapshotBeforeUpdate=Ks}break;case 3:Fe&&cs(oe.stateNode.containerInfo);break;case 5:case 6:case 4:case 17:break;default:throw Error(l(163))}}catch(fr){jm(oe,oe.return,fr)}if(de=oe.sibling,de!==null){de.return=oe.return,dr=de;break}dr=oe.return}return Oe=_o,_o=!1,Oe}function bl(oe,de,Oe){var et=de.updateQueue;if(et=et!==null?et.lastEffect:null,et!==null){var dt=et=et.next;do{if((dt.tag&oe)===oe){var Ot=dt.destroy;dt.destroy=void 0,Ot!==void 0&&Ea(de,Oe,Ot)}dt=dt.next}while(dt!==et)}}function lo(oe,de){if(de=de.updateQueue,de=de!==null?de.lastEffect:null,de!==null){var Oe=de=de.next;do{if((Oe.tag&oe)===oe){var et=Oe.create;Oe.destroy=et()}Oe=Oe.next}while(Oe!==de)}}function Dc(oe){var de=oe.ref;if(de!==null){var Oe=oe.stateNode;switch(oe.tag){case 5:oe=Y(Oe);break;default:oe=Oe}typeof de=="function"?de(oe):de.current=oe}}function mf(oe){var de=oe.alternate;de!==null&&(oe.alternate=null,mf(de)),oe.child=null,oe.deletions=null,oe.sibling=null,oe.tag===5&&(de=oe.stateNode,de!==null&&qe(de)),oe.stateNode=null,oe.return=null,oe.dependencies=null,oe.memoizedProps=null,oe.memoizedState=null,oe.pendingProps=null,oe.stateNode=null,oe.updateQueue=null}function Zl(oe){return oe.tag===5||oe.tag===3||oe.tag===4}function yo(oe){e:for(;;){for(;oe.sibling===null;){if(oe.return===null||Zl(oe.return))return null;oe=oe.return}for(oe.sibling.return=oe.return,oe=oe.sibling;oe.tag!==5&&oe.tag!==6&&oe.tag!==18;){if(oe.flags&2||oe.child===null||oe.tag===4)continue e;oe.child.return=oe,oe=oe.child}if(!(oe.flags&2))return oe.stateNode}}function bi(oe,de,Oe){var et=oe.tag;if(et===5||et===6)oe=oe.stateNode,de?rs(Oe,oe,de):qt(Oe,oe);else if(et!==4&&(oe=oe.child,oe!==null))for(bi(oe,de,Oe),oe=oe.sibling;oe!==null;)bi(oe,de,Oe),oe=oe.sibling}function mm(oe,de,Oe){var et=oe.tag;if(et===5||et===6)oe=oe.stateNode,de?Ft(Oe,oe,de):Yt(Oe,oe);else if(et!==4&&(oe=oe.child,oe!==null))for(mm(oe,de,Oe),oe=oe.sibling;oe!==null;)mm(oe,de,Oe),oe=oe.sibling}var To=null,Xl=!1;function Uc(oe,de,Oe){for(Oe=Oe.child;Oe!==null;)Lf(oe,de,Oe),Oe=Oe.sibling}function Lf(oe,de,Oe){if(gt&&typeof gt.onCommitFiberUnmount=="function")try{gt.onCommitFiberUnmount(xh,Oe)}catch{}switch(Oe.tag){case 5:mr||Ua(Oe,de);case 6:if(Fe){var et=To,dt=Xl;To=null,Uc(oe,de,Oe),To=et,Xl=dt,To!==null&&(Xl?Xs(To,Oe.stateNode):St(To,Oe.stateNode))}else Uc(oe,de,Oe);break;case 18:Fe&&To!==null&&(Xl?xa(To,Oe.stateNode):Rn(To,Oe.stateNode));break;case 4:Fe?(et=To,dt=Xl,To=Oe.stateNode.containerInfo,Xl=!0,Uc(oe,de,Oe),To=et,Xl=dt):(ke&&(et=Oe.stateNode.containerInfo,dt=kn(et),ds(et,dt)),Uc(oe,de,Oe));break;case 0:case 11:case 14:case 15:if(!mr&&(et=Oe.updateQueue,et!==null&&(et=et.lastEffect,et!==null))){dt=et=et.next;do{var Ot=dt,Ks=Ot.destroy;Ot=Ot.tag,Ks!==void 0&&(Ot&2||Ot&4)&&Ea(Oe,de,Ks),dt=dt.next}while(dt!==et)}Uc(oe,de,Oe);break;case 1:if(!mr&&(Ua(Oe,de),et=Oe.stateNode,typeof et.componentWillUnmount=="function"))try{et.props=Oe.memoizedProps,et.state=Oe.memoizedState,et.componentWillUnmount()}catch(fr){jm(Oe,de,fr)}Uc(oe,de,Oe);break;case 21:Uc(oe,de,Oe);break;case 22:Oe.mode&1?(mr=(et=mr)||Oe.memoizedState!==null,Uc(oe,de,Oe),mr=et):Uc(oe,de,Oe);break;default:Uc(oe,de,Oe)}}function ig(oe){var de=oe.updateQueue;if(de!==null){oe.updateQueue=null;var Oe=oe.stateNode;Oe===null&&(Oe=oe.stateNode=new pa),de.forEach(function(et){var dt=E9.bind(null,oe,et);Oe.has(et)||(Oe.add(et),et.then(dt,dt))})}}function Qd(oe,de){var Oe=de.deletions;if(Oe!==null)for(var et=0;et";case op:return":has("+(Mp(oe)||"")+")";case hh:return'[role="'+oe.value+'"]';case vc:return'"'+oe.value+'"';case bh:return'[data-testname="'+oe.value+'"]';default:throw Error(l(365))}}function nx(oe,de){var Oe=[];oe=[oe,0];for(var et=0;etdt&&(dt=Ks),et&=~Ot}if(et=dt,et=Xd()-et,et=(120>et?120:480>et?480:1080>et?1080:1920>et?1920:3e3>et?3e3:4320>et?4320:1960*rx(et/1960))-et,10oe?16:oe,lp===null)var et=!1;else{if(oe=lp,lp=null,H_=0,Ql&6)throw Error(l(331));var dt=Ql;for(Ql|=4,dr=oe.current;dr!==null;){var Ot=dr,Ks=Ot.child;if(dr.flags&16){var fr=Ot.deletions;if(fr!==null){for(var $r=0;$rXd()-J2?cg(oe,0):lg|=Oe),dp(oe,de)}function YT(oe,de){de===0&&(oe.mode&1?(de=Ih,Ih<<=1,!(Ih&130023424)&&(Ih=4194304)):de=1);var Oe=cp();oe=Qc(oe,de),oe!==null&&(ko(oe,de,Oe),dp(oe,Oe))}function A9(oe){var de=oe.memoizedState,Oe=0;de!==null&&(Oe=de.retryLane),YT(oe,Oe)}function E9(oe,de){var Oe=0;switch(oe.tag){case 13:var et=oe.stateNode,dt=oe.memoizedState;dt!==null&&(Oe=dt.retryLane);break;case 19:et=oe.stateNode;break;default:throw Error(l(314))}et!==null&&et.delete(de),YT(oe,Oe)}var Hk;Hk=function(oe,de,Oe){if(oe!==null)if(oe.memoizedProps!==de.pendingProps||Co.current)tx=!0;else{if(!(oe.lanes&Oe)&&!(de.flags&128))return tx=!1,Tt(oe,de,Oe);tx=!!(oe.flags&131072)}else tx=!1,tn&&de.flags&1048576&&Va(de,bn,de.index);switch(de.lanes=0,de.tag){case 2:var et=de.type;He(oe,de),oe=de.pendingProps;var dt=nc(de,fl.current);Mu(de,Oe),dt=Wo(null,de,et,oe,dt,Oe);var Ot=q0();return de.flags|=1,typeof dt=="object"&&dt!==null&&typeof dt.render=="function"&&dt.$$typeof===void 0?(de.tag=1,de.memoizedState=null,de.updateQueue=null,ad(et)?(Ot=!0,$c(de)):Ot=!1,de.memoizedState=dt.state!==null&&dt.state!==void 0?dt.state:null,lh(de),dt.updater=RC,de.stateNode=dt,dt._reactInternals=de,Fb(de,et,oe,Oe),de=Bk(null,de,et,!0,Ot,Oe)):(de.tag=0,tn&&Ot&&Je(de),hf(null,de,dt,Oe),de=de.child),de;case 16:et=de.elementType;e:{switch(He(oe,de),oe=de.pendingProps,dt=et._init,et=dt(et._payload),de.type=et,dt=de.tag=I3(et),oe=Hd(et,oe),dt){case 0:de=X2(null,de,et,oe,Oe);break e;case 1:de=zk(null,de,et,oe,Oe);break e;case 11:de=$1(null,de,et,oe,Oe);break e;case 14:de=H0(null,de,et,Hd(et.type,oe),Oe);break e}throw Error(l(306,et,""))}return de;case 0:return et=de.type,dt=de.pendingProps,dt=de.elementType===et?dt:Hd(et,dt),X2(oe,de,et,dt,Oe);case 1:return et=de.type,dt=de.pendingProps,dt=de.elementType===et?dt:Hd(et,dt),zk(oe,de,et,dt,Oe);case 3:e:{if(U_(de),oe===null)throw Error(l(387));et=de.pendingProps,Ot=de.memoizedState,dt=Ot.element,If(oe,de),qd(de,et,null,Oe);var Ks=de.memoizedState;if(et=Ks.element,Ve&&Ot.isDehydrated)if(Ot={element:et,isDehydrated:!1,cache:Ks.cache,pendingSuspenseBoundaries:Ks.pendingSuspenseBoundaries,transitions:Ks.transitions},de.updateQueue.baseState=Ot,de.memoizedState=Ot,de.flags&256){dt=Tp(Error(l(423)),de),de=rj(oe,de,et,Oe,dt);break e}else if(et!==dt){dt=Tp(Error(l(424)),de),de=rj(oe,de,et,Oe,dt);break e}else for(Ve&&(ln=ca(de.stateNode.containerInfo),Ts=de,tn=!0,rr=null,nr=!1),Oe=ar(de,null,et,Oe),de.child=Oe;Oe;)Oe.flags=Oe.flags&-3|4096,Oe=Oe.sibling;else{if(oo(),et===dt){de=pt(oe,de,Oe);break e}hf(oe,de,et,Oe)}de=de.child}return de;case 5:return zv(de),oe===null&&Na(de),et=de.type,dt=de.pendingProps,Ot=oe!==null?oe.memoizedProps:null,Ks=dt.children,he(et,dt)?Ks=null:Ot!==null&&he(et,Ot)&&(de.flags|=32),Ok(oe,de),hf(oe,de,Ks,Oe),de.child;case 6:return oe===null&&Na(de),null;case 13:return Q2(oe,de,Oe);case 4:return _d(de,de.stateNode.containerInfo),et=de.pendingProps,oe===null?de.child=Cn(de,null,et,Oe):hf(oe,de,et,Oe),de.child;case 11:return et=de.type,dt=de.pendingProps,dt=de.elementType===et?dt:Hd(et,dt),$1(oe,de,et,dt,Oe);case 7:return hf(oe,de,de.pendingProps,Oe),de.child;case 8:return hf(oe,de,de.pendingProps.children,Oe),de.child;case 12:return hf(oe,de,de.pendingProps.children,Oe),de.child;case 10:e:{if(et=de.type._context,dt=de.pendingProps,Ot=de.memoizedProps,Ks=dt.value,el(de,et,Ks),Ot!==null)if(jt(Ot.value,Ks)){if(Ot.children===dt.children&&!Co.current){de=pt(oe,de,Oe);break e}}else for(Ot=de.child,Ot!==null&&(Ot.return=de);Ot!==null;){var fr=Ot.dependencies;if(fr!==null){Ks=Ot.child;for(var $r=fr.firstContext;$r!==null;){if($r.context===et){if(Ot.tag===1){$r=Ud(-1,Oe&-Oe),$r.tag=2;var ui=Ot.updateQueue;if(ui!==null){ui=ui.shared;var Pi=ui.pending;Pi===null?$r.next=$r:($r.next=Pi.next,Pi.next=$r),ui.pending=$r}}Ot.lanes|=Oe,$r=Ot.alternate,$r!==null&&($r.lanes|=Oe),Lc(Ot.return,Oe,de),fr.lanes|=Oe;break}$r=$r.next}}else if(Ot.tag===10)Ks=Ot.type===de.type?null:Ot.child;else if(Ot.tag===18){if(Ks=Ot.return,Ks===null)throw Error(l(341));Ks.lanes|=Oe,fr=Ks.alternate,fr!==null&&(fr.lanes|=Oe),Lc(Ks,Oe,de),Ks=Ot.sibling}else Ks=Ot.child;if(Ks!==null)Ks.return=Ot;else for(Ks=Ot;Ks!==null;){if(Ks===de){Ks=null;break}if(Ot=Ks.sibling,Ot!==null){Ot.return=Ks.return,Ks=Ot;break}Ks=Ks.return}Ot=Ks}hf(oe,de,dt.children,Oe),de=de.child}return de;case 9:return dt=de.type,et=de.pendingProps.children,Mu(de,Oe),dt=ou(dt),et=et(dt),de.flags|=1,hf(oe,de,et,Oe),de.child;case 14:return et=de.type,dt=Hd(et,de.pendingProps),dt=Hd(et.type,dt),H0(oe,de,et,dt,Oe);case 15:return G0(oe,de,de.type,de.pendingProps,Oe);case 17:return et=de.type,dt=de.pendingProps,dt=de.elementType===et?dt:Hd(et,dt),He(oe,de),de.tag=1,ad(et)?(oe=!0,$c(de)):oe=!1,Mu(de,Oe),WT(de,et,dt),Fb(de,et,dt,Oe),Bk(null,de,et,!0,oe,Oe);case 19:return Pe(oe,de,Oe);case 22:return zx(oe,de,Oe)}throw Error(l(156,de.tag))};function BC(oe,de){return Zg(oe,de)}function $C(oe,de,Oe,et){this.tag=oe,this.key=Oe,this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null,this.index=0,this.ref=null,this.pendingProps=de,this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null,this.mode=et,this.subtreeFlags=this.flags=0,this.deletions=null,this.childLanes=this.lanes=0,this.alternate=null}function Y0(oe,de,Oe,et){return new $C(oe,de,Oe,et)}function ZT(oe){return oe=oe.prototype,!(!oe||!oe.isReactComponent)}function I3(oe){if(typeof oe=="function")return ZT(oe)?1:0;if(oe!=null){if(oe=oe.$$typeof,oe===x)return 11;if(oe===b)return 14}return 2}function $b(oe,de){var Oe=oe.alternate;return Oe===null?(Oe=Y0(oe.tag,de,oe.key,oe.mode),Oe.elementType=oe.elementType,Oe.type=oe.type,Oe.stateNode=oe.stateNode,Oe.alternate=oe,oe.alternate=Oe):(Oe.pendingProps=de,Oe.type=oe.type,Oe.flags=0,Oe.subtreeFlags=0,Oe.deletions=null),Oe.flags=oe.flags&14680064,Oe.childLanes=oe.childLanes,Oe.lanes=oe.lanes,Oe.child=oe.child,Oe.memoizedProps=oe.memoizedProps,Oe.memoizedState=oe.memoizedState,Oe.updateQueue=oe.updateQueue,de=oe.dependencies,Oe.dependencies=de===null?null:{lanes:de.lanes,firstContext:de.firstContext},Oe.sibling=oe.sibling,Oe.index=oe.index,Oe.ref=oe.ref,Oe}function Gk(oe,de,Oe,et,dt,Ot){var Ks=2;if(et=oe,typeof oe=="function")ZT(oe)&&(Ks=1);else if(typeof oe=="string")Ks=5;else e:switch(oe){case u:return lj(Oe.children,dt,Ot,de);case h:Ks=8,dt|=8;break;case m:return oe=Y0(12,Oe,de,dt|2),oe.elementType=m,oe.lanes=Ot,oe;case y:return oe=Y0(13,Oe,de,dt),oe.elementType=y,oe.lanes=Ot,oe;case v:return oe=Y0(19,Oe,de,dt),oe.elementType=v,oe.lanes=Ot,oe;case S:return Wk(Oe,dt,Ot,de);default:if(typeof oe=="object"&&oe!==null)switch(oe.$$typeof){case f:Ks=10;break e;case g:Ks=9;break e;case x:Ks=11;break e;case b:Ks=14;break e;case w:Ks=16,et=null;break e}throw Error(l(130,oe==null?oe:typeof oe,""))}return de=Y0(Ks,Oe,de,dt),de.elementType=oe,de.type=et,de.lanes=Ot,de}function lj(oe,de,Oe,et){return oe=Y0(7,oe,et,de),oe.lanes=Oe,oe}function Wk(oe,de,Oe,et){return oe=Y0(22,oe,et,de),oe.elementType=S,oe.lanes=Oe,oe.stateNode={isHidden:!1},oe}function UC(oe,de,Oe){return oe=Y0(6,oe,null,de),oe.lanes=Oe,oe}function qC(oe,de,Oe){return de=Y0(4,oe.children!==null?oe.children:[],oe.key,de),de.lanes=Oe,de.stateNode={containerInfo:oe.containerInfo,pendingChildren:null,implementation:oe.implementation},de}function B6(oe,de,Oe,et,dt){this.tag=de,this.containerInfo=oe,this.finishedWork=this.pingCache=this.current=this.pendingChildren=null,this.timeoutHandle=Se,this.callbackNode=this.pendingContext=this.context=null,this.callbackPriority=0,this.eventTimes=io(0),this.expirationTimes=io(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=io(0),this.identifierPrefix=et,this.onRecoverableError=dt,Ve&&(this.mutableSourceEagerHydrationData=null)}function L3(oe,de,Oe,et,dt,Ot,Ks,fr,$r){return oe=new B6(oe,de,Oe,fr,$r),de===1?(de=1,Ot===!0&&(de|=8)):de=0,Ot=Y0(3,null,null,de),oe.current=Ot,Ot.stateNode=oe,Ot.memoizedState={element:et,isDehydrated:Oe,cache:null,transitions:null,pendingSuspenseBoundaries:null},lh(Ot),oe}function $6(oe){if(!oe)return xc;oe=oe._reactInternals;e:{if(R(oe)!==oe||oe.tag!==1)throw Error(l(170));var de=oe;do{switch(de.tag){case 3:de=de.stateNode.context;break e;case 1:if(ad(de.type)){de=de.stateNode.__reactInternalMemoizedMergedChildContext;break e}}de=de.return}while(de!==null);throw Error(l(171))}if(oe.tag===1){var Oe=oe.type;if(ad(Oe))return Bc(oe,Oe,de)}return de}function XT(oe){var de=oe._reactInternals;if(de===void 0)throw typeof oe.render=="function"?Error(l(188)):(oe=Object.keys(oe).join(","),Error(l(268,oe)));return oe=U(de),oe===null?null:oe.stateNode}function U6(oe,de){if(oe=oe.memoizedState,oe!==null&&oe.dehydrated!==null){var Oe=oe.retryLane;oe.retryLane=Oe!==0&&Oe=ui&&Ot>=gl&&dt<=Pi&&Ks<=Zi){oe.splice(de,1);break}else if(et!==ui||Oe.width!==$r.width||ZiKs){if(!(Ot!==gl||Oe.height!==$r.height||Pidt)){ui>et&&($r.width+=ui-et,$r.x=et),PiOt&&($r.height+=gl-Ot,$r.y=Ot),ZiOe&&(Oe=Ks)),Ks ")+` No matching component was found for: `)+oe.join(" > ")}return null},n.getPublicRootInstance=function(oe){if(oe=oe.current,!oe.child)return null;switch(oe.child.tag){case 5:return Y(oe.child.stateNode);default:return oe.child.stateNode}},n.injectIntoDevTools=function(oe){if(oe={bundleType:oe.bundleType,version:oe.version,rendererPackageName:oe.rendererPackageName,rendererConfig:oe.rendererConfig,overrideHookState:null,overrideHookStateDeletePath:null,overrideHookStateRenamePath:null,overrideProps:null,overridePropsDeletePath:null,overridePropsRenamePath:null,setErrorHandler:null,setSuspenseHandler:null,scheduleUpdate:null,currentDispatcherRef:o.ReactCurrentDispatcher,findHostInstanceByFiber:T9,findFiberByHostInstance:oe.findFiberByHostInstance||q6,findHostInstancesForRefresh:null,scheduleRefresh:null,scheduleRoot:null,setRefreshHandler:null,getCurrentFiber:null,reconcilerVersion:"18.3.1"},typeof __REACT_DEVTOOLS_GLOBAL_HOOK__>"u")oe=!1;else{var de=__REACT_DEVTOOLS_GLOBAL_HOOK__;if(de.isDisabled||!de.supportsFiber)oe=!0;else{try{xh=de.inject(oe),gt=de}catch{}oe=!!de.checkDCE}}return oe},n.isAlreadyRendering=function(){return!1},n.observeVisibleRects=function(oe,de,Oe,et){if(!ct)throw Error(l(363));oe=Pp(oe,de);var dt=rt(oe,Oe,et).disconnect;return{disconnect:function(){dt()}}},n.registerMutableSourceForHydration=function(oe,de){var Oe=de._getVersion;Oe=Oe(de._source),oe.mutableSourceEagerHydrationData==null?oe.mutableSourceEagerHydrationData=[de,Oe]:oe.mutableSourceEagerHydrationData.push(de,Oe)},n.runWithPriority=function(oe,de){var Oe=Zo;try{return Zo=oe,de()}finally{Zo=Oe}},n.shouldError=function(){return null},n.shouldSuspend=function(){return!1},n.updateContainer=function(oe,de,Oe,et){var dt=de.current,Ot=cp(),Ks=W1(dt);return Oe=$6(Oe),de.context===null?de.context=Oe:de.pendingContext=Oe,de=Ud(Ot,Ks),de.payload={element:oe},et=et===void 0?null:et,et!==null&&(de.callback=et),oe=od(dt,de,Ks),oe!==null&&(Ux(oe,dt,Ks,Ot),Lh(oe,dt,Ks)),Ks},n};eWt.exports=Fcn;var Ocn=eWt.exports;const zcn=au(Ocn);var tWt={exports:{}},QB={};/** * @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. */QB.ConcurrentRoot=1;QB.ContinuousEventPriority=4;QB.DefaultEventPriority=16;QB.DiscreteEventPriority=1;QB.IdleEventPriority=536870912;QB.LegacyRoot=0;tWt.exports=QB;var sWt=tWt.exports;const xwt={children:!0,ref:!0,key:!0,style:!0,forwardedRef:!0,unstable_applyCache:!0,unstable_applyDrawHitFromCache:!0};let ywt=!1,vwt=!1;const Prt=".react-konva-event",Bcn=`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 `,$cn=`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 `,Ucn={};function iRe(s,t,n=Ucn){if(!ywt&&"zIndex"in t&&(console.warn($cn),ywt=!0),!vwt&&t.draggable){var r=t.x!==void 0||t.y!==void 0,a=t.onDragEnd||t.onDragMove;r&&!a&&(console.warn(Bcn),vwt=!0)}for(var i in n)if(!xwt[i]){var l=i.slice(0,2)==="on",o=n[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,n[i])}var d=!t.hasOwnProperty(i);d&&s.setAttr(i,void 0)}var u=t._useStrictMode,h={},m=!1;const f={};for(var i in t)if(!xwt[i]){var l=i.slice(0,2)==="on",g=n[i]!==t[i];if(l&&g){var c=i.substr(2).toLowerCase();c.substr(0,7)==="content"&&(c="content"+c.substr(7,1).toUpperCase()+c.substr(8)),t[i]&&(f[c]=t[i])}!l&&(t[i]!==n[i]||u&&t[i]!==s.getAttr(i))&&(m=!0,h[i]=t[i])}m&&(s.setAttrs(h),N6(s));for(var c in f)s.on(c+Prt,f[c])}function N6(s){if(!Qo.autoDrawEnabled){var t=s.getLayer()||s.getStage();t&&t.batchDraw()}}const nWt={},qcn={};aB.Node.prototype._applyProps=iRe;function Vcn(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),N6(s)}function Hcn(s,t,n){let r=aB[s];r||(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`),r=aB.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 r(a);return iRe(c,i),c}function Gcn(s,t,n){console.error(`Text components are not supported for now in ReactKonva. Your text is: "${s}"`)}function Wcn(s,t,n){return!1}function Kcn(s){return s}function Ycn(){return null}function Zcn(){return null}function Xcn(s,t,n,r){return qcn}function Qcn(){}function Jcn(s){}function edn(s,t){return!1}function tdn(){return nWt}function sdn(){return nWt}const ndn=setTimeout,rdn=clearTimeout,adn=-1;function idn(s,t){return!1}const odn=!1,ldn=!0,cdn=!0;function ddn(s,t){t.parent===s?t.moveToTop():s.add(t),N6(s)}function udn(s,t){t.parent===s?t.moveToTop():s.add(t),N6(s)}function rWt(s,t,n){t._remove(),s.add(t),t.setZIndex(n.getZIndex()),N6(s)}function hdn(s,t,n){rWt(s,t,n)}function mdn(s,t){t.destroy(),t.off(Prt),N6(s)}function fdn(s,t){t.destroy(),t.off(Prt),N6(s)}function pdn(s,t,n){console.error(`Text components are not yet supported in ReactKonva. You text is: "${n}"`)}function gdn(s,t,n){}function xdn(s,t,n,r,a){iRe(s,a,r)}function ydn(s){s.hide(),N6(s)}function vdn(s){}function bdn(s,t){(t.visible==null||t.visible)&&s.show()}function _dn(s,t){}function wdn(s){}function jdn(){}const Ndn=()=>sWt.DefaultEventPriority,kdn=Object.freeze(Object.defineProperty({__proto__:null,appendChild:ddn,appendChildToContainer:udn,appendInitialChild:Vcn,cancelTimeout:rdn,clearContainer:wdn,commitMount:gdn,commitTextUpdate:pdn,commitUpdate:xdn,createInstance:Hcn,createTextInstance:Gcn,detachDeletedInstance:jdn,finalizeInitialChildren:Wcn,getChildHostContext:sdn,getCurrentEventPriority:Ndn,getPublicInstance:Kcn,getRootHostContext:tdn,hideInstance:ydn,hideTextInstance:vdn,idlePriority:rJ.unstable_IdlePriority,insertBefore:rWt,insertInContainerBefore:hdn,isPrimaryRenderer:odn,noTimeout:adn,now:rJ.unstable_now,prepareForCommit:Ycn,preparePortalMount:Zcn,prepareUpdate:Xcn,removeChild:mdn,removeChildFromContainer:fdn,resetAfterCommit:Qcn,resetTextContent:Jcn,run:rJ.unstable_runWithPriority,scheduleTimeout:ndn,shouldDeprioritizeSubtree:edn,shouldSetTextContent:idn,supportsMutation:cdn,unhideInstance:bdn,unhideTextInstance:_dn,warnsIfNotActing:ldn},Symbol.toStringTag,{value:"Module"}));var Sdn=Object.defineProperty,Cdn=Object.defineProperties,Adn=Object.getOwnPropertyDescriptors,bwt=Object.getOwnPropertySymbols,Edn=Object.prototype.hasOwnProperty,Tdn=Object.prototype.propertyIsEnumerable,_wt=(s,t,n)=>t in s?Sdn(s,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):s[t]=n,wwt=(s,t)=>{for(var n in t||(t={}))Edn.call(t,n)&&_wt(s,n,t[n]);if(bwt)for(var n of bwt(t))Tdn.call(t,n)&&_wt(s,n,t[n]);return s},Mdn=(s,t)=>Cdn(s,Adn(t)),jwt,Nwt;typeof window<"u"&&((jwt=window.document)!=null&&jwt.createElement||((Nwt=window.navigator)==null?void 0:Nwt.product)==="ReactNative")?j.useLayoutEffect:j.useEffect;function aWt(s,t,n){if(!s)return;if(n(s)===!0)return s;let r=s.child;for(;r;){const a=aWt(r,t,n);if(a)return a;r=r.sibling}}function iWt(s){try{return Object.defineProperties(s,{_currentRenderer:{get(){return null},set(){}},_currentRenderer2:{get(){return null},set(){}}})}catch{return s}}const kwt=console.error;console.error=function(){const s=[...arguments].join("");if(s!=null&&s.startsWith("Warning:")&&s.includes("useContext")){console.error=kwt;return}return kwt.apply(this,arguments)};const Irt=iWt(j.createContext(null));class oWt extends j.Component{render(){return j.createElement(Irt.Provider,{value:this._reactInternals},this.props.children)}}function Pdn(){const s=j.useContext(Irt);if(s===null)throw new Error("its-fine: useFiber must be called within a !");const t=j.useId();return j.useMemo(()=>{for(const r of[s,s==null?void 0:s.alternate]){if(!r)continue;const a=aWt(r,!1,i=>{let l=i.memoizedState;for(;l;){if(l.memoizedState===t)return!0;l=l.next}});if(a)return a}},[s,t])}function Idn(){const s=Pdn(),[t]=j.useState(()=>new Map);t.clear();let n=s;for(;n;){if(n.type&&typeof n.type=="object"){const a=n.type._context===void 0&&n.type.Provider===n.type?n.type:n.type._context;a&&a!==Irt&&!t.has(a)&&t.set(a,j.useContext(iWt(a)))}n=n.return}return t}function Ldn(){const s=Idn();return j.useMemo(()=>Array.from(s.keys()).reduce((t,n)=>r=>j.createElement(t,null,j.createElement(n.Provider,Mdn(wwt({},r),{value:s.get(n)}))),t=>j.createElement(oWt,wwt({},t))),[s])}function Rdn(s){const t=Gt.useRef({});return Gt.useLayoutEffect(()=>{t.current=s}),Gt.useLayoutEffect(()=>()=>{t.current={}},[]),t.current}const Ddn=s=>{const t=Gt.useRef(null),n=Gt.useRef(null),r=Gt.useRef(null),a=Rdn(s),i=Ldn(),l=o=>{const{forwardedRef:c}=s;c&&(typeof c=="function"?c(o):c.current=o)};return Gt.useLayoutEffect(()=>(n.current=new aB.Stage({width:s.width,height:s.height,container:t.current}),l(n.current),r.current=NQ.createContainer(n.current,sWt.LegacyRoot,!1,null),NQ.updateContainer(Gt.createElement(i,{},s.children),r.current),()=>{aB.isBrowser&&(l(null),NQ.updateContainer(null,r.current,null),n.current.destroy())}),[]),Gt.useLayoutEffect(()=>{l(n.current),iRe(n.current,s,a),NQ.updateContainer(Gt.createElement(i,{},s.children),r.current,null)}),Gt.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})},Fdn="Layer",wI="Group",v5="Rect",oq="Image",L$="Text",zSr="Transformer",NQ=zcn(kdn);NQ.injectIntoDevTools({findHostInstanceByFiber:()=>null,bundleType:0,version:Gt.version,rendererPackageName:"react-konva"});const Odn=Gt.forwardRef((s,t)=>Gt.createElement(oWt,{},Gt.createElement(Ddn,{...s,forwardedRef:t})));function zdn({imageUrl:s,preset:t,barStyleId:n,overrides:r,maxDisplayWidth:a=720,stageRef:i}){const l=j.useRef(null),[o,c]=j.useState(null),[d,u]=j.useState(null),[h,m]=j.useState(null),f=(t==null?void 0:t.headshot_url)??"",g=(t==null?void 0:t.brokerage_logo_url)??"";j.useEffect(()=>{if(!s){c(null);return}const W=new window.Image;W.crossOrigin="anonymous",W.onload=()=>c(W),W.onerror=()=>c(null),W.src=s},[s]),j.useEffect(()=>{if(!f){u(null);return}const W=new window.Image;W.crossOrigin="anonymous",W.onload=()=>u(W),W.onerror=()=>u(null),W.src=f},[f]),j.useEffect(()=>{if(!g){m(null);return}const W=new window.Image;W.crossOrigin="anonymous",W.onload=()=>m(W),W.onerror=()=>m(null),W.src=g},[g]);const x=hon(n),y=(o==null?void 0:o.naturalWidth)??1080,v=(o==null?void 0:o.naturalHeight)??1080,b=j.useMemo(()=>Math.min(1,a/y),[y,a]),w=y*b,S=v*b,C=(r==null?void 0:r.brand_color)??(t==null?void 0:t.brand_color)??"#0f172a",E=(r==null?void 0:r.accent_color)??(t==null?void 0:t.accent_color)??"#3b82f6",I=(r==null?void 0:r.display_name)??(t==null?void 0:t.display_name)??"",P=(r==null?void 0:r.phone)??(t==null?void 0:t.phone)??"",R=(r==null?void 0:r.email)??(t==null?void 0:t.email)??"",D=(r==null?void 0:r.tagline)??(t==null?void 0:t.tagline)??"",O=new Set((r==null?void 0:r.hidden_fields)??(t==null?void 0:t.hidden_fields)??[]),U=W=>x.fields.includes(W)&&!O.has(W);return e.jsx("div",{className:"border rounded-lg overflow-hidden bg-muted/40 inline-block",children:e.jsx(Odn,{ref:W=>{l.current=W,i&&(i.current=W)},width:w,height:S,scaleX:b,scaleY:b,children:e.jsxs(Fdn,{children:[o&&e.jsx(oq,{image:o,width:y,height:v,listening:!1}),!o&&e.jsx(v5,{x:0,y:0,width:y,height:v,fill:"#e2e8f0"}),e.jsx(Bdn,{style:x,canvasW:y,canvasH:v,brandColor:C,accentColor:E,name:I,phone:P,email:R,tagline:D,headshot:d,logo:h,hidden:O,has:U})]})})})}function Bdn({style:s,canvasW:t,canvasH:n,brandColor:r,accentColor:a,name:i,phone:l,email:o,tagline:c,headshot:d,logo:u,has:h}){const m=n*s.heightRatio,f=m*.18,g=s.textColor==="light"?"#ffffff":s.textColor==="dark"?"#0f172a":s.background==="dark"||s.background==="gradient"?"#ffffff":mon(r),x=g==="#ffffff"?"rgba(255,255,255,0.78)":"rgba(15,23,42,0.7)";if(s.position==="bottom"||s.position==="top"){const y=s.position==="bottom"?n-m:0;return e.jsxs(wI,{children:[e.jsx(v5,{x:0,y,width:t,height:m,fill:r}),e.jsx(v5,{x:0,y:s.position==="bottom"?y:m-4,width:t,height:4,fill:a}),e.jsx(Ode,{x:f,y:y+f,width:t-f*2,height:m-f*2,textColor:g,subTextColor:x,name:i,phone:l,email:o,tagline:c,headshot:d,logo:u,has:h,circular:s.circularHeadshot})]})}if(s.position==="corner-br"){const y=t*.42,v=m,b=t-y-n*.025,w=n-v-n*.025;return e.jsxs(wI,{children:[e.jsx(v5,{x:b,y:w,width:y,height:v,fill:r,cornerRadius:v*.12,opacity:.92}),e.jsx(v5,{x:b,y:w+v-4,width:y,height:4,fill:a,cornerRadius:2}),e.jsx(Ode,{x:b+f,y:w+f,width:y-f*2,height:v-f*2,textColor:g,subTextColor:x,name:i,phone:l,email:o,tagline:c,headshot:d,logo:u,has:h,circular:s.circularHeadshot})]})}if(s.position==="side-right"){const y=Math.max(t*.22,Math.min(t*.3,260)),v=y*.12;return e.jsxs(wI,{children:[e.jsx(v5,{x:t-y,y:0,width:y,height:n,fill:r}),e.jsx(v5,{x:t-y,y:0,width:4,height:n,fill:a}),e.jsx(Ode,{x:t-y+v,y:n*.08,width:y-v*2,height:n*.84,textColor:g,subTextColor:x,name:i,phone:l,email:o,tagline:c,headshot:d,logo:u,has:h,circular:s.circularHeadshot,vertical:!0,railWidth:y})]})}return s.position==="letterbox"?e.jsxs(wI,{children:[e.jsx(v5,{x:0,y:0,width:t,height:m,fill:"#0a0a0a"}),e.jsx(v5,{x:0,y:n-m,width:t,height:m,fill:"#0a0a0a"}),e.jsx(v5,{x:0,y:n-m,width:t,height:3,fill:a}),e.jsx(Ode,{x:f,y:n-m+f,width:t-f*2,height:m-f*2,textColor:"#ffffff",subTextColor:"rgba(255,255,255,0.75)",name:i,phone:l,email:o,tagline:c,headshot:d,logo:u,has:h,circular:s.circularHeadshot}),u&&h("logo")&&e.jsx(oq,{image:u,x:t-f-m*.7,y:f,height:m-f*2,width:m*.7})]}):null}function Ode({x:s,y:t,width:n,height:r,textColor:a,subTextColor:i,name:l,phone:o,email:c,tagline:d,headshot:u,logo:h,has:m,circular:f,vertical:g,railWidth:x}){if(g){const W=x??n,V=Math.min(n,W*.7),G=Math.max(14,W*.13),Y=Math.max(11,W*.085),X=W*.08,ae=W*.35;let ie=t;const ne=ie;ie+=V+X;const te=ie,J=l.length>12?2:1;ie+=G*1.15*J+X*.5;const ce=ie;m("phone")&&o&&(ie+=Y*1.3+X*.4);const _e=ie;m("email")&&c&&(ie+=Y*1.3+X*.4);const he=ie+X*.5;return e.jsxs(wI,{children:[m("headshot")&&u&&e.jsx(wI,{clipFunc:f?ue=>{ue.beginPath(),ue.arc(s+n/2,ne+V/2,V/2,0,Math.PI*2),ue.closePath()}:void 0,children:e.jsx(oq,{image:u,x:s+(n-V)/2,y:ne,width:V,height:V})}),m("name")&&l&&e.jsx(L$,{text:l,x:s,y:te,width:n,align:"center",fontSize:G,fontStyle:"bold",fill:a}),m("phone")&&o&&e.jsx(L$,{text:o,x:s,y:ce,width:n,align:"center",fontSize:Y,fill:i}),m("email")&&c&&e.jsx(L$,{text:c,x:s,y:_e,width:n,align:"center",fontSize:Y,fill:i,ellipsis:!0,wrap:"none"}),m("logo")&&h&&e.jsx(oq,{image:h,x:s,y:he,width:n,height:ae})]})}const y=r*.95,v=u&&m("headshot")?s+y+r*.18:s,b=n-(v-s)-(h&&m("logo")?r*1.6:0),w=Math.max(20,r*.34),S=Math.max(13,r*.22),C=r*.06,E=m("tagline")&&d?1:0,I=m("phone")&&o?1:0,P=m("email")&&c?1:0,R=1+E+(I||P?1:0),D=R*w+(R-1)*C;let U=t+(r-D)/2;return e.jsxs(wI,{children:[m("headshot")&&u&&e.jsx(wI,{clipFunc:f?W=>{W.beginPath(),W.arc(s+y/2,t+y/2,y/2,0,Math.PI*2),W.closePath()}:void 0,children:e.jsx(oq,{image:u,x:s,y:t+(r-y)/2,width:y,height:y})}),m("name")&&l&&e.jsx(L$,{text:l,x:v,y:U,width:b,fontSize:w,fontStyle:"bold",fill:a,ellipsis:!0,wrap:"none"}),(U+=w+C,null),m("tagline")&&d&&e.jsxs(e.Fragment,{children:[e.jsx(L$,{text:d,x:v,y:U,width:b,fontSize:S*1.1,fontStyle:"italic",fill:i,ellipsis:!0,wrap:"none"}),(U+=S*1.1+C,null)]}),I||P?e.jsx(L$,{text:[o,c].filter(Boolean).join(" • "),x:v,y:U,width:b,fontSize:S,fill:i,ellipsis:!0,wrap:"none"}):null,m("logo")&&h&&e.jsx(oq,{image:h,x:s+n-r*1.4,y:t+(r-r*.8)/2,width:r*1.4,height:r*.8})]})}function $dn(){const{data:s}=_ie(),t=(s==null?void 0:s.find(U=>U.is_default))??(s==null?void 0:s[0])??null,[n,r]=j.useState(void 0),a=(s==null?void 0:s.find(U=>U.id===n))??t,[i,l]=j.useState([]),[o,c]=j.useState(0),[d,u]=j.useState("minimal-stripe"),[h,m]=j.useState({}),[f,g]=j.useState(!1),x=j.useRef(null),[y,v]=j.useState(780),b=j.useRef(null),w=U=>{if(b.current&&(b.current.disconnect(),b.current=null),!U)return;const W=()=>{const G=U.clientWidth;G>0&&v(Math.min(780,G-16))};W();const V=new ResizeObserver(W);V.observe(U),b.current=V};j.useEffect(()=>()=>{var U;(U=b.current)==null||U.disconnect()},[]);const S=j.useRef(null),C=U=>{if(!U)return;const W=[];Array.from(U).forEach(V=>{V.type.startsWith("image/")&&W.push({id:crypto.randomUUID(),url:URL.createObjectURL(V),file:V,name:V.name})}),l(V=>[...V,...W])},E=U=>{l(W=>{const V=W.find(G=>G.id===U);return V&&URL.revokeObjectURL(V.url),W.filter(G=>G.id!==U)}),c(0)},I=typeof navigator<"u"&&/iPad|iPhone|iPod/.test(navigator.userAgent),P=U=>{var ae;const[W,V]=U.split(","),G=((ae=W.match(/:(.*?);/))==null?void 0:ae[1])??"image/jpeg",Y=atob(V),X=new Uint8Array(Y.length);for(let ie=0;ie{var U;if(S.current){g(!0);try{const W=S.current,V=W.toDataURL({pixelRatio:1/(W.scaleX()||1),mimeType:"image/jpeg",quality:.95}),Y=`${((U=i[o])==null?void 0:U.name.replace(/\.[^.]+$/,""))||"branded"}-branded.jpg`,X=P(V),ae=URL.createObjectURL(X);if(I)window.open(ae,"_blank")||(window.location.href=ae),re.success('Long-press the image and tap "Save to Photos"');else{const ie=document.createElement("a");ie.href=ae,ie.download=Y,document.body.appendChild(ie),ie.click(),ie.remove(),re.success("Image exported")}setTimeout(()=>URL.revokeObjectURL(ae),6e4)}catch(W){re.error(W.message||"Export failed")}finally{g(!1)}}},D=async()=>{if(i.length){g(!0);try{const U=new sGt,W=i.length,V=o;for(let X=0;XsetTimeout(J,600)),!S.current)continue;const ae=S.current,ne=ae.toDataURL({pixelRatio:1/(ae.scaleX()||1),mimeType:"image/jpeg",quality:.95}).split(",")[1],te=i[X].name.replace(/\.[^.]+$/,"")||`image-${X+1}`;U.file(`${te}-branded.jpg`,ne,{base64:!0})}c(V);const G=await U.generateAsync({type:"blob"}),Y=document.createElement("a");Y.href=URL.createObjectURL(G),Y.download=`branded-images-${Date.now()}.zip`,Y.click(),URL.revokeObjectURL(Y.href),re.success(`${W} images exported`)}catch(U){re.error(U.message||"Batch export failed")}finally{g(!1)}}},O=i[o];return e.jsx(Vs,{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(Ml,{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(wr,{to:"/marketing-studio",className:"text-sm text-muted-foreground inline-flex items-center gap-1 hover:underline",children:[e.jsx(qa,{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($,{variant:"outline",asChild:!0,className:"w-full sm:w-auto",children:e.jsxs(wr,{to:"/marketing-studio/brand-kit",children:[e.jsx(Yc,{className:"h-4 w-4 mr-1"})," Brand Kit"]})})]}),!a&&e.jsx(Ne,{className:"border-dashed border-amber-500/50 bg-amber-500/5",children:e.jsxs(Ie,{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($,{asChild:!0,className:"w-full sm:w-auto",children:e.jsx(wr,{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(Ne,{className:"overflow-hidden",children:e.jsxs(Ie,{className:"p-4",children:[O?e.jsx("div",{ref:w,className:"flex justify-center bg-muted/30 rounded p-2 overflow-hidden",children:e.jsx(zdn,{imageUrl:O.url,preset:a,barStyleId:d,overrides:h,maxDisplayWidth:y,stageRef:S})}):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 U;return(U=x.current)==null?void 0:U.click()},onDragOver:U=>U.preventDefault(),onDrop:U=>{U.preventDefault(),C(U.dataTransfer.files)},children:[e.jsx(Mc,{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($,{type:"button",children:[e.jsx(ni,{className:"h-4 w-4 mr-1"})," Choose images"]})]}),e.jsx("input",{ref:x,type:"file",accept:"image/*",multiple:!0,hidden:!0,onChange:U=>C(U.target.files)})]})}),i.length>0&&e.jsx(Ne,{className:"overflow-hidden",children:e.jsx(Ie,{className:"p-3",children:e.jsxs("div",{className:"flex gap-2 overflow-x-auto py-1",children:[i.map((U,W)=>e.jsxs("div",{className:"relative group flex-shrink-0",children:[e.jsx("button",{onClick:()=>c(W),className:`block h-16 w-16 rounded overflow-hidden border-2 transition-all ${W===o?"border-primary":"border-transparent hover:border-muted-foreground/30"}`,children:e.jsx("img",{src:U.url,alt:"",className:"h-full w-full object-cover"})}),e.jsx("button",{onClick:()=>E(U.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(gr,{className:"h-3 w-3"})})]},U.id)),e.jsx("button",{onClick:()=>{var U;return(U=x.current)==null?void 0:U.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(dn,{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($,{variant:"outline",onClick:()=>{i.forEach(U=>URL.revokeObjectURL(U.url)),l([])},children:"Clear all"}),e.jsxs($,{onClick:R,disabled:f||!O,children:[f?e.jsx(kt,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(di,{className:"h-4 w-4 mr-1"}),"Download this image"]}),i.length>1&&e.jsxs($,{onClick:D,disabled:f,children:[f?e.jsx(kt,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(di,{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(Ne,{className:"overflow-hidden",children:[e.jsx(Ct,{className:"pb-2",children:e.jsx(At,{className:"text-base",children:"Brand preset"})}),e.jsx(Ie,{children:e.jsxs(ms,{value:(a==null?void 0:a.id)??"",onValueChange:r,children:[e.jsx(us,{children:e.jsx(fs,{placeholder:"Choose preset"})}),e.jsx(hs,{children:s==null?void 0:s.map(U=>e.jsxs(Ge,{value:U.id,children:[U.name," ",U.is_default?"(default)":""]},U.id))})]})})]}),e.jsxs(Ne,{className:"overflow-hidden",children:[e.jsx(Ct,{className:"pb-2",children:e.jsx(At,{className:"text-base",children:"Bar style"})}),e.jsx(Ie,{children:e.jsx(fon,{value:d,onChange:u,mediaType:"image"})})]}),e.jsxs(Ne,{className:"overflow-hidden",children:[e.jsx(Ct,{className:"pb-2",children:e.jsx(At,{className:"text-base",children:"Tweak this design"})}),e.jsx(Ie,{children:e.jsxs(ha,{defaultValue:"text",children:[e.jsxs(ma,{className:"grid grid-cols-2 w-full",children:[e.jsx(Zt,{value:"text",children:"Text"}),e.jsx(Zt,{value:"colors",children:"Colors"})]}),e.jsxs(Xt,{value:"text",className:"space-y-3 pt-3",children:[e.jsxs("div",{children:[e.jsx(ee,{children:"Display name"}),e.jsx(pe,{value:h.display_name??(a==null?void 0:a.display_name)??"",onChange:U=>m({...h,display_name:U.target.value})})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Phone"}),e.jsx(pe,{value:h.phone??(a==null?void 0:a.phone)??"",onChange:U=>m({...h,phone:U.target.value})})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Email"}),e.jsx(pe,{value:h.email??(a==null?void 0:a.email)??"",onChange:U=>m({...h,email:U.target.value})})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Tagline"}),e.jsx(pe,{value:h.tagline??(a==null?void 0:a.tagline)??"",onChange:U=>m({...h,tagline:U.target.value})})]})]}),e.jsxs(Xt,{value:"colors",className:"space-y-3 pt-3",children:[e.jsxs("div",{children:[e.jsx(ee,{children:"Bar color"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("input",{type:"color",value:h.brand_color??(a==null?void 0:a.brand_color)??"#0f172a",onChange:U=>m({...h,brand_color:U.target.value}),className:"h-10 w-14 rounded border cursor-pointer"}),e.jsx(pe,{value:h.brand_color??(a==null?void 0:a.brand_color)??"#0f172a",onChange:U=>m({...h,brand_color:U.target.value})})]})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Accent line"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("input",{type:"color",value:h.accent_color??(a==null?void 0:a.accent_color)??"#3b82f6",onChange:U=>m({...h,accent_color:U.target.value}),className:"h-10 w-14 rounded border cursor-pointer"}),e.jsx(pe,{value:h.accent_color??(a==null?void 0:a.accent_color)??"#3b82f6",onChange:U=>m({...h,accent_color:U.target.value})})]})]}),e.jsx($,{variant:"ghost",size:"sm",onClick:()=>m({}),children:"Reset to preset"})]})]})})]})]})]})]})})}function Udn(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 n=document.implementation.createHTMLDocument(),r=n.createElement("base"),a=n.createElement("a");return n.head.appendChild(r),n.body.appendChild(a),t&&(r.href=t),a.href=s,a.href}const qdn=(()=>{let s=0;const t=()=>`0000${(Math.random()*36**4<<0).toString(36)}`.slice(-4);return()=>(s+=1,`u${t()}${s}`)})();function fL(s){const t=[];for(let n=0,r=s.length;nvj||s.height>vj)&&(s.width>vj&&s.height>vj?s.width>s.height?(s.height*=vj/s.width,s.width=vj):(s.width*=vj/s.height,s.height=vj):s.width>vj?(s.height*=vj/s.width,s.width=vj):(s.width*=vj/s.height,s.height=vj))}function VTe(s){return new Promise((t,n)=>{const r=new Image;r.onload=()=>{r.decode().then(()=>{requestAnimationFrame(()=>t(r))})},r.onerror=n,r.crossOrigin="anonymous",r.decoding="async",r.src=s})}async function Kdn(s){return Promise.resolve().then(()=>new XMLSerializer().serializeToString(s)).then(encodeURIComponent).then(t=>`data:image/svg+xml;charset=utf-8,${t}`)}async function Ydn(s,t,n){const r="http://www.w3.org/2000/svg",a=document.createElementNS(r,"svg"),i=document.createElementNS(r,"foreignObject");return a.setAttribute("width",`${t}`),a.setAttribute("height",`${n}`),a.setAttribute("viewBox",`0 0 ${t} ${n}`),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),Kdn(a)}const Ow=(s,t)=>{if(s instanceof t)return!0;const n=Object.getPrototypeOf(s);return n===null?!1:n.constructor.name===t.name||Ow(n,t)};function Zdn(s){const t=s.getPropertyValue("content");return`${s.cssText} content: '${t.replace(/'|"/g,"")}';`}function Xdn(s,t){return lWt(t).map(n=>{const r=s.getPropertyValue(n),a=s.getPropertyPriority(n);return`${n}: ${r}${a?" !important":""};`}).join(" ")}function Qdn(s,t,n,r){const a=`.${s}:${t}`,i=n.cssText?Zdn(n):Xdn(n,r);return document.createTextNode(`${a}{${i}}`)}function Swt(s,t,n,r){const a=window.getComputedStyle(s,n),i=a.getPropertyValue("content");if(i===""||i==="none")return;const l=qdn();try{t.className=`${t.className} ${l}`}catch{return}const o=document.createElement("style");o.appendChild(Qdn(l,n,a,r)),t.appendChild(o)}function Jdn(s,t,n){Swt(s,t,":before",n),Swt(s,t,":after",n)}const Cwt="application/font-woff",Awt="image/jpeg",eun={woff:Cwt,woff2:Cwt,ttf:"application/font-truetype",eot:"application/vnd.ms-fontobject",png:"image/png",jpg:Awt,jpeg:Awt,gif:"image/gif",tiff:"image/tiff",svg:"image/svg+xml",webp:"image/webp"};function tun(s){const t=/\.([^./]*?)$/g.exec(s);return t?t[1]:""}function Lrt(s){const t=tun(s).toLowerCase();return eun[t]||""}function sun(s){return s.split(/,/)[1]}function HWe(s){return s.search(/^(data:)/)!==-1}function nun(s,t){return`data:${t};base64,${s}`}async function dWt(s,t,n){const r=await fetch(s,t);if(r.status===404)throw new Error(`Resource "${r.url}" not found`);const a=await r.blob();return new Promise((i,l)=>{const o=new FileReader;o.onerror=l,o.onloadend=()=>{try{i(n({res:r,result:o.result}))}catch(c){l(c)}},o.readAsDataURL(a)})}const e9e={};function run(s,t,n){let r=s.replace(/\?.*/,"");return n&&(r=s),/ttf|otf|eot|woff2?/i.test(r)&&(r=r.replace(/.*\//,"")),t?`[${t}]${r}`:r}async function Rrt(s,t,n){const r=run(s,t,n.includeQueryParams);if(e9e[r]!=null)return e9e[r];n.cacheBust&&(s+=(/\?/.test(s)?"&":"?")+new Date().getTime());let a;try{const i=await dWt(s,n.fetchRequestInit,({res:l,result:o})=>(t||(t=l.headers.get("Content-Type")||""),sun(o)));a=nun(i,t)}catch(i){a=n.imagePlaceholder||"";let l=`Failed to fetch resource: ${s}`;i&&(l=typeof i=="string"?i:i.message),l&&console.warn(l)}return e9e[r]=a,a}async function aun(s){const t=s.toDataURL();return t==="data:,"?s.cloneNode(!1):VTe(t)}async function iun(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 VTe(o)}const n=s.poster,r=Lrt(n),a=await Rrt(n,r,t);return VTe(a)}async function oun(s,t){var n;try{if(!((n=s==null?void 0:s.contentDocument)===null||n===void 0)&&n.body)return await oRe(s.contentDocument.body,t,!0)}catch{}return s.cloneNode(!1)}async function lun(s,t){return Ow(s,HTMLCanvasElement)?aun(s):Ow(s,HTMLVideoElement)?iun(s,t):Ow(s,HTMLIFrameElement)?oun(s,t):s.cloneNode(uWt(s))}const cun=s=>s.tagName!=null&&s.tagName.toUpperCase()==="SLOT",uWt=s=>s.tagName!=null&&s.tagName.toUpperCase()==="SVG";async function dun(s,t,n){var r,a;if(uWt(t))return t;let i=[];return cun(s)&&s.assignedNodes?i=fL(s.assignedNodes()):Ow(s,HTMLIFrameElement)&&(!((r=s.contentDocument)===null||r===void 0)&&r.body)?i=fL(s.contentDocument.body.childNodes):i=fL(((a=s.shadowRoot)!==null&&a!==void 0?a:s).childNodes),i.length===0||Ow(s,HTMLVideoElement)||await i.reduce((l,o)=>l.then(()=>oRe(o,n)).then(c=>{c&&t.appendChild(c)}),Promise.resolve()),t}function uun(s,t,n){const r=t.style;if(!r)return;const a=window.getComputedStyle(s);a.cssText?(r.cssText=a.cssText,r.transformOrigin=a.transformOrigin):lWt(n).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`),Ow(s,HTMLIFrameElement)&&i==="display"&&l==="inline"&&(l="block"),i==="d"&&t.getAttribute("d")&&(l=`path(${t.getAttribute("d")})`),r.setProperty(i,l,a.getPropertyPriority(i))})}function hun(s,t){Ow(s,HTMLTextAreaElement)&&(t.innerHTML=s.value),Ow(s,HTMLInputElement)&&t.setAttribute("value",s.value)}function mun(s,t){if(Ow(s,HTMLSelectElement)){const n=t,r=Array.from(n.children).find(a=>s.value===a.getAttribute("value"));r&&r.setAttribute("selected","")}}function fun(s,t,n){return Ow(t,Element)&&(uun(s,t,n),Jdn(s,t,n),hun(s,t),mun(s,t)),t}async function pun(s,t){const n=s.querySelectorAll?s.querySelectorAll("use"):[];if(n.length===0)return s;const r={};for(let i=0;ilun(r,t)).then(r=>dun(s,r,t)).then(r=>fun(s,r,t)).then(r=>pun(r,t))}const hWt=/url\((['"]?)([^'"]+?)\1\)/g,gun=/url\([^)]+\)\s*format\((["']?)([^"']+)\1\)/g,xun=/src:\s*(?:url\([^)]+\)\s*format\([^)]+\)[,;]\s*)+/g;function yun(s){const t=s.replace(/([.*+?^${}()|\[\]\/\\])/g,"\\$1");return new RegExp(`(url\\(['"]?)(${t})(['"]?\\))`,"g")}function vun(s){const t=[];return s.replace(hWt,(n,r,a)=>(t.push(a),n)),t.filter(n=>!HWe(n))}async function bun(s,t,n,r,a){try{const i=n?Udn(t,n):t,l=Lrt(t);let o;return a||(o=await Rrt(i,l,r)),s.replace(yun(t),`$1${o}$3`)}catch{}return s}function _un(s,{preferredFontFormat:t}){return t?s.replace(xun,n=>{for(;;){const[r,,a]=gun.exec(n)||[];if(!a)return"";if(a===t)return`src: ${r};`}}):s}function mWt(s){return s.search(hWt)!==-1}async function fWt(s,t,n){if(!mWt(s))return s;const r=_un(s,n);return vun(r).reduce((i,l)=>i.then(o=>bun(o,l,t,n)),Promise.resolve(r))}async function D$(s,t,n){var r;const a=(r=t.style)===null||r===void 0?void 0:r.getPropertyValue(s);if(a){const i=await fWt(a,null,n);return t.style.setProperty(s,i,t.style.getPropertyPriority(s)),!0}return!1}async function wun(s,t){await D$("background",s,t)||await D$("background-image",s,t),await D$("mask",s,t)||await D$("-webkit-mask",s,t)||await D$("mask-image",s,t)||await D$("-webkit-mask-image",s,t)}async function jun(s,t){const n=Ow(s,HTMLImageElement);if(!(n&&!HWe(s.src))&&!(Ow(s,SVGImageElement)&&!HWe(s.href.baseVal)))return;const r=n?s.src:s.href.baseVal,a=await Rrt(r,Lrt(r),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"),n?(s.srcset="",s.src=a):s.href.baseVal=a})}async function Nun(s,t){const r=fL(s.childNodes).map(a=>pWt(a,t));await Promise.all(r).then(()=>s)}async function pWt(s,t){Ow(s,Element)&&(await wun(s,t),await jun(s,t),await Nun(s,t))}function kun(s,t){const{style:n}=s;t.backgroundColor&&(n.backgroundColor=t.backgroundColor),t.width&&(n.width=`${t.width}px`),t.height&&(n.height=`${t.height}px`);const r=t.style;return r!=null&&Object.keys(r).forEach(a=>{n[a]=r[a]}),s}const Ewt={};async function Twt(s){let t=Ewt[s];if(t!=null)return t;const r=await(await fetch(s)).text();return t={url:s,cssText:r},Ewt[s]=t,t}async function Mwt(s,t){let n=s.cssText;const r=/url\(["']?([^"')]+)["']?\)/g,i=(n.match(/url\([^)]+\)/g)||[]).map(async l=>{let o=l.replace(r,"$1");return o.startsWith("https://")||(o=new URL(o,s.url).href),dWt(o,t.fetchRequestInit,({result:c})=>(n=n.replace(l,`url(${c})`),[l,c]))});return Promise.all(i).then(()=>n)}function Pwt(s){if(s==null)return[];const t=[],n=/(\/\*[\s\S]*?\*\/)/gi;let r=s.replace(n,"");const a=new RegExp("((@.*?keyframes [\\s\\S]*?){([\\s\\S]*?}\\s*?)})","gi");for(;;){const c=a.exec(r);if(c===null)break;t.push(c[0])}r=r.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(r);if(c===null){if(c=o.exec(r),c===null)break;i.lastIndex=o.lastIndex}else o.lastIndex=i.lastIndex;t.push(c[0])}return t}async function Sun(s,t){const n=[],r=[];return s.forEach(a=>{if("cssRules"in a)try{fL(a.cssRules||[]).forEach((i,l)=>{if(i.type===CSSRule.IMPORT_RULE){let o=l+1;const c=i.href,d=Twt(c).then(u=>Mwt(u,t)).then(u=>Pwt(u).forEach(h=>{try{a.insertRule(h,h.startsWith("@import")?o+=1:a.cssRules.length)}catch(m){console.error("Error inserting rule from remote css",{rule:h,error:m})}})).catch(u=>{console.error("Error loading remote css",u.toString())});r.push(d)}})}catch(i){const l=s.find(o=>o.href==null)||document.styleSheets[0];a.href!=null&&r.push(Twt(a.href).then(o=>Mwt(o,t)).then(o=>Pwt(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(r).then(()=>(s.forEach(a=>{if("cssRules"in a)try{fL(a.cssRules||[]).forEach(i=>{n.push(i)})}catch(i){console.error(`Error while reading CSS rules from ${a.href}`,i)}}),n))}function Cun(s){return s.filter(t=>t.type===CSSRule.FONT_FACE_RULE).filter(t=>mWt(t.style.getPropertyValue("src")))}async function Aun(s,t){if(s.ownerDocument==null)throw new Error("Provided element is not within a Document");const n=fL(s.ownerDocument.styleSheets),r=await Sun(n,t);return Cun(r)}function gWt(s){return s.trim().replace(/["']/g,"")}function Eun(s){const t=new Set;function n(r){(r.style.fontFamily||getComputedStyle(r).fontFamily).split(",").forEach(i=>{t.add(gWt(i))}),Array.from(r.children).forEach(i=>{i instanceof HTMLElement&&n(i)})}return n(s),t}async function Tun(s,t){const n=await Aun(s,t),r=Eun(s);return(await Promise.all(n.filter(i=>r.has(gWt(i.style.fontFamily))).map(i=>{const l=i.parentStyleSheet?i.parentStyleSheet.href:null;return fWt(i.cssText,l,t)}))).join(` `)}async function Mun(s,t){const n=t.fontEmbedCSS!=null?t.fontEmbedCSS:t.skipFonts?null:await Tun(s,t);if(n){const r=document.createElement("style"),a=document.createTextNode(n);r.appendChild(a),s.firstChild?s.insertBefore(r,s.firstChild):s.appendChild(r)}}async function xWt(s,t={}){const{width:n,height:r}=cWt(s,t),a=await oRe(s,t,!0);return await Mun(a,t),await pWt(a,t),kun(a,t),await Ydn(a,n,r)}async function yWt(s,t={}){const{width:n,height:r}=cWt(s,t),a=await xWt(s,t),i=await VTe(a),l=document.createElement("canvas"),o=l.getContext("2d"),c=t.pixelRatio||Gdn(),d=t.canvasWidth||n,u=t.canvasHeight||r;return l.width=d*c,l.height=u*c,t.skipAutoScale||Wdn(l),l.style.width=`${d}`,l.style.height=`${u}`,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 $G(s,t={}){return(await yWt(s,t)).toDataURL()}const vWt=Object.freeze(Object.defineProperty({__proto__:null,toCanvas:yWt,toPng:$G,toSvg:xWt},Symbol.toStringTag,{value:"Module"})),UG=s=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(s),lRe={"just-listed":"JUST LISTED","just-sold":"JUST SOLD","open-house":"OPEN HOUSE","price-drop":"PRICE DROP"},jI={"instagram-square":{width:1080,height:1080},"instagram-story":{width:1080,height:1920},"facebook-post":{width:1200,height:630}},Pun=({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})]})]}),Drt=Gt.forwardRef(({listing:s,postType:t,format:n,branding:r,selectedPhotoIndex:a},i)=>{var h;const l=n==="instagram-story"?{w:1080,h:1920}:n==="facebook-post"?{w:1200,h:630}:{w:1080,h:1080},o=400/l.w,c=(h=s.photos)==null?void 0:h[a],d=lRe[t],u=[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:UG(s.price)}),t==="just-sold"&&s.soldPrice&&e.jsxs("div",{style:{fontSize:l.w*.028,color:"#C9A84C",marginBottom:l.w*.01},children:["Sold for ",UG(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:u})}),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(Pun,{branding:r,dim:l})]})]})]})});Drt.displayName="LuxuryDarkTemplate";const Iun=({branding:s,dim:t,accentColor:n})=>!(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 ${n}`,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})]})]}),Frt=Gt.forwardRef(({listing:s,postType:t,format:n,branding:r,selectedPhotoIndex:a},i)=>{var f;const l=n==="instagram-story"?{w:1080,h:1920}:n==="facebook-post"?{w:1200,h:630}:{w:1080,h:1080},o=400/l.w,c=(f=s.photos)==null?void 0:f[a],d=lRe[t],u=n==="instagram-story",h=n==="facebook-post",m=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:h?"row":"column"},children:[e.jsxs("div",{style:{width:h?"55%":"100%",height:h?"100%":u?"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:m,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*(h?.055:.065),fontWeight:800,lineHeight:1.1,color:m,marginBottom:l.w*.012},children:UG(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:`${m}10`,border:`2px solid ${m}`,borderRadius:l.w*.01,padding:`${l.w*.01}px ${l.w*.02}px`,fontSize:l.w*.022,fontWeight:700,color:m,display:"inline-block",marginBottom:l.w*.015},children:"SAT & SUN • 1–4 PM"}),e.jsx(Iun,{branding:r,dim:l,accentColor:m})]})]})});Frt.displayName="ModernCleanTemplate";const Lun=({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})]})]}),Ort=Gt.forwardRef(({listing:s,postType:t,format:n,branding:r,selectedPhotoIndex:a},i)=>{var m;const l=n==="instagram-story"?{w:1080,h:1920}:n==="facebook-post"?{w:1200,h:630}:{w:1080,h:1080},o=400/l.w,c=(m=s.photos)==null?void 0:m[a],d=lRe[t],u={"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)"},h=[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:u[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:UG(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:h}),t==="open-house"&&e.jsx("div",{style:{marginTop:l.w*.015,background:u["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(Lun,{branding:r,dim:l})]})]})]})});Ort.displayName="BoldColorfulTemplate";const Run=({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})]})]}),zrt=Gt.forwardRef(({listing:s,postType:t,format:n,branding:r,selectedPhotoIndex:a},i)=>{var h;const l=n==="instagram-story"?{w:1080,h:1920}:n==="facebook-post"?{w:1200,h:630}:{w:1080,h:1080},o=400/l.w,c=(h=s.photos)==null?void 0:h[a],d=lRe[t],u=n==="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:u?"column":"row",height:"100%"},children:[e.jsxs("div",{style:{width:u?"100%":"42%",height:u?"40%":"100%",display:"flex",flexDirection:"column",justifyContent:"center",padding:l.w*.05,order:u?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*(u?.06:.055),fontWeight:700,lineHeight:1.1,marginBottom:l.w*.015,fontStyle:"italic"},children:UG(s.price)}),t==="just-sold"&&s.soldPrice&&e.jsxs("div",{style:{fontSize:l.w*.02,color:"#8B7355",marginBottom:l.w*.01},children:["Sold: ",UG(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(Run,{branding:r,dim:l})]}),e.jsxs("div",{style:{width:u?"100%":"58%",height:u?"60%":"100%",position:"relative",overflow:"hidden",order:u?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"}})]})]})})});zrt.displayName="EditorialTemplate";const Dun=[{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:"📉"}],Iwt=[{value:"instagram-square",label:"IG Post",dimensions:"1080×1080",icon:e.jsx(Tf,{className:"h-4 w-4"})},{value:"instagram-story",label:"IG Story",dimensions:"1080×1920",icon:e.jsx(Tf,{className:"h-4 w-4"})},{value:"facebook-post",label:"Facebook",dimensions:"1200×630",icon:e.jsx(Qp,{className:"h-4 w-4"})}],Fun=[{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:"📰"}],Lwt={"luxury-dark":Drt,"modern-clean":Frt,"bold-colorful":Ort,editorial:zrt},t9e=s=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(s);function Oun(s){var l;const[t,n]=s.split(","),r=((l=t.match(/:(.*?);/))==null?void 0:l[1])||"image/png",a=atob(n),i=new Uint8Array(a.length);for(let o=0;oEe.is_default))??(s==null?void 0:s[0])??null,[n,r]=j.useState(void 0),a=(s==null?void 0:s.find(Ee=>Ee.id===n))??t,i=Sa(),[l,o]=j.useState("mine"),[c,d]=j.useState(""),[u,h]=j.useState("address"),[m,f]=j.useState(!1),[g,x]=j.useState([]),[y,v]=j.useState(null),[b,w]=j.useState(0),[S,C]=j.useState("just-listed"),[E,I]=j.useState(["instagram-square"]),[P,R]=j.useState("luxury-dark"),[D,O]=j.useState(!0),[U,W]=j.useState(!1),[V,G]=j.useState([]),[Y,X]=j.useState("search"),ae=j.useRef({}),{data:ie=[],isLoading:ne}=tt({queryKey:["marketing-studio-my-listings",i],enabled:!!i,queryFn:async()=>{const{data:Ee,error:Se}=await q.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(Se)throw Se;return(Ee||[]).map(Le=>{const Fe=(Le.listing_photos||[]).slice().sort((Ve,je)=>(je.is_primary?1:0)-(Ve.is_primary?1:0)||(Ve.sort_order??0)-(je.sort_order??0)).map(Ve=>Ve.photo_url).filter(Boolean),ke=String(Le.status||"");return{mlsNumber:Le.id,address:Le.property_address||"",city:Le.city||"",state:Le.state||"",zip:"",price:Number(Le.price||0),status:ke,bedrooms:Number(Le.bedrooms||0),bathrooms:Number(Le.bathrooms||0),sqft:Number(Le.square_footage||0),lotSize:"",yearBuilt:Le.year_built??null,propertyType:Le.property_type||"",description:Le.description||"",photos:Fe,listDate:Le.created_at,soldDate:ke.toLowerCase().includes("sold")?Le.created_at:null,soldPrice:null,agent:{name:"",office:""}}})}}),te=j.useMemo(()=>!D||!a?{enabled:!1}:{enabled:!0,agentName:a.display_name||"",brokerage:a.tagline||"",agentPhotoUrl:a.headshot_url||void 0},[D,a]),J=async()=>{if(c.trim()){f(!0),x([]);try{const{data:Ee,error:Se}=await q.functions.invoke("repliers-mls-search",{body:{searchType:u,query:c.trim()}});if(Se)throw Se;if(Ee!=null&&Ee.error)throw new Error(Ee.error);x((Ee==null?void 0:Ee.listings)||[]),((Ee==null?void 0:Ee.listings)||[]).length===0&&re.info("No listings found. Try a different search.")}catch(Ee){re.error(Ee.message||"Search failed")}finally{f(!1)}}},ce=Ee=>{var Se;v(Ee),w(0),X("customize"),Ee.soldDate||(Se=Ee.status)!=null&&Se.toLowerCase().includes("sold")?C("just-sold"):C("just-listed")},_e=Ee=>I(Se=>Se.includes(Ee)?Se.filter(Le=>Le!==Ee):[...Se,Ee]),he=y?{listing:y,postType:S,format:"instagram-square",branding:te,selectedPhotoIndex:b}:null,ue=j.useCallback(async()=>{if(!(!y||E.length===0)){W(!0),G([]),X("generate");try{await new Promise(Se=>setTimeout(Se,600));const Ee=[];for(const Se of E){const Le=`${P}-${Se}`,Fe=ae.current[Le];if(!Fe)continue;const ke=jI[Se],Ve=await $G(Fe,{width:ke.width,height:ke.height,pixelRatio:1,cacheBust:!0,style:{transform:"none",transformOrigin:"top left"}});Ee.push({format:Se,url:Ve})}G(Ee),re.success(`Generated ${Ee.length} design${Ee.length>1?"s":""}!`)}catch(Ee){re.error(Ee.message||"Generation failed")}finally{W(!1)}}},[y,E,P]),ve=(Ee,Se)=>{const Le=`${((y==null?void 0:y.address)||"listing").replace(/\s+/g,"-")}-${S}-${Se}.png`;try{const Fe=Oun(Ee),ke=URL.createObjectURL(Fe);if(zun)window.open(ke,"_blank"),re.message("Long-press the image to save to Photos");else{const Ve=document.createElement("a");Ve.href=ke,Ve.download=Le,document.body.appendChild(Ve),Ve.click(),document.body.removeChild(Ve)}setTimeout(()=>URL.revokeObjectURL(ke),6e4)}catch{const Fe=document.createElement("a");Fe.href=Ee,Fe.download=Le,Fe.click()}};return j.useEffect(()=>{!n&&t&&r(t.id)},[t,n]),e.jsx(Vs,{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(Ml,{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($,{variant:"ghost",size:"sm",asChild:!0,children:e.jsxs(wr,{to:"/marketing-studio",children:[e.jsx(qa,{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(Be,{variant:"secondary",className:"mb-2 gap-1",children:[e.jsx(Nn,{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(ee,{className:"text-xs text-muted-foreground",children:"Brand preset"}),e.jsxs(ms,{value:n,onValueChange:r,children:[e.jsx(us,{children:e.jsx(fs,{placeholder:"Default"})}),e.jsx(hs,{children:s.map(Ee=>e.jsxs(Ge,{value:Ee.id,children:[Ee.name,Ee.is_default?" (default)":""]},Ee.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:()=>X("search"),className:`flex items-center gap-1.5 px-3 py-1.5 rounded-full whitespace-nowrap ${Y==="search"?"bg-primary text-primary-foreground":"bg-muted text-muted-foreground"}`,children:[e.jsx(Kr,{className:"h-3.5 w-3.5"})," 1. Find listing"]}),e.jsx(Di,{className:"h-4 w-4 text-muted-foreground shrink-0"}),e.jsxs("button",{onClick:()=>y&&X("customize"),disabled:!y,className:`flex items-center gap-1.5 px-3 py-1.5 rounded-full whitespace-nowrap ${Y==="customize"?"bg-primary text-primary-foreground":y?"bg-muted text-muted-foreground":"bg-muted text-muted-foreground/50"}`,children:[e.jsx(Nn,{className:"h-3.5 w-3.5"})," 2. Customize"]}),e.jsx(Di,{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 ${Y==="generate"?"bg-primary text-primary-foreground":"bg-muted text-muted-foreground/50"}`,children:[e.jsx(di,{className:"h-3.5 w-3.5"})," 3. Download"]})]}),Y==="search"&&e.jsxs("div",{className:"space-y-4",children:[e.jsx(ha,{value:l,onValueChange:Ee=>o(Ee),children:e.jsxs(ma,{className:"grid grid-cols-2 w-full sm:w-auto",children:[e.jsxs(Zt,{value:"mine",children:[e.jsx(va,{className:"h-4 w-4 mr-1.5"})," My Listings"]}),e.jsxs(Zt,{value:"mls",children:[e.jsx(Kr,{className:"h-4 w-4 mr-1.5"})," MLS Search"]})]})}),l==="mine"&&e.jsx("div",{className:"space-y-3",children:ne?e.jsx(Ne,{children:e.jsx(Ie,{className:"py-12 flex items-center justify-center",children:e.jsx(kt,{className:"h-6 w-6 animate-spin text-muted-foreground"})})}):ie.length===0?e.jsx(Ne,{children:e.jsxs(Ie,{className:"py-10 text-center space-y-2",children:[e.jsx(va,{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($,{variant:"outline",size:"sm",asChild:!0,className:"mt-2",children:e.jsx(wr,{to:"/mission-control/listings",children:"Go to Listings"})})]})}):e.jsxs(e.Fragment,{children:[e.jsxs("h3",{className:"text-sm font-medium text-muted-foreground",children:[ie.length," listing",ie.length!==1?"s":""," from your Listing Exchange"]}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:ie.map((Ee,Se)=>{var Le;return e.jsx(Ne,{className:"cursor-pointer hover:border-primary/50 hover:shadow-md transition-all group overflow-hidden",onClick:()=>ce(Ee),children:e.jsx(Ie,{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:(Le=Ee.photos)!=null&&Le[0]?e.jsx("img",{src:Ee.photos[0],alt:Ee.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(va,{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:Ee.price>0?t9e(Ee.price):"—"}),e.jsx("p",{className:"text-sm text-muted-foreground truncate",children:Ee.address}),e.jsxs("p",{className:"text-xs text-muted-foreground truncate",children:[Ee.city,Ee.state?`, ${Ee.state}`:""]}),e.jsxs("div",{className:"flex items-center gap-3 mt-1.5 text-xs text-muted-foreground",children:[Ee.bedrooms>0&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(T4,{className:"h-3 w-3"})," ",Ee.bedrooms]}),Ee.bathrooms>0&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(T0,{className:"h-3 w-3"})," ",Ee.bathrooms]}),Ee.sqft>0&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(Zz,{className:"h-3 w-3"})," ",Ee.sqft.toLocaleString()]})]}),Ee.status&&e.jsx("div",{className:"flex items-center gap-2 mt-1 flex-wrap",children:e.jsx(Be,{variant:"outline",className:"text-[10px]",children:Ee.status})})]})]})})},Ee.mlsNumber||Se)})})]})}),l==="mls"&&e.jsxs(e.Fragment,{children:[e.jsxs(Ne,{className:"overflow-hidden",children:[e.jsxs(Ct,{children:[e.jsxs(At,{className:"flex items-center gap-2 text-base md:text-lg",children:[e.jsx(Kr,{className:"h-5 w-5 text-primary"})," Search MLS"]}),e.jsxs(Gn,{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(Ie,{className:"space-y-3",children:[e.jsx(ha,{value:u,onValueChange:Ee=>h(Ee),children:e.jsxs(ma,{children:[e.jsxs(Zt,{value:"address",children:[e.jsx(ci,{className:"h-4 w-4 mr-1.5"})," Address"]}),e.jsxs(Zt,{value:"mls",children:[e.jsx(Ap,{className:"h-4 w-4 mr-1.5"})," MLS #"]})]})}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-2",children:[e.jsx(pe,{value:c,onChange:Ee=>d(Ee.target.value),placeholder:u==="mls"?"Enter MLS number...":"Enter property address...",className:"flex-1",onKeyDown:Ee=>Ee.key==="Enter"&&J()}),e.jsxs($,{onClick:J,disabled:m||!c.trim(),className:"sm:w-auto w-full",children:[m?e.jsx(kt,{className:"h-4 w-4 animate-spin mr-1.5"}):e.jsx(Kr,{className:"h-4 w-4 mr-1.5"})," Search"]})]})]})]}),g.length>0&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("h3",{className:"text-sm font-medium text-muted-foreground",children:[g.length," listing",g.length!==1?"s":""," found"]}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:g.map((Ee,Se)=>{var Le;return e.jsx(Ne,{className:"cursor-pointer hover:border-primary/50 hover:shadow-md transition-all group overflow-hidden",onClick:()=>ce(Ee),children:e.jsx(Ie,{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:(Le=Ee.photos)!=null&&Le[0]?e.jsx("img",{src:Ee.photos[0],alt:Ee.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(va,{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:t9e(Ee.price)}),e.jsx("p",{className:"text-sm text-muted-foreground truncate",children:Ee.address}),e.jsxs("p",{className:"text-xs text-muted-foreground truncate",children:[Ee.city,", ",Ee.state," ",Ee.zip]}),e.jsxs("div",{className:"flex items-center gap-3 mt-1.5 text-xs text-muted-foreground",children:[Ee.bedrooms>0&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(T4,{className:"h-3 w-3"})," ",Ee.bedrooms]}),Ee.bathrooms>0&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(T0,{className:"h-3 w-3"})," ",Ee.bathrooms]}),Ee.sqft>0&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(Zz,{className:"h-3 w-3"})," ",Ee.sqft.toLocaleString()]})]}),e.jsxs("div",{className:"flex items-center gap-2 mt-1 flex-wrap",children:[Ee.mlsNumber&&e.jsx(Be,{variant:"outline",className:"text-[10px]",children:Ee.mlsNumber}),Ee.status&&e.jsx(Be,{variant:"outline",className:"text-[10px]",children:Ee.status})]})]})]})})},Ee.mlsNumber||Se)})})]})]})]}),Y==="customize"&&y&&he&&e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-3 gap-4 md:gap-6",children:[e.jsxs(Ne,{className:"lg:col-span-1 overflow-hidden min-w-0",children:[e.jsx(Ct,{className:"pb-3",children:e.jsx(At,{className:"text-base",children:"Selected listing"})}),e.jsxs(Ie,{className:"space-y-3",children:[y.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:y.photos[b],alt:"",className:"w-full h-full object-cover"})}),y.photos.length>1&&e.jsxs("div",{className:"flex items-center justify-between mt-2",children:[e.jsx($,{variant:"outline",size:"icon",className:"h-7 w-7",onClick:()=>w(Ee=>Math.max(0,Ee-1)),disabled:b===0,children:e.jsx(Cd,{className:"h-4 w-4"})}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[b+1," of ",y.photos.length]}),e.jsx($,{variant:"outline",size:"icon",className:"h-7 w-7",onClick:()=>w(Ee=>Math.min(y.photos.length-1,Ee+1)),disabled:b===y.photos.length-1,children:e.jsx(Di,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{children:[e.jsx("p",{className:"font-bold text-lg",children:t9e(y.price)}),e.jsx("p",{className:"text-sm text-muted-foreground",children:y.address}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[y.city,", ",y.state," ",y.zip]})]}),e.jsxs("div",{className:"grid grid-cols-3 gap-2 text-center",children:[y.bedrooms>0&&e.jsxs("div",{className:"bg-muted/50 rounded-lg p-2",children:[e.jsx("p",{className:"text-sm font-semibold",children:y.bedrooms}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"Beds"})]}),y.bathrooms>0&&e.jsxs("div",{className:"bg-muted/50 rounded-lg p-2",children:[e.jsx("p",{className:"text-sm font-semibold",children:y.bathrooms}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"Baths"})]}),y.sqft>0&&e.jsxs("div",{className:"bg-muted/50 rounded-lg p-2",children:[e.jsx("p",{className:"text-sm font-semibold",children:y.sqft.toLocaleString()}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"Sq Ft"})]})]}),e.jsxs($,{variant:"outline",size:"sm",className:"w-full",onClick:()=>{X("search"),v(null)},children:[e.jsx(Ex,{className:"h-3.5 w-3.5 mr-1.5"})," Choose different listing"]})]})]}),e.jsxs(Ne,{className:"lg:col-span-2 overflow-hidden min-w-0",children:[e.jsxs(Ct,{children:[e.jsxs(At,{className:"flex items-center gap-2 text-base",children:[e.jsx(Nn,{className:"h-5 w-5 text-primary"})," Customize"]}),e.jsx(Gn,{children:"Pick a template, post type, and output format."})]}),e.jsxs(Ie,{className:"space-y-5",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ee,{className:"text-sm font-medium flex items-center gap-2",children:[e.jsx(Yc,{className:"h-4 w-4"})," Template style"]}),e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-2",children:Fun.map(Ee=>e.jsxs("button",{onClick:()=>R(Ee.value),className:`flex flex-col items-center gap-1 px-2 py-3 rounded-lg border-2 transition-all text-center ${P===Ee.value?"border-primary bg-primary/5":"border-border hover:border-primary/30"}`,children:[e.jsx("span",{className:"text-2xl",children:Ee.preview}),e.jsx("span",{className:"text-sm font-medium",children:Ee.label}),e.jsx("span",{className:"text-[10px] text-muted-foreground leading-tight",children:Ee.description})]},Ee.value))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{className:"text-sm font-medium",children:"Post type"}),e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-2",children:Dun.map(Ee=>e.jsxs("button",{onClick:()=>C(Ee.value),className:`flex items-center justify-center gap-2 px-3 py-2.5 rounded-lg border-2 transition-all text-sm font-medium ${S===Ee.value?"border-primary bg-primary/5":"border-border hover:border-primary/30"}`,children:[e.jsx("span",{className:"text-lg",children:Ee.icon})," ",e.jsx("span",{className:"truncate",children:Ee.label})]},Ee.value))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{className:"text-sm font-medium",children:"Output formats"}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-2",children:Iwt.map(Ee=>e.jsxs("button",{onClick:()=>_e(Ee.value),className:`flex items-center gap-2 px-3 py-2.5 rounded-lg border-2 transition-all text-sm ${E.includes(Ee.value)?"border-primary bg-primary/5":"border-border hover:border-primary/30"}`,children:[Ee.icon,e.jsxs("div",{className:"text-left min-w-0",children:[e.jsx("p",{className:"font-medium truncate",children:Ee.label}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:Ee.dimensions})]})]},Ee.value))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(ee,{className:"text-sm font-medium flex items-center gap-2",children:[e.jsx(sl,{className:"h-4 w-4"})," Show my branding"]}),e.jsx(Sn,{checked:D,onCheckedChange:O})]}),D&&!a&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["No brand preset yet. ",e.jsx(wr,{to:"/marketing-studio/brand-kit",className:"underline",children:"Create one"})," to add your headshot and name."]}),D&&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(ee,{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*(jI[E[0]||"instagram-square"].height/jI[E[0]||"instagram-square"].width)},children:(()=>{const Ee=Lwt[P],Se=E[0]||"instagram-square";return e.jsx(Ee,{...he,format:Se})})()})})]}),e.jsx($,{onClick:ue,disabled:E.length===0||U,size:"lg",className:"w-full gap-2",children:U?e.jsxs(e.Fragment,{children:[e.jsx(kt,{className:"h-5 w-5 animate-spin"})," Generating..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Nn,{className:"h-5 w-5"})," Generate ",E.length," design",E.length>1?"s":""]})})]})]})]}),Y==="generate"&&e.jsxs("div",{className:"space-y-4",children:[U&&e.jsx(Ne,{children:e.jsxs(Ie,{className:"flex flex-col items-center justify-center py-16",children:[e.jsx(kt,{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."})]})}),V.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($,{variant:"outline",size:"sm",onClick:()=>X("customize"),children:[e.jsx(Ex,{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:V.map((Ee,Se)=>{const Le=Iwt.find(Fe=>Fe.value===Ee.format);return e.jsxs(Ne,{className:"overflow-hidden",children:[e.jsx("div",{className:"bg-muted/30 p-1",children:e.jsx("img",{src:Ee.url,alt:"",className:"w-full rounded"})}),e.jsxs(Ie,{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:[Le==null?void 0:Le.icon,e.jsx("span",{className:"text-sm font-medium",children:Le==null?void 0:Le.label})]}),e.jsx(Be,{variant:"outline",className:"text-[10px]",children:Le==null?void 0:Le.dimensions})]}),e.jsxs($,{size:"sm",className:"w-full gap-1.5",onClick:()=>ve(Ee.url,Ee.format),children:[e.jsx(di,{className:"h-3.5 w-3.5"})," Download"]})]})]},Se)})})]})]}),Y==="generate"&&y&&he&&e.jsx("div",{style:{position:"fixed",left:"-99999px",top:0,pointerEvents:"none"},"aria-hidden":!0,children:E.map(Ee=>{const Se=Lwt[P],Le=jI[Ee];return e.jsx("div",{style:{width:Le.width,height:Le.height},children:e.jsx(Se,{ref:Fe=>{ae.current[`${P}-${Ee}`]=Fe},...he,format:Ee})},`${P}-${Ee}`)})})]})})}var $un=Object.defineProperty,Uun=(s,t)=>$un(s,"name",{value:t,configurable:!0}),qun="Toggle",bWt=j.forwardRef(Uun(function(t,n){const{pressed:r,defaultPressed:a,onPressedChange:i,...l}=t,[o,c]=fy({prop:r,onChange:i,defaultProp:a??!1,caller:qun});return e.jsx(Ei.button,{type:"button","aria-pressed":o,"data-state":o?"on":"off","data-disabled":t.disabled?"":void 0,...l,ref:n,onClick:Ra(t.onClick,()=>{t.disabled||c(!o)})})},"Toggle")),_Wt=bWt,Vun=Object.defineProperty,FL=(s,t)=>Vun(s,"name",{value:t,configurable:!0}),jK="ToggleGroup",[wWt,BSr]=tp(jK,[r6]),jWt=r6(),NWt=j.forwardRef(FL(function(t,n){const{type:r,...a}=t;if(r==="single"){const i=a;return e.jsx(Hun,{role:"radiogroup",...i,ref:n})}if(r==="multiple"){const i=a;return e.jsx(Gun,{role:"toolbar",...i,ref:n})}throw new Error(`Missing prop \`type\` expected on \`${jK}\``)},"ToggleGroup")),[kWt,SWt]=wWt(jK),Hun=j.forwardRef(FL(function(t,n){const{value:r,defaultValue:a,onValueChange:i=FL(()=>{},"onValueChange"),...l}=t,[o,c]=fy({prop:r,defaultProp:a??"",onChange:i,caller:jK});return e.jsx(kWt,{scope:t.__scopeToggleGroup,type:"single",value:j.useMemo(()=>o?[o]:[],[o]),onItemActivate:c,onItemDeactivate:j.useCallback(()=>c(""),[c]),children:e.jsx(CWt,{...l,ref:n})})},"ToggleGroupImplSingle")),Gun=j.forwardRef(FL(function(t,n){const{value:r,defaultValue:a,onValueChange:i=FL(()=>{},"onValueChange"),...l}=t,[o,c]=fy({prop:r,defaultProp:a??[],onChange:i,caller:jK}),d=j.useCallback(h=>c((m=[])=>[...m,h]),[c]),u=j.useCallback(h=>c((m=[])=>m.filter(f=>f!==h)),[c]);return e.jsx(kWt,{scope:t.__scopeToggleGroup,type:"multiple",value:o,onItemActivate:d,onItemDeactivate:u,children:e.jsx(CWt,{...l,ref:n})})},"ToggleGroupImplMultiple")),[Wun,Kun]=wWt(jK),CWt=j.forwardRef(FL(function(t,n){const{__scopeToggleGroup:r,disabled:a=!1,rovingFocus:i=!0,orientation:l,dir:o,loop:c=!0,...d}=t,u=jWt(r),h=l3(o),m={dir:h,...d};return e.jsx(Wun,{scope:r,rovingFocus:i,disabled:a,children:i?e.jsx(xLe,{asChild:!0,...u,orientation:l,dir:h,loop:c,children:e.jsx(Ei.div,{...m,ref:n})}):e.jsx(Ei.div,{...m,ref:n})})},"ToggleGroupImpl")),GWe="ToggleGroupItem",AWt=j.forwardRef(FL(function(t,n){const r=SWt(GWe,t.__scopeToggleGroup),a=Kun(GWe,t.__scopeToggleGroup),i=jWt(t.__scopeToggleGroup),l=r.value.includes(t.value),o=a.disabled||t.disabled,c={...t,pressed:l,disabled:o},d=j.useRef(null);return a.rovingFocus?e.jsx(yLe,{asChild:!0,...i,focusable:!o,active:l,ref:d,children:e.jsx(Rwt,{...c,ref:n})}):e.jsx(Rwt,{...c,ref:n})},"ToggleGroupItem")),Rwt=j.forwardRef(FL(function(t,n){const{__scopeToggleGroup:r,value:a,...i}=t,l=SWt(GWe,r),o={role:"radio","aria-checked":t.pressed,"aria-pressed":void 0},c=l.type==="single"?o:void 0;return e.jsx(bWt,{...c,...i,ref:n,onPressedChange:d=>{d?l.onItemActivate(a):l.onItemDeactivate(a)}})},"ToggleGroupItemImpl"));const EWt=DB("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"}}),Yun=j.forwardRef(({className:s,variant:t,size:n,...r},a)=>e.jsx(_Wt,{ref:a,className:Pt(EWt({variant:t,size:n,className:s})),...r}));Yun.displayName=_Wt.displayName;const TWt=j.createContext({size:"default",variant:"default"}),EV=j.forwardRef(({className:s,variant:t,size:n,children:r,...a},i)=>e.jsx(NWt,{ref:i,className:Pt("flex items-center justify-center gap-1",s),...a,children:e.jsx(TWt.Provider,{value:{variant:t,size:n},children:r})}));EV.displayName=NWt.displayName;const _7=j.forwardRef(({className:s,children:t,variant:n,size:r,...a},i)=>{const l=j.useContext(TWt);return e.jsx(AWt,{ref:i,className:Pt(EWt({variant:l.variant||n,size:l.size||r}),s),...a,children:t})});_7.displayName=AWt.displayName;const Zun=[{id:"meet",label:"Meet Your Agent",icon:sl,description:"Polished intro card with your headshot, story, and contact."},{id:"testimonial",label:"Testimonial",icon:x2,description:"Turn a Zillow / Google review into a branded graphic."},{id:"milestone",label:"Milestone",icon:Kl,description:"Celebrate homes sold, awards, anniversaries, achievements."},{id:"tip",label:"Pro Tip",icon:tC,description:"Drop a value-bomb tip — buyer/seller advice, market insight."},{id:"quote",label:"Quote / Mantra",icon:xm,description:"Personal philosophy, mantra, or rallying call."}],s9e={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"}},Xun=[{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."}],Dwt={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 Qun(){const{data:s}=ion(),{data:t}=_ie(),[n,r]=j.useState(void 0),a=j.useMemo(()=>(t==null?void 0:t.find(g=>g.id===n))??s??null,[t,n,s]),[i,l]=j.useState({template:"meet",style:"editorial",aspect:"portrait",rating:5,...Dwt.meet}),o=g=>l(x=>({...x,...g})),c=g=>l(x=>({...x,template:g,...Dwt[g]})),d=j.useRef(null),[u,h]=j.useState(!1),m=async()=>{if(!d.current)return;h(!0);const g=d.current,x=g.style.transform;try{g.style.transform="none",await new Promise(b=>requestAnimationFrame(()=>b(null)));const y=await $G(g,{cacheBust:!0,pixelRatio:2,width:g.offsetWidth,height:g.offsetHeight,backgroundColor:"#ffffff"}),v=document.createElement("a");v.href=y,v.download=`personal-branding-${i.template}-${Date.now()}.png`,document.body.appendChild(v),v.click(),v.remove(),re.success("Downloaded to your device")}catch(y){re.error((y==null?void 0:y.message)||"Export failed")}finally{g.style.transform=x,h(!1)}},f=s9e[i.aspect];return e.jsx(Vs,{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(Ml,{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(wr,{to:"/marketing-studio",className:"text-sm text-muted-foreground inline-flex items-center gap-1 hover:underline",children:[e.jsx(qa,{className:"h-3 w-3"})," Back to Marketing Studio"]}),e.jsx("div",{className:"flex items-center gap-2 mt-1",children:e.jsxs(Be,{variant:"secondary",className:"gap-1",children:[e.jsx(Nn,{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($,{variant:"outline",asChild:!0,children:e.jsxs(wr,{to:"/marketing-studio/brand-kit",children:[e.jsx(Yc,{className:"h-4 w-4 mr-1"})," Brand Kit"]})}),e.jsxs($,{onClick:m,disabled:u,children:[e.jsx(di,{className:"h-4 w-4 mr-1"})," ",u?"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(Ne,{children:e.jsxs(Ie,{className:"p-4 space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{className:"text-xs uppercase tracking-wider text-muted-foreground",children:"Template"}),e.jsx("div",{className:"grid grid-cols-2 gap-2",children:Zun.map(g=>{const x=g.icon,y=i.template===g.id;return e.jsxs("button",{onClick:()=>c(g.id),className:`text-left rounded-lg border p-3 transition-all ${y?"border-primary bg-primary/5 ring-2 ring-primary/30":"border-border hover:border-primary/50"}`,children:[e.jsx(x,{className:"h-4 w-4 mb-1"}),e.jsx("div",{className:"text-xs font-semibold",children:g.label})]},g.id)})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{className:"text-xs uppercase tracking-wider text-muted-foreground",children:"Style"}),e.jsx(EV,{type:"single",value:i.style,onValueChange:g=>g&&o({style:g}),className:"grid grid-cols-2 gap-1",children:Xun.map(g=>e.jsx(_7,{value:g.id,className:"text-xs h-9",children:g.label},g.id))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{className:"text-xs uppercase tracking-wider text-muted-foreground",children:"Format"}),e.jsx(EV,{type:"single",value:i.aspect,onValueChange:g=>g&&o({aspect:g}),className:"grid grid-cols-3 gap-1",children:Object.keys(s9e).map(g=>e.jsx(_7,{value:g,className:"text-xs h-9",children:s9e[g].label},g))})]}),t&&t.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{className:"text-xs uppercase tracking-wider text-muted-foreground",children:"Brand preset"}),e.jsxs(ms,{value:n??(s==null?void 0:s.id)??"",onValueChange:r,children:[e.jsx(us,{children:e.jsx(fs,{placeholder:"Choose preset"})}),e.jsx(hs,{children:t.map(g=>e.jsx(Ge,{value:g.id,children:g.name},g.id))})]})]})]})}),e.jsx(Ne,{children:e.jsxs(Ie,{className:"p-4 space-y-3",children:[e.jsx(ee,{className:"text-xs uppercase tracking-wider text-muted-foreground",children:"Content"}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{htmlFor:"headline",className:"text-xs",children:"Headline"}),e.jsx(Rs,{id:"headline",value:i.headline,onChange:g=>o({headline:g.target.value}),rows:2})]}),i.template!=="quote"&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{htmlFor:"subline",className:"text-xs",children:"Subline"}),e.jsx(pe,{id:"subline",value:i.subline,onChange:g=>o({subline:g.target.value})})]}),i.template!=="quote"&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{htmlFor:"body",className:"text-xs",children:"Body"}),e.jsx(Rs,{id:"body",value:i.body,onChange:g=>o({body:g.target.value}),rows:4})]}),(i.template==="testimonial"||i.template==="quote")&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{htmlFor:"attribution",className:"text-xs",children:"Attribution"}),e.jsx(pe,{id:"attribution",value:i.attribution,onChange:g=>o({attribution:g.target.value}),placeholder:"— Client name / Source"})]}),i.template==="testimonial"&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{className:"text-xs",children:"Rating"}),e.jsx(EV,{type:"single",value:String(i.rating),onValueChange:g=>g&&o({rating:Number(g)}),className:"grid grid-cols-5 gap-1",children:[1,2,3,4,5].map(g=>e.jsxs(_7,{value:String(g),className:"text-xs h-9",children:[g,"★"]},g))})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{htmlFor:"badge",className:"text-xs",children:"Eyebrow tag"}),e.jsx(pe,{id:"badge",value:i.badgeText,onChange:g=>o({badgeText:g.target.value})})]})]})})]}),e.jsx(Jun,{aspect:f,canvasRef:d,children:e.jsx(ehn,{form:i,preset:a,width:f.w,height:f.h})})]})]})})}function Jun({aspect:s,canvasRef:t,children:n}){const r=j.useRef(null),[a,i]=j.useState(.5);return j.useEffect(()=>{const l=r.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:r,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:n})})}),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 ehn({form:s,preset:t,width:n,height:r}){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)||"",u=(t==null?void 0:t.email)||"",h=(t==null?void 0:t.tagline)||"",m=(t==null?void 0:t.website_url)||"",f={form:s,brandColor:a,accentColor:i,headshot:l,logo:o,name:c,phone:d,email:u,tagline:h,website:m,width:n,height:r};return s.style==="editorial"?e.jsx(thn,{...f}):s.style==="bold"?e.jsx(shn,{...f}):s.style==="luxury"?e.jsx(rhn,{...f}):e.jsx(nhn,{...f})}function MWt({name:s,phone:t,email:n,website:r,color:a}){const i=[t,n,r].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 cRe({rating:s,color:t}){return e.jsx("div",{style:{display:"flex",gap:4},children:Array.from({length:5}).map((n,r)=>e.jsx(Ja,{size:28,fill:r1.5;return e.jsxs("div",{style:{width:h,height:m,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:n},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:h-128,height:f?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:r,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(cRe,{rating:t.rating,color:r}),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(MWt,{name:l,phone:o,email:c,website:d,color:"#1a1a1a"}),i&&e.jsx("img",{src:i,crossOrigin:"anonymous",style:{height:56,objectFit:"contain"}})]}),u&&e.jsx("div",{style:{fontFamily:"Inter, sans-serif",fontSize:13,color:"#888",marginTop:12,fontStyle:"italic"},children:u})]})]})}function shn(s){const{form:t,brandColor:n,accentColor:r,headshot:a,logo:i,name:l,phone:o,email:c,website:d,width:u,height:h}=s;return e.jsxs("div",{style:{width:u,height:h,position:"relative",overflow:"hidden",fontFamily:"Inter, system-ui, sans-serif",background:`linear-gradient(135deg, ${n} 0%, ${ahn(n,-20)} 100%)`,color:"#fff"},children:[e.jsx("div",{style:{position:"absolute",top:-200,right:-200,width:700,height:700,borderRadius:"50%",background:r,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:r,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 ${r}`},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:r},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:u-128},children:t.headline}),t.subline&&e.jsx("div",{style:{fontSize:28,marginTop:16,color:r,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(cRe,{rating:t.rating,color:r}),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:r,marginBottom:20,width:80}}),e.jsx(MWt,{name:l,phone:o,email:c,website:d,color:"#fff"})]})]})}function nhn(s){const{form:t,brandColor:n,accentColor:r,headshot:a,logo:i,name:l,phone:o,email:c,website:d,width:u,height:h}=s;return e.jsxs("div",{style:{width:u,height:h,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:r}}),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:n,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(cRe,{rating:t.rating,color:r})}),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 rhn(s){const{form:t,accentColor:n,headshot:r,logo:a,name:i,phone:l,email:o,website:c,width:d,height:u}=s,h=n||"#D4AF37";return e.jsxs("div",{style:{width:d,height:u,background:"#0B0B0E",position:"relative",fontFamily:"Georgia, serif",color:"#EAE6DC",overflow:"hidden"},children:[e.jsx("div",{style:{position:"absolute",inset:40,border:`1px solid ${h}`,opacity:.6}}),e.jsx("div",{style:{position:"absolute",inset:50,border:`1px solid ${h}`,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:h},children:t.badgeText}),e.jsx("div",{style:{width:40,height:1,background:h,margin:"20px auto 0"}})]}),r&&(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 ${h}`},children:e.jsx("img",{src:r,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:r&&(t.template==="meet"||t.template==="milestone")?680:280,textAlign:"center"},children:[t.template==="testimonial"&&e.jsx("div",{style:{fontSize:100,lineHeight:.6,color:h},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:h,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(cRe,{rating:t.rating,color:h})}),t.attribution&&e.jsxs("div",{style:{fontFamily:"Inter, sans-serif",fontSize:16,marginTop:16,color:h,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:h,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 ahn(s,t){const n=s.replace("#",""),r=parseInt(n.length===3?n.split("").map(o=>o+o).join(""):n,16);let a=(r>>16)+Math.round(t/100*255),i=(r>>8&255)+Math.round(t/100*255),l=(r&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 ihn=()=>{const{swagId:s}=Wi(),{user:t}=vs(),{toast:n}=Bi(),r=Vt(),{trackEngagement:a}=gK(),[i,l]=j.useState(""),{data:o,isLoading:c}=tt({queryKey:["social-swag-detail",s],queryFn:async()=>{const{data:v,error:b}=await q.from("social_swag").select("*").eq("id",s).single();if(b)throw b;const{data:w}=await q.from("social_swag_links").select("*").eq("swag_id",s).order("sort_order");return{...v,links:w||[]}},enabled:!!s});j.useEffect(()=>{o&&a("social_swag",o.id,o.title,"view")},[o==null?void 0:o.id]);const{data:d=[]}=tt({queryKey:["social-swag-likes",s],queryFn:async()=>{const{data:v,error:b}=await q.from("social_swag_likes").select("*").eq("swag_id",s);if(b)throw b;return v},enabled:!!s}),{data:u=[]}=tt({queryKey:["social-swag-comments",s],queryFn:async()=>{const{data:v,error:b}=await q.from("social_swag_comments").select("*").eq("swag_id",s).order("created_at",{ascending:!1});if(b)throw b;const w=[...new Set(v.map(E=>E.user_id))],{data:S}=await q.from("profiles").select("id, name").in("id",w),C=new Map((S==null?void 0:S.map(E=>[E.id,E.name]))||[]);return v.map(E=>({...E,user_name:C.get(E.user_id)||"Unknown User"}))},enabled:!!s}),h=ft({mutationFn:async v=>{const{error:b}=await q.from("social_swag_comments").insert({swag_id:s,user_id:t.id,content:v});if(b)throw b},onSuccess:()=>{r.invalidateQueries({queryKey:["social-swag-comments",s]}),l(""),n({title:"Comment added!"})},onError:v=>{n({title:"Error adding comment",description:v.message,variant:"destructive"})}}),m=ft({mutationFn:async v=>{const{error:b}=await q.from("social_swag_comments").delete().eq("id",v);if(b)throw b},onSuccess:()=>{r.invalidateQueries({queryKey:["social-swag-comments",s]}),n({title:"Comment deleted"})}}),f=ft({mutationFn:async()=>{const v=d.find(b=>b.user_id===(t==null?void 0:t.id));if(v){const{error:b}=await q.from("social_swag_likes").delete().eq("id",v.id);if(b)throw b}else{const{error:b}=await q.from("social_swag_likes").insert({swag_id:s,user_id:t.id});if(b)throw b}},onSuccess:()=>{r.invalidateQueries({queryKey:["social-swag-likes",s]})}}),g=d.some(v=>v.user_id===(t==null?void 0:t.id)),x=v=>v.split(" ").map(b=>b[0]).join("").toUpperCase().slice(0,2),y=v=>{v.preventDefault(),!(!i.trim()||!t)&&h.mutate(i.trim())};return c?e.jsx(Vs,{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(Vs,{title:o.title,children:e.jsxs("div",{className:"space-y-6 max-w-5xl mx-auto",children:[e.jsx($,{variant:"ghost",size:"sm",asChild:!0,className:"gap-2",children:e.jsxs(wr,{to:"/social-swag",children:[e.jsx(qa,{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(vK,{resourceType:"social_swag",resourceId:o.id,resourceTitle:o.title}),e.jsxs($,{variant:g?"default":"outline",className:"gap-2 w-fit",onClick:()=>f.mutate(),disabled:!t||f.isPending,children:[e.jsx(Vy,{className:`h-4 w-4 ${g?"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(Ne,{children:e.jsxs(Ie,{className:"pt-6",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 mb-4",children:[e.jsx(Ad,{className:"h-4 w-4"}),o.links.length===1?"Canva Link":"Canva Links"]}),e.jsx("div",{className:"grid gap-2",children:o.links.map(v=>e.jsxs($,{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(v.canva_share_link,"_blank")},children:[e.jsx("span",{className:"font-medium",children:v.title}),e.jsx(kr,{className:"h-4 w-4 text-muted-foreground"})]},v.id))})]})}),e.jsx(Gc,{}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 text-lg",children:[e.jsx(Th,{className:"h-5 w-5"}),"Comments (",u.length,")"]}),t?e.jsxs("form",{onSubmit:y,className:"flex gap-2",children:[e.jsx(Rs,{placeholder:"Add a comment...",value:i,onChange:v=>l(v.target.value),className:"min-h-[80px] resize-none flex-1"}),e.jsx($,{type:"submit",size:"icon",className:"h-10 w-10",disabled:!i.trim()||h.isPending,children:e.jsx(Yr,{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:u.length===0?e.jsx(Ne,{children:e.jsx(Ie,{className:"py-8 text-center",children:e.jsx("p",{className:"text-muted-foreground",children:"No comments yet. Be the first to share your thoughts!"})})}):u.map(v=>e.jsx(Ne,{children:e.jsx(Ie,{className:"pt-4 pb-4",children:e.jsxs("div",{className:"flex gap-3",children:[e.jsx(Oa,{className:"h-10 w-10 flex-shrink-0",children:e.jsx(za,{className:"text-sm",children:x(v.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:v.user_name}),e.jsx("span",{className:"text-sm text-muted-foreground",children:mu(new Date(v.created_at),{addSuffix:!0})}),v.user_id===(t==null?void 0:t.id)&&e.jsx($,{variant:"ghost",size:"icon",className:"h-6 w-6 ml-auto",onClick:()=>m.mutate(v.id),children:e.jsx(Wn,{className:"h-3 w-3 text-muted-foreground"})})]}),e.jsx("p",{className:"text-sm whitespace-pre-wrap",children:v.content})]})]})})},v.id))})]})]})}):e.jsx(Vs,{title:"Social Swag",children:e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(Ad,{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($,{asChild:!0,className:"mt-4",children:e.jsx(wr,{to:"/social-swag",children:"Back to Social Swag"})})]})})},ohn=({categories:s,privateGroups:t,selectedFilter:n,onFilterChange:r,onlineUsers:a})=>{const[i,l]=j.useState(!0),[o,c]=j.useState(!0),[d,u]=j.useState(!0),h=m=>m.split(" ").map(f=>f[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($,{variant:n==="all"?"secondary":"ghost",className:"w-full justify-start",onClick:()=>r("all"),children:[e.jsx(WI,{className:"h-4 w-4 mr-2"}),"All Posts"]}),e.jsxs(j1,{open:i,onOpenChange:l,children:[e.jsx(N1,{asChild:!0,children:e.jsxs($,{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(Tl,{className:"h-4 w-4"}):e.jsx(Di,{className:"h-4 w-4"})]})}),e.jsx(k1,{className:"space-y-1 pl-2",children:s.map(m=>e.jsxs($,{variant:n===m.id?"secondary":"ghost",size:"sm",className:"w-full justify-start h-9",onClick:()=>r(m.id),children:[e.jsx("span",{className:"mr-2",children:m.icon||"📂"}),e.jsx("span",{className:"truncate",children:m.name})]},m.id))})]}),t.length>0&&e.jsxs(j1,{open:o,onOpenChange:c,children:[e.jsx(N1,{asChild:!0,children:e.jsxs($,{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(pc,{className:"h-3 w-3"}),"Your Groups"]}),o?e.jsx(Tl,{className:"h-4 w-4"}):e.jsx(Di,{className:"h-4 w-4"})]})}),e.jsx(k1,{className:"space-y-1 pl-2",children:t.map(m=>e.jsxs($,{variant:n===`group:${m.id}`?"secondary":"ghost",size:"sm",className:"w-full justify-start h-9",onClick:()=>r(`group:${m.id}`),children:[e.jsx("span",{className:"mr-2",children:m.icon||"🔒"}),e.jsx("span",{className:"truncate",children:m.name})]},m.id))})]}),e.jsxs(j1,{open:d,onOpenChange:u,children:[e.jsx(N1,{asChild:!0,children:e.jsxs($,{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(Zn,{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(Tl,{className:"h-4 w-4"}):e.jsx(Di,{className:"h-4 w-4"})]})}),e.jsx(k1,{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(m=>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(Oa,{className:"h-7 w-7",children:[e.jsx(Li,{src:m.avatarUrl}),e.jsx(za,{className:"text-xs",children:h(m.name)})]}),e.jsx(Og,{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:m.name})]},m.id))})]})]})})})},lhn=({categories:s,privateGroups:t,selectedFilter:n,onFilterChange:r,onlineUsers:a})=>{const[i,l]=j.useState(!1),o=d=>d.split(" ").map(u=>u[0]).join("").toUpperCase().slice(0,2),c=()=>{if(n==="all")return"All Posts";if(n.startsWith("group:")){const u=n.replace("group:",""),h=t.find(m=>m.id===u);return h?`🔒 ${h.name}`:"Private Group"}const d=s.find(u=>u.id===n);return d?`${d.icon||"📂"} ${d.name}`:"Category"};return e.jsxs("div",{className:"lg:hidden flex items-center gap-2 mb-4",children:[e.jsxs(Uu,{children:[e.jsx(qu,{asChild:!0,children:e.jsxs($,{variant:"outline",className:"flex-1 justify-between",children:[e.jsx("span",{className:"truncate",children:c()}),e.jsx(Tl,{className:"h-4 w-4 ml-2 shrink-0"})]})}),e.jsxs(Eu,{className:"w-56 bg-background border",children:[e.jsxs(ja,{onClick:()=>r("all"),children:[e.jsx(WI,{className:"h-4 w-4 mr-2"}),"All Posts"]}),e.jsx(R0,{}),e.jsx(SL,{className:"text-xs text-muted-foreground",children:"Categories"}),s.map(d=>e.jsxs(ja,{onClick:()=>r(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(R0,{}),e.jsxs(SL,{className:"text-xs text-muted-foreground flex items-center gap-1",children:[e.jsx(pc,{className:"h-3 w-3"}),"Your Groups"]}),t.map(d=>e.jsxs(ja,{onClick:()=>r(`group:${d.id}`),children:[e.jsx("span",{className:"mr-2",children:d.icon||"🔒"}),d.name]},d.id))]})]})]}),e.jsxs(Wy,{open:i,onOpenChange:l,children:[e.jsx(Fae,{asChild:!0,children:e.jsxs($,{variant:"outline",size:"icon",className:"relative",children:[e.jsx(Zn,{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(py,{children:[e.jsx(D0,{children:e.jsxs(F0,{className:"flex items-center gap-2",children:[e.jsx(Zn,{className:"h-5 w-5"}),"Online Now (",a.length,")"]})}),e.jsx(uo,{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(Oa,{className:"h-10 w-10",children:[e.jsx(Li,{src:d.avatarUrl}),e.jsx(za,{children:o(d.name)})]}),e.jsx(Og,{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 chn=Object.defineProperty,OL=(s,t)=>chn(s,"name",{value:t,configurable:!0}),n9e,Brt="HoverCard",[PWt,$Sr]=tp(Brt,[i3]),$rt=i3(),[dhn,Urt]=PWt(Brt),uhn=OL(s=>{const{__scopeHoverCard:t,children:n,open:r,defaultOpen:a,onOpenChange:i,openDelay:l=700,closeDelay:o=300}=s,c=$rt(t),d=j.useRef(0),u=j.useRef(0),h=j.useRef(!1),m=j.useRef(!1),[f,g]=fy({prop:r,defaultProp:a??!1,onChange:i,caller:Brt}),x=j.useCallback(()=>{clearTimeout(u.current),d.current=window.setTimeout(()=>g(!0),l)},[l,g]),y=j.useCallback(()=>{clearTimeout(d.current),!h.current&&!m.current&&(u.current=window.setTimeout(()=>g(!1),o))},[o,g]),v=j.useCallback(()=>g(!1),[g]);return j.useEffect(()=>()=>{clearTimeout(d.current),clearTimeout(u.current)},[]),e.jsx(dhn,{scope:t,open:f,onOpenChange:g,onOpen:x,onClose:y,onDismiss:v,hasSelectionRef:h,isPointerDownOnContentRef:m,children:e.jsx(Cae,{...c,children:n})})},"HoverCard"),hhn="HoverCardTrigger",mhn=j.forwardRef(OL(function(t,n){const{__scopeHoverCard:r,...a}=t,i=Urt(hhn,r),l=$rt(r);return e.jsx(Aae,{asChild:!0,...l,children:e.jsx(Ei.a,{"data-state":i.open?"open":"closed",...a,ref:n,onPointerEnter:Ra(t.onPointerEnter,Ise(i.onOpen)),onPointerLeave:Ra(t.onPointerLeave,Ise(i.onClose)),onFocus:Ra(t.onFocus,i.onOpen),onBlur:Ra(t.onBlur,i.onClose),onTouchStart:Ra(t.onTouchStart,o=>o.preventDefault())})})},"HoverCardTrigger")),fhn="HoverCardPortal",[USr,phn]=PWt(fhn,{forceMount:void 0}),WWe="HoverCardContent",ghn=j.forwardRef(OL(function(t,n){const r=phn(WWe,t.__scopeHoverCard),{forceMount:a=r.forceMount,...i}=t,l=Urt(WWe,t.__scopeHoverCard);return e.jsx(xy,{present:a||l.open,children:e.jsx(xhn,{"data-state":l.open?"open":"closed",...i,onPointerEnter:Ra(t.onPointerEnter,Ise(l.onOpen)),onPointerLeave:Ra(t.onPointerLeave,Ise(l.onClose)),ref:n})})},"HoverCardContent")),xhn=j.forwardRef(OL(function(t,n){const{__scopeHoverCard:r,onEscapeKeyDown:a,onPointerDownOutside:i,onFocusOutside:l,onInteractOutside:o,...c}=t,d=Urt(WWe,r),u=$rt(r),h=j.useRef(null),m=Vo(n,h),[f,g]=j.useState(!1);return j.useEffect(()=>{if(f){const x=document.body;return n9e=x.style.userSelect||x.style.webkitUserSelect,x.style.userSelect="none",x.style.webkitUserSelect="none",()=>{x.style.userSelect=n9e,x.style.webkitUserSelect=n9e}}},[f]),j.useEffect(()=>{if(h.current){const x=OL(()=>{g(!1),d.isPointerDownOnContentRef.current=!1,setTimeout(()=>{var v;((v=document.getSelection())==null?void 0:v.toString())!==""&&(d.hasSelectionRef.current=!0)})},"handlePointerUp");return document.addEventListener("pointerup",x),()=>{document.removeEventListener("pointerup",x),d.hasSelectionRef.current=!1,d.isPointerDownOnContentRef.current=!1}}},[d.isPointerDownOnContentRef,d.hasSelectionRef]),j.useEffect(()=>{h.current&&IWt(h.current).forEach(y=>y.setAttribute("tabindex","-1"))}),e.jsx(RB,{asChild:!0,disableOutsidePointerEvents:!1,onInteractOutside:o,onEscapeKeyDown:a,onPointerDownOutside:i,onFocusOutside:Ra(l,x=>{x.preventDefault()}),onDismiss:d.onDismiss,children:e.jsx(Eae,{...u,...c,onPointerDown:Ra(c.onPointerDown,x=>{x.currentTarget.contains(x.target)&&g(!0),d.hasSelectionRef.current=!1,d.isPointerDownOnContentRef.current=!0}),ref:m,style:{...c.style,userSelect:f?"text":void 0,WebkitUserSelect:f?"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)"}})})},"HoverCardContentImpl"));function Ise(s){return t=>t.pointerType==="touch"?void 0:s()}OL(Ise,"excludeTouch");function IWt(s){const t=[],n=document.createTreeWalker(s,NodeFilter.SHOW_ELEMENT,{acceptNode:OL(r=>r.tabIndex>=0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP,"acceptNode")});for(;n.nextNode();)t.push(n.currentNode);return t}OL(IWt,"getTabbableNodes");var yhn=uhn,vhn=mhn,LWt=ghn;const bhn=yhn,_hn=vhn,RWt=j.forwardRef(({className:s,align:t="center",sideOffset:n=4,...r},a)=>e.jsx(LWt,{ref:a,align:t,sideOffset:n,className:Pt("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),...r}));RWt.displayName=LWt.displayName;const whn=[{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"}],jhn=s=>s.split(" ").map(t=>t[0]).join("").toUpperCase().slice(0,2),DWt=({reactions:s,children:t})=>{if(s.length===0)return e.jsx(e.Fragment,{children:t});const n={};return s.forEach(r=>{n[r.reaction_type]||(n[r.reaction_type]=[]),n[r.reaction_type].push(r)}),e.jsxs(bhn,{openDelay:200,closeDelay:100,children:[e.jsx(_hn,{asChild:!0,children:e.jsx("div",{className:"cursor-pointer",children:t})}),e.jsx(RWt,{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(n).map(([r,a])=>{const i=whn.find(l=>l.type===r);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(Oa,{className:"h-6 w-6",children:[e.jsx(Li,{src:l.user_avatar||void 0}),e.jsx(za,{className:"text-[10px]",children:jhn(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"]})]})]},r)})})})]})};function Nhn({images:s,initialIndex:t=0,open:n,onOpenChange:r}){const[a,i]=j.useState(t),[l,o]=j.useState(!1);j.useEffect(()=>{n&&(i(t),o(!1))},[n,t]);const c=()=>{i(m=>m>0?m-1:s.length-1),o(!1)},d=()=>{i(m=>m{n&&(m.key==="ArrowLeft"&&c(),m.key==="ArrowRight"&&d(),m.key==="Escape"&&r(!1))},[n,s.length]);j.useEffect(()=>(window.addEventListener("keydown",u),()=>window.removeEventListener("keydown",u)),[u]);const h=s[a];return e.jsx(zs,{open:n,onOpenChange:r,children:e.jsxs(Os,{className:"max-w-[95vw] max-h-[95vh] w-auto h-auto p-0 border-none bg-black/95 overflow-hidden",children:[e.jsx($,{variant:"ghost",size:"icon",className:"absolute top-2 right-2 z-50 text-white hover:bg-white/20 h-10 w-10",onClick:()=>r(!1),children:e.jsx(gr,{className:"h-6 w-6"})}),s.length>1&&e.jsxs(e.Fragment,{children:[e.jsx($,{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(Cd,{className:"h-8 w-8"})}),e.jsx($,{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(Di,{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]}),(h==null?void 0:h.type)==="image"&&e.jsx($,{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(yV,{className:"h-5 w-5"}):e.jsx(nL,{className:"h-5 w-5"})}),e.jsx("div",{className:Pt("flex items-center justify-center w-full h-full min-h-[50vh] p-4",l?"cursor-zoom-out overflow-auto":"cursor-zoom-in"),onClick:()=>(h==null?void 0:h.type)==="image"&&o(!l),children:(h==null?void 0:h.type)==="video"?e.jsx("video",{src:h.url,controls:!0,autoPlay:!0,className:"max-w-full max-h-[85vh] object-contain",onClick:m=>m.stopPropagation()}):e.jsx("img",{src:h==null?void 0:h.url,alt:"",className:Pt("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((m,f)=>e.jsx("button",{onClick:()=>{i(f),o(!1)},className:Pt("w-12 h-12 rounded overflow-hidden flex-shrink-0 border-2 transition-all",a===f?"border-white":"border-transparent opacity-60 hover:opacity-100"),children:m.type==="video"?e.jsx("video",{src:m.url,className:"w-full h-full object-cover"}):e.jsx("img",{src:m.url,alt:"",className:"w-full h-full object-cover"})},f))})]})})}const zde=[{type:"like",emoji:"👍",label:"Like"},{type:"love",emoji:"❤️",label:"Love"}],khn=({commentId:s,reactions:t,currentUserId:n})=>{var d,u;const r=Vt(),[a,i]=j.useState(!1),l=t.find(h=>h.user_id===n),o=ft({mutationFn:async h=>{l?l.reaction_type===h?await q.from("community_comment_reactions").delete().eq("id",l.id):await q.from("community_comment_reactions").update({reaction_type:h}).eq("id",l.id):await q.from("community_comment_reactions").insert({comment_id:s,user_id:n,reaction_type:h})},onSuccess:()=>{r.invalidateQueries({queryKey:["community-posts"]}),i(!1)}}),c={};return t.forEach(h=>{c[h.reaction_type]=(c[h.reaction_type]||0)+1}),e.jsxs("div",{className:"flex items-center gap-2",children:[t.length>0&&e.jsx(DWt,{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(h=>{var m;return e.jsx("span",{className:"text-sm",children:(m=zde.find(f=>f.type===h))==null?void 0:m.emoji},h)})}),e.jsx("span",{children:t.length})]})}),n&&e.jsxs(Yd,{open:a,onOpenChange:i,children:[e.jsx(Zd,{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=zde.find(h=>h.type===l.reaction_type))==null?void 0:d.emoji," ",(u=zde.find(h=>h.type===l.reaction_type))==null?void 0:u.label]}):e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Jo,{className:"h-3 w-3"}),"Like"]})})}),e.jsx(Bd,{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:zde.map(h=>e.jsx("button",{onClick:()=>o.mutate(h.type),className:"text-xl hover:scale-125 transition-transform p-1",title:h.label,children:h.emoji},h.type))})})]})]})};function qrt({content:s,className:t}){const n=/([@#])\[([^\]]+)\]\(([^)]+)\)|(https?:\/\/[^\s<>]+)/g,r=[];let a=0,i,l=0;for(;(i=n.exec(s))!==null;){if(i.index>a&&r.push(s.substring(a,i.index)),i[1]){const o=i[1],c=i[2],d=i[3],u=o==="#";r.push(e.jsx(wr,{to:u?`/templates/${d}`:`/profile?user=${d}`,className:Pt("font-medium hover:underline",u?"text-white bg-[#2a4c64] px-1.5 py-0.5 rounded":"text-primary"),onClick:h=>h.stopPropagation(),children:u?c:`@${c}`},`mention-${l++}`))}else if(i[4]){const o=i[4],c=o.replace(/[.,;:!?)]+$/,""),d=o.slice(c.length);let u;try{const h=new URL(c);u=h.hostname+(h.pathname!=="/"?h.pathname.slice(0,20)+(h.pathname.length>20?"...":""):"")}catch{u=c.length>40?c.slice(0,40)+"...":c}r.push(e.jsx("a",{href:c,target:"_blank",rel:"noopener noreferrer",className:"text-primary hover:underline break-all",onClick:h=>h.stopPropagation(),children:u},`url-${l++}`)),d&&r.push(d)}a=i.index+i[0].length}return ae.jsx(j.Fragment,{children:o},c))})}function HTe({value:s,onChange:t,placeholder:n="What's on your mind? Use @ to mention someone",className:r,minHeight:a="80px",onMentionsChange:i,onTemplatesChange:l,onKeyDown:o,mentionFormat:c="encoded",enableTemplateMentions:d=!1}){const u=j.useRef(null),h=j.useRef(null),[m,f]=j.useState(!1),[g,x]=j.useState("user"),[y,v]=j.useState(""),[b,w]=j.useState(null),[S,C]=j.useState(0),[E,I]=j.useState({top:0,left:0,width:0}),P=j.useRef(new Map),R=j.useRef(new Map),D=J=>{if(c==="plain"){const ue=[];return P.current.forEach((Ee,Se)=>{J.includes(`@${Se}`)&&ue.push(Ee)}),[...new Set(ue)]}const ce=/@\[([^\]]+)\]\(([^)]+)\)/g,_e=[];let he;for(;(he=ce.exec(J))!==null;)_e.push(he[2]);return[...new Set(_e)]},O=J=>{if(c==="plain"){const ue=[];return R.current.forEach((Ee,Se)=>{J.includes(`#${Se}`)&&ue.push(Ee)}),[...new Set(ue)]}const ce=/#\[([^\]]+)\]\(([^)]+)\)/g,_e=[];let he;for(;(he=ce.exec(J))!==null;)_e.push(he[2]);return[...new Set(_e)]};j.useEffect(()=>{if(i){const J=D(s);i(J)}if(l){const J=O(s);l(J)}},[s,i,l,c]);const{data:U=[],isLoading:W}=tt({queryKey:["mention-users",y],queryFn:async()=>{const J=q.from("profiles").select("id, name").limit(8),ce=y.length>=1?J.ilike("name",`%${y}%`):J.order("name"),{data:_e,error:he}=await ce;if(he)throw he;const ue=_e.map(Ee=>Ee.id),ve=await UOt(ue);return _e.map(Ee=>({id:Ee.id,name:Ee.name||"Unknown",avatar_url:ve.get(Ee.id)}))},enabled:m&&g==="user",staleTime:3e4}),{data:V=[],isLoading:G}=tt({queryKey:["mention-templates",y],queryFn:async()=>{let J=q.from("canva_templates").select("id, name, preview_image_url").lte("publish_date",new Date().toISOString()).order("publish_date",{ascending:!1}).limit(8);y.length>=1&&(J=J.ilike("name",`%${y}%`));const{data:ce,error:_e}=await J;if(_e)throw _e;return ce||[]},enabled:m&&g==="template"&&d,staleTime:3e4}),Y=g==="user"?W:G,X=g==="user"?U:V,ae=J=>J.split(" ").map(ce=>ce[0]).join("").toUpperCase().slice(0,2),ie=J=>{const ce=J.target.value,_e=J.target.selectionStart;t(ce);const he=ce.substring(0,_e),ue=he.lastIndexOf("@"),ve=d?he.lastIndexOf("#"):-1;let Ee=-1,Se="user";if(ue>ve?(Ee=ue,Se="user"):ve>ue&&d&&(Ee=ve,Se="template"),Ee!==-1){const Le=he.substring(Ee+1),Fe=Le.includes(" "),ke=Le.includes(` `);if(!Fe&&!ke&&Le.length<=30){w(Ee),v(Le),x(Se),f(!0),C(0);return}}f(!1),w(null)},ne=J=>{if(b===null)return;const ce=s.substring(0,b),_e=s.substring(b+y.length+1),he=g==="user"?"@":"#",ue=c==="plain"?`${he}${J.name} `:`${he}[${J.name}](${J.id}) `;c==="plain"&&(g==="user"?P.current.set(J.name,J.id):R.current.set(J.name,J.id));const ve=ce+ue+_e;t(ve),f(!1),w(null),v(""),setTimeout(()=>{if(u.current){const Ee=ce.length+ue.length;u.current.focus(),u.current.setSelectionRange(Ee,Ee)}},0)},te=J=>{if(!(!m||X.length===0))switch(J.key){case"ArrowDown":J.preventDefault(),C(ce=>(ce+1)%X.length);break;case"ArrowUp":J.preventDefault(),C(ce=>(ce-1+X.length)%X.length);break;case"Enter":X[S]&&(J.preventDefault(),ne(X[S]));break;case"Escape":J.preventDefault(),f(!1);break;case"Tab":X[S]&&(J.preventDefault(),ne(X[S]));break}};return j.useEffect(()=>{const J=ce=>{h.current&&!h.current.contains(ce.target)&&u.current&&!u.current.contains(ce.target)&&f(!1)};return document.addEventListener("mousedown",J),()=>document.removeEventListener("mousedown",J)},[]),j.useEffect(()=>{if(!m)return;const J=()=>{const ce=u.current;if(!ce)return;const _e=ce.getBoundingClientRect();I({top:_e.bottom+4,left:_e.left,width:_e.width})};return J(),window.addEventListener("resize",J),window.addEventListener("scroll",J,!0),()=>{window.removeEventListener("resize",J),window.removeEventListener("scroll",J,!0)}},[m,s]),e.jsxs("div",{className:"relative flex-1",children:[e.jsx(Rs,{ref:u,value:s,onChange:ie,onKeyDown:J=>{te(J),J.defaultPrevented||o==null||o(J)},placeholder:n,className:Pt("resize-none",r),style:{minHeight:a}}),m&&wv.createPortal(e.jsxs("div",{ref:h,className:"fixed z-[1000] max-h-[220px] overflow-hidden rounded-lg border bg-popover shadow-lg",style:{top:E.top,left:E.left,width:E.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:g==="user"?"👤 Mention a person":"📋 Link a template"}),Y?e.jsx("div",{className:"px-3 py-2 text-sm text-muted-foreground",children:"Searching..."}):X.length===0?e.jsx("div",{className:"px-3 py-2 text-sm text-muted-foreground",children:y.length<1?`Type to search ${g==="user"?"people":"templates"}...`:`No ${g==="user"?"users":"templates"} found`}):e.jsx("ul",{className:"py-1 max-h-[180px] overflow-y-auto",children:X.map((J,ce)=>e.jsx("li",{className:Pt("flex items-center gap-2 px-3 py-2 cursor-pointer transition-colors",ce===S?"bg-accent":"hover:bg-accent/50"),onClick:()=>ne(J),onMouseEnter:()=>C(ce),children:g==="user"?e.jsxs(e.Fragment,{children:[e.jsxs(Oa,{className:"h-6 w-6",children:[e.jsx(Li,{src:J.avatar_url}),e.jsx(za,{className:"text-xs",children:ae(J.name)})]}),e.jsx("span",{className:"text-sm font-medium truncate",children:J.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:J.preview_image_url?e.jsx("img",{src:J.preview_image_url,alt:"",className:"w-full h-full object-cover"}):e.jsx(Yc,{className:"h-4 w-4 text-muted-foreground"})}),e.jsx("span",{className:"text-sm font-medium truncate",children:J.name})]})},J.id))})]}),document.body)]})}function Shn(s){const t=/#\[([^\]]+)\]\(([^)]+)\)/g,n=[];let r;for(;(r=t.exec(s))!==null;)n.push(r[2]);return[...new Set(n)]}const Fwt=s=>s.split(" ").map(t=>t[0]).join("").toUpperCase().slice(0,2);function FWt({comment:s,postId:t,currentUserId:n,currentUserAvatar:r,currentUserEmail:a,canModerate:i,depth:l=0}){const o=Vt(),[c,d]=j.useState(!1),[u,h]=j.useState(""),[m,f]=j.useState([]),g=ft({mutationFn:async({content:b,parentCommentId:w})=>{const{data:S,error:C}=await q.from("community_comments").insert({post_id:t,user_id:n,content:b,parent_comment_id:w}).select("id").single();if(C)throw C;const E=m;if(E.length>0&&S){const I=E.filter(P=>P!==n).map(P=>({comment_id:S.id,mentioned_user_id:P,mentioned_by_user_id:n}));I.length>0&&await q.from("community_comment_mentions").insert(I)}},onSuccess:()=>{o.invalidateQueries({queryKey:["community-posts"]}),h(""),f([]),d(!1)}}),x=ft({mutationFn:async b=>{const{error:w}=await q.from("community_comments").delete().eq("id",b);if(w)throw w},onSuccess:()=>o.invalidateQueries({queryKey:["community-posts"]})}),y=()=>{u.trim()&&g.mutate({content:u,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(Oa,{className:"h-8 w-8 shrink-0",children:[e.jsx(Li,{src:s.user_avatar||void 0}),e.jsx(za,{className:"text-xs",children:Fwt(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(qrt,{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:mu(new Date(s.created_at),{addSuffix:!0})}),e.jsx(khn,{commentId:s.id,reactions:s.reactions,currentUserId:n}),n&&l<2&&e.jsxs("button",{onClick:()=>d(!c),className:"hover:text-primary flex items-center gap-1",children:[e.jsx(tV,{className:"h-3 w-3"}),"Reply"]}),(s.user_id===n||i)&&e.jsx("button",{onClick:()=>x.mutate(s.id),className:"hover:text-destructive",children:s.user_id!==n?"Remove":"Delete"})]}),c&&n&&e.jsxs("div",{className:"flex gap-2 mt-2",children:[e.jsxs(Oa,{className:"h-6 w-6 shrink-0 mt-1",children:[e.jsx(Li,{src:r||void 0}),e.jsx(za,{className:"text-xs",children:Fwt((a==null?void 0:a.split("@")[0])||"U")})]}),e.jsxs("div",{className:"flex-1 flex gap-2 items-start",children:[e.jsx(HTe,{placeholder:`Reply to ${s.user_name}...`,value:u,onChange:h,onMentionsChange:f,mentionFormat:"plain",className:"text-sm min-h-0 py-1.5",minHeight:"32px"}),e.jsx($,{size:"sm",variant:"ghost",onClick:y,disabled:!u.trim()||g.isPending,className:"h-8 px-2 mt-0.5",children:e.jsx(Yr,{className:"h-3 w-3"})})]})]})]})]}),s.replies&&s.replies.length>0&&e.jsx("div",{className:"mt-2 space-y-2",children:s.replies.map(b=>e.jsx(FWt,{comment:b,postId:t,currentUserId:n,currentUserAvatar:r,currentUserEmail:a,canModerate:i,depth:l+1},b.id))})]})}const Bde=[{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"}],Chn=()=>{const{user:s,isBrokerageManager:t,managedBrokerages:n,isAdmin:r}=vs(),{avatarUrl:a}=$Ot(s==null?void 0:s.id),{onlineUsers:i}=ZFt(),{toast:l}=Bi(),o=Vt(),c=j.useRef(null),[d,u]=j.useState("all"),[h,m]=j.useState(""),[f,g]=j.useState(""),[x,y]=j.useState(""),[v,b]=j.useState([]),[w,S]=j.useState([]),[C,E]=j.useState(""),[I,P]=j.useState(!1),[R,D]=j.useState(null),[O,U]=j.useState(""),[W,V]=j.useState(new Set),[G,Y]=j.useState({}),[X,ae]=j.useState({}),[ie,ne]=j.useState([]),[te,J]=j.useState([]),[ce,_e]=j.useState({open:!1,images:[],index:0});j.useEffect(()=>{if(d.startsWith("group:")){const rt=d.replace("group:","");y(rt),g("")}else d!=="all"?(g(d),y("")):(g(""),y(""))},[d]);const{data:he=[]}=tt({queryKey:["community-categories"],queryFn:async()=>{const{data:rt,error:Yt}=await q.from("community_categories").select("*").order("sort_order");if(Yt)throw Yt;return rt}}),{data:ue=[]}=tt({queryKey:["community-private-groups"],queryFn:async()=>{const{data:rt,error:Yt}=await q.from("community_private_groups").select("id, name, description, icon, brokerage_id, sort_order").order("sort_order");if(Yt)throw Yt;return rt}}),ve=20,{data:Ee,isLoading:Se,hasNextPage:Le,fetchNextPage:Fe,isFetchingNextPage:ke}=rFt({queryKey:["community-posts",d],initialPageParam:0,queryFn:async({pageParam:rt})=>{var Jn;const Yt=rt*ve,qt=Yt+ve;let ts=q.from("community_posts").select("*").order("is_pinned",{ascending:!1}).order("pinned_at",{ascending:!1,nullsFirst:!1}).order("created_at",{ascending:!1}).range(Yt,qt);if(d.startsWith("group:")){const Sr=d.replace("group:","");ts=ts.eq("private_group_id",Sr)}else d==="all"||(ts=ts.eq("category_id",d).is("private_group_id",null));const{data:ys,error:Bt}=await ts;if(Bt)throw Bt;const Ft=((ys==null?void 0:ys.length)||0)>ve,rs=(ys||[]).slice(0,ve);if(rs.length===0)return{posts:[],hasMore:!1,nextPage:rt+1};const St=rs.map(Sr=>Sr.id),Xs=[...new Set(rs.filter(Sr=>Sr.category_id).map(Sr=>Sr.category_id))].filter(Boolean),[vt,gs,Ss,Is,Ys]=await Promise.all([Xs.length?q.from("community_categories").select("*").in("id",Xs):Promise.resolve({data:[]}),q.from("community_post_media").select("*").in("post_id",St).order("sort_order"),q.from("community_reactions").select("*").in("post_id",St),q.from("community_comments").select("*").in("post_id",St).order("created_at",{ascending:!0}),q.from("community_post_resources").select("*").in("post_id",St)]),cs=vt==null?void 0:vt.data,js=gs==null?void 0:gs.data,kn=Ss==null?void 0:Ss.data,Ws=Is==null?void 0:Is.data,On=Ys==null?void 0:Ys.data,ds=(Ws||[]).map(Sr=>Sr.id),[gn,As]=await Promise.all([ds.length?q.from("community_comment_reactions").select("*").in("comment_id",ds):Promise.resolve({data:[]}),(()=>{const Sr=(On||[]).filter(Un=>Un.resource_type==="template").map(Un=>Un.resource_id);return Sr.length===0?Promise.resolve({data:[]}):q.from("canva_templates").select("id, name, preview_image_url").in("id",Sr)})()]),hr=(gn==null?void 0:gn.data)||[],Er=(As==null?void 0:As.data)||[],qn=new Map(Er.map(Sr=>[Sr.id,{name:Sr.name,preview_image_url:Sr.preview_image_url}])),hn=Array.from(new Set([...rs.map(Sr=>Sr.user_id),...(kn||[]).map(Sr=>Sr.user_id),...(Ws||[]).map(Sr=>Sr.user_id),...hr.map(Sr=>Sr.user_id)])),[Fn,vn]=await Promise.all([hn.length?q.from("profiles").select("id, name").in("id",hn):Promise.resolve({data:[]}),UOt(hn)]),xs=new Map(((Jn=Fn==null?void 0:Fn.data)==null?void 0:Jn.map(Sr=>[Sr.id,Sr.name]))||[]),Lr=new Map((cs||[]).map(Sr=>[Sr.id,Sr])),Or=Sr=>{const Un=new Map,ur=[];return Sr.forEach(Pa=>{Un.set(Pa.id,{...Pa,user_name:xs.get(Pa.user_id)||"Unknown User",user_avatar:vn.get(Pa.user_id),reactions:hr.filter(ii=>ii.comment_id===Pa.id).map(ii=>({...ii,user_name:xs.get(ii.user_id)||"Unknown User",user_avatar:vn.get(ii.user_id)})),replies:[]})}),Sr.forEach(Pa=>{const ii=Un.get(Pa.id);if(Pa.parent_comment_id&&Un.has(Pa.parent_comment_id)){const $i=Un.get(Pa.parent_comment_id);$i.replies=$i.replies||[],$i.replies.push(ii)}else ur.push(ii)}),ur};return{posts:rs.map(Sr=>{const Un=(On||[]).filter(ur=>ur.post_id===Sr.id).map(ur=>{let Pa="",ii=null;if(ur.resource_type==="template"){const $i=qn.get(ur.resource_id);Pa=($i==null?void 0:$i.name)||"Unknown Template",ii=($i==null?void 0:$i.preview_image_url)||null}return{id:ur.id,resource_type:ur.resource_type,resource_id:ur.resource_id,resource_name:Pa,resource_preview_url:ii}});return{...Sr,user_name:xs.get(Sr.user_id)||"Unknown User",user_avatar:vn.get(Sr.user_id),category:Sr.category_id?Lr.get(Sr.category_id):null,media:(js||[]).filter(ur=>ur.post_id===Sr.id),reactions:((kn||[]).filter(ur=>ur.post_id===Sr.id)||[]).map(ur=>({...ur,user_name:xs.get(ur.user_id)||"Unknown User",user_avatar:vn.get(ur.user_id)})),comments:Or((Ws||[]).filter(ur=>ur.post_id===Sr.id)),resources:Un}}),hasMore:Ft,nextPage:rt+1}},getNextPageParam:rt=>rt.hasMore?rt.nextPage:void 0}),Ve=j.useMemo(()=>(Ee==null?void 0:Ee.pages.flatMap(rt=>rt.posts))??[],[Ee]),je=ft({mutationFn:async()=>{P(!0);const{data:rt,error:Yt}=await q.from("community_posts").insert({user_id:s.id,category_id:x?null:f||null,private_group_id:x||null,content:h,link_url:C||null}).select().single();if(Yt)throw Yt;for(let ts=0;ts0){const ts=ie.filter(ys=>ys!==s.id).map(ys=>({post_id:rt.id,mentioned_user_id:ys,mentioned_by_user_id:s.id}));ts.length>0&&await q.from("community_post_mentions").insert(ts)}const qt=Shn(h);if(qt.length>0){const ts=qt.map(ys=>({post_id:rt.id,resource_type:"template",resource_id:ys}));await q.from("community_post_resources").insert(ts)}return rt},onSuccess:async rt=>{var Yt;o.invalidateQueries({queryKey:["community-posts"]}),m(""),ne([]),J([]),g(""),y(""),b([]),S([]),E(""),l({title:"Post created!"});try{const qt=((Yt=s==null?void 0:s.user_metadata)==null?void 0:Yt.name)||"Someone",ts=h.replace(/@\[([^\]]+)\]\([^)]+\)/g,"@$1"),ys=ts.length>50?ts.substring(0,50)+"...":ts;await q.functions.invoke("send-push-notification",{body:{title:"New Community Post",body:`${qt}: ${ys}`,url:"/community"}})}catch(qt){console.error("Failed to send push notification:",qt)}},onError:rt=>{l({title:"Error creating post",description:rt.message,variant:"destructive"})},onSettled:()=>P(!1)}),Ae=ft({mutationFn:async({postId:rt,content:Yt})=>{const{error:qt}=await q.from("community_posts").update({content:Yt}).eq("id",rt);if(qt)throw qt},onSuccess:()=>{o.invalidateQueries({queryKey:["community-posts"]}),D(null),U(""),l({title:"Post updated!"})}}),Ce=ft({mutationFn:async rt=>{const{error:Yt}=await q.from("community_posts").delete().eq("id",rt);if(Yt)throw Yt},onSuccess:()=>{o.invalidateQueries({queryKey:["community-posts"]}),l({title:"Post deleted"})}}),qe=ft({mutationFn:async({postId:rt,isPinned:Yt})=>{const{error:qt}=await q.from("community_posts").update({is_pinned:!Yt,pinned_at:Yt?null:new Date().toISOString(),pinned_by:Yt?null:s==null?void 0:s.id}).eq("id",rt);if(qt)throw qt},onSuccess:(rt,{isPinned:Yt})=>{o.invalidateQueries({queryKey:["community-posts"]}),l({title:Yt?"Post unpinned":"Post pinned to top"})}}),ze=ft({mutationFn:async({postId:rt,reactionType:Yt})=>{var ts;const qt=(ts=Ve.find(ys=>ys.id===rt))==null?void 0:ts.reactions.find(ys=>ys.user_id===(s==null?void 0:s.id));qt?qt.reaction_type===Yt?await q.from("community_reactions").delete().eq("id",qt.id):await q.from("community_reactions").update({reaction_type:Yt}).eq("id",qt.id):await q.from("community_reactions").insert({post_id:rt,user_id:s.id,reaction_type:Yt})},onSuccess:()=>o.invalidateQueries({queryKey:["community-posts"]})}),$e=ft({mutationFn:async({postId:rt,content:Yt})=>{const{data:qt,error:ts}=await q.from("community_comments").insert({post_id:rt,user_id:s.id,content:Yt}).select("id").single();if(ts)throw ts;const ys=X[rt]||[];if(ys.length>0&&qt){const Bt=ys.filter(Ft=>Ft!==s.id).map(Ft=>({comment_id:qt.id,mentioned_user_id:Ft,mentioned_by_user_id:s.id}));Bt.length>0&&await q.from("community_comment_mentions").insert(Bt)}},onSuccess:(rt,{postId:Yt})=>{o.invalidateQueries({queryKey:["community-posts"]}),Y(qt=>({...qt,[Yt]:""})),ae(qt=>({...qt,[Yt]:[]}))}});ft({mutationFn:async rt=>{const{error:Yt}=await q.from("community_comments").delete().eq("id",rt);if(Yt)throw Yt},onSuccess:()=>o.invalidateQueries({queryKey:["community-posts"]})});const ct=rt=>{const Yt=Array.from(rt.target.files||[]);if(Yt.length+v.length>10){l({title:"Maximum 10 files allowed",variant:"destructive"});return}b(qt=>[...qt,...Yt]),Yt.forEach(qt=>{const ts=new FileReader;ts.onloadend=()=>{S(ys=>[...ys,ts.result])},ts.readAsDataURL(qt)})},Xe=rt=>{b(Yt=>Yt.filter((qt,ts)=>ts!==rt)),S(Yt=>Yt.filter((qt,ts)=>ts!==rt))},it=rt=>rt.split(" ").map(Yt=>Yt[0]).join("").toUpperCase().slice(0,2),at=rt=>{const Yt={};return rt.forEach(qt=>{Yt[qt.reaction_type]=(Yt[qt.reaction_type]||0)+1}),Yt},Ke=rt=>{var Yt;return(Yt=rt.find(qt=>qt.user_id===(s==null?void 0:s.id)))==null?void 0:Yt.reaction_type},nt=rt=>rt.reduce((Yt,qt)=>Yt+1+(qt.replies?nt(qt.replies):0),0),xt=rt=>{if(r)return!0;if(!t||!rt.private_group_id)return!1;const Yt=ue.find(qt=>qt.id===rt.private_group_id);return Yt!=null&&Yt.brokerage_id?n.some(qt=>qt.id===Yt.brokerage_id):!1};return e.jsx(Vs,{title:"Community",children:e.jsxs("div",{className:"flex gap-6 w-full isolate z-0",children:[e.jsx(ohn,{categories:he,privateGroups:ue,selectedFilter:d,onFilterChange:u,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(lhn,{categories:he,privateGroups:ue,selectedFilter:d,onFilterChange:u,onlineUsers:i}),e.jsx(Ne,{children:e.jsx(Ie,{className:"pt-6",children:e.jsxs("div",{className:"flex gap-3",children:[e.jsxs(Oa,{className:"h-10 w-10",children:[e.jsx(Li,{src:a||void 0}),e.jsx(za,{children:s!=null&&s.email?it(s.email.split("@")[0]):"U"})]}),e.jsxs("div",{className:"flex-1 space-y-3",children:[e.jsx(HTe,{placeholder:r?"What's on your mind? Use @ to mention someone, # to link a template":"What's on your mind? Use @ to mention someone",value:h,onChange:m,onMentionsChange:ne,onTemplatesChange:J,mentionFormat:"encoded",minHeight:"80px",enableTemplateMentions:r}),w.length>0&&e.jsx("div",{className:"grid grid-cols-3 gap-2",children:w.map((rt,Yt)=>{var qt;return e.jsxs("div",{className:"relative aspect-square rounded-lg overflow-hidden bg-muted",children:[(qt=v[Yt])!=null&&qt.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($,{variant:"destructive",size:"icon",className:"absolute top-1 right-1 h-6 w-6",onClick:()=>Xe(Yt),children:e.jsx(gr,{className:"h-3 w-3"})})]},Yt)})}),C&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ad,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(pe,{value:C,onChange:rt=>E(rt.target.value),placeholder:"https://...",className:"flex-1"}),e.jsx($,{variant:"ghost",size:"icon",onClick:()=>E(""),children:e.jsx(gr,{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:ct,accept:"image/*,video/*",multiple:!0,className:"hidden"}),e.jsxs($,{variant:"ghost",size:"sm",onClick:()=>{var rt;return(rt=c.current)==null?void 0:rt.click()},children:[e.jsx(Mc,{className:"h-4 w-4 mr-1"}),"Photo"]}),e.jsxs($,{variant:"ghost",size:"sm",onClick:()=>{var rt;return(rt=c.current)==null?void 0:rt.click()},children:[e.jsx(ua,{className:"h-4 w-4 mr-1"}),"Video"]}),e.jsxs($,{variant:"ghost",size:"sm",onClick:()=>E("https://"),children:[e.jsx(Ad,{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:[ue.length>0?e.jsxs(ms,{value:x||f||"none",onValueChange:rt=>{rt==="none"?(g(""),y("")):rt.startsWith("group:")?(y(rt.replace("group:","")),g("")):(g(rt),y(""))},children:[e.jsx(us,{className:"w-[130px] sm:w-[160px] h-8 text-xs sm:text-sm",children:e.jsx(fs,{placeholder:"Select..."})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"none",children:"No category"}),he.map(rt=>e.jsxs(Ge,{value:rt.id,children:[rt.icon," ",rt.name]},rt.id)),ue.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"}),ue.map(rt=>e.jsxs(Ge,{value:`group:${rt.id}`,children:[rt.icon||"🔒"," ",rt.name]},rt.id))]})]})]}):e.jsxs(ms,{value:f,onValueChange:g,children:[e.jsx(us,{className:"w-[110px] sm:w-[140px] h-8 text-xs sm:text-sm",children:e.jsx(fs,{placeholder:"Category"})}),e.jsx(hs,{children:he.map(rt=>e.jsxs(Ge,{value:rt.id,children:[rt.icon," ",rt.name]},rt.id))})]}),e.jsxs($,{size:"sm",onClick:()=>je.mutate(),disabled:!h.trim()||I,children:[e.jsx(Yr,{className:"h-4 w-4 mr-1"}),"Post"]})]})]})]})]})})}),Se?e.jsx("div",{className:"space-y-4",children:[...Array(3)].map((rt,Yt)=>e.jsx(Ne,{children:e.jsx(Ie,{className:"pt-6",children:e.jsxs("div",{className:"flex gap-3",children:[e.jsx(yn,{className:"h-10 w-10 rounded-full"}),e.jsxs("div",{className:"flex-1 space-y-2",children:[e.jsx(yn,{className:"h-4 w-32"}),e.jsx(yn,{className:"h-4 w-full"}),e.jsx(yn,{className:"h-4 w-3/4"})]})]})})},Yt))}):Ve.length===0?e.jsx(Ne,{children:e.jsxs(Ie,{className:"py-12 text-center",children:[e.jsx(Th,{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:[Ve.map(rt=>{var Yt,qt,ts,ys;return e.jsx(Ne,{children:e.jsxs(Ie,{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(Oa,{className:"h-10 w-10",children:[e.jsx(Li,{src:rt.user_avatar||void 0}),e.jsx(za,{children:it(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:mu(new Date(rt.created_at),{addSuffix:!0})}),rt.category&&e.jsxs(e.Fragment,{children:[e.jsx("span",{children:"•"}),e.jsxs(Be,{variant:"secondary",className:"text-xs",children:[rt.category.icon," ",rt.category.name]})]})]})]})]}),(rt.user_id===(s==null?void 0:s.id)||xt(rt))&&e.jsxs(Uu,{children:[e.jsx(qu,{asChild:!0,children:e.jsx($,{variant:"ghost",size:"icon",className:"h-8 w-8",children:e.jsx(h_,{className:"h-4 w-4"})})}),e.jsxs(Eu,{align:"end",children:[xt(rt)&&rt.private_group_id&&e.jsx(ja,{onClick:()=>qe.mutate({postId:rt.id,isPinned:rt.is_pinned}),children:rt.is_pinned?e.jsxs(e.Fragment,{children:[e.jsx(XJ,{className:"h-4 w-4 mr-2"}),"Unpin Post"]}):e.jsxs(e.Fragment,{children:[e.jsx(DE,{className:"h-4 w-4 mr-2"}),"Pin to Top"]})}),rt.user_id===(s==null?void 0:s.id)&&e.jsxs(ja,{onClick:()=>{D(rt),U(rt.content)},children:[e.jsx(gi,{className:"h-4 w-4 mr-2"}),"Edit"]}),e.jsxs(ja,{className:"text-destructive",onClick:()=>Ce.mutate(rt.id),children:[e.jsx(Wn,{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(DE,{className:"h-4 w-4"}),e.jsx("span",{className:"font-medium",children:"Pinned"})]}),e.jsx("div",{className:"mb-3",children:e.jsx(qrt,{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((Bt,Ft)=>{const rs=Ft===3&&rt.media.length>4,St=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:()=>_e({open:!0,images:rt.media.map(Xs=>({url:Xs.media_url,type:Xs.media_type==="video"?"video":"image"})),index:Ft}),children:[Bt.media_type==="video"?e.jsx("video",{src:Bt.media_url,className:"w-full h-full object-cover transition-transform group-hover:scale-105"}):e.jsx("img",{src:Bt.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"})})})}),rs&&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:["+",St]})})]},Bt.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:Bt=>{Bt.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(Ad,{className:"h-4 w-4 flex-shrink-0"}),e.jsx("span",{className:"truncate",children:rt.link_url})]})})]}),rt.reactions.length>0&&e.jsx(DWt,{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(at(rt.reactions)).slice(0,3).map(([Bt])=>{var Ft;return e.jsx("span",{className:"text-base",children:(Ft=Bde.find(rs=>rs.type===Bt))==null?void 0:Ft.emoji},Bt)})}),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(Yd,{children:[e.jsx(Zd,{asChild:!0,children:e.jsxs($,{variant:"ghost",size:"sm",className:"flex-1",children:[Ke(rt.reactions)?e.jsx("span",{className:"mr-1",children:(Yt=Bde.find(Bt=>Bt.type===Ke(rt.reactions)))==null?void 0:Yt.emoji}):e.jsx(Vy,{className:"h-4 w-4 mr-1"}),Ke(rt.reactions)?(qt=Bde.find(Bt=>Bt.type===Ke(rt.reactions)))==null?void 0:qt.label:"Like"]})}),e.jsx(Bd,{className:"w-auto p-2",side:"top",children:e.jsx("div",{className:"flex gap-1",children:Bde.map(Bt=>e.jsx("button",{onClick:()=>ze.mutate({postId:rt.id,reactionType:Bt.type}),className:"text-2xl hover:scale-125 transition-transform p-1",title:Bt.label,children:Bt.emoji},Bt.type))})})]}),e.jsxs($,{variant:"ghost",size:"sm",className:"flex-1",onClick:()=>V(Bt=>{const Ft=new Set(Bt);return Ft.has(rt.id)?Ft.delete(rt.id):Ft.add(rt.id),Ft}),children:[e.jsx(Th,{className:"h-4 w-4 mr-1"}),(()=>{const Bt=nt(rt.comments);return Bt>0?`Comment (${Bt})`:"Comment"})()]})]}),W.has(rt.id)&&e.jsxs("div",{className:"space-y-3 mt-3",children:[rt.comments.map(Bt=>e.jsx(FWt,{comment:Bt,postId:rt.id,currentUserId:s==null?void 0:s.id,currentUserAvatar:a,currentUserEmail:s==null?void 0:s.email,canModerate:xt(rt)},Bt.id)),s&&e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(Oa,{className:"h-8 w-8",children:[e.jsx(Li,{src:a||void 0}),e.jsx(za,{className:"text-xs",children:it(((ts=s.email)==null?void 0:ts.split("@")[0])||"U")})]}),e.jsxs("div",{className:"flex-1 flex gap-2",children:[e.jsx(HTe,{placeholder:"Write a comment... (use @ to mention)",value:G[rt.id]||"",onChange:Bt=>Y(Ft=>({...Ft,[rt.id]:Bt})),onMentionsChange:Bt=>ae(Ft=>({...Ft,[rt.id]:Bt})),mentionFormat:"plain",onKeyDown:Bt=>{var Ft;Bt.defaultPrevented||Bt.key==="Enter"&&!Bt.shiftKey&&((Ft=G[rt.id])!=null&&Ft.trim())&&(Bt.preventDefault(),$e.mutate({postId:rt.id,content:G[rt.id]}))},className:"text-sm min-h-0 py-1.5",minHeight:"32px"}),e.jsx($,{size:"sm",variant:"ghost",onClick:()=>{var Bt;(Bt=G[rt.id])!=null&&Bt.trim()&&$e.mutate({postId:rt.id,content:G[rt.id]})},disabled:!((ys=G[rt.id])!=null&&ys.trim()),className:"h-8 px-2 mt-0.5",children:e.jsx(Yr,{className:"h-4 w-4"})})]})]})]})]})},rt.id)}),Le&&e.jsx("div",{className:"flex justify-center pt-2",children:e.jsx($,{variant:"outline",onClick:()=>Fe(),disabled:ke,children:ke?"Loading…":"Load more posts"})})]}),e.jsx(zs,{open:!!R,onOpenChange:()=>D(null),children:e.jsxs(Os,{children:[e.jsx(Us,{children:e.jsx(Bs,{children:"Edit Post"})}),e.jsx(Rs,{value:O,onChange:rt=>U(rt.target.value),className:"min-h-[120px]"}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx($,{variant:"outline",onClick:()=>D(null),children:"Cancel"}),e.jsx($,{onClick:()=>{R&&Ae.mutate({postId:R.id,content:O})},disabled:!O.trim(),children:"Save Changes"})]})]})}),e.jsx(Nhn,{images:ce.images,initialIndex:ce.index,open:ce.open,onOpenChange:rt=>_e(Yt=>({...Yt,open:rt}))})]})]})})},Ahn=50*1024*1024;function OWt({value:s,onChange:t,disabled:n}){const{user:r}=vs(),a=j.useRef(null),[i,l]=j.useState(!1),o=async d=>{if(!d||!r)return;const u=[];l(!0);try{for(const h of Array.from(d)){if(!h.type.startsWith("image/")&&!h.type.startsWith("video/")){re.error(`${h.name}: only images and videos allowed`);continue}if(h.size>Ahn){re.error(`${h.name}: must be under 50MB`);continue}const m=h.name.split(".").pop()||"bin",f=`${r.id}/${Date.now()}-${Math.random().toString(36).slice(2,8)}.${m}`,{error:g}=await q.storage.from("support-attachments").upload(f,h,{contentType:h.type,upsert:!1});if(g){re.error(`${h.name}: ${g.message}`);continue}u.push({path:f,type:h.type,name:h.name,size:h.size})}u.length&&t([...s,...u])}finally{l(!1),a.current&&(a.current.value="")}},c=async d=>{const u=s[d];t(s.filter((h,m)=>m!==d)),await q.storage.from("support-attachments").remove([u.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,u)=>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(CJ,{className:"h-3.5 w-3.5 text-muted-foreground"}):e.jsx(GI,{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(u),className:"text-muted-foreground hover:text-foreground",children:e.jsx(gr,{className:"h-3 w-3"})})]},d.path))}),e.jsxs($,{type:"button",variant:"outline",size:"sm",onClick:()=>{var d;return(d=a.current)==null?void 0:d.click()},disabled:n||i,className:"gap-1.5",children:[i?e.jsx(kt,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(QI,{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 zWt({attachments:s}){const[t,n]=j.useState({}),[r,a]=j.useState(!0);return j.useEffect(()=>{if(!(s!=null&&s.length)){a(!1);return}let i=!1;return(async()=>{const l=s.map(d=>d.path),{data:o}=await q.storage.from("support-attachments").createSignedUrls(l,60*60*24);if(i||!o)return;const c={};o.forEach((d,u)=>{d.signedUrl&&(c[l[u]]=d.signedUrl)}),n(c),a(!1)})(),()=>{i=!0}},[s]),s!=null&&s.length?r?e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground mt-2",children:[e.jsx(kt,{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 F$={open:{label:"Open",icon:da,color:"bg-yellow-500"},in_progress:{label:"In Progress",icon:Th,color:"bg-blue-500"},resolved:{label:"Resolved",icon:Nc,color:"bg-green-500"},closed:{label:"Closed",icon:ku,color:"bg-muted-foreground"}},Owt={general:"General Support",technology:"Technology Support",crm:"CRM Support",marketing:"Marketing Support"};function Ehn(){const{user:s}=vs(),t=Vt(),[n,r]=j.useState(null),[a,i]=j.useState(""),[l,o]=j.useState([]),{data:c=[],isLoading:d}=tt({queryKey:["support-tickets"],queryFn:async()=>{const{data:f,error:g}=await q.from("support_tickets").select("*").eq("user_id",s==null?void 0:s.id).order("created_at",{ascending:!1});if(g)throw g;return f},enabled:!!s}),{data:u=[]}=tt({queryKey:["ticket-replies",n==null?void 0:n.id],queryFn:async()=>{if(!n)return[];const{data:f,error:g}=await q.from("support_ticket_replies").select("*, profiles(name)").eq("ticket_id",n.id).order("created_at",{ascending:!0});if(g)throw g;return f},enabled:!!n}),h=ft({mutationFn:async({content:f,attachments:g})=>{if(!n||!s)throw new Error("Missing data");const{error:x}=await q.from("support_ticket_replies").insert({ticket_id:n.id,user_id:s.id,content:f,is_admin_reply:!1,attachments:g});if(x)throw x},onSuccess:()=>{t.invalidateQueries({queryKey:["ticket-replies",n==null?void 0:n.id]}),i(""),o([]),re.success("Reply sent!")},onError:()=>{re.error("Failed to send reply")}}),m=()=>{!a.trim()&&l.length===0||h.mutate({content:a,attachments:l})};if(n){const f=F$[n.status].icon;return e.jsx(Vs,{children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx($,{variant:"ghost",size:"icon",onClick:()=>r(null),children:e.jsx(qa,{className:"h-5 w-5"})}),e.jsxs("div",{className:"flex-1",children:[e.jsx("h1",{className:"text-2xl font-bold",children:n.subject}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx(Be,{variant:"secondary",children:Owt[n.category]}),e.jsxs(Be,{className:F$[n.status].color,children:[e.jsx(f,{className:"h-3 w-3 mr-1"}),F$[n.status].label]})]})]})]}),e.jsxs(Ne,{children:[e.jsx(Ct,{children:e.jsxs(Gn,{children:["Created on ",en(new Date(n.created_at),"MMM d, yyyy 'at' h:mm a")]})}),e.jsx(Ie,{children:e.jsx("p",{className:"text-muted-foreground whitespace-pre-wrap",children:n.description})})]}),e.jsxs(Ne,{children:[e.jsx(Ct,{children:e.jsx(At,{className:"text-lg",children:"Conversation"})}),e.jsxs(Ie,{children:[e.jsx(uo,{className:"h-[300px] pr-4",children:u.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:u.map(g=>{var x;return e.jsxs("div",{className:`p-4 rounded-lg ${g.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:g.is_admin_reply?"Support Team":((x=g.profiles)==null?void 0:x.name)||"You"}),e.jsx("span",{className:"text-xs text-muted-foreground",children:en(new Date(g.created_at),"MMM d, h:mm a")})]}),e.jsx("p",{className:"text-sm whitespace-pre-wrap",children:g.content}),g.attachments&&g.attachments.length>0&&e.jsx(zWt,{attachments:g.attachments})]},g.id)})})}),n.status!=="closed"&&e.jsxs(e.Fragment,{children:[e.jsx(Gc,{className:"my-4"}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsx(Rs,{placeholder:"Type your reply...",value:a,onChange:g=>i(g.target.value),className:"min-h-[80px]"}),e.jsx($,{onClick:m,disabled:!a.trim()&&l.length===0||h.isPending,className:"self-end",children:e.jsx(Yr,{className:"h-4 w-4"})})]}),e.jsx(OWt,{value:l,onChange:o,disabled:h.isPending})]})]})]})]})]})})}return e.jsx(Vs,{children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(Ne,{className:"bg-gradient-to-br from-primary/10 via-primary/5 to-background border-primary/20",children:e.jsx(Ie,{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(s4,{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(ZHe,{trigger:e.jsxs($,{size:"lg",className:"gap-2",children:[e.jsx(dn,{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(Da,{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(ZHe,{trigger:e.jsxs($,{variant:"outline",size:"sm",className:"gap-2",children:[e.jsx(dn,{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(Ne,{className:"border-dashed",children:e.jsxs(Ie,{className:"text-center py-12",children:[e.jsx(Th,{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(f=>{const g=F$[f.status].icon;return e.jsx(Ne,{className:"cursor-pointer hover:bg-muted/50 transition-colors",onClick:()=>r(f),children:e.jsx(Ie,{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:f.subject}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx(Be,{variant:"outline",className:"text-xs",children:Owt[f.category]}),e.jsx("span",{className:"text-xs text-muted-foreground",children:en(new Date(f.created_at),"MMM d, yyyy")})]})]}),e.jsxs(Be,{className:F$[f.status].color,children:[e.jsx(g,{className:"h-3 w-3 mr-1"}),F$[f.status].label]})]})})},f.id)})})]})})}function Thn({open:s,onOpenChange:t}){return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Os,{className:"max-w-3xl max-h-[90vh] overflow-hidden",children:[e.jsx(Us,{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(Ta,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{children:[e.jsx(Bs,{children:"Schedule Agent Onboarding"}),e.jsx(Ir,{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 Mhn({open:s,onOpenChange:t}){const{brokerageId:n}=vs(),[r,a]=j.useState(""),[i,l]=j.useState([]),[o,c]=j.useState(!1),{data:d,isLoading:u}=tt({queryKey:["brokerage-agents-for-onboarding",n],queryFn:async()=>{if(!n)return[];const{data:x,error:y}=await q.from("profiles").select("id, name, email").eq("brokerage_id",n).order("name",{ascending:!0});if(y)throw y;return x},enabled:s&&!!n}),h=d==null?void 0:d.filter(x=>x.name.toLowerCase().includes(r.toLowerCase())||x.email.toLowerCase().includes(r.toLowerCase())),m=x=>{l(y=>y.includes(x)?y.filter(v=>v!==x):[...y,x])},f=async()=>{if(i.length===0){re.error("Please select at least one agent");return}c(!0);try{const{data:x,error:y}=await q.functions.invoke("send-onboarding-link",{body:{agentIds:i}});if(y)throw y;re.success(`Onboarding link sent to ${i.length} agent${i.length>1?"s":""}`),l([]),t(!1)}catch(x){console.error("Error sending onboarding link:",x),re.error(x.message||"Failed to send onboarding link")}finally{c(!1)}},g=x=>{x||(l([]),a("")),t(x)};return e.jsx(zs,{open:s,onOpenChange:g,children:e.jsxs(Os,{className:"max-w-md",children:[e.jsx(Us,{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(Yr,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{children:[e.jsx(Bs,{children:"Send Onboarding Link"}),e.jsx(Ir,{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(Kr,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(pe,{placeholder:"Search agents...",value:r,onChange:x=>a(x.target.value),className:"pl-10"})]}),u?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(kt,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):(h==null?void 0:h.length)===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(Zn,{className:"h-8 w-8 mx-auto mb-2 opacity-50"}),e.jsx("p",{children:"No agents found"})]}):e.jsx(uo,{className:"h-[300px] border rounded-lg",children:e.jsx("div",{className:"p-2 space-y-1",children:h==null?void 0:h.map(x=>e.jsxs("div",{className:"flex items-center gap-3 p-2 rounded-lg hover:bg-muted cursor-pointer",onClick:()=>m(x.id),children:[e.jsx(ai,{checked:i.includes(x.id),onCheckedChange:()=>m(x.id)}),e.jsx(Oa,{className:"h-8 w-8",children:e.jsx(za,{className:"text-xs",children:x.name.split(" ").map(y=>y[0]).join("").toUpperCase()})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium truncate",children:x.name}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:x.email})]})]},x.id))})}),i.length>0&&e.jsxs("p",{className:"text-sm text-muted-foreground",children:[i.length," agent",i.length>1?"s":""," selected"]})]}),e.jsxs(Ar,{children:[e.jsx($,{variant:"outline",onClick:()=>g(!1),children:"Cancel"}),e.jsx($,{onClick:f,disabled:i.length===0||o,children:o?e.jsxs(e.Fragment,{children:[e.jsx(kt,{className:"h-4 w-4 mr-2 animate-spin"}),"Sending..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Yr,{className:"h-4 w-4 mr-2"}),"Send Link"]})})]})]})})}function Phn(){const[s,t]=j.useState(!1),[n,r]=j.useState(!1);return e.jsxs(e.Fragment,{children:[e.jsxs(Ne,{className:"mb-8",children:[e.jsx(Ct,{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(Zn,{className:"h-6 w-6 text-primary"})}),e.jsxs("div",{children:[e.jsx(At,{children:"Agent Onboarding"}),e.jsx(Gn,{children:"Schedule onboarding sessions for yourself or your agents"})]})]})}),e.jsx(Ie,{children:e.jsxs("div",{className:"flex flex-wrap gap-4",children:[e.jsxs($,{onClick:()=>t(!0),className:"flex items-center gap-2",children:[e.jsx(Ta,{className:"h-4 w-4"}),"Schedule Agent Onboarding"]}),e.jsxs($,{variant:"outline",onClick:()=>r(!0),className:"flex items-center gap-2",children:[e.jsx(Yr,{className:"h-4 w-4"}),"Send New Agent Onboarding Link"]})]})})]}),e.jsx(Thn,{open:s,onOpenChange:t}),e.jsx(Mhn,{open:n,onOpenChange:r})]})}function Ihn({open:s,onOpenChange:t}){return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Os,{className:"max-w-3xl max-h-[90vh] overflow-hidden",children:[e.jsx(Us,{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(qg,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{children:[e.jsx(Bs,{children:"Schedule Launch Meeting"}),e.jsx(Ir,{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 Lhn(){const[s,t]=j.useState(!1);return e.jsxs(e.Fragment,{children:[e.jsxs(Ne,{className:"mb-8",children:[e.jsx(Ct,{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(qg,{className:"h-6 w-6 text-primary"})}),e.jsxs("div",{children:[e.jsx(At,{children:"Launch or ReLaunch Meeting"}),e.jsx(Gn,{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(Ie,{children:e.jsxs($,{onClick:()=>t(!0),className:"flex items-center gap-2",children:[e.jsx(qg,{className:"h-4 w-4"}),"Schedule Launch Meeting"]})})]}),e.jsx(Ihn,{open:s,onOpenChange:t})]})}function Rhn(){const s=Qn(),[t,n]=j.useState(""),[r,a]=j.useState(null),{data:i,isLoading:l}=tt({queryKey:["brokerage-resources-published"],queryFn:async()=>{const{data:x,error:y}=await q.from("brokerage_resources").select("*").eq("is_published",!0).order("publish_date",{ascending:!1});if(y)throw y;return x}}),{data:o}=tt({queryKey:["brokerage-resource-categories"],queryFn:async()=>{const{data:x,error:y}=await q.from("brokerage_resource_categories").select("*").order("sort_order",{ascending:!0});if(y)throw y;return x}}),{data:c}=tt({queryKey:["brokerage-resource-pdfs-all"],queryFn:async()=>{const{data:x,error:y}=await q.from("brokerage_resource_pdfs").select("resource_id");if(y)throw y;return x}}),{data:d}=tt({queryKey:["brokerage-resource-videos-all"],queryFn:async()=>{const{data:x,error:y}=await q.from("brokerage_resource_videos").select("resource_id");if(y)throw y;return x}}),{data:u}=tt({queryKey:["brokerage-resource-links-all"],queryFn:async()=>{const{data:x,error:y}=await q.from("brokerage_resource_links").select("resource_id");if(y)throw y;return x}}),h=i==null?void 0:i.filter(x=>{var b;const y=x.title.toLowerCase().includes(t.toLowerCase())||((b=x.description)==null?void 0:b.toLowerCase().includes(t.toLowerCase())),v=!r||x.category_id===r;return y&&v}),m=o==null?void 0:o.filter(x=>i==null?void 0:i.some(y=>y.category_id===x.id)),f=x=>{const y=(c==null?void 0:c.filter(w=>w.resource_id===x).length)||0,v=(d==null?void 0:d.filter(w=>w.resource_id===x).length)||0,b=(u==null?void 0:u.filter(w=>w.resource_id===x).length)||0;return{pdfCount:y,videoCount:v,linkCount:b}},g=x=>{s(`/brokerage-resources/${x}`)};return e.jsx(Vs,{title:"Brokerage Resources",description:"Access exclusive resources for brokerage managers",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(Phn,{}),e.jsx(Lhn,{}),e.jsxs("div",{className:"relative max-w-md",children:[e.jsx(Kr,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(pe,{placeholder:"Search resources...",value:t,onChange:x=>n(x.target.value),className:"pl-10"})]}),m&&m.length>0&&e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx(Be,{variant:r===null?"default":"outline",className:"cursor-pointer",onClick:()=>a(null),children:"All"}),m.map(x=>e.jsx(Be,{variant:r===x.id?"default":"outline",className:"cursor-pointer",onClick:()=>a(x.id),children:x.name},x.id))]}),!l&&e.jsxs("p",{className:"text-sm text-muted-foreground",children:[(h==null?void 0:h.length)||0," resource",(h==null?void 0:h.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((x,y)=>e.jsxs(Ne,{children:[e.jsx(yn,{className:"h-40 w-full"}),e.jsx(Ct,{children:e.jsx(yn,{className:"h-5 w-3/4"})}),e.jsxs(Ie,{children:[e.jsx(yn,{className:"h-4 w-full mb-2"}),e.jsx(yn,{className:"h-4 w-2/3"})]})]},y))}):(h==null?void 0:h.length)===0?e.jsxs(Ne,{className:"p-12 text-center",children:[e.jsx(Sx,{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||r?"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:h==null?void 0:h.map(x=>{const{pdfCount:y,videoCount:v,linkCount:b}=f(x.id),w=o==null?void 0:o.find(S=>S.id===x.category_id);return e.jsxs(Ne,{className:"overflow-hidden cursor-pointer hover:shadow-lg transition-shadow",onClick:()=>g(x.id),children:[x.preview_image_url?e.jsx("img",{src:x.preview_image_url,alt:x.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(Sx,{className:"h-16 w-16 text-muted-foreground"})}),e.jsx(Ct,{className:"pb-2",children:e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsx(At,{className:"text-lg line-clamp-1",children:x.title}),w&&e.jsx(Be,{variant:"secondary",className:"shrink-0 text-xs",children:w.name})]})}),e.jsxs(Ie,{children:[x.description&&e.jsx("p",{className:"text-sm text-muted-foreground line-clamp-2 mb-3",children:x.description}),e.jsxs("div",{className:"flex items-center gap-4 text-sm text-muted-foreground",children:[y>0&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Jr,{className:"h-4 w-4"}),y]}),v>0&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(ua,{className:"h-4 w-4"}),v]}),b>0&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Ad,{className:"h-4 w-4"}),b]})]})]})]},x.id)})})]})})}const Dhn=()=>{const{resourceId:s}=Wi(),{data:t,isLoading:n}=tt({queryKey:["brokerage-resource-detail",s],queryFn:async()=>{const{data:a,error:i}=await q.from("brokerage_resources").select("*").eq("id",s).eq("is_published",!0).single();if(i)throw i;const{data:l}=await q.from("brokerage_resource_pdfs").select("*").eq("resource_id",s).order("sort_order"),{data:o}=await q.from("brokerage_resource_videos").select("*").eq("resource_id",s).order("sort_order"),{data:c}=await q.from("brokerage_resource_links").select("*").eq("resource_id",s).order("sort_order");return{...a,pdfs:l||[],videos:o||[],links:c||[]}},enabled:!!s}),r=a=>a?a<1024?a+" B":a<1024*1024?(a/1024).toFixed(1)+" KB":(a/(1024*1024)).toFixed(1)+" MB":"";return n?e.jsx(Vs,{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(Vs,{title:t.title,children:e.jsxs("div",{className:"space-y-6 max-w-5xl mx-auto",children:[e.jsx($,{variant:"ghost",size:"sm",asChild:!0,className:"gap-2",children:e.jsxs(wr,{to:"/brokerage-resources",children:[e.jsx(qa,{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(Ne,{children:e.jsxs(Ie,{className:"pt-6",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 mb-4",children:[e.jsx(ua,{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(Ne,{children:e.jsxs(Ie,{className:"pt-6",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 mb-4",children:[e.jsx(Jr,{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(Jr,{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:r(a.file_size)})]})]}),e.jsx(di,{className:"h-4 w-4 text-muted-foreground group-hover:text-primary transition-colors"})]},a.id))})]})}),t.links&&t.links.length>0&&e.jsx(Ne,{children:e.jsxs(Ie,{className:"pt-6",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 mb-4",children:[e.jsx(kr,{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(kr,{className:"h-4 w-4 text-primary"})}),e.jsx("div",{className:"font-medium text-sm",children:a.title})]}),e.jsx(kr,{className:"h-4 w-4 text-muted-foreground group-hover:text-primary transition-colors"})]},a.id))})]})})]})}):e.jsx(Vs,{title:"Brokerage Resources",children:e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(Sx,{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($,{asChild:!0,className:"mt-4",children:e.jsx(wr,{to:"/brokerage-resources",children:"Back to Resources"})})]})})};function Fhn(){const{onlineUsers:s,totalOnline:t}=ZFt(),{user:n}=vs();return e.jsxs(Ne,{children:[e.jsx(Ct,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(At,{className:"text-base flex items-center gap-2",children:[e.jsx(Zn,{className:"h-4 w-4"}),"Online Now"]}),e.jsxs(Be,{variant:"secondary",className:"bg-green-100 text-green-700",children:[e.jsx(Og,{className:"h-2 w-2 fill-green-500 text-green-500 mr-1"}),t," online"]})]})}),e.jsx(Ie,{children:s.length===0?e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"No users online right now"}):e.jsx(uo,{className:"h-[300px] pr-4",children:e.jsx("div",{className:"space-y-3",children:s.map(r=>{var a;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(Oa,{className:"h-9 w-9",children:[e.jsx(Li,{src:r.avatarUrl,alt:r.name}),e.jsx(za,{className:"text-xs",children:(a=r.name)==null?void 0:a.split(" ").map(i=>i[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.jsxs("p",{className:"text-sm font-medium truncate",children:[r.name,r.id===(n==null?void 0:n.id)?" (You)":""]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Online ",mu(new Date(r.onlineSince),{addSuffix:!1})]})]})]},r.id)})})})})]})}const zwt={users:{label:"Users & Access",sections:[{title:"Member Broadcasts",description:"Email a filtered group of members (paste HTML or write it)",icon:xm,path:"/admin/broadcasts",color:"bg-rose-500/10 text-rose-600"},{title:"Members",description:"Manage users, roles, and brokerage assignments",icon:Zn,path:"/admin/members",color:"bg-blue-500/10 text-blue-600"},{title:"Partnerships",description:"Manage partnership packages, rosters, and upgrade requests",icon:ul,path:"/admin/partnerships",color:"bg-indigo-500/10 text-indigo-600"},{title:"Invite Codes",description:"Create and manage signup invite codes",icon:a7,path:"/admin/invite-codes",color:"bg-amber-500/10 text-amber-600"},{title:"Subscriptions",description:"Track and manage user subscriptions",icon:Cv,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:_J,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:Ap,path:"/admin/discounts",color:"bg-red-500/10 text-red-600"},{title:"Referral Program",description:"Track brokerage referrals and discounts",icon:zd,path:"/admin/referrals",color:"bg-teal-500/10 text-teal-600"},{title:"Teams",description:"Manage agent teams across all brokerages",icon:Zn,path:"/admin/members?tab=teams",color:"bg-violet-500/10 text-violet-600"},{title:"Prospector",description:"Send free trial invites and track conversions",icon:rh,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:sc,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:Kl,path:"/admin/coaching",color:"bg-gradient-to-br from-teal-500/20 to-cyan-500/10 text-teal-600"}]},content:{label:"Content",sections:[{title:"Blog",description:"Write founder articles, moderate comments, publish to /blog",icon:nk,path:"/admin/blog",color:"bg-amber-500/10 text-amber-600"},{title:"Manage Templates",description:"Upload and organize Canva templates",icon:Yc,path:"/admin/templates",color:"bg-pink-500/10 text-pink-600"},{title:"Manage Programs",description:"Cohorts, enrollments and delayed billing",icon:of,path:"/admin/programs",color:"bg-emerald-500/10 text-emerald-600"},{title:"Manage Academy",description:"Upload videos and training content",icon:of,path:"/admin/academy",color:"bg-indigo-500/10 text-indigo-600"},{title:"Manage Toolbox",description:"Create and manage resource kits",icon:F4,path:"/admin/toolbox",color:"bg-orange-500/10 text-orange-600"},{title:"Social Swag",description:"Manage social media content and links",icon:Nn,path:"/admin/social-swag",color:"bg-fuchsia-500/10 text-fuchsia-600"},{title:"Social Swag 2.0",description:"New monthly social media images",icon:Nn,path:"/admin/social-swag-2",color:"bg-cyan-500/10 text-cyan-600"},{title:"Newsletters",description:"Manage monthly newsletter templates",icon:nk,path:"/admin/newsletters",color:"bg-violet-500/10 text-violet-600"},{title:"Newsletter Graphics",description:"Upload branded graphics agents drop into newsletters & emails",icon:nk,path:"/admin/newsletter-graphics",color:"bg-fuchsia-500/10 text-fuchsia-600"},{title:"Manage Events",description:"Create and publish events with Zoom integration",icon:Kc,path:"/admin/events",color:"bg-green-500/10 text-green-600"},{title:"LevelUp Live",description:"Public streaming pages, invite links, and live leads",icon:Nb,path:"/admin/live",color:"bg-red-500/10 text-red-600"},{title:"Additional Services",description:"Manage additional service offerings",icon:Sx,path:"/admin/additional-services",color:"bg-lime-500/10 text-lime-600"},{title:"Brokerage Resources",description:"Manage resources for brokerage managers",icon:Sx,path:"/admin/brokerage-resources",color:"bg-slate-500/10 text-slate-600"},{title:"Agent Email Templates",description:"Manage curated email templates for agents",icon:mn,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:xm,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:YI,path:"/admin/dashboard-management",color:"bg-teal-500/10 text-teal-600"},{title:"Manage Apps",description:"Configure app tiles and access requirements",icon:Uj,path:"/admin/apps",color:"bg-purple-500/10 text-purple-600"},{title:"Email Templates",description:"Customize system email templates",icon:mn,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:xm,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:JN,path:"/admin/onboarding-checklist",color:"bg-emerald-500/10 text-emerald-600"},{title:"Marketplace",description:"Manage store categories, products, and orders",icon:D4,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:ul,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:Kl,path:"/admin/agent-points",color:"bg-amber-500/10 text-amber-600"},{title:"Integrations",description:"Connect Canva, Facebook & Instagram for platform-level features",icon:bd,path:"/admin/integrations",color:"bg-blue-500/10 text-blue-600"},{title:"Agent Cards",description:"Manage digital business cards for agents",icon:Zn,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:xm,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:eo,path:"/admin/community",color:"bg-cyan-500/10 text-cyan-600"},{title:"Support Tickets",description:"View and respond to agent support requests",icon:Vq,path:"/admin/support-tickets",color:"bg-rose-500/10 text-rose-600"},{title:"Wishlist",description:"Review and manage community feature requests",icon:tC,path:"/admin/wishlist",color:"bg-yellow-500/10 text-yellow-600"},{title:"Membership Reviews",description:"View member feedback and ratings",icon:Ja,path:"/admin/membership-reviews",color:"bg-amber-500/10 text-amber-600"},{title:"Weekly Digest",description:"Configure automated weekly email digests",icon:mn,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:Wl,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:Xf,path:"/admin/brokerage-content-activity",color:"bg-sky-500/10 text-sky-600"},{title:"Music Videos",description:"View all listing music videos created by agents across the platform",icon:jb,path:"/admin/music-videos",color:"bg-gradient-to-br from-pink-500/20 to-rose-500/10 text-pink-600"}]},lms:{label:"LevelUp U",sections:[{title:"Manage Courses",description:"Create and manage LMS training courses, modules, and access",icon:of,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:Jo,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:va,path:"/admin/listing-exchange",color:"bg-gradient-to-br from-blue-500/20 to-sky-500/10 text-blue-600"},{title:"Listing Leads",description:"View all leads from the public listings site with property & agent assignment",icon:sc,path:"/admin/listing-leads",color:"bg-gradient-to-br from-teal-500/20 to-emerald-500/10 text-teal-600"},{title:"Public Site Leads",description:"Alerts signups, exit-intent captures & saved-home leads from listings.relevelup.com",icon:sc,path:"/admin/public-site-leads",color:"bg-gradient-to-br from-amber-500/20 to-orange-500/10 text-amber-600"},{title:"Presentation Analytics",description:"Track agent presentation usage, views, and leads",icon:jb,path:"/admin/presentation-analytics",color:"bg-gradient-to-br from-violet-500/20 to-indigo-500/10 text-violet-600"},{title:"Listing Presentation Studio",description:"Track every listing presentation agents build, generate, and send",icon:Jr,path:"/admin/listing-presentation-studio",color:"bg-gradient-to-br from-slate-500/20 to-zinc-500/10 text-slate-600"},{title:"Listing Revival",description:"Track expired-listing campaigns, seller leads, and manage who has access",icon:Nn,path:"/admin/listing-revival",color:"bg-gradient-to-br from-amber-500/20 to-yellow-500/10 text-amber-600"},{title:"Staging Studio",description:"Member conversions gallery, credits, subscriptions, and credit pack pricing",icon:Mc,path:"/admin/staging-studio",color:"bg-gradient-to-br from-teal-500/20 to-emerald-500/10 text-teal-600"},{title:"Weekly Reels",description:"Manage Weekly Reels access, generation runs, and email delivery",icon:rf,path:"/admin/weekly-reels",color:"bg-gradient-to-br from-pink-500/20 to-rose-500/10 text-pink-600"},{title:"Guest Book Analytics",description:"Track open house sign-in usage, visitors, and lead generation",icon:Xf,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:Mc,path:"/admin/beta/social-post-generator",color:"bg-gradient-to-br from-fuchsia-500/20 to-pink-500/10 text-fuchsia-600"},{title:"Mail Studio Designs",description:"Upload postcard designs for the Mail Studio template library",icon:mn,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:I4,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:dl,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:Iq,path:"/admin/mls-feeds",color:"bg-gradient-to-br from-emerald-500/20 to-green-500/10 text-emerald-600"},{title:"Free Website Offers",description:"Choose which brokerages get a free luxury website, and set their default template",icon:ul,path:"/admin/lead-sites/offers",color:"bg-gradient-to-br from-violet-500/20 to-purple-500/10 text-violet-600"},{title:"Lead Analytics",description:"Cross-site lead capture stats, conversions, and top-performing sites",icon:Yl,path:"/admin/lead-site-analytics",color:"bg-gradient-to-br from-amber-500/20 to-orange-500/10 text-amber-600"},{title:"Beta Website Requests",description:"Member requests for free beta (non-IDX) agent websites — review, build and launch",icon:Jr,path:"/admin/website-requests",color:"bg-gradient-to-br from-sky-500/20 to-blue-500/10 text-sky-600"},{title:"Website Interests",description:"Track interest form submissions from TheLocalMove.com",icon:Jr,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:Jr,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:ru,path:"/admin/mls-fee-tracker",color:"bg-gradient-to-br from-teal-500/20 to-cyan-500/10 text-teal-600"}]}};function Bwt(){const s=Qn();return console.log("[AdminDashboard] render"),e.jsx(Vs,{title:"Admin Dashboard",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{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.jsxs(ha,{defaultValue:"users",className:"w-full",children:[e.jsx(ma,{className:"w-full justify-start flex-wrap h-auto gap-1 bg-muted/50 p-1 overflow-x-auto",children:Object.entries(zwt).map(([t,n])=>e.jsx(Zt,{value:t,className:"data-[state=active]:bg-background",children:n.label},t))}),Object.entries(zwt).map(([t,n])=>e.jsx(Xt,{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:n.sections.map(r=>e.jsxs(Ne,{className:"cursor-pointer hover:shadow-md transition-all hover:border-primary/50 group",onClick:()=>s(r.path),children:[e.jsxs(Ct,{className:"pb-3",children:[e.jsx("div",{className:`w-10 h-10 rounded-lg flex items-center justify-center ${r.color} mb-2 group-hover:scale-110 transition-transform`,children:e.jsx(r.icon,{className:"h-5 w-5"})}),e.jsx(At,{className:"text-base",children:r.title})]}),e.jsx(Ie,{className:"pt-0",children:e.jsx(Gn,{className:"text-sm",children:r.description})})]},r.path))})},t))]}),e.jsx(Fhn,{})]})})}const Ohn=()=>{const{isAdmin:s}=vs(),t=Qn(),[n,r]=j.useState([]),[a,i]=j.useState(!0),[l,o]=j.useState(!1),[c,d]=j.useState(null);j.useEffect(()=>{if(!s){t("/dashboard");return}u()},[s]);const u=async()=>{try{const{data:x,error:y}=await q.from("app_tiles").select("*").order("name");if(y)throw y;r(x||[])}catch(x){console.error("Error loading apps:",x),re.error("Failed to load apps")}finally{i(!1)}},h=async x=>{x.preventDefault();const y=new FormData(x.currentTarget),v={name:y.get("name"),description:y.get("description"),icon:y.get("icon"),app_id:y.get("app_id"),target_url:y.get("target_url"),required_tags:y.get("required_tags").split(",").map(b=>b.trim()).filter(Boolean)};try{if(c){const{error:b}=await q.from("app_tiles").update(v).eq("id",c.id);if(b)throw b;re.success("App updated successfully")}else{const{error:b}=await q.from("app_tiles").insert([v]);if(b)throw b;re.success("App created successfully")}o(!1),d(null),u()}catch(b){console.error("Error saving app:",b),re.error("Failed to save app")}},m=async x=>{if(await fo("Are you sure you want to delete this app?"))try{const{error:y}=await q.from("app_tiles").delete().eq("id",x);if(y)throw y;re.success("App deleted successfully"),u()}catch(y){console.error("Error deleting app:",y),re.error("Failed to delete app")}},f=x=>{d(x),o(!0)},g=()=>{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($,{variant:"ghost",size:"sm",onClick:()=>t("/dashboard"),children:[e.jsx(qa,{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(zs,{open:l,onOpenChange:o,children:[e.jsx(jl,{asChild:!0,children:e.jsxs($,{onClick:g,children:[e.jsx(dn,{className:"mr-2 h-4 w-4"}),"Add App"]})}),e.jsxs(Os,{className:"max-w-2xl",children:[e.jsxs(Us,{children:[e.jsx(Bs,{children:c?"Edit App":"Create New App"}),e.jsx(Ir,{children:"Configure the application tile settings"})]}),e.jsxs("form",{onSubmit:h,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(ee,{htmlFor:"name",children:"App Name"}),e.jsx(pe,{id:"name",name:"name",defaultValue:c==null?void 0:c.name,required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"app_id",children:"App ID"}),e.jsx(pe,{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(ee,{htmlFor:"description",children:"Description"}),e.jsx(Rs,{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(ee,{htmlFor:"icon",children:"Icon (emoji)"}),e.jsx(pe,{id:"icon",name:"icon",defaultValue:c==null?void 0:c.icon,placeholder:"🚀",required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"target_url",children:"Target URL"}),e.jsx(pe,{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(ee,{htmlFor:"required_tags",children:"Required Tags (comma-separated)"}),e.jsx(pe,{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($,{type:"button",variant:"outline",onClick:()=>o(!1),children:"Cancel"}),e.jsx($,{type:"submit",children:c?"Update":"Create"})]})]})]})]})]})})}),e.jsx("div",{className:"container mx-auto px-4 py-8",children:e.jsxs(Ne,{children:[e.jsxs(Ct,{children:[e.jsx(At,{children:"Application Tiles"}),e.jsx(Gn,{children:"Manage the apps that appear on the member dashboard"})]}),e.jsx(Ie,{children:n.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($,{onClick:g,children:[e.jsx(dn,{className:"mr-2 h-4 w-4"}),"Create First App"]})]}):e.jsxs(mi,{children:[e.jsx(fi,{children:e.jsxs(En,{children:[e.jsx(Dt,{children:"Icon"}),e.jsx(Dt,{children:"Name"}),e.jsx(Dt,{children:"App ID"}),e.jsx(Dt,{children:"Target URL"}),e.jsx(Dt,{children:"Tags"}),e.jsx(Dt,{className:"text-right",children:"Actions"})]})}),e.jsx(pi,{children:n.map(x=>e.jsxs(En,{children:[e.jsx(wt,{className:"text-2xl",children:x.icon}),e.jsx(wt,{className:"font-medium",children:x.name}),e.jsx(wt,{className:"font-mono text-sm",children:x.app_id}),e.jsx(wt,{className:"text-sm text-muted-foreground max-w-xs truncate",children:x.target_url}),e.jsx(wt,{children:e.jsx("div",{className:"flex flex-wrap gap-1",children:x.required_tags.map(y=>e.jsx("span",{className:"text-xs bg-secondary text-secondary-foreground px-2 py-1 rounded",children:y},y))})}),e.jsx(wt,{className:"text-right",children:e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx($,{size:"sm",variant:"ghost",onClick:()=>f(x),children:e.jsx(gi,{className:"h-4 w-4"})}),e.jsx($,{size:"sm",variant:"ghost",onClick:()=>m(x.id),children:e.jsx(Wn,{className:"h-4 w-4"})})]})})]},x.id))})]})})]})})]})};function Fm({title:s,description:t,children:n}){return e.jsxs("div",{className:"space-y-4",children:[e.jsx(wr,{to:"/admin",children:e.jsxs($,{variant:"ghost",size:"sm",className:"gap-2 text-muted-foreground hover:text-foreground",children:[e.jsx(qa,{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})]}),n]})]})}const $wt=({expiresAt:s,className:t})=>{const n=new Date().getTime(),r=new Date(s).getTime(),a=Math.ceil((r-n)/(1e3*60*60*24));return a<=0?e.jsxs(Be,{variant:"destructive",className:Pt("gap-1",t),children:[e.jsx(wl,{className:"h-3 w-3"}),"Trial Expired"]}):a<=1?e.jsxs(Be,{variant:"destructive",className:Pt("gap-1",t),children:[e.jsx(da,{className:"h-3 w-3"}),"Trial: <1 day left"]}):a<=3?e.jsxs(Be,{className:Pt("gap-1 bg-amber-500 hover:bg-amber-600",t),children:[e.jsx(da,{className:"h-3 w-3"}),"Trial: ",a," days left"]}):e.jsxs(Be,{variant:"secondary",className:Pt("gap-1",t),children:[e.jsx(da,{className:"h-3 w-3"}),"Trial: ",a," days left"]})},BWt=({open:s,onOpenChange:t,brokerages:n,fixedBrokerageId:r,onSuccess:a})=>{const{toast:i}=Bi(),l=j.useRef(null),[o,c]=j.useState([]),[d,u]=j.useState(""),[h,m]=j.useState(!1),[f,g]=j.useState("upload"),[x,y]=j.useState(null),v=()=>{c([]),u(""),g("upload"),y(null),l.current&&(l.current.value="")},b=()=>{v(),t(!1)},w=P=>{const R=P.split(` `).map(V=>V.trim()).filter(V=>V);if(R.length===0)return[];const D=R[0].toLowerCase(),U=D.includes("first")||D.includes("last")||D.includes("email")||D.includes("name")||D.includes("phone")||D.includes("sms")||D.includes("consent")?R.slice(1):R,W=[];for(const V of U){const Y=(V.includes(" ")?V.split(" "):V.split(",")).map(X=>X.trim().replace(/^["']|["']$/g,""));if(Y.length>=2){let X="",ae="",ie="",ne="",te;if(Y.length===2){const _e=Y[0].split(" ");X=_e[0]||"",ae=_e.slice(1).join(" ")||"",ie=Y[1]}else if(Y.length===3)X=Y[0],ae=Y[1],ie=Y[2];else if(Y.length===4)X=Y[0],ae=Y[1],ie=Y[2],ne=Y[3];else if(Y.length>=5){X=Y[0],ae=Y[1],ie=Y[2],ne=Y[3];const _e=Y[4].toLowerCase();te=_e==="true"||_e==="yes"||_e==="1"||_e==="y"}const ce=/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(ie);W.push({firstName:X.trim(),lastName:ae.trim(),email:ie.trim().toLowerCase(),phone:ne.trim()||void 0,smsConsent:te,isValid:ce&&X.trim().length>0,error:ce?X.trim()?void 0:"Missing name":"Invalid email"})}}return W},S=P=>{var O;const R=(O=P.target.files)==null?void 0:O[0];if(!R)return;const D=new FileReader;D.onload=U=>{var G;const W=(G=U.target)==null?void 0:G.result,V=w(W);if(V.length===0){i({title:"No data found",description:"The CSV file appears to be empty or in an unsupported format.",variant:"destructive"});return}c(V),g("preview")},D.readAsText(R)},C=async()=>{const P=o.filter(D=>D.isValid);if(P.length===0){i({title:"No valid users",description:"There are no valid users to import.",variant:"destructive"});return}const R=r||d||null;m(!0);try{const{data:{session:D}}=await q.auth.getSession(),O=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/bulk-create-users",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${D==null?void 0:D.access_token}`},body:JSON.stringify({users:P.map(W=>({firstName:W.firstName,lastName:W.lastName,email:W.email,phone:W.phone,smsConsent:W.smsConsent})),brokerageId:R})}),U=await O.json();if(!O.ok)throw new Error(U.error||"Failed to import users");y(U),g("result"),U.created>0&&a(),i({title:"Import Complete",description:`${U.created} user(s) created successfully.${U.failed>0?` ${U.failed} failed.`:""}`})}catch(D){console.error("Import error:",D),i({title:"Import Failed",description:D.message||"Failed to import users",variant:"destructive"})}finally{m(!1)}},E=o.filter(P=>P.isValid).length,I=o.filter(P=>!P.isValid).length;return e.jsx(zs,{open:s,onOpenChange:b,children:e.jsxs(Os,{className:"max-w-2xl max-h-[85vh] overflow-hidden flex flex-col",children:[e.jsxs(Us,{children:[e.jsxs(Bs,{className:"flex items-center gap-2",children:[e.jsx(ek,{className:"h-5 w-5"}),"Import Agents from CSV"]}),e.jsx(Ir,{children:"Upload a CSV file with agent information. Each row should contain First Name, Last Name, and Email."})]}),f==="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:S,className:"hidden"}),e.jsx(ni,{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($,{onClick:()=>{var P;return(P=l.current)==null?void 0:P.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."})]})]}),f==="preview"&&e.jsxs("div",{className:"flex-1 overflow-hidden flex flex-col space-y-4",children:[!r&&n&&n.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Assign to Brokerage (optional)"}),e.jsxs(ms,{value:d||"none",onValueChange:P=>u(P==="none"?"":P),children:[e.jsx(us,{children:e.jsx(fs,{placeholder:"Select a brokerage..."})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"none",children:"No brokerage"}),n.map(P=>e.jsx(Ge,{value:P.id,children:P.name},P.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(qr,{className:"h-4 w-4 text-green-500"}),e.jsxs("span",{children:[E," valid"]})]}),I>0&&e.jsxs("div",{className:"flex items-center gap-2 text-destructive",children:[e.jsx(ll,{className:"h-4 w-4"}),e.jsxs("span",{children:[I," invalid"]})]})]}),e.jsxs("div",{className:"flex-1 overflow-auto border rounded-lg",children:[e.jsxs(mi,{children:[e.jsx(fi,{children:e.jsxs(En,{className:"bg-muted/30",children:[e.jsx(Dt,{children:"First Name"}),e.jsx(Dt,{children:"Last Name"}),e.jsx(Dt,{children:"Email"}),e.jsx(Dt,{children:"Phone"}),e.jsx(Dt,{children:"SMS"}),e.jsx(Dt,{children:"Status"})]})}),e.jsx(pi,{children:o.slice(0,100).map((P,R)=>e.jsxs(En,{children:[e.jsx(wt,{children:P.firstName}),e.jsx(wt,{children:P.lastName}),e.jsx(wt,{children:P.email}),e.jsx(wt,{className:"text-muted-foreground",children:P.phone||"-"}),e.jsx(wt,{className:"text-muted-foreground",children:P.smsConsent===!0?"✓":P.smsConsent===!1?"✗":"-"}),e.jsx(wt,{children:P.isValid?e.jsx(Be,{variant:"default",className:"bg-green-500/10 text-green-600",children:"Valid"}):e.jsx(Be,{variant:"destructive",children:P.error||"Invalid"})})]},R))})]}),o.length>100&&e.jsxs("p",{className:"text-sm text-muted-foreground text-center py-2",children:["Showing first 100 of ",o.length," users"]})]})]}),f==="result"&&x&&e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"text-center",children:[e.jsx(qr,{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:[x.created," agent(s) created and invited"]}),x.failed>0&&e.jsxs("p",{className:"text-destructive mt-1",children:[x.failed," failed to create"]})]}),x.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:[x.errors.slice(0,10).map((P,R)=>e.jsxs("li",{children:["• ",P]},R)),x.errors.length>10&&e.jsxs("li",{children:["...and ",x.errors.length-10," more"]})]})]})]}),e.jsxs(Ar,{children:[f==="upload"&&e.jsx($,{variant:"outline",onClick:b,children:"Cancel"}),f==="preview"&&e.jsxs(e.Fragment,{children:[e.jsx($,{variant:"outline",onClick:v,children:"Back"}),e.jsx($,{onClick:C,disabled:h||E===0,children:h?e.jsxs(e.Fragment,{children:[e.jsx(kt,{className:"mr-2 h-4 w-4 animate-spin"}),"Importing..."]}):`Import ${E} Agent${E!==1?"s":""}`})]}),f==="result"&&e.jsx($,{onClick:b,children:"Done"})]})]})})};function Im({sortKey:s,currentSortKey:t,currentDirection:n,onSort:r,children:a,className:i,...l}){const o=t===s;return e.jsx(Dt,{className:Pt("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:()=>r(s),children:[a,o?n==="asc"?e.jsx(Zf,{className:"h-3.5 w-3.5 shrink-0"}):e.jsx(Dg,{className:"h-3.5 w-3.5 shrink-0"}):e.jsx(By,{className:"h-3.5 w-3.5 shrink-0 opacity-40"})]})})}function Nie(s=null,t=null){const[n,r]=j.useState(s),[a,i]=j.useState(t),l=j.useCallback(c=>{n===c?a==="asc"?i("desc"):a==="desc"?(r(null),i(null)):i("asc"):(r(c),i("asc"))},[n,a]),o=j.useCallback((c,d)=>{if(!n||!a||!d[n])return c;const u=d[n];return[...c].sort((h,m)=>{const f=u(h),g=u(m);if(f==null&&g==null)return 0;if(f==null)return 1;if(g==null)return-1;let x;return typeof f=="string"&&typeof g=="string"?x=f.localeCompare(g,void 0,{sensitivity:"base"}):x=f-g,a==="asc"?x:-x})},[n,a]);return{sortKey:n,sortDirection:a,handleSort:l,sortData:o}}const zhn=[{type:"custom",title:"Great job!",message:"Keep up the amazing work!",icon:Ja},{type:"custom",title:"You're on fire!",message:"Your dedication is inspiring!",icon:Kl},{type:"custom",title:"Congratulations!",message:"You earned this celebration!",icon:Ax}];function $Wt({open:s,onOpenChange:t,userId:n,userName:r}){const[a,i]=j.useState("custom"),[l,o]=j.useState(""),[c,d]=j.useState(""),u=DRs(),h=f=>{i(f.type),o(f.title),d(f.message)},m=async f=>{if(f.preventDefault(),!l.trim()){_a({title:"Title required",description:"Please enter a celebration title",variant:"destructive"});return}try{await u.mutateAsync({user_id:n,celebration_type:a,title:l.trim(),message:c.trim()||void 0}),_a({title:"Celebration sent! 🎉",description:`${r} will see confetti on their next visit!`}),t(!1),o(""),d(""),i("custom")}catch{_a({title:"Error",description:"Failed to send celebration",variant:"destructive"})}};return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Os,{className:"sm:max-w-md",children:[e.jsxs(Us,{children:[e.jsxs(Bs,{className:"flex items-center gap-2",children:[e.jsx(Ax,{className:"h-5 w-5 text-primary"}),"Send Celebration to ",r]}),e.jsx(Ir,{children:"They'll see confetti and this message next time they log in!"})]}),e.jsxs("div",{className:"mb-4",children:[e.jsx(ee,{className:"text-sm text-muted-foreground mb-2 block",children:"Quick presets:"}),e.jsx("div",{className:"flex gap-2 flex-wrap",children:zhn.map((f,g)=>e.jsxs($,{variant:"outline",size:"sm",onClick:()=>h(f),className:"text-xs",children:[e.jsx(f.icon,{className:"h-3 w-3 mr-1"}),f.title]},g))})]}),e.jsxs("form",{onSubmit:m,className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"type",children:"Celebration Type"}),e.jsxs(ms,{value:a,onValueChange:f=>i(f),children:[e.jsx(us,{children:e.jsx(fs,{})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"custom",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ja,{className:"h-4 w-4"})," Custom"]})}),e.jsx(Ge,{value:"points_earned",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Kl,{className:"h-4 w-4"})," Points Earned"]})}),e.jsx(Ge,{value:"listing_created",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(va,{className:"h-4 w-4"})," Listing Created"]})}),e.jsx(Ge,{value:"deal_closed",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ru,{className:"h-4 w-4"})," Deal Closed"]})})]})]})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"title",children:"Title *"}),e.jsx(pe,{id:"title",value:l,onChange:f=>o(f.target.value),placeholder:"e.g., Congratulations!",maxLength:100})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"message",children:"Message (optional)"}),e.jsx(Rs,{id:"message",value:c,onChange:f=>d(f.target.value),placeholder:"Add a personal message...",rows:3,maxLength:500})]}),e.jsxs("div",{className:"flex gap-2 justify-end",children:[e.jsx($,{type:"button",variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsxs($,{type:"submit",disabled:u.isPending,children:[e.jsx(Ax,{className:"h-4 w-4 mr-2"}),u.isPending?"Sending...":"Send Celebration"]})]})]})]})})}const r9e={points_earned:{label:"Points Earned",icon:Kl,color:"bg-yellow-500"},listing_created:{label:"Listing Created",icon:va,color:"bg-blue-500"},deal_closed:{label:"Deal Closed",icon:ru,color:"bg-green-500"},custom:{label:"Custom",icon:Nn,color:"bg-purple-500"}};function Bhn(){const[s,t]=j.useState(""),[n,r]=j.useState("all"),[a,i]=j.useState("all"),{data:l=[],isLoading:o}=tt({queryKey:["admin-celebrations"],queryFn:async()=>{const{data:u,error:h}=await q.from("celebration_queue").select("*").order("created_at",{ascending:!1}).limit(500);if(h)throw h;const m=[...new Set([...u.map(x=>x.user_id),...u.map(x=>x.created_by).filter(Boolean)])],{data:f}=await q.from("profiles").select("id, name, email").in("id",m),g=new Map((f==null?void 0:f.map(x=>[x.id,x]))||[]);return u.map(x=>{var y,v,b;return{...x,user_name:((y=g.get(x.user_id))==null?void 0:y.name)||"Unknown",user_email:((v=g.get(x.user_id))==null?void 0:v.email)||"",creator_name:x.created_by?((b=g.get(x.created_by))==null?void 0:b.name)||"System":"Auto-triggered"}})}}),c=l.filter(u=>{var g,x;const h=((g=u.user_name)==null?void 0:g.toLowerCase().includes(s.toLowerCase()))||((x=u.user_email)==null?void 0:x.toLowerCase().includes(s.toLowerCase()))||u.title.toLowerCase().includes(s.toLowerCase()),m=n==="all"||u.celebration_type===n,f=a==="all"||a==="seen"&&u.seen_at||a==="unseen"&&!u.seen_at;return h&&m&&f}),d={total:l.length,seen:l.filter(u=>u.seen_at).length,unseen:l.filter(u=>!u.seen_at).length,byType:Object.keys(r9e).reduce((u,h)=>(u[h]=l.filter(m=>m.celebration_type===h).length,u),{})};return o?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(kt,{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(Ne,{children:[e.jsx(Ct,{className:"pb-2",children:e.jsx(At,{className:"text-sm font-medium",children:"Total Celebrations"})}),e.jsx(Ie,{children:e.jsx("div",{className:"text-2xl font-bold",children:d.total})})]}),e.jsxs(Ne,{children:[e.jsx(Ct,{className:"pb-2",children:e.jsx(At,{className:"text-sm font-medium text-green-600",children:"Seen"})}),e.jsx(Ie,{children:e.jsx("div",{className:"text-2xl font-bold text-green-600",children:d.seen})})]}),e.jsxs(Ne,{children:[e.jsx(Ct,{className:"pb-2",children:e.jsx(At,{className:"text-sm font-medium text-orange-600",children:"Pending"})}),e.jsx(Ie,{children:e.jsx("div",{className:"text-2xl font-bold text-orange-600",children:d.unseen})})]}),e.jsxs(Ne,{children:[e.jsx(Ct,{className:"pb-2",children:e.jsx(At,{className:"text-sm font-medium text-purple-600",children:"Custom Sent"})}),e.jsx(Ie,{children:e.jsx("div",{className:"text-2xl font-bold text-purple-600",children:d.byType.custom||0})})]})]}),e.jsxs(Ne,{children:[e.jsxs(Ct,{children:[e.jsxs(At,{className:"flex items-center gap-2",children:[e.jsx(Ax,{className:"h-5 w-5"}),"Celebration History"]}),e.jsx(Gn,{children:"View all celebrations awarded to agents"})]}),e.jsxs(Ie,{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(Kr,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(pe,{placeholder:"Search by agent name, email, or title...",value:s,onChange:u=>t(u.target.value),className:"pl-9"})]}),e.jsxs(ms,{value:n,onValueChange:r,children:[e.jsx(us,{className:"w-[180px]",children:e.jsx(fs,{placeholder:"Filter by type"})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"all",children:"All Types"}),Object.entries(r9e).map(([u,h])=>e.jsx(Ge,{value:u,children:h.label},u))]})]}),e.jsxs(ms,{value:a,onValueChange:i,children:[e.jsx(us,{className:"w-[140px]",children:e.jsx(fs,{placeholder:"Status"})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"all",children:"All Status"}),e.jsx(Ge,{value:"seen",children:"Seen"}),e.jsx(Ge,{value:"unseen",children:"Pending"})]})]})]}),e.jsx("div",{className:"rounded-md border",children:e.jsxs(mi,{children:[e.jsx(fi,{children:e.jsxs(En,{children:[e.jsx(Dt,{children:"Type"}),e.jsx(Dt,{children:"Agent"}),e.jsx(Dt,{children:"Title"}),e.jsx(Dt,{children:"Points"}),e.jsx(Dt,{children:"Created By"}),e.jsx(Dt,{children:"Created"}),e.jsx(Dt,{children:"Status"})]})}),e.jsx(pi,{children:c.length===0?e.jsx(En,{children:e.jsx(wt,{colSpan:7,className:"text-center py-8 text-muted-foreground",children:"No celebrations found"})}):c.map(u=>{const h=r9e[u.celebration_type],m=h.icon;return e.jsxs(En,{children:[e.jsx(wt,{children:e.jsxs(Be,{variant:"outline",className:"gap-1",children:[e.jsx(m,{className:"h-3 w-3"}),h.label]})}),e.jsx(wt,{children:e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:u.user_name}),e.jsx("div",{className:"text-xs text-muted-foreground",children:u.user_email})]})}),e.jsx(wt,{children:e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:u.title}),u.message&&e.jsx("div",{className:"text-xs text-muted-foreground truncate max-w-[200px]",children:u.message})]})}),e.jsx(wt,{children:u.points_amount?e.jsxs(Be,{variant:"secondary",children:["+",u.points_amount]}):e.jsx("span",{className:"text-muted-foreground",children:"-"})}),e.jsx(wt,{children:e.jsx("span",{className:"text-sm text-muted-foreground",children:u.creator_name})}),e.jsx(wt,{children:e.jsx("span",{className:"text-sm text-muted-foreground",children:en(new Date(u.created_at),"MMM d, yyyy h:mm a")})}),e.jsx(wt,{children:u.seen_at?e.jsx(Be,{variant:"outline",className:"bg-green-50 text-green-700 border-green-200",children:"Seen"}):e.jsx(Be,{variant:"outline",className:"bg-orange-50 text-orange-700 border-orange-200",children:"Pending"})})]},u.id)})})]})}),c.length>0&&e.jsxs("p",{className:"text-sm text-muted-foreground text-right",children:["Showing ",c.length," of ",l.length," celebrations"]})]})]})]})}const $hn=()=>{const{user:s}=vs(),{toast:t}=Bi(),[n,r]=j.useState([]),[a,i]=j.useState(!0),[l,o]=j.useState(!1),[c,d]=j.useState("all"),[u,h]=j.useState("all"),[m,f]=j.useState("new"),[g,x]=j.useState(new Set),y=j.useCallback(async()=>{try{i(!0);const{data:W,error:V}=await q.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(V)throw V;const{data:G,error:Y}=await q.from("trial_email_exports").select("user_id");if(Y)throw Y;const X=new Set((G||[]).map(ie=>ie.user_id)),ae=(W||[]).map(ie=>({...ie,converted_from_trial_at:ie.converted_from_trial_at??null,already_exported:X.has(ie.id)}));ae.sort((ie,ne)=>new Date(ne.created_at).getTime()-new Date(ie.created_at).getTime()),r(ae)}catch(W){console.error("Error loading trial users:",W),t({title:"Error",description:"Failed to load trial users",variant:"destructive"})}finally{i(!1)}},[t]);j.useEffect(()=>{y()},[y]);const v=W=>W.trial_started_at?"ghl":"stripe",b=W=>W.trial_expires_at?W.trial_expires_at:W.subscription_end_date?W.subscription_end_date:null,w=W=>W.converted_from_trial_at!==null,S=W=>{if(w(W))return!1;const V=b(W);return V?new Date(V).getTime()<=Date.now():!1},C=n.filter(W=>!(c!=="all"&&v(W)!==c||u==="active"&&(S(W)||w(W))||u==="expired"&&!S(W)||u==="converted"&&!w(W)||m==="new"&&W.already_exported||m==="exported"&&!W.already_exported)),E=()=>{g.size===C.length?x(new Set):x(new Set(C.map(W=>W.id)))},I=W=>{const V=new Set(g);V.has(W)?V.delete(W):V.add(W),x(V)},P=async()=>{if(g.size===0){t({title:"No users selected",description:"Select users to export",variant:"destructive"});return}o(!0);try{const W=n.filter(te=>g.has(te.id)),V="First Name,Last Name,Email,Phone,Trial Type,Status,Signup Date,Expiry Date",G=W.map(te=>{const J=(te.name||"").split(" "),ce=J[0]||"",_e=J.slice(1).join(" ")||"",he=v(te)==="stripe"?"Credit Card Trial":"Free Trial (No CC)",ue=w(te)?"Converted":S(te)?"Expired":"Active",ve=te.created_at?new Date(te.created_at).toLocaleDateString():"",Ee=b(te)?new Date(b(te)).toLocaleDateString():"";return`"${ce}","${_e}","${te.email}","${te.phone||""}","${he}","${ue}","${ve}","${Ee}"`}),Y=[V,...G].join(` `),X=new Blob([Y],{type:"text/csv"}),ae=URL.createObjectURL(X),ie=document.createElement("a");ie.href=ae,ie.download=`trial-users-${new Date().toISOString().split("T")[0]}.csv`,ie.click(),URL.revokeObjectURL(ae);const ne=W.filter(te=>!te.already_exported).map(te=>({user_id:te.id,exported_by:s.id}));if(ne.length>0){const{error:te}=await q.from("trial_email_exports").upsert(ne,{onConflict:"user_id"});te&&console.error("Error marking exports:",te)}t({title:"Export complete",description:`Downloaded ${W.length} trial user(s). ${ne.length} newly marked as exported.`}),x(new Set),y()}catch(W){console.error("Export error:",W),t({title:"Error",description:"Failed to export",variant:"destructive"})}finally{o(!1)}},R=n.filter(W=>!W.already_exported).length,D=n.filter(W=>W.already_exported).length,O=n.filter(W=>w(W)).length,U=n.filter(W=>!S(W)&&!w(W)).length;return a?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(kt,{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(Ne,{children:e.jsxs(Ct,{className:"pb-2",children:[e.jsx(Gn,{children:"Total"}),e.jsx(At,{className:"text-2xl",children:n.length})]})}),e.jsx(Ne,{children:e.jsxs(Ct,{className:"pb-2",children:[e.jsx(Gn,{children:"New (Not Exported)"}),e.jsx(At,{className:"text-2xl text-green-600",children:R})]})}),e.jsx(Ne,{children:e.jsxs(Ct,{className:"pb-2",children:[e.jsx(Gn,{children:"Active Trials"}),e.jsx(At,{className:"text-2xl",children:U})]})}),e.jsx(Ne,{children:e.jsxs(Ct,{className:"pb-2",children:[e.jsx(Gn,{children:"Converted 🎉"}),e.jsx(At,{className:"text-2xl text-primary",children:O})]})}),e.jsx(Ne,{children:e.jsxs(Ct,{className:"pb-2",children:[e.jsx(Gn,{children:"Already Exported"}),e.jsx(At,{className:"text-2xl text-muted-foreground",children:D})]})})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsxs(ms,{value:m,onValueChange:W=>f(W),children:[e.jsx(us,{className:"w-[160px]",children:e.jsx(fs,{})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"all",children:"All Users"}),e.jsx(Ge,{value:"new",children:"New Only"}),e.jsx(Ge,{value:"exported",children:"Already Exported"})]})]}),e.jsxs(ms,{value:c,onValueChange:W=>d(W),children:[e.jsx(us,{className:"w-[180px]",children:e.jsx(fs,{})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"all",children:"All Trial Types"}),e.jsx(Ge,{value:"stripe",children:"Credit Card Trial"}),e.jsx(Ge,{value:"ghl",children:"Free Trial (No CC)"})]})]}),e.jsxs(ms,{value:u,onValueChange:W=>h(W),children:[e.jsx(us,{className:"w-[160px]",children:e.jsx(fs,{})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"all",children:"All Statuses"}),e.jsx(Ge,{value:"active",children:"Active Trial"}),e.jsx(Ge,{value:"expired",children:"Expired"}),e.jsx(Ge,{value:"converted",children:"Converted ✓"})]})]}),e.jsx("div",{className:"ml-auto",children:e.jsxs($,{onClick:P,disabled:l||g.size===0,children:[l?e.jsx(kt,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(di,{className:"h-4 w-4 mr-2"}),"Export Selected (",g.size,")"]})})]}),e.jsx("div",{className:"border rounded-lg",children:e.jsxs(mi,{children:[e.jsx(fi,{children:e.jsxs(En,{className:"bg-muted/30 hover:bg-muted/30",children:[e.jsx(Dt,{className:"w-[40px]",children:e.jsx(ai,{checked:C.length>0&&g.size===C.length,onCheckedChange:E})}),e.jsx(Dt,{children:"Name"}),e.jsx(Dt,{children:"Email"}),e.jsx(Dt,{children:"Trial Type"}),e.jsx(Dt,{children:"Status"}),e.jsx(Dt,{children:"Signup Date"}),e.jsx(Dt,{children:"Last Login"}),e.jsx(Dt,{children:"Expires / Renews"}),e.jsx(Dt,{children:"Exported"})]})}),e.jsx(pi,{children:C.length===0?e.jsx(En,{children:e.jsx(wt,{colSpan:9,className:"text-center py-8 text-muted-foreground",children:"No trial users match the current filters"})}):C.map(W=>{const V=v(W),G=w(W),Y=S(W),X=b(W);return e.jsxs(En,{className:`hover:bg-muted/30 ${G?"bg-primary/5":""}`,children:[e.jsx(wt,{children:e.jsx(ai,{checked:g.has(W.id),onCheckedChange:()=>I(W.id)})}),e.jsx(wt,{className:"font-medium",children:e.jsxs("div",{className:"flex items-center gap-2",children:[W.name,G&&e.jsx(Yl,{className:"h-3.5 w-3.5 text-primary"})]})}),e.jsx(wt,{className:"text-muted-foreground",children:W.email}),e.jsx(wt,{children:V==="stripe"?e.jsxs(Be,{variant:"outline",className:"gap-1",children:[e.jsx(Cv,{className:"h-3 w-3"}),"Credit Card"]}):e.jsxs(Be,{variant:"secondary",className:"gap-1",children:[e.jsx(mn,{className:"h-3 w-3"}),"Free (No CC)"]})}),e.jsx(wt,{children:G?e.jsxs(Be,{className:"bg-primary/10 text-primary hover:bg-primary/20 gap-1",children:[e.jsx(Yl,{className:"h-3 w-3"}),"Converted"]}):Y?e.jsx(Be,{variant:"destructive",children:"Expired"}):e.jsx(Be,{className:"bg-green-500/10 text-green-600 hover:bg-green-500/20",children:"Active Trial"})}),e.jsx(wt,{className:"text-sm",children:W.created_at?new Date(W.created_at).toLocaleDateString():"—"}),e.jsx(wt,{className:"text-sm",children:W.last_login?e.jsxs("div",{className:"flex flex-col",children:[e.jsx("span",{children:new Date(W.last_login).toLocaleDateString()}),e.jsx("span",{className:"text-xs text-muted-foreground",children:new Date(W.last_login).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})})]}):e.jsx("span",{className:"text-muted-foreground",children:"Never"})}),e.jsx(wt,{className:"text-sm",children:G&&X?e.jsxs("span",{className:"text-muted-foreground",children:["Renews ",new Date(X).toLocaleDateString()]}):X?new Date(X).toLocaleDateString():"—"}),e.jsx(wt,{children:W.already_exported?e.jsx(qr,{className:"h-4 w-4 text-muted-foreground"}):e.jsx(Be,{variant:"outline",className:"text-green-600 border-green-300",children:"New"})})]},W.id)})})]})}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Showing ",C.length," of ",n.length," trial users · ",O," converted to paid"]})]})},Uhn=s=>s==null?'""':`"${String(s).replace(/"/g,'""')}"`,qhn=()=>{const[s,t]=j.useState([]),[n,r]=j.useState(!0);j.useEffect(()=>{(async()=>{const{data:l,error:o}=await q.from("user_deletion_log").select("*").order("created_at",{ascending:!1});!o&&l&&t(l),r(!1)})()},[]);const a=()=>{if(s.length===0){re.info("No deletion records to export");return}const i=["Date","Deleted User","Deleted Email","Brokerage","Type","Deleted By"],l=s.map(h=>[en(new Date(h.created_at),"MMM d, yyyy h:mm a"),h.deleted_user_name||"—",h.deleted_user_email||"—",h.brokerage_name||"—",h.deletion_type==="deleted"?"Account Deleted":"Removed",h.deleted_by_name||h.deleted_by_email||"—"]),o=[i.join(","),...l.map(h=>h.map(Uhn).join(","))].join(` `),c=new Blob([o],{type:"text/csv"}),d=URL.createObjectURL(c),u=document.createElement("a");u.href=d,u.download=`deletion-log-${new Date().toISOString().split("T")[0]}.csv`,u.click(),URL.revokeObjectURL(d),re.success(`Exported ${s.length} deletion record(s)`)};return n?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(kt,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):s.length===0?e.jsx(Ne,{children:e.jsxs(Ie,{className:"py-12 text-center text-muted-foreground",children:[e.jsx(Wn,{className:"h-10 w-10 mx-auto mb-3 opacity-40"}),e.jsx("p",{children:"No deletion records yet"})]})}):e.jsxs(Ne,{children:[e.jsxs(Ct,{className:"flex flex-row items-center justify-between",children:[e.jsx(At,{className:"text-lg",children:"User Deletion History"}),e.jsxs($,{variant:"outline",size:"sm",onClick:a,children:[e.jsx(di,{className:"h-4 w-4 mr-2"}),"Export CSV"]})]}),e.jsx(Ie,{children:e.jsxs(mi,{children:[e.jsx(fi,{children:e.jsxs(En,{children:[e.jsx(Dt,{children:"Date"}),e.jsx(Dt,{children:"User"}),e.jsx(Dt,{children:"Email"}),e.jsx(Dt,{children:"Brokerage"}),e.jsx(Dt,{children:"Type"}),e.jsx(Dt,{children:"Deleted By"})]})}),e.jsx(pi,{children:s.map(i=>e.jsxs(En,{children:[e.jsx(wt,{className:"whitespace-nowrap text-sm",children:en(new Date(i.created_at),"MMM d, yyyy h:mm a")}),e.jsx(wt,{className:"font-medium",children:i.deleted_user_name||"—"}),e.jsx(wt,{className:"text-sm text-muted-foreground",children:i.deleted_user_email||"—"}),e.jsx(wt,{children:i.brokerage_name||"—"}),e.jsx(wt,{children:e.jsx(Be,{variant:i.deletion_type==="deleted"?"destructive":"secondary",children:i.deletion_type==="deleted"?"Account Deleted":"Removed"})}),e.jsx(wt,{className:"text-sm",children:i.deleted_by_name||i.deleted_by_email||"—"})]},i.id))})]})})]})},m3=s=>{const{user:t}=vs(),n=Vt(),r=tt({queryKey:["teams",s],queryFn:async()=>{let h=q.from("teams").select("*").order("created_at",{ascending:!1});s&&(h=h.eq("brokerage_id",s));const{data:m,error:f}=await h;if(f)throw f;return m||[]},enabled:!!t}),a=h=>tt({queryKey:["team-members",h],queryFn:async()=>{const{data:m,error:f}=await q.from("team_members").select("*").eq("team_id",h).order("role",{ascending:!0});if(f)throw f;const g=(m||[]).map(v=>v.user_id),{data:x}=await q.from("profiles").select("id, name, email, avatar_url").in("id",g),y=new Map((x||[]).map(v=>[v.id,v]));return(m||[]).map(v=>({...v,profile:y.get(v.user_id)||null}))},enabled:!!h}),i=ft({mutationFn:async h=>{const m={name:h.name,created_by:t.id,description:h.description,contact_visibility:h.contact_visibility,lead_pond_enabled:h.lead_pond_enabled,shared_assets_enabled:h.shared_assets_enabled};h.brokerage_id&&(m.brokerage_id=h.brokerage_id);const{data:f,error:g}=await q.from("teams").insert(m).select().single();if(g)throw g;return f},onSuccess:()=>{n.invalidateQueries({queryKey:["teams"]}),re.success("Team created!")},onError:h=>{re.error("Failed to create team: "+h.message)}}),l=ft({mutationFn:async({id:h,...m})=>{const{data:f,error:g}=await q.from("teams").update(m).eq("id",h).select().single();if(g)throw g;return f},onSuccess:()=>{n.invalidateQueries({queryKey:["teams"]}),re.success("Team updated")},onError:h=>{re.error("Failed to update team: "+h.message)}}),o=ft({mutationFn:async h=>{const{error:m}=await q.from("teams").delete().eq("id",h);if(m)throw m},onSuccess:()=>{n.invalidateQueries({queryKey:["teams"]}),re.success("Team deleted")},onError:h=>{re.error("Failed to delete team: "+h.message)}}),c=ft({mutationFn:async h=>{const{data:m,error:f}=await q.from("team_members").insert({team_id:h.team_id,user_id:h.user_id,role:h.role||"team_member"}).select().single();if(f)throw f.message.includes("duplicate")||f.message.includes("unique")?new Error("This agent is already on this team."):f;return m},onSuccess:(h,m)=>{n.invalidateQueries({queryKey:["team-members",m.team_id]}),re.success("Member added to team")},onError:h=>{re.error(h.message)}}),d=ft({mutationFn:async h=>{const{error:m}=await q.from("team_members").delete().eq("id",h.member_id);if(m)throw m},onSuccess:(h,m)=>{n.invalidateQueries({queryKey:["team-members",m.team_id]}),re.success("Member removed from team")},onError:h=>{re.error("Failed to remove member: "+h.message)}}),u=ft({mutationFn:async h=>{const{error:m}=await q.from("team_members").update({role:h.role}).eq("id",h.member_id);if(m)throw m},onSuccess:(h,m)=>{n.invalidateQueries({queryKey:["team-members",m.team_id]}),re.success("Member role updated")},onError:h=>{re.error("Failed to update role: "+h.message)}});return{teams:r.data||[],isLoading:r.isLoading,createTeam:i,updateTeam:l,deleteTeam:o,addMember:c,removeMember:d,updateMemberRole:u,useTeamMembers:a}},Vrt=s=>{const t=Vt(),n=tt({queryKey:["team-ponds",s],queryFn:async()=>{const{data:o,error:c}=await q.rpc("get_team_ponds",{_team_id:s});if(c)throw c;return o||[]},enabled:!!s}),r=()=>{t.invalidateQueries({queryKey:["team-ponds"]}),t.invalidateQueries({queryKey:["lead-pond"]})},a=ft({mutationFn:async o=>{const{data:c,error:d}=await q.from("team_ponds").insert({team_id:s,name:o.name,description:o.description||null}).select().single();if(d)throw d;return c},onSuccess:()=>{r(),re.success("Pond created")},onError:o=>re.error(o.message)}),i=ft({mutationFn:async({id:o,...c})=>{const{error:d}=await q.from("team_ponds").update(c).eq("id",o);if(d)throw d},onSuccess:()=>{r(),re.success("Pond updated")},onError:o=>re.error(o.message)}),l=ft({mutationFn:async o=>{const{error:c}=await q.from("team_ponds").delete().eq("id",o);if(c)throw c},onSuccess:()=>{r(),re.success("Pond deleted")},onError:o=>re.error(o.message)});return{ponds:n.data||[],isLoading:n.isLoading,createPond:a,updatePond:i,deletePond:l}},Vhn=s=>{const t=Vt(),n=tt({queryKey:["pond-assignments",s],queryFn:async()=>{const{data:a,error:i}=await q.from("team_pond_members").select("id, user_id").eq("pond_id",s);if(i)throw i;return a||[]},enabled:!!s}),r=ft({mutationFn:async a=>{if(a.assigned){const{error:i}=await q.from("team_pond_members").insert({pond_id:s,user_id:a.user_id});if(i&&!i.message.includes("duplicate"))throw i}else{const{error:i}=await q.from("team_pond_members").delete().eq("pond_id",s).eq("user_id",a.user_id);if(i)throw i}},onSuccess:()=>{t.invalidateQueries({queryKey:["pond-assignments",s]}),t.invalidateQueries({queryKey:["team-ponds"]}),t.invalidateQueries({queryKey:["lead-pond"]})},onError:a=>re.error(a.message)});return{assignedUserIds:(n.data||[]).map(a=>a.user_id),isLoading:n.isLoading,setAssigned:r}},Hhn=({pond:s,teamId:t})=>{const{useTeamMembers:n}=m3(),{data:r=[],isLoading:a}=n(t),{assignedUserIds:i,isLoading:l,setAssigned:o}=Vhn(s.id);return a||l?e.jsx(yn,{className:"h-16 w-full"}):e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[e.jsx(Zn,{className:"h-3.5 w-3.5"}),i.length===0?"Open to everyone on the team (no agents assigned)":`${i.length} agent${i.length===1?"":"s"} assigned`]}),e.jsx("div",{className:"grid gap-2 sm:grid-cols-2",children:r.map(c=>{var u,h;const d=i.includes(c.user_id);return e.jsxs("label",{className:"flex cursor-pointer items-center gap-2 rounded-md border p-2 text-sm",children:[e.jsx(ai,{checked:d,onCheckedChange:m=>o.mutate({user_id:c.user_id,assigned:!!m})}),e.jsx("span",{className:"truncate",children:((u=c.profile)==null?void 0:u.name)||((h=c.profile)==null?void 0:h.email)||"Unknown"}),c.role==="team_leader"&&e.jsx(Be,{variant:"secondary",className:"ml-auto text-[10px]",children:"Leader"})]},c.id)})})]})},UWt=({teamId:s})=>{const{ponds:t,isLoading:n,createPond:r,updatePond:a,deletePond:i}=Vrt(s),[l,o]=j.useState(!1),[c,d]=j.useState(""),[u,h]=j.useState(""),[m,f]=j.useState(null),[g,x]=j.useState(null),y=async()=>{c.trim()&&(await r.mutateAsync({name:c.trim(),description:u.trim()}),d(""),h(""),o(!1))};return e.jsxs(Ne,{children:[e.jsxs(Ct,{className:"flex flex-row items-start justify-between gap-4 space-y-0",children:[e.jsxs("div",{children:[e.jsx(At,{className:"text-lg",children:"Lead Ponds"}),e.jsx(Gn,{children:"Create multiple ponds (by area, source, or specialty) and assign which agents can see each one."})]}),e.jsxs($,{size:"sm",onClick:()=>o(!0),children:[e.jsx(dn,{className:"mr-1 h-4 w-4"})," New Pond"]})]}),e.jsxs(Ie,{className:"space-y-3",children:[n&&e.jsx(yn,{className:"h-20 w-full"}),!n&&t.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"No ponds yet. Create your first pond to start sharing leads with the team."}),t.map(v=>e.jsxs("div",{className:"rounded-lg border p-3 space-y-3",children:[e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-2",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(b1,{className:"h-4 w-4 text-primary"}),e.jsx("p",{className:"font-medium",children:v.name}),v.is_default&&e.jsx(Be,{variant:"secondary",className:"text-[10px]",children:"Default"})]}),v.description&&e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:v.description}),e.jsxs("div",{className:"mt-1 flex flex-wrap gap-2 text-[11px] text-muted-foreground",children:[e.jsxs("span",{children:[v.available_count," available"]}),e.jsx("span",{children:"·"}),e.jsxs("span",{children:[v.claimed_count," claimed"]})]})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsxs($,{size:"sm",variant:"ghost",onClick:()=>x(g===v.id?null:v.id),children:[e.jsx(Zn,{className:"mr-1 h-3.5 w-3.5"}),g===v.id?"Hide agents":"Assign agents"]}),e.jsx($,{size:"icon",variant:"ghost",onClick:()=>f(v),children:e.jsx(gi,{className:"h-3.5 w-3.5"})}),e.jsx($,{size:"icon",variant:"ghost",onClick:()=>{confirm(`Delete "${v.name}"? Leads in this pond will no longer be shared.`)&&i.mutate(v.id)},children:e.jsx(Wn,{className:"h-3.5 w-3.5 text-destructive"})})]})]}),g===v.id&&e.jsx(Hhn,{pond:v,teamId:s})]},v.id))]}),e.jsx(zs,{open:l,onOpenChange:o,children:e.jsxs(Os,{children:[e.jsxs(Us,{children:[e.jsx(Bs,{children:"New Lead Pond"}),e.jsx(Ir,{children:"Leave agents unassigned to make the pond open to the whole team."})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Pond name"}),e.jsx(pe,{value:c,onChange:v=>d(v.target.value),placeholder:"e.g. Northland Buyers"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Description (optional)"}),e.jsx(pe,{value:u,onChange:v=>h(v.target.value),placeholder:"What kind of leads go in this pond?"})]})]}),e.jsxs(Ar,{children:[e.jsx($,{variant:"outline",onClick:()=>o(!1),children:"Cancel"}),e.jsx($,{onClick:y,disabled:!c.trim()||r.isPending,children:"Create Pond"})]})]})}),e.jsx(zs,{open:!!m,onOpenChange:v=>!v&&f(null),children:e.jsxs(Os,{children:[e.jsx(Us,{children:e.jsx(Bs,{children:"Edit Pond"})}),m&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Pond name"}),e.jsx(pe,{value:m.name,onChange:v=>f({...m,name:v.target.value})})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Description"}),e.jsx(pe,{value:m.description||"",onChange:v=>f({...m,description:v.target.value})})]})]}),e.jsxs(Ar,{children:[e.jsx($,{variant:"outline",onClick:()=>f(null),children:"Cancel"}),e.jsx($,{onClick:async()=>{m&&(await a.mutateAsync({id:m.id,name:m.name,description:m.description||""}),f(null))},disabled:a.isPending,children:"Save"})]})]})})]})},Ghn=(s,t=!0)=>tt({queryKey:["lead-pond-activity",s],queryFn:async()=>{const{data:n,error:r}=await q.rpc("get_lead_pond_activity",{_lead_pond_id:s});if(r)throw r;return n||[]},enabled:!!s&&t}),Whn=()=>{const{user:s}=vs();return tt({queryKey:["team-contacts",s==null?void 0:s.id],queryFn:async()=>{const{data:t,error:n}=await q.rpc("get_team_contacts",{_user_id:s.id});if(n)throw n;return t||[]},enabled:!!s})},qWt=(s,t)=>{const{user:n}=vs(),r=Vt(),a=tt({queryKey:["lead-pond",s,t||"all"],queryFn:async()=>{const{data:c,error:d}=await q.rpc("get_team_lead_pond",{_team_id:s,_pond_id:t||null});if(d)throw d;return(c||[]).map(u=>({id:u.id,team_id:u.team_id,pond_id:u.pond_id,pond_name:u.pond_name,contact_id:u.contact_id,added_by:u.added_by,claimed_by:u.claimed_by,claimed_at:u.claimed_at,returned_at:u.returned_at,notes:u.notes,created_at:u.created_at,status:u.claimed_by?"claimed":"available",contact:{first_name:u.first_name,last_name:u.last_name,email:u.email,phone:u.phone,address:u.address,lead_source:u.lead_source,notes:u.contact_notes},contributor:{name:u.contributor_name,avatar_url:u.contributor_avatar_url},claimer:u.claimed_by?{name:u.claimer_name,avatar_url:u.claimer_avatar_url}:null,touch_count:u.touch_count??0,last_activity_at:u.last_activity_at,can_view_activity:!!u.can_view_activity}))},enabled:!!s&&!!n}),i=ft({mutationFn:async c=>{const{data:d,error:u}=await q.rpc("add_to_lead_pond",{_contact_id:c.contact_id,_team_id:c.team_id,_notes:c.notes||null,_pond_id:c.pond_id||null});if(u)throw u;return d},onSuccess:()=>{r.invalidateQueries({queryKey:["lead-pond"]}),re.success("Contact added to Lead Pond")},onError:c=>{re.error(c.message)}}),l=ft({mutationFn:async c=>{const{error:d}=await q.rpc("claim_lead_pond_contact",{_lead_pond_id:c});if(d)throw d},onSuccess:()=>{r.invalidateQueries({queryKey:["lead-pond"]}),r.invalidateQueries({queryKey:["innercircle-contacts"]}),r.invalidateQueries({queryKey:["contacts"]}),r.invalidateQueries({queryKey:["contact-custom-tags"]}),re.success("Lead claimed and added to your contacts, tagged with the pond name. Your notes and follow-ups stay visible to your team leader and the agent who shared it.")},onError:c=>{re.error(c.message)}}),o=ft({mutationFn:async c=>{const{error:d}=await q.rpc("return_lead_pond_contact",{_lead_pond_id:c});if(d)throw d},onSuccess:()=>{r.invalidateQueries({queryKey:["lead-pond"]}),re.success("Lead returned to pond")},onError:c=>{re.error(c.message)}});return{leadPondItems:a.data||[],isLoading:a.isLoading,addToLeadPond:i,claimLead:l,returnLead:o}},Khn=(s,t,n=100)=>tt({queryKey:["team-pond-history",s,t||"all",n],queryFn:async()=>{const{data:r,error:a}=await q.rpc("get_team_pond_history",{_team_id:s,_pond_id:t||null,_limit:n});if(a)throw a;return r||[]},enabled:!!s}),Yhn=()=>{const s=Vt();return ft({mutationFn:async t=>{const{data:n,error:r}=await q.rpc("transfer_contact",{_contact_id:t.contactId,_to_user_id:t.toUserId,_notes:t.notes||null});if(r)throw r;const a=n;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"]}),re.success("Contact transferred successfully")},onError:t=>{re.error(t.message||"Failed to transfer contact")}})};function VWt({open:s,onOpenChange:t,contactIds:n,contactNames:r=[],onComplete:a}){var C;const{user:i}=vs(),{data:l}=Hw(),{useTeamMembers:o}=m3(),{data:c=[]}=o((l==null?void 0:l.teamId)||""),d=Yhn(),[u,h]=j.useState(null),[m,f]=j.useState(""),[g,x]=j.useState(!1),y=c.filter(E=>E.user_id!==(i==null?void 0:i.id)),v=async()=>{if(u){x(!0);try{for(const E of n)await d.mutateAsync({contactId:E,toUserId:u,notes:m||void 0});t(!1),h(null),f(""),a==null||a()}catch{}finally{x(!1)}}},b=y.find(E=>E.user_id===u),w=n.length>1,S=r.length>0?w?`${r.length} contacts`:r[0]:w?`${n.length} contacts`:"this contact";return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Os,{className:"sm:max-w-md",children:[e.jsxs(Us,{children:[e.jsxs(Bs,{className:"flex items-center gap-2",children:[e.jsx(E4,{className:"h-5 w-5"}),"Transfer ",S]}),e.jsxs(Ir,{children:["Select a team member to transfer ",w?"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(ee,{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:y.length===0?e.jsx("p",{className:"text-sm text-muted-foreground py-4 text-center",children:"No other team members available"}):y.map(E=>{var I,P,R;return e.jsxs("button",{onClick:()=>h(E.user_id),className:`w-full flex items-center gap-3 p-3 rounded-lg text-left transition-colors ${u===E.user_id?"bg-primary/10 border border-primary/30":"hover:bg-accent border border-transparent"}`,children:[e.jsxs(Oa,{className:"h-8 w-8",children:[e.jsx(Li,{src:((I=E.profile)==null?void 0:I.avatar_url)||""}),e.jsx(za,{className:"text-xs",children:(((P=E.profile)==null?void 0:P.name)||"?").charAt(0).toUpperCase()})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",children:((R=E.profile)==null?void 0:R.name)||"Unknown"}),e.jsx("p",{className:"text-xs text-muted-foreground capitalize",children:E.role.replace("_"," ")})]})]},E.user_id)})})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"transfer-notes",className:"text-sm font-medium",children:"Notes (optional)"}),e.jsx(Rs,{id:"transfer-notes",value:m,onChange:E=>f(E.target.value),placeholder:"Reason for transfer...",className:"mt-1",rows:2})]})]}),e.jsxs(Ar,{children:[e.jsx($,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsxs($,{onClick:v,disabled:!u||g,children:[g?e.jsx(kt,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(E4,{className:"h-4 w-4 mr-2"}),"Transfer",b?` to ${(C=b.profile)==null?void 0:C.name}`:""]})]})]})})}const dRe=()=>{const s=Qn(),{data:t,isLoading:n}=Whn(),{data:r}=Hw(),[a,i]=j.useState(""),[l,o]=j.useState("all"),[c,d]=j.useState(null),[u,h]=j.useState(""),m=(r==null?void 0:r.role)==="team_leader",f=j.useMemo(()=>{if(!t)return[];const x=new Map;return t.forEach(y=>{x.has(y.owner_user_id)||x.set(y.owner_user_id,{id:y.owner_user_id,name:y.owner_name||"Unknown",avatar:y.owner_avatar_url})}),Array.from(x.values())},[t]),g=j.useMemo(()=>{if(!t)return[];let x=t;if(l!=="all"&&(x=x.filter(y=>y.owner_user_id===l)),a.trim()){const y=a.toLowerCase();x=x.filter(v=>{var b,w,S;return(v.first_name+" "+(v.last_name||"")).toLowerCase().includes(y)||((b=v.email)==null?void 0:b.toLowerCase().includes(y))||((w=v.phone)==null?void 0:w.includes(y))||((S=v.owner_name)==null?void 0:S.toLowerCase().includes(y))})}return x},[t,a,l]);return n?e.jsxs("div",{className:"space-y-4",children:[e.jsx(yn,{className:"h-10 w-full"}),e.jsx(yn,{className:"h-64 w-full"})]}):!t||t.length===0?e.jsx(Ne,{children:e.jsxs(Ie,{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(Zn,{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(Ne,{children:e.jsx(Ie,{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(Kr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(pe,{placeholder:"Search by name, email, phone, or agent...",value:a,onChange:x=>i(x.target.value),className:"pl-9"})]}),e.jsxs(ms,{value:l,onValueChange:o,children:[e.jsx(us,{className:"w-[200px]",children:e.jsx(fs,{placeholder:"Filter by agent"})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"all",children:"All Team Members"}),f.map(x=>e.jsx(Ge,{value:x.id,children:x.name},x.id))]})]})]})})}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[g.length," contact",g.length!==1?"s":""," from ",f.length," teammate",f.length!==1?"s":""]}),e.jsx(Ne,{children:e.jsx(Ie,{className:"p-0 overflow-x-auto",children:e.jsxs(mi,{className:"min-w-[800px]",children:[e.jsx(fi,{children:e.jsxs(En,{children:[e.jsx(Dt,{children:"Name"}),e.jsx(Dt,{children:"Agent"}),e.jsx(Dt,{children:"Contact Info"}),e.jsx(Dt,{children:"Address"}),e.jsx(Dt,{children:"Lead Source"}),e.jsx(Dt,{children:"Date Added"}),m&&e.jsx(Dt,{className:"w-[80px]",children:"Actions"})]})}),e.jsx(pi,{children:g.length===0?e.jsx(En,{children:e.jsx(wt,{colSpan:m?7:6,className:"text-center py-8 text-muted-foreground",children:a||l!=="all"?"No contacts match your filters":"No team contacts available"})}):g.map(x=>e.jsxs(En,{className:`hover:bg-accent/50 ${m?"cursor-pointer":""}`,onClick:m?()=>s(`/mission-control/contacts/${x.id}`):void 0,children:[e.jsx(wt,{className:"font-medium",children:e.jsxs("span",{className:m?"hover:text-primary hover:underline transition-colors":"",children:[x.first_name," ",x.last_name||""]})}),e.jsx(wt,{children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(Oa,{className:"h-6 w-6",children:[e.jsx(Li,{src:x.owner_avatar_url||""}),e.jsx(za,{className:"text-[10px]",children:(x.owner_name||"?").charAt(0).toUpperCase()})]}),e.jsx("span",{className:"text-sm text-muted-foreground truncate max-w-[120px]",children:x.owner_name||"Unknown"})]})}),e.jsx(wt,{children:e.jsxs("div",{className:"space-y-1 text-sm",children:[x.email&&e.jsxs("div",{className:"flex items-center gap-1 text-muted-foreground",children:[e.jsx(mn,{className:"h-3 w-3 shrink-0"}),e.jsx("span",{className:"truncate",children:x.email})]}),x.phone&&e.jsxs("div",{className:"flex items-center gap-1 text-muted-foreground",children:[e.jsx(Da,{className:"h-3 w-3 shrink-0"}),e.jsx("span",{children:x.phone})]}),!x.email&&!x.phone&&e.jsx("span",{className:"text-xs text-muted-foreground italic",children:"No contact info"})]})}),e.jsx(wt,{children:x.address?e.jsxs("div",{className:"flex items-center gap-1 text-sm text-muted-foreground",children:[e.jsx(ci,{className:"h-3 w-3 shrink-0"}),e.jsx("span",{className:"truncate max-w-[180px]",children:x.address})]}):e.jsx("span",{className:"text-xs text-muted-foreground italic",children:"—"})}),e.jsx(wt,{children:x.lead_source?e.jsx(Be,{variant:"outline",className:"text-xs border-primary/30 text-primary",children:x.lead_source}):e.jsx("span",{className:"text-xs text-muted-foreground italic",children:"—"})}),e.jsx(wt,{children:e.jsx("span",{className:"text-sm text-muted-foreground",children:en(new Date(x.created_at),"MMM d, yyyy")})}),m&&e.jsx(wt,{children:e.jsx($,{variant:"ghost",size:"sm",className:"h-8 px-2",onClick:y=>{y.stopPropagation(),d(x.id),h(`${x.first_name} ${x.last_name||""}`.trim())},title:"Transfer to team member",children:e.jsx(E4,{className:"h-4 w-4"})})})]},x.id))})]})})}),e.jsx(VWt,{open:!!c,onOpenChange:x=>{x||d(null)},contactIds:c?[c]:[],contactNames:u?[u]:[],onComplete:()=>d(null)})]})},Zhn=s=>{if(!s)return"";const t=new Date(s);return new Intl.DateTimeFormat("en-US",{timeZone:"America/New_York",month:"short",day:"numeric",year:"numeric",hour:"numeric",minute:"2-digit"}).format(t)},Xhn=({leadPondId:s})=>{const{data:t,isLoading:n,error:r}=Ghn(s);return n?e.jsxs("div",{className:"space-y-2 pt-2",children:[e.jsx(yn,{className:"h-4 w-2/3"}),e.jsx(yn,{className:"h-4 w-1/2"})]}):r?e.jsx("p",{className:"pt-2 text-xs text-muted-foreground",children:"Activity isn't available for this lead."}):!t||t.length===0?e.jsx("p",{className:"pt-2 text-xs text-muted-foreground",children:"No notes or logged follow-ups yet."}):e.jsx("div",{className:"space-y-3 pt-2",children:t.map((a,i)=>e.jsxs("div",{className:"flex gap-2 border-l-2 border-muted pl-3",children:[a.kind==="note"?e.jsx(r7,{className:"mt-0.5 h-3 w-3 shrink-0 text-muted-foreground"}):e.jsx(af,{className:"mt-0.5 h-3 w-3 shrink-0 text-muted-foreground"}),e.jsxs("div",{className:"min-w-0 space-y-0.5",children:[e.jsxs("p",{className:"text-xs font-medium",children:[a.label,a.actor_name?e.jsxs("span",{className:"font-normal text-muted-foreground",children:[" · ",a.actor_name]}):null]}),a.notes&&e.jsx("p",{className:"whitespace-pre-wrap text-xs text-muted-foreground",children:a.notes}),a.occurred_at&&e.jsx("p",{className:"text-[10px] text-muted-foreground",children:Zhn(a.occurred_at)})]})]},i))})},Qhn=s=>s?new Intl.DateTimeFormat("en-US",{timeZone:"America/New_York",month:"short",day:"numeric",year:"numeric",hour:"numeric",minute:"2-digit"}).format(new Date(s)):"",Jhn=s=>{var n;const t=((n=s.contact_name)==null?void 0:n.trim())||"A lead";switch(s.event_type){case"claimed":return{icon:zq,text:e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"font-medium",children:s.actor_name||"Someone"})," claimed"," ",e.jsx("span",{className:"font-medium",children:t})]})};case"returned":return{icon:Ex,text:e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"font-medium",children:s.actor_name||"Someone"})," returned"," ",e.jsx("span",{className:"font-medium",children:t})," to the pond"]})};default:return{icon:b1,text:e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"font-medium",children:s.actor_name||"Someone"})," added"," ",e.jsx("span",{className:"font-medium",children:t})," to the pond"]})}}},Uwt=({teamId:s,pondId:t})=>{const{data:n,isLoading:r}=Khn(s,t),[a,i]=j.useState(!1),l=n||[],o=a?l:l.slice(0,8);return e.jsxs(Ne,{children:[e.jsx(Ct,{className:"pb-3",children:e.jsxs(At,{className:"flex items-center gap-2 text-sm",children:[e.jsx(Lw,{className:"h-4 w-4"}),"Pond Activity History"]})}),e.jsx(Ie,{className:"space-y-3",children:r?e.jsx("div",{className:"space-y-2",children:[1,2,3].map(c=>e.jsx(yn,{className:"h-8 w-full"},c))}):l.length===0?e.jsx("p",{className:"text-xs text-muted-foreground",children:"No pond activity yet. Adding, claiming, and returning leads will show up here."}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"space-y-3",children:o.map((c,d)=>{const u=Jhn(c),h=u.icon;return e.jsxs("div",{className:"flex gap-3",children:[e.jsxs(Oa,{className:"h-6 w-6 shrink-0",children:[e.jsx(Li,{src:c.actor_avatar_url||""}),e.jsx(za,{className:"text-[9px]",children:(c.actor_name||"?").charAt(0)})]}),e.jsxs("div",{className:"min-w-0 space-y-0.5",children:[e.jsxs("p",{className:"flex items-center gap-1.5 text-xs",children:[e.jsx(h,{className:"h-3 w-3 shrink-0 text-muted-foreground"}),e.jsx("span",{children:u.text})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("span",{className:"text-[10px] text-muted-foreground",children:Qhn(c.occurred_at)}),c.pond_name&&e.jsx(Be,{variant:"secondary",className:"text-[9px]",children:c.pond_name})]}),c.notes&&e.jsx("p",{className:"whitespace-pre-wrap text-[11px] text-muted-foreground",children:c.notes})]})]},`${c.lead_pond_id}-${c.event_type}-${d}`)})}),l.length>8&&e.jsxs($,{size:"sm",variant:"ghost",className:"h-7 px-2 text-xs",onClick:()=>i(c=>!c),children:[a?e.jsx(v1,{className:"mr-1 h-3 w-3"}):e.jsx(Tl,{className:"mr-1 h-3 w-3"}),a?"Show less":`Show all ${l.length} events`]})]})})]})},emn=s=>s?new Intl.DateTimeFormat("en-US",{timeZone:"America/New_York",month:"short",day:"numeric"}).format(new Date(s)):null,tmn=({item:s,isClaimer:t,onReturn:n,returning:r})=>{var o,c,d;const[a,i]=j.useState(!1),l=emn(s.last_activity_at);return e.jsx(Ne,{children:e.jsxs(Ie,{className:"space-y-3 p-4",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0 space-y-1.5",children:[e.jsxs("p",{className:"text-sm font-medium",children:[(o=s.contact)==null?void 0:o.first_name," ",((c=s.contact)==null?void 0:c.last_name)||""]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs(Be,{variant:"secondary",className:"text-xs",children:["Claimed by ",((d=s.claimer)==null?void 0:d.name)||"Unknown"]}),e.jsxs(Be,{variant:"outline",className:"text-[10px]",children:[s.touch_count||0," follow-up",(s.touch_count||0)===1?"":"s"]}),e.jsxs("span",{className:"flex items-center gap-1 text-[11px] text-muted-foreground",children:[e.jsx(da,{className:"h-3 w-3"}),l?`Last activity ${l}`:"No activity yet"]})]}),t&&e.jsxs("p",{className:"flex items-center gap-1 text-[11px] text-muted-foreground",children:[e.jsx(Ca,{className:"h-3 w-3"}),"Your notes and follow-ups on this lead are visible to the team leader and the agent who shared it."]})]}),t&&e.jsxs($,{size:"sm",variant:"outline",onClick:n,disabled:r,children:[e.jsx(Ex,{className:"mr-1 h-3 w-3"}),"Return"]})]}),s.can_view_activity&&e.jsxs("div",{className:"border-t pt-2",children:[e.jsxs($,{size:"sm",variant:"ghost",className:"h-7 px-2 text-xs",onClick:()=>i(u=>!u),children:[a?e.jsx(v1,{className:"mr-1 h-3 w-3"}):e.jsx(Tl,{className:"mr-1 h-3 w-3"}),a?"Hide notes & activity":"View notes & activity"]}),a&&e.jsx(Xhn,{leadPondId:s.id})]})]})})},uRe=({teamId:s})=>{const{user:t}=vs(),[n,r]=j.useState(null),{ponds:a}=Vrt(s),i=a.filter(f=>f.has_access),{leadPondItems:l,isLoading:o,claimLead:c,returnLead:d}=qWt(s,n),u=i.length>1?e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx($,{size:"sm",variant:n===null?"default":"outline",onClick:()=>r(null),children:"All Ponds"}),i.map(f=>e.jsxs($,{size:"sm",variant:n===f.id?"default":"outline",onClick:()=>r(f.id),children:[e.jsx(b1,{className:"mr-1 h-3 w-3"}),f.name,e.jsx(Be,{variant:"secondary",className:"ml-2 text-[10px]",children:f.available_count})]},f.id))]}):null;if(console.log("[LeadPondView] render — teamId:",s,"itemCount:",l.length,"loading:",o),o)return e.jsx("div",{className:"space-y-3",children:[1,2,3].map(f=>e.jsx(yn,{className:"h-20 w-full"},f))});if(l.length===0)return e.jsxs("div",{className:"space-y-4",children:[u,e.jsx(Ne,{children:e.jsxs(Ie,{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(b1,{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."})]})}),e.jsx(Uwt,{teamId:s,pondId:n})]});const h=l.filter(f=>f.status==="available"),m=l.filter(f=>f.status==="claimed");return e.jsxs("div",{className:"space-y-6",children:[u,e.jsxs("div",{children:[e.jsxs("h3",{className:"text-sm font-semibold text-muted-foreground mb-3",children:["Available (",h.length,")"]}),h.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:h.map(f=>{var g,x,y,v,b,w,S,C,E,I,P;return e.jsx(Ne,{children:e.jsxs(Ie,{className:"flex flex-col gap-3 p-4 sm:flex-row sm:items-start sm:justify-between",children:[e.jsxs("div",{className:"min-w-0 space-y-1.5",children:[e.jsxs("p",{className:"font-medium text-sm",children:[((g=f.contact)==null?void 0:g.first_name)||"Unnamed"," ",((x=f.contact)==null?void 0:x.last_name)||""]}),e.jsxs("div",{className:"flex flex-wrap gap-x-4 gap-y-1",children:[((y=f.contact)==null?void 0:y.email)&&e.jsxs("span",{className:"text-xs text-muted-foreground flex items-center gap-1",children:[e.jsx(mn,{className:"h-3 w-3"})," ",f.contact.email]}),((v=f.contact)==null?void 0:v.phone)&&e.jsxs("span",{className:"text-xs text-muted-foreground flex items-center gap-1",children:[e.jsx(Da,{className:"h-3 w-3"})," ",f.contact.phone]}),((b=f.contact)==null?void 0:b.address)&&e.jsxs("span",{className:"text-xs text-muted-foreground flex items-center gap-1",children:[e.jsx(ci,{className:"h-3 w-3"})," ",f.contact.address]})]}),f.pond_name&&n===null&&i.length>1&&e.jsxs(Be,{variant:"secondary",className:"text-[10px]",children:[e.jsx(b1,{className:"mr-1 h-2.5 w-2.5"})," ",f.pond_name]}),((w=f.contact)==null?void 0:w.lead_source)&&e.jsxs(Be,{variant:"outline",className:"text-[10px]",children:["Source: ",f.contact.lead_source]}),(f.notes||((S=f.contact)==null?void 0:S.notes))&&e.jsxs("p",{className:"text-xs text-muted-foreground flex items-start gap-1 max-w-xl",children:[e.jsx(r7,{className:"h-3 w-3 mt-0.5 shrink-0"}),e.jsx("span",{className:"whitespace-pre-wrap",children:f.notes||((C=f.contact)==null?void 0:C.notes)})]}),e.jsxs("div",{className:"flex items-center gap-2 pt-0.5",children:[e.jsxs(Oa,{className:"h-4 w-4",children:[e.jsx(Li,{src:((E=f.contributor)==null?void 0:E.avatar_url)||""}),e.jsx(za,{className:"text-[8px]",children:(((I=f.contributor)==null?void 0:I.name)||"?").charAt(0)})]}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:["from ",((P=f.contributor)==null?void 0:P.name)||"Unknown"]})]})]}),e.jsxs($,{size:"sm",className:"shrink-0",onClick:()=>c.mutate(f.id),disabled:c.isPending,children:[e.jsx(zq,{className:"mr-1 h-3 w-3"}),"Claim"]})]})},f.id)})})]}),m.length>0&&e.jsxs("div",{children:[e.jsxs("h3",{className:"text-sm font-semibold text-muted-foreground mb-3",children:["Claimed (",m.length,")"]}),e.jsx("div",{className:"space-y-2",children:m.map(f=>e.jsx(tmn,{item:f,isClaimer:f.claimed_by===(t==null?void 0:t.id),onReturn:()=>d.mutate(f.id),returning:d.isPending},f.id))})]}),e.jsx(Uwt,{teamId:s,pondId:n})]})},Hrt=({teamId:s})=>{const{useTeamMembers:t}=m3(),{data:n=[]}=t(s),r=n.map(f=>f.user_id),a=new Map(n.map(f=>[f.user_id,f.profile])),{data:i=[],isLoading:l}=tt({queryKey:["team-shared-presentations",s,r],queryFn:async()=>{if(r.length===0)return[];const{data:f,error:g}=await q.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",r).neq("status","archived").order("created_at",{ascending:!1});if(g)throw g;return f||[]},enabled:r.length>0}),{data:o=[],isLoading:c}=tt({queryKey:["team-shared-open-houses",s,r],queryFn:async()=>{if(r.length===0)return[];const{data:f,error:g}=await q.from("open_houses").select("id, agent_id, property_address, city, state, event_date, is_active, visitor_count, slug, created_at").in("agent_id",r).order("event_date",{ascending:!1});if(g)throw g;return f||[]},enabled:r.length>0}),{data:d=[],isLoading:u}=tt({queryKey:["team-shared-videos",s,r],queryFn:async()=>{if(r.length===0)return[];const{data:f,error:g}=await q.from("agent_videos").select("id, owner_user_id, title, recipient_name, status, view_count, touch_type, share_token, created_at").in("owner_user_id",r).eq("is_deleted",!1).order("created_at",{ascending:!1}).limit(50);if(g)throw g;return f||[]},enabled:r.length>0});if(l||c||u)return e.jsx("div",{className:"space-y-3",children:[1,2,3].map(f=>e.jsx(yn,{className:"h-20 w-full"},f))});const m=f=>{const g=a.get(f);return{name:(g==null?void 0:g.name)||"Unknown",avatar:(g==null?void 0:g.avatar_url)||"",initials:((g==null?void 0:g.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(Ne,{children:e.jsxs(Ie,{className:"flex items-center gap-3 p-4",children:[e.jsx(jb,{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(Ne,{children:e.jsxs(Ie,{className:"flex items-center gap-3 p-4",children:[e.jsx(va,{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(Ne,{children:e.jsxs(Ie,{className:"flex items-center gap-3 p-4",children:[e.jsx(ua,{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(ha,{defaultValue:"presentations",className:"space-y-4",children:[e.jsxs(ma,{children:[e.jsxs(Zt,{value:"presentations",children:["Presentations (",i.length,")"]}),e.jsxs(Zt,{value:"guest-books",children:["Guest Books (",o.length,")"]}),e.jsxs(Zt,{value:"videos",children:["Videos (",d.length,")"]})]}),e.jsx(Xt,{value:"presentations",className:"space-y-2",children:i.length===0?e.jsx(a9e,{icon:e.jsx(jb,{className:"h-10 w-10"}),label:"No presentations yet"}):i.map(f=>{const g=m(f.owner_user_id);return e.jsx(Ne,{children:e.jsxs(Ie,{className:"flex items-center justify-between p-4",children:[e.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[e.jsxs(Oa,{className:"h-8 w-8 shrink-0",children:[e.jsx(Li,{src:g.avatar}),e.jsx(za,{className:"text-xs",children:g.initials})]}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"font-medium truncate",children:f.title||"Untitled"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[g.name," · ",en(new Date(f.created_at),"MMM d, yyyy")]})]})]}),e.jsxs("div",{className:"flex items-center gap-3 shrink-0",children:[e.jsx(Be,{variant:f.status==="published"?"default":"secondary",className:"text-xs capitalize",children:f.status}),e.jsxs("div",{className:"flex items-center gap-1 text-xs text-muted-foreground",children:[e.jsx(Ca,{className:"h-3 w-3"}),f.view_count||0]})]})]})},f.id)})}),e.jsx(Xt,{value:"guest-books",className:"space-y-2",children:o.length===0?e.jsx(a9e,{icon:e.jsx(va,{className:"h-10 w-10"}),label:"No guest books yet"}):o.map(f=>{const g=m(f.agent_id);return e.jsx(Ne,{children:e.jsxs(Ie,{className:"flex items-center justify-between p-4",children:[e.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[e.jsxs(Oa,{className:"h-8 w-8 shrink-0",children:[e.jsx(Li,{src:g.avatar}),e.jsx(za,{className:"text-xs",children:g.initials})]}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"font-medium truncate",children:f.property_address}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[g.name," · ",en(new Date(f.event_date),"MMM d, yyyy")]})]})]}),e.jsxs("div",{className:"flex items-center gap-3 shrink-0",children:[f.is_active?e.jsx(Be,{className:"text-xs",children:"Active"}):e.jsx(Be,{variant:"secondary",className:"text-xs",children:"Inactive"}),e.jsxs("div",{className:"flex items-center gap-1 text-xs text-muted-foreground",children:[e.jsx(Zn,{className:"h-3 w-3"}),f.visitor_count||0]})]})]})},f.id)})}),e.jsx(Xt,{value:"videos",className:"space-y-2",children:d.length===0?e.jsx(a9e,{icon:e.jsx(ua,{className:"h-10 w-10"}),label:"No videos yet"}):d.map(f=>{const g=m(f.owner_user_id);return e.jsx(Ne,{children:e.jsxs(Ie,{className:"flex items-center justify-between p-4",children:[e.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[e.jsxs(Oa,{className:"h-8 w-8 shrink-0",children:[e.jsx(Li,{src:g.avatar}),e.jsx(za,{className:"text-xs",children:g.initials})]}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"font-medium truncate",children:f.title||f.recipient_name||"Untitled Video"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[g.name," · ",en(new Date(f.created_at),"MMM d, yyyy")]})]})]}),e.jsxs("div",{className:"flex items-center gap-3 shrink-0",children:[e.jsx(Be,{variant:"secondary",className:"text-xs capitalize",children:f.touch_type}),e.jsxs("div",{className:"flex items-center gap-1 text-xs text-muted-foreground",children:[e.jsx(Ca,{className:"h-3 w-3"}),f.view_count||0]})]})]})},f.id)})})]})]})},a9e=({icon:s,label:t})=>e.jsx(Ne,{children:e.jsxs(Ie,{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})]})}),HWt=({team:s,brokerageAgents:t,onBack:n,onUpdate:r,onAddMember:a,onRemoveMember:i,onUpdateRole:l,onDeleteTeam:o,isUpdating:c,isAddingMember:d})=>{var I,P;const{useTeamMembers:u}=m3(),{data:h=[],isLoading:m}=u(s.id),[f,g]=j.useState(!1),[x,y]=j.useState(""),[v,b]=j.useState("team_member"),{data:w}=tt({queryKey:["agents-on-other-teams",s.id],queryFn:async()=>{const{data:R}=await q.from("team_members").select("user_id, team_id, teams:team_id(name)").neq("team_id",s.id),D=new Map;return(R||[]).forEach(O=>{var W;const U=D.get(O.user_id)||[];U.push(((W=O.teams)==null?void 0:W.name)||"another team"),D.set(O.user_id,U)}),D}}),S=new Set(h.map(R=>R.user_id)),C=t.filter(R=>!S.has(R.id)),E=async()=>{x&&(await a(x,v),y(""),b("team_member"),g(!1))};return e.jsxs("div",{className:"space-y-6",children:[e.jsx($,{variant:"ghost",onClick:n,className:"mb-2",children:"← Back to Teams"}),e.jsxs(ha,{defaultValue:"members",className:"space-y-4",children:[e.jsxs(ma,{children:[e.jsx(Zt,{value:"members",children:"Members"}),e.jsxs(Zt,{value:"contacts",children:[e.jsx(HI,{className:"mr-1 h-3.5 w-3.5"}),"Team Contacts"]}),s.lead_pond_enabled&&e.jsxs(Zt,{value:"lead-pond",children:[e.jsx(b1,{className:"mr-1 h-3.5 w-3.5"}),"Lead Pond"]}),s.shared_assets_enabled&&e.jsxs(Zt,{value:"shared-assets",children:[e.jsx(_b,{className:"mr-1 h-3.5 w-3.5"}),"Shared Assets"]}),e.jsx(Zt,{value:"settings",children:"Settings"})]}),e.jsxs(Xt,{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(zs,{open:f,onOpenChange:g,children:[e.jsx(jl,{asChild:!0,children:e.jsxs($,{size:"sm",children:[e.jsx(sc,{className:"mr-2 h-4 w-4"}),"Add Member"]})}),e.jsxs(Os,{children:[e.jsxs(Us,{children:[e.jsx(Bs,{children:"Add Team Member"}),e.jsxs(Ir,{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(ee,{children:"Agent"}),e.jsxs(Yd,{children:[e.jsx(Zd,{asChild:!0,children:e.jsxs($,{variant:"outline",role:"combobox",className:"w-full justify-between font-normal",children:[x&&(((I=C.find(R=>R.id===x))==null?void 0:I.name)||((P=C.find(R=>R.id===x))==null?void 0:P.email))||"Select an agent",e.jsx(Pw,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(Bd,{className:"w-[--radix-popover-trigger-width] p-0",align:"start",children:e.jsxs(P2,{children:[e.jsx(I2,{placeholder:"Search agents..."}),e.jsxs(L2,{children:[e.jsx(R2,{children:"No agents found."}),e.jsx(Uw,{children:C.map(R=>{const D=w==null?void 0:w.get(R.id);return e.jsxs(g1,{value:R.name||R.email||R.id,onSelect:()=>y(R.id),children:[e.jsx(la,{className:Pt("mr-2 h-4 w-4",x===R.id?"opacity-100":"opacity-0")}),R.name||R.email,D!=null&&D.length?e.jsxs("span",{className:"text-xs text-muted-foreground ml-1",children:["(also on ",D.join(", "),")"]}):null]},R.id)})})]})]})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Role"}),e.jsxs(ms,{value:v,onValueChange:b,children:[e.jsx(us,{children:e.jsx(fs,{})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"team_leader",children:"Team Leader"}),e.jsx(Ge,{value:"team_member",children:"Team Member"})]})]})]})]}),e.jsxs(Ar,{children:[e.jsx($,{variant:"outline",onClick:()=>g(!1),children:"Cancel"}),e.jsx($,{onClick:E,disabled:!x||d,children:d?"Adding...":"Add to Team"})]})]})]})]}),m?e.jsx("div",{className:"space-y-3",children:[1,2,3].map(R=>e.jsx(yn,{className:"h-16 w-full"},R))}):h.length===0?e.jsx(Ne,{children:e.jsxs(Ie,{className:"flex flex-col items-center justify-center py-8 text-center",children:[e.jsx(Zn,{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:h.map(R=>{var D,O,U,W,V;return e.jsx(Ne,{children:e.jsxs(Ie,{className:"flex items-center justify-between p-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs(Oa,{className:"h-10 w-10",children:[e.jsx(Li,{src:((D=R.profile)==null?void 0:D.avatar_url)||""}),e.jsx(za,{children:(((O=R.profile)==null?void 0:O.name)||"?").charAt(0).toUpperCase()})]}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:((U=R.profile)==null?void 0:U.name)||"Unknown"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:(W=R.profile)==null?void 0:W.email})]}),R.role==="team_leader"?e.jsxs(Be,{className:"bg-[hsl(var(--chart-4)/0.1)] text-[hsl(var(--chart-4))] border-[hsl(var(--chart-4))]",children:[e.jsx(Bg,{className:"mr-1 h-3 w-3"})," Leader"]}):e.jsx(Be,{variant:"secondary",children:"Member"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(ms,{value:R.role,onValueChange:G=>l(R.id,G),children:[e.jsx(us,{className:"w-[140px]",children:e.jsx(fs,{})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"team_leader",children:"Team Leader"}),e.jsx(Ge,{value:"team_member",children:"Team Member"})]})]}),e.jsxs(kc,{children:[e.jsx(jx,{asChild:!0,children:e.jsx($,{variant:"ghost",size:"icon",className:"text-muted-foreground hover:text-destructive",children:e.jsx(mV,{className:"h-4 w-4"})})}),e.jsxs(cc,{children:[e.jsxs(dc,{children:[e.jsx(hc,{children:"Remove Member?"}),e.jsxs(mc,{children:["Remove ",((V=R.profile)==null?void 0:V.name)||"this member"," from ",s.name,"?"]})]}),e.jsxs(uc,{children:[e.jsx(fc,{children:"Cancel"}),e.jsx(tc,{onClick:()=>i(R.id),className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Remove"})]})]})]})]})]})},R.id)})})]}),e.jsx(Xt,{value:"contacts",className:"space-y-4",children:e.jsx(dRe,{})}),s.lead_pond_enabled&&e.jsx(Xt,{value:"lead-pond",className:"space-y-4",children:e.jsx(uRe,{teamId:s.id})}),s.shared_assets_enabled&&e.jsx(Xt,{value:"shared-assets",className:"space-y-4",children:e.jsx(Hrt,{teamId:s.id})}),e.jsxs(Xt,{value:"settings",className:"space-y-4",children:[e.jsxs(Ne,{children:[e.jsxs(Ct,{children:[e.jsx(At,{className:"text-lg",children:"Team Settings"}),e.jsx(Gn,{children:"Configure how this team operates."})]}),e.jsxs(Ie,{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Team Name"}),e.jsx(pe,{defaultValue:s.name,onBlur:R=>{R.target.value!==s.name&&r({name:R.target.value})}})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Description"}),e.jsx(Rs,{defaultValue:s.description||"",onBlur:R=>{R.target.value!==(s.description||"")&&r({description:R.target.value||null})},rows:3})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Contact Visibility"}),e.jsxs(ms,{defaultValue:s.contact_visibility,onValueChange:R=>r({contact_visibility:R}),children:[e.jsx(us,{children:e.jsx(fs,{})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"private",children:"Private — Members keep their contacts private"}),e.jsx(Ge,{value:"leader_only",children:"Leader Only — Only team leaders can see member contacts"}),e.jsx(Ge,{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(ee,{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(Sn,{checked:s.lead_pond_enabled,onCheckedChange:R=>r({lead_pond_enabled:R})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(ee,{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(Sn,{checked:s.shared_assets_enabled,onCheckedChange:R=>r({shared_assets_enabled:R})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(ee,{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(Sn,{checked:s.shared_videos_enabled??!1,onCheckedChange:R=>r({shared_videos_enabled:R})})]})]})]}),s.lead_pond_enabled&&e.jsx(UWt,{teamId:s.id}),e.jsxs(kc,{children:[e.jsx(jx,{asChild:!0,children:e.jsxs($,{variant:"destructive",size:"sm",children:[e.jsx(Wn,{className:"mr-2 h-4 w-4"}),"Delete Team"]})}),e.jsxs(cc,{children:[e.jsxs(dc,{children:[e.jsx(hc,{children:"Delete Team?"}),e.jsxs(mc,{children:['This will permanently delete "',s.name,'" and remove all team members. This cannot be undone.']})]}),e.jsxs(uc,{children:[e.jsx(fc,{children:"Cancel"}),e.jsx(tc,{onClick:()=>{o(),n()},className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Delete Team"})]})]})]})]})]})]})},GWt=({open:s,onOpenChange:t,onCreateTeam:n,isCreating:r,brokerageAgents:a,isAdmin:i,allBrokerages:l,activeBrokerageId:o})=>{const[c,d]=j.useState(1),[u,h]=j.useState(""),[m,f]=j.useState(""),[g,x]=j.useState(""),[y,v]=j.useState(""),[b,w]=j.useState([]),S=()=>{d(1),h(""),f(""),x(""),v(""),w([])},C=R=>{R||S(),t(R)},E=async()=>{const R=g&&g!=="none"?g:o||null;await n({name:u.trim(),description:m.trim()||void 0,brokerage_id:R,leaderId:y||void 0,memberIds:b.length>0?b:void 0}),S()},I=R=>{R!==y&&w(D=>D.includes(R)?D.filter(O=>O!==R):[...D,R])},P=a.filter(R=>R.id!==y);return e.jsx(zs,{open:s,onOpenChange:C,children:e.jsxs(Os,{className:"sm:max-w-lg max-h-[90vh] flex flex-col",children:[e.jsxs(Us,{children:[e.jsx(Bs,{children:c===1?"Create New Team":"Assign Team Members"}),e.jsx(Ir,{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:Pt("h-1.5 flex-1 rounded-full transition-colors","bg-primary")}),e.jsx("div",{className:Pt("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(ee,{htmlFor:"team-name",children:"Team Name *"}),e.jsx(pe,{id:"team-name",value:u,onChange:R=>h(R.target.value),placeholder:"e.g., Downtown Squad",autoFocus:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"team-desc",children:"Description"}),e.jsx(Rs,{id:"team-desc",value:m,onChange:R=>f(R.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(ee,{children:"Brokerage"}),e.jsxs(ms,{value:g,onValueChange:x,children:[e.jsx(us,{children:e.jsx(fs,{placeholder:"No brokerage (independent team)"})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"none",children:"No brokerage (independent)"}),l.map(R=>e.jsx(Ge,{value:R.id,children:R.name},R.id))]})]})]})]}):e.jsxs("div",{className:"space-y-4 py-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ee,{className:"flex items-center gap-1.5",children:[e.jsx(Bg,{className:"h-3.5 w-3.5 text-[hsl(var(--chart-4))]"}),"Team Leader"]}),e.jsxs(ms,{value:y,onValueChange:R=>{v(R),w(D=>D.filter(O=>O!==R))},children:[e.jsx(us,{children:e.jsx(fs,{placeholder:"Select a team leader (optional)"})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"none",children:"No leader for now"}),a.map(R=>e.jsx(Ge,{value:R.id,children:R.name||R.email||"Unknown"},R.id))]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ee,{className:"flex items-center gap-1.5",children:[e.jsx(sc,{className:"h-3.5 w-3.5"}),"Initial Members",b.length>0&&e.jsxs(Be,{variant:"secondary",className:"ml-1 text-xs",children:[b.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:P.length===0?e.jsxs("div",{className:"p-4 text-center text-sm text-muted-foreground",children:[e.jsx(Zn,{className:"h-8 w-8 mx-auto mb-2 opacity-50"}),"No agents available"]}):P.map(R=>{const D=b.includes(R.id);return e.jsxs("button",{type:"button",className:Pt("w-full flex items-center gap-3 p-3 text-left transition-colors hover:bg-accent/50",D&&"bg-primary/5"),onClick:()=>I(R.id),children:[e.jsxs(Oa,{className:"h-8 w-8",children:[e.jsx(Li,{src:R.avatar_url||""}),e.jsx(za,{className:"text-xs",children:(R.name||"?").charAt(0).toUpperCase()})]}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium truncate",children:R.name||"Unknown"}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:R.email})]}),e.jsx("div",{className:Pt("h-5 w-5 rounded-full border-2 flex items-center justify-center transition-colors shrink-0",D?"bg-primary border-primary text-primary-foreground":"border-muted-foreground/30"),children:D&&e.jsx(la,{className:"h-3 w-3"})})]},R.id)})})]})]})}),e.jsx(Ar,{className:"gap-2 sm:gap-0",children:c===1?e.jsxs(e.Fragment,{children:[e.jsx($,{variant:"outline",onClick:()=>C(!1),children:"Cancel"}),e.jsxs($,{onClick:()=>d(2),disabled:!u.trim(),children:["Next",e.jsx(ei,{className:"ml-2 h-4 w-4"})]})]}):e.jsxs(e.Fragment,{children:[e.jsxs($,{variant:"outline",onClick:()=>d(1),children:[e.jsx(qa,{className:"mr-2 h-4 w-4"}),"Back"]}),e.jsx($,{onClick:E,disabled:r,children:r?"Creating…":"Create Team"})]})})]})})},smn=()=>{const{teams:s,isLoading:t,createTeam:n,updateTeam:r,deleteTeam:a,addMember:i,removeMember:l,updateMemberRole:o}=m3(),[c,d]=j.useState(!1),[u,h]=j.useState(null),[m,f]=j.useState(""),{data:g}=tt({queryKey:["all-brokerages-for-teams"],queryFn:async()=>{const{data:C,error:E}=await q.from("brokerages").select("id, name").order("name");if(E)throw E;return C||[]}}),{data:x}=tt({queryKey:["admin-team-member-info",s.map(C=>C.id).join(",")],queryFn:async()=>{var R;if(s.length===0)return{};const{data:C}=await q.from("team_members").select("team_id, user_id, role").in("team_id",s.map(D=>D.id));if(!C)return{};const E=C.filter(D=>D.role==="team_leader").map(D=>D.user_id);let I={};if(E.length>0){const{data:D}=await q.from("profiles").select("id, name").in("id",E);D&&(I=Object.fromEntries(D.map(O=>[O.id,{name:O.name}])))}const P={};for(const D of s){const O=C.filter(W=>W.team_id===D.id),U=O.find(W=>W.role==="team_leader");P[D.id]={count:O.length,leaderName:U&&((R=I[U.user_id])==null?void 0:R.name)||null}}return P},enabled:s.length>0}),y=(u==null?void 0:u.brokerage_id)||null,{data:v}=tt({queryKey:["brokerage-agents-for-teams",y],queryFn:async()=>{let C=q.from("profiles").select("id, name, email, avatar_url").order("name");y&&(C=C.eq("brokerage_id",y));const{data:E,error:I}=await C;if(I)throw I;return E||[]},enabled:!!u}),b=Object.fromEntries((g||[]).map(C=>[C.id,C.name])),w=async C=>{const E=await n.mutateAsync({name:C.name,brokerage_id:C.brokerage_id||null,description:C.description});if(C.leaderId&&C.leaderId!=="none"&&await i.mutateAsync({team_id:E.id,user_id:C.leaderId,role:"team_leader"}),C.memberIds)for(const I of C.memberIds)await i.mutateAsync({team_id:E.id,user_id:I,role:"team_member"});d(!1)};if(u)return e.jsx(HWt,{team:u,brokerageAgents:v||[],onBack:()=>h(null),onUpdate:C=>r.mutateAsync({id:u.id,...C}).then(E=>h(E)),onAddMember:(C,E)=>i.mutateAsync({team_id:u.id,user_id:C,role:E}),onRemoveMember:C=>l.mutateAsync({team_id:u.id,member_id:C}),onUpdateRole:(C,E)=>o.mutateAsync({team_id:u.id,member_id:C,role:E}),onDeleteTeam:()=>{a.mutate(u.id),h(null)},isUpdating:r.isPending,isAddingMember:i.isPending});const S=s.filter(C=>C.name.toLowerCase().includes(m.toLowerCase())||(C.description||"").toLowerCase().includes(m.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(Kr,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(pe,{placeholder:"Search teams...",value:m,onChange:C=>f(C.target.value),className:"pl-10"})]}),e.jsxs("span",{className:"text-sm text-muted-foreground whitespace-nowrap",children:[S.length," of ",s.length," teams"]})]}),e.jsxs($,{size:"sm",onClick:()=>d(!0),children:[e.jsx(dn,{className:"mr-2 h-4 w-4"}),"Create Team"]})]}),e.jsx(GWt,{open:c,onOpenChange:d,onCreateTeam:w,isCreating:n.isPending,brokerageAgents:[],isAdmin:!0,allBrokerages:g,activeBrokerageId:null}),e.jsx("div",{className:"border rounded-lg bg-card overflow-hidden",children:e.jsxs(mi,{children:[e.jsx(fi,{children:e.jsxs(En,{className:"bg-muted/30 hover:bg-muted/30",children:[e.jsx(Dt,{className:"font-semibold",children:"Team Name"}),e.jsx(Dt,{className:"font-semibold",children:"Brokerage"}),e.jsx(Dt,{className:"font-semibold",children:"Leader"}),e.jsx(Dt,{className:"font-semibold",children:"Members"}),e.jsx(Dt,{className:"font-semibold",children:"Visibility"}),e.jsx(Dt,{className:"w-[100px]"})]})}),e.jsx(pi,{children:t?e.jsx(e.Fragment,{children:[1,2,3].map(C=>e.jsxs(En,{children:[e.jsx(wt,{children:e.jsx(yn,{className:"h-4 w-32"})}),e.jsx(wt,{children:e.jsx(yn,{className:"h-4 w-24"})}),e.jsx(wt,{children:e.jsx(yn,{className:"h-4 w-28"})}),e.jsx(wt,{children:e.jsx(yn,{className:"h-4 w-12"})}),e.jsx(wt,{children:e.jsx(yn,{className:"h-4 w-20"})}),e.jsx(wt,{children:e.jsx(yn,{className:"h-4 w-16"})})]},C))}):S.length===0?e.jsx(En,{children:e.jsx(wt,{colSpan:6,className:"text-center py-12 text-muted-foreground",children:m?"No teams match your search":"No teams found. Create one to get started."})}):S.map(C=>{const E=x==null?void 0:x[C.id];return e.jsxs(En,{className:"hover:bg-muted/30",children:[e.jsxs(wt,{children:[e.jsx("button",{onClick:()=>h(C),className:"text-primary hover:underline font-medium",children:C.name}),C.description&&e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5 line-clamp-1",children:C.description})]}),e.jsx(wt,{children:C.brokerage_id?e.jsx("span",{className:"text-sm",children:b[C.brokerage_id]||"—"}):e.jsx("span",{className:"text-sm text-muted-foreground",children:"Independent"})}),e.jsx(wt,{children:E!=null&&E.leaderName?e.jsxs("span",{className:"text-sm flex items-center gap-1",children:[e.jsx(Bg,{className:"h-3 w-3 text-[hsl(var(--chart-4))]"}),E.leaderName]}):e.jsx("span",{className:"text-sm text-muted-foreground",children:"No leader"})}),e.jsx(wt,{children:e.jsxs(Be,{variant:"secondary",className:"text-xs",children:[e.jsx(Zn,{className:"h-3 w-3 mr-1"}),(E==null?void 0:E.count)??0]})}),e.jsx(wt,{children:e.jsxs("span",{className:"text-xs text-muted-foreground capitalize flex items-center gap-1",children:[e.jsx(Mf,{className:"h-3 w-3"}),C.contact_visibility.replace("_"," ")]})}),e.jsx(wt,{children:e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx($,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>h(C),title:"Edit team",children:e.jsx(gi,{className:"h-3.5 w-3.5"})}),e.jsx($,{variant:"ghost",size:"icon",className:"h-8 w-8 text-destructive hover:text-destructive",onClick:async()=>{await fo(`Delete team "${C.name}"? This cannot be undone.`)&&a.mutate(C.id)},title:"Delete team",children:e.jsx(Wn,{className:"h-3.5 w-3.5"})})]})})]},C.id)})})]})})]})};function qwt(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 nmn({open:s,onOpenChange:t,recipients:n}){const{toast:r}=Bi(),[a,i]=j.useState([]),[l,o]=j.useState(!1),[c,d]=j.useState(""),[u,h]=j.useState(""),[m,f]=j.useState(""),[g,x]=j.useState(!1),[y,v]=j.useState(!1),b=j.useMemo(()=>a.find(E=>E.id===c)||null,[a,c]);j.useEffect(()=>{s&&(o(!0),(async()=>{const E=new Date().toISOString(),{data:I,error:P}=await q.from("events").select("id,title,description,event_date,zoom_link,image_url,is_published").gte("event_date",E).order("event_date",{ascending:!0}).limit(50);P?r({title:"Could not load events",description:P.message,variant:"destructive"}):i(I||[]),o(!1)})())},[s,r]);const w=j.useMemo(()=>n.filter(E=>E.email&&/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(E.email)),[n]),S=()=>{if(!b){r({title:"Pick an event first",variant:"destructive"});return}if(w.length===0){r({title:"No valid recipient emails",variant:"destructive"});return}v(!0)},C=async()=>{if(b){v(!1),x(!0);try{const{data:{session:E}}=await q.auth.getSession(),I=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/admin-send-event-invite",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${E==null?void 0:E.access_token}`},body:JSON.stringify({event_id:b.id,recipients:w.map(U=>({email:U.email,name:U.name,user_id:U.id})),custom_subject:u.trim()||void 0,custom_intro:m.trim()||void 0})}),P=await I.json().catch(()=>({}));if(!I.ok)throw new Error((P==null?void 0:P.error)||"Failed to send event invite");const R=(P==null?void 0:P.sent)??0,D=(P==null?void 0:P.failed)??0,O=(P==null?void 0:P.already_invited)??0;r({title:"Invites sent",description:`Sent: ${R}${O?` · Skipped (already invited): ${O}`:""}${D?` · Failed: ${D}`:""}`}),t(!1),f(""),h(""),d("")}catch(E){const I=E instanceof Error?E.message:"Send failed";r({title:"Send failed",description:I,variant:"destructive"})}finally{x(!1)}}};return e.jsxs(e.Fragment,{children:[e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Os,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsxs(Us,{children:[e.jsxs(Bs,{className:"flex items-center gap-2",children:[e.jsx(mn,{className:"h-5 w-5 text-primary"}),"Send Event Invite"]}),e.jsxs(Ir,{children:["Send a beautiful event invitation to ",w.length," selected member",w.length===1?"":"s",".",n.length!==w.length&&e.jsxs("span",{className:"block text-amber-600 mt-1",children:[n.length-w.length," skipped (missing or invalid email)"]})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(ee,{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(kt,{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(ms,{value:c,onValueChange:d,children:[e.jsx(us,{id:"event-select",children:e.jsx(fs,{placeholder:"Pick an upcoming event..."})}),e.jsx(hs,{children:a.map(E=>e.jsx(Ge,{value:E.id,children:e.jsxs("div",{className:"flex flex-col text-left",children:[e.jsx("span",{className:"font-medium",children:E.title}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[qwt(E.event_date),!E.is_published&&" · (Draft)"]})]})},E.id))})]})]}),b&&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(Ta,{className:"h-4 w-4 text-primary"}),b.title]}),e.jsx("div",{className:"text-xs text-muted-foreground",children:qwt(b.event_date)}),b.description&&e.jsx("p",{className:"text-xs text-muted-foreground line-clamp-2 mt-1",children:b.description})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"subject",children:"Subject line (optional)"}),e.jsx(pe,{id:"subject",placeholder:b?`You're invited: ${b.title}`:"You're invited to...",value:u,onChange:E=>h(E.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(ee,{htmlFor:"intro",children:"Personal message (optional)"}),e.jsx(Rs,{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:m,onChange:E=>f(E.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 (",w.length,")"]}),e.jsxs("div",{className:"flex flex-wrap gap-1 max-h-24 overflow-y-auto",children:[w.slice(0,30).map(E=>e.jsx(Be,{variant:"secondary",className:"text-xs font-normal",children:E.name||E.email},E.id)),w.length>30&&e.jsxs(Be,{variant:"outline",className:"text-xs",children:["+",w.length-30," more"]})]})]})]}),e.jsxs(Ar,{children:[e.jsx($,{variant:"outline",onClick:()=>t(!1),disabled:g,children:"Cancel"}),e.jsx($,{onClick:S,disabled:g||!c||w.length===0,children:g?e.jsxs(e.Fragment,{children:[e.jsx(kt,{className:"h-4 w-4 mr-2 animate-spin"})," Sending..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Yr,{className:"h-4 w-4 mr-2"})," Send to ",w.length]})})]})]})}),e.jsx(kc,{open:y,onOpenChange:v,children:e.jsxs(cc,{children:[e.jsxs(dc,{children:[e.jsx(hc,{children:"Send event invite?"}),e.jsx(mc,{children:b?e.jsxs(e.Fragment,{children:["Send invite for ",e.jsxs("span",{className:"font-medium text-foreground",children:['"',b.title,'"']})," to"," ",e.jsxs("span",{className:"font-medium text-foreground",children:[w.length," member",w.length===1?"":"s"]}),"?"]}):null})]}),e.jsxs(uc,{children:[e.jsx(fc,{children:"Cancel"}),e.jsxs(tc,{onClick:C,children:[e.jsx(Yr,{className:"h-4 w-4 mr-2"})," Send"]})]})]})})]})}const rmn=()=>{var iu;const s=Qn(),{user:t,isAdmin:n}=vs(),{startImpersonation:r,isLoading:a}=pLe(),{toast:i}=Bi(),[l,o]=j.useState([]),[c,d]=j.useState([]),[u,h]=j.useState([]),[m,f]=j.useState({}),[g,x]=j.useState(!0),[y,v]=j.useState({}),[b,w]=j.useState(!1),[S,C]=j.useState({email:"",name:"",password:"",brokerage_id:"",role:"user",phone:"",trial_days:""}),[E,I]=j.useState(!1),[P,R]=j.useState(""),[D,O]=j.useState(1),[U,W]=j.useState(50),[V,G]=j.useState("all"),[Y,X]=j.useState(!1),[ae,ie]=j.useState(!1),[ne,te]=j.useState({done:0,total:0}),[J,ce]=j.useState(null),[_e,he]=j.useState("all"),[ue,ve]=j.useState("all"),[Ee,Se]=j.useState("all"),[Le,Fe]=j.useState("all"),[ke,Ve]=j.useState(!1),[je,Ae]=j.useState(!1),[Ce,qe]=j.useState(!1),[ze,$e]=j.useState(""),[ct,Xe]=j.useState(!1),[it,at]=j.useState(null),[Ke,nt]=j.useState(null),[xt,rt]=j.useState(!1),[Yt,qt]=j.useState({name:"",email:"",brokerage_id:"",phone:""}),[ts,ys]=j.useState(null),[Bt,Ft]=j.useState(!1),[rs,St]=j.useState(""),[Xs,vt]=j.useState(!1),[gs,Ss]=j.useState(!1),[Is,Ys]=j.useState(null),[cs,js]=j.useState(""),[kn,Ws]=j.useState(!1),[On,ds]=j.useState(!1),[gn,As]=j.useState(null),[hr,Er]=j.useState(!1),[qn,hn]=j.useState(!1),[Fn,vn]=j.useState(null),[xs,Lr]=j.useState(""),[Or,ca]=j.useState(!1),[Jn,Sr]=j.useState({email:"",name:"",password:"",phone:""}),[Un,ur]=j.useState(!1),[Pa,ii]=j.useState(null),[$i,Rn]=j.useState([]),[xa,Ya]=j.useState("none"),[ho,Pc]=j.useState(!1),[$d,Nl]=j.useState(""),[Ho,ti]=j.useState(!1),[Xr,Eo]=j.useState(!1),[Ph,ih]=j.useState(""),[ao,ta]=j.useState(new Set),[xc,fl]=j.useState(!1),[Co,pu]=j.useState(!1),[nc,ad]=j.useState(null),[zr,Hi]=j.useState(!1),[Bc,$c]=j.useState(null),[yc,Ul]=j.useState([]),[rg,Lx]=j.useState([]),[Yo,Ic]=j.useState(!1),[Ih,cm]=j.useState({});j.useEffect(()=>{if(!t||!n){t&&!n&&x(!1);return}_s(),Xa()},[t,n]);const Xc=async()=>{try{const{data:Ut,error:Cn}=await q.from("brokerage_manager_assignments").select("user_id, brokerage_id");if(Cn)throw Cn;const ar={};for(const ra of Ut??[])ar[ra.brokerage_id]||(ar[ra.brokerage_id]=[]),ar[ra.brokerage_id].push(ra.user_id);f(ar)}catch(Ut){console.error("Error loading brokerage manager assignments:",Ut)}},_s=async()=>{try{x(!0);const{data:Ut,error:Cn}=await q.functions.invoke("get-user-details");if(Cn)throw Cn;const ar=Ut.users||[];o(ar),h(Ut.brokerages||[]),await Xc();const ra=ar.filter(Zr=>Zr.roles.includes("assistant"));if(ra.length>0){const Zr=ra.map(xi=>xi.id),{data:Aa}=await q.from("agent_assistant_assignments").select("agent_id, assistant_id").in("assistant_id",Zr);if(Aa&&Aa.length>0){const xi=[...new Set(Aa.map(zo=>zo.agent_id))],{data:Ia}=await q.from("profiles").select("id, name, email").in("id",xi),el={};for(const zo of Aa){const Lc=Ia==null?void 0:Ia.find(Mu=>Mu.id===zo.agent_id);Lc&&(el[zo.assistant_id]={agent_name:Lc.name||"",agent_email:Lc.email||""})}cm(el)}}}catch(Ut){console.error("Error loading members:",Ut),i({title:"Error",description:"Failed to load members",variant:"destructive"})}finally{x(!1)}},Xa=async()=>{try{const{data:Ut,error:Cn}=await q.from("app_tiles").select("id, name, icon, app_id, required_tags").order("name");if(Cn)throw Cn;d(Ut||[])}catch(Ut){console.error("Error loading apps:",Ut),i({title:"Error",description:"Failed to load apps",variant:"destructive"})}},No=async Ut=>{if(!Yt.name.trim()||!Yt.email.trim()){i({title:"Error",description:"Name and email are required",variant:"destructive"});return}if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(Yt.email)){i({title:"Error",description:"Please enter a valid email address",variant:"destructive"});return}try{const{error:ar}=await q.from("profiles").update({name:Yt.name.trim(),email:Yt.email.trim(),brokerage_id:Yt.brokerage_id||null,phone:Yt.phone.trim()||null}).eq("id",Ut);if(ar)throw ar;i({title:"Success",description:"Member details updated successfully"}),at(null),_s()}catch(ar){console.error("Error updating member:",ar),i({title:"Error",description:ar.message||"Failed to update member",variant:"destructive"})}},Ba=async Ut=>{try{const{data:{session:Cn}}=await q.auth.getSession(),ar=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/resend-welcome-email",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Cn==null?void 0:Cn.access_token}`},body:JSON.stringify({userId:Ut})}),ra=await ar.json();if(!ar.ok)throw new Error(ra.error||"Failed to resend welcome email");i({title:"Success",description:"Welcome email sent successfully"})}catch(Cn){console.error("Error resending welcome email:",Cn),i({title:"Error",description:Cn.message||"Failed to resend welcome email",variant:"destructive"})}},io=async(Ut,Cn)=>{try{const{error:ar}=await q.functions.invoke("send-password-reset",{body:{email:Ut,redirectTo:"https://dashboard.relevelup.com/profile?reset=true"}});if(ar)throw ar;i({title:"Password Reset Sent",description:`Password reset email sent to ${Cn}`})}catch(ar){console.error("Error sending password reset:",ar),i({title:"Error",description:ar.message||"Failed to send password reset email",variant:"destructive"})}},ko=async(Ut,Cn)=>{if(await fo(`Are you sure you want to delete ${Cn}? This action cannot be undone.`))try{const{data:{session:ar}}=await q.auth.getSession(),ra=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/delete-user",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${ar==null?void 0:ar.access_token}`},body:JSON.stringify({userId:Ut})}),Zr=await ra.json();if(!ra.ok)throw new Error(Zr.error||"Failed to delete user");i({title:"Success",description:"User deleted successfully"}),_s()}catch(ar){console.error("Error deleting user:",ar),i({title:"Error",description:ar.message||"Failed to delete user",variant:"destructive"})}},qi=async()=>{if(!S.email||!S.name||!S.password){i({title:"Error",description:"Please fill in all fields",variant:"destructive"});return}if(S.role==="brokerage_manager"&&!S.brokerage_id){i({title:"Error",description:"Please select a brokerage for this manager",variant:"destructive"});return}w(!0);try{const{data:{session:Ut}}=await q.auth.getSession(),Cn=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/create-user",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Ut==null?void 0:Ut.access_token}`},body:JSON.stringify(S)}),ar=await Cn.json();if(!Cn.ok)throw new Error(ar.error||"Failed to create user");if(S.role&&S.role!=="user"&&ar.userId){const ra=S.role==="brokerage_manager"?S.brokerage_id:void 0;await dm(ar.userId,S.role,"add",ra)}i({title:"Success",description:`User ${S.email} created successfully`}),C({email:"",name:"",password:"",brokerage_id:"",role:"user",phone:"",trial_days:""}),I(!1),_s()}catch(Ut){console.error("Error creating user:",Ut),i({title:"Error",description:Ut.message||"Failed to create user",variant:"destructive"})}finally{w(!1)}},dm=async(Ut,Cn,ar,ra)=>{try{const{data:{session:Zr}}=await q.auth.getSession(),Aa={userId:Ut,role:Cn,action:ar};if(Cn==="brokerage_manager"){if(!ra){i({title:"Error",description:"Please choose a brokerage for this manager assignment",variant:"destructive"});return}Aa.brokerageId=ra}const xi=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/manage-user-roles",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Zr==null?void 0:Zr.access_token}`},body:JSON.stringify(Aa)}),Ia=await xi.json();if(!xi.ok)throw new Error(Ia.error||"Failed to manage user role");i({title:"Success",description:`Role ${ar==="add"?"added":"removed"} successfully`}),_s()}catch(Zr){console.error("Error managing user role:",Zr),i({title:"Error",description:Zr.message||"Failed to manage user role",variant:"destructive"})}},Zo=(Ut,Cn)=>Cn.length===0?!0:Cn.some(ar=>Ut.includes(ar)),vo=async(Ut,Cn,ar)=>{const ra=`${Ut}-${Cn.id}`;ys(ra);try{if(ar){const Zr=l.find(xi=>xi.id===Ut),Aa=Cn.required_tags.filter(xi=>Zr==null?void 0:Zr.tags.includes(xi));for(const xi of Aa){const{error:Ia}=await q.from("user_tags").delete().eq("user_id",Ut).eq("tag",xi);if(Ia)throw Ia}i({title:"Access Removed",description:`Removed access to ${Cn.name}`})}else if(Cn.required_tags.length>0){const{error:Zr}=await q.from("user_tags").insert({user_id:Ut,tag:Cn.required_tags[0]});if(Zr)throw Zr;i({title:"Access Granted",description:`Granted access to ${Cn.name}`})}await _s()}catch(Zr){console.error("Error toggling access:",Zr),i({title:"Error",description:Zr.message||"Failed to update access",variant:"destructive"})}finally{ys(null)}},Zg=async()=>{const Ut=rs.trim();if(!Ut){i({title:"Error",description:"Brokerage name is required",variant:"destructive"});return}if(Ut.length>100){i({title:"Error",description:"Brokerage name must be less than 100 characters",variant:"destructive"});return}if(u.find(ar=>ar.name.toLowerCase()===Ut.toLowerCase())){i({title:"Error",description:"A brokerage with this name already exists",variant:"destructive"});return}vt(!0);try{const{error:ar}=await q.from("brokerages").insert({name:Ut});if(ar)throw ar;i({title:"Success",description:`Brokerage "${Ut}" created successfully`}),St(""),Ft(!1),_s()}catch(ar){console.error("Error creating brokerage:",ar),i({title:"Error",description:ar.message||"Failed to create brokerage",variant:"destructive"})}finally{vt(!1)}},Ol=Ut=>{Ys(Ut),js(Ut.name),Ss(!0)},zl=()=>{Ys(null),js(""),Ss(!1)},vy=async()=>{if(!Is)return;const Ut=cs.trim();if(!Ut){i({title:"Error",description:"Brokerage name is required",variant:"destructive"});return}if(Ut.length>100){i({title:"Error",description:"Brokerage name must be less than 100 characters",variant:"destructive"});return}Ws(!0);try{const{error:Cn}=await q.from("brokerages").update({name:Ut}).eq("id",Is.id);if(Cn)throw Cn;i({title:"Success",description:"Brokerage updated successfully"}),zl(),_s()}catch(Cn){console.error("Error updating brokerage:",Cn),i({title:"Error",description:Cn.message||"Failed to update brokerage",variant:"destructive"})}finally{Ws(!1)}},Xd=async(Ut,Cn)=>{var ar;if(!Cn||typeof Cn!="string"){i({title:"Error",description:"Please select a brokerage first",variant:"destructive"});return}try{const ra={userId:Ut,role:"brokerage_manager",action:"add",brokerageId:Cn};console.debug("[assignManagerToBrokerage] payload",ra);const{data:{session:Zr}}=await q.auth.getSession(),Aa=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/manage-user-roles",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Zr==null?void 0:Zr.access_token}`},body:JSON.stringify(ra)}),xi=await Aa.json();if(!Aa.ok&&!((ar=xi.error)!=null&&ar.includes("duplicate")))throw new Error(xi.error||"Failed to add role");i({title:"Success",description:"Manager assigned to brokerage"}),await _s()}catch(ra){console.error("Error assigning manager:",ra),i({title:"Error",description:ra.message||"Failed to assign manager",variant:"destructive"})}},Wh=Ut=>{As(Ut),ds(!0)},df=async()=>{if(gn){Er(!0);try{const Ut=l.filter(ra=>ra.brokerage_id===gn.id),{data:{session:Cn}}=await q.auth.getSession();for(const ra of Ut){const Zr=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/delete-user",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Cn==null?void 0:Cn.access_token}`},body:JSON.stringify({userId:ra.id})});if(!Zr.ok){const Aa=await Zr.json();console.error(`Failed to delete user ${ra.email}:`,Aa.error)}}const{error:ar}=await q.from("brokerages").delete().eq("id",gn.id);if(ar)throw ar;i({title:"Success",description:`Brokerage "${gn.name}" and ${Ut.length} member(s) deleted`}),ds(!1),As(null),_s()}catch(Ut){console.error("Error deleting brokerage:",Ut),i({title:"Error",description:Ut.message||"Failed to delete brokerage",variant:"destructive"})}finally{Er(!1)}}},Yy=Ut=>{vn(Ut),Lr(""),hn(!0)},oh=()=>{vn(null),Lr(""),hn(!1)},xh=async Ut=>{try{const{error:Cn}=await q.from("profiles").update({brokerage_id:null}).eq("id",Ut);if(Cn)throw Cn;i({title:"Success",description:"User removed from brokerage"}),_s()}catch(Cn){console.error("Error removing user from brokerage:",Cn),i({title:"Error",description:Cn.message||"Failed to remove user",variant:"destructive"})}},gt=async(Ut,Cn)=>{try{const{error:ar}=await q.from("profiles").update({brokerage_id:Cn}).eq("id",Ut);if(ar)throw ar;i({title:"Success",description:"User added to brokerage"}),_s()}catch(ar){console.error("Error adding user to brokerage:",ar),i({title:"Error",description:ar.message||"Failed to add user",variant:"destructive"})}};j.useEffect(()=>{(async()=>{var Cn;if(!(Fn!=null&&Fn.id)){ii(null),Rn([]),Ya("none");return}try{const{data:ar}=await q.from("partnership_programs").select("id, name, enabled").eq("brokerage_id",Fn.id).maybeSingle();if(!ar||!ar.enabled){ii(null),Rn([]),Ya("none");return}const{data:ra}=await q.from("partnership_packages").select("id, name, description, sort_order").eq("program_id",ar.id).order("sort_order",{ascending:!0});ii({id:ar.id,name:ar.name}),Rn(ra||[]),Ya(((Cn=ra==null?void 0:ra[0])==null?void 0:Cn.id)||"none")}catch(ar){console.error("Error loading partnership packages:",ar)}})()},[Fn==null?void 0:Fn.id]);const We=async()=>{if(!Fn||!Jn.email||!Jn.name||!Jn.password){i({title:"Error",description:"Please fill in all fields",variant:"destructive"});return}ur(!0);try{const{data:{session:Ut}}=await q.auth.getSession(),Cn=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/create-user",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Ut==null?void 0:Ut.access_token}`},body:JSON.stringify({...Jn,brokerage_id:Fn.id,role:"user",partnershipPackageId:Pa&&xa!=="none"?xa:void 0})}),ar=await Cn.json();if(!Cn.ok)throw new Error(ar.error||"Failed to create agent");i({title:"Success",description:`Agent ${Jn.email} created successfully`}),Sr({email:"",name:"",password:"",phone:""}),ca(!1),_s()}catch(Ut){console.error("Error creating agent:",Ut),i({title:"Error",description:Ut.message||"Failed to create agent",variant:"destructive"})}finally{ur(!1)}},ut=Ut=>l.filter(Cn=>Cn.brokerage_id===Ut),jt=Ut=>{const Cn=ut(Ut);if(!xs)return Cn;const ar=xs.toLowerCase();return Cn.filter(ra=>ra.name.toLowerCase().includes(ar)||ra.email.toLowerCase().includes(ar))},Rt=Ut=>l.filter(Cn=>Cn.brokerage_id!==Ut),zt=l.filter(Ut=>{var ar;if(P){const ra=P.toLowerCase();if(!(Ut.name.toLowerCase().includes(ra)||Ut.email.toLowerCase().includes(ra)||((ar=Ut.brokerage_name)==null?void 0:ar.toLowerCase().includes(ra))))return!1}if(V==="claimed"&&!Ut.claimed||V==="unclaimed"&&Ut.claimed||_e!=="all"&&!Ut.roles.includes(_e))return!1;const Cn=Ut.is_trial||Ut.subscription_status==="trialing";if(ue==="trial"&&!Cn||ue==="non-trial"&&Cn||Ee==="none"&&Ut.brokerage_id||Ee!=="all"&&Ee!=="none"&&Ut.brokerage_id!==Ee)return!1;if(Le!=="all"){if(!Ut.created_at)return!1;const ra=parseInt(Le,10),Zr=Date.now()-ra*24*60*60*1e3;if(new Date(Ut.created_at).getTime(){var Cn;return((Cn=Ut.name)==null?void 0:Cn.toLowerCase())||""},brokerage:Ut=>{var Cn;return((Cn=Ut.brokerage_name)==null?void 0:Cn.toLowerCase())||""},status:Ut=>Ut.claimed?"active":"pending",role:Ut=>Ut.roles[0]||"",last_login:Ut=>Ut.last_sign_in_at?new Date(Ut.last_sign_in_at).getTime():null,created_at:Ut=>Ut.created_at?new Date(Ut.created_at).getTime():null}),fn=Ps.length,xn=U===0,bn=xn?1:Math.ceil(fn/U),Pn=xn?0:(D-1)*U,or=xn?fn:Pn+U,tr=Ps.slice(Pn,or),sr=Ut=>{R(Ut),O(1)},br=Ut=>{W(Ut),O(1)},vr=(Ut,Cn)=>{Ut(Cn),O(1)},Va=async(Ut,Cn)=>{Ae(!0);try{const ar=l.find(xi=>xi.id===Ut);if(!ar)return;const ra=ar.trial_expires_at?new Date(ar.trial_expires_at):new Date,Zr=new Date(ra.getTime()+Cn*24*60*60*1e3),{error:Aa}=await q.from("profiles").update({trial_expires_at:Zr.toISOString()}).eq("id",Ut);if(Aa)throw Aa;i({title:"Trial Extended",description:`Trial extended by ${Cn} days`}),_s()}catch(ar){console.error("Error extending trial:",ar),i({title:"Error",description:ar.message||"Failed to extend trial",variant:"destructive"})}finally{Ae(!1)}},Je=async(Ut,Cn,ar)=>{qe(!0);try{const{error:ra}=await q.from("profiles").update({is_paused:Cn,paused_at:Cn?new Date().toISOString():null,paused_reason:Cn&&(ar==null?void 0:ar.trim())||null}).eq("id",Ut);if(ra)throw ra;o(Zr=>Zr.map(Aa=>Aa.id===Ut?{...Aa,is_paused:Cn,paused_reason:Cn&&(ar==null?void 0:ar.trim())||null,paused_at:Cn?new Date().toISOString():null}:Aa)),nt(Zr=>Zr&&Zr.id===Ut?{...Zr,is_paused:Cn,paused_reason:Cn&&(ar==null?void 0:ar.trim())||null}:Zr),i({title:Cn?"Account paused":"Account reactivated",description:Cn?"This member can no longer sign in and will see a paused message.":"This member can sign in again."})}catch(ra){console.error("Error updating pause state:",ra),i({title:"Error",description:ra.message||"Failed to update account",variant:"destructive"})}finally{qe(!1)}},Ht=async Ut=>{Xe(!0);try{const{error:Cn}=await q.from("profiles").update({is_trial:!1,trial_expires_at:null,trial_started_at:null,trial_claimed_at:null}).eq("id",Ut);if(Cn)throw Cn;i({title:"Account Converted",description:"User has been converted to a full account"}),_s(),Qr()}catch(Cn){console.error("Error converting trial:",Cn),i({title:"Error",description:Cn.message||"Failed to convert account",variant:"destructive"})}finally{Xe(!1)}},[Ts,ln]=j.useState(!1),tn=async(Ut,Cn)=>{if(await fo(`Revert this user to a ${Cn}-day free trial? This will clear their paid/grandfathered status. Any active Stripe subscription will need to be cancelled separately.`)){ln(!0);try{const ar=new Date,ra=new Date(ar.getTime()+Cn*24*60*60*1e3),{error:Zr}=await q.from("profiles").update({is_trial:!0,trial_started_at:ar.toISOString(),trial_expires_at:ra.toISOString(),trial_claimed_at:ar.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",Ut);if(Zr)throw Zr;i({title:"Reverted to Trial",description:`User is now on a ${Cn}-day free trial.`}),_s()}catch(ar){console.error("Error reverting to trial:",ar),i({title:"Error",description:ar.message||"Failed to revert to trial",variant:"destructive"})}finally{ln(!1)}}},nr=async Ut=>{Ic(!0);try{const{data:Cn}=await q.from("agent_assistant_assignments").select("id, assistant_id, permissions").eq("agent_id",Ut);if(Cn&&Cn.length>0){const ra=Cn.map(Aa=>Aa.assistant_id),{data:Zr}=await q.from("profiles").select("id, name, email").in("id",ra);Ul(Cn.map(Aa=>{const xi=Zr==null?void 0:Zr.find(Ia=>Ia.id===Aa.assistant_id);return{id:Aa.id,assistant_id:Aa.assistant_id,assistant_name:(xi==null?void 0:xi.name)||"Unknown",assistant_email:(xi==null?void 0:xi.email)||"",permissions:Aa.permissions||{}}}))}else Ul([]);const{data:ar}=await q.from("agent_assistant_assignments").select("id, agent_id, permissions").eq("assistant_id",Ut);if(ar&&ar.length>0){const ra=ar.map(Aa=>Aa.agent_id),{data:Zr}=await q.from("profiles").select("id, name, email").in("id",ra);Lx(ar.map(Aa=>{const xi=Zr==null?void 0:Zr.find(Ia=>Ia.id===Aa.agent_id);return{id:Aa.id,agent_id:Aa.agent_id,agent_name:(xi==null?void 0:xi.name)||"Unknown",agent_email:(xi==null?void 0:xi.email)||"",permissions:Aa.permissions||{}}}))}else Lx([])}catch(Cn){console.error("Error loading assistant data:",Cn)}finally{Ic(!1)}},rr=Ut=>{nt(Ut),qt({name:Ut.name,email:Ut.email,brokerage_id:Ut.brokerage_id||"",phone:Ut.phone||""}),rt(!0),nr(Ut.id)},Qr=()=>{nt(null),rt(!1),qt({name:"",email:"",brokerage_id:"",phone:""})},na=async()=>{Ke&&(await No(Ke.id),Qr())},$a=Ut=>{ta(Cn=>{const ar=new Set(Cn);return ar.has(Ut)?ar.delete(Ut):ar.add(Ut),ar})},Na=()=>{if(ao.size===tr.length&&tr.every(Ut=>ao.has(Ut.id))){const Ut=new Set(ao);tr.forEach(Cn=>Ut.delete(Cn.id)),ta(Ut)}else{const Ut=new Set(ao);tr.forEach(Cn=>Ut.add(Cn.id)),ta(Ut)}},La=()=>{ta(new Set)},to=async()=>{if(ao.size===0)return;fl(!0);let Ut=0,Cn=0;try{const{data:{session:ar}}=await q.auth.getSession();for(const ra of ao)try{(await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/resend-welcome-email",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${ar==null?void 0:ar.access_token}`},body:JSON.stringify({userId:ra,redirectTo:"https://dashboard.relevelup.com/profile?reset=true"})})).ok?Ut++:Cn++}catch{Cn++}i({title:"Bulk Email Complete",description:`Sent ${Ut} emails${Cn>0?`, ${Cn} failed`:""}`}),La()}catch(ar){i({title:"Error",description:ar.message||"Failed to send emails",variant:"destructive"})}finally{fl(!1)}},xo=async()=>{if(ao.size===0)return;fl(!0);let Ut=0,Cn=0;try{const{data:{session:ar}}=await q.auth.getSession();for(const ra of ao)try{(await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/send-password-reset",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${ar==null?void 0:ar.access_token}`},body:JSON.stringify({userId:ra})})).ok?Ut++:Cn++}catch{Cn++}i({title:"Bulk Password Reset Complete",description:`Sent ${Ut} reset emails${Cn>0?`, ${Cn} failed`:""}`}),La()}catch(ar){i({title:"Error",description:ar.message||"Failed to send password reset emails",variant:"destructive"})}finally{fl(!1)}},oo=async Ut=>{ie(!0),te({done:0,total:Ut.length});const Cn=[];try{const{data:{session:ar}}=await q.auth.getSession(),ra=5;for(let Aa=0;Aa{try{const el=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/send-password-reset",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${ar==null?void 0:ar.access_token}`},body:JSON.stringify({userId:Ia.id,variant:"activation"})}),zo=await el.json().catch(()=>({}));el.ok&&(zo==null?void 0:zo.sent)!==!1?Cn.push({email:Ia.email,ok:!0}):Cn.push({email:Ia.email,ok:!1,reason:(zo==null?void 0:zo.reason)||`HTTP ${el.status}`})}catch(el){Cn.push({email:Ia.email,ok:!1,reason:(el==null?void 0:el.message)||"Network error"})}})),te({done:Math.min(Aa+ra,Ut.length),total:Ut.length}),Aa+rasetTimeout(Ia,1200))}ce(Cn);const Zr=Cn.filter(Aa=>Aa.ok).length;i({title:"Activation emails sent",description:`${Zr} of ${Ut.length} sent successfully`})}finally{ie(!1)}},Lo=async()=>{if(ao.size===0)return;const Ut=l.filter(Zr=>ao.has(Zr.id)).map(Zr=>Zr.name).slice(0,5).join(", "),Cn=ao.size>5?` and ${ao.size-5} more`:"";if(!await fo(`Are you sure you want to delete ${ao.size} users (${Ut}${Cn})? This action cannot be undone.`))return;fl(!0);let ar=0,ra=0;try{const{data:{session:Zr}}=await q.auth.getSession();for(const Aa of ao)try{(await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/delete-user",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Zr==null?void 0:Zr.access_token}`},body:JSON.stringify({userId:Aa})})).ok?ar++:ra++}catch{ra++}i({title:"Bulk Delete Complete",description:`Deleted ${ar} users${ra>0?`, ${ra} failed`:""}`}),La(),_s()}catch(Zr){i({title:"Error",description:Zr.message||"Failed to delete users",variant:"destructive"})}finally{fl(!1)}},ql=async()=>{pu(!0);try{const{data:{session:Ut}}=await q.auth.getSession(),Cn=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/ghl-phone-sync",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Ut==null?void 0:Ut.access_token}`}});if(!Cn.ok){const ra=await Cn.json();throw new Error(ra.error||"Failed to sync phones")}const ar=await Cn.json();i({title:"Phone Sync Complete",description:`Pulled ${ar.summary.pulledFromGHL} from GHL, pushed ${ar.summary.pushedToGHL} to GHL, ${ar.summary.alreadySynced} already synced`}),_s()}catch(Ut){i({title:"Error",description:Ut.message||"Failed to sync phones with GHL",variant:"destructive"})}finally{pu(!1)}},po=async(Ut,Cn)=>{ad(Ut);try{const{data:{session:ar}}=await q.auth.getSession(),{data:ra}=await q.from("profiles").select("phone").eq("id",Ut).single(),Zr=(ra==null?void 0:ra.phone)||"",Aa=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/ghl-tag-sync",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${ar==null?void 0:ar.access_token}`},body:JSON.stringify({email:Cn,action:"update",phone:Zr||void 0})});if(!Aa.ok){const Ia=await Aa.json();throw new Error(Ia.error||"Failed to sync with GHL")}const xi=await fetch(`https://services.leadconnectorhq.com/contacts/lookup?locationId=&email=${encodeURIComponent(Cn)}`,{method:"GET",headers:{"Content-Type":"application/json"}});i({title:"Phone Synced",description:Zr?`Phone ${Zr} synced to GHL`:"Sync attempted - run bulk sync to pull phone from GHL"}),_s()}catch(ar){i({title:"Error",description:ar.message||"Failed to sync phone",variant:"destructive"})}finally{ad(null)}},nl=async Ut=>{await r(Ut)},Il=()=>{if(ao.size===0){i({title:"No members selected",description:"Please select members to export",variant:"destructive"});return}const Ut=l.filter(Ia=>ao.has(Ia.id)),Cn=["Name","Email","Phone","Brokerage","Roles","Status","Created At"],ar=Ut.map(Ia=>[Ia.name,Ia.email,Ia.phone||"",Ia.brokerage_name||"",Ia.roles.join("; "),Ia.claimed?"Claimed":"Unclaimed",new Date(Ia.created_at).toLocaleDateString()]),ra=[Cn.join(","),...ar.map(Ia=>Ia.map(el=>`"${(el||"").replace(/"/g,'""')}"`).join(","))].join(` `),Zr=new Blob([ra],{type:"text/csv"}),Aa=URL.createObjectURL(Zr),xi=document.createElement("a");xi.href=Aa,xi.download=`members-export-${new Date().toISOString().split("T")[0]}.csv`,xi.click(),URL.revokeObjectURL(Aa),i({title:"Export complete",description:`Exported ${Ut.length} member(s)`})},Ed=()=>{if(zt.length===0){i({title:"No members to export",description:"Adjust filters to include at least one member",variant:"destructive"});return}const Ut=["Name","Email","Phone","Brokerage","Roles","Status","Created At"],Cn=zt.map(Ia=>[Ia.name,Ia.email,Ia.phone||"",Ia.brokerage_name||"",Ia.roles.join("; "),Ia.claimed?"Claimed":"Unclaimed",Ia.created_at?new Date(Ia.created_at).toLocaleDateString():""]),ar=[Ut.join(","),...Cn.map(Ia=>Ia.map(el=>`"${(el||"").replace(/"/g,'""')}"`).join(","))].join(` `),ra=new Blob([ar],{type:"text/csv"}),Zr=URL.createObjectURL(ra),Aa=document.createElement("a"),xi=Le!=="all"?`-last-${Le}days`:"";Aa.href=Zr,Aa.download=`members-export${xi}-${new Date().toISOString().split("T")[0]}.csv`,Aa.click(),URL.revokeObjectURL(Zr),i({title:"Export complete",description:`Exported ${zt.length} member(s)`})};return g?e.jsx(Vs,{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(Vs,{title:"Members",children:[e.jsxs("div",{className:"space-y-6",children:[e.jsx(Fm,{title:"Member Management",description:"Manage users, roles, and permissions",children:e.jsxs($,{size:"sm",variant:"outline",onClick:()=>s("/admin/unassigned-members"),className:"gap-2",children:[e.jsx(wl,{className:"h-4 w-4 text-amber-500"}),"Unassigned Members"]})}),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($,{size:"sm",variant:"outline",onClick:ql,disabled:Co,children:[Co?e.jsx(kt,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(Da,{className:"mr-2 h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:Co?"Syncing...":"Sync Phones with GHL"}),e.jsx("span",{className:"sm:hidden",children:Co?"Syncing...":"Sync GHL"})]}),e.jsxs($,{size:"sm",variant:"outline",onClick:()=>Pc(!0),children:[e.jsx(ek,{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(zs,{open:E,onOpenChange:I,children:[e.jsx(jl,{asChild:!0,children:e.jsxs($,{size:"sm",children:[e.jsx(sc,{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(Os,{children:[e.jsxs(Us,{children:[e.jsx(Bs,{children:"Create New User"}),e.jsx(Ir,{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(ee,{htmlFor:"name",children:"Name"}),e.jsx(pe,{id:"name",placeholder:"John Doe",value:S.name,onChange:Ut=>C({...S,name:Ut.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"email",children:"Email"}),e.jsx(pe,{id:"email",type:"email",placeholder:"john@example.com",value:S.email,onChange:Ut=>C({...S,email:Ut.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"password",children:"Password"}),e.jsx(pe,{id:"password",type:"password",placeholder:"Min 6 characters",value:S.password,onChange:Ut=>C({...S,password:Ut.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"phone",children:"Phone (optional)"}),e.jsx(pe,{id:"phone",type:"tel",placeholder:"555-123-4567",value:S.phone,onChange:Ut=>C({...S,phone:Ut.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ee,{htmlFor:"brokerage",children:["Brokerage",S.role==="brokerage_manager"?" (required)":""]}),e.jsxs(ms,{value:S.brokerage_id||"none",onValueChange:Ut=>C({...S,brokerage_id:Ut==="none"?"":Ut}),children:[e.jsx(us,{id:"brokerage",children:e.jsx(fs,{placeholder:S.role==="brokerage_manager"?"Select brokerage":"Select brokerage (optional)"})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"none",children:"None"}),u.map(Ut=>e.jsx(Ge,{value:Ut.id,children:Ut.name},Ut.id))]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"role",children:"Role"}),e.jsxs(ms,{value:S.role,onValueChange:Ut=>C({...S,role:Ut}),children:[e.jsx(us,{id:"role",children:e.jsx(fs,{placeholder:"Select role"})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"user",children:"User"}),e.jsx(Ge,{value:"moderator",children:"Moderator"}),e.jsx(Ge,{value:"brokerage_manager",children:"Brokerage Manager"}),e.jsx(Ge,{value:"admin",children:"Admin"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"trial_days",children:"Trial Period (optional)"}),e.jsxs(ms,{value:S.trial_days||"none",onValueChange:Ut=>C({...S,trial_days:Ut==="none"?"":Ut}),children:[e.jsx(us,{id:"trial_days",children:e.jsx(fs,{placeholder:"No trial (full access)"})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"none",children:"No trial (full access)"}),e.jsx(Ge,{value:"7",children:"7-day trial"}),e.jsx(Ge,{value:"30",children:"30-day trial"}),e.jsx(Ge,{value:"60",children:"60-day trial"}),e.jsx(Ge,{value:"90",children:"90-day trial"}),e.jsx(Ge,{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(Ar,{children:[e.jsx($,{variant:"outline",onClick:()=>I(!1),children:"Cancel"}),e.jsx($,{onClick:qi,disabled:b,children:b?"Creating...":"Create User"})]})]})]})]})]}),e.jsxs(ha,{defaultValue:new URLSearchParams(window.location.search).get("tab")||"members",className:"space-y-6",children:[e.jsxs(ma,{children:[e.jsx(Zt,{value:"members",children:"Members"}),e.jsx(Zt,{value:"brokerages",children:"Brokerages"}),e.jsx(Zt,{value:"teams",children:"Teams"}),e.jsx(Zt,{value:"trials",children:"Trial Users"}),e.jsx(Zt,{value:"access",children:"Access Matrix"}),e.jsx(Zt,{value:"celebrations",children:"Celebrations"}),e.jsx(Zt,{value:"deletions",children:"Deletion Log"})]}),e.jsxs(Xt,{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(Kr,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(pe,{placeholder:"Search members...",value:P,onChange:Ut=>sr(Ut.target.value),className:"pl-10 h-9"})]}),e.jsxs(ms,{value:V,onValueChange:Ut=>vr(G,Ut),children:[e.jsx(us,{className:"w-[130px] h-9",children:e.jsx(fs,{})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"all",children:"All Status"}),e.jsx(Ge,{value:"claimed",children:"Active"}),e.jsx(Ge,{value:"unclaimed",children:"Pending"})]})]}),e.jsxs(ms,{value:_e,onValueChange:Ut=>vr(he,Ut),children:[e.jsx(us,{className:"w-[130px] h-9",children:e.jsx(fs,{})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"all",children:"All Roles"}),e.jsx(Ge,{value:"admin",children:"Admin"}),e.jsx(Ge,{value:"brokerage_manager",children:"Manager"}),e.jsx(Ge,{value:"assistant",children:"Assistant"}),e.jsx(Ge,{value:"user",children:"User"})]})]}),e.jsxs(ms,{value:ue,onValueChange:Ut=>vr(ve,Ut),children:[e.jsx(us,{className:"w-[130px] h-9",children:e.jsx(fs,{})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"all",children:"All Users"}),e.jsx(Ge,{value:"trial",children:"Trial Only"}),e.jsx(Ge,{value:"non-trial",children:"Full Only"})]})]}),e.jsxs(ms,{value:Ee,onValueChange:Ut=>vr(Se,Ut),children:[e.jsx(us,{className:"w-[150px] h-9",children:e.jsx(fs,{})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"all",children:"All Brokerages"}),e.jsx(Ge,{value:"none",children:"No Brokerage"}),u.map(Ut=>e.jsx(Ge,{value:Ut.id,children:Ut.name},Ut.id))]})]}),e.jsxs(ms,{value:Le,onValueChange:Ut=>vr(Fe,Ut),children:[e.jsx(us,{className:"w-[150px] h-9",children:e.jsx(fs,{})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"all",children:"Any Join Date"}),e.jsx(Ge,{value:"30",children:"Joined Last 30 Days"}),e.jsx(Ge,{value:"60",children:"Joined Last 60 Days"}),e.jsx(Ge,{value:"90",children:"Joined Last 90 Days"})]})]}),e.jsxs($,{size:"sm",variant:"outline",className:"h-9",onClick:Ed,title:"Export currently filtered members to CSV",children:[e.jsx(di,{className:"h-4 w-4 mr-1"}),"Export Filtered"]}),e.jsxs($,{size:"sm",variant:"outline",className:"h-9",disabled:Ps.filter(Ut=>!Ut.claimed&&Ut.email).length===0,onClick:()=>{ce(null),X(!0)},title:"Email every pending (never signed in) member a link to set their password",children:[e.jsx(mn,{className:"h-4 w-4 mr-1"}),"Email Pending (",Ps.filter(Ut=>!Ut.claimed&&Ut.email).length,")"]}),e.jsx(zs,{open:Y,onOpenChange:Ut=>{ae||X(Ut)},children:e.jsxs(Os,{className:"max-w-lg",children:[e.jsxs(Us,{children:[e.jsx(Bs,{children:"Email pending members"}),e.jsx(Ir,{children:'Sends the branded "Activate your account" email with a set-password link to every member in the current filter who has never signed in. Sent in small batches, so this can take a few minutes.'})]}),ae&&e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Sending… ",ne.done," of ",ne.total]}),J&&!ae&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("p",{className:"text-sm",children:[J.filter(Ut=>Ut.ok).length," sent",J.some(Ut=>!Ut.ok)&&`, ${J.filter(Ut=>!Ut.ok).length} failed`]}),J.some(Ut=>!Ut.ok)&&e.jsx("div",{className:"max-h-48 overflow-y-auto rounded border p-2 text-xs space-y-1",children:J.filter(Ut=>!Ut.ok).map(Ut=>e.jsxs("div",{className:"flex justify-between gap-2",children:[e.jsx("span",{className:"truncate",children:Ut.email}),e.jsx("span",{className:"text-muted-foreground truncate",children:Ut.reason})]},Ut.email))})]}),e.jsxs(Ar,{children:[e.jsx($,{variant:"outline",disabled:ae,onClick:()=>X(!1),children:"Close"}),!J&&e.jsx($,{disabled:ae,onClick:()=>oo(Ps.filter(Ut=>!Ut.claimed&&Ut.email).map(Ut=>({id:Ut.id,email:Ut.email,name:Ut.name}))),children:ae?e.jsxs(e.Fragment,{children:[e.jsx(kt,{className:"h-4 w-4 mr-1 animate-spin"}),"Sending…"]}):`Send to ${Ps.filter(Ut=>!Ut.claimed&&Ut.email).length} members`})]})]})}),(P||V!=="all"||_e!=="all"||ue!=="all"||Ee!=="all"||Le!=="all")&&e.jsxs($,{variant:"ghost",size:"sm",className:"h-9",onClick:()=>{R(""),G("all"),he("all"),ve("all"),Se("all"),Fe("all"),O(1)},children:[e.jsx(gr,{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:xn?`Showing all ${fn} members`:`Showing ${Pn+1}-${Math.min(or,fn)} of ${fn} members`}),e.jsxs(ms,{value:U.toString(),onValueChange:Ut=>br(Number(Ut)),children:[e.jsx(us,{className:"h-9 w-[110px]",children:e.jsx(fs,{})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"50",children:"50 / page"}),e.jsx(Ge,{value:"100",children:"100 / page"}),e.jsx(Ge,{value:"250",children:"250 / page"}),e.jsx(Ge,{value:"0",children:"All"})]})]})]})]}),ao.size>0&&e.jsxs("div",{className:"flex flex-col gap-2 p-3 bg-primary/10 border border-primary/20 rounded-lg",children:[tr.length>0&&tr.every(Ut=>ao.has(Ut.id))&&Ps.length>ao.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 ",ao.size," on this page are selected."]}),e.jsxs($,{size:"sm",variant:"link",className:"h-auto p-0 text-primary",onClick:()=>ta(new Set(Ps.map(Ut=>Ut.id))),children:["Select all ",Ps.length," filtered members"]})]}),Ps.length>0&&ao.size===Ps.length&&e.jsxs("div",{className:"px-1 text-sm text-muted-foreground",children:["All ",Ps.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(Kj,{className:"h-4 w-4 text-primary"}),e.jsxs("span",{className:"text-sm font-medium",children:[ao.size," selected"]})]}),e.jsx("div",{className:"flex-1"}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs($,{size:"sm",variant:"outline",onClick:to,disabled:xc,children:[xc?e.jsx(kt,{className:"h-4 w-4 animate-spin mr-1"}):e.jsx(mn,{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($,{size:"sm",variant:"outline",onClick:xo,disabled:xc,children:[xc?e.jsx(kt,{className:"h-4 w-4 animate-spin mr-1"}):e.jsx(S_,{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($,{size:"sm",variant:"outline",onClick:()=>Ve(!0),disabled:xc,className:"bg-primary/5 border-primary/30 text-primary hover:bg-primary/10",children:[e.jsx(JS,{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($,{size:"sm",variant:"outline",onClick:Il,children:[e.jsx(di,{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($,{size:"sm",variant:"destructive",onClick:Lo,disabled:xc,children:[xc?e.jsx(kt,{className:"h-4 w-4 animate-spin mr-1"}):e.jsx(Wn,{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($,{size:"sm",variant:"ghost",onClick:La,disabled:xc,children:e.jsx(gr,{className:"h-4 w-4"})})]})]})]}),e.jsx("div",{className:"border rounded-lg bg-card overflow-hidden",children:e.jsxs(mi,{children:[e.jsx(fi,{children:e.jsxs(En,{className:"bg-muted/30 hover:bg-muted/30",children:[e.jsx(Dt,{className:"w-[50px]",children:e.jsx(ai,{checked:tr.length>0&&tr.every(Ut=>ao.has(Ut.id)),onCheckedChange:Na,"aria-label":"Select all on page"})}),e.jsx(Im,{sortKey:"name",currentSortKey:Wt,currentDirection:ws,onSort:Ms,children:"Name"}),e.jsx(Im,{sortKey:"brokerage",currentSortKey:Wt,currentDirection:ws,onSort:Ms,children:"Brokerage"}),e.jsx(Im,{sortKey:"status",currentSortKey:Wt,currentDirection:ws,onSort:Ms,children:"Status"}),e.jsx(Im,{sortKey:"role",currentSortKey:Wt,currentDirection:ws,onSort:Ms,children:"Role"}),e.jsx(Im,{sortKey:"last_login",currentSortKey:Wt,currentDirection:ws,onSort:Ms,children:"Last Login"}),e.jsx(Im,{sortKey:"created_at",currentSortKey:Wt,currentDirection:ws,onSort:Ms,children:"Member Since"}),e.jsx(Dt,{className:"w-[100px]"})]})}),e.jsx(pi,{children:tr.length===0?e.jsx(En,{children:e.jsx(wt,{colSpan:8,className:"text-center py-12 text-muted-foreground",children:"No members found"})}):tr.map(Ut=>e.jsxs(En,{className:`hover:bg-muted/30 ${ao.has(Ut.id)?"bg-primary/5":""}`,children:[e.jsx(wt,{children:e.jsx(ai,{checked:ao.has(Ut.id),onCheckedChange:()=>$a(Ut.id),"aria-label":`Select ${Ut.name}`})}),e.jsx(wt,{children:e.jsxs("div",{children:[e.jsx("button",{onClick:()=>rr(Ut),className:"text-primary hover:underline font-medium text-left",children:Ut.name}),e.jsx("div",{className:"text-xs text-muted-foreground",children:Ut.email})]})}),e.jsx(wt,{className:"text-muted-foreground",children:Ut.brokerage_name||"—"}),e.jsx(wt,{children:e.jsx("div",{className:"flex flex-col",children:(()=>{const Cn=Ut.trial_expires_at||Ut.subscription_end_date;if((Ut.is_trial||Ut.subscription_status==="trialing")&&Cn){const ra=Math.ceil((new Date(Cn).getTime()-Date.now())/864e5),Zr=ra<=0,Aa=ra<=3;return e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(Be,{variant:"outline",className:Pt("w-fit",Zr?"border-destructive text-destructive":Aa?"border-amber-500 text-amber-600":"border-violet-300 text-violet-700 bg-violet-50"),children:Zr?"Trial Expired":`Trial · ${ra}d left`}),e.jsx("button",{type:"button",title:"Copy upgrade link — paste into an email so this agent can sign in and pay on their existing account",className:"text-muted-foreground hover:text-primary transition-colors",onClick:async()=>{const xi="https://dashboard.relevelup.com/upgrade";try{await navigator.clipboard.writeText(xi),i({title:"Upgrade link copied",description:xi})}catch{window.prompt("Copy this upgrade link:",xi)}},children:e.jsx(Ha,{className:"h-3.5 w-3.5"})})]})}return e.jsx(Be,{variant:Ut.claimed?"default":"secondary",className:Ut.claimed?"bg-primary text-primary-foreground w-fit":"w-fit",children:Ut.claimed?"Active":"Pending"})})()})}),e.jsx(wt,{children:e.jsxs("div",{className:"flex flex-col",children:[Ut.roles.length>0?e.jsx("span",{className:"text-sm capitalize",children:Ut.roles[0]}):e.jsx("span",{className:"text-muted-foreground",children:"—"}),Ut.roles.includes("assistant")&&Ih[Ut.id]&&e.jsxs("span",{className:"text-xs text-muted-foreground",children:["→ ",Ih[Ut.id].agent_name||Ih[Ut.id].agent_email]})]})}),e.jsx(wt,{className:"text-muted-foreground",children:Ut.last_sign_in_at?new Date(Ut.last_sign_in_at).toLocaleDateString():"—"}),e.jsx(wt,{className:"text-muted-foreground",children:Ut.created_at?new Date(Ut.created_at).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"}):"—"}),e.jsx(wt,{children:e.jsxs("div",{className:"flex gap-1 justify-end",children:[e.jsx($,{size:"icon",variant:"ghost",className:"h-8 w-8 text-yellow-500 hover:text-yellow-600 hover:bg-yellow-50",onClick:()=>{$c(Ut),Hi(!0)},title:"Send celebration",children:e.jsx(Ax,{className:"h-4 w-4"})}),e.jsx($,{size:"icon",variant:"ghost",className:"h-8 w-8",onClick:()=>rr(Ut),title:"Edit member",children:e.jsx(gi,{className:"h-4 w-4"})}),e.jsx($,{size:"icon",variant:"ghost",className:"h-8 w-8",onClick:()=>po(Ut.id,Ut.email),disabled:nc===Ut.id,title:"Sync phone with GHL",children:nc===Ut.id?e.jsx(kt,{className:"h-4 w-4 animate-spin"}):e.jsx(Da,{className:"h-4 w-4"})}),e.jsx($,{size:"icon",variant:"ghost",className:"h-8 w-8",onClick:()=>Ba(Ut.id),title:"Resend welcome email",children:e.jsx(mn,{className:"h-4 w-4"})}),e.jsx($,{size:"icon",variant:"ghost",className:"h-8 w-8",onClick:()=>io(Ut.email,Ut.name),title:"Send password reset",children:e.jsx(KI,{className:"h-4 w-4"})}),e.jsx($,{size:"icon",variant:"ghost",className:"h-8 w-8 text-blue-600 hover:text-blue-700 hover:bg-blue-50",onClick:()=>nl(Ut.id),disabled:a||Ut.id===(t==null?void 0:t.id),title:Ut.id===(t==null?void 0:t.id)?"Cannot impersonate yourself":`Login as ${Ut.name}`,children:a?e.jsx(kt,{className:"h-4 w-4 animate-spin"}):e.jsx(ZI,{className:"h-4 w-4"})}),e.jsx($,{size:"icon",variant:"ghost",className:"h-8 w-8 text-destructive hover:text-destructive hover:bg-destructive/10",onClick:()=>ko(Ut.id,Ut.name),title:"Delete user",children:e.jsx(Wn,{className:"h-4 w-4"})})]})})]},Ut.id))})]})}),bn>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 ",D," of ",bn]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx($,{variant:"outline",size:"sm",onClick:()=>O(1),disabled:D===1,children:"First"}),e.jsx($,{variant:"outline",size:"icon",className:"h-8 w-8",onClick:()=>O(Ut=>Math.max(1,Ut-1)),disabled:D===1,children:e.jsx(Cd,{className:"h-4 w-4"})}),e.jsx("div",{className:"flex items-center gap-1",children:Array.from({length:Math.min(5,bn)},(Ut,Cn)=>{let ar;return bn<=5||D<=3?ar=Cn+1:D>=bn-2?ar=bn-4+Cn:ar=D-2+Cn,e.jsx($,{variant:D===ar?"default":"outline",size:"sm",className:"h-8 w-8 p-0",onClick:()=>O(ar),children:ar},ar)})}),e.jsx($,{variant:"outline",size:"icon",className:"h-8 w-8",onClick:()=>O(Ut=>Math.min(bn,Ut+1)),disabled:D===bn,children:e.jsx(Di,{className:"h-4 w-4"})}),e.jsx($,{variant:"outline",size:"sm",onClick:()=>O(bn),disabled:D===bn,children:"Last"})]})]})]}),e.jsx(zs,{open:xt,onOpenChange:rt,children:e.jsxs(Os,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsxs(Us,{children:[e.jsx(Bs,{children:"Edit Member"}),e.jsx(Ir,{children:"Update member details, roles, and app access"})]}),Ke&&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(ee,{htmlFor:"edit-name",children:"Name"}),e.jsx(pe,{id:"edit-name",value:Yt.name,onChange:Ut=>qt({...Yt,name:Ut.target.value}),maxLength:100})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"edit-email",children:"Email"}),e.jsx(pe,{id:"edit-email",type:"email",value:Yt.email,onChange:Ut=>qt({...Yt,email:Ut.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(ee,{htmlFor:"edit-phone",children:"Phone"}),e.jsx(pe,{id:"edit-phone",type:"tel",value:Yt.phone,onChange:Ut=>qt({...Yt,phone:Ut.target.value}),placeholder:"555-123-4567"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"edit-brokerage",children:"Brokerage"}),e.jsxs(ms,{value:Yt.brokerage_id||"none",onValueChange:Ut=>qt({...Yt,brokerage_id:Ut==="none"?"":Ut}),children:[e.jsx(us,{id:"edit-brokerage",children:e.jsx(fs,{placeholder:"Select brokerage"})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"none",children:"None"}),u.map(Ut=>e.jsx(Ge,{value:Ut.id,children:Ut.name},Ut.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:[Ke.roles.map(Ut=>e.jsxs(Be,{variant:"default",className:"gap-1",children:[e.jsx(Mf,{className:"h-3 w-3"}),Ut,Ut==="brokerage_manager"?e.jsx("span",{className:"text-xs text-muted-foreground ml-1",children:"(manage in Brokerages tab)"}):e.jsx("button",{onClick:()=>dm(Ke.id,Ut,"remove"),className:"ml-1 rounded-full hover:bg-destructive/20",title:"Remove role",children:e.jsx(gr,{className:"h-3 w-3"})})]},Ut)),Ke.roles.length===0&&e.jsx("span",{className:"text-sm text-muted-foreground",children:"No roles assigned"})]}),e.jsxs(ms,{onValueChange:Ut=>dm(Ke.id,Ut,"add"),children:[e.jsx(us,{className:"w-[200px]",children:e.jsx(fs,{placeholder:"Add role..."})}),e.jsxs(hs,{children:[!Ke.roles.includes("admin")&&e.jsx(Ge,{value:"admin",children:"Admin"}),!Ke.roles.includes("user")&&e.jsx(Ge,{value:"user",children:"User"})]})]}),!Ke.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"})]}),(yc.length>0||rg.length>0||Ke.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(Zn,{className:"h-4 w-4"}),"Assistant Relationships"]}),Yo?e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(kt,{className:"h-4 w-4 animate-spin"}),"Loading..."]}):e.jsxs("div",{className:"space-y-3",children:[yc.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:"}),yc.map(Ut=>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:Ut.assistant_name}),e.jsx(Be,{variant:"outline",className:"text-xs",children:"Assistant"})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:Ut.assistant_email}),e.jsx("div",{className:"flex flex-wrap gap-1 mt-1",children:Object.entries(Ut.permissions).filter(([,Cn])=>Cn).map(([Cn])=>e.jsx(Be,{variant:"secondary",className:"text-[10px] capitalize",children:Cn},Cn))})]},Ut.id))]}),rg.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:"}),rg.map(Ut=>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:Ut.agent_name}),e.jsx(Be,{variant:"outline",className:"text-xs",children:"Agent"})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:Ut.agent_email}),e.jsx("div",{className:"flex flex-wrap gap-1 mt-1",children:Object.entries(Ut.permissions).filter(([,Cn])=>Cn).map(([Cn])=>e.jsx(Be,{variant:"secondary",className:"text-[10px] capitalize",children:Cn},Cn))})]},Ut.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(Ut=>{const Cn=Zo(Ke.tags,Ut.required_tags),ar=`${Ke.id}-${Ut.id}`,ra=ts===ar,Zr=Ut.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:Ut.icon}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium text-sm",children:Ut.name}),Zr&&e.jsx("span",{className:"text-xs text-muted-foreground",children:"Available to all members"})]})]}),e.jsx("div",{className:"flex items-center gap-2",children:ra?e.jsx(kt,{className:"h-4 w-4 animate-spin text-muted-foreground"}):Zr?e.jsx(Be,{variant:"secondary",className:"text-xs",children:"Always On"}):e.jsx(Sn,{checked:Cn,onCheckedChange:()=>vo(Ke.id,Ut,Cn)})})]},Ut.id)})})]}),e.jsxs("div",{className:"space-y-3 pt-4 border-t",children:[e.jsx("h3",{className:"text-sm font-semibold",children:"Account Access"}),Ke.is_paused?e.jsxs("div",{className:"p-4 rounded-lg border bg-amber-50 dark:bg-amber-950/20 border-amber-200 dark:border-amber-800 space-y-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-sm font-medium",children:"This account is paused"}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:["They cannot sign in and see a paused message on the login page.",Ke.paused_reason?` Reason shown: “${Ke.paused_reason}”`:""]})]}),e.jsx($,{size:"sm",onClick:()=>Je(Ke.id,!1),disabled:Ce,children:"Reactivate account"})]}):e.jsxs("div",{className:"p-4 rounded-lg border bg-muted/30 space-y-3",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Pausing blocks sign-in and shows this member a message explaining their account is paused."}),e.jsx(pe,{placeholder:"Optional message shown to them (e.g. Payment is past due.)",value:ze,onChange:Ut=>$e(Ut.target.value)}),e.jsx($,{size:"sm",variant:"destructive",onClick:async()=>{await Je(Ke.id,!0,ze),$e("")},disabled:Ce,children:"Pause account"})]})]}),(Ke.is_trial||Ke.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(da,{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:[Ke.trial_expires_at&&e.jsx($wt,{expiresAt:Ke.trial_expires_at}),!Ke.trial_expires_at&&Ke.subscription_status==="trialing"&&Ke.subscription_end_date&&e.jsx($wt,{expiresAt:Ke.subscription_end_date})]}),(Ke.trial_expires_at||Ke.subscription_end_date)&&e.jsxs("span",{className:"text-sm text-muted-foreground",children:["Expires: ",new Date(Ke.trial_expires_at||Ke.subscription_end_date).toLocaleDateString()]})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs($,{size:"sm",variant:"outline",onClick:()=>Va(Ke.id,7),disabled:je,children:[e.jsx(jv,{className:"h-4 w-4 mr-1"}),"+7 Days"]}),e.jsxs($,{size:"sm",variant:"outline",onClick:()=>Va(Ke.id,14),disabled:je,children:[e.jsx(jv,{className:"h-4 w-4 mr-1"}),"+14 Days"]}),e.jsxs($,{size:"sm",variant:"outline",onClick:()=>Va(Ke.id,30),disabled:je,children:[e.jsx(jv,{className:"h-4 w-4 mr-1"}),"+30 Days"]}),e.jsxs($,{size:"sm",variant:"default",onClick:()=>Ht(Ke.id),disabled:ct,className:"bg-green-600 hover:bg-green-700",children:[e.jsx(y2,{className:"h-4 w-4 mr-1"}),"Convert to Full Account"]})]}),Ke.trial_started_at&&e.jsxs("div",{className:"mt-3 text-xs text-muted-foreground",children:["Trial started: ",new Date(Ke.trial_started_at).toLocaleDateString(),Ke.trial_claimed_at&&e.jsxs("span",{children:[" • Claimed: ",new Date(Ke.trial_claimed_at).toLocaleDateString()]})]})]})]}),!(Ke.is_trial||Ke.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(da,{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(Ut=>e.jsxs($,{size:"sm",variant:"outline",onClick:()=>tn(Ke.id,Ut),disabled:Ts,children:[e.jsx(jv,{className:"h-4 w-4 mr-1"}),Ut,"-day trial"]},Ut))})]})]}),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:[Ke.email_confirmed_at&&e.jsxs("div",{children:["Claimed: ",new Date(Ke.email_confirmed_at).toLocaleString()]}),Ke.last_sign_in_at&&e.jsxs("div",{children:["Last login: ",new Date(Ke.last_sign_in_at).toLocaleString()]}),e.jsxs("div",{children:["Created: ",new Date(Ke.created_at).toLocaleString()]})]})]})]}),e.jsxs(Ar,{children:[e.jsx($,{variant:"outline",onClick:Qr,children:"Cancel"}),e.jsx($,{onClick:na,children:"Save Changes"})]})]})}),e.jsxs(Xt,{value:"access",children:[c.length===0?e.jsx(Ne,{children:e.jsxs(Ie,{className:"py-12 text-center",children:[e.jsx("p",{className:"text-muted-foreground mb-4",children:"No apps configured yet"}),e.jsx($,{onClick:()=>s("/admin/apps"),children:"Configure Apps"})]})}):e.jsxs(Ne,{children:[e.jsxs(Ct,{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-4 space-y-0",children:[e.jsxs("div",{children:[e.jsx(At,{children:"Member Access Matrix"}),e.jsx(Gn,{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(Kr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(pe,{placeholder:"Search agents by name or email...",value:P,onChange:Ut=>{R(Ut.target.value),O(1)},className:"pl-9"})]})]}),e.jsxs(Ie,{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(Ut=>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:Ut.icon}),e.jsx("span",{className:"text-sm",children:Ut.name})]})},Ut.id))]})}),e.jsxs("tbody",{children:[tr.map(Ut=>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:Ut.name}),e.jsx("div",{className:"text-sm text-muted-foreground",children:Ut.email})]})}),c.map(Cn=>{const ar=Zo(Ut.tags,Cn.required_tags),ra=`${Ut.id}-${Cn.id}`,Zr=ts===ra;return e.jsx("td",{className:"p-4 text-center",children:e.jsx("div",{className:"flex items-center justify-center",children:Zr?e.jsx(kt,{className:"h-5 w-5 animate-spin text-muted-foreground"}):e.jsx(Sn,{checked:ar,onCheckedChange:()=>vo(Ut.id,Cn,ar),disabled:Cn.required_tags.length===0})})},Cn.id)})]},Ut.id)),tr.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"})})]})]})}),bn>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 ",Pn+1,"-",Math.min(or,fn)," of ",fn," • Page ",D," of ",bn]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx($,{variant:"outline",size:"icon",className:"h-8 w-8",onClick:()=>O(Ut=>Math.max(1,Ut-1)),disabled:D===1,children:e.jsx(Cd,{className:"h-4 w-4"})}),e.jsx($,{variant:"outline",size:"icon",className:"h-8 w-8",onClick:()=>O(Ut=>Math.min(bn,Ut+1)),disabled:D===bn,children:e.jsx(Di,{className:"h-4 w-4"})})]})]})]})]}),e.jsx("div",{className:"mt-6",children:e.jsx($,{variant:"outline",onClick:()=>s("/admin/apps"),children:"Manage Apps"})})]}),e.jsxs(Xt,{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(Kr,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(pe,{placeholder:"Search brokerages...",value:$d,onChange:Ut=>Nl(Ut.target.value),className:"pl-10"})]}),e.jsxs("span",{className:"text-sm text-muted-foreground whitespace-nowrap",children:[u.filter(Ut=>Ut.name.toLowerCase().includes($d.toLowerCase())).length," of ",u.length," brokerages"]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs($,{size:"sm",variant:"outline",onClick:()=>{const Ut=[];for(const xi of u){const Ia=m[xi.id]??[];for(const el of Ia){const zo=l.find(Lc=>Lc.id===el);if(zo){const Lc=(zo.name||"").trim().split(/\s+/),Mu=Lc[0]||"",ou=Lc.slice(1).join(" ")||"";Ut.push({firstName:Mu,lastName:ou,email:zo.email,brokerageName:xi.name})}}}if(Ut.length===0){i({title:"No managers found to export"});return}const ar=[["First Name","Last Name","Email","Brokerage Name"].join(","),...Ut.map(xi=>[xi.firstName,xi.lastName,xi.email,xi.brokerageName].map(Ia=>`"${(Ia||"").replace(/"/g,'""')}"`).join(","))].join(` `),ra=new Blob([ar],{type:"text/csv"}),Zr=URL.createObjectURL(ra),Aa=document.createElement("a");Aa.href=Zr,Aa.download=`brokerage-managers-${new Date().toISOString().slice(0,10)}.csv`,Aa.click(),URL.revokeObjectURL(Zr),i({title:`Exported ${Ut.length} managers`})},children:[e.jsx(di,{className:"mr-2 h-4 w-4"}),"Export Managers"]}),e.jsxs(zs,{open:Bt,onOpenChange:Ft,children:[e.jsx(jl,{asChild:!0,children:e.jsxs($,{size:"sm",children:[e.jsx(ji,{className:"mr-2 h-4 w-4"}),"Add Brokerage"]})}),e.jsxs(Os,{children:[e.jsxs(Us,{children:[e.jsx(Bs,{children:"Create New Brokerage"}),e.jsx(Ir,{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(ee,{htmlFor:"brokerage-name",children:"Brokerage Name"}),e.jsx(pe,{id:"brokerage-name",placeholder:"Enter brokerage name",value:rs,onChange:Ut=>St(Ut.target.value),maxLength:100})]})}),e.jsxs(Ar,{children:[e.jsx($,{variant:"outline",onClick:()=>Ft(!1),children:"Cancel"}),e.jsx($,{onClick:Zg,disabled:Xs,children:Xs?"Creating...":"Create Brokerage"})]})]})]})]})]}),e.jsx("div",{className:"border rounded-lg bg-card overflow-hidden",children:e.jsxs(mi,{children:[e.jsx(fi,{children:e.jsxs(En,{className:"bg-muted/30 hover:bg-muted/30",children:[e.jsx(Dt,{className:"font-semibold",children:"Brokerage Name"}),e.jsx(Dt,{className:"font-semibold",children:"Manager(s)"}),e.jsx(Dt,{className:"font-semibold",children:"Agents"}),e.jsx(Dt,{className:"w-[150px]"})]})}),e.jsx(pi,{children:(()=>{const Ut=u.filter(Cn=>Cn.name.toLowerCase().includes($d.toLowerCase()));return Ut.length===0?e.jsx(En,{children:e.jsx(wt,{colSpan:4,className:"text-center py-12 text-muted-foreground",children:$d?"No brokerages match your search":"No brokerages found"})}):Ut.map(Cn=>{const ar=l.filter(xi=>xi.brokerage_id===Cn.id),Zr=(m[Cn.id]??[]).map(xi=>l.find(Ia=>Ia.id===xi)).filter(Boolean),Aa=ar.length;return e.jsxs(En,{className:"hover:bg-muted/30",children:[e.jsx(wt,{children:e.jsx("button",{onClick:()=>Ol(Cn),className:"text-primary hover:underline font-medium",children:Cn.name})}),e.jsx(wt,{children:Zr.length>0?e.jsx("div",{className:"flex flex-wrap gap-1",children:Zr.map(xi=>e.jsx(Be,{variant:"secondary",className:"text-xs",children:xi.name},xi.id))}):e.jsx("span",{className:"text-muted-foreground text-sm",children:"No manager"})}),e.jsxs(wt,{children:[Aa," member",Aa!==1?"s":""]}),e.jsx(wt,{children:e.jsxs("div",{className:"flex gap-1 justify-end",children:[e.jsxs($,{size:"sm",variant:"outline",className:"h-8",onClick:()=>Yy(Cn),children:[e.jsx(Zn,{className:"h-4 w-4 mr-1"}),"Manage"]}),e.jsx($,{size:"icon",variant:"ghost",className:"h-8 w-8",onClick:()=>Ol(Cn),title:"Edit brokerage",children:e.jsx(gi,{className:"h-4 w-4"})}),e.jsx($,{size:"icon",variant:"ghost",className:"h-8 w-8 text-destructive hover:text-destructive hover:bg-destructive/10",onClick:()=>Wh(Cn),title:"Delete brokerage",children:e.jsx(Wn,{className:"h-4 w-4"})})]})})]},Cn.id)})})()})]})}),e.jsx(zs,{open:gs,onOpenChange:Ss,children:e.jsxs(Os,{className:"max-w-lg",children:[e.jsxs(Us,{children:[e.jsx(Bs,{children:"Edit Brokerage"}),e.jsx(Ir,{children:"Update brokerage details and manage managers"})]}),Is&&e.jsxs("div",{className:"space-y-6 py-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"edit-brokerage-name",children:"Brokerage Name"}),e.jsx(pe,{id:"edit-brokerage-name",value:cs,onChange:Ut=>js(Ut.target.value),maxLength:100})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx(ee,{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 Cn=(m[Is.id]??[]).map(ar=>l.find(ra=>ra.id===ar)).filter(Boolean);return Cn.length===0?e.jsx("span",{className:"text-sm text-muted-foreground",children:"No managers assigned"}):Cn.map(ar=>e.jsxs(Be,{variant:"default",className:"gap-1",children:[e.jsx(Mf,{className:"h-3 w-3"}),ar.name,e.jsx("button",{onClick:()=>dm(ar.id,"brokerage_manager","remove",Is.id),className:"ml-1 rounded-full hover:bg-destructive/20",title:"Remove manager from this brokerage",children:e.jsx(gr,{className:"h-3 w-3"})})]},ar.id))})()}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{className:"text-sm text-muted-foreground",children:"Assign manager from existing members:"}),e.jsxs(Yd,{open:Ho,onOpenChange:ti,children:[e.jsx(Zd,{asChild:!0,children:e.jsxs($,{variant:"outline",role:"combobox","aria-expanded":Ho,className:"w-full justify-between",children:["Search for a member...",e.jsx(Kr,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(Bd,{className:"w-full p-0",align:"start",children:e.jsxs(P2,{children:[e.jsx(I2,{placeholder:"Search by name or email..."}),e.jsxs(L2,{className:"max-h-[200px]",children:[e.jsx(R2,{children:"No members found."}),e.jsx(Uw,{children:(()=>{const Ut=new Set(m[Is.id]??[]);return l.filter(Cn=>!Ut.has(Cn.id)&&(n||Cn.brokerage_id===Is.id)).map(Cn=>e.jsxs(g1,{value:`${Cn.name} ${Cn.email}`,onSelect:()=>{Xd(Cn.id,Is.id),ti(!1)},children:[Cn.name," (",Cn.email,")"]},Cn.id))})()})]})]})})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Members in this Brokerage"}),e.jsx("div",{className:"max-h-32 overflow-y-auto border rounded p-2",children:l.filter(Ut=>Ut.brokerage_id===Is.id).length===0?e.jsx("span",{className:"text-sm text-muted-foreground",children:"No members"}):l.filter(Ut=>Ut.brokerage_id===Is.id).map(Ut=>e.jsxs("div",{className:"text-sm py-1 flex items-center justify-between",children:[e.jsx("span",{children:Ut.name}),Ut.roles.includes("brokerage_manager")&&e.jsx(Be,{variant:"outline",className:"text-xs",children:"Manager"})]},Ut.id))})]})]}),e.jsxs(Ar,{children:[e.jsx($,{variant:"outline",onClick:zl,children:"Cancel"}),e.jsx($,{onClick:vy,disabled:kn,children:kn?"Saving...":"Save Changes"})]})]})}),e.jsx(zs,{open:On,onOpenChange:ds,children:e.jsxs(Os,{children:[e.jsxs(Us,{children:[e.jsx(Bs,{className:"text-destructive",children:"Delete Brokerage"}),e.jsxs(Ir,{children:['Are you sure you want to delete "',gn==null?void 0:gn.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 "',gn==null?void 0:gn.name,'"']}),e.jsxs("li",{children:["All ",l.filter(Ut=>Ut.brokerage_id===(gn==null?void 0:gn.id)).length," member(s) assigned to this brokerage"]}),e.jsx("li",{children:"All their data, roles, and access"})]})]})}),e.jsxs(Ar,{children:[e.jsx($,{variant:"outline",onClick:()=>ds(!1),children:"Cancel"}),e.jsx($,{variant:"destructive",onClick:df,disabled:hr,children:hr?"Deleting...":"Yes, Delete Brokerage"})]})]})}),e.jsx(zs,{open:qn,onOpenChange:hn,children:e.jsxs(Os,{className:"max-w-4xl max-h-[85vh] overflow-hidden flex flex-col",children:[e.jsxs(Us,{children:[e.jsxs(Bs,{className:"flex items-center gap-2",children:[e.jsx(ji,{className:"h-5 w-5"}),"Manage ",Fn==null?void 0:Fn.name]}),e.jsx(Ir,{children:"Add, remove, or manage users in this brokerage"})]}),Fn&&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(Kr,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(pe,{placeholder:"Search members...",value:xs,onChange:Ut=>Lr(Ut.target.value),className:"pl-10 h-9"})]}),e.jsxs(zs,{open:Or,onOpenChange:ca,children:[e.jsx(jl,{asChild:!0,children:e.jsxs($,{size:"sm",children:[e.jsx(sc,{className:"h-4 w-4 mr-1"}),"Add New Agent"]})}),e.jsxs(Os,{children:[e.jsxs(Us,{children:[e.jsx(Bs,{children:"Add New Agent"}),e.jsxs(Ir,{children:["Create a new agent for ",Fn.name]})]}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"agent-name",children:"Name"}),e.jsx(pe,{id:"agent-name",placeholder:"John Doe",value:Jn.name,onChange:Ut=>Sr({...Jn,name:Ut.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"agent-email",children:"Email"}),e.jsx(pe,{id:"agent-email",type:"email",placeholder:"john@example.com",value:Jn.email,onChange:Ut=>Sr({...Jn,email:Ut.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"agent-password",children:"Password"}),e.jsx(pe,{id:"agent-password",type:"password",placeholder:"Min 6 characters",value:Jn.password,onChange:Ut=>Sr({...Jn,password:Ut.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"agent-phone",children:"Phone (optional)"}),e.jsx(pe,{id:"agent-phone",type:"tel",placeholder:"555-123-4567",value:Jn.phone,onChange:Ut=>Sr({...Jn,phone:Ut.target.value})})]}),Pa&&$i.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ee,{htmlFor:"agent-package",children:[Pa.name," Package"]}),e.jsxs(ms,{value:xa,onValueChange:Ya,children:[e.jsx(us,{id:"agent-package",children:e.jsx(fs,{placeholder:"Select a package"})}),e.jsxs(hs,{children:[$i.map(Ut=>e.jsx(Ge,{value:Ut.id,children:Ut.name},Ut.id)),e.jsx(Ge,{value:"none",children:"No package (full access)"})]})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:xa==="none"?"Agent gets unrestricted access; welcome email has no package block.":((iu=$i.find(Ut=>Ut.id===xa))==null?void 0:iu.description)||"Entitlements and the welcome email reflect this package."})]})]}),e.jsxs(Ar,{children:[e.jsx($,{variant:"outline",onClick:()=>ca(!1),children:"Cancel"}),e.jsx($,{onClick:We,disabled:Un,children:Un?"Creating...":"Create Agent"})]})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ee,{className:"text-sm text-muted-foreground whitespace-nowrap",children:"Add existing user:"}),e.jsxs(Yd,{open:Xr,onOpenChange:Eo,children:[e.jsx(Zd,{asChild:!0,children:e.jsxs($,{variant:"outline",role:"combobox","aria-expanded":Xr,className:"w-[300px] justify-between",children:["Select a user to add...",e.jsx(Kr,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(Bd,{className:"w-[300px] p-0",align:"start",children:e.jsxs(P2,{children:[e.jsx(I2,{placeholder:"Search users...",value:Ph,onValueChange:ih}),e.jsxs(L2,{children:[e.jsx(R2,{children:"No users found."}),e.jsx(Uw,{children:Rt(Fn.id).filter(Ut=>Ph===""||Ut.name.toLowerCase().includes(Ph.toLowerCase())||Ut.email.toLowerCase().includes(Ph.toLowerCase())).map(Ut=>e.jsxs(g1,{value:`${Ut.name} ${Ut.email}`,onSelect:()=>{gt(Ut.id,Fn.id),Eo(!1),ih("")},children:[Ut.name," (",Ut.email,")"]},Ut.id))})]})]})})]})]}),e.jsx("div",{className:"flex-1 overflow-auto border rounded-lg",children:e.jsxs(mi,{children:[e.jsx(fi,{children:e.jsxs(En,{className:"bg-muted/30 hover:bg-muted/30",children:[e.jsx(Dt,{className:"font-semibold",children:"Name"}),e.jsx(Dt,{className:"font-semibold",children:"Email"}),e.jsx(Dt,{className:"font-semibold",children:"Status"}),e.jsx(Dt,{className:"font-semibold",children:"Role"}),e.jsx(Dt,{className:"w-[120px]"})]})}),e.jsx(pi,{children:jt(Fn.id).length===0?e.jsx(En,{children:e.jsx(wt,{colSpan:5,className:"text-center py-8 text-muted-foreground",children:xs?"No matching members found":"No members in this brokerage"})}):jt(Fn.id).map(Ut=>e.jsxs(En,{className:"hover:bg-muted/30",children:[e.jsx(wt,{className:"font-medium",children:Ut.name}),e.jsx(wt,{className:"text-muted-foreground",children:Ut.email}),e.jsx(wt,{children:Ut.claimed?e.jsx(Be,{variant:"default",className:"bg-green-500/10 text-green-600 hover:bg-green-500/20",children:"Active"}):e.jsx(Be,{variant:"secondary",children:"Pending"})}),e.jsx(wt,{children:Ut.roles.includes("brokerage_manager")?e.jsxs(Be,{variant:"outline",className:"gap-1",children:[e.jsx(Mf,{className:"h-3 w-3"}),"Manager"]}):e.jsx("span",{className:"text-muted-foreground text-sm",children:"Agent"})}),e.jsx(wt,{children:e.jsxs("div",{className:"flex gap-1 justify-end",children:[!Ut.claimed&&e.jsx($,{size:"icon",variant:"ghost",className:"h-8 w-8",onClick:()=>Ba(Ut.id),title:"Resend welcome email",children:e.jsx(mn,{className:"h-4 w-4"})}),e.jsx($,{size:"icon",variant:"ghost",className:"h-8 w-8",onClick:()=>xh(Ut.id),title:"Remove from brokerage",children:e.jsx(gr,{className:"h-4 w-4"})}),e.jsx($,{size:"icon",variant:"ghost",className:"h-8 w-8 text-blue-600 hover:text-blue-700 hover:bg-blue-50",onClick:()=>nl(Ut.id),disabled:a||Ut.id===(t==null?void 0:t.id),title:Ut.id===(t==null?void 0:t.id)?"Cannot impersonate yourself":`Login as ${Ut.name}`,children:a?e.jsx(kt,{className:"h-4 w-4 animate-spin"}):e.jsx(ZI,{className:"h-4 w-4"})}),e.jsx($,{size:"icon",variant:"ghost",className:"h-8 w-8 text-destructive hover:text-destructive hover:bg-destructive/10",onClick:()=>ko(Ut.id,Ut.name),title:"Delete user",children:e.jsx(Wn,{className:"h-4 w-4"})})]})})]},Ut.id))})]})}),e.jsxs("div",{className:"text-sm text-muted-foreground",children:[ut(Fn.id).length," total member",ut(Fn.id).length!==1?"s":""," •",ut(Fn.id).filter(Ut=>Ut.roles.includes("brokerage_manager")).length," manager",ut(Fn.id).filter(Ut=>Ut.roles.includes("brokerage_manager")).length!==1?"s":""]})]}),e.jsx(Ar,{children:e.jsx($,{variant:"outline",onClick:oh,children:"Close"})})]})})]}),e.jsx(Xt,{value:"teams",children:e.jsx(smn,{})}),e.jsx(Xt,{value:"trials",children:e.jsx($hn,{})}),e.jsx(Xt,{value:"celebrations",children:e.jsx(Bhn,{})}),e.jsx(Xt,{value:"deletions",children:e.jsx(qhn,{})})]})]}),e.jsx(BWt,{open:ho,onOpenChange:Pc,brokerages:u,onSuccess:_s}),Bc&&e.jsx($Wt,{open:zr,onOpenChange:Ut=>{Hi(Ut),Ut||$c(null)},userId:Bc.id,userName:Bc.name}),e.jsx(nmn,{open:ke,onOpenChange:Ve,recipients:l.filter(Ut=>ao.has(Ut.id)).map(Ut=>({id:Ut.id,name:Ut.name,email:Ut.email}))})]})};function amn(){const{toast:s}=Bi(),t=Vt(),[n,r]=j.useState(""),[a,i]=j.useState(new Set),[l,o]=j.useState({}),[c,d]=j.useState({}),[u,h]=j.useState(""),[m,f]=j.useState(!1),{data:g=[],isLoading:x}=tt({queryKey:["unassigned-members"],queryFn:async()=>{const{data:P,error:R}=await q.from("profiles").select("id, name, email, phone, created_at, subscription_status").is("brokerage_id",null).or("subscription_status.is.null,subscription_status.eq.none").order("created_at",{ascending:!1});if(R)throw R;return P||[]}}),{data:y=[]}=tt({queryKey:["brokerages-all"],queryFn:async()=>{const{data:P,error:R}=await q.from("brokerages").select("id, name").order("name");if(R)throw R;return P||[]}}),v=j.useMemo(()=>{const P=n.toLowerCase().trim();return P?g.filter(R=>(R.name||"").toLowerCase().includes(P)||(R.email||"").toLowerCase().includes(P)||(R.phone||"").toLowerCase().includes(P)):g},[g,n]),b=j.useMemo(()=>{var R;const P=new Map;for(const D of g){const O=(R=(D.email||"").split("@")[1])==null?void 0:R.toLowerCase();O&&(["gmail.com","yahoo.com","hotmail.com","outlook.com","icloud.com","aol.com","me.com","comcast.net"].includes(O)||P.set(O,(P.get(O)||0)+1))}return Array.from(P.entries()).sort((D,O)=>O[1]-D[1]).slice(0,10)},[g]),w=P=>{i(R=>{const D=new Set(R);return D.has(P)?D.delete(P):D.add(P),D})},S=()=>{a.size===v.length?i(new Set):i(new Set(v.map(P=>P.id)))},C=async(P,R)=>{if(R){d(D=>({...D,[P]:!0}));try{const{data:D,error:O}=await q.functions.invoke("assign-brokerage",{body:{userId:P,brokerageId:R}});if(O)throw O;if(D!=null&&D.error)throw new Error(D.error);s({title:"Assigned",description:"Member added to brokerage."}),t.invalidateQueries({queryKey:["unassigned-members"]}),i(U=>{const W=new Set(U);return W.delete(P),W})}catch(D){s({title:"Failed",description:D.message,variant:"destructive"})}finally{d(D=>({...D,[P]:!1}))}}},E=async()=>{if(!u||a.size===0)return;f(!0);let P=0,R=0;for(const D of a)try{const{data:O,error:U}=await q.functions.invoke("assign-brokerage",{body:{userId:D,brokerageId:u}});if(U||O!=null&&O.error)throw new Error((U==null?void 0:U.message)||O.error);P++}catch{R++}f(!1),s({title:`Assigned ${P}${R?`, ${R} failed`:""}`,description:"Bulk assignment complete.",variant:R?"destructive":"default"}),i(new Set),h(""),t.invalidateQueries({queryKey:["unassigned-members"]})},I=(P,R)=>{const D={...l};for(const O of g)(O.email||"").toLowerCase().endsWith(`@${P}`)&&(D[O.id]=R);o(D),s({title:"Suggestions applied",description:`Pre-filled brokerage for @${P}`})};return e.jsx(Vs,{children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(Fm,{title:"Unassigned Members",description:"Members with no brokerage and no active subscription — likely missed brokerage invites."}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:[e.jsxs(Ne,{children:[e.jsx(Ct,{className:"pb-2",children:e.jsxs(At,{className:"text-sm font-medium text-muted-foreground flex items-center gap-2",children:[e.jsx(Zn,{className:"h-4 w-4"})," Orphan members"]})}),e.jsx(Ie,{children:e.jsx("div",{className:"text-3xl font-bold",children:g.length})})]}),e.jsxs(Ne,{children:[e.jsx(Ct,{className:"pb-2",children:e.jsxs(At,{className:"text-sm font-medium text-muted-foreground flex items-center gap-2",children:[e.jsx(ji,{className:"h-4 w-4"})," Selected"]})}),e.jsx(Ie,{children:e.jsx("div",{className:"text-3xl font-bold",children:a.size})})]}),e.jsxs(Ne,{children:[e.jsx(Ct,{className:"pb-2",children:e.jsxs(At,{className:"text-sm font-medium text-muted-foreground flex items-center gap-2",children:[e.jsx(Nn,{className:"h-4 w-4"})," Top email domains"]})}),e.jsx(Ie,{children:e.jsx("div",{className:"text-3xl font-bold",children:b.length})})]})]}),b.length>0&&e.jsxs(Ne,{children:[e.jsx(Ct,{children:e.jsx(At,{className:"text-base",children:"Domain suggestions"})}),e.jsx(Ie,{children:e.jsx("div",{className:"flex flex-wrap gap-2",children:b.map(([P,R])=>{const D=y.find(O=>O.name.toLowerCase().replace(/[^a-z0-9]/g,"").includes(P.split(".")[0].toLowerCase()));return e.jsxs("div",{className:"flex items-center gap-2 rounded-md border bg-muted/30 px-3 py-2",children:[e.jsxs("span",{className:"font-mono text-sm",children:["@",P]}),e.jsx(Be,{variant:"secondary",children:R}),e.jsxs(ms,{onValueChange:O=>I(P,O),defaultValue:D==null?void 0:D.id,children:[e.jsx(us,{className:"h-8 w-[220px]",children:e.jsx(fs,{placeholder:"Apply brokerage…"})}),e.jsx(hs,{children:y.map(O=>e.jsx(Ge,{value:O.id,children:O.name},O.id))})]})]},P)})})})]}),e.jsxs(Ne,{children:[e.jsxs(Ct,{className:"flex flex-col md:flex-row md:items-center md:justify-between gap-4",children:[e.jsxs("div",{className:"relative w-full md:w-96",children:[e.jsx(Kr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(pe,{value:n,onChange:P=>r(P.target.value),placeholder:"Search name, email, phone…",className:"pl-9"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(ms,{value:u,onValueChange:h,children:[e.jsx(us,{className:"w-[240px]",children:e.jsx(fs,{placeholder:"Bulk assign to brokerage…"})}),e.jsx(hs,{children:y.map(P=>e.jsx(Ge,{value:P.id,children:P.name},P.id))})]}),e.jsxs($,{onClick:E,disabled:!u||a.size===0||m,children:[m&&e.jsx(kt,{className:"h-4 w-4 mr-2 animate-spin"}),"Assign ",a.size||""]})]})]}),e.jsx(Ie,{children:x?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(kt,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):v.length===0?e.jsx("div",{className:"py-12 text-center text-muted-foreground",children:"🎉 No unassigned members."}):e.jsx("div",{className:"overflow-x-auto",children:e.jsxs(mi,{children:[e.jsx(fi,{children:e.jsxs(En,{children:[e.jsx(Dt,{className:"w-10",children:e.jsx(ai,{checked:a.size===v.length&&v.length>0,onCheckedChange:S})}),e.jsx(Dt,{children:"Name"}),e.jsx(Dt,{children:"Email"}),e.jsx(Dt,{children:"Signed up"}),e.jsx(Dt,{children:"Status"}),e.jsx(Dt,{children:"Assign to brokerage"}),e.jsx(Dt,{className:"w-24"})]})}),e.jsx(pi,{children:v.map(P=>{const R=l[P.id]||"";return e.jsxs(En,{children:[e.jsx(wt,{children:e.jsx(ai,{checked:a.has(P.id),onCheckedChange:()=>w(P.id)})}),e.jsx(wt,{className:"font-medium",children:P.name||"—"}),e.jsx(wt,{className:"text-sm text-muted-foreground",children:P.email}),e.jsx(wt,{className:"text-sm text-muted-foreground",children:mu(new Date(P.created_at),{addSuffix:!0})}),e.jsx(wt,{children:e.jsx(Be,{variant:"outline",children:P.subscription_status||"none"})}),e.jsx(wt,{children:e.jsxs(ms,{value:R,onValueChange:D=>o(O=>({...O,[P.id]:D})),children:[e.jsx(us,{className:"h-9 w-[240px]",children:e.jsx(fs,{placeholder:"Pick brokerage…"})}),e.jsx(hs,{children:y.map(D=>e.jsx(Ge,{value:D.id,children:D.name},D.id))})]})}),e.jsx(wt,{children:e.jsx($,{size:"sm",disabled:!R||c[P.id],onClick:()=>C(P.id,R),children:c[P.id]?e.jsx(kt,{className:"h-4 w-4 animate-spin"}):"Assign"})})]},P.id)})})]})})})]})]})})}const imn=()=>{const[s,t]=j.useState([]),[n,r]=j.useState(!0),[a,i]=j.useState(!1),[l,o]=j.useState(""),[c,d]=j.useState(""),[u,h]=j.useState(""),[m,f]=j.useState("");j.useEffect(()=>{g()},[]);const g=async()=>{const{data:C,error:E}=await q.from("invite_codes").select("*").order("created_at",{ascending:!1});E?(re.error("Failed to load invite codes"),console.error(E)):t(C||[]),r(!1)},x=async C=>{if(C.preventDefault(),!l.trim()){re.error("Please enter a code");return}i(!0);const{error:E}=await q.from("invite_codes").insert({code:l.trim().toUpperCase(),description:c.trim()||null,max_uses:u?parseInt(u):null,trial_days:m?parseInt(m):null});E?E.code==="23505"?re.error("This code already exists"):(re.error("Failed to create invite code"),console.error(E)):(re.success("Invite code created"),o(""),d(""),h(""),f(""),g()),i(!1)},y=async(C,E)=>{const{error:I}=await q.from("invite_codes").update({is_active:!E}).eq("id",C);I?re.error("Failed to update code"):t(s.map(P=>P.id===C?{...P,is_active:!E}:P))},v=async C=>{const{error:E}=await q.from("invite_codes").delete().eq("id",C);E?re.error("Failed to delete code"):(re.success("Code deleted"),t(s.filter(I=>I.id!==C)))},b="https://dashboard.relevelup.com",w=C=>{const E=`${b}/join?code=${C}`;navigator.clipboard.writeText(E),re.success("Link copied to clipboard")},S=`${b}/join`;return e.jsx(Vs,{title:"Invite Codes",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(Fm,{title:"Invite Codes",description:"Manage signup invite codes"}),e.jsxs(Ne,{children:[e.jsxs(Ct,{children:[e.jsx(At,{children:"Create New Code"}),e.jsxs(Gn,{children:["Share link: ",e.jsx("code",{className:"bg-muted px-2 py-1 rounded text-sm",children:S})]})]}),e.jsx(Ie,{children:e.jsxs("form",{onSubmit:x,className:"flex flex-wrap gap-4 items-end",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"code",children:"Code"}),e.jsx(pe,{id:"code",placeholder:"WELCOME2024",value:l,onChange:C=>o(C.target.value),className:"w-40"})]}),e.jsxs("div",{className:"space-y-2 flex-1 min-w-[200px]",children:[e.jsx(ee,{htmlFor:"description",children:"Description (optional)"}),e.jsx(pe,{id:"description",placeholder:"For marketing campaign",value:c,onChange:C=>d(C.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"maxUses",children:"Max Uses"}),e.jsx(pe,{id:"maxUses",type:"number",placeholder:"Unlimited",value:u,onChange:C=>h(C.target.value),className:"w-28"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"trialDays",children:"Trial Days"}),e.jsx(pe,{id:"trialDays",type:"number",placeholder:"None",value:m,onChange:C=>f(C.target.value),className:"w-28"})]}),e.jsxs($,{type:"submit",disabled:a,children:[a?e.jsx(kt,{className:"h-4 w-4 animate-spin"}):e.jsx(dn,{className:"h-4 w-4 mr-2"}),"Create"]})]})})]}),e.jsxs(Ne,{children:[e.jsx(Ct,{children:e.jsx(At,{children:"Active Codes"})}),e.jsx(Ie,{children:n?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx(kt,{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(mi,{children:[e.jsx(fi,{children:e.jsxs(En,{children:[e.jsx(Dt,{children:"Code"}),e.jsx(Dt,{children:"Description"}),e.jsx(Dt,{children:"Uses"}),e.jsx(Dt,{children:"Trial"}),e.jsx(Dt,{children:"Created"}),e.jsx(Dt,{children:"Active"}),e.jsx(Dt,{className:"w-24",children:"Actions"})]})}),e.jsx(pi,{children:s.map(C=>e.jsxs(En,{children:[e.jsx(wt,{className:"font-mono font-medium",children:C.code}),e.jsx(wt,{className:"text-muted-foreground",children:C.description||"—"}),e.jsxs(wt,{children:[C.uses_count,C.max_uses&&` / ${C.max_uses}`]}),e.jsx(wt,{children:C.trial_days?e.jsxs("span",{className:"text-amber-600 dark:text-amber-400 font-medium",children:[C.trial_days," days"]}):e.jsx("span",{className:"text-muted-foreground",children:"—"})}),e.jsx(wt,{className:"text-muted-foreground",children:en(new Date(C.created_at),"MMM d, yyyy")}),e.jsx(wt,{children:e.jsx(Sn,{checked:C.is_active,onCheckedChange:()=>y(C.id,C.is_active)})}),e.jsx(wt,{children:e.jsxs("div",{className:"flex gap-1",children:[e.jsx($,{variant:"ghost",size:"icon",onClick:()=>w(C.code),title:"Copy invite link",children:e.jsx(Ha,{className:"h-4 w-4"})}),e.jsx($,{variant:"ghost",size:"icon",onClick:()=>v(C.id),className:"text-destructive hover:text-destructive",title:"Delete code",children:e.jsx(Wn,{className:"h-4 w-4"})})]})})]},C.id))})]})})]})]})})},jE=q;function qSr(s){if(!s)return null;const t=s.trim();if(!t)return null;if(/^[\w-]{8,20}$/.test(t))return t;const n=[/youtu\.be\/([\w-]{8,20})/,/[?&]v=([\w-]{8,20})/,/youtube\.com\/live\/([\w-]{8,20})/,/youtube\.com\/embed\/([\w-]{8,20})/];for(const r of n){const a=t.match(r);if(a)return a[1]}return null}function omn(s){return s.toLowerCase().replace(/[^a-z0-9\s-]/g,"").trim().replace(/\s+/g,"-").slice(0,70)}const lmn="https://dashboard.relevelup.com";function VSr(s,t){const r=`${typeof window<"u"&&window.location.hostname==="localhost"?window.location.origin:lmn}/live/${s}`;return t?`${r}?i=${t}`:r}function HSr(){const s=Vt(),t=tt({queryKey:["live-events"],queryFn:async()=>{const{data:i,error:l}=await jE.from("live_events").select("*").order("starts_at",{ascending:!1});if(l)throw l;return i||[]}}),n=ft({mutationFn:async i=>{var d;const{data:l}=await q.auth.getUser(),{data:o,error:c}=await jE.from("live_events").insert({...i,created_by:(d=l.user)==null?void 0:d.id}).select().single();if(c)throw c;return o},onSuccess:()=>{s.invalidateQueries({queryKey:["live-events"]}),re.success("Live event created")},onError:i=>re.error((i==null?void 0:i.message)||"Could not create event")}),r=ft({mutationFn:async({id:i,...l})=>{const{error:o}=await jE.from("live_events").update(l).eq("id",i);if(o)throw o},onSuccess:(i,l)=>{s.invalidateQueries({queryKey:["live-events"]}),s.invalidateQueries({queryKey:["live-event",l.id]}),re.success("Saved")},onError:i=>re.error((i==null?void 0:i.message)||"Could not save")}),a=ft({mutationFn:async i=>{const{error:l}=await jE.from("live_events").delete().eq("id",i);if(l)throw l},onSuccess:()=>{s.invalidateQueries({queryKey:["live-events"]}),re.success("Event deleted")},onError:i=>re.error((i==null?void 0:i.message)||"Could not delete")});return{list:t,create:n,update:r,remove:a}}function GSr(s){return tt({queryKey:["live-event",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await jE.from("live_events").select("*").eq("id",s).maybeSingle();if(n)throw n;return t}})}function WSr(s){return tt({queryKey:["live-registrations",s],enabled:!!s,refetchInterval:2e4,queryFn:async()=>{const{data:t,error:n}=await jE.from("live_registrations").select("*").eq("event_id",s).order("created_at",{ascending:!1});if(n)throw n;return t||[]}})}function KSr(s){const t=Vt(),n=tt({queryKey:["live-invites",s],enabled:!!s,queryFn:async()=>{const{data:i,error:l}=await jE.from("live_invites").select("*").eq("event_id",s).order("created_at",{ascending:!1});if(l)throw l;return i||[]}}),r=ft({mutationFn:async i=>{const{data:l}=await q.auth.getUser(),o=i.map(u=>{var h;return{event_id:s,code:crypto.randomUUID().replace(/-/g,"").slice(0,12),name:u.name||null,email:u.email||null,phone:u.phone||null,brokerage:u.brokerage||null,created_by:(h=l.user)==null?void 0:h.id}}),{data:c,error:d}=await jE.from("live_invites").insert(o).select();if(d)throw d;return c||[]},onSuccess:i=>{t.invalidateQueries({queryKey:["live-invites",s]}),re.success(`${i.length} invite link${i.length===1?"":"s"} created`)},onError:i=>re.error((i==null?void 0:i.message)||"Could not create invites")}),a=ft({mutationFn:async i=>{const{error:l}=await jE.from("live_invites").delete().eq("id",i);if(l)throw l},onSuccess:()=>t.invalidateQueries({queryKey:["live-invites",s]})});return{list:n,createMany:r,remove:a}}const kie=async s=>{try{const{data:t,error:n}=await q.from("push_notification_settings").select("is_enabled").eq("setting_key",s).maybeSingle();return n?(console.error("Error checking notification setting:",n),!0):(t==null?void 0:t.is_enabled)??!0}catch(t){return console.error("Error checking notification setting:",t),!0}},NK=async s=>{try{const{data:t,error:n}=await q.functions.invoke("send-push-notification",{body:s});return n?(console.error("Error sending notification:",n),{success:!1,error:n}):(console.log("Notification sent:",t),{success:!0,data:t})}catch(t){return console.error("Error sending notification:",t),{success:!1,error:t}}},cmn=async(s,t)=>await kie("new_templates")?NK({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}),dmn=async(s,t)=>NK({title:"New Academy Video",body:`New video added: ${s}`,url:`/academy/${t}`}),umn=async(s,t)=>await kie("new_events")?NK({title:"New Event",body:`New event: ${s}`,url:`/events/${t}`}):(console.log("New event notifications are disabled"),{success:!1,skipped:!0}),hmn=async(s,t)=>await kie("new_toolbox")?NK({title:"New Resource Kit",body:`New resource kit available: ${s}`,url:`/toolbox/${t}`}):(console.log("New toolbox notifications are disabled"),{success:!1,skipped:!0}),KWe=async(s,t)=>await kie("new_social_swag")?NK({title:"New Social Swag",body:`New social swag available: ${s}`,url:"/social-swag-2"}):(console.log("New social swag notifications are disabled"),{success:!1,skipped:!0}),mmn=async(s,t)=>await kie("new_newsletters")?NK({title:"New Newsletter",body:`New newsletter available: ${s}`,url:`/newsletters/${t}`}):(console.log("New newsletter notifications are disabled"),{success:!1,skipped:!0}),i9e=400;function fmn(s){const t=new Date(s);return new Intl.DateTimeFormat("en-US",{weekday:"long",month:"short",day:"numeric",hour:"numeric",minute:"2-digit",timeZone:"America/New_York"}).format(t)+" ET"}async function pmn(){const s=[];let t=0;const n=1e3;for(;;){const{data:r,error:a}=await q.from("profiles").select("id, name, email, event_invite_opt_out").not("email","is",null).neq("email","").eq("event_invite_opt_out",!1).order("created_at",{ascending:!1}).range(t,t+n-1);if(a)throw a;if(!r||r.length===0)break;for(const i of r)i.email&&/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(i.email)&&s.push({id:i.id,name:i.name||"",email:i.email});if(r.length{if(!s||!n)return;let Y=!1;return(async()=>{h(!0);try{const[X,ae,ie]=await Promise.all([pmn(),Vwt("event_registrations",n.id),Vwt("event_attendees",n.id)]);if(Y)return;f(X),x(ae),v(ie)}catch(X){Y||r({title:"Could not load audience",description:X instanceof Error?X.message:"Unknown error",variant:"destructive"})}finally{Y||h(!1)}})(),()=>{Y=!0}},[s,n,r]),j.useEffect(()=>{s||(C(null),d(""),o(""),i("not_registered"))},[s]);const D=j.useMemo(()=>a==="all"?m:a==="not_registered"?m.filter(Y=>!g.has(Y.id)):m.filter(Y=>g.has(Y.id)&&!y.has(Y.id)),[a,m,g,y]),O={all:m.length,not_registered:m.filter(Y=>!g.has(Y.id)).length,registered_never_attended:m.filter(Y=>g.has(Y.id)&&!y.has(Y.id)).length},U=async(Y,X=!1)=>{const{data:{session:ae}}=await q.auth.getSession(),ie=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/admin-send-event-invite",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${ae==null?void 0:ae.access_token}`},body:JSON.stringify({event_id:n.id,recipients:Y.map(te=>({email:te.email,name:te.name,user_id:te.id})),custom_subject:l.trim()||void 0,custom_intro:c.trim()||void 0,force_resend:X||void 0})}),ne=await ie.json().catch(()=>({}));if(!ie.ok)throw new Error((ne==null?void 0:ne.error)||`HTTP ${ie.status}`);return{sent:(ne==null?void 0:ne.sent)??0,failed:(ne==null?void 0:ne.failed)??0,alreadyInvited:(ne==null?void 0:ne.already_invited)??0}},W=async()=>{var Y;if(n){R(!0);try{const{data:{session:X}}=await q.auth.getSession(),ae=X==null?void 0:X.user;if(!(ae!=null&&ae.email))throw new Error("No signed-in email found");const ie=await U([{id:ae.id,name:((Y=ae.user_metadata)==null?void 0:Y.name)||"",email:ae.email}],!0);r({title:"Test sent",description:`Sent to ${ae.email} · Sent: ${ie.sent} · Failed: ${ie.failed}`})}catch(X){r({title:"Test failed",description:X instanceof Error?X.message:"Unknown error",variant:"destructive"})}finally{R(!1)}}},V=async()=>{if(!(!n||D.length===0)){I(!1),w(!0),C({done:0,total:D.length,sent:0,failed:0});try{let Y=0,X=0,ae=0;for(let ie=0;ie!b&&t(Y),children:e.jsxs(Os,{className:"max-w-2xl max-h-[92vh] overflow-y-auto",children:[e.jsxs(Us,{children:[e.jsxs(Bs,{className:"flex items-center gap-2",children:[e.jsx(Nn,{className:"h-5 w-5 text-primary"}),"Invite Members to Event"]}),e.jsx(Ir,{children:n?e.jsxs("span",{className:"flex items-center gap-2 text-sm",children:[e.jsx(Au,{className:"h-4 w-4"}),e.jsx("span",{className:"font-medium text-foreground",children:n.title}),e.jsx("span",{children:"·"}),e.jsx("span",{children:fmn(n.event_date)})]}):"Send a beautiful branded invite to members."})]}),e.jsxs("div",{className:"space-y-5",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ee,{className:"flex items-center gap-2",children:[e.jsx(Zn,{className:"h-4 w-4"})," Audience"]}),u?e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground py-2",children:[e.jsx(kt,{className:"h-4 w-4 animate-spin"})," Loading members..."]}):e.jsxs(kw,{value:a,onValueChange:Y=>i(Y),className:"space-y-2",children:[e.jsxs("label",{htmlFor:"aud-not-reg",className:"flex items-start gap-3 rounded-lg border p-3 cursor-pointer hover:bg-muted/40 transition",children:[e.jsx(Ym,{value:"not_registered",id:"aud-not-reg",className:"mt-1"}),e.jsxs("div",{className:"flex-1",children:[e.jsx("div",{className:"font-medium text-sm",children:"Members not yet registered"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Skip anyone already registered for this event. Best for weekly boost sends."})]}),e.jsx("span",{className:"text-sm font-semibold text-primary",children:O.not_registered.toLocaleString()})]}),e.jsxs("label",{htmlFor:"aud-all",className:"flex items-start gap-3 rounded-lg border p-3 cursor-pointer hover:bg-muted/40 transition",children:[e.jsx(Ym,{value:"all",id:"aud-all",className:"mt-1"}),e.jsxs("div",{className:"flex-1",children:[e.jsx("div",{className:"font-medium text-sm",children:"All members with an email"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Everyone in the system. Use sparingly to avoid inbox fatigue."})]}),e.jsx("span",{className:"text-sm font-semibold text-primary",children:O.all.toLocaleString()})]}),e.jsxs("label",{htmlFor:"aud-reg-noatt",className:"flex items-start gap-3 rounded-lg border p-3 cursor-pointer hover:bg-muted/40 transition",children:[e.jsx(Ym,{value:"registered_never_attended",id:"aud-reg-noatt",className:"mt-1"}),e.jsxs("div",{className:"flex-1",children:[e.jsx("div",{className:"font-medium text-sm",children:"Registered but haven't attended"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Nudge people who signed up but didn't join the Zoom."})]}),e.jsx("span",{className:"text-sm font-semibold text-primary",children:O.registered_never_attended.toLocaleString()})]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{htmlFor:"ev-inv-subject",children:"Subject line (optional)"}),e.jsx(pe,{id:"ev-inv-subject",placeholder:n?`You're invited: ${n.title}`:"You're invited to...",value:l,onChange:Y=>o(Y.target.value),disabled:b}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Leave blank for the default."})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{htmlFor:"ev-inv-intro",children:"Personal message (optional)"}),e.jsx(Rs,{id:"ev-inv-intro",placeholder:"e.g. Our Wednesday live training this week is on lead conversion. Grab your seat — it's a game-changer.",value:c,onChange:Y=>d(Y.target.value),rows:4,disabled:b}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Appears at the top of the email above the event details."})]}),S&&e.jsxs("div",{className:"rounded-lg border bg-muted/30 p-3 space-y-2",children:[e.jsxs("div",{className:"flex justify-between text-xs",children:[e.jsxs("span",{className:"text-muted-foreground",children:["Sending ",S.done.toLocaleString()," / ",S.total.toLocaleString()]}),e.jsxs("span",{className:"font-medium",children:["✓ ",S.sent.toLocaleString(),S.failed>0&&e.jsxs("span",{className:"text-destructive",children:[" · ✗ ",S.failed.toLocaleString()]})]})]}),e.jsx(Yi,{value:G})]})]}),e.jsxs(Ar,{className:"gap-2 sm:gap-2",children:[e.jsx($,{variant:"outline",onClick:W,disabled:b||P||u,children:P?e.jsxs(e.Fragment,{children:[e.jsx(kt,{className:"h-4 w-4 mr-2 animate-spin"})," Sending test..."]}):e.jsxs(e.Fragment,{children:[e.jsx(mn,{className:"h-4 w-4 mr-2"})," Send test to me"]})}),e.jsx($,{variant:"ghost",onClick:()=>t(!1),disabled:b,children:"Cancel"}),e.jsx($,{onClick:()=>I(!0),disabled:b||u||D.length===0,children:b?e.jsxs(e.Fragment,{children:[e.jsx(kt,{className:"h-4 w-4 mr-2 animate-spin"})," Sending..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Yr,{className:"h-4 w-4 mr-2"})," Send to ",D.length.toLocaleString()]})})]})]})}),e.jsx(kc,{open:E,onOpenChange:I,children:e.jsxs(cc,{children:[e.jsxs(dc,{children:[e.jsx(hc,{children:"Send event invite?"}),e.jsxs(mc,{children:["This will send a branded invite to"," ",e.jsxs("span",{className:"font-semibold text-foreground",children:[D.length.toLocaleString()," member",D.length===1?"":"s"]})," ","for"," ",e.jsxs("span",{className:"font-semibold text-foreground",children:['"',n==null?void 0:n.title,'"']}),". This can't be undone."]})]}),e.jsxs(uc,{children:[e.jsx(fc,{children:"Cancel"}),e.jsxs(tc,{onClick:V,children:[e.jsx(Yr,{className:"h-4 w-4 mr-2"})," Send now"]})]})]})})]})}const $de={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 xmn(){const s=Qn(),t=Vt(),[n,r]=j.useState(!1),[a,i]=j.useState(null),[l,o]=j.useState($de),[c,d]=j.useState(null),[u,h]=j.useState(null),[m,f]=j.useState(!1),g=j.useRef(null),[x,y]=j.useState(!1),[v,b]=j.useState(null),[w,S]=j.useState(!1),[C,E]=j.useState(null),[I,P]=j.useState(null),[R,D]=j.useState(!0),[O,U]=j.useState(""),[W,V]=j.useState(!1),[G,Y]=j.useState(null),{data:X,isLoading:ae}=tt({queryKey:["admin-events"],queryFn:async()=>{const{data:Ke,error:nt}=await q.from("events").select("*").order("event_date",{ascending:!0});if(nt)throw nt;return Ke}}),{data:ie}=tt({queryKey:["event-registrations-count"],queryFn:async()=>{let Ke=[],nt=0;const xt=1e3;for(;;){const{data:Yt,error:qt}=await q.from("event_registrations").select("event_id").range(nt,nt+xt-1);if(qt)throw qt;if(!Yt||Yt.length===0||(Ke=Ke.concat(Yt),Yt.length{rt[Yt.event_id]=(rt[Yt.event_id]||0)+1}),rt}}),{data:ne,isLoading:te}=tt({queryKey:["event-registrations-details",v==null?void 0:v.id],queryFn:async()=>{if(!v)return[];const{data:Ke,error:nt}=await q.from("event_registrations").select("id, user_id, registered_at, zoom_join_url, zoom_name, zoom_email").eq("event_id",v.id).order("registered_at",{ascending:!1});if(nt)throw nt;if(!Ke||Ke.length===0)return[];const xt=Ke.map(qt=>qt.user_id).filter(Boolean);let rt=[];if(xt.length>0){const{data:qt,error:ts}=await q.from("profiles").select("id, name, email").in("id",xt);if(ts)throw ts;rt=qt||[]}const Yt=new Map((rt==null?void 0:rt.map(qt=>[qt.id,qt]))||[]);return Ke.map(qt=>({...qt,profiles:qt.user_id&&Yt.get(qt.user_id)||null}))},enabled:!!v}),{data:J,isLoading:ce}=tt({queryKey:["event-attendees-details",v==null?void 0:v.id],queryFn:async()=>{if(!v)return[];const{data:Ke,error:nt}=await q.from("event_attendees").select("id, user_id, zoom_email, zoom_name, join_time, leave_time, duration_minutes, manually_added, created_at").eq("event_id",v.id).order("created_at",{ascending:!1});if(nt)throw nt;if(!Ke||Ke.length===0)return[];const xt=Ke.map(ys=>ys.user_id).filter(Boolean);let rt=[];if(xt.length>0){const{data:ys,error:Bt}=await q.from("profiles").select("id, name, email").in("id",xt);if(Bt)throw Bt;rt=ys||[]}const{data:Yt}=await q.from("agent_points").select("user_id").eq("event_id",v.id),qt=new Set((Yt==null?void 0:Yt.map(ys=>ys.user_id))||[]),ts=new Map((rt==null?void 0:rt.map(ys=>[ys.id,ys]))||[]);return Ke.map(ys=>({...ys,profiles:ys.user_id&&ts.get(ys.user_id)||null,points_awarded:ys.user_id?qt.has(ys.user_id):!1}))},enabled:!!v}),_e=Ke=>{b(Ke),y(!0)},he=ft({mutationFn:async Ke=>{const{data:{session:nt}}=await q.auth.getSession();if(!nt)throw new Error("Not authenticated");const xt=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/zoom-sync-registrations",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${nt.access_token}`},body:JSON.stringify({event_id:Ke})}),rt=await xt.json();if(!xt.ok){const Yt=new Error(rt.error||"Failed to sync");throw Yt.scopeError=!!rt.scope_error,Yt.details=rt.scope_error?"In Zoom, make sure meeting:read:list_registrants:admin is not marked Optional, then Continue/Activate. If it already is required, update the saved Zoom credentials because the backend is using a different app.":void 0,Yt}return rt},onSuccess:Ke=>{if(t.invalidateQueries({queryKey:["event-registrations-details",v==null?void 0:v.id]}),t.invalidateQueries({queryKey:["event-registrations-count"]}),Ke!=null&&Ke.scope_error||(Ke==null?void 0:Ke.success)===!1){re.error("Zoom needs one more authorization step",{description:Ke!=null&&Ke.scope_error?"The app is working, but Zoom is still issuing a token without meeting:read:list_registrants:admin. Make that scope required, not Optional, then Continue/Activate/Save in Zoom and retry. If it still shows 7 scopes, update the saved Zoom credentials to the app you edited.":(Ke==null?void 0:Ke.message)||"Zoom registration sync could not complete.",duration:2e4});return}re.success(Ke.message)},onError:Ke=>{re.error("Failed to sync Zoom registrations",{description:Ke.scopeError&&Ke.details||Ke.message,duration:Ke.scopeError?2e4:5e3})}}),ue=ft({mutationFn:async Ke=>{const{data:{session:nt}}=await q.auth.getSession();if(!nt)throw new Error("Not authenticated");const xt=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/zoom-sync-attendees",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${nt.access_token}`},body:JSON.stringify({event_id:Ke})}),rt=await xt.json();if(!xt.ok)throw new Error(rt.error||"Failed to sync attendees");return rt},onSuccess:Ke=>{if(t.invalidateQueries({queryKey:["event-attendees-details",v==null?void 0:v.id]}),t.invalidateQueries({queryKey:["event-leaderboard"]}),t.invalidateQueries({queryKey:["admin-agent-points"]}),Ke!=null&&Ke.scope_error||(Ke==null?void 0:Ke.success)===!1){re.error((Ke==null?void 0:Ke.message)||"Zoom sync failed",{description:Ke!=null&&Ke.scope_error?"Zoom must be re-authorized after adding the missing report scope.":void 0,duration:15e3});return}Ke!=null&&Ke.message?re.success(Ke.message):re.success(`Synced ${Ke.synced||0} attendees. ${Ke.points_awarded||0} points awarded!`)},onError:Ke=>{re.error("Failed to sync attendees: "+Ke.message)}}),ve=ft({mutationFn:async()=>{const{data:Ke,error:nt}=await q.functions.invoke("zoom-retry-registrations",{body:{}});if(nt)throw nt;return Ke},onSuccess:Ke=>{t.invalidateQueries({queryKey:["event-registrations-details",v==null?void 0:v.id]}),t.invalidateQueries({queryKey:["event-registrations-count"]}),re.success(`Retry complete: ${(Ke==null?void 0:Ke.successCount)??0} fixed, ${(Ke==null?void 0:Ke.failCount)??0} still failing, ${(Ke==null?void 0:Ke.rateLimitedCount)??0} rate-limited`)},onError:Ke=>{re.error("Retry failed: "+Ke.message)}}),Ee=ft({mutationFn:async({eventId:Ke,testMode:nt})=>{const{data:{session:xt}}=await q.auth.getSession();if(!xt)throw new Error("Not authenticated");const rt=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/send-event-reminder",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${xt.access_token}`},body:JSON.stringify({event_id:Ke,test_mode:nt})}),Yt=await rt.json();if(!rt.ok)throw new Error(Yt.error||"Failed to send reminders");return Yt},onSuccess:Ke=>{Ke.test?re.success(Ke.message||"Test email sent!"):re.success(Ke.message||`Reminder emails sent to ${Ke.sent} registrants!`)},onError:Ke=>{re.error("Failed to send reminders: "+Ke.message)}}),{data:Se}=tt({queryKey:["all-profiles-for-linking"],queryFn:async()=>{let Ke=[],nt=0;const xt=1e3;for(;;){const{data:rt,error:Yt}=await q.from("profiles").select("id, name, email").order("name",{ascending:!0}).range(nt,nt+xt-1);if(Yt)throw Yt;if(!rt||rt.length===0||(Ke=[...Ke,...rt],rt.length{const{error:Yt}=await q.from("event_attendees").update({user_id:nt}).eq("id",Ke);if(Yt)throw Yt;if(rt&&xt){const{error:ts}=await q.from("zoom_email_aliases").upsert({user_id:nt,zoom_email:xt.toLowerCase()},{onConflict:"zoom_email"});ts&&console.error("Failed to save alias:",ts)}const qt=v==null?void 0:v.id;if(qt){const{data:ts}=await q.from("user_roles").select("id").eq("user_id",nt).eq("role","admin").single();if(!ts){const{data:ys}=await q.from("agent_points").select("id").eq("user_id",nt).eq("event_id",qt).single();ys||(await q.rpc("award_attendance_points",{p_user_id:nt,p_event_id:qt,p_points:10,p_reason:"Event Attendance (Manual Link)"}),await q.rpc("check_and_award_badges",{p_user_id:nt}))}}return{userId:nt,zoomEmail:xt,shouldSaveAlias:rt}},onSuccess:Ke=>{t.invalidateQueries({queryKey:["event-attendees-details",v==null?void 0:v.id]}),t.invalidateQueries({queryKey:["event-leaderboard"]}),t.invalidateQueries({queryKey:["admin-agent-points"]});let nt="Attendee linked and points awarded!";Ke.shouldSaveAlias&&Ke.zoomEmail&&(nt+=` Email "${Ke.zoomEmail}" will be auto-matched in the future.`),re.success(nt),S(!1),E(null),P(null),U("")},onError:Ke=>{re.error("Failed to link attendee: "+Ke.message)}}),Fe=Ke=>{E(Ke),P(null),D(!0),U(""),S(!0)},ke=()=>{!C||!I||Le.mutate({attendeeId:C.id,userId:I,zoomEmail:C.zoom_email,shouldSaveAlias:R})},Ve=(Se==null?void 0:Se.filter(Ke=>{var xt,rt;if(!O)return!0;const nt=O.toLowerCase();return((xt=Ke.name)==null?void 0:xt.toLowerCase().includes(nt))||((rt=Ke.email)==null?void 0:rt.toLowerCase().includes(nt))}))||[],je=async Ke=>{const nt=Ke.name.split(".").pop(),rt=`${`${crypto.randomUUID()}.${nt}`}`,{error:Yt}=await q.storage.from("event-images").upload(rt,Ke);if(Yt)throw Yt;const{data:{publicUrl:qt}}=q.storage.from("event-images").getPublicUrl(rt);return qt},Ae=Ke=>{var xt;const nt=(xt=Ke.target.files)==null?void 0:xt[0];if(nt){if(nt.size>5*1024*1024){re.error("Image must be less than 5MB");return}d(nt),h(URL.createObjectURL(nt))}},Ce=()=>{d(null),h(null),o({...l,image_url:""}),g.current&&(g.current.value="")},qe=ft({mutationFn:async Ke=>{f(!0);let nt=Ke.image_url;c&&(nt=await je(c)||"");const xt=new Date(Ke.event_date),[rt,Yt]=Ke.event_time.split(":");xt.setHours(parseInt(rt),parseInt(Yt));const qt=[new Date(xt)];if(Ke.is_recurring&&Ke.recurrence_end_date){let Ft=new Date(xt);for(;Ke.recurrence_pattern==="weekly"?Ft=c8(Ft,1):Ke.recurrence_pattern==="biweekly"?Ft=c8(Ft,2):Ft=Mv(Ft,1),!(Ft>Ke.recurrence_end_date);)qt.push(new Date(Ft))}const ts=qt.map(Ft=>({title:Ke.title,description:Ke.description||null,image_url:nt||null,video_url:Ke.video_url||null,event_date:Ft.toISOString(),zoom_link:Ke.zoom_link,zoom_meeting_id:Ke.zoom_meeting_id||null,capacity:Ke.capacity?parseInt(Ke.capacity):null,is_published:Ke.is_published})),{data:ys,error:Bt}=await q.from("events").insert(ts).select();if(Bt)throw Bt;return ys&&ys.length>0&&umn(Ke.title,ys[0].id),qt.length},onSuccess:Ke=>{t.invalidateQueries({queryKey:["admin-events"]}),re.success(Ke>1?`${Ke} recurring events created successfully`:"Event created successfully"),r(!1),o($de),d(null),h(null),f(!1)},onError:Ke=>{re.error("Failed to create event: "+Ke.message),f(!1)}}),ze=ft({mutationFn:async({id:Ke,data:nt})=>{f(!0);let xt=nt.image_url;c&&(xt=await je(c)||"");const rt=new Date(nt.event_date),[Yt,qt]=nt.event_time.split(":");rt.setHours(parseInt(Yt),parseInt(qt));const{error:ts}=await q.from("events").update({title:nt.title,description:nt.description||null,image_url:xt||null,video_url:nt.video_url||null,event_date:rt.toISOString(),zoom_link:nt.zoom_link,zoom_meeting_id:nt.zoom_meeting_id||null,capacity:nt.capacity?parseInt(nt.capacity):null,is_published:nt.is_published}).eq("id",Ke);if(ts)throw ts},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-events"]}),re.success("Event updated successfully"),r(!1),i(null),o($de),d(null),h(null),f(!1)},onError:Ke=>{re.error("Failed to update event: "+Ke.message),f(!1)}}),$e=ft({mutationFn:async Ke=>{const{error:nt}=await q.from("events").delete().eq("id",Ke);if(nt)throw nt},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-events"]}),re.success("Event deleted successfully")},onError:Ke=>{re.error("Failed to delete event: "+Ke.message)}}),ct=ft({mutationFn:async Ke=>{var Ft;const{data:nt}=await q.auth.getUser(),xt=new Date(Ke.event_date),rt=new Date(xt.getTime()+60*60*1e3),Yt=omn(Ke.title),qt=Math.random().toString(36).slice(2,7),ts=`${Yt}-${qt}`,{data:ys,error:Bt}=await q.from("live_events").insert({slug:ts,title:Ke.title,description:Ke.description||null,hero_image_url:Ke.image_url||null,starts_at:Ke.event_date,ends_at:rt.toISOString(),timezone:"America/New_York",status:"scheduled",is_published:!1,require_registration:!0,invite_only:!1,chat_enabled:!0,questions_mode:!1,replay_enabled:!0,auto_go_live:!0,auto_end:!0,zoom_meeting_id:Ke.zoom_meeting_id||null,cta_label:"Join the training",cta_url:Ke.zoom_link||"https://dashboard.relevelup.com/trial",created_by:(Ft=nt.user)==null?void 0:Ft.id,agenda:[],offer_bullets:[]}).select().single();if(Bt)throw Bt;return ys},onSuccess:Ke=>{t.invalidateQueries({queryKey:["live-events"]}),re.success("Cloned to LevelUp Live — configure stream next"),s(`/admin/live/${Ke.id}`)},onError:Ke=>{re.error("Failed to clone to LevelUp Live: "+Ke.message)}}),Xe=Ke=>{var xt;const nt=new Date(Ke.event_date);i(Ke),o({title:Ke.title,description:Ke.description||"",image_url:Ke.image_url||"",video_url:Ke.video_url||"",event_date:nt,event_time:en(nt,"HH:mm"),zoom_link:Ke.zoom_link,zoom_meeting_id:Ke.zoom_meeting_id||"",capacity:((xt=Ke.capacity)==null?void 0:xt.toString())||"",is_published:Ke.is_published,is_recurring:!1,recurrence_pattern:"weekly",recurrence_end_date:void 0}),h(Ke.image_url||null),d(null),r(!0)},it=Ke=>{if(Ke.preventDefault(),!l.event_date){re.error("Please select a date");return}if(l.is_recurring&&!l.recurrence_end_date){re.error("Please select an end date for recurring events");return}a?ze.mutate({id:a.id,data:l}):qe.mutate(l)},at=()=>{r(!1),i(null),o($de),d(null),h(null)};return e.jsx("div",{className:"min-h-screen bg-background p-6",children:e.jsxs("div",{className:"max-w-6xl mx-auto space-y-6",children:[e.jsx(Fm,{title:"Event Management",description:"Create and manage upcoming events"}),e.jsxs(Ne,{className:"mb-6",children:[e.jsxs(Ct,{className:"flex flex-row items-center justify-between",children:[e.jsx(At,{children:"All Events"}),e.jsxs(zs,{open:n,onOpenChange:Ke=>!Ke&&at(),children:[e.jsx(jl,{asChild:!0,children:e.jsxs($,{onClick:()=>r(!0),children:[e.jsx(dn,{className:"h-4 w-4 mr-2"}),"Add Event"]})}),e.jsxs(Os,{className:"max-w-lg max-h-[90vh] overflow-y-auto",children:[e.jsx(Us,{children:e.jsx(Bs,{children:a?"Edit Event":"Create New Event"})}),e.jsxs("form",{onSubmit:it,className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"title",children:"Title *"}),e.jsx(pe,{id:"title",value:l.title,onChange:Ke=>o({...l,title:Ke.target.value}),placeholder:"Event title",required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Description"}),e.jsx(Ek,{content:l.description,onChange:Ke=>o({...l,description:Ke}),placeholder:"Event description",minHeight:"120px"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Event Image"}),e.jsx("input",{type:"file",ref:g,accept:"image/*",onChange:Ae,className:"hidden"}),u?e.jsxs("div",{className:"relative",children:[e.jsx("img",{src:u,alt:"Event preview",className:"w-full h-32 object-cover rounded-lg border"}),e.jsx($,{type:"button",variant:"destructive",size:"icon",className:"absolute top-2 right-2 h-6 w-6",onClick:Ce,children:e.jsx(gr,{className:"h-4 w-4"})})]}):e.jsxs($,{type:"button",variant:"outline",className:"w-full h-32 border-dashed flex flex-col gap-2",onClick:()=>{var Ke;return(Ke=g.current)==null?void 0:Ke.click()},children:[e.jsx(ni,{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(ee,{children:"Date *"}),e.jsxs(Yd,{children:[e.jsx(Zd,{asChild:!0,children:e.jsxs($,{variant:"outline",className:Pt("w-full justify-start text-left font-normal",!l.event_date&&"text-muted-foreground"),children:[e.jsx(Ta,{className:"mr-2 h-4 w-4"}),l.event_date?en(l.event_date,"PPP"):"Pick a date"]})}),e.jsx(Bd,{className:"w-auto p-0",align:"start",children:e.jsx(D2,{mode:"single",selected:l.event_date,onSelect:Ke=>o({...l,event_date:Ke}),initialFocus:!0,className:"p-3 pointer-events-auto"})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"time",children:"Time *"}),e.jsx(pe,{id:"time",type:"time",value:l.event_time,onChange:Ke=>o({...l,event_time:Ke.target.value}),required:!0})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"zoom_link",children:"Zoom Link *"}),e.jsx(pe,{id:"zoom_link",value:l.zoom_link,onChange:Ke=>o({...l,zoom_link:Ke.target.value}),placeholder:"https://zoom.us/j/...",required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"zoom_meeting_id",children:"Zoom Meeting ID (for API registration)"}),e.jsx(pe,{id:"zoom_meeting_id",value:l.zoom_meeting_id,onChange:Ke=>o({...l,zoom_meeting_id:Ke.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(ee,{htmlFor:"video_url",children:"Promo Video URL (optional)"}),e.jsx(pe,{id:"video_url",value:l.video_url,onChange:Ke=>o({...l,video_url:Ke.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(ee,{htmlFor:"capacity",children:"Capacity (optional)"}),e.jsx(pe,{id:"capacity",type:"number",value:l.capacity,onChange:Ke=>o({...l,capacity:Ke.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(zE,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(ee,{htmlFor:"is_recurring",children:"Recurring Event"})]}),e.jsx(Sn,{id:"is_recurring",checked:l.is_recurring,onCheckedChange:Ke=>o({...l,is_recurring:Ke})})]}),l.is_recurring&&e.jsxs("div",{className:"space-y-3 pt-1",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Frequency"}),e.jsxs(ms,{value:l.recurrence_pattern,onValueChange:Ke=>o({...l,recurrence_pattern:Ke}),children:[e.jsx(us,{children:e.jsx(fs,{})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"weekly",children:"Weekly"}),e.jsx(Ge,{value:"biweekly",children:"Every 2 Weeks"}),e.jsx(Ge,{value:"monthly",children:"Monthly"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Repeat Until"}),e.jsxs(Yd,{children:[e.jsx(Zd,{asChild:!0,children:e.jsxs($,{variant:"outline",className:Pt("w-full justify-start text-left font-normal",!l.recurrence_end_date&&"text-muted-foreground"),children:[e.jsx(Ta,{className:"mr-2 h-4 w-4"}),l.recurrence_end_date?en(l.recurrence_end_date,"PPP"):"Pick end date"]})}),e.jsx(Bd,{className:"w-auto p-0",align:"start",children:e.jsx(D2,{mode:"single",selected:l.recurrence_end_date,onSelect:Ke=>o({...l,recurrence_end_date:Ke}),disabled:Ke=>Ke<(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 Ke=1,nt=new Date(l.event_date);for(;nt=l.recurrence_pattern==="weekly"?c8(nt,1):l.recurrence_pattern==="biweekly"?c8(nt,2):Mv(nt,1),!(nt>l.recurrence_end_date);)Ke++;return Ke})()," events with the same Zoom link"]})]})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(ee,{htmlFor:"is_published",children:"Published"}),e.jsx(Sn,{id:"is_published",checked:l.is_published,onCheckedChange:Ke=>o({...l,is_published:Ke})})]}),e.jsxs("div",{className:"flex gap-2 pt-4",children:[e.jsx($,{type:"button",variant:"outline",onClick:at,className:"flex-1",children:"Cancel"}),e.jsx($,{type:"submit",className:"flex-1",disabled:qe.isPending||ze.isPending||m,children:m?"Uploading...":a?"Update Event":l.is_recurring&&l.event_date&&l.recurrence_end_date?"Create Recurring Events":"Create Event"})]})]})]})]})]}),e.jsx(Ie,{children:ae?e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:"Loading events..."}):(X==null?void 0:X.length)===0?e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:"No events yet. Create your first event!"}):(()=>{const Ke=new Date,nt=[...X||[]],xt=nt.filter(ys=>new Date(ys.event_date)>=Ke).sort((ys,Bt)=>new Date(ys.event_date).getTime()-new Date(Bt.event_date).getTime()),rt=nt.filter(ys=>new Date(ys.event_date)new Date(Bt.event_date).getTime()-new Date(ys.event_date).getTime()),Yt=xt[0],qt=ys=>e.jsxs(En,{children:[e.jsx(wt,{className:"font-medium",children:ys.title}),e.jsx(wt,{className:"whitespace-nowrap",children:en(new Date(ys.event_date),"PPP p")}),e.jsx(wt,{children:e.jsxs($,{variant:"ghost",size:"sm",className:"gap-1",onClick:()=>_e(ys),children:[e.jsx(Zn,{className:"h-4 w-4"}),(ie==null?void 0:ie[ys.id])||0,ys.capacity&&` / ${ys.capacity}`]})}),e.jsx(wt,{children:e.jsx("span",{className:Pt("px-2 py-1 rounded-full text-xs font-medium",ys.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:ys.is_published?"Published":"Draft"})}),e.jsx(wt,{className:"text-right",children:e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsxs($,{variant:"outline",size:"sm",className:"gap-1.5",onClick:()=>{Y(ys),V(!0)},title:"Send invite email to members",children:[e.jsx(Yr,{className:"h-3.5 w-3.5"}),e.jsx("span",{className:"hidden sm:inline",children:"Invite Members"})]}),e.jsxs($,{variant:"outline",size:"sm",className:"gap-1.5 border-primary/50 text-primary hover:bg-primary/10",onClick:()=>ct.mutate(ys),disabled:ct.isPending,title:"Clone to LevelUp Live",children:[e.jsx(Nb,{className:"h-3.5 w-3.5"}),e.jsx("span",{className:"hidden sm:inline",children:"LevelUp Live"})]}),e.jsx($,{variant:"ghost",size:"icon",onClick:()=>window.open(ys.zoom_link,"_blank"),title:"Open Zoom Link",children:e.jsx(kr,{className:"h-4 w-4"})}),e.jsx($,{variant:"ghost",size:"icon",onClick:()=>Xe(ys),children:e.jsx(gi,{className:"h-4 w-4"})}),e.jsx($,{variant:"ghost",size:"icon",onClick:async()=>{await fo("Are you sure you want to delete this event?")&&$e.mutate(ys.id)},children:e.jsx(Wn,{className:"h-4 w-4 text-destructive"})})]})})]},ys.id),ts=(ys,Bt)=>ys.length===0?e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:Bt}):e.jsxs(mi,{children:[e.jsx(fi,{children:e.jsxs(En,{children:[e.jsx(Dt,{children:"Title"}),e.jsx(Dt,{children:"Date & Time"}),e.jsx(Dt,{children:"Registrations"}),e.jsx(Dt,{children:"Status"}),e.jsx(Dt,{className:"text-right",children:"Actions"})]})}),e.jsx(pi,{children:ys.map(qt)})]});return e.jsxs("div",{className:"space-y-6",children:[Yt&&e.jsx("div",{className:"rounded-xl border bg-gradient-to-br from-primary/10 via-primary/5 to-transparent p-5",children:e.jsxs("div",{className:"flex items-start justify-between gap-4 flex-wrap",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 text-xs font-semibold uppercase tracking-wide text-primary mb-1",children:[e.jsx(da,{className:"h-3.5 w-3.5"}),"Next Upcoming Event"]}),e.jsx("h3",{className:"text-xl font-bold truncate",children:Yt.title}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:en(new Date(Yt.event_date),"EEEE, PPP 'at' p")}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:[(ie==null?void 0:ie[Yt.id])||0," registered",Yt.capacity?` of ${Yt.capacity}`:""]})]}),e.jsxs("div",{className:"flex gap-2 flex-wrap",children:[e.jsxs($,{size:"sm",className:"gap-1.5",onClick:()=>{Y(Yt),V(!0)},children:[e.jsx(Yr,{className:"h-4 w-4"}),"Invite Members"]}),e.jsxs($,{size:"sm",variant:"outline",className:"gap-1.5",onClick:()=>_e(Yt),children:[e.jsx(Zn,{className:"h-4 w-4"}),"Registrations"]}),e.jsxs($,{size:"sm",variant:"outline",className:"gap-1.5 border-primary/50 text-primary hover:bg-primary/10",onClick:()=>ct.mutate(Yt),disabled:ct.isPending,children:[e.jsx(Nb,{className:"h-4 w-4"}),"LevelUp Live"]}),e.jsxs($,{size:"sm",variant:"outline",className:"gap-1.5",onClick:()=>window.open(Yt.zoom_link,"_blank"),children:[e.jsx(kr,{className:"h-4 w-4"}),"Zoom"]})]})]})}),e.jsxs(ha,{defaultValue:"upcoming",className:"w-full",children:[e.jsxs(ma,{children:[e.jsxs(Zt,{value:"upcoming",className:"gap-2",children:[e.jsx(da,{className:"h-4 w-4"}),"Upcoming",e.jsx("span",{className:"ml-1 rounded-full bg-muted px-2 py-0.5 text-xs",children:xt.length})]}),e.jsxs(Zt,{value:"past",className:"gap-2",children:[e.jsx(qr,{className:"h-4 w-4"}),"Past",e.jsx("span",{className:"ml-1 rounded-full bg-muted px-2 py-0.5 text-xs",children:rt.length})]})]}),e.jsx(Xt,{value:"upcoming",className:"mt-4",children:ts(xt,"No upcoming events scheduled.")}),e.jsx(Xt,{value:"past",className:"mt-4",children:ts(rt,"No past events.")})]})]})})()})]}),e.jsx(gmn,{open:W,onOpenChange:V,event:G}),e.jsx(zs,{open:x,onOpenChange:y,children:e.jsxs(Os,{className:"max-w-3xl max-h-[80vh] overflow-y-auto",children:[e.jsxs(Us,{children:[e.jsxs(Bs,{className:"flex items-center gap-2",children:[e.jsx(Zn,{className:"h-5 w-5"}),v==null?void 0:v.title]}),e.jsx(Ir,{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($,{variant:"ghost",size:"sm",onClick:()=>Ee.mutate({eventId:v.id,testMode:!0}),disabled:Ee.isPending,children:[e.jsx(mn,{className:Pt("h-4 w-4 mr-2",Ee.isPending&&"animate-spin")}),"Send Test to Me"]}),e.jsxs($,{variant:"outline",size:"sm",onClick:()=>Ee.mutate({eventId:v.id}),disabled:Ee.isPending||!(ne!=null&&ne.length),children:[e.jsx(mn,{className:Pt("h-4 w-4 mr-2",Ee.isPending&&"animate-spin")}),Ee.isPending?"Sending...":"Send Reminder to All"]}),(v==null?void 0:v.zoom_meeting_id)&&e.jsxs(e.Fragment,{children:[e.jsxs($,{variant:"outline",size:"sm",onClick:()=>he.mutate(v.id),disabled:he.isPending,children:[e.jsx(ro,{className:Pt("h-4 w-4 mr-2",he.isPending&&"animate-spin")}),he.isPending?"Syncing...":"Sync Registrations"]}),e.jsxs($,{variant:"outline",size:"sm",onClick:()=>ve.mutate(),disabled:ve.isPending,children:[e.jsx(ro,{className:Pt("h-4 w-4 mr-2",ve.isPending&&"animate-spin")}),ve.isPending?"Retrying...":"Retry Failed Registrations"]}),e.jsxs($,{variant:"default",size:"sm",onClick:()=>ue.mutate(v.id),disabled:ue.isPending,children:[e.jsx(Kl,{className:Pt("h-4 w-4 mr-2",ue.isPending&&"animate-spin")}),ue.isPending?"Syncing...":"Sync Attendees & Award Points"]})]})]}),e.jsxs(ha,{defaultValue:"registrations",className:"w-full",children:[e.jsxs(ma,{className:"grid w-full grid-cols-2",children:[e.jsxs(Zt,{value:"registrations",className:"gap-2",children:[e.jsx(Zn,{className:"h-4 w-4"}),"Registrations (",(ne==null?void 0:ne.length)||0,")"]}),e.jsxs(Zt,{value:"attendees",className:"gap-2",children:[e.jsx(qr,{className:"h-4 w-4"}),"Attendees (",(J==null?void 0:J.length)||0,")"]})]}),e.jsx(Xt,{value:"registrations",className:"mt-4",children:te?e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:"Loading registrations..."}):(ne==null?void 0:ne.length)===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx("p",{children:"No registrations yet for this event."}),(v==null?void 0:v.zoom_meeting_id)&&e.jsx("p",{className:"text-xs mt-2",children:'Click "Sync Registrations" to import from Zoom.'})]}):e.jsxs(mi,{children:[e.jsx(fi,{children:e.jsxs(En,{children:[e.jsx(Dt,{children:"Name"}),e.jsx(Dt,{children:"Email"}),e.jsx(Dt,{children:"Registered"}),e.jsx(Dt,{children:"Status"})]})}),e.jsx(pi,{children:ne==null?void 0:ne.map(Ke=>{var Yt,qt;const nt=((Yt=Ke.profiles)==null?void 0:Yt.name)||Ke.zoom_name||"Unknown",xt=((qt=Ke.profiles)==null?void 0:qt.email)||Ke.zoom_email||null,rt=!Ke.user_id;return e.jsxs(En,{children:[e.jsx(wt,{className:"font-medium",children:e.jsxs("div",{className:"flex items-center gap-2",children:[nt,rt&&e.jsx("span",{className:"text-xs px-1.5 py-0.5 rounded bg-muted text-muted-foreground",children:"External"})]})}),e.jsx(wt,{children:xt?e.jsxs("a",{href:`mailto:${xt}`,className:"flex items-center gap-1 text-primary hover:underline",children:[e.jsx(mn,{className:"h-3 w-3"}),xt]}):e.jsx("span",{className:"text-muted-foreground",children:"No email"})}),e.jsx(wt,{className:"text-muted-foreground text-sm",children:en(new Date(Ke.registered_at),"MMM d, yyyy h:mm a")}),e.jsx(wt,{children:Ke.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"})})]},Ke.id)})})]})}),e.jsx(Xt,{value:"attendees",className:"mt-4",children:ce?e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:"Loading attendees..."}):(J==null?void 0:J.length)===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx("p",{children:"No attendees recorded yet."}),(v==null?void 0:v.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:[(J==null?void 0:J.filter(Ke=>!Ke.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(ll,{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 (",J==null?void 0:J.filter(Ke=>!Ke.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:J==null?void 0:J.filter(Ke=>!Ke.user_id).map(Ke=>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:Ke.zoom_name||"Unknown"}),e.jsx("span",{className:"text-xs text-muted-foreground",children:Ke.zoom_email||"No email"})]}),e.jsxs($,{variant:"outline",size:"sm",onClick:()=>Fe(Ke),className:"gap-1",children:[e.jsx(bd,{className:"h-3 w-3"}),"Link to Profile"]})]},Ke.id))})]}),e.jsxs(mi,{children:[e.jsx(fi,{children:e.jsxs(En,{children:[e.jsx(Dt,{children:"Name"}),e.jsx(Dt,{children:"Email"}),e.jsx(Dt,{children:"Duration"}),e.jsx(Dt,{children:"Points"})]})}),e.jsx(pi,{children:J==null?void 0:J.filter(Ke=>Ke.user_id).map(Ke=>{var rt,Yt;const nt=((rt=Ke.profiles)==null?void 0:rt.name)||Ke.zoom_name||"Unknown",xt=((Yt=Ke.profiles)==null?void 0:Yt.email)||Ke.zoom_email||null;return e.jsxs(En,{children:[e.jsx(wt,{className:"font-medium",children:e.jsxs("div",{className:"flex items-center gap-2",children:[nt,Ke.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(wt,{children:xt?e.jsxs("a",{href:`mailto:${xt}`,className:"flex items-center gap-1 text-primary hover:underline",children:[e.jsx(mn,{className:"h-3 w-3"}),xt]}):e.jsx("span",{className:"text-muted-foreground",children:"No email"})}),e.jsx(wt,{children:Ke.duration_minutes?e.jsxs("span",{className:"flex items-center gap-1 text-muted-foreground text-sm",children:[e.jsx(da,{className:"h-3 w-3"}),Ke.duration_minutes," min"]}):e.jsx("span",{className:"text-muted-foreground text-sm",children:"—"})}),e.jsx(wt,{children:Ke.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(Kl,{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"})})]},Ke.id)})})]})]})})]})]})}),e.jsx(zs,{open:w,onOpenChange:S,children:e.jsxs(Os,{className:"max-w-md",children:[e.jsxs(Us,{children:[e.jsxs(Bs,{className:"flex items-center gap-2",children:[e.jsx(bd,{className:"h-5 w-5"}),"Link Attendee to Profile"]}),e.jsx(Ir,{children:"Link this Zoom attendee to an existing member profile to award them points."})]}),C&&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:C.zoom_name||"Unknown"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:C.zoom_email||"No email"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Search for a profile"}),e.jsxs("div",{className:"relative",children:[e.jsx(Kr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(pe,{placeholder:"Search by name or email...",value:O,onChange:Ke=>U(Ke.target.value),className:"pl-9"})]})]}),e.jsx("div",{className:"max-h-48 overflow-y-auto border rounded-md",children:Ve.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:Ve.slice(0,20).map(Ke=>e.jsxs("button",{type:"button",onClick:()=>P(Ke.id),className:Pt("w-full p-3 text-left hover:bg-muted/50 transition-colors",I===Ke.id&&"bg-primary/10 border-l-2 border-primary"),children:[e.jsx("p",{className:"text-sm font-medium",children:Ke.name||"Unnamed"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:Ke.email})]},Ke.id))})}),C.zoom_email&&e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(ai,{id:"save-alias",checked:R,onCheckedChange:Ke=>D(Ke)}),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($,{variant:"outline",onClick:()=>S(!1),children:"Cancel"}),e.jsx($,{onClick:ke,disabled:!I||Le.isPending,children:Le.isPending?"Linking...":"Link & Award Points"})]})]})]})})]})})}const ymn={ok:"bg-emerald-500/10 text-emerald-700 dark:text-emerald-400",error:"bg-red-500/10 text-red-700 dark:text-red-400",denied:"bg-amber-500/10 text-amber-700 dark:text-amber-400",rate_limited:"bg-orange-500/10 text-orange-700 dark:text-orange-400"};function vmn(){const[s,t]=j.useState([]),[n,r]=j.useState(!0),[a,i]=j.useState("issues");async function l(){r(!0);let o=q.from("mcp_audit_log").select("id, user_id, tool_name, outcome, error_message, duration_ms, client_id, created_at").order("created_at",{ascending:!1}).limit(200);a==="issues"&&(o=o.in("outcome",["denied","rate_limited","error"]));const{data:c,error:d}=await o;d||t(c??[]),r(!1)}return j.useEffect(()=>{l()},[a]),e.jsx(Vs,{title:"MCP Audit Log",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(Fm,{title:"MCP Audit Log",description:"Recent LevelUp MCP tool calls — ChatGPT / Claude / Codex activity, denials, and rate limits."}),e.jsxs(Ne,{children:[e.jsxs(Ct,{className:"flex flex-row items-center justify-between",children:[e.jsxs(At,{className:"flex items-center gap-2",children:[e.jsx(aV,{className:"h-5 w-5"}),"Recent activity"]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx($,{variant:a==="issues"?"default":"outline",size:"sm",onClick:()=>i("issues"),children:"Issues only"}),e.jsx($,{variant:a==="all"?"default":"outline",size:"sm",onClick:()=>i("all"),children:"All calls"}),e.jsx($,{variant:"ghost",size:"sm",onClick:l,disabled:n,children:e.jsx(ro,{className:`h-4 w-4 ${n?"animate-spin":""}`})})]})]}),e.jsx(Ie,{children:n?e.jsx("p",{className:"text-sm text-muted-foreground",children:"Loading…"}):s.length===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:"No entries."}):e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{className:"border-b text-left text-muted-foreground",children:e.jsxs("tr",{children:[e.jsx("th",{className:"py-2 pr-4",children:"When"}),e.jsx("th",{className:"py-2 pr-4",children:"Tool"}),e.jsx("th",{className:"py-2 pr-4",children:"Outcome"}),e.jsx("th",{className:"py-2 pr-4",children:"User"}),e.jsx("th",{className:"py-2 pr-4",children:"Client"}),e.jsx("th",{className:"py-2 pr-4",children:"ms"}),e.jsx("th",{className:"py-2 pr-4",children:"Error"})]})}),e.jsx("tbody",{children:s.map(o=>e.jsxs("tr",{className:"border-b last:border-0",children:[e.jsx("td",{className:"py-2 pr-4 whitespace-nowrap",children:new Date(o.created_at).toLocaleString()}),e.jsx("td",{className:"py-2 pr-4 font-mono text-xs",children:o.tool_name}),e.jsx("td",{className:"py-2 pr-4",children:e.jsx(Be,{className:ymn[o.outcome]??"",variant:"secondary",children:o.outcome})}),e.jsx("td",{className:"py-2 pr-4 font-mono text-xs",children:o.user_id?o.user_id.slice(0,8):"—"}),e.jsx("td",{className:"py-2 pr-4 font-mono text-xs",children:o.client_id?o.client_id.slice(0,12):"—"}),e.jsx("td",{className:"py-2 pr-4",children:o.duration_ms??"—"}),e.jsx("td",{className:"py-2 pr-4 text-xs text-muted-foreground max-w-[24rem] truncate",children:o.error_message??""})]},o.id))})]})})})]})]})})}function bmn({selectedKitIds:s,onChange:t}){const[n,r]=j.useState(""),[a,i]=j.useState(!1),{data:l=[]}=tt({queryKey:["all-resource-kits-picker"],queryFn:async()=>{const{data:h,error:m}=await q.from("resource_kits").select("id, name, featured_image_url").eq("is_published",!0).order("name");if(m)throw m;return h}}),o=l.filter(h=>s.includes(h.id)),c=l.filter(h=>!s.includes(h.id)&&h.name.toLowerCase().includes(n.toLowerCase())),d=h=>{t([...s,h])},u=h=>{t(s.filter(m=>m!==h))};return e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ee,{className:"flex items-center gap-2",children:[e.jsx(vm,{className:"h-4 w-4"}),"Linked Toolkits"]}),o.length>0&&e.jsx("div",{className:"flex flex-wrap gap-1.5",children:o.map(h=>e.jsxs(Be,{variant:"secondary",className:"gap-1 pr-1",children:[h.name,e.jsx("button",{type:"button",onClick:()=>u(h.id),className:"ml-1 rounded-full hover:bg-muted-foreground/20 p-0.5",children:e.jsx(gr,{className:"h-3 w-3"})})]},h.id))}),e.jsxs(Yd,{open:a,onOpenChange:i,children:[e.jsx(Zd,{asChild:!0,children:e.jsxs($,{type:"button",variant:"outline",size:"sm",className:"gap-1",children:[e.jsx(vm,{className:"h-3.5 w-3.5"}),"Add Toolkit"]})}),e.jsxs(Bd,{className:"w-80 p-2",align:"start",children:[e.jsxs("div",{className:"relative mb-2",children:[e.jsx(Kr,{className:"absolute left-2 top-2.5 h-3.5 w-3.5 text-muted-foreground"}),e.jsx(pe,{placeholder:"Search toolkits...",value:n,onChange:h=>r(h.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:n?"No toolkits found":"All toolkits selected"}):c.map(h=>e.jsxs("button",{type:"button",onClick:()=>{d(h.id),r("")},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:[h.featured_image_url?e.jsx("img",{src:h.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(vm,{className:"h-3.5 w-3.5 text-muted-foreground"})}),e.jsx("span",{className:"truncate",children:h.name})]},h.id))})]})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Link toolkits that agents can download alongside this template."})]})}const _mn=()=>{const{user:s}=vs(),{toast:t}=Bi(),n=Vt(),[r,a]=gc(),[i,l]=j.useState(!1),[o,c]=j.useState(null),[d,u]=j.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:""}),[h,m]=j.useState(null),[f,g]=j.useState(0),[x,y]=j.useState(!1),[v,b]=j.useState(null),[w,S]=j.useState(""),[C,E]=j.useState([]),[I,P]=j.useState(""),[R,D]=j.useState(""),[O,U]=j.useState(!1),[W,V]=j.useState(!1),{data:G=[]}=tt({queryKey:["template-categories"],queryFn:async()=>{const{data:Ce,error:qe}=await q.from("template_categories").select("*").order("name");if(qe)throw qe;return Ce}}),{data:Y=[]}=tt({queryKey:["template-types"],queryFn:async()=>{const{data:Ce,error:qe}=await q.from("template_types").select("*").order("name");if(qe)throw qe;return Ce}}),{data:X=[],isLoading:ae}=tt({queryKey:["canva-templates-admin"],queryFn:async()=>{const{data:Ce,error:qe}=await q.from("canva_templates").select(` *, category:template_categories(id, name), type:template_types(id, name) `).order("publish_date",{ascending:!1});if(qe)throw qe;const{data:ze,error:$e}=await q.from("template_links").select("*").order("sort_order");if($e)throw $e;const{data:ct,error:Xe}=await q.from("template_guides").select("*").order("sort_order");if(Xe)throw Xe;return Ce.map(at=>({...at,links:(ze==null?void 0:ze.filter(Ke=>Ke.template_id===at.id))||[],guides:(ct==null?void 0:ct.filter(Ke=>Ke.template_id===at.id))||[]}))}});j.useEffect(()=>{const Ce=r.get("edit");if(Ce&&X.length>0){const qe=X.find(ze=>ze.id===Ce);qe&&(he(qe),a({},{replace:!0}))}},[X,r]);const ie=ft({mutationFn:async Ce=>{const{data:qe,error:ze}=await q.from("template_categories").insert({name:Ce}).select().single();if(ze)throw ze;return qe},onSuccess:Ce=>{n.invalidateQueries({queryKey:["template-categories"]}),u({...d,category_id:Ce.id}),P(""),U(!1),t({title:"Category added"})},onError:Ce=>{t({title:"Error adding category",description:Ce.message,variant:"destructive"})}}),ne=ft({mutationFn:async Ce=>{const{data:qe,error:ze}=await q.from("template_types").insert({name:Ce}).select().single();if(ze)throw ze;return qe},onSuccess:Ce=>{n.invalidateQueries({queryKey:["template-types"]}),u({...d,type_id:Ce.id}),D(""),V(!1),t({title:"Type added"})},onError:Ce=>{t({title:"Error adding type",description:Ce.message,variant:"destructive"})}}),te=ft({mutationFn:async Ce=>{var Xe;let qe=Ce.existingImageUrl;if(Ce.image){const it=Ce.image.name.split(".").pop(),at=`${Date.now()}-${Math.random().toString(36).substring(7)}.${it}`,{error:Ke}=await q.storage.from("template-previews").upload(at,Ce.image);if(Ke)throw Ke;const{data:nt}=q.storage.from("template-previews").getPublicUrl(at);qe=nt.publicUrl}const ze={name:Ce.template.name,description:Ce.template.description||null,category_id:Ce.template.category_id||null,type_id:Ce.template.type_id||null,preview_image_url:qe,video_url:Ce.videoUrl||null,publish_date:Ce.template.publish_date?new Date(Ce.template.publish_date).toISOString():new Date().toISOString(),created_by:s==null?void 0:s.id};let $e=Ce.templateId;if($e){const{error:it}=await q.from("canva_templates").update(ze).eq("id",$e);if(it)throw it;const{error:at}=await q.from("template_links").delete().eq("template_id",$e);if(at)throw at;const Ke=((Xe=Ce.existingGuides)==null?void 0:Xe.map(rt=>rt.id).filter(Boolean))||[],nt=Ce.template.guides.map(rt=>rt.id).filter(Boolean),xt=Ke.filter(rt=>!nt.includes(rt));xt.length>0&&await q.from("template_guides").delete().in("id",xt)}else{const{data:it,error:at}=await q.from("canva_templates").insert(ze).select().single();if(at)throw at;$e=it.id,cmn(Ce.template.name,it.id)}const ct=Ce.template.links.filter(it=>it.title.trim()&&it.canva_share_link.trim());if(ct.length>0){const it=ct.map((Ke,nt)=>({template_id:$e,title:Ke.title.trim(),canva_share_link:Ke.canva_share_link.trim(),sort_order:nt})),{error:at}=await q.from("template_links").insert(it);if(at)throw at}for(let it=0;it0)){const{error:it}=await q.from("resource_kit_templates").insert(Ce.linkedKitIds.map(at=>({template_id:$e,kit_id:at})));if(it)throw it}},onSuccess:()=>{n.invalidateQueries({queryKey:["canva-templates-admin"]}),n.invalidateQueries({queryKey:["canva-templates"]}),_e(),l(!1),t({title:o?"Template updated":"Template created"})},onError:Ce=>{t({title:"Error saving template",description:Ce.message,variant:"destructive"})}}),J=ft({mutationFn:async Ce=>{const{error:qe}=await q.from("canva_templates").delete().eq("id",Ce);if(qe)throw qe},onSuccess:()=>{n.invalidateQueries({queryKey:["canva-templates-admin"]}),n.invalidateQueries({queryKey:["canva-templates"]}),t({title:"Template deleted"})},onError:Ce=>{t({title:"Error deleting template",description:Ce.message,variant:"destructive"})}}),ce=ft({mutationFn:async({id:Ce,is_featured:qe})=>{const{error:ze}=await q.from("canva_templates").update({is_featured:qe}).eq("id",Ce);if(ze)throw ze},onSuccess:()=>{n.invalidateQueries({queryKey:["canva-templates-admin"]}),n.invalidateQueries({queryKey:["canva-templates"]})},onError:Ce=>{t({title:"Error updating featured",description:Ce.message,variant:"destructive"})}}),_e=()=>{u({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:""}),b(null),S(""),c(null),U(!1),V(!1),P(""),D(""),m(null),g(0),y(!1),E([])},he=async Ce=>{var ze;c(Ce),u({name:Ce.name,description:Ce.description||"",category_id:Ce.category_id||"",type_id:Ce.type_id||"",publish_date:Ce.publish_date?new Date(Ce.publish_date).toISOString().split("T")[0]:new Date().toISOString().split("T")[0],links:Ce.links&&Ce.links.length>0?Ce.links.map($e=>({id:$e.id,title:$e.title,canva_share_link:$e.canva_share_link,sort_order:$e.sort_order})):[{title:"",canva_share_link:"",sort_order:0}],guides:((ze=Ce.guides)==null?void 0:ze.map($e=>({id:$e.id,name:$e.name,file_url:$e.file_url,file_type:$e.file_type,file_size:$e.file_size,sort_order:$e.sort_order})))||[],video_url:Ce.video_url||""}),S(Ce.preview_image_url||""),m(null);const{data:qe}=await q.from("resource_kit_templates").select("kit_id").eq("template_id",Ce.id);E((qe||[]).map($e=>$e.kit_id)),l(!0)},ue=Ce=>{var ze;const qe=(ze=Ce.target.files)==null?void 0:ze[0];qe&&(b(qe),S(URL.createObjectURL(qe)))},ve=()=>{u({...d,links:[...d.links,{title:"",canva_share_link:"",sort_order:d.links.length}]})},Ee=Ce=>{if(d.links.length<=1)return;const qe=d.links.filter((ze,$e)=>$e!==Ce);u({...d,links:qe})},Se=(Ce,qe,ze)=>{const $e=[...d.links];$e[Ce]={...$e[Ce],[qe]:ze},u({...d,links:$e})},Le=Ce=>{const qe=Ce.target.files;if(!qe)return;const ze=Array.from(qe).map(($e,ct)=>({name:$e.name.replace(/\.[^/.]+$/,""),file_url:"",file_type:$e.type,file_size:$e.size,sort_order:d.guides.length+ct,file:$e}));u({...d,guides:[...d.guides,...ze]}),Ce.target.value=""},Fe=Ce=>{const qe=d.guides.filter((ze,$e)=>$e!==Ce);u({...d,guides:qe})},ke=(Ce,qe)=>{const ze=[...d.guides];ze[Ce]={...ze[Ce],name:qe},u({...d,guides:ze})},Ve=async()=>{if(!h)return null;y(!0),g(0);try{const{data:Ce,error:qe}=await q.functions.invoke("bunny-upload",{body:{action:"create",title:d.name||h.name}});if(qe)throw new Error(qe.message);const{videoId:ze,libraryId:$e}=Ce,{data:ct,error:Xe}=await q.functions.invoke("bunny-upload",{body:{action:"upload-url",videoId:ze}});if(Xe)throw new Error(Xe.message);const it=new XMLHttpRequest;return await new Promise((Ke,nt)=>{it.upload.addEventListener("progress",xt=>{if(xt.lengthComputable){const rt=Math.round(xt.loaded/xt.total*100);g(rt)}}),it.addEventListener("load",()=>{it.status>=200&&it.status<300?Ke():nt(new Error(`Upload failed with status ${it.status}`))}),it.addEventListener("error",()=>nt(new Error("Upload failed"))),it.open("PUT",ct.uploadUrl),it.setRequestHeader("AccessKey",ct.apiKey),it.send(h)}),`https://player.mediadelivery.net/embed/${$e}/${ze}`}catch(Ce){return console.error("Bunny upload error:",Ce),t({title:"Video upload failed",description:Ce instanceof Error?Ce.message:"Unknown error",variant:"destructive"}),null}finally{y(!1)}},je=Ce=>{var ze;const qe=(ze=Ce.target.files)==null?void 0:ze[0];qe&&m(qe),Ce.target.value=""},Ae=async Ce=>{if(Ce.preventDefault(),!d.name.trim()){t({title:"Please enter a template name",variant:"destructive"});return}if(d.links.filter($e=>$e.title.trim()&&$e.canva_share_link.trim()).length===0){t({title:"Please add at least one Canva link",variant:"destructive"});return}let ze=d.video_url;if(h){const $e=await Ve();if(!$e)return;ze=$e}te.mutate({template:d,image:v,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:ze,linkedKitIds:C})};return e.jsx(Vs,{title:"Manage Templates",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(Fm,{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(Ne,{children:[e.jsx(Ct,{className:"pb-2",children:e.jsx(At,{className:"text-sm font-medium text-muted-foreground",children:"Total Templates"})}),e.jsx(Ie,{children:e.jsx("div",{className:"text-2xl font-bold",children:X.length})})]}),e.jsxs(Ne,{children:[e.jsx(Ct,{className:"pb-2",children:e.jsx(At,{className:"text-sm font-medium text-muted-foreground",children:"Categories"})}),e.jsx(Ie,{children:e.jsx("div",{className:"text-2xl font-bold",children:G.length})})]}),e.jsxs(Ne,{children:[e.jsx(Ct,{className:"pb-2",children:e.jsx(At,{className:"text-sm font-medium text-muted-foreground",children:"Template Types"})}),e.jsx(Ie,{children:e.jsx("div",{className:"text-2xl font-bold",children:Y.length})})]})]}),e.jsxs(zs,{open:i,onOpenChange:Ce=>{l(Ce),Ce||_e()},children:[e.jsx(jl,{asChild:!0,children:e.jsxs($,{className:"gap-2",children:[e.jsx(dn,{className:"h-4 w-4"}),"Add Template"]})}),e.jsxs(Os,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(Us,{children:e.jsx(Bs,{children:o?"Edit Template":"Add New Template"})}),e.jsxs("form",{onSubmit:Ae,className:"space-y-6 pt-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"name",children:"Name *"}),e.jsx(pe,{id:"name",value:d.name,onChange:Ce=>u({...d,name:Ce.target.value}),placeholder:"Template name",required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Description"}),e.jsx(Ek,{content:d.description,onChange:Ce=>u({...d,description:Ce}),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(ee,{children:"Canva Links *"}),e.jsxs($,{type:"button",variant:"outline",size:"sm",onClick:ve,className:"gap-1",children:[e.jsx(dn,{className:"h-3 w-3"}),"Add Link"]})]}),e.jsx("div",{className:"space-y-3",children:d.links.map((Ce,qe)=>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(pe,{value:Ce.title,onChange:ze=>Se(qe,"title",ze.target.value),placeholder:"Link title (e.g., Instagram Post, Story)"}),e.jsx(pe,{value:Ce.canva_share_link,onChange:ze=>Se(qe,"canva_share_link",ze.target.value),placeholder:"https://www.canva.com/design/..."})]}),d.links.length>1&&e.jsx($,{type:"button",variant:"ghost",size:"icon",className:"shrink-0 text-muted-foreground hover:text-destructive",onClick:()=>Ee(qe),children:e.jsx(gr,{className:"h-4 w-4"})})]},qe))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Category"}),O?e.jsxs("div",{className:"flex gap-2",children:[e.jsx(pe,{value:I,onChange:Ce=>P(Ce.target.value),placeholder:"New category name",className:"flex-1"}),e.jsx($,{type:"button",size:"sm",onClick:()=>I.trim()&&ie.mutate(I.trim()),disabled:ie.isPending,children:"Add"}),e.jsx($,{type:"button",size:"sm",variant:"ghost",onClick:()=>{U(!1),P("")},children:e.jsx(gr,{className:"h-4 w-4"})})]}):e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(ms,{value:d.category_id,onValueChange:Ce=>u({...d,category_id:Ce}),children:[e.jsx(us,{className:"flex-1",children:e.jsx(fs,{placeholder:"Select category"})}),e.jsx(hs,{children:G.map(Ce=>e.jsx(Ge,{value:Ce.id,children:Ce.name},Ce.id))})]}),e.jsx($,{type:"button",variant:"outline",size:"icon",onClick:()=>U(!0),children:e.jsx(dn,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Template Type"}),W?e.jsxs("div",{className:"flex gap-2",children:[e.jsx(pe,{value:R,onChange:Ce=>D(Ce.target.value),placeholder:"New type name",className:"flex-1"}),e.jsx($,{type:"button",size:"sm",onClick:()=>R.trim()&&ne.mutate(R.trim()),disabled:ne.isPending,children:"Add"}),e.jsx($,{type:"button",size:"sm",variant:"ghost",onClick:()=>{V(!1),D("")},children:e.jsx(gr,{className:"h-4 w-4"})})]}):e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(ms,{value:d.type_id,onValueChange:Ce=>u({...d,type_id:Ce}),children:[e.jsx(us,{className:"flex-1",children:e.jsx(fs,{placeholder:"Select type"})}),e.jsx(hs,{children:Y.map(Ce=>e.jsx(Ge,{value:Ce.id,children:Ce.name},Ce.id))})]}),e.jsx($,{type:"button",variant:"outline",size:"icon",onClick:()=>V(!0),children:e.jsx(dn,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"publish_date",children:"Publish Date"}),e.jsx(pe,{id:"publish_date",type:"date",value:d.publish_date,onChange:Ce=>u({...d,publish_date:Ce.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(ee,{children:"Preview Image"}),e.jsxs("div",{className:"flex items-start gap-4",children:[w?e.jsxs("div",{className:"relative w-32 h-24 rounded-lg overflow-hidden border bg-muted",children:[e.jsx("img",{src:w,alt:"Preview",className:"w-full h-full object-cover"}),e.jsx($,{type:"button",size:"icon",variant:"destructive",className:"absolute top-1 right-1 h-6 w-6",onClick:()=>{b(null),S("")},children:e.jsx(gr,{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(Mc,{className:"h-8 w-8 text-muted-foreground/50"})}),e.jsxs("div",{className:"flex-1",children:[e.jsx(pe,{type:"file",accept:"image/*",onChange:ue,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(ee,{children:"Video (Optional)"}),d.video_url&&!h?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(ua,{className:"h-5 w-5 text-primary shrink-0"}),e.jsx("span",{className:"text-sm flex-1 truncate",children:"Video uploaded"}),e.jsx($,{type:"button",variant:"ghost",size:"sm",onClick:()=>u({...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})})]}):x?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(kt,{className:"h-4 w-4 animate-spin"}),e.jsxs("span",{className:"text-sm",children:["Uploading video... ",f,"%"]})]}),e.jsx(Yi,{value:f,className:"h-2"})]}):h?e.jsxs("div",{className:"flex items-center gap-2 p-3 border rounded-lg bg-muted/30",children:[e.jsx(ua,{className:"h-5 w-5 text-muted-foreground shrink-0"}),e.jsx("span",{className:"text-sm flex-1 truncate",children:h.name}),e.jsxs("span",{className:"text-xs text-muted-foreground shrink-0",children:[(h.size/1024/1024).toFixed(1)," MB"]}),e.jsx($,{type:"button",variant:"ghost",size:"icon",className:"shrink-0 text-muted-foreground hover:text-destructive h-8 w-8",onClick:()=>m(null),children:e.jsx(gr,{className:"h-4 w-4"})})]}):e.jsxs("div",{className:"space-y-2",children:[e.jsxs("label",{className:"cursor-pointer",children:[e.jsx(pe,{type:"file",accept:"video/*",onChange:je,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(ua,{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(ee,{children:"Guide Files (PDFs)"}),e.jsxs("label",{className:"cursor-pointer",children:[e.jsx(pe,{type:"file",accept:".pdf,.doc,.docx",multiple:!0,onChange:Le,className:"hidden"}),e.jsx($,{type:"button",variant:"outline",size:"sm",className:"gap-1",asChild:!0,children:e.jsxs("span",{children:[e.jsx(ni,{className:"h-3 w-3"}),"Add Files"]})})]})]}),d.guides.length>0?e.jsx("div",{className:"space-y-2",children:d.guides.map((Ce,qe)=>e.jsxs("div",{className:"flex gap-2 items-center p-3 border rounded-lg bg-muted/30",children:[e.jsx(Jr,{className:"h-5 w-5 text-muted-foreground shrink-0"}),e.jsx(pe,{value:Ce.name,onChange:ze=>ke(qe,ze.target.value),placeholder:"Guide name",className:"flex-1"}),Ce.file_size&&e.jsxs("span",{className:"text-xs text-muted-foreground shrink-0",children:[(Ce.file_size/1024).toFixed(0)," KB"]}),e.jsx($,{type:"button",variant:"ghost",size:"icon",className:"shrink-0 text-muted-foreground hover:text-destructive h-8 w-8",onClick:()=>Fe(qe),children:e.jsx(gr,{className:"h-4 w-4"})})]},Ce.id||qe))}):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(bmn,{selectedKitIds:C,onChange:E}),e.jsxs("div",{className:"flex justify-end gap-2 pt-4",children:[e.jsx($,{type:"button",variant:"outline",onClick:()=>{l(!1),_e()},children:"Cancel"}),e.jsx($,{type:"submit",disabled:te.isPending,children:te.isPending?"Saving...":o?"Update":"Create"})]})]})]})]})]}),e.jsx(Ne,{children:e.jsx(Ie,{className:"p-0",children:ae?e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:"Loading..."}):X.length===0?e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:"No templates yet. Add your first template!"}):e.jsxs(mi,{children:[e.jsx(fi,{children:e.jsxs(En,{children:[e.jsx(Dt,{children:"Preview"}),e.jsx(Dt,{children:"Name"}),e.jsx(Dt,{children:"Links"}),e.jsx(Dt,{children:"Category"}),e.jsx(Dt,{children:"Type"}),e.jsx(Dt,{children:"Publish Date"}),e.jsx(Dt,{className:"w-[72px] text-center",children:"Featured"}),e.jsx(Dt,{className:"text-right",children:"Actions"})]})}),e.jsx(pi,{children:X.map(Ce=>{var qe,ze,$e,ct,Xe;return e.jsxs(En,{children:[e.jsx(wt,{children:e.jsx("div",{className:"w-16 h-12 rounded overflow-hidden bg-muted",children:Ce.preview_image_url?e.jsx("img",{src:Ce.preview_image_url,alt:Ce.name,className:"w-full h-full object-cover"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center",children:e.jsx(Mc,{className:"h-4 w-4 text-muted-foreground"})})})}),e.jsx(wt,{className:"font-medium",children:Ce.name}),e.jsx(wt,{children:e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsxs(Be,{variant:"secondary",children:[((qe=Ce.links)==null?void 0:qe.length)||0," link",(((ze=Ce.links)==null?void 0:ze.length)||0)!==1?"s":""]}),((($e=Ce.guides)==null?void 0:$e.length)||0)>0&&e.jsxs(Be,{variant:"outline",className:"gap-1",children:[e.jsx(Jr,{className:"h-3 w-3"}),(ct=Ce.guides)==null?void 0:ct.length," guide",(((Xe=Ce.guides)==null?void 0:Xe.length)||0)!==1?"s":""]})]})}),e.jsx(wt,{children:Ce.category?e.jsx(Be,{variant:"secondary",children:Ce.category.name}):e.jsx("span",{className:"text-muted-foreground",children:"-"})}),e.jsx(wt,{children:Ce.type?e.jsx(Be,{variant:"outline",children:Ce.type.name}):e.jsx("span",{className:"text-muted-foreground",children:"-"})}),e.jsx(wt,{className:"text-muted-foreground",children:new Date(Ce.publish_date).toLocaleDateString()}),e.jsx(wt,{className:"text-center",children:e.jsx($,{type:"button",size:"icon",variant:"ghost",className:"mx-auto",title:Ce.is_featured?"Remove from featured templates":"Add to featured templates",onClick:()=>ce.mutate({id:Ce.id,is_featured:!Ce.is_featured}),children:e.jsx(Ja,{className:`h-4 w-4 ${Ce.is_featured?"fill-yellow-400 text-yellow-400":"text-muted-foreground"}`})})}),e.jsx(wt,{className:"text-right",children:e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx($,{size:"icon",variant:"ghost",onClick:()=>he(Ce),children:e.jsx(gi,{className:"h-4 w-4"})}),e.jsx($,{size:"icon",variant:"ghost",className:"text-destructive hover:text-destructive",onClick:async()=>{await fo("Delete this template?")&&J.mutate(Ce.id)},children:e.jsx(Wn,{className:"h-4 w-4"})})]})})]},Ce.id)})})]})})})]})})};function WWt({selectedTemplateIds:s,onChange:t}){const[n,r]=j.useState(""),[a,i]=j.useState(!1),{data:l=[]}=tt({queryKey:["all-canva-templates-picker"],queryFn:async()=>{const{data:h,error:m}=await q.from("canva_templates").select("id, name, preview_image_url").order("name");if(m)throw m;return h}}),o=l.filter(h=>s.includes(h.id)),c=l.filter(h=>!s.includes(h.id)&&h.name.toLowerCase().includes(n.toLowerCase())),d=h=>{t([...s,h])},u=h=>{t(s.filter(m=>m!==h))};return e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ee,{className:"flex items-center gap-2",children:[e.jsx(m2,{className:"h-4 w-4"}),"Linked Templates"]}),o.length>0&&e.jsx("div",{className:"flex flex-wrap gap-1.5",children:o.map(h=>e.jsxs(Be,{variant:"secondary",className:"gap-1 pr-1",children:[h.name,e.jsx("button",{type:"button",onClick:()=>u(h.id),className:"ml-1 rounded-full hover:bg-muted-foreground/20 p-0.5",children:e.jsx(gr,{className:"h-3 w-3"})})]},h.id))}),e.jsxs(Yd,{open:a,onOpenChange:i,children:[e.jsx(Zd,{asChild:!0,children:e.jsxs($,{type:"button",variant:"outline",size:"sm",className:"gap-1",children:[e.jsx(m2,{className:"h-3.5 w-3.5"}),"Add Template"]})}),e.jsxs(Bd,{className:"w-80 p-2",align:"start",children:[e.jsxs("div",{className:"relative mb-2",children:[e.jsx(Kr,{className:"absolute left-2 top-2.5 h-3.5 w-3.5 text-muted-foreground"}),e.jsx(pe,{placeholder:"Search templates...",value:n,onChange:h=>r(h.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:n?"No templates found":"All templates selected"}):c.map(h=>e.jsxs("button",{type:"button",onClick:()=>{d(h.id),r("")},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:[h.preview_image_url?e.jsx("img",{src:h.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(m2,{className:"h-3.5 w-3.5 text-muted-foreground"})}),e.jsx("span",{className:"truncate",children:h.name})]},h.id))})]})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Link templates that agents can use alongside this content."})]})}const wmn=[{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"}],Hwt=new Intl.DateTimeFormat("en-CA",{timeZone:"America/New_York",year:"numeric",month:"2-digit",day:"2-digit"}).format(new Date),Gwt=s=>{const[t,n,r]=s.split(/[-/T]/);return`${Number(n)}/${Number(r)}/${t}`},jmn=()=>{const{user:s}=vs(),[t,n]=gc(),{toast:r}=Bi(),a=Vt(),[i,l]=j.useState(!1),[o,c]=j.useState(null),[d,u]=j.useState({title:"",description:"",video_url:"",video_type:"youtube",duration:"",category_id:"",publish_date:new Date().toISOString().split("T")[0],is_published:!1}),[h,m]=j.useState(null),[f,g]=j.useState(""),[x,y]=j.useState([]),[v,b]=j.useState([]),[w,S]=j.useState([]),[C,E]=j.useState([]),[I,P]=j.useState(""),[R,D]=j.useState(!1),[O,U]=j.useState(null),[W,V]=j.useState(0),[G,Y]=j.useState(!1),[X,ae]=j.useState(null),{data:ie=[]}=tt({queryKey:["academy-categories"],queryFn:async()=>{const{data:Ce,error:qe}=await q.from("academy_categories").select("*").order("sort_order",{ascending:!0});if(qe)throw qe;return Ce}}),{data:ne=[],isLoading:te}=tt({queryKey:["academy-videos-admin"],queryFn:async()=>{const{data:Ce,error:qe}=await q.from("academy_videos").select(` *, category:academy_categories(id, name) `).order("publish_date",{ascending:!1});if(qe)throw qe;const{data:ze,error:$e}=await q.from("academy_resources").select("*").order("sort_order");if($e)throw $e;return Ce.map(Xe=>({...Xe,resources:(ze==null?void 0:ze.filter(it=>it.video_id===Xe.id))||[]}))}});j.useEffect(()=>{const Ce=t.get("edit");if(Ce&&ne.length>0){const qe=ne.find(ze=>ze.id===Ce);qe&&(Se(qe),n({},{replace:!0}))}},[ne,t]);const J=ft({mutationFn:async Ce=>{const{data:qe,error:ze}=await q.from("academy_categories").insert({name:Ce,sort_order:ie.length}).select().single();if(ze)throw ze;return qe},onSuccess:Ce=>{a.invalidateQueries({queryKey:["academy-categories"]}),u({...d,category_id:Ce.id}),P(""),D(!1),r({title:"Category added"})},onError:Ce=>{r({title:"Error adding category",description:Ce.message,variant:"destructive"})}}),ce=ft({mutationFn:async Ce=>{let qe=Ce.existingThumbnailUrl;if(Ce.thumbnail){const ct=Ce.thumbnail.name.split(".").pop(),Xe=`thumbnails/${Date.now()}-${Math.random().toString(36).substring(7)}.${ct}`,{error:it}=await q.storage.from("academy-resources").upload(Xe,Ce.thumbnail);if(it)throw it;const{data:at}=q.storage.from("academy-resources").getPublicUrl(Xe);qe=at.publicUrl}const ze={title:Ce.video.title,description:Ce.video.description||null,video_url:Ce.video.video_url,video_type:Ce.video.video_type,duration:Ce.video.duration||null,thumbnail_url:qe,category_id:Ce.video.category_id||null,publish_date:Ce.video.publish_date?new Date(Ce.video.publish_date).toISOString():new Date().toISOString(),is_published:Ce.video.is_published,created_by:s==null?void 0:s.id};let $e=Ce.videoId;if($e){const{error:ct}=await q.from("academy_videos").update(ze).eq("id",$e);if(ct)throw ct}else{const{data:ct,error:Xe}=await q.from("academy_videos").insert(ze).select().single();if(Xe)throw Xe;$e=ct.id,dmn(Ce.video.title,ct.id)}if(Ce.resourcesToDelete.length>0){const{error:ct}=await q.from("academy_resources").delete().in("id",Ce.resourcesToDelete);if(ct)throw ct}for(let ct=0;ct0){const{error:ct}=await q.from("academy_video_templates").insert(C.map(Xe=>({video_id:$e,template_id:Xe})));if(ct)throw ct}},onSuccess:()=>{a.invalidateQueries({queryKey:["academy-videos-admin"]}),a.invalidateQueries({queryKey:["academy-videos"]}),Ee(),l(!1),r({title:o?"Video updated":"Video created"})},onError:Ce=>{r({title:"Error saving video",description:Ce.message,variant:"destructive"})}}),_e=ft({mutationFn:async Ce=>{const{error:qe}=await q.from("academy_videos").delete().eq("id",Ce);if(qe)throw qe},onSuccess:()=>{a.invalidateQueries({queryKey:["academy-videos-admin"]}),a.invalidateQueries({queryKey:["academy-videos"]}),r({title:"Video deleted"})},onError:Ce=>{r({title:"Error deleting video",description:Ce.message,variant:"destructive"})}}),he=ft({mutationFn:async({id:Ce,is_published:qe})=>{const{error:ze}=await q.from("academy_videos").update({is_published:qe}).eq("id",Ce);if(ze)throw ze},onSuccess:()=>{a.invalidateQueries({queryKey:["academy-videos-admin"]}),a.invalidateQueries({queryKey:["academy-videos"]})},onError:Ce=>{r({title:"Error updating video",description:Ce.message,variant:"destructive"})}}),ue=async Ce=>{try{let qe=Ce.public_slug||null,ze=!!Ce.is_public;if(!qe||!ze){const ct=(Ce.title||"video").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,60)||"video";if(!qe){let it=ct;const{data:at}=await q.from("academy_videos").select("id").eq("public_slug",it).maybeSingle();at&&at.id!==Ce.id&&(it=`${ct}-${Ce.id.slice(0,6)}`),qe=it}const{error:Xe}=await q.from("academy_videos").update({public_slug:qe,is_public:!0}).eq("id",Ce.id);if(Xe)throw Xe;a.invalidateQueries({queryKey:["academy-videos-admin"]})}const $e=`${window.location.origin}/watch/${qe}`;await navigator.clipboard.writeText($e),r({title:"Public link copied",description:$e})}catch(qe){r({title:"Could not copy link",description:qe.message,variant:"destructive"})}},ve=async Ce=>{if(!await fo("Disable the public teaser link for this video?"))return;const{error:qe}=await q.from("academy_videos").update({is_public:!1}).eq("id",Ce.id);if(qe){r({title:"Error",description:qe.message,variant:"destructive"});return}a.invalidateQueries({queryKey:["academy-videos-admin"]}),r({title:"Public link disabled"})},Ee=()=>{u({title:"",description:"",video_url:"",video_type:"bunny_stream",duration:"",category_id:"",publish_date:new Date().toISOString().split("T")[0],is_published:!1}),m(null),g(""),y([]),b([]),S([]),c(null),E([]),P(""),U(null),V(0),Y(!1),ae(null)},Se=async Ce=>{c(Ce),u({title:Ce.title,description:Ce.description||"",video_url:Ce.video_url,video_type:Ce.video_type,duration:Ce.duration||"",category_id:Ce.category_id||"",publish_date:Ce.publish_date?new Date(Ce.publish_date).toISOString().split("T")[0]:new Date().toISOString().split("T")[0],is_published:Ce.is_published}),g(Ce.thumbnail_url||""),b(Ce.resources||[]),y([]),S([]);const{data:qe}=await q.from("academy_video_templates").select("template_id").eq("video_id",Ce.id);E((qe||[]).map(ze=>ze.template_id)),l(!0)},Le=Ce=>{var ze;const qe=(ze=Ce.target.files)==null?void 0:ze[0];qe&&(m(qe),g(URL.createObjectURL(qe)))},Fe=Ce=>{const qe=Ce.target.files;if(qe){const ze=Array.from(qe).map($e=>({file:$e,title:$e.name.replace(/\.[^/.]+$/,"")}));y([...x,...ze])}Ce.target.value=""},ke=Ce=>{y(x.filter((qe,ze)=>ze!==Ce))},Ve=Ce=>{S([...w,Ce]),b(v.filter(qe=>qe.id!==Ce))},je=async()=>{if(!O)return null;Y(!0),V(0);try{const{data:Ce,error:qe}=await q.functions.invoke("bunny-upload",{body:{action:"create",title:d.title||O.name}});if(qe)throw new Error(qe.message);const{videoId:ze,libraryId:$e}=Ce;ae(ze);const{data:ct,error:Xe}=await q.functions.invoke("bunny-upload",{body:{action:"upload-url",videoId:ze}});if(Xe)throw new Error(Xe.message);const it=new XMLHttpRequest;return await new Promise((Ke,nt)=>{it.upload.addEventListener("progress",xt=>{if(xt.lengthComputable){const rt=Math.round(xt.loaded/xt.total*100);V(rt)}}),it.addEventListener("load",()=>{it.status>=200&&it.status<300?Ke():nt(new Error(`Upload failed with status ${it.status}`))}),it.addEventListener("error",()=>nt(new Error("Upload failed"))),it.open("PUT",ct.uploadUrl),it.setRequestHeader("AccessKey",ct.apiKey),it.send(O)}),`https://player.mediadelivery.net/embed/${$e}/${ze}`}catch(Ce){return console.error("Bunny upload error:",Ce),r({title:"Video upload failed",description:Ce instanceof Error?Ce.message:"Unknown error",variant:"destructive"}),null}finally{Y(!1)}},Ae=async Ce=>{if(Ce.preventDefault(),!d.title.trim()){r({title:"Please enter a video title",variant:"destructive"});return}let qe=d.video_url;if(d.video_type==="bunny_stream"&&O&&!o){const ze=await je();if(!ze)return;qe=ze}else if(!d.video_url.trim()&&d.video_type!=="bunny_stream"){r({title:"Please enter a video URL",variant:"destructive"});return}else if(d.video_type==="bunny_stream"&&!O&&!d.video_url&&!o){r({title:"Please select a video file to upload",variant:"destructive"});return}ce.mutate({video:{...d,video_url:qe},thumbnail:h,existingThumbnailUrl:(o==null?void 0:o.thumbnail_url)||null,videoId:o==null?void 0:o.id,newResources:x,resourcesToDelete:w})};return e.jsx(Vs,{title:"Manage Academy",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(Fm,{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 md:grid-cols-4 gap-4",children:[e.jsxs(Ne,{children:[e.jsx(Ct,{className:"pb-2",children:e.jsx(At,{className:"text-sm font-medium text-muted-foreground",children:"Total Videos"})}),e.jsx(Ie,{children:e.jsx("div",{className:"text-2xl font-bold",children:ne.length})})]}),e.jsxs(Ne,{children:[e.jsx(Ct,{className:"pb-2",children:e.jsx(At,{className:"text-sm font-medium text-muted-foreground",children:"Published"})}),e.jsx(Ie,{children:e.jsx("div",{className:"text-2xl font-bold",children:ne.filter(Ce=>Ce.is_published).length})})]}),e.jsxs(Ne,{children:[e.jsx(Ct,{className:"pb-2",children:e.jsx(At,{className:"text-sm font-medium text-muted-foreground",children:"Public Teasers"})}),e.jsx(Ie,{children:e.jsx("div",{className:"text-2xl font-bold",children:ne.filter(Ce=>Ce.is_public).length})})]}),e.jsxs(Ne,{children:[e.jsx(Ct,{className:"pb-2",children:e.jsx(At,{className:"text-sm font-medium text-muted-foreground",children:"Total Public Views"})}),e.jsx(Ie,{children:e.jsx("div",{className:"text-2xl font-bold",children:ne.reduce((Ce,qe)=>Ce+(qe.public_view_count||0),0).toLocaleString()})})]})]}),e.jsxs(zs,{open:i,onOpenChange:Ce=>{l(Ce),Ce||Ee()},children:[e.jsx(jl,{asChild:!0,children:e.jsxs($,{className:"gap-2",children:[e.jsx(dn,{className:"h-4 w-4"}),"Add Video"]})}),e.jsxs(Os,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(Us,{children:e.jsx(Bs,{children:o?"Edit Video":"Add New Video"})}),e.jsxs("form",{onSubmit:Ae,className:"space-y-6 pt-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"title",children:"Title *"}),e.jsx(pe,{id:"title",value:d.title,onChange:Ce=>u({...d,title:Ce.target.value}),placeholder:"Video title",required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Description"}),e.jsx(Ek,{content:d.description,onChange:Ce=>u({...d,description:Ce}),placeholder:"Brief description of the video",minHeight:"120px"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Video Type"}),e.jsxs(ms,{value:d.video_type,onValueChange:Ce=>{u({...d,video_type:Ce,video_url:""}),U(null)},disabled:G,children:[e.jsx(us,{children:e.jsx(fs,{})}),e.jsx(hs,{children:wmn.map(Ce=>e.jsx(Ge,{value:Ce.value,children:Ce.label},Ce.value))})]})]}),d.video_type==="bunny_stream"?e.jsxs("div",{className:"space-y-3",children:[e.jsxs(ee,{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(pe,{type:"file",accept:"video/*",onChange:Ce=>{var ze;const qe=(ze=Ce.target.files)==null?void 0:ze[0];qe&&U(qe)},disabled:G}),O&&e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(ua,{className:"h-4 w-4"}),O.name," (",(O.size/(1024*1024)).toFixed(1)," MB)"]}),G&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(kt,{className:"h-4 w-4 animate-spin"}),e.jsx("span",{className:"text-sm",children:"Uploading to Bunny.net..."})]}),e.jsx(Yi,{value:W,className:"h-2"}),e.jsxs("p",{className:"text-xs text-muted-foreground text-right",children:[W,"%"]})]})]})]}):e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"video_url",children:"Video URL *"}),e.jsx(pe,{id:"video_url",value:d.video_url,onChange:Ce=>u({...d,video_url:Ce.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(ee,{htmlFor:"duration",children:"Duration"}),e.jsx(pe,{id:"duration",value:d.duration,onChange:Ce=>u({...d,duration:Ce.target.value}),placeholder:"e.g., 45:30"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"publish_date",children:"Publish Date (go-live)"}),e.jsx(pe,{id:"publish_date",type:"date",value:d.publish_date,onChange:Ce=>u({...d,publish_date:Ce.target.value})}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Members only see the video on or after this date."})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Category"}),R?e.jsxs("div",{className:"flex gap-2",children:[e.jsx(pe,{value:I,onChange:Ce=>P(Ce.target.value),placeholder:"New category name",className:"flex-1"}),e.jsx($,{type:"button",size:"sm",onClick:()=>I.trim()&&J.mutate(I.trim()),disabled:J.isPending,children:"Add"}),e.jsx($,{type:"button",size:"sm",variant:"ghost",onClick:()=>{D(!1),P("")},children:e.jsx(gr,{className:"h-4 w-4"})})]}):e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(ms,{value:d.category_id,onValueChange:Ce=>u({...d,category_id:Ce}),children:[e.jsx(us,{className:"flex-1",children:e.jsx(fs,{placeholder:"Select category"})}),e.jsx(hs,{children:ie.map(Ce=>e.jsx(Ge,{value:Ce.id,children:Ce.name},Ce.id))})]}),e.jsx($,{type:"button",variant:"outline",size:"sm",onClick:()=>D(!0),children:e.jsx(dn,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Thumbnail Image"}),e.jsxs("div",{className:"flex items-start gap-4",children:[f&&e.jsx("img",{src:f,alt:"Thumbnail preview",className:"w-32 h-20 object-cover rounded-md border"}),e.jsxs("div",{className:"flex-1",children:[e.jsx(pe,{type:"file",accept:"image/*",onChange:Le,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(ee,{children:"Resource Files"}),e.jsx($,{type:"button",variant:"outline",size:"sm",asChild:!0,children:e.jsxs("label",{className:"cursor-pointer gap-1",children:[e.jsx(ni,{className:"h-3 w-3"}),"Add Files",e.jsx("input",{type:"file",multiple:!0,accept:".pdf,.pptx,.ppt,.xlsx,.xls,.docx,.doc,.zip",onChange:Fe,className:"hidden"})]})})]}),(v.length>0||x.length>0)&&e.jsxs("div",{className:"space-y-2 mt-2",children:[v.map(Ce=>e.jsxs("div",{className:"flex items-center gap-2 p-2 border rounded-md bg-muted/30",children:[e.jsx(Jr,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"flex-1 text-sm truncate",children:Ce.title}),e.jsx(Be,{variant:"outline",className:"text-xs",children:Ce.file_type}),e.jsx($,{type:"button",variant:"ghost",size:"sm",onClick:()=>Ve(Ce.id),className:"text-destructive hover:text-destructive",children:e.jsx(gr,{className:"h-4 w-4"})})]},Ce.id)),x.map((Ce,qe)=>e.jsxs("div",{className:"flex items-center gap-2 p-2 border rounded-md bg-muted/30",children:[e.jsx(Jr,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(pe,{value:Ce.title,onChange:ze=>{const $e=[...x];$e[qe].title=ze.target.value,y($e)},className:"flex-1 h-8",placeholder:"Resource title"}),e.jsx(Be,{variant:"secondary",className:"text-xs",children:"New"}),e.jsx($,{type:"button",variant:"ghost",size:"sm",onClick:()=>ke(qe),className:"text-destructive hover:text-destructive",children:e.jsx(gr,{className:"h-4 w-4"})})]},qe))]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Supported: PDF, PowerPoint, Excel, Word, ZIP"})]}),e.jsx(WWt,{selectedTemplateIds:C,onChange:E}),e.jsxs("div",{className:"space-y-2 rounded-lg border p-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Sn,{id:"is_published",checked:d.is_published,onCheckedChange:Ce=>u({...d,is_published:Ce})}),e.jsx(ee,{htmlFor:"is_published",children:"Published"})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:d.is_published?d.publish_date>Hwt?`Scheduled — goes live automatically on ${Gwt(d.publish_date)}.`:"Live now for members.":"Draft — hidden from members until you turn this on."})]}),e.jsxs(Ar,{children:[e.jsx($,{type:"button",variant:"outline",onClick:()=>l(!1),disabled:G,children:"Cancel"}),e.jsx($,{type:"submit",disabled:ce.isPending||G,children:G?e.jsxs(e.Fragment,{children:[e.jsx(kt,{className:"h-4 w-4 mr-2 animate-spin"}),"Uploading..."]}):ce.isPending?"Saving...":o?"Update Video":"Add Video"})]})]})]})]})]}),e.jsx(Ne,{children:e.jsx(Ie,{className:"p-0",children:te?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"})}):ne.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(ua,{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(mi,{children:[e.jsx(fi,{children:e.jsxs(En,{children:[e.jsx(Dt,{children:"Title"}),e.jsx(Dt,{children:"Category"}),e.jsx(Dt,{children:"Duration"}),e.jsx(Dt,{children:"Resources"}),e.jsx(Dt,{children:"Publish Date"}),e.jsx(Dt,{children:"Status"}),e.jsx(Dt,{children:"Public Views"}),e.jsx(Dt,{className:"w-[120px]",children:"Actions"})]})}),e.jsx(pi,{children:ne.map(Ce=>e.jsxs(En,{children:[e.jsx(wt,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[Ce.thumbnail_url?e.jsx("img",{src:Ce.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(ua,{className:"h-4 w-4 text-muted-foreground"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:Ce.title}),e.jsx("p",{className:"text-xs text-muted-foreground capitalize",children:Ce.video_type.replace("_"," ")})]})]})}),e.jsx(wt,{children:Ce.category?e.jsx(Be,{variant:"outline",children:Ce.category.name}):e.jsx("span",{className:"text-muted-foreground text-sm",children:"-"})}),e.jsx(wt,{children:Ce.duration||"-"}),e.jsx(wt,{children:Ce.resources&&Ce.resources.length>0?e.jsxs(Be,{variant:"secondary",children:[Ce.resources.length," file(s)"]}):e.jsx("span",{className:"text-muted-foreground text-sm",children:"-"})}),e.jsx(wt,{children:Gwt(Ce.publish_date)}),e.jsx(wt,{children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Sn,{checked:Ce.is_published,onCheckedChange:qe=>he.mutate({id:Ce.id,is_published:qe})}),Ce.is_published?Ce.publish_date.slice(0,10)>Hwt?e.jsxs(Be,{variant:"outline",className:"gap-1",children:[e.jsx(da,{className:"h-3 w-3"})," Scheduled"]}):e.jsx(Be,{variant:"secondary",children:"Live"}):e.jsx(Be,{variant:"outline",className:"text-muted-foreground",children:"Draft"})]})}),e.jsx(wt,{children:Ce.is_public?e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(Ca,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"text-sm font-medium",children:(Ce.public_view_count||0).toLocaleString()})]}):e.jsx("span",{className:"text-muted-foreground text-sm",children:"-"})}),e.jsx(wt,{children:e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx($,{variant:"ghost",size:"sm",title:Ce.is_public?"Copy public teaser link":"Make public & copy teaser link",onClick:()=>ue(Ce),children:Ce.is_public?e.jsx(Ha,{className:"h-4 w-4 text-primary"}):e.jsx(zd,{className:"h-4 w-4"})}),Ce.is_public&&e.jsx($,{variant:"ghost",size:"sm",title:"Disable public link",onClick:()=>ve(Ce),children:e.jsx(dl,{className:"h-4 w-4 text-emerald-500"})}),e.jsx($,{variant:"ghost",size:"sm",onClick:()=>Se(Ce),children:e.jsx(gi,{className:"h-4 w-4"})}),e.jsx($,{variant:"ghost",size:"sm",onClick:()=>_e.mutate(Ce.id),className:"text-destructive hover:text-destructive",children:e.jsx(Wn,{className:"h-4 w-4"})})]})})]},Ce.id))})]})})})]})})},GZ=s=>s.toLowerCase().trim().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,60),Wwt={public_enabled:!1,public_slug:"",public_headline:"",public_subheadline:"",public_cta_text:"",public_benefits:"",public_hero_image_url:""};function Nmn(){var _e,he,ue;const s=Vt(),[t,n]=gc(),[r,a]=j.useState(!1),[i,l]=j.useState(null),[o,c]=j.useState({name:"",description:"",publish_date:new Date().toISOString().split("T")[0],is_published:!1,...Wwt}),[d,u]=j.useState(null),[h,m]=j.useState(""),[f,g]=j.useState([]),[x,y]=j.useState([]),[v,b]=j.useState([]),[w,S]=j.useState(null),{data:C,isLoading:E}=tt({queryKey:["resource-kits"],queryFn:async()=>{const{data:ve,error:Ee}=await q.from("resource_kits").select("*").order("publish_date",{ascending:!1});if(Ee)throw Ee;return ve}}),{data:I}=tt({queryKey:["resource-kit-files"],queryFn:async()=>{const{data:ve,error:Ee}=await q.from("resource_kit_files").select("*").order("sort_order",{ascending:!0});if(Ee)throw Ee;return ve}}),{data:P}=tt({queryKey:["resource-kit-links"],queryFn:async()=>{const{data:ve,error:Ee}=await q.from("resource_kit_links").select("*").order("sort_order",{ascending:!0});if(Ee)throw Ee;return ve}}),{data:R}=tt({queryKey:["resource-kit-leads"],queryFn:async()=>{const{data:ve,error:Ee}=await q.from("resource_kit_leads").select("id, kit_id, full_name, email, brokerage, created_at").order("created_at",{ascending:!1}).limit(500);if(Ee)throw Ee;return ve}});j.useEffect(()=>{const ve=t.get("edit");if(ve&&C&&C.length>0&&I&&P){const Ee=C.find(Se=>Se.id===ve);Ee&&(O(Ee),n({},{replace:!0}))}},[C,I,P,t]);const D=()=>{c({name:"",description:"",publish_date:new Date().toISOString().split("T")[0],is_published:!1,...Wwt}),u(null),m(""),g([]),y([]),b([]),l(null)},O=async ve=>{l(ve),c({name:ve.name,description:ve.description||"",publish_date:ve.publish_date.split("T")[0],is_published:ve.is_published,public_enabled:!!ve.public_enabled,public_slug:ve.public_slug||"",public_headline:ve.public_headline||"",public_subheadline:ve.public_subheadline||"",public_cta_text:ve.public_cta_text||"",public_benefits:Array.isArray(ve.public_benefits)?ve.public_benefits.join(` `):"",public_hero_image_url:ve.public_hero_image_url||""}),m(ve.featured_image_url||"");const Ee=(I==null?void 0:I.filter(Fe=>Fe.kit_id===ve.id))||[];g(Ee.map(Fe=>({id:Fe.id,name:Fe.name,file_url:Fe.file_url,file_type:Fe.file_type,file_size:Fe.file_size,sort_order:Fe.sort_order})));const Se=(P==null?void 0:P.filter(Fe=>Fe.kit_id===ve.id))||[];y(Se.map(Fe=>({id:Fe.id,title:Fe.title,canva_share_link:Fe.canva_share_link,sort_order:Fe.sort_order})));const{data:Le}=await q.from("resource_kit_templates").select("template_id").eq("kit_id",ve.id);b((Le||[]).map(Fe=>Fe.template_id)),a(!0)},U=ve=>{var Se;const Ee=(Se=ve.target.files)==null?void 0:Se[0];Ee&&(u(Ee),m(URL.createObjectURL(Ee)))},W=()=>{g([...f,{name:"",file_url:"",sort_order:f.length}])},V=ve=>{g(f.filter((Ee,Se)=>Se!==ve))},G=(ve,Ee,Se)=>{const Le=[...f];Le[ve]={...Le[ve],[Ee]:Se},g(Le)},Y=()=>{y([...x,{title:"",canva_share_link:"",sort_order:x.length}])},X=ve=>{y(x.filter((Ee,Se)=>Se!==ve))},ae=(ve,Ee,Se)=>{const Le=[...x];Le[ve]={...Le[ve],[Ee]:Se},y(Le)},ie=(ve,Ee)=>{var Le;const Se=(Le=Ee.target.files)==null?void 0:Le[0];if(Se){const Fe=[...f],ke=Se.name.replace(/\.[^/.]+$/,"");Fe[ve]={...Fe[ve],file:Se,file_type:Se.type,file_size:Se.size,name:Fe[ve].name||ke},g(Fe)}},ne=ft({mutationFn:async()=>{let ve=(i==null?void 0:i.featured_image_url)||null;if(d){const Ve=d.name.split(".").pop(),je=`${Date.now()}.${Ve}`,{error:Ae}=await q.storage.from("resource-kits").upload(`featured/${je}`,d);if(Ae)throw Ae;const{data:Ce}=q.storage.from("resource-kits").getPublicUrl(`featured/${je}`);ve=Ce.publicUrl}const Ee=o.public_enabled?o.public_slug?GZ(o.public_slug):GZ(o.name):o.public_slug?GZ(o.public_slug):null,Se={name:o.name,description:o.description||null,featured_image_url:ve,publish_date:o.publish_date,is_published:o.is_published,public_enabled:o.public_enabled,public_slug:Ee||null,public_headline:o.public_headline||null,public_subheadline:o.public_subheadline||null,public_cta_text:o.public_cta_text||null,public_benefits:o.public_benefits.split(` `).map(Ve=>Ve.trim()).filter(Boolean),public_hero_image_url:o.public_hero_image_url||null};let Le;const Fe=!i,ke=(i==null?void 0:i.is_published)||!1;if(i){const{error:Ve}=await q.from("resource_kits").update(Se).eq("id",i.id);if(Ve)throw Ve;Le=i.id;const je=(I==null?void 0:I.filter(ct=>ct.kit_id===i.id).map(ct=>ct.id))||[],Ae=f.filter(ct=>ct.id).map(ct=>ct.id),Ce=je.filter(ct=>!Ae.includes(ct));Ce.length>0&&await q.from("resource_kit_files").delete().in("id",Ce);const qe=(P==null?void 0:P.filter(ct=>ct.kit_id===i.id).map(ct=>ct.id))||[],ze=x.filter(ct=>ct.id).map(ct=>ct.id),$e=qe.filter(ct=>!ze.includes(ct));$e.length>0&&await q.from("resource_kit_links").delete().in("id",$e)}else{const{data:Ve,error:je}=await q.from("resource_kits").insert(Se).select().single();if(je)throw je;Le=Ve.id}for(let Ve=0;Ve0){const{error:Ve}=await q.from("resource_kit_templates").insert(v.map(je=>({kit_id:Le,template_id:je})));if(Ve)throw Ve}return{kitId:Le,kitName:o.name,isNewKit:Fe,wasPublished:ke,isPublished:o.is_published}},onSuccess:ve=>{s.invalidateQueries({queryKey:["resource-kits"]}),s.invalidateQueries({queryKey:["resource-kit-files"]}),s.invalidateQueries({queryKey:["resource-kit-links"]}),re.success(i?"Resource kit updated":"Resource kit created"),ve.isPublished&&(ve.isNewKit||!ve.wasPublished)&&hmn(ve.kitName,ve.kitId),a(!1),D()},onError:ve=>{re.error("Failed to save resource kit: "+ve.message)}}),te=ft({mutationFn:async ve=>{const{error:Ee}=await q.from("resource_kits").delete().eq("id",ve);if(Ee)throw Ee},onSuccess:()=>{s.invalidateQueries({queryKey:["resource-kits"]}),s.invalidateQueries({queryKey:["resource-kit-files"]}),re.success("Resource kit deleted")},onError:ve=>{re.error("Failed to delete: "+ve.message)}}),J=ve=>{if(ve.preventDefault(),!o.name){re.error("Please enter a name");return}ne.mutate()},ce=ve=>(I==null?void 0:I.filter(Ee=>Ee.kit_id===ve).length)||0;return e.jsx(Vs,{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(Ne,{children:[e.jsx(Ct,{className:"pb-2",children:e.jsx(At,{className:"text-sm font-medium text-muted-foreground",children:"Total Kits"})}),e.jsx(Ie,{children:e.jsx("div",{className:"text-2xl font-bold",children:(C==null?void 0:C.length)||0})})]}),e.jsxs(Ne,{children:[e.jsx(Ct,{className:"pb-2",children:e.jsx(At,{className:"text-sm font-medium text-muted-foreground",children:"Published"})}),e.jsx(Ie,{children:e.jsx("div",{className:"text-2xl font-bold",children:(C==null?void 0:C.filter(ve=>ve.is_published).length)||0})})]})]}),e.jsxs($,{onClick:()=>{D(),a(!0)},children:[e.jsx(dn,{className:"h-4 w-4 mr-2"}),"Add Resource Kit"]})]}),e.jsx(Ne,{children:e.jsx(Ie,{className:"p-0",children:e.jsxs(mi,{children:[e.jsx(fi,{children:e.jsxs(En,{children:[e.jsx(Dt,{children:"Name"}),e.jsx(Dt,{children:"Files"}),e.jsx(Dt,{children:"Publish Date"}),e.jsx(Dt,{children:"Status"}),e.jsx(Dt,{className:"text-right",children:"Actions"})]})}),e.jsx(pi,{children:E?e.jsx(En,{children:e.jsx(wt,{colSpan:5,className:"text-center py-8",children:"Loading..."})}):(C==null?void 0:C.length)===0?e.jsx(En,{children:e.jsx(wt,{colSpan:5,className:"text-center py-8 text-muted-foreground",children:"No resource kits yet. Create your first one!"})}):C==null?void 0:C.map(ve=>e.jsxs(En,{children:[e.jsx(wt,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[ve.featured_image_url?e.jsx("img",{src:ve.featured_image_url,alt:ve.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(vm,{className:"h-5 w-5 text-muted-foreground"})}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:ve.name}),ve.description&&e.jsx("div",{className:"text-sm text-muted-foreground line-clamp-1",children:ve.description})]})]})}),e.jsx(wt,{children:e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(Jr,{className:"h-4 w-4 text-muted-foreground"}),ce(ve.id)]})}),e.jsx(wt,{children:en(new Date(ve.publish_date),"MMM d, yyyy")}),e.jsx(wt,{children:e.jsx("span",{className:`inline-flex items-center px-2 py-1 rounded-full text-xs font-medium ${ve.is_published?"bg-green-100 text-green-800":"bg-yellow-100 text-yellow-800"}`,children:ve.is_published?"Published":"Draft"})}),e.jsx(wt,{className:"text-right",children:e.jsxs("div",{className:"flex justify-end gap-2",children:[ve.public_enabled&&ve.public_slug&&e.jsx($,{variant:"ghost",size:"icon",title:"Copy public landing page link",onClick:()=>{navigator.clipboard.writeText(`${window.location.origin}/resources/${ve.public_slug}`),re.success("Public link copied")},children:e.jsx(dl,{className:"h-4 w-4 text-emerald-600"})}),e.jsx($,{variant:"ghost",size:"icon",onClick:()=>{const Ee=(I==null?void 0:I.filter(Le=>Le.kit_id===ve.id))||[],Se=(P==null?void 0:P.filter(Le=>Le.kit_id===ve.id))||[];S({...ve,files:Ee,links:Se})},children:e.jsx(Ca,{className:"h-4 w-4"})}),e.jsx($,{variant:"ghost",size:"icon",onClick:()=>O(ve),children:e.jsx(gi,{className:"h-4 w-4"})}),e.jsx($,{variant:"ghost",size:"icon",onClick:async()=>{await fo("Delete this resource kit?")&&te.mutate(ve.id)},children:e.jsx(Wn,{className:"h-4 w-4 text-destructive"})})]})})]},ve.id))})]})})}),e.jsxs(Ne,{className:"mt-6",children:[e.jsx(Ct,{children:e.jsxs(At,{className:"flex items-center gap-2",children:[e.jsx(Zn,{className:"h-5 w-5"}),"Public Resource Leads",e.jsxs("span",{className:"text-sm font-normal text-muted-foreground",children:["(",(R==null?void 0:R.length)||0,")"]})]})}),e.jsx(Ie,{children:!R||R.length===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:"No leads yet. Turn on a public landing page for a kit and share the link."}):e.jsxs(mi,{children:[e.jsx(fi,{children:e.jsxs(En,{children:[e.jsx(Dt,{children:"Agent"}),e.jsx(Dt,{children:"Email"}),e.jsx(Dt,{children:"Brokerage"}),e.jsx(Dt,{children:"Resource"}),e.jsx(Dt,{children:"Captured"})]})}),e.jsx(pi,{children:R.map(ve=>{var Ee;return e.jsxs(En,{children:[e.jsx(wt,{className:"font-medium",children:ve.full_name}),e.jsx(wt,{children:ve.email}),e.jsx(wt,{children:ve.brokerage||"—"}),e.jsx(wt,{children:((Ee=C==null?void 0:C.find(Se=>Se.id===ve.kit_id))==null?void 0:Ee.name)||"—"}),e.jsx(wt,{children:en(new Date(ve.created_at),"MMM d, yyyy")})]},ve.id)})})]})})]}),e.jsx(zs,{open:r,onOpenChange:a,children:e.jsxs(Os,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(Us,{children:e.jsx(Bs,{children:i?"Edit Resource Kit":"Add Resource Kit"})}),e.jsxs("form",{onSubmit:J,className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Featured Image"}),e.jsxs("div",{className:"flex items-center gap-4",children:[h?e.jsx("img",{src:h,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(vm,{className:"h-8 w-8 text-muted-foreground"})}),e.jsx(pe,{type:"file",accept:"image/*",onChange:U})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"name",children:"Name *"}),e.jsx(pe,{id:"name",value:o.name,onChange:ve=>c({...o,name:ve.target.value}),placeholder:"Resource Kit Name"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Description"}),e.jsx(Ek,{content:o.description,onChange:ve=>c({...o,description:ve}),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(ee,{htmlFor:"publish_date",children:"Publish Date"}),e.jsx(pe,{id:"publish_date",type:"date",value:o.publish_date,onChange:ve=>c({...o,publish_date:ve.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Published"}),e.jsxs("div",{className:"flex items-center space-x-2 pt-2",children:[e.jsx(Sn,{checked:o.is_published,onCheckedChange:ve=>c({...o,is_published:ve})}),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 rounded-xl border p-4 bg-muted/30",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(ee,{className:"text-base",children:"Public Landing Page"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Share this resource publicly and capture agent name, email and brokerage as leads."})]}),e.jsx(Sn,{checked:o.public_enabled,onCheckedChange:ve=>c({...o,public_enabled:ve,public_slug:o.public_slug||GZ(o.name)})})]}),o.public_enabled&&e.jsxs("div",{className:"space-y-3 pt-1",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Public link"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx("div",{className:"flex items-center rounded-md border bg-background px-2 text-sm text-muted-foreground",children:"/resources/"}),e.jsx(pe,{value:o.public_slug,onChange:ve=>c({...o,public_slug:ve.target.value}),placeholder:"listing-checklist"}),e.jsxs($,{type:"button",variant:"outline",onClick:()=>{const ve=GZ(o.public_slug||o.name);navigator.clipboard.writeText(`${window.location.origin}/resources/${ve}`),re.success("Public link copied")},children:[e.jsx(Ad,{className:"h-4 w-4 mr-1"})," Copy"]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Headline"}),e.jsx(pe,{value:o.public_headline,onChange:ve=>c({...o,public_headline:ve.target.value}),placeholder:o.name||"The Ultimate Listing Checklist"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Subheadline"}),e.jsx(pe,{value:o.public_subheadline,onChange:ve=>c({...o,public_subheadline:ve.target.value}),placeholder:"Everything top agents do before a listing goes live."})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Button text"}),e.jsx(pe,{value:o.public_cta_text,onChange:ve=>c({...o,public_cta_text:ve.target.value}),placeholder:"Get Instant Access"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Hero image URL (optional)"}),e.jsx(pe,{value:o.public_hero_image_url,onChange:ve=>c({...o,public_hero_image_url:ve.target.value}),placeholder:"Defaults to featured image"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Benefit bullets (one per line)"}),e.jsx("textarea",{value:o.public_benefits,onChange:ve=>c({...o,public_benefits:ve.target.value}),rows:4,placeholder:`Save hours on every listing Proven scripts included Printable + editable`,className:"w-full rounded-md border bg-background px-3 py-2 text-sm"})]})]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx(ee,{children:"Resource Files"}),e.jsxs($,{type:"button",variant:"outline",size:"sm",onClick:W,children:[e.jsx(dn,{className:"h-4 w-4 mr-1"}),"Add File"]})]}),f.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:f.map((ve,Ee)=>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 ",Ee+1]}),e.jsx($,{type:"button",variant:"ghost",size:"icon",className:"h-6 w-6",onClick:()=>V(Ee),children:e.jsx(gr,{className:"h-4 w-4"})})]}),e.jsx(pe,{placeholder:"File name (e.g., Getting Started Guide)",value:ve.name,onChange:Se=>G(Ee,"name",Se.target.value)}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(pe,{type:"file",onChange:Se=>ie(Ee,Se),className:"flex-1"}),ve.file_url&&!ve.file&&e.jsx("a",{href:ve.file_url,target:"_blank",rel:"noopener noreferrer",className:"text-sm text-primary hover:underline whitespace-nowrap",children:"Current file"}),ve.file&&e.jsx("span",{className:"text-sm text-green-600 whitespace-nowrap",children:"New file selected"})]})]},Ee))})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx(ee,{children:"Canva Links"}),e.jsxs($,{type:"button",variant:"outline",size:"sm",onClick:Y,children:[e.jsx(dn,{className:"h-4 w-4 mr-1"}),"Add Canva Link"]})]}),x.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:x.map((ve,Ee)=>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 ",Ee+1]}),e.jsx($,{type:"button",variant:"ghost",size:"icon",className:"h-6 w-6",onClick:()=>X(Ee),children:e.jsx(gr,{className:"h-4 w-4"})})]}),e.jsx(pe,{placeholder:"Link title (e.g., Social Media Post Template)",value:ve.title,onChange:Se=>ae(Ee,"title",Se.target.value)}),e.jsx(pe,{placeholder:"Canva share link (e.g., https://www.canva.com/design/...)",value:ve.canva_share_link,onChange:Se=>ae(Ee,"canva_share_link",Se.target.value)})]},Ee))})]}),e.jsx(WWt,{selectedTemplateIds:v,onChange:b}),e.jsxs("div",{className:"flex justify-end gap-2 pt-4",children:[e.jsx($,{type:"button",variant:"outline",onClick:()=>a(!1),children:"Cancel"}),e.jsx($,{type:"submit",disabled:ne.isPending,children:ne.isPending?"Saving...":i?"Update":"Create"})]})]})]})}),e.jsx(zs,{open:!!w,onOpenChange:()=>S(null),children:e.jsxs(Os,{className:"max-w-lg",children:[e.jsx(Us,{children:e.jsx(Bs,{children:w==null?void 0:w.name})}),e.jsxs("div",{className:"space-y-4",children:[(w==null?void 0:w.featured_image_url)&&e.jsx("img",{src:w.featured_image_url,alt:w.name,className:"w-full h-48 object-cover rounded-lg"}),(w==null?void 0:w.description)&&e.jsx("p",{className:"text-muted-foreground",children:w.description}),e.jsxs("div",{children:[e.jsxs("h4",{className:"font-medium mb-2",children:["Resource Files (",((_e=w==null?void 0:w.files)==null?void 0:_e.length)||0,")"]}),((he=w==null?void 0:w.files)==null?void 0:he.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:(ue=w==null?void 0:w.files)==null?void 0:ue.map(ve=>e.jsxs("a",{href:ve.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(Jr,{className:"h-4 w-4 text-primary"}),e.jsx("span",{className:"text-sm",children:ve.name})]},ve.id))})]}),(w==null?void 0:w.links)&&w.links.length>0&&e.jsxs("div",{children:[e.jsxs("h4",{className:"font-medium mb-2",children:["Canva Links (",w.links.length,")"]}),e.jsx("div",{className:"space-y-2",children:w.links.map(ve=>e.jsxs("a",{href:ve.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(Ad,{className:"h-4 w-4 text-primary"}),e.jsx("span",{className:"text-sm",children:ve.title})]},ve.id))})]})]})]})})]})})}const kmn=()=>{const{user:s}=vs(),{toast:t}=Bi(),n=Vt(),[r,a]=j.useState(!1),[i,l]=j.useState(null),[o,c]=j.useState({title:"",description:"",publish_date:new Date().toISOString().split("T")[0],is_published:!1,links:[{title:"",canva_share_link:"",sort_order:0}]}),[d,u]=j.useState(null),[h,m]=j.useState(""),{data:f=[],isLoading:g}=tt({queryKey:["social-swag-admin"],queryFn:async()=>{const{data:P,error:R}=await q.from("social_swag").select("*").order("publish_date",{ascending:!1});if(R)throw R;const{data:D,error:O}=await q.from("social_swag_links").select("*").order("sort_order");if(O)throw O;return P.map(W=>({...W,links:(D==null?void 0:D.filter(V=>V.swag_id===W.id))||[]}))}}),x=ft({mutationFn:async P=>{let R=P.existingImageUrl;if(P.image){const G=P.image.name.split(".").pop(),Y=`${Date.now()}-${Math.random().toString(36).substring(7)}.${G}`,{error:X}=await q.storage.from("template-previews").upload(Y,P.image);if(X)throw X;const{data:ae}=q.storage.from("template-previews").getPublicUrl(Y);R=ae.publicUrl}const D={title:P.item.title,description:P.item.description||null,preview_image_url:R,publish_date:P.item.publish_date?new Date(P.item.publish_date).toISOString():new Date().toISOString(),is_published:P.item.is_published,created_by:s==null?void 0:s.id};let O=P.itemId;const U=!O,W=(i==null?void 0:i.is_published)||!1;if(O){const{error:G}=await q.from("social_swag").update(D).eq("id",O);if(G)throw G;await q.from("social_swag_links").delete().eq("swag_id",O)}else{const{data:G,error:Y}=await q.from("social_swag").insert(D).select().single();if(Y)throw Y;O=G.id}const V=P.item.links.filter(G=>G.title.trim()&&G.canva_share_link.trim());if(V.length>0){const G=V.map((X,ae)=>({swag_id:O,title:X.title.trim(),canva_share_link:X.canva_share_link.trim(),sort_order:ae})),{error:Y}=await q.from("social_swag_links").insert(G);if(Y)throw Y}return{itemId:O,itemTitle:P.item.title,isNewItem:U,wasPublished:W,isPublished:P.item.is_published}},onSuccess:P=>{n.invalidateQueries({queryKey:["social-swag-admin"]}),n.invalidateQueries({queryKey:["social-swag"]}),t({title:i?"Item updated":"Item created"}),P.isPublished&&(P.isNewItem||!P.wasPublished)&&KWe(P.itemTitle,P.itemId),a(!1),v()},onError:P=>{t({title:"Error saving item",description:P.message,variant:"destructive"})}}),y=ft({mutationFn:async P=>{const{error:R}=await q.from("social_swag").delete().eq("id",P);if(R)throw R},onSuccess:()=>{n.invalidateQueries({queryKey:["social-swag-admin"]}),n.invalidateQueries({queryKey:["social-swag"]}),t({title:"Item deleted"})},onError:P=>{t({title:"Error deleting item",description:P.message,variant:"destructive"})}}),v=()=>{c({title:"",description:"",publish_date:new Date().toISOString().split("T")[0],is_published:!1,links:[{title:"",canva_share_link:"",sort_order:0}]}),u(null),m(""),l(null)},b=P=>{l(P),c({title:P.title,description:P.description||"",publish_date:P.publish_date?new Date(P.publish_date).toISOString().split("T")[0]:new Date().toISOString().split("T")[0],is_published:P.is_published,links:P.links&&P.links.length>0?P.links.map(R=>({id:R.id,title:R.title,canva_share_link:R.canva_share_link,sort_order:R.sort_order})):[{title:"",canva_share_link:"",sort_order:0}]}),m(P.preview_image_url||""),a(!0)},w=P=>{var D;const R=(D=P.target.files)==null?void 0:D[0];R&&(u(R),m(URL.createObjectURL(R)))},S=()=>{c({...o,links:[...o.links,{title:"",canva_share_link:"",sort_order:o.links.length}]})},C=P=>{if(o.links.length<=1)return;const R=o.links.filter((D,O)=>O!==P);c({...o,links:R})},E=(P,R,D)=>{const O=[...o.links];O[P]={...O[P],[R]:D},c({...o,links:O})},I=P=>{if(P.preventDefault(),!o.title.trim()){t({title:"Title is required",variant:"destructive"});return}x.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(Vs,{title:"Manage Social Swag",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(Fm,{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(Ne,{children:[e.jsx(Ct,{className:"pb-2",children:e.jsx(At,{className:"text-sm font-medium text-muted-foreground",children:"Total Items"})}),e.jsx(Ie,{children:e.jsx("div",{className:"text-2xl font-bold",children:f.length})})]}),e.jsxs(Ne,{children:[e.jsx(Ct,{className:"pb-2",children:e.jsx(At,{className:"text-sm font-medium text-muted-foreground",children:"Published"})}),e.jsx(Ie,{children:e.jsx("div",{className:"text-2xl font-bold",children:f.filter(P=>P.is_published).length})})]})]}),e.jsxs(zs,{open:r,onOpenChange:P=>{a(P),P||v()},children:[e.jsx(jl,{asChild:!0,children:e.jsxs($,{className:"gap-2",children:[e.jsx(dn,{className:"h-4 w-4"}),"Add Item"]})}),e.jsxs(Os,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(Us,{children:e.jsx(Bs,{children:i?"Edit Item":"Add New Item"})}),e.jsxs("form",{onSubmit:I,className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"title",children:"Title *"}),e.jsx(pe,{id:"title",value:o.title,onChange:P=>c({...o,title:P.target.value}),placeholder:"Enter title"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Description"}),e.jsx(Ek,{content:o.description,onChange:P=>c({...o,description:P}),placeholder:"Enter description",minHeight:"120px"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"publish_date",children:"Publish Date"}),e.jsx(pe,{id:"publish_date",type:"date",value:o.publish_date,onChange:P=>c({...o,publish_date:P.target.value})})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Sn,{id:"is_published",checked:o.is_published,onCheckedChange:P=>c({...o,is_published:P})}),e.jsx(ee,{htmlFor:"is_published",children:"Published"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Preview Image"}),h?e.jsxs("div",{className:"relative",children:[e.jsx("img",{src:h,alt:"Preview",className:"w-full max-h-48 object-contain rounded-lg border"}),e.jsx($,{type:"button",variant:"destructive",size:"icon",className:"absolute top-2 right-2 h-6 w-6",onClick:()=>{u(null),m("")},children:e.jsx(gr,{className:"h-3 w-3"})})]}):e.jsxs("div",{className:"border-2 border-dashed rounded-lg p-4 text-center",children:[e.jsx(Mc,{className:"h-8 w-8 mx-auto text-muted-foreground mb-2"}),e.jsx(pe,{type:"file",accept:"image/*",onChange:w,className:"cursor-pointer"})]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(ee,{children:"Canva Links"}),e.jsxs($,{type:"button",variant:"outline",size:"sm",onClick:S,children:[e.jsx(dn,{className:"h-3 w-3 mr-1"}),"Add Link"]})]}),o.links.map((P,R)=>e.jsx(Ne,{children:e.jsxs(Ie,{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 ",R+1]}),o.links.length>1&&e.jsx($,{type:"button",variant:"ghost",size:"icon",className:"h-6 w-6 ml-auto",onClick:()=>C(R),children:e.jsx(gr,{className:"h-3 w-3"})})]}),e.jsx(pe,{placeholder:"Link title (e.g., Instagram Post)",value:P.title,onChange:D=>E(R,"title",D.target.value)}),e.jsx(pe,{placeholder:"Canva share link",value:P.canva_share_link,onChange:D=>E(R,"canva_share_link",D.target.value)})]})},R))]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-4",children:[e.jsx($,{type:"button",variant:"outline",onClick:()=>a(!1),children:"Cancel"}),e.jsx($,{type:"submit",disabled:x.isPending,children:x.isPending?"Saving...":i?"Update":"Create"})]})]})]})]})]}),e.jsx(Ne,{children:e.jsx(Ie,{className:"p-0",children:g?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"})}):f.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(mi,{children:[e.jsx(fi,{children:e.jsxs(En,{children:[e.jsx(Dt,{className:"w-16",children:"Preview"}),e.jsx(Dt,{children:"Title"}),e.jsx(Dt,{children:"Links"}),e.jsx(Dt,{children:"Publish Date"}),e.jsx(Dt,{children:"Status"}),e.jsx(Dt,{className:"text-right",children:"Actions"})]})}),e.jsx(pi,{children:f.map(P=>{var R;return e.jsxs(En,{children:[e.jsx(wt,{children:P.preview_image_url?e.jsx("img",{src:P.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(Mc,{className:"h-4 w-4 text-muted-foreground"})})}),e.jsx(wt,{className:"font-medium",children:P.title}),e.jsxs(wt,{children:[((R=P.links)==null?void 0:R.length)||0," links"]}),e.jsx(wt,{children:new Date(P.publish_date).toLocaleDateString()}),e.jsx(wt,{children:e.jsx(Be,{variant:P.is_published?"default":"secondary",children:P.is_published?"Published":"Draft"})}),e.jsx(wt,{className:"text-right",children:e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx($,{variant:"ghost",size:"icon",onClick:()=>window.open(`/social-swag/${P.id}`,"_blank"),children:e.jsx(Ca,{className:"h-4 w-4"})}),e.jsx($,{variant:"ghost",size:"icon",onClick:()=>b(P),children:e.jsx(gi,{className:"h-4 w-4"})}),e.jsx($,{variant:"ghost",size:"icon",onClick:async()=>{await fo("Are you sure you want to delete this item?")&&y.mutate(P.id)},children:e.jsx(Wn,{className:"h-4 w-4"})})]})})]},P.id)})})]})})})]})})};function Smn({item:s,onEdit:t,onDelete:n,onDateChange:r}){const{attributes:a,listeners:i,setNodeRef:l,transform:o,transition:c,isDragging:d}=_6e({id:s.id}),u={transform:RL.Transform.toString(o),transition:c,opacity:d?.5:1,zIndex:d?10:void 0};return e.jsx("div",{ref:l,style:u,children:e.jsxs(Ne,{className:"overflow-hidden",children:[e.jsxs("div",{...a,...i,className:"flex items-center justify-center gap-1 py-1.5 bg-muted hover:bg-muted/80 cursor-grab active:cursor-grabbing border-b select-none",title:"Drag to reorder",children:[e.jsx(Ug,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"text-[10px] text-muted-foreground font-medium",children:"Drag to reorder"})]}),e.jsxs("div",{className:"relative aspect-[4/5]",children:[e.jsx("img",{src:s.image_url,alt:"Social swag",className:"w-full h-full object-cover",loading:"lazy",decoding:"async"}),e.jsxs("div",{className:"absolute top-2 right-2 flex gap-1",children:[e.jsx($,{variant:"secondary",size:"icon",className:"h-7 w-7 bg-black/50 hover:bg-black/70 border-0 text-white",onClick:()=>t(s),children:e.jsx(gi,{className:"h-3.5 w-3.5"})}),e.jsx($,{variant:"destructive",size:"icon",className:"h-7 w-7",onClick:()=>n(s),children:e.jsx(Wn,{className:"h-3.5 w-3.5"})})]}),s.post_date&&e.jsx("div",{className:"absolute bottom-2 left-2",children:e.jsxs(Be,{className:"bg-primary/90 text-primary-foreground text-[10px] gap-1 backdrop-blur-sm px-1.5 py-0.5",children:[e.jsx(Ta,{className:"h-2.5 w-2.5"}),en(new Date(s.post_date+"T00:00:00"),"MMM d")]})})]}),e.jsxs(Ie,{className:"p-3 space-y-2",children:[e.jsx("p",{className:"text-xs text-muted-foreground line-clamp-3",children:s.caption}),e.jsxs(Yd,{children:[e.jsx(Zd,{asChild:!0,children:e.jsxs($,{variant:"outline",size:"sm",className:Pt("w-full h-7 text-[11px] gap-1 justify-start font-normal",!s.post_date&&"text-muted-foreground"),children:[e.jsx(Ta,{className:"h-3 w-3"}),s.post_date?en(new Date(s.post_date+"T00:00:00"),"MMM d, yyyy"):"Set post date"]})}),e.jsxs(Bd,{className:"w-auto p-0",align:"start",children:[e.jsx(D2,{mode:"single",selected:s.post_date?new Date(s.post_date+"T00:00:00"):void 0,onSelect:h=>r(s.id,h?en(h,"yyyy-MM-dd"):null),className:"p-3 pointer-events-auto"}),s.post_date&&e.jsx("div",{className:"p-2 border-t",children:e.jsx($,{variant:"ghost",size:"sm",className:"w-full text-xs text-muted-foreground",onClick:()=>r(s.id,null),children:"Clear date"})})]})]})]})]})})}const Cmn=()=>{const s=Vt(),[t,n]=j.useState("all"),[r,a]=j.useState(!1),[i,l]=j.useState(en(new Date,"yyyy-MM")),[o,c]=j.useState([]),[d,u]=j.useState(!1),[h,m]=j.useState(null),[f,g]=j.useState(null),[x,y]=j.useState(""),[v,b]=j.useState(null),[w,S]=j.useState(!1),[C,E]=j.useState(!1),[I,P]=j.useState(en(new Date,"yyyy-MM")),[R,D]=j.useState(null),[O,U]=j.useState(""),[W,V]=j.useState(""),[G,Y]=j.useState(""),[X,ae]=j.useState(!1),ie=h6e(IG(fK,{activationConstraint:{distance:5}}),IG(p6e,{coordinateGetter:xUt})),{data:ne=[],isLoading:te}=tt({queryKey:["admin-social-swag-2"],queryFn:async()=>{const{data:at,error:Ke}=await q.from("social_swag_2").select("*").order("month",{ascending:!1}).order("sort_order");if(Ke)throw Ke;return at}}),{data:J=[]}=tt({queryKey:["admin-social-swag-2-months"],queryFn:async()=>{const{data:at,error:Ke}=await q.from("social_swag_2_months").select("*").order("month",{ascending:!1});if(Ke)throw Ke;return at}}),{data:ce=[]}=tt({queryKey:["admin-social-swag-2-reels"],queryFn:async()=>{const{data:at,error:Ke}=await q.from("social_swag_2_reels").select("*").order("month",{ascending:!1});if(Ke)throw Ke;return at}}),_e=[...new Set(ne.map(at=>at.month))].sort((at,Ke)=>Ke.localeCompare(at)),he=t==="all"?ne:ne.filter(at=>at.month===t),ue=at=>{const Ke=Ltt(at,"yyyy-MM",new Date);return en(Ke,"MMMM yyyy")},ve=at=>{g(at),y(at.caption),b(at.post_date)},Ee=async()=>{if(f){S(!0);try{const{error:at}=await q.from("social_swag_2").update({caption:x,post_date:v}).eq("id",f.id);if(at)throw at;re.success("Image updated"),g(null),s.invalidateQueries({queryKey:["admin-social-swag-2"]}),s.invalidateQueries({queryKey:["social-swag-2"]})}catch{re.error("Failed to update image")}finally{S(!1)}}},Se=async at=>{const{active:Ke,over:nt}=at;if(!nt||Ke.id===nt.id)return;const xt=he,rt=xt.findIndex(ts=>ts.id===Ke.id),Yt=xt.findIndex(ts=>ts.id===nt.id);if(rt===-1||Yt===-1)return;const qt=v6e(xt,rt,Yt);s.setQueryData(["admin-social-swag-2"],ts=>{if(!ts)return ts;const ys={};return qt.forEach((Bt,Ft)=>{ys[Bt.id]=Ft}),ts.map(Bt=>ys[Bt.id]!==void 0?{...Bt,sort_order:ys[Bt.id]}:Bt).sort((Bt,Ft)=>Bt.month!==Ft.month?Ft.month.localeCompare(Bt.month):Bt.sort_order-Ft.sort_order)});try{await Promise.all(qt.map((ts,ys)=>q.from("social_swag_2").update({sort_order:ys}).eq("id",ts.id)))}catch{re.error("Failed to save order"),s.invalidateQueries({queryKey:["admin-social-swag-2"]})}},Le=at=>{const nt=Array.from(at.target.files||[]).sort((xt,rt)=>xt.name.localeCompare(rt.name,void 0,{numeric:!0,sensitivity:"base"})).slice(0,16-o.length).map(xt=>({file:xt,preview:URL.createObjectURL(xt),caption:""}));c(xt=>[...xt,...nt].slice(0,16))},Fe=at=>{c(Ke=>{const nt=[...Ke];return URL.revokeObjectURL(nt[at].preview),nt.splice(at,1),nt})},ke=(at,Ke)=>{c(nt=>{const xt=[...nt];return xt[at]={...xt[at],caption:Ke},xt})},Ve=async()=>{var Ke;if(o.length===0){re.error("Please add at least one image");return}if(o.filter(nt=>!nt.caption.trim()).length>0){re.error("Please add captions to all images");return}u(!0);try{const{data:nt}=await q.from("social_swag_2").select("sort_order").eq("month",i).order("sort_order",{ascending:!1}).limit(1),xt=(((Ke=nt==null?void 0:nt[0])==null?void 0:Ke.sort_order)??-1)+1;for(let rt=0;rt{const Ke=at.image_url.split("/social-swag-2/");Ke[1]&&await q.storage.from("social-swag-2").remove([Ke[1]]);const{error:nt}=await q.from("social_swag_2").delete().eq("id",at.id);if(nt)throw nt},onSuccess:()=>{re.success("Image deleted"),s.invalidateQueries({queryKey:["admin-social-swag-2"]})},onError:()=>re.error("Failed to delete image")}),Ae=ft({mutationFn:async({id:at,postDate:Ke})=>{const{error:nt}=await q.from("social_swag_2").update({post_date:Ke}).eq("id",at);if(nt)throw nt},onSuccess:()=>{re.success("Post date updated"),s.invalidateQueries({queryKey:["admin-social-swag-2"]}),s.invalidateQueries({queryKey:["social-swag-2"]})},onError:()=>re.error("Failed to update post date")}),Ce=ft({mutationFn:async({month:at,link:Ke})=>{const{error:nt}=await q.from("social_swag_2_months").upsert({month:at,canva_link:Ke||null},{onConflict:"month"});if(nt)throw nt},onSuccess:()=>{re.success("Canva link updated"),m(null),s.invalidateQueries({queryKey:["admin-social-swag-2-months"]})},onError:()=>re.error("Failed to update Canva link")}),qe=at=>{var Ke;return((Ke=J.find(nt=>nt.month===at))==null?void 0:Ke.canva_link)||""},ze=at=>ce.find(Ke=>Ke.month===at)||null,$e=at=>{var nt;const Ke=(nt=at.target.files)==null?void 0:nt[0];Ke&&(D(Ke),U(URL.createObjectURL(Ke)))},ct=()=>{O&&URL.revokeObjectURL(O),D(null),U(""),V(""),Y("")},Xe=async()=>{if(!R){re.error("Please select an image");return}ae(!0);try{const at=R.name.split(".").pop(),Ke=`reels/${I}-${Date.now()}.${at}`,{error:nt}=await q.storage.from("social-swag-2").upload(Ke,R);if(nt)throw nt;const{data:{publicUrl:xt}}=q.storage.from("social-swag-2").getPublicUrl(Ke),{error:rt}=await q.from("social_swag_2_reels").upsert({month:I,image_url:xt,canva_link:G||null,caption:W||null},{onConflict:"month"});if(rt)throw rt;re.success("Reel uploaded successfully!"),KWe(`${ue(I)} Reel`,"social-swag-2"),ct(),E(!1),s.invalidateQueries({queryKey:["admin-social-swag-2-reels"]})}catch(at){console.error("Reel upload error:",at),re.error("Failed to upload reel")}finally{ae(!1)}},it=ft({mutationFn:async at=>{const Ke=at.image_url.split("/social-swag-2/");Ke[1]&&await q.storage.from("social-swag-2").remove([Ke[1]]);const{error:nt}=await q.from("social_swag_2_reels").delete().eq("id",at.id);if(nt)throw nt},onSuccess:()=>{re.success("Reel deleted"),s.invalidateQueries({queryKey:["admin-social-swag-2-reels"]})},onError:()=>re.error("Failed to delete reel")});return e.jsxs(Vs,{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(zs,{open:r,onOpenChange:a,children:[e.jsx(jl,{asChild:!0,children:e.jsxs($,{className:"gap-2",children:[e.jsx(dn,{className:"h-4 w-4"}),"Upload Images"]})}),e.jsxs(Os,{className:"max-w-4xl max-h-[90vh] overflow-y-auto",children:[e.jsx(Us,{children:e.jsx(Bs,{children:"Upload Social Swag Images"})}),e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Month"}),e.jsx(pe,{type:"month",value:i,onChange:at=>l(at.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ee,{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:Le,className:"hidden",id:"swag-upload",disabled:o.length>=16}),e.jsxs("label",{htmlFor:"swag-upload",className:"cursor-pointer",children:[e.jsx(ni,{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((at,Ke)=>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:at.preview,alt:`Upload ${Ke+1}`,className:"w-full h-full object-cover"}),e.jsx($,{variant:"destructive",size:"icon",className:"absolute top-1 right-1 h-6 w-6",onClick:()=>Fe(Ke),children:e.jsx(gr,{className:"h-3 w-3"})})]}),e.jsx(Rs,{placeholder:"Caption...",value:at.caption,onChange:nt=>ke(Ke,nt.target.value),className:"text-xs h-20"})]},Ke))}),e.jsx($,{onClick:Ve,disabled:d||o.length===0,className:"w-full gap-2",children:d?e.jsxs(e.Fragment,{children:[e.jsx(kt,{className:"h-4 w-4 animate-spin"}),"Uploading..."]}):e.jsxs(e.Fragment,{children:[e.jsx(ni,{className:"h-4 w-4"}),"Upload ",o.length," Images"]})})]})]})]}),e.jsxs(zs,{open:C,onOpenChange:at=>{E(at),at||ct()},children:[e.jsx(jl,{asChild:!0,children:e.jsxs($,{variant:"outline",className:"gap-2",children:[e.jsx(rf,{className:"h-4 w-4"}),"Upload Reel"]})}),e.jsxs(Os,{className:"max-w-lg max-h-[85vh] overflow-y-auto",children:[e.jsx(Us,{children:e.jsx(Bs,{children:"Upload Monthly Reel"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Month"}),e.jsx(pe,{type:"month",value:I,onChange:at=>P(at.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Reel Preview Image"}),O?e.jsxs("div",{className:"relative aspect-[9/16] max-w-[120px] mx-auto rounded-lg overflow-hidden bg-muted",children:[e.jsx("img",{src:O,alt:"Reel preview",className:"w-full h-full object-cover"}),e.jsx($,{variant:"destructive",size:"icon",className:"absolute top-2 right-2 h-6 w-6",onClick:()=>{URL.revokeObjectURL(O),D(null),U("")},children:e.jsx(gr,{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:$e,className:"hidden",id:"reel-upload"}),e.jsxs("label",{htmlFor:"reel-upload",className:"cursor-pointer",children:[e.jsx(rf,{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(ee,{children:"Canva Download Link"}),e.jsx(pe,{value:G,onChange:at=>Y(at.target.value),placeholder:"https://www.canva.com/..."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Caption"}),e.jsx(Rs,{value:W,onChange:at=>V(at.target.value),placeholder:"Enter caption for this reel...",className:"h-24"})]}),e.jsx($,{onClick:Xe,disabled:X||!R,className:"w-full gap-2",children:X?e.jsxs(e.Fragment,{children:[e.jsx(kt,{className:"h-4 w-4 animate-spin"}),"Uploading..."]}):e.jsxs(e.Fragment,{children:[e.jsx(ni,{className:"h-4 w-4"}),"Upload Reel"]})})]})]})]})]})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[e.jsx(Ne,{children:e.jsxs(Ie,{className:"p-4",children:[e.jsx("div",{className:"text-2xl font-bold",children:ne.length}),e.jsx("div",{className:"text-sm text-muted-foreground",children:"Total Images"})]})}),e.jsx(Ne,{children:e.jsxs(Ie,{className:"p-4",children:[e.jsx("div",{className:"text-2xl font-bold",children:_e.length}),e.jsx("div",{className:"text-sm text-muted-foreground",children:"Months"})]})})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsx(ha,{value:t,onValueChange:n,children:e.jsxs(ma,{children:[e.jsx(Zt,{value:"all",children:"All"}),_e.map(at=>e.jsx(Zt,{value:at,children:ue(at)},at))]})}),t!=="all"&&e.jsx(Ne,{children:e.jsx(Ie,{className:"p-4",children:e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx(Ad,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("div",{className:"flex-1",children:[e.jsxs(ee,{className:"text-sm text-muted-foreground",children:["Canva Edit Link for ",ue(t)]}),(h==null?void 0:h.month)===t?e.jsxs("div",{className:"flex gap-2 mt-1",children:[e.jsx(pe,{value:h.link,onChange:at=>m({...h,link:at.target.value}),placeholder:"https://www.canva.com/..."}),e.jsx($,{size:"sm",onClick:()=>Ce.mutate(h),children:"Save"}),e.jsx($,{size:"sm",variant:"outline",onClick:()=>m(null),children:"Cancel"})]}):e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx("span",{className:"text-sm",children:qe(t)||"No link set"}),e.jsx($,{size:"sm",variant:"outline",onClick:()=>m({month:t,link:qe(t)}),children:"Edit"})]})]})]})})}),t!=="all"&&e.jsx(Ne,{children:e.jsx(Ie,{className:"p-4",children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx(rf,{className:"h-4 w-4 text-muted-foreground mt-1"}),e.jsxs("div",{className:"flex-1",children:[e.jsxs(ee,{className:"text-sm text-muted-foreground",children:["Reel for ",ue(t)]}),(()=>{const at=ze(t);return at?e.jsxs("div",{className:"flex items-center gap-4 mt-2",children:[e.jsx("img",{src:at.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:at.caption||"No caption"}),at.canva_link&&e.jsx("a",{href:at.canva_link,target:"_blank",rel:"noopener noreferrer",className:"text-primary hover:underline text-xs",children:"View Canva Link"})]}),e.jsx($,{variant:"destructive",size:"sm",onClick:()=>it.mutate(at),children:e.jsx(Wn,{className:"h-4 w-4"})})]}):e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:"No reel uploaded for this month"})})()]})]})})})]}),te?e.jsx("div",{className:"text-center py-12 text-muted-foreground",children:"Loading..."}):he.length===0?e.jsxs("div",{className:"text-center py-12",children:[e.jsx(Mc,{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(y6e,{sensors:ie,collisionDetection:m6e,onDragEnd:Se,children:e.jsx(b6e,{items:he.map(at=>at.id),strategy:aie,children:e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 lg:grid-cols-6 gap-4",children:he.map(at=>e.jsx(Smn,{item:at,onEdit:ve,onDelete:Ke=>je.mutate(Ke),onDateChange:(Ke,nt)=>Ae.mutate({id:Ke,postDate:nt})},at.id))})})})]}),e.jsx(zs,{open:!!f,onOpenChange:at=>{at||g(null)},children:e.jsxs(Os,{className:"max-w-md",children:[e.jsx(Us,{children:e.jsx(Bs,{children:"Edit Image"})}),f&&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:f.image_url,alt:"Preview",className:"w-full h-full object-cover"})}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Caption"}),e.jsx(Rs,{value:x,onChange:at=>y(at.target.value),placeholder:"Enter caption...",className:"h-28"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Post Date"}),e.jsxs("div",{className:"flex gap-2 items-center",children:[e.jsxs(Yd,{children:[e.jsx(Zd,{asChild:!0,children:e.jsxs($,{variant:"outline",className:Pt("flex-1 justify-start gap-2 font-normal",!v&&"text-muted-foreground"),children:[e.jsx(Ta,{className:"h-4 w-4"}),v?en(new Date(v+"T00:00:00"),"MMM d, yyyy"):"Pick a date"]})}),e.jsx(Bd,{className:"w-auto p-0",align:"start",children:e.jsx(D2,{mode:"single",selected:v?new Date(v+"T00:00:00"):void 0,onSelect:at=>b(at?en(at,"yyyy-MM-dd"):null),className:"p-3 pointer-events-auto"})})]}),v&&e.jsx($,{variant:"ghost",size:"icon",onClick:()=>b(null),children:e.jsx(gr,{className:"h-4 w-4"})})]})]})]}),e.jsxs(Ar,{children:[e.jsx($,{variant:"outline",onClick:()=>g(null),children:"Cancel"}),e.jsx($,{onClick:Ee,disabled:w,className:"gap-2",children:w?e.jsxs(e.Fragment,{children:[e.jsx(kt,{className:"h-4 w-4 animate-spin"}),"Saving..."]}):"Save Changes"})]})]})})]})},Amn=()=>{const{toast:s}=Bi(),t=Vt(),[n,r]=j.useState("categories"),[a,i]=j.useState(!1),[l,o]=j.useState(null),[c,d]=j.useState({name:"",description:"",icon:""}),[u,h]=j.useState(!1),[m,f]=j.useState(null),[g,x]=j.useState({name:"",description:"",icon:""}),[y,v]=j.useState(!1),[b,w]=j.useState(null),[S,C]=j.useState(""),{data:E=[],isLoading:I}=tt({queryKey:["admin-community-categories"],queryFn:async()=>{const{data:Se,error:Le}=await q.from("community_categories").select("*").order("sort_order");if(Le)throw Le;return Se}}),{data:P=[],isLoading:R}=tt({queryKey:["admin-private-groups"],queryFn:async()=>{const{data:Se,error:Le}=await q.from("community_private_groups").select("*").order("sort_order");if(Le)throw Le;return Se}}),{data:D=[]}=tt({queryKey:["admin-group-members",b==null?void 0:b.id],queryFn:async()=>{if(!b)return[];const{data:Se,error:Le}=await q.from("community_private_group_members").select("*").eq("group_id",b.id);if(Le)throw Le;return Se},enabled:!!b}),{data:O=[]}=tt({queryKey:["admin-all-profiles"],queryFn:async()=>{let Le=[],Fe=0,ke=!0;for(;ke;){const{data:Ve,error:je}=await q.from("profiles").select("id, name, email, brokerage_id").order("name").range(Fe,Fe+1e3-1);if(je)throw je;Ve&&Ve.length>0?(Le=[...Le,...Ve],Fe+=1e3,ke=Ve.length===1e3):ke=!1}return Le}}),{data:U=[]}=tt({queryKey:["admin-all-brokerages"],queryFn:async()=>{const{data:Se,error:Le}=await q.from("brokerages").select("*").order("name");if(Le)throw Le;return Se}}),W=ft({mutationFn:async Se=>{if(Se.id){const{error:Le}=await q.from("community_categories").update({name:Se.name,description:Se.description||null,icon:Se.icon||null}).eq("id",Se.id);if(Le)throw Le}else{const Le=Math.max(...E.map(ke=>ke.sort_order),0),{error:Fe}=await q.from("community_categories").insert({name:Se.name,description:Se.description||null,icon:Se.icon||null,sort_order:Le+1});if(Fe)throw Fe}},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-community-categories"]}),i(!1),o(null),d({name:"",description:"",icon:""}),s({title:l?"Category updated!":"Category created!"})},onError:Se=>{s({title:"Error",description:Se.message,variant:"destructive"})}}),V=ft({mutationFn:async Se=>{const{error:Le}=await q.from("community_categories").delete().eq("id",Se);if(Le)throw Le},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-community-categories"]}),s({title:"Category deleted"})}}),G=ft({mutationFn:async({id:Se,direction:Le})=>{const Fe=E.findIndex(ke=>ke.id===Se);if(Le==="up"&&Fe>0){const ke=E[Fe-1],Ve=E[Fe];await q.from("community_categories").update({sort_order:Ve.sort_order}).eq("id",ke.id),await q.from("community_categories").update({sort_order:ke.sort_order}).eq("id",Ve.id)}else if(Le==="down"&&Fet.invalidateQueries({queryKey:["admin-community-categories"]})}),Y=ft({mutationFn:async Se=>{if(Se.id){const{error:Le}=await q.from("community_private_groups").update({name:Se.name,description:Se.description||null,icon:Se.icon||null}).eq("id",Se.id);if(Le)throw Le}else{const Le=Math.max(...P.map(ke=>ke.sort_order),0),{error:Fe}=await q.from("community_private_groups").insert({name:Se.name,description:Se.description||null,icon:Se.icon||null,sort_order:Le+1});if(Fe)throw Fe}},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-private-groups"]}),h(!1),f(null),x({name:"",description:"",icon:""}),s({title:m?"Private group updated!":"Private group created!"})},onError:Se=>{s({title:"Error",description:Se.message,variant:"destructive"})}}),X=ft({mutationFn:async Se=>{const{error:Le}=await q.from("community_private_groups").delete().eq("id",Se);if(Le)throw Le},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-private-groups"]}),s({title:"Private group deleted"})}}),ae=ft({mutationFn:async({id:Se,direction:Le})=>{const Fe=P.findIndex(ke=>ke.id===Se);if(Le==="up"&&Fe>0){const ke=P[Fe-1],Ve=P[Fe];await q.from("community_private_groups").update({sort_order:Ve.sort_order}).eq("id",ke.id),await q.from("community_private_groups").update({sort_order:ke.sort_order}).eq("id",Ve.id)}else if(Le==="down"&&Fet.invalidateQueries({queryKey:["admin-private-groups"]})}),ie=ft({mutationFn:async({groupId:Se,userId:Le,isMember:Fe})=>{if(Fe){const{error:ke}=await q.from("community_private_group_members").delete().eq("group_id",Se).eq("user_id",Le);if(ke)throw ke}else{const{error:ke}=await q.from("community_private_group_members").insert({group_id:Se,user_id:Le});if(ke)throw ke}},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-group-members",b==null?void 0:b.id]})}}),ne=ft({mutationFn:async({groupId:Se,brokerageId:Le,isMember:Fe})=>{if(Fe){const{error:ke}=await q.from("community_private_group_members").delete().eq("group_id",Se).eq("brokerage_id",Le);if(ke)throw ke}else{const{error:ke}=await q.from("community_private_group_members").insert({group_id:Se,brokerage_id:Le});if(ke)throw ke}},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-group-members",b==null?void 0:b.id]})}}),te=Se=>{o(Se),d({name:Se.name,description:Se.description||"",icon:Se.icon||""}),i(!0)},J=()=>{o(null),d({name:"",description:"",icon:""}),i(!0)},ce=Se=>{f(Se),x({name:Se.name,description:Se.description||"",icon:Se.icon||""}),h(!0)},_e=()=>{f(null),x({name:"",description:"",icon:""}),h(!0)},he=Se=>{w(Se),C(""),v(!0)},ue=Se=>D.some(Le=>Le.user_id===Se),ve=Se=>D.some(Le=>Le.brokerage_id===Se),Ee=O.filter(Se=>Se.name.toLowerCase().includes(S.toLowerCase())||Se.email.toLowerCase().includes(S.toLowerCase()));return e.jsx(Vs,{title:"Community Management",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(Fm,{title:"Community Management",description:"Manage categories and private groups for community discussions"}),e.jsxs(ha,{value:n,onValueChange:r,children:[e.jsxs(ma,{children:[e.jsx(Zt,{value:"categories",children:"Public Categories"}),e.jsxs(Zt,{value:"private-groups",children:[e.jsx(pc,{className:"h-4 w-4 mr-1"}),"Private Groups"]})]}),e.jsxs(Xt,{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($,{onClick:J,children:[e.jsx(dn,{className:"h-4 w-4 mr-2"}),"Add Category"]})]}),e.jsx(Ne,{children:e.jsx(Ie,{className:"pt-6",children:e.jsxs(mi,{children:[e.jsx(fi,{children:e.jsxs(En,{children:[e.jsx(Dt,{className:"w-[50px]",children:"Order"}),e.jsx(Dt,{className:"w-[80px]",children:"Icon"}),e.jsx(Dt,{children:"Name"}),e.jsx(Dt,{children:"Description"}),e.jsx(Dt,{className:"w-[100px]",children:"Actions"})]})}),e.jsx(pi,{children:I?e.jsx(En,{children:e.jsx(wt,{colSpan:5,className:"text-center py-8",children:"Loading..."})}):E.length===0?e.jsx(En,{children:e.jsx(wt,{colSpan:5,className:"text-center py-8 text-muted-foreground",children:"No categories yet. Create your first one!"})}):E.map((Se,Le)=>e.jsxs(En,{children:[e.jsx(wt,{children:e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsx($,{variant:"ghost",size:"icon",className:"h-6 w-6",disabled:Le===0,onClick:()=>G.mutate({id:Se.id,direction:"up"}),children:"↑"}),e.jsx($,{variant:"ghost",size:"icon",className:"h-6 w-6",disabled:Le===E.length-1,onClick:()=>G.mutate({id:Se.id,direction:"down"}),children:"↓"})]})}),e.jsx(wt,{className:"text-2xl",children:Se.icon||"📁"}),e.jsx(wt,{className:"font-medium",children:Se.name}),e.jsx(wt,{className:"text-muted-foreground",children:Se.description||"—"}),e.jsx(wt,{children:e.jsxs("div",{className:"flex gap-1",children:[e.jsx($,{variant:"ghost",size:"icon",onClick:()=>te(Se),children:e.jsx(gi,{className:"h-4 w-4"})}),e.jsx($,{variant:"ghost",size:"icon",className:"text-destructive",onClick:async()=>{await fo("Delete this category? Posts will be uncategorized.")&&V.mutate(Se.id)},children:e.jsx(Wn,{className:"h-4 w-4"})})]})})]},Se.id))})]})})})]}),e.jsxs(Xt,{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(ji,{className:"h-3 w-3"}),"Brokerage groups are created automatically and sync with brokerage names"]})]}),e.jsxs($,{onClick:_e,children:[e.jsx(dn,{className:"h-4 w-4 mr-2"}),"Add Private Group"]})]}),e.jsx(Ne,{children:e.jsx(Ie,{className:"pt-6",children:e.jsxs(mi,{children:[e.jsx(fi,{children:e.jsxs(En,{children:[e.jsx(Dt,{className:"w-[50px]",children:"Order"}),e.jsx(Dt,{className:"w-[80px]",children:"Icon"}),e.jsx(Dt,{children:"Name"}),e.jsx(Dt,{children:"Description"}),e.jsx(Dt,{className:"w-[120px]",children:"Members"}),e.jsx(Dt,{className:"w-[140px]",children:"Actions"})]})}),e.jsx(pi,{children:R?e.jsx(En,{children:e.jsx(wt,{colSpan:6,className:"text-center py-8",children:"Loading..."})}):P.length===0?e.jsx(En,{children:e.jsx(wt,{colSpan:6,className:"text-center py-8 text-muted-foreground",children:"No private groups yet. Create your first one!"})}):P.map((Se,Le)=>e.jsxs(En,{children:[e.jsx(wt,{children:e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsx($,{variant:"ghost",size:"icon",className:"h-6 w-6",disabled:Le===0,onClick:()=>ae.mutate({id:Se.id,direction:"up"}),children:"↑"}),e.jsx($,{variant:"ghost",size:"icon",className:"h-6 w-6",disabled:Le===P.length-1,onClick:()=>ae.mutate({id:Se.id,direction:"down"}),children:"↓"})]})}),e.jsx(wt,{className:"text-2xl",children:Se.icon||"🔒"}),e.jsx(wt,{className:"font-medium",children:e.jsxs("div",{className:"flex items-center gap-2",children:[Se.name,Se.brokerage_id?e.jsxs(Be,{variant:"outline",className:"text-xs bg-blue-50 text-blue-700 border-blue-200",children:[e.jsx(ji,{className:"h-3 w-3 mr-1"}),"Auto-managed"]}):e.jsxs(Be,{variant:"secondary",className:"text-xs",children:[e.jsx(pc,{className:"h-3 w-3 mr-1"}),"Private"]})]})}),e.jsx(wt,{className:"text-muted-foreground",children:Se.description||"—"}),e.jsx(wt,{children:e.jsxs($,{variant:"outline",size:"sm",onClick:()=>he(Se),children:[e.jsx(Zn,{className:"h-4 w-4 mr-1"}),"Manage"]})}),e.jsx(wt,{children:e.jsxs("div",{className:"flex gap-1",children:[!Se.brokerage_id&&e.jsx($,{variant:"ghost",size:"icon",onClick:()=>ce(Se),children:e.jsx(gi,{className:"h-4 w-4"})}),!Se.brokerage_id&&e.jsx($,{variant:"ghost",size:"icon",className:"text-destructive",onClick:async()=>{await fo("Delete this private group? All posts in this group will be deleted.")&&X.mutate(Se.id)},children:e.jsx(Wn,{className:"h-4 w-4"})}),Se.brokerage_id&&e.jsx("span",{className:"text-xs text-muted-foreground italic",children:"Managed via brokerage"})]})})]},Se.id))})]})})})]})]}),e.jsx(zs,{open:a,onOpenChange:i,children:e.jsxs(Os,{children:[e.jsx(Us,{children:e.jsx(Bs,{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(pe,{value:c.icon,onChange:Se=>d(Le=>({...Le,icon:Se.target.value})),placeholder:"💬",className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium",children:"Name *"}),e.jsx(pe,{value:c.name,onChange:Se=>d(Le=>({...Le,name:Se.target.value})),placeholder:"Category name",className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium",children:"Description"}),e.jsx(Rs,{value:c.description,onChange:Se=>d(Le=>({...Le,description:Se.target.value})),placeholder:"Brief description of this category",className:"mt-1"})]}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx($,{variant:"outline",onClick:()=>i(!1),children:"Cancel"}),e.jsx($,{onClick:()=>W.mutate({...c,id:l==null?void 0:l.id}),disabled:!c.name.trim(),children:l?"Save Changes":"Create Category"})]})]})]})}),e.jsx(zs,{open:u,onOpenChange:h,children:e.jsxs(Os,{children:[e.jsx(Us,{children:e.jsx(Bs,{children:m?"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(pe,{value:g.icon,onChange:Se=>x(Le=>({...Le,icon:Se.target.value})),placeholder:"🔒",className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium",children:"Name *"}),e.jsx(pe,{value:g.name,onChange:Se=>x(Le=>({...Le,name:Se.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(Rs,{value:g.description,onChange:Se=>x(Le=>({...Le,description:Se.target.value})),placeholder:"Brief description of this private group",className:"mt-1"})]}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx($,{variant:"outline",onClick:()=>h(!1),children:"Cancel"}),e.jsx($,{onClick:()=>Y.mutate({...g,id:m==null?void 0:m.id}),disabled:!g.name.trim(),children:m?"Save Changes":"Create Private Group"})]})]})]})}),e.jsx(zs,{open:y,onOpenChange:v,children:e.jsxs(Os,{className:"max-w-2xl",children:[e.jsx(Us,{children:e.jsxs(Bs,{children:["Manage Members: ",b==null?void 0:b.name]})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs(ha,{defaultValue:"brokerages",children:[e.jsxs(ma,{className:"w-full",children:[e.jsx(Zt,{value:"brokerages",className:"flex-1",children:"By Brokerage"}),e.jsx(Zt,{value:"users",className:"flex-1",children:"Individual Users"})]}),e.jsxs(Xt,{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(uo,{className:"h-[300px] border rounded-md p-4",children:e.jsxs("div",{className:"space-y-2",children:[U.map(Se=>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(ai,{checked:ve(Se.id),onCheckedChange:()=>{b&&ne.mutate({groupId:b.id,brokerageId:Se.id,isMember:ve(Se.id)})}}),e.jsx("span",{className:"font-medium",children:Se.name})]}),e.jsxs(Be,{variant:"secondary",children:[O.filter(Le=>Le.brokerage_id===Se.id).length," agents"]})]},Se.id)),U.length===0&&e.jsx("p",{className:"text-center text-muted-foreground py-4",children:"No brokerages found"})]})})]}),e.jsxs(Xt,{value:"users",className:"space-y-4",children:[e.jsxs("div",{className:"relative",children:[e.jsx(Kr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(pe,{placeholder:"Search users...",value:S,onChange:Se=>C(Se.target.value),className:"pl-9"})]}),e.jsx(uo,{className:"h-[300px] border rounded-md p-4",children:e.jsxs("div",{className:"space-y-2",children:[Ee.map(Se=>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(ai,{checked:ue(Se.id),onCheckedChange:()=>{b&&ie.mutate({groupId:b.id,userId:Se.id,isMember:ue(Se.id)})}}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:Se.name}),e.jsx("div",{className:"text-sm text-muted-foreground",children:Se.email})]})]})},Se.id)),Ee.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($,{onClick:()=>v(!1),children:"Done"})})]})]})})]})})},Kwt=s=>{switch(s){case"academy_video":return e.jsx(Bu,{className:"h-3 w-3"});case"template":return e.jsx(Jr,{className:"h-3 w-3"});case"toolbox":return e.jsx(vm,{className:"h-3 w-3"});case"newsletter":return e.jsx(nk,{className:"h-3 w-3"});case"social_swag":return e.jsx(Nn,{className:"h-3 w-3"});default:return e.jsx(kr,{className:"h-3 w-3"})}},Emn=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}},Tmn=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}},Mmn=()=>{const{toast:s}=Bi(),[t,n]=j.useState([]),[r,a]=j.useState([]),[i,l]=j.useState([]),[o,c]=j.useState(!0),[d,u]=j.useState(""),[h,m]=j.useState(null),[f,g]=j.useState([]),[x,y]=j.useState([]);j.useEffect(()=>{v()},[]);const v=async()=>{try{c(!0);const{data:D,error:O}=await q.from("activity_logs").select(` id, user_id, app_name, launched_at, profiles ( name, email, brokerages ( name ) ) `).order("launched_at",{ascending:!1}).limit(5e3);if(O)throw O;const{data:U,error:W}=await q.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(W)throw W;const V=[...new Set((U==null?void 0:U.map(te=>te.user_id))||[])],{data:G}=await q.from("profiles").select(` id, name, email, brokerages ( name ) `).in("id",V),Y=new Map((G==null?void 0:G.map(te=>[te.id,te]))||[]),X=(D==null?void 0:D.map(te=>{var J,ce,_e,he;return{id:te.id,user_id:te.user_id,app_name:te.app_name,launched_at:te.launched_at,user_name:((J=te.profiles)==null?void 0:J.name)||"Unknown",user_email:((ce=te.profiles)==null?void 0:ce.email)||"Unknown",brokerage_name:((he=(_e=te.profiles)==null?void 0:_e.brokerages)==null?void 0:he.name)||null}}))||[],ae=(U==null?void 0:U.map(te=>{var ce;const J=Y.get(te.user_id);return{id:te.id,user_id:te.user_id,resource_type:te.resource_type,resource_id:te.resource_id,resource_title:te.resource_title,action_type:te.action_type,created_at:te.created_at,user_name:(J==null?void 0:J.name)||"Unknown",user_email:(J==null?void 0:J.email)||"Unknown",brokerage_name:((ce=J==null?void 0:J.brokerages)==null?void 0:ce.name)||null}}))||[];n(X),a(ae);const ie=new Map;X.forEach(te=>{if(!ie.has(te.user_id))ie.set(te.user_id,{user_id:te.user_id,user_name:te.user_name,user_email:te.user_email,brokerage_name:te.brokerage_name,last_activity_type:"app",last_activity_name:te.app_name,last_activity_at:te.launched_at,total_app_launches:1,total_content_views:0});else{const J=ie.get(te.user_id);J.total_app_launches++,new Date(te.launched_at)>new Date(J.last_activity_at)&&(J.last_activity_type="app",J.last_activity_name=te.app_name,J.last_activity_at=te.launched_at)}}),ae.forEach(te=>{if(!ie.has(te.user_id))ie.set(te.user_id,{user_id:te.user_id,user_name:te.user_name,user_email:te.user_email,brokerage_name:te.brokerage_name,last_activity_type:te.resource_type,last_activity_name:te.resource_title,last_activity_at:te.created_at,total_app_launches:0,total_content_views:1});else{const J=ie.get(te.user_id);J.total_content_views++,new Date(te.created_at)>new Date(J.last_activity_at)&&(J.last_activity_type=te.resource_type,J.last_activity_name=te.resource_title,J.last_activity_at=te.created_at)}});const ne=Array.from(ie.values()).sort((te,J)=>new Date(J.last_activity_at).getTime()-new Date(te.last_activity_at).getTime());l(ne)}catch(D){console.error("Error loading activity:",D),s({title:"Error",description:"Failed to load activity logs",variant:"destructive"})}finally{c(!1)}},b=D=>{m({id:D.user_id,name:D.user_name,email:D.user_email});const O=t.filter(W=>W.user_id===D.user_id),U=r.filter(W=>W.user_id===D.user_id);g(O),y(U)},w=()=>{m(null),g([]),y([])},{sortKey:S,sortDirection:C,handleSort:E,sortData:I}=Nie("last_activity_at","desc"),P=i.filter(D=>{var U;if(!d)return!0;const O=d.toLowerCase();return D.user_name.toLowerCase().includes(O)||D.user_email.toLowerCase().includes(O)||((U=D.brokerage_name)==null?void 0:U.toLowerCase().includes(O))}),R=I(P,{user:D=>{var O;return((O=D.user_name)==null?void 0:O.toLowerCase())||""},brokerage:D=>{var O;return((O=D.brokerage_name)==null?void 0:O.toLowerCase())||""},last_activity_at:D=>new Date(D.last_activity_at).getTime(),apps:D=>D.total_app_launches,content:D=>D.total_content_views});return o?e.jsx(Ne,{children:e.jsx(Ie,{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(Ne,{children:[e.jsxs(Ct,{children:[e.jsx(At,{children:"User Activity"}),e.jsx(Gn,{children:"App launches and content engagement - click to see full history"})]}),e.jsxs(Ie,{children:[e.jsx("div",{className:"mb-4",children:e.jsxs("div",{className:"relative",children:[e.jsx(Kr,{className:"absolute left-3 top-3 h-4 w-4 text-muted-foreground"}),e.jsx(pe,{placeholder:"Search by name, email, or brokerage...",value:d,onChange:D=>u(D.target.value),className:"pl-9"})]})}),e.jsx("div",{className:"rounded-md border",children:e.jsxs(mi,{children:[e.jsx(fi,{children:e.jsxs(En,{children:[e.jsx(Im,{sortKey:"user",currentSortKey:S,currentDirection:C,onSort:E,children:"User"}),e.jsx(Im,{sortKey:"brokerage",currentSortKey:S,currentDirection:C,onSort:E,children:"Brokerage"}),e.jsx(Dt,{children:"Last Activity"}),e.jsx(Im,{sortKey:"last_activity_at",currentSortKey:S,currentDirection:C,onSort:E,children:"Last Active"}),e.jsx(Im,{sortKey:"apps",currentSortKey:S,currentDirection:C,onSort:E,className:"text-right",children:"Apps"}),e.jsx(Im,{sortKey:"content",currentSortKey:S,currentDirection:C,onSort:E,className:"text-right",children:"Content"})]})}),e.jsx(pi,{children:R.length===0?e.jsx(En,{children:e.jsx(wt,{colSpan:6,className:"text-center text-muted-foreground",children:"No activity found"})}):R.map(D=>e.jsxs(En,{className:"cursor-pointer hover:bg-muted/50 transition-colors",onClick:()=>b(D),children:[e.jsx(wt,{children:e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:D.user_name}),e.jsx("div",{className:"text-sm text-muted-foreground",children:D.user_email})]})}),e.jsx(wt,{children:D.brokerage_name?e.jsx(Be,{variant:"outline",children:D.brokerage_name}):e.jsx("span",{className:"text-muted-foreground text-sm",children:"-"})}),e.jsx(wt,{children:e.jsx("div",{className:"flex items-center gap-2",children:D.last_activity_type==="app"?e.jsxs(Be,{variant:"secondary",children:[e.jsx(kr,{className:"h-3 w-3 mr-1"}),D.last_activity_name]}):e.jsxs(Be,{variant:"outline",className:"flex items-center gap-1",children:[Kwt(D.last_activity_type),e.jsx("span",{className:"max-w-32 truncate",children:D.last_activity_name})]})})}),e.jsx(wt,{className:"text-sm text-muted-foreground",children:mu(new Date(D.last_activity_at),{addSuffix:!0})}),e.jsx(wt,{className:"text-right",children:e.jsx(Be,{variant:"outline",children:D.total_app_launches})}),e.jsx(wt,{className:"text-right",children:e.jsx(Be,{variant:"outline",children:D.total_content_views})})]},D.user_id))})]})})]})]}),e.jsx(zs,{open:!!h,onOpenChange:D=>!D&&w(),children:e.jsxs(Os,{className:"max-w-3xl max-h-[80vh] overflow-hidden flex flex-col",children:[e.jsxs(Us,{children:[e.jsxs(Bs,{children:[h==null?void 0:h.name,"'s Activity"]}),e.jsx(Ir,{children:h==null?void 0:h.email})]}),e.jsxs(ha,{defaultValue:"content",className:"flex-1 overflow-hidden flex flex-col",children:[e.jsxs(ma,{className:"grid w-full grid-cols-2",children:[e.jsxs(Zt,{value:"content",children:["Content (",x.length,")"]}),e.jsxs(Zt,{value:"apps",children:["App Launches (",f.length,")"]})]}),e.jsx(Xt,{value:"content",className:"flex-1 overflow-auto mt-4",children:e.jsx("div",{className:"rounded-md border",children:e.jsxs(mi,{children:[e.jsx(fi,{children:e.jsxs(En,{children:[e.jsx(Dt,{children:"Type"}),e.jsx(Dt,{children:"Resource"}),e.jsx(Dt,{children:"Action"}),e.jsx(Dt,{children:"Time"})]})}),e.jsx(pi,{children:x.length===0?e.jsx(En,{children:e.jsx(wt,{colSpan:4,className:"text-center text-muted-foreground",children:"No content engagement"})}):x.map(D=>e.jsxs(En,{children:[e.jsx(wt,{children:e.jsxs(Be,{variant:"outline",className:"flex items-center gap-1 w-fit",children:[Kwt(D.resource_type),Emn(D.resource_type)]})}),e.jsx(wt,{className:"max-w-48",children:e.jsx("span",{className:"truncate block",children:D.resource_title})}),e.jsx(wt,{children:e.jsx(Be,{variant:"secondary",children:Tmn(D.action_type)})}),e.jsx(wt,{className:"text-sm text-muted-foreground",children:mu(new Date(D.created_at),{addSuffix:!0})})]},D.id))})]})})}),e.jsx(Xt,{value:"apps",className:"flex-1 overflow-auto mt-4",children:e.jsx("div",{className:"rounded-md border",children:e.jsxs(mi,{children:[e.jsx(fi,{children:e.jsxs(En,{children:[e.jsx(Dt,{children:"App"}),e.jsx(Dt,{children:"Time"})]})}),e.jsx(pi,{children:f.length===0?e.jsx(En,{children:e.jsx(wt,{colSpan:2,className:"text-center text-muted-foreground",children:"No app launches"})}):f.map(D=>e.jsxs(En,{children:[e.jsx(wt,{children:e.jsx(Be,{variant:"secondary",children:D.app_name})}),e.jsx(wt,{className:"text-sm text-muted-foreground",children:mu(new Date(D.launched_at),{addSuffix:!0})})]},D.id))})]})})})]})]})})]})},Pmn=()=>{const{toast:s}=Bi(),[t,n]=j.useState({totalUsers:0,activeUsers:0,pendingUsers:0,totalBrokerages:0,totalLaunches:0,launchesThisWeek:0,launchesThisMonth:0,uniqueActiveThisWeek:0}),[r,a]=j.useState(!0);j.useEffect(()=>{i()},[]);const i=async()=>{try{a(!0);const{count:l}=await q.from("profiles").select("*",{count:"exact",head:!0}),{count:o}=await q.from("profiles").select("*",{count:"exact",head:!0}).not("last_login","is",null),c=(l||0)-(o||0),{count:d}=await q.from("brokerages").select("*",{count:"exact",head:!0}),{count:u}=await q.from("activity_logs").select("*",{count:"exact",head:!0}),h=new Date;h.setDate(h.getDate()-7);const{count:m}=await q.from("activity_logs").select("*",{count:"exact",head:!0}).gte("launched_at",h.toISOString()),f=new Date;f.setMonth(f.getMonth()-1);const{count:g}=await q.from("activity_logs").select("*",{count:"exact",head:!0}).gte("launched_at",f.toISOString()),{data:x}=await q.from("activity_logs").select("user_id").gte("launched_at",h.toISOString()),y=new Set(x==null?void 0:x.map(v=>v.user_id)).size;n({totalUsers:l||0,activeUsers:o||0,pendingUsers:c,totalBrokerages:d||0,totalLaunches:u||0,launchesThisWeek:m||0,launchesThisMonth:g||0,uniqueActiveThisWeek:y})}catch(l){console.error("Error loading analytics:",l),s({title:"Error",description:"Failed to load analytics",variant:"destructive"})}finally{a(!1)}};return r?e.jsx(Ne,{children:e.jsx(Ie,{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(Ne,{children:[e.jsxs(Ct,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(At,{className:"text-sm font-medium",children:"Total Users"}),e.jsx(Zn,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Ie,{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(Ne,{children:[e.jsxs(Ct,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(At,{className:"text-sm font-medium",children:"Active Users"}),e.jsx(Nc,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Ie,{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(Ne,{children:[e.jsxs(Ct,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(At,{className:"text-sm font-medium",children:"Pending Invites"}),e.jsx(da,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Ie,{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(Ne,{children:[e.jsxs(Ct,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(At,{className:"text-sm font-medium",children:"Brokerages"}),e.jsx(ji,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Ie,{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(Ne,{children:[e.jsxs(Ct,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(At,{className:"text-sm font-medium",children:"Total App Launches"}),e.jsx(af,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Ie,{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(Ne,{children:[e.jsxs(Ct,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(At,{className:"text-sm font-medium",children:"Launches This Week"}),e.jsx(af,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Ie,{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(Ne,{children:[e.jsxs(Ct,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(At,{className:"text-sm font-medium",children:"Launches This Month"}),e.jsx(af,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Ie,{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(Ne,{children:[e.jsxs(Ct,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(At,{className:"text-sm font-medium",children:"Active This Week"}),e.jsx(Yl,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Ie,{children:[e.jsx("div",{className:"text-2xl font-bold",children:t.uniqueActiveThisWeek}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Unique users"})]})]})]})},Ywt={event:"Event",template:"Template",academy_video:"Academy Video",resource_kit:"Resource Kit",newsletter:"Newsletter",social_swag:"Social Swag"},Zwt={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 KWt({brokerageOnly:s=!1,brokerageId:t}){const[n,r]=j.useState([]),[a,i]=j.useState(!0),[l,o]=j.useState(""),[c,d]=j.useState("all");j.useEffect(()=>{u()},[t]);const u=async()=>{i(!0);try{let E=[];if(s&&t){const{data:V}=await q.from("profiles").select("id").eq("brokerage_id",t);if(E=(V==null?void 0:V.map(G=>G.id))||[],E.length===0){r([]),i(!1);return}}let I=q.from("resource_shares").select("*").order("created_at",{ascending:!1});s&&E.length>0&&(I=I.or(`sender_id.in.(${E.join(",")}),recipient_id.in.(${E.join(",")})`));const{data:P,error:R}=await I;if(R)throw R;const D=new Set;P==null||P.forEach(V=>{D.add(V.sender_id),D.add(V.recipient_id)});const{data:O}=await q.from("profiles").select("id, name, email").in("id",Array.from(D)),U=new Map((O==null?void 0:O.map(V=>[V.id,V]))||[]),W=(P==null?void 0:P.map(V=>({...V,sender:U.get(V.sender_id),recipient:U.get(V.recipient_id)})))||[];r(W)}catch(E){console.error("Error loading shares:",E)}finally{i(!1)}},{sortKey:h,sortDirection:m,handleSort:f,sortData:g}=Nie("created_at","desc"),x=n.filter(E=>{var R,D;const I=l===""||E.resource_title.toLowerCase().includes(l.toLowerCase())||((R=E.sender)==null?void 0:R.name.toLowerCase().includes(l.toLowerCase()))||((D=E.recipient)==null?void 0:D.name.toLowerCase().includes(l.toLowerCase())),P=c==="all"||E.resource_type===c;return I&&P}),y=g(x,{resource:E=>{var I;return((I=E.resource_title)==null?void 0:I.toLowerCase())||""},type:E=>E.resource_type,sender:E=>{var I,P;return((P=(I=E.sender)==null?void 0:I.name)==null?void 0:P.toLowerCase())||""},recipient:E=>{var I,P;return((P=(I=E.recipient)==null?void 0:I.name)==null?void 0:P.toLowerCase())||""},status:E=>E.is_read?1:0,created_at:E=>new Date(E.created_at).getTime()}),v=n.length,b=new Set(n.map(E=>E.sender_id)).size,w=new Set(n.map(E=>E.recipient_id)).size,S=n.length>0?Math.round(n.filter(E=>E.is_read).length/n.length*100):0,C=n.reduce((E,I)=>(E[I.resource_type]=(E[I.resource_type]||0)+1,E),{});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((E,I)=>e.jsxs(Ne,{children:[e.jsx(Ct,{className:"pb-2",children:e.jsx(yn,{className:"h-4 w-20"})}),e.jsx(Ie,{children:e.jsx(yn,{className:"h-8 w-16"})})]},I))}),e.jsx(Ne,{children:e.jsx(Ie,{className:"p-6",children:e.jsx(yn,{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(Ne,{children:[e.jsxs(Ct,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(At,{className:"text-sm font-medium",children:"Total Shares"}),e.jsx(zd,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsx(Ie,{children:e.jsx("div",{className:"text-2xl font-bold",children:v})})]}),e.jsxs(Ne,{children:[e.jsxs(Ct,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(At,{className:"text-sm font-medium",children:"Active Sharers"}),e.jsx(Zn,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsx(Ie,{children:e.jsx("div",{className:"text-2xl font-bold",children:b})})]}),e.jsxs(Ne,{children:[e.jsxs(Ct,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(At,{className:"text-sm font-medium",children:"Recipients Reached"}),e.jsx(Yl,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsx(Ie,{children:e.jsx("div",{className:"text-2xl font-bold",children:w})})]}),e.jsxs(Ne,{children:[e.jsxs(Ct,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(At,{className:"text-sm font-medium",children:"Read Rate"}),e.jsx(Jr,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsx(Ie,{children:e.jsxs("div",{className:"text-2xl font-bold",children:[S,"%"]})})]})]}),e.jsxs(Ne,{children:[e.jsx(Ct,{children:e.jsx(At,{className:"text-sm font-medium",children:"Shares by Resource Type"})}),e.jsx(Ie,{children:e.jsxs("div",{className:"flex flex-wrap gap-2",children:[Object.entries(C).map(([E,I])=>e.jsxs(Be,{variant:"secondary",className:Zwt[E],children:[Ywt[E],": ",I]},E)),Object.keys(C).length===0&&e.jsx("span",{className:"text-muted-foreground text-sm",children:"No shares yet"})]})})]}),e.jsxs(Ne,{children:[e.jsxs(Ct,{children:[e.jsx(At,{children:"Share History"}),e.jsxs(Gn,{children:["All resource shares ",s?"in your brokerage":"across the platform"]})]}),e.jsxs(Ie,{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(Kr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(pe,{placeholder:"Search by resource, sender, or recipient...",value:l,onChange:E=>o(E.target.value),className:"pl-9"})]}),e.jsxs(ms,{value:c,onValueChange:d,children:[e.jsx(us,{className:"w-[180px]",children:e.jsx(fs,{placeholder:"Resource type"})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"all",children:"All Types"}),e.jsx(Ge,{value:"event",children:"Events"}),e.jsx(Ge,{value:"template",children:"Templates"}),e.jsx(Ge,{value:"academy_video",children:"Academy Videos"}),e.jsx(Ge,{value:"resource_kit",children:"Resource Kits"}),e.jsx(Ge,{value:"newsletter",children:"Newsletters"}),e.jsx(Ge,{value:"social_swag",children:"Social Swag"})]})]})]}),e.jsx(uo,{className:"h-[400px]",children:e.jsxs(mi,{children:[e.jsx(fi,{children:e.jsxs(En,{children:[e.jsx(Im,{sortKey:"resource",currentSortKey:h,currentDirection:m,onSort:f,children:"Resource"}),e.jsx(Im,{sortKey:"type",currentSortKey:h,currentDirection:m,onSort:f,children:"Type"}),e.jsx(Im,{sortKey:"sender",currentSortKey:h,currentDirection:m,onSort:f,children:"Sender"}),e.jsx(Im,{sortKey:"recipient",currentSortKey:h,currentDirection:m,onSort:f,children:"Recipient"}),e.jsx(Im,{sortKey:"status",currentSortKey:h,currentDirection:m,onSort:f,children:"Status"}),e.jsx(Im,{sortKey:"created_at",currentSortKey:h,currentDirection:m,onSort:f,children:"Date"})]})}),e.jsx(pi,{children:y.length===0?e.jsx(En,{children:e.jsx(wt,{colSpan:6,className:"text-center text-muted-foreground py-8",children:"No shares found"})}):y.map(E=>{var I,P;return e.jsxs(En,{children:[e.jsx(wt,{className:"font-medium max-w-[200px] truncate",children:E.resource_title}),e.jsx(wt,{children:e.jsx(Be,{variant:"secondary",className:Zwt[E.resource_type],children:Ywt[E.resource_type]})}),e.jsx(wt,{children:((I=E.sender)==null?void 0:I.name)||"Unknown"}),e.jsx(wt,{children:((P=E.recipient)==null?void 0:P.name)||"Unknown"}),e.jsx(wt,{children:e.jsx(Be,{variant:E.is_read?"default":"outline",children:E.is_read?"Read":"Unread"})}),e.jsx(wt,{className:"text-muted-foreground",children:en(new Date(E.created_at),"MMM d, yyyy")})]},E.id)})})]})})]})]})]})}const o9e={academy_video:{label:"Academy Videos",icon:ua,color:"bg-purple-100 text-purple-800",actionLabel:"Watched",actionIcon:Ca},template:{label:"Templates",icon:DA,color:"bg-blue-100 text-blue-800",actionLabel:"Accessed",actionIcon:hb},toolbox:{label:"Toolkit",icon:F4,color:"bg-amber-100 text-amber-800",actionLabel:"Downloaded",actionIcon:di},newsletter:{label:"Newsletters",icon:mn,color:"bg-emerald-100 text-emerald-800",actionLabel:"Clicked",actionIcon:hb},social_swag:{label:"Social Swag",icon:Yc,color:"bg-pink-100 text-pink-800",actionLabel:"Accessed",actionIcon:hb},event:{label:"Events",icon:Ta,color:"bg-cyan-100 text-cyan-800",actionLabel:"Registered",actionIcon:hb}};function Xwt(s){return s.resource_type==="toolbox"?s.total_downloads:s.total_clicks}function Imn(s,t){return s==="toolbox"?t.downloads:t.clicks}function Lmn(){var E;const[s,t]=j.useState([]),[n,r]=j.useState(!0),[a,i]=j.useState(null),l=j.useRef(null),{sortKey:o,sortDirection:c,handleSort:d,sortData:u}=Nie("total_views","desc");j.useEffect(()=>{h()},[]);const h=async()=>{try{const{data:I,error:P}=await q.rpc("get_admin_content_engagement");if(P)throw P;t(I||[])}catch(I){console.error("Error loading content engagement:",I)}finally{r(!1)}},m=I=>{i(P=>{const R=P===I?null:I;return requestAnimationFrame(()=>{var D;(D=l.current)==null||D.scrollIntoView({behavior:"smooth",block:"start"})}),R})};if(n)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((I,P)=>e.jsxs(Ne,{children:[e.jsx(Ct,{className:"pb-2",children:e.jsx(yn,{className:"h-4 w-20"})}),e.jsx(Ie,{children:e.jsx(yn,{className:"h-8 w-16"})})]},P))}),e.jsx(Ne,{children:e.jsx(Ie,{className:"py-8",children:e.jsx(yn,{className:"h-64 w-full"})})})]});const f=s.reduce((I,P)=>I+P.total_views,0),g=s.reduce((I,P)=>I+P.total_clicks,0),x=s.reduce((I,P)=>I+P.total_downloads,0),y=s.length,v=s.reduce((I,P)=>(I[P.resource_type]||(I[P.resource_type]={views:0,clicks:0,downloads:0,assets:0,uniqueUsers:0}),I[P.resource_type].views+=P.total_views,I[P.resource_type].clicks+=P.total_clicks,I[P.resource_type].downloads+=P.total_downloads,I[P.resource_type].assets+=1,I[P.resource_type].uniqueUsers+=P.unique_users,I),{}),b=a?s.filter(I=>I.resource_type===a):s,w=u(b,{asset:I=>{var P;return((P=I.resource_title)==null?void 0:P.toLowerCase())||""},type:I=>I.resource_type,views:I=>I.total_views,actions:I=>Xwt(I),unique_users:I=>I.unique_users,last_activity:I=>I.last_engaged_at?new Date(I.last_engaged_at).getTime():0}),S=a?o9e[a]||{label:a,icon:Ca,actionLabel:"Actions"}:null,C=S==null?void 0:S.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(Ne,{children:[e.jsxs(Ct,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(At,{className:"text-sm font-medium",children:"Total Views"}),e.jsx(Ca,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Ie,{children:[e.jsx("div",{className:"text-2xl font-bold",children:f.toLocaleString()}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Across all content"})]})]}),e.jsxs(Ne,{children:[e.jsxs(Ct,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(At,{className:"text-sm font-medium",children:"Total Clicks"}),e.jsx(hb,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Ie,{children:[e.jsx("div",{className:"text-2xl font-bold",children:g.toLocaleString()}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Link & Canva clicks"})]})]}),e.jsxs(Ne,{children:[e.jsxs(Ct,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(At,{className:"text-sm font-medium",children:"Downloads"}),e.jsx(di,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Ie,{children:[e.jsx("div",{className:"text-2xl font-bold",children:x.toLocaleString()}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"PDF downloads"})]})]}),e.jsxs(Ne,{children:[e.jsxs(Ct,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(At,{className:"text-sm font-medium",children:"Assets Tracked"}),e.jsx(Yl,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Ie,{children:[e.jsx("div",{className:"text-2xl font-bold",children:y}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Unique content items"})]})]}),e.jsxs(Ne,{children:[e.jsxs(Ct,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(At,{className:"text-sm font-medium",children:"Click Rate"}),e.jsx(hb,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Ie,{children:[e.jsxs("div",{className:"text-2xl font-bold",children:[f>0?Math.round((g+x)/f*100):0,"%"]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Of views → actions"})]})]})]}),e.jsxs(Ne,{children:[e.jsxs(Ct,{children:[e.jsx(At,{className:"text-sm font-medium",children:"Engagement by Content Type"}),e.jsx(Gn,{children:"Click a category to see individual asset performance"})]}),e.jsx(Ie,{children:e.jsx("div",{className:"grid gap-3 grid-cols-2 md:grid-cols-3",children:Object.entries(v).map(([I,P])=>{const R=o9e[I]||{label:I,icon:Ca,color:"bg-muted text-muted-foreground",actionIcon:hb},D=R.icon,O=a===I;return e.jsxs("button",{type:"button",onClick:()=>m(I),className:`flex items-center gap-3 p-3 rounded-lg border text-left transition-colors cursor-pointer ${O?"ring-2 ring-primary border-primary bg-primary/5":"hover:bg-muted/50"}`,children:[e.jsx("div",{className:`p-2 rounded-md ${R.color}`,children:e.jsx(D,{className:"h-4 w-4"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium",children:R.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(Ca,{className:"h-3 w-3"})," ",P.views]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(R.actionIcon,{className:"h-3 w-3"})," ",Imn(I,P)]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Zn,{className:"h-3 w-3"})," ",P.uniqueUsers]})]})]}),e.jsxs(Be,{variant:"secondary",className:"text-[10px]",children:[P.assets," items"]})]},I)})})})]}),e.jsx("div",{ref:l,children:e.jsxs(Ne,{children:[e.jsx(Ct,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(At,{className:"text-sm font-medium flex items-center gap-2",children:S&&C?e.jsxs(e.Fragment,{children:[e.jsx(C,{className:"h-4 w-4"}),S.label," — Top Performers"]}):"Top Content by Engagement"}),e.jsx(Gn,{children:a?`${b.length} ${((E=S==null?void 0:S.label)==null?void 0:E.toLowerCase())||"items"} ranked by total interactions`:"All tracked assets ranked by total interactions"})]}),a&&e.jsxs($,{variant:"ghost",size:"sm",onClick:()=>i(null),className:"gap-1",children:[e.jsx(qa,{className:"h-3.5 w-3.5"}),"Show All"]})]})}),e.jsx(Ie,{children:b.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(uo,{className:"h-[400px]",children:e.jsxs(mi,{children:[e.jsx(fi,{children:e.jsxs(En,{children:[e.jsx(Dt,{className:"w-[40px]",children:"#"}),e.jsx(Im,{sortKey:"asset",currentSortKey:o,currentDirection:c,onSort:d,children:"Asset"}),!a&&e.jsx(Im,{sortKey:"type",currentSortKey:o,currentDirection:c,onSort:d,children:"Type"}),e.jsx(Im,{sortKey:"views",currentSortKey:o,currentDirection:c,onSort:d,className:"text-right",children:"Views"}),e.jsx(Im,{sortKey:"actions",currentSortKey:o,currentDirection:c,onSort:d,className:"text-right",children:S?S.actionLabel:"Actions"}),e.jsx(Im,{sortKey:"unique_users",currentSortKey:o,currentDirection:c,onSort:d,className:"text-right",children:"Unique Users"}),e.jsx(Im,{sortKey:"last_activity",currentSortKey:o,currentDirection:c,onSort:d,children:"Last Activity"})]})}),e.jsx(pi,{children:w.map((I,P)=>{const R=o9e[I.resource_type]||{label:I.resource_type,color:"bg-muted text-muted-foreground"};return e.jsxs(En,{children:[e.jsx(wt,{className:"text-muted-foreground text-xs",children:P+1}),e.jsx(wt,{children:e.jsx("p",{className:"font-medium text-sm truncate max-w-[250px]",children:I.resource_title})}),!a&&e.jsx(wt,{children:e.jsx(Be,{className:`text-[10px] ${R.color}`,children:R.label})}),e.jsx(wt,{className:"text-right font-medium",children:I.total_views}),e.jsx(wt,{className:"text-right font-medium",children:Xwt(I)}),e.jsx(wt,{className:"text-right",children:I.unique_users}),e.jsx(wt,{className:"text-xs text-muted-foreground",children:I.last_engaged_at?mu(new Date(I.last_engaged_at),{addSuffix:!0}):"—"})]},`${I.resource_type}-${I.resource_id}`)})})]})})})]})})]})}var Rmn=Array.isArray,Zw=Rmn,Dmn=typeof Sp=="object"&&Sp&&Sp.Object===Object&&Sp,YWt=Dmn,Fmn=YWt,Omn=typeof self=="object"&&self&&self.Object===Object&&self,zmn=Fmn||Omn||Function("return this")(),f3=zmn,Bmn=f3,$mn=Bmn.Symbol,Sie=$mn,Qwt=Sie,ZWt=Object.prototype,Umn=ZWt.hasOwnProperty,qmn=ZWt.toString,WZ=Qwt?Qwt.toStringTag:void 0;function Vmn(s){var t=Umn.call(s,WZ),n=s[WZ];try{s[WZ]=void 0;var r=!0}catch{}var a=qmn.call(s);return r&&(t?s[WZ]=n:delete s[WZ]),a}var Hmn=Vmn,Gmn=Object.prototype,Wmn=Gmn.toString;function Kmn(s){return Wmn.call(s)}var Ymn=Kmn,Jwt=Sie,Zmn=Hmn,Xmn=Ymn,Qmn="[object Null]",Jmn="[object Undefined]",ejt=Jwt?Jwt.toStringTag:void 0;function efn(s){return s==null?s===void 0?Jmn:Qmn:ejt&&ejt in Object(s)?Zmn(s):Xmn(s)}var FT=efn;function tfn(s){return s!=null&&typeof s=="object"}var OT=tfn,sfn=FT,nfn=OT,rfn="[object Symbol]";function afn(s){return typeof s=="symbol"||nfn(s)&&sfn(s)==rfn}var kK=afn,ifn=Zw,ofn=kK,lfn=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,cfn=/^\w*$/;function dfn(s,t){if(ifn(s))return!1;var n=typeof s;return n=="number"||n=="symbol"||n=="boolean"||s==null||ofn(s)?!0:cfn.test(s)||!lfn.test(s)||t!=null&&s in Object(t)}var Grt=dfn;function ufn(s){var t=typeof s;return s!=null&&(t=="object"||t=="function")}var k6=ufn;const SK=au(k6);var hfn=FT,mfn=k6,ffn="[object AsyncFunction]",pfn="[object Function]",gfn="[object GeneratorFunction]",xfn="[object Proxy]";function yfn(s){if(!mfn(s))return!1;var t=hfn(s);return t==pfn||t==gfn||t==ffn||t==xfn}var Wrt=yfn;const ic=au(Wrt);var vfn=f3,bfn=vfn["__core-js_shared__"],_fn=bfn,l9e=_fn,tjt=function(){var s=/[^.]+$/.exec(l9e&&l9e.keys&&l9e.keys.IE_PROTO||"");return s?"Symbol(src)_1."+s:""}();function wfn(s){return!!tjt&&tjt in s}var jfn=wfn,Nfn=Function.prototype,kfn=Nfn.toString;function Sfn(s){if(s!=null){try{return kfn.call(s)}catch{}try{return s+""}catch{}}return""}var XWt=Sfn,Cfn=Wrt,Afn=jfn,Efn=k6,Tfn=XWt,Mfn=/[\\^$.*+?()[\]{}|]/g,Pfn=/^\[object .+?Constructor\]$/,Ifn=Function.prototype,Lfn=Object.prototype,Rfn=Ifn.toString,Dfn=Lfn.hasOwnProperty,Ffn=RegExp("^"+Rfn.call(Dfn).replace(Mfn,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function Ofn(s){if(!Efn(s)||Afn(s))return!1;var t=Cfn(s)?Ffn:Pfn;return t.test(Tfn(s))}var zfn=Ofn;function Bfn(s,t){return s==null?void 0:s[t]}var $fn=Bfn,Ufn=zfn,qfn=$fn;function Vfn(s,t){var n=qfn(s,t);return Ufn(n)?n:void 0}var JB=Vfn,Hfn=JB,Gfn=Hfn(Object,"create"),hRe=Gfn,sjt=hRe;function Wfn(){this.__data__=sjt?sjt(null):{},this.size=0}var Kfn=Wfn;function Yfn(s){var t=this.has(s)&&delete this.__data__[s];return this.size-=t?1:0,t}var Zfn=Yfn,Xfn=hRe,Qfn="__lodash_hash_undefined__",Jfn=Object.prototype,epn=Jfn.hasOwnProperty;function tpn(s){var t=this.__data__;if(Xfn){var n=t[s];return n===Qfn?void 0:n}return epn.call(t,s)?t[s]:void 0}var spn=tpn,npn=hRe,rpn=Object.prototype,apn=rpn.hasOwnProperty;function ipn(s){var t=this.__data__;return npn?t[s]!==void 0:apn.call(t,s)}var opn=ipn,lpn=hRe,cpn="__lodash_hash_undefined__";function dpn(s,t){var n=this.__data__;return this.size+=this.has(s)?0:1,n[s]=lpn&&t===void 0?cpn:t,this}var upn=dpn,hpn=Kfn,mpn=Zfn,fpn=spn,ppn=opn,gpn=upn;function CK(s){var t=-1,n=s==null?0:s.length;for(this.clear();++t-1}var Ipn=Ppn,Lpn=mRe;function Rpn(s,t){var n=this.__data__,r=Lpn(n,s);return r<0?(++this.size,n.push([s,t])):n[r][1]=t,this}var Dpn=Rpn,Fpn=vpn,Opn=Cpn,zpn=Tpn,Bpn=Ipn,$pn=Dpn;function AK(s){var t=-1,n=s==null?0:s.length;for(this.clear();++t0?1:-1},v8=function(t){return iB(t)&&t.indexOf("%")===t.length-1},yi=function(t){return oxn(t)&&!TK(t)},uxn=function(t){return Wc(t)},C0=function(t){return yi(t)||iB(t)},hxn=0,e9=function(t){var n=++hxn;return"".concat(t||"").concat(n)},j_=function(t,n){var r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:0,a=arguments.length>3&&arguments[3]!==void 0?arguments[3]:!1;if(!yi(t)&&!iB(t))return r;var i;if(v8(t)){var l=t.indexOf("%");i=n*parseFloat(t.slice(0,l))/100}else i=+t;return TK(i)&&(i=r),a&&i>n&&(i=n),i},TP=function(t){if(!t)return null;var n=Object.keys(t);return n&&n.length?t[n[0]]:null},mxn=function(t){if(!Array.isArray(t))return!1;for(var n=t.length,r={},a=0;a=0)&&Object.prototype.propertyIsEnumerable.call(s,r)&&(n[r]=s[r])}return n}function bxn(s,t){if(s==null)return{};var n={};for(var r in s)if(Object.prototype.hasOwnProperty.call(s,r)){if(t.indexOf(r)>=0)continue;n[r]=s[r]}return n}function ZWe(s){"@babel/helpers - typeof";return ZWe=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},ZWe(s)}var cjt={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"},WE=function(t){return typeof t=="string"?t:t?t.displayName||t.name||"Component":""},djt=null,d9e=null,nat=function s(t){if(t===djt&&Array.isArray(d9e))return d9e;var n=[];return j.Children.forEach(t,function(r){Wc(r)||(sxn.isFragment(r)?n=n.concat(s(r.props.children)):n.push(r))}),d9e=n,djt=t,n};function k2(s,t){var n=[],r=[];return Array.isArray(t)?r=t.map(function(a){return WE(a)}):r=[WE(t)],nat(s).forEach(function(a){var i=N2(a,"type.displayName")||N2(a,"type.name");r.indexOf(i)!==-1&&n.push(a)}),n}function Gj(s,t){var n=k2(s,t);return n&&n[0]}var ujt=function(t){if(!t||!t.props)return!1;var n=t.props,r=n.width,a=n.height;return!(!yi(r)||r<=0||!yi(a)||a<=0)},_xn=["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"],wxn=function(t){return t&&t.type&&iB(t.type)&&_xn.indexOf(t.type)>=0},oKt=function(t){return t&&ZWe(t)==="object"&&"clipDot"in t},jxn=function(t,n,r,a){var i,l=(i=c9e==null?void 0:c9e[a])!==null&&i!==void 0?i:[];return n.startsWith("data-")||!ic(t)&&(a&&l.includes(n)||gxn.includes(n))||r&&sat.includes(n)},cl=function(t,n,r){if(!t||typeof t=="function"||typeof t=="boolean")return null;var a=t;if(j.isValidElement(t)&&(a=t.props),!SK(a))return null;var i={};return Object.keys(a).forEach(function(l){var o;jxn((o=a)===null||o===void 0?void 0:o[l],l,n,r)&&(i[l]=a[l])}),i},XWe=function s(t,n){if(t===n)return!0;var r=j.Children.count(t);if(r!==j.Children.count(n))return!1;if(r===0)return!0;if(r===1)return hjt(Array.isArray(t)?t[0]:t,Array.isArray(n)?n[0]:n);for(var a=0;a=0)&&Object.prototype.propertyIsEnumerable.call(s,r)&&(n[r]=s[r])}return n}function Axn(s,t){if(s==null)return{};var n={};for(var r in s)if(Object.prototype.hasOwnProperty.call(s,r)){if(t.indexOf(r)>=0)continue;n[r]=s[r]}return n}function JWe(s){var t=s.children,n=s.width,r=s.height,a=s.viewBox,i=s.className,l=s.style,o=s.title,c=s.desc,d=Cxn(s,Sxn),u=a||{width:n,height:r,x:0,y:0},h=rd("recharts-surface",i);return Gt.createElement("svg",QWe({},cl(d,!0,"svg"),{className:h,width:n,height:r,style:l,viewBox:"".concat(u.x," ").concat(u.y," ").concat(u.width," ").concat(u.height)}),Gt.createElement("title",null,o),Gt.createElement("desc",null,c),t)}var Exn=["children","className"];function eKe(){return eKe=Object.assign?Object.assign.bind():function(s){for(var t=1;t=0)&&Object.prototype.propertyIsEnumerable.call(s,r)&&(n[r]=s[r])}return n}function Mxn(s,t){if(s==null)return{};var n={};for(var r in s)if(Object.prototype.hasOwnProperty.call(s,r)){if(t.indexOf(r)>=0)continue;n[r]=s[r]}return n}var Cu=Gt.forwardRef(function(s,t){var n=s.children,r=s.className,a=Txn(s,Exn),i=rd("recharts-layer",r);return Gt.createElement("g",eKe({className:i},cl(a,!0),{ref:t}),n)}),cC=function(t,n){for(var r=arguments.length,a=new Array(r>2?r-2:0),i=2;ia?0:a+t),n=n>a?a:n,n<0&&(n+=a),a=t>n?0:n-t>>>0,t>>>=0;for(var i=Array(a);++r=r?s:Lxn(s,t,n)}var Dxn=Rxn,Fxn="\\ud800-\\udfff",Oxn="\\u0300-\\u036f",zxn="\\ufe20-\\ufe2f",Bxn="\\u20d0-\\u20ff",$xn=Oxn+zxn+Bxn,Uxn="\\ufe0e\\ufe0f",qxn="\\u200d",Vxn=RegExp("["+qxn+Fxn+$xn+Uxn+"]");function Hxn(s){return Vxn.test(s)}var lKt=Hxn;function Gxn(s){return s.split("")}var Wxn=Gxn,cKt="\\ud800-\\udfff",Kxn="\\u0300-\\u036f",Yxn="\\ufe20-\\ufe2f",Zxn="\\u20d0-\\u20ff",Xxn=Kxn+Yxn+Zxn,Qxn="\\ufe0e\\ufe0f",Jxn="["+cKt+"]",tKe="["+Xxn+"]",sKe="\\ud83c[\\udffb-\\udfff]",eyn="(?:"+tKe+"|"+sKe+")",dKt="[^"+cKt+"]",uKt="(?:\\ud83c[\\udde6-\\uddff]){2}",hKt="[\\ud800-\\udbff][\\udc00-\\udfff]",tyn="\\u200d",mKt=eyn+"?",fKt="["+Qxn+"]?",syn="(?:"+tyn+"(?:"+[dKt,uKt,hKt].join("|")+")"+fKt+mKt+")*",nyn=fKt+mKt+syn,ryn="(?:"+[dKt+tKe+"?",tKe,uKt,hKt,Jxn].join("|")+")",ayn=RegExp(sKe+"(?="+sKe+")|"+ryn+nyn,"g");function iyn(s){return s.match(ayn)||[]}var oyn=iyn,lyn=Wxn,cyn=lKt,dyn=oyn;function uyn(s){return cyn(s)?dyn(s):lyn(s)}var hyn=uyn,myn=Dxn,fyn=lKt,pyn=hyn,gyn=tKt;function xyn(s){return function(t){t=gyn(t);var n=fyn(t)?pyn(t):void 0,r=n?n[0]:t.charAt(0),a=n?myn(n,1).join(""):t.slice(1);return r[s]()+a}}var yyn=xyn,vyn=yyn,byn=vyn("toUpperCase"),_yn=byn;const CRe=au(_yn);function Hf(s){return function(){return s}}const pKt=Math.cos,KTe=Math.sin,CC=Math.sqrt,YTe=Math.PI,ARe=2*YTe,nKe=Math.PI,rKe=2*nKe,OO=1e-6,wyn=rKe-OO;function gKt(s){this._+=s[0];for(let t=1,n=s.length;t=0))throw new Error(`invalid digits: ${s}`);if(t>15)return gKt;const n=10**t;return function(r){this._+=r[0];for(let a=1,i=r.length;aOO)if(!(Math.abs(h*c-d*u)>OO)||!i)this._append`L${this._x1=t},${this._y1=n}`;else{let f=r-l,g=a-o,x=c*c+d*d,y=f*f+g*g,v=Math.sqrt(x),b=Math.sqrt(m),w=i*Math.tan((nKe-Math.acos((x+m-y)/(2*v*b)))/2),S=w/b,C=w/v;Math.abs(S-1)>OO&&this._append`L${t+S*u},${n+S*h}`,this._append`A${i},${i},0,0,${+(h*f>u*g)},${this._x1=t+C*c},${this._y1=n+C*d}`}}arc(t,n,r,a,i,l){if(t=+t,n=+n,r=+r,l=!!l,r<0)throw new Error(`negative radius: ${r}`);let o=r*Math.cos(a),c=r*Math.sin(a),d=t+o,u=n+c,h=1^l,m=l?a-i:i-a;this._x1===null?this._append`M${d},${u}`:(Math.abs(this._x1-d)>OO||Math.abs(this._y1-u)>OO)&&this._append`L${d},${u}`,r&&(m<0&&(m=m%rKe+rKe),m>wyn?this._append`A${r},${r},0,1,${h},${t-o},${n-c}A${r},${r},0,1,${h},${this._x1=d},${this._y1=u}`:m>OO&&this._append`A${r},${r},0,${+(m>=nKe)},${h},${this._x1=t+r*Math.cos(i)},${this._y1=n+r*Math.sin(i)}`)}rect(t,n,r,a){this._append`M${this._x0=this._x1=+t},${this._y0=this._y1=+n}h${r=+r}v${+a}h${-r}Z`}toString(){return this._}}function rat(s){let t=3;return s.digits=function(n){if(!arguments.length)return t;if(n==null)t=null;else{const r=Math.floor(n);if(!(r>=0))throw new RangeError(`invalid digits: ${n}`);t=r}return s},()=>new Nyn(t)}function aat(s){return typeof s=="object"&&"length"in s?s:Array.from(s)}function xKt(s){this._context=s}xKt.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 ERe(s){return new xKt(s)}function yKt(s){return s[0]}function vKt(s){return s[1]}function bKt(s,t){var n=Hf(!0),r=null,a=ERe,i=null,l=rat(o);s=typeof s=="function"?s:s===void 0?yKt:Hf(s),t=typeof t=="function"?t:t===void 0?vKt:Hf(t);function o(c){var d,u=(c=aat(c)).length,h,m=!1,f;for(r==null&&(i=a(f=l())),d=0;d<=u;++d)!(d=f;--g)o.point(w[g],S[g]);o.lineEnd(),o.areaEnd()}v&&(w[m]=+s(y,m,h),S[m]=+t(y,m,h),o.point(r?+r(y,m,h):w[m],n?+n(y,m,h):S[m]))}if(b)return o=null,b+""||null}function u(){return bKt().defined(a).curve(l).context(i)}return d.x=function(h){return arguments.length?(s=typeof h=="function"?h:Hf(+h),r=null,d):s},d.x0=function(h){return arguments.length?(s=typeof h=="function"?h:Hf(+h),d):s},d.x1=function(h){return arguments.length?(r=h==null?null:typeof h=="function"?h:Hf(+h),d):r},d.y=function(h){return arguments.length?(t=typeof h=="function"?h:Hf(+h),n=null,d):t},d.y0=function(h){return arguments.length?(t=typeof h=="function"?h:Hf(+h),d):t},d.y1=function(h){return arguments.length?(n=h==null?null:typeof h=="function"?h:Hf(+h),d):n},d.lineX0=d.lineY0=function(){return u().x(s).y(t)},d.lineY1=function(){return u().x(s).y(n)},d.lineX1=function(){return u().x(r).y(t)},d.defined=function(h){return arguments.length?(a=typeof h=="function"?h:Hf(!!h),d):a},d.curve=function(h){return arguments.length?(l=h,i!=null&&(o=l(i)),d):l},d.context=function(h){return arguments.length?(h==null?i=o=null:o=l(i=h),d):i},d}class _Kt{constructor(t,n){this._context=t,this._x=n}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,n){switch(t=+t,n=+n,this._point){case 0:{this._point=1,this._line?this._context.lineTo(t,n):this._context.moveTo(t,n);break}case 1:this._point=2;default:{this._x?this._context.bezierCurveTo(this._x0=(this._x0+t)/2,this._y0,this._x0,n,t,n):this._context.bezierCurveTo(this._x0,this._y0=(this._y0+n)/2,t,this._y0,t,n);break}}this._x0=t,this._y0=n}}function kyn(s){return new _Kt(s,!0)}function Syn(s){return new _Kt(s,!1)}const iat={draw(s,t){const n=CC(t/YTe);s.moveTo(n,0),s.arc(0,0,n,0,ARe)}},Cyn={draw(s,t){const n=CC(t/5)/2;s.moveTo(-3*n,-n),s.lineTo(-n,-n),s.lineTo(-n,-3*n),s.lineTo(n,-3*n),s.lineTo(n,-n),s.lineTo(3*n,-n),s.lineTo(3*n,n),s.lineTo(n,n),s.lineTo(n,3*n),s.lineTo(-n,3*n),s.lineTo(-n,n),s.lineTo(-3*n,n),s.closePath()}},wKt=CC(1/3),Ayn=wKt*2,Eyn={draw(s,t){const n=CC(t/Ayn),r=n*wKt;s.moveTo(0,-n),s.lineTo(r,0),s.lineTo(0,n),s.lineTo(-r,0),s.closePath()}},Tyn={draw(s,t){const n=CC(t),r=-n/2;s.rect(r,r,n,n)}},Myn=.8908130915292852,jKt=KTe(YTe/10)/KTe(7*YTe/10),Pyn=KTe(ARe/10)*jKt,Iyn=-pKt(ARe/10)*jKt,Lyn={draw(s,t){const n=CC(t*Myn),r=Pyn*n,a=Iyn*n;s.moveTo(0,-n),s.lineTo(r,a);for(let i=1;i<5;++i){const l=ARe*i/5,o=pKt(l),c=KTe(l);s.lineTo(c*n,-o*n),s.lineTo(o*r-c*a,c*r+o*a)}s.closePath()}},u9e=CC(3),Ryn={draw(s,t){const n=-CC(t/(u9e*3));s.moveTo(0,n*2),s.lineTo(-u9e*n,-n),s.lineTo(u9e*n,-n),s.closePath()}},lN=-.5,cN=CC(3)/2,aKe=1/CC(12),Dyn=(aKe/2+1)*3,Fyn={draw(s,t){const n=CC(t/Dyn),r=n/2,a=n*aKe,i=r,l=n*aKe+n,o=-i,c=l;s.moveTo(r,a),s.lineTo(i,l),s.lineTo(o,c),s.lineTo(lN*r-cN*a,cN*r+lN*a),s.lineTo(lN*i-cN*l,cN*i+lN*l),s.lineTo(lN*o-cN*c,cN*o+lN*c),s.lineTo(lN*r+cN*a,lN*a-cN*r),s.lineTo(lN*i+cN*l,lN*l-cN*i),s.lineTo(lN*o+cN*c,lN*c-cN*o),s.closePath()}};function Oyn(s,t){let n=null,r=rat(a);s=typeof s=="function"?s:Hf(s||iat),t=typeof t=="function"?t:Hf(t===void 0?64:+t);function a(){let i;if(n||(n=i=r()),s.apply(this,arguments).draw(n,+t.apply(this,arguments)),i)return n=null,i+""||null}return a.type=function(i){return arguments.length?(s=typeof i=="function"?i:Hf(i),a):s},a.size=function(i){return arguments.length?(t=typeof i=="function"?i:Hf(+i),a):t},a.context=function(i){return arguments.length?(n=i??null,a):n},a}function ZTe(){}function XTe(s,t,n){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+n)/6)}function NKt(s){this._context=s}NKt.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:XTe(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:XTe(this,s,t);break}this._x0=this._x1,this._x1=s,this._y0=this._y1,this._y1=t}};function zyn(s){return new NKt(s)}function kKt(s){this._context=s}kKt.prototype={areaStart:ZTe,areaEnd:ZTe,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:XTe(this,s,t);break}this._x0=this._x1,this._x1=s,this._y0=this._y1,this._y1=t}};function Byn(s){return new kKt(s)}function SKt(s){this._context=s}SKt.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 n=(this._x0+4*this._x1+s)/6,r=(this._y0+4*this._y1+t)/6;this._line?this._context.lineTo(n,r):this._context.moveTo(n,r);break;case 3:this._point=4;default:XTe(this,s,t);break}this._x0=this._x1,this._x1=s,this._y0=this._y1,this._y1=t}};function $yn(s){return new SKt(s)}function CKt(s){this._context=s}CKt.prototype={areaStart:ZTe,areaEnd:ZTe,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 Uyn(s){return new CKt(s)}function fjt(s){return s<0?-1:1}function pjt(s,t,n){var r=s._x1-s._x0,a=t-s._x1,i=(s._y1-s._y0)/(r||a<0&&-0),l=(n-s._y1)/(a||r<0&&-0),o=(i*a+l*r)/(r+a);return(fjt(i)+fjt(l))*Math.min(Math.abs(i),Math.abs(l),.5*Math.abs(o))||0}function gjt(s,t){var n=s._x1-s._x0;return n?(3*(s._y1-s._y0)/n-t)/2:t}function h9e(s,t,n){var r=s._x0,a=s._y0,i=s._x1,l=s._y1,o=(i-r)/3;s._context.bezierCurveTo(r+o,a+o*t,i-o,l-o*n,i,l)}function QTe(s){this._context=s}QTe.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:h9e(this,this._t0,gjt(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 n=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,h9e(this,gjt(this,n=pjt(this,s,t)),n);break;default:h9e(this,this._t0,n=pjt(this,s,t));break}this._x0=this._x1,this._x1=s,this._y0=this._y1,this._y1=t,this._t0=n}}};function AKt(s){this._context=new EKt(s)}(AKt.prototype=Object.create(QTe.prototype)).point=function(s,t){QTe.prototype.point.call(this,t,s)};function EKt(s){this._context=s}EKt.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,n,r,a,i){this._context.bezierCurveTo(t,s,r,n,i,a)}};function qyn(s){return new QTe(s)}function Vyn(s){return new AKt(s)}function TKt(s){this._context=s}TKt.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,n=s.length;if(n)if(this._line?this._context.lineTo(s[0],t[0]):this._context.moveTo(s[0],t[0]),n===2)this._context.lineTo(s[1],t[1]);else for(var r=xjt(s),a=xjt(t),i=0,l=1;l=0;--t)a[t]=(l[t]-a[t+1])/i[t];for(i[n-1]=(s[n]+a[n-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 n=this._x*(1-this._t)+s*this._t;this._context.lineTo(n,this._y),this._context.lineTo(n,t)}break}}this._x=s,this._y=t}};function Gyn(s){return new TRe(s,.5)}function Wyn(s){return new TRe(s,0)}function Kyn(s){return new TRe(s,1)}function qG(s,t){if((l=s.length)>1)for(var n=1,r,a,i=s[t[0]],l,o=i.length;n=0;)n[t]=t;return n}function Yyn(s,t){return s[t]}function Zyn(s){const t=[];return t.key=s,t}function Xyn(){var s=Hf([]),t=iKe,n=qG,r=Yyn;function a(i){var l=Array.from(s.apply(this,arguments),Zyn),o,c=l.length,d=-1,u;for(const h of i)for(o=0,++d;o0){for(var n,r,a=0,i=s[0].length,l;a0){for(var n=0,r=s[t[0]],a,i=r.length;n0)||!((i=(a=s[t[0]]).length)>0))){for(var n=0,r=1,a,i,l;r=0)&&Object.prototype.propertyIsEnumerable.call(s,r)&&(n[r]=s[r])}return n}function i0n(s,t){if(s==null)return{};var n={};for(var r in s)if(Object.prototype.hasOwnProperty.call(s,r)){if(t.indexOf(r)>=0)continue;n[r]=s[r]}return n}var MKt={symbolCircle:iat,symbolCross:Cyn,symbolDiamond:Eyn,symbolSquare:Tyn,symbolStar:Lyn,symbolTriangle:Ryn,symbolWye:Fyn},o0n=Math.PI/180,l0n=function(t){var n="symbol".concat(CRe(t));return MKt[n]||iat},c0n=function(t,n,r){if(n==="area")return t;switch(r){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*o0n;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}},d0n=function(t,n){MKt["symbol".concat(CRe(t))]=n},oat=function(t){var n=t.type,r=n===void 0?"circle":n,a=t.size,i=a===void 0?64:a,l=t.sizeType,o=l===void 0?"area":l,c=a0n(t,t0n),d=vjt(vjt({},c),{},{type:r,size:i,sizeType:o}),u=function(){var y=l0n(r),v=Oyn().type(y).size(c0n(i,o,r));return v()},h=d.className,m=d.cx,f=d.cy,g=cl(d,!0);return m===+m&&f===+f&&i===+i?Gt.createElement("path",oKe({},g,{className:rd("recharts-symbols",h),transform:"translate(".concat(m,", ").concat(f,")"),d:u()})):null};oat.registerSymbol=d0n;function VG(s){"@babel/helpers - typeof";return VG=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},VG(s)}function lKe(){return lKe=Object.assign?Object.assign.bind():function(s){for(var t=1;t`);var b=f.inactive?d:f.color;return Gt.createElement("li",lKe({className:y,style:h,key:"legend-item-".concat(g)},oB(r.props,f,g)),Gt.createElement(JWe,{width:l,height:l,viewBox:u,style:m},r.renderIcon(f)),Gt.createElement("span",{className:"recharts-legend-item-text",style:{color:b}},x?x(v,f,g):v))})}},{key:"render",value:function(){var r=this.props,a=r.payload,i=r.layout,l=r.align;if(!a||!a.length)return null;var o={padding:0,margin:0,textAlign:i==="horizontal"?l:"left"};return Gt.createElement("ul",{className:"recharts-default-legend",style:o},this.renderItems())}}])}(j.PureComponent);Rse(lat,"displayName","Legend");Rse(lat,"defaultProps",{iconSize:14,layout:"horizontal",align:"center",verticalAlign:"middle",inactiveColor:"#ccc"});var b0n=fRe;function _0n(){this.__data__=new b0n,this.size=0}var w0n=_0n;function j0n(s){var t=this.__data__,n=t.delete(s);return this.size=t.size,n}var N0n=j0n;function k0n(s){return this.__data__.get(s)}var S0n=k0n;function C0n(s){return this.__data__.has(s)}var A0n=C0n,E0n=fRe,T0n=Yrt,M0n=Zrt,P0n=200;function I0n(s,t){var n=this.__data__;if(n instanceof E0n){var r=n.__data__;if(!T0n||r.lengtho))return!1;var d=i.get(s),u=i.get(t);if(d&&u)return d==t&&u==s;var h=-1,m=!0,f=n&tvn?new X0n:void 0;for(i.set(s,t),i.set(t,s);++h-1&&s%1==0&&s-1&&s%1==0&&s<=abn}var hat=ibn,obn=FT,lbn=hat,cbn=OT,dbn="[object Arguments]",ubn="[object Array]",hbn="[object Boolean]",mbn="[object Date]",fbn="[object Error]",pbn="[object Function]",gbn="[object Map]",xbn="[object Number]",ybn="[object Object]",vbn="[object RegExp]",bbn="[object Set]",_bn="[object String]",wbn="[object WeakMap]",jbn="[object ArrayBuffer]",Nbn="[object DataView]",kbn="[object Float32Array]",Sbn="[object Float64Array]",Cbn="[object Int8Array]",Abn="[object Int16Array]",Ebn="[object Int32Array]",Tbn="[object Uint8Array]",Mbn="[object Uint8ClampedArray]",Pbn="[object Uint16Array]",Ibn="[object Uint32Array]",vp={};vp[kbn]=vp[Sbn]=vp[Cbn]=vp[Abn]=vp[Ebn]=vp[Tbn]=vp[Mbn]=vp[Pbn]=vp[Ibn]=!0;vp[dbn]=vp[ubn]=vp[jbn]=vp[hbn]=vp[Nbn]=vp[mbn]=vp[fbn]=vp[pbn]=vp[gbn]=vp[xbn]=vp[ybn]=vp[vbn]=vp[bbn]=vp[_bn]=vp[wbn]=!1;function Lbn(s){return cbn(s)&&lbn(s.length)&&!!vp[obn(s)]}var Rbn=Lbn;function Dbn(s){return function(t){return s(t)}}var UKt=Dbn,sMe={exports:{}};sMe.exports;(function(s,t){var n=YWt,r=t&&!t.nodeType&&t,a=r&&!0&&s&&!s.nodeType&&s,i=a&&a.exports===r,l=i&&n.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})(sMe,sMe.exports);var Fbn=sMe.exports,Obn=Rbn,zbn=UKt,Sjt=Fbn,Cjt=Sjt&&Sjt.isTypedArray,Bbn=Cjt?zbn(Cjt):Obn,qKt=Bbn,$bn=Vvn,Ubn=dat,qbn=Zw,Vbn=$Kt,Hbn=uat,Gbn=qKt,Wbn=Object.prototype,Kbn=Wbn.hasOwnProperty;function Ybn(s,t){var n=qbn(s),r=!n&&Ubn(s),a=!n&&!r&&Vbn(s),i=!n&&!r&&!a&&Gbn(s),l=n||r||a||i,o=l?$bn(s.length,String):[],c=o.length;for(var d in s)(t||Kbn.call(s,d))&&!(l&&(d=="length"||a&&(d=="offset"||d=="parent")||i&&(d=="buffer"||d=="byteLength"||d=="byteOffset")||Hbn(d,c)))&&o.push(d);return o}var Zbn=Ybn,Xbn=Object.prototype;function Qbn(s){var t=s&&s.constructor,n=typeof t=="function"&&t.prototype||Xbn;return s===n}var Jbn=Qbn;function e1n(s,t){return function(n){return s(t(n))}}var VKt=e1n,t1n=VKt,s1n=t1n(Object.keys,Object),n1n=s1n,r1n=Jbn,a1n=n1n,i1n=Object.prototype,o1n=i1n.hasOwnProperty;function l1n(s){if(!r1n(s))return a1n(s);var t=[];for(var n in Object(s))o1n.call(s,n)&&n!="constructor"&&t.push(n);return t}var c1n=l1n,d1n=Wrt,u1n=hat;function h1n(s){return s!=null&&u1n(s.length)&&!d1n(s)}var Cie=h1n,m1n=Zbn,f1n=c1n,p1n=Cie;function g1n(s){return p1n(s)?m1n(s):f1n(s)}var MRe=g1n,x1n=Pvn,y1n=Uvn,v1n=MRe;function b1n(s){return x1n(s,v1n,y1n)}var _1n=b1n,Ajt=_1n,w1n=1,j1n=Object.prototype,N1n=j1n.hasOwnProperty;function k1n(s,t,n,r,a,i){var l=n&w1n,o=Ajt(s),c=o.length,d=Ajt(t),u=d.length;if(c!=u&&!l)return!1;for(var h=c;h--;){var m=o[h];if(!(l?m in t:N1n.call(t,m)))return!1}var f=i.get(s),g=i.get(t);if(f&&g)return f==t&&g==s;var x=!0;i.set(s,t),i.set(t,s);for(var y=l;++h-1}var jwn=wwn;function Nwn(s,t,n){for(var r=-1,a=s==null?0:s.length;++r=zwn){var d=t?null:Fwn(s);if(d)return Own(d);l=!1,a=Dwn,c=new Iwn}else c=t?[]:o;e:for(;++r=0)&&Object.prototype.propertyIsEnumerable.call(s,r)&&(n[r]=s[r])}return n}function tjn(s,t){if(s==null)return{};var n={};for(var r in s)if(Object.prototype.hasOwnProperty.call(s,r)){if(t.indexOf(r)>=0)continue;n[r]=s[r]}return n}function sjn(s){return s.value}function njn(s,t){if(Gt.isValidElement(s))return Gt.cloneElement(s,t);if(typeof s=="function")return Gt.createElement(s,t);t.ref;var n=ejn(t,Gwn);return Gt.createElement(lat,n)}var Vjt=1,MV=function(s){function t(){var n;Wwn(this,t);for(var r=arguments.length,a=new Array(r),i=0;iVjt||Math.abs(a.height-this.lastBoundingBox.height)>Vjt)&&(this.lastBoundingBox.width=a.width,this.lastBoundingBox.height=a.height,r&&r(a)):(this.lastBoundingBox.width!==-1||this.lastBoundingBox.height!==-1)&&(this.lastBoundingBox.width=-1,this.lastBoundingBox.height=-1,r&&r(null))}},{key:"getBBoxSnapshot",value:function(){return this.lastBoundingBox.width>=0&&this.lastBoundingBox.height>=0?rA({},this.lastBoundingBox):{width:0,height:0}}},{key:"getDefaultPosition",value:function(r){var a=this.props,i=a.layout,l=a.align,o=a.verticalAlign,c=a.margin,d=a.chartWidth,u=a.chartHeight,h,m;if(!r||(r.left===void 0||r.left===null)&&(r.right===void 0||r.right===null))if(l==="center"&&i==="vertical"){var f=this.getBBoxSnapshot();h={left:((d||0)-f.width)/2}}else h=l==="right"?{right:c&&c.right||0}:{left:c&&c.left||0};if(!r||(r.top===void 0||r.top===null)&&(r.bottom===void 0||r.bottom===null))if(o==="middle"){var g=this.getBBoxSnapshot();m={top:((u||0)-g.height)/2}}else m=o==="bottom"?{bottom:c&&c.bottom||0}:{top:c&&c.top||0};return rA(rA({},h),m)}},{key:"render",value:function(){var r=this,a=this.props,i=a.content,l=a.width,o=a.height,c=a.wrapperStyle,d=a.payloadUniqBy,u=a.payload,h=rA(rA({position:"absolute",width:l||"auto",height:o||"auto"},this.getDefaultPosition(c)),c);return Gt.createElement("div",{className:"recharts-legend-wrapper",style:h,ref:function(f){r.wrapperNode=f}},njn(i,rA(rA({},this.props),{},{payload:XKt(u,d,sjn)})))}}],[{key:"getWithHeight",value:function(r,a){var i=rA(rA({},this.defaultProps),r.props),l=i.layout;return l==="vertical"&&yi(r.props.height)?{height:r.props.height}:l==="horizontal"?{width:r.props.width||a}:null}}])}(j.PureComponent);PRe(MV,"displayName","Legend");PRe(MV,"defaultProps",{iconSize:14,layout:"horizontal",align:"center",verticalAlign:"bottom"});var Hjt=Sie,rjn=dat,ajn=Zw,Gjt=Hjt?Hjt.isConcatSpreadable:void 0;function ijn(s){return ajn(s)||rjn(s)||!!(Gjt&&s&&s[Gjt])}var ojn=ijn,ljn=zKt,cjn=ojn;function eYt(s,t,n,r,a){var i=-1,l=s.length;for(n||(n=cjn),a||(a=[]);++i0&&n(o)?t>1?eYt(o,t-1,n,r,a):ljn(a,o):r||(a[a.length]=o)}return a}var tYt=eYt;function djn(s){return function(t,n,r){for(var a=-1,i=Object(t),l=r(t),o=l.length;o--;){var c=l[s?o:++a];if(n(i[c],c,i)===!1)break}return t}}var ujn=djn,hjn=ujn,mjn=hjn(),fjn=mjn,pjn=fjn,gjn=MRe;function xjn(s,t){return s&&pjn(s,t,gjn)}var sYt=xjn,yjn=Cie;function vjn(s,t){return function(n,r){if(n==null)return n;if(!yjn(n))return s(n,r);for(var a=n.length,i=t?a:-1,l=Object(n);(t?i--:++it||i&&l&&c&&!o&&!d||r&&l&&c||!n&&c||!a)return 1;if(!r&&!i&&!d&&s=o)return c;var d=n[r];return c*(d=="desc"?-1:1)}}return s.index-t.index}var Ijn=Pjn,g9e=Qrt,Ljn=Jrt,Rjn=p3,Djn=nYt,Fjn=Ajn,Ojn=UKt,zjn=Ijn,Bjn=IK,$jn=Zw;function Ujn(s,t,n){t.length?t=g9e(t,function(i){return $jn(i)?function(l){return Ljn(l,i.length===1?i[0]:i)}:i}):t=[Bjn];var r=-1;t=g9e(t,Ojn(Rjn));var a=Djn(s,function(i,l,o){var c=g9e(t,function(d){return d(i)});return{criteria:c,index:++r,value:i}});return Fjn(a,function(i,l){return zjn(i,l,n)})}var qjn=Ujn;function Vjn(s,t,n){switch(n.length){case 0:return s.call(t);case 1:return s.call(t,n[0]);case 2:return s.call(t,n[0],n[1]);case 3:return s.call(t,n[0],n[1],n[2])}return s.apply(t,n)}var Hjn=Vjn,Gjn=Hjn,Kjt=Math.max;function Wjn(s,t,n){return t=Kjt(t===void 0?s.length-1:t,0),function(){for(var r=arguments,a=-1,i=Kjt(r.length-t,0),l=Array(i);++a0){if(++t>=n2n)return arguments[0]}else t=0;return s.apply(void 0,arguments)}}var o2n=i2n,l2n=s2n,c2n=o2n,d2n=c2n(l2n),u2n=d2n,h2n=IK,m2n=Kjn,f2n=u2n;function p2n(s,t){return f2n(m2n(s,t,h2n),s+"")}var g2n=p2n,x2n=Krt,y2n=Cie,v2n=uat,b2n=k6;function _2n(s,t,n){if(!b2n(n))return!1;var r=typeof t;return(r=="number"?y2n(n)&&v2n(t,n.length):r=="string"&&t in n)?x2n(n[t],s):!1}var IRe=_2n,w2n=tYt,j2n=qjn,N2n=g2n,Zjt=IRe,k2n=N2n(function(s,t){if(s==null)return[];var n=t.length;return n>1&&Zjt(s,t[0],t[1])?t=[]:n>2&&Zjt(t[0],t[1],t[2])&&(t=[t[0]]),j2n(s,w2n(t,1),[])}),S2n=k2n;const pat=au(S2n);function Dse(s){"@babel/helpers - typeof";return Dse=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},Dse(s)}function gKe(){return gKe=Object.assign?Object.assign.bind():function(s){for(var t=1;ts.length)&&(t=s.length);for(var n=0,r=new Array(t);n=t.x),"".concat(KZ,"-left"),yi(n)&&t&&yi(t.x)&&n=t.y),"".concat(KZ,"-top"),yi(r)&&t&&yi(t.y)&&rx?Math.max(u,c[r]):Math.max(h,c[r])}function $2n(s){var t=s.translateX,n=s.translateY,r=s.useTranslate3d;return{transform:r?"translate3d(".concat(t,"px, ").concat(n,"px, 0)"):"translate(".concat(t,"px, ").concat(n,"px)")}}function U2n(s){var t=s.allowEscapeViewBox,n=s.coordinate,r=s.offsetTopLeft,a=s.position,i=s.reverseDirection,l=s.tooltipBox,o=s.useTranslate3d,c=s.viewBox,d,u,h;return l.height>0&&l.width>0&&n?(u=Jjt({allowEscapeViewBox:t,coordinate:n,key:"x",offsetTopLeft:r,position:a,reverseDirection:i,tooltipDimension:l.width,viewBox:c,viewBoxDimension:c.width}),h=Jjt({allowEscapeViewBox:t,coordinate:n,key:"y",offsetTopLeft:r,position:a,reverseDirection:i,tooltipDimension:l.height,viewBox:c,viewBoxDimension:c.height}),d=$2n({translateX:u,translateY:h,useTranslate3d:o})):d=z2n,{cssProperties:d,cssClasses:B2n({translateX:u,translateY:h,coordinate:n})}}function GG(s){"@babel/helpers - typeof";return GG=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},GG(s)}function e2t(s,t){var n=Object.keys(s);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(s);t&&(r=r.filter(function(a){return Object.getOwnPropertyDescriptor(s,a).enumerable})),n.push.apply(n,r)}return n}function t2t(s){for(var t=1;ts2t||Math.abs(r.height-this.state.lastBoundingBox.height)>s2t)&&this.setState({lastBoundingBox:{width:r.width,height:r.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 r,a;this.props.active&&this.updateBBox(),this.state.dismissed&&(((r=this.props.coordinate)===null||r===void 0?void 0:r.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 r=this,a=this.props,i=a.active,l=a.allowEscapeViewBox,o=a.animationDuration,c=a.animationEasing,d=a.children,u=a.coordinate,h=a.hasPayload,m=a.isAnimationActive,f=a.offset,g=a.position,x=a.reverseDirection,y=a.useTranslate3d,v=a.viewBox,b=a.wrapperStyle,w=U2n({allowEscapeViewBox:l,coordinate:u,offsetTopLeft:f,position:g,reverseDirection:x,tooltipBox:this.state.lastBoundingBox,useTranslate3d:y,viewBox:v}),S=w.cssClasses,C=w.cssProperties,E=t2t(t2t({transition:m&&i?"transform ".concat(o,"ms ").concat(c):void 0},C),{},{pointerEvents:"none",visibility:!this.state.dismissed&&i&&h?"visible":"hidden",position:"absolute",top:0,left:0},b);return Gt.createElement("div",{tabIndex:-1,className:S,style:E,ref:function(P){r.wrapperNode=P}},d)}}])}(j.PureComponent),Q2n=function(){return!(typeof window<"u"&&window.document&&window.document.createElement&&window.setTimeout)},S6={isSsr:Q2n()};function WG(s){"@babel/helpers - typeof";return WG=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},WG(s)}function n2t(s,t){var n=Object.keys(s);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(s);t&&(r=r.filter(function(a){return Object.getOwnPropertyDescriptor(s,a).enumerable})),n.push.apply(n,r)}return n}function r2t(s){for(var t=1;t0;return Gt.createElement(X2n,{allowEscapeViewBox:l,animationDuration:o,animationEasing:c,isAnimationActive:m,active:i,coordinate:u,hasPayload:E,offset:f,position:y,reverseDirection:v,useTranslate3d:b,viewBox:w,wrapperStyle:S},lNn(d,r2t(r2t({},this.props),{},{payload:C})))}}])}(j.PureComponent);gat(Ag,"displayName","Tooltip");gat(Ag,"defaultProps",{accessibilityLayer:!1,allowEscapeViewBox:{x:!1,y:!1},animationDuration:400,animationEasing:"ease",contentStyle:{},coordinate:{x:0,y:0},cursor:!0,cursorStyle:{},filterNull:!0,isAnimationActive:!S6.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 cNn=f3,dNn=function(){return cNn.Date.now()},uNn=dNn,hNn=/\s/;function mNn(s){for(var t=s.length;t--&&hNn.test(s.charAt(t)););return t}var fNn=mNn,pNn=fNn,gNn=/^\s+/;function xNn(s){return s&&s.slice(0,pNn(s)+1).replace(gNn,"")}var yNn=xNn,vNn=yNn,a2t=k6,bNn=kK,i2t=NaN,_Nn=/^[-+]0x[0-9a-f]+$/i,wNn=/^0b[01]+$/i,jNn=/^0o[0-7]+$/i,NNn=parseInt;function kNn(s){if(typeof s=="number")return s;if(bNn(s))return i2t;if(a2t(s)){var t=typeof s.valueOf=="function"?s.valueOf():s;s=a2t(t)?t+"":t}if(typeof s!="string")return s===0?s:+s;s=vNn(s);var n=wNn.test(s);return n||jNn.test(s)?NNn(s.slice(2),n?2:8):_Nn.test(s)?i2t:+s}var cYt=kNn,SNn=k6,y9e=uNn,o2t=cYt,CNn="Expected a function",ANn=Math.max,ENn=Math.min;function TNn(s,t,n){var r,a,i,l,o,c,d=0,u=!1,h=!1,m=!0;if(typeof s!="function")throw new TypeError(CNn);t=o2t(t)||0,SNn(n)&&(u=!!n.leading,h="maxWait"in n,i=h?ANn(o2t(n.maxWait)||0,t):i,m="trailing"in n?!!n.trailing:m);function f(E){var I=r,P=a;return r=a=void 0,d=E,l=s.apply(P,I),l}function g(E){return d=E,o=setTimeout(v,t),u?f(E):l}function x(E){var I=E-c,P=E-d,R=t-I;return h?ENn(R,i-P):R}function y(E){var I=E-c,P=E-d;return c===void 0||I>=t||I<0||h&&P>=i}function v(){var E=y9e();if(y(E))return b(E);o=setTimeout(v,x(E))}function b(E){return o=void 0,m&&r?f(E):(r=a=void 0,l)}function w(){o!==void 0&&clearTimeout(o),d=0,r=c=a=o=void 0}function S(){return o===void 0?l:b(y9e())}function C(){var E=y9e(),I=y(E);if(r=arguments,a=this,c=E,I){if(o===void 0)return g(c);if(h)return clearTimeout(o),o=setTimeout(v,t),f(c)}return o===void 0&&(o=setTimeout(v,t)),l}return C.cancel=w,C.flush=S,C}var MNn=TNn,PNn=MNn,INn=k6,LNn="Expected a function";function RNn(s,t,n){var r=!0,a=!0;if(typeof s!="function")throw new TypeError(LNn);return INn(n)&&(r="leading"in n?!!n.leading:r,a="trailing"in n?!!n.trailing:a),PNn(s,t,{leading:r,maxWait:t,trailing:a})}var DNn=RNn;const dYt=au(DNn);function Ose(s){"@babel/helpers - typeof";return Ose=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},Ose(s)}function l2t(s,t){var n=Object.keys(s);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(s);t&&(r=r.filter(function(a){return Object.getOwnPropertyDescriptor(s,a).enumerable})),n.push.apply(n,r)}return n}function Hde(s){for(var t=1;ts.length)&&(t=s.length);for(var n=0,r=new Array(t);n0&&(W=dYt(W,x,{trailing:!0,leading:!1}));var V=new ResizeObserver(W),G=C.current.getBoundingClientRect(),Y=G.width,X=G.height;return O(Y,X),V.observe(C.current),function(){V.disconnect()}},[O,x]);var U=j.useMemo(function(){var W=R.containerWidth,V=R.containerHeight;if(W<0||V<0)return null;cC(v8(l)||v8(c),`The width(%s) and height(%s) are both fixed numbers, maybe you don't need to use a ResponsiveContainer.`,l,c),cC(!n||n>0,"The aspect(%s) must be greater than zero.",n);var G=v8(l)?W:l,Y=v8(c)?V:c;n&&n>0&&(G?Y=G/n:Y&&(G=Y*n),m&&Y>m&&(Y=m)),cC(G>0||Y>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.`,G,Y,l,c,u,h,n);var X=!Array.isArray(f)&&WE(f.type).endsWith("Chart");return Gt.Children.map(f,function(ae){return Gt.isValidElement(ae)?j.cloneElement(ae,Hde({width:G,height:Y},X?{style:Hde({height:"100%",width:"100%",maxHeight:Y,maxWidth:G},ae.props.style)}:{})):ae})},[n,f,c,m,h,u,R,l]);return Gt.createElement("div",{id:y?"".concat(y):void 0,className:rd("recharts-responsive-container",v),style:Hde(Hde({},S),{},{width:l,height:c,minWidth:u,minHeight:h,maxHeight:m}),ref:C},U)}),t9=function(t){return null};t9.displayName="Cell";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 d2t(s,t){var n=Object.keys(s);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(s);t&&(r=r.filter(function(a){return Object.getOwnPropertyDescriptor(s,a).enumerable})),n.push.apply(n,r)}return n}function bKe(s){for(var t=1;t1&&arguments[1]!==void 0?arguments[1]:{};if(t==null||S6.isSsr)return{width:0,height:0};var r=ZNn(n),a=JSON.stringify({text:t,copyStyle:r});if(O$.widthCache[a])return O$.widthCache[a];try{var i=document.getElementById(u2t);i||(i=document.createElement("span"),i.setAttribute("id",u2t),i.setAttribute("aria-hidden","true"),document.body.appendChild(i));var l=bKe(bKe({},YNn),r);Object.assign(i.style,l),i.textContent="".concat(t);var o=i.getBoundingClientRect(),c={width:o.width,height:o.height};return O$.widthCache[a]=c,++O$.cacheCount>KNn&&(O$.cacheCount=0,O$.widthCache={}),c}catch{return{width:0,height:0}}},XNn=function(t){return{top:t.top+window.scrollY-document.documentElement.clientTop,left:t.left+window.scrollX-document.documentElement.clientLeft}};function Bse(s){"@babel/helpers - typeof";return Bse=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},Bse(s)}function iMe(s,t){return tkn(s)||ekn(s,t)||JNn(s,t)||QNn()}function QNn(){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 JNn(s,t){if(s){if(typeof s=="string")return h2t(s,t);var n=Object.prototype.toString.call(s).slice(8,-1);if(n==="Object"&&s.constructor&&(n=s.constructor.name),n==="Map"||n==="Set")return Array.from(s);if(n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return h2t(s,t)}}function h2t(s,t){(t==null||t>s.length)&&(t=s.length);for(var n=0,r=new Array(t);n=0)&&Object.prototype.propertyIsEnumerable.call(s,r)&&(n[r]=s[r])}return n}function pkn(s,t){if(s==null)return{};var n={};for(var r in s)if(Object.prototype.hasOwnProperty.call(s,r)){if(t.indexOf(r)>=0)continue;n[r]=s[r]}return n}function y2t(s,t){return vkn(s)||ykn(s,t)||xkn(s,t)||gkn()}function gkn(){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 xkn(s,t){if(s){if(typeof s=="string")return v2t(s,t);var n=Object.prototype.toString.call(s).slice(8,-1);if(n==="Object"&&s.constructor&&(n=s.constructor.name),n==="Map"||n==="Set")return Array.from(s);if(n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return v2t(s,t)}}function v2t(s,t){(t==null||t>s.length)&&(t=s.length);for(var n=0,r=new Array(t);n0&&arguments[0]!==void 0?arguments[0]:[];return G.reduce(function(Y,X){var ae=X.word,ie=X.width,ne=Y[Y.length-1];if(ne&&(a==null||i||ne.width+ie+rX.width?Y:X})};if(!u)return f;for(var x="…",y=function(G){var Y=h.slice(0,G),X=fYt({breakAll:d,style:c,children:Y+x}).wordsWithComputedWidth,ae=m(X),ie=ae.length>l||g(ae).width>Number(a);return[ie,ae]},v=0,b=h.length-1,w=0,S;v<=b&&w<=h.length-1;){var C=Math.floor((v+b)/2),E=C-1,I=y(E),P=y2t(I,2),R=P[0],D=P[1],O=y(C),U=y2t(O,1),W=U[0];if(!R&&!W&&(v=C+1),R&&W&&(b=C-1),!R&&W){S=D;break}w++}return S||f},b2t=function(t){var n=Wc(t)?[]:t.toString().split(mYt);return[{words:n}]},_kn=function(t){var n=t.width,r=t.scaleToFit,a=t.children,i=t.style,l=t.breakAll,o=t.maxLines;if((n||r)&&!S6.isSsr){var c,d,u=fYt({breakAll:l,children:a,style:i});if(u){var h=u.wordsWithComputedWidth,m=u.spaceWidth;c=h,d=m}else return b2t(a);return bkn({breakAll:l,children:a,maxLines:o,style:i},c,d,n,r)}return b2t(a)},_2t="#808080",lB=function(t){var n=t.x,r=n===void 0?0:n,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,u=t.scaleToFit,h=u===void 0?!1:u,m=t.textAnchor,f=m===void 0?"start":m,g=t.verticalAnchor,x=g===void 0?"end":g,y=t.fill,v=y===void 0?_2t:y,b=x2t(t,mkn),w=j.useMemo(function(){return _kn({breakAll:b.breakAll,children:b.children,maxLines:b.maxLines,scaleToFit:h,style:b.style,width:b.width})},[b.breakAll,b.children,b.maxLines,h,b.style,b.width]),S=b.dx,C=b.dy,E=b.angle,I=b.className,P=b.breakAll,R=x2t(b,fkn);if(!C0(r)||!C0(i))return null;var D=r+(yi(S)?S:0),O=i+(yi(C)?C:0),U;switch(x){case"start":U=v9e("calc(".concat(d,")"));break;case"middle":U=v9e("calc(".concat((w.length-1)/2," * -").concat(o," + (").concat(d," / 2))"));break;default:U=v9e("calc(".concat(w.length-1," * -").concat(o,")"));break}var W=[];if(h){var V=w[0].width,G=b.width;W.push("scale(".concat((yi(G)?G/V:1)/V,")"))}return E&&W.push("rotate(".concat(E,", ").concat(D,", ").concat(O,")")),W.length&&(R.transform=W.join(" ")),Gt.createElement("text",_Ke({},cl(R,!0),{x:D,y:O,className:rd("recharts-text",I),textAnchor:f,fill:v.includes("url")?_2t:v}),w.map(function(Y,X){var ae=Y.words.join(P?"":" ");return Gt.createElement("tspan",{x:D,dy:X===0?U:o,key:"".concat(ae,"-").concat(X)},ae)}))};function pL(s,t){return s==null||t==null?NaN:st?1:s>=t?0:NaN}function wkn(s,t){return s==null||t==null?NaN:ts?1:t>=s?0:NaN}function xat(s){let t,n,r;s.length!==2?(t=pL,n=(o,c)=>pL(s(o),c),r=(o,c)=>s(o)-c):(t=s===pL||s===wkn?s:jkn,n=s,r=s);function a(o,c,d=0,u=o.length){if(d>>1;n(o[h],c)<0?d=h+1:u=h}while(d>>1;n(o[h],c)<=0?d=h+1:u=h}while(dd&&r(o[h-1],c)>-r(o[h],c)?h-1:h}return{left:a,center:l,right:i}}function jkn(){return 0}function pYt(s){return s===null?NaN:+s}function*Nkn(s,t){for(let n of s)n!=null&&(n=+n)>=n&&(yield n)}const kkn=xat(pL),Aie=kkn.right;xat(pYt).center;class w2t extends Map{constructor(t,n=Akn){if(super(),Object.defineProperties(this,{_intern:{value:new Map},_key:{value:n}}),t!=null)for(const[r,a]of t)this.set(r,a)}get(t){return super.get(j2t(this,t))}has(t){return super.has(j2t(this,t))}set(t,n){return super.set(Skn(this,t),n)}delete(t){return super.delete(Ckn(this,t))}}function j2t({_intern:s,_key:t},n){const r=t(n);return s.has(r)?s.get(r):n}function Skn({_intern:s,_key:t},n){const r=t(n);return s.has(r)?s.get(r):(s.set(r,n),n)}function Ckn({_intern:s,_key:t},n){const r=t(n);return s.has(r)&&(n=s.get(r),s.delete(r)),n}function Akn(s){return s!==null&&typeof s=="object"?s.valueOf():s}function Ekn(s=pL){if(s===pL)return gYt;if(typeof s!="function")throw new TypeError("compare is not a function");return(t,n)=>{const r=s(t,n);return r||r===0?r:(s(n,n)===0)-(s(t,t)===0)}}function gYt(s,t){return(s==null||!(s>=s))-(t==null||!(t>=t))||(st?1:0)}const Tkn=Math.sqrt(50),Mkn=Math.sqrt(10),Pkn=Math.sqrt(2);function oMe(s,t,n){const r=(t-s)/Math.max(0,n),a=Math.floor(Math.log10(r)),i=r/Math.pow(10,a),l=i>=Tkn?10:i>=Mkn?5:i>=Pkn?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 r=t=a))return[];const o=i-a+1,c=new Array(o);if(r)if(l<0)for(let d=0;d=r)&&(n=r);return n}function k2t(s,t){let n;for(const r of s)r!=null&&(n>r||n===void 0&&r>=r)&&(n=r);return n}function xYt(s,t,n=0,r=1/0,a){if(t=Math.floor(t),n=Math.floor(Math.max(0,n)),r=Math.floor(Math.min(s.length-1,r)),!(n<=t&&t<=r))return s;for(a=a===void 0?gYt:Ekn(a);r>n;){if(r-n>600){const c=r-n+1,d=t-n+1,u=Math.log(c),h=.5*Math.exp(2*u/3),m=.5*Math.sqrt(u*h*(c-h)/c)*(d-c/2<0?-1:1),f=Math.max(n,Math.floor(t-d*h/c+m)),g=Math.min(r,Math.floor(t+(c-d)*h/c+m));xYt(s,t,f,g,a)}const i=s[t];let l=n,o=r;for(YZ(s,n,t),a(s[r],i)>0&&YZ(s,n,r);l0;)--o}a(s[n],i)===0?YZ(s,n,o):(++o,YZ(s,o,r)),o<=t&&(n=o+1),t<=o&&(r=o-1)}return s}function YZ(s,t,n){const r=s[t];s[t]=s[n],s[n]=r}function Ikn(s,t,n){if(s=Float64Array.from(Nkn(s)),!(!(r=s.length)||isNaN(t=+t))){if(t<=0||r<2)return k2t(s);if(t>=1)return N2t(s);var r,a=(r-1)*t,i=Math.floor(a),l=N2t(xYt(s,i).subarray(0,i+1)),o=k2t(s.subarray(i+1));return l+(o-l)*(a-i)}}function Lkn(s,t,n=pYt){if(!(!(r=s.length)||isNaN(t=+t))){if(t<=0||r<2)return+n(s[0],0,s);if(t>=1)return+n(s[r-1],r-1,s);var r,a=(r-1)*t,i=Math.floor(a),l=+n(s[i],i,s),o=+n(s[i+1],i+1,s);return l+(o-l)*(a-i)}}function Rkn(s,t,n){s=+s,t=+t,n=(a=arguments.length)<2?(t=s,s=0,1):a<3?1:+n;for(var r=-1,a=Math.max(0,Math.ceil((t-s)/n))|0,i=new Array(a);++r>8&15|t>>4&240,t>>4&15|t&240,(t&15)<<4|t&15,1):n===8?Wde(t>>24&255,t>>16&255,t>>8&255,(t&255)/255):n===4?Wde(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=Fkn.exec(s))?new Sw(t[1],t[2],t[3],1):(t=Okn.exec(s))?new Sw(t[1]*255/100,t[2]*255/100,t[3]*255/100,1):(t=zkn.exec(s))?Wde(t[1],t[2],t[3],t[4]):(t=Bkn.exec(s))?Wde(t[1]*255/100,t[2]*255/100,t[3]*255/100,t[4]):(t=$kn.exec(s))?P2t(t[1],t[2]/100,t[3]/100,1):(t=Ukn.exec(s))?P2t(t[1],t[2]/100,t[3]/100,t[4]):S2t.hasOwnProperty(s)?E2t(S2t[s]):s==="transparent"?new Sw(NaN,NaN,NaN,0):null}function E2t(s){return new Sw(s>>16&255,s>>8&255,s&255,1)}function Wde(s,t,n,r){return r<=0&&(s=t=n=NaN),new Sw(s,t,n,r)}function Hkn(s){return s instanceof Eie||(s=Vse(s)),s?(s=s.rgb(),new Sw(s.r,s.g,s.b,s.opacity)):new Sw}function SKe(s,t,n,r){return arguments.length===1?Hkn(s):new Sw(s,t,n,r??1)}function Sw(s,t,n,r){this.r=+s,this.g=+t,this.b=+n,this.opacity=+r}vat(Sw,SKe,vYt(Eie,{brighter(s){return s=s==null?lMe:Math.pow(lMe,s),new Sw(this.r*s,this.g*s,this.b*s,this.opacity)},darker(s){return s=s==null?Use:Math.pow(Use,s),new Sw(this.r*s,this.g*s,this.b*s,this.opacity)},rgb(){return this},clamp(){return new Sw(w7(this.r),w7(this.g),w7(this.b),cMe(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:T2t,formatHex:T2t,formatHex8:Gkn,formatRgb:M2t,toString:M2t}));function T2t(){return`#${b8(this.r)}${b8(this.g)}${b8(this.b)}`}function Gkn(){return`#${b8(this.r)}${b8(this.g)}${b8(this.b)}${b8((isNaN(this.opacity)?1:this.opacity)*255)}`}function M2t(){const s=cMe(this.opacity);return`${s===1?"rgb(":"rgba("}${w7(this.r)}, ${w7(this.g)}, ${w7(this.b)}${s===1?")":`, ${s})`}`}function cMe(s){return isNaN(s)?1:Math.max(0,Math.min(1,s))}function w7(s){return Math.max(0,Math.min(255,Math.round(s)||0))}function b8(s){return s=w7(s),(s<16?"0":"")+s.toString(16)}function P2t(s,t,n,r){return r<=0?s=t=n=NaN:n<=0||n>=1?s=t=NaN:t<=0&&(s=NaN),new VS(s,t,n,r)}function bYt(s){if(s instanceof VS)return new VS(s.h,s.s,s.l,s.opacity);if(s instanceof Eie||(s=Vse(s)),!s)return new VS;if(s instanceof VS)return s;s=s.rgb();var t=s.r/255,n=s.g/255,r=s.b/255,a=Math.min(t,n,r),i=Math.max(t,n,r),l=NaN,o=i-a,c=(i+a)/2;return o?(t===i?l=(n-r)/o+(n0&&c<1?0:l,new VS(l,o,c,s.opacity)}function Wkn(s,t,n,r){return arguments.length===1?bYt(s):new VS(s,t,n,r??1)}function VS(s,t,n,r){this.h=+s,this.s=+t,this.l=+n,this.opacity=+r}vat(VS,Wkn,vYt(Eie,{brighter(s){return s=s==null?lMe:Math.pow(lMe,s),new VS(this.h,this.s,this.l*s,this.opacity)},darker(s){return s=s==null?Use:Math.pow(Use,s),new VS(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,n=this.l,r=n+(n<.5?n:1-n)*t,a=2*n-r;return new Sw(b9e(s>=240?s-240:s+120,a,r),b9e(s,a,r),b9e(s<120?s+240:s-120,a,r),this.opacity)},clamp(){return new VS(I2t(this.h),Kde(this.s),Kde(this.l),cMe(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=cMe(this.opacity);return`${s===1?"hsl(":"hsla("}${I2t(this.h)}, ${Kde(this.s)*100}%, ${Kde(this.l)*100}%${s===1?")":`, ${s})`}`}}));function I2t(s){return s=(s||0)%360,s<0?s+360:s}function Kde(s){return Math.max(0,Math.min(1,s||0))}function b9e(s,t,n){return(s<60?t+(n-t)*s/60:s<180?n:s<240?t+(n-t)*(240-s)/60:t)*255}const bat=s=>()=>s;function Kkn(s,t){return function(n){return s+n*t}}function Ykn(s,t,n){return s=Math.pow(s,n),t=Math.pow(t,n)-s,n=1/n,function(r){return Math.pow(s+r*t,n)}}function Zkn(s){return(s=+s)==1?_Yt:function(t,n){return n-t?Ykn(t,n,s):bat(isNaN(t)?n:t)}}function _Yt(s,t){var n=t-s;return n?Kkn(s,n):bat(isNaN(s)?t:s)}const L2t=function s(t){var n=Zkn(t);function r(a,i){var l=n((a=SKe(a)).r,(i=SKe(i)).r),o=n(a.g,i.g),c=n(a.b,i.b),d=_Yt(a.opacity,i.opacity);return function(u){return a.r=l(u),a.g=o(u),a.b=c(u),a.opacity=d(u),a+""}}return r.gamma=s,r}(1);function Xkn(s,t){t||(t=[]);var n=s?Math.min(t.length,s.length):0,r=t.slice(),a;return function(i){for(a=0;an&&(i=t.slice(n,i),o[l]?o[l]+=i:o[++l]=i),(r=r[0])===(a=a[0])?o[l]?o[l]+=a:o[++l]=a:(o[++l]=null,c.push({i:l,x:dMe(r,a)})),n=_9e.lastIndex;return nt&&(n=s,s=t,t=n),function(r){return Math.max(s,Math.min(t,r))}}function lSn(s,t,n){var r=s[0],a=s[1],i=t[0],l=t[1];return a2?cSn:lSn,c=d=null,h}function h(m){return m==null||isNaN(m=+m)?i:(c||(c=o(s.map(r),t,n)))(r(l(m)))}return h.invert=function(m){return l(a((d||(d=o(t,s.map(r),dMe)))(m)))},h.domain=function(m){return arguments.length?(s=Array.from(m,uMe),u()):s.slice()},h.range=function(m){return arguments.length?(t=Array.from(m),u()):t.slice()},h.rangeRound=function(m){return t=Array.from(m),n=_at,u()},h.clamp=function(m){return arguments.length?(l=m?!0:N_,u()):l!==N_},h.interpolate=function(m){return arguments.length?(n=m,u()):n},h.unknown=function(m){return arguments.length?(i=m,h):i},function(m,f){return r=m,a=f,u()}}function wat(){return LRe()(N_,N_)}function dSn(s){return Math.abs(s=Math.round(s))>=1e21?s.toLocaleString("en").replace(/,/g,""):s.toString(10)}function hMe(s,t){if(!isFinite(s)||s===0)return null;var n=(s=t?s.toExponential(t-1):s.toExponential()).indexOf("e"),r=s.slice(0,n);return[r.length>1?r[0]+r.slice(2):r,+s.slice(n+1)]}function KG(s){return s=hMe(Math.abs(s)),s?s[1]:NaN}function uSn(s,t){return function(n,r){for(var a=n.length,i=[],l=0,o=s[0],c=0;a>0&&o>0&&(c+o+1>r&&(o=Math.max(1,r-c)),i.push(n.substring(a-=o,a+o)),!((c+=o+1)>r));)o=s[l=(l+1)%s.length];return i.reverse().join(t)}}function hSn(s){return function(t){return t.replace(/[0-9]/g,function(n){return s[+n]})}}var mSn=/^(?:(.)?([<>=^]))?([+\-( ])?([$#])?(0)?(\d+)?(,)?(\.\d+)?(~)?([a-z%])?$/i;function Hse(s){if(!(t=mSn.exec(s)))throw new Error("invalid format: "+s);var t;return new jat({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]})}Hse.prototype=jat.prototype;function jat(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+""}jat.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 fSn(s){e:for(var t=s.length,n=1,r=-1,a;n0&&(r=0);break}return r>0?s.slice(0,r)+s.slice(a+1):s}var mMe;function pSn(s,t){var n=hMe(s,t);if(!n)return mMe=void 0,s.toPrecision(t);var r=n[0],a=n[1],i=a-(mMe=Math.max(-8,Math.min(8,Math.floor(a/3)))*3)+1,l=r.length;return i===l?r:i>l?r+new Array(i-l+1).join("0"):i>0?r.slice(0,i)+"."+r.slice(i):"0."+new Array(1-i).join("0")+hMe(s,Math.max(0,t+i-1))[0]}function D2t(s,t){var n=hMe(s,t);if(!n)return s+"";var r=n[0],a=n[1];return a<0?"0."+new Array(-a).join("0")+r:r.length>a+1?r.slice(0,a+1)+"."+r.slice(a+1):r+new Array(a-r.length+2).join("0")}const F2t={"%":(s,t)=>(s*100).toFixed(t),b:s=>Math.round(s).toString(2),c:s=>s+"",d:dSn,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)=>D2t(s*100,t),r:D2t,s:pSn,X:s=>Math.round(s).toString(16).toUpperCase(),x:s=>Math.round(s).toString(16)};function O2t(s){return s}var z2t=Array.prototype.map,B2t=["y","z","a","f","p","n","µ","m","","k","M","G","T","P","E","Z","Y"];function gSn(s){var t=s.grouping===void 0||s.thousands===void 0?O2t:uSn(z2t.call(s.grouping,Number),s.thousands+""),n=s.currency===void 0?"":s.currency[0]+"",r=s.currency===void 0?"":s.currency[1]+"",a=s.decimal===void 0?".":s.decimal+"",i=s.numerals===void 0?O2t:hSn(z2t.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(h,m){h=Hse(h);var f=h.fill,g=h.align,x=h.sign,y=h.symbol,v=h.zero,b=h.width,w=h.comma,S=h.precision,C=h.trim,E=h.type;E==="n"?(w=!0,E="g"):F2t[E]||(S===void 0&&(S=12),C=!0,E="g"),(v||f==="0"&&g==="=")&&(v=!0,f="0",g="=");var I=(m&&m.prefix!==void 0?m.prefix:"")+(y==="$"?n:y==="#"&&/[boxX]/.test(E)?"0"+E.toLowerCase():""),P=(y==="$"?r:/[%p]/.test(E)?l:"")+(m&&m.suffix!==void 0?m.suffix:""),R=F2t[E],D=/[defgprs%]/.test(E);S=S===void 0?6:/[gprs]/.test(E)?Math.max(1,Math.min(21,S)):Math.max(0,Math.min(20,S));function O(U){var W=I,V=P,G,Y,X;if(E==="c")V=R(U)+V,U="";else{U=+U;var ae=U<0||1/U<0;if(U=isNaN(U)?c:R(Math.abs(U),S),C&&(U=fSn(U)),ae&&+U==0&&x!=="+"&&(ae=!1),W=(ae?x==="("?x:o:x==="-"||x==="("?"":x)+W,V=(E==="s"&&!isNaN(U)&&mMe!==void 0?B2t[8+mMe/3]:"")+V+(ae&&x==="("?")":""),D){for(G=-1,Y=U.length;++GX||X>57){V=(X===46?a+U.slice(G+1):U.slice(G))+V,U=U.slice(0,G);break}}}w&&!v&&(U=t(U,1/0));var ie=W.length+U.length+V.length,ne=ie>1)+W+U+V+ne.slice(ie);break;default:U=ne+W+U+V;break}return i(U)}return O.toString=function(){return h+""},O}function u(h,m){var f=Math.max(-8,Math.min(8,Math.floor(KG(m)/3)))*3,g=Math.pow(10,-f),x=d((h=Hse(h),h.type="f",h),{suffix:B2t[8+f/3]});return function(y){return x(g*y)}}return{format:d,formatPrefix:u}}var Yde,Nat,wYt;xSn({thousands:",",grouping:[3],currency:["$",""]});function xSn(s){return Yde=gSn(s),Nat=Yde.format,wYt=Yde.formatPrefix,Yde}function ySn(s){return Math.max(0,-KG(Math.abs(s)))}function vSn(s,t){return Math.max(0,Math.max(-8,Math.min(8,Math.floor(KG(t)/3)))*3-KG(Math.abs(s)))}function bSn(s,t){return s=Math.abs(s),t=Math.abs(t)-s,Math.max(0,KG(t)-KG(s))+1}function jYt(s,t,n,r){var a=NKe(s,t,n),i;switch(r=Hse(r??",f"),r.type){case"s":{var l=Math.max(Math.abs(s),Math.abs(t));return r.precision==null&&!isNaN(i=vSn(a,l))&&(r.precision=i),wYt(r,l)}case"":case"e":case"g":case"p":case"r":{r.precision==null&&!isNaN(i=bSn(a,Math.max(Math.abs(s),Math.abs(t))))&&(r.precision=i-(r.type==="e"));break}case"f":case"%":{r.precision==null&&!isNaN(i=ySn(a))&&(r.precision=i-(r.type==="%")*2);break}}return Nat(r)}function C6(s){var t=s.domain;return s.ticks=function(n){var r=t();return wKe(r[0],r[r.length-1],n??10)},s.tickFormat=function(n,r){var a=t();return jYt(a[0],a[a.length-1],n??10,r)},s.nice=function(n){n==null&&(n=10);var r=t(),a=0,i=r.length-1,l=r[a],o=r[i],c,d,u=10;for(o0;){if(d=jKe(l,o,n),d===c)return r[a]=l,r[i]=o,t(r);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 fMe(){var s=wat();return s.copy=function(){return Tie(s,fMe())},Mk.apply(s,arguments),C6(s)}function NYt(s){var t;function n(r){return r==null||isNaN(r=+r)?t:r}return n.invert=n,n.domain=n.range=function(r){return arguments.length?(s=Array.from(r,uMe),n):s.slice()},n.unknown=function(r){return arguments.length?(t=r,n):t},n.copy=function(){return NYt(s).unknown(t)},s=arguments.length?Array.from(s,uMe):[0,1],C6(n)}function kYt(s,t){s=s.slice();var n=0,r=s.length-1,a=s[n],i=s[r],l;return iMath.pow(s,t)}function kSn(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 q2t(s){return(t,n)=>-s(-t,n)}function kat(s){const t=s($2t,U2t),n=t.domain;let r=10,a,i;function l(){return a=kSn(r),i=NSn(r),n()[0]<0?(a=q2t(a),i=q2t(i),s(_Sn,wSn)):s($2t,U2t),t}return t.base=function(o){return arguments.length?(r=+o,l()):r},t.domain=function(o){return arguments.length?(n(o),l()):n()},t.ticks=o=>{const c=n();let d=c[0],u=c[c.length-1];const h=u0){for(;m<=f;++m)for(g=1;gu)break;v.push(x)}}else for(;m<=f;++m)for(g=r-1;g>=1;--g)if(x=m>0?g/i(-m):g*i(m),!(xu)break;v.push(x)}v.length*2{if(o==null&&(o=10),c==null&&(c=r===10?"s":","),typeof c!="function"&&(!(r%1)&&(c=Hse(c)).precision==null&&(c.trim=!0),c=Nat(c)),o===1/0)return c;const d=Math.max(1,r*o/t.ticks().length);return u=>{let h=u/i(Math.round(a(u)));return h*rn(kYt(n(),{floor:o=>i(Math.floor(a(o))),ceil:o=>i(Math.ceil(a(o)))})),t}function SYt(){const s=kat(LRe()).domain([1,10]);return s.copy=()=>Tie(s,SYt()).base(s.base()),Mk.apply(s,arguments),s}function V2t(s){return function(t){return Math.sign(t)*Math.log1p(Math.abs(t/s))}}function H2t(s){return function(t){return Math.sign(t)*Math.expm1(Math.abs(t))*s}}function Sat(s){var t=1,n=s(V2t(t),H2t(t));return n.constant=function(r){return arguments.length?s(V2t(t=+r),H2t(t)):t},C6(n)}function CYt(){var s=Sat(LRe());return s.copy=function(){return Tie(s,CYt()).constant(s.constant())},Mk.apply(s,arguments)}function G2t(s){return function(t){return t<0?-Math.pow(-t,s):Math.pow(t,s)}}function SSn(s){return s<0?-Math.sqrt(-s):Math.sqrt(s)}function CSn(s){return s<0?-s*s:s*s}function Cat(s){var t=s(N_,N_),n=1;function r(){return n===1?s(N_,N_):n===.5?s(SSn,CSn):s(G2t(n),G2t(1/n))}return t.exponent=function(a){return arguments.length?(n=+a,r()):n},C6(t)}function Aat(){var s=Cat(LRe());return s.copy=function(){return Tie(s,Aat()).exponent(s.exponent())},Mk.apply(s,arguments),s}function ASn(){return Aat.apply(null,arguments).exponent(.5)}function W2t(s){return Math.sign(s)*s*s}function ESn(s){return Math.sign(s)*Math.sqrt(Math.abs(s))}function AYt(){var s=wat(),t=[0,1],n=!1,r;function a(i){var l=ESn(s(i));return isNaN(l)?r:n?Math.round(l):l}return a.invert=function(i){return s.invert(W2t(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,uMe)).map(W2t)),a):t.slice()},a.rangeRound=function(i){return a.range(i).round(!0)},a.round=function(i){return arguments.length?(n=!!i,a):n},a.clamp=function(i){return arguments.length?(s.clamp(i),a):s.clamp()},a.unknown=function(i){return arguments.length?(r=i,a):r},a.copy=function(){return AYt(s.domain(),t).round(n).clamp(s.clamp()).unknown(r)},Mk.apply(a,arguments),C6(a)}function EYt(){var s=[],t=[],n=[],r;function a(){var l=0,o=Math.max(1,t.length);for(n=new Array(o-1);++l0?n[o-1]:s[0],o=n?[r[n-1],t]:[r[d-1],r[d]]},l.unknown=function(c){return arguments.length&&(i=c),l},l.thresholds=function(){return r.slice()},l.copy=function(){return TYt().domain([s,t]).range(a).unknown(i)},Mk.apply(C6(l),arguments)}function MYt(){var s=[.5],t=[0,1],n,r=1;function a(i){return i!=null&&i<=i?t[Aie(s,i,0,r)]:n}return a.domain=function(i){return arguments.length?(s=Array.from(i),r=Math.min(s.length,t.length-1),a):s.slice()},a.range=function(i){return arguments.length?(t=Array.from(i),r=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?(n=i,a):n},a.copy=function(){return MYt().domain(s).range(t).unknown(n)},Mk.apply(a,arguments)}const w9e=new Date,j9e=new Date;function U0(s,t,n,r){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(dU0(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););}),n&&(a.count=(i,l)=>(w9e.setTime(+i),j9e.setTime(+l),s(w9e),s(j9e),Math.floor(n(w9e,j9e))),a.every=i=>(i=Math.floor(i),!isFinite(i)||!(i>0)?null:i>1?a.filter(r?l=>r(l)%i===0:l=>a.count(0,l)%i===0):a)),a}const pMe=U0(()=>{},(s,t)=>{s.setTime(+s+t)},(s,t)=>t-s);pMe.every=s=>(s=Math.floor(s),!isFinite(s)||!(s>0)?null:s>1?U0(t=>{t.setTime(Math.floor(t/s)*s)},(t,n)=>{t.setTime(+t+n*s)},(t,n)=>(n-t)/s):pMe);pMe.range;const NE=1e3,KN=NE*60,kE=KN*60,gT=kE*24,Eat=gT*7,K2t=gT*30,N9e=gT*365,_8=U0(s=>{s.setTime(s-s.getMilliseconds())},(s,t)=>{s.setTime(+s+t*NE)},(s,t)=>(t-s)/NE,s=>s.getUTCSeconds());_8.range;const Tat=U0(s=>{s.setTime(s-s.getMilliseconds()-s.getSeconds()*NE)},(s,t)=>{s.setTime(+s+t*KN)},(s,t)=>(t-s)/KN,s=>s.getMinutes());Tat.range;const Mat=U0(s=>{s.setUTCSeconds(0,0)},(s,t)=>{s.setTime(+s+t*KN)},(s,t)=>(t-s)/KN,s=>s.getUTCMinutes());Mat.range;const Pat=U0(s=>{s.setTime(s-s.getMilliseconds()-s.getSeconds()*NE-s.getMinutes()*KN)},(s,t)=>{s.setTime(+s+t*kE)},(s,t)=>(t-s)/kE,s=>s.getHours());Pat.range;const Iat=U0(s=>{s.setUTCMinutes(0,0,0)},(s,t)=>{s.setTime(+s+t*kE)},(s,t)=>(t-s)/kE,s=>s.getUTCHours());Iat.range;const Mie=U0(s=>s.setHours(0,0,0,0),(s,t)=>s.setDate(s.getDate()+t),(s,t)=>(t-s-(t.getTimezoneOffset()-s.getTimezoneOffset())*KN)/gT,s=>s.getDate()-1);Mie.range;const RRe=U0(s=>{s.setUTCHours(0,0,0,0)},(s,t)=>{s.setUTCDate(s.getUTCDate()+t)},(s,t)=>(t-s)/gT,s=>s.getUTCDate()-1);RRe.range;const PYt=U0(s=>{s.setUTCHours(0,0,0,0)},(s,t)=>{s.setUTCDate(s.getUTCDate()+t)},(s,t)=>(t-s)/gT,s=>Math.floor(s/gT));PYt.range;function s9(s){return U0(t=>{t.setDate(t.getDate()-(t.getDay()+7-s)%7),t.setHours(0,0,0,0)},(t,n)=>{t.setDate(t.getDate()+n*7)},(t,n)=>(n-t-(n.getTimezoneOffset()-t.getTimezoneOffset())*KN)/Eat)}const DRe=s9(0),gMe=s9(1),TSn=s9(2),MSn=s9(3),YG=s9(4),PSn=s9(5),ISn=s9(6);DRe.range;gMe.range;TSn.range;MSn.range;YG.range;PSn.range;ISn.range;function n9(s){return U0(t=>{t.setUTCDate(t.getUTCDate()-(t.getUTCDay()+7-s)%7),t.setUTCHours(0,0,0,0)},(t,n)=>{t.setUTCDate(t.getUTCDate()+n*7)},(t,n)=>(n-t)/Eat)}const FRe=n9(0),xMe=n9(1),LSn=n9(2),RSn=n9(3),ZG=n9(4),DSn=n9(5),FSn=n9(6);FRe.range;xMe.range;LSn.range;RSn.range;ZG.range;DSn.range;FSn.range;const Lat=U0(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());Lat.range;const Rat=U0(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());Rat.range;const xT=U0(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());xT.every=s=>!isFinite(s=Math.floor(s))||!(s>0)?null:U0(t=>{t.setFullYear(Math.floor(t.getFullYear()/s)*s),t.setMonth(0,1),t.setHours(0,0,0,0)},(t,n)=>{t.setFullYear(t.getFullYear()+n*s)});xT.range;const yT=U0(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());yT.every=s=>!isFinite(s=Math.floor(s))||!(s>0)?null:U0(t=>{t.setUTCFullYear(Math.floor(t.getUTCFullYear()/s)*s),t.setUTCMonth(0,1),t.setUTCHours(0,0,0,0)},(t,n)=>{t.setUTCFullYear(t.getUTCFullYear()+n*s)});yT.range;function IYt(s,t,n,r,a,i){const l=[[_8,1,NE],[_8,5,5*NE],[_8,15,15*NE],[_8,30,30*NE],[i,1,KN],[i,5,5*KN],[i,15,15*KN],[i,30,30*KN],[a,1,kE],[a,3,3*kE],[a,6,6*kE],[a,12,12*kE],[r,1,gT],[r,2,2*gT],[n,1,Eat],[t,1,K2t],[t,3,3*K2t],[s,1,N9e]];function o(d,u,h){const m=uy).right(l,m);if(f===l.length)return s.every(NKe(d/N9e,u/N9e,h));if(f===0)return pMe.every(Math.max(NKe(d,u,h),1));const[g,x]=l[m/l[f-1][2]53)return null;"w"in ke||(ke.w=1),"Z"in ke?(je=S9e(ZZ(ke.y,0,1)),Ae=je.getUTCDay(),je=Ae>4||Ae===0?xMe.ceil(je):xMe(je),je=RRe.offset(je,(ke.V-1)*7),ke.y=je.getUTCFullYear(),ke.m=je.getUTCMonth(),ke.d=je.getUTCDate()+(ke.w+6)%7):(je=k9e(ZZ(ke.y,0,1)),Ae=je.getDay(),je=Ae>4||Ae===0?gMe.ceil(je):gMe(je),je=Mie.offset(je,(ke.V-1)*7),ke.y=je.getFullYear(),ke.m=je.getMonth(),ke.d=je.getDate()+(ke.w+6)%7)}else("W"in ke||"U"in ke)&&("w"in ke||(ke.w="u"in ke?ke.u%7:"W"in ke?1:0),Ae="Z"in ke?S9e(ZZ(ke.y,0,1)).getUTCDay():k9e(ZZ(ke.y,0,1)).getDay(),ke.m=0,ke.d="W"in ke?(ke.w+6)%7+ke.W*7-(Ae+5)%7:ke.w+ke.U*7-(Ae+6)%7);return"Z"in ke?(ke.H+=ke.Z/100|0,ke.M+=ke.Z%100,S9e(ke)):k9e(ke)}}function P(Se,Le,Fe,ke){for(var Ve=0,je=Le.length,Ae=Fe.length,Ce,qe;Ve=Ae)return-1;if(Ce=Le.charCodeAt(Ve++),Ce===37){if(Ce=Le.charAt(Ve++),qe=C[Ce in Y2t?Le.charAt(Ve++):Ce],!qe||(ke=qe(Se,Fe,ke))<0)return-1}else if(Ce!=Fe.charCodeAt(ke++))return-1}return ke}function R(Se,Le,Fe){var ke=d.exec(Le.slice(Fe));return ke?(Se.p=u.get(ke[0].toLowerCase()),Fe+ke[0].length):-1}function D(Se,Le,Fe){var ke=f.exec(Le.slice(Fe));return ke?(Se.w=g.get(ke[0].toLowerCase()),Fe+ke[0].length):-1}function O(Se,Le,Fe){var ke=h.exec(Le.slice(Fe));return ke?(Se.w=m.get(ke[0].toLowerCase()),Fe+ke[0].length):-1}function U(Se,Le,Fe){var ke=v.exec(Le.slice(Fe));return ke?(Se.m=b.get(ke[0].toLowerCase()),Fe+ke[0].length):-1}function W(Se,Le,Fe){var ke=x.exec(Le.slice(Fe));return ke?(Se.m=y.get(ke[0].toLowerCase()),Fe+ke[0].length):-1}function V(Se,Le,Fe){return P(Se,t,Le,Fe)}function G(Se,Le,Fe){return P(Se,n,Le,Fe)}function Y(Se,Le,Fe){return P(Se,r,Le,Fe)}function X(Se){return l[Se.getDay()]}function ae(Se){return i[Se.getDay()]}function ie(Se){return c[Se.getMonth()]}function ne(Se){return o[Se.getMonth()]}function te(Se){return a[+(Se.getHours()>=12)]}function J(Se){return 1+~~(Se.getMonth()/3)}function ce(Se){return l[Se.getUTCDay()]}function _e(Se){return i[Se.getUTCDay()]}function he(Se){return c[Se.getUTCMonth()]}function ue(Se){return o[Se.getUTCMonth()]}function ve(Se){return a[+(Se.getUTCHours()>=12)]}function Ee(Se){return 1+~~(Se.getUTCMonth()/3)}return{format:function(Se){var Le=E(Se+="",w);return Le.toString=function(){return Se},Le},parse:function(Se){var Le=I(Se+="",!1);return Le.toString=function(){return Se},Le},utcFormat:function(Se){var Le=E(Se+="",S);return Le.toString=function(){return Se},Le},utcParse:function(Se){var Le=I(Se+="",!0);return Le.toString=function(){return Se},Le}}}var Y2t={"-":"",_:" ",0:"0"},Dv=/^\s*\d+/,qSn=/^%/,VSn=/[\\^$*+?|[\]().{}]/g;function Gh(s,t,n){var r=s<0?"-":"",a=(r?-s:s)+"",i=a.length;return r+(i[t.toLowerCase(),n]))}function GSn(s,t,n){var r=Dv.exec(t.slice(n,n+1));return r?(s.w=+r[0],n+r[0].length):-1}function WSn(s,t,n){var r=Dv.exec(t.slice(n,n+1));return r?(s.u=+r[0],n+r[0].length):-1}function KSn(s,t,n){var r=Dv.exec(t.slice(n,n+2));return r?(s.U=+r[0],n+r[0].length):-1}function YSn(s,t,n){var r=Dv.exec(t.slice(n,n+2));return r?(s.V=+r[0],n+r[0].length):-1}function ZSn(s,t,n){var r=Dv.exec(t.slice(n,n+2));return r?(s.W=+r[0],n+r[0].length):-1}function Z2t(s,t,n){var r=Dv.exec(t.slice(n,n+4));return r?(s.y=+r[0],n+r[0].length):-1}function X2t(s,t,n){var r=Dv.exec(t.slice(n,n+2));return r?(s.y=+r[0]+(+r[0]>68?1900:2e3),n+r[0].length):-1}function XSn(s,t,n){var r=/^(Z)|([+-]\d\d)(?::?(\d\d))?/.exec(t.slice(n,n+6));return r?(s.Z=r[1]?0:-(r[2]+(r[3]||"00")),n+r[0].length):-1}function QSn(s,t,n){var r=Dv.exec(t.slice(n,n+1));return r?(s.q=r[0]*3-3,n+r[0].length):-1}function JSn(s,t,n){var r=Dv.exec(t.slice(n,n+2));return r?(s.m=r[0]-1,n+r[0].length):-1}function Q2t(s,t,n){var r=Dv.exec(t.slice(n,n+2));return r?(s.d=+r[0],n+r[0].length):-1}function eCn(s,t,n){var r=Dv.exec(t.slice(n,n+3));return r?(s.m=0,s.d=+r[0],n+r[0].length):-1}function J2t(s,t,n){var r=Dv.exec(t.slice(n,n+2));return r?(s.H=+r[0],n+r[0].length):-1}function tCn(s,t,n){var r=Dv.exec(t.slice(n,n+2));return r?(s.M=+r[0],n+r[0].length):-1}function sCn(s,t,n){var r=Dv.exec(t.slice(n,n+2));return r?(s.S=+r[0],n+r[0].length):-1}function nCn(s,t,n){var r=Dv.exec(t.slice(n,n+3));return r?(s.L=+r[0],n+r[0].length):-1}function rCn(s,t,n){var r=Dv.exec(t.slice(n,n+6));return r?(s.L=Math.floor(r[0]/1e3),n+r[0].length):-1}function aCn(s,t,n){var r=qSn.exec(t.slice(n,n+1));return r?n+r[0].length:-1}function iCn(s,t,n){var r=Dv.exec(t.slice(n));return r?(s.Q=+r[0],n+r[0].length):-1}function oCn(s,t,n){var r=Dv.exec(t.slice(n));return r?(s.s=+r[0],n+r[0].length):-1}function eNt(s,t){return Gh(s.getDate(),t,2)}function lCn(s,t){return Gh(s.getHours(),t,2)}function cCn(s,t){return Gh(s.getHours()%12||12,t,2)}function dCn(s,t){return Gh(1+Mie.count(xT(s),s),t,3)}function LYt(s,t){return Gh(s.getMilliseconds(),t,3)}function uCn(s,t){return LYt(s,t)+"000"}function hCn(s,t){return Gh(s.getMonth()+1,t,2)}function mCn(s,t){return Gh(s.getMinutes(),t,2)}function fCn(s,t){return Gh(s.getSeconds(),t,2)}function pCn(s){var t=s.getDay();return t===0?7:t}function gCn(s,t){return Gh(DRe.count(xT(s)-1,s),t,2)}function RYt(s){var t=s.getDay();return t>=4||t===0?YG(s):YG.ceil(s)}function xCn(s,t){return s=RYt(s),Gh(YG.count(xT(s),s)+(xT(s).getDay()===4),t,2)}function yCn(s){return s.getDay()}function vCn(s,t){return Gh(gMe.count(xT(s)-1,s),t,2)}function bCn(s,t){return Gh(s.getFullYear()%100,t,2)}function _Cn(s,t){return s=RYt(s),Gh(s.getFullYear()%100,t,2)}function wCn(s,t){return Gh(s.getFullYear()%1e4,t,4)}function jCn(s,t){var n=s.getDay();return s=n>=4||n===0?YG(s):YG.ceil(s),Gh(s.getFullYear()%1e4,t,4)}function NCn(s){var t=s.getTimezoneOffset();return(t>0?"-":(t*=-1,"+"))+Gh(t/60|0,"0",2)+Gh(t%60,"0",2)}function tNt(s,t){return Gh(s.getUTCDate(),t,2)}function kCn(s,t){return Gh(s.getUTCHours(),t,2)}function SCn(s,t){return Gh(s.getUTCHours()%12||12,t,2)}function CCn(s,t){return Gh(1+RRe.count(yT(s),s),t,3)}function DYt(s,t){return Gh(s.getUTCMilliseconds(),t,3)}function ACn(s,t){return DYt(s,t)+"000"}function ECn(s,t){return Gh(s.getUTCMonth()+1,t,2)}function TCn(s,t){return Gh(s.getUTCMinutes(),t,2)}function MCn(s,t){return Gh(s.getUTCSeconds(),t,2)}function PCn(s){var t=s.getUTCDay();return t===0?7:t}function ICn(s,t){return Gh(FRe.count(yT(s)-1,s),t,2)}function FYt(s){var t=s.getUTCDay();return t>=4||t===0?ZG(s):ZG.ceil(s)}function LCn(s,t){return s=FYt(s),Gh(ZG.count(yT(s),s)+(yT(s).getUTCDay()===4),t,2)}function RCn(s){return s.getUTCDay()}function DCn(s,t){return Gh(xMe.count(yT(s)-1,s),t,2)}function FCn(s,t){return Gh(s.getUTCFullYear()%100,t,2)}function OCn(s,t){return s=FYt(s),Gh(s.getUTCFullYear()%100,t,2)}function zCn(s,t){return Gh(s.getUTCFullYear()%1e4,t,4)}function BCn(s,t){var n=s.getUTCDay();return s=n>=4||n===0?ZG(s):ZG.ceil(s),Gh(s.getUTCFullYear()%1e4,t,4)}function $Cn(){return"+0000"}function sNt(){return"%"}function nNt(s){return+s}function rNt(s){return Math.floor(+s/1e3)}var z$,OYt,zYt;UCn({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 UCn(s){return z$=USn(s),OYt=z$.format,z$.parse,zYt=z$.utcFormat,z$.utcParse,z$}function qCn(s){return new Date(s)}function VCn(s){return s instanceof Date?+s:+new Date(+s)}function Dat(s,t,n,r,a,i,l,o,c,d){var u=wat(),h=u.invert,m=u.domain,f=d(".%L"),g=d(":%S"),x=d("%I:%M"),y=d("%I %p"),v=d("%a %d"),b=d("%b %d"),w=d("%B"),S=d("%Y");function C(E){return(c(E)t(a/(s.length-1)))},n.quantiles=function(r){return Array.from({length:r+1},(a,i)=>Ikn(s,i/r))},n.copy=function(){return qYt(t).domain(s)},zT.apply(n,arguments)}function zRe(){var s=0,t=.5,n=1,r=1,a,i,l,o,c,d=N_,u,h=!1,m;function f(x){return isNaN(x=+x)?m:(x=.5+((x=+u(x))-i)*(r*xt}var WYt=XCn,QCn=BRe,JCn=WYt,e5n=IK;function t5n(s){return s&&s.length?QCn(s,e5n,JCn):void 0}var s5n=t5n;const NI=au(s5n);function n5n(s,t){return ss.e^i.s<0?1:-1;for(r=i.d.length,a=s.d.length,t=0,n=rs.d[t]^i.s<0?1:-1;return r===a?0:r>a^i.s<0?1:-1};Io.decimalPlaces=Io.dp=function(){var s=this,t=s.d.length-1,n=(t-s.e)*wp;if(t=s.d[t],t)for(;t%10==0;t/=10)n--;return n<0?0:n};Io.dividedBy=Io.div=function(s){return KE(this,new this.constructor(s))};Io.dividedToIntegerBy=Io.idiv=function(s){var t=this,n=t.constructor;return Cf(KE(t,new n(s),0,1),n.precision)};Io.equals=Io.eq=function(s){return!this.cmp(s)};Io.exponent=function(){return Hy(this)};Io.greaterThan=Io.gt=function(s){return this.cmp(s)>0};Io.greaterThanOrEqualTo=Io.gte=function(s){return this.cmp(s)>=0};Io.isInteger=Io.isint=function(){return this.e>this.d.length-2};Io.isNegative=Io.isneg=function(){return this.s<0};Io.isPositive=Io.ispos=function(){return this.s>0};Io.isZero=function(){return this.s===0};Io.lessThan=Io.lt=function(s){return this.cmp(s)<0};Io.lessThanOrEqualTo=Io.lte=function(s){return this.cmp(s)<1};Io.logarithm=Io.log=function(s){var t,n=this,r=n.constructor,a=r.precision,i=a+5;if(s===void 0)s=new r(10);else if(s=new r(s),s.s<1||s.eq(Jj))throw Error(pk+"NaN");if(n.s<1)throw Error(pk+(n.s?"NaN":"-Infinity"));return n.eq(Jj)?new r(0):(Xp=!1,t=KE(Gse(n,i),Gse(s,i),i),Xp=!0,Cf(t,a))};Io.minus=Io.sub=function(s){var t=this;return s=new t.constructor(s),t.s==s.s?QYt(t,s):ZYt(t,(s.s=-s.s,s))};Io.modulo=Io.mod=function(s){var t,n=this,r=n.constructor,a=r.precision;if(s=new r(s),!s.s)throw Error(pk+"NaN");return n.s?(Xp=!1,t=KE(n,s,0,1).times(s),Xp=!0,n.minus(t)):Cf(new r(n),a)};Io.naturalExponential=Io.exp=function(){return XYt(this)};Io.naturalLogarithm=Io.ln=function(){return Gse(this)};Io.negated=Io.neg=function(){var s=new this.constructor(this);return s.s=-s.s||0,s};Io.plus=Io.add=function(s){var t=this;return s=new t.constructor(s),t.s==s.s?ZYt(t,s):QYt(t,(s.s=-s.s,s))};Io.precision=Io.sd=function(s){var t,n,r,a=this;if(s!==void 0&&s!==!!s&&s!==1&&s!==0)throw Error(j7+s);if(t=Hy(a)+1,r=a.d.length-1,n=r*wp+1,r=a.d[r],r){for(;r%10==0;r/=10)n--;for(r=a.d[0];r>=10;r/=10)n++}return s&&t>n?t:n};Io.squareRoot=Io.sqrt=function(){var s,t,n,r,a,i,l,o=this,c=o.constructor;if(o.s<1){if(!o.s)return new c(0);throw Error(pk+"NaN")}for(s=Hy(o),Xp=!1,a=Math.sqrt(+o),a==0||a==1/0?(t=v4(o.d),(t.length+s)%2==0&&(t+="0"),a=Math.sqrt(t),s=DK((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),r=new c(t)):r=new c(a.toString()),n=c.precision,a=l=n+3;;)if(i=r,r=i.plus(KE(o,i,l+2)).times(.5),v4(i.d).slice(0,l)===(t=v4(r.d)).slice(0,l)){if(t=t.slice(l-3,l+1),a==l&&t=="4999"){if(Cf(i,n+1,0),i.times(i).eq(o)){r=i;break}}else if(t!="9999")break;l+=4}return Xp=!0,Cf(r,n)};Io.times=Io.mul=function(s){var t,n,r,a,i,l,o,c,d,u=this,h=u.constructor,m=u.d,f=(s=new h(s)).d;if(!u.s||!s.s)return new h(0);for(s.s*=u.s,n=u.e+s.e,c=m.length,d=f.length,c=0;){for(t=0,a=c+r;a>r;)o=i[a]+f[r]*m[a-r-1]+t,i[a--]=o%uv|0,t=o/uv|0;i[a]=(i[a]+t)%uv|0}for(;!i[--l];)i.pop();return t?++n:i.shift(),s.d=i,s.e=n,Xp?Cf(s,h.precision):s};Io.toDecimalPlaces=Io.todp=function(s,t){var n=this,r=n.constructor;return n=new r(n),s===void 0?n:(e3(s,0,RK),t===void 0?t=r.rounding:e3(t,0,8),Cf(n,s+Hy(n)+1,t))};Io.toExponential=function(s,t){var n,r=this,a=r.constructor;return s===void 0?n=dB(r,!0):(e3(s,0,RK),t===void 0?t=a.rounding:e3(t,0,8),r=Cf(new a(r),s+1,t),n=dB(r,!0,s+1)),n};Io.toFixed=function(s,t){var n,r,a=this,i=a.constructor;return s===void 0?dB(a):(e3(s,0,RK),t===void 0?t=i.rounding:e3(t,0,8),r=Cf(new i(a),s+Hy(a)+1,t),n=dB(r.abs(),!1,s+Hy(r)+1),a.isneg()&&!a.isZero()?"-"+n:n)};Io.toInteger=Io.toint=function(){var s=this,t=s.constructor;return Cf(new t(s),Hy(s)+1,t.rounding)};Io.toNumber=function(){return+this};Io.toPower=Io.pow=function(s){var t,n,r,a,i,l,o=this,c=o.constructor,d=12,u=+(s=new c(s));if(!s.s)return new c(Jj);if(o=new c(o),!o.s){if(s.s<1)throw Error(pk+"Infinity");return o}if(o.eq(Jj))return o;if(r=c.precision,s.eq(Jj))return Cf(o,r);if(t=s.e,n=s.d.length-1,l=t>=n,i=o.s,l){if((n=u<0?-u:u)<=YYt){for(a=new c(Jj),t=Math.ceil(r/wp+4),Xp=!1;n%2&&(a=a.times(o),oNt(a.d,t)),n=DK(n/2),n!==0;)o=o.times(o),oNt(o.d,t);return Xp=!0,s.s<0?new c(Jj).div(a):Cf(a,r)}}else if(i<0)throw Error(pk+"NaN");return i=i<0&&s.d[Math.max(t,n)]&1?-1:1,o.s=1,Xp=!1,a=s.times(Gse(o,r+d)),Xp=!0,a=XYt(a),a.s=i,a};Io.toPrecision=function(s,t){var n,r,a=this,i=a.constructor;return s===void 0?(n=Hy(a),r=dB(a,n<=i.toExpNeg||n>=i.toExpPos)):(e3(s,1,RK),t===void 0?t=i.rounding:e3(t,0,8),a=Cf(new i(a),s,t),n=Hy(a),r=dB(a,s<=n||n<=i.toExpNeg,s)),r};Io.toSignificantDigits=Io.tosd=function(s,t){var n=this,r=n.constructor;return s===void 0?(s=r.precision,t=r.rounding):(e3(s,1,RK),t===void 0?t=r.rounding:e3(t,0,8)),Cf(new r(n),s,t)};Io.toString=Io.valueOf=Io.val=Io.toJSON=Io[Symbol.for("nodejs.util.inspect.custom")]=function(){var s=this,t=Hy(s),n=s.constructor;return dB(s,t<=n.toExpNeg||t>=n.toExpPos)};function ZYt(s,t){var n,r,a,i,l,o,c,d,u=s.constructor,h=u.precision;if(!s.s||!t.s)return t.s||(t=new u(s)),Xp?Cf(t,h):t;if(c=s.d,d=t.d,l=s.e,a=t.e,c=c.slice(),i=l-a,i){for(i<0?(r=c,i=-i,o=d.length):(r=d,a=l,o=c.length),l=Math.ceil(h/wp),o=l>o?l+1:o+1,i>o&&(i=o,r.length=1),r.reverse();i--;)r.push(0);r.reverse()}for(o=c.length,i=d.length,o-i<0&&(i=o,r=d,d=c,c=r),n=0;i;)n=(c[--i]=c[i]+d[i]+n)/uv|0,c[i]%=uv;for(n&&(c.unshift(n),++a),o=c.length;c[--o]==0;)c.pop();return t.d=c,t.e=a,Xp?Cf(t,h):t}function e3(s,t,n){if(s!==~~s||sn)throw Error(j7+s)}function v4(s){var t,n,r,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 n(r,a,i){for(var l=0;i--;)r[i]-=l,l=r[i]1;)r.shift()}return function(r,a,i,l){var o,c,d,u,h,m,f,g,x,y,v,b,w,S,C,E,I,P,R=r.constructor,D=r.s==a.s?1:-1,O=r.d,U=a.d;if(!r.s)return new R(r);if(!a.s)throw Error(pk+"Division by zero");for(c=r.e-a.e,I=U.length,C=O.length,f=new R(D),g=f.d=[],d=0;U[d]==(O[d]||0);)++d;if(U[d]>(O[d]||0)&&--c,i==null?b=i=R.precision:l?b=i+(Hy(r)-Hy(a))+1:b=i,b<0)return new R(0);if(b=b/wp+2|0,d=0,I==1)for(u=0,U=U[0],b++;(d1&&(U=s(U,u),O=s(O,u),I=U.length,C=O.length),S=I,x=O.slice(0,I),y=x.length;y=uv/2&&++E;do u=0,o=t(U,x,I,y),o<0?(v=x[0],I!=y&&(v=v*uv+(x[1]||0)),u=v/E|0,u>1?(u>=uv&&(u=uv-1),h=s(U,u),m=h.length,y=x.length,o=t(h,x,m,y),o==1&&(u--,n(h,I16)throw Error(zat+Hy(s));if(!s.s)return new u(Jj);for(Xp=!1,o=h,l=new u(.03125);s.abs().gte(.1);)s=s.times(l),d+=5;for(r=Math.log(BO(2,d))/Math.LN10*2+5|0,o+=r,n=a=i=new u(Jj),u.precision=o;;){if(a=Cf(a.times(s),o),n=n.times(++c),l=i.plus(KE(a,n,o)),v4(l.d).slice(0,o)===v4(i.d).slice(0,o)){for(;d--;)i=Cf(i.times(i),o);return u.precision=h,t==null?(Xp=!0,Cf(i,h)):i}i=l}}function Hy(s){for(var t=s.e*wp,n=s.d[0];n>=10;n/=10)t++;return t}function C9e(s,t,n){if(t>s.LN10.sd())throw Xp=!0,n&&(s.precision=n),Error(pk+"LN10 precision limit exceeded");return Cf(new s(s.LN10),t)}function vP(s){for(var t="";s--;)t+="0";return t}function Gse(s,t){var n,r,a,i,l,o,c,d,u,h=1,m=10,f=s,g=f.d,x=f.constructor,y=x.precision;if(f.s<1)throw Error(pk+(f.s?"NaN":"-Infinity"));if(f.eq(Jj))return new x(0);if(t==null?(Xp=!1,d=y):d=t,f.eq(10))return t==null&&(Xp=!0),C9e(x,d);if(d+=m,x.precision=d,n=v4(g),r=n.charAt(0),i=Hy(f),Math.abs(i)<15e14){for(;r<7&&r!=1||r==1&&n.charAt(1)>3;)f=f.times(s),n=v4(f.d),r=n.charAt(0),h++;i=Hy(f),r>1?(f=new x("0."+n),i++):f=new x(r+"."+n.slice(1))}else return c=C9e(x,d+2,y).times(i+""),f=Gse(new x(r+"."+n.slice(1)),d-m).plus(c),x.precision=y,t==null?(Xp=!0,Cf(f,y)):f;for(o=l=f=KE(f.minus(Jj),f.plus(Jj),d),u=Cf(f.times(f),d),a=3;;){if(l=Cf(l.times(u),d),c=o.plus(KE(l,new x(a),d)),v4(c.d).slice(0,d)===v4(o.d).slice(0,d))return o=o.times(2),i!==0&&(o=o.plus(C9e(x,d+2,y).times(i+""))),o=KE(o,new x(h),d),x.precision=y,t==null?(Xp=!0,Cf(o,y)):o;o=c,a+=2}}function iNt(s,t){var n,r,a;for((n=t.indexOf("."))>-1&&(t=t.replace(".","")),(r=t.search(/e/i))>0?(n<0&&(n=r),n+=+t.slice(r+1),t=t.substring(0,r)):n<0&&(n=t.length),r=0;t.charCodeAt(r)===48;)++r;for(a=t.length;t.charCodeAt(a-1)===48;)--a;if(t=t.slice(r,a),t){if(a-=r,n=n-r-1,s.e=DK(n/wp),s.d=[],r=(n+1)%wp,n<0&&(r+=wp),ryMe||s.e<-yMe))throw Error(zat+n)}else s.s=0,s.e=0,s.d=[0];return s}function Cf(s,t,n){var r,a,i,l,o,c,d,u,h=s.d;for(l=1,i=h[0];i>=10;i/=10)l++;if(r=t-l,r<0)r+=wp,a=t,d=h[u=0];else{if(u=Math.ceil((r+1)/wp),i=h.length,u>=i)return s;for(d=i=h[u],l=1;i>=10;i/=10)l++;r%=wp,a=r-wp+l}if(n!==void 0&&(i=BO(10,l-a-1),o=d/i%10|0,c=t<0||h[u+1]!==void 0||d%i,c=n<4?(o||c)&&(n==0||n==(s.s<0?3:2)):o>5||o==5&&(n==4||c||n==6&&(r>0?a>0?d/BO(10,l-a):0:h[u-1])%10&1||n==(s.s<0?8:7))),t<1||!h[0])return c?(i=Hy(s),h.length=1,t=t-i-1,h[0]=BO(10,(wp-t%wp)%wp),s.e=DK(-t/wp)||0):(h.length=1,h[0]=s.e=s.s=0),s;if(r==0?(h.length=u,i=1,u--):(h.length=u+1,i=BO(10,wp-r),h[u]=a>0?(d/BO(10,l-a)%BO(10,a)|0)*i:0),c)for(;;)if(u==0){(h[0]+=i)==uv&&(h[0]=1,++s.e);break}else{if(h[u]+=i,h[u]!=uv)break;h[u--]=0,i=1}for(r=h.length;h[--r]===0;)h.pop();if(Xp&&(s.e>yMe||s.e<-yMe))throw Error(zat+Hy(s));return s}function QYt(s,t){var n,r,a,i,l,o,c,d,u,h,m=s.constructor,f=m.precision;if(!s.s||!t.s)return t.s?t.s=-t.s:t=new m(s),Xp?Cf(t,f):t;if(c=s.d,h=t.d,r=t.e,d=s.e,c=c.slice(),l=d-r,l){for(u=l<0,u?(n=c,l=-l,o=h.length):(n=h,r=d,o=c.length),a=Math.max(Math.ceil(f/wp),o)+2,l>a&&(l=a,n.length=1),n.reverse(),a=l;a--;)n.push(0);n.reverse()}else{for(a=c.length,o=h.length,u=a0;--a)c[o++]=0;for(a=h.length;a>l;){if(c[--a]0?i=i.charAt(0)+"."+i.slice(1)+vP(r):l>1&&(i=i.charAt(0)+"."+i.slice(1)),i=i+(a<0?"e":"e+")+a):a<0?(i="0."+vP(-a-1)+i,n&&(r=n-l)>0&&(i+=vP(r))):a>=l?(i+=vP(a+1-l),n&&(r=n-a-1)>0&&(i=i+"."+vP(r))):((r=a+1)0&&(a+1===l&&(i+="."),i+=vP(r))),s.s<0?"-"+i:i}function oNt(s,t){if(s.length>t)return s.length=t,!0}function JYt(s){var t,n,r;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(j7+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 iNt(l,i.toString())}else if(typeof i!="string")throw Error(j7+i);if(i.charCodeAt(0)===45?(i=i.slice(1),l.s=-1):l.s=1,N5n.test(i))iNt(l,i);else throw Error(j7+i)}if(a.prototype=Io,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=JYt,a.config=a.set=k5n,s===void 0&&(s={}),s)for(r=["precision","rounding","toExpNeg","toExpPos","LN10"],t=0;t=a[t+1]&&r<=a[t+2])this[n]=r;else throw Error(j7+n+": "+r);if((r=s[n="LN10"])!==void 0)if(r==Math.LN10)this[n]=new this(r);else throw Error(j7+n+": "+r);return this}var Bat=JYt(j5n);Jj=new Bat(1);const Zm=Bat;function S5n(s){return T5n(s)||E5n(s)||A5n(s)||C5n()}function C5n(){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 A5n(s,t){if(s){if(typeof s=="string")return EKe(s,t);var n=Object.prototype.toString.call(s).slice(8,-1);if(n==="Object"&&s.constructor&&(n=s.constructor.name),n==="Map"||n==="Set")return Array.from(s);if(n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return EKe(s,t)}}function E5n(s){if(typeof Symbol<"u"&&Symbol.iterator in Object(s))return Array.from(s)}function T5n(s){if(Array.isArray(s))return EKe(s)}function EKe(s,t){(t==null||t>s.length)&&(t=s.length);for(var n=0,r=new Array(t);n=t?n.apply(void 0,a):s(t-l,lNt(function(){for(var o=arguments.length,c=new Array(o),d=0;ds.length)&&(t=s.length);for(var n=0,r=new Array(t);n"u"||!(Symbol.iterator in Object(s)))){var n=[],r=!0,a=!1,i=void 0;try{for(var l=s[Symbol.iterator](),o;!(r=(o=l.next()).done)&&(n.push(o.value),!(t&&n.length===t));r=!0);}catch(c){a=!0,i=c}finally{try{!r&&l.return!=null&&l.return()}finally{if(a)throw i}}return n}}function H5n(s){if(Array.isArray(s))return s}function rZt(s){var t=Wse(s,2),n=t[0],r=t[1],a=n,i=r;return n>r&&(a=r,i=n),[a,i]}function aZt(s,t,n){if(s.lte(0))return new Zm(0);var r=qRe.getDigitCount(s.toNumber()),a=new Zm(10).pow(r),i=s.div(a),l=r!==1?.05:.1,o=new Zm(Math.ceil(i.div(l).toNumber())).add(n).mul(l),c=o.mul(a);return t?c:new Zm(Math.ceil(c))}function G5n(s,t,n){var r=1,a=new Zm(s);if(!a.isint()&&n){var i=Math.abs(s);i<1?(r=new Zm(10).pow(qRe.getDigitCount(s)-1),a=new Zm(Math.floor(a.div(r).toNumber())).mul(r)):i>1&&(a=new Zm(Math.floor(s)))}else s===0?a=new Zm(Math.floor((t-1)/2)):n||(a=new Zm(Math.floor(s)));var l=Math.floor((t-1)/2),o=L5n(I5n(function(c){return a.add(new Zm(c-l).mul(r)).toNumber()}),TKe);return o(0,t)}function iZt(s,t,n,r){var a=arguments.length>4&&arguments[4]!==void 0?arguments[4]:0;if(!Number.isFinite((t-s)/(n-1)))return{step:new Zm(0),tickMin:new Zm(0),tickMax:new Zm(0)};var i=aZt(new Zm(t).sub(s).div(n-1),r,a),l;s<=0&&t>=0?l=new Zm(0):(l=new Zm(s).add(t).div(2),l=l.sub(new Zm(l).mod(i)));var o=Math.ceil(l.sub(s).div(i).toNumber()),c=Math.ceil(new Zm(t).sub(l).div(i).toNumber()),d=o+c+1;return d>n?iZt(s,t,n,r,a+1):(d0?c+(n-d):c,o=t>0?o:o+(n-d)),{step:i,tickMin:l.sub(new Zm(o).mul(i)),tickMax:l.add(new Zm(c).mul(i))})}function W5n(s){var t=Wse(s,2),n=t[0],r=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=rZt([n,r]),c=Wse(o,2),d=c[0],u=c[1];if(d===-1/0||u===1/0){var h=u===1/0?[d].concat(PKe(TKe(0,a-1).map(function(){return 1/0}))):[].concat(PKe(TKe(0,a-1).map(function(){return-1/0})),[u]);return n>r?MKe(h):h}if(d===u)return G5n(d,a,i);var m=iZt(d,u,l,i),f=m.step,g=m.tickMin,x=m.tickMax,y=qRe.rangeStep(g,x.add(new Zm(.1).mul(f)),f);return n>r?MKe(y):y}function K5n(s,t){var n=Wse(s,2),r=n[0],a=n[1],i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0,l=rZt([r,a]),o=Wse(l,2),c=o[0],d=o[1];if(c===-1/0||d===1/0)return[r,a];if(c===d)return[c];var u=Math.max(t,2),h=aZt(new Zm(d).sub(c).div(u-1),i,0),m=[].concat(PKe(qRe.rangeStep(new Zm(c),new Zm(d).sub(new Zm(.99).mul(h)),h)),[d]);return r>a?MKe(m):m}var Y5n=sZt(W5n),Z5n=sZt(K5n),X5n="Invariant failed";function uB(s,t){throw new Error(X5n)}var Q5n=["offset","layout","width","dataKey","data","dataPointFormatter","xAxis","yAxis"];function XG(s){"@babel/helpers - typeof";return XG=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},XG(s)}function vMe(){return vMe=Object.assign?Object.assign.bind():function(s){for(var t=1;ts.length)&&(t=s.length);for(var n=0,r=new Array(t);n=0)&&Object.prototype.propertyIsEnumerable.call(s,r)&&(n[r]=s[r])}return n}function a4n(s,t){if(s==null)return{};var n={};for(var r in s)if(Object.prototype.hasOwnProperty.call(s,r)){if(t.indexOf(r)>=0)continue;n[r]=s[r]}return n}function i4n(s,t){if(!(s instanceof t))throw new TypeError("Cannot call a class as a function")}function o4n(s,t){for(var n=0;ns.length)&&(t=s.length);for(var n=0,r=new Array(t);n1&&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=(n=r==null?void 0:r.length)!==null&&n!==void 0?n: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,h=a[d].coordinate,m=d>=o-1?a[0].coordinate:a[d+1].coordinate,f=void 0;if(w_(h-u)!==w_(m-h)){var g=[];if(w_(m-h)===w_(c[1]-c[0])){f=m;var x=h+c[1]-c[0];g[0]=Math.min(x,(x+u)/2),g[1]=Math.max(x,(x+u)/2)}else{f=u;var y=m+c[1]-c[0];g[0]=Math.min(h,(y+h)/2),g[1]=Math.max(h,(y+h)/2)}var v=[Math.min(h,(f+h)/2),Math.max(h,(f+h)/2)];if(t>v[0]&&t<=v[1]||t>=g[0]&&t<=g[1]){l=a[d].index;break}}else{var b=Math.min(u,m),w=Math.max(u,m);if(t>(b+h)/2&&t<=(w+h)/2){l=a[d].index;break}}}else for(var S=0;S0&&S(r[S].coordinate+r[S-1].coordinate)/2&&t<=(r[S].coordinate+r[S+1].coordinate)/2||S===o-1&&t>(r[S].coordinate+r[S-1].coordinate)/2){l=r[S].index;break}return l},$at=function(t){var n,r=t,a=r.type.displayName,i=(n=t.type)!==null&&n!==void 0&&n.defaultProps?xx(xx({},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},N4n=function(t){var n=t.barSize,r=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(v&&v.length){var b=v[0].type.defaultProps,w=b!==void 0?xx(xx({},b),v[0].props):v[0].props,S=w.barSize,C=w[y];l[C]||(l[C]=[]);var E=Wc(S)?n:S;l[C].push({item:v[0],stackList:v.slice(1),barSize:Wc(E)?void 0:j_(E,r,0)})}}return l},k4n=function(t){var n=t.barGap,r=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=j_(n,a,0,!0),u,h=[];if(l[0].barSize===+l[0].barSize){var m=!1,f=a/c,g=l.reduce(function(S,C){return S+C.barSize||0},0);g+=(c-1)*d,g>=a&&(g-=(c-1)*d,d=0),g>=a&&f>0&&(m=!0,f*=.9,g=c*f);var x=(a-g)/2>>0,y={offset:x-d,size:0};u=l.reduce(function(S,C){var E={item:C.item,position:{offset:y.offset+y.size+d,size:m?f:C.barSize}},I=[].concat(uNt(S),[E]);return y=I[I.length-1].position,C.stackList&&C.stackList.length&&C.stackList.forEach(function(P){I.push({item:P,position:y})}),I},h)}else{var v=j_(r,a,0,!0);a-2*v-(c-1)*d<=0&&(d=0);var b=(a-2*v-(c-1)*d)/c;b>1&&(b>>=0);var w=o===+o?Math.min(b,o):b;u=l.reduce(function(S,C,E){var I=[].concat(uNt(S),[{item:C.item,position:{offset:v+(b+d)*E+(b-w)/2,size:w}}]);return C.stackList&&C.stackList.length&&C.stackList.forEach(function(P){I.push({item:P,position:I[I.length-1].position})}),I},h)}return u},S4n=function(t,n,r,a){var i=r.children,l=r.width,o=r.margin,c=l-(o.left||0)-(o.right||0),d=dZt({children:i,legendWidth:c});if(d){var u=a||{},h=u.width,m=u.height,f=d.align,g=d.verticalAlign,x=d.layout;if((x==="vertical"||x==="horizontal"&&g==="middle")&&f!=="center"&&yi(t[f]))return xx(xx({},t),{},IV({},f,t[f]+(h||0)));if((x==="horizontal"||x==="vertical"&&f==="center")&&g!=="middle"&&yi(t[g]))return xx(xx({},t),{},IV({},g,t[g]+(m||0)))}return t},C4n=function(t,n,r){return Wc(n)?!0:t==="horizontal"?n==="yAxis":t==="vertical"||r==="x"?n==="xAxis":r==="y"?n==="yAxis":!0},uZt=function(t,n,r,a,i){var l=n.props.children,o=k2(l,Pie).filter(function(d){return C4n(a,i,d.props.direction)});if(o&&o.length){var c=o.map(function(d){return d.props.dataKey});return t.reduce(function(d,u){var h=oy(u,r);if(Wc(h))return d;var m=Array.isArray(h)?[$Re(h),NI(h)]:[h,h],f=c.reduce(function(g,x){var y=oy(u,x,0),v=m[0]-Math.abs(Array.isArray(y)?y[0]:y),b=m[1]+Math.abs(Array.isArray(y)?y[1]:y);return[Math.min(v,g[0]),Math.max(b,g[1])]},[1/0,-1/0]);return[Math.min(f[0],d[0]),Math.max(f[1],d[1])]},[1/0,-1/0])}return null},A4n=function(t,n,r,a,i){var l=n.map(function(o){return uZt(t,o,r,i,a)}).filter(function(o){return!Wc(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},hZt=function(t,n,r,a,i){var l=n.map(function(c){var d=c.props.dataKey;return r==="number"&&d&&uZt(t,c,d,a)||Wee(t,d,r,i)});if(r==="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 u=0,h=d.length;u=2?w_(o[0]-o[1])*2*d:d,n&&(t.ticks||t.niceTicks)){var u=(t.ticks||t.niceTicks).map(function(h){var m=i?i.indexOf(h):h;return{coordinate:a(m)+d,value:h,offset:d}});return u.filter(function(h){return!TK(h.coordinate)})}return t.isCategorical&&t.categoricalDomain?t.categoricalDomain.map(function(h,m){return{coordinate:a(h)+d,value:h,index:m,offset:d}}):a.ticks&&!r?a.ticks(t.tickCount).map(function(h){return{coordinate:a(h)+d,value:h,offset:d}}):a.domain().map(function(h,m){return{coordinate:a(h)+d,value:i?i[h]:h,index:m,offset:d}})},A9e=new WeakMap,Zde=function(t,n){if(typeof n!="function")return t;A9e.has(t)||A9e.set(t,new WeakMap);var r=A9e.get(t);if(r.has(n))return r.get(n);var a=function(){t.apply(void 0,arguments),n.apply(void 0,arguments)};return r.set(n,a),a},pZt=function(t,n,r){var a=t.scale,i=t.type,l=t.layout,o=t.axisType;if(a==="auto")return l==="radial"&&o==="radiusAxis"?{scale:$se(),realScaleType:"band"}:l==="radial"&&o==="angleAxis"?{scale:fMe(),realScaleType:"linear"}:i==="category"&&n&&(n.indexOf("LineChart")>=0||n.indexOf("AreaChart")>=0||n.indexOf("ComposedChart")>=0&&!r)?{scale:Gee(),realScaleType:"point"}:i==="category"?{scale:$se(),realScaleType:"band"}:{scale:fMe(),realScaleType:"linear"};if(iB(a)){var c="scale".concat(CRe(a));return{scale:(aNt[c]||Gee)(),realScaleType:aNt[c]?c:"point"}}return ic(a)?{scale:a}:{scale:Gee(),realScaleType:"point"}},mNt=1e-4,gZt=function(t){var n=t.domain();if(!(!n||n.length<=2)){var r=n.length,a=t.range(),i=Math.min(a[0],a[1])-mNt,l=Math.max(a[0],a[1])+mNt,o=t(n[0]),c=t(n[r-1]);(ol||cl)&&t.domain([n[0],n[r-1]])}},E4n=function(t,n){if(!t)return null;for(var r=0,a=t.length;ra)&&(i[1]=a),i[0]>a&&(i[0]=a),i[1]=0?(t[o][r][0]=i,t[o][r][1]=i+c,i=t[o][r][1]):(t[o][r][0]=l,t[o][r][1]=l+c,l=t[o][r][1])}},P4n=function(t){var n=t.length;if(!(n<=0))for(var r=0,a=t[0].length;r=0?(t[l][r][0]=i,t[l][r][1]=i+o,i=t[l][r][1]):(t[l][r][0]=0,t[l][r][1]=0)}},I4n={sign:M4n,expand:Qyn,none:qG,silhouette:Jyn,wiggle:e0n,positive:P4n},L4n=function(t,n,r){var a=n.map(function(o){return o.props.dataKey}),i=I4n[r],l=Xyn().keys(a).value(function(o,c){return+oy(o,c,0)}).order(iKe).offset(i);return l(t)},R4n=function(t,n,r,a,i,l){if(!t)return null;var o=l?n.reverse():n,c={},d=o.reduce(function(h,m){var f,g=(f=m.type)!==null&&f!==void 0&&f.defaultProps?xx(xx({},m.type.defaultProps),m.props):m.props,x=g.stackId,y=g.hide;if(y)return h;var v=g[r],b=h[v]||{hasStack:!1,stackGroups:{}};if(C0(x)){var w=b.stackGroups[x]||{numericAxisId:r,cateAxisId:a,items:[]};w.items.push(m),b.hasStack=!0,b.stackGroups[x]=w}else b.stackGroups[e9("_stackId_")]={numericAxisId:r,cateAxisId:a,items:[m]};return xx(xx({},h),{},IV({},v,b))},c),u={};return Object.keys(d).reduce(function(h,m){var f=d[m];if(f.hasStack){var g={};f.stackGroups=Object.keys(f.stackGroups).reduce(function(x,y){var v=f.stackGroups[y];return xx(xx({},x),{},IV({},y,{numericAxisId:r,cateAxisId:a,items:v.items,stackedData:L4n(t,v.items,i)}))},g)}return xx(xx({},h),{},IV({},m,f))},u)},xZt=function(t,n){var r=n.realScaleType,a=n.type,i=n.tickCount,l=n.originalDomain,o=n.allowDecimals,c=r||n.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 u=Y5n(d,i,o);return t.domain([$Re(u),NI(u)]),{niceTicks:u}}if(i&&a==="number"){var h=t.domain(),m=Z5n(h,i,o);return{niceTicks:m}}return null};function _Me(s){var t=s.axis,n=s.ticks,r=s.bandSize,a=s.entry,i=s.index,l=s.dataKey;if(t.type==="category"){if(!t.allowDuplicatedCategory&&t.dataKey&&!Wc(a[t.dataKey])){var o=GTe(n,"value",a[t.dataKey]);if(o)return o.coordinate+r/2}return n[i]?n[i].coordinate+r/2:null}var c=oy(a,Wc(l)?t.dataKey:l);return Wc(c)?null:t.scale(c)}var fNt=function(t){var n=t.axis,r=t.ticks,a=t.offset,i=t.bandSize,l=t.entry,o=t.index;if(n.type==="category")return r[o]?r[o].coordinate+a:null;var c=oy(l,n.dataKey,n.domain[o]);return Wc(c)?null:n.scale(c)-i/2+a},D4n=function(t){var n=t.numericAxis,r=n.scale.domain();if(n.type==="number"){var a=Math.min(r[0],r[1]),i=Math.max(r[0],r[1]);return a<=0&&i>=0?0:i<0?i:a}return r[0]},F4n=function(t,n){var r,a=(r=t.type)!==null&&r!==void 0&&r.defaultProps?xx(xx({},t.type.defaultProps),t.props):t.props,i=a.stackId;if(C0(i)){var l=n[i];if(l){var o=l.items.indexOf(t);return o>=0?l.stackedData[o]:null}}return null},O4n=function(t){return t.reduce(function(n,r){return[$Re(r.concat([n[0]]).filter(yi)),NI(r.concat([n[1]]).filter(yi))]},[1/0,-1/0])},yZt=function(t,n,r){return Object.keys(t).reduce(function(a,i){var l=t[i],o=l.stackedData,c=o.reduce(function(d,u){var h=O4n(u.slice(n,r+1));return[Math.min(d[0],h[0]),Math.max(d[1],h[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})},pNt=/^dataMin[\s]*-[\s]*([0-9]+([.]{1}[0-9]+){0,1})$/,gNt=/^dataMax[\s]*\+[\s]*([0-9]+([.]{1}[0-9]+){0,1})$/,DKe=function(t,n,r){if(ic(t))return t(n,r);if(!Array.isArray(t))return n;var a=[];if(yi(t[0]))a[0]=r?t[0]:Math.min(t[0],n[0]);else if(pNt.test(t[0])){var i=+pNt.exec(t[0])[1];a[0]=n[0]-i}else ic(t[0])?a[0]=t[0](n[0]):a[0]=n[0];if(yi(t[1]))a[1]=r?t[1]:Math.max(t[1],n[1]);else if(gNt.test(t[1])){var l=+gNt.exec(t[1])[1];a[1]=n[1]+l}else ic(t[1])?a[1]=t[1](n[1]):a[1]=n[1];return a},wMe=function(t,n,r){if(t&&t.scale&&t.scale.bandwidth){var a=t.scale.bandwidth();if(!r||a>0)return a}if(t&&n&&n.length>=2){for(var i=pat(n,function(h){return h.coordinate}),l=1/0,o=1,c=i.length;os.length)&&(t=s.length);for(var n=0,r=new Array(t);n2&&arguments[2]!==void 0?arguments[2]:{top:0,right:0,bottom:0,left:0};return Math.min(Math.abs(t-(r.left||0)-(r.right||0)),Math.abs(n-(r.top||0)-(r.bottom||0)))/2},W4n=function(t,n,r,a,i){var l=t.width,o=t.height,c=t.startAngle,d=t.endAngle,u=j_(t.cx,l,l/2),h=j_(t.cy,o,o/2),m=_Zt(l,o,r),f=j_(t.innerRadius,m,0),g=j_(t.outerRadius,m,m*.8),x=Object.keys(n);return x.reduce(function(y,v){var b=n[v],w=b.domain,S=b.reversed,C;if(Wc(b.range))a==="angleAxis"?C=[c,d]:a==="radiusAxis"&&(C=[f,g]),S&&(C=[C[1],C[0]]);else{C=b.range;var E=C,I=$4n(E,2);c=I[0],d=I[1]}var P=pZt(b,i),R=P.realScaleType,D=P.scale;D.domain(w).range(C),gZt(D);var O=xZt(D,TA(TA({},b),{},{realScaleType:R})),U=TA(TA(TA({},b),O),{},{range:C,radius:g,realScaleType:R,scale:D,cx:u,cy:h,innerRadius:f,outerRadius:g,startAngle:c,endAngle:d});return TA(TA({},y),{},bZt({},v,U))},{})},K4n=function(t,n){var r=t.x,a=t.y,i=n.x,l=n.y;return Math.sqrt(Math.pow(r-i,2)+Math.pow(a-l,2))},Y4n=function(t,n){var r=t.x,a=t.y,i=n.cx,l=n.cy,o=K4n({x:r,y:a},{x:i,y:l});if(o<=0)return{radius:o};var c=(r-i)/o,d=Math.acos(c);return a>l&&(d=2*Math.PI-d),{radius:o,angle:G4n(d),angleInRadian:d}},Z4n=function(t){var n=t.startAngle,r=t.endAngle,a=Math.floor(n/360),i=Math.floor(r/360),l=Math.min(a,i);return{startAngle:n-l*360,endAngle:r-l*360}},X4n=function(t,n){var r=n.startAngle,a=n.endAngle,i=Math.floor(r/360),l=Math.floor(a/360),o=Math.min(i,l);return t+o*360},bNt=function(t,n){var r=t.x,a=t.y,i=Y4n({x:r,y:a},n),l=i.radius,o=i.angle,c=n.innerRadius,d=n.outerRadius;if(ld)return!1;if(l===0)return!0;var u=Z4n(n),h=u.startAngle,m=u.endAngle,f=o,g;if(h<=m){for(;f>m;)f-=360;for(;f=h&&f<=m}else{for(;f>h;)f-=360;for(;f=m&&f<=h}return g?TA(TA({},n),{},{radius:l,angle:X4n(f,n)}):null},wZt=function(t){return!j.isValidElement(t)&&!ic(t)&&typeof t!="boolean"?t.className:""};function Xse(s){"@babel/helpers - typeof";return Xse=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},Xse(s)}var Q4n=["offset"];function J4n(s){return n3n(s)||s3n(s)||t3n(s)||e3n()}function e3n(){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 t3n(s,t){if(s){if(typeof s=="string")return FKe(s,t);var n=Object.prototype.toString.call(s).slice(8,-1);if(n==="Object"&&s.constructor&&(n=s.constructor.name),n==="Map"||n==="Set")return Array.from(s);if(n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return FKe(s,t)}}function s3n(s){if(typeof Symbol<"u"&&s[Symbol.iterator]!=null||s["@@iterator"]!=null)return Array.from(s)}function n3n(s){if(Array.isArray(s))return FKe(s)}function FKe(s,t){(t==null||t>s.length)&&(t=s.length);for(var n=0,r=new Array(t);n=0)&&Object.prototype.propertyIsEnumerable.call(s,r)&&(n[r]=s[r])}return n}function a3n(s,t){if(s==null)return{};var n={};for(var r in s)if(Object.prototype.hasOwnProperty.call(s,r)){if(t.indexOf(r)>=0)continue;n[r]=s[r]}return n}function _Nt(s,t){var n=Object.keys(s);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(s);t&&(r=r.filter(function(a){return Object.getOwnPropertyDescriptor(s,a).enumerable})),n.push.apply(n,r)}return n}function a0(s){for(var t=1;t=0?1:-1,w,S;a==="insideStart"?(w=f+b*l,S=x):a==="insideEnd"?(w=g-b*l,S=!x):a==="end"&&(w=g+b*l,S=x),S=v<=0?S:!S;var C=Yf(d,u,y,w),E=Yf(d,u,y,w+(S?1:-1)*359),I="M".concat(C.x,",").concat(C.y,` A`).concat(y,",").concat(y,",0,1,").concat(S?0:1,`, `).concat(E.x,",").concat(E.y),P=Wc(t.id)?e9("recharts-radial-line-"):t.id;return Gt.createElement("text",Qse({},r,{dominantBaseline:"central",className:rd("recharts-radial-bar-label",o)}),Gt.createElement("defs",null,Gt.createElement("path",{id:P,d:I})),Gt.createElement("textPath",{xlinkHref:"#".concat(P)},n))},h3n=function(t){var n=t.viewBox,r=t.offset,a=t.position,i=n,l=i.cx,o=i.cy,c=i.innerRadius,d=i.outerRadius,u=i.startAngle,h=i.endAngle,m=(u+h)/2;if(a==="outside"){var f=Yf(l,o,d+r,m),g=f.x,x=f.y;return{x:g,y:x,textAnchor:g>=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 y=(c+d)/2,v=Yf(l,o,y,m),b=v.x,w=v.y;return{x:b,y:w,textAnchor:"middle",verticalAnchor:"middle"}},m3n=function(t){var n=t.viewBox,r=t.parentViewBox,a=t.offset,i=t.position,l=n,o=l.x,c=l.y,d=l.width,u=l.height,h=u>=0?1:-1,m=h*a,f=h>0?"end":"start",g=h>0?"start":"end",x=d>=0?1:-1,y=x*a,v=x>0?"end":"start",b=x>0?"start":"end";if(i==="top"){var w={x:o+d/2,y:c-h*a,textAnchor:"middle",verticalAnchor:f};return a0(a0({},w),r?{height:Math.max(c-r.y,0),width:d}:{})}if(i==="bottom"){var S={x:o+d/2,y:c+u+m,textAnchor:"middle",verticalAnchor:g};return a0(a0({},S),r?{height:Math.max(r.y+r.height-(c+u),0),width:d}:{})}if(i==="left"){var C={x:o-y,y:c+u/2,textAnchor:v,verticalAnchor:"middle"};return a0(a0({},C),r?{width:Math.max(C.x-r.x,0),height:u}:{})}if(i==="right"){var E={x:o+d+y,y:c+u/2,textAnchor:b,verticalAnchor:"middle"};return a0(a0({},E),r?{width:Math.max(r.x+r.width-E.x,0),height:u}:{})}var I=r?{width:d,height:u}:{};return i==="insideLeft"?a0({x:o+y,y:c+u/2,textAnchor:b,verticalAnchor:"middle"},I):i==="insideRight"?a0({x:o+d-y,y:c+u/2,textAnchor:v,verticalAnchor:"middle"},I):i==="insideTop"?a0({x:o+d/2,y:c+m,textAnchor:"middle",verticalAnchor:g},I):i==="insideBottom"?a0({x:o+d/2,y:c+u-m,textAnchor:"middle",verticalAnchor:f},I):i==="insideTopLeft"?a0({x:o+y,y:c+m,textAnchor:b,verticalAnchor:g},I):i==="insideTopRight"?a0({x:o+d-y,y:c+m,textAnchor:v,verticalAnchor:g},I):i==="insideBottomLeft"?a0({x:o+y,y:c+u-m,textAnchor:b,verticalAnchor:f},I):i==="insideBottomRight"?a0({x:o+d-y,y:c+u-m,textAnchor:v,verticalAnchor:f},I):SK(i)&&(yi(i.x)||v8(i.x))&&(yi(i.y)||v8(i.y))?a0({x:o+j_(i.x,d),y:c+j_(i.y,u),textAnchor:"end",verticalAnchor:"end"},I):a0({x:o+d/2,y:c+u/2,textAnchor:"middle",verticalAnchor:"middle"},I)},f3n=function(t){return"cx"in t&&yi(t.cx)};function bv(s){var t=s.offset,n=t===void 0?5:t,r=r3n(s,Q4n),a=a0({offset:n},r),i=a.viewBox,l=a.position,o=a.value,c=a.children,d=a.content,u=a.className,h=u===void 0?"":u,m=a.textBreakAll;if(!i||Wc(o)&&Wc(c)&&!j.isValidElement(d)&&!ic(d))return null;if(j.isValidElement(d))return j.cloneElement(d,a);var f;if(ic(d)){if(f=j.createElement(d,a),j.isValidElement(f))return f}else f=c3n(a);var g=f3n(i),x=cl(a,!0);if(g&&(l==="insideStart"||l==="insideEnd"||l==="end"))return u3n(a,f,x);var y=g?h3n(a):m3n(a);return Gt.createElement(lB,Qse({className:rd("recharts-label",h)},x,y,{breakAll:m}),f)}bv.displayName="Label";var jZt=function(t){var n=t.cx,r=t.cy,a=t.angle,i=t.startAngle,l=t.endAngle,o=t.r,c=t.radius,d=t.innerRadius,u=t.outerRadius,h=t.x,m=t.y,f=t.top,g=t.left,x=t.width,y=t.height,v=t.clockWise,b=t.labelViewBox;if(b)return b;if(yi(x)&&yi(y)){if(yi(h)&&yi(m))return{x:h,y:m,width:x,height:y};if(yi(f)&&yi(g))return{x:f,y:g,width:x,height:y}}return yi(h)&&yi(m)?{x:h,y:m,width:0,height:0}:yi(n)&&yi(r)?{cx:n,cy:r,startAngle:i||a||0,endAngle:l||a||0,innerRadius:d||0,outerRadius:u||c||o||0,clockWise:v}:t.viewBox?t.viewBox:{}},p3n=function(t,n){return t?t===!0?Gt.createElement(bv,{key:"label-implicit",viewBox:n}):C0(t)?Gt.createElement(bv,{key:"label-implicit",viewBox:n,value:t}):j.isValidElement(t)?t.type===bv?j.cloneElement(t,{key:"label-implicit",viewBox:n}):Gt.createElement(bv,{key:"label-implicit",content:t,viewBox:n}):ic(t)?Gt.createElement(bv,{key:"label-implicit",content:t,viewBox:n}):SK(t)?Gt.createElement(bv,Qse({viewBox:n},t,{key:"label-implicit"})):null:null},g3n=function(t,n){var r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0;if(!t||!t.children&&r&&!t.label)return null;var a=t.children,i=jZt(t),l=k2(a,bv).map(function(c,d){return j.cloneElement(c,{viewBox:n||i,key:"label-".concat(d)})});if(!r)return l;var o=p3n(t.label,n||i);return[o].concat(J4n(l))};bv.parseViewBox=jZt;bv.renderCallByParent=g3n;function x3n(s){var t=s==null?0:s.length;return t?s[t-1]:void 0}var y3n=x3n;const v3n=au(y3n);function Jse(s){"@babel/helpers - typeof";return Jse=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},Jse(s)}var b3n=["valueAccessor"],_3n=["data","dataKey","clockWise","id","textBreakAll"];function w3n(s){return S3n(s)||k3n(s)||N3n(s)||j3n()}function j3n(){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 N3n(s,t){if(s){if(typeof s=="string")return OKe(s,t);var n=Object.prototype.toString.call(s).slice(8,-1);if(n==="Object"&&s.constructor&&(n=s.constructor.name),n==="Map"||n==="Set")return Array.from(s);if(n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return OKe(s,t)}}function k3n(s){if(typeof Symbol<"u"&&s[Symbol.iterator]!=null||s["@@iterator"]!=null)return Array.from(s)}function S3n(s){if(Array.isArray(s))return OKe(s)}function OKe(s,t){(t==null||t>s.length)&&(t=s.length);for(var n=0,r=new Array(t);n=0)&&Object.prototype.propertyIsEnumerable.call(s,r)&&(n[r]=s[r])}return n}function T3n(s,t){if(s==null)return{};var n={};for(var r in s)if(Object.prototype.hasOwnProperty.call(s,r)){if(t.indexOf(r)>=0)continue;n[r]=s[r]}return n}var M3n=function(t){return Array.isArray(t.value)?v3n(t.value):t.value};function q4(s){var t=s.valueAccessor,n=t===void 0?M3n:t,r=NNt(s,b3n),a=r.data,i=r.dataKey,l=r.clockWise,o=r.id,c=r.textBreakAll,d=NNt(r,_3n);return!a||!a.length?null:Gt.createElement(Cu,{className:"recharts-label-list"},a.map(function(u,h){var m=Wc(i)?n(u,h):oy(u&&u.payload,i),f=Wc(o)?{}:{id:"".concat(o,"-").concat(h)};return Gt.createElement(bv,NMe({},cl(u,!0),d,f,{parentViewBox:u.parentViewBox,value:m,textBreakAll:c,viewBox:bv.parseViewBox(Wc(l)?u:jNt(jNt({},u),{},{clockWise:l})),key:"label-".concat(h),index:h}))}))}q4.displayName="LabelList";function P3n(s,t){return s?s===!0?Gt.createElement(q4,{key:"labelList-implicit",data:t}):Gt.isValidElement(s)||ic(s)?Gt.createElement(q4,{key:"labelList-implicit",data:t,content:s}):SK(s)?Gt.createElement(q4,NMe({data:t},s,{key:"labelList-implicit"})):null:null}function I3n(s,t){var n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0;if(!s||!s.children&&n&&!s.label)return null;var r=s.children,a=k2(r,q4).map(function(l,o){return j.cloneElement(l,{data:t,key:"labelList-".concat(o)})});if(!n)return a;var i=P3n(s.label,t);return[i].concat(w3n(a))}q4.renderCallByParent=I3n;function ene(s){"@babel/helpers - typeof";return ene=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},ene(s)}function zKe(){return zKe=Object.assign?Object.assign.bind():function(s){for(var t=1;t180),",").concat(+(l>d),`, `).concat(h.x,",").concat(h.y,` `);if(a>0){var f=Yf(n,r,a,l),g=Yf(n,r,a,d);m+="L ".concat(g.x,",").concat(g.y,` A `).concat(a,",").concat(a,`,0, `).concat(+(Math.abs(c)>180),",").concat(+(l<=d),`, `).concat(f.x,",").concat(f.y," Z")}else m+="L ".concat(n,",").concat(r," Z");return m},O3n=function(t){var n=t.cx,r=t.cy,a=t.innerRadius,i=t.outerRadius,l=t.cornerRadius,o=t.forceCornerRadius,c=t.cornerIsExternal,d=t.startAngle,u=t.endAngle,h=w_(u-d),m=Xde({cx:n,cy:r,radius:i,angle:d,sign:h,cornerRadius:l,cornerIsExternal:c}),f=m.circleTangency,g=m.lineTangency,x=m.theta,y=Xde({cx:n,cy:r,radius:i,angle:u,sign:-h,cornerRadius:l,cornerIsExternal:c}),v=y.circleTangency,b=y.lineTangency,w=y.theta,S=c?Math.abs(d-u):Math.abs(d-u)-x-w;if(S<0)return o?"M ".concat(g.x,",").concat(g.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 `):NZt({cx:n,cy:r,innerRadius:a,outerRadius:i,startAngle:d,endAngle:u});var C="M ".concat(g.x,",").concat(g.y,` A`).concat(l,",").concat(l,",0,0,").concat(+(h<0),",").concat(f.x,",").concat(f.y,` A`).concat(i,",").concat(i,",0,").concat(+(S>180),",").concat(+(h<0),",").concat(v.x,",").concat(v.y,` A`).concat(l,",").concat(l,",0,0,").concat(+(h<0),",").concat(b.x,",").concat(b.y,` `);if(a>0){var E=Xde({cx:n,cy:r,radius:a,angle:d,sign:h,isExternal:!0,cornerRadius:l,cornerIsExternal:c}),I=E.circleTangency,P=E.lineTangency,R=E.theta,D=Xde({cx:n,cy:r,radius:a,angle:u,sign:-h,isExternal:!0,cornerRadius:l,cornerIsExternal:c}),O=D.circleTangency,U=D.lineTangency,W=D.theta,V=c?Math.abs(d-u):Math.abs(d-u)-R-W;if(V<0&&l===0)return"".concat(C,"L").concat(n,",").concat(r,"Z");C+="L".concat(U.x,",").concat(U.y,` A`).concat(l,",").concat(l,",0,0,").concat(+(h<0),",").concat(O.x,",").concat(O.y,` A`).concat(a,",").concat(a,",0,").concat(+(V>180),",").concat(+(h>0),",").concat(I.x,",").concat(I.y,` A`).concat(l,",").concat(l,",0,0,").concat(+(h<0),",").concat(P.x,",").concat(P.y,"Z")}else C+="L".concat(n,",").concat(r,"Z");return C},z3n={cx:0,cy:0,innerRadius:0,outerRadius:0,startAngle:0,endAngle:0,cornerRadius:0,forceCornerRadius:!1,cornerIsExternal:!1},kZt=function(t){var n=SNt(SNt({},z3n),t),r=n.cx,a=n.cy,i=n.innerRadius,l=n.outerRadius,o=n.cornerRadius,c=n.forceCornerRadius,d=n.cornerIsExternal,u=n.startAngle,h=n.endAngle,m=n.className;if(l0&&Math.abs(u-h)<360?y=O3n({cx:r,cy:a,innerRadius:i,outerRadius:l,cornerRadius:Math.min(x,g/2),forceCornerRadius:c,cornerIsExternal:d,startAngle:u,endAngle:h}):y=NZt({cx:r,cy:a,innerRadius:i,outerRadius:l,startAngle:u,endAngle:h}),Gt.createElement("path",zKe({},cl(n,!0),{className:f,d:y,role:"img"}))};function tne(s){"@babel/helpers - typeof";return tne=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},tne(s)}function BKe(){return BKe=Object.assign?Object.assign.bind():function(s){for(var t=1;tQ3n.call(s,t));function r9(s,t){return s===t||!s&&!t&&s!==s&&t!==t}const tAn="__v",sAn="__o",nAn="_owner",rAn=typeof Float16Array<"u",{getOwnPropertyDescriptor:MNt,keys:PNt}=Object;function aAn(s,t){return s.byteLength===t.byteLength&&kMe(new Uint8Array(s),new Uint8Array(t))}function iAn(s,t,n){let r=s.length;if(t.length!==r)return!1;for(;r-- >0;)if(!n.equals(s[r],t[r],r,r,s,t,n))return!1;return!0}function oAn(s,t){return s.byteLength===t.byteLength&&kMe(new Uint8Array(s.buffer,s.byteOffset,s.byteLength),new Uint8Array(t.buffer,t.byteOffset,t.byteLength))}function lAn(s,t){return r9(s.getTime(),t.getTime())}function INt(s,t,n){return s.name===t.name&&s.message===t.message&&s.stack===t.stack&&n.equals(s.cause,t.cause,"cause","cause",s,t,n)}function cAn(s,t){return s===t}function LNt(s,t,n){const r=s.size;if(r!==t.size)return!1;if(!r)return!0;const a=new Array(r),i=s.entries();let l,o,c=0;for(;(l=i.next())&&!l.done;){const d=t.entries();let u=!1,h=0;for(;(o=d.next())&&!o.done;){if(a[h]){h++;continue}const m=l.value,f=o.value;if(n.equals(m[0],f[0],c,h,s,t,n)&&n.equals(m[1],f[1],m[0],f[0],s,t,n)){u=a[h]=!0;break}h++}if(!u)return!1;c++}return!0}const dAn=r9;function RNt(s,t,n){const r=PNt(s);let a=r.length;if(PNt(t).length!==a)return!1;for(;a-- >0;)if(!EZt(s,t,n,r[a]))return!1;return!0}function B$(s,t,n){const r=TNt(s);let a=r.length;if(TNt(t).length!==a)return!1;let i,l,o;for(;a-- >0;)if(i=r[a],!EZt(s,t,n,i)||(l=MNt(s,i),o=MNt(t,i),(l||o)&&(!l||!o||l.configurable!==o.configurable||l.enumerable!==o.enumerable||l.writable!==o.writable)))return!1;return!0}function uAn(s,t){return r9(s.valueOf(),t.valueOf())}function hAn(s,t){return s.source===t.source&&s.flags===t.flags}function DNt(s,t,n){const r=s.size;if(r!==t.size)return!1;if(!r)return!0;const a=new Array(r),i=s.values();let l,o;for(;(l=i.next())&&!l.done;){const c=t.values();let d=!1,u=0;for(;(o=c.next())&&!o.done;){if(!a[u]&&n.equals(l.value,o.value,l.value,o.value,s,t,n)){d=a[u]=!0;break}u++}if(!d)return!1}return!0}function kMe(s,t){let n=s.length;if(t.length!==n||s.byteOffset!==t.byteOffset)return!1;if(s instanceof Float64Array||s instanceof Float32Array||rAn&&s instanceof Float16Array){for(;n-- >0;)if(s[n]!==t[n]&&(s[n]===s[n]||t[n]===t[n]))return!1;return!0}for(;n-- >0;)if(s[n]!==t[n])return!1;return!0}function mAn(s,t){return s.href===t.href?!0:s.protocol===t.protocol&&s.username===t.username&&s.password===t.password&&s.host===t.host&&s.pathname===t.pathname&&s.hash===t.hash&&fAn(s.searchParams,t.searchParams)}function fAn(s,t){const n=s.toString(),r=t.toString();return n===r||FNt(n)===FNt(r)}function FNt(s){return s.split("&").sort().join("&")}function EZt(s,t,n,r){return(r===nAn||r===sAn||r===tAn)&&(s.$$typeof||t.$$typeof)?!0:eAn(t,r)&&n.equals(s[r],t[r],r,r,s,t,n)}const pAn="[object ArrayBuffer]",gAn="[object Arguments]",xAn="[object Boolean]",yAn="[object DataView]",vAn="[object Date]",bAn="[object Error]",_An="[object Map]",wAn="[object Number]",jAn="[object Object]",NAn="[object RegExp]",kAn="[object Set]",SAn="[object String]",CAn={"[object Int8Array]":!0,"[object Uint8Array]":!0,"[object Uint8ClampedArray]":!0,"[object Int16Array]":!0,"[object Uint16Array]":!0,"[object Int32Array]":!0,"[object Uint32Array]":!0,"[object Float16Array]":!0,"[object Float32Array]":!0,"[object Float64Array]":!0,"[object BigInt64Array]":!0,"[object BigUint64Array]":!0},AAn="[object URL]",EAn=Object.prototype.toString;function TAn({areArrayBuffersEqual:s,areArraysEqual:t,areDataViewsEqual:n,areDatesEqual:r,areErrorsEqual:a,areFunctionsEqual:i,areMapsEqual:l,areNumbersEqual:o,areObjectsEqual:c,arePrimitiveWrappersEqual:d,areRegExpsEqual:u,areSetsEqual:h,areTypedArraysEqual:m,areUrlsEqual:f,unknownTagComparators:g}){return function(y,v,b){if(y===v)return!0;if(y==null||v==null)return!1;const w=typeof y;if(w!==typeof v)return!1;if(w!=="object")return w==="number"?o(y,v,b):w==="function"?i(y,v,b):!1;const S=y.constructor;if(S!==v.constructor)return!1;if(S===Object)return c(y,v,b);if(Array.isArray(y))return t(y,v,b);if(S===Date)return r(y,v,b);if(S===RegExp)return u(y,v,b);if(S===Map)return l(y,v,b);if(S===Set)return h(y,v,b);if(S==null)return c(y,v,b);const C=EAn.call(y);if(C===vAn)return r(y,v,b);if(C===NAn)return u(y,v,b);if(C===_An)return l(y,v,b);if(C===kAn)return h(y,v,b);if(C===jAn)return typeof y.then!="function"&&typeof v.then!="function"&&c(y,v,b);if(C===AAn)return f(y,v,b);if(C===bAn)return a(y,v,b);if(C===gAn)return c(y,v,b);if(CAn[C])return m(y,v,b);if(C===pAn)return s(y,v,b);if(C===yAn)return n(y,v,b);if(C===xAn||C===wAn||C===SAn)return d(y,v,b);if(g){let E=g[C];if(!E){const I=J3n(y);I&&(E=g[I])}if(E)return E(y,v,b)}return!1}}function MAn({circular:s,createCustomConfig:t,strict:n}){let r={areArrayBuffersEqual:aAn,areArraysEqual:n?B$:iAn,areDataViewsEqual:oAn,areDatesEqual:lAn,areErrorsEqual:n?tX(INt,B$):tX(INt,RNt),areFunctionsEqual:cAn,areMapsEqual:n?tX(LNt,B$):LNt,areNumbersEqual:dAn,areObjectsEqual:n?B$:RNt,arePrimitiveWrappersEqual:uAn,areRegExpsEqual:hAn,areSetsEqual:n?tX(DNt,B$):DNt,areTypedArraysEqual:n?tX(kMe,B$):kMe,areUrlsEqual:mAn,unknownTagComparators:void 0};if(t&&(r=Object.assign({},r,t(r))),s){const a=sX(r.areArraysEqual),i=sX(r.areErrorsEqual),l=sX(r.areMapsEqual),o=sX(r.areObjectsEqual),c=sX(r.areSetsEqual);r=Object.assign({},r,{areArraysEqual:a,areErrorsEqual:i,areMapsEqual:l,areObjectsEqual:o,areSetsEqual:c})}return r}function PAn(s){return function(t,n,r,a,i,l,o){return s(t,n,o)}}function IAn({circular:s,comparator:t,createState:n,equals:r,strict:a}){if(n)return function(o,c){const{cache:d=s?new WeakMap:void 0,meta:u}=n();return t(o,c,{cache:d,equals:r,meta:u,strict:a})};if(s)return function(o,c){return t(o,c,{cache:new WeakMap,equals:r,meta:void 0,strict:a})};const i={cache:void 0,equals:r,meta:void 0,strict:a};return function(o,c){return t(o,c,i)}}const LAn=E6();E6({strict:!0});E6({circular:!0});E6({circular:!0,strict:!0});E6({createInternalComparator:()=>r9});E6({strict:!0,createInternalComparator:()=>r9});E6({circular:!0,createInternalComparator:()=>r9});E6({circular:!0,createInternalComparator:()=>r9,strict:!0});function E6(s={}){const{circular:t=!1,createInternalComparator:n,createState:r,strict:a=!1}=s,i=MAn(s),l=TAn(i),o=n?n(l):PAn(l);return IAn({circular:t,comparator:l,createState:r,equals:o,strict:a})}function RAn(s){typeof requestAnimationFrame<"u"&&requestAnimationFrame(s)}function ONt(s){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,n=-1,r=function a(i){n<0&&(n=i),i-n>t?(s(i),n=-1):RAn(a)};requestAnimationFrame(r)}function $Ke(s){"@babel/helpers - typeof";return $Ke=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},$Ke(s)}function DAn(s){return BAn(s)||zAn(s)||OAn(s)||FAn()}function FAn(){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 OAn(s,t){if(s){if(typeof s=="string")return zNt(s,t);var n=Object.prototype.toString.call(s).slice(8,-1);if(n==="Object"&&s.constructor&&(n=s.constructor.name),n==="Map"||n==="Set")return Array.from(s);if(n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return zNt(s,t)}}function zNt(s,t){(t==null||t>s.length)&&(t=s.length);for(var n=0,r=new Array(t);ns.length)&&(t=s.length);for(var n=0,r=new Array(t);n1?1:v<0?0:v},x=function(v){for(var b=v>1?1:v,w=b,S=0;S<8;++S){var C=h(w)-b,E=f(w);if(Math.abs(C-b)0&&arguments[0]!==void 0?arguments[0]:{},n=t.stiff,r=n===void 0?100:n,a=t.damping,i=a===void 0?8:a,l=t.dt,o=l===void 0?17:l,c=function(u,h,m){var f=-(u-h)*r,g=m*i,x=m+(f-g)*o/1e3,y=m*o/1e3+u;return Math.abs(y-h)s.length)&&(t=s.length);for(var n=0,r=new Array(t);n=0)&&Object.prototype.propertyIsEnumerable.call(s,r)&&(n[r]=s[r])}return n}function xEn(s,t){if(s==null)return{};var n={},r=Object.keys(s),a,i;for(i=0;i=0)&&(n[a]=s[a]);return n}function E9e(s){return _En(s)||bEn(s)||vEn(s)||yEn()}function yEn(){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 vEn(s,t){if(s){if(typeof s=="string")return GKe(s,t);var n=Object.prototype.toString.call(s).slice(8,-1);if(n==="Object"&&s.constructor&&(n=s.constructor.name),n==="Map"||n==="Set")return Array.from(s);if(n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return GKe(s,t)}}function bEn(s){if(typeof Symbol<"u"&&s[Symbol.iterator]!=null||s["@@iterator"]!=null)return Array.from(s)}function _En(s){if(Array.isArray(s))return GKe(s)}function GKe(s,t){(t==null||t>s.length)&&(t=s.length);for(var n=0,r=new Array(t);n"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 AMe(s){return AMe=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(n){return n.__proto__||Object.getPrototypeOf(n)},AMe(s)}var vC=function(s){SEn(n,s);var t=CEn(n);function n(r,a){var i;wEn(this,n),i=t.call(this,r,a);var l=i.props,o=l.isActive,c=l.attributeName,d=l.from,u=l.to,h=l.steps,m=l.children,f=l.duration;if(i.handleStyleChange=i.handleStyleChange.bind(YKe(i)),i.changeStyle=i.changeStyle.bind(YKe(i)),!o||f<=0)return i.state={style:{}},typeof m=="function"&&(i.state={style:u}),KKe(i);if(h&&h.length)i.state={style:h[0].style};else if(d){if(typeof m=="function")return i.state={style:d},KKe(i);i.state={style:c?kQ({},c,d):d}}else i.state={style:{}};return i}return NEn(n,[{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,u=i.to,h=i.from,m=this.state.style;if(o){if(!l){var f={style:c?kQ({},c,u):u};this.state&&m&&(c&&m[c]!==u||!c&&m!==u)&&this.setState(f);return}if(!(LAn(a.to,u)&&a.canBegin&&a.isActive)){var g=!a.canBegin||!a.isActive;this.manager&&this.manager.stop(),this.stopJSAnimation&&this.stopJSAnimation();var x=g||d?h:a.to;if(this.state&&m){var y={style:c?kQ({},c,x):x};(c&&m[c]!==x||!c&&m!==x)&&this.setState(y)}this.runAnimation(nS(nS({},this.props),{},{from:x,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,u=a.begin,h=a.onAnimationEnd,m=a.onAnimationStart,f=fEn(l,o,nEn(d),c,this.changeStyle),g=function(){i.stopJSAnimation=f()};this.manager.start([m,u,g,c,h])}},{key:"runStepAnimation",value:function(a){var i=this,l=a.steps,o=a.begin,c=a.onAnimationStart,d=l[0],u=d.style,h=d.duration,m=h===void 0?0:h,f=function(x,y,v){if(v===0)return x;var b=y.duration,w=y.easing,S=w===void 0?"ease":w,C=y.style,E=y.properties,I=y.onAnimationEnd,P=v>0?l[v-1]:y,R=E||Object.keys(C);if(typeof S=="function"||S==="spring")return[].concat(E9e(x),[i.runJSAnimation.bind(i,{from:P.style,to:C,duration:b,easing:S}),b]);var D=UNt(R,b,S),O=nS(nS(nS({},P.style),C),{},{transition:D});return[].concat(E9e(x),[O,b,I]).filter(HAn)};return this.manager.start([c].concat(E9e(l.reduce(f,[u,Math.max(m,o)])),[a.onAnimationEnd]))}},{key:"runAnimation",value:function(a){this.manager||(this.manager=$An());var i=a.begin,l=a.duration,o=a.attributeName,c=a.to,d=a.easing,u=a.onAnimationStart,h=a.onAnimationEnd,m=a.steps,f=a.children,g=this.manager;if(this.unSubscribe=g.subscribe(this.handleStyleChange),typeof d=="function"||typeof f=="function"||d==="spring"){this.runJSAnimation(a);return}if(m.length>1){this.runStepAnimation(a);return}var x=o?kQ({},o,c):c,y=UNt(Object.keys(x),l,d);g.start([u,i,nS(nS({},x),{},{transition:y}),l,h])}},{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=gEn(a,pEn),d=j.Children.count(i),u=this.state.style;if(typeof i=="function")return i(u);if(!o||d===0||l<=0)return i;var h=function(f){var g=f.props,x=g.style,y=x===void 0?{}:x,v=g.className,b=j.cloneElement(f,nS(nS({},c),{},{style:nS(nS({},y),u),className:v}));return b};return d===1?h(j.Children.only(i)):Gt.createElement("div",null,j.Children.map(i,function(m){return h(m)}))}}]),n}(j.PureComponent);vC.displayName="Animate";vC.defaultProps={begin:0,duration:1e3,from:"",to:"",attributeName:"",easing:"ease",isActive:!0,canBegin:!0,steps:[],onAnimationEnd:function(){},onAnimationStart:function(){}};vC.propTypes={from:pm.oneOfType([pm.object,pm.string]),to:pm.oneOfType([pm.object,pm.string]),attributeName:pm.string,duration:pm.number,begin:pm.number,easing:pm.oneOfType([pm.string,pm.func]),steps:pm.arrayOf(pm.shape({duration:pm.number.isRequired,style:pm.object.isRequired,easing:pm.oneOfType([pm.oneOf(["ease","ease-in","ease-out","ease-in-out","linear"]),pm.func]),properties:pm.arrayOf("string"),onAnimationEnd:pm.func})),children:pm.oneOfType([pm.node,pm.func]),isActive:pm.bool,canBegin:pm.bool,onAnimationEnd:pm.func,shouldReAnimate:pm.bool,onAnimationStart:pm.func,onAnimationReStart:pm.func};function rne(s){"@babel/helpers - typeof";return rne=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},rne(s)}function EMe(){return EMe=Object.assign?Object.assign.bind():function(s){for(var t=1;ts.length)&&(t=s.length);for(var n=0,r=new Array(t);n=0?1:-1,c=r>=0?1:-1,d=a>=0&&r>=0||a<0&&r<0?1:0,u;if(l>0&&i instanceof Array){for(var h=[0,0,0,0],m=0,f=4;ml?l:i[m];u="M".concat(t,",").concat(n+o*h[0]),h[0]>0&&(u+="A ".concat(h[0],",").concat(h[0],",0,0,").concat(d,",").concat(t+c*h[0],",").concat(n)),u+="L ".concat(t+r-c*h[1],",").concat(n),h[1]>0&&(u+="A ".concat(h[1],",").concat(h[1],",0,0,").concat(d,`, `).concat(t+r,",").concat(n+o*h[1])),u+="L ".concat(t+r,",").concat(n+a-o*h[2]),h[2]>0&&(u+="A ".concat(h[2],",").concat(h[2],",0,0,").concat(d,`, `).concat(t+r-c*h[2],",").concat(n+a)),u+="L ".concat(t+c*h[3],",").concat(n+a),h[3]>0&&(u+="A ".concat(h[3],",").concat(h[3],",0,0,").concat(d,`, `).concat(t,",").concat(n+a-o*h[3])),u+="Z"}else if(l>0&&i===+i&&i>0){var g=Math.min(l,i);u="M ".concat(t,",").concat(n+o*g,` A `).concat(g,",").concat(g,",0,0,").concat(d,",").concat(t+c*g,",").concat(n,` L `).concat(t+r-c*g,",").concat(n,` A `).concat(g,",").concat(g,",0,0,").concat(d,",").concat(t+r,",").concat(n+o*g,` L `).concat(t+r,",").concat(n+a-o*g,` A `).concat(g,",").concat(g,",0,0,").concat(d,",").concat(t+r-c*g,",").concat(n+a,` L `).concat(t+c*g,",").concat(n+a,` A `).concat(g,",").concat(g,",0,0,").concat(d,",").concat(t,",").concat(n+a-o*g," Z")}else u="M ".concat(t,",").concat(n," h ").concat(r," v ").concat(a," h ").concat(-r," Z");return u},FEn=function(t,n){if(!t||!n)return!1;var r=t.x,a=t.y,i=n.x,l=n.y,o=n.width,c=n.height;if(Math.abs(o)>0&&Math.abs(c)>0){var d=Math.min(i,i+o),u=Math.max(i,i+o),h=Math.min(l,l+c),m=Math.max(l,l+c);return r>=d&&r<=u&&a>=h&&a<=m}return!1},OEn={x:0,y:0,width:0,height:0,radius:0,isAnimationActive:!1,isUpdateAnimationActive:!1,animationBegin:0,animationDuration:1500,animationEasing:"ease"},Uat=function(t){var n=ZNt(ZNt({},OEn),t),r=j.useRef(),a=j.useState(-1),i=EEn(a,2),l=i[0],o=i[1];j.useEffect(function(){if(r.current&&r.current.getTotalLength)try{var S=r.current.getTotalLength();S&&o(S)}catch{}},[]);var c=n.x,d=n.y,u=n.width,h=n.height,m=n.radius,f=n.className,g=n.animationEasing,x=n.animationDuration,y=n.animationBegin,v=n.isAnimationActive,b=n.isUpdateAnimationActive;if(c!==+c||d!==+d||u!==+u||h!==+h||u===0||h===0)return null;var w=rd("recharts-rectangle",f);return b?Gt.createElement(vC,{canBegin:l>0,from:{width:u,height:h,x:c,y:d},to:{width:u,height:h,x:c,y:d},duration:x,animationEasing:g,isActive:b},function(S){var C=S.width,E=S.height,I=S.x,P=S.y;return Gt.createElement(vC,{canBegin:l>0,from:"0px ".concat(l===-1?1:l,"px"),to:"".concat(l,"px 0px"),attributeName:"strokeDasharray",begin:y,duration:x,isActive:v,easing:g},Gt.createElement("path",EMe({},cl(n,!0),{className:w,d:XNt(I,P,C,E,m),ref:r})))}):Gt.createElement("path",EMe({},cl(n,!0),{className:w,d:XNt(c,d,u,h,m)}))},zEn=["points","className","baseLinePoints","connectNulls"];function cq(){return cq=Object.assign?Object.assign.bind():function(s){for(var t=1;t=0)&&Object.prototype.propertyIsEnumerable.call(s,r)&&(n[r]=s[r])}return n}function $En(s,t){if(s==null)return{};var n={};for(var r in s)if(Object.prototype.hasOwnProperty.call(s,r)){if(t.indexOf(r)>=0)continue;n[r]=s[r]}return n}function QNt(s){return HEn(s)||VEn(s)||qEn(s)||UEn()}function UEn(){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 qEn(s,t){if(s){if(typeof s=="string")return ZKe(s,t);var n=Object.prototype.toString.call(s).slice(8,-1);if(n==="Object"&&s.constructor&&(n=s.constructor.name),n==="Map"||n==="Set")return Array.from(s);if(n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return ZKe(s,t)}}function VEn(s){if(typeof Symbol<"u"&&s[Symbol.iterator]!=null||s["@@iterator"]!=null)return Array.from(s)}function HEn(s){if(Array.isArray(s))return ZKe(s)}function ZKe(s,t){(t==null||t>s.length)&&(t=s.length);for(var n=0,r=new Array(t);n0&&arguments[0]!==void 0?arguments[0]:[],n=[[]];return t.forEach(function(r){JNt(r)?n[n.length-1].push(r):n[n.length-1].length>0&&n.push([])}),JNt(t[0])&&n[n.length-1].push(t[0]),n[n.length-1].length<=0&&(n=n.slice(0,-1)),n},Yee=function(t,n){var r=GEn(t);n&&(r=[r.reduce(function(i,l){return[].concat(QNt(i),QNt(l))},[])]);var a=r.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 r.length===1?"".concat(a,"Z"):a},WEn=function(t,n,r){var a=Yee(t,r);return"".concat(a.slice(-1)==="Z"?a.slice(0,-1):a,"L").concat(Yee(n.reverse(),r).slice(1))},KEn=function(t){var n=t.points,r=t.className,a=t.baseLinePoints,i=t.connectNulls,l=BEn(t,zEn);if(!n||!n.length)return null;var o=rd("recharts-polygon",r);if(a&&a.length){var c=l.stroke&&l.stroke!=="none",d=WEn(n,a,i);return Gt.createElement("g",{className:o},Gt.createElement("path",cq({},cl(l,!0),{fill:d.slice(-1)==="Z"?l.fill:"none",stroke:"none",d})),c?Gt.createElement("path",cq({},cl(l,!0),{fill:"none",d:Yee(n,i)})):null,c?Gt.createElement("path",cq({},cl(l,!0),{fill:"none",d:Yee(a,i)})):null)}var u=Yee(n,i);return Gt.createElement("path",cq({},cl(l,!0),{fill:u.slice(-1)==="Z"?l.fill:"none",className:o,d:u}))};function XKe(){return XKe=Object.assign?Object.assign.bind():function(s){for(var t=1;t=0)&&Object.prototype.propertyIsEnumerable.call(s,r)&&(n[r]=s[r])}return n}function tTn(s,t){if(s==null)return{};var n={};for(var r in s)if(Object.prototype.hasOwnProperty.call(s,r)){if(t.indexOf(r)>=0)continue;n[r]=s[r]}return n}var sTn=function(t,n,r,a,i,l){return"M".concat(t,",").concat(i,"v").concat(a,"M").concat(l,",").concat(n,"h").concat(r)},nTn=function(t){var n=t.x,r=n===void 0?0:n,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,u=t.width,h=u===void 0?0:u,m=t.height,f=m===void 0?0:m,g=t.className,x=eTn(t,YEn),y=ZEn({x:r,y:i,top:o,left:d,width:h,height:f},x);return!yi(r)||!yi(i)||!yi(h)||!yi(f)||!yi(o)||!yi(d)?null:Gt.createElement("path",QKe({},cl(y,!0),{className:rd("recharts-cross",g),d:sTn(r,i,h,f,o,d)}))},rTn=BRe,aTn=WYt,iTn=p3;function oTn(s,t){return s&&s.length?rTn(s,iTn(t),aTn):void 0}var lTn=oTn;const cTn=au(lTn);var dTn=BRe,uTn=p3,hTn=KYt;function mTn(s,t){return s&&s.length?dTn(s,uTn(t),hTn):void 0}var fTn=mTn;const pTn=au(fTn);var gTn=["cx","cy","angle","ticks","axisLine"],xTn=["ticks","tick","angle","tickFormatter","stroke"];function JG(s){"@babel/helpers - typeof";return JG=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},JG(s)}function Zee(){return Zee=Object.assign?Object.assign.bind():function(s){for(var t=1;t=0)&&Object.prototype.propertyIsEnumerable.call(s,r)&&(n[r]=s[r])}return n}function yTn(s,t){if(s==null)return{};var n={};for(var r in s)if(Object.prototype.hasOwnProperty.call(s,r)){if(t.indexOf(r)>=0)continue;n[r]=s[r]}return n}function vTn(s,t){if(!(s instanceof t))throw new TypeError("Cannot call a class as a function")}function nkt(s,t){for(var n=0;nikt?l=a==="outer"?"start":"end":i<-ikt?l=a==="outer"?"end":"start":l="middle",l}},{key:"renderAxisLine",value:function(){var r=this.props,a=r.cx,i=r.cy,l=r.radius,o=r.axisLine,c=r.axisLineType,d=jR(jR({},cl(this.props,!1)),{},{fill:"none"},cl(o,!1));if(c==="circle")return Gt.createElement(Iie,JO({className:"recharts-polar-angle-axis-line"},d,{cx:a,cy:i,r:l}));var u=this.props.ticks,h=u.map(function(m){return Yf(a,i,l,m.coordinate)});return Gt.createElement(KEn,JO({className:"recharts-polar-angle-axis-line"},d,{points:h}))}},{key:"renderTicks",value:function(){var r=this,a=this.props,i=a.ticks,l=a.tick,o=a.tickLine,c=a.tickFormatter,d=a.stroke,u=cl(this.props,!1),h=cl(l,!1),m=jR(jR({},u),{},{fill:"none"},cl(o,!1)),f=i.map(function(g,x){var y=r.getTickLineCoord(g),v=r.getTickTextAnchor(g),b=jR(jR(jR({textAnchor:v},u),{},{stroke:"none",fill:d},h),{},{index:x,payload:g,x:y.x2,y:y.y2});return Gt.createElement(Cu,JO({className:rd("recharts-polar-angle-axis-tick",wZt(l)),key:"tick-".concat(g.coordinate)},oB(r.props,g,x)),o&&Gt.createElement("line",JO({className:"recharts-polar-angle-axis-tick-line"},m,y)),l&&t.renderTickItem(l,b,c?c(g.value,x):g.value))});return Gt.createElement(Cu,{className:"recharts-polar-angle-axis-ticks"},f)}},{key:"render",value:function(){var r=this.props,a=r.ticks,i=r.radius,l=r.axisLine;return i<=0||!a||!a.length?null:Gt.createElement(Cu,{className:rd("recharts-polar-angle-axis",this.props.className)},l&&this.renderAxisLine(),this.renderTicks())}}],[{key:"renderTickItem",value:function(r,a,i){var l;return Gt.isValidElement(r)?l=Gt.cloneElement(r,a):ic(r)?l=r(a):l=Gt.createElement(lB,JO({},a,{className:"recharts-polar-angle-axis-tick-value"}),i),l}}])}(j.PureComponent);GRe(WRe,"displayName","PolarAngleAxis");GRe(WRe,"axisType","angleAxis");GRe(WRe,"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 LTn=VKt,RTn=LTn(Object.getPrototypeOf,Object),DTn=RTn,FTn=FT,OTn=DTn,zTn=OT,BTn="[object Object]",$Tn=Function.prototype,UTn=Object.prototype,BZt=$Tn.toString,qTn=UTn.hasOwnProperty,VTn=BZt.call(Object);function HTn(s){if(!zTn(s)||FTn(s)!=BTn)return!1;var t=OTn(s);if(t===null)return!0;var n=qTn.call(t,"constructor")&&t.constructor;return typeof n=="function"&&n instanceof n&&BZt.call(n)==VTn}var GTn=HTn;const WTn=au(GTn);var KTn=FT,YTn=OT,ZTn="[object Boolean]";function XTn(s){return s===!0||s===!1||YTn(s)&&KTn(s)==ZTn}var QTn=XTn;const JTn=au(QTn);function ine(s){"@babel/helpers - typeof";return ine=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},ine(s)}function PMe(){return PMe=Object.assign?Object.assign.bind():function(s){for(var t=1;ts.length)&&(t=s.length);for(var n=0,r=new Array(t);n0,from:{upperWidth:0,lowerWidth:0,height:m,x:c,y:d},to:{upperWidth:u,lowerWidth:h,height:m,x:c,y:d},duration:x,animationEasing:g,isActive:v},function(w){var S=w.upperWidth,C=w.lowerWidth,E=w.height,I=w.x,P=w.y;return Gt.createElement(vC,{canBegin:l>0,from:"0px ".concat(l===-1?1:l,"px"),to:"".concat(l,"px 0px"),attributeName:"strokeDasharray",begin:y,duration:x,easing:g},Gt.createElement("path",PMe({},cl(n,!0),{className:b,d:dkt(I,P,S,C,E),ref:r})))}):Gt.createElement("g",null,Gt.createElement("path",PMe({},cl(n,!0),{className:b,d:dkt(c,d,u,h,m)})))},dMn=["option","shapeType","propTransformer","activeClassName","isActive"];function one(s){"@babel/helpers - typeof";return one=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},one(s)}function uMn(s,t){if(s==null)return{};var n=hMn(s,t),r,a;if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(s);for(a=0;a=0)&&Object.prototype.propertyIsEnumerable.call(s,r)&&(n[r]=s[r])}return n}function hMn(s,t){if(s==null)return{};var n={};for(var r in s)if(Object.prototype.hasOwnProperty.call(s,r)){if(t.indexOf(r)>=0)continue;n[r]=s[r]}return n}function ukt(s,t){var n=Object.keys(s);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(s);t&&(r=r.filter(function(a){return Object.getOwnPropertyDescriptor(s,a).enumerable})),n.push.apply(n,r)}return n}function IMe(s){for(var t=1;t0?N2(w,"paddingAngle",0):0;if(C){var I=w0(C.endAngle-C.startAngle,w.endAngle-w.startAngle),P=Vf(Vf({},w),{},{startAngle:b+E,endAngle:b+I(x)+E});y.push(P),b=P.endAngle}else{var R=w.endAngle,D=w.startAngle,O=w0(0,R-D),U=O(x),W=Vf(Vf({},w),{},{startAngle:b+E,endAngle:b+U+E});y.push(W),b=W.endAngle}}),Gt.createElement(Cu,null,r.renderSectorsStatically(y))})}},{key:"attachKeyboardHandlers",value:function(r){var a=this;r.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 r=this.props,a=r.sectors,i=r.isAnimationActive,l=this.state.prevSectors;return i&&a&&a.length&&(!l||!cB(l,a))?this.renderSectorsWithAnimation():this.renderSectorsStatically(a)}},{key:"componentDidMount",value:function(){this.pieRef&&this.attachKeyboardHandlers(this.pieRef)}},{key:"render",value:function(){var r=this,a=this.props,i=a.hide,l=a.sectors,o=a.className,c=a.label,d=a.cx,u=a.cy,h=a.innerRadius,m=a.outerRadius,f=a.isAnimationActive,g=this.state.isAnimationFinished;if(i||!l||!l.length||!yi(d)||!yi(u)||!yi(h)||!yi(m))return null;var x=rd("recharts-pie",o);return Gt.createElement(Cu,{tabIndex:this.props.rootTabIndex,className:x,ref:function(v){r.pieRef=v}},this.renderSectors(),c&&this.renderLabels(l),bv.renderCallByParent(this.props,null,!1),(!f||g)&&q4.renderCallByParent(this.props,l,!1))}}],[{key:"getDerivedStateFromProps",value:function(r,a){return a.prevIsAnimationActive!==r.isAnimationActive?{prevIsAnimationActive:r.isAnimationActive,prevAnimationId:r.animationId,curSectors:r.sectors,prevSectors:[],isAnimationFinished:!0}:r.isAnimationActive&&r.animationId!==a.prevAnimationId?{prevAnimationId:r.animationId,curSectors:r.sectors,prevSectors:a.curSectors,isAnimationFinished:!0}:r.sectors!==a.curSectors?{curSectors:r.sectors,isAnimationFinished:!0}:null}},{key:"getTextAnchor",value:function(r,a){return r>a?"start":r=360?b:b-1)*c,S=y-b*f-w,C=a.reduce(function(P,R){var D=oy(R,v,0);return P+(yi(D)?D:0)},0),E;if(C>0){var I;E=a.map(function(P,R){var D=oy(P,v,0),O=oy(P,u,R),U=(yi(D)?D:0)/C,W;R?W=I.endAngle+w_(x)*c*(D!==0?1:0):W=l;var V=W+w_(x)*((D!==0?f:0)+U*S),G=(W+V)/2,Y=(g.innerRadius+g.outerRadius)/2,X=[{name:O,value:D,payload:P,dataKey:v,type:m}],ae=Yf(g.cx,g.cy,Y,G);return I=Vf(Vf(Vf({percent:U,cornerRadius:i,name:O,tooltipPayload:X,midAngle:G,middleRadius:Y,tooltipPosition:ae},P),g),{},{value:oy(P,v),startAngle:W,endAngle:V,payload:P,paddingAngle:w_(x)*c}),I})}return Vf(Vf({},g),{},{sectors:E,data:a})});var IMn=Math.ceil,LMn=Math.max;function RMn(s,t,n,r){for(var a=-1,i=LMn(IMn((t-s)/(n||1)),0),l=Array(i);i--;)l[r?i:++a]=s,s+=n;return l}var DMn=RMn,FMn=cYt,pkt=1/0,OMn=17976931348623157e292;function zMn(s){if(!s)return s===0?s:0;if(s=FMn(s),s===pkt||s===-pkt){var t=s<0?-1:1;return t*OMn}return s===s?s:0}var VZt=zMn,BMn=DMn,$Mn=IRe,T9e=VZt;function UMn(s){return function(t,n,r){return r&&typeof r!="number"&&$Mn(t,n,r)&&(n=r=void 0),t=T9e(t),n===void 0?(n=t,t=0):n=T9e(n),r=r===void 0?t0&&r.handleDrag(a.changedTouches[0])}),Ij(r,"handleDragEnd",function(){r.setState({isTravellerMoving:!1,isSlideMoving:!1},function(){var a=r.props,i=a.endIndex,l=a.onDragEnd,o=a.startIndex;l==null||l({endIndex:i,startIndex:o})}),r.detachDragEndListener()}),Ij(r,"handleLeaveWrapper",function(){(r.state.isTravellerMoving||r.state.isSlideMoving)&&(r.leaveTimer=window.setTimeout(r.handleDragEnd,r.props.leaveTimeOut))}),Ij(r,"handleEnterSlideOrTraveller",function(){r.setState({isTextActive:!0})}),Ij(r,"handleLeaveSlideOrTraveller",function(){r.setState({isTextActive:!1})}),Ij(r,"handleSlideDragStart",function(a){var i=bkt(a)?a.changedTouches[0]:a;r.setState({isTravellerMoving:!1,isSlideMoving:!0,slideMoveStartX:i.pageX}),r.attachDragEndListener()}),r.travellerDragStartHandlers={startX:r.handleTravellerDragStart.bind(r,"startX"),endX:r.handleTravellerDragStart.bind(r,"endX")},r.state={},r}return sPn(t,s),QMn(t,[{key:"componentWillUnmount",value:function(){this.leaveTimer&&(clearTimeout(this.leaveTimer),this.leaveTimer=null),this.detachDragEndListener()}},{key:"getIndex",value:function(r){var a=r.startX,i=r.endX,l=this.state.scaleValues,o=this.props,c=o.gap,d=o.data,u=d.length-1,h=Math.min(a,i),m=Math.max(a,i),f=t.getIndexInRange(l,h),g=t.getIndexInRange(l,m);return{startIndex:f-f%c,endIndex:g===u?u:g-g%c}}},{key:"getTextOfTick",value:function(r){var a=this.props,i=a.data,l=a.tickFormatter,o=a.dataKey,c=oy(i[r],o,r);return ic(l)?l(c,r):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(r){var a=this.state,i=a.slideMoveStartX,l=a.startX,o=a.endX,c=this.props,d=c.x,u=c.width,h=c.travellerWidth,m=c.startIndex,f=c.endIndex,g=c.onChange,x=r.pageX-i;x>0?x=Math.min(x,d+u-h-o,d+u-h-l):x<0&&(x=Math.max(x,d-l,d-o));var y=this.getIndex({startX:l+x,endX:o+x});(y.startIndex!==m||y.endIndex!==f)&&g&&g(y),this.setState({startX:l+x,endX:o+x,slideMoveStartX:r.pageX})}},{key:"handleTravellerDragStart",value:function(r,a){var i=bkt(a)?a.changedTouches[0]:a;this.setState({isSlideMoving:!1,isTravellerMoving:!0,movingTravellerId:r,brushMoveStartX:i.pageX}),this.attachDragEndListener()}},{key:"handleTravellerMove",value:function(r){var a=this.state,i=a.brushMoveStartX,l=a.movingTravellerId,o=a.endX,c=a.startX,d=this.state[l],u=this.props,h=u.x,m=u.width,f=u.travellerWidth,g=u.onChange,x=u.gap,y=u.data,v={startX:this.state.startX,endX:this.state.endX},b=r.pageX-i;b>0?b=Math.min(b,h+m-f-d):b<0&&(b=Math.max(b,h-d)),v[l]=d+b;var w=this.getIndex(v),S=w.startIndex,C=w.endIndex,E=function(){var P=y.length-1;return l==="startX"&&(o>c?S%x===0:C%x===0)||oc?C%x===0:S%x===0)||o>c&&C===P};this.setState(Ij(Ij({},l,d+b),"brushMoveStartX",r.pageX),function(){g&&E()&&g(w)})}},{key:"handleTravellerMoveKeyboard",value:function(r,a){var i=this,l=this.state,o=l.scaleValues,c=l.startX,d=l.endX,u=this.state[a],h=o.indexOf(u);if(h!==-1){var m=h+r;if(!(m===-1||m>=o.length)){var f=o[m];a==="startX"&&f>=d||a==="endX"&&f<=c||this.setState(Ij({},a,f),function(){i.props.onChange(i.getIndex({startX:i.state.startX,endX:i.state.endX}))})}}}},{key:"renderBackground",value:function(){var r=this.props,a=r.x,i=r.y,l=r.width,o=r.height,c=r.fill,d=r.stroke;return Gt.createElement("rect",{stroke:d,fill:c,x:a,y:i,width:l,height:o})}},{key:"renderPanorama",value:function(){var r=this.props,a=r.x,i=r.y,l=r.width,o=r.height,c=r.data,d=r.children,u=r.padding,h=j.Children.only(d);return h?Gt.cloneElement(h,{x:a,y:i,width:l,height:o,margin:u,compact:!0,data:c}):null}},{key:"renderTravellerLayer",value:function(r,a){var i,l,o=this,c=this.props,d=c.y,u=c.travellerWidth,h=c.height,m=c.traveller,f=c.ariaLabel,g=c.data,x=c.startIndex,y=c.endIndex,v=Math.max(r,this.props.x),b=M9e(M9e({},cl(this.props,!1)),{},{x:v,y:d,width:u,height:h}),w=f||"Min value: ".concat((i=g[x])===null||i===void 0?void 0:i.name,", Max value: ").concat((l=g[y])===null||l===void 0?void 0:l.name);return Gt.createElement(Cu,{tabIndex:0,role:"slider","aria-label":w,"aria-valuenow":r,className:"recharts-brush-traveller",onMouseEnter:this.handleEnterSlideOrTraveller,onMouseLeave:this.handleLeaveSlideOrTraveller,onMouseDown:this.travellerDragStartHandlers[a],onTouchStart:this.travellerDragStartHandlers[a],onKeyDown:function(C){["ArrowLeft","ArrowRight"].includes(C.key)&&(C.preventDefault(),C.stopPropagation(),o.handleTravellerMoveKeyboard(C.key==="ArrowRight"?1:-1,a))},onFocus:function(){o.setState({isTravellerFocused:!0})},onBlur:function(){o.setState({isTravellerFocused:!1})},style:{cursor:"col-resize"}},t.renderTraveller(m,b))}},{key:"renderSlide",value:function(r,a){var i=this.props,l=i.y,o=i.height,c=i.stroke,d=i.travellerWidth,u=Math.min(r,a)+d,h=Math.max(Math.abs(a-r)-d,0);return Gt.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:u,y:l,width:h,height:o})}},{key:"renderText",value:function(){var r=this.props,a=r.startIndex,i=r.endIndex,l=r.y,o=r.height,c=r.travellerWidth,d=r.stroke,u=this.state,h=u.startX,m=u.endX,f=5,g={pointerEvents:"none",fill:d};return Gt.createElement(Cu,{className:"recharts-brush-texts"},Gt.createElement(lB,DMe({textAnchor:"end",verticalAnchor:"middle",x:Math.min(h,m)-f,y:l+o/2},g),this.getTextOfTick(a)),Gt.createElement(lB,DMe({textAnchor:"start",verticalAnchor:"middle",x:Math.max(h,m)+c+f,y:l+o/2},g),this.getTextOfTick(i)))}},{key:"render",value:function(){var r=this.props,a=r.data,i=r.className,l=r.children,o=r.x,c=r.y,d=r.width,u=r.height,h=r.alwaysShowText,m=this.state,f=m.startX,g=m.endX,x=m.isTextActive,y=m.isSlideMoving,v=m.isTravellerMoving,b=m.isTravellerFocused;if(!a||!a.length||!yi(o)||!yi(c)||!yi(d)||!yi(u)||d<=0||u<=0)return null;var w=rd("recharts-brush",i),S=Gt.Children.count(l)===1,C=ZMn("userSelect","none");return Gt.createElement(Cu,{className:w,onMouseLeave:this.handleLeaveWrapper,onTouchMove:this.handleTouchMove,style:C},this.renderBackground(),S&&this.renderPanorama(),this.renderSlide(f,g),this.renderTravellerLayer(f,"startX"),this.renderTravellerLayer(g,"endX"),(x||y||v||b||h)&&this.renderText())}}],[{key:"renderDefaultTraveller",value:function(r){var a=r.x,i=r.y,l=r.width,o=r.height,c=r.stroke,d=Math.floor(i+o/2)-1;return Gt.createElement(Gt.Fragment,null,Gt.createElement("rect",{x:a,y:i,width:l,height:o,fill:c,stroke:"none"}),Gt.createElement("line",{x1:a+1,y1:d,x2:a+l-1,y2:d,fill:"none",stroke:"#fff"}),Gt.createElement("line",{x1:a+1,y1:d+2,x2:a+l-1,y2:d+2,fill:"none",stroke:"#fff"}))}},{key:"renderTraveller",value:function(r,a){var i;return Gt.isValidElement(r)?i=Gt.cloneElement(r,a):ic(r)?i=r(a):i=t.renderDefaultTraveller(a),i}},{key:"getDerivedStateFromProps",value:function(r,a){var i=r.data,l=r.width,o=r.x,c=r.travellerWidth,d=r.updateId,u=r.startIndex,h=r.endIndex;if(i!==a.prevData||d!==a.prevUpdateId)return M9e({prevData:i,prevTravellerWidth:c,prevUpdateId:d,prevX:o,prevWidth:l},i&&i.length?rPn({data:i,width:l,x:o,travellerWidth:c,startIndex:u,endIndex:h}):{scale:null,scaleValues:null});if(a.scale&&(l!==a.prevWidth||o!==a.prevX||c!==a.prevTravellerWidth)){a.scale.range([o,o+l-c]);var m=a.scale.domain().map(function(f){return a.scale(f)});return{prevData:i,prevTravellerWidth:c,prevUpdateId:d,prevX:o,prevWidth:l,startX:a.scale(r.startIndex),endX:a.scale(r.endIndex),scaleValues:m}}return null}},{key:"getIndexInRange",value:function(r,a){for(var i=r.length,l=0,o=i-1;o-l>1;){var c=Math.floor((l+o)/2);r[c]>a?o=c:l=c}return a>=r[o]?o:l}}])}(j.PureComponent);Ij(nW,"displayName","Brush");Ij(nW,"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 aPn=fat;function iPn(s,t){var n;return aPn(s,function(r,a,i){return n=t(r,a,i),!n}),!!n}var oPn=iPn,lPn=DKt,cPn=p3,dPn=oPn,uPn=Zw,hPn=IRe;function mPn(s,t,n){var r=uPn(s)?lPn:dPn;return n&&hPn(s,t,n)&&(t=void 0),r(s,cPn(t))}var fPn=mPn;const pPn=au(fPn);var V4=function(t,n){var r=t.alwaysShow,a=t.ifOverflow;return r&&(a="extendDomain"),a===n},_kt=rYt;function gPn(s,t,n){t=="__proto__"&&_kt?_kt(s,t,{configurable:!0,enumerable:!0,value:n,writable:!0}):s[t]=n}var xPn=gPn,yPn=xPn,vPn=sYt,bPn=p3;function _Pn(s,t){var n={};return t=bPn(t),vPn(s,function(r,a,i){yPn(n,a,t(r,a,i))}),n}var wPn=_Pn;const jPn=au(wPn);function NPn(s,t){for(var n=-1,r=s==null?0:s.length;++n=0)&&Object.prototype.propertyIsEnumerable.call(s,r)&&(n[r]=s[r])}return n}function $Pn(s,t){if(s==null)return{};var n={};for(var r in s)if(Object.prototype.hasOwnProperty.call(s,r)){if(t.indexOf(r)>=0)continue;n[r]=s[r]}return n}function UPn(s,t){var n=s.x,r=s.y,a=BPn(s,DPn),i="".concat(n),l=parseInt(i,10),o="".concat(r),c=parseInt(o,10),d="".concat(t.height||a.height),u=parseInt(d,10),h="".concat(t.width||a.width),m=parseInt(h,10);return nX(nX(nX(nX(nX({},t),a),l?{x:l}:{}),c?{y:c}:{}),{},{height:u,width:m,name:t.name,radius:t.radius})}function jkt(s){return Gt.createElement($Zt,nYe({shapeType:"rectangle",propTransformer:UPn,activeClassName:"recharts-active-bar"},s))}var qPn=function(t){var n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0;return function(r,a){if(typeof t=="number")return t;var i=yi(r)||uxn(r);return i?t(r,a):(i||uB(),n)}},VPn=["value","background"],YZt;function rW(s){"@babel/helpers - typeof";return rW=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},rW(s)}function HPn(s,t){if(s==null)return{};var n=GPn(s,t),r,a;if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(s);for(a=0;a=0)&&Object.prototype.propertyIsEnumerable.call(s,r)&&(n[r]=s[r])}return n}function GPn(s,t){if(s==null)return{};var n={};for(var r in s)if(Object.prototype.hasOwnProperty.call(s,r)){if(t.indexOf(r)>=0)continue;n[r]=s[r]}return n}function OMe(){return OMe=Object.assign?Object.assign.bind():function(s){for(var t=1;t0&&Math.abs(G)0&&Math.abs(V)0&&(W=Math.min((_e||0)-(V[he-1]||0),W))}),Number.isFinite(W)){var G=W/U,Y=x.layout==="vertical"?r.height:r.width;if(x.padding==="gap"&&(I=G*Y/2),x.padding==="no-gap"){var X=j_(t.barCategoryGap,G*Y),ae=G*Y/2;I=ae-X-(ae-X)/Y*X}}}a==="xAxis"?P=[r.left+(w.left||0)+(I||0),r.left+r.width-(w.right||0)-(I||0)]:a==="yAxis"?P=c==="horizontal"?[r.top+r.height-(w.bottom||0),r.top+(w.top||0)]:[r.top+(w.top||0)+(I||0),r.top+r.height-(w.bottom||0)-(I||0)]:P=x.range,C&&(P=[P[1],P[0]]);var ie=pZt(x,i,m),ne=ie.scale,te=ie.realScaleType;ne.domain(v).range(P),gZt(ne);var J=xZt(ne,DS(DS({},x),{},{realScaleType:te}));a==="xAxis"?(O=y==="top"&&!S||y==="bottom"&&S,R=r.left,D=h[E]-O*x.height):a==="yAxis"&&(O=y==="left"&&!S||y==="right"&&S,R=h[E]-O*x.width,D=r.top);var ce=DS(DS(DS({},x),J),{},{realScaleType:te,x:R,y:D,scale:ne,width:a==="xAxis"?r.width:x.width,height:a==="yAxis"?r.height:x.height});return ce.bandSize=wMe(ce,J),!x.hide&&a==="xAxis"?h[E]+=(O?-1:1)*ce.height:x.hide||(h[E]+=(O?-1:1)*ce.width),DS(DS({},f),{},ZRe({},g,ce))},{})},JZt=function(t,n){var r=t.x,a=t.y,i=n.x,l=n.y;return{x:Math.min(r,i),y:Math.min(a,l),width:Math.abs(i-r),height:Math.abs(l-a)}},nIn=function(t){var n=t.x1,r=t.y1,a=t.x2,i=t.y2;return JZt({x:n,y:r},{x:a,y:i})},eXt=function(){function s(t){eIn(this,s),this.scale=t}return tIn(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(n){var r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},a=r.bandAware,i=r.position;if(n!==void 0){if(i)switch(i){case"start":return this.scale(n);case"middle":{var l=this.bandwidth?this.bandwidth()/2:0;return this.scale(n)+l}case"end":{var o=this.bandwidth?this.bandwidth():0;return this.scale(n)+o}default:return this.scale(n)}if(a){var c=this.bandwidth?this.bandwidth()/2:0;return this.scale(n)+c}return this.scale(n)}}},{key:"isInRange",value:function(n){var r=this.range(),a=r[0],i=r[r.length-1];return a<=i?n>=a&&n<=i:n>=i&&n<=a}}],[{key:"create",value:function(n){return new s(n)}}])}();ZRe(eXt,"EPS",1e-4);var Vat=function(t){var n=Object.keys(t).reduce(function(r,a){return DS(DS({},r),{},ZRe({},a,eXt.create(t[a])))},{});return DS(DS({},n),{},{apply:function(a){var i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},l=i.bandAware,o=i.position;return jPn(a,function(c,d){return n[d].apply(c,{bandAware:l,position:o})})},isInRange:function(a){return KZt(a,function(i,l){return n[l].isInRange(i)})}})};function rIn(s){return(s%180+180)%180}var aIn=function(t){var n=t.width,r=t.height,a=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,i=rIn(a),l=i*Math.PI/180,o=Math.atan(r/n),c=l>o&&l-1?a[i?t[l]:l]:void 0}}var dIn=cIn,uIn=VZt;function hIn(s){var t=uIn(s),n=t%1;return t===t?n?t-n:t:0}var mIn=hIn,fIn=ZKt,pIn=p3,gIn=mIn,xIn=Math.max;function yIn(s,t,n){var r=s==null?0:s.length;if(!r)return-1;var a=n==null?0:gIn(n);return a<0&&(a=xIn(r+a,0)),fIn(s,pIn(t),a)}var vIn=yIn,bIn=dIn,_In=vIn,wIn=bIn(_In),jIn=wIn;const NIn=au(jIn);var kIn=xgn(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("")}),Hat=j.createContext(void 0),Gat=j.createContext(void 0),tXt=j.createContext(void 0),sXt=j.createContext({}),nXt=j.createContext(void 0),rXt=j.createContext(0),aXt=j.createContext(0),Akt=function(t){var n=t.state,r=n.xAxisMap,a=n.yAxisMap,i=n.offset,l=t.clipPathId,o=t.children,c=t.width,d=t.height,u=kIn(i);return Gt.createElement(Hat.Provider,{value:r},Gt.createElement(Gat.Provider,{value:a},Gt.createElement(sXt.Provider,{value:i},Gt.createElement(tXt.Provider,{value:u},Gt.createElement(nXt.Provider,{value:l},Gt.createElement(rXt.Provider,{value:d},Gt.createElement(aXt.Provider,{value:c},o)))))))},SIn=function(){return j.useContext(nXt)},iXt=function(t){var n=j.useContext(Hat);n==null&&uB();var r=n[t];return r==null&&uB(),r},CIn=function(){var t=j.useContext(Hat);return TP(t)},AIn=function(){var t=j.useContext(Gat),n=NIn(t,function(r){return KZt(r.domain,Number.isFinite)});return n||TP(t)},oXt=function(t){var n=j.useContext(Gat);n==null&&uB();var r=n[t];return r==null&&uB(),r},EIn=function(){var t=j.useContext(tXt);return t},TIn=function(){return j.useContext(sXt)},Wat=function(){return j.useContext(aXt)},Kat=function(){return j.useContext(rXt)};function aW(s){"@babel/helpers - typeof";return aW=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},aW(s)}function MIn(s,t){if(!(s instanceof t))throw new TypeError("Cannot call a class as a function")}function PIn(s,t){for(var n=0;ns.length)&&(t=s.length);for(var n=0,r=new Array(t);ns*a)return!1;var i=n();return s*(t-s*i/2-r)>=0&&s*(t+s*i/2-a)<=0}function mLn(s,t){return fXt(s,t+1)}function fLn(s,t,n,r,a){for(var i=(r||[]).slice(),l=t.start,o=t.end,c=0,d=1,u=l,h=function(){var g=r==null?void 0:r[c];if(g===void 0)return{v:fXt(r,d)};var x=c,y,v=function(){return y===void 0&&(y=n(g,x)),y},b=g.coordinate,w=c===0||qMe(s,b,v,u,o);w||(c=0,u=l,d+=1),w&&(u=b+s*(v()/2+a),c+=d)},m;d<=i.length;)if(m=h(),m)return m.v;return[]}function hne(s){"@babel/helpers - typeof";return hne=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},hne(s)}function Dkt(s,t){var n=Object.keys(s);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(s);t&&(r=r.filter(function(a){return Object.getOwnPropertyDescriptor(s,a).enumerable})),n.push.apply(n,r)}return n}function u1(s){for(var t=1;t0?f.coordinate-y*s:f.coordinate})}else i[m]=f=u1(u1({},f),{},{tickCoord:f.coordinate});var v=qMe(s,f.tickCoord,x,o,c);v&&(c=f.tickCoord-s*(x()/2+a),i[m]=u1(u1({},f),{},{isShow:!0}))},u=l-1;u>=0;u--)d(u);return i}function vLn(s,t,n,r,a,i){var l=(r||[]).slice(),o=l.length,c=t.start,d=t.end;if(i){var u=r[o-1],h=n(u,o-1),m=s*(u.coordinate+s*h/2-d);l[o-1]=u=u1(u1({},u),{},{tickCoord:m>0?u.coordinate-m*s:u.coordinate});var f=qMe(s,u.tickCoord,function(){return h},c,d);f&&(d=u.tickCoord-s*(h/2+a),l[o-1]=u1(u1({},u),{},{isShow:!0}))}for(var g=i?o-1:o,x=function(b){var w=l[b],S,C=function(){return S===void 0&&(S=n(w,b)),S};if(b===0){var E=s*(w.coordinate-s*C()/2-c);l[b]=w=u1(u1({},w),{},{tickCoord:E<0?w.coordinate-E*s:w.coordinate})}else l[b]=w=u1(u1({},w),{},{tickCoord:w.coordinate});var I=qMe(s,w.tickCoord,C,c,d);I&&(c=w.tickCoord+s*(C()/2+a),l[b]=u1(u1({},w),{},{isShow:!0}))},y=0;y=2?w_(a[1].coordinate-a[0].coordinate):1,v=hLn(i,y,f);return c==="equidistantPreserveStart"?fLn(y,v,x,a,l):(c==="preserveStart"||c==="preserveStartEnd"?m=vLn(y,v,x,a,l,c==="preserveStartEnd"):m=yLn(y,v,x,a,l),m.filter(function(b){return b.isShow}))}var bLn=["viewBox"],_Ln=["viewBox"],wLn=["ticks"];function lW(s){"@babel/helpers - typeof";return lW=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},lW(s)}function uq(){return uq=Object.assign?Object.assign.bind():function(s){for(var t=1;t=0)&&Object.prototype.propertyIsEnumerable.call(s,r)&&(n[r]=s[r])}return n}function jLn(s,t){if(s==null)return{};var n={};for(var r in s)if(Object.prototype.hasOwnProperty.call(s,r)){if(t.indexOf(r)>=0)continue;n[r]=s[r]}return n}function NLn(s,t){if(!(s instanceof t))throw new TypeError("Cannot call a class as a function")}function Okt(s,t){for(var n=0;n0?c(this.props):c(f)),l<=0||o<=0||!g||!g.length?null:Gt.createElement(Cu,{className:rd("recharts-cartesian-axis",d),ref:function(y){r.layerReference=y}},i&&this.renderAxisLine(),this.renderTicks(g,this.state.fontSize,this.state.letterSpacing),bv.renderCallByParent(this.props))}}],[{key:"renderTickItem",value:function(r,a,i){var l,o=rd(a.className,"recharts-cartesian-axis-tick-value");return Gt.isValidElement(r)?l=Gt.cloneElement(r,n0(n0({},a),{},{className:o})):ic(r)?l=r(n0(n0({},a),{},{className:o})):l=Gt.createElement(lB,uq({},a,{className:"recharts-cartesian-axis-tick-value"}),i),l}}])}(j.Component);Qat(FK,"displayName","CartesianAxis");Qat(FK,"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 MLn=["x1","y1","x2","y2","key"],PLn=["offset"];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 zkt(s,t){var n=Object.keys(s);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(s);t&&(r=r.filter(function(a){return Object.getOwnPropertyDescriptor(s,a).enumerable})),n.push.apply(n,r)}return n}function f1(s){for(var t=1;t=0)&&Object.prototype.propertyIsEnumerable.call(s,r)&&(n[r]=s[r])}return n}function DLn(s,t){if(s==null)return{};var n={};for(var r in s)if(Object.prototype.hasOwnProperty.call(s,r)){if(t.indexOf(r)>=0)continue;n[r]=s[r]}return n}var FLn=function(t){var n=t.fill;if(!n||n==="none")return null;var r=t.fillOpacity,a=t.x,i=t.y,l=t.width,o=t.height,c=t.ry;return Gt.createElement("rect",{x:a,y:i,ry:c,width:l,height:o,stroke:"none",fill:n,fillOpacity:r,className:"recharts-cartesian-grid-bg"})};function xXt(s,t){var n;if(Gt.isValidElement(s))n=Gt.cloneElement(s,t);else if(ic(s))n=s(t);else{var r=t.x1,a=t.y1,i=t.x2,l=t.y2,o=t.key,c=Bkt(t,MLn),d=cl(c,!1);d.offset;var u=Bkt(d,PLn);n=Gt.createElement("line",w8({},u,{x1:r,y1:a,x2:i,y2:l,fill:"none",key:o}))}return n}function OLn(s){var t=s.x,n=s.width,r=s.horizontal,a=r===void 0?!0:r,i=s.horizontalPoints;if(!a||!i||!i.length)return null;var l=i.map(function(o,c){var d=f1(f1({},s),{},{x1:t,y1:o,x2:t+n,y2:o,key:"line-".concat(c),index:c});return xXt(a,d)});return Gt.createElement("g",{className:"recharts-cartesian-grid-horizontal"},l)}function zLn(s){var t=s.y,n=s.height,r=s.vertical,a=r===void 0?!0:r,i=s.verticalPoints;if(!a||!i||!i.length)return null;var l=i.map(function(o,c){var d=f1(f1({},s),{},{x1:o,y1:t,x2:o,y2:t+n,key:"line-".concat(c),index:c});return xXt(a,d)});return Gt.createElement("g",{className:"recharts-cartesian-grid-vertical"},l)}function BLn(s){var t=s.horizontalFill,n=s.fillOpacity,r=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 u=o.map(function(m){return Math.round(m+a-a)}).sort(function(m,f){return m-f});a!==u[0]&&u.unshift(0);var h=u.map(function(m,f){var g=!u[f+1],x=g?a+l-m:u[f+1]-m;if(x<=0)return null;var y=f%t.length;return Gt.createElement("rect",{key:"react-".concat(f),y:m,x:r,height:x,width:i,stroke:"none",fill:t[y],fillOpacity:n,className:"recharts-cartesian-grid-bg"})});return Gt.createElement("g",{className:"recharts-cartesian-gridstripes-horizontal"},h)}function $Ln(s){var t=s.vertical,n=t===void 0?!0:t,r=s.verticalFill,a=s.fillOpacity,i=s.x,l=s.y,o=s.width,c=s.height,d=s.verticalPoints;if(!n||!r||!r.length)return null;var u=d.map(function(m){return Math.round(m+i-i)}).sort(function(m,f){return m-f});i!==u[0]&&u.unshift(0);var h=u.map(function(m,f){var g=!u[f+1],x=g?i+o-m:u[f+1]-m;if(x<=0)return null;var y=f%r.length;return Gt.createElement("rect",{key:"react-".concat(f),x:m,y:l,width:x,height:c,stroke:"none",fill:r[y],fillOpacity:a,className:"recharts-cartesian-grid-bg"})});return Gt.createElement("g",{className:"recharts-cartesian-gridstripes-vertical"},h)}var ULn=function(t,n){var r=t.xAxis,a=t.width,i=t.height,l=t.offset;return fZt(Xat(f1(f1(f1({},FK.defaultProps),r),{},{ticks:SE(r,!0),viewBox:{x:0,y:0,width:a,height:i}})),l.left,l.left+l.width,n)},qLn=function(t,n){var r=t.yAxis,a=t.width,i=t.height,l=t.offset;return fZt(Xat(f1(f1(f1({},FK.defaultProps),r),{},{ticks:SE(r,!0),viewBox:{x:0,y:0,width:a,height:i}})),l.top,l.top+l.height,n)},$$={horizontal:!0,vertical:!0,stroke:"#ccc",fill:"none",verticalFill:[],horizontalFill:[]};function vT(s){var t,n,r,a,i,l,o=Wat(),c=Kat(),d=TIn(),u=f1(f1({},s),{},{stroke:(t=s.stroke)!==null&&t!==void 0?t:$$.stroke,fill:(n=s.fill)!==null&&n!==void 0?n:$$.fill,horizontal:(r=s.horizontal)!==null&&r!==void 0?r:$$.horizontal,horizontalFill:(a=s.horizontalFill)!==null&&a!==void 0?a:$$.horizontalFill,vertical:(i=s.vertical)!==null&&i!==void 0?i:$$.vertical,verticalFill:(l=s.verticalFill)!==null&&l!==void 0?l:$$.verticalFill,x:yi(s.x)?s.x:d.left,y:yi(s.y)?s.y:d.top,width:yi(s.width)?s.width:d.width,height:yi(s.height)?s.height:d.height}),h=u.x,m=u.y,f=u.width,g=u.height,x=u.syncWithTicks,y=u.horizontalValues,v=u.verticalValues,b=CIn(),w=AIn();if(!yi(f)||f<=0||!yi(g)||g<=0||!yi(h)||h!==+h||!yi(m)||m!==+m)return null;var S=u.verticalCoordinatesGenerator||ULn,C=u.horizontalCoordinatesGenerator||qLn,E=u.horizontalPoints,I=u.verticalPoints;if((!E||!E.length)&&ic(C)){var P=y&&y.length,R=C({yAxis:w?f1(f1({},w),{},{ticks:P?y:w.ticks}):void 0,width:o,height:c,offset:d},P?!0:x);cC(Array.isArray(R),"horizontalCoordinatesGenerator should return Array but instead it returned [".concat(hB(R),"]")),Array.isArray(R)&&(E=R)}if((!I||!I.length)&&ic(S)){var D=v&&v.length,O=S({xAxis:b?f1(f1({},b),{},{ticks:D?v:b.ticks}):void 0,width:o,height:c,offset:d},D?!0:x);cC(Array.isArray(O),"verticalCoordinatesGenerator should return Array but instead it returned [".concat(hB(O),"]")),Array.isArray(O)&&(I=O)}return Gt.createElement("g",{className:"recharts-cartesian-grid"},Gt.createElement(FLn,{fill:u.fill,fillOpacity:u.fillOpacity,x:u.x,y:u.y,width:u.width,height:u.height,ry:u.ry}),Gt.createElement(OLn,w8({},u,{offset:d,horizontalPoints:E,xAxis:b,yAxis:w})),Gt.createElement(zLn,w8({},u,{offset:d,verticalPoints:I,xAxis:b,yAxis:w})),Gt.createElement(BLn,w8({},u,{horizontalPoints:E})),Gt.createElement($Ln,w8({},u,{verticalPoints:I})))}vT.displayName="CartesianGrid";var VLn=["type","layout","connectNulls","ref"],HLn=["key"];function cW(s){"@babel/helpers - typeof";return cW=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},cW(s)}function $kt(s,t){if(s==null)return{};var n=GLn(s,t),r,a;if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(s);for(a=0;a=0)&&Object.prototype.propertyIsEnumerable.call(s,r)&&(n[r]=s[r])}return n}function GLn(s,t){if(s==null)return{};var n={};for(var r in s)if(Object.prototype.hasOwnProperty.call(s,r)){if(t.indexOf(r)>=0)continue;n[r]=s[r]}return n}function Xee(){return Xee=Object.assign?Object.assign.bind():function(s){for(var t=1;ts.length)&&(t=s.length);for(var n=0,r=new Array(t);nh){f=[].concat(U$(c.slice(0,g)),[h-x]);break}var y=f.length%2===0?[0,m]:[m];return[].concat(U$(t.repeat(c,u)),U$(f),y).map(function(v){return"".concat(v,"px")}).join(", ")}),FS(n,"id",e9("recharts-line-")),FS(n,"pathRef",function(l){n.mainCurve=l}),FS(n,"handleAnimationEnd",function(){n.setState({isAnimationFinished:!0}),n.props.onAnimationEnd&&n.props.onAnimationEnd()}),FS(n,"handleAnimationStart",function(){n.setState({isAnimationFinished:!1}),n.props.onAnimationStart&&n.props.onAnimationStart()}),n}return s6n(t,s),QLn(t,[{key:"componentDidMount",value:function(){if(this.props.isAnimationActive){var r=this.getTotalLength();this.setState({totalLength:r})}}},{key:"componentDidUpdate",value:function(){if(this.props.isAnimationActive){var r=this.getTotalLength();r!==this.state.totalLength&&this.setState({totalLength:r})}}},{key:"getTotalLength",value:function(){var r=this.mainCurve;try{return r&&r.getTotalLength&&r.getTotalLength()||0}catch{return 0}}},{key:"renderErrorBar",value:function(r,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,u=i.children,h=k2(u,Pie);if(!h)return null;var m=function(x,y){return{x:x.x,y:x.y,value:x.value,errorVal:oy(x.payload,y)}},f={clipPath:r?"url(#clipPath-".concat(a,")"):null};return Gt.createElement(Cu,f,h.map(function(g){return Gt.cloneElement(g,{key:"bar-".concat(g.props.dataKey),data:l,xAxis:o,yAxis:c,layout:d,dataPointFormatter:m})}))}},{key:"renderDots",value:function(r,a,i){var l=this.props.isAnimationActive;if(l&&!this.state.isAnimationFinished)return null;var o=this.props,c=o.dot,d=o.points,u=o.dataKey,h=cl(this.props,!1),m=cl(c,!0),f=d.map(function(x,y){var v=Ej(Ej(Ej({key:"dot-".concat(y),r:3},h),m),{},{index:y,cx:x.x,cy:x.y,value:x.value,dataKey:u,payload:x.payload,points:d});return t.renderDotItem(c,v)}),g={clipPath:r?"url(#clipPath-".concat(a?"":"dots-").concat(i,")"):null};return Gt.createElement(Cu,Xee({className:"recharts-line-dots",key:"dots"},g),f)}},{key:"renderCurveStatically",value:function(r,a,i,l){var o=this.props,c=o.type,d=o.layout,u=o.connectNulls;o.ref;var h=$kt(o,VLn),m=Ej(Ej(Ej({},cl(h,!0)),{},{fill:"none",className:"recharts-line-curve",clipPath:a?"url(#clipPath-".concat(i,")"):null,points:r},l),{},{type:c,layout:d,connectNulls:u});return Gt.createElement(N7,Xee({},m,{pathRef:this.pathRef}))}},{key:"renderCurveWithAnimation",value:function(r,a){var i=this,l=this.props,o=l.points,c=l.strokeDasharray,d=l.isAnimationActive,u=l.animationBegin,h=l.animationDuration,m=l.animationEasing,f=l.animationId,g=l.animateNewValues,x=l.width,y=l.height,v=this.state,b=v.prevPoints,w=v.totalLength;return Gt.createElement(vC,{begin:u,duration:h,isActive:d,easing:m,from:{t:0},to:{t:1},key:"line-".concat(f),onAnimationEnd:this.handleAnimationEnd,onAnimationStart:this.handleAnimationStart},function(S){var C=S.t;if(b){var E=b.length/o.length,I=o.map(function(U,W){var V=Math.floor(W*E);if(b[V]){var G=b[V],Y=w0(G.x,U.x),X=w0(G.y,U.y);return Ej(Ej({},U),{},{x:Y(C),y:X(C)})}if(g){var ae=w0(x*2,U.x),ie=w0(y/2,U.y);return Ej(Ej({},U),{},{x:ae(C),y:ie(C)})}return Ej(Ej({},U),{},{x:U.x,y:U.y})});return i.renderCurveStatically(I,r,a)}var P=w0(0,w),R=P(C),D;if(c){var O="".concat(c).split(/[,\s]+/gim).map(function(U){return parseFloat(U)});D=i.getStrokeDasharray(R,w,O)}else D=i.generateSimpleStrokeDasharray(w,R);return i.renderCurveStatically(o,r,a,{strokeDasharray:D})})}},{key:"renderCurve",value:function(r,a){var i=this.props,l=i.points,o=i.isAnimationActive,c=this.state,d=c.prevPoints,u=c.totalLength;return o&&l&&l.length&&(!d&&u>0||!cB(d,l))?this.renderCurveWithAnimation(r,a):this.renderCurveStatically(l,r,a)}},{key:"render",value:function(){var r,a=this.props,i=a.hide,l=a.dot,o=a.points,c=a.className,d=a.xAxis,u=a.yAxis,h=a.top,m=a.left,f=a.width,g=a.height,x=a.isAnimationActive,y=a.id;if(i||!o||!o.length)return null;var v=this.state.isAnimationFinished,b=o.length===1,w=rd("recharts-line",c),S=d&&d.allowDataOverflow,C=u&&u.allowDataOverflow,E=S||C,I=Wc(y)?this.id:y,P=(r=cl(l,!1))!==null&&r!==void 0?r:{r:3,strokeWidth:2},R=P.r,D=R===void 0?3:R,O=P.strokeWidth,U=O===void 0?2:O,W=oKt(l)?l:{},V=W.clipDot,G=V===void 0?!0:V,Y=D*2+U;return Gt.createElement(Cu,{className:w},S||C?Gt.createElement("defs",null,Gt.createElement("clipPath",{id:"clipPath-".concat(I)},Gt.createElement("rect",{x:S?m:m-f/2,y:C?h:h-g/2,width:S?f:f*2,height:C?g:g*2})),!G&&Gt.createElement("clipPath",{id:"clipPath-dots-".concat(I)},Gt.createElement("rect",{x:m-Y/2,y:h-Y/2,width:f+Y,height:g+Y}))):null,!b&&this.renderCurve(E,I),this.renderErrorBar(E,I),(b||l)&&this.renderDots(E,G,I),(!x||v)&&q4.renderCallByParent(this.props,o))}}],[{key:"getDerivedStateFromProps",value:function(r,a){return r.animationId!==a.prevAnimationId?{prevAnimationId:r.animationId,curPoints:r.points,prevPoints:a.curPoints}:r.points!==a.curPoints?{curPoints:r.points}:null}},{key:"repeat",value:function(r,a){for(var i=r.length%2!==0?[].concat(U$(r),[0]):r,l=[],o=0;o=0)&&Object.prototype.propertyIsEnumerable.call(s,r)&&(n[r]=s[r])}return n}function i6n(s,t){if(s==null)return{};var n={};for(var r in s)if(Object.prototype.hasOwnProperty.call(s,r)){if(t.indexOf(r)>=0)continue;n[r]=s[r]}return n}function j8(){return j8=Object.assign?Object.assign.bind():function(s){for(var t=1;t0||!cB(u,l)||!cB(h,o))?this.renderAreaWithAnimation(r,a):this.renderAreaStatically(l,o,r,a)}},{key:"render",value:function(){var r,a=this.props,i=a.hide,l=a.dot,o=a.points,c=a.className,d=a.top,u=a.left,h=a.xAxis,m=a.yAxis,f=a.width,g=a.height,x=a.isAnimationActive,y=a.id;if(i||!o||!o.length)return null;var v=this.state.isAnimationFinished,b=o.length===1,w=rd("recharts-area",c),S=h&&h.allowDataOverflow,C=m&&m.allowDataOverflow,E=S||C,I=Wc(y)?this.id:y,P=(r=cl(l,!1))!==null&&r!==void 0?r:{r:3,strokeWidth:2},R=P.r,D=R===void 0?3:R,O=P.strokeWidth,U=O===void 0?2:O,W=oKt(l)?l:{},V=W.clipDot,G=V===void 0?!0:V,Y=D*2+U;return Gt.createElement(Cu,{className:w},S||C?Gt.createElement("defs",null,Gt.createElement("clipPath",{id:"clipPath-".concat(I)},Gt.createElement("rect",{x:S?u:u-f/2,y:C?d:d-g/2,width:S?f:f*2,height:C?g:g*2})),!G&&Gt.createElement("clipPath",{id:"clipPath-dots-".concat(I)},Gt.createElement("rect",{x:u-Y/2,y:d-Y/2,width:f+Y,height:g+Y}))):null,b?null:this.renderArea(E,I),(l||b)&&this.renderDots(E,G,I),(!x||v)&&q4.renderCallByParent(this.props,o))}}],[{key:"getDerivedStateFromProps",value:function(r,a){return r.animationId!==a.prevAnimationId?{prevAnimationId:r.animationId,curPoints:r.points,curBaseLine:r.baseLine,prevPoints:a.curPoints,prevBaseLine:a.curBaseLine}:r.points!==a.curPoints||r.baseLine!==a.curBaseLine?{curPoints:r.points,curBaseLine:r.baseLine}:null}}])}(j.PureComponent);bXt=zw;b4(zw,"displayName","Area");b4(zw,"defaultProps",{stroke:"#3182bd",fill:"#3182bd",fillOpacity:.6,xAxisId:0,yAxisId:0,legendType:"line",connectNulls:!1,points:[],dot:!1,activeDot:!0,hide:!1,isAnimationActive:!S6.isSsr,animationBegin:0,animationDuration:1500,animationEasing:"ease"});b4(zw,"getBaseValue",function(s,t,n,r){var a=s.layout,i=s.baseValue,l=t.props.baseValue,o=l??i;if(yi(o)&&typeof o=="number")return o;var c=a==="horizontal"?r:n,d=c.scale.domain();if(c.type==="number"){var u=Math.max(d[0],d[1]),h=Math.min(d[0],d[1]);return o==="dataMin"?h:o==="dataMax"||u<0?u:Math.max(Math.min(d[0],d[1]),0)}return o==="dataMin"?d[0]:o==="dataMax"?d[1]:d[0]});b4(zw,"getComposedData",function(s){var t=s.props,n=s.item,r=s.xAxis,a=s.yAxis,i=s.xAxisTicks,l=s.yAxisTicks,o=s.bandSize,c=s.dataKey,d=s.stackedData,u=s.dataStartIndex,h=s.displayedData,m=s.offset,f=t.layout,g=d&&d.length,x=bXt.getBaseValue(t,n,r,a),y=f==="horizontal",v=!1,b=h.map(function(S,C){var E;g?E=d[u+C]:(E=oy(S,c),Array.isArray(E)?v=!0:E=[x,E]);var I=E[1]==null||g&&oy(S,c)==null;return y?{x:_Me({axis:r,ticks:i,bandSize:o,entry:S,index:C}),y:I?null:a.scale(E[1]),value:E,payload:S}:{x:I?null:r.scale(E[1]),y:_Me({axis:a,ticks:l,bandSize:o,entry:S,index:C}),value:E,payload:S}}),w;return g||v?w=b.map(function(S){var C=Array.isArray(S.value)?S.value[0]:null;return y?{x:S.x,y:C!=null&&S.y!=null?a.scale(C):null}:{x:C!=null?r.scale(C):null,y:S.y}}):w=y?a.scale(x):r.scale(x),QM({points:b,baseLine:w,layout:f,isRange:v},m)});b4(zw,"renderDotItem",function(s,t){var n;if(Gt.isValidElement(s))n=Gt.cloneElement(s,t);else if(ic(s))n=s(t);else{var r=rd("recharts-area-dot",typeof s!="boolean"?s.className:""),a=t.key,i=_Xt(t,a6n);n=Gt.createElement(Iie,j8({},i,{key:a,className:r}))}return n});function uW(s){"@babel/helpers - typeof";return uW=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},uW(s)}function f6n(s,t){if(!(s instanceof t))throw new TypeError("Cannot call a class as a function")}function p6n(s,t){for(var n=0;ns.length)&&(t=s.length);for(var n=0,r=new Array(t);n=0)&&Object.prototype.propertyIsEnumerable.call(s,r)&&(n[r]=s[r])}return n}function tRn(s,t){if(s==null)return{};var n={};for(var r in s)if(Object.prototype.hasOwnProperty.call(s,r)){if(t.indexOf(r)>=0)continue;n[r]=s[r]}return n}function sRn(s,t){if(!(s instanceof t))throw new TypeError("Cannot call a class as a function")}function nRn(s,t){for(var n=0;ns.length)&&(t=s.length);for(var n=0,r=new Array(t);n0?l:t&&t.length&&yi(a)&&yi(i)?t.slice(a,i+1):[]};function FXt(s){return s==="number"?[0,"auto"]:void 0}var jYe=function(t,n,r,a){var i=t.graphicalItems,l=t.tooltipAxis,o=tDe(n,t);return r<0||!i||!i.length||r>=o.length?null:i.reduce(function(c,d){var u,h=(u=d.props.data)!==null&&u!==void 0?u:n;h&&t.dataStartIndex+t.dataEndIndex!==0&&t.dataEndIndex-t.dataStartIndex>=r&&(h=h.slice(t.dataStartIndex,t.dataEndIndex+1));var m;if(l.dataKey&&!l.allowDuplicatedCategory){var f=h===void 0?o:h;m=GTe(f,l.dataKey,a)}else m=h&&h[r]||o[r];return m?[].concat(fW(c),[vZt(d,m)]):c},[])},Xkt=function(t,n,r,a){var i=a||{x:t.chartX,y:t.chartY},l=pRn(i,r),o=t.orderedTooltipTicks,c=t.tooltipAxis,d=t.tooltipTicks,u=j4n(l,o,d,c);if(u>=0&&d){var h=d[u]&&d[u].value,m=jYe(t,n,u,h),f=gRn(r,o,u,i);return{activeTooltipIndex:u,activeLabel:h,activePayload:m,activeCoordinate:f}}return null},xRn=function(t,n){var r=n.axes,a=n.graphicalItems,i=n.axisType,l=n.axisIdKey,o=n.stackGroups,c=n.dataStartIndex,d=n.dataEndIndex,u=t.layout,h=t.children,m=t.stackOffset,f=mZt(u,i);return r.reduce(function(g,x){var y,v=x.type.defaultProps!==void 0?ba(ba({},x.type.defaultProps),x.props):x.props,b=v.type,w=v.dataKey,S=v.allowDataOverflow,C=v.allowDuplicatedCategory,E=v.scale,I=v.ticks,P=v.includeHidden,R=v[l];if(g[R])return g;var D=tDe(t.data,{graphicalItems:a.filter(function(J){var ce,_e=l in J.props?J.props[l]:(ce=J.type.defaultProps)===null||ce===void 0?void 0:ce[l];return _e===R}),dataStartIndex:c,dataEndIndex:d}),O=D.length,U,W,V;q6n(v.domain,S,b)&&(U=DKe(v.domain,null,S),f&&(b==="number"||E!=="auto")&&(V=Wee(D,w,"category")));var G=FXt(b);if(!U||U.length===0){var Y,X=(Y=v.domain)!==null&&Y!==void 0?Y:G;if(w){if(U=Wee(D,w,b),b==="category"&&f){var ae=mxn(U);C&&ae?(W=U,U=RMe(0,O)):C||(U=xNt(X,U,x).reduce(function(J,ce){return J.indexOf(ce)>=0?J:[].concat(fW(J),[ce])},[]))}else if(b==="category")C?U=U.filter(function(J){return J!==""&&!Wc(J)}):U=xNt(X,U,x).reduce(function(J,ce){return J.indexOf(ce)>=0||ce===""||Wc(ce)?J:[].concat(fW(J),[ce])},[]);else if(b==="number"){var ie=A4n(D,a.filter(function(J){var ce,_e,he=l in J.props?J.props[l]:(ce=J.type.defaultProps)===null||ce===void 0?void 0:ce[l],ue="hide"in J.props?J.props.hide:(_e=J.type.defaultProps)===null||_e===void 0?void 0:_e.hide;return he===R&&(P||!ue)}),w,i,u);ie&&(U=ie)}f&&(b==="number"||E!=="auto")&&(V=Wee(D,w,"category"))}else f?U=RMe(0,O):o&&o[R]&&o[R].hasStack&&b==="number"?U=m==="expand"?[0,1]:yZt(o[R].stackGroups,c,d):U=hZt(D,a.filter(function(J){var ce=l in J.props?J.props[l]:J.type.defaultProps[l],_e="hide"in J.props?J.props.hide:J.type.defaultProps.hide;return ce===R&&(P||!_e)}),b,u,!0);if(b==="number")U=bYe(h,U,R,i,I),X&&(U=DKe(X,U,S));else if(b==="category"&&X){var ne=X,te=U.every(function(J){return ne.indexOf(J)>=0});te&&(U=ne)}}return ba(ba({},g),{},ac({},R,ba(ba({},v),{},{axisType:i,domain:U,categoricalDomain:V,duplicateDomain:W,originalDomain:(y=v.domain)!==null&&y!==void 0?y:G,isCategorical:f,layout:u})))},{})},yRn=function(t,n){var r=n.graphicalItems,a=n.Axis,i=n.axisType,l=n.axisIdKey,o=n.stackGroups,c=n.dataStartIndex,d=n.dataEndIndex,u=t.layout,h=t.children,m=tDe(t.data,{graphicalItems:r,dataStartIndex:c,dataEndIndex:d}),f=m.length,g=mZt(u,i),x=-1;return r.reduce(function(y,v){var b=v.type.defaultProps!==void 0?ba(ba({},v.type.defaultProps),v.props):v.props,w=b[l],S=FXt("number");if(!y[w]){x++;var C;return g?C=RMe(0,f):o&&o[w]&&o[w].hasStack?(C=yZt(o[w].stackGroups,c,d),C=bYe(h,C,w,i)):(C=DKe(S,hZt(m,r.filter(function(E){var I,P,R=l in E.props?E.props[l]:(I=E.type.defaultProps)===null||I===void 0?void 0:I[l],D="hide"in E.props?E.props.hide:(P=E.type.defaultProps)===null||P===void 0?void 0:P.hide;return R===w&&!D}),"number",u),a.defaultProps.allowDataOverflow),C=bYe(h,C,w,i)),ba(ba({},y),{},ac({},w,ba(ba({axisType:i},a.defaultProps),{},{hide:!0,orientation:N2(mRn,"".concat(i,".").concat(x%2),null),domain:C,originalDomain:S,isCategorical:g,layout:u})))}return y},{})},vRn=function(t,n){var r=n.axisType,a=r===void 0?"xAxis":r,i=n.AxisComp,l=n.graphicalItems,o=n.stackGroups,c=n.dataStartIndex,d=n.dataEndIndex,u=t.children,h="".concat(a,"Id"),m=k2(u,i),f={};return m&&m.length?f=xRn(t,{axes:m,graphicalItems:l,axisType:a,axisIdKey:h,stackGroups:o,dataStartIndex:c,dataEndIndex:d}):l&&l.length&&(f=yRn(t,{Axis:i,graphicalItems:l,axisType:a,axisIdKey:h,stackGroups:o,dataStartIndex:c,dataEndIndex:d})),f},bRn=function(t){var n=TP(t),r=SE(n,!1,!0);return{tooltipTicks:r,orderedTooltipTicks:pat(r,function(a){return a.coordinate}),tooltipAxis:n,tooltipAxisBandSize:wMe(n,r)}},Qkt=function(t){var n=t.children,r=t.defaultShowTooltip,a=Gj(n,nW),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:!!r}},_Rn=function(t){return!t||!t.length?!1:t.some(function(n){var r=WE(n&&n.type);return r&&r.indexOf("Bar")>=0})},Jkt=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"}},wRn=function(t,n){var r=t.props,a=t.graphicalItems,i=t.xAxisMap,l=i===void 0?{}:i,o=t.yAxisMap,c=o===void 0?{}:o,d=r.width,u=r.height,h=r.children,m=r.margin||{},f=Gj(h,nW),g=Gj(h,MV),x=Object.keys(c).reduce(function(C,E){var I=c[E],P=I.orientation;return!I.mirror&&!I.hide?ba(ba({},C),{},ac({},P,C[P]+I.width)):C},{left:m.left||0,right:m.right||0}),y=Object.keys(l).reduce(function(C,E){var I=l[E],P=I.orientation;return!I.mirror&&!I.hide?ba(ba({},C),{},ac({},P,N2(C,"".concat(P))+I.height)):C},{top:m.top||0,bottom:m.bottom||0}),v=ba(ba({},y),x),b=v.bottom;f&&(v.bottom+=f.props.height||nW.defaultProps.height),g&&n&&(v=S4n(v,a,r,n));var w=d-v.left-v.right,S=u-v.top-v.bottom;return ba(ba({brushBottom:b},v),{},{width:Math.max(w,0),height:Math.max(S,0)})},jRn=function(t,n){if(n==="xAxis")return t[n].width;if(n==="yAxis")return t[n].height},sDe=function(t){var n=t.chartName,r=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,u=t.formatAxisMap,h=t.defaultProps,m=function(v,b){var w=b.graphicalItems,S=b.stackGroups,C=b.offset,E=b.updateId,I=b.dataStartIndex,P=b.dataEndIndex,R=v.barSize,D=v.layout,O=v.barGap,U=v.barCategoryGap,W=v.maxBarSize,V=Jkt(D),G=V.numericAxisName,Y=V.cateAxisName,X=_Rn(w),ae=[];return w.forEach(function(ie,ne){var te=tDe(v.data,{graphicalItems:[ie],dataStartIndex:I,dataEndIndex:P}),J=ie.type.defaultProps!==void 0?ba(ba({},ie.type.defaultProps),ie.props):ie.props,ce=J.dataKey,_e=J.maxBarSize,he=J["".concat(G,"Id")],ue=J["".concat(Y,"Id")],ve={},Ee=c.reduce(function(Xe,it){var at=b["".concat(it.axisType,"Map")],Ke=J["".concat(it.axisType,"Id")];at&&at[Ke]||it.axisType==="zAxis"||uB();var nt=at[Ke];return ba(ba({},Xe),{},ac(ac({},it.axisType,nt),"".concat(it.axisType,"Ticks"),SE(nt)))},ve),Se=Ee[Y],Le=Ee["".concat(Y,"Ticks")],Fe=S&&S[he]&&S[he].hasStack&&F4n(ie,S[he].stackGroups),ke=WE(ie.type).indexOf("Bar")>=0,Ve=wMe(Se,Le),je=[],Ae=X&&N4n({barSize:R,stackGroups:S,totalSize:jRn(Ee,Y)});if(ke){var Ce,qe,ze=Wc(_e)?W:_e,$e=(Ce=(qe=wMe(Se,Le,!0))!==null&&qe!==void 0?qe:ze)!==null&&Ce!==void 0?Ce:0;je=k4n({barGap:O,barCategoryGap:U,bandSize:$e!==Ve?$e:Ve,sizeList:Ae[ue],maxBarSize:ze}),$e!==Ve&&(je=je.map(function(Xe){return ba(ba({},Xe),{},{position:ba(ba({},Xe.position),{},{offset:Xe.position.offset-$e/2})})}))}var ct=ie&&ie.type&&ie.type.getComposedData;ct&&ae.push({props:ba(ba({},ct(ba(ba({},Ee),{},{displayedData:te,props:v,dataKey:ce,item:ie,bandSize:Ve,barPosition:je,offset:C,stackedData:Fe,layout:D,dataStartIndex:I,dataEndIndex:P}))),{},ac(ac(ac({key:ie.key||"item-".concat(ne)},G,Ee[G]),Y,Ee[Y]),"animationId",E)),childIndex:kxn(ie,v.children),item:ie})}),ae},f=function(v,b){var w=v.props,S=v.dataStartIndex,C=v.dataEndIndex,E=v.updateId;if(!ujt({props:w}))return null;var I=w.children,P=w.layout,R=w.stackOffset,D=w.data,O=w.reverseStackOrder,U=Jkt(P),W=U.numericAxisName,V=U.cateAxisName,G=k2(I,r),Y=R4n(D,G,"".concat(W,"Id"),"".concat(V,"Id"),R,O),X=c.reduce(function(J,ce){var _e="".concat(ce.axisType,"Map");return ba(ba({},J),{},ac({},_e,vRn(w,ba(ba({},ce),{},{graphicalItems:G,stackGroups:ce.axisType===W&&Y,dataStartIndex:S,dataEndIndex:C}))))},{}),ae=wRn(ba(ba({},X),{},{props:w,graphicalItems:G}),b==null?void 0:b.legendBBox);Object.keys(X).forEach(function(J){X[J]=u(w,X[J],ae,J.replace("Map",""),n)});var ie=X["".concat(V,"Map")],ne=bRn(ie),te=m(w,ba(ba({},X),{},{dataStartIndex:S,dataEndIndex:C,updateId:E,graphicalItems:G,stackGroups:Y,offset:ae}));return ba(ba({formattedGraphicalItems:te,graphicalItems:G,offset:ae,stackGroups:Y},ne),X)},g=function(y){function v(b){var w,S,C;return sRn(this,v),C=aRn(this,v,[b]),ac(C,"eventEmitterSymbol",Symbol("rechartsEventEmitter")),ac(C,"accessibilityManager",new U6n),ac(C,"handleLegendBBoxUpdate",function(E){if(E){var I=C.state,P=I.dataStartIndex,R=I.dataEndIndex,D=I.updateId;C.setState(ba({legendBBox:E},f({props:C.props,dataStartIndex:P,dataEndIndex:R,updateId:D},ba(ba({},C.state),{},{legendBBox:E}))))}}),ac(C,"handleReceiveSyncEvent",function(E,I,P){if(C.props.syncId===E){if(P===C.eventEmitterSymbol&&typeof C.props.syncMethod!="function")return;C.applySyncEvent(I)}}),ac(C,"handleBrushChange",function(E){var I=E.startIndex,P=E.endIndex;if(I!==C.state.dataStartIndex||P!==C.state.dataEndIndex){var R=C.state.updateId;C.setState(function(){return ba({dataStartIndex:I,dataEndIndex:P},f({props:C.props,dataStartIndex:I,dataEndIndex:P,updateId:R},C.state))}),C.triggerSyncEvent({dataStartIndex:I,dataEndIndex:P})}}),ac(C,"handleMouseEnter",function(E){var I=C.getMouseInfo(E);if(I){var P=ba(ba({},I),{},{isTooltipActive:!0});C.setState(P),C.triggerSyncEvent(P);var R=C.props.onMouseEnter;ic(R)&&R(P,E)}}),ac(C,"triggeredAfterMouseMove",function(E){var I=C.getMouseInfo(E),P=I?ba(ba({},I),{},{isTooltipActive:!0}):{isTooltipActive:!1};C.setState(P),C.triggerSyncEvent(P);var R=C.props.onMouseMove;ic(R)&&R(P,E)}),ac(C,"handleItemMouseEnter",function(E){C.setState(function(){return{isTooltipActive:!0,activeItem:E,activePayload:E.tooltipPayload,activeCoordinate:E.tooltipPosition||{x:E.cx,y:E.cy}}})}),ac(C,"handleItemMouseLeave",function(){C.setState(function(){return{isTooltipActive:!1}})}),ac(C,"handleMouseMove",function(E){E.persist(),C.throttleTriggeredAfterMouseMove(E)}),ac(C,"handleMouseLeave",function(E){C.throttleTriggeredAfterMouseMove.cancel();var I={isTooltipActive:!1};C.setState(I),C.triggerSyncEvent(I);var P=C.props.onMouseLeave;ic(P)&&P(I,E)}),ac(C,"handleOuterEvent",function(E){var I=Nxn(E),P=N2(C.props,"".concat(I));if(I&&ic(P)){var R,D;/.*touch.*/i.test(I)?D=C.getMouseInfo(E.changedTouches[0]):D=C.getMouseInfo(E),P((R=D)!==null&&R!==void 0?R:{},E)}}),ac(C,"handleClick",function(E){var I=C.getMouseInfo(E);if(I){var P=ba(ba({},I),{},{isTooltipActive:!0});C.setState(P),C.triggerSyncEvent(P);var R=C.props.onClick;ic(R)&&R(P,E)}}),ac(C,"handleMouseDown",function(E){var I=C.props.onMouseDown;if(ic(I)){var P=C.getMouseInfo(E);I(P,E)}}),ac(C,"handleMouseUp",function(E){var I=C.props.onMouseUp;if(ic(I)){var P=C.getMouseInfo(E);I(P,E)}}),ac(C,"handleTouchMove",function(E){E.changedTouches!=null&&E.changedTouches.length>0&&C.throttleTriggeredAfterMouseMove(E.changedTouches[0])}),ac(C,"handleTouchStart",function(E){E.changedTouches!=null&&E.changedTouches.length>0&&C.handleMouseDown(E.changedTouches[0])}),ac(C,"handleTouchEnd",function(E){E.changedTouches!=null&&E.changedTouches.length>0&&C.handleMouseUp(E.changedTouches[0])}),ac(C,"handleDoubleClick",function(E){var I=C.props.onDoubleClick;if(ic(I)){var P=C.getMouseInfo(E);I(P,E)}}),ac(C,"handleContextMenu",function(E){var I=C.props.onContextMenu;if(ic(I)){var P=C.getMouseInfo(E);I(P,E)}}),ac(C,"triggerSyncEvent",function(E){C.props.syncId!==void 0&&I9e.emit(L9e,C.props.syncId,E,C.eventEmitterSymbol)}),ac(C,"applySyncEvent",function(E){var I=C.props,P=I.layout,R=I.syncMethod,D=C.state.updateId,O=E.dataStartIndex,U=E.dataEndIndex;if(E.dataStartIndex!==void 0||E.dataEndIndex!==void 0)C.setState(ba({dataStartIndex:O,dataEndIndex:U},f({props:C.props,dataStartIndex:O,dataEndIndex:U,updateId:D},C.state)));else if(E.activeTooltipIndex!==void 0){var W=E.chartX,V=E.chartY,G=E.activeTooltipIndex,Y=C.state,X=Y.offset,ae=Y.tooltipTicks;if(!X)return;if(typeof R=="function")G=R(ae,E);else if(R==="value"){G=-1;for(var ie=0;ie=0){var Fe,ke;if(W.dataKey&&!W.allowDuplicatedCategory){var Ve=typeof W.dataKey=="function"?Le:"payload.".concat(W.dataKey.toString());Fe=GTe(ie,Ve,G),ke=ne&&te&>e(te,Ve,G)}else Fe=ie==null?void 0:ie[V],ke=ne&&te&&te[V];if(ue||he){var je=E.props.activeIndex!==void 0?E.props.activeIndex:V;return[j.cloneElement(E,ba(ba(ba({},R.props),Ee),{},{activeIndex:je})),null,null]}if(!Wc(Fe))return[Se].concat(fW(C.renderActivePoints({item:R,activePoint:Fe,basePoint:ke,childIndex:V,isRange:ne})))}else{var Ae,Ce=(Ae=C.getItemByXY(C.state.activeCoordinate))!==null&&Ae!==void 0?Ae:{graphicalItem:Se},qe=Ce.graphicalItem,ze=qe.item,$e=ze===void 0?E:ze,ct=qe.childIndex,Xe=ba(ba(ba({},R.props),Ee),{},{activeIndex:ct});return[j.cloneElement($e,Xe),null,null]}return ne?[Se,null,null]:[Se,null]}),ac(C,"renderCustomized",function(E,I,P){return j.cloneElement(E,ba(ba({key:"recharts-customized-".concat(P)},C.props),C.state))}),ac(C,"renderMap",{CartesianGrid:{handler:eue,once:!0},ReferenceArea:{handler:C.renderReferenceElement},ReferenceLine:{handler:eue},ReferenceDot:{handler:C.renderReferenceElement},XAxis:{handler:eue},YAxis:{handler:eue},Brush:{handler:C.renderBrush,once:!0},Bar:{handler:C.renderGraphicChild},Line:{handler:C.renderGraphicChild},Area:{handler:C.renderGraphicChild},Radar:{handler:C.renderGraphicChild},RadialBar:{handler:C.renderGraphicChild},Scatter:{handler:C.renderGraphicChild},Pie:{handler:C.renderGraphicChild},Funnel:{handler:C.renderGraphicChild},Tooltip:{handler:C.renderCursor,once:!0},PolarGrid:{handler:C.renderPolarGrid,once:!0},PolarAngleAxis:{handler:C.renderPolarAxis},PolarRadiusAxis:{handler:C.renderPolarAxis},Customized:{handler:C.renderCustomized}}),C.clipPathId="".concat((w=b.id)!==null&&w!==void 0?w:e9("recharts"),"-clip"),C.throttleTriggeredAfterMouseMove=dYt(C.triggeredAfterMouseMove,(S=b.throttleDelay)!==null&&S!==void 0?S:1e3/60),C.state={},C}return lRn(v,y),rRn(v,[{key:"componentDidMount",value:function(){var w,S;this.addListener(),this.accessibilityManager.setDetails({container:this.container,offset:{left:(w=this.props.margin.left)!==null&&w!==void 0?w:0,top:(S=this.props.margin.top)!==null&&S!==void 0?S:0},coordinateList:this.state.tooltipTicks,mouseHandlerCallback:this.triggeredAfterMouseMove,layout:this.props.layout}),this.displayDefaultTooltip()}},{key:"displayDefaultTooltip",value:function(){var w=this.props,S=w.children,C=w.data,E=w.height,I=w.layout,P=Gj(S,Ag);if(P){var R=P.props.defaultIndex;if(!(typeof R!="number"||R<0||R>this.state.tooltipTicks.length-1)){var D=this.state.tooltipTicks[R]&&this.state.tooltipTicks[R].value,O=jYe(this.state,C,R,D),U=this.state.tooltipTicks[R].coordinate,W=(this.state.offset.top+E)/2,V=I==="horizontal",G=V?{x:U,y:W}:{y:U,x:W},Y=this.state.formattedGraphicalItems.find(function(ae){var ie=ae.item;return ie.type.name==="Scatter"});Y&&(G=ba(ba({},G),Y.props.points[R].tooltipPosition),O=Y.props.points[R].tooltipPayload);var X={activeTooltipIndex:R,isTooltipActive:!0,activeLabel:D,activePayload:O,activeCoordinate:G};this.setState(X),this.renderCursor(P),this.accessibilityManager.setIndex(R)}}}},{key:"getSnapshotBeforeUpdate",value:function(w,S){if(!this.props.accessibilityLayer)return null;if(this.state.tooltipTicks!==S.tooltipTicks&&this.accessibilityManager.setDetails({coordinateList:this.state.tooltipTicks}),this.props.layout!==w.layout&&this.accessibilityManager.setDetails({layout:this.props.layout}),this.props.margin!==w.margin){var C,E;this.accessibilityManager.setDetails({offset:{left:(C=this.props.margin.left)!==null&&C!==void 0?C:0,top:(E=this.props.margin.top)!==null&&E!==void 0?E:0}})}return null}},{key:"componentDidUpdate",value:function(w){XWe([Gj(w.children,Ag)],[Gj(this.props.children,Ag)])||this.displayDefaultTooltip()}},{key:"componentWillUnmount",value:function(){this.removeListener(),this.throttleTriggeredAfterMouseMove.cancel()}},{key:"getTooltipEventType",value:function(){var w=Gj(this.props.children,Ag);if(w&&typeof w.props.shared=="boolean"){var S=w.props.shared?"axis":"item";return o.indexOf(S)>=0?S:i}return i}},{key:"getMouseInfo",value:function(w){if(!this.container)return null;var S=this.container,C=S.getBoundingClientRect(),E=XNn(C),I={chartX:Math.round(w.pageX-E.left),chartY:Math.round(w.pageY-E.top)},P=C.width/S.offsetWidth||1,R=this.inRange(I.chartX,I.chartY,P);if(!R)return null;var D=this.state,O=D.xAxisMap,U=D.yAxisMap,W=this.getTooltipEventType(),V=Xkt(this.state,this.props.data,this.props.layout,R);if(W!=="axis"&&O&&U){var G=TP(O).scale,Y=TP(U).scale,X=G&&G.invert?G.invert(I.chartX):null,ae=Y&&Y.invert?Y.invert(I.chartY):null;return ba(ba({},I),{},{xValue:X,yValue:ae},V)}return V?ba(ba({},I),V):null}},{key:"inRange",value:function(w,S){var C=arguments.length>2&&arguments[2]!==void 0?arguments[2]:1,E=this.props.layout,I=w/C,P=S/C;if(E==="horizontal"||E==="vertical"){var R=this.state.offset,D=I>=R.left&&I<=R.left+R.width&&P>=R.top&&P<=R.top+R.height;return D?{x:I,y:P}:null}var O=this.state,U=O.angleAxisMap,W=O.radiusAxisMap;if(U&&W){var V=TP(U);return bNt({x:I,y:P},V)}return null}},{key:"parseEventsOfWrapper",value:function(){var w=this.props.children,S=this.getTooltipEventType(),C=Gj(w,Ag),E={};C&&S==="axis"&&(C.props.trigger==="click"?E={onClick:this.handleClick}:E={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 I=WTe(this.props,this.handleOuterEvent);return ba(ba({},I),E)}},{key:"addListener",value:function(){I9e.on(L9e,this.handleReceiveSyncEvent)}},{key:"removeListener",value:function(){I9e.removeListener(L9e,this.handleReceiveSyncEvent)}},{key:"filterFormatItem",value:function(w,S,C){for(var E=this.state.formattedGraphicalItems,I=0,P=E.length;I{const{data:b,error:w}=await q.from("email_campaigns").select("*").eq("status","sent").order("sent_at",{ascending:!0});if(w)throw w;return b}}),{data:r}=tt({queryKey:["campaign-agent-profiles"],queryFn:async()=>{const{data:b,error:w}=await q.from("profiles").select("id, name, email");if(w)throw w;return b}});if(n)return e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:"Loading analytics..."});const a=t||[],i=new Map((r||[]).map(b=>[b.id,b])),l=a.reduce((b,w)=>b+(w.sent_count||0),0),o=a.reduce((b,w)=>b+(w.open_count||0),0),c=a.reduce((b,w)=>b+(w.click_count||0),0),d=a.reduce((b,w)=>b+(w.bounce_count||0),0),u=a.reduce((b,w)=>b+(w.complaint_count||0),0),h=l>0?(o/l*100).toFixed(1):"0.0",m=l>0?(c/l*100).toFixed(1):"0.0",f=[{label:"Campaigns Sent",value:a.length,icon:Yr,color:"text-foreground"},{label:"Total Emails Sent",value:l,icon:Zn,color:"text-green-600"},{label:"Avg Open Rate",value:`${h}%`,icon:Ca,color:"text-blue-600"},{label:"Avg Click Rate",value:`${m}%`,icon:hb,color:"text-purple-600"},{label:"Total Bounces",value:d,icon:wl,color:"text-orange-600"},{label:"Complaints",value:u,icon:Yl,color:"text-destructive"}],g=new Map;a.forEach(b=>{var C,E;const w=b.user_id,S=g.get(w)||{name:((C=i.get(w))==null?void 0:C.name)||((E=i.get(w))==null?void 0:E.email)||"Unknown",campaigns:0,sent:0,opens:0,clicks:0};S.campaigns++,S.sent+=b.sent_count||0,S.opens+=b.open_count||0,S.clicks+=b.click_count||0,g.set(w,S)});const x=[...g.entries()].map(([b,w])=>({id:b,...w,openRate:w.sent>0?+(w.opens/w.sent*100).toFixed(1):0})).sort((b,w)=>w.sent-b.sent),y=x.slice(0,6).map(b=>({name:b.name,value:b.sent})),v=a.map(b=>{var w;return{name:b.name.length>20?b.name.slice(0,20)+"…":b.name,agent:((w=i.get(b.user_id))==null?void 0:w.name)||"Unknown",openRate:b.sent_count>0?+(b.open_count/b.sent_count*100).toFixed(1):0,clickRate:b.sent_count>0?+(b.click_count/b.sent_count*100).toFixed(1):0,sent:b.sent_count,date:b.sent_at?en(new Date(b.sent_at),"MMM d"):""}});return e.jsx("div",{className:"space-y-6",children:a.length===0?e.jsx(Ne,{children:e.jsxs(Ie,{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(Yr,{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:f.map(b=>e.jsx(Ne,{children:e.jsxs(Ie,{className:"p-4 text-center",children:[e.jsx(b.icon,{className:`h-5 w-5 mx-auto mb-1 ${b.color}`}),e.jsx("p",{className:"text-2xl font-bold",children:b.value}),e.jsx("p",{className:"text-xs text-muted-foreground",children:b.label})]})},b.label))}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs(Ne,{children:[e.jsx(Ct,{children:e.jsx(At,{className:"text-base",children:"Open & Click Rates by Campaign"})}),e.jsx(Ie,{children:e.jsx("div",{className:"h-[280px]",children:e.jsx(A_,{width:"100%",height:"100%",children:e.jsxs(OK,{data:v,children:[e.jsx(Mb,{dataKey:"date",fontSize:11}),e.jsx(Pb,{fontSize:11,unit:"%"}),e.jsx(Ag,{formatter:b=>`${b}%`}),e.jsx(qw,{dataKey:"openRate",fill:"hsl(220, 70%, 50%)",name:"Open Rate",radius:[2,2,0,0]}),e.jsx(qw,{dataKey:"clickRate",fill:"hsl(270, 70%, 50%)",name:"Click Rate",radius:[2,2,0,0]})]})})})})]}),e.jsxs(Ne,{children:[e.jsx(Ct,{children:e.jsx(At,{className:"text-base",children:"Send Volume by Agent"})}),e.jsx(Ie,{children:e.jsx("div",{className:"h-[280px]",children:e.jsx(A_,{width:"100%",height:"100%",children:e.jsxs(OXt,{children:[e.jsx(g3,{data:y,dataKey:"value",nameKey:"name",cx:"50%",cy:"50%",outerRadius:100,label:({name:b,percent:w})=>`${b} (${(w*100).toFixed(0)}%)`,fontSize:11,children:y.map((b,w)=>e.jsx(t9,{fill:eSt[w%eSt.length]},w))}),e.jsx(Ag,{})]})})})})]})]}),e.jsxs(Ne,{children:[e.jsx(Ct,{children:e.jsx(At,{className:"text-base",children:"Send Volume Trend"})}),e.jsx(Ie,{children:e.jsx("div",{className:"h-[240px]",children:e.jsx(A_,{width:"100%",height:"100%",children:e.jsxs(Jat,{data:v,children:[e.jsx(Mb,{dataKey:"date",fontSize:11}),e.jsx(Pb,{fontSize:11}),e.jsx(Ag,{}),e.jsx(zL,{type:"monotone",dataKey:"sent",stroke:"hsl(142, 71%, 45%)",strokeWidth:2,name:"Emails Sent",dot:{r:4}})]})})})})]}),e.jsxs(Ne,{children:[e.jsx(Ct,{children:e.jsx(At,{className:"text-base",children:"Agent Performance"})}),e.jsx(Ie,{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:x.map(b=>e.jsxs("tr",{className:"border-b last:border-0 hover:bg-muted/30",children:[e.jsx("td",{className:"py-2.5 font-medium",children:b.name}),e.jsx("td",{className:"py-2.5 text-center",children:b.campaigns}),e.jsx("td",{className:"py-2.5 text-center",children:b.sent}),e.jsx("td",{className:"py-2.5 text-center",children:b.opens}),e.jsx("td",{className:"py-2.5 text-center",children:b.clicks}),e.jsx("td",{className:"py-2.5 text-center",children:e.jsxs(Be,{variant:"outline",children:[b.openRate,"%"]})})]},b.id))})]})})})]}),e.jsxs(Ne,{children:[e.jsx(Ct,{children:e.jsx(At,{className:"text-base",children:"Campaign Leaderboard"})}),e.jsx(Ie,{children:e.jsx("div",{className:"space-y-2",children:[...a].sort((b,w)=>{const S=b.sent_count>0?b.open_count/b.sent_count:0;return(w.sent_count>0?w.open_count/w.sent_count:0)-S}).slice(0,10).map((b,w)=>{const S=b.sent_count>0?(b.open_count/b.sent_count*100).toFixed(1):"0.0",C=b.sent_count>0?(b.click_count/b.sent_count*100).toFixed(1):"0.0",E=i.get(b.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/${b.id}`),children:[e.jsxs("span",{className:"text-lg font-bold text-muted-foreground w-6",children:["#",w+1]}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-medium text-sm truncate",children:b.name}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[(E==null?void 0:E.name)||"Unknown"," · ",b.sent_at?en(new Date(b.sent_at),"MMM d, yyyy"):""," · ",b.sent_count," sent"]})]}),e.jsxs("div",{className:"flex gap-3 text-xs",children:[e.jsxs(Be,{variant:"outline",className:"gap-1",children:[e.jsx(Ca,{className:"h-3 w-3"})," ",S,"%"]}),e.jsxs(Be,{variant:"outline",className:"gap-1",children:[e.jsx(hb,{className:"h-3 w-3"})," ",C,"%"]})]})]},b.id)})})})]})]})})}const kRn=()=>{const{toast:s}=Bi(),[t,n]=j.useState(!0),[r,a]=j.useState([]),[i,l]=j.useState([]),[o,c]=j.useState({installs:0,activeAgents:0,impressions30d:0,leads30d:0});j.useEffect(()=>{d()},[]);const d=async()=>{try{n(!0);const u=new Date;u.setDate(u.getDate()-30);const h=u.toISOString(),{data:m}=await q.from("website_apps").select("slug, name").order("sort_order"),f=[];let g=0;for(;;){const{data:C,error:E}=await q.from("agent_website_app_installs").select("user_id, app_slug, enabled").range(g,g+999);if(E)throw E;if(f.push(...C||[]),!C||C.length<1e3)break;g+=1e3}const x=[];for(g=0;;){const{data:C,error:E}=await q.from("widget_events").select("user_id, app_slug, event_type, created_at").gte("created_at",h).order("created_at",{ascending:!1}).range(g,g+999);if(E)throw E;if(x.push(...C||[]),!C||C.length<1e3||(g+=1e3,g>2e4))break}const y=new Map;for(const C of m||[])y.set(C.slug,{app_slug:C.slug,app_name:C.name,installs:0,enabled:0,impressions:0,expands:0,cta_clicks:0,lead_captures:0});for(const C of f){const E=y.get(C.app_slug);E&&(E.installs+=1,C.enabled&&(E.enabled+=1))}for(const C of x){const E=y.get(C.app_slug);E&&(C.event_type==="impression"?E.impressions+=1:C.event_type==="expand"?E.expands+=1:C.event_type==="cta_click"?E.cta_clicks+=1:C.event_type==="lead_capture"&&(E.lead_captures+=1))}const v=new Map;for(const C of f){if(!C.enabled)continue;const E=v.get(C.user_id)||{user_id:C.user_id,name:null,email:null,apps_enabled:[],events_30d:0,leads_30d:0};E.apps_enabled.includes(C.app_slug)||E.apps_enabled.push(C.app_slug),v.set(C.user_id,E)}for(const C of x){const E=v.get(C.user_id);E&&(E.events_30d+=1,C.event_type==="lead_capture"&&(E.leads_30d+=1))}const b=Array.from(v.keys());if(b.length>0){const{data:C}=await q.from("profiles").select("id, name, email").in("id",b);for(const E of C||[]){const I=v.get(E.id);I&&(I.name=E.name,I.email=E.email)}}const w=Array.from(y.values()),S=Array.from(v.values()).sort((C,E)=>E.events_30d-C.events_30d);a(w),l(S),c({installs:w.reduce((C,E)=>C+E.enabled,0),activeAgents:S.length,impressions30d:w.reduce((C,E)=>C+E.impressions,0),leads30d:w.reduce((C,E)=>C+E.lead_captures,0)})}catch(u){console.error(u),s({title:"Error",description:u.message||"Failed to load website app analytics",variant:"destructive"})}finally{n(!1)}};return t?e.jsx(Ne,{children:e.jsx(Ie,{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(Ne,{children:[e.jsxs(Ct,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(At,{className:"text-sm font-medium",children:"Active Installs"}),e.jsx(dl,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Ie,{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(Ne,{children:[e.jsxs(Ct,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(At,{className:"text-sm font-medium",children:"Agents Using Apps"}),e.jsx(Zn,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Ie,{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(Ne,{children:[e.jsxs(Ct,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(At,{className:"text-sm font-medium",children:"Impressions (30d)"}),e.jsx(Ca,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Ie,{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(Ne,{children:[e.jsxs(Ct,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(At,{className:"text-sm font-medium",children:"Leads Captured (30d)"}),e.jsx(mn,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Ie,{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(Ne,{children:[e.jsx(Ct,{children:e.jsx(At,{children:"App Performance (last 30 days)"})}),e.jsx(Ie,{children:e.jsxs(mi,{children:[e.jsx(fi,{children:e.jsxs(En,{children:[e.jsx(Dt,{children:"App"}),e.jsx(Dt,{className:"text-right",children:"Installs"}),e.jsx(Dt,{className:"text-right",children:"Enabled"}),e.jsx(Dt,{className:"text-right",children:"Impressions"}),e.jsx(Dt,{className:"text-right",children:"Expands"}),e.jsx(Dt,{className:"text-right",children:"CTA Clicks"}),e.jsx(Dt,{className:"text-right",children:"Leads"}),e.jsx(Dt,{className:"text-right",children:"Conv. Rate"})]})}),e.jsxs(pi,{children:[r.map(u=>{const h=u.impressions>0?(u.lead_captures/u.impressions*100).toFixed(1):"—";return e.jsxs(En,{children:[e.jsx(wt,{className:"font-medium",children:u.app_name}),e.jsx(wt,{className:"text-right",children:u.installs}),e.jsx(wt,{className:"text-right",children:u.enabled}),e.jsx(wt,{className:"text-right",children:u.impressions}),e.jsx(wt,{className:"text-right",children:u.expands}),e.jsx(wt,{className:"text-right",children:u.cta_clicks}),e.jsx(wt,{className:"text-right font-semibold",children:u.lead_captures}),e.jsx(wt,{className:"text-right text-muted-foreground",children:h==="—"?"—":`${h}%`})]},u.app_slug)}),r.length===0&&e.jsx(En,{children:e.jsx(wt,{colSpan:8,className:"text-center text-muted-foreground py-6",children:"No data yet"})})]})]})})]}),e.jsxs(Ne,{children:[e.jsx(Ct,{children:e.jsx(At,{children:"Agent Usage (last 30 days)"})}),e.jsxs(Ie,{children:[e.jsxs(mi,{children:[e.jsx(fi,{children:e.jsxs(En,{children:[e.jsx(Dt,{children:"Agent"}),e.jsx(Dt,{children:"Email"}),e.jsx(Dt,{children:"Apps Enabled"}),e.jsx(Dt,{className:"text-right",children:"Events (30d)"}),e.jsx(Dt,{className:"text-right",children:"Leads (30d)"})]})}),e.jsxs(pi,{children:[i.slice(0,100).map(u=>e.jsxs(En,{children:[e.jsx(wt,{className:"font-medium",children:u.name||"—"}),e.jsx(wt,{className:"text-muted-foreground",children:u.email||"—"}),e.jsx(wt,{children:e.jsx("div",{className:"flex flex-wrap gap-1",children:u.apps_enabled.map(h=>e.jsx(Be,{variant:"secondary",className:"text-xs",children:h},h))})}),e.jsx(wt,{className:"text-right",children:u.events_30d}),e.jsx(wt,{className:"text-right font-semibold",children:u.leads_30d})]},u.user_id)),i.length===0&&e.jsx(En,{children:e.jsx(wt,{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."]})]})]})]})},SRn=()=>{const[s,t]=j.useState([]),[n,r]=j.useState([]),[a,i]=j.useState({}),[l,o]=j.useState(!0);j.useEffect(()=>{c()},[]);const c=async()=>{o(!0);try{const[{data:h},{data:m}]=await Promise.all([q.rpc("get_extension_usage_summary"),q.from("extension_usage_events").select("id, user_id, action, metadata, created_at").order("created_at",{ascending:!1}).limit(50)]),f=h||[],g=m||[];t(f),r(g);const x=Array.from(new Set(g.map(y=>y.user_id)));if(x.length){const{data:y}=await q.from("profiles").select("id, name, email").in("id",x),v={};(y||[]).forEach(b=>{v[b.id]={name:b.name,email:b.email}}),i(v)}}finally{o(!1)}},d=s.reduce((h,m)=>({users:h.users+1,contacts:h.contacts+Number(m.contacts_saved||0),listings:h.listings+Number(m.listings_imported||0),activities:h.activities+Number(m.activities_logged||0),events:h.events+Number(m.total_events||0)}),{users:0,contacts:0,listings:0,activities:0,events:0});if(l)return e.jsx(Ne,{children:e.jsx(Ie,{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 u=h=>{switch(h){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 h}};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(Ne,{children:[e.jsxs(Ct,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(At,{className:"text-sm font-medium",children:"Active Users"}),e.jsx(Zn,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Ie,{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(Ne,{children:[e.jsxs(Ct,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(At,{className:"text-sm font-medium",children:"Total Actions"}),e.jsx($z,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Ie,{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(Ne,{children:[e.jsxs(Ct,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(At,{className:"text-sm font-medium",children:"Contacts Saved"}),e.jsx(sc,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsx(Ie,{children:e.jsx("div",{className:"text-2xl font-bold",children:d.contacts})})]}),e.jsxs(Ne,{children:[e.jsxs(Ct,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(At,{className:"text-sm font-medium",children:"Listings Imported"}),e.jsx(va,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsx(Ie,{children:e.jsx("div",{className:"text-2xl font-bold",children:d.listings})})]}),e.jsxs(Ne,{children:[e.jsxs(Ct,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(At,{className:"text-sm font-medium",children:"Activities Logged"}),e.jsx(eo,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsx(Ie,{children:e.jsx("div",{className:"text-2xl font-bold",children:d.activities})})]})]}),e.jsxs(Ne,{children:[e.jsx(Ct,{children:e.jsx(At,{children:"Users by Extension Activity"})}),e.jsx(Ie,{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(mi,{children:[e.jsx(fi,{children:e.jsxs(En,{children:[e.jsx(Dt,{children:"User"}),e.jsx(Dt,{className:"text-right",children:"Total"}),e.jsx(Dt,{className:"text-right",children:"Contacts"}),e.jsx(Dt,{className:"text-right",children:"Listings"}),e.jsx(Dt,{className:"text-right",children:"Activities"}),e.jsx(Dt,{children:"First Used"}),e.jsx(Dt,{children:"Last Used"})]})}),e.jsx(pi,{children:s.map(h=>e.jsxs(En,{children:[e.jsxs(wt,{children:[e.jsx("div",{className:"font-medium",children:h.name||"—"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:h.email})]}),e.jsx(wt,{className:"text-right font-medium",children:h.total_events}),e.jsx(wt,{className:"text-right",children:h.contacts_saved}),e.jsx(wt,{className:"text-right",children:h.listings_imported}),e.jsx(wt,{className:"text-right",children:h.activities_logged}),e.jsx(wt,{className:"text-xs text-muted-foreground",children:h.first_event_at?en(new Date(h.first_event_at),"MMM d, yyyy"):"—"}),e.jsx(wt,{className:"text-xs text-muted-foreground",children:h.last_event_at?en(new Date(h.last_event_at),"MMM d, h:mm a"):"—"})]},h.user_id))})]})})})]}),e.jsxs(Ne,{children:[e.jsx(Ct,{children:e.jsx(At,{children:"Recent Activity"})}),e.jsx(Ie,{children:n.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:n.map(h=>{const m=a[h.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(Be,{variant:"secondary",children:u(h.action)}),e.jsxs("div",{children:[e.jsx("div",{className:"text-sm font-medium",children:(m==null?void 0:m.name)||(m==null?void 0:m.email)||h.user_id.slice(0,8)}),h.metadata&&Object.keys(h.metadata).length>0&&e.jsx("div",{className:"text-xs text-muted-foreground truncate max-w-md",children:JSON.stringify(h.metadata)})]})]}),e.jsx("div",{className:"text-xs text-muted-foreground",children:en(new Date(h.created_at),"MMM d, h:mm a")})]},h.id)})})})]})]})},CRn=()=>e.jsx(Vs,{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(ha,{defaultValue:"analytics",className:"space-y-4",children:[e.jsxs(ma,{children:[e.jsx(Zt,{value:"analytics",children:"Analytics"}),e.jsx(Zt,{value:"website-apps",children:"Website Apps"}),e.jsx(Zt,{value:"extension",children:"Chrome Extension"}),e.jsx(Zt,{value:"content",children:"Content"}),e.jsx(Zt,{value:"email-campaigns",children:"Email Campaigns"}),e.jsx(Zt,{value:"activity",children:"Activity"}),e.jsx(Zt,{value:"shares",children:"Shares"})]}),e.jsx(Xt,{value:"analytics",className:"space-y-4",children:e.jsx(Pmn,{})}),e.jsx(Xt,{value:"website-apps",className:"space-y-4",children:e.jsx(kRn,{})}),e.jsx(Xt,{value:"extension",className:"space-y-4",children:e.jsx(SRn,{})}),e.jsx(Xt,{value:"content",className:"space-y-4",children:e.jsx(Lmn,{})}),e.jsx(Xt,{value:"email-campaigns",className:"space-y-4",children:e.jsx(NRn,{})}),e.jsx(Xt,{value:"activity",className:"space-y-4",children:e.jsx(Mmn,{})}),e.jsx(Xt,{value:"shares",className:"space-y-4",children:e.jsx(KWt,{})})]})]})});function ARn(){const s=Vt(),[t,n]=j.useState(!1),[r,a]=j.useState(null),[i,l]=j.useState({title:"",description:"",publish_date:new Date().toISOString().split("T")[0],is_published:!1,category_id:""}),[o,c]=j.useState(null),[d,u]=j.useState(""),[h,m]=j.useState([]),[f,g]=j.useState([]),[x,y]=j.useState([]),[v,b]=j.useState(!1),[w,S]=j.useState(null),[C,E]=j.useState(""),{data:I,isLoading:P}=tt({queryKey:["brokerage-resources"],queryFn:async()=>{const{data:ke,error:Ve}=await q.from("brokerage_resources").select("*").order("publish_date",{ascending:!1});if(Ve)throw Ve;return ke}}),{data:R}=tt({queryKey:["brokerage-resource-pdfs"],queryFn:async()=>{const{data:ke,error:Ve}=await q.from("brokerage_resource_pdfs").select("*").order("sort_order",{ascending:!0});if(Ve)throw Ve;return ke}}),{data:D}=tt({queryKey:["brokerage-resource-videos"],queryFn:async()=>{const{data:ke,error:Ve}=await q.from("brokerage_resource_videos").select("*").order("sort_order",{ascending:!0});if(Ve)throw Ve;return ke}}),{data:O}=tt({queryKey:["brokerage-resource-links"],queryFn:async()=>{const{data:ke,error:Ve}=await q.from("brokerage_resource_links").select("*").order("sort_order",{ascending:!0});if(Ve)throw Ve;return ke}}),{data:U,isLoading:W}=tt({queryKey:["brokerage-resource-categories"],queryFn:async()=>{const{data:ke,error:Ve}=await q.from("brokerage_resource_categories").select("*").order("sort_order",{ascending:!0});if(Ve)throw Ve;return ke}}),V=()=>{l({title:"",description:"",publish_date:new Date().toISOString().split("T")[0],is_published:!1,category_id:""}),c(null),u(""),m([]),g([]),y([]),a(null),E("")},G=ke=>{a(ke),l({title:ke.title,description:ke.description||"",publish_date:ke.publish_date.split("T")[0],is_published:ke.is_published,category_id:ke.category_id||""}),u(ke.preview_image_url||""),E("");const Ve=(R==null?void 0:R.filter(Ce=>Ce.resource_id===ke.id))||[];m(Ve.map(Ce=>({id:Ce.id,name:Ce.name,file_url:Ce.file_url,file_size:Ce.file_size,sort_order:Ce.sort_order})));const je=(D==null?void 0:D.filter(Ce=>Ce.resource_id===ke.id))||[];g(je.map(Ce=>({id:Ce.id,title:Ce.title,video_url:Ce.video_url,sort_order:Ce.sort_order})));const Ae=(O==null?void 0:O.filter(Ce=>Ce.resource_id===ke.id))||[];y(Ae.map(Ce=>({id:Ce.id,title:Ce.title,canva_share_link:Ce.canva_share_link,sort_order:Ce.sort_order}))),n(!0)},Y=ke=>{var je;const Ve=(je=ke.target.files)==null?void 0:je[0];Ve&&(c(Ve),u(URL.createObjectURL(Ve)))},X=()=>{m([...h,{name:"",file_url:"",sort_order:h.length}])},ae=ke=>{m(h.filter((Ve,je)=>je!==ke))},ie=(ke,Ve,je)=>{const Ae=[...h];if(Ve==="file"&&je instanceof File){const Ce=je.name.replace(/\.[^/.]+$/,"");Ae[ke]={...Ae[ke],file:je,file_size:je.size,name:Ae[ke].name||Ce}}else Ae[ke]={...Ae[ke],[Ve]:je};m(Ae)},ne=()=>{g([...f,{title:"",video_url:"",sort_order:f.length}])},te=ke=>{g(f.filter((Ve,je)=>je!==ke))},J=(ke,Ve,je)=>{const Ae=[...f];Ve==="file"&&je instanceof File?Ae[ke]={...Ae[ke],file:je}:Ae[ke]={...Ae[ke],[Ve]:je},g(Ae)},ce=()=>{y([...x,{title:"",canva_share_link:"",sort_order:x.length}])},_e=ke=>{y(x.filter((Ve,je)=>je!==ke))},he=(ke,Ve,je)=>{const Ae=[...x];Ae[ke]={...Ae[ke],[Ve]:je},y(Ae)},ue=async(ke,Ve)=>{try{const je=await q.functions.invoke("bunny-upload",{body:{action:"create",title:ke.name}});if(je.error)throw je.error;const{videoId:Ae,uploadUrl:Ce,libraryId:qe}=je.data,ze=await q.functions.invoke("bunny-upload",{body:{action:"upload-url",videoId:Ae,libraryId:qe}});if(ze.error)throw ze.error;const{uploadUrl:$e,apiKey:ct}=ze.data,Xe=new XMLHttpRequest;return Xe.open("PUT",$e,!0),Xe.setRequestHeader("AccessKey",ct),Xe.upload.onprogress=it=>{if(it.lengthComputable){const at=Math.round(it.loaded/it.total*100),Ke=[...f];Ke[Ve]={...Ke[Ve],uploadProgress:at},g(Ke)}},await new Promise((it,at)=>{Xe.onload=()=>Xe.status>=200&&Xe.status<300?it():at(new Error("Upload failed")),Xe.onerror=()=>at(new Error("Upload failed")),Xe.send(ke)}),`https://iframe.mediadelivery.net/embed/${qe}/${Ae}`}catch(je){throw console.error("Bunny upload error:",je),je}},ve=ft({mutationFn:async ke=>{const{data:Ve,error:je}=await q.from("brokerage_resource_categories").insert({name:ke,sort_order:(U==null?void 0:U.length)||0}).select().single();if(je)throw je;return Ve},onSuccess:ke=>{s.invalidateQueries({queryKey:["brokerage-resource-categories"]}),l({...i,category_id:ke.id}),E(""),re.success("Category created")},onError:ke=>{re.error("Failed to create category: "+ke.message)}}),Ee=ft({mutationFn:async()=>{b(!0);let ke=(r==null?void 0:r.preview_image_url)||null;if(o){const Ae=o.name.split(".").pop(),Ce=`${Date.now()}.${Ae}`,{error:qe}=await q.storage.from("brokerage-resources").upload(`previews/${Ce}`,o);if(qe)throw qe;const{data:ze}=q.storage.from("brokerage-resources").getPublicUrl(`previews/${Ce}`);ke=ze.publicUrl}const Ve={title:i.title,description:i.description||null,preview_image_url:ke,publish_date:i.publish_date,is_published:i.is_published,category_id:i.category_id||null};let je;if(r){const{error:Ae}=await q.from("brokerage_resources").update(Ve).eq("id",r.id);if(Ae)throw Ae;je=r.id;const Ce=(R==null?void 0:R.filter(nt=>nt.resource_id===r.id).map(nt=>nt.id))||[],qe=h.filter(nt=>nt.id).map(nt=>nt.id),ze=Ce.filter(nt=>!qe.includes(nt));ze.length>0&&await q.from("brokerage_resource_pdfs").delete().in("id",ze);const $e=(D==null?void 0:D.filter(nt=>nt.resource_id===r.id).map(nt=>nt.id))||[],ct=f.filter(nt=>nt.id).map(nt=>nt.id),Xe=$e.filter(nt=>!ct.includes(nt));Xe.length>0&&await q.from("brokerage_resource_videos").delete().in("id",Xe);const it=(O==null?void 0:O.filter(nt=>nt.resource_id===r.id).map(nt=>nt.id))||[],at=x.filter(nt=>nt.id).map(nt=>nt.id),Ke=it.filter(nt=>!at.includes(nt));Ke.length>0&&await q.from("brokerage_resource_links").delete().in("id",Ke)}else{const{data:Ae,error:Ce}=await q.from("brokerage_resources").insert(Ve).select().single();if(Ce)throw Ce;je=Ae.id}for(let Ae=0;Ae{s.invalidateQueries({queryKey:["brokerage-resources"]}),s.invalidateQueries({queryKey:["brokerage-resource-pdfs"]}),s.invalidateQueries({queryKey:["brokerage-resource-videos"]}),s.invalidateQueries({queryKey:["brokerage-resource-links"]}),re.success(r?"Resource updated":"Resource created"),n(!1),V(),b(!1)},onError:ke=>{re.error("Failed to save resource: "+ke.message),b(!1)}}),Se=ft({mutationFn:async ke=>{const{error:Ve}=await q.from("brokerage_resources").delete().eq("id",ke);if(Ve)throw Ve},onSuccess:()=>{s.invalidateQueries({queryKey:["brokerage-resources"]}),s.invalidateQueries({queryKey:["brokerage-resource-pdfs"]}),s.invalidateQueries({queryKey:["brokerage-resource-videos"]}),s.invalidateQueries({queryKey:["brokerage-resource-links"]}),re.success("Resource deleted")},onError:ke=>{re.error("Failed to delete: "+ke.message)}}),Le=ke=>{if(ke.preventDefault(),!i.title){re.error("Please enter a title");return}Ee.mutate()},Fe=ke=>{const Ve=(R==null?void 0:R.filter(Ce=>Ce.resource_id===ke).length)||0,je=(D==null?void 0:D.filter(Ce=>Ce.resource_id===ke).length)||0,Ae=(O==null?void 0:O.filter(Ce=>Ce.resource_id===ke).length)||0;return{pdfCount:Ve,videoCount:je,linkCount:Ae}};return e.jsx(Vs,{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(Ne,{children:[e.jsx(Ct,{className:"pb-2",children:e.jsx(At,{className:"text-sm font-medium text-muted-foreground",children:"Total Resources"})}),e.jsx(Ie,{children:e.jsx("div",{className:"text-2xl font-bold",children:(I==null?void 0:I.length)||0})})]}),e.jsxs(Ne,{children:[e.jsx(Ct,{className:"pb-2",children:e.jsx(At,{className:"text-sm font-medium text-muted-foreground",children:"Published"})}),e.jsx(Ie,{children:e.jsx("div",{className:"text-2xl font-bold",children:(I==null?void 0:I.filter(ke=>ke.is_published).length)||0})})]})]}),e.jsxs($,{onClick:()=>{V(),n(!0)},children:[e.jsx(dn,{className:"h-4 w-4 mr-2"}),"Add Resource"]})]}),e.jsx(Ne,{children:e.jsx(Ie,{className:"p-0",children:e.jsxs(mi,{children:[e.jsx(fi,{children:e.jsxs(En,{children:[e.jsx(Dt,{children:"Title"}),e.jsx(Dt,{children:"Category"}),e.jsx(Dt,{children:"Content"}),e.jsx(Dt,{children:"Publish Date"}),e.jsx(Dt,{children:"Status"}),e.jsx(Dt,{className:"text-right",children:"Actions"})]})}),e.jsx(pi,{children:P?e.jsx(En,{children:e.jsx(wt,{colSpan:6,className:"text-center py-8",children:"Loading..."})}):(I==null?void 0:I.length)===0?e.jsx(En,{children:e.jsx(wt,{colSpan:6,className:"text-center py-8 text-muted-foreground",children:"No brokerage resources yet. Create your first one!"})}):I==null?void 0:I.map(ke=>{const{pdfCount:Ve,videoCount:je,linkCount:Ae}=Fe(ke.id),Ce=U==null?void 0:U.find(qe=>qe.id===ke.category_id);return e.jsxs(En,{children:[e.jsx(wt,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[ke.preview_image_url?e.jsx("img",{src:ke.preview_image_url,alt:ke.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(Sx,{className:"h-5 w-5 text-muted-foreground"})}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:ke.title}),ke.description&&e.jsx("div",{className:"text-sm text-muted-foreground line-clamp-1",children:ke.description})]})]})}),e.jsx(wt,{children:Ce?e.jsx("span",{className:"inline-flex items-center px-2 py-1 rounded-full text-xs font-medium bg-muted",children:Ce.name}):e.jsx("span",{className:"text-muted-foreground text-sm",children:"—"})}),e.jsx(wt,{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(Jr,{className:"h-3.5 w-3.5"}),Ve]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(ua,{className:"h-3.5 w-3.5"}),je]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Ad,{className:"h-3.5 w-3.5"}),Ae]})]})}),e.jsx(wt,{children:en(new Date(ke.publish_date),"MMM d, yyyy")}),e.jsx(wt,{children:e.jsx("span",{className:`inline-flex items-center px-2 py-1 rounded-full text-xs font-medium ${ke.is_published?"bg-green-100 text-green-800":"bg-yellow-100 text-yellow-800"}`,children:ke.is_published?"Published":"Draft"})}),e.jsx(wt,{className:"text-right",children:e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx($,{variant:"ghost",size:"icon",onClick:()=>{const qe=(R==null?void 0:R.filter(ct=>ct.resource_id===ke.id))||[],ze=(D==null?void 0:D.filter(ct=>ct.resource_id===ke.id))||[],$e=(O==null?void 0:O.filter(ct=>ct.resource_id===ke.id))||[];S({...ke,pdfs:qe,videos:ze,links:$e})},children:e.jsx(Ca,{className:"h-4 w-4"})}),e.jsx($,{variant:"ghost",size:"icon",onClick:()=>G(ke),children:e.jsx(gi,{className:"h-4 w-4"})}),e.jsx($,{variant:"ghost",size:"icon",onClick:async()=>{await fo("Delete this resource?")&&Se.mutate(ke.id)},children:e.jsx(Wn,{className:"h-4 w-4 text-destructive"})})]})})]},ke.id)})})]})})}),e.jsx(zs,{open:t,onOpenChange:n,children:e.jsxs(Os,{className:"max-w-3xl max-h-[90vh] overflow-y-auto",children:[e.jsx(Us,{children:e.jsx(Bs,{children:r?"Edit Brokerage Resource":"Add Brokerage Resource"})}),e.jsxs("form",{onSubmit:Le,className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{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(Sx,{className:"h-8 w-8 text-muted-foreground"})}),e.jsx(pe,{type:"file",accept:"image/*",onChange:Y})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"title",children:"Title *"}),e.jsx(pe,{id:"title",value:i.title,onChange:ke=>l({...i,title:ke.target.value}),placeholder:"Resource Title"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ee,{className:"flex items-center gap-2",children:[e.jsx(Ap,{className:"h-4 w-4"}),"Category"]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(ms,{value:i.category_id,onValueChange:ke=>l({...i,category_id:ke}),children:[e.jsx(us,{className:"flex-1",children:e.jsx(fs,{placeholder:"Select a category"})}),e.jsx(hs,{children:U==null?void 0:U.map(ke=>e.jsx(Ge,{value:ke.id,children:ke.name},ke.id))})]}),i.category_id&&e.jsx($,{type:"button",variant:"ghost",size:"icon",onClick:()=>l({...i,category_id:""}),children:e.jsx(gr,{className:"h-4 w-4"})})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(pe,{placeholder:"Or create new category...",value:C,onChange:ke=>E(ke.target.value),className:"flex-1"}),e.jsxs($,{type:"button",variant:"outline",size:"sm",disabled:!C.trim()||ve.isPending,onClick:()=>ve.mutate(C.trim()),children:[e.jsx(dn,{className:"h-4 w-4 mr-1"}),"Add"]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Description"}),e.jsx(Ek,{content:i.description,onChange:ke=>l({...i,description:ke}),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(ee,{htmlFor:"publish_date",children:"Publish Date"}),e.jsx(pe,{id:"publish_date",type:"date",value:i.publish_date,onChange:ke=>l({...i,publish_date:ke.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Published"}),e.jsxs("div",{className:"flex items-center space-x-2 pt-2",children:[e.jsx(Sn,{checked:i.is_published,onCheckedChange:ke=>l({...i,is_published:ke})}),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(ee,{className:"flex items-center gap-2",children:[e.jsx(Jr,{className:"h-4 w-4"}),"PDF Documents (",h.length,")"]}),e.jsxs($,{type:"button",variant:"outline",size:"sm",onClick:X,children:[e.jsx(dn,{className:"h-4 w-4 mr-1"}),"Add PDF"]})]}),h.map((ke,Ve)=>e.jsxs("div",{className:"flex items-center gap-2 p-3 border rounded-lg bg-muted/50",children:[e.jsx(pe,{placeholder:"PDF Name",value:ke.name,onChange:je=>ie(Ve,"name",je.target.value),className:"flex-1"}),e.jsx(pe,{type:"file",accept:".pdf",onChange:je=>{var Ce;const Ae=(Ce=je.target.files)==null?void 0:Ce[0];Ae&&ie(Ve,"file",Ae)},className:"flex-1"}),ke.file_url&&!ke.file&&e.jsx("span",{className:"text-xs text-muted-foreground",children:"Uploaded"}),e.jsx($,{type:"button",variant:"ghost",size:"icon",onClick:()=>ae(Ve),children:e.jsx(gr,{className:"h-4 w-4"})})]},Ve))]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(ee,{className:"flex items-center gap-2",children:[e.jsx(ua,{className:"h-4 w-4"}),"Videos (",f.length,")"]}),e.jsxs($,{type:"button",variant:"outline",size:"sm",onClick:ne,children:[e.jsx(dn,{className:"h-4 w-4 mr-1"}),"Add Video"]})]}),f.map((ke,Ve)=>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(pe,{placeholder:"Video Title",value:ke.title,onChange:je=>J(Ve,"title",je.target.value),className:"flex-1"}),e.jsx($,{type:"button",variant:"ghost",size:"icon",onClick:()=>te(Ve),children:e.jsx(gr,{className:"h-4 w-4"})})]}),e.jsx(pe,{type:"file",accept:"video/*",onChange:je=>{var Ce;const Ae=(Ce=je.target.files)==null?void 0:Ce[0];Ae&&J(Ve,"file",Ae)}}),ke.uploadProgress!==void 0&&ke.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:`${ke.uploadProgress}%`}})}),ke.video_url&&!ke.file&&e.jsx("span",{className:"text-xs text-muted-foreground",children:"Video uploaded"})]},Ve))]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(ee,{className:"flex items-center gap-2",children:[e.jsx(Ad,{className:"h-4 w-4"}),"Canva Links (",x.length,")"]}),e.jsxs($,{type:"button",variant:"outline",size:"sm",onClick:ce,children:[e.jsx(dn,{className:"h-4 w-4 mr-1"}),"Add Link"]})]}),x.map((ke,Ve)=>e.jsxs("div",{className:"flex items-center gap-2 p-3 border rounded-lg bg-muted/50",children:[e.jsx(pe,{placeholder:"Link Title",value:ke.title,onChange:je=>he(Ve,"title",je.target.value),className:"flex-1"}),e.jsx(pe,{placeholder:"Canva Share Link",value:ke.canva_share_link,onChange:je=>he(Ve,"canva_share_link",je.target.value),className:"flex-1"}),e.jsx($,{type:"button",variant:"ghost",size:"icon",onClick:()=>_e(Ve),children:e.jsx(gr,{className:"h-4 w-4"})})]},Ve))]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-4",children:[e.jsx($,{type:"button",variant:"outline",onClick:()=>n(!1),children:"Cancel"}),e.jsx($,{type:"submit",disabled:Ee.isPending||v,children:Ee.isPending||v?"Saving...":r?"Update":"Create"})]})]})]})}),e.jsx(zs,{open:!!w,onOpenChange:()=>S(null),children:e.jsxs(Os,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(Us,{children:e.jsx(Bs,{children:w==null?void 0:w.title})}),w&&e.jsxs("div",{className:"space-y-4",children:[w.preview_image_url&&e.jsx("img",{src:w.preview_image_url,alt:w.title,className:"w-full h-48 object-cover rounded-lg"}),w.description&&e.jsx("p",{className:"text-muted-foreground",children:w.description}),w.pdfs&&w.pdfs.length>0&&e.jsxs("div",{children:[e.jsxs("h4",{className:"font-medium mb-2 flex items-center gap-2",children:[e.jsx(Jr,{className:"h-4 w-4"}),"PDF Documents (",w.pdfs.length,")"]}),e.jsx("div",{className:"space-y-1",children:w.pdfs.map(ke=>e.jsx("a",{href:ke.file_url,target:"_blank",rel:"noopener noreferrer",className:"block p-2 border rounded hover:bg-muted",children:ke.name},ke.id))})]}),w.videos&&w.videos.length>0&&e.jsxs("div",{children:[e.jsxs("h4",{className:"font-medium mb-2 flex items-center gap-2",children:[e.jsx(ua,{className:"h-4 w-4"}),"Videos (",w.videos.length,")"]}),e.jsx("div",{className:"space-y-2",children:w.videos.map(ke=>e.jsx("div",{className:"p-2 border rounded",children:e.jsx("p",{className:"font-medium text-sm",children:ke.title})},ke.id))})]}),w.links&&w.links.length>0&&e.jsxs("div",{children:[e.jsxs("h4",{className:"font-medium mb-2 flex items-center gap-2",children:[e.jsx(Ad,{className:"h-4 w-4"}),"Canva Links (",w.links.length,")"]}),e.jsx("div",{className:"space-y-1",children:w.links.map(ke=>e.jsx("a",{href:ke.canva_share_link,target:"_blank",rel:"noopener noreferrer",className:"block p-2 border rounded hover:bg-muted",children:ke.title},ke.id))})]})]})]})})]})})}const zXt=[{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 ERn(){const[s,t]=j.useState([]),[n,r]=j.useState(!0),[a,i]=j.useState(!1),[l,o]=j.useState(!1),[c,d]=j.useState(null),[u,h]=j.useState(!1),[m,f]=j.useState(!1),[g,x]=j.useState(""),[y,v]=j.useState(""),[b,w]=j.useState(""),[S,C]=j.useState(""),[E,I]=j.useState("Learn More"),[P,R]=j.useState("top"),[D,O]=j.useState(""),[U,W]=j.useState(!0),[V,G]=j.useState(""),[Y,X]=j.useState("");j.useEffect(()=>{ae()},[]);const ae=async()=>{try{const{data:ve,error:Ee}=await q.from("dashboard_banners").select("*").order("placement").order("sort_order");if(Ee)throw Ee;t(ve||[])}catch(ve){re.error("Failed to load banners: "+ve.message)}finally{r(!1)}},ie=()=>{x(""),v(""),w(""),C(""),I("Learn More"),R("top"),O(""),W(!0),G(""),X(""),d(null)},ne=ve=>{d(ve),x(ve.title),v(ve.description||""),w(ve.image_url),C(ve.link_url||""),I(ve.link_text||"Learn More"),R(ve.placement),O(ve.section_after||""),W(ve.is_active),G(ve.start_date?en(new Date(ve.start_date),"yyyy-MM-dd'T'HH:mm"):""),X(ve.end_date?en(new Date(ve.end_date),"yyyy-MM-dd'T'HH:mm"):""),i(!0)},te=async ve=>{var Se;const Ee=(Se=ve.target.files)==null?void 0:Se[0];if(Ee){h(!0);try{const Le=Ee.name.split(".").pop(),Fe=`${Date.now()}.${Le}`,{error:ke}=await q.storage.from("banner-images").upload(Fe,Ee);if(ke)throw ke;const{data:{publicUrl:Ve}}=q.storage.from("banner-images").getPublicUrl(Fe);w(Ve),re.success("Image uploaded successfully")}catch(Le){re.error("Failed to upload image: "+Le.message)}finally{h(!1)}}},J=async()=>{if(!g.trim()||!b){re.error("Please fill in required fields (title and image)");return}f(!0);try{const ve={title:g.trim(),description:y.trim()||null,image_url:b,link_url:S.trim()||null,link_text:E.trim()||"Learn More",placement:P,section_after:P==="between"?D:null,is_active:U,start_date:V?new Date(V).toISOString():null,end_date:Y?new Date(Y).toISOString():null};if(c){const{error:Ee}=await q.from("dashboard_banners").update(ve).eq("id",c.id);if(Ee)throw Ee;re.success("Banner updated successfully")}else{const Ee=s.filter(Le=>Le.placement===P).length,{error:Se}=await q.from("dashboard_banners").insert({...ve,sort_order:Ee});if(Se)throw Se;re.success("Banner created successfully")}i(!1),ie(),ae()}catch(ve){re.error("Failed to save banner: "+ve.message)}finally{f(!1)}},ce=async()=>{if(c)try{const{error:ve}=await q.from("dashboard_banners").delete().eq("id",c.id);if(ve)throw ve;re.success("Banner deleted successfully"),o(!1),d(null),ae()}catch(ve){re.error("Failed to delete banner: "+ve.message)}},_e=async ve=>{try{const{error:Ee}=await q.from("dashboard_banners").update({is_active:!ve.is_active}).eq("id",ve.id);if(Ee)throw Ee;re.success(ve.is_active?"Banner deactivated":"Banner activated"),ae()}catch(Ee){re.error("Failed to update banner: "+Ee.message)}},he=s.filter(ve=>ve.placement==="top"),ue=s.filter(ve=>ve.placement==="between");return n?e.jsx(Vs,{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(Vs,{title:"Dashboard Management",description:"Configure dashboard modules and banners",children:[e.jsxs("div",{className:"space-y-8",children:[e.jsxs(Ne,{children:[e.jsxs(Ct,{className:"flex flex-row items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs(At,{className:"flex items-center gap-2",children:[e.jsx(Mc,{className:"h-5 w-5"}),"Hero Banners (Top of Dashboard)"]}),e.jsx(Gn,{children:"These banners appear in a rotating carousel at the top of the dashboard"})]}),e.jsxs(zs,{open:a&&P==="top",onOpenChange:ve=>{ve||ie(),i(ve),ve&&R("top")},children:[e.jsx(jl,{asChild:!0,children:e.jsxs($,{onClick:()=>{ie(),R("top")},children:[e.jsx(dn,{className:"mr-2 h-4 w-4"}),"Add Hero Banner"]})}),e.jsxs(Os,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsxs(Us,{children:[e.jsxs(Bs,{children:[c?"Edit":"Create"," Banner"]}),e.jsx(Ir,{children:"Configure the banner's content and display settings"})]}),e.jsx(tSt,{title:g,setTitle:x,description:y,setDescription:v,imageUrl:b,linkUrl:S,setLinkUrl:C,linkText:E,setLinkText:I,placement:P,setPlacement:R,sectionAfter:D,setSectionAfter:O,isActive:U,setIsActive:W,startDate:V,setStartDate:G,endDate:Y,setEndDate:X,handleImageUpload:te,uploading:u,showPlacementOptions:!1}),e.jsxs(Ar,{children:[e.jsx($,{variant:"outline",onClick:()=>{i(!1),ie()},children:"Cancel"}),e.jsx($,{onClick:J,disabled:m,children:m?"Saving...":c?"Update Banner":"Create Banner"})]})]})]})]}),e.jsx(Ie,{children:he.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:he.map(ve=>e.jsx(sSt,{banner:ve,onEdit:()=>ne(ve),onDelete:()=>{d(ve),o(!0)},onToggleActive:()=>_e(ve)},ve.id))})})]}),e.jsxs(Ne,{children:[e.jsxs(Ct,{className:"flex flex-row items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs(At,{className:"flex items-center gap-2",children:[e.jsx(Mc,{className:"h-5 w-5"}),"Section Banners"]}),e.jsx(Gn,{children:"These banners appear between dashboard content sections"})]}),e.jsxs(zs,{open:a&&P==="between",onOpenChange:ve=>{ve||ie(),i(ve),ve&&R("between")},children:[e.jsx(jl,{asChild:!0,children:e.jsxs($,{onClick:()=>{ie(),R("between")},children:[e.jsx(dn,{className:"mr-2 h-4 w-4"}),"Add Section Banner"]})}),e.jsxs(Os,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsxs(Us,{children:[e.jsxs(Bs,{children:[c?"Edit":"Create"," Section Banner"]}),e.jsx(Ir,{children:"Configure where this banner appears between sections"})]}),e.jsx(tSt,{title:g,setTitle:x,description:y,setDescription:v,imageUrl:b,linkUrl:S,setLinkUrl:C,linkText:E,setLinkText:I,placement:P,setPlacement:R,sectionAfter:D,setSectionAfter:O,isActive:U,setIsActive:W,startDate:V,setStartDate:G,endDate:Y,setEndDate:X,handleImageUpload:te,uploading:u,showPlacementOptions:!0}),e.jsxs(Ar,{children:[e.jsx($,{variant:"outline",onClick:()=>{i(!1),ie()},children:"Cancel"}),e.jsx($,{onClick:J,disabled:m,children:m?"Saving...":c?"Update Banner":"Create Banner"})]})]})]})]}),e.jsx(Ie,{children:ue.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:ue.map(ve=>e.jsx(sSt,{banner:ve,onEdit:()=>ne(ve),onDelete:()=>{d(ve),o(!0)},onToggleActive:()=>_e(ve),showSection:!0},ve.id))})})]})]}),e.jsx(zs,{open:l,onOpenChange:o,children:e.jsxs(Os,{children:[e.jsxs(Us,{children:[e.jsx(Bs,{children:"Delete Banner"}),e.jsxs(Ir,{children:['Are you sure you want to delete "',c==null?void 0:c.title,'"? This action cannot be undone.']})]}),e.jsxs(Ar,{children:[e.jsx($,{variant:"outline",onClick:()=>o(!1),children:"Cancel"}),e.jsx($,{variant:"destructive",onClick:ce,children:"Delete"})]})]})})]})}function tSt({title:s,setTitle:t,description:n,setDescription:r,imageUrl:a,linkUrl:i,setLinkUrl:l,linkText:o,setLinkText:c,placement:d,setPlacement:u,sectionAfter:h,setSectionAfter:m,isActive:f,setIsActive:g,startDate:x,setStartDate:y,endDate:v,setEndDate:b,handleImageUpload:w,uploading:S,showPlacementOptions:C}){return e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"title",children:"Title *"}),e.jsx(pe,{id:"title",placeholder:"Banner headline...",value:s,onChange:E=>t(E.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"description",children:"Description"}),e.jsx(Rs,{id:"description",placeholder:"Optional banner description...",value:n,onChange:E=>r(E.target.value),rows:2})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Banner Image *"}),e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx(pe,{type:"file",accept:"image/*",onChange:w,disabled:S,className:"flex-1"}),S&&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(ee,{htmlFor:"linkUrl",children:"Link URL (optional)"}),e.jsx(pe,{id:"linkUrl",placeholder:"https://...",value:i,onChange:E=>l(E.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"linkText",children:"Button Text"}),e.jsx(pe,{id:"linkText",placeholder:"Learn More",value:o,onChange:E=>c(E.target.value)})]})]}),C&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Placement"}),e.jsxs(ms,{value:h,onValueChange:m,children:[e.jsx(us,{children:e.jsx(fs,{placeholder:"Select section placement..."})}),e.jsx(hs,{children:zXt.map(E=>e.jsx(Ge,{value:E.value,children:E.label},E.value))})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ee,{htmlFor:"startDate",className:"flex items-center gap-2",children:[e.jsx(Ta,{className:"h-4 w-4"}),"Start Date (optional)"]}),e.jsx(pe,{id:"startDate",type:"datetime-local",value:x,onChange:E=>y(E.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ee,{htmlFor:"endDate",className:"flex items-center gap-2",children:[e.jsx(Ta,{className:"h-4 w-4"}),"End Date (optional)"]}),e.jsx(pe,{id:"endDate",type:"datetime-local",value:v,onChange:E=>b(E.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(Sn,{id:"isActive",checked:f,onCheckedChange:g}),e.jsx(ee,{htmlFor:"isActive",children:"Active"})]})})]})}function sSt({banner:s,onEdit:t,onDelete:n,onToggleActive:r,showSection:a=!1}){var c;const i=(c=zXt.find(d=>d.value===s.section_after))==null?void 0:c.label,[l,o]=j.useState(null);return j.useEffect(()=>{(async()=>{const{count:u}=await q.from("content_engagement_logs").select("*",{count:"exact",head:!0}).eq("resource_id",s.id).eq("action_type","click_link");o(u??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(Ug,{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(Be,{variant:"secondary",children:"Inactive"}),s.start_date&&new Date(s.start_date)>new Date&&e.jsx(Be,{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(Lm,{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($,{variant:"ghost",size:"icon",children:e.jsx(kr,{className:"h-4 w-4"})})}),e.jsx($,{variant:"ghost",size:"icon",onClick:r,children:s.is_active?e.jsx(Ca,{className:"h-4 w-4"}):e.jsx($g,{className:"h-4 w-4"})}),e.jsx($,{variant:"ghost",size:"icon",onClick:t,children:e.jsx(gi,{className:"h-4 w-4"})}),e.jsx($,{variant:"ghost",size:"icon",onClick:n,children:e.jsx(Wn,{className:"h-4 w-4 text-destructive"})})]})]})}const tue={open:{label:"Open",icon:da,color:"bg-yellow-500"},in_progress:{label:"In Progress",icon:Th,color:"bg-blue-500"},resolved:{label:"Resolved",icon:Nc,color:"bg-green-500"},closed:{label:"Closed",icon:ku,color:"bg-muted-foreground"}},nSt={general:"General Support",technology:"Technology Support",crm:"CRM Support",marketing:"Marketing Support"};function TRn(){var P,R;const{user:s}=vs(),t=Vt(),[n,r]=j.useState(null),[a,i]=j.useState(""),[l,o]=j.useState([]),[c,d]=j.useState("all"),[u,h]=j.useState("all"),[m,f]=j.useState(!1),{data:g=[],isLoading:x}=tt({queryKey:["admin-support-tickets",c,u],queryFn:async()=>{let D=q.from("support_tickets").select("*, profiles!support_tickets_user_id_fkey(name, email)").order("created_at",{ascending:!1});c!=="all"&&(D=D.eq("status",c)),u!=="all"&&(D=D.eq("category",u));const{data:O,error:U}=await D;if(U)throw U;return O}}),{data:y=[]}=tt({queryKey:["admin-users-notifications"],queryFn:async()=>{const{data:D,error:O}=await q.from("user_roles").select("user_id").eq("role","admin");if(O)throw O;const U=D.map(ae=>ae.user_id),{data:W,error:V}=await q.from("profiles").select("id, name, email").in("id",U);if(V)throw V;const{data:G,error:Y}=await q.from("support_notification_settings").select("user_id, receive_notifications");if(Y)throw Y;const X=new Map((G==null?void 0:G.map(ae=>[ae.user_id,ae.receive_notifications]))||[]);return W.map(ae=>({...ae,receives_notifications:X.get(ae.id)||!1}))}}),{data:v=[]}=tt({queryKey:["admin-ticket-replies",n==null?void 0:n.id],queryFn:async()=>{if(!n)return[];const{data:D,error:O}=await q.from("support_ticket_replies").select("*, profiles(name)").eq("ticket_id",n.id).order("created_at",{ascending:!0});if(O)throw O;return D},enabled:!!n}),b=ft({mutationFn:async({userId:D,enabled:O})=>{const{data:U}=await q.from("support_notification_settings").select("id").eq("user_id",D).maybeSingle();if(U){const{error:W}=await q.from("support_notification_settings").update({receive_notifications:O}).eq("user_id",D);if(W)throw W}else{const{error:W}=await q.from("support_notification_settings").insert({user_id:D,receive_notifications:O});if(W)throw W}},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-users-notifications"]}),re.success("Notification settings updated")},onError:()=>{re.error("Failed to update settings")}}),w=ft({mutationFn:async({ticketId:D,status:O})=>{const{error:U}=await q.from("support_tickets").update({status:O}).eq("id",D);if(U)throw U},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-support-tickets"]}),n&&r({...n,status:n.status}),re.success("Status updated")},onError:()=>{re.error("Failed to update status")}}),S=ft({mutationFn:async({ticketId:D,assignedTo:O})=>{const{error:U}=await q.from("support_tickets").update({assigned_to:O}).eq("id",D);if(U)throw U},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-support-tickets"]}),re.success("Ticket assigned")},onError:()=>{re.error("Failed to assign ticket")}}),C=ft({mutationFn:async({content:D,attachments:O})=>{var W,V;if(!n||!s)throw new Error("Missing data");const{error:U}=await q.from("support_ticket_replies").insert({ticket_id:n.id,user_id:s.id,content:D,is_admin_reply:!0,attachments:O});if(U)throw U;try{await q.functions.invoke("support-reply-notify",{body:{ticketId:n.id,ticketSubject:n.subject,replyContent:D,userEmail:(W=n.profiles)==null?void 0:W.email,userName:(V=n.profiles)==null?void 0:V.name}})}catch(G){console.error("Failed to send reply notification:",G)}},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-ticket-replies",n==null?void 0:n.id]}),i(""),o([]),re.success("Reply sent!")},onError:()=>{re.error("Failed to send reply")}}),E=()=>{!a.trim()&&l.length===0||C.mutate({content:a,attachments:l})};j.useEffect(()=>{const D=q.channel("admin-tickets").on("postgres_changes",{event:"*",schema:"public",table:"support_tickets"},()=>{t.invalidateQueries({queryKey:["admin-support-tickets"]})}).subscribe();return()=>{q.removeChannel(D)}},[t]);const I=g.filter(D=>D.status==="open").length;return n?(tue[n.status].icon,e.jsx(Vs,{children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx($,{variant:"ghost",size:"icon",onClick:()=>r(null),children:e.jsx(qa,{className:"h-5 w-5"})}),e.jsxs("div",{className:"flex-1",children:[e.jsx("h1",{className:"text-2xl font-bold",children:n.subject}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx(Be,{variant:"secondary",children:nSt[n.category]}),e.jsxs("span",{className:"text-sm text-muted-foreground",children:["from ",((P=n.profiles)==null?void 0:P.name)||"Unknown"," (",(R=n.profiles)==null?void 0:R.email,")"]})]})]})]}),e.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[e.jsxs(Ne,{children:[e.jsx(Ct,{className:"pb-2",children:e.jsx(At,{className:"text-sm",children:"Status"})}),e.jsx(Ie,{children:e.jsxs(ms,{value:n.status,onValueChange:D=>{w.mutate({ticketId:n.id,status:D}),r({...n,status:D})},children:[e.jsx(us,{children:e.jsx(fs,{})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"open",children:"Open"}),e.jsx(Ge,{value:"in_progress",children:"In Progress"}),e.jsx(Ge,{value:"resolved",children:"Resolved"}),e.jsx(Ge,{value:"closed",children:"Closed"})]})]})})]}),e.jsxs(Ne,{children:[e.jsx(Ct,{className:"pb-2",children:e.jsx(At,{className:"text-sm",children:"Assigned To"})}),e.jsx(Ie,{children:e.jsxs(ms,{value:n.assigned_to||"unassigned",onValueChange:D=>{const O=D==="unassigned"?null:D;S.mutate({ticketId:n.id,assignedTo:O}),r({...n,assigned_to:O})},children:[e.jsx(us,{children:e.jsx(fs,{placeholder:"Unassigned"})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"unassigned",children:"Unassigned"}),y.map(D=>e.jsx(Ge,{value:D.id,children:D.name},D.id))]})]})})]})]}),e.jsxs(Ne,{children:[e.jsx(Ct,{children:e.jsxs(Gn,{children:["Created on ",en(new Date(n.created_at),"MMM d, yyyy 'at' h:mm a")]})}),e.jsx(Ie,{children:e.jsx("p",{className:"text-muted-foreground whitespace-pre-wrap",children:n.description})})]}),e.jsxs(Ne,{children:[e.jsx(Ct,{children:e.jsx(At,{className:"text-lg",children:"Conversation"})}),e.jsxs(Ie,{children:[e.jsx(uo,{className:"h-[300px] pr-4",children:v.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:v.map(D=>{var O,U;return e.jsxs("div",{className:`p-4 rounded-lg ${D.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:D.is_admin_reply?`${((O=D.profiles)==null?void 0:O.name)||"Admin"} (Support)`:((U=D.profiles)==null?void 0:U.name)||"User"}),e.jsx("span",{className:"text-xs text-muted-foreground",children:en(new Date(D.created_at),"MMM d, h:mm a")})]}),e.jsx("p",{className:"text-sm whitespace-pre-wrap",children:D.content}),D.attachments&&D.attachments.length>0&&e.jsx(zWt,{attachments:D.attachments})]},D.id)})})}),e.jsx(Gc,{className:"my-4"}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsx(Rs,{placeholder:"Type your reply...",value:a,onChange:D=>i(D.target.value),className:"min-h-[80px]"}),e.jsx($,{onClick:E,disabled:!a.trim()&&l.length===0||C.isPending,className:"self-end",children:e.jsx(Yr,{className:"h-4 w-4"})})]}),e.jsx(OWt,{value:l,onChange:o,disabled:C.isPending})]})]})]})]})})):e.jsx(Vs,{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",I>0&&e.jsxs(Be,{variant:"destructive",className:"ml-2",children:[I," open"]})]})]}),e.jsxs(zs,{open:m,onOpenChange:f,children:[e.jsx(jl,{asChild:!0,children:e.jsxs($,{variant:"outline",children:[e.jsx(Sd,{className:"h-4 w-4 mr-2"}),"Notification Settings"]})}),e.jsxs(Os,{children:[e.jsxs(Us,{children:[e.jsx(Bs,{children:"Email Notification Settings"}),e.jsx(Ir,{children:"Choose which admins receive email notifications for new support tickets."})]}),e.jsx("div",{className:"space-y-4 mt-4",children:y.map(D=>e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(sl,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:D.name}),e.jsx("p",{className:"text-sm text-muted-foreground",children:D.email})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[D.receives_notifications?e.jsx(qy,{className:"h-4 w-4 text-primary"}):e.jsx(XS,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(Sn,{checked:D.receives_notifications,onCheckedChange:O=>b.mutate({userId:D.id,enabled:O})})]})]},D.id))})]})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex flex-wrap gap-4 items-center",children:[e.jsx(ha,{value:c,onValueChange:d,className:"w-auto",children:e.jsxs(ma,{children:[e.jsx(Zt,{value:"all",children:"All"}),e.jsx(Zt,{value:"open",children:"Open"}),e.jsx(Zt,{value:"in_progress",children:"In Progress"}),e.jsx(Zt,{value:"resolved",children:"Resolved"}),e.jsx(Zt,{value:"closed",children:"Closed"})]})}),e.jsxs(ms,{value:u,onValueChange:h,children:[e.jsx(us,{className:"w-[180px]",children:e.jsx(fs,{placeholder:"All Categories"})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"all",children:"All Categories"}),e.jsx(Ge,{value:"general",children:"General Support"}),e.jsx(Ge,{value:"technology",children:"Technology Support"}),e.jsx(Ge,{value:"crm",children:"CRM Support"}),e.jsx(Ge,{value:"marketing",children:"Marketing Support"})]})]})]}),e.jsx("div",{className:"mt-4",children:x?e.jsx("div",{className:"text-center py-12 text-muted-foreground",children:"Loading tickets..."}):g.length===0?e.jsx(Ne,{children:e.jsxs(Ie,{className:"text-center py-12",children:[e.jsx(Th,{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:g.map(D=>{var U,W;const O=tue[D.status].icon;return e.jsx(Ne,{className:"cursor-pointer hover:bg-muted/50 transition-colors",onClick:()=>r(D),children:e.jsx(Ie,{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:D.subject}),e.jsxs("div",{className:"flex items-center gap-2 mt-1 flex-wrap",children:[e.jsx(Be,{variant:"outline",className:"text-xs",children:nSt[D.category]}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[(U=D.profiles)==null?void 0:U.name," • ",en(new Date(D.created_at),"MMM d, yyyy")]}),D.assigned_to&&e.jsxs(Be,{variant:"secondary",className:"text-xs gap-1",children:[e.jsx(sl,{className:"h-3 w-3"}),((W=y.find(V=>V.id===D.assigned_to))==null?void 0:W.name)||"Assigned"]})]})]}),e.jsxs(Be,{className:tue[D.status].color,children:[e.jsx(O,{className:"h-3 w-3 mr-1"}),tue[D.status].label]})]})})},D.id)})})})]})]})})}const BXt=Tb.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 MRn({content:s,onChange:t,variables:n}){const r=G6e({extensions:[W6e,Y6e.configure({openOnClick:!1,HTMLAttributes:{class:"text-primary underline"}}),Z6e.configure({types:["heading","paragraph"]}),trt,BXt],content:s,onUpdate:({editor:l})=>{t(l.getHTML())}});j.useEffect(()=>{r&&s!==r.getHTML()&&r.commands.setContent(s)},[s,r]);const a=l=>{r&&r.chain().focus().insertContent(`{{${l.key}}}`).run()},i=()=>{if(!r)return;const l=r.getAttributes("link").href,o=window.prompt("URL",l);if(o!==null){if(o===""){r.chain().focus().extendMarkRange("link").unsetLink().run();return}r.chain().focus().extendMarkRange("link").setLink({href:o}).run()}};return r?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($,{type:"button",variant:"ghost",size:"sm",onClick:()=>r.chain().focus().toggleBold().run(),className:r.isActive("bold")?"bg-muted":"",children:e.jsx(AE,{className:"h-4 w-4"})}),e.jsx($,{type:"button",variant:"ghost",size:"sm",onClick:()=>r.chain().focus().toggleItalic().run(),className:r.isActive("italic")?"bg-muted":"",children:e.jsx(ME,{className:"h-4 w-4"})}),e.jsx("div",{className:"w-px h-6 bg-border mx-1"}),e.jsx($,{type:"button",variant:"ghost",size:"sm",onClick:()=>r.chain().focus().toggleBulletList().run(),className:r.isActive("bulletList")?"bg-muted":"",children:e.jsx(P0,{className:"h-4 w-4"})}),e.jsx($,{type:"button",variant:"ghost",size:"sm",onClick:()=>r.chain().focus().toggleOrderedList().run(),className:r.isActive("orderedList")?"bg-muted":"",children:e.jsx(p2,{className:"h-4 w-4"})}),e.jsx("div",{className:"w-px h-6 bg-border mx-1"}),e.jsx($,{type:"button",variant:"ghost",size:"sm",onClick:()=>r.chain().focus().setTextAlign("left").run(),className:r.isActive({textAlign:"left"})?"bg-muted":"",children:e.jsx(BI,{className:"h-4 w-4"})}),e.jsx($,{type:"button",variant:"ghost",size:"sm",onClick:()=>r.chain().focus().setTextAlign("center").run(),className:r.isActive({textAlign:"center"})?"bg-muted":"",children:e.jsx(zI,{className:"h-4 w-4"})}),e.jsx($,{type:"button",variant:"ghost",size:"sm",onClick:()=>r.chain().focus().setTextAlign("right").run(),className:r.isActive({textAlign:"right"})?"bg-muted":"",children:e.jsx($I,{className:"h-4 w-4"})}),e.jsx("div",{className:"w-px h-6 bg-border mx-1"}),e.jsx($,{type:"button",variant:"ghost",size:"sm",onClick:i,className:r.isActive("link")?"bg-muted":"",children:e.jsx(Ad,{className:"h-4 w-4"})}),e.jsx($,{type:"button",variant:"ghost",size:"sm",onClick:()=>r.chain().focus().toggleCodeBlock().run(),className:r.isActive("codeBlock")?"bg-muted":"",children:e.jsx(EE,{className:"h-4 w-4"})}),e.jsx("div",{className:"w-px h-6 bg-border mx-1"}),e.jsx($,{type:"button",variant:"ghost",size:"sm",onClick:()=>r.chain().focus().undo().run(),disabled:!r.can().undo(),children:e.jsx(BE,{className:"h-4 w-4"})}),e.jsx($,{type:"button",variant:"ghost",size:"sm",onClick:()=>r.chain().focus().redo().run(),disabled:!r.can().redo(),children:e.jsx(OE,{className:"h-4 w-4"})}),e.jsx("div",{className:"flex-1"}),n.length>0&&e.jsxs(Uu,{children:[e.jsx(qu,{asChild:!0,children:e.jsxs($,{type:"button",variant:"outline",size:"sm",className:"gap-2",children:[e.jsx(gV,{className:"h-4 w-4"}),"Insert Variable"]})}),e.jsx(Eu,{align:"end",className:"w-64",children:n.map(l=>e.jsxs(ja,{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(H6e,{editor:r,className:"prose prose-sm max-w-none p-4 min-h-[300px] focus:outline-none [&_.ProseMirror]:outline-none [&_.ProseMirror]:min-h-[280px]"}),n.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:n.map(l=>e.jsx(Be,{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 PRn(){const s=Vt(),[t,n]=j.useState(null),[r,a]=j.useState(null),[i,l]=j.useState(""),[o,c]=j.useState(""),[d,u]=j.useState(""),[h,m]=j.useState(!0),[f,g]=j.useState("visual"),{data:x,isLoading:y}=tt({queryKey:["email-templates"],queryFn:async()=>{const{data:C,error:E}=await q.from("email_templates").select("*").order("name");if(E)throw E;return C.map(I=>({...I,available_variables:I.available_variables||[]}))}}),v=ft({mutationFn:async C=>{const{error:E}=await q.from("email_templates").update({subject:C.subject,body_html:C.body_html,description:C.description,is_active:C.is_active}).eq("id",C.id);if(E)throw E},onSuccess:()=>{s.invalidateQueries({queryKey:["email-templates"]}),re.success("Email template updated successfully"),n(null)},onError:C=>{re.error("Failed to update template: "+C.message)}}),b=C=>{n(C),l(C.subject),c(C.body_html),u(C.description||""),m(C.is_active),g("visual")},w=()=>{t&&v.mutate({id:t.id,subject:i,body_html:o,description:d,is_active:h})},S=(C,E)=>{let I=C;return E.forEach(P=>{const R=`{{${P.key}}}`,D=`[${P.label}]`;I=I.replace(new RegExp(R.replace(/[{}]/g,"\\$&"),"g"),D)}),I};return t?e.jsxs(Vs,{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($,{variant:"ghost",onClick:()=>n(null),children:[e.jsx(qa,{className:"h-4 w-4 mr-2"}),"Back to Templates"]}),e.jsx("div",{className:"flex-1"}),e.jsxs($,{variant:"outline",onClick:()=>a(t),children:[e.jsx(Ca,{className:"h-4 w-4 mr-2"}),"Preview"]}),e.jsxs($,{onClick:w,disabled:v.isPending,children:[e.jsx(tl,{className:"h-4 w-4 mr-2"}),v.isPending?"Saving...":"Save Changes"]})]}),e.jsxs(Ne,{children:[e.jsx(Ct,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs(At,{className:"flex items-center gap-2",children:[e.jsx(mn,{className:"h-5 w-5"}),t.name]}),e.jsxs(Gn,{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(ee,{htmlFor:"active-toggle",children:"Active"}),e.jsx(Sn,{id:"active-toggle",checked:h,onCheckedChange:m})]})]})}),e.jsxs(Ie,{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"description",children:"Description"}),e.jsx(Rs,{id:"description",value:d,onChange:C=>u(C.target.value),placeholder:"Brief description of when this email is sent",rows:2})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"subject",children:"Email Subject"}),e.jsx(pe,{id:"subject",value:i,onChange:C=>l(C.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(ee,{children:"Email Body"}),e.jsx(ha,{value:f,onValueChange:C=>g(C),children:e.jsxs(ma,{className:"h-8",children:[e.jsxs(Zt,{value:"visual",className:"text-xs px-3 h-6",children:[e.jsx(sk,{className:"h-3 w-3 mr-1"}),"Visual"]}),e.jsxs(Zt,{value:"html",className:"text-xs px-3 h-6",children:[e.jsx(EE,{className:"h-3 w-3 mr-1"}),"HTML"]})]})})]}),f==="visual"?e.jsx(MRn,{content:o,onChange:c,variables:t.available_variables}):e.jsx(Rs,{value:o,onChange:C=>c(C.target.value),className:"font-mono text-sm min-h-[400px]",placeholder:"HTML email body"})]})]})]})]}),e.jsx(zs,{open:!!r,onOpenChange:()=>a(null),children:e.jsxs(Os,{className:"max-w-3xl max-h-[90vh] overflow-auto",children:[e.jsxs(Us,{children:[e.jsx(Bs,{children:"Email Preview"}),e.jsxs(Ir,{children:["Subject: ",i.replace(/\{\{(\w+)\}\}/g,"[$1]")]})]}),e.jsx("div",{className:"border rounded-lg p-4 bg-white",children:e.jsx("div",{dangerouslySetInnerHTML:{__html:S(o,t.available_variables)}})})]})})]}):e.jsx(Vs,{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"})]}),y?e.jsx("div",{className:"grid gap-4",children:[...Array(4)].map((C,E)=>e.jsx(Ne,{children:e.jsxs(Ct,{children:[e.jsx(yn,{className:"h-5 w-48"}),e.jsx(yn,{className:"h-4 w-96"})]})},E))}):e.jsx("div",{className:"grid gap-4",children:x==null?void 0:x.map(C=>e.jsxs(Ne,{className:"hover:shadow-md transition-shadow",children:[e.jsx(Ct,{children:e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsxs(At,{className:"flex items-center gap-2 text-lg",children:[e.jsx(mn,{className:"h-5 w-5 text-muted-foreground"}),C.name,!C.is_active&&e.jsx(Be,{variant:"secondary",children:"Inactive"})]}),e.jsx(Gn,{children:C.description})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs($,{variant:"outline",size:"sm",onClick:()=>a(C),children:[e.jsx(Ca,{className:"h-4 w-4 mr-2"}),"Preview"]}),e.jsxs($,{size:"sm",onClick:()=>b(C),children:[e.jsx(_p,{className:"h-4 w-4 mr-2"}),"Edit"]})]})]})}),e.jsx(Ie,{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:C.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:C.available_variables.map(E=>e.jsx(Be,{variant:"outline",className:"font-mono text-xs",children:`{{${E.key}}}`},E.key))})]})]})})]},C.id))}),e.jsx(zs,{open:!!r&&!t,onOpenChange:()=>a(null),children:e.jsxs(Os,{className:"max-w-3xl max-h-[90vh] overflow-auto",children:[e.jsxs(Us,{children:[e.jsxs(Bs,{children:["Email Preview: ",r==null?void 0:r.name]}),e.jsxs(Ir,{children:["Subject: ",r==null?void 0:r.subject.replace(/\{\{(\w+)\}\}/g,"[$1]")]})]}),r&&e.jsx("div",{className:"border rounded-lg p-4 bg-white",children:e.jsx("div",{dangerouslySetInnerHTML:{__html:S(r.body_html,r.available_variables)}})})]})})]})})}function IRn(){const s=Vt(),[t,n]=j.useState("templates"),[r,a]=j.useState(null),[i,l]=j.useState(null),[o,c]=j.useState(!1),[d,u]=j.useState(!1),[h,m]=j.useState({title:"",subject:"",body:"",description:"",tone:"",category_id:"",is_active:!0}),[f,g]=j.useState({name:"",description:"",icon:"📧"}),{data:x=[]}=tt({queryKey:["agent-email-template-categories"],queryFn:async()=>{const{data:D,error:O}=await q.from("email_template_categories").select("*").order("sort_order");if(O)throw O;return D}}),{data:y=[],isLoading:v}=tt({queryKey:["agent-email-templates-admin"],queryFn:async()=>{const{data:D,error:O}=await q.from("agent_email_templates").select("*, category:email_template_categories(*)").order("sort_order");if(O)throw O;return D}}),b=ft({mutationFn:async D=>{const O={title:D.title,subject:D.subject,body:D.body,description:D.description||null,tone:D.tone||null,category_id:D.category_id||null,is_active:D.is_active};if(D.id){const{error:U}=await q.from("agent_email_templates").update(O).eq("id",D.id);if(U)throw U}else{const{error:U}=await q.from("agent_email_templates").insert(O);if(U)throw U}},onSuccess:()=>{s.invalidateQueries({queryKey:["agent-email-templates-admin"]}),c(!1),re.success(r?"Template updated":"Template created")},onError:()=>re.error("Failed to save template")}),w=ft({mutationFn:async D=>{const{error:O}=await q.from("agent_email_templates").delete().eq("id",D);if(O)throw O},onSuccess:()=>{s.invalidateQueries({queryKey:["agent-email-templates-admin"]}),re.success("Template deleted")}}),S=ft({mutationFn:async D=>{const O={name:D.name,description:D.description||null,icon:D.icon};if(D.id){const{error:U}=await q.from("email_template_categories").update(O).eq("id",D.id);if(U)throw U}else{const U=x.length>0?Math.max(...x.map(V=>V.sort_order))+1:0,{error:W}=await q.from("email_template_categories").insert({...O,sort_order:U});if(W)throw W}},onSuccess:()=>{s.invalidateQueries({queryKey:["agent-email-template-categories"]}),u(!1),re.success(i?"Category updated":"Category created")},onError:()=>re.error("Failed to save category")}),C=ft({mutationFn:async D=>{const{error:O}=await q.from("email_template_categories").delete().eq("id",D);if(O)throw O},onSuccess:()=>{s.invalidateQueries({queryKey:["agent-email-template-categories"]}),re.success("Category deleted")}}),E=()=>{a(null),m({title:"",subject:"",body:"",description:"",tone:"",category_id:"",is_active:!0}),c(!0)},I=D=>{a(D),m({title:D.title,subject:D.subject,body:D.body,description:D.description||"",tone:D.tone||"",category_id:D.category_id||"",is_active:D.is_active}),c(!0)},P=()=>{l(null),g({name:"",description:"",icon:"📧"}),u(!0)},R=D=>{l(D),g({name:D.name,description:D.description||"",icon:D.icon}),u(!0)};return e.jsx(Vs,{children:e.jsxs("div",{className:"space-y-6 animate-fade-in",children:[e.jsx(Fm,{title:"Agent Email Templates",description:"Manage email templates that agents use when composing emails from Mission Control."}),e.jsxs(ha,{value:t,onValueChange:n,children:[e.jsxs(ma,{children:[e.jsxs(Zt,{value:"templates",className:"gap-2",children:[e.jsx(mn,{className:"h-4 w-4"})," Templates"]}),e.jsxs(Zt,{value:"categories",className:"gap-2",children:[e.jsx(_b,{className:"h-4 w-4"})," Categories"]})]}),e.jsxs(Xt,{value:"templates",className:"space-y-4",children:[e.jsx("div",{className:"flex justify-end",children:e.jsxs($,{onClick:E,className:"gap-2",children:[e.jsx(dn,{className:"h-4 w-4"})," Add Template"]})}),e.jsx(Ne,{children:e.jsx(Ie,{className:"p-0",children:e.jsxs(mi,{children:[e.jsx(fi,{children:e.jsxs(En,{children:[e.jsx(Dt,{children:"Template"}),e.jsx(Dt,{className:"hidden md:table-cell",children:"Category"}),e.jsx(Dt,{className:"hidden md:table-cell",children:"Tone"}),e.jsx(Dt,{children:"Status"}),e.jsx(Dt,{className:"text-right",children:"Actions"})]})}),e.jsx(pi,{children:v?e.jsx(En,{children:e.jsx(wt,{colSpan:5,className:"text-center py-8",children:e.jsx(kt,{className:"h-6 w-6 animate-spin mx-auto"})})}):y.length===0?e.jsx(En,{children:e.jsx(wt,{colSpan:5,className:"text-center py-8 text-muted-foreground",children:"No templates yet. Create your first one!"})}):y.map(D=>e.jsxs(En,{children:[e.jsx(wt,{children:e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:D.title}),e.jsx("p",{className:"text-xs text-muted-foreground truncate max-w-[300px]",children:D.subject})]})}),e.jsx(wt,{className:"hidden md:table-cell",children:D.category?e.jsxs(Be,{variant:"outline",className:"gap-1",children:[D.category.icon," ",D.category.name]}):e.jsx("span",{className:"text-muted-foreground text-sm",children:"—"})}),e.jsx(wt,{className:"hidden md:table-cell",children:D.tone?e.jsx(Be,{variant:"secondary",children:D.tone}):"—"}),e.jsx(wt,{children:e.jsx(Be,{variant:D.is_active?"default":"secondary",children:D.is_active?"Active":"Inactive"})}),e.jsx(wt,{className:"text-right",children:e.jsxs("div",{className:"flex justify-end gap-1",children:[e.jsx($,{variant:"ghost",size:"icon",onClick:()=>I(D),children:e.jsx(gi,{className:"h-4 w-4"})}),e.jsx($,{variant:"ghost",size:"icon",className:"text-destructive hover:text-destructive",onClick:async()=>{await fo("Delete this template?")&&w.mutate(D.id)},children:e.jsx(Wn,{className:"h-4 w-4"})})]})})]},D.id))})]})})})]}),e.jsxs(Xt,{value:"categories",className:"space-y-4",children:[e.jsx("div",{className:"flex justify-end",children:e.jsxs($,{onClick:P,className:"gap-2",children:[e.jsx(dn,{className:"h-4 w-4"})," Add Category"]})}),e.jsx("div",{className:"grid gap-3 sm:grid-cols-2 lg:grid-cols-3",children:x.map(D=>e.jsxs(Ne,{children:[e.jsx(Ct,{className:"pb-2",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(At,{className:"text-base flex items-center gap-2",children:[e.jsx("span",{className:"text-lg",children:D.icon})," ",D.name]}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx($,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>R(D),children:e.jsx(gi,{className:"h-3.5 w-3.5"})}),e.jsx($,{variant:"ghost",size:"icon",className:"h-8 w-8 text-destructive",onClick:async()=>{await fo("Delete this category?")&&C.mutate(D.id)},children:e.jsx(Wn,{className:"h-3.5 w-3.5"})})]})]})}),e.jsxs(Ie,{children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:D.description||"No description"}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-2",children:[y.filter(O=>O.category_id===D.id).length," templates"]})]})]},D.id))})]})]}),e.jsx(zs,{open:o,onOpenChange:c,children:e.jsxs(Os,{className:"sm:max-w-[700px] max-h-[90vh] overflow-y-auto",children:[e.jsx(Us,{children:e.jsx(Bs,{children:r?"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(ee,{children:"Title"}),e.jsx(pe,{value:h.title,onChange:D=>m(O=>({...O,title:D.target.value})),placeholder:"e.g. Quick Check-in"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Category"}),e.jsxs(ms,{value:h.category_id,onValueChange:D=>m(O=>({...O,category_id:D})),children:[e.jsx(us,{children:e.jsx(fs,{placeholder:"Select category"})}),e.jsx(hs,{children:x.map(D=>e.jsxs(Ge,{value:D.id,children:[D.icon," ",D.name]},D.id))})]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Subject Line"}),e.jsx(pe,{value:h.subject,onChange:D=>m(O=>({...O,subject:D.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(ee,{children:"Email Body"}),e.jsx(Rs,{value:h.body,onChange:D=>m(O=>({...O,body:D.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(ee,{children:"Description (internal)"}),e.jsx(pe,{value:h.description,onChange:D=>m(O=>({...O,description:D.target.value})),placeholder:"Short description for admin reference"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Tone"}),e.jsx(pe,{value:h.tone,onChange:D=>m(O=>({...O,tone:D.target.value})),placeholder:"e.g. Warm & Casual"})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Sn,{checked:h.is_active,onCheckedChange:D=>m(O=>({...O,is_active:D}))}),e.jsx(ee,{children:"Active"})]})]}),e.jsxs(Ar,{children:[e.jsx($,{variant:"outline",onClick:()=>c(!1),children:"Cancel"}),e.jsxs($,{onClick:()=>b.mutate({...h,id:r==null?void 0:r.id}),disabled:b.isPending||!h.title||!h.subject||!h.body,children:[b.isPending&&e.jsx(kt,{className:"h-4 w-4 mr-2 animate-spin"}),r?"Save Changes":"Create Template"]})]})]})}),e.jsx(zs,{open:d,onOpenChange:u,children:e.jsxs(Os,{className:"sm:max-w-[450px]",children:[e.jsx(Us,{children:e.jsx(Bs,{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(ee,{children:"Icon"}),e.jsx(pe,{value:f.icon,onChange:D=>g(O=>({...O,icon:D.target.value})),className:"text-center text-lg"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Name"}),e.jsx(pe,{value:f.name,onChange:D=>g(O=>({...O,name:D.target.value})),placeholder:"e.g. Check-in & Stay in Touch"})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Description"}),e.jsx(pe,{value:f.description,onChange:D=>g(O=>({...O,description:D.target.value})),placeholder:"Brief description of this category"})]})]}),e.jsxs(Ar,{children:[e.jsx($,{variant:"outline",onClick:()=>u(!1),children:"Cancel"}),e.jsxs($,{onClick:()=>S.mutate({...f,id:i==null?void 0:i.id}),disabled:S.isPending||!f.name,children:[S.isPending&&e.jsx(kt,{className:"h-4 w-4 mr-2 animate-spin"}),i?"Save Changes":"Create Category"]})]})]})})]})})}const LRn=({brokerageId:s})=>{var Pa,ii,$i;const{toast:t}=Bi(),n=Qn(),[r,a]=j.useState([]),[i,l]=j.useState(!0),[o,c]=j.useState(""),[d,u]=j.useState("all"),[h,m]=j.useState(new Set),[f,g]=j.useState(!1),[x,y]=j.useState({}),[v,b]=j.useState(!1),[w,S]=j.useState(!1),[C,E]=j.useState({email:"",name:"",password:"",phone:""}),[I,P]=j.useState(null),[R,D]=j.useState([]),[O,U]=j.useState("none"),[W,V]=j.useState(!1),[G,Y]=j.useState(null),[X,ae]=j.useState(!1),[ie,ne]=j.useState(!1),[te,J]=j.useState(!1),[ce,_e]=j.useState(""),[he,ue]=j.useState(!1),[ve,Ee]=j.useState([]),[Se,Le]=j.useState(!1),[Fe,ke]=j.useState(!1),[Ve,je]=j.useState(null),[Ae,Ce]=j.useState({name:"",phone:"",email:""}),[qe,ze]=j.useState(!1),[$e,ct]=j.useState(!1),[Xe,it]=j.useState(null),[at,Ke]=j.useState("asc"),[nt,xt]=j.useState(!1),[rt,Yt]=j.useState(null),[qt,ts]=j.useState(!1),[ys,Bt]=j.useState(null),[Ft,rs]=j.useState(""),[St,Xs]=j.useState(!1),[vt,gs]=j.useState(null);j.useEffect(()=>{Ys(),Is(),Ss()},[s]);const Ss=async()=>{try{const{data:Rn}=await q.from("partnership_programs").select("id, name, enabled").eq("brokerage_id",s).maybeSingle();if(!Rn||!Rn.enabled){P(null),D([]);return}const{data:xa}=await q.from("partnership_packages").select("id, name, description, sort_order").eq("program_id",Rn.id).order("sort_order",{ascending:!0});P({id:Rn.id,name:Rn.name}),D(xa||[]),xa&&xa.length>0&&U(xa[0].id)}catch(Rn){console.error("Error loading partnership packages:",Rn)}},Is=async()=>{try{const{data:Rn,error:xa}=await q.from("brokerage_manager_assignments").select("user_id").eq("brokerage_id",s);if(xa)throw xa;Ee((Rn==null?void 0:Rn.map(Ya=>Ya.user_id))||[])}catch(Rn){console.error("Error loading brokerage managers:",Rn)}},Ys=async()=>{try{l(!0);const{data:Rn,error:xa}=await q.functions.invoke("get-brokerage-agents",{body:{brokerageId:s}});if(xa)throw xa;const Ya=Rn.agents||[];if(a(Ya),Ya.length>0){const ho=Ya.map($d=>$d.id),{data:Pc}=await q.from("agent_assistant_assignments").select("agent_id, assistant_id").in("agent_id",ho);if(Pc&&Pc.length>0){const $d=Pc.map(ti=>ti.assistant_id),{data:Nl}=await q.from("profiles").select("id, name, email").in("id",$d),Ho={};for(const ti of Pc){const Xr=Nl==null?void 0:Nl.find(Eo=>Eo.id===ti.assistant_id);Xr&&(Ho[ti.agent_id]={name:Xr.name||"",email:Xr.email||""})}y(Ho)}else y({})}}catch(Rn){console.error("Error loading agents:",Rn),t({title:"Error",description:"Failed to load agents",variant:"destructive"})}finally{l(!1)}},cs=async()=>{var Rn;if(!C.email||!C.name||!C.password){t({title:"Error",description:"Please fill in all fields",variant:"destructive"});return}S(!0);try{const{data:{session:xa}}=await q.auth.getSession(),Ya=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/create-user",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${xa==null?void 0:xa.access_token}`},body:JSON.stringify({...C,brokerageId:s,partnershipPackageId:I&&O!=="none"?O:void 0})}),ho=await Ya.json();if(!Ya.ok)throw new Error(ho.error||"Failed to create agent");t({title:"Success",description:`Agent ${C.email} created successfully`}),E({email:"",name:"",password:"",phone:""}),U(((Rn=R[0])==null?void 0:Rn.id)||"none"),b(!1),Ys()}catch(xa){console.error("Error creating agent:",xa),t({title:"Error",description:xa.message||"Failed to create agent",variant:"destructive"})}finally{S(!1)}},js=async Rn=>{try{const{data:{session:xa}}=await q.auth.getSession(),Ya=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/resend-welcome-email",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${xa==null?void 0:xa.access_token}`},body:JSON.stringify({userId:Rn})}),ho=await Ya.json();if(!Ya.ok)throw new Error(ho.error||"Failed to resend welcome email");t({title:"Success",description:"Welcome email sent successfully"})}catch(xa){console.error("Error resending welcome email:",xa),t({title:"Error",description:xa.message||"Failed to resend welcome email",variant:"destructive"})}},kn=async(Rn,xa)=>{try{const{error:Ya}=await q.functions.invoke("send-password-reset",{body:{email:Rn,redirectTo:"https://dashboard.relevelup.com/profile?reset=true"}});if(Ya)throw Ya;t({title:"Password Reset Sent",description:`Password reset email sent to ${xa}`})}catch(Ya){console.error("Error sending password reset:",Ya),t({title:"Error",description:Ya.message||"Failed to send password reset email",variant:"destructive"})}},Ws=Rn=>{Y(Rn),V(!0)},On=Rn=>{je(Rn),Ce({name:Rn.name,phone:Rn.phone||"",email:Rn.email}),ke(!0)},ds=async()=>{if(!Ve)return;if(!Ae.name.trim()){t({title:"Error",description:"Name is required",variant:"destructive"});return}const Rn=Ae.email.trim().toLowerCase()!==Ve.email.toLowerCase();ze(!0);try{if(Rn){if(!Ae.email.trim())throw new Error("Email is required");ct(!0);const{data:{session:Ya}}=await q.auth.getSession(),ho=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/update-agent-email",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Ya==null?void 0:Ya.access_token}`},body:JSON.stringify({agentId:Ve.id,newEmail:Ae.email.trim(),brokerageId:s})}),Pc=await ho.json();if(ct(!1),!ho.ok)throw new Error(Pc.error||"Failed to update email")}const{error:xa}=await q.from("profiles").update({name:Ae.name.trim(),phone:Ae.phone.trim()||null}).eq("id",Ve.id);if(xa)throw xa;t({title:"Success",description:"Agent profile updated successfully"}),ke(!1),je(null),Ys()}catch(xa){console.error("Error updating agent:",xa),t({title:"Error",description:xa.message||"Failed to update agent",variant:"destructive"})}finally{ze(!1),ct(!1)}},gn=async()=>{if(!ce){t({title:"Error",description:"Please select an agent to promote",variant:"destructive"});return}ue(!0);try{const{data:{session:Rn}}=await q.auth.getSession(),xa=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/manage-user-roles",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Rn==null?void 0:Rn.access_token}`},body:JSON.stringify({userId:ce,role:"brokerage_manager",action:"add",brokerageId:s})}),Ya=await xa.json();if(!xa.ok)throw new Error(Ya.error||"Failed to add brokerage manager");t({title:"Success",description:"Brokerage manager added successfully"}),J(!1),_e(""),Is()}catch(Rn){console.error("Error adding brokerage manager:",Rn),t({title:"Error",description:Rn.message||"Failed to add brokerage manager",variant:"destructive"})}finally{ue(!1)}},As=async Rn=>{try{const{data:{session:xa}}=await q.auth.getSession(),Ya=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/manage-user-roles",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${xa==null?void 0:xa.access_token}`},body:JSON.stringify({userId:Rn,role:"brokerage_manager",action:"remove",brokerageId:s})}),ho=await Ya.json();if(!Ya.ok)throw new Error(ho.error||"Failed to remove brokerage manager");t({title:"Success",description:"Brokerage manager role removed"}),Is()}catch(xa){console.error("Error removing brokerage manager:",xa),t({title:"Error",description:xa.message||"Failed to remove brokerage manager",variant:"destructive"})}},hr=Rn=>ve.includes(Rn),Er=Rn=>{Bt(Rn),rs(""),ts(!0)},qn=async()=>{if(!(!ys||!Ft)){if(Ft.length<6){t({title:"Error",description:"Password must be at least 6 characters",variant:"destructive"});return}Xs(!0);try{const{data:{session:Rn}}=await q.auth.getSession(),xa=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/update-agent-email",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Rn==null?void 0:Rn.access_token}`},body:JSON.stringify({agentId:ys.id,brokerageId:s,action:"set_password",newPassword:Ft})}),Ya=await xa.json();if(!xa.ok)throw new Error(Ya.error||"Failed to set password");t({title:"Success",description:`Password set for ${ys.name}`}),ts(!1),Bt(null),rs("")}catch(Rn){console.error("Error setting password:",Rn),t({title:"Error",description:Rn.message||"Failed to set password",variant:"destructive"})}finally{Xs(!1)}}},hn=async Rn=>{gs(Rn.id);try{const{data:{session:xa}}=await q.auth.getSession(),Ya=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/update-agent-email",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${xa==null?void 0:xa.access_token}`},body:JSON.stringify({agentId:Rn.id,brokerageId:s,action:"claim_account"})}),ho=await Ya.json();if(!Ya.ok)throw new Error(ho.error||"Failed to claim account");t({title:"Success",description:`Account claimed for ${Rn.name}`}),Ys()}catch(xa){console.error("Error claiming account:",xa),t({title:"Error",description:xa.message||"Failed to claim account",variant:"destructive"})}finally{gs(null)}},Fn=async()=>{if(G){ae(!0);try{const{data:{session:Rn}}=await q.auth.getSession(),xa=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/remove-agent",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Rn==null?void 0:Rn.access_token}`},body:JSON.stringify({userId:G.id,brokerageId:s})}),Ya=await xa.json();if(!xa.ok)throw new Error(Ya.error||"Failed to remove agent");t({title:"Success",description:`${G.name} has been removed from your brokerage`}),V(!1),Y(null),Ys()}catch(Rn){console.error("Error removing agent:",Rn),t({title:"Error",description:Rn.message||"Failed to remove agent",variant:"destructive"})}finally{ae(!1)}}},vn=Rn=>{const xa=Rn.trim().split(" ");return xa.length>1?xa[xa.length-1].toLowerCase():Rn.toLowerCase()},xs=Rn=>{Xe===Rn?Ke(at==="asc"?"desc":"asc"):(it(Rn),Ke("asc"))},Lr=Rn=>Xe!==Rn?e.jsx(By,{className:"ml-1 h-4 w-4"}):at==="asc"?e.jsx(Zf,{className:"ml-1 h-4 w-4"}):e.jsx(Dg,{className:"ml-1 h-4 w-4"}),Or=r.filter(Rn=>{if(d==="active"&&!Rn.claimed||d==="pending"&&Rn.claimed)return!1;if(!o)return!0;const xa=o.toLowerCase();return Rn.name.toLowerCase().includes(xa)||Rn.email.toLowerCase().includes(xa)}),ca=[...Or].sort((Rn,xa)=>{if(!Xe)return 0;let Ya=0;return Xe==="name"?Ya=vn(Rn.name).localeCompare(vn(xa.name)):Xe==="status"&&(Ya=Rn.claimed===xa.claimed?0:Rn.claimed?-1:1),at==="asc"?Ya:-Ya});Or.filter(Rn=>Rn.claimed&&!hr(Rn.id));const Jn=Rn=>{m(xa=>{const Ya=new Set(xa);return Ya.has(Rn)?Ya.delete(Rn):Ya.add(Rn),Ya})},Sr=()=>{h.size===ca.length?m(new Set):m(new Set(ca.map(Rn=>Rn.id)))},Un=()=>{m(new Set)},ur=async()=>{const Rn=Array.from(h);if(Rn.length===0)return;g(!0);let xa=0,Ya=0;try{const{data:{session:ho}}=await q.auth.getSession();for(const Pc of Rn)try{(await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/resend-welcome-email",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${ho==null?void 0:ho.access_token}`},body:JSON.stringify({userId:Pc})})).ok?xa++:Ya++}catch{Ya++}xa>0?t({title:"Success",description:`Welcome emails sent to ${xa} agent${xa>1?"s":""}${Ya>0?` (${Ya} failed)`:""}`}):t({title:"Error",description:"Failed to send welcome emails",variant:"destructive"}),Un()}catch(ho){console.error("Error bulk sending welcome emails:",ho),t({title:"Error",description:ho.message||"Failed to send welcome emails",variant:"destructive"})}finally{g(!1)}};return i?e.jsx(Ne,{children:e.jsx(Ie,{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(Ne,{children:[e.jsx(Ct,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(At,{children:"Agents"}),e.jsx(Gn,{children:"Manage your brokerage's agents"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs($,{variant:"outline",onClick:()=>J(!0),children:[e.jsx(Mf,{className:"mr-2 h-4 w-4"}),"Add Brokerage Manager"]}),e.jsxs($,{variant:"outline",onClick:()=>ne(!0),children:[e.jsx(ek,{className:"mr-2 h-4 w-4"}),"Import CSV"]}),e.jsxs($,{onClick:()=>b(!0),children:[e.jsx(sc,{className:"mr-2 h-4 w-4"}),"Add Agent"]})]})]})}),e.jsxs(Ie,{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(Kr,{className:"absolute left-3 top-3 h-4 w-4 text-muted-foreground"}),e.jsx(pe,{placeholder:"Search agents...",value:o,onChange:Rn=>c(Rn.target.value),className:"pl-9"})]}),e.jsxs(ms,{value:d,onValueChange:Rn=>u(Rn),children:[e.jsx(us,{className:"w-[160px]",children:e.jsx(fs,{placeholder:"Filter by status"})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"all",children:"All Agents"}),e.jsx(Ge,{value:"active",children:"Active"}),e.jsx(Ge,{value:"pending",children:"Pending"})]})]})]}),h.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:[h.size," agent",h.size>1?"s":""," selected"]}),e.jsx("div",{className:"flex-1"}),e.jsxs($,{size:"sm",variant:"outline",onClick:()=>{const xa=r.filter(Ya=>h.has(Ya.id)&&Ya.email).map(Ya=>({email:Ya.email,name:Ya.name}));sessionStorage.setItem("campaign_direct_recipients",JSON.stringify(xa)),n("/admin/email-campaigns/new?directMode=1",{state:{directRecipients:xa}})},disabled:f,children:[e.jsx(xm,{className:"mr-2 h-4 w-4"}),"Email Agents (",h.size,")"]}),e.jsxs($,{size:"sm",variant:"outline",onClick:ur,disabled:f,children:[e.jsx(mn,{className:"mr-2 h-4 w-4"}),f?"Sending...":"Resend Welcome Email"]}),e.jsx($,{size:"sm",variant:"ghost",onClick:Un,children:"Clear"})]}),e.jsx("div",{className:"rounded-md border",children:e.jsxs(mi,{children:[e.jsx(fi,{children:e.jsxs(En,{children:[e.jsx(Dt,{className:"w-[40px]",children:e.jsx(ai,{checked:ca.length>0&&h.size===ca.length,onCheckedChange:Sr,"aria-label":"Select all"})}),e.jsx(Dt,{children:e.jsxs($,{variant:"ghost",size:"sm",className:"-ml-3 h-8 hover:bg-transparent",onClick:()=>xs("name"),children:["Name (Last)",Lr("name")]})}),e.jsx(Dt,{children:"Email"}),e.jsx(Dt,{children:e.jsxs($,{variant:"ghost",size:"sm",className:"-ml-3 h-8 hover:bg-transparent",onClick:()=>xs("status"),children:["Status",Lr("status")]})}),e.jsx(Dt,{children:"Actions"})]})}),e.jsx(pi,{children:ca.length===0?e.jsx(En,{children:e.jsx(wt,{colSpan:5,className:"text-center text-muted-foreground",children:"No agents found"})}):ca.map(Rn=>e.jsxs(En,{children:[e.jsx(wt,{children:e.jsx(ai,{checked:h.has(Rn.id),onCheckedChange:()=>Jn(Rn.id),"aria-label":`Select ${Rn.name}`})}),e.jsx(wt,{className:"font-medium",children:Rn.name}),e.jsx(wt,{children:Rn.email}),e.jsx(wt,{children:e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[Rn.claimed?e.jsx(Be,{variant:"default",children:"Active"}):e.jsx(Be,{variant:"secondary",children:"Pending"}),hr(Rn.id)&&e.jsxs(Be,{variant:"outline",className:"border-primary text-primary",children:[e.jsx(bm,{className:"mr-1 h-3 w-3"}),"Manager"]}),x[Rn.id]&&e.jsxs(Be,{variant:"outline",className:"text-xs",children:[e.jsx(Zn,{className:"mr-1 h-3 w-3"}),"Asst: ",x[Rn.id].name||x[Rn.id].email]})]})}),e.jsx(wt,{children:e.jsxs("div",{className:"flex items-center gap-1 flex-wrap",children:[e.jsx($,{size:"sm",variant:"ghost",onClick:()=>{Yt(Rn),xt(!0)},title:"Send celebration",className:"text-yellow-500 hover:text-yellow-600 hover:bg-yellow-50",children:e.jsx(Ax,{className:"h-4 w-4"})}),e.jsx($,{size:"sm",variant:"ghost",onClick:()=>On(Rn),title:"Edit agent",children:e.jsx(gi,{className:"h-4 w-4"})}),!Rn.claimed&&e.jsxs(e.Fragment,{children:[e.jsx($,{size:"sm",variant:"ghost",onClick:()=>js(Rn.id),title:"Resend welcome email",children:e.jsx(mn,{className:"h-4 w-4"})}),e.jsx($,{size:"sm",variant:"ghost",onClick:()=>hn(Rn),title:"Claim account for agent",disabled:vt===Rn.id,className:"text-green-600 hover:text-green-700 hover:bg-green-50",children:e.jsx(y2,{className:"h-4 w-4"})})]}),e.jsx($,{size:"sm",variant:"ghost",onClick:()=>Er(Rn),title:"Set password",className:"text-blue-600 hover:text-blue-700 hover:bg-blue-50",children:e.jsx(pc,{className:"h-4 w-4"})}),e.jsx($,{size:"sm",variant:"ghost",onClick:()=>kn(Rn.email,Rn.name),title:"Send password reset email",children:e.jsx(KI,{className:"h-4 w-4"})}),hr(Rn.id)&&e.jsx($,{size:"sm",variant:"ghost",onClick:()=>As(Rn.id),title:"Remove manager role",className:"text-orange-500 hover:text-orange-600",children:e.jsx(Mf,{className:"h-4 w-4"})}),e.jsx($,{size:"sm",variant:"ghost",onClick:()=>Ws(Rn),className:"text-destructive hover:text-destructive",title:"Remove agent",children:e.jsx(Wn,{className:"h-4 w-4"})})]})})]},Rn.id))})]})})]})]}),e.jsx(zs,{open:v,onOpenChange:b,children:e.jsxs(Os,{children:[e.jsxs(Us,{children:[e.jsx(Bs,{children:"Add New Agent"}),e.jsx(Ir,{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(ee,{htmlFor:"name",children:"Name"}),e.jsx(pe,{id:"name",value:C.name,onChange:Rn=>E({...C,name:Rn.target.value}),placeholder:"John Doe"})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"email",children:"Email"}),e.jsx(pe,{id:"email",type:"email",value:C.email,onChange:Rn=>E({...C,email:Rn.target.value}),placeholder:"john@example.com"})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"phone",children:"Phone (optional)"}),e.jsx(pe,{id:"phone",type:"tel",value:C.phone,onChange:Rn=>E({...C,phone:Rn.target.value}),placeholder:"555-123-4567"})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"password",children:"Temporary Password"}),e.jsx(pe,{id:"password",type:"password",value:C.password,onChange:Rn=>E({...C,password:Rn.target.value}),placeholder:"Temporary password"})]}),I&&R.length>0&&e.jsxs("div",{children:[e.jsxs(ee,{htmlFor:"package",children:[I.name," Package"]}),e.jsxs(ms,{value:O,onValueChange:U,children:[e.jsx(us,{id:"package",children:e.jsx(fs,{placeholder:"Choose a package"})}),e.jsxs(hs,{children:[R.map(Rn=>e.jsx(Ge,{value:Rn.id,children:Rn.name},Rn.id)),e.jsx(Ge,{value:"none",children:"No package (full access)"})]})]}),e.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:O==="none"?"Agent gets unrestricted LevelUp access.":((Pa=R.find(Rn=>Rn.id===O))==null?void 0:Pa.description)||"Their welcome email will list what is included in this package."})]})]}),e.jsxs(Ar,{children:[e.jsx($,{variant:"outline",onClick:()=>b(!1),children:"Cancel"}),e.jsx($,{onClick:cs,disabled:w,children:w?"Creating...":"Create Agent"})]})]})}),e.jsx(zs,{open:W,onOpenChange:V,children:e.jsxs(Os,{children:[e.jsxs(Us,{children:[e.jsx(Bs,{children:"Remove Agent"}),e.jsxs(Ir,{children:["Are you sure you want to remove ",e.jsx("strong",{children:G==null?void 0:G.name})," from your brokerage? This will revoke their access to the dashboard."]})]}),e.jsxs(Ar,{children:[e.jsx($,{variant:"outline",onClick:()=>V(!1),children:"Cancel"}),e.jsx($,{variant:"destructive",onClick:Fn,disabled:X,children:X?"Removing...":"Remove Agent"})]})]})}),e.jsx(BWt,{open:ie,onOpenChange:ne,fixedBrokerageId:s,onSuccess:Ys}),e.jsx(zs,{open:te,onOpenChange:J,children:e.jsxs(Os,{children:[e.jsxs(Us,{children:[e.jsx(Bs,{children:"Add Brokerage Manager"}),e.jsx(Ir,{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(ee,{children:"Select Agent"}),e.jsxs(Yd,{open:Se,onOpenChange:Le,children:[e.jsx(Zd,{asChild:!0,children:e.jsxs($,{variant:"outline",role:"combobox","aria-expanded":Se,className:"w-full justify-between",children:[ce?((ii=r.find(Rn=>Rn.id===ce))==null?void 0:ii.name)+" ("+(($i=r.find(Rn=>Rn.id===ce))==null?void 0:$i.email)+")":"Select an agent to promote...",e.jsx(Pw,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(Bd,{className:"w-full p-0",align:"start",children:e.jsxs(P2,{children:[e.jsx(I2,{placeholder:"Search by name or email..."}),e.jsxs(L2,{className:"max-h-[200px]",children:[e.jsx(R2,{children:"No eligible agents found."}),e.jsx(Uw,{children:r.filter(Rn=>!hr(Rn.id)).map(Rn=>e.jsxs(g1,{value:`${Rn.name} ${Rn.email}`,onSelect:()=>{_e(Rn.id),Le(!1)},children:[e.jsx(la,{className:`mr-2 h-4 w-4 ${ce===Rn.id?"opacity-100":"opacity-0"}`}),Rn.name," (",Rn.email,")"]},Rn.id))})]})]})})]}),r.filter(Rn=>!hr(Rn.id)).length===0&&e.jsx("p",{className:"mt-2 text-sm text-muted-foreground",children:"All agents are already brokerage managers."})]})}),e.jsxs(Ar,{children:[e.jsx($,{variant:"outline",onClick:()=>J(!1),children:"Cancel"}),e.jsx($,{onClick:gn,disabled:he||!ce,children:he?"Adding...":"Add as Manager"})]})]})}),e.jsx(zs,{open:Fe,onOpenChange:ke,children:e.jsxs(Os,{children:[e.jsxs(Us,{children:[e.jsx(Bs,{children:"Edit Agent"}),e.jsxs(Ir,{children:["Update profile information for ",Ve==null?void 0:Ve.name]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"edit-name",children:"Name"}),e.jsx(pe,{id:"edit-name",value:Ae.name,onChange:Rn=>Ce({...Ae,name:Rn.target.value}),placeholder:"Agent name"})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"edit-email",children:"Email"}),e.jsx(pe,{id:"edit-email",type:"email",value:Ae.email,onChange:Rn=>Ce({...Ae,email:Rn.target.value}),placeholder:"agent@example.com"}),Ae.email.trim().toLowerCase()!==(Ve==null?void 0:Ve.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(ee,{htmlFor:"edit-phone",children:"Phone"}),e.jsx(pe,{id:"edit-phone",type:"tel",value:Ae.phone,onChange:Rn=>Ce({...Ae,phone:Rn.target.value}),placeholder:"555-123-4567"})]})]}),e.jsxs(Ar,{children:[e.jsx($,{variant:"outline",onClick:()=>ke(!1),children:"Cancel"}),e.jsx($,{onClick:ds,disabled:qe||$e,children:$e?"Updating email...":qe?"Saving...":"Save Changes"})]})]})}),rt&&e.jsx($Wt,{open:nt,onOpenChange:Rn=>{xt(Rn),Rn||Yt(null)},userId:rt.id,userName:rt.name}),e.jsx(zs,{open:qt,onOpenChange:ts,children:e.jsxs(Os,{children:[e.jsxs(Us,{children:[e.jsx(Bs,{children:"Set Password"}),e.jsxs(Ir,{children:["Set a new password for ",ys==null?void 0:ys.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(ee,{htmlFor:"new-password",children:"New Password"}),e.jsx(pe,{id:"new-password",type:"password",value:Ft,onChange:Rn=>rs(Rn.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(Ar,{children:[e.jsx($,{variant:"outline",onClick:()=>ts(!1),children:"Cancel"}),e.jsx($,{onClick:qn,disabled:St||!Ft||Ft.length<6,children:St?"Setting...":"Set Password"})]})]})})]})},RRn={academy_video:"Academy Video",template:"Template",toolbox:"Toolbox Resource",newsletter:"Newsletter",social_swag:"Social Swag",event:"Event"},DRn={view:"Viewed",click_canva:"Opened Canva",click_pdf:"Downloaded PDF",click_video:"Watched Video",click_link:"Clicked Link",register:"Registered"},FRn=s=>{switch(s){case"academy_video":return e.jsx(ua,{className:"h-4 w-4"});case"template":return e.jsx(Jr,{className:"h-4 w-4"});case"toolbox":return e.jsx(Jr,{className:"h-4 w-4"});case"newsletter":return e.jsx(nk,{className:"h-4 w-4"});case"social_swag":return e.jsx(Nn,{className:"h-4 w-4"});case"event":return e.jsx(Ta,{className:"h-4 w-4"});default:return e.jsx(kr,{className:"h-4 w-4"})}},ORn=({brokerageId:s})=>{const{toast:t}=Bi(),[n,r]=j.useState([]),[a,i]=j.useState([]),[l,o]=j.useState([]),[c,d]=j.useState(!0),[u,h]=j.useState(null);j.useEffect(()=>{m()},[s]);const m=async()=>{try{d(!0);const{data:x,error:y}=await q.from("profiles").select("id, name, email").eq("brokerage_id",s);if(y)throw y;const v=x.map(O=>O.id),b=new Map(x.map(O=>[O.id,O]));if(v.length===0){r([]),i([]),o([]);return}const{data:w,error:S}=await q.from("activity_logs").select("*").in("user_id",v).order("launched_at",{ascending:!1});if(S)throw S;const C=w.map(O=>{var U,W;return{id:O.id,user_id:O.user_id,app_name:O.app_name,launched_at:O.launched_at,user_name:((U=b.get(O.user_id))==null?void 0:U.name)||"Unknown",user_email:((W=b.get(O.user_id))==null?void 0:W.email)||"Unknown"}});r(C);const{data:E,error:I}=await q.from("content_engagement_logs").select("*").in("user_id",v).order("created_at",{ascending:!1});if(I)throw I;const P=(E||[]).map(O=>{var U,W;return{id:O.id,user_id:O.user_id,resource_type:O.resource_type,resource_id:O.resource_id,resource_title:O.resource_title,action_type:O.action_type,created_at:O.created_at,user_name:((U=b.get(O.user_id))==null?void 0:U.name)||"Unknown",user_email:((W=b.get(O.user_id))==null?void 0:W.email)||"Unknown"}});i(P);const R=new Map;x.forEach(O=>{R.set(O.id,{user_id:O.id,user_name:O.name,user_email:O.email,app_launches:0,content_views:0,last_activity:""})}),C.forEach(O=>{const U=R.get(O.user_id);U&&(U.app_launches++,(!U.last_activity||new Date(O.launched_at)>new Date(U.last_activity))&&(U.last_activity=O.launched_at))}),P.forEach(O=>{const U=R.get(O.user_id);U&&(U.content_views++,(!U.last_activity||new Date(O.created_at)>new Date(U.last_activity))&&(U.last_activity=O.created_at))});const D=Array.from(R.values()).filter(O=>O.app_launches>0||O.content_views>0).sort((O,U)=>new Date(U.last_activity).getTime()-new Date(O.last_activity).getTime());o(D)}catch(x){console.error("Error loading activity:",x),t({title:"Error",description:"Failed to load activity logs",variant:"destructive"})}finally{d(!1)}},f=x=>n.filter(y=>y.user_id===x),g=x=>a.filter(y=>y.user_id===x);return c?e.jsx(Ne,{children:e.jsx(Ie,{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(Ne,{children:[e.jsxs(Ct,{children:[e.jsx(At,{children:"Agent Activity"}),e.jsx(Gn,{children:"Track app usage and content engagement - click an agent for details"})]}),e.jsx(Ie,{children:e.jsx("div",{className:"rounded-md border",children:e.jsxs(mi,{children:[e.jsx(fi,{children:e.jsxs(En,{children:[e.jsx(Dt,{children:"Agent"}),e.jsx(Dt,{className:"text-center",children:"App Launches"}),e.jsx(Dt,{className:"text-center",children:"Content Views"}),e.jsx(Dt,{children:"Last Active"})]})}),e.jsx(pi,{children:l.length===0?e.jsx(En,{children:e.jsx(wt,{colSpan:4,className:"text-center text-muted-foreground",children:"No activity yet"})}):l.map(x=>e.jsxs(En,{className:"cursor-pointer hover:bg-muted/50 transition-colors",onClick:()=>h({id:x.user_id,name:x.user_name,email:x.user_email}),children:[e.jsx(wt,{children:e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:x.user_name}),e.jsx("div",{className:"text-sm text-muted-foreground",children:x.user_email})]})}),e.jsx(wt,{className:"text-center",children:e.jsxs(Be,{variant:"outline",className:"gap-1",children:[e.jsx(Bu,{className:"h-3 w-3"}),x.app_launches]})}),e.jsx(wt,{className:"text-center",children:e.jsxs(Be,{variant:"secondary",className:"gap-1",children:[e.jsx(Jr,{className:"h-3 w-3"}),x.content_views]})}),e.jsx(wt,{className:"text-sm text-muted-foreground",children:x.last_activity&&mu(new Date(x.last_activity),{addSuffix:!0})})]},x.user_id))})]})})})]}),e.jsx(zs,{open:!!u,onOpenChange:x=>!x&&h(null),children:e.jsxs(Os,{className:"max-w-3xl max-h-[80vh] overflow-hidden flex flex-col",children:[e.jsxs(Us,{children:[e.jsxs(Bs,{children:[u==null?void 0:u.name,"'s Activity"]}),e.jsx(Ir,{children:u==null?void 0:u.email})]}),e.jsxs(ha,{defaultValue:"content",className:"flex-1 overflow-hidden flex flex-col",children:[e.jsxs(ma,{className:"grid w-full grid-cols-2",children:[e.jsx(Zt,{value:"content",children:"Content Engagement"}),e.jsx(Zt,{value:"apps",children:"App Launches"})]}),e.jsx(Xt,{value:"content",className:"flex-1 overflow-auto",children:e.jsx("div",{className:"rounded-md border",children:e.jsxs(mi,{children:[e.jsx(fi,{children:e.jsxs(En,{children:[e.jsx(Dt,{children:"Resource"}),e.jsx(Dt,{children:"Type"}),e.jsx(Dt,{children:"Action"}),e.jsx(Dt,{children:"Time"})]})}),e.jsx(pi,{children:u&&g(u.id).length===0?e.jsx(En,{children:e.jsx(wt,{colSpan:4,className:"text-center text-muted-foreground",children:"No content engagement yet"})}):u&&g(u.id).map(x=>e.jsxs(En,{children:[e.jsx(wt,{className:"max-w-[200px] truncate font-medium",children:x.resource_title}),e.jsx(wt,{children:e.jsxs(Be,{variant:"outline",className:"gap-1",children:[FRn(x.resource_type),RRn[x.resource_type]||x.resource_type]})}),e.jsx(wt,{children:e.jsx("span",{className:"text-sm text-muted-foreground",children:DRn[x.action_type]||x.action_type})}),e.jsx(wt,{className:"text-sm text-muted-foreground",children:mu(new Date(x.created_at),{addSuffix:!0})})]},x.id))})]})})}),e.jsx(Xt,{value:"apps",className:"flex-1 overflow-auto",children:e.jsx("div",{className:"rounded-md border",children:e.jsxs(mi,{children:[e.jsx(fi,{children:e.jsxs(En,{children:[e.jsx(Dt,{children:"App"}),e.jsx(Dt,{children:"Time"})]})}),e.jsx(pi,{children:u&&f(u.id).length===0?e.jsx(En,{children:e.jsx(wt,{colSpan:2,className:"text-center text-muted-foreground",children:"No app launches yet"})}):u&&f(u.id).map(x=>e.jsxs(En,{children:[e.jsx(wt,{children:e.jsx(Be,{variant:"outline",children:x.app_name})}),e.jsx(wt,{className:"text-sm text-muted-foreground",children:mu(new Date(x.launched_at),{addSuffix:!0})})]},x.id))})]})})})]})]})})]})},zRn=({brokerageId:s})=>{const{toast:t}=Bi(),[n,r]=j.useState({totalAgents:0,activeAgents:0,pendingAgents:0,totalLaunches:0,launchesThisWeek:0,launchesThisMonth:0}),[a,i]=j.useState(!0);j.useEffect(()=>{l()},[s]);const l=async()=>{try{i(!0);const{data:o,error:c}=await q.from("profiles").select("id").eq("brokerage_id",s);if(c)throw c;const d=o.map(C=>C.id),u=d.length;if(d.length===0){i(!1);return}const{data:h,error:m}=await q.from("profiles").select("id, email").in("id",d);if(m)throw m;const{count:f}=await q.from("profiles").select("*",{count:"exact",head:!0}).eq("brokerage_id",s).not("last_login","is",null),g=f||0,x=u-g,{count:y}=await q.from("activity_logs").select("*",{count:"exact",head:!0}).in("user_id",d),v=new Date;v.setDate(v.getDate()-7);const{count:b}=await q.from("activity_logs").select("*",{count:"exact",head:!0}).in("user_id",d).gte("launched_at",v.toISOString()),w=new Date;w.setMonth(w.getMonth()-1);const{count:S}=await q.from("activity_logs").select("*",{count:"exact",head:!0}).in("user_id",d).gte("launched_at",w.toISOString());r({totalAgents:u,activeAgents:g,pendingAgents:x,totalLaunches:y||0,launchesThisWeek:b||0,launchesThisMonth:S||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(Ne,{children:e.jsx(Ie,{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(Ne,{children:[e.jsxs(Ct,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(At,{className:"text-sm font-medium",children:"Total Agents"}),e.jsx(Zn,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Ie,{children:[e.jsx("div",{className:"text-2xl font-bold",children:n.totalAgents}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[n.activeAgents," active, ",n.pendingAgents," pending"]})]})]}),e.jsxs(Ne,{children:[e.jsxs(Ct,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(At,{className:"text-sm font-medium",children:"Active Agents"}),e.jsx(Nc,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Ie,{children:[e.jsx("div",{className:"text-2xl font-bold",children:n.activeAgents}),e.jsx("p",{className:"text-xs text-muted-foreground",children:n.totalAgents>0?`${Math.round(n.activeAgents/n.totalAgents*100)}% of total`:"0% of total"})]})]}),e.jsxs(Ne,{children:[e.jsxs(Ct,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(At,{className:"text-sm font-medium",children:"Pending Invites"}),e.jsx(da,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Ie,{children:[e.jsx("div",{className:"text-2xl font-bold",children:n.pendingAgents}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Awaiting setup"})]})]}),e.jsxs(Ne,{children:[e.jsxs(Ct,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(At,{className:"text-sm font-medium",children:"Total App Launches"}),e.jsx(af,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Ie,{children:[e.jsx("div",{className:"text-2xl font-bold",children:n.totalLaunches}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"All time"})]})]}),e.jsxs(Ne,{children:[e.jsxs(Ct,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(At,{className:"text-sm font-medium",children:"This Week"}),e.jsx(af,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Ie,{children:[e.jsx("div",{className:"text-2xl font-bold",children:n.launchesThisWeek}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Last 7 days"})]})]}),e.jsxs(Ne,{children:[e.jsxs(Ct,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(At,{className:"text-sm font-medium",children:"This Month"}),e.jsx(af,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Ie,{children:[e.jsx("div",{className:"text-2xl font-bold",children:n.launchesThisMonth}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Last 30 days"})]})]})]})},BRn=({brokerageId:s})=>{const[t,n]=j.useState([]),[r,a]=j.useState(!0),[i,l]=j.useState(!1),[o,c]=j.useState(!1),[d,u]=j.useState({description:"",maxUses:""});j.useEffect(()=>{h()},[s]);const h=async()=>{try{const{data:v,error:b}=await q.from("invite_codes").select("*").eq("brokerage_id",s).order("created_at",{ascending:!1});if(b)throw b;n(v||[])}catch(v){console.error("Error loading invite codes:",v),re.error("Failed to load invite links")}finally{a(!1)}},m=()=>Math.random().toString(36).substring(2,8).toUpperCase(),f=async()=>{l(!0);try{const v=m(),{error:b}=await q.from("invite_codes").insert({code:v,description:d.description||null,max_uses:d.maxUses?parseInt(d.maxUses):null,brokerage_id:s,is_active:!0});if(b)throw b;re.success("Invite link created!"),c(!1),u({description:"",maxUses:""}),h()}catch(v){console.error("Error creating invite code:",v),re.error("Failed to create invite link")}finally{l(!1)}},g=async v=>{try{const{error:b}=await q.from("invite_codes").delete().eq("id",v);if(b)throw b;re.success("Invite link deleted"),n(t.filter(w=>w.id!==v))}catch(b){console.error("Error deleting invite code:",b),re.error("Failed to delete invite link")}},x=async(v,b)=>{try{const{error:w}=await q.from("invite_codes").update({is_active:!b}).eq("id",v);if(w)throw w;n(t.map(S=>S.id===v?{...S,is_active:!b}:S)),re.success(`Invite link ${b?"deactivated":"activated"}`)}catch(w){console.error("Error toggling invite code:",w),re.error("Failed to update invite link")}},y=v=>{const b=`${window.location.origin}/join?code=${v}`;navigator.clipboard.writeText(b),re.success("Link copied to clipboard!")};return r?e.jsx(Ne,{children:e.jsx(Ie,{className:"flex items-center justify-center py-8",children:e.jsx(kt,{className:"h-6 w-6 animate-spin text-muted-foreground"})})}):e.jsxs(Ne,{children:[e.jsxs(Ct,{className:"flex flex-row items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs(At,{className:"flex items-center gap-2",children:[e.jsx(Ad,{className:"h-5 w-5"}),"Agent Invite Links"]}),e.jsx(Gn,{children:"Create shareable links for agents to join your brokerage"})]}),e.jsxs(zs,{open:o,onOpenChange:c,children:[e.jsx(jl,{asChild:!0,children:e.jsxs($,{size:"sm",children:[e.jsx(dn,{className:"mr-2 h-4 w-4"}),"Create Link"]})}),e.jsxs(Os,{children:[e.jsxs(Us,{children:[e.jsx(Bs,{children:"Create Invite Link"}),e.jsx(Ir,{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(ee,{htmlFor:"description",children:"Description (optional)"}),e.jsx(pe,{id:"description",placeholder:"e.g., New agent recruiting campaign",value:d.description,onChange:v=>u({...d,description:v.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"maxUses",children:"Max Uses (optional)"}),e.jsx(pe,{id:"maxUses",type:"number",placeholder:"Leave empty for unlimited",value:d.maxUses,onChange:v=>u({...d,maxUses:v.target.value})})]}),e.jsx($,{onClick:f,disabled:i,className:"w-full",children:i?e.jsxs(e.Fragment,{children:[e.jsx(kt,{className:"mr-2 h-4 w-4 animate-spin"}),"Creating..."]}):"Create Invite Link"})]})]})]})]}),e.jsx(Ie,{children:t.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(Ad,{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(v=>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:v.code}),e.jsx(Be,{variant:v.is_active?"default":"secondary",children:v.is_active?"Active":"Inactive"})]}),v.description&&e.jsx("p",{className:"text-sm text-muted-foreground mt-1 truncate",children:v.description}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:[v.uses_count," uses",v.max_uses&&` / ${v.max_uses} max`]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx($,{variant:"ghost",size:"sm",onClick:()=>y(v.code),title:"Copy link",children:e.jsx(Ha,{className:"h-4 w-4"})}),e.jsx($,{variant:"ghost",size:"sm",onClick:()=>x(v.id,v.is_active),title:v.is_active?"Deactivate":"Activate",children:v.is_active?"Disable":"Enable"}),e.jsx($,{variant:"ghost",size:"sm",onClick:()=>g(v.id),className:"text-destructive hover:text-destructive",title:"Delete",children:e.jsx(Wn,{className:"h-4 w-4"})})]})]},v.id))})})]})},$Rn=({open:s,onOpenChange:t,referralCode:n,brokerageId:r,senderName:a,brokerageName:i,onInvitesSent:l})=>{const[o,c]=j.useState(""),[d,u]=j.useState([]),[h,m]=j.useState(""),[f,g]=j.useState(!1),x=S=>/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(S),y=()=>{const S=o.trim().toLowerCase();if(S&&x(S)&&!d.includes(S)){if(d.length>=10){re.error("Maximum 10 emails per invite");return}u([...d,S]),c("")}else S&&!x(S)?re.error("Please enter a valid email address"):d.includes(S)&&re.error("Email already added")},v=S=>{u(d.filter(C=>C!==S))},b=S=>{(S.key==="Enter"||S.key===",")&&(S.preventDefault(),y())},w=async()=>{if(d.length===0){re.error("Please add at least one email address");return}g(!0);try{const{data:S,error:C}=await q.functions.invoke("send-referral-invite",{body:{emails:d,personalMessage:h.trim()||void 0,referralCode:n,brokerageId:r,senderName:a,brokerageName:i}});if(C)throw C;S.successCount===S.totalCount?re.success(`${S.successCount} invite${S.successCount>1?"s":""} sent successfully!`):re.warning(`${S.successCount} of ${S.totalCount} invites sent. Some failed.`),u([]),m(""),t(!1),l==null||l()}catch(S){console.error("Error sending invites:",S),re.error("Failed to send invites. Please try again.")}finally{g(!1)}};return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Os,{className:"sm:max-w-[550px]",children:[e.jsxs(Us,{children:[e.jsxs(Bs,{className:"flex items-center gap-2",children:[e.jsx(mn,{className:"h-5 w-5 text-primary"}),"Invite Broker Friends"]}),e.jsx(Ir,{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(ul,{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(ee,{htmlFor:"email",children:"Email Addresses (up to 10)"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(pe,{id:"email",type:"email",placeholder:"Enter email and press Enter",value:o,onChange:S=>c(S.target.value),onKeyDown:b,onBlur:y}),e.jsx($,{type:"button",variant:"secondary",onClick:y,children:"Add"})]}),d.length>0&&e.jsx("div",{className:"flex flex-wrap gap-2 mt-2",children:d.map(S=>e.jsxs(Be,{variant:"secondary",className:"flex items-center gap-1 pr-1",children:[S,e.jsx("button",{type:"button",onClick:()=>v(S),className:"ml-1 rounded-full p-0.5 hover:bg-muted",children:e.jsx(gr,{className:"h-3 w-3"})})]},S))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"message",children:"Personal Message (optional)"}),e.jsx(Rs,{id:"message",placeholder:"Add a personal note that will appear at the top of the email...",value:h,onChange:S=>m(S.target.value),rows:3,maxLength:500}),e.jsxs("p",{className:"text-xs text-muted-foreground text-right",children:[h.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(Nn,{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($,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsx($,{onClick:w,disabled:d.length===0||f,children:f?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(Yr,{className:"h-4 w-4 mr-2"}),"Send ",d.length>0&&`(${d.length})`," Invite",d.length!==1?"s":""]})})]})]})})},URn=({brokerageId:s,refreshTrigger:t})=>{const[n,r]=j.useState([]),[a,i]=j.useState(!0);j.useEffect(()=>{l()},[s,t]);const l=async()=>{try{const{data:c,error:d}=await q.from("referral_invites").select("*").eq("referrer_brokerage_id",s).order("sent_at",{ascending:!1}).limit(20);if(d)throw d;r(c||[])}catch(c){console.error("Error fetching invites:",c)}finally{i(!1)}},o=c=>{switch(c){case"signed_up":return e.jsxs(Be,{className:"bg-green-100 text-green-800 gap-1",children:[e.jsx(Nc,{className:"h-3 w-3"}),"Signed Up"]});case"expired":return e.jsxs(Be,{variant:"outline",className:"text-muted-foreground gap-1",children:[e.jsx(ku,{className:"h-3 w-3"}),"Expired"]});default:return e.jsxs(Be,{variant:"secondary",className:"gap-1",children:[e.jsx(da,{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"})}):n.length===0?e.jsxs("div",{className:"text-center py-6 text-muted-foreground",children:[e.jsx(mn,{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"}),n.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 ",en(new Date(c.sent_at),"MMM d, yyyy")]})]}),o(c.status)]},c.id))]})},qRn=()=>{const{brokerageId:s,user:t}=vs(),[n,r]=j.useState(null),[a,i]=j.useState(""),[l,o]=j.useState(""),[c,d]=j.useState([]),[u,h]=j.useState(!0),[m,f]=j.useState(!1),[g,x]=j.useState(0);j.useEffect(()=>{s&&y()},[s]);const y=async()=>{try{const[E,I]=await Promise.all([q.from("brokerages").select("name").eq("id",s).single(),t?q.from("profiles").select("name").eq("id",t.id).single():Promise.resolve({data:null})]);E.data&&i(E.data.name),I.data&&o(I.data.name||"A LevelUp Member");const{data:P}=await q.from("referral_codes").select("code").eq("brokerage_id",s).single();if(P)r(P.code);else{const D=`REF${s==null?void 0:s.slice(0,8).toUpperCase()}`;await q.from("referral_codes").insert({brokerage_id:s,code:D}),r(D)}const{data:R}=await q.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(R||[])}catch(E){console.error("Error fetching referral data:",E)}finally{h(!1)}},v=()=>{const E=`https://dashboard.relevelup.com/?ref=${n}`;navigator.clipboard.writeText(E),re.success("Referral link copied to clipboard!")},b=c.filter(E=>E.status==="qualified").length,w=c.filter(E=>E.status==="pending").length,S=b*25,C=Math.max(0,Math.ceil((299-S)/25));return u?null:e.jsxs(e.Fragment,{children:[e.jsxs(Ne,{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(ul,{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:["$",S]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Monthly Savings"})]}),S>0&&e.jsxs("div",{className:"flex items-center gap-1 text-green-600",children:[e.jsx(Nc,{className:"h-4 w-4"}),e.jsx("span",{className:"text-sm font-medium",children:"Active"})]})]}),C>0&&S<299&&e.jsxs("div",{className:"text-right",children:[e.jsxs("p",{className:"text-sm font-medium",children:["Refer ",C," 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"})]}),S>=299&&e.jsxs("div",{className:"flex items-center gap-2 text-primary",children:[e.jsx(Nn,{className:"h-5 w-5"}),e.jsx("span",{className:"font-bold",children:"FREE Membership Unlocked!"})]})]})})]})}),e.jsxs(Ie,{className:"pt-6 space-y-6",children:[e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-3",children:[e.jsxs($,{onClick:()=>f(!0),className:"w-full",size:"lg",children:[e.jsx(mn,{className:"h-4 w-4 mr-2"}),"Invite Broker Friends"]}),e.jsxs($,{onClick:v,variant:"outline",className:"w-full",size:"lg",children:[e.jsx(Ha,{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=",n]})]}),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(ru,{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:["$",S]}),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(Zn,{className:"h-5 w-5 mx-auto text-primary mb-1"}),e.jsx("p",{className:"text-2xl font-bold",children:b}),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(da,{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:w}),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(URn,{brokerageId:s,refreshTrigger:g}),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(E=>{var I,P;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:((I=E.referred_brokerage)==null?void 0:I.name)||((P=E.referred_user)==null?void 0:P.email)||"Pending setup"}),e.jsxs(Be,{variant:E.status==="qualified"?"default":E.status==="pending"?"secondary":"destructive",className:E.status==="qualified"?"bg-green-600":"",children:[E.status==="qualified"&&e.jsx(Nc,{className:"h-3 w-3 mr-1"}),E.status]})]},E.id)})]})]})]}),e.jsx($Rn,{open:m,onOpenChange:f,referralCode:n||"",brokerageId:s||"",senderName:l||"A LevelUp Member",brokerageName:a,onInvitesSent:()=>x(E=>E+1)})]})},VRn=({brokerageId:s})=>{const t=Qn(),{teams:n,isLoading:r}=m3(s),{data:a,isLoading:i}=tt({queryKey:["team-aggregate-stats",s,n.map(u=>u.id)],queryFn:async()=>{if(n.length===0)return[];const u=n.map(E=>E.id),{data:h}=await q.from("team_members").select("team_id, user_id, role").in("team_id",u);if(!h||h.length===0)return n.map(E=>({team_id:E.id,team_name:E.name,member_count:0,leader_name:null,leader_avatar:null,total_contacts:0,total_deals:0,total_videos:0}));const m=h.map(E=>E.user_id),f=h.filter(E=>E.role==="team_leader").map(E=>E.user_id),{data:g}=await q.from("profiles").select("id, name, avatar_url").in("id",f),x=new Map((g||[]).map(E=>[E.id,E])),{data:y}=await q.from("innercircle_contacts").select("owner_user_id").in("owner_user_id",m),{data:v}=await q.from("deal_pipeline").select("owner_user_id").in("owner_user_id",m),{data:b}=await q.from("agent_videos").select("owner_user_id").in("owner_user_id",m).eq("is_deleted",!1),w=new Map;(y||[]).forEach(E=>{w.set(E.owner_user_id,(w.get(E.owner_user_id)||0)+1)});const S=new Map;(v||[]).forEach(E=>{S.set(E.owner_user_id,(S.get(E.owner_user_id)||0)+1)});const C=new Map;return(b||[]).forEach(E=>{C.set(E.owner_user_id,(C.get(E.owner_user_id)||0)+1)}),n.map(E=>{const I=h.filter(V=>V.team_id===E.id),P=I.find(V=>V.role==="team_leader"),R=P?x.get(P.user_id):null,D=I.map(V=>V.user_id),O=D.reduce((V,G)=>V+(w.get(G)||0),0),U=D.reduce((V,G)=>V+(S.get(G)||0),0),W=D.reduce((V,G)=>V+(C.get(G)||0),0);return{team_id:E.id,team_name:E.name,member_count:I.length,leader_name:(R==null?void 0:R.name)||null,leader_avatar:(R==null?void 0:R.avatar_url)||null,total_contacts:O,total_deals:U,total_videos:W}})},enabled:n.length>0});if(r||i)return e.jsx("div",{className:"grid gap-4 md:grid-cols-2 lg:grid-cols-3",children:[1,2,3].map(u=>e.jsxs(Ne,{children:[e.jsx(Ct,{children:e.jsx(yn,{className:"h-5 w-32"})}),e.jsx(Ie,{children:e.jsx(yn,{className:"h-24 w-full"})})]},u))});if(n.length===0)return e.jsx(Ne,{children:e.jsxs(Ie,{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(Zn,{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($,{onClick:()=>t("/brokerage/teams"),children:"Manage Teams"})]})});const o=(a||[]).reduce((u,h)=>u+h.member_count,0),c=(a||[]).reduce((u,h)=>u+h.total_contacts,0),d=(a||[]).reduce((u,h)=>u+h.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(Ne,{children:e.jsxs(Ie,{className:"pt-6",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground mb-1",children:[e.jsx(Zn,{className:"h-4 w-4"})," Teams"]}),e.jsx("p",{className:"text-2xl font-bold",children:n.length})]})}),e.jsx(Ne,{children:e.jsxs(Ie,{className:"pt-6",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground mb-1",children:[e.jsx(Zn,{className:"h-4 w-4"})," Total Members"]}),e.jsx("p",{className:"text-2xl font-bold",children:o})]})}),e.jsx(Ne,{children:e.jsxs(Ie,{className:"pt-6",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground mb-1",children:[e.jsx(HI,{className:"h-4 w-4"})," Total Contacts"]}),e.jsx("p",{className:"text-2xl font-bold",children:c.toLocaleString()})]})}),e.jsx(Ne,{children:e.jsxs(Ie,{className:"pt-6",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground mb-1",children:[e.jsx(Sx,{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(u=>e.jsxs(Ne,{className:"hover:shadow-md transition-shadow",children:[e.jsxs(Ct,{className:"pb-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(At,{className:"text-lg",children:u.team_name}),e.jsxs(Be,{variant:"secondary",children:[u.member_count," members"]})]}),u.leader_name&&e.jsxs("div",{className:"flex items-center gap-2 mt-2",children:[e.jsxs(Oa,{className:"h-6 w-6",children:[e.jsx(Li,{src:u.leader_avatar||""}),e.jsx(za,{className:"text-xs",children:u.leader_name.charAt(0).toUpperCase()})]}),e.jsxs("span",{className:"text-sm text-muted-foreground flex items-center gap-1",children:[e.jsx(Bg,{className:"h-3 w-3 text-amber-500"}),u.leader_name]})]})]}),e.jsx(Ie,{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:u.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:u.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:u.total_videos.toLocaleString()}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Videos"})]})]})})]},u.team_id))}),e.jsx("div",{className:"flex justify-end",children:e.jsx($,{variant:"outline",onClick:()=>t("/brokerage/teams"),children:"Manage Teams →"})})]})},HRn=()=>{const{user:s,isBrokerageManager:t,brokerageId:n,isAdmin:r,managedBrokerages:a,selectedBrokerageId:i,setSelectedBrokerageId:l}=vs(),o=Qn(),{toast:c}=Bi(),[d,u]=j.useState(""),[h,m]=j.useState(!0),f=i||(a.length>0?a[0].id:n);j.useEffect(()=>{if(!s||!t&&!r){o("/dashboard");return}!i&&a.length>0&&l(a[0].id),f?g():a.length===0&&!n&&m(!1)},[s,t,r,f,o,a,i]);const g=async()=>{if(!f){m(!1);return}try{const{data:x,error:y}=await q.from("brokerages").select("name").eq("id",f).single();if(y)throw y;u(x.name)}catch(x){console.error("Error loading brokerage info:",x),c({title:"Error",description:"Failed to load brokerage information",variant:"destructive"})}finally{m(!1)}};return h?e.jsx(Vs,{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"})})}):f?e.jsx(Vs,{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(ms,{value:i||"",onValueChange:l,children:[e.jsxs(us,{className:"w-[280px]",children:[e.jsx(ji,{className:"mr-2 h-4 w-4"}),e.jsx(fs,{placeholder:"Select brokerage"})]}),e.jsx(hs,{children:a.map(x=>e.jsx(Ge,{value:x.id,children:x.name},x.id))})]})]}),e.jsxs(ha,{defaultValue:"agents",className:"space-y-4",children:[e.jsxs(ma,{className:"grid w-full grid-cols-4 md:grid-cols-8",children:[e.jsx(Zt,{value:"agents",children:"Agents"}),e.jsx(Zt,{value:"teams",children:"Teams"}),e.jsx(Zt,{value:"invite",children:"Invite Links"}),e.jsx(Zt,{value:"referrals",children:"Referrals"}),e.jsx(Zt,{value:"leaderboard",children:"Leaderboard"}),e.jsx(Zt,{value:"activity",children:"Activity"}),e.jsx(Zt,{value:"analytics",children:"Analytics"}),e.jsx(Zt,{value:"shares",children:"Shares"})]}),e.jsx(Xt,{value:"agents",className:"space-y-4",children:e.jsx(LRn,{brokerageId:f})}),e.jsx(Xt,{value:"teams",className:"space-y-4",children:e.jsx(VRn,{brokerageId:f})}),e.jsx(Xt,{value:"invite",className:"space-y-4",children:e.jsx(BRn,{brokerageId:f})}),e.jsx(Xt,{value:"referrals",className:"space-y-4",children:e.jsx(qRn,{})}),e.jsx(Xt,{value:"leaderboard",className:"space-y-4",children:e.jsx(SHt,{brokerageId:f,title:`${d} Event Leaderboard`,showUserStats:!1})}),e.jsx(Xt,{value:"activity",className:"space-y-4",children:e.jsx(ORn,{brokerageId:f})}),e.jsx(Xt,{value:"analytics",className:"space-y-4",children:e.jsx(zRn,{brokerageId:f})}),e.jsx(Xt,{value:"shares",className:"space-y-4",children:e.jsx(KWt,{brokerageOnly:!0,brokerageId:f})})]})]})}):e.jsx(Vs,{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(ji,{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 GRn({brokerageId:s,canManage:t}){const{user:n}=vs(),[r,a]=j.useState([]),[i,l]=j.useState(!0),[o,c]=j.useState(!1),[d,u]=j.useState(null),[h,m]=j.useState(null),[f,g]=j.useState(!1),[x,y]=j.useState(""),[v,b]=j.useState(""),[w,S]=j.useState(!1),C=async()=>{try{const{data:D,error:O}=await q.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(O)throw O;const U=D;if(U&&U.length>0){const W=[...new Set(U.map(X=>X.created_by))],{data:V}=await q.from("profiles").select("id, name, avatar_url").in("id",W),G=new Map((V==null?void 0:V.map(X=>[X.id,X]))||[]),Y=U.map(X=>({...X,author:G.get(X.created_by)||{name:"Unknown",avatar_url:null}}));a(Y)}else a([])}catch(D){console.error("Error fetching announcements:",D)}finally{l(!1)}};j.useEffect(()=>{C()},[s]);const E=()=>{y(""),b(""),S(!1),u(null)},I=D=>{D?(u(D),y(D.title),b(D.content),S(D.is_pinned)):E(),c(!0)},P=async()=>{if(!x.trim()||!v.trim()){re.error("Please fill in all fields");return}g(!0);try{if(d){const{error:D}=await q.from("brokerage_announcements").update({title:x.trim(),content:v.trim(),is_pinned:w,pinned_at:w?new Date().toISOString():null}).eq("id",d.id);if(D)throw D;re.success("Announcement updated")}else{const{error:D}=await q.from("brokerage_announcements").insert({brokerage_id:s,created_by:n==null?void 0:n.id,title:x.trim(),content:v.trim(),is_pinned:w,pinned_at:w?new Date().toISOString():null});if(D)throw D;re.success("Announcement created")}c(!1),E(),C()}catch(D){console.error("Error saving announcement:",D),re.error("Failed to save announcement")}finally{g(!1)}},R=async()=>{if(h)try{const{error:D}=await q.from("brokerage_announcements").delete().eq("id",h);if(D)throw D;re.success("Announcement deleted"),C()}catch(D){console.error("Error deleting announcement:",D),re.error("Failed to delete announcement")}finally{m(null)}};return i?e.jsxs(Ne,{children:[e.jsx(Ct,{children:e.jsxs(At,{className:"flex items-center gap-2",children:[e.jsx(xm,{className:"h-5 w-5"}),"Announcements"]})}),e.jsx(Ie,{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(Ne,{children:[e.jsxs(Ct,{className:"flex flex-row items-center justify-between space-y-0 pb-4",children:[e.jsxs(At,{className:"flex items-center gap-2",children:[e.jsx(xm,{className:"h-5 w-5 text-primary"}),"Announcements"]}),t&&e.jsxs($,{size:"sm",onClick:()=>I(),className:"gap-1",children:[e.jsx(dn,{className:"h-4 w-4"}),"New"]})]}),e.jsx(Ie,{children:r.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:r.map(D=>{var O,U,W,V;return e.jsx("div",{className:`p-4 rounded-lg border ${D.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:[D.is_pinned&&e.jsx(DE,{className:"h-3.5 w-3.5 text-primary shrink-0"}),e.jsx("h4",{className:"font-semibold truncate",children:D.title})]}),e.jsx("p",{className:"text-sm text-muted-foreground whitespace-pre-wrap",children:D.content}),e.jsxs("div",{className:"flex items-center gap-2 mt-3 text-xs text-muted-foreground",children:[e.jsxs(Oa,{className:"h-5 w-5",children:[e.jsx(Li,{src:((O=D.author)==null?void 0:O.avatar_url)||void 0}),e.jsx(za,{className:"text-[10px]",children:((W=(U=D.author)==null?void 0:U.name)==null?void 0:W.charAt(0))||"?"})]}),e.jsx("span",{children:(V=D.author)==null?void 0:V.name}),e.jsx("span",{children:"•"}),e.jsx("span",{children:en(new Date(D.created_at),"MMM d, yyyy")})]})]}),t&&e.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[e.jsx($,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>I(D),children:e.jsx(gi,{className:"h-4 w-4"})}),e.jsx($,{variant:"ghost",size:"icon",className:"h-8 w-8 text-destructive hover:text-destructive",onClick:()=>m(D.id),children:e.jsx(Wn,{className:"h-4 w-4"})})]})]})},D.id)})})})]}),e.jsx(zs,{open:o,onOpenChange:c,children:e.jsxs(Os,{children:[e.jsx(Us,{children:e.jsx(Bs,{children:d?"Edit Announcement":"New Announcement"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"title",children:"Title"}),e.jsx(pe,{id:"title",value:x,onChange:D=>y(D.target.value),placeholder:"Announcement title..."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"content",children:"Content"}),e.jsx(Rs,{id:"content",value:v,onChange:D=>b(D.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(Sn,{id:"pinned",checked:w,onCheckedChange:S}),e.jsxs(ee,{htmlFor:"pinned",className:"flex items-center gap-1 cursor-pointer",children:[e.jsx(DE,{className:"h-4 w-4"}),"Pin to top"]})]})}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx($,{variant:"outline",onClick:()=>c(!1),children:"Cancel"}),e.jsx($,{onClick:P,disabled:f,children:f?"Saving...":d?"Update":"Create"})]})]})]})}),e.jsx(kc,{open:!!h,onOpenChange:()=>m(null),children:e.jsxs(cc,{children:[e.jsxs(dc,{children:[e.jsx(hc,{children:"Delete Announcement"}),e.jsx(mc,{children:"Are you sure you want to delete this announcement? This action cannot be undone."})]}),e.jsxs(uc,{children:[e.jsx(fc,{children:"Cancel"}),e.jsx(tc,{onClick:R,className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Delete"})]})]})})]})}function WRn({brokerageId:s,canManage:t=!1}){const{startImpersonation:n,isLoading:r}=pLe(),{user:a}=vs(),[i,l]=j.useState([]),[o,c]=j.useState(!0),[d,u]=j.useState(""),[h,m]=j.useState(new Set);j.useEffect(()=>{(async()=>{try{const{data:x,error:y}=await q.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(y)throw y;if(l(x||[]),x&&x.length>0){const v=x.map(w=>w.id),{data:b}=await q.from("agent_assistant_assignments").select("agent_id").in("agent_id",v);b&&m(new Set(b.map(w=>w.agent_id)))}}catch(x){console.error("Error fetching agents:",x)}finally{c(!1)}})()},[s]);const f=i.filter(g=>{var x,y;return g.name.toLowerCase().includes(d.toLowerCase())||g.email.toLowerCase().includes(d.toLowerCase())||((x=g.title)==null?void 0:x.toLowerCase().includes(d.toLowerCase()))||((y=g.areas_served)==null?void 0:y.toLowerCase().includes(d.toLowerCase()))});return o?e.jsxs(Ne,{children:[e.jsx(Ct,{children:e.jsxs(At,{className:"flex items-center gap-2",children:[e.jsx(Zn,{className:"h-5 w-5"}),"Agent Roster"]})}),e.jsx(Ie,{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(g=>e.jsx("div",{className:"animate-pulse",children:e.jsx("div",{className:"h-48 bg-muted rounded-lg"})},g))})})]}):e.jsxs(Ne,{children:[e.jsxs(Ct,{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-4 space-y-0",children:[e.jsxs(At,{className:"flex items-center gap-2",children:[e.jsx(Zn,{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(Kr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(pe,{placeholder:"Search agents...",value:d,onChange:g=>u(g.target.value),className:"pl-9"})]})]}),e.jsx(Ie,{children:f.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:f.map(g=>e.jsx(KRn,{agent:g,hasAssistant:h.has(g.id),canImpersonate:t&&g.id!==(a==null?void 0:a.id),onImpersonate:()=>n(g.id,"/my-brokerage"),impersonationLoading:r},g.id))})})]})}function KRn({agent:s,hasAssistant:t,canImpersonate:n,onImpersonate:r,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(Oa,{className:"h-20 w-20 mb-3 ring-2 ring-background shadow-md",children:[e.jsx(Li,{src:s.avatar_url||void 0,alt:s.name}),e.jsx(za,{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(Be,{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(ci,{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:[n&&e.jsxs(ly,{children:[e.jsx(cy,{asChild:!0,children:e.jsx($,{variant:"outline",size:"icon",className:"h-8 w-8 text-blue-600 hover:text-blue-700 hover:bg-blue-50",onClick:r,disabled:a,children:e.jsx(ZI,{className:"h-4 w-4"})})}),e.jsxs(Nx,{children:["Login as ",s.name]})]}),s.phone&&e.jsx($,{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(Da,{className:"h-4 w-4"})})}),e.jsx($,{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(mn,{className:"h-4 w-4"})})}),s.linkedin_url&&e.jsx($,{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(hy,{className:"h-4 w-4"})})}),s.instagram_url&&e.jsx($,{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(Tf,{className:"h-4 w-4"})})})]})]})}function YRn({brokerageId:s}){const[t,n]=j.useState([]),[r,a]=j.useState(!0);if(j.useEffect(()=>{(async()=>{try{const{data:c,error:d}=await q.from("profiles").select("id, name, avatar_url").eq("brokerage_id",s);if(d)throw d;if(!c||c.length===0){n([]),a(!1);return}const u=c.map(x=>x.id),{data:h,error:m}=await q.from("agent_attendance_stats").select("user_id, total_points").in("user_id",u).order("total_points",{ascending:!1});if(m)throw m;const f=new Map(c.map(x=>[x.id,x])),g=(h||[]).filter(x=>x.total_points>0).map(x=>{const y=f.get(x.user_id);return{user_id:x.user_id,total_points:x.total_points,name:(y==null?void 0:y.name)||"Unknown",avatar_url:(y==null?void 0:y.avatar_url)||null}});n(g)}catch(c){console.error("Error fetching leaderboard:",c)}finally{a(!1)}})()},[s]),r)return e.jsxs(Ne,{children:[e.jsx(Ct,{children:e.jsxs(At,{className:"flex items-center gap-2",children:[e.jsx(Kl,{className:"h-5 w-5"}),"Team Leaderboard"]})}),e.jsx(Ie,{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(PE,{className:Pt("h-5 w-5",i(o))}):e.jsx("span",{className:"w-5 text-center text-sm text-muted-foreground",children:o});return e.jsxs(Ne,{children:[e.jsx(Ct,{children:e.jsxs(At,{className:"flex items-center gap-2",children:[e.jsx(Kl,{className:"h-5 w-5 text-primary"}),"Team Leaderboard"]})}),e.jsx(Ie,{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(h=>h[0]).join("").toUpperCase().slice(0,2),u=c+1;return e.jsxs("div",{className:Pt("flex items-center gap-3 p-2 rounded-lg",u<=3&&"bg-muted/50"),children:[e.jsx("div",{className:"w-6 flex justify-center",children:l(u)}),e.jsxs(Oa,{className:"h-8 w-8",children:[e.jsx(Li,{src:o.avatar_url||void 0}),e.jsx(za,{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 ZRn({brokerageId:s}){const t=Qn(),[n,r]=j.useState([]),[a,i]=j.useState(!0);j.useEffect(()=>{(async()=>{try{const{data:c,error:d}=await q.from("profiles").select("id, name, avatar_url").eq("brokerage_id",s);if(d)throw d;if(!c||c.length===0){r([]),i(!1);return}const u=c.map(x=>x.id),h=new Map(c.map(x=>[x.id,x])),{data:m,error:f}=await q.from("listings").select(` id, slug, property_address, city, price, property_type, agent_id, listing_photos(photo_url) `).in("agent_id",u).eq("status","active").order("created_at",{ascending:!1}).limit(6);if(f)throw f;const g=(m||[]).map(x=>({id:x.id,slug:x.slug,property_address:x.property_address,city:x.city,price:x.price,property_type:x.property_type,agent_id:x.agent_id,agent:h.get(x.agent_id)||null,photos:x.listing_photos||[]}));r(g)}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(Ne,{children:[e.jsx(Ct,{children:e.jsxs(At,{className:"flex items-center gap-2",children:[e.jsx(va,{className:"h-5 w-5"}),"Brokerage Listings"]})}),e.jsx(Ie,{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(Ne,{children:[e.jsxs(Ct,{className:"flex flex-row items-center justify-between space-y-0 pb-4",children:[e.jsxs(At,{className:"flex items-center gap-2",children:[e.jsx(va,{className:"h-5 w-5 text-primary"}),"Brokerage Listings"]}),e.jsxs($,{size:"sm",variant:"outline",onClick:()=>t("/mission-control/listings"),className:"gap-1",children:[e.jsx(dn,{className:"h-4 w-4"}),"Add Listing"]})]}),e.jsxs(Ie,{children:[n.length===0?e.jsxs("div",{className:"text-center py-8",children:[e.jsx(va,{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($,{size:"sm",onClick:()=>t("/mission-control/listings/new"),className:"gap-1",children:[e.jsx(dn,{className:"h-4 w-4"}),"Add Your First Listing"]})]}):e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-3",children:n.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(va,{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))}),n.length>0&&e.jsxs($,{variant:"ghost",size:"sm",className:"w-full mt-3",onClick:()=>t("/mission-control/listings"),children:["View All Listings",e.jsx(kr,{className:"h-3 w-3 ml-1"})]})]})]})}const XRn={primary_color:"",secondary_color:"",accent_color:"",logo_url:"",logo_dark_url:"",icon_mark_url:"",heading_font:"",body_font:"",legal_name:"",license_number:"",license_state:"",compliance_line:""};function QRn({brokerageId:s,canManage:t}){const{user:n}=vs(),{toast:r}=Bi(),{data:a,isLoading:i}=Lsn(s),l=Rsn(s),[o,c]=j.useState({...XRn}),[d,u]=j.useState({show_equal_housing:!1,show_realtor_logo:!1,lock_colors:!1,lock_logo:!1}),[h,m]=j.useState(null),f={logo_url:j.useRef(null),logo_dark_url:j.useRef(null),icon_mark_url:j.useRef(null)};j.useEffect(()=>{a&&(c({primary_color:a.primary_color||"",secondary_color:a.secondary_color||"",accent_color:a.accent_color||"",logo_url:a.logo_url||"",logo_dark_url:a.logo_dark_url||"",icon_mark_url:a.icon_mark_url||"",heading_font:a.heading_font||"",body_font:a.body_font||"",legal_name:a.legal_name||"",license_number:a.license_number||"",license_state:a.license_state||"",compliance_line:a.compliance_line||""}),u({show_equal_housing:!!a.show_equal_housing,show_realtor_logo:!!a.show_realtor_logo,lock_colors:!!a.lock_colors,lock_logo:!!a.lock_logo}))},[a]);const g=(b,w)=>c(S=>({...S,[b]:w})),x=async(b,w)=>{if(n){m(b);try{const S=await kHt(n.id,w,`brokerage-${b}`);g(b,S),r({title:"Image uploaded"})}catch(S){r({title:"Upload failed",description:S.message,variant:"destructive"})}finally{m(null)}}},y=async()=>{try{await l.mutateAsync({...Object.fromEntries(Object.entries(o).map(([b,w])=>[b,w||null])),...d}),r({title:"Brokerage brand saved",description:"Agents in this brokerage now inherit these settings."})}catch(b){r({title:"Could not save",description:b.message,variant:"destructive"})}},v=(b,w)=>e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:w}),e.jsxs("div",{className:"flex items-center gap-3",children:[o[b]&&e.jsx("img",{src:o[b],alt:w,className:"h-12 w-auto rounded border bg-background p-1"}),e.jsx("input",{ref:f[b],type:"file",accept:"image/*",className:"hidden",onChange:S=>{var C;return((C=S.target.files)==null?void 0:C[0])&&x(b,S.target.files[0])}}),e.jsxs($,{type:"button",variant:"outline",disabled:!t||h===b,onClick:()=>{var S;return(S=f[b].current)==null?void 0:S.click()},children:[h===b?e.jsx(kt,{className:"h-4 w-4 animate-spin"}):e.jsx(ni,{className:"h-4 w-4"}),e.jsx("span",{className:"ml-2",children:"Upload"})]}),o[b]&&t&&e.jsx($,{type:"button",variant:"ghost",onClick:()=>g(b,""),children:"Remove"})]})]});return e.jsxs(Ne,{children:[e.jsxs(Ct,{children:[e.jsxs(At,{className:"flex items-center gap-2",children:[e.jsx(ji,{className:"h-5 w-5"}),"Brokerage Brand"]}),e.jsx(Gn,{children:t?"Every agent in this brokerage inherits these colors, logos and disclaimer wherever they leave their own brand blank — including AI-generated marketing through the LevelUp connector.":"These are your brokerage brand settings. Only a brokerage manager can change them."})]}),e.jsx(Ie,{className:"space-y-6",children:i?e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground text-sm",children:[e.jsx(kt,{className:"h-4 w-4 animate-spin"})," Loading…"]}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"grid gap-4 sm:grid-cols-3",children:[["primary_color","Primary color","#2a4c64"],["secondary_color","Secondary color","#1c1c1c"],["accent_color","Accent color","#B8965A"]].map(([b,w,S])=>e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:w}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(pe,{type:"color",className:"h-10 w-14 p-1",disabled:!t,value:o[b]||S,onChange:C=>g(b,C.target.value)}),e.jsx(pe,{disabled:!t,value:o[b],placeholder:S,onChange:C=>g(b,C.target.value)})]})]},b))}),e.jsxs("div",{className:"grid gap-4 sm:grid-cols-3",children:[v("logo_url","Logo (light background)"),v("logo_dark_url","Logo (dark background)"),v("icon_mark_url","Icon mark")]}),e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Heading font"}),e.jsx(pe,{disabled:!t,value:o.heading_font,placeholder:"Playfair Display",onChange:b=>g("heading_font",b.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Body font"}),e.jsx(pe,{disabled:!t,value:o.body_font,placeholder:"Inter",onChange:b=>g("body_font",b.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Legal brokerage name"}),e.jsx(pe,{disabled:!t,value:o.legal_name,placeholder:"Acme Realty, Inc.",onChange:b=>g("legal_name",b.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Brokerage license #"}),e.jsx(pe,{disabled:!t,value:o.license_number,placeholder:"DRE #01234567",onChange:b=>g("license_number",b.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"License state"}),e.jsx(pe,{disabled:!t,value:o.license_state,placeholder:"CA",onChange:b=>g("license_state",b.target.value)})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Required disclaimer / compliance line"}),e.jsx(Rs,{disabled:!t,rows:2,value:o.compliance_line,placeholder:"Each office independently owned and operated. Information deemed reliable but not guaranteed.",onChange:b=>g("compliance_line",b.target.value)}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Included in every brand kit so AI-generated marketing carries it automatically."})]}),e.jsx("div",{className:"grid gap-3 sm:grid-cols-2",children:[["show_equal_housing","Include Equal Housing logo"],["show_realtor_logo","Include REALTOR® logo"],["lock_colors","Lock colors (agents cannot override)"],["lock_logo","Lock logo (agents cannot override)"]].map(([b,w])=>e.jsxs("div",{className:"flex items-center justify-between rounded-md border p-3",children:[e.jsx(ee,{className:"text-sm font-normal",children:w}),e.jsx(Sn,{disabled:!t,checked:d[b],onCheckedChange:S=>u(C=>({...C,[b]:S}))})]},b))}),t&&e.jsxs($,{onClick:y,disabled:l.isPending,children:[l.isPending?e.jsx(kt,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(tl,{className:"mr-2 h-4 w-4"}),"Save brokerage brand"]})]})})]})}const $Xt="brokerage-onboarding-docs",mE=s=>s.status==="approved"||s.status==="complete";function UXt(s){return tt({queryKey:["onboarding-templates",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await q.from("brokerage_onboarding_templates").select("*").eq("brokerage_id",s).eq("is_archived",!1).order("created_at",{ascending:!0});if(n)throw n;return t||[]}})}function JRn(s){return tt({queryKey:["onboarding-template-steps",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await q.from("brokerage_onboarding_template_steps").select("*").eq("template_id",s).order("sort_order",{ascending:!0});if(n)throw n;return t||[]}})}function qXt(s){return tt({queryKey:["onboarding-roster",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await q.from("profiles").select("id, name, email, avatar_url, created_at").eq("brokerage_id",s).order("name",{ascending:!0});if(n)throw n;const{data:r,error:a}=await q.from("brokerage_onboarding_assignments").select("*").eq("brokerage_id",s);if(a)throw a;const i=(r||[]).map(c=>c.id);let l=[];if(i.length){const{data:c,error:d}=await q.from("brokerage_onboarding_steps").select("*").in("assignment_id",i);if(d)throw d;l=c||[]}const o=new Date().toISOString().slice(0,10);return(t||[]).map(c=>{const d=(r||[]).find(h=>h.agent_user_id===c.id)||null,u=d?l.filter(h=>h.assignment_id===d.id):[];return{agentId:c.id,name:c.name||c.email,email:c.email,avatarUrl:c.avatar_url||null,joinedAt:c.created_at||null,assignment:d,total:u.length,done:u.filter(mE).length,overdue:u.filter(h=>!mE(h)&&h.due_date&&h.due_dateh.status==="submitted").length}})}})}function VXt(s){return tt({queryKey:["onboarding-detail",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await q.from("brokerage_onboarding_steps").select("*").eq("assignment_id",s).order("sort_order",{ascending:!0});if(n)throw n;const r=(t||[]).map(i=>i.id);let a=[];if(r.length){const{data:i,error:l}=await q.from("brokerage_onboarding_documents").select("*").in("step_id",r).order("version",{ascending:!1});if(l)throw l;a=i||[]}return{steps:t||[],documents:a}}})}function eDn(s){return tt({queryKey:["my-onboarding",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await q.from("brokerage_onboarding_assignments").select("*").eq("agent_user_id",s).maybeSingle();if(n)throw n;return t||null}})}function tDn(s,t){return tt({queryKey:["agent-record",s,t],enabled:!!s&&!!t,queryFn:async()=>{const{data:n,error:r}=await q.from("brokerage_agent_records").select("*").eq("brokerage_id",s).eq("agent_user_id",t).maybeSingle();if(r)throw r;return n||null}})}function sDn(s,t){return tt({queryKey:["agent-notes",s,t],enabled:!!s&&!!t,queryFn:async()=>{const{data:n,error:r}=await q.from("brokerage_agent_notes").select("*").eq("brokerage_id",s).eq("agent_user_id",t).order("created_at",{ascending:!1});if(r)throw r;return n||[]}})}function HXt(s,t){return tt({queryKey:["agent-activity",s,t],enabled:!!s&&!!t,queryFn:async()=>{const{data:n,error:r}=await q.from("brokerage_onboarding_activity").select("*").eq("brokerage_id",s).eq("agent_user_id",t).order("created_at",{ascending:!1}).limit(100);if(r)throw r;return n||[]}})}async function sue(s){const{data:t}=await q.auth.getUser();t.user&&await q.from("brokerage_onboarding_activity").insert({brokerage_id:s.brokerageId,agent_user_id:s.agentUserId,actor_id:t.user.id,event_type:s.eventType,description:s.description})}function nDe(s){const t=Vt(),n=(h,m)=>{t.invalidateQueries({queryKey:["onboarding-roster",s]}),m&&t.invalidateQueries({queryKey:["onboarding-detail",m]}),h&&(t.invalidateQueries({queryKey:["agent-activity",s,h]}),t.invalidateQueries({queryKey:["my-onboarding",h]}))},r=ft({mutationFn:async({agentUserId:h,templateId:m})=>{var S;const{data:f}=await q.auth.getUser(),{data:g,error:x}=await q.from("brokerage_onboarding_templates").select("id, name").eq("id",m).single();if(x)throw x;const{data:y,error:v}=await q.from("brokerage_onboarding_template_steps").select("*").eq("template_id",m).order("sort_order",{ascending:!0});if(v)throw v;const{data:b,error:w}=await q.from("brokerage_onboarding_assignments").insert({brokerage_id:s,agent_user_id:h,template_id:m,template_name:g.name,status:"in_progress",created_by:((S=f.user)==null?void 0:S.id)??null}).select().single();if(w)throw w;if(y!=null&&y.length){const C=new Date,E=y.map(P=>{let R=null;if(P.due_days!=null){const D=new Date(C);D.setDate(D.getDate()+P.due_days),R=D.toISOString().slice(0,10)}return{assignment_id:b.id,title:P.title,description:P.description,step_type:P.step_type,assignee:P.assignee,form_template_id:P.form_template_id,external_url:P.external_url,due_date:R,sort_order:P.sort_order}}),{error:I}=await q.from("brokerage_onboarding_steps").insert(E);if(I)throw I}return await sue({brokerageId:s,agentUserId:h,eventType:"onboarding_started",description:`Onboarding started using "${g.name}"`}),b},onSuccess:h=>n(h.agent_user_id,h.id)}),a=ft({mutationFn:async h=>{const{error:m}=await q.from("brokerage_onboarding_assignments").delete().eq("id",h.id);if(m)throw m;return h},onSuccess:h=>n(h.agent_user_id,h.id)}),i=ft({mutationFn:async({step:h,status:m,note:f,agentUserId:g})=>{var b;const{data:x}=await q.auth.getUser(),y=m==="approved"||m==="complete",{error:v}=await q.from("brokerage_onboarding_steps").update({status:m,review_note:f??null,completed_at:y?new Date().toISOString():null,completed_by:y?((b=x.user)==null?void 0:b.id)??null:null}).eq("id",h.id);if(v)throw v;return s&&await sue({brokerageId:s,agentUserId:g,eventType:`step_${m}`,description:`"${h.title}" marked ${m.replace("_"," ")}`}),{step:h,agentUserId:g}},onSuccess:({step:h,agentUserId:m})=>n(m,h.assignment_id)}),l=ft({mutationFn:async({step:h,file:m,agentUserId:f,existingVersions:g})=>{var S;const{data:x}=await q.auth.getUser(),y=m.name.replace(/[^a-zA-Z0-9._-]/g,"_"),v=`${s}/${f}/${h.id}/${Date.now()}-${y}`,{error:b}=await q.storage.from($Xt).upload(v,m,{upsert:!1,contentType:m.type||void 0});if(b)throw b;const{error:w}=await q.from("brokerage_onboarding_documents").insert({step_id:h.id,storage_path:v,file_name:m.name,file_size:m.size,file_type:m.type,version:g+1,uploaded_by:((S=x.user)==null?void 0:S.id)??null,review_status:"submitted"});if(w)throw w;return await q.from("brokerage_onboarding_steps").update({status:"submitted",review_note:null}).eq("id",h.id),s&&await sue({brokerageId:s,agentUserId:f,eventType:"document_uploaded",description:`Document uploaded for "${h.title}"`}),{step:h,agentUserId:f}},onSuccess:({step:h,agentUserId:m})=>n(m,h.assignment_id)}),o=ft({mutationFn:async({doc:h,step:m,status:f,note:g,agentUserId:x})=>{var w;const{data:y}=await q.auth.getUser(),{error:v}=await q.from("brokerage_onboarding_documents").update({review_status:f,review_note:g??null,reviewed_by:((w=y.user)==null?void 0:w.id)??null,reviewed_at:new Date().toISOString()}).eq("id",h.id);if(v)throw v;const b=f==="approved"?"approved":f==="changes_requested"?"changes_requested":"submitted";return await q.from("brokerage_onboarding_steps").update({status:b,review_note:g??null,completed_at:f==="approved"?new Date().toISOString():null}).eq("id",m.id),s&&await sue({brokerageId:s,agentUserId:x,eventType:`document_${f}`,description:`${h.file_name} ${f==="approved"?"approved":f==="changes_requested"?"needs changes":"approval revoked"}`}),{step:m,agentUserId:x}},onSuccess:({step:h,agentUserId:m})=>n(m,h.assignment_id)}),c=ft({mutationFn:async h=>{const{error:m}=await q.from("brokerage_agent_records").upsert(h,{onConflict:"brokerage_id,agent_user_id"});if(m)throw m;return h},onSuccess:h=>{t.invalidateQueries({queryKey:["agent-record",h.brokerage_id,h.agent_user_id]})}}),d=ft({mutationFn:async({agentUserId:h,body:m})=>{const{data:f}=await q.auth.getUser(),{error:g}=await q.from("brokerage_agent_notes").insert({brokerage_id:s,agent_user_id:h,body:m,author_id:f.user.id});if(g)throw g;return h},onSuccess:h=>{t.invalidateQueries({queryKey:["agent-notes",s,h]})}}),u=ft({mutationFn:async({id:h,agentUserId:m})=>{const{error:f}=await q.from("brokerage_agent_notes").delete().eq("id",h);if(f)throw f;return m},onSuccess:h=>{t.invalidateQueries({queryKey:["agent-notes",s,h]})}});return{assignTemplate:r,removeAssignment:a,setStepStatus:i,uploadDocument:l,reviewDocument:o,saveRecord:c,addNote:d,deleteNote:u}}function nDn(s){const t=Vt(),n=d=>{t.invalidateQueries({queryKey:["onboarding-templates",s]}),d&&t.invalidateQueries({queryKey:["onboarding-template-steps",d]})},r=ft({mutationFn:async({name:d,description:u})=>{var g;const{data:h}=await q.auth.getUser(),{data:m,error:f}=await q.from("brokerage_onboarding_templates").insert({brokerage_id:s,name:d,description:u||null,created_by:((g=h.user)==null?void 0:g.id)??null}).select().single();if(f)throw f;return m},onSuccess:()=>n()}),a=ft({mutationFn:async({id:d,...u})=>{const{error:h}=await q.from("brokerage_onboarding_templates").update(u).eq("id",d);if(h)throw h;return d},onSuccess:()=>n()}),i=ft({mutationFn:async d=>{const{error:u}=await q.from("brokerage_onboarding_templates").delete().eq("id",d);if(u)throw u;return d},onSuccess:()=>n()}),l=ft({mutationFn:async d=>{if(d.id){const{error:u}=await q.from("brokerage_onboarding_template_steps").update(d).eq("id",d.id);if(u)throw u}else{const{error:u}=await q.from("brokerage_onboarding_template_steps").insert(d);if(u)throw u}return d.template_id},onSuccess:d=>n(d)}),o=ft({mutationFn:async({id:d,templateId:u})=>{const{error:h}=await q.from("brokerage_onboarding_template_steps").delete().eq("id",d);if(h)throw h;return u},onSuccess:d=>n(d)}),c=ft({mutationFn:async({steps:d,templateId:u})=>{for(let h=0;hn(d)});return{createTemplate:r,updateTemplate:a,deleteTemplate:i,upsertStep:l,deleteStep:o,reorderSteps:c}}async function rDn(s){const{data:t,error:n}=await q.storage.from($Xt).createSignedUrl(s,300);if(n)throw n;return t.signedUrl}const aDn=s=>s==="document"?Jr:s==="form"?m_:Kj,iDn=s=>{switch(s.status){case"approved":return{label:"Approved",className:"bg-emerald-500/15 text-emerald-600 border-emerald-500/30"};case"complete":return{label:"Complete",className:"bg-emerald-500/15 text-emerald-600 border-emerald-500/30"};case"submitted":return{label:"In review",className:"bg-amber-500/15 text-amber-600 border-amber-500/30"};case"changes_requested":return{label:"Needs changes",className:"bg-destructive/10 text-destructive border-destructive/30"};default:return{label:"Pending",className:"bg-muted text-muted-foreground border-border"}}},NYe=({brokerageId:s,agentUserId:t,steps:n,documents:r,mode:a,displayMode:i="all"})=>{const{toast:l}=Bi(),{setStepStatus:o,uploadDocument:c,reviewDocument:d}=nDe(s),u=j.useRef({}),[h,m]=j.useState(null),[f,g]=j.useState(""),x=new Date().toISOString().slice(0,10),y=w=>r.filter(S=>S.step_id===w).sort((S,C)=>C.version-S.version),v=async(w,S)=>{try{await c.mutateAsync({step:w,file:S,agentUserId:t,existingVersions:y(w.id).length}),l({title:"Uploaded",description:`${S.name} is ready for review.`})}catch(C){l({title:"Upload failed",description:C.message,variant:"destructive"})}},b=async w=>{try{const S=await rDn(w);window.open(S,"_blank","noopener,noreferrer")}catch(S){l({title:"Could not open file",description:S.message,variant:"destructive"})}};return e.jsxs("div",{className:"space-y-3",children:[n.filter(w=>i==="all"||w.step_type!=="task").length===0&&e.jsx("p",{className:"py-10 text-center text-sm text-muted-foreground",children:"No steps in this checklist yet."}),n.filter(w=>i==="all"||w.step_type!=="task").map(w=>{const S=aDn(w.step_type),C=iDn(w),E=y(w.id),I=E[0],P=!mE(w)&&w.due_date&&w.due_date0&&e.jsx("div",{className:"mt-3 space-y-1",children:E.map(D=>e.jsxs("div",{className:"flex flex-wrap items-center gap-2 rounded-md bg-muted/50 px-3 py-2 text-sm",children:[e.jsx(Jr,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"min-w-0 flex-1 truncate",children:D.file_name}),e.jsxs(Be,{variant:"outline",className:"capitalize",children:["v",D.version," · ",D.review_status.replace("_"," ")]}),e.jsxs($,{size:"sm",variant:"ghost",onClick:()=>b(D.storage_path),children:[e.jsx(di,{className:"mr-1 h-4 w-4"})," Open"]})]},D.id))})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[w.step_type!=="task"&&R&&e.jsxs(e.Fragment,{children:[e.jsx("input",{type:"file",className:"hidden",accept:".pdf,.png,.jpg,.jpeg,.heic,.doc,.docx",ref:D=>u.current[w.id]=D,onChange:D=>{var U;const O=(U=D.target.files)==null?void 0:U[0];O&&v(w,O),D.target.value=""}}),e.jsxs($,{size:"sm",variant:"outline",onClick:()=>{var D;return(D=u.current[w.id])==null?void 0:D.click()},children:[e.jsx(ni,{className:"mr-1 h-4 w-4"})," Upload"]})]}),w.step_type==="task"&&R&&!mE(w)&&e.jsxs($,{size:"sm",onClick:()=>o.mutate({step:w,status:"complete",agentUserId:t}),children:[e.jsx(Kj,{className:"mr-1 h-4 w-4"})," Complete"]}),a==="manager"&&I&&I.review_status!=="approved"&&e.jsxs(e.Fragment,{children:[e.jsxs($,{size:"sm",onClick:()=>d.mutate({doc:I,step:w,status:"approved",agentUserId:t}),children:[e.jsx(qr,{className:"mr-1 h-4 w-4"})," Approve"]}),e.jsxs($,{size:"sm",variant:"outline",onClick:()=>{m({step:w,doc:I}),g("")},children:[e.jsx(ku,{className:"mr-1 h-4 w-4"})," Needs changes"]})]}),a==="manager"&&mE(w)&&e.jsxs($,{size:"sm",variant:"ghost",onClick:()=>I?d.mutate({doc:I,step:w,status:"submitted",agentUserId:t}):o.mutate({step:w,status:"pending",agentUserId:t}),children:[e.jsx(Ex,{className:"mr-1 h-4 w-4"})," Revoke"]})]})]})},w.id)}),e.jsx(zs,{open:!!h,onOpenChange:w=>!w&&m(null),children:e.jsxs(Os,{children:[e.jsx(Us,{children:e.jsx(Bs,{children:"Request changes"})}),e.jsx(Rs,{rows:4,value:f,onChange:w=>g(w.target.value),placeholder:"Tell the agent what needs to be fixed…"}),e.jsxs(Ar,{children:[e.jsx($,{variant:"outline",onClick:()=>m(null),children:"Cancel"}),e.jsx($,{onClick:async()=>{h&&(await d.mutateAsync({doc:h.doc,step:h.step,status:"changes_requested",note:f,agentUserId:t}),m(null))},children:"Send back"})]})]})})]})},oDn=()=>{const{user:s}=vs(),{data:t}=eDn(s==null?void 0:s.id),{data:n}=VXt(t==null?void 0:t.id);if(!t)return null;const r=(n==null?void 0:n.steps)||[],a=r.filter(mE).length,i=r.length?Math.round(a/r.length*100):0;return e.jsxs(Ne,{children:[e.jsx(Ct,{children:e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(JN,{className:"h-5 w-5 text-primary"}),e.jsxs("div",{children:[e.jsx(At,{children:"Your onboarding"}),e.jsx(Gn,{children:t.template_name||"Onboarding checklist"})]})]}),e.jsxs("div",{className:"w-full max-w-[220px]",children:[e.jsx(Yi,{value:i}),e.jsxs("p",{className:"mt-1 text-right text-xs text-muted-foreground",children:[a," of ",r.length," complete"]})]})]})}),e.jsx(Ie,{children:e.jsx(NYe,{brokerageId:t.brokerage_id,agentUserId:t.agent_user_id,steps:r,documents:(n==null?void 0:n.documents)||[],mode:"agent"})})]})};function lDn(){const{user:s,isAdmin:t,isBrokerageManager:n}=vs(),r=Qn(),[a,i]=j.useState(!0),[l,o]=j.useState(null),[c,d]=j.useState(""),[u,h]=j.useState(0),[m,f]=j.useState(!1),[g,x]=j.useState(!1);return j.useEffect(()=>{(async()=>{if(s)try{const{data:v}=await q.from("profiles").select("brokerage_id").eq("id",s.id).maybeSingle();if(!(v!=null&&v.brokerage_id)){i(!1);return}o(v.brokerage_id);const{data:b}=await q.from("brokerages").select("name").eq("id",v.brokerage_id).maybeSingle();b&&d(b.name);const{count:w}=await q.from("profiles").select("id",{count:"exact",head:!0}).eq("brokerage_id",v.brokerage_id);if(h(w||0),t)f(!0),x(!0);else if(n){const{data:S}=await q.from("brokerage_manager_assignments").select("id").eq("user_id",s.id).eq("brokerage_id",v.brokerage_id).maybeSingle();f(!!S),x(!!S)}}catch(v){console.error("Error fetching brokerage info:",v)}finally{i(!1)}})()},[s,t,n]),a?e.jsx(Vs,{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(Vs,{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(Zn,{className:"h-5 w-5 text-primary"}),e.jsxs("span",{className:"font-medium",children:[u," ",u===1?"Agent":"Agents"]})]}),g&&e.jsxs("div",{className:"flex gap-2",children:[e.jsxs($,{variant:"outline",onClick:()=>r("/brokerage-content"),children:[e.jsx(Xf,{className:"h-4 w-4 mr-2"}),"Brokerage Content"]}),e.jsxs($,{onClick:()=>r(`/mission-control/listings/new?brokerage=${l}`),children:[e.jsx(va,{className:"h-4 w-4 mr-2"}),"Add Listing"]})]})]}),e.jsx(oDn,{}),e.jsx(QRn,{brokerageId:l,canManage:m}),e.jsx(GRn,{brokerageId:l,canManage:m}),e.jsx(WRn,{brokerageId:l,canManage:m}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-8",children:[e.jsx(YRn,{brokerageId:l}),e.jsx(ZRn,{brokerageId:l})]})]})}):e.jsx(Vs,{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(ji,{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 cDn(s){if(!s)return null;try{const t=new URL(s),n=t.hostname.replace("www.","");let r=null;if(n==="youtube.com"||n==="m.youtube.com"?r=t.searchParams.get("v"):n==="youtu.be"&&(r=t.pathname.slice(1)),r)return`https://img.youtube.com/vi/${r}/hqdefault.jpg`}catch{}return null}function dDn(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 rSt={video:{icon:Bu,label:"Video",color:"bg-red-500/10 text-red-600 dark:text-red-400"},pdf:{icon:Jr,label:"Document",color:"bg-blue-500/10 text-blue-600 dark:text-blue-400"},link:{icon:bd,label:"Link",color:"bg-green-500/10 text-green-600 dark:text-green-400"},event:{icon:Ta,label:"Event",color:"bg-purple-500/10 text-purple-600 dark:text-purple-400"},graphic:{icon:Yc,label:"Graphic",color:"bg-amber-500/10 text-amber-600 dark:text-amber-400"}};function uDn({item:s,canManage:t}){const[n,r]=j.useState(!1),[a,i]=j.useState(null),l=TWs(),o=Qn(),c=rSt[s.content_type]||rSt.link,d=c.icon,u=j.useMemo(()=>s.thumbnail_url?s.thumbnail_url:s.content_type==="graphic"&&s.file_url?s.file_url:s.content_type==="video"?cDn(s.url):null,[s]);j.useEffect(()=>{u||!s.url||s.content_type!=="video"||!dDn(s.url)||fetch(`https://www.youtube.com/oembed?url=${encodeURIComponent(s.url)}&format=json`).then(g=>g.ok?g.json():null).then(g=>{g!=null&&g.thumbnail_url&&i(g.thumbnail_url)}).catch(()=>{})},[s.url,s.content_type,u]);const h=u||a,m=()=>{o(`/brokerage-content/${s.id}`)},f=async()=>{try{await l.mutateAsync(s.id),re.success("Content deleted")}catch{re.error("Failed to delete")}r(!1)};return e.jsxs(e.Fragment,{children:[e.jsxs(Ne,{className:"group overflow-hidden transition-all duration-200 hover:shadow-lg hover:border-primary/30 cursor-pointer",onClick:m,children:[h?e.jsx("div",{className:"aspect-video bg-muted/50 overflow-hidden",children:e.jsx("img",{src:h,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(Ie,{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(Be,{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(Be,{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:["📅 ",en(new Date(s.event_date),"MMM d, yyyy · h:mm a")]}),e.jsxs("p",{className:"text-[10px] text-muted-foreground mt-2",children:["Added ",en(new Date(s.created_at),"MMM d, yyyy")]})]}),t&&e.jsxs(Uu,{children:[e.jsx(qu,{asChild:!0,onClick:g=>g.stopPropagation(),children:e.jsx($,{variant:"ghost",size:"icon",className:"h-7 w-7 shrink-0",children:e.jsx(ty,{className:"h-4 w-4"})})}),e.jsx(Eu,{align:"end",children:e.jsxs(ja,{onClick:g=>{g.stopPropagation(),r(!0)},className:"text-destructive",children:[e.jsx(Wn,{className:"h-4 w-4 mr-2"}),"Delete"]})})]})]})})]}),e.jsx(kc,{open:n,onOpenChange:r,children:e.jsxs(cc,{children:[e.jsxs(dc,{children:[e.jsx(hc,{children:"Delete Content"}),e.jsxs(mc,{children:['Are you sure you want to delete "',s.title,'"? This cannot be undone.']})]}),e.jsxs(uc,{children:[e.jsx(fc,{children:"Cancel"}),e.jsx(tc,{onClick:f,className:"bg-destructive text-destructive-foreground",children:"Delete"})]})]})})]})}function hDn(s){try{const t=new URL(s),n=t.hostname.replace("www.","");let r=null;if(n==="youtube.com"||n==="m.youtube.com"?r=t.searchParams.get("v"):n==="youtu.be"&&(r=t.pathname.slice(1)),r)return`https://img.youtube.com/vi/${r}/hqdefault.jpg`}catch{}return null}const aSt=[{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 mDn({brokerageId:s,categories:t}){var J;const{user:n}=vs(),[r,a]=j.useState(!1),[i,l]=j.useState(!1),[o,c]=j.useState(""),[d,u]=j.useState("📁"),[h,m]=j.useState(!1);j.useRef(null);const[f,g]=j.useState("video"),[x,y]=j.useState(""),[v,b]=j.useState(""),[w,S]=j.useState(""),[C,E]=j.useState(""),[I,P]=j.useState(""),[R,D]=j.useState(""),[O,U]=j.useState(""),W=EWs(),V=MWs(s),G=PWs(),Y=IWs(s),X=()=>{g("video"),y(""),b(""),S(""),E(""),P(""),D(""),U("")},ae=async(ce,_e)=>{var ue;const he=(ue=ce.target.files)==null?void 0:ue[0];if(he){m(!0);try{const ve=he.name.split(".").pop(),Ee=`${s}/${Date.now()}-${Math.random().toString(36).slice(2)}.${ve}`,{error:Se}=await q.storage.from("brokerage-content").upload(Ee,he);if(Se)throw Se;const{data:{publicUrl:Le}}=q.storage.from("brokerage-content").getPublicUrl(Ee);_e==="file"?(E(Le),f==="graphic"&&!I&&P(Le)):P(Le),re.success("File uploaded")}catch(ve){re.error(ve.message||"Upload failed")}finally{m(!1)}}},ie=async()=>{if(!x.trim()){re.error("Title is required");return}if(n)try{await W.mutateAsync({brokerage_id:s,category_id:O||null,content_type:f,title:x.trim(),description:v.trim()||null,url:w.trim()||null,file_url:C.trim()||null,thumbnail_url:I.trim()||null,event_date:R?new Date(R).toISOString():null,created_by:n.id}),re.success("Content added!"),X(),a(!1)}catch(ce){re.error(ce.message||"Failed to add content")}},ne=async()=>{if(o.trim())try{await V.mutateAsync({name:o.trim(),icon:d,sort_order:t.length}),c(""),u("📁"),re.success("Category created")}catch(ce){re.error(ce.message||"Failed to create category")}},te=async()=>{try{await Y.mutateAsync(),re.success("Default categories created")}catch{re.error("Failed to create defaults")}};return e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsxs(zs,{open:r,onOpenChange:a,children:[e.jsx(jl,{asChild:!0,children:e.jsxs($,{children:[e.jsx(dn,{className:"h-4 w-4 mr-2"}),"Add Content"]})}),e.jsxs(Os,{className:"max-w-lg max-h-[90vh] overflow-y-auto",children:[e.jsx(Us,{children:e.jsx(Bs,{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(ee,{children:"Content Type"}),e.jsxs(ms,{value:f,onValueChange:g,children:[e.jsx(us,{children:e.jsx(fs,{})}),e.jsx(hs,{children:aSt.map(ce=>e.jsx(Ge,{value:ce.value,children:ce.label},ce.value))})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:(J=aSt.find(ce=>ce.value===f))==null?void 0:J.hint})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Category"}),e.jsxs(ms,{value:O,onValueChange:U,children:[e.jsx(us,{children:e.jsx(fs,{placeholder:"Select category (optional)"})}),e.jsx(hs,{children:t.map(ce=>e.jsxs(Ge,{value:ce.id,children:[ce.icon," ",ce.name]},ce.id))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Title *"}),e.jsx(pe,{value:x,onChange:ce=>y(ce.target.value),placeholder:"Content title"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Description"}),e.jsx(Rs,{value:v,onChange:ce=>b(ce.target.value),placeholder:"Brief description...",rows:2})]}),["video","link","graphic","event"].includes(f)&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:f==="video"?"Video URL":f==="graphic"?"Canva / Image URL":f==="event"?"Event Link (Zoom, etc.)":"URL"}),e.jsx(pe,{value:w,onChange:ce=>{const _e=ce.target.value;if(S(_e),f==="video"&&!I){const he=hDn(_e);he&&P(he)}},placeholder:"https://..."})]}),["pdf","graphic"].includes(f)&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:f==="pdf"?"Upload PDF":"Upload Image"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(pe,{type:"file",accept:f==="pdf"?".pdf,.doc,.docx":"image/*",onChange:ce=>ae(ce,"file"),disabled:h}),h&&e.jsx(kt,{className:"h-4 w-4 animate-spin"})]}),C&&e.jsx("p",{className:"text-xs text-green-600",children:"✓ File uploaded"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Thumbnail Image (optional)"}),e.jsx(pe,{type:"file",accept:"image/*",onChange:ce=>ae(ce,"thumbnail"),disabled:h}),I&&e.jsxs("div",{className:"relative w-20 h-20 rounded overflow-hidden",children:[e.jsx("img",{src:I,className:"w-full h-full object-cover",alt:"thumb"}),e.jsx("button",{onClick:()=>P(""),className:"absolute top-0 right-0 bg-background/80 rounded-bl p-0.5",children:e.jsx(gr,{className:"h-3 w-3"})})]})]}),f==="event"&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Event Date & Time"}),e.jsx(pe,{type:"datetime-local",value:R,onChange:ce=>D(ce.target.value)})]}),e.jsxs($,{onClick:ie,disabled:W.isPending||!x.trim(),className:"w-full",children:[W.isPending?e.jsx(kt,{className:"h-4 w-4 animate-spin mr-2"}):e.jsx(dn,{className:"h-4 w-4 mr-2"}),"Add Content"]})]})]})]}),e.jsxs(zs,{open:i,onOpenChange:l,children:[e.jsx(jl,{asChild:!0,children:e.jsxs($,{variant:"outline",size:"sm",children:[e.jsx(Sd,{className:"h-4 w-4 mr-2"}),"Categories"]})}),e.jsxs(Os,{className:"max-w-md",children:[e.jsx(Us,{children:e.jsx(Bs,{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($,{variant:"outline",size:"sm",onClick:te,disabled:Y.isPending,children:[Y.isPending?e.jsx(kt,{className:"h-4 w-4 animate-spin mr-2"}):null,"Create Default Categories"]})]}),t.map(ce=>e.jsxs("div",{className:"flex items-center justify-between p-2 rounded-lg border",children:[e.jsxs("span",{className:"text-sm",children:[ce.icon," ",ce.name]}),!ce.is_default&&e.jsx($,{variant:"ghost",size:"icon",className:"h-7 w-7 text-destructive",onClick:async()=>{await G.mutateAsync(ce.id),re.success("Category deleted")},children:e.jsx(gr,{className:"h-4 w-4"})})]},ce.id)),e.jsxs("div",{className:"flex gap-2 pt-2 border-t",children:[e.jsx(pe,{value:d,onChange:ce=>u(ce.target.value),className:"w-14 text-center",maxLength:2}),e.jsx(pe,{value:o,onChange:ce=>c(ce.target.value),placeholder:"New category name",className:"flex-1",onKeyDown:ce=>ce.key==="Enter"&&ne()}),e.jsx($,{size:"sm",onClick:ne,disabled:!o.trim(),children:"Add"})]})]})]})]})]})}function fDn(){const{user:s,isAdmin:t,isBrokerageManager:n}=vs(),[r,a]=j.useState(!0),[i,l]=j.useState(null),[o,c]=j.useState(""),[d,u]=j.useState(!1),[h,m]=j.useState(null),[f,g]=j.useState("");j.useEffect(()=>{(async()=>{if(s)try{const{data:S}=await q.from("profiles").select("brokerage_id").eq("id",s.id).maybeSingle();if(!(S!=null&&S.brokerage_id)){a(!1);return}l(S.brokerage_id);const{data:C}=await q.from("brokerages").select("name").eq("id",S.brokerage_id).maybeSingle();if(C&&c(C.name),t)u(!0);else if(n){const{data:E}=await q.from("brokerage_manager_assignments").select("id").eq("user_id",s.id).eq("brokerage_id",S.brokerage_id).maybeSingle();u(!!E)}}catch(S){console.error("Error fetching brokerage info:",S)}finally{a(!1)}})()},[s,t,n]);const{data:x=[]}=SWs(i),{data:y=[],isLoading:v}=CWs(i,h),b=j.useMemo(()=>{if(!f.trim())return y;const w=f.toLowerCase();return y.filter(S=>{var C;return S.title.toLowerCase().includes(w)||((C=S.description)==null?void 0:C.toLowerCase().includes(w))||S.content_type.toLowerCase().includes(w)})},[y,f]);return r?e.jsx(Vs,{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(Vs,{title:`${o} Content`,description:"Brokerage Content Hub",children:e.jsxs("div",{className:"space-y-6",children:[d&&i&&e.jsx(mDn,{brokerageId:i,categories:x}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"relative max-w-sm",children:[e.jsx(Kr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(pe,{placeholder:"Search content...",value:f,onChange:w=>g(w.target.value),className:"pl-9"})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx($,{variant:h===null?"default":"outline",size:"sm",onClick:()=>m(null),children:"All"}),x.map(w=>e.jsxs($,{variant:h===w.id?"default":"outline",size:"sm",onClick:()=>m(w.id),children:[e.jsx("span",{className:"mr-1",children:w.icon}),w.name]},w.id))]})]}),v?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"})}):b.length===0?e.jsx(Ne,{className:"bg-muted/30 border-dashed",children:e.jsxs(Ie,{className:"flex flex-col items-center justify-center py-12",children:[e.jsx(_b,{className:"h-12 w-12 text-muted-foreground/50 mb-3"}),e.jsx("p",{className:"text-muted-foreground font-medium",children:f.trim()?"No matching content found":"No content yet"}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:f.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:b.map(w=>e.jsx(uDn,{item:w,canManage:d},w.id))})]})}):e.jsx(Vs,{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(ji,{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 iSt={video:{icon:Bu,label:"Video",color:"bg-red-500/10 text-red-600 dark:text-red-400"},pdf:{icon:Jr,label:"Document",color:"bg-blue-500/10 text-blue-600 dark:text-blue-400"},link:{icon:bd,label:"Link",color:"bg-green-500/10 text-green-600 dark:text-green-400"},event:{icon:Ta,label:"Event",color:"bg-purple-500/10 text-purple-600 dark:text-purple-400"},graphic:{icon:Yc,label:"Graphic",color:"bg-amber-500/10 text-amber-600 dark:text-amber-400"}};function pDn(s){try{const t=new URL(s),n=t.hostname.replace("www.","");if(t.pathname==="/playlist"){const r=t.searchParams.get("list");if(r)return`https://www.youtube.com/embed/videoseries?list=${r}`}if(n==="youtube.com"||n==="m.youtube.com"){const r=t.searchParams.get("v");if(r){const a=t.searchParams.get("list");let i=`https://www.youtube.com/embed/${r}`;return a&&(i+=`?list=${a}`),i}}if(n==="youtu.be"){const r=t.pathname.slice(1);if(r){const a=t.searchParams.get("list");let i=`https://www.youtube.com/embed/${r}`;return a&&(i+=`?list=${a}`),i}}if(n==="youtube.com"&&t.pathname.startsWith("/embed/"))return s}catch{}return null}function gDn(s){try{const t=new URL(s).hostname.replace("www.","");return["youtube.com","youtu.be","m.youtube.com"].includes(t)}catch{return!1}}function xDn(s){try{return new URL(s).hostname.includes("vimeo.com")}catch{return!1}}function yDn(s){try{const t=s.match(/vimeo\.com\/(\d+)/);if(t)return`https://player.vimeo.com/video/${t[1]}`}catch{}return null}function vDn(){const{contentId:s}=Wi(),{data:t,isLoading:n}=tt({queryKey:["brokerage-content-detail",s],queryFn:async()=>{const{data:d,error:u}=await q.from("brokerage_content").select(` *, category:brokerage_content_categories(*) `).eq("id",s).single();if(u)throw u;return d},enabled:!!s});if(n)return e.jsx(Vs,{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(Vs,{title:"Brokerage Content",children:e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(ji,{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($,{asChild:!0,className:"mt-4",children:e.jsx(wr,{to:"/brokerage-content",children:"Back to Content"})})]})});const r=iSt[t.content_type]||iSt.link,a=r.icon,i=t.url||t.file_url,l=i&&gDn(i)?pDn(i):null,o=i&&xDn(i)?yDn(i):null,c=l||o;return e.jsx(Vs,{title:t.title,children:e.jsxs("div",{className:"space-y-6 max-w-4xl mx-auto",children:[e.jsx($,{variant:"ghost",size:"sm",asChild:!0,className:"gap-2",children:e.jsxs(wr,{to:"/brokerage-content",children:[e.jsx(qa,{className:"h-4 w-4"}),"Back to Content"]})}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(Be,{variant:"secondary",className:`text-xs px-2 py-0.5 ${r.color}`,children:[e.jsx(a,{className:"h-3 w-3 mr-1"}),r.label]}),t.category&&e.jsxs(Be,{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 ",en(new Date(t.created_at),"MMMM d, yyyy")]})]}),e.jsx("h1",{className:"text-2xl font-bold text-foreground",children:t.title}),c&&e.jsx(Ne,{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(Ne,{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(Ne,{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(Ne,{children:e.jsx(Ie,{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(Ne,{children:e.jsxs(Ie,{className:"pt-6 flex items-center gap-3",children:[e.jsx("div",{className:"p-2 rounded-md bg-primary/10",children:e.jsx(Ta,{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:en(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($,{asChild:!0,size:"lg",children:e.jsxs("a",{href:t.file_url,target:"_blank",rel:"noopener noreferrer",children:[e.jsx(di,{className:"h-4 w-4 mr-2"}),t.content_type==="pdf"?"Download Document":"Download File"]})}),t.url&&e.jsx($,{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(kr,{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 ZMe={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 bDn(s="open"){const{user:t}=vs();return tt({queryKey:["brokerage-help-requests",s,t==null?void 0:t.id],queryFn:async()=>{if(!t)return[];let n=q.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")n=n.eq("status","open");else if(s==="mine")n=n.eq("requester_user_id",t.id);else if(s==="filled")n=n.in("status",["filled","completed"]);else if(s==="my_claims"){const{data:i}=await q.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[];n=n.in("id",l)}const{data:r,error:a}=await n;if(a)throw a;return r},enabled:!!t})}function _Dn(s){return tt({queryKey:["brokerage-help-request",s],queryFn:async()=>{if(!s)return null;const{data:t,error:n}=await q.from("brokerage_help_requests").select("*, requester:profiles!brokerage_help_requests_requester_user_id_fkey(name, email, phone, avatar_url)").eq("id",s).single();if(n)throw n;return t},enabled:!!s})}function wDn(s){return tt({queryKey:["brokerage-help-claims",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await q.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(n)throw n;return t},enabled:!!s})}function jDn(){const s=Vt(),{user:t,brokerageId:n}=vs();return ft({mutationFn:async r=>{if(!t||!n)throw new Error("You must be in a brokerage to post.");const{data:a,error:i}=await q.from("brokerage_help_requests").insert({...r,brokerage_id:n,requester_user_id:t.id}).select().single();if(i)throw i;try{await q.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 NDn(){const s=Vt(),{user:t}=vs();return ft({mutationFn:async({request_id:n,note:r})=>{if(!t)throw new Error("Not signed in");const{data:a,error:i}=await q.from("brokerage_help_claims").insert({request_id:n,claimant_user_id:t.id,note:r}).select().single();if(i)throw i;return a},onSuccess:(n,r)=>{s.invalidateQueries({queryKey:["brokerage-help-claims",r.request_id]}),s.invalidateQueries({queryKey:["brokerage-help-requests"]})}})}function kDn(){const s=Vt();return ft({mutationFn:async({claim_id:t,request_id:n,claimant_user_id:r})=>{const{error:a}=await q.from("brokerage_help_claims").update({status:"accepted",responded_at:new Date().toISOString()}).eq("id",t);if(a)throw a;const{error:i}=await q.from("brokerage_help_requests").update({status:"filled",assigned_user_id:r}).eq("id",n);if(i)throw i;try{await q.functions.invoke("brokerage-help-claim-decision",{body:{claim_id:t}})}catch(l){console.warn("claim decision notify failed:",l)}},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["brokerage-help-claims",n.request_id]}),s.invalidateQueries({queryKey:["brokerage-help-request",n.request_id]}),s.invalidateQueries({queryKey:["brokerage-help-requests"]})}})}function SDn(){const s=Vt();return ft({mutationFn:async({claim_id:t})=>{const{error:n}=await q.from("brokerage_help_claims").update({status:"declined",responded_at:new Date().toISOString()}).eq("id",t);if(n)throw n},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["brokerage-help-claims",n.request_id]})}})}function CDn(){const s=Vt();return ft({mutationFn:async t=>{const{error:n}=await q.from("brokerage_help_requests").update({status:"cancelled"}).eq("id",t);if(n)throw n},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["brokerage-help-requests"]}),s.invalidateQueries({queryKey:["brokerage-help-request",n]})}})}function ADn(){const s=Vt();return ft({mutationFn:async t=>{const{error:n}=await q.from("brokerage_help_requests").update({status:"completed"}).eq("id",t);if(n)throw n},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["brokerage-help-requests"]}),s.invalidateQueries({queryKey:["brokerage-help-request",n]})}})}function EDn(){const{user:s,brokerageId:t}=vs(),n=Vt(),r=tt({queryKey:["brokerage-help-prefs",s==null?void 0:s.id,t],queryFn:async()=>{if(!s||!t)return null;const{data:i,error:l}=await q.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=ft({mutationFn:async i=>{if(!s||!t)throw new Error("No user/brokerage");const{error:l}=await q.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:()=>{n.invalidateQueries({queryKey:["brokerage-help-prefs"]})}});return{...r,setEmailEnabled:a.mutate,isSaving:a.isPending}}function TDn(s,t){if(!s)return null;const n=(a,i)=>new Intl.DateTimeFormat("en-US",{timeZone:"America/New_York",...i}).format(new Date(a)),r=n(s,{weekday:"short",month:"short",day:"numeric",hour:"numeric",minute:"2-digit"});if(t){const a=n(t,{hour:"numeric",minute:"2-digit"});return`${r} – ${a} ET`}return`${r} ET`}function MDn(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 PDn({req:s,onClick:t}){var i;const n=ZMe[s.request_type],r=TDn(s.event_start_at,s.event_end_at),a=[s.address,s.city,s.state].filter(Boolean).join(", ");return e.jsx(Ne,{className:"cursor-pointer hover:shadow-md transition group",onClick:t,children:e.jsxs(Ie,{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(Be,{variant:"secondary",className:"text-xs",children:[n.emoji," ",n.label]}),s.status!=="open"&&e.jsx(Be,{variant:"outline",className:"text-xs capitalize",children:s.status})]}),e.jsx(Di,{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:[r&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(da,{className:"h-3.5 w-3.5 shrink-0"}),e.jsx("span",{children:r})]}),a&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ci,{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(ru,{className:"h-3.5 w-3.5 shrink-0"}),e.jsx("span",{children:MDn(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 IDn(){var c;const s=Qn(),{brokerageId:t}=vs(),[n,r]=j.useState("open"),{data:a=[],isLoading:i}=bDn(n),l=EDn(),o=((c=l.data)==null?void 0:c.email_enabled)??!0;return t?e.jsx(Vs,{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(ha,{value:n,onValueChange:d=>r(d),children:e.jsxs(ma,{children:[e.jsx(Zt,{value:"open",children:"Open"}),e.jsx(Zt,{value:"mine",children:"My Posts"}),e.jsx(Zt,{value:"my_claims",children:"My Claims"}),e.jsx(Zt,{value:"filled",children:"Filled"})]})}),e.jsxs($,{onClick:()=>s("/brokerage/help-board/new"),className:"gap-2",children:[e.jsx(dn,{className:"h-4 w-4"})," Post Request"]})]}),e.jsx(Ne,{className:"bg-muted/30 border-dashed",children:e.jsxs(Ie,{className:"flex items-center justify-between py-3 px-5",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[o?e.jsx(qy,{className:"h-4 w-4 text-primary"}):e.jsx(XS,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("div",{children:[e.jsx(ee,{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(Sn,{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(Ne,{className:"bg-muted/30 border-dashed",children:e.jsxs(Ie,{className:"flex flex-col items-center justify-center py-12",children:[e.jsx(r4,{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:n==="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(PDn,{req:d,onClick:()=>s(`/brokerage/help-board/${d.id}`)},d.id))})]})}):e.jsx(Vs,{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(r4,{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 LDn(){const s=Qn(),{toast:t}=Bi(),n=jDn(),[r,a]=j.useState("open_house"),[i,l]=j.useState(""),[o,c]=j.useState(""),[d,u]=j.useState(""),[h,m]=j.useState(""),[f,g]=j.useState(""),[x,y]=j.useState(""),[v,b]=j.useState(""),[w,S]=j.useState(""),[C,E]=j.useState(""),[I,P]=j.useState(""),[R,D]=j.useState("goodwill"),[O,U]=j.useState(""),[W,V]=j.useState(""),G=r==="open_house"||r==="showing_coverage",Y=r!=="general",X=(ie,ne)=>!ie||!ne?null:`${ie}T${ne}:00`,ae=async ie=>{if(ie.preventDefault(),!i.trim()){t({title:"Add a title",description:"Tell teammates what you need help with.",variant:"destructive"});return}try{const ne=X(d,h),te=X(d,f);await n.mutateAsync({request_type:r,title:i.trim(),description:o.trim()||null,event_start_at:ne,event_end_at:te,address:G&&x.trim()||null,city:G&&v.trim()||null,state:G&&w.trim()||null,zip:G&&C.trim()||null,mls_number:I.trim()||null,compensation_type:R,compensation_amount:O?Number(O):null,compensation_notes:W.trim()||null}),t({title:"Posted!",description:"Your teammates have been notified."}),s("/brokerage/help-board")}catch(ne){t({title:"Could not post",description:(ne==null?void 0:ne.message)??"Something went wrong.",variant:"destructive"})}};return e.jsx(Vs,{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($,{variant:"ghost",size:"sm",onClick:()=>s("/brokerage/help-board"),className:"mb-4 gap-2",children:[e.jsx(qa,{className:"h-4 w-4"})," Back to board"]}),e.jsx("form",{onSubmit:ae,children:e.jsx(Ne,{children:e.jsxs(Ie,{className:"p-6 space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"What do you need help with?"}),e.jsx("div",{className:"grid grid-cols-2 gap-2",children:Object.keys(ZMe).map(ie=>{const ne=ZMe[ie],te=ie===r;return e.jsxs("button",{type:"button",onClick:()=>a(ie),className:`text-left p-3 rounded-lg border-2 transition ${te?"border-primary bg-primary/5":"border-border hover:border-primary/40"}`,children:[e.jsx("div",{className:"text-lg",children:ne.emoji}),e.jsx("div",{className:"font-medium text-sm mt-1",children:ne.label}),e.jsx("div",{className:"text-xs text-muted-foreground line-clamp-1",children:ne.description})]},ie)})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"title",children:"Title *"}),e.jsx(pe,{id:"title",value:i,onChange:ie=>l(ie.target.value),placeholder:r==="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(ee,{htmlFor:"description",children:"Details"}),e.jsx(Rs,{id:"description",value:o,onChange:ie=>c(ie.target.value),placeholder:"Any context — lockbox code instructions later, what to expect, etc.",rows:3,maxLength:1e3})]}),Y&&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(ee,{htmlFor:"date",children:"Date"}),e.jsx(pe,{id:"date",type:"date",value:d,onChange:ie=>u(ie.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"start",children:"Start"}),e.jsx(pe,{id:"start",type:"time",value:h,onChange:ie=>m(ie.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"end",children:"End"}),e.jsx(pe,{id:"end",type:"time",value:f,onChange:ie=>g(ie.target.value)})]})]}),G&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"address",children:"Address"}),e.jsx(pe,{id:"address",value:x,onChange:ie=>y(ie.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(ee,{htmlFor:"city",children:"City"}),e.jsx(pe,{id:"city",value:v,onChange:ie=>b(ie.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"state",children:"State"}),e.jsx(pe,{id:"state",value:w,onChange:ie=>S(ie.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(ee,{htmlFor:"zip",children:"Zip"}),e.jsx(pe,{id:"zip",value:C,onChange:ie=>E(ie.target.value),maxLength:10})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"mls",children:"MLS # (optional)"}),e.jsx(pe,{id:"mls",value:I,onChange:ie=>P(ie.target.value)})]})]})]}),e.jsxs("div",{className:"space-y-3 pt-2 border-t",children:[e.jsx(ee,{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(ie=>{const ne=R===ie.val;return e.jsxs("button",{type:"button",onClick:()=>D(ie.val),className:`text-left p-3 rounded-lg border-2 transition ${ne?"border-primary bg-primary/5":"border-border hover:border-primary/40"}`,children:[e.jsx("div",{className:"font-medium text-sm",children:ie.label}),e.jsx("div",{className:"text-xs text-muted-foreground",children:ie.sub})]},ie.val)})}),R!=="goodwill"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"amount",children:R==="flat_fee"?"Amount ($)":"Percent (%)"}),e.jsx(pe,{id:"amount",type:"number",min:"0",step:R==="referral_percent"?"1":"5",value:O,onChange:ie=>U(ie.target.value),placeholder:R==="flat_fee"?"100":"25"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"comp-notes",children:"Compensation notes"}),e.jsx(pe,{id:"comp-notes",value:W,onChange:ie=>V(ie.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($,{type:"button",variant:"ghost",onClick:()=>s("/brokerage/help-board"),children:"Cancel"}),e.jsxs($,{type:"submit",disabled:n.isPending,className:"gap-2",children:[n.isPending&&e.jsx(kt,{className:"h-4 w-4 animate-spin"}),"Post & Notify Brokerage"]})]})]})})})]})})}function RDn(s,t){if(!s)return null;const n=(a,i)=>new Intl.DateTimeFormat("en-US",{timeZone:"America/New_York",...i}).format(new Date(a)),r=n(s,{weekday:"long",month:"long",day:"numeric",year:"numeric",hour:"numeric",minute:"2-digit"});return t?`${r} – ${n(t,{hour:"numeric",minute:"2-digit"})} ET`:`${r} ET`}function D9e(s){return s?s.split(" ").map(t=>t[0]).slice(0,2).join("").toUpperCase():"?"}function DDn(){var I,P,R,D,O,U,W,V;const{id:s}=Wi(),t=Qn(),{user:n}=vs(),{toast:r}=Bi(),{data:a,isLoading:i}=_Dn(s),{data:l=[]}=wDn(s),o=NDn(),c=kDn(),d=SDn(),u=CDn(),h=ADn(),[m,f]=j.useState("");if(i)return e.jsx(Vs,{title:"Loading...",description:"",children:e.jsx("div",{className:"flex items-center justify-center py-16",children:e.jsx(kt,{className:"h-8 w-8 animate-spin text-primary"})})});if(!a)return e.jsxs(Vs,{title:"Not Found",description:"",children:[e.jsxs($,{variant:"ghost",onClick:()=>t("/brokerage/help-board"),className:"gap-2",children:[e.jsx(qa,{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 g=ZMe[a.request_type],x=RDn(a.event_start_at,a.event_end_at),y=[a.address,a.city,a.state,a.zip].filter(Boolean).join(", "),v=(n==null?void 0:n.id)===a.requester_user_id,b=l.find(G=>G.claimant_user_id===(n==null?void 0:n.id)),w=l.find(G=>G.status==="accepted"),S=a.status==="open",C=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)",E=async()=>{if(!m.trim()){r({title:"Add a quick note",description:"Let the requester know you're available."});return}try{await o.mutateAsync({request_id:a.id,note:m.trim()}),r({title:"You're in!",description:"The requester will review and pick someone."}),f("")}catch(G){r({title:"Could not submit",description:G==null?void 0:G.message,variant:"destructive"})}};return e.jsx(Vs,{title:a.title,description:`${g.emoji} ${g.label}`,children:e.jsxs("div",{className:"max-w-3xl mx-auto space-y-4",children:[e.jsxs($,{variant:"ghost",size:"sm",onClick:()=>t("/brokerage/help-board"),className:"gap-2",children:[e.jsx(qa,{className:"h-4 w-4"})," Back to board"]}),e.jsx(Ne,{children:e.jsxs(Ie,{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(Be,{variant:"secondary",children:[g.emoji," ",g.label]}),e.jsx(Be,{variant:S?"default":"outline",className:"capitalize",children:a.status})]}),e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsxs(Oa,{className:"h-7 w-7",children:[e.jsx(Li,{src:((I=a.requester)==null?void 0:I.avatar_url)||void 0}),e.jsx(za,{children:D9e((P=a.requester)==null?void 0:P.name)})]}),e.jsx("span",{children:((R=a.requester)==null?void 0:R.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:[x&&e.jsxs("div",{className:"flex items-start gap-2 text-sm",children:[e.jsx(da,{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:x})]})]}),y&&e.jsxs("div",{className:"flex items-start gap-2 text-sm",children:[e.jsx(ci,{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:y})]})]}),e.jsxs("div",{className:"flex items-start gap-2 text-sm",children:[e.jsx(ru,{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:C})]})]}),a.mls_number&&e.jsxs("div",{className:"flex items-start gap-2 text-sm",children:[e.jsx(WI,{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]})]})}),!v&&S&&!b&&e.jsx(Ne,{children:e.jsxs(Ie,{className:"p-6 space-y-3",children:[e.jsx("h3",{className:"font-semibold",children:"Offer to cover this"}),e.jsx(Rs,{placeholder:"Quick note — e.g. 'I'm 10 min away and free that day'",value:m,onChange:G=>f(G.target.value),rows:3,maxLength:400}),e.jsxs($,{onClick:E,disabled:o.isPending,className:"gap-2",children:[o.isPending&&e.jsx(kt,{className:"h-4 w-4 animate-spin"}),"I can cover this"]})]})}),!v&&b&&e.jsx(Ne,{className:"border-primary/30 bg-primary/5",children:e.jsxs(Ie,{className:"p-4 flex items-center gap-3",children:[e.jsx(la,{className:"h-5 w-5 text-primary"}),e.jsxs("div",{className:"text-sm",children:[e.jsxs("div",{className:"font-medium capitalize",children:["Your offer: ",b.status]}),e.jsxs("div",{className:"text-muted-foreground",children:[b.status==="pending"&&"Waiting for the requester to pick.",b.status==="accepted"&&"You're confirmed — see contact info below.",b.status==="declined"&&"They went with someone else this time."]})]})]})}),w&&(v||w.claimant_user_id===(n==null?void 0:n.id))&&e.jsx(Ne,{className:"border-primary/30",children:e.jsxs(Ie,{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(Oa,{className:"h-10 w-10",children:[e.jsx(Li,{src:((D=w.claimant)==null?void 0:D.avatar_url)||void 0}),e.jsx(za,{children:D9e((O=w.claimant)==null?void 0:O.name)})]}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:(U=w.claimant)==null?void 0:U.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:[((W=w.claimant)==null?void 0:W.email)&&e.jsxs("a",{href:`mailto:${w.claimant.email}`,className:"flex items-center gap-2 text-primary hover:underline",children:[e.jsx(mn,{className:"h-4 w-4"})," ",w.claimant.email]}),((V=w.claimant)==null?void 0:V.phone)&&e.jsxs("a",{href:`tel:${w.claimant.phone}`,className:"flex items-center gap-2 text-primary hover:underline",children:[e.jsx(Da,{className:"h-4 w-4"})," ",w.claimant.phone]})]})]})}),v&&e.jsx(Ne,{children:e.jsxs(Ie,{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(G=>{var Y,X,ae,ie,ne;return e.jsxs("div",{className:"flex items-start gap-3 p-3 rounded-lg border",children:[e.jsxs(Oa,{className:"h-10 w-10",children:[e.jsx(Li,{src:((Y=G.claimant)==null?void 0:Y.avatar_url)||void 0}),e.jsx(za,{children:D9e((X=G.claimant)==null?void 0:X.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:((ae=G.claimant)==null?void 0:ae.name)||"Teammate"}),e.jsx(Be,{variant:"outline",className:"capitalize text-xs",children:G.status})]}),G.note&&e.jsxs("p",{className:"text-sm text-muted-foreground mt-1",children:['"',G.note,'"']}),G.status==="pending"&&S&&e.jsxs("div",{className:"flex gap-2 mt-2",children:[e.jsxs($,{size:"sm",onClick:()=>c.mutate({claim_id:G.id,request_id:a.id,claimant_user_id:G.claimant_user_id}),disabled:c.isPending,className:"gap-1",children:[e.jsx(la,{className:"h-3.5 w-3.5"})," Pick ",((ne=(ie=G.claimant)==null?void 0:ie.name)==null?void 0:ne.split(" ")[0])||"them"]}),e.jsxs($,{size:"sm",variant:"ghost",onClick:()=>d.mutate({claim_id:G.id,request_id:a.id}),disabled:d.isPending,className:"gap-1",children:[e.jsx(gr,{className:"h-3.5 w-3.5"})," Pass"]})]})]})]},G.id)}),v&&S&&e.jsx("div",{className:"pt-3 border-t flex justify-end",children:e.jsx($,{variant:"ghost",size:"sm",onClick:()=>u.mutate(a.id),disabled:u.isPending,children:"Cancel request"})}),v&&a.status==="filled"&&e.jsx("div",{className:"pt-3 border-t flex justify-end",children:e.jsx($,{size:"sm",onClick:()=>h.mutate(a.id),disabled:h.isPending,children:"Mark complete"})})]})})]})})}function GXt({onSelect:s,maxHeight:t="460px"}){const[n,r]=j.useState(""),[a,i]=j.useState("all"),{data:l=[],isLoading:o}=tt({queryKey:["newsletter-graphics-picker"],queryFn:async()=>{const{data:u,error:h}=await q.from("newsletter_graphics").select("*").eq("is_active",!0).order("is_featured",{ascending:!1}).order("sort_order",{ascending:!0}).order("created_at",{ascending:!1});if(h)throw h;return u||[]}}),c=j.useMemo(()=>{const u=new Set;return l.forEach(h=>u.add(h.category||"general")),["all",...Array.from(u).sort()]},[l]),d=j.useMemo(()=>{const u=n.trim().toLowerCase();return l.filter(h=>a!=="all"&&h.category!==a?!1:u?h.title.toLowerCase().includes(u)||(h.description||"").toLowerCase().includes(u)||(h.tags||[]).some(m=>m.toLowerCase().includes(u)):!0)},[l,n,a]);return e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"relative",children:[e.jsx(Kr,{className:"absolute left-2.5 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground"}),e.jsx(pe,{value:n,onChange:u=>r(u.target.value),placeholder:"Search graphics...",className:"pl-8 h-9"})]}),c.length>1&&e.jsx("div",{className:"flex flex-wrap gap-1.5",children:c.map(u=>e.jsx("button",{onClick:()=>i(u),className:`px-2.5 py-1 rounded-full text-xs font-medium transition-colors ${a===u?"bg-primary text-primary-foreground":"bg-muted hover:bg-muted/70 text-muted-foreground"}`,children:u==="all"?"All":u},u))}),e.jsx(uo,{style:{maxHeight:t},className:"rounded-md border",children:o?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(kt,{className:"h-5 w-5 animate-spin text-muted-foreground"})}):d.length===0?e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(Mc,{className:"h-8 w-8 text-muted-foreground/50 mb-2"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:l.length===0?"No graphics available yet":"No graphics match your search"})]}):e.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 gap-2 p-2",children:d.map(u=>e.jsxs("button",{onClick:()=>s(u),className:"group relative rounded-md overflow-hidden border bg-muted/30 hover:ring-2 hover:ring-primary hover:border-primary transition-all text-left",title:u.title,children:[e.jsx("div",{className:"aspect-video bg-muted overflow-hidden",children:e.jsx("img",{src:u.thumbnail_url||u.image_url,alt:u.title,loading:"lazy",className:"w-full h-full object-cover group-hover:scale-105 transition-transform duration-200"})}),u.is_featured&&e.jsxs(Be,{className:"absolute top-1 left-1 h-5 px-1.5 gap-0.5 text-[10px] bg-amber-500 hover:bg-amber-500 text-white border-0",children:[e.jsx(Ja,{className:"h-2.5 w-2.5 fill-current"}),"Featured"]}),e.jsxs("div",{className:"p-1.5 bg-background",children:[e.jsx("p",{className:"text-xs font-medium truncate",children:u.title}),e.jsx("p",{className:"text-[10px] text-muted-foreground truncate",children:u.category})]})]},u.id))})}),e.jsxs("p",{className:"text-xs text-muted-foreground text-center",children:[d.length," graphic",d.length===1?"":"s",a!=="all"?` in ${a}`:""]})]})}const FDn=[{key:"search",label:"Search for Properties",icon:Kr,defaultText:"Search for Properties",placeholder:"https://your-website.com/search",helper:"Link to your home search page"},{key:"call",label:"Call Agent",icon:Da,defaultText:"Call Me",hrefPrefix:"tel:",placeholder:"+15555551234",helper:"Your phone number"},{key:"email",label:"Email Agent",icon:mn,defaultText:"Email Me",hrefPrefix:"mailto:",placeholder:"you@email.com",helper:"Your email address"},{key:"schedule",label:"Schedule a Call",icon:Ta,defaultText:"Schedule a Call",placeholder:"https://calendly.com/you",helper:"Link to your booking page"},{key:"listings",label:"View My Listings",icon:va,defaultText:"View My Listings",placeholder:"https://your-website.com/listings",helper:"Link to your listings page"},{key:"valuation",label:"Get Home Value",icon:ru,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:ci,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:zd,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:Lm,defaultText:"Learn More",placeholder:"https://...",helper:"Any link you want"}];function oSt(s){const t=s.match(/(?:youtube\.com\/(?:watch\?v=|embed\/|v\/)|youtu\.be\/)([A-Za-z0-9_-]{11})/);return t?t[1]:null}function ODn(s){const t=s.match(/vimeo\.com\/(?:video\/)?(\d+)/);return t?t[1]:null}function tit({html:s,onChange:t}){const{user:n}=vs(),r=j.useRef(null),a=j.useRef(""),i=j.useRef(t);i.current=t;const[l,o]=j.useState("desktop"),c=j.useRef(null),[d,u]=j.useState(!1),[h,m]=j.useState(""),[f,g]=j.useState(""),x=j.useRef(null),y=()=>{var St;const Ft=(St=r.current)==null?void 0:St.contentDocument,rs=Ft==null?void 0:Ft.getSelection();rs&&rs.rangeCount>0&&(Ft!=null&&Ft.body.contains(rs.anchorNode))&&(x.current=rs.getRangeAt(0).cloneRange())},v=()=>{var gs;const Ft=c.current,rs=(gs=r.current)==null?void 0:gs.contentDocument;if(!Ft||!rs)return;let St=h.trim();St&&!/^(https?:|mailto:|tel:|#|\/)/i.test(St)&&(St="https://"+St),Ft.setAttribute("href",St),Ft.setAttribute("target","_blank");const Xs=f.trim();Xs&&Xs!==(Ft.textContent||"").trim()&&(Ft.textContent=Xs);const vt=` `+rs.documentElement.outerHTML;a.current=vt,i.current(vt),u(!1)};j.useEffect(()=>{var St,Xs;const Ft=r.current;if(!Ft||a.current===s)return;const rs=()=>{const vt=Ft.contentDocument;if(!vt)return;vt.open(),vt.write(s||""),vt.close(),a.current=s;const gs=vt.body;if(!gs)return;gs.setAttribute("contenteditable","true"),gs.style.outline="none",gs.style.minHeight="400px",gs.style.cursor="text";const Ss=()=>{const Ys=` `+vt.documentElement.outerHTML;a.current=Ys,i.current(Ys)};gs.addEventListener("input",Ss),gs.addEventListener("blur",Ss),gs.addEventListener("mouseup",y),gs.addEventListener("keyup",y),vt.addEventListener("selectionchange",y);const Is=Ys=>{var ds;const cs=Ys.target,js=cs==null?void 0:cs.closest("a");if(js){if(Ys.metaKey||Ys.ctrlKey||Ys.shiftKey)return;Ys.preventDefault(),Ys.stopPropagation(),c.current=js,m(js.getAttribute("href")||""),g((js.textContent||"").trim()),u(!0);return}const kn=vt.getSelection();if(!kn)return;const Ws=(ds=vt.caretRangeFromPoint)==null?void 0:ds.call(vt,Ys.clientX,Ys.clientY),On=Ws==null?void 0:Ws.startContainer;if(On&&On.nodeType===Node.TEXT_NODE){const gn=On.textContent||"",As=Ws.startOffset,hr=gn.lastIndexOf("[",As),Er=gn.indexOf("]",As);if(hr!==-1&&Er!==-1&&Er>hr){const qn=vt.createRange();qn.setStart(On,hr),qn.setEnd(On,Er+1),kn.removeAllRanges(),kn.addRange(qn),x.current=qn.cloneRange()}}};gs.addEventListener("click",Is,!0)};((St=Ft.contentDocument)==null?void 0:St.readyState)==="complete"||(Xs=Ft.contentDocument)!=null&&Xs.body?rs():Ft.addEventListener("load",rs,{once:!0})},[s]);const b=(Ft,rs)=>{var vt;const St=(vt=r.current)==null?void 0:vt.contentDocument;if(!St)return;St.body.focus(),St.execCommand(Ft,!1,rs);const Xs=` `+St.documentElement.outerHTML;a.current=Xs,i.current(Xs)},w=()=>{const Ft=window.prompt("Enter URL (https://...)");Ft&&b("createLink",Ft)},S=(Ft,rs)=>{var vt;const St=(vt=r.current)==null?void 0:vt.contentDocument;if(!St)return;if(St.body.focus(),rs==="cursor"&&x.current&&St.body.contains(x.current.startContainer)){const gs=St.getSelection();if(gs){gs.removeAllRanges(),gs.addRange(x.current),St.execCommand("insertHTML",!1,Ft);const Ss=` `+St.documentElement.outerHTML;a.current=Ss,i.current(Ss);return}}rs==="top"?St.body.insertAdjacentHTML("afterbegin",Ft):St.body.insertAdjacentHTML("beforeend",Ft);const Xs=` `+St.documentElement.outerHTML;a.current=Xs,i.current(Xs)},[C,E]=j.useState(!1),[I,P]=j.useState(null),[R,D]=j.useState(""),[O,U]=j.useState(""),[W,V]=j.useState("#406E71"),[G,Y]=j.useState("cursor"),X=Ft=>{P(Ft),D(Ft.defaultText),U(""),E(!0)},ae=()=>{if(!I)return;const Ft=O.trim();if(!I.isForward&&!Ft)return;let rs=Ft;if(I.isForward){const gs=Ft||"",Ss=encodeURIComponent("You should see this newsletter"),Is=encodeURIComponent(gs?`I thought you'd like this — take a look: ${gs} `:`I thought you'd like this newsletter — take a look! `);rs=`mailto:?subject=${Ss}&body=${Is}`}else I.hrefPrefix==="tel:"?rs="tel:"+Ft.replace(/[^0-9+]/g,""):I.hrefPrefix==="mailto:"?rs="mailto:"+Ft:/^https?:\/\//i.test(Ft)||(rs="https://"+Ft);const St=(R||I.defaultText).replace(/[<>]/g,""),Xs=W||"#406E71",vt=`
${St}

 

`;S(vt,G),E(!1)},[ie,ne]=j.useState(!1),[te,J]=j.useState(""),[ce,_e]=j.useState(""),[he,ue]=j.useState(""),[ve,Ee]=j.useState("cursor"),Se=(()=>{if(ce.trim())return ce.trim();const Ft=oSt(te);return Ft?`https://i.ytimg.com/vi/${Ft}/hqdefault.jpg`:""})(),Le=()=>{J(""),_e(""),ue(""),ne(!0)},Fe=()=>{const Ft=te.trim();if(!Ft)return;let rs=Ft;/^https?:\/\//i.test(rs)||(rs="https://"+rs);const St=oSt(rs),Xs=St?null:ODn(rs);let vt=ce.trim();!vt&&St&&(vt=`https://i.ytimg.com/vi/${St}/hqdefault.jpg`),!vt&&Xs&&(vt=`https://vumbnail.com/${Xs}.jpg`),vt||(vt="https://placehold.co/600x340/406E71/ffffff?text=Watch+Video");const gs=(he||"Watch the video").replace(/[<>]/g,""),Ss=`
${gs}
▶
▶ ${gs}

 

`.trim();S(Ss,ve),ne(!1)},[ke,Ve]=j.useState(!1),[je,Ae]=j.useState(""),[Ce,qe]=j.useState(""),[ze,$e]=j.useState("full"),[ct,Xe]=j.useState("cursor"),[it,at]=j.useState(!1),Ke=j.useRef(null),nt=()=>{Ae(""),qe(""),$e("full"),Ve(!0)},xt=async Ft=>{var rs;if(!n){re.error("You must be signed in to upload images");return}if(Ft.size>10*1024*1024){re.error("Image must be under 10MB");return}at(!0);try{const St=((rs=Ft.name.split(".").pop())==null?void 0:rs.toLowerCase())||"png",Xs=`${n.id}/newsletters/${Date.now()}-${Math.random().toString(36).slice(2,8)}.${St}`,{error:vt}=await q.storage.from("email-assets").upload(Xs,Ft,{cacheControl:"3600",upsert:!1,contentType:Ft.type});if(vt)throw vt;const{data:gs}=q.storage.from("email-assets").getPublicUrl(Xs);Ae(gs.publicUrl),re.success("Image uploaded")}catch(St){re.error(St.message||"Upload failed")}finally{at(!1)}},rt=()=>{if(!je.trim())return;const Ft=(Ce||"").replace(/[<>"]/g,""),rs=ze==="half"?280:560,St=`
${Ft}

 

`.trim();S(St,ct),Ve(!1)},{data:Yt,isLoading:qt}=tt({queryKey:["newsletter-editor-videos",n==null?void 0:n.id],enabled:!!(n!=null&&n.id)&&ie,queryFn:async()=>{const{data:Ft,error:rs}=await q.from("agent_videos").select("id, title, thumbnail_url, share_token, duration_seconds, created_at").eq("owner_user_id",n.id).eq("is_deleted",!1).eq("status","ready").not("share_token","is",null).order("created_at",{ascending:!1}).limit(50);if(rs)throw rs;return Ft||[]}}),ts=Ft=>{Ft.share_token&&(J(`https://video.relevelup.com/share/video/${Ft.share_token}`),_e(`https://video.relevelup.com/thumb/${Ft.share_token}`),ue(Ft.title||"Watch the video"))},ys=l==="mobile"?390:"100%",Bt=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($,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>b("bold"),title:"Bold",children:e.jsx(AE,{className:"h-3.5 w-3.5"})}),e.jsx($,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>b("italic"),title:"Italic",children:e.jsx(ME,{className:"h-3.5 w-3.5"})}),e.jsx($,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>b("underline"),title:"Underline",children:e.jsx(i7,{className:"h-3.5 w-3.5"})}),e.jsx("div",{className:"w-px h-5 bg-border mx-1"}),e.jsx($,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>b("insertUnorderedList"),title:"Bullet list",children:e.jsx(P0,{className:"h-3.5 w-3.5"})}),e.jsx($,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>b("insertOrderedList"),title:"Numbered list",children:e.jsx(p2,{className:"h-3.5 w-3.5"})}),e.jsx($,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:w,title:"Insert link",children:e.jsx(Ad,{className:"h-3.5 w-3.5"})}),e.jsx("div",{className:"w-px h-5 bg-border mx-1"}),e.jsx($,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>b("undo"),title:"Undo",children:e.jsx(BE,{className:"h-3.5 w-3.5"})}),e.jsx($,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>b("redo"),title:"Redo",children:e.jsx(OE,{className:"h-3.5 w-3.5"})}),e.jsx("div",{className:"w-px h-5 bg-border mx-1"}),e.jsxs(Uu,{children:[e.jsx(qu,{asChild:!0,children:e.jsxs($,{type:"button",variant:"ghost",size:"sm",className:"h-7 px-2 gap-1.5",title:"Insert CTA Button",children:[e.jsx(Lm,{className:"h-3.5 w-3.5"}),e.jsx("span",{className:"text-xs font-medium",children:"CTA Button"})]})}),e.jsxs(Eu,{align:"start",className:"w-56 bg-popover z-50",children:[e.jsx(SL,{children:"Insert a call-to-action"}),e.jsx(R0,{}),FDn.map(Ft=>{const rs=Ft.icon;return e.jsxs(ja,{onClick:()=>X(Ft),children:[e.jsx(rs,{className:"h-4 w-4 mr-2"}),Ft.label]},Ft.key)})]})]}),e.jsxs($,{type:"button",variant:"ghost",size:"sm",className:"h-7 px-2 gap-1.5",title:"Insert image",onClick:nt,children:[e.jsx(Mc,{className:"h-3.5 w-3.5"}),e.jsx("span",{className:"text-xs font-medium",children:"Image"})]}),e.jsxs($,{type:"button",variant:"ghost",size:"sm",className:"h-7 px-2 gap-1.5",title:"Insert video block",onClick:Le,children:[e.jsx(ua,{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(EV,{type:"single",value:l,onValueChange:Ft=>Ft&&o(Ft),size:"sm",className:"h-7",children:[e.jsx(_7,{value:"desktop",className:"h-7 px-2",title:"Desktop preview",children:e.jsx(sk,{className:"h-3.5 w-3.5"})}),e.jsx(_7,{value:"mobile",className:"h-7 px-2",title:"Mobile preview",children:e.jsx(_1,{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(Lm,{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:r,title:"Newsletter visual editor",className:"bg-white",style:{width:ys,maxWidth:Bt,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(zs,{open:d,onOpenChange:u,children:e.jsxs(Os,{className:"sm:max-w-md",children:[e.jsx(Us,{children:e.jsx(Bs,{children:"Edit link"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"link-edit-text",children:"Button / link text"}),e.jsx(pe,{id:"link-edit-text",value:f,onChange:Ft=>g(Ft.target.value),placeholder:"Click here"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"link-edit-href",children:"Where should this link go?"}),e.jsx(pe,{id:"link-edit-href",value:h,onChange:Ft=>m(Ft.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(Ar,{children:[e.jsx($,{type:"button",variant:"outline",onClick:()=>u(!1),children:"Cancel"}),e.jsx($,{type:"button",onClick:v,disabled:!h.trim(),children:"Save link"})]})]})}),e.jsx(zs,{open:C,onOpenChange:E,children:e.jsxs(Os,{className:"sm:max-w-md",children:[e.jsx(Us,{children:e.jsxs(Bs,{children:["Insert ",(I==null?void 0:I.label)||"CTA Button"]})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"cta-text",children:"Button text"}),e.jsx(pe,{id:"cta-text",value:R,onChange:Ft=>D(Ft.target.value),placeholder:I==null?void 0:I.defaultText})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"cta-value",children:I==null?void 0:I.helper}),e.jsx(pe,{id:"cta-value",value:O,onChange:Ft=>U(Ft.target.value),placeholder:I==null?void 0:I.placeholder,autoFocus:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"cta-color",children:"Button color"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(pe,{id:"cta-color",type:"color",value:W,onChange:Ft=>V(Ft.target.value),className:"h-9 w-16 p-1 cursor-pointer"}),e.jsx(pe,{value:W,onChange:Ft=>V(Ft.target.value),className:"flex-1"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Position"}),e.jsxs(kw,{value:G,onValueChange:Ft=>Y(Ft),className:"flex gap-4 flex-wrap",children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Ym,{value:"cursor",id:"cta-cursor"}),e.jsxs(ee,{htmlFor:"cta-cursor",className:"flex items-center gap-1.5 cursor-pointer font-normal",children:[e.jsx(Lm,{className:"h-3.5 w-3.5"}),"At cursor"]})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Ym,{value:"top",id:"cta-top"}),e.jsxs(ee,{htmlFor:"cta-top",className:"flex items-center gap-1.5 cursor-pointer font-normal",children:[e.jsx(Zf,{className:"h-3.5 w-3.5"}),"Top of newsletter"]})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Ym,{value:"bottom",id:"cta-bottom"}),e.jsxs(ee,{htmlFor:"cta-bottom",className:"flex items-center gap-1.5 cursor-pointer font-normal",children:[e.jsx(Dg,{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:W,color:"#ffffff",borderRadius:6,padding:"14px 28px",fontFamily:"Arial, sans-serif",fontWeight:600,fontSize:16},children:R||(I==null?void 0:I.defaultText)})})]}),e.jsxs(Ar,{children:[e.jsx($,{type:"button",variant:"outline",onClick:()=>E(!1),children:"Cancel"}),e.jsx($,{type:"button",onClick:ae,disabled:!(I!=null&&I.isForward)&&!O.trim(),children:"Insert Button"})]})]})}),e.jsx(zs,{open:ie,onOpenChange:ne,children:e.jsxs(Os,{className:"sm:max-w-lg max-h-[90vh] overflow-y-auto",children:[e.jsx(Us,{children:e.jsx(Bs,{children:"Insert Video Block"})}),e.jsxs(ha,{defaultValue:"library",className:"space-y-3",children:[e.jsxs(ma,{className:"grid w-full grid-cols-3",children:[e.jsx(Zt,{value:"library",children:"My Library"}),e.jsx(Zt,{value:"url",children:"From URL"}),e.jsx(Zt,{value:"record",children:"Record New"})]}),e.jsxs(Xt,{value:"library",className:"space-y-3 mt-2",children:[qt?e.jsxs("div",{className:"text-center py-8 text-sm text-muted-foreground",children:[e.jsx(kt,{className:"h-5 w-5 animate-spin mx-auto mb-2"}),"Loading your videos..."]}):!Yt||Yt.length===0?e.jsxs("div",{className:"text-center py-8 text-sm text-muted-foreground border rounded-md",children:[e.jsx(ua,{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:Yt.map(Ft=>{const rs=te.includes(Ft.share_token||"___"),St=Ft.share_token?`https://video.relevelup.com/thumb/${Ft.share_token}`:Ft.thumbnail_url||"";return e.jsxs("button",{type:"button",onClick:()=>ts(Ft),className:`group text-left rounded-md border-2 overflow-hidden transition-all ${rs?"border-primary ring-2 ring-primary/30":"border-transparent hover:border-primary/40"}`,children:[e.jsxs("div",{className:"aspect-video bg-muted relative",children:[St?e.jsx("img",{src:St,alt:Ft.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(ua,{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(Bu,{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:Ft.title||"Untitled"})})]},Ft.id)})}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{htmlFor:"vid-title-lib",className:"text-xs",children:"Caption (optional)"}),e.jsx(pe,{id:"vid-title-lib",value:he,onChange:Ft=>ue(Ft.target.value),placeholder:"Watch the video"})]})]}),e.jsxs(Xt,{value:"url",className:"space-y-3 mt-2",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{htmlFor:"vid-url",children:"Video URL"}),e.jsx(pe,{id:"vid-url",value:te,onChange:Ft=>J(Ft.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(ee,{htmlFor:"vid-title",children:"Caption (optional)"}),e.jsx(pe,{id:"vid-title",value:he,onChange:Ft=>ue(Ft.target.value),placeholder:"Watch the video"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{htmlFor:"vid-thumb",children:"Custom thumbnail URL (optional)"}),e.jsx(pe,{id:"vid-thumb",value:ce,onChange:Ft=>_e(Ft.target.value),placeholder:"https://... (only if not YouTube/Vimeo)"})]})]}),e.jsx(Xt,{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(ua,{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($,{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(ee,{children:"Position"}),e.jsxs(kw,{value:ve,onValueChange:Ft=>Ee(Ft),className:"flex gap-4 flex-wrap",children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Ym,{value:"cursor",id:"vid-cursor"}),e.jsxs(ee,{htmlFor:"vid-cursor",className:"flex items-center gap-1.5 cursor-pointer font-normal",children:[e.jsx(Lm,{className:"h-3.5 w-3.5"}),"At cursor"]})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Ym,{value:"top",id:"vid-top"}),e.jsxs(ee,{htmlFor:"vid-top",className:"flex items-center gap-1.5 cursor-pointer font-normal",children:[e.jsx(Zf,{className:"h-3.5 w-3.5"}),"Top"]})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Ym,{value:"bottom",id:"vid-bottom"}),e.jsxs(ee,{htmlFor:"vid-bottom",className:"flex items-center gap-1.5 cursor-pointer font-normal",children:[e.jsx(Dg,{className:"h-3.5 w-3.5"}),"Bottom"]})]})]})]}),Se&&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:Se,alt:"thumbnail",className:"w-full rounded-md",style:{maxHeight:180,objectFit:"cover"},onError:Ft=>{Ft.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(Ar,{children:[e.jsx($,{type:"button",variant:"outline",onClick:()=>ne(!1),children:"Cancel"}),e.jsx($,{type:"button",onClick:Fe,disabled:!te.trim(),children:"Insert Video"})]})]})}),e.jsx(zs,{open:ke,onOpenChange:Ve,children:e.jsxs(Os,{className:"sm:max-w-md max-h-[90vh] overflow-y-auto",children:[e.jsx(Us,{children:e.jsx(Bs,{children:"Insert Image"})}),e.jsxs(ha,{defaultValue:"library",className:"space-y-3",children:[e.jsxs(ma,{className:"grid w-full grid-cols-3",children:[e.jsx(Zt,{value:"library",children:"Library"}),e.jsx(Zt,{value:"upload",children:"Upload"}),e.jsx(Zt,{value:"url",children:"From URL"})]}),e.jsx(Xt,{value:"library",className:"mt-2",children:e.jsx(GXt,{maxHeight:"380px",onSelect:Ft=>{Ae(Ft.image_url),Ce||qe(Ft.title)}})}),e.jsxs(Xt,{value:"upload",className:"space-y-3 mt-2",children:[e.jsx("input",{ref:Ke,type:"file",accept:"image/png,image/jpeg,image/webp,image/gif",className:"hidden",onChange:Ft=>{var St;const rs=(St=Ft.target.files)==null?void 0:St[0];rs&&xt(rs),Ft.target.value=""}}),je?e.jsxs("div",{className:"rounded-md border overflow-hidden bg-muted/30",children:[e.jsx("img",{src:je,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($,{type:"button",variant:"ghost",size:"sm",onClick:()=>Ae(""),children:"Replace"})]})]}):e.jsx("button",{type:"button",onClick:()=>{var Ft;return(Ft=Ke.current)==null?void 0:Ft.click()},disabled:it,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:it?e.jsxs(e.Fragment,{children:[e.jsx(kt,{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(ni,{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(Xt,{value:"url",className:"space-y-3 mt-2",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{htmlFor:"img-url",children:"Image URL"}),e.jsx(pe,{id:"img-url",value:je,onChange:Ft=>Ae(Ft.target.value),placeholder:"https://..."})]}),je&&/^https?:\/\//i.test(je)&&e.jsx("div",{className:"rounded-md border overflow-hidden bg-muted/30",children:e.jsx("img",{src:je,alt:"Preview",className:"w-full max-h-48 object-contain",onError:Ft=>{Ft.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(ee,{htmlFor:"img-alt",children:"Alt text (for accessibility)"}),e.jsx(pe,{id:"img-alt",value:Ce,onChange:Ft=>qe(Ft.target.value),placeholder:"Describe the image"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Size"}),e.jsxs(kw,{value:ze,onValueChange:Ft=>$e(Ft),className:"flex gap-4",children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Ym,{value:"full",id:"img-full"}),e.jsx(ee,{htmlFor:"img-full",className:"cursor-pointer font-normal",children:"Full width"})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Ym,{value:"half",id:"img-half"}),e.jsx(ee,{htmlFor:"img-half",className:"cursor-pointer font-normal",children:"Half width"})]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Position"}),e.jsxs(kw,{value:ct,onValueChange:Ft=>Xe(Ft),className:"flex gap-4 flex-wrap",children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Ym,{value:"cursor",id:"img-cursor"}),e.jsxs(ee,{htmlFor:"img-cursor",className:"flex items-center gap-1.5 cursor-pointer font-normal",children:[e.jsx(Lm,{className:"h-3.5 w-3.5"}),"At cursor"]})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Ym,{value:"top",id:"img-top"}),e.jsxs(ee,{htmlFor:"img-top",className:"flex items-center gap-1.5 cursor-pointer font-normal",children:[e.jsx(Zf,{className:"h-3.5 w-3.5"}),"Top"]})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Ym,{value:"bottom",id:"img-bottom"}),e.jsxs(ee,{htmlFor:"img-bottom",className:"flex items-center gap-1.5 cursor-pointer font-normal",children:[e.jsx(Dg,{className:"h-3.5 w-3.5"}),"Bottom"]})]})]})]})]}),e.jsxs(Ar,{children:[e.jsx($,{type:"button",variant:"outline",onClick:()=>Ve(!1),children:"Cancel"}),e.jsx($,{type:"button",onClick:rt,disabled:!je.trim()||it,children:"Insert Image"})]})]})})]})}const lSt="newsletter-content",zDn="inline-images";function BDn(s,t){const n=atob(s),r=new Array(n.length);for(let a=0;a{const{data:P}=await q.from("team_members").select("team_id, role").eq("user_id",a.id).maybeSingle();return P}}),C=(S==null?void 0:S.role)==="team_leader",E=(S==null?void 0:S.team_id)??null;j.useEffect(()=>{s&&(d((n==null?void 0:n.title)??""),h((n==null?void 0:n.description)??""),f((n==null?void 0:n.html_content)??qDn()),x((n==null?void 0:n.is_template)??!1),v((n==null?void 0:n.share_scope)??"private"))},[s,n]);const I=async()=>{if(a){if(!c.trim()){re.error("Please enter a title");return}if(!m.trim()){re.error("Newsletter content is empty");return}w(!0);try{const P=await $Dn(m);P!==m&&f(P);const R={user_id:a.id,title:c.trim(),description:u.trim()||null,html_content:P,is_template:g,share_scope:y,shared_team_id:y==="team"?E:null,shared_brokerage_id:y==="brokerage"?o:null};if(y==="team"&&!E){re.error("You must be a team leader to share with a team"),w(!1);return}if(y==="brokerage"&&!l){re.error("Only brokerage managers can share to a brokerage"),w(!1);return}if(y==="global"&&!i){re.error("Only admins can publish global starter templates"),w(!1);return}let D;if(n!=null&&n.id?{error:D}=await q.from("agent_custom_newsletters").update(R).eq("id",n.id):{error:D}=await q.from("agent_custom_newsletters").insert(R),D)throw D;re.success(n!=null&&n.id?"Saved":"Newsletter created"),r==null||r(),t(!1)}catch(P){re.error(P.message||"Failed to save")}finally{w(!1)}}};return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Os,{className:"max-w-6xl h-[92vh] flex flex-col p-0",children:[e.jsx(Us,{className:"px-6 pt-6 pb-3 border-b",children:e.jsx(Bs,{children:n!=null&&n.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(ee,{htmlFor:"acn-title",children:"Title *"}),e.jsx(pe,{id:"acn-title",value:c,onChange:P=>d(P.target.value),placeholder:"e.g. June Market Update"})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"acn-desc",children:"Description (optional)"}),e.jsx(pe,{id:"acn-desc",value:u,onChange:P=>h(P.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(Sn,{id:"acn-template",checked:g,onCheckedChange:x}),e.jsx(ee,{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"})]}),(C||l||i)&&e.jsxs("div",{className:"rounded-lg border p-4 space-y-3",children:[e.jsx(ee,{className:"text-sm font-semibold",children:"Sharing"}),e.jsxs(kw,{value:y,onValueChange:P=>v(P),className:"space-y-2",children:[e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(Ym,{value:"private",id:"s-private",className:"mt-0.5"}),e.jsxs(ee,{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"})]})]}),C&&e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(Ym,{value:"team",id:"s-team",className:"mt-0.5"}),e.jsxs(ee,{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(Ym,{value:"brokerage",id:"s-brokerage",className:"mt-0.5"}),e.jsxs(ee,{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(Ym,{value:"global",id:"s-global",className:"mt-0.5"}),e.jsxs(ee,{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(ee,{className:"mb-2 block",children:"Content"}),e.jsx(tit,{html:m,onChange:f})]})]}),e.jsxs(Ar,{className:"px-6 py-3 border-t",children:[e.jsx($,{variant:"outline",onClick:()=>t(!1),disabled:b,children:"Cancel"}),e.jsxs($,{onClick:I,disabled:b,children:[b?e.jsx(kt,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(tl,{className:"h-4 w-4 mr-2"}),n!=null&&n.id?"Save Changes":"Create"]})]})]})})}function qDn(){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}}

`}const sit=/\[[^\]\[<>]{2,80}\]/g,VDn=/^\[\s*(?:\/?\s*if\b[^\]]*|endif|else|x-apple-[\w-]*|data-[\w-]*|object [^\]]*|cdata[^\]]*)\s*\]$/i;function nit(s){return!VDn.test(s)}function HDn(s){return(s.match(sit)||[]).filter(nit)}function cSt(s){const t=s.toLowerCase();return t.charAt(0).toUpperCase()+t.slice(1)}function GDn(s){const t=[],n=new RegExp(sit.source,"g");let r;for(;(r=n.exec(s))!==null;)nit(r[0])&&t.push({token:r[0],start:r.index});const a=t.reduce((l,o)=>(l[o.token]=(l[o.token]||0)+1,l),{}),i={};return t.map((l,o)=>{const c=l.token.slice(1,-1),d=/^#+$/.test(c);i[l.token]=(i[l.token]||0)+1;const u=t[o+1],h=u?u.token.slice(1,-1):"";let m;return d?m=u&&!/^#+$/.test(h)?`Date · ${cSt(h)}`:`Date ${i[l.token]}`:(m=cSt(c),a[l.token]>1&&(m+=` (${i[l.token]} of ${a[l.token]})`)),{index:o,token:l.token,label:m,hint:d?"Day of the month, e.g. 14":l.token}})}function WDn({html:s,onChange:t,originalHtml:n}){const r=j.useMemo(()=>GDn(s),[s]),[a,i]=j.useState({}),[l,o]=j.useState([]),c=j.useRef(null);c.current===null&&s&&(c.current=n??s);const d=j.useRef(!1);j.useEffect(()=>{if(d.current){d.current=!1;return}i({}),o([])},[s]);const u=()=>{const v=new RegExp(sit.source,"g");let b=0;const w=s.replace(v,S=>{if(!nit(S))return S;const C=(a[b]||"").trim();return b+=1,C||S});w!==s&&(o(S=>[...S,{html:s,values:a}]),d.current=!0,i({}),t(w))},h=()=>{const v=l[l.length-1];v&&(o(b=>b.slice(0,-1)),d.current=!0,i(v.values),t(v.html))},m=()=>{const v=c.current;!v||v===s||(o([]),d.current=!0,i({}),t(v))},f=l.length>0,g=!!c.current&&c.current!==s,x=e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs($,{type:"button",size:"sm",variant:"outline",onClick:h,disabled:!f,children:[e.jsx(cee,{className:"h-3.5 w-3.5 mr-1"}),"Undo last fill"]}),e.jsxs($,{type:"button",size:"sm",variant:"ghost",onClick:m,disabled:!g,children:[e.jsx(Ex,{className:"h-3.5 w-3.5 mr-1"}),"Start over"]})]});if(r.length===0)return e.jsxs("div",{className:"rounded-lg border border-emerald-500/30 bg-emerald-500/5 p-3 space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[e.jsx(qr,{className:"h-4 w-4 text-emerald-600 shrink-0"}),e.jsx("span",{className:"text-muted-foreground",children:"All template fields are filled in. Your name, phone, website and brokerage fill in automatically."})]}),(f||g)&&e.jsxs("div",{className:"flex flex-wrap items-center gap-2 pl-6",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:"Made a typo?"}),x]})]});const y=r.filter(v=>(a[v.index]||"").trim()).length;return e.jsxs("div",{className:"rounded-xl border border-amber-500/40 bg-amber-500/5 p-4 space-y-3",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(wl,{className:"h-4 w-4 text-amber-600 mt-0.5 shrink-0"}),e.jsxs("div",{children:[e.jsx("div",{className:"text-sm font-semibold",children:"Customize before you send"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["This template has ",r.length," field",r.length===1?"":"s"," that only you can fill in (local dates, events, favorite spots). Sending is locked until they're done."]})]})]}),e.jsxs(Be,{variant:"secondary",className:"shrink-0",children:[y,"/",r.length," ready"]})]}),e.jsx("div",{className:"grid grid-cols-1 gap-4",children:r.map(v=>e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{className:"text-[11px] uppercase tracking-wide text-muted-foreground",children:v.label}),e.jsx(pe,{value:a[v.index]||"",placeholder:v.hint,className:"h-10 text-sm",onChange:b=>i(w=>({...w,[v.index]:b.target.value})),onKeyDown:b=>{b.key==="Enter"&&(b.preventDefault(),u())}})]},v.index))}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs($,{type:"button",size:"sm",onClick:u,children:[e.jsx(Xq,{className:"h-3.5 w-3.5 mr-1"}),"Apply to email"]}),x]}),e.jsxs("p",{className:"text-[11px] text-muted-foreground",children:["Typed something wrong? Use ",e.jsx("span",{className:"font-medium",children:"Undo last fill"})," to bring the fields back with your text still in them, or ",e.jsx("span",{className:"font-medium",children:"Start over"})," to restore the original template."]})]})}function a9(){const s=Sa();return tt({queryKey:["custom-tags",s],queryFn:async()=>{const{data:t,error:n}=await q.from("contact_custom_tags").select("*").eq("owner_user_id",s).order("name");if(n)throw n;return t},enabled:!!s})}function KDn(s){return tt({queryKey:["contact-custom-tags",s],queryFn:async()=>{const{data:t,error:n}=await q.from("contact_custom_tag_assignments").select("*, tag:contact_custom_tags(*)").eq("contact_id",s);if(n)throw n;return t},enabled:!!s})}function rit(){const s=Vt(),t=Sa();return ft({mutationFn:async({name:n,color:r})=>{const{data:a,error:i}=await q.from("contact_custom_tags").insert({owner_user_id:t,name:n.trim(),color:r||"#6366F1"}).select().single();if(i)throw i;return a},onSuccess:()=>{s.invalidateQueries({queryKey:["custom-tags"]})}})}function YDn(){const s=Vt();return ft({mutationFn:async t=>{const{error:n}=await q.from("contact_custom_tags").delete().eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["custom-tags"]}),s.invalidateQueries({queryKey:["contact-custom-tags"]}),s.invalidateQueries({queryKey:["all-contact-custom-tags"]})}})}function ZDn(){const s=Vt();return ft({mutationFn:async({id:t,name:n,color:r})=>{const a={};n!==void 0&&(a.name=n.trim()),r!==void 0&&(a.color=r);const{error:i}=await q.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 WXt(){const s=Vt();return ft({mutationFn:async({contactId:t,tagId:n})=>{const{error:r}=await q.from("contact_custom_tag_assignments").insert({contact_id:t,tag_id:n});if(r)throw r},onSuccess:(t,{contactId:n})=>{s.invalidateQueries({queryKey:["contact-custom-tags",n]}),s.invalidateQueries({queryKey:["all-contact-custom-tags"]})}})}function XDn(){const s=Vt();return ft({mutationFn:async({contactId:t,tagId:n})=>{const{error:r}=await q.from("contact_custom_tag_assignments").delete().eq("contact_id",t).eq("tag_id",n);if(r)throw r},onSuccess:(t,{contactId:n})=>{s.invalidateQueries({queryKey:["contact-custom-tags",n]}),s.invalidateQueries({queryKey:["all-contact-custom-tags"]})}})}function Lie(){const s=Sa();return tt({queryKey:["all-contact-custom-tags",s],queryFn:async()=>{const{data:t,error:n}=await q.from("contact_custom_tag_assignments").select("contact_id, tag_id, tag:contact_custom_tags!inner(id, name, color, owner_user_id)").eq("tag.owner_user_id",s);if(n)throw n;return t},staleTime:5*60*1e3,enabled:!!s})}function ait(){const{user:s}=vs();return tt({queryKey:["contact-smart-lists",s==null?void 0:s.id],queryFn:async()=>{const{data:t,error:n}=await q.from("contact_smart_lists").select("*").order("created_at",{ascending:!1});if(n)throw n;return t},enabled:!!s})}function KXt(){const s=Vt(),{user:t}=vs();return ft({mutationFn:async({name:n,filters:r,sort_by:a})=>{const{data:i,error:l}=await q.from("contact_smart_lists").insert({owner_user_id:t.id,name:n,filters:r,sort_by:a}).select().single();if(l)throw l;return i},onSuccess:()=>{s.invalidateQueries({queryKey:["contact-smart-lists"]}),_a({title:"Smart filter saved"})},onError:n=>{_a({title:"Error saving smart filter",description:n.message,variant:"destructive"})}})}function YXt(){const s=Vt();return ft({mutationFn:async t=>{const{error:n}=await q.from("contact_smart_lists").delete().eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["contact-smart-lists"]}),_a({title:"Smart filter deleted"})}})}const dSt=s=>s.replace(/&/g,"&").replace(//g,">").replace(/"/g,""");function uSt(s,t,n,r){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=(n==null?void 0:n.name)||"",d=c.split(/\s+/).filter(Boolean).map(f=>f[0]).join("").slice(0,2).toUpperCase(),u=((n==null?void 0:n.website_url)||"").trim(),h=[n==null?void 0:n.return_address_line1,[n==null?void 0:n.return_address_city,n==null?void 0:n.return_address_state].filter(Boolean).join(", "),n==null?void 0:n.return_address_zip].filter(Boolean).join(" · "),m={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:c,agent_first_name:c.split(" ")[0]||"",agent_initials:d,agent_email:(n==null?void 0:n.email)||"",agent_phone:(n==null?void 0:n.phone)||"",agent_title:(n==null?void 0:n.title)||"",agent_website:u.replace(/^https?:\/\//i,"").replace(/\/$/,""),agent_website_url:u?/^https?:\/\//i.test(u)?u:`https://${u}`:"#",market_city:(n==null?void 0:n.market_city)||t.city||"",brokerage:r||(n==null?void 0:n.brokerage_name)||"",brokerage_address:h,current_date:l,current_year:o};return s.replace(/\{\{\s*(\w+)\s*\}\}/g,(f,g)=>m[g]??`{{${g}}}`)}function QDn(s,t,n,r){const a=t.trim()?`
${dSt(t).replace(/\n/g,"
")}
`:"",i=n.trim()?`
${dSt(n).replace(/\n/g,"
")}
`:"",l=r?`
${r}
`:"";return`${a} ${s} ${i} ${l}`}function JDn(s,t,n){const r=(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 ${n} from your newsletter list.`)}`:"#";return`
${r}${i?" • "+i:""}
${l?`
${l}
`:""}
You're receiving this because ${r} thought you'd find it useful. Unsubscribe
`}const eFn=["free","act now","click here","limited time","urgent","$$$","100% free","guarantee","no obligation","risk-free","winner","cash bonus","make money","earn extra","amazing"];function tFn(s,t){const n=[],r=s.trim();if(r.length>0){r.length<10&&n.push("Subject line is very short — most opened subjects are 30-60 characters."),r.length>90&&n.push("Subject line is very long — many inboxes truncate after 60-70 characters.");const l=r.replace(/[^A-Za-z]/g,""),o=r.replace(/[^A-Z]/g,"");l.length>6&&o.length/l.length>.6&&n.push("Subject is mostly uppercase — this often triggers spam filters."),(r.match(/!/g)||[]).length>=3&&n.push("Too many exclamation marks in the subject.");const d=r.toLowerCase(),u=eFn.filter(h=>d.includes(h));u.length>0&&n.push(`Subject contains spam-trigger words: ${u.slice(0,3).join(", ")}.`)}const a=t.replace(/<[^>]+>/g," ").replace(/\s+/g," ").trim();return a.length<40&&n.push("Email body is very short — add more text so it doesn't look like a spam blast."),(t.match(/0&&a.length<80&&n.push("Email is mostly images with little text — many spam filters block these."),n}function iit({open:s,onOpenChange:t,newsletterId:n,newsletterTitle:r,htmlCode:a}){const{user:i}=vs();yy();const{isReady:l,settings:o}=u6(),{data:c}=oie(),[d,u]=j.useState(!1),h=Sa(),{data:m}=tt({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:vn}=await q.from("profiles").select("name, email, phone, avatar_url, title, email_signature, use_email_signature, website_url, market_city, brokerage_name, return_address_line1, return_address_city, return_address_state, return_address_zip").eq("id",i.id).maybeSingle();return vn}}),[f,g]=j.useState("visual"),[x,y]=j.useState("all"),[v,b]=j.useState(""),[w,S]=j.useState(""),[C,E]=j.useState(""),[I,P]=j.useState(""),[R,D]=j.useState(!0),[O,U]=j.useState([]),[W,V]=j.useState(null),[G,Y]=j.useState(new Set),[X,ae]=j.useState(""),[ie,ne]=j.useState(!1),[te,J]=j.useState(!1),[ce,_e]=j.useState(!1),[he,ue]=j.useState({sent:0,failed:0,total:0,currentName:""}),[ve,Ee]=j.useState(!0),[Se,Le]=j.useState(!1),[Fe,ke]=j.useState([]),[Ve,je]=j.useState(!1),[Ae,Ce]=j.useState(new Set),[qe,ze]=j.useState("now"),[$e,ct]=j.useState(""),{data:Xe=[]}=a9(),{data:it=[]}=Lie(),{data:at=[]}=ait(),{data:Ke=[],isLoading:nt}=tt({queryKey:["newsletter-send-contacts",h],enabled:!!h&&s,queryFn:async()=>{const vn=[];let xs=0;const Lr=1e3;for(;;){const{data:Or,error:ca}=await q.from("innercircle_contacts").select("id, first_name, last_name, email, phone, address, city, state, zip, zip_code").eq("owner_user_id",h).eq("email_opt_out",!1).not("email","is",null).neq("email","").order("first_name").range(xs,xs+Lr-1);if(ca)throw ca;if(!Or||Or.length===0||(vn.push(...Or),Or.length{const{data:vn}=await q.from("ses_suppressed_emails").select("email");return(vn||[]).map(xs=>xs.email.toLowerCase())}}),{data:rt}=tt({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:vn}=await q.from("profiles").select("brokerage_id").eq("id",i.id).maybeSingle();if(!(vn!=null&&vn.brokerage_id))return null;const{data:xs}=await q.from("brokerages").select("name, city, state").eq("id",vn.brokerage_id).maybeSingle();return xs}}),{data:Yt}=tt({queryKey:["newsletter-active-lead-site",h],enabled:!!h&&s,staleTime:5*60*1e3,queryFn:async()=>{if(!h)return null;const{data:vn}=await q.from("lead_sites").select("id, subdomain_slug, mls_provider_id, mls_agent_id, mls_agent_key, is_active").eq("agent_id",h).eq("is_active",!0).not("mls_provider_id","is",null).order("created_at",{ascending:!0}).limit(1).maybeSingle();return vn}}),qt=!!(Yt!=null&&Yt.mls_provider_id),ts=(Yt==null?void 0:Yt.mls_agent_id)||(Yt==null?void 0:Yt.mls_agent_key)||null,{data:ys=[],isLoading:Bt}=tt({queryKey:["newsletter-agent-listings",h,ts],enabled:!!h&&!!ts&&Ve,staleTime:60*1e3,queryFn:async()=>{if(!ts)return[];const{data:vn}=await q.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",ts).eq("standard_status","Active").order("modification_timestamp",{ascending:!1}).limit(30);return vn||[]}}),{data:Ft=[],isLoading:rs}=tt({queryKey:["newsletter-exchange-listings",h],enabled:!!h&&Ve,staleTime:60*1e3,queryFn:async()=>{const{data:vn}=await q.from("listings").select("id, slug, property_address, city, state, price, bedrooms, bathrooms, square_footage, status, created_at").eq("agent_id",h).in("status",["active","coming_soon","office_exclusive","pre_market"]).order("created_at",{ascending:!1}).limit(30),xs=vn||[];if(xs.length===0)return[];const Lr=xs.map(Sr=>Sr.id),{data:Or}=await q.from("listing_photos").select("listing_id, photo_url, is_primary, sort_order").in("listing_id",Lr),ca=new Map,Jn=new Map;for(const Sr of Or||[])Sr.is_primary&&!ca.has(Sr.listing_id)&&ca.set(Sr.listing_id,Sr.photo_url),Jn.has(Sr.listing_id)||Jn.set(Sr.listing_id,Sr.photo_url);return xs.map(Sr=>({...Sr,_photo:ca.get(Sr.id)||Jn.get(Sr.id)||""}))}}),{data:St=!1}=tt({queryKey:["newsletter-exchange-listings-exists",h],enabled:!!h&&s,staleTime:5*60*1e3,queryFn:async()=>{const{count:vn}=await q.from("listings").select("id",{count:"exact",head:!0}).eq("agent_id",h).in("status",["active","coming_soon","office_exclusive","pre_market"]);return(vn||0)>0}}),Xs=j.useMemo(()=>{const vn=new Set(xt);return Ke.filter(xs=>xs.email&&xs.email.includes("@")&&!vn.has(xs.email.toLowerCase()))},[Ke,xt]),vt=j.useMemo(()=>{if(O.length===0)return null;const vn=new Set;for(const xs of it)O.includes(xs.tag_id)&&vn.add(xs.contact_id);return vn},[it,O]),gs=j.useMemo(()=>at.find(vn=>vn.id===W)||null,[at,W]),Ss=j.useMemo(()=>{var vn;if(x==="all")return Xs;if(x==="tags")return vt?Xs.filter(xs=>vt.has(xs.id)):[];if(x==="smartlists"){if(!gs)return[];const xs=(((vn=gs.filters)==null?void 0:vn.search)||"").toLowerCase().trim();return xs?Xs.filter(Lr=>`${Lr.first_name||""} ${Lr.last_name||""}`.toLowerCase().includes(xs)||(Lr.email||"").toLowerCase().includes(xs)):Xs}return Xs.filter(xs=>G.has(xs.id))},[x,Xs,vt,gs,G]),Is=j.useMemo(()=>{if(!X.trim())return Xs;const vn=X.toLowerCase();return Xs.filter(xs=>`${xs.first_name||""} ${xs.last_name||""}`.toLowerCase().includes(vn))},[Xs,X]);j.useEffect(()=>{s&&(b(""),S(`Hi {{first_name}}, Sharing this month's update — hope you find something useful!`),E(`As always, reach out anytime if I can help. Talk soon!`),P(a||""),g("light"),y("all"),U([]),V(null),Y(new Set),ae(""),ne(!1),D(!0),Ee(!0),ke([]),ze("now"),ct(""),ue({sent:0,failed:0,total:0,currentName:""}))},[s,r,a]);const Ys=l,cs=j.useMemo(()=>HDn(I||a||""),[I,a]),js=!!(v.trim()&&Ys&&Ss.length>0&&!te&&cs.length===0),kn=vn=>{const xs=I||a,Lr=R&&(m!=null&&m.email_signature)?m.email_signature:null;let Or;return f==="light"?Or=QDn(xs,w,C,Lr):Or=Lr?`${xs}
${Lr}
`:xs,ve&&(Or+=JDn(m??null,rt??null,vn.email)),uSt(Or,vn,m??null,(rt==null?void 0:rt.name)??null)},Ws=j.useMemo(()=>kn({first_name:"Friend",last_name:"",email:"preview@example.com",phone:"",address:"",city:"",state:"",zip:""}),[f,w,C,I,a,R,m,ve,rt]),On=j.useMemo(()=>tFn(v,f==="advanced"||f==="visual"?I:a),[v,f,I,a]),ds=async()=>{Le(!0),ke([]);try{const vn=f==="advanced"||f==="visual"?I:a,{data:xs,error:Lr}=await q.functions.invoke("generate-newsletter-subjects",{body:{newsletterTitle:r,bodyHtml:vn,currentSubject:v}});if(Lr)throw Lr;const Or=xs==null?void 0:xs.subjects;if(!Array.isArray(Or)||Or.length===0)throw new Error("No subjects returned");ke(Or)}catch(vn){const xs=(vn==null?void 0:vn.message)||"Failed to generate subjects";xs.includes("credits exhausted")||xs.includes("402")?re.error("AI credits exhausted. Please add credits to your workspace."):xs.includes("Rate limit")||xs.includes("429")?re.error("Rate limit hit — try again in a moment."):re.error(xs)}finally{Le(!1)}},gn=vn=>vn?"$"+Number(vn).toLocaleString("en-US"):"",As=()=>{var Jn,Sr;if(Ae.size===0){re.error("Pick at least one listing first.");return}const vn=(Yt==null?void 0:Yt.subdomain_slug)||"",xs=vn?`https://${vn}.relevelup.com`:"https://relevelup.com",Lr=[];for(const Un of ys){const ur=`mls:${Un.listing_key}`;if(!Ae.has(ur))continue;const Pa=Array.isArray(Un.photos)&&Un.photos.length>0?typeof Un.photos[0]=="string"?Un.photos[0]:((Jn=Un.photos[0])==null?void 0:Jn.MediaURL)||((Sr=Un.photos[0])==null?void 0:Sr.url)||"":"",ii=Un.bedrooms?`${Un.bedrooms} bd`:"",$i=Un.bathrooms_total?`${Un.bathrooms_total} ba`:"",Rn=Un.living_area?`${Number(Un.living_area).toLocaleString()} sqft`:"";Lr.push({url:`${xs}/listings/${Un.listing_key}`,photo:Pa,price:gn(Un.list_price),addr:`${Un.address||""}${Un.city?", "+Un.city:""}`,stats:[ii,$i,Rn].filter(Boolean).join(" • ")})}for(const Un of Ft){const ur=`ex:${Un.id}`;if(!Ae.has(ur))continue;const Pa=Un.bedrooms?`${Un.bedrooms} bd`:"",ii=Un.bathrooms?`${Un.bathrooms} ba`:"",$i=Un.square_footage?`${Number(Un.square_footage).toLocaleString()} sqft`:"";Lr.push({url:`https://listings.relevelup.com/${Un.slug||Un.id}`,photo:Un._photo||"",price:gn(Un.price),addr:`${Un.property_address||""}${Un.city?", "+Un.city:""}`,stats:[Pa,ii,$i].filter(Boolean).join(" • ")})}const ca=`

Featured Listings

${Lr.map(Un=>`
${Un.photo?`${Un.addr}`:""}
${Un.price}
${Un.addr}
${Un.stats}
`.trim()).join(` `)}
`.trim();P(Un=>(Un||a||"")+` `+ca),g("visual"),Ce(new Set),je(!1),re.success(`Added ${Lr.length} listing${Lr.length===1?"":"s"} to your newsletter.`)},hr=()=>kn({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}}"),Er=()=>uSt(v,{first_name:"__FN__",last_name:"__LN__",email:"__EM__",name:"__NAME__",phone:"__PHONE__",address:"__ADDR__",city:"__CITY__",state:"__STATE__",zip:"__ZIP__"},m??null,(rt==null?void 0:rt.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}}"),qn=()=>{if(cs.length>0){re.error(`Fill in ${cs.length} template field${cs.length===1?"":"s"} before sending.`);return}if(js){if(qe==="later"){if(!$e){re.error("Pick a date and time to schedule.");return}const vn=new Date($e).getTime();if(Number.isNaN(vn)||vn{if(!(!js||!i)){_e(!1),J(!0),ue({sent:0,failed:0,total:Ss.length,currentName:"Preparing campaign…"});try{const xs=`${((o==null?void 0:o.display_name)||"ReLevelUp").toLowerCase().replace(/[^a-z]/g,".")}@send.relevelup.com`,Lr=hr(),Or=Er(),ca=qe==="later",{data:Jn,error:Sr}=await q.from("email_campaigns").insert({user_id:h||i.id,name:`Newsletter: ${r}`,subject:Or,body_html:Lr,from_email:xs,reply_to_email:(o==null?void 0:o.reply_to_email)||null,total_recipients:Ss.length,status:ca?"scheduled":"draft",scheduled_at:ca?new Date($e).toISOString():null}).select("id").single();if(Sr)throw Sr;ue(ur=>({...ur,currentName:"Adding recipients…"}));const Un=Ss.map(ur=>({campaign_id:Jn.id,contact_id:ur.id,email:ur.email,name:[ur.first_name,ur.last_name].filter(Boolean).join(" ")||null,status:"pending"}));for(let ur=0;ur({...$i,sent:Math.min(ur+Pa.length,Un.length)}))}if(ca){const{error:ur}=await q.functions.invoke("ses-schedule-campaign",{body:{action:"schedule",campaign_id:Jn.id}});if(ur)throw ur;re.success(`Newsletter scheduled for ${new Date($e).toLocaleString()}.`)}else{const{error:ur}=await q.functions.invoke("ses-send-campaign",{body:{action:"send_campaign",campaign_id:Jn.id}});if(ur)throw ur;re.success(`Sending to ${Ss.length} contact${Ss.length===1?"":"s"}! Open & click tracking will appear in Sent Emails.`)}t(!1)}catch(vn){console.error("Newsletter send failed:",vn),re.error(`Failed to send: ${vn.message||"Unknown error"}`)}finally{J(!1)}}},Fn=vn=>{Y(xs=>{const Lr=new Set(xs);return Lr.has(vn)?Lr.delete(vn):Lr.add(vn),Lr})};return e.jsxs(zs,{open:s,onOpenChange:vn=>!te&&t(vn),children:[e.jsxs(Os,{className:"max-w-5xl max-h-[92vh] overflow-y-auto",children:[e.jsx(Us,{children:e.jsxs(Bs,{className:"flex items-center gap-2",children:[e.jsx(Yr,{className:"h-5 w-5"})," Send Newsletter"]})}),!Ys&&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(ll,{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($,{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(ee,{children:"Subject"}),e.jsxs($,{type:"button",variant:"ghost",size:"sm",className:"h-7 gap-1 text-xs",onClick:ds,disabled:Se,title:"Generate subject lines with AI",children:[Se?e.jsx(kt,{className:"h-3 w-3 animate-spin"}):e.jsx(Nn,{className:"h-3 w-3"}),"AI Suggestions"]})]}),e.jsx(pe,{value:v,onChange:vn=>b(vn.target.value),placeholder:"Newsletter subject"}),Fe.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:"}),Fe.map((vn,xs)=>e.jsxs("button",{type:"button",onClick:()=>{b(vn),ke([])},className:"w-full text-left text-sm px-2 py-1.5 rounded hover:bg-primary/10 transition-colors",children:[e.jsx(Nn,{className:"h-3 w-3 inline-block mr-1.5 text-primary"}),vn]},xs))]}),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}}"})]})]}),On.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(aV,{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:On.map((vn,xs)=>e.jsx("li",{children:vn},xs))})]}),(qt||St)&&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(va,{className:"h-3.5 w-3.5 text-primary"}),"Insert your active listings"]}),e.jsx("p",{className:"text-muted-foreground mt-0.5",children:qt&&St?"Pick from your live MLS listings or your Listing Exchange listings.":qt?"Pick from your live MLS listings and drop them into the email.":"Pick from your Listing Exchange listings and drop them into the email."})]}),e.jsx($,{type:"button",size:"sm",variant:"outline",onClick:()=>je(!0),children:"Choose listings"})]}),e.jsx(WDn,{html:I||a||"",originalHtml:a||"",onChange:P}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Editing"}),e.jsxs(ha,{value:f,onValueChange:vn=>g(vn),children:[e.jsxs(ma,{className:"grid grid-cols-3 w-full",children:[e.jsxs(Zt,{value:"visual",children:[e.jsx(sy,{className:"h-3 w-3 mr-1"}),"Visual"]}),e.jsxs(Zt,{value:"light",children:[e.jsx(Jr,{className:"h-3 w-3 mr-1"}),"Quick edit"]}),e.jsxs(Zt,{value:"advanced",children:[e.jsx(n4,{className:"h-3 w-3 mr-1"}),"HTML"]})]}),e.jsx(Xt,{value:"visual",className:"mt-3",children:e.jsx(tit,{html:I,onChange:P})}),e.jsxs(Xt,{value:"light",className:"space-y-3 mt-3",children:[e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs text-muted-foreground",children:"Personal intro (above newsletter)"}),e.jsx(Rs,{value:w,onChange:vn=>S(vn.target.value),rows:4,placeholder:"Hi {{first_name}}, ..."})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs text-muted-foreground",children:"Personal outro (below newsletter)"}),e.jsx(Rs,{value:C,onChange:vn=>E(vn.target.value),rows:3,placeholder:"Talk soon!"})]})]}),e.jsxs(Xt,{value:"advanced",className:"mt-3",children:[e.jsx(ee,{className:"text-xs text-muted-foreground",children:"Edit full HTML"}),e.jsx(Rs,{value:I,onChange:vn=>P(vn.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:m!=null&&m.email_signature?"Will append the signature from your profile.":"No signature set. Add one in Profile → Email Signature."})]}),e.jsx(Sn,{checked:R&&!!(m!=null&&m.email_signature),disabled:!(m!=null&&m.email_signature),onCheckedChange:D})]}),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(Sn,{checked:ve,onCheckedChange:Ee})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Recipients"}),e.jsxs(ha,{value:x,onValueChange:vn=>y(vn),children:[e.jsxs(ma,{className:"grid grid-cols-4 w-full",children:[e.jsxs(Zt,{value:"all",children:[e.jsx(Zn,{className:"h-3 w-3 mr-1"}),"All"]}),e.jsxs(Zt,{value:"tags",children:[e.jsx(Ap,{className:"h-3 w-3 mr-1"}),"Tags"]}),e.jsxs(Zt,{value:"smartlists",children:[e.jsx(DJ,{className:"h-3 w-3 mr-1"}),"Lists"]}),e.jsxs(Zt,{value:"individual",children:[e.jsx(sl,{className:"h-3 w-3 mr-1"}),"Pick"]})]}),e.jsx(Xt,{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:Xs.length})," contact",Xs.length===1?"":"s"," with a valid, non-suppressed email."]})}),e.jsxs(Xt,{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(uo,{className:"h-40 rounded-lg border p-2",children:Xe.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."}):Xe.map(vn=>e.jsxs("label",{className:"flex items-center gap-2 p-1.5 hover:bg-muted rounded cursor-pointer",children:[e.jsx(ai,{checked:O.includes(vn.id),onCheckedChange:xs=>U(Lr=>xs?[...Lr,vn.id]:Lr.filter(Or=>Or!==vn.id))}),e.jsx("span",{className:"inline-block h-2 w-2 rounded-full",style:{background:vn.color||"#406E71"}}),e.jsx("span",{className:"text-sm",children:vn.name})]},vn.id))})]}),e.jsxs(Xt,{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(uo,{className:"h-40 rounded-lg border p-2",children:at.length===0?e.jsx("p",{className:"text-xs text-muted-foreground p-2",children:"No smart lists yet. Save one from the contacts page."}):at.map(vn=>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:W===vn.id,onChange:()=>V(vn.id)}),e.jsx("span",{className:"text-sm",children:vn.name})]},vn.id))})]}),e.jsxs(Xt,{value:"individual",className:"mt-3 space-y-2",children:[e.jsx(pe,{placeholder:"Search contacts...",value:X,onChange:vn=>ae(vn.target.value)}),e.jsxs("div",{className:"flex items-center justify-between text-xs text-muted-foreground",children:[e.jsxs("span",{children:[G.size," selected"]}),e.jsx("button",{type:"button",className:"underline",onClick:()=>Y(new Set),children:"Clear"})]}),e.jsxs(uo,{className:"h-48 rounded-lg border p-2",children:[nt&&e.jsx("p",{className:"text-xs text-muted-foreground p-2",children:"Loading contacts…"}),!nt&&Is.length===0&&e.jsx("p",{className:"text-xs text-muted-foreground p-2",children:"No matching contacts."}),Is.slice(0,200).map(vn=>e.jsxs("label",{className:"flex items-center gap-2 p-1.5 hover:bg-muted rounded cursor-pointer",children:[e.jsx(ai,{checked:G.has(vn.id),onCheckedChange:()=>Fn(vn.id)}),e.jsxs("div",{className:"text-sm flex-1 min-w-0",children:[e.jsxs("div",{className:"truncate",children:[vn.first_name," ",vn.last_name||""]}),e.jsx("div",{className:"text-xs text-muted-foreground truncate",children:vn.email})]})]},vn.id)),Is.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(Be,{variant:"secondary",className:"gap-1",children:[e.jsx(qr,{className:"h-3 w-3"})," ",Ss.length," recipient",Ss.length===1?"":"s"]}),Ys&&e.jsxs(Be,{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(ee,{children:"Preview"}),e.jsx($,{variant:"ghost",size:"sm",onClick:()=>ne(vn=>!vn),children:ie?e.jsxs(e.Fragment,{children:[e.jsx($g,{className:"h-3 w-3 mr-1"}),"Hide"]}):e.jsxs(e.Fragment,{children:[e.jsx(Ca,{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:Ws,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)."]})]})]}),te&&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(kt,{className:"h-4 w-4 animate-spin"}),"Sending to ",he.currentName||"..."]}),e.jsxs("span",{className:"text-muted-foreground",children:[he.sent+he.failed," / ",he.total]})]}),e.jsx(Yi,{value:he.total?(he.sent+he.failed)/he.total*100:0}),he.failed>0&&e.jsxs("p",{className:"text-xs text-destructive",children:[he.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(da,{className:"h-4 w-4"})," When to send"]}),e.jsxs(kw,{value:qe,onValueChange:vn=>ze(vn),className:"flex flex-col sm:flex-row gap-3",children:[e.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[e.jsx(Ym,{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(Ym,{value:"later",id:"send-later"}),e.jsxs("span",{className:"text-sm flex items-center gap-1",children:[e.jsx(Au,{className:"h-3.5 w-3.5"})," Schedule for later"]})]}),qe==="later"&&e.jsx(pe,{type:"datetime-local",value:$e,onChange:vn=>ct(vn.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:cs.length>0?`${cs.length} template field${cs.length===1?"":"s"} still need${cs.length===1?"s":""} your input before this can go out.`:"Suppressed/unsubscribed contacts are skipped automatically. Open & click tracking is included."}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx($,{variant:"outline",onClick:()=>t(!1),disabled:te,children:"Cancel"}),e.jsx($,{onClick:qn,disabled:!js,children:te?e.jsxs(e.Fragment,{children:[e.jsx(kt,{className:"h-4 w-4 mr-1 animate-spin"}),"Working…"]}):qe==="later"?e.jsxs(e.Fragment,{children:[e.jsx(Au,{className:"h-4 w-4 mr-1"}),"Schedule for ",Ss.length]}):e.jsxs(e.Fragment,{children:[e.jsx(Yr,{className:"h-4 w-4 mr-1"}),"Send to ",Ss.length]})})]})]})]})]}),e.jsx(kc,{open:ce,onOpenChange:_e,children:e.jsxs(cc,{children:[e.jsxs(dc,{children:[e.jsx(hc,{children:qe==="later"?"Schedule newsletter?":"Send newsletter?"}),e.jsxs(mc,{children:[qe==="later"?"Schedule ":"Send ",e.jsxs("span",{className:"font-medium text-foreground",children:['"',v,'"']})," to"," ",e.jsxs("span",{className:"font-medium text-foreground",children:[Ss.length," contact",Ss.length===1?"":"s"]}),qe==="later"&&$e?` for ${new Date($e).toLocaleString()}`:"","? Suppressed and unsubscribed contacts are skipped automatically."]})]}),e.jsxs(uc,{children:[e.jsx(fc,{children:"Cancel"}),e.jsx(tc,{onClick:hn,children:qe==="later"?e.jsxs(e.Fragment,{children:[e.jsx(Au,{className:"h-4 w-4 mr-1"}),"Schedule"]}):e.jsxs(e.Fragment,{children:[e.jsx(Yr,{className:"h-4 w-4 mr-1"}),"Send to ",Ss.length]})})]})]})}),e.jsx(zs,{open:Ve,onOpenChange:je,children:e.jsxs(Os,{className:"max-w-2xl max-h-[85vh] overflow-y-auto",children:[e.jsx(Us,{children:e.jsxs(Bs,{className:"flex items-center gap-2",children:[e.jsx(va,{className:"h-5 w-5"})," Choose listings to insert"]})}),e.jsxs("div",{className:"space-y-4",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Pick up to 6 listings. They'll be added as an email-safe grid."}),(Bt||rs)&&e.jsxs("div",{className:"text-sm text-muted-foreground p-6 text-center",children:[e.jsx(kt,{className:"h-4 w-4 animate-spin inline-block mr-2"}),"Loading your listings…"]}),!Bt&&!rs&&ys.length===0&&Ft.length===0&&e.jsx("div",{className:"rounded-lg border bg-muted/30 p-6 text-center text-sm text-muted-foreground",children:"No listings found. Add a listing on the Listing Exchange or connect your MLS to get started."}),ys.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"text-[11px] font-semibold uppercase tracking-wide text-muted-foreground",children:"From your MLS"}),e.jsx("div",{className:"grid grid-cols-2 gap-3",children:ys.map(vn=>{var ca,Jn;const xs=`mls:${vn.listing_key}`,Lr=Ae.has(xs),Or=Array.isArray(vn.photos)&&vn.photos.length>0?typeof vn.photos[0]=="string"?vn.photos[0]:((ca=vn.photos[0])==null?void 0:ca.MediaURL)||((Jn=vn.photos[0])==null?void 0:Jn.url)||"":"";return e.jsxs("button",{type:"button",onClick:()=>{Ce(Sr=>{const Un=new Set(Sr);return Un.has(xs)?Un.delete(xs):Un.size<6?Un.add(xs):re.error("Max 6 listings per newsletter"),Un})},className:`relative rounded-lg border-2 overflow-hidden text-left transition-all ${Lr?"border-primary ring-2 ring-primary/30":"border-border hover:border-primary/50"}`,children:[Or&&e.jsx("img",{src:Or,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:vn.list_price?`$${Number(vn.list_price).toLocaleString()}`:""}),e.jsx("div",{className:"text-xs truncate",children:vn.address}),e.jsxs("div",{className:"text-[11px] text-muted-foreground truncate",children:[vn.city,vn.state?`, ${vn.state}`:""]})]}),Lr&&e.jsx("div",{className:"absolute top-1 right-1 bg-primary text-primary-foreground rounded-full p-0.5",children:e.jsx(qr,{className:"h-4 w-4"})})]},xs)})})]}),Ft.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"text-[11px] font-semibold uppercase tracking-wide text-muted-foreground",children:"From your Listing Exchange"}),e.jsx("div",{className:"grid grid-cols-2 gap-3",children:Ft.map(vn=>{const xs=`ex:${vn.id}`,Lr=Ae.has(xs);return e.jsxs("button",{type:"button",onClick:()=>{Ce(Or=>{const ca=new Set(Or);return ca.has(xs)?ca.delete(xs):ca.size<6?ca.add(xs):re.error("Max 6 listings per newsletter"),ca})},className:`relative rounded-lg border-2 overflow-hidden text-left transition-all ${Lr?"border-primary ring-2 ring-primary/30":"border-border hover:border-primary/50"}`,children:[vn._photo&&e.jsx("img",{src:vn._photo,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:vn.price?`$${Number(vn.price).toLocaleString()}`:""}),e.jsx("div",{className:"text-xs truncate",children:vn.property_address}),e.jsxs("div",{className:"text-[11px] text-muted-foreground truncate",children:[vn.city,vn.state?`, ${vn.state}`:""]})]}),Lr&&e.jsx("div",{className:"absolute top-1 right-1 bg-primary text-primary-foreground rounded-full p-0.5",children:e.jsx(qr,{className:"h-4 w-4"})})]},xs)})})]})]}),e.jsxs(Ar,{children:[e.jsx($,{variant:"outline",onClick:()=>je(!1),children:"Cancel"}),e.jsxs($,{onClick:As,disabled:Ae.size===0,children:["Insert ",Ae.size>0?Ae.size:""," listing",Ae.size===1?"":"s"]})]})]})}),e.jsx(S6e,{open:d,onOpenChange:u,hasPending:!!(c!=null&&c.hasPendingSes),pendingEmails:c==null?void 0:c.pendingEmails})]})}function sFn(){const{user:s}=vs(),t=Vt(),[n,r]=j.useState("starters"),[a,i]=j.useState(!1),[l,o]=j.useState(null),[c,d]=j.useState(null),[u,h]=j.useState(null),{data:m,isLoading:f}=tt({queryKey:["agent-custom-newsletters",s==null?void 0:s.id],enabled:!!(s!=null&&s.id),queryFn:async()=>{const{data:I,error:P}=await q.from("agent_custom_newsletters").select("*").order("updated_at",{ascending:!1});if(P)throw P;return I||[]}}),g=()=>t.invalidateQueries({queryKey:["agent-custom-newsletters"]}),x=(m==null?void 0:m.filter(I=>I.user_id===(s==null?void 0:s.id)&&!I.is_template))??[],y=(m==null?void 0:m.filter(I=>I.user_id===(s==null?void 0:s.id)&&I.is_template))??[],v=(m==null?void 0:m.filter(I=>I.user_id!==(s==null?void 0:s.id)&&I.is_template&&(I.share_scope==="team"||I.share_scope==="brokerage"||I.share_scope==="global")))??[],b=(m==null?void 0:m.filter(I=>I.share_scope==="global"&&I.is_template))??[],w=n==="starters"?b:n==="mine"?x:n==="templates"?y:v.filter(I=>I.share_scope!=="global"),S=async I=>{if(!s)return;const{error:P}=await q.from("agent_custom_newsletters").insert({user_id:s.id,title:`${I.title} (Copy)`,description:I.description,html_content:I.html_content,is_template:!1,share_scope:"private"});if(P){re.error(P.message);return}re.success('Duplicated to "My Newsletters"'),g(),r("mine")},C=async I=>{const{error:P}=await q.from("agent_custom_newsletters").delete().eq("id",I);if(P){re.error(P.message);return}re.success("Deleted"),h(null),g()},E=I=>I.share_scope==="global"?e.jsxs(Be,{variant:"secondary",className:"gap-1",children:[e.jsx(Nn,{className:"h-3 w-3"}),"Starter"]}):I.share_scope==="brokerage"?e.jsxs(Be,{variant:"secondary",className:"gap-1",children:[e.jsx(ji,{className:"h-3 w-3"}),"Brokerage"]}):I.share_scope==="team"?e.jsxs(Be,{variant:"secondary",className:"gap-1",children:[e.jsx(Zn,{className:"h-3 w-3"}),"Team"]}):e.jsxs(Be,{variant:"outline",className:"gap-1 text-muted-foreground",children:[e.jsx(pc,{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($,{variant:n==="starters"?"default":"outline",size:"sm",onClick:()=>r("starters"),className:"gap-1.5",children:[e.jsx(Nn,{className:"h-3.5 w-3.5"}),"Starter Templates (",b.length,")"]}),e.jsxs($,{variant:n==="mine"?"default":"outline",size:"sm",onClick:()=>r("mine"),children:["My Newsletters (",x.length,")"]}),e.jsxs($,{variant:n==="templates"?"default":"outline",size:"sm",onClick:()=>r("templates"),children:["My Templates (",y.length,")"]}),e.jsxs($,{variant:n==="shared"?"default":"outline",size:"sm",onClick:()=>r("shared"),children:["Shared with Me (",v.filter(I=>I.share_scope!=="global").length,")"]})]}),e.jsxs($,{onClick:()=>{o(null),i(!0)},children:[e.jsx(dn,{className:"h-4 w-4 mr-1.5"})," Create Newsletter"]})]}),f&&e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4",children:[...Array(3)].map((I,P)=>e.jsx(yn,{className:"h-48 w-full"},P))}),n==="starters"&&!f&&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(Nn,{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.']})]}),!f&&w.length===0&&e.jsx(Ne,{children:e.jsxs(Ie,{className:"py-12 text-center text-muted-foreground",children:[e.jsx(Jr,{className:"h-10 w-10 mx-auto mb-3 opacity-50"}),n==="starters"&&e.jsx("p",{children:"No starter templates available yet."}),n==="mine"&&e.jsx("p",{children:`You haven't created any newsletters yet. Try a Starter Template or click "Create Newsletter"!`}),n==="templates"&&e.jsx("p",{children:`You haven't saved any templates yet. Toggle "Save as reusable template" when creating a newsletter.`}),n==="shared"&&e.jsx("p",{children:"No team or brokerage templates have been shared with you yet."})]})}),!f&&w.length>0&&e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4",children:w.map(I=>{const P=I.user_id===(s==null?void 0:s.id);return e.jsxs(Ne,{className:"overflow-hidden hover:shadow-md transition-shadow",children:[e.jsxs("div",{className:"aspect-[3/2] bg-muted relative overflow-hidden",children:[I.thumbnail_url?e.jsx("img",{src:I.thumbnail_url,alt:I.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:`
${I.html_content}
`}}),e.jsxs("div",{className:"absolute top-2 right-2 flex gap-1",children:[I.is_template&&e.jsx(Be,{className:"bg-primary/90",children:"Template"}),E(I)]})]}),e.jsxs(Ie,{className:"p-3 space-y-2",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"font-semibold line-clamp-1",children:I.title}),I.description&&e.jsx("p",{className:"text-xs text-muted-foreground line-clamp-1",children:I.description}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-0.5",children:["Updated ",en(new Date(I.updated_at||I.created_at),"MMM d, yyyy")]})]}),e.jsxs("div",{className:"flex gap-1.5 flex-wrap",children:[e.jsxs($,{size:"sm",onClick:()=>d(I),className:"flex-1 min-w-[80px]",children:[e.jsx(Yr,{className:"h-3.5 w-3.5 mr-1"})," Send"]}),P?e.jsxs(e.Fragment,{children:[e.jsx($,{size:"sm",variant:"outline",onClick:()=>{o(I),i(!0)},children:e.jsx(gi,{className:"h-3.5 w-3.5"})}),e.jsx($,{size:"sm",variant:"outline",onClick:()=>S(I),children:e.jsx(Ha,{className:"h-3.5 w-3.5"})}),e.jsx($,{size:"sm",variant:"outline",onClick:()=>h(I.id),children:e.jsx(Wn,{className:"h-3.5 w-3.5"})})]}):e.jsxs($,{size:"sm",variant:"outline",onClick:()=>S(I),children:[e.jsx(Ha,{className:"h-3.5 w-3.5 mr-1"})," Use"]})]})]})]},I.id)})}),e.jsx(UDn,{open:a,onOpenChange:i,initial:l,onSaved:g}),c&&e.jsx(iit,{open:!!c,onOpenChange:I=>!I&&d(null),newsletterId:c.id,newsletterTitle:c.title,htmlCode:c.html_content}),e.jsx(kc,{open:!!u,onOpenChange:I=>!I&&h(null),children:e.jsxs(cc,{children:[e.jsxs(dc,{children:[e.jsx(hc,{children:"Delete this newsletter?"}),e.jsx(mc,{children:"This cannot be undone."})]}),e.jsxs(uc,{children:[e.jsx(fc,{children:"Cancel"}),e.jsx(tc,{onClick:()=>u&&C(u),children:"Delete"})]})]})})]})}function nFn(){const s=Qn(),[t,n]=j.useState(""),[r,a]=j.useState("grid"),[i,l]=j.useState(null),{data:o,isLoading:c}=tt({queryKey:["newsletters"],queryFn:async()=>{const{data:C,error:E}=await q.from("newsletter_content").select("*").eq("is_published",!0).order("publish_date",{ascending:!1});if(E)throw E;return C}}),{data:d}=tt({queryKey:["newsletter-likes-all"],queryFn:async()=>{const{data:C}=await q.from("newsletter_likes").select("newsletter_id");return C||[]}}),{data:u}=tt({queryKey:["newsletter-comments-all"],queryFn:async()=>{const{data:C}=await q.from("newsletter_comments").select("newsletter_id");return C||[]}}),{data:h}=tt({queryKey:["newsletter-resource-counts"],queryFn:async()=>{const[C,E,I,P]=await Promise.all([q.from("newsletter_canva_links").select("newsletter_id"),q.from("newsletter_pdfs").select("newsletter_id"),q.from("newsletter_videos").select("newsletter_id"),q.from("newsletter_drive_links").select("newsletter_id")]);return{canva:C.data||[],pdfs:E.data||[],videos:I.data||[],drives:P.data||[]}}}),m=C=>(d==null?void 0:d.filter(E=>E.newsletter_id===C).length)||0,f=C=>(u==null?void 0:u.filter(E=>E.newsletter_id===C).length)||0,g=C=>{var E;return((E=h==null?void 0:h.canva)==null?void 0:E.filter(I=>I.newsletter_id===C).length)||0},x=C=>{var E;return((E=h==null?void 0:h.pdfs)==null?void 0:E.filter(I=>I.newsletter_id===C).length)||0},y=C=>{var E;return((E=h==null?void 0:h.videos)==null?void 0:E.filter(I=>I.newsletter_id===C).length)||0},v=C=>{var E;return((E=h==null?void 0:h.drives)==null?void 0:E.filter(I=>I.newsletter_id===C).length)||0},b=C=>g(C)+x(C)+y(C)+v(C),w=o==null?void 0:o.filter(C=>{var E;return C.title.toLowerCase().includes(t.toLowerCase())||((E=C.description)==null?void 0:E.toLowerCase().includes(t.toLowerCase()))}),S=C=>{s(`/newsletters/${C}`)};return e.jsx(Vs,{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(ha,{defaultValue:"custom",className:"space-y-4",children:[e.jsxs(ma,{children:[e.jsx(Zt,{value:"custom",children:"Build & Send"}),e.jsx(Zt,{value:"curated",children:"Curated Monthly"})]}),e.jsx(Xt,{value:"custom",className:"mt-2",children:e.jsx(sFn,{})}),e.jsxs(Xt,{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(Kr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(pe,{placeholder:"Search newsletters...",value:t,onChange:C=>n(C.target.value),className:"pl-9"})]}),e.jsxs("div",{className:"flex gap-2",children:[t&&e.jsx($,{variant:"outline",size:"sm",onClick:()=>n(""),children:"Clear"}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx($,{variant:r==="grid"?"secondary":"outline",size:"icon",onClick:()=>a("grid"),className:"rounded-full",children:e.jsx(Qf,{className:"h-4 w-4"})}),e.jsx($,{variant:r==="list"?"secondary":"outline",size:"icon",onClick:()=>a("list"),className:"rounded-full",children:e.jsx(P0,{className:"h-4 w-4"})})]})]})]}),e.jsxs("div",{className:"text-sm text-muted-foreground",children:[(w==null?void 0:w.length)||0," item",(w==null?void 0:w.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((C,E)=>e.jsx(Ne,{children:e.jsxs(Ie,{className:"p-0",children:[e.jsx(yn,{className:"aspect-[3/2] w-full"}),e.jsxs("div",{className:"p-4 space-y-2",children:[e.jsx(yn,{className:"h-5 w-3/4"}),e.jsx(yn,{className:"h-4 w-full"})]})]})},E))}),!c&&(w==null?void 0:w.length)===0&&e.jsxs("div",{className:"text-center py-12",children:[e.jsx(Jr,{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($,{variant:"outline",onClick:()=>n(""),children:"Clear Search"})]}),!c&&w&&w.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-3",children:w.map(C=>{const E=b(C.id),I=g(C.id),P=x(C.id),R=y(C.id);return r==="grid"?e.jsxs(Ne,{className:"group overflow-hidden hover:shadow-lg transition-all duration-200 cursor-pointer border-border/50",onClick:()=>S(C.id),children:[e.jsx("div",{className:"relative overflow-hidden bg-muted aspect-[3/2]",children:C.preview_image_url?e.jsx("img",{src:C.preview_image_url,alt:C.title,className:"w-full h-full object-contain group-hover:scale-105 transition-transform duration-300"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center text-muted-foreground",children:e.jsx(Jr,{className:"h-16 w-16"})})}),e.jsxs(Ie,{className:"p-4 space-y-3",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"font-semibold text-foreground line-clamp-1",children:C.title}),e.jsxs("div",{className:"flex items-center gap-1.5 mt-1 text-xs text-muted-foreground",children:[e.jsx(Ta,{className:"h-3 w-3"}),en(new Date(C.publish_date),"MMM d, yyyy")]})]}),C.description&&e.jsx("p",{className:"text-sm text-muted-foreground line-clamp-2",children:C.description.replace(/<[^>]*>/g,"")}),E>0&&e.jsxs("div",{className:"flex flex-wrap gap-1.5",children:[I>0&&e.jsxs(Be,{variant:"secondary",className:"text-xs gap-1 font-normal",children:[e.jsx(Yc,{className:"h-3 w-3"})," ",I," Template",I>1?"s":""]}),P>0&&e.jsxs(Be,{variant:"secondary",className:"text-xs gap-1 font-normal",children:[e.jsx(di,{className:"h-3 w-3"})," ",P," PDF",P>1?"s":""]}),R>0&&e.jsxs(Be,{variant:"secondary",className:"text-xs gap-1 font-normal",children:[e.jsx(Bu,{className:"h-3 w-3"})," ",R," Video",R>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(Vy,{className:"h-3 w-3"})," ",m(C.id)]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Th,{className:"h-3 w-3"})," ",f(C.id)]})]}),C.html_code&&e.jsxs($,{size:"sm",className:"w-full bg-gradient-to-r from-[#2a4c64] to-[#406E71] text-white hover:opacity-90",onClick:D=>{D.stopPropagation(),l(C)},children:[e.jsx(Yr,{className:"h-4 w-4 mr-1.5"}),"Send Newsletter"]})]})]},C.id):e.jsx(Ne,{className:"group overflow-hidden hover:shadow-md transition-all duration-200 cursor-pointer border-border/50",onClick:()=>S(C.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:C.preview_image_url?e.jsx("img",{src:C.preview_image_url,alt:C.title,className:"w-full h-full object-contain group-hover:scale-105 transition-transform duration-300"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center text-muted-foreground min-h-[100px]",children:e.jsx(Jr,{className:"h-10 w-10"})})}),e.jsxs(Ie,{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:C.title}),e.jsxs("div",{className:"flex items-center gap-1.5 mt-0.5 text-xs text-muted-foreground",children:[e.jsx(Ta,{className:"h-3 w-3"}),en(new Date(C.publish_date),"MMM d, yyyy")]})]}),C.description&&e.jsx("p",{className:"text-sm text-muted-foreground line-clamp-1",children:C.description.replace(/<[^>]*>/g,"")}),e.jsxs("div",{className:"flex items-center gap-4 text-xs text-muted-foreground",children:[E>0&&e.jsxs("span",{children:[E," resource",E>1?"s":""]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Vy,{className:"h-3 w-3"})," ",m(C.id)]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Th,{className:"h-3 w-3"})," ",f(C.id)]})]})]}),C.html_code&&e.jsx("div",{className:"p-3 flex items-center shrink-0",children:e.jsxs($,{size:"sm",className:"bg-gradient-to-r from-[#2a4c64] to-[#406E71] text-white hover:opacity-90",onClick:D=>{D.stopPropagation(),l(C)},children:[e.jsx(Yr,{className:"h-4 w-4 mr-1.5"}),"Send"]})})]})},C.id)})})]})]}),(i==null?void 0:i.html_code)&&e.jsx(iit,{open:!!i,onOpenChange:C=>!C&&l(null),newsletterId:i.id,newsletterTitle:i.title,htmlCode:i.html_code})]})})}function rFn({rows:s}){if(!s||s.length===0)return null;const t=s.filter(n=>n.columns.some(r=>r.title||r.description||r.image_url));return t.length===0?null:e.jsx("div",{className:"space-y-6",children:t.map((n,r)=>{const a=n.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(Ne,{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(Ie,{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))},r)})})}function aFn(){const{id:s}=Wi(),t=Qn(),{user:n}=vs(),{toast:r}=Bi(),a=Vt(),{trackEngagement:i}=gK(),[l,o]=j.useState(""),[c,d]=j.useState(!1),{data:u,isLoading:h}=tt({queryKey:["newsletter",s],queryFn:async()=>{const{data:I,error:P}=await q.from("newsletter_content").select("*").eq("id",s).single();if(P)throw P;return I},enabled:!!s});j.useEffect(()=>{u&&i("newsletter",u.id,u.title,"view")},[u==null?void 0:u.id]);const{data:m}=tt({queryKey:["newsletter-drives",s],queryFn:async()=>{const{data:I}=await q.from("newsletter_drive_links").select("*").eq("newsletter_id",s).order("sort_order");return I||[]},enabled:!!s}),{data:f}=tt({queryKey:["newsletter-pdfs",s],queryFn:async()=>{const{data:I}=await q.from("newsletter_pdfs").select("*").eq("newsletter_id",s).order("sort_order");return I||[]},enabled:!!s}),{data:g}=tt({queryKey:["newsletter-videos",s],queryFn:async()=>{const{data:I}=await q.from("newsletter_videos").select("*").eq("newsletter_id",s).order("sort_order");return I||[]},enabled:!!s}),{data:x}=tt({queryKey:["newsletter-canva-links",s],queryFn:async()=>{const{data:I}=await q.from("newsletter_canva_links").select("*").eq("newsletter_id",s).order("sort_order");return I||[]},enabled:!!s}),{data:y}=tt({queryKey:["newsletter-likes",s],queryFn:async()=>{const{data:I}=await q.from("newsletter_likes").select("*").eq("newsletter_id",s);return I||[]},enabled:!!s}),{data:v}=tt({queryKey:["newsletter-comments",s],queryFn:async()=>{const{data:I}=await q.from("newsletter_comments").select("*, profiles:user_id(name)").eq("newsletter_id",s).order("created_at",{ascending:!1});return I||[]},enabled:!!s}),b=y==null?void 0:y.some(I=>I.user_id===(n==null?void 0:n.id)),w=ft({mutationFn:async()=>{b?await q.from("newsletter_likes").delete().eq("newsletter_id",s).eq("user_id",n==null?void 0:n.id):await q.from("newsletter_likes").insert({newsletter_id:s,user_id:n==null?void 0:n.id})},onSuccess:()=>{a.invalidateQueries({queryKey:["newsletter-likes",s]})}}),S=ft({mutationFn:async I=>{const{error:P}=await q.from("newsletter_comments").insert({newsletter_id:s,user_id:n==null?void 0:n.id,content:I});if(P)throw P},onSuccess:()=>{a.invalidateQueries({queryKey:["newsletter-comments",s]}),o(""),r({title:"Comment added"})}}),C=ft({mutationFn:async I=>{const{error:P}=await q.from("newsletter_comments").delete().eq("id",I);if(P)throw P},onSuccess:()=>{a.invalidateQueries({queryKey:["newsletter-comments",s]}),r({title:"Comment deleted"})}}),E=I=>{if(I.includes("player.mediadelivery.net")||I.includes("iframe.mediadelivery.net")){const P=I.match(/embed\/(\d+)\/([a-f0-9-]+)/);if(P)return e.jsx("div",{className:"relative w-full pt-[56.25%]",children:e.jsx("iframe",{src:`https://iframe.mediadelivery.net/embed/${P[1]}/${P[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(I.includes("youtube.com")||I.includes("youtu.be")){const P=I.match(/(?:youtube\.com\/(?:watch\?v=|embed\/)|youtu\.be\/)([^&\s]+)/);if(P)return e.jsx("div",{className:"relative w-full pt-[56.25%]",children:e.jsx("iframe",{src:`https://www.youtube.com/embed/${P[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:I,target:"_blank",rel:"noopener noreferrer",className:"flex items-center gap-2 text-primary hover:underline",children:[e.jsx(Bu,{className:"h-4 w-4"})," Watch Video"]})};return h?e.jsx(Vs,{title:"",description:"",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(yn,{className:"h-8 w-32"}),e.jsx(yn,{className:"h-64 w-full"}),e.jsx(yn,{className:"h-32 w-full"})]})}):u?e.jsx(Vs,{title:"",description:"",children:e.jsxs("div",{className:"max-w-4xl mx-auto space-y-6",children:[e.jsxs($,{variant:"ghost",onClick:()=>t("/newsletters"),className:"mb-4",children:[e.jsx(qa,{className:"mr-2 h-4 w-4"})," Back to Newsletters"]}),u.preview_image_url&&e.jsx("img",{src:u.preview_image_url,alt:u.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:u.title}),e.jsx("p",{className:"text-muted-foreground mt-1",children:en(new Date(u.publish_date),"MMMM d, yyyy")})]}),u.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:u.description}}),e.jsx(rFn,{rows:u.content_blocks||[]}),e.jsxs("div",{className:"flex items-center gap-4 flex-wrap",children:[e.jsx(vK,{resourceType:"newsletter",resourceId:u.id,resourceTitle:u.title}),e.jsxs($,{variant:b?"default":"outline",size:"sm",onClick:()=>w.mutate(),children:[e.jsx(Jo,{className:`h-4 w-4 mr-1 ${b?"fill-current":""}`}),(y==null?void 0:y.length)||0," ",(y==null?void 0:y.length)===1?"Like":"Likes"]}),u.html_code&&e.jsxs($,{size:"sm",className:"bg-gradient-to-r from-[#2a4c64] to-[#406E71] text-white hover:opacity-90",onClick:()=>d(!0),children:[e.jsx(Yr,{className:"h-4 w-4 mr-1"}),"Send Newsletter"]})]}),u.html_code&&e.jsx(iit,{open:c,onOpenChange:d,newsletterId:u.id,newsletterTitle:u.title,htmlCode:u.html_code}),x&&x.length>0&&e.jsxs(Ne,{children:[e.jsx(Ct,{children:e.jsx(At,{className:"text-lg",children:"Canva Templates"})}),e.jsx(Ie,{className:"space-y-2",children:x.map(I=>e.jsxs("a",{href:I.canva_share_link,target:"_blank",rel:"noopener noreferrer",onClick:()=>i("newsletter",u.id,u.title,"click_canva"),className:"flex items-center gap-3 p-3 rounded-lg hover:bg-muted transition-colors",children:[e.jsx(Yc,{className:"h-5 w-5 text-purple-500"}),e.jsx("span",{className:"font-medium",children:I.title}),e.jsx(kr,{className:"h-4 w-4 text-muted-foreground ml-auto"})]},I.id))})]}),m&&m.length>0&&e.jsxs(Ne,{children:[e.jsx(Ct,{children:e.jsx(At,{className:"text-lg",children:"Google Drive Files"})}),e.jsx(Ie,{className:"space-y-2",children:m.map(I=>e.jsxs("a",{href:I.drive_url,target:"_blank",rel:"noopener noreferrer",onClick:()=>i("newsletter",u.id,u.title,"click_link"),className:"flex items-center gap-3 p-3 rounded-lg hover:bg-muted transition-colors",children:[e.jsx(kr,{className:"h-5 w-5 text-primary"}),e.jsx("span",{className:"font-medium",children:I.title})]},I.id))})]}),f&&f.length>0&&e.jsxs(Ne,{children:[e.jsx(Ct,{children:e.jsx(At,{className:"text-lg",children:"PDF Downloads"})}),e.jsx(Ie,{className:"space-y-2",children:f.map(I=>e.jsxs("a",{href:I.file_url,target:"_blank",rel:"noopener noreferrer",onClick:()=>i("newsletter",u.id,u.title,"click_pdf"),className:"flex items-center gap-3 p-3 rounded-lg hover:bg-muted transition-colors",children:[e.jsx(Jr,{className:"h-5 w-5 text-red-500"}),e.jsx("span",{className:"font-medium flex-1",children:I.name}),e.jsx(di,{className:"h-4 w-4 text-muted-foreground"})]},I.id))})]}),g&&g.length>0&&e.jsxs(Ne,{children:[e.jsx(Ct,{children:e.jsx(At,{className:"text-lg",children:"Videos"})}),e.jsx(Ie,{className:"space-y-6",children:g.map(I=>e.jsxs("div",{className:"space-y-2",children:[e.jsx("h4",{className:"font-medium",children:I.title}),E(I.video_url)]},I.id))})]}),e.jsxs(Ne,{children:[e.jsx(Ct,{children:e.jsxs(At,{className:"text-lg",children:["Comments (",(v==null?void 0:v.length)||0,")"]})}),e.jsxs(Ie,{className:"space-y-4",children:[e.jsxs("div",{className:"flex gap-3",children:[e.jsx(Rs,{placeholder:"Write a comment...",value:l,onChange:I=>o(I.target.value),className:"flex-1"}),e.jsx($,{onClick:()=>l.trim()&&S.mutate(l),disabled:!l.trim()||S.isPending,children:e.jsx(Yr,{className:"h-4 w-4"})})]}),e.jsx("div",{className:"space-y-4",children:v==null?void 0:v.map(I=>{var P,R,D;return e.jsxs("div",{className:"flex gap-3",children:[e.jsx(Oa,{className:"h-8 w-8",children:e.jsx(za,{children:((R=(P=I.profiles)==null?void 0:P.name)==null?void 0:R[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:((D=I.profiles)==null?void 0:D.name)||"User"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:en(new Date(I.created_at),"MMM d, yyyy")}),I.user_id===(n==null?void 0:n.id)&&e.jsx($,{variant:"ghost",size:"icon",className:"h-6 w-6",onClick:()=>C.mutate(I.id),children:e.jsx(Wn,{className:"h-3 w-3"})})]})]}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:I.content})]})]},I.id)})})]})]})]})}):e.jsx(Vs,{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($,{variant:"link",onClick:()=>t("/newsletters"),children:"Back to Newsletters"})]})})}function iFn({rows:s,onChange:t}){const[n,r]=j.useState(null),[a,i]=j.useState(null),l=()=>{t([...s,{columns:[{title:"",description:""},{title:"",description:""},{title:"",description:""}]}])},o=h=>{t(s.filter((m,f)=>f!==h))},c=(h,m,f,g)=>{const x=[...s];x[h]={...x[h],columns:x[h].columns.map((y,v)=>v===m?{...y,[f]:g}:y)},t(x)},d=async(h,m,f)=>{var y;const g=(y=f.target.files)==null?void 0:y[0];if(!g)return;const x=`${h}-${m}`;r(x);try{const v=`content-blocks/${Date.now()}-${g.name}`,{error:b}=await q.storage.from("newsletter-content").upload(v,g);if(!b){const{data:w}=q.storage.from("newsletter-content").getPublicUrl(v);c(h,m,"image_url",w.publicUrl)}}finally{r(null)}},u=(h,m)=>{c(h,m,"image_url","")};return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(ee,{className:"text-base font-medium",children:"Content Blocks (3-Column Rows)"}),e.jsxs($,{type:"button",variant:"outline",size:"sm",onClick:l,children:[e.jsx(dn,{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((h,m)=>e.jsxs(Ne,{className:"relative",children:[e.jsx($,{type:"button",variant:"ghost",size:"icon",className:"absolute top-2 right-2 h-6 w-6 text-muted-foreground hover:text-destructive",onClick:()=>o(m),children:e.jsx(gr,{className:"h-4 w-4"})}),e.jsxs(Ie,{className:"p-4 pt-3",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[e.jsx(Ug,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("span",{className:"text-xs font-medium text-muted-foreground uppercase tracking-wider",children:["Row ",m+1]})]}),e.jsx("div",{className:"grid grid-cols-3 gap-3",children:h.columns.map((f,g)=>{const x=`${m}-${g}`;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 ",g+1]}),f.image_url?e.jsxs("div",{className:"relative group",children:[e.jsx("img",{src:f.image_url,alt:"",className:"w-full h-20 object-cover rounded"}),e.jsx($,{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:()=>u(m,g),children:e.jsx(gr,{className:"h-3 w-3"})})]}):e.jsxs("div",{className:"grid grid-cols-2 gap-1.5",children:[e.jsx(pe,{type:"file",accept:"image/*",className:"hidden",id:`block-img-${x}`,onChange:y=>d(m,g,y)}),e.jsx($,{type:"button",variant:"outline",size:"sm",className:"text-xs h-8",disabled:n===x,asChild:!0,children:e.jsx("label",{htmlFor:`block-img-${x}`,className:"cursor-pointer",children:n===x?"...":e.jsxs(e.Fragment,{children:[e.jsx(Mc,{className:"h-3 w-3 mr-1"})," Upload"]})})}),e.jsxs($,{type:"button",variant:"outline",size:"sm",className:"text-xs h-8",onClick:()=>i({row:m,col:g}),children:[e.jsx(f2,{className:"h-3 w-3 mr-1"})," Library"]})]}),e.jsx(pe,{placeholder:"Title",value:f.title,onChange:y=>c(m,g,"title",y.target.value),className:"h-8 text-sm"}),e.jsx(Rs,{placeholder:"Description",value:f.description,onChange:y=>c(m,g,"description",y.target.value),className:"text-sm min-h-[60px] resize-none"})]},g)})})]})]},m)),e.jsx(zs,{open:!!a,onOpenChange:h=>!h&&i(null),children:e.jsxs(Os,{className:"sm:max-w-2xl",children:[e.jsx(Us,{children:e.jsx(Bs,{children:"Choose a Graphic"})}),e.jsx(GXt,{onSelect:h=>{a&&(c(a.row,a.col,"image_url",h.image_url),i(null))}})]})})]})}function oFn(){const{toast:s}=Bi(),t=Vt(),[n,r]=j.useState(!1),[a,i]=j.useState(null),[l,o]=j.useState({title:"",description:"",publish_date:en(new Date,"yyyy-MM-dd'T'HH:mm"),is_published:!1}),[c,d]=j.useState(null),[u,h]=j.useState(null),[m,f]=j.useState([]),[g,x]=j.useState([]),[y,v]=j.useState([]),[b,w]=j.useState([]),[S,C]=j.useState([]),[E,I]=j.useState(""),[P,R]=j.useState([]),[D,O]=j.useState(!1),{data:U,isLoading:W}=tt({queryKey:["admin-newsletters"],queryFn:async()=>{const{data:ve,error:Ee}=await q.from("newsletter_content").select("*").order("publish_date",{ascending:!1});if(Ee)throw Ee;return ve}}),V=ft({mutationFn:async ve=>{const{data:Ee,error:Se}=await q.from("newsletter_content").insert({title:ve.title,description:ve.description||null,preview_image_url:ve.preview_image_url,publish_date:ve.publish_date,is_published:ve.is_published,content_blocks:ve.content_blocks,html_code:ve.html_code}).select().single();if(Se)throw Se;return Ee},onSuccess:async ve=>{await X(ve.id),t.invalidateQueries({queryKey:["admin-newsletters"]}),s({title:"Newsletter created successfully"}),ve.is_published&&mmn(ve.title,ve.id),ne()},onError:ve=>{s({title:"Error creating newsletter",description:ve.message,variant:"destructive"})}}),G=ft({mutationFn:async ve=>{const{error:Ee}=await q.from("newsletter_content").update({title:ve.title,description:ve.description||null,preview_image_url:ve.preview_image_url,publish_date:ve.publish_date,is_published:ve.is_published,content_blocks:ve.content_blocks,html_code:ve.html_code}).eq("id",ve.id);if(Ee)throw Ee;return ve.id},onSuccess:async ve=>{await X(ve),t.invalidateQueries({queryKey:["admin-newsletters"]}),s({title:"Newsletter updated successfully"}),ne()},onError:ve=>{s({title:"Error updating newsletter",description:ve.message,variant:"destructive"})}}),Y=ft({mutationFn:async ve=>{const{error:Ee}=await q.from("newsletter_content").delete().eq("id",ve);if(Ee)throw Ee},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-newsletters"]}),s({title:"Newsletter deleted successfully"})},onError:ve=>{s({title:"Error deleting newsletter",description:ve.message,variant:"destructive"})}}),X=async ve=>{await q.from("newsletter_drive_links").delete().eq("newsletter_id",ve),await q.from("newsletter_pdfs").delete().eq("newsletter_id",ve),await q.from("newsletter_videos").delete().eq("newsletter_id",ve),await q.from("newsletter_canva_links").delete().eq("newsletter_id",ve);for(const Ee of P){const Se=`${ve}/${Date.now()}-${Ee.file.name}`,{error:Le}=await q.storage.from("newsletter-content").upload(Se,Ee.file);if(!Le){const{data:Fe}=q.storage.from("newsletter-content").getPublicUrl(Se);g.push({name:Ee.name,file_url:Fe.publicUrl,file_size:Ee.file.size,sort_order:g.length})}}m.length>0&&await q.from("newsletter_drive_links").insert(m.map((Ee,Se)=>({newsletter_id:ve,title:Ee.title,drive_url:Ee.drive_url,sort_order:Se}))),g.length>0&&await q.from("newsletter_pdfs").insert(g.map((Ee,Se)=>({newsletter_id:ve,name:Ee.name,file_url:Ee.file_url,file_size:Ee.file_size||null,sort_order:Se}))),y.length>0&&await q.from("newsletter_videos").insert(y.map((Ee,Se)=>({newsletter_id:ve,title:Ee.title,video_url:Ee.video_url,sort_order:Se}))),b.length>0&&await q.from("newsletter_canva_links").insert(b.map((Ee,Se)=>({newsletter_id:ve,title:Ee.title,canva_share_link:Ee.canva_share_link,sort_order:Se})))},ae=async ve=>{i(ve),o({title:ve.title,description:ve.description||"",publish_date:en(new Date(ve.publish_date),"yyyy-MM-dd'T'HH:mm"),is_published:ve.is_published}),h(ve.preview_image_url),C(ve.content_blocks||[]),I(ve.html_code||"");const[Ee,Se,Le,Fe]=await Promise.all([q.from("newsletter_drive_links").select("*").eq("newsletter_id",ve.id).order("sort_order"),q.from("newsletter_pdfs").select("*").eq("newsletter_id",ve.id).order("sort_order"),q.from("newsletter_videos").select("*").eq("newsletter_id",ve.id).order("sort_order"),q.from("newsletter_canva_links").select("*").eq("newsletter_id",ve.id).order("sort_order")]);f(Ee.data||[]),x(Se.data||[]),v(Le.data||[]),w(Fe.data||[]),R([]),r(!0)},ie=async ve=>{const[Ee,Se,Le,Fe]=await Promise.all([q.from("newsletter_drive_links").select("*").eq("newsletter_id",ve.id).order("sort_order"),q.from("newsletter_pdfs").select("*").eq("newsletter_id",ve.id).order("sort_order"),q.from("newsletter_videos").select("*").eq("newsletter_id",ve.id).order("sort_order"),q.from("newsletter_canva_links").select("*").eq("newsletter_id",ve.id).order("sort_order")]);i(null),o({title:`${ve.title} (Copy)`,description:ve.description||"",publish_date:en(new Date,"yyyy-MM-dd'T'HH:mm"),is_published:!1}),h(ve.preview_image_url),C(ve.content_blocks||[]),I(ve.html_code||""),f((Ee.data||[]).map(({id:ke,...Ve})=>Ve)),x((Se.data||[]).map(({id:ke,...Ve})=>Ve)),v((Le.data||[]).map(({id:ke,...Ve})=>Ve)),w((Fe.data||[]).map(({id:ke,...Ve})=>Ve)),R([]),r(!0)},ne=()=>{r(!1),i(null),o({title:"",description:"",publish_date:en(new Date,"yyyy-MM-dd'T'HH:mm"),is_published:!1}),d(null),h(null),f([]),x([]),v([]),w([]),C([]),I(""),R([])},te=async ve=>{var Se;const Ee=(Se=ve.target.files)==null?void 0:Se[0];Ee&&(d(Ee),h(URL.createObjectURL(Ee)))},J=async()=>{if(!l.title){s({title:"Title is required",variant:"destructive"});return}O(!0);let ve=u;if(c){const Ee=`previews/${Date.now()}-${c.name}`,{error:Se}=await q.storage.from("newsletter-content").upload(Ee,c);if(!Se){const{data:Le}=q.storage.from("newsletter-content").getPublicUrl(Ee);ve=Le.publicUrl}}a?G.mutate({id:a.id,...l,preview_image_url:ve,content_blocks:S,html_code:E||null}):V.mutate({...l,preview_image_url:ve,content_blocks:S,html_code:E||null}),O(!1)},ce=()=>f([...m,{title:"",drive_url:"",sort_order:m.length}]),_e=()=>v([...y,{title:"",video_url:"",sort_order:y.length}]),he=()=>w([...b,{title:"",canva_share_link:"",sort_order:b.length}]),ue=ve=>{const Ee=ve.target.files;if(!Ee)return;const Se=Array.from(Ee).map(Le=>({file:Le,name:Le.name.replace(/\.[^/.]+$/,"")}));R([...P,...Se])};return e.jsx(Vs,{title:"Newsletter Content",description:"Manage monthly newsletter templates and resources",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(Fm,{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(Ne,{children:[e.jsx(Ct,{className:"pb-2",children:e.jsx(At,{className:"text-sm font-medium text-muted-foreground",children:"Total"})}),e.jsx(Ie,{children:e.jsx("div",{className:"text-2xl font-bold",children:(U==null?void 0:U.length)||0})})]}),e.jsxs(Ne,{children:[e.jsx(Ct,{className:"pb-2",children:e.jsx(At,{className:"text-sm font-medium text-muted-foreground",children:"Published"})}),e.jsx(Ie,{children:e.jsx("div",{className:"text-2xl font-bold",children:(U==null?void 0:U.filter(ve=>ve.is_published).length)||0})})]})]}),e.jsxs(zs,{open:n,onOpenChange:ve=>!ve&&ne(),children:[e.jsx(jl,{asChild:!0,children:e.jsxs($,{onClick:()=>r(!0),children:[e.jsx(dn,{className:"mr-2 h-4 w-4"})," Add Newsletter"]})}),e.jsxs(Os,{className:"max-w-4xl max-h-[90vh] overflow-y-auto",children:[e.jsx(Us,{children:e.jsx(Bs,{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(ee,{children:"Title *"}),e.jsx(pe,{value:l.title,onChange:ve=>o({...l,title:ve.target.value}),placeholder:"Newsletter title"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Publish Date"}),e.jsx(pe,{type:"datetime-local",value:l.publish_date,onChange:ve=>o({...l,publish_date:ve.target.value})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Description"}),e.jsx(Ek,{content:l.description,onChange:ve=>o({...l,description:ve}),placeholder:"Newsletter description",minHeight:"120px"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Preview Image"}),e.jsxs("div",{className:"flex items-center gap-4",children:[u&&e.jsxs("div",{className:"relative group",children:[e.jsx("img",{src:u,alt:"Preview",className:"h-20 w-32 object-cover rounded-md"}),e.jsx($,{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),h(null)},children:e.jsx(gr,{className:"h-3 w-3"})})]}),e.jsxs("div",{children:[e.jsx(pe,{type:"file",accept:"image/*",onChange:te,className:"hidden",id:"preview-upload"}),e.jsx($,{variant:"outline",asChild:!0,children:e.jsxs("label",{htmlFor:"preview-upload",className:"cursor-pointer",children:[e.jsx(ni,{className:"mr-2 h-4 w-4"})," Upload Image"]})})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Sn,{checked:l.is_published,onCheckedChange:ve=>o({...l,is_published:ve})}),e.jsx(ee,{children:"Published"})]}),e.jsx(iFn,{rows:S,onChange:C}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(ee,{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:E,onChange:ve=>I(ve.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(ee,{className:"text-base font-medium",children:"Canva Links"}),e.jsxs($,{type:"button",variant:"outline",size:"sm",onClick:he,children:[e.jsx(dn,{className:"mr-1 h-3 w-3"})," Add Canva Link"]})]}),b.map((ve,Ee)=>e.jsxs("div",{className:"flex gap-2 items-center",children:[e.jsx(pe,{placeholder:"Link title",value:ve.title,onChange:Se=>{const Le=[...b];Le[Ee].title=Se.target.value,w(Le)},className:"w-1/3"}),e.jsx(pe,{placeholder:"Canva share link",value:ve.canva_share_link,onChange:Se=>{const Le=[...b];Le[Ee].canva_share_link=Se.target.value,w(Le)},className:"flex-1"}),e.jsx($,{type:"button",variant:"ghost",size:"icon",onClick:()=>w(b.filter((Se,Le)=>Le!==Ee)),children:e.jsx(gr,{className:"h-4 w-4"})})]},Ee))]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(ee,{className:"text-base font-medium",children:"Google Drive Links"}),e.jsxs($,{type:"button",variant:"outline",size:"sm",onClick:ce,children:[e.jsx(dn,{className:"mr-1 h-3 w-3"})," Add Link"]})]}),m.map((ve,Ee)=>e.jsxs("div",{className:"flex gap-2 items-center",children:[e.jsx(pe,{placeholder:"Link title",value:ve.title,onChange:Se=>{const Le=[...m];Le[Ee].title=Se.target.value,f(Le)},className:"w-1/3"}),e.jsx(pe,{placeholder:"Google Drive URL",value:ve.drive_url,onChange:Se=>{const Le=[...m];Le[Ee].drive_url=Se.target.value,f(Le)},className:"flex-1"}),e.jsx($,{type:"button",variant:"ghost",size:"icon",onClick:()=>f(m.filter((Se,Le)=>Le!==Ee)),children:e.jsx(gr,{className:"h-4 w-4"})})]},Ee))]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(ee,{className:"text-base font-medium",children:"PDF Files"}),e.jsxs("div",{children:[e.jsx(pe,{type:"file",accept:".pdf",multiple:!0,onChange:ue,className:"hidden",id:"pdf-upload"}),e.jsx($,{variant:"outline",size:"sm",asChild:!0,children:e.jsxs("label",{htmlFor:"pdf-upload",className:"cursor-pointer",children:[e.jsx(ni,{className:"mr-1 h-3 w-3"})," Upload PDF"]})})]})]}),g.map((ve,Ee)=>e.jsxs("div",{className:"flex gap-2 items-center bg-muted/50 p-2 rounded",children:[e.jsx(Jr,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"flex-1 text-sm",children:ve.name}),e.jsx($,{type:"button",variant:"ghost",size:"icon",onClick:()=>x(g.filter((Se,Le)=>Le!==Ee)),children:e.jsx(gr,{className:"h-4 w-4"})})]},`existing-${Ee}`)),P.map((ve,Ee)=>e.jsxs("div",{className:"flex gap-2 items-center bg-muted/50 p-2 rounded",children:[e.jsx(Jr,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(pe,{value:ve.name,onChange:Se=>{const Le=[...P];Le[Ee].name=Se.target.value,R(Le)},className:"flex-1 h-8",placeholder:"PDF name"}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"(new)"}),e.jsx($,{type:"button",variant:"ghost",size:"icon",onClick:()=>R(P.filter((Se,Le)=>Le!==Ee)),children:e.jsx(gr,{className:"h-4 w-4"})})]},`pending-${Ee}`))]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(ee,{className:"text-base font-medium",children:"Video Links"}),e.jsxs($,{type:"button",variant:"outline",size:"sm",onClick:_e,children:[e.jsx(dn,{className:"mr-1 h-3 w-3"})," Add Video"]})]}),y.map((ve,Ee)=>e.jsxs("div",{className:"flex gap-2 items-center",children:[e.jsx(pe,{placeholder:"Video title",value:ve.title,onChange:Se=>{const Le=[...y];Le[Ee].title=Se.target.value,v(Le)},className:"w-1/3"}),e.jsx(pe,{placeholder:"Video URL",value:ve.video_url,onChange:Se=>{const Le=[...y];Le[Ee].video_url=Se.target.value,v(Le)},className:"flex-1"}),e.jsx($,{type:"button",variant:"ghost",size:"icon",onClick:()=>v(y.filter((Se,Le)=>Le!==Ee)),children:e.jsx(gr,{className:"h-4 w-4"})})]},Ee))]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-4 border-t",children:[e.jsx($,{variant:"outline",onClick:ne,children:"Cancel"}),e.jsx($,{onClick:J,disabled:D||V.isPending||G.isPending,children:D?"Uploading...":a?"Update":"Create"})]})]})]})]})]}),e.jsx(Ne,{children:e.jsx(Ie,{className:"p-0",children:e.jsxs(mi,{children:[e.jsx(fi,{children:e.jsxs(En,{children:[e.jsx(Dt,{children:"Name"}),e.jsx(Dt,{children:"Publish Date"}),e.jsx(Dt,{children:"Status"}),e.jsx(Dt,{className:"text-right",children:"Actions"})]})}),e.jsx(pi,{children:W?e.jsx(En,{children:e.jsx(wt,{colSpan:4,className:"text-center py-8",children:"Loading..."})}):(U==null?void 0:U.length)===0?e.jsx(En,{children:e.jsx(wt,{colSpan:4,className:"text-center py-8 text-muted-foreground",children:"No newsletters yet. Create your first one!"})}):U==null?void 0:U.map(ve=>e.jsxs(En,{children:[e.jsx(wt,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[ve.preview_image_url?e.jsx("img",{src:ve.preview_image_url,alt:ve.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(Jr,{className:"h-5 w-5 text-muted-foreground"})}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:ve.title}),ve.description&&e.jsx("div",{className:"text-sm text-muted-foreground line-clamp-1",children:ve.description.replace(/<[^>]*>/g,"")})]})]})}),e.jsx(wt,{children:en(new Date(ve.publish_date),"MMM d, yyyy")}),e.jsx(wt,{children:e.jsx("span",{className:`inline-flex items-center px-2 py-1 rounded-full text-xs font-medium ${ve.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:ve.is_published?"Published":"Draft"})}),e.jsx(wt,{className:"text-right",children:e.jsxs("div",{className:"flex justify-end gap-1",children:[e.jsx($,{variant:"ghost",size:"icon",onClick:()=>ae(ve),title:"Edit",children:e.jsx(gi,{className:"h-4 w-4"})}),e.jsx($,{variant:"ghost",size:"icon",onClick:()=>ie(ve),title:"Duplicate",children:e.jsx(Ha,{className:"h-4 w-4"})}),e.jsx($,{variant:"ghost",size:"icon",className:"text-destructive hover:text-destructive",title:"Delete",onClick:async()=>{await fo("Are you sure you want to delete this newsletter?")&&Y.mutate(ve.id)},children:e.jsx(Wn,{className:"h-4 w-4"})})]})})]},ve.id))})]})})})]})})}const lFn={status:"all",billing:"all",role:"all",brokerage:"all",joinedWithinDays:null};function cFn({brokerages:s}){var C;const{toast:t}=Bi(),[n,r]=j.useState(lFn),[a,i]=j.useState(""),[l,o]=j.useState(""),[c,d]=j.useState(""),[u,h]=j.useState(null),[m,f]=j.useState(!1),[g,x]=j.useState(!1),[y,v]=j.useState(null),b=(E,I)=>r(P=>({...P,[E]:I}));j.useEffect(()=>{const E=setTimeout(async()=>{f(!0);try{const{data:I,error:P}=await q.functions.invoke("admin-broadcast-sms",{body:{action:"preview",filters:n,sms_body:a||"Sample message"}});if(P)throw P;h(I)}catch{h(null)}finally{f(!1)}},450);return()=>clearTimeout(E)},[n,a]);const w=async()=>{if(!c||!a.trim()){t({title:"Add a test number and message",variant:"destructive"});return}x(!0);const{data:E,error:I}=await q.functions.invoke("admin-broadcast-sms",{body:{action:"test",to:c,sms_body:a}});if(x(!1),I||E!=null&&E.error){t({title:"Test failed",description:(E==null?void 0:E.error)||(I==null?void 0:I.message),variant:"destructive"});return}t({title:"Test text sent",description:`Sent to ${c}`})},S=async()=>{const E=(u==null?void 0:u.count)||0;if(!(!a.trim()||E===0||!await fo({title:"Send text broadcast?",description:`This will text ${E} member${E===1?"":"s"} who have a recorded SMS opt-in. Texts cannot be recalled.`,confirmText:"Send broadcast"}))){x(!0),v({total:E,sent:0,failed:0});try{const{data:P,error:R}=await q.functions.invoke("admin-broadcast-sms",{body:{action:"queue",name:l||a.slice(0,60),sms_body:a,filters:n}});if(R||P!=null&&P.error)throw new Error((P==null?void 0:P.error)||(R==null?void 0:R.message));let D=0,O=0,U=P.total,W=0;for(;U>0&&W++<400;){const{data:V,error:G}=await q.functions.invoke("admin-broadcast-sms",{body:{action:"process",broadcast_id:P.broadcast_id,limit:40}});if(G||V!=null&&V.error)throw new Error((V==null?void 0:V.error)||(G==null?void 0:G.message));if(V.deferred){t({title:"Paused for quiet hours",description:V.reason});break}D+=V.sent||0,O+=V.failed||0,U=V.remaining||0,v({total:E,sent:D,failed:O})}t({title:"Broadcast complete",description:`${D} sent${O?`, ${O} failed`:""}.`})}catch(P){t({title:"Broadcast failed",description:P.message,variant:"destructive"})}finally{x(!1)}}};return e.jsxs("div",{className:"grid gap-6 lg:grid-cols-[340px_1fr]",children:[e.jsx("div",{className:"space-y-4",children:e.jsxs(Ne,{children:[e.jsxs(Ct,{className:"pb-3",children:[e.jsxs(At,{className:"flex items-center gap-2 text-base",children:[e.jsx(bm,{className:"h-4 w-4"})," SMS Audience"]}),e.jsx(Gn,{children:"Only members with a recorded consent date and source are included. Opted-out and undeliverable numbers are always excluded."})]}),e.jsxs(Ie,{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{className:"text-xs",children:"Account status"}),e.jsxs(ms,{value:n.status,onValueChange:E=>b("status",E),children:[e.jsx(us,{children:e.jsx(fs,{})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"all",children:"All members"}),e.jsx(Ge,{value:"active",children:"Signed in before"}),e.jsx(Ge,{value:"pending",children:"Never signed in"})]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{className:"text-xs",children:"Billing"}),e.jsxs(ms,{value:n.billing,onValueChange:E=>b("billing",E),children:[e.jsx(us,{children:e.jsx(fs,{})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"all",children:"All"}),e.jsx(Ge,{value:"trial",children:"On trial"}),e.jsx(Ge,{value:"paid",children:"Paid"}),e.jsx(Ge,{value:"grandfathered",children:"Grandfathered"}),e.jsx(Ge,{value:"canceled",children:"Canceled / past due"})]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{className:"text-xs",children:"Role"}),e.jsxs(ms,{value:n.role,onValueChange:E=>b("role",E),children:[e.jsx(us,{children:e.jsx(fs,{})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"all",children:"All roles"}),e.jsx(Ge,{value:"user",children:"Agents"}),e.jsx(Ge,{value:"brokerage_manager",children:"Brokerage managers"}),e.jsx(Ge,{value:"coach",children:"Coaches"}),e.jsx(Ge,{value:"admin",children:"Admins"})]})]})]}),!!(s!=null&&s.length)&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{className:"text-xs",children:"Brokerage"}),e.jsxs(ms,{value:n.brokerage,onValueChange:E=>b("brokerage",E),children:[e.jsx(us,{children:e.jsx(fs,{})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"all",children:"All brokerages"}),e.jsx(Ge,{value:"none",children:"No brokerage"}),s.map(E=>e.jsx(Ge,{value:E.id,children:E.name},E.id))]})]})]}),e.jsxs("div",{className:"rounded-lg border bg-muted/30 p-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-sm text-muted-foreground",children:"SMS-eligible members"}),e.jsx("span",{className:"text-lg font-semibold",children:m?e.jsx(kt,{className:"h-4 w-4 animate-spin"}):(u==null?void 0:u.count)??0})]}),(C=u==null?void 0:u.sample)!=null&&C.length?e.jsxs("p",{className:"mt-2 text-xs text-muted-foreground",children:["e.g. ",u.sample.slice(0,3).map(E=>E.name||E.phone).join(", ")]}):null]}),u&&!u.quiet_hours_ok&&e.jsxs("div",{className:"flex items-start gap-2 rounded-lg border border-amber-500/40 bg-amber-500/10 p-3 text-xs",children:[e.jsx(da,{className:"mt-0.5 h-3.5 w-3.5 shrink-0"}),e.jsx("span",{children:"Outside the 9:00 AM – 8:00 PM ET sending window. Queued texts will be held and resumed instead of sent now."})]})]})]})}),e.jsx("div",{className:"space-y-4",children:e.jsxs(Ne,{children:[e.jsxs(Ct,{className:"pb-3",children:[e.jsxs(At,{className:"flex items-center gap-2 text-base",children:[e.jsx(eo,{className:"h-4 w-4"})," Text message"]}),e.jsxs(Gn,{children:["Merge tags: ",e.jsx("code",{children:"{{first_name}}"})," ",e.jsx("code",{children:"{{name}}"}),'. The LevelUp prefix and "Reply STOP to opt out" are added automatically.']})]}),e.jsxs(Ie,{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{htmlFor:"sms-broadcast-name",className:"text-xs",children:"Internal name"}),e.jsx(pe,{id:"sms-broadcast-name",value:l,onChange:E=>o(E.target.value),placeholder:"August member update"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{htmlFor:"sms-broadcast-body",className:"text-xs",children:"Message"}),e.jsx(Rs,{id:"sms-broadcast-body",value:a,onChange:E=>i(E.target.value),rows:5,maxLength:480,placeholder:"Hi {{first_name}} — join us Thursday at 11am ET for the LevelUp Live session on listing videos."}),e.jsxs("div",{className:"flex items-center justify-between text-xs text-muted-foreground",children:[e.jsxs("span",{children:[(u==null?void 0:u.length)??a.length," characters"]}),e.jsxs(Be,{variant:((u==null?void 0:u.segments)??1)>2?"destructive":"secondary",children:[(u==null?void 0:u.segments)??1," segment",((u==null?void 0:u.segments)??1)===1?"":"s"]})]})]}),(u==null?void 0:u.composed)&&e.jsxs("div",{className:"rounded-lg border bg-muted/30 p-3",children:[e.jsx("p",{className:"mb-1 text-xs font-medium text-muted-foreground",children:"Preview as delivered"}),e.jsx("p",{className:"whitespace-pre-wrap text-sm",children:u.composed})]}),e.jsxs("div",{className:"flex flex-wrap items-end gap-2",children:[e.jsxs("div",{className:"flex-1 space-y-1.5",style:{minWidth:200},children:[e.jsx(ee,{htmlFor:"sms-test-phone",className:"text-xs",children:"Send a test to"}),e.jsx(pe,{id:"sms-test-phone",value:c,onChange:E=>d(E.target.value),placeholder:"(555) 123-4567",type:"tel"})]}),e.jsxs($,{variant:"outline",onClick:w,disabled:g,children:[g&&e.jsx(kt,{className:"mr-2 h-4 w-4 animate-spin"})," Send test"]})]}),y&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(Yi,{value:y.total?(y.sent+y.failed)/y.total*100:0}),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(qr,{className:"h-3 w-3"})," ",y.sent," sent"]}),y.failed>0&&e.jsxs("span",{className:"flex items-center gap-1 text-destructive",children:[e.jsx(ll,{className:"h-3 w-3"})," ",y.failed," failed"]}),e.jsxs("span",{children:["of ",y.total]})]})]}),e.jsxs($,{onClick:S,disabled:g||!a.trim()||!(u!=null&&u.count),className:"w-full",children:[g?e.jsx(kt,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(Yr,{className:"mr-2 h-4 w-4"}),"Send to ",(u==null?void 0:u.count)??0," member",((u==null?void 0:u.count)??0)===1?"":"s"]})]})]})})]})}const F9e={status:"all",billing:"all",role:"all",brokerage:"all",joinedWithinDays:null,respectOptOut:!0,program:"all",programStatus:"active"},dFn=["{{first_name}}","{{name}}","{{email}}"];function uFn(s){return`${s||'

Your email preview will appear here…

'}`}function hFn(){var Ke;const{toast:s}=Bi(),{user:t}=vs(),n=Vt(),[r,a]=j.useState("filters"),[i,l]=j.useState([]),[o,c]=j.useState(""),[d,u]=j.useState([]),[h,m]=j.useState(!1),[f,g]=j.useState(""),[x,y]=j.useState(!1),[v,b]=j.useState(F9e),[w,S]=j.useState(null),[C,E]=j.useState(!1),[I,P]=j.useState(""),[R,D]=j.useState(""),[O,U]=j.useState(""),[W,V]=j.useState(""),[G,Y]=j.useState("rich"),[X,ae]=j.useState(""),[ie,ne]=j.useState(""),[te,J]=j.useState(""),[ce,_e]=j.useState(!1),[he,ue]=j.useState(null),ve=G==="rich"?X:ie;j.useEffect(()=>{t!=null&&t.email&&(U(nt=>nt||t.email),V(nt=>nt||t.email),J(nt=>nt||t.email))},[t==null?void 0:t.email]);const{data:Ee}=tt({queryKey:["broadcast-brokerages"],queryFn:async()=>{const{data:nt}=await q.from("brokerages").select("id, name").order("name");return nt||[]}}),{data:Se}=tt({queryKey:["broadcast-programs"],queryFn:async()=>{const{data:nt}=await q.from("programs").select("id, name").order("created_at",{ascending:!1});return nt||[]}}),{data:Le}=tt({queryKey:["admin-broadcasts"],queryFn:async()=>{const{data:nt,error:xt}=await q.from("admin_broadcasts").select("*").order("created_at",{ascending:!1}).limit(30);if(xt)throw xt;return nt}}),{data:Fe}=tt({queryKey:["admin-broadcast-templates"],queryFn:async()=>{const{data:nt,error:xt}=await q.from("admin_broadcast_templates").select("*").order("updated_at",{ascending:!1});if(xt)throw xt;return nt}}),ke=async nt=>{E(!0);try{const{data:xt,error:rt}=await q.functions.invoke("admin-broadcast",{body:{action:"preview",filters:nt}});if(rt)throw rt;if(xt!=null&&xt.error)throw new Error(xt.error);S(xt)}catch(xt){s({title:"Could not load audience",description:xt.message,variant:"destructive"})}finally{E(!1)}};j.useEffect(()=>{if(r!=="filters")return;const nt=setTimeout(()=>ke(v),400);return()=>clearTimeout(nt)},[v,r]),j.useEffect(()=>{if(r!=="manual")return;const nt=setTimeout(async()=>{m(!0);try{const{data:xt,error:rt}=await q.functions.invoke("admin-broadcast",{body:{action:"search_members",query:o}});if(rt)throw rt;u((xt==null?void 0:xt.members)||[])}catch{u([])}finally{m(!1)}},350);return()=>clearTimeout(nt)},[o,r]);const Ve=(nt,xt)=>b(rt=>({...rt,[nt]:xt})),je=r==="manual"?i.length:(w==null?void 0:w.count)||0,Ae=()=>r==="manual"?{recipient_mode:"manual",manual_emails:i.map(nt=>nt.email)}:{recipient_mode:"filters",filters:v},Ce=nt=>l(xt=>xt.some(rt=>rt.email.toLowerCase()===nt.email.toLowerCase())?xt.filter(rt=>rt.email.toLowerCase()!==nt.email.toLowerCase()):[...xt,nt]),qe=async()=>{const nt=(f||I||R).trim();if(!nt||!ve.trim()){s({title:"Add a template name and content first",variant:"destructive"});return}y(!0);try{const{error:xt}=await q.from("admin_broadcast_templates").insert({created_by:t.id,name:nt,subject:R,body_html:ve,editor_mode:G,from_email:O||null,reply_to_email:W||null,filters:v});if(xt)throw xt;g(""),s({title:"Template saved",description:`"${nt}" is available for future sends.`}),n.invalidateQueries({queryKey:["admin-broadcast-templates"]})}catch(xt){s({title:"Could not save template",description:xt.message,variant:"destructive"})}finally{y(!1)}},ze=nt=>{P(nt.name||""),D(nt.subject||""),nt.from_email&&U(nt.from_email),nt.reply_to_email&&V(nt.reply_to_email);const xt=nt.editor_mode==="html"?"html":"rich";Y(xt),xt==="html"?ne(nt.body_html||""):ae(nt.body_html||""),nt.filters&&Object.keys(nt.filters).length&&b({...F9e,...nt.filters}),s({title:"Template loaded",description:"Edit and send when ready."})},$e=async nt=>{if(!await fo(`Delete template "${nt.name}"?`))return;const{error:xt}=await q.from("admin_broadcast_templates").delete().eq("id",nt.id);if(xt){s({title:"Delete failed",description:xt.message,variant:"destructive"});return}n.invalidateQueries({queryKey:["admin-broadcast-templates"]})},ct=j.useMemo(()=>!!R.trim()&&!!ve.trim()&&!!O.trim()&&je>0,[R,ve,O,je]),Xe=async()=>{if(!te||!R.trim()||!ve.trim()){s({title:"Add a subject, content and test address first",variant:"destructive"});return}try{const{data:nt,error:xt}=await q.functions.invoke("admin-broadcast",{body:{action:"test",to:te,subject:R,html:ve,from_email:O,reply_to:W||void 0}});if(xt)throw xt;if(nt!=null&&nt.error)throw new Error(nt.error);s({title:"Test sent",description:`Check ${te}`})}catch(nt){s({title:"Test failed",description:nt.message,variant:"destructive"})}},it=async()=>{const nt=je;if(await fo({title:"Send this broadcast?",description:`"${R}" will be emailed to ${nt} member${nt===1?"":"s"}. Sent emails can't be recalled.`,confirmText:"Send broadcast",cancelText:"Cancel",destructive:!1})){_e(!0),ue({total:nt,sent:0,failed:0});try{const{data:rt,error:Yt}=await q.functions.invoke("admin-broadcast",{body:{action:"queue",name:I||R,subject:R,html:ve,from_email:O,reply_to:W||void 0,...Ae()}});if(Yt)throw Yt;if(rt!=null&&rt.error)throw new Error(rt.error);let qt=0,ts=0,ys=rt.total,Bt=0;for(;ys>0;){const{data:Ft,error:rs}=await q.functions.invoke("admin-broadcast",{body:{action:"process",broadcast_id:rt.broadcast_id,limit:40}});if(rs)throw rs;if(Ft!=null&&Ft.error)throw new Error(Ft.error);if(qt+=Ft.sent,ts+=Ft.failed,ys=Ft.remaining,ue({total:rt.total,sent:qt,failed:ts}),Ft.throttled){const St=Math.min(Math.max(Number(Ft.retry_after_ms)||15e3,5e3),45e3);await new Promise(Xs=>setTimeout(Xs,St));continue}if(Ft.sent===0&&Ft.failed===0){if(++Bt>=3)break;await new Promise(St=>setTimeout(St,5e3))}else Bt=0}s({title:"Broadcast complete",description:`${qt} sent${ts?`, ${ts} failed`:""}`}),n.invalidateQueries({queryKey:["admin-broadcasts"]})}catch(rt){s({title:"Send failed",description:rt.message,variant:"destructive"})}finally{_e(!1)}}},at=async nt=>{_e(!0);try{const{data:xt,error:rt}=await q.functions.invoke("admin-broadcast",{body:{action:"retry_failed",broadcast_id:nt}});if(rt)throw rt;if(xt!=null&&xt.error)throw new Error(xt.error);let Yt=0,qt=0,ts=xt.requeued,ys=0;for(ue({total:ts,sent:0,failed:0});ts>0;){const{data:Bt,error:Ft}=await q.functions.invoke("admin-broadcast",{body:{action:"process",broadcast_id:nt,limit:25}});if(Ft)throw Ft;if(Bt!=null&&Bt.error)throw new Error(Bt.error);if(Yt+=Bt.sent,qt+=Bt.failed,ts=Bt.remaining,ue({total:xt.requeued,sent:Yt,failed:qt}),Bt.throttled){await new Promise(rs=>setTimeout(rs,Math.min(Math.max(Number(Bt.retry_after_ms)||15e3,5e3),45e3)));continue}if(Bt.sent===0&&Bt.failed===0){if(++ys>=3)break;await new Promise(rs=>setTimeout(rs,5e3))}else ys=0}s({title:"Retry complete",description:`${Yt} sent${qt?`, ${qt} still failed`:""}`}),n.invalidateQueries({queryKey:["admin-broadcasts"]})}catch(xt){s({title:"Retry failed",description:xt.message,variant:"destructive"})}finally{_e(!1)}};return e.jsx(Vs,{children:e.jsxs("div",{className:"space-y-6 p-4 md:p-8",children:[e.jsx(Fm,{title:"Member Broadcasts",description:"Send a one-off email to a filtered slice of LevelUp members"}),e.jsxs(ha,{defaultValue:"compose",className:"space-y-6",children:[e.jsxs(ma,{children:[e.jsxs(Zt,{value:"compose",className:"gap-2",children:[e.jsx(mn,{className:"h-4 w-4"})," Compose"]}),e.jsxs(Zt,{value:"sms",className:"gap-2",children:[e.jsx(eo,{className:"h-4 w-4"})," Text (SMS)"]}),e.jsxs(Zt,{value:"templates",className:"gap-2",children:[e.jsx(m2,{className:"h-4 w-4"})," Templates"]}),e.jsxs(Zt,{value:"history",className:"gap-2",children:[e.jsx(Lw,{className:"h-4 w-4"})," History"]})]}),e.jsx(Xt,{value:"sms",className:"space-y-6",children:e.jsx(cFn,{brokerages:Ee})}),e.jsx(Xt,{value:"compose",className:"space-y-6",children:e.jsxs("div",{className:"grid gap-6 lg:grid-cols-[340px_1fr]",children:[e.jsx("div",{className:"space-y-4",children:e.jsxs(Ne,{className:"overflow-hidden",children:[e.jsxs("div",{className:"bg-gradient-to-br from-primary/90 to-primary p-5 text-primary-foreground",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm opacity-90",children:[e.jsx(Zn,{className:"h-4 w-4"})," Audience"]}),e.jsxs("div",{className:"mt-2 flex items-baseline gap-2",children:[e.jsx("span",{className:"text-4xl font-bold",children:r==="manual"?i.length:C?"—":(w==null?void 0:w.count)??0}),e.jsx("span",{className:"text-sm opacity-90",children:r==="manual"?"members selected":"members match"})]})]}),e.jsxs(Ie,{className:"space-y-4 pt-5",children:[e.jsx(ha,{value:r,onValueChange:nt=>a(nt),children:e.jsxs(ma,{className:"grid w-full grid-cols-2",children:[e.jsxs(Zt,{value:"filters",className:"gap-1.5 text-xs",children:[e.jsx(Zn,{className:"h-3.5 w-3.5"})," Filters"]}),e.jsxs(Zt,{value:"manual",className:"gap-1.5 text-xs",children:[e.jsx(sc,{className:"h-3.5 w-3.5"})," Individuals"]})]})}),r==="manual"&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Find members"}),e.jsxs("div",{className:"relative",children:[e.jsx(Kr,{className:"pointer-events-none absolute left-2.5 top-2.5 h-4 w-4 text-muted-foreground"}),e.jsx(pe,{value:o,onChange:nt=>c(nt.target.value),placeholder:"Search by name or email",className:"pl-8"})]})]}),i.length>0&&e.jsx("div",{className:"flex flex-wrap gap-1.5",children:i.map(nt=>e.jsxs(Be,{variant:"secondary",className:"gap-1",children:[e.jsx("span",{className:"max-w-[150px] truncate",children:nt.name||nt.email}),e.jsx("button",{type:"button",onClick:()=>Ce(nt),"aria-label":`Remove ${nt.email}`,children:e.jsx(gr,{className:"h-3 w-3"})})]},nt.email))}),e.jsx("div",{className:"max-h-72 space-y-1 overflow-y-auto rounded-lg border p-1",children:h?e.jsx("p",{className:"p-3 text-xs text-muted-foreground",children:"Searching…"}):d.length===0?e.jsx("p",{className:"p-3 text-xs text-muted-foreground",children:"No members found."}):d.map(nt=>{const xt=i.some(rt=>rt.email.toLowerCase()===nt.email.toLowerCase());return e.jsxs("button",{type:"button",onClick:()=>Ce(nt),className:`flex w-full items-center justify-between rounded-md px-2.5 py-2 text-left text-xs hover:bg-muted ${xt?"bg-muted":""}`,children:[e.jsxs("span",{className:"min-w-0",children:[e.jsx("span",{className:"block truncate font-medium",children:nt.name||"Member"}),e.jsx("span",{className:"block truncate text-muted-foreground",children:nt.email})]}),xt&&e.jsx(qr,{className:"h-4 w-4 shrink-0 text-primary"})]},nt.id)})})]}),r==="filters"&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Account status"}),e.jsxs(ms,{value:v.status,onValueChange:nt=>Ve("status",nt),children:[e.jsx(us,{children:e.jsx(fs,{})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"all",children:"All members"}),e.jsx(Ge,{value:"active",children:"Active (signed in)"}),e.jsx(Ge,{value:"pending",children:"Pending (never signed in)"})]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Membership"}),e.jsxs(ms,{value:v.billing,onValueChange:nt=>Ve("billing",nt),children:[e.jsx(us,{children:e.jsx(fs,{})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"all",children:"Any membership"}),e.jsx(Ge,{value:"trial",children:"On trial"}),e.jsx(Ge,{value:"paid",children:"Paid subscribers"}),e.jsx(Ge,{value:"grandfathered",children:"Grandfathered"}),e.jsx(Ge,{value:"canceled",children:"Canceled / past due"})]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Role"}),e.jsxs(ms,{value:v.role,onValueChange:nt=>Ve("role",nt),children:[e.jsx(us,{children:e.jsx(fs,{})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"all",children:"Any role"}),e.jsx(Ge,{value:"user",children:"Members"}),e.jsx(Ge,{value:"brokerage_manager",children:"Brokerage managers"}),e.jsx(Ge,{value:"coach",children:"Coaches"}),e.jsx(Ge,{value:"assistant",children:"Assistants"}),e.jsx(Ge,{value:"admin",children:"Admins"})]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Brokerage"}),e.jsxs(ms,{value:v.brokerage,onValueChange:nt=>Ve("brokerage",nt),children:[e.jsx(us,{children:e.jsx(fs,{})}),e.jsxs(hs,{className:"max-h-72",children:[e.jsx(Ge,{value:"all",children:"All brokerages"}),e.jsx(Ge,{value:"none",children:"No brokerage"}),(Ee||[]).map(nt=>e.jsx(Ge,{value:nt.id,children:nt.name},nt.id))]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Program enrollment"}),e.jsxs(ms,{value:v.program,onValueChange:nt=>Ve("program",nt),children:[e.jsx(us,{children:e.jsx(fs,{})}),e.jsxs(hs,{className:"max-h-72",children:[e.jsx(Ge,{value:"all",children:"Not filtered by program"}),e.jsx(Ge,{value:"any",children:"Enrolled in any program"}),(Se||[]).map(nt=>e.jsx(Ge,{value:nt.id,children:nt.name},nt.id))]})]})]}),v.program!=="all"&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Enrollment status"}),e.jsxs(ms,{value:v.programStatus,onValueChange:nt=>Ve("programStatus",nt),children:[e.jsx(us,{children:e.jsx(fs,{})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"active",children:"Active enrollees (paid, reserved, completed)"}),e.jsx(Ge,{value:"any",children:"Any enrollment status"}),e.jsx(Ge,{value:"paid",children:"Paid"}),e.jsx(Ge,{value:"reserved",children:"Reserved"}),e.jsx(Ge,{value:"scheduled_for_charge",children:"Scheduled for charge"}),e.jsx(Ge,{value:"pending_payment_method",children:"Pending payment method"}),e.jsx(Ge,{value:"payment_failed",children:"Payment failed"}),e.jsx(Ge,{value:"completed",children:"Completed"}),e.jsx(Ge,{value:"canceled",children:"Canceled"}),e.jsx(Ge,{value:"refunded",children:"Refunded"})]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Joined within"}),e.jsxs(ms,{value:v.joinedWithinDays?String(v.joinedWithinDays):"all",onValueChange:nt=>Ve("joinedWithinDays",nt==="all"?null:Number(nt)),children:[e.jsx(us,{children:e.jsx(fs,{})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"all",children:"Any time"}),e.jsx(Ge,{value:"30",children:"Last 30 days"}),e.jsx(Ge,{value:"60",children:"Last 60 days"}),e.jsx(Ge,{value:"90",children:"Last 90 days"})]})]})]}),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:"Respect opt-outs"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Skip members who opted out of updates"})]}),e.jsx(Sn,{checked:v.respectOptOut,onCheckedChange:nt=>Ve("respectOptOut",nt)})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx($,{variant:"ghost",size:"sm",onClick:()=>b(F9e),children:"Reset"}),e.jsxs($,{variant:"outline",size:"sm",className:"gap-2",onClick:()=>ke(v),disabled:C,children:[C?e.jsx(kt,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(ro,{className:"h-3.5 w-3.5"}),"Refresh"]})]}),(Ke=w==null?void 0:w.sample)!=null&&Ke.length?e.jsxs("div",{className:"rounded-lg bg-muted/40 p-3",children:[e.jsx("p",{className:"mb-2 text-xs font-medium text-muted-foreground",children:"Sample recipients"}),e.jsx("div",{className:"space-y-1",children:w.sample.map(nt=>e.jsxs("p",{className:"truncate text-xs",children:[e.jsx("span",{className:"font-medium",children:nt.name||"Member"})," ",e.jsx("span",{className:"text-muted-foreground",children:nt.email})]},nt.email))})]}):null]})]})]})}),e.jsxs("div",{className:"space-y-6",children:[e.jsxs(Ne,{children:[e.jsxs(Ct,{className:"pb-4",children:[e.jsx(At,{className:"text-base",children:"Message"}),e.jsxs(Gn,{children:["Personalize with merge tags: ",dFn.join(" ")]})]}),e.jsxs(Ie,{className:"space-y-4",children:[e.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Internal name"}),e.jsx(pe,{value:I,onChange:nt=>P(nt.target.value),placeholder:"August product update"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Subject line"}),e.jsx(pe,{value:R,onChange:nt=>D(nt.target.value),placeholder:"Big news for LevelUp members"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"From (must be a verified sender)"}),e.jsx(pe,{value:O,onChange:nt=>U(nt.target.value),placeholder:"hello@relevelup.com"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Reply-to"}),e.jsx(pe,{value:W,onChange:nt=>V(nt.target.value),placeholder:"support@relevelup.com"})]})]}),e.jsxs(ha,{value:G,onValueChange:nt=>Y(nt),children:[e.jsxs(ma,{children:[e.jsxs(Zt,{value:"rich",className:"gap-2",children:[e.jsx(Nn,{className:"h-3.5 w-3.5"})," Rich text"]}),e.jsxs(Zt,{value:"html",className:"gap-2",children:[e.jsx(EE,{className:"h-3.5 w-3.5"})," Paste HTML"]})]}),e.jsx(Xt,{value:"rich",className:"mt-3",children:e.jsx(Ek,{content:X,onChange:ae,minHeight:"320px",placeholder:"Write your message…"})}),e.jsxs(Xt,{value:"html",className:"mt-3 space-y-2",children:[e.jsx(Rs,{value:ie,onChange:nt=>ne(nt.target.value),placeholder:"…paste your full email HTML here…",className:"min-h-[320px] font-mono text-xs"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Paste full HTML from Canva, Beefree, Mailchimp, etc. It is sent exactly as written (merge tags still work)."})]})]})]})]}),e.jsxs(Ne,{children:[e.jsxs(Ct,{className:"flex flex-row items-center justify-between space-y-0 pb-3",children:[e.jsxs(At,{className:"flex items-center gap-2 text-base",children:[e.jsx(Ca,{className:"h-4 w-4"})," Preview"]}),e.jsx(Be,{variant:"secondary",children:G==="html"?"Raw HTML":"Rich text"})]}),e.jsx(Ie,{children:e.jsx("iframe",{title:"Email preview",srcDoc:uFn(ve),className:"h-[420px] w-full rounded-lg border bg-white"})})]}),e.jsx(Ne,{children:e.jsxs(Ie,{className:"space-y-4 pt-6",children:[he&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex justify-between text-sm",children:[e.jsxs("span",{children:[he.sent+he.failed," of ",he.total," processed"]}),e.jsxs("span",{className:"text-muted-foreground",children:[he.sent," sent",he.failed?` • ${he.failed} failed`:""]})]}),e.jsx(Yi,{value:he.total?(he.sent+he.failed)/he.total*100:0})]}),e.jsxs("div",{className:"flex flex-wrap items-end gap-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Send a test to"}),e.jsx(pe,{value:te,onChange:nt=>J(nt.target.value),className:"w-64"})]}),e.jsx($,{variant:"outline",onClick:Xe,disabled:ce,children:"Send test"}),e.jsx("div",{className:"flex-1"}),e.jsxs($,{onClick:it,disabled:!ct||ce,size:"lg",className:"gap-2",children:[ce?e.jsx(kt,{className:"h-4 w-4 animate-spin"}):e.jsx(Yr,{className:"h-4 w-4"}),ce?"Sending…":`Send to ${je} member${je===1?"":"s"}`]})]}),e.jsxs("div",{className:"flex flex-wrap items-end gap-3 border-t pt-4",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Save as template"}),e.jsx(pe,{value:f,onChange:nt=>g(nt.target.value),placeholder:I||R||"Template name",className:"w-64"})]}),e.jsxs($,{variant:"outline",className:"gap-2",onClick:qe,disabled:x,children:[x?e.jsx(kt,{className:"h-4 w-4 animate-spin"}):e.jsx(qI,{className:"h-4 w-4"}),"Save template"]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Saves the subject, content, sender and current filters for reuse later."})]})]})})]})]})}),e.jsx(Xt,{value:"templates",className:"space-y-3",children:(Fe||[]).length===0?e.jsx(Ne,{children:e.jsxs(Ie,{className:"flex flex-col items-center py-14 text-center",children:[e.jsx(m2,{className:"mb-3 h-10 w-10 text-muted-foreground"}),e.jsx("p",{className:"font-medium",children:"No saved templates yet"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:'Compose an email, then use "Save template" to reuse it for future sends.'})]})}):(Fe||[]).map(nt=>e.jsx(Ne,{children:e.jsxs(Ie,{className:"flex flex-wrap items-center justify-between gap-4 py-4",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h3",{className:"truncate text-sm font-semibold",children:nt.name}),e.jsx(Be,{variant:"secondary",className:"text-xs",children:nt.editor_mode==="html"?"Raw HTML":"Rich text"})]}),e.jsxs("p",{className:"truncate text-xs text-muted-foreground",children:["Subject: ",nt.subject||"—"]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Updated ",en(new Date(nt.updated_at),"MMM d, yyyy h:mm a")]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs($,{size:"sm",className:"gap-2",onClick:()=>ze(nt),children:[e.jsx(tl,{className:"h-3.5 w-3.5"})," Use template"]}),e.jsx($,{size:"sm",variant:"ghost",onClick:()=>$e(nt),children:e.jsx(Wn,{className:"h-3.5 w-3.5"})})]})]})},nt.id))}),e.jsx(Xt,{value:"history",className:"space-y-3",children:(Le||[]).length===0?e.jsx(Ne,{children:e.jsxs(Ie,{className:"flex flex-col items-center py-14 text-center",children:[e.jsx(mn,{className:"mb-3 h-10 w-10 text-muted-foreground"}),e.jsx("p",{className:"font-medium",children:"No broadcasts sent yet"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Your sent member emails will show up here."})]})}):(Le||[]).map(nt=>e.jsx(Ne,{children:e.jsxs(Ie,{className:"flex flex-wrap items-center justify-between gap-4 py-4",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h3",{className:"truncate text-sm font-semibold",children:nt.name}),e.jsxs(Be,{variant:nt.status==="sent"?"default":nt.status==="sending"?"secondary":"outline",className:"gap-1 text-xs",children:[nt.status==="sent"?e.jsx(qr,{className:"h-3 w-3"}):e.jsx(ll,{className:"h-3 w-3"}),nt.status]})]}),e.jsxs("p",{className:"truncate text-xs text-muted-foreground",children:["Subject: ",nt.subject]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[en(new Date(nt.created_at),"MMM d, yyyy h:mm a")," • from ",nt.from_email]})]}),e.jsxs("div",{className:"flex gap-6 text-center",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-lg font-bold",children:nt.total_recipients}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Recipients"})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-lg font-bold",children:nt.sent_count}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Sent"})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-lg font-bold",children:nt.failed_count}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Failed"})]}),e.jsxs("div",{children:[e.jsxs("p",{className:"text-lg font-bold",children:[nt.open_count??0,nt.sent_count>0&&e.jsxs("span",{className:"ml-1 text-xs font-medium text-muted-foreground",children:[Math.round((nt.open_count??0)/nt.sent_count*100),"%"]})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Opens"})]}),e.jsxs("div",{children:[e.jsxs("p",{className:"text-lg font-bold",children:[nt.click_count??0,nt.sent_count>0&&e.jsxs("span",{className:"ml-1 text-xs font-medium text-muted-foreground",children:[Math.round((nt.click_count??0)/nt.sent_count*100),"%"]})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Clicks"})]}),nt.failed_count>0&&e.jsx("div",{className:"flex items-center",children:e.jsx($,{size:"sm",variant:"outline",disabled:ce,onClick:()=>at(nt.id),children:"Retry failed"})})]})]})},nt.id))})]})]})})}const mFn=["Headers","Footers","Seasonal","Holidays","Market Updates","Just Sold","Just Listed","Open House","Buyer Tips","Seller Tips","Testimonials","CTAs & Buttons","Dividers","General"];function fFn(){const s=Vt(),t=j.useRef(null),[n,r]=j.useState(""),[a,i]=j.useState("all"),[l,o]=j.useState(null),[c,d]=j.useState(!1),[u,h]=j.useState(!1),[m,f]=j.useState({title:"",description:"",image_url:"",category:"General",tags:"",is_active:!0,is_featured:!1}),{data:g=[],isLoading:x}=tt({queryKey:["admin-newsletter-graphics"],queryFn:async()=>{const{data:O,error:U}=await q.from("newsletter_graphics").select("*").order("is_featured",{ascending:!1}).order("created_at",{ascending:!1});if(U)throw U;return O||[]}}),y=j.useMemo(()=>{const O=new Set(mFn);return g.forEach(U=>O.add(U.category)),Array.from(O).sort()},[g]),v=j.useMemo(()=>{const O=n.trim().toLowerCase();return g.filter(U=>a!=="all"&&U.category!==a?!1:O?U.title.toLowerCase().includes(O)||(U.description||"").toLowerCase().includes(O)||U.tags.some(W=>W.toLowerCase().includes(O)):!0)},[g,n,a]),b=()=>{f({title:"",description:"",image_url:"",category:"General",tags:"",is_active:!0,is_featured:!1}),o(null)},w=()=>{b(),d(!0)},S=O=>{o(O),f({title:O.title,description:O.description||"",image_url:O.image_url,category:O.category,tags:O.tags.join(", "),is_active:O.is_active,is_featured:O.is_featured}),d(!0)},C=async O=>{var U;if(!O.type.startsWith("image/")){re.error("Please choose an image file");return}if(O.size>15*1024*1024){re.error("Image must be under 15MB");return}h(!0);try{const W=((U=O.name.split(".").pop())==null?void 0:U.toLowerCase())||"png",V=`graphics-library/${Date.now()}-${Math.random().toString(36).slice(2,8)}.${W}`,{error:G}=await q.storage.from("newsletter-content").upload(V,O,{cacheControl:"31536000",upsert:!1,contentType:O.type});if(G)throw G;const{data:Y}=q.storage.from("newsletter-content").getPublicUrl(V);f(X=>({...X,image_url:Y.publicUrl,title:X.title||O.name.replace(/\.[^.]+$/,"").replace(/[-_]/g," ")})),re.success("Uploaded")}catch(W){re.error(W.message||"Upload failed")}finally{h(!1),t.current&&(t.current.value="")}},E=ft({mutationFn:async()=>{var W;if(!m.image_url)throw new Error("Please upload an image");if(!m.title.trim())throw new Error("Please add a title");const O=m.tags.split(",").map(V=>V.trim()).filter(Boolean),U={title:m.title.trim(),description:m.description.trim()||null,image_url:m.image_url,category:m.category||"General",tags:O,is_active:m.is_active,is_featured:m.is_featured};if(l){const{error:V}=await q.from("newsletter_graphics").update(U).eq("id",l.id);if(V)throw V}else{const{data:V}=await q.auth.getUser(),{error:G}=await q.from("newsletter_graphics").insert({...U,created_by:(W=V.user)==null?void 0:W.id});if(G)throw G}},onSuccess:()=>{re.success(l?"Updated":"Graphic added to library"),s.invalidateQueries({queryKey:["admin-newsletter-graphics"]}),s.invalidateQueries({queryKey:["newsletter-graphics-picker"]}),d(!1),b()},onError:O=>re.error(O.message||"Save failed")}),I=ft({mutationFn:async O=>{const{error:U}=await q.from("newsletter_graphics").delete().eq("id",O);if(U)throw U},onSuccess:()=>{re.success("Deleted"),s.invalidateQueries({queryKey:["admin-newsletter-graphics"]}),s.invalidateQueries({queryKey:["newsletter-graphics-picker"]})},onError:O=>re.error(O.message||"Delete failed")}),P=async O=>{const{error:U}=await q.from("newsletter_graphics").update({is_active:!O.is_active}).eq("id",O.id);U?re.error(U.message):(s.invalidateQueries({queryKey:["admin-newsletter-graphics"]}),s.invalidateQueries({queryKey:["newsletter-graphics-picker"]}))},R=async O=>{const{error:U}=await q.from("newsletter_graphics").update({is_featured:!O.is_featured}).eq("id",O.id);U?re.error(U.message):(s.invalidateQueries({queryKey:["admin-newsletter-graphics"]}),s.invalidateQueries({queryKey:["newsletter-graphics-picker"]}))},D=O=>{navigator.clipboard.writeText(O),re.success("URL copied")};return e.jsxs(Vs,{children:[e.jsxs("div",{className:"p-4 md:p-6 max-w-7xl mx-auto space-y-5",children:[e.jsx(Fm,{title:"Newsletter Graphics Library",description:"Upload branded graphics agents can drop into their newsletters and email campaigns."}),e.jsx(Ne,{children:e.jsxs(Ie,{className:"p-4 flex flex-col md:flex-row gap-3 md:items-center",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(Kr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(pe,{value:n,onChange:O=>r(O.target.value),placeholder:"Search graphics by title, tag, description...",className:"pl-9"})]}),e.jsxs(ms,{value:a,onValueChange:i,children:[e.jsx(us,{className:"w-full md:w-56",children:e.jsx(fs,{})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"all",children:"All categories"}),y.map(O=>e.jsx(Ge,{value:O,children:O},O))]})]}),e.jsxs($,{onClick:w,className:"gap-1.5 whitespace-nowrap",children:[e.jsx(Av,{className:"h-4 w-4"})," Add Graphic"]})]})}),x?e.jsx("div",{className:"flex justify-center py-16",children:e.jsx(kt,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):v.length===0?e.jsx(Ne,{children:e.jsxs(Ie,{className:"py-16 text-center",children:[e.jsx(Mc,{className:"h-10 w-10 mx-auto mb-3 text-muted-foreground/50"}),e.jsx("p",{className:"text-sm text-muted-foreground mb-4",children:g.length===0?"No graphics uploaded yet — add your first one to get started.":"No graphics match your filters."}),g.length===0&&e.jsxs($,{onClick:w,className:"gap-1.5",children:[e.jsx(Av,{className:"h-4 w-4"})," Upload First Graphic"]})]})}):e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-4",children:v.map(O=>e.jsxs(Ne,{className:`overflow-hidden group ${O.is_active?"":"opacity-60"}`,children:[e.jsxs("div",{className:"aspect-video bg-muted relative overflow-hidden",children:[e.jsx("img",{src:O.image_url,alt:O.title,loading:"lazy",className:"w-full h-full object-cover"}),O.is_featured&&e.jsxs(Be,{className:"absolute top-2 left-2 gap-0.5 bg-amber-500 hover:bg-amber-500 text-white border-0",children:[e.jsx(Ja,{className:"h-3 w-3 fill-current"})," Featured"]}),!O.is_active&&e.jsx(Be,{variant:"secondary",className:"absolute top-2 right-2",children:"Hidden"})]}),e.jsxs(Ie,{className:"p-3 space-y-2",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-sm truncate",children:O.title}),e.jsx("p",{className:"text-xs text-muted-foreground",children:O.category})]}),O.tags.length>0&&e.jsx("div",{className:"flex flex-wrap gap-1",children:O.tags.slice(0,3).map(U=>e.jsx(Be,{variant:"outline",className:"text-[10px] px-1.5 py-0",children:U},U))}),e.jsxs("div",{className:"flex items-center justify-between pt-1 border-t",children:[e.jsxs("div",{className:"flex gap-1",children:[e.jsx($,{size:"icon",variant:"ghost",className:"h-7 w-7",onClick:()=>S(O),title:"Edit",children:e.jsx(gi,{className:"h-3.5 w-3.5"})}),e.jsx($,{size:"icon",variant:"ghost",className:"h-7 w-7",onClick:()=>R(O),title:O.is_featured?"Unfeature":"Feature",children:e.jsx(Ja,{className:`h-3.5 w-3.5 ${O.is_featured?"fill-amber-500 text-amber-500":""}`})}),e.jsx($,{size:"icon",variant:"ghost",className:"h-7 w-7",onClick:()=>D(O.image_url),title:"Copy URL",children:e.jsx(Ha,{className:"h-3.5 w-3.5"})})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Sn,{checked:O.is_active,onCheckedChange:()=>P(O)}),e.jsx($,{size:"icon",variant:"ghost",className:"h-7 w-7 text-destructive hover:text-destructive",onClick:async()=>{await fo(`Delete "${O.title}"?`)&&I.mutate(O.id)},children:e.jsx(Wn,{className:"h-3.5 w-3.5"})})]})]})]})]},O.id))})]}),e.jsx(zs,{open:c,onOpenChange:d,children:e.jsxs(Os,{className:"sm:max-w-lg max-h-[90vh] overflow-y-auto",children:[e.jsx(Us,{children:e.jsx(Bs,{children:l?"Edit Graphic":"Add New Graphic"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(ee,{children:"Image"}),e.jsx("input",{ref:t,type:"file",accept:"image/*",className:"hidden",onChange:O=>{var W;const U=(W=O.target.files)==null?void 0:W[0];U&&C(U)}}),m.image_url?e.jsxs("div",{className:"relative rounded-lg overflow-hidden border bg-muted/30 mt-1.5",children:[e.jsx("img",{src:m.image_url,alt:"Preview",className:"w-full max-h-64 object-contain"}),e.jsx($,{type:"button",variant:"destructive",size:"icon",className:"absolute top-2 right-2 h-7 w-7",onClick:()=>f(O=>({...O,image_url:""})),children:e.jsx(gr,{className:"h-3.5 w-3.5"})})]}):e.jsx("button",{type:"button",onClick:()=>{var O;return(O=t.current)==null?void 0:O.click()},disabled:u,className:"w-full mt-1.5 rounded-lg border-2 border-dashed border-border hover:border-primary/50 hover:bg-muted/40 transition-colors py-10 text-center disabled:opacity-60",children:u?e.jsxs(e.Fragment,{children:[e.jsx(kt,{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(ni,{className:"h-8 w-8 mx-auto mb-2 text-muted-foreground"}),e.jsx("p",{className:"text-sm font-medium",children:"Click to upload image"}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"PNG, JPG, WEBP, GIF · up to 15MB"})]})})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"g-title",children:"Title *"}),e.jsx(pe,{id:"g-title",value:m.title,onChange:O=>f(U=>({...U,title:O.target.value})),placeholder:"e.g. Fall Market Update Banner"})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"g-desc",children:"Description"}),e.jsx(Rs,{id:"g-desc",value:m.description,onChange:O=>f(U=>({...U,description:O.target.value})),placeholder:"Short note about when to use this graphic",rows:2})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(ee,{children:"Category"}),e.jsxs(ms,{value:m.category,onValueChange:O=>f(U=>({...U,category:O})),children:[e.jsx(us,{children:e.jsx(fs,{})}),e.jsx(hs,{children:y.map(O=>e.jsx(Ge,{value:O,children:O},O))})]})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"g-tags",children:"Tags (comma-separated)"}),e.jsx(pe,{id:"g-tags",value:m.tags,onChange:O=>f(U=>({...U,tags:O.target.value})),placeholder:"fall, autumn, banner"})]})]}),e.jsxs("div",{className:"flex items-center justify-between rounded-md border p-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",children:"Featured"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Show at top of the picker"})]}),e.jsx(Sn,{checked:m.is_featured,onCheckedChange:O=>f(U=>({...U,is_featured:O}))})]}),e.jsxs("div",{className:"flex items-center justify-between rounded-md border p-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",children:"Active"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Visible to agents"})]}),e.jsx(Sn,{checked:m.is_active,onCheckedChange:O=>f(U=>({...U,is_active:O}))})]})]}),e.jsxs(Ar,{children:[e.jsx($,{variant:"outline",onClick:()=>d(!1),children:"Cancel"}),e.jsxs($,{onClick:()=>E.mutate(),disabled:E.isPending,children:[E.isPending&&e.jsx(kt,{className:"h-3.5 w-3.5 mr-1.5 animate-spin"}),l?"Save Changes":"Add to Library"]})]})]})})]})}const hSt={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 pFn(){const{user:s}=vs(),{toast:t}=Bi(),n=Qn(),r=Vt(),[a,i]=j.useState(""),[l,o]=j.useState("popular"),[c,d]=j.useState(!1),[u,h]=j.useState(""),[m,f]=j.useState(""),[g,x]=j.useState(!1),{data:y=[],isLoading:v}=tt({queryKey:["wishlist-items",l,g],queryFn:async()=>{let E=q.from("wishlist_items").select("*");g&&s&&(E=E.eq("user_id",s.id)),l==="latest"?E=E.order("created_at",{ascending:!1}):l==="popular"?E=E.order("vote_count",{ascending:!1}):l==="trending"&&(E=E.order("vote_count",{ascending:!1}));const{data:I,error:P}=await E;if(P)throw P;const R=[...new Set((I==null?void 0:I.map(Y=>Y.user_id))||[])],{data:D}=await q.from("profiles").select("id, name").in("id",R),O=new Map((D==null?void 0:D.map(Y=>[Y.id,Y]))||[]);let U=[];if(s){const{data:Y}=await q.from("wishlist_votes").select("item_id").eq("user_id",s.id);U=(Y==null?void 0:Y.map(X=>X.item_id))||[]}const W=(I==null?void 0:I.map(Y=>Y.id))||[],{data:V}=await q.from("wishlist_comments").select("item_id").in("item_id",W),G=new Map;return V==null||V.forEach(Y=>{G.set(Y.item_id,(G.get(Y.item_id)||0)+1)}),I==null?void 0:I.map(Y=>{const X=O.get(Y.user_id),ae=(X==null?void 0:X.name)||"Unknown";return{...Y,user_name:ae,user_initials:ae.split(" ").map(ie=>ie[0]).join("").toUpperCase().slice(0,2),has_voted:U.includes(Y.id),comment_count:G.get(Y.id)||0}})}}),b=ft({mutationFn:async({title:E,description:I})=>{const{error:P}=await q.from("wishlist_items").insert({user_id:s.id,title:E,description:I});if(P)throw P},onSuccess:()=>{r.invalidateQueries({queryKey:["wishlist-items"]}),d(!1),h(""),f(""),t({title:"Idea submitted!",description:"Your idea has been added to the wishlist."})},onError:E=>{t({title:"Error",description:E.message,variant:"destructive"})}}),w=ft({mutationFn:async({itemId:E,hasVoted:I})=>{if(I){const{error:P}=await q.from("wishlist_votes").delete().eq("item_id",E).eq("user_id",s.id);if(P)throw P;return{itemId:E,wasAdded:!1}}else{const{error:P}=await q.from("wishlist_votes").insert({item_id:E,user_id:s.id});if(P)throw P;return{itemId:E,wasAdded:!0}}},onSuccess:async E=>{if(r.invalidateQueries({queryKey:["wishlist-items"]}),E!=null&&E.wasAdded){const I=y.find(R=>R.id===E.itemId),P=((I==null?void 0:I.vote_count)||0)+1;q.functions.invoke("wishlist-notify",{body:{itemId:E.itemId,voteCount:P}}).catch(console.error)}},onError:E=>{t({title:"Error",description:E.message,variant:"destructive"})}}),S=y.filter(E=>E.title.toLowerCase().includes(a.toLowerCase())||E.description.toLowerCase().includes(a.toLowerCase())),C=()=>{if(!u.trim()||!m.trim()){t({title:"Error",description:"Please fill in both title and description.",variant:"destructive"});return}b.mutate({title:u.trim(),description:m.trim()})};return e.jsx(Vs,{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(tC,{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(zs,{open:c,onOpenChange:d,children:[e.jsx(jl,{asChild:!0,children:e.jsxs($,{className:"gap-2",children:[e.jsx(dn,{className:"h-4 w-4"}),"Add Idea"]})}),e.jsxs(Os,{children:[e.jsx(Us,{children:e.jsx(Bs,{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(ee,{htmlFor:"title",children:"Title"}),e.jsx(pe,{id:"title",placeholder:"Give your idea a clear title...",value:u,onChange:E=>h(E.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"description",children:"Description"}),e.jsx(Rs,{id:"description",placeholder:"Describe your idea in detail. What problem does it solve? How would it help agents?",value:m,onChange:E=>f(E.target.value),rows:4})]}),e.jsx($,{onClick:C,className:"w-full",disabled:b.isPending,children:b.isPending?e.jsxs(e.Fragment,{children:[e.jsx(kt,{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(Kr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(pe,{placeholder:"Search ideas...",value:a,onChange:E=>i(E.target.value),className:"pl-10"})]}),e.jsx("div",{className:"flex gap-2",children:e.jsx(ha,{value:l,onValueChange:E=>o(E),children:e.jsxs(ma,{children:[e.jsx(Zt,{value:"popular",children:"Most Popular"}),e.jsx(Zt,{value:"latest",children:"Latest"}),e.jsx(Zt,{value:"trending",children:"Trending"})]})})})]}),e.jsx("div",{className:"flex items-center gap-2 mb-4",children:e.jsx($,{variant:g?"default":"outline",size:"sm",onClick:()=>x(!g),children:g?"Show All Ideas":"My Ideas"})}),v?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(kt,{className:"h-8 w-8 animate-spin text-muted-foreground"})}):S.length===0?e.jsxs("div",{className:"text-center py-12 bg-muted/30 rounded-lg",children:[e.jsx(tC,{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($,{onClick:()=>d(!0),children:[e.jsx(dn,{className:"h-4 w-4 mr-2"}),"Add Idea"]})]}):e.jsx("div",{className:"space-y-3",children:S.map(E=>e.jsx("div",{className:"bg-card border rounded-lg p-4 hover:shadow-md transition-shadow cursor-pointer",onClick:()=>n(`/wishlist/${E.id}`),children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsxs("button",{onClick:I=>{I.stopPropagation(),w.mutate({itemId:E.id,hasVoted:E.has_voted||!1})},className:Pt("flex flex-col items-center justify-center min-w-[50px] py-2 px-3 rounded-lg border transition-colors",E.has_voted?"bg-primary/10 border-primary text-primary":"bg-muted/50 border-border hover:bg-muted"),children:[e.jsx(Zf,{className:Pt("h-4 w-4",E.has_voted&&"fill-current")}),e.jsx("span",{className:"text-sm font-semibold",children:E.vote_count})]}),e.jsx(Oa,{className:"h-10 w-10 bg-primary/20",children:e.jsx(za,{className:"bg-primary/20 text-primary text-sm font-medium",children:E.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:E.title}),e.jsx(Be,{className:Pt("text-xs",hSt[E.status].color),children:hSt[E.status].label})]}),e.jsx("p",{className:"text-muted-foreground text-sm line-clamp-2",children:E.description}),e.jsxs("div",{className:"flex items-center gap-3 mt-2 text-xs text-muted-foreground",children:[e.jsx("span",{children:E.user_name}),e.jsx("span",{children:"•"}),e.jsx("span",{children:new Date(E.created_at).toLocaleDateString()})]})]}),e.jsxs("div",{className:"flex items-center gap-1 text-muted-foreground",children:[e.jsx(eo,{className:"h-4 w-4"}),e.jsx("span",{className:"text-sm",children:E.comment_count})]})]})},E.id))})]})})}const mSt={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 gFn(){const{itemId:s}=Wi(),t=Qn(),{user:n}=vs(),{toast:r}=Bi(),a=Vt(),[i,l]=j.useState(""),{data:o=!1}=tt({queryKey:["user-is-admin",n==null?void 0:n.id],queryFn:async()=>{if(!n)return!1;const{data:y,error:v}=await q.from("user_roles").select("role").eq("user_id",n.id).eq("role","admin").maybeSingle();return!v&&!!y},enabled:!!n}),{data:c,isLoading:d}=tt({queryKey:["wishlist-item",s],queryFn:async()=>{const{data:y,error:v}=await q.from("wishlist_items").select("*").eq("id",s).single();if(v)throw v;const{data:b}=await q.from("profiles").select("name").eq("id",y.user_id).single();let w=!1;if(n){const{data:S}=await q.from("wishlist_votes").select("id").eq("item_id",s).eq("user_id",n.id).maybeSingle();w=!!S}return{...y,user_name:(b==null?void 0:b.name)||"Unknown",user_initials:((b==null?void 0:b.name)||"U").split(" ").map(S=>S[0]).join("").toUpperCase().slice(0,2),has_voted:w}}}),{data:u=[],isLoading:h}=tt({queryKey:["wishlist-comments",s],queryFn:async()=>{const{data:y,error:v}=await q.from("wishlist_comments").select("*").eq("item_id",s).order("created_at",{ascending:!0});if(v)throw v;const b=[...new Set((y==null?void 0:y.map(C=>C.user_id))||[])],{data:w}=await q.from("profiles").select("id, name").in("id",b),S=new Map((w==null?void 0:w.map(C=>[C.id,C]))||[]);return y==null?void 0:y.map(C=>{const E=S.get(C.user_id),I=(E==null?void 0:E.name)||"Unknown";return{...C,user_name:I,user_initials:I.split(" ").map(P=>P[0]).join("").toUpperCase().slice(0,2)}})}}),m=ft({mutationFn:async y=>{if(y){const{error:v}=await q.from("wishlist_votes").delete().eq("item_id",s).eq("user_id",n.id);if(v)throw v;return{wasAdded:!1}}else{const{error:v}=await q.from("wishlist_votes").insert({item_id:s,user_id:n.id});if(v)throw v;return{wasAdded:!0}}},onSuccess:async y=>{if(a.invalidateQueries({queryKey:["wishlist-item",s]}),a.invalidateQueries({queryKey:["wishlist-items"]}),y!=null&&y.wasAdded&&c){const v=(c.vote_count||0)+1;q.functions.invoke("wishlist-notify",{body:{itemId:s,voteCount:v}}).catch(console.error)}},onError:y=>{r({title:"Error",description:y.message,variant:"destructive"})}}),f=ft({mutationFn:async y=>{const{error:v}=await q.from("wishlist_comments").insert({item_id:s,user_id:n.id,content:y});if(v)throw v},onSuccess:()=>{a.invalidateQueries({queryKey:["wishlist-comments",s]}),l(""),r({title:"Comment added!"})},onError:y=>{r({title:"Error",description:y.message,variant:"destructive"})}}),g=ft({mutationFn:async y=>{const{error:v}=await q.from("wishlist_comments").delete().eq("id",y);if(v)throw v},onSuccess:()=>{a.invalidateQueries({queryKey:["wishlist-comments",s]}),r({title:"Comment deleted"})},onError:y=>{r({title:"Error",description:y.message,variant:"destructive"})}}),x=()=>{i.trim()&&f.mutate(i.trim())};return d?e.jsx(Vs,{title:"Wishlist",children:e.jsxs("div",{className:"max-w-3xl mx-auto",children:[e.jsx(yn,{className:"h-8 w-32 mb-6"}),e.jsx(yn,{className:"h-48 w-full mb-6"}),e.jsx(yn,{className:"h-32 w-full"})]})}):c?e.jsx(Vs,{title:"Wishlist",children:e.jsxs("div",{className:"max-w-3xl mx-auto",children:[e.jsxs($,{variant:"ghost",size:"sm",onClick:()=>t("/wishlist"),className:"mb-4",children:[e.jsx(qa,{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:()=>m.mutate(c.has_voted),className:Pt("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(Zf,{className:Pt("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(Be,{className:Pt("text-xs",mSt[c.status].color),children:mSt[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(Oa,{className:"h-6 w-6",children:e.jsx(za,{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 (",u.length,")"]}),e.jsxs("div",{className:"flex gap-3 mb-6",children:[e.jsx(HTe,{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($,{onClick:x,disabled:!i.trim()||f.isPending,size:"icon",className:"h-auto",children:f.isPending?e.jsx(kt,{className:"h-4 w-4 animate-spin"}):e.jsx(Yr,{className:"h-4 w-4"})})]}),h?e.jsx("div",{className:"space-y-4",children:[1,2].map(y=>e.jsx(yn,{className:"h-20 w-full"},y))}):u.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:u.map(y=>e.jsxs("div",{className:"flex gap-3 p-3 bg-muted/30 rounded-lg",children:[e.jsx(Oa,{className:"h-8 w-8",children:e.jsx(za,{className:"bg-primary/20 text-primary text-xs",children:y.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:y.user_name}),e.jsx("span",{className:"text-xs text-muted-foreground",children:new Date(y.created_at).toLocaleDateString()})]}),e.jsx(qrt,{content:y.content,className:"text-sm text-foreground"})]}),(n==null?void 0:n.id)===y.user_id&&e.jsx($,{variant:"ghost",size:"icon",className:"h-8 w-8 text-muted-foreground hover:text-destructive",onClick:()=>g.mutate(y.id),children:e.jsx(Wn,{className:"h-4 w-4"})})]},y.id))})]})]})}):e.jsx(Vs,{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($,{variant:"link",onClick:()=>t("/wishlist"),children:"Go back to Wishlist"})]})})}const fSt={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"}},pSt=["open","under_review","planned","in_progress","launched","declined"];function xFn(){const{toast:s}=Bi(),t=Qn(),n=Vt(),[r,a]=j.useState(""),[i,l]=j.useState("all"),[o,c]=j.useState(!1),[d,u]=j.useState(null),{data:h=[],isLoading:m}=tt({queryKey:["admin-wishlist-items"],queryFn:async()=>{const{data:v,error:b}=await q.from("wishlist_items").select("*").order("vote_count",{ascending:!1});if(b)throw b;const w=[...new Set((v==null?void 0:v.map(R=>R.user_id))||[])],{data:S}=await q.from("profiles").select("id, name, email").in("id",w),C=new Map((S==null?void 0:S.map(R=>[R.id,R]))||[]),E=(v==null?void 0:v.map(R=>R.id))||[],{data:I}=await q.from("wishlist_comments").select("item_id").in("item_id",E),P=new Map;return I==null||I.forEach(R=>{P.set(R.item_id,(P.get(R.item_id)||0)+1)}),v==null?void 0:v.map(R=>{const D=C.get(R.user_id);return{...R,user_name:(D==null?void 0:D.name)||"Unknown",user_email:(D==null?void 0:D.email)||"",comment_count:P.get(R.id)||0}})}}),f=ft({mutationFn:async({itemId:v,status:b})=>{const{error:w}=await q.from("wishlist_items").update({status:b}).eq("id",v);if(w)throw w},onSuccess:()=>{n.invalidateQueries({queryKey:["admin-wishlist-items"]}),s({title:"Status updated!"})},onError:v=>{s({title:"Error",description:v.message,variant:"destructive"})}}),g=ft({mutationFn:async v=>{const{error:b}=await q.from("wishlist_items").delete().eq("id",v);if(b)throw b},onSuccess:()=>{n.invalidateQueries({queryKey:["admin-wishlist-items"]}),c(!1),u(null),s({title:"Item deleted!"})},onError:v=>{s({title:"Error",description:v.message,variant:"destructive"})}}),x=h.filter(v=>{const b=v.title.toLowerCase().includes(r.toLowerCase())||v.description.toLowerCase().includes(r.toLowerCase())||v.user_name.toLowerCase().includes(r.toLowerCase()),w=i==="all"||v.status===i;return b&&w}),y={total:h.length,open:h.filter(v=>v.status==="open").length,inProgress:h.filter(v=>v.status==="in_progress").length,launched:h.filter(v=>v.status==="launched").length,highVotes:h.filter(v=>v.vote_count>=10).length};return e.jsx(Vs,{title:"Admin - Wishlist",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx($,{variant:"ghost",size:"icon",onClick:()=>t("/admin"),children:e.jsx(qa,{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:y.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:y.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:y.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:y.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:y.highVotes})]})]}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-4",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(Kr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(pe,{placeholder:"Search ideas, users...",value:r,onChange:v=>a(v.target.value),className:"pl-10"})]}),e.jsxs(ms,{value:i,onValueChange:v=>l(v),children:[e.jsx(us,{className:"w-[180px]",children:e.jsx(fs,{placeholder:"Filter by status"})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"all",children:"All Statuses"}),pSt.map(v=>e.jsx(Ge,{value:v,children:fSt[v].label},v))]})]})]}),m?e.jsx("div",{className:"space-y-2",children:[1,2,3,4,5].map(v=>e.jsx(yn,{className:"h-16 w-full"},v))}):e.jsx("div",{className:"bg-card border rounded-lg overflow-hidden",children:e.jsxs(mi,{children:[e.jsx(fi,{children:e.jsxs(En,{children:[e.jsx(Dt,{className:"w-[60px]",children:"Votes"}),e.jsx(Dt,{children:"Title"}),e.jsx(Dt,{className:"hidden md:table-cell",children:"Submitted By"}),e.jsx(Dt,{className:"hidden sm:table-cell",children:"Comments"}),e.jsx(Dt,{children:"Status"}),e.jsx(Dt,{className:"w-[100px]",children:"Actions"})]})}),e.jsx(pi,{children:x.length===0?e.jsx(En,{children:e.jsx(wt,{colSpan:6,className:"text-center py-8 text-muted-foreground",children:"No items found"})}):x.map(v=>e.jsxs(En,{className:Pt(v.vote_count>=10&&"bg-primary/5"),children:[e.jsx(wt,{children:e.jsx(Be,{variant:v.vote_count>=10?"default":"secondary",children:v.vote_count})}),e.jsx(wt,{children:e.jsxs("div",{children:[e.jsx("p",{className:"font-medium line-clamp-1",children:v.title}),e.jsx("p",{className:"text-sm text-muted-foreground line-clamp-1",children:v.description})]})}),e.jsx(wt,{className:"hidden md:table-cell",children:e.jsxs("div",{children:[e.jsx("p",{className:"text-sm",children:v.user_name}),e.jsx("p",{className:"text-xs text-muted-foreground",children:v.user_email})]})}),e.jsx(wt,{className:"hidden sm:table-cell",children:v.comment_count}),e.jsx(wt,{children:e.jsxs(ms,{value:v.status,onValueChange:b=>f.mutate({itemId:v.id,status:b}),children:[e.jsx(us,{className:"w-[140px] h-8",children:e.jsx(fs,{})}),e.jsx(hs,{children:pSt.map(b=>e.jsx(Ge,{value:b,children:fSt[b].label},b))})]})}),e.jsx(wt,{children:e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx($,{variant:"ghost",size:"icon",onClick:()=>window.open(`/wishlist/${v.id}`,"_blank"),children:e.jsx(kr,{className:"h-4 w-4"})}),e.jsx($,{variant:"ghost",size:"icon",className:"text-destructive",onClick:()=>{u(v.id),c(!0)},children:e.jsx(Wn,{className:"h-4 w-4"})})]})})]},v.id))})]})}),e.jsx(zs,{open:o,onOpenChange:c,children:e.jsxs(Os,{children:[e.jsx(Us,{children:e.jsx(Bs,{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($,{variant:"outline",onClick:()=>c(!1),children:"Cancel"}),e.jsx($,{variant:"destructive",onClick:()=>d&&g.mutate(d),disabled:g.isPending,children:g.isPending?e.jsxs(e.Fragment,{children:[e.jsx(kt,{className:"h-4 w-4 mr-2 animate-spin"}),"Deleting..."]}):"Delete"})]})]})})]})})}function yFn(){const{user:s}=vs(),[t,n]=j.useState([]),[r,a]=j.useState(!0),[i,l]=j.useState(!1),[o,c]=j.useState(null),[d,u]=j.useState(!1),[h,m]=j.useState(null),[f,g]=j.useState(""),[x,y]=j.useState(""),[v,b]=j.useState(""),[w,S]=j.useState(""),[C,E]=j.useState(""),[I,P]=j.useState(!1),[R,D]=j.useState(""),[O,U]=j.useState("once"),[W,V]=j.useState([]),[G,Y]=j.useState([]),[X,ae]=j.useState(!1),[ie,ne]=j.useState(!1),[te,J]=j.useState([]),[ce,_e]=j.useState({total:0,dismissed:0});j.useEffect(()=>{he()},[]);const he=async()=>{const{data:at,error:Ke}=await q.from("levelup_briefs").select("*").order("created_at",{ascending:!1});Ke?(re.error("Failed to fetch briefs"),console.error(Ke)):n(at||[]),a(!1)},ue=()=>{g(""),y(""),b(""),S(""),E(""),P(!1),D(new Date().toISOString().slice(0,16)),U("once"),V([]),Y([]),c(null)},ve=()=>{ue(),l(!0)},Ee=async at=>{c(at),g(at.title),y(at.description||""),b(at.video_url||""),S(at.graphic_url||""),E(at.graphic_link_url||""),P(at.is_published),D(at.publish_date.slice(0,16)),U(at.show_frequency);const{data:Ke}=await q.from("levelup_brief_links").select("*").eq("brief_id",at.id).order("sort_order");V((Ke==null?void 0:Ke.map(xt=>({title:xt.title,url:xt.url})))||[]);const{data:nt}=await q.from("levelup_brief_polls").select("*").eq("brief_id",at.id).order("sort_order");if(nt){const xt=[];for(const rt of nt){const{data:Yt}=await q.from("levelup_brief_poll_options").select("*").eq("poll_id",rt.id).order("sort_order");xt.push({question:rt.question,poll_type:rt.poll_type,options:(Yt==null?void 0:Yt.map(qt=>qt.option_text))||[]})}Y(xt)}l(!0)},Se=async at=>{var nt;const Ke=(nt=at.target.files)==null?void 0:nt[0];if(Ke){ae(!0);try{const xt=await q.functions.invoke("bunny-upload",{body:{action:"create",title:Ke.name.replace(/\.[^/.]+$/,"")}});if(xt.error)throw xt.error;const{videoId:rt,libraryId:Yt}=xt.data,qt=await q.functions.invoke("bunny-upload",{body:{action:"upload-url",videoId:rt}});if(qt.error)throw qt.error;const{uploadUrl:ts,apiKey:ys}=qt.data,Bt=new XMLHttpRequest;await new Promise((rs,St)=>{Bt.upload.addEventListener("progress",Xs=>{if(Xs.lengthComputable){const vt=Math.round(Xs.loaded/Xs.total*100);console.log("Upload progress:",vt)}}),Bt.addEventListener("load",()=>{Bt.status>=200&&Bt.status<300?rs():St(new Error(`Upload failed with status ${Bt.status}`))}),Bt.addEventListener("error",()=>St(new Error("Upload failed"))),Bt.open("PUT",ts),Bt.setRequestHeader("AccessKey",ys),Bt.send(Ke)});const Ft=`https://player.mediadelivery.net/embed/${Yt}/${rt}`;b(Ft),re.success("Video uploaded successfully! It may take a few minutes to process.")}catch(xt){console.error("Upload error:",xt),re.error("Failed to upload video")}finally{ae(!1)}}},Le=async()=>{if(!f.trim()){re.error("Title is required");return}try{let at;if(o){const{error:Ke}=await q.from("levelup_briefs").update({title:f,description:x||null,video_url:v||null,graphic_url:w||null,graphic_link_url:C||null,is_published:I,publish_date:R,show_frequency:O}).eq("id",o.id);if(Ke)throw Ke;at=o.id,await q.from("levelup_brief_links").delete().eq("brief_id",at);const{data:nt}=await q.from("levelup_brief_polls").select("id").eq("brief_id",at);if(nt)for(const xt of nt)await q.from("levelup_brief_poll_options").delete().eq("poll_id",xt.id);await q.from("levelup_brief_polls").delete().eq("brief_id",at)}else{const{data:Ke,error:nt}=await q.from("levelup_briefs").insert({title:f,description:x||null,video_url:v||null,graphic_url:w||null,graphic_link_url:C||null,is_published:I,publish_date:R,show_frequency:O,created_by:s==null?void 0:s.id}).select().single();if(nt)throw nt;at=Ke.id}if(W.length>0){const Ke=W.map((nt,xt)=>({brief_id:at,title:nt.title,url:nt.url,sort_order:xt}));await q.from("levelup_brief_links").insert(Ke)}for(let Ke=0;Ke0){const Yt=nt.options.map((qt,ts)=>({poll_id:xt.id,option_text:qt,sort_order:ts}));await q.from("levelup_brief_poll_options").insert(Yt)}}re.success(o?"Brief updated":"Brief created"),l(!1),ue(),he()}catch(at){console.error("Error saving brief:",at),re.error("Failed to save brief")}},Fe=async at=>{if(await fo("Are you sure you want to delete this brief?"))try{const{error:Ke}=await q.from("levelup_briefs").delete().eq("id",at);if(Ke)throw Ke;re.success("Brief deleted"),he()}catch(Ke){console.error("Error deleting brief:",Ke),re.error("Failed to delete brief")}},ke=async at=>{m(at);const{count:Ke}=await q.from("levelup_brief_views").select("*",{count:"exact",head:!0}).eq("brief_id",at.id),{count:nt}=await q.from("levelup_brief_views").select("*",{count:"exact",head:!0}).eq("brief_id",at.id).not("dismissed_at","is",null);_e({total:Ke||0,dismissed:nt||0});const{data:xt}=await q.from("levelup_brief_polls").select("*").eq("brief_id",at.id).order("sort_order");if(xt){const rt=[];for(const Yt of xt){const{data:qt}=await q.from("levelup_brief_poll_options").select("*").eq("poll_id",Yt.id).order("sort_order"),{data:ts}=await q.from("levelup_brief_poll_responses").select("option_id, user_id").eq("poll_id",Yt.id),ys=[...new Set((ts==null?void 0:ts.map(Xs=>Xs.user_id))||[])];let Bt={};if(ys.length>0){const{data:Xs}=await q.from("profiles").select("id, name, email").in("id",ys);Xs&&Xs.forEach(vt=>{Bt[vt.id]=vt.name||vt.email||"Unknown"})}const Ft=(ts||[]).map(Xs=>({optionId:Xs.option_id,userName:Bt[Xs.user_id]||"Unknown",userId:Xs.user_id})),rs={};let St=0;qt&&qt.forEach(Xs=>{const vt=(ts==null?void 0:ts.filter(gs=>gs.option_id===Xs.id).length)||0;rs[Xs.id]=vt,St+=vt}),rt.push({...Yt,options:qt||[],results:rs,respondents:Ft,totalResponses:Yt.poll_type==="single"?new Set(ts==null?void 0:ts.map(Xs=>Xs.user_id)).size:St})}J(rt)}u(!0)},Ve=()=>{V([...W,{title:"",url:""}])},je=(at,Ke,nt)=>{const xt=[...W];xt[at][Ke]=nt,V(xt)},Ae=at=>{V(W.filter((Ke,nt)=>nt!==at))},Ce=()=>{Y([...G,{question:"",poll_type:"single",options:["",""]}])},qe=(at,Ke)=>{const nt=[...G];nt[at].question=Ke,Y(nt)},ze=(at,Ke)=>{const nt=[...G];nt[at].poll_type=Ke,Y(nt)},$e=at=>{const Ke=[...G];Ke[at].options.push(""),Y(Ke)},ct=(at,Ke,nt)=>{const xt=[...G];xt[at].options[Ke]=nt,Y(xt)},Xe=(at,Ke)=>{const nt=[...G];nt[at].options=nt[at].options.filter((xt,rt)=>rt!==Ke),Y(nt)},it=at=>{Y(G.filter((Ke,nt)=>nt!==at))};return e.jsxs(Vs,{title:"The LevelUp Brief",children:[e.jsxs("div",{className:"space-y-6",children:[e.jsx(Fm,{title:"The LevelUp Brief",description:"Create engaging popup briefs for your agents",children:e.jsxs($,{onClick:ve,children:[e.jsx(dn,{className:"h-4 w-4 mr-2"}),"Create Brief"]})}),e.jsx(Ne,{children:e.jsx(Ie,{className:"p-0",children:e.jsxs(mi,{children:[e.jsx(fi,{children:e.jsxs(En,{children:[e.jsx(Dt,{children:"Title"}),e.jsx(Dt,{children:"Status"}),e.jsx(Dt,{children:"Frequency"}),e.jsx(Dt,{children:"Publish Date"}),e.jsx(Dt,{className:"text-right",children:"Actions"})]})}),e.jsx(pi,{children:r?e.jsx(En,{children:e.jsx(wt,{colSpan:5,className:"text-center py-8",children:"Loading..."})}):t.length===0?e.jsx(En,{children:e.jsx(wt,{colSpan:5,className:"text-center py-8 text-muted-foreground",children:"No briefs created yet"})}):t.map(at=>e.jsxs(En,{children:[e.jsx(wt,{className:"font-medium",children:at.title}),e.jsx(wt,{children:e.jsx(Be,{variant:at.is_published?"default":"secondary",children:at.is_published?"Published":"Draft"})}),e.jsx(wt,{className:"capitalize",children:at.show_frequency.replace("_"," ")}),e.jsx(wt,{children:en(new Date(at.publish_date),"MMM d, yyyy h:mm a")}),e.jsx(wt,{className:"text-right",children:e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx($,{variant:"ghost",size:"icon",onClick:()=>ke(at),children:e.jsx(Wl,{className:"h-4 w-4"})}),e.jsx($,{variant:"ghost",size:"icon",onClick:()=>Ee(at),children:e.jsx(_p,{className:"h-4 w-4"})}),e.jsx($,{variant:"ghost",size:"icon",onClick:()=>Fe(at.id),children:e.jsx(Wn,{className:"h-4 w-4 text-destructive"})})]})})]},at.id))})]})})})]}),e.jsx(zs,{open:i,onOpenChange:l,children:e.jsxs(Os,{className:"max-w-3xl max-h-[90vh] overflow-y-auto",children:[e.jsx(Us,{children:e.jsx(Bs,{children:o?"Edit Brief":"Create New Brief"})}),e.jsxs(ha,{defaultValue:"content",className:"w-full",children:[e.jsxs(ma,{className:"grid w-full grid-cols-4",children:[e.jsx(Zt,{value:"content",children:"Content"}),e.jsx(Zt,{value:"media",children:"Media"}),e.jsx(Zt,{value:"links",children:"Links"}),e.jsx(Zt,{value:"polls",children:"Polls"})]}),e.jsxs(Xt,{value:"content",className:"space-y-4 mt-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Title *"}),e.jsx(pe,{value:f,onChange:at=>g(at.target.value),placeholder:"What's happening at LevelUp..."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Description"}),e.jsx(Ek,{content:x,onChange:at=>y(at),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(ee,{children:"Publish Date"}),e.jsx(pe,{type:"datetime-local",value:R,onChange:at=>D(at.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Show Frequency"}),e.jsxs(ms,{value:O,onValueChange:U,children:[e.jsx(us,{children:e.jsx(fs,{})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"once",children:"Once (until dismissed)"}),e.jsx(Ge,{value:"every_login",children:"Every login"}),e.jsx(Ge,{value:"daily",children:"Daily"})]})]})]})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Sn,{checked:I,onCheckedChange:P}),e.jsx(ee,{children:"Publish immediately"})]})]}),e.jsxs(Xt,{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(ee,{children:"Upload Video to Bunny.net"}),e.jsx("div",{className:"flex gap-2",children:e.jsx(pe,{type:"file",accept:"video/*",onChange:Se,disabled:X})}),X&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"Uploading..."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Or paste embed URL"}),e.jsx(pe,{value:v,onChange:at=>b(at.target.value),placeholder:"https://iframe.mediadelivery.net/embed/..."})]}),v&&e.jsx("div",{className:"aspect-video rounded-lg overflow-hidden bg-muted",children:e.jsx("iframe",{src:v,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(ee,{children:"Upload Image"}),e.jsx("div",{className:"flex gap-2",children:e.jsx(pe,{type:"file",accept:"image/*",onChange:async at=>{var nt;const Ke=(nt=at.target.files)==null?void 0:nt[0];if(Ke){ne(!0);try{const xt=Ke.name.split(".").pop(),rt=`brief-graphics/${Date.now()}.${xt}`,{error:Yt}=await q.storage.from("banner-images").upload(rt,Ke,{upsert:!0});if(Yt)throw Yt;const{data:qt}=q.storage.from("banner-images").getPublicUrl(rt);S(qt.publicUrl),re.success("Image uploaded!")}catch(xt){console.error(xt),re.error("Failed to upload image")}finally{ne(!1)}}},disabled:ie})}),ie&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"Uploading..."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Or paste Image URL"}),e.jsx(pe,{value:w,onChange:at=>S(at.target.value),placeholder:"https://example.com/image.png"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Click-through Link (optional)"}),e.jsx(pe,{value:C,onChange:at=>E(at.target.value),placeholder:"https://example.com/landing-page"})]}),w&&e.jsx("div",{className:"rounded-lg overflow-hidden bg-muted border",children:e.jsx("img",{src:w,alt:"Brief graphic preview",className:"w-full object-contain max-h-64"})})]})]}),e.jsxs(Xt,{value:"links",className:"space-y-4 mt-4",children:[e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx(ee,{children:"Quick Links"}),e.jsxs($,{variant:"outline",size:"sm",onClick:Ve,children:[e.jsx(dn,{className:"h-4 w-4 mr-1"}),"Add Link"]})]}),W.map((at,Ke)=>e.jsxs("div",{className:"flex gap-2 items-start",children:[e.jsx(pe,{value:at.title,onChange:nt=>je(Ke,"title",nt.target.value),placeholder:"Link title",className:"flex-1"}),e.jsx(pe,{value:at.url,onChange:nt=>je(Ke,"url",nt.target.value),placeholder:"https://...",className:"flex-[2]"}),e.jsx($,{variant:"ghost",size:"icon",onClick:()=>Ae(Ke),children:e.jsx(Wn,{className:"h-4 w-4 text-destructive"})})]},Ke)),W.length===0&&e.jsx("p",{className:"text-muted-foreground text-center py-4",children:"No links added yet"})]}),e.jsxs(Xt,{value:"polls",className:"space-y-4 mt-4",children:[e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx(ee,{children:"Polls"}),e.jsxs($,{variant:"outline",size:"sm",onClick:Ce,children:[e.jsx(dn,{className:"h-4 w-4 mr-1"}),"Add Poll"]})]}),G.map((at,Ke)=>e.jsx(Ne,{className:"p-4",children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx(pe,{value:at.question,onChange:nt=>qe(Ke,nt.target.value),placeholder:"Poll question...",className:"flex-1 mr-2"}),e.jsxs(ms,{value:at.poll_type,onValueChange:nt=>ze(Ke,nt),children:[e.jsx(us,{className:"w-32",children:e.jsx(fs,{})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"single",children:"Single"}),e.jsx(Ge,{value:"multi",children:"Multi-select"})]})]}),e.jsx($,{variant:"ghost",size:"icon",onClick:()=>it(Ke),children:e.jsx(Wn,{className:"h-4 w-4 text-destructive"})})]}),e.jsxs("div",{className:"space-y-2 pl-4",children:[at.options.map((nt,xt)=>e.jsxs("div",{className:"flex gap-2",children:[e.jsx(pe,{value:nt,onChange:rt=>ct(Ke,xt,rt.target.value),placeholder:`Option ${xt+1}`}),at.options.length>2&&e.jsx($,{variant:"ghost",size:"icon",onClick:()=>Xe(Ke,xt),children:e.jsx(Wn,{className:"h-4 w-4 text-muted-foreground"})})]},xt)),e.jsxs($,{variant:"ghost",size:"sm",onClick:()=>$e(Ke),children:[e.jsx(dn,{className:"h-4 w-4 mr-1"}),"Add Option"]})]})]})},Ke)),G.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($,{variant:"outline",onClick:()=>l(!1),children:"Cancel"}),e.jsx($,{onClick:Le,children:o?"Update Brief":"Create Brief"})]})]})}),e.jsx(zs,{open:d,onOpenChange:u,children:e.jsxs(Os,{className:"max-w-2xl",children:[e.jsx(Us,{children:e.jsxs(Bs,{children:["Results: ",h==null?void 0:h.title]})}),e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs(Ne,{children:[e.jsx(Ct,{className:"pb-2",children:e.jsx(At,{className:"text-sm font-medium text-muted-foreground",children:"Total Views"})}),e.jsx(Ie,{children:e.jsx("p",{className:"text-2xl font-bold",children:ce.total})})]}),e.jsxs(Ne,{children:[e.jsx(Ct,{className:"pb-2",children:e.jsx(At,{className:"text-sm font-medium text-muted-foreground",children:"Dismissed"})}),e.jsx(Ie,{children:e.jsx("p",{className:"text-2xl font-bold",children:ce.dismissed})})]})]}),te.length>0?e.jsxs("div",{className:"space-y-4",children:[e.jsx("h3",{className:"font-semibold",children:"Poll Results"}),te.map(at=>e.jsxs(Ne,{className:"p-4",children:[e.jsx("h4",{className:"font-medium mb-3",children:at.question}),e.jsx("div",{className:"space-y-2",children:at.options.map(Ke=>{const nt=at.results[Ke.id]||0,xt=at.totalResponses>0?Math.round(nt/at.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:Ke.option_text}),e.jsxs("span",{className:"text-muted-foreground",children:[nt," (",xt,"%)"]})]}),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:`${xt}%`}})}),nt>0&&e.jsx("div",{className:"flex flex-wrap gap-1 pt-1",children:(at.respondents||[]).filter(rt=>rt.optionId===Ke.id).map((rt,Yt)=>e.jsx(Be,{variant:"secondary",className:"text-xs font-normal",children:rt.userName},Yt))})]},Ke.id)})})]},at.id))]}):e.jsx("p",{className:"text-muted-foreground text-center py-4",children:"No polls in this brief"})]})]})})]})}const vFn=()=>{const{user:s}=vs(),{toast:t}=Bi(),n=Vt(),[r,a]=j.useState(!1),[i,l]=j.useState(null),[o,c]=j.useState({name:"",description:"",signup_link_url:"",publish_date:new Date().toISOString().split("T")[0],is_published:!1}),[d,u]=j.useState(null),[h,m]=j.useState(""),{data:f=[],isLoading:g}=tt({queryKey:["additional-services-admin"],queryFn:async()=>{const{data:C,error:E}=await q.from("additional_services").select("*").order("publish_date",{ascending:!1});if(E)throw E;return C}}),x=ft({mutationFn:async C=>{let E=C.existingImageUrl;if(C.image){const P=C.image.name.split(".").pop(),R=`${Date.now()}-${Math.random().toString(36).substring(7)}.${P}`,{error:D}=await q.storage.from("service-images").upload(R,C.image);if(D)throw D;const{data:O}=q.storage.from("service-images").getPublicUrl(R);E=O.publicUrl}const I={name:C.item.name,description:C.item.description||null,preview_image_url:E,signup_link_url:C.item.signup_link_url,publish_date:C.item.publish_date?new Date(C.item.publish_date).toISOString():new Date().toISOString(),is_published:C.item.is_published,created_by:s==null?void 0:s.id};if(C.itemId){const{error:P}=await q.from("additional_services").update(I).eq("id",C.itemId);if(P)throw P}else{const{error:P}=await q.from("additional_services").insert(I);if(P)throw P}},onSuccess:()=>{n.invalidateQueries({queryKey:["additional-services-admin"]}),n.invalidateQueries({queryKey:["additional-services"]}),t({title:i?"Service updated":"Service created"}),a(!1),v()},onError:C=>{t({title:"Error saving service",description:C.message,variant:"destructive"})}}),y=ft({mutationFn:async C=>{const{error:E}=await q.from("additional_services").delete().eq("id",C);if(E)throw E},onSuccess:()=>{n.invalidateQueries({queryKey:["additional-services-admin"]}),n.invalidateQueries({queryKey:["additional-services"]}),t({title:"Service deleted"})},onError:C=>{t({title:"Error deleting service",description:C.message,variant:"destructive"})}}),v=()=>{c({name:"",description:"",signup_link_url:"",publish_date:new Date().toISOString().split("T")[0],is_published:!1}),u(null),m(""),l(null)},b=C=>{l(C),c({name:C.name,description:C.description||"",signup_link_url:C.signup_link_url,publish_date:C.publish_date?new Date(C.publish_date).toISOString().split("T")[0]:new Date().toISOString().split("T")[0],is_published:C.is_published}),m(C.preview_image_url||""),a(!0)},w=C=>{var I;const E=(I=C.target.files)==null?void 0:I[0];E&&(u(E),m(URL.createObjectURL(E)))},S=C=>{if(C.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}x.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(Vs,{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(Ne,{children:[e.jsx(Ct,{className:"pb-2",children:e.jsx(At,{className:"text-sm font-medium text-muted-foreground",children:"Total Services"})}),e.jsx(Ie,{children:e.jsx("div",{className:"text-2xl font-bold",children:f.length})})]}),e.jsxs(Ne,{children:[e.jsx(Ct,{className:"pb-2",children:e.jsx(At,{className:"text-sm font-medium text-muted-foreground",children:"Published"})}),e.jsx(Ie,{children:e.jsx("div",{className:"text-2xl font-bold",children:f.filter(C=>C.is_published).length})})]})]}),e.jsxs(zs,{open:r,onOpenChange:C=>{a(C),C||v()},children:[e.jsx(jl,{asChild:!0,children:e.jsxs($,{className:"gap-2",children:[e.jsx(dn,{className:"h-4 w-4"}),"Add Service"]})}),e.jsxs(Os,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(Us,{children:e.jsx(Bs,{children:i?"Edit Service":"Add New Service"})}),e.jsxs("form",{onSubmit:S,className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"name",children:"Name *"}),e.jsx(pe,{id:"name",value:o.name,onChange:C=>c({...o,name:C.target.value}),placeholder:"Enter service name"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Description"}),e.jsx(Ek,{content:o.description,onChange:C=>c({...o,description:C}),placeholder:"Enter description",minHeight:"120px"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"signup_link_url",children:"Signup Link URL *"}),e.jsx(pe,{id:"signup_link_url",type:"url",value:o.signup_link_url,onChange:C=>c({...o,signup_link_url:C.target.value}),placeholder:"https://example.com/signup"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"publish_date",children:"Publish Date"}),e.jsx(pe,{id:"publish_date",type:"date",value:o.publish_date,onChange:C=>c({...o,publish_date:C.target.value})})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Sn,{id:"is_published",checked:o.is_published,onCheckedChange:C=>c({...o,is_published:C})}),e.jsx(ee,{htmlFor:"is_published",children:"Published"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Preview Image"}),h?e.jsxs("div",{className:"relative",children:[e.jsx("img",{src:h,alt:"Preview",className:"w-full max-h-48 object-contain rounded-lg border"}),e.jsx($,{type:"button",variant:"destructive",size:"icon",className:"absolute top-2 right-2 h-6 w-6",onClick:()=>{u(null),m("")},children:e.jsx(gr,{className:"h-3 w-3"})})]}):e.jsxs("div",{className:"border-2 border-dashed rounded-lg p-4 text-center",children:[e.jsx(Mc,{className:"h-8 w-8 mx-auto text-muted-foreground mb-2"}),e.jsx(pe,{type:"file",accept:"image/*",onChange:w,className:"cursor-pointer"})]})]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-4",children:[e.jsx($,{type:"button",variant:"outline",onClick:()=>a(!1),children:"Cancel"}),e.jsx($,{type:"submit",disabled:x.isPending,children:x.isPending?"Saving...":i?"Update":"Create"})]})]})]})]})]}),e.jsx(Ne,{children:e.jsx(Ie,{className:"p-0",children:g?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"})}):f.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(mi,{children:[e.jsx(fi,{children:e.jsxs(En,{children:[e.jsx(Dt,{className:"w-16",children:"Preview"}),e.jsx(Dt,{children:"Name"}),e.jsx(Dt,{children:"Signup Link"}),e.jsx(Dt,{children:"Publish Date"}),e.jsx(Dt,{children:"Status"}),e.jsx(Dt,{className:"text-right",children:"Actions"})]})}),e.jsx(pi,{children:f.map(C=>e.jsxs(En,{children:[e.jsx(wt,{children:C.preview_image_url?e.jsx("img",{src:C.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(Mc,{className:"h-5 w-5 text-muted-foreground"})})}),e.jsx(wt,{className:"font-medium",children:C.name}),e.jsx(wt,{children:e.jsxs("a",{href:C.signup_link_url,target:"_blank",rel:"noopener noreferrer",className:"text-primary hover:underline flex items-center gap-1",children:[e.jsx(kr,{className:"h-3 w-3"}),"Link"]})}),e.jsx(wt,{children:new Date(C.publish_date).toLocaleDateString()}),e.jsx(wt,{children:e.jsx(Be,{variant:C.is_published?"default":"secondary",children:C.is_published?"Published":"Draft"})}),e.jsx(wt,{className:"text-right",children:e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx($,{variant:"ghost",size:"icon",onClick:()=>b(C),children:e.jsx(gi,{className:"h-4 w-4"})}),e.jsx($,{variant:"ghost",size:"icon",onClick:async()=>{await fo("Are you sure you want to delete this service?")&&y.mutate(C.id)},children:e.jsx(Wn,{className:"h-4 w-4 text-destructive"})})]})})]},C.id))})]})})})]})})};function bFn(){const{toast:s}=Bi(),[t,n]=j.useState([]),[r,a]=j.useState(!0),[i,l]=j.useState(!1),[o,c]=j.useState(!1),[d,u]=j.useState({name:"",promotionCode:"",discountType:"percent",percentOff:"",amountOff:"",duration:"once",durationInMonths:""});j.useEffect(()=>{h()},[]);const h=async()=>{try{const{data:y,error:v}=await q.functions.invoke("stripe-manage-coupons",{body:{action:"list"}});if(v)throw v;n(y.coupons||[])}catch(y){console.error("Error fetching coupons:",y),s({title:"Error",description:"Failed to load coupons",variant:"destructive"})}finally{a(!1)}},m=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 y={action:"create",name:d.name,duration:d.duration,promotion_code:d.promotionCode.trim()||void 0};d.discountType==="percent"?y.percent_off=parseFloat(d.percentOff):(y.amount_off=Math.round(parseFloat(d.amountOff)*100),y.currency="usd"),d.duration==="repeating"&&(y.duration_in_months=parseInt(d.durationInMonths));const{data:v,error:b}=await q.functions.invoke("stripe-manage-coupons",{body:y});if(b)throw b;s({title:"Success",description:"Coupon created successfully"}),c(!1),u({name:"",promotionCode:"",discountType:"percent",percentOff:"",amountOff:"",duration:"once",durationInMonths:""}),h()}catch(y){console.error("Error creating coupon:",y),s({title:"Error",description:y.message||"Failed to create coupon",variant:"destructive"})}finally{l(!1)}},f=async y=>{if(await fo("Are you sure you want to delete this coupon?"))try{const{error:v}=await q.functions.invoke("stripe-manage-coupons",{body:{action:"delete",couponId:y}});if(v)throw v;s({title:"Success",description:"Coupon deleted successfully"}),h()}catch(v){console.error("Error deleting coupon:",v),s({title:"Error",description:v.message||"Failed to delete coupon",variant:"destructive"})}},g=y=>y.percent_off?`${y.percent_off}% off`:y.amount_off?`$${(y.amount_off/100).toFixed(2)} off`:"N/A",x=y=>{switch(y.duration){case"once":return"Once";case"forever":return"Forever";case"repeating":return`${y.duration_in_months} months`;default:return y.duration}};return e.jsx(Vs,{title:"Subscription Discounts",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(Fm,{title:"Subscription Discounts",description:"Create and manage discount coupons for subscriptions",children:e.jsxs(zs,{open:o,onOpenChange:c,children:[e.jsx(jl,{asChild:!0,children:e.jsxs($,{children:[e.jsx(dn,{className:"mr-2 h-4 w-4"}),"Create Coupon"]})}),e.jsxs(Os,{children:[e.jsxs(Us,{children:[e.jsx(Bs,{children:"Create New Coupon"}),e.jsx(Ir,{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(ee,{children:"Promotion Code (what users will type)"}),e.jsx(pe,{placeholder:"e.g., BROKERAGE50",value:d.promotionCode,onChange:y=>u({...d,promotionCode:y.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(ee,{children:"Coupon Name (internal label)"}),e.jsx(pe,{placeholder:"e.g., 50% Off Brokerage Launch",value:d.name,onChange:y=>u({...d,name:y.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Discount Type"}),e.jsxs(ms,{value:d.discountType,onValueChange:y=>{const v=y==="amount"&&d.duration==="forever"?"once":d.duration;u({...d,discountType:y,duration:v})},children:[e.jsx(us,{children:e.jsx(fs,{})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"percent",children:e.jsxs("span",{className:"flex items-center",children:[e.jsx(Rw,{className:"mr-2 h-4 w-4"}),"Percentage Off"]})}),e.jsx(Ge,{value:"amount",children:e.jsxs("span",{className:"flex items-center",children:[e.jsx(ru,{className:"mr-2 h-4 w-4"}),"Fixed Amount Off"]})})]})]})]}),d.discountType==="percent"?e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Percent Off"}),e.jsxs("div",{className:"relative",children:[e.jsx(pe,{type:"number",min:"1",max:"100",placeholder:"20",value:d.percentOff,onChange:y=>u({...d,percentOff:y.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(ee,{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(pe,{type:"number",min:"1",placeholder:"10.00",className:"pl-7",value:d.amountOff,onChange:y=>u({...d,amountOff:y.target.value})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Duration"}),e.jsxs(ms,{value:d.duration,onValueChange:y=>u({...d,duration:y}),children:[e.jsx(us,{children:e.jsx(fs,{})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"once",children:"Once (first payment only)"}),e.jsx(Ge,{value:"repeating",children:"Multiple months"}),e.jsxs(Ge,{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(ee,{children:"Number of Months"}),e.jsx(pe,{type:"number",min:"1",placeholder:"3",value:d.durationInMonths,onChange:y=>u({...d,durationInMonths:y.target.value})})]}),e.jsx($,{onClick:m,disabled:i,className:"w-full",children:i?e.jsxs(e.Fragment,{children:[e.jsx(kt,{className:"mr-2 h-4 w-4 animate-spin"}),"Creating..."]}):"Create Coupon"})]})]})]})}),e.jsxs(Ne,{children:[e.jsxs(Ct,{children:[e.jsx(At,{children:"Active Coupons"}),e.jsx(Gn,{children:"Share coupon codes with users to give them discounts on subscriptions"})]}),e.jsx(Ie,{children:r?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(kt,{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(mi,{children:[e.jsx(fi,{children:e.jsxs(En,{children:[e.jsx(Dt,{children:"Promo Code"}),e.jsx(Dt,{children:"Name"}),e.jsx(Dt,{children:"Discount"}),e.jsx(Dt,{children:"Duration"}),e.jsx(Dt,{children:"Redemptions"}),e.jsx(Dt,{children:"Status"}),e.jsx(Dt,{className:"text-right",children:"Actions"})]})}),e.jsx(pi,{children:t.map(y=>{var v;return e.jsxs(En,{children:[e.jsx(wt,{className:"font-mono font-medium",children:((v=y.promotion_codes)==null?void 0:v.length)>0?y.promotion_codes.join(", "):e.jsx("span",{className:"text-muted-foreground text-xs",children:"No promo code"})}),e.jsx(wt,{children:y.name||"-"}),e.jsx(wt,{children:g(y)}),e.jsx(wt,{children:x(y)}),e.jsx(wt,{children:y.times_redeemed}),e.jsx(wt,{children:e.jsx(Be,{variant:y.valid?"default":"secondary",children:y.valid?"Active":"Inactive"})}),e.jsx(wt,{className:"text-right",children:e.jsx($,{variant:"ghost",size:"sm",onClick:()=>f(y.id),children:e.jsx(Wn,{className:"h-4 w-4 text-destructive"})})})]},y.id)})})]})})]}),e.jsxs(Ne,{children:[e.jsx(Ct,{children:e.jsx(At,{children:"How to Use Coupons"})}),e.jsxs(Ie,{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 O9e={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 _Fn(){const[s,t]=j.useState(""),[n,r]=j.useState("all"),[a,i]=j.useState("all"),[l,o]=j.useState(null),{data:c,isLoading:d,refetch:u}=tt({queryKey:["admin-subscriptions"],queryFn:async()=>{const{data:v,error:b}=await q.from("profiles").select(` *, brokerages:brokerage_id (id, name) `).order("created_at",{ascending:!1});if(b)throw b;return v}}),{data:h}=tt({queryKey:["admin-brokerages-subscriptions"],queryFn:async()=>{const{data:v,error:b}=await q.from("brokerages").select("*").order("name");if(b)throw b;return await Promise.all((v||[]).map(async S=>{const{data:C}=await q.from("profiles").select("id, name, email, subscription_status, subscription_product_id").eq("brokerage_id",S.id),{data:E}=await q.from("user_roles").select("user_id").eq("role","brokerage_manager"),I=(E==null?void 0:E.map(D=>D.user_id))||[],P=(C==null?void 0:C.filter(D=>I.includes(D.id)))||[],R=(C==null?void 0:C.length)||0;return{...S,managers:P,agentCount:R}}))}}),{data:m}=tt({queryKey:["admin-website-subscriptions"],queryFn:async()=>{const{data:v,error:b}=await q.from("local_move_subscriptions").select("*").order("created_at",{ascending:!1});if(b)throw b;return v}}),f=v=>{if(v.is_grandfathered)return{status:"Grandfathered",badge:"Legacy",variant:"secondary"};if(v.brokerage_id&&!v.subscription_product_id)return{status:"Brokerage",badge:"Team Member",variant:"outline"};if(v.is_trial&&v.trial_expires_at)return new Date(v.trial_expires_at)>new Date?{status:"Trial",badge:"Active Trial",variant:"default"}:{status:"Trial Expired",badge:"Expired",variant:"destructive"};if(v.subscription_status==="active"||v.subscription_status==="trialing"){const b=O9e[v.subscription_product_id];return{status:(b==null?void 0:b.name)||"Active",badge:v.subscription_status==="trialing"?"Trial":"Active",variant:"default"}}return v.subscription_status==="canceled"||v.subscription_status==="past_due"?{status:"Canceled",badge:"Inactive",variant:"destructive"}:{status:"None",badge:"No Subscription",variant:"outline"}},g=c==null?void 0:c.filter(v=>{var w,S;if(!(((w=v.name)==null?void 0:w.toLowerCase().includes(s.toLowerCase()))||((S=v.email)==null?void 0:S.toLowerCase().includes(s.toLowerCase()))))return!1;if(a!=="all"){const C=v.subscription_source||"platform";if(a==="platform"&&C==="local_move_website"||a==="local_move_website"&&C!=="local_move_website")return!1}switch(f(v),n){case"active":return v.subscription_status==="active";case"trialing":return v.subscription_status==="trialing"||v.is_trial&&new Date(v.trial_expires_at)>new Date;case"grandfathered":return v.is_grandfathered;case"brokerage":return v.brokerage_id&&!v.subscription_product_id&&!v.is_grandfathered;case"expired":return v.subscription_status==="canceled"||v.subscription_status==="past_due"||v.is_trial&&new Date(v.trial_expires_at)<=new Date;case"none":return!v.subscription_status||v.subscription_status==="none";default:return!0}}),x={totalUsers:(c==null?void 0:c.length)||0,activeSubscriptions:(c==null?void 0:c.filter(v=>v.subscription_status==="active").length)||0,trials:(c==null?void 0:c.filter(v=>v.subscription_status==="trialing"||v.is_trial&&new Date(v.trial_expires_at)>new Date).length)||0,grandfathered:(c==null?void 0:c.filter(v=>v.is_grandfathered).length)||0,brokerageMembers:(c==null?void 0:c.filter(v=>v.brokerage_id&&!v.subscription_product_id&&!v.is_grandfathered).length)||0,individualSubscribers:(c==null?void 0:c.filter(v=>v.subscription_status==="active"&&v.subscription_product_id==="prod_Tc07cYplXUGNkm").length)||0,brokerageSubscribers:(c==null?void 0:c.filter(v=>v.subscription_status==="active"&&(v.subscription_product_id==="prod_Tc08MupgoVySDG"||v.subscription_product_id==="prod_Tc09N1tJ4RrAFn")).length)||0},y=v=>{window.open(`https://dashboard.stripe.com/customers/${v}`,"_blank")};return e.jsx(Vs,{title:"Subscription Management",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(Fm,{title:"Subscription Management",description:"Track and manage all subscriptions",children:e.jsxs($,{onClick:()=>u(),variant:"outline",size:"sm",children:[e.jsx(ro,{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(Ne,{children:e.jsxs(Ie,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Zn,{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:x.totalUsers})]})}),e.jsx(Ne,{className:"border-green-500/50",children:e.jsxs(Ie,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Cv,{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:x.activeSubscriptions})]})}),e.jsx(Ne,{className:"border-blue-500/50",children:e.jsxs(Ie,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(da,{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:x.trials})]})}),e.jsx(Ne,{className:"border-purple-500/50",children:e.jsxs(Ie,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Bg,{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:x.grandfathered})]})}),e.jsx(Ne,{className:"border-orange-500/50",children:e.jsxs(Ie,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ji,{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:x.brokerageMembers})]})}),e.jsx(Ne,{children:e.jsxs(Ie,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(y2,{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:x.individualSubscribers})]})}),e.jsx(Ne,{children:e.jsxs(Ie,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ji,{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:x.brokerageSubscribers})]})})]}),e.jsxs(ha,{defaultValue:"users",className:"space-y-4",children:[e.jsxs(ma,{children:[e.jsx(Zt,{value:"users",children:"All Users"}),e.jsx(Zt,{value:"brokerages",children:"Brokerages"}),e.jsxs(Zt,{value:"websites",className:"gap-2",children:[e.jsx(dl,{className:"h-4 w-4"}),"Website Subscriptions",m&&m.length>0&&e.jsx(Be,{variant:"secondary",className:"ml-1",children:m.length})]})]}),e.jsxs(Xt,{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(Kr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(pe,{placeholder:"Search by name or email...",value:s,onChange:v=>t(v.target.value),className:"pl-9"})]}),e.jsxs(ms,{value:a,onValueChange:v=>i(v),children:[e.jsx(us,{className:"w-[200px]",children:e.jsx(fs,{placeholder:"Source"})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"all",children:"All Sources"}),e.jsx(Ge,{value:"platform",children:"Platform"}),e.jsx(Ge,{value:"local_move_website",children:"Local Move Website"})]})]}),e.jsxs(ms,{value:n,onValueChange:v=>r(v),children:[e.jsx(us,{className:"w-[200px]",children:e.jsx(fs,{placeholder:"Filter by status"})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"all",children:"All Statuses"}),e.jsx(Ge,{value:"active",children:"Active Subscriptions"}),e.jsx(Ge,{value:"trialing",children:"Trials"}),e.jsx(Ge,{value:"grandfathered",children:"Grandfathered"}),e.jsx(Ge,{value:"brokerage",children:"Brokerage Members"}),e.jsx(Ge,{value:"expired",children:"Expired/Canceled"}),e.jsx(Ge,{value:"none",children:"No Subscription"})]})]})]}),e.jsx(Ne,{children:e.jsx(Ie,{className:"p-0",children:e.jsxs(mi,{children:[e.jsx(fi,{children:e.jsxs(En,{children:[e.jsx(Dt,{children:"User"}),e.jsx(Dt,{children:"Status"}),e.jsx(Dt,{children:"Plan"}),e.jsx(Dt,{children:"Brokerage"}),e.jsx(Dt,{children:"End Date"}),e.jsx(Dt,{className:"text-right",children:"Actions"})]})}),e.jsx(pi,{children:d?e.jsx(En,{children:e.jsx(wt,{colSpan:6,className:"text-center py-8",children:"Loading subscriptions..."})}):(g==null?void 0:g.length)===0?e.jsx(En,{children:e.jsx(wt,{colSpan:6,className:"text-center py-8 text-muted-foreground",children:"No users found"})}):g==null?void 0:g.map(v=>{var S,C;const b=f(v),w=O9e[v.subscription_product_id];return e.jsxs(En,{children:[e.jsx(wt,{children:e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:v.name}),e.jsx("p",{className:"text-sm text-muted-foreground",children:v.email})]})}),e.jsx(wt,{children:e.jsx(Be,{variant:b.variant,children:b.badge})}),e.jsx(wt,{children:e.jsx("span",{className:"text-sm",children:v.is_grandfathered?"Legacy Access":v.brokerage_id&&!v.subscription_product_id?"Brokerage Subscription":(w==null?void 0:w.name)||b.status})}),e.jsx(wt,{children:(S=v.brokerages)!=null&&S.name?e.jsx("span",{className:"text-sm",children:v.brokerages.name}):e.jsx("span",{className:"text-sm text-muted-foreground",children:"—"})}),e.jsx(wt,{children:v.subscription_end_date?e.jsx("span",{className:"text-sm",children:en(new Date(v.subscription_end_date),"MMM d, yyyy")}):v.trial_expires_at?e.jsxs("span",{className:"text-sm text-blue-600",children:["Trial: ",en(new Date(v.trial_expires_at),"MMM d, yyyy")]}):e.jsx("span",{className:"text-sm text-muted-foreground",children:"—"})}),e.jsx(wt,{className:"text-right",children:e.jsxs("div",{className:"flex items-center justify-end gap-2",children:[v.stripe_customer_id&&e.jsx($,{variant:"ghost",size:"sm",onClick:()=>y(v.stripe_customer_id),children:e.jsx(kr,{className:"h-4 w-4"})}),e.jsxs(zs,{children:[e.jsx(jl,{asChild:!0,children:e.jsx($,{variant:"outline",size:"sm",onClick:()=>o(v),children:"Details"})}),e.jsxs(Os,{children:[e.jsxs(Us,{children:[e.jsx(Bs,{children:"Subscription Details"}),e.jsxs(Ir,{children:[v.name," (",v.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(Be,{variant:b.variant,className:"mt-1",children:b.badge})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Plan"}),e.jsx("p",{className:"font-medium",children:v.is_grandfathered?"Grandfathered (Legacy)":v.brokerage_id&&!v.subscription_product_id?"Brokerage Subscription":(w==null?void 0:w.name)||"None"})]}),v.brokerage_id&&e.jsxs("div",{children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Brokerage"}),e.jsx("p",{className:"font-medium",children:((C=v.brokerages)==null?void 0:C.name)||"Unknown"})]}),v.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:en(new Date(v.subscription_end_date),"MMMM d, yyyy")})]}),v.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:en(new Date(v.trial_expires_at),"MMMM d, yyyy")})]}),v.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:v.stripe_customer_id})]})]}),v.stripe_customer_id&&e.jsxs($,{className:"w-full",onClick:()=>y(v.stripe_customer_id),children:[e.jsx(kr,{className:"h-4 w-4 mr-2"}),"View in Stripe Dashboard"]})]})]})]})]})})]},v.id)})})]})})})]}),e.jsx(Xt,{value:"brokerages",className:"space-y-4",children:e.jsx("div",{className:"grid gap-4",children:h==null?void 0:h.map(v=>{var w,S;const b=(w=v.managers)==null?void 0:w.some(C=>C.subscription_status==="active"&&(C.subscription_product_id==="prod_Tc08MupgoVySDG"||C.subscription_product_id==="prod_Tc09N1tJ4RrAFn"));return e.jsxs(Ne,{children:[e.jsx(Ct,{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(ji,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{children:[e.jsx(At,{className:"text-lg",children:v.name}),e.jsxs(Gn,{children:[v.agentCount," agents"]})]})]}),e.jsx(Be,{variant:b?"default":"outline",children:b?"Active Subscription":"No Active Subscription"})]})}),e.jsx(Ie,{children:((S=v.managers)==null?void 0:S.length)>0?e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-sm font-medium text-muted-foreground",children:"Managers:"}),v.managers.map(C=>{const E=O9e[C.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:C.name}),e.jsx("p",{className:"text-sm text-muted-foreground",children:C.email})]}),e.jsx("div",{className:"text-right",children:E?e.jsxs("div",{children:[e.jsx(Be,{variant:"default",children:E.name}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:E.price})]}):e.jsx(Be,{variant:"outline",children:"No Subscription"})})]},C.id)})]}):e.jsx("p",{className:"text-sm text-muted-foreground",children:"No managers assigned"})})]},v.id)})})}),e.jsx(Xt,{value:"websites",className:"space-y-4",children:e.jsxs(Ne,{children:[e.jsxs(Ct,{children:[e.jsxs(At,{className:"flex items-center gap-2",children:[e.jsx(dl,{className:"h-5 w-5 text-primary"}),"Local Move Website Subscriptions"]}),e.jsx(Gn,{children:"$249 setup fee + $99/mo subscriptions from TheLocalMove.com agent websites"})]}),e.jsx(Ie,{className:"p-0",children:e.jsxs(mi,{children:[e.jsx(fi,{children:e.jsxs(En,{children:[e.jsx(Dt,{children:"Agent"}),e.jsx(Dt,{children:"Status"}),e.jsx(Dt,{children:"Setup Fee"}),e.jsx(Dt,{children:"Monthly"}),e.jsx(Dt,{children:"Next Renewal"}),e.jsx(Dt,{children:"Started"}),e.jsx(Dt,{className:"text-right",children:"Actions"})]})}),e.jsx(pi,{children:m?m.length===0?e.jsx(En,{children:e.jsx(wt,{colSpan:7,className:"text-center py-8 text-muted-foreground",children:"No website subscriptions yet"})}):m.map(v=>e.jsxs(En,{children:[e.jsx(wt,{children:e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:v.agent_name||"—"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:v.agent_email})]})}),e.jsx(wt,{children:e.jsx(Be,{variant:v.status==="active"?"default":v.status==="canceled"?"destructive":"outline",children:v.status})}),e.jsx(wt,{children:v.setup_fee_paid?e.jsxs(Be,{variant:"secondary",children:["Paid · $",(v.setup_fee_amount_cents/100).toFixed(0)]}):e.jsx(Be,{variant:"outline",children:"Unpaid"})}),e.jsxs(wt,{className:"font-medium",children:["$",(v.monthly_amount_cents/100).toFixed(0),"/mo"]}),e.jsx(wt,{children:v.current_period_end?e.jsx("span",{className:"text-sm",children:en(new Date(v.current_period_end),"MMM d, yyyy")}):e.jsx("span",{className:"text-sm text-muted-foreground",children:"—"})}),e.jsx(wt,{children:e.jsx("span",{className:"text-sm",children:en(new Date(v.created_at),"MMM d, yyyy")})}),e.jsx(wt,{className:"text-right",children:v.stripe_customer_id&&e.jsx($,{variant:"ghost",size:"sm",onClick:()=>y(v.stripe_customer_id),children:e.jsx(kr,{className:"h-4 w-4"})})})]},v.id)):e.jsx(En,{children:e.jsx(wt,{colSpan:7,className:"text-center py-8",children:"Loading…"})})})]})})]})})]})]})})}function wFn(){const[s,t]=j.useState([]),[n,r]=j.useState(!0),[a,i]=j.useState(""),[l,o]=j.useState("all"),[c,d]=j.useState({total:0,qualified:0,pending:0,cancelled:0,totalDiscounts:0});j.useEffect(()=>{u()},[]);const u=async()=>{try{const{data:g,error:x}=await q.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(x)throw x;t(g||[]);const y=(g==null?void 0:g.filter(w=>w.status==="qualified").length)||0,v=(g==null?void 0:g.filter(w=>w.status==="pending").length)||0,b=(g==null?void 0:g.filter(w=>w.status==="cancelled").length)||0;d({total:(g==null?void 0:g.length)||0,qualified:y,pending:v,cancelled:b,totalDiscounts:y*25})}catch(g){console.error("Error fetching referrals:",g),re.error("Failed to load referrals")}finally{r(!1)}},h=async()=>{try{re.loading("Processing qualifications...");const{error:g}=await q.functions.invoke("process-referral-qualifications");if(g)throw g;re.dismiss(),re.success("Qualifications processed successfully"),u()}catch(g){re.dismiss(),console.error("Error processing qualifications:",g),re.error("Failed to process qualifications")}},m=s.filter(g=>{var v,b,w,S,C,E;const x=((b=(v=g.referrer_brokerage)==null?void 0:v.name)==null?void 0:b.toLowerCase().includes(a.toLowerCase()))||((S=(w=g.referred_brokerage)==null?void 0:w.name)==null?void 0:S.toLowerCase().includes(a.toLowerCase()))||((E=(C=g.referred_user)==null?void 0:C.email)==null?void 0:E.toLowerCase().includes(a.toLowerCase())),y=l==="all"||g.status===l;return x&&y}),f=g=>{switch(g){case"qualified":return e.jsxs(Be,{className:"bg-green-100 text-green-800",children:[e.jsx(Nc,{className:"h-3 w-3 mr-1"}),"Qualified"]});case"pending":return e.jsxs(Be,{variant:"secondary",children:[e.jsx(da,{className:"h-3 w-3 mr-1"}),"Pending"]});case"cancelled":return e.jsxs(Be,{variant:"destructive",children:[e.jsx(ku,{className:"h-3 w-3 mr-1"}),"Cancelled"]});default:return e.jsx(Be,{children:g})}};return e.jsx(Vs,{title:"Referral Program",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(Fm,{title:"Referral Program",description:"Track and manage brokerage referrals",children:e.jsxs($,{onClick:h,variant:"outline",children:[e.jsx(ro,{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(Ne,{children:e.jsx(Ie,{className:"pt-6",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Zn,{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(Ne,{children:e.jsx(Ie,{className:"pt-6",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Nc,{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(Ne,{children:e.jsx(Ie,{className:"pt-6",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(da,{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(Ne,{children:e.jsx(Ie,{className:"pt-6",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ku,{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(Ne,{children:e.jsx(Ie,{className:"pt-6",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ru,{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(Ne,{children:[e.jsxs(Ct,{children:[e.jsx(At,{children:"All Referrals"}),e.jsx(Gn,{children:"View and manage all referral relationships"})]}),e.jsxs(Ie,{children:[e.jsxs("div",{className:"flex gap-4 mb-4",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(Kr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(pe,{placeholder:"Search by brokerage or email...",value:a,onChange:g=>i(g.target.value),className:"pl-10"})]}),e.jsxs(ms,{value:l,onValueChange:o,children:[e.jsx(us,{className:"w-[180px]",children:e.jsx(fs,{placeholder:"Filter by status"})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"all",children:"All Statuses"}),e.jsx(Ge,{value:"pending",children:"Pending"}),e.jsx(Ge,{value:"qualified",children:"Qualified"}),e.jsx(Ge,{value:"cancelled",children:"Cancelled"})]})]})]}),n?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(mi,{children:[e.jsx(fi,{children:e.jsxs(En,{children:[e.jsx(Dt,{children:"Referrer"}),e.jsx(Dt,{children:"Referred"}),e.jsx(Dt,{children:"Signup Date"}),e.jsx(Dt,{children:"Status"}),e.jsx(Dt,{children:"Qualified Date"}),e.jsx(Dt,{children:"Discount"})]})}),e.jsx(pi,{children:m.length===0?e.jsx(En,{children:e.jsx(wt,{colSpan:6,className:"text-center text-muted-foreground py-8",children:"No referrals found"})}):m.map(g=>{var x,y,v,b;return e.jsxs(En,{children:[e.jsx(wt,{className:"font-medium",children:((x=g.referrer_brokerage)==null?void 0:x.name)||"Unknown"}),e.jsx(wt,{children:e.jsxs("div",{children:[e.jsx("p",{children:((y=g.referred_brokerage)==null?void 0:y.name)||((v=g.referred_user)==null?void 0:v.name)||"Pending setup"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:(b=g.referred_user)==null?void 0:b.email})]})}),e.jsx(wt,{children:en(new Date(g.signup_date),"MMM d, yyyy")}),e.jsx(wt,{children:f(g.status)}),e.jsx(wt,{children:g.qualified_date?en(new Date(g.qualified_date),"MMM d, yyyy"):"-"}),e.jsx(wt,{children:g.discount_applied?e.jsx(Be,{variant:"outline",className:"text-green-600",children:"$25/mo applied"}):e.jsx("span",{className:"text-muted-foreground",children:"-"})})]},g.id)})})]})]})]})]})})}const z9e=[{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"}],jFn=[{value:"brokerage_manager",label:"Brokerage Manager"},{value:"agent",label:"Agent"}];function NFn(){const[s,t]=j.useState([]),[n,r]=j.useState(!0),[a,i]=j.useState(!1),[l,o]=j.useState(null),[c,d]=j.useState({title:"",description:"",action_type:"view_template",target_role:"agent",is_active:!0});j.useEffect(()=>{u()},[]);const u=async()=>{try{const{data:b,error:w}=await q.from("onboarding_checklist_items").select("*").order("target_role").order("sort_order");if(w)throw w;t(b||[])}catch(b){console.error("Error fetching checklist items:",b),re.error("Failed to load checklist items")}finally{r(!1)}},h=()=>{o(null),d({title:"",description:"",action_type:"view_template",target_role:"agent",is_active:!0}),i(!0)},m=b=>{o(b),d({title:b.title,description:b.description||"",action_type:b.action_type,target_role:b.target_role,is_active:b.is_active}),i(!0)},f=async()=>{if(!c.title.trim()){re.error("Title is required");return}try{if(l){const{error:b}=await q.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(b)throw b;re.success("Checklist item updated")}else{const b=s.filter(S=>S.target_role===c.target_role).reduce((S,C)=>Math.max(S,C.sort_order),-1),{error:w}=await q.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:b+1});if(w)throw w;re.success("Checklist item created")}i(!1),u()}catch(b){console.error("Error saving checklist item:",b),re.error("Failed to save checklist item")}},g=async b=>{if(await fo("Are you sure you want to delete this checklist item?"))try{const{error:w}=await q.from("onboarding_checklist_items").delete().eq("id",b);if(w)throw w;re.success("Checklist item deleted"),u()}catch(w){console.error("Error deleting checklist item:",w),re.error("Failed to delete checklist item")}},x=async b=>{try{const{error:w}=await q.from("onboarding_checklist_items").update({is_active:!b.is_active}).eq("id",b.id);if(w)throw w;re.success(b.is_active?"Item deactivated":"Item activated"),u()}catch(w){console.error("Error toggling item:",w),re.error("Failed to update item")}},y=s.filter(b=>b.target_role==="brokerage_manager"),v=s.filter(b=>b.target_role==="agent");return e.jsxs(Vs,{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($,{onClick:h,className:"gap-2",children:[e.jsx(dn,{className:"h-4 w-4"}),"Add Item"]})]}),e.jsxs(Ne,{children:[e.jsx(Ct,{children:e.jsxs(At,{className:"flex items-center gap-2",children:[e.jsx(Be,{variant:"secondary",children:"Brokerage Manager"}),"Checklist Items"]})}),e.jsx(Ie,{children:y.length===0?e.jsx("p",{className:"text-muted-foreground text-center py-4",children:"No checklist items for brokerage managers"}):e.jsxs(mi,{children:[e.jsx(fi,{children:e.jsxs(En,{children:[e.jsx(Dt,{className:"w-12",children:"#"}),e.jsx(Dt,{children:"Title"}),e.jsx(Dt,{children:"Action Type"}),e.jsx(Dt,{children:"Status"}),e.jsx(Dt,{className:"text-right",children:"Actions"})]})}),e.jsx(pi,{children:y.map((b,w)=>{var S;return e.jsxs(En,{children:[e.jsx(wt,{className:"text-muted-foreground",children:w+1}),e.jsx(wt,{children:e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:b.title}),b.description&&e.jsx("p",{className:"text-sm text-muted-foreground line-clamp-1",children:b.description})]})}),e.jsx(wt,{children:e.jsx(Be,{variant:"outline",children:((S=z9e.find(C=>C.value===b.action_type))==null?void 0:S.label)||b.action_type})}),e.jsx(wt,{children:e.jsx(Sn,{checked:b.is_active,onCheckedChange:()=>x(b)})}),e.jsx(wt,{className:"text-right",children:e.jsxs("div",{className:"flex items-center justify-end gap-2",children:[e.jsx($,{variant:"ghost",size:"icon",onClick:()=>m(b),children:e.jsx(gi,{className:"h-4 w-4"})}),e.jsx($,{variant:"ghost",size:"icon",onClick:()=>g(b.id),children:e.jsx(Wn,{className:"h-4 w-4 text-destructive"})})]})})]},b.id)})})]})})]}),e.jsxs(Ne,{children:[e.jsx(Ct,{children:e.jsxs(At,{className:"flex items-center gap-2",children:[e.jsx(Be,{variant:"secondary",children:"Agent"}),"Checklist Items"]})}),e.jsx(Ie,{children:v.length===0?e.jsx("p",{className:"text-muted-foreground text-center py-4",children:"No checklist items for agents"}):e.jsxs(mi,{children:[e.jsx(fi,{children:e.jsxs(En,{children:[e.jsx(Dt,{className:"w-12",children:"#"}),e.jsx(Dt,{children:"Title"}),e.jsx(Dt,{children:"Action Type"}),e.jsx(Dt,{children:"Status"}),e.jsx(Dt,{className:"text-right",children:"Actions"})]})}),e.jsx(pi,{children:v.map((b,w)=>{var S;return e.jsxs(En,{children:[e.jsx(wt,{className:"text-muted-foreground",children:w+1}),e.jsx(wt,{children:e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:b.title}),b.description&&e.jsx("p",{className:"text-sm text-muted-foreground line-clamp-1",children:b.description})]})}),e.jsx(wt,{children:e.jsx(Be,{variant:"outline",children:((S=z9e.find(C=>C.value===b.action_type))==null?void 0:S.label)||b.action_type})}),e.jsx(wt,{children:e.jsx(Sn,{checked:b.is_active,onCheckedChange:()=>x(b)})}),e.jsx(wt,{className:"text-right",children:e.jsxs("div",{className:"flex items-center justify-end gap-2",children:[e.jsx($,{variant:"ghost",size:"icon",onClick:()=>m(b),children:e.jsx(gi,{className:"h-4 w-4"})}),e.jsx($,{variant:"ghost",size:"icon",onClick:()=>g(b.id),children:e.jsx(Wn,{className:"h-4 w-4 text-destructive"})})]})})]},b.id)})})]})})]})]}),e.jsx(zs,{open:a,onOpenChange:i,children:e.jsxs(Os,{children:[e.jsx(Us,{children:e.jsx(Bs,{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(ee,{htmlFor:"title",children:"Title *"}),e.jsx(pe,{id:"title",value:c.title,onChange:b=>d({...c,title:b.target.value}),placeholder:"e.g., Watch your first academy video"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"description",children:"Description"}),e.jsx(Rs,{id:"description",value:c.description,onChange:b=>d({...c,description:b.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(ee,{children:"Target Role"}),e.jsxs(ms,{value:c.target_role,onValueChange:b=>d({...c,target_role:b}),children:[e.jsx(us,{children:e.jsx(fs,{})}),e.jsx(hs,{children:jFn.map(b=>e.jsx(Ge,{value:b.value,children:b.label},b.value))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Action Type"}),e.jsxs(ms,{value:c.action_type,onValueChange:b=>d({...c,action_type:b}),children:[e.jsx(us,{children:e.jsx(fs,{})}),e.jsx(hs,{children:z9e.map(b=>e.jsx(Ge,{value:b.value,children:b.label},b.value))})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Sn,{id:"is_active",checked:c.is_active,onCheckedChange:b=>d({...c,is_active:b})}),e.jsx(ee,{htmlFor:"is_active",children:"Active"})]})]}),e.jsxs(Ar,{children:[e.jsx($,{variant:"outline",onClick:()=>i(!1),children:"Cancel"}),e.jsx($,{onClick:f,children:l?"Save Changes":"Create Item"})]})]})})]})}function kFn(){const[s,t]=j.useState(""),[n,r]=j.useState("all"),[a,i]=j.useState("name"),[l,o]=j.useState("asc"),[c,d]=j.useState(""),[u,h]=j.useState(""),[m,f]=j.useState(""),[g,x]=j.useState(""),{data:y}=tt({queryKey:["admin-brokerages"],queryFn:async()=>{const{data:D,error:O}=await q.from("brokerages").select("id, name").order("name");if(O)throw O;return D}}),v=async D=>{let U=[],W=0,V=!0;for(;V;){const{data:G,error:Y}=await D(W,W+1e3-1);if(Y)throw Y;G&&G.length>0?(U=[...U,...G],W+=1e3,V=G.length===1e3):V=!1}return U},{data:b,isLoading:w}=tt({queryKey:["admin-agent-os-user-stats"],queryFn:async()=>{const D=await v((Ee,Se)=>q.from("profiles").select("id, name, email, brokerage_id, created_at").range(Ee,Se)),{data:O}=await q.from("brokerages").select("id, name"),U=new Map((O==null?void 0:O.map(Ee=>[Ee.id,Ee.name]))||[]),[{data:W},{data:V},{data:G},{data:Y},{data:X},{data:ae},{data:ie}]=await Promise.all([q.rpc("get_admin_contact_counts"),q.rpc("get_admin_video_counts"),q.rpc("get_admin_popby_counts"),q.rpc("get_admin_listing_counts"),q.rpc("get_admin_deal_counts"),q.rpc("get_admin_portal_counts"),q.rpc("get_admin_sendable_card_counts")]),ne=new Map;W==null||W.forEach(Ee=>ne.set(Ee.owner_user_id,Ee.contact_count));const te=new Map;V==null||V.forEach(Ee=>te.set(Ee.owner_user_id,Ee.video_count));const J=new Map;G==null||G.forEach(Ee=>J.set(Ee.owner_user_id,Ee.popby_count));const ce=new Map;Y==null||Y.forEach(Ee=>ce.set(Ee.agent_id,Ee.listing_count));const _e=new Map;X==null||X.forEach(Ee=>_e.set(Ee.owner_user_id,Ee.deal_count));const he=new Map;ae==null||ae.forEach(Ee=>he.set(Ee.owner_user_id,{total:Ee.portal_count,active:Ee.active_portal_count}));const ue=new Map;return ie==null||ie.forEach(Ee=>ue.set(Ee.owner_user_id,{total:Ee.card_count,sent:Ee.sent_card_count,views:Ee.total_card_views})),D.map(Ee=>{const Se=he.get(Ee.id),Le=ue.get(Ee.id);return{id:Ee.id,name:Ee.name||"Unknown",email:Ee.email||"",brokerage_id:Ee.brokerage_id,brokerage_name:Ee.brokerage_id&&U.get(Ee.brokerage_id)||null,contact_count:ne.get(Ee.id)||0,video_count:te.get(Ee.id)||0,popby_count:J.get(Ee.id)||0,listing_count:ce.get(Ee.id)||0,deal_count:_e.get(Ee.id)||0,portal_count:(Se==null?void 0:Se.total)||0,active_portal_count:(Se==null?void 0:Se.active)||0,card_count:(Le==null?void 0:Le.total)||0,sent_card_count:(Le==null?void 0:Le.sent)||0,total_card_views:(Le==null?void 0:Le.views)||0,created_at:Ee.created_at}})}}),S=j.useMemo(()=>{if(!b)return[];let D=b.filter(O=>{const U=s.toLowerCase(),W=!s||O.name.toLowerCase().includes(U)||O.email.toLowerCase().includes(U),V=n==="all"||n==="none"&&!O.brokerage_id||O.brokerage_id===n,G=parseInt(c)||0,Y=parseInt(u)||0,X=parseInt(m)||0,ae=parseInt(g)||0,ie=O.contact_count>=G&&O.video_count>=Y&&O.popby_count>=X&&O.listing_count>=ae;return W&&V&&ie});return D.sort((O,U)=>{let W=0;return a==="name"?W=O.name.localeCompare(U.name):W=O[a]-U[a],l==="asc"?W:-W}),D},[b,s,n,a,l,c,u,m,g]),C=D=>{a===D?o(l==="asc"?"desc":"asc"):(i(D),o("desc"))},E=()=>{const D=["Name","Email","Brokerage","Contacts","Videos","Popbys","Listings","Deals","Portals (Active)","Cards Created","Cards Sent","Card Views"],O=S.map(Y=>[Y.name,Y.email,Y.brokerage_name||"None",Y.contact_count,Y.video_count,Y.popby_count,Y.listing_count,Y.deal_count,`${Y.portal_count} (${Y.active_portal_count})`,Y.card_count,Y.sent_card_count,Y.total_card_views]),U=[D.join(","),...O.map(Y=>Y.map(X=>`"${X}"`).join(","))].join(` `),W=new Blob([U],{type:"text/csv"}),V=URL.createObjectURL(W),G=document.createElement("a");G.href=V,G.download=`agent-os-user-stats-${new Date().toISOString().split("T")[0]}.csv`,G.click(),URL.revokeObjectURL(V)},I=j.useMemo(()=>S.length?S.reduce((D,O)=>({contacts:D.contacts+O.contact_count,videos:D.videos+O.video_count,popbys:D.popbys+O.popby_count,listings:D.listings+O.listing_count,deals:D.deals+O.deal_count,portals:D.portals+O.portal_count,activePortals:D.activePortals+O.active_portal_count,cards:D.cards+O.card_count,sentCards:D.sentCards+O.sent_card_count,cardViews:D.cardViews+O.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},[S]),P=j.useMemo(()=>S.length?{portals:S.filter(D=>D.portal_count>0).length,cards:S.filter(D=>D.card_count>0).length}:{portals:0,cards:0},[S]),R=({field:D,children:O})=>e.jsx(Dt,{className:"cursor-pointer hover:bg-muted/50 select-none",onClick:()=>C(D),children:e.jsxs("div",{className:"flex items-center gap-1",children:[O,e.jsx(By,{className:`h-3 w-3 ${a===D?"text-primary":"text-muted-foreground"}`})]})});return e.jsx(jk,{children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[e.jsxs(Ne,{className:"border-blue-500/20 bg-gradient-to-br from-blue-500/5 to-transparent",children:[e.jsx(Ct,{className:"pb-2",children:e.jsxs(At,{className:"text-sm font-medium flex items-center gap-2",children:[e.jsx(d2,{className:"h-4 w-4 text-blue-500"}),"Client Portals"]})}),e.jsx(Ie,{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:P.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:I.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:I.activePortals}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Active Portals"})]})]})})]}),e.jsxs(Ne,{className:"border-violet-500/20 bg-gradient-to-br from-violet-500/5 to-transparent",children:[e.jsx(Ct,{className:"pb-2",children:e.jsxs(At,{className:"text-sm font-medium flex items-center gap-2",children:[e.jsx(mn,{className:"h-4 w-4 text-violet-500"}),"Card Studio"]})}),e.jsx(Ie,{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:P.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:I.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:I.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:I.cardViews}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Total Views"})]})]})})]})]}),e.jsxs(Ne,{children:[e.jsx(Ct,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs(At,{className:"flex items-center gap-2",children:[e.jsx(Zn,{className:"h-5 w-5"}),"User Activity Analytics"]}),e.jsx(Gn,{children:"View all users and their Agent OS usage metrics"})]}),e.jsxs($,{variant:"outline",size:"sm",onClick:E,children:[e.jsx(di,{className:"h-4 w-4 mr-2"}),"Export CSV"]})]})}),e.jsxs(Ie,{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(Kr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(pe,{placeholder:"Search by name or email...",value:s,onChange:D=>t(D.target.value),className:"pl-9"})]})}),e.jsx("div",{children:e.jsxs(ms,{value:n,onValueChange:r,children:[e.jsxs(us,{children:[e.jsx(ji,{className:"h-4 w-4 mr-2 text-muted-foreground"}),e.jsx(fs,{placeholder:"Brokerage"})]}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"all",children:"All Brokerages"}),e.jsx(Ge,{value:"none",children:"No Brokerage"}),y==null?void 0:y.map(D=>e.jsx(Ge,{value:D.id,children:D.name},D.id))]})]})}),e.jsx("div",{children:e.jsx(pe,{type:"number",placeholder:"Min contacts",value:c,onChange:D=>d(D.target.value),min:"0"})}),e.jsx("div",{children:e.jsx(pe,{type:"number",placeholder:"Min videos",value:u,onChange:D=>h(D.target.value),min:"0"})}),e.jsx("div",{children:e.jsx(pe,{type:"number",placeholder:"Min popbys",value:m,onChange:D=>f(D.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:S.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:I.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:I.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:I.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:I.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:I.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:I.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:I.cards.toLocaleString()}),e.jsx("div",{className:"text-muted-foreground",children:"Cards"})]})]}),w?e.jsx("div",{className:"flex justify-center py-12",children:e.jsx(kt,{className:"h-8 w-8 animate-spin text-muted-foreground"})}):e.jsx("div",{className:"rounded-md border overflow-x-auto",children:e.jsxs(mi,{children:[e.jsx(fi,{children:e.jsxs(En,{children:[e.jsx(R,{field:"name",children:"Name"}),e.jsx(Dt,{children:"Email"}),e.jsx(Dt,{children:"Brokerage"}),e.jsx(R,{field:"contact_count",children:"Contacts"}),e.jsx(R,{field:"video_count",children:"Videos"}),e.jsx(R,{field:"popby_count",children:"Popbys"}),e.jsx(R,{field:"listing_count",children:"Listings"}),e.jsx(R,{field:"deal_count",children:"Deals"}),e.jsx(R,{field:"portal_count",children:e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(d2,{className:"h-3 w-3 text-blue-500"}),"Portals"]})}),e.jsx(R,{field:"card_count",children:e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(mn,{className:"h-3 w-3 text-violet-500"}),"Cards"]})})]})}),e.jsx(pi,{children:S.length===0?e.jsx(En,{children:e.jsx(wt,{colSpan:10,className:"text-center py-8 text-muted-foreground",children:"No users found matching your filters"})}):S.map(D=>e.jsxs(En,{children:[e.jsx(wt,{className:"font-medium",children:D.name}),e.jsx(wt,{className:"text-muted-foreground",children:D.email}),e.jsx(wt,{children:D.brokerage_name?e.jsx(Be,{variant:"secondary",children:D.brokerage_name}):e.jsx("span",{className:"text-muted-foreground",children:"—"})}),e.jsx(wt,{children:e.jsx(Be,{variant:D.contact_count>0?"default":"outline",children:D.contact_count})}),e.jsx(wt,{children:e.jsx(Be,{variant:D.video_count>0?"default":"outline",children:D.video_count})}),e.jsx(wt,{children:e.jsx(Be,{variant:D.popby_count>0?"default":"outline",children:D.popby_count})}),e.jsx(wt,{children:e.jsx(Be,{variant:D.listing_count>0?"default":"outline",children:D.listing_count})}),e.jsx(wt,{children:e.jsx(Be,{variant:D.deal_count>0?"default":"outline",children:D.deal_count})}),e.jsx(wt,{children:D.portal_count>0?e.jsxs(ly,{children:[e.jsx(cy,{children:e.jsxs(Be,{variant:"default",className:"bg-blue-600 hover:bg-blue-700",children:[D.portal_count,D.active_portal_count>0&&e.jsxs("span",{className:"ml-1 opacity-75",children:["(",D.active_portal_count," active)"]})]})}),e.jsxs(Nx,{children:[e.jsxs("p",{children:[D.portal_count," total portals"]}),e.jsxs("p",{children:[D.active_portal_count," currently active"]})]})]}):e.jsx(Be,{variant:"outline",children:"0"})}),e.jsx(wt,{children:D.card_count>0?e.jsxs(ly,{children:[e.jsx(cy,{children:e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(Be,{variant:"default",className:"bg-violet-600 hover:bg-violet-700",children:D.card_count}),D.sent_card_count>0&&e.jsxs("span",{className:"flex items-center gap-0.5 text-xs text-emerald-600",children:[e.jsx(Yr,{className:"h-3 w-3"}),D.sent_card_count]}),D.total_card_views>0&&e.jsxs("span",{className:"flex items-center gap-0.5 text-xs text-muted-foreground",children:[e.jsx(Ca,{className:"h-3 w-3"}),D.total_card_views]})]})}),e.jsxs(Nx,{children:[e.jsxs("p",{children:[D.card_count," cards created"]}),e.jsxs("p",{children:[D.sent_card_count," sent"]}),e.jsxs("p",{children:[D.total_card_views," total views"]})]})]}):e.jsx(Be,{variant:"outline",children:"0"})})]},D.id))})]})})]})]})]})})}function SFn(){Bi(),Vt();const[s,t]=j.useState("user-analytics"),{data:n}=tt({queryKey:["admin-feature-flags"],queryFn:async()=>{const{data:f,error:g}=await q.from("feature_flags").select("*").order("key");if(g)throw g;return f}}),{data:r,isLoading:a}=tt({queryKey:["admin-relationship-types"],queryFn:async()=>{const{data:f,error:g}=await q.from("relationship_types").select("*").order("sort_order");if(g)throw g;return f}}),{data:i,isLoading:l}=tt({queryKey:["admin-action-types"],queryFn:async()=>{const{data:f,error:g}=await q.from("action_types").select("*").order("sort_order");if(g)throw g;return f}}),{data:o,isLoading:c}=tt({queryKey:["admin-action-scripts"],queryFn:async()=>{const{data:f,error:g}=await q.from("action_scripts").select("*, action_type:action_types(*)");if(g)throw g;return f}}),{data:d,isLoading:u}=tt({queryKey:["admin-touchpoint-plans"],queryFn:async()=>{const{data:f,error:g}=await q.from("touchpoint_plans").select("*").order("name");if(g)throw g;return f}}),{data:h,isLoading:m}=tt({queryKey:["admin-popby-items"],queryFn:async()=>{const{data:f,error:g}=await q.from("popby_items").select("*").is("owner_user_id",null).order("name");if(g)throw g;return f}});return e.jsx(Vs,{title:"Agent OS Control Center",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(Fm,{title:"Agent OS Control Center",description:"Manage InnerCircle settings, scripts, and touchpoint plans"}),e.jsxs(ha,{value:s,onValueChange:t,children:[e.jsxs(ma,{className:"grid w-full grid-cols-9",children:[e.jsxs(Zt,{value:"user-analytics",className:"gap-2",children:[e.jsx(Wl,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Users"})]}),e.jsxs(Zt,{value:"relationship-types",className:"gap-2",children:[e.jsx(Zn,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Relationships"})]}),e.jsxs(Zt,{value:"action-types",className:"gap-2",children:[e.jsx(Da,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Actions"})]}),e.jsxs(Zt,{value:"scripts",className:"gap-2",children:[e.jsx(Jr,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Scripts"})]}),e.jsxs(Zt,{value:"video-scripts",className:"gap-2",children:[e.jsx(rf,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Video Scripts"})]}),e.jsxs(Zt,{value:"plans",className:"gap-2",children:[e.jsx(Ta,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Plans"})]}),e.jsxs(Zt,{value:"popbys",className:"gap-2",children:[e.jsx(ul,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Popbys"})]}),e.jsxs(Zt,{value:"settings",className:"gap-2",children:[e.jsx(Sd,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Settings"})]}),e.jsxs(Zt,{value:"feature-flags",className:"gap-2",children:[e.jsx(TE,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Flags"})]})]}),e.jsx(Xt,{value:"user-analytics",className:"mt-6",children:e.jsx(kFn,{})}),e.jsx(Xt,{value:"relationship-types",className:"mt-6",children:e.jsx(CFn,{types:r||[],isLoading:a})}),e.jsx(Xt,{value:"action-types",className:"mt-6",children:e.jsx(AFn,{types:i||[],isLoading:l})}),e.jsx(Xt,{value:"scripts",className:"mt-6",children:e.jsx(EFn,{scripts:o||[],actionTypes:i||[],isLoading:c})}),e.jsx(Xt,{value:"video-scripts",className:"mt-6",children:e.jsx(IFn,{})}),e.jsx(Xt,{value:"plans",className:"mt-6",children:e.jsx(TFn,{plans:d||[],actionTypes:i||[],scripts:o||[],isLoading:u})}),e.jsx(Xt,{value:"popbys",className:"mt-6",children:e.jsx(PFn,{items:h||[],isLoading:m})}),e.jsx(Xt,{value:"settings",className:"mt-6",children:e.jsx(LFn,{})}),e.jsx(Xt,{value:"feature-flags",className:"mt-6",children:e.jsx(MFn,{flags:n||[]})})]})]})})}function CFn({types:s,isLoading:t}){const{toast:n}=Bi(),r=Vt(),[a,i]=j.useState(null),[l,o]=j.useState(!1),c=ft({mutationFn:async u=>{if(u.id){const{error:h}=await q.from("relationship_types").update({name:u.name,description:u.description,icon:u.icon}).eq("id",u.id);if(h)throw h}else{const{error:h}=await q.from("relationship_types").insert([{name:u.name,description:u.description,icon:u.icon,sort_order:s.length}]);if(h)throw h}},onSuccess:()=>{r.invalidateQueries({queryKey:["admin-relationship-types"]}),o(!1),i(null),n({title:"Saved successfully"})},onError:u=>{n({title:"Error",description:u.message,variant:"destructive"})}}),d=async u=>{await q.from("relationship_types").update({active:!u.active}).eq("id",u.id),r.invalidateQueries({queryKey:["admin-relationship-types"]})};return e.jsxs(Ne,{children:[e.jsxs(Ct,{className:"flex flex-row items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(At,{children:"Relationship Types"}),e.jsx(Gn,{children:"Define the relationship categories for InnerCircle contacts"})]}),e.jsxs($,{onClick:()=>{i(null),o(!0)},children:[e.jsx(dn,{className:"h-4 w-4 mr-2"}),"Add Type"]})]}),e.jsx(Ie,{children:t?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx(kt,{className:"h-8 w-8 animate-spin text-muted-foreground"})}):e.jsxs(mi,{children:[e.jsx(fi,{children:e.jsxs(En,{children:[e.jsx(Dt,{className:"w-12"}),e.jsx(Dt,{children:"Name"}),e.jsx(Dt,{children:"Description"}),e.jsx(Dt,{children:"Status"}),e.jsx(Dt,{className:"w-24",children:"Actions"})]})}),e.jsx(pi,{children:s.map(u=>e.jsxs(En,{children:[e.jsx(wt,{children:e.jsx(Ug,{className:"h-4 w-4 text-muted-foreground cursor-grab"})}),e.jsx(wt,{className:"font-medium",children:u.name}),e.jsx(wt,{className:"text-muted-foreground",children:u.description}),e.jsx(wt,{children:e.jsx(Sn,{checked:u.active,onCheckedChange:()=>d(u)})}),e.jsx(wt,{children:e.jsx($,{variant:"ghost",size:"icon",onClick:()=>{i(u),o(!0)},children:e.jsx(gi,{className:"h-4 w-4"})})})]},u.id))})]})}),e.jsx(zs,{open:l,onOpenChange:o,children:e.jsxs(Os,{children:[e.jsx(Us,{children:e.jsxs(Bs,{children:[a?"Edit":"Add"," Relationship Type"]})}),e.jsxs("form",{onSubmit:u=>{u.preventDefault();const h=new FormData(u.currentTarget);c.mutate({id:a==null?void 0:a.id,name:h.get("name"),description:h.get("description"),icon:h.get("icon")})},children:[e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"name",children:"Name"}),e.jsx(pe,{id:"name",name:"name",defaultValue:a==null?void 0:a.name,required:!0})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"description",children:"Description"}),e.jsx(Rs,{id:"description",name:"description",defaultValue:(a==null?void 0:a.description)||""})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"icon",children:"Icon"}),e.jsx(pe,{id:"icon",name:"icon",defaultValue:(a==null?void 0:a.icon)||"",placeholder:"e.g., star, heart, user"})]})]}),e.jsxs(Ar,{className:"mt-4",children:[e.jsx($,{type:"button",variant:"outline",onClick:()=>o(!1),children:"Cancel"}),e.jsxs($,{type:"submit",disabled:c.isPending,children:[c.isPending&&e.jsx(kt,{className:"h-4 w-4 mr-2 animate-spin"}),"Save"]})]})]})]})})]})}function AFn({types:s,isLoading:t}){const{toast:n}=Bi(),r=Vt(),[a,i]=j.useState(null),[l,o]=j.useState(!1),c=ft({mutationFn:async u=>{if(u.id){const{error:h}=await q.from("action_types").update({name:u.name,description:u.description,icon:u.icon,color:u.color}).eq("id",u.id);if(h)throw h}else{const{error:h}=await q.from("action_types").insert([{name:u.name,description:u.description,icon:u.icon,color:u.color,sort_order:s.length}]);if(h)throw h}},onSuccess:()=>{r.invalidateQueries({queryKey:["admin-action-types"]}),o(!1),i(null),n({title:"Saved successfully"})},onError:u=>{n({title:"Error",description:u.message,variant:"destructive"})}}),d=async u=>{await q.from("action_types").update({active:!u.active}).eq("id",u.id),r.invalidateQueries({queryKey:["admin-action-types"]})};return e.jsxs(Ne,{children:[e.jsxs(Ct,{className:"flex flex-row items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(At,{children:"Action Types"}),e.jsx(Gn,{children:"Define the types of touchpoint actions agents can take"})]}),e.jsxs($,{onClick:()=>{i(null),o(!0)},children:[e.jsx(dn,{className:"h-4 w-4 mr-2"}),"Add Action"]})]}),e.jsx(Ie,{children:t?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx(kt,{className:"h-8 w-8 animate-spin text-muted-foreground"})}):e.jsxs(mi,{children:[e.jsx(fi,{children:e.jsxs(En,{children:[e.jsx(Dt,{children:"Name"}),e.jsx(Dt,{children:"Description"}),e.jsx(Dt,{children:"Color"}),e.jsx(Dt,{children:"Status"}),e.jsx(Dt,{className:"w-24",children:"Actions"})]})}),e.jsx(pi,{children:s.map(u=>e.jsxs(En,{children:[e.jsx(wt,{className:"font-medium",children:u.name}),e.jsx(wt,{className:"text-muted-foreground",children:u.description}),e.jsx(wt,{children:u.color&&e.jsx("div",{className:"w-6 h-6 rounded",style:{backgroundColor:u.color}})}),e.jsx(wt,{children:e.jsx(Sn,{checked:u.active,onCheckedChange:()=>d(u)})}),e.jsx(wt,{children:e.jsx($,{variant:"ghost",size:"icon",onClick:()=>{i(u),o(!0)},children:e.jsx(gi,{className:"h-4 w-4"})})})]},u.id))})]})}),e.jsx(zs,{open:l,onOpenChange:o,children:e.jsxs(Os,{children:[e.jsx(Us,{children:e.jsxs(Bs,{children:[a?"Edit":"Add"," Action Type"]})}),e.jsxs("form",{onSubmit:u=>{u.preventDefault();const h=new FormData(u.currentTarget);c.mutate({id:a==null?void 0:a.id,name:h.get("name"),description:h.get("description"),icon:h.get("icon"),color:h.get("color")})},children:[e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"name",children:"Name"}),e.jsx(pe,{id:"name",name:"name",defaultValue:a==null?void 0:a.name,required:!0})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"description",children:"Description"}),e.jsx(Rs,{id:"description",name:"description",defaultValue:(a==null?void 0:a.description)||""})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"icon",children:"Icon"}),e.jsx(pe,{id:"icon",name:"icon",defaultValue:(a==null?void 0:a.icon)||"",placeholder:"e.g., phone, message"})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"color",children:"Color"}),e.jsx(pe,{id:"color",name:"color",type:"color",defaultValue:(a==null?void 0:a.color)||"#6366f1"})]})]}),e.jsxs(Ar,{className:"mt-4",children:[e.jsx($,{type:"button",variant:"outline",onClick:()=>o(!1),children:"Cancel"}),e.jsxs($,{type:"submit",disabled:c.isPending,children:[c.isPending&&e.jsx(kt,{className:"h-4 w-4 mr-2 animate-spin"}),"Save"]})]})]})]})})]})}function EFn({scripts:s,actionTypes:t,isLoading:n}){const{toast:r}=Bi(),a=Vt(),[i,l]=j.useState(null),[o,c]=j.useState(!1),d=ft({mutationFn:async h=>{if(h.id){const{error:m}=await q.from("action_scripts").update({title:h.title,action_type_id:h.action_type_id,tone:h.tone,script_body:h.script_body,active:h.active}).eq("id",h.id);if(m)throw m}else{const{error:m}=await q.from("action_scripts").insert([{title:h.title,action_type_id:h.action_type_id,tone:h.tone,script_body:h.script_body,active:!0}]);if(m)throw m}},onSuccess:()=>{a.invalidateQueries({queryKey:["admin-action-scripts"]}),c(!1),l(null),r({title:"Saved successfully"})},onError:h=>{r({title:"Error",description:h.message,variant:"destructive"})}}),u=ft({mutationFn:async h=>{const{error:m}=await q.from("action_scripts").delete().eq("id",h);if(m)throw m},onSuccess:()=>{a.invalidateQueries({queryKey:["admin-action-scripts"]}),r({title:"Deleted successfully"})}});return e.jsxs(Ne,{children:[e.jsxs(Ct,{className:"flex flex-row items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(At,{children:"Script Library"}),e.jsx(Gn,{children:"Create and manage scripts for each action type"})]}),e.jsxs($,{onClick:()=>{l(null),c(!0)},children:[e.jsx(dn,{className:"h-4 w-4 mr-2"}),"Add Script"]})]}),e.jsx(Ie,{children:n?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx(kt,{className:"h-8 w-8 animate-spin text-muted-foreground"})}):e.jsxs(mi,{children:[e.jsx(fi,{children:e.jsxs(En,{children:[e.jsx(Dt,{children:"Title"}),e.jsx(Dt,{children:"Action Type"}),e.jsx(Dt,{children:"Tone"}),e.jsx(Dt,{children:"Status"}),e.jsx(Dt,{className:"w-24",children:"Actions"})]})}),e.jsx(pi,{children:s.map(h=>{var m;return e.jsxs(En,{children:[e.jsx(wt,{className:"font-medium",children:h.title}),e.jsx(wt,{children:e.jsx(Be,{variant:"outline",children:((m=h.action_type)==null?void 0:m.name)||"Unknown"})}),e.jsx(wt,{className:"text-muted-foreground",children:h.tone}),e.jsx(wt,{children:e.jsx(Be,{variant:h.active?"default":"secondary",children:h.active?"Active":"Inactive"})}),e.jsxs(wt,{className:"flex gap-1",children:[e.jsx($,{variant:"ghost",size:"icon",onClick:()=>{l(h),c(!0)},children:e.jsx(gi,{className:"h-4 w-4"})}),e.jsx($,{variant:"ghost",size:"icon",onClick:()=>u.mutate(h.id),children:e.jsx(Wn,{className:"h-4 w-4 text-destructive"})})]})]},h.id)})})]})}),e.jsx(zs,{open:o,onOpenChange:c,children:e.jsxs(Os,{className:"max-w-2xl",children:[e.jsx(Us,{children:e.jsxs(Bs,{children:[i?"Edit":"Add"," Script"]})}),e.jsxs("form",{onSubmit:h=>{h.preventDefault();const m=new FormData(h.currentTarget);d.mutate({id:i==null?void 0:i.id,title:m.get("title"),action_type_id:m.get("action_type_id"),tone:m.get("tone"),script_body:m.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(ee,{htmlFor:"title",children:"Title"}),e.jsx(pe,{id:"title",name:"title",defaultValue:i==null?void 0:i.title,required:!0})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"action_type_id",children:"Action Type"}),e.jsxs(ms,{name:"action_type_id",defaultValue:i==null?void 0:i.action_type_id,children:[e.jsx(us,{children:e.jsx(fs,{placeholder:"Select action type"})}),e.jsx(hs,{children:t.map(h=>e.jsx(Ge,{value:h.id,children:h.name},h.id))})]})]})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"tone",children:"Tone (optional)"}),e.jsx(pe,{id:"tone",name:"tone",defaultValue:(i==null?void 0:i.tone)||"",placeholder:"e.g., Friendly, Professional, Casual"})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"script_body",children:"Script Body"}),e.jsx(Rs,{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(Ar,{className:"mt-4",children:[e.jsx($,{type:"button",variant:"outline",onClick:()=>c(!1),children:"Cancel"}),e.jsxs($,{type:"submit",disabled:d.isPending,children:[d.isPending&&e.jsx(kt,{className:"h-4 w-4 mr-2 animate-spin"}),"Save"]})]})]})]})})]})}function TFn({plans:s,actionTypes:t,scripts:n,isLoading:r}){const{toast:a}=Bi(),i=Vt(),[l,o]=j.useState(null),[c,d]=j.useState(!1),[u,h]=j.useState(null),[m,f]=j.useState(!1),[g,x]=j.useState(null),[y,v]=j.useState(null),{data:b}=tt({queryKey:["plan-items",u],queryFn:async()=>{if(!u)return[];const{data:R,error:D}=await q.from("touchpoint_plan_items").select("*").eq("plan_id",u).order("month_number");if(D)throw D;return R},enabled:!!u}),w=ft({mutationFn:async R=>{if(R.id){const{error:D}=await q.from("touchpoint_plans").update({name:R.name,description:R.description,active:R.active}).eq("id",R.id);if(D)throw D}else{const{error:D}=await q.from("touchpoint_plans").insert([{name:R.name,description:R.description,active:!0}]);if(D)throw D}},onSuccess:()=>{i.invalidateQueries({queryKey:["admin-touchpoint-plans"]}),d(!1),o(null),a({title:"Saved successfully"})},onError:R=>{a({title:"Error",description:R.message,variant:"destructive"})}}),S=ft({mutationFn:async R=>{if(R.id){const{error:D}=await q.from("touchpoint_plan_items").update({action_type_id:R.action_type_id,default_script_id:R.default_script_id,notes:R.notes}).eq("id",R.id);if(D)throw D}else{const{error:D}=await q.from("touchpoint_plan_items").insert([{plan_id:R.plan_id,month_number:R.month_number,action_type_id:R.action_type_id,default_script_id:R.default_script_id,notes:R.notes}]);if(D)throw D}},onSuccess:()=>{i.invalidateQueries({queryKey:["plan-items",u]}),a({title:"Item saved"})}}),C=ft({mutationFn:async R=>{const{error:D}=await q.from("touchpoint_plan_items").delete().eq("id",R);if(D)throw D},onSuccess:()=>{i.invalidateQueries({queryKey:["plan-items",u]})}}),E=ft({mutationFn:async R=>{const{data:D,error:O}=await q.from("action_scripts").insert([{...R,active:!0}]).select().single();if(O)throw O;return D},onSuccess:async R=>{i.invalidateQueries({queryKey:["admin-action-scripts"]}),g&&await S.mutateAsync({id:g.itemId,plan_id:u,month_number:g.month,action_type_id:g.actionTypeId,default_script_id:R.id}),f(!1),x(null),a({title:"Script created and assigned"})},onError:R=>{a({title:"Error",description:R.message,variant:"destructive"})}}),I=(R,D,O)=>{x({month:R,actionTypeId:D,itemId:O}),f(!0)},P=R=>n.find(D=>D.id===R);return e.jsxs("div",{className:"space-y-6",children:[e.jsxs(Ne,{children:[e.jsxs(Ct,{className:"flex flex-row items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(At,{children:"Touchpoint Plans"}),e.jsx(Gn,{children:"Create annual touchpoint plans that agents can apply to their contacts"})]}),e.jsxs($,{onClick:()=>{o(null),d(!0)},children:[e.jsx(dn,{className:"h-4 w-4 mr-2"}),"Add Plan"]})]}),e.jsx(Ie,{children:r?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx(kt,{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(R=>e.jsxs(Ne,{className:`cursor-pointer transition-colors ${u===R.id?"border-primary":""}`,onClick:()=>h(R.id),children:[e.jsx(Ct,{className:"pb-2",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(At,{className:"text-base",children:R.name}),e.jsx($,{variant:"ghost",size:"icon",onClick:D=>{D.stopPropagation(),o(R),d(!0)},children:e.jsx(gi,{className:"h-4 w-4"})})]})}),e.jsxs(Ie,{children:[e.jsx("p",{className:"text-sm text-muted-foreground line-clamp-2",children:R.description}),e.jsx(Be,{variant:R.active?"default":"secondary",className:"mt-2",children:R.active?"Active":"Inactive"})]})]},R.id))})})]}),u&&e.jsxs(Ne,{children:[e.jsxs(Ct,{children:[e.jsx(At,{children:"Plan Schedule"}),e.jsx(Gn,{children:"Configure the monthly touchpoint schedule. Select an action type for each month, then assign or create a script."})]}),e.jsx(Ie,{children:e.jsx("div",{className:"grid gap-3",children:Array.from({length:12},(R,D)=>D+1).map(R=>{const D=b==null?void 0:b.find(W=>W.month_number===R),O=D!=null&&D.default_script_id?P(D.default_script_id):null,U=n.filter(W=>W.action_type_id===(D==null?void 0:D.action_type_id)&&W.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 ",R]}),e.jsxs(ms,{value:(D==null?void 0:D.action_type_id)||"none",onValueChange:W=>{W==="none"&&D?C.mutate(D.id):W!=="none"&&S.mutate({id:D==null?void 0:D.id,plan_id:u,month_number:R,action_type_id:W,default_script_id:null})},children:[e.jsx(us,{className:"w-40",children:e.jsx(fs,{placeholder:"No action"})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"none",children:"No action"}),t.filter(W=>W.active).map(W=>e.jsx(Ge,{value:W.id,children:e.jsxs("span",{className:"flex items-center gap-2",children:[W.color&&e.jsx("span",{className:"w-3 h-3 rounded-full",style:{backgroundColor:W.color}}),W.name]})},W.id))]})]}),D&&e.jsxs(e.Fragment,{children:[e.jsxs(ms,{value:D.default_script_id||"none",onValueChange:W=>{v(null),S.mutate({id:D.id,default_script_id:W==="none"?null:W})},children:[e.jsx(us,{className:"w-56",children:e.jsx(fs,{placeholder:"Select script"})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"none",children:"No default script"}),U.map(W=>e.jsxs(Ge,{value:W.id,children:[W.title," ",W.tone&&`(${W.tone})`]},W.id))]})]}),e.jsxs($,{variant:"outline",size:"sm",onClick:()=>I(R,D.action_type_id,D.id),children:[e.jsx(dn,{className:"h-3 w-3 mr-1"}),"New Script"]}),O&&e.jsx($,{variant:"ghost",size:"sm",onClick:()=>v((y==null?void 0:y.id)===O.id?null:O),children:(y==null?void 0:y.id)===O.id?"Hide":"Preview"})]})]}),y&&(D==null?void 0:D.default_script_id)===y.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(Be,{variant:"outline",children:y.title}),y.tone&&e.jsx(Be,{variant:"secondary",children:y.tone})]}),e.jsx("p",{className:"text-muted-foreground whitespace-pre-wrap",children:y.script_body})]})]},R)})})})]}),e.jsx(zs,{open:c,onOpenChange:d,children:e.jsxs(Os,{children:[e.jsx(Us,{children:e.jsxs(Bs,{children:[l?"Edit":"Add"," Touchpoint Plan"]})}),e.jsxs("form",{onSubmit:R=>{R.preventDefault();const D=new FormData(R.currentTarget);w.mutate({id:l==null?void 0:l.id,name:D.get("name"),description:D.get("description"),active:!0})},children:[e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"name",children:"Name"}),e.jsx(pe,{id:"name",name:"name",defaultValue:l==null?void 0:l.name,required:!0})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"description",children:"Description"}),e.jsx(Rs,{id:"description",name:"description",defaultValue:(l==null?void 0:l.description)||"",rows:3})]})]}),e.jsxs(Ar,{className:"mt-4",children:[e.jsx($,{type:"button",variant:"outline",onClick:()=>d(!1),children:"Cancel"}),e.jsxs($,{type:"submit",disabled:w.isPending,children:[w.isPending&&e.jsx(kt,{className:"h-4 w-4 mr-2 animate-spin"}),"Save"]})]})]})]})}),e.jsx(zs,{open:m,onOpenChange:f,children:e.jsxs(Os,{className:"max-w-2xl",children:[e.jsxs(Us,{children:[e.jsx(Bs,{children:"Create New Script"}),e.jsxs(Ir,{children:["Create a script for Month ",g==null?void 0:g.month,". Use ","{{FirstName}}",", ","{{LastName}}",", and ","{{AgentName}}"," as placeholders."]})]}),e.jsxs("form",{onSubmit:R=>{R.preventDefault();const D=new FormData(R.currentTarget);E.mutate({title:D.get("title"),action_type_id:g.actionTypeId,tone:D.get("tone"),script_body:D.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(ee,{htmlFor:"script_title",children:"Title"}),e.jsx(pe,{id:"script_title",name:"title",placeholder:"e.g., Warm Check-In",required:!0})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"script_tone",children:"Tone"}),e.jsx(pe,{id:"script_tone",name:"tone",placeholder:"e.g., Friendly, Professional"})]})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"script_body",children:"Script Body"}),e.jsx(Rs,{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(Ar,{className:"mt-4",children:[e.jsx($,{type:"button",variant:"outline",onClick:()=>f(!1),children:"Cancel"}),e.jsxs($,{type:"submit",disabled:E.isPending,children:[E.isPending&&e.jsx(kt,{className:"h-4 w-4 mr-2 animate-spin"}),"Create & Assign"]})]})]})]})})]})}function MFn({flags:s}){const{toast:t}=Bi(),n=Vt(),r=async(a,i)=>{const{error:l}=await q.from("feature_flags").update({...i,updated_at:new Date().toISOString()}).eq("id",a.id);l?t({title:"Error",description:l.message,variant:"destructive"}):(n.invalidateQueries({queryKey:["admin-feature-flags"]}),t({title:"Flag updated"}))};return e.jsxs(Ne,{children:[e.jsxs(Ct,{children:[e.jsx(At,{children:"Feature Flags"}),e.jsx(Gn,{children:"Control which features are enabled for members"})]}),e.jsx(Ie,{children:e.jsxs(mi,{children:[e.jsx(fi,{children:e.jsxs(En,{children:[e.jsx(Dt,{children:"Flag"}),e.jsx(Dt,{children:"Status"}),e.jsx(Dt,{children:"Notes"}),e.jsx(Dt,{children:"Last Updated"})]})}),e.jsx(pi,{children:s.map(a=>e.jsxs(En,{children:[e.jsx(wt,{className:"font-mono text-sm",children:a.key}),e.jsx(wt,{children:e.jsx(Sn,{checked:a.enabled,onCheckedChange:i=>r(a,{enabled:i})})}),e.jsx(wt,{children:e.jsx(pe,{defaultValue:a.notes||"",placeholder:"Add notes...",className:"max-w-xs",onBlur:i=>{i.target.value!==a.notes&&r(a,{notes:i.target.value})}})}),e.jsx(wt,{className:"text-muted-foreground text-sm",children:new Date(a.updated_at).toLocaleDateString()})]},a.id))})]})})]})}function PFn({items:s,isLoading:t}){const{toast:n}=Bi(),r=Vt(),[a,i]=j.useState(null),[l,o]=j.useState(!1),c=ft({mutationFn:async h=>{if(h.id){const{error:m}=await q.from("popby_items").update({name:h.name,description:h.description}).eq("id",h.id);if(m)throw m}else{const{error:m}=await q.from("popby_items").insert([{name:h.name,description:h.description,owner_user_id:null}]);if(m)throw m}},onSuccess:()=>{r.invalidateQueries({queryKey:["admin-popby-items"]}),r.invalidateQueries({queryKey:["popby-items"]}),o(!1),i(null),n({title:"Saved successfully"})},onError:h=>{n({title:"Error",description:h.message,variant:"destructive"})}}),d=async h=>{await q.from("popby_items").update({is_active:!h.is_active}).eq("id",h.id),r.invalidateQueries({queryKey:["admin-popby-items"]}),r.invalidateQueries({queryKey:["popby-items"]})},u=async h=>{await q.from("popby_items").delete().eq("id",h),r.invalidateQueries({queryKey:["admin-popby-items"]}),r.invalidateQueries({queryKey:["popby-items"]}),n({title:"Deleted successfully"})};return e.jsxs(Ne,{children:[e.jsxs(Ct,{className:"flex flex-row items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(At,{children:"Popby Ideas"}),e.jsx(Gn,{children:"Manage global popby ideas that all agents can see"})]}),e.jsxs($,{onClick:()=>{i(null),o(!0)},children:[e.jsx(dn,{className:"h-4 w-4 mr-2"}),"Add Popby Idea"]})]}),e.jsx(Ie,{children:t?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx(kt,{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(ul,{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(mi,{children:[e.jsx(fi,{children:e.jsxs(En,{children:[e.jsx(Dt,{children:"Name"}),e.jsx(Dt,{children:"Description"}),e.jsx(Dt,{children:"Status"}),e.jsx(Dt,{className:"w-24",children:"Actions"})]})}),e.jsx(pi,{children:s.map(h=>e.jsxs(En,{children:[e.jsx(wt,{className:"font-medium",children:h.name}),e.jsx(wt,{className:"text-muted-foreground",children:h.description}),e.jsx(wt,{children:e.jsx(Sn,{checked:h.is_active,onCheckedChange:()=>d(h)})}),e.jsx(wt,{children:e.jsxs("div",{className:"flex gap-1",children:[e.jsx($,{variant:"ghost",size:"icon",onClick:()=>{i(h),o(!0)},children:e.jsx(gi,{className:"h-4 w-4"})}),e.jsx($,{variant:"ghost",size:"icon",onClick:()=>u(h.id),children:e.jsx(Wn,{className:"h-4 w-4 text-destructive"})})]})})]},h.id))})]})}),e.jsx(zs,{open:l,onOpenChange:o,children:e.jsxs(Os,{children:[e.jsx(Us,{children:e.jsxs(Bs,{children:[a?"Edit":"Add"," Popby Idea"]})}),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")})},children:[e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"name",children:"Name"}),e.jsx(pe,{id:"name",name:"name",defaultValue:a==null?void 0:a.name,required:!0,placeholder:"e.g., Homemade Cookies"})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"description",children:"Description"}),e.jsx(Rs,{id:"description",name:"description",defaultValue:(a==null?void 0:a.description)||"",placeholder:"Brief description of the popby idea..."})]})]}),e.jsxs(Ar,{className:"mt-4",children:[e.jsx($,{type:"button",variant:"outline",onClick:()=>o(!1),children:"Cancel"}),e.jsxs($,{type:"submit",disabled:c.isPending,children:[c.isPending&&e.jsx(kt,{className:"h-4 w-4 mr-2 animate-spin"}),"Save"]})]})]})]})})]})}function IFn(){var f;const{toast:s}=Bi(),t=Vt(),[n,r]=j.useState(null),[a,i]=j.useState(!1),{data:l,isLoading:o}=tt({queryKey:["admin-video-script-categories"],queryFn:async()=>{const{data:g,error:x}=await q.from("video_script_categories").select("*").order("sort_order");if(x)throw x;return g}}),{data:c,isLoading:d}=tt({queryKey:["admin-video-scripts"],queryFn:async()=>{const{data:g,error:x}=await q.from("video_scripts").select("*, category:video_script_categories(*)").order("title");if(x)throw x;return g}}),u=ft({mutationFn:async g=>{var x,y;if(g.id){const{error:v}=await q.from("video_scripts").update({title:g.title,script_text:g.script_text,category_id:g.category_id,tags:((x=g.tags)==null?void 0:x.split(",").map(b=>b.trim()).filter(Boolean))||[]}).eq("id",g.id);if(v)throw v}else{const{error:v}=await q.from("video_scripts").insert([{title:g.title,script_text:g.script_text,category_id:g.category_id||null,tags:((y=g.tags)==null?void 0:y.split(",").map(b=>b.trim()).filter(Boolean))||[]}]);if(v)throw v}},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-video-scripts"]}),i(!1),r(null),s({title:"Video script saved!"})},onError:g=>s({title:"Error",description:g.message,variant:"destructive"})}),h=async g=>{await q.from("video_scripts").update({is_active:!g.is_active}).eq("id",g.id),t.invalidateQueries({queryKey:["admin-video-scripts"]})},m=async g=>{await fo("Delete this video script?")&&(await q.from("video_scripts").delete().eq("id",g),t.invalidateQueries({queryKey:["admin-video-scripts"]}),s({title:"Script deleted"}))};return e.jsxs(Ne,{children:[e.jsxs(Ct,{className:"flex flex-row items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(At,{children:"Video Scripts"}),e.jsx(Gn,{children:"Manage teleprompter scripts for Quick Video Touch"})]}),e.jsxs($,{onClick:()=>{r(null),i(!0)},children:[e.jsx(dn,{className:"h-4 w-4 mr-2"}),"Add Script"]})]}),e.jsx(Ie,{children:d?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx(kt,{className:"h-8 w-8 animate-spin text-muted-foreground"})}):e.jsxs(mi,{children:[e.jsx(fi,{children:e.jsxs(En,{children:[e.jsx(Dt,{children:"Title"}),e.jsx(Dt,{children:"Category"}),e.jsx(Dt,{children:"Status"}),e.jsx(Dt,{className:"w-24",children:"Actions"})]})}),e.jsx(pi,{children:c==null?void 0:c.map(g=>{var x;return e.jsxs(En,{children:[e.jsx(wt,{className:"font-medium",children:g.title}),e.jsx(wt,{className:"text-muted-foreground",children:((x=g.category)==null?void 0:x.name)||"Uncategorized"}),e.jsx(wt,{children:e.jsx(Sn,{checked:g.is_active,onCheckedChange:()=>h(g)})}),e.jsxs(wt,{className:"flex gap-1",children:[e.jsx($,{variant:"ghost",size:"icon",onClick:()=>{r(g),i(!0)},children:e.jsx(gi,{className:"h-4 w-4"})}),e.jsx($,{variant:"ghost",size:"icon",onClick:()=>m(g.id),children:e.jsx(Wn,{className:"h-4 w-4"})})]})]},g.id)})})]})}),e.jsx(zs,{open:a,onOpenChange:i,children:e.jsxs(Os,{className:"max-w-2xl",children:[e.jsx(Us,{children:e.jsxs(Bs,{children:[n?"Edit":"Add"," Video Script"]})}),e.jsxs("form",{onSubmit:g=>{g.preventDefault();const x=new FormData(g.currentTarget);u.mutate({id:n==null?void 0:n.id,title:x.get("title"),script_text:x.get("script_text"),category_id:x.get("category_id")||null,tags:x.get("tags")})},children:[e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"title",children:"Title"}),e.jsx(pe,{id:"title",name:"title",defaultValue:n==null?void 0:n.title,required:!0})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"category_id",children:"Category"}),e.jsxs(ms,{name:"category_id",defaultValue:(n==null?void 0:n.category_id)||"",children:[e.jsx(us,{children:e.jsx(fs,{placeholder:"Select category"})}),e.jsx(hs,{children:l==null?void 0:l.map(g=>e.jsx(Ge,{value:g.id,children:g.name},g.id))})]})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"script_text",children:"Script Text"}),e.jsx(Rs,{id:"script_text",name:"script_text",defaultValue:n==null?void 0:n.script_text,rows:6,required:!0,placeholder:"Enter the teleprompter script..."})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"tags",children:"Tags (comma-separated)"}),e.jsx(pe,{id:"tags",name:"tags",defaultValue:((f=n==null?void 0:n.tags)==null?void 0:f.join(", "))||"",placeholder:"birthday, follow-up, thank-you"})]})]}),e.jsxs(Ar,{className:"mt-4",children:[e.jsx($,{type:"button",variant:"outline",onClick:()=>i(!1),children:"Cancel"}),e.jsxs($,{type:"submit",disabled:u.isPending,children:[u.isPending&&e.jsx(kt,{className:"h-4 w-4 mr-2 animate-spin"}),"Save"]})]})]})]})})]})}function LFn(){const{toast:s}=Bi(),[t,n]=j.useState(""),[r,a]=j.useState(!0),[i,l]=j.useState(!1);j.useEffect(()=>{(async()=>{a(!0);try{const{data:d}=await q.from("settings").select("value").eq("key","mapbox_public_token").maybeSingle();d!=null&&d.value&&n(d.value)}catch(d){console.error("Error fetching settings:",d)}a(!1)})()},[]);const o=async()=>{l(!0);try{await q.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 r?e.jsx(Ne,{children:e.jsx(Ie,{className:"flex justify-center py-8",children:e.jsx(kt,{className:"h-8 w-8 animate-spin text-muted-foreground"})})}):e.jsx("div",{className:"space-y-6",children:e.jsxs(Ne,{children:[e.jsxs(Ct,{children:[e.jsxs(At,{className:"flex items-center gap-2",children:[e.jsx(ci,{className:"h-5 w-5"}),"Popby Map Settings"]}),e.jsx(Gn,{children:"Configure the map feature for popbys"})]}),e.jsxs(Ie,{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"mapbox-token",children:"Mapbox Public Token"}),e.jsx(pe,{id:"mapbox-token",placeholder:"pk.eyJ1I...",value:t,onChange:c=>n(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($,{onClick:o,disabled:i,children:[i&&e.jsx(kt,{className:"h-4 w-4 mr-2 animate-spin"}),"Save Token"]}),t&&e.jsx(Be,{variant:"secondary",className:"ml-2",children:"Token configured"})]})]})})}const RFn=()=>{const[s,t]=j.useState(""),[n,r]=j.useState("grid"),a=Qn(),{data:i=[],isLoading:l}=tt({queryKey:["additional-services"],queryFn:async()=>{const{data:c,error:d}=await q.from("additional_services").select("*").eq("is_published",!0).order("publish_date",{ascending:!1});if(d)throw d;return c}}),o=i.filter(c=>{var u;return c.name.toLowerCase().includes(s.toLowerCase())||((u=c.description)==null?void 0:u.toLowerCase().includes(s.toLowerCase()))});return e.jsx(Vs,{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(Kr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(pe,{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($,{variant:"outline",size:"sm",onClick:()=>t(""),children:"Clear"}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx($,{variant:n==="grid"?"secondary":"outline",size:"icon",onClick:()=>r("grid"),className:"rounded-full",children:e.jsx(Qf,{className:"h-4 w-4"})}),e.jsx($,{variant:n==="list"?"secondary":"outline",size:"icon",onClick:()=>r("list"),className:"rounded-full",children:e.jsx(P0,{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: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(4)].map((c,d)=>e.jsx(Ne,{children:e.jsxs(Ie,{className:"p-4",children:[e.jsx(yn,{className:"aspect-[3/2] w-full rounded-lg mb-4"}),e.jsx(yn,{className:"h-5 w-3/4 mb-2"}),e.jsx(yn,{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($,{variant:"outline",onClick:()=>t(""),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(c=>e.jsxs(Ne,{className:`group overflow-hidden hover:shadow-lg transition-all duration-200 cursor-pointer ${n==="list"?"flex flex-row":""}`,onClick:()=>a(`/additional-services/${c.id}`),children:[e.jsx("div",{className:`relative overflow-hidden bg-muted ${n==="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(Nn,{className:"h-8 w-8"})})}),e.jsxs(Ie,{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:c.name}),c.description&&e.jsx("p",{className:"text-sm text-muted-foreground line-clamp-2 flex-1",children:Vte(c.description)})]})]},c.id))})]})})},DFn=()=>{const{serviceId:s}=Wi(),t=Qn(),{data:n,isLoading:r}=tt({queryKey:["additional-service",s],queryFn:async()=>{const{data:a,error:i}=await q.from("additional_services").select("*").eq("id",s).eq("is_published",!0).single();if(i)throw i;return a},enabled:!!s});return r?e.jsx(Vs,{title:"Loading...",children:e.jsxs("div",{className:"max-w-4xl mx-auto space-y-6",children:[e.jsx(yn,{className:"h-8 w-48"}),e.jsx(yn,{className:"h-64 w-full rounded-lg"}),e.jsx(yn,{className:"h-24 w-full"})]})}):n?e.jsx(Vs,{title:n.name,children:e.jsxs("div",{className:"max-w-4xl mx-auto space-y-6",children:[e.jsxs($,{variant:"ghost",onClick:()=>t("/additional-services"),className:"gap-2",children:[e.jsx(qa,{className:"h-4 w-4"}),"Back to Services"]}),e.jsx(Ne,{className:"overflow-hidden",children:e.jsx("div",{className:"relative bg-muted",children:n.preview_image_url?e.jsx("img",{src:n.preview_image_url,alt:n.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(Nn,{className:"h-16 w-16"})})})}),e.jsx(Ne,{children:e.jsxs(Ie,{className:"p-6 space-y-6",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold text-foreground mb-2",children:n.name}),e.jsxs("div",{className:"flex items-center text-sm text-muted-foreground",children:[e.jsx(Ta,{className:"h-4 w-4 mr-1"}),"Published ",en(new Date(n.publish_date),"MMMM d, yyyy")]})]}),n.description&&e.jsx("div",{className:"prose prose-sm max-w-none text-muted-foreground [&_a]:text-primary [&_a]:underline",dangerouslySetInnerHTML:{__html:n.description}}),e.jsx("div",{className:"pt-4 border-t",children:e.jsxs($,{size:"lg",className:"gap-2",onClick:()=>window.open(n.signup_link_url,"_blank"),children:[e.jsx(kr,{className:"h-5 w-5"}),"Sign Up Now"]})})]})})]})}):e.jsx(Vs,{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($,{onClick:()=>t("/additional-services"),children:[e.jsx(qa,{className:"h-4 w-4 mr-2"}),"Back to Services"]})]})})},rX=[{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 FFn(){const[s,t]=j.useState(rX[0].id),n=rX.find(r=>r.id===s)||rX[0];return e.jsx(Vs,{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(M4,{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(ms,{value:s,onValueChange:t,children:[e.jsx(us,{className:"w-full",children:e.jsx(fs,{placeholder:"Select a tool"})}),e.jsx(hs,{children:rX.map(r=>e.jsx(Ge,{value:r.id,children:r.name},r.id))})]})}),e.jsx("div",{className:"hidden md:block",children:e.jsx(ha,{value:s,onValueChange:t,className:"w-full",children:e.jsx(ma,{className:"w-full flex-wrap h-auto gap-1 bg-muted p-1",children:rX.map(r=>e.jsx(Zt,{value:r.id,className:"flex-1 min-w-[150px] text-xs lg:text-sm whitespace-normal h-auto py-2",children:r.name},r.id))})})}),e.jsx("div",{className:"flex justify-center",children:e.jsx("div",{className:"w-full max-w-[700px]",dangerouslySetInnerHTML:{__html:n.iframe}})})]})})}function OFn(s,t){const n={};return(s[s.length-1]===""?[...s,""]:s).join((n.padRight?" ":"")+","+(n.padLeft===!1?"":" ")).trim()}const zFn=/^[$_\p{ID_Start}][$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,BFn=/^[$_\p{ID_Start}][-$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,$Fn={};function gSt(s,t){return($Fn.jsx?BFn:zFn).test(s)}const UFn=/[ \t\n\f\r]/g;function qFn(s){return typeof s=="object"?s.type==="text"?xSt(s.value):!1:xSt(s)}function xSt(s){return s.replace(UFn,"")===""}class Rie{constructor(t,n,r){this.normal=n,this.property=t,r&&(this.space=r)}}Rie.prototype.normal={};Rie.prototype.property={};Rie.prototype.space=void 0;function ZXt(s,t){const n={},r={};for(const a of s)Object.assign(n,a.property),Object.assign(r,a.normal);return new Rie(n,r,t)}function kYe(s){return s.toLowerCase()}class Xw{constructor(t,n){this.attribute=n,this.property=t}}Xw.prototype.attribute="";Xw.prototype.booleanish=!1;Xw.prototype.boolean=!1;Xw.prototype.commaOrSpaceSeparated=!1;Xw.prototype.commaSeparated=!1;Xw.prototype.defined=!1;Xw.prototype.mustUseProperty=!1;Xw.prototype.number=!1;Xw.prototype.overloadedBoolean=!1;Xw.prototype.property="";Xw.prototype.spaceSeparated=!1;Xw.prototype.space=void 0;let VFn=0;const sd=i9(),Iy=i9(),SYe=i9(),wi=i9(),bf=i9(),k7=i9(),Tj=i9();function i9(){return 2**++VFn}const CYe=Object.freeze(Object.defineProperty({__proto__:null,boolean:sd,booleanish:Iy,commaOrSpaceSeparated:Tj,commaSeparated:k7,number:wi,overloadedBoolean:SYe,spaceSeparated:bf},Symbol.toStringTag,{value:"Module"})),B9e=Object.keys(CYe);class oit extends Xw{constructor(t,n,r,a){let i=-1;if(super(t,n),ySt(this,"space",a),typeof r=="number")for(;++i4&&n.slice(0,4)==="data"&&YFn.test(t)){if(t.charAt(4)==="-"){const i=t.slice(5).replace(vSt,QFn);r="data"+i.charAt(0).toUpperCase()+i.slice(1)}else{const i=t.slice(4);if(!vSt.test(i)){let l=i.replace(KFn,XFn);l.charAt(0)!=="-"&&(l="-"+l),t="data"+l}}a=oit}return new a(r,t)}function XFn(s){return"-"+s.toLowerCase()}function QFn(s){return s.charAt(1).toUpperCase()}const JFn=ZXt([XXt,HFn,eQt,tQt,sQt],"html"),lit=ZXt([XXt,GFn,eQt,tQt,sQt],"svg");function eOn(s){return s.join(" ").trim()}var cit={},bSt=/\/\*[^*]*\*+([^/*][^*]*\*+)*\//g,tOn=/\n/g,sOn=/^\s*/,nOn=/^(\*?[-#/*\\\w]+(\[[0-9a-z_-]+\])?)\s*/,rOn=/^:\s*/,aOn=/^((?:'(?:\\'|.)*?'|"(?:\\"|.)*?"|\([^)]*?\)|[^};])+)/,iOn=/^[;\s]*/,oOn=/^\s+|\s+$/g,lOn=` `,_St="/",wSt="*",e8="",cOn="comment",dOn="declaration";function uOn(s,t){if(typeof s!="string")throw new TypeError("First argument must be a string");if(!s)return[];t=t||{};var n=1,r=1;function a(g){var x=g.match(tOn);x&&(n+=x.length);var y=g.lastIndexOf(lOn);r=~y?g.length-y:r+g.length}function i(){var g={line:n,column:r};return function(x){return x.position=new l(g),d(),x}}function l(g){this.start=g,this.end={line:n,column:r},this.source=t.source}l.prototype.content=s;function o(g){var x=new Error(t.source+":"+n+":"+r+": "+g);if(x.reason=g,x.filename=t.source,x.line=n,x.column=r,x.source=s,!t.silent)throw x}function c(g){var x=g.exec(s);if(x){var y=x[0];return a(y),s=s.slice(y.length),x}}function d(){c(sOn)}function u(g){var x;for(g=g||[];x=h();)x!==!1&&g.push(x);return g}function h(){var g=i();if(!(_St!=s.charAt(0)||wSt!=s.charAt(1))){for(var x=2;e8!=s.charAt(x)&&(wSt!=s.charAt(x)||_St!=s.charAt(x+1));)++x;if(x+=2,e8===s.charAt(x-1))return o("End of comment missing");var y=s.slice(2,x-2);return r+=2,a(y),s=s.slice(x),r+=2,g({type:cOn,comment:y})}}function m(){var g=i(),x=c(nOn);if(x){if(h(),!c(rOn))return o("property missing ':'");var y=c(aOn),v=g({type:dOn,property:jSt(x[0].replace(bSt,e8)),value:y?jSt(y[0].replace(bSt,e8)):e8});return c(iOn),v}}function f(){var g=[];u(g);for(var x;x=m();)x!==!1&&(g.push(x),u(g));return g}return d(),f()}function jSt(s){return s?s.replace(oOn,e8):e8}var hOn=uOn,mOn=Sp&&Sp.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(cit,"__esModule",{value:!0});cit.default=pOn;const fOn=mOn(hOn);function pOn(s,t){let n=null;if(!s||typeof s!="string")return n;const r=(0,fOn.default)(s),a=typeof t=="function";return r.forEach(i=>{if(i.type!=="declaration")return;const{property:l,value:o}=i;a?t(l,o,i):o&&(n=n||{},n[l]=o)}),n}var rDe={};Object.defineProperty(rDe,"__esModule",{value:!0});rDe.camelCase=void 0;var gOn=/^--[a-zA-Z0-9_-]+$/,xOn=/-([a-z])/g,yOn=/^[^-]+$/,vOn=/^-(webkit|moz|ms|o|khtml)-/,bOn=/^-(ms)-/,_On=function(s){return!s||yOn.test(s)||gOn.test(s)},wOn=function(s,t){return t.toUpperCase()},NSt=function(s,t){return"".concat(t,"-")},jOn=function(s,t){return t===void 0&&(t={}),_On(s)?s:(s=s.toLowerCase(),t.reactCompat?s=s.replace(bOn,NSt):s=s.replace(vOn,NSt),s.replace(xOn,wOn))};rDe.camelCase=jOn;var NOn=Sp&&Sp.__importDefault||function(s){return s&&s.__esModule?s:{default:s}},kOn=NOn(cit),SOn=rDe;function AYe(s,t){var n={};return!s||typeof s!="string"||(0,kOn.default)(s,function(r,a){r&&a&&(n[(0,SOn.camelCase)(r,t)]=a)}),n}AYe.default=AYe;var COn=AYe;const AOn=au(COn),nQt=rQt("end"),dit=rQt("start");function rQt(s){return t;function t(n){const r=n&&n.position&&n.position[s]||{};if(typeof r.line=="number"&&r.line>0&&typeof r.column=="number"&&r.column>0)return{line:r.line,column:r.column,offset:typeof r.offset=="number"&&r.offset>-1?r.offset:void 0}}}function EOn(s){const t=dit(s),n=nQt(s);if(t&&n)return{start:t,end:n}}function Qee(s){return!s||typeof s!="object"?"":"position"in s||"type"in s?kSt(s.position):"start"in s||"end"in s?kSt(s):"line"in s||"column"in s?EYe(s):""}function EYe(s){return SSt(s&&s.line)+":"+SSt(s&&s.column)}function kSt(s){return EYe(s&&s.start)+"-"+EYe(s&&s.end)}function SSt(s){return s&&typeof s=="number"?s:1}class L1 extends Error{constructor(t,n,r){super(),typeof n=="string"&&(r=n,n=void 0);let a="",i={},l=!1;if(n&&("line"in n&&"column"in n?i={place:n}:"start"in n&&"end"in n?i={place:n}:"type"in n?i={ancestors:[n],place:n.position}:i={...n}),typeof t=="string"?a=t:!i.cause&&t&&(l=!0,a=t.message,i.cause=t),!i.ruleId&&!i.source&&typeof r=="string"){const c=r.indexOf(":");c===-1?i.ruleId=r:(i.source=r.slice(0,c),i.ruleId=r.slice(c+1))}if(!i.place&&i.ancestors&&i.ancestors){const c=i.ancestors[i.ancestors.length-1];c&&(i.place=c.position)}const o=i.place&&"start"in i.place?i.place.start:i.place;this.ancestors=i.ancestors||void 0,this.cause=i.cause||void 0,this.column=o?o.column:void 0,this.fatal=void 0,this.file="",this.message=a,this.line=o?o.line:void 0,this.name=Qee(i.place)||"1:1",this.place=i.place||void 0,this.reason=this.message,this.ruleId=i.ruleId||void 0,this.source=i.source||void 0,this.stack=l&&i.cause&&typeof i.cause.stack=="string"?i.cause.stack:"",this.actual=void 0,this.expected=void 0,this.note=void 0,this.url=void 0}}L1.prototype.file="";L1.prototype.name="";L1.prototype.reason="";L1.prototype.message="";L1.prototype.stack="";L1.prototype.column=void 0;L1.prototype.line=void 0;L1.prototype.ancestors=void 0;L1.prototype.cause=void 0;L1.prototype.fatal=void 0;L1.prototype.place=void 0;L1.prototype.ruleId=void 0;L1.prototype.source=void 0;const uit={}.hasOwnProperty,TOn=new Map,MOn=/[A-Z]/g,POn=new Set(["table","tbody","thead","tfoot","tr"]),IOn=new Set(["td","th"]),aQt="https://github.com/syntax-tree/hast-util-to-jsx-runtime";function LOn(s,t){if(!t||t.Fragment===void 0)throw new TypeError("Expected `Fragment` in options");const n=t.filePath||void 0;let r;if(t.development){if(typeof t.jsxDEV!="function")throw new TypeError("Expected `jsxDEV` in options when `development: true`");r=UOn(n,t.jsxDEV)}else{if(typeof t.jsx!="function")throw new TypeError("Expected `jsx` in production options");if(typeof t.jsxs!="function")throw new TypeError("Expected `jsxs` in production options");r=$On(n,t.jsx,t.jsxs)}const a={Fragment:t.Fragment,ancestors:[],components:t.components||{},create:r,elementAttributeNameCase:t.elementAttributeNameCase||"react",evaluater:t.createEvaluater?t.createEvaluater():void 0,filePath:n,ignoreInvalidStyle:t.ignoreInvalidStyle||!1,passKeys:t.passKeys!==!1,passNode:t.passNode||!1,schema:t.space==="svg"?lit:JFn,stylePropertyNameCase:t.stylePropertyNameCase||"dom",tableCellAlignToStyle:t.tableCellAlignToStyle!==!1},i=iQt(a,s,void 0);return i&&typeof i!="string"?i:a.create(s,a.Fragment,{children:i||void 0},void 0)}function iQt(s,t,n){if(t.type==="element")return ROn(s,t,n);if(t.type==="mdxFlowExpression"||t.type==="mdxTextExpression")return DOn(s,t);if(t.type==="mdxJsxFlowElement"||t.type==="mdxJsxTextElement")return OOn(s,t,n);if(t.type==="mdxjsEsm")return FOn(s,t);if(t.type==="root")return zOn(s,t,n);if(t.type==="text")return BOn(s,t)}function ROn(s,t,n){const r=s.schema;let a=r;t.tagName.toLowerCase()==="svg"&&r.space==="html"&&(a=lit,s.schema=a),s.ancestors.push(t);const i=lQt(s,t.tagName,!1),l=qOn(s,t);let o=mit(s,t);return POn.has(t.tagName)&&(o=o.filter(function(c){return typeof c=="string"?!qFn(c):!0})),oQt(s,l,i,t),hit(l,o),s.ancestors.pop(),s.schema=r,s.create(t,i,l,n)}function DOn(s,t){if(t.data&&t.data.estree&&s.evaluater){const r=t.data.estree.body[0];return r.type,s.evaluater.evaluateExpression(r.expression)}pne(s,t.position)}function FOn(s,t){if(t.data&&t.data.estree&&s.evaluater)return s.evaluater.evaluateProgram(t.data.estree);pne(s,t.position)}function OOn(s,t,n){const r=s.schema;let a=r;t.name==="svg"&&r.space==="html"&&(a=lit,s.schema=a),s.ancestors.push(t);const i=t.name===null?s.Fragment:lQt(s,t.name,!0),l=VOn(s,t),o=mit(s,t);return oQt(s,l,i,t),hit(l,o),s.ancestors.pop(),s.schema=r,s.create(t,i,l,n)}function zOn(s,t,n){const r={};return hit(r,mit(s,t)),s.create(t,s.Fragment,r,n)}function BOn(s,t){return t.value}function oQt(s,t,n,r){typeof n!="string"&&n!==s.Fragment&&s.passNode&&(t.node=r)}function hit(s,t){if(t.length>0){const n=t.length>1?t:t[0];n&&(s.children=n)}}function $On(s,t,n){return r;function r(a,i,l,o){const d=Array.isArray(l.children)?n:t;return o?d(i,l,o):d(i,l)}}function UOn(s,t){return n;function n(r,a,i,l){const o=Array.isArray(i.children),c=dit(r);return t(a,i,l,o,{columnNumber:c?c.column-1:void 0,fileName:s,lineNumber:c?c.line:void 0},void 0)}}function qOn(s,t){const n={};let r,a;for(a in t.properties)if(a!=="children"&&uit.call(t.properties,a)){const i=HOn(s,a,t.properties[a]);if(i){const[l,o]=i;s.tableCellAlignToStyle&&l==="align"&&typeof o=="string"&&IOn.has(t.tagName)?r=o:n[l]=o}}if(r){const i=n.style||(n.style={});i[s.stylePropertyNameCase==="css"?"text-align":"textAlign"]=r}return n}function VOn(s,t){const n={};for(const r of t.attributes)if(r.type==="mdxJsxExpressionAttribute")if(r.data&&r.data.estree&&s.evaluater){const i=r.data.estree.body[0];i.type;const l=i.expression;l.type;const o=l.properties[0];o.type,Object.assign(n,s.evaluater.evaluateExpression(o.argument))}else pne(s,t.position);else{const a=r.name;let i;if(r.value&&typeof r.value=="object")if(r.value.data&&r.value.data.estree&&s.evaluater){const o=r.value.data.estree.body[0];o.type,i=s.evaluater.evaluateExpression(o.expression)}else pne(s,t.position);else i=r.value===null?!0:r.value;n[a]=i}return n}function mit(s,t){const n=[];let r=-1;const a=s.passKeys?new Map:TOn;for(;++ra?0:a+t:t=t>a?a:t,n=n>0?n:0,r.length<1e4)l=Array.from(r),l.unshift(t,n),s.splice(...l);else for(n&&s.splice(t,n);i0?(T6(s,s.length,0,t),s):t}const ESt={}.hasOwnProperty;function JOn(s){const t={};let n=-1;for(;++n13&&n<32||n>126&&n<160||n>55295&&n<57344||n>64975&&n<65008||(n&65535)===65535||(n&65535)===65534||n>1114111?"�":String.fromCodePoint(n)}function LV(s){return s.replace(/[\t\n\r ]+/g," ").replace(/^ | $/g,"").toLowerCase().toUpperCase()}const h4=M6(/[A-Za-z]/),s2=M6(/[\dA-Za-z]/),s8n=M6(/[#-'*+\--9=?A-Z^-~]/);function TYe(s){return s!==null&&(s<32||s===127)}const MYe=M6(/\d/),n8n=M6(/[\dA-Fa-f]/),r8n=M6(/[!-/:-@[-`{-~]/);function Hc(s){return s!==null&&s<-2}function Bw(s){return s!==null&&(s<0||s===32)}function kh(s){return s===-2||s===-1||s===32}const a8n=M6(new RegExp("\\p{P}|\\p{S}","u")),i8n=M6(/\s/);function M6(s){return t;function t(n){return n!==null&&n>-1&&s.test(String.fromCharCode(n))}}function BK(s){const t=[];let n=-1,r=0,a=0;for(;++n55295&&i<57344){const o=s.charCodeAt(n+1);i<56320&&o>56319&&o<57344?(l=String.fromCharCode(i,o),a=1):l="�"}else l=String.fromCharCode(i);l&&(t.push(s.slice(r,n),encodeURIComponent(l)),r=n+a+1,l=""),a&&(n+=a,a=0)}return t.join("")+s.slice(r)}function Zp(s,t,n,r){const a=r?r-1:1/0;let i=0;return l;function l(c){return kh(c)?(s.enter(n),o(c)):t(c)}function o(c){return kh(c)&&i++=a?t(u):n(u)}}const o8n={tokenize:l8n};function l8n(s){const t=s.attempt(this.parser.constructs.contentInitial,r,a);let n;return t;function r(o){if(o===null){s.consume(o);return}return s.enter("lineEnding"),s.consume(o),s.exit("lineEnding"),Zp(s,t,"linePrefix")}function a(o){return s.enter("paragraph"),i(o)}function i(o){const c=s.enter("chunkText",{contentType:"text",previous:n});return n&&(n.next=c),n=c,l(o)}function l(o){if(o===null){s.exit("chunkText"),s.exit("paragraph"),s.consume(o);return}return Hc(o)?(s.consume(o),s.exit("chunkText"),i):(s.consume(o),l)}}class XMe{constructor(){this.index=new Map,this.map=[]}add(t,n,r){TSt(this,t,n,r,!1)}addBefore(t,n,r){TSt(this,t,n,r,!0)}consume(t){if(this.map.sort(function(i,l){return i[0]-l[0]}),this.map.length===0)return;let n=this.map.length;const r=[];for(;n>0;)n-=1,r.push(t.slice(this.map[n][0]+this.map[n][1]),this.map[n][2]),t.length=this.map[n][0];r.push(t.slice()),t.length=0;let a=r.pop();for(;a;){for(const i of a)t.push(i);a=r.pop()}this.map.length=0,this.index.clear()}}function TSt(s,t,n,r,a){if(n===0&&r.length===0)return;const i=s.index.get(t);if(i){i[1]+=n,a?(r.push(...i[2]),i[2]=r):i[2].push(...r);return}const l=[t,n,r];s.map.push(l),s.index.set(t,l)}const c8n={tokenize:d8n},MSt={tokenize:u8n};function d8n(s){const t=this,n=[];let r=0,a,i,l;return o;function o(w){if(rl))return;const I=t.events.length;let P=I,R,D;for(;P--;)if(t.events[P][0]==="exit"&&t.events[P][1].type==="chunkFlow"){if(R){D=t.events[P][1].end;break}R=!0}for(v(r),E=I;Ew;){const C=n[S];t.containerState=C[1],C[0].exit.call(t,s)}n.length=w}function b(){a.write([null]),i=void 0,a=void 0,t.containerState._closeFlow=void 0}}function u8n(s,t,n){return Zp(s,s.attempt(this.parser.constructs.document,t,n),"linePrefix",this.parser.constructs.disable.null.includes("codeIndented")?void 0:4)}function PSt(s){if(s===null||Bw(s)||i8n(s))return 1;if(a8n(s))return 2}function pit(s,t,n){const r=[];let a=-1;for(;++a1&&s[n][1].end.offset-s[n][1].start.offset>1?2:1,l={...s[a][1].end},o={...s[n][1].start};ISt(l,-i),ISt(o,i);const c={type:i>1?"strongSequence":"emphasisSequence",start:l,end:{...s[a][1].end}},d={type:i>1?"strongSequence":"emphasisSequence",start:{...s[n][1].start},end:o},u={type:i>1?"strongText":"emphasisText",start:{...s[a][1].end},end:{...s[n][1].start}},h={type:i>1?"strong":"emphasis",start:{...c.start},end:{...d.end}};s[a][1].end={...c.start},s[n][1].start={...d.end},r=[],s[a][1].end.offset-s[a][1].start.offset&&(r=RN(r,[["enter",s[a][1],t],["exit",s[a][1],t]])),r=RN(r,[["enter",h,t],["enter",c,t],["exit",c,t],["enter",u,t]]),r=RN(r,pit(t.parser.constructs.insideSpan.null,s.slice(a+1,n),t)),r=RN(r,[["exit",u,t],["enter",d,t],["exit",d,t],["exit",h,t]]);let m=0;s[n][1].end.offset-s[n][1].start.offset&&(m=2,r=RN(r,[["enter",s[n][1],t],["exit",s[n][1],t]])),T6(s,a-1,n-a+3,r),n=a+r.length-m-2;break}}for(n=-1;++n0&&kh(E)?Zp(s,b,"linePrefix",i+1)(E):b(E)}function b(E){return E===null||Hc(E)?s.check(IYe,x,S)(E):(s.enter("codeFlowValue"),w(E))}function w(E){return E===null||Hc(E)?(s.exit("codeFlowValue"),b(E)):(s.consume(E),w)}function S(E){return s.exit("codeFenced"),t(E)}function C(E,I,P){let R=0;return D;function D(G){return E.enter("lineEnding"),E.consume(G),E.exit("lineEnding"),O}function O(G){return E.enter("codeFencedFence"),kh(G)?Zp(E,U,"linePrefix",r.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(G):U(G)}function U(G){return G===o?(E.enter("codeFencedFenceSequence"),W(G)):P(G)}function W(G){return G===o?(R++,E.consume(G),W):R>=l?(E.exit("codeFencedFenceSequence"),kh(G)?Zp(E,V,"whitespace")(G):V(G)):P(G)}function V(G){return G===null||Hc(G)?(E.exit("codeFencedFence"),I(G)):P(G)}}}const U9e={name:"codeIndented",tokenize:k8n},N8n={partial:!0,tokenize:S8n};function k8n(s,t,n){return r;function r(o){return s.enter("codeIndented"),uQt(s,a,n,"linePrefix",4,4)(o)}function a(o){return o===null?l(o):Hc(o)?s.attempt(N8n,a,l)(o):(s.enter("codeFlowValue"),i(o))}function i(o){return o===null||Hc(o)?(s.exit("codeFlowValue"),a(o)):(s.consume(o),i)}function l(o){return s.exit("codeIndented"),t(o)}}function S8n(s,t,n){const r=this;return a;function a(l){return r.parser.lazy[r.now().line]?n(l):Hc(l)?(s.enter("lineEnding"),s.consume(l),s.exit("lineEnding"),a):uQt(s,t,i,"linePrefix",4,4)(l)}function i(l){return Hc(l)?a(l):n(l)}}const C8n={name:"codeText",previous:E8n,resolve:A8n,tokenize:T8n};function A8n(s){let t=s.length-4,n=3,r,a;if((s[n][1].type==="lineEnding"||s[n][1].type==="space")&&(s[t][1].type==="lineEnding"||s[t][1].type==="space")){for(r=n;++r=this.left.length+this.right.length)throw new RangeError("Cannot access index `"+t+"` in a splice buffer of size `"+(this.left.length+this.right.length)+"`");return tthis.left.length?this.right.slice(this.right.length-r+this.left.length,this.right.length-t+this.left.length).reverse():this.left.slice(t).concat(this.right.slice(this.right.length-r+this.left.length).reverse())}splice(t,n,r){const a=n||0;this.setCursor(Math.trunc(t));const i=this.right.splice(this.right.length-a,Number.POSITIVE_INFINITY);return r&&aX(this.left,r),i.reverse()}pop(){return this.setCursor(Number.POSITIVE_INFINITY),this.left.pop()}push(t){this.setCursor(Number.POSITIVE_INFINITY),this.left.push(t)}pushMany(t){this.setCursor(Number.POSITIVE_INFINITY),aX(this.left,t)}unshift(t){this.setCursor(0),this.right.push(t)}unshiftMany(t){this.setCursor(0),aX(this.right,t.reverse())}setCursor(t){if(!(t===this.left.length||t>this.left.length&&this.right.length===0||t<0&&this.left.length===0))if(t=4?t(l):s.interrupt(r.parser.constructs.flow,n,t)(l)}}function gQt(s,t,n,r,a,i,l,o,c){const d=c||Number.POSITIVE_INFINITY;let u=0;return h;function h(v){return v===60?(s.enter(r),s.enter(a),s.enter(i),s.consume(v),s.exit(i),m):v===null||v===32||v===41||TYe(v)?n(v):(s.enter(r),s.enter(l),s.enter(o),s.enter("chunkString",{contentType:"string"}),x(v))}function m(v){return v===62?(s.enter(i),s.consume(v),s.exit(i),s.exit(a),s.exit(r),t):(s.enter(o),s.enter("chunkString",{contentType:"string"}),f(v))}function f(v){return v===62?(s.exit("chunkString"),s.exit(o),m(v)):v===null||v===60||Hc(v)?n(v):(s.consume(v),v===92?g:f)}function g(v){return v===60||v===62||v===92?(s.consume(v),f):f(v)}function x(v){return!u&&(v===null||v===41||Bw(v))?(s.exit("chunkString"),s.exit(o),s.exit(l),s.exit(r),t(v)):u999||f===null||f===91||f===93&&!c||f===94&&!o&&"_hiddenFootnoteSupport"in l.parser.constructs?n(f):f===93?(s.exit(i),s.enter(a),s.consume(f),s.exit(a),s.exit(r),t):Hc(f)?(s.enter("lineEnding"),s.consume(f),s.exit("lineEnding"),u):(s.enter("chunkString",{contentType:"string"}),h(f))}function h(f){return f===null||f===91||f===93||Hc(f)||o++>999?(s.exit("chunkString"),u(f)):(s.consume(f),c||(c=!kh(f)),f===92?m:h)}function m(f){return f===91||f===92||f===93?(s.consume(f),o++,h):h(f)}}function yQt(s,t,n,r,a,i){let l;return o;function o(m){return m===34||m===39||m===40?(s.enter(r),s.enter(a),s.consume(m),s.exit(a),l=m===40?41:m,c):n(m)}function c(m){return m===l?(s.enter(a),s.consume(m),s.exit(a),s.exit(r),t):(s.enter(i),d(m))}function d(m){return m===l?(s.exit(i),c(l)):m===null?n(m):Hc(m)?(s.enter("lineEnding"),s.consume(m),s.exit("lineEnding"),Zp(s,d,"linePrefix")):(s.enter("chunkString",{contentType:"string"}),u(m))}function u(m){return m===l||m===null||Hc(m)?(s.exit("chunkString"),d(m)):(s.consume(m),m===92?h:u)}function h(m){return m===l||m===92?(s.consume(m),u):u(m)}}function Jee(s,t){let n;return r;function r(a){return Hc(a)?(s.enter("lineEnding"),s.consume(a),s.exit("lineEnding"),n=!0,r):kh(a)?Zp(s,r,n?"linePrefix":"lineSuffix")(a):t(a)}}const O8n={name:"definition",tokenize:B8n},z8n={partial:!0,tokenize:$8n};function B8n(s,t,n){const r=this;let a;return i;function i(f){return s.enter("definition"),l(f)}function l(f){return xQt.call(r,s,o,n,"definitionLabel","definitionLabelMarker","definitionLabelString")(f)}function o(f){return a=LV(r.sliceSerialize(r.events[r.events.length-1][1]).slice(1,-1)),f===58?(s.enter("definitionMarker"),s.consume(f),s.exit("definitionMarker"),c):n(f)}function c(f){return Bw(f)?Jee(s,d)(f):d(f)}function d(f){return gQt(s,u,n,"definitionDestination","definitionDestinationLiteral","definitionDestinationLiteralMarker","definitionDestinationRaw","definitionDestinationString")(f)}function u(f){return s.attempt(z8n,h,h)(f)}function h(f){return kh(f)?Zp(s,m,"whitespace")(f):m(f)}function m(f){return f===null||Hc(f)?(s.exit("definition"),r.parser.defined.push(a),t(f)):n(f)}}function $8n(s,t,n){return r;function r(o){return Bw(o)?Jee(s,a)(o):n(o)}function a(o){return yQt(s,i,n,"definitionTitle","definitionTitleMarker","definitionTitleString")(o)}function i(o){return kh(o)?Zp(s,l,"whitespace")(o):l(o)}function l(o){return o===null||Hc(o)?t(o):n(o)}}const U8n={name:"hardBreakEscape",tokenize:q8n};function q8n(s,t,n){return r;function r(i){return s.enter("hardBreakEscape"),s.consume(i),a}function a(i){return Hc(i)?(s.exit("hardBreakEscape"),t(i)):n(i)}}const V8n={name:"headingAtx",resolve:H8n,tokenize:G8n};function H8n(s,t){let n=s.length-2,r=3;if(s[r][1].type==="whitespace"&&(r+=2),n-2>r&&s[n][1].type==="whitespace"&&(n-=2),s[n][1].type==="atxHeadingSequence"&&(r===n-1||n-4>r&&s[n-2][1].type==="whitespace")&&(n-=r+1===n?2:4),n>r){const a={type:"atxHeadingText",start:s[r][1].start,end:s[n][1].end},i={type:"chunkText",start:s[r][1].start,end:s[n][1].end,contentType:"text"};T6(s,r,n-r+1,[["enter",a,t],["enter",i,t],["exit",i,t],["exit",a,t]])}return s}function G8n(s,t,n){let r=0;return a;function a(u){return s.enter("atxHeading"),i(u)}function i(u){return s.enter("atxHeadingSequence"),l(u)}function l(u){return u===35&&r++<6?(s.consume(u),l):u===null||Bw(u)?(s.exit("atxHeadingSequence"),o(u)):n(u)}function o(u){return u===35?(s.enter("atxHeadingSequence"),c(u)):u===null||Hc(u)?(s.exit("atxHeading"),t(u)):kh(u)?Zp(s,o,"whitespace")(u):(s.enter("atxHeadingText"),d(u))}function c(u){return u===35?(s.consume(u),c):(s.exit("atxHeadingSequence"),o(u))}function d(u){return u===null||u===35||Bw(u)?(s.exit("atxHeadingText"),o(u)):(s.consume(u),d)}}const W8n=["address","article","aside","base","basefont","blockquote","body","caption","center","col","colgroup","dd","details","dialog","dir","div","dl","dt","fieldset","figcaption","figure","footer","form","frame","frameset","h1","h2","h3","h4","h5","h6","head","header","hr","html","iframe","legend","li","link","main","menu","menuitem","nav","noframes","ol","optgroup","option","p","param","search","section","summary","table","tbody","td","tfoot","th","thead","title","tr","track","ul"],RSt=["pre","script","style","textarea"],K8n={concrete:!0,name:"htmlFlow",resolveTo:Z8n,tokenize:X8n},Y8n={partial:!0,tokenize:Q8n};function Z8n(s){let t=s.length;for(;t--&&!(s[t][0]==="enter"&&s[t][1].type==="htmlFlow"););return t>1&&s[t-2][1].type==="linePrefix"&&(s[t][1].start=s[t-2][1].start,s[t+1][1].start=s[t-2][1].start,s.splice(t-2,2)),s}function X8n(s,t,n){const r=this;let a,i,l,o,c;return d;function d(ce){return u(ce)}function u(ce){return s.enter("htmlFlow"),s.enter("htmlFlowData"),s.consume(ce),h}function h(ce){return ce===33?(s.consume(ce),m):ce===47?(s.consume(ce),i=!0,x):ce===63?(s.consume(ce),a=3,r.interrupt?t:ne):h4(ce)?(s.consume(ce),l=String.fromCharCode(ce),y):n(ce)}function m(ce){return ce===45?(s.consume(ce),a=2,f):ce===91?(s.consume(ce),a=5,o=0,g):h4(ce)?(s.consume(ce),a=4,r.interrupt?t:ne):n(ce)}function f(ce){return ce===45?(s.consume(ce),r.interrupt?t:ne):n(ce)}function g(ce){const _e="CDATA[";return ce===_e.charCodeAt(o++)?(s.consume(ce),o===_e.length?r.interrupt?t:U:g):n(ce)}function x(ce){return h4(ce)?(s.consume(ce),l=String.fromCharCode(ce),y):n(ce)}function y(ce){if(ce===null||ce===47||ce===62||Bw(ce)){const _e=ce===47,he=l.toLowerCase();return!_e&&!i&&RSt.includes(he)?(a=1,r.interrupt?t(ce):U(ce)):W8n.includes(l.toLowerCase())?(a=6,_e?(s.consume(ce),v):r.interrupt?t(ce):U(ce)):(a=7,r.interrupt&&!r.parser.lazy[r.now().line]?n(ce):i?b(ce):w(ce))}return ce===45||s2(ce)?(s.consume(ce),l+=String.fromCharCode(ce),y):n(ce)}function v(ce){return ce===62?(s.consume(ce),r.interrupt?t:U):n(ce)}function b(ce){return kh(ce)?(s.consume(ce),b):D(ce)}function w(ce){return ce===47?(s.consume(ce),D):ce===58||ce===95||h4(ce)?(s.consume(ce),S):kh(ce)?(s.consume(ce),w):D(ce)}function S(ce){return ce===45||ce===46||ce===58||ce===95||s2(ce)?(s.consume(ce),S):C(ce)}function C(ce){return ce===61?(s.consume(ce),E):kh(ce)?(s.consume(ce),C):w(ce)}function E(ce){return ce===null||ce===60||ce===61||ce===62||ce===96?n(ce):ce===34||ce===39?(s.consume(ce),c=ce,I):kh(ce)?(s.consume(ce),E):P(ce)}function I(ce){return ce===c?(s.consume(ce),c=null,R):ce===null||Hc(ce)?n(ce):(s.consume(ce),I)}function P(ce){return ce===null||ce===34||ce===39||ce===47||ce===60||ce===61||ce===62||ce===96||Bw(ce)?C(ce):(s.consume(ce),P)}function R(ce){return ce===47||ce===62||kh(ce)?w(ce):n(ce)}function D(ce){return ce===62?(s.consume(ce),O):n(ce)}function O(ce){return ce===null||Hc(ce)?U(ce):kh(ce)?(s.consume(ce),O):n(ce)}function U(ce){return ce===45&&a===2?(s.consume(ce),Y):ce===60&&a===1?(s.consume(ce),X):ce===62&&a===4?(s.consume(ce),te):ce===63&&a===3?(s.consume(ce),ne):ce===93&&a===5?(s.consume(ce),ie):Hc(ce)&&(a===6||a===7)?(s.exit("htmlFlowData"),s.check(Y8n,J,W)(ce)):ce===null||Hc(ce)?(s.exit("htmlFlowData"),W(ce)):(s.consume(ce),U)}function W(ce){return s.check(IYe,V,J)(ce)}function V(ce){return s.enter("lineEnding"),s.consume(ce),s.exit("lineEnding"),G}function G(ce){return ce===null||Hc(ce)?W(ce):(s.enter("htmlFlowData"),U(ce))}function Y(ce){return ce===45?(s.consume(ce),ne):U(ce)}function X(ce){return ce===47?(s.consume(ce),l="",ae):U(ce)}function ae(ce){if(ce===62){const _e=l.toLowerCase();return RSt.includes(_e)?(s.consume(ce),te):U(ce)}return h4(ce)&&l.length<8?(s.consume(ce),l+=String.fromCharCode(ce),ae):U(ce)}function ie(ce){return ce===93?(s.consume(ce),ne):U(ce)}function ne(ce){return ce===62?(s.consume(ce),te):ce===45&&a===2?(s.consume(ce),ne):U(ce)}function te(ce){return ce===null||Hc(ce)?(s.exit("htmlFlowData"),J(ce)):(s.consume(ce),te)}function J(ce){return s.exit("htmlFlow"),t(ce)}}function Q8n(s,t,n){return r;function r(a){return s.enter("lineEnding"),s.consume(a),s.exit("lineEnding"),s.attempt(aDe,t,n)}}const J8n={name:"htmlText",tokenize:ezn};function ezn(s,t,n){const r=this;let a,i,l;return o;function o(ne){return s.enter("htmlText"),s.enter("htmlTextData"),s.consume(ne),c}function c(ne){return ne===33?(s.consume(ne),d):ne===47?(s.consume(ne),C):ne===63?(s.consume(ne),w):h4(ne)?(s.consume(ne),P):n(ne)}function d(ne){return ne===45?(s.consume(ne),u):ne===91?(s.consume(ne),i=0,g):h4(ne)?(s.consume(ne),b):n(ne)}function u(ne){return ne===45?(s.consume(ne),f):n(ne)}function h(ne){return ne===null?n(ne):ne===45?(s.consume(ne),m):Hc(ne)?(l=h,X(ne)):(s.consume(ne),h)}function m(ne){return ne===45?(s.consume(ne),f):h(ne)}function f(ne){return ne===62?Y(ne):ne===45?m(ne):h(ne)}function g(ne){const te="CDATA[";return ne===te.charCodeAt(i++)?(s.consume(ne),i===te.length?x:g):n(ne)}function x(ne){return ne===null?n(ne):ne===93?(s.consume(ne),y):Hc(ne)?(l=x,X(ne)):(s.consume(ne),x)}function y(ne){return ne===93?(s.consume(ne),v):x(ne)}function v(ne){return ne===62?Y(ne):ne===93?(s.consume(ne),v):x(ne)}function b(ne){return ne===null||ne===62?Y(ne):Hc(ne)?(l=b,X(ne)):(s.consume(ne),b)}function w(ne){return ne===null?n(ne):ne===63?(s.consume(ne),S):Hc(ne)?(l=w,X(ne)):(s.consume(ne),w)}function S(ne){return ne===62?Y(ne):w(ne)}function C(ne){return h4(ne)?(s.consume(ne),E):n(ne)}function E(ne){return ne===45||s2(ne)?(s.consume(ne),E):I(ne)}function I(ne){return Hc(ne)?(l=I,X(ne)):kh(ne)?(s.consume(ne),I):Y(ne)}function P(ne){return ne===45||s2(ne)?(s.consume(ne),P):ne===47||ne===62||Bw(ne)?R(ne):n(ne)}function R(ne){return ne===47?(s.consume(ne),Y):ne===58||ne===95||h4(ne)?(s.consume(ne),D):Hc(ne)?(l=R,X(ne)):kh(ne)?(s.consume(ne),R):Y(ne)}function D(ne){return ne===45||ne===46||ne===58||ne===95||s2(ne)?(s.consume(ne),D):O(ne)}function O(ne){return ne===61?(s.consume(ne),U):Hc(ne)?(l=O,X(ne)):kh(ne)?(s.consume(ne),O):R(ne)}function U(ne){return ne===null||ne===60||ne===61||ne===62||ne===96?n(ne):ne===34||ne===39?(s.consume(ne),a=ne,W):Hc(ne)?(l=U,X(ne)):kh(ne)?(s.consume(ne),U):(s.consume(ne),V)}function W(ne){return ne===a?(s.consume(ne),a=void 0,G):ne===null?n(ne):Hc(ne)?(l=W,X(ne)):(s.consume(ne),W)}function V(ne){return ne===null||ne===34||ne===39||ne===60||ne===61||ne===96?n(ne):ne===47||ne===62||Bw(ne)?R(ne):(s.consume(ne),V)}function G(ne){return ne===47||ne===62||Bw(ne)?R(ne):n(ne)}function Y(ne){return ne===62?(s.consume(ne),s.exit("htmlTextData"),s.exit("htmlText"),t):n(ne)}function X(ne){return s.exit("htmlTextData"),s.enter("lineEnding"),s.consume(ne),s.exit("lineEnding"),ae}function ae(ne){return kh(ne)?Zp(s,ie,"linePrefix",r.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(ne):ie(ne)}function ie(ne){return s.enter("htmlTextData"),l(ne)}}const git={name:"labelEnd",resolveAll:rzn,resolveTo:azn,tokenize:izn},tzn={tokenize:ozn},szn={tokenize:lzn},nzn={tokenize:czn};function rzn(s){let t=-1;const n=[];for(;++t0&&a[a.length-1]._balanced;)a.pop();i=a[a.length-1]}return o;function o(m){return i?i._inactive?h(m):(l=r.parser.defined.includes(LV(r.sliceSerialize({start:i.end,end:r.now()}))),s.enter("labelEnd"),s.enter("labelMarker"),s.consume(m),s.exit("labelMarker"),s.exit("labelEnd"),c):n(m)}function c(m){return m===40?s.attempt(tzn,u,l?u:h)(m):m===91?s.attempt(szn,u,l?d:h)(m):l?u(m):h(m)}function d(m){return s.attempt(nzn,u,h)(m)}function u(m){return a.pop(),t(m)}function h(m){return i._balanced=!0,n(m)}}function ozn(s,t,n){return r;function r(h){return s.enter("resource"),s.enter("resourceMarker"),s.consume(h),s.exit("resourceMarker"),a}function a(h){return Bw(h)?Jee(s,i)(h):i(h)}function i(h){return h===41?u(h):gQt(s,l,o,"resourceDestination","resourceDestinationLiteral","resourceDestinationLiteralMarker","resourceDestinationRaw","resourceDestinationString",32)(h)}function l(h){return Bw(h)?Jee(s,c)(h):u(h)}function o(h){return n(h)}function c(h){return h===34||h===39||h===40?yQt(s,d,n,"resourceTitle","resourceTitleMarker","resourceTitleString")(h):u(h)}function d(h){return Bw(h)?Jee(s,u)(h):u(h)}function u(h){return h===41?(s.enter("resourceMarker"),s.consume(h),s.exit("resourceMarker"),s.exit("resource"),t):n(h)}}function lzn(s,t,n){const r=this;return a;function a(o){return xQt.call(r,s,i,l,"reference","referenceMarker","referenceString")(o)}function i(o){return r.parser.defined.includes(LV(r.sliceSerialize(r.events[r.events.length-1][1]).slice(1,-1)))?t(o):n(o)}function l(o){return n(o)}}function czn(s,t,n){return r;function r(i){return s.enter("reference"),s.enter("referenceMarker"),s.consume(i),s.exit("referenceMarker"),a}function a(i){return i===93?(s.enter("referenceMarker"),s.consume(i),s.exit("referenceMarker"),s.exit("reference"),t):n(i)}}const dzn={name:"labelStartImage",resolveAll:git.resolveAll,tokenize:uzn};function uzn(s,t,n){const r=this;let a;return i;function i(c){return s.enter("labelImage"),s.enter("labelImageMarker"),s.consume(c),s.exit("labelImageMarker"),l}function l(c){return c===91?(s.enter("labelMarker"),s.consume(c),s.exit("labelMarker"),a=s.exit("labelImage"),o):n(c)}function o(c){return c===94&&"_hiddenFootnoteSupport"in r.parser.constructs?n(c):(r._labelStarts=r._labelStarts||[],r._labelStarts.push(a),t(c))}}const hzn={name:"labelStartLink",resolveAll:git.resolveAll,tokenize:mzn};function mzn(s,t,n){const r=this;let a;return i;function i(o){return s.enter("labelLink"),s.enter("labelMarker"),s.consume(o),s.exit("labelMarker"),a=s.exit("labelLink"),l}function l(o){return o===94&&"_hiddenFootnoteSupport"in r.parser.constructs?n(o):(r._labelStarts=r._labelStarts||[],r._labelStarts.push(a),t(o))}}const q9e={name:"lineEnding",tokenize:fzn};function fzn(s,t){return n;function n(r){return s.enter("lineEnding"),s.consume(r),s.exit("lineEnding"),Zp(s,t,"linePrefix")}}const A3e={name:"thematicBreak",tokenize:pzn};function pzn(s,t,n){let r=0,a;return i;function i(d){return s.enter("thematicBreak"),l(d)}function l(d){return a=d,o(d)}function o(d){return d===a?(s.enter("thematicBreakSequence"),c(d)):r>=3&&(d===null||Hc(d))?(s.exit("thematicBreak"),t(d)):n(d)}function c(d){return d===a?(s.consume(d),r++,c):(s.exit("thematicBreakSequence"),kh(d)?Zp(s,o,"whitespace")(d):o(d))}}const ow={continuation:{tokenize:vzn},exit:_zn,name:"list",tokenize:yzn},gzn={partial:!0,tokenize:wzn},xzn={partial:!0,tokenize:bzn};function yzn(s,t,n){const r=this,a=r.events[r.events.length-1];let i=a&&a[1].type==="linePrefix"?a[2].sliceSerialize(a[1],!0).length:0,l=0;return o;function o(f){const g=r.containerState.type||(f===42||f===43||f===45?"listUnordered":"listOrdered");if(g==="listUnordered"?!r.containerState.marker||f===r.containerState.marker:MYe(f)){if(r.containerState.type||(r.containerState.type=g,s.enter(g,{_container:!0})),g==="listUnordered")return s.enter("listItemPrefix"),f===42||f===45?s.check(A3e,n,d)(f):d(f);if(!r.interrupt||f===49)return s.enter("listItemPrefix"),s.enter("listItemValue"),c(f)}return n(f)}function c(f){return MYe(f)&&++l<10?(s.consume(f),c):(!r.interrupt||l<2)&&(r.containerState.marker?f===r.containerState.marker:f===41||f===46)?(s.exit("listItemValue"),d(f)):n(f)}function d(f){return s.enter("listItemMarker"),s.consume(f),s.exit("listItemMarker"),r.containerState.marker=r.containerState.marker||f,s.check(aDe,r.interrupt?n:u,s.attempt(gzn,m,h))}function u(f){return r.containerState.initialBlankLine=!0,i++,m(f)}function h(f){return kh(f)?(s.enter("listItemPrefixWhitespace"),s.consume(f),s.exit("listItemPrefixWhitespace"),m):n(f)}function m(f){return r.containerState.size=i+r.sliceSerialize(s.exit("listItemPrefix"),!0).length,t(f)}}function vzn(s,t,n){const r=this;return r.containerState._closeFlow=void 0,s.check(aDe,a,i);function a(o){return r.containerState.furtherBlankLines=r.containerState.furtherBlankLines||r.containerState.initialBlankLine,Zp(s,t,"listItemIndent",r.containerState.size+1)(o)}function i(o){return r.containerState.furtherBlankLines||!kh(o)?(r.containerState.furtherBlankLines=void 0,r.containerState.initialBlankLine=void 0,l(o)):(r.containerState.furtherBlankLines=void 0,r.containerState.initialBlankLine=void 0,s.attempt(xzn,t,l)(o))}function l(o){return r.containerState._closeFlow=!0,r.interrupt=void 0,Zp(s,s.attempt(ow,t,n),"linePrefix",r.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(o)}}function bzn(s,t,n){const r=this;return Zp(s,a,"listItemIndent",r.containerState.size+1);function a(i){const l=r.events[r.events.length-1];return l&&l[1].type==="listItemIndent"&&l[2].sliceSerialize(l[1],!0).length===r.containerState.size?t(i):n(i)}}function _zn(s){s.exit(this.containerState.type)}function wzn(s,t,n){const r=this;return Zp(s,a,"listItemPrefixWhitespace",r.parser.constructs.disable.null.includes("codeIndented")?void 0:5);function a(i){const l=r.events[r.events.length-1];return!kh(i)&&l&&l[1].type==="listItemPrefixWhitespace"?t(i):n(i)}}const DSt={name:"setextUnderline",resolveTo:jzn,tokenize:Nzn};function jzn(s,t){const n=new XMe;let r=s.length,a,i,l;for(;r--;)if(s[r][0]==="enter"){if(s[r][1].type==="content"){a=r;break}s[r][1].type==="paragraph"&&(i=r)}else s[r][1].type==="content"&&n.add(r,1,[]),!l&&s[r][1].type==="definition"&&(l=r);const o={type:"setextHeading",start:{...s[a][1].start},end:{...s[s.length-1][1].end}};return s[i][1].type="setextHeadingText",l?(n.add(i,0,[["enter",o,t]]),n.add(l+1,0,[["exit",s[a][1],t]]),s[a][1].end={...s[l][1].end}):s[a][1]=o,n.add(s.length,0,[["exit",o,t]]),n.consume(s),s}function Nzn(s,t,n){const r=this;let a;return i;function i(d){let u=r.events.length,h;for(;u--;)if(r.events[u][1].type!=="lineEnding"&&r.events[u][1].type!=="linePrefix"&&r.events[u][1].type!=="content"){h=r.events[u][1].type==="paragraph";break}return!r.parser.lazy[r.now().line]&&(r.interrupt||h)?(s.enter("setextHeadingLine"),a=d,l(d)):n(d)}function l(d){return s.enter("setextHeadingLineSequence"),o(d)}function o(d){return d===a?(s.consume(d),o):(s.exit("setextHeadingLineSequence"),kh(d)?Zp(s,c,"lineSuffix")(d):c(d))}function c(d){return d===null||Hc(d)?(s.exit("setextHeadingLine"),t(d)):n(d)}}const kzn={tokenize:Szn};function Szn(s){const t=this,n=s.attempt(aDe,r,s.attempt(this.parser.constructs.flowInitial,a,Zp(s,s.attempt(this.parser.constructs.flow,a,s.attempt(I8n,a)),"linePrefix")));return n;function r(i){if(i===null){s.consume(i);return}return s.enter("lineEndingBlank"),s.consume(i),s.exit("lineEndingBlank"),t.currentConstruct=void 0,n}function a(i){if(i===null){s.consume(i);return}return s.enter("lineEnding"),s.consume(i),s.exit("lineEnding"),t.currentConstruct=void 0,n}}const Czn={resolveAll:bQt()},Azn=vQt("string"),Ezn=vQt("text");function vQt(s){return{resolveAll:bQt(s==="text"?Tzn:void 0),tokenize:t};function t(n){const r=this,a=this.parser.constructs[s],i=n.attempt(a,l,o);return l;function l(u){return d(u)?i(u):o(u)}function o(u){if(u===null){n.consume(u);return}return n.enter("data"),n.consume(u),c}function c(u){return d(u)?(n.exit("data"),i(u)):(n.consume(u),c)}function d(u){if(u===null)return!0;const h=a[u];let m=-1;if(h)for(;++m-1){const o=l[0];typeof o=="string"?l[0]=o.slice(r):l.shift()}i>0&&l.push(s[a].slice(0,i))}return l}function qzn(s,t){let n=-1;const r=[];let a;for(;++n0){const ys=Yt.tokenStack[Yt.tokenStack.length-1];(ys[1]||OSt).call(Yt,void 0,ys[0])}for(rt.position={start:CM(xt.length>0?xt[0][1].start:{line:1,column:1,offset:0}),end:CM(xt.length>0?xt[xt.length-2][1].end:{line:1,column:1,offset:0})},ts=-1;++ts0&&(r.className=["language-"+a[0]]);let i={type:"element",tagName:"code",properties:r,children:[{type:"text",value:n}]};return t.meta&&(i.data={meta:t.meta}),s.patch(t,i),i=s.applyData(t,i),i={type:"element",tagName:"pre",properties:{},children:[i]},s.patch(t,i),i}function n7n(s,t){const n={type:"element",tagName:"del",properties:{},children:s.all(t)};return s.patch(t,n),s.applyData(t,n)}function r7n(s,t){const n={type:"element",tagName:"em",properties:{},children:s.all(t)};return s.patch(t,n),s.applyData(t,n)}function a7n(s,t){const n=typeof s.options.clobberPrefix=="string"?s.options.clobberPrefix:"user-content-",r=String(t.identifier).toUpperCase(),a=BK(r.toLowerCase()),i=s.footnoteOrder.indexOf(r);let l,o=s.footnoteCounts.get(r);o===void 0?(o=0,s.footnoteOrder.push(r),l=s.footnoteOrder.length):l=i+1,o+=1,s.footnoteCounts.set(r,o);const c={type:"element",tagName:"a",properties:{href:"#"+n+"fn-"+a,id:n+"fnref-"+a+(o>1?"-"+o:""),dataFootnoteRef:!0,ariaDescribedBy:["footnote-label"]},children:[{type:"text",value:String(l)}]};s.patch(t,c);const d={type:"element",tagName:"sup",properties:{},children:[c]};return s.patch(t,d),s.applyData(t,d)}function i7n(s,t){const n={type:"element",tagName:"h"+t.depth,properties:{},children:s.all(t)};return s.patch(t,n),s.applyData(t,n)}function o7n(s,t){if(s.options.allowDangerousHtml){const n={type:"raw",value:t.value};return s.patch(t,n),s.applyData(t,n)}}function jQt(s,t){const n=t.referenceType;let r="]";if(n==="collapsed"?r+="[]":n==="full"&&(r+="["+(t.label||t.identifier)+"]"),t.type==="imageReference")return[{type:"text",value:"!["+t.alt+r}];const a=s.all(t),i=a[0];i&&i.type==="text"?i.value="["+i.value:a.unshift({type:"text",value:"["});const l=a[a.length-1];return l&&l.type==="text"?l.value+=r:a.push({type:"text",value:r}),a}function l7n(s,t){const n=String(t.identifier).toUpperCase(),r=s.definitionById.get(n);if(!r)return jQt(s,t);const a={src:BK(r.url||""),alt:t.alt};r.title!==null&&r.title!==void 0&&(a.title=r.title);const i={type:"element",tagName:"img",properties:a,children:[]};return s.patch(t,i),s.applyData(t,i)}function c7n(s,t){const n={src:BK(t.url)};t.alt!==null&&t.alt!==void 0&&(n.alt=t.alt),t.title!==null&&t.title!==void 0&&(n.title=t.title);const r={type:"element",tagName:"img",properties:n,children:[]};return s.patch(t,r),s.applyData(t,r)}function d7n(s,t){const n={type:"text",value:t.value.replace(/\r?\n|\r/g," ")};s.patch(t,n);const r={type:"element",tagName:"code",properties:{},children:[n]};return s.patch(t,r),s.applyData(t,r)}function u7n(s,t){const n=String(t.identifier).toUpperCase(),r=s.definitionById.get(n);if(!r)return jQt(s,t);const a={href:BK(r.url||"")};r.title!==null&&r.title!==void 0&&(a.title=r.title);const i={type:"element",tagName:"a",properties:a,children:s.all(t)};return s.patch(t,i),s.applyData(t,i)}function h7n(s,t){const n={href:BK(t.url)};t.title!==null&&t.title!==void 0&&(n.title=t.title);const r={type:"element",tagName:"a",properties:n,children:s.all(t)};return s.patch(t,r),s.applyData(t,r)}function m7n(s,t,n){const r=s.all(t),a=n?f7n(n):NQt(t),i={},l=[];if(typeof t.checked=="boolean"){const u=r[0];let h;u&&u.type==="element"&&u.tagName==="p"?h=u:(h={type:"element",tagName:"p",properties:{},children:[]},r.unshift(h)),h.children.length>0&&h.children.unshift({type:"text",value:" "}),h.children.unshift({type:"element",tagName:"input",properties:{type:"checkbox",checked:t.checked,disabled:!0},children:[]}),i.className=["task-list-item"]}let o=-1;for(;++o1}function p7n(s,t){const n={},r=s.all(t);let a=-1;for(typeof t.start=="number"&&t.start!==1&&(n.start=t.start);++a0){const l={type:"element",tagName:"tbody",properties:{},children:s.wrap(n,!0)},o=dit(t.children[1]),c=nQt(t.children[t.children.length-1]);o&&c&&(l.position={start:o,end:c}),a.push(l)}const i={type:"element",tagName:"table",properties:{},children:s.wrap(a,!0)};return s.patch(t,i),s.applyData(t,i)}function b7n(s,t,n){const r=n?n.children:void 0,i=(r?r.indexOf(t):1)===0?"th":"td",l=n&&n.type==="table"?n.align:void 0,o=l?l.length:t.children.length;let c=-1;const d=[];for(;++c0,!0),r[0]),a=r.index+r[0].length,r=n.exec(t);return i.push($St(t.slice(a),a>0,!1)),i.join("")}function $St(s,t,n){let r=0,a=s.length;if(t){let i=s.codePointAt(r);for(;i===zSt||i===BSt;)r++,i=s.codePointAt(r)}if(n){let i=s.codePointAt(a-1);for(;i===zSt||i===BSt;)a--,i=s.codePointAt(a-1)}return a>r?s.slice(r,a):""}function j7n(s,t){const n={type:"text",value:w7n(String(t.value))};return s.patch(t,n),s.applyData(t,n)}function N7n(s,t){const n={type:"element",tagName:"hr",properties:{},children:[]};return s.patch(t,n),s.applyData(t,n)}const k7n={blockquote:e7n,break:t7n,code:s7n,delete:n7n,emphasis:r7n,footnoteReference:a7n,heading:i7n,html:o7n,imageReference:l7n,image:c7n,inlineCode:d7n,linkReference:u7n,link:h7n,listItem:m7n,list:p7n,paragraph:g7n,root:x7n,strong:y7n,table:v7n,tableCell:_7n,tableRow:b7n,text:j7n,thematicBreak:N7n,toml:nue,yaml:nue,definition:nue,footnoteDefinition:nue};function nue(){}const kQt=-1,iDe=0,ete=1,QMe=2,xit=3,yit=4,vit=5,bit=6,SQt=7,CQt=8,{defineProperty:S7n}=Object,AQt=typeof self=="object"?self:globalThis,USt=(s,t)=>{switch(s){case"Function":case"SharedWorker":case"Worker":case"eval":case"setInterval":case"setTimeout":throw new TypeError("unable to deserialize "+s)}return new AQt[s](t)},C7n=(s,t)=>{const n=(a,i)=>(s.set(i,a),a),r=a=>{if(s.has(a))return s.get(a);const[i,l]=t[a];switch(i){case iDe:case kQt:return n(l,a);case ete:{const o=n([],a);for(const c of l)o.push(r(c));return o}case QMe:{const o=n({},a);for(const[c,d]of l){const u=r(c),h=r(d);u==="__proto__"?S7n(o,u,{value:h,configurable:!0,enumerable:!0,writable:!0}):o[u]=h}return o}case xit:return n(new Date(l),a);case yit:{const{source:o,flags:c}=l;return n(new RegExp(o,c),a)}case vit:{const o=n(new Map,a);for(const[c,d]of l)o.set(r(c),r(d));return o}case bit:{const o=n(new Set,a);for(const c of l)o.add(r(c));return o}case SQt:{const{name:o,message:c}=l;return n(typeof AQt[o]=="function"?USt(o,c):new Error(c),a)}case CQt:return n(BigInt(l),a);case"BigInt":return n(Object(BigInt(l)),a);case"ArrayBuffer":return n(new Uint8Array(l).buffer,l);case"DataView":{const{buffer:o}=new Uint8Array(l);return n(new DataView(o),l)}case"-0":return-0}return n(USt(i,l),a)};return r},qSt=s=>C7n(new Map,s)(0),$O="",{toString:A7n}={},{keys:E7n,is:T7n}=Object,iX=s=>{const t=typeof s;if(t!=="object"||!s)return[iDe,t];const n=A7n.call(s).slice(8,-1);switch(n){case"Array":return[ete,$O];case"Object":return[QMe,$O];case"Date":return[xit,$O];case"RegExp":return[yit,$O];case"Map":return[vit,$O];case"Set":return[bit,$O];case"DataView":return[ete,n]}return n.includes("Array")?[ete,n]:s instanceof Error?[SQt,s.name||"Error"]:[QMe,n]},rue=([s,t])=>s===iDe&&(t==="function"||t==="symbol"),M7n=(s,t,n,r)=>{const a=(l,o)=>{const c=r.push(l)-1;return n.set(o,c),c},i=l=>{if(n.has(l))return n.get(l);let[o,c]=iX(l);switch(o){case iDe:{let u=l;switch(c){case"bigint":o=CQt,u=l.toString();break;case"number":if(!l&&T7n(l,-0))return r.push(["-0"])-1;break;case"function":case"symbol":if(s)throw new TypeError("unable to serialize "+c);u=null;break;case"undefined":return a([kQt],l)}return a([o,u],l)}case ete:{if(c){let m=l;return c==="DataView"?m=new Uint8Array(l.buffer):c==="ArrayBuffer"&&(m=new Uint8Array(l)),a([c,[...m]],l)}const u=[],h=a([o,u],l);for(const m of l)u.push(i(m));return h}case QMe:{if(c)switch(c){case"BigInt":return a([c,l.toString()],l);case"Boolean":case"Number":case"String":return a([c,l.valueOf()],l)}if(t&&"toJSON"in l)return i(l.toJSON());const u=[],h=a([o,u],l);for(const m of E7n(l))(s||!rue(iX(l[m])))&&u.push([i(m),i(l[m])]);return h}case xit:return a([o,isNaN(l.getTime())?$O:l.toISOString()],l);case yit:{const{source:u,flags:h}=l;return a([o,{source:u,flags:h}],l)}case vit:{const u=[],h=a([o,u],l);for(const[m,f]of l)(s||!(rue(iX(m))||rue(iX(f))))&&u.push([i(m),i(f)]);return h}case bit:{const u=[],h=a([o,u],l);for(const m of l)(s||!rue(iX(m)))&&u.push(i(m));return h}}const{message:d}=l;return a([o,{name:c,message:d}],l)};return i},VSt=(s,{json:t,lossy:n}={})=>{const r=[];return M7n(!(t||n),!!t,new Map,r)(s),r},JMe=typeof structuredClone=="function"?(s,t)=>t&&("json"in t||"lossy"in t)?qSt(VSt(s,t)):structuredClone(s):(s,t)=>qSt(VSt(s,t));function P7n(s,t){const n=[{type:"text",value:"↩"}];return t>1&&n.push({type:"element",tagName:"sup",properties:{},children:[{type:"text",value:String(t)}]}),n}function I7n(s,t){return"Back to reference "+(s+1)+(t>1?"-"+t:"")}function L7n(s){const t=typeof s.options.clobberPrefix=="string"?s.options.clobberPrefix:"user-content-",n=s.options.footnoteBackContent||P7n,r=s.options.footnoteBackLabel||I7n,a=s.options.footnoteLabel||"Footnotes",i=s.options.footnoteLabelTagName||"h2",l=s.options.footnoteLabelProperties||{className:["sr-only"]},o=[];let c=-1;for(;++c0&&g.push({type:"text",value:" "});let b=typeof n=="string"?n:n(c,f);typeof b=="string"&&(b={type:"text",value:b}),g.push({type:"element",tagName:"a",properties:{href:"#"+t+"fnref-"+m+(f>1?"-"+f:""),dataFootnoteBackref:"",ariaLabel:typeof r=="string"?r:r(c,f),className:["data-footnote-backref"]},children:Array.isArray(b)?b:[b]})}const y=u[u.length-1];if(y&&y.type==="element"&&y.tagName==="p"){const b=y.children[y.children.length-1];b&&b.type==="text"?b.value+=" ":y.children.push({type:"text",value:" "}),y.children.push(...g)}else u.push(...g);const v={type:"element",tagName:"li",properties:{id:t+"fn-"+m},children:s.wrap(u,!0)};s.patch(d,v),o.push(v)}if(o.length!==0)return{type:"element",tagName:"section",properties:{dataFootnotes:!0,className:["footnotes"]},children:[{type:"element",tagName:i,properties:{...JMe(l),id:"footnote-label"},children:[{type:"text",value:a}]},{type:"text",value:` `},{type:"element",tagName:"ol",properties:{},children:s.wrap(o,!0)},{type:"text",value:` `}]}}const EQt=function(s){if(s==null)return O7n;if(typeof s=="function")return oDe(s);if(typeof s=="object")return Array.isArray(s)?R7n(s):D7n(s);if(typeof s=="string")return F7n(s);throw new Error("Expected function, string, or object as test")};function R7n(s){const t=[];let n=-1;for(;++n":""))+")"})}return m;function m(){let f=TQt,g,x,y;if((!t||i(c,d,u[u.length-1]||void 0))&&(f=q7n(n(c,u)),f[0]===HSt))return f;if("children"in c&&c.children){const v=c;if(v.children&&f[0]!==$7n)for(x=(r?v.children.length:-1)+l,y=u.concat(v);x>-1&&x0&&n.push({type:"text",value:` `}),n}function GSt(s){let t=0,n=s.charCodeAt(t);for(;n===9||n===32;)t++,n=s.charCodeAt(t);return s.slice(t)}function WSt(s,t){const n=H7n(s,t),r=n.one(s,void 0),a=L7n(n),i=Array.isArray(r)?{type:"root",children:r}:r||{type:"root",children:[]};return a&&i.children.push({type:"text",value:` `},a),i}function Z7n(s,t){return s&&"run"in s?async function(n,r){const a=WSt(n,{file:r,...t});await s.run(a,r)}:function(n,r){return WSt(n,{file:r,...s||t})}}function KSt(s){if(s)throw s}var E3e=Object.prototype.hasOwnProperty,PQt=Object.prototype.toString,YSt=Object.defineProperty,ZSt=Object.getOwnPropertyDescriptor,XSt=function(t){return typeof Array.isArray=="function"?Array.isArray(t):PQt.call(t)==="[object Array]"},QSt=function(t){if(!t||PQt.call(t)!=="[object Object]")return!1;var n=E3e.call(t,"constructor"),r=t.constructor&&t.constructor.prototype&&E3e.call(t.constructor.prototype,"isPrototypeOf");if(t.constructor&&!n&&!r)return!1;var a;for(a in t);return typeof a>"u"||E3e.call(t,a)},JSt=function(t,n){YSt&&n.name==="__proto__"?YSt(t,n.name,{enumerable:!0,configurable:!0,value:n.newValue,writable:!0}):t[n.name]=n.newValue},eCt=function(t,n){if(n==="__proto__")if(E3e.call(t,n)){if(ZSt)return ZSt(t,n).value}else return;return t[n]},X7n=function s(){var t,n,r,a,i,l,o=arguments[0],c=1,d=arguments.length,u=!1;for(typeof o=="boolean"&&(u=o,o=arguments[1]||{},c=2),(o==null||typeof o!="object"&&typeof o!="function")&&(o={});cl.length;let c;o&&l.push(a);try{c=s.apply(this,l)}catch(d){const u=d;if(o&&n)throw u;return a(u)}o||(c&&c.then&&typeof c.then=="function"?c.then(i,a):c instanceof Error?a(c):i(c))}function a(l,...o){n||(n=!0,t(l,...o))}function i(l){a(null,l)}}const C5={basename:eBn,dirname:tBn,extname:sBn,join:nBn,sep:"/"};function eBn(s,t){if(t!==void 0&&typeof t!="string")throw new TypeError('"ext" argument must be a string');Die(s);let n=0,r=-1,a=s.length,i;if(t===void 0||t.length===0||t.length>s.length){for(;a--;)if(s.codePointAt(a)===47){if(i){n=a+1;break}}else r<0&&(i=!0,r=a+1);return r<0?"":s.slice(n,r)}if(t===s)return"";let l=-1,o=t.length-1;for(;a--;)if(s.codePointAt(a)===47){if(i){n=a+1;break}}else l<0&&(i=!0,l=a+1),o>-1&&(s.codePointAt(a)===t.codePointAt(o--)?o<0&&(r=a):(o=-1,r=l));return n===r?r=l:r<0&&(r=s.length),s.slice(n,r)}function tBn(s){if(Die(s),s.length===0)return".";let t=-1,n=s.length,r;for(;--n;)if(s.codePointAt(n)===47){if(r){t=n;break}}else r||(r=!0);return t<0?s.codePointAt(0)===47?"/":".":t===1&&s.codePointAt(0)===47?"//":s.slice(0,t)}function sBn(s){Die(s);let t=s.length,n=-1,r=0,a=-1,i=0,l;for(;t--;){const o=s.codePointAt(t);if(o===47){if(l){r=t+1;break}continue}n<0&&(l=!0,n=t+1),o===46?a<0?a=t:i!==1&&(i=1):a>-1&&(i=-1)}return a<0||n<0||i===0||i===1&&a===n-1&&a===r+1?"":s.slice(a,n)}function nBn(...s){let t=-1,n;for(;++t0&&s.codePointAt(s.length-1)===47&&(n+="/"),t?"/"+n:n}function aBn(s,t){let n="",r=0,a=-1,i=0,l=-1,o,c;for(;++l<=s.length;){if(l2){if(c=n.lastIndexOf("/"),c!==n.length-1){c<0?(n="",r=0):(n=n.slice(0,c),r=n.length-1-n.lastIndexOf("/")),a=l,i=0;continue}}else if(n.length>0){n="",r=0,a=l,i=0;continue}}t&&(n=n.length>0?n+"/..":"..",r=2)}else n.length>0?n+="/"+s.slice(a+1,l):n=s.slice(a+1,l),r=l-a-1;a=l,i=0}else o===46&&i>-1?i++:i=-1}return n}function Die(s){if(typeof s!="string")throw new TypeError("Path must be a string. Received "+JSON.stringify(s))}const iBn={cwd:oBn};function oBn(){return"/"}function DYe(s){return!!(s!==null&&typeof s=="object"&&"href"in s&&s.href&&"protocol"in s&&s.protocol&&s.auth===void 0)}function lBn(s){if(typeof s=="string")s=new URL(s);else if(!DYe(s)){const t=new TypeError('The "path" argument must be of type string or an instance of URL. Received `'+s+"`");throw t.code="ERR_INVALID_ARG_TYPE",t}if(s.protocol!=="file:"){const t=new TypeError("The URL must be of scheme file");throw t.code="ERR_INVALID_URL_SCHEME",t}return cBn(s)}function cBn(s){if(s.hostname!==""){const r=new TypeError('File URL host must be "localhost" or empty on darwin');throw r.code="ERR_INVALID_FILE_URL_HOST",r}const t=s.pathname;let n=-1;for(;++n0){let[f,...g]=u;const x=r[m][1];RYe(x)&&RYe(f)&&(f=V9e(!0,x,f)),r[m]=[d,f,...g]}}}}const mBn=new _it().freeze();function K9e(s,t){if(typeof t!="function")throw new TypeError("Cannot `"+s+"` without `parser`")}function Y9e(s,t){if(typeof t!="function")throw new TypeError("Cannot `"+s+"` without `compiler`")}function Z9e(s,t){if(t)throw new Error("Cannot call `"+s+"` on a frozen processor.\nCreate a new processor first, by calling it: use `processor()` instead of `processor`.")}function sCt(s){if(!RYe(s)||typeof s.type!="string")throw new TypeError("Expected node, got `"+s+"`")}function nCt(s,t,n){if(!n)throw new Error("`"+s+"` finished async. Use `"+t+"` instead")}function aue(s){return fBn(s)?s:new IQt(s)}function fBn(s){return!!(s&&typeof s=="object"&&"message"in s&&"messages"in s)}function pBn(s){return typeof s=="string"||gBn(s)}function gBn(s){return!!(s&&typeof s=="object"&&"byteLength"in s&&"byteOffset"in s)}const xBn="https://github.com/remarkjs/react-markdown/blob/main/changelog.md",rCt=[],aCt={allowDangerousHtml:!0},yBn=/^(https?|ircs?|mailto|xmpp)$/i,vBn=[{from:"astPlugins",id:"remove-buggy-html-in-markdown-parser"},{from:"allowDangerousHtml",id:"remove-buggy-html-in-markdown-parser"},{from:"allowNode",id:"replace-allownode-allowedtypes-and-disallowedtypes",to:"allowElement"},{from:"allowedTypes",id:"replace-allownode-allowedtypes-and-disallowedtypes",to:"allowedElements"},{from:"className",id:"remove-classname"},{from:"disallowedTypes",id:"replace-allownode-allowedtypes-and-disallowedtypes",to:"disallowedElements"},{from:"escapeHtml",id:"remove-buggy-html-in-markdown-parser"},{from:"includeElementIndex",id:"#remove-includeelementindex"},{from:"includeNodeIndex",id:"change-includenodeindex-to-includeelementindex"},{from:"linkTarget",id:"remove-linktarget"},{from:"plugins",id:"change-plugins-to-remarkplugins",to:"remarkPlugins"},{from:"rawSourcePos",id:"#remove-rawsourcepos"},{from:"renderers",id:"change-renderers-to-components",to:"components"},{from:"source",id:"change-source-to-children",to:"children"},{from:"sourcePos",id:"#remove-sourcepos"},{from:"transformImageUri",id:"#add-urltransform",to:"urlTransform"},{from:"transformLinkUri",id:"#add-urltransform",to:"urlTransform"}];function bBn(s){const t=_Bn(s),n=wBn(s);return jBn(t.runSync(t.parse(n),n),s)}function _Bn(s){const t=s.rehypePlugins||rCt,n=s.remarkPlugins||rCt,r=s.remarkRehypeOptions?{...s.remarkRehypeOptions,...aCt}:aCt;return mBn().use(Jzn).use(n).use(Z7n,r).use(t)}function wBn(s){const t=s.children||"",n=new IQt;return typeof t=="string"&&(n.value=t),n}function jBn(s,t){const n=t.allowedElements,r=t.allowElement,a=t.components,i=t.disallowedElements,l=t.skipHtml,o=t.unwrapDisallowed,c=t.urlTransform||NBn;for(const u of vBn)Object.hasOwn(t,u.from)&&(""+u.from+(u.to?"use `"+u.to+"` instead":"remove it")+xBn+u.id,void 0);return MQt(s,d),LOn(s,{Fragment:e.Fragment,components:a,ignoreInvalidStyle:!0,jsx:e.jsx,jsxs:e.jsxs,passKeys:!0,passNode:!0});function d(u,h,m){if(u.type==="raw"&&m&&typeof h=="number")return l?m.children.splice(h,1):m.children[h]={type:"text",value:u.value},h;if(u.type==="element"){let f;for(f in $9e)if(Object.hasOwn($9e,f)&&Object.hasOwn(u.properties,f)){const g=u.properties[f],x=$9e[f];(x===null||x.includes(u.tagName))&&(u.properties[f]=c(String(g||""),f,u))}}if(u.type==="element"){let f=n?!n.includes(u.tagName):i?i.includes(u.tagName):!1;if(!f&&r&&typeof h=="number"&&(f=!r(u,h,m)),f&&m&&typeof h=="number")return o&&u.children?m.children.splice(h,1,...u.children):m.children.splice(h,1),h}}}function NBn(s){const t=s.indexOf(":"),n=s.indexOf("?"),r=s.indexOf("#"),a=s.indexOf("/");return t===-1||a!==-1&&t>a||n!==-1&&t>n||r!==-1&&t>r||yBn.test(s.slice(0,t))?s:""}const kBn={a:({href:s,children:t})=>{const n=s||"",r=n.startsWith("/"),a="inline-flex items-center gap-1 rounded-md bg-primary/10 px-1.5 py-0.5 font-medium text-primary no-underline transition-colors hover:bg-primary/20";return r?e.jsxs(wr,{to:n,className:a,children:[t,e.jsx(Oz,{className:"h-3 w-3"})]}):e.jsxs("a",{href:n,target:"_blank",rel:"noopener noreferrer",className:a,children:[t,e.jsx(Oz,{className:"h-3 w-3"})]})}},SBn=["What should I do first thing every morning in LevelUp?","How do I get my website showing up on Google?","Write me a follow-up text for a lead who toured a home last week","Where do I create social posts for a new listing?"];function CBn(){var h,m,f;const{user:s}=vs(),[t,n]=j.useState([]),[r,a]=j.useState(""),[i,l]=j.useState(!1),o=j.useRef(null),c=j.useRef(null),d=((h=s==null?void 0:s.user_metadata)==null?void 0:h.first_name)||((f=(m=s==null?void 0:s.user_metadata)==null?void 0:m.full_name)==null?void 0:f.split(" ")[0])||"";j.useEffect(()=>{var g;(g=c.current)==null||g.scrollTo({top:c.current.scrollHeight,behavior:"smooth"})},[t,i]);const u=async g=>{var b;const x=g.trim();if(!x||i)return;const y=[...t,{role:"user",content:x}];n([...y,{role:"assistant",content:""}]),a(""),l(!0);const v=new AbortController;o.current=v;try{const{data:w}=await q.auth.getSession(),S=(b=w.session)==null?void 0:b.access_token,C=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/levelup-assistant",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${S}`,apikey:"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InJlbHplamlzd25vdGlramd2amh6Iiwicm9sZSI6ImFub24iLCJpYXQiOjE3NjE5NTAzNDQsImV4cCI6MjA3NzUyNjM0NH0.dzIkIr_oFSbFE3oWS0ktIr83iKHHkZxt40Gc7SpC_mM"},body:JSON.stringify({messages:y,agentName:d}),signal:v.signal});if(!C.ok||!C.body){const D=await C.json().catch(()=>({error:"Something went wrong."}));throw new Error(D.error||"Something went wrong.")}const E=C.body.getReader(),I=new TextDecoder;let P="",R="";for(;;){const{done:D,value:O}=await E.read();if(D)break;P+=I.decode(O,{stream:!0});const U=P.split(` `);P=U.pop()||"";for(const W of U){const V=W.trim();if(!V.startsWith("data:"))continue;const G=V.slice(5).trim();if(!(!G||G==="[DONE]"))try{const Y=JSON.parse(G);Y.delta&&(R+=Y.delta,n(X=>{const ae=[...X];return ae[ae.length-1]={role:"assistant",content:R},ae}))}catch{}}}R||n(D=>{const O=[...D];return O[O.length-1]={role:"assistant",content:"I didn't catch that — mind asking again?"},O})}catch(w){w.name==="AbortError"?n(S=>S.filter((C,E)=>!(E===S.length-1&&!C.content))):(re.error(w.message||"The assistant is unavailable right now."),n(S=>S.slice(0,-1)))}finally{l(!1),o.current=null}};return e.jsx(Vs,{children:e.jsxs("div",{className:"mx-auto flex h-[calc(100vh-7rem)] w-full max-w-3xl flex-col p-4 md:p-6",children:[e.jsxs("div",{className:"mb-4 flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("span",{className:"flex h-10 w-10 items-center justify-center rounded-xl bg-primary/10",children:e.jsx(M4,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{children:[e.jsx("h1",{className:"text-xl font-bold tracking-tight",children:"Ask LevelUp AI"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Your in-app guide to the platform and your business."})]})]}),t.length>0&&e.jsxs($,{variant:"ghost",size:"sm",className:"gap-1",onClick:()=>n([]),children:[e.jsx(Ex,{className:"h-4 w-4"})," New chat"]})]}),e.jsx("div",{ref:c,className:"flex-1 space-y-5 overflow-y-auto rounded-2xl border bg-card/40 p-4",children:t.length===0?e.jsxs("div",{className:"flex h-full flex-col items-center justify-center text-center",children:[e.jsx("span",{className:"mb-3 flex h-14 w-14 items-center justify-center rounded-2xl bg-primary/10",children:e.jsx(M4,{className:"h-7 w-7 text-primary"})}),e.jsx("p",{className:"text-base font-semibold",children:d?`Hey ${d} — what can I help with?`:"What can I help with?"}),e.jsx("p",{className:"mt-1 max-w-md text-sm text-muted-foreground",children:"I know every tool in LevelUp and can help you write, plan, and find things fast."}),e.jsx("div",{className:"mt-5 grid w-full max-w-lg gap-2 sm:grid-cols-2",children:SBn.map(g=>e.jsx("button",{onClick:()=>u(g),className:"rounded-xl border bg-background px-3 py-2.5 text-left text-sm transition-colors hover:border-primary/40 hover:bg-muted/50",children:g},g))})]}):t.map((g,x)=>e.jsx("div",{className:Pt("flex",g.role==="user"?"justify-end":"justify-start"),children:g.role==="user"?e.jsx("div",{className:"max-w-[85%] rounded-2xl rounded-br-sm bg-primary px-3.5 py-2.5 text-sm text-primary-foreground",children:e.jsx("p",{className:"whitespace-pre-wrap break-words",children:g.content})}):e.jsx("div",{className:"max-w-full text-sm leading-relaxed text-foreground",children:g.content?e.jsx("div",{className:"prose prose-sm max-w-none dark:prose-invert prose-p:my-2 prose-ul:my-2 prose-headings:mt-4 prose-headings:mb-2",children:e.jsx(bBn,{components:kBn,children:g.content})}):e.jsx("span",{className:"animate-pulse text-muted-foreground",children:"Thinking…"})})},x))}),e.jsxs("div",{className:"mt-3 flex items-end gap-2 rounded-2xl border bg-background p-2",children:[e.jsx(Rs,{value:r,onChange:g=>a(g.target.value),onKeyDown:g=>{g.key==="Enter"&&!g.shiftKey&&(g.preventDefault(),u(r))},rows:1,placeholder:"Ask anything about LevelUp or your business…",className:"min-h-[44px] resize-none border-0 bg-transparent shadow-none focus-visible:ring-0"}),i?e.jsx($,{size:"icon",variant:"secondary",onClick:()=>{var g;return(g=o.current)==null?void 0:g.abort()},children:e.jsx(C_,{className:"h-4 w-4"})}):e.jsx($,{size:"icon",disabled:!r.trim(),onClick:()=>u(r),children:e.jsx(Yr,{className:"h-4 w-4"})})]}),e.jsx("p",{className:"mt-2 text-center text-[11px] text-muted-foreground",children:"LevelUp AI can make mistakes. Double-check anything important."})]})})}function ABn({done:s,total:t,size:n=132}){const a=(n-10)/2,i=2*Math.PI*a,l=t>0?Math.min(100,s/t*100):0,o=i-l/100*i;return e.jsxs("div",{className:"relative shrink-0",style:{width:n,height:n},children:[e.jsxs("svg",{width:n,height:n,className:"-rotate-90 text-primary",children:[e.jsx("circle",{cx:n/2,cy:n/2,r:a,fill:"none",strokeWidth:10,className:"stroke-muted"}),e.jsx("circle",{cx:n/2,cy:n/2,r:a,fill:"none",strokeWidth:10,strokeLinecap:"round",stroke:"currentColor",strokeDasharray:i,strokeDashoffset:o,style:{transition:"stroke-dashoffset 700ms ease"}})]}),e.jsxs("div",{className:"absolute inset-0 flex flex-col items-center justify-center",children:[e.jsxs("div",{className:"flex items-baseline gap-0.5",children:[e.jsx("span",{className:"text-3xl font-semibold tabular-nums",children:s}),e.jsxs("span",{className:"text-sm text-muted-foreground",children:["/",t]})]}),e.jsx("span",{className:"text-[10px] uppercase tracking-wider text-muted-foreground",children:"today"})]})]})}function iue({icon:s,label:t,value:n,hint:r,tone:a="default",onClick:i,action:l}){const o=i?"button":"div";return e.jsxs(o,{onClick:i,className:Pt("group relative flex flex-col justify-between rounded-2xl border bg-card p-4 text-left transition-colors",i&&"hover:bg-accent/50 cursor-pointer",a==="warm"&&"border-orange-500/30 bg-orange-500/[0.04]",a==="alert"&&"border-amber-500/30 bg-amber-500/[0.04]"),children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("span",{className:"inline-flex items-center gap-1.5 text-[11px] font-medium uppercase tracking-wide text-muted-foreground",children:[s,t]}),l,i&&!l&&e.jsx(Di,{className:"h-3.5 w-3.5 text-muted-foreground opacity-0 group-hover:opacity-100 transition-opacity"})]}),e.jsxs("div",{className:"mt-2",children:[e.jsx("div",{className:"text-2xl font-semibold tabular-nums leading-none",children:n}),r&&e.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:r})]})]})}function EBn({agentName:s,todayDone:t,todayTotal:n,focusLine:r,weekDone:a,weekGoal:i,streak:l,staleCount:o,sphereCount:c,onEditGoal:d,onStaleClick:u,onSphereClick:h}){const m=new Date().getHours(),f=m<12?"Good morning":m<17?"Good afternoon":"Good evening",g=i>0?Math.min(100,Math.round(a/i*100)):0;return e.jsxs("div",{className:"grid gap-4 lg:grid-cols-[minmax(0,1.15fr)_minmax(0,1fr)]",children:[e.jsxs("div",{className:"relative overflow-hidden rounded-2xl border bg-gradient-to-br from-primary/[0.07] via-card to-card p-5 sm:p-6",children:[e.jsx("div",{className:"pointer-events-none absolute -right-16 -top-16 h-48 w-48 rounded-full bg-primary/10 blur-3xl"}),e.jsxs("div",{className:"relative flex flex-col-reverse items-start gap-5 sm:flex-row sm:items-center",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("p",{className:"text-[11px] font-semibold uppercase tracking-[0.16em] text-primary",children:[f,s?`, ${s}`:""]}),e.jsx("h2",{className:"mt-1.5 text-xl font-semibold leading-snug sm:text-2xl",children:n===0?"Your day is clear — pick a few people to reconnect with.":t>=n?"Today's list is done. That's how referrals get built.":`${n-t} ${n-t===1?"touch":"touches"} left to stay on track.`}),e.jsxs("p",{className:"mt-2 flex items-start gap-1.5 text-sm text-muted-foreground",children:[e.jsx(Nn,{className:"mt-0.5 h-3.5 w-3.5 shrink-0 text-primary"}),e.jsx("span",{children:r})]})]}),e.jsx(ABn,{done:t,total:n})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsx(iue,{icon:e.jsx(rh,{className:"h-3.5 w-3.5"}),label:"Weekly goal",value:`${a}/${i}`,hint:`${g}% of your weekly touches`,action:e.jsx("button",{onClick:d,className:"rounded p-0.5 text-muted-foreground transition-colors hover:text-primary","aria-label":"Edit weekly goal",children:e.jsx(Sd,{className:"h-3.5 w-3.5"})})}),e.jsx(iue,{icon:e.jsx(nh,{className:"h-3.5 w-3.5 text-orange-500"}),label:"Streak",value:l>0?`${l}d`:"—",hint:l>0?"Log one touch to keep it alive":"Log a touch today to start one",tone:l>0?"warm":"default"}),e.jsx(iue,{icon:e.jsx(da,{className:"h-3.5 w-3.5 text-amber-500"}),label:"Going cold",value:String(o),hint:"No contact in 90+ days",tone:o>0?"alert":"default",onClick:u}),e.jsx(iue,{icon:e.jsx(Zn,{className:"h-3.5 w-3.5"}),label:"Your sphere",value:String(c),hint:"People in your database",onClick:h})]})]})}const iCt="agent-os-onboarding-completed",oue=[{icon:qg,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:eg,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:Zn,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:Kc,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:ul,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:Wl,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"]}],TBn=()=>{const[s,t]=j.useState(!1),[n,r]=j.useState(0),[a,i]=j.useState(!1);j.useEffect(()=>{if(!localStorage.getItem(iCt)){const g=setTimeout(()=>t(!0),500);return()=>clearTimeout(g)}},[]);const l=()=>{n{r(n+1),i(!1)},150)):c()},o=()=>{c()},c=()=>{localStorage.setItem(iCt,"true"),t(!1)},d=oue[n],u=d.icon,h=n===oue.length-1,m=f=>{f||c(),t(f)};return e.jsx(zs,{open:s,onOpenChange:m,children:e.jsxs(Os,{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(u,{className:`h-10 w-10 ${d.iconColor} drop-shadow-lg`})})]}),n===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(Nn,{className:"h-3 w-3"}),"Beta"]})]}),e.jsxs("div",{className:"p-6 pt-4",children:[e.jsxs(Us,{className:"text-center sm:text-center pb-2",children:[e.jsx(Bs,{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(Ir,{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((f,g)=>e.jsxs("div",{className:"flex items-center gap-3 group",style:{transitionDelay:`${150+g*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(la,{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:f})]},g))}),e.jsx("div",{className:"flex justify-center gap-2 py-4",children:oue.map((f,g)=>e.jsx("button",{onClick:()=>{g!==n&&(i(!0),setTimeout(()=>{r(g),i(!1)},150))},className:`h-2 rounded-full transition-all duration-300 ${g===n?"w-8 bg-gradient-to-r "+d.bgGradient:g{const{user:s}=vs();return tt({queryKey:["contact-snoozes",s==null?void 0:s.id],queryFn:async()=>{const{data:t,error:n}=await q.from("contact_snoozes").select("*").gte("snoozed_until",new Date().toISOString());if(n)throw n;return t},enabled:!!s})},PBn=()=>{const s=Vt(),{user:t}=vs();return ft({mutationFn:async({contactId:n,days:r})=>{if(!(t!=null&&t.id))throw new Error("Not authenticated");const a=Tm(new Date,r);await q.from("contact_snoozes").delete().eq("contact_id",n);const{error:i}=await q.from("contact_snoozes").insert({contact_id:n,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"]}),_a({title:"Touch snoozed!",description:"Contact has been snoozed."})},onError:n=>{_a({title:"Error snoozing contact",description:n.message,variant:"destructive"})}})},IBn=()=>{const s=Vt();return ft({mutationFn:async t=>{const{error:n}=await q.from("contact_snoozes").delete().eq("contact_id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["contact-snoozes"]}),_a({title:"Snooze cancelled"})},onError:t=>{_a({title:"Error cancelling snooze",description:t.message,variant:"destructive"})}})},LBn=[{label:"1 week",days:7},{label:"2 weeks",days:14},{label:"1 month",days:30}];function lDe({open:s,onOpenChange:t,contactId:n,contactName:r}){const[a,i]=j.useState(null),l=PBn(),o=async()=>{a&&(await l.mutateAsync({contactId:n,days:a}),i(null),t(!1))},c=d=>en(Tm(new Date,d),"MMM d, yyyy");return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Os,{className:"sm:max-w-md",children:[e.jsxs(Us,{children:[e.jsxs(Bs,{className:"flex items-center gap-2",children:[e.jsx(da,{className:"h-5 w-5"}),"Snooze Touch"]}),e.jsxs(Ir,{children:["Postpone the next scheduled touch for ",r,". Select how long to snooze."]})]}),e.jsx("div",{className:"space-y-3 py-4",children:LBn.map(d=>e.jsxs("button",{type:"button",onClick:()=>i(d.days),className:Pt("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(Ta,{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($,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsx($,{onClick:o,disabled:!a||l.isPending,children:l.isPending?"Snoozing...":"Snooze Touch"})]})]})})}const RBn={Crown:Bg,FileText:Jr,Users:Zn,Globe:dl,Star:Ja,Phone:Da,MessageSquare:eo,PenTool:RE,Video:ua,Gift:ul};function DBn({actions:s,onMarkComplete:t,onViewScript:n,isLoading:r,buildSmsLink:a,buildEmailLink:i,onGmailCompose:l}){const o=Qn(),[c,d]=j.useState("name"),[u,h]=j.useState("asc"),[m,f]=j.useState(null),[g,x]=j.useState(""),y=C=>{c===C?h(E=>E==="asc"?"desc":"asc"):(d(C),h("asc"))},v=j.useMemo(()=>[...s].sort((C,E)=>{var P,R;let I=0;switch(c){case"name":{const D=`${C.contact.first_name} ${C.contact.last_name||""}`.toLowerCase(),O=`${E.contact.first_name} ${E.contact.last_name||""}`.toLowerCase();I=D.localeCompare(O);break}case"relationship_type":I=(C.relationshipTypeName||"").localeCompare(E.relationshipTypeName||"");break;case"action_type":I=(((P=C.actionType)==null?void 0:P.name)||"").localeCompare(((R=E.actionType)==null?void 0:R.name)||"");break;case"last_touch":I=(C.monthNumber||0)-(E.monthNumber||0);break}return u==="asc"?I:-I}),[s,c,u]),b=C=>RBn[C||"Phone"]||Da,w=({field:C,children:E})=>e.jsxs($,{variant:"ghost",size:"sm",className:"h-8 -ml-3 font-medium",onClick:()=>y(C),children:[E,c===C?u==="asc"?e.jsx(Zf,{className:"ml-2 h-4 w-4"}):e.jsx(Dg,{className:"ml-2 h-4 w-4"}):e.jsx(By,{className:"ml-2 h-4 w-4 opacity-50"})]}),S=(C,E,I)=>{f(C),x(`${E} ${I||""}`.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(mi,{children:[e.jsx(fi,{children:e.jsxs(En,{className:"bg-muted/50",children:[e.jsx(Dt,{className:"w-[180px]",children:e.jsx(w,{field:"name",children:"Contact"})}),e.jsx(Dt,{className:"w-[130px]",children:e.jsx(w,{field:"relationship_type",children:"Type"})}),e.jsx(Dt,{className:"w-[120px]",children:e.jsx(w,{field:"action_type",children:"Action"})}),e.jsx(Dt,{className:"w-[130px]",children:"Phone"}),e.jsx(Dt,{className:"w-[200px]",children:"Quick Actions"})]})}),e.jsx(pi,{children:v.map((C,E)=>{var U,W,V,G,Y,X;const I=C.isSpecialDate,P=C.specialDateType,R=I?P==="birthday"?Fg:va:b(((U=C.actionType)==null?void 0:U.icon)||null),D=C.contact.phone,O=C.contact.email;return e.jsxs(En,{className:Pt("hover:bg-muted/50 transition-colors",I&&P==="birthday"&&"bg-pink-50/50 dark:bg-pink-950/20",I&&P==="anniversary"&&"bg-purple-50/50 dark:bg-purple-950/20"),children:[e.jsx(wt,{className:"font-medium",children:e.jsx("div",{children:e.jsxs("button",{onClick:()=>o(`/mission-control/contacts/${C.contact.id}`),className:"truncate max-w-[160px] text-left hover:text-primary hover:underline transition-colors",children:[C.contact.first_name," ",C.contact.last_name]})})}),e.jsx(wt,{children:C.relationshipTypeName?e.jsx(Be,{variant:"secondary",className:"text-xs",children:C.relationshipTypeName}):e.jsx("span",{className:"text-muted-foreground text-sm",children:"—"})}),e.jsx(wt,{children:e.jsx("div",{className:"flex items-center gap-1.5",children:I?e.jsx(Be,{className:Pt("gap-1",P==="birthday"&&"bg-pink-500 hover:bg-pink-600",P==="anniversary"&&"bg-purple-500 hover:bg-purple-600"),children:P==="birthday"?e.jsxs(e.Fragment,{children:[e.jsx(Fg,{className:"h-3 w-3"})," Birthday"]}):e.jsxs(e.Fragment,{children:[e.jsx(va,{className:"h-3 w-3"})," Anniversary"]})}):e.jsxs(Be,{variant:"outline",className:"gap-1",children:[e.jsx(R,{className:"h-3 w-3"}),(W=C.actionType)==null?void 0:W.name]})})}),e.jsx(wt,{children:D?e.jsx("span",{className:"text-sm font-mono",children:C.contact.phone}):e.jsx("span",{className:"text-muted-foreground text-sm",children:"—"})}),e.jsx(wt,{children:e.jsxs("div",{className:"flex items-center gap-1",children:[D&&e.jsx("a",{href:`tel:${C.contact.phone}`,className:"p-1.5 rounded bg-primary/10 hover:bg-primary/20 text-primary transition-colors",title:"Call",children:e.jsx(Da,{className:"h-3.5 w-3.5"})}),D&&e.jsx("a",{href:a(C.contact.phone,(V=C.script)==null?void 0:V.script_body,C.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(eo,{className:"h-3.5 w-3.5"})}),O&&(l?e.jsx("button",{onClick:()=>l({id:C.contact.id,first_name:C.contact.first_name,last_name:C.contact.last_name,email:C.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(mn,{className:"h-3.5 w-3.5"})}):e.jsx("a",{href:i(C.contact.email,(G=C.script)==null?void 0:G.script_body,(Y=C.script)==null?void 0:Y.email_subject,(X=C.actionType)==null?void 0:X.name,C.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(mn,{className:"h-3.5 w-3.5"})})),I&&e.jsxs("button",{onClick:()=>{const ae=`${C.contact.first_name}${C.contact.last_name?" "+C.contact.last_name:""}`,ie=P==="birthday"?"birthday":"home_anniversary",ne=new URLSearchParams({cardType:ie,contactId:C.contact.id,name:ae,...C.contact.address?{address:C.contact.address}:{},...P==="anniversary"&&C.contact.home_anniversary?{date:C.contact.home_anniversary}:{}});o(`/mission-control/card-studio?${ne.toString()}`)},className:Pt("h-7 px-2 rounded text-xs font-semibold flex items-center gap-1 transition-colors",P==="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 ${P==="birthday"?"Birthday":"Anniversary"} Card`,children:[e.jsx(mn,{className:"h-3.5 w-3.5"}),"Send Card"]}),e.jsx($,{variant:"ghost",size:"icon",className:"h-7 w-7 text-muted-foreground hover:text-foreground",onClick:()=>S(C.contact.id,C.contact.first_name,C.contact.last_name),title:"Snooze",children:e.jsx(Tv,{className:"h-3.5 w-3.5"})}),e.jsxs($,{variant:"default",size:"sm",className:"h-7 px-2 text-xs ml-1",onClick:()=>{var ae;return t(C.contact.id,C.actionType.id,(ae=C.script)==null?void 0:ae.id)},disabled:r,children:[e.jsx(qr,{className:"h-3.5 w-3.5 mr-1"}),"Done"]})]})})]},`${C.contact.id}-${E}`)})})]})}),e.jsx(lDe,{open:!!m,onOpenChange:C=>!C&&f(null),contactId:m||"",contactName:g})]})}function FBn(){const s=Qn(),{data:t}=DUt(),{data:n}=iie(),r=N6e(),{isGmailConnected:a,gmailEmail:i}=yy(),[l,o]=j.useState(null),[c,d]=j.useState(!1),[u,h]=j.useState(new Set),m=Mg(new Date),f=Tm(m,30),g=C=>{if(!C)return null;const E=C.split(/[-/T]/);if(E.length<3)return null;const I=parseInt(E[1],10)-1,P=parseInt(E[2],10);return isNaN(I)||isNaN(P)?null:new Date(m.getFullYear(),I,P)},x=j.useMemo(()=>{if(!t)return[];const C=[];for(const E of t){if(E.birthday){const I=g(E.birthday);I&&(nf(I,m)||O4(I,m)&&iC(I,f))&&C.push({contact:E,type:"birthday",date:I,daysUntil:fb(I,m),dateStr:E.birthday})}if(E.home_anniversary){const I=g(E.home_anniversary);I&&(nf(I,m)||O4(I,m)&&iC(I,f))&&C.push({contact:E,type:"anniversary",date:I,daysUntil:fb(I,m),dateStr:E.home_anniversary})}if(E.wedding_anniversary){const I=g(E.wedding_anniversary);I&&(nf(I,m)||O4(I,m)&&iC(I,f))&&C.push({contact:E,type:"wedding_anniversary",date:I,daysUntil:fb(I,m),dateStr:E.wedding_anniversary})}}return C.sort((E,I)=>E.daysUntil-I.daysUntil),C},[t]),y=C=>C==="birthday"?"Birthday":C==="wedding_anniversary"?"Wedding Anniversary":"Home Anniversary",v=async C=>{const E=(n==null?void 0:n.find(I=>I.name==="Call"))||(n==null?void 0:n[0]);if(E)try{await r.mutateAsync({contactId:C.contact.id,actionTypeId:E.id,notes:`${y(C.type)} outreach`}),h(I=>new Set(I).add(`${C.contact.id}-${C.type}`)),_a({title:"Touch logged!",description:`Logged outreach for ${C.contact.first_name}`})}catch{_a({title:"Error",description:"Failed to log touch",variant:"destructive"})}},b=C=>{const E=`${C.contact.first_name}${C.contact.last_name?" "+C.contact.last_name:""}`,I=C.type==="birthday"?"birthday":C.type==="wedding_anniversary"?"wedding_anniversary":"home_anniversary",P=new URLSearchParams({cardType:I,contactId:C.contact.id,name:E,...C.contact.address?{address:C.contact.address}:{},...(C.type==="anniversary"||C.type==="wedding_anniversary")&&C.dateStr?{date:C.dateStr}:{}});s(`/mission-control/card-studio?${P.toString()}`)},w=C=>C===0?"Today!":C===1?"Tomorrow":`${C} days`,S=C=>C===0?"bg-red-500/15 text-red-600 dark:text-red-400 border-red-500/30":C<=3?"bg-amber-500/15 text-amber-600 dark:text-amber-400 border-amber-500/30":C<=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(Ne,{children:[e.jsx(Ct,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(At,{className:"text-lg flex items-center gap-2",children:[e.jsx(Kc,{className:"h-5 w-5 text-primary"}),"Upcoming Milestones",e.jsx(Be,{variant:"secondary",className:"text-xs font-normal",children:"Next 30 days"})]}),e.jsxs("span",{className:"text-sm text-muted-foreground",children:[x.length," event",x.length!==1?"s":""]})]})}),e.jsxs(Ie,{className:"space-y-2",children:[x.length===0&&e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(Fg,{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."})]}),x.map((C,E)=>{var D,O;const I=`${C.contact.id}-${C.type}`,P=u.has(I),R=`${((D=C.contact.first_name)==null?void 0:D[0])||""}${((O=C.contact.last_name)==null?void 0:O[0])||""}`.toUpperCase();return e.jsxs("div",{className:Pt("p-3 rounded-lg border transition-colors",C.daysUntil===0&&C.type==="birthday"?"bg-pink-500/10 border-pink-500/30 dark:bg-pink-900/20 dark:border-pink-800/40":C.daysUntil===0&&(C.type==="anniversary"||C.type==="wedding_anniversary")?"bg-blue-500/10 border-blue-500/30 dark:bg-blue-900/20 dark:border-blue-800/40":C.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(Oa,{className:Pt("h-10 w-10",C.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(za,{className:Pt("text-xs font-medium",C.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:R})}),e.jsx("span",{className:"absolute -bottom-1.5 -right-1.5 text-base leading-none drop-shadow-sm",children:C.type==="birthday"?"🎂":C.type==="wedding_anniversary"?"💍":"🏠"})]}),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:[C.contact.first_name," ",C.contact.last_name||""]}),e.jsx(Be,{variant:"outline",className:Pt("text-[10px] shrink-0 whitespace-nowrap",S(C.daysUntil)),children:w(C.daysUntil)})]}),e.jsxs("div",{className:Pt("text-xs flex items-center gap-1.5 mt-0.5",C.type==="birthday"?"text-pink-600/80 dark:text-pink-400/80":"text-blue-600/80 dark:text-blue-400/80"),children:[C.type==="birthday"?e.jsxs(e.Fragment,{children:[e.jsx(Fg,{className:"h-3 w-3"})," Birthday"]}):C.type==="wedding_anniversary"?e.jsxs(e.Fragment,{children:[e.jsx(Jo,{className:"h-3 w-3"})," Wedding Anniversary"]}):e.jsxs(e.Fragment,{children:[e.jsx(va,{className:"h-3 w-3"})," Home Anniversary"]}),e.jsx("span",{children:"·"}),e.jsx("span",{children:en(C.date,"MMM d")})]})]})]}),e.jsxs("div",{className:"flex items-center gap-1 mt-2 pl-[52px]",children:[C.contact.phone&&e.jsx($,{variant:"ghost",size:"icon",className:"h-7 w-7",title:"Call",asChild:!0,children:e.jsx("a",{href:`tel:${C.contact.phone}`,children:e.jsx(Da,{className:"h-3.5 w-3.5"})})}),C.contact.phone&&e.jsx($,{variant:"ghost",size:"icon",className:"h-7 w-7",title:"Text",asChild:!0,children:e.jsx("a",{href:`sms:${C.contact.phone}`,children:e.jsx(eo,{className:"h-3.5 w-3.5"})})}),C.contact.email&&e.jsx($,{variant:"ghost",size:"icon",className:"h-7 w-7",title:"Email",onClick:()=>{a?(o({id:C.contact.id,first_name:C.contact.first_name,last_name:C.contact.last_name,email:C.contact.email}),d(!0)):window.location.href=`mailto:${C.contact.email}`},children:e.jsx(mn,{className:"h-3.5 w-3.5"})}),e.jsx($,{variant:"ghost",size:"icon",className:"h-7 w-7",title:"Record video",onClick:()=>s(`/mission-control/video/record?contactId=${C.contact.id}`),children:e.jsx(ua,{className:"h-3.5 w-3.5"})}),e.jsxs($,{variant:"ghost",size:"sm",className:Pt("h-7 px-2 gap-1 text-xs",C.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 ${C.type==="birthday"?"birthday":"anniversary"} card`,onClick:()=>b(C),children:[e.jsx(Nn,{className:"h-3.5 w-3.5"}),e.jsx("span",{children:"Card"})]}),e.jsx($,{variant:"ghost",size:"icon",className:Pt("h-7 w-7",P&&"text-green-600"),title:"Log a touch",disabled:P||r.isPending,onClick:()=>v(C),children:e.jsx(qr,{className:"h-3.5 w-3.5"})}),e.jsx($,{variant:"ghost",size:"icon",className:"h-7 w-7",title:"View contact",onClick:()=>s(`/mission-control/contacts/${C.contact.id}`),children:e.jsx(Ca,{className:"h-3.5 w-3.5"})})]})]},`${I}-${E}`)})]})]}),a&&l&&e.jsx(Ak,{open:c,onOpenChange:d,contact:l,gmailEmail:i})]})}function OBn(s){const[t,n]=j.useState([]),[r,a]=j.useState(!1),{data:i,isLoading:l}=tt({queryKey:["active-visitors",s],queryFn:async()=>{if(!s)return[];try{await q.rpc("cleanup_stale_visitors")}catch{}const{data:u}=await q.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(!u)return[];const h=u.map(g=>g.contact_id).filter(Boolean);let m={};if(h.length>0){const{data:g}=await q.from("innercircle_contacts").select("id, first_name, last_name, email, phone").in("id",h);(g||[]).forEach(x=>{m[x.id]=x})}const f=u.map(g=>g.auth_user_id).filter(Boolean);if(f.length>0){const{data:g}=await q.from("lead_site_consumer_profiles").select("user_id, name, phone, contact_id").eq("lead_site_id",s).in("user_id",f);(g||[]).forEach(x=>{const y=u.find(v=>v.auth_user_id===x.user_id);y&&!y.contact_id&&x.contact_id&&(y.contact_id=x.contact_id),y&&!m[y.contact_id||""]&&x.name&&(m[y.contact_id||y.auth_user_id||""]={first_name:x.name.split(" ")[0],last_name:x.name.split(" ").slice(1).join(" ")||null,email:null,phone:x.phone})})}return u.map(g=>{var x,y;return{...g,contact_name:m[g.contact_id||g.auth_user_id||""]?`${m[g.contact_id||g.auth_user_id||""].first_name} ${m[g.contact_id||g.auth_user_id||""].last_name||""}`.trim():null,contact_email:((x=m[g.contact_id||g.auth_user_id||""])==null?void 0:x.email)||null,contact_phone:((y=m[g.contact_id||g.auth_user_id||""])==null?void 0:y.phone)||null}})},enabled:!!s,refetchInterval:6e4});j.useEffect(()=>{if(!s)return;const u=q.channel(`active-visitors-${s}`).on("postgres_changes",{event:"*",schema:"public",table:"lead_site_active_visitors",filter:`lead_site_id=eq.${s}`},h=>{h.eventType==="INSERT"?n(m=>m.find(g=>g.id===h.new.id)?m:[h.new,...m]):h.eventType==="UPDATE"?n(m=>m.map(f=>f.id===h.new.id?{...f,...h.new}:f)):h.eventType==="DELETE"&&n(m=>m.filter(f=>f.id!==h.old.id))}).subscribe(h=>{h==="SUBSCRIBED"&&a(!0)});return()=>{q.removeChannel(u)}},[s]);const o=r&&t.length>0?zBn([...t,...i||[]]):i||[],c=Date.now(),d=o.filter(u=>c-new Date(u.last_seen_at).getTime()<2*60*1e3);return{activeVisitors:d,isLoading:l,count:d.length}}function zBn(s){const t=new Set;return s.filter(n=>t.has(n.id)?!1:(t.add(n.id),!0))}const BBn={property_view:{label:"Viewed",icon:Ca,color:"text-blue-500",bgColor:"bg-blue-500/10"},new_lead:{label:"New Lead",icon:sc,color:"text-emerald-500",bgColor:"bg-emerald-500/10"},saved_listing:{label:"Saved",icon:Jo,color:"text-rose-500",bgColor:"bg-rose-500/10"}};function $Bn(){const{user:s}=vs(),t=Qn(),{isGmailConnected:n,gmailEmail:r}=yy(),{leadSite:a}=ng(),{count:i}=OBn(a==null?void 0:a.id),[l,o]=j.useState(!1),[c,d]=j.useState(null),{data:u,isLoading:h}=tt({queryKey:["lead-site-activity",s==null?void 0:s.id],queryFn:async()=>{const{data:v,error:b}=await q.rpc("get_lead_site_activity",{_user_id:s.id});if(b)throw b;return v},enabled:!!s,refetchInterval:6e4});if(h||!(u!=null&&u.has_site))return null;const m=(u.activities||[]).filter(v=>v.visitor_name&&v.visitor_name!=="Site Visitor"),f=m.filter(v=>v.activity_type==="new_lead"),g=(u.activities||[]).filter(v=>v.activity_type==="property_view").length,x=(u.activities||[]).filter(v=>v.activity_type==="saved_listing").length,y=v=>{if(v.visitor_email)if(n){const b=(v.visitor_name||"").split(" ");d({id:v.contact_id||"",first_name:b[0]||"",last_name:b.slice(1).join(" ")||null,email:v.visitor_email}),o(!0)}else window.location.href=`mailto:${v.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(dl,{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($,{variant:"ghost",size:"sm",className:"text-primary gap-1",onClick:()=>t("/mission-control/website-activity"),children:["View All",e.jsx(ei,{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(sc,{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:f.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(Ca,{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:g}),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(Jo,{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:x}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"Saved"})]})]})]}),m.length>0?e.jsxs("div",{className:"space-y-2",children:[m.slice(0,5).map((v,b)=>{const w=BBn[v.activity_type],S=w.icon,C=mu(new Date(v.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 ${w.bgColor}`,children:e.jsx(S,{className:`h-3.5 w-3.5 ${w.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:()=>{v.contact_id&&t(`/mission-control/contacts/${v.contact_id}`)},children:v.visitor_name}),e.jsxs("div",{className:"flex items-center gap-2 text-[11px] text-muted-foreground",children:[e.jsx("span",{children:w.label}),v.mls_number&&e.jsxs("span",{children:["· MLS# ",v.mls_number]}),v.lead_type&&e.jsxs("span",{children:["· ",v.lead_type]}),e.jsxs("span",{children:["· ",C]})]})]}),e.jsxs("div",{className:"flex items-center gap-0.5 shrink-0",children:[v.visitor_email&&e.jsx($,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0 text-primary",onClick:()=>y(v),children:e.jsx(mn,{className:"h-3.5 w-3.5"})}),v.visitor_phone&&e.jsxs(e.Fragment,{children:[e.jsx($,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0 text-primary",onClick:()=>window.location.href=`tel:${v.visitor_phone}`,children:e.jsx(Da,{className:"h-3.5 w-3.5"})}),e.jsx($,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0 text-primary",onClick:()=>window.location.href=`sms:${v.visitor_phone}`,children:e.jsx(eo,{className:"h-3.5 w-3.5"})})]}),v.contact_id&&e.jsx($,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>t(`/mission-control/contacts/${v.contact_id}`),children:e.jsx(Di,{className:"h-3.5 w-3.5"})})]})]},`${v.activity_type}-${v.occurred_at}-${b}`)}),m.length>5&&e.jsxs($,{variant:"outline",className:"w-full text-xs",onClick:()=>t("/mission-control/website-activity"),children:["View ",m.length-5," more activities",e.jsx(ei,{className:"h-3.5 w-3.5 ml-1"})]})]}):e.jsx(Ne,{children:e.jsxs(Ie,{className:"p-6 text-center",children:[e.jsx(af,{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:g>0?`${g} anonymous listing views recorded.`:"Lead engagement will appear here as visitors interact with your site."}),e.jsxs($,{variant:"outline",size:"sm",className:"mt-3",onClick:()=>t("/mission-control/website-activity"),children:["View Full Activity",e.jsx(ei,{className:"h-3.5 w-3.5 ml-1"})]})]})}),n&&c&&e.jsx(Ak,{open:l,onOpenChange:o,contact:c,gmailEmail:r})]})}const oCt={Crown:Bg,FileText:Jr,Users:Zn,Globe:dl,Star:Ja,Phone:Da,MessageSquare:eo,PenTool:RE,Video:ua,Gift:ul},UBn={"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 qBn(){var xt,rt,Yt,qt,ts,ys;const s=Qn(),{user:t}=vs(),{data:n}=Yw(),{data:r}=FUt(),{data:a}=z_(),{data:i}=iie(),{data:l}=ont(),o=tGs(),c=k6e(),d=QHs(90),u=N6e(),[h,m]=j.useState(null),[f,g]=j.useState(null),[x,y]=j.useState(!1),[v,b]=j.useState(""),[w,S]=j.useState(!1),[C,E]=j.useState(""),[I,P]=j.useState(UUt()),[R,D]=j.useState("cards"),[O,U]=j.useState(!1),[W,V]=j.useState(null),[G,Y]=j.useState(null),[X,ae]=j.useState(""),{isGmailConnected:ie,gmailEmail:ne}=yy(),te=()=>{const Bt=parseInt(C,10);if(isNaN(Bt)||Bt<1){_a({title:"Invalid goal",description:"Please enter a number greater than 0",variant:"destructive"});return}P(Bt),JHs(Bt),S(!1),_a({title:"Goal updated",description:`Weekly touch goal set to ${Bt}`})},J=()=>{E(I.toString()),S(!0)};j.useEffect(()=>{(async()=>{if(!(t!=null&&t.id))return;const{data:Ft}=await q.from("profiles").select("name").eq("id",t.id).single();Ft!=null&&Ft.name&&b(Ft.name.split(" ")[0])})()},[t==null?void 0:t.id]),j.useEffect(()=>{o.mutate()},[]);const ce=Mg(new Date),_e=Tm(ce,7),he=Bt=>{if(!Bt)return null;const Ft=Bt.split(/[-/T]/);if(Ft.length<3)return null;const rs=parseInt(Ft[1],10)-1,St=parseInt(Ft[2],10);return isNaN(rs)||isNaN(St)?null:new Date(ce.getFullYear(),rs,St)},ue=(a==null?void 0:a.filter(Bt=>{const Ft=he(Bt.birthday),rs=he(Bt.home_anniversary);return Ft&&nf(Ft,ce)||rs&&nf(rs,ce)}))||[],ve=(a==null?void 0:a.filter(Bt=>{if(!Bt.birthday&&!Bt.home_anniversary)return!1;const Ft=rs=>{if(!rs)return!1;const St=he(rs);return St?O4(St,ce)&&iC(St,_e):!1};return Ft(Bt.birthday)||Ft(Bt.home_anniversary)}).slice(0,5))||[],Ee=[],Se=(i==null?void 0:i.find(Bt=>Bt.name==="Call"))||(i==null?void 0:i[0]);for(const Bt of ue){const Ft=he(Bt.birthday),rs=he(Bt.home_anniversary),St=Ft&&nf(Ft,ce),Xs=rs&&nf(rs,ce);St&&Ee.push({contact:Bt,actionType:Se||{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:((Yt=(rt=(xt=Bt.tags)==null?void 0:xt[0])==null?void 0:rt.relationship_type)==null?void 0:Yt.name)||"",monthNumber:0,isSpecialDate:!0,specialDateType:"birthday"}),Xs&&Ee.push({contact:Bt,actionType:Se||{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:((ys=(ts=(qt=Bt.tags)==null?void 0:qt[0])==null?void 0:ts.relationship_type)==null?void 0:ys.name)||"",monthNumber:0,isSpecialDate:!0,specialDateType:"anniversary"})}const Fe=l!==void 0?l||[]:(a==null?void 0:a.slice(0,5).map((Bt,Ft)=>{var St,Xs,vt;const rs=i==null?void 0:i[Ft%((i==null?void 0:i.length)||1)];return rs?{contact:Bt,actionType:rs,planName:"Quick Touch",relationshipTypeName:((vt=(Xs=(St=Bt.tags)==null?void 0:St[0])==null?void 0:Xs.relationship_type)==null?void 0:vt.name)||"",monthNumber:0}:null}).filter(Boolean))||[],ke=[...Ee,...Fe],{data:Ve}=pK(7),je=(Ve||[]).filter(Bt=>nf(new Date(Bt.completed_at),ce)).length,Ae=je+ke.length,Ce=(a==null?void 0:a.length)??0,qe=Ee.length>0?`${Ee.length} celebration${Ee.length===1?"":"s"} today — a card or a call goes a long way.`:d.count>0?`${d.count} people haven't heard from you in 90+ days. Start with one.`:ve.length>0?`${ve.length} milestone${ve.length===1?"":"s"} coming up this week — get ahead of them.`:"Consistency beats intensity. A few real conversations today is a win.",ze=async(Bt,Ft,rs)=>{await u.mutateAsync({contactId:Bt,actionTypeId:Ft,scriptUsedId:rs}),y(!1),g(null)},$e=Bt=>{Bt.script?(g(Bt),y(!0)):ze(Bt.contact.id,Bt.actionType.id)},ct=Bt=>oCt[Bt||"Phone"]||Da,Xe=Bt=>oCt[Bt||"Users"]||Zn,it=(Bt,Ft)=>Bt.replace(/\{\{FirstName\}\}/g,Ft.first_name).replace(/\{\{LastName\}\}/g,Ft.last_name||"").replace(/\{\{AgentName\}\}/g,v||"there"),at=(Bt,Ft)=>({Call:`Thinking of you, ${Ft}!`,Text:`Quick hello, ${Ft}`,Email:`Checking in, ${Ft}`,"Handwritten Note":`A note for ${Ft}`,Video:`Video message for ${Ft}`,Gift:`Something special for you, ${Ft}`})[Bt]||`Hello ${Ft}!`,Ke=(Bt,Ft,rs)=>{const St=`sms:${Bt}`;if(Ft&&rs){const Xs=it(Ft,rs);return`${St}?body=${encodeURIComponent(Xs)}`}return St},nt=(Bt,Ft,rs,St,Xs)=>{const vt=`mailto:${Bt}`,gs=[];if(Xs){const Ss=rs||at(St||"Email",Xs.first_name);if(gs.push(`subject=${encodeURIComponent(Ss)}`),Ft){const Is=it(Ft,Xs);gs.push(`body=${encodeURIComponent(Is)}`)}}return gs.length>0?`${vt}?${gs.join("&")}`:vt};return e.jsxs(e.Fragment,{children:[e.jsxs(Vs,{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 flex-wrap items-center justify-between gap-3",children:[e.jsxs("div",{className:"flex items-center gap-2.5",children:[e.jsx("h1",{className:"text-2xl font-bold tracking-tight",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.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs($,{size:"sm",onClick:()=>s("/mission-control/video/record"),className:"gap-1.5 bg-gradient-to-r from-primary to-primary/80",children:[e.jsx(rf,{className:"h-4 w-4"}),"Quick Video"]}),e.jsxs($,{size:"sm",variant:"outline",onClick:()=>s("/mission-control/contacts"),className:"gap-1.5",children:[e.jsx(Zn,{className:"h-4 w-4"}),"Contacts"]}),e.jsxs($,{size:"sm",variant:"outline",onClick:()=>s("/mission-control/video-library"),className:"gap-1.5",children:[e.jsx(ua,{className:"h-4 w-4"}),"Library"]}),e.jsxs($,{size:"sm",variant:"outline",onClick:()=>s("/mission-control/plans"),className:"gap-1.5",children:[e.jsx(Sd,{className:"h-4 w-4"}),"Plans"]})]})]}),e.jsx(EBn,{agentName:v,todayDone:je,todayTotal:Ae,focusLine:qe,weekDone:c.actionsThisWeek,weekGoal:I,streak:c.streak,staleCount:d.count,sphereCount:Ce,onEditGoal:J,onStaleClick:()=>s("/mission-control/contacts?filter=not-touched-90"),onSphereClick:()=>s("/mission-control/contacts")}),e.jsx($Bn,{}),e.jsxs("section",{children:[e.jsxs("div",{className:"mb-3 flex items-center justify-between gap-2",children:[e.jsx("h2",{className:"text-sm font-semibold uppercase tracking-wide text-muted-foreground",children:"Your Sphere"}),e.jsxs("button",{onClick:()=>s("/mission-control/contacts"),className:"inline-flex items-center gap-1 text-xs font-medium text-primary hover:underline",children:["View all ",e.jsx(Di,{className:"h-3 w-3"})]})]}),e.jsx("div",{className:"flex flex-wrap gap-2",children:n==null?void 0:n.filter(Bt=>Bt.active).map(Bt=>{const Ft=Xe(Bt.icon),rs=(r==null?void 0:r[Bt.id])||0,St=h===Bt.id,Xs=UBn[Bt.name]||"bg-secondary text-secondary-foreground";return e.jsxs("button",{onClick:()=>{St?(m(null),s("/mission-control/contacts")):(m(Bt.id),s(`/mission-control/contacts?type=${Bt.id}`))},className:` inline-flex items-center gap-2 rounded-full border px-3 py-1.5 text-sm transition-all ${St?Xs:"bg-card hover:bg-accent"} `,children:[e.jsx(Ft,{className:"h-3.5 w-3.5"}),e.jsx("span",{className:"font-medium",children:Bt.name}),e.jsx("span",{className:`rounded-full px-1.5 py-0.5 text-[11px] tabular-nums ${St?"bg-black/15":"bg-muted text-muted-foreground"}`,children:rs})]},Bt.id)})})]}),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(Be,{variant:"outline",className:"gap-1",children:[e.jsx(Nn,{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($,{variant:R==="cards"?"secondary":"ghost",size:"sm",className:"h-7 px-2",onClick:()=>D("cards"),title:"Card view",children:e.jsx(Qf,{className:"h-4 w-4"})}),e.jsx($,{variant:R==="table"?"secondary":"ghost",size:"sm",className:"h-7 px-2",onClick:()=>D("table"),title:"Table view",children:e.jsx(P0,{className:"h-4 w-4"})})]})]}),e.jsx(Ne,{children:e.jsx(Ie,{className:"p-4",children:ke.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($,{variant:"outline",className:"mt-4",onClick:()=>s("/mission-control/plans"),children:"Manage Plans"})]}):R==="table"?e.jsx(DBn,{actions:ke,onMarkComplete:ze,onViewScript:$e,isLoading:u.isPending,buildSmsLink:Ke,buildEmailLink:nt,onGmailCompose:ie?Bt=>{V(Bt),U(!0)}:void 0}):e.jsxs("div",{className:"flex gap-3 overflow-x-auto pb-2",children:[ke.map((Bt,Ft)=>{var Ys,cs,js,kn,Ws,On,ds;const rs=Bt.isSpecialDate,St=Bt.specialDateType,Xs=rs?St==="birthday"?Fg:va:ct(((Ys=Bt.actionType)==null?void 0:Ys.icon)||null),vt=Bt.contact.phone,gs=Bt.contact.email,Ss=rs?St==="birthday"?"#EC4899":"#8B5CF6":((cs=Bt.actionType)==null?void 0:cs.color)||"#3B82F6",Is=rs?St==="birthday"?"🎂 Birthday Today!":"🏠 Home Anniversary!":(js=Bt.actionType)==null?void 0:js.name;return e.jsxs("div",{className:`flex-shrink-0 w-[260px] border rounded-lg overflow-hidden ${rs?"ring-2 ring-offset-2":""}`,style:rs?{"--tw-ring-color":Ss}:void 0,children:[e.jsxs("div",{className:"p-3 text-white flex items-center gap-2",style:{backgroundColor:Ss},children:[e.jsx(Xs,{className:"h-4 w-4"}),e.jsx("span",{className:"font-medium text-sm",children:Is})]}),e.jsxs("div",{className:"p-3 space-y-2",children:[e.jsxs("button",{onClick:()=>s(`/mission-control/contacts/${Bt.contact.id}`),className:"font-medium text-sm hover:text-primary hover:underline transition-colors text-left",children:[Bt.contact.first_name," ",Bt.contact.last_name]}),e.jsxs("div",{className:"flex gap-1.5",children:[vt&&e.jsxs(e.Fragment,{children:[e.jsxs("a",{href:`tel:${Bt.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(Da,{className:"h-3 w-3"}),"Call"]}),e.jsxs("a",{href:Ke(Bt.contact.phone,(kn=Bt.script)==null?void 0:kn.script_body,Bt.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(eo,{className:"h-3 w-3"}),"Text"]})]}),gs&&(ie?e.jsxs("button",{onClick:()=>{V({id:Bt.contact.id,first_name:Bt.contact.first_name,last_name:Bt.contact.last_name,email:Bt.contact.email}),U(!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(mn,{className:"h-3 w-3"}),"Email"]}):e.jsxs("a",{href:nt(Bt.contact.email,(Ws=Bt.script)==null?void 0:Ws.script_body,(On=Bt.script)==null?void 0:On.email_subject,(ds=Bt.actionType)==null?void 0:ds.name,Bt.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(mn,{className:"h-3 w-3"}),"Email"]}))]}),rs&&e.jsxs("button",{onClick:()=>{const gn=`${Bt.contact.first_name}${Bt.contact.last_name?" "+Bt.contact.last_name:""}`,As=St==="birthday"?"birthday":"home_anniversary",hr=new URLSearchParams({cardType:As,contactId:Bt.contact.id,name:gn,...Bt.contact.address?{address:Bt.contact.address}:{},...St==="anniversary"&&Bt.contact.home_anniversary?{date:Bt.contact.home_anniversary}:{}});s(`/mission-control/card-studio?${hr.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(mn,{className:"h-3 w-3"}),"Send ",St==="birthday"?"Birthday":"Anniversary"," Card"]}),!vt&&!gs&&e.jsx("p",{className:"text-xs text-muted-foreground italic",children:"No contact info"}),e.jsxs("div",{className:"flex gap-1 flex-wrap",children:[Bt.relationshipTypeName&&e.jsx(Be,{variant:"secondary",className:"text-xs",children:Bt.relationshipTypeName}),Bt.monthNumber>0&&e.jsxs(Be,{variant:"outline",className:"text-xs",children:["Month ",Bt.monthNumber]})]}),Bt.script&&e.jsx($,{size:"sm",variant:"outline",className:"w-full",onClick:()=>$e(Bt),children:"View Script"}),e.jsxs("div",{className:"flex gap-1.5",children:[e.jsxs($,{size:"sm",variant:"outline",className:"flex-1 gap-1",onClick:()=>{Y(Bt.contact.id),ae(`${Bt.contact.first_name} ${Bt.contact.last_name||""}`.trim())},children:[e.jsx(Tv,{className:"h-3.5 w-3.5"}),"Snooze"]}),e.jsx($,{size:"sm",className:"flex-1",onClick:()=>{var gn;return ze(Bt.contact.id,Bt.actionType.id,(gn=Bt.script)==null?void 0:gn.id)},disabled:u.isPending,children:"Mark Complete"})]})]})]},Bt.contact.id+Ft)}),e.jsx("div",{className:"flex-shrink-0 w-[100px] border rounded-lg flex items-center justify-center",children:e.jsxs(Uu,{children:[e.jsx(qu,{asChild:!0,children:e.jsxs($,{variant:"ghost",className:"h-full w-full",children:[e.jsx(h_,{className:"h-5 w-5 mr-2"}),"More"]})}),e.jsx(Eu,{children:e.jsx(ja,{onClick:()=>s("/mission-control/contacts"),children:"View all contacts"})})]})})]})})})]}),e.jsxs("div",{className:"rounded-2xl border bg-card p-4",children:[e.jsxs("div",{className:"mb-2 flex items-center justify-between gap-2",children:[e.jsxs("span",{className:"inline-flex items-center gap-1.5 text-[11px] font-medium uppercase tracking-wide text-muted-foreground",children:[e.jsx(nh,{className:"h-3.5 w-3.5 text-orange-500"}),"This week's momentum"]}),e.jsxs("span",{className:"text-xs tabular-nums text-muted-foreground",children:[c.actionsThisWeek," of ",I," touches"]})]}),e.jsx(Yi,{value:Math.min(c.actionsThisWeek/I*100,100),className:"h-2.5 w-full max-w-full"}),e.jsx("p",{className:"mt-2 text-xs text-muted-foreground",children:c.actionsThisWeek>=I?"Goal hit for the week — anything else is bonus.":`${I-c.actionsThisWeek} more to hit your goal.`})]}),e.jsx(zs,{open:w,onOpenChange:S,children:e.jsxs(Os,{className:"sm:max-w-[360px]",children:[e.jsxs(Us,{children:[e.jsx(Bs,{children:"Set Weekly Goal"}),e.jsx(Ir,{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(ee,{htmlFor:"weekly-goal-ic",children:"Weekly touch goal"}),e.jsx(pe,{id:"weekly-goal-ic",type:"number",min:"1",value:C,onChange:Bt=>E(Bt.target.value),placeholder:"20",onKeyDown:Bt=>{Bt.key==="Enter"&&te()}})]}),e.jsx($,{onClick:te,className:"w-full",children:"Save Goal"})]})]})}),e.jsxs("div",{className:"grid md:grid-cols-2 gap-6",children:[e.jsx(iqt,{}),e.jsx(FBn,{})]})]}),e.jsx(zs,{open:x,onOpenChange:y,children:e.jsxs(Os,{className:"max-w-md",children:[e.jsx(Us,{children:e.jsx(Bs,{className:"flex items-center gap-2",children:f&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"w-3 h-3 rounded-full",style:{backgroundColor:f.actionType.color||"#3B82F6"}}),f.actionType.name," Script"]})})}),f&&f.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:[f.contact.first_name," ",f.contact.last_name]})]}),e.jsx("div",{className:"bg-muted p-4 rounded-lg",children:e.jsx("p",{className:"whitespace-pre-wrap",children:it(f.script.script_body,f.contact)})}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx($,{variant:"outline",className:"flex-1",onClick:()=>y(!1),children:"Close"}),e.jsx($,{className:"flex-1",onClick:()=>{var Bt;return ze(f.contact.id,f.actionType.id,(Bt=f.script)==null?void 0:Bt.id)},disabled:u.isPending,children:"Mark Complete"})]})]})]})}),e.jsx(TBn,{})]}),ie&&W&&e.jsx(Ak,{open:O,onOpenChange:U,contact:W,gmailEmail:ne}),e.jsx(lDe,{open:!!G,onOpenChange:Bt=>!Bt&&Y(null),contactId:G||"",contactName:X})]})}const qN=s=>(s||"").trim(),LQt=["Home","Vacation home","Work","Mailing","Rental"];function lCt(s){return s?!!(qN(s.address2)||qN(s.address2_city)):!1}function VBn(s){const t=qN(s==null?void 0:s.address),n=qN(s==null?void 0:s.city);return{line:t,city:n,state:qN(s==null?void 0:s.state),zip:qN(s==null?void 0:s.zip_code)||qN(s==null?void 0:s.zip),label:"Home",isSecondary:!1,hasAddress:!!(t||n)}}function FYe(s){const t=qN(s==null?void 0:s.address2),n=qN(s==null?void 0:s.address2_city);return{line:t,city:n,state:qN(s==null?void 0:s.address2_state),zip:qN(s==null?void 0:s.address2_zip),label:qN(s==null?void 0:s.address2_label)||"Second address",isSecondary:!0,hasAddress:!!(t||n)}}function oX(s){const t=FYe(s);return s!=null&&s.mail_to_secondary&&t.hasAddress?t:VBn(s)}function HBn(s){const t=[s.city,s.state].filter(Boolean).join(", ");return[s.line,[t,s.zip].filter(Boolean).join(" ")].filter(Boolean).join(", ")}const GBn=[{value:"bidirectional",label:"Two-Way",icon:By,tooltip:"Sync contacts in both directions"},{value:"push_only",label:"Push Only",icon:Zf,tooltip:"Only push Agent OS → BoldTrail"},{value:"pull_only",label:"Pull Only",icon:Dg,tooltip:"Only pull BoldTrail → Agent OS"}];function ePe({value:s,onChange:t,size:n="default"}){const r=n==="sm"?"text-xs":"text-sm";return e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("p",{className:`font-medium ${r} text-muted-foreground`,children:"Sync Direction"}),e.jsx(EV,{type:"single",value:s,onValueChange:a=>{a&&t(a)},className:"justify-start",children:GBn.map(a=>e.jsxs(ly,{children:[e.jsx(cy,{asChild:!0,children:e.jsxs(_7,{value:a.value,"aria-label":a.tooltip,className:`gap-1.5 ${r} 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:n==="sm"?"h-3 w-3":"h-4 w-4"}),a.label]})}),e.jsx(Nx,{children:a.tooltip})]},a.value))})]})}function WBn(){const s=Vt(),[t,n]=j.useState(!1),[r,a]=j.useState(null),[i,l]=j.useState(!1),[o,c]=j.useState(!1),[d,u]=j.useState(null),[h,m]=j.useState(null),[f,g]=j.useState(0),x=j.useRef(!1),{data:y}=tt({queryKey:["boldtrail-status"],queryFn:async()=>{const{data:R,error:D}=await q.functions.invoke("boldtrail-sync",{body:{action:"status"}});if(D)throw D;return R}}),v=(y==null?void 0:y.sync_direction)||"bidirectional",b=d??v,w=ft({mutationFn:async()=>{const{data:R,error:D}=await q.functions.invoke("boldtrail-sync",{body:{action:"sync_preview"}});if(D)throw D;if(R!=null&&R.error)throw new Error(R.error);return R},onSuccess:R=>{u(null),a(R),n(!0)},onError:R=>{re.error(R.message||"Failed to generate sync preview")}}),S=ft({mutationFn:async()=>{x.current=!1,m("Initializing sync..."),g(5);const{data:R,error:D}=await q.functions.invoke("boldtrail-sync",{body:{action:"sync",phase:"init",sync_direction:b}});if(D)throw D;if(R!=null&&R.error)throw new Error(R.error);const O=R;let U=O.sync_log_id,W=O.next_phase,V=O.next_offset,G=O.push_total||0,Y=O.pull_total||0,X=O.update_total||0,ae=0,ie=0,ne=0;for(;W!=="finalize"&&!x.current;){const ce=G+Y+X;W==="fetch_bt"?m("Fetching BoldTrail contacts..."):W==="analyze"?(m("Analyzing contacts..."),g(15)):W==="push"?(m(`Pushing contacts to BoldTrail... (${ae}/${G})`),g(ce>0?ae/ce*90:0)):W==="pull"?(m(`Pulling contacts from BoldTrail... (${ie}/${Y})`),g(ce>0?(G+ie)/ce*90:0)):W==="update"&&(m(`Updating existing contacts... (${ne}/${X})`),g(ce>0?(G+Y+ne)/ce*90:0));const{data:_e,error:he}=await q.functions.invoke("boldtrail-sync",{body:{action:"sync",phase:W,offset:V,sync_log_id:U,sync_direction:b}});if(he)throw he;if(_e!=null&&_e.error)throw new Error(_e.error);const ue=_e;ae+=ue.chunk_pushed||0,ie+=ue.chunk_pulled||0,ne+=ue.chunk_updated||0,ue.push_total!==void 0&&(G=ue.push_total||0),ue.pull_total!==void 0&&(Y=ue.pull_total||0),ue.update_total!==void 0&&(X=ue.update_total||0),ue.progress&&m(ue.progress),W=ue.next_phase,V=ue.next_offset}m("Finalizing sync..."),g(95);const{data:te,error:J}=await q.functions.invoke("boldtrail-sync",{body:{action:"sync",phase:"finalize",sync_log_id:U,sync_direction:b}});if(J)throw J;return g(100),te},onSuccess:R=>{m(null),g(0),n(!1),s.invalidateQueries({queryKey:["boldtrail-status"]}),s.invalidateQueries({queryKey:["innercircle-contacts"]}),s.invalidateQueries({queryKey:["innercircle-contact-counts"]}),s.invalidateQueries({queryKey:["contacts-last-touch"]});const D=[`Pushed ${R.contacts_pushed||0}`,`pulled ${R.contacts_pulled||0}`,`updated ${R.contacts_updated||0}`,`skipped ${R.contacts_skipped||0} duplicates`];re.success(`Sync complete! ${D.join(", ")}.`)},onError:R=>{m(null),g(0),re.error(R.message||"Sync failed")}});if(!(y!=null&&y.connected))return null;const C=b==="pull_only"?0:(r==null?void 0:r.to_push)??0,E=b==="push_only"?0:(r==null?void 0:r.to_pull)??0,I=(r==null?void 0:r.to_update)??0,P=C>0||E>0||I>0;return e.jsxs(e.Fragment,{children:[e.jsxs(ly,{children:[e.jsx(cy,{asChild:!0,children:e.jsx($,{variant:"outline",size:"icon",onClick:()=>w.mutate(),disabled:w.isPending,className:"shrink-0",children:w.isPending?e.jsx(ro,{className:"h-4 w-4 animate-spin"}):e.jsx(By,{className:"h-4 w-4 text-emerald-600"})})}),e.jsx(Nx,{children:"Sync with BoldTrail"})]}),e.jsx(zs,{open:t,onOpenChange:R=>{S.isPending||n(R)},children:e.jsxs(Os,{className:"sm:max-w-lg",children:[e.jsxs(Us,{children:[e.jsxs(Bs,{className:"flex items-center gap-2",children:[e.jsx(By,{className:"h-5 w-5 text-emerald-600"}),"Sync Preview"]}),e.jsx(Ir,{children:"Review what will happen when you sync your contacts."})]}),r&&e.jsxs("div",{className:"space-y-4",children:[e.jsx(ePe,{value:b,onChange:u,size:"sm"}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:`rounded-lg border p-3 text-center ${b==="pull_only"?"opacity-40":""}`,children:[e.jsx("p",{className:"text-2xl font-bold text-emerald-600",children:C}),e.jsxs("p",{className:"text-xs text-muted-foreground flex items-center justify-center gap-1",children:[e.jsx(Zf,{className:"h-3 w-3"})," Push to BoldTrail"]})]}),e.jsxs("div",{className:`rounded-lg border p-3 text-center ${b==="push_only"?"opacity-40":""}`,children:[e.jsx("p",{className:"text-2xl font-bold text-blue-600",children:E}),e.jsxs("p",{className:"text-xs text-muted-foreground flex items-center justify-center gap-1",children:[e.jsx(Dg,{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:I}),e.jsxs("p",{className:"text-xs text-muted-foreground flex items-center justify-center gap-1",children:[e.jsx(eV,{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:r.already_synced}),e.jsxs("p",{className:"text-xs text-muted-foreground flex items-center justify-center gap-1",children:[e.jsx(Zn,{className:"h-3 w-3"})," Already synced"]})]})]}),e.jsxs("div",{className:"text-xs text-muted-foreground text-center",children:["Agent OS: ",r.agent_os_total," contacts · BoldTrail: ",r.boldtrail_total," contacts"]}),I>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(eV,{className:"h-3 w-3 inline mr-1"}),I," contacts have missing fields that will be filled from the other system"]}),C>0&&e.jsxs(j1,{open:i,onOpenChange:l,children:[e.jsx(N1,{asChild:!0,children:e.jsxs($,{variant:"ghost",size:"sm",className:"w-full justify-between text-xs",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Zf,{className:"h-3 w-3 text-emerald-600"}),C," contacts to push to BoldTrail"]}),e.jsx(Tl,{className:`h-3 w-3 transition-transform ${i?"rotate-180":""}`})]})}),e.jsx(k1,{children:e.jsxs("div",{className:"rounded border divide-y max-h-40 overflow-y-auto",children:[r.push_preview.map((R,D)=>e.jsxs("div",{className:"px-3 py-1.5 text-xs flex justify-between",children:[e.jsx("span",{className:"font-medium",children:R.name||"No name"}),e.jsx("span",{className:"text-muted-foreground",children:R.email})]},D)),r.to_push>20&&e.jsxs("div",{className:"px-3 py-1.5 text-xs text-muted-foreground text-center",children:["...and ",r.to_push-20," more"]})]})})]}),E>0&&e.jsxs(j1,{open:o,onOpenChange:c,children:[e.jsx(N1,{asChild:!0,children:e.jsxs($,{variant:"ghost",size:"sm",className:"w-full justify-between text-xs",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Dg,{className:"h-3 w-3 text-blue-600"}),E," contacts to pull from BoldTrail"]}),e.jsx(Tl,{className:`h-3 w-3 transition-transform ${o?"rotate-180":""}`})]})}),e.jsx(k1,{children:e.jsxs("div",{className:"rounded border divide-y max-h-40 overflow-y-auto",children:[r.pull_preview.map((R,D)=>e.jsxs("div",{className:"px-3 py-1.5 text-xs flex justify-between",children:[e.jsx("span",{className:"font-medium",children:R.name||"No name"}),e.jsx("span",{className:"text-muted-foreground",children:R.email})]},D)),r.to_pull>20&&e.jsxs("div",{className:"px-3 py-1.5 text-xs text-muted-foreground text-center",children:["...and ",r.to_pull-20," more"]})]})})]}),!P&&!S.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."}),S.isPending&&e.jsxs("div",{className:"space-y-2 py-2",children:[e.jsx(Yi,{value:f||10,className:"h-2"}),e.jsx("p",{className:"text-xs text-muted-foreground text-center",children:h||"Sync in progress..."})]}),e.jsxs("div",{className:"flex gap-2 justify-end pt-2",children:[e.jsx($,{variant:"outline",onClick:()=>n(!1),disabled:S.isPending,children:"Cancel"}),e.jsxs($,{onClick:()=>S.mutate(),disabled:S.isPending||!P,className:"gap-2",children:[S.isPending?e.jsx(ro,{className:"h-4 w-4 animate-spin"}):e.jsx(By,{className:"h-4 w-4"}),S.isPending?"Syncing...":"Sync Now"]})]})]})]})})]})}const KBn=[{key:"first_name",label:"First name"},{key:"last_name",label:"Last name"},{key:"email",label:"Email"},{key:"phone",label:"Phone"},{key:"address",label:"Street address"},{key:"city",label:"City"},{key:"state",label:"State"},{key:"zip",label:"ZIP"},{key:"birthday",label:"Birthday"},{key:"home_anniversary",label:"Home anniversary"},{key:"wedding_anniversary",label:"Wedding anniversary"},{key:"spouse_name",label:"Spouse name"},{key:"spouse_email",label:"Spouse email"},{key:"spouse_birthday",label:"Spouse birthday"},{key:"company_name",label:"Company"},{key:"job_title",label:"Job title"},{key:"lead_source",label:"Lead source"},{key:"avatar_url",label:"Photo"}],YBn="id, first_name, last_name, email, phone, address, city, state, zip, birthday, home_anniversary, wedding_anniversary, spouse_name, spouse_email, spouse_birthday, company_name, job_title, lead_source, avatar_url, notes, created_at, updated_at";function tPe(s){return Object.entries(s).filter(([t,n])=>t!=="id"&&n!==null&&n!==void 0&&String(n).trim()!=="").length}function ZBn(s){return tt({queryKey:["contact-duplicates"],enabled:s,staleTime:6e4,queryFn:async()=>{const{data:t,error:n}=await q.rpc("find_duplicate_contacts",{_limit:200});if(n)throw n;return(t??[]).map(r=>({match_type:r.match_type,match_value:r.match_value,contact_ids:r.contact_ids??[],contacts:r.contacts??[]}))}})}function XBn(s,t){return tt({queryKey:["merge-candidates",[...s].sort().join(",")],enabled:t&&s.length>1,queryFn:async()=>{const{data:n,error:r}=await q.from("innercircle_contacts").select(YBn).in("id",s);if(r)throw r;return n??[]}})}function RQt(){const s=Vt();return ft({mutationFn:async({primaryId:t,duplicateIds:n,overrides:r})=>{if(r&&Object.keys(r).length>0){const{error:l}=await q.from("innercircle_contacts").update({...r,updated_at:new Date().toISOString()}).eq("id",t);if(l)throw l}const a=[];let i=0;for(const l of n){if(l===t)continue;const{error:o}=await q.rpc("merge_innercircle_contacts",{_primary_id:t,_duplicate_id:l});o?a.push({id:l,message:o.message}):i+=1}return{merged:i,failed:a}},onSuccess:()=>{s.invalidateQueries({queryKey:["innercircle-contacts"]}),s.invalidateQueries({queryKey:["innercircle-contact-counts"]}),s.invalidateQueries({queryKey:["all-contact-custom-tags"]}),s.invalidateQueries({queryKey:["contact-duplicates"]})}})}function cCt(s){return[s.first_name,s.last_name].filter(Boolean).join(" ")||"Unnamed contact"}function lue(s,t){const n=s==null?void 0:s[t];return n==null||String(n).trim()===""?null:String(n)}function DQt({open:s,onOpenChange:t,contactIds:n,onMerged:r}){const{data:a,isLoading:i}=XBn(n,s),l=RQt(),[o,c]=j.useState(null),[d,u]=j.useState({}),h=j.useMemo(()=>a??[],[a]);j.useEffect(()=>{if(!s){c(y=>y===null?y:null),u(y=>Object.keys(y).length===0?y:{});return}if(h.length&&!o){const y=[...h].sort((v,b)=>tPe(b)-tPe(v))[0];c(y.id)}},[s,h,o]),j.useEffect(()=>{u(y=>Object.keys(y).length===0?y:{})},[o]);const m=j.useMemo(()=>KBn.map(y=>{const v=h.map(w=>({id:w.id,value:lue(w,y.key)})).filter(w=>w.value!==null),b=Array.from(new Set(v.map(w=>w.value)));return{...y,values:v,distinct:b}}).filter(y=>y.distinct.length>1),[h]),f=h.find(y=>y.id===o)??null,g=async()=>{if(!f)return;const y={};for(const[v,b]of Object.entries(d)){const w=h.find(C=>C.id===b);if(!w)continue;const S=lue(w,v);S!==null&&S!==lue(f,v)&&(y[v]=w[v])}try{const v=await l.mutateAsync({primaryId:f.id,duplicateIds:h.filter(b=>b.id!==f.id).map(b=>b.id),overrides:y});v.failed.length?_a({title:`Merged ${v.merged} of ${v.merged+v.failed.length}`,description:v.failed[0].message,variant:"destructive"}):_a({title:`Merged into ${cCt(f)}`,description:"Nothing in their history was lost."}),t(!1),r==null||r()}catch(v){_a({title:"Could not merge",description:v.message,variant:"destructive"})}},x=n.length>10;return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Os,{className:"max-w-3xl max-h-[90vh] flex flex-col",children:[e.jsxs(Us,{children:[e.jsxs(Bs,{className:"flex items-center gap-2",children:[e.jsx(Xz,{className:"h-4 w-4"}),"Merge contacts"]}),e.jsx(Ir,{children:"Choose the record to keep, then pick which details win. Notes, tags, history, deals and tasks from every record stay with the contact you keep."})]}),x?e.jsx("p",{className:"py-6 text-sm text-muted-foreground",children:"You can merge up to 10 contacts at a time. Please narrow your selection."}):i?e.jsx("div",{className:"flex items-center justify-center py-10",children:e.jsx(kt,{className:"h-5 w-5 animate-spin text-muted-foreground"})}):h.length<2?e.jsx("p",{className:"py-6 text-sm text-muted-foreground",children:"Pick at least two contacts to merge."}):e.jsx(uo,{className:"flex-1 -mx-2 px-2",children:e.jsxs("div",{className:"space-y-5 pb-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-sm font-medium",children:"Which record should we keep?"}),e.jsx("div",{className:"grid gap-2 sm:grid-cols-2",children:h.map(y=>e.jsxs("button",{type:"button",onClick:()=>c(y.id),className:`rounded-lg border p-3 text-left transition-colors ${o===y.id?"border-primary bg-primary/5":"hover:bg-accent"}`,children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("span",{className:"font-medium truncate",children:cCt(y)}),o===y.id&&e.jsx(Be,{variant:"secondary",children:"Keep"})]}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:y.email||"No email"}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:y.phone||"No phone"}),y.created_at&&e.jsxs("p",{className:"mt-1 text-[11px] text-muted-foreground",children:["Added ",new Date(String(y.created_at)).toLocaleDateString()]})]},y.id))})]}),m.length>0&&e.jsxs("div",{className:"space-y-3",children:[e.jsx("p",{className:"text-sm font-medium",children:"These details differ — pick what to keep"}),m.map(y=>{var b;const v=d[y.key]??(f&&lue(f,y.key)!==null?f.id:(b=y.values[0])==null?void 0:b.id);return e.jsxs("div",{className:"rounded-lg border p-3",children:[e.jsx("p",{className:"mb-2 text-xs uppercase tracking-wide text-muted-foreground",children:y.label}),e.jsx("div",{className:"flex flex-wrap gap-2",children:y.values.map(w=>e.jsx("button",{type:"button",onClick:()=>u(S=>({...S,[y.key]:w.id})),className:`rounded-md border px-2.5 py-1.5 text-sm transition-colors ${v===w.id?"border-primary bg-primary/10 font-medium":"hover:bg-accent text-muted-foreground"}`,children:w.value},w.id))})]},y.key)})]}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:["1 contact will be kept, ",h.length-1," will be removed. Nothing in their history is lost."]})]})}),e.jsxs(Ar,{children:[e.jsx($,{variant:"outline",onClick:()=>t(!1),disabled:l.isPending,children:"Cancel"}),e.jsxs($,{onClick:g,disabled:!f||h.length<2||x||l.isPending,children:[l.isPending&&e.jsx(kt,{className:"mr-2 h-4 w-4 animate-spin"}),"Merge — this can't be undone"]})]})]})})}const QBn={email:"Same email",phone:"Same phone",name:"Same name"};function JBn(s){return[s.first_name,s.last_name].filter(Boolean).join(" ")||"Unnamed contact"}function e9n({open:s,onOpenChange:t}){const{data:n,isLoading:r,isError:a,error:i}=ZBn(s),l=RQt(),[o,c]=j.useState(new Set),[d,u]=j.useState(null),[h,m]=j.useState(!1),f=j.useMemo(()=>(n??[]).filter(y=>y.contact_ids.length>1&&!o.has(y.contact_ids.join(","))),[n,o]),g=f.filter(y=>y.match_type!=="name"),x=async()=>{m(!0);let y=0,v=0;try{for(const b of g){const w=[...b.contacts].sort((E,I)=>tPe(I)-tPe(E))[0],S=(w==null?void 0:w.id)??b.contact_ids[0],C=await l.mutateAsync({primaryId:S,duplicateIds:b.contact_ids.filter(E=>E!==S)});y+=C.merged,v+=C.failed.length}_a({title:`Merged ${y} duplicate${y===1?"":"s"}`,description:v?`${v} could not be merged.`:"Name-only matches still need your review.",variant:v?"destructive":void 0})}catch(b){_a({title:"Could not finish merging",description:b.message,variant:"destructive"})}finally{m(!1)}};return e.jsxs(e.Fragment,{children:[e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Os,{className:"flex h-[90dvh] max-h-[90dvh] max-w-2xl flex-col overflow-hidden",children:[e.jsxs(Us,{className:"shrink-0",children:[e.jsx(Bs,{children:"Find duplicates"}),e.jsx(Ir,{children:"We looked through your whole database for contacts that share an email, a phone number, or a name."})]}),r?e.jsx("div",{className:"flex items-center justify-center py-10",children:e.jsx(kt,{className:"h-5 w-5 animate-spin text-muted-foreground"})}):a?e.jsx("p",{className:"py-6 text-sm text-destructive",children:(i==null?void 0:i.message)??"Could not check for duplicates."}):f.length===0?e.jsx("p",{className:"py-8 text-center text-sm text-muted-foreground",children:"No duplicates found. Your database looks clean."}):e.jsx("div",{className:"min-h-0 flex-1 -mx-2 overflow-y-auto overscroll-contain px-2 pr-3 touch-pan-y",children:e.jsx("div",{className:"space-y-3 pb-2",children:f.map(y=>{const v=y.contact_ids.join(",");return e.jsxs("div",{className:"rounded-lg border p-3",children:[e.jsxs("div",{className:"mb-2 flex items-center gap-2",children:[e.jsx(Be,{variant:"secondary",children:QBn[y.match_type]}),e.jsx("span",{className:"truncate text-xs text-muted-foreground",children:y.match_value}),e.jsxs("span",{className:"ml-auto text-xs text-muted-foreground",children:[y.contact_ids.length," records"]})]}),e.jsx("div",{className:"space-y-1",children:y.contacts.map(b=>e.jsxs("div",{className:"flex flex-wrap items-center gap-x-3 text-sm",children:[e.jsx("span",{className:"font-medium",children:JBn(b)}),b.email&&e.jsx("span",{className:"text-muted-foreground",children:b.email}),b.phone&&e.jsx("span",{className:"text-muted-foreground",children:b.phone}),b.created_at&&e.jsxs("span",{className:"text-xs text-muted-foreground",children:["added ",new Date(String(b.created_at)).toLocaleDateString()]})]},b.id))}),e.jsxs("div",{className:"mt-3 flex gap-2",children:[e.jsx($,{size:"sm",onClick:()=>u(y.contact_ids),children:"Review & merge"}),e.jsx($,{size:"sm",variant:"ghost",onClick:()=>c(b=>new Set(b).add(v)),children:"Not a duplicate"})]})]},`${y.match_type}-${v}`)})})}),e.jsxs(Ar,{className:"shrink-0 gap-2 sm:justify-between",children:[e.jsx($,{variant:"outline",onClick:()=>t(!1),disabled:h,children:"Close"}),g.length>0&&e.jsxs($,{onClick:x,disabled:h,children:[h?e.jsx(kt,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(Nn,{className:"mr-2 h-4 w-4"}),"Merge all safe matches (",g.length,")"]})]})]})}),e.jsx(DQt,{open:!!d,onOpenChange:y=>{y||u(null)},contactIds:d??[]})]})}const t9n=()=>{const{user:s}=vs();return tt({queryKey:["popby-items",s==null?void 0:s.id],queryFn:async()=>{const{data:t,error:n}=await q.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(n)throw n;return t},enabled:!!s})},cDe=s=>{const{user:t}=vs();return tt({queryKey:["popby-logs",t==null?void 0:t.id,s],queryFn:async()=>{let n=q.from("popby_logs").select("*").order("completed_at",{ascending:!1});if(s){const i=new Date;i.setDate(i.getDate()-s),n=n.gte("completed_at",i.toISOString())}const{data:r,error:a}=await n;if(a)throw a;return r},enabled:!!t})},wit=()=>{const{user:s}=vs();return tt({queryKey:["relationship-type-popby-defaults",s==null?void 0:s.id],queryFn:async()=>{const{data:t,error:n}=await q.from("relationship_type_popby_defaults").select("*");if(n)throw n;return t},enabled:!!s})},FQt=()=>{const{user:s}=vs();return tt({queryKey:["contact-popby-settings",s==null?void 0:s.id],queryFn:async()=>{const{data:t,error:n}=await q.from("contact_popby_settings").select("*");if(n)throw n;return t},enabled:!!s})},s9n=()=>{const{data:s}=z_(),{data:t}=Yw(),{data:n}=cDe(),{data:r}=FQt(),{data:a}=wit(),i=new Map;n==null||n.forEach(u=>{const h=i.get(u.contact_id);(!h||new Date(u.completed_at)>new Date(h))&&i.set(u.contact_id,u.completed_at)});const l=new Map;a==null||a.forEach(u=>l.set(u.relationship_type_id,u.frequency_days));const o=new Map;r==null||r.filter(u=>u.is_active).forEach(u=>{o.set(u.contact_id,u.frequency_days)});const c=Mg(new Date);return(s||[]).map(u=>{let h=90;if(o.has(u.id))h=o.get(u.id);else if(u.tags&&u.tags.length>0){const y=u.tags.map(v=>l.get(v.relationship_type_id)).filter(v=>v!==void 0);y.length>0&&(h=Math.min(...y))}const m=i.get(u.id)||null,f=m?mk(c,Mg(new Date(m))):null,g=f===null||f>=h,x=g&&f!==null?f-h:0;return{...u,lastPopby:m,daysSinceLastPopby:f,frequencyDays:h,isDue:g,daysOverdue:x}}).sort((u,h)=>h.daysOverdue-u.daysOverdue)},OQt=()=>s9n().filter(t=>t.isDue),n9n=()=>{const s=Vt(),{user:t}=vs();return ft({mutationFn:async n=>{const{error:r}=await q.from("popby_items").insert({...n,owner_user_id:t==null?void 0:t.id});if(r)throw r},onSuccess:()=>{s.invalidateQueries({queryKey:["popby-items"]}),_a({title:"Popby item created!"})},onError:n=>{_a({title:"Error creating popby item",description:n.message,variant:"destructive"})}})},r9n=()=>{const s=Vt(),{user:t}=vs();return ft({mutationFn:async n=>{const r=new Date().toISOString(),{error:a}=await q.from("popby_logs").insert({...n,owner_user_id:t==null?void 0:t.id,completed_at:r});if(a)throw a;try{const{data:i}=await q.from("action_types").select("id").ilike("name","Pop-By").eq("active",!0).maybeSingle();i!=null&&i.id&&await q.from("contact_touch_logs").insert({owner_user_id:t==null?void 0:t.id,contact_id:n.contact_id,action_type_id:i.id,notes:n.notes??"Pop-by logged",completed_at:r})}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"]}),_a({title:"Popby logged!"})},onError:n=>{_a({title:"Error logging popby",description:n.message,variant:"destructive"})}})},a9n=()=>{const s=Vt(),{user:t}=vs();return ft({mutationFn:async n=>{const{error:r}=await q.from("relationship_type_popby_defaults").upsert({...n,owner_user_id:t==null?void 0:t.id},{onConflict:"relationship_type_id,owner_user_id"});if(r)throw r},onSuccess:()=>{s.invalidateQueries({queryKey:["relationship-type-popby-defaults"]}),_a({title:"Frequency updated!"})},onError:n=>{_a({title:"Error updating frequency",description:n.message,variant:"destructive"})}})},i9n=()=>{const{data:s}=cDe(30),t=OQt(),n=new Date;n.setDate(n.getDate()-7);const r=(s==null?void 0:s.filter(i=>new Date(i.completed_at)>=n).length)||0,a=(s==null?void 0:s.length)||0;return{thisWeekCount:r,thisMonthCount:a,dueCount:t.length}};function o9n(){const{user:s}=vs();return tt({queryKey:["contact-touch-logs",s==null?void 0:s.id],queryFn:async()=>{const{data:t,error:n}=await q.from("contact_touch_logs").select("*").order("completed_at",{ascending:!1});if(n)throw n;return t},enabled:!!s})}function zQt(s){const{data:t}=o9n(),{data:n}=FQt(),{data:r}=wit(),{data:a}=MBn();return j.useMemo(()=>{const i=a==null?void 0:a.find(y=>y.contact_id===s.id),l=i?new Date(i.snoozed_until):null,o=Mg(new Date);if(l&&!iC(l,o))return{nextTouchDate:l,daysUntil:mk(l,o),status:"snoozed",frequencyDays:90,lastTouchDate:null,snoozedUntil:l};const d=((t==null?void 0:t.filter(y=>y.contact_id===s.id))||[]).sort((y,v)=>new Date(v.completed_at).getTime()-new Date(y.completed_at).getTime())[0],u=d?new Date(d.completed_at):null;let h=90;const m=n==null?void 0:n.find(y=>y.contact_id===s.id&&y.is_active);if(m)h=m.frequency_days;else if(s.tags&&s.tags.length>0){const y=s.tags.map(v=>{const b=r==null?void 0:r.find(w=>w.relationship_type_id===v.relationship_type_id);return b==null?void 0:b.frequency_days}).filter(v=>v!==void 0);y.length>0&&(h=Math.min(...y))}if(!u)return{nextTouchDate:null,daysUntil:null,status:"never-touched",frequencyDays:h,lastTouchDate:null,snoozedUntil:null};const f=Tm(Mg(u),h),g=mk(f,o);let x;return g<0?x="overdue":g<=7?x="due-soon":x="on-track",{nextTouchDate:f,daysUntil:g,status:x,frequencyDays:h,lastTouchDate:u,snoozedUntil:null}},[s,t,n,r,a])}function dCt({contact:s}){const t=zQt(s),r=(()=>{switch(t.status){case"overdue":return{variant:"destructive",icon:ll,text:`${Math.abs(t.daysUntil)} days overdue`,className:""};case"due-soon":return{variant:"secondary",icon:da,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:qr,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:Tv,text:`Snoozed until ${en(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:Ta,text:"Never touched",className:"border-dashed"}}})(),a=r.icon;return e.jsxs(Be,{variant:r.variant,className:Pt("gap-1",r.className),children:[e.jsx(a,{className:"h-3 w-3"}),r.text]})}function l9n({contact:s,onLogTouch:t,onSnooze:n}){const r=zQt(s),a=IBn(),[i,l]=j.useState(!1),o=()=>{switch(r.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(r.status){case"overdue":return e.jsx(ll,{className:"h-5 w-5 text-destructive"});case"due-soon":return e.jsx(da,{className:"h-5 w-5 text-amber-600 dark:text-amber-400"});case"on-track":return e.jsx(qr,{className:"h-5 w-5 text-emerald-600 dark:text-emerald-400"});case"snoozed":return e.jsx(Tv,{className:"h-5 w-5 text-slate-600 dark:text-slate-400"});case"never-touched":return e.jsx(Ta,{className:"h-5 w-5 text-muted-foreground"})}},d=()=>{switch(r.status){case"overdue":return`${Math.abs(r.daysUntil)} days overdue`;case"due-soon":return r.daysUntil===0?"Due today!":`Due in ${r.daysUntil} days`;case"on-track":return`On track - ${r.daysUntil} days remaining`;case"snoozed":return`Snoozed for ${r.daysUntil} more days`;case"never-touched":return"No touches logged yet"}},u=async()=>{await a.mutateAsync(s.id)};return e.jsxs(e.Fragment,{children:[e.jsxs(Ne,{children:[e.jsx(Ct,{className:"pb-2",children:e.jsxs(At,{className:"text-sm font-medium flex items-center gap-2",children:[e.jsx(Ta,{className:"h-4 w-4"}),"Next Touch"]})}),e.jsxs(Ie,{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[c(),e.jsx("span",{className:Pt("font-medium",o()),children:d()})]}),r.status==="snoozed"&&r.snoozedUntil&&e.jsxs("div",{className:"text-sm text-muted-foreground",children:[e.jsx("span",{className:"font-medium",children:"Snoozed until:"})," ",en(r.snoozedUntil,"MMMM d, yyyy")]}),r.status!=="snoozed"&&r.nextTouchDate&&e.jsxs("div",{className:"text-sm text-muted-foreground",children:[e.jsx("span",{className:"font-medium",children:"Scheduled:"})," ",en(r.nextTouchDate,"MMMM d, yyyy")]}),r.lastTouchDate&&e.jsxs("div",{className:"text-sm text-muted-foreground",children:[e.jsx("span",{className:"font-medium",children:"Last touch:"})," ",en(r.lastTouchDate,"MMM d, yyyy")]}),r.status!=="snoozed"&&e.jsxs("div",{className:"text-xs text-muted-foreground border-t pt-2",children:["Touch frequency: Every ",r.frequencyDays," days"]}),r.status==="snoozed"&&e.jsxs("div",{className:"flex gap-2 pt-1",children:[e.jsxs($,{size:"sm",variant:"outline",className:"flex-1",onClick:u,disabled:a.isPending,children:[e.jsx(gr,{className:"h-4 w-4 mr-1"}),"Cancel Snooze"]}),t&&e.jsx($,{size:"sm",className:"flex-1",onClick:t,children:"Log Touch"})]}),r.status!=="snoozed"&&e.jsxs("div",{className:"flex gap-2 pt-1",children:[e.jsxs($,{size:"sm",variant:"outline",className:"flex-1",onClick:()=>l(!0),children:[e.jsx(Tv,{className:"h-4 w-4 mr-1"}),"Snooze"]}),(r.status==="overdue"||r.status==="due-soon"||r.status==="never-touched")&&t&&e.jsx($,{size:"sm",className:"flex-1",variant:r.status==="overdue"?"default":"outline",onClick:t,children:"Log Touch"})]})]})]}),e.jsx(lDe,{open:i,onOpenChange:l,contactId:s.id,contactName:`${s.first_name} ${s.last_name||""}`.trim()})]})}const X9e=768;function $K(){const[s,t]=j.useState(void 0);return j.useEffect(()=>{const n=window.matchMedia(`(max-width: ${X9e-1}px)`),r=()=>{t(window.innerWidthn.removeEventListener("change",r)},[]),!!s}function c9n(){const{user:s}=vs(),{hasLeadSite:t,leadSite:n}=ng(),{data:r,isLoading:a}=tt({queryKey:["website-active-contacts",s==null?void 0:s.id,n==null?void 0:n.id],queryFn:async()=>{if(!n)return new Set;const{data:i}=await q.from("lead_site_visitors").select("contact_id").eq("lead_site_id",n.id).not("contact_id","is",null),{data:l}=await q.from("lead_site_consumer_profiles").select("contact_id").eq("lead_site_id",n.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:r??new Set,hasLeadSite:t,isLoading:a}}const d9n={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"}},u9n={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 OYe({score:s,showScore:t=!1,showTooltip:n=!0,size:r="sm",className:a}){const i=d9n[s.status],l=u9n[r],o=e.jsxs("div",{className:Pt("inline-flex items-center rounded-full font-medium",i.bgLightClass,i.textClass,l.badge,l.text,a),children:[e.jsx("span",{className:Pt("rounded-full",i.bgClass,l.dot)}),t?e.jsx("span",{children:s.score}):e.jsx("span",{children:i.label})]});return n?e.jsx(jk,{children:e.jsxs(ly,{children:[e.jsx(cy,{asChild:!0,children:o}),e.jsx(Nx,{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:Pt("font-bold",i.textClass),children:[s.score,"/100"]})]}),e.jsx(Yi,{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 h9n=[{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:"address2_label",label:"Second Address Label",required:!1},{key:"address2",label:"Second Street Address",required:!1},{key:"address2_city",label:"Second City",required:!1},{key:"address2_state",label:"Second State",required:!1},{key:"address2_zip",label:"Second 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}],cue=s=>{if(!s||!s.trim())return null;const t=s.trim();if(/^\d{4}-\d{2}-\d{2}$/.test(t))return t;const n=t.match(/^(\d{1,2})[\/\-](\d{1,2})(?:[\/\-](\d{2,4}))?$/);if(n){const a=n[1].padStart(2,"0"),i=n[2].padStart(2,"0");let l="2000";n[3]&&(l=n[3].length===2?(parseInt(n[3])>50?"19":"20")+n[3]:n[3]);const o=parseInt(a),c=parseInt(i);if(o>=1&&o<=12&&c>=1&&c<=31)return`${l}-${a}-${i}`}const r=new Date(t);return isNaN(r.getTime())?null:r.toISOString().split("T")[0]},m9n=({open:s,onOpenChange:t,relationshipTypes:n,onSuccess:r})=>{const{user:a}=vs(),{toast:i}=Bi(),l=j.useRef(null),[o,c]=j.useState("upload"),[d,u]=j.useState([]),[h,m]=j.useState([]),[f,g]=j.useState({}),[x,y]=j.useState([]),[v,b]=j.useState([]),[w,S]=j.useState([]),[C,E]=j.useState(""),[I,P]=j.useState(!1),[R,D]=j.useState([]),[O,U]=j.useState(!1),[W,V]=j.useState(null);j.useEffect(()=>{!s||!(a!=null&&a.id)||(async()=>{const{data:Le}=await q.from("contact_custom_tags").select("id, name, color").eq("owner_user_id",a.id).order("name");b(Le||[])})()},[s,a==null?void 0:a.id]);const G=Le=>{S(Fe=>Fe.includes(Le)?Fe.filter(ke=>ke!==Le):[...Fe,Le])},Y=async()=>{const Le=C.trim();if(!(!Le||!(a!=null&&a.id))){P(!0);try{const{data:Fe,error:ke}=await q.from("contact_custom_tags").insert({owner_user_id:a.id,name:Le}).select("id, name, color").single();if(ke)throw ke;Fe&&(b(Ve=>[...Ve,Fe].sort((je,Ae)=>je.name.localeCompare(Ae.name))),S(Ve=>[...Ve,Fe.id]),E(""))}catch(Fe){i({title:"Could not create tag",description:Fe.message||"Try a different name.",variant:"destructive"})}finally{P(!1)}}},X=()=>{c("upload"),u([]),m([]),g({}),y([]),S([]),E(""),D([]),V(null),l.current&&(l.current.value="")},ae=()=>{X(),t(!1)},ie=Le=>{const Fe=Le.split(` `).map(qe=>qe.trim()).filter(qe=>qe);if(Fe.length===0)return{headers:[],data:[]};const ke=qe=>{const ze=[];let $e="",ct=!1;for(let Xe=0;Xe0&&(Ve[0]=Ve[0].replace(/^\uFEFF/,""));const je=new Map,Ae=Ve.map((qe,ze)=>{let $e=(qe||"").trim();$e||($e=`Column ${ze+1}`);const ct=je.get($e)||0;return je.set($e,ct+1),ct===0?$e:`${$e} (${ct+1})`}),Ce=Fe.slice(1).map(ke);return{headers:Ae,data:Ce}},ne=Le=>{var Ve;const Fe=(Ve=Le.target.files)==null?void 0:Ve[0];if(!Fe)return;const ke=new FileReader;ke.onload=je=>{var $e;const Ae=($e=je.target)==null?void 0:$e.result,{headers:Ce,data:qe}=ie(Ae);if(Ce.length===0){i({title:"No data found",description:"The CSV file appears to be empty.",variant:"destructive"});return}u(Ce),m(qe);const ze={};Ce.forEach(ct=>{const Xe=ct.toLowerCase().replace(/[_\s-]/g,"");Xe.includes("firstname")||Xe==="first"?ze.first_name=ct:Xe.includes("lastname")||Xe==="last"?ze.last_name=ct:Xe.includes("spouse")&&Xe.includes("email")?ze.spouse_email=ct:Xe.includes("spouse")||Xe.includes("partner")?ze.spouse_name=ct:Xe.includes("email")?ze.email=ct:Xe.includes("phone")||Xe.includes("mobile")||Xe.includes("cell")?ze.phone=ct:(Xe.includes("address")||Xe.includes("street"))&&(Xe.includes("2")||Xe.includes("second")||Xe.includes("secondary"))?ze.address2=ct:Xe.includes("address")||Xe.includes("street")?ze.address=ct:Xe==="city"?ze.city=ct:Xe==="state"||Xe==="province"?ze.state=ct:Xe==="zip"||Xe==="zipcode"||Xe==="postalcode"?ze.zip=ct:Xe.includes("company")||Xe.includes("organization")||Xe.includes("business")?ze.company_name=ct:Xe.includes("jobtitle")||Xe.includes("title")&&!Xe.includes("spouse")?ze.job_title=ct:Xe.includes("birthday")||Xe.includes("dob")||Xe.includes("birthdate")?ze.birthday=ct:Xe.includes("anniversary")||Xe.includes("homeanniversary")?ze.home_anniversary=ct:(Xe.includes("notes")||Xe.includes("comment"))&&(ze.notes=ct)}),g(ze),c("mapping")},ke.readAsText(Fe)},te=(Le,Fe)=>{g(ke=>{if(Fe==="none"){const{[Le]:Ve,...je}=ke;return je}return{...ke,[Le]:Fe}})},J=Le=>{y(Fe=>Fe.includes(Le)?Fe.filter(ke=>ke!==Le):[...Fe,Le])},ce=async()=>{if(!(a!=null&&a.id))return;const{data:Le}=await q.from("innercircle_contacts").select("id, email, phone").eq("owner_user_id",a.id),Fe=new Set((Le||[]).filter(je=>je.email).map(je=>je.email.toLowerCase())),ke=new Set((Le||[]).filter(je=>je.phone).map(je=>je.phone.replace(/[^0-9]/g,""))),Ve=h.map(je=>{const Ae=Xe=>{const it=f[Xe];if(!it)return"";const at=d.indexOf(it);return at>=0?(je[at]||"").trim():""},Ce=Ae("first_name"),qe=Ae("email"),ze=Ae("phone"),$e=Ce.length>0,ct=!!(qe&&Fe.has(qe.toLowerCase())||ze&&ke.has(ze.replace(/[^0-9]/g,"")));return{first_name:Ce,last_name:Ae("last_name"),email:qe,phone:ze,address:Ae("address"),city:Ae("city"),state:Ae("state"),zip:Ae("zip"),address2_label:Ae("address2_label"),address2:Ae("address2"),address2_city:Ae("address2_city"),address2_state:Ae("address2_state"),address2_zip:Ae("address2_zip"),spouse_name:Ae("spouse_name"),spouse_email:Ae("spouse_email"),company_name:Ae("company_name"),job_title:Ae("job_title"),birthday:Ae("birthday"),home_anniversary:Ae("home_anniversary"),notes:Ae("notes"),isValid:$e,isDuplicate:ct,error:$e?void 0:"First name is required"}});D(Ve),c("preview")},_e=Le=>{const Fe=Le.trim().split(/\s+/);return{first_name:Fe[0],last_name:Fe.length>1?Fe.slice(1).join(" "):null}},he=async()=>{if(!(a!=null&&a.id))return;const Le=R.filter(je=>je.isValid);if(Le.length===0){i({title:"No valid contacts",description:"There are no valid contacts to import.",variant:"destructive"});return}U(!0);let Fe=0,ke=0,Ve=0;try{for(const je of Le)try{let Ae=null;if(je.email){const{data:ze}=await q.from("innercircle_contacts").select("id").eq("owner_user_id",a.id).eq("email",je.email).maybeSingle();Ae=ze}if(!Ae&&je.phone){const ze=je.phone.replace(/[^0-9]/g,""),{data:$e}=await q.from("innercircle_contacts").select("id, phone").eq("owner_user_id",a.id).not("phone","is",null);if($e){const ct=$e.find(Xe=>Xe.phone&&Xe.phone.replace(/[^0-9]/g,"")===ze);ct&&(Ae={id:ct.id})}}const Ce={owner_user_id:a.id,first_name:je.first_name,last_name:je.last_name||null,email:je.email||null,phone:je.phone||null,address:je.address||null,city:je.city||null,state:je.state||null,zip:je.zip||null,address2_label:je.address2_label||null,address2:je.address2||null,address2_city:je.address2_city||null,address2_state:je.address2_state||null,address2_zip:je.address2_zip||null,spouse_name:je.spouse_name||null,spouse_email:je.spouse_email||null,company_name:je.company_name||null,job_title:je.job_title||null,birthday:cue(je.birthday),home_anniversary:cue(je.home_anniversary),notes:je.notes||null};let qe=null;if(Ae){const{data:ze}=await q.from("innercircle_contacts").select("*").eq("id",Ae.id).single();if(ze){const $e={},ct=["last_name","email","phone","address","city","state","zip","address2_label","address2","address2_city","address2_state","address2_zip","spouse_name","spouse_email","company_name","job_title","birthday","home_anniversary","notes"];for(const Xe of ct){const it=ze[Xe],at=Ce[Xe];(!it||it==="")&&at&&($e[Xe]=at)}Object.keys($e).length>0&&await q.from("innercircle_contacts").update($e).eq("id",Ae.id)}qe=Ae.id,ke++}else{const{data:ze,error:$e}=await q.from("innercircle_contacts").insert(Ce).select("id").single();$e?(console.error("Insert error for contact:",je.first_name,$e),Ve++):ze?(qe=ze.id,x.length>0&&await q.from("innercircle_contact_tags").insert(x.map(ct=>({contact_id:ze.id,relationship_type_id:ct}))),Fe++):Ve++}if(qe&&w.length>0&&await q.from("contact_custom_tag_assignments").upsert(w.map(ze=>({contact_id:qe,tag_id:ze})),{onConflict:"contact_id,tag_id",ignoreDuplicates:!0}),qe&&je.spouse_name){const ze=_e(je.spouse_name);let $e=null;if(je.spouse_email){const{data:Xe}=await q.from("innercircle_contacts").select("id").eq("owner_user_id",a.id).eq("email",je.spouse_email).maybeSingle();$e=Xe}if(!$e){const{data:Xe}=await q.from("innercircle_contacts").select("id").eq("owner_user_id",a.id).eq("first_name",ze.first_name).eq("last_name",ze.last_name||je.last_name||"").maybeSingle();$e=Xe}let ct=null;if($e){ct=$e.id;const Xe=cue(je.home_anniversary);Xe&&await q.from("innercircle_contacts").update({home_anniversary:Xe}).eq("id",$e.id).is("home_anniversary",null)}else{const{data:Xe}=await q.from("innercircle_contacts").insert({owner_user_id:a.id,first_name:ze.first_name,last_name:ze.last_name||je.last_name||null,email:je.spouse_email||null,address:je.address||null,city:je.city||null,state:je.state||null,zip:je.zip||null,home_anniversary:cue(je.home_anniversary),spouse_name:`${je.first_name}${je.last_name?" "+je.last_name:""}`,spouse_email:je.email||null,notes:`Spouse of ${je.first_name} ${je.last_name||""} (imported via CSV)`.trim()}).select("id").single();Xe&&(ct=Xe.id,Fe++)}ct&&(await q.from("innercircle_contacts").update({spouse_contact_id:ct}).eq("id",qe),await q.from("innercircle_contacts").update({spouse_contact_id:qe}).eq("id",ct))}}catch(Ae){console.error("Error importing contact:",Ae),Ve++}V({created:Fe,updated:ke,failed:Ve}),c("result"),(Fe>0||ke>0)&&r(),i({title:"Import Complete",description:`${Fe} created, ${ke} updated${Ve>0?`, ${Ve} failed`:""}.`})}catch(je){console.error("Import error:",je),i({title:"Import Failed",description:je.message||"Failed to import contacts",variant:"destructive"})}finally{U(!1)}},ue=R.filter(Le=>Le.isValid).length,ve=R.filter(Le=>!Le.isValid).length,Ee=R.filter(Le=>Le.isValid&&Le.isDuplicate).length,Se=ue-Ee;return e.jsx(zs,{open:s,onOpenChange:ae,children:e.jsxs(Os,{className:"max-w-3xl max-h-[85vh] overflow-hidden flex flex-col",children:[e.jsxs(Us,{children:[e.jsxs(Bs,{className:"flex items-center gap-2",children:[e.jsx(ek,{className:"h-5 w-5"}),"Import Contacts from CSV"]}),e.jsx(Ir,{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:ne,className:"hidden"}),e.jsx(ni,{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($,{onClick:()=>{var Le;return(Le=l.current)==null?void 0:Le.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($,{variant:"outline",size:"sm",onClick:()=>{const Le=`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`,Fe=new Blob([Le],{type:"text/csv"}),ke=URL.createObjectURL(Fe),Ve=document.createElement("a");Ve.href=ke,Ve.download="contact_import_template.csv",Ve.click(),URL.revokeObjectURL(ke)},children:[e.jsx(di,{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(ee,{className:"text-base font-medium",children:"Map CSV Columns to Contact Fields"}),e.jsx("div",{className:"grid gap-3",children:h9n.map(Le=>e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs(ee,{className:"w-40 text-sm",children:[Le.label,Le.required&&e.jsx("span",{className:"text-destructive ml-1",children:"*"})]}),e.jsxs(ms,{value:f[Le.key]||"none",onValueChange:Fe=>te(Le.key,Fe),children:[e.jsx(us,{className:"w-48",children:e.jsx(fs,{placeholder:"Select column..."})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"none",children:"-- Not mapped --"}),d.map(Fe=>e.jsx(Ge,{value:Fe,children:Fe},Fe))]})]})]},Le.key))})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx(ee,{className:"text-base font-medium",children:"Apply Relationship Types (optional)"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:n.map(Le=>e.jsx(Be,{variant:x.includes(Le.id)?"default":"outline",className:"cursor-pointer",onClick:()=>J(Le.id),children:Le.name},Le.id))})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx(ee,{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."}),v.length>0&&e.jsx("div",{className:"flex flex-wrap gap-2",children:v.map(Le=>{const Fe=w.includes(Le.id);return e.jsxs(Be,{variant:Fe?"default":"outline",className:"cursor-pointer gap-1",style:Fe&&Le.color?{backgroundColor:Le.color,borderColor:Le.color}:void 0,onClick:()=>G(Le.id),children:[Le.name,Fe&&e.jsx(gr,{className:"h-3 w-3"})]},Le.id)})}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(pe,{placeholder:"Create a new tag (e.g. Open House Oct 2026)",value:C,onChange:Le=>E(Le.target.value),onKeyDown:Le=>{Le.key==="Enter"&&(Le.preventDefault(),Y())},className:"max-w-xs"}),e.jsxs($,{type:"button",variant:"outline",size:"sm",onClick:Y,disabled:!C.trim()||I,children:[I?e.jsx(kt,{className:"h-4 w-4 animate-spin"}):e.jsx(dn,{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: ",h.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(qr,{className:"h-4 w-4 text-primary"}),e.jsxs("span",{children:[Se," new"]})]}),Ee>0&&e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground",children:[e.jsx(ll,{className:"h-4 w-4"}),e.jsxs("span",{children:[Ee," existing (will merge gaps)"]})]}),ve>0&&e.jsxs("div",{className:"flex items-center gap-2 text-destructive",children:[e.jsx(ll,{className:"h-4 w-4"}),e.jsxs("span",{children:[ve," invalid"]})]})]}),Ee>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(mi,{children:[e.jsx(fi,{children:e.jsxs(En,{className:"bg-muted/30",children:[e.jsx(Dt,{children:"First Name"}),e.jsx(Dt,{children:"Last Name"}),e.jsx(Dt,{children:"Email"}),e.jsx(Dt,{children:"Phone"}),e.jsx(Dt,{children:"Status"})]})}),e.jsx(pi,{children:R.slice(0,100).map((Le,Fe)=>e.jsxs(En,{children:[e.jsx(wt,{children:Le.first_name}),e.jsx(wt,{children:Le.last_name}),e.jsx(wt,{children:Le.email}),e.jsx(wt,{children:Le.phone}),e.jsx(wt,{children:Le.isValid?Le.isDuplicate?e.jsx(Be,{variant:"outline",className:"bg-accent text-accent-foreground",children:"Merge"}):e.jsx(Be,{variant:"secondary",className:"bg-primary/10 text-primary",children:"New"}):e.jsx(Be,{variant:"destructive",children:Le.error||"Invalid"})})]},Fe))})]}),R.length>100&&e.jsxs("p",{className:"text-sm text-muted-foreground text-center py-2",children:["Showing first 100 of ",R.length," contacts"]})]})]}),o==="result"&&W&&e.jsxs("div",{className:"space-y-4 py-4 text-center",children:[e.jsx(qr,{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:[W.created," created, ",W.updated," merged"]}),W.failed>0&&e.jsxs("p",{className:"text-destructive",children:[W.failed," failed to import"]})]}),e.jsxs(Ar,{children:[o==="upload"&&e.jsx($,{variant:"outline",onClick:ae,children:"Cancel"}),o==="mapping"&&e.jsxs(e.Fragment,{children:[e.jsx($,{variant:"outline",onClick:X,children:"Back"}),e.jsx($,{onClick:ce,disabled:!f.first_name,children:"Continue"})]}),o==="preview"&&e.jsxs(e.Fragment,{children:[e.jsx($,{variant:"outline",onClick:()=>c("mapping"),children:"Back"}),e.jsx($,{onClick:he,disabled:O||ue===0,children:O?e.jsxs(e.Fragment,{children:[e.jsx(kt,{className:"mr-2 h-4 w-4 animate-spin"}),"Importing..."]}):`Import ${ue} Contact${ue!==1?"s":""}`})]}),o==="result"&&e.jsx($,{onClick:ae,children:"Done"})]})]})})};function f9n(){return"contacts"in navigator&&"ContactsManager"in window}function p9n(s){const t=[],n=s.split("BEGIN:VCARD").filter(r=>r.trim());for(const r of n){const a=r.split(/\r?\n/);let i="",l="",o="",c="",d="";for(const u of a){const h=u.replace(/^\s+/,"");if(h.startsWith("N:")||h.startsWith("N;")){const f=h.substring(h.indexOf(":")+1).split(";");l=(f[0]||"").trim(),i=(f[1]||"").trim()}if((h.startsWith("FN:")||h.startsWith("FN;"))&&!i){const f=h.substring(h.indexOf(":")+1).trim().split(" ");i=f[0]||"",l=f.slice(1).join(" ")}(h.startsWith("EMAIL")||h.match(/^item\d+\.EMAIL/i))&&!o&&(o=h.substring(h.indexOf(":")+1).trim()),(h.startsWith("TEL")||h.match(/^item\d+\.TEL/i))&&!c&&(c=h.substring(h.indexOf(":")+1).trim()),(h.startsWith("ADR")||h.match(/^item\d+\.ADR/i))&&!d&&(d=h.substring(h.indexOf(":")+1).split(";").map(g=>g.trim()).filter(Boolean).join(", "))}(i||l)&&t.push({first_name:i,last_name:l,email:o,phone:c,address:d})}return t}function g9n({open:s,onOpenChange:t,onComplete:n}){const{user:r}=vs(),{data:a}=z_(),i=j6e(),l=j.useRef(null),[o,c]=j.useState("choose"),[d,u]=j.useState([]),[h,m]=j.useState(new Set),[f,g]=j.useState(0),[x,y]=j.useState(0),v=f9n(),b=j.useCallback(O=>{if(!a)return O;const U=new Set(a.filter(V=>V.email).map(V=>V.email.toLowerCase())),W=new Set(a.filter(V=>V.phone).map(V=>V.phone.replace(/\D/g,"")));return O.map(V=>{var X,ae;const G=(X=V.email)==null?void 0:X.toLowerCase(),Y=(ae=V.phone)==null?void 0:ae.replace(/\D/g,"");return G&&U.has(G)?{...V,isDuplicate:!0,duplicateField:"email"}:Y&&Y.length>=7&&W.has(Y)?{...V,isDuplicate:!0,duplicateField:"phone"}:V})},[a]),w=async()=>{try{const O=["name","email","tel","address"],U=await navigator.contacts.select(O,{multiple:!0});if(!U||U.length===0)return;const W=U.map(Y=>{var ie,ne,te,J;const ae=(((ie=Y.name)==null?void 0:ie[0])||"").split(" ");return{first_name:ae[0]||"",last_name:ae.slice(1).join(" "),email:((ne=Y.email)==null?void 0:ne[0])||"",phone:((te=Y.tel)==null?void 0:te[0])||"",address:(J=Y.address)!=null&&J[0]?[Y.address[0].streetAddress,Y.address[0].city,Y.address[0].region,Y.address[0].postalCode].filter(Boolean).join(", "):""}}),V=b(W);u(V);const G=new Set;V.forEach((Y,X)=>{Y.isDuplicate||G.add(X)}),m(G),c("preview")}catch(O){console.error("Contact Picker error:",O),_a({title:"Could not access contacts",description:"Please try the file upload option instead.",variant:"destructive"})}},S=O=>{var V;const U=(V=O.target.files)==null?void 0:V[0];if(!U)return;const W=new FileReader;W.onload=G=>{var ne;const Y=(ne=G.target)==null?void 0:ne.result,X=p9n(Y);if(X.length===0){_a({title:"No contacts found",description:"The file didn't contain any valid contacts.",variant:"destructive"});return}const ae=b(X);u(ae);const ie=new Set;ae.forEach((te,J)=>{te.isDuplicate||ie.add(J)}),m(ie),c("preview")},W.readAsText(U),l.current&&(l.current.value="")},C=async()=>{const O=d.filter((W,V)=>h.has(V));if(O.length===0)return;c("importing");let U=0;for(const W of O)try{await i.mutateAsync({first_name:W.first_name,last_name:W.last_name||void 0,email:W.email||void 0,phone:W.phone||void 0,address:W.address||void 0}),U++,y(Math.round(U/O.length*100))}catch(V){console.error(`Failed to import ${W.first_name} ${W.last_name}:`,V)}g(U),c("done")},E=O=>{m(U=>{const W=new Set(U);return W.has(O)?W.delete(O):W.add(O),W})},I=()=>{h.size===d.length?m(new Set):m(new Set(d.map((O,U)=>U)))},P=O=>{O||(c("choose"),u([]),m(new Set),g(0),y(0),o==="done"&&n()),t(O)},R=d.filter(O=>O.isDuplicate).length,D=h.size;return e.jsx(zs,{open:s,onOpenChange:P,children:e.jsxs(Os,{className:"sm:max-w-lg max-h-[90vh]",children:[e.jsxs(Us,{children:[e.jsxs(Bs,{className:"flex items-center gap-2",children:[e.jsx(_1,{className:"h-5 w-5 text-primary"}),o==="choose"&&"Import Phone Contacts",o==="preview"&&"Select Contacts to Import",o==="importing"&&"Importing Contacts...",o==="done"&&"Import Complete"]}),o==="choose"&&e.jsx(Ir,{children:"Add contacts from your phone directly into Agent OS."})]}),o==="choose"&&e.jsxs("div",{className:"space-y-4 pt-2",children:[v&&e.jsxs($,{onClick:w,className:"w-full h-auto py-4 flex flex-col items-center gap-2",children:[e.jsx(_1,{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:[v&&e.jsx("div",{className:"absolute inset-0 flex items-center",children:e.jsx("span",{className:"w-full border-t"})}),v&&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($,{variant:v?"outline":"default",onClick:()=>{var O;return(O=l.current)==null?void 0:O.click()},className:"w-full h-auto py-4 flex flex-col items-center gap-2",children:[e.jsx(ni,{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:v?"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:l,type:"file",accept:".vcf,.vcard",onChange:S,className:"hidden"}),!v&&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"})]})]})]}),o==="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:[d.length," contact",d.length!==1?"s":""," found",R>0&&e.jsxs("span",{className:"text-amber-600 ml-1",children:["(",R," already exist)"]})]}),e.jsx($,{variant:"ghost",size:"sm",onClick:I,children:h.size===d.length?"Deselect All":"Select All"})]}),e.jsx(uo,{className:"h-[350px] rounded-md border",children:e.jsx("div",{className:"divide-y",children:d.map((O,U)=>e.jsxs("div",{className:`flex items-start gap-3 p-3 cursor-pointer hover:bg-accent/50 transition-colors ${O.isDuplicate?"opacity-60":""}`,onClick:()=>E(U),children:[e.jsx(ai,{checked:h.has(U),onCheckedChange:()=>E(U),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:[O.first_name," ",O.last_name]}),O.isDuplicate&&e.jsxs(Be,{variant:"secondary",className:"text-[10px] px-1.5 py-0 bg-amber-500/10 text-amber-600 border-amber-200",children:["Exists (",O.duplicateField,")"]})]}),e.jsxs("div",{className:"text-xs text-muted-foreground space-y-0.5 mt-0.5",children:[O.phone&&e.jsx("div",{children:O.phone}),O.email&&e.jsx("div",{className:"truncate",children:O.email})]})]})]},U))})}),e.jsxs("div",{className:"flex items-center justify-between pt-2",children:[e.jsx($,{variant:"ghost",size:"sm",onClick:()=>c("choose"),children:"Back"}),e.jsxs($,{onClick:C,disabled:D===0,children:["Import ",D," Contact",D!==1?"s":""]})]})]}),o==="importing"&&e.jsxs("div",{className:"flex flex-col items-center gap-4 py-8",children:[e.jsx(kt,{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:[x,"% 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:`${x}%`}})})]}),o==="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(la,{className:"h-6 w-6 text-emerald-600"})}),e.jsxs("div",{className:"text-center",children:[e.jsxs("p",{className:"font-semibold text-lg",children:[f," contact",f!==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($,{onClick:()=>P(!1),className:"mt-2",children:"Done"})]})]})})}const zYe="mailStudioHandoff";function x9n(s){sessionStorage.setItem(zYe,JSON.stringify({...s,at:Date.now()}))}function YSr(){const s=sessionStorage.getItem(zYe);if(sessionStorage.removeItem(zYe),!s)return null;try{const t=JSON.parse(s);return Date.now()-(t.at||0)>10*60*1e3?null:t}catch{return null}}const y9n="/mission-control/direct-mail";function dDe({build:s,label:t="Mail Studio",...n}){const{isAdmin:r}=vs(),a=Qn();return r?e.jsxs($,{variant:"outline",size:"sm",...n,onClick:()=>{const i=s();i&&(x9n(i),a(`${y9n}?handoff=1`))},children:[e.jsx(mn,{className:"mr-1.5 h-3.5 w-3.5"}),t]}):null}function v9n(s){return tt({queryKey:["video-share-recipients",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await q.from("video_share_recipients").select("*").eq("video_id",s).order("sent_at",{ascending:!1});if(n)throw n;return t},enabled:!!s})}function b9n(){const{user:s}=vs();return tt({queryKey:["video-share-stats",s==null?void 0:s.id],queryFn:async()=>{if(!(s!=null&&s.id))return null;const{data:t,error:n}=await q.from("video_share_recipients").select("*").eq("owner_user_id",s.id);if(n)throw n;const r=t;return{totalSent:r.length,totalOpened:r.filter(a=>a.opened_at).length,totalClicked:r.filter(a=>a.clicked_at).length,totalWatched:r.filter(a=>a.watched_at).length,openRate:r.length>0?Math.round(r.filter(a=>a.opened_at).length/r.length*100):0,clickRate:r.length>0?Math.round(r.filter(a=>a.clicked_at).length/r.length*100):0,watchRate:r.length>0?Math.round(r.filter(a=>a.watched_at).length/r.length*100):0}},enabled:!!(s!=null&&s.id)})}function _9n(){const{user:s}=vs();return tt({queryKey:["video-share-history",s==null?void 0:s.id],queryFn:async()=>{if(!(s!=null&&s.id))return[];const{data:t,error:n}=await q.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(n)throw n;return t},enabled:!!(s!=null&&s.id)})}function BQt(){const{user:s}=vs(),t=Vt();return ft({mutationFn:async n=>{if(!(s!=null&&s.id))throw new Error("Not authenticated");const{data:r,error:a}=await q.from("video_share_recipients").insert([{video_id:n.video_id,owner_user_id:s.id,recipient_email:n.recipient_email,recipient_name:n.recipient_name||null,contact_id:n.contact_id||null,sent_via:n.sent_via||"gmail",share_token:"placeholder"}]).select().single();if(a)throw a;return r},onSuccess:n=>{t.invalidateQueries({queryKey:["video-share-recipients",n.video_id]}),t.invalidateQueries({queryKey:["video-share-stats"]}),t.invalidateQueries({queryKey:["video-share-history"]})}})}function $Qt(s){return`https://relzejiswnotikjgvjhz.supabase.co/functions/v1/track-video-share?t=${s}&e=open`}function UQt(s){return`https://relzejiswnotikjgvjhz.supabase.co/functions/v1/track-video-share?t=${s}&e=click`}const w9n=100;function j9n({open:s,onOpenChange:t,contacts:n,isGmailConnected:r,isMassEmailReady:a,onSendComplete:i}){const l=Qn(),o=Sa(),c=BQt(),[d,u]=j.useState([]),[h,m]=j.useState(!1),[f,g]=j.useState(""),[x,y]=j.useState(null),[v,b]=j.useState(""),[w,S]=j.useState(""),[C,E]=j.useState(!1),[I,P]=j.useState({done:0,total:0,failed:0}),R=n.filter(X=>!!X.email),D=n.length-R.length,O=R.length>w9n;j.useEffect(()=>{s&&(y(null),g(""),P({done:0,total:0,failed:0}))},[s]),j.useEffect(()=>{!s||!o||(m(!0),q.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:X})=>{u(X||[]),m(!1)}))},[s,o]),j.useEffect(()=>{if(!x)return;const X=x.title||"a quick video";b(`I recorded a video for you — ${X}`),S("Hey {{first_name}}! I recorded a quick video just for you. Click below to watch it:")},[x]);const U=d.filter(X=>!f||(X.title||"").toLowerCase().includes(f.toLowerCase())),W=(X,ae)=>{if(!x)return"";const ie=x.share_token?`https://video.relevelup.com/share/video/${x.share_token}`:"",ne=x.share_token?`https://video.relevelup.com/thumb/${x.share_token}`:x.thumbnail_url||"",te=x.title||"Video Message",ce=w.replace(/\{\{first_name\}\}/gi,X).split(/\n\n+/).map(ue=>`

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

`).join(""),_e=ae?UQt(ae):ie,he=ae?``:"";return`
${ce}

▶ Watch Video

${he}
`},V=async()=>{if(!x)return;E(!0),P({done:0,total:R.length,failed:0});let X=0,ae=0;for(const ie of R)try{let ne;try{ne=(await c.mutateAsync({video_id:x.id,recipient_email:ie.email,recipient_name:`${ie.first_name} ${ie.last_name||""}`.trim(),contact_id:ie.id,sent_via:"gmail"})).share_token}catch(he){console.warn("Tracking record failed for",ie.email,he)}const te=W(ie.first_name,ne),J=v.replace(/\{\{first_name\}\}/gi,ie.first_name),{data:ce,error:_e}=await q.functions.invoke("gmail-send",{body:{to:ie.email,subject:J,body:te,contactId:ie.id}});if(_e||!(ce!=null&&ce.success))throw new Error((ce==null?void 0:ce.error)||(_e==null?void 0:_e.message)||"Send failed");X+=1}catch(ne){console.error("Failed to send to",ie.email,ne),ae+=1}finally{P({done:X+ae,total:R.length,failed:ae}),await new Promise(ne=>setTimeout(ne,250))}E(!1),ae===0?re.success(`Video sent to ${X} ${X===1?"contact":"contacts"}!`):re.warning(`Sent to ${X}, ${ae} failed. Check console for details.`),t(!1),i==null||i()},G=()=>{if(!x)return;const X=W("there",void 0);l("/admin/email-campaigns/new",{state:{directRecipients:R.map(ae=>({email:ae.email,name:`${ae.first_name} ${ae.last_name||""}`.trim()})),initialSubject:v,initialBodyHtml:X}}),t(!1)},Y=!!x&&!!v.trim()&&R.length>0&&(O?a:r);return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Os,{className:"sm:max-w-[640px] max-h-[90vh] overflow-y-auto",children:[e.jsxs(Us,{children:[e.jsxs(Bs,{className:"flex items-center gap-2",children:[e.jsx(ua,{className:"h-5 w-5 text-primary"}),"Send Video to ",R.length," ",R.length===1?"Contact":"Contacts"]}),e.jsxs(Ir,{children:[O?e.jsxs("span",{className:"flex items-center gap-1.5 text-amber-600",children:[e.jsx(xm,{className:"h-3.5 w-3.5"}),R.length," recipients — will be sent as a Mass Email campaign"]}):e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(mn,{className:"h-3.5 w-3.5"}),"Sent individually via your connected Gmail"]}),D>0&&e.jsxs("span",{className:"ml-2 text-xs text-muted-foreground",children:["(",D," skipped — no email)"]})]})]}),e.jsxs("div",{className:"space-y-4",children:[O&&!a&&e.jsxs("div",{className:"flex items-start gap-2 p-3 rounded-md bg-destructive/10 text-destructive text-sm",children:[e.jsx(ll,{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 ",R.length," recipients."]})]}),!O&&!r&&e.jsxs("div",{className:"flex items-start gap-2 p-3 rounded-md bg-destructive/10 text-destructive text-sm",children:[e.jsx(ll,{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(ee,{children:"Choose a video"}),e.jsxs($,{type:"button",variant:"ghost",size:"sm",className:"gap-1",onClick:()=>l("/innercircle/videos/record"),children:[e.jsx(dn,{className:"h-3.5 w-3.5"})," Record new"]})]}),e.jsxs("div",{className:"relative",children:[e.jsx(Kr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(pe,{placeholder:"Search your video library...",value:f,onChange:X=>g(X.target.value),className:"pl-10"})]}),e.jsx("div",{className:"max-h-[220px] overflow-y-auto space-y-2 border rounded-md p-2",children:h?e.jsxs(e.Fragment,{children:[e.jsx(yn,{className:"h-14 w-full"}),e.jsx(yn,{className:"h-14 w-full"})]}):U.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."}):U.map(X=>{const ae=(x==null?void 0:x.id)===X.id;return e.jsxs("button",{type:"button",onClick:()=>y(X),className:`w-full flex items-center gap-3 p-2 rounded-md border text-left transition-colors ${ae?"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:[X.thumbnail_url?e.jsx("img",{src:X.thumbnail_url,alt:"",className:"w-full h-full object-cover",referrerPolicy:"no-referrer"}):e.jsx(rf,{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(Bu,{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:X.title||"Untitled Video"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[X.duration_seconds?`${Math.round(X.duration_seconds)}s`:"",X.created_at?` · ${new Date(X.created_at).toLocaleDateString()}`:""]})]})]},X.id)})})]}),e.jsx(Gc,{}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{htmlFor:"bulk-video-subject",children:"Subject"}),e.jsx(pe,{id:"bulk-video-subject",value:v,onChange:X=>b(X.target.value),placeholder:"I recorded a video for you"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs(ee,{htmlFor:"bulk-video-message",children:["Personal message ",e.jsxs("span",{className:"text-xs text-muted-foreground",children:["(use ","{{first_name}}"," to personalize)"]})]}),e.jsx(Rs,{id:"bulk-video-message",value:w,onChange:X=>S(X.target.value),rows:4,className:"resize-y"})]}),C&&I.total>0&&e.jsxs("div",{className:"p-3 rounded-md bg-muted text-sm",children:["Sending… ",I.done," / ",I.total,I.failed>0&&e.jsxs("span",{className:"text-destructive ml-2",children:["(",I.failed," failed)"]})]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[e.jsx($,{variant:"outline",onClick:()=>t(!1),disabled:C,children:"Cancel"}),O?e.jsxs($,{onClick:G,disabled:!Y,className:"gap-2",children:[e.jsx(xm,{className:"h-4 w-4"}),"Continue in Mass Email"]}):e.jsxs($,{onClick:V,disabled:!Y||C,className:"gap-2",children:[C?e.jsx(kt,{className:"h-4 w-4 animate-spin"}):e.jsx(Yr,{className:"h-4 w-4"}),C?"Sending…":`Send to ${R.length}`]})]})]})]})})}function Fie(){const s=Sa();return tt({queryKey:["drip-campaigns",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await q.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(n)throw n;return t},enabled:!!s})}function N9n(s){return tt({queryKey:["drip-campaign",s],queryFn:async()=>{if(!s)return null;const{data:t,error:n}=await q.from("drip_campaigns").select("*").eq("id",s).maybeSingle();if(n)throw n;return t},enabled:!!s})}function k9n(){const s=Sa(),t=Vt();return ft({mutationFn:async n=>{if(!s)throw new Error("Not authenticated");const{data:r,error:a}=await q.from("drip_campaigns").insert({owner_user_id:s,name:n.name,description:n.description??null,category:n.category??"nurture",icon:n.icon??"🌱",cover_color:n.cover_color??"from-emerald-500 to-teal-600",goal:n.goal??null,is_active:!1}).select().single();if(a)throw a;return r},onSuccess:()=>t.invalidateQueries({queryKey:["drip-campaigns"]})})}function qQt(){const s=Vt();return ft({mutationFn:async({id:t,...n})=>{const{data:r,error:a}=await q.from("drip_campaigns").update(n).eq("id",t).select().single();if(a)throw a;return r},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["drip-campaigns"]}),s.invalidateQueries({queryKey:["drip-campaign",n.id]})}})}function S9n(){const s=Vt();return ft({mutationFn:async t=>{const{error:n}=await q.from("drip_campaigns").delete().eq("id",t);if(n)throw n},onSuccess:()=>s.invalidateQueries({queryKey:["drip-campaigns"]})})}function jit(){const s=Sa(),t=Vt();return ft({mutationFn:async n=>{if(!s)throw new Error("Not authenticated");const[{data:r,error:a},{data:i,error:l}]=await Promise.all([q.from("drip_campaigns").select("*").eq("id",n).single(),q.from("drip_campaign_steps").select("*").eq("campaign_id",n).order("step_order")]);if(a)throw a;if(l)throw l;const{data:o,error:c}=await q.from("drip_campaigns").insert({owner_user_id:s,name:r.name,description:r.description,category:r.category,icon:r.icon,cover_color:r.cover_color,goal:r.goal,is_active:!1,is_starter:!1}).select().single();if(c)throw c;if(i&&i.length>0){const d=i.map(h=>({campaign_id:o.id,step_order:h.step_order,channel:h.channel,subject:h.subject,body:h.body,video_url:h.video_url,delay_type:h.delay_type,delay_days:h.delay_days,delay_hours:h.delay_hours,anchor_field:h.anchor_field,anchor_offset_days:h.anchor_offset_days,send_window_start:h.send_window_start,send_window_end:h.send_window_end})),{error:u}=await q.from("drip_campaign_steps").insert(d);if(u)throw u}return o},onSuccess:()=>t.invalidateQueries({queryKey:["drip-campaigns"]})})}function VQt(s){return tt({queryKey:["drip-campaign-steps",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await q.from("drip_campaign_steps").select("*").eq("campaign_id",s).order("step_order",{ascending:!0});if(n)throw n;return t},enabled:!!s})}function C9n(){const s=Vt();return ft({mutationFn:async t=>{const{data:n,error:r}=await q.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(r)throw r;return n},onSuccess:(t,n)=>s.invalidateQueries({queryKey:["drip-campaign-steps",n.campaign_id]})})}function A9n(){const s=Vt();return ft({mutationFn:async({id:t,campaign_id:n,...r})=>{const{data:a,error:i}=await q.from("drip_campaign_steps").update(r).eq("id",t).select().single();if(i)throw i;return{data:a,campaign_id:n}},onSuccess:t=>s.invalidateQueries({queryKey:["drip-campaign-steps",t.campaign_id]})})}function E9n(){const s=Vt();return ft({mutationFn:async({id:t,campaign_id:n})=>{const{error:r}=await q.from("drip_campaign_steps").delete().eq("id",t);if(r)throw r;return n},onSuccess:t=>s.invalidateQueries({queryKey:["drip-campaign-steps",t]})})}function T9n(s){return tt({queryKey:["campaign-enrollments",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await q.from("drip_campaign_enrollments").select("*, contact:innercircle_contacts(id, first_name, last_name, email)").eq("campaign_id",s).order("enrolled_at",{ascending:!1});if(n)throw n;return t},enabled:!!s})}function M9n(s){return tt({queryKey:["campaign-enrollment-count",s],queryFn:async()=>{if(!s)return 0;const{count:t,error:n}=await q.from("drip_campaign_enrollments").select("id",{count:"exact",head:!0}).eq("campaign_id",s).eq("status","active");if(n)throw n;return t??0},enabled:!!s,staleTime:3e4})}function Nit(){const s=Vt();return ft({mutationFn:async({campaignId:t,contactIds:n})=>{const{data:r,error:a}=await q.functions.invoke("enroll-contacts-in-campaign",{body:{campaign_id:t,contact_ids:n}});if(a)throw a;return r},onSuccess:()=>{s.invalidateQueries({queryKey:["campaign-enrollments"]}),s.invalidateQueries({queryKey:["contact-campaigns"]})}})}function P9n(){const s=Vt();return ft({mutationFn:async({id:t,status:n})=>{const r={status:n};n==="paused"&&(r.paused_at=new Date().toISOString()),n==="exited"&&(r.exited_at=new Date().toISOString(),r.exit_reason="manual");const{data:a,error:i}=await q.from("drip_campaign_enrollments").update(r).eq("id",t).select().single();if(i)throw i;return a},onSuccess:()=>{s.invalidateQueries({queryKey:["campaign-enrollments"]}),s.invalidateQueries({queryKey:["contact-campaigns"]})}})}const I9n=[{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"}],uDe={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"},L9n={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 R9n({open:s,onOpenChange:t,subject:n,body:r,ownerUserId:a,stepLabel:i}){const[l,o]=j.useState(!1),[c,d]=j.useState(""),[u,h]=j.useState(""),[m,f]=j.useState("desktop"),[g,x]=j.useState(""),[y,v]=j.useState(!1);j.useEffect(()=>{if(!s)return;let w=!1;return(async()=>{var S,C;o(!0);try{const{data:E}=await q.auth.getSession();g||x(((C=(S=E==null?void 0:E.session)==null?void 0:S.user)==null?void 0:C.email)||"");const{data:I,error:P}=await q.functions.invoke("process-drip-campaigns",{body:{action:"preview",subject:n,body:r,owner_user_id:a||void 0}});if(P)throw P;if(w)return;d((I==null?void 0:I.html)||""),h((I==null?void 0:I.subject)||n)}catch{w||re.error("Could not build preview")}finally{w||o(!1)}})(),()=>{w=!0}},[s,n,r,a]);const b=async()=>{if(g.trim()){v(!0);try{const{data:w,error:S}=await q.functions.invoke("process-drip-campaigns",{body:{action:"test_send",subject:n,body:r,to:g.trim(),owner_user_id:a||void 0}});if(S)throw S;w!=null&&w.success?re.success(`Test email sent to ${g.trim()}`):re.error((w==null?void 0:w.error)||"Could not send test email",{duration:1e4})}catch{re.error("Could not send test email")}finally{v(!1)}}};return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Os,{className:"sm:max-w-3xl max-h-[92vh] flex flex-col p-0 gap-0",children:[e.jsxs(Us,{className:"p-5 pb-3 border-b shrink-0",children:[e.jsxs(Bs,{children:["Email preview",i?` — ${i}`:""]}),e.jsx(Ir,{children:"Exactly how this email will look when it sends, with sample contact details filled in."})]}),e.jsxs("div",{className:"px-5 py-3 border-b shrink-0 space-y-2",children:[e.jsx("div",{className:"text-xs text-muted-foreground",children:"Subject"}),e.jsx("div",{className:"text-sm font-medium",children:u||n||"(no subject)"}),e.jsxs("div",{className:"flex items-center gap-1.5 pt-1",children:[e.jsxs($,{variant:m==="desktop"?"secondary":"ghost",size:"sm",className:"h-7 text-xs",onClick:()=>f("desktop"),children:[e.jsx(sk,{className:"h-3.5 w-3.5 mr-1"})," Desktop"]}),e.jsxs($,{variant:m==="mobile"?"secondary":"ghost",size:"sm",className:"h-7 text-xs",onClick:()=>f("mobile"),children:[e.jsx(_1,{className:"h-3.5 w-3.5 mr-1"})," Mobile"]})]})]}),e.jsx("div",{className:"flex-1 overflow-y-auto overscroll-contain bg-muted/30 p-4 min-h-0",children:l?e.jsxs("div",{className:"flex items-center justify-center py-16 text-sm text-muted-foreground",children:[e.jsx(kt,{className:"h-4 w-4 mr-2 animate-spin"})," Building preview…"]}):e.jsx("div",{className:"mx-auto bg-background rounded-lg overflow-hidden border",style:{maxWidth:m==="mobile"?390:"100%"},children:e.jsx("iframe",{title:"Email preview",srcDoc:c,sandbox:"",className:"w-full",style:{height:620,border:0,background:"#fff"}})})}),e.jsxs("div",{className:"border-t p-4 shrink-0 flex flex-col sm:flex-row sm:items-end gap-3",children:[e.jsxs("div",{className:"flex-1 space-y-1.5",children:[e.jsx(ee,{className:"text-xs",children:"Send a test to"}),e.jsx(pe,{type:"email",value:g,onChange:w=>x(w.target.value),placeholder:"you@email.com",className:"h-9",onKeyDown:w=>w.key==="Enter"&&b()})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx($,{variant:"outline",onClick:()=>t(!1),children:"Close"}),e.jsxs($,{onClick:b,disabled:y||!g.trim(),children:[y?e.jsx(kt,{className:"h-4 w-4 mr-1.5 animate-spin"}):e.jsx(Yr,{className:"h-4 w-4 mr-1.5"}),"Send test"]})]})]})]})})}function o9({userId:s,onSelect:t,onSelectVideo:n,triggerLabel:r="Library",triggerSize:a="sm",triggerVariant:i="outline",triggerClassName:l}){const[o,c]=j.useState(!1),[d,u]=j.useState([]),[h,m]=j.useState(!1),[f,g]=j.useState("");j.useEffect(()=>{!o||!s||(m(!0),q.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:y})=>{u(y||[]),m(!1)}))},[o,s]);const x=d.filter(y=>!f||(y.title||y.recipient_name||"").toLowerCase().includes(f.toLowerCase()));return e.jsxs(zs,{open:o,onOpenChange:c,children:[e.jsx(jl,{asChild:!0,children:e.jsxs($,{variant:i,size:a,className:l||"gap-1.5 shrink-0",children:[e.jsx(rf,{className:"h-3.5 w-3.5"}),r]})}),e.jsxs(Os,{className:"max-w-lg max-h-[70vh] flex flex-col",children:[e.jsxs(Us,{children:[e.jsx(Bs,{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(Kr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(pe,{placeholder:"Search videos...",value:f,onChange:y=>g(y.target.value),className:"pl-10"})]}),e.jsx("div",{className:"flex-1 overflow-y-auto space-y-2 min-h-0",children:h?e.jsxs(e.Fragment,{children:[e.jsx(yn,{className:"h-16 w-full"}),e.jsx(yn,{className:"h-16 w-full"})]}):x.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"}):x.map(y=>e.jsxs("button",{onClick:()=>{t(y.playback_url||""),n==null||n(y),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:y.thumbnail_url?e.jsx("img",{src:y.thumbnail_url,alt:"",className:"w-full h-full object-cover",referrerPolicy:"no-referrer",onError:v=>{const b=v.currentTarget.parentElement;if(b){v.currentTarget.remove();const w=document.createElement("span");w.innerHTML="🎬",w.className="text-lg",b.appendChild(w)}}}):e.jsx(ua,{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:y.title||y.recipient_name||"Untitled Video"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[y.duration_seconds?`${Math.round(y.duration_seconds)}s`:"",y.created_at?` · ${new Date(y.created_at).toLocaleDateString()}`:""]})]})]},y.id))})]})]})}function D9n(){return tt({queryKey:["video-script-categories"],queryFn:async()=>{const{data:s,error:t}=await q.from("video_script_categories").select("*").order("sort_order");if(t)throw t;return s}})}function F9n(s){return tt({queryKey:["video-scripts",s],queryFn:async()=>{let t=q.from("video_scripts").select("*, category:video_script_categories(*)").eq("is_active",!0).order("title");const{data:n,error:r}=await t;if(r)throw r;return n}})}function O9n(){const{user:s}=vs();return tt({queryKey:["user-video-scripts",s==null?void 0:s.id],queryFn:async()=>{if(!(s!=null&&s.id))return[];const{data:t,error:n}=await q.from("user_video_scripts").select("*, category:video_script_categories(*)").eq("owner_user_id",s.id).order("title");if(n)throw n;return t},enabled:!!(s!=null&&s.id)})}function z9n(){const{user:s}=vs(),t=Vt();return ft({mutationFn:async n=>{if(!(s!=null&&s.id))throw new Error("Not authenticated");const{data:r,error:a}=await q.from("user_video_scripts").insert([{owner_user_id:s.id,source_script_id:n.id,category_id:n.category_id,title:n.title,script_text:n.script_text,tags:n.tags,is_custom:!1}]).select().single();if(a)throw a;return r},onSuccess:()=>{t.invalidateQueries({queryKey:["user-video-scripts"]})}})}function B9n(s){const{user:t}=vs();return tt({queryKey:["agent-videos",t==null?void 0:t.id,s],queryFn:async()=>{if(!(t!=null&&t.id))return[];let n=q.from("agent_videos").select("*, contact:innercircle_contacts(id, first_name, last_name)").eq("owner_user_id",t.id).order("created_at",{ascending:!1});n=n.eq("is_deleted",!1);const{data:r,error:a}=await n;if(a)throw a;return r},enabled:!!(t!=null&&t.id)})}function $9n(s){return tt({queryKey:["agent-video",s],queryFn:async()=>{const{data:t,error:n}=await q.from("agent_videos").select("*, contact:innercircle_contacts(id, first_name, last_name)").eq("id",s).single();if(n)throw n;return t},enabled:!!s})}function x3(){const{user:s}=vs(),t=Vt();return ft({mutationFn:async n=>{if(!(s!=null&&s.id))throw new Error("Not authenticated");const{data:r,error:a}=await q.from("agent_videos").insert([{owner_user_id:s.id,contact_id:n.contact_id,bunny_video_id:n.bunny_video_id,playback_url:n.playback_url,thumbnail_url:n.thumbnail_url,preview_url:n.preview_url,duration_seconds:n.duration_seconds,file_size_mb:n.file_size_mb||0,title:n.title,notes:n.notes,task_id:n.task_id,status:n.status||"processing",touch_type:n.touch_type||"video",page_template:"default",category:n.category||"general"}]).select("*, share_token").single();if(a)throw a;return r},onSuccess:()=>{t.invalidateQueries({queryKey:["agent-videos"]}),t.invalidateQueries({queryKey:["storage-usage"]})}})}function U9n(){const s=Vt();return ft({mutationFn:async({id:t,...n})=>{const{data:r,error:a}=await q.from("agent_videos").update(n).eq("id",t).select().single();if(a)throw a;return r},onSuccess:t=>{s.invalidateQueries({queryKey:["agent-videos"]}),s.invalidateQueries({queryKey:["agent-video",t.id]})}})}function q9n(){const s=Vt();return ft({mutationFn:async({id:t,bunnyVideoId:n,hardDelete:r=!1})=>{if(console.log("Deleting video:",{id:t,bunnyVideoId:n,hardDelete:r}),n){console.log("Calling bunny-upload delete for videoId:",n);const{data:a,error:i}=await q.functions.invoke("bunny-upload",{body:{action:"delete",videoId:n,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(r){console.log("Hard deleting from database:",t);const{error:a}=await q.from("agent_videos").delete().eq("id",t);if(a)throw a}else{console.log("Soft deleting from database:",t);const{error:a}=await q.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 hDe(){const{user:s}=vs();return tt({queryKey:["storage-usage",s==null?void 0:s.id],queryFn:async()=>{if(!(s!=null&&s.id))return null;const{data:t,error:n}=await q.from("agent_storage_usage").select("*").eq("user_id",s.id).maybeSingle();if(n)throw n;return t||{user_id:s.id,total_storage_mb:0,storage_tier:"basic",max_storage_mb:1024}},enabled:!!(s!=null&&s.id)})}function HQt(){const{data:s,isLoading:t}=hDe(),n=s?s.total_storage_mb0?s.total_storage_mb/s.max_storage_mb*100:0,i=a>=80;return{canRecord:n,remainingMb:r,usagePercent:a,isNearLimit:i,storage:s,isLoading:t}}async function P6(s){const{data:t,error:n}=await q.functions.invoke("bunny-upload",{body:{action:"create",title:s,isAgentVideo:!0}});if(n)throw n;return t}async function I6(s){const{data:t,error:n}=await q.functions.invoke("bunny-upload",{body:{action:"upload-url",videoId:s,isAgentVideo:!0}});if(n)throw n;return t}async function gk(s){const{data:t,error:n}=await q.functions.invoke("bunny-upload",{body:{action:"status",videoId:s,isAgentVideo:!0}});if(n)throw n;return t}function V9n(){const{user:s}=vs(),t=Vt();return ft({mutationFn:async({contactId:n,videoId:r,notes:a})=>{if(!(s!=null&&s.id))throw new Error("Not authenticated");const{data:i}=await q.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 q.from("contact_touch_logs").insert([{owner_user_id:s.id,contact_id:n,action_type_id:i.id,notes:a||`Quick Video Touch - Video ID: ${r}`}]).select().single();if(o)throw o;return l},onSuccess:()=>{t.invalidateQueries({queryKey:["contact-touch-logs"]}),t.invalidateQueries({queryKey:["contacts"]})}})}function GQt({open:s,onOpenChange:t,onUploadComplete:n}){const{data:r}=z_(),{data:a}=hDe(),i=x3(),l=j.useRef(null),[o,c]=j.useState(null),[d,u]=j.useState(""),[h,m]=j.useState(""),[f,g]=j.useState(""),[x,y]=j.useState(!1),[v,b]=j.useState(0),[w,S]=j.useState("idle"),C=(a==null?void 0:a.total_storage_mb)||0,I=((a==null?void 0:a.max_storage_mb)||1024)-C,P=U=>{var G;const W=(G=U.target.files)==null?void 0:G[0];if(!W)return;if(!W.type.startsWith("video/")){re.error("Please select a video file");return}const V=W.size/(1024*1024);if(V>500){re.error("Video file must be less than 500MB");return}if(V>I){re.error(`Not enough storage. You have ${I.toFixed(1)} MB remaining.`);return}c(W),d||u(W.name.replace(/\.[^/.]+$/,""))},R=async()=>{if(!o){re.error("Please select a video file");return}y(!0),b(0),S("creating");try{const{data:U,error:W}=await q.functions.invoke("bunny-upload",{body:{action:"create",title:d||o.name,isAgentVideo:!0}});if(W)throw new Error(W.message);const{videoId:V,libraryId:G}=U;S("uploading");const{data:Y,error:X}=await q.functions.invoke("bunny-upload",{body:{action:"upload-url",videoId:V,isAgentVideo:!0}});if(X)throw new Error(X.message);await new Promise((ne,te)=>{const J=new XMLHttpRequest;J.upload.addEventListener("progress",ce=>{if(ce.lengthComputable){const _e=Math.round(ce.loaded/ce.total*100);b(_e)}}),J.addEventListener("load",()=>{J.status>=200&&J.status<300?ne():te(new Error(`Upload failed with status ${J.status}`))}),J.addEventListener("error",()=>te(new Error("Upload failed"))),J.open("PUT",Y.uploadUrl),J.setRequestHeader("AccessKey",Y.apiKey),J.send(o)}),S("processing");const ae=o.size/(1024*1024),ie=`https://iframe.mediadelivery.net/embed/${G}/${V}`;await i.mutateAsync({bunny_video_id:V,playback_url:ie,file_size_mb:ae,title:d||o.name,notes:h||void 0,contact_id:f||void 0,status:"processing",touch_type:"video_upload"}),re.success("Video uploaded successfully! Processing may take a few minutes."),n==null||n(ie),D()}catch(U){console.error("Upload error:",U),re.error(U instanceof Error?U.message:"Failed to upload video")}finally{y(!1),S("idle")}},D=()=>{x||(c(null),u(""),m(""),g(""),b(0),S("idle"),t(!1))},O=()=>{switch(w){case"creating":return"Preparing upload...";case"uploading":return`Uploading... ${v}%`;case"processing":return"Saving video...";default:return""}};return e.jsx(zs,{open:s,onOpenChange:D,children:e.jsxs(Os,{className:"sm:max-w-md",children:[e.jsxs(Us,{children:[e.jsx(Bs,{children:"Upload Video"}),e.jsx(Ir,{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(ee,{children:"Video File"}),o?e.jsxs("div",{className:"flex items-center gap-3 p-3 bg-muted rounded-lg",children:[e.jsx(ua,{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"]})]}),!x&&e.jsx($,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:U=>{U.stopPropagation(),c(null)},children:e.jsx(gr,{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 U;return(U=l.current)==null?void 0:U.click()},children:[e.jsx(ni,{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:P,disabled:x})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"title",children:"Title"}),e.jsx(pe,{id:"title",value:d,onChange:U=>u(U.target.value),placeholder:"Enter video title",disabled:x})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Associate with Contact (optional)"}),e.jsxs(ms,{value:f||"__none__",onValueChange:U=>g(U==="__none__"?"":U),disabled:x,children:[e.jsx(us,{children:e.jsx(fs,{placeholder:"Select a contact"})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"__none__",children:"No contact"}),r==null?void 0:r.map(U=>e.jsxs(Ge,{value:U.id,children:[U.first_name," ",U.last_name||""]},U.id))]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"notes",children:"Notes (optional)"}),e.jsx(Rs,{id:"notes",value:h,onChange:U=>m(U.target.value),placeholder:"Add any notes about this video",rows:2,disabled:x})]}),x&&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(kt,{className:"h-4 w-4 animate-spin"}),e.jsx("span",{children:O()})]}),e.jsx(Yi,{value:w==="uploading"?v:w==="processing"?100:10})]})]}),e.jsxs(Ar,{children:[e.jsx($,{variant:"outline",onClick:D,disabled:x,children:"Cancel"}),e.jsx($,{onClick:R,disabled:!o||x,children:x?e.jsxs(e.Fragment,{children:[e.jsx(kt,{className:"h-4 w-4 mr-2 animate-spin"}),"Uploading..."]}):e.jsxs(e.Fragment,{children:[e.jsx(ni,{className:"h-4 w-4 mr-2"}),"Upload Video"]})})]})]})})}const H9n=["🌱","💎","🏠","🔑","📧","💌","🎂","🥂","🤝","⭐","🎉","📞"],G9n={" ":" ","&":"&","<":"<",">":">",""":'"',"'":"'"},uCt=s=>s?/<\/?[a-z][\s\S]*>/i.test(s)?s.replace(//gi,"").replace(//gi,"").replace(//gi,` `).replace(/<\/p\s*>/gi,` `).replace(/<\/div\s*>/gi,` `).replace(/<\/h[1-6]\s*>/gi,` `).replace(/<\/li\s*>/gi,` `).replace(/]*>/gi,"• ").replace(/<[^>]+>/g,"").replace(/&(nbsp|amp|lt|gt|quot);|'/gi,t=>G9n[t.toLowerCase()]||t).replace(/\n{3,}/g,` `).replace(/[ \t]+\n/g,` `).trim():s:"";function WQt({open:s,onOpenChange:t,campaignId:n}){const[r,a]=j.useState(n??null),[i,l]=j.useState("details");j.useEffect(()=>{a(n??null),l("details")},[n,s]);const o=r,c=!!o,{data:d}=N9n(o||void 0),{data:u,isLoading:h}=VQt(o||void 0),m=k9n(),f=qQt(),g=C9n(),[x,y]=j.useState(""),[v,b]=j.useState(""),[w,S]=j.useState("nurture"),[C,E]=j.useState("🌱"),[I,P]=j.useState("");j.useEffect(()=>{d?(y(d.name),b(d.description||""),S(d.category),E(d.icon),P(d.goal||"")):c||(y(""),b(""),S("nurture"),E("🌱"),P(""))},[d,c,s]);const R=L9n[w],D=async()=>{if(!x.trim()){re.error("Give your campaign a name");return}try{if(c&&o)await f.mutateAsync({id:o,name:x,description:v,category:w,icon:C,goal:I,cover_color:R}),re.success("Campaign updated");else{const U=await m.mutateAsync({name:x,description:v,category:w,icon:C,goal:I,cover_color:R});return re.success("Campaign created — now add your first step!"),a(U.id),l("steps"),U}}catch(U){re.error(U.message||"Failed to save")}},O=async()=>{if(!o){re.error("Save the campaign first, then add steps");return}const U=((u==null?void 0:u.length)||0)+1;try{await g.mutateAsync({campaign_id:o,step_order:U,channel:"email",subject:"",body:"",delay_type:"relative",delay_days:U===1?0:2,delay_hours:0})}catch{re.error("Failed to add step")}};return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Os,{className:"max-w-3xl max-h-[90vh] flex flex-col p-0 overflow-hidden",children:[e.jsx("div",{className:`bg-gradient-to-br ${R} 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:C}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx(Bs,{className:"text-lg font-bold text-white",children:c?"Edit Campaign":"Create New Campaign"}),e.jsx(Ir,{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(ha,{value:i,onValueChange:U=>l(U),className:"flex-1 flex flex-col overflow-hidden min-h-0",children:[e.jsxs(ma,{className:"mx-5 mt-4 grid grid-cols-2 w-fit",children:[e.jsx(Zt,{value:"details",children:"Details"}),e.jsxs(Zt,{value:"steps",disabled:!c,children:["Steps ",u&&u.length>0&&e.jsx(Be,{variant:"secondary",className:"ml-1.5 text-[10px]",children:u.length})]})]}),e.jsx(Xt,{value:"details",className:"flex-1 overflow-y-auto overscroll-contain mt-0 min-h-0 data-[state=inactive]:hidden",children:e.jsx("div",{children:e.jsxs("div",{className:"p-5 space-y-4",children:[e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs",children:"Campaign Name *"}),e.jsx(pe,{value:x,onChange:U=>y(U.target.value),placeholder:"e.g. New Buyer Lead — 7 Touch Nurture",className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs",children:"Description"}),e.jsx(Rs,{value:v,onChange:U=>b(U.target.value),placeholder:"What's this campaign for? When should you use it?",rows:2,className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs",children:"Goal (optional)"}),e.jsx(pe,{value:I,onChange:U=>P(U.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(ee,{className:"text-xs",children:"Category"}),e.jsxs(ms,{value:w,onValueChange:U=>S(U),children:[e.jsx(us,{className:"mt-1",children:e.jsx(fs,{})}),e.jsx(hs,{children:Object.entries(uDe).map(([U,W])=>e.jsx(Ge,{value:U,children:W},U))})]})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs",children:"Icon"}),e.jsx("div",{className:"flex gap-1.5 flex-wrap mt-1",children:H9n.map(U=>e.jsx("button",{type:"button",onClick:()=>E(U),className:`h-8 w-8 rounded-md text-lg flex items-center justify-center transition-all ${C===U?"bg-primary/15 ring-2 ring-primary":"hover:bg-muted"}`,children:U},U))})]})]}),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(Xt,{value:"steps",className:"flex-1 overflow-y-auto overscroll-contain mt-0 min-h-0 data-[state=inactive]:hidden",children:e.jsx("div",{children:e.jsx("div",{className:"p-5 space-y-3",children:h?e.jsx("div",{className:"text-center text-sm text-muted-foreground py-8",children:"Loading steps…"}):!u||u.length===0?e.jsxs("div",{className:"text-center py-10 border border-dashed rounded-xl",children:[e.jsx(Nn,{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($,{size:"sm",onClick:O,disabled:g.isPending,children:[e.jsx(dn,{className:"h-3.5 w-3.5 mr-1.5"})," Add first step"]})]}):e.jsxs(e.Fragment,{children:[u.map((U,W)=>e.jsx(W9n,{step:U,index:W,totalSteps:u.length},U.id)),e.jsxs($,{variant:"outline",size:"sm",onClick:O,disabled:g.isPending,className:"w-full",children:[g.isPending?e.jsx(kt,{className:"h-3.5 w-3.5 mr-1.5 animate-spin"}):e.jsx(dn,{className:"h-3.5 w-3.5 mr-1.5"}),"Add another step"]})]})})})})]}),e.jsxs(Ar,{className:"border-t p-4 shrink-0",children:[e.jsx($,{variant:"outline",onClick:()=>t(!1),children:c?"Done":"Cancel"}),e.jsxs($,{onClick:D,disabled:m.isPending||f.isPending,children:[(m.isPending||f.isPending)&&e.jsx(kt,{className:"h-3.5 w-3.5 mr-1.5 animate-spin"}),c?"Save Changes":"Create Campaign"]})]})]})})}function W9n({step:s,index:t,totalSteps:n}){const r=A9n(),a=E9n(),i=Sa(),[l,o]=j.useState(!1),[c,d]=j.useState(()=>({...s,body:uCt(s.body)})),[u,h]=j.useState(!1),[m,f]=j.useState(!1),[g,x]=j.useState(""),[y,v]=j.useState(!1),[b,w]=j.useState(!1);j.useEffect(()=>{d({...s,body:uCt(s.body)})},[s]);const S=JSON.stringify(c)!==JSON.stringify(s),C=async()=>{h(!0);try{await r.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}),re.success(`Step ${t+1} saved`)}catch{re.error("Failed to save step")}finally{h(!1)}},E=async()=>{if(await fo(`Delete step ${t+1}?`))try{await a.mutateAsync({id:s.id,campaign_id:s.campaign_id}),re.success("Step deleted")}catch{re.error("Failed to delete")}},I=R=>{d({...c,body:c.body+R})},P=()=>{if(c.delay_type==="calendar_anchor"){const D=c.anchor_field==="birthday"?"birthday":"home anniversary",O=c.anchor_offset_days||0;return O===0?`On their ${D}`:O<0?`${Math.abs(O)}d before ${D}`:`${O}d after ${D}`}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(Ta,{className:"h-3 w-3"}):e.jsx(da,{className:"h-3 w-3"}),e.jsx("span",{children:P()}),e.jsx("span",{children:"·"}),c.channel==="email"?e.jsx(mn,{className:"h-3 w-3"}):e.jsx(eo,{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(v1,{className:"h-4 w-4 text-muted-foreground"}):e.jsx(Tl,{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(ee,{className:"text-xs",children:"Channel"}),e.jsxs(ms,{value:c.channel,onValueChange:R=>d({...c,channel:R}),children:[e.jsx(us,{className:"mt-1 h-9",children:e.jsx(fs,{})}),e.jsx(hs,{children:e.jsx(Ge,{value:"email",children:"📧 Email"})})]})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs",children:"Timing Type"}),e.jsxs(ms,{value:c.delay_type,onValueChange:R=>d({...c,delay_type:R}),children:[e.jsx(us,{className:"mt-1 h-9",children:e.jsx(fs,{})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"relative",children:"⏱ Relative delay"}),e.jsx(Ge,{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(ee,{className:"text-xs",children:"Days delay"}),e.jsx(pe,{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(ee,{className:"text-xs",children:"Hours delay"}),e.jsx(pe,{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(ee,{className:"text-xs",children:"Anchor"}),e.jsxs(ms,{value:c.anchor_field||"birthday",onValueChange:R=>d({...c,anchor_field:R}),children:[e.jsx(us,{className:"mt-1 h-9",children:e.jsx(fs,{})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"birthday",children:"🎂 Birthday"}),e.jsx(Ge,{value:"home_anniversary",children:"🏠 Home Anniversary"})]})]})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs",children:"Offset (days, negative = before)"}),e.jsx(pe,{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(ee,{className:"text-xs",children:"Subject Line"}),e.jsx(pe,{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(ee,{className:"text-xs",children:"Email Body"}),e.jsxs("span",{className:"text-[10px] text-muted-foreground",children:[c.body.length," chars"]})]}),e.jsx(Rs,{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:"}),I9n.map(R=>e.jsx("button",{type:"button",onClick:()=>I(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(ee,{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(ua,{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($,{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(o9,{userId:i||void 0,onSelect:R=>d({...c,video_url:R}),triggerSize:"sm",triggerClassName:"gap-1.5 flex-1 min-w-[120px]"}),e.jsxs($,{variant:"outline",size:"sm",className:"gap-1 text-xs flex-1 min-w-[120px]",onClick:()=>v(!0),children:[e.jsx(ni,{className:"h-3 w-3"})," Upload"]}),e.jsxs($,{variant:"ghost",size:"sm",className:"gap-1 text-xs text-muted-foreground flex-1 min-w-[120px]",onClick:()=>{x(""),f(!0)},children:[e.jsx(Ad,{className:"h-3 w-3"})," Paste URL"]}),e.jsx(GQt,{open:y,onOpenChange:v,onUploadComplete:R=>d({...c,video_url:R})}),e.jsx(zs,{open:m,onOpenChange:f,children:e.jsxs(Os,{className:"sm:max-w-md",children:[e.jsxs(Us,{children:[e.jsx(Bs,{children:"Add video URL"}),e.jsx(Ir,{children:"Paste a YouTube, Loom, or direct video URL."})]}),e.jsx(pe,{value:g,onChange:R=>x(R.target.value),placeholder:"https://...",autoFocus:!0,onKeyDown:R=>{R.key==="Enter"&&g.trim()&&(d({...c,video_url:g.trim()}),f(!1))}}),e.jsxs(Ar,{children:[e.jsx($,{variant:"ghost",onClick:()=>f(!1),children:"Cancel"}),e.jsx($,{disabled:!g.trim(),onClick:()=>{d({...c,video_url:g.trim()}),f(!1)},children:"Add video"})]})]})})]})]}),e.jsxs("div",{className:"flex items-center justify-between pt-2 border-t",children:[e.jsxs($,{variant:"ghost",size:"sm",onClick:E,className:"text-destructive hover:text-destructive",children:[e.jsx(Wn,{className:"h-3.5 w-3.5 mr-1"})," Delete step"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[c.channel==="email"&&e.jsxs($,{variant:"outline",size:"sm",onClick:()=>w(!0),children:[e.jsx(Ca,{className:"h-3.5 w-3.5 mr-1.5"})," Preview"]}),e.jsxs($,{size:"sm",onClick:C,disabled:!S||u,children:[u&&e.jsx(kt,{className:"h-3.5 w-3.5 mr-1.5 animate-spin"}),"Save step"]})]})]}),e.jsx(R9n,{open:b,onOpenChange:w,subject:c.subject||"",body:c.body||"",ownerUserId:i,stepLabel:`Step ${t+1}`})]})]})}function K9n({open:s,onOpenChange:t,contactIds:n,onSuccess:r}){const{data:a,isLoading:i}=Fie(),l=Nit(),[o,c]=j.useState(""),[d,u]=j.useState(null),[h,m]=j.useState(!1),f=(a||[]).filter(y=>!y.is_starter),g=f.filter(y=>y.name.toLowerCase().includes(o.toLowerCase())||(y.description||"").toLowerCase().includes(o.toLowerCase())),x=async()=>{if(d)try{const y=await l.mutateAsync({campaignId:d,contactIds:n}),v=[`${y.enrolled} enrolled`];y.skipped>0&&v.push(`${y.skipped} skipped`),y.errors>0&&v.push(`${y.errors} errors`),re.success(v.join(" · ")),t(!1),u(null),r==null||r()}catch(y){re.error(y.message||"Failed to enroll contacts")}};return e.jsxs(zs,{open:s,onOpenChange:t,children:[e.jsxs(Os,{className:"max-w-md",children:[e.jsxs(Us,{children:[e.jsxs(Bs,{className:"flex items-center gap-2",children:[e.jsx(Nn,{className:"h-4 w-4 text-primary"}),"Enroll in Drip Campaign"]}),e.jsxs(Ir,{children:[n.length," contact",n.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(Kr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground"}),e.jsx(pe,{placeholder:"Search campaigns...",value:o,onChange:y=>c(y.target.value),className:"pl-9 h-9"})]}),e.jsx(uo,{className:"h-[320px] -mx-1 px-1",children:i?e.jsx("div",{className:"text-center py-8 text-sm text-muted-foreground",children:"Loading..."}):g.length===0?e.jsx("div",{className:"text-center py-8",children:f.length===0?e.jsxs(e.Fragment,{children:[e.jsx(Nn,{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($,{size:"sm",onClick:()=>m(!0),children:[e.jsx(dn,{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:g.map(y=>e.jsxs("button",{onClick:()=>u(y.id),className:`w-full flex items-start gap-3 p-3 rounded-lg border text-left transition-all ${d===y.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 ${y.cover_color} flex items-center justify-center text-lg`,children:y.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:y.name}),y.is_active&&e.jsx(Be,{variant:"outline",className:"text-[9px] bg-emerald-500/10 text-emerald-600 border-emerald-200 px-1 py-0",children:"Active"})]}),y.description&&e.jsx("p",{className:"text-xs text-muted-foreground line-clamp-2 mt-0.5",children:y.description})]}),d===y.id&&e.jsx(la,{className:"h-4 w-4 text-primary shrink-0 mt-1"})]},y.id))})})]}),e.jsxs(Ar,{className:"gap-2 sm:gap-2",children:[f.length>0&&e.jsxs($,{variant:"ghost",size:"sm",onClick:()=>m(!0),className:"mr-auto text-xs",children:[e.jsx(dn,{className:"h-3.5 w-3.5 mr-1"})," New campaign"]}),e.jsx($,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsxs($,{onClick:x,disabled:!d||l.isPending,children:[l.isPending&&e.jsx(kt,{className:"h-3.5 w-3.5 mr-1.5 animate-spin"}),"Enroll ",n.length," contact",n.length!==1?"s":""]})]})]}),e.jsx(WQt,{open:h,onOpenChange:m})]})}function Y9n({selectedIds:s,contacts:t,onClearSelection:n,onSendToLeadPond:r,showLeadPondAction:a,onTransfer:i,showTransferAction:l}){const o=Qn(),{data:c}=Yw(),d=$Hs(),u=Vt(),{isGmailConnected:h}=yy(),{isReady:m}=u6(),{data:f}=a9(),g=rit(),x=WXt(),[y,v]=j.useState(!1),[b,w]=j.useState(!1),[S,C]=j.useState(!1),[E,I]=j.useState(!1),[P,R]=j.useState(!1),[D,O]=j.useState(""),[U,W]=j.useState(!1),[V,G]=j.useState(null),Y=s.size;if(Y===0)return null;const X=async _e=>{v(!0);try{const ue=Array.from(s).map(Ee=>({contact_id:Ee,relationship_type_id:_e})),{error:ve}=await q.from("innercircle_contact_tags").upsert(ue,{onConflict:"contact_id,relationship_type_id",ignoreDuplicates:!0});if(ve)throw ve;u.invalidateQueries({queryKey:["innercircle-contacts"]}),u.invalidateQueries({queryKey:["innercircle-contact-counts"]}),_a({title:`Assigned type to ${Y} contacts`}),n()}catch(he){_a({title:"Error assigning type",description:he.message,variant:"destructive"})}finally{v(!1)}},ae=async _e=>{v(!0);try{const he=Array.from(s);for(const ue of he)try{await x.mutateAsync({contactId:ue,tagId:_e})}catch{}u.invalidateQueries({queryKey:["all-contact-custom-tags"]}),_a({title:`Tagged ${Y} contacts`}),R(!1),O("")}catch(he){_a({title:"Error adding tags",description:he.message,variant:"destructive"})}finally{v(!1)}},ie=async()=>{if(D.trim()){v(!0);try{const _e=await g.mutateAsync({name:D.trim()});await ae(_e.id)}catch(_e){_a({title:"Error creating tag",description:_e.message,variant:"destructive"}),v(!1)}}},ne=(f==null?void 0:f.filter(_e=>_e.name.toLowerCase().includes(D.toLowerCase())))||[],te=f==null?void 0:f.find(_e=>_e.name.toLowerCase()===D.trim().toLowerCase()),J=()=>{const _e=t.filter(Fe=>s.has(Fe.id)),he=["First Name","Last Name","Email","Phone","Street Address","City","State","ZIP","Full Address","Birthday","Home Anniversary","Notes","Relationship Types"],ue=_e.map(Fe=>{var $e;const ke=Fe,Ve=ke.address||"",je=ke.city||"",Ae=ke.state||"",Ce=ke.zip||ke.zip_code||"",qe=[je,[Ae,Ce].filter(Boolean).join(" ")].filter(Boolean).join(", "),ze=[Ve,qe].filter(Boolean).join(", ");return[Fe.first_name,Fe.last_name||"",Fe.email||"",Fe.phone||"",Ve,je,Ae,Ce,ze,Fe.birthday||"",Fe.home_anniversary||"",Fe.notes||"",(($e=Fe.tags)==null?void 0:$e.map(ct=>{var Xe;return(Xe=ct.relationship_type)==null?void 0:Xe.name}).join("; "))||""]}),ve=[he.join(","),...ue.map(Fe=>Fe.map(ke=>`"${(ke||"").replace(/"/g,'""')}"`).join(","))].join(` `),Ee=new Blob([ve],{type:"text/csv"}),Se=URL.createObjectURL(Ee),Le=document.createElement("a");Le.href=Se,Le.download=`contacts-export-${new Date().toISOString().slice(0,10)}.csv`,Le.click(),URL.revokeObjectURL(Se),_a({title:`Exported ${Y} contacts`})},ce=async()=>{if(!await fo(`Are you sure you want to delete ${Y} contacts? This cannot be undone.`))return;const _e=Array.from(s);v(!0),G({done:0,total:_e.length});try{const he=await d.mutateAsync({ids:_e,onProgress:(ue,ve)=>G({done:ue,total:ve})});n(),_a({title:`Deleted ${he.toLocaleString()} contacts`})}catch(he){const ue=typeof(he==null?void 0:he.deleted)=="number"?he.deleted:0;_a({title:"Error deleting contacts",description:ue>0?`${ue.toLocaleString()} of ${_e.length.toLocaleString()} were deleted before this failed: ${he.message}`:he.message,variant:"destructive"})}finally{G(null),v(!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(Be,{variant:"secondary",className:"font-semibold",children:[Y," selected"]}),V&&e.jsxs("span",{className:"text-sm text-muted-foreground",children:["Deleting ",V.done.toLocaleString()," of ",V.total.toLocaleString(),"…"]}),e.jsxs(ms,{onValueChange:X,disabled:y,children:[e.jsx(us,{className:"w-[180px] h-8",children:e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(Ap,{className:"h-3.5 w-3.5"}),e.jsx("span",{className:"text-sm",children:"Assign Type"})]})}),e.jsx(hs,{children:c==null?void 0:c.filter(_e=>_e.active).map(_e=>e.jsx(Ge,{value:_e.id,children:_e.name},_e.id))})]}),e.jsxs(Yd,{open:P,onOpenChange:R,children:[e.jsx(Zd,{asChild:!0,children:e.jsxs($,{variant:"outline",size:"sm",disabled:y,children:[e.jsx(dn,{className:"h-3.5 w-3.5 mr-1"}),"Add Tag"]})}),e.jsxs(Bd,{className:"w-56 p-2",align:"start",children:[e.jsx(pe,{placeholder:"Search or create tag...",value:D,onChange:_e=>O(_e.target.value),onKeyDown:_e=>{_e.key==="Enter"&&D.trim()&&!te?(_e.preventDefault(),ie()):_e.key==="Enter"&&te&&(_e.preventDefault(),ae(te.id))},className:"h-8 text-sm mb-2"}),e.jsxs("div",{className:"max-h-[200px] overflow-y-auto space-y-0.5",children:[ne.map(_e=>e.jsxs("button",{onClick:()=>ae(_e.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:_e.color}}),e.jsx("span",{className:"flex-1 text-left truncate",children:_e.name})]},_e.id)),D.trim()&&!te&&e.jsxs("button",{onClick:ie,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(dn,{className:"h-3.5 w-3.5"}),'Create "',D.trim(),'"']}),ne.length===0&&!D.trim()&&e.jsx("p",{className:"text-xs text-muted-foreground text-center py-2",children:"Type to create a tag"})]})]})]}),h&&e.jsxs($,{variant:"outline",size:"sm",onClick:()=>w(!0),disabled:y,children:[e.jsx(mn,{className:"h-3.5 w-3.5 mr-1"}),"Email"]}),m&&e.jsxs($,{variant:"outline",size:"sm",onClick:()=>{const _e=Array.from(s).join(",");o(`/admin/email-campaigns/new?contactIds=${_e}`)},disabled:y,children:[e.jsx(xm,{className:"h-3.5 w-3.5 mr-1"}),"Mass Email"]}),e.jsxs($,{variant:"outline",size:"sm",onClick:()=>C(!0),disabled:y,children:[e.jsx(ua,{className:"h-3.5 w-3.5 mr-1"}),"Send Video"]}),e.jsxs($,{variant:"outline",size:"sm",onClick:()=>I(!0),disabled:y,children:[e.jsx(Nn,{className:"h-3.5 w-3.5 mr-1"}),"Enroll in Campaign"]}),a&&r&&e.jsxs($,{variant:"outline",size:"sm",onClick:()=>r(Array.from(s)),disabled:y,children:[e.jsx(b1,{className:"h-3.5 w-3.5 mr-1"}),"Send to Lead Pond"]}),l&&i&&e.jsxs($,{variant:"outline",size:"sm",onClick:()=>i(Array.from(s)),disabled:y,children:[e.jsx(E4,{className:"h-3.5 w-3.5 mr-1"}),"Transfer"]}),Y>=2&&Y<=10&&e.jsxs($,{variant:"outline",size:"sm",onClick:()=>W(!0),disabled:y,children:[e.jsx(Xz,{className:"h-3.5 w-3.5 mr-1"}),"Merge"]}),e.jsx(dDe,{disabled:y,label:"Mail",build:()=>({source:"contacts",contactIds:Array.from(s).slice(0,500)})}),e.jsxs($,{variant:"outline",size:"sm",onClick:J,disabled:y,children:[e.jsx(di,{className:"h-3.5 w-3.5 mr-1"}),"Export"]}),e.jsxs($,{variant:"outline",size:"sm",onClick:ce,disabled:y,className:"text-destructive hover:text-destructive",children:[e.jsx(Wn,{className:"h-3.5 w-3.5 mr-1"}),"Delete"]}),e.jsxs($,{variant:"ghost",size:"sm",onClick:n,className:"ml-auto",children:[e.jsx(gr,{className:"h-3.5 w-3.5 mr-1"}),"Clear"]})]}),e.jsx(DQt,{open:U,onOpenChange:W,contactIds:Array.from(s),onMerged:n}),e.jsx(K9n,{open:E,onOpenChange:I,contactIds:Array.from(s),onSuccess:n}),e.jsx(Ak,{open:b,onOpenChange:w,bulkContacts:Array.from(s).map(_e=>{const he=t.find(ue=>ue.id===_e);return he?{id:he.id,first_name:he.first_name,last_name:he.last_name,email:he.email||""}:null}).filter(_e=>_e!==null&&_e.email!==""),onSendComplete:()=>{w(!1),n()}}),e.jsx(j9n,{open:S,onOpenChange:C,contacts:Array.from(s).map(_e=>t.find(he=>he.id===_e)).filter(_e=>!!_e).map(_e=>({id:_e.id,first_name:_e.first_name,last_name:_e.last_name,email:_e.email})),isGmailConnected:!!h,isMassEmailReady:!!m,onSendComplete:()=>{C(!1),n()}})]})}function hCt({contact:s,onEdit:t,onDelete:n,onSnooze:r,onSendToLeadPond:a,showLeadPondAction:i,onTransfer:l,showTransferAction:o}){const c=Qn(),{isReady:d}=u6(),u=`${s.first_name} ${s.last_name||""}`.trim();return e.jsxs(Uu,{children:[e.jsx(qu,{asChild:!0,children:e.jsx($,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:h=>h.stopPropagation(),children:e.jsx(h_,{className:"h-4 w-4"})})}),e.jsxs(Eu,{align:"end",onClick:h=>h.stopPropagation(),children:[e.jsxs(ja,{onClick:()=>c(`/mission-control/contacts/${s.id}?tab=activity&action=log`),children:[e.jsx(Da,{className:"h-4 w-4 mr-2"}),"Log Touch"]}),e.jsxs(ja,{onClick:()=>c(`/mission-control/video?contactId=${s.id}`),children:[e.jsx(ua,{className:"h-4 w-4 mr-2"}),"Send Video"]}),e.jsxs(ja,{onClick:()=>c(`/mission-control/popbys?contactId=${s.id}`),children:[e.jsx(ci,{className:"h-4 w-4 mr-2"}),"Schedule Pop-by"]}),d&&s.email&&e.jsxs(ja,{onClick:()=>c(`/admin/email-campaigns/new?contactIds=${s.id}`),children:[e.jsx(mn,{className:"h-4 w-4 mr-2"}),"Mass Email"]}),e.jsxs(ja,{onClick:()=>r(s.id,u),children:[e.jsx(Tv,{className:"h-4 w-4 mr-2"}),"Snooze"]}),i&&a&&e.jsxs(ja,{onClick:()=>a(s.id),children:[e.jsx(b1,{className:"h-4 w-4 mr-2"}),"Send to Lead Pond"]}),o&&l&&e.jsxs(ja,{onClick:()=>l(s.id),children:[e.jsx(E4,{className:"h-4 w-4 mr-2"}),"Transfer to Team Member"]}),e.jsxs(ja,{onClick:()=>t(s),children:[e.jsx(gi,{className:"h-4 w-4 mr-2"}),"Edit"]}),e.jsxs(ja,{onClick:()=>n(s.id),className:"text-destructive focus:text-destructive",children:[e.jsx(Wn,{className:"h-4 w-4 mr-2"}),"Delete"]})]})]})}function mCt({currentFilters:s,currentSortBy:t,onApplySmartList:n}){const{data:r}=ait(),a=KXt(),i=YXt(),[l,o]=j.useState(!1),[c,d]=j.useState(""),u=s.search||s.type&&s.type!=="all"||s.status&&s.status!=="all"||s.behavior&&Object.values(s.behavior).some(m=>m!==void 0&&m!==!1),h=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(Uu,{children:[e.jsx(qu,{asChild:!0,children:e.jsxs($,{variant:"outline",size:"sm",className:"gap-1.5",children:[e.jsx(Iw,{className:"h-3.5 w-3.5"}),"Smart Filters",r&&r.length>0&&e.jsx(Be,{variant:"secondary",className:"h-5 px-1.5 text-[10px]",children:r.length}),e.jsx(Tl,{className:"h-3.5 w-3.5"})]})}),e.jsxs(Eu,{align:"start",className:"w-56",children:[r&&r.length>0?e.jsxs(e.Fragment,{children:[r.map(m=>e.jsxs(ja,{className:"flex items-center justify-between group",children:[e.jsx("span",{className:"flex-1 cursor-pointer",onClick:()=>n(m.filters,m.sort_by),children:m.name}),e.jsx($,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 opacity-0 group-hover:opacity-100",onClick:f=>{f.stopPropagation(),i.mutate(m.id)},children:e.jsx(Wn,{className:"h-3 w-3 text-destructive"})})]},m.id)),e.jsx(R0,{})]}):e.jsx(ja,{disabled:!0,className:"text-muted-foreground text-xs",children:"No saved filters yet"}),u&&e.jsxs(ja,{onClick:()=>o(!0),children:[e.jsx(qI,{className:"h-4 w-4 mr-2"}),"Save Current Filter"]})]})]}),e.jsx(zs,{open:l,onOpenChange:o,children:e.jsxs(Os,{className:"max-w-sm",children:[e.jsx(Us,{children:e.jsx(Bs,{children:"Save Smart Filter"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsx(pe,{placeholder:"e.g. Buyers in 40205",value:c,onChange:m=>d(m.target.value),onKeyDown:m=>m.key==="Enter"&&h(),autoFocus:!0}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx($,{variant:"outline",onClick:()=>o(!1),children:"Cancel"}),e.jsx($,{onClick:h,disabled:!c.trim()||a.isPending,children:"Save"})]})]})]})})]})}const sPe=[{value:1,label:"January"},{value:2,label:"February"},{value:3,label:"March"},{value:4,label:"April"},{value:5,label:"May"},{value:6,label:"June"},{value:7,label:"July"},{value:8,label:"August"},{value:9,label:"September"},{value:10,label:"October"},{value:11,label:"November"},{value:12,label:"December"}],KQt=[{value:"home_anniversary",label:"Home anniversary"},{value:"wedding_anniversary",label:"Wedding anniversary"}],Z9n=[{value:"today",label:"Today"},{value:"7d",label:"Last 7 days"},{value:"30d",label:"Last 30 days"},{value:"90d",label:"Last 90 days"},{value:"never",label:"Never active"}];function X9n({open:s,onOpenChange:t,hasLeadSite:n,behavior:r,onApply:a,selectedType:i,onSelectedTypeChange:l,relationshipTypes:o,contactLeadSources:c}){const[d,u]=j.useState(r),[h,m]=j.useState(n?"behavior":"contact"),{data:f}=HB(),g=j.useMemo(()=>{const v=new Map;return(f||[]).forEach(b=>{v.set(b.name.trim().toLowerCase(),{value:`name:${b.name}`,label:b.name})}),(c||[]).forEach(b=>{const w=b.trim().toLowerCase();!w||v.has(w)||v.set(w,{value:`name:${b}`,label:b})}),Array.from(v.values()).sort((b,w)=>b.label.localeCompare(w.label))},[f,c]);j.useEffect(()=>{s&&u(r)},[s,r]);const x=v=>u(b=>({...b,...v})),y=Object.entries(d).filter(([,v])=>v!==void 0&&v!==!1&&v!=="").length;return e.jsx(Wy,{open:s,onOpenChange:t,children:e.jsxs(py,{side:"right",className:"w-full sm:max-w-lg overflow-y-auto",children:[e.jsxs(D0,{children:[e.jsxs(F0,{className:"flex items-center gap-2",children:[e.jsx(Nn,{className:"h-4 w-4 text-primary"}),"Advanced Filters"]}),e.jsx($B,{children:"Slice your database by website activity, contact details, and engagement."})]}),e.jsxs(ha,{value:h,onValueChange:v=>m(v),className:"mt-4",children:[e.jsxs(ma,{className:"grid w-full grid-cols-3",children:[e.jsxs(Zt,{value:"contact",className:"gap-1.5",children:[e.jsx(Zn,{className:"h-3.5 w-3.5"})," Contact"]}),e.jsxs(Zt,{value:"behavior",disabled:!n,className:"gap-1.5",children:[e.jsx(af,{className:"h-3.5 w-3.5"})," Behavior"]}),e.jsx(Zt,{value:"engagement",children:"Engagement"})]}),e.jsxs(Xt,{value:"contact",className:"space-y-6 mt-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Contact Type"}),e.jsxs(ms,{value:i,onValueChange:l,children:[e.jsx(us,{children:e.jsx(fs,{placeholder:"All types"})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"all",children:"All Types"}),o==null?void 0:o.map(v=>e.jsx(Ge,{value:v.id,children:v.name},v.id))]})]})]}),e.jsxs(aA,{title:"Contact Info Present",children:[e.jsx(Xb,{label:"Has email",checked:d.hasEmail===!0,onChange:v=>x({hasEmail:v||void 0})}),e.jsx(Xb,{label:"Has phone",checked:d.hasPhone===!0,onChange:v=>x({hasPhone:v||void 0})}),e.jsx(Xb,{label:"Has address",checked:d.hasAddress===!0,onChange:v=>x({hasAddress:v||void 0})}),e.jsx(Xb,{label:"Has birthday",checked:d.hasBirthday===!0,onChange:v=>x({hasBirthday:v||void 0})}),e.jsx(Xb,{label:"Has spouse",checked:d.hasSpouse===!0,onChange:v=>x({hasSpouse:v||void 0})}),e.jsx(Xb,{label:"Has company / job",checked:d.hasCompany===!0,onChange:v=>x({hasCompany:v||void 0})}),e.jsx(Xb,{label:"Has notes",checked:d.hasNotes===!0,onChange:v=>x({hasNotes:v||void 0})})]}),e.jsxs(aA,{title:"Location",children:[e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-2",children:[e.jsx(Q9e,{label:"City",value:d.city||"",onChange:v=>x({city:v||void 0}),placeholder:"Any city"}),e.jsx(Q9e,{label:"State",value:d.state||"",onChange:v=>x({state:v||void 0}),placeholder:"Any state"})]}),e.jsx(Q9e,{label:"ZIP / Postal",value:d.zip||"",onChange:v=>x({zip:v||void 0}),placeholder:"Any ZIP"})]}),e.jsxs(aA,{title:"Important Dates",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:"Birthday month"}),e.jsxs(ms,{value:d.birthdayMonth?String(d.birthdayMonth):"all",onValueChange:v=>x({birthdayMonth:v==="all"?void 0:Number(v)}),children:[e.jsx(us,{children:e.jsx(fs,{placeholder:"Any month"})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"all",children:"Any month"}),sPe.map(v=>e.jsx(Ge,{value:String(v.value),children:v.label},v.value))]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:"Anniversary month"}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-2",children:[e.jsxs(ms,{value:d.anniversaryField||"home_anniversary",onValueChange:v=>x({anniversaryField:v}),children:[e.jsx(us,{children:e.jsx(fs,{placeholder:"Field"})}),e.jsx(hs,{children:KQt.map(v=>e.jsx(Ge,{value:v.value,children:v.label},v.value))})]}),e.jsxs(ms,{value:d.anniversaryMonth?String(d.anniversaryMonth):"all",onValueChange:v=>x({anniversaryMonth:v==="all"?void 0:Number(v)}),children:[e.jsx(us,{children:e.jsx(fs,{placeholder:"Any month"})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"all",children:"Any month"}),sPe.map(v=>e.jsx(Ge,{value:String(v.value),children:v.label},v.value))]})]})]})]})]}),e.jsx(aA,{title:"Date Added",children:e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-2",children:[e.jsx(fCt,{label:"From",value:d.dateAddedFrom,onChange:v=>x({dateAddedFrom:v||void 0})}),e.jsx(fCt,{label:"To",value:d.dateAddedTo,onChange:v=>x({dateAddedTo:v||void 0})})]})}),e.jsx(aA,{title:"Lead Source",children:e.jsxs(ms,{value:d.leadSourceId||"all",onValueChange:v=>x({leadSourceId:v==="all"?void 0:v}),children:[e.jsx(us,{children:e.jsx(fs,{placeholder:"All sources"})}),e.jsxs(hs,{className:"max-h-72",children:[e.jsx(Ge,{value:"all",children:"All sources"}),e.jsx(Ge,{value:"none",children:"No source"}),g.map(v=>e.jsx(Ge,{value:v.value,children:v.label},v.value))]})]})})]}),e.jsx(Xt,{value:"behavior",className:"space-y-6 mt-4",children:n?e.jsxs(e.Fragment,{children:[e.jsxs(aA,{title:"Last Active On Site",children:[e.jsx(kw,{value:d.lastActive||"",onValueChange:v=>x({lastActive:v||void 0}),className:"grid grid-cols-2 gap-2",children:Z9n.map(v=>e.jsxs("label",{className:"flex items-center gap-2 rounded-md border px-3 py-2 cursor-pointer hover:bg-accent",children:[e.jsx(Ym,{value:v.value}),e.jsx("span",{className:"text-sm",children:v.label})]},v.value))}),d.lastActive&&e.jsx($,{variant:"ghost",size:"sm",className:"mt-1 h-7 px-2 text-xs",onClick:()=>x({lastActive:void 0}),children:"Clear"})]}),e.jsxs(aA,{title:"Registration",children:[e.jsx(Xb,{label:"Registered on lead site",checked:d.registered==="yes",onChange:v=>x({registered:v?"yes":void 0})}),e.jsx(Xb,{label:"Anonymous visitors only",checked:d.registered==="no",onChange:v=>x({registered:v?"no":void 0})})]}),e.jsxs(aA,{title:"Property Activity",children:[e.jsx(Xb,{label:"Viewed any listing",checked:d.viewedListing==="any",onChange:v=>x({viewedListing:v?"any":void 0})}),e.jsx(Xb,{label:"Hot buyer — 3+ views in last 7 days",checked:d.viewedListing==="multiple7d",onChange:v=>x({viewedListing:v?"multiple7d":void 0})}),e.jsx(Xb,{label:"Saved a property",checked:!!d.savedProperty,onChange:v=>x({savedProperty:v||void 0})}),e.jsx(Xb,{label:"Has an active saved search / alert",checked:!!d.hasSavedSearch,onChange:v=>x({hasSavedSearch:v||void 0})})]}),e.jsxs(aA,{title:"Requests",children:[e.jsx(Xb,{label:"Requested a showing / asked a question",checked:!!d.requestedShowing,onChange:v=>x({requestedShowing:v||void 0})}),e.jsx(Xb,{label:"Requested a home valuation",checked:!!d.requestedValuation,onChange:v=>x({requestedValuation:v||void 0})})]})]}):e.jsx("div",{className:"rounded-md border border-dashed p-4 text-sm text-muted-foreground",children:"Connect a Lead Site with MLS to unlock website behavior filters."})}),e.jsxs(Xt,{value:"engagement",className:"space-y-4 mt-4",children:[e.jsx(Xb,{label:"Any website activity",checked:!!d.websiteActiveOnly,onChange:v=>x({websiteActiveOnly:v||void 0})}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"More engagement filters (last emailed, awaiting response, past-due tasks) are in the pipeline."})]})]}),e.jsxs(VOt,{className:"mt-6 flex-row gap-2 sm:justify-between",children:[e.jsx($,{variant:"ghost",onClick:()=>u({}),disabled:y===0,children:"Clear behavior filters"}),e.jsx($,{onClick:()=>{a(d),t(!1)},children:"Apply"})]})]})})}function aA({title:s,children:t}){return e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:s}),e.jsx("div",{className:"space-y-2",children:t})]})}function Xb({label:s,checked:t,onChange:n}){return e.jsxs("div",{className:"flex items-center justify-between rounded-md border px-3 py-2",children:[e.jsx("span",{className:"text-sm",children:s}),e.jsx(Sn,{checked:t,onCheckedChange:n})]})}function Q9e({label:s,value:t,onChange:n,placeholder:r}){return e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:s}),e.jsxs("div",{className:"relative",children:[e.jsx(pe,{value:t,onChange:a=>n(a.target.value),placeholder:r,className:"h-8"}),t&&e.jsx("button",{onClick:()=>n(""),className:"absolute right-2 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground",children:e.jsx(gr,{className:"h-3 w-3"})})]})]})}function fCt({label:s,value:t,onChange:n}){const[r,a]=j.useState(!1),i=t?vv(t):void 0;return e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:s}),e.jsxs(Yd,{open:r,onOpenChange:a,children:[e.jsx(Zd,{asChild:!0,children:e.jsxs($,{variant:"outline",className:Pt("w-full justify-start text-left font-normal h-8",!i&&"text-muted-foreground"),children:[e.jsx(Ta,{className:"mr-2 h-3.5 w-3.5"}),i?en(i,"MMM d, yyyy"):e.jsx("span",{children:"Pick a date"})]})}),e.jsx(Bd,{className:"w-auto p-0",align:"start",children:e.jsx(D2,{mode:"single",selected:i,onSelect:l=>{n(l?en(l,"yyyy-MM-dd"):void 0),a(!1)},initialFocus:!0})})]})]})}function Q9n({behavior:s,onRemove:t,onClearAll:n}){const r=J9n(s);return r.length===0?null:e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[r.map(({key:a,label:i})=>e.jsxs("span",{className:"inline-flex items-center gap-1 rounded-full bg-primary/10 text-primary text-xs px-2.5 py-1",children:[i,e.jsx("button",{onClick:()=>t(a),className:"hover:bg-primary/20 rounded-full h-4 w-4 inline-flex items-center justify-center","aria-label":`Remove ${i}`,children:"×"})]},a)),e.jsx("button",{onClick:n,className:"text-xs text-primary underline underline-offset-2 hover:no-underline",children:"Clear"})]})}function J9n(s){var n;const t=[];if(s.lastActive){const r={today:"Active today","7d":"Active last 7 days","30d":"Active last 30 days","90d":"Active last 90 days",never:"Never active"};t.push({key:"lastActive",label:r[s.lastActive]})}if(s.registered==="yes"&&t.push({key:"registered",label:"Registered"}),s.registered==="no"&&t.push({key:"registered",label:"Anonymous visitor"}),s.viewedListing==="any"&&t.push({key:"viewedListing",label:"Viewed a listing"}),s.viewedListing==="multiple7d"&&t.push({key:"viewedListing",label:"Hot buyer (3+ views/7d)"}),s.savedProperty&&t.push({key:"savedProperty",label:"Saved a property"}),s.hasSavedSearch&&t.push({key:"hasSavedSearch",label:"Active saved search"}),s.requestedShowing&&t.push({key:"requestedShowing",label:"Requested showing/question"}),s.requestedValuation&&t.push({key:"requestedValuation",label:"Requested valuation"}),s.websiteActiveOnly&&t.push({key:"websiteActiveOnly",label:"Any website activity"}),s.hasEmail&&t.push({key:"hasEmail",label:"Has email"}),s.hasPhone&&t.push({key:"hasPhone",label:"Has phone"}),s.hasAddress&&t.push({key:"hasAddress",label:"Has address"}),s.hasBirthday&&t.push({key:"hasBirthday",label:"Has birthday"}),s.hasSpouse&&t.push({key:"hasSpouse",label:"Has spouse"}),s.hasCompany&&t.push({key:"hasCompany",label:"Has company / job"}),s.hasNotes&&t.push({key:"hasNotes",label:"Has notes"}),s.city&&t.push({key:"city",label:`City: ${s.city}`}),s.state&&t.push({key:"state",label:`State: ${s.state}`}),s.zip&&t.push({key:"zip",label:`ZIP: ${s.zip}`}),s.birthdayMonth){const r=sPe.find(a=>a.value===s.birthdayMonth);t.push({key:"birthdayMonth",label:`Birthday in ${(r==null?void 0:r.label)||s.birthdayMonth}`})}if(s.anniversaryMonth){const r=sPe.find(i=>i.value===s.anniversaryMonth),a=((n=KQt.find(i=>i.value===(s.anniversaryField||"home_anniversary")))==null?void 0:n.label)||"Anniversary";t.push({key:"anniversaryMonth",label:`${a} in ${(r==null?void 0:r.label)||s.anniversaryMonth}`})}return s.dateAddedFrom&&t.push({key:"dateAddedFrom",label:`Added on/after ${en(vv(s.dateAddedFrom),"MMM d, yyyy")}`}),s.dateAddedTo&&t.push({key:"dateAddedTo",label:`Added on/before ${en(vv(s.dateAddedTo),"MMM d, yyyy")}`}),s.leadSourceId&&t.push({key:"leadSourceId",label:s.leadSourceId==="none"?"No lead source":"Lead source"}),t}function e$n(){const[s,t]=j.useState(""),[n,r]=j.useState(!0);return j.useEffect(()=>{let a=!1;return(async()=>{const{data:i}=await q.from("settings").select("value").eq("key","mapbox_public_token").maybeSingle();a||(t((i==null?void 0:i.value)??""),r(!1))})(),()=>{a=!0}},[]),{token:s,loading:n}}function t$n(){const s=Sa();return tt({queryKey:["sphere-map-contacts",s],queryFn:async()=>{if(!s)return[];const t=1e3,n=[];for(let r=0;;r+=t){const{data:a,error:i}=await q.rpc("get_sphere_map_contacts",{_owner:s}).order("id",{ascending:!0}).range(r,r+t-1);if(i)throw i;const l=a??[];if(n.push(...l),l.length{let n=0,r=0,a=0;for(let i=0;i<20;i++){const{data:l,error:o}=await q.functions.invoke("geocode-contacts",{body:{owner_user_id:s,limit:200}});if(o)throw o;if(n+=(l==null?void 0:l.processed)??0,r+=(l==null?void 0:l.matched)??0,a=(l==null?void 0:l.remaining)??0,!(l!=null&&l.processed))break}return{processed:n,matched:r,remaining:a}},onSuccess:n=>{t.invalidateQueries({queryKey:["sphere-map-contacts"]}),_a({title:n.processed?`Mapped ${n.matched} of ${n.processed} addresses`:"Everything is already mapped",description:n.remaining?`${n.remaining} still to look up`:void 0})},onError:n=>_a({title:"Could not map addresses",description:n.message,variant:"destructive"})})}function XSr(){const s=Sa();return tt({queryKey:["contact-map-views",s],queryFn:async()=>{const{data:t,error:n}=await q.from("contact_map_views").select("*").eq("owner_user_id",s).order("created_at");if(n)throw n;return t},enabled:!!s})}function QSr(){const s=Sa(),t=Vt();return ft({mutationFn:async n=>{const{error:r}=await q.from("contact_map_views").insert({...n,owner_user_id:s});if(r)throw r},onSuccess:()=>{t.invalidateQueries({queryKey:["contact-map-views"]}),_a({title:"View saved"})},onError:n=>_a({title:"Could not save view",description:n.message,variant:"destructive"})})}function JSr(){const s=Vt();return ft({mutationFn:async t=>{const{error:n}=await q.from("contact_map_views").delete().eq("id",t);if(n)throw n},onSuccess:()=>s.invalidateQueries({queryKey:["contact-map-views"]})})}function s$n(){const s=Sa();return tt({queryKey:["contact-farms",s],queryFn:async()=>{const{data:t,error:n}=await q.from("contact_farms").select("*").eq("owner_user_id",s).order("created_at");if(n)throw n;return t},enabled:!!s})}function eCr(){const s=Sa(),t=Vt();return ft({mutationFn:async n=>{const{error:r}=await q.from("contact_farms").insert({...n,boundary:n.boundary,owner_user_id:s});if(r)throw r},onSuccess:()=>{t.invalidateQueries({queryKey:["contact-farms"]}),_a({title:"Farm saved"})},onError:n=>_a({title:"Could not save farm",description:n.message,variant:"destructive"})})}function tCr(){const s=Vt();return ft({mutationFn:async t=>{const{error:n}=await q.from("contact_farms").delete().eq("id",t);if(n)throw n},onSuccess:()=>s.invalidateQueries({queryKey:["contact-farms"]})})}function sCr(){const s=Sa();return tt({queryKey:["popby-routes",s],queryFn:async()=>{const{data:t,error:n}=await q.from("popby_routes").select("*, stops:popby_route_stops(*)").eq("owner_user_id",s).order("created_at",{ascending:!1});if(n)throw n;return t??[]},enabled:!!s})}function nCr(){const s=Sa(),t=Vt();return ft({mutationFn:async({name:n,plannedDate:r,contactIds:a})=>{const{data:i,error:l}=await q.from("popby_routes").insert({owner_user_id:s,name:n,planned_date:r??null}).select().single();if(l)throw l;if(a.length){const{error:o}=await q.from("popby_route_stops").insert(a.map((c,d)=>({route_id:i.id,contact_id:c,sort_order:d})));if(o)throw o}return i},onSuccess:()=>{t.invalidateQueries({queryKey:["popby-routes"]}),_a({title:"Route created"})},onError:n=>_a({title:"Could not create route",description:n.message,variant:"destructive"})})}function rCr(){const s=Vt();return ft({mutationFn:async({id:t,...n})=>{const{error:r}=await q.from("popby_route_stops").update(n).eq("id",t);if(r)throw r},onSuccess:()=>s.invalidateQueries({queryKey:["popby-routes"]})})}function aCr(){const s=Vt();return ft({mutationFn:async t=>{for(const n of t){const{error:r}=await q.from("popby_route_stops").update({sort_order:n.sort_order}).eq("id",n.id);if(r)throw r}},onSuccess:()=>s.invalidateQueries({queryKey:["popby-routes"]})})}function iCr(){const s=Vt();return ft({mutationFn:async t=>{const{error:n}=await q.from("popby_routes").delete().eq("id",t);if(n)throw n},onSuccess:()=>s.invalidateQueries({queryKey:["popby-routes"]})})}function oCr(){const s=Sa();return tt({queryKey:["sphere-map-anchors",s],queryFn:async()=>{const[t,n]=await Promise.all([q.from("listings").select("id, property_address, city, state, latitude, longitude, status, slug").eq("agent_id",s).not("latitude","is",null),q.from("open_houses").select("id, property_address, city, state, event_date, slug, is_active").eq("agent_id",s).eq("is_active",!0)]);return{listings:t.data??[],openHouses:n.data??[]}},enabled:!!s})}function lCr(){const s=Sa();return tt({queryKey:["sphere-map-listings",s],queryFn:async()=>{const t=[];for(let r=0;r<20;r++){const{data:a,error:i}=await q.from("listings").select("id, property_address, city, state, price, status, bedrooms, bathrooms, square_footage, slug, latitude, longitude, listing_class, photos:listing_photos(photo_url, is_primary, sort_order)").eq("agent_id",s).order("created_at",{ascending:!1}).range(r*1e3,r*1e3+1e3-1);if(i)throw i;const l=a??[];if(l.forEach(o=>{var h;const c=(o.photos??[]).slice().sort((m,f)=>(f.is_primary?1:0)-(m.is_primary?1:0)||(m.sort_order??0)-(f.sort_order??0)),{photos:d,...u}=o;t.push({...u,photo_url:((h=c[0])==null?void 0:h.photo_url)??null})}),l.length<1e3)break}return t},enabled:!!s,staleTime:6e4})}function cCr(){const s=Sa();return tt({queryKey:["sphere-map-open-houses",s],queryFn:async()=>{const t=[];for(let r=0;r<10;r++){const{data:a,error:i}=await q.from("open_houses").select("id, slug, property_address, city, state, zip, event_date, start_time, end_time, price, beds, baths, sqft, photo_url, is_active, latitude, longitude").eq("agent_id",s).order("event_date",{ascending:!1}).range(r*1e3,r*1e3+1e3-1);if(i)throw i;const l=a??[];if(l.forEach(o=>t.push(o)),l.length<1e3)break}return t},enabled:!!s,staleTime:6e4})}function dCr(s){const{leadSiteId:t,filters:n,enabled:r}=s,a=JSON.stringify(n);return tt({queryKey:["sphere-map-idx",t,a],queryFn:async()=>{if(!t||!n.cities.length||!n.statuses.length)return[];const{data:i,error:l}=await q.functions.invoke("lead-site-search",{body:{leadSiteId:t,filterCities:n.cities,statuses:n.statuses,minPrice:n.minPrice??void 0,maxPrice:n.maxPrice??void 0,minBeds:n.minBeds??void 0,minBaths:n.minBaths??void 0,propertyType:n.propertyType??void 0,limit:250,pageSize:250}});if(l)throw l;return((i==null?void 0:i.listings)??[]).filter(c=>Number.isFinite(c.latitude)&&Number.isFinite(c.longitude))},enabled:r&&!!t,staleTime:5*60*1e3})}function YQt(s,t,n){const r=Vt(),{token:a}=e$n();return ft({mutationFn:async i=>{var o,c;if(!a)throw new Error("Map is still loading. Try again in a moment.");let l=0;for(const d of i){const u=[d.property_address,d.city,d.state].filter(Boolean).join(", ");if(u)try{const m=await(await fetch(`https://api.mapbox.com/geocoding/v5/mapbox.places/${encodeURIComponent(u)}.json?access_token=${a}&limit=1&country=us`)).json(),f=(c=(o=m==null?void 0:m.features)==null?void 0:o[0])==null?void 0:c.center;if(!f)continue;const[g,x]=f,{error:y}=await q.from(s).update({latitude:x,longitude:g}).eq("id",d.id);y||l++}catch(h){console.error("Geocode error:",h)}}return l},onSuccess:i=>{r.invalidateQueries({queryKey:[t]}),_a({title:i?`${i} ${i===1?n.one:n.many} placed on the map`:"No locations found",description:i?void 0:"Check the street address, city and state."})},onError:i=>_a({title:"Could not look up addresses",description:i.message,variant:"destructive"})})}function uCr(){return YQt("listings","sphere-map-listings",{one:"listing",many:"listings"})}function hCr(){return YQt("open_houses","sphere-map-open-houses",{one:"open house",many:"open houses"})}const mCr={never:{label:"Never contacted",color:"#8b5cf6"},red:{label:"12+ months",color:"#ef4444"},orange:{label:"6–12 months",color:"#f97316"},yellow:{label:"3–6 months",color:"#eab308"},green:{label:"Recent",color:"#22c55e"}};function n$n(s){if(!s)return null;const t=new Date(s).getTime();return Number.isNaN(t)?null:Math.max(0,Math.floor((Date.now()-t)/864e5))}function fCr(s){return s===null?"never":s>=365?"red":s>=180?"orange":s>=90?"yellow":"green"}function r$n(s){return`${s.first_name??""} ${s.last_name??""}`.trim()||"Unnamed contact"}function a$n(s){return[s.address,[s.city,s.state].filter(Boolean).join(", "),s.zip].filter(Boolean).join(" · ")}function pCr(s){const t=new Map;return s.forEach(n=>{if(typeof n.latitude!="number"||typeof n.longitude!="number")return;const r=n.household_key||`${n.latitude.toFixed(5)},${n.longitude.toFixed(5)}`,a=t.get(r);a?a.push(n):t.set(r,[n])}),Array.from(t.entries()).map(([n,r])=>{const a=r.map(c=>n$n(c.last_touch_at)),i=a.some(c=>c===null)?null:Math.max(...a),l=Array.from(new Set(r.map(c=>c.last_name).filter(Boolean))),o=r.length===1?r$n(r[0]):l.length===1?`${r.map(c=>c.first_name).filter(Boolean).join(" & ")} ${l[0]}`:`${r.length} contacts`;return{key:n,lat:r[0].latitude,lng:r[0].longitude,contacts:r,label:o,addressLine:a$n(r[0]),gapDays:i}})}const i$n=3958.8;function ZQt(s,t,n,r){const a=c=>c*Math.PI/180,i=a(n-s),l=a(r-t),o=Math.sin(i/2)**2+Math.cos(a(s))*Math.cos(a(n))*Math.sin(l/2)**2;return 2*i$n*Math.asin(Math.sqrt(o))}function o$n(s,t,n){let r=!1;for(let a=0,i=n.length-1;at!=d>t&&s<(c-l)*(t-o)/(d-o)+l&&(r=!r)}return r}function gCr(s,t,n,r=64){const a=[],i=t*Math.PI/180,l=n/69,o=n/(69*Math.max(.15,Math.cos(i)));for(let c=0;c<=r;c++){const d=c/r*Math.PI*2;a.push([s+o*Math.cos(d),t+l*Math.sin(d)])}return a}function xCr(s){const t=s.reduce((n,[r,a])=>({lng:n.lng+r,lat:n.lat+a}),{lng:0,lat:0});return{lng:t.lng/s.length,lat:t.lat/s.length}}function yCr(s,t){if(s.length<=2)return[...s];const n=[...s],r=[];let a={lat:s[0].lat,lng:s[0].lng};for(;n.length;){let i=0,l=1/0;n.forEach((c,d)=>{const u=ZQt(a.lat,a.lng,c.lat,c.lng);u{const l=n.filter(o=>typeof o.latitude=="number"&&typeof o.longitude=="number");return s.map(o=>{var u;const c=((u=o.boundary)==null?void 0:u.ring)??[],d=new Set;if(c.length>=3)for(const h of l)o$n(h.longitude,h.latitude,c)&&d.add(h.id);return{id:o.id,name:o.name,color:o.color,contactIds:d,count:d.size}})},[s,n]),i=j.useMemo(()=>n.filter(l=>typeof l.latitude!="number"||typeof l.longitude!="number").length,[n]);return{neighborhoods:a,unmappedCount:i,isLoading:t||r}}function XQt(s,t){const n=t instanceof Set?t:new Set(t);if(n.size===0)return null;const r=new Set;for(const a of s)n.has(a.id)&&a.contactIds.forEach(i=>r.add(i));return r}function c$n({selected:s,onChange:t,className:n}){const{neighborhoods:r,unmappedCount:a,isLoading:i}=kit(),l=new Set(s),o=c=>{const d=new Set(l);d.has(c)?d.delete(c):d.add(c),t(Array.from(d))};return e.jsxs(Yd,{children:[e.jsx(Zd,{asChild:!0,children:e.jsxs($,{variant:"outline",size:"sm",className:`gap-1.5 h-8 rounded-lg ${n??""}`,children:[e.jsx(ci,{className:"h-3.5 w-3.5"}),"Neighborhoods",s.length>0&&e.jsx(Be,{variant:"secondary",className:"h-5 px-1.5 text-[10px]",children:s.length})]})}),e.jsxs(Bd,{align:"start",className:"w-72 p-0",children:[e.jsxs("div",{className:"p-3 border-b",children:[e.jsx("p",{className:"text-sm font-medium",children:"Neighborhoods"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Areas you've drawn on the contacts map."})]}),i?e.jsxs("div",{className:"p-6 flex items-center justify-center text-sm text-muted-foreground gap-2",children:[e.jsx(kt,{className:"h-4 w-4 animate-spin"})," Loading…"]}):r.length===0?e.jsxs("div",{className:"p-4 space-y-2 text-sm",children:[e.jsx("p",{className:"text-muted-foreground",children:"You haven't drawn any neighborhoods yet."}),e.jsx($,{asChild:!0,variant:"outline",size:"sm",className:"w-full",children:e.jsx(wr,{to:"/mission-control/sphere-map",children:"Open the contacts map"})})]}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"max-h-64 overflow-y-auto p-2 space-y-1",children:r.map(c=>e.jsxs("button",{type:"button",onClick:()=>o(c.id),className:"w-full flex items-center gap-2 px-2 py-1.5 rounded-md hover:bg-muted text-sm text-left",children:[e.jsx(ai,{checked:l.has(c.id),className:"pointer-events-none"}),e.jsx("span",{className:"h-2.5 w-2.5 rounded-full shrink-0",style:{backgroundColor:c.color}}),e.jsx("span",{className:"flex-1 truncate",children:c.name}),e.jsx("span",{className:"text-xs text-muted-foreground",children:c.count})]},c.id))}),e.jsxs("div",{className:"p-2 border-t space-y-2",children:[a>0&&e.jsxs("p",{className:"text-[11px] text-muted-foreground px-1",children:[a.toLocaleString()," contacts don't have a mapped address yet, so they can't land in a neighborhood."," ",e.jsx(wr,{to:"/mission-control/sphere-map",className:"underline",children:"Map them"})]}),s.length>0&&e.jsx($,{variant:"ghost",size:"sm",className:"w-full text-xs",onClick:()=>t([]),children:"Clear neighborhoods"})]})]})]})]})}async function q$(s){const n=[];for(let r=0;r<50;r++){const{data:a,error:i}=await s(r*1e3,r*1e3+1e3-1);if(i)throw i;const l=a||[];if(n.push(...l),l.length<1e3)break}return n}function lX(){return{lastActiveAt:null,registered:!1,propertyViewCount:0,propertyViewCount7d:0,savedListingCount:0,activeSavedSearchCount:0,showingRequests:0,valuationRequests:0,viewedCities:[],viewedZips:[]}}function d$n(){const{user:s}=vs(),{leadSite:t,hasLeadSite:n}=ng(),{data:r,isLoading:a}=tt({queryKey:["contact-behavior-summary",s==null?void 0:s.id,t==null?void 0:t.id],queryFn:async()=>{const i=new Map;if(!t)return i;const l=(v,b)=>{const w=i.get(v)||lX();i.set(v,{...w,...b})},o=await q$((v,b)=>q.from("lead_site_visitors").select("id, contact_id, last_seen_at, email").eq("lead_site_id",t.id).not("contact_id","is",null).range(v,b)),c=new Map,d=new Map;o.forEach(v=>{if(!v.contact_id)return;c.set(v.id,v.contact_id),v.email&&d.set(v.email.toLowerCase(),v.contact_id);const b=i.get(v.contact_id);(!b||!b.lastActiveAt||v.last_seen_at>b.lastActiveAt)&&l(v.contact_id,{lastActiveAt:v.last_seen_at})});const u=await q$((v,b)=>q.from("lead_site_consumer_profiles").select("contact_id, user_id").eq("lead_site_id",t.id).not("contact_id","is",null).range(v,b)),h=new Map;u.forEach(v=>{v.contact_id&&(h.set(v.user_id,v.contact_id),l(v.contact_id,{registered:!0}))});const m=new Date(Date.now()-7*24*60*60*1e3).toISOString();return(await q$((v,b)=>q.from("lead_site_property_views").select("visitor_id, viewed_at, property_address").eq("lead_site_id",t.id).not("visitor_id","is",null).range(v,b))).forEach(v=>{const b=v.visitor_id?c.get(v.visitor_id):null;if(!b)return;const w=i.get(b)||lX();w.propertyViewCount+=1,v.viewed_at>=m&&(w.propertyViewCount7d+=1),i.set(b,w)}),(await q$((v,b)=>q.from("lead_site_saved_listings").select("user_id, mls_number").eq("lead_site_id",t.id).range(v,b))).forEach(v=>{const b=h.get(v.user_id);if(!b)return;const w=i.get(b)||lX();w.savedListingCount+=1,i.set(b,w)}),(await q$((v,b)=>q.from("lead_site_saved_searches").select("user_id").eq("lead_site_id",t.id).eq("is_active",!0).range(v,b))).forEach(v=>{const b=h.get(v.user_id);if(!b)return;const w=i.get(b)||lX();w.activeSavedSearchCount+=1,i.set(b,w)}),(await q$((v,b)=>q.from("lead_site_leads").select("email, lead_type").eq("lead_site_id",t.id).not("email","is",null).range(v,b))).forEach(v=>{if(!v.email)return;const b=d.get(v.email.toLowerCase());if(!b)return;const w=i.get(b)||lX(),S=(v.lead_type||"").toLowerCase();(S.includes("showing")||S.includes("question")||S==="contact")&&(w.showingRequests+=1),(S.includes("valuation")||S.includes("cma")||S.includes("home_value"))&&(w.valuationRequests+=1),i.set(b,w)}),i},enabled:!!s&&n,staleTime:5*60*1e3});return{behaviorMap:r??new Map,hasLeadSite:n,isLoading:a}}const QQt="innercircle_geocode_cache_v1";function u$n(){try{return JSON.parse(localStorage.getItem(QQt)||"{}")}catch{return{}}}function h$n(s){try{localStorage.setItem(QQt,JSON.stringify(s))}catch{}}function m$n(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 f$n({open:s,onOpenChange:t,contacts:n,onCitySelect:r}){const a=j.useRef(null),i=j.useRef(null),[l,o]=j.useState(""),[c,d]=j.useState(!0),[u,h]=j.useState([]),[m,f]=j.useState({done:0,total:0}),[g,x]=j.useState(!1),[y,v]=j.useState("heat");j.useEffect(()=>{if(!s)return;let w=!1;return(async()=>{d(!0);const{data:S}=await q.from("settings").select("value").eq("key","mapbox_public_token").maybeSingle();w||(o((S==null?void 0:S.value)||""),d(!1))})(),()=>{w=!0}},[s]),j.useEffect(()=>{if(!s||!l)return;let w=!1;return(async()=>{const C=u$n(),E=n.map(V=>({c:V,addr:m$n(V)})).filter(V=>V.addr),I=[],P=[];for(const{c:V,addr:G}of E){const Y=C[G];Y!==null&&(Y?I.push({id:V.id,name:`${V.first_name||""} ${V.last_name||""}`.trim(),city:V.city||null,state:V.state||null,zip:V.zip||V.zip_code||null,lat:Y.lat,lng:Y.lng}):P.push({c:V,addr:G}))}if(w||h(I),f({done:I.length,total:E.length}),P.length===0)return;x(!0);const R=6;let D=0;const O={...C},U=[...I],W=async()=>{var V;for(;D{w=!0}},[s,l,n]);const b=j.useMemo(()=>{const w=new Map;for(const S of n){const C=(S.city||"").trim();if(!C)continue;const E=(S.state||"").trim()||null,I=`${C.toLowerCase()}|${E||""}`,P=w.get(I);P?P.count++:w.set(I,{city:C,state:E,count:1})}return Array.from(w.values()).sort((S,C)=>C.count-S.count)},[n]);return j.useEffect(()=>{if(!(!s||!l||!a.current||i.current))return ju.accessToken=l,i.current=new ju.Map({container:a.current,style:"mapbox://styles/mapbox/light-v11",center:[-98.5795,39.8283],zoom:3.5}),i.current.addControl(new ju.NavigationControl,"top-right"),()=>{var w;(w=i.current)==null||w.remove(),i.current=null}},[s,l]),j.useEffect(()=>{const w=i.current;if(!w||u.length===0)return;const S=()=>{const E={type:"FeatureCollection",features:u.map(P=>({type:"Feature",properties:{id:P.id,name:P.name},geometry:{type:"Point",coordinates:[P.lng,P.lat]}}))},I=w.getSource("contacts-src");if(I?I.setData(E):(w.addSource("contacts-src",{type:"geojson",data:E}),w.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]}}),w.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}}),w.on("click","contacts-points",P=>{var O;const R=(O=P.features)==null?void 0:O[0];if(!R)return;const D=R.geometry.coordinates.slice();new ju.Popup({offset:12}).setLngLat(D).setHTML(`
${R.properties.name||"Contact"}
`).addTo(w)}),w.on("mouseenter","contacts-points",()=>{w.getCanvas().style.cursor="pointer"}),w.on("mouseleave","contacts-points",()=>{w.getCanvas().style.cursor=""})),w.getLayer("contacts-heat")&&w.setLayoutProperty("contacts-heat","visibility",y==="heat"?"visible":"none"),w.getLayer("contacts-points")&&(w.setPaintProperty("contacts-points","circle-opacity",y==="points"?.9:0),w.setLayoutProperty("contacts-points","visibility","visible")),u.length>0&&!w._fitDone){const P=new ju.LngLatBounds;u.forEach(R=>P.extend([R.lng,R.lat]));try{w.fitBounds(P,{padding:60,maxZoom:11,duration:600}),w._fitDone=!0}catch{}}};w.isStyleLoaded()?S():w.once("load",S)},[u,y]),e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Os,{className:"max-w-6xl w-[95vw] h-[90vh] p-0 flex flex-col",children:[e.jsx(Us,{className:"p-4 pb-2 border-b",children:e.jsxs(Bs,{className:"flex items-center gap-2",children:[e.jsx(nh,{className:"h-5 w-5 text-orange-500"}),"Geographic Heat Map",e.jsxs(Be,{variant:"secondary",className:"ml-2",children:[u.length," mapped · ",b.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(kt,{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($,{size:"sm",variant:y==="heat"?"default":"ghost",onClick:()=>v("heat"),className:"h-8",children:[e.jsx(nh,{className:"h-3.5 w-3.5 mr-1"})," Heat"]}),e.jsxs($,{size:"sm",variant:y==="points"?"default":"ghost",onClick:()=>v("points"),className:"h-8",children:[e.jsx(L4,{className:"h-3.5 w-3.5 mr-1"})," Pins"]})]}),g&&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(kt,{className:"h-3 w-3 animate-spin"}),"Mapping ",m.done," / ",m.total]})]})]}):e.jsxs("div",{className:"h-full flex flex-col items-center justify-center gap-3 p-6 text-center",children:[e.jsx(ll,{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(ci,{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(uo,{className:"flex-1",children:e.jsxs("div",{className:"p-2 space-y-1.5",children:[b.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."}),b.slice(0,50).map((w,S)=>{var I;const C=((I=b[0])==null?void 0:I.count)||1,E=w.count/C*100;return e.jsx(Ne,{className:"cursor-pointer hover:border-primary transition-colors overflow-hidden",onClick:()=>{r==null||r(w.city,w.state),t(!1)},children:e.jsxs(Ie,{className:"p-2.5 relative",children:[e.jsx("div",{className:"absolute inset-y-0 left-0 bg-primary/10",style:{width:`${E}%`}}),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:[w.city,w.state?`, ${w.state}`:""]}),e.jsx("div",{className:"text-[10px] text-muted-foreground",children:S===0?"🔥 Hottest market":`Rank #${S+1}`})]}),e.jsx(Be,{variant:"secondary",className:"shrink-0",children:w.count})]})]})},`${w.city}-${w.state}-${S}`)})]})})]})]})]})})}function UO(s){if(!s)return null;try{const t=s.split(/[-/T]/);if(t.length<3)return null;const n=parseInt(t[1],10)-1,r=parseInt(t[2],10);if(isNaN(n)||isNaN(r))return null;const a=new Date;a.setHours(0,0,0,0);let i=new Date(a.getFullYear(),n,r);return i.setHours(0,0,0,0),in)return null;const a=t==="birthday"?"🎂":"🏡",i=r===0?t==="birthday"?"Birthday today!":"Anniversary today!":r===1?t==="birthday"?"Birthday tomorrow":"Anniversary tomorrow":`${a} in ${r}d`;return{emoji:a,label:i,daysUntil:r}}function pCt({birthday:s,homeAnniversary:t,weddingAnniversary:n,className:r,contactId:a,contactName:i,contactAddress:l}){const o=Qn(),c=J9e(s,"birthday",7),d=J9e(t,"anniversary",7),u=J9e(n||null,"anniversary",7);if(!c&&!d&&!u)return null;const h=(m,f,g)=>{g.stopPropagation();const x=new URLSearchParams;a&&x.set("contactId",a),i&&x.set("name",i),l&&x.set("address",l),(m==="home_anniversary"||m==="wedding_anniversary")&&f&&x.set("date",f),x.set("cardType",m),o(`/mission-control/card-studio?${x.toString()}`)};return e.jsxs("div",{className:Pt("flex flex-wrap gap-1",r),children:[c&&e.jsxs("div",{className:"flex items-center gap-0.5",children:[e.jsx(Be,{variant:"secondary",className:Pt("text-[10px] gap-0.5 font-medium",c.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:c.label}),a&&e.jsxs("button",{onClick:m=>h("birthday",s,m),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(mn,{className:"h-2.5 w-2.5"}),"Send Card"]})]}),d&&e.jsxs("div",{className:"flex items-center gap-0.5",children:[e.jsx(Be,{variant:"secondary",className:Pt("text-[10px] gap-0.5 font-medium",d.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:d.label}),a&&e.jsxs("button",{onClick:m=>h("home_anniversary",t,m),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(mn,{className:"h-2.5 w-2.5"}),"Send Card"]})]}),u&&e.jsxs("div",{className:"flex items-center gap-0.5",children:[e.jsxs(Be,{variant:"secondary",className:Pt("text-[10px] gap-0.5 font-medium",u.daysUntil===0?"bg-rose-100 text-rose-700 dark:bg-rose-900/30 dark:text-rose-400 animate-pulse":"bg-rose-50 text-rose-600 dark:bg-rose-900/20 dark:text-rose-400"),children:["💍 ",u.label.replace(/^[^\w]+/,"")]}),a&&e.jsxs("button",{onClick:m=>h("wedding_anniversary",n||null,m),className:"inline-flex items-center gap-0.5 px-1.5 py-0.5 rounded-full text-[9px] font-semibold bg-rose-500/15 text-rose-600 dark:text-rose-400 hover:bg-rose-500/25 transition-colors",title:"Send a wedding anniversary card",children:[e.jsx(mn,{className:"h-2.5 w-2.5"}),"Send Card"]})]})]})}function gCt({deal:s}){if(!s||!s.stage)return null;const{stage:t}=s;return e.jsxs(Be,{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 xCt({count:s,className:t}){return!s||s<=0?null:e.jsxs(Be,{variant:"outline",className:Pt("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(tL,{className:"h-2.5 w-2.5"}),s===1?"In drip":`${s} drips`]})}function p$n(){const s=Sa();return tt({queryKey:["contacts-campaign-counts",s],queryFn:async()=>{if(!s)return{};const{data:t,error:n}=await q.from("drip_campaign_enrollments").select("contact_id, status").eq("owner_user_id",s).eq("status","active");if(n)throw n;const r={};return(t||[]).forEach(a=>{a.contact_id&&(r[a.contact_id]=(r[a.contact_id]||0)+1)}),r},enabled:!!s,staleTime:6e4})}function g$n(){const s=Sa();return tt({queryKey:["contact-deals-map",s],queryFn:async()=>{const{data:t,error:n}=await q.from("deal_pipeline").select(` id, deal_name, contact_id, deal_type, expected_price, sale_price, stage:deal_pipeline_stages(id, name, color, icon, is_won_stage, is_lost_stage) `).not("contact_id","is",null);if(n)throw n;const r={};return(t||[]).forEach(a=>{a.contact_id&&!r[a.contact_id]&&(r[a.contact_id]=a)}),r},enabled:!!s})}const x$n="#6366F1";function yCt(s,t){return`color-mix(in srgb, ${s} ${t}%, transparent)`}function y$n(s){return`color-mix(in oklab, ${s} 78%, hsl(var(--foreground)))`}function JQt({label:s,color:t,className:n,onClick:r,title:a}){const i=t||x$n,l=r?"button":"span";return e.jsxs(l,{type:r?"button":void 0,onClick:r,title:a??s,style:{backgroundColor:yCt(i,14),color:y$n(i),boxShadow:`inset 0 0 0 1px ${yCt(i,22)}`},className:Pt("inline-flex h-6 max-w-[140px] items-center gap-1.5 rounded-full px-2.5 text-[11px] font-medium leading-none",r&&"transition-transform hover:scale-[1.03]",n),children:[e.jsx("span",{className:"h-1.5 w-1.5 shrink-0 rounded-full",style:{backgroundColor:i},"aria-hidden":!0}),e.jsx("span",{className:"truncate",children:s})]})}function v$n({tags:s,max:t=2,className:n}){const[r,a]=j.useState(!1);if(!s||s.length===0)return null;const i=r?s:s.slice(0,t),l=s.length-i.length;return e.jsxs("div",{className:Pt("flex flex-wrap items-center gap-1.5",n),children:[i.map(o=>{var c,d;return e.jsx(JQt,{label:((c=o.tag)==null?void 0:c.name)||"Tag",color:(d=o.tag)==null?void 0:d.color},o.tag_id)}),l>0&&e.jsxs("button",{type:"button",onClick:o=>{o.stopPropagation(),a(!0)},className:"inline-flex h-6 items-center rounded-full bg-muted px-2 text-[11px] font-medium leading-none text-muted-foreground transition-colors hover:bg-accent hover:text-foreground",children:["+",l]})]})}function vCt({contactId:s,compact:t=!1}){const{data:n}=a9(),{data:r}=KDn(s),a=rit(),i=WXt(),l=XDn(),[o,c]=j.useState(!1),[d,u]=j.useState(""),h=j.useRef(null),m=new Set((r==null?void 0:r.map(v=>v.tag_id))||[]),f=(n==null?void 0:n.filter(v=>v.name.toLowerCase().includes(d.toLowerCase())))||[],g=n==null?void 0:n.find(v=>v.name.toLowerCase()===d.trim().toLowerCase()),x=async v=>{m.has(v.id)?await l.mutateAsync({contactId:s,tagId:v.id}):await i.mutateAsync({contactId:s,tagId:v.id})},y=async()=>{if(!(!d.trim()||g))try{const v=await a.mutateAsync({name:d.trim()});await i.mutateAsync({contactId:s,tagId:v.id}),u("")}catch{}};return e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[r==null?void 0:r.map(v=>{var b,w,S;return e.jsxs(Be,{variant:"outline",className:"text-xs gap-1 pr-1",style:{borderColor:((b=v.tag)==null?void 0:b.color)||"#6366F1",color:((w=v.tag)==null?void 0:w.color)||"#6366F1"},children:[e.jsx(Ap,{className:"h-2.5 w-2.5"}),(S=v.tag)==null?void 0:S.name,e.jsx("button",{onClick:C=>{C.stopPropagation(),l.mutate({contactId:s,tagId:v.tag_id})},className:"ml-0.5 rounded-full hover:bg-accent p-0.5",children:e.jsx(gr,{className:"h-2.5 w-2.5"})})]},v.id)}),e.jsxs(Yd,{open:o,onOpenChange:c,children:[e.jsx(Zd,{asChild:!0,children:e.jsxs($,{variant:"ghost",size:"sm",className:t?"h-6 w-6 p-0":"h-6 px-2 text-xs",onClick:v=>v.stopPropagation(),children:[e.jsx(dn,{className:"h-3 w-3"}),!t&&e.jsx("span",{className:"ml-1",children:"Tag"})]})}),e.jsxs(Bd,{className:"w-56 p-2",align:"start",onClick:v=>v.stopPropagation(),children:[e.jsx(pe,{ref:h,placeholder:"Search or create tag...",value:d,onChange:v=>u(v.target.value),onKeyDown:v=>{v.key==="Enter"&&d.trim()&&!g?(v.preventDefault(),y()):v.key==="Enter"&&g&&!m.has(g.id)&&(v.preventDefault(),x(g))},className:"h-8 text-sm mb-2"}),e.jsxs("div",{className:"max-h-[200px] overflow-y-auto space-y-0.5",children:[f.map(v=>e.jsxs("button",{onClick:()=>x(v),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:v.color}}),e.jsx("span",{className:"flex-1 text-left truncate",children:v.name}),m.has(v.id)&&e.jsx(la,{className:"h-3.5 w-3.5 text-primary shrink-0"})]},v.id)),d.trim()&&!g&&e.jsxs("button",{onClick:y,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(dn,{className:"h-3.5 w-3.5"}),'Create "',d.trim(),'"']}),f.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 bCt({contactId:s,tags:t,max:n=2}){return!t||t.length===0?null:e.jsx(v$n,{tags:t,max:n})}const due=["#6366F1","#8B5CF6","#EC4899","#EF4444","#F97316","#F59E0B","#10B981","#14B8A6","#06B6D4","#3B82F6","#6B7280","#1F2937"];function b$n({open:s,onOpenChange:t}){const{data:n,isLoading:r}=a9(),a=rit(),i=ZDn(),l=YDn(),[o,c]=j.useState(""),[d,u]=j.useState(due[0]),[h,m]=j.useState(null),[f,g]=j.useState(""),[x,y]=j.useState(""),v=async()=>{if(o.trim())try{await a.mutateAsync({name:o.trim(),color:d}),c(""),u(due[0]),_a({title:"Tag created"})}catch(C){_a({title:"Error",description:C.message,variant:"destructive"})}},b=async C=>{if(f.trim())try{await i.mutateAsync({id:C,name:f.trim(),color:x}),m(null),_a({title:"Tag updated"})}catch(E){_a({title:"Error",description:E.message,variant:"destructive"})}},w=async(C,E)=>{if(await fo(`Delete tag "${E}"? It will be removed from all contacts.`))try{await l.mutateAsync(C),_a({title:"Tag deleted"})}catch(I){_a({title:"Error",description:I.message,variant:"destructive"})}},S=C=>{m(C.id),g(C.name),y(C.color)};return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Os,{className:"max-w-md",children:[e.jsx(Us,{children:e.jsx(Bs,{children:"Manage Tags"})}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsx(pe,{placeholder:"New tag name...",value:o,onChange:C=>c(C.target.value),onKeyDown:C=>C.key==="Enter"&&v(),className:"flex-1 h-9"}),e.jsxs($,{size:"sm",onClick:v,disabled:!o.trim()||a.isPending,className:"h-9",children:[e.jsx(dn,{className:"h-4 w-4 mr-1"}),"Add"]})]}),e.jsx("div",{className:"flex flex-wrap gap-1.5",children:due.map(C=>e.jsx("button",{onClick:()=>u(C),className:`h-6 w-6 rounded-full border-2 transition-transform ${d===C?"border-foreground scale-110":"border-transparent hover:scale-105"}`,style:{backgroundColor:C}},C))})]}),e.jsxs("div",{className:"mt-2 space-y-1 max-h-[320px] overflow-y-auto",children:[r&&e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"Loading..."}),(n==null?void 0:n.length)===0&&e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"No tags yet. Create one above!"}),n==null?void 0:n.map(C=>e.jsx("div",{className:"flex items-center gap-2 p-2 rounded-lg hover:bg-accent/50 group",children:h===C.id?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"flex flex-wrap gap-1",children:due.map(E=>e.jsx("button",{onClick:()=>y(E),className:`h-5 w-5 rounded-full border-2 ${x===E?"border-foreground":"border-transparent"}`,style:{backgroundColor:E}},E))}),e.jsx(pe,{value:f,onChange:E=>g(E.target.value),onKeyDown:E=>E.key==="Enter"&&b(C.id),className:"flex-1 h-8 text-sm",autoFocus:!0}),e.jsx($,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>b(C.id),children:e.jsx(la,{className:"h-4 w-4 text-primary"})}),e.jsx($,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>m(null),children:e.jsx(gr,{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:C.color}}),e.jsx("span",{className:"flex-1 text-sm",children:C.name}),e.jsx($,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0 opacity-0 group-hover:opacity-100 transition-opacity",onClick:()=>S(C),children:e.jsx(gi,{className:"h-3.5 w-3.5"})}),e.jsx($,{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:()=>w(C.id,C.name),children:e.jsx(Wn,{className:"h-3.5 w-3.5"})})]})},C.id))]})]})})}function _$n({open:s,onOpenChange:t}){const{data:n,isLoading:r}=HB(),a=fnt(),i=HWs(),l=GWs(),[o,c]=j.useState(""),[d,u]=j.useState(null),[h,m]=j.useState(""),f=async()=>{if(o.trim())try{await a.mutateAsync(o.trim()),c("")}catch(v){re.error(v.message||"Failed to add lead source")}},g=async v=>{if(h.trim())try{await i.mutateAsync({id:v,name:h.trim()}),u(null)}catch(b){re.error(b.message||"Failed to update")}},x=async(v,b)=>{if(await fo(`Remove lead source "${b}"? Contacts using it will keep the label but it won't appear in new dropdowns.`))try{await l.mutateAsync(v)}catch(w){re.error(w.message||"Failed to remove")}},y=v=>{u(v.id),m(v.name)};return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Os,{className:"max-w-md",children:[e.jsx(Us,{children:e.jsx(Bs,{children:"Manage Lead Sources"})}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(pe,{placeholder:"New lead source name...",value:o,onChange:v=>c(v.target.value),onKeyDown:v=>v.key==="Enter"&&f(),className:"flex-1 h-9"}),e.jsxs($,{size:"sm",onClick:f,disabled:!o.trim()||a.isPending,className:"h-9",children:[e.jsx(dn,{className:"h-4 w-4 mr-1"}),"Add"]})]}),e.jsxs("div",{className:"mt-2 space-y-1 max-h-[360px] overflow-y-auto",children:[r&&e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"Loading..."}),(n==null?void 0:n.length)===0&&e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"No lead sources yet. Create one above!"}),n==null?void 0:n.map(v=>e.jsx("div",{className:"flex items-center gap-2 p-2 rounded-lg hover:bg-accent/50 group",children:d===v.id?e.jsxs(e.Fragment,{children:[e.jsx(pe,{value:h,onChange:b=>m(b.target.value),onKeyDown:b=>b.key==="Enter"&&g(v.id),className:"flex-1 h-8 text-sm",autoFocus:!0}),e.jsx($,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>g(v.id),children:e.jsx(la,{className:"h-4 w-4 text-primary"})}),e.jsx($,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>u(null),children:e.jsx(gr,{className:"h-4 w-4"})})]}):e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"flex-1 text-sm",children:v.name}),v.owner_user_id&&e.jsxs(e.Fragment,{children:[e.jsx($,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0 opacity-0 group-hover:opacity-100 transition-opacity",onClick:()=>y(v),children:e.jsx(gi,{className:"h-3.5 w-3.5"})}),e.jsx($,{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:()=>x(v.id,v.name),children:e.jsx(Wn,{className:"h-3.5 w-3.5"})})]}),!v.owner_user_id&&e.jsx("span",{className:"text-xs text-muted-foreground",children:"Default"})]})},v.id))]})]})})}function eJt({value:s,onChange:t,label:n="Lead Source"}){const{data:r}=HB(),a=fnt(),[i,l]=j.useState(!1),[o,c]=j.useState(""),d=async()=>{if(o.trim())try{const u=await a.mutateAsync(o.trim());u&&(t(u.id),c(""),l(!1))}catch{}};return e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:n}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(ms,{value:s||"_none",onValueChange:u=>t(u==="_none"?"":u),children:[e.jsx(us,{className:"flex-1",children:e.jsx(fs,{placeholder:"Select lead source"})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"_none",children:"No source"}),r==null?void 0:r.map(u=>e.jsx(Ge,{value:u.id,children:u.name},u.id))]})]}),e.jsx($,{type:"button",variant:"outline",size:"icon",className:"shrink-0",onClick:()=>l(!i),children:i?e.jsx(gr,{className:"h-4 w-4"}):e.jsx(dn,{className:"h-4 w-4"})})]}),i&&e.jsxs("div",{className:"flex gap-2",children:[e.jsx(pe,{placeholder:"New lead source name...",value:o,onChange:u=>c(u.target.value),onKeyDown:u=>{u.key==="Enter"&&(u.preventDefault(),d())},className:"flex-1"}),e.jsx($,{type:"button",size:"sm",onClick:d,disabled:!o.trim()||a.isPending,children:"Add"})]})]})}function BYe({contactId:s,currentSpouseContactId:t,currentSpouseName:n,currentSpouseEmail:r,onLink:a,onUnlink:i,isEditing:l}){const o=Qn(),c=Sa(),[d,u]=j.useState(!1),[h,m]=j.useState(""),{data:f}=tt({queryKey:["innercircle-contact-spouse",t],queryFn:async()=>{const{data:x,error:y}=await q.from("innercircle_contacts").select("id, first_name, last_name, email, phone, birthday").eq("id",t).maybeSingle();if(y)throw y;return x},enabled:!!t}),{data:g}=tt({queryKey:["spouse-search",c,s,h],queryFn:async()=>{let x=q.from("innercircle_contacts").select("id, first_name, last_name, email, phone").eq("owner_user_id",c).is("synced_source",null).neq("id",s).order("first_name").limit(20);if(h.trim()){const b=h.replace(/[,()%]/g," ").trim();b&&(x=x.or(`first_name.ilike.%${b}%,last_name.ilike.%${b}%,email.ilike.%${b}%,phone.ilike.%${b}%`))}const{data:y,error:v}=await x;if(v)throw v;return y},enabled:d&&!!c});if(t&&f){const x=`${f.first_name} ${f.last_name||""}`.trim();return e.jsxs("div",{className:"space-y-1",children:[e.jsx(ee,{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(sl,{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/${f.id}`),className:"text-sm font-medium text-primary hover:underline truncate block",children:x}),e.jsx("div",{className:"text-xs text-muted-foreground truncate",children:[f.phone,f.email].filter(Boolean).join(" · ")||"No contact info"})]}),l&&e.jsxs($,{variant:"ghost",size:"sm",onClick:i,className:"shrink-0 h-7 px-2",children:[e.jsx($E,{className:"h-3.5 w-3.5 mr-1"}),"Unlink"]}),!l&&e.jsx($,{variant:"ghost",size:"sm",onClick:()=>o(`/mission-control/contacts/${f.id}`),className:"shrink-0 h-7 px-2",children:e.jsx(ei,{className:"h-3.5 w-3.5"})})]})]})}return!t&&(n||r)?e.jsxs("div",{className:"space-y-1",children:[e.jsx(ee,{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(sl,{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:n}),r&&e.jsx("span",{className:"text-xs text-muted-foreground block truncate",children:r})]}),l&&e.jsxs(Yd,{open:d,onOpenChange:u,children:[e.jsx(Zd,{asChild:!0,children:e.jsxs($,{variant:"outline",size:"sm",className:"shrink-0 h-7 px-2",children:[e.jsx(bd,{className:"h-3.5 w-3.5 mr-1"}),"Link Contact"]})}),e.jsx(Bd,{className:"w-72 p-2",align:"end",children:e.jsx(_Ct,{search:h,setSearch:m,results:g,onSelect:x=>{a(x),u(!1),m("")}})})]})]})]}):l?e.jsxs("div",{className:"space-y-1",children:[e.jsx(ee,{className:"text-sm font-medium",children:"Spouse / Partner"}),e.jsxs(Yd,{open:d,onOpenChange:u,children:[e.jsx(Zd,{asChild:!0,children:e.jsxs($,{variant:"outline",className:"w-full justify-start text-muted-foreground font-normal h-10",children:[e.jsx(bd,{className:"h-4 w-4 mr-2"}),"Link an existing contact as spouse..."]})}),e.jsx(Bd,{className:"w-72 p-2",align:"start",children:e.jsx(_Ct,{search:h,setSearch:m,results:g,onSelect:x=>{a(x),u(!1),m("")}})})]})]}):null}function _Ct({search:s,setSearch:t,results:n,onSelect:r}){return e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"relative",children:[e.jsx(Kr,{className:"absolute left-2 top-2.5 h-3.5 w-3.5 text-muted-foreground"}),e.jsx(pe,{value:s,onChange:a=>t(a.target.value),placeholder:"Search contacts...",className:"pl-7 h-8 text-sm",autoFocus:!0})]}),e.jsx(uo,{className:"max-h-48",children:n&&n.length>0?e.jsx("div",{className:"space-y-0.5",children:n.map(a=>e.jsxs("button",{onClick:()=>r(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"})})]})}const w$n={warm:"stroke-emerald-500",cooling:"stroke-amber-500","at-risk":"stroke-red-500"},j$n={warm:"text-emerald-600 dark:text-emerald-400",cooling:"text-amber-600 dark:text-amber-400","at-risk":"text-red-600 dark:text-red-400"};function N$n({score:s,status:t,size:n=36,className:r}){const a=n>=56?5:3,i=(n-a)/2,l=2*Math.PI*i,o=Math.max(0,Math.min(100,s)),c=l-o/100*l;return e.jsxs("div",{className:Pt("relative shrink-0",r),style:{width:n,height:n},children:[e.jsxs("svg",{width:n,height:n,className:"-rotate-90",children:[e.jsx("circle",{cx:n/2,cy:n/2,r:i,fill:"none",strokeWidth:a,className:"stroke-muted"}),e.jsx("circle",{cx:n/2,cy:n/2,r:i,fill:"none",strokeWidth:a,strokeLinecap:"round",strokeDasharray:l,strokeDashoffset:c,className:w$n[t]})]}),e.jsx("span",{className:Pt("absolute inset-0 flex items-center justify-center font-semibold tabular-nums",j$n[t],n>=56?"text-lg":"text-[11px]"),children:o})]})}const uue=new Map;async function k$n(s){const t=new TextEncoder().encode(s),n=await crypto.subtle.digest("SHA-256",t);return Array.from(new Uint8Array(n)).map(r=>r.toString(16).padStart(2,"0")).join("")}async function S$n(s,t=256){const n=s.trim().toLowerCase();if(!n||!n.includes("@"))return null;const r=`${n}|${t}`;if(uue.has(r))return uue.get(r)??null;try{const i=`https://gravatar.com/avatar/${await k$n(n)}?s=${t}&d=404`;return uue.set(r,i),i}catch{return uue.set(r,null),null}}function C$n(s,t=256){const[n,r]=j.useState(null);return j.useEffect(()=>{let a=!0;if(!s){r(null);return}return S$n(s,t).then(i=>{a&&r(i)}),()=>{a=!1}},[s,t]),n}function Sit({firstName:s,lastName:t,avatarUrl:n,email:r,size:a=36,className:i,rounded:l="full"}){const o=`${(s==null?void 0:s[0])??""}${(t==null?void 0:t[0])??""}`.toUpperCase()||"?",c=l==="full"?"rounded-full":l==="xl"?"rounded-xl":"rounded-2xl",d=C$n(n?null:r,Math.max(64,a*2)),[u,h]=j.useState(!1);j.useEffect(()=>h(!1),[d]);const m=n||(u?null:d);return e.jsx("div",{className:Pt("shrink-0 overflow-hidden bg-primary/10 text-primary flex items-center justify-center font-semibold select-none",c,i),style:{width:a,height:a,fontSize:Math.max(10,Math.round(a*.36))},children:m?e.jsx("img",{src:m,alt:`${s??""} ${t??""}`.trim()||"Contact photo",className:"h-full w-full object-cover",loading:"lazy",onError:()=>h(!0)}):e.jsx("span",{children:o})})}function A$n({spouseName:s,linked:t,onClick:n}){if(!s&&!t)return null;const r=s?`${t?"Linked spouse":"Spouse"}: ${s}`:"Spouse / partner linked";return e.jsxs(ly,{children:[e.jsx(cy,{asChild:!0,children:e.jsx("span",{role:n?"button":void 0,onClick:n?a=>{a.stopPropagation(),n()}:void 0,className:`inline-flex h-5 w-5 shrink-0 items-center justify-center rounded-full bg-muted text-muted-foreground ${n?"cursor-pointer hover:bg-accent hover:text-accent-foreground":""}`,"aria-label":r,children:e.jsx(Zn,{className:"h-3 w-3"})})}),e.jsx(Nx,{children:r})]})}function E$n({totalLabel:s,stats:t,search:n,onSearchChange:r,onAddContact:a,onImportCsv:i,onImportPhone:l,onManageTags:o,onHeatMap:c,viewMode:d="my",onViewModeChange:u,showTeamTab:h,showLeadPondTab:m,extraActions:f}){const g=!!u&&(h||m);return e.jsx("section",{className:"hub-ink relative overflow-hidden rounded-2xl p-5 sm:p-6",children:e.jsxs("div",{className:"relative flex flex-col gap-5",children:[e.jsxs("div",{className:"flex flex-col gap-4 lg:flex-row lg:items-start lg:justify-between",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-xs uppercase tracking-wider hub-ink-muted",children:"Agent OS"}),e.jsx("h1",{className:"mt-1 text-2xl font-bold sm:text-3xl",children:"Contacts"}),e.jsx("p",{className:"mt-1 text-sm hub-ink-muted",children:s})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs("button",{onClick:a,className:"inline-flex items-center gap-2 rounded-full bg-background px-4 py-2 text-sm font-semibold text-foreground shadow-sm transition-transform hover:scale-[1.02]",children:[e.jsx(dn,{className:"h-4 w-4"}),"Add Contact"]}),e.jsxs("button",{onClick:c,className:"hub-glass inline-flex items-center gap-2 rounded-full px-4 py-2 text-sm font-medium transition-colors",children:[e.jsx(nh,{className:"h-4 w-4",style:{color:"hsl(var(--hub-glow))"}}),"Heat Map"]}),e.jsxs(Uu,{children:[e.jsx(qu,{asChild:!0,children:e.jsxs("button",{className:"hub-glass inline-flex items-center gap-2 rounded-full px-4 py-2 text-sm font-medium transition-colors",children:[e.jsx(ni,{className:"h-4 w-4",style:{color:"hsl(var(--hub-glow))"}}),"Import",e.jsx(Tl,{className:"h-3.5 w-3.5 opacity-70"})]})}),e.jsxs(Eu,{align:"end",children:[e.jsxs(ja,{onClick:i,children:[e.jsx(ni,{className:"mr-2 h-4 w-4"})," Import CSV"]}),e.jsxs(ja,{onClick:l,children:[e.jsx(_1,{className:"mr-2 h-4 w-4"})," Import from Phone"]}),e.jsxs(ja,{onClick:o,children:[e.jsx(Ap,{className:"mr-2 h-4 w-4"})," Manage Tags"]})]})]}),f]})]}),e.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-center",children:[e.jsxs("div",{className:"relative flex-1 min-w-0",children:[e.jsx(Kr,{className:"pointer-events-none absolute left-3.5 top-1/2 h-4 w-4 -translate-y-1/2 opacity-70"}),e.jsx(pe,{value:n,onChange:x=>r(x.target.value),placeholder:"Search by name, email, phone, or notes...",className:"h-11 rounded-xl border-transparent bg-white/10 pl-10 text-current placeholder:text-current/50 focus-visible:ring-2 focus-visible:ring-white/30"})]}),g&&e.jsx("div",{className:"hub-glass inline-flex shrink-0 items-center gap-1 rounded-xl p-1",children:[{key:"my",label:"Mine",icon:Zn,show:!0},{key:"team",label:"Team",icon:Zn,show:!!h},{key:"lead-pond",label:"Pond",icon:b1,show:!!m}].filter(x=>x.show).map(x=>e.jsxs("button",{onClick:()=>u==null?void 0:u(x.key),className:Pt("inline-flex items-center gap-1.5 rounded-lg px-3 py-1.5 text-xs font-semibold transition-colors",d===x.key?"bg-background text-foreground shadow-sm":"hub-ink-muted"),children:[e.jsx(x.icon,{className:"h-3.5 w-3.5"}),x.label]},x.key))})]}),e.jsx("div",{className:"grid grid-cols-2 gap-2 sm:grid-cols-4",children:t.map(x=>e.jsxs("button",{onClick:x.onClick,className:Pt("hub-glass rounded-xl px-3 py-2.5 text-left transition-colors",x.active&&"ring-2 ring-white/40"),children:[e.jsx("span",{className:"text-xl font-bold",children:x.value}),e.jsx("p",{className:"mt-0.5 text-[11px] hub-ink-muted",children:x.label})]},x.label))})]})})}function T$n({rows:s=8,columns:t=5}){return e.jsx(e.Fragment,{children:Array.from({length:s}).map((n,r)=>e.jsxs("tr",{className:"border-b border-border/60",children:[e.jsx("td",{className:"px-4 py-4",children:e.jsx(yn,{className:"h-4 w-4 rounded"})}),e.jsx("td",{className:"px-4 py-4",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(yn,{className:"h-9 w-9 rounded-full"}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(yn,{className:"h-3.5 w-36"}),e.jsx(yn,{className:"h-3 w-24"})]})]})}),Array.from({length:Math.max(t-2,1)}).map((a,i)=>e.jsx("td",{className:"px-4 py-4",children:e.jsx(yn,{className:"h-3.5 w-20"})},i))]},r))})}function M$n({count:s=6}){return e.jsx("div",{className:"space-y-3",children:Array.from({length:s}).map((t,n)=>e.jsxs("div",{className:"rounded-xl border border-border bg-card p-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(yn,{className:"h-10 w-10 rounded-full"}),e.jsxs("div",{className:"flex-1 space-y-2",children:[e.jsx(yn,{className:"h-4 w-2/5"}),e.jsx(yn,{className:"h-3 w-3/5"})]})]}),e.jsxs("div",{className:"mt-3 flex gap-2",children:[e.jsx(yn,{className:"h-6 w-16 rounded-full"}),e.jsx(yn,{className:"h-6 w-20 rounded-full"})]})]},n))})}function wCt({filtered:s,onAdd:t,onImport:n,onClearFilters:r}){return e.jsxs("div",{className:"flex flex-col items-center justify-center gap-3 px-6 py-14 text-center",children:[e.jsx("div",{className:"flex h-12 w-12 items-center justify-center rounded-2xl bg-primary/10 text-primary",children:e.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",className:"h-6 w-6",children:[e.jsx("path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2",strokeLinecap:"round"}),e.jsx("circle",{cx:"9",cy:"7",r:"4"}),e.jsx("path",{d:"M19 8v6M22 11h-6",strokeLinecap:"round"})]})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-base font-semibold text-foreground",children:s?"No contacts match these filters":"Your database is empty"}),e.jsx("p",{className:"mt-1 text-sm text-muted-foreground",children:s?"Try a different search or clear the filters to see everyone.":"Add someone manually or import your existing contacts to get started."})]}),e.jsx("div",{className:"mt-1 flex flex-wrap items-center justify-center gap-2",children:s?e.jsx("button",{onClick:r,className:"rounded-full bg-primary px-4 py-2 text-sm font-semibold text-primary-foreground",children:"Clear filters"}):e.jsxs(e.Fragment,{children:[e.jsx("button",{onClick:t,className:"rounded-full bg-primary px-4 py-2 text-sm font-semibold text-primary-foreground",children:"Add contact"}),e.jsx("button",{onClick:n,className:"rounded-full border border-border px-4 py-2 text-sm font-medium text-foreground hover:bg-accent",children:"Import contacts"})]})})]})}function tJt(s){const t=r=>!(typeof r=="string"?r.trim():r),n=!t(s==null?void 0:s.address)||!t(s==null?void 0:s.city)||!t(s==null?void 0:s.state)||!t(s==null?void 0:s.zip);return t(s==null?void 0:s.email)||t(s==null?void 0:s.phone)||t(s==null?void 0:s.birthday)||!n}function jCt(s){if(!s)return null;const t=Ch(s);if(!t)return null;const n=new Date;n.setHours(0,0,0,0);const r=new Date(n.getFullYear(),t.getMonth(),t.getDate());return rs.relationshipScore.status==="at-risk"},{key:"never-contacted",title:"Never Contacted",icon:sc,color:"text-violet-600 dark:text-violet-400",match:s=>s.relationshipScore.daysSinceTouch===null},{key:"stale-90",title:"Stale 90+ Days",icon:da,color:"text-amber-600 dark:text-amber-400",match:s=>{const t=s.relationshipScore.daysSinceTouch;return t!==null&&t>90}},{key:"cooling",title:"Cooling Off",icon:t2,color:"text-cyan-600 dark:text-cyan-400",match:s=>s.relationshipScore.status==="cooling"},{key:"birthdays-soon",title:"Birthdays Soon",icon:Fg,color:"text-pink-600 dark:text-pink-400",match:(s,t)=>t.daysToBirthday!==null&&t.daysToBirthday<=30},{key:"anniversary-soon",title:"Home Anniversary",icon:va,color:"text-emerald-600 dark:text-emerald-400",match:(s,t)=>t.daysToAnniv!==null&&t.daysToAnniv<=30},{key:"has-deal",title:"Active Deal",icon:Sx,color:"text-teal-700 dark:text-teal-400",match:(s,t)=>t.hasDeal},{key:"website-active",title:"Active on Site",icon:dl,color:"text-indigo-600 dark:text-indigo-400",match:()=>!1},{key:"vips",title:"VIPs",icon:Nn,color:"text-amber-600 dark:text-amber-300",match:s=>s.relationshipScore.score>=80},{key:"active-buyers",title:"Active Buyers",icon:Kr,color:"text-sky-600 dark:text-sky-400",match:(s,t)=>t.hasCriteria},{key:"missing-criteria",title:"No Home Search",icon:rV,color:"text-orange-600 dark:text-orange-400",match:(s,t)=>!t.hasCriteria},{key:"missing-info",title:"Missing Info",icon:wl,color:"text-slate-600 dark:text-slate-400",match:s=>tJt(s)}];function P$n({contacts:s,contactDealsMap:t,websiteActiveIds:n,criteriaContactIds:r,totalCount:a,activeKey:i,onSelectSegment:l,currentFilters:o,currentSortBy:c,activeViewId:d,onApplyView:u,onClearAll:h}){const{data:m}=ait(),f=KXt(),g=YXt(),[x,y]=j.useState(!1),[v,b]=j.useState(""),w=j.useMemo(()=>{const I={"needs-attention":0,cooling:0,"never-contacted":0,"stale-90":0,"birthdays-soon":0,"anniversary-soon":0,"has-deal":0,"website-active":n.size,"missing-info":0,vips:0,"active-buyers":0,"missing-criteria":0};if(!s)return I;for(const P of s){const R={hasDeal:!!(t&&t[P.id]),daysToBirthday:jCt(P.birthday),daysToAnniv:jCt(P.home_anniversary),hasCriteria:!!(r!=null&&r.has(P.id))};for(const D of NCt)D.key!=="website-active"&&D.match(P,R)&&I[D.key]++}return I},[s,t,n,r]),S=!!o.search||!!o.type&&o.type!=="all"||!!o.status&&o.status!=="all"||!!o.behavior&&Object.values(o.behavior).some(I=>I!==void 0&&I!==!1),C=async()=>{v.trim()&&(await f.mutateAsync({name:v.trim(),filters:o,sort_by:c}),b(""),y(!1))},E="inline-flex items-center gap-1.5 h-8 shrink-0 rounded-full border px-3 text-xs font-medium transition-colors whitespace-nowrap";return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-2 overflow-x-auto pb-1 -mx-1 px-1 [scrollbar-width:none] [&::-webkit-scrollbar]:hidden",children:[e.jsxs("button",{type:"button",onClick:h,className:Pt(E,!i&&!d?"bg-primary text-primary-foreground border-primary":"bg-card hover:bg-accent border-border"),children:[e.jsx(Zn,{className:"h-3.5 w-3.5"}),"All Contacts",e.jsx("span",{className:"tabular-nums opacity-70",children:a.toLocaleString()})]}),m==null?void 0:m.map(I=>{const P=d===I.id;return e.jsxs("div",{className:Pt(E,"group pr-1",P?"bg-primary text-primary-foreground border-primary":"bg-card hover:bg-accent border-border"),children:[e.jsx("button",{type:"button",onClick:()=>u(I.id,I.filters,I.sort_by),children:I.name}),e.jsx("button",{type:"button","aria-label":`Delete view ${I.name}`,className:"h-5 w-5 rounded-full flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity hover:bg-foreground/10",onClick:()=>{g.mutate(I.id),P&&h()},children:e.jsx(gr,{className:"h-3 w-3"})})]},I.id)}),e.jsx("div",{className:"h-5 w-px bg-border shrink-0"}),NCt.map(I=>{const P=I.icon,R=w[I.key],D=i===I.key;return e.jsxs("button",{type:"button",onClick:()=>l(D?null:I.key),"aria-pressed":D,className:Pt(E,D?"bg-primary text-primary-foreground border-primary":"bg-card hover:bg-accent border-border",!D&&R===0&&"opacity-55"),children:[e.jsx(P,{className:Pt("h-3.5 w-3.5",D?"":I.color)}),I.title,e.jsx("span",{className:"tabular-nums opacity-70",children:R.toLocaleString()})]},I.key)}),e.jsxs($,{variant:"ghost",size:"sm",className:"h-8 gap-1.5 text-xs shrink-0",disabled:!S,onClick:()=>y(!0),children:[e.jsx(qI,{className:"h-3.5 w-3.5"}),"Save view"]})]}),e.jsx(zs,{open:x,onOpenChange:y,children:e.jsxs(Os,{className:"sm:max-w-sm",children:[e.jsxs(Us,{children:[e.jsx(Bs,{children:"Save this view"}),e.jsx(Ir,{children:"Your current search, filters, and sorting are saved as a one-click chip."})]}),e.jsx(pe,{autoFocus:!0,placeholder:"e.g. Past clients cooling off",value:v,onChange:I=>b(I.target.value),onKeyDown:I=>I.key==="Enter"&&C()}),e.jsxs(Ar,{children:[e.jsx($,{variant:"outline",onClick:()=>y(!1),children:"Cancel"}),e.jsx($,{onClick:C,disabled:!v.trim()||f.isPending,children:"Save view"})]})]})})]})}const kCt=[{key:"relationship",label:"Relationship"},{key:"buyerCriteria",label:"Looking For"},{key:"stage",label:"Stage"},{key:"leadSource",label:"Lead Source"},{key:"tags",label:"Tags"},{key:"lastTouch",label:"Last Touch"},{key:"nextAction",label:"Next Action"},{key:"dealValue",label:"Pipeline Value"},{key:"email",label:"Email"},{key:"phone",label:"Phone"},{key:"address",label:"Address"},{key:"birthday",label:"Birthday"}],e$e={relationship:!0,buyerCriteria:!0,stage:!0,leadSource:!0,tags:!0,lastTouch:!0,nextAction:!0,dealValue:!0,email:!1,phone:!1,address:!1,birthday:!1},SCt="innercircle:contact-columns:v1";function I$n(){const[s,t]=j.useState(()=>{try{const a=localStorage.getItem(SCt);if(a)return{...e$e,...JSON.parse(a)}}catch{}return e$e});j.useEffect(()=>{try{localStorage.setItem(SCt,JSON.stringify(s))}catch{}},[s]);const n=j.useCallback(a=>{t(i=>({...i,[a]:!i[a]}))},[]),r=j.useCallback(()=>t(e$e),[]);return{columns:s,toggle:n,reset:r}}function L$n({columns:s,onToggle:t,onReset:n}){const r=kCt.filter(a=>s[a.key]).length;return e.jsxs(Yd,{children:[e.jsx(Zd,{asChild:!0,children:e.jsxs($,{variant:"outline",size:"sm",className:"h-8 gap-1.5 rounded-lg text-xs",children:[e.jsx(oP,{className:"h-3.5 w-3.5"}),"Columns",e.jsx(Be,{variant:"secondary",className:"h-5 px-1.5 text-[10px]",children:r})]})}),e.jsxs(Bd,{align:"end",className:"w-56 p-2",children:[e.jsxs("div",{className:"flex items-center justify-between px-1 pb-2",children:[e.jsx("p",{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:"Show columns"}),e.jsxs("button",{type:"button",onClick:n,className:"inline-flex items-center gap-1 text-[11px] text-muted-foreground hover:text-foreground",children:[e.jsx(Ex,{className:"h-3 w-3"}),"Reset"]})]}),e.jsx("div",{className:"max-h-[320px] overflow-y-auto space-y-0.5",children:kCt.map(a=>e.jsxs("button",{type:"button",onClick:()=>t(a.key),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(ai,{checked:s[a.key],className:"pointer-events-none"}),e.jsx("span",{className:"flex-1 text-left",children:a.label})]},a.key))}),e.jsx("p",{className:"px-2 pt-2 text-[11px] text-muted-foreground",children:"Name and actions are always shown."})]})]})}const RV=1e3;function sJt(){const s=Sa();return tt({queryKey:["contact-criteria-map",s],enabled:!!s,staleTime:60*1e3,queryFn:async()=>{const t=[];for(let r=0;;r+=RV){const{data:a,error:i}=await q.from("contact_property_alerts").select("id, contact_id, is_active, min_price, max_price, min_beds, min_baths, min_sqft, max_sqft, cities, zip_codes, property_types, frequency, last_sent_at").eq("owner_user_id",s).range(r,r+RV-1);if(i)throw i;const l=a||[];if(t.push(...l),l.length{const n=new Date(Date.now()-6048e5).toISOString(),r=[];for(let o=0;;o+=RV){const{data:c,error:d}=await q.from("contact_property_alerts").select("id, contact_id").eq("owner_user_id",t).range(o,o+RV-1);if(d)throw d;const u=c||[];if(r.push(...u),u.length[o.id,o.contact_id])),i={},l=r.map(o=>o.id);for(let o=0;o{const i={contact_id:n,owner_user_id:s,is_active:a.is_active??!0,min_price:a.min_price||null,max_price:a.max_price||null,min_beds:a.min_beds||null,min_baths:a.min_baths||null,min_sqft:a.min_sqft||null,max_sqft:a.max_sqft||null,cities:a.cities||[],zip_codes:a.zip_codes||[],property_types:a.property_types||[],frequency:a.frequency||"daily"};if(r){const{error:l}=await q.from("contact_property_alerts").update(i).eq("id",r);if(l)throw l}else{const{error:l}=await q.from("contact_property_alerts").insert(i);if(l)throw l}},onSuccess:(n,r)=>{t.invalidateQueries({queryKey:["contact-criteria-map"]}),t.invalidateQueries({queryKey:["contact-property-alert",r.contactId]})}})}function F$n(){const s=Vt();return ft({mutationFn:async({id:t})=>{const{error:n}=await q.from("contact_property_alerts").delete().eq("id",t);if(n)throw n},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["contact-criteria-map"]}),n.contactId&&s.invalidateQueries({queryKey:["contact-property-alert",n.contactId]})}})}const mq=s=>String(s??"").trim().toLowerCase();function O$n(s,t){const n=mq(s).replace(/[\s_-]+/g,""),r=mq(t).replace(/[\s_-]+/g,"");return!n||!r?!1:n===r||n.includes(r)||r.includes(n)}function z$n(s,t){var m,f,g;const n=[],r=[],a=t.price??null,i=t.bedrooms??null,l=t.bathrooms??null,o=t.sqft??null;if((((m=s.cities)==null?void 0:m.length)||0)>0||(((f=s.zip_codes)==null?void 0:f.length)||0)>0){const x=!!t.city&&(s.cities||[]).some(v=>mq(v)===mq(t.city)),y=!!t.zip&&(s.zip_codes||[]).some(v=>mq(v)===mq(t.zip));x?n.push(`Wants ${t.city}`):y?n.push(`Wants ${t.zip}`):(t.city||t.zip)&&r.push(`Looking in ${[...s.cities||[],...s.zip_codes||[]].slice(0,3).join(", ")}`)}a!==null&&(s.min_price&&as.max_price?r.push(`Over their $${Math.round(s.max_price/1e3)}k budget`):(s.min_price||s.max_price)&&n.push("In their price range")),s.min_beds&&(i!==null&&i0&&(s.min_sqft&&os.max_sqft?r.push("Over their max sqft"):(s.min_sqft||s.max_sqft)&&n.push("Size fits")),(((g=s.property_types)==null?void 0:g.length)||0)>0&&t.propertyType&&(s.property_types.some(y=>O$n(y,t.propertyType))?n.push(String(t.propertyType).replace(/_/g," ")):r.push(`Wants ${s.property_types.slice(0,2).join(" / ")}`));const d=r.length===0&&n.length>0,u=n.length+r.length,h=u===0?0:Math.round(n.length/u*100);return{matches:d,score:h,reasons:n,misses:r}}function B$n(s,t,n,r={}){const a=[];for(const i of s){const l=t[i.id];if(!l)continue;const o=z$n(l,n);(o.matches||r.includeNearMatches&&o.misses.length===1&&o.score>=50)&&a.push({contact:i,criteria:l,result:o})}return a.sort((i,l)=>l.result.score-i.result.score||i.result.misses.length-l.result.misses.length)}const hue=s=>s>=1e3?`$${Math.round(s/1e3)}k`:`$${s}`;function nJt(s){var t,n,r;return s?!!(s.min_price||s.max_price||s.min_beds||s.min_baths||s.min_sqft||s.max_sqft||(t=s.cities)!=null&&t.length||(n=s.zip_codes)!=null&&n.length||(r=s.property_types)!=null&&r.length):!1}function $$n(s){var r;if(!s)return"";const t=[];s.min_price&&s.max_price?t.push(`${hue(s.min_price)}–${hue(s.max_price)}`):s.max_price?t.push(`up to ${hue(s.max_price)}`):s.min_price&&t.push(`${hue(s.min_price)}+`),s.min_beds&&t.push(`${s.min_beds}+ bd`),s.min_baths&&t.push(`${s.min_baths}+ ba`),s.min_sqft&&t.push(`${s.min_sqft.toLocaleString()}+ sqft`);const n=[...s.cities||[],...s.zip_codes||[]];return n.length&&t.push(n.length<=2?n.join(", "):`${n.slice(0,2).join(", ")} +${n.length-2}`),!n.length&&((r=s.property_types)!=null&&r.length)&&t.push(s.property_types.slice(0,2).join(", ")),t.join(" · ")}function CCt({criteria:s,onEdit:t,showAlertState:n,matchCount:r,className:a,compact:i}){const l=$$n(s);return nJt(s)?e.jsxs("button",{type:"button",onClick:t?c=>{c.stopPropagation(),t()}:void 0,className:Pt("group/crit inline-flex max-w-full items-center gap-1.5 rounded-md px-1.5 py-0.5 text-left",t&&"hover:bg-accent transition-colors",a),title:l,children:[n?s!=null&&s.is_active?e.jsx(qy,{className:"h-3.5 w-3.5 shrink-0 text-emerald-600 dark:text-emerald-400"}):e.jsx(XS,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}):e.jsx(Kr,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}),e.jsx("span",{className:Pt("truncate",i?"text-[11px]":"text-xs","text-foreground/80"),children:l}),!!r&&r>0&&e.jsxs("span",{className:"shrink-0 rounded-full bg-primary/10 px-1.5 text-[10px] font-semibold text-primary tabular-nums",children:[r," new"]})]}):t?e.jsxs("button",{type:"button",onClick:c=>{c.stopPropagation(),t()},className:Pt("inline-flex items-center gap-1 whitespace-nowrap rounded-full border border-dashed border-primary/40 px-2 py-0.5","text-[11px] text-muted-foreground hover:bg-primary/5 hover:text-primary transition-colors",a),children:[e.jsx(dn,{className:"h-3 w-3"}),"Add home search"]}):e.jsx("span",{className:"text-sm text-muted-foreground",children:"—"})}const rJt=["Single Family","Condo","Townhouse","Multi-Family","Land","Commercial"];function U$n(){const s=Sa();return tt({queryKey:["agent-lead-site-config",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await q.from("lead_sites").select("theme_config, mls_market_area").eq("agent_id",s).eq("is_active",!0).order("created_at",{ascending:!0}).limit(1).maybeSingle();if(n||!t)return{cities:[],zipCodes:[]};const r=t.theme_config||{},a=Array.isArray(r.searchCities)?r.searchCities:[];t.mls_market_area&&!a.includes(t.mls_market_area)&&a.unshift(t.mls_market_area);const i=Array.isArray(r.searchZipCodes)?r.searchZipCodes:[];return{cities:a,zipCodes:i}}})}function ACt({value:s,onChange:t,onAdd:n,suggestions:r,placeholder:a,icon:i}){const[l,o]=j.useState(!1),c=j.useRef(null),d=j.useRef(null);j.useEffect(()=>{const h=m=>{d.current&&!d.current.contains(m.target)&&o(!1)};return document.addEventListener("mousedown",h),()=>document.removeEventListener("mousedown",h)},[]);const u=r.filter(h=>h.toLowerCase().includes(s.trim().toLowerCase()));return e.jsxs("div",{className:"relative",ref:d,children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsx("div",{className:"flex-1",children:e.jsx(pe,{value:s,onChange:h=>{t(h.target.value),o(!0)},onFocus:()=>o(!0),onKeyDown:h=>{h.key==="Enter"&&(h.preventDefault(),n(s),o(!1))},placeholder:a})}),e.jsx($,{type:"button",variant:"outline",size:"sm",onClick:()=>n(s),children:e.jsx(dn,{className:"h-4 w-4"})})]}),l&&u.length>0&&e.jsx("div",{ref:c,className:"absolute z-50 mt-1 w-full max-h-60 overflow-y-auto rounded-md border bg-popover shadow-md",children:u.map(h=>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:()=>{n(h),o(!1)},children:[i||e.jsx(ci,{className:"h-3 w-3 text-muted-foreground flex-shrink-0"}),h]},h))})]})}function aJt({value:s,onChange:t,hasIdx:n=!0,idxNote:r}){const[a,i]=j.useState(""),[l,o]=j.useState(""),{data:c}=U$n(),d=((c==null?void 0:c.cities)||[]).filter(g=>{var x;return!((x=s.cities)!=null&&x.includes(g))}),u=((c==null?void 0:c.zipCodes)||[]).filter(g=>{var x;return!((x=s.zip_codes)!=null&&x.includes(g))}),h=g=>{var y;const x=g.trim();x&&!((y=s.cities)!=null&&y.includes(x))&&t(v=>({...v,cities:[...v.cities||[],x]})),i("")},m=g=>{var y;const x=g.trim();x&&!((y=s.zip_codes)!=null&&y.includes(x))&&t(v=>({...v,zip_codes:[...v.zip_codes||[],x]})),o("")},f=g=>{t(x=>{const y=x.property_types||[];return{...x,property_types:y.includes(g)?y.filter(v=>v!==g):[...y,g]}})};return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsxs(ee,{className:"flex items-center gap-1 mb-1.5",children:[e.jsx(ru,{className:"h-3.5 w-3.5"})," Price Range"]}),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsx(pe,{type:"number",placeholder:"Min price",value:s.min_price??"",onChange:g=>t(x=>({...x,min_price:g.target.value?Number(g.target.value):null}))}),e.jsx(pe,{type:"number",placeholder:"Max price",value:s.max_price??"",onChange:g=>t(x=>({...x,max_price:g.target.value?Number(g.target.value):null}))})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsxs(ee,{className:"flex items-center gap-1 mb-1.5",children:[e.jsx(T4,{className:"h-3.5 w-3.5"})," Min Beds"]}),e.jsxs(ms,{value:s.min_beds?String(s.min_beds):"any",onValueChange:g=>t(x=>({...x,min_beds:g==="any"?null:Number(g)})),children:[e.jsx(us,{children:e.jsx(fs,{placeholder:"Any"})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"any",children:"Any"}),[1,2,3,4,5].map(g=>e.jsxs(Ge,{value:String(g),children:[g,"+"]},g))]})]})]}),e.jsxs("div",{children:[e.jsxs(ee,{className:"flex items-center gap-1 mb-1.5",children:[e.jsx(T0,{className:"h-3.5 w-3.5"})," Min Baths"]}),e.jsxs(ms,{value:s.min_baths?String(s.min_baths):"any",onValueChange:g=>t(x=>({...x,min_baths:g==="any"?null:Number(g)})),children:[e.jsx(us,{children:e.jsx(fs,{placeholder:"Any"})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"any",children:"Any"}),[1,1.5,2,2.5,3,4].map(g=>e.jsxs(Ge,{value:String(g),children:[g,"+"]},g))]})]})]})]}),e.jsxs("div",{children:[e.jsxs(ee,{className:"flex items-center gap-1 mb-1.5",children:[e.jsx(R4,{className:"h-3.5 w-3.5"})," Square Feet"]}),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsx(pe,{type:"number",placeholder:"Min sqft",value:s.min_sqft??"",onChange:g=>t(x=>({...x,min_sqft:g.target.value?Number(g.target.value):null}))}),e.jsx(pe,{type:"number",placeholder:"Max sqft",value:s.max_sqft??"",onChange:g=>t(x=>({...x,max_sqft:g.target.value?Number(g.target.value):null}))})]})]}),e.jsxs("div",{children:[e.jsxs(ee,{className:"flex items-center gap-1 mb-1.5",children:[e.jsx(ci,{className:"h-3.5 w-3.5"})," Cities"]}),e.jsx(ACt,{value:a,onChange:i,onAdd:h,suggestions:d,placeholder:"Type a city and press Enter..."}),s.cities&&s.cities.length>0&&e.jsx("div",{className:"flex flex-wrap gap-1 mt-2",children:s.cities.map(g=>e.jsxs(Be,{variant:"secondary",className:"gap-1",children:[g,e.jsx("button",{type:"button",onClick:()=>t(x=>{var y;return{...x,cities:(y=x.cities)==null?void 0:y.filter(v=>v!==g)}}),children:e.jsx(gr,{className:"h-3 w-3"})})]},g))})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"mb-1.5",children:"Zip Codes"}),e.jsx(ACt,{value:l,onChange:o,onAdd:m,suggestions:u,placeholder:"Type a zip code and press Enter...",icon:e.jsx("span",{className:"text-xs text-muted-foreground font-mono",children:"#"})}),s.zip_codes&&s.zip_codes.length>0&&e.jsx("div",{className:"flex flex-wrap gap-1 mt-2",children:s.zip_codes.map(g=>e.jsxs(Be,{variant:"secondary",className:"gap-1",children:[g,e.jsx("button",{type:"button",onClick:()=>t(x=>{var y;return{...x,zip_codes:(y=x.zip_codes)==null?void 0:y.filter(v=>v!==g)}}),children:e.jsx(gr,{className:"h-3 w-3"})})]},g))})]}),e.jsxs("div",{children:[e.jsxs(ee,{className:"flex items-center gap-1 mb-1.5",children:[e.jsx(va,{className:"h-3.5 w-3.5"})," Property Types"]}),e.jsx("div",{className:"flex flex-wrap gap-1.5",children:rJt.map(g=>{var x;return e.jsx(Be,{variant:(x=s.property_types)!=null&&x.includes(g)?"default":"outline",className:"cursor-pointer",onClick:()=>f(g),children:g},g)})})]}),n?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(ee,{children:"Email new matching listings"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Automatic alerts from your MLS feed"})]}),e.jsx(Sn,{checked:s.is_active??!0,onCheckedChange:g=>t(x=>({...x,is_active:g}))})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"mb-1.5",children:"Frequency"}),e.jsxs(ms,{value:s.frequency||"daily",onValueChange:g=>t(x=>({...x,frequency:g})),children:[e.jsx(us,{children:e.jsx(fs,{})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"daily",children:"Daily"}),e.jsx(Ge,{value:"weekly",children:"Weekly"})]})]})]})]}):e.jsxs("div",{className:"rounded-lg border border-dashed bg-muted/40 p-3 space-y-1.5",children:[e.jsxs("p",{className:"text-xs text-muted-foreground flex items-start gap-2",children:[e.jsx(eC,{className:"h-3.5 w-3.5 mt-0.5 shrink-0"}),e.jsx("span",{children:"Saved here so you can match listings to this contact any time. Automatic new-listing emails need an IDX website."})]}),r]})]})}function q$n({open:s,onOpenChange:t,contactId:n,contactName:r,existing:a}){const{hasIdx:i}=ng(),l=D$n(),o=F$n(),[c,d]=j.useState({});j.useEffect(()=>{s&&d({is_active:(a==null?void 0:a.is_active)??!0,min_price:(a==null?void 0:a.min_price)??null,max_price:(a==null?void 0:a.max_price)??null,min_beds:(a==null?void 0:a.min_beds)??null,min_baths:(a==null?void 0:a.min_baths)??null,min_sqft:(a==null?void 0:a.min_sqft)??null,max_sqft:(a==null?void 0:a.max_sqft)??null,cities:(a==null?void 0:a.cities)??[],zip_codes:(a==null?void 0:a.zip_codes)??[],property_types:(a==null?void 0:a.property_types)??[],frequency:(a==null?void 0:a.frequency)??"daily"})},[s,a]);const u=async()=>{try{await l.mutateAsync({contactId:n,existingId:(a==null?void 0:a.id)??null,values:c}),re.success(`Home search saved for ${r}`),t(!1)}catch(m){re.error((m==null?void 0:m.message)||"Could not save home search")}},h=async()=>{if(a!=null&&a.id)try{await o.mutateAsync({id:a.id,contactId:n}),re.success("Home search removed"),t(!1)}catch(m){re.error((m==null?void 0:m.message)||"Could not remove home search")}};return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Os,{className:"max-w-lg max-h-[90vh] overflow-y-auto",children:[e.jsxs(Us,{children:[e.jsxs(Bs,{children:["Home search for ",r]}),e.jsx(Ir,{children:"What are they looking for? This shows on your contacts dashboard so you can match new listings to them."})]}),e.jsx(aJt,{value:c,onChange:d,hasIdx:i,idxNote:e.jsx($,{asChild:!0,variant:"link",size:"sm",className:"h-auto p-0 text-xs",children:e.jsx(wr,{to:"/mission-control/website",children:"Explore IDX websites"})})}),e.jsxs(Ar,{className:"gap-2 sm:gap-2",children:[(a==null?void 0:a.id)&&e.jsxs($,{variant:"ghost",onClick:h,disabled:o.isPending,className:"text-destructive hover:text-destructive mr-auto",children:[o.isPending?e.jsx(kt,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(Wn,{className:"h-4 w-4 mr-1"}),"Remove"]}),e.jsx($,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsxs($,{onClick:u,disabled:l.isPending,children:[l.isPending?e.jsx(kt,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(tl,{className:"h-4 w-4 mr-1"}),"Save"]})]})]})})}const Rp=s=>s.replace(/&/g,"&").replace(//g,">").replace(/"/g,"""),V$n=s=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(s);function H$n(s,t){const n=s.address||[s.city,s.state].filter(Boolean).join(", ")||"a home";return t?`${t}, this one looks like your kind of home — ${n}`:`Thought of you: ${n}`}function G$n(s){const t=[];return s.bedrooms&&t.push(`${s.bedrooms} bedrooms`),s.bathrooms&&t.push(`${s.bathrooms} baths`),s.city&&t.push(`in ${s.city}`),`Hi {{first_name}}, This just came across my desk and it lines up with what you told me you're looking for${t.length?` — ${t.join(", ")}`:""}. I wanted you to see it before it gets busy. Want me to set up a private showing?`}function W$n(s,t,n){const r=(s.photos||[]).filter(Boolean),a=r[0]||"",i=r[1]||"",l=r[2]||"",o=s.publicUrl||"",c=[s.city,s.state].filter(Boolean).join(", ")+(s.zip?` ${s.zip}`:""),d=s.address||c||"A home worth seeing",u=s.price?V$n(Number(s.price)):"",h=(n==null?void 0:n.name)||"",m=(n==null?void 0:n.title)||"Real Estate Agent",f=(n==null?void 0:n.phone)||"",g=(n==null?void 0:n.email)||"",x=(n==null?void 0:n.avatar_url)||"",y=(n==null?void 0:n.brokerage_name)||"",v=h?h.split(" ").map(S=>S[0]).slice(0,2).join("").toUpperCase():"A",b=(S,C,E=!1)=>`
${Rp(S)}
${Rp(C)}
`,w=[];return s.bedrooms&&w.push(b(String(s.bedrooms),"Beds")),s.bathrooms&&w.push(b(String(s.bathrooms),"Baths")),s.sqft&&w.push(b(Number(s.sqft).toLocaleString(),"Sq Ft")),s.propertyType&&w.push(b(s.propertyType,"Type")),` ${Rp(d)}
${Rp([u,d].filter(Boolean).join(" · "))}
${a?` `:""} ${w.length?` `:""} ${t?` `:""} ${o?` `:""} ${i||l?` `:""} ${h?` `:""}
 
${o?``:""} ${Rp(d)} ${o?"":""}
${u?``:""}
A home matched to your search${Rp(u)}

${Rp(d)}

${s.address&&c?`

${Rp(c)}

`:""}
${w.join("")}

${Rp(t)}

View this home  →

See all the photos and details

${i?``:""} ${l?``:""}
${x?`${Rp(h)}`:`
${Rp(v)}
`}
${Rp(h)}
${Rp(m)}${y?` · ${Rp(y)}`:""}
${f?`${Rp(f)}`:""} ${f&&g?'  ·  ':""} ${g?`${Rp(g)}`:""}

You're receiving this because you asked to hear about homes that fit your search.

`}function K$n({open:s,onOpenChange:t,property:n,recipient:r}){const{user:a}=vs(),i=Sa(),{isGmailConnected:l,gmailEmail:o}=yy(),{isReady:c,settings:d}=u6(),[u,h]=j.useState(""),[m,f]=j.useState(""),[g,x]=j.useState(!1),[y,v]=j.useState(!1),{data:b}=tt({queryKey:["match-email-agent",i],enabled:!!i&&s,queryFn:async()=>{const{data:R}=await q.from("profiles").select("name, title, email, phone, avatar_url, brokerage_name").eq("id",i).maybeSingle();return R??null}});j.useEffect(()=>{!s||!r||(h(H$n(n,r.first_name)),f(G$n(n)),x(!1))},[s,r==null?void 0:r.id]);const w=j.useMemo(()=>m.replace(/\{\{first_name\}\}/gi,(r==null?void 0:r.first_name)||"there"),[m,r==null?void 0:r.first_name]),S=j.useMemo(()=>W$n(n,w,b??null),[n,w,b]),C=l||c,E=!!(r!=null&&r.email&&u.trim()&&C&&!y),I=async()=>{if(!(!E||!(r!=null&&r.email))){v(!0);try{if(l){const{data:R,error:D}=await q.functions.invoke("gmail-send",{body:{to:r.email,subject:u.trim(),body:S,contactId:r.id}});if(D)throw D;if(!(R!=null&&R.success))throw new Error((R==null?void 0:R.error)||"Failed to send")}else{const R=(d==null?void 0:d.display_name)||"ReLevelUp",D=`${R.toLowerCase().replace(/[^a-z]/g,".")}@send.relevelup.com`,{data:O,error:U}=await q.functions.invoke("ses-send-campaign",{body:{action:"test_send",to:r.email,from_email:`${R} <${D}>`,subject:u.trim(),body_html:S,reply_to:(d==null?void 0:d.reply_to_email)||(b==null?void 0:b.email)||void 0,contact_id:r.id}});if(U)throw U;if(!(O!=null&&O.success))throw new Error((O==null?void 0:O.error)||"Failed to send")}if(a)try{await q.from("bulk_email_sends").insert({user_id:a.id,contact_id:r.id,contact_email:r.email,subject:u.trim(),source:"listing_match"})}catch{}re.success(`Sent to ${r.first_name}`),t(!1)}catch(R){re.error((R==null?void 0:R.message)||"Could not send the email")}finally{v(!1)}}},P=r?`${r.first_name} ${r.last_name||""}`.trim():"";return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Os,{className:"w-[95vw] max-w-[95vw] sm:max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsxs(Us,{children:[e.jsxs(Bs,{className:"flex items-center gap-2",children:[e.jsx(mn,{className:"h-4 w-4 text-primary"}),"Email this home to ",P||"your buyer"]}),e.jsx(Ir,{children:C?e.jsxs(e.Fragment,{children:["Sending from ",l?`your Gmail (${o})`:"your mass email sender","."]}):"Connect Gmail or set up mass email first."})]}),!C&&e.jsxs("div",{className:"flex items-start gap-2 rounded-lg border border-amber-500/40 bg-amber-500/10 p-3 text-sm",children:[e.jsx(ll,{className:"h-4 w-4 mt-0.5 text-amber-600 shrink-0"}),e.jsx("span",{children:"You don't have an email sender connected yet. Connect Gmail in Settings, or finish mass email setup, and this will send straight from you."})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{className:"text-xs",children:"To"}),e.jsxs("div",{className:"flex items-center gap-2 rounded-md border px-3 py-2 text-sm",children:[e.jsx("span",{className:"font-medium",children:P}),e.jsx(Be,{variant:"secondary",className:"font-normal",children:r==null?void 0:r.email})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{htmlFor:"match-subject",className:"text-xs",children:"Subject"}),e.jsx(pe,{id:"match-subject",value:u,onChange:R=>h(R.target.value)})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{htmlFor:"match-message",className:"text-xs",children:"Your note"}),e.jsx(Rs,{id:"match-message",rows:6,value:m,onChange:R=>f(R.target.value)}),e.jsxs("p",{className:"text-[11px] text-muted-foreground",children:["Use ","{{first_name}}"," anywhere and we'll swap in their name."]})]}),e.jsxs($,{variant:"outline",size:"sm",onClick:()=>x(R=>!R),children:[g?e.jsx($g,{className:"h-4 w-4 mr-2"}):e.jsx(Ca,{className:"h-4 w-4 mr-2"}),g?"Hide preview":"Preview email"]}),g&&e.jsx(uo,{className:"h-[380px] rounded-lg border",children:e.jsx("iframe",{title:"Email preview",srcDoc:S,className:"w-full h-[1200px] border-0"})})]}),e.jsxs(Ar,{children:[e.jsx($,{variant:"ghost",onClick:()=>t(!1),children:"Cancel"}),e.jsxs($,{onClick:I,disabled:!E,children:[y?e.jsx(kt,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Yr,{className:"h-4 w-4 mr-2"}),"Send email"]})]})]})})}const Y$n={city:"",state:"",zip:"",price:null,bedrooms:null,bathrooms:null,sqft:null,propertyType:"",address:""};function Z$n({open:s,onOpenChange:t,contacts:n}){const r=Qn(),{data:a}=sJt(),{data:i}=Qst(),[l,o]=j.useState(Y$n),[c,d]=j.useState(!0),[u,h]=j.useState(""),[m,f]=j.useState(null),g=S=>o(C=>({...C,...S})),x=S=>{h(S);const C=(i||[]).find(E=>E.id===S);C&&g({address:C.property_address||"",city:C.city||"",state:C.state||"",zip:"",price:C.price??null,bedrooms:C.bedrooms??null,bathrooms:C.bathrooms??null,sqft:C.square_footage??null,propertyType:C.property_type||""})},y=!!(l.city||l.zip||l.price),v=j.useMemo(()=>{const S=i==null?void 0:i.find(I=>I.id===u),C=Array.isArray(S==null?void 0:S.photos)?S.photos.slice().sort((I,P)=>!!P.is_primary!=!!I.is_primary?P.is_primary?1:-1:(I.sort_order??0)-(P.sort_order??0)).map(I=>I.photo_url).filter(Boolean):[],E=S&&S.is_public&&S.is_approved?`${window.location.origin}/public/listing/${S.slug||S.id}`:null;return{address:l.address||void 0,city:l.city||void 0,state:l.state||void 0,zip:l.zip||void 0,price:l.price,bedrooms:l.bedrooms,bathrooms:l.bathrooms,sqft:l.sqft,propertyType:l.propertyType||void 0,photos:C,publicUrl:E}},[i,u,l]),b=j.useMemo(()=>!a||!y?[]:B$n(n,a,l,{includeNearMatches:c}),[n,a,l,c,y]),w=j.useMemo(()=>Object.keys(a||{}).length,[a]);return e.jsxs(Wy,{open:s,onOpenChange:t,children:[e.jsxs(py,{side:"right",className:"w-full sm:max-w-xl overflow-y-auto",children:[e.jsxs(D0,{children:[e.jsxs(F0,{className:"flex items-center gap-2",children:[e.jsx(Zn,{className:"h-4 w-4 text-primary"}),"Who wants this house?"]}),e.jsx($B,{children:"Enter a property — or pick one of your listings — and we'll show the contacts whose saved home search fits. No IDX needed."})]}),e.jsxs("div",{className:"mt-4 space-y-4",children:[e.jsxs(ha,{defaultValue:i!=null&&i.length?"listing":"manual",children:[e.jsxs(ma,{className:"grid w-full grid-cols-2",children:[e.jsx(Zt,{value:"listing",children:"My listings"}),e.jsx(Zt,{value:"manual",children:"Enter a property"})]}),e.jsx(Xt,{value:"listing",className:"pt-3",children:i!=null&&i.length?e.jsxs(ms,{value:u,onValueChange:x,children:[e.jsx(us,{children:e.jsx(fs,{placeholder:"Choose a listing…"})}),e.jsx(hs,{children:i.map(S=>e.jsxs(Ge,{value:S.id,children:[[S.property_address,S.city].filter(Boolean).join(", "),S.price?` — ${Qm(Number(S.price))}`:""]},S.id))})]}):e.jsx("p",{className:"text-sm text-muted-foreground",children:`You don't have any Listing Exchange listings yet. Use "Enter a property" instead.`})}),e.jsx(Xt,{value:"manual",className:"pt-3",children:e.jsx("p",{className:"text-xs text-muted-foreground mb-3",children:"Saw something in your MLS? Type the basics here."})})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"col-span-2",children:[e.jsx(ee,{className:"mb-1.5 text-xs",children:"Address (optional)"}),e.jsx(pe,{value:l.address||"",onChange:S=>g({address:S.target.value}),placeholder:"123 Main St"})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"mb-1.5 text-xs",children:"City"}),e.jsx(pe,{value:l.city||"",onChange:S=>g({city:S.target.value}),placeholder:"Cypress"})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"mb-1.5 text-xs",children:"Zip"}),e.jsx(pe,{value:l.zip||"",onChange:S=>g({zip:S.target.value}),placeholder:"90630"})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"mb-1.5 text-xs",children:"Price"}),e.jsx(pe,{type:"number",value:l.price??"",onChange:S=>g({price:S.target.value?Number(S.target.value):null}),placeholder:"750000"})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"mb-1.5 text-xs",children:"Sqft"}),e.jsx(pe,{type:"number",value:l.sqft??"",onChange:S=>g({sqft:S.target.value?Number(S.target.value):null}),placeholder:"1800"})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"mb-1.5 text-xs",children:"Beds"}),e.jsx(pe,{type:"number",value:l.bedrooms??"",onChange:S=>g({bedrooms:S.target.value?Number(S.target.value):null}),placeholder:"3"})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"mb-1.5 text-xs",children:"Baths"}),e.jsx(pe,{type:"number",step:"0.5",value:l.bathrooms??"",onChange:S=>g({bathrooms:S.target.value?Number(S.target.value):null}),placeholder:"2"})]}),e.jsxs("div",{className:"col-span-2",children:[e.jsx(ee,{className:"mb-1.5 text-xs",children:"Property type"}),e.jsxs(ms,{value:l.propertyType||"any",onValueChange:S=>g({propertyType:S==="any"?"":S}),children:[e.jsx(us,{children:e.jsx(fs,{})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"any",children:"Any"}),rJt.map(S=>e.jsx(Ge,{value:S,children:S},S))]})]})]})]}),e.jsxs("div",{className:"flex items-center justify-between border-t pt-3",children:[e.jsxs("div",{className:"text-xs text-muted-foreground",children:[w," ",w===1?"contact has":"contacts have"," a saved home search"]}),e.jsx($,{variant:c?"secondary":"outline",size:"sm",className:"h-7 text-xs",onClick:()=>d(S=>!S),children:c?"Including close matches":"Exact matches only"})]}),y?b.length===0?e.jsxs("div",{className:"rounded-lg border border-dashed p-6 text-center text-sm text-muted-foreground",children:[e.jsx(va,{className:"h-5 w-5 mx-auto mb-2 opacity-60"}),"No contacts match this property yet. Add home searches to your buyers so matches show up here."]}):e.jsxs("div",{className:"space-y-2",children:[e.jsxs("p",{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:[b.length," ",b.length===1?"match":"matches"]}),b.map(({contact:S,result:C})=>{const E=`${S.first_name} ${S.last_name||""}`.trim();return e.jsxs("div",{className:"flex items-start gap-3 rounded-lg border p-3",children:[e.jsx(Sit,{firstName:S.first_name,lastName:S.last_name||void 0,avatarUrl:S.avatar_url||void 0,email:S.email||void 0,size:36}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("button",{type:"button",className:"font-medium text-sm hover:underline",onClick:()=>r(`/mission-control/contacts/${S.id}`),children:E}),e.jsxs("div",{className:"mt-1 flex flex-wrap gap-1",children:[C.reasons.slice(0,4).map(I=>e.jsx(Be,{variant:"secondary",className:"text-[10px]",children:I},I)),C.misses.map(I=>e.jsx(Be,{variant:"outline",className:"text-[10px] text-muted-foreground",children:I},I))]})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[S.email&&e.jsx($,{variant:"ghost",size:"icon",className:"h-8 w-8",title:`Email ${E}`,onClick:()=>f(S),children:e.jsx(mn,{className:"h-4 w-4"})}),S.phone&&e.jsx($,{variant:"ghost",size:"icon",className:"h-8 w-8",title:`Text ${E}`,asChild:!0,children:e.jsx("a",{href:`sms:${S.phone}`,children:e.jsx(eo,{className:"h-4 w-4"})})})]})]},S.id)})]}):e.jsxs("div",{className:"rounded-lg border border-dashed p-6 text-center text-sm text-muted-foreground",children:[e.jsx(Kr,{className:"h-5 w-5 mx-auto mb-2 opacity-60"}),"Add a city, zip, or price to see matches."]})]})]}),e.jsx(K$n,{open:!!m,onOpenChange:S=>!S&&f(null),property:v,recipient:m})]})}function X$n(){var Xc;const s=Qn(),[t,n]=gc(),{user:r}=vs(),a=$K(),i=Vt(),{columns:l,toggle:o,reset:c}=I$n(),d=t.get("type"),u=t.get("filter")??t.get("status"),h=t.get("new")==="true",{contactsWithScores:m,isLoading:f}=cie(),{activeContactIds:g,hasLeadSite:x}=c9n(),{data:y}=p$n(),{data:v}=Yw(),{data:b}=g$n(),{data:w}=a9(),{data:S}=Lie(),{hasIdx:C}=ng(),{data:E}=sJt(),{data:I}=R$n(!!C),P=j.useMemo(()=>new Set(Object.entries(E||{}).filter(([,_s])=>nJt(_s)).map(([_s])=>_s)),[E]),[R,D]=j.useState(null),[O,U]=j.useState(!1),[W,V]=j.useState(new Set),[G,Y]=j.useState("any"),X=j6e(),ae=int(),ie=zUt(),ne=OUt(),[te,J]=j.useState(""),[ce,_e]=j.useState(!1),[he,ue]=j.useState(d||"all"),[ve,Ee]=j.useState(u||"all"),[Se,Le]=j.useState("date-added"),[Fe,ke]=j.useState("all"),[Ve,je]=j.useState({}),Ae=j.useMemo(()=>Object.values(Ve).filter(_s=>_s!==void 0&&_s!==!1&&_s!=="").length,[Ve]),[Ce,qe]=j.useState(!1),[ze,$e]=j.useState([]),{neighborhoods:ct}=kit(),Xe=j.useMemo(()=>XQt(ct,ze),[ct,ze]),{behaviorMap:it,hasLeadSite:at}=d$n(),[Ke,nt]=j.useState(h),[xt,rt]=j.useState(null),[Yt,qt]=j.useState(!1),[ts,ys]=j.useState(!1),[Bt,Ft]=j.useState(null),[rs,St]=j.useState(""),[Xs,vt]=j.useState(new Set),[gs,Ss]=j.useState(!1),[Is,Ys]=j.useState(!1),cs=Math.max(1,parseInt(t.get("page")||"1",10)||1),[js,kn]=j.useState(cs),Ws=j.useCallback(_s=>{kn(Xa=>{const No=typeof _s=="function"?_s(Xa):_s;return n(Ba=>{const io=new URLSearchParams(Ba);return No<=1?io.delete("page"):io.set("page",String(No)),io},{replace:!0}),No})},[]),[On,ds]=j.useState(50),[gn,As]=j.useState("my"),[hr,Er]=j.useState(!1),[qn,hn]=j.useState(!1),{data:Fn}=Hw(),{addToLeadPond:vn}=qWt(Fn==null?void 0:Fn.teamId),{ponds:xs}=Vrt(Fn==null?void 0:Fn.teamId),Lr=xs.filter(_s=>_s.has_access),[Or,ca]=j.useState(null),[Jn,Sr]=j.useState(""),Un=!!((Xc=Fn==null?void 0:Fn.team)!=null&&Xc.lead_pond_enabled&&(Fn!=null&&Fn.teamId)),ur=!!(Fn!=null&&Fn.teamId),[Pa,ii]=j.useState([]),[$i,Rn]=j.useState(!1),xa=_s=>{ii([_s]),Rn(!0)},Ya=_s=>{ii(_s),Rn(!0)},ho=(_s,Xa)=>{Fn!=null&&Fn.teamId&&_s.forEach(No=>{vn.mutate({contact_id:No,team_id:Fn.teamId,pond_id:Xa||null})})},Pc=_s=>{var Xa;if(Fn!=null&&Fn.teamId){if(Lr.length>1){Sr(Lr[0].id),ca(_s);return}ho(_s,((Xa=Lr[0])==null?void 0:Xa.id)||null)}},$d=_s=>Pc([_s]),Nl=_s=>Pc(_s),Ho=j.useCallback(_s=>{Ys(!1),vt(Xa=>{const No=new Set(Xa);return No.has(_s)?No.delete(_s):No.add(_s),No})},[]);j.useEffect(()=>{if(!(r!=null&&r.id))return;const _s=q.channel(`innercircle_contacts_inserts_${r.id}`).on("postgres_changes",{event:"INSERT",schema:"public",table:"innercircle_contacts",filter:`owner_user_id=eq.${r.id}`},()=>{i.invalidateQueries({queryKey:["innercircle-contacts"]}),i.invalidateQueries({queryKey:["innercircle-contact-counts"]})}).subscribe();return()=>{q.removeChannel(_s)}},[i,r==null?void 0:r.id]),j.useEffect(()=>{u&&Ee(u)},[u]);const[ti,Xr]=j.useState({first_name:"",last_name:"",email:"",phone:"",address:"",city:"",state:"",zip_code:"",address2_label:"",address2:"",address2_city:"",address2_state:"",address2_zip:"",mail_to_secondary:!1,birthday:"",home_anniversary:"",spouse_name:"",spouse_email:"",lead_source_id:"",notes:"",tagIds:[]}),[Eo,Ph]=j.useState(!1);j.useEffect(()=>{h&&nt(!0)},[h]),j.useEffect(()=>{var _s;xt&&Xr({first_name:xt.first_name||"",last_name:xt.last_name||"",email:xt.email||"",phone:xt.phone||"",address:xt.address||"",city:xt.city||"",state:xt.state||"",zip_code:xt.zip_code||"",address2_label:xt.address2_label||"",address2:xt.address2||"",address2_city:xt.address2_city||"",address2_state:xt.address2_state||"",address2_zip:xt.address2_zip||"",mail_to_secondary:!!xt.mail_to_secondary,birthday:xt.birthday||"",home_anniversary:xt.home_anniversary||"",spouse_name:xt.spouse_name||"",spouse_email:xt.spouse_email||"",lead_source_id:xt.lead_source_id||"",notes:xt.notes||"",tagIds:((_s=xt.tags)==null?void 0:_s.map(Xa=>Xa.relationship_type_id))||[]})},[xt]);const ih=j.useMemo(()=>{const _s=new Set;return w==null||w.forEach(Xa=>{(Xa.name==="Recruits"||Xa.name==="Brokerage Agents")&&_s.add(Xa.id)}),_s},[w]),ao=j.useMemo(()=>Array.from(W).some(_s=>ih.has(_s)),[W,ih]),ta=j.useMemo(()=>{const _s={};return(m||[]).forEach(Xa=>{_s[Xa.id]=`${Xa.first_name||""} ${Xa.last_name||""}`.trim()}),_s},[m]),xc=j.useMemo(()=>{const _s=new Set;return(m||[]).forEach(Xa=>{var Ba;const No=(((Ba=Xa.lead_source_ref)==null?void 0:Ba.name)||Xa.lead_source||"").trim();No&&_s.add(No)}),Array.from(_s).sort((Xa,No)=>Xa.localeCompare(No))},[m]),fl=j.useMemo(()=>{if(!m)return[];let _s=m.filter(Ba=>{var Xd,Wh,df,Yy,oh,xh,gt,We,ut,jt,Rt;const io=Ba.synced_source;if(!ao&&(io==="recruit"||io==="brokerage_agent")||Xe&&!Xe.has(Ba.id))return!1;const qi=te===""||`${Ba.first_name} ${Ba.last_name}`.toLowerCase().includes(te.toLowerCase())||((Xd=Ba.email)==null?void 0:Xd.toLowerCase().includes(te.toLowerCase()))||((Wh=Ba.phone)==null?void 0:Wh.includes(te))||((df=Ba.city)==null?void 0:df.toLowerCase().includes(te.toLowerCase()))||((Yy=Ba.state)==null?void 0:Yy.toLowerCase().includes(te.toLowerCase()))||((oh=Ba.address)==null?void 0:oh.toLowerCase().includes(te.toLowerCase()))||((xh=Ba.zip_code)==null?void 0:xh.toLowerCase().includes(te.toLowerCase())),dm=he==="all"||((gt=Ba.tags)==null?void 0:gt.some(zt=>zt.relationship_type_id===he)),Zo=W.size===0||(()=>{const zt=(S==null?void 0:S.filter(Wt=>Wt.contact_id===Ba.id).map(Wt=>Wt.tag_id))||[];return G==="any"?zt.some(Wt=>W.has(Wt)):Array.from(W).every(Wt=>zt.includes(Wt))})(),vo=!!((We=Ba.address)!=null&&We.trim()||(ut=Ba.city)!=null&&ut.trim()||(jt=Ba.state)!=null&&jt.trim()||(Rt=Ba.zip_code)!=null&&Rt.trim()),Zg=Fe==="all"||Fe==="has-address"&&vo||Fe==="no-address"&&!vo,Ol=Ba,zl=Ve,vy=(zl.hasEmail===void 0||!!Ol.email===zl.hasEmail)&&(zl.hasPhone===void 0||!!Ol.phone===zl.hasPhone)&&(zl.hasAddress===void 0||vo===zl.hasAddress)&&(zl.hasBirthday===void 0||!!Ol.birthday===zl.hasBirthday)&&(zl.hasSpouse===void 0||!!(Ol.spouse_name||Ol.spouse_contact_id||Ol.spouse_email)===zl.hasSpouse)&&(zl.hasCompany===void 0||!!(Ol.company_name||Ol.job_title)===zl.hasCompany)&&(zl.hasNotes===void 0||!!(Ol.notes&&Ol.notes.trim())===zl.hasNotes)&&(!zl.city||(Ol.city||"").toLowerCase().includes(zl.city.toLowerCase()))&&(!zl.state||(Ol.state||"").toLowerCase().includes(zl.state.toLowerCase()))&&(!zl.zip||((Ol.zip||"")+(Ol.zip_code||"")).toLowerCase().includes(zl.zip.toLowerCase()))&&(!zl.birthdayMonth||!!Ol.birthday&&Ch(Ol.birthday).getMonth()+1===zl.birthdayMonth)&&(!zl.anniversaryMonth||((zl.anniversaryField||"home_anniversary")==="home_anniversary"?!!Ol.home_anniversary&&Ch(Ol.home_anniversary).getMonth()+1===zl.anniversaryMonth:!!Ol.wedding_anniversary&&Ch(Ol.wedding_anniversary).getMonth()+1===zl.anniversaryMonth))&&(!zl.dateAddedFrom||!!Ol.created_at&&Ol.created_at.slice(0,10)>=zl.dateAddedFrom)&&(!zl.dateAddedTo||!!Ol.created_at&&Ol.created_at.slice(0,10)<=zl.dateAddedTo)&&(()=>{var ws;const zt=zl.leadSourceId;if(!zt)return!0;const Wt=(((ws=Ol.lead_source_ref)==null?void 0:ws.name)||Ol.lead_source||"").trim();return zt==="none"?!Wt&&!Ol.lead_source_id:zt.startsWith("name:")?Wt.toLowerCase()===zt.slice(5).toLowerCase():Ol.lead_source_id===zt})();return qi&&dm&&Zo&&Zg&&vy});ve==="not-touched-90"?_s=_s.filter(Ba=>{const io=Ba.relationshipScore.daysSinceTouch;return io===null||io>90}):ve==="at-risk"?_s=_s.filter(Ba=>Ba.relationshipScore.status==="at-risk"):ve==="cooling"?_s=_s.filter(Ba=>Ba.relationshipScore.status==="cooling"):ve==="warm"?_s=_s.filter(Ba=>Ba.relationshipScore.status==="warm"):ve==="has-deal"?_s=_s.filter(Ba=>b&&b[Ba.id]):ve==="no-deal"?_s=_s.filter(Ba=>!b||!b[Ba.id]):ve==="open-house"?_s=_s.filter(Ba=>{var ko;return(((ko=Ba.lead_source_ref)==null?void 0:ko.name)||Ba.lead_source)==="Open House"}):ve==="website-active"?_s=_s.filter(Ba=>g.has(Ba.id)):ve==="never-contacted"?_s=_s.filter(Ba=>Ba.relationshipScore.daysSinceTouch===null):ve==="vips"?_s=_s.filter(Ba=>Ba.relationshipScore.score>=80):ve==="missing-info"?_s=_s.filter(Ba=>tJt(Ba)):ve==="birthdays-soon"?_s=_s.filter(Ba=>{const io=UO(Ba.birthday);return io!==null&&io<=30}):ve==="anniversary-soon"?_s=_s.filter(Ba=>{const io=UO(Ba.home_anniversary);return io!==null&&io<=30}):ve==="in-drip"?_s=_s.filter(Ba=>((y==null?void 0:y[Ba.id])??0)>0):ve==="not-in-drip"?_s=_s.filter(Ba=>((y==null?void 0:y[Ba.id])??0)===0):ve==="active-buyers"?_s=_s.filter(Ba=>P.has(Ba.id)):ve==="missing-criteria"&&(_s=_s.filter(Ba=>!P.has(Ba.id)));const Xa=Ve;if(Xa.lastActive||Xa.registered||Xa.viewedListing||Xa.savedProperty||Xa.hasSavedSearch||Xa.requestedShowing||Xa.requestedValuation||Xa.websiteActiveOnly){const Ba=Date.now(),io={today:24*60*60*1e3,"7d":7*24*60*60*1e3,"30d":30*24*60*60*1e3,"90d":90*24*60*60*1e3};_s=_s.filter(ko=>{const qi=it.get(ko.id);if(Xa.lastActive==="never"){if(qi!=null&&qi.lastActiveAt)return!1}else if(Xa.lastActive){const dm=Ba-io[Xa.lastActive];if(!(qi!=null&&qi.lastActiveAt)||new Date(qi.lastActiveAt).getTime()0)||Xa.viewedListing==="multiple7d"&&!(qi&&qi.propertyViewCount7d>=3)||Xa.savedProperty&&!(qi&&qi.savedListingCount>0)||Xa.hasSavedSearch&&!(qi&&qi.activeSavedSearchCount>0)||Xa.requestedShowing&&!(qi&&qi.showingRequests>0)||Xa.requestedValuation&&!(qi&&qi.valuationRequests>0)||Xa.websiteActiveOnly&&!g.has(ko.id))})}return _s=[..._s].sort((Ba,io)=>{switch(Se){case"important-dates":{const ko=UO(Ba.birthday),qi=UO(io.birthday),dm=UO(Ba.home_anniversary),Zo=UO(io.home_anniversary),vo=[ko,dm].filter(Ol=>Ol!==null).sort((Ol,zl)=>(Ol??1/0)-(zl??1/0))[0]??1/0,Zg=[qi,Zo].filter(Ol=>Ol!==null).sort((Ol,zl)=>(Ol??1/0)-(zl??1/0))[0]??1/0;return vo-Zg}case"last-touched":{const ko=Ba.relationshipScore.lastTouchDate,qi=io.relationshipScore.lastTouchDate;return!ko&&!qi?0:ko?qi?new Date(ko).getTime()-new Date(qi).getTime():1:-1}case"next-touch":{const ko=Ba.relationshipScore.daysSinceTouch,qi=io.relationshipScore.daysSinceTouch;return ko===null&&qi===null?0:ko===null?-1:qi===null?1:qi-ko}case"score":return Ba.relationshipScore.score-io.relationshipScore.score;case"date-added":{const ko=Ba.created_at,qi=io.created_at;return!ko&&!qi?0:ko?qi?new Date(qi).getTime()-new Date(ko).getTime():-1:1}case"last-name":{const ko=(Ba.last_name||"").toLowerCase(),qi=(io.last_name||"").toLowerCase();if(ko!==qi)return ko.localeCompare(qi);const dm=(Ba.first_name||"").toLowerCase(),Zo=(io.first_name||"").toLowerCase();return dm.localeCompare(Zo)}case"name":default:{const ko=`${Ba.first_name||""} ${Ba.last_name||""}`.toLowerCase(),qi=`${io.first_name||""} ${io.last_name||""}`.toLowerCase();return ko.localeCompare(qi)}}}),_s},[m,te,he,W,G,ve,Se,b,S,g,y,Fe,Ve,it,ao,P,Xe]),Co=fl.length,pu=Math.max(1,Math.ceil(Co/On)),nc=Math.min(js,pu),ad=j.useMemo(()=>{const _s=(nc-1)*On;return fl.slice(_s,_s+On)},[fl,nc,On]),zr=j.useMemo(()=>{const _s=(m||[]).length;return{total:_s,label:_s===0?"Build your database — add or import your first contacts.":`${_s.toLocaleString()} ${_s===1?"person":"people"} in your database`}},[m]),Hi=j.useMemo(()=>{const _s=m||[],Xa=_s.filter(ko=>{var qi;return((qi=ko.relationshipScore)==null?void 0:qi.status)==="at-risk"}).length,No=_s.filter(ko=>{var dm;const qi=(dm=ko.relationshipScore)==null?void 0:dm.daysSinceTouch;return typeof qi=="number"&&qi<=7}).length,Ba=new Date().getMonth()+1,io=_s.filter(ko=>ko.birthday?String(ko.birthday).split(/[-/T]/).map(Number)[1]===Ba:!1).length;return[{label:"Total contacts",value:zr.total.toLocaleString(),onClick:()=>{Ee("all"),Ws(1)},active:ve==="all"},{label:"Needs attention",value:Xa,onClick:()=>{Ee("at-risk"),Ws(1)},active:ve==="at-risk"},{label:"Touched this week",value:No,onClick:()=>{Ee("warm"),Ws(1)},active:ve==="warm"},{label:"Birthdays this month",value:io,onClick:()=>{Ee("birthdays-soon"),Ws(1)},active:ve==="birthdays-soon"}]},[m,zr.total,ve,Ws]),Bc=j.useCallback(_s=>{const Xa=new URLSearchParams;te&&Xa.set("search",te),he!=="all"&&Xa.set("type",he),ve!=="all"&&Xa.set("filter",ve),W.size>0&&(Xa.set("tags",Array.from(W).join(",")),Xa.set("tagMode",G));const No=Xa.toString();s(`/mission-control/contacts/${_s}${No?`?${No}`:""}`)},[s,te,he,ve,W,G]),$c=j.useRef(!1);j.useEffect(()=>{if(!$c.current){$c.current=!0;return}Ws(1)},[te,he,W,G,ve,Se,Fe,Ve]);const yc=j.useCallback(()=>{Ys(!1),vt(_s=>_s.size>0?new Set:new Set(ad.map(Xa=>Xa.id)))},[ad]),Ul=j.useCallback(()=>{Ys(!0),vt(new Set(fl.map(_s=>_s.id)))},[fl]),[rg,Lx]=j.useState(null),Yo=j.useCallback((_s,Xa)=>{J(_s.search||""),ue(_s.type||"all"),Ee(_s.status||"all"),je(_s.behavior||{}),Le(Xa||"name")},[]),Ic=()=>{Xr({first_name:"",last_name:"",email:"",phone:"",address:"",city:"",state:"",zip_code:"",address2_label:"",address2:"",address2_city:"",address2_state:"",address2_zip:"",mail_to_secondary:!1,birthday:"",home_anniversary:"",spouse_name:"",spouse_email:"",lead_source_id:"",notes:"",tagIds:[]})},Ih=async _s=>{_s.preventDefault();const Xa={...ti,lead_source_id:ti.lead_source_id||null};xt?(await ae.mutateAsync({id:xt.id,...Xa}),rt(null)):(await X.mutateAsync(Xa),nt(!1)),Ic()},cm=async _s=>{await fo("Are you sure you want to delete this contact?")&&await ie.mutateAsync(_s)};return e.jsx(Vs,{title:"Contacts",description:"Manage your InnerCircle contacts",children:e.jsxs("div",{className:"space-y-6 overflow-x-hidden",children:[e.jsx(E$n,{totalLabel:zr.label,stats:Hi,search:te,onSearchChange:J,onAddContact:()=>nt(!0),onImportCsv:()=>qt(!0),onImportPhone:()=>ys(!0),onManageTags:()=>Er(!0),onHeatMap:()=>_e(!0),viewMode:gn,onViewModeChange:_s=>As(_s),showTeamTab:!!Fn&&(Fn.team.contact_visibility==="full_team"||Fn.team.contact_visibility==="leader_only"&&Fn.role==="team_leader"),showLeadPondTab:!!(Fn!=null&&Fn.team.lead_pond_enabled),extraActions:e.jsxs(e.Fragment,{children:[e.jsxs($,{variant:"secondary",size:"sm",className:"h-9 gap-1.5",onClick:()=>s("/mission-control/sphere-map"),children:[e.jsx(zJ,{className:"h-4 w-4"}),"Map view"]}),e.jsxs($,{variant:"secondary",size:"sm",className:"h-9 gap-1.5",onClick:()=>U(!0),children:[e.jsx(Kr,{className:"h-4 w-4"}),"Match a listing"]}),e.jsxs($,{variant:"secondary",size:"sm",className:"h-9 gap-1.5",onClick:()=>Ss(!0),children:[e.jsx(Xz,{className:"h-4 w-4"}),"Find duplicates"]}),e.jsx(WBn,{})]})}),e.jsx(e9n,{open:gs,onOpenChange:Ss}),e.jsx(Z$n,{open:O,onOpenChange:U,contacts:m||[]}),R&&e.jsx(q$n,{open:!!R,onOpenChange:_s=>{_s||D(null)},contactId:R.id,contactName:R.name,existing:(E==null?void 0:E[R.id])??null}),gn==="team"?e.jsx(dRe,{}):gn==="lead-pond"&&Fn?e.jsx(uRe,{teamId:Fn.teamId}):e.jsxs(e.Fragment,{children:[e.jsx(P$n,{contacts:m,contactDealsMap:b,websiteActiveIds:g,criteriaContactIds:P,totalCount:(m||[]).length,activeViewId:rg,currentFilters:{search:te,type:he,status:ve,behavior:Ve},currentSortBy:Se,onApplyView:(_s,Xa,No)=>{Lx(_s),Yo(Xa,No),Ws(1)},onClearAll:()=>{Lx(null),Yo({search:"",type:"all",status:"all",behavior:{}},"name"),Ws(1)},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","active-buyers":"active-buyers","missing-criteria":"missing-criteria"}[ve]??null,onSelectSegment:_s=>{const No=_s?{"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","active-buyers":"active-buyers","missing-criteria":"missing-criteria"}[_s]:"all";Ee(No),Ws(1)}}),e.jsxs(Ne,{className:"overflow-hidden",children:[e.jsxs("div",{className:"p-3 sm:p-4 bg-background",children:[e.jsx("div",{className:"sm:hidden space-y-3",children:e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs(Wy,{children:[e.jsx(Fae,{asChild:!0,children:e.jsxs($,{variant:"outline",className:"h-10 flex-1 rounded-xl relative gap-2","aria-label":"Filters",children:[e.jsx(JI,{className:"h-4 w-4"}),"Filters & Views",(()=>{const _s=(he!=="all"?1:0)+(ve!=="all"?1:0)+(Fe!=="all"?1:0)+W.size+Ae;return _s>0?e.jsx("span",{className:"absolute -top-1 -right-1 h-4 min-w-[16px] px-1 rounded-full bg-primary text-primary-foreground text-[10px] font-bold flex items-center justify-center",children:_s}):null})()]})}),e.jsxs(py,{side:"bottom",className:"h-[85vh] rounded-t-2xl overflow-y-auto",children:[e.jsx(D0,{className:"text-left",children:e.jsx(F0,{children:"Filters & Views"})}),e.jsxs("div",{className:"space-y-5 py-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Type"}),e.jsxs(ms,{value:he,onValueChange:ue,children:[e.jsx(us,{className:"h-11 rounded-xl bg-muted/40",children:e.jsx(fs,{placeholder:"All Types"})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"all",children:"All Types"}),v==null?void 0:v.filter(_s=>_s.active).map(_s=>e.jsx(Ge,{value:_s.id,children:_s.name},_s.id))]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Status"}),e.jsxs(ms,{value:ve,onValueChange:Ee,children:[e.jsx(us,{className:"h-11 rounded-xl bg-muted/40",children:e.jsx(fs,{placeholder:"All Status"})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"all",children:"All Status"}),e.jsx(Ge,{value:"warm",children:"🟢 Warm"}),e.jsx(Ge,{value:"cooling",children:"🟡 Cooling Off"}),e.jsx(Ge,{value:"at-risk",children:"🔴 At Risk"}),e.jsx(Ge,{value:"has-deal",children:"📋 Has Deal"}),e.jsx(Ge,{value:"no-deal",children:"📭 No Deal"}),e.jsx(Ge,{value:"open-house",children:"🏠 Open House"}),x&&e.jsx(Ge,{value:"website-active",children:"🌐 Website Active"}),e.jsx(Ge,{value:"in-drip",children:"🌱 In Drip Campaign"}),e.jsx(Ge,{value:"not-in-drip",children:"🚫 Not In Drip"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Address"}),e.jsxs(ms,{value:Fe,onValueChange:_s=>ke(_s),children:[e.jsx(us,{className:"h-11 rounded-xl bg-muted/40",children:e.jsx(fs,{placeholder:"All Addresses"})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"all",children:"All Addresses"}),e.jsx(Ge,{value:"has-address",children:"Has Address"}),e.jsx(Ge,{value:"no-address",children:"No Address"})]})]})]}),w&&w.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(ee,{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Tags"}),e.jsxs("div",{className:"flex items-center gap-1 bg-muted rounded-md p-0.5",children:[e.jsx("button",{onClick:()=>Y("any"),className:`px-2 py-0.5 rounded text-xs font-medium ${G==="any"?"bg-background shadow-sm":"text-muted-foreground"}`,children:"Any"}),e.jsx("button",{onClick:()=>Y("all"),className:`px-2 py-0.5 rounded text-xs font-medium ${G==="all"?"bg-background shadow-sm":"text-muted-foreground"}`,children:"All"})]})]}),e.jsx("div",{className:"flex flex-wrap gap-2",children:w.map(_s=>{const Xa=W.has(_s.id);return e.jsxs("button",{onClick:()=>{V(No=>{const Ba=new Set(No);return Ba.has(_s.id)?Ba.delete(_s.id):Ba.add(_s.id),Ba})},className:`inline-flex items-center gap-1.5 px-3 py-1.5 rounded-full text-xs border transition-colors ${Xa?"bg-primary text-primary-foreground border-primary":"bg-background border-border"}`,children:[e.jsx("span",{className:"h-2 w-2 rounded-full",style:{backgroundColor:_s.color}}),_s.name]},_s.id)})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Sort by"}),e.jsxs(ms,{value:Se,onValueChange:Le,children:[e.jsx(us,{className:"h-11 rounded-xl bg-muted/40",children:e.jsx(fs,{})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"name",children:"Name (A-Z)"}),e.jsx(Ge,{value:"last-name",children:"Last Name (A-Z)"}),e.jsx(Ge,{value:"important-dates",children:"Important Dates"}),e.jsx(Ge,{value:"last-touched",children:"Last Touched"}),e.jsx(Ge,{value:"next-touch",children:"Next Touch Due"}),e.jsx(Ge,{value:"score",children:"Relationship Score"}),e.jsx(Ge,{value:"date-added",children:"Date Added"})]})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-2 pt-2",children:[e.jsxs($,{variant:"outline",className:"h-11 rounded-xl gap-1.5",onClick:()=>qe(!0),children:[e.jsx(Nn,{className:"h-4 w-4"})," Advanced"]}),e.jsxs($,{variant:"outline",className:"h-11 rounded-xl gap-1.5",onClick:()=>Er(!0),children:[e.jsx(Ap,{className:"h-4 w-4"})," Manage Tags"]})]}),e.jsx("div",{children:e.jsx(mCt,{currentFilters:{search:te,type:he,status:ve,behavior:Ve},currentSortBy:Se,onApplySmartList:Yo})}),e.jsx($,{variant:"ghost",className:"w-full h-11 rounded-xl text-muted-foreground",onClick:()=>{ue("all"),Ee("all"),ke("all"),V(new Set),je({})},children:"Clear all filters"})]})]})]})})}),e.jsxs("div",{className:"hidden sm:flex items-center gap-3 flex-wrap",children:[e.jsxs("div",{className:"flex-1 min-w-[120px] text-sm text-muted-foreground",children:[Co.toLocaleString()," ",Co===1?"contact":"contacts"," shown"]}),e.jsxs(Yd,{children:[e.jsx(Zd,{asChild:!0,children:e.jsx($,{variant:"outline",size:"icon",className:"h-10 w-10 rounded-xl",title:"Sort contacts",children:e.jsx(p2,{className:"h-4 w-4"})})}),e.jsxs(Bd,{align:"end",className:"w-56 p-2",children:[e.jsx("div",{className:"text-xs font-semibold text-muted-foreground px-2 py-1.5",children:"Sort by"}),[{v:"name",l:"Name (A-Z)"},{v:"last-name",l:"Last Name (A-Z)"},{v:"important-dates",l:"Important Dates"},{v:"last-touched",l:"Last Touched"},{v:"next-touch",l:"Next Touch Due"},{v:"score",l:"Relationship Score"},{v:"date-added",l:"Date Added"}].map(_s=>e.jsx("button",{onClick:()=>Le(_s.v),className:`w-full text-left px-2 py-1.5 rounded-md text-sm hover:bg-accent transition-colors ${Se===_s.v?"bg-accent font-medium text-primary":""}`,children:_s.l},_s.v))]})]})]})]}),e.jsxs("div",{className:"hidden sm:flex px-3 sm:px-4 py-3 bg-muted/40 border-t flex-wrap items-center justify-between gap-3",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsxs(ms,{value:he,onValueChange:ue,children:[e.jsx(us,{className:"h-8 text-xs rounded-lg bg-background w-auto min-w-[130px] gap-2",children:e.jsx(fs,{placeholder:"All Types"})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"all",children:"All Types"}),v==null?void 0:v.filter(_s=>_s.active).map(_s=>e.jsx(Ge,{value:_s.id,children:_s.name},_s.id))]})]}),e.jsxs(ms,{value:ve,onValueChange:Ee,children:[e.jsx(us,{className:"h-8 text-xs rounded-lg bg-background w-auto min-w-[130px] gap-2",children:e.jsx(fs,{placeholder:"All Status"})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"all",children:"All Status"}),e.jsx(Ge,{value:"warm",children:"🟢 Warm"}),e.jsx(Ge,{value:"cooling",children:"🟡 Cooling Off"}),e.jsx(Ge,{value:"at-risk",children:"🔴 At Risk"}),e.jsx(Ge,{value:"has-deal",children:"📋 Has Deal"}),e.jsx(Ge,{value:"no-deal",children:"📭 No Deal"}),e.jsx(Ge,{value:"open-house",children:"🏠 Open House"}),x&&e.jsx(Ge,{value:"website-active",children:"🌐 Website Active"}),e.jsx(Ge,{value:"in-drip",children:"🌱 In Drip Campaign"}),e.jsx(Ge,{value:"not-in-drip",children:"🚫 Not In Drip"})]})]}),e.jsxs(ms,{value:Fe,onValueChange:_s=>ke(_s),children:[e.jsx(us,{className:"h-8 text-xs rounded-lg bg-background w-auto min-w-[130px] gap-2",children:e.jsx(fs,{placeholder:"All Addresses"})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"all",children:"All Addresses"}),e.jsx(Ge,{value:"has-address",children:"Has Address"}),e.jsx(Ge,{value:"no-address",children:"No Address"})]})]}),w&&w.length>0&&e.jsxs("div",{className:"inline-flex items-center bg-background border rounded-lg overflow-hidden h-8",children:[e.jsxs(Yd,{children:[e.jsx(Zd,{asChild:!0,children:e.jsxs("button",{className:"pl-2.5 pr-2 h-full text-xs font-medium text-muted-foreground hover:text-foreground inline-flex items-center gap-1.5",children:[e.jsx(Ap,{className:"h-3.5 w-3.5"}),W.size===0?"Filter by Tags":`${W.size} tag${W.size>1?"s":""}`]})}),e.jsx(Bd,{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:()=>Y("any"),className:`px-2 py-0.5 rounded text-xs font-medium transition-colors ${G==="any"?"bg-background text-foreground shadow-sm":"text-muted-foreground"}`,children:"Any"}),e.jsx("button",{onClick:()=>Y("all"),className:`px-2 py-0.5 rounded text-xs font-medium transition-colors ${G==="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:w.map(_s=>{const Xa=W.has(_s.id);return e.jsxs("button",{onClick:()=>{V(No=>{const Ba=new Set(No);return Ba.has(_s.id)?Ba.delete(_s.id):Ba.add(_s.id),Ba})},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(ai,{checked:Xa,className:"pointer-events-none"}),e.jsx("div",{className:"h-2.5 w-2.5 rounded-full shrink-0",style:{backgroundColor:_s.color}}),e.jsx("span",{className:"flex-1 text-left truncate",children:_s.name})]},_s.id)})}),W.size>0&&e.jsx($,{variant:"ghost",size:"sm",className:"w-full text-xs",onClick:()=>V(new Set),children:"Clear tags"})]})})]}),e.jsx("div",{className:"w-px h-4 bg-border"}),e.jsxs(Uu,{children:[e.jsx(qu,{asChild:!0,children:e.jsx("button",{className:"px-2 h-full text-muted-foreground hover:text-primary transition-colors",title:"Manage tags & lead sources",children:e.jsx(Sd,{className:"h-3.5 w-3.5"})})}),e.jsxs(Eu,{align:"end",children:[e.jsxs(ja,{onClick:()=>Er(!0),children:[e.jsx(Ap,{className:"h-4 w-4 mr-2"}),"Manage Tags"]}),e.jsxs(ja,{onClick:()=>hn(!0),children:[e.jsx(b1,{className:"h-4 w-4 mr-2"}),"Manage Lead Sources"]})]})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(mCt,{currentFilters:{search:te,type:he,status:ve,behavior:Ve},currentSortBy:Se,onApplySmartList:Yo}),e.jsx("div",{className:"h-5 w-px bg-border"}),e.jsx(c$n,{selected:ze,onChange:$e}),e.jsxs($,{variant:"outline",size:"sm",className:"gap-1.5 h-8 rounded-lg border-[#2a4c64]/20 text-[#2a4c64] hover:bg-[#2a4c64]/5 hover:text-[#2a4c64]",onClick:()=>qe(!0),children:[e.jsx(Nn,{className:"h-3.5 w-3.5"}),"Advanced Filters",Ae>0&&e.jsx(Be,{variant:"secondary",className:"h-5 px-1.5 text-[10px]",children:Ae})]}),e.jsx(L$n,{columns:l,onToggle:o,onReset:c})]})]}),Ae>0&&e.jsx("div",{className:"px-3 sm:px-4 py-3 border-t bg-background",children:e.jsx(Q9n,{behavior:Ve,onRemove:_s=>je(Xa=>{const No={...Xa};return delete No[_s],No}),onClearAll:()=>je({})})})]}),e.jsx(X9n,{open:Ce,onOpenChange:qe,hasLeadSite:at||x,behavior:Ve,onApply:je,selectedType:he,onSelectedTypeChange:ue,relationshipTypes:v,contactLeadSources:xc}),e.jsx(Y9n,{selectedIds:Xs,contacts:fl,onClearSelection:()=>{vt(new Set),Ys(!1)},showLeadPondAction:Un,onSendToLeadPond:Nl,showTransferAction:ur,onTransfer:Ya}),Xs.size>0&&Xs.size===ad.length&&!Is&&Co>On&&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 ",ad.length," contacts on this page are selected."]}),e.jsxs($,{variant:"link",size:"sm",className:"h-auto p-0 font-semibold",onClick:Ul,children:["Select all ",Co.toLocaleString()," matching contacts"]})]}),Is&&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 ",Co.toLocaleString()," matching contacts are selected.",e.jsx($,{variant:"link",size:"sm",className:"h-auto p-0",onClick:()=>{vt(new Set),Ys(!1)},children:"Clear selection"})]}),Co>On&&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 ",(nc-1)*On+1,"–",Math.min(nc*On,Co)," of ",Co.toLocaleString()," contacts"]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx($,{variant:"outline",size:"sm",disabled:nc<=1,onClick:()=>Ws(1),children:"First"}),e.jsx($,{variant:"outline",size:"sm",disabled:nc<=1,onClick:()=>Ws(_s=>_s-1),children:e.jsx(Cd,{className:"h-4 w-4"})}),e.jsxs("span",{className:"px-3 text-sm font-medium",children:["Page ",nc," of ",pu]}),e.jsx($,{variant:"outline",size:"sm",disabled:nc>=pu,onClick:()=>Ws(_s=>_s+1),children:e.jsx(Di,{className:"h-4 w-4"})}),e.jsx($,{variant:"outline",size:"sm",disabled:nc>=pu,onClick:()=>Ws(pu),children:"Last"})]})]}),a?e.jsx("div",{className:"space-y-3",children:f?e.jsx(M$n,{}):fl.length===0?e.jsx(Ne,{children:e.jsx(wCt,{filtered:!!te||he!=="all"||ve!=="all"||Fe!=="all"||W.size>0,onAdd:()=>nt(!0),onImport:()=>qt(!0),onClearFilters:()=>{J(""),ue("all"),Ee("all"),ke("all"),V(new Set),je({})}})}):ad.map(_s=>{var No,Ba,io;const{relationshipScore:Xa}=_s;return e.jsx(Ne,{className:"cursor-pointer hover:bg-accent/50 transition-colors",onClick:()=>Bc(_s.id),children:e.jsx(Ie,{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:[_s.first_name," ",_s.last_name]}),e.jsx(xCt,{count:(y==null?void 0:y[_s.id])??0}),e.jsx(Di,{className:"h-4 w-4 text-muted-foreground shrink-0 ml-auto"})]}),e.jsxs("div",{className:"space-y-1 text-sm mb-3",children:[_s.email&&e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground",children:[e.jsx(mn,{className:"h-3.5 w-3.5 shrink-0"}),e.jsx("span",{className:"truncate",children:_s.email})]}),_s.phone&&e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground",children:[e.jsx(Da,{className:"h-3.5 w-3.5 shrink-0"}),e.jsx("span",{children:_s.phone})]})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-1 mb-2",children:[e.jsx(OYe,{score:Xa,size:"sm"}),e.jsx(dCt,{contact:_s}),(((No=_s.lead_source_ref)==null?void 0:No.name)||_s.lead_source)&&e.jsx(Be,{variant:"outline",className:"text-xs gap-1 border-primary/30 text-primary",children:((Ba=_s.lead_source_ref)==null?void 0:Ba.name)||_s.lead_source}),(io=_s.tags)==null?void 0:io.map(ko=>{var qi;return e.jsx(Be,{variant:"secondary",className:"text-xs",children:(qi=ko.relationship_type)==null?void 0:qi.name},ko.id)}),e.jsx(bCt,{contactId:_s.id,tags:S==null?void 0:S.filter(ko=>ko.contact_id===_s.id)}),e.jsx(gCt,{deal:b==null?void 0:b[_s.id]})]}),e.jsx("div",{className:"mb-2",children:e.jsx(CCt,{criteria:E==null?void 0:E[_s.id],onEdit:()=>D({id:_s.id,name:`${_s.first_name}${_s.last_name?" "+_s.last_name:""}`}),showAlertState:!!C,matchCount:I==null?void 0:I[_s.id],compact:!0})}),e.jsx(pCt,{birthday:_s.birthday,homeAnniversary:_s.home_anniversary,weddingAnniversary:_s.wedding_anniversary,className:"mb-2",contactId:_s.id,contactName:`${_s.first_name}${_s.last_name?" "+_s.last_name:""}`,contactAddress:[_s.address,_s.city,_s.state].filter(Boolean).join(", ")}),e.jsxs("div",{className:"flex flex-wrap items-center gap-3 text-xs text-muted-foreground",children:[Xa.lastTouchDate?e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(da,{className:"h-3 w-3"}),en(new Date(Xa.lastTouchDate),"MMM d")]}):e.jsx("span",{className:"italic",children:"Never contacted"}),_s.birthday&&e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(Ta,{className:"h-3 w-3"}),en(Ch(_s.birthday),"MMM d")]}),_s.home_anniversary&&e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(va,{className:"h-3 w-3"}),en(Ch(_s.home_anniversary),"MMM d")]}),_s.created_at&&e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(dn,{className:"h-3 w-3"}),"Added ",en(new Date(_s.created_at),"MMM d, yyyy")]})]})]}),e.jsx("div",{className:"ml-2",onClick:ko=>ko.stopPropagation(),children:e.jsx(hCt,{contact:_s,onEdit:rt,onDelete:cm,onSnooze:(ko,qi)=>{Ft(ko),St(qi)},showLeadPondAction:Un,onSendToLeadPond:$d,showTransferAction:ur,onTransfer:xa})})]})})},_s.id)})}):e.jsx(Ne,{children:e.jsx(Ie,{className:"p-0 overflow-x-auto",children:e.jsxs(mi,{className:"min-w-[800px]",children:[e.jsx(fi,{className:"sticky top-0 z-10 bg-card/95 backdrop-blur supports-[backdrop-filter]:bg-card/80",children:e.jsxs(En,{className:"hover:bg-transparent",children:[e.jsx(Dt,{className:"w-[40px]",children:e.jsx(ai,{checked:ad.length>0&&ad.every(_s=>Xs.has(_s.id)),onCheckedChange:()=>yc()})}),e.jsx(Dt,{children:e.jsxs("button",{onClick:()=>Le(_s=>_s==="last-name"?"name":"last-name"),className:"group inline-flex items-center gap-1 font-medium text-muted-foreground hover:text-foreground transition-colors",children:["Contact",Se==="name"&&e.jsx(Di,{className:"h-3 w-3 rotate-90 text-primary"}),Se==="last-name"&&e.jsx(Di,{className:"h-3 w-3 -rotate-90 text-primary"})]})}),l.relationship&&e.jsx(Dt,{children:"Relationship"}),l.buyerCriteria&&e.jsx(Dt,{className:"min-w-[170px] whitespace-nowrap",children:"Looking For"}),l.stage&&e.jsx(Dt,{children:"Stage"}),l.leadSource&&e.jsx(Dt,{children:"Lead Source"}),l.tags&&e.jsx(Dt,{children:"Tags"}),l.lastTouch&&e.jsx(Dt,{children:"Last Touch"}),l.nextAction&&e.jsx(Dt,{children:"Next Action"}),l.dealValue&&e.jsx(Dt,{title:"Total value of deals linked to this contact in your pipeline",children:"Pipeline Value"}),l.email&&e.jsx(Dt,{children:"Email"}),l.phone&&e.jsx(Dt,{children:"Phone"}),l.address&&e.jsx(Dt,{children:"Address"}),l.birthday&&e.jsx(Dt,{children:"Birthday"}),e.jsx(Dt,{className:"w-[50px]"})]})}),e.jsx(pi,{children:f?e.jsx(T$n,{columns:2+Object.values(l).filter(Boolean).length}):fl.length===0?e.jsx(En,{className:"hover:bg-transparent",children:e.jsx(wt,{colSpan:3+Object.values(l).filter(Boolean).length,className:"p-0",children:e.jsx(wCt,{filtered:!!te||he!=="all"||ve!=="all"||Fe!=="all"||W.size>0,onAdd:()=>nt(!0),onImport:()=>qt(!0),onClearFilters:()=>{J(""),ue("all"),Ee("all"),ke("all"),V(new Set),je({})}})})}):ad.map(_s=>{var Ba;const{relationshipScore:Xa}=_s,No=b==null?void 0:b[_s.id];return e.jsxs(En,{className:`group cursor-pointer border-border/60 transition-colors hover:bg-accent/40 [&>td]:py-3.5 ${Xs.has(_s.id)?"bg-accent/30":""}`,onClick:()=>Bc(_s.id),children:[e.jsx(wt,{onClick:io=>io.stopPropagation(),children:e.jsx(ai,{checked:Xs.has(_s.id),onCheckedChange:()=>Ho(_s.id)})}),e.jsx(wt,{className:"min-w-[220px]",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Sit,{firstName:_s.first_name,lastName:_s.last_name,avatarUrl:_s.avatar_url,email:_s.email,size:36}),e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsxs("span",{className:"font-medium truncate",children:[_s.first_name," ",_s.last_name]}),e.jsx(A$n,{linked:!!_s.spouse_contact_id||!!_s.spouse_name,spouseName:_s.spouse_contact_id&&ta[_s.spouse_contact_id]||_s.spouse_name||null}),e.jsx(xCt,{count:(y==null?void 0:y[_s.id])??0})]}),_s.email&&!l.email&&e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:_s.email}),_s.phone&&!l.phone&&e.jsx("p",{className:"text-xs text-muted-foreground",children:_s.phone})]})]})}),l.relationship&&e.jsx(wt,{children:e.jsxs("div",{className:"flex items-center gap-2.5",children:[e.jsx(N$n,{score:Xa.score,status:Xa.status}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-sm font-medium leading-tight",children:Xa.status==="warm"?"Strong":Xa.status==="cooling"?"Cooling":"At Risk"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:Xa.daysSinceTouch===null?"Never contacted":Xa.daysSinceTouch===0?"Touched today":`${Xa.daysSinceTouch}d since touch`})]})]})}),l.buyerCriteria&&e.jsx(wt,{className:"min-w-[170px] max-w-[240px]",children:e.jsx(CCt,{criteria:E==null?void 0:E[_s.id],onEdit:()=>D({id:_s.id,name:`${_s.first_name}${_s.last_name?" "+_s.last_name:""}`}),showAlertState:!!C,matchCount:I==null?void 0:I[_s.id]})}),l.stage&&e.jsx(wt,{children:e.jsx(gCt,{deal:No})}),l.leadSource&&e.jsx(wt,{className:"text-sm text-muted-foreground max-w-[160px] truncate",children:((Ba=_s.lead_source_ref)==null?void 0:Ba.name)||_s.lead_source||"—"}),l.tags&&e.jsx(wt,{children:e.jsx("div",{className:"flex flex-wrap items-center gap-1 max-w-[220px]",children:e.jsx(bCt,{contactId:_s.id,tags:S==null?void 0:S.filter(io=>io.contact_id===_s.id)})})}),l.lastTouch&&e.jsx(wt,{children:Xa.lastTouchDate?e.jsxs("div",{className:"flex items-center gap-1.5 text-sm text-muted-foreground",children:[e.jsx(da,{className:"h-3.5 w-3.5"}),en(new Date(Xa.lastTouchDate),"MMM d, yyyy")]}):e.jsx("span",{className:"text-xs italic text-muted-foreground",children:"No activity"})}),l.nextAction&&e.jsx(wt,{children:e.jsxs("div",{className:"flex flex-col items-start gap-1",children:[e.jsx(dCt,{contact:_s}),e.jsx(pCt,{birthday:_s.birthday,homeAnniversary:_s.home_anniversary,weddingAnniversary:_s.wedding_anniversary,contactId:_s.id,contactName:`${_s.first_name}${_s.last_name?" "+_s.last_name:""}`,contactAddress:[_s.address,_s.city,_s.state].filter(Boolean).join(", ")})]})}),l.dealValue&&e.jsx(wt,{children:(()=>{const io=(No==null?void 0:No.sale_price)??(No==null?void 0:No.expected_price);return io?e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-semibold",children:Qm(Number(io))}),(No==null?void 0:No.deal_type)&&e.jsx("p",{className:"text-xs text-muted-foreground capitalize",children:String(No.deal_type).replace(/_/g," ")})]}):e.jsx("span",{className:"text-sm text-muted-foreground",children:"—"})})()}),l.email&&e.jsx(wt,{className:"text-sm text-muted-foreground max-w-[220px] truncate",children:_s.email||"—"}),l.phone&&e.jsx(wt,{className:"text-sm text-muted-foreground whitespace-nowrap",children:_s.phone||"—"}),l.address&&e.jsx(wt,{className:"text-sm text-muted-foreground max-w-[220px] truncate",children:[_s.address,_s.city,_s.state].filter(Boolean).join(", ")||"—"}),l.birthday&&e.jsx(wt,{className:"text-sm text-muted-foreground whitespace-nowrap",children:_s.birthday?(()=>{const[io,ko,qi]=String(_s.birthday).split(/[-/T]/).map(Number);return ko&&qi?`${ko}/${qi}${io&&io>1900?`/${io}`:""}`:"—"})():"—"}),e.jsx(wt,{onClick:io=>io.stopPropagation(),children:e.jsx(hCt,{contact:_s,onEdit:rt,onDelete:cm,onSnooze:(io,ko)=>{Ft(io),St(ko)},showLeadPondAction:Un,onSendToLeadPond:$d,showTransferAction:ur,onTransfer:xa})})]},_s.id)})})]})})}),Co>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 ",(nc-1)*On+1,"–",Math.min(nc*On,Co)," of ",Co.toLocaleString()," contacts"]}),e.jsxs(ms,{value:String(On),onValueChange:_s=>{ds(Number(_s)),Ws(1)},children:[e.jsx(us,{className:"w-[80px] h-8",children:e.jsx(fs,{})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"50",children:"50"}),e.jsx(Ge,{value:"100",children:"100"}),e.jsx(Ge,{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($,{variant:"outline",size:"sm",disabled:nc<=1,onClick:()=>Ws(1),children:"First"}),e.jsx($,{variant:"outline",size:"sm",disabled:nc<=1,onClick:()=>Ws(_s=>_s-1),children:e.jsx(Cd,{className:"h-4 w-4"})}),e.jsxs("span",{className:"px-3 text-sm font-medium",children:["Page ",nc," of ",pu]}),e.jsx($,{variant:"outline",size:"sm",disabled:nc>=pu,onClick:()=>Ws(_s=>_s+1),children:e.jsx(Di,{className:"h-4 w-4"})}),e.jsx($,{variant:"outline",size:"sm",disabled:nc>=pu,onClick:()=>Ws(pu),children:"Last"})]})]}),e.jsx(zs,{open:Ke||!!xt,onOpenChange:_s=>{_s||(nt(!1),rt(null),Ic())},children:e.jsxs(Os,{className:"max-w-lg max-h-[90vh] overflow-y-auto",children:[e.jsx(Us,{children:e.jsx(Bs,{children:xt?"Edit Contact":"Add Contact"})}),e.jsxs("form",{onSubmit:Ih,className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"first_name",children:"First Name *"}),e.jsx(pe,{id:"first_name",value:ti.first_name,onChange:_s=>Xr({...ti,first_name:_s.target.value}),required:!0})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"last_name",children:"Last Name"}),e.jsx(pe,{id:"last_name",value:ti.last_name,onChange:_s=>Xr({...ti,last_name:_s.target.value})})]})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"email",children:"Email"}),e.jsx(pe,{id:"email",type:"email",value:ti.email,onChange:_s=>Xr({...ti,email:_s.target.value})})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"phone",children:"Phone"}),e.jsx(pe,{id:"phone",value:ti.phone,onChange:_s=>Xr({...ti,phone:_s.target.value})})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"address",children:"Address"}),e.jsx(pe,{id:"address",value:ti.address,onChange:_s=>Xr({...ti,address:_s.target.value}),placeholder:"Street address"})]}),e.jsxs("div",{className:"grid grid-cols-3 gap-4",children:[e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"city",children:"City"}),e.jsx(pe,{id:"city",value:ti.city,onChange:_s=>Xr({...ti,city:_s.target.value})})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"state",children:"State"}),e.jsx(pe,{id:"state",value:ti.state,onChange:_s=>Xr({...ti,state:_s.target.value})})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"zip_code",children:"Zip"}),e.jsx(pe,{id:"zip_code",value:ti.zip_code,onChange:_s=>Xr({...ti,zip_code:_s.target.value})})]})]}),Eo?e.jsxs("div",{className:"space-y-4 rounded-lg border p-3",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"address2_label",children:"Label"}),e.jsx(pe,{id:"address2_label",list:"contact-address-labels-new",value:ti.address2_label,onChange:_s=>Xr({...ti,address2_label:_s.target.value}),placeholder:"Vacation home"}),e.jsx("datalist",{id:"contact-address-labels-new",children:LQt.map(_s=>e.jsx("option",{value:_s},_s))})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"address2",children:"Street Address"}),e.jsx(pe,{id:"address2",value:ti.address2,onChange:_s=>Xr({...ti,address2:_s.target.value})})]})]}),e.jsxs("div",{className:"grid grid-cols-3 gap-4",children:[e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"address2_city",children:"City"}),e.jsx(pe,{id:"address2_city",value:ti.address2_city,onChange:_s=>Xr({...ti,address2_city:_s.target.value})})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"address2_state",children:"State"}),e.jsx(pe,{id:"address2_state",value:ti.address2_state,onChange:_s=>Xr({...ti,address2_state:_s.target.value}),maxLength:2})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"address2_zip",children:"Zip"}),e.jsx(pe,{id:"address2_zip",value:ti.address2_zip,onChange:_s=>Xr({...ti,address2_zip:_s.target.value})})]})]}),e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx(ee,{htmlFor:"mail_to_secondary",className:"text-sm font-normal",children:"Send mail here instead of the main address"}),e.jsx(Sn,{id:"mail_to_secondary",checked:ti.mail_to_secondary,onCheckedChange:_s=>Xr({...ti,mail_to_secondary:_s})})]})]}):e.jsx($,{type:"button",variant:"ghost",size:"sm",className:"justify-start px-0 text-primary",onClick:()=>Ph(!0),children:"+ Add another address"}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"birthday",children:"Birthday"}),e.jsx(pe,{id:"birthday",type:"date",value:ti.birthday,onChange:_s=>Xr({...ti,birthday:_s.target.value})})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"home_anniversary",children:"Home Anniversary"}),e.jsx(pe,{id:"home_anniversary",type:"date",value:ti.home_anniversary,onChange:_s=>Xr({...ti,home_anniversary:_s.target.value})})]})]}),xt&&e.jsx(BYe,{contactId:xt.id,currentSpouseContactId:(xt==null?void 0:xt.spouse_contact_id)||null,currentSpouseName:(xt==null?void 0:xt.spouse_name)||null,currentSpouseEmail:(xt==null?void 0:xt.spouse_email)||null,onLink:_s=>ne.mutate({contactId:xt.id,spouseContactId:_s}),onUnlink:()=>ne.mutate({contactId:xt.id,spouseContactId:null}),isEditing:!0}),e.jsx(eJt,{value:ti.lead_source_id,onChange:_s=>Xr({...ti,lead_source_id:_s})}),e.jsxs("div",{children:[e.jsx(ee,{children:"Relationship Types"}),e.jsx("div",{className:"flex flex-wrap gap-2 mt-2",children:v==null?void 0:v.filter(_s=>_s.active).map(_s=>e.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[e.jsx(ai,{checked:ti.tagIds.includes(_s.id),onCheckedChange:Xa=>{Xr(Xa?{...ti,tagIds:[...ti.tagIds,_s.id]}:{...ti,tagIds:ti.tagIds.filter(No=>No!==_s.id)})}}),e.jsx("span",{className:"text-sm",children:_s.name})]},_s.id))})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"notes",children:"Notes"}),e.jsx(Rs,{id:"notes",value:ti.notes,onChange:_s=>Xr({...ti,notes:_s.target.value}),rows:3})]}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx($,{type:"button",variant:"outline",onClick:()=>{nt(!1),rt(null),Ic()},children:"Cancel"}),e.jsxs($,{type:"submit",disabled:X.isPending||ae.isPending,children:[xt?"Update":"Create"," Contact"]})]})]})]})}),e.jsx(m9n,{open:Yt,onOpenChange:qt,relationshipTypes:(v==null?void 0:v.filter(_s=>_s.active))||[],onSuccess:()=>{qt(!1)}}),e.jsx(g9n,{open:ts,onOpenChange:ys,onComplete:()=>ys(!1)}),e.jsx(lDe,{open:!!Bt,onOpenChange:_s=>{_s||Ft(null)},contactId:Bt||"",contactName:rs}),e.jsx(b$n,{open:hr,onOpenChange:Er}),e.jsx(_$n,{open:qn,onOpenChange:hn}),e.jsx(f$n,{open:ce,onOpenChange:_e,contacts:m||[],onCitySelect:_s=>{J(_s),Ws(1)}}),e.jsx(VWt,{open:$i,onOpenChange:Rn,contactIds:Pa,contactNames:Pa.map(_s=>{const Xa=fl.find(No=>No.id===_s);return Xa?`${Xa.first_name} ${Xa.last_name||""}`.trim():""}),onComplete:()=>{ii([]),vt(new Set),Ys(!1)}}),e.jsx(zs,{open:!!Or,onOpenChange:_s=>!_s&&ca(null),children:e.jsxs(Os,{className:"sm:max-w-md",children:[e.jsx(Us,{children:e.jsx(Bs,{children:"Choose a Lead Pond"})}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Sharing ",(Or==null?void 0:Or.length)||0," contact",((Or==null?void 0:Or.length)||0)===1?"":"s"," with your team."]}),e.jsxs(ms,{value:Jn,onValueChange:Sr,children:[e.jsx(us,{children:e.jsx(fs,{placeholder:"Select a pond"})}),e.jsx(hs,{children:Lr.map(_s=>e.jsx(Ge,{value:_s.id,children:_s.name},_s.id))})]}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx($,{variant:"outline",onClick:()=>ca(null),children:"Cancel"}),e.jsx($,{onClick:()=>{Or&&ho(Or,Jn),ca(null)},disabled:!Jn,children:"Share to Pond"})]})]})]})})]})]})})}const Q$n=5*1024*1024;function J$n({contactId:s,firstName:t,lastName:n,avatarUrl:r,email:a,size:i=88}){const l=j.useRef(null),o=Vt(),[c,d]=j.useState(!1),u=()=>{o.invalidateQueries({queryKey:["innercircle-contacts"]}),o.invalidateQueries({queryKey:["innercircle-contact"]}),o.invalidateQueries({queryKey:["contact",s]})},h=async g=>{const{error:x}=await q.from("innercircle_contacts").update({avatar_url:g}).eq("id",s);if(x)throw x;u()},m=async g=>{var x;if(!g.type.startsWith("image/")){_a({title:"Please choose an image file",variant:"destructive"});return}if(g.size>Q$n){_a({title:"Image too large",description:"Please use an image under 5MB.",variant:"destructive"});return}d(!0);try{const{data:y}=await q.auth.getUser(),v=(x=y.user)==null?void 0:x.id,b=(g.name.split(".").pop()||"jpg").toLowerCase(),w=`contacts/${v}/${s}-${Date.now()}.${b}`,{error:S}=await q.storage.from("avatars").upload(w,g,{upsert:!0,contentType:g.type});if(S)throw S;const{data:C}=q.storage.from("avatars").getPublicUrl(w);await h(C.publicUrl),_a({title:"Photo updated"})}catch(y){_a({title:"Upload failed",description:y.message,variant:"destructive"})}finally{d(!1),l.current&&(l.current.value="")}},f=async()=>{d(!0);try{await h(null),_a({title:"Photo removed"})}catch(g){_a({title:"Could not remove photo",description:g.message,variant:"destructive"})}finally{d(!1)}};return e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("button",{type:"button",onClick:()=>{var g;return(g=l.current)==null?void 0:g.click()},disabled:c,className:"relative group rounded-full focus:outline-none focus-visible:ring-2 focus-visible:ring-ring","aria-label":r?"Change contact photo":"Upload contact photo",children:[e.jsx(Sit,{firstName:t,lastName:n,avatarUrl:r,email:a,size:i}),e.jsx("span",{className:"absolute inset-0 rounded-full bg-foreground/55 opacity-0 group-hover:opacity-100 transition-opacity flex items-center justify-center",children:c?e.jsx(kt,{className:"h-5 w-5 text-background animate-spin"}):e.jsx(Cx,{className:"h-5 w-5 text-background"})}),c&&e.jsx("span",{className:"absolute inset-0 rounded-full bg-foreground/55 flex items-center justify-center",children:e.jsx(kt,{className:"h-5 w-5 text-background animate-spin"})})]}),r&&e.jsxs($,{variant:"ghost",size:"sm",className:"text-muted-foreground gap-1.5",onClick:f,disabled:c,children:[e.jsx(Wn,{className:"h-3.5 w-3.5"}),"Remove"]}),e.jsx("input",{ref:l,type:"file",accept:"image/*",className:"hidden",onChange:g=>{var y;const x=(y=g.target.files)==null?void 0:y[0];x&&m(x)}})]})}const eUn={job_title:"Job title",company_name:"Company",city:"City",state:"State",avatar_url:"Profile photo",email:"Email",phone:"Phone"},tUn=4e3,sUn=5*60*1e3;function nUn({open:s,onOpenChange:t,contactId:n,contactName:r,hasEmail:a}){var W;const{toast:i}=Bi(),l=Vt(),[o,c]=j.useState(""),[d,u]=j.useState(!1),[h,m]=j.useState(!1),[f,g]=j.useState(null),[x,y]=j.useState(!1),[v,b]=j.useState(null),[w,S]=j.useState(null),[C,E]=j.useState(0),I=j.useRef(null),[P,R]=j.useState({job_title:!0,company_name:!0,city:!0,state:!0,avatar_url:!1,email:!1,phone:!1});j.useEffect(()=>{if(!w||!s)return;I.current=Date.now(),E(0);let V=!1,G=null,Y=null;const X=async()=>{if(!V)try{const{data:ae,error:ie}=await q.functions.invoke("enrich-contact",{body:{contact_id:n,batch_id:w}});if(ie)throw ie;if((ae==null?void 0:ae.status)==="pending"){E(Date.now()-(I.current||Date.now()));return}ae!=null&&ae.ok&&ae.found?(g(ae.profile),b(ae.matched_on??null),S(null)):(y(!0),S(null))}catch(ae){i({title:"Enrichment status check failed",description:(ae==null?void 0:ae.message)??"Please try again.",variant:"destructive"}),S(null)}};return X(),G=setInterval(X,tUn),Y=setTimeout(()=>{V||(S(null),i({title:"Enrichment is taking longer than expected",description:"The provider has not finished processing yet. You can close this dialog and try again later.",variant:"default"}))},sUn),()=>{V=!0,G&&clearInterval(G),Y&&clearTimeout(Y)}},[w,s,n,i]);const D=async()=>{u(!0),y(!1),g(null),S(null);try{const{data:V,error:G}=await q.functions.invoke("enrich-contact",{body:{contact_id:n,linkedin_url:o.trim()||void 0}});if(G)throw G;if((V==null?void 0:V.status)==="pending"&&(V!=null&&V.batch_id)){S(V.batch_id);return}if(!(V!=null&&V.found)){y(!0);return}g(V.profile),b(V.matched_on??null)}catch(V){i({title:"Enrichment failed",description:(V==null?void 0:V.message)??"Please try again.",variant:"destructive"})}finally{u(!1)}},O=()=>{var G,Y;if(!f)return[];const V=[];if(f.job_title&&V.push({key:"job_title",value:f.job_title}),f.company_name&&V.push({key:"company_name",value:f.company_name}),f.city&&V.push({key:"city",value:f.city}),f.state&&V.push({key:"state",value:f.state}),f.photo_url&&V.push({key:"avatar_url",value:f.photo_url}),(G=f.emails)!=null&&G.length&&V.push({key:"email",value:f.emails[0]}),(Y=f.phones)!=null&&Y.length&&V.push({key:"phone",value:f.phones[0]}),!f.city&&!f.state&&f.location){const[X,ae]=f.location.split(",").map(ie=>ie.trim());X&&V.push({key:"city",value:X}),ae&&V.push({key:"state",value:ae})}return V},U=async()=>{const V={};for(const G of O())P[G.key]&&(V[G.key==="avatar_url"?"avatar_url":G.key]=G.value);if(Object.keys(V).length===0){i({title:"Nothing selected",description:"Pick at least one field to save."});return}m(!0);try{const{error:G}=await q.from("innercircle_contacts").update(V).eq("id",n);if(G)throw G;await l.invalidateQueries({queryKey:["contact",n]}),await l.invalidateQueries({queryKey:["contacts"]}),i({title:"Contact updated",description:`${Object.keys(V).length} field(s) saved.`}),t(!1)}catch(G){i({title:"Could not save",description:(G==null?void 0:G.message)??"Please try again.",variant:"destructive"})}finally{m(!1)}};return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Os,{className:"max-w-lg",children:[e.jsxs(Us,{children:[e.jsxs(Bs,{className:"flex items-center gap-2",children:[e.jsx(Nn,{className:"h-4 w-4 text-primary"}),"Find person details — ",r]}),e.jsx(Ir,{children:"Looks up public professional details (job title, company, social profiles) for this person and lets you choose what to save. This does not look up home or property data — use the Property tab for that."})]}),e.jsxs("div",{className:"space-y-4",children:[!f&&!w&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"li-url",children:"LinkedIn URL (optional)"}),e.jsx(pe,{id:"li-url",placeholder:"https://linkedin.com/in/username",value:o,onChange:V=>c(V.target.value)}),e.jsx("p",{className:"text-xs text-muted-foreground",children:a?"We’ll match on the contact’s email, phone, or the LinkedIn URL above.":"This contact has no email — add a LinkedIn URL or phone number for the best match."})]}),w&&e.jsxs("div",{className:"rounded-lg border border-dashed p-4 text-sm text-center space-y-2",children:[e.jsx(kt,{className:"h-5 w-5 animate-spin mx-auto text-primary"}),e.jsx("p",{className:"font-medium",children:"Searching public profiles…"}),e.jsx("p",{className:"text-muted-foreground",children:"The enrichment provider is processing this lookup. This can take 10–30 seconds."}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Elapsed: ",Math.floor(C/1e3),"s"]})]}),x&&e.jsx("div",{className:"rounded-lg border border-dashed p-4 text-sm text-muted-foreground",children:"No public profile matched this contact. Try adding a LinkedIn URL."}),f&&e.jsx(uo,{className:"max-h-[45vh] pr-3",children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-start gap-3 rounded-lg border p-3",children:[f.photo_url&&e.jsx("img",{src:f.photo_url,alt:f.full_name??"Profile photo",className:"h-14 w-14 rounded-full object-cover"}),e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("p",{className:"font-semibold truncate",children:f.full_name||r}),v&&e.jsxs(Be,{variant:"secondary",className:"text-[10px]",children:["matched via ",v]})]}),f.headline&&e.jsx("p",{className:"text-sm text-muted-foreground",children:f.headline}),e.jsxs("div",{className:"mt-1 flex flex-wrap gap-3 text-xs text-muted-foreground",children:[f.company_name&&e.jsxs("span",{className:"inline-flex items-center gap-1",children:[e.jsx(ji,{className:"h-3 w-3"}),f.company_name]}),f.location&&e.jsxs("span",{className:"inline-flex items-center gap-1",children:[e.jsx(ci,{className:"h-3 w-3"}),f.location]}),f.industry&&e.jsxs("span",{className:"inline-flex items-center gap-1",children:[e.jsx(Sx,{className:"h-3 w-3"}),f.industry]})]}),f.linkedin_url&&e.jsxs("a",{href:f.linkedin_url,target:"_blank",rel:"noreferrer",className:"mt-2 inline-flex items-center gap-1 text-xs text-primary hover:underline",children:[e.jsx(hy,{className:"h-3 w-3"})," LinkedIn ",e.jsx(kr,{className:"h-3 w-3"})]})]})]}),f.summary&&e.jsx("p",{className:"text-sm text-muted-foreground whitespace-pre-line",children:f.summary}),!!((W=f.experience)!=null&&W.length)&&e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"text-xs font-semibold uppercase text-muted-foreground",children:"Experience"}),f.experience.map((V,G)=>e.jsxs("p",{className:"text-sm",children:[V.title," ",V.company?`· ${V.company}`:"",V.starts_at?e.jsxs("span",{className:"text-muted-foreground text-xs",children:[" (",V.starts_at,V.ends_at?` – ${V.ends_at}`:" – present",")"]}):null]},G))]}),O().length===0&&e.jsx("div",{className:"rounded-lg border border-dashed p-3 text-sm text-muted-foreground",children:"We found this person, but the public profile didn’t include any details we can save to the contact (job title, company, city, state, photo, email or phone). Try adding their LinkedIn address and searching again."}),O().length>0&&e.jsxs("div",{className:"space-y-2 rounded-lg border p-3",children:[e.jsx("p",{className:"text-xs font-semibold uppercase text-muted-foreground",children:"Save to contact"}),O().map(V=>e.jsxs("label",{className:"flex items-start gap-2 text-sm",children:[e.jsx(ai,{checked:P[V.key],onCheckedChange:G=>R(Y=>({...Y,[V.key]:G===!0}))}),e.jsxs("span",{className:"min-w-0",children:[e.jsxs("span",{className:"font-medium",children:[eUn[V.key],": "]}),e.jsx("span",{className:"text-muted-foreground break-all",children:V.value})]})]},V.key))]})]})})]}),e.jsxs(Ar,{children:[e.jsx($,{variant:"outline",onClick:()=>t(!1),children:"Close"}),!f&&!w?e.jsxs($,{onClick:D,disabled:d,children:[d?e.jsx(kt,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Nn,{className:"h-4 w-4 mr-2"}),d?"Searching…":"Find profile"]}):w?e.jsxs($,{disabled:!0,children:[e.jsx(kt,{className:"h-4 w-4 mr-2 animate-spin"}),"Searching…"]}):e.jsxs($,{onClick:U,disabled:h||O().every(V=>!P[V.key]),children:[h&&e.jsx(kt,{className:"h-4 w-4 mr-2 animate-spin"}),"Save selected"]})]})]})})}const rUn=["jeremy@relevelup.com"];function aUn(){const{user:s}=vs(),t=((s==null?void 0:s.email)||"").toLowerCase();return rUn.includes(t)}const ECt="America/New_York";function iUn(s){const t=new Date(s),n=new Intl.DateTimeFormat("en-US",{timeZone:ECt,month:"short",day:"numeric",year:"numeric"}).format(t),r=new Intl.DateTimeFormat("en-US",{timeZone:ECt,hour:"numeric",minute:"2-digit"}).format(t);return`${n} · ${r}`}function oUn(s){const t=Date.now()-new Date(s).getTime(),n=Math.round(t/6e4);if(n<1)return"just now";if(n<60)return`${n}m ago`;const r=Math.round(n/60);if(r<24)return`${r}h ago`;const a=Math.round(r/24);return a<30?`${a}d ago`:`${Math.round(a/30)}mo ago`}function lUn({contactId:s,ownerUserId:t,legacyNote:n}){const r=Vt(),[a,i]=j.useState(""),{data:l=[],isLoading:o}=tt({queryKey:["contact-notes",s],queryFn:async()=>{const{data:u,error:h}=await q.from("innercircle_contact_notes").select("id, body, source, author_name, created_at").eq("contact_id",s).order("created_at",{ascending:!1});if(h)throw h;return u||[]},enabled:!!s}),c=ft({mutationFn:async u=>{var x,y,v;const{data:h}=await q.auth.getUser(),m=h.user,f=((x=m==null?void 0:m.user_metadata)==null?void 0:x.full_name)||[(y=m==null?void 0:m.user_metadata)==null?void 0:y.first_name,(v=m==null?void 0:m.user_metadata)==null?void 0:v.last_name].filter(Boolean).join(" ")||(m==null?void 0:m.email)||null,{error:g}=await q.from("innercircle_contact_notes").insert({contact_id:s,owner_user_id:t||(m==null?void 0:m.id),author_user_id:m==null?void 0:m.id,author_name:f,source:"agent",body:u});if(g)throw g},onSuccess:()=>{i(""),r.invalidateQueries({queryKey:["contact-notes",s]}),_a({title:"Note added"})},onError:u=>_a({title:"Could not add note",description:u.message,variant:"destructive"})}),d=ft({mutationFn:async u=>{const{error:h}=await q.from("innercircle_contact_notes").delete().eq("id",u);if(h)throw h},onSuccess:()=>r.invalidateQueries({queryKey:["contact-notes",s]})});return e.jsxs(Ne,{children:[e.jsx(Ct,{className:"pb-3",children:e.jsxs(At,{className:"flex items-center gap-2 text-base",children:[e.jsx(eo,{className:"h-4 w-4 text-primary"}),"Notes",l.length>0&&e.jsx(Be,{variant:"secondary",className:"ml-1 rounded-full text-[11px]",children:l.length})]})}),e.jsxs(Ie,{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(Rs,{value:a,onChange:u=>i(u.target.value),placeholder:"Add a note — it's stamped with the date and time automatically.",rows:3,className:"resize-none"}),e.jsx("div",{className:"flex justify-end",children:e.jsxs($,{size:"sm",disabled:!a.trim()||c.isPending,onClick:()=>c.mutate(a.trim()),children:[c.isPending?e.jsx(kt,{className:"mr-1.5 h-3.5 w-3.5 animate-spin"}):null,"Add Note"]})})]}),o?e.jsx("p",{className:"text-sm text-muted-foreground",children:"Loading notes…"}):l.length===0&&!n?e.jsx("p",{className:"text-sm text-muted-foreground",children:"No notes yet — add context about this relationship."}):e.jsxs("div",{className:"space-y-3",children:[l.map(u=>e.jsxs("div",{className:"group rounded-xl border border-border/60 bg-muted/30 p-3",children:[e.jsxs("div",{className:"mb-1.5 flex flex-wrap items-center gap-2 text-[11px] text-muted-foreground",children:[e.jsxs("span",{className:"inline-flex items-center gap-1 font-medium text-foreground/80",children:[e.jsx(da,{className:"h-3 w-3"}),iUn(u.created_at)]}),e.jsxs("span",{children:["· ",oUn(u.created_at)]}),u.source!=="agent"?e.jsxs(Be,{variant:"outline",className:"gap-1 text-[10px]",children:[e.jsx(Nn,{className:"h-2.5 w-2.5"})," System"]}):u.author_name?e.jsxs("span",{children:["· ",u.author_name]}):null,e.jsx("button",{type:"button",onClick:()=>d.mutate(u.id),className:"ml-auto opacity-0 transition-opacity hover:text-destructive group-hover:opacity-100","aria-label":"Delete note",children:e.jsx(Wn,{className:"h-3.5 w-3.5"})})]}),e.jsx("p",{className:"whitespace-pre-wrap text-sm",children:u.body})]},u.id)),n&&e.jsxs("div",{className:"rounded-xl border border-dashed border-border/60 p-3",children:[e.jsx("div",{className:"mb-1.5 text-[11px] font-medium uppercase tracking-wide text-muted-foreground",children:"Background (no timestamp)"}),e.jsx("p",{className:"whitespace-pre-wrap text-sm text-muted-foreground",children:n})]})]})]})]})}const cUn="9a88a47c-cb2a-4401-a2b5-111a76b19f9d";function dUn({open:s,onOpenChange:t,contact:n}){var W;const{user:r}=vs(),a=Qn(),i=Vt(),{intakePage:l,isLoading:o}=C6e(),{isGmailConnected:c,gmailEmail:d}=yy(),u=N6e(),{data:h}=tt({queryKey:["profile-for-invite",r==null?void 0:r.id],enabled:!!(r!=null&&r.id)&&s,queryFn:async()=>{const{data:V}=await q.from("profiles").select("name, email, avatar_url").eq("id",r.id).maybeSingle();return V}}),m=(h==null?void 0:h.name)||((W=r==null?void 0:r.email)==null?void 0:W.split("@")[0])||"Your Agent",f=m.split(" ")[0],g=l?`https://contacts.relevelup.com/${l.slug}`:"",x=j.useMemo(()=>`Hi ${n.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!`,[n.first_name]),[y,v]=j.useState("gmail"),[b,w]=j.useState(""),[S,C]=j.useState(""),[E,I]=j.useState(!1);j.useEffect(()=>{s&&(w(`Quick favor, ${n.first_name} — can you update your info?`),C(x),v(c?"gmail":"system"))},[s,x,n.first_name,c]);const P=j.useMemo(()=>S.split(/\n\n+/).map(V=>`

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

`).join(""),[S]),R=async()=>{var V,G;if(!l)return g;try{const{data:Y,error:X}=await q.functions.invoke("process-intake-submissions",{body:{action:"generate_tokens",contact_ids:[n.id],intake_page_id:l.id}}),ae=X?null:(G=(V=Y==null?void 0:Y.tokens)==null?void 0:V[0])==null?void 0:G.token;return ae?`${g}?t=${ae}`:g}catch{return g}},D=V=>`
${h!=null&&h.avatar_url?`${m}`:`
${f.charAt(0)}
`}

A note from ${m}

${P}

Update Your Info

Takes about a minute — promise

Share My Info →

${V}

Sent with care by ${m}

Powered by ReLevelUp

`,O=async()=>{if(!l){re.error("Set up your Connect Page first",{action:{label:"Set Up",onClick:()=>a("/mission-control/connect-page")}});return}if(!b.trim()||!S.trim()){re.error("Subject and message are required");return}I(!0);const V=await R(),G=D(V),Y=async()=>{const{data:X,error:ae}=await q.functions.invoke("send-connect-invite",{body:{contactEmail:n.email,subject:b,htmlBody:G,replyToEmail:(h==null?void 0:h.email)||(r==null?void 0:r.email),agentName:m}});if(ae)throw ae;if(!(X!=null&&X.success))throw new Error((X==null?void 0:X.error)||"Failed to send")};try{if(y==="gmail"&&c){const{data:X,error:ae}=await q.functions.invoke("gmail-send",{body:{to:n.email,subject:b,body:G,contactId:n.id}});let ie=X&&X.error?X:null;if(ae){ie={error:"send_failed",message:ae.message};const ne=ae.context;if(ne&&typeof ne.json=="function")try{ie=await ne.clone().json()}catch{}}if(ie)if(ie.error==="insufficient_scope")await Y(),re.warning("Sent using system email — your Gmail connection is missing send permission. Reconnect Gmail in Integrations to send from your own inbox.",{duration:8e3});else throw new Error(ie.message||ie.error||"Failed to send");else if(!(X!=null&&X.success))throw new Error("Failed to send")}else await Y();try{await u.mutateAsync({contactId:n.id,actionTypeId:cUn,notes:`Sent Connect Page invite — Subject: "${b}"`})}catch(X){console.warn("Failed to log activity:",X)}i.invalidateQueries({queryKey:["contact-touch-logs"]}),re.success("Connect Page invite sent!"),t(!1)}catch(X){console.error("Send error:",X),re.error(X instanceof Error?X.message:"Failed to send invite")}finally{I(!1)}},U=S.split(/\n\n+/).filter(Boolean);return e.jsx(zs,{open:s,onOpenChange:V=>!E&&t(V),children:e.jsxs(Os,{className:"sm:max-w-[720px] max-h-[92vh] overflow-y-auto",children:[e.jsxs(Us,{children:[e.jsxs(Bs,{className:"flex items-center gap-2",children:[e.jsx(Nn,{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:[n.first_name," ",n.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(kt,{className:"h-6 w-6 animate-spin text-primary"})}):l?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Send From"}),e.jsx(ha,{value:y,onValueChange:V=>v(V),className:"mt-1.5",children:e.jsxs(ma,{className:"grid w-full grid-cols-2",children:[e.jsxs(Zt,{value:"gmail",disabled:!c,children:[e.jsx(mn,{className:"h-3.5 w-3.5 mr-1.5"}),c?`Gmail (${d})`:"Gmail (not connected)"]}),e.jsxs(Zt,{value:"system",children:[e.jsx(Nn,{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:y==="gmail"?"Replies go directly to your Gmail inbox.":`Sent from notifications@dashboard.relevelup.com — replies go to ${(h==null?void 0:h.email)||(r==null?void 0:r.email)||"your account email"}.`})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"invite-subject",children:"Subject"}),e.jsx(pe,{id:"invite-subject",value:b,onChange:V=>w(V.target.value),className:"mt-1.5"})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"invite-message",children:"Personal Message"}),e.jsx(Rs,{id:"invite-message",value:S,onChange:V=>C(V.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(ee,{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Preview"}),e.jsxs("a",{href:g,target:"_blank",rel:"noopener noreferrer",className:"text-xs text-primary hover:underline flex items-center gap-1",children:["Open Connect Page ",e.jsx(kr,{className:"h-3 w-3"})]})]}),e.jsx("div",{className:"rounded-xl border bg-muted/40 p-4 max-h-[380px] overflow-y-auto",children:e.jsxs("div",{className:"mx-auto max-w-[480px] rounded-2xl bg-white shadow-sm overflow-hidden",children:[e.jsxs("div",{className:"bg-gradient-to-br from-[#406E71] to-[#2a4c64] px-6 py-7 text-center",children:[h!=null&&h.avatar_url?e.jsx("img",{src:h.avatar_url,alt:m,className:"mx-auto mb-3 h-14 w-14 rounded-full object-cover ring-2 ring-white/40"}):e.jsx("div",{className:"mx-auto mb-3 flex h-14 w-14 items-center justify-center rounded-full bg-white/20 text-xl font-bold text-white",children:f.charAt(0)}),e.jsxs("p",{className:"text-base font-bold text-white",children:["A note from ",m]})]}),e.jsx("div",{className:"px-6 py-5 space-y-3",children:U.map((V,G)=>e.jsx("p",{className:"text-[13px] leading-relaxed text-slate-600 whitespace-pre-line",children:V},G))}),e.jsx("div",{className:"px-6 pb-6",children:e.jsxs("div",{className:"rounded-xl border border-slate-200 bg-slate-50 px-5 py-6 text-center",children:[e.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-wider text-slate-400",children:"Update Your Info"}),e.jsx("p",{className:"mt-1 text-sm font-semibold text-slate-800",children:"Takes about a minute — promise"}),e.jsx("span",{className:"mt-4 inline-block rounded-lg bg-gradient-to-br from-[#406E71] to-[#2a4c64] px-7 py-3 text-sm font-semibold text-white",children:"Share My Info →"}),e.jsxs("p",{className:"mt-3 break-all text-[11px] text-slate-400",children:[g,"?t=…"]})]})}),e.jsx("div",{className:"border-t border-slate-100 px-6 py-4 text-center",children:e.jsxs("p",{className:"text-[11px] text-slate-400",children:["Sent with care by ",m]})})]})}),e.jsxs("p",{className:"text-[11px] text-muted-foreground mt-1.5",children:["Each invite includes a private link that pre-fills ",n.first_name,"'s current info, so their updates come straight back to this contact record."]})]}),e.jsxs("div",{className:"flex items-center justify-end gap-2 pt-2",children:[e.jsx($,{variant:"outline",onClick:()=>t(!1),disabled:E,children:"Cancel"}),e.jsx($,{onClick:O,disabled:E,children:E?e.jsxs(e.Fragment,{children:[e.jsx(kt,{className:"h-4 w-4 mr-1.5 animate-spin"})," Sending…"]}):e.jsxs(e.Fragment,{children:[e.jsx(Yr,{className:"h-4 w-4 mr-1.5"})," Send Invite"]})})]})]}):e.jsxs("div",{className:"space-y-4 py-6 text-center",children:[e.jsx(ll,{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($,{onClick:()=>a("/mission-control/connect-page"),children:[e.jsx(bd,{className:"h-4 w-4 mr-1"})," Set Up Connect Page"]})]})]})})}function uUn(){const{user:s}=vs();return tt({queryKey:["cmas",s==null?void 0:s.id],queryFn:async()=>{const{data:t,error:n}=await q.from("cmas").select("*").eq("agent_id",s.id).order("updated_at",{ascending:!1});if(n)throw n;return t},enabled:!!s})}function hUn(s){return tt({queryKey:["cma",s],queryFn:async()=>{const{data:t,error:n}=await q.from("cmas").select("*").eq("id",s).single();if(n)throw n;return t},enabled:!!s})}function mUn(s){return tt({queryKey:["cma-comps",s],queryFn:async()=>{const{data:t,error:n}=await q.from("cma_comps").select("*").eq("cma_id",s).order("position",{ascending:!0});if(n)throw n;return t||[]},enabled:!!s})}function iJt(){const s=Vt(),{user:t}=vs(),{leadSite:n}=ng();return ft({mutationFn:async r=>{const{data:a,error:i}=await q.from("cmas").insert({agent_id:t.id,lead_site_id:(n==null?void 0:n.id)??null,contact_id:r.contactId??null,deal_id:r.dealId??null,buyer_mode:!!r.buyerMode,title:r.title??r.subject.address,subject:r.subject,settings:{sqftPct:.2,monthsBack:6,statuses:["Active","Pending","Closed"]}}).select("*").single();if(i)throw i;return a},onSuccess:()=>s.invalidateQueries({queryKey:["cmas"]})})}function fUn(){const s=Vt();return ft({mutationFn:async({id:t,patch:n})=>{const{data:r,error:a}=await q.from("cmas").update(n).eq("id",t).select("*").single();if(a)throw a;return r},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["cma",n.id]}),s.invalidateQueries({queryKey:["cmas"]})}})}function pUn(){const s=Vt();return ft({mutationFn:async t=>{const{error:n}=await q.from("cmas").delete().eq("id",t);if(n)throw n},onSuccess:()=>s.invalidateQueries({queryKey:["cmas"]})})}function gUn(){const{leadSite:s}=ng();return ft({mutationFn:async t=>{const{data:n,error:r}=await q.functions.invoke("cma-subject-lookup",{body:{...t,leadSiteId:(s==null?void 0:s.id)??null}});if(r)throw r;return n}})}function xUn(){const{leadSite:s}=ng();return ft({mutationFn:async t=>{const{data:n,error:r}=await q.functions.invoke("cma-comp-search",{body:{...t,leadSiteId:t.leadSiteId??(s==null?void 0:s.id)??null}});if(r)throw r;return n}})}function yUn(){const s=Vt();return ft({mutationFn:async({cmaId:t,comps:n})=>{if(await q.from("cma_comps").delete().eq("cma_id",t),!n.length)return;const r=n.map((i,l)=>({cma_id:t,mls_number:i.mlsNumber??null,source_provider:i.source_provider??null,selected:i.selected!==!1,manual:!!i.manual,score:i.score??null,position:l,snapshot:i})),{error:a}=await q.from("cma_comps").insert(r);if(a)throw a},onSuccess:(t,n)=>s.invalidateQueries({queryKey:["cma-comps",n.cmaId]})})}function TCt(s,t){const n=t.filter(h=>{var m,f;return h.selected!==!1&&(((m=h.snapshot)==null?void 0:m.sqft)||h.sqft)&&(((f=h.snapshot)==null?void 0:f.price)||h.price)});if(!n.length||!s.sqft)return{low:null,likely:null,high:null,ppsf:null};const r=n.map(h=>{const m=h.snapshot||h;return(m.soldPrice||m.price)/m.sqft}).filter(h=>Number.isFinite(h)&&h>0).sort((h,m)=>h-m);if(!r.length)return{low:null,likely:null,high:null,ppsf:null};const a=r[Math.floor(r.length/2)],i=r.reduce((h,m)=>h+m,0)/r.length,l=r.reduce((h,m)=>h+(m-i)**2,0)/r.length,o=Math.sqrt(l),c=Math.round(a*s.sqft),d=Math.round((a-o)*s.sqft),u=Math.round((a+o)*s.sqft);return{low:d,likely:c,high:u,ppsf:Math.round(a)}}function vUn(s){return tt({queryKey:["contact-video-replies",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await q.from("video_replies").select(` *, video:agent_videos(id, title, thumbnail_url, playback_url) `).eq("contact_id",s).order("created_at",{ascending:!1});if(n)throw n;return t},enabled:!!s})}function bUn(s){return tt({queryKey:["client-portal",s],queryFn:async()=>{if(!s)return null;const{data:t,error:n}=await q.from("client_portals").select("*").eq("deal_id",s).maybeSingle();if(n)throw n;return t},enabled:!!s})}function Cit(){const s=Sa(),t=Vt();return ft({mutationFn:async n=>{if(!s)throw new Error("Not authenticated");const{data:r,error:a}=await q.from("client_portals").insert({deal_id:n.deal_id,owner_user_id:s,slug:"",is_enabled:n.is_enabled??!0,visibility:n.visibility||"private",require_onboarding:n.require_onboarding??!0,allow_spouse:n.allow_spouse??!1,client_name:n.client_name||null,client_email:n.client_email||null,client_phone:n.client_phone||null,invite_method:n.invite_method||"email"}).select().single();if(a)throw a;return r},onSuccess:(n,r)=>{t.invalidateQueries({queryKey:["client-portal",r.deal_id]})}})}function UK(){const s=Vt();return ft({mutationFn:async({id:t,...n})=>{const{data:r,error:a}=await q.from("client_portals").update(n).eq("id",t).select().single();if(a)throw a;return r},onSuccess:t=>{s.invalidateQueries({queryKey:["client-portal",t.deal_id]}),s.invalidateQueries({queryKey:["all-client-portals"]})}})}function oJt(){const s=Vt();return ft({mutationFn:async t=>{const{data:n,error:r}=await q.from("client_portals").update({archived_at:new Date().toISOString(),is_enabled:!1}).eq("id",t).select().single();if(r)throw r;return n},onSuccess:t=>{s.invalidateQueries({queryKey:["client-portal",t.deal_id]}),s.invalidateQueries({queryKey:["all-client-portals"]})}})}function lJt(){const s=Vt();return ft({mutationFn:async t=>{const{data:n,error:r}=await q.from("client_portals").update({archived_at:null}).eq("id",t).select().single();if(r)throw r;return n},onSuccess:t=>{s.invalidateQueries({queryKey:["client-portal",t.deal_id]}),s.invalidateQueries({queryKey:["all-client-portals"]})}})}function cJt(){const s=Vt();return ft({mutationFn:async({id:t,dealId:n})=>{await q.from("portal_updates").delete().eq("portal_id",t);const{error:r}=await q.from("client_portals").delete().eq("id",t);if(r)throw r;return n},onSuccess:t=>{s.invalidateQueries({queryKey:["client-portal",t]}),s.invalidateQueries({queryKey:["all-client-portals"]})}})}function _Un(s){return tt({queryKey:["portal-updates",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await q.from("portal_updates").select("*").eq("portal_id",s).order("created_at",{ascending:!1});if(n)throw n;return t},enabled:!!s})}function dJt(){const s=Vt();return ft({mutationFn:async t=>{const{data:n,error:r}=await q.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(r)throw r;return n},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["portal-updates",n.portal_id]})}})}function wUn(){const s=Sa();return tt({queryKey:["portal-custom-questions",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await q.from("portal_custom_questions").select("*").eq("owner_user_id",s).eq("is_active",!0).order("sort_order",{ascending:!0});if(n)throw n;return t},enabled:!!s})}function jUn(){const s=Sa(),t=Vt();return ft({mutationFn:async n=>{if(!s)throw new Error("Not authenticated");const{data:r,error:a}=await q.from("portal_custom_questions").insert({owner_user_id:s,question_text:n.question_text,field_type:n.field_type,options:n.options||[],is_required:n.is_required||!1,sort_order:n.sort_order||0}).select().single();if(a)throw a;return r},onSuccess:()=>{t.invalidateQueries({queryKey:["portal-custom-questions"]})}})}function NUn(){const s=Vt();return ft({mutationFn:async({id:t,...n})=>{const{data:r,error:a}=await q.from("portal_custom_questions").update(n).eq("id",t).select().single();if(a)throw a;return r},onSuccess:()=>{s.invalidateQueries({queryKey:["portal-custom-questions"]})}})}function kUn(){const s=Vt();return ft({mutationFn:async t=>{const{error:n}=await q.from("portal_custom_questions").update({is_active:!1}).eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["portal-custom-questions"]})}})}function dC(s){const t=window.location.hostname;return t==="localhost"||t.includes("lovable.app")?`${window.location.origin}/portal/${s}`:`https://clients.relevelup.com/${s}`}function SUn({contactId:s}){const t=Qn(),n=Vt(),[r,a]=j.useState(null),[i,l]=j.useState(!1),[o,c]=j.useState(!1),[d,u]=j.useState(""),[h,m]=j.useState(""),[f,g]=j.useState(null),x=UK(),y=dJt(),{data:v,isLoading:b}=tt({queryKey:["contact-portals",s],queryFn:async()=>{const{data:P,error:R}=await q.from("deal_pipeline").select("id, deal_name, deal_type").eq("contact_id",s);if(R)throw R;if(!P||P.length===0)return[];const D=P.map(W=>W.id),{data:O,error:U}=await q.from("client_portals").select("*").in("deal_id",D).is("archived_at",null);if(U)throw U;return(O||[]).map(W=>({...W,deal:P.find(V=>V.id===W.deal_id)}))},enabled:!!s}),w=(v==null?void 0:v.map(P=>P.id))||[],{data:S}=tt({queryKey:["contact-portal-updates",w],queryFn:async()=>{if(w.length===0)return{};const{data:P,error:R}=await q.from("portal_updates").select("*").in("portal_id",w).order("created_at",{ascending:!1});if(R)throw R;const D={};return(P||[]).forEach(O=>{D[O.portal_id]||(D[O.portal_id]=O)}),D},enabled:w.length>0}),C=P=>{navigator.clipboard.writeText(dC(P)),a(P),re.success("Portal link copied!"),setTimeout(()=>a(null),2e3)},E=async(P,R)=>{if(!d.trim())return;const D=d.trim(),O=h.trim();await y.mutateAsync({portal_id:P,title:D,content:O||void 0}),c(!1),u(""),m(""),n.invalidateQueries({queryKey:["contact-portal-updates"]});try{const{data:U,error:W}=await q.functions.invoke("send-portal-notification",{body:{portal_id:P,update_title:D,update_content:O||null,portal_url:R?dC(R):void 0,force:!0}});if(W)throw W;U!=null&&U.emailSent?re.success("Update posted & client emailed"):re.success(`Update posted (${(U==null?void 0:U.reason)||"no email sent"})`)}catch(U){console.error("Portal notification failed:",U),re.success("Update posted (notification failed to send)")}},I=async()=>{f&&(await x.mutateAsync({id:f.id,welcome_message:f.welcome_message,next_step_text:f.next_step_text,is_enabled:f.is_enabled,show_post_close_tips:f.show_post_close_tips,review_url:f.review_url}),l(!1),g(null),n.invalidateQueries({queryKey:["contact-portals",s]}),re.success("Portal settings updated!"))};return b||!v||v.length===0?null:e.jsxs(Ne,{children:[e.jsx(Ct,{className:"pb-2",children:e.jsxs(At,{className:"text-base flex items-center gap-2",children:[e.jsx(dl,{className:"h-4 w-4"}),"Client Portal"]})}),e.jsx(Ie,{className:"space-y-3",children:v.map(P=>{var U,W,V;const R=((U=P.stage_mapping)==null?void 0:U.length)>0?P.stage_mapping:n6e(((W=P.deal)==null?void 0:W.deal_type)||"buyer"),D=R==null?void 0:R[P.current_stage_index??0],O=S==null?void 0:S[P.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:((V=P.deal)==null?void 0:V.deal_name)||"Portal"}),D&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Stage: ",D.label||D.name]})]}),e.jsx(Be,{variant:P.is_enabled?"default":"secondary",className:"text-[10px] flex-shrink-0",children:P.is_enabled?"Active":"Disabled"})]}),O&&e.jsxs("div",{className:"bg-muted/50 rounded-md p-2",children:[e.jsx("p",{className:"text-xs font-medium truncate",children:O.title}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:en(new Date(O.created_at),"MMM d, yyyy")})]}),e.jsxs("div",{className:"flex flex-wrap gap-1.5",children:[e.jsxs($,{variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>C(P.slug),children:[r===P.slug?e.jsx(la,{className:"h-3 w-3 mr-1"}):e.jsx(Ha,{className:"h-3 w-3 mr-1"}),"Copy Link"]}),e.jsxs($,{variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>window.open(dC(P.slug),"_blank"),children:[e.jsx(kr,{className:"h-3 w-3 mr-1"}),"View"]}),e.jsxs(zs,{open:o,onOpenChange:c,children:[e.jsx(jl,{asChild:!0,children:e.jsxs($,{variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>c(!0),children:[e.jsx(eo,{className:"h-3 w-3 mr-1"}),"Post Update"]})}),e.jsxs(Os,{children:[e.jsx(Us,{children:e.jsx(Bs,{children:"Post Portal Update"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(ee,{children:"Title"}),e.jsx(pe,{value:d,onChange:G=>u(G.target.value),placeholder:"e.g. Inspection completed!"})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Details (optional)"}),e.jsx(Rs,{value:h,onChange:G=>m(G.target.value),placeholder:"Add more details...",rows:3})]}),e.jsxs($,{onClick:()=>E(P.id,P.slug),disabled:!d.trim()||y.isPending,className:"w-full",children:[e.jsx(Yr,{className:"h-4 w-4 mr-1"}),"Post Update"]})]})]})]}),e.jsxs(zs,{open:i,onOpenChange:l,children:[e.jsx(jl,{asChild:!0,children:e.jsxs($,{variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>{g({...P}),l(!0)},children:[e.jsx(Sd,{className:"h-3 w-3 mr-1"}),"Settings"]})}),e.jsxs(Os,{children:[e.jsx(Us,{children:e.jsx(Bs,{children:"Portal Settings"})}),f&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(ee,{children:"Portal Enabled"}),e.jsx(Sn,{checked:f.is_enabled,onCheckedChange:G=>g({...f,is_enabled:G})})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Welcome Message"}),e.jsx(Rs,{value:f.welcome_message||"",onChange:G=>g({...f,welcome_message:G.target.value}),placeholder:"Welcome to your home journey!",rows:2})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Next Step"}),e.jsx(pe,{value:f.next_step_text||"",onChange:G=>g({...f,next_step_text:G.target.value}),placeholder:"What your client should do next..."})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Review URL"}),e.jsx(pe,{value:f.review_url||"",onChange:G=>g({...f,review_url:G.target.value}),placeholder:"https://..."})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(ee,{children:"Show Post-Close Tips"}),e.jsx(Sn,{checked:f.show_post_close_tips,onCheckedChange:G=>g({...f,show_post_close_tips:G})})]}),e.jsx(Gc,{}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx($,{onClick:I,disabled:x.isPending,className:"flex-1",children:"Save Settings"}),e.jsxs($,{variant:"outline",onClick:()=>t(`/mission-control/pipeline?deal=${P.deal_id}`),children:[e.jsx(ei,{className:"h-4 w-4 mr-1"}),"Full Settings"]})]})]})]})]})]}),v.length>1&&e.jsx(Gc,{})]},P.id)})})]})}function CUn({contactId:s}){const{data:t}=tt({queryKey:["agent-lead-sites-slugs"],queryFn:async()=>{const{data:l,error:o}=await q.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}),n=t&&t.size>0,{data:r,isLoading:a}=tt({queryKey:["contact-property-views",s],queryFn:async()=>{const{data:l,error:o}=await q.rpc("get_contact_property_views",{p_contact_id:s});if(o)throw o;return l||[]},enabled:!!s&&!!n});if(!n||a||!r||r.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(Ne,{className:"overflow-hidden",children:[e.jsx(Ct,{className:"pb-2",children:e.jsxs(At,{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(Ca,{className:"h-4 w-4 text-primary"})}),"Property Activity",e.jsxs(Be,{variant:"secondary",className:"text-xs ml-auto",children:[r.length," ",r.length===1?"property":"properties"]})]})}),e.jsx(Ie,{className:"pt-0",children:e.jsx("div",{className:"space-y-1",children:r.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(va,{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(da,{className:"h-3 w-3"}),e.jsx("span",{title:en(new Date(l.viewed_at),"PPp"),children:mu(new Date(l.viewed_at),{addSuffix:!0})})]})]}),o&&e.jsx(kr,{className:"h-3.5 w-3.5 text-muted-foreground opacity-0 group-hover:opacity-100 transition-opacity"})]},l.mls_number)})})})]})}function AUn({contactId:s,contactName:t}){var O,U,W;const{user:n}=vs(),r=Sa(),{hasIdx:a}=ng(),i=Vt(),[l,o]=j.useState(!1),[c,d]=j.useState(!1),[u,h]=j.useState(""),[m,f]=j.useState(null),[g,x]=j.useState(!1),[y,v]=j.useState(!1),{data:b,isLoading:w}=tt({queryKey:["contact-property-alert",s],queryFn:async()=>{const{data:V,error:G}=await q.from("contact_property_alerts").select("*").eq("contact_id",s).maybeSingle();if(G)throw G;return V},enabled:!!s&&!!n}),[S,C]=j.useState({}),E=()=>{C({is_active:(b==null?void 0:b.is_active)??!0,min_price:(b==null?void 0:b.min_price)??null,max_price:(b==null?void 0:b.max_price)??null,min_beds:(b==null?void 0:b.min_beds)??null,min_baths:(b==null?void 0:b.min_baths)??null,min_sqft:(b==null?void 0:b.min_sqft)??null,max_sqft:(b==null?void 0:b.max_sqft)??null,cities:(b==null?void 0:b.cities)??[],zip_codes:(b==null?void 0:b.zip_codes)??[],property_types:(b==null?void 0:b.property_types)??[],frequency:(b==null?void 0:b.frequency)??"daily"}),o(!0)},I=ft({mutationFn:async()=>{const V={contact_id:s,owner_user_id:r,is_active:S.is_active??!0,min_price:S.min_price||null,max_price:S.max_price||null,min_beds:S.min_beds||null,min_baths:S.min_baths||null,min_sqft:S.min_sqft||null,max_sqft:S.max_sqft||null,cities:S.cities||[],zip_codes:S.zip_codes||[],property_types:S.property_types||[],frequency:S.frequency||"daily"};if(b!=null&&b.id){const{error:G}=await q.from("contact_property_alerts").update(V).eq("id",b.id);if(G)throw G}else{const{error:G}=await q.from("contact_property_alerts").insert(V);if(G)throw G}},onSuccess:()=>{i.invalidateQueries({queryKey:["contact-property-alert",s]}),i.invalidateQueries({queryKey:["contact-criteria-map"]}),o(!1),re.success("Home search saved!")},onError:V=>{re.error(V.message||"Failed to save home search")}}),P=ft({mutationFn:async()=>{if(!(b!=null&&b.id))return;const{error:V}=await q.from("contact_property_alerts").delete().eq("id",b.id);if(V)throw V},onSuccess:()=>{i.invalidateQueries({queryKey:["contact-property-alert",s]}),i.invalidateQueries({queryKey:["contact-criteria-map"]}),o(!1),re.success("Home search removed")}}),R=async()=>{if(b!=null&&b.id){x(!0),d(!0),h(""),f(null);try{const{data:V,error:G}=await q.functions.invoke("process-property-alerts",{body:{alert_id:b.id,mode:"preview"}});if(G)throw G;V!=null&&V.html?(h(V.html),f({count:V.listings_count||0,recipient:V.recipient,subject:V.subject})):f({count:0,message:(V==null?void 0:V.message)||"No matching listings found right now."})}catch(V){re.error(V.message||"Failed to generate preview"),d(!1)}finally{x(!1)}}},D=async()=>{if(b!=null&&b.id&&await fo(`Send property alert email to ${t} now?`)){v(!0);try{const{data:V,error:G}=await q.functions.invoke("process-property-alerts",{body:{alert_id:b.id,mode:"send"}});if(G)throw G;V!=null&&V.sent_count?(re.success(`Sent ${V.sent_count} ${V.sent_count===1?"listing":"listings"} to ${V.recipient}`),i.invalidateQueries({queryKey:["contact-property-alert",s]})):re.info((V==null?void 0:V.message)||"No new matching listings to send right now.")}catch(V){re.error(V.message||"Failed to send alert")}finally{v(!1)}}};return w?null:b&&!l?e.jsxs(e.Fragment,{children:[e.jsxs(Ne,{className:"overflow-hidden",children:[e.jsx(Ct,{className:"pb-2",children:e.jsxs(At,{className:"text-base flex items-center gap-2",children:[e.jsx("div",{className:`h-7 w-7 rounded-lg flex items-center justify-center ${a&&b.is_active?"bg-green-500/10":"bg-muted"}`,children:a?b.is_active?e.jsx(qy,{className:"h-4 w-4 text-green-600"}):e.jsx(XS,{className:"h-4 w-4 text-muted-foreground"}):e.jsx(Kr,{className:"h-4 w-4 text-muted-foreground"})}),a?"Property Alerts":"Home Search",a&&e.jsxs(Be,{variant:b.is_active?"default":"secondary",className:"text-xs ml-auto",children:[b.is_active?"Active":"Paused"," · ",b.frequency]})]})}),e.jsxs(Ie,{className:"pt-0 space-y-2",children:[e.jsxs("div",{className:"flex flex-wrap gap-1.5 text-xs",children:[b.min_price||b.max_price?e.jsxs(Be,{variant:"outline",className:"gap-1",children:[e.jsx(ru,{className:"h-3 w-3"}),b.min_price?`$${(b.min_price/1e3).toFixed(0)}k`:"$0"," - ",b.max_price?`$${(b.max_price/1e3).toFixed(0)}k`:"Any"]}):null,b.min_beds?e.jsxs(Be,{variant:"outline",className:"gap-1",children:[e.jsx(T4,{className:"h-3 w-3"}),b.min_beds,"+ beds"]}):null,b.min_baths?e.jsxs(Be,{variant:"outline",className:"gap-1",children:[e.jsx(T0,{className:"h-3 w-3"}),b.min_baths,"+ baths"]}):null,(O=b.cities)==null?void 0:O.map(V=>e.jsxs(Be,{variant:"outline",className:"gap-1",children:[e.jsx(ci,{className:"h-3 w-3"}),V]},V)),(U=b.zip_codes)==null?void 0:U.map(V=>e.jsx(Be,{variant:"outline",children:V},V)),(W=b.property_types)==null?void 0:W.map(V=>e.jsx(Be,{variant:"outline",children:V},V))]}),a&&b.last_sent_at&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Last sent: ",new Date(b.last_sent_at).toLocaleDateString()]}),!a&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Automatic new-listing emails need an IDX website —"," ",e.jsx(wr,{to:"/mission-control/website",className:"text-primary hover:underline",children:"explore IDX websites"}),"."]}),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[a&&e.jsxs(e.Fragment,{children:[e.jsxs($,{variant:"outline",size:"sm",onClick:R,disabled:g,children:[g?e.jsx(kt,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(Ca,{className:"h-4 w-4 mr-1"}),"Preview Email"]}),e.jsxs($,{size:"sm",onClick:D,disabled:y||!b.is_active,title:b.is_active?"Send this alert email now":"Activate alert to send",children:[y?e.jsx(kt,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(Yr,{className:"h-4 w-4 mr-1"}),"Send Now"]})]}),e.jsx($,{variant:"outline",size:"sm",onClick:E,children:"Edit Search"}),e.jsxs($,{variant:"destructive",size:"sm",onClick:()=>P.mutate(),disabled:P.isPending,children:[P.isPending?e.jsx(kt,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(gr,{className:"h-4 w-4 mr-1"}),"Remove"]})]})]})]}),e.jsx(zs,{open:c,onOpenChange:d,children:e.jsxs(Os,{className:"max-w-3xl max-h-[90vh] flex flex-col",children:[e.jsxs(Us,{children:[e.jsx(Bs,{children:"Property Alert Email Preview"}),(m==null?void 0:m.subject)&&e.jsxs("div",{className:"text-xs text-muted-foreground space-y-0.5 pt-1",children:[e.jsxs("div",{children:[e.jsx("span",{className:"font-medium",children:"To:"})," ",m.recipient]}),e.jsxs("div",{children:[e.jsx("span",{className:"font-medium",children:"Subject:"})," ",m.subject]}),e.jsxs("div",{children:[e.jsx("span",{className:"font-medium",children:"Listings:"})," ",m.count]})]})]}),e.jsx("div",{className:"flex-1 overflow-hidden border rounded-md bg-muted/30",children:g?e.jsxs("div",{className:"flex items-center justify-center h-96 text-muted-foreground",children:[e.jsx(kt,{className:"h-5 w-5 mr-2 animate-spin"})," Building preview…"]}):u?e.jsx("iframe",{srcDoc:u,title:"Property alert preview",className:"w-full h-[65vh] bg-white rounded-md"}):e.jsx("div",{className:"flex items-center justify-center h-96 text-sm text-muted-foreground p-6 text-center",children:(m==null?void 0:m.message)||"No matching listings found right now."})}),e.jsxs(Ar,{children:[e.jsx($,{variant:"outline",onClick:()=>d(!1),children:"Close"}),u&&e.jsxs($,{onClick:()=>{d(!1),D()},disabled:y||!b.is_active,children:[e.jsx(Yr,{className:"h-4 w-4 mr-1"}),"Send to ",t]})]})]})})]}):l?e.jsxs(Ne,{children:[e.jsx(Ct,{className:"pb-3",children:e.jsxs(At,{className:"text-base flex items-center gap-2",children:[a?e.jsx(qy,{className:"h-4 w-4 text-primary"}):e.jsx(Kr,{className:"h-4 w-4 text-primary"}),b?"Edit":"Set up"," home search for ",t]})}),e.jsxs(Ie,{className:"space-y-4",children:[e.jsx(aJt,{value:S,onChange:C,hasIdx:a,idxNote:e.jsx($,{asChild:!0,variant:"link",size:"sm",className:"h-auto p-0 text-xs",children:e.jsx(wr,{to:"/mission-control/website",children:"Explore IDX websites"})})}),e.jsxs("div",{className:"flex gap-2 pt-2",children:[e.jsxs($,{onClick:()=>I.mutate(),disabled:I.isPending,className:"flex-1",children:[I.isPending?e.jsx(kt,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(tl,{className:"h-4 w-4 mr-1"}),"Save"]}),e.jsx($,{variant:"outline",onClick:()=>o(!1),children:"Cancel"}),b&&e.jsx($,{variant:"destructive",size:"icon",onClick:()=>P.mutate(),disabled:P.isPending,children:e.jsx(gr,{className:"h-4 w-4"})})]})]})]}):e.jsx(Ne,{className:"overflow-hidden",children:e.jsx(Ie,{className:"p-4",children:e.jsxs("button",{onClick:E,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:a?e.jsx(qy,{className:"h-4 w-4 text-primary"}):e.jsx(Kr,{className:"h-4 w-4 text-primary"})}),e.jsxs("div",{className:"text-left",children:[e.jsx("p",{className:"font-medium text-sm",children:"Add Home Search"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:a?`Automatically email ${t} new listings matching their criteria`:`Save what ${t} is looking for so you can match new listings to them`})]})]})})})}function EUn({contactId:s,contactName:t}){var Y;const{user:n}=vs(),r=Sa(),{hasLeadSite:a}=ng(),i=Vt(),[l,o]=j.useState(!1),[c,d]=j.useState(""),[u,h]=j.useState([]),[m,f]=j.useState(!1),[g,x]=j.useState(!1),[y,v]=j.useState(!1),[b,w]=j.useState(""),S=j.useRef(null),C=j.useRef(null),{data:E}=tt({queryKey:["agent-lead-site-cities",r],queryFn:async()=>{const{data:X,error:ae}=await q.from("lead_sites").select("theme_config, mls_market_area").eq("agent_id",r).eq("is_active",!0).order("created_at",{ascending:!0}).limit(1).maybeSingle();if(ae||!X)return[];const ie=X.theme_config||{},ne=Array.isArray(ie.searchCities)?ie.searchCities:[];return X.mls_market_area&&!ne.includes(X.mls_market_area)&&ne.unshift(X.mls_market_area),ne},enabled:!!r}),{data:I,isLoading:P}=tt({queryKey:["contact-market-report",s],queryFn:async()=>{const{data:X,error:ae}=await q.from("innercircle_contacts").select("market_report_enabled, market_report_cities").eq("id",s).single();if(ae)throw ae;return X},enabled:!!s&&!!n});j.useEffect(()=>{const X=ae=>{C.current&&!C.current.contains(ae.target)&&S.current&&!S.current.contains(ae.target)&&x(!1)};return document.addEventListener("mousedown",X),()=>document.removeEventListener("mousedown",X)},[]);const R=()=>{f((I==null?void 0:I.market_report_enabled)??!1),h((I==null?void 0:I.market_report_cities)??[]),o(!0)},D=X=>{const ae=(X||c).trim();ae&&!u.includes(ae)&&h([...u,ae]),d(""),x(!1)},O=(E||[]).filter(X=>!u.includes(X)&&X.toLowerCase().includes(c.toLowerCase())),U=ft({mutationFn:async()=>{const{data:X,error:ae}=await q.functions.invoke("send-market-report",{body:{action:"preview",agentId:r,cities:(I==null?void 0:I.market_report_cities)??[]}});if(ae)throw new Error(ae.message||"Failed to generate preview");if(X&&!X.ok&&X.error)throw new Error(X.error);return X},onSuccess:X=>{w(X.html),v(!0)},onError:X=>{re.error(X.message||"Failed to generate preview")}}),W=ft({mutationFn:async()=>{const{data:X,error:ae}=await q.functions.invoke("send-market-report",{body:{action:"send",agentId:r,cities:(I==null?void 0:I.market_report_cities)??[],contactIds:[s]}});if(ae)throw new Error(ae.message||"Failed to send report");if(X&&!X.ok&&X.error)throw new Error(X.error);return X},onSuccess:()=>{re.success(`Market report sent to ${t}!`)},onError:X=>{re.error(X.message||"Failed to send report")}}),V=ft({mutationFn:async()=>{const{error:X}=await q.from("innercircle_contacts").update({market_report_enabled:m,market_report_cities:u}).eq("id",s);if(X)throw X},onSuccess:()=>{i.invalidateQueries({queryKey:["contact-market-report",s]}),o(!1),re.success(m?"Monthly market report enabled!":"Market report disabled")},onError:X=>{re.error(X.message||"Failed to save")}}),G=ft({mutationFn:async()=>{const{error:X}=await q.from("innercircle_contacts").update({market_report_enabled:!1,market_report_cities:[]}).eq("id",s);if(X)throw X},onSuccess:()=>{i.invalidateQueries({queryKey:["contact-market-report",s]}),o(!1),f(!1),h([]),re.success("Market report removed")},onError:X=>{re.error(X.message||"Failed to remove market report")}});return!a||P?null:I!=null&&I.market_report_enabled&&!l?e.jsxs(Ne,{className:"overflow-hidden",children:[e.jsx(Ct,{className:"pb-2",children:e.jsxs(At,{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(Wl,{className:"h-4 w-4 text-primary"})}),"Monthly Market Report",e.jsx(Be,{variant:"default",className:"text-xs ml-auto",children:"Active"})]})}),e.jsxs(Ie,{className:"pt-0 space-y-2",children:[e.jsx("div",{className:"flex flex-wrap gap-1.5 text-xs",children:((Y=I.market_report_cities)==null?void 0:Y.length)>0?I.market_report_cities.map(X=>e.jsxs(Be,{variant:"outline",className:"gap-1",children:[e.jsx(ci,{className:"h-3 w-3"}),X]},X)):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($,{variant:"outline",size:"sm",onClick:()=>U.mutate(),disabled:U.isPending,className:"flex-1",children:[U.isPending?e.jsx(kt,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(Ca,{className:"h-4 w-4 mr-1"}),"Preview"]}),e.jsxs($,{variant:"default",size:"sm",onClick:()=>W.mutate(),disabled:W.isPending,className:"flex-1",children:[W.isPending?e.jsx(kt,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(Yr,{className:"h-4 w-4 mr-1"}),"Send Now"]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx($,{variant:"outline",size:"sm",onClick:R,className:"flex-1",children:"Manage"}),e.jsxs($,{variant:"destructive",size:"sm",onClick:()=>G.mutate(),disabled:G.isPending,className:"flex-1",children:[G.isPending?e.jsx(kt,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(gr,{className:"h-4 w-4 mr-1"}),"Remove"]})]}),e.jsx(zs,{open:y,onOpenChange:v,children:e.jsxs(Os,{className:"max-w-3xl max-h-[85vh] overflow-hidden flex flex-col",children:[e.jsx(Us,{children:e.jsxs(Bs,{className:"flex items-center gap-2",children:[e.jsx(Wl,{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:b}})}),e.jsxs("div",{className:"flex gap-2 pt-4 border-t",children:[e.jsxs($,{onClick:()=>{v(!1),W.mutate()},disabled:W.isPending,className:"flex-1",children:[W.isPending?e.jsx(kt,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(Yr,{className:"h-4 w-4 mr-1"}),"Send to ",t]}),e.jsx($,{variant:"outline",onClick:()=>v(!1),children:"Close"})]})]})})]})]}):l?e.jsxs(Ne,{children:[e.jsx(Ct,{className:"pb-3",children:e.jsxs(At,{className:"text-base flex items-center gap-2",children:[e.jsx(Wl,{className:"h-4 w-4 text-primary"}),"Market Report for ",t]})}),e.jsxs(Ie,{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(ee,{children:"Send Monthly Report"}),e.jsx(Sn,{checked:m,onCheckedChange:f})]}),m&&e.jsxs("div",{children:[e.jsxs(ee,{className:"flex items-center gap-1 mb-1.5",children:[e.jsx(ci,{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(pe,{ref:S,value:c,onChange:X=>{d(X.target.value),x(!0)},onFocus:()=>x(!0),placeholder:"Type to search cities...",onKeyDown:X=>{X.key==="Enter"&&(X.preventDefault(),O.length>0?D(O[0]):D())}}),e.jsx(Tl,{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($,{type:"button",variant:"outline",size:"sm",onClick:()=>D(),children:e.jsx(dn,{className:"h-4 w-4"})})]}),g&&O.length>0&&e.jsx("div",{ref:C,className:"absolute z-50 mt-1 w-full max-h-60 overflow-y-auto rounded-md border bg-popover shadow-md",children:O.map(X=>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:()=>D(X),children:[e.jsx(ci,{className:"h-3 w-3 text-muted-foreground flex-shrink-0"}),X]},X))})]}),u.length>0&&e.jsx("div",{className:"flex flex-wrap gap-1 mt-2",children:u.map(X=>e.jsxs(Be,{variant:"secondary",className:"gap-1",children:[X,e.jsx("button",{onClick:()=>h(u.filter(ae=>ae!==X)),children:e.jsx(gr,{className:"h-3 w-3"})})]},X))})]}),e.jsxs("div",{className:"flex gap-2 pt-2",children:[e.jsxs($,{onClick:()=>V.mutate(),disabled:V.isPending,className:"flex-1",children:[V.isPending?e.jsx(kt,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(tl,{className:"h-4 w-4 mr-1"}),"Save"]}),e.jsx($,{variant:"outline",onClick:()=>o(!1),children:"Cancel"})]})]})]}):e.jsx(Ne,{className:"overflow-hidden",children:e.jsx(Ie,{className:"p-4",children:e.jsxs("button",{onClick:R,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(Wl,{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 TUn({contactId:s,contactName:t}){const n=Vt(),[r,a]=j.useState(""),{data:i,isLoading:l}=tt({queryKey:["contact-email-prefs",s],enabled:!!s,queryFn:async()=>{const{data:d,error:u}=await q.from("innercircle_contacts").select("email, email_opt_out, email_opt_out_at, email_opt_out_reason").eq("id",s).single();if(u)throw u;return d}});j.useEffect(()=>{a((i==null?void 0:i.email_opt_out_reason)||"")},[i==null?void 0:i.email_opt_out_reason]);const o=ft({mutationFn:async({optOut:d,reasonText:u})=>{const{error:h}=await q.from("innercircle_contacts").update({email_opt_out:d,email_opt_out_at:d?new Date().toISOString():null,email_opt_out_reason:d&&u.trim()||null}).eq("id",s);if(h)throw h;return d},onSuccess:d=>{n.invalidateQueries({queryKey:["contact-email-prefs",s]}),n.invalidateQueries({queryKey:["contact",s]}),n.invalidateQueries({queryKey:["innercircle-contacts"]}),re.success(d?`${t} will no longer receive newsletters or marketing emails`:`${t} is opted back in to marketing emails`)},onError:d=>re.error(d.message)}),c=!!(i!=null&&i.email_opt_out);return e.jsxs(Ne,{children:[e.jsx(Ct,{className:"pb-3",children:e.jsxs(At,{className:"flex items-center gap-2 text-base",children:[e.jsx(XI,{className:"h-4 w-4"}),"Email Preferences",c&&e.jsx(Be,{variant:"destructive",className:"ml-1",children:"Opted out"})]})}),e.jsx(Ie,{className:"space-y-4",children:l?e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(kt,{className:"h-4 w-4 animate-spin"})," Loading…"]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-start justify-between gap-4",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(ee,{htmlFor:"opt-out-toggle",className:"text-sm font-medium",children:"Opt out of newsletters & marketing emails"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"When on, this contact is skipped in newsletters, mass emails, drip campaigns, market reports and listing blasts. One-to-one emails still work."})]}),e.jsx(Sn,{id:"opt-out-toggle",checked:c,disabled:o.isPending,onCheckedChange:d=>o.mutate({optOut:d,reasonText:r})})]}),c&&e.jsxs("div",{className:"space-y-2 rounded-lg border bg-muted/40 p-3",children:[e.jsx(ee,{htmlFor:"opt-out-reason",className:"text-xs",children:"Reason (optional)"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(pe,{id:"opt-out-reason",value:r,placeholder:"e.g. Asked to stop monthly newsletter",onChange:d=>a(d.target.value)}),e.jsx($,{variant:"outline",size:"sm",disabled:o.isPending||r===((i==null?void 0:i.email_opt_out_reason)||""),onClick:()=>o.mutate({optOut:!0,reasonText:r}),children:"Save"})]}),(i==null?void 0:i.email_opt_out_at)&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Opted out ",en(new Date(i.email_opt_out_at),"MMM d, yyyy")]})]})]})})]})}function MUn(s){return tt({queryKey:["contact-drip-activity",s],queryFn:async()=>{if(!s)return{enrollments:[],stepLogs:[]};const{data:t,error:n}=await q.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(n)throw console.error("[ContactDripActivity] enrollments error",n),n;const r=(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 q.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(r.length>0){const{data:c,error:d}=await q.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",r).order("sent_at",{ascending:!1});d?console.error("[ContactDripActivity] step log error",d):o=(c||[]).map(u=>{var h;return{...u,campaign:{name:((h=i.get(u.campaign_id))==null?void 0:h.name)??""}}})}return{enrollments:l,stepLogs:o}},enabled:!!s})}function PUn(s){switch(s){case"active":return e.jsx(Be,{variant:"secondary",className:"bg-emerald-500/10 text-emerald-600 border-emerald-500/20",children:"Active"});case"paused":return e.jsx(Be,{variant:"secondary",className:"bg-amber-500/10 text-amber-600 border-amber-500/20",children:"Paused"});case"completed":return e.jsx(Be,{variant:"secondary",className:"bg-sky-500/10 text-sky-600 border-sky-500/20",children:"Completed"});case"exited":return e.jsx(Be,{variant:"outline",children:"Exited"});default:return e.jsx(Be,{variant:"outline",children:s})}}function MCt(s){return s==="sent"?e.jsx(qr,{className:"h-4 w-4 text-emerald-500"}):s==="failed"?e.jsx(wl,{className:"h-4 w-4 text-destructive"}):s==="skipped"?e.jsx(Tv,{className:"h-4 w-4 text-muted-foreground"}):e.jsx(da,{className:"h-4 w-4 text-muted-foreground"})}function IUn({contactId:s}){const t=Qn(),{data:n,isLoading:r}=MUn(s),[a,i]=j.useState(null);if(r)return null;const l=(n==null?void 0:n.enrollments)||[],o=(n==null?void 0:n.stepLogs)||[];return l.length===0&&o.length===0?null:e.jsxs(Ne,{children:[e.jsx(Ct,{children:e.jsxs(At,{className:"flex items-center gap-2 text-base",children:[e.jsx(tL,{className:"h-5 w-5 text-emerald-500"}),"Drip Campaign Activity"]})}),e.jsxs(Ie,{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(tL,{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"}),PUn(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: ",mu(new Date(c.next_send_at),{addSuffix:!0})]}),c.completed_at&&e.jsxs(e.Fragment,{children:[" · Completed ",mu(new Date(c.completed_at),{addSuffix:!0})]}),c.exited_at&&!c.completed_at&&e.jsxs(e.Fragment,{children:[" · ",c.exit_reason||"Exited"," ",mu(new Date(c.exited_at),{addSuffix:!0})]})]})]}),e.jsx(Di,{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,u;return e.jsxs(zs,{open:(a==null?void 0:a.id)===c.id,onOpenChange:h=>!h&&i(null),children:[e.jsx(jl,{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:MCt(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(eo,{className:"h-3 w-3 text-muted-foreground flex-shrink-0"}):e.jsx(mn,{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"," · ",en(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(Os,{className:"max-w-lg",children:[e.jsx(Us,{children:e.jsxs(Bs,{className:"flex items-center gap-2",children:[MCt(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:((u=c.campaign)==null?void 0:u.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:en(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($,{variant:"ghost",size:"sm",className:"w-full text-xs",onClick:()=>t("/mission-control/smart-drips"),children:"View all in Smart Drips"})]})]})]})]})}const t$e=1e3,LUn=5e4;async function mue(s){const t=[];for(let n=0;n{const n=t.id,r=await mue(()=>{let f=q.from("gmail_sent_emails").select("id, contact_id, to_email, subject, sent_at, source").eq("user_id",n).or("source.is.null,source.neq.drip_campaign").order("sent_at",{ascending:!1});return s&&(f=f.eq("contact_id",s)),f}),a=await mue(()=>{let f=q.from("bulk_email_sends").select("id, contact_id, contact_email, subject, sent_at, source, opened_at, clicked_at").eq("user_id",n).order("sent_at",{ascending:!1});return s&&(f=f.eq("contact_id",s)),f}),i=await mue(()=>q.from("email_campaigns").select("id, subject").eq("user_id",n).order("id")),l=i.map(f=>f.id),o=new Map(i.map(f=>[f.id,f.subject]));let c=[];if(l.length>0)for(let g=0;g{let v=q.from("email_campaign_recipients").select("id, contact_id, email, sent_at, campaign_id, opened_at, clicked_at").in("campaign_id",x).eq("status","sent").not("sent_at","is",null).order("sent_at",{ascending:!1});return s&&(v=v.eq("contact_id",s)),v});c.push(...y)}const d=r.map(f=>({id:`g-${f.id}`,channel:f.source==="portal_invite"?"Client Portal Invite":String(f.source||"").startsWith("card_studio")?"Card Studio":"Gmail",subject:f.subject,to_email:f.to_email,contact_id:f.contact_id,sent_at:f.sent_at,source:f.source})),u=a.map(f=>({id:`b-${f.id}`,channel:"Mass Email",subject:f.subject,to_email:f.contact_email,contact_id:f.contact_id,sent_at:f.sent_at,source:f.source,opened_at:f.opened_at,clicked_at:f.clicked_at})),h=c.map(f=>({id:`c-${f.id}`,channel:"Campaign",subject:o.get(f.campaign_id)||"(campaign)",to_email:f.email,contact_id:f.contact_id,sent_at:f.sent_at,source:null,campaign_id:f.campaign_id,opened_at:f.opened_at,clicked_at:f.clicked_at})),m=[...d,...u,...h];return m.sort((f,g)=>f.sent_at0&&e.jsx(Be,{variant:"secondary",className:"ml-1",children:t.length})]})}),e.jsx(Ie,{children:n?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(mn,{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(Be,{variant:"outline",className:`text-xs ${RUn[l.channel]}`,children:l.channel}),e.jsx("span",{className:"text-xs text-muted-foreground",children:en(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($,{variant:"ghost",size:"sm",className:"w-full mt-3",onClick:()=>a(!r),children:r?"Show less":`Show all ${t.length}`}),e.jsx("div",{className:"mt-3 pt-3 border-t",children:e.jsx(wr,{to:"/mission-control/sent-emails",className:"text-xs text-primary hover:underline",children:"View all sent emails →"})})]})})]})}const FUn={alabama:"AL",alaska:"AK",arizona:"AZ",arkansas:"AR",california:"CA",colorado:"CO",connecticut:"CT",delaware:"DE",florida:"FL",georgia:"GA",hawaii:"HI",idaho:"ID",illinois:"IL",indiana:"IN",iowa:"IA",kansas:"KS",kentucky:"KY",louisiana:"LA",maine:"ME",maryland:"MD",massachusetts:"MA",michigan:"MI",minnesota:"MN",mississippi:"MS",missouri:"MO",montana:"MT",nebraska:"NE",nevada:"NV","new hampshire":"NH","new jersey":"NJ","new mexico":"NM","new york":"NY","north carolina":"NC","north dakota":"ND",ohio:"OH",oklahoma:"OK",oregon:"OR",pennsylvania:"PA","rhode island":"RI","south carolina":"SC","south dakota":"SD",tennessee:"TN",texas:"TX",utah:"UT",vermont:"VT",virginia:"VA",washington:"WA","west virginia":"WV",wisconsin:"WI",wyoming:"WY","district of columbia":"DC","puerto rico":"PR"},OUn={avenue:"ave",boulevard:"blvd",circle:"cir",court:"ct",drive:"dr",highway:"hwy",lane:"ln",parkway:"pkwy",place:"pl",road:"rd",square:"sq",street:"st",terrace:"ter",trail:"trl",way:"way","suite ":"ste ","unit ":"unit ","apartment ":"apt ","#":"unit "};function zUn(s){if(!s)return null;const t=s.trim();if(/^[A-Za-z]{2}$/.test(t))return t.toUpperCase();const n=t.toLowerCase();return FUn[n]||null}function BUn(s){return!s||!s.trim().match(/^\d{5}(-?\d{4})?$/)?null:s.trim().split("-")[0]}function $Un(s){let t=s.toLowerCase();for(const[n,r]of Object.entries(OUn))t=t.replace(new RegExp(`\\b${n}\\b`,"g"),r);return t}function UUn(s){const t=s.toLowerCase(),n=[/\b(apt|apartment|unit|suite|ste|#)\s*([A-Za-z0-9\-]+)\b/,/\b(floor|fl)\s*([A-Za-z0-9\-]+)\b/];for(const r of n){const a=t.match(r);if(a){const i=a[0].replace(/#/,"unit ").trim();return{street:s.replace(new RegExp(a[0],"i"),"").replace(/\s+/g," ").trim(),unit:i}}}return{street:s,unit:null}}function hJt(s,t,n,r){const a=[s,t,n,r].filter(Boolean).join(", ").trim(),i=zUn(n),l=BUn(r);let o=null,c=null;if(s){const g=UUn(s.trim());o=g.street,c=g.unit}const d=(t==null?void 0:t.trim())||null,u=[];o&&u.push($Un(o)),c&&u.push(c.toLowerCase().replace(/\s+/g,"")),d&&u.push(d.toLowerCase()),i&&u.push(i.toLowerCase()),l&&u.push(l);const h=u.join(" | "),m=[!!o,!!d,!!i,!!l].filter(Boolean).length;let f="low";return m>=4?f="high":m>=2&&(f="medium"),{original:a,normalized:h,streetAddress:o,unitNumber:c,city:d,state:i,postalCode:l,confidence:f}}async function Ait(){const{data:{user:s},error:t}=await q.auth.getUser();if(t||!s)throw new Error("Not authenticated");return s.id}async function qUn(s){const{data:t,error:n}=await q.from("contact_properties").select("*, property:properties(*)").eq("contact_id",s).order("created_at",{ascending:!1});if(n)throw new Error(n.message);const r=t??[],a=Array.from(new Set(r.map(o=>o.property_id).filter(Boolean)));let i=[],l=[];if(a.length){const[o,c]=await Promise.all([q.from("property_field_locks").select("*").in("property_id",a),q.from("property_enrichment_events").select("*").in("property_id",a).order("created_at",{ascending:!1})]);if(o.error)throw new Error(o.error.message);if(c.error)throw new Error(c.error.message);i=o.data??[],l=c.data??[]}return r.map(o=>({property:o.property,relationship:o,locks:i.filter(c=>c.property_id===o.property_id),events:l.filter(c=>c.property_id===o.property_id)}))}async function VUn(s){const t=await Ait(),{data:n,error:r}=await q.from("properties").insert({...s,owner_user_id:t}).select().single();if(r)throw new Error(r.message);return n}async function HUn(s,t,n={}){const a={owner_user_id:await Ait(),contact_id:s,property_id:t,relationship_type:n.relationship_type??"unknown",is_primary_residence:n.is_primary_residence??!1,ownership_status:n.ownership_status??"unknown",relationship_started_at:n.relationship_started_at??null,relationship_ended_at:n.relationship_ended_at??null},{data:i,error:l}=await q.from("contact_properties").insert(a).select().single();if(l)throw new Error(l.message);return i}async function GUn(s){const{error:t}=await q.from("contact_properties").delete().eq("id",s);if(t)throw new Error(t.message)}async function PCt(s,t){const{data:n,error:r}=await q.from("contact_properties").update(t).eq("id",s).select().single();if(r)throw new Error(r.message);return n}function iA(s){return s==null||Number.isNaN(s)?"—":new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(s)}function oA(s,t=""){return s==null||Number.isNaN(s)?"—":`${new Intl.NumberFormat("en-US").format(s)}${t}`}function ICt(s){return{never_enriched:"Never enriched",pending:"Pending",enriched:"Enriched",partially_enriched:"Partially enriched",not_found:"Not found",unsupported_active_listing:"Active listing — unsupported",incomplete_address:"Incomplete address",needs_review:"Needs review",failed:"Failed"}[s]??s}async function _Cr(){const{data:{user:s}}=await q.auth.getUser();if(!s)throw new Error("Not authenticated");const t=s.id,n=new Date;n.setDate(n.getDate()-90);const r=n.toISOString(),[{count:a,error:i},{count:l,error:o},{count:c,error:d},{count:u,error:h},{count:m,error:f},{count:g,error:x},{count:y,error:v},{count:b,error:w},{count:S,error:C},{count:E,error:I}]=await Promise.all([q.from("innercircle_contacts").select("id",{count:"exact",head:!0}).eq("owner_user_id",t).not("address","is",null),q.from("properties").select("id",{count:"exact",head:!0}).eq("owner_user_id",t),q.from("properties").select("id",{count:"exact",head:!0}).eq("owner_user_id",t).eq("enrichment_status","enriched"),q.from("properties").select("id",{count:"exact",head:!0}).eq("owner_user_id",t).eq("enrichment_status","needs_review"),q.from("properties").select("id",{count:"exact",head:!0}).eq("owner_user_id",t).eq("enrichment_status","incomplete_address"),q.from("properties").select("id",{count:"exact",head:!0}).eq("owner_user_id",t).eq("enrichment_status","failed"),q.from("properties").select("id",{count:"exact",head:!0}).eq("owner_user_id",t).or(`last_enriched_at.is.null,last_enriched_at.lt.${r}`),q.from("properties").select("id",{count:"exact",head:!0}).eq("owner_user_id",t).eq("owner_occupied_status","non_owner_occupied"),q.from("properties").select("id",{count:"exact",head:!0}).eq("owner_user_id",t).is("estimated_value",null),q.rpc("count_contacts_missing_property_data",{owner_id:t})]),P=[i,o,d,h,f,x,v,w,C,I].filter(Boolean);if(P.length)throw new Error(P.map(R=>R==null?void 0:R.message).join("; "));return{contactsWithAddresses:a??0,propertiesLinked:l??0,contactsMissingPropertyData:E??0,propertiesEnriched:c??0,propertiesNeedingReview:u??0,incompleteAddresses:m??0,enrichmentFailures:g??0,staleProperties:y??0,possibleNonOwnerOccupied:b??0,propertiesMissingValuation:S??0}}async function wCr(s={}){const{data:{user:t}}=await q.auth.getUser();if(!t)throw new Error("Not authenticated");const n=s.limit??25,r=s.offset??0,a=!!(s.enrichmentStatus&&s.enrichmentStatus!=="all")||!!s.staleBefore,i=s.missingOnly?"":a?"!inner":"",l=s.missingOnly?"":a?"!inner":"";let o=q.from("innercircle_contacts").select(`id, first_name, last_name, address, city, state, zip_code, zip, contact_properties${i}(id, property_id, properties${l}(id, enrichment_status, last_enriched_at))`,{count:"exact"}).eq("owner_user_id",t.id).not("address","is",null);s.city&&(o=o.ilike("city",`%${s.city}%`)),s.state&&(o=o.ilike("state",`%${s.state}%`)),s.postalCode&&(o=o.or(`zip_code.ilike.%${s.postalCode}%,zip.ilike.%${s.postalCode}%`)),s.missingOnly?o=o.is("contact_properties",null):a&&(s.enrichmentStatus&&s.enrichmentStatus!=="all"&&(o=o.eq("contact_properties.properties.enrichment_status",s.enrichmentStatus)),s.staleBefore&&(o=o.or(`last_enriched_at.is.null,last_enriched_at.lt.${s.staleBefore}`,{referencedTable:"contact_properties.properties"})));const{data:c,error:d,count:u}=await o.order("last_name",{ascending:!0}).range(r,r+n-1);if(d)throw new Error(d.message);return{contacts:(c??[]).map(m=>{const f=Array.isArray(m.contact_properties)?m.contact_properties[0]:m.contact_properties,g=f==null?void 0:f.properties;return{id:m.id,first_name:m.first_name,last_name:m.last_name,address:m.address,city:m.city,state:m.state,zip_code:m.zip_code??m.zip,linked_property_id:(f==null?void 0:f.property_id)??null,enrichment_status:(g==null?void 0:g.enrichment_status)??"never_enriched",last_enriched_at:(g==null?void 0:g.last_enriched_at)??null}}),count:u??0}}function WUn(s){switch(s){case"verified":return"default";case"high":return"default";case"medium":return"secondary";case"low":return"outline";default:return"outline"}}async function jCr(s,t={}){const n=await Ait();if(!s.length)throw new Error("Select at least one contact");const{data:r,error:a}=await q.from("innercircle_contacts").select("id, address, city, state, zip_code, zip").eq("owner_user_id",n).in("id",s);if(a)throw new Error(a.message);const i=r??[];if(!i.length)throw new Error("No matching contacts found");const{data:l,error:o}=await q.from("property_enrichment_runs").insert({owner_user_id:n,name:t.name??null,requested_source:t.requestedSource??"zillow_chatgpt_app",status:"ready",total_contacts:i.length,pending_count:i.length}).select("id").single();if(o)throw new Error(o.message);const c=i.map(u=>({owner_user_id:n,enrichment_run_id:l.id,contact_id:u.id,normalized_address:hJt(u.address,u.city,u.state,u.zip_code??u.zip).normalized||null,status:"pending"})),{error:d}=await q.from("property_enrichment_items").insert(c);if(d)throw new Error(d.message);return{runId:l.id,count:i.length}}const mJt=[{value:"owner",label:"Owner"},{value:"co_owner",label:"Co-owner"},{value:"household_member",label:"Household member"},{value:"former_owner",label:"Former owner"},{value:"buyer_prospect",label:"Buyer prospect"},{value:"seller_prospect",label:"Seller prospect"},{value:"tenant",label:"Tenant"},{value:"landlord",label:"Landlord"},{value:"unknown",label:"Unknown"}],fJt=[{value:"current",label:"Current"},{value:"former",label:"Former"},{value:"possible",label:"Possible"},{value:"unknown",label:"Unknown"}];function KUn({detail:s,onMutate:t}){const{property:n,relationship:r,events:a}=s,[i,l]=j.useState(!1),[o,c]=j.useState(!1),[d,u]=j.useState(r.relationship_type),[h,m]=j.useState(r.ownership_status),[f,g]=j.useState(r.is_primary_residence),x=ft({mutationFn:()=>PCt(r.id,{relationship_type:d,ownership_status:h,is_primary_residence:f}),onSuccess:()=>{re.success("Property relationship updated"),c(!1),t()},onError:C=>re.error(C instanceof Error?C.message:"Update failed")}),y=ft({mutationFn:()=>GUn(r.id),onSuccess:()=>{re.success("Property unlinked"),t()},onError:C=>re.error(C instanceof Error?C.message:"Unlink failed")}),v=a[0],b=n.primary_data_source||(v==null?void 0:v.source_name)||"Manual",w=n.last_enriched_at||(v==null?void 0:v.retrieved_at)||n.updated_at,S=[{id:"overview",title:"Property Overview",icon:VI,rows:[{label:"Property type",value:n.property_type||"—"},{label:"Bedrooms",value:oA(n.bedrooms)},{label:"Bathrooms",value:oA(n.bathrooms,"+")},{label:"Living area",value:oA(n.living_area_square_feet," sq ft")},{label:"Lot size",value:n.lot_size?`${oA(n.lot_size)} ${n.lot_size_units||""}`:"—"},{label:"Year built",value:oA(n.year_built)},{label:"Parcel ID",value:n.parcel_id||"—"},{label:"County",value:n.county||"—"}]},{id:"value",title:"Value & Valuation",icon:ru,rows:[{label:"Estimated value",value:iA(n.estimated_value)},{label:"Value range",value:n.estimated_value_low&&n.estimated_value_high?`${iA(n.estimated_value_low)} – ${iA(n.estimated_value_high)}`:"—"},{label:"Rent estimate",value:iA(n.rent_estimate)},{label:"Data confidence",value:n.data_confidence}]},{id:"tax",title:"Tax Information",icon:Mf,rows:[{label:"Tax-assessed value",value:iA(n.tax_assessed_value)},{label:"Assessed year",value:oA(n.tax_assessed_year)},{label:"Annual property tax",value:iA(n.latest_annual_property_tax)},{label:"Tax rate",value:n.property_tax_rate?`${(n.property_tax_rate*100).toFixed(2)}%`:"—"}]},{id:"ownership",title:"Ownership & Relationship",icon:sl,rows:[{label:"Relationship",value:r.relationship_type.replace(/_/g," ")},{label:"Ownership status",value:r.ownership_status},{label:"Primary residence",value:r.is_primary_residence?"Yes":"No"},{label:"Owner-occupied status",value:n.owner_occupied_status.replace(/_/g," ")},{label:"Foreclosure status",value:n.foreclosure_status||"—"}]},{id:"sale",title:"Sale History",icon:Lw,rows:[{label:"Last sale price",value:iA(n.last_sale_price)},{label:"Last sale date",value:n.last_sale_date||"—"}]},{id:"sources",title:"Data Sources",icon:Iq,rows:[{label:"Primary source",value:b},{label:"Source URL",value:n.source_property_url?"View source":"—"},{label:"Last updated",value:w?new Date(w).toLocaleDateString():"—"}]},{id:"history",title:"Enrichment History",icon:Ta,rows:a.length?a.slice(0,5).map(C=>({label:new Date(C.created_at).toLocaleDateString(),value:`${C.source_name} — ${ICt(C.status)}`})):[{label:"History",value:"No enrichment events yet"}]}];return e.jsxs(Ne,{className:"overflow-hidden",children:[e.jsx(Ct,{className:"pb-3",children:e.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-start sm:justify-between",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsxs(At,{className:"flex items-start gap-2 text-base",children:[e.jsx(va,{className:"mt-0.5 h-4 w-4 text-primary"}),e.jsx("span",{children:n.street_address||n.normalized_address})]}),e.jsxs("div",{className:"flex items-center gap-1 text-sm text-muted-foreground",children:[e.jsx(ci,{className:"h-3.5 w-3.5"}),[n.city,n.state,n.postal_code].filter(Boolean).join(", ")]})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[r.is_primary_residence&&e.jsxs(Be,{variant:"default",className:"gap-1",children:[e.jsx(Ja,{className:"h-3 w-3"})," Primary"]}),e.jsx(Be,{variant:WUn(n.data_confidence),children:n.data_confidence}),e.jsx(Be,{variant:"outline",children:ICt(n.enrichment_status)})]})]})}),e.jsxs(Ie,{className:"space-y-4",children:[e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2 lg:grid-cols-4",children:[e.jsx(fue,{label:"Estimated value",value:iA(n.estimated_value)}),e.jsx(fue,{label:"Tax assessed",value:iA(n.tax_assessed_value)}),e.jsx(fue,{label:"Bed / Bath",value:`${oA(n.bedrooms)} / ${oA(n.bathrooms)}`}),e.jsx(fue,{label:"Sq ft",value:oA(n.living_area_square_feet)})]}),e.jsxs(j1,{open:i,onOpenChange:l,children:[e.jsx(N1,{asChild:!0,children:e.jsxs($,{variant:"ghost",size:"sm",className:"w-full justify-between",children:[e.jsx("span",{children:"Property details"}),e.jsx(Tl,{className:Pt("h-4 w-4 transition-transform",i&&"rotate-180")})]})}),e.jsx(k1,{className:"space-y-4 pt-2",children:S.map(C=>e.jsxs("div",{className:"rounded-xl border border-border/70 bg-muted/30 p-4",children:[e.jsxs("h4",{className:"mb-3 flex items-center gap-2 text-sm font-semibold",children:[e.jsx(C.icon,{className:"h-4 w-4 text-primary"}),C.title]}),e.jsx("div",{className:"grid gap-2 sm:grid-cols-2",children:C.rows.map((E,I)=>e.jsxs("div",{className:"flex flex-col",children:[e.jsx("span",{className:"text-[11px] uppercase tracking-wide text-muted-foreground",children:E.label}),e.jsx("span",{className:"text-sm font-medium",children:E.label==="Source URL"&&E.value!=="—"?e.jsx("a",{href:n.source_property_url||"#",target:"_blank",rel:"noopener noreferrer",className:"text-primary underline",children:E.value}):E.value})]},I))})]},C.id))})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs(zs,{open:o,onOpenChange:c,children:[e.jsx(jl,{asChild:!0,children:e.jsxs($,{variant:"outline",size:"sm",children:[e.jsx(wf,{className:"mr-1 h-3.5 w-3.5"})," Edit relationship"]})}),e.jsxs(Os,{className:"sm:max-w-md",children:[e.jsx(Us,{children:e.jsx(Bs,{children:"Edit property relationship"})}),e.jsxs("div",{className:"space-y-4 py-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Relationship type"}),e.jsxs(ms,{value:d,onValueChange:C=>u(C),children:[e.jsx(us,{children:e.jsx(fs,{})}),e.jsx(hs,{children:mJt.map(C=>e.jsx(Ge,{value:C.value,children:C.label},C.value))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Ownership status"}),e.jsxs(ms,{value:h,onValueChange:C=>m(C),children:[e.jsx(us,{children:e.jsx(fs,{})}),e.jsx(hs,{children:fJt.map(C=>e.jsx(Ge,{value:C.value,children:C.label},C.value))})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("input",{id:`primary-${r.id}`,type:"checkbox",checked:f,onChange:C=>g(C.target.checked),className:"h-4 w-4 rounded border-border"}),e.jsx(ee,{htmlFor:`primary-${r.id}`,children:"Primary residence"})]})]}),e.jsxs(Ar,{children:[e.jsx($,{variant:"outline",onClick:()=>c(!1),children:"Cancel"}),e.jsx($,{onClick:()=>x.mutate(),disabled:x.isPending,children:"Save changes"})]})]})]}),e.jsxs($,{variant:"outline",size:"sm",onClick:()=>PCt(r.id,{is_primary_residence:!r.is_primary_residence}).then(()=>{re.success(r.is_primary_residence?"Removed primary residence":"Marked as primary residence"),t()}).catch(C=>re.error(C.message)),children:[e.jsx(Ja,{className:"mr-1 h-3.5 w-3.5"}),r.is_primary_residence?"Unmark primary":"Mark primary"]}),e.jsxs($,{variant:"outline",size:"sm",className:"text-destructive hover:bg-destructive/10",onClick:()=>y.mutate(),disabled:y.isPending,children:[e.jsx(Sv,{className:"mr-1 h-3.5 w-3.5"})," Unlink property"]})]})]})]})}function fue({label:s,value:t}){return e.jsxs("div",{className:"rounded-xl border border-border/70 bg-muted/30 p-3",children:[e.jsx("p",{className:"text-[11px] uppercase tracking-wide text-muted-foreground",children:s}),e.jsx("p",{className:"text-sm font-semibold",children:t})]})}function YUn({contactId:s,defaultAddress:t,defaultCity:n,defaultState:r,defaultZip:a,onAdded:i}){const[l,o]=j.useState(!1),[c,d]=j.useState(t||""),[u,h]=j.useState(n||""),[m,f]=j.useState(r||""),[g,x]=j.useState(a||""),[y,v]=j.useState("owner"),[b,w]=j.useState("current"),[S,C]=j.useState(!1),E=ft({mutationFn:async()=>{const I=[c,u,m,g].filter(Boolean).join(", "),P=hJt(c,u,m,g);if(!P.normalized)throw new Error("Could not normalize address. Please check the fields.");const R=await VUn({original_address:I,normalized_address:P.normalized,street_address:P.streetAddress,unit_number:P.unitNumber,city:P.city,state:P.state,postal_code:P.postalCode,property_type:null,enrichment_status:"never_enriched",data_confidence:"unknown",owner_occupied_status:"unknown",photo_usage_authorized:!1,external_ids:{}});await HUn(s,R.id,{relationship_type:y,ownership_status:b,is_primary_residence:S})},onSuccess:()=>{re.success("Property added"),o(!1),d(t||""),h(n||""),f(r||""),x(a||""),i()},onError:I=>re.error(I instanceof Error?I.message:"Failed to add property")});return e.jsxs(zs,{open:l,onOpenChange:o,children:[e.jsx(jl,{asChild:!0,children:e.jsxs($,{size:"sm",children:[e.jsx(dn,{className:"mr-1 h-4 w-4"})," Add property"]})}),e.jsxs(Os,{className:"sm:max-w-lg",children:[e.jsx(Us,{children:e.jsx(Bs,{children:"Add property to contact"})}),e.jsxs("div",{className:"grid gap-4 py-2",children:[e.jsxs("div",{className:"grid gap-2",children:[e.jsx(ee,{htmlFor:"pi-street",children:"Street address"}),e.jsx(pe,{id:"pi-street",value:c,onChange:I=>d(I.target.value),placeholder:"123 Main St"})]}),e.jsxs("div",{className:"grid gap-2 sm:grid-cols-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"pi-city",children:"City"}),e.jsx(pe,{id:"pi-city",value:u,onChange:I=>h(I.target.value),placeholder:"City"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"pi-state",children:"State"}),e.jsx(pe,{id:"pi-state",value:m,onChange:I=>f(I.target.value),placeholder:"State"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"pi-zip",children:"ZIP"}),e.jsx(pe,{id:"pi-zip",value:g,onChange:I=>x(I.target.value),placeholder:"ZIP"})]})]}),e.jsxs("div",{className:"grid gap-2 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Relationship type"}),e.jsxs(ms,{value:y,onValueChange:I=>v(I),children:[e.jsx(us,{children:e.jsx(fs,{})}),e.jsx(hs,{children:mJt.map(I=>e.jsx(Ge,{value:I.value,children:I.label},I.value))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Ownership status"}),e.jsxs(ms,{value:b,onValueChange:I=>w(I),children:[e.jsx(us,{children:e.jsx(fs,{})}),e.jsx(hs,{children:fJt.map(I=>e.jsx(Ge,{value:I.value,children:I.label},I.value))})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("input",{id:"pi-primary",type:"checkbox",checked:S,onChange:I=>C(I.target.checked),className:"h-4 w-4 rounded border-border"}),e.jsx(ee,{htmlFor:"pi-primary",children:"Primary residence"})]})]}),e.jsxs(Ar,{children:[e.jsx($,{variant:"outline",onClick:()=>o(!1),children:"Cancel"}),e.jsx($,{onClick:()=>E.mutate(),disabled:E.isPending||!c,children:E.isPending?"Saving...":"Save property"})]})]})]})}function ZUn({contactId:s,contactAddress:t,contactCity:n,contactState:r,contactZip:a}){const i=Vt(),{data:l,isLoading:o,error:c}=tt({queryKey:["contact-properties",s],queryFn:()=>qUn(s)}),d=()=>{i.invalidateQueries({queryKey:["contact-properties",s]})};if(o)return e.jsxs("div",{className:"space-y-4",children:[e.jsx(yn,{className:"h-10 w-48"}),e.jsx(yn,{className:"h-48 w-full"})]});if(c)return e.jsx(Ne,{className:"border-destructive/50 bg-destructive/5",children:e.jsxs(Ie,{className:"flex items-center gap-3 py-6",children:[e.jsx(wl,{className:"h-5 w-5 text-destructive"}),e.jsx("p",{className:"text-sm",children:"Could not load property intelligence."})]})});const u=l??[];return e.jsxs("div",{className:"space-y-5",children:[e.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-lg font-semibold",children:"Property Intelligence"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:'Home and property details for this contact. Property details are filled in from your ChatGPT assistant or entered by hand — the "Find person details" button at the top of the page looks up work and social info, not property data.'})]}),e.jsx(YUn,{contactId:s,defaultAddress:t||void 0,defaultCity:n||void 0,defaultState:r||void 0,defaultZip:a||void 0,onAdded:d})]}),u.length===0?e.jsx(Ne,{className:"border-dashed",children:e.jsxs(Ie,{className:"flex flex-col items-center justify-center py-10 text-center",children:[e.jsx(va,{className:"mb-3 h-10 w-10 text-muted-foreground/60"}),e.jsx("h4",{className:"text-base font-medium",children:"No properties linked yet"}),e.jsx("p",{className:"max-w-md text-sm text-muted-foreground",children:"Add the contact's property above, or run a ChatGPT enrichment to match addresses with public property data."}),t&&e.jsxs("p",{className:"mt-2 text-xs text-muted-foreground",children:["Contact address on file: ",t,n?`, ${n}`:"",r?`, ${r}`:"",a?` ${a}`:""]})]})}):e.jsx("div",{className:"space-y-4",children:u.map(h=>e.jsx(KUn,{detail:h,onMutate:d},h.relationship.id))})]})}function XUn({videoId:s}){var l;const{data:t,isLoading:n,error:r}=$9n(s);if(n)return e.jsxs("div",{className:"space-y-4",children:[e.jsx(yn,{className:"w-full aspect-video rounded-lg"}),e.jsx(yn,{className:"h-4 w-1/3"})]});if(r||!t||t.is_deleted)return e.jsxs("div",{className:"flex flex-col items-center justify-center py-8 text-center",children:[e.jsx(wl,{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 QUn({contactId:s}){const t=Qn(),[n,r]=j.useState(!1),{data:a,isLoading:i}=tt({queryKey:["deal-tasks","contact",s],queryFn:async()=>{const{data:h,error:m}=await q.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(m)throw m;return h},enabled:!!s}),l=async(h,m)=>{const f=m==="done"?"todo":"done";await q.from("deal_tasks").update({status:f,completed_at:f==="done"?new Date().toISOString():null}).eq("id",h),window.dispatchEvent(new CustomEvent("refetch-contact-tasks"))},{refetch:o}=tt({queryKey:["deal-tasks","contact",s],queryFn:async()=>{const{data:h,error:m}=await q.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(m)throw m;return h},enabled:!!s}),c={urgent:"🔴",high:"🟠",medium:"🟡",low:"🟢"},d=(a==null?void 0:a.filter(h=>h.status!=="done"))||[],u=(a==null?void 0:a.filter(h=>h.status==="done"))||[];return e.jsxs(Ne,{children:[e.jsx(Ct,{className:"pb-2",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(At,{className:"text-base flex items-center gap-2",children:[e.jsx(la,{className:"h-4 w-4"}),"Tasks",d.length>0&&e.jsx(Be,{variant:"secondary",className:"text-xs",children:d.length})]}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx($,{variant:"ghost",size:"sm",onClick:()=>t("/mission-control/tasks"),children:"View All"}),e.jsx($,{variant:"outline",size:"sm",onClick:()=>r(!0),children:e.jsx(dn,{className:"h-3.5 w-3.5"})})]})]})}),e.jsx(Ie,{className:"space-y-1",children:i?e.jsx(yn,{className:"h-8 w-full"}):d.length===0&&u.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(h=>e.jsxs("button",{onClick:async()=>{await l(h.id,h.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[h.priority]," ",h.title]}),h.due_date&&e.jsx("span",{className:"text-[10px] text-muted-foreground",children:en(new Date(h.due_date),"MMM d")})]},h.id)),u.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:[u.length," completed"]})})]})}),n&&e.jsx(JUn,{contactId:s,open:n,onOpenChange:h=>{r(h),h||o()}})]})}function JUn({contactId:s,open:t,onOpenChange:n}){const[r,a]=j.useState(""),[i,l]=j.useState("medium"),[o,c]=j.useState(),{data:d}=tt({queryKey:["session"],queryFn:async()=>{const{data:h}=await q.auth.getSession();return h.session}}),u=async()=>{var m;if(!r.trim()||!((m=d==null?void 0:d.user)!=null&&m.id))return;const{error:h}=await q.from("deal_tasks").insert([{owner_user_id:d.user.id,contact_id:s,title:r.trim(),priority:i,status:"todo",due_date:o?en(o,"yyyy-MM-dd"):null}]);if(h){console.error("Task create error:",h);return}n(!1)};return e.jsx(zs,{open:t,onOpenChange:n,children:e.jsxs(Os,{className:"sm:max-w-[400px]",children:[e.jsx(Us,{children:e.jsx(Bs,{children:"Add Task"})}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(ee,{children:"Title"}),e.jsx(pe,{value:r,onChange:h=>a(h.target.value),placeholder:"Task title...",onKeyDown:h=>h.key==="Enter"&&u()})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(ee,{children:"Priority"}),e.jsxs("select",{value:i,onChange:h=>l(h.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(ee,{children:"Due Date"}),e.jsx(pe,{type:"date",value:o?en(o,"yyyy-MM-dd"):"",onChange:h=>c(h.target.value?new Date(h.target.value+"T00:00:00"):void 0)})]})]}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx($,{variant:"outline",onClick:()=>n(!1),children:"Cancel"}),e.jsx($,{onClick:u,disabled:!r.trim(),children:"Create Task"})]})]})]})})}function eqn({contactId:s}){const t=Qn(),{data:n,isLoading:r}=tt({queryKey:["contact-linked-deals",s],queryFn:async()=>{const{data:a,error:i}=await q.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 r||!n||n.length===0?null:e.jsxs(Ne,{children:[e.jsx(Ct,{className:"pb-2",children:e.jsxs(At,{className:"text-base flex items-center gap-2",children:[e.jsx(Sx,{className:"h-4 w-4"}),"Linked Deals"]})}),e.jsx(Ie,{className:"space-y-2",children:n.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(Be,{variant:"outline",className:"text-[10px] capitalize",children:a.deal_type}),i&&e.jsxs(Be,{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(ei,{className:"h-4 w-4 text-muted-foreground group-hover:text-primary transition-colors flex-shrink-0"})]})},a.id)})})]})}function tqn(){var Ws,On,ds,gn;const{contactId:s}=Wi(),{isAdmin:t}=vs(),{hasIdx:n}=ng(),r=Qn(),[a]=gc(),i=a.get("search")||"",l=a.get("type")||"all",o=a.get("status")||a.get("filter")||"all",c=a.get("tags")||"",d=a.get("tagMode")==="all"?"all":"any",u=j.useMemo(()=>new Set(c.split(",").map(As=>As.trim()).filter(Boolean)),[c]),{data:h,isLoading:m}=BHs(s||""),{data:f}=Yw(),{data:g}=iie(),{data:x}=pK(3650),{data:y}=cDe(365),{data:v}=vUn(s),{contactsWithScores:b}=cie(),{data:w}=Lie(),{score:S}=nKs(s||""),C=int(),E=zUt(),I=N6e(),P=OUt(),[R,D]=j.useState(!1),[O,U]=j.useState("overview"),[W,V]=j.useState(!1),G=aUn(),[Y,X]=j.useState({}),[ae,ie]=j.useState(!1),[ne,te]=j.useState(!1),[J,ce]=j.useState(null),[_e,he]=j.useState(""),[ue,ve]=j.useState(void 0),[Ee,Se]=j.useState(""),[Le,Fe]=j.useState(null),[ke,Ve]=j.useState(!1),[je,Ae]=j.useState(null),[Ce,qe]=j.useState(!1),{isGmailConnected:ze,gmailEmail:$e}=yy(),{isReady:ct}=u6(),Xe=ct||ze,it=iJt(),[at,Ke]=j.useState(!1),{data:nt}=tt({queryKey:["cma-eligible"],queryFn:async()=>{const{data:{user:As}}=await q.auth.getUser();if(!As)return!1;const{data:hr}=await q.from("lead_sites").select("id, mls_provider_id, no_mls_mode, is_active").eq("agent_id",As.id);return(hr||[]).some(Er=>Er.is_active&&Er.mls_provider_id&&!Er.no_mls_mode)}}),xt=async()=>{var hn,Fn,vn,xs;if(!h)return;const As=(hn=h.address)==null?void 0:hn.trim(),hr=(Fn=h.city)==null?void 0:Fn.trim(),Er=(vn=h.state)==null?void 0:vn.trim().toUpperCase(),qn=((xs=h.zip_code)==null?void 0:xs.trim())||"";if(!As||!hr||!Er){re.error("Add a full address (street, city, state) before creating a CMA.");return}try{Ke(!0);const Lr=await it.mutateAsync({subject:{address:As,city:hr,state:Er,zip:qn},contactId:h.id,title:`${h.first_name||""} ${h.last_name||""}`.trim()+" — "+As});r(`/mission-control/cma/${Lr.id}`)}catch(Lr){re.error("Could not create CMA: "+((Lr==null?void 0:Lr.message)||"unknown error"))}finally{Ke(!1)}},{data:rt}=tt({queryKey:["gmail-sent-emails",s],queryFn:async()=>{const{data:As,error:hr}=await q.from("gmail_sent_emails").select("*").eq("contact_id",s).order("sent_at",{ascending:!1});if(hr)throw hr;return As},enabled:!!s}),Yt=As=>{if(!As)return null;const hr=As.match(/Video ID:\s*([a-f0-9-]+)/i);return hr?hr[1]:null},qt=j.useMemo(()=>{if(!b)return[];const As=new Map;if(u.size>0&&w)for(const Er of w)As.has(Er.contact_id)||As.set(Er.contact_id,new Set),As.get(Er.contact_id).add(Er.tag_id);let hr=b.filter(Er=>{var vn,xs,Lr;const qn=i===""||`${Er.first_name} ${Er.last_name}`.toLowerCase().includes(i.toLowerCase())||((vn=Er.email)==null?void 0:vn.toLowerCase().includes(i.toLowerCase()))||((xs=Er.phone)==null?void 0:xs.includes(i)),hn=l==="all"||((Lr=Er.tags)==null?void 0:Lr.some(Or=>Or.relationship_type_id===l));let Fn=!0;if(u.size>0){const Or=As.get(Er.id)||new Set;d==="all"?Fn=Array.from(u).every(ca=>Or.has(ca)):Fn=Array.from(u).some(ca=>Or.has(ca))}return qn&&hn&&Fn});return o==="not-touched-90"?hr=hr.filter(Er=>{const qn=Er.relationshipScore.daysSinceTouch;return qn===null||qn>90}):o==="at-risk"?hr=hr.filter(Er=>Er.relationshipScore.status==="at-risk"):o==="cooling"?hr=hr.filter(Er=>Er.relationshipScore.status==="cooling"):o==="warm"&&(hr=hr.filter(Er=>Er.relationshipScore.status==="warm")),hr.map(Er=>Er.id)},[b,i,l,o,u,d,w]),ts=qt.indexOf(s||""),ys=ts>0?qt[ts-1]:null,Bt=ts1&&ts!==-1,rs=As=>{const hr=new URLSearchParams;i&&hr.set("search",i),l!=="all"&&hr.set("type",l),o!=="all"&&hr.set("status",o),u.size>0&&(hr.set("tags",Array.from(u).join(",")),hr.set("tagMode",d));const Er=hr.toString();return`/mission-control/contacts/${As}${Er?`?${Er}`:""}`},St=j.useMemo(()=>{const As=((x==null?void 0:x.filter(Er=>Er.contact_id===s))||[]).map(Er=>{var vn,xs,Lr;const qn=Yt(Er.notes);let hn=((vn=Er.action_type)==null?void 0:vn.name)||"Touch",Fn=Er.notes;if(hn==="Other"&&((xs=Er.notes)!=null&&xs.startsWith("["))){const Or=Er.notes.indexOf("]");Or>0&&(hn=Er.notes.substring(1,Or),Fn=Er.notes.substring(Or+1).replace(/^\s*—\s*/,"").trim()||null)}return{id:Er.id,type:"touch",completed_at:Er.completed_at,name:hn,color:((Lr=Er.action_type)==null?void 0:Lr.color)||"#3B82F6",notes:Fn,videoId:qn}}),hr=((y==null?void 0:y.filter(Er=>Er.contact_id===s))||[]).map(Er=>({id:Er.id,type:"popby",completed_at:Er.completed_at,name:"Pop-by",color:"#F97316",notes:Er.notes,videoId:null}));return[...As,...hr].sort((Er,qn)=>new Date(qn.completed_at).getTime()-new Date(Er.completed_at).getTime())},[x,y,s]),Xs=As=>{var hr;return{first_name:As.first_name||"",last_name:As.last_name||"",email:As.email||"",phone:As.phone||"",address:As.address||"",city:As.city||"",state:As.state||"",zip_code:As.zip_code||"",address2_label:As.address2_label||"",address2:As.address2||"",address2_city:As.address2_city||"",address2_state:As.address2_state||"",address2_zip:As.address2_zip||"",mail_to_secondary:!!As.mail_to_secondary,birthday:As.birthday||"",home_anniversary:As.home_anniversary||"",wedding_anniversary:As.wedding_anniversary||"",spouse_birthday:As.spouse_birthday||"",spouse_name:As.spouse_name||"",spouse_email:As.spouse_email||"",company_name:As.company_name||"",job_title:As.job_title||"",lead_source_id:As.lead_source_id||"",notes:As.notes||"",tagIds:((hr=As.tags)==null?void 0:hr.map(Er=>Er.relationship_type_id))||[]}};j.useEffect(()=>{D(!1),X({})},[s]);const vt=j.useRef(null);j.useEffect(()=>{h!=null&&h.id&&vt.current!==h.id&&(vt.current=h.id,X(Xs(h)))},[h==null?void 0:h.id,h]);const gs=()=>{h&&(X(Xs(h)),ie(lCt(h)),D(!0))},Ss=async()=>{await C.mutateAsync({id:s,...Y,lead_source_id:Y.lead_source_id||null}),D(!1)},Is=async()=>{await fo("Are you sure you want to delete this contact?")&&(await E.mutateAsync(s),r("/mission-control/contacts"))},cs=((Ws=g==null?void 0:g.find(As=>As.id===J))==null?void 0:Ws.name)==="Other",js=async()=>{if(!J||cs&&!Ee.trim())return;const As=ue?new Date(ue.getFullYear(),ue.getMonth(),ue.getDate(),12,0,0).toISOString():void 0,hr=cs?`[${Ee.trim()}]${_e?" — "+_e:""}`:_e;await I.mutateAsync({contactId:s,actionTypeId:J,notes:hr,completedAt:As}),te(!1),ce(null),he(""),ve(void 0),Se("")},kn=(As,hr)=>{Xe&&h?(Ae({email:As,name:hr||`${h.first_name} ${h.last_name||""}`.trim()}),Ve(!0)):window.location.href=`mailto:${As}`};return m?e.jsx(Vs,{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"})})}):h?e.jsxs(e.Fragment,{children:[e.jsx(Vs,{title:`${h.first_name} ${h.last_name||""}`,description:"Contact details and activity",children:e.jsxs("div",{className:"space-y-5 overflow-x-hidden pb-24 lg:pb-6",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs($,{variant:"ghost",size:"sm",className:"-ml-2",onClick:()=>{window.history.length>1?r(-1):r("/mission-control/contacts")},children:[e.jsx(Cd,{className:"h-4 w-4 mr-1"}),"Back to Contacts"]}),Ft&&e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx($,{variant:"outline",size:"sm",className:"h-8 px-2",onClick:()=>ys&&r(rs(ys)),disabled:!ys,children:e.jsx(Cd,{className:"h-4 w-4"})}),e.jsxs("span",{className:"px-1 text-xs text-muted-foreground whitespace-nowrap",children:[ts+1," of ",qt.length]}),e.jsx($,{variant:"outline",size:"sm",className:"h-8 px-2",onClick:()=>Bt&&r(rs(Bt)),disabled:!Bt,children:e.jsx(Di,{className:"h-4 w-4"})})]})]}),e.jsx("section",{className:"hub-ink relative overflow-hidden rounded-2xl p-4 sm:p-6",children:e.jsxs("div",{className:"relative flex flex-col gap-5",children:[e.jsxs("div",{className:"flex flex-col gap-4 sm:flex-row sm:items-start sm:justify-between",children:[e.jsxs("div",{className:"flex min-w-0 items-start gap-4",children:[e.jsx("div",{className:"shrink-0 rounded-full bg-background p-1 shadow-lg ring-2 ring-white/20",children:e.jsx(J$n,{contactId:h.id,firstName:h.first_name,lastName:h.last_name,avatarUrl:h.avatar_url,email:h.email,size:72})}),e.jsxs("div",{className:"min-w-0",children:[e.jsxs("h1",{className:"truncate text-2xl font-bold sm:text-3xl",children:[h.first_name," ",h.last_name||""]}),e.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-1.5",children:[S&&e.jsxs("span",{className:"hub-glass inline-flex items-center gap-1.5 rounded-full px-2.5 py-1 text-[11px] font-semibold capitalize",children:[e.jsx("span",{className:"h-1.5 w-1.5 rounded-full",style:{backgroundColor:S.status==="warm"?"#22c55e":S.status==="cooling"?"#f59e0b":"#ef4444"}}),S.status==="at-risk"?"At risk":S.status," · ",S.score]}),h.email_opt_out&&e.jsxs("span",{className:"inline-flex items-center gap-1.5 rounded-full bg-destructive/90 px-2.5 py-1 text-[11px] font-semibold text-destructive-foreground",children:[e.jsx(XI,{className:"h-3 w-3"}),"Emails opted out"]}),(((On=h.lead_source_ref)==null?void 0:On.name)||h.lead_source)&&e.jsx("span",{className:"hub-glass rounded-full px-2.5 py-1 text-[11px] font-medium",children:((ds=h.lead_source_ref)==null?void 0:ds.name)||h.lead_source}),(gn=h.tags)==null?void 0:gn.map(As=>{const hr=f==null?void 0:f.find(Er=>Er.id===As.relationship_type_id);return hr?e.jsx("span",{className:"hub-glass rounded-full px-2.5 py-1 text-[11px] font-medium",children:hr.name},As.id):null})]}),e.jsxs("div",{className:"mt-3 flex flex-col gap-1.5 text-sm sm:flex-row sm:flex-wrap sm:items-center sm:gap-4",children:[h.email&&e.jsxs("button",{onClick:()=>kn(h.email),className:"inline-flex min-w-0 items-center gap-1.5 hub-ink-muted transition-opacity hover:opacity-100",children:[e.jsx(mn,{className:"h-3.5 w-3.5 shrink-0"}),e.jsx("span",{className:"truncate",children:h.email})]}),h.phone&&e.jsxs("a",{href:`tel:${h.phone}`,className:"inline-flex items-center gap-1.5 hub-ink-muted",children:[e.jsx(Da,{className:"h-3.5 w-3.5"}),h.phone]}),(h.address||h.city)&&e.jsxs("span",{className:"inline-flex min-w-0 items-center gap-1.5 hub-ink-muted",children:[e.jsx(ci,{className:"h-3.5 w-3.5 shrink-0"}),e.jsx("span",{className:"truncate",children:[h.address,h.city,h.state].filter(Boolean).join(", ")})]})]})]})]}),e.jsxs("div",{className:"flex shrink-0 items-center gap-2",children:[G&&e.jsxs("button",{onClick:()=>V(!0),className:"hub-glass inline-flex items-center gap-2 rounded-full px-4 py-2 text-sm font-semibold transition-transform hover:scale-[1.02]",title:"Find public professional details (job, company, social profiles) for this person. Property data is on the Property tab.",children:[e.jsx(Nn,{className:"h-4 w-4"}),"Find person details"]}),e.jsxs("button",{onClick:()=>{gs(),U("details")},className:"inline-flex items-center gap-2 rounded-full bg-background px-4 py-2 text-sm font-semibold text-foreground shadow-sm transition-transform hover:scale-[1.02]",children:[e.jsx(_p,{className:"h-4 w-4"}),"Edit"]}),e.jsx("button",{onClick:Is,className:"hub-glass inline-flex h-9 w-9 items-center justify-center rounded-full",title:"Delete contact",children:e.jsx(Wn,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-2 sm:flex sm:flex-wrap",children:[h.phone&&e.jsxs("a",{href:`tel:${h.phone}`,className:"hub-glass inline-flex items-center justify-center gap-2 rounded-xl px-4 py-2.5 text-sm font-medium",children:[e.jsx(Da,{className:"h-4 w-4",style:{color:"hsl(var(--hub-glow))"}}),"Call"]}),h.phone&&e.jsxs("button",{onClick:()=>window.location.href=`sms:${h.phone}`,className:"hub-glass inline-flex items-center justify-center gap-2 rounded-xl px-4 py-2.5 text-sm font-medium",children:[e.jsx(eo,{className:"h-4 w-4",style:{color:"hsl(var(--hub-glow))"}}),"Text"]}),h.email&&e.jsxs("button",{onClick:()=>kn(h.email,`${h.first_name} ${h.last_name||""}`.trim()),className:"hub-glass inline-flex items-center justify-center gap-2 rounded-xl px-4 py-2.5 text-sm font-medium",children:[e.jsx(mn,{className:"h-4 w-4",style:{color:"hsl(var(--hub-glow))"}}),"Email"]}),e.jsxs("button",{onClick:()=>r(`/mission-control/video/record?contact_id=${s}`),className:"hub-glass inline-flex items-center justify-center gap-2 rounded-xl px-4 py-2.5 text-sm font-medium",children:[e.jsx(ua,{className:"h-4 w-4",style:{color:"hsl(var(--hub-glow))"}}),"Video"]}),e.jsxs("button",{onClick:()=>te(!0),className:"hub-glass inline-flex items-center justify-center gap-2 rounded-xl px-4 py-2.5 text-sm font-medium",children:[e.jsx(dn,{className:"h-4 w-4",style:{color:"hsl(var(--hub-glow))"}}),"Log Action"]}),h.email&&e.jsxs("button",{onClick:()=>qe(!0),className:"hub-glass inline-flex items-center justify-center gap-2 rounded-xl px-4 py-2.5 text-sm font-medium",children:[e.jsx(Nn,{className:"h-4 w-4",style:{color:"hsl(var(--hub-glow))"}}),"Connect Page"]})]})]})}),e.jsxs(ha,{value:O,onValueChange:As=>{As==="details"&&!R&&gs(),U(As)},children:[e.jsx("div",{className:"-mx-1 overflow-x-auto px-1",children:e.jsxs(ma,{className:"inline-flex h-10 w-auto",children:[e.jsx(Zt,{value:"overview",children:"Overview"}),e.jsx(Zt,{value:"details",children:"Details"}),e.jsx(Zt,{value:"activity",children:"Activity"}),e.jsx(Zt,{value:"marketing",children:"Marketing"}),t&&e.jsx(Zt,{value:"property-intel",children:"Property Intelligence"})]})}),e.jsx(Xt,{value:"overview",className:"mt-4 space-y-5",children:e.jsxs("div",{className:"grid gap-5 lg:grid-cols-3",children:[e.jsxs("div",{className:"space-y-5 lg:col-span-2",children:[e.jsx(l9n,{contact:h,onLogTouch:()=>te(!0)}),e.jsxs(Ne,{children:[e.jsx(Ct,{className:"pb-3",children:e.jsxs(At,{className:"flex items-center gap-2 text-base",children:[e.jsx(Ta,{className:"h-4 w-4 text-primary"}),"Key Dates"]})}),e.jsxs(Ie,{children:[e.jsx("div",{className:"grid gap-3 sm:grid-cols-2",children:[{icon:ul,label:"Birthday",value:h.birthday},{icon:va,label:"Home Anniversary",value:h.home_anniversary},{icon:Jo,label:"Wedding Anniversary",value:h.wedding_anniversary},{icon:Jo,label:"Spouse Birthday",value:h.spouse_birthday}].map(({icon:As,label:hr,value:Er})=>e.jsxs("div",{className:"flex items-center gap-3 rounded-xl border border-border/70 bg-muted/30 px-3 py-2.5",children:[e.jsx(As,{className:"h-4 w-4 shrink-0 text-primary"}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-[11px] uppercase tracking-wide text-muted-foreground",children:hr}),e.jsx("p",{className:"truncate text-sm font-medium",children:Er?en(Ch(Er),Ch(Er).getFullYear()===1900?"MMMM d":"MMMM d, yyyy"):"—"})]})]},hr))}),St.length>0&&e.jsxs("p",{className:"mt-3 text-xs text-muted-foreground",children:["Last contacted ",en(new Date(St[0].completed_at),"MMM d, yyyy")," (",St[0].name,")",h.created_at&&` · Added ${en(new Date(h.created_at),"MMM d, yyyy")}`]})]})]}),(h.address||h.city)&&e.jsxs(Ne,{children:[e.jsx(Ct,{className:"pb-3",children:e.jsxs(At,{className:"flex items-center gap-2 text-base",children:[e.jsx(va,{className:"h-4 w-4 text-primary"}),"Home"]})}),e.jsxs(Ie,{className:"flex flex-wrap items-start justify-between gap-3",children:[e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(ci,{className:"mt-0.5 h-4 w-4 text-muted-foreground"}),e.jsxs("div",{className:"text-sm",children:[h.address&&e.jsx("div",{children:h.address}),e.jsxs("div",{className:"text-muted-foreground",children:[[h.city,h.state].filter(Boolean).join(", "),h.zip_code?` ${h.zip_code}`:""]})]})]}),nt&&h.address&&h.city&&h.state&&e.jsxs($,{size:"sm",variant:"outline",onClick:xt,disabled:at,children:[at?e.jsx(kt,{className:"mr-1 h-4 w-4 animate-spin"}):e.jsx(c2,{className:"mr-1 h-4 w-4"}),"Create CMA"]})]}),lCt(h)&&e.jsx(Ie,{className:"pt-0",children:e.jsxs("div",{className:"flex items-start gap-2 rounded-lg border border-dashed p-3",children:[e.jsx(ci,{className:"mt-0.5 h-4 w-4 text-muted-foreground"}),e.jsxs("div",{className:"text-sm",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"font-medium",children:FYe(h).label}),h.mail_to_secondary&&e.jsx(Be,{variant:"secondary",className:"text-[10px]",children:"Mail goes here"})]}),e.jsx("div",{className:"text-muted-foreground",children:HBn(FYe(h))})]})]})})]}),e.jsx(lUn,{contactId:h.id,ownerUserId:h.owner_user_id,legacyNote:h.notes}),e.jsx(QUn,{contactId:s})]}),e.jsxs("div",{className:"space-y-5",children:[e.jsxs(Ne,{children:[e.jsx(Ct,{className:"pb-3",children:e.jsx(At,{className:"text-base",children:"Tags"})}),e.jsx(Ie,{children:e.jsx(vCt,{contactId:s})})]}),e.jsxs(Ne,{children:[e.jsx(Ct,{className:"pb-3",children:e.jsxs(At,{className:"flex items-center gap-2 text-base",children:[e.jsx(sl,{className:"h-4 w-4 text-primary"}),"People & Work"]})}),e.jsxs(Ie,{className:"space-y-3",children:[e.jsx(BYe,{contactId:s,currentSpouseContactId:(h==null?void 0:h.spouse_contact_id)||null,currentSpouseName:h.spouse_name||null,currentSpouseEmail:h.spouse_email||null,onLink:As=>P.mutate({contactId:s,spouseContactId:As}),onUnlink:()=>P.mutate({contactId:s,spouseContactId:null}),isEditing:!1}),e.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[e.jsx(ji,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:Pt(!h.company_name&&!h.job_title&&"text-muted-foreground"),children:h.job_title&&h.company_name?`${h.job_title} at ${h.company_name}`:h.job_title||h.company_name||"No company on file"})]})]})]}),e.jsx(eqn,{contactId:s}),e.jsx(SUn,{contactId:s})]})]})}),e.jsx(Xt,{value:"details",className:"mt-4",children:e.jsxs(Ne,{children:[e.jsx(Ct,{className:"pb-3",children:e.jsx(At,{className:"text-base",children:"Edit Contact"})}),e.jsxs(Ie,{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-4",children:[e.jsx("p",{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:"Basics"}),e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"first_name",children:"First Name"}),e.jsx(pe,{id:"first_name",value:Y.first_name||"",onChange:As=>X({...Y,first_name:As.target.value})})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"last_name",children:"Last Name"}),e.jsx(pe,{id:"last_name",value:Y.last_name||"",onChange:As=>X({...Y,last_name:As.target.value})})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"email",children:"Email"}),e.jsx(pe,{id:"email",type:"email",value:Y.email||"",onChange:As=>X({...Y,email:As.target.value})})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"phone",children:"Phone"}),e.jsx(pe,{id:"phone",value:Y.phone||"",onChange:As=>X({...Y,phone:As.target.value})})]})]})]}),e.jsx(Gc,{}),e.jsxs("div",{className:"space-y-4",children:[e.jsx("p",{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:"Address"}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"address",children:"Street Address"}),e.jsx(pe,{id:"address",value:Y.address||"",onChange:As=>X({...Y,address:As.target.value}),placeholder:"123 Main St"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4 sm:grid-cols-4",children:[e.jsxs("div",{className:"col-span-2",children:[e.jsx(ee,{htmlFor:"city",children:"City"}),e.jsx(pe,{id:"city",value:Y.city||"",onChange:As=>X({...Y,city:As.target.value}),placeholder:"City"})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"state",children:"State"}),e.jsx(pe,{id:"state",value:Y.state||"",onChange:As=>X({...Y,state:As.target.value}),placeholder:"TX",maxLength:2})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"zip_code",children:"Zip Code"}),e.jsx(pe,{id:"zip_code",value:Y.zip_code||"",onChange:As=>X({...Y,zip_code:As.target.value}),placeholder:"12345"})]})]})]}),e.jsx(Gc,{}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("p",{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:"Second Address (optional)"}),!ae&&e.jsx($,{type:"button",variant:"ghost",size:"sm",onClick:()=>ie(!0),children:"Add another address"})]}),ae&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"address2_label",children:"Label"}),e.jsx(pe,{id:"address2_label",list:"contact-address-labels",value:Y.address2_label||"",onChange:As=>X({...Y,address2_label:As.target.value}),placeholder:"Vacation home"}),e.jsx("datalist",{id:"contact-address-labels",children:LQt.map(As=>e.jsx("option",{value:As},As))})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"address2",children:"Street Address"}),e.jsx(pe,{id:"address2",value:Y.address2||"",onChange:As=>X({...Y,address2:As.target.value}),placeholder:"456 Lake Rd"})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4 sm:grid-cols-4",children:[e.jsxs("div",{className:"col-span-2",children:[e.jsx(ee,{htmlFor:"address2_city",children:"City"}),e.jsx(pe,{id:"address2_city",value:Y.address2_city||"",onChange:As=>X({...Y,address2_city:As.target.value}),placeholder:"City"})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"address2_state",children:"State"}),e.jsx(pe,{id:"address2_state",value:Y.address2_state||"",onChange:As=>X({...Y,address2_state:As.target.value}),placeholder:"TX",maxLength:2})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"address2_zip",children:"Zip Code"}),e.jsx(pe,{id:"address2_zip",value:Y.address2_zip||"",onChange:As=>X({...Y,address2_zip:As.target.value}),placeholder:"12345"})]})]}),e.jsxs("div",{className:"flex items-center justify-between rounded-lg border p-3",children:[e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"mail_to_secondary",className:"text-sm",children:"Send mail here instead"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Pop-bys and mailers will use this address."})]}),e.jsx(Sn,{id:"mail_to_secondary",checked:!!Y.mail_to_secondary,onCheckedChange:As=>X({...Y,mail_to_secondary:As})})]}),e.jsx($,{type:"button",variant:"ghost",size:"sm",className:"text-destructive",onClick:()=>{X({...Y,address2_label:"",address2:"",address2_city:"",address2_state:"",address2_zip:"",mail_to_secondary:!1}),ie(!1)},children:"Remove second address"})]})]}),e.jsx(Gc,{}),e.jsxs("div",{className:"space-y-4",children:[e.jsx("p",{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:"Important Dates"}),e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"birthday",children:"Birthday"}),e.jsx(pe,{id:"birthday",type:"date",value:Y.birthday||"",onChange:As=>X({...Y,birthday:As.target.value})})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"home_anniversary",children:"Home Anniversary"}),e.jsx(pe,{id:"home_anniversary",type:"date",value:Y.home_anniversary||"",onChange:As=>X({...Y,home_anniversary:As.target.value})})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"wedding_anniversary",children:"Wedding Anniversary"}),e.jsx(pe,{id:"wedding_anniversary",type:"date",value:Y.wedding_anniversary||"",onChange:As=>X({...Y,wedding_anniversary:As.target.value})})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"spouse_birthday",children:"Spouse Birthday"}),e.jsx(pe,{id:"spouse_birthday",type:"date",value:Y.spouse_birthday||"",onChange:As=>X({...Y,spouse_birthday:As.target.value})})]})]})]}),e.jsx(Gc,{}),e.jsxs("div",{className:"space-y-4",children:[e.jsx("p",{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:"Household & Work"}),e.jsx(BYe,{contactId:s,currentSpouseContactId:(h==null?void 0:h.spouse_contact_id)||null,currentSpouseName:(h==null?void 0:h.spouse_name)||null,currentSpouseEmail:(h==null?void 0:h.spouse_email)||null,onLink:As=>P.mutate({contactId:s,spouseContactId:As}),onUnlink:()=>P.mutate({contactId:s,spouseContactId:null}),isEditing:!0}),e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"company_name",children:"Company"}),e.jsx(pe,{id:"company_name",value:Y.company_name||"",onChange:As=>X({...Y,company_name:As.target.value}),placeholder:"Enter company name"})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"job_title",children:"Job Title"}),e.jsx(pe,{id:"job_title",value:Y.job_title||"",onChange:As=>X({...Y,job_title:As.target.value}),placeholder:"Enter job title"})]})]}),e.jsx(eJt,{value:Y.lead_source_id||"",onChange:As=>X({...Y,lead_source_id:As})})]}),e.jsx(Gc,{}),e.jsxs("div",{className:"space-y-3",children:[e.jsx("p",{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:"Relationship Types"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:f==null?void 0:f.filter(As=>As.active).map(As=>{var Er;const hr=!!((Er=Y.tagIds)!=null&&Er.includes(As.id));return e.jsxs("label",{className:Pt("inline-flex cursor-pointer items-center gap-2 rounded-full border px-3 py-1.5 text-sm transition-colors",hr?"border-primary bg-primary/10 text-primary":"border-border hover:bg-accent"),children:[e.jsx(ai,{checked:hr,onCheckedChange:qn=>{var hn;X(qn?{...Y,tagIds:[...Y.tagIds||[],As.id]}:{...Y,tagIds:(hn=Y.tagIds)==null?void 0:hn.filter(Fn=>Fn!==As.id)})}}),As.name]},As.id)})}),e.jsxs("div",{children:[e.jsx(ee,{children:"Tags"}),e.jsx("div",{className:"mt-2",children:e.jsx(vCt,{contactId:s})})]})]}),e.jsx(Gc,{}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"notes",children:"Notes"}),e.jsx(Rs,{id:"notes",value:Y.notes||"",onChange:As=>X({...Y,notes:As.target.value}),rows:5})]}),e.jsxs("div",{className:"sticky bottom-0 -mx-6 flex flex-wrap items-center justify-end gap-2 border-t bg-card/95 px-6 py-3 backdrop-blur",children:[e.jsx($,{variant:"outline",onClick:()=>{D(!1),U("overview")},children:"Cancel"}),e.jsxs($,{onClick:Ss,disabled:C.isPending,children:[C.isPending?e.jsx(kt,{className:"mr-1 h-4 w-4 animate-spin"}):e.jsx(la,{className:"mr-1 h-4 w-4"}),"Save Changes"]})]})]})]})}),e.jsx(Xt,{value:"activity",className:"mt-4",children:e.jsxs("div",{className:"grid gap-5 lg:grid-cols-3",children:[e.jsx("div",{className:"lg:col-span-2",children:e.jsxs(Ne,{children:[e.jsxs(Ct,{className:"flex flex-row items-center justify-between gap-2 pb-3",children:[e.jsx(At,{className:"text-base",children:"Activity Log"}),e.jsxs($,{size:"sm",variant:"outline",onClick:()=>te(!0),children:[e.jsx(dn,{className:"mr-1 h-3.5 w-3.5"})," Log Action"]})]}),e.jsx(Ie,{children:St.length>0?e.jsx("div",{className:"space-y-4",children:St.map(As=>{var hr;return e.jsxs("div",{className:"flex items-start gap-3 border-b pb-3 last:border-0",children:[e.jsx("div",{className:"flex h-8 w-8 items-center justify-center rounded-full text-xs text-white",style:{backgroundColor:As.color},children:As.type==="popby"?e.jsx(ul,{className:"h-4 w-4"}):(hr=As.name)==null?void 0:hr.charAt(0)}),e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-sm font-medium",children:As.name}),As.videoId&&e.jsxs($,{variant:"ghost",size:"sm",className:"h-6 px-2 text-xs",onClick:()=>Fe(As.videoId),children:[e.jsx(Bu,{className:"mr-1 h-3 w-3"}),"Preview"]})]}),e.jsx("div",{className:"text-xs text-muted-foreground",children:en(new Date(As.completed_at),"MMM d, yyyy h:mm a")}),As.notes&&!As.videoId&&e.jsx("p",{className:"mt-1 text-sm text-muted-foreground",children:As.notes})]})]},As.id)})}):e.jsx("p",{className:"py-6 text-center text-sm text-muted-foreground",children:"No activity logged yet"})})]})}),e.jsxs("div",{className:"space-y-5",children:[v&&v.length>0&&e.jsxs(Ne,{children:[e.jsx(Ct,{className:"pb-3",children:e.jsxs(At,{className:"flex items-center gap-2 text-base",children:[e.jsx(eo,{className:"h-4 w-4 text-primary"}),"Video Replies"]})}),e.jsx(Ie,{children:e.jsx("div",{className:"space-y-4",children:v.map(As=>{var hr,Er;return e.jsxs("div",{className:"flex items-start gap-3 border-b pb-3 last:border-0",children:[(hr=As.video)!=null&&hr.thumbnail_url?e.jsx("img",{src:As.video.thumbnail_url,alt:As.video.title||"Video",className:"h-12 w-16 cursor-pointer rounded object-cover transition-opacity hover:opacity-80",onClick:()=>Fe(As.video_id)}):e.jsx("div",{className:"flex h-12 w-16 cursor-pointer items-center justify-center rounded bg-muted transition-colors hover:bg-muted/80",onClick:()=>Fe(As.video_id),children:e.jsx(ua,{className:"h-5 w-5 text-muted-foreground"})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("span",{className:"block truncate text-sm font-medium",children:["Replied to: ",((Er=As.video)==null?void 0:Er.title)||"Untitled Video"]}),e.jsx("div",{className:"text-xs text-muted-foreground",children:en(new Date(As.created_at),"MMM d, yyyy h:mm a")}),As.message&&e.jsxs("p",{className:"mt-1 line-clamp-2 text-sm text-muted-foreground",children:['"',As.message,'"']})]})]},As.id)})})})]}),rt&&rt.length>0&&e.jsxs(Ne,{children:[e.jsx(Ct,{className:"pb-3",children:e.jsxs(At,{className:"flex items-center gap-2 text-base",children:[e.jsx(Yr,{className:"h-4 w-4 text-sky-500"}),"Sent Emails"]})}),e.jsx(Ie,{children:e.jsx("div",{className:"space-y-3",children:rt.map(As=>e.jsxs(zs,{children:[e.jsx(jl,{asChild:!0,children:e.jsxs("button",{className:"flex w-full cursor-pointer items-start gap-3 rounded-lg border p-3 text-left transition-colors hover:bg-muted/50",children:[e.jsx("div",{className:"flex h-8 w-8 flex-shrink-0 items-center justify-center rounded-full bg-sky-500/10 text-sky-600",children:e.jsx(mn,{className:"h-4 w-4"})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"truncate text-sm font-medium",children:As.subject}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["To: ",As.to_email," · ",en(new Date(As.sent_at),"MMM d, yyyy h:mm a")]})]}),e.jsx(Di,{className:"mt-1 h-4 w-4 flex-shrink-0 text-muted-foreground"})]})}),e.jsxs(Os,{className:"flex max-h-[85vh] max-w-2xl flex-col",children:[e.jsxs(Us,{children:[e.jsxs(Bs,{className:"flex items-center gap-2",children:[e.jsx(mn,{className:"h-5 w-5 text-sky-500"}),As.subject]}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:["To: ",As.to_email," · ",en(new Date(As.sent_at),"MMM d, yyyy h:mm a")]})]}),e.jsx("div",{className:"min-h-0 flex-1 overflow-hidden rounded-lg border bg-white",children:e.jsx("iframe",{srcDoc:As.body,className:"h-[400px] w-full border-0",sandbox:"",title:`Email: ${As.subject}`})})]})]},As.id))})})]}),e.jsx(DUn,{contactId:s})]})]})}),e.jsx(Xt,{value:"marketing",className:"mt-4",children:e.jsxs("div",{className:"grid gap-5 lg:grid-cols-2",children:[e.jsx(TUn,{contactId:s,contactName:h.first_name}),e.jsx(CUn,{contactId:s}),n&&e.jsxs(e.Fragment,{children:[e.jsx(AUn,{contactId:s,contactName:h.first_name}),e.jsx(EUn,{contactId:s,contactName:h.first_name})]}),e.jsx(IUn,{contactId:s})]})}),t&&e.jsx(Xt,{value:"property-intel",className:"mt-4",children:e.jsx(ZUn,{contactId:s,contactAddress:h.address,contactCity:h.city,contactState:h.state,contactZip:h.zip_code})})]}),e.jsxs("div",{className:"fixed inset-x-0 bottom-0 z-40 flex items-center gap-2 border-t bg-background/95 px-3 py-2 pb-[calc(env(safe-area-inset-bottom)+0.5rem)] backdrop-blur lg:hidden",children:[h.phone&&e.jsx("a",{href:`tel:${h.phone}`,className:"flex-1",children:e.jsxs($,{variant:"outline",className:"w-full",children:[e.jsx(Da,{className:"mr-1 h-4 w-4"})," Call"]})}),h.phone&&e.jsxs($,{variant:"outline",className:"flex-1",onClick:()=>window.location.href=`sms:${h.phone}`,children:[e.jsx(eo,{className:"mr-1 h-4 w-4"})," Text"]}),e.jsxs($,{className:"flex-1",onClick:()=>te(!0),children:[e.jsx(dn,{className:"mr-1 h-4 w-4"})," Log"]})]}),e.jsx(zs,{open:ne,onOpenChange:te,children:e.jsxs(Os,{className:"max-h-[85vh] overflow-y-auto",children:[e.jsx(Us,{children:e.jsx(Bs,{children:"Log an Action"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(ee,{children:"Action Type"}),e.jsx("div",{className:"mt-2 grid grid-cols-2 gap-2",children:g==null?void 0:g.filter(As=>As.active).map(As=>e.jsxs("button",{onClick:()=>ce(As.id),className:Pt("rounded-lg border p-3 text-left transition-all",J===As.id?"border-primary bg-primary/10":"hover:bg-accent"),children:[e.jsx("div",{className:"font-medium",children:As.name}),e.jsx("div",{className:"text-xs text-muted-foreground",children:As.description})]},As.id))}),cs&&e.jsxs("div",{className:"mt-3",children:[e.jsx(ee,{htmlFor:"custom-action-name",children:"What did you do?"}),e.jsx(pe,{id:"custom-action-name",value:Ee,onChange:As=>Se(As.target.value),placeholder:"e.g. Met a client for lunch, Dropped off a gift...",className:"mt-1"})]})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Date (optional — backdate if needed)"}),e.jsxs(Yd,{children:[e.jsx(Zd,{asChild:!0,children:e.jsxs($,{variant:"outline",className:Pt("mt-2 w-full justify-start text-left font-normal",!ue&&"text-muted-foreground"),children:[e.jsx(Ta,{className:"mr-2 h-4 w-4"}),ue?en(ue,"PPP"):"Today (default)"]})}),e.jsx(Bd,{className:"w-auto p-0",align:"start",children:e.jsx(D2,{mode:"single",selected:ue,onSelect:ve,disabled:As=>As>new Date,initialFocus:!0,className:Pt("p-3 pointer-events-auto")})})]})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"action-notes",children:"Notes (optional)"}),e.jsx(Rs,{id:"action-notes",value:_e,onChange:As=>he(As.target.value),placeholder:"Add any notes about this interaction...",rows:3})]}),e.jsxs($,{onClick:js,disabled:!J||cs&&!Ee.trim()||I.isPending,className:"w-full",children:[e.jsx(la,{className:"mr-1 h-4 w-4"}),"Complete Action"]})]})]})}),e.jsx(zs,{open:!!Le,onOpenChange:As=>!As&&Fe(null),children:e.jsxs(Os,{className:"max-w-2xl",children:[e.jsx(Us,{children:e.jsx(Bs,{children:"Video Preview"})}),Le&&e.jsx(XUn,{videoId:Le})]})})]})}),G&&h&&e.jsx(nUn,{open:W,onOpenChange:V,contactId:h.id,contactName:`${h.first_name} ${h.last_name||""}`.trim(),hasEmail:!!h.email}),Xe&&h&&je&&e.jsx(Ak,{open:ke,onOpenChange:Ve,contact:{id:h.id,first_name:h.first_name,last_name:h.last_name,email:je.email},gmailEmail:$e}),h&&h.email&&e.jsx(dUn,{open:Ce,onOpenChange:qe,contact:{id:h.id,first_name:h.first_name,last_name:h.last_name,email:h.email}})]}):e.jsx(Vs,{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($,{onClick:()=>r("/mission-control/contacts"),children:"Back to Contacts"})]})})}function sqn({rangeDays:s}){const{user:t}=vs(),n=Vt(),[r,a]=j.useState(null),[i,l]=j.useState(null),[o,c]=j.useState(!1),{data:d=[],isLoading:u}=tt({queryKey:["newsletter-campaigns",t==null?void 0:t.id,s],enabled:!!t,queryFn:async()=>{let f=q.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 y=new Date(Date.now()-s*864e5).toISOString();f=f.gte("created_at",y)}const{data:g,error:x}=await f;if(x)throw x;return g||[]}}),{data:h}=tt({queryKey:["newsletter-campaign-recipients",r],enabled:!!r,queryFn:async()=>{const{data:f,error:g}=await q.from("email_campaign_recipients").select("id, email, name, status, sent_at, opened_at, clicked_at, error_message").eq("campaign_id",r).order("sent_at",{ascending:!1}).limit(2e3);if(g)throw g;return f||[]}}),m=async()=>{if(!(!i||!t)){c(!0);try{const{data:f,error:g}=await q.from("email_campaign_recipients").select("email, name, contact_id").eq("campaign_id",i.id).eq("status","sent").is("opened_at",null).limit(5e3);if(g)throw g;if(!f||f.length===0){re.info("All recipients opened — nothing to resend!"),l(null),c(!1);return}const{data:x}=await q.from("email_campaigns").select("subject, body_html, from_email, reply_to_email").eq("id",i.id).single();if(!x)throw new Error("Original campaign not found");const{data:y,error:v}=await q.from("email_campaigns").insert({user_id:t.id,name:`${i.name} (Resend to non-openers)`,subject:x.subject,body_html:x.body_html,from_email:x.from_email,reply_to_email:x.reply_to_email,total_recipients:f.length,status:"draft"}).select("id").single();if(v)throw v;const b=f.map(S=>({campaign_id:y.id,contact_id:S.contact_id,email:S.email,name:S.name,status:"pending"}));for(let S=0;S{const g=f.sent_count||0,x=g>0?f.open_count/g*100:0,y=g>0?f.click_count/g*100:0,v=f.sent_at?mk(new Date,new Date(f.sent_at)):0,b=f.status==="sent"&&v>=3&&g>0&&f.open_counta(f.id),children:[e.jsx(Ca,{className:"h-3.5 w-3.5 mr-1"})," Details"]}),b&&e.jsxs($,{variant:"outline",size:"sm",onClick:()=>l(f),children:[e.jsx(e7,{className:"h-3.5 w-3.5 mr-1"})," Resend"]})]})]}),f.status==="sent"&&g>0&&e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-3 mt-3",children:[e.jsx(pue,{icon:e.jsx(Yr,{className:"h-3.5 w-3.5"}),label:"Sent",value:g,sub:`of ${f.total_recipients}`}),e.jsx(pue,{icon:e.jsx(Ca,{className:"h-3.5 w-3.5 text-blue-600"}),label:"Opens",value:f.open_count,sub:`${x.toFixed(1)}%`,children:e.jsx(Yi,{value:x,className:"h-1 mt-1"})}),e.jsx(pue,{icon:e.jsx(Lm,{className:"h-3.5 w-3.5 text-purple-600"}),label:"Clicks",value:f.click_count,sub:`${y.toFixed(1)}%`,children:e.jsx(Yi,{value:y,className:"h-1 mt-1"})}),e.jsx(pue,{icon:e.jsx(XI,{className:"h-3.5 w-3.5 text-orange-600"}),label:"Bounces",value:f.bounce_count,sub:f.bounce_count>0?"review":"none"})]})]},f.id)})})]})}),e.jsx(Wy,{open:!!r,onOpenChange:f=>!f&&a(null),children:e.jsxs(py,{className:"w-full sm:max-w-2xl overflow-y-auto",children:[e.jsx(D0,{children:e.jsx(F0,{children:"Recipient Activity"})}),e.jsx("div",{className:"mt-4 space-y-1",children:h?h.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:h.map(f=>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:f.name||"—"}),e.jsx("div",{className:"text-xs text-muted-foreground truncate max-w-[180px]",children:f.email})]}),e.jsx("td",{className:"py-2 text-xs",children:f.opened_at?e.jsx(Be,{variant:"default",className:"text-xs",children:en(new Date(f.opened_at),"MMM d")}):e.jsx("span",{className:"text-muted-foreground",children:"—"})}),e.jsx("td",{className:"py-2 text-xs",children:f.clicked_at?e.jsx(Be,{variant:"default",className:"text-xs bg-purple-600",children:en(new Date(f.clicked_at),"MMM d")}):e.jsx("span",{className:"text-muted-foreground",children:"—"})}),e.jsxs("td",{className:"py-2 text-xs",children:[f.status==="sent"&&e.jsx(Be,{variant:"outline",className:"text-xs",children:"sent"}),f.status==="pending"&&e.jsx(Be,{variant:"secondary",className:"text-xs",children:"queued"}),f.status==="failed"&&e.jsx(Be,{variant:"destructive",className:"text-xs",title:f.error_message||"",children:"failed"}),f.status==="suppressed"&&e.jsx(Be,{variant:"outline",className:"text-xs",children:"suppressed"})]})]},f.id))})]}):e.jsx("p",{className:"text-sm text-muted-foreground",children:"Loading…"})})]})}),e.jsx(kc,{open:!!i,onOpenChange:f=>!f&&l(null),children:e.jsxs(cc,{children:[e.jsxs(dc,{children:[e.jsx(hc,{children:"Resend to non-openers?"}),e.jsxs(mc,{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(uc,{children:[e.jsx(fc,{disabled:o,children:"Cancel"}),e.jsx(tc,{onClick:m,disabled:o,children:o?e.jsxs(e.Fragment,{children:[e.jsx(kt,{className:"h-4 w-4 mr-1 animate-spin"}),"Resending…"]}):e.jsxs(e.Fragment,{children:[e.jsx(e7,{className:"h-4 w-4 mr-1"}),"Resend"]})})]})]})})]})}function pue({icon:s,label:t,value:n,sub:r,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:n.toLocaleString()}),r&&e.jsx("span",{className:"text-xs text-muted-foreground",children:r})]}),a]})}async function gne(){var r;const{data:{session:s}}=await q.auth.getSession(),t=s!=null&&s.expires_at?s.expires_at*1e3:0;if(!(s!=null&&s.access_token)||t-Date.now()<12e4){const{data:a,error:i}=await q.auth.refreshSession();if(i||!((r=a.session)!=null&&r.access_token))throw new Error("Your session expired. Please refresh the page (or sign in again) and try sending once more.");return a.session.access_token}return s.access_token}function nqn(){const{user:s}=vs(),t=Qn(),n=Vt(),{data:r=[],isLoading:a}=tt({queryKey:["scheduled-email-campaigns",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:d,error:u}=await q.from("email_campaigns").select("id, name, subject, scheduled_at, total_recipients, status, created_at").eq("user_id",s.id).eq("status","scheduled").order("scheduled_at",{ascending:!0});if(u)throw u;return d||[]},refetchInterval:3e4}),i=async(d,u)=>{const h=await gne(),f=await(await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/ses-schedule-campaign",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${h}`},body:JSON.stringify({action:d,campaign_id:u})})).json();if(!f.success)throw new Error(f.error||`Failed to ${d}`);return f},l=ft({mutationFn:d=>i("cancel",d),onSuccess:()=>{re.success("Schedule cancelled — saved as draft"),n.invalidateQueries({queryKey:["scheduled-email-campaigns"]})},onError:d=>re.error(d.message)}),o=ft({mutationFn:d=>i("delete",d),onSuccess:()=>{re.success("Scheduled email deleted"),n.invalidateQueries({queryKey:["scheduled-email-campaigns"]})},onError:d=>re.error(d.message)}),c=ft({mutationFn:async({id:d,iso:u})=>{const{error:h}=await q.from("email_campaigns").update({scheduled_at:u,status:"scheduled"}).eq("id",d);if(h)throw h;await i("schedule",d)},onSuccess:()=>{re.success("Send time updated"),n.invalidateQueries({queryKey:["scheduled-email-campaigns"]})},onError:d=>re.error(d.message)});return a?e.jsx("div",{className:"text-center py-12 text-muted-foreground",children:"Loading scheduled emails..."}):r.length===0?e.jsx(Ne,{children:e.jsxs(Ie,{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(da,{className:"h-12 w-12 text-muted-foreground mb-3"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"No scheduled emails."}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Emails you schedule for the future will appear here."})]})}):e.jsx("div",{className:"space-y-3",children:r.map(d=>e.jsx(rqn,{campaign:d,onEdit:()=>t(`/admin/email-campaigns/new?edit=${d.id}`),onCancel:()=>l.mutate(d.id),onDelete:()=>o.mutate(d.id),onReschedule:u=>c.mutate({id:d.id,iso:u}),isBusy:l.isPending||o.isPending||c.isPending},d.id))})}function rqn({campaign:s,onEdit:t,onCancel:n,onDelete:r,onReschedule:a,isBusy:i}){const l=s.scheduled_at?new Date(s.scheduled_at):null,[o,c]=j.useState(!1),[d,u]=j.useState(l||void 0),[h,m]=j.useState(l?`${String(l.getHours()).padStart(2,"0")}:${String(l.getMinutes()).padStart(2,"0")}`:"09:00"),f=()=>{if(!d)return re.error("Pick a date");const g=new Date(`${en(d,"yyyy-MM-dd")}T${h}:00`).toISOString();if(new Date(g).getTime()gm(g.target.value)})]})]}),e.jsxs(Ar,{children:[e.jsx($,{variant:"ghost",onClick:()=>c(!1),children:"Cancel"}),e.jsxs($,{onClick:f,disabled:i,children:[i&&e.jsx(kt,{className:"h-4 w-4 mr-1.5 animate-spin"}),"Save new time"]})]})]})]}),e.jsxs(kc,{children:[e.jsx(jx,{asChild:!0,children:e.jsxs($,{size:"sm",variant:"outline",disabled:i,children:[e.jsx(ku,{className:"h-3.5 w-3.5 mr-1.5"})," Cancel Send"]})}),e.jsxs(cc,{children:[e.jsxs(dc,{children:[e.jsx(hc,{children:"Cancel this scheduled send?"}),e.jsxs(mc,{children:["The email will move back to ",e.jsx("strong",{children:"Draft"})," and won't send at the scheduled time. You can re-schedule or delete it later."]})]}),e.jsxs(uc,{children:[e.jsx(fc,{children:"Keep scheduled"}),e.jsx(tc,{onClick:n,children:"Cancel send"})]})]})]}),e.jsxs(kc,{children:[e.jsx(jx,{asChild:!0,children:e.jsxs($,{size:"sm",variant:"ghost",className:"text-destructive hover:text-destructive",disabled:i,children:[e.jsx(Wn,{className:"h-3.5 w-3.5 mr-1.5"})," Delete"]})}),e.jsxs(cc,{children:[e.jsxs(dc,{children:[e.jsx(hc,{children:"Delete this scheduled email?"}),e.jsx(mc,{children:"This permanently removes the scheduled email and all its recipient records. This can't be undone."})]}),e.jsxs(uc,{children:[e.jsx(fc,{children:"Keep"}),e.jsx(tc,{onClick:r,className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Delete permanently"})]})]})]})]})]})})})}function aqn({pct:s,size:t=132,label:n}){const a=(t-10)/2,i=2*Math.PI*a,l=Math.max(0,Math.min(100,s)),o=i-l/100*i;return e.jsxs("div",{className:"relative shrink-0",style:{width:t,height:t},children:[e.jsxs("svg",{width:t,height:t,className:"-rotate-90 text-primary",children:[e.jsx("circle",{cx:t/2,cy:t/2,r:a,fill:"none",strokeWidth:10,className:"stroke-muted"}),e.jsx("circle",{cx:t/2,cy:t/2,r:a,fill:"none",strokeWidth:10,strokeLinecap:"round",stroke:"currentColor",strokeDasharray:i,strokeDashoffset:o,style:{transition:"stroke-dashoffset 700ms ease"}})]}),e.jsxs("div",{className:"absolute inset-0 flex flex-col items-center justify-center",children:[e.jsxs("span",{className:"text-3xl font-semibold tabular-nums",children:[Math.round(l),"%"]}),e.jsx("span",{className:"text-[10px] uppercase tracking-wider text-muted-foreground",children:n})]})]})}function gue({icon:s,label:t,value:n,hint:r,tone:a="default",onClick:i}){const l=i?"button":"div";return e.jsxs(l,{onClick:i,className:Pt("group relative flex flex-col justify-between rounded-2xl border bg-card p-4 text-left transition-colors",i&&"hover:bg-accent/50 cursor-pointer",a==="warm"&&"border-orange-500/30 bg-orange-500/[0.04]",a==="alert"&&"border-amber-500/30 bg-amber-500/[0.04]"),children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("span",{className:"inline-flex items-center gap-1.5 text-[11px] font-medium uppercase tracking-wide text-muted-foreground",children:[s,t]}),i&&e.jsx(Di,{className:"h-3.5 w-3.5 text-muted-foreground opacity-0 group-hover:opacity-100 transition-opacity"})]}),e.jsxs("div",{className:"mt-2",children:[e.jsx("div",{className:"text-2xl font-semibold tabular-nums leading-none",children:n}),r&&e.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:r})]})]})}function iqn({total:s,opened:t,clicked:n,trackable:r,scheduled:a,rangeLabel:i,channelSummary:l,onScheduledClick:o}){const c=r>0?t/r*100:0,d=r>0?n/r*100:0;return e.jsx("div",{className:"rounded-3xl border bg-gradient-to-br from-primary/[0.06] via-card to-card p-5 md:p-6",children:e.jsxs("div",{className:"grid gap-5 lg:grid-cols-[auto_1fr] lg:items-center",children:[e.jsxs("div",{className:"flex items-center gap-5",children:[e.jsx(aqn,{pct:c,label:"open rate"}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-[11px] uppercase tracking-wider text-muted-foreground",children:i}),e.jsxs("h2",{className:"mt-1 text-xl font-semibold leading-tight",children:[s.toLocaleString()," email",s===1?"":"s"," sent"]}),e.jsx("p",{className:"mt-1 text-sm text-muted-foreground line-clamp-2",children:l||"No sends in this window yet."}),r>0&&e.jsxs("p",{className:"mt-2 text-xs text-muted-foreground",children:[t.toLocaleString()," opens · ",n.toLocaleString()," clicks across ",r.toLocaleString()," tracked"]})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3 xl:grid-cols-4",children:[e.jsx(gue,{icon:e.jsx(qr,{className:"h-3.5 w-3.5"}),label:"Delivered",value:s.toLocaleString(),hint:"All sends completed"}),e.jsx(gue,{icon:e.jsx(Ca,{className:"h-3.5 w-3.5"}),label:"Opened",value:t.toLocaleString(),hint:r>0?`${Math.round(c)}% of tracked`:"No tracked emails"}),e.jsx(gue,{icon:e.jsx(Lm,{className:"h-3.5 w-3.5"}),label:"Clicked",value:n.toLocaleString(),hint:r>0?`${Math.round(d)}% of tracked`:"No tracked emails",tone:n>0?"warm":"default"}),e.jsx(gue,{icon:e.jsx(da,{className:"h-3.5 w-3.5"}),label:"Scheduled",value:a.toLocaleString(),hint:a>0?"Editable before send":"Nothing queued",tone:a>0?"alert":"default",onClick:o})]})]})})}const LCt=["Gmail","Mass Email","Campaign","Client Portal Invite","Card Studio"],oqn={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","Card Studio":"bg-amber-100 text-amber-700 border-amber-200"};function lqn(){const{user:s}=vs(),[t,n]=gc(),{data:r=[],isLoading:a}=uJt(),[i,l]=j.useState(""),[o,c]=j.useState("all"),[d,u]=j.useState("30"),[h,m]=j.useState(!1),[f,g]=j.useState(t.get("tab")==="scheduled"?"scheduled":"sent"),{gmailEmail:x}=yy(),{data:y=0}=tt({queryKey:["scheduled-email-count",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{count:I}=await q.from("email_campaigns").select("id",{count:"exact",head:!0}).eq("user_id",s.id).eq("status","scheduled");return I||0},refetchInterval:3e4});j.useEffect(()=>{const I=new URLSearchParams(t);f==="scheduled"?I.set("tab","scheduled"):I.delete("tab"),n(I,{replace:!0})},[f]);const v=j.useMemo(()=>Array.from(new Set(r.map(I=>I.contact_id).filter(Boolean))),[r]),{data:b}=tt({queryKey:["sent-emails-contact-names",s==null?void 0:s.id,v.length],enabled:v.length>0,queryFn:async()=>{const{data:I}=await q.from("innercircle_contacts").select("id, first_name, last_name").in("id",v),P=new Map;return(I||[]).forEach(R=>{P.set(R.id,[R.first_name,R.last_name].filter(Boolean).join(" ")||"Contact")}),P}}),w=j.useMemo(()=>{const I=d==="all"?null:Date.now()-parseInt(d)*864e5,P=i.trim().toLowerCase();return r.filter(R=>{if(o!=="all"&&R.channel!==o||I&&new Date(R.sent_at).getTime(){const I={};let P=0,R=0,D=0;return w.forEach(O=>{I[O.channel]=(I[O.channel]||0)+1,(O.channel==="Campaign"||O.channel==="Mass Email")&&(D++,O.opened_at&&P++,O.clicked_at&&R++)}),{byChannel:I,opened:P,clicked:R,trackable:D}},[w]),C=d==="all"?"All time":`Last ${d} days`,E=LCt.map(I=>S.byChannel[I]?`${S.byChannel[I]} ${I}`:null).filter(Boolean).join(" · ");return e.jsx(Vs,{children:e.jsxs("div",{className:"space-y-5 p-4 md:p-8",children:[e.jsxs("div",{className:"flex flex-col gap-3 md:flex-row md:items-center md:justify-between",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("h1",{className:"text-2xl font-bold flex items-center gap-2",children:[e.jsx(Yr,{className:"h-6 w-6"})," Sent Emails"]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Every send in one place — Gmail, mass emails, campaigns, and portal invites."})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("div",{className:"inline-flex rounded-full border bg-muted/40 p-1",children:[e.jsxs("button",{onClick:()=>g("sent"),className:`inline-flex items-center gap-1.5 rounded-full px-3 py-1.5 text-sm transition-colors ${f==="sent"?"bg-background shadow-sm font-medium":"text-muted-foreground hover:text-foreground"}`,children:[e.jsx(Yr,{className:"h-3.5 w-3.5"})," Sent"]}),e.jsxs("button",{onClick:()=>g("scheduled"),className:`inline-flex items-center gap-1.5 rounded-full px-3 py-1.5 text-sm transition-colors ${f==="scheduled"?"bg-background shadow-sm font-medium":"text-muted-foreground hover:text-foreground"}`,children:[e.jsx(da,{className:"h-3.5 w-3.5"})," Scheduled",y>0&&e.jsx(Be,{variant:"secondary",className:"ml-0.5 h-5 min-w-5 px-1.5 text-xs",children:y})]})]}),e.jsxs($,{onClick:()=>m(!0),className:"rounded-full",children:[e.jsx(mn,{className:"h-4 w-4 mr-2"})," Send Email"]})]})]}),e.jsxs(ha,{value:f,onValueChange:I=>g(I),className:"space-y-5",children:[e.jsxs(Xt,{value:"sent",className:"space-y-5 mt-0",children:[e.jsx(iqn,{total:w.length,opened:S.opened,clicked:S.clicked,trackable:S.trackable,scheduled:y,rangeLabel:C,channelSummary:E,onScheduledClick:()=>g("scheduled")}),e.jsxs("div",{className:"flex flex-col gap-2 rounded-2xl border bg-card p-2 md:flex-row md:items-center",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(Kr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(pe,{placeholder:"Search subject, recipient, contact...",value:i,onChange:I=>l(I.target.value),className:"pl-9 border-0 bg-transparent shadow-none focus-visible:ring-0"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(ms,{value:o,onValueChange:c,children:[e.jsx(us,{className:"w-[170px] rounded-full h-9",children:e.jsx(fs,{})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"all",children:"All Channels"}),LCt.map(I=>e.jsx(Ge,{value:I,children:I},I))]})]}),e.jsxs(ms,{value:d,onValueChange:u,children:[e.jsx(us,{className:"w-[150px] rounded-full h-9",children:e.jsx(fs,{})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"7",children:"Last 7 days"}),e.jsx(Ge,{value:"30",children:"Last 30 days"}),e.jsx(Ge,{value:"90",children:"Last 90 days"}),e.jsx(Ge,{value:"365",children:"Last year"}),e.jsx(Ge,{value:"all",children:"All time"})]})]})]})]}),e.jsxs("p",{className:"text-xs text-muted-foreground -mt-3 px-1",children:[e.jsx(eC,{className:"h-3 w-3 inline mr-1"}),"Open & click tracking is available for Mass Emails and Campaigns. Emails sent through your connected Gmail inbox aren't tracked."]}),e.jsx(sqn,{rangeDays:d==="all"?null:parseInt(d)}),a?e.jsx("div",{className:"text-center py-12 text-muted-foreground",children:"Loading..."}):w.length===0?e.jsx(Ne,{className:"rounded-2xl",children:e.jsxs(Ie,{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(mn,{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(Ne,{className:"rounded-2xl overflow-hidden",children:e.jsx(Ie,{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("th",{className:"text-left py-3 px-4 font-medium",children:e.jsx(jk,{children:e.jsxs(ly,{children:[e.jsxs(cy,{className:"inline-flex items-center gap-1",children:["Engagement ",e.jsx(eC,{className:"h-3 w-3"})]}),e.jsx(Nx,{className:"max-w-xs",children:"Open & click tracking works for Mass Emails and Campaigns. Emails sent through your connected Gmail inbox aren't tracked."})]})})})]})}),e.jsx("tbody",{children:w.slice(0,500).map(I=>{const P=I.contact_id?b==null?void 0:b.get(I.contact_id):null,R=I.channel==="Campaign"||I.channel==="Mass Email";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:en(new Date(I.sent_at),"MMM d, yyyy h:mm a")}),e.jsx("td",{className:"py-3 px-4",children:e.jsx(Be,{variant:"outline",className:oqn[I.channel],children:I.channel})}),e.jsx("td",{className:"py-3 px-4 max-w-xs truncate font-medium",children:I.subject}),e.jsx("td",{className:"py-3 px-4 text-muted-foreground",children:I.to_email}),e.jsx("td",{className:"py-3 px-4",children:I.contact_id&&P?e.jsx(wr,{to:`/mission-control/contacts/${I.contact_id}`,className:"text-primary hover:underline",children:P}):e.jsx("span",{className:"text-muted-foreground",children:"—"})}),e.jsx("td",{className:"py-3 px-4",children:R?e.jsxs("div",{className:"flex flex-wrap gap-1",children:[e.jsxs(Be,{variant:"outline",className:"bg-slate-50 text-slate-700 border-slate-200 gap-1",children:[e.jsx(qr,{className:"h-3 w-3"})," Delivered"]}),I.opened_at&&e.jsxs(Be,{variant:"outline",className:"bg-blue-50 text-blue-700 border-blue-200 gap-1",children:[e.jsx(Ca,{className:"h-3 w-3"})," Opened"]}),I.clicked_at&&e.jsxs(Be,{variant:"outline",className:"bg-emerald-50 text-emerald-700 border-emerald-200 gap-1",children:[e.jsx(Lm,{className:"h-3 w-3"})," Clicked"]})]}):e.jsx("span",{className:"text-xs text-muted-foreground",children:"Not tracked"})})]},I.id)})})]}),w.length>500&&e.jsxs("p",{className:"text-xs text-muted-foreground text-center py-3 border-t",children:["Showing first 500 of ",w.length," — narrow your filters to see more."]})]})})})]}),e.jsx(Xt,{value:"scheduled",className:"mt-0",children:e.jsx(nqn,{})})]}),e.jsx(Ak,{open:h,onOpenChange:m,gmailEmail:x})]})})}const RCt={Crown:Bg,FileText:Jr,Users:Zn,Globe:dl,Star:Ja,Phone:Da,MessageSquare:eo,PenTool:RE,Video:ua,Gift:ul},xue=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function cqn(){var rt,Yt;const s=Qn(),{user:t}=vs(),{data:n}=Yw(),{data:r}=qHs(),{data:a}=ZHs(),{data:i}=FUt(),{data:l}=iie(),{data:o}=UHs(),c=XHs(),d=VHs(),u=GHs(),h=WHs(),m=KHs(),f=YHs(),g=HHs(),[x,y]=j.useState(null),[v,b]=j.useState(!1),[w,S]=j.useState(null),[C,E]=j.useState(""),[I,P]=j.useState(""),[R,D]=j.useState([]),[O,U]=j.useState(null),[W,V]=j.useState(null),[G,Y]=j.useState(null),[X,ae]=j.useState(!1),[ie,ne]=j.useState(""),[te,J]=j.useState(""),[ce,_e]=j.useState(""),[he,ue]=j.useState(""),ve=(qt,ts)=>a==null?void 0:a.some(ys=>ys.plan_id===qt&&ys.relationship_type_id===ts&&ys.active),Ee=qt=>a==null?void 0:a.find(ts=>ts.relationship_type_id===qt&&ts.active),Se=async(qt,ts)=>{const ys=ve(qt,ts);await c.mutateAsync({planId:qt,relationshipTypeId:ts,active:!ys})},Le=(r==null?void 0:r.filter(qt=>qt.active&&!qt.owner_user_id))||[],Fe=(r==null?void 0:r.filter(qt=>qt.owner_user_id===(t==null?void 0:t.id)))||[],ke=n==null?void 0:n.find(qt=>qt.id===x),Ve=x?Ee(x):null,je=r==null?void 0:r.find(qt=>qt.id===(Ve==null?void 0:Ve.plan_id)),Ae=async()=>{if(!C.trim())return;const qt=await d.mutateAsync({name:C,description:I});qt&&R.length>0&&await m.mutateAsync({planId:qt.id,items:R}),$e()},Ce=async()=>{!C.trim()||!w||(await u.mutateAsync({id:w,name:C,description:I}),await m.mutateAsync({planId:w,items:R}),$e())},qe=qt=>{var ts;S(qt.id),E(qt.name),P(qt.description||""),D(((ts=qt.items)==null?void 0:ts.map(ys=>({month_number:ys.month_number,action_type_id:ys.action_type_id,default_script_id:ys.default_script_id||void 0,notes:ys.notes||void 0})))||[]),b(!0)},ze=async(qt,ts)=>{if(qt.owner_user_id===(t==null?void 0:t.id)){qe(qt);return}try{const ys=await g.mutateAsync({sourcePlanId:qt.id,newName:`${qt.name} (My Copy)`});if(!ys)return;await c.mutateAsync({planId:qt.id,relationshipTypeId:ts,active:!1}),await c.mutateAsync({planId:ys.id,relationshipTypeId:ts,active:!0}),S(ys.id),E(ys.name),P(ys.description||""),D((qt.items||[]).map(Bt=>({month_number:Bt.month_number,action_type_id:Bt.action_type_id,default_script_id:Bt.default_script_id||void 0,notes:Bt.notes||void 0}))),b(!0)}catch{}},$e=()=>{b(!1),S(null),E(""),P(""),D([])},ct=(qt,ts)=>{V(ts)},Xe=(qt,ts,ys)=>{D(Bt=>[...Bt.filter(rs=>rs.month_number!==qt),{month_number:qt,action_type_id:ts,default_script_id:ys}]),U(null),V(null)},it=qt=>{D(ts=>ts.filter(ys=>ys.month_number!==qt))},at=async()=>{if(!ie.trim()||!te.trim()||!W)return;const qt=await f.mutateAsync({actionTypeId:W,title:ie,scriptBody:te,emailSubject:ce||void 0,tone:he||void 0});qt&&O!==null&&Xe(O,W,qt.id),ae(!1),ne(""),J(""),_e(""),ue("")},Ke=W?o==null?void 0:o.filter(qt=>qt.action_type_id===W&&qt.active):[],nt=qt=>RCt[qt||"Phone"]||Da,xt=qt=>RCt[qt||"Users"]||Zn;return e.jsxs(Vs,{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($,{variant:"ghost",size:"sm",onClick:()=>s("/mission-control"),children:[e.jsx(Cd,{className:"h-4 w-4 mr-1"}),"Back"]}),e.jsxs($,{onClick:()=>b(!0),className:"w-full sm:w-auto",children:[e.jsx(dn,{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"}),n==null?void 0:n.filter(qt=>qt.active).map(qt=>{const ts=xt(qt.icon),ys=(i==null?void 0:i[qt.id])||0,Bt=Ee(qt.id),Ft=r==null?void 0:r.find(St=>St.id===(Bt==null?void 0:Bt.plan_id)),rs=x===qt.id;return e.jsxs("button",{onClick:()=>y(qt.id),className:` w-full flex items-center gap-3 p-4 rounded-lg border text-left transition-all ${rs?"border-primary bg-primary/5 ring-2 ring-primary":"hover:bg-accent"} `,children:[e.jsx(ts,{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:qt.name}),e.jsxs("div",{className:"text-sm text-muted-foreground",children:[ys," contacts"]})]}),Ft?e.jsxs(Be,{variant:"secondary",className:"text-xs",children:[e.jsx(Nc,{className:"h-3 w-3 mr-1"}),Ft.name.split(" ")[0]]}):e.jsx(Be,{variant:"outline",className:"text-xs text-muted-foreground",children:"No plan"})]},qt.id)})]}),e.jsx("div",{className:"lg:col-span-2",children:x&&ke?e.jsxs(Ne,{children:[e.jsxs(Ct,{children:[e.jsxs(At,{className:"flex items-center gap-2",children:[(()=>{const qt=xt(ke.icon);return e.jsx(qt,{className:"h-5 w-5"})})(),ke.name," Touchpoint Plan"]}),e.jsxs(Gn,{children:["Choose a plan for your ",ke.name," contacts"]})]}),e.jsxs(Ie,{className:"space-y-6",children:[je&&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(Nc,{className:"h-4 w-4 text-green-500"}),"Currently using: ",je.name]}),je.description&&e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:je.description})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs($,{variant:"outline",size:"sm",disabled:g.isPending||c.isPending,onClick:()=>ze(je,x),children:[e.jsx(LN,{className:"h-4 w-4 mr-1"}),"Edit Steps"]}),e.jsx($,{variant:"outline",size:"sm",onClick:()=>Se(je.id,x),children:"Disable"})]})]}),je.items&&je.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(Ta,{className:"h-4 w-4"}),"12-Month Schedule"]}),e.jsx("div",{className:"grid grid-cols-4 sm:grid-cols-6 gap-2",children:xue.map((qt,ts)=>{var rs,St;const ys=((rs=je.items)==null?void 0:rs.filter(Xs=>Xs.month_number===ts+1))||[],Bt=(St=ys[0])==null?void 0:St.action_type,Ft=Bt?nt(Bt.icon):null;return e.jsxs("div",{className:` p-2 rounded border text-center ${ys.length>0?"bg-primary/10 border-primary":"bg-muted"} `,children:[e.jsx("div",{className:"text-xs text-muted-foreground",children:qt}),Ft&&e.jsx(Ft,{className:"h-4 w-4 mx-auto mt-1",style:{color:(Bt==null?void 0:Bt.color)||"#3B82F6"}})]},ts)})})]})]}),e.jsxs("div",{children:[e.jsx("h4",{className:"font-medium mb-3",children:je?"Switch to a Different Plan":"Choose a Plan"}),Le.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"}),Le.map(qt=>{var ys;const ts=(je==null?void 0:je.id)===qt.id;return e.jsxs("div",{className:` flex items-center justify-between p-3 rounded-lg border ${ts?"opacity-50":"hover:bg-accent"} `,children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:qt.name}),e.jsxs("div",{className:"text-sm text-muted-foreground",children:[((ys=qt.items)==null?void 0:ys.length)||0," touchpoints/year"]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx($,{size:"sm",variant:"ghost",title:"View plan details",onClick:()=>Y(qt.id),children:e.jsx(Ca,{className:"h-4 w-4"})}),e.jsx($,{size:"sm",variant:"ghost",title:"Duplicate as my own plan",disabled:g.isPending,onClick:()=>{const Bt=`${qt.name} (Copy)`;g.mutate({sourcePlanId:qt.id,newName:Bt})},children:e.jsx(Ha,{className:"h-4 w-4"})}),e.jsx($,{size:"sm",variant:ts?"outline":"default",disabled:ts||c.isPending,onClick:()=>Se(qt.id,x),children:ts?"Active":"Use This"})]})]},qt.id)})]}),Fe.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"text-sm text-muted-foreground",children:"My Custom Plans"}),Fe.map(qt=>{var ys;const ts=(je==null?void 0:je.id)===qt.id;return e.jsxs("div",{className:` flex items-center justify-between p-3 rounded-lg border ${ts?"opacity-50":"hover:bg-accent"} `,children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:qt.name}),e.jsxs("div",{className:"text-sm text-muted-foreground",children:[((ys=qt.items)==null?void 0:ys.length)||0," touchpoints/year"]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx($,{size:"sm",variant:"ghost",title:"View plan details",onClick:()=>Y(qt.id),children:e.jsx(Ca,{className:"h-4 w-4"})}),e.jsx($,{size:"sm",variant:"ghost",title:"Edit plan",onClick:()=>qe(qt),children:e.jsx(LN,{className:"h-4 w-4"})}),e.jsx($,{size:"sm",variant:"ghost",title:"Delete plan",onClick:()=>h.mutate(qt.id),children:e.jsx(Wn,{className:"h-4 w-4 text-destructive"})}),e.jsx($,{size:"sm",variant:ts?"outline":"default",disabled:ts||c.isPending,onClick:()=>Se(qt.id,x),children:ts?"Active":"Use This"})]})]},qt.id)})]}),Le.length===0&&Fe.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(Ne,{children:e.jsxs(Ie,{className:"py-12 text-center text-muted-foreground",children:[e.jsx(Ta,{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(Ne,{className:"bg-muted/50",children:e.jsx(Ie,{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(zs,{open:v,onOpenChange:qt=>{qt?b(!0):$e()},children:e.jsxs(Os,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(Us,{children:e.jsx(Bs,{children:w?"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(ee,{htmlFor:"plan-name",children:"Plan Name"}),e.jsx(pe,{id:"plan-name",value:C,onChange:qt=>E(qt.target.value),placeholder:"e.g., My VIP Plan"})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"plan-description",children:"Description (optional)"}),e.jsx(Rs,{id:"plan-description",value:I,onChange:qt=>P(qt.target.value),placeholder:"Describe your plan...",rows:2})]})]}),e.jsxs("div",{children:[e.jsx(ee,{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:xue.map((qt,ts)=>{const ys=ts+1,Bt=R.find(St=>St.month_number===ys),Ft=Bt?l==null?void 0:l.find(St=>St.id===Bt.action_type_id):null,rs=Ft?nt(Ft.icon):null;return e.jsxs("div",{className:"relative",children:[e.jsxs("button",{type:"button",onClick:()=>U(O===ys?null:ys),className:` w-full p-3 rounded-lg border text-center transition-all ${Bt?"bg-primary/10 border-primary":"bg-muted hover:bg-accent"} ${O===ys?"ring-2 ring-primary":""} `,children:[e.jsx("div",{className:"text-xs text-muted-foreground font-medium",children:qt}),rs?e.jsx(rs,{className:"h-5 w-5 mx-auto mt-1",style:{color:(Ft==null?void 0:Ft.color)||"#3B82F6"}}):e.jsx(dn,{className:"h-5 w-5 mx-auto mt-1 text-muted-foreground/50"})]}),Bt&&e.jsx("button",{type:"button",onClick:St=>{St.stopPropagation(),it(ys)},className:"absolute -top-1 -right-1 p-1 bg-destructive text-destructive-foreground rounded-full",children:e.jsx(gr,{className:"h-3 w-3"})})]},ts)})}),O!==null&&!W&&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 ",xue[O-1],":"]}),e.jsx("div",{className:"flex flex-wrap gap-2",children:l==null?void 0:l.filter(qt=>qt.active).map(qt=>{const ts=nt(qt.icon);return e.jsxs("button",{type:"button",onClick:()=>ct(O,qt.id),className:"flex items-center gap-2 px-3 py-2 rounded-lg border bg-background hover:bg-accent transition-colors",children:[e.jsx(ts,{className:"h-4 w-4",style:{color:qt.color||"#3B82F6"}}),e.jsx("span",{className:"text-sm",children:qt.name})]},qt.id)})})]}),O!==null&&W&&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($,{variant:"ghost",size:"sm",onClick:()=>V(null),children:[e.jsx(Cd,{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:()=>Xe(O,W),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"})]})}),Ke==null?void 0:Ke.map(qt=>e.jsx("button",{type:"button",onClick:()=>Xe(O,W,qt.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:qt.title}),qt.tone&&e.jsx(Be,{variant:"secondary",className:"text-xs mt-1",children:qt.tone}),e.jsxs("div",{className:"text-xs text-muted-foreground mt-1 line-clamp-2",children:[qt.script_body.substring(0,100),"..."]})]})},qt.id)),e.jsxs("button",{type:"button",onClick:()=>ae(!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(dn,{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"})]})]})]})]})]}),R.length>0&&e.jsxs("div",{className:"text-sm text-muted-foreground",children:[R.length," touchpoint",R.length!==1?"s":""," per year"]})]}),e.jsxs(Ar,{children:[e.jsx($,{variant:"outline",onClick:$e,children:"Cancel"}),e.jsxs($,{onClick:w?Ce:Ae,disabled:!C.trim()||d.isPending||u.isPending,children:[e.jsx(tl,{className:"h-4 w-4 mr-2"}),w?"Save Changes":"Create Plan"]})]})]})}),e.jsx(zs,{open:X,onOpenChange:ae,children:e.jsxs(Os,{className:"max-w-lg",children:[e.jsx(Us,{children:e.jsx(Bs,{children:"Create Custom Script"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"script-title",children:"Script Title"}),e.jsx(pe,{id:"script-title",value:ie,onChange:qt=>ne(qt.target.value),placeholder:"e.g., Friendly Check-in Call"})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"script-tone",children:"Tone (optional)"}),e.jsxs(ms,{value:he,onValueChange:ue,children:[e.jsx(us,{children:e.jsx(fs,{placeholder:"Select tone..."})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"friendly",children:"Friendly"}),e.jsx(Ge,{value:"professional",children:"Professional"}),e.jsx(Ge,{value:"casual",children:"Casual"}),e.jsx(Ge,{value:"formal",children:"Formal"})]})]})]}),((Yt=(rt=l==null?void 0:l.find(qt=>qt.id===W))==null?void 0:rt.name)==null?void 0:Yt.toLowerCase().includes("email"))&&e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"script-email-subject",children:"Email Subject"}),e.jsx(pe,{id:"script-email-subject",value:ce,onChange:qt=>_e(qt.target.value),placeholder:"e.g., Quick Hello!"})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"script-body",children:"Script Content"}),e.jsx(Rs,{id:"script-body",value:te,onChange:qt=>J(qt.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(Ar,{children:[e.jsx($,{variant:"outline",onClick:()=>ae(!1),children:"Cancel"}),e.jsxs($,{onClick:at,disabled:!ie.trim()||!te.trim()||f.isPending,children:[e.jsx(tl,{className:"h-4 w-4 mr-2"}),"Create & Use Script"]})]})]})}),e.jsx(zs,{open:!!G,onOpenChange:qt=>{qt||Y(null)},children:e.jsx(Os,{className:"max-w-3xl max-h-[90vh] overflow-y-auto",children:(()=>{const qt=r==null?void 0:r.find(Bt=>Bt.id===G);if(!qt)return null;const ts=qt.owner_user_id===(t==null?void 0:t.id),ys=[...qt.items||[]].sort((Bt,Ft)=>Bt.month_number-Ft.month_number);return e.jsxs(e.Fragment,{children:[e.jsxs(Us,{children:[e.jsxs(Bs,{className:"flex items-center gap-2",children:[qt.name,!ts&&e.jsx(Be,{variant:"secondary",children:"Template"})]}),qt.description&&e.jsx("p",{className:"text-sm text-muted-foreground",children:qt.description})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"text-sm text-muted-foreground",children:[ys.length," touchpoint",ys.length!==1?"s":""," per year"]}),e.jsx("div",{className:"space-y-2",children:Array.from({length:12},(Bt,Ft)=>Ft+1).map(Bt=>{const Ft=ys.find(vt=>vt.month_number===Bt),rs=Ft?l==null?void 0:l.find(vt=>vt.id===Ft.action_type_id):null,St=Ft!=null&&Ft.default_script_id?o==null?void 0:o.find(vt=>vt.id===Ft.default_script_id):null,Xs=rs?nt(rs.icon):null;return e.jsxs("div",{className:`p-3 rounded-lg border flex items-start gap-3 ${Ft?"bg-muted/30":"opacity-60"}`,children:[e.jsx("div",{className:"w-16 shrink-0 font-medium text-sm",children:xue[Bt-1]}),Ft&&rs?e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[Xs&&e.jsx(Xs,{className:"h-4 w-4",style:{color:rs.color||"#3B82F6"}}),e.jsx("span",{className:"font-medium text-sm",children:rs.name}),St&&e.jsx(Be,{variant:"outline",className:"text-xs",children:St.title})]}),St&&e.jsx("div",{className:"mt-2 text-sm text-muted-foreground whitespace-pre-wrap bg-background p-2 rounded border",children:St.script_body}),Ft.notes&&e.jsx("div",{className:"mt-1 text-xs text-muted-foreground italic",children:Ft.notes})]}):e.jsx("div",{className:"flex-1 text-sm text-muted-foreground",children:"No touchpoint scheduled"})]},Bt)})})]}),e.jsxs(Ar,{children:[e.jsx($,{variant:"outline",onClick:()=>Y(null),children:"Close"}),ts?e.jsxs($,{onClick:()=>{const Bt=r==null?void 0:r.find(Ft=>Ft.id===G);Bt&&(Y(null),qe(Bt))},children:[e.jsx(LN,{className:"h-4 w-4 mr-2"}),"Edit Plan"]}):e.jsxs($,{disabled:g.isPending,onClick:()=>{g.mutate({sourcePlanId:qt.id,newName:`${qt.name} (Copy)`}),Y(null)},children:[e.jsx(Ha,{className:"h-4 w-4 mr-2"}),"Duplicate to Edit"]})]})]})})()})})]})}const s$e="https://cma.relevelup.com";function pJt({open:s,onOpenChange:t,cma:n}){var Y;const{user:r}=vs(),{toast:a}=Bi(),[i,l]=j.useState([]),[o,c]=j.useState(null),[d,u]=j.useState(!1),[h,m]=j.useState(""),[f,g]=j.useState(""),[x,y]=j.useState(""),[v,b]=j.useState(!1),[w,S]=j.useState(null),[C,E]=j.useState(!1),[I,P]=j.useState(!1),[R,D]=j.useState(null);j.useEffect(()=>{!s||!r||(async()=>{var _e;const[X,ae,ie,ne,te]=await Promise.all([q.from("innercircle_contacts").select("id, first_name, last_name, email").eq("owner_user_id",r.id).not("email","is",null).order("first_name"),q.from("profiles").select("name, email, phone, brokerage_name, avatar_url, email_signature").eq("id",r.id).maybeSingle(),q.from("gmail_integrations").select("id, is_active").eq("user_id",r.id).maybeSingle(),q.from("ses_verified_emails").select("email, status").eq("user_id",r.id).eq("status","Success").limit(1),q.from("mass_email_settings").select("*").eq("user_id",r.id).maybeSingle()]),J=(X.data||[]).filter(he=>he.email&&he.email.includes("@"));l(J),S(ae.data||null),E(!!((_e=ie.data)!=null&&_e.is_active)),P(!!(ne.data&&ne.data.length>0)),D(te.data||null);const ce=n.contact_id?J.find(he=>he.id===n.contact_id):null;ce&&(c(ce),m(ce.email))})()},[s,r,n.contact_id]),j.useEffect(()=>{var ne;if(!s)return;const X=((ne=n.subject)==null?void 0:ne.address)||"your home",ae=((w==null?void 0:w.name)||"").split(" ")[0]||"your agent",ie=(o==null?void 0:o.first_name)||"there";g(`Your home value report for ${X}`),y(`Hi ${ie}, I put together a fresh market analysis for ${X}. It pulls live comparable sales, active listings, and pending homes near you so you can see exactly where your value sits today. Take a look here — it only takes a minute: {{cma_link}} When you've had a chance to review, I'd love to hear your thoughts. Reply to this email or give me a call any time. Talk soon, ${(w==null?void 0:w.name)||ae}`)},[s,o==null?void 0:o.id,w==null?void 0:w.name,(Y=n.subject)==null?void 0:Y.address]);const O=j.useMemo(()=>C?"Gmail (your inbox)":I?"Amazon SES":null,[C,I]),U=!!(h.trim()&&f.trim()&&x.trim()&&O&&!v),W=X=>{c(X),m(X.email||""),u(!1)},V=X=>{const ae=`${s$e}/${n.share_token}?e=${X}`,te=x.replace(/&/g,"&").replace(//g,">").replace(/\{\{cma_link\}\}/g,`View Your Home Value Report`).split(/\n{2,}/).map(_e=>`

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

`).join(""),J=w!=null&&w.use_email_signature&&(w!=null&&w.email_signature)?`
${w.email_signature}
`:`
${w!=null&&w.name?`
${w.name}
`:""} ${w!=null&&w.brokerage_name?`
${w.brokerage_name}
`:""} ${w!=null&&w.phone?`
${w.phone}
`:""} ${w!=null&&w.email?``:""}
`,ce=``;return`
${te} ${J}
Prepared with LevelUp · ReLevelUp Real Estate
${ce}
`},G=async()=>{if(!(!r||!U)){b(!0);try{const{data:X,error:ae}=await q.from("cma_email_sends").insert({cma_id:n.id,agent_id:r.id,contact_id:(o==null?void 0:o.id)??null,recipient_email:h.trim(),subject:f.trim(),sent_via:C?"gmail":"ses"}).select("id").single();if(ae)throw ae;const ie=V(X.id);if(C){const{data:ne,error:te}=await q.functions.invoke("gmail-send",{body:{to:h.trim(),subject:f.trim(),body:ie}});if(te)throw te;if(!(ne!=null&&ne.success))throw new Error((ne==null?void 0:ne.error)||"Gmail send failed")}else if(I){const ne=(R==null?void 0:R.display_name)||(w==null?void 0:w.name)||"ReLevelUp",te=`${ne.toLowerCase().replace(/[^a-z]/g,".").replace(/^\.+|\.+$/g,"")||"noreply"}@send.relevelup.com`,{data:J,error:ce}=await q.functions.invoke("ses-send-campaign",{body:{action:"test_send",to:h.trim(),from_email:`${ne} <${te}>`,subject:f.trim(),body_html:ie,reply_to:(R==null?void 0:R.reply_to_email)||(w==null?void 0:w.email)||void 0}});if(ce)throw ce;if(!(J!=null&&J.success))throw new Error((J==null?void 0:J.error)||"SES send failed")}o&&!n.contact_id&&await q.from("cmas").update({contact_id:o.id}).eq("id",n.id),a({title:"CMA sent",description:`Delivered to ${h.trim()}`}),t(!1)}catch(X){console.error("Send CMA error:",X),a({title:"Send failed",description:X.message||"Could not send email",variant:"destructive"})}finally{b(!1)}}};return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Os,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(Us,{children:e.jsxs(Bs,{className:"flex items-center gap-2",children:[e.jsx(mn,{className:"w-5 h-5"}),"Send CMA to contact"]})}),O?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"text-xs text-muted-foreground",children:["Sending via ",e.jsx("span",{className:"font-semibold text-foreground",children:O})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Contact"}),e.jsxs(Yd,{open:d,onOpenChange:u,children:[e.jsx(Zd,{asChild:!0,children:e.jsxs($,{variant:"outline",role:"combobox",className:"w-full justify-between font-normal",children:[o?`${o.first_name} ${o.last_name||""}`.trim():"Pick a contact (optional)",e.jsx(Pw,{className:"w-4 h-4 opacity-50"})]})}),e.jsx(Bd,{className:"w-[--radix-popover-trigger-width] p-0",align:"start",children:e.jsxs(P2,{children:[e.jsx(I2,{placeholder:"Search contacts…"}),e.jsxs(L2,{children:[e.jsx(R2,{children:"No contacts with email found."}),e.jsx(Uw,{children:i.map(X=>e.jsxs(g1,{value:`${X.first_name} ${X.last_name||""} ${X.email}`,onSelect:()=>W(X),children:[e.jsx(la,{className:Pt("w-4 h-4 mr-2",(o==null?void 0:o.id)===X.id?"opacity-100":"opacity-0")}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"font-medium",children:[X.first_name," ",X.last_name||""]}),e.jsx("div",{className:"text-xs text-muted-foreground truncate",children:X.email})]})]},X.id))})]})]})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"To email"}),e.jsx(pe,{type:"email",value:h,onChange:X=>m(X.target.value),placeholder:"client@example.com"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Subject"}),e.jsx(pe,{value:f,onChange:X=>g(X.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Message"}),e.jsx(Rs,{rows:10,value:x,onChange:X=>y(X.target.value)}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[e.jsx("code",{children:"{{cma_link}}"})," will be replaced with a styled button linking to ",e.jsxs("code",{children:["cma.relevelup.com/",n.share_token]}),". Email opens are tracked and shown on the contact's Signals."]})]}),e.jsxs("div",{className:"rounded border bg-muted/40 p-3 text-sm flex items-center gap-2",children:[e.jsx(kr,{className:"w-4 h-4 text-muted-foreground"}),e.jsx("span",{className:"text-muted-foreground",children:"Public link:"}),e.jsx("a",{className:"text-primary underline truncate",href:`${s$e}/${n.share_token}`,target:"_blank",rel:"noreferrer",children:`${s$e}/${n.share_token}`})]})]}):e.jsx("div",{className:"p-4 rounded border bg-amber-50 text-amber-900 text-sm",children:"Connect Gmail or set up Amazon SES under Integrations to send CMAs by email."}),e.jsxs(Ar,{children:[e.jsx($,{variant:"ghost",onClick:()=>t(!1),children:"Cancel"}),e.jsxs($,{onClick:G,disabled:!U,children:[v?e.jsx(kt,{className:"w-4 h-4 mr-2 animate-spin"}):e.jsx(Yr,{className:"w-4 h-4 mr-2"}),"Send CMA"]})]})]})})}function dqn(s){const{user:t}=vs(),n=Vt(),{data:r}=tt({queryKey:["lead-site-upgrade-requests",t==null?void 0:t.id],enabled:!!t,queryFn:async()=>{const{data:l,error:o}=await q.from("lead_site_upgrade_requests").select("id, feature_key, status, created_at").eq("user_id",t.id);if(o)throw o;return l}}),a=ft({mutationFn:async({featureKey:l,notes:o})=>{const{error:c}=await q.from("lead_site_upgrade_requests").insert({user_id:t.id,site_id:s??null,feature_key:l,notes:o??null});if(c)throw c},onSuccess:()=>{n.invalidateQueries({queryKey:["lead-site-upgrade-requests",t==null?void 0:t.id]}),re.success("Request sent — we'll reach out about upgrading your site.")},onError:l=>re.error((l==null?void 0:l.message)||"Could not send your request")});return{requestUpgrade:a,hasRequested:l=>!!(r!=null&&r.some(o=>o.feature_key===l&&o.status!=="declined")),isSending:a.isPending}}const uqn="free_luxury",hqn="free_beta";function gJt(s){const t=s==null?void 0:s.planTier;return t===uqn||t===hqn}const mqn={idx_search:{title:"MLS / IDX Home Search",description:"Let visitors search every active MLS listing in your market, with saved searches and instant alerts."},mls_listings:{title:"MLS Listing Feeds",description:"Automatically feature live MLS listings, new listings and sold comps on your homepage and city pages."},cma_reports:{title:"CMA Reports",description:"Build branded comparative market analyses with live MLS comps and share them with sellers."},custom_domain:{title:"Custom Branded Domain",description:"Point your own web address at your site instead of the free subdomain."},ai_content:{title:"AI Content Creation",description:"Auto-written blog posts, city guides and monthly market updates published to your site."}};function fqn({featureKey:s,siteId:t,bullets:n}){const r=mqn[s],{requestUpgrade:a,hasRequested:i,isSending:l}=dqn(t),o=i(s);return e.jsx("section",{className:"rounded-xl border border-amber-500/30 bg-gradient-to-br from-amber-500/10 via-card to-card p-6",children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx("div",{className:"h-10 w-10 shrink-0 rounded-full bg-amber-500/15 flex items-center justify-center",children:e.jsx(pc,{className:"h-5 w-5 text-amber-500"})}),e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h2",{className:"text-lg font-semibold text-foreground",children:r.title}),e.jsx("span",{className:"text-[10px] font-bold uppercase tracking-wide px-2 py-0.5 rounded-full bg-amber-100 text-amber-700",children:"Upgrade"})]}),e.jsx("p",{className:"mt-1 text-sm text-muted-foreground",children:r.description}),n!=null&&n.length?e.jsx("ul",{className:"mt-4 space-y-2",children:n.map(c=>e.jsxs("li",{className:"flex items-start gap-2 text-sm text-muted-foreground",children:[e.jsx(Nn,{className:"h-4 w-4 mt-0.5 text-amber-500 shrink-0"}),c]},c))}):null,e.jsx($,{className:"mt-5",disabled:o||l,onClick:()=>a.mutate({featureKey:s}),children:o?e.jsxs(e.Fragment,{children:[e.jsx(la,{className:"h-4 w-4 mr-2"})," Upgrade requested"]}):"Request this upgrade"})]})]})})}function pqn({onCreated:s}){const[t,n]=j.useState(!1),[r,a]=j.useState(""),[i,l]=j.useState(""),[o,c]=j.useState(""),[d,u]=j.useState(""),h=gUn(),m=iJt(),{toast:f}=Bi(),[g,x]=j.useState([]),y=async()=>{var w;x([]);try{const S=await h.mutateAsync({address:r,city:i,state:o,zip:d});x(S.matches||[]),(w=S.matches)!=null&&w.length||f({title:"No MLS match",description:'Use "Create from manual entry" below.'})}catch(S){f({title:"Search failed",description:S.message,variant:"destructive"})}},v=async w=>{const S=await m.mutateAsync({subject:w});n(!1),s(S.id)},b=async()=>{if(!r||!i||!o){f({title:"Address, city, state required"});return}const w=await m.mutateAsync({subject:{address:r,city:i,state:o,zip:d}});n(!1),s(w.id)};return e.jsxs(zs,{open:t,onOpenChange:n,children:[e.jsx(jl,{asChild:!0,children:e.jsxs($,{children:[e.jsx(dn,{className:"w-4 h-4 mr-2"}),"New CMA"]})}),e.jsxs(Os,{className:"max-w-2xl",children:[e.jsx(Us,{children:e.jsx(Bs,{children:"Start a CMA"})}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-4 gap-2",children:[e.jsx(pe,{className:"md:col-span-2",placeholder:"Street address",value:r,onChange:w=>a(w.target.value)}),e.jsx(pe,{placeholder:"City",value:i,onChange:w=>l(w.target.value)}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(pe,{placeholder:"ST",maxLength:2,value:o,onChange:w=>c(w.target.value.toUpperCase())}),e.jsx(pe,{placeholder:"ZIP",value:d,onChange:w=>u(w.target.value)})]})]}),e.jsxs($,{onClick:y,disabled:!r||h.isPending,className:"w-full",children:[h.isPending?e.jsx(kt,{className:"w-4 h-4 mr-2 animate-spin"}):e.jsx(Kr,{className:"w-4 h-4 mr-2"}),"Find in MLS"]}),g.length>0&&e.jsxs("div",{className:"space-y-2 max-h-80 overflow-y-auto",children:[e.jsxs("p",{className:"text-sm text-muted-foreground",children:[g.length," match(es) — pick the subject property:"]}),g.map((w,S)=>{var C;return e.jsxs("button",{onClick:()=>v(w),className:"w-full text-left p-3 border rounded hover:bg-accent transition",children:[e.jsx("div",{className:"font-medium",children:w.address}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[w.city,", ",w.state," ",w.zip," · ",w.bedrooms??"?"," bd / ",w.bathrooms??"?"," ba · ",((C=w.sqft)==null?void 0:C.toLocaleString())??"?"," sqft",w.mlsNumber?` · MLS# ${w.mlsNumber}`:""," · ",w.source_provider]})]},S)})]}),e.jsx("div",{className:"border-t pt-3",children:e.jsxs($,{variant:"outline",onClick:b,disabled:m.isPending,className:"w-full",children:[e.jsx(va,{className:"w-4 h-4 mr-2"}),"Create from manual entry"]})})]})]})]})}function gqn(){const{data:s,isLoading:t}=uUn(),n=pUn(),r=Qn(),{toast:a}=Bi(),[i,l]=j.useState(null),{isFreePlan:o,leadSite:c}=ng();return o?e.jsx(Vs,{children:e.jsxs("div",{className:"container mx-auto p-4 md:p-6 max-w-3xl space-y-6",children:[e.jsxs("h1",{className:"text-2xl md:text-3xl font-bold flex items-center gap-2",children:[e.jsx(Jr,{className:"w-7 h-7"})," CMAs"]}),e.jsx(fqn,{featureKey:"cma_reports",siteId:c==null?void 0:c.id,bullets:["Pull live MLS comparables for any subject property","Interactive, shareable CMA presentations for sellers","Track when your seller opens and interacts with the report"]})]})}):e.jsx(Vs,{children:e.jsxs("div",{className:"container mx-auto p-4 md:p-6 max-w-6xl",children:[e.jsxs("div",{className:"flex items-center justify-between mb-6",children:[e.jsxs("div",{children:[e.jsxs("h1",{className:"text-2xl md:text-3xl font-bold flex items-center gap-2",children:[e.jsx(Jr,{className:"w-7 h-7"})," CMAs"]}),e.jsx("p",{className:"text-muted-foreground text-sm",children:"Comparative Market Analyses — interactive, shareable, no static PDFs."})]}),e.jsx(pqn,{onCreated:d=>r(`/mission-control/cma/${d}`)})]}),t?e.jsx("p",{className:"text-muted-foreground",children:"Loading…"}):s!=null&&s.length?e.jsx("div",{className:"grid gap-3",children:s.map(d=>{var u,h,m;return e.jsx(Ne,{className:"hover:shadow-md transition",children:e.jsxs(Ie,{className:"p-4 flex flex-wrap items-center gap-3 justify-between",children:[e.jsxs("div",{className:"flex-1 min-w-[200px]",children:[e.jsx("div",{className:"font-semibold",children:d.title||((u=d.subject)==null?void 0:u.address)||"Untitled CMA"}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[(h=d.subject)==null?void 0:h.city,", ",(m=d.subject)==null?void 0:m.state," · ",d.buyer_mode?"Buyer":"Seller"," ·"," ",e.jsx(Be,{variant:d.status==="shared"?"default":"secondary",className:"ml-1",children:d.status})]}),d.price_likely?e.jsxs("div",{className:"text-sm mt-1",children:["Suggested: ",e.jsxs("span",{className:"font-medium",children:["$",d.price_likely.toLocaleString()]}),d.price_low&&d.price_high?e.jsxs("span",{className:"text-muted-foreground",children:[" · $",d.price_low.toLocaleString(),"–$",d.price_high.toLocaleString()]}):null]}):null]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx($,{variant:"outline",size:"sm",onClick:()=>r(`/mission-control/cma/${d.id}`),children:"Open"}),d.status==="shared"&&e.jsxs(e.Fragment,{children:[e.jsx($,{variant:"ghost",size:"sm",onClick:()=>{const f=`https://cma.relevelup.com/${d.share_token}`;navigator.clipboard.writeText(f),a({title:"Share link copied"})},children:e.jsx(kr,{className:"w-4 h-4"})}),e.jsxs($,{variant:"secondary",size:"sm",onClick:()=>l(d),children:[e.jsx(mn,{className:"w-4 h-4 mr-1"}),"Send"]})]}),e.jsx($,{variant:"ghost",size:"sm",onClick:async()=>{await fo("Delete this CMA?")&&n.mutate(d.id)},children:e.jsx(Wn,{className:"w-4 h-4"})})]})]})},d.id)})}):e.jsx(Ne,{children:e.jsx(Ie,{className:"py-12 text-center text-muted-foreground",children:"No CMAs yet. Start one above."})}),i&&e.jsx(pJt,{open:!!i,onOpenChange:d=>!d&&l(null),cma:i})]})})}function xqn(s){return s?/Closed|Sold/i.test(s)?"#16a34a":/Pending|Contingent|Under Contract/i.test(s)?"#f59e0b":/Active/i.test(s)?"#2563eb":"#64748b":"#64748b"}function DCt(s,t,n){const a=n*1.60934,i=[],l=a/(111.32*Math.cos(s*Math.PI/180)),o=a/110.574;for(let c=0;c<64;c++){const d=c/64*(2*Math.PI);i.push([t+l*Math.cos(d),s+o*Math.sin(d)])}return i.push(i[0]),{type:"Feature",geometry:{type:"Polygon",coordinates:[i]},properties:{}}}function yqn({subject:s,comps:t,radiusMiles:n,onMarkerClick:r}){const a=j.useRef(null),i=j.useRef(null),l=j.useRef([]),[o,c]=j.useState(null);j.useEffect(()=>{let u=!1;return(async()=>{const{data:h}=await q.from("settings").select("value").eq("key","mapbox_public_token").maybeSingle();!u&&(h!=null&&h.value)&&c(h.value)})(),()=>{u=!0}},[]);const d=j.useMemo(()=>{const u=Number(s==null?void 0:s.latitude),h=Number(s==null?void 0:s.longitude);return!Number.isFinite(u)||!Number.isFinite(h)?null:{lat:u,lng:h}},[s==null?void 0:s.latitude,s==null?void 0:s.longitude]);return j.useEffect(()=>{if(!o||!a.current||i.current||!d)return;ju.accessToken=o;const u=new ju.Map({container:a.current,style:"mapbox://styles/mapbox/light-v11",center:[d.lng,d.lat],zoom:12});return u.addControl(new ju.NavigationControl({showCompass:!1}),"top-right"),u.on("load",()=>{u.addSource("radius",{type:"geojson",data:DCt(d.lat,d.lng,n)}),u.addLayer({id:"radius-fill",type:"fill",source:"radius",paint:{"fill-color":"#2563eb","fill-opacity":.08}}),u.addLayer({id:"radius-line",type:"line",source:"radius",paint:{"line-color":"#2563eb","line-width":2,"line-dasharray":[2,2],"line-opacity":.5}})}),i.current=u,()=>{u.remove(),i.current=null}},[o,d]),j.useEffect(()=>{const u=i.current;if(!u||!d)return;const h=()=>{const m=u.getSource("radius");m&&m.setData(DCt(d.lat,d.lng,n))};u.isStyleLoaded()?h():u.once("load",h)},[n,d]),j.useEffect(()=>{const u=i.current;if(!u||!d)return;l.current.forEach(y=>y.remove()),l.current=[];const h=document.createElement("div");h.style.cssText=` width: 28px; height: 28px; border-radius: 50%; background: hsl(222 47% 11%); border: 3px solid white; box-shadow: 0 4px 12px rgba(0,0,0,0.3); display: flex; align-items: center; justify-content: center; color: white; font-size: 12px; font-weight: 700; `,h.textContent="★";const m=new ju.Marker({element:h}).setLngLat([d.lng,d.lat]).setPopup(new ju.Popup({offset:18}).setHTML(`Subject
${s.address??""}`)).addTo(u);l.current.push(m);const f=new ju.LngLatBounds;f.extend([d.lng,d.lat]),t.forEach((y,v)=>{const b=Number(y.latitude),w=Number(y.longitude);if(!Number.isFinite(b)||!Number.isFinite(w))return;const S=xqn(y.status),C=document.createElement("div");C.style.cssText="width:22px;height:22px;";const E=document.createElement("div");E.style.cssText=` width: 22px; height: 22px; border-radius: 50%; background: ${S}; border: 2px solid white; box-shadow: 0 2px 6px rgba(0,0,0,0.25); cursor: pointer; opacity: ${y.selected===!1?.4:1}; transition: transform 0.15s; transform-origin: center; `,E.onmouseenter=()=>{E.style.transform="scale(1.25)"},E.onmouseleave=()=>{E.style.transform="scale(1)"},r&&(E.onclick=()=>r(v)),C.appendChild(E);const I=y.soldPrice||y.price,P=new ju.Popup({offset:14}).setHTML(`
${y.address??""}
${y.status??""}`+(I?` · $${I.toLocaleString()}`:"")+"
"),R=new ju.Marker({element:C}).setLngLat([w,b]).setPopup(P).addTo(u);l.current.push(R),f.extend([w,b])});const x=n*1.60934/110.574;f.extend([d.lng,d.lat+x]),f.extend([d.lng,d.lat-x]);try{u.fitBounds(f,{padding:60,maxZoom:14,duration:600})}catch{}},[t,d,n,s.address,r]),d?e.jsxs("div",{className:"relative w-full h-[420px] rounded-xl overflow-hidden border shadow-sm",children:[e.jsx("div",{ref:a,className:"absolute inset-0"}),!o&&e.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-muted/40 text-sm text-muted-foreground",children:"Loading map…"}),e.jsxs("div",{className:"absolute bottom-3 left-3 bg-background/95 backdrop-blur rounded-lg shadow-md border px-3 py-2 text-xs space-y-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"inline-block w-3 h-3 rounded-full",style:{background:"hsl(222 47% 11%)"}}),"Subject"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"inline-block w-3 h-3 rounded-full",style:{background:"#2563eb"}}),"Active"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"inline-block w-3 h-3 rounded-full",style:{background:"#f59e0b"}}),"Pending"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"inline-block w-3 h-3 rounded-full",style:{background:"#16a34a"}}),"Closed"]})]})]}):e.jsx("div",{className:"w-full h-[420px] rounded-xl border bg-muted/30 flex items-center justify-center text-sm text-muted-foreground",children:"Subject property has no coordinates — map unavailable."})}let nw=null;function xJt(){if(nw)return nw;try{const s=document.createElement("canvas"),t=s.getContext("webgl2")||s.getContext("webgl");if(!t)return nw={canRunVirtualBg:!1,reason:"WebGL is not supported on this device"},nw;const n=t.getExtension("WEBGL_debug_renderer_info"),r=n?t.getParameter(n.UNMASKED_RENDERER_WEBGL):"Unknown",a=["swiftshader","llvmpipe","software","microsoft basic render"],i=(r||"").toLowerCase();if(a.some(c=>i.includes(c)))return nw={canRunVirtualBg:!1,reason:"Your device uses a software renderer which may cause lag",renderer:r},nw;const o=performance;return o.memory&&o.memory.jsHeapSizeLimit<256*1024*1024?(nw={canRunVirtualBg:!1,reason:"Limited device memory detected",renderer:r},nw):navigator.hardwareConcurrency&&navigator.hardwareConcurrency<2?(nw={canRunVirtualBg:!1,reason:"Single-core device detected — virtual backgrounds may cause lag",renderer:r},nw):(nw={canRunVirtualBg:!0,renderer:r},nw)}catch{return nw={canRunVirtualBg:!0},nw}}const vqn=[{type:"none",label:"Off"},{type:"blur",label:"Blur"}];function bqn({value:s,onChange:t,isLoading:n=!1,disabled:r=!1,className:a}){const i=j.useRef(null),[l,o]=j.useState(!1),[c,d]=j.useState(null),[u]=j.useState(()=>xJt()),h=!u.canRunVirtualBg,{data:m=[],refetch:f}=tt({queryKey:["video-backgrounds"],queryFn:async()=>{const{data:{user:w}}=await q.auth.getUser();if(!w)return[];const{data:S,error:C}=await q.from("video_backgrounds").select("*").eq("is_active",!0).order("sort_order",{ascending:!0});return C?(console.error("Failed to load backgrounds:",C),[]):(S||[]).map(E=>({...E,__ownerId:w.id}))}}),g=m.map(w=>({type:"image",label:w.name,imageUrl:w.image_url,thumbnail:w.thumbnail_url||w.image_url,id:w.id,deletable:!w.is_stock&&w.user_id===w.__ownerId})),x=[...vqn,...g],y=w=>w.type!==s.type?!1:w.type==="image"?w.imageUrl===s.imageUrl:!0,v=async w=>{if(!(!w.id||!w.imageUrl)&&window.confirm(`Delete the background "${w.label}"? This can't be undone.`)){d(w.id);try{const{error:S}=await q.from("video_backgrounds").delete().eq("id",w.id);if(S)throw S;const C="/video-backgrounds/",E=w.imageUrl.indexOf(C);if(E!==-1){const I=decodeURIComponent(w.imageUrl.slice(E+C.length).split("?")[0]);await q.storage.from("video-backgrounds").remove([I])}s.type==="image"&&s.imageUrl===w.imageUrl&&t({type:"none",mirror:s.mirror}),await f(),re.success("Background deleted")}catch(S){console.error("Delete background error:",S),re.error((S==null?void 0:S.message)||"Failed to delete background")}finally{d(null)}}},b=async w=>{var C;const S=(C=w.target.files)==null?void 0:C[0];if(S){if(!S.type.startsWith("image/")){re.error("Please select an image file");return}if(S.size>5*1024*1024){re.error("Image must be under 5MB");return}o(!0);try{const{data:{user:E}}=await q.auth.getUser();if(!E)throw new Error("Not authenticated");const I=S.name.split(".").pop()||"jpg",P=`${E.id}/${crypto.randomUUID()}.${I}`,{error:R}=await q.storage.from("video-backgrounds").upload(P,S,{contentType:S.type});if(R)throw R;const{data:D}=q.storage.from("video-backgrounds").getPublicUrl(P),O=D.publicUrl,{error:U}=await q.from("video_backgrounds").insert({name:S.name.replace(/\.[^.]+$/,""),image_url:O,thumbnail_url:O,category:"custom",is_stock:!1,user_id:E.id});if(U)throw U;await f(),t({type:"image",imageUrl:O,blurRadius:15}),re.success("Background uploaded!")}catch(E){console.error("Upload error:",E),re.error("Failed to upload background")}finally{o(!1),i.current&&(i.current.value="")}}};return e.jsxs("div",{className:Pt("flex flex-col gap-1",a),children:[h&&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(wl,{className:"h-3 w-3 flex-shrink-0"}),e.jsx("span",{children:u.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:"}),n&&e.jsxs("div",{className:"flex items-center gap-1 text-xs text-muted-foreground",children:[e.jsx(kt,{className:"h-3 w-3 animate-spin"}),e.jsx("span",{children:"Loading…"})]}),x.map((w,S)=>{const C=y(w);return e.jsxs("div",{className:"relative flex-shrink-0 group",children:[e.jsxs("button",{type:"button",disabled:r,onClick:()=>t({type:w.type,imageUrl:w.imageUrl,blurRadius:15,mirror:s.mirror}),className:Pt("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",C?"border-primary bg-primary/10":"border-transparent bg-muted/50",r&&"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:[w.type==="none"&&e.jsx(zz,{className:"h-4 w-4 text-muted-foreground"}),w.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"})}),w.type==="image"&&w.thumbnail&&e.jsx("img",{src:w.thumbnail,alt:w.label,className:"w-full h-full object-cover"})]}),e.jsx("span",{className:"text-[10px] text-muted-foreground truncate max-w-14",children:w.label})]}),w.deletable&&e.jsx("button",{type:"button","aria-label":`Delete background ${w.label}`,disabled:r||c===w.id,onClick:E=>{E.stopPropagation(),v(w)},className:Pt("absolute -top-1 -right-1 h-5 w-5 rounded-full bg-background border shadow-sm","flex items-center justify-center text-muted-foreground hover:text-destructive hover:border-destructive","opacity-100 sm:opacity-0 sm:group-hover:opacity-100 focus:opacity-100 transition-opacity"),children:c===w.id?e.jsx(kt,{className:"h-3 w-3 animate-spin"}):e.jsx(gr,{className:"h-3 w-3"})})]},`${w.type}-${w.imageUrl||S}`)}),e.jsxs("button",{type:"button",disabled:r||l,onClick:()=>{var w;return(w=i.current)==null?void 0:w.click()},className:Pt("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",(r||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(kt,{className:"h-4 w-4 animate-spin text-muted-foreground"}):e.jsx(dn,{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:b}),e.jsxs("button",{type:"button",disabled:r,onClick:()=>t({...s,mirror:!s.mirror}),className:Pt("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",r&&"opacity-50 cursor-not-allowed"),children:[e.jsx("div",{className:"w-12 h-8 rounded flex items-center justify-center",children:e.jsx(AJ,{className:"h-4 w-4 text-muted-foreground"})}),e.jsx("span",{className:"text-[10px] text-muted-foreground",children:"Mirror"})]})]})]})}var pW=typeof self<"u"?self:{};function yJt(s,t){e:{for(var n=["CLOSURE_FLAGS"],r=pW,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,r[n++]=t>>18|240,r[n++]=t>>12&63|128,r[n++]=t>>6&63|128,r[n++]=63&t|128;continue}a--}t=65533}r[n++]=t>>12|224,r[n++]=t>>6&63|128}r[n++]=63&t|128}}s=n===r.length?r:r.subarray(0,n)}return s}function bJt(s){pW.setTimeout(()=>{throw s},0)}var $Ye,Nqn=yJt(610401301,!1),OCt=yJt(748402147,!0);function zCt(){var s=pW.navigator;return s&&(s=s.userAgent)?s:""}const BCt=pW.navigator;function mDe(s){return mDe[" "](s),s}$Ye=BCt&&BCt.userAgentData||null,mDe[" "]=function(){};const _Jt={};let SQ=null;function kqn(s){const t=s.length;let n=3*t/4;n%3?n=Math.floor(n):"=.".indexOf(s[t-1])!=-1&&(n="=.".indexOf(s[t-2])!=-1?n-2:n-1);const r=new Uint8Array(n);let a=0;return function(i,l){function o(d){for(;c>4),h!=64&&(l(u<<4&240|h>>2),m!=64&&l(h<<6&192|m))}}(s,function(i){r[a++]=i}),a!==n?r.subarray(0,a):r}function wJt(){if(!SQ){SQ={};var s="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789".split(""),t=["+/=","+/","-_=","-_.","-_"];for(let n=0;n<5;n++){const r=s.concat(t[n].split(""));_Jt[n]=r;for(let a=0;a0)&&(zCt().indexOf("Trident")!=-1||zCt().indexOf("MSIE")!=-1))&&typeof btoa=="function";const $Ct=/[-_.]/g,Cqn={"-":"+",_:"/",".":"="};function Aqn(s){return Cqn[s]||""}function NJt(s){if(!jJt)return kqn(s);s=$Ct.test(s)?s.replace($Ct,Aqn):s,s=atob(s);const t=new Uint8Array(s.length);for(let n=0;n=t||(n[s]=r+1,SJt(s=Error(),"incident"),bJt(s))}}function qK(){return typeof BigInt=="function"}var VK=typeof Symbol=="function"&&typeof Symbol()=="symbol";function y3(s,t,n=!1){return typeof Symbol=="function"&&typeof Symbol()=="symbol"?n&&Symbol.for&&s?Symbol.for(s):s!=null?Symbol(s):Symbol():t}var Mqn=y3("jas",void 0,!0),UCt=y3(void 0,"0di"),cX=y3(void 0,"1oa"),S2=y3(void 0,Symbol()),Pqn=y3(void 0,"0ub"),Iqn=y3(void 0,"0ubs"),qYe=y3(void 0,"0ubsb"),Lqn=y3(void 0,"0actk"),yW=y3("m_m","Pa",!0),qCt=y3();const CJt={Ga:{value:0,configurable:!0,writable:!0,enumerable:!1}},AJt=Object.defineProperties,hl=VK?Mqn:"Ga";var l9;const VCt=[];function Oie(s,t){VK||hl in s||AJt(s,CJt),s[hl]|=t}function O0(s,t){VK||hl in s||AJt(s,CJt),s[hl]=t}function zie(s){return Oie(s,34),s}function xne(s){return Oie(s,8192),s}O0(VCt,7),l9=Object.freeze(VCt);var vW={};function F2(s,t){return t===void 0?s.h!==fB&&!!(2&(0|s.v[hl])):!!(2&t)&&s.h!==fB}const fB={};function Mit(s,t){if(s!=null){if(typeof s=="string")s=s?new H4(s,gW):mB();else if(s.constructor!==H4)if(Eit(s))s=s.length?new H4(new Uint8Array(s),gW):mB();else{if(!t)throw Error();s=void 0}}return s}let HCt=class{constructor(t,n,r){this.g=t,this.h=n,this.l=r}next(){const t=this.g.next();return t.done||(t.value=this.h.call(this.l,t.value)),t}[Symbol.iterator](){return this}};var Rqn=Object.freeze({});function EJt(s,t,n){const r=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"),GCt=fDe(s=>typeof s=="string"),Fqn=fDe(s=>typeof s=="boolean"),pDe=typeof pW.BigInt=="function"&&typeof pW.BigInt(0)=="bigint";function C2(s){var t=s;if(GCt(t)){if(!/^\s*(?:-?[1-9]\d*|0)?\s*$/.test(t))throw Error(String(t))}else if(Dqn(t)&&!Number.isSafeInteger(t))throw Error(String(t));return pDe?BigInt(s):s=Fqn(s)?s?"1":"0":GCt(s)?s.trim()||"0":String(s)}var VYe=fDe(s=>pDe?s>=zqn&&s<=$qn:s[0]==="-"?WCt(s,Oqn):WCt(s,Bqn));const Oqn=Number.MIN_SAFE_INTEGER.toString(),zqn=pDe?BigInt(Number.MIN_SAFE_INTEGER):void 0,Bqn=Number.MAX_SAFE_INTEGER.toString(),$qn=pDe?BigInt(Number.MAX_SAFE_INTEGER):void 0;function WCt(s,t){if(s.length>t.length)return!1;if(s.lengtha)return!1;if(r>>0;Ng=t,Fy=(s-t)/4294967296>>>0}function bW(s){if(s<0){KCt(-s);const[t,n]=Lit(Ng,Fy);Ng=t>>>0,Fy=n>>>0}else KCt(s)}function Pit(s){const t=qqn||(qqn=new DataView(new ArrayBuffer(8)));t.setFloat32(0,+s,!0),Fy=0,Ng=t.getUint32(0,!0)}function MJt(s,t){const n=4294967296*t+(s>>>0);return Number.isSafeInteger(n)?n:yne(s,t)}function Vqn(s,t){return C2(qK()?BigInt.asUintN(64,(BigInt(t>>>0)<>>0)):yne(s,t))}function PJt(s,t){return qK()?C2(BigInt.asIntN(64,(BigInt.asUintN(32,BigInt(t))<>>=0,(t>>>=0)<=2097151)var n=""+(4294967296*t+s);else qK()?n=""+(BigInt(t)<>>24|t<<8))+6710656*(t=t>>16&65535),n+=8147497*t,t*=2,s>=1e7&&(n+=s/1e7>>>0,s%=1e7),n>=1e7&&(t+=n/1e7>>>0,n%=1e7),n=t+YCt(n)+YCt(s));return n}function YCt(s){return s=String(s),"0000000".slice(s.length)+s}function Iit(s,t){if(2147483648&t)if(qK())s=""+(BigInt(0|t)<>>0));else{const[n,r]=Lit(s,t);s="-"+yne(n,r)}else s=yne(s,t);return s}function gDe(s){if(s.length<16)bW(Number(s));else if(qK())s=BigInt(s),Ng=Number(s&BigInt(4294967295))>>>0,Fy=Number(s>>BigInt(32)&BigInt(4294967295));else{const t=+(s[0]==="-");Fy=Ng=0;const n=s.length;for(let r=t,a=(n-t)%6+t;a<=n;r=a,a+=6){const i=Number(s.slice(r,a));Fy*=1e6,Ng=1e6*Ng+i,Ng>=4294967296&&(Fy+=Math.trunc(Ng/4294967296),Fy>>>=0,Ng>>>=0)}if(t){const[r,a]=Lit(Ng,Fy);Ng=r,Fy=a}}}function Lit(s,t){return t=~t,s?s=1+~s:t+=1,[s,t]}function uC(s){return Array.prototype.slice.call(s)}const Bie=typeof BigInt=="function"?BigInt.asIntN:void 0,Hqn=typeof BigInt=="function"?BigInt.asUintN:void 0,pB=Number.isSafeInteger,xDe=Number.isFinite,_W=Math.trunc,Gqn=C2(0);function CQ(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 _4(s){return s==null||typeof s=="number"?s:s==="NaN"||s==="Infinity"||s==="-Infinity"?Number(s):void 0}function vne(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 IJt(s){return s==null||typeof s=="boolean"?s:typeof s=="number"?!!s:void 0}const Wqn=/^-?([1-9][0-9]*|0)(\.[0-9]+)?$/;function $ie(s){switch(typeof s){case"bigint":return!0;case"number":return xDe(s);case"string":return Wqn.test(s);default:return!1}}function GK(s){if(s==null)return s;if(typeof s=="string"&&s)s=+s;else if(typeof s!="number")return;return xDe(s)?0|s:void 0}function LJt(s){if(s==null)return s;if(typeof s=="string"&&s)s=+s;else if(typeof s!="number")return;return xDe(s)?s>>>0:void 0}function RJt(s){const t=s.length;return(s[0]==="-"?t<20||t===20&&s<="-9223372036854775808":t<19||t===19&&s<="9223372036854775807")?s:(gDe(s),Iit(Ng,Fy))}function Rit(s){if(s=_W(s),!pB(s)){bW(s);var t=Ng,n=Fy;(s=2147483648&n)&&(n=~n>>>0,(t=1+~t>>>0)==0&&(n=n+1>>>0)),s=typeof(t=MJt(t,n))=="number"?s?-t:t:s?"-"+t:t}return s}function DJt(s){var t=_W(Number(s));return pB(t)?String(t):((t=s.indexOf("."))!==-1&&(s=s.substring(0,t)),RJt(s))}function FJt(s){var t=_W(Number(s));return pB(t)?C2(t):((t=s.indexOf("."))!==-1&&(s=s.substring(0,t)),qK()?C2(Bie(64,BigInt(s))):C2(RJt(s)))}function OJt(s){return pB(s)?s=C2(Rit(s)):(s=_W(s),pB(s)?s=String(s):(bW(s),s=Iit(Ng,Fy)),s=C2(s)),s}function nPe(s){const t=typeof s;return s==null?s:t==="bigint"?C2(Bie(64,s)):$ie(s)?t==="string"?FJt(s):OJt(s):void 0}function zJt(s){if(typeof s!="string")throw Error();return s}function Uie(s){if(s!=null&&typeof s!="string")throw Error();return s}function kb(s){return s==null||typeof s=="string"?s:void 0}function Dit(s,t,n,r){return s!=null&&s[yW]===vW?s:Array.isArray(s)?((r=(n=0|s[hl])|32&r|2&r)!==n&&O0(s,r),new t(s)):(n?2&r?((s=t[UCt])||(zie((s=new t).v),s=t[UCt]=s),t=s):t=new t:t=void 0,t)}function Kqn(s,t,n){if(t)e:{if(!$ie(t=s))throw UYe("int64");switch(typeof t){case"string":t=FJt(t);break e;case"bigint":t=C2(Bie(64,t));break e;default:t=OJt(t)}}else t=nPe(s);return(s=t)==null?n?Gqn:void 0:s}const Yqn={};let Zqn=function(){try{return mDe(new class extends Map{constructor(){super()}}),!1}catch{return!0}}(),r$e=class{constructor(){this.g=new Map}get(t){return this.g.get(t)}set(t,n){return this.g.set(t,n),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,n){return this.g.forEach(t,n)}[Symbol.iterator](){return this.entries()}};const Xqn=Zqn?(Object.setPrototypeOf(r$e.prototype,Map.prototype),Object.defineProperties(r$e.prototype,{size:{value:0,configurable:!0,enumerable:!0,writable:!0}}),r$e):class extends Map{constructor(){super()}};function ZCt(s){return s}function a$e(s){if(2&s.J)throw Error("Cannot mutate an immutable Map")}var bT=class extends Xqn{constructor(s,t,n=ZCt,r=ZCt){super(),this.J=0|s[hl],this.K=t,this.S=n,this.fa=this.K?Qqn:r;for(let a=0;a{s.call(t,a.get(r),r,a)}):super.forEach(s,t)}set(s,t){return a$e(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 n=this.K;return n?((n=this.fa(t,!1,!0,n,this.ra,this.J))!==t&&super.set(s,n),n):t}}[Symbol.iterator](){return this.entries()}};function Qqn(s,t,n,r,a,i){return s=Dit(s,r,n,i),a&&(s=Oit(s)),s}function Jqn(s){return[s,this.get(s)]}let eVn;function XCt(){return eVn||(eVn=new bT(zie([]),void 0,void 0,void 0,Yqn))}function yDe(s){return S2?s[S2]:void 0}function rPe(s,t){for(const n in s)!isNaN(n)&&t(s,+n,s[n])}bT.prototype.toJSON=void 0;var HYe=class{};const tVn={Ka:!0};function sVn(s,t){t<100||xW(Iqn,1)}function vDe(s,t,n,r){const a=r!==void 0;r=!!r;var i,l=S2;!a&&VK&&l&&(i=s[l])&&rPe(i,sVn),l=[];var o=s.length;let c;i=4294967295;let d=!1;const u=!!(64&t),h=u?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,!u||128&t||a||(d=!0,i=i-h+h)),t=void 0;for(var m=0;m=i){const g=m-h;(t??(t={}))[g]=f}else l[m]=f}if(c)for(let f in c){if((o=c[f])==null||(o=n(o,r))==null)continue;let g;m=+f,u&&!Number.isNaN(m)&&(g=m+h){g[y]=uC(v)}),g.da=f.da,g}(s)),l}function nVn(s){return s[0]=bne(s[0]),s[1]=bne(s[1]),s}function bne(s){switch(typeof s){case"number":return Number.isFinite(s)?s:""+s;case"bigint":return VYe(s)?Number(s):""+s;case"boolean":return s?1:0;case"object":if(Array.isArray(s)){var t=0|s[hl];return s.length===0&&1&t?void 0:vDe(s,t,bne)}if(s!=null&&s[yW]===vW)return BJt(s);if(s instanceof H4){if((t=s.g)==null)s="";else if(typeof t=="string")s=t;else{if(jJt){for(var n="",r=0,a=t.length-10240;r>2];i=n[(3&i)<<4|l>>4],l=n[(15&l)<<2|o>>6],o=n[63&o],r[u++]=c+i+l+o}switch(c=0,o=a,t.length-d){case 2:o=n[(15&(c=t[d+1]))<<2]||a;case 1:t=t[d],r[u]=n[t>>2]+n[(3&t)<<4|c>>4]+o+a}t=r.join("")}s=s.g=t}return s}return s instanceof bT?s=s.size!==0?s.V(nVn):void 0:void 0}return s}let rVn,aVn;function BJt(s){return vDe(s=s.v,0|s[hl],bne)}function S7(s,t){return $Jt(s,t[0],t[1])}function $Jt(s,t,n,r=0){if(s==null){var a=32;n?(s=[n],a|=128):s=[],t&&(a=-16760833&a|(1023&t)<<14)}else{if(!Array.isArray(s))throw Error("narr");if(a=0|s[hl],OCt&&1&a)throw Error("rfarr");if(2048&a&&!(2&a)&&function(){if(OCt)throw Error("carr");xW(Lqn,5)}(),256&a)throw Error("farr");if(64&a)return(a|r)!==a&&O0(s,a|r),s;if(n&&(a|=128,n!==s[0]))throw Error("mid");e:{a|=64;var i=(n=s).length;if(i){var l=i-1;const c=n[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 O0(s,64|a|r),s}function iVn(s,t){if(typeof s!="object")return s;if(Array.isArray(s)){var n=0|s[hl];return s.length===0&&1&n?void 0:QCt(s,n,t)}if(s!=null&&s[yW]===vW)return JCt(s);if(s instanceof bT){if(2&(t=s.J))return s;if(!s.size)return;if(n=zie(s.V()),s.K)for(s=0;s=i)if(l=s[i],l!=null&&typeof l=="object"&&l.constructor===Object)n=l[t],o=!0;else{if(a!==i)return;n=l}else n=s[a];if(r&&n!=null){if((r=r(n))==null)return r;if(!Object.is(r,n))return o?l[t]=r:s[a]=r,r}return n}}function sf(s,t,n,r){YK(s),I0(s=s.v,0|s[hl],t,n,r)}function I0(s,t,n,r,a){const i=n+(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[n]=r,t}return i<=l?(s[i]=r,t):(r!==void 0&&(n>=(l=(t??(t=0|s[hl]))>>14&1023||536870912)?r!=null&&(s[l+(a?0:-1)]={[n]:r}):s[i]=r),t)}function N8(){return Rqn===void 0?2:4}function k8(s,t,n,r,a){let i=s.v,l=0|i[hl];r=F2(s,l)?1:r,a=!!a||r===3,r===2&&KK(s)&&(i=s.v,l=0|i[hl]);let o=(s=Bit(i,t))===l9?7:0|s[hl],c=$it(o,l);var d=!(4&c);if(d){4&c&&(s=uC(s),o=0,c=A7(c,l),l=I0(i,l,t,s));let u=0,h=0;for(;u{const o=Dit(l,n,!1,t);return i=o!==l&&o!=null,o}))!=null)return i&&!F2(r)&&c9(s,t),r}function Vh(s,t,n,r){let a=s.v,i=0|a[hl];if((t=WJt(a,i,t,n,r))==null)return t;if(i=0|a[hl],!F2(s,i)){const l=Oit(t);l!==t&&(KK(s)&&(a=s.v,i=0|a[hl]),i=I0(a,i,n,t=l,r),c9(a,i))}return t}function KJt(s,t,n,r,a,i,l,o){var c=F2(s,n);i=c?1:i,l=!!l||i===3,c=o&&!c,(i===2||c)&&KK(s)&&(n=0|(t=s.v)[hl]);var d=(s=Bit(t,a))===l9?7:0|s[hl],u=$it(d,n);if(o=!(4&u)){var h=s,m=n;const f=!!(2&u);f&&(m|=2);let g=!f,x=!0,y=0,v=0;for(;y32)for(a|=(127&n)>>4,i=3;i<32&&128&n;i+=7)n=l[o++],a|=(127&n)<>>0,a>>>0);throw Error()}function Kit(s){let t=0,n=s.g;const r=n+10,a=s.h;for(;n>>0}function iPe(s){var t=s.h;const n=s.g;var r=t[n],a=t[n+1];const i=t[n+2];return t=t[n+3],E7(s,s.g+4),s=2*((a=(r<<0|a<<8|i<<16|t<<24)>>>0)>>31)+1,r=a>>>23&255,a&=8388607,r==255?a?NaN:s*(1/0):r==0?1401298464324817e-60*s*a:s*Math.pow(2,r-150)*(a+8388608)}function oVn(s){return BL(s)}function E7(s,t){if(s.g=t,t>s.l)throw Error()}function ZJt(s,t){if(t<0)throw Error();const n=s.g;if((t=n+t)>s.l)throw Error();return s.g=t,n}function XJt(s,t){if(t==0)return mB();var n=ZJt(s,t);return s.Y&&s.j?n=s.h.subarray(n,n+t):(s=s.h,n=n===(t=n+t)?new Uint8Array(0):Uqn?s.slice(n,t):new Uint8Array(s.subarray(n,t))),n.length==0?mB():new H4(n,gW)}var e5t=[];function QJt(s,t,n,r){if(oPe.length){const a=oPe.pop();return a.o(r),a.g.init(s,t,n,r),a}return new lVn(s,t,n,r)}function JJt(s){s.g.clear(),s.l=-1,s.h=-1,oPe.length<100&&oPe.push(s)}function ees(s){var t=s.g;if(t.g==t.l)return!1;s.m=s.g.g;var n=t3(s.g);if(t=n>>>3,!((n&=7)>=0&&n<=5)||t<1)throw Error();return s.l=t,s.h=n,!0}function T3e(s){switch(s.h){case 0:s.h!=0?T3e(s):Kit(s.g);break;case 1:E7(s=s.g,s.g+8);break;case 2:if(s.h!=2)T3e(s);else{var t=t3(s.g);E7(s=s.g,s.g+t)}break;case 5:E7(s=s.g,s.g+4);break;case 3:for(t=s.l;;){if(!ees(s))throw Error();if(s.h==4){if(s.l!=t)throw Error();break}T3e(s)}break;default:throw Error()}}function qie(s,t,n){const r=s.g.l;var a=t3(s.g);let i=(a=s.g.g+a)-r;if(i<=0&&(s.g.l=a,n(t,s,void 0,void 0,void 0),i=a-s.g.g),i)throw Error();return s.g.g=a,s.g.l=r,t}function Yit(s){var t=t3(s.g),n=ZJt(s=s.g,t);if(s=s.h,_qn){var r,a=s;(r=n$e)||(r=n$e=new TextDecoder("utf-8",{fatal:!0})),t=n+t,a=n===0&&t===a.length?a:a.subarray(n,t);try{var i=r.decode(a)}catch(o){if(yue===void 0){try{r.decode(new Uint8Array([128]))}catch{}try{r.decode(new Uint8Array([97])),yue=!0}catch{yue=!1}}throw!yue&&(n$e=void 0),o}}else{t=(i=n)+t,n=[];let o,c=null;for(;i=t?NR():(o=s[i++],l<194||(192&o)!=128?(i--,NR()):n.push((31&l)<<6|63&o)):l<240?i>=t-1?NR():(o=s[i++],(192&o)!=128||l===224&&o<160||l===237&&o>=160||(192&(r=s[i++]))!=128?(i--,NR()):n.push((15&l)<<12|(63&o)<<6|63&r)):l<=244?i>=t-2?NR():(o=s[i++],(192&o)!=128||o-144+(l<<28)>>30||(192&(r=s[i++]))!=128||(192&(a=s[i++]))!=128?(i--,NR()):(l=(7&l)<<18|(63&o)<<12|(63&r)<<6|63&a,l-=65536,n.push(55296+(l>>10&1023),56320+(1023&l)))):NR(),n.length>=8192&&(c=FCt(c,n),n.length=0)}i=FCt(c,n)}return i}function tes(s){const t=t3(s.g);return XJt(s.g,t)}function _De(s,t,n){var r=t3(s.g);for(r=s.g.g+r;s.g.g>>0,this.g=t>>>0}};let cVn;function s5t(s){return s?/^-?\d+$/.test(s)?(gDe(s),new WYe(Ng,Fy)):null:dVn||(dVn=new WYe(0,0))}var WYe=class{constructor(s,t){this.h=s>>>0,this.g=t>>>0}};let dVn;function DV(s,t,n){for(;n>0||t>127;)s.g.push(127&t|128),t=(t>>>7|n<<25)>>>0,n>>>=7;s.g.push(t)}function XK(s,t){for(;t>127;)s.g.push(127&t|128),t>>>=7;s.g.push(t)}function wDe(s,t){if(t>=0)XK(s,t);else{for(let n=0;n<9;n++)s.g.push(127&t|128),t>>=7;s.g.push(1)}}function Zit(s){var t=Ng;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 wW(s,t){t.length!==0&&(s.l.push(t),s.h+=t.length)}function Pk(s,t,n){XK(s.g,8*t+n)}function Xit(s,t){return Pk(s,t,2),t=s.g.end(),wW(s,t),t.push(s.h),t}function Qit(s,t){var n=t.pop();for(n=s.h+s.g.length()-n;n>127;)t.push(127&n|128),n>>>=7,s.h++;t.push(n),s.h++}function jDe(s,t,n){Pk(s,t,2),XK(s.g,n.length),wW(s,s.g.end()),wW(s,n)}function lPe(s,t,n,r){n!=null&&(t=Xit(s,t),r(n,s),Qit(s,t))}function v3(){const s=class{constructor(){throw Error()}};return Object.setPrototypeOf(s,s.prototype),s}var Jit=v3(),ses=v3(),eot=v3(),tot=v3(),sot=v3(),nes=v3(),uVn=v3(),NDe=v3(),res=v3(),aes=v3();function b3(s,t,n){var r=s.v;S2&&S2 in r&&(r=r[S2])&&delete r[t.g],t.h?t.j(s,t.h,t.g,n,t.l):t.j(s,t.g,n,t.l)}var ml=class{constructor(s,t){this.v=$Jt(s,t,void 0,2048)}toJSON(){return BJt(this)}j(){var a;var s=GVn,t=this.v,n=s.g,r=S2;if(VK&&r&&((a=t[r])==null?void 0:a[n])!=null&&xW(Pqn,3),t=s.g,qCt&&S2&&qCt===void 0&&(r=(n=this.v)[S2])&&(r=r.da))try{r(n,t,tVn)}catch(i){bJt(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[hl];return zit(this,s,t)?Fit(this,s,!0):new this.constructor(WK(s,t,!1))}};ml.prototype[yW]=vW,ml.prototype.toString=function(){return this.v.toString()};var QK=class{constructor(s,t,n){this.g=s,this.h=t,s=Jit,this.l=!!s&&n===s||!1}};function kDe(s,t){return new QK(s,t,Jit)}function ies(s,t,n,r,a){lPe(s,n,des(t,r),a)}const hVn=kDe(function(s,t,n,r,a){return s.h===2&&(qie(s,Vit(t,r,n),a),!0)},ies),mVn=kDe(function(s,t,n,r,a){return s.h===2&&(qie(s,Vit(t,r,n),a),!0)},ies);var SDe=Symbol(),CDe=Symbol(),KYe=Symbol(),n5t=Symbol(),r5t=Symbol();let oes,les;function d9(s,t,n,r){var a=r[s];if(a)return a;(a={}).qa=r,a.T=function(h){switch(typeof h){case"boolean":return rVn||(rVn=[0,void 0,!0]);case"number":return h>0?void 0:h===0?aVn||(aVn=[0,void 0]):[-h,void 0];case"string":return[0,h];case"object":return h}}(r[0]);var i=r[1];let l=1;i&&i.constructor===Object&&(a.ba=i,typeof(i=r[++l])=="function"&&(a.ma=!0,oes??(oes=i),les??(les=r[l+1]),i=r[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,r):a}function rot(s,t,n,r,a){const i=n.g;let l,o;s[t]=(c,d,u)=>i(c,d,u,o||(o=d9(CDe,not,rot,r).T),l||(l=aot(r)),a)}function aot(s){let t=s[KYe];if(t!=null)return t;const n=d9(CDe,not,rot,s);return t=n.ma?(r,a)=>oes(r,a,n):(r,a)=>{for(;ees(a)&&a.h!=4;){var i=a.l,l=n[i];if(l==null){var o=n.ba;o&&(o=o[i])&&(o=pVn(o))!=null&&(l=n[i]=o)}if(l==null||!l(a,r,i)){if(l=(o=a).m,T3e(o),o.ha)var c=void 0;else c=o.g.g-l,o.g.g=l,c=XJt(o.g,c);l=void 0,o=r,c&&((l=o[S2]??(o[S2]=new HYe))[i]??(l[i]=[])).push(c)}}return(r=yDe(r))&&(r.da=n.qa[r5t]),!0},s[KYe]=t,s[r5t]=fVn.bind(s),t}function fVn(s,t,n,r){var a=this[CDe];const i=this[KYe],l=S7(void 0,a.T),o=yDe(s);if(o){var c=!1,d=a.ba;if(d){if(a=(u,h,m)=>{if(m.length!==0)if(d[h])for(const f of m){u=QJt(f);try{c=!0,i(l,u)}finally{JJt(u)}}else r==null||r(s,h,m)},t==null)rPe(o,a);else if(o!=null){const u=o[t];u&&a(o,t,u)}if(c){let u=0|s[hl];if(2&u&&2048&u&&!(n!=null&&n.Ka))throw Error();const h=HK(u),m=(f,g)=>{if(_T(s,f,h)!=null){if((n==null?void 0:n.Qa)===1)return;throw Error()}g!=null&&(u=I0(s,u,f,g,h)),delete o[f]};t==null?EJt(l,0|l[hl],(f,g)=>{m(f,g)}):m(t,_T(l,t,h))}}}}function pVn(s){const t=(s=ces(s))[0].g;if(s=s[1]){const n=aot(s),r=d9(CDe,not,rot,s).T;return(a,i,l)=>t(a,i,l,r,n)}return t}function ADe(s,t,n){s[t]=n.h}function EDe(s,t,n,r){let a,i;const l=n.h;s[t]=(o,c,d)=>l(o,c,d,i||(i=d9(SDe,ADe,EDe,r).T),a||(a=ues(r)))}function ues(s){let t=s[n5t];if(!t){const n=d9(SDe,ADe,EDe,s);t=(r,a)=>hes(r,a,n),s[n5t]=t}return t}function hes(s,t,n){EJt(s,0|s[hl],(r,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=ces(c))[0].h;if(c=c[1]){const u=ues(c),h=d9(SDe,ADe,EDe,c).T;c=l.ma?les(h,u):(m,f,g)=>d(m,f,g,h,u)}else c=d;return l[o]=c}}(n,r);i?i(t,a,r):r<500||xW(qYe,3)}}),(s=yDe(s))&&rPe(s,(r,a,i)=>{for(wW(t,t.g.end()),r=0;r{lPe(s,n,S7([l,i],r),a)});else if(Array.isArray(t)){for(let i=0;i>BigInt(32))),DV(s.g,n.h,n.g);break;default:n=s5t(t),DV(s.g,n.h,n.g)}}function pes(s,t,n){(t=GK(t))!=null&&t!=null&&(Pk(s,n,0),wDe(s.g,t))}function ges(s,t,n){(t=IJt(t))!=null&&(Pk(s,n,0),s.g.g.push(t?1:0))}function xes(s,t,n){(t=kb(t))!=null&&jDe(s,n,vJt(t))}function yes(s,t,n,r,a){lPe(s,n,des(t,r),a)}function ves(s,t,n){(t=t==null||typeof t=="string"||t instanceof H4?t:void 0)!=null&&jDe(s,n,Git(t,!0).buffer)}function bes(s,t,n){(t=LJt(t))!=null&&t!=null&&(Pk(s,n,0),XK(s.g,t))}function _es(s,t,n){return(s.h===5||s.h===2)&&(t=ZK(t,0|t[hl],n),s.h==2?_De(s,iPe,t):t.push(iPe(s.g)),!0)}var Uy=R1(function(s,t,n){return s.h===5&&(D1(t,n,iPe(s.g)),!0)},mes,NDe),yVn=eY(_es,function(s,t,n){if((t=JK(_4,t))!=null)for(let l=0;l=0?r=String(a):((a=r.indexOf("."))!==-1&&(r=r.substring(0,a)),(a=r[0]!=="-"&&((a=r.length)<20||a===20&&r<="18446744073709551615"))||(gDe(r),r=yne(Ng,Fy))),r;if(a==="number")return(r=_W(r))>=0&&pB(r)||(bW(r),r=MJt(Ng,Fy)),r}}(t),t!=null&&(typeof t=="string"&&t5t(t),t!=null))switch(Pk(s,n,0),typeof t){case"number":s=s.g,bW(t),DV(s,Ng,Fy);break;case"bigint":n=BigInt.asUintN(64,t),n=new GYe(Number(n&BigInt(4294967295)),Number(n>>BigInt(32))),DV(s.g,n.h,n.g);break;default:n=t5t(t),DV(s.g,n.h,n.g)}},uVn),A0=R1(function(s,t,n){return s.h===0&&(D1(t,n,BL(s.g)),!0)},pes,tot),Vie=eY(function(s,t,n){return(s.h===0||s.h===2)&&(t=ZK(t,0|t[hl],n),s.h==2?_De(s,BL,t):t.push(BL(s.g)),!0)},function(s,t,n){if((t=JK(GK,t))!=null&&t.length){n=Xit(s,n);for(let r=0;r{{const i={ea:!0};r&&Object.assign(i,r),n=QJt(n,void 0,void 0,i);try{const l=new s,o=l.v;aot(t)(o,n);var a=l}finally{JJt(n)}}return a}}function TDe(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}}}};hes(this.v,t,d9(SDe,ADe,EDe,s)),wW(t,t.g.end());const n=new Uint8Array(t.h),r=t.l,a=r.length;let i=0;for(let l=0;la;n=o5t.createPolicy("goog#html",{createHTML:r,createScript:r,createScriptURL:r})}catch{}return n}()),s=(t=l$e)?t.createScriptURL(s):s,new class{constructor(n){this.g=n}toString(){return this.g+""}}(s)}function vue(s,...t){if(t.length===0)return l5t(s[0]);let n=s[0];for(let r=0;r({index:YN(r,1)??0??-1,score:Jx(r,2)??0,categoryName:kb(Pg(r,3))??""??"",displayName:kb(Pg(r,4))??""??""})),headIndex:t,headName:n}}function ZVn(s){const t={classifications:wT(s,MVn,1).map(n=>{var r;return fot(((r=Vh(n,Tes,4))==null?void 0:r.g())??[],YN(n,2)??0,kb(Pg(n,3))??"")})};return function(n){return n==null?n:typeof n=="bigint"?(VYe(n)?n=Number(n):(n=Bie(64,n),n=VYe(n)?Number(n):String(n)),n):$ie(n)?typeof n=="number"?Rit(n):DJt(n):void 0}(Pg(s,2,void 0,void 0,nPe))!=null&&(t.timestampMs=nts(Pg(s,2,void 0,void 0,nPe)??UJt)),t}function rts(s){var l,o;var t=k8(s,3,_4,N8()),n=k8(s,2,GK,N8()),r=k8(s,1,kb,N8()),a=k8(s,9,kb,N8());const i={categories:[],keypoints:[]};for(let c=0;ct>127?t-256:t)}function b5t(s,t){if(s.length!==t.length)throw Error(`Cannot compute cosine similarity between embeddings of different sizes (${s.length} vs. ${t.length}).`);let n=0,r=0,a=0;for(let i=0;i=1&&Number(s[1])>=17))}async function _5t(s){if(typeof importScripts!="function"){const t=document.createElement("script");return t.src=s.toString(),t.crossOrigin="anonymous",new Promise((n,r)=>{t.addEventListener("load",()=>{n()},!1),t.addEventListener("error",a=>{r(a)},!1),document.body.appendChild(t)})}try{importScripts(s.toString())}catch(t){if(!(t instanceof TypeError))throw t;{const n=self.import;n?await n(s.toString()):await import(s.toString())}}}function ots(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 yl(s,t,n){s.m||console.error("No wasm multistream support detected: ensure dependency inclusion of :gl_graph_runner_internal_multi_input target"),n(t=s.i.stringToNewUTF8(t)),s.i._free(t)}function w5t(s,t,n){if(!s.i.canvas)throw Error("No OpenGL canvas configured.");if(n?s.i._bindTextureToStream(n):s.i._bindTextureToCanvas(),!(n=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&&n.pixelStorei(n.UNPACK_FLIP_Y_WEBGL,!0),n.texImage2D(n.TEXTURE_2D,0,n.RGBA,n.RGBA,n.UNSIGNED_BYTE,t),s.i.gpuOriginForWebTexturesIsBottomLeft&&n.pixelStorei(n.UNPACK_FLIP_Y_WEBGL,!1);const[r,a]=ots(t);return!s.l||r===s.i.canvas.width&&a===s.i.canvas.height||(s.i.canvas.width=r,s.i.canvas.height=a),[r,a]}function j5t(s,t,n){s.m||console.error("No wasm multistream support detected: ensure dependency inclusion of :gl_graph_runner_internal_multi_input target");const r=new Uint32Array(t.length);for(let a=0;a>2),n(t);for(const a of r)s.i._free(a);s.i._free(t)}function a5(s,t,n){s.i.simpleListeners=s.i.simpleListeners||{},s.i.simpleListeners[t]=n}function EM(s,t,n){let r=[];s.i.simpleListeners=s.i.simpleListeners||{},s.i.simpleListeners[t]=(a,i,l)=>{i?(n(r,l),r=[]):r.push(a)}}kU.forVisionTasks=function(s,t=!1){return _ue("vision",s??vue``,t)},kU.forTextTasks=function(s,t=!1){return _ue("text",s??vue``,t)},kU.forGenAiTasks=function(s,t=!1){return _ue("genai",s??vue``,t)},kU.forAudioTasks=function(s,t=!1){return _ue("audio",s??vue``,t)},kU.isSimdSupported=function(s=!1){return ats(s)};async function QVn(s,t,n,r){return s=await(async(a,i,l,o,c)=>{if(i&&await _5t(i),!self.ModuleFactory||l&&(await _5t(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,n.wasmLoaderPath,n.assetLoaderPath,t,{locateFile:a=>a.endsWith(".wasm")?n.wasmBinaryPath.toString():n.assetBinaryPath&&a.endsWith(".data")?n.assetBinaryPath.toString():a}),await s.o(r),s}function u$e(s,t){const n=Vh(s.baseOptions,cPe,1)||new cPe;typeof t=="string"?(sf(n,2,Uie(t)),sf(n,1)):t instanceof Uint8Array&&(sf(n,1,Mit(t,!1)),sf(n,2)),Jl(s.baseOptions,0,1,n)}function N5t(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(n=>n.message).join(", "))}finally{s.H=[]}}function qo(s,t){s.C=Math.max(s.C,t)}function LDe(s,t){s.B=new Qw,O2(s.B,2,"PassThroughCalculator"),tg(s.B,"free_memory"),gh(s.B,"free_memory_unused_out"),Hg(t,"free_memory"),Ik(t,s.B)}function jW(s,t){tg(s.B,t),gh(s.B,t+"_unused_out")}function RDe(s){s.g.addBoolToStream(!0,"free_memory",s.C)}var JYe=class{constructor(s){this.g=s,this.H=[],this.C=0,this.g.setAutoRenderToScreen(!1)}l(s,t=!0){var n,r,a,i,l,o;if(t){const c=s.baseOptions||{};if((n=s.baseOptions)!=null&&n.modelAssetBuffer&&((r=s.baseOptions)!=null&&r.modelAssetPath))throw Error("Cannot set both baseOptions.modelAssetPath and baseOptions.modelAssetBuffer");if(!((a=Vh(this.baseOptions,cPe,1))!=null&&a.g()||(i=Vh(this.baseOptions,cPe,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,u){let h=Vh(d.baseOptions,p5t,3);if(!h){var m=h=new p5t,f=new c5t;tte(m,4,M3e,f)}"delegate"in u&&(u.delegate==="GPU"?(u=h,m=new NVn,tte(u,2,M3e,m)):(u=h,m=new c5t,tte(u,4,M3e,m))),Jl(d.baseOptions,0,3,h)}(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),u$e(this,"/model.dat"),this.m(),this.L()});if(c.modelAssetBuffer instanceof Uint8Array)u$e(this,c.modelAssetBuffer);else if(c.modelAssetBuffer)return async function(d){const u=[];for(var h=0;;){const{done:m,value:f}=await d.read();if(m)break;u.push(f),h+=f.length}if(u.length===0)return new Uint8Array(0);if(u.length===1)return u[0];d=new Uint8Array(h),h=0;for(const m of u)d.set(m,h),h+=m.length;return d}(c.modelAssetBuffer).then(d=>{u$e(this,d),this.m(),this.L()})}return this.m(),this.L(),Promise.resolve()}L(){}ca(){let s;if(this.g.ca(t=>{s=kVn(t)}),!s)throw Error("Failed to retrieve CalculatorGraphConfig");return s}setGraph(s,t){this.g.attachErrorListener((n,r)=>{this.H.push(Error(r))}),this.g.Ja(),this.g.setGraph(s,t),this.B=void 0,N5t(this)}finishProcessing(){this.g.finishProcessing(),N5t(this)}close(){this.B=void 0,this.g.closeGraph()}};function gL(s,t){if(!s)throw Error(`Unable to obtain required WebGL resource: ${t}`);return s}JYe.prototype.close=JYe.prototype.close;class JVn{constructor(t,n,r,a){this.g=t,this.h=n,this.m=r,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 k5t(s,t,n){const r=s.g;if(n=gL(r.createShader(n),"Failed to create WebGL shader"),r.shaderSource(n,t),r.compileShader(n),!r.getShaderParameter(n,r.COMPILE_STATUS))throw Error(`Could not compile WebGL shader: ${r.getShaderInfoLog(n)}`);return r.attachShader(s.h,n),n}function S5t(s,t){const n=s.g,r=gL(n.createVertexArray(),"Failed to create vertex array");n.bindVertexArray(r);const a=gL(n.createBuffer(),"Failed to create buffer");n.bindBuffer(n.ARRAY_BUFFER,a),n.enableVertexAttribArray(s.O),n.vertexAttribPointer(s.O,2,n.FLOAT,!1,0,0),n.bufferData(n.ARRAY_BUFFER,new Float32Array([-1,-1,-1,1,1,1,1,-1]),n.STATIC_DRAW);const i=gL(n.createBuffer(),"Failed to create buffer");return n.bindBuffer(n.ARRAY_BUFFER,i),n.enableVertexAttribArray(s.L),n.vertexAttribPointer(s.L,2,n.FLOAT,!1,0,0),n.bufferData(n.ARRAY_BUFFER,new Float32Array(t?[0,1,0,0,1,0,1,1]:[0,0,0,1,1,1,1,0]),n.STATIC_DRAW),n.bindBuffer(n.ARRAY_BUFFER,null),n.bindVertexArray(null),new JVn(n,r,a,i)}function pot(s,t){if(s.g){if(t!==s.g)throw Error("Cannot change GL context once initialized")}else s.g=t}function eHn(s,t,n,r){return pot(s,t),s.h||(s.m(),s.D()),n?(s.u||(s.u=S5t(s,!0)),n=s.u):(s.A||(s.A=S5t(s,!1)),n=s.A),t.useProgram(s.h),n.bind(),s.l(),s=r(),n.g.bindVertexArray(null),s}function lts(s,t,n){return pot(s,t),s=gL(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,n??t.LINEAR),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,n??t.LINEAR),t.bindTexture(t.TEXTURE_2D,null),s}function cts(s,t,n){pot(s,t),s.B||(s.B=gL(t.createFramebuffer(),"Failed to create framebuffe.")),t.bindFramebuffer(t.FRAMEBUFFER,s.B),t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,n,0)}function tHn(s){var t;(t=s.g)==null||t.bindFramebuffer(s.g.FRAMEBUFFER,null)}var dts=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=gL(s.createProgram(),"Failed to create WebGL program"),this.X=k5t(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=k5t(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 fE(s,t){switch(t){case 0:return s.g.find(n=>n instanceof Uint8Array);case 1:return s.g.find(n=>n instanceof Float32Array);case 2:return s.g.find(n=>typeof WebGLTexture<"u"&&n instanceof WebGLTexture);default:throw Error(`Type is not supported: ${t}`)}}function eZe(s){var t=fE(s,1);if(!t){if(t=fE(s,0))t=new Float32Array(t).map(r=>r/255);else{t=new Float32Array(s.width*s.height);const r=NW(s);var n=got(s);if(cts(n,r,uts(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){n=new Float32Array(s.width*s.height*4),r.readPixels(0,0,s.width,s.height,r.RGBA,r.FLOAT,n);for(let a=0,i=0;aMath.round(255*n))),s.g.push(t)),t;var s,t}ia(){return eZe(this)}N(){return uts(this)}clone(){const s=[];for(const t of this.g){let n;if(t instanceof Uint8Array)n=new Uint8Array(t);else if(t instanceof Float32Array)n=new Float32Array(t);else{if(!(t instanceof WebGLTexture))throw Error(`Type is not supported: ${t}`);{const r=NW(this),a=got(this);r.activeTexture(r.TEXTURE1),n=lts(a,r,this.m?r.LINEAR:r.NEAREST),r.bindTexture(r.TEXTURE_2D,n);const i=hts(this);r.texImage2D(r.TEXTURE_2D,0,i,this.width,this.height,0,r.RED,r.FLOAT,null),r.bindTexture(r.TEXTURE_2D,null),cts(a,r,n),eHn(a,r,!1,()=>{mts(this),r.clearColor(0,0,0,0),r.clear(r.COLOR_BUFFER_BIT),r.drawArrays(r.TRIANGLE_FAN,0,4),tZe(this)}),tHn(a),tZe(this)}}s.push(n)}return new sv(s,this.m,this.R(),this.canvas,this.l,this.width,this.height)}close(){this.j&&NW(this).deleteTexture(fE(this,2)),C5t=-1}};sv.prototype.close=sv.prototype.close,sv.prototype.clone=sv.prototype.clone,sv.prototype.getAsWebGLTexture=sv.prototype.N,sv.prototype.getAsFloat32Array=sv.prototype.ia,sv.prototype.getAsUint8Array=sv.prototype.ja,sv.prototype.hasWebGLTexture=sv.prototype.R,sv.prototype.hasFloat32Array=sv.prototype.ka,sv.prototype.hasUint8Array=sv.prototype.Fa;var C5t=250;function AC(...s){return s.map(([t,n])=>({start:t,end:n}))}const sHn=function(s){return class extends s{Ja(){this.i._registerModelResourcesGraphService()}}}((A5t=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:its()?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 n=s.length,r=this.i._malloc(n);this.i.HEAPU8.set(s,r),t?this.i._changeBinaryGraph(n,r):this.i._changeTextGraph(n,r),this.i._free(r)}configureAudio(s,t,n,r,a){this.i._configureAudio||console.warn('Attempting to use configureAudio without support for input audio. Is build dep ":gl_graph_runner_audio" missing?'),yl(this,r||"input_audio",i=>{yl(this,a=a||"audio_header",l=>{this.i._configureAudio(i,l,s,t??0,n)})})}setAutoResizeCanvas(s){this.l=s}setAutoRenderToScreen(s){this.i._setAutoRenderToScreen(s)}setGpuBufferVerticalFlip(s){this.i.gpuOriginForWebTexturesIsBottomLeft=s}ca(s){a5(this,"__graph_config__",t=>{s(t)}),yl(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,n){this.addAudioToStreamWithShape(s,0,0,t,n)}addAudioToStreamWithShape(s,t,n,r,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),yl(this,r,l=>{this.i._addAudioToInputStream(this.g,t,n,l,a)})}addGpuBufferToStream(s,t,n){yl(this,t,r=>{const[a,i]=w5t(this,s,r);this.i._addBoundTextureToStream(r,a,i,n)})}addBoolToStream(s,t,n){yl(this,t,r=>{this.i._addBoolToInputStream(s,r,n)})}addDoubleToStream(s,t,n){yl(this,t,r=>{this.i._addDoubleToInputStream(s,r,n)})}addFloatToStream(s,t,n){yl(this,t,r=>{this.i._addFloatToInputStream(s,r,n)})}addIntToStream(s,t,n){yl(this,t,r=>{this.i._addIntToInputStream(s,r,n)})}addUintToStream(s,t,n){yl(this,t,r=>{this.i._addUintToInputStream(s,r,n)})}addStringToStream(s,t,n){yl(this,t,r=>{yl(this,s,a=>{this.i._addStringToInputStream(a,r,n)})})}addStringRecordToStream(s,t,n){yl(this,t,r=>{j5t(this,Object.keys(s),a=>{j5t(this,Object.values(s),i=>{this.i._addFlatHashMapToInputStream(a,i,Object.keys(s).length,r,n)})})})}addProtoToStream(s,t,n,r){yl(this,n,a=>{yl(this,t,i=>{const l=this.i._malloc(s.length);this.i.HEAPU8.set(s,l),this.i._addProtoToInputStream(l,s.length,i,a,r),this.i._free(l)})})}addEmptyPacketToStream(s,t){yl(this,s,n=>{this.i._addEmptyPacketToInputStream(n,t)})}addBoolVectorToStream(s,t,n){yl(this,t,r=>{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,r,n)})}addDoubleVectorToStream(s,t,n){yl(this,t,r=>{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,r,n)})}addFloatVectorToStream(s,t,n){yl(this,t,r=>{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,r,n)})}addIntVectorToStream(s,t,n){yl(this,t,r=>{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,r,n)})}addUintVectorToStream(s,t,n){yl(this,t,r=>{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,r,n)})}addStringVectorToStream(s,t,n){yl(this,t,r=>{const a=this.i._allocateStringVector(s.length);if(!a)throw Error("Unable to allocate new string vector on heap.");for(const i of s)yl(this,i,l=>{this.i._addStringVectorEntry(a,l)});this.i._addStringVectorToInputStream(a,r,n)})}addBoolToInputSidePacket(s,t){yl(this,t,n=>{this.i._addBoolToInputSidePacket(s,n)})}addDoubleToInputSidePacket(s,t){yl(this,t,n=>{this.i._addDoubleToInputSidePacket(s,n)})}addFloatToInputSidePacket(s,t){yl(this,t,n=>{this.i._addFloatToInputSidePacket(s,n)})}addIntToInputSidePacket(s,t){yl(this,t,n=>{this.i._addIntToInputSidePacket(s,n)})}addUintToInputSidePacket(s,t){yl(this,t,n=>{this.i._addUintToInputSidePacket(s,n)})}addStringToInputSidePacket(s,t){yl(this,t,n=>{yl(this,s,r=>{this.i._addStringToInputSidePacket(r,n)})})}addProtoToInputSidePacket(s,t,n){yl(this,n,r=>{yl(this,t,a=>{const i=this.i._malloc(s.length);this.i.HEAPU8.set(s,i),this.i._addProtoToInputSidePacket(i,s.length,a,r),this.i._free(i)})})}addBoolVectorToInputSidePacket(s,t){yl(this,t,n=>{const r=this.i._allocateBoolVector(s.length);if(!r)throw Error("Unable to allocate new bool vector on heap.");for(const a of s)this.i._addBoolVectorEntry(r,a);this.i._addBoolVectorToInputSidePacket(r,n)})}addDoubleVectorToInputSidePacket(s,t){yl(this,t,n=>{const r=this.i._allocateDoubleVector(s.length);if(!r)throw Error("Unable to allocate new double vector on heap.");for(const a of s)this.i._addDoubleVectorEntry(r,a);this.i._addDoubleVectorToInputSidePacket(r,n)})}addFloatVectorToInputSidePacket(s,t){yl(this,t,n=>{const r=this.i._allocateFloatVector(s.length);if(!r)throw Error("Unable to allocate new float vector on heap.");for(const a of s)this.i._addFloatVectorEntry(r,a);this.i._addFloatVectorToInputSidePacket(r,n)})}addIntVectorToInputSidePacket(s,t){yl(this,t,n=>{const r=this.i._allocateIntVector(s.length);if(!r)throw Error("Unable to allocate new int vector on heap.");for(const a of s)this.i._addIntVectorEntry(r,a);this.i._addIntVectorToInputSidePacket(r,n)})}addUintVectorToInputSidePacket(s,t){yl(this,t,n=>{const r=this.i._allocateUintVector(s.length);if(!r)throw Error("Unable to allocate new unsigned int vector on heap.");for(const a of s)this.i._addUintVectorEntry(r,a);this.i._addUintVectorToInputSidePacket(r,n)})}addStringVectorToInputSidePacket(s,t){yl(this,t,n=>{const r=this.i._allocateStringVector(s.length);if(!r)throw Error("Unable to allocate new string vector on heap.");for(const a of s)yl(this,a,i=>{this.i._addStringVectorEntry(r,i)});this.i._addStringVectorToInputSidePacket(r,n)})}attachBoolListener(s,t){a5(this,s,t),yl(this,s,n=>{this.i._attachBoolListener(n)})}attachBoolVectorListener(s,t){EM(this,s,t),yl(this,s,n=>{this.i._attachBoolVectorListener(n)})}attachIntListener(s,t){a5(this,s,t),yl(this,s,n=>{this.i._attachIntListener(n)})}attachIntVectorListener(s,t){EM(this,s,t),yl(this,s,n=>{this.i._attachIntVectorListener(n)})}attachUintListener(s,t){a5(this,s,t),yl(this,s,n=>{this.i._attachUintListener(n)})}attachUintVectorListener(s,t){EM(this,s,t),yl(this,s,n=>{this.i._attachUintVectorListener(n)})}attachDoubleListener(s,t){a5(this,s,t),yl(this,s,n=>{this.i._attachDoubleListener(n)})}attachDoubleVectorListener(s,t){EM(this,s,t),yl(this,s,n=>{this.i._attachDoubleVectorListener(n)})}attachFloatListener(s,t){a5(this,s,t),yl(this,s,n=>{this.i._attachFloatListener(n)})}attachFloatVectorListener(s,t){EM(this,s,t),yl(this,s,n=>{this.i._attachFloatVectorListener(n)})}attachStringListener(s,t){a5(this,s,t),yl(this,s,n=>{this.i._attachStringListener(n)})}attachStringVectorListener(s,t){EM(this,s,t),yl(this,s,n=>{this.i._attachStringVectorListener(n)})}attachProtoListener(s,t,n){a5(this,s,t),yl(this,s,r=>{this.i._attachProtoListener(r,n||!1)})}attachProtoVectorListener(s,t,n){EM(this,s,t),yl(this,s,r=>{this.i._attachProtoVectorListener(r,n||!1)})}attachAudioListener(s,t,n){this.i._attachAudioListener||console.warn('Attempting to use attachAudioListener without support for output audio. Is build dep ":gl_graph_runner_audio_out" missing?'),a5(this,s,(r,a)=>{r=new Float32Array(r.buffer,r.byteOffset,r.length/4),t(r,a)}),yl(this,s,r=>{this.i._attachAudioListener(r,n||!1)})}finishProcessing(){this.i._waitUntilIdle()}closeGraph(){this.i._closeGraph(),this.i.simpleListeners=void 0,this.i.emptyPacketListeners=void 0}},class extends A5t{get ga(){return this.i}pa(s,t,n){yl(this,t,r=>{const[a,i]=w5t(this,s,r);this.ga._addBoundTextureAsImageToStream(r,a,i,n)})}Z(s,t){a5(this,s,t),yl(this,s,n=>{this.ga._attachImageListener(n)})}aa(s,t){EM(this,s,t),yl(this,s,n=>{this.ga._attachImageVectorListener(n)})}}));var A5t,EC=class extends sHn{};async function Mh(s,t,n){return async function(r,a,i,l){return QVn(r,a,i,l)}(s,n.canvas??(its()?void 0:document.createElement("canvas")),t,n)}function fts(s,t,n,r){if(s.U){const i=new Res;if(n!=null&&n.regionOfInterest){if(!s.oa)throw Error("This task doesn't support region-of-interest.");var a=n.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].");Cl(i,1,(a.left+a.right)/2),Cl(i,2,(a.top+a.bottom)/2),Cl(i,4,a.right-a.left),Cl(i,3,a.bottom-a.top)}else Cl(i,1,.5),Cl(i,2,.5),Cl(i,4,1),Cl(i,3,1);if(n!=null&&n.rotationDegrees){if((n==null?void 0:n.rotationDegrees)%90!=0)throw Error("Expected rotation to be a multiple of 90°.");if(Cl(i,5,-Math.PI*n.rotationDegrees/180),(n==null?void 0:n.rotationDegrees)%180!=0){const[l,o]=ots(t);n=Jx(i,3)*o/l,a=Jx(i,4)*l/o,Cl(i,4,n),Cl(i,3,a)}}s.g.addProtoToStream(i.g(),"mediapipe.NormalizedRect",s.U,r)}s.g.pa(t,s.X,r??performance.now()),s.finishProcessing()}function TC(s,t,n){var r;if((r=s.baseOptions)!=null&&r.g())throw Error("Task is not initialized with image mode. 'runningMode' must be set to 'IMAGE'.");fts(s,t,n,s.C+1)}function w3(s,t,n,r){var a;if(!((a=s.baseOptions)!=null&&a.g()))throw Error("Task is not initialized with video mode. 'runningMode' must be set to 'VIDEO'.");fts(s,t,n,r)}function kW(s,t,n,r){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 sv([a],n,!1,s.g.i.canvas,s.P,i,t),r?s.clone():s}var z2=class extends JYe{constructor(s,t,n,r){super(s),this.g=s,this.X=t,this.U=n,this.oa=r,this.P=new dts}l(s,t=!0){if("runningMode"in s&&sf(this.baseOptions,2,vne(!!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()}};z2.prototype.close=z2.prototype.close;var uN=class extends z2{constructor(s,t){super(new EC(s,t),"image_in","norm_rect_in",!1),this.j={detections:[]},Jl(s=this.h=new PDe,0,1,t=new Mx),Cl(this.h,2,.5),Cl(this.h,3,.3)}get baseOptions(){return Vh(this.h,Mx,1)}set baseOptions(s){Jl(this.h,0,1,s)}o(s){return"minDetectionConfidence"in s&&Cl(this.h,2,s.minDetectionConfidence??.5),"minSuppressionThreshold"in s&&Cl(this.h,3,s.minSuppressionThreshold??.3),this.l(s)}F(s,t){return this.j={detections:[]},TC(this,s,t),this.j}G(s,t,n){return this.j={detections:[]},w3(this,s,n,t),this.j}m(){var s=new W2;Hg(s,"image_in"),Hg(s,"norm_rect_in"),nm(s,"detections");const t=new G2;b3(t,FVn,this.h);const n=new Qw;O2(n,2,"mediapipe.tasks.vision.face_detector.FaceDetectorGraph"),tg(n,"IMAGE:image_in"),tg(n,"NORM_RECT:norm_rect_in"),gh(n,"DETECTIONS:detections"),n.o(t),Ik(s,n),this.g.attachProtoVectorListener("detections",(r,a)=>{for(const i of r)r=Pes(i),this.j.detections.push(rts(r));qo(this,a)}),this.g.attachEmptyPacketListener("detections",r=>{qo(this,r)}),s=s.g(),this.setGraph(new Uint8Array(s),!0)}};uN.prototype.detectForVideo=uN.prototype.G,uN.prototype.detect=uN.prototype.F,uN.prototype.setOptions=uN.prototype.o,uN.createFromModelPath=async function(s,t){return Mh(uN,s,{baseOptions:{modelAssetPath:t}})},uN.createFromModelBuffer=function(s,t){return Mh(uN,s,{baseOptions:{modelAssetBuffer:t}})},uN.createFromOptions=function(s,t){return Mh(uN,s,t)};var xot=AC([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]),yot=AC([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]),vot=AC([276,283],[283,282],[282,295],[295,285],[300,293],[293,334],[334,296],[296,336]),pts=AC([474,475],[475,476],[476,477],[477,474]),bot=AC([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]),_ot=AC([46,53],[53,52],[52,65],[65,55],[70,63],[63,105],[105,66],[66,107]),gts=AC([469,470],[470,471],[471,472],[472,469]),wot=AC([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]),xts=[...xot,...yot,...vot,...bot,..._ot,...wot],yts=AC([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 E5t(s){s.j={faceLandmarks:[],faceBlendshapes:[],facialTransformationMatrixes:[]}}var cx=class extends z2{constructor(s,t){super(new EC(s,t),"image_in","norm_rect",!1),this.j={faceLandmarks:[],faceBlendshapes:[],facialTransformationMatrixes:[]},this.outputFacialTransformationMatrixes=this.outputFaceBlendshapes=!1,Jl(s=this.h=new Bes,0,1,t=new Mx),this.A=new zes,Jl(this.h,0,3,this.A),this.u=new PDe,Jl(this.h,0,2,this.u),jT(this.u,4,1),Cl(this.u,2,.5),Cl(this.A,2,.5),Cl(this.h,4,.5)}get baseOptions(){return Vh(this.h,Mx,1)}set baseOptions(s){Jl(this.h,0,1,s)}o(s){return"numFaces"in s&&jT(this.u,4,s.numFaces??1),"minFaceDetectionConfidence"in s&&Cl(this.u,2,s.minFaceDetectionConfidence??.5),"minTrackingConfidence"in s&&Cl(this.h,4,s.minTrackingConfidence??.5),"minFacePresenceConfidence"in s&&Cl(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 E5t(this),TC(this,s,t),this.j}G(s,t,n){return E5t(this),w3(this,s,n,t),this.j}m(){var s=new W2;Hg(s,"image_in"),Hg(s,"norm_rect"),nm(s,"face_landmarks");const t=new G2;b3(t,zVn,this.h);const n=new Qw;O2(n,2,"mediapipe.tasks.vision.face_landmarker.FaceLandmarkerGraph"),tg(n,"IMAGE:image_in"),tg(n,"NORM_RECT:norm_rect"),gh(n,"NORM_LANDMARKS:face_landmarks"),n.o(t),Ik(s,n),this.g.attachProtoVectorListener("face_landmarks",(r,a)=>{for(const i of r)r=Hie(i),this.j.faceLandmarks.push(IDe(r));qo(this,a)}),this.g.attachEmptyPacketListener("face_landmarks",r=>{qo(this,r)}),this.outputFaceBlendshapes&&(nm(s,"blendshapes"),gh(n,"BLENDSHAPES:blendshapes"),this.g.attachProtoVectorListener("blendshapes",(r,a)=>{if(this.outputFaceBlendshapes)for(const i of r)r=MDe(i),this.j.faceBlendshapes.push(fot(r.g()??[]));qo(this,a)}),this.g.attachEmptyPacketListener("blendshapes",r=>{qo(this,r)})),this.outputFacialTransformationMatrixes&&(nm(s,"face_geometry"),gh(n,"FACE_GEOMETRY:face_geometry"),this.g.attachProtoVectorListener("face_geometry",(r,a)=>{if(this.outputFacialTransformationMatrixes)for(const i of r)(r=Vh(r=OVn(i),EVn,2))&&this.j.facialTransformationMatrixes.push({rows:YN(r,1)??0??0,columns:YN(r,2)??0??0,data:k8(r,3,_4,N8()).slice()??[]});qo(this,a)}),this.g.attachEmptyPacketListener("face_geometry",r=>{qo(this,r)})),s=s.g(),this.setGraph(new Uint8Array(s),!0)}};cx.prototype.detectForVideo=cx.prototype.G,cx.prototype.detect=cx.prototype.F,cx.prototype.setOptions=cx.prototype.o,cx.createFromModelPath=function(s,t){return Mh(cx,s,{baseOptions:{modelAssetPath:t}})},cx.createFromModelBuffer=function(s,t){return Mh(cx,s,{baseOptions:{modelAssetBuffer:t}})},cx.createFromOptions=function(s,t){return Mh(cx,s,t)},cx.FACE_LANDMARKS_LIPS=xot,cx.FACE_LANDMARKS_LEFT_EYE=yot,cx.FACE_LANDMARKS_LEFT_EYEBROW=vot,cx.FACE_LANDMARKS_LEFT_IRIS=pts,cx.FACE_LANDMARKS_RIGHT_EYE=bot,cx.FACE_LANDMARKS_RIGHT_EYEBROW=_ot,cx.FACE_LANDMARKS_RIGHT_IRIS=gts,cx.FACE_LANDMARKS_FACE_OVAL=wot,cx.FACE_LANDMARKS_CONTOURS=xts,cx.FACE_LANDMARKS_TESSELATION=yts;var jot=AC([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 T5t(s){s.gestures=[],s.landmarks=[],s.worldLandmarks=[],s.handedness=[]}function M5t(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 P5t(s,t=!0){const n=[];for(const a of s){var r=MDe(a);s=[];for(const i of r.g())r=t&&YN(i,1)!=null?YN(i,1)??0:-1,s.push({score:Jx(i,2)??0,index:r,categoryName:kb(Pg(i,3))??""??"",displayName:kb(Pg(i,4))??""??""});n.push(s)}return n}var bj=class extends z2{constructor(s,t){super(new EC(s,t),"image_in","norm_rect",!1),this.gestures=[],this.landmarks=[],this.worldLandmarks=[],this.handedness=[],Jl(s=this.j=new qes,0,1,t=new Mx),this.u=new dot,Jl(this.j,0,2,this.u),this.D=new cot,Jl(this.u,0,3,this.D),this.A=new Ues,Jl(this.u,0,2,this.A),this.h=new BVn,Jl(this.j,0,3,this.h),Cl(this.A,2,.5),Cl(this.u,4,.5),Cl(this.D,2,.5)}get baseOptions(){return Vh(this.j,Mx,1)}set baseOptions(s){Jl(this.j,0,1,s)}o(s){var a,i,l,o;if(jT(this.A,3,s.numHands??1),"minHandDetectionConfidence"in s&&Cl(this.A,2,s.minHandDetectionConfidence??.5),"minTrackingConfidence"in s&&Cl(this.u,4,s.minTrackingConfidence??.5),"minHandPresenceConfidence"in s&&Cl(this.D,2,s.minHandPresenceConfidence??.5),s.cannedGesturesClassifierOptions){var t=new H$,n=t,r=QYe(s.cannedGesturesClassifierOptions,(a=Vh(this.h,H$,3))==null?void 0:a.l());Jl(n,0,2,r),Jl(this.h,0,3,t)}else s.cannedGesturesClassifierOptions===void 0&&((i=Vh(this.h,H$,3))==null||i.g());return s.customGesturesClassifierOptions?(Jl(n=t=new H$,0,2,r=QYe(s.customGesturesClassifierOptions,(l=Vh(this.h,H$,4))==null?void 0:l.l())),Jl(this.h,0,4,t)):s.customGesturesClassifierOptions===void 0&&((o=Vh(this.h,H$,4))==null||o.g()),this.l(s)}Ha(s,t){return T5t(this),TC(this,s,t),M5t(this)}Ia(s,t,n){return T5t(this),w3(this,s,n,t),M5t(this)}m(){var s=new W2;Hg(s,"image_in"),Hg(s,"norm_rect"),nm(s,"hand_gestures"),nm(s,"hand_landmarks"),nm(s,"world_hand_landmarks"),nm(s,"handedness");const t=new G2;b3(t,$Vn,this.j);const n=new Qw;O2(n,2,"mediapipe.tasks.vision.gesture_recognizer.GestureRecognizerGraph"),tg(n,"IMAGE:image_in"),tg(n,"NORM_RECT:norm_rect"),gh(n,"HAND_GESTURES:hand_gestures"),gh(n,"LANDMARKS:hand_landmarks"),gh(n,"WORLD_LANDMARKS:world_hand_landmarks"),gh(n,"HANDEDNESS:handedness"),n.o(t),Ik(s,n),this.g.attachProtoVectorListener("hand_landmarks",(r,a)=>{for(const i of r){r=Hie(i);const l=[];for(const o of wT(r,Les,1))l.push({x:Jx(o,1)??0,y:Jx(o,2)??0,z:Jx(o,3)??0,visibility:Jx(o,4)??0});this.landmarks.push(l)}qo(this,a)}),this.g.attachEmptyPacketListener("hand_landmarks",r=>{qo(this,r)}),this.g.attachProtoVectorListener("world_hand_landmarks",(r,a)=>{for(const i of r){r=FV(i);const l=[];for(const o of wT(r,Ies,1))l.push({x:Jx(o,1)??0,y:Jx(o,2)??0,z:Jx(o,3)??0,visibility:Jx(o,4)??0});this.worldLandmarks.push(l)}qo(this,a)}),this.g.attachEmptyPacketListener("world_hand_landmarks",r=>{qo(this,r)}),this.g.attachProtoVectorListener("hand_gestures",(r,a)=>{this.gestures.push(...P5t(r,!1)),qo(this,a)}),this.g.attachEmptyPacketListener("hand_gestures",r=>{qo(this,r)}),this.g.attachProtoVectorListener("handedness",(r,a)=>{this.handedness.push(...P5t(r)),qo(this,a)}),this.g.attachEmptyPacketListener("handedness",r=>{qo(this,r)}),s=s.g(),this.setGraph(new Uint8Array(s),!0)}};function I5t(s){return{landmarks:s.landmarks,worldLandmarks:s.worldLandmarks,handednesses:s.handedness,handedness:s.handedness}}bj.prototype.recognizeForVideo=bj.prototype.Ia,bj.prototype.recognize=bj.prototype.Ha,bj.prototype.setOptions=bj.prototype.o,bj.createFromModelPath=function(s,t){return Mh(bj,s,{baseOptions:{modelAssetPath:t}})},bj.createFromModelBuffer=function(s,t){return Mh(bj,s,{baseOptions:{modelAssetBuffer:t}})},bj.createFromOptions=function(s,t){return Mh(bj,s,t)},bj.HAND_CONNECTIONS=jot;var _j=class extends z2{constructor(s,t){super(new EC(s,t),"image_in","norm_rect",!1),this.landmarks=[],this.worldLandmarks=[],this.handedness=[],Jl(s=this.h=new dot,0,1,t=new Mx),this.u=new cot,Jl(this.h,0,3,this.u),this.j=new Ues,Jl(this.h,0,2,this.j),jT(this.j,3,1),Cl(this.j,2,.5),Cl(this.u,2,.5),Cl(this.h,4,.5)}get baseOptions(){return Vh(this.h,Mx,1)}set baseOptions(s){Jl(this.h,0,1,s)}o(s){return"numHands"in s&&jT(this.j,3,s.numHands??1),"minHandDetectionConfidence"in s&&Cl(this.j,2,s.minHandDetectionConfidence??.5),"minTrackingConfidence"in s&&Cl(this.h,4,s.minTrackingConfidence??.5),"minHandPresenceConfidence"in s&&Cl(this.u,2,s.minHandPresenceConfidence??.5),this.l(s)}F(s,t){return this.landmarks=[],this.worldLandmarks=[],this.handedness=[],TC(this,s,t),I5t(this)}G(s,t,n){return this.landmarks=[],this.worldLandmarks=[],this.handedness=[],w3(this,s,n,t),I5t(this)}m(){var s=new W2;Hg(s,"image_in"),Hg(s,"norm_rect"),nm(s,"hand_landmarks"),nm(s,"world_hand_landmarks"),nm(s,"handedness");const t=new G2;b3(t,UVn,this.h);const n=new Qw;O2(n,2,"mediapipe.tasks.vision.hand_landmarker.HandLandmarkerGraph"),tg(n,"IMAGE:image_in"),tg(n,"NORM_RECT:norm_rect"),gh(n,"LANDMARKS:hand_landmarks"),gh(n,"WORLD_LANDMARKS:world_hand_landmarks"),gh(n,"HANDEDNESS:handedness"),n.o(t),Ik(s,n),this.g.attachProtoVectorListener("hand_landmarks",(r,a)=>{for(const i of r)r=Hie(i),this.landmarks.push(IDe(r));qo(this,a)}),this.g.attachEmptyPacketListener("hand_landmarks",r=>{qo(this,r)}),this.g.attachProtoVectorListener("world_hand_landmarks",(r,a)=>{for(const i of r)r=FV(i),this.worldLandmarks.push(nte(r));qo(this,a)}),this.g.attachEmptyPacketListener("world_hand_landmarks",r=>{qo(this,r)}),this.g.attachProtoVectorListener("handedness",(r,a)=>{var i=this.handedness,l=i.push;const o=[];for(const c of r){r=MDe(c);const d=[];for(const u of r.g())d.push({score:Jx(u,2)??0,index:YN(u,1)??0??-1,categoryName:kb(Pg(u,3))??""??"",displayName:kb(Pg(u,4))??""??""});o.push(d)}l.call(i,...o),qo(this,a)}),this.g.attachEmptyPacketListener("handedness",r=>{qo(this,r)}),s=s.g(),this.setGraph(new Uint8Array(s),!0)}};_j.prototype.detectForVideo=_j.prototype.G,_j.prototype.detect=_j.prototype.F,_j.prototype.setOptions=_j.prototype.o,_j.createFromModelPath=function(s,t){return Mh(_j,s,{baseOptions:{modelAssetPath:t}})},_j.createFromModelBuffer=function(s,t){return Mh(_j,s,{baseOptions:{modelAssetBuffer:t}})},_j.createFromOptions=function(s,t){return Mh(_j,s,t)},_j.HAND_CONNECTIONS=jot;var vts=AC([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 L5t(s){s.h={faceLandmarks:[],faceBlendshapes:[],poseLandmarks:[],poseWorldLandmarks:[],poseSegmentationMasks:[],leftHandLandmarks:[],leftHandWorldLandmarks:[],rightHandLandmarks:[],rightHandWorldLandmarks:[]}}function R5t(s){try{if(!s.D)return s.h;s.D(s.h)}finally{RDe(s)}}function jue(s,t){s=Hie(s),t.push(IDe(s))}var Dp=class extends z2{constructor(s,t){super(new EC(s,t),"input_frames_image",null,!1),this.h={faceLandmarks:[],faceBlendshapes:[],poseLandmarks:[],poseWorldLandmarks:[],poseSegmentationMasks:[],leftHandLandmarks:[],leftHandWorldLandmarks:[],rightHandLandmarks:[],rightHandWorldLandmarks:[]},this.outputPoseSegmentationMasks=this.outputFaceBlendshapes=!1,Jl(s=this.j=new Kes,0,1,t=new Mx),this.I=new cot,Jl(this.j,0,2,this.I),this.W=new qVn,Jl(this.j,0,3,this.W),this.u=new PDe,Jl(this.j,0,4,this.u),this.O=new zes,Jl(this.j,0,5,this.O),this.A=new Ges,Jl(this.j,0,6,this.A),this.M=new Wes,Jl(this.j,0,7,this.M),Cl(this.u,2,.5),Cl(this.u,3,.3),Cl(this.O,2,.5),Cl(this.A,2,.5),Cl(this.A,3,.3),Cl(this.M,2,.5),Cl(this.I,2,.5)}get baseOptions(){return Vh(this.j,Mx,1)}set baseOptions(s){Jl(this.j,0,1,s)}o(s){return"minFaceDetectionConfidence"in s&&Cl(this.u,2,s.minFaceDetectionConfidence??.5),"minFaceSuppressionThreshold"in s&&Cl(this.u,3,s.minFaceSuppressionThreshold??.3),"minFacePresenceConfidence"in s&&Cl(this.O,2,s.minFacePresenceConfidence??.5),"outputFaceBlendshapes"in s&&(this.outputFaceBlendshapes=!!s.outputFaceBlendshapes),"minPoseDetectionConfidence"in s&&Cl(this.A,2,s.minPoseDetectionConfidence??.5),"minPoseSuppressionThreshold"in s&&Cl(this.A,3,s.minPoseSuppressionThreshold??.3),"minPosePresenceConfidence"in s&&Cl(this.M,2,s.minPosePresenceConfidence??.5),"outputPoseSegmentationMasks"in s&&(this.outputPoseSegmentationMasks=!!s.outputPoseSegmentationMasks),"minHandLandmarksConfidence"in s&&Cl(this.I,2,s.minHandLandmarksConfidence??.5),this.l(s)}F(s,t,n){const r=typeof t!="function"?t:{};return this.D=typeof t=="function"?t:n,L5t(this),TC(this,s,r),R5t(this)}G(s,t,n,r){const a=typeof n!="function"?n:{};return this.D=typeof n=="function"?n:r,L5t(this),w3(this,s,a,t),R5t(this)}m(){var s=new W2;Hg(s,"input_frames_image"),nm(s,"pose_landmarks"),nm(s,"pose_world_landmarks"),nm(s,"face_landmarks"),nm(s,"left_hand_landmarks"),nm(s,"left_hand_world_landmarks"),nm(s,"right_hand_landmarks"),nm(s,"right_hand_world_landmarks");const t=new G2,n=new a5t;O2(n,1,"type.googleapis.com/mediapipe.tasks.vision.holistic_landmarker.proto.HolisticLandmarkerGraphOptions"),function(a,i){if(i!=null)if(Array.isArray(i))sf(a,2,vDe(i,0,bne));else{if(!(typeof i=="string"||i instanceof H4||Eit(i)))throw Error("invalid value in Any.value field: "+i+" expected a ByteString, a base64 encoded string, a Uint8Array or a jspb array");bP(a,2,Mit(i,!1),mB())}}(n,this.j.g());const r=new Qw;O2(r,2,"mediapipe.tasks.vision.holistic_landmarker.HolisticLandmarkerGraph"),Hit(r,8,a5t,n),tg(r,"IMAGE:input_frames_image"),gh(r,"POSE_LANDMARKS:pose_landmarks"),gh(r,"POSE_WORLD_LANDMARKS:pose_world_landmarks"),gh(r,"FACE_LANDMARKS:face_landmarks"),gh(r,"LEFT_HAND_LANDMARKS:left_hand_landmarks"),gh(r,"LEFT_HAND_WORLD_LANDMARKS:left_hand_world_landmarks"),gh(r,"RIGHT_HAND_LANDMARKS:right_hand_landmarks"),gh(r,"RIGHT_HAND_WORLD_LANDMARKS:right_hand_world_landmarks"),r.o(t),Ik(s,r),LDe(this,s),this.g.attachProtoListener("pose_landmarks",(a,i)=>{jue(a,this.h.poseLandmarks),qo(this,i)}),this.g.attachEmptyPacketListener("pose_landmarks",a=>{qo(this,a)}),this.g.attachProtoListener("pose_world_landmarks",(a,i)=>{var l=this.h.poseWorldLandmarks;a=FV(a),l.push(nte(a)),qo(this,i)}),this.g.attachEmptyPacketListener("pose_world_landmarks",a=>{qo(this,a)}),this.outputPoseSegmentationMasks&&(gh(r,"POSE_SEGMENTATION_MASK:pose_segmentation_mask"),jW(this,"pose_segmentation_mask"),this.g.Z("pose_segmentation_mask",(a,i)=>{this.h.poseSegmentationMasks=[kW(this,a,!0,!this.D)],qo(this,i)}),this.g.attachEmptyPacketListener("pose_segmentation_mask",a=>{this.h.poseSegmentationMasks=[],qo(this,a)})),this.g.attachProtoListener("face_landmarks",(a,i)=>{jue(a,this.h.faceLandmarks),qo(this,i)}),this.g.attachEmptyPacketListener("face_landmarks",a=>{qo(this,a)}),this.outputFaceBlendshapes&&(nm(s,"extra_blendshapes"),gh(r,"FACE_BLENDSHAPES:extra_blendshapes"),this.g.attachProtoListener("extra_blendshapes",(a,i)=>{var l=this.h.faceBlendshapes;this.outputFaceBlendshapes&&(a=MDe(a),l.push(fot(a.g()??[]))),qo(this,i)}),this.g.attachEmptyPacketListener("extra_blendshapes",a=>{qo(this,a)})),this.g.attachProtoListener("left_hand_landmarks",(a,i)=>{jue(a,this.h.leftHandLandmarks),qo(this,i)}),this.g.attachEmptyPacketListener("left_hand_landmarks",a=>{qo(this,a)}),this.g.attachProtoListener("left_hand_world_landmarks",(a,i)=>{var l=this.h.leftHandWorldLandmarks;a=FV(a),l.push(nte(a)),qo(this,i)}),this.g.attachEmptyPacketListener("left_hand_world_landmarks",a=>{qo(this,a)}),this.g.attachProtoListener("right_hand_landmarks",(a,i)=>{jue(a,this.h.rightHandLandmarks),qo(this,i)}),this.g.attachEmptyPacketListener("right_hand_landmarks",a=>{qo(this,a)}),this.g.attachProtoListener("right_hand_world_landmarks",(a,i)=>{var l=this.h.rightHandWorldLandmarks;a=FV(a),l.push(nte(a)),qo(this,i)}),this.g.attachEmptyPacketListener("right_hand_world_landmarks",a=>{qo(this,a)}),s=s.g(),this.setGraph(new Uint8Array(s),!0)}};Dp.prototype.detectForVideo=Dp.prototype.G,Dp.prototype.detect=Dp.prototype.F,Dp.prototype.setOptions=Dp.prototype.o,Dp.createFromModelPath=function(s,t){return Mh(Dp,s,{baseOptions:{modelAssetPath:t}})},Dp.createFromModelBuffer=function(s,t){return Mh(Dp,s,{baseOptions:{modelAssetBuffer:t}})},Dp.createFromOptions=function(s,t){return Mh(Dp,s,t)},Dp.HAND_CONNECTIONS=jot,Dp.POSE_CONNECTIONS=vts,Dp.FACE_LANDMARKS_LIPS=xot,Dp.FACE_LANDMARKS_LEFT_EYE=yot,Dp.FACE_LANDMARKS_LEFT_EYEBROW=vot,Dp.FACE_LANDMARKS_LEFT_IRIS=pts,Dp.FACE_LANDMARKS_RIGHT_EYE=bot,Dp.FACE_LANDMARKS_RIGHT_EYEBROW=_ot,Dp.FACE_LANDMARKS_RIGHT_IRIS=gts,Dp.FACE_LANDMARKS_FACE_OVAL=wot,Dp.FACE_LANDMARKS_CONTOURS=xts,Dp.FACE_LANDMARKS_TESSELATION=yts;var hN=class extends z2{constructor(s,t){super(new EC(s,t),"input_image","norm_rect",!0),this.j={classifications:[]},Jl(s=this.h=new Yes,0,1,t=new Mx)}get baseOptions(){return Vh(this.h,Mx,1)}set baseOptions(s){Jl(this.h,0,1,s)}o(s){return Jl(this.h,0,2,QYe(s,Vh(this.h,oot,2))),this.l(s)}sa(s,t){return this.j={classifications:[]},TC(this,s,t),this.j}ta(s,t,n){return this.j={classifications:[]},w3(this,s,n,t),this.j}m(){var s=new W2;Hg(s,"input_image"),Hg(s,"norm_rect"),nm(s,"classifications");const t=new G2;b3(t,VVn,this.h);const n=new Qw;O2(n,2,"mediapipe.tasks.vision.image_classifier.ImageClassifierGraph"),tg(n,"IMAGE:input_image"),tg(n,"NORM_RECT:norm_rect"),gh(n,"CLASSIFICATIONS:classifications"),n.o(t),Ik(s,n),this.g.attachProtoListener("classifications",(r,a)=>{this.j=ZVn(PVn(r)),qo(this,a)}),this.g.attachEmptyPacketListener("classifications",r=>{qo(this,r)}),s=s.g(),this.setGraph(new Uint8Array(s),!0)}};hN.prototype.classifyForVideo=hN.prototype.ta,hN.prototype.classify=hN.prototype.sa,hN.prototype.setOptions=hN.prototype.o,hN.createFromModelPath=function(s,t){return Mh(hN,s,{baseOptions:{modelAssetPath:t}})},hN.createFromModelBuffer=function(s,t){return Mh(hN,s,{baseOptions:{modelAssetBuffer:t}})},hN.createFromOptions=function(s,t){return Mh(hN,s,t)};var wj=class extends z2{constructor(s,t){super(new EC(s,t),"image_in","norm_rect",!0),this.h=new Zes,this.embeddings={embeddings:[]},Jl(s=this.h,0,1,t=new Mx)}get baseOptions(){return Vh(this.h,Mx,1)}set baseOptions(s){Jl(this.h,0,1,s)}o(s){var t=this.h,n=Vh(this.h,f5t,2);return n=n?n.clone():new f5t,s.l2Normalize!==void 0?sf(n,1,vne(s.l2Normalize)):"l2Normalize"in s&&sf(n,1),s.quantize!==void 0?sf(n,2,vne(s.quantize)):"quantize"in s&&sf(n,2),Jl(t,0,2,n),this.l(s)}za(s,t){return TC(this,s,t),this.embeddings}Aa(s,t,n){return w3(this,s,n,t),this.embeddings}m(){var s=new W2;Hg(s,"image_in"),Hg(s,"norm_rect"),nm(s,"embeddings_out");const t=new G2;b3(t,HVn,this.h);const n=new Qw;O2(n,2,"mediapipe.tasks.vision.image_embedder.ImageEmbedderGraph"),tg(n,"IMAGE:image_in"),tg(n,"NORM_RECT:norm_rect"),gh(n,"EMBEDDINGS:embeddings_out"),n.o(t),Ik(s,n),this.g.attachProtoListener("embeddings_out",(r,a)=>{r=RVn(r),this.embeddings=function(i){return{embeddings:wT(i,LVn,1).map(l=>{var d,u;const o={headIndex:YN(l,3)??0??-1,headName:kb(Pg(l,4))??""??""};var c=l.v;return WJt(c,0|c[hl],m5t,i$e(l,1))!==void 0?(l=k8(l=Vh(l,m5t,i$e(l,1),void 0),1,_4,N8()),o.floatEmbedding=l.slice()):(c=new Uint8Array(0),o.quantizedEmbedding=((u=(d=Vh(l,IVn,i$e(l,2),void 0))==null?void 0:d.na())==null?void 0:u.h())??c),o}),timestampMs:nts(Pg(i,2,void 0,void 0,nPe)??UJt)}}(r),qo(this,a)}),this.g.attachEmptyPacketListener("embeddings_out",r=>{qo(this,r)}),s=s.g(),this.setGraph(new Uint8Array(s),!0)}};wj.cosineSimilarity=function(s,t){if(s.floatEmbedding&&t.floatEmbedding)s=b5t(s.floatEmbedding,t.floatEmbedding);else{if(!s.quantizedEmbedding||!t.quantizedEmbedding)throw Error("Cannot compute cosine similarity between quantized and float embeddings.");s=b5t(v5t(s.quantizedEmbedding),v5t(t.quantizedEmbedding))}return s},wj.prototype.embedForVideo=wj.prototype.Aa,wj.prototype.embed=wj.prototype.za,wj.prototype.setOptions=wj.prototype.o,wj.createFromModelPath=function(s,t){return Mh(wj,s,{baseOptions:{modelAssetPath:t}})},wj.createFromModelBuffer=function(s,t){return Mh(wj,s,{baseOptions:{modelAssetBuffer:t}})},wj.createFromOptions=function(s,t){return Mh(wj,s,t)};var sZe=class{constructor(s,t,n){this.confidenceMasks=s,this.categoryMask=t,this.qualityScores=n}close(){var s,t;(s=this.confidenceMasks)==null||s.forEach(n=>{n.close()}),(t=this.categoryMask)==null||t.close()}};function nHn(s){var n,r;const t=function(a){return wT(a,Qw,1)}(s.ca()).filter(a=>(kb(Pg(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&&(((r=(n=Vh(t[0],G2,7))==null?void 0:n.j())==null?void 0:r.g())??new Map).forEach((a,i)=>{s.u[Number(i)]=kb(Pg(a,1))??""})}function D5t(s){s.categoryMask=void 0,s.confidenceMasks=void 0,s.qualityScores=void 0}function F5t(s){try{const t=new sZe(s.confidenceMasks,s.categoryMask,s.qualityScores);if(!s.j)return t;s.j(t)}finally{RDe(s)}}sZe.prototype.close=sZe.prototype.close;var n_=class extends z2{constructor(s,t){super(new EC(s,t),"image_in","norm_rect",!1),this.u=[],this.outputCategoryMask=!1,this.outputConfidenceMasks=!0,this.h=new mot,this.A=new Xes,Jl(this.h,0,3,this.A),Jl(s=this.h,0,1,t=new Mx)}get baseOptions(){return Vh(this.h,Mx,1)}set baseOptions(s){Jl(this.h,0,1,s)}o(s){return s.displayNamesLocale!==void 0?sf(this.h,2,Uie(s.displayNamesLocale)):"displayNamesLocale"in s&&sf(this.h,2),"outputCategoryMask"in s&&(this.outputCategoryMask=s.outputCategoryMask??!1),"outputConfidenceMasks"in s&&(this.outputConfidenceMasks=s.outputConfidenceMasks??!0),super.l(s)}L(){nHn(this)}segment(s,t,n){const r=typeof t!="function"?t:{};return this.j=typeof t=="function"?t:n,D5t(this),TC(this,s,r),F5t(this)}La(s,t,n,r){const a=typeof n!="function"?n:{};return this.j=typeof n=="function"?n:r,D5t(this),w3(this,s,a,t),F5t(this)}Da(){return this.u}m(){var s=new W2;Hg(s,"image_in"),Hg(s,"norm_rect");const t=new G2;b3(t,Jes,this.h);const n=new Qw;O2(n,2,"mediapipe.tasks.vision.image_segmenter.ImageSegmenterGraph"),tg(n,"IMAGE:image_in"),tg(n,"NORM_RECT:norm_rect"),n.o(t),Ik(s,n),LDe(this,s),this.outputConfidenceMasks&&(nm(s,"confidence_masks"),gh(n,"CONFIDENCE_MASKS:confidence_masks"),jW(this,"confidence_masks"),this.g.aa("confidence_masks",(r,a)=>{this.confidenceMasks=r.map(i=>kW(this,i,!0,!this.j)),qo(this,a)}),this.g.attachEmptyPacketListener("confidence_masks",r=>{this.confidenceMasks=[],qo(this,r)})),this.outputCategoryMask&&(nm(s,"category_mask"),gh(n,"CATEGORY_MASK:category_mask"),jW(this,"category_mask"),this.g.Z("category_mask",(r,a)=>{this.categoryMask=kW(this,r,!1,!this.j),qo(this,a)}),this.g.attachEmptyPacketListener("category_mask",r=>{this.categoryMask=void 0,qo(this,r)})),nm(s,"quality_scores"),gh(n,"QUALITY_SCORES:quality_scores"),this.g.attachFloatVectorListener("quality_scores",(r,a)=>{this.qualityScores=r,qo(this,a)}),this.g.attachEmptyPacketListener("quality_scores",r=>{this.categoryMask=void 0,qo(this,r)}),s=s.g(),this.setGraph(new Uint8Array(s),!0)}};n_.prototype.getLabels=n_.prototype.Da,n_.prototype.segmentForVideo=n_.prototype.La,n_.prototype.segment=n_.prototype.segment,n_.prototype.setOptions=n_.prototype.o,n_.createFromModelPath=function(s,t){return Mh(n_,s,{baseOptions:{modelAssetPath:t}})},n_.createFromModelBuffer=function(s,t){return Mh(n_,s,{baseOptions:{modelAssetBuffer:t}})},n_.createFromOptions=function(s,t){return Mh(n_,s,t)};var nZe=class{constructor(s,t,n){this.confidenceMasks=s,this.categoryMask=t,this.qualityScores=n}close(){var s,t;(s=this.confidenceMasks)==null||s.forEach(n=>{n.close()}),(t=this.categoryMask)==null||t.close()}};nZe.prototype.close=nZe.prototype.close;var i5=class extends z2{constructor(s,t){super(new EC(s,t),"image_in","norm_rect_in",!1),this.outputCategoryMask=!1,this.outputConfidenceMasks=!0,this.h=new mot,this.u=new Xes,Jl(this.h,0,3,this.u),Jl(s=this.h,0,1,t=new Mx)}get baseOptions(){return Vh(this.h,Mx,1)}set baseOptions(s){Jl(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,n,r){const a=typeof n!="function"?n:{};if(this.j=typeof n=="function"?n:r,this.qualityScores=this.categoryMask=this.confidenceMasks=void 0,n=this.C+1,r=new ets,t.keypoint&&t.scribble)throw Error("Cannot provide both keypoint and scribble.");if(t.keypoint){var i=new d$e;bP(i,3,vne(!0),!1),bP(i,1,CQ(t.keypoint.x),0),bP(i,2,CQ(t.keypoint.y),0),tte(r,1,XYe,i)}else{if(!t.scribble)throw Error("Must provide either a keypoint or a scribble.");{const o=new WVn;for(i of t.scribble)bP(t=new d$e,3,vne(!0),!1),bP(t,1,CQ(i.x),0),bP(t,2,CQ(i.y),0),Hit(o,1,d$e,t);tte(r,2,XYe,o)}}this.g.addProtoToStream(r.g(),"mediapipe.tasks.vision.interactive_segmenter.proto.RegionOfInterest","roi_in",n),TC(this,s,a);e:{try{const o=new nZe(this.confidenceMasks,this.categoryMask,this.qualityScores);if(!this.j){var l=o;break e}this.j(o)}finally{RDe(this)}l=void 0}return l}m(){var s=new W2;Hg(s,"image_in"),Hg(s,"roi_in"),Hg(s,"norm_rect_in");const t=new G2;b3(t,Jes,this.h);const n=new Qw;O2(n,2,"mediapipe.tasks.vision.interactive_segmenter.InteractiveSegmenterGraphV2"),tg(n,"IMAGE:image_in"),tg(n,"ROI:roi_in"),tg(n,"NORM_RECT:norm_rect_in"),n.o(t),Ik(s,n),LDe(this,s),this.outputConfidenceMasks&&(nm(s,"confidence_masks"),gh(n,"CONFIDENCE_MASKS:confidence_masks"),jW(this,"confidence_masks"),this.g.aa("confidence_masks",(r,a)=>{this.confidenceMasks=r.map(i=>kW(this,i,!0,!this.j)),qo(this,a)}),this.g.attachEmptyPacketListener("confidence_masks",r=>{this.confidenceMasks=[],qo(this,r)})),this.outputCategoryMask&&(nm(s,"category_mask"),gh(n,"CATEGORY_MASK:category_mask"),jW(this,"category_mask"),this.g.Z("category_mask",(r,a)=>{this.categoryMask=kW(this,r,!1,!this.j),qo(this,a)}),this.g.attachEmptyPacketListener("category_mask",r=>{this.categoryMask=void 0,qo(this,r)})),nm(s,"quality_scores"),gh(n,"QUALITY_SCORES:quality_scores"),this.g.attachFloatVectorListener("quality_scores",(r,a)=>{this.qualityScores=r,qo(this,a)}),this.g.attachEmptyPacketListener("quality_scores",r=>{this.categoryMask=void 0,qo(this,r)}),s=s.g(),this.setGraph(new Uint8Array(s),!0)}};i5.prototype.segment=i5.prototype.segment,i5.prototype.setOptions=i5.prototype.o,i5.createFromModelPath=function(s,t){return Mh(i5,s,{baseOptions:{modelAssetPath:t}})},i5.createFromModelBuffer=function(s,t){return Mh(i5,s,{baseOptions:{modelAssetBuffer:t}})},i5.createFromOptions=function(s,t){return Mh(i5,s,t)};var mN=class extends z2{constructor(s,t){super(new EC(s,t),"input_frame_gpu","norm_rect",!1),this.j={detections:[]},Jl(s=this.h=new tts,0,1,t=new Mx)}get baseOptions(){return Vh(this.h,Mx,1)}set baseOptions(s){Jl(this.h,0,1,s)}o(s){return s.displayNamesLocale!==void 0?sf(this.h,2,Uie(s.displayNamesLocale)):"displayNamesLocale"in s&&sf(this.h,2),s.maxResults!==void 0?jT(this.h,3,s.maxResults):"maxResults"in s&&sf(this.h,3),s.scoreThreshold!==void 0?Cl(this.h,4,s.scoreThreshold):"scoreThreshold"in s&&sf(this.h,4),s.categoryAllowlist!==void 0?aPe(this.h,5,s.categoryAllowlist):"categoryAllowlist"in s&&sf(this.h,5),s.categoryDenylist!==void 0?aPe(this.h,6,s.categoryDenylist):"categoryDenylist"in s&&sf(this.h,6),this.l(s)}F(s,t){return this.j={detections:[]},TC(this,s,t),this.j}G(s,t,n){return this.j={detections:[]},w3(this,s,n,t),this.j}m(){var s=new W2;Hg(s,"input_frame_gpu"),Hg(s,"norm_rect"),nm(s,"detections");const t=new G2;b3(t,KVn,this.h);const n=new Qw;O2(n,2,"mediapipe.tasks.vision.ObjectDetectorGraph"),tg(n,"IMAGE:input_frame_gpu"),tg(n,"NORM_RECT:norm_rect"),gh(n,"DETECTIONS:detections"),n.o(t),Ik(s,n),this.g.attachProtoVectorListener("detections",(r,a)=>{for(const i of r)r=Pes(i),this.j.detections.push(rts(r));qo(this,a)}),this.g.attachEmptyPacketListener("detections",r=>{qo(this,r)}),s=s.g(),this.setGraph(new Uint8Array(s),!0)}};mN.prototype.detectForVideo=mN.prototype.G,mN.prototype.detect=mN.prototype.F,mN.prototype.setOptions=mN.prototype.o,mN.createFromModelPath=async function(s,t){return Mh(mN,s,{baseOptions:{modelAssetPath:t}})},mN.createFromModelBuffer=function(s,t){return Mh(mN,s,{baseOptions:{modelAssetBuffer:t}})},mN.createFromOptions=function(s,t){return Mh(mN,s,t)};var rZe=class{constructor(s,t,n){this.landmarks=s,this.worldLandmarks=t,this.segmentationMasks=n}close(){var s;(s=this.segmentationMasks)==null||s.forEach(t=>{t.close()})}};function O5t(s){s.landmarks=[],s.worldLandmarks=[],s.segmentationMasks=void 0}function z5t(s){try{const t=new rZe(s.landmarks,s.worldLandmarks,s.segmentationMasks);if(!s.u)return t;s.u(t)}finally{RDe(s)}}rZe.prototype.close=rZe.prototype.close;var jj=class extends z2{constructor(s,t){super(new EC(s,t),"image_in","norm_rect",!1),this.landmarks=[],this.worldLandmarks=[],this.outputSegmentationMasks=!1,Jl(s=this.h=new sts,0,1,t=new Mx),this.A=new Wes,Jl(this.h,0,3,this.A),this.j=new Ges,Jl(this.h,0,2,this.j),jT(this.j,4,1),Cl(this.j,2,.5),Cl(this.A,2,.5),Cl(this.h,4,.5)}get baseOptions(){return Vh(this.h,Mx,1)}set baseOptions(s){Jl(this.h,0,1,s)}o(s){return"numPoses"in s&&jT(this.j,4,s.numPoses??1),"minPoseDetectionConfidence"in s&&Cl(this.j,2,s.minPoseDetectionConfidence??.5),"minTrackingConfidence"in s&&Cl(this.h,4,s.minTrackingConfidence??.5),"minPosePresenceConfidence"in s&&Cl(this.A,2,s.minPosePresenceConfidence??.5),"outputSegmentationMasks"in s&&(this.outputSegmentationMasks=s.outputSegmentationMasks??!1),this.l(s)}F(s,t,n){const r=typeof t!="function"?t:{};return this.u=typeof t=="function"?t:n,O5t(this),TC(this,s,r),z5t(this)}G(s,t,n,r){const a=typeof n!="function"?n:{};return this.u=typeof n=="function"?n:r,O5t(this),w3(this,s,a,t),z5t(this)}m(){var s=new W2;Hg(s,"image_in"),Hg(s,"norm_rect"),nm(s,"normalized_landmarks"),nm(s,"world_landmarks"),nm(s,"segmentation_masks");const t=new G2;b3(t,YVn,this.h);const n=new Qw;O2(n,2,"mediapipe.tasks.vision.pose_landmarker.PoseLandmarkerGraph"),tg(n,"IMAGE:image_in"),tg(n,"NORM_RECT:norm_rect"),gh(n,"NORM_LANDMARKS:normalized_landmarks"),gh(n,"WORLD_LANDMARKS:world_landmarks"),n.o(t),Ik(s,n),LDe(this,s),this.g.attachProtoVectorListener("normalized_landmarks",(r,a)=>{this.landmarks=[];for(const i of r)r=Hie(i),this.landmarks.push(IDe(r));qo(this,a)}),this.g.attachEmptyPacketListener("normalized_landmarks",r=>{this.landmarks=[],qo(this,r)}),this.g.attachProtoVectorListener("world_landmarks",(r,a)=>{this.worldLandmarks=[];for(const i of r)r=FV(i),this.worldLandmarks.push(nte(r));qo(this,a)}),this.g.attachEmptyPacketListener("world_landmarks",r=>{this.worldLandmarks=[],qo(this,r)}),this.outputSegmentationMasks&&(gh(n,"SEGMENTATION_MASK:segmentation_masks"),jW(this,"segmentation_masks"),this.g.aa("segmentation_masks",(r,a)=>{this.segmentationMasks=r.map(i=>kW(this,i,!0,!this.u)),qo(this,a)}),this.g.attachEmptyPacketListener("segmentation_masks",r=>{this.segmentationMasks=[],qo(this,r)})),s=s.g(),this.setGraph(new Uint8Array(s),!0)}};jj.prototype.detectForVideo=jj.prototype.G,jj.prototype.detect=jj.prototype.F,jj.prototype.setOptions=jj.prototype.o,jj.createFromModelPath=function(s,t){return Mh(jj,s,{baseOptions:{modelAssetPath:t}})},jj.createFromModelBuffer=function(s,t){return Mh(jj,s,{baseOptions:{modelAssetBuffer:t}})},jj.createFromOptions=function(s,t){return Mh(jj,s,t)},jj.POSE_CONNECTIONS=vts;let S8=null,AQ=null;async function rHn(){return S8||AQ||(AQ=(async()=>{const s=await kU.forVisionTasks("https://cdn.jsdelivr.net/npm/@mediapipe/tasks-vision@latest/wasm");return S8=await n_.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}),S8})(),AQ)}function aHn(s,t,n,r,a){const i=new Float32Array(s.length);for(let l=0;l=0&&(o-=s[c+u]);const m=Math.min(h,n-1)-Math.max(u+1,0)+1;i[c+d]=o/m}}for(let l=0;l=0&&(o-=i[d*n+l]);const h=Math.min(u,r-1)-Math.max(d+1,0)+1;t[c*n+l]=o/h}}}function iHn(){S8&&(S8.close(),S8=null,AQ=null)}const oHn=1280,lHn=720;function cHn(s,t){const n=j.useRef(null),r=j.useRef(null),a=j.useRef(null),i=j.useRef(0),l=j.useRef(t),[o,c]=j.useState(null),[d,u]=j.useState(!1),[h,m]=j.useState(null);l.current=t;const f=t.type!=="none"&&s!==null;return j.useEffect(()=>{if(t.type==="image"&&t.imageUrl){const g=new Image;g.crossOrigin="anonymous",g.src=t.imageUrl,g.onload=()=>{a.current=g},g.onerror=()=>{a.current=null}}else t.type!=="image"&&(a.current=null)},[t.type,t.imageUrl]),j.useEffect(()=>{if(!f||!s){r.current&&(r.current.srcObject=null,r.current=null);return}const g=document.createElement("video");return g.srcObject=s,g.muted=!0,g.playsInline=!0,g.autoplay=!0,g.play().catch(()=>{}),r.current=g,()=>{g.srcObject=null,r.current=null}},[f,s]),j.useEffect(()=>{if(!f){c(null),m(null);return}let g=!1,x=null,y=null;const v=async()=>{u(!0),m(null);try{const w=await rHn();if(g)return;u(!1);const S=r.current;if(!S||(await new Promise(ts=>{if(S.videoWidth>0)return ts();S.onloadedmetadata=()=>ts(),setTimeout(ts,2e3)}),g))return;const C=S.videoWidth||640,E=S.videoHeight||480,I=Math.max(C,E),P=Math.min(C,E),R=Math.min(1,oHn/I,lHn/P),D=Math.max(2,Math.round(C*R/2)*2),O=Math.max(2,Math.round(E*R/2)*2),W=!xJt().canRunVirtualBg,G=(W?192:256)/Math.max(D,O),Y=Math.max(2,Math.round(D*G)),X=Math.max(2,Math.round(O*G)),ae=W?90:55,ie=W?24:30,ne=n.current;if(!ne)return;ne.width=D,ne.height=O;const te=ne.getContext("2d",{alpha:!1}),J=document.createElement("canvas");J.width=D,J.height=O;const ce=J.getContext("2d"),_e=document.createElement("canvas");_e.width=Math.max(2,Math.round(D/2)),_e.height=Math.max(2,Math.round(O/2));const he=_e.getContext("2d",{alpha:!1}),ue=document.createElement("canvas");ue.width=Y,ue.height=X;const ve=ue.getContext("2d",{alpha:!1}),Ee=document.createElement("canvas");Ee.width=Y,Ee.height=X;const Se=Ee.getContext("2d"),Le=Se.createImageData(Y,X),Fe=Le.data;for(let ts=0;tske.addTrack(ts)),g||c(ke);const je=new Float32Array(Y*X),Ae=new Float32Array(Y*X),Ce=new Float32Array(Y*X);let qe=!1,ze=!1;const $e=2,ct=.4;let Xe=0;const it=(ts,ys)=>{ve.drawImage(ts,0,0,Y,X);const Ft=w.segmentForVideo(ue,ys).confidenceMasks;if(!(!Ft||Ft.length===0)){Ae.fill(0);for(let rs=1;rs1?1:gs}}for(const rs of Ft)rs.close();if(aHn(Ae,je,Y,X,$e),qe)for(let rs=0;rs=1?255:Xs*255|0}Se.putImageData(Le,0,0),ze=!0}},at=ts=>{const ys=l.current;if(ys.type==="blur"){const Bt=Math.max(2,Math.round((ys.blurRadius??15)/2));he.filter=`blur(${Bt}px)`,he.drawImage(ts,0,0,_e.width,_e.height),he.filter="none",te.drawImage(_e,0,0,D,O)}else if(ys.type==="image"&&a.current){const Bt=a.current,Ft=Bt.width/Bt.height,rs=D/O;let St=0,Xs=0,vt=Bt.width,gs=Bt.height;Ft>rs?(vt=Bt.height*rs,St=(Bt.width-vt)/2):(gs=Bt.width/rs,Xs=(Bt.height-gs)/2),te.drawImage(Bt,St,Xs,vt,gs,0,0,D,O)}else te.fillStyle="#000",te.fillRect(0,0,D,O)},Ke=()=>{if(g||!r.current)return;const ts=r.current;if(ts.readyState<2){qt(ts);return}try{const ys=performance.now();ys-Xe>=ae&&(Xe=ys,it(ts,ys)),ze?(at(ts),ce.globalCompositeOperation="source-over",ce.clearRect(0,0,D,O),ce.drawImage(ts,0,0,D,O),ce.globalCompositeOperation="destination-in",ce.drawImage(Ee,0,0,D,O),ce.globalCompositeOperation="source-over",l.current.mirror?(te.save(),te.translate(D,0),te.scale(-1,1),te.drawImage(J,0,0),te.restore()):te.drawImage(J,0,0)):te.drawImage(ts,0,0,D,O)}catch{try{te.drawImage(ts,0,0,D,O)}catch{}}qt(ts)},nt=typeof S.requestVideoFrameCallback=="function",xt="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{clearInterval(id);id=null}}",rt=new Blob([xt],{type:"application/javascript"});y=URL.createObjectURL(rt),x=new Worker(y),x.onmessage=()=>{g||!document.hidden||Ke()};const Yt=()=>{x&&(document.hidden?x.postMessage({type:"start",fps:ie}):(x.postMessage({type:"stop"}),qt(r.current)))};document.addEventListener("visibilitychange",Yt);const qt=ts=>{g||document.hidden||(nt?ts.requestVideoFrameCallback(()=>Ke()):i.current=requestAnimationFrame(Ke))};qt(S),b=()=>{document.removeEventListener("visibilitychange",Yt)}}catch(w){console.error("[useVirtualBackground] init error:",w),g||(u(!1),m(w.message||"Failed to initialize virtual background"))}};let b=null;return v(),()=>{g=!0,i.current&&cancelAnimationFrame(i.current),b==null||b(),x&&(x.postMessage({type:"stop"}),x.terminate(),x=null),y&&URL.revokeObjectURL(y),c(null)}},[f,s]),j.useEffect(()=>()=>{iHn()},[]),{canvasRef:n,compositedStream:o,isLoading:d,isActive:f,error:h}}function BT({maxDurationSeconds:s=600,onRecordingComplete:t,onError:n,onRecordingStateChange:r,showBackgroundPicker:a=!0,className:i,teleprompterContent:l}){const o=j.useRef(null),c=j.useRef(null),d=j.useRef(null),[u,h]=j.useState(null),m=j.useRef([]),f=j.useRef(null),g=j.useRef(null),x=j.useRef(null),y=j.useRef(null),v=$K(),[b,w]=j.useState("camera"),S=j.useRef(null),C=j.useRef(null),E=j.useRef(null),I=j.useRef(null),P=j.useRef(null),R=j.useRef(null),[D,O]=j.useState(!0),[U,W]=j.useState(!0),[V,G]=j.useState(null),[Y,X]=j.useState(!1),[ae,ie]=j.useState(!1),[ne,te]=j.useState(null),[J,ce]=j.useState(null),[_e,he]=j.useState(0),[ue,ve]=j.useState("user"),[Ee,Se]=j.useState(0),[Le,Fe]=j.useState(!1),[ke,Ve]=j.useState(!0),[je,Ae]=j.useState(null),[Ce,qe]=j.useState(!1),[ze,$e]=j.useState(null),ct=j.useRef(null),[Xe,it]=j.useState(()=>{try{const hn=localStorage.getItem("video-bg-config");if(hn)return JSON.parse(hn)}catch{}return{type:"none"}});j.useEffect(()=>{try{localStorage.setItem("video-bg-config",JSON.stringify(Xe))}catch{}},[Xe]);const[at,Ke]=j.useState([]),[nt,xt]=j.useState([]),[rt,Yt]=j.useState(()=>{try{return localStorage.getItem("video-mic-id")||""}catch{return""}}),[qt,ts]=j.useState(()=>{try{return localStorage.getItem("video-cam-id")||""}catch{return""}});j.useEffect(()=>{try{localStorage.setItem("video-mic-id",rt)}catch{}},[rt]),j.useEffect(()=>{try{localStorage.setItem("video-cam-id",qt)}catch{}},[qt]),j.useEffect(()=>{var Fn,vn,xs;if(!((Fn=navigator.mediaDevices)!=null&&Fn.enumerateDevices))return;const hn=async()=>{try{const Lr=await navigator.mediaDevices.enumerateDevices();Ke(Lr.filter(Or=>Or.kind==="audioinput")),xt(Lr.filter(Or=>Or.kind==="videoinput"))}catch(Lr){console.warn("[VideoRecorder] enumerateDevices failed",Lr)}};return hn(),(xs=(vn=navigator.mediaDevices).addEventListener)==null||xs.call(vn,"devicechange",hn),()=>{var Lr,Or;return(Or=(Lr=navigator.mediaDevices).removeEventListener)==null?void 0:Or.call(Lr,"devicechange",hn)}},[V]);const{canvasRef:ys,compositedStream:Bt,isLoading:Ft,isActive:rs}=cHn(u,Xe),St=j.useRef(n);St.current=n;const Xs=j.useCallback(hn=>{O(hn)},[]),vt=j.useRef(D),gs=j.useCallback(()=>{E.current&&(cancelAnimationFrame(E.current),E.current=null),I.current&&(I.current.terminate(),I.current=null),S.current&&(S.current.getTracks().forEach(hn=>hn.stop()),S.current=null),P.current&&(P.current.getTracks().forEach(hn=>hn.stop()),P.current=null),R.current&&(R.current.srcObject=null,R.current=null)},[]),Ss=j.useCallback(async()=>{var hn;try{const Fn=await navigator.mediaDevices.getDisplayMedia({video:{width:{ideal:1920},height:{ideal:1080}},audio:!0});S.current=Fn;let vn=null;try{vn=await navigator.mediaDevices.getUserMedia({video:qt?{deviceId:{exact:qt},width:{ideal:320},height:{ideal:240}}:{width:{ideal:320},height:{ideal:240}},audio:!1})}catch{console.warn("[VideoRecorder] No webcam for PiP overlay")}let xs=null;try{xs=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0,...rt?{deviceId:{exact:rt}}:{}}}),console.log("[VideoRecorder] mic acquired for screen recording",xs.getAudioTracks().map(Nl=>Nl.label))}catch(Nl){console.warn("[VideoRecorder] No mic audio for screen recording",Nl);try{xs=await navigator.mediaDevices.getUserMedia({audio:!0})}catch{}}const Lr=Fn.getVideoTracks()[0],Or=Lr.getSettings(),ca=Or.width||1920,Jn=Or.height||1080,Sr=document.createElement("canvas");Sr.width=ca,Sr.height=Jn,C.current=Sr;const Un=Sr.getContext("2d");let ur=null;vn&&(ur=document.createElement("video"),ur.srcObject=vn,ur.muted=!0,ur.playsInline=!0,ur.autoplay=!0,await ur.play(),R.current=ur);const Pa=document.createElement("video");Pa.srcObject=Fn,Pa.muted=!0,Pa.playsInline=!0,Pa.autoplay=!0,await Pa.play();const ii=()=>{if(Un.drawImage(Pa,0,0,ca,Jn),ur&&ur.readyState>=2){const Nl=Math.round(ca*.2),Ho=Math.round(Nl*(ur.videoHeight/ur.videoWidth||.75)),ti=ca-Nl-20,Xr=Jn-Ho-20,Eo=12;Un.save(),Un.beginPath(),Un.moveTo(ti+Eo,Xr),Un.lineTo(ti+Nl-Eo,Xr),Un.quadraticCurveTo(ti+Nl,Xr,ti+Nl,Xr+Eo),Un.lineTo(ti+Nl,Xr+Ho-Eo),Un.quadraticCurveTo(ti+Nl,Xr+Ho,ti+Nl-Eo,Xr+Ho),Un.lineTo(ti+Eo,Xr+Ho),Un.quadraticCurveTo(ti,Xr+Ho,ti,Xr+Ho-Eo),Un.lineTo(ti,Xr+Eo),Un.quadraticCurveTo(ti,Xr,ti+Eo,Xr),Un.closePath(),Un.clip(),Un.translate(ti+Nl,Xr),Un.scale(-1,1),Un.drawImage(ur,0,0,Nl,Ho),Un.restore(),Un.strokeStyle="rgba(255,255,255,0.6)",Un.lineWidth=2,Un.beginPath(),Un.moveTo(ti+Eo,Xr),Un.lineTo(ti+Nl-Eo,Xr),Un.quadraticCurveTo(ti+Nl,Xr,ti+Nl,Xr+Eo),Un.lineTo(ti+Nl,Xr+Ho-Eo),Un.quadraticCurveTo(ti+Nl,Xr+Ho,ti+Nl-Eo,Xr+Ho),Un.lineTo(ti+Eo,Xr+Ho),Un.quadraticCurveTo(ti,Xr+Ho,ti,Xr+Ho-Eo),Un.lineTo(ti,Xr+Eo),Un.quadraticCurveTo(ti,Xr,ti+Eo,Xr),Un.closePath(),Un.stroke()}},$i="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}}",Rn=new Blob([$i],{type:"application/javascript"}),xa=new Worker(URL.createObjectURL(Rn));I.current=xa,xa.onmessage=()=>ii(),xa.postMessage({type:"start",fps:30}),ii();const Ya=Sr.captureStream(30),ho=[],Pc=Fn.getAudioTracks();Pc.length&&ho.push(...Pc),xs&&ho.push(...xs.getAudioTracks());const $d=new MediaStream([...Ya.getVideoTracks(),...ho]);return P.current=$d,Lr.onended=()=>{c.current&&c.current.state!=="inactive"&&c.current.stop(),gs()},$d}catch(Fn){return console.error("[VideoRecorder] Screen capture error:",Fn),Fn.name!=="NotAllowedError"&&((hn=St.current)==null||hn.call(St,"Failed to start screen capture: "+(Fn.message||"Unknown error"))),null}},[gs]),Is=j.useCallback(async()=>{var Fn,vn;W(!0),Ae(null);const hn=v&&D;console.log("[VideoRecorder] initCamera start",{isMobile:v,usePortraitMode:D,shouldBePortrait:hn,facingMode:ue});try{if(!navigator.mediaDevices||!navigator.mediaDevices.getUserMedia)throw new Error("Camera not available in this browser or context. Try opening in a new tab.");d.current&&(console.log("[VideoRecorder] stopping existing stream"),d.current.getTracks().forEach(Un=>Un.stop()));const xs=v&&hn?{width:{ideal:720},height:{ideal:1280}}:{width:{ideal:1280},height:{ideal:720}},Lr=qt?{...xs,deviceId:{exact:qt}}:{...xs,facingMode:{ideal:ue}},Or={echoCancellation:!0,noiseSuppression:!0,...rt?{deviceId:{exact:rt}}:{}};console.log("[VideoRecorder] requesting getUserMedia",Lr);const ca=await navigator.mediaDevices.getUserMedia({video:Lr,audio:Or});if(console.log("[VideoRecorder] getUserMedia success"),ca.getVideoTracks().length===0)throw new Error("Camera stream started but no video track was provided.");d.current=ca,h(ca),G(!0);const Sr=ca.getVideoTracks()[0].getSettings();if(console.log("[VideoRecorder] Camera initialized with dimensions:",Sr.width,"x",Sr.height),o.current){const Un=o.current;Un.srcObject=ca,Un.muted=!0,Un.playsInline=!0,Un.autoplay=!0,Un.setAttribute("muted",""),Un.setAttribute("playsinline",""),Un.setAttribute("autoplay","");try{(Fn=Un.load)==null||Fn.call(Un)}catch(Pa){console.warn("[VideoRecorder] videoEl.load failed",Pa)}const ur=async()=>{try{return await Un.play(),console.log("[VideoRecorder] preview play ok"),qe(!1),setTimeout(()=>{console.debug("[VideoRecorder] preview metrics",{readyState:Un.readyState,videoWidth:Un.videoWidth,videoHeight:Un.videoHeight})},300),!0}catch(Pa){return console.warn("[VideoRecorder] preview play blocked",Pa),qe(!0),!1}};await new Promise(Pa=>{let ii=!1;const $i=()=>{ii||(ii=!0,Pa())},Rn=()=>{ur().finally($i)};Un.onloadedmetadata=Rn,Un.onloadeddata=Rn,setTimeout($i,1500)})}try{g.current=new AudioContext;const Un=g.current.createMediaStreamSource(ca);x.current=g.current.createAnalyser(),x.current.fftSize=256,Un.connect(x.current);const ur=()=>{if(x.current){const Pa=new Uint8Array(x.current.frequencyBinCount);x.current.getByteFrequencyData(Pa);const ii=Pa.reduce(($i,Rn)=>$i+Rn)/Pa.length;Se(Math.min(100,ii/128*100))}y.current=requestAnimationFrame(ur)};ur()}catch(Un){console.warn("Audio context not available:",Un)}}catch(xs){console.error("Camera initialization error:",xs),G(!1);let Lr="Failed to access camera or microphone.";xs.name==="NotAllowedError"?Lr="Camera permission denied. Please allow camera access in your browser settings.":xs.name==="NotFoundError"?Lr="No camera found. Please connect a camera and try again.":xs.name==="NotReadableError"?Lr="Camera is in use by another application. Please close other apps using the camera.":xs.message&&(Lr=xs.message),Ae(Lr),(vn=St.current)==null||vn.call(St,Lr)}finally{W(!1)}},[ue,v,D,rt,qt]);j.useEffect(()=>{vt.current!==D&&V&&!Y&&!J&&(vt.current=D,Is())},[D,V,Y,J,Is]),j.useEffect(()=>(Is(),()=>{d.current&&d.current.getTracks().forEach(hn=>hn.stop()),f.current&&clearInterval(f.current),y.current&&cancelAnimationFrame(y.current),g.current&&g.current.close(),ct.current&&clearInterval(ct.current),J&&URL.revokeObjectURL(J),gs()}),[Is,J]),j.useEffect(()=>{if(U||V!==!0||J)return;const hn=d.current,Fn=o.current;!hn||!Fn||rs||(Fn.srcObject!==hn&&(Fn.srcObject=hn,Fn.muted=!0,Fn.playsInline=!0,Fn.autoplay=!0,Fn.setAttribute("muted",""),Fn.setAttribute("playsinline",""),Fn.setAttribute("autoplay","")),Fn.play().then(()=>qe(!1)).catch(vn=>{qe(!0),console.warn("Live preview play blocked on mount:",vn)}))},[V,U,J,rs]),j.useEffect(()=>{r==null||r(Y)},[Y,r]);const Ys=j.useCallback(async()=>{if(J)return;const hn=o.current;if(hn)try{await hn.play(),qe(!1)}catch(Fn){qe(!0),console.warn("Live preview still blocked (needs user gesture):",Fn)}},[J]),cs=j.useCallback(()=>{c.current&&c.current.state!=="inactive"&&c.current.stop(),f.current&&(clearInterval(f.current),f.current=null),gs(),X(!1),ie(!1)},[gs]),js=j.useCallback(async()=>{let hn=null;if(b==="screen"){if(hn=await Ss(),!hn)return}else hn=rs&&Bt?Bt:d.current;if(!hn)return;Ys(),m.current=[],he(0);const vn=["video/webm;codecs=vp9,opus","video/webm;codecs=vp8,opus","video/webm;codecs=vp9","video/webm;codecs=vp8","video/webm","video/mp4"].find(Lr=>MediaRecorder.isTypeSupported(Lr)),xs=new MediaRecorder(hn,vn?{mimeType:vn,videoBitsPerSecond:b==="screen"?4e6:25e5,audioBitsPerSecond:128e3}:{videoBitsPerSecond:b==="screen"?4e6:25e5,audioBitsPerSecond:128e3});xs.ondataavailable=Lr=>{Lr.data.size>0&&m.current.push(Lr.data)},xs.onstop=()=>{var Jn;const Lr=xs.mimeType||vn||((Jn=m.current[0])==null?void 0:Jn.type)||"video/webm",Or=new Blob(m.current,{type:Lr});te(Or);const ca=URL.createObjectURL(Or);ce(ca)},c.current=xs,xs.start(1e3),X(!0),f.current=setInterval(()=>{he(Lr=>Lr>=s-1?(cs(),s):Lr+1)},1e3)},[Ys,s,cs,rs,Bt,b,Ss]),kn=j.useCallback(()=>{ct.current&&(clearInterval(ct.current),ct.current=null),$e(3);let hn=3;ct.current=setInterval(()=>{hn-=1,hn<=0?(ct.current&&clearInterval(ct.current),ct.current=null,$e(null),js()):$e(hn)},1e3)},[js]),Ws=j.useCallback(()=>{c.current&&c.current.state==="recording"&&(c.current.pause(),ie(!0),f.current&&clearInterval(f.current))},[]),On=j.useCallback(()=>{c.current&&c.current.state==="paused"&&(c.current.resume(),ie(!1),f.current=setInterval(()=>{he(hn=>hn>=s-1?(cs(),s):hn+1)},1e3))},[s,cs]),ds=j.useCallback(()=>{J&&URL.revokeObjectURL(J),te(null),ce(null),he(0),Fe(!1),Ve(!0),o.current&&d.current&&!rs&&(o.current.srcObject=d.current,o.current.muted=!0,Ys())},[Ys,J,rs]),gn=j.useCallback(()=>{ve(hn=>hn==="user"?"environment":"user")},[]),As=j.useCallback(()=>{ne&&t(ne,_e)},[ne,_e,t]),hr=j.useCallback(()=>{o.current&&J&&(Le?o.current.pause():(Ve(!1),o.current.muted=!1,o.current.play()),Fe(!Le))},[J,Le]);j.useEffect(()=>{if(!J)return;const hn=o.current;if(!hn)return;Ve(!1),hn.pause(),hn.removeAttribute("src"),hn.srcObject=null,hn.load(),hn.src=J,hn.currentTime=0,hn.playsInline=!0,hn.muted=!1,hn.onended=()=>Fe(!1);const Fn=()=>{var Lr;const vn=hn.error,xs=vn?`Recorded video failed to play (code ${vn.code}). Likely unsupported format/codec in this browser.`:"Recorded video failed to play.";console.warn("[VideoRecorder] recorded playback error",vn),(Lr=St.current)==null||Lr.call(St,xs)};return hn.addEventListener("error",Fn),hn.load(),()=>{hn.removeEventListener("error",Fn)}},[J]);const Er=hn=>{const Fn=Math.floor(hn/60),vn=hn%60;return`${Fn}:${vn.toString().padStart(2,"0")}`},qn=b==="screen"?"aspect-video":v&&D?"aspect-[9/16]":"aspect-video";return U?e.jsx("div",{className:Pt("flex items-center justify-center bg-black rounded-lg",qn,i),children:e.jsxs("div",{className:"text-center text-white",children:[e.jsx(kt,{className:"h-12 w-12 animate-spin mx-auto mb-4"}),e.jsx("p",{children:"Initializing camera..."})]})}):V===!1?e.jsx("div",{className:Pt("flex items-center justify-center bg-black rounded-lg",qn,i),children:e.jsxs("div",{className:"text-center text-white p-8 max-w-md",children:[e.jsx(ll,{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:je||"Please allow camera and microphone access to record videos."}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs($,{onClick:()=>Is(),variant:"secondary",className:"w-full",children:[e.jsx(ro,{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:Pt("flex flex-col gap-2",i),children:[!Y&&!J&&e.jsxs("div",{className:"flex items-center justify-center gap-1 p-1 bg-muted rounded-lg",children:[e.jsxs($,{variant:b==="camera"?"default":"ghost",size:"sm",className:"gap-1.5 flex-1",onClick:()=>w("camera"),children:[e.jsx(Cx,{className:"h-4 w-4"}),"Camera"]}),e.jsxs($,{variant:b==="screen"?"default":"ghost",size:"sm",className:"gap-1.5 flex-1",onClick:()=>w("screen"),children:[e.jsx(Jz,{className:"h-4 w-4"}),"Screen"]})]}),a&&b==="camera"&&!Y&&!J&&e.jsx(bqn,{value:Xe,onChange:it,isLoading:Ft,disabled:Y}),!Y&&!J&&(at.length>0||nt.length>0)&&e.jsxs("div",{className:"flex flex-wrap items-center gap-3 px-3 py-2 bg-muted/40 rounded-lg",children:[at.length>0&&e.jsxs("div",{className:"flex items-center gap-2 flex-1 min-w-[200px]",children:[e.jsx(Qz,{className:"h-4 w-4 text-muted-foreground shrink-0"}),e.jsxs(ms,{value:rt||"default",onValueChange:hn=>Yt(hn==="default"?"":hn),children:[e.jsx(us,{className:"h-8 text-xs",children:e.jsx(fs,{placeholder:"Default microphone"})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"default",children:"Default microphone"}),at.map(hn=>e.jsx(Ge,{value:hn.deviceId,children:hn.label||`Microphone ${hn.deviceId.slice(0,6)}`},hn.deviceId))]})]})]}),nt.length>1&&b==="camera"&&e.jsxs("div",{className:"flex items-center gap-2 flex-1 min-w-[200px]",children:[e.jsx(Cx,{className:"h-4 w-4 text-muted-foreground shrink-0"}),e.jsxs(ms,{value:qt||"default",onValueChange:hn=>ts(hn==="default"?"":hn),children:[e.jsx(us,{className:"h-8 text-xs",children:e.jsx(fs,{placeholder:"Default camera"})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"default",children:"Default camera"}),nt.map(hn=>e.jsx(Ge,{value:hn.deviceId,children:hn.label||`Camera ${hn.deviceId.slice(0,6)}`},hn.deviceId))]})]})]})]}),b==="camera"&&v&&!Y&&!J&&e.jsxs("div",{className:"flex items-center justify-center gap-3 py-2 bg-muted/50 rounded-lg",children:[e.jsx(sk,{className:Pt("h-4 w-4",D?"text-muted-foreground":"text-primary")}),e.jsx(ee,{htmlFor:"orientation-toggle",className:"text-sm text-muted-foreground",children:"Landscape"}),e.jsx(Sn,{id:"orientation-toggle",checked:D,onCheckedChange:Xs}),e.jsx(ee,{htmlFor:"orientation-toggle",className:"text-sm text-muted-foreground",children:"Portrait"}),e.jsx(_1,{className:Pt("h-4 w-4",D?"text-primary":"text-muted-foreground")})]}),b==="screen"&&!Y&&!J&&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(Jz,{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:Pt("relative bg-black rounded-lg overflow-hidden"),onPointerDown:()=>{Ys()},children:[e.jsx("video",{ref:o,src:J??void 0,className:Pt("w-full bg-black",D&&!J?"object-contain":"object-cover",qn,!J&&ue==="user"!==(Xe.mirror??!1)&&"scale-x-[-1]",rs&&!J&&"hidden"),playsInline:!0,controls:!!J,muted:J?ke:!0,autoPlay:!J},J??"live"),rs&&!J&&e.jsx("canvas",{ref:ys,className:Pt("w-full bg-black",D?"object-contain":"object-cover",qn,ue==="user"!==(Xe.mirror??!1)&&"scale-x-[-1]")}),rs&&Ft&&!J&&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(kt,{className:"h-8 w-8 animate-spin mx-auto mb-2"}),e.jsx("p",{className:"text-sm",children:"Loading virtual background…"})]})}),!J&&Ce&&e.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-black/40",children:e.jsx($,{type:"button",variant:"secondary",onClick:()=>void Ys(),className:"bg-white/20 hover:bg-white/30 text-white",children:"Tap to enable preview"})}),l&&!J&&e.jsx("div",{className:"absolute inset-0 pointer-events-none",children:l}),ze!==null&&!J&&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:ze},ze),e.jsx("p",{className:"text-white/80 text-lg font-medium drop-shadow-md",children:"Get ready…"})]})}),Y&&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:Pt("w-3 h-3 rounded-full",ae?"bg-yellow-500":"bg-red-500 animate-pulse")}),e.jsxs("span",{className:"text-white text-sm font-medium",children:[Er(_e)," / ",Er(s)]})]}),Y&&e.jsx("div",{className:"absolute top-0 left-0 right-0",children:e.jsx(Yi,{value:_e/s*100,className:"h-1 rounded-none"})}),!J&&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(Qz,{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:`${Ee}%`}})})]}),e.jsx("div",{className:"absolute bottom-4 left-0 right-0 flex justify-center gap-3 px-4",children:J?e.jsxs(e.Fragment,{children:[e.jsxs($,{variant:"secondary",size:"lg",className:"bg-white/20 hover:bg-white/30 text-white",onClick:ds,children:[e.jsx(ro,{className:"h-5 w-5 mr-2"}),"Re-record"]}),e.jsx($,{variant:"secondary",size:"icon",className:"h-12 w-12 rounded-full bg-white/20 hover:bg-white/30 text-white",onClick:hr,children:Le?e.jsx(Tv,{className:"h-5 w-5"}):e.jsx(Bu,{className:"h-5 w-5"})}),e.jsxs($,{size:"lg",className:"bg-green-500 hover:bg-green-600 text-white",onClick:As,children:[e.jsx(la,{className:"h-5 w-5 mr-2"}),"Use This Video"]})]}):e.jsxs(e.Fragment,{children:[b==="camera"?e.jsx($,{variant:"secondary",size:"icon",className:"h-12 w-12 rounded-full bg-white/20 hover:bg-white/30 text-white",onClick:gn,disabled:Y||ze!==null,children:e.jsx(Ex,{className:"h-5 w-5"})}):e.jsx("div",{className:"h-12 w-12"}),!Y&&ze===null?e.jsx($,{size:"icon",className:"h-16 w-16 rounded-full bg-red-500 hover:bg-red-600 text-white",onClick:b==="screen"?js:kn,children:b==="screen"?e.jsx(Jz,{className:"h-6 w-6"}):e.jsx(ua,{className:"h-6 w-6"})}):e.jsxs(e.Fragment,{children:[e.jsx($,{size:"icon",className:"h-12 w-12 rounded-full bg-white/20 hover:bg-white/30 text-white",onClick:ae?On:Ws,children:ae?e.jsx(Bu,{className:"h-5 w-5"}):e.jsx(Tv,{className:"h-5 w-5"})}),e.jsx($,{size:"icon",className:"h-16 w-16 rounded-full bg-red-500 hover:bg-red-600 text-white",onClick:cs,children:e.jsx(C_,{className:"h-6 w-6 fill-current"})})]}),e.jsx("div",{className:"h-12 w-12"})]})})]})]})}function dHn({open:s,onOpenChange:t,onUploaded:n}){const{user:r}=vs(),{toast:a}=Bi(),[i,l]=j.useState(!1),o=async(c,d)=>{if(r){l(!0);try{const u=c.type.includes("mp4")?"mp4":"webm",h=`${r.id}/${crypto.randomUUID()}.${u}`,{error:m}=await q.storage.from("cma-videos").upload(h,c,{contentType:c.type||"video/webm",upsert:!1});if(m)throw m;const{data:f,error:g}=await q.storage.from("cma-videos").createSignedUrl(h,60*60*24*365*5);if(g||!(f!=null&&f.signedUrl))throw g||new Error("Could not sign video URL");n(f.signedUrl,Math.round(d)),a({title:"Video added to your CMA"}),t(!1)}catch(u){a({title:"Upload failed",description:u==null?void 0:u.message,variant:"destructive"})}finally{l(!1)}}};return e.jsx(zs,{open:s,onOpenChange:c=>!i&&t(c),children:e.jsxs(Os,{className:"max-w-2xl",children:[e.jsxs(Us,{children:[e.jsx(Bs,{children:"Record a personal message"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"A 30-second hello goes a long way. Welcome your client, explain the price, and invite their reply."})]}),i?e.jsxs("div",{className:"py-12 flex flex-col items-center gap-3",children:[e.jsx(kt,{className:"w-8 h-8 animate-spin text-primary"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Uploading your video…"})]}):e.jsx(BT,{maxDurationSeconds:180,onRecordingComplete:o})]})})}function uHn({value:s,onChange:t}){const{user:n}=vs(),[r,a]=j.useState(!1);return e.jsxs(Ne,{children:[e.jsxs(Ct,{children:[e.jsxs(At,{className:"text-base flex items-center gap-2",children:[e.jsx(ua,{className:"w-4 h-4"}),"Personal Video Message"]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Adds the human touch your client will remember. Plays right at the top of the CMA."})]}),e.jsxs(Ie,{className:"space-y-3",children:[s!=null&&s.url?e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"relative rounded-lg overflow-hidden bg-black aspect-video group",children:[e.jsx("video",{src:s.url,poster:s.thumb,controls:!0,className:"w-full h-full object-cover"}),e.jsx("button",{className:"absolute top-2 right-2 bg-black/60 text-white rounded-full p-1.5 opacity-0 group-hover:opacity-100 transition-opacity",onClick:()=>t(null),"aria-label":"Remove video",type:"button",children:e.jsx(gr,{className:"w-3.5 h-3.5"})})]}),e.jsxs("p",{className:"text-xs text-emerald-700 flex items-center gap-1",children:[e.jsx(Bu,{className:"w-3 h-3"})," Video attached"]})]}):e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsx(o9,{userId:n==null?void 0:n.id,triggerLabel:"Pick from Library",triggerVariant:"outline",triggerSize:"default",triggerClassName:"w-full justify-center gap-2",onSelect:()=>{},onSelectVideo:i=>t({url:i.playback_url,thumb:i.thumbnail_url,label:i.title||i.recipient_name})}),e.jsxs($,{variant:"outline",onClick:()=>a(!0),className:"gap-2",children:[e.jsx(ua,{className:"w-4 h-4"}),"Record New"]})]}),e.jsx(dHn,{open:r,onOpenChange:a,onUploaded:i=>t({url:i,label:"Personal message"})})]})]})}function OS(s){const t=Number(String(s).replace(/[^0-9.]/g,""));return Number.isFinite(t)&&t>0?t:null}function hHn({open:s,onOpenChange:t,subject:n,onSave:r,isSaving:a}){const[i,l]=j.useState({bedrooms:"",bathrooms:"",sqft:"",yearBuilt:"",propertyType:"",propertySubType:""});j.useEffect(()=>{s&&l({bedrooms:(n==null?void 0:n.bedrooms)!=null?String(n.bedrooms):"",bathrooms:(n==null?void 0:n.bathrooms)!=null?String(n.bathrooms):"",sqft:(n==null?void 0:n.sqft)!=null?String(n.sqft):"",yearBuilt:(n==null?void 0:n.yearBuilt)!=null?String(n.yearBuilt):"",propertyType:(n==null?void 0:n.propertyType)||"Residential",propertySubType:(n==null?void 0:n.propertySubType)||"Single Family"})},[s,n]);const o=async()=>{await r({bedrooms:OS(i.bedrooms),bathrooms:OS(i.bathrooms),sqft:OS(i.sqft),yearBuilt:OS(i.yearBuilt),propertyType:i.propertyType||null,propertySubType:i.propertySubType||null}),t(!1)};return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Os,{className:"max-w-lg",children:[e.jsx(Us,{children:e.jsx(Bs,{children:"Fill in the subject property basics"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"When the MLS feed does not return the home details, add the basics here and LevelUp will keep the CMA moving."}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs",children:"Beds"}),e.jsx(pe,{inputMode:"decimal",value:i.bedrooms,onChange:c=>l(d=>({...d,bedrooms:c.target.value})),placeholder:"3"})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs",children:"Baths"}),e.jsx(pe,{inputMode:"decimal",value:i.bathrooms,onChange:c=>l(d=>({...d,bathrooms:c.target.value})),placeholder:"2"})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs",children:"Sq Ft"}),e.jsx(pe,{inputMode:"numeric",value:i.sqft,onChange:c=>l(d=>({...d,sqft:c.target.value})),placeholder:"1850"})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs",children:"Year Built"}),e.jsx(pe,{inputMode:"numeric",value:i.yearBuilt,onChange:c=>l(d=>({...d,yearBuilt:c.target.value})),placeholder:"2006"})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs",children:"Property Type"}),e.jsx(pe,{value:i.propertyType,onChange:c=>l(d=>({...d,propertyType:c.target.value})),placeholder:"Residential"})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs",children:"Subtype"}),e.jsx(pe,{value:i.propertySubType,onChange:c=>l(d=>({...d,propertySubType:c.target.value})),placeholder:"Single Family"})]})]}),e.jsxs($,{className:"w-full",onClick:o,disabled:a,children:[a?e.jsx(kt,{className:"w-4 h-4 mr-2 animate-spin"}):e.jsx(tl,{className:"w-4 h-4 mr-2"}),"Save subject details"]})]})]})})}function mHn({open:s,onOpenChange:t,subject:n,onAdd:r}){const[a,i]=j.useState({address:"",city:"",state:"",status:"Closed",price:"",bedrooms:"",bathrooms:"",sqft:"",yearBuilt:""});j.useEffect(()=>{s&&i({address:"",city:(n==null?void 0:n.city)||"",state:(n==null?void 0:n.state)||"",status:"Closed",price:"",bedrooms:"",bathrooms:"",sqft:"",yearBuilt:""})},[s,n]);const l=()=>{const o=OS(a.price),c=OS(a.sqft);!a.address.trim()||!o||!c||(r({mlsNumber:`manual-${Date.now()}`,source_provider:"manual",manual:!0,selected:!0,score:100,address:a.address.trim(),city:a.city||(n==null?void 0:n.city)||"",state:(a.state||(n==null?void 0:n.state)||"").toUpperCase(),status:a.status||"Closed",price:o,soldPrice:/closed|sold/i.test(a.status)?o:null,bedrooms:OS(a.bedrooms),bathrooms:OS(a.bathrooms),sqft:c,yearBuilt:OS(a.yearBuilt),photos:[]}),t(!1))};return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Os,{className:"max-w-2xl",children:[e.jsx(Us,{children:e.jsx(Bs,{children:"Add a comparable manually"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Use this when the MLS feed misses a property or you already know the best comp. Add at least the address, price, and square footage."}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-4 gap-3",children:[e.jsxs("div",{className:"md:col-span-2",children:[e.jsx(ee,{className:"text-xs",children:"Address"}),e.jsx(pe,{value:a.address,onChange:o=>i(c=>({...c,address:o.target.value})),placeholder:"123 Comparable St"})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs",children:"City"}),e.jsx(pe,{value:a.city,onChange:o=>i(c=>({...c,city:o.target.value}))})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs",children:"State"}),e.jsx(pe,{maxLength:2,value:a.state,onChange:o=>i(c=>({...c,state:o.target.value.toUpperCase()}))})]})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-5 gap-3",children:[e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs",children:"Status"}),e.jsx(pe,{value:a.status,onChange:o=>i(c=>({...c,status:o.target.value})),placeholder:"Closed"})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs",children:"Price"}),e.jsx(pe,{inputMode:"numeric",value:a.price,onChange:o=>i(c=>({...c,price:o.target.value})),placeholder:"525000"})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs",children:"Sq Ft"}),e.jsx(pe,{inputMode:"numeric",value:a.sqft,onChange:o=>i(c=>({...c,sqft:o.target.value})),placeholder:"1800"})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs",children:"Beds"}),e.jsx(pe,{inputMode:"decimal",value:a.bedrooms,onChange:o=>i(c=>({...c,bedrooms:o.target.value})),placeholder:"3"})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs",children:"Baths"}),e.jsx(pe,{inputMode:"decimal",value:a.bathrooms,onChange:o=>i(c=>({...c,bathrooms:o.target.value})),placeholder:"2"})]})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs",children:"Year Built"}),e.jsx(pe,{className:"max-w-[180px]",inputMode:"numeric",value:a.yearBuilt,onChange:o=>i(c=>({...c,yearBuilt:o.target.value})),placeholder:"2005"})]}),e.jsxs($,{className:"w-full",onClick:l,disabled:!a.address.trim()||!OS(a.price)||!OS(a.sqft),children:[e.jsx(dn,{className:"w-4 h-4 mr-2"}),"Add comp to CMA"]})]})]})})}function fHn(){var ue,ve,Ee,Se,Le,Fe,ke;const{id:s}=Wi(),t=Qn(),{toast:n}=Bi(),{data:r,isLoading:a}=hUn(s),{data:i}=mUn(s),l=fUn(),o=xUn(),c=yUn(),{leadSite:d,isLoading:u}=ng(),[h,m]=j.useState([]),[f,g]=j.useState({sqftPct:.2,monthsBack:6,maxMiles:5,statuses:["Active","Pending","Closed"]}),[x,y]=j.useState(null),[v,b]=j.useState(!1),[w,S]=j.useState({low:"",likely:"",high:"",note:""}),[C,E]=j.useState(!1),[I,P]=j.useState(!1),[R,D]=j.useState(!1),[O,U]=j.useState(null),W=async Ve=>{var $e,ct;if(!r||!(Ve!=null&&Ve.address)||!(Ve!=null&&Ve.city)||!(Ve!=null&&Ve.state))return Ve;let je={...Ve};const Ae=async Xe=>{const{data:it,error:at}=await q.functions.invoke("cma-subject-lookup",{body:{address:Xe.address,city:Xe.city,state:Xe.state,zip:Xe.zip,latitude:Xe.latitude,longitude:Xe.longitude,leadSiteId:(d==null?void 0:d.id)??r.lead_site_id}});if(at)throw at;return(it==null?void 0:it.matches)||[]},Ce=Xe=>{const at=Xe.find(rt=>Number.isFinite(Number(rt.latitude))&&Number.isFinite(Number(rt.longitude)))||Xe[0];if(!at)return;const Ke=typeof at.match_type=="string"&&at.match_type.startsWith("nearby-"),nt=Ke&&Number.isFinite(Number(je.latitude))&&Number.isFinite(Number(je.longitude)),xt=rt=>at[rt]!==void 0&&at[rt]!==null&&at[rt]!==""&&at[rt]!==0?at[rt]:je[rt];je={...je,bedrooms:xt("bedrooms"),bathrooms:xt("bathrooms"),sqft:xt("sqft"),yearBuilt:xt("yearBuilt"),lotSize:xt("lotSize"),propertyType:xt("propertyType"),propertySubType:xt("propertySubType"),source_provider:at.source_provider??je.source_provider,match_type:at.match_type??je.match_type,matched_mls_address:Ke?at.address:je.matched_mls_address,latitude:nt?je.latitude:at.latitude??je.latitude,longitude:nt?je.longitude:at.longitude??je.longitude,mlsNumber:Ke?je.mlsNumber:at.mlsNumber??je.mlsNumber,photos:!Ke&&Array.isArray(at.photos)&&at.photos.length?at.photos:je.photos}};Ce(await Ae(je));const qe=()=>Number.isFinite(Number(je.latitude))&&Number.isFinite(Number(je.longitude));if(!qe()){const{data:Xe}=await q.from("settings").select("value").eq("key","mapbox_public_token").maybeSingle(),it=Xe==null?void 0:Xe.value;if(it){const at=encodeURIComponent(`${je.address}, ${je.city}, ${je.state} ${je.zip||""}`.trim()),nt=await(await fetch(`https://api.mapbox.com/geocoding/v5/mapbox.places/${at}.json?access_token=${it}&limit=1&country=us`)).json(),xt=(ct=($e=nt==null?void 0:nt.features)==null?void 0:$e[0])==null?void 0:ct.center;Array.isArray(xt)&&xt.length===2&&(je.longitude=xt[0],je.latitude=xt[1])}}if((!je.bedrooms||!je.bathrooms||!je.sqft||!je.yearBuilt)&&qe())try{Ce(await Ae(je))}catch(Xe){console.warn("second-pass subject lookup failed",Xe)}return JSON.stringify(je)!==JSON.stringify(Ve)&&await l.mutateAsync({id:r.id,patch:{subject:je}}),je};j.useEffect(()=>{var Ae,Ce;r!=null&&r.settings&&g({sqftPct:r.settings.sqftPct??.2,monthsBack:r.settings.monthsBack??6,maxMiles:r.settings.maxMiles??5,statuses:r.settings.statuses??["Active","Pending","Closed"]});const Ve=(Ae=r==null?void 0:r.settings)==null?void 0:Ae.priceOverride;Ve!=null&&Ve.enabled&&(b(!0),S({low:Ve.low!=null?String(Ve.low):"",likely:Ve.likely!=null?String(Ve.likely):"",high:Ve.high!=null?String(Ve.high):"",note:Ve.note??""}));const je=(Ce=r==null?void 0:r.settings)==null?void 0:Ce.personalVideo;je!=null&&je.url&&U({url:je.url,thumb:je.thumb,label:je.label})},[r==null?void 0:r.id]);const V=j.useRef(!1);j.useEffect(()=>{V.current||i!=null&&i.length&&(m(i.map(Ve=>({...Ve.snapshot,selected:Ve.selected,manual:Ve.manual,score:Ve.score}))),V.current=!0)},[i]);const G=j.useRef(null);j.useEffect(()=>{if(!r||u)return;const Ve=r.subject||{},je=Number.isFinite(Number(Ve.latitude))&&Number.isFinite(Number(Ve.longitude)),Ae=!!(Number(Ve.bedrooms)||Number(Ve.bathrooms)||Number(Ve.sqft)||Number(Ve.yearBuilt));if(je&&Ae)return;const Ce=`${r.id}:${(d==null?void 0:d.id)??r.lead_site_id??"no-site"}`;G.current!==Ce&&(!Ve.address||!Ve.city||!Ve.state||(G.current=Ce,(async()=>{try{await W(Ve)}catch(qe){console.warn("subject enrich failed",qe)}})()))},[r==null?void 0:r.id,r==null?void 0:r.lead_site_id,d==null?void 0:d.id,u]);const Y=j.useMemo(()=>r?TCt(r.subject,h):null,[r,h]),X=async()=>{if(r)try{const Ve=await W(r.subject),je=await o.mutateAsync({subject:Ve,filters:f,leadSiteId:(d==null?void 0:d.id)??r.lead_site_id});m(je.comps.map(Ae=>({...Ae,selected:!0})).slice(0,12)),n({title:`Found ${je.comps.length} comps`,description:`Top ${Math.min(12,je.comps.length)} auto-selected.`})}catch(Ve){n({title:"Search failed",description:Ve.message,variant:"destructive"})}},ae=Ve=>{m(je=>je.map((Ae,Ce)=>Ce===Ve?{...Ae,selected:!Ae.selected}:Ae))},ie=Ve=>{m(je=>je.filter((Ae,Ce)=>Ce!==Ve))},ne=async Ve=>{if(!r)return;const je=Object.fromEntries(Object.entries(Ve).filter(([,Ce])=>Ce!=null&&Ce!=="")),Ae={...r.subject,...je,manually_enriched:!0};await l.mutateAsync({id:r.id,patch:{subject:Ae}}),n({title:"Subject details saved",description:Ae.sqft?"You can now find comps or add your own.":"Add square footage to unlock suggested pricing."})},te=Ve=>{m(je=>[{...Ve,selected:!0,manual:!0},...je]),n({title:"Manual comp added"})},J=async(Ve=!1)=>{if(!r)return;const je=TCt(r.subject,h),Ae=ct=>{const Xe=Number(String(ct).replace(/[^0-9.]/g,""));return Number.isFinite(Xe)&&Xe>0?Math.round(Xe):null},Ce=v?Ae(w.likely):null,qe=v?Ae(w.low):null,ze=v?Ae(w.high):null,$e=v&&Ce;await l.mutateAsync({id:r.id,patch:{settings:{...f,priceOverride:{enabled:v,low:qe,likely:Ce,high:ze,note:w.note||null},personalVideo:O},price_low:$e?qe??Ce:je.low??null,price_likely:$e?Ce:je.likely??null,price_high:$e?ze??Ce:je.high??null,status:Ve?"shared":r.status}}),await c.mutateAsync({cmaId:r.id,comps:h}),n({title:Ve?"CMA published":"CMA saved"})},ce=r?`https://cma.relevelup.com/${r.share_token}`:"";if(a||!r)return e.jsx(Vs,{children:e.jsx("div",{className:"p-6",children:e.jsx(kt,{className:"w-6 h-6 animate-spin"})})});const _e=h.filter(Ve=>Ve.selected).length,he=!((ue=r.subject)!=null&&ue.bedrooms)||!((ve=r.subject)!=null&&ve.bathrooms)||!((Ee=r.subject)!=null&&Ee.sqft)||!((Se=r.subject)!=null&&Se.yearBuilt);return e.jsx(Vs,{children:e.jsxs("div",{className:"container mx-auto p-4 md:p-6 max-w-7xl",children:[e.jsxs("div",{className:"flex items-center justify-between mb-4 gap-2 flex-wrap",children:[e.jsxs($,{variant:"ghost",size:"sm",onClick:()=>t("/mission-control/cma"),children:[e.jsx(qa,{className:"w-4 h-4 mr-1"})," All CMAs"]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs($,{variant:"outline",onClick:()=>J(!1),disabled:l.isPending,children:[e.jsx(tl,{className:"w-4 h-4 mr-1"}),"Save"]}),e.jsxs($,{onClick:()=>J(!0),disabled:l.isPending,children:[e.jsx(zd,{className:"w-4 h-4 mr-1"}),"Publish & Share"]}),r.status==="shared"&&e.jsxs(e.Fragment,{children:[e.jsxs($,{variant:"secondary",onClick:()=>{navigator.clipboard.writeText(ce),n({title:"Link copied"})},children:[e.jsx(kr,{className:"w-4 h-4 mr-1"}),"Copy Link"]}),e.jsxs($,{onClick:()=>E(!0),children:[e.jsx(mn,{className:"w-4 h-4 mr-1"}),"Send to Contact"]})]})]})]}),e.jsxs("div",{className:"grid lg:grid-cols-3 gap-4",children:[e.jsxs("div",{className:"lg:col-span-1 space-y-4",children:[e.jsxs(Ne,{children:[e.jsx(Ct,{children:e.jsx(At,{className:"text-base",children:"Subject Property"})}),e.jsxs(Ie,{className:"space-y-2 text-sm",children:[e.jsx("div",{className:"font-semibold",children:r.subject.address}),e.jsxs("div",{className:"text-muted-foreground",children:[r.subject.city,", ",r.subject.state," ",r.subject.zip]}),e.jsxs("div",{className:"grid grid-cols-2 gap-2 pt-2",children:[e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Beds:"})," ",r.subject.bedrooms??"—"]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Baths:"})," ",r.subject.bathrooms??"—"]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"SqFt:"})," ",((Le=r.subject.sqft)==null?void 0:Le.toLocaleString())??"—"]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Year:"})," ",r.subject.yearBuilt??"—"]})]}),he&&e.jsxs("div",{className:"rounded-lg border border-amber-200 bg-amber-50 p-3 text-amber-950 space-y-2",children:[e.jsx("p",{className:"font-medium",children:"No panic — we can still build this."}),e.jsx("p",{className:"text-xs leading-relaxed",children:"If the MLS/feed does not return beds, baths, sqft, or year, add them manually and LevelUp will use them for comps and pricing."}),e.jsxs($,{size:"sm",variant:"outline",className:"bg-white",onClick:()=>P(!0),children:[e.jsx(gi,{className:"w-3.5 h-3.5 mr-1"}),"Fill in property details"]})]}),!he&&e.jsxs($,{size:"sm",variant:"ghost",className:"px-0",onClick:()=>P(!0),children:[e.jsx(gi,{className:"w-3.5 h-3.5 mr-1"}),"Edit details"]}),!r.subject.sqft&&e.jsxs("div",{className:"pt-2 border-t",children:[e.jsx(ee,{className:"text-xs",children:"Subject SqFt (needed for price band)"}),e.jsx(pe,{type:"number",defaultValue:"",onBlur:async Ve=>{const je=Number(Ve.target.value);je>0&&await l.mutateAsync({id:r.id,patch:{subject:{...r.subject,sqft:je}}})}})]})]})]}),e.jsxs(Ne,{children:[e.jsx(Ct,{children:e.jsxs(At,{className:"text-base flex items-center gap-2",children:[e.jsx(c2,{className:"w-4 h-4"}),"Suggested Price"]})}),e.jsxs(Ie,{className:"space-y-3",children:[Y!=null&&Y.likely?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"text-3xl font-bold",children:["$",(v&&Number(w.likely)>0?Number(w.likely):Y.likely).toLocaleString()]}),e.jsxs("div",{className:"text-xs text-muted-foreground mt-1",children:["Comps suggest: $",(Fe=Y.low)==null?void 0:Fe.toLocaleString()," – $",(ke=Y.high)==null?void 0:ke.toLocaleString()]}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:["$",Y.ppsf,"/sqft median · ",_e," comps"]})]}):e.jsx("p",{className:"text-sm text-muted-foreground",children:"Add comps with sqft + price to see suggested pricing."}),e.jsxs("div",{className:"pt-3 border-t space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(ee,{htmlFor:"override-toggle",className:"text-sm font-medium",children:"Override with my price"}),e.jsx(Sn,{id:"override-toggle",checked:v,onCheckedChange:b})]}),v&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs",children:"My suggested price"}),e.jsx(pe,{type:"number",placeholder:"e.g. 750000",value:w.likely,onChange:Ve=>S(je=>({...je,likely:Ve.target.value}))})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs",children:"Range low"}),e.jsx(pe,{type:"number",placeholder:"optional",value:w.low,onChange:Ve=>S(je=>({...je,low:Ve.target.value}))})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs",children:"Range high"}),e.jsx(pe,{type:"number",placeholder:"optional",value:w.high,onChange:Ve=>S(je=>({...je,high:Ve.target.value}))})]})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs",children:"Why this price (optional)"}),e.jsx(Rs,{rows:2,maxLength:500,placeholder:"Notes shown to your client",value:w.note,onChange:Ve=>S(je=>({...je,note:Ve.target.value}))})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Save to apply. Your price will replace the comp-based number on the shared report."})]})]})]})]}),e.jsx(uHn,{value:O,onChange:U}),e.jsxs(Ne,{children:[e.jsx(Ct,{children:e.jsx(At,{className:"text-base",children:"Filters"})}),e.jsxs(Ie,{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsxs(ee,{className:"text-xs",children:["SqFt tolerance: ±",Math.round(f.sqftPct*100),"%"]}),e.jsx(kx,{value:[f.sqftPct*100],min:5,max:50,step:5,onValueChange:([Ve])=>g(je=>({...je,sqftPct:Ve/100}))})]}),e.jsxs("div",{children:[e.jsxs(ee,{className:"text-xs",children:["Search radius: ",f.maxMiles," mi"]}),e.jsx(kx,{value:[f.maxMiles],min:1,max:25,step:1,onValueChange:([Ve])=>g(je=>({...je,maxMiles:Ve}))})]}),e.jsxs("div",{children:[e.jsxs(ee,{className:"text-xs",children:["Sold within: ",f.monthsBack," months"]}),e.jsx(kx,{value:[f.monthsBack],min:1,max:24,step:1,onValueChange:([Ve])=>g(je=>({...je,monthsBack:Ve}))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{className:"text-xs",children:"Status"}),["Active","Pending","Closed"].map(Ve=>e.jsxs("label",{className:"flex items-center gap-2 text-sm",children:[e.jsx(ai,{checked:f.statuses.includes(Ve),onCheckedChange:je=>g(Ae=>({...Ae,statuses:je?[...Ae.statuses,Ve]:Ae.statuses.filter(Ce=>Ce!==Ve)}))})," ",Ve]},Ve))]}),e.jsxs($,{className:"w-full",onClick:X,disabled:o.isPending,children:[o.isPending?e.jsx(kt,{className:"w-4 h-4 animate-spin mr-2"}):e.jsx(Nn,{className:"w-4 h-4 mr-2"}),"Find Comps"]}),e.jsxs($,{variant:"outline",className:"w-full",onClick:()=>D(!0),children:[e.jsx(dn,{className:"w-4 h-4 mr-2"}),"Add a comp manually"]})]})]})]}),e.jsxs("div",{className:"lg:col-span-2 space-y-3",children:[e.jsx(yqn,{subject:r.subject,comps:h,radiusMiles:f.maxMiles,onMarkerClick:Ve=>y(Ve)}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("h2",{className:"text-lg font-semibold",children:["Comparables (",h.length,")"]}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[_e," selected"]})]}),h.length?e.jsx("div",{className:"space-y-2",children:h.map((Ve,je)=>{var Ae;return e.jsx(Ne,{className:Ve.selected?"":"opacity-50",children:e.jsxs(Ie,{className:"p-3 flex gap-3 items-center",children:[e.jsx(ai,{checked:Ve.selected,onCheckedChange:()=>ae(je)}),e.jsxs("button",{type:"button",onClick:()=>y(je),className:"flex gap-3 items-center flex-1 min-w-0 text-left hover:bg-muted/40 -mx-1 px-1 py-1 rounded transition",children:[e.jsx(GEe,{photos:Ve.photos,className:"w-20 h-16 rounded flex-none"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"font-medium truncate hover:underline",children:Ve.address}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[Ve.city,", ",Ve.state," · ",Ve.bedrooms??"?","bd/",Ve.bathrooms??"?","ba · ",((Ae=Ve.sqft)==null?void 0:Ae.toLocaleString())??"?"," sqft",Ve.yearBuilt?` · ${Ve.yearBuilt}`:""]}),e.jsxs("div",{className:"text-xs mt-0.5",children:[e.jsx(Be,{variant:"outline",className:"mr-1",children:Ve.status}),Ve.score!=null&&e.jsxs("span",{className:"text-muted-foreground",children:["Score ",Ve.score]})]})]}),e.jsxs("div",{className:"text-right",children:[e.jsxs("div",{className:"font-semibold",children:["$",(Ve.soldPrice||Ve.price||0).toLocaleString()]}),Ve.sqft&&(Ve.soldPrice||Ve.price)?e.jsxs("div",{className:"text-xs text-muted-foreground",children:["$",Math.round((Ve.soldPrice||Ve.price)/Ve.sqft),"/sqft"]}):null]})]}),e.jsx($,{variant:"ghost",size:"icon",onClick:()=>y(je),title:"View details",children:e.jsx(Ca,{className:"w-4 h-4"})}),e.jsx($,{variant:"ghost",size:"icon",onClick:()=>ie(je),title:"Remove",children:e.jsx(Wn,{className:"w-4 h-4"})})]})},je)})}):e.jsx(Ne,{children:e.jsx(Ie,{className:"py-12 text-center text-muted-foreground",children:e.jsxs("div",{className:"max-w-md mx-auto space-y-3",children:[e.jsxs("p",{children:["Click ",e.jsx("strong",{children:"Find Comps"})," to auto-pull from your MLS."]}),e.jsx("p",{className:"text-sm",children:"If nothing comes back, you are not stuck — use LevelUp's fallback template: enter the subject details, add 2–3 known comps, then set your suggested price."}),e.jsxs("div",{className:"flex flex-wrap justify-center gap-2",children:[he&&e.jsx($,{variant:"outline",size:"sm",onClick:()=>P(!0),children:"Fill subject details"}),e.jsx($,{variant:"outline",size:"sm",onClick:()=>D(!0),children:"Add manual comp"})]})]})})})]})]}),e.jsx(h$t,{comp:x!=null?h[x]:null,open:x!=null,onClose:()=>y(null)}),e.jsx(hHn,{open:I,onOpenChange:P,subject:r.subject,onSave:ne,isSaving:l.isPending}),e.jsx(mHn,{open:R,onOpenChange:D,subject:r.subject,onAdd:te}),e.jsx(pJt,{open:C,onOpenChange:E,cma:r})]})})}const UL="listing-presentations";function bts(){const{user:s}=vs(),t=Vt(),n=tt({queryKey:["listing-presentation-saved-templates",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:o,error:c}=await q.from("listing_presentation_saved_templates").select("*").eq("owner_user_id",s.id).order("updated_at",{ascending:!1});if(c)throw c;return o}}),r=()=>t.invalidateQueries({queryKey:["listing-presentation-saved-templates",s==null?void 0:s.id]}),a=ft({mutationFn:async o=>{const{data:c,error:d}=await q.from("listing_presentation_saved_templates").insert({...o,owner_user_id:s.id}).select().single();if(d)throw d;return c},onSuccess:()=>{r(),re.success("Template saved")},onError:o=>re.error(o.message||"Could not save the template")}),i=ft({mutationFn:async({id:o,...c})=>{const{error:d}=await q.from("listing_presentation_saved_templates").update(c).eq("id",o);if(d)throw d},onSuccess:()=>{r(),re.success("Template updated")},onError:o=>re.error(o.message||"Could not update the template")}),l=ft({mutationFn:async o=>{const{error:c}=await q.from("listing_presentation_saved_templates").delete().eq("id",o);if(c)throw c},onSuccess:()=>{r(),re.success("Template deleted")},onError:o=>re.error(o.message||"Could not delete the template")});return{savedTemplates:n.data??[],isLoading:n.isLoading,save:a,update:i,remove:l}}function pHn(){return tt({queryKey:["listing-presentation-templates"],staleTime:10*60*1e3,queryFn:async()=>{const{data:s,error:t}=await q.from("listing_presentation_templates").select("*").eq("is_active",!0).order("sort_order",{ascending:!0});if(t)throw t;return s}})}function _ts(){const{user:s}=vs(),t=Vt(),n=tt({queryKey:["listing-presentations",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:c,error:d}=await q.from("listing_presentations").select("*").eq("owner_user_id",s.id).order("updated_at",{ascending:!1});if(d)throw d;return c}}),r=()=>t.invalidateQueries({queryKey:["listing-presentations",s==null?void 0:s.id]}),a=ft({mutationFn:async c=>{const{data:d,error:u}=await q.from("listing_presentations").insert({...c,owner_user_id:s.id}).select().single();if(u)throw u;return d},onSuccess:r,onError:c=>re.error(c.message||"Could not create presentation")}),i=ft({mutationFn:async({id:c,...d})=>{const{data:u,error:h}=await q.from("listing_presentations").update(d).eq("id",c).select().single();if(h)throw h;return u},onSuccess:c=>{r(),t.invalidateQueries({queryKey:["listing-presentation",c.id]})},onError:c=>re.error(c.message||"Could not save presentation")}),l=ft({mutationFn:async c=>{let d=null;const{data:u,error:h}=await q.from("listing_presentations").insert({owner_user_id:s.id,title:`${c.title} (Copy)`,template_id:c.template_id,status:"draft",property_address_line1:c.property_address_line1,city:c.city,state:c.state,postal_code:c.postal_code,list_price:c.list_price,beds:c.beds,baths:c.baths,sqft:c.sqft,agent_snapshot:c.agent_snapshot,co_agent:c.co_agent,custom_pages:c.custom_pages,services:c.services,page_settings:c.page_settings,photo_focal:c.photo_focal}).select().single();if(h)throw h;if(c.property_photo_path){d=`${s.id}/${u.id}/photo.jpg`;const{error:m}=await q.storage.from(UL).copy(c.property_photo_path,d);m||await q.from("listing_presentations").update({property_photo_path:d}).eq("id",u.id)}return u},onSuccess:()=>{r(),re.success("Presentation duplicated")},onError:c=>re.error(c.message||"Could not duplicate")}),o=ft({mutationFn:async c=>{const d=[c.property_photo_path,c.pdf_path,c.thumbnail_path].filter(Boolean);d.length&&await q.storage.from(UL).remove(d);const{error:u}=await q.from("listing_presentations").delete().eq("id",c.id);if(u)throw u},onSuccess:()=>{r(),re.success("Presentation deleted")},onError:c=>re.error(c.message||"Could not delete")});return{presentations:n.data??[],isLoading:n.isLoading,create:a,update:i,duplicate:l,remove:o}}function gHn(s){return tt({queryKey:["listing-presentation",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await q.from("listing_presentations").select("*").eq("id",s).maybeSingle();if(n)throw n;return t}})}async function xHn(s,t=3600){if(!s)return null;const{data:n,error:r}=await q.storage.from(UL).createSignedUrl(s,t);return r?null:(n==null?void 0:n.signedUrl)??null}const aZe={cover:{kicker:"A smarter launch for",headline:"",subhead:"",body:"A complete marketing plan designed to make your home stand out, reach more buyers, and create stronger interest."},welcome:{kicker:"The strategy",headline:"Your listing deserves more than a sign and an MLS entry.",subhead:"It deserves a coordinated launch that builds attention from day one.",body:""},agent:{kicker:"Your agent",headline:"Who you are working with.",subhead:"",body:""},overview:{kicker:"The plan",headline:"Every home gets listed. Very few get marketed.",subhead:"These are the steps we run on your home, in order, starting the day we sign.",body:""},closing:{kicker:"The commitment",headline:'Your home will never feel like "just another listing."',subhead:"",body:"It will be prepared carefully, presented professionally, launched strategically, and promoted with purpose — from the first photo to the final signature."}},yHn={cover:"Cover",welcome:"Marketing commitment",agent:"About your agent",overview:"Marketing plan overview",closing:"Closing commitment"};function wts(s,t){var i;const n=((i=s==null?void 0:s.copy)==null?void 0:i[t])||{},r=aZe[t],a=l=>{const o=n[l];return o??r[l]};return{kicker:a("kicker"),headline:a("headline"),subhead:a("subhead"),body:a("body")}}const jts={enabled:!1,name:"",title:null,headshotUrl:null,phone:null,email:null,brokerageName:null,licenseNumber:null,bio:null};function Nts(s){return{...jts,...s||{}}}const h$e=[{layout:"story",name:"Story + photo",description:'Editorial two-column story next to a full-height photo. Great for "About Us".'},{layout:"testimonials",name:"Testimonial cards",description:'Up to four pull-quote cards. Great for "What Others Are Saying".'},{layout:"stats",name:"Numbers band",description:"Big stat tiles with a short lead paragraph. Great for a track record page."},{layout:"checklist",name:"Checklist",description:"Headline, intro copy, and an accent-marked list of promises or steps."},{layout:"statement",name:"Full-bleed statement",description:"A dark, photo-backed page with one powerful line. Great for a section break."}],kts=()=>typeof crypto<"u"&&"randomUUID"in crypto?crypto.randomUUID():`cp_${Math.random().toString(36).slice(2)}`;function Not(s,t=0){const n={id:kts(),layout:s,enabled:!0,order:t,placement:"after-agent",kicker:"",headline:"",subhead:"",body:"",bullets:[],testimonials:[],stats:[],imageUrl:null,imageSide:"right",dark:!1};switch(s){case"story":return{...n,kicker:"About us",headline:"A team built around one thing: your move.",subhead:"Who we are, how we work, and why sellers keep referring us.",body:"Share your background, your team, and what a seller can expect when they work with you. Two or three short paragraphs is the sweet spot — enough to build trust without turning the page into a resume."};case"testimonials":return{...n,kicker:"What others are saying",headline:"The people we have already moved.",subhead:"Real words from recent sellers and buyers.",testimonials:[{quote:"Add a real client quote here.",name:"Client name",detail:"Neighborhood or year"},{quote:"Add a second client quote here.",name:"Client name",detail:"Neighborhood or year"}]};case"stats":return{...n,kicker:"Track record",headline:"The numbers behind the plan.",body:"Add only numbers you can stand behind — sellers notice when the math is real.",stats:[{value:"",label:"Homes sold"},{value:"",label:"Avg. days on market"},{value:"",label:"List-to-sale price"}]};case"checklist":return{...n,kicker:"Our promise",headline:"What you can count on from us.",body:"A short intro to the list below.",bullets:["Add a promise, step, or service here","Add another line","Add another line"]};case"statement":return{...n,dark:!0,kicker:"Our approach",headline:"Every home has a story. We make sure buyers hear it.",body:""};default:return n}}function Sts(s){return Array.isArray(s)?s.filter(t=>t&&typeof t=="object").map((t,n)=>({...Not(t.layout||"story",n),...t,id:t.id||kts(),order:typeof t.order=="number"?t.order:n,bullets:Array.isArray(t.bullets)?t.bullets:[],testimonials:Array.isArray(t.testimonials)?t.testimonials:[],stats:Array.isArray(t.stats)?t.stats:[]})).sort((t,n)=>t.order-n.order):[]}const iZe={hidden:["overview"]},oZe={x:.5,y:.5},su=(s,t,n=!0)=>({key:s,label:t,enabled:n}),dPe=[{key:"photography",title:"Professional Photography",body:"Your home is photographed by a professional real estate photographer — HDR interiors, crisp exteriors, and the detail shots that make buyers stop scrolling. Every image is color-corrected and delivered ready for print and every portal.",enabled:!0,order:0,options:[su("hdr","Full HDR interior and exterior photo set"),su("drone","Aerial drone photography of the home and lot"),su("twilight","Twilight exterior session for the hero image"),su("staging","Virtual staging for vacant or transitional rooms",!1),su("floorplan","Measured floor plan buyers can explore")]},{key:"video",title:"Video That Sells the Feeling",body:"Photos show the rooms. Video shows the life. We produce a cinematic walkthrough plus short-form vertical cuts built specifically for how buyers actually watch — on their phone, in the first ten seconds.",enabled:!0,order:1,options:[su("walkthrough","Cinematic full-property walkthrough video"),su("reels","Vertical short-form cuts for Reels, Shorts, and TikTok"),su("oncamera","On-camera agent introduction to the home"),su("neighborhood","Neighborhood and lifestyle b-roll")]},{key:"mls",title:"MLS Launch & Pricing Strategy",body:"We launch on the MLS with a carefully written description, complete data fields, and a pricing strategy built around live comparable activity — positioning your home to attract the strongest possible offers in the first two weeks.",enabled:!0,order:2,options:[su("data","Complete, accurate MLS data so your home shows in every filter"),su("copy","Copywriting that leads with the features buyers pay for"),su("pricing","Pricing built on live comparable and absorption data"),su("comingsoon","Coming-soon window to build demand before day one")]},{key:"syndication",title:"Maximum Exposure & Portal Distribution",body:"Your listing is pushed to the sites buyers already live on, with the data monitored so your photos, price, and details stay accurate everywhere they appear.",enabled:!0,order:3,options:[su("zillow","Zillow — the highest-traffic buyer search portal"),su("realtor","Realtor.com — direct MLS-sourced listing feed"),su("homes","Homes.com — agent-attributed listing exposure"),su("others","Redfin, Trulia, Movoto, and hundreds of partner sites"),su("routing","Buyer inquiries routed straight to me and answered fast")]},{key:"website",title:"Dedicated Property Website",body:"Your home gets its own single-property website with the full photo gallery, video, floor plan, neighborhood details, and a direct inquiry form — a link we can share in every ad, email, and social post.",enabled:!0,order:4,options:[su("gallery","Full-screen gallery, video, and floor plan in one place"),su("mobile","Mobile-first design with a one-tap inquiry form"),su("link","Shareable link used across ads, email, and QR signage"),su("traffic","Traffic tracked and reported back to you")]},{key:"social",title:"Social Media Campaign",body:"A launch that looks like a campaign, not a post. Organic content across my channels plus targeted paid placement aimed at qualified buyers and the agents who represent them.",enabled:!0,order:5,options:[su("organic","Just-listed launch across feed, stories, and reels"),su("ads","Geo-targeted paid campaigns aimed at active buyers"),su("retarget","Retargeting so interested viewers keep seeing your home"),su("agentsocial","Agent-to-agent promotion inside local networks")]},{key:"email",title:"Email, Database & Agent Outreach",body:"The fastest buyer is often already in someone’s database. Your listing goes directly to my buyers, past clients, and referral partners — and to the agents actively working your price range.",enabled:!0,order:6,options:[su("database","Direct email to my buyer and past-client database"),su("agents","Broadcast to area agents with matching buyers"),su("referral","Referral partner network notified at launch"),su("followup","Follow-up sequence to everyone who engages")]},{key:"openhouse",title:"Open Houses & Neighborhood Marketing",body:"Neighbors sell neighborhoods. We combine well-timed open houses with the local marketing that reaches the people most likely to know your next buyer.",enabled:!0,order:7,options:[su("public","Strategically timed public open houses"),su("broker","Broker open house for agents with active buyers"),su("signin","Digital sign-in that captures every visitor"),su("neighbors","Neighbor invitations and just-listed mailers"),su("signage","Premium signage, riders, and directional placement")]},{key:"communication",title:"Communication & Weekly Reporting",body:"You will never wonder what is happening. You get a regular seller report with showing feedback, online traffic numbers, and market shifts, plus direct access to me by call, text, or email.",enabled:!0,order:8,options:[su("weekly","Weekly seller report on the schedule you prefer"),su("feedback","Showing feedback delivered as it comes in"),su("analytics","Online traffic and engagement analytics"),su("access","Direct access to me by call, text, or email")]}],vHn=Object.fromEntries(dPe.map(s=>[s.key,(s.options||[]).map(t=>t.label)]));function lZe(s){return s!=null&&s.length?dPe.map(t=>{var a;const n=s.find(i=>i.key===t.key);if(!n)return{...t,options:(a=t.options)==null?void 0:a.map(i=>({...i}))};const r=(t.options||[]).map(i=>{var o;const l=(o=n.options)==null?void 0:o.find(c=>c.key===i.key);return l?{...i,enabled:l.enabled}:{...i}});return{...t,title:n.title||t.title,body:n.body||t.body,enabled:n.enabled,order:t.order,options:r}}):dPe.map(t=>{var n;return{...t,options:(n=t.options)==null?void 0:n.map(r=>({...r}))}})}const bHn={welcome:"Marketing commitment",agent:"About your agent",overview:"Marketing plan overview",closing:"Closing commitment"};function Pm(s){"@babel/helpers - typeof";return Pm=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},Pm(s)}var bC=Uint8Array,n2=Uint16Array,kot=Int32Array,Sot=new bC([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]),Cot=new bC([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]),B5t=new bC([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),Cts=function(s,t){for(var n=new n2(31),r=0;r<31;++r)n[r]=t+=1<>1|(Np&21845)<<1;TM=(TM&52428)>>2|(TM&13107)<<2,TM=(TM&61680)>>4|(TM&3855)<<4,dZe[Np]=((TM&65280)>>8|(TM&255)<<8)>>1}var rte=function(s,t,n){for(var r=s.length,a=0,i=new n2(t);a>c]=d}else for(o=new n2(r),a=0;a>15-s[a]);return o},gB=new bC(288);for(var Np=0;Np<144;++Np)gB[Np]=8;for(var Np=144;Np<256;++Np)gB[Np]=9;for(var Np=256;Np<280;++Np)gB[Np]=7;for(var Np=280;Np<288;++Np)gB[Np]=8;var uPe=new bC(32);for(var Np=0;Np<32;++Np)uPe[Np]=5;var jHn=rte(gB,9,0),NHn=rte(uPe,5,0),Ets=function(s){return(s+7)/8|0},kHn=function(s,t,n){return(n==null||n>s.length)&&(n=s.length),new bC(s.subarray(t,n))},lA=function(s,t,n){n<<=t&7;var r=t/8|0;s[r]|=n,s[r+1]|=n>>8},dX=function(s,t,n){n<<=t&7;var r=t/8|0;s[r]|=n,s[r+1]|=n>>8,s[r+2]|=n>>16},m$e=function(s,t){for(var n=[],r=0;rm&&(m=i[r].s);var f=new n2(m+1),g=uZe(n[u-1],f,0);if(g>t){var r=0,x=0,y=g-t,v=1<t)x+=v-(1<>=y;x>0;){var w=i[r].s;f[w]=0&&x;--r){var S=i[r].s;f[S]==t&&(--f[S],++x)}g=t}return{t:new bC(f),l:g}},uZe=function(s,t,n){return s.s==-1?Math.max(uZe(s.l,t,n+1),uZe(s.r,t,n+1)):t[s.s]=n},U5t=function(s){for(var t=s.length;t&&!s[--t];);for(var n=new n2(++t),r=0,a=s[0],i=1,l=function(c){n[r++]=c},o=1;o<=t;++o)if(s[o]==a&&o!=t)++i;else{if(!a&&i>2){for(;i>138;i-=138)l(32754);i>2&&(l(i>10?i-11<<5|28690:i-3<<5|12305),i=0)}else if(i>3){for(l(a),--i;i>6;i-=6)l(8304);i>2&&(l(i-3<<5|8208),i=0)}for(;i--;)l(a);i=1,a=s[o]}return{c:n.subarray(0,r),n:t}},uX=function(s,t){for(var n=0,r=0;r>8,s[a+2]=s[a]^255,s[a+3]=s[a+1]^255;for(var i=0;i4&&!D[B5t[U-1]];--U);var W=d+5<<3,V=uX(a,gB)+uX(i,uPe)+l,G=uX(a,m)+uX(i,x)+l+14+3*U+uX(I,D)+2*I[16]+3*I[17]+7*I[18];if(c>=0&&W<=V&&W<=G)return Tts(t,u,s.subarray(c,c+d));var Y,X,ae,ie;if(lA(t,u,1+(G15&&(lA(t,u,ce[P]>>5&127),u+=ce[P]>>12)}}else Y=jHn,X=gB,ae=NHn,ie=uPe;for(var P=0;P255){var _e=he>>18&31;dX(t,u,Y[_e+257]),u+=X[_e+257],_e>7&&(lA(t,u,he>>23&31),u+=Sot[_e]);var ue=he&31;dX(t,u,ae[ue]),u+=ie[ue],ue>3&&(dX(t,u,he>>5&8191),u+=Cot[ue])}else dX(t,u,Y[he]),u+=X[he]}return dX(t,u,Y[256]),u+X[256]},SHn=new kot([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),Mts=new bC(0),CHn=function(s,t,n,r,a,i){var l=i.z||s.length,o=new bC(r+l+5*(1+Math.ceil(l/7e3))+a),c=o.subarray(r,o.length-a),d=i.l,u=(i.r||0)&7;if(t){u&&(c[0]=i.r>>3);for(var h=SHn[t-1],m=h>>13,f=h&8191,g=(1<7e3||D>24576)&&(Y>423||!d)){u=q5t(s,c,0,S,C,E,P,D,U,R-U,u),D=I=P=0,U=R;for(var X=0;X<286;++X)C[X]=0;for(var X=0;X<30;++X)E[X]=0}var ae=2,ie=0,ne=f,te=V-G&32767;if(Y>2&&W==w(R-te))for(var J=Math.min(m,Y)-1,ce=Math.min(32767,R),_e=Math.min(258,Y);te<=ce&&--ne&&V!=G;){if(s[R+ae]==s[R+ae-te]){for(var he=0;he<_e&&s[R+he]==s[R+he-te];++he);if(he>ae){if(ae=he,ie=te,he>J)break;for(var ue=Math.min(te,he-2),ve=0,X=0;Xve&&(ve=Le,G=Ee)}}}V=G,G=x[V],te+=V-G&32767}if(ie){S[D++]=268435456|cZe[ae]<<18|$5t[ie];var Fe=cZe[ae]&31,ke=$5t[ie]&31;P+=Sot[Fe]+Cot[ke],++C[257+Fe],++E[ke],O=R+ae,++I}else S[D++]=s[R],++C[s[R]]}}for(R=Math.max(R,O);R=l&&(c[u/8|0]=d,Ve=l),u=Tts(c,u+1,s.subarray(R,Ve))}i.i=l}return kHn(o,0,r+Ets(u)+a)},Pts=function(){var s=1,t=0;return{p:function(n){for(var r=s,a=t,i=n.length|0,l=0;l!=i;){for(var o=Math.min(l+2655,i);l>16),a=(a&65535)+15*(a>>16)}s=r,t=a},d:function(){return s%=65521,t%=65521,(s&255)<<24|(s&65280)<<8|(t&255)<<8|t>>8}}},AHn=function(s,t,n,r,a){if(!a&&(a={l:1},t.dictionary)){var i=t.dictionary.subarray(-32768),l=new bC(i.length+s.length);l.set(i),l.set(s,i.length),s=l,a.w=i.length}return CHn(s,t.level==null?6:t.level,t.mem==null?a.l?Math.ceil(Math.max(8,Math.min(13,Math.log(s.length)))*1.5):20:12+t.mem,n,r,a)},Its=function(s,t,n){for(;n;++t)s[t]=n,n>>>=8},EHn=function(s,t){var n=t.level,r=n==0?0:n<6?1:n==9?3:2;if(s[0]=120,s[1]=r<<6|(t.dictionary&&32),s[1]|=31-(s[0]<<8|s[1])%31,t.dictionary){var a=Pts();a.p(t.dictionary),Its(s,2,a.d())}};function hZe(s,t){t||(t={});var n=Pts();n.p(s);var r=AHn(s,t,t.dictionary?6:2,4);return EHn(r,t),Its(r,r.length-4,n.d()),r}var THn=typeof TextDecoder<"u"&&new TextDecoder,MHn=0;try{THn.decode(Mts,{stream:!0}),MHn=1}catch{}function PHn(s){if(Array.isArray(s))return s}function IHn(s,t){var n=s==null?null:typeof Symbol<"u"&&s[Symbol.iterator]||s["@@iterator"];if(n!=null){var r,a,i,l,o=[],c=!0,d=!1;try{if(i=(n=n.call(s)).next,t!==0)for(;!(c=(r=i.call(n)).done)&&(o.push(r.value),o.length!==t);c=!0);}catch(u){d=!0,a=u}finally{try{if(!c&&n.return!=null&&(l=n.return(),Object(l)!==l))return}finally{if(d)throw a}}return o}}function V5t(s,t){(t==null||t>s.length)&&(t=s.length);for(var n=0,r=Array(t);n{const s=new Uint8Array(4),t=new Uint32Array(s.buffer);return!((t[0]=1)&s[0])})(),f$e={int8:globalThis.Int8Array,uint8:globalThis.Uint8Array,int16:globalThis.Int16Array,uint16:globalThis.Uint16Array,int32:globalThis.Int32Array,uint32:globalThis.Uint32Array,uint64:globalThis.BigUint64Array,int64:globalThis.BigInt64Array,float32:globalThis.Float32Array,float64:globalThis.Float64Array};class Aot{constructor(t=OHn,n={}){Nr(this,"buffer");Nr(this,"byteLength");Nr(this,"byteOffset");Nr(this,"length");Nr(this,"offset");Nr(this,"lastWrittenByte");Nr(this,"littleEndian");Nr(this,"_data");Nr(this,"_mark");Nr(this,"_marks");let r=!1;typeof t=="number"?t=new ArrayBuffer(t):(r=!0,this.lastWrittenByte=t.byteLength);const a=n.offset?n.offset>>>0:0,i=t.byteLength-a;let l=a;(ArrayBuffer.isView(t)||t instanceof Aot)&&(t.byteLength!==t.buffer.byteLength&&(l=t.byteOffset+a),t=t.buffer),r?this.lastWrittenByte=i:this.lastWrittenByte=0,this.buffer=t,this.length=i,this.byteLength=i,this.byteOffset=l,this.offset=0,this.littleEndian=!0,this._data=new DataView(this.buffer,l,i),this._mark=0,this._marks=[]}available(t=1){return this.offset+t<=this.length}isLittleEndian(){return this.littleEndian}setLittleEndian(){return this.littleEndian=!0,this}isBigEndian(){return!this.littleEndian}setBigEndian(){return this.littleEndian=!1,this}skip(t=1){return this.offset+=t,this}back(t=1){return this.offset-=t,this}seek(t){return this.offset=t,this}mark(){return this._mark=this.offset,this}reset(){return this.offset=this._mark,this}pushMark(){return this._marks.push(this.offset),this}popMark(){const t=this._marks.pop();if(t===void 0)throw new Error("Mark stack empty");return this.seek(t),this}rewind(){return this.offset=0,this}ensureAvailable(t=1){if(!this.available(t)){const r=(this.offset+t)*2,a=new Uint8Array(r);a.set(new Uint8Array(this.buffer)),this.buffer=a.buffer,this.length=r,this.byteLength=r,this._data=new DataView(this.buffer)}return this}readBoolean(){return this.readUint8()!==0}readInt8(){return this._data.getInt8(this.offset++)}readUint8(){return this._data.getUint8(this.offset++)}readByte(){return this.readUint8()}readBytes(t=1){return this.readArray(t,"uint8")}readArray(t,n){const r=f$e[n].BYTES_PER_ELEMENT*t,a=this.byteOffset+this.offset,i=this.buffer.slice(a,a+r);if(this.littleEndian===zHn&&n!=="uint8"&&n!=="int8"){const o=new Uint8Array(this.buffer.slice(a,a+r));o.reverse();const c=new f$e[n](o.buffer);return this.offset+=r,c.reverse(),c}const l=new f$e[n](i);return this.offset+=r,l}readInt16(){const t=this._data.getInt16(this.offset,this.littleEndian);return this.offset+=2,t}readUint16(){const t=this._data.getUint16(this.offset,this.littleEndian);return this.offset+=2,t}readInt32(){const t=this._data.getInt32(this.offset,this.littleEndian);return this.offset+=4,t}readUint32(){const t=this._data.getUint32(this.offset,this.littleEndian);return this.offset+=4,t}readFloat32(){const t=this._data.getFloat32(this.offset,this.littleEndian);return this.offset+=4,t}readFloat64(){const t=this._data.getFloat64(this.offset,this.littleEndian);return this.offset+=8,t}readBigInt64(){const t=this._data.getBigInt64(this.offset,this.littleEndian);return this.offset+=8,t}readBigUint64(){const t=this._data.getBigUint64(this.offset,this.littleEndian);return this.offset+=8,t}readChar(){return String.fromCharCode(this.readInt8())}readChars(t=1){let n="";for(let r=0;rthis.lastWrittenByte&&(this.lastWrittenByte=this.offset)}}function tY(s){let t=s.length;for(;--t>=0;)s[t]=0}const BHn=3,$Hn=258,Lts=29,UHn=256,qHn=UHn+1+Lts,Rts=30,VHn=512,HHn=new Array((qHn+2)*2);tY(HHn);const GHn=new Array(Rts*2);tY(GHn);const WHn=new Array(VHn);tY(WHn);const KHn=new Array($Hn-BHn+1);tY(KHn);const YHn=new Array(Lts);tY(YHn);const ZHn=new Array(Rts);tY(ZHn);const XHn=(s,t,n,r)=>{let a=s&65535|0,i=s>>>16&65535|0,l=0;for(;n!==0;){l=n>2e3?2e3:n,n-=l;do a=a+t[r++]|0,i=i+a|0;while(--l);a%=65521,i%=65521}return a|i<<16|0};var mZe=XHn;const QHn=()=>{let s,t=[];for(var n=0;n<256;n++){s=n;for(var r=0;r<8;r++)s=s&1?3988292384^s>>>1:s>>>1;t[n]=s}return t},JHn=new Uint32Array(QHn()),eGn=(s,t,n,r)=>{const a=JHn,i=r+n;s^=-1;for(let l=r;l>>8^a[(s^t[l])&255];return s^-1};var o5=eGn,fZe={2:"need dictionary",1:"stream end",0:"","-1":"file error","-2":"stream error","-3":"data error","-4":"insufficient memory","-5":"buffer error","-6":"incompatible version"},Dts={Z_NO_FLUSH:0,Z_FINISH:4,Z_BLOCK:5,Z_TREES:6,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_MEM_ERROR:-4,Z_BUF_ERROR:-5,Z_DEFLATED:8};const tGn=(s,t)=>Object.prototype.hasOwnProperty.call(s,t);var sGn=function(s){const t=Array.prototype.slice.call(arguments,1);for(;t.length;){const n=t.shift();if(n){if(typeof n!="object")throw new TypeError(n+"must be non-object");for(const r in n)tGn(n,r)&&(s[r]=n[r])}}return s},nGn=s=>{let t=0;for(let r=0,a=s.length;r=252?6:s>=248?5:s>=240?4:s>=224?3:s>=192?2:1;_ne[254]=_ne[255]=1;var rGn=s=>{if(typeof TextEncoder=="function"&&TextEncoder.prototype.encode)return new TextEncoder().encode(s);let t,n,r,a,i,l=s.length,o=0;for(a=0;a>>6,t[i++]=128|n&63):n<65536?(t[i++]=224|n>>>12,t[i++]=128|n>>>6&63,t[i++]=128|n&63):(t[i++]=240|n>>>18,t[i++]=128|n>>>12&63,t[i++]=128|n>>>6&63,t[i++]=128|n&63);return t};const aGn=(s,t)=>{if(t<65534&&s.subarray&&Ots)return String.fromCharCode.apply(null,s.length===t?s:s.subarray(0,t));let n="";for(let r=0;r{const n=t||s.length;if(typeof TextDecoder=="function"&&TextDecoder.prototype.decode)return new TextDecoder().decode(s.subarray(0,t));let r,a;const i=new Array(n*2);for(a=0,r=0;r4){i[a++]=65533,r+=o-1;continue}for(l&=o===2?31:o===3?15:7;o>1&&r1){i[a++]=65533;continue}l<65536?i[a++]=l:(l-=65536,i[a++]=55296|l>>10&1023,i[a++]=56320|l&1023)}return aGn(i,a)},oGn=(s,t)=>{t=t||s.length,t>s.length&&(t=s.length);let n=t-1;for(;n>=0&&(s[n]&192)===128;)n--;return n<0||n===0?t:n+_ne[s[n]]>t?n:t},pZe={string2buf:rGn,buf2string:iGn,utf8border:oGn};function lGn(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0}var cGn=lGn;const Nue=16209,dGn=16191;var uGn=function(t,n){let r,a,i,l,o,c,d,u,h,m,f,g,x,y,v,b,w,S,C,E,I,P,R,D;const O=t.state;r=t.next_in,R=t.input,a=r+(t.avail_in-5),i=t.next_out,D=t.output,l=i-(n-t.avail_out),o=i+(t.avail_out-257),c=O.dmax,d=O.wsize,u=O.whave,h=O.wnext,m=O.window,f=O.hold,g=O.bits,x=O.lencode,y=O.distcode,v=(1<>>24,f>>>=S,g-=S,S=w>>>16&255,S===0)D[i++]=w&65535;else if(S&16){C=w&65535,S&=15,S&&(g>>=S,g-=S),g<15&&(f+=R[r++]<>>24,f>>>=S,g-=S,S=w>>>16&255,S&16){if(E=w&65535,S&=15,gc){t.msg="invalid distance too far back",O.mode=Nue;break e}if(f>>>=S,g-=S,S=i-l,E>S){if(S=E-S,S>u&&O.sane){t.msg="invalid distance too far back",O.mode=Nue;break e}if(I=0,P=m,h===0){if(I+=d-S,S2;)D[i++]=P[I++],D[i++]=P[I++],D[i++]=P[I++],C-=3;C&&(D[i++]=P[I++],C>1&&(D[i++]=P[I++]))}else{I=i-E;do D[i++]=D[I++],D[i++]=D[I++],D[i++]=D[I++],C-=3;while(C>2);C&&(D[i++]=D[I++],C>1&&(D[i++]=D[I++]))}}else if(S&64){t.msg="invalid distance code",O.mode=Nue;break e}else{w=y[(w&65535)+(f&(1<>3,r-=C,g-=C<<3,f&=(1<{const c=o.bits;let d=0,u=0,h=0,m=0,f=0,g=0,x=0,y=0,v=0,b=0,w,S,C,E,I,P=null,R;const D=new Uint16Array(G$+1),O=new Uint16Array(G$+1);let U=null,W,V,G;for(d=0;d<=G$;d++)D[d]=0;for(u=0;u=1&&D[m]===0;m--);if(f>m&&(f=m),m===0)return a[i++]=1<<24|64<<16|0,a[i++]=1<<24|64<<16|0,o.bits=1,0;for(h=1;h0&&(s===Y5t||m!==1))return-1;for(O[1]=0,d=1;dW5t||s===Z5t&&v>K5t)return 1;for(;;){W=d-x,l[u]+1=R?(V=U[l[u]-R],G=P[l[u]-R]):(V=96,G=0),w=1<>x)+S]=W<<24|V<<16|G|0;while(S!==0);for(w=1<>=1;if(w!==0?(b&=w-1,b+=w):b=0,u++,--D[d]===0){if(d===m)break;d=t[n+l[u]]}if(d>f&&(b&E)!==C){for(x===0&&(x=f),I+=h,g=d-x,y=1<W5t||s===Z5t&&v>K5t)return 1;C=b&E,a[C]=f<<24|g<<16|I-i|0}}return b!==0&&(a[I+b]=d-x<<24|64<<16|0),o.bits=f,0};var ate=gGn;const xGn=0,zts=1,Bts=2,{Z_FINISH:X5t,Z_BLOCK:yGn,Z_TREES:kue,Z_OK:xB,Z_STREAM_END:vGn,Z_NEED_DICT:bGn,Z_STREAM_ERROR:xk,Z_DATA_ERROR:$ts,Z_MEM_ERROR:Uts,Z_BUF_ERROR:_Gn,Z_DEFLATED:Q5t}=Dts,DDe=16180,J5t=16181,e4t=16182,t4t=16183,s4t=16184,n4t=16185,r4t=16186,a4t=16187,i4t=16188,o4t=16189,hPe=16190,cA=16191,g$e=16192,l4t=16193,x$e=16194,c4t=16195,d4t=16196,u4t=16197,h4t=16198,Sue=16199,Cue=16200,m4t=16201,f4t=16202,p4t=16203,g4t=16204,x4t=16205,y$e=16206,y4t=16207,v4t=16208,Fp=16209,qts=16210,Vts=16211,wGn=852,jGn=592,NGn=15,kGn=NGn,b4t=s=>(s>>>24&255)+(s>>>8&65280)+((s&65280)<<8)+((s&255)<<24);function SGn(){this.strm=null,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 Uint16Array(320),this.work=new Uint16Array(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}const u9=s=>{if(!s)return 1;const t=s.state;return!t||t.strm!==s||t.modeVts?1:0},Hts=s=>{if(u9(s))return xk;const t=s.state;return s.total_in=s.total_out=t.total=0,s.msg="",t.wrap&&(s.adler=t.wrap&1),t.mode=DDe,t.last=0,t.havedict=0,t.flags=-1,t.dmax=32768,t.head=null,t.hold=0,t.bits=0,t.lencode=t.lendyn=new Int32Array(wGn),t.distcode=t.distdyn=new Int32Array(jGn),t.sane=1,t.back=-1,xB},Gts=s=>{if(u9(s))return xk;const t=s.state;return t.wsize=0,t.whave=0,t.wnext=0,Hts(s)},Wts=(s,t)=>{let n;if(u9(s))return xk;const r=s.state;return t<0?(n=0,t=-t):(n=(t>>4)+5,t<48&&(t&=15)),t&&(t<8||t>15)?xk:(r.window!==null&&r.wbits!==t&&(r.window=null),r.wrap=n,r.wbits=t,Gts(s))},Kts=(s,t)=>{if(!s)return xk;const n=new SGn;s.state=n,n.strm=s,n.window=null,n.mode=DDe;const r=Wts(s,t);return r!==xB&&(s.state=null),r},CGn=s=>Kts(s,kGn);let _4t=!0,v$e,b$e;const AGn=s=>{if(_4t){v$e=new Int32Array(512),b$e=new Int32Array(32);let t=0;for(;t<144;)s.lens[t++]=8;for(;t<256;)s.lens[t++]=9;for(;t<280;)s.lens[t++]=7;for(;t<288;)s.lens[t++]=8;for(ate(zts,s.lens,0,288,v$e,0,s.work,{bits:9}),t=0;t<32;)s.lens[t++]=5;ate(Bts,s.lens,0,32,b$e,0,s.work,{bits:5}),_4t=!1}s.lencode=v$e,s.lenbits=9,s.distcode=b$e,s.distbits=5},Yts=(s,t,n,r)=>{let a;const i=s.state;return i.window===null&&(i.window=new Uint8Array(1<=i.wsize?(i.window.set(t.subarray(n-i.wsize,n),0),i.wnext=0,i.whave=i.wsize):(a=i.wsize-i.wnext,a>r&&(a=r),i.window.set(t.subarray(n-r,n-r+a),i.wnext),r-=a,r?(i.window.set(t.subarray(n-r,n),0),i.wnext=r,i.whave=i.wsize):(i.wnext+=a,i.wnext===i.wsize&&(i.wnext=0),i.whave{let n,r,a,i,l,o,c,d,u,h,m,f,g,x,y=0,v,b,w,S,C,E,I,P;const R=new Uint8Array(4);let D,O;const U=new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]);if(u9(s)||!s.output||!s.input&&s.avail_in!==0)return xk;n=s.state,n.mode===cA&&(n.mode=g$e),l=s.next_out,a=s.output,c=s.avail_out,i=s.next_in,r=s.input,o=s.avail_in,d=n.hold,u=n.bits,h=o,m=c,P=xB;e:for(;;)switch(n.mode){case DDe:if(n.wrap===0){n.mode=g$e;break}for(;u<16;){if(o===0)break e;o--,d+=r[i++]<>>8&255,n.check=o5(n.check,R,2,0),d=0,u=0,n.mode=J5t;break}if(n.head&&(n.head.done=!1),!(n.wrap&1)||(((d&255)<<8)+(d>>8))%31){s.msg="incorrect header check",n.mode=Fp;break}if((d&15)!==Q5t){s.msg="unknown compression method",n.mode=Fp;break}if(d>>>=4,u-=4,I=(d&15)+8,n.wbits===0&&(n.wbits=I),I>15||I>n.wbits){s.msg="invalid window size",n.mode=Fp;break}n.dmax=1<>8&1),n.flags&512&&n.wrap&4&&(R[0]=d&255,R[1]=d>>>8&255,n.check=o5(n.check,R,2,0)),d=0,u=0,n.mode=e4t;case e4t:for(;u<32;){if(o===0)break e;o--,d+=r[i++]<>>8&255,R[2]=d>>>16&255,R[3]=d>>>24&255,n.check=o5(n.check,R,4,0)),d=0,u=0,n.mode=t4t;case t4t:for(;u<16;){if(o===0)break e;o--,d+=r[i++]<>8),n.flags&512&&n.wrap&4&&(R[0]=d&255,R[1]=d>>>8&255,n.check=o5(n.check,R,2,0)),d=0,u=0,n.mode=s4t;case s4t:if(n.flags&1024){for(;u<16;){if(o===0)break e;o--,d+=r[i++]<>>8&255,n.check=o5(n.check,R,2,0)),d=0,u=0}else n.head&&(n.head.extra=null);n.mode=n4t;case n4t:if(n.flags&1024&&(f=n.length,f>o&&(f=o),f&&(n.head&&(I=n.head.extra_len-n.length,n.head.extra||(n.head.extra=new Uint8Array(n.head.extra_len)),n.head.extra.set(r.subarray(i,i+f),I)),n.flags&512&&n.wrap&4&&(n.check=o5(n.check,r,f,i)),o-=f,i+=f,n.length-=f),n.length))break e;n.length=0,n.mode=r4t;case r4t:if(n.flags&2048){if(o===0)break e;f=0;do I=r[i+f++],n.head&&I&&n.length<65536&&(n.head.name+=String.fromCharCode(I));while(I&&f>9&1,n.head.done=!0),s.adler=n.check=0,n.mode=cA;break;case o4t:for(;u<32;){if(o===0)break e;o--,d+=r[i++]<>>=u&7,u-=u&7,n.mode=y$e;break}for(;u<3;){if(o===0)break e;o--,d+=r[i++]<>>=1,u-=1,d&3){case 0:n.mode=l4t;break;case 1:if(AGn(n),n.mode=Sue,t===kue){d>>>=2,u-=2;break e}break;case 2:n.mode=d4t;break;case 3:s.msg="invalid block type",n.mode=Fp}d>>>=2,u-=2;break;case l4t:for(d>>>=u&7,u-=u&7;u<32;){if(o===0)break e;o--,d+=r[i++]<>>16^65535)){s.msg="invalid stored block lengths",n.mode=Fp;break}if(n.length=d&65535,d=0,u=0,n.mode=x$e,t===kue)break e;case x$e:n.mode=c4t;case c4t:if(f=n.length,f){if(f>o&&(f=o),f>c&&(f=c),f===0)break e;a.set(r.subarray(i,i+f),l),o-=f,i+=f,c-=f,l+=f,n.length-=f;break}n.mode=cA;break;case d4t:for(;u<14;){if(o===0)break e;o--,d+=r[i++]<>>=5,u-=5,n.ndist=(d&31)+1,d>>>=5,u-=5,n.ncode=(d&15)+4,d>>>=4,u-=4,n.nlen>286||n.ndist>30){s.msg="too many length or distance symbols",n.mode=Fp;break}n.have=0,n.mode=u4t;case u4t:for(;n.have>>=3,u-=3}for(;n.have<19;)n.lens[U[n.have++]]=0;if(n.lencode=n.lendyn,n.lenbits=7,D={bits:n.lenbits},P=ate(xGn,n.lens,0,19,n.lencode,0,n.work,D),n.lenbits=D.bits,P){s.msg="invalid code lengths set",n.mode=Fp;break}n.have=0,n.mode=h4t;case h4t:for(;n.have>>24,b=y>>>16&255,w=y&65535,!(v<=u);){if(o===0)break e;o--,d+=r[i++]<>>=v,u-=v,n.lens[n.have++]=w;else{if(w===16){for(O=v+2;u>>=v,u-=v,n.have===0){s.msg="invalid bit length repeat",n.mode=Fp;break}I=n.lens[n.have-1],f=3+(d&3),d>>>=2,u-=2}else if(w===17){for(O=v+3;u>>=v,u-=v,I=0,f=3+(d&7),d>>>=3,u-=3}else{for(O=v+7;u>>=v,u-=v,I=0,f=11+(d&127),d>>>=7,u-=7}if(n.have+f>n.nlen+n.ndist){s.msg="invalid bit length repeat",n.mode=Fp;break}for(;f--;)n.lens[n.have++]=I}}if(n.mode===Fp)break;if(n.lens[256]===0){s.msg="invalid code -- missing end-of-block",n.mode=Fp;break}if(n.lenbits=9,D={bits:n.lenbits},P=ate(zts,n.lens,0,n.nlen,n.lencode,0,n.work,D),n.lenbits=D.bits,P){s.msg="invalid literal/lengths set",n.mode=Fp;break}if(n.distbits=6,n.distcode=n.distdyn,D={bits:n.distbits},P=ate(Bts,n.lens,n.nlen,n.ndist,n.distcode,0,n.work,D),n.distbits=D.bits,P){s.msg="invalid distances set",n.mode=Fp;break}if(n.mode=Sue,t===kue)break e;case Sue:n.mode=Cue;case Cue:if(o>=6&&c>=258){s.next_out=l,s.avail_out=c,s.next_in=i,s.avail_in=o,n.hold=d,n.bits=u,uGn(s,m),l=s.next_out,a=s.output,c=s.avail_out,i=s.next_in,r=s.input,o=s.avail_in,d=n.hold,u=n.bits,n.mode===cA&&(n.back=-1);break}for(n.back=0;y=n.lencode[d&(1<>>24,b=y>>>16&255,w=y&65535,!(v<=u);){if(o===0)break e;o--,d+=r[i++]<>S)],v=y>>>24,b=y>>>16&255,w=y&65535,!(S+v<=u);){if(o===0)break e;o--,d+=r[i++]<>>=S,u-=S,n.back+=S}if(d>>>=v,u-=v,n.back+=v,n.length=w,b===0){n.mode=x4t;break}if(b&32){n.back=-1,n.mode=cA;break}if(b&64){s.msg="invalid literal/length code",n.mode=Fp;break}n.extra=b&15,n.mode=m4t;case m4t:if(n.extra){for(O=n.extra;u>>=n.extra,u-=n.extra,n.back+=n.extra}n.was=n.length,n.mode=f4t;case f4t:for(;y=n.distcode[d&(1<>>24,b=y>>>16&255,w=y&65535,!(v<=u);){if(o===0)break e;o--,d+=r[i++]<>S)],v=y>>>24,b=y>>>16&255,w=y&65535,!(S+v<=u);){if(o===0)break e;o--,d+=r[i++]<>>=S,u-=S,n.back+=S}if(d>>>=v,u-=v,n.back+=v,b&64){s.msg="invalid distance code",n.mode=Fp;break}n.offset=w,n.extra=b&15,n.mode=p4t;case p4t:if(n.extra){for(O=n.extra;u>>=n.extra,u-=n.extra,n.back+=n.extra}if(n.offset>n.dmax){s.msg="invalid distance too far back",n.mode=Fp;break}n.mode=g4t;case g4t:if(c===0)break e;if(f=m-c,n.offset>f){if(f=n.offset-f,f>n.whave&&n.sane){s.msg="invalid distance too far back",n.mode=Fp;break}f>n.wnext?(f-=n.wnext,g=n.wsize-f):g=n.wnext-f,f>n.length&&(f=n.length),x=n.window}else x=a,g=l-n.offset,f=n.length;f>c&&(f=c),c-=f,n.length-=f;do a[l++]=x[g++];while(--f);n.length===0&&(n.mode=Cue);break;case x4t:if(c===0)break e;a[l++]=n.length,c--,n.mode=Cue;break;case y$e:if(n.wrap){for(;u<32;){if(o===0)break e;o--,d|=r[i++]<{if(u9(s))return xk;let t=s.state;return t.window&&(t.window=null),s.state=null,xB},MGn=(s,t)=>{if(u9(s))return xk;const n=s.state;return n.wrap&2?(n.head=t,t.done=!1,xB):xk},PGn=(s,t)=>{const n=t.length;let r,a,i;return u9(s)||(r=s.state,r.wrap!==0&&r.mode!==hPe)?xk:r.mode===hPe&&(a=1,a=mZe(a,t,n,0),a!==r.check)?$ts:(i=Yts(s,t,n,n),i?(r.mode=qts,Uts):(r.havedict=1,xB))};var IGn=Gts,LGn=Wts,RGn=Hts,DGn=CGn,FGn=Kts,OGn=EGn,zGn=TGn,BGn=MGn,$Gn=PGn,UGn="pako inflate (from Nodeca project)",P5={inflateReset:IGn,inflateReset2:LGn,inflateResetKeep:RGn,inflateInit:DGn,inflateInit2:FGn,inflate:OGn,inflateEnd:zGn,inflateGetHeader:BGn,inflateSetDictionary:$Gn,inflateInfo:UGn};function qGn(){this.text=0,this.time=0,this.xflags=0,this.os=0,this.extra=null,this.extra_len=0,this.name="",this.comment="",this.hcrc=0,this.done=!1}var VGn=qGn;const Zts=Object.prototype.toString,{Z_NO_FLUSH:HGn,Z_FINISH:w4t,Z_OK:OV,Z_STREAM_END:_$e,Z_NEED_DICT:w$e,Z_STREAM_ERROR:GGn,Z_DATA_ERROR:j4t,Z_MEM_ERROR:WGn,Z_BUF_ERROR:N4t}=Dts,KGn={chunkSize:1024*64,windowBits:15,to:""};function Gie(s){this.options=Fts.assign({},KGn,s||{});const t=this.options;t.raw&&t.windowBits>=0&&t.windowBits<16&&(t.windowBits=-t.windowBits,t.windowBits===0&&(t.windowBits=-15)),t.windowBits>=0&&t.windowBits<16&&!(s&&s.windowBits)&&(t.windowBits+=32),t.windowBits>15&&t.windowBits<48&&(t.windowBits&15||(t.windowBits|=15)),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new cGn,this.strm.avail_out=0;let n=P5.inflateInit2(this.strm,t.windowBits);if(n!==OV)throw new Error(fZe[n]);if(this.header=new VGn,P5.inflateGetHeader(this.strm,this.header),t.dictionary&&(typeof t.dictionary=="string"?t.dictionary=pZe.string2buf(t.dictionary):Zts.call(t.dictionary)==="[object ArrayBuffer]"&&(t.dictionary=new Uint8Array(t.dictionary)),t.raw&&(n=P5.inflateSetDictionary(this.strm,t.dictionary),n!==OV)))throw new Error(fZe[n])}Gie.prototype.push=function(s,t){const n=this.strm,r=this.options.chunkSize,a=this.options.dictionary;let i,l,o;if(this.ended)return!1;for(t===~~t?l=t:l=t===!0?w4t:HGn,Zts.call(s)==="[object ArrayBuffer]"?n.input=new Uint8Array(s):n.input=s,n.next_in=0,n.avail_in=n.input.length;;){for(n.avail_out===0&&(n.output=new Uint8Array(r),n.next_out=0,n.avail_out=r),i=P5.inflate(n,l),i===w$e&&a&&(i=P5.inflateSetDictionary(n,a),i===OV?i=P5.inflate(n,l):i===j4t&&(i=w$e));n.avail_in>0&&i===_$e&&n.state.wrap&2&&n.state.flags!==0&&n.input[n.next_in]!==0;)P5.inflateReset(n),i=P5.inflate(n,l);switch(i){case GGn:case j4t:case w$e:case WGn:return this.onEnd(i),this.ended=!0,!1}if(o=n.avail_out,n.next_out&&(n.avail_out===0||i===_$e||l>0))if(this.options.to==="string"){let c=pZe.utf8border(n.output,n.next_out),d=n.next_out-c,u=pZe.buf2string(n.output,c);n.next_out=d,n.avail_out=r-d,d&&n.output.set(n.output.subarray(c,c+d),0),this.onData(u)}else this.onData(n.output.length===n.next_out?n.output:n.output.subarray(0,n.next_out)),n.avail_out=0,n.next_out=0;if(!((i===OV||i===N4t)&&o===0)){if(i===_$e)return i=P5.inflateEnd(this.strm),this.onEnd(i),this.ended=!0,!0;if(n.avail_in===0){if(l===w4t)return i=P5.inflateEnd(this.strm),this.onEnd(i===OV?N4t:i),this.ended=!0,!1;break}}}return!0};Gie.prototype.onData=function(s){this.chunks.push(s)};Gie.prototype.onEnd=function(s){s===OV&&(this.options.to==="string"?this.result=this.chunks.join(""):this.result=Fts.flattenChunks(this.chunks)),this.chunks=[],this.err=s,this.msg=this.strm.msg};function YGn(s,t){const n=new Gie(t);if(n.push(s,!0),n.err)throw n.msg||fZe[n.err];return n.result}var ZGn=Gie,XGn=YGn,QGn={Inflate:ZGn,inflate:XGn};const{Inflate:JGn,inflate:eWn}=QGn;var k4t=JGn,tWn=eWn;const Xts=[];for(let s=0;s<256;s++){let t=s;for(let n=0;n<8;n++)t&1?t=3988292384^t>>>1:t=t>>>1;Xts[s]=t}const S4t=4294967295;function sWn(s,t,n){let r=s;for(let a=0;a>>8;return r}function nWn(s,t){return(sWn(S4t,s,t)^S4t)>>>0}function C4t(s,t,n){const r=s.readUint32(),a=nWn(new Uint8Array(s.buffer,s.byteOffset+s.offset-t-4,t),t);if(a!==r)throw new Error(`CRC mismatch for chunk ${n}. Expected ${r}, found ${a}`)}function Qts(s,t,n){for(let r=0;r>1)&255}else{for(;i>1)&255;for(;i>1)&255}}function sss(s,t,n,r,a){let i=0;if(n.length===0){for(;i=n||E>=r))for(let I=0;I>8&255}const uWn=new Uint16Array([255]),hWn=new Uint8Array(uWn.buffer),mWn=hWn[0]===255,fWn=new Uint8Array(0);function A4t(s){const{data:t,width:n,height:r,channels:a,depth:i}=s,l=Math.ceil(i/8)*a,o=Math.ceil(i/8*a*n),c=new Uint8Array(r*o);let d=fWn,u=0,h,m;for(let f=0;f>8&255}const P3e=Uint8Array.of(137,80,78,71,13,10,26,10);function E4t(s){if(!gWn(s.readBytes(P3e.length)))throw new Error("wrong PNG signature")}function gWn(s){if(s.length79)throw new Error("keyword length must be between 1 and 79")}const bWn=/^[\u0000-\u00FF]*$/;function _Wn(s){if(!bWn.test(s))throw new Error("invalid latin1 text")}function wWn(s,t,n){const r=rss(t);s[r]=jWn(t,n-r.length-1)}function rss(s){for(s.mark();s.readByte()!==yWn;);const t=s.offset;s.reset();const n=nss.decode(s.readBytes(t-s.offset-1));return s.skip(1),vWn(n),n}function jWn(s,t){return nss.decode(s.readBytes(t))}const Nj={UNKNOWN:-1,GREYSCALE:0,TRUECOLOUR:2,INDEXED_COLOUR:3,GREYSCALE_ALPHA:4,TRUECOLOUR_ALPHA:6},j$e={UNKNOWN:-1,DEFLATE:0},T4t={UNKNOWN:-1,ADAPTIVE:0},N$e={UNKNOWN:-1,NO_INTERLACE:0,ADAM7:1},Aue={NONE:0,BACKGROUND:1,PREVIOUS:2},k$e={SOURCE:0,OVER:1};class NWn extends Aot{constructor(n,r={}){super(n);Nr(this,"_checkCrc");Nr(this,"_inflator");Nr(this,"_png");Nr(this,"_apng");Nr(this,"_end");Nr(this,"_hasPalette");Nr(this,"_palette");Nr(this,"_hasTransparency");Nr(this,"_transparency");Nr(this,"_compressionMethod");Nr(this,"_filterMethod");Nr(this,"_interlaceMethod");Nr(this,"_colorType");Nr(this,"_isAnimated");Nr(this,"_numberOfFrames");Nr(this,"_numberOfPlays");Nr(this,"_frames");Nr(this,"_writingDataChunks");const{checkCrc:a=!1}=r;this._checkCrc=a,this._inflator=new k4t,this._png={width:-1,height:-1,channels:-1,data:new Uint8Array(0),depth:1,text:{}},this._apng={width:-1,height:-1,channels:-1,depth:1,numberOfFrames:1,numberOfPlays:0,text:{},frames:[]},this._end=!1,this._hasPalette=!1,this._palette=[],this._hasTransparency=!1,this._transparency=new Uint16Array(0),this._compressionMethod=j$e.UNKNOWN,this._filterMethod=T4t.UNKNOWN,this._interlaceMethod=N$e.UNKNOWN,this._colorType=Nj.UNKNOWN,this._isAnimated=!1,this._numberOfFrames=1,this._numberOfPlays=0,this._frames=[],this._writingDataChunks=!1,this.setBigEndian()}decode(){for(E4t(this);!this._end;){const n=this.readUint32(),r=this.readChars(4);this.decodeChunk(n,r)}return this.decodeImage(),this._png}decodeApng(){for(E4t(this);!this._end;){const n=this.readUint32(),r=this.readChars(4);this.decodeApngChunk(n,r)}return this.decodeApngImage(),this._apng}decodeChunk(n,r){const a=this.offset;switch(r){case"IHDR":this.decodeIHDR();break;case"PLTE":this.decodePLTE(n);break;case"IDAT":this.decodeIDAT(n);break;case"IEND":this._end=!0;break;case"tRNS":this.decodetRNS(n);break;case"iCCP":this.decodeiCCP(n);break;case xWn:wWn(this._png.text,this,n);break;case"pHYs":this.decodepHYs();break;default:this.skip(n);break}if(this.offset-a!==n)throw new Error(`Length mismatch while decoding chunk ${r}`);this._checkCrc?C4t(this,n+4,r):this.skip(4)}decodeApngChunk(n,r){const a=this.offset;switch(r!=="fdAT"&&r!=="IDAT"&&this._writingDataChunks&&this.pushDataToFrame(),r){case"acTL":this.decodeACTL();break;case"fcTL":this.decodeFCTL();break;case"fdAT":this.decodeFDAT(n);break;default:this.decodeChunk(n,r),this.offset=a+n;break}if(this.offset-a!==n)throw new Error(`Length mismatch while decoding chunk ${r}`);this._checkCrc?C4t(this,n+4,r):this.skip(4)}decodeIHDR(){const n=this._png;n.width=this.readUint32(),n.height=this.readUint32(),n.depth=kWn(this.readUint8());const r=this.readUint8();this._colorType=r;let a;switch(r){case Nj.GREYSCALE:a=1;break;case Nj.TRUECOLOUR:a=3;break;case Nj.INDEXED_COLOUR:a=1;break;case Nj.GREYSCALE_ALPHA:a=2;break;case Nj.TRUECOLOUR_ALPHA:a=4;break;case Nj.UNKNOWN:default:throw new Error(`Unknown color type: ${r}`)}if(this._png.channels=a,this._compressionMethod=this.readUint8(),this._compressionMethod!==j$e.DEFLATE)throw new Error(`Unsupported compression method: ${this._compressionMethod}`);this._filterMethod=this.readUint8(),this._interlaceMethod=this.readUint8()}decodeACTL(){this._numberOfFrames=this.readUint32(),this._numberOfPlays=this.readUint32(),this._isAnimated=!0}decodeFCTL(){const n={sequenceNumber:this.readUint32(),width:this.readUint32(),height:this.readUint32(),xOffset:this.readUint32(),yOffset:this.readUint32(),delayNumber:this.readUint16(),delayDenominator:this.readUint16(),disposeOp:this.readUint8(),blendOp:this.readUint8(),data:new Uint8Array(0)};this._frames.push(n)}decodePLTE(n){if(n%3!==0)throw new RangeError(`PLTE field length must be a multiple of 3. Got ${n}`);const r=n/3;this._hasPalette=!0;const a=[];this._palette=a;for(let i=0;ithis._png.width*this._png.height)throw new Error(`tRNS chunk contains more alpha values than there are pixels (${n/2} vs ${this._png.width*this._png.height})`);this._hasTransparency=!0,this._transparency=new Uint16Array(n/2);for(let r=0;rthis._palette.length)throw new Error(`tRNS chunk contains more alpha values than there are palette colors (${n} vs ${this._palette.length})`);let r=0;for(;r{const c=((l+r.yOffset)*this._png.width+r.xOffset+o)*this._png.channels,d=(l*r.width+o)*this._png.channels;return{index:c,frameIndex:d}};switch(r.blendOp){case k$e.SOURCE:for(let l=0;l=200&&t.status<=299}function Eue(s){try{s.dispatchEvent(new MouseEvent("click"))}catch{var t=document.createEvent("MouseEvents");t.initMouseEvent("click",!0,!0,window,0,0,0,80,20,!1,!1,!1,!1,0,null),s.dispatchEvent(t)}}var qO=Oc.saveAs||((typeof window>"u"?"undefined":Pm(window))!=="object"||window!==Oc?function(){}:typeof HTMLAnchorElement<"u"&&"download"in HTMLAnchorElement.prototype?function(s,t,n){var r=Oc.URL||Oc.webkitURL,a=document.createElement("a");t=t||s.name||"download",a.download=t,a.rel="noopener",typeof s=="string"?(a.href=s,a.origin!==location.origin?P4t(a.href)?C$e(s,t,n):Eue(a,a.target="_blank"):Eue(a)):(a.href=r.createObjectURL(s),setTimeout(function(){r.revokeObjectURL(a.href)},4e4),setTimeout(function(){Eue(a)},0))}:"msSaveOrOpenBlob"in navigator?function(s,t,n){if(t=t||s.name||"download",typeof s=="string")if(P4t(s))C$e(s,t,n);else{var r=document.createElement("a");r.href=s,r.target="_blank",setTimeout(function(){Eue(r)})}else navigator.msSaveOrOpenBlob(function(a,i){return i===void 0?i={autoBom:!1}:Pm(i)!=="object"&&(vf.warn("Deprecated: Expected third argument to be a object"),i={autoBom:!i}),i.autoBom&&/^\s*(?:text\/\S*|application\/xml|\S*\/\S*\+xml)\s*;.*charset\s*=\s*utf-8/i.test(a.type)?new Blob(["\uFEFF",a],{type:a.type}):a}(s,n),t)}:function(s,t,n,r){if((r=r||open("","_blank"))&&(r.document.title=r.document.body.innerText="downloading..."),typeof s=="string")return C$e(s,t,n);var a=s.type==="application/octet-stream",i=/constructor/i.test(Oc.HTMLElement)||Oc.safari,l=/CriOS\/[\d]+/.test(navigator.userAgent);if((l||a&&i)&&(typeof FileReader>"u"?"undefined":Pm(FileReader))==="object"){var o=new FileReader;o.onloadend=function(){var u=o.result;u=l?u:u.replace(/^data:[^;]*;/,"data:attachment/file;"),r?r.location.href=u:location=u,r=null},o.readAsDataURL(s)}else{var c=Oc.URL||Oc.webkitURL,d=c.createObjectURL(s);r?r.location=d:location.href=d,r=null,setTimeout(function(){c.revokeObjectURL(d)},4e4)}});/** * A class to parse color values * @author Stoyan Stefanov * {@link http://www.phpied.com/rgb-color-parser-in-javascript/} * @license Use it if you like it */function ass(s){var t;s=s||"",this.ok=!1,s.charAt(0)=="#"&&(s=s.substr(1,6)),s={aliceblue:"f0f8ff",antiquewhite:"faebd7",aqua:"00ffff",aquamarine:"7fffd4",azure:"f0ffff",beige:"f5f5dc",bisque:"ffe4c4",black:"000000",blanchedalmond:"ffebcd",blue:"0000ff",blueviolet:"8a2be2",brown:"a52a2a",burlywood:"deb887",cadetblue:"5f9ea0",chartreuse:"7fff00",chocolate:"d2691e",coral:"ff7f50",cornflowerblue:"6495ed",cornsilk:"fff8dc",crimson:"dc143c",cyan:"00ffff",darkblue:"00008b",darkcyan:"008b8b",darkgoldenrod:"b8860b",darkgray:"a9a9a9",darkgreen:"006400",darkkhaki:"bdb76b",darkmagenta:"8b008b",darkolivegreen:"556b2f",darkorange:"ff8c00",darkorchid:"9932cc",darkred:"8b0000",darksalmon:"e9967a",darkseagreen:"8fbc8f",darkslateblue:"483d8b",darkslategray:"2f4f4f",darkturquoise:"00ced1",darkviolet:"9400d3",deeppink:"ff1493",deepskyblue:"00bfff",dimgray:"696969",dodgerblue:"1e90ff",feldspar:"d19275",firebrick:"b22222",floralwhite:"fffaf0",forestgreen:"228b22",fuchsia:"ff00ff",gainsboro:"dcdcdc",ghostwhite:"f8f8ff",gold:"ffd700",goldenrod:"daa520",gray:"808080",green:"008000",greenyellow:"adff2f",honeydew:"f0fff0",hotpink:"ff69b4",indianred:"cd5c5c",indigo:"4b0082",ivory:"fffff0",khaki:"f0e68c",lavender:"e6e6fa",lavenderblush:"fff0f5",lawngreen:"7cfc00",lemonchiffon:"fffacd",lightblue:"add8e6",lightcoral:"f08080",lightcyan:"e0ffff",lightgoldenrodyellow:"fafad2",lightgrey:"d3d3d3",lightgreen:"90ee90",lightpink:"ffb6c1",lightsalmon:"ffa07a",lightseagreen:"20b2aa",lightskyblue:"87cefa",lightslateblue:"8470ff",lightslategray:"778899",lightsteelblue:"b0c4de",lightyellow:"ffffe0",lime:"00ff00",limegreen:"32cd32",linen:"faf0e6",magenta:"ff00ff",maroon:"800000",mediumaquamarine:"66cdaa",mediumblue:"0000cd",mediumorchid:"ba55d3",mediumpurple:"9370d8",mediumseagreen:"3cb371",mediumslateblue:"7b68ee",mediumspringgreen:"00fa9a",mediumturquoise:"48d1cc",mediumvioletred:"c71585",midnightblue:"191970",mintcream:"f5fffa",mistyrose:"ffe4e1",moccasin:"ffe4b5",navajowhite:"ffdead",navy:"000080",oldlace:"fdf5e6",olive:"808000",olivedrab:"6b8e23",orange:"ffa500",orangered:"ff4500",orchid:"da70d6",palegoldenrod:"eee8aa",palegreen:"98fb98",paleturquoise:"afeeee",palevioletred:"d87093",papayawhip:"ffefd5",peachpuff:"ffdab9",peru:"cd853f",pink:"ffc0cb",plum:"dda0dd",powderblue:"b0e0e6",purple:"800080",red:"ff0000",rosybrown:"bc8f8f",royalblue:"4169e1",saddlebrown:"8b4513",salmon:"fa8072",sandybrown:"f4a460",seagreen:"2e8b57",seashell:"fff5ee",sienna:"a0522d",silver:"c0c0c0",skyblue:"87ceeb",slateblue:"6a5acd",slategray:"708090",snow:"fffafa",springgreen:"00ff7f",steelblue:"4682b4",tan:"d2b48c",teal:"008080",thistle:"d8bfd8",tomato:"ff6347",turquoise:"40e0d0",violet:"ee82ee",violetred:"d02090",wheat:"f5deb3",white:"ffffff",whitesmoke:"f5f5f5",yellow:"ffff00",yellowgreen:"9acd32"}[s=(s=s.replace(/ /g,"")).toLowerCase()]||s;for(var n=[{re:/^rgb\((\d{1,3}),\s*(\d{1,3}),\s*(\d{1,3})\)$/,example:["rgb(123, 234, 45)","rgb(255,234,245)"],process:function(o){return[parseInt(o[1]),parseInt(o[2]),parseInt(o[3])]}},{re:/^(\w{2})(\w{2})(\w{2})$/,example:["#00ff00","336699"],process:function(o){return[parseInt(o[1],16),parseInt(o[2],16),parseInt(o[3],16)]}},{re:/^(\w{1})(\w{1})(\w{1})$/,example:["#fb0","f0f"],process:function(o){return[parseInt(o[1]+o[1],16),parseInt(o[2]+o[2],16),parseInt(o[3]+o[3],16)]}}],r=0;r255?255:this.r,this.g=this.g<0||isNaN(this.g)?0:this.g>255?255:this.g,this.b=this.b<0||isNaN(this.b)?0:this.b>255?255:this.b,this.toRGB=function(){return"rgb("+this.r+", "+this.g+", "+this.b+")"},this.toHex=function(){var o=this.r.toString(16),c=this.g.toString(16),d=this.b.toString(16);return o.length==1&&(o="0"+o),c.length==1&&(c="0"+c),d.length==1&&(d="0"+d),"#"+o+c+d}}var I3e=Oc.atob.bind(Oc),I4t=Oc.btoa.bind(Oc);/** * @license * Joseph Myers does not specify a particular license for his work. * * Author: Joseph Myers * Accessed from: http://www.myersdaily.org/joseph/javascript/md5.js * * Modified by: Owen Leong */function A$e(s,t){var n=s[0],r=s[1],a=s[2],i=s[3];n=Qb(n,r,a,i,t[0],7,-680876936),i=Qb(i,n,r,a,t[1],12,-389564586),a=Qb(a,i,n,r,t[2],17,606105819),r=Qb(r,a,i,n,t[3],22,-1044525330),n=Qb(n,r,a,i,t[4],7,-176418897),i=Qb(i,n,r,a,t[5],12,1200080426),a=Qb(a,i,n,r,t[6],17,-1473231341),r=Qb(r,a,i,n,t[7],22,-45705983),n=Qb(n,r,a,i,t[8],7,1770035416),i=Qb(i,n,r,a,t[9],12,-1958414417),a=Qb(a,i,n,r,t[10],17,-42063),r=Qb(r,a,i,n,t[11],22,-1990404162),n=Qb(n,r,a,i,t[12],7,1804603682),i=Qb(i,n,r,a,t[13],12,-40341101),a=Qb(a,i,n,r,t[14],17,-1502002290),n=Jb(n,r=Qb(r,a,i,n,t[15],22,1236535329),a,i,t[1],5,-165796510),i=Jb(i,n,r,a,t[6],9,-1069501632),a=Jb(a,i,n,r,t[11],14,643717713),r=Jb(r,a,i,n,t[0],20,-373897302),n=Jb(n,r,a,i,t[5],5,-701558691),i=Jb(i,n,r,a,t[10],9,38016083),a=Jb(a,i,n,r,t[15],14,-660478335),r=Jb(r,a,i,n,t[4],20,-405537848),n=Jb(n,r,a,i,t[9],5,568446438),i=Jb(i,n,r,a,t[14],9,-1019803690),a=Jb(a,i,n,r,t[3],14,-187363961),r=Jb(r,a,i,n,t[8],20,1163531501),n=Jb(n,r,a,i,t[13],5,-1444681467),i=Jb(i,n,r,a,t[2],9,-51403784),a=Jb(a,i,n,r,t[7],14,1735328473),n=e1(n,r=Jb(r,a,i,n,t[12],20,-1926607734),a,i,t[5],4,-378558),i=e1(i,n,r,a,t[8],11,-2022574463),a=e1(a,i,n,r,t[11],16,1839030562),r=e1(r,a,i,n,t[14],23,-35309556),n=e1(n,r,a,i,t[1],4,-1530992060),i=e1(i,n,r,a,t[4],11,1272893353),a=e1(a,i,n,r,t[7],16,-155497632),r=e1(r,a,i,n,t[10],23,-1094730640),n=e1(n,r,a,i,t[13],4,681279174),i=e1(i,n,r,a,t[0],11,-358537222),a=e1(a,i,n,r,t[3],16,-722521979),r=e1(r,a,i,n,t[6],23,76029189),n=e1(n,r,a,i,t[9],4,-640364487),i=e1(i,n,r,a,t[12],11,-421815835),a=e1(a,i,n,r,t[15],16,530742520),n=t1(n,r=e1(r,a,i,n,t[2],23,-995338651),a,i,t[0],6,-198630844),i=t1(i,n,r,a,t[7],10,1126891415),a=t1(a,i,n,r,t[14],15,-1416354905),r=t1(r,a,i,n,t[5],21,-57434055),n=t1(n,r,a,i,t[12],6,1700485571),i=t1(i,n,r,a,t[3],10,-1894986606),a=t1(a,i,n,r,t[10],15,-1051523),r=t1(r,a,i,n,t[1],21,-2054922799),n=t1(n,r,a,i,t[8],6,1873313359),i=t1(i,n,r,a,t[15],10,-30611744),a=t1(a,i,n,r,t[6],15,-1560198380),r=t1(r,a,i,n,t[13],21,1309151649),n=t1(n,r,a,i,t[4],6,-145523070),i=t1(i,n,r,a,t[11],10,-1120210379),a=t1(a,i,n,r,t[2],15,718787259),r=t1(r,a,i,n,t[9],21,-343485551),s[0]=SI(n,s[0]),s[1]=SI(r,s[1]),s[2]=SI(a,s[2]),s[3]=SI(i,s[3])}function FDe(s,t,n,r,a,i){return t=SI(SI(t,s),SI(r,i)),SI(t<>>32-a,n)}function Qb(s,t,n,r,a,i,l){return FDe(t&n|~t&r,s,t,a,i,l)}function Jb(s,t,n,r,a,i,l){return FDe(t&r|n&~r,s,t,a,i,l)}function e1(s,t,n,r,a,i,l){return FDe(t^n^r,s,t,a,i,l)}function t1(s,t,n,r,a,i,l){return FDe(n^(t|~r),s,t,a,i,l)}function iss(s){var t,n=s.length,r=[1732584193,-271733879,-1732584194,271733878];for(t=64;t<=s.length;t+=64)A$e(r,CWn(s.substring(t-64,t)));s=s.substring(t-64);var a=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];for(t=0;t>2]|=s.charCodeAt(t)<<(t%4<<3);if(a[t>>2]|=128<<(t%4<<3),t>55)for(A$e(r,a),t=0;t<16;t++)a[t]=0;return a[14]=8*n,A$e(r,a),r}function CWn(s){var t,n=[];for(t=0;t<64;t+=4)n[t>>2]=s.charCodeAt(t)+(s.charCodeAt(t+1)<<8)+(s.charCodeAt(t+2)<<16)+(s.charCodeAt(t+3)<<24);return n}var L4t="0123456789abcdef".split("");function AWn(s){for(var t="",n=0;n<4;n++)t+=L4t[s>>8*n+4&15]+L4t[s>>8*n&15];return t}function EWn(s){return String.fromCharCode(255&s,(65280&s)>>8,(16711680&s)>>16,(4278190080&s)>>24)}function gZe(s){return iss(s).map(EWn).join("")}var TWn=function(s){for(var t=0;t>16)+(t>>16)+(n>>16)<<16|65535&n}return s+t&4294967295}/** * @license * FPDF is released under a permissive license: there is no usage restriction. * You may embed it freely in your application (commercial or not), with or * without modifications. * * Reference: http://www.fpdf.org/en/script/script37.php */function xZe(s,t){var n,r,a,i;if(s!==n){for(var l=(a=s,i=1+(256/s.length|0),new Array(i+1).join(a)),o=[],c=0;c<256;c++)o[c]=c;var d=0;for(c=0;c<256;c++){var u=o[c];d=(d+u+l.charCodeAt(c))%256,o[c]=o[d],o[d]=u}n=s,r=o}else o=r;var h=t.length,m=0,f=0,g="";for(c=0;c€/\f©þdSiz";var i=(t+this.padding).substr(0,32),l=(n+this.padding).substr(0,32);this.O=this.processOwnerPassword(i,l),this.P=-(1+(255^a)),this.encryptionKey=gZe(i+this.O+this.lsbFirstWord(this.P)+this.hexToBytes(r)).substr(0,5),this.U=xZe(this.encryptionKey,this.padding)}function CU(s){if(/[^\u0000-\u00ff]/.test(s))throw new Error("Invalid PDF Name Object: "+s+", Only accept ASCII characters.");for(var t="",n=s.length,r=0;r126?"#"+("0"+a.toString(16)).slice(-2):s[r]}return t}function D4t(s){if(Pm(s)!=="object")throw new Error("Invalid Context passed to initialize PubSub (jsPDF-module)");var t={};this.subscribe=function(n,r,a){if(a=a||!1,typeof n!="string"||typeof r!="function"||typeof a!="boolean")throw new Error("Invalid arguments passed to PubSub.subscribe (jsPDF-module)");t.hasOwnProperty(n)||(t[n]={});var i=Math.random().toString(35);return t[n][i]=[r,!!a],i},this.unsubscribe=function(n){for(var r in t)if(t[r][n])return delete t[r][n],Object.keys(t[r]).length===0&&delete t[r],!0;return!1},this.publish=function(n){if(t.hasOwnProperty(n)){var r=Array.prototype.slice.call(arguments,1),a=[];for(var i in t[n]){var l=t[n][i];try{l[0].apply(s,r)}catch(o){Oc.console&&vf.error("jsPDF PubSub Error",o.message,o)}l[1]&&a.push(i)}a.length&&a.forEach(this.unsubscribe)}},this.getTopics=function(){return t}}function mPe(s){if(!(this instanceof mPe))return new mPe(s);var t="opacity,stroke-opacity".split(",");for(var n in s)s.hasOwnProperty(n)&&t.indexOf(n)>=0&&(this[n]=s[n]);this.id="",this.objectNumber=-1}function oss(s,t){this.gState=s,this.matrix=t,this.id="",this.objectNumber=-1}function t8(s,t,n,r,a){if(!(this instanceof t8))return new t8(s,t,n,r,a);this.type=s==="axial"?2:3,this.coords=t,this.colors=n,oss.call(this,r,a)}function pq(s,t,n,r,a){if(!(this instanceof pq))return new pq(s,t,n,r,a);this.boundingBox=s,this.xStep=t,this.yStep=n,this.stream="",this.cloneIndex=0,oss.call(this,r,a)}function Go(s){var t,n=typeof arguments[0]=="string"?arguments[0]:"p",r=arguments[1],a=arguments[2],i=arguments[3],l=[],o=1,c=16,d="S",u=null;Pm(s=s||{})==="object"&&(n=s.orientation,r=s.unit||r,a=s.format||a,i=s.compress||s.compressPdf||i,(u=s.encryption||null)!==null&&(u.userPassword=u.userPassword||"",u.ownerPassword=u.ownerPassword||"",u.userPermissions=u.userPermissions||[]),o=typeof s.userUnit=="number"?Math.abs(s.userUnit):1,s.precision!==void 0&&(t=s.precision),s.floatPrecision!==void 0&&(c=s.floatPrecision),d=s.defaultPathOperation||"S"),l=s.filters||(i===!0?["FlateEncode"]:l),r=r||"mm",n=(""+(n||"P")).toLowerCase();var h=s.putOnlyUsedFonts||!1,m={},f={internal:{},__private__:{}};f.__private__.PubSub=D4t;var g="1.3",x=f.__private__.getPdfVersion=function(){return g};f.__private__.setPdfVersion=function(Je){g=Je};var y={a0:[2383.94,3370.39],a1:[1683.78,2383.94],a2:[1190.55,1683.78],a3:[841.89,1190.55],a4:[595.28,841.89],a5:[419.53,595.28],a6:[297.64,419.53],a7:[209.76,297.64],a8:[147.4,209.76],a9:[104.88,147.4],a10:[73.7,104.88],b0:[2834.65,4008.19],b1:[2004.09,2834.65],b2:[1417.32,2004.09],b3:[1000.63,1417.32],b4:[708.66,1000.63],b5:[498.9,708.66],b6:[354.33,498.9],b7:[249.45,354.33],b8:[175.75,249.45],b9:[124.72,175.75],b10:[87.87,124.72],c0:[2599.37,3676.54],c1:[1836.85,2599.37],c2:[1298.27,1836.85],c3:[918.43,1298.27],c4:[649.13,918.43],c5:[459.21,649.13],c6:[323.15,459.21],c7:[229.61,323.15],c8:[161.57,229.61],c9:[113.39,161.57],c10:[79.37,113.39],dl:[311.81,623.62],letter:[612,792],"government-letter":[576,756],legal:[612,1008],"junior-legal":[576,360],ledger:[1224,792],tabloid:[792,1224],"credit-card":[153,243]};f.__private__.getPageFormats=function(){return y};var v=f.__private__.getPageFormat=function(Je){return y[Je]};a=a||"a4";var b="compat",w="advanced",S=b;function C(){this.saveGraphicsState(),Ae(new As(ts,0,0,-ts,0,vr()*ts).toString()+" cm"),this.setFontSize(this.getFontSize()/ts),d="n",S=w}function E(){this.restoreGraphicsState(),d="S",S=b}var I=f.__private__.combineFontStyleAndFontWeight=function(Je,Ht){if(Je=="bold"&&Ht=="normal"||Je=="bold"&&Ht==400||Je=="normal"&&Ht=="italic"||Je=="bold"&&Ht=="italic")throw new Error("Invalid Combination of fontweight and fontstyle");return Ht&&(Je=Ht==400||Ht==="normal"?Je==="italic"?"italic":"normal":Ht!=700&&Ht!=="bold"||Je!=="normal"?(Ht==700?"bold":Ht)+""+Je:"bold"),Je};f.advancedAPI=function(Je){var Ht=S===b;return Ht&&C.call(this),typeof Je!="function"||(Je(this),Ht&&E.call(this)),this},f.compatAPI=function(Je){var Ht=S===w;return Ht&&E.call(this),typeof Je!="function"||(Je(this),Ht&&C.call(this)),this},f.isAdvancedAPI=function(){return S===w};var P,R=function(Je){if(S!==w)throw new Error(Je+" is only available in 'advanced' API mode. You need to call advancedAPI() first.")},D=f.roundToPrecision=f.__private__.roundToPrecision=function(Je,Ht){var Ts=t||Ht;if(isNaN(Je)||isNaN(Ts))throw new Error("Invalid argument passed to jsPDF.roundToPrecision");return Je.toFixed(Ts).replace(/0+$/,"")};P=f.hpf=f.__private__.hpf=typeof c=="number"?function(Je){if(isNaN(Je))throw new Error("Invalid argument passed to jsPDF.hpf");return D(Je,c)}:c==="smart"?function(Je){if(isNaN(Je))throw new Error("Invalid argument passed to jsPDF.hpf");return D(Je,Je>-1&&Je<1?16:5)}:function(Je){if(isNaN(Je))throw new Error("Invalid argument passed to jsPDF.hpf");return D(Je,16)};var O=f.f2=f.__private__.f2=function(Je){if(isNaN(Je))throw new Error("Invalid argument passed to jsPDF.f2");return D(Je,2)},U=f.__private__.f3=function(Je){if(isNaN(Je))throw new Error("Invalid argument passed to jsPDF.f3");return D(Je,3)},W=f.scale=f.__private__.scale=function(Je){if(isNaN(Je))throw new Error("Invalid argument passed to jsPDF.scale");return S===b?Je*ts:S===w?Je:void 0},V=function(Je){return W(function(Ht){return S===b?vr()-Ht:S===w?Ht:void 0}(Je))};f.__private__.setPrecision=f.setPrecision=function(Je){typeof parseInt(Je,10)=="number"&&(t=parseInt(Je,10))};var G,Y="00000000000000000000000000000000",X=f.__private__.getFileId=function(){return Y},ae=f.__private__.setFileId=function(Je){return Y=Je!==void 0&&/^[a-fA-F0-9]{32}$/.test(Je)?Je.toUpperCase():Y.split("").map(function(){return"ABCDEF0123456789".charAt(Math.floor(16*Math.random()))}).join(""),u!==null&&(yc=new SU(u.userPermissions,u.userPassword,u.ownerPassword,Y)),Y};f.setFileId=function(Je){return ae(Je),this},f.getFileId=function(){return X()};var ie=f.__private__.convertDateToPDFDate=function(Je){var Ht=Je.getTimezoneOffset(),Ts=Ht<0?"+":"-",ln=Math.floor(Math.abs(Ht/60)),tn=Math.abs(Ht%60),nr=[Ts,_e(ln),"'",_e(tn),"'"].join("");return["D:",Je.getFullYear(),_e(Je.getMonth()+1),_e(Je.getDate()),_e(Je.getHours()),_e(Je.getMinutes()),_e(Je.getSeconds()),nr].join("")},ne=f.__private__.convertPDFDateToDate=function(Je){var Ht=parseInt(Je.substr(2,4),10),Ts=parseInt(Je.substr(6,2),10)-1,ln=parseInt(Je.substr(8,2),10),tn=parseInt(Je.substr(10,2),10),nr=parseInt(Je.substr(12,2),10),rr=parseInt(Je.substr(14,2),10);return new Date(Ht,Ts,ln,tn,nr,rr,0)},te=f.__private__.setCreationDate=function(Je){var Ht;if(Je===void 0&&(Je=new Date),Je instanceof Date)Ht=ie(Je);else{if(!/^D:(20[0-2][0-9]|203[0-7]|19[7-9][0-9])(0[0-9]|1[0-2])([0-2][0-9]|3[0-1])(0[0-9]|1[0-9]|2[0-3])(0[0-9]|[1-5][0-9])(0[0-9]|[1-5][0-9])(\+0[0-9]|\+1[0-4]|-0[0-9]|-1[0-1])'(0[0-9]|[1-5][0-9])'?$/.test(Je))throw new Error("Invalid argument passed to jsPDF.setCreationDate");Ht=Je}return G=Ht},J=f.__private__.getCreationDate=function(Je){var Ht=G;return Je==="jsDate"&&(Ht=ne(G)),Ht};f.setCreationDate=function(Je){return te(Je),this},f.getCreationDate=function(Je){return J(Je)};var ce,_e=f.__private__.padd2=function(Je){return("0"+parseInt(Je)).slice(-2)},he=f.__private__.padd2Hex=function(Je){return("00"+(Je=Je.toString())).substr(Je.length)},ue=0,ve=[],Ee=[],Se=0,Le=[],Fe=[],ke=!1,Ve=Ee;f.__private__.setCustomOutputDestination=function(Je){ke=!0,Ve=Je};var je=function(Je){ke||(Ve=Je)};f.__private__.resetCustomOutputDestination=function(){ke=!1,Ve=Ee};var Ae=f.__private__.out=function(Je){return Je=Je.toString(),Se+=Je.length+1,Ve.push(Je),Ve},Ce=f.__private__.write=function(Je){return Ae(arguments.length===1?Je.toString():Array.prototype.join.call(arguments," "))},qe=f.__private__.getArrayBuffer=function(Je){for(var Ht=Je.length,Ts=new ArrayBuffer(Ht),ln=new Uint8Array(Ts);Ht--;)ln[Ht]=Je.charCodeAt(Ht);return Ts},ze=[["Helvetica","helvetica","normal","WinAnsiEncoding"],["Helvetica-Bold","helvetica","bold","WinAnsiEncoding"],["Helvetica-Oblique","helvetica","italic","WinAnsiEncoding"],["Helvetica-BoldOblique","helvetica","bolditalic","WinAnsiEncoding"],["Courier","courier","normal","WinAnsiEncoding"],["Courier-Bold","courier","bold","WinAnsiEncoding"],["Courier-Oblique","courier","italic","WinAnsiEncoding"],["Courier-BoldOblique","courier","bolditalic","WinAnsiEncoding"],["Times-Roman","times","normal","WinAnsiEncoding"],["Times-Bold","times","bold","WinAnsiEncoding"],["Times-Italic","times","italic","WinAnsiEncoding"],["Times-BoldItalic","times","bolditalic","WinAnsiEncoding"],["ZapfDingbats","zapfdingbats","normal",null],["Symbol","symbol","normal",null]];f.__private__.getStandardFonts=function(){return ze};var $e=s.fontSize||16;f.__private__.setFontSize=f.setFontSize=function(Je){return $e=S===w?Je/ts:Je,this};var ct,Xe=f.__private__.getFontSize=f.getFontSize=function(){return S===b?$e:$e*ts},it=s.R2L||!1;f.__private__.setR2L=f.setR2L=function(Je){return it=Je,this},f.__private__.getR2L=f.getR2L=function(){return it};var at,Ke=f.__private__.setZoomMode=function(Je){if(/^(?:\d+\.\d*|\d*\.\d+|\d+)%$/.test(Je))ct=Je;else if(isNaN(Je)){if([void 0,null,"fullwidth","fullheight","fullpage","original"].indexOf(Je)===-1)throw new Error('zoom must be Integer (e.g. 2), a percentage Value (e.g. 300%) or fullwidth, fullheight, fullpage, original. "'+Je+'" is not recognized.');ct=Je}else ct=parseInt(Je,10)};f.__private__.getZoomMode=function(){return ct};var nt,xt=f.__private__.setPageMode=function(Je){if([void 0,null,"UseNone","UseOutlines","UseThumbs","FullScreen"].indexOf(Je)==-1)throw new Error('Page mode must be one of UseNone, UseOutlines, UseThumbs, or FullScreen. "'+Je+'" is not recognized.');at=Je};f.__private__.getPageMode=function(){return at};var rt=f.__private__.setLayoutMode=function(Je){if([void 0,null,"continuous","single","twoleft","tworight","two"].indexOf(Je)==-1)throw new Error('Layout mode must be one of continuous, single, twoleft, tworight. "'+Je+'" is not recognized.');nt=Je};f.__private__.getLayoutMode=function(){return nt},f.__private__.setDisplayMode=f.setDisplayMode=function(Je,Ht,Ts){return Ke(Je),rt(Ht),xt(Ts),this};var Yt={title:"",subject:"",author:"",keywords:"",creator:""};f.__private__.getDocumentProperty=function(Je){if(Object.keys(Yt).indexOf(Je)===-1)throw new Error("Invalid argument passed to jsPDF.getDocumentProperty");return Yt[Je]},f.__private__.getDocumentProperties=function(){return Yt},f.__private__.setDocumentProperties=f.setProperties=f.setDocumentProperties=function(Je){for(var Ht in Yt)Yt.hasOwnProperty(Ht)&&Je[Ht]&&(Yt[Ht]=Je[Ht]);return this},f.__private__.setDocumentProperty=function(Je,Ht){if(Object.keys(Yt).indexOf(Je)===-1)throw new Error("Invalid arguments passed to jsPDF.setDocumentProperty");return Yt[Je]=Ht};var qt,ts,ys,Bt,Ft,rs={},St={},Xs=[],vt={},gs={},Ss={},Is={},Ys=null,cs=0,js=[],kn=new D4t(f),Ws=s.hotfixes||[],On={},ds={},gn=[],As=function Je(Ht,Ts,ln,tn,nr,rr){if(!(this instanceof Je))return new Je(Ht,Ts,ln,tn,nr,rr);isNaN(Ht)&&(Ht=1),isNaN(Ts)&&(Ts=0),isNaN(ln)&&(ln=0),isNaN(tn)&&(tn=1),isNaN(nr)&&(nr=0),isNaN(rr)&&(rr=0),this._matrix=[Ht,Ts,ln,tn,nr,rr]};Object.defineProperty(As.prototype,"sx",{get:function(){return this._matrix[0]},set:function(Je){this._matrix[0]=Je}}),Object.defineProperty(As.prototype,"shy",{get:function(){return this._matrix[1]},set:function(Je){this._matrix[1]=Je}}),Object.defineProperty(As.prototype,"shx",{get:function(){return this._matrix[2]},set:function(Je){this._matrix[2]=Je}}),Object.defineProperty(As.prototype,"sy",{get:function(){return this._matrix[3]},set:function(Je){this._matrix[3]=Je}}),Object.defineProperty(As.prototype,"tx",{get:function(){return this._matrix[4]},set:function(Je){this._matrix[4]=Je}}),Object.defineProperty(As.prototype,"ty",{get:function(){return this._matrix[5]},set:function(Je){this._matrix[5]=Je}}),Object.defineProperty(As.prototype,"a",{get:function(){return this._matrix[0]},set:function(Je){this._matrix[0]=Je}}),Object.defineProperty(As.prototype,"b",{get:function(){return this._matrix[1]},set:function(Je){this._matrix[1]=Je}}),Object.defineProperty(As.prototype,"c",{get:function(){return this._matrix[2]},set:function(Je){this._matrix[2]=Je}}),Object.defineProperty(As.prototype,"d",{get:function(){return this._matrix[3]},set:function(Je){this._matrix[3]=Je}}),Object.defineProperty(As.prototype,"e",{get:function(){return this._matrix[4]},set:function(Je){this._matrix[4]=Je}}),Object.defineProperty(As.prototype,"f",{get:function(){return this._matrix[5]},set:function(Je){this._matrix[5]=Je}}),Object.defineProperty(As.prototype,"rotation",{get:function(){return Math.atan2(this.shx,this.sx)}}),Object.defineProperty(As.prototype,"scaleX",{get:function(){return this.decompose().scale.sx}}),Object.defineProperty(As.prototype,"scaleY",{get:function(){return this.decompose().scale.sy}}),Object.defineProperty(As.prototype,"isIdentity",{get:function(){return this.sx===1&&this.shy===0&&this.shx===0&&this.sy===1&&this.tx===0&&this.ty===0}}),As.prototype.join=function(Je){return[this.sx,this.shy,this.shx,this.sy,this.tx,this.ty].map(P).join(Je)},As.prototype.multiply=function(Je){var Ht=Je.sx*this.sx+Je.shy*this.shx,Ts=Je.sx*this.shy+Je.shy*this.sy,ln=Je.shx*this.sx+Je.sy*this.shx,tn=Je.shx*this.shy+Je.sy*this.sy,nr=Je.tx*this.sx+Je.ty*this.shx+this.tx,rr=Je.tx*this.shy+Je.ty*this.sy+this.ty;return new As(Ht,Ts,ln,tn,nr,rr)},As.prototype.decompose=function(){var Je=this.sx,Ht=this.shy,Ts=this.shx,ln=this.sy,tn=this.tx,nr=this.ty,rr=Math.sqrt(Je*Je+Ht*Ht),Qr=(Je/=rr)*Ts+(Ht/=rr)*ln;Ts-=Je*Qr,ln-=Ht*Qr;var na=Math.sqrt(Ts*Ts+ln*ln);return Qr/=na,Je*(ln/=na)>16&255,ln=na>>8&255,tn=255&na}if(ln===void 0||nr===void 0&&Ts===ln&&ln===tn)Ht=typeof Ts=="string"?Ts+" "+rr[0]:Je.precision===2?O(Ts/255)+" "+rr[0]:U(Ts/255)+" "+rr[0];else if(nr===void 0||Pm(nr)==="object"){if(nr&&!isNaN(nr.a)&&nr.a===0)return["1.","1.","1.",rr[1]].join(" ");Ht=typeof Ts=="string"?[Ts,ln,tn,rr[1]].join(" "):Je.precision===2?[O(Ts/255),O(ln/255),O(tn/255),rr[1]].join(" "):[U(Ts/255),U(ln/255),U(tn/255),rr[1]].join(" ")}else Ht=typeof Ts=="string"?[Ts,ln,tn,nr,rr[2]].join(" "):Je.precision===2?[O(Ts),O(ln),O(tn),O(nr),rr[2]].join(" "):[U(Ts),U(ln),U(tn),U(nr),rr[2]].join(" ");return Ht},Un=f.__private__.getFilters=function(){return l},ur=f.__private__.putStream=function(Je){var Ht=(Je=Je||{}).data||"",Ts=Je.filters||Un(),ln=Je.alreadyAppliedFilters||[],tn=Je.addLength1||!1,nr=Ht.length,rr=Je.objectId,Qr=function(Lo){return Lo};if(u!==null&&rr===void 0)throw new Error("ObjectId must be passed to putStream for file encryption");u!==null&&(Qr=yc.encryptor(rr,0));var na={};Ts===!0&&(Ts=["FlateEncode"]);var $a=Je.additionalKeyValues||[],Na=(na=Go.API.processDataByFilters!==void 0?Go.API.processDataByFilters(Ht,Ts):{data:Ht,reverseChain:[]}).reverseChain+(Array.isArray(ln)?ln.join(" "):ln.toString());if(na.data.length!==0&&($a.push({key:"Length",value:na.data.length}),tn===!0&&$a.push({key:"Length1",value:nr})),Na.length!=0)if(Na.split("/").length-1==1)$a.push({key:"Filter",value:Na});else{$a.push({key:"Filter",value:"["+Na+"]"});for(var La=0;La<$a.length;La+=1)if($a[La].key==="DecodeParms"){for(var to=[],xo=0;xo>"),na.data.length!==0&&(Ae("stream"),Ae(Qr(na.data)),Ae("endstream"))},Pa=f.__private__.putPage=function(Je){var Ht=Je.number,Ts=Je.data,ln=Je.objId,tn=Je.contentsObjId;xs(ln,!0),Ae("<>"),Ae("endobj");var nr=Ts.join(` `);return S===w&&(nr+=` Q`),xs(tn,!0),ur({data:nr,filters:Un(),objectId:tn}),Ae("endobj"),ln},ii=f.__private__.putPages=function(){var Je,Ht,Ts=[];for(Je=1;Je<=cs;Je++)js[Je].objId=vn(),js[Je].contentsObjId=vn();for(Je=1;Je<=cs;Je++)Ts.push(Pa({number:Je,data:Fe[Je],objId:js[Je].objId,contentsObjId:js[Je].contentsObjId,mediaBox:js[Je].mediaBox,cropBox:js[Je].cropBox,bleedBox:js[Je].bleedBox,trimBox:js[Je].trimBox,artBox:js[Je].artBox,userUnit:js[Je].userUnit,rootDictionaryObjId:Or,resourceDictionaryObjId:ca}));xs(Or,!0),Ae("<>"),Ae("endobj"),kn.publish("postPutPages")},$i=function(Je){kn.publish("putFont",{font:Je,out:Ae,newObject:Fn,putStream:ur}),Je.isAlreadyPutted!==!0&&(Je.objectNumber=Fn(),Ae("<<"),Ae("/Type /Font"),Ae("/BaseFont /"+CU(Je.postScriptName)),Ae("/Subtype /Type1"),typeof Je.encoding=="string"&&Ae("/Encoding /"+Je.encoding),Ae("/FirstChar 32"),Ae("/LastChar 255"),Ae(">>"),Ae("endobj"))},Rn=function(Je){Je.objectNumber=Fn();var Ht=[];Ht.push({key:"Type",value:"/XObject"}),Ht.push({key:"Subtype",value:"/Form"}),Ht.push({key:"BBox",value:"["+[P(Je.x),P(Je.y),P(Je.x+Je.width),P(Je.y+Je.height)].join(" ")+"]"}),Ht.push({key:"Matrix",value:"["+Je.matrix.toString()+"]"});var Ts=Je.pages[1].join(` `);ur({data:Ts,additionalKeyValues:Ht,objectId:Je.objectNumber}),Ae("endobj")},xa=function(Je,Ht){Ht||(Ht=21);var Ts=Fn(),ln=function(rr,Qr){var na,$a=[],Na=1/(Qr-1);for(na=0;na<1;na+=Na)$a.push(na);if($a.push(1),rr[0].offset!=0){var La={offset:0,color:rr[0].color};rr.unshift(La)}if(rr[rr.length-1].offset!=1){var to={offset:1,color:rr[rr.length-1].color};rr.push(to)}for(var xo="",oo=0,Lo=0;Lo<$a.length;Lo++){for(na=$a[Lo];na>rr[oo+1].offset;)oo++;var ql=rr[oo].offset,po=(na-ql)/(rr[oo+1].offset-ql),nl=rr[oo].color,Il=rr[oo+1].color;xo+=he(Math.round((1-po)*nl[0]+po*Il[0]).toString(16))+he(Math.round((1-po)*nl[1]+po*Il[1]).toString(16))+he(Math.round((1-po)*nl[2]+po*Il[2]).toString(16))}return xo.trim()}(Je.colors,Ht),tn=[];tn.push({key:"FunctionType",value:"0"}),tn.push({key:"Domain",value:"[0.0 1.0]"}),tn.push({key:"Size",value:"["+Ht+"]"}),tn.push({key:"BitsPerSample",value:"8"}),tn.push({key:"Range",value:"[0.0 1.0 0.0 1.0 0.0 1.0]"}),tn.push({key:"Decode",value:"[0.0 1.0 0.0 1.0 0.0 1.0]"}),ur({data:ln,additionalKeyValues:tn,alreadyAppliedFilters:["/ASCIIHexDecode"],objectId:Ts}),Ae("endobj"),Je.objectNumber=Fn(),Ae("<< /ShadingType "+Je.type),Ae("/ColorSpace /DeviceRGB");var nr="/Coords ["+P(parseFloat(Je.coords[0]))+" "+P(parseFloat(Je.coords[1]))+" ";Je.type===2?nr+=P(parseFloat(Je.coords[2]))+" "+P(parseFloat(Je.coords[3])):nr+=P(parseFloat(Je.coords[2]))+" "+P(parseFloat(Je.coords[3]))+" "+P(parseFloat(Je.coords[4]))+" "+P(parseFloat(Je.coords[5])),Ae(nr+="]"),Je.matrix&&Ae("/Matrix ["+Je.matrix.toString()+"]"),Ae("/Function "+Ts+" 0 R"),Ae("/Extend [true true]"),Ae(">>"),Ae("endobj")},Ya=function(Je,Ht){var Ts=vn(),ln=Fn();Ht.push({resourcesOid:Ts,objectOid:ln}),Je.objectNumber=ln;var tn=[];tn.push({key:"Type",value:"/Pattern"}),tn.push({key:"PatternType",value:"1"}),tn.push({key:"PaintType",value:"1"}),tn.push({key:"TilingType",value:"1"}),tn.push({key:"BBox",value:"["+Je.boundingBox.map(P).join(" ")+"]"}),tn.push({key:"XStep",value:P(Je.xStep)}),tn.push({key:"YStep",value:P(Je.yStep)}),tn.push({key:"Resources",value:Ts+" 0 R"}),Je.matrix&&tn.push({key:"Matrix",value:"["+Je.matrix.toString()+"]"}),ur({data:Je.stream,additionalKeyValues:tn,objectId:Je.objectNumber}),Ae("endobj")},ho=function(Je){for(var Ht in Je.objectNumber=Fn(),Ae("<<"),Je)switch(Ht){case"opacity":Ae("/ca "+O(Je[Ht]));break;case"stroke-opacity":Ae("/CA "+O(Je[Ht]))}Ae(">>"),Ae("endobj")},Pc=function(Je){xs(Je.resourcesOid,!0),Ae("<<"),Ae("/ProcSet [/PDF /Text /ImageB /ImageC /ImageI]"),function(){for(var Ht in Ae("/Font <<"),rs)rs.hasOwnProperty(Ht)&&(h===!1||h===!0&&m.hasOwnProperty(Ht))&&Ae("/"+Ht+" "+rs[Ht].objectNumber+" 0 R");Ae(">>")}(),function(){if(Object.keys(vt).length>0){for(var Ht in Ae("/Shading <<"),vt)vt.hasOwnProperty(Ht)&&vt[Ht]instanceof t8&&vt[Ht].objectNumber>=0&&Ae("/"+Ht+" "+vt[Ht].objectNumber+" 0 R");kn.publish("putShadingPatternDict"),Ae(">>")}}(),function(Ht){if(Object.keys(vt).length>0){for(var Ts in Ae("/Pattern <<"),vt)vt.hasOwnProperty(Ts)&&vt[Ts]instanceof f.TilingPattern&&vt[Ts].objectNumber>=0&&vt[Ts].objectNumber>")}}(Je.objectOid),function(){if(Object.keys(Ss).length>0){var Ht;for(Ht in Ae("/ExtGState <<"),Ss)Ss.hasOwnProperty(Ht)&&Ss[Ht].objectNumber>=0&&Ae("/"+Ht+" "+Ss[Ht].objectNumber+" 0 R");kn.publish("putGStateDict"),Ae(">>")}}(),function(){for(var Ht in Ae("/XObject <<"),On)On.hasOwnProperty(Ht)&&On[Ht].objectNumber>=0&&Ae("/"+Ht+" "+On[Ht].objectNumber+" 0 R");kn.publish("putXobjectDict"),Ae(">>")}(),Ae(">>"),Ae("endobj")},$d=function(Je){St[Je.fontName]=St[Je.fontName]||{},St[Je.fontName][Je.fontStyle]=Je.id},Nl=function(Je,Ht,Ts,ln,tn){var nr={id:"F"+(Object.keys(rs).length+1).toString(10),postScriptName:Je,fontName:Ht,fontStyle:Ts,encoding:ln,isStandardFont:tn||!1,metadata:{}};return kn.publish("addFont",{font:nr,instance:this}),rs[nr.id]=nr,$d(nr),nr.id},Ho=f.__private__.pdfEscape=f.pdfEscape=function(Je,Ht){return function(Ts,ln){var tn,nr,rr,Qr,na,$a,Na,La,to;if(rr=(ln=ln||{}).sourceEncoding||"Unicode",na=ln.outputEncoding,(ln.autoencode||na)&&rs[qt].metadata&&rs[qt].metadata[rr]&&rs[qt].metadata[rr].encoding&&(Qr=rs[qt].metadata[rr].encoding,!na&&rs[qt].encoding&&(na=rs[qt].encoding),!na&&Qr.codePages&&(na=Qr.codePages[0]),typeof na=="string"&&(na=Qr[na]),na)){for(Na=!1,$a=[],tn=0,nr=Ts.length;tn>8&&(Na=!0);Ts=$a.join("")}for(tn=Ts.length;Na===void 0&&tn!==0;)Ts.charCodeAt(tn-1)>>8&&(Na=!0),tn--;if(!Na)return Ts;for($a=ln.noBOM?[]:[254,255],tn=0,nr=Ts.length;tn>8)>>8)throw new Error("Character at position "+tn+" of string '"+Ts+"' exceeds 16bits. Cannot be encoded into UCS-2 BE");$a.push(to),$a.push(La-(to<<8))}return String.fromCharCode.apply(void 0,$a)}(Je,Ht).replace(/\\/g,"\\\\").replace(/\(/g,"\\(").replace(/\)/g,"\\)")},ti=f.__private__.beginPage=function(Je){Fe[++cs]=[],js[cs]={objId:0,contentsObjId:0,userUnit:Number(o),artBox:null,bleedBox:null,cropBox:null,trimBox:null,mediaBox:{bottomLeftX:0,bottomLeftY:0,topRightX:Number(Je[0]),topRightY:Number(Je[1])}},Ph(cs),je(Fe[ce])},Xr=function(Je,Ht){var Ts,ln,tn;switch(n=Ht||n,typeof Je=="string"&&(Ts=v(Je.toLowerCase()),Array.isArray(Ts)&&(ln=Ts[0],tn=Ts[1])),Array.isArray(Je)&&(ln=Je[0]*ts,tn=Je[1]*ts),isNaN(ln)&&(ln=a[0],tn=a[1]),(ln>14400||tn>14400)&&(vf.warn("A page in a PDF can not be wider or taller than 14400 userUnit. jsPDF limits the width/height to 14400"),ln=Math.min(14400,ln),tn=Math.min(14400,tn)),a=[ln,tn],n.substr(0,1)){case"l":tn>ln&&(a=[tn,ln]);break;case"p":ln>tn&&(a=[tn,ln])}ti(a),Ol(vo),Ae(xh),zt!==0&&Ae(zt+" J"),Wt!==0&&Ae(Wt+" j"),kn.publish("addPage",{pageNumber:cs})},Eo=function(Je){Je>0&&Je<=cs&&(Fe.splice(Je,1),js.splice(Je,1),cs--,ce>cs&&(ce=cs),this.setPage(ce))},Ph=function(Je){Je>0&&Je<=cs&&(ce=Je)},ih=f.__private__.getNumberOfPages=f.getNumberOfPages=function(){return Fe.length-1},ao=function(Je,Ht,Ts){var ln,tn=void 0;return Ts=Ts||{},Je=Je!==void 0?Je:rs[qt].fontName,Ht=Ht!==void 0?Ht:rs[qt].fontStyle,ln=Je.toLowerCase(),St[ln]!==void 0&&St[ln][Ht]!==void 0?tn=St[ln][Ht]:St[Je]!==void 0&&St[Je][Ht]!==void 0?tn=St[Je][Ht]:Ts.disableWarning===!1&&vf.warn("Unable to look up font label for font '"+Je+"', '"+Ht+"'. Refer to getFontList() for available fonts."),tn||Ts.noFallback||(tn=St.times[Ht])==null&&(tn=St.times.normal),tn},ta=f.__private__.putInfo=function(){var Je=Fn(),Ht=function(ln){return ln};for(var Ts in u!==null&&(Ht=yc.encryptor(Je,0)),Ae("<<"),Ae("/Producer ("+Ho(Ht("jsPDF "+Go.version))+")"),Yt)Yt.hasOwnProperty(Ts)&&Yt[Ts]&&Ae("/"+Ts.substr(0,1).toUpperCase()+Ts.substr(1)+" ("+Ho(Ht(Yt[Ts]))+")");Ae("/CreationDate ("+Ho(Ht(G))+")"),Ae(">>"),Ae("endobj")},xc=f.__private__.putCatalog=function(Je){var Ht=(Je=Je||{}).rootDictionaryObjId||Or;switch(Fn(),Ae("<<"),Ae("/Type /Catalog"),Ae("/Pages "+Ht+" 0 R"),ct||(ct="fullwidth"),ct){case"fullwidth":Ae("/OpenAction [3 0 R /FitH null]");break;case"fullheight":Ae("/OpenAction [3 0 R /FitV null]");break;case"fullpage":Ae("/OpenAction [3 0 R /Fit]");break;case"original":Ae("/OpenAction [3 0 R /XYZ null null 1]");break;default:var Ts=""+ct;Ts.substr(Ts.length-1)==="%"&&(ct=parseInt(ct)/100),typeof ct=="number"&&Ae("/OpenAction [3 0 R /XYZ null null "+O(ct)+"]")}switch(nt||(nt="continuous"),nt){case"continuous":Ae("/PageLayout /OneColumn");break;case"single":Ae("/PageLayout /SinglePage");break;case"two":case"twoleft":Ae("/PageLayout /TwoColumnLeft");break;case"tworight":Ae("/PageLayout /TwoColumnRight")}at&&Ae("/PageMode /"+at),kn.publish("putCatalog"),Ae(">>"),Ae("endobj")},fl=f.__private__.putTrailer=function(){Ae("trailer"),Ae("<<"),Ae("/Size "+(ue+1)),Ae("/Root "+ue+" 0 R"),Ae("/Info "+(ue-1)+" 0 R"),u!==null&&Ae("/Encrypt "+yc.oid+" 0 R"),Ae("/ID [ <"+Y+"> <"+Y+"> ]"),Ae(">>")},Co=f.__private__.putHeader=function(){Ae("%PDF-"+g),Ae("%ºß¬à")},pu=f.__private__.putXRef=function(){var Je="0000000000";Ae("xref"),Ae("0 "+(ue+1)),Ae("0000000000 65535 f ");for(var Ht=1;Ht<=ue;Ht++)typeof ve[Ht]=="function"?Ae((Je+ve[Ht]()).slice(-10)+" 00000 n "):ve[Ht]!==void 0?Ae((Je+ve[Ht]).slice(-10)+" 00000 n "):Ae("0000000000 00000 n ")},nc=f.__private__.buildDocument=function(){var Je;ue=0,Se=0,Ee=[],ve=[],Le=[],Or=vn(),ca=vn(),je(Ee),kn.publish("buildDocument"),Co(),ii(),function(){kn.publish("putAdditionalObjects");for(var Ts=0;Ts"),Ae("/O <"+yc.toHexString(yc.O)+">"),Ae("/P "+yc.P),Ae(">>"),Ae("endobj")),ta(),xc();var Ht=Se;return pu(),fl(),Ae("startxref"),Ae(""+Ht),Ae("%%EOF"),je(Fe[ce]),Ee.join(` `)},ad=f.__private__.getBlob=function(Je){return new Blob([qe(Je)],{type:"application/pdf"})},zr=function(Je){for(;Je.firstChild;)Je.removeChild(Je.firstChild)},Hi=function(Je){var Ht,Ts=Je.document,ln=Ts.documentElement,tn=Ts.head,nr=Ts.body;return tn||(tn=Ts.createElement("head"),ln.appendChild(tn)),nr||(nr=Ts.createElement("body"),ln.appendChild(nr)),zr(tn),zr(nr),(Ht=Ts.createElement("style")).appendChild(Ts.createTextNode("html, body { padding: 0; margin: 0; } iframe { width: 100%; height: 100%; border: 0;}")),tn.appendChild(Ht),{document:Ts,body:nr}},Bc=f.output=f.__private__.output=(hn=function(Je,Ht){switch(typeof(Ht=Ht||{})=="string"?Ht={filename:Ht}:Ht.filename=Ht.filename||"generated.pdf",Je){case void 0:return nc();case"save":f.save(Ht.filename);break;case"arraybuffer":return qe(nc());case"blob":return ad(nc());case"bloburi":case"bloburl":if(Oc.URL!==void 0&&typeof Oc.URL.createObjectURL=="function")return Oc.URL&&Oc.URL.createObjectURL(ad(nc()))||void 0;vf.warn("bloburl is not supported by your system, because URL.createObjectURL is not supported by your browser.");break;case"datauristring":case"dataurlstring":var Ts="",ln=nc();try{Ts=I4t(ln)}catch{Ts=I4t(unescape(encodeURIComponent(ln)))}return"data:application/pdf;filename="+encodeURIComponent(Ht.filename)+";base64,"+Ts;case"pdfobjectnewwindow":if(Object.prototype.toString.call(Oc)==="[object Window]"){var tn="https://cdnjs.cloudflare.com/ajax/libs/pdfobject/2.1.1/pdfobject.min.js",nr=!Ht.pdfObjectUrl;nr||(tn=Ht.pdfObjectUrl);var rr=Oc.open();if(rr!==null){var Qr=Hi(rr),na=Qr.document.createElement("script"),$a=this;na.src=tn,nr&&(na.integrity="sha512-4ze/a9/4jqu+tX9dfOqJYSvyYd5M6qum/3HpCLr+/Jqf0whc37VUbkpNGHR7/8pSnCFw47T1fmIpwBV7UySh3g==",na.crossOrigin="anonymous"),na.onload=function(){rr.PDFObject.embed($a.output("dataurlstring"),Ht)},Qr.body.appendChild(na)}return rr}throw new Error("The option pdfobjectnewwindow just works in a browser-environment.");case"pdfjsnewwindow":if(Object.prototype.toString.call(Oc)==="[object Window]"){var Na=Ht.pdfJsUrl||"examples/PDF.js/web/viewer.html",La=Oc.open();if(La!==null){var to=Hi(La),xo=to.document.createElement("iframe"),oo=Na.indexOf("?")===-1?"?":"&";$a=this,xo.id="pdfViewer",xo.width="500px",xo.height="400px",xo.src=Na+oo+"file=&downloadName="+encodeURIComponent(Ht.filename),xo.onload=function(){La.document.title=Ht.filename,xo.contentWindow.PDFViewerApplication.open($a.output("bloburl"))},to.body.appendChild(xo)}return La}throw new Error("The option pdfjsnewwindow just works in a browser-environment.");case"dataurlnewwindow":if(Object.prototype.toString.call(Oc)!=="[object Window]")throw new Error("The option dataurlnewwindow just works in a browser-environment.");var Lo=Oc.open();if(Lo!==null){var ql=Hi(Lo),po=ql.document.createElement("iframe");po.src=this.output("datauristring",Ht),ql.body.appendChild(po),Lo.document.title=Ht.filename}if(Lo||typeof safari>"u")return Lo;break;case"datauri":case"dataurl":return Oc.document.location.href=this.output("datauristring",Ht);default:return null}},hn.foo=function(){try{return hn.apply(this,arguments)}catch(Ts){var Je=Ts.stack||"";~Je.indexOf(" at ")&&(Je=Je.split(" at ")[1]);var Ht="Error in function "+Je.split(` `)[0].split("<")[0]+": "+Ts.message;if(!Oc.console)throw new Error(Ht);Oc.console.error(Ht,Ts),Oc.alert&&alert(Ht)}},hn.foo.bar=hn,hn.foo),$c=function(Je){return Array.isArray(Ws)===!0&&Ws.indexOf(Je)>-1};switch(r){case"pt":ts=1;break;case"mm":ts=72/25.4;break;case"cm":ts=72/2.54;break;case"in":ts=72;break;case"px":ts=$c("px_scaling")==1?.75:96/72;break;case"pc":case"em":ts=12;break;case"ex":ts=6;break;default:if(typeof r!="number")throw new Error("Invalid unit: "+r);ts=r}var yc=null;te(),ae();var Ul=f.__private__.getPageInfo=f.getPageInfo=function(Je){if(isNaN(Je)||Je%1!=0)throw new Error("Invalid argument passed to jsPDF.getPageInfo");return{objId:js[Je].objId,pageNumber:Je,pageContext:js[Je]}},rg=f.__private__.getPageInfoByObjId=function(Je){if(isNaN(Je)||Je%1!=0)throw new Error("Invalid argument passed to jsPDF.getPageInfoByObjId");for(var Ht in js)if(js[Ht].objId===Je)break;return Ul(Ht)},Lx=f.__private__.getCurrentPageInfo=f.getCurrentPageInfo=function(){return{objId:js[ce].objId,pageNumber:ce,pageContext:js[ce]}};f.addPage=function(){return Xr.apply(this,arguments),this},f.setPage=function(){return Ph.apply(this,arguments),je.call(this,Fe[ce]),this},f.insertPage=function(Je){return this.addPage(),this.movePage(ce,Je),this},f.movePage=function(Je,Ht){var Ts,ln;if(Je>Ht){Ts=Fe[Je],ln=js[Je];for(var tn=Je;tn>Ht;tn--)Fe[tn]=Fe[tn-1],js[tn]=js[tn-1];Fe[Ht]=Ts,js[Ht]=ln,this.setPage(Ht)}else if(Je0&&(typeof Je=="string"?Je=oo.splitTextToSize(Je,Na):Object.prototype.toString.call(Je)==="[object Array]"&&(Je=Je.reduce(function(Ro,kl){return Ro.concat(oo.splitTextToSize(kl,Na))},[]))),nr={text:Je,x:Ht,y:Ts,options:ln,mutex:{pdfEscape:Ho,activeFontKey:qt,fonts:rs,activeFontSize:$e}},kn.publish("preProcessText",nr),Je=nr.text,Qr=(ln=nr.options).angle,xo instanceof As==0&&Qr&&typeof Qr=="number"){Qr*=Math.PI/180,ln.rotationDirection===0&&(Qr=-Qr),S===w&&(Qr=-Qr);var el=Math.cos(Qr),zo=Math.sin(Qr);xo=new As(el,zo,-zo,el,0,0)}else Qr&&Qr instanceof As&&(xo=Qr);S!==w||xo||(xo=Er),($a=ln.charSpace||jt)!==void 0&&(po+=P(W($a))+` Tc `,this.setCharSpace(this.getCharSpace()||0)),(to=ln.horizontalScale)!==void 0&&(po+=P(100*to)+` Tz `),ln.lang;var Lc=-1,Mu=ln.renderingMode!==void 0?ln.renderingMode:ln.stroke,ou=oo.internal.getCurrentPageInfo().pageContext;switch(Mu){case 0:case!1:case"fill":Lc=0;break;case 1:case!0:case"stroke":Lc=1;break;case 2:case"fillThenStroke":Lc=2;break;case 3:case"invisible":Lc=3;break;case 4:case"fillAndAddForClipping":Lc=4;break;case 5:case"strokeAndAddPathForClipping":Lc=5;break;case 6:case"fillThenStrokeAndAddToPathForClipping":Lc=6;break;case 7:case"addToPathForClipping":Lc=7}var um=ou.usedRenderingMode!==void 0?ou.usedRenderingMode:-1;Lc!==-1?po+=Lc+` Tr `:um!==-1&&(po+=`0 Tr `),Lc!==-1&&(ou.usedRenderingMode=Lc),na=ln.align||"left";var Td,gu=$e*nl,Qc=oo.internal.pageSize.getWidth(),id=rs[qt];$a=ln.charSpace||jt,Na=ln.maxWidth||0,La=Object.assign({autoencode:!0,noBOM:!0},ln.flags);var lh=[],If=function(Ro){return oo.getStringUnitWidth(Ro,{font:id,charSpace:$a,fontSize:$e,doKerning:!1})*$e/Il};if(Object.prototype.toString.call(Je)==="[object Array]"){var Ud;rr=iu(Je),na!=="left"&&(Td=rr.map(If));var od,Lh=0;if(na==="right"){Ht-=Td[0],Je=[],Aa=rr.length;for(var Gu=0;Gu0?(Na-Td[Xi])/Ep:0;Xi":")"),ya=parseFloat(rr[Wu][1]),Zy=parseFloat(rr[Wu][2]);break;case 0:Ci=(ql?"<":"(")+rr[Wu]+(ql?">":")"),ya=Wh(Ht),Zy=df(Ts)}lh!==void 0&&lh[Wu]!==void 0&&(zm=lh[Wu]+` Tw `),Wu===0?Je.push(zm+Dx(ya,Zy,xo)+Ci):Xg===0?Je.push(zm+Ci):Xg===1&&Je.push(zm+Dx(ya,Zy,xo)+Ci)}Je=Xg===0?Je.join(` Tj T* `):Je.join(` Tj `),Je+=` Tj `;var Sc=`BT /`;return Sc+=qt+" "+$e+` Tf `,Sc+=P($e*nl)+` TL `,Sc+=We+` `,Sc+=po,Sc+=Je,Ae(Sc+="ET"),m[qt]=!0,oo};var Yo=f.__private__.clip=f.clip=function(Je){return Ae(Je==="evenodd"?"W*":"W"),this};f.clipEvenOdd=function(){return Yo("evenodd")},f.__private__.discardPath=f.discardPath=function(){return Ae("n"),this};var Ic=f.__private__.isValidStyle=function(Je){var Ht=!1;return[void 0,null,"S","D","F","DF","FD","f","f*","B","B*","n"].indexOf(Je)!==-1&&(Ht=!0),Ht};f.__private__.setDefaultPathOperation=f.setDefaultPathOperation=function(Je){return Ic(Je)&&(d=Je),this};var Ih=f.__private__.getStyle=f.getStyle=function(Je){var Ht=d;switch(Je){case"D":case"S":Ht="S";break;case"F":Ht="f";break;case"FD":case"DF":Ht="B";break;case"f":case"f*":case"B":case"B*":Ht=Je}return Ht},cm=f.close=function(){return Ae("h"),this};f.stroke=function(){return Ae("S"),this},f.fill=function(Je){return Xc("f",Je),this},f.fillEvenOdd=function(Je){return Xc("f*",Je),this},f.fillStroke=function(Je){return Xc("B",Je),this},f.fillStrokeEvenOdd=function(Je){return Xc("B*",Je),this};var Xc=function(Je,Ht){Pm(Ht)==="object"?No(Ht,Je):Ae(Je)},_s=function(Je){Je===null||S===w&&Je===void 0||(Je=Ih(Je),Ae(Je))};function Xa(Je,Ht,Ts,ln,tn){var nr=new pq(Ht||this.boundingBox,Ts||this.xStep,ln||this.yStep,this.gState,tn||this.matrix);nr.stream=this.stream;var rr=Je+"$$"+this.cloneIndex+++"$$";return qn(rr,nr),nr}var No=function(Je,Ht){var Ts=gs[Je.key],ln=vt[Ts];if(ln instanceof t8)Ae("q"),Ae(Ba(Ht)),ln.gState&&f.setGState(ln.gState),Ae(Je.matrix.toString()+" cm"),Ae("/"+Ts+" sh"),Ae("Q");else if(ln instanceof pq){var tn=new As(1,0,0,-1,0,vr());Je.matrix&&(tn=tn.multiply(Je.matrix||Er),Ts=Xa.call(ln,Je.key,Je.boundingBox,Je.xStep,Je.yStep,tn).id),Ae("q"),Ae("/Pattern cs"),Ae("/"+Ts+" scn"),ln.gState&&f.setGState(ln.gState),Ae(Ht),Ae("Q")}},Ba=function(Je){switch(Je){case"f":case"F":case"n":return"W n";case"f*":return"W* n";case"B":case"S":return"W S";case"B*":return"W* S"}},io=f.moveTo=function(Je,Ht){return Ae(P(W(Je))+" "+P(V(Ht))+" m"),this},ko=f.lineTo=function(Je,Ht){return Ae(P(W(Je))+" "+P(V(Ht))+" l"),this},qi=f.curveTo=function(Je,Ht,Ts,ln,tn,nr){return Ae([P(W(Je)),P(V(Ht)),P(W(Ts)),P(V(ln)),P(W(tn)),P(V(nr)),"c"].join(" ")),this};f.__private__.line=f.line=function(Je,Ht,Ts,ln,tn){if(isNaN(Je)||isNaN(Ht)||isNaN(Ts)||isNaN(ln)||!Ic(tn))throw new Error("Invalid arguments passed to jsPDF.line");return S===b?this.lines([[Ts-Je,ln-Ht]],Je,Ht,[1,1],tn||"S"):this.lines([[Ts-Je,ln-Ht]],Je,Ht,[1,1]).stroke()},f.__private__.lines=f.lines=function(Je,Ht,Ts,ln,tn,nr){var rr,Qr,na,$a,Na,La,to,xo,oo,Lo,ql,po;if(typeof Je=="number"&&(po=Ts,Ts=Ht,Ht=Je,Je=po),ln=ln||[1,1],nr=nr||!1,isNaN(Ht)||isNaN(Ts)||!Array.isArray(Je)||!Array.isArray(ln)||!Ic(tn)||typeof nr!="boolean")throw new Error("Invalid arguments passed to jsPDF.lines");for(io(Ht,Ts),rr=ln[0],Qr=ln[1],$a=Je.length,Lo=Ht,ql=Ts,na=0;na<$a;na++)(Na=Je[na]).length===2?(Lo=Na[0]*rr+Lo,ql=Na[1]*Qr+ql,ko(Lo,ql)):(La=Na[0]*rr+Lo,to=Na[1]*Qr+ql,xo=Na[2]*rr+Lo,oo=Na[3]*Qr+ql,Lo=Na[4]*rr+Lo,ql=Na[5]*Qr+ql,qi(La,to,xo,oo,Lo,ql));return nr&&cm(),_s(tn),this},f.path=function(Je){for(var Ht=0;Ht>8&255,s>>16&255,s>>24&255)},SU.prototype.toHexString=function(s){return s.split("").map(function(t){return("0"+(255&t.charCodeAt(0)).toString(16)).slice(-2)}).join("")},SU.prototype.hexToBytes=function(s){for(var t=[],n=0;n>8&255,s>>16&255,255&t,t>>8&255)).substr(0,10);return function(r){return xZe(n,r)}},mPe.prototype.equals=function(s){var t,n="id,objectNumber,equals";if(!s||Pm(s)!==Pm(this))return!1;var r=0;for(t in this)if(!(n.indexOf(t)>=0)){if(this.hasOwnProperty(t)&&!s.hasOwnProperty(t)||this[t]!==s[t])return!1;r++}for(t in s)s.hasOwnProperty(t)&&n.indexOf(t)<0&&r--;return r===0},Go.API={events:[]},Go.version="4.2.1";var mx=Go.API,Eot=1,h9=function(s){return s.replace(/\\/g,"\\\\").replace(/\(/g,"\\(").replace(/\)/g,"\\)")},W$=function(s){return s.replace(/\\\\/g,"\\").replace(/\\\(/g,"(").replace(/\\\)/g,")")},yB=function(s){return s.toString().replace(/#/g,"#23").replace(/[\s\n\r()<>[\]{}\/%]/g,function(t){var n=t.charCodeAt(0).toString(16).toUpperCase();return"#"+(n.length===1?"0"+n:n)})},cd=function(s){return s.toFixed(2)},MM=function(s){return s.toFixed(5)};mx.__acroform__={};var Jw=function(s,t){s.prototype=Object.create(t.prototype),s.prototype.constructor=s},F4t=function(s){return s*Eot},b5=function(s){var t=new css,n=$o.internal.getHeight(s)||0,r=$o.internal.getWidth(s)||0;return t.BBox=[0,0,Number(cd(r)),Number(cd(n))],t},MWn=mx.__acroform__.setBit=function(s,t){if(s=s||0,t=t||0,isNaN(s)||isNaN(t))throw new Error("Invalid arguments passed to jsPDF.API.__acroform__.setBit");return s|1<0;){t="",i--;var d,u,h=Tue("3",s,i).height,m=s.multiline?l-i:(l-h)/2,f=m+=2,g=0,x=0,y=0;if(i<=0){t=`(...) Tj `,t+="% Width of Text: "+Tue(t,s,i=12).width+", FieldWidth:"+o+` `;break}for(var v="",b=0,w=0;wl)continue e;v+=a[w][y],S=!0,x=w,w--}else{v=(v+=a[w][y]+" ").substr(v.length-1)==" "?v.substr(0,v.length-1):v;var C=parseInt(w),E=c(C,v,i),I=w>=a.length-1;if(E&&!I){v+=" ",y=0;continue}if(E||I){if(I)x=C;else if(s.multiline&&(h+2)*(b+2)+2>l)continue e}else{if(!s.multiline||(h+2)*(b+2)+2>l)continue e;x=C}}for(var P="",R=g;R<=x;R++){var D=a[R];if(s.multiline){if(R===x){P+=D[y]+" ",y=(y+1)%D.length;continue}if(R===g){P+=D[D.length-1]+" ";continue}}P+=D[0]+" "}switch(P=P.substr(P.length-1)==" "?P.substr(0,P.length-1):P,u=Tue(P,s,i).width,s.textAlign){case"right":d=o-u-2;break;case"center":d=(o-u)/2;break;default:d=2}t+=cd(d)+" "+cd(f)+` Td `,t+="("+h9(P)+`) Tj `,t+=-cd(d)+` 0 Td `,f=-(i+2),u=0,g=S?x:x+1,b++,v=""}break}return r.text=t,r.fontSize=i,r},Tue=function(s,t,n){var r=t.scope.internal.getFont(t.fontName,t.fontStyle),a=t.scope.getStringUnitWidth(s,{font:r,fontSize:parseFloat(n),charSpace:0})*parseFloat(n);return{height:t.scope.getStringUnitWidth("3",{font:r,fontSize:parseFloat(n),charSpace:0})*parseFloat(n)*1.5,width:a}},DWn={fields:[],xForms:[],acroFormDictionaryRoot:null,printedOut:!1,internal:null,isInitialized:!1},FWn=function(s,t){var n={type:"reference",object:s};t.internal.getPageInfo(s.page).pageContext.annotations.find(function(r){return r.type===n.type&&r.object===n.object})===void 0&&t.internal.getPageInfo(s.page).pageContext.annotations.push(n)},OWn=function(s,t){if(t.scope=s,s.internal!==void 0&&(s.internal.acroformPlugin===void 0||s.internal.acroformPlugin.isInitialized===!1)){if(MC.FieldNum=0,s.internal.acroformPlugin=JSON.parse(JSON.stringify(DWn)),s.internal.acroformPlugin.acroFormDictionaryRoot)throw new Error("Exception while creating AcroformDictionary");Eot=s.internal.scaleFactor,s.internal.acroformPlugin.acroFormDictionaryRoot=new dss,s.internal.acroformPlugin.acroFormDictionaryRoot.scope=s,s.internal.acroformPlugin.acroFormDictionaryRoot._eventID=s.internal.events.subscribe("postPutResources",function(){(function(n){n.internal.events.unsubscribe(n.internal.acroformPlugin.acroFormDictionaryRoot._eventID),delete n.internal.acroformPlugin.acroFormDictionaryRoot._eventID,n.internal.acroformPlugin.printedOut=!0})(s)}),s.internal.events.subscribe("buildDocument",function(){(function(n){n.internal.acroformPlugin.acroFormDictionaryRoot.objId=void 0;var r=n.internal.acroformPlugin.acroFormDictionaryRoot.Fields;for(var a in r)if(r.hasOwnProperty(a)){var i=r[a];i.objId=void 0,i.hasAnnotation&&FWn(i,n)}})(s)}),s.internal.events.subscribe("putCatalog",function(){(function(n){if(n.internal.acroformPlugin.acroFormDictionaryRoot===void 0)throw new Error("putCatalogCallback: Root missing.");n.internal.write("/AcroForm "+n.internal.acroformPlugin.acroFormDictionaryRoot.objId+" 0 R")})(s)}),s.internal.events.subscribe("postPutPages",function(n){(function(r,a){var i=!r;for(var l in r||(a.internal.newObjectDeferredBegin(a.internal.acroformPlugin.acroFormDictionaryRoot.objId,!0),a.internal.acroformPlugin.acroFormDictionaryRoot.putStream()),r=r||a.internal.acroformPlugin.acroFormDictionaryRoot.Kids)if(r.hasOwnProperty(l)){var o=r[l],c=[],d=o.Rect;if(o.Rect&&(o.Rect=LWn(o.Rect,a)),a.internal.newObjectDeferredBegin(o.objId,!0),o.DA=$o.createDefaultAppearanceStream(o),Pm(o)==="object"&&typeof o.getKeyValueListForStream=="function"&&(c=o.getKeyValueListForStream()),o.Rect=d,o.hasAppearanceStream&&!o.appearanceStreamContent){var u=RWn(o);c.push({key:"AP",value:"<>"}),a.internal.acroformPlugin.xForms.push(u)}if(o.appearanceStreamContent){var h="";for(var m in o.appearanceStreamContent)if(o.appearanceStreamContent.hasOwnProperty(m)){var f=o.appearanceStreamContent[m];if(h+="/"+m+" ",h+="<<",Object.keys(f).length>=1||Array.isArray(f)){for(var l in f)if(f.hasOwnProperty(l)){var g=f[l];typeof g=="function"&&(g=g.call(a,o)),h+="/"+l+" "+g+" ",a.internal.acroformPlugin.xForms.indexOf(g)>=0||a.internal.acroformPlugin.xForms.push(g)}}else typeof(g=f)=="function"&&(g=g.call(a,o)),h+="/"+l+" "+g,a.internal.acroformPlugin.xForms.indexOf(g)>=0||a.internal.acroformPlugin.xForms.push(g);h+=">>"}c.push({key:"AP",value:`<< `+h+">>"})}a.internal.putStream({additionalKeyValues:c,objectId:o.objId}),a.internal.out("endobj")}i&&function(x,y){for(var v in x)if(x.hasOwnProperty(v)){var b=v,w=x[v];y.internal.newObjectDeferredBegin(w.objId,!0),Pm(w)==="object"&&typeof w.putStream=="function"&&w.putStream(),delete x[b]}}(a.internal.acroformPlugin.xForms,a)})(n,s)}),s.internal.acroformPlugin.isInitialized=!0}},lss=mx.__acroform__.arrayToPdfArray=function(s,t,n){var r=function(l){return l};if(Array.isArray(s)){for(var a="[",i=0;i0?t:void 0}}),Object.defineProperty(this,"Fields",{enumerable:!1,configurable:!1,get:function(){return t}}),Object.defineProperty(this,"DA",{enumerable:!1,configurable:!1,get:function(){if(s){var n=function(r){return r};return this.scope&&(n=this.scope.internal.getEncryptor(this.objId)),"("+h9(n(s))+")"}},set:function(n){s=n}})};Jw(dss,w4);var MC=function s(){w4.call(this);var t=4;Object.defineProperty(this,"F",{enumerable:!1,configurable:!1,get:function(){return t},set:function(v){if(isNaN(v))throw new Error('Invalid value "'+v+'" for attribute F supplied.');t=v}}),Object.defineProperty(this,"showWhenPrinted",{enumerable:!0,configurable:!0,get:function(){return!!ny(t,3)},set:function(v){v?this.F=ry(t,3):this.F=ay(t,3)}});var n=0;Object.defineProperty(this,"Ff",{enumerable:!1,configurable:!1,get:function(){return n},set:function(v){if(isNaN(v))throw new Error('Invalid value "'+v+'" for attribute Ff supplied.');n=v}});var r=[];Object.defineProperty(this,"Rect",{enumerable:!1,configurable:!1,get:function(){if(r.length!==0)return r},set:function(v){r=v!==void 0?v:[]}}),Object.defineProperty(this,"x",{enumerable:!0,configurable:!0,get:function(){return!r||isNaN(r[0])?0:r[0]},set:function(v){r[0]=v}}),Object.defineProperty(this,"y",{enumerable:!0,configurable:!0,get:function(){return!r||isNaN(r[1])?0:r[1]},set:function(v){r[1]=v}}),Object.defineProperty(this,"width",{enumerable:!0,configurable:!0,get:function(){return!r||isNaN(r[2])?0:r[2]},set:function(v){r[2]=v}}),Object.defineProperty(this,"height",{enumerable:!0,configurable:!0,get:function(){return!r||isNaN(r[3])?0:r[3]},set:function(v){r[3]=v}});var a="";Object.defineProperty(this,"FT",{enumerable:!0,configurable:!1,get:function(){return a},set:function(v){switch(v){case"/Btn":case"/Tx":case"/Ch":case"/Sig":a=v;break;default:throw new Error('Invalid value "'+v+'" for attribute FT supplied.')}}});var i=null;Object.defineProperty(this,"T",{enumerable:!0,configurable:!1,get:function(){if(!i||i.length<1){if(this instanceof fPe)return;i="FieldObject"+s.FieldNum++}var v=function(b){return b};return this.scope&&(v=this.scope.internal.getEncryptor(this.objId)),"("+h9(v(i))+")"},set:function(v){i=v.toString()}}),Object.defineProperty(this,"fieldName",{configurable:!0,enumerable:!0,get:function(){return i},set:function(v){i=v}});var l="helvetica";Object.defineProperty(this,"fontName",{enumerable:!0,configurable:!0,get:function(){return l},set:function(v){l=v}});var o="normal";Object.defineProperty(this,"fontStyle",{enumerable:!0,configurable:!0,get:function(){return o},set:function(v){o=v}});var c=0;Object.defineProperty(this,"fontSize",{enumerable:!0,configurable:!0,get:function(){return c},set:function(v){c=v}});var d=void 0;Object.defineProperty(this,"maxFontSize",{enumerable:!0,configurable:!0,get:function(){return d===void 0?50/Eot:d},set:function(v){d=v}});var u="black";Object.defineProperty(this,"color",{enumerable:!0,configurable:!0,get:function(){return u},set:function(v){u=v}});var h="/F1 0 Tf 0 g";Object.defineProperty(this,"DA",{enumerable:!0,configurable:!1,get:function(){if(!(!h||this instanceof fPe||this instanceof M7))return E$e(h,this.objId,this.scope)},set:function(v){v=v.toString(),h=v}});var m=null;Object.defineProperty(this,"DV",{enumerable:!1,configurable:!1,get:function(){if(m)return this instanceof gv==0?E$e(m,this.objId,this.scope):m},set:function(v){v=v.toString(),m=this instanceof gv==0?v.substr(0,1)==="("?W$(v.substr(1,v.length-2)):W$(v):v}}),Object.defineProperty(this,"defaultValue",{enumerable:!0,configurable:!0,get:function(){return this instanceof gv==1?W$(m.substr(1,m.length-1)):m},set:function(v){v=v.toString(),m=this instanceof gv==1?"/"+yB(v):v}});var f=null;Object.defineProperty(this,"_V",{enumerable:!1,configurable:!1,get:function(){if(f)return f},set:function(v){this.V=v}}),Object.defineProperty(this,"V",{enumerable:!1,configurable:!1,get:function(){if(f)return this instanceof gv==0?E$e(f,this.objId,this.scope):f},set:function(v){v=v.toString(),f=this instanceof gv==0?v.substr(0,1)==="("?W$(v.substr(1,v.length-2)):W$(v):v}}),Object.defineProperty(this,"value",{enumerable:!0,configurable:!0,get:function(){return this instanceof gv==1?W$(f.substr(1,f.length-1)):f},set:function(v){v=v.toString(),f=this instanceof gv==1?"/"+yB(v):v}}),Object.defineProperty(this,"hasAnnotation",{enumerable:!0,configurable:!0,get:function(){return this.Rect}}),Object.defineProperty(this,"Type",{enumerable:!0,configurable:!1,get:function(){return this.hasAnnotation?"/Annot":null}}),Object.defineProperty(this,"Subtype",{enumerable:!0,configurable:!1,get:function(){return this.hasAnnotation?"/Widget":null}});var g,x=!1;Object.defineProperty(this,"hasAppearanceStream",{enumerable:!0,configurable:!0,get:function(){return x},set:function(v){v=!!v,x=v}}),Object.defineProperty(this,"page",{enumerable:!0,configurable:!0,get:function(){if(g)return g},set:function(v){g=v}}),Object.defineProperty(this,"readOnly",{enumerable:!0,configurable:!0,get:function(){return!!ny(this.Ff,1)},set:function(v){v?this.Ff=ry(this.Ff,1):this.Ff=ay(this.Ff,1)}}),Object.defineProperty(this,"required",{enumerable:!0,configurable:!0,get:function(){return!!ny(this.Ff,2)},set:function(v){v?this.Ff=ry(this.Ff,2):this.Ff=ay(this.Ff,2)}}),Object.defineProperty(this,"noExport",{enumerable:!0,configurable:!0,get:function(){return!!ny(this.Ff,3)},set:function(v){v?this.Ff=ry(this.Ff,3):this.Ff=ay(this.Ff,3)}});var y=null;Object.defineProperty(this,"Q",{enumerable:!0,configurable:!1,get:function(){if(y!==null)return y},set:function(v){if([0,1,2].indexOf(v)===-1)throw new Error('Invalid value "'+v+'" for attribute Q supplied.');y=v}}),Object.defineProperty(this,"textAlign",{get:function(){var v;switch(y){case 0:default:v="left";break;case 1:v="center";break;case 2:v="right"}return v},configurable:!0,enumerable:!0,set:function(v){switch(v){case"right":case 2:y=2;break;case"center":case 1:y=1;break;default:y=0}}})};Jw(MC,w4);var zV=function(){MC.call(this),this.FT="/Ch",this.V="()",this.fontName="zapfdingbats";var s=0;Object.defineProperty(this,"TI",{enumerable:!0,configurable:!1,get:function(){return s},set:function(n){s=n}}),Object.defineProperty(this,"topIndex",{enumerable:!0,configurable:!0,get:function(){return s},set:function(n){s=n}});var t=[];Object.defineProperty(this,"Opt",{enumerable:!0,configurable:!1,get:function(){return lss(t,this.objId,this.scope)},set:function(n){var r,a;a=[],typeof(r=n)=="string"&&(a=function(i,l,o){o||(o=1);for(var c,d=[];c=l.exec(i);)d.push(c[o]);return d}(r,/\((.*?)\)/g)),t=a}}),this.getOptions=function(){return t},this.setOptions=function(n){t=n,this.sort&&t.sort()},this.addOption=function(n){n=(n=n||"").toString(),t.push(n),this.sort&&t.sort()},this.removeOption=function(n,r){for(r=r||!1,n=(n=n||"").toString();t.indexOf(n)!==-1&&(t.splice(t.indexOf(n),1),r!==!1););},Object.defineProperty(this,"combo",{enumerable:!0,configurable:!0,get:function(){return!!ny(this.Ff,18)},set:function(n){n?this.Ff=ry(this.Ff,18):this.Ff=ay(this.Ff,18)}}),Object.defineProperty(this,"edit",{enumerable:!0,configurable:!0,get:function(){return!!ny(this.Ff,19)},set:function(n){this.combo===!0&&(n?this.Ff=ry(this.Ff,19):this.Ff=ay(this.Ff,19))}}),Object.defineProperty(this,"sort",{enumerable:!0,configurable:!0,get:function(){return!!ny(this.Ff,20)},set:function(n){n?(this.Ff=ry(this.Ff,20),t.sort()):this.Ff=ay(this.Ff,20)}}),Object.defineProperty(this,"multiSelect",{enumerable:!0,configurable:!0,get:function(){return!!ny(this.Ff,22)},set:function(n){n?this.Ff=ry(this.Ff,22):this.Ff=ay(this.Ff,22)}}),Object.defineProperty(this,"doNotSpellCheck",{enumerable:!0,configurable:!0,get:function(){return!!ny(this.Ff,23)},set:function(n){n?this.Ff=ry(this.Ff,23):this.Ff=ay(this.Ff,23)}}),Object.defineProperty(this,"commitOnSelChange",{enumerable:!0,configurable:!0,get:function(){return!!ny(this.Ff,27)},set:function(n){n?this.Ff=ry(this.Ff,27):this.Ff=ay(this.Ff,27)}}),this.hasAppearanceStream=!1};Jw(zV,MC);var BV=function(){zV.call(this),this.fontName="helvetica",this.combo=!1};Jw(BV,zV);var $V=function(){BV.call(this),this.combo=!0};Jw($V,BV);var L3e=function(){$V.call(this),this.edit=!0};Jw(L3e,$V);var gv=function(){MC.call(this),this.FT="/Btn",Object.defineProperty(this,"noToggleToOff",{enumerable:!0,configurable:!0,get:function(){return!!ny(this.Ff,15)},set:function(n){n?this.Ff=ry(this.Ff,15):this.Ff=ay(this.Ff,15)}}),Object.defineProperty(this,"radio",{enumerable:!0,configurable:!0,get:function(){return!!ny(this.Ff,16)},set:function(n){n?this.Ff=ry(this.Ff,16):this.Ff=ay(this.Ff,16)}}),Object.defineProperty(this,"pushButton",{enumerable:!0,configurable:!0,get:function(){return!!ny(this.Ff,17)},set:function(n){n?this.Ff=ry(this.Ff,17):this.Ff=ay(this.Ff,17)}}),Object.defineProperty(this,"radioIsUnison",{enumerable:!0,configurable:!0,get:function(){return!!ny(this.Ff,26)},set:function(n){n?this.Ff=ry(this.Ff,26):this.Ff=ay(this.Ff,26)}});var s,t={};Object.defineProperty(this,"MK",{enumerable:!1,configurable:!1,get:function(){var n=function(i){return i};if(this.scope&&(n=this.scope.internal.getEncryptor(this.objId)),Object.keys(t).length!==0){var r,a=[];for(r in a.push("<<"),t)a.push("/"+r+" ("+h9(n(t[r]))+")");return a.push(">>"),a.join(` `)}},set:function(n){Pm(n)==="object"&&(t=n)}}),Object.defineProperty(this,"caption",{enumerable:!0,configurable:!0,get:function(){return t.CA||""},set:function(n){typeof n=="string"&&(t.CA=n)}}),Object.defineProperty(this,"AS",{enumerable:!1,configurable:!1,get:function(){return s},set:function(n){var r=n==null?"":n.toString();r.substr(0,1)==="/"&&(r=r.substr(1)),s="/"+yB(r)}}),Object.defineProperty(this,"appearanceState",{enumerable:!0,configurable:!0,get:function(){return s.substr(1,s.length-1)},set:function(n){s="/"+yB(n)}})};Jw(gv,MC);var R3e=function(){gv.call(this),this.pushButton=!0};Jw(R3e,gv);var UV=function(){gv.call(this),this.radio=!0,this.pushButton=!1;var s=[];Object.defineProperty(this,"Kids",{enumerable:!0,configurable:!1,get:function(){return s},set:function(t){s=t!==void 0?t:[]}})};Jw(UV,gv);var fPe=function(){var s,t;MC.call(this),Object.defineProperty(this,"Parent",{enumerable:!1,configurable:!1,get:function(){return s},set:function(a){s=a}}),Object.defineProperty(this,"optionName",{enumerable:!1,configurable:!0,get:function(){return t},set:function(a){t=a}});var n,r={};Object.defineProperty(this,"MK",{enumerable:!1,configurable:!1,get:function(){var a=function(o){return o};this.scope&&(a=this.scope.internal.getEncryptor(this.objId));var i,l=[];for(i in l.push("<<"),r)l.push("/"+i+" ("+h9(a(r[i]))+")");return l.push(">>"),l.join(` `)},set:function(a){Pm(a)==="object"&&(r=a)}}),Object.defineProperty(this,"caption",{enumerable:!0,configurable:!0,get:function(){return r.CA||""},set:function(a){typeof a=="string"&&(r.CA=a)}}),Object.defineProperty(this,"AS",{enumerable:!1,configurable:!1,get:function(){return n},set:function(a){var i=a==null?"":a.toString();i.substr(0,1)==="/"&&(i=i.substr(1)),n="/"+yB(i)}}),Object.defineProperty(this,"appearanceState",{enumerable:!0,configurable:!0,get:function(){return n.substr(1,n.length-1)},set:function(a){var i=a==null?"":a.toString();i.substr(0,1)==="/"&&(i=i.substr(1)),n="/"+yB(i)}}),this.caption="l",this.appearanceState="Off",this._AppearanceType=$o.RadioButton.Circle,this.appearanceStreamContent=this._AppearanceType.createAppearanceStream(this.optionName)};Jw(fPe,MC),UV.prototype.setAppearance=function(s){if(!("createAppearanceStream"in s)||!("getCA"in s))throw new Error("Couldn't assign Appearance to RadioButton. Appearance was Invalid!");for(var t in this.Kids)if(this.Kids.hasOwnProperty(t)){var n=this.Kids[t];n.appearanceStreamContent=s.createAppearanceStream(n.optionName),n.caption=s.getCA()}},UV.prototype.createOption=function(s){var t=new fPe;return t.Parent=this,t.optionName=s,this.Kids.push(t),zWn.call(this.scope,t),t};var D3e=function(){gv.call(this),this.fontName="zapfdingbats",this.caption="3",this.appearanceState="On",this.value="On",this.textAlign="center",this.appearanceStreamContent=$o.CheckBox.createAppearanceStream()};Jw(D3e,gv);var M7=function(){MC.call(this),this.FT="/Tx",Object.defineProperty(this,"multiline",{enumerable:!0,configurable:!0,get:function(){return!!ny(this.Ff,13)},set:function(t){t?this.Ff=ry(this.Ff,13):this.Ff=ay(this.Ff,13)}}),Object.defineProperty(this,"fileSelect",{enumerable:!0,configurable:!0,get:function(){return!!ny(this.Ff,21)},set:function(t){t?this.Ff=ry(this.Ff,21):this.Ff=ay(this.Ff,21)}}),Object.defineProperty(this,"doNotSpellCheck",{enumerable:!0,configurable:!0,get:function(){return!!ny(this.Ff,23)},set:function(t){t?this.Ff=ry(this.Ff,23):this.Ff=ay(this.Ff,23)}}),Object.defineProperty(this,"doNotScroll",{enumerable:!0,configurable:!0,get:function(){return!!ny(this.Ff,24)},set:function(t){t?this.Ff=ry(this.Ff,24):this.Ff=ay(this.Ff,24)}}),Object.defineProperty(this,"comb",{enumerable:!0,configurable:!0,get:function(){return!!ny(this.Ff,25)},set:function(t){t?this.Ff=ry(this.Ff,25):this.Ff=ay(this.Ff,25)}}),Object.defineProperty(this,"richText",{enumerable:!0,configurable:!0,get:function(){return!!ny(this.Ff,26)},set:function(t){t?this.Ff=ry(this.Ff,26):this.Ff=ay(this.Ff,26)}});var s=null;Object.defineProperty(this,"MaxLen",{enumerable:!0,configurable:!1,get:function(){return s},set:function(t){s=t}}),Object.defineProperty(this,"maxLength",{enumerable:!0,configurable:!0,get:function(){return s},set:function(t){Number.isInteger(t)&&(s=t)}}),Object.defineProperty(this,"hasAppearanceStream",{enumerable:!0,configurable:!0,get:function(){return this.V||this.DV}})};Jw(M7,MC);var F3e=function(){M7.call(this),Object.defineProperty(this,"password",{enumerable:!0,configurable:!0,get:function(){return!!ny(this.Ff,14)},set:function(s){s?this.Ff=ry(this.Ff,14):this.Ff=ay(this.Ff,14)}}),this.password=!0};Jw(F3e,M7);var $o={CheckBox:{createAppearanceStream:function(){return{N:{On:$o.CheckBox.YesNormal},D:{On:$o.CheckBox.YesPushDown,Off:$o.CheckBox.OffPushDown}}},YesPushDown:function(s){var t=b5(s);t.scope=s.scope;var n=[],r=s.scope.internal.getFont(s.fontName,s.fontStyle).id,a=s.scope.__private__.encodeColorString(s.color),i=yZe(s,s.caption);return n.push("0.749023 g"),n.push("0 0 "+cd($o.internal.getWidth(s))+" "+cd($o.internal.getHeight(s))+" re"),n.push("f"),n.push("BMC"),n.push("q"),n.push("0 0 1 rg"),n.push("/"+r+" "+cd(i.fontSize)+" Tf "+a),n.push("BT"),n.push(i.text),n.push("ET"),n.push("Q"),n.push("EMC"),t.stream=n.join(` `),t},YesNormal:function(s){var t=b5(s);t.scope=s.scope;var n=s.scope.internal.getFont(s.fontName,s.fontStyle).id,r=s.scope.__private__.encodeColorString(s.color),a=[],i=$o.internal.getHeight(s),l=$o.internal.getWidth(s),o=yZe(s,s.caption);return a.push("1 g"),a.push("0 0 "+cd(l)+" "+cd(i)+" re"),a.push("f"),a.push("q"),a.push("0 0 1 rg"),a.push("0 0 "+cd(l-1)+" "+cd(i-1)+" re"),a.push("W"),a.push("n"),a.push("0 g"),a.push("BT"),a.push("/"+n+" "+cd(o.fontSize)+" Tf "+r),a.push(o.text),a.push("ET"),a.push("Q"),t.stream=a.join(` `),t},OffPushDown:function(s){var t=b5(s);t.scope=s.scope;var n=[];return n.push("0.749023 g"),n.push("0 0 "+cd($o.internal.getWidth(s))+" "+cd($o.internal.getHeight(s))+" re"),n.push("f"),t.stream=n.join(` `),t}},RadioButton:{Circle:{createAppearanceStream:function(s){var t={D:{Off:$o.RadioButton.Circle.OffPushDown},N:{}};return t.N[s]=$o.RadioButton.Circle.YesNormal,t.D[s]=$o.RadioButton.Circle.YesPushDown,t},getCA:function(){return"l"},YesNormal:function(s){var t=b5(s);t.scope=s.scope;var n=[],r=$o.internal.getWidth(s)<=$o.internal.getHeight(s)?$o.internal.getWidth(s)/4:$o.internal.getHeight(s)/4;r=Number((.9*r).toFixed(5));var a=$o.internal.Bezier_C,i=Number((r*a).toFixed(5));return n.push("q"),n.push("1 0 0 1 "+MM($o.internal.getWidth(s)/2)+" "+MM($o.internal.getHeight(s)/2)+" cm"),n.push(r+" 0 m"),n.push(r+" "+i+" "+i+" "+r+" 0 "+r+" c"),n.push("-"+i+" "+r+" -"+r+" "+i+" -"+r+" 0 c"),n.push("-"+r+" -"+i+" -"+i+" -"+r+" 0 -"+r+" c"),n.push(i+" -"+r+" "+r+" -"+i+" "+r+" 0 c"),n.push("f"),n.push("Q"),t.stream=n.join(` `),t},YesPushDown:function(s){var t=b5(s);t.scope=s.scope;var n=[],r=$o.internal.getWidth(s)<=$o.internal.getHeight(s)?$o.internal.getWidth(s)/4:$o.internal.getHeight(s)/4;r=Number((.9*r).toFixed(5));var a=Number((2*r).toFixed(5)),i=Number((a*$o.internal.Bezier_C).toFixed(5)),l=Number((r*$o.internal.Bezier_C).toFixed(5));return n.push("0.749023 g"),n.push("q"),n.push("1 0 0 1 "+MM($o.internal.getWidth(s)/2)+" "+MM($o.internal.getHeight(s)/2)+" cm"),n.push(a+" 0 m"),n.push(a+" "+i+" "+i+" "+a+" 0 "+a+" c"),n.push("-"+i+" "+a+" -"+a+" "+i+" -"+a+" 0 c"),n.push("-"+a+" -"+i+" -"+i+" -"+a+" 0 -"+a+" c"),n.push(i+" -"+a+" "+a+" -"+i+" "+a+" 0 c"),n.push("f"),n.push("Q"),n.push("0 g"),n.push("q"),n.push("1 0 0 1 "+MM($o.internal.getWidth(s)/2)+" "+MM($o.internal.getHeight(s)/2)+" cm"),n.push(r+" 0 m"),n.push(r+" "+l+" "+l+" "+r+" 0 "+r+" c"),n.push("-"+l+" "+r+" -"+r+" "+l+" -"+r+" 0 c"),n.push("-"+r+" -"+l+" -"+l+" -"+r+" 0 -"+r+" c"),n.push(l+" -"+r+" "+r+" -"+l+" "+r+" 0 c"),n.push("f"),n.push("Q"),t.stream=n.join(` `),t},OffPushDown:function(s){var t=b5(s);t.scope=s.scope;var n=[],r=$o.internal.getWidth(s)<=$o.internal.getHeight(s)?$o.internal.getWidth(s)/4:$o.internal.getHeight(s)/4;r=Number((.9*r).toFixed(5));var a=Number((2*r).toFixed(5)),i=Number((a*$o.internal.Bezier_C).toFixed(5));return n.push("0.749023 g"),n.push("q"),n.push("1 0 0 1 "+MM($o.internal.getWidth(s)/2)+" "+MM($o.internal.getHeight(s)/2)+" cm"),n.push(a+" 0 m"),n.push(a+" "+i+" "+i+" "+a+" 0 "+a+" c"),n.push("-"+i+" "+a+" -"+a+" "+i+" -"+a+" 0 c"),n.push("-"+a+" -"+i+" -"+i+" -"+a+" 0 -"+a+" c"),n.push(i+" -"+a+" "+a+" -"+i+" "+a+" 0 c"),n.push("f"),n.push("Q"),t.stream=n.join(` `),t}},Cross:{createAppearanceStream:function(s){var t={D:{Off:$o.RadioButton.Cross.OffPushDown},N:{}};return t.N[s]=$o.RadioButton.Cross.YesNormal,t.D[s]=$o.RadioButton.Cross.YesPushDown,t},getCA:function(){return"8"},YesNormal:function(s){var t=b5(s);t.scope=s.scope;var n=[],r=$o.internal.calculateCross(s);return n.push("q"),n.push("1 1 "+cd($o.internal.getWidth(s)-2)+" "+cd($o.internal.getHeight(s)-2)+" re"),n.push("W"),n.push("n"),n.push(cd(r.x1.x)+" "+cd(r.x1.y)+" m"),n.push(cd(r.x2.x)+" "+cd(r.x2.y)+" l"),n.push(cd(r.x4.x)+" "+cd(r.x4.y)+" m"),n.push(cd(r.x3.x)+" "+cd(r.x3.y)+" l"),n.push("s"),n.push("Q"),t.stream=n.join(` `),t},YesPushDown:function(s){var t=b5(s);t.scope=s.scope;var n=$o.internal.calculateCross(s),r=[];return r.push("0.749023 g"),r.push("0 0 "+cd($o.internal.getWidth(s))+" "+cd($o.internal.getHeight(s))+" re"),r.push("f"),r.push("q"),r.push("1 1 "+cd($o.internal.getWidth(s)-2)+" "+cd($o.internal.getHeight(s)-2)+" re"),r.push("W"),r.push("n"),r.push(cd(n.x1.x)+" "+cd(n.x1.y)+" m"),r.push(cd(n.x2.x)+" "+cd(n.x2.y)+" l"),r.push(cd(n.x4.x)+" "+cd(n.x4.y)+" m"),r.push(cd(n.x3.x)+" "+cd(n.x3.y)+" l"),r.push("s"),r.push("Q"),t.stream=r.join(` `),t},OffPushDown:function(s){var t=b5(s);t.scope=s.scope;var n=[];return n.push("0.749023 g"),n.push("0 0 "+cd($o.internal.getWidth(s))+" "+cd($o.internal.getHeight(s))+" re"),n.push("f"),t.stream=n.join(` `),t}}},createDefaultAppearanceStream:function(s){var t=s.scope.internal.getFont(s.fontName,s.fontStyle).id,n=s.scope.__private__.encodeColorString(s.color);return"/"+t+" "+s.fontSize+" Tf "+n}};$o.internal={Bezier_C:.551915024494,calculateCross:function(s){var t=$o.internal.getWidth(s),n=$o.internal.getHeight(s),r=Math.min(t,n);return{x1:{x:(t-r)/2,y:(n-r)/2+r},x2:{x:(t-r)/2+r,y:(n-r)/2},x3:{x:(t-r)/2,y:(n-r)/2},x4:{x:(t-r)/2+r,y:(n-r)/2+r}}}},$o.internal.getWidth=function(s){var t=0;return Pm(s)==="object"&&(t=F4t(s.Rect[2])),t},$o.internal.getHeight=function(s){var t=0;return Pm(s)==="object"&&(t=F4t(s.Rect[3])),t};var zWn=mx.addField=function(s){if(OWn(this,s),!(s instanceof MC))throw new Error("Invalid argument passed to jsPDF.addField.");var t;return(t=s).scope.internal.acroformPlugin.printedOut&&(t.scope.internal.acroformPlugin.printedOut=!1,t.scope.internal.acroformPlugin.acroFormDictionaryRoot=null),t.scope.internal.acroformPlugin.acroFormDictionaryRoot.Fields.push(t),s.page=s.scope.internal.getCurrentPageInfo().pageNumber,this};mx.AcroFormChoiceField=zV,mx.AcroFormListBox=BV,mx.AcroFormComboBox=$V,mx.AcroFormEditBox=L3e,mx.AcroFormButton=gv,mx.AcroFormPushButton=R3e,mx.AcroFormRadioButton=UV,mx.AcroFormCheckBox=D3e,mx.AcroFormTextField=M7,mx.AcroFormPasswordField=F3e,mx.AcroFormAppearance=$o,mx.AcroForm={ChoiceField:zV,ListBox:BV,ComboBox:$V,EditBox:L3e,Button:gv,PushButton:R3e,RadioButton:UV,CheckBox:D3e,TextField:M7,PasswordField:F3e,Appearance:$o},Go.AcroForm={ChoiceField:zV,ListBox:BV,ComboBox:$V,EditBox:L3e,Button:gv,PushButton:R3e,RadioButton:UV,CheckBox:D3e,TextField:M7,PasswordField:F3e,Appearance:$o};Go.AcroForm;function uss(s){return s.reduce(function(t,n,r){return t[n]=r,t},{})}(function(s){var t="addImage_";s.__addimage__={};var n="UNKNOWN",r={PNG:[[137,80,78,71]],TIFF:[[77,77,0,42],[73,73,42,0]],JPEG:[[255,216,255,224,void 0,void 0,74,70,73,70,0],[255,216,255,225,void 0,void 0,69,120,105,102,0,0],[255,216,255,219],[255,216,255,238]],JPEG2000:[[0,0,0,12,106,80,32,32]],GIF87a:[[71,73,70,56,55,97]],GIF89a:[[71,73,70,56,57,97]],WEBP:[[82,73,70,70,void 0,void 0,void 0,void 0,87,69,66,80]],BMP:[[66,77],[66,65],[67,73],[67,80],[73,67],[80,84]]},a=s.__addimage__.getImageFileTypeByImageData=function(O,U){var W,V,G,Y,X,ae=n;if((U=U||n)==="RGBA"||O.data!==void 0&&O.data instanceof Uint8ClampedArray&&"height"in O&&"width"in O)return"RGBA";if(E(O))for(X in r)for(G=r[X],W=0;W>"}),"transparency"in U&&Array.isArray(U.transparency)&&U.transparency.length>0){for(var X="",ae=0,ie=U.transparency.length;ae>",x.content=i;var w=x.objId+" 0 R";i="<>";else if(r.options.pageNumber)switch(i="<=0};s.__arabicParser__.arabicLetterHasIsolatedForm=function(x){return l(x)&&i(x)&&t[x.charCodeAt(0)].length>=1};var d=s.__arabicParser__.arabicLetterHasFinalForm=function(x){return l(x)&&i(x)&&t[x.charCodeAt(0)].length>=2};s.__arabicParser__.arabicLetterHasInitialForm=function(x){return l(x)&&i(x)&&t[x.charCodeAt(0)].length>=3};var u=s.__arabicParser__.arabicLetterHasMedialForm=function(x){return l(x)&&i(x)&&t[x.charCodeAt(0)].length==4},h=s.__arabicParser__.resolveLigatures=function(x){var y=0,v=n,b="",w=0;for(y=0;y>"),this.internal.out("endobj")}),this.internal.events.subscribe("putCatalog",function(){this.internal.out("/OpenAction "+t+" 0 R")})),this},function(s){var t=function(){var n=void 0;Object.defineProperty(this,"pdf",{get:function(){return n},set:function(o){n=o}});var r=150;Object.defineProperty(this,"width",{get:function(){return r},set:function(o){r=isNaN(o)||Number.isInteger(o)===!1||o<0?150:o,this.getContext("2d").pageWrapXEnabled&&(this.getContext("2d").pageWrapX=r+1)}});var a=300;Object.defineProperty(this,"height",{get:function(){return a},set:function(o){a=isNaN(o)||Number.isInteger(o)===!1||o<0?300:o,this.getContext("2d").pageWrapYEnabled&&(this.getContext("2d").pageWrapY=a+1)}});var i=[];Object.defineProperty(this,"childNodes",{get:function(){return i},set:function(o){i=o}});var l={};Object.defineProperty(this,"style",{get:function(){return l},set:function(o){l=o}}),Object.defineProperty(this,"parentNode",{})};t.prototype.getContext=function(n,r){var a;if((n=n||"2d")!=="2d")return null;for(a in r)this.pdf.context2d.hasOwnProperty(a)&&(this.pdf.context2d[a]=r[a]);return this.pdf.context2d._canvas=this,this.pdf.context2d},t.prototype.toDataURL=function(){throw new Error("toDataURL is not implemented.")},s.events.push(["initialized",function(){this.canvas=new t,this.canvas.pdf=this}])}(Go.API),function(s){var t={left:0,top:0,bottom:0,right:0},n=!1,r=function(){this.internal.__cell__===void 0&&(this.internal.__cell__={},this.internal.__cell__.padding=3,this.internal.__cell__.headerFunction=void 0,this.internal.__cell__.margins=Object.assign({},t),this.internal.__cell__.margins.width=this.getPageWidth(),a.call(this))},a=function(){this.internal.__cell__.lastCell=new i,this.internal.__cell__.pages=1},i=function(){var c=arguments[0];Object.defineProperty(this,"x",{enumerable:!0,get:function(){return c},set:function(x){c=x}});var d=arguments[1];Object.defineProperty(this,"y",{enumerable:!0,get:function(){return d},set:function(x){d=x}});var u=arguments[2];Object.defineProperty(this,"width",{enumerable:!0,get:function(){return u},set:function(x){u=x}});var h=arguments[3];Object.defineProperty(this,"height",{enumerable:!0,get:function(){return h},set:function(x){h=x}});var m=arguments[4];Object.defineProperty(this,"text",{enumerable:!0,get:function(){return m},set:function(x){m=x}});var f=arguments[5];Object.defineProperty(this,"lineNumber",{enumerable:!0,get:function(){return f},set:function(x){f=x}});var g=arguments[6];return Object.defineProperty(this,"align",{enumerable:!0,get:function(){return g},set:function(x){g=x}}),this};i.prototype.clone=function(){return new i(this.x,this.y,this.width,this.height,this.text,this.lineNumber,this.align)},i.prototype.toArray=function(){return[this.x,this.y,this.width,this.height,this.text,this.lineNumber,this.align]},s.setHeaderFunction=function(c){return r.call(this),this.internal.__cell__.headerFunction=typeof c=="function"?c:void 0,this},s.getTextDimensions=function(c,d){r.call(this);var u=(d=d||{}).fontSize||this.getFontSize(),h=d.font||this.getFont(),m=d.scaleFactor||this.internal.scaleFactor,f=0,g=0,x=0,y=this;if(!Array.isArray(c)&&typeof c!="string"){if(typeof c!="number")throw new Error("getTextDimensions expects text-parameter to be of type String or type Number or an Array of Strings.");c=String(c)}var v=d.maxWidth;v>0?typeof c=="string"?c=this.splitTextToSize(c,v):Object.prototype.toString.call(c)==="[object Array]"&&(c=c.reduce(function(w,S){return w.concat(y.splitTextToSize(S,v))},[])):c=Array.isArray(c)?c:[c];for(var b=0;bthis.getPageHeight()?(this.cellAddPage(),c.y=h.top,f&&m&&(this.printHeaderRow(c.lineNumber,!0),c.y+=m[0].height)):c.y=d.y+d.height||c.y),c.text[0]!==void 0&&(this.rect(c.x,c.y,c.width,c.height,n===!0?"FD":void 0),c.align==="right"?this.text(c.text,c.x+c.width-u,c.y+u,{align:"right",baseline:"top"}):c.align==="center"?this.text(c.text,c.x+c.width/2,c.y+u,{align:"center",baseline:"top",maxWidth:c.width-u-u}):this.text(c.text,c.x+u,c.y+u,{align:"left",baseline:"top",maxWidth:c.width-u-u})),this.internal.__cell__.lastCell=c,this};s.table=function(c,d,u,h,m){if(r.call(this),!u)throw new Error("No data for PDF table.");var f,g,x,y,v=[],b=[],w=[],S={},C={},E=[],I=[],P=(m=m||{}).autoSize||!1,R=m.printHeaders!==!1,D=m.css&&m.css["font-size"]!==void 0?16*m.css["font-size"]:m.fontSize||12,O=m.margins||Object.assign({width:this.getPageWidth()},t),U=typeof m.padding=="number"?m.padding:3,W=m.headerBackgroundColor||"#c8c8c8",V=m.headerTextColor||"#000";if(a.call(this),this.internal.__cell__.printHeaders=R,this.internal.__cell__.margins=O,this.internal.__cell__.table_font_size=D,this.internal.__cell__.padding=U,this.internal.__cell__.headerBackgroundColor=W,this.internal.__cell__.headerTextColor=V,this.setFontSize(D),h==null)b=v=Object.keys(u[0]),w=v.map(function(){return"left"});else if(Array.isArray(h)&&Pm(h[0])==="object")for(v=h.map(function(ne){return ne.name}),b=h.map(function(ne){return ne.prompt||ne.name||""}),w=h.map(function(ne){return ne.align||"left"}),f=0;f0&&this.setTableHeaderRow(m),this.setFont(void 0,"normal"),n=!1}}(Go.API);var hss={italic:["italic","oblique","normal"],oblique:["oblique","italic","normal"],normal:["normal","oblique","italic"]},mss=["ultra-condensed","extra-condensed","condensed","semi-condensed","normal","semi-expanded","expanded","extra-expanded","ultra-expanded"],vZe=uss(mss),fss=[100,200,300,400,500,600,700,800,900],BWn=uss(fss);function T$e(s){var t=s.family.replace(/"|'/g,"").toLowerCase(),n=function(i){return hss[i=i||"normal"]?i:"normal"}(s.style),r=function(i){return i?typeof i=="number"?i>=100&&i<=900&&i%100==0?i:400:/^\d00$/.test(i)?parseInt(i):i==="bold"?700:400:400}(s.weight),a=function(i){return typeof vZe[i=i||"normal"]=="number"?i:"normal"}(s.stretch);return{family:t,style:n,weight:r,stretch:a,src:s.src||[],ref:s.ref||{name:t,style:[a,n,r].join(" ")}}}function O4t(s,t,n,r){var a;for(a=n;a>=0&&a=0&&a>>1)&255}return a}function Y4t(s,t,n){var r=s.length,a=[];a[0]=4;for(var i=0;i>i&l}function Z4t(s,t,n,r){var a=n*r,i=Math.floor(a/8),l=16-(a-8*i+r),o=(1<>8&255;d.setUint8(u,m)}})(s,i,pss(s,i)&~(o<>7,l=1<<1+(7&a);s[t++],s[t++];var o=null,c=null;i&&(o=t,c=l,t+=3*l);var d=!0,u=[],h=0,m=null,f=0,g=null;for(this.width=n,this.height=r;d&&t=0))throw Error("Invalid block size");if(O===0)break;t+=O}break;case 249:if(s[t++]!==4||s[t+4]!==0)throw new Error("Invalid graphics extension block.");var x=s[t++];h=s[t++]|s[t++]<<8,m=s[t++],1&x||(m=null),f=x>>2&7,t++;break;case 254:for(;;){if(!((O=s[t++])>=0))throw Error("Invalid block size");if(O===0)break;t+=O}break;default:throw new Error("Unknown graphic control label: 0x"+s[t-1].toString(16))}break;case 44:var y=s[t++]|s[t++]<<8,v=s[t++]|s[t++]<<8,b=s[t++]|s[t++]<<8,w=s[t++]|s[t++]<<8,S=s[t++],C=S>>6&1,E=1<<1+(7&S),I=o,P=c,R=!1;S>>7&&(R=!0,I=t,P=E,t+=3*E);var D=t;for(t++;;){var O;if(!((O=s[t++])>=0))throw Error("Invalid block size");if(O===0)break;t+=O}u.push({x:y,y:v,width:b,height:w,has_local_palette:R,palette_offset:I,palette_size:P,data_offset:D,data_length:t-D,transparent_index:m,interlaced:!!C,delay:h,disposal:f});break;case 59:d=!1;break;default:throw new Error("Unknown gif block: 0x"+s[t-1].toString(16))}this.numFrames=function(){return u.length},this.loopCount=function(){return g},this.frameInfo=function(U){if(U<0||U>=u.length)throw new Error("Frame index out of range.");return u[U]},this.decodeAndBlitFrameBGRA=function(U,W){var V=this.frameInfo(U),G=V.width*V.height;if(G>536870912)throw new Error("Image dimensions exceed 512MB, which is too large.");var Y=new Uint8Array(G);X4t(s,V.data_offset,Y,G);var X=V.palette_offset,ae=V.transparent_index;ae===null&&(ae=256);var ie=V.width,ne=n-ie,te=ie,J=4*(V.y*n+V.x),ce=4*((V.y+V.height)*n+V.x),_e=J,he=4*ne;V.interlaced===!0&&(he+=4*n*7);for(var ue=8,ve=0,Ee=Y.length;ve=ce&&(he=4*ne+4*n*(ue-1),_e=J+(ie+ne)*(ue<<1),ue>>=1)),Se===ae)_e+=4;else{var Le=s[X+3*Se],Fe=s[X+3*Se+1],ke=s[X+3*Se+2];W[_e++]=ke,W[_e++]=Fe,W[_e++]=Le,W[_e++]=255}--te}},this.decodeAndBlitFrameRGBA=function(U,W){var V=this.frameInfo(U),G=V.width*V.height;if(G>536870912)throw new Error("Image dimensions exceed 512MB, which is too large.");var Y=new Uint8Array(G);X4t(s,V.data_offset,Y,G);var X=V.palette_offset,ae=V.transparent_index;ae===null&&(ae=256);var ie=V.width,ne=n-ie,te=ie,J=4*(V.y*n+V.x),ce=4*((V.y+V.height)*n+V.x),_e=J,he=4*ne;V.interlaced===!0&&(he+=4*n*7);for(var ue=8,ve=0,Ee=Y.length;ve=ce&&(he=4*ne+4*n*(ue-1),_e=J+(ie+ne)*(ue<<1),ue>>=1)),Se===ae)_e+=4;else{var Le=s[X+3*Se],Fe=s[X+3*Se+1],ke=s[X+3*Se+2];W[_e++]=Le,W[_e++]=Fe,W[_e++]=ke,W[_e++]=255}--te}}}function X4t(s,t,n,r){for(var a=s[t++],i=1<>=c,u-=c,y!==i){if(y===l)break;for(var v=yi;)w=g[w]>>8,++b;var S=w;if(m+b+(v!==y?1:0)>r)return void vf.log("Warning, gif stream longer than expected.");n[m++]=S;var C=m+=b;for(v!==y&&(n[m++]=S),w=v;b--;)w=g[w],n[--C]=255&w,w>>=8;x!==null&&o<4096&&(g[o++]=x<<8|S,o>=d+1&&c<12&&(++c,d=d<<1|1)),x=y}else o=l+1,d=(1<<(c=a+1))-1,x=null}return m!==r&&vf.log("Warning, gif stream shorter than expected."),n}/** * @license Copyright (c) 2008, Adobe Systems Incorporated All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Adobe Systems Incorporated nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */function I$e(s){var t,n,r,a,i,l=Math.floor,o=new Array(64),c=new Array(64),d=new Array(64),u=new Array(64),h=new Array(65535),m=new Array(65535),f=new Array(64),g=new Array(64),x=[],y=0,v=7,b=new Array(64),w=new Array(64),S=new Array(64),C=new Array(256),E=new Array(2048),I=[0,1,5,6,14,15,27,28,2,4,7,13,16,26,29,42,3,8,12,17,25,30,41,43,9,11,18,24,31,40,44,53,10,19,23,32,39,45,52,54,20,22,33,38,46,51,55,60,21,34,37,47,50,56,59,61,35,36,48,49,57,58,62,63],P=[0,0,1,5,1,1,1,1,1,1,0,0,0,0,0,0,0],R=[0,1,2,3,4,5,6,7,8,9,10,11],D=[0,0,2,1,3,3,2,4,3,5,5,4,4,0,0,1,125],O=[1,2,3,0,4,17,5,18,33,49,65,6,19,81,97,7,34,113,20,50,129,145,161,8,35,66,177,193,21,82,209,240,36,51,98,114,130,9,10,22,23,24,25,26,37,38,39,40,41,42,52,53,54,55,56,57,58,67,68,69,70,71,72,73,74,83,84,85,86,87,88,89,90,99,100,101,102,103,104,105,106,115,116,117,118,119,120,121,122,131,132,133,134,135,136,137,138,146,147,148,149,150,151,152,153,154,162,163,164,165,166,167,168,169,170,178,179,180,181,182,183,184,185,186,194,195,196,197,198,199,200,201,202,210,211,212,213,214,215,216,217,218,225,226,227,228,229,230,231,232,233,234,241,242,243,244,245,246,247,248,249,250],U=[0,0,3,1,1,1,1,1,1,1,1,1,0,0,0,0,0],W=[0,1,2,3,4,5,6,7,8,9,10,11],V=[0,0,2,1,2,4,4,3,4,7,5,4,4,0,1,2,119],G=[0,1,2,3,17,4,5,33,49,6,18,65,81,7,97,113,19,34,50,129,8,20,66,145,161,177,193,9,35,51,82,240,21,98,114,209,10,22,36,52,225,37,241,23,24,25,26,38,39,40,41,42,53,54,55,56,57,58,67,68,69,70,71,72,73,74,83,84,85,86,87,88,89,90,99,100,101,102,103,104,105,106,115,116,117,118,119,120,121,122,130,131,132,133,134,135,136,137,138,146,147,148,149,150,151,152,153,154,162,163,164,165,166,167,168,169,170,178,179,180,181,182,183,184,185,186,194,195,196,197,198,199,200,201,202,210,211,212,213,214,215,216,217,218,226,227,228,229,230,231,232,233,234,242,243,244,245,246,247,248,249,250];function Y(J,ce){for(var _e=0,he=0,ue=new Array,ve=1;ve<=16;ve++){for(var Ee=1;Ee<=J[ve];Ee++)ue[ce[he]]=[],ue[ce[he]][0]=_e,ue[ce[he]][1]=ve,he++,_e++;_e*=2}return ue}function X(J){for(var ce=J[0],_e=J[1]-1;_e>=0;)ce&1<<_e&&(y|=1<>8&255),ae(255&J)}function ne(J,ce,_e,he,ue){for(var ve,Ee=ue[0],Se=ue[240],Le=function($e,ct){var Xe,it,at,Ke,nt,xt,rt,Yt,qt,ts,ys=0;for(qt=0;qt<8;++qt){Xe=$e[ys],it=$e[ys+1],at=$e[ys+2],Ke=$e[ys+3],nt=$e[ys+4],xt=$e[ys+5],rt=$e[ys+6];var Bt=Xe+(Yt=$e[ys+7]),Ft=Xe-Yt,rs=it+rt,St=it-rt,Xs=at+xt,vt=at-xt,gs=Ke+nt,Ss=Ke-nt,Is=Bt+gs,Ys=Bt-gs,cs=rs+Xs,js=rs-Xs;$e[ys]=Is+cs,$e[ys+4]=Is-cs;var kn=.707106781*(js+Ys);$e[ys+2]=Ys+kn,$e[ys+6]=Ys-kn;var Ws=.382683433*((Is=Ss+vt)-(js=St+Ft)),On=.5411961*Is+Ws,ds=1.306562965*js+Ws,gn=.707106781*(cs=vt+St),As=Ft+gn,hr=Ft-gn;$e[ys+5]=hr+On,$e[ys+3]=hr-On,$e[ys+1]=As+ds,$e[ys+7]=As-ds,ys+=8}for(ys=0,qt=0;qt<8;++qt){Xe=$e[ys],it=$e[ys+8],at=$e[ys+16],Ke=$e[ys+24],nt=$e[ys+32],xt=$e[ys+40],rt=$e[ys+48];var Er=Xe+(Yt=$e[ys+56]),qn=Xe-Yt,hn=it+rt,Fn=it-rt,vn=at+xt,xs=at-xt,Lr=Ke+nt,Or=Ke-nt,ca=Er+Lr,Jn=Er-Lr,Sr=hn+vn,Un=hn-vn;$e[ys]=ca+Sr,$e[ys+32]=ca-Sr;var ur=.707106781*(Un+Jn);$e[ys+16]=Jn+ur,$e[ys+48]=Jn-ur;var Pa=.382683433*((ca=Or+xs)-(Un=Fn+qn)),ii=.5411961*ca+Pa,$i=1.306562965*Un+Pa,Rn=.707106781*(Sr=xs+Fn),xa=qn+Rn,Ya=qn-Rn;$e[ys+40]=Ya+ii,$e[ys+24]=Ya-ii,$e[ys+8]=xa+$i,$e[ys+56]=xa-$i,ys++}for(qt=0;qt<64;++qt)ts=$e[qt]*ct[qt],f[qt]=ts>0?ts+.5|0:ts-.5|0;return f}(J,ce),Fe=0;Fe<64;++Fe)g[I[Fe]]=Le[Fe];var ke=g[0]-_e;_e=g[0],ke==0?X(he[0]):(X(he[m[ve=32767+ke]]),X(h[ve]));for(var Ve=63;Ve>0&&g[Ve]==0;)Ve--;if(Ve==0)return X(Ee),_e;for(var je,Ae=1;Ae<=Ve;){for(var Ce=Ae;g[Ae]==0&&Ae<=Ve;)++Ae;var qe=Ae-Ce;if(qe>=16){je=qe>>4;for(var ze=1;ze<=je;++ze)X(Se);qe&=15}ve=32767+g[Ae],X(ue[(qe<<4)+m[ve]]),X(h[ve]),Ae++}return Ve!=63&&X(Ee),_e}function te(J){J=Math.min(Math.max(J,1),100),i!=J&&(function(ce){for(var _e=[16,11,10,16,24,40,51,61,12,12,14,19,26,58,60,55,14,13,16,24,40,57,69,56,14,17,22,29,51,87,80,62,18,22,37,56,68,109,103,77,24,35,55,64,81,104,113,92,49,64,78,87,103,121,120,101,72,92,95,98,112,100,103,99],he=0;he<64;he++){var ue=l((_e[he]*ce+50)/100);ue=Math.min(Math.max(ue,1),255),o[I[he]]=ue}for(var ve=[17,18,24,47,99,99,99,99,18,21,26,66,99,99,99,99,24,26,56,99,99,99,99,99,47,66,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99],Ee=0;Ee<64;Ee++){var Se=l((ve[Ee]*ce+50)/100);Se=Math.min(Math.max(Se,1),255),c[I[Ee]]=Se}for(var Le=[1,1.387039845,1.306562965,1.175875602,1,.785694958,.5411961,.275899379],Fe=0,ke=0;ke<8;ke++)for(var Ve=0;Ve<8;Ve++)d[Fe]=1/(o[I[Fe]]*Le[ke]*Le[Ve]*8),u[Fe]=1/(c[I[Fe]]*Le[ke]*Le[Ve]*8),Fe++}(J<50?Math.floor(5e3/J):Math.floor(200-2*J)),i=J)}this.encode=function(J,ce){ce&&te(ce),x=new Array,y=0,v=7,ie(65496),ie(65504),ie(16),ae(74),ae(70),ae(73),ae(70),ae(0),ae(1),ae(1),ae(0),ie(1),ie(1),ae(0),ae(0),function(){ie(65499),ie(132),ae(0);for(var it=0;it<64;it++)ae(o[it]);ae(1);for(var at=0;at<64;at++)ae(c[at])}(),function(it,at){ie(65472),ie(17),ae(8),ie(at),ie(it),ae(3),ae(1),ae(17),ae(0),ae(2),ae(17),ae(1),ae(3),ae(17),ae(1)}(J.width,J.height),function(){ie(65476),ie(418),ae(0);for(var it=0;it<16;it++)ae(P[it+1]);for(var at=0;at<=11;at++)ae(R[at]);ae(16);for(var Ke=0;Ke<16;Ke++)ae(D[Ke+1]);for(var nt=0;nt<=161;nt++)ae(O[nt]);ae(1);for(var xt=0;xt<16;xt++)ae(U[xt+1]);for(var rt=0;rt<=11;rt++)ae(W[rt]);ae(17);for(var Yt=0;Yt<16;Yt++)ae(V[Yt+1]);for(var qt=0;qt<=161;qt++)ae(G[qt])}(),ie(65498),ie(12),ae(3),ae(1),ae(0),ae(2),ae(17),ae(3),ae(17),ae(0),ae(63),ae(0);var _e=0,he=0,ue=0;y=0,v=7,this.encode.displayName="_encode_";for(var ve,Ee,Se,Le,Fe,ke,Ve,je,Ae,Ce=J.data,qe=J.width,ze=J.height,$e=4*qe,ct=0;ct>3)*$e+(Ve=4*(7&Ae)),ct+je>=ze&&(ke-=$e*(ct+1+je-ze)),ve+Ve>=$e&&(ke-=ve+Ve-$e+4),Ee=Ce[ke++],Se=Ce[ke++],Le=Ce[ke++],b[Ae]=(E[Ee]+E[Se+256|0]+E[Le+512|0]>>16)-128,w[Ae]=(E[Ee+768|0]+E[Se+1024|0]+E[Le+1280|0]>>16)-128,S[Ae]=(E[Ee+1280|0]+E[Se+1536|0]+E[Le+1792|0]>>16)-128;_e=ne(b,d,_e,t,r),he=ne(w,u,he,n,a),ue=ne(S,u,ue,n,a),ve+=32}ct+=8}if(v>=0){var Xe=[];Xe[1]=v+1,Xe[0]=(1<U;U++)if(R[D+U]!=O.charCodeAt(U))return!0;return!1}function r(R,D,O,U,W){for(var V=0;VV+1?[]:new D),!(G.length>>0;Pe&pt;)pt>>>=1;return pt?(Pe&pt-1)+pt:Pe}function O(Pe,He,pt,Tt,is){t(!(Tt%pt));do Pe[He+(Tt-=pt)]=is;while(0=is),512>=is)var ks=i(512);else if((ks=i(is))==null)return 0;return function(Es,Ds,qs,on,Xn,Cr){var Js,lr,_r=Ds,aa=1<Js;++Js){if(mr[Js]>1<(bl-=mr[Js]))return 0;for(;0=Js;++Js,Xn<<=1){if(Fi+=bl<<=1,0>(bl-=mr[Js]))return 0;for(;0Ua&&!(0>=(dr-=mr[Ua]));)++Ua,dr<<=1;aa+=lo=1<<(dr=Ua-qs),Es[Ds+(Ua=_o&Ea)].g=dr+qs,Es[Ds+Ua].value=_r-Ds-Ua}on.g=Js-qs,on.value=Cr[lr++],O(Es,_r+(_o>>qs),Xn,lo,on),_o=D(_o,Js)}}return Fi!=2*pa[15]-1?0:aa}(Pe,He,pt,Tt,is,ks)}function W(){this.value=this.g=0}function V(){this.value=this.g=0}function G(){this.G=l(5,W),this.H=i(5),this.jc=this.Qb=this.qb=this.nd=0,this.pd=l(id,V)}function Y(Pe,He,pt,Tt){t(Pe!=null),t(He!=null),t(2147483648>Tt),Pe.Ca=254,Pe.I=0,Pe.b=-8,Pe.Ka=0,Pe.oa=He,Pe.pa=pt,Pe.Jd=He,Pe.Yc=pt+Tt,Pe.Zc=4<=Tt?pt+Tt-4+1:pt,Ee(Pe)}function X(Pe,He){for(var pt=0;0Tt),Pe.Sb=Tt,Pe.Ra=0,Pe.u=0,Pe.h=0,4>>=8,Pe.Ra+=Pe.oa[Pe.pa+Pe.bb]<>>0,++Pe.bb,Pe.u-=8;he(Pe)&&(Pe.h=1,Pe.u=0)}function te(Pe,He){if(t(0<=He),!Pe.h&&He<=If){var pt=_e(Pe)&lh[He];return Pe.u+=He,ne(Pe),pt}return Pe.h=1,Pe.u=0}function J(){this.b=this.Ca=this.I=0,this.oa=[],this.pa=0,this.Jd=[],this.Yc=0,this.Zc=[],this.Ka=0}function ce(){this.Ra=0,this.oa=[],this.h=this.u=this.bb=this.Sb=this.pa=0}function _e(Pe){return Pe.Ra>>>(Pe.u&Ud-1)>>>0}function he(Pe){return t(Pe.bb<=Pe.Sb),Pe.h||Pe.bb==Pe.Sb&&Pe.u>Ud}function ue(Pe,He){Pe.u=He,Pe.h=he(Pe)}function ve(Pe){Pe.u>=od&&(t(Pe.u>=od),ne(Pe))}function Ee(Pe){t(Pe!=null&&Pe.oa!=null),Pe.pa>>0,Pe.b+=8):(t(Pe!=null&&Pe.oa!=null),Pe.paPe.b&&Ee(Pe);var Tt=Pe.b,is=pt*He>>>8,ks=(Pe.I>>>Tt>is)+0;for(ks?(pt-=is,Pe.I-=is+1<>>0):pt=is+1,Tt=pt,is=0;256<=Tt;)is+=8,Tt>>=8;return Tt=7^is+Lh[Tt],Pe.b-=Tt,Pe.Ca=(pt<>24&255,Pe[He+1]=pt>>16&255,Pe[He+2]=pt>>8&255,Pe[He+3]=255&pt}function ke(Pe,He){return Pe[He+0]|Pe[He+1]<<8}function Ve(Pe,He){return ke(Pe,He)|Pe[He+2]<<16}function je(Pe,He){return ke(Pe,He)|ke(Pe,He+2)<<16}function Ae(Pe,He){var pt=1<=is||0>=ks?0:(pt[0]=is,Tt[0]=ks,1)}function $e(Pe,He){return Pe+(1<>>He}function ct(Pe,He){return((4278255360&Pe)+(4278255360&He)>>>0&4278255360)+((16711935&Pe)+(16711935&He)>>>0&16711935)>>>0}function Xe(Pe,He){R[He]=function(pt,Tt,is,ks,Es,Ds,qs){var on;for(on=0;on>>1)+(Pe&He)>>>0}function Ke(Pe){return 0<=Pe&&256>Pe?Pe:0>Pe?0:255>1))}function xt(Pe,He,pt){return Math.abs(He-pt)-Math.abs(Pe-pt)}function rt(Pe,He,pt,Tt,is,ks,Es){for(Tt=ks[Es-1],pt=0;pt>8&255,qs=16711935&(qs=(qs=16711935&Es)+((Ds<<16)+Ds));Tt[is+ks]=(4278255360&Es)+qs>>>0}}function qt(Pe,He){He.jd=255&Pe,He.hd=Pe>>8&255,He.ud=Pe>>16&255}function ts(Pe,He,pt,Tt,is,ks){var Es;for(Es=0;Es>>8,on=Ds,Xn=255&(Xn=(Xn=Ds>>>16)+((Pe.jd<<24>>24)*(qs<<24>>24)>>>5));on=255&(on=(on+=(Pe.hd<<24>>24)*(qs<<24>>24)>>>5)+((Pe.ud<<24>>24)*(Xn<<24>>24)>>>5)),is[ks+Es]=(4278255360&Ds)+(Xn<<16)+on}}function ys(Pe,He,pt,Tt,is){R[He]=function(ks,Es,Ds,qs,on,Xn,Cr,Js,lr){for(qs=Cr;qs>ks.b,lr=ks.Ea,_r=ks.K[0],aa=ks.w;if(8>Js)for(ks=(1<>=Js}else R["VP8LMapColor"+pt](qs,on,_r,aa,Xn,Cr,Es,Ds,lr)}}function Bt(Pe,He,pt,Tt,is){for(pt=He+pt;He>16&255,Tt[is++]=ks>>8&255,Tt[is++]=255&ks}}function Ft(Pe,He,pt,Tt,is){for(pt=He+pt;He>16&255,Tt[is++]=ks>>8&255,Tt[is++]=255&ks,Tt[is++]=ks>>24&255}}function rs(Pe,He,pt,Tt,is){for(pt=He+pt;He>16&240|Es>>12&15,Es=240&Es|Es>>28&15;Tt[is++]=ks,Tt[is++]=Es}}function St(Pe,He,pt,Tt,is){for(pt=He+pt;He>16&248|Es>>13&7,Es=Es>>5&224|Es>>3&31;Tt[is++]=ks,Tt[is++]=Es}}function Xs(Pe,He,pt,Tt,is){for(pt=He+pt;He>8&255,Tt[is++]=ks>>16&255}}function vt(Pe,He,pt,Tt,is,ks){if(ks==0)for(pt=He+pt;He>24|ks[1]>>8&65280|ks[2]<<8&16711680|ks[3]<<24)>>>0),is+=32;else r(Tt,is,Pe,He,pt)}function gs(Pe,He){R[He][0]=R[Pe+"0"],R[He][1]=R[Pe+"1"],R[He][2]=R[Pe+"2"],R[He][3]=R[Pe+"3"],R[He][4]=R[Pe+"4"],R[He][5]=R[Pe+"5"],R[He][6]=R[Pe+"6"],R[He][7]=R[Pe+"7"],R[He][8]=R[Pe+"8"],R[He][9]=R[Pe+"9"],R[He][10]=R[Pe+"10"],R[He][11]=R[Pe+"11"],R[He][12]=R[Pe+"12"],R[He][13]=R[Pe+"13"],R[He][14]=R[Pe+"0"],R[He][15]=R[Pe+"0"]}function Ss(Pe){return Pe==O1||Pe==z1||Pe==tj||Pe==sj}function Is(){this.eb=[],this.size=this.A=this.fb=0}function Ys(){this.y=[],this.f=[],this.ea=[],this.F=[],this.Tc=this.Ed=this.Cd=this.Fd=this.lb=this.Db=this.Ab=this.fa=this.J=this.W=this.N=this.O=0}function cs(){this.Rd=this.height=this.width=this.S=0,this.f={},this.f.RGBA=new Is,this.f.kb=new Ys,this.sd=null}function js(){this.width=[0],this.height=[0],this.Pd=[0],this.Qd=[0],this.format=[0]}function kn(){this.Id=this.fd=this.Md=this.hb=this.ib=this.da=this.bd=this.cd=this.j=this.v=this.Da=this.Sd=this.ob=0}function Ws(Pe){return alert("todo:WebPSamplerProcessPlane"),Pe.T}function On(Pe,He){var pt=Pe.T,Tt=He.ba.f.RGBA,is=Tt.eb,ks=Tt.fb+Pe.ka*Tt.A,Es=ip[He.ba.S],Ds=Pe.y,qs=Pe.O,on=Pe.f,Xn=Pe.N,Cr=Pe.ea,Js=Pe.W,lr=He.cc,_r=He.dc,aa=He.Mc,mr=He.Nc,pa=Pe.ka,dr=Pe.ka+Pe.T,Ua=Pe.U,Ea=Ua+1>>1;for(pa==0?Es(Ds,qs,null,null,on,Xn,Cr,Js,on,Xn,Cr,Js,is,ks,null,null,Ua):(Es(He.ec,He.fc,Ds,qs,lr,_r,aa,mr,on,Xn,Cr,Js,is,ks-Tt.A,is,ks,Ua),++pt);pa+2pt,is=pt==np||pt==dh||pt==Rc||pt==Jg||pt==12||Ss(pt);if(He.memory=null,He.Ib=null,He.Jb=null,He.Nd=null,!Td(He.Oa,Pe,is?11:12))return 0;if(is&&Ss(pt)&&Il(),Pe.da)alert("todo:use_scaling");else{if(Tt){if(He.Ib=Ws,Pe.Kb){if(pt=Pe.U+1>>1,He.memory=i(Pe.U+2*pt),He.memory==null)return 0;He.ec=He.memory,He.fc=0,He.cc=He.ec,He.dc=He.fc+Pe.U,He.Mc=He.cc,He.Nc=He.dc+pt,He.Ib=On,Il()}}else alert("todo:EmitYUV");is&&(He.Jb=ds,Tt&&po())}if(Tt&&!zk){for(Pe=0;256>Pe;++Pe)Bk[Pe]=89858*(Pe-128)+G0>>H0,q_[Pe]=-22014*(Pe-128)+G0,rj[Pe]=-45773*(Pe-128),U_[Pe]=113618*(Pe-128)+G0>>H0;for(Pe=zx;Pe>H0,OC[Pe-zx]=ta(He,255),Q2[Pe-zx]=ta(He+8>>4,15);zk=1}return 1}function As(Pe){var He=Pe.ma,pt=Pe.U,Tt=Pe.T;return t(!(1&Pe.ka)),0>=pt||0>=Tt?0:(pt=He.Ib(Pe,He),He.Jb!=null&&He.Jb(Pe,He,pt),He.Dc+=pt,1)}function hr(Pe){Pe.ma.memory=null}function Er(Pe,He,pt,Tt){return te(Pe,8)!=47?0:(He[0]=te(Pe,14)+1,pt[0]=te(Pe,14)+1,Tt[0]=te(Pe,1),te(Pe,3)!=0?0:!Pe.h)}function qn(Pe,He){if(4>Pe)return Pe+1;var pt=Pe-2>>1;return(2+(1&Pe)<>4)*Pe+(8-(15&pt)))?pt:1;var pt}function Fn(Pe,He,pt){var Tt=_e(pt),is=Pe[He+=255&Tt].g-8;return 0>>0,t(8>=pt.g),Pe.g}function xs(Pe,He,pt){var Tt=Pe.xc;return t((He=Tt==0?0:Pe.vc[Pe.md*(pt>>Tt)+(He>>Tt)])>lo.b)*Fi;aaUa&&(yo=Ua),(0,Jc[Dc[mf++]>>8&15])(Js,lr+ +Zl,pa,dr+Zl-Ua,yo-Zl,pa,dr+Zl),Zl=yo}lr+=Ua,dr+=Ua,++aa&_o||(lo+=Fi)}Cr!=on.nc&&r(qs,Ds-_r,qs,Ds+(Cr-Xn-1)*_r,_r);break;case 1:for(_r=Js,mr=lr,Ua=(Js=on.Ea)-(dr=Js&~(pa=(lr=1<>on.b)*aa;Xn=is),0ks.o&&(Tt=ks.o),pt=Tt?pt=0:(is[0]+=4*ks.v,ks.ka=pt-ks.j,ks.U=ks.va-ks.v,ks.T=Tt-pt,pt=1),pt){if(Ds=Ds[0],11>(pt=Pe.ca).S){var Xn=pt.f.RGBA,Cr=(Tt=pt.S,is=ks.U,ks=ks.T,on=Xn.eb,Xn.A),Js=ks;for(Xn=Xn.fb+Pe.Ma*Xn.A;0Tt){var is=Pe.l.width,ks=pt.ca,Es=pt.tb+is*Tt,Ds=Pe.V,qs=Pe.Ba+Pe.c*Tt,on=Pe.gc;t(Pe.ab==1),t(on[0].hc==3),Md(on[0],Tt,He,Ds,qs,ks,Es),Jn(pt,Tt,He,ks,Es,is)}Pe.C=Pe.Ma=He}function Un(Pe,He,pt,Tt,is,ks,Es){var Ds=Pe.$/Tt,qs=Pe.$%Tt,on=Pe.m,Xn=Pe.s,Cr=pt+Pe.$,Js=Cr;is=pt+Tt*is;var lr=pt+Tt*ks,_r=280+Xn.ua,aa=Pe.Pb?Ds:16777216,mr=0=aa){var _o=Cr-pt;t((aa=Pe).Pb),aa.wd=aa.m,aa.xd=_o,0bl.g?(ue(Ea,Ea.u+bl.g),_o[Fi]=bl.value,Ea=0):(ue(Ea,Ea.u+bl.g-256),t(256<=bl.value),Ea=bl.value),Ea==0&&(Ua=!0)}else Ea=Fn(dr.G[0],dr.H[0],on);if(on.h)break;if(Ua||256>Ea){if(!Ua)if(dr.nd)He[Cr]=(dr.qb|Ea<<8)>>>0;else{if(ve(on),Ua=Fn(dr.G[1],dr.H[1],on),ve(on),_o=Fn(dr.G[2],dr.H[2],on),Fi=Fn(dr.G[3],dr.H[3],on),on.h)break;He[Cr]=(Fi<<24|Ua<<16|Ea<<8|_o)>>>0}if(Ua=!1,++Cr,++qs>=Tt&&(qs=0,++Ds,Es!=null&&Ds<=ks&&!(Ds%16)&&Es(Pe,Ds),mr!=null))for(;Js>>mr.Mb]=Ea}else if(280>Ea){if(Ea=qn(Ea-256,on),_o=Fn(dr.G[4],dr.H[4],on),ve(on),_o=hn(Tt,_o=qn(_o,on)),on.h)break;if(Cr-pt<_o||is-Cr=Tt;)qs-=Tt,++Ds,Es!=null&&Ds<=ks&&!(Ds%16)&&Es(Pe,Ds);if(t(Cr<=is),qs&pa&&(dr=xs(Xn,qs,Ds)),mr!=null)for(;Js>>mr.Mb]=Ea}else{if(!(Ea<_r))break e;for(Ua=Ea-280,t(mr!=null);Js>>mr.Mb]=Ea;Ea=Cr,t(!(Ua>>>(_o=mr).Xa)),He[Ea]=_o.X[Ua],Ua=!0}Ua||t(on.h==he(on))}if(Pe.Pb&&on.h&&Crks?ks:Ds),Pe.a=0,Pe.$=Cr-pt}return 1}return Pe.a=3,0}function ur(Pe){t(Pe!=null),Pe.vc=null,Pe.yc=null,Pe.Ya=null;var He=Pe.Wa;He!=null&&(He.X=null),Pe.vb=null,t(Pe!=null)}function Pa(){var Pe=new Qr;return Pe==null?null:(Pe.a=0,Pe.xb=E3,gs("Predictor","VP8LPredictors"),gs("Predictor","VP8LPredictors_C"),gs("PredictorAdd","VP8LPredictorsAdd"),gs("PredictorAdd","VP8LPredictorsAdd_C"),hd=Yt,_d=ts,Ep=Bt,zv=Ft,Rx=rs,ya=St,Zy=Xs,R.VP8LMapColor32b=Xi,R.VP8LMapColor8b=lu,Pe)}function ii(Pe,He,pt,Tt,is){var ks=1,Es=[Pe],Ds=[He],qs=Tt.m,on=Tt.s,Xn=null,Cr=0;e:for(;;){if(pt)for(;ks&&te(qs,1);){var Js=Es,lr=Ds,_r=Tt,aa=1,mr=_r.m,pa=_r.gc[_r.ab],dr=te(mr,2);if(_r.Oc&1<=_r.ab),dr){case 0:case 1:pa.b=te(mr,3)+2,aa=ii($e(pa.Ea,pa.b),$e(pa.nc,pa.b),0,_r,pa.K),pa.K=pa.K[0];break;case 3:var Ua,Ea=te(mr,8)+1,_o=16>lo.b),mf=i(Dc);if(mf==null)Ua=0;else{var Zl=lo.K[0],yo=lo.w;for(mf[0]=lo.K[0][0],Fi=1;Fi<1*bl;++Fi)mf[Fi]=ct(Zl[yo+Fi],mf[Fi-1]);for(;Fi<4*Dc;++Fi)mf[Fi]=0;lo.K[0]=null,lo.K[0]=mf,Ua=1}}aa=Ua;break;case 2:break;default:t(0)}ks=aa}}if(Es=Es[0],Ds=Ds[0],ks&&te(qs,1)&&!(ks=1<=(Cr=te(qs,4))&&11>=Cr)){Tt.a=3;break e}var bi;if(bi=ks)t:{var mm,To,Xl,Uc=Tt,Lf=Es,ig=Ds,Qd=Cr,og=pt,Dh=Uc.m,ff=Uc.s,md=[null],cu=1,uh=0,du=rp[Qd];s:for(;;){if(og&&te(Dh,1)){var Rf=te(Dh,3)+2,op=$e(Lf,Rf),hh=$e(ig,Rf),bh=op*hh;if(!ii(op,hh,0,Uc,md))break s;for(md=md[0],ff.xc=Rf,mm=0;mm>8&65535;md[mm]=vc,vc>=cu&&(cu=vc+1)}}if(Dh.h)break s;for(To=0;5>To;++To){var Fh=Db[To];!To&&0=Df),nx=Mp;var Pp=i(uh);if(nx==null||Pp==null||$m==null){Uc.a=1;break s}var rx=$m;for(mm=Xl=0;mmTo;++To){Fh=Db[To],pf[To]=rx,Pd[To]=Xl,!To&&0Xy)break n}else $x=Xy;for(G1=0;G1K1)qk[G1++]=K1,K1!=0&&(cp=K1);else{var T3=K1==16,Vk=K1-16,KT=Rk[Vk],qv=te(Qy,$_[Vk])+KT;if(G1+qv>Xy)break n;for(var Vv=T3?cp:0;0=To){var W0,G_=Pp[0];for(W0=1;W0G_&&(G_=Pp[W0]);wd+=G_}}if(Jd.nd=Gd,Jd.Qb=0,Gd&&(Jd.qb=(pf[3][Pd[3]+0].value<<24|pf[1][Pd[1]+0].value<<16|pf[2][Pd[2]+0].value)>>>0,Ql==0&&256>pf[0][Pd[0]+0].value&&(Jd.Qb=1,Jd.qb+=pf[0][Pd[0]+0].value<<8)),Jd.jc=!Jd.Qb&&6>wd,Jd.jc){var cg,K0=Jd;for(cg=0;cg>=vn(Hv,8,up),Jy>>=vn(K0.G[1][K0.H[1]+Jy],16,up),Jy>>=vn(K0.G[2][K0.H[2]+Jy],0,up),vn(K0.G[3][K0.H[3]+Jy],24,up))}}}ff.vc=md,ff.Wb=cu,ff.Ya=nx,ff.yc=$m,bi=1;break t}bi=0}if(!(ks=bi)){Tt.a=3;break e}if(0Tt+1?[]:0),!(is.lengthPe?0:Pe>He?He:Pe}function xc(){this.T=this.U=this.ka=this.height=this.width=0,this.y=[],this.f=[],this.ea=[],this.Rc=this.fa=this.W=this.N=this.O=0,this.ma="void",this.put="VP8IoPutHook",this.ac="VP8IoSetupHook",this.bc="VP8IoTeardownHook",this.ha=this.Kb=0,this.data=[],this.hb=this.ib=this.da=this.o=this.j=this.va=this.v=this.Da=this.ob=this.w=0,this.F=[],this.J=0}function fl(){var Pe=new ao;return Pe!=null&&(Pe.a=0,Pe.sc="OK",Pe.cb=0,Pe.Xb=0,ap||(ap=ad)),Pe}function Co(Pe,He,pt){return Pe.a==0&&(Pe.a=He,Pe.sc=pt,Pe.cb=0),0}function pu(Pe,He,pt){return 3<=pt&&Pe[He+0]==157&&Pe[He+1]==1&&Pe[He+2]==42}function nc(Pe,He){if(Pe==null)return 0;if(Pe.a=0,Pe.sc="OK",He==null)return Co(Pe,2,"null VP8Io passed to VP8GetHeaders()");var pt=He.data,Tt=He.w,is=He.ha;if(4>is)return Co(Pe,7,"Truncated header.");var ks=pt[Tt+0]|pt[Tt+1]<<8|pt[Tt+2]<<16,Es=Pe.Od;if(Es.Rb=!(1&ks),Es.td=ks>>1&7,Es.yd=ks>>4&1,Es.ub=ks>>5,3is)return Co(Pe,7,"cannot parse picture header");if(!pu(pt,Tt,is))return Co(Pe,3,"Bad code word");Ds.c=16383&(pt[Tt+4]<<8|pt[Tt+3]),Ds.Td=pt[Tt+4]>>6,Ds.i=16383&(pt[Tt+6]<<8|pt[Tt+5]),Ds.Ud=pt[Tt+6]>>6,Tt+=7,is-=7,Pe.za=Ds.c+15>>4,Pe.Ub=Ds.i+15>>4,He.width=Ds.c,He.height=Ds.i,He.Da=0,He.j=0,He.v=0,He.va=He.width,He.o=He.height,He.da=0,He.ib=He.width,He.hb=He.height,He.U=He.width,He.T=He.height,a((ks=Pe.Pa).jb,0,255,ks.jb.length),t((ks=Pe.Qa)!=null),ks.Cb=0,ks.Bb=0,ks.Fb=1,a(ks.Zb,0,0,ks.Zb.length),a(ks.Lb,0,0,ks.Lb)}if(Es.ub>is)return Co(Pe,7,"bad partition length");Y(ks=Pe.m,pt,Tt,Es.ub),Tt+=Es.ub,is-=Es.ub,Es.Rb&&(Ds.Ld=Se(ks),Ds.Kd=Se(ks)),Ds=Pe.Qa;var qs,on=Pe.Pa;if(t(ks!=null),t(Ds!=null),Ds.Cb=Se(ks),Ds.Cb){if(Ds.Bb=Se(ks),Se(ks)){for(Ds.Fb=Se(ks),qs=0;4>qs;++qs)Ds.Zb[qs]=Se(ks)?ae(ks,7):0;for(qs=0;4>qs;++qs)Ds.Lb[qs]=Se(ks)?ae(ks,6):0}if(Ds.Bb)for(qs=0;3>qs;++qs)on.jb[qs]=Se(ks)?X(ks,8):255}else Ds.Bb=0;if(ks.Ka)return Co(Pe,3,"cannot parse segment header");if((Ds=Pe.ed).zd=Se(ks),Ds.Tb=X(ks,6),Ds.wb=X(ks,3),Ds.Pc=Se(ks),Ds.Pc&&Se(ks)){for(on=0;4>on;++on)Se(ks)&&(Ds.vd[on]=ae(ks,6));for(on=0;4>on;++on)Se(ks)&&(Ds.od[on]=ae(ks,6))}if(Pe.L=Ds.Tb==0?0:Ds.zd?1:2,ks.Ka)return Co(Pe,3,"cannot parse filter header");var Xn=is;if(is=qs=Tt,Tt=qs+Xn,Ds=Xn,Pe.Xb=(1<Ds&&(Cr=Ds),Y(Pe.Jc[+Xn],pt,qs,Cr),qs+=Cr,Ds-=Cr,is+=3}Y(Pe.Jc[+on],pt,qs,Ds),pt=qsCr;++Cr){if(Xn.Cb){var Js=Xn.Zb[Cr];Xn.Fb||(Js+=pt)}else{if(0>16,8>lr.Eb[1]&&(lr.Eb[1]=8),lr.Qc[0]=B1[ta(Js+on,117)],lr.Qc[1]=ex[ta(Js+qs,127)],lr.lc=Js+qs}if(!Es.Rb)return Co(Pe,4,"Not a key frame.");for(Se(ks),Es=Pe.Pa,pt=0;4>pt;++pt){for(is=0;8>is;++is)for(Tt=0;3>Tt;++Tt)for(Ds=0;11>Ds;++Ds)on=Le(ks,WT[pt][is][Tt][Ds])?X(ks,8):RC[pt][is][Tt][Ds],Es.Wc[pt][is].Yb[Tt][Ds]=on;for(is=0;17>is;++is)Es.Xc[pt][is]=Es.Wc[pt][A3[is]]}return Pe.kc=Se(ks),Pe.kc&&(Pe.Bd=X(ks,8)),Pe.cb=1}function ad(Pe,He,pt,Tt,is,ks,Es){var Ds=He[is].Yb[pt];for(pt=0;16>is;++is){if(!Le(Pe,Ds[pt+0]))return is;for(;!Le(Pe,Ds[pt+1]);)if(Ds=He[++is].Yb[0],pt=0,is==16)return 16;var qs=He[is+1].Yb;if(Le(Pe,Ds[pt+2])){var on=Pe,Xn=0;if(Le(on,(Js=Ds)[(Cr=pt)+3]))if(Le(on,Js[Cr+6])){for(Ds=0,Cr=2*(Xn=Le(on,Js[Cr+8]))+(Js=Le(on,Js[Cr+9+Xn])),Xn=0,Js=Ox[Cr];Js[Ds];++Ds)Xn+=Xn+Le(on,Js[Ds]);Xn+=3+(8<(on=Pe).b&&Ee(on);var Cr,Js=on.b,lr=(Cr=on.Ca>>1)-(on.I>>Js)>>31;--on.b,on.Ca+=lr,on.Ca|=1,on.I-=(Cr+1&lr)<>3),Pe[He+pt+32*Tt]=-256&is?0>is?0:255:is}function Bc(Pe,He,pt,Tt,is,ks){Hi(Pe,He,0,pt,Tt+is),Hi(Pe,He,1,pt,Tt+ks),Hi(Pe,He,2,pt,Tt-ks),Hi(Pe,He,3,pt,Tt-is)}function $c(Pe){return(20091*Pe>>16)+Pe}function yc(Pe,He,pt,Tt){var is,ks=0,Es=i(16);for(is=0;4>is;++is){var Ds=Pe[He+0]+Pe[He+8],qs=Pe[He+0]-Pe[He+8],on=(35468*Pe[He+4]>>16)-$c(Pe[He+12]),Xn=$c(Pe[He+4])+(35468*Pe[He+12]>>16);Es[ks+0]=Ds+Xn,Es[ks+1]=qs+on,Es[ks+2]=qs-on,Es[ks+3]=Ds-Xn,ks+=4,He++}for(is=ks=0;4>is;++is)Ds=(Pe=Es[ks+0]+4)+Es[ks+8],qs=Pe-Es[ks+8],on=(35468*Es[ks+4]>>16)-$c(Es[ks+12]),Hi(pt,Tt,0,0,Ds+(Xn=$c(Es[ks+4])+(35468*Es[ks+12]>>16))),Hi(pt,Tt,1,0,qs+on),Hi(pt,Tt,2,0,qs-on),Hi(pt,Tt,3,0,Ds-Xn),ks++,Tt+=32}function Ul(Pe,He,pt,Tt){var is=Pe[He+0]+4,ks=35468*Pe[He+4]>>16,Es=$c(Pe[He+4]),Ds=35468*Pe[He+1]>>16;Bc(pt,Tt,0,is+Es,Pe=$c(Pe[He+1]),Ds),Bc(pt,Tt,1,is+ks,Pe,Ds),Bc(pt,Tt,2,is-ks,Pe,Ds),Bc(pt,Tt,3,is-Es,Pe,Ds)}function rg(Pe,He,pt,Tt,is){yc(Pe,He,pt,Tt),is&&yc(Pe,He+16,pt,Tt+4)}function Lx(Pe,He,pt,Tt){Xg(Pe,He+0,pt,Tt,1),Xg(Pe,He+32,pt,Tt+128,1)}function Yo(Pe,He,pt,Tt){var is;for(Pe=Pe[He+0]+4,is=0;4>is;++is)for(He=0;4>He;++He)Hi(pt,Tt,He,is,Pe)}function Ic(Pe,He,pt,Tt){Pe[He+0]&&Wu(Pe,He+0,pt,Tt),Pe[He+16]&&Wu(Pe,He+16,pt,Tt+4),Pe[He+32]&&Wu(Pe,He+32,pt,Tt+128),Pe[He+48]&&Wu(Pe,He+48,pt,Tt+128+4)}function Ih(Pe,He,pt,Tt){var is,ks=i(16);for(is=0;4>is;++is){var Es=Pe[He+0+is]+Pe[He+12+is],Ds=Pe[He+4+is]+Pe[He+8+is],qs=Pe[He+4+is]-Pe[He+8+is],on=Pe[He+0+is]-Pe[He+12+is];ks[0+is]=Es+Ds,ks[8+is]=Es-Ds,ks[4+is]=on+qs,ks[12+is]=on-qs}for(is=0;4>is;++is)Es=(Pe=ks[0+4*is]+3)+ks[3+4*is],Ds=ks[1+4*is]+ks[2+4*is],qs=ks[1+4*is]-ks[2+4*is],on=Pe-ks[3+4*is],pt[Tt+0]=Es+Ds>>3,pt[Tt+16]=on+qs>>3,pt[Tt+32]=Es-Ds>>3,pt[Tt+48]=on-qs>>3,Tt+=64}function cm(Pe,He,pt){var Tt,is=He-32,ks=Ui,Es=255-Pe[is-1];for(Tt=0;Ttpt;++pt)r(Pe,He+32*pt,Pe,He-32,16)}function Ba(Pe,He){var pt;for(pt=16;0Tt;++Tt)a(He,pt+32*Tt,Pe,16)}function ko(Pe,He){var pt,Tt=16;for(pt=0;16>pt;++pt)Tt+=Pe[He-1+32*pt]+Pe[He+pt-32];io(Tt>>5,Pe,He)}function qi(Pe,He){var pt,Tt=8;for(pt=0;16>pt;++pt)Tt+=Pe[He-1+32*pt];io(Tt>>4,Pe,He)}function dm(Pe,He){var pt,Tt=8;for(pt=0;16>pt;++pt)Tt+=Pe[He+pt-32];io(Tt>>4,Pe,He)}function Zo(Pe,He){io(128,Pe,He)}function vo(Pe,He,pt){return Pe+2*He+pt+2>>2}function Zg(Pe,He){var pt,Tt=He-32;for(Tt=new Uint8Array([vo(Pe[Tt-1],Pe[Tt+0],Pe[Tt+1]),vo(Pe[Tt+0],Pe[Tt+1],Pe[Tt+2]),vo(Pe[Tt+1],Pe[Tt+2],Pe[Tt+3]),vo(Pe[Tt+2],Pe[Tt+3],Pe[Tt+4])]),pt=0;4>pt;++pt)r(Pe,He+32*pt,Tt,0,Tt.length)}function Ol(Pe,He){var pt=Pe[He-1],Tt=Pe[He-1+32],is=Pe[He-1+64],ks=Pe[He-1+96];Fe(Pe,He+0,16843009*vo(Pe[He-1-32],pt,Tt)),Fe(Pe,He+32,16843009*vo(pt,Tt,is)),Fe(Pe,He+64,16843009*vo(Tt,is,ks)),Fe(Pe,He+96,16843009*vo(is,ks,ks))}function zl(Pe,He){var pt,Tt=4;for(pt=0;4>pt;++pt)Tt+=Pe[He+pt-32]+Pe[He-1+32*pt];for(Tt>>=3,pt=0;4>pt;++pt)a(Pe,He+32*pt,Tt,4)}function vy(Pe,He){var pt=Pe[He-1+0],Tt=Pe[He-1+32],is=Pe[He-1+64],ks=Pe[He-1-32],Es=Pe[He+0-32],Ds=Pe[He+1-32],qs=Pe[He+2-32],on=Pe[He+3-32];Pe[He+0+96]=vo(Tt,is,Pe[He-1+96]),Pe[He+1+96]=Pe[He+0+64]=vo(pt,Tt,is),Pe[He+2+96]=Pe[He+1+64]=Pe[He+0+32]=vo(ks,pt,Tt),Pe[He+3+96]=Pe[He+2+64]=Pe[He+1+32]=Pe[He+0+0]=vo(Es,ks,pt),Pe[He+3+64]=Pe[He+2+32]=Pe[He+1+0]=vo(Ds,Es,ks),Pe[He+3+32]=Pe[He+2+0]=vo(qs,Ds,Es),Pe[He+3+0]=vo(on,qs,Ds)}function Xd(Pe,He){var pt=Pe[He+1-32],Tt=Pe[He+2-32],is=Pe[He+3-32],ks=Pe[He+4-32],Es=Pe[He+5-32],Ds=Pe[He+6-32],qs=Pe[He+7-32];Pe[He+0+0]=vo(Pe[He+0-32],pt,Tt),Pe[He+1+0]=Pe[He+0+32]=vo(pt,Tt,is),Pe[He+2+0]=Pe[He+1+32]=Pe[He+0+64]=vo(Tt,is,ks),Pe[He+3+0]=Pe[He+2+32]=Pe[He+1+64]=Pe[He+0+96]=vo(is,ks,Es),Pe[He+3+32]=Pe[He+2+64]=Pe[He+1+96]=vo(ks,Es,Ds),Pe[He+3+64]=Pe[He+2+96]=vo(Es,Ds,qs),Pe[He+3+96]=vo(Ds,qs,qs)}function Wh(Pe,He){var pt=Pe[He-1+0],Tt=Pe[He-1+32],is=Pe[He-1+64],ks=Pe[He-1-32],Es=Pe[He+0-32],Ds=Pe[He+1-32],qs=Pe[He+2-32],on=Pe[He+3-32];Pe[He+0+0]=Pe[He+1+64]=ks+Es+1>>1,Pe[He+1+0]=Pe[He+2+64]=Es+Ds+1>>1,Pe[He+2+0]=Pe[He+3+64]=Ds+qs+1>>1,Pe[He+3+0]=qs+on+1>>1,Pe[He+0+96]=vo(is,Tt,pt),Pe[He+0+64]=vo(Tt,pt,ks),Pe[He+0+32]=Pe[He+1+96]=vo(pt,ks,Es),Pe[He+1+32]=Pe[He+2+96]=vo(ks,Es,Ds),Pe[He+2+32]=Pe[He+3+96]=vo(Es,Ds,qs),Pe[He+3+32]=vo(Ds,qs,on)}function df(Pe,He){var pt=Pe[He+0-32],Tt=Pe[He+1-32],is=Pe[He+2-32],ks=Pe[He+3-32],Es=Pe[He+4-32],Ds=Pe[He+5-32],qs=Pe[He+6-32],on=Pe[He+7-32];Pe[He+0+0]=pt+Tt+1>>1,Pe[He+1+0]=Pe[He+0+64]=Tt+is+1>>1,Pe[He+2+0]=Pe[He+1+64]=is+ks+1>>1,Pe[He+3+0]=Pe[He+2+64]=ks+Es+1>>1,Pe[He+0+32]=vo(pt,Tt,is),Pe[He+1+32]=Pe[He+0+96]=vo(Tt,is,ks),Pe[He+2+32]=Pe[He+1+96]=vo(is,ks,Es),Pe[He+3+32]=Pe[He+2+96]=vo(ks,Es,Ds),Pe[He+3+64]=vo(Es,Ds,qs),Pe[He+3+96]=vo(Ds,qs,on)}function Yy(Pe,He){var pt=Pe[He-1+0],Tt=Pe[He-1+32],is=Pe[He-1+64],ks=Pe[He-1+96];Pe[He+0+0]=pt+Tt+1>>1,Pe[He+2+0]=Pe[He+0+32]=Tt+is+1>>1,Pe[He+2+32]=Pe[He+0+64]=is+ks+1>>1,Pe[He+1+0]=vo(pt,Tt,is),Pe[He+3+0]=Pe[He+1+32]=vo(Tt,is,ks),Pe[He+3+32]=Pe[He+1+64]=vo(is,ks,ks),Pe[He+3+64]=Pe[He+2+64]=Pe[He+0+96]=Pe[He+1+96]=Pe[He+2+96]=Pe[He+3+96]=ks}function oh(Pe,He){var pt=Pe[He-1+0],Tt=Pe[He-1+32],is=Pe[He-1+64],ks=Pe[He-1+96],Es=Pe[He-1-32],Ds=Pe[He+0-32],qs=Pe[He+1-32],on=Pe[He+2-32];Pe[He+0+0]=Pe[He+2+32]=pt+Es+1>>1,Pe[He+0+32]=Pe[He+2+64]=Tt+pt+1>>1,Pe[He+0+64]=Pe[He+2+96]=is+Tt+1>>1,Pe[He+0+96]=ks+is+1>>1,Pe[He+3+0]=vo(Ds,qs,on),Pe[He+2+0]=vo(Es,Ds,qs),Pe[He+1+0]=Pe[He+3+32]=vo(pt,Es,Ds),Pe[He+1+32]=Pe[He+3+64]=vo(Tt,pt,Es),Pe[He+1+64]=Pe[He+3+96]=vo(is,Tt,pt),Pe[He+1+96]=vo(ks,is,Tt)}function xh(Pe,He){var pt;for(pt=0;8>pt;++pt)r(Pe,He+32*pt,Pe,He-32,8)}function gt(Pe,He){var pt;for(pt=0;8>pt;++pt)a(Pe,He,Pe[He-1],8),He+=32}function We(Pe,He,pt){var Tt;for(Tt=0;8>Tt;++Tt)a(He,pt+32*Tt,Pe,8)}function ut(Pe,He){var pt,Tt=8;for(pt=0;8>pt;++pt)Tt+=Pe[He+pt-32]+Pe[He-1+32*pt];We(Tt>>4,Pe,He)}function jt(Pe,He){var pt,Tt=4;for(pt=0;8>pt;++pt)Tt+=Pe[He+pt-32];We(Tt>>3,Pe,He)}function Rt(Pe,He){var pt,Tt=4;for(pt=0;8>pt;++pt)Tt+=Pe[He-1+32*pt];We(Tt>>3,Pe,He)}function zt(Pe,He){We(128,Pe,He)}function Wt(Pe,He,pt){var Tt=Pe[He-pt],is=Pe[He+0],ks=3*(is-Tt)+Rh[1020+Pe[He-2*pt]-Pe[He+pt]],Es=vh[112+(ks+4>>3)];Pe[He-pt]=Ui[255+Tt+vh[112+(ks+3>>3)]],Pe[He+0]=Ui[255+is-Es]}function ws(Pe,He,pt,Tt){var is=Pe[He+0],ks=Pe[He+pt];return hm[255+Pe[He-2*pt]-Pe[He-pt]]>Tt||hm[255+ks-is]>Tt}function Ms(Pe,He,pt,Tt){return 4*hm[255+Pe[He-pt]-Pe[He+0]]+hm[255+Pe[He-2*pt]-Pe[He+pt]]<=Tt}function Ns(Pe,He,pt,Tt,is){var ks=Pe[He-3*pt],Es=Pe[He-2*pt],Ds=Pe[He-pt],qs=Pe[He+0],on=Pe[He+pt],Xn=Pe[He+2*pt],Cr=Pe[He+3*pt];return 4*hm[255+Ds-qs]+hm[255+Es-on]>Tt?0:hm[255+Pe[He-4*pt]-ks]<=is&&hm[255+ks-Es]<=is&&hm[255+Es-Ds]<=is&&hm[255+Cr-Xn]<=is&&hm[255+Xn-on]<=is&&hm[255+on-qs]<=is}function Ps(Pe,He,pt,Tt){var is=2*Tt+1;for(Tt=0;16>Tt;++Tt)Ms(Pe,He+Tt,pt,is)&&Wt(Pe,He+Tt,pt)}function fn(Pe,He,pt,Tt){var is=2*Tt+1;for(Tt=0;16>Tt;++Tt)Ms(Pe,He+Tt*pt,1,is)&&Wt(Pe,He+Tt*pt,1)}function xn(Pe,He,pt,Tt){var is;for(is=3;0>7,pa=18*dr+63>>7,dr=9*dr+63>>7;qs[on-3*Xn]=Ui[255+qs[on-3*Xn]+dr],qs[on-2*Xn]=Ui[255+Cr+pa],qs[on-Xn]=Ui[255+Js+mr],qs[on+0]=Ui[255+lr-mr],qs[on+Xn]=Ui[255+_r-pa],qs[on+2*Xn]=Ui[255+aa-dr]}He+=Tt}}function or(Pe,He,pt,Tt,is,ks,Es,Ds){for(ks=2*ks+1;0>3)],aa=vh[112+(aa+3>>3)],mr=_r+1>>1;qs[on-2*Xn]=Ui[255+qs[on-2*Xn]+mr],qs[on-Xn]=Ui[255+Cr+aa],qs[on+0]=Ui[255+Js-_r],qs[on+Xn]=Ui[255+lr-mr]}He+=Tt}}function tr(Pe,He,pt,Tt,is,ks){Pn(Pe,He,pt,1,16,Tt,is,ks)}function sr(Pe,He,pt,Tt,is,ks){Pn(Pe,He,1,pt,16,Tt,is,ks)}function br(Pe,He,pt,Tt,is,ks){var Es;for(Es=3;0on?0:255:on)&255,on=qs,is[ks+Ds]=Xn}}function to(Pe,He,pt,Tt){var is=He.width,ks=He.o;if(t(Pe!=null&&He!=null),0>pt||0>=Tt||pt+Tt>ks)return null;if(!Pe.Cc){if(Pe.ga==null){var Es;if(Pe.ga=new na,(Es=Pe.ga==null)||(Es=He.width*He.o,t(Pe.Gb.length==0),Pe.Gb=i(Es),Pe.Uc=0,Pe.Gb==null?Es=0:(Pe.mb=Pe.Gb,Pe.nb=Pe.Uc,Pe.rc=null,Es=1),Es=!Es),!Es){Es=Pe.ga;var Ds=Pe.Fa,qs=Pe.P,on=Pe.qc,Xn=Pe.mb,Cr=Pe.nb,Js=qs+1,lr=on-1,_r=Es.l;if(t(Ds!=null&&Xn!=null&&He!=null),Ob[0]=null,Ob[1]=$a,Ob[2]=Na,Ob[3]=La,Es.ca=Xn,Es.tb=Cr,Es.c=He.width,Es.i=He.height,t(0=on)He=0;else if(Es.$a=3&Ds[qs+0],Es.Z=Ds[qs+0]>>2&3,Es.Lc=Ds[qs+0]>>4&3,qs=Ds[qs+0]>>6&3,0>Es.$a||1=Es.c*Es.i;Es=!He}if(Es)return null;Pe.ga.Lc!=1?Pe.Ga=0:Tt=ks-pt}t(Pe.ga!=null),t(pt+Tt<=ks);e:{if(He=(Ds=Pe.ga).c,ks=Ds.l.o,Ds.$a==0){if(Js=Pe.rc,lr=Pe.Vc,_r=Pe.Fa,qs=Pe.P+1+pt*He,on=Pe.mb,Xn=Pe.nb+pt*He,t(qs<=Pe.P+Pe.qc),Ds.Z!=0)for(t(Ob[Ds.Z]!=null),Es=0;Es=He)He=1;else if(Ds.ic||po(),Ds.ic){Ds=Es.V,Js=Es.Ba,lr=Es.c;var aa=Es.i,mr=(_r=1,qs=Es.$/lr,on=Es.$%lr,Xn=Es.m,Cr=Es.s,Es.$),pa=lr*aa,dr=lr*He,Ua=Cr.wc,Ea=mr(aa=Fn(Ea.G[0],Ea.H[0],Xn)))Ds[Js+mr]=aa,++mr,++on>=lr&&(on=0,++qs<=He&&!(qs%16)&&Sr(Es,qs));else{if(!(280>aa)){_r=0;break t}aa=qn(aa-256,Xn);var _o,Fi=Fn(Ea.G[4],Ea.H[4],Xn);if(ve(Xn),!(mr>=(Fi=hn(lr,Fi=qn(Fi,Xn)))&&pa-mr>=aa)){_r=0;break t}for(_o=0;_o=lr;)on-=lr,++qs<=He&&!(qs%16)&&Sr(Es,qs);mrHe?He:qs);break t}!_r||Xn.h&&mr=ks&&(Pe.Cc=1),Tt=1}if(!Tt)return null;if(Pe.Cc&&((Tt=Pe.ga)!=null&&(Tt.mc=null),Pe.ga=null,0>23,Ds[qs+4*Es+1]=Ds[qs+4*Es+1]*Cr>>23,Ds[qs+4*Es+2]=Ds[qs+4*Es+2]*Cr>>23)}He+=ks}}function oo(Pe,He,pt,Tt,is){for(;0>4)*qs>>16;Pe[He+2*ks+0]=(240&Es|Es>>4)*qs>>16&240|(15&Es|Es<<4)*qs>>16>>4&15,Pe[He+2*ks+1]=240&on|Ds}He+=is}}function Lo(Pe,He,pt,Tt,is,ks,Es,Ds){var qs,on,Xn=255;for(on=0;on>8}function po(){Vd=xo,yu=oo,B_=Lo,Bv=ql}function nl(Pe,He,pt){R[Pe]=function(Tt,is,ks,Es,Ds,qs,on,Xn,Cr,Js,lr,_r,aa,mr,pa,dr,Ua){var Ea,_o=Ua-1>>1,Fi=Ds[qs+0]|on[Xn+0]<<16,bl=Cr[Js+0]|lr[_r+0]<<16;t(Tt!=null);var lo=3*Fi+bl+131074>>2;for(He(Tt[is+0],255&lo,lo>>16,aa,mr),ks!=null&&(lo=3*bl+Fi+131074>>2,He(ks[Es+0],255&lo,lo>>16,pa,dr)),Ea=1;Ea<=_o;++Ea){var Dc=Ds[qs+Ea]|on[Xn+Ea]<<16,mf=Cr[Js+Ea]|lr[_r+Ea]<<16,Zl=Fi+Dc+bl+mf+524296,yo=Zl+2*(Dc+bl)>>3;lo=yo+Fi>>1,Fi=(Zl=Zl+2*(Fi+mf)>>3)+Dc>>1,He(Tt[is+2*Ea-1],255&lo,lo>>16,aa,mr+(2*Ea-1)*pt),He(Tt[is+2*Ea-0],255&Fi,Fi>>16,aa,mr+(2*Ea-0)*pt),ks!=null&&(lo=Zl+bl>>1,Fi=yo+mf>>1,He(ks[Es+2*Ea-1],255&lo,lo>>16,pa,dr+(2*Ea-1)*pt),He(ks[Es+2*Ea+0],255&Fi,Fi>>16,pa,dr+(2*Ea+0)*pt)),Fi=Dc,bl=mf}1&Ua||(lo=3*Fi+bl+131074>>2,He(Tt[is+Ua-1],255&lo,lo>>16,aa,mr+(Ua-1)*pt),ks!=null&&(lo=3*bl+Fi+131074>>2,He(ks[Es+Ua-1],255&lo,lo>>16,pa,dr+(Ua-1)*pt)))}}function Il(){ip[ch]=nj,ip[np]=Fk,ip[Qg]=Fr,ip[dh]=FC,ip[Rc]=tx,ip[Jg]=hf,ip[F1]=$1,ip[O1]=Fk,ip[z1]=FC,ip[tj]=tx,ip[sj]=hf}function Ed(Pe){return Pe&-16384?0>Pe?0:255:Pe>>X2}function iu(Pe,He){return Ed((19077*Pe>>8)+(26149*He>>8)-14234)}function Ut(Pe,He,pt){return Ed((19077*Pe>>8)-(6419*He>>8)-(13320*pt>>8)+8708)}function Cn(Pe,He){return Ed((19077*Pe>>8)+(33050*He>>8)-17685)}function ar(Pe,He,pt,Tt,is){Tt[is+0]=iu(Pe,pt),Tt[is+1]=Ut(Pe,He,pt),Tt[is+2]=Cn(Pe,He)}function ra(Pe,He,pt,Tt,is){Tt[is+0]=Cn(Pe,He),Tt[is+1]=Ut(Pe,He,pt),Tt[is+2]=iu(Pe,pt)}function Zr(Pe,He,pt,Tt,is){var ks=Ut(Pe,He,pt);He=ks<<3&224|Cn(Pe,He)>>3,Tt[is+0]=248&iu(Pe,pt)|ks>>5,Tt[is+1]=He}function Aa(Pe,He,pt,Tt,is){var ks=240&Cn(Pe,He)|15;Tt[is+0]=240&iu(Pe,pt)|Ut(Pe,He,pt)>>4,Tt[is+1]=ks}function xi(Pe,He,pt,Tt,is){Tt[is+0]=255,ar(Pe,He,pt,Tt,is+1)}function Ia(Pe,He,pt,Tt,is){ra(Pe,He,pt,Tt,is),Tt[is+3]=255}function el(Pe,He,pt,Tt,is){ar(Pe,He,pt,Tt,is),Tt[is+3]=255}function zo(Pe,He,pt){R[Pe]=function(Tt,is,ks,Es,Ds,qs,on,Xn,Cr){for(var Js=Xn+(-2&Cr)*pt;Xn!=Js;)He(Tt[is+0],ks[Es+0],Ds[qs+0],on,Xn),He(Tt[is+1],ks[Es+0],Ds[qs+0],on,Xn+pt),is+=2,++Es,++qs,Xn+=2*pt;1&Cr&&He(Tt[is+0],ks[Es+0],Ds[qs+0],on,Xn)}}function Lc(Pe,He,pt){return pt==0?Pe==0?He==0?6:5:He==0?4:0:pt}function Mu(Pe,He,pt,Tt,is){switch(Pe>>>30){case 3:Xg(He,pt,Tt,is,0);break;case 2:zm(He,pt,Tt,is);break;case 1:Wu(He,pt,Tt,is)}}function ou(Pe,He){var pt,Tt,is=He.M,ks=He.Nb,Es=Pe.oc,Ds=Pe.pc+40,qs=Pe.oc,on=Pe.pc+584,Xn=Pe.oc,Cr=Pe.pc+600;for(pt=0;16>pt;++pt)Es[Ds+32*pt-1]=129;for(pt=0;8>pt;++pt)qs[on+32*pt-1]=129,Xn[Cr+32*pt-1]=129;for(0pt;++pt)r(Es,Ds+32*pt-4,Es,Ds+32*pt+12,4);for(pt=-1;8>pt;++pt)r(qs,on+32*pt-4,qs,on+32*pt+4,4),r(Xn,Cr+32*pt-4,Xn,Cr+32*pt+4,4)}var lr=Pe.Gd,_r=Pe.Hd+Tt,aa=Js.ad,mr=Js.Hc;if(0=Pe.za-1?a(pa,dr,lr[_r].y[15],4):r(pa,dr,lr[_r+1].y,0,4)),pt=0;4>pt;pt++)pa[dr+128+pt]=pa[dr+256+pt]=pa[dr+384+pt]=pa[dr+0+pt];for(pt=0;16>pt;++pt,mr<<=2)pa=Es,dr=Ds+V_[pt],Tp[Js.Ob[pt]](pa,dr),Mu(mr,aa,16*+pt,pa,dr)}else if(pa=Lc(Tt,is,Js.Ob[0]),Fb[pa](Es,Ds),mr!=0)for(pt=0;16>pt;++pt,mr<<=2)Mu(mr,aa,16*+pt,Es,Ds+V_[pt]);for(pt=Js.Gc,pa=Lc(Tt,is,Js.Dd),V0[pa](qs,on),V0[pa](Xn,Cr),mr=aa,pa=qs,dr=on,255&(Js=0|pt)&&(170&Js?Dx(mr,256,pa,dr):Sc(mr,256,pa,dr)),Js=Xn,mr=Cr,255&(pt>>=8)&&(170&pt?Dx(aa,320,Js,mr):Sc(aa,320,Js,mr)),ispt;++pt)r(lr,_r+pt*Pe.R,Es,Ds+32*pt,16);for(pt=0;8>pt;++pt)r(aa,Js+pt*Pe.B,qs,on+32*pt,8),r(mr,pa+pt*Pe.B,Xn,Cr+32*pt,8)}}function um(Pe,He,pt,Tt,is,ks,Es,Ds,qs){var on=[0],Xn=[0],Cr=0,Js=qs!=null?qs.kd:0,lr=qs??new tn;if(Pe==null||12>pt)return 7;lr.data=Pe,lr.w=He,lr.ha=pt,He=[He],pt=[pt],lr.gb=[lr.gb];e:{var _r=He,aa=pt,mr=lr.gb;if(t(Pe!=null),t(aa!=null),t(mr!=null),mr[0]=0,12<=aa[0]&&!n(Pe,_r[0],"RIFF")){if(n(Pe,_r[0]+8,"WEBP")){mr=3;break e}var pa=je(Pe,_r[0]+4);if(12>pa||4294967286aa[0]-8){mr=7;break e}mr[0]=pa,_r[0]+=12,aa[0]-=12}mr=0}if(mr!=0)return mr;for(pa=0mr[0])mr=7;else{if(!n(dr,aa[0],"VP8X")){if(je(dr,aa[0]+4)!=10){mr=3;break e}if(18>mr[0]){mr=7;break e}var Fi=je(dr,aa[0]+8),bl=1+Ve(dr,aa[0]+12);if(2147483648<=bl*(dr=1+Ve(dr,aa[0]+15))){mr=3;break e}_o!=null&&(_o[0]=Fi),Ua!=null&&(Ua[0]=bl),Ea!=null&&(Ea[0]=dr),aa[0]+=18,mr[0]-=18,lo[0]=1}mr=0}}if(Cr=Cr[0],_r=_r[0],mr!=0)return mr;if(aa=!!(2&_r),!pa&&Cr)return 3;if(ks!=null&&(ks[0]=!!(16&_r)),Es!=null&&(Es[0]=aa),Ds!=null&&(Ds[0]=0),Es=on[0],_r=Xn[0],Cr&&aa&&qs==null){mr=0;break}if(4>pt){mr=7;break}if(pa&&Cr||!pa&&!Cr&&!n(Pe,He[0],"ALPH")){pt=[pt],lr.na=[lr.na],lr.P=[lr.P],lr.Sa=[lr.Sa];e:{Fi=Pe,mr=He,pa=pt;var lo=lr.gb;Ua=lr.na,Ea=lr.P,_o=lr.Sa,bl=22,t(Fi!=null),t(pa!=null),dr=mr[0];var Dc=pa[0];for(t(Ua!=null),t(_o!=null),Ua[0]=null,Ea[0]=null,_o[0]=0;;){if(mr[0]=dr,pa[0]=Dc,8>Dc){mr=7;break e}var mf=je(Fi,dr+4);if(4294967286lo){mr=3;break e}if(!n(Fi,dr,"VP8 ")||!n(Fi,dr,"VP8L")){mr=0;break e}if(Dc[0]pa[0])mr=7;else{if(dr||bl){if(lo=je(lo,Fi+4),12<=Ua&&lo>Ua-12){mr=3;break e}if(Js&&lo>pa[0]-8){mr=7;break e}Ea[0]=lo,mr[0]+=8,pa[0]-=8,_o[0]=bl}else _o[0]=5<=pa[0]&&lo[Fi+0]==47&&!(lo[Fi+4]>>5),Ea[0]=pa[0];mr=0}if(pt=pt[0],lr.Ja=lr.Ja[0],lr.xa=lr.xa[0],He=He[0],mr!=0)break;if(4294967286pt){mr=7;break}Ds=Es,Js=_r,aa=ks,Pe==null||5>pt?Pe=0:5<=pt&&Pe[He+0]==47&&!(Pe[He+4]>>5)?(pa=[0],lo=[0],Ua=[0],ie(Ea=new ce,Pe,He,pt),Er(Ea,pa,lo,Ua)?(Ds!=null&&(Ds[0]=pa[0]),Js!=null&&(Js[0]=lo[0]),aa!=null&&(aa[0]=Ua[0]),Pe=1):Pe=0):Pe=0}else{if(10>pt){mr=7;break}Ds=_r,Pe==null||10>pt||!pu(Pe,He+3,pt-3)?Pe=0:(Js=Pe[He+0]|Pe[He+1]<<8|Pe[He+2]<<16,aa=16383&(Pe[He+7]<<8|Pe[He+6]),Pe=16383&(Pe[He+9]<<8|Pe[He+8]),1&Js||3<(Js>>1&7)||!(Js>>4&1)||Js>>5>=lr.Ja||!aa||!Pe?Pe=0:(Es&&(Es[0]=aa),Ds&&(Ds[0]=Pe),Pe=1))}if(!Pe||(Es=Es[0],_r=_r[0],Cr&&(on[0]!=Es||Xn[0]!=_r)))return 3;qs!=null&&(qs[0]=lr,qs.offset=He-qs.w,t(4294967286>He-qs.w),t(qs.offset==qs.ha-pt));break}return mr==0||mr==7&&Cr&&qs==null?(ks!=null&&(ks[0]|=lr.na!=null&&0pt||(ks&=-2,Es&=-2),0>ks||0>Es||0>=Ds||0>=qs||ks+Ds>Tt||Es+qs>is))return 0;if(He.v=ks,He.j=Es,He.va=ks+Ds,He.o=Es+qs,He.U=Ds,He.T=qs,He.da=Pe!=null&&0Pe.S){var He=Pe.f.RGBA;He.fb+=(Pe.height-1)*He.A,He.A=-He.A}else He=Pe.f.kb,Pe=Pe.height,He.O+=(Pe-1)*He.fa,He.fa=-He.fa,He.N+=(Pe-1>>1)*He.Ab,He.Ab=-He.Ab,He.W+=(Pe-1>>1)*He.Db,He.Db=-He.Db,He.F!=null&&(He.J+=(Pe-1)*He.lb,He.lb=-He.lb);return 0}function Qc(Pe,He,pt,Tt){if(Tt==null||0>=Pe||0>=He)return 2;if(pt!=null){if(pt.Da){var is=pt.cd,ks=pt.bd,Es=-2&pt.v,Ds=-2&pt.j;if(0>Es||0>Ds||0>=is||0>=ks||Es+is>Pe||Ds+ks>He)return 2;Pe=is,He=ks}if(pt.da){if(!ze(Pe,He,is=[pt.ib],ks=[pt.hb]))return 2;Pe=is[0],He=ks[0]}}Tt.width=Pe,Tt.height=He;e:{var qs=Tt.width,on=Tt.height;if(Pe=Tt.S,0>=qs||0>=on||!(Pe>=ch&&13>Pe))Pe=2;else{if(0>=Tt.Rd&&Tt.sd==null){Es=ks=is=He=0;var Xn=(Ds=qs*aj[Pe])*on;if(11>Pe||(ks=(on+1)/2*(He=(qs+1)/2),Pe==12&&(Es=(is=qs)*on)),(on=i(Xn+2*ks+Es))==null){Pe=1;break e}Tt.sd=on,11>Pe?((qs=Tt.f.RGBA).eb=on,qs.fb=0,qs.A=Ds,qs.size=Xn):((qs=Tt.f.kb).y=on,qs.O=0,qs.fa=Ds,qs.Fd=Xn,qs.f=on,qs.N=0+Xn,qs.Ab=He,qs.Cd=ks,qs.ea=on,qs.W=0+Xn+ks,qs.Db=He,qs.Ed=ks,Pe==12&&(qs.F=on,qs.J=0+Xn+2*ks),qs.Tc=Es,qs.lb=is)}if(He=1,is=Tt.S,ks=Tt.width,Es=Tt.height,is>=ch&&13>is)if(11>is)Pe=Tt.f.RGBA,He&=(Ds=Math.abs(Pe.A))*(Es-1)+ks<=Pe.size,He&=Ds>=ks*aj[is],He&=Pe.eb!=null;else{Pe=Tt.f.kb,Ds=(ks+1)/2,Xn=(Es+1)/2,qs=Math.abs(Pe.fa),on=Math.abs(Pe.Ab);var Cr=Math.abs(Pe.Db),Js=Math.abs(Pe.lb),lr=Js*(Es-1)+ks;He&=qs*(Es-1)+ks<=Pe.Fd,He&=on*(Xn-1)+Ds<=Pe.Cd,He=(He&=Cr*(Xn-1)+Ds<=Pe.Ed)&qs>=ks&on>=Ds&Cr>=Ds,He&=Pe.y!=null,He&=Pe.f!=null,He&=Pe.ea!=null,is==12&&(He&=Js>=ks,He&=lr<=Pe.Tc,He&=Pe.F!=null)}else He=0;Pe=He?0:2}}return Pe!=0||pt!=null&&pt.fd&&(Pe=gu(Tt)),Pe}var id=64,lh=[0,1,3,7,15,31,63,127,255,511,1023,2047,4095,8191,16383,32767,65535,131071,262143,524287,1048575,2097151,4194303,8388607,16777215],If=24,Ud=32,od=8,Lh=[0,0,1,1,2,2,2,2,3,3,3,3,3,3,3,3,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7];Xe("Predictor0","PredictorAdd0"),R.Predictor0=function(){return 4278190080},R.Predictor1=function(Pe){return Pe},R.Predictor2=function(Pe,He,pt){return He[pt+0]},R.Predictor3=function(Pe,He,pt){return He[pt+1]},R.Predictor4=function(Pe,He,pt){return He[pt-1]},R.Predictor5=function(Pe,He,pt){return at(at(Pe,He[pt+1]),He[pt+0])},R.Predictor6=function(Pe,He,pt){return at(Pe,He[pt-1])},R.Predictor7=function(Pe,He,pt){return at(Pe,He[pt+0])},R.Predictor8=function(Pe,He,pt){return at(He[pt-1],He[pt+0])},R.Predictor9=function(Pe,He,pt){return at(He[pt+0],He[pt+1])},R.Predictor10=function(Pe,He,pt){return at(at(Pe,He[pt-1]),at(He[pt+0],He[pt+1]))},R.Predictor11=function(Pe,He,pt){var Tt=He[pt+0];return 0>=xt(Tt>>24&255,Pe>>24&255,(He=He[pt-1])>>24&255)+xt(Tt>>16&255,Pe>>16&255,He>>16&255)+xt(Tt>>8&255,Pe>>8&255,He>>8&255)+xt(255&Tt,255&Pe,255&He)?Tt:Pe},R.Predictor12=function(Pe,He,pt){var Tt=He[pt+0];return(Ke((Pe>>24&255)+(Tt>>24&255)-((He=He[pt-1])>>24&255))<<24|Ke((Pe>>16&255)+(Tt>>16&255)-(He>>16&255))<<16|Ke((Pe>>8&255)+(Tt>>8&255)-(He>>8&255))<<8|Ke((255&Pe)+(255&Tt)-(255&He)))>>>0},R.Predictor13=function(Pe,He,pt){var Tt=He[pt-1];return(nt((Pe=at(Pe,He[pt+0]))>>24&255,Tt>>24&255)<<24|nt(Pe>>16&255,Tt>>16&255)<<16|nt(Pe>>8&255,Tt>>8&255)<<8|nt(255&Pe,255&Tt))>>>0};var Gu=R.PredictorAdd0;R.PredictorAdd1=rt,Xe("Predictor2","PredictorAdd2"),Xe("Predictor3","PredictorAdd3"),Xe("Predictor4","PredictorAdd4"),Xe("Predictor5","PredictorAdd5"),Xe("Predictor6","PredictorAdd6"),Xe("Predictor7","PredictorAdd7"),Xe("Predictor8","PredictorAdd8"),Xe("Predictor9","PredictorAdd9"),Xe("Predictor10","PredictorAdd10"),Xe("Predictor11","PredictorAdd11"),Xe("Predictor12","PredictorAdd12"),Xe("Predictor13","PredictorAdd13");var qd=R.PredictorAdd2;ys("ColorIndexInverseTransform","MapARGB","32b",function(Pe){return Pe>>8&255},function(Pe){return Pe}),ys("VP8LColorIndexInverseTransformAlpha","MapAlpha","8b",function(Pe){return Pe},function(Pe){return Pe>>8&255});var hd,Bl=R.ColorIndexInverseTransform,Xi=R.MapARGB,Md=R.VP8LColorIndexInverseTransformAlpha,lu=R.MapAlpha,Jc=R.VP8LPredictorsAdd=[];Jc.length=16,(R.VP8LPredictors=[]).length=16,(R.VP8LPredictorsAdd_C=[]).length=16,(R.VP8LPredictors_C=[]).length=16;var _d,Ep,zv,Rx,ya,Zy,Ci,Xg,zm,Dx,Wu,Sc,Ro,kl,xu,fa,Ao,pl,ed,ag,Wo,q0,yh,uf,Vd,yu,B_,Bv,Fx=i(511),Rb=i(2041),ej=i(225),Bm=i(767),vu=0,Rh=Rb,vh=ej,Ui=Bm,hm=Fx,ch=0,np=1,Qg=2,dh=3,Rc=4,Jg=5,F1=6,O1=7,z1=8,tj=9,sj=10,$_=[2,3,7],Rk=[3,3,11],Db=[280,256,256,256,40],$v=[0,1,1,1,0],C3=[17,18,0,1,2,3,4,5,16,6,7,8,9,10,11,12,13,14,15],Z2=[24,7,23,25,40,6,39,41,22,26,38,42,56,5,55,57,21,27,54,58,37,43,72,4,71,73,20,28,53,59,70,74,36,44,88,69,75,52,60,3,87,89,19,29,86,90,35,45,68,76,85,91,51,61,104,2,103,105,18,30,102,106,34,46,84,92,67,77,101,107,50,62,120,1,119,121,83,93,17,31,100,108,66,78,118,122,33,47,117,123,49,63,99,109,82,94,0,116,124,65,79,16,32,98,110,48,115,125,81,95,64,114,126,97,111,80,113,127,96,112],rp=[2954,2956,2958,2962,2970,2986,3018,3082,3212,3468,3980,5004],Dk=8,B1=[4,5,6,7,8,9,10,10,11,12,13,14,15,16,17,17,18,19,20,20,21,21,22,22,23,23,24,25,25,26,27,28,29,30,31,32,33,34,35,36,37,37,38,39,40,41,42,43,44,45,46,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,76,77,78,79,80,81,82,83,84,85,86,87,88,89,91,93,95,96,98,100,101,102,104,106,108,110,112,114,116,118,122,124,126,128,130,132,134,136,138,140,143,145,148,151,154,157],ex=[4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,60,62,64,66,68,70,72,74,76,78,80,82,84,86,88,90,92,94,96,98,100,102,104,106,108,110,112,114,116,119,122,125,128,131,134,137,140,143,146,149,152,155,158,161,164,167,170,173,177,181,185,189,193,197,201,205,209,213,217,221,225,229,234,239,245,249,254,259,264,269,274,279,284],ap=null,Ox=[[173,148,140,0],[176,155,140,135,0],[180,157,141,134,130,0],[254,254,243,230,196,177,153,140,133,130,129,0]],Hd=[0,1,4,8,5,2,3,6,9,12,13,10,7,11,14,15],Uv=[-0,1,-1,2,-2,3,4,6,-3,5,-4,-5,-6,7,-7,8,-8,-9],RC=[[[[128,128,128,128,128,128,128,128,128,128,128],[128,128,128,128,128,128,128,128,128,128,128],[128,128,128,128,128,128,128,128,128,128,128]],[[253,136,254,255,228,219,128,128,128,128,128],[189,129,242,255,227,213,255,219,128,128,128],[106,126,227,252,214,209,255,255,128,128,128]],[[1,98,248,255,236,226,255,255,128,128,128],[181,133,238,254,221,234,255,154,128,128,128],[78,134,202,247,198,180,255,219,128,128,128]],[[1,185,249,255,243,255,128,128,128,128,128],[184,150,247,255,236,224,128,128,128,128,128],[77,110,216,255,236,230,128,128,128,128,128]],[[1,101,251,255,241,255,128,128,128,128,128],[170,139,241,252,236,209,255,255,128,128,128],[37,116,196,243,228,255,255,255,128,128,128]],[[1,204,254,255,245,255,128,128,128,128,128],[207,160,250,255,238,128,128,128,128,128,128],[102,103,231,255,211,171,128,128,128,128,128]],[[1,152,252,255,240,255,128,128,128,128,128],[177,135,243,255,234,225,128,128,128,128,128],[80,129,211,255,194,224,128,128,128,128,128]],[[1,1,255,128,128,128,128,128,128,128,128],[246,1,255,128,128,128,128,128,128,128,128],[255,128,128,128,128,128,128,128,128,128,128]]],[[[198,35,237,223,193,187,162,160,145,155,62],[131,45,198,221,172,176,220,157,252,221,1],[68,47,146,208,149,167,221,162,255,223,128]],[[1,149,241,255,221,224,255,255,128,128,128],[184,141,234,253,222,220,255,199,128,128,128],[81,99,181,242,176,190,249,202,255,255,128]],[[1,129,232,253,214,197,242,196,255,255,128],[99,121,210,250,201,198,255,202,128,128,128],[23,91,163,242,170,187,247,210,255,255,128]],[[1,200,246,255,234,255,128,128,128,128,128],[109,178,241,255,231,245,255,255,128,128,128],[44,130,201,253,205,192,255,255,128,128,128]],[[1,132,239,251,219,209,255,165,128,128,128],[94,136,225,251,218,190,255,255,128,128,128],[22,100,174,245,186,161,255,199,128,128,128]],[[1,182,249,255,232,235,128,128,128,128,128],[124,143,241,255,227,234,128,128,128,128,128],[35,77,181,251,193,211,255,205,128,128,128]],[[1,157,247,255,236,231,255,255,128,128,128],[121,141,235,255,225,227,255,255,128,128,128],[45,99,188,251,195,217,255,224,128,128,128]],[[1,1,251,255,213,255,128,128,128,128,128],[203,1,248,255,255,128,128,128,128,128,128],[137,1,177,255,224,255,128,128,128,128,128]]],[[[253,9,248,251,207,208,255,192,128,128,128],[175,13,224,243,193,185,249,198,255,255,128],[73,17,171,221,161,179,236,167,255,234,128]],[[1,95,247,253,212,183,255,255,128,128,128],[239,90,244,250,211,209,255,255,128,128,128],[155,77,195,248,188,195,255,255,128,128,128]],[[1,24,239,251,218,219,255,205,128,128,128],[201,51,219,255,196,186,128,128,128,128,128],[69,46,190,239,201,218,255,228,128,128,128]],[[1,191,251,255,255,128,128,128,128,128,128],[223,165,249,255,213,255,128,128,128,128,128],[141,124,248,255,255,128,128,128,128,128,128]],[[1,16,248,255,255,128,128,128,128,128,128],[190,36,230,255,236,255,128,128,128,128,128],[149,1,255,128,128,128,128,128,128,128,128]],[[1,226,255,128,128,128,128,128,128,128,128],[247,192,255,128,128,128,128,128,128,128,128],[240,128,255,128,128,128,128,128,128,128,128]],[[1,134,252,255,255,128,128,128,128,128,128],[213,62,250,255,255,128,128,128,128,128,128],[55,93,255,128,128,128,128,128,128,128,128]],[[128,128,128,128,128,128,128,128,128,128,128],[128,128,128,128,128,128,128,128,128,128,128],[128,128,128,128,128,128,128,128,128,128,128]]],[[[202,24,213,235,186,191,220,160,240,175,255],[126,38,182,232,169,184,228,174,255,187,128],[61,46,138,219,151,178,240,170,255,216,128]],[[1,112,230,250,199,191,247,159,255,255,128],[166,109,228,252,211,215,255,174,128,128,128],[39,77,162,232,172,180,245,178,255,255,128]],[[1,52,220,246,198,199,249,220,255,255,128],[124,74,191,243,183,193,250,221,255,255,128],[24,71,130,219,154,170,243,182,255,255,128]],[[1,182,225,249,219,240,255,224,128,128,128],[149,150,226,252,216,205,255,171,128,128,128],[28,108,170,242,183,194,254,223,255,255,128]],[[1,81,230,252,204,203,255,192,128,128,128],[123,102,209,247,188,196,255,233,128,128,128],[20,95,153,243,164,173,255,203,128,128,128]],[[1,222,248,255,216,213,128,128,128,128,128],[168,175,246,252,235,205,255,255,128,128,128],[47,116,215,255,211,212,255,255,128,128,128]],[[1,121,236,253,212,214,255,255,128,128,128],[141,84,213,252,201,202,255,219,128,128,128],[42,80,160,240,162,185,255,205,128,128,128]],[[1,1,255,128,128,128,128,128,128,128,128],[244,1,255,128,128,128,128,128,128,128,128],[238,1,255,128,128,128,128,128,128,128,128]]]],GT=[[[231,120,48,89,115,113,120,152,112],[152,179,64,126,170,118,46,70,95],[175,69,143,80,85,82,72,155,103],[56,58,10,171,218,189,17,13,152],[114,26,17,163,44,195,21,10,173],[121,24,80,195,26,62,44,64,85],[144,71,10,38,171,213,144,34,26],[170,46,55,19,136,160,33,206,71],[63,20,8,114,114,208,12,9,226],[81,40,11,96,182,84,29,16,36]],[[134,183,89,137,98,101,106,165,148],[72,187,100,130,157,111,32,75,80],[66,102,167,99,74,62,40,234,128],[41,53,9,178,241,141,26,8,107],[74,43,26,146,73,166,49,23,157],[65,38,105,160,51,52,31,115,128],[104,79,12,27,217,255,87,17,7],[87,68,71,44,114,51,15,186,23],[47,41,14,110,182,183,21,17,194],[66,45,25,102,197,189,23,18,22]],[[88,88,147,150,42,46,45,196,205],[43,97,183,117,85,38,35,179,61],[39,53,200,87,26,21,43,232,171],[56,34,51,104,114,102,29,93,77],[39,28,85,171,58,165,90,98,64],[34,22,116,206,23,34,43,166,73],[107,54,32,26,51,1,81,43,31],[68,25,106,22,64,171,36,225,114],[34,19,21,102,132,188,16,76,124],[62,18,78,95,85,57,50,48,51]],[[193,101,35,159,215,111,89,46,111],[60,148,31,172,219,228,21,18,111],[112,113,77,85,179,255,38,120,114],[40,42,1,196,245,209,10,25,109],[88,43,29,140,166,213,37,43,154],[61,63,30,155,67,45,68,1,209],[100,80,8,43,154,1,51,26,71],[142,78,78,16,255,128,34,197,171],[41,40,5,102,211,183,4,1,221],[51,50,17,168,209,192,23,25,82]],[[138,31,36,171,27,166,38,44,229],[67,87,58,169,82,115,26,59,179],[63,59,90,180,59,166,93,73,154],[40,40,21,116,143,209,34,39,175],[47,15,16,183,34,223,49,45,183],[46,17,33,183,6,98,15,32,183],[57,46,22,24,128,1,54,17,37],[65,32,73,115,28,128,23,128,205],[40,3,9,115,51,192,18,6,223],[87,37,9,115,59,77,64,21,47]],[[104,55,44,218,9,54,53,130,226],[64,90,70,205,40,41,23,26,57],[54,57,112,184,5,41,38,166,213],[30,34,26,133,152,116,10,32,134],[39,19,53,221,26,114,32,73,255],[31,9,65,234,2,15,1,118,73],[75,32,12,51,192,255,160,43,51],[88,31,35,67,102,85,55,186,85],[56,21,23,111,59,205,45,37,192],[55,38,70,124,73,102,1,34,98]],[[125,98,42,88,104,85,117,175,82],[95,84,53,89,128,100,113,101,45],[75,79,123,47,51,128,81,171,1],[57,17,5,71,102,57,53,41,49],[38,33,13,121,57,73,26,1,85],[41,10,67,138,77,110,90,47,114],[115,21,2,10,102,255,166,23,6],[101,29,16,10,85,128,101,196,26],[57,18,10,102,102,213,34,20,43],[117,20,15,36,163,128,68,1,26]],[[102,61,71,37,34,53,31,243,192],[69,60,71,38,73,119,28,222,37],[68,45,128,34,1,47,11,245,171],[62,17,19,70,146,85,55,62,70],[37,43,37,154,100,163,85,160,1],[63,9,92,136,28,64,32,201,85],[75,15,9,9,64,255,184,119,16],[86,6,28,5,64,255,25,248,1],[56,8,17,132,137,255,55,116,128],[58,15,20,82,135,57,26,121,40]],[[164,50,31,137,154,133,25,35,218],[51,103,44,131,131,123,31,6,158],[86,40,64,135,148,224,45,183,128],[22,26,17,131,240,154,14,1,209],[45,16,21,91,64,222,7,1,197],[56,21,39,155,60,138,23,102,213],[83,12,13,54,192,255,68,47,28],[85,26,85,85,128,128,32,146,171],[18,11,7,63,144,171,4,4,246],[35,27,10,146,174,171,12,26,128]],[[190,80,35,99,180,80,126,54,45],[85,126,47,87,176,51,41,20,32],[101,75,128,139,118,146,116,128,85],[56,41,15,176,236,85,37,9,62],[71,30,17,119,118,255,17,18,138],[101,38,60,138,55,70,43,26,142],[146,36,19,30,171,255,97,27,20],[138,45,61,62,219,1,81,188,64],[32,41,20,117,151,142,20,21,163],[112,19,12,61,195,128,48,4,24]]],WT=[[[[255,255,255,255,255,255,255,255,255,255,255],[255,255,255,255,255,255,255,255,255,255,255],[255,255,255,255,255,255,255,255,255,255,255]],[[176,246,255,255,255,255,255,255,255,255,255],[223,241,252,255,255,255,255,255,255,255,255],[249,253,253,255,255,255,255,255,255,255,255]],[[255,244,252,255,255,255,255,255,255,255,255],[234,254,254,255,255,255,255,255,255,255,255],[253,255,255,255,255,255,255,255,255,255,255]],[[255,246,254,255,255,255,255,255,255,255,255],[239,253,254,255,255,255,255,255,255,255,255],[254,255,254,255,255,255,255,255,255,255,255]],[[255,248,254,255,255,255,255,255,255,255,255],[251,255,254,255,255,255,255,255,255,255,255],[255,255,255,255,255,255,255,255,255,255,255]],[[255,253,254,255,255,255,255,255,255,255,255],[251,254,254,255,255,255,255,255,255,255,255],[254,255,254,255,255,255,255,255,255,255,255]],[[255,254,253,255,254,255,255,255,255,255,255],[250,255,254,255,254,255,255,255,255,255,255],[254,255,255,255,255,255,255,255,255,255,255]],[[255,255,255,255,255,255,255,255,255,255,255],[255,255,255,255,255,255,255,255,255,255,255],[255,255,255,255,255,255,255,255,255,255,255]]],[[[217,255,255,255,255,255,255,255,255,255,255],[225,252,241,253,255,255,254,255,255,255,255],[234,250,241,250,253,255,253,254,255,255,255]],[[255,254,255,255,255,255,255,255,255,255,255],[223,254,254,255,255,255,255,255,255,255,255],[238,253,254,254,255,255,255,255,255,255,255]],[[255,248,254,255,255,255,255,255,255,255,255],[249,254,255,255,255,255,255,255,255,255,255],[255,255,255,255,255,255,255,255,255,255,255]],[[255,253,255,255,255,255,255,255,255,255,255],[247,254,255,255,255,255,255,255,255,255,255],[255,255,255,255,255,255,255,255,255,255,255]],[[255,253,254,255,255,255,255,255,255,255,255],[252,255,255,255,255,255,255,255,255,255,255],[255,255,255,255,255,255,255,255,255,255,255]],[[255,254,254,255,255,255,255,255,255,255,255],[253,255,255,255,255,255,255,255,255,255,255],[255,255,255,255,255,255,255,255,255,255,255]],[[255,254,253,255,255,255,255,255,255,255,255],[250,255,255,255,255,255,255,255,255,255,255],[254,255,255,255,255,255,255,255,255,255,255]],[[255,255,255,255,255,255,255,255,255,255,255],[255,255,255,255,255,255,255,255,255,255,255],[255,255,255,255,255,255,255,255,255,255,255]]],[[[186,251,250,255,255,255,255,255,255,255,255],[234,251,244,254,255,255,255,255,255,255,255],[251,251,243,253,254,255,254,255,255,255,255]],[[255,253,254,255,255,255,255,255,255,255,255],[236,253,254,255,255,255,255,255,255,255,255],[251,253,253,254,254,255,255,255,255,255,255]],[[255,254,254,255,255,255,255,255,255,255,255],[254,254,254,255,255,255,255,255,255,255,255],[255,255,255,255,255,255,255,255,255,255,255]],[[255,254,255,255,255,255,255,255,255,255,255],[254,254,255,255,255,255,255,255,255,255,255],[254,255,255,255,255,255,255,255,255,255,255]],[[255,255,255,255,255,255,255,255,255,255,255],[254,255,255,255,255,255,255,255,255,255,255],[255,255,255,255,255,255,255,255,255,255,255]],[[255,255,255,255,255,255,255,255,255,255,255],[255,255,255,255,255,255,255,255,255,255,255],[255,255,255,255,255,255,255,255,255,255,255]],[[255,255,255,255,255,255,255,255,255,255,255],[255,255,255,255,255,255,255,255,255,255,255],[255,255,255,255,255,255,255,255,255,255,255]],[[255,255,255,255,255,255,255,255,255,255,255],[255,255,255,255,255,255,255,255,255,255,255],[255,255,255,255,255,255,255,255,255,255,255]]],[[[248,255,255,255,255,255,255,255,255,255,255],[250,254,252,254,255,255,255,255,255,255,255],[248,254,249,253,255,255,255,255,255,255,255]],[[255,253,253,255,255,255,255,255,255,255,255],[246,253,253,255,255,255,255,255,255,255,255],[252,254,251,254,254,255,255,255,255,255,255]],[[255,254,252,255,255,255,255,255,255,255,255],[248,254,253,255,255,255,255,255,255,255,255],[253,255,254,254,255,255,255,255,255,255,255]],[[255,251,254,255,255,255,255,255,255,255,255],[245,251,254,255,255,255,255,255,255,255,255],[253,253,254,255,255,255,255,255,255,255,255]],[[255,251,253,255,255,255,255,255,255,255,255],[252,253,254,255,255,255,255,255,255,255,255],[255,254,255,255,255,255,255,255,255,255,255]],[[255,252,255,255,255,255,255,255,255,255,255],[249,255,254,255,255,255,255,255,255,255,255],[255,255,254,255,255,255,255,255,255,255,255]],[[255,255,253,255,255,255,255,255,255,255,255],[250,255,255,255,255,255,255,255,255,255,255],[255,255,255,255,255,255,255,255,255,255,255]],[[255,255,255,255,255,255,255,255,255,255,255],[254,255,255,255,255,255,255,255,255,255,255],[255,255,255,255,255,255,255,255,255,255,255]]]],A3=[0,1,2,3,6,4,5,6,6,6,6,6,6,6,6,7,0],Fb=[],Tp=[],V0=[],DC=1,E3=2,Ob=[],ip=[];nl("UpsampleRgbLinePair",ar,3),nl("UpsampleBgrLinePair",ra,3),nl("UpsampleRgbaLinePair",el,4),nl("UpsampleBgraLinePair",Ia,4),nl("UpsampleArgbLinePair",xi,4),nl("UpsampleRgba4444LinePair",Aa,2),nl("UpsampleRgb565LinePair",Zr,2);var nj=R.UpsampleRgbLinePair,Fr=R.UpsampleBgrLinePair,Fk=R.UpsampleRgbaLinePair,FC=R.UpsampleBgraLinePair,tx=R.UpsampleArgbLinePair,hf=R.UpsampleRgba4444LinePair,$1=R.UpsampleRgb565LinePair,H0=16,G0=1<Tt.ca.S||(alert("todo:WebPInitConvertARGBToYUV"),Tt.ca.f.kb.F!=null&&po()),Tt.Pb&&0(qs=pt.Md)?0:100on;++on)12>(Cr=is.pb[on]).lc&&(Cr.ia=qs*zC[0>Cr.lc?0:Cr.lc]>>3),Xn|=Cr.ia;Xn&&(alert("todo:VP8InitRandom"),is.ia=1)}is.Ga=pt.Id,100is.Ga&&(is.Ga=0)}(function(Js,lr){if(Js==null)return 0;if(lr==null)return Co(Js,2,"NULL VP8Io parameter in VP8Decode().");if(!Js.cb&&!nc(Js,lr))return 0;if(t(Js.cb),lr.ac==null||lr.ac(lr)){lr.ob&&(Js.L=0);var _r=sx[Js.L];if(Js.L==2?(Js.yb=0,Js.zb=0):(Js.yb=lr.v-_r>>4,Js.zb=lr.j-_r>>4,0>Js.yb&&(Js.yb=0),0>Js.zb&&(Js.zb=0)),Js.Va=lr.o+15+_r>>4,Js.Hb=lr.va+15+_r>>4,Js.Hb>Js.za&&(Js.Hb=Js.za),Js.Va>Js.Ub&&(Js.Va=Js.Ub),0_r;++_r){var mr;if(Js.Qa.Cb){var pa=Js.Qa.Lb[_r];Js.Qa.Fb||(pa+=aa.Tb)}else pa=aa.Tb;for(mr=0;1>=mr;++mr){var dr=Js.gd[_r][mr],Ua=pa;if(aa.Pc&&(Ua+=aa.vd[0],mr&&(Ua+=aa.od[0])),0<(Ua=0>Ua?0:63>2:Ea>>1)>9-aa.wb&&(Ea=9-aa.wb),1>Ea&&(Ea=1),dr.dd=Ea,dr.tc=2*Ua+Ea,dr.ld=40<=Ua?2:15<=Ua?1:0}else dr.tc=0;dr.La=mr}}}_r=0}else Co(Js,6,"Frame setup failed"),_r=Js.a;if(_r=_r==0){if(_r){Js.$c=0,0Js.Vb){if(Js.Vb=0,Js.Ec=i(dr),Js.Fc=0,Js.Ec==null){_r=Co(Js,1,"no memory during frame initialization.");break t}Js.Vb=dr}dr=Js.Ec,Ua=Js.Fc,Js.Ac=dr,Js.Bc=Ua,Ua+=aa,Js.Gd=l(_o,ih),Js.Hd=0,Js.rb=l(Fi+1,ti),Js.sb=1,Js.wa=bl?l(bl,Ho):null,Js.Y=0,Js.D.Nb=0,Js.D.wa=Js.wa,Js.D.Y=Js.Y,0=_r;++_r)Fx[255+_r]=0>_r?-_r:_r;for(_r=-1020;1020>=_r;++_r)Rb[1020+_r]=-128>_r?-128:127<_r?127:_r;for(_r=-112;112>=_r;++_r)ej[112+_r]=-16>_r?-16:15<_r?15:_r;for(_r=-255;510>=_r;++_r)Bm[255+_r]=0>_r?0:255<_r?255:_r;vu=1}Ci=Ih,Xg=rg,Dx=Lx,Wu=Yo,Sc=Ic,zm=Ul,Ro=tr,kl=sr,xu=Va,fa=Je,Ao=br,pl=vr,ed=Ht,ag=Ts,Wo=Ps,q0=fn,yh=xn,uf=bn,Tp[0]=zl,Tp[1]=Xc,Tp[2]=Zg,Tp[3]=Ol,Tp[4]=vy,Tp[5]=Wh,Tp[6]=Xd,Tp[7]=df,Tp[8]=oh,Tp[9]=Yy,Fb[0]=ko,Fb[1]=Xa,Fb[2]=No,Fb[3]=Ba,Fb[4]=qi,Fb[5]=dm,Fb[6]=Zo,V0[0]=ut,V0[1]=_s,V0[2]=xh,V0[3]=gt,V0[4]=Rt,V0[5]=jt,V0[6]=zt,_r=1}else _r=0}_r&&(_r=function(Dc,mf){for(Dc.M=0;Dc.MXl;++Xl){var ff,md=ig[0+Xl];for(ff=0;4>ff;++ff){md=GT[Uc[Lf+ff]][md];for(var cu=Uv[Le(To,md[0])];0>3;for(cu=0;256>cu;cu+=16)Xl[og+cu]=bh}Rf=1,op=Lf[0]}var vc=15&To.la,Fh=15&Dh.la;for(cu=0;4>cu;++cu){var $m=1&Fh;for(bh=du=0;4>bh;++bh)vc=vc>>1|($m=(hh=ap(Uc,op,hh=$m+(1&vc),Qd.Sc,Rf,Xl,og))>Rf)<<7,du=du<<2|(3>=4,Fh=Fh>>1|$m<<7,ff=(ff<<8|du)>>>0}for(op=vc,Rf=Fh>>4,uh=0;4>uh;uh+=2){for(du=0,vc=To.la>>4+uh,Fh=Dh.la>>4+uh,cu=0;2>cu;++cu){for($m=1&Fh,bh=0;2>bh;++bh)hh=$m+(1&vc),vc=vc>>1|($m=0<(hh=ap(Uc,Lf[2],hh,Qd.Qc,0,Xl,og)))<<3,du=du<<2|(3>=2,Fh=Fh>>1|$m<<5}md|=du<<4*uh,op|=vc<<4<=yo.zb&&yo.M<=yo.Va,yo.Aa==0)t:{if(Zl.M=yo.M,Zl.uc=To,ou(yo,Zl),mm=1,Zl=(du=yo.D).Nb,To=(md=sx[yo.L])*yo.R,Uc=md/2*yo.B,cu=16*Zl*yo.R,bh=8*Zl*yo.B,Lf=yo.sa,ig=yo.ta-To+cu,Qd=yo.qa,Xl=yo.ra-Uc+bh,og=yo.Ha,Dh=yo.Ia-Uc+bh,Fh=(vc=du.M)==0,ff=vc>=yo.Va-1,yo.Aa==2&&ou(yo,du),du.uc)for($m=(hh=yo).D.M,t(hh.D.uc),du=hh.yb;dubi.o&&(vc=bi.o),bi.F=null,bi.J=null,yo.Fa!=null&&0>1),bi.W+=yo.B*(md>>1),bi.F!=null&&(bi.J+=bi.width*md)),du>1,bi.W+=bi.v>>1,bi.F!=null&&(bi.J+=bi.v),bi.ka=du-bi.j,bi.U=bi.va-bi.v,bi.T=vc-du,mm=bi.put(bi))}Zl+1!=yo.Ic||ff||(r(yo.sa,yo.ta-To,Lf,ig+16*yo.R,To),r(yo.qa,yo.ra-Uc,Qd,Xl+8*yo.B,Uc),r(yo.Ha,yo.Ia-Uc,og,Dh+8*yo.B,Uc))}if(!mm)return Co(Dc,6,"Output aborted.")}return 1}(Js,lr)),lr.bc!=null&&lr.bc(lr),_r&=1}return _r?(Js.cb=0,_r):0})(Pe,Tt)||(He=Pe.a)}}else He=Pe.a}He==0&&Es.Oa!=null&&Es.Oa.fd&&(He=gu(Es.ba))}Es=He}ks=Es!=0?null:11>ks?Ds.f.RGBA.eb:Ds.f.kb.y}else ks=null;return ks};var aj=[3,4,3,4,4,2,2,4,4,4,2,1,1]};function d(R,D){for(var O="",U=0;U<4;U++)O+=String.fromCharCode(R[D++]);return O}function u(R,D){return R[D+0]|R[D+1]<<8}function h(R,D){return(R[D+0]|R[D+1]<<8|R[D+2]<<16)>>>0}function m(R,D){return(R[D+0]|R[D+1]<<8|R[D+2]<<16|R[D+3]<<24)>>>0}new c;var f=[0],g=[0],x=[],y=new c,v=s,b=function(R,D){var O={},U=0,W=!1,V=0,G=0;if(O.frames=[],!function(J,ce){for(var _e=0;_e<4;_e++)if(J[ce+_e]!="RIFF".charCodeAt(_e))return!0;return!1}(R,D)){for(m(R,D+=4),D+=8;D>1&1}Y!="ANMF"&&(D+=ae)}return O}}(v,0);b.response=v,b.rgbaoutput=!0,b.dataurl=!1;var w=b.header?b.header:null,S=b.frames?b.frames:null;if(w){w.loop_counter=w.loop_count,f=[w.canvas_height],g=[w.canvas_width];for(var C=0;C'+n.replace(/&/g,"&").replace(//g,">").replace(/"/g,""").replace(/'/g,"'")+"",this.internal.__metadata__.metadataObjectNumber=this.internal.newObject(),this.internal.write("<< /Type /Metadata /Subtype /XML /Length "+s.length+" >>"),this.internal.write("stream"),this.internal.write(s),this.internal.write("endstream"),this.internal.write("endobj")}function YWn(){this.internal.__metadata__.metadataObjectNumber&&this.internal.write("/Metadata "+this.internal.__metadata__.metadataObjectNumber+" 0 R")}(function(s){var t,n,r,a,i,l,o,c,d,u=function(J){return J=J||{},this.isStrokeTransparent=J.isStrokeTransparent||!1,this.strokeOpacity=J.strokeOpacity||1,this.strokeStyle=J.strokeStyle||"#000000",this.fillStyle=J.fillStyle||"#000000",this.isFillTransparent=J.isFillTransparent||!1,this.fillOpacity=J.fillOpacity||1,this.font=J.font||"10px sans-serif",this.textBaseline=J.textBaseline||"alphabetic",this.textAlign=J.textAlign||"left",this.lineWidth=J.lineWidth||1,this.lineJoin=J.lineJoin||"miter",this.lineCap=J.lineCap||"butt",this.path=J.path||[],this.transform=J.transform!==void 0?J.transform.clone():new c,this.globalCompositeOperation=J.globalCompositeOperation||"normal",this.globalAlpha=J.globalAlpha||1,this.clip_path=J.clip_path||[],this.currentPoint=J.currentPoint||new l,this.miterLimit=J.miterLimit||10,this.lastPoint=J.lastPoint||new l,this.lineDashOffset=J.lineDashOffset||0,this.lineDash=J.lineDash||[],this.margin=J.margin||[0,0,0,0],this.prevPageLastElemOffset=J.prevPageLastElemOffset||0,this.ignoreClearRect=typeof J.ignoreClearRect!="boolean"||J.ignoreClearRect,this};s.events.push(["initialized",function(){this.context2d=new h(this),t=this.internal.f2,n=this.internal.getCoordinateString,r=this.internal.getVerticalCoordinateString,a=this.internal.getHorizontalCoordinate,i=this.internal.getVerticalCoordinate,l=this.internal.Point,o=this.internal.Rectangle,c=this.internal.Matrix,d=new u}]);var h=function(J){Object.defineProperty(this,"canvas",{get:function(){return{parentNode:!1,style:!1}}});var ce=J;Object.defineProperty(this,"pdf",{get:function(){return ce}});var _e=!1;Object.defineProperty(this,"pageWrapXEnabled",{get:function(){return _e},set:function(Ae){_e=!!Ae}});var he=!1;Object.defineProperty(this,"pageWrapYEnabled",{get:function(){return he},set:function(Ae){he=!!Ae}});var ue=0;Object.defineProperty(this,"posX",{get:function(){return ue},set:function(Ae){isNaN(Ae)||(ue=Ae)}});var ve=0;Object.defineProperty(this,"posY",{get:function(){return ve},set:function(Ae){isNaN(Ae)||(ve=Ae)}}),Object.defineProperty(this,"margin",{get:function(){return d.margin},set:function(Ae){var Ce;typeof Ae=="number"?Ce=[Ae,Ae,Ae,Ae]:((Ce=new Array(4))[0]=Ae[0],Ce[1]=Ae.length>=2?Ae[1]:Ce[0],Ce[2]=Ae.length>=3?Ae[2]:Ce[0],Ce[3]=Ae.length>=4?Ae[3]:Ce[1]),d.margin=Ce}});var Ee=!1;Object.defineProperty(this,"autoPaging",{get:function(){return Ee},set:function(Ae){Ee=Ae}});var Se=0;Object.defineProperty(this,"lastBreak",{get:function(){return Se},set:function(Ae){Se=Ae}});var Le=[];Object.defineProperty(this,"pageBreaks",{get:function(){return Le},set:function(Ae){Le=Ae}}),Object.defineProperty(this,"ctx",{get:function(){return d},set:function(Ae){Ae instanceof u&&(d=Ae)}}),Object.defineProperty(this,"path",{get:function(){return d.path},set:function(Ae){d.path=Ae}});var Fe=[];Object.defineProperty(this,"ctxStack",{get:function(){return Fe},set:function(Ae){Fe=Ae}}),Object.defineProperty(this,"fillStyle",{get:function(){return this.ctx.fillStyle},set:function(Ae){var Ce;Ce=m(Ae),this.ctx.fillStyle=Ce.style,this.ctx.isFillTransparent=Ce.a===0,this.ctx.fillOpacity=Ce.a,this.pdf.setFillColor(Ce.r,Ce.g,Ce.b,{a:Ce.a}),this.pdf.setTextColor(Ce.r,Ce.g,Ce.b,{a:Ce.a})}}),Object.defineProperty(this,"strokeStyle",{get:function(){return this.ctx.strokeStyle},set:function(Ae){var Ce=m(Ae);this.ctx.strokeStyle=Ce.style,this.ctx.isStrokeTransparent=Ce.a===0,this.ctx.strokeOpacity=Ce.a,Ce.a===0?this.pdf.setDrawColor(255,255,255):(Ce.a,this.pdf.setDrawColor(Ce.r,Ce.g,Ce.b))}}),Object.defineProperty(this,"lineCap",{get:function(){return this.ctx.lineCap},set:function(Ae){["butt","round","square"].indexOf(Ae)!==-1&&(this.ctx.lineCap=Ae,this.pdf.setLineCap(Ae))}}),Object.defineProperty(this,"lineWidth",{get:function(){return this.ctx.lineWidth},set:function(Ae){isNaN(Ae)||(this.ctx.lineWidth=Ae,this.pdf.setLineWidth(Ae))}}),Object.defineProperty(this,"lineJoin",{get:function(){return this.ctx.lineJoin},set:function(Ae){["bevel","round","miter"].indexOf(Ae)!==-1&&(this.ctx.lineJoin=Ae,this.pdf.setLineJoin(Ae))}}),Object.defineProperty(this,"miterLimit",{get:function(){return this.ctx.miterLimit},set:function(Ae){isNaN(Ae)||(this.ctx.miterLimit=Ae,this.pdf.setMiterLimit(Ae))}}),Object.defineProperty(this,"textBaseline",{get:function(){return this.ctx.textBaseline},set:function(Ae){this.ctx.textBaseline=Ae}}),Object.defineProperty(this,"textAlign",{get:function(){return this.ctx.textAlign},set:function(Ae){["right","end","center","left","start"].indexOf(Ae)!==-1&&(this.ctx.textAlign=Ae)}});var ke=null,Ve=null,je=null;Object.defineProperty(this,"fontFaces",{get:function(){return je},set:function(Ae){ke=null,Ve=null,je=Ae}}),Object.defineProperty(this,"font",{get:function(){return this.ctx.font},set:function(Ae){var Ce;if(this.ctx.font=Ae,(Ce=/^\s*(?=(?:(?:[-a-z]+\s*){0,2}(italic|oblique))?)(?=(?:(?:[-a-z]+\s*){0,2}(small-caps))?)(?=(?:(?:[-a-z]+\s*){0,2}(bold(?:er)?|lighter|[1-9]00))?)(?:(?:normal|\1|\2|\3)\s*){0,3}((?:xx?-)?(?:small|large)|medium|smaller|larger|[.\d]+(?:\%|in|[cem]m|ex|p[ctx]))(?:\s*\/\s*(normal|[.\d]+(?:\%|in|[cem]m|ex|p[ctx])))?\s*([-_,\"\'\sa-z0-9]+?)\s*$/i.exec(Ae))!==null){var qe=Ce[1];Ce[2];var ze=Ce[3],$e=Ce[4];Ce[5];var ct=Ce[6],Xe=/^([.\d]+)((?:%|in|[cem]m|ex|p[ctx]))$/i.exec($e)[2];$e=Math.floor(Xe==="px"?parseFloat($e)*this.pdf.internal.scaleFactor:Xe==="em"?parseFloat($e)*this.pdf.getFontSize():parseFloat($e)*this.pdf.internal.scaleFactor),this.pdf.setFontSize($e);var it=function(ys){var Bt,Ft,rs=[],St=ys.trim();if(St==="")return M$e;if(St in z4t)return[z4t[St]];for(;St!=="";){switch(Ft=null,Bt=(St=$4t(St)).charAt(0)){case'"':case"'":Ft=UWn(St.substring(1),Bt);break;default:Ft=qWn(St)}if(Ft===null||(rs.push(Ft[0]),(St=$4t(Ft[1]))!==""&&St.charAt(0)!==","))return M$e;St=St.replace(/^,/,"")}return rs}(ct);if(this.fontFaces){var at=function(ys,Bt){var Ft=ys.getFontList(),rs=JSON.stringify(Ft);if(ke===null||Ve!==rs){var St=function(Xs){var vt=[];return Object.keys(Xs).forEach(function(gs){Xs[gs].forEach(function(Ss){var Is=null;switch(Ss){case"bold":Is={family:gs,weight:"bold"};break;case"italic":Is={family:gs,style:"italic"};break;case"bolditalic":Is={family:gs,weight:"bold",style:"italic"};break;case"":case"normal":Is={family:gs}}Is!==null&&(Is.ref={name:gs,style:Ss},vt.push(Is))})}),vt}(Ft);ke=function(Xs){for(var vt={},gs=0;gs=700||qe==="bold")&&(xt="bold"),qe==="italic"&&(xt+="italic"),xt.length===0&&(xt="normal");for(var rt="",Yt={arial:"Helvetica",Arial:"Helvetica",verdana:"Helvetica",Verdana:"Helvetica",helvetica:"Helvetica",Helvetica:"Helvetica","sans-serif":"Helvetica",fixed:"Courier",monospace:"Courier",terminal:"Courier",cursive:"Times",fantasy:"Times",serif:"Times"},qt=0;qt=2*Math.PI&&(he=0,ue=2*Math.PI),this.path.push({type:"arc",x:J,y:ce,radius:_e,startAngle:he,endAngle:ue,counterclockwise:ve})},h.prototype.arcTo=function(J,ce,_e,he,ue){throw new Error("arcTo not implemented.")},h.prototype.rect=function(J,ce,_e,he){if(isNaN(J)||isNaN(ce)||isNaN(_e)||isNaN(he))throw vf.error("jsPDF.context2d.rect: Invalid arguments",arguments),new Error("Invalid arguments passed to jsPDF.context2d.rect");this.moveTo(J,ce),this.lineTo(J+_e,ce),this.lineTo(J+_e,ce+he),this.lineTo(J,ce+he),this.lineTo(J,ce),this.lineTo(J+_e,ce),this.lineTo(J,ce)},h.prototype.fillRect=function(J,ce,_e,he){if(isNaN(J)||isNaN(ce)||isNaN(_e)||isNaN(he))throw vf.error("jsPDF.context2d.fillRect: Invalid arguments",arguments),new Error("Invalid arguments passed to jsPDF.context2d.fillRect");if(!f.call(this)){var ue={};this.lineCap!=="butt"&&(ue.lineCap=this.lineCap,this.lineCap="butt"),this.lineJoin!=="miter"&&(ue.lineJoin=this.lineJoin,this.lineJoin="miter"),this.beginPath(),this.rect(J,ce,_e,he),this.fill(),ue.hasOwnProperty("lineCap")&&(this.lineCap=ue.lineCap),ue.hasOwnProperty("lineJoin")&&(this.lineJoin=ue.lineJoin)}},h.prototype.strokeRect=function(J,ce,_e,he){if(isNaN(J)||isNaN(ce)||isNaN(_e)||isNaN(he))throw vf.error("jsPDF.context2d.strokeRect: Invalid arguments",arguments),new Error("Invalid arguments passed to jsPDF.context2d.strokeRect");g.call(this)||(this.beginPath(),this.rect(J,ce,_e,he),this.stroke())},h.prototype.clearRect=function(J,ce,_e,he){if(isNaN(J)||isNaN(ce)||isNaN(_e)||isNaN(he))throw vf.error("jsPDF.context2d.clearRect: Invalid arguments",arguments),new Error("Invalid arguments passed to jsPDF.context2d.clearRect");this.ignoreClearRect||(this.fillStyle="#ffffff",this.fillRect(J,ce,_e,he))},h.prototype.save=function(J){J=typeof J!="boolean"||J;for(var ce=this.pdf.internal.getCurrentPageInfo().pageNumber,_e=0;_e0||this.margin[1]>0||this.margin[2]>0||this.margin[3]>0};h.prototype.drawImage=function(J,ce,_e,he,ue,ve,Ee,Se,Le){var Fe=this.pdf.getImageProperties(J),ke=1,Ve=1,je=1,Ae=1;he!==void 0&&Se!==void 0&&(je=Se/he,Ae=Le/ue,ke=Fe.width/he*Se/he,Ve=Fe.height/ue*Le/ue),ve===void 0&&(ve=ce,Ee=_e,ce=0,_e=0),he!==void 0&&Se===void 0&&(Se=he,Le=ue),he===void 0&&Se===void 0&&(Se=Fe.width,Le=Fe.height);var Ce=this.ctx.transform.decompose(),qe=ae(Ce.rotate.shx),ze=new c,$e=(ze=(ze=(ze=ze.multiply(Ce.translate)).multiply(Ce.skew)).multiply(Ce.scale)).applyToRectangle(new o(ve-ce*je,Ee-_e*Ae,he*ke,ue*Ve));if(this.autoPaging){for(var ct,Xe=y.call(this,$e),it=[],at=0;atKe||xt$e||Xe0)){for(;Le>=0;Le--)if(ue[Le-1].close!==!0&&ue[Le-1].begin!==!0){ue[Le-1].deltas.push(_e),ue[Le-1].abs.push(Se);break}}break;case"bct":_e=[Se.x1-ve[Ee-1].x,Se.y1-ve[Ee-1].y,Se.x2-ve[Ee-1].x,Se.y2-ve[Ee-1].y,Se.x-ve[Ee-1].x,Se.y-ve[Ee-1].y],ue[ue.length-1].deltas.push(_e);break;case"qct":var Fe=ve[Ee-1].x+2/3*(Se.x1-ve[Ee-1].x),ke=ve[Ee-1].y+2/3*(Se.y1-ve[Ee-1].y),Ve=Se.x+2/3*(Se.x1-Se.x),je=Se.y+2/3*(Se.y1-Se.y),Ae=Se.x,Ce=Se.y;_e=[Fe-ve[Ee-1].x,ke-ve[Ee-1].y,Ve-ve[Ee-1].x,je-ve[Ee-1].y,Ae-ve[Ee-1].x,Ce-ve[Ee-1].y],ue[ue.length-1].deltas.push(_e);break;case"arc":ue.push({deltas:[],abs:[],arc:!0}),Array.isArray(ue[ue.length-1].abs)&&ue[ue.length-1].abs.push(Se)}}he=ce?null:J==="stroke"?"stroke":"fill";for(var qe=!1,ze=0;ze=.01&&(he=this.pdf.internal.getFontSize(),this.pdf.setFontSize(he*J.scale),ue=this.lineWidth,this.lineWidth=ue*J.scale);var ts=this.autoPaging!=="text";if(ts||qt.y+qt.h<=at){if(ts||qt.y>=Xe&&qt.x<=nt){var ys=ts?J.text:this.pdf.splitTextToSize(J.text,J.maxWidth||nt-qt.x)[0],Bt=b([JSON.parse(JSON.stringify(Ve))],this.posX+this.margin[3],-rt+Xe+this.ctx.prevPageLastElemOffset)[0],Ft=ts&&(ct>ze||ct<$e)&&x.call(this);Ft&&(this.pdf.saveGraphicsState(),this.pdf.rect(this.margin[3],this.margin[0],xt,Ke,null).clip().discardPath()),this.pdf.text(ys,Bt.x,Bt.y,{angle:J.angle,align:ce,renderingMode:J.renderingMode}),Ft&&this.pdf.restoreGraphicsState()}}else qt.y=.01&&(this.pdf.setFontSize(he),this.lineWidth=ue)}}else J.scale>=.01&&(he=this.pdf.internal.getFontSize(),this.pdf.setFontSize(he*J.scale),ue=this.lineWidth,this.lineWidth=ue*J.scale),this.pdf.text(J.text,Le.x+this.posX,Le.y+this.posY,{angle:J.angle,align:ce,renderingMode:J.renderingMode,maxWidth:J.maxWidth}),J.scale>=.01&&(this.pdf.setFontSize(he),this.lineWidth=ue)},W=function(J,ce,_e,he){_e=_e||0,he=he||0,this.pdf.internal.out(n(J+_e)+" "+r(ce+he)+" l")},V=function(J,ce,_e){return this.pdf.lines(J,ce,_e,null,null)},G=function(J,ce,_e,he,ue,ve,Ee,Se){this.pdf.internal.out([t(a(_e+J)),t(i(he+ce)),t(a(ue+J)),t(i(ve+ce)),t(a(Ee+J)),t(i(Se+ce)),"c"].join(" "))},Y=function(J,ce,_e,he){for(var ue=2*Math.PI,ve=Math.PI/2;ce>_e;)ce-=ue;var Ee=Math.abs(_e-ce);Ee1e-5;){var ke=Fe+Le*Math.min(Ee,ve);Se.push(X.call(this,J,Fe,ke)),Ee-=Math.abs(ke-Fe),Fe=ke}return Se},X=function(J,ce,_e){var he=(_e-ce)/2,ue=J*Math.cos(he),ve=J*Math.sin(he),Ee=ue,Se=-ve,Le=Ee*Ee+Se*Se,Fe=Le+Ee*ue+Se*ve,ke=4/3*(Math.sqrt(2*Le*Fe)-Fe)/(Ee*ve-Se*ue),Ve=Ee-ke*Se,je=Se+ke*Ee,Ae=Ve,Ce=-je,qe=he+ce,ze=Math.cos(qe),$e=Math.sin(qe);return{x1:J*Math.cos(ce),y1:J*Math.sin(ce),x2:Ve*ze-je*$e,y2:Ve*$e+je*ze,x3:Ae*ze-Ce*$e,y3:Ae*$e+Ce*ze,x4:J*Math.cos(_e),y4:J*Math.sin(_e)}},ae=function(J){return 180*J/Math.PI},ie=function(J,ce,_e,he,ue,ve){var Ee=J+.5*(_e-J),Se=ce+.5*(he-ce),Le=ue+.5*(_e-ue),Fe=ve+.5*(he-ve),ke=Math.min(J,ue,Ee,Le),Ve=Math.max(J,ue,Ee,Le),je=Math.min(ce,ve,Se,Fe),Ae=Math.max(ce,ve,Se,Fe);return new o(ke,je,Ve-ke,Ae-je)},ne=function(J,ce,_e,he,ue,ve,Ee,Se){var Le,Fe,ke,Ve,je,Ae,Ce,qe,ze,$e,ct,Xe,it,at,Ke=_e-J,nt=he-ce,xt=ue-_e,rt=ve-he,Yt=Ee-ue,qt=Se-ve;for(Fe=0;Fe<41;Fe++)ze=(Ce=(ke=J+(Le=Fe/40)*Ke)+Le*((je=_e+Le*xt)-ke))+Le*(je+Le*(ue+Le*Yt-je)-Ce),$e=(qe=(Ve=ce+Le*nt)+Le*((Ae=he+Le*rt)-Ve))+Le*(Ae+Le*(ve+Le*qt-Ae)-qe),Fe==0?(ct=ze,Xe=$e,it=ze,at=$e):(ct=Math.min(ct,ze),Xe=Math.min(Xe,$e),it=Math.max(it,ze),at=Math.max(at,$e));return new o(Math.round(ct),Math.round(Xe),Math.round(it-ct),Math.round(at-Xe))},te=function(){if(this.prevLineDash||this.ctx.lineDash.length||this.ctx.lineDashOffset){var J,ce,_e=(J=this.ctx.lineDash,ce=this.ctx.lineDashOffset,JSON.stringify({lineDash:J,lineDashOffset:ce}));this.prevLineDash!==_e&&(this.pdf.setLineDash(this.ctx.lineDash,this.ctx.lineDashOffset),this.prevLineDash=_e)}}})(Go.API),function(s){var t=function(l){var o,c,d,u,h,m,f,g,x,y;for(c=[],d=0,u=(l+=o="\0\0\0\0".slice(l.length%4||4)).length;u>d;d+=4)(h=(l.charCodeAt(d)<<24)+(l.charCodeAt(d+1)<<16)+(l.charCodeAt(d+2)<<8)+l.charCodeAt(d+3))!==0?(m=(h=((h=((h=((h=(h-(y=h%85))/85)-(x=h%85))/85)-(g=h%85))/85)-(f=h%85))/85)%85,c.push(m+33,f+33,g+33,x+33,y+33)):c.push(122);return function(v,b){for(var w=b;w>0;w--)v.pop()}(c,o.length),String.fromCharCode.apply(String,c)+"~>"},n=function(l){var o,c,d,u,h,m=String,f="length",g=255,x="charCodeAt",y="slice",v="replace";for(l[y](-2),l=l[y](0,-2)[v](/\s/g,"")[v]("z","!!!!!"),d=[],u=0,h=(l+=o="uuuuu"[y](l[f]%5||5))[f];h>u;u+=5)c=52200625*(l[x](u)-33)+614125*(l[x](u+1)-33)+7225*(l[x](u+2)-33)+85*(l[x](u+3)-33)+(l[x](u+4)-33),d.push(g&c>>24,g&c>>16,g&c>>8,g&c);return function(b,w){for(var S=w;S>0;S--)b.pop()}(d,o[f]),m.fromCharCode.apply(m,d)},r=function(l){return l.split("").map(function(o){return("0"+o.charCodeAt().toString(16)).slice(-2)}).join("")+">"},a=function(l){var o=new RegExp(/^([0-9A-Fa-f]{2})+$/);if((l=l.replace(/\s/g,"")).indexOf(">")!==-1&&(l=l.substr(0,l.indexOf(">"))),l.length%2&&(l+="0"),o.test(l)===!1)return"";for(var c="",d=0;dimport("./html2canvas.esm-CBrSDip1.js"),[])).catch(function(o){return Promise.reject(new Error("Could not load html2canvas: "+o))}).then(function(o){return o.default?o.default:o})}function n(){return(Oc.DOMPurify?Promise.resolve(Oc.DOMPurify):ri(()=>import("./purify.es-BYftNTi7.js"),[])).catch(function(o){return Promise.reject(new Error("Could not load dompurify: "+o))}).then(function(o){return o.default?o.default:o})}var r=function(o){var c=Pm(o);return c==="undefined"?"undefined":c==="string"||o instanceof String?"string":c==="number"||o instanceof Number?"number":c==="function"||o instanceof Function?"function":o&&o.constructor===Array?"array":o&&o.nodeType===1?"element":c==="object"?"object":"unknown"},a=function(o,c){var d=document.createElement(o);for(var u in c.className&&(d.className=c.className),c.innerHTML&&c.dompurify&&(d.innerHTML=c.dompurify.sanitize(c.innerHTML)),c.style)d.style[u]=c.style[u];return d},i=function o(c,d){for(var u=c.nodeType===3?document.createTextNode(c.nodeValue):c.cloneNode(!1),h=c.firstChild;h;h=h.nextSibling)d!==!0&&h.nodeType===1&&h.nodeName==="SCRIPT"||u.appendChild(o(h,d));return c.nodeType===1&&(c.nodeName==="CANVAS"?(u.width=c.width,u.height=c.height,u.getContext("2d").drawImage(c,0,0)):c.nodeName!=="TEXTAREA"&&c.nodeName!=="SELECT"||(u.value=c.value),u.addEventListener("load",function(){u.scrollTop=c.scrollTop,u.scrollLeft=c.scrollLeft},!0)),u},l=function o(c){var d=Object.assign(o.convert(Promise.resolve()),JSON.parse(JSON.stringify(o.template))),u=o.convert(Promise.resolve(),d);return(u=u.setProgress(1,o,1,[o])).set(c)};(l.prototype=Object.create(Promise.prototype)).constructor=l,l.convert=function(o,c){return o.__proto__=c||l.prototype,o},l.template={prop:{src:null,container:null,overlay:null,canvas:null,img:null,pdf:null,pageSize:null,callback:function(){}},progress:{val:0,state:null,n:0,stack:[]},opt:{filename:"file.pdf",margin:[0,0,0,0],enableLinks:!0,x:0,y:0,html2canvas:{},jsPDF:{},backgroundColor:"transparent"}},l.prototype.from=function(o,c){return this.then(function(){switch(c=c||function(d){switch(r(d)){case"string":return"string";case"element":return d.nodeName.toLowerCase()==="canvas"?"canvas":"element";default:return"unknown"}}(o),c){case"string":return this.then(n).then(function(d){return this.set({src:a("div",{innerHTML:o,dompurify:d})})});case"element":return this.set({src:o});case"canvas":return this.set({canvas:o});case"img":return this.set({img:o});default:return this.error("Unknown source type.")}})},l.prototype.to=function(o){switch(o){case"container":return this.toContainer();case"canvas":return this.toCanvas();case"img":return this.toImg();case"pdf":return this.toPdf();default:return this.error("Invalid target.")}},l.prototype.toContainer=function(){return this.thenList([function(){return this.prop.src||this.error("Cannot duplicate - no source HTML.")},function(){return this.prop.pageSize||this.setPageSize()}]).then(function(){var o={position:"relative",display:"inline-block",width:(typeof this.opt.width!="number"||isNaN(this.opt.width)||typeof this.opt.windowWidth!="number"||isNaN(this.opt.windowWidth)?Math.max(this.prop.src.clientWidth,this.prop.src.scrollWidth,this.prop.src.offsetWidth):this.opt.windowWidth)+"px",left:0,right:0,top:0,margin:"auto",backgroundColor:this.opt.backgroundColor},c=i(this.prop.src,this.opt.html2canvas.javascriptEnabled);c.tagName==="BODY"&&(o.height=Math.max(document.body.scrollHeight,document.body.offsetHeight,document.documentElement.clientHeight,document.documentElement.scrollHeight,document.documentElement.offsetHeight)+"px"),this.prop.overlay=a("div",{className:"html2pdf__overlay",style:{position:"fixed",overflow:"hidden",zIndex:1e3,left:"-100000px",right:0,bottom:0,top:0}}),this.prop.container=a("div",{className:"html2pdf__container",style:o}),this.prop.container.appendChild(c),this.prop.container.firstChild.appendChild(a("div",{style:{clear:"both",border:"0 none transparent",margin:0,padding:0,height:0}})),this.prop.container.style.float="none",this.prop.overlay.appendChild(this.prop.container),document.body.appendChild(this.prop.overlay),this.prop.container.firstChild.style.position="relative",this.prop.container.height=Math.max(this.prop.container.firstChild.clientHeight,this.prop.container.firstChild.scrollHeight,this.prop.container.firstChild.offsetHeight)+"px"})},l.prototype.toCanvas=function(){var o=[function(){return document.body.contains(this.prop.container)||this.toContainer()}];return this.thenList(o).then(t).then(function(c){var d=Object.assign({},this.opt.html2canvas);return delete d.onrendered,c(this.prop.container,d)}).then(function(c){(this.opt.html2canvas.onrendered||function(){})(c),this.prop.canvas=c,document.body.removeChild(this.prop.overlay)})},l.prototype.toContext2d=function(){var o=[function(){return document.body.contains(this.prop.container)||this.toContainer()}];return this.thenList(o).then(t).then(function(c){var d=this.opt.jsPDF,u=this.opt.fontFaces,h=typeof this.opt.width!="number"||isNaN(this.opt.width)||typeof this.opt.windowWidth!="number"||isNaN(this.opt.windowWidth)?1:this.opt.width/this.opt.windowWidth,m=Object.assign({async:!0,allowTaint:!0,scale:h,scrollX:this.opt.scrollX||0,scrollY:this.opt.scrollY||0,backgroundColor:"#ffffff",imageTimeout:15e3,logging:!0,proxy:null,removeContainer:!0,foreignObjectRendering:!1,useCORS:!1},this.opt.html2canvas);if(delete m.onrendered,d.context2d.autoPaging=this.opt.autoPaging===void 0||this.opt.autoPaging,d.context2d.posX=this.opt.x,d.context2d.posY=this.opt.y,d.context2d.margin=this.opt.margin,d.context2d.fontFaces=u,u)for(var f=0;fx&&(g=y,y=x,x=g);else{if(o!=="l"&&o!=="landscape")throw"Invalid orientation: "+o;o="l",x>y&&(g=y,y=x,x=g)}return{width:y,height:x,unit:c,k:h,orientation:o}},s.html=function(o,c){(c=c||{}).callback=c.callback||function(){},c.html2canvas=c.html2canvas||{},c.html2canvas.canvas=c.html2canvas.canvas||this.canvas,c.jsPDF=c.jsPDF||this,c.fontFaces=c.fontFaces?c.fontFaces.map(T$e):null;var d=new l(c);return c.worker?d:d.from(o).doCallback()}}(Go.API),Go.API.addJS=function(s){var t,n,r=function(a){for(var i="",l=0;l=0&&a[d]==="\\";d--)c++;i+=c%2==0?"\\"+o:o}else i+=o}return i}(s);return this.internal.events.subscribe("postPutResources",function(){t=this.internal.newObject(),this.internal.out("<<"),this.internal.out("/Names [(EmbeddedJS) "+(t+1)+" 0 R]"),this.internal.out(">>"),this.internal.out("endobj"),n=this.internal.newObject(),this.internal.out("<<"),this.internal.out("/S /JavaScript"),this.internal.out("/JS ("+r+")"),this.internal.out(">>"),this.internal.out("endobj")}),this.internal.events.subscribe("putCatalog",function(){t!==void 0&&n!==void 0&&this.internal.out("/Names <>")}),this},function(s){var t;s.events.push(["postPutResources",function(){var n=this,r=/^(\d+) 0 obj$/;if(this.outline.root.children.length>0)for(var a=n.outline.render().split(/\r\n/),i=0;i> endobj")}var f=n.internal.newObject();for(n.internal.write("<< /Names [ "),i=0;i>","endobj"),t=n.internal.newObject(),n.internal.write("<< /Dests "+f+" 0 R"),n.internal.write(">>","endobj")}}]),s.events.push(["putCatalog",function(){var n=this;n.outline.root.children.length>0&&(n.internal.write("/Outlines",this.outline.makeRef(this.outline.root)),this.outline.createNamedDestinations&&n.internal.write("/Names "+t+" 0 R"))}]),s.events.push(["initialized",function(){var n=this;n.outline={createNamedDestinations:!1,root:{children:[]}},n.outline.add=function(r,a,i){var l={title:a,options:i,children:[]};return r==null&&(r=this.root),r.children.push(l),l},n.outline.render=function(){return this.ctx={},this.ctx.val="",this.ctx.pdf=n,this.genIds_r(this.root),this.renderRoot(this.root),this.renderItems(this.root),this.ctx.val},n.outline.genIds_r=function(r){r.id=n.internal.newObjectDeferred();for(var a=0;a0&&(this.line("/First "+this.makeRef(r.children[0])),this.line("/Last "+this.makeRef(r.children[r.children.length-1]))),this.line("/Count "+this.count_r({count:0},r)),this.objEnd()},n.outline.renderItems=function(r){for(var a=this.ctx.pdf.internal.getVerticalCoordinateString,i=0;i0&&this.line("/Prev "+this.makeRef(r.children[i-1])),i0&&(this.line("/First "+this.makeRef(l.children[0])),this.line("/Last "+this.makeRef(l.children[l.children.length-1])));var o=this.count=this.count_r({count:0},l);if(o>0&&this.line("/Count "+o),l.options&&l.options.pageNumber){var c=n.internal.getPageInfo(l.options.pageNumber);this.line("/Dest ["+c.objId+" 0 R /XYZ 0 "+a(0)+" 0]")}this.objEnd()}for(var d=0;d> \r endobj\r `},n.outline.count_r=function(r,a){for(var i=0;i1){V=!0,Y=void 0;var ue=R*D;X=new Uint8Array(ue);for(var ve=new DataView(O.buffer),Ee=0;Ee536870912)throw new Error("Image dimensions exceed 512MB, which is too large.");this.data=new Uint8Array(t);try{this[s]()}catch(n){vf.log("bit decode error:"+n)}},rS.prototype.bit1=function(){var s,t=Math.ceil(this.width/8),n=t%4;for(s=this.height-1;s>=0;s--){for(var r=this.bottom_up?s:this.height-1-s,a=0;a>7-o&1];this.data[l+4*o]=c.blue,this.data[l+4*o+1]=c.green,this.data[l+4*o+2]=c.red,this.data[l+4*o+3]=255}n!==0&&(this.pos+=4-n)}},rS.prototype.bit4=function(){for(var s=Math.ceil(this.width/2),t=s%4,n=this.height-1;n>=0;n--){for(var r=this.bottom_up?n:this.height-1-n,a=0;a>4,c=15&i,d=this.palette[o];if(this.data[l]=d.blue,this.data[l+1]=d.green,this.data[l+2]=d.red,this.data[l+3]=255,2*a+1>=this.width)break;d=this.palette[c],this.data[l+4]=d.blue,this.data[l+4+1]=d.green,this.data[l+4+2]=d.red,this.data[l+4+3]=255}t!==0&&(this.pos+=4-t)}},rS.prototype.bit8=function(){for(var s=this.width%4,t=this.height-1;t>=0;t--){for(var n=this.bottom_up?t:this.height-1-t,r=0;r=0;n--){for(var r=this.bottom_up?n:this.height-1-n,a=0;a>5&t)/t*255|0,c=(i>>10&t)/t*255|0,d=i>>15?255:0,u=r*this.width*4+4*a;this.data[u]=c,this.data[u+1]=o,this.data[u+2]=l,this.data[u+3]=d}this.pos+=s}},rS.prototype.bit16=function(){for(var s=this.width%3,t=parseInt("11111",2),n=parseInt("111111",2),r=this.height-1;r>=0;r--){for(var a=this.bottom_up?r:this.height-1-r,i=0;i>5&n)/n*255|0,d=(l>>11)/t*255|0,u=a*this.width*4+4*i;this.data[u]=d,this.data[u+1]=c,this.data[u+2]=o,this.data[u+3]=255}this.pos+=s}},rS.prototype.bit24=function(){for(var s=this.height-1;s>=0;s--){for(var t=this.bottom_up?s:this.height-1-s,n=0;n=0;s--)for(var t=this.bottom_up?s:this.height-1-s,n=0;nr&&(a.push(s.slice(c,i)),o=0,c=i),o+=t[i],i++;return c!==i&&a.push(s.slice(c,i)),a},V4t=function(s,t,n){n||(n={});var r,a,i,l,o,c,d,u=[],h=[u],m=n.textIndent||0,f=0,g=0,x=s.split(" "),y=Mue.apply(this,[" ",n])[0];if(c=n.lineIndent===-1?x[0].length+2:n.lineIndent||0){var v=Array(c).join(" "),b=[];x.map(function(S){(S=S.split(/\s*\n/)).length>1?b=b.concat(S.map(function(C,E){return(E&&C.length?` `:"")+C})):b.push(S[0])}),x=b,c=U4t.apply(this,[v,n])}for(i=0,l=x.length;it||w){if(g>t){for(o=q4t.apply(this,[r,a,t-(m+f),t]),u.push(o.shift()),u=[o.pop()];o.length;)h.push([o.shift()]);g=a.slice(r.length-(u[0]?u[0].length:0)).reduce(function(S,C){return S+C},0)}else u=[r];h.push(u),m=g+c,f=y}else u.push(r),m+=f+g,f=y}return d=c?function(S,C){return(C?v:"")+S.join(" ")}:function(S){return S.join(" ")},h.map(d)},K$.splitTextToSize=function(s,t,n){var r,a=(n=n||{}).fontSize||this.internal.getFontSize(),i=(function(u){if(u.widths&&u.kerning)return{widths:u.widths,kerning:u.kerning};var h=this.internal.getFont(u.fontName,u.fontStyle),m="Unicode";return h.metadata[m]?{widths:h.metadata[m].widths||{0:1},kerning:h.metadata[m].kerning||{}}:{font:h.metadata,fontSize:this.internal.getFontSize(),charSpace:this.internal.getCharSpace()}}).call(this,n);r=Array.isArray(s)?s:String(s).split(/\r?\n/);var l=1*this.internal.scaleFactor*t/a;i.textIndent=n.textIndent?1*n.textIndent*this.internal.scaleFactor/a:0,i.lineIndent=n.lineIndent;var o,c,d=[];for(o=0,c=r.length;oimport("./index.es-CVDok0HZ.js"),[])).catch(function(m){return Promise.reject(new Error("Could not load canvg: "+m))}).then(function(m){return m.default?m.default:m}).then(function(m){return m.fromString(d,s,u)},function(){return Promise.reject(new Error("Could not load canvg."))}).then(function(m){return m.render(u)}).then(function(){h.addImage(c.toDataURL("image/jpeg",1),t,n,r,a,l,o)})},Go.API.putTotalPages=function(s){var t,n=0;parseInt(this.internal.getFont().id.substr(1),10)<15?(t=new RegExp(s,"g"),n=this.internal.getNumberOfPages()):(t=new RegExp(this.pdfEscape16(s,this.internal.getFont()),"g"),n=this.pdfEscape16(this.internal.getNumberOfPages()+"",this.internal.getFont()));for(var r=1;r<=this.internal.getNumberOfPages();r++)for(var a=0;a1){for(u=0;u>`)}),this.internal.viewerpreferences.isSubscribed=!0),this.internal.viewerpreferences.configuration=n,this},Go.API.addMetadata=function(s,t){return this.internal.__metadata__===void 0&&(this.internal.__metadata__={metadata:s,namespaceUri:t??"http://jspdf.default.namespaceuri/",rawXml:typeof t=="boolean"&&t},this.internal.events.subscribe("putCatalog",YWn),this.internal.events.subscribe("postPutResources",KWn)),this},function(s){var t=s.API,n=t.pdfEscape16=function(i,l){for(var o,c=l.metadata.Unicode.widths,d=["","0","00","000","0000"],u=[""],h=0,m=i.length;h> def /CMapName /Adobe-Identity-UCS def /CMapType 2 def 1 begincodespacerange <0000> endcodespacerange`,c=[],h=0,m=(o=Object.keys(i).sort(function(f,g){return f-g})).length;h=100&&(u+=` `+c.length+` beginbfchar `+c.join(` `)+` endbfchar`,c=[]),i[l]!==void 0&&i[l]!==null&&typeof i[l].toString=="function"&&(d=("0000"+i[l].toString(16)).slice(-4),l=("0000"+(+l).toString(16)).slice(-4),c.push("<"+l+"><"+d+">"));return c.length&&(u+=` `+c.length+` beginbfchar `+c.join(` `)+` endbfchar `),u+`endcmap CMapName currentdict /CMap defineresource pop end end`};t.events.push(["putFont",function(i){(function(l){var o=l.font,c=l.out,d=l.newObject,u=l.putStream;if(o.metadata instanceof s.API.TTFFont&&o.encoding==="Identity-H"){for(var h=o.metadata.Unicode.widths,m=o.metadata.subset.encode(o.metadata.glyIdsUsed,1),f="",g=0;g>"),c("endobj");var b=d();c("<<"),c("/Type /Font"),c("/BaseFont /"+CU(o.fontName)),c("/FontDescriptor "+v+" 0 R"),c("/W "+s.API.PDFObject.convert(h)),c("/CIDToGIDMap /Identity"),c("/DW 1000"),c("/Subtype /CIDFontType2"),c("/CIDSystemInfo"),c("<<"),c("/Supplement 0"),c("/Registry (Adobe)"),c("/Ordering ("+o.encoding+")"),c(">>"),c(">>"),c("endobj"),o.objectNumber=d(),c("<<"),c("/Type /Font"),c("/Subtype /Type0"),c("/ToUnicode "+y+" 0 R"),c("/BaseFont /"+CU(o.fontName)),c("/Encoding /"+o.encoding),c("/DescendantFonts ["+b+" 0 R]"),c(">>"),c("endobj"),o.isAlreadyPutted=!0}})(i)}]),t.events.push(["putFont",function(i){(function(l){var o=l.font,c=l.out,d=l.newObject,u=l.putStream;if(o.metadata instanceof s.API.TTFFont&&o.encoding==="WinAnsiEncoding"){for(var h=o.metadata.rawData,m="",f=0;f>"),c("endobj"),o.objectNumber=d();for(var v=0;v>"),c("endobj"),o.isAlreadyPutted=!0}})(i)}]);var a=function(i){var l,o=i.text||"",c=i.x,d=i.y,u=i.options||{},h=i.mutex||{},m=h.pdfEscape,f=h.activeFontKey,g=h.fonts,x=f,y="",v=0,b="",w=g[x].encoding;if(g[x].encoding!=="Identity-H")return{text:o,x:c,y:d,options:u,mutex:h};for(b=o,x=f,Array.isArray(o)&&(b=o[0]),v=0;v","<","[","]","[","{","}","{","«","»","«","‹","›","‹","⁅","⁆","⁅","⁽","⁾","⁽","₍","₎","₍","≤","≥","≤","〈","〉","〈","﹙","﹚","﹙","﹛","﹜","﹛","﹝","﹞","﹝","﹤","﹥","﹤"],v=new RegExp(/^([1-4|9]|1[0-9]|2[0-9]|3[0168]|4[04589]|5[012]|7[78]|159|16[0-9]|17[0-2]|21[569]|22[03489]|250)$/),b=!1,w=0;this.__bidiEngine__={};var S=function(O){var U=O.charCodeAt(),W=U>>8,V=x[W];return V!==void 0?h[256*V+(255&U)]:W===252||W===253?"AL":v.test(W)?"L":W===8?"R":"N"},C=function(O){for(var U,W=0;W=U.length||(G=W[V-1])!=="EN"&&G!=="AN"||(Y=U[V+1])!=="EN"&&Y!=="AN"?ie="N":b&&(Y="AN"),ie=Y===G?Y:"N";break;case"ES":ie=(G=V>0?W[V-1]:"B")==="EN"&&V+10&&W[V-1]==="EN"){ie="EN";break}if(b){ie="N";break}for(X=V+1,ae=U.length;X=1425&&ne<=2303||ne===64286;if(G=U[X],te&&(G==="R"||G==="AL")){ie="R";break}}}ie=V<1||(G=U[V-1])==="B"?"N":W[V-1];break;case"B":b=!1,a=!0,ie=w;break;case"S":i=!0,ie="N"}return ie},I=function(O,U,W){var V=O.split("");return W&&P(V,W,{hiLevel:w}),V.reverse(),U&&U.reverse(),V.join("")},P=function(O,U,W){var V,G,Y,X,ae,ie=-1,ne=O.length,te=0,J=[],ce=w?f:m,_e=[];for(b=!1,a=!1,i=!1,G=0;G0)if(V===16){for(G=ie;G-1){for(G=ie;G=0&&he[Se]==="WS";Se--)ue[Se]=w}}(_e,U,ne)},R=function(O,U,W,V,G){if(!(G.hiLevel=O){for(ae=te+1;ae=O;)ae++;for(ie=te,X=ae-1;ie=0&&(Y[ne]=y[ie+1])}(V,W,G),R(2,V,U,W,G),R(1,V,U,W,G),V.join("")};return this.__bidiEngine__.doBidiReorder=function(O,U,W){if(function(G,Y){if(Y)for(var X=0;X>16)&&(n=-(1+(65535^n))),this.italicAngle=+(n+"."+r)):this.italicAngle=0,this.ascender=Math.round(this.ascender*this.scaleFactor),this.decender=Math.round(this.decender*this.scaleFactor),this.lineGap=Math.round(this.lineGap*this.scaleFactor),this.capHeight=this.os2.exists&&this.os2.capHeight||this.ascender,this.xHeight=this.os2.exists&&this.os2.xHeight||0,this.familyClass=(this.os2.exists&&this.os2.familyClass||0)>>8,this.isSerif=(i=this.familyClass)===1||i===2||i===3||i===4||i===5||i===7,this.isScript=this.familyClass===10,this.flags=0,this.post.isFixedPitch&&(this.flags|=1),this.isSerif&&(this.flags|=2),this.isScript&&(this.flags|=8),this.italicAngle!==0&&(this.flags|=64),this.flags|=32,!this.cmap.unicode)throw new Error("No unicode cmap for font")},s.prototype.characterToGlyph=function(t){var n;return((n=this.cmap.unicode)!=null?n.codeMap[t]:void 0)||0},s.prototype.widthOfGlyph=function(t){var n;return n=1e3/this.head.unitsPerEm,this.hmtx.forGlyph(t).advance*n},s.prototype.widthOfString=function(t,n,r){var a,i,l,o;for(l=0,i=0,o=(t=""+t).length;0<=o?io;i=0<=o?++i:--i)a=t.charCodeAt(i),l+=this.widthOfGlyph(this.characterToGlyph(a))+r*(1e3/n)||0;return l*(n/1e3)},s.prototype.lineHeight=function(t,n){var r;return n==null&&(n=!1),r=n?this.lineGap:0,(this.ascender+r-this.decender)/1e3*t},s}();var PC,qL=function(){function s(t){this.data=t??[],this.pos=0,this.length=this.data.length}return s.prototype.readByte=function(){return this.data[this.pos++]},s.prototype.writeByte=function(t){return this.data[this.pos++]=t},s.prototype.readUInt32=function(){return 16777216*this.readByte()+(this.readByte()<<16)+(this.readByte()<<8)+this.readByte()},s.prototype.writeUInt32=function(t){return this.writeByte(t>>>24&255),this.writeByte(t>>16&255),this.writeByte(t>>8&255),this.writeByte(255&t)},s.prototype.readInt32=function(){var t;return(t=this.readUInt32())>=2147483648?t-4294967296:t},s.prototype.writeInt32=function(t){return t<0&&(t+=4294967296),this.writeUInt32(t)},s.prototype.readUInt16=function(){return this.readByte()<<8|this.readByte()},s.prototype.writeUInt16=function(t){return this.writeByte(t>>8&255),this.writeByte(255&t)},s.prototype.readInt16=function(){var t;return(t=this.readUInt16())>=32768?t-65536:t},s.prototype.writeInt16=function(t){return t<0&&(t+=65536),this.writeUInt16(t)},s.prototype.readString=function(t){var n,r;for(r=[],n=0;0<=t?nt;n=0<=t?++n:--n)r[n]=String.fromCharCode(this.readByte());return r.join("")},s.prototype.writeString=function(t){var n,r,a;for(a=[],n=0,r=t.length;0<=r?nr;n=0<=r?++n:--n)a.push(this.writeByte(t.charCodeAt(n)));return a},s.prototype.readShort=function(){return this.readInt16()},s.prototype.writeShort=function(t){return this.writeInt16(t)},s.prototype.readLongLong=function(){var t,n,r,a,i,l,o,c;return t=this.readByte(),n=this.readByte(),r=this.readByte(),a=this.readByte(),i=this.readByte(),l=this.readByte(),o=this.readByte(),c=this.readByte(),128&t?-1*(72057594037927940*(255^t)+281474976710656*(255^n)+1099511627776*(255^r)+4294967296*(255^a)+16777216*(255^i)+65536*(255^l)+256*(255^o)+(255^c)+1):72057594037927940*t+281474976710656*n+1099511627776*r+4294967296*a+16777216*i+65536*l+256*o+c},s.prototype.writeLongLong=function(t){var n,r;return n=Math.floor(t/4294967296),r=4294967295&t,this.writeByte(n>>24&255),this.writeByte(n>>16&255),this.writeByte(n>>8&255),this.writeByte(255&n),this.writeByte(r>>24&255),this.writeByte(r>>16&255),this.writeByte(r>>8&255),this.writeByte(255&r)},s.prototype.readInt=function(){return this.readInt32()},s.prototype.writeInt=function(t){return this.writeInt32(t)},s.prototype.read=function(t){var n,r;for(n=[],r=0;0<=t?rt;r=0<=t?++r:--r)n.push(this.readByte());return n},s.prototype.write=function(t){var n,r,a,i;for(i=[],r=0,a=t.length;ri;a=0<=i?++a:--a)r={tag:n.readString(4),checksum:n.readInt(),offset:n.readInt(),length:n.readInt()},this.tables[r.tag]=r}return t.prototype.encode=function(n){var r,a,i,l,o,c,d,u,h,m,f,g,x;for(x in f=Object.keys(n).length,c=Math.log(2),h=16*Math.floor(Math.log(f)/c),l=Math.floor(h/c),u=16*f-h,(a=new qL).writeInt(this.scalarType),a.writeShort(f),a.writeShort(h),a.writeShort(l),a.writeShort(u),i=16*f,d=a.pos+i,o=null,g=[],n)for(m=n[x],a.writeString(x),a.writeInt(s(m)),a.writeInt(d),a.writeInt(m.length),g=g.concat(m),x==="head"&&(o=d),d+=m.length;d%4;)g.push(0),d++;return a.write(g),r=2981146554-s(a.data),a.pos=o+8,a.writeUInt32(r),a.data},s=function(n){var r,a,i,l;for(n=xss.call(n);n.length%4;)n.push(0);for(i=new qL(n),a=0,r=0,l=n.length;rm;c=0<=m?++S:--S)C.push(t.readUInt16());return C}(),t.pos+=2,x=function(){var S,C;for(C=[],c=S=0;0<=m?Sm;c=0<=m?++S:--S)C.push(t.readUInt16());return C}(),d=function(){var S,C;for(C=[],c=S=0;0<=m?Sm;c=0<=m?++S:--S)C.push(t.readUInt16());return C}(),u=function(){var S,C;for(C=[],c=S=0;0<=m?Sm;c=0<=m?++S:--S)C.push(t.readUInt16());return C}(),a=(this.length-t.pos+this.offset)/2,o=function(){var S,C;for(C=[],c=S=0;0<=a?Sa;c=0<=a?++S:--S)C.push(t.readUInt16());return C}(),c=v=0,w=i.length;v=y;r=g<=y?++b:--b)u[c]===0?l=r+d[c]:(l=o[u[c]/2+(r-g)-(m-c)]||0)!==0&&(l+=d[c]),this.codeMap[r]=65535&l}t.pos=h}return s.encode=function(t,n){var r,a,i,l,o,c,d,u,h,m,f,g,x,y,v,b,w,S,C,E,I,P,R,D,O,U,W,V,G,Y,X,ae,ie,ne,te,J,ce,_e,he,ue,ve,Ee,Se,Le,Fe,ke;switch(V=new qL,l=Object.keys(t).sort(function(Ve,je){return Ve-je}),n){case"macroman":for(x=0,y=function(){var Ve=[];for(g=0;g<256;++g)Ve.push(0);return Ve}(),b={0:0},i={},G=0,ie=l.length;G=32768)for(c.push(0),E.push(2*(f.length+R-g)),a=ae=O;O<=u?ae<=u:ae>=u;a=O<=u?++ae:--ae)f.push(r[a].new);else c.push(W-O),E.push(0)}for(V.writeUInt16(3),V.writeUInt16(1),V.writeUInt32(12),V.writeUInt16(4),V.writeUInt16(16+8*R+2*f.length),V.writeUInt16(0),V.writeUInt16(D),V.writeUInt16(P),V.writeUInt16(m),V.writeUInt16(I),ve=0,J=h.length;vea;r=0<=a?++r:--r)n=new J4t(t,this.offset),this.tables.push(n),n.isUnicode&&this.unicode==null&&(this.unicode=n);return!0},s.encode=function(t,n){var r,a;return n==null&&(n="macroman"),r=J4t.encode(t,n),(a=new qL).writeUInt16(0),a.writeUInt16(1),r.table=a.data.concat(r.subtable),r},s}(),JWn=function(){function s(){return s.__super__.constructor.apply(this,arguments)}return j3(s,PC),s.prototype.tag="hhea",s.prototype.parse=function(t){return t.pos=this.offset,this.version=t.readInt(),this.ascender=t.readShort(),this.decender=t.readShort(),this.lineGap=t.readShort(),this.advanceWidthMax=t.readShort(),this.minLeftSideBearing=t.readShort(),this.minRightSideBearing=t.readShort(),this.xMaxExtent=t.readShort(),this.caretSlopeRise=t.readShort(),this.caretSlopeRun=t.readShort(),this.caretOffset=t.readShort(),t.pos+=8,this.metricDataFormat=t.readShort(),this.numberOfMetrics=t.readUInt16()},s}(),eKn=function(){function s(){return s.__super__.constructor.apply(this,arguments)}return j3(s,PC),s.prototype.tag="OS/2",s.prototype.parse=function(t){if(t.pos=this.offset,this.version=t.readUInt16(),this.averageCharWidth=t.readShort(),this.weightClass=t.readUInt16(),this.widthClass=t.readUInt16(),this.type=t.readShort(),this.ySubscriptXSize=t.readShort(),this.ySubscriptYSize=t.readShort(),this.ySubscriptXOffset=t.readShort(),this.ySubscriptYOffset=t.readShort(),this.ySuperscriptXSize=t.readShort(),this.ySuperscriptYSize=t.readShort(),this.ySuperscriptXOffset=t.readShort(),this.ySuperscriptYOffset=t.readShort(),this.yStrikeoutSize=t.readShort(),this.yStrikeoutPosition=t.readShort(),this.familyClass=t.readShort(),this.panose=function(){var n,r;for(r=[],n=0;n<10;++n)r.push(t.readByte());return r}(),this.charRange=function(){var n,r;for(r=[],n=0;n<4;++n)r.push(t.readInt());return r}(),this.vendorID=t.readString(4),this.selection=t.readShort(),this.firstCharIndex=t.readShort(),this.lastCharIndex=t.readShort(),this.version>0&&(this.ascent=t.readShort(),this.descent=t.readShort(),this.lineGap=t.readShort(),this.winAscent=t.readShort(),this.winDescent=t.readShort(),this.codePageRange=function(){var n,r;for(r=[],n=0;n<2;n=++n)r.push(t.readInt());return r}(),this.version>1))return this.xHeight=t.readShort(),this.capHeight=t.readShort(),this.defaultChar=t.readShort(),this.breakChar=t.readShort(),this.maxContext=t.readShort()},s}(),tKn=function(){function s(){return s.__super__.constructor.apply(this,arguments)}return j3(s,PC),s.prototype.tag="post",s.prototype.parse=function(t){var n,r,a;switch(t.pos=this.offset,this.format=t.readInt(),this.italicAngle=t.readInt(),this.underlinePosition=t.readShort(),this.underlineThickness=t.readShort(),this.isFixedPitch=t.readInt(),this.minMemType42=t.readInt(),this.maxMemType42=t.readInt(),this.minMemType1=t.readInt(),this.maxMemType1=t.readInt(),this.format){case 65536:case 196608:break;case 131072:var i;for(r=t.readUInt16(),this.glyphNameIndex=[],i=0;0<=r?ir;i=0<=r?++i:--i)this.glyphNameIndex.push(t.readUInt16());for(this.names=[],a=[];t.poso;i=0<=o?++l:--l)c.push(t.readUInt32());return c}).call(this)}},s}(),sKn=function(s,t){this.raw=s,this.length=s.length,this.platformID=t.platformID,this.encodingID=t.encodingID,this.languageID=t.languageID},nKn=function(){function s(){return s.__super__.constructor.apply(this,arguments)}return j3(s,PC),s.prototype.tag="name",s.prototype.parse=function(t){var n,r,a,i,l,o,c,d,u,h,m;for(t.pos=this.offset,t.readShort(),n=t.readShort(),o=t.readShort(),r=[],i=0;0<=n?in;i=0<=n?++i:--i)r.push({platformID:t.readShort(),encodingID:t.readShort(),languageID:t.readShort(),nameID:t.readShort(),length:t.readShort(),offset:this.offset+o+t.readShort()});for(c={},i=u=0,h=r.length;uo;n=0<=o?++n:--n)this.metrics.push({advance:t.readUInt16(),lsb:t.readInt16()});for(a=this.file.maxp.numGlyphs-this.file.hhea.numberOfMetrics,this.leftSideBearings=function(){var d,u;for(u=[],n=d=0;0<=a?da;n=0<=a?++d:--d)u.push(t.readInt16());return u}(),this.widths=(function(){var d,u,h,m;for(m=[],d=0,u=(h=this.metrics).length;da;n=0<=a?++l:--l)c.push(this.widths.push(r));return c},s.prototype.forGlyph=function(t){return t in this.metrics?this.metrics[t]:{advance:this.metrics[this.metrics.length-1].advance,lsb:this.leftSideBearings[t-this.metrics.length]}},s}(),xss=[].slice,iKn=function(){function s(){return s.__super__.constructor.apply(this,arguments)}return j3(s,PC),s.prototype.tag="glyf",s.prototype.parse=function(){return this.cache={}},s.prototype.glyphFor=function(t){var n,r,a,i,l,o,c,d,u,h;return t in this.cache?this.cache[t]:(i=this.file.loca,n=this.file.contents,r=i.indexOf(t),(a=i.lengthOf(t))===0?this.cache[t]=null:(n.pos=this.offset+r,l=(o=new qL(n.read(a))).readShort(),d=o.readShort(),h=o.readShort(),c=o.readShort(),u=o.readShort(),this.cache[t]=l===-1?new lKn(o,d,h,c,u):new oKn(o,l,d,h,c,u),this.cache[t]))},s.prototype.encode=function(t,n,r){var a,i,l,o,c;for(l=[],i=[],o=0,c=n.length;o0&&(a+=c)}for(var d=new Array(4*r.length),u=0;u>8,d[4*u+1]=(16711680&r[u])>>16,d[4*u]=(4278190080&r[u])>>24;return d},s}(),dKn=function(){function s(t){this.font=t,this.subset={},this.unicodes={},this.next=33}return s.prototype.generateCmap=function(){var t,n,r,a,i;for(n in a=this.font.cmap.tables[0].codeMap,t={},i=this.subset)r=i[n],t[n]=a[r];return t},s.prototype.glyphsFor=function(t){var n,r,a,i,l,o,c;for(a={},l=0,o=t.length;l0)for(i in c=this.glyphsFor(n))r=c[i],a[i]=r;return a},s.prototype.encode=function(t,n){var r,a,i,l,o,c,d,u,h,m,f,g,x,y,v;for(a in r=gss.encode(this.generateCmap(),"unicode"),l=this.glyphsFor(t),f={0:0},v=r.charMap)f[(c=v[a]).old]=c.new;for(g in m=r.maxGlyphID,l)g in f||(f[g]=m++);return u=function(b){var w,S;for(w in S={},b)S[b[w]]=w;return S}(f),h=Object.keys(u).sort(function(b,w){return b-w}),x=function(){var b,w,S;for(S=[],b=0,w=h.length;b>"),i.join(` `)}return""+n},t}();const bZe=[{id:"signature",name:"Signature",description:"The default editorial look, tinted with your own brand and accent colors.",swatch:["#0E1B2C","#2A4C64","#B8965A","#FCFBF8"],brand:"#2A4C64",accent:"#B8965A",paper:"#FCFBF8",paperCool:"#F4F7FA",softLine:"#DFE4EA",bodyInk:"#484E58",headFont:"helvetica",useAgentColors:!0},{id:"land-ranch",name:"Land, Farm & Ranch",description:"Warm olive and saddle leather on a natural paper stock. Built for acreage and estates.",swatch:["#2C3A24","#3E5232","#B07C3A","#F7F4EC"],brand:"#3E5232",accent:"#B07C3A",paper:"#F7F4EC",paperCool:"#F0EDE1",softLine:"#DCD4C2",bodyInk:"#4C4A40",headFont:"times",useAgentColors:!1},{id:"luxury",name:"Luxury",description:"Near-black ink with brushed gold and serif headlines. Quiet, expensive, restrained.",swatch:["#0B0C0F","#16181E","#C9A84C","#FAF8F4"],brand:"#16181E",accent:"#C9A84C",paper:"#FAF8F4",paperCool:"#F2EFE8",softLine:"#E0DACB",bodyInk:"#4A4A50",headFont:"times",useAgentColors:!1},{id:"coastal",name:"Beaches",description:"Deep ocean navy, surf teal, and sea-glass paper. Bright, breezy, coastal.",swatch:["#08293A","#0F3B52","#2FA0A8","#F8FBFC"],brand:"#0F3B52",accent:"#2FA0A8",paper:"#F8FBFC",paperCool:"#EDF6F8",softLine:"#D2E3E9",bodyInk:"#44565E",headFont:"helvetica",useAgentColors:!1}],uKn="signature";function hKn(s){return bZe.find(t=>t.id===s)||bZe[0]}const vd=792,Gf=612,wa=52;function Y$(s){const t=(s||"").replace("#","").padEnd(6,"0");return[parseInt(t.slice(0,2),16)||0,parseInt(t.slice(2,4),16)||0,parseInt(t.slice(4,6),16)||0]}function Lg(s,t,n){return[Math.round(s[0]+(t[0]-s[0])*n),Math.round(s[1]+(t[1]-s[1])*n),Math.round(s[2]+(t[2]-s[2])*n)]}const N3=[22,24,28],E_=[124,128,136],Xo=[255,255,255];function mKn(s){return s==null||!Number.isFinite(Number(s))?null:new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(Number(s))}const L$e="https://relzejiswnotikjgvjhz.supabase.co";function fKn(s){if(!s||s.startsWith("data:")||s.startsWith("blob:"))return s;try{const t=new URL(s,window.location.origin);return t.origin===window.location.origin||t.origin===new URL(L$e).origin?s:`${L$e}/functions/v1/image-proxy?url=${encodeURIComponent(t.toString())}`}catch{return s}}async function hX(s,t=2e3){if(!s)return null;try{const n=await fetch(fKn(s),{mode:"cors"});if(!n.ok)return null;const r=await n.blob(),a=URL.createObjectURL(r),i=await new Promise((x,y)=>{const v=new Image;v.crossOrigin="anonymous",v.onload=()=>x(v),v.onerror=y,v.src=a}),l=Math.min(1,t/i.naturalWidth),o=Math.max(1,Math.round(i.naturalWidth*l)),c=Math.max(1,Math.round(i.naturalHeight*l)),d=document.createElement("canvas");d.width=o,d.height=c,d.getContext("2d").drawImage(i,0,0,o,c),URL.revokeObjectURL(a);const h=r.type.includes("png"),m=h?"PNG":"JPEG",f=d.toDataURL(h?"image/png":"image/jpeg",.92);return{el:await new Promise(x=>{const y=new Image;y.onload=()=>x(y),y.onerror=()=>x(y),y.src=f}),dataUrl:f,w:o,h:c,format:m}}catch{return null}}let yss={x:.5,y:.5};function pKn(s){yss={x:Math.min(1,Math.max(0,(s==null?void 0:s.x)??.5)),y:Math.min(1,Math.max(0,(s==null?void 0:s.y)??.5))}}function Wie(s,t,n,r,a,i,l={}){const o=l.dpi??2,c=Math.max(1,Math.round(a*o)),d=Math.max(1,Math.round(i*o)),u=document.createElement("canvas");u.width=c,u.height=d;const h=u.getContext("2d"),m=t.w/t.h,f=a/i;let g=0,x=0,y=t.w,v=t.h;const b=l.focal??yss;if(m>f?(y=t.h*f,g=Math.min(Math.max(0,t.w*b.x-y/2),t.w-y)):(v=t.w/f,x=Math.min(Math.max(0,t.h*b.y-v/2),t.h-v)),l.radius&&l.radius>0){const C=Math.min(l.radius*o,c/2,d/2);h.beginPath(),h.moveTo(C,0),h.arcTo(c,0,c,d,C),h.arcTo(c,d,0,d,C),h.arcTo(0,d,0,0,C),h.arcTo(0,0,c,0,C),h.closePath(),h.clip()}const w=[];l.grayscale&&w.push("grayscale(1)"),l.blur&&w.push(`blur(${l.blur*o}px)`),w.length&&(h.filter=w.join(" "));try{h.drawImage(t.el,g,x,y,v,0,0,c,d)}catch{h.fillStyle="#e9e6e0",h.fillRect(0,0,c,d)}if(h.filter="none",l.tint&&l.tint.amount>0){const[C,E,I]=l.tint.color;h.globalCompositeOperation="multiply",h.fillStyle=`rgba(${C},${E},${I},${Math.min(1,l.tint.amount)})`,h.fillRect(0,0,c,d),h.globalCompositeOperation="source-over"}if(l.darken&&l.darken>0&&(h.fillStyle=`rgba(0,0,0,${Math.min(.9,l.darken)})`,h.fillRect(0,0,c,d)),l.gradient==="bottom"){const C=h.createLinearGradient(0,0,0,d);C.addColorStop(0,"rgba(0,0,0,0)"),C.addColorStop(.45,"rgba(0,0,0,0.05)"),C.addColorStop(1,"rgba(0,0,0,0.8)"),h.fillStyle=C,h.fillRect(0,0,c,d)}else if(l.gradient==="full"){const C=h.createLinearGradient(0,0,0,d);C.addColorStop(0,"rgba(0,0,0,0.4)"),C.addColorStop(.5,"rgba(0,0,0,0.18)"),C.addColorStop(1,"rgba(0,0,0,0.85)"),h.fillStyle=C,h.fillRect(0,0,c,d)}else if(l.gradient==="left"){const C=h.createLinearGradient(0,0,c,0);C.addColorStop(0,"rgba(0,0,0,0.75)"),C.addColorStop(.6,"rgba(0,0,0,0.15)"),C.addColorStop(1,"rgba(0,0,0,0)"),h.fillStyle=C,h.fillRect(0,0,c,d)}const S=u.toDataURL("image/jpeg",.92);s.addImage(S,"JPEG",n,r,a,i,void 0,"FAST")}function P7(s,t,n,r,a,i=3){const l=a*2,o=Math.max(1,Math.round(l*i)),c=document.createElement("canvas");c.width=o,c.height=o;const d=c.getContext("2d");d.fillStyle="#ffffff",d.fillRect(0,0,o,o),d.save(),d.beginPath(),d.arc(o/2,o/2,o/2,0,Math.PI*2),d.closePath(),d.clip();const u=t.w/t.h;let h=0,m=0,f=t.w,g=t.h;u>1?(f=t.h,h=(t.w-f)/2):(g=t.w,m=(t.h-g)/2);try{d.drawImage(t.el,h,m,f,g,0,0,o,o)}catch{}d.restore(),s.addImage(c.toDataURL("image/jpeg",.92),"JPEG",n-a,r-a,l,l,void 0,"FAST")}function Tot(s,t,n,r,a,i,l="left"){const o=t.w/t.h;let c=i,d=c*o;d>a&&(d=a,c=d/o);const u=l==="right"?n-d:n;return s.addImage(t.dataUrl,t.format,u,r,d,c,void 0,"FAST"),{w:d,h:c}}function pw(s,t){const n=s.GState;n&&s.setGState(new n({opacity:t}))}function gKn(s,t,n,r,a,i={font:"helvetica",size:10,color:N3}){s.setFont(i.font,i.style||"normal"),s.setFontSize(i.size),s.setTextColor(...i.color);const l=i.leading??i.size*1.5,o=s.splitTextToSize(t,a);return o.forEach((c,d)=>{s.text(c,n,r+d*l,i.align==="center"?{align:"center"}:void 0)}),r+o.length*l}function sY(s,t,n,r,a,i){let l=r;const o=i.size*1.45;return t.forEach(c=>{s.setFillColor(...i.accent),s.circle(n+2.4,l-i.size*.32,2,"F"),l=gKn(s,c,n+13,l,a-13,{font:i.font,size:i.size,color:i.color,leading:o})+(i.gap??7)}),l}function T1(s,t,n,r,a,i,l,o="F",c,d=.6){s.setFillColor(...l),c&&(s.setDrawColor(...c),s.setLineWidth(d)),s.roundedRect(t,n,r,a,i,i,o)}const m9='',f9='',xKn={title:"Facebook",slug:"facebook",get svg(){return m9+"Facebook"+f9+this.path+p9},path:"M9.101 23.691v-7.98H6.627v-3.667h2.474v-1.58c0-4.085 1.848-5.978 5.858-5.978.401 0 .955.042 1.468.103a8.68 8.68 0 0 1 1.141.195v3.325a8.623 8.623 0 0 0-.653-.036 26.805 26.805 0 0 0-.733-.009c-.707 0-1.259.096-1.675.309a1.686 1.686 0 0 0-.679.622c-.258.42-.374.995-.374 1.752v1.297h3.919l-.386 2.103-.287 1.564h-3.246v8.245C19.396 23.238 24 18.179 24 12.044c0-6.627-5.373-12-12-12s-12 5.373-12 12c0 5.628 3.874 10.35 9.101 11.647Z",source:"https://about.meta.com/brand/resources/facebook/logo",hex:"0866FF",guidelines:"https://about.meta.com/brand/resources/facebook/logo"},yKn={title:"Instagram",slug:"instagram",get svg(){return m9+"Instagram"+f9+this.path+p9},path:"M7.0301.084c-1.2768.0602-2.1487.264-2.911.5634-.7888.3075-1.4575.72-2.1228 1.3877-.6652.6677-1.075 1.3368-1.3802 2.127-.2954.7638-.4956 1.6365-.552 2.914-.0564 1.2775-.0689 1.6882-.0626 4.947.0062 3.2586.0206 3.6671.0825 4.9473.061 1.2765.264 2.1482.5635 2.9107.308.7889.72 1.4573 1.388 2.1228.6679.6655 1.3365 1.0743 2.1285 1.38.7632.295 1.6361.4961 2.9134.552 1.2773.056 1.6884.069 4.9462.0627 3.2578-.0062 3.668-.0207 4.9478-.0814 1.28-.0607 2.147-.2652 2.9098-.5633.7889-.3086 1.4578-.72 2.1228-1.3881.665-.6682 1.0745-1.3378 1.3795-2.1284.2957-.7632.4966-1.636.552-2.9124.056-1.2809.0692-1.6898.063-4.948-.0063-3.2583-.021-3.6668-.0817-4.9465-.0607-1.2797-.264-2.1487-.5633-2.9117-.3084-.7889-.72-1.4568-1.3876-2.1228C21.2982 1.33 20.628.9208 19.8378.6165 19.074.321 18.2017.1197 16.9244.0645 15.6471.0093 15.236-.005 11.977.0014 8.718.0076 8.31.0215 7.0301.0839m.1402 21.6932c-1.17-.0509-1.8053-.2453-2.2287-.408-.5606-.216-.96-.4771-1.3819-.895-.422-.4178-.6811-.8186-.9-1.378-.1644-.4234-.3624-1.058-.4171-2.228-.0595-1.2645-.072-1.6442-.079-4.848-.007-3.2037.0053-3.583.0607-4.848.05-1.169.2456-1.805.408-2.2282.216-.5613.4762-.96.895-1.3816.4188-.4217.8184-.6814 1.3783-.9003.423-.1651 1.0575-.3614 2.227-.4171 1.2655-.06 1.6447-.072 4.848-.079 3.2033-.007 3.5835.005 4.8495.0608 1.169.0508 1.8053.2445 2.228.408.5608.216.96.4754 1.3816.895.4217.4194.6816.8176.9005 1.3787.1653.4217.3617 1.056.4169 2.2263.0602 1.2655.0739 1.645.0796 4.848.0058 3.203-.0055 3.5834-.061 4.848-.051 1.17-.245 1.8055-.408 2.2294-.216.5604-.4763.96-.8954 1.3814-.419.4215-.8181.6811-1.3783.9-.4224.1649-1.0577.3617-2.2262.4174-1.2656.0595-1.6448.072-4.8493.079-3.2045.007-3.5825-.006-4.848-.0608M16.953 5.5864A1.44 1.44 0 1 0 18.39 4.144a1.44 1.44 0 0 0-1.437 1.4424M5.8385 12.012c.0067 3.4032 2.7706 6.1557 6.173 6.1493 3.4026-.0065 6.157-2.7701 6.1506-6.1733-.0065-3.4032-2.771-6.1565-6.174-6.1498-3.403.0067-6.156 2.771-6.1496 6.1738M8 12.0077a4 4 0 1 1 4.008 3.9921A3.9996 3.9996 0 0 1 8 12.0077",source:"https://about.meta.com/brand/resources/instagram",hex:"FF0069",guidelines:"https://about.meta.com/brand/resources/instagram"},vKn={title:"Pinterest",slug:"pinterest",get svg(){return m9+"Pinterest"+f9+this.path+p9},path:"M12.017 0C5.396 0 .029 5.367.029 11.987c0 5.079 3.158 9.417 7.618 11.162-.105-.949-.199-2.403.041-3.439.219-.937 1.406-5.957 1.406-5.957s-.359-.72-.359-1.781c0-1.663.967-2.911 2.168-2.911 1.024 0 1.518.769 1.518 1.688 0 1.029-.653 2.567-.992 3.992-.285 1.193.6 2.165 1.775 2.165 2.128 0 3.768-2.245 3.768-5.487 0-2.861-2.063-4.869-5.008-4.869-3.41 0-5.409 2.562-5.409 5.199 0 1.033.394 2.143.889 2.741.099.12.112.225.085.345-.09.375-.293 1.199-.334 1.363-.053.225-.172.271-.401.165-1.495-.69-2.433-2.878-2.433-4.646 0-3.776 2.748-7.252 7.92-7.252 4.158 0 7.392 2.967 7.392 6.923 0 4.135-2.607 7.462-6.233 7.462-1.214 0-2.354-.629-2.758-1.379l-.749 2.848c-.269 1.045-1.004 2.352-1.498 3.146 1.123.345 2.306.535 3.55.535 6.607 0 11.985-5.365 11.985-11.987C23.97 5.39 18.592.026 11.985.026L12.017 0z",source:"https://business.pinterest.com/en/brand-guidelines",hex:"BD081C",guidelines:"https://business.pinterest.com/en/brand-guidelines"},bKn={title:"TikTok",slug:"tiktok",get svg(){return m9+"TikTok"+f9+this.path+p9},path:"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",source:"https://tiktok.com",hex:"000000"},_Kn={title:"trulia",slug:"trulia",get svg(){return m9+"trulia"+f9+this.path+p9},path:"M17.6958 8.9368a.6678.6678 0 0 0 .095 1.329.6678.6678 0 0 0 .6678-.668.6678.6678 0 0 0-.7628-.661zm-4.3956.2812v1.121h.7513v3.4726h-.7513v1.121h2.6262v-1.121h-.7513V9.218Zm-12.549.121v1.3814H.0001v1.1281h.7513v1.0852c0 1.1799.9502 2.1362 2.1226 2.1362a2.1126 2.1126 0 0 0 .4608-.0507v-1.115a1.1025 1.1025 0 0 1-.3837.0685c-.5958 0-1.0789-.4689-1.0789-1.047v-1.0772H3.335v-1.1281H1.872V9.339Zm20.92 1.2609c-1.1147-.005-2.0196.9806-2.019 2.1905.0005 1.21.9043 2.1952 2.019 2.1905.0292 0 .0598-.0009.0877-.002.4221-.0111.8757-.2098 1.113-.488v.4218H24v-4.2458h-1.1275l-.0005.4236c-.2385-.2791-.692-.477-1.113-.4879-.0292-.002-.0585-.002-.0878-.002zm-14.8245.0473c-.5173.003-.9275.153-1.2964.654l-.2277-.64h-1.098v1.1271h.5195v3.1444h1.118v-2.1983a.9887.9887 0 0 1 .9851-.9906h.339v-1.0966Zm9.6549.047v1.1172h.7513v3.121h1.8736v-1.117h-.7514l.001-3.1212zm-8.2605.0298v2.2125c0 1.1773.9494 2.1315 2.1195 2.1315s2.1193-.9525 2.1193-2.1298v-2.214h-1.1186v2.2539a1.0018 1.0018 0 1 1-2.001 0v-2.254zm13.5857.9717c.5932 0 1.074.5008 1.0746 1.1191.0005.6184-.4814 1.1192-1.0746 1.1192-.5933 0-1.0742-.5008-1.075-1.1192-.0008-.6183.4817-1.1191 1.075-1.1191z",source:"https://www.trulia.com/newsroom/media/brand-logos",hex:"0A0B09",guidelines:"https://www.trulia.com/newsroom/media/brand-logos"},wKn={title:"YouTube",slug:"youtube",get svg(){return m9+"YouTube"+f9+this.path+p9},path:"M23.498 6.186a3.016 3.016 0 0 0-2.122-2.136C19.505 3.545 12 3.545 12 3.545s-7.505 0-9.377.505A3.017 3.017 0 0 0 .502 6.186C0 8.07 0 12 0 12s0 3.93.502 5.814a3.016 3.016 0 0 0 2.122 2.136c1.871.505 9.376.505 9.376.505s7.505 0 9.377-.505a3.015 3.015 0 0 0 2.122-2.136C24 15.93 24 12 24 12s0-3.93-.502-5.814zM9.545 15.568V8.432L15.818 12l-6.273 3.568z",source:"https://www.youtube.com/howyoutubeworks/resources/brand-resources/#logos-icons-and-colors",hex:"FF0000",guidelines:"https://www.youtube.com/howyoutubeworks/resources/brand-resources/#logos-icons-and-colors"},jKn={title:"Zillow",slug:"zillow",get svg(){return m9+"Zillow"+f9+this.path+p9},path:"M12.006 0L1.086 8.627v3.868c3.386-2.013 11.219-5.13 14.763-6.015.11-.024.16.005.227.078.372.427 1.586 1.899 1.916 2.301a.128.128 0 0 1-.03.195 43.607 43.607 0 0 0-6.67 6.527c-.03.037-.006.043.012.03 2.642-1.134 8.828-2.94 11.622-3.452V8.627zm-.48 11.177c-2.136.708-8.195 3.307-10.452 4.576V24h21.852v-7.936c-2.99.506-11.902 3.16-15.959 5.246a.183.183 0 0 1-.23-.036l-2.044-2.429c-.055-.061-.062-.098.011-.208 1.574-2.3 4.789-5.899 6.833-7.418.042-.03.031-.06-.012-.042Z",source:"https://www.zillow.com",hex:"006AFF"},NKn={facebook:xKn,instagram:yKn,youtube:wKn,tiktok:bKn,pinterest:vKn,zillow:jKn,trulia:_Kn},e3t=new Map;function kKn(s,t,n){return`${s}|${t}|${n}`}function SKn(s,t,n=128){const r=s.toLowerCase().replace(/[^a-z]/g,""),a=NKn[r];if(!a)return null;const i=kKn(r,t,n),l=e3t.get(i);if(l)return l;try{const o=document.createElement("canvas");o.width=n,o.height=n;const c=o.getContext("2d");if(!c)return null;c.clearRect(0,0,n,n),c.scale(n/24,n/24),c.fillStyle=t,c.fill(new Path2D(a.path));const d=o.toDataURL("image/png");return e3t.set(i,d),d}catch{return null}}const $u="helvetica";let SW="helvetica";function vss(s,t,n,r,a,i){const l=`#${n.map(d=>Math.round(d).toString(16).padStart(2,"0")).join("")}`,o=SKn(t,l,160);if(o){s.addImage(o,"PNG",r-i/2,a-i/2,i,i,void 0,"FAST");return}const c=i/2;s.setFillColor(...n),s.circle(r,a,c,"F"),s.setFont($u,"bold"),s.setFontSize(c*1.15),s.setTextColor(...Xo),s.text(t.charAt(0).toUpperCase(),r,a+c*.42,{align:"center"})}let Kie=[252,251,248],vB=[244,247,250],$w=[223,228,234],Ib=[72,78,88];function Yie(s,t){return wts(s.data.pages,t)}function Mot(s){var n;const t=s.coAgent;return t!=null&&t.enabled&&((n=t.name)!=null&&n.trim())?t:null}function bss(s){const t=s.property,n=[t.city,[t.state,t.postalCode].filter(Boolean).join(" ")].filter(Boolean).join(", ");return{line1:t.addressLine1||"Your Home",line2:n}}function CKn(s){return[s.agent.brokerageName,s.agent.phone,s.agent.email].filter(Boolean).join(" | ")}function iy(s,t,n,r,a,i,l){const o=l.font||$u,c=l.style||"normal";let d=i;s.setFont(o,c),s.setFontSize(d);const u=l.charSpace??0,h=()=>s.getTextWidth(t)+u*Math.max(0,t.length-1);for(;h()>a&&d>(l.min??6);)d-=.5,s.setFontSize(d);return s.setTextColor(...l.color),s.text(t,n,r,{align:l.align,charSpace:u}),d}function om(s,t,n,r,a,i){s.setFont($u,i.style||"normal"),s.setFontSize(i.size),s.setTextColor(...i.color);const l=i.leading??i.size*1.45;let o=s.splitTextToSize(t,a);if(i.maxLines&&o.length>i.maxLines){o=o.slice(0,i.maxLines);const c=o[o.length-1];o[o.length-1]=c.replace(/[\s,;.:]+$/,"")+"…"}return o.forEach((c,d)=>s.text(c,n,r+d*l,i.align==="center"?{align:"center"}:void 0)),r+(o.length-1)*l}function nY(s,t,n,r,a,i){const{doc:l}=s;l.setFont($u,"bold"),l.setFontSize(7.5),l.setTextColor(...a||s.accent),l.text(t.toUpperCase(),n,r,{charSpace:1.8,align:i})}function Fv(s,t=Kie){s.doc.addPage("letter","landscape"),s.pageNo+=1,s.doc.setFillColor(...t),s.doc.rect(0,0,vd,Gf,"F")}function Lb(s,t,n,r,a={}){const{doc:i}=s,l=!!a.dark,o=a.width??vd-wa*2-60;nY(s,t,wa,62,s.accent),i.setFont(SW,"bold"),i.setFontSize(SW==="times"?25:23);const c=i.splitTextToSize(n,o).slice(0,3);i.setTextColor(...l?Xo:s.brand),c.forEach((u,h)=>i.text(u,wa,96+h*29));let d=96+(c.length-1)*29;return r&&(d=om(i,r,wa,d+26,Math.min(o+40,vd-wa*2),{size:10,color:l?Lg(Xo,s.deep,.28):E_,leading:15,maxLines:2})),d+34}function Ov(s,t=!1){const{doc:n,data:r}=s,a=t?Lg(Xo,s.deep,.7):$w;n.setDrawColor(...a),n.setLineWidth(.6),n.line(wa,Gf-46,vd-wa,Gf-46);const i=Gf-30;n.setFont($u,"bold"),n.setFontSize(7),n.setTextColor(...t?Xo:s.brand),t&&pw(n,.9),n.text((r.agent.name||"").toUpperCase(),wa,i,{charSpace:1.4});const l=CKn(r);l&&(n.setFont($u,"normal"),n.setFontSize(7),n.setTextColor(...t?Xo:E_),iy(n,l,vd/2,i,vd/2-wa-40,7,{color:t?Xo:E_,align:"center"})),n.setFont($u,"normal"),n.setFontSize(7),n.setTextColor(...t?Xo:E_),n.text(String(s.pageNo).padStart(2,"0"),vd-wa,i,{align:"right"}),t&&pw(n,1)}function _ss(s,t,n,r,a){const{doc:i}=s;i.setFont($u,"bold"),i.setFontSize(8);const l=i.splitTextToSize(t,a-28),o=16+l.length*12;return T1(i,n,r,a,o,6,Lg(s.accent,Xo,.86)),i.setTextColor(...Lg(s.brand,N3,.2)),l.forEach((c,d)=>i.text(c,n+14,r+20+d*12)),r+o}function Pot(s,t,n,r,a,i={}){const{doc:l}=s;s.hero?Wie(l,s.hero,t,n,r,a,{radius:10,dpi:s.dpi,tint:i.tint?{color:s.deep,amount:i.tint}:void 0}):T1(l,t,n,r,a,10,Lg(s.deep,Xo,.12))}function AKn(s){const{doc:t,data:n}=s,{line1:r,line2:a}=bss(n),i=336;s.hero?Wie(t,s.hero,0,0,vd,Gf,{dpi:s.dpi,darken:.12}):(t.setFillColor(...s.deep),t.rect(0,0,vd,Gf,"F")),t.setFillColor(...s.deep),t.rect(0,0,i,Gf,"F"),t.setFillColor(...s.accent),t.rect(i-3,0,3,Gf,"F");const l=Yie(s,"cover");nY(s,l.kicker,wa,66),t.setFont(SW,"bold"),t.setFontSize(SW==="times"?29:26),t.setTextColor(...Xo);const o=t.splitTextToSize(r,i-wa*2).slice(0,3);o.forEach((y,v)=>t.text(y,wa,102+v*30));let c=102+(o.length-1)*30;a&&(t.setFont($u,"normal"),t.setFontSize(9),pw(t,.9),iy(t,a.toUpperCase(),wa,c+22,i-wa*2,9,{color:Xo,charSpace:1.4}),pw(t,1),c+=22),c=om(t,l.body,wa,c+34,i-wa*2,{size:10,color:Lg(Xo,s.deep,.22),leading:16});const d=[mKn(n.property.listPrice),n.property.beds?`${n.property.beds} BD`:null,n.property.baths?`${n.property.baths} BA`:null,n.property.sqft?`${Number(n.property.sqft).toLocaleString()} SF`:null].filter(Boolean);d.length&&(t.setDrawColor(...s.accent),t.setLineWidth(1.5),t.line(wa,c+30,wa+40,c+30),iy(t,d.join(" · "),wa,c+54,i-wa*2,10,{style:"bold",color:Xo,charSpace:1}));const u=Mot(n),h=Gf-(u?152:128);let m=wa;s.headshot&&(P7(t,s.headshot,wa+22,h+18,22),u&&s.coHeadshot?(P7(t,s.coHeadshot,wa+56,h+18,22),m=wa+90):m=wa+56),iy(t,u?`${n.agent.name} + ${u.name}`:n.agent.name,m,h+12,i-m-24,14,{style:"bold",color:Xo}),t.setFont($u,"normal"),t.setFontSize(8),pw(t,.85);const f=[n.agent.brokerageName].filter(Boolean).join("");f&&iy(t,f,m,h+26,i-m-24,8,{color:Xo});const g=[n.agent.phone,n.agent.email].filter(Boolean).join(" · ");if(g&&iy(t,g,m,h+38,i-m-24,8,{color:Xo}),u){const y=[u.title||"Co-listing agent",u.phone].filter(Boolean).join(" · ");y&&iy(t,y,wa,h+56,i-wa-24,8,{color:Xo})}pw(t,1),s.logo&&(pw(t,.95),Tot(t,s.logo,wa,Gf-74,132,30,"left"),pw(t,1));const x=n.sellerName?`PREPARED FOR ${n.sellerName.toUpperCase()}`:"PREPARED FOR YOUR HOME";t.setFont($u,"bold"),t.setFontSize(7.5),t.setTextColor(...Xo),pw(t,.9),t.text(x,vd-wa,Gf-34,{align:"right",charSpace:1.6}),pw(t,1)}function EKn(s){Fv(s);const{doc:t}=s,n=Yie(s,"welcome"),r=Lb(s,n.kicker,n.headline,n.subhead||null),a=[["Make it look irresistible","Professional visuals help buyers stop, click, and imagine themselves at home."],["Put it everywhere buyers search","MLS distribution, property portals, mobile search, and a dedicated online showcase."],["Create demand beyond the portals","Social campaigns, email, database outreach, and local promotion keep momentum moving."]];let i=r+10;a.forEach(([l,o],c)=>{t.setFillColor(...Lg(s.accent,Xo,.85)),t.circle(wa+13,i-3,13,"F"),t.setFont($u,"bold"),t.setFontSize(9),t.setTextColor(...s.brand),t.text(String(c+1).padStart(2,"0"),wa+13,i,{align:"center"});const d=wa+44,u=vd-d-wa-40;t.setFont($u,"bold"),t.setFontSize(11.5),t.setTextColor(...N3),t.text(l,d,i),om(t,o,d,i+18,u,{size:9.5,color:Ib,leading:14,maxLines:2}),i+=88}),Ov(s)}function TKn(s){Fv(s,Xo);const{doc:t,data:n}=s,r=Yie(s,"agent"),a=Lb(s,r.kicker,r.headline,r.subhead||n.agent.tagline||"You are not hiring a website or a billboard — you are hiring a person."),i=Mot(n),l=vd-wa-260,o=a-6,c=262;if(i){const g=(x,y,v,b)=>{T1(t,l,x,260,124,10,vB,"FD",$w),t.setFillColor(...s.accent),t.rect(l,x,260,3,"F");let w=l+18;v&&(P7(t,v,l+48,x+62+2,30),w=l+90);const S=260-(w-l)-18;iy(t,y,w,x+40,S,13,{style:"bold",color:s.brand});let C=x+56;b.filter(Boolean).slice(0,4).forEach(E=>{iy(t,String(E),w,C,S,8,{color:E_}),C+=13})};g(o,n.agent.name,s.headshot,[n.agent.brokerageName,n.agent.phone,n.agent.email]),g(o+124+14,i.name,s.coHeadshot,[i.title||"Co-listing agent",i.brokerageName||n.agent.brokerageName,i.phone,i.email])}else{T1(t,l,o,260,c,10,vB,"FD",$w),t.setFillColor(...s.accent),t.rect(l,o,260,3,"F"),s.headshot&&P7(t,s.headshot,l+130,o+72,42),iy(t,n.agent.name,l+130,o+(s.headshot?138:70),216,16,{style:"bold",color:s.brand,align:"center"});let m=o+(s.headshot?158:92);[n.agent.brokerageName,n.agent.phone,n.agent.email,n.agent.website].filter(Boolean).slice(0,4).forEach(f=>{iy(t,String(f),l+130,m,220,8.5,{color:E_,align:"center"}),m+=14}),s.logo&&Tot(t,s.logo,l+80,o+c-44,100,28,"left")}const d=l-wa-44;let u=om(t,i?i.bio||"You are working with both of us. Here is how to reach us, and the professional details behind the marketing plan in this presentation — every step that follows is something we run personally on your home.":"Here is how to reach me, and the professional details behind the marketing plan in this presentation. Every step that follows is something I run personally on your home.",wa,a+4,d,{size:10,color:Ib,leading:16,maxLines:5});u+=34,[["Phone",n.agent.phone],["Email",n.agent.email],["Website",n.agent.website],["Brokerage",n.agent.brokerageName],["License",n.agent.licenseNumber?`${n.agent.licenseNumber}${n.agent.licenseState?` · ${n.agent.licenseState}`:""}`:null],i?["Co-listing",[i.name,i.licenseNumber].filter(Boolean).join(" · ")]:["",null]].filter(([m,f])=>!!m&&!!f).forEach(([m,f])=>{t.setFont($u,"bold"),t.setFontSize(7),t.setTextColor(...E_),t.text(m.toUpperCase(),wa,u,{charSpace:1.4}),iy(t,f,wa+86,u,d-86,10.5,{color:N3}),t.setDrawColor(...$w),t.setLineWidth(.5),t.line(wa,u+11,wa+d,u+11),u+=36}),Ov(s)}function MKn(s,t){Fv(s);const{doc:n}=s,r=Yie(s,"overview"),a=Lb(s,r.kicker,r.headline,r.subhead||null),i=4,l=14,o=(vd-wa*2-l*(i-1))/i,c=96;t.slice(0,8).forEach((d,u)=>{const h=wa+u%i*(o+l),m=a+Math.floor(u/i)*(c+l);T1(n,h,m,o,c,8,Xo,"FD",$w),n.setFillColor(...s.accent),n.rect(h,m,3,c,"F"),n.setFont($u,"bold"),n.setFontSize(15),n.setTextColor(...Lg(s.brand,Xo,.55)),n.text(String(u+1).padStart(2,"0"),h+16,m+30),om(n,d.title,h+16,m+52,o-30,{size:9.5,style:"bold",color:N3,leading:13,maxLines:3})}),Ov(s)}function R6(s,t=5){var n;return(((n=s.options)==null?void 0:n.filter(r=>r.enabled).map(r=>r.label))??vHn[s.key]??[]).slice(0,t)}function t3t(s,t,n){Fv(s,n.dark?s.deep:Kie);const{doc:r}=s,a=Lb(s,n.kicker,n.headline,n.sub,{dark:n.dark}),i=404,l=272,o=!!n.flip,c=o?vd-wa-i:wa,d=o?wa:wa+i+40,u=vd-wa*2-i-40;Pot(s,c,a,i,l,{tint:n.dark?.1:0}),nY(s,t.title,d,a+12);let h=om(r,t.body,d,a+32,u,{size:9.5,color:n.dark?Lg(Xo,s.deep,.2):Ib,leading:15,maxLines:4});const m=R6(t,5);if(m.length&&(h=sY(r,m,d,h+28,u,{font:$u,size:9.5,color:n.dark?Xo:N3,accent:s.accent,gap:7})),n.note&&!n.dark){const f=Math.min(h+14,Gf-120);_ss(s,n.note,d,f,u)}else n.note&&(r.setFont($u,"bold"),r.setFontSize(9.5),r.setTextColor(...Xo),pw(r,.9),om(r,n.note,wa,Gf-78,vd-wa*2,{size:9.5,style:"bold",color:Xo,leading:13,maxLines:1}),pw(r,1));Ov(s,n.dark)}function PKn(s,t){Fv(s);const{doc:n}=s,r=Lb(s,"Launch day","The MLS is the starting point — not the entire plan.","We prepare the details, media, and messaging before the listing goes live."),a=R6(t,4),i=["Price + position","MLS story","Media ready","Go live"],l=Math.max(1,a.length||4),o=16,c=(vd-wa*2-o*(l-1))/l,d=176;(a.length?a:i).forEach((u,h)=>{const m=wa+h*(c+o);T1(n,m,r,c,d,8,Xo,"FD",$w),n.setFont($u,"bold"),n.setFontSize(16),n.setTextColor(...s.accent),n.text(String(h+1),m+16,r+34),n.setFont($u,"bold"),n.setFontSize(7.5),n.setTextColor(...E_),n.text((i[h]||`STEP ${h+1}`).toUpperCase(),m+16,r+56,{charSpace:1.2}),om(n,u,m+16,r+76,c-32,{size:9,color:Ib,leading:13,maxLines:5})}),om(n,t.body,wa,r+d+34,vd-wa*2-120,{size:10,style:"bold",color:s.brand,leading:15,maxLines:2}),Ov(s)}function IKn(s,t){Fv(s);const{doc:n}=s,r=Lb(s,"Maximum visibility","Your listing goes where buyers already search.","MLS syndication helps distribute your property across major real estate destinations."),a=[["Zillow",[0,106,255]],["Realtor.com",[214,40,40]],["Homes.com",[58,61,178]],["Redfin",[200,32,46]],["Trulia",[0,128,116]],["Movoto",[40,44,60]]],i=3,l=16,o=(vd-wa*2-l*(i-1))/i,c=68;a.forEach(([u,h],m)=>{const f=wa+m%i*(o+l),g=r+Math.floor(m/i)*(c+l);T1(n,f,g,o,c,8,Xo,"FD",$w),vss(n,u,h,f+28,g+c/2,20),iy(n,u,f+48,g+c/2+4,o-64,13,{style:"bold",color:h})});const d=r+2*(c+l)+22;om(n,t.body,wa,d,vd-wa*2-140,{size:9.5,color:Ib,leading:14,maxLines:3}),n.setFont($u,"normal"),n.setFontSize(7.5),n.setTextColor(...E_),n.text("Distribution varies by MLS, market, and portal policies.",wa,Gf-62),Ov(s)}function LKn(s,t){Fv(s,vB);const{doc:n,data:r}=s,{line1:a}=bss(r),i=Lb(s,"A home of its own","Your property gets a dedicated online showcase.","One clean destination makes the listing easy to explore, save, and share."),l=404,o=274;T1(n,wa,i,l,o,10,Xo,"FD",$w),T1(n,wa,i,l,22,10,s.deep),n.setFillColor(...s.deep),n.rect(wa,i+12,l,10,"F"),n.setFont($u,"bold"),n.setFontSize(7),n.setTextColor(...Xo);const c=(r.agent.website||`${a}`).replace(/^https?:\/\//,"").toUpperCase();iy(n,c,wa+14,i+15,l-28,7,{style:"bold",color:Xo,charSpace:1}),Pot(s,wa+14,i+36,186,142);const d=wa+214,u=l-228;iy(n,a,d,i+54,u,12,{style:"bold",color:s.brand}),om(n,"Welcome home.",d,i+72,u,{size:9,color:s.accent,leading:12,maxLines:1}),om(n,"Photo gallery, property highlights, video tour, showing inquiry, and easy social sharing — all in one place.",d,i+92,u,{size:8.5,color:Ib,leading:12,maxLines:5}),_ss(s,"Shareable. Trackable. Memorable.",wa+14,i+o-46,l-28);const h=wa+l+40,m=vd-h-wa;nY(s,t.title,h,i+12);let f=om(n,t.body,h,i+32,m,{size:9.5,color:Ib,leading:15,maxLines:5});const g=R6(t,5);g.length&&sY(n,g,h,f+26,m,{font:$u,size:9,color:N3,accent:s.accent,gap:7}),Ov(s)}function RKn(s,t){Fv(s,s.deep);const{doc:n}=s,r=Lb(s,"Beyond the search portals","We turn your listing into social content people want to stop and watch.","Creative is tailored for the platforms — not copied and pasted everywhere.",{dark:!0}),a=[["Facebook",[24,119,242]],["Instagram",[214,41,118]],["YouTube",[255,0,0]],["TikTok",[16,16,16]],["Pinterest",[230,0,35]]],i=72,l=16;a.forEach(([d,u],h)=>{const m=wa+h*(i+l);T1(n,m,r,i,i,12,Xo),vss(n,d,u,m+i/2,r+i/2-4,30),n.setFont($u,"bold"),n.setFontSize(6.5),n.setTextColor(...E_),n.text(d.toUpperCase(),m+i/2,r+i-8,{align:"center",charSpace:.6})});const o=wa+5*(i+l)+14,c=vd-o-wa;nY(s,"The campaign can include",o,r+12),sY(n,R6(t,5),o,r+32,c,{font:$u,size:9,color:Xo,accent:s.accent,gap:7}),om(n,t.body,wa,r+i+44,420,{size:9.5,color:Lg(Xo,s.deep,.2),leading:15,maxLines:4}),om(n,"Every post sends attention back to the property.",wa,Gf-84,460,{size:11,style:"bold",color:Xo,leading:14,maxLines:1}),Ov(s,!0)}function DKn(s,t){Fv(s);const{doc:n}=s,r=Lb(s,"Reach buyers directly","Great marketing does not wait for someone to stumble across the listing.","We activate local relationships and existing audiences to create more opportunities."),a=R6(t,4),i=["Email announcement","Agent-to-agent outreach","Database follow-up","Local community visibility"];let l=r+6;a.forEach((o,c)=>{T1(n,wa,l-14,34,34,8,Lg(s.accent,Xo,.85)),n.setFont($u,"bold"),n.setFontSize(11),n.setTextColor(...s.brand),n.text(String(c+1),wa+17,l+7,{align:"center"});const d=wa+52,u=vd-d-wa-20;n.setFont($u,"bold"),n.setFontSize(8),n.setTextColor(...s.brand),n.text((i[c]||t.title).toUpperCase(),d,l-2,{charSpace:1.2}),om(n,o,d,l+14,u,{size:9.5,color:Ib,leading:14,maxLines:2}),l+=76}),om(n,t.body,wa,Math.min(l+8,Gf-92),vd-wa*2-120,{size:9.5,color:E_,leading:14,maxLines:2}),Ov(s)}function FKn(s,t){Fv(s);const{doc:n}=s,r=Lb(s,"Real-world marketing still matters","Digital reach gets attention. Local presence turns attention into action.","Each tactic is selected for the property, timing, neighborhood, and likely buyer."),a=R6(t,4),i=["Open house","Signage","Neighborhood","Follow-up"],l=2,o=20,c=(vd-wa*2-o)/l,d=112;a.forEach((u,h)=>{const m=wa+h%l*(c+o),f=r+Math.floor(h/l)*(d+o);T1(n,m,f,c,d,8,vB,"FD",$w),n.setFont($u,"bold"),n.setFontSize(7.5),n.setTextColor(...s.brand),n.text((i[h]||t.title).toUpperCase(),m+16,f+24,{charSpace:1.2}),om(n,u,m+16,f+46,c-32,{size:9.5,color:Ib,leading:14,maxLines:3})}),Ov(s)}function OKn(s,t){Fv(s,vB);const{doc:n}=s,r=Lb(s,"You will always know what is happening","A strong launch needs clear communication and thoughtful adjustments.","You receive useful feedback — not a pile of disconnected activity."),a=R6(t,4),i=["Weekly update","Market check","Smart adjustments","Direct access"];let l=r+10;a.forEach((o,c)=>{n.setFont($u,"bold"),n.setFontSize(11),n.setTextColor(...s.accent),n.text(String(c+1).padStart(2,"0"),wa,l),n.setFont($u,"bold"),n.setFontSize(9),n.setTextColor(...s.brand),n.text((i[c]||"").toUpperCase(),wa+48,l,{charSpace:1.2}),om(n,o,wa+250,l-1,vd-wa-250-wa,{size:9.5,color:Ib,leading:13,maxLines:2}),n.setDrawColor(...$w),n.setLineWidth(.5),n.line(wa,l+22,vd-wa,l+22),l+=62}),om(n,"Marketing creates opportunity. Communication helps us act on it.",wa,Math.min(l+18,Gf-84),520,{size:11,style:"bold",color:s.brand,leading:14,maxLines:1}),Ov(s)}function zKn(s){Fv(s,s.deep);const{doc:t,data:n}=s;s.hero&&Wie(t,s.hero,0,0,vd,Gf,{tint:{color:s.deep,amount:.92},darken:.25,dpi:s.dpi});const r=Yie(s,"closing"),a=Lb(s,r.kicker,r.headline,r.subhead||null,{dark:!0,width:520}),i=420;let l=om(t,r.body,wa,a,i,{size:10.5,color:Lg(Xo,s.deep,.18),leading:17});l+=30,sY(t,["Regular written updates for as long as your home is on the market","Showing and online traffic feedback shared as it arrives","Honest pricing conversations backed by current data","Every offer reviewed with you line by line"],wa,l,i,{font:$u,size:9.5,color:Xo,accent:s.accent,gap:8});const o=Mot(n),c=250,d=vd-wa-c,u=a-20,h=o?300:258;T1(t,d,u,c,h,10,Xo),t.setFillColor(...s.accent),t.rect(d,u,c,3,"F"),s.headshot&&(o&&s.coHeadshot?(P7(t,s.headshot,d+c/2-34,u+70,32),P7(t,s.coHeadshot,d+c/2+34,u+70,32)):P7(t,s.headshot,d+c/2,u+70,38)),iy(t,o?`${n.agent.name} + ${o.name}`:n.agent.name,d+c/2,u+(s.headshot?132:68),c-30,16,{style:"bold",color:s.brand,align:"center"});let m=u+(s.headshot?152:90);[n.agent.brokerageName,n.agent.phone,n.agent.email,n.agent.website,n.agent.licenseNumber?`License ${n.agent.licenseNumber}${n.agent.licenseState?` · ${n.agent.licenseState}`:""}`:null].filter(Boolean).slice(0,5).forEach(f=>{iy(t,String(f),d+c/2,m,c-30,8.5,{color:E_,align:"center"}),m+=14}),o?(m+=6,t.setDrawColor(...$w),t.setLineWidth(.5),t.line(d+24,m-8,d+c-24,m-8),iy(t,o.name,d+c/2,m+8,c-30,10,{style:"bold",color:s.brand,align:"center"}),m+=22,[o.title||"Co-listing agent",o.phone,o.email].filter(Boolean).slice(0,3).forEach(f=>{iy(t,String(f),d+c/2,m,c-30,8.5,{color:E_,align:"center"}),m+=13})):s.logo&&Tot(t,s.logo,d+c/2-50,u+h-44,100,28,"left"),t.setFont($u,"bold"),t.setFontSize(9),t.setTextColor(...Xo),pw(t,.9),t.text("LET'S MAKE YOUR HOME THE ONE BUYERS REMEMBER.",wa,Gf-72,{charSpace:1.4}),pw(t,1),Ov(s,!0)}function Iot(s,t){return s.customImages[t.id]||null}function wss(s,t,n,r,a,i){const l=Iot(s,t);l?Wie(s.doc,l,n,r,a,i,{radius:10,dpi:s.dpi}):Pot(s,n,r,a,i)}function BKn(s,t){Fv(s,t.dark?s.deep:Kie);const{doc:n}=s,r=Lb(s,t.kicker||"About",t.headline,t.subhead||null,{dark:t.dark}),a=300,i=t.imageSide!=="left",l=i?vd-wa-a:wa,o=i?wa:wa+a+40,c=vd-wa*2-a-40;wss(s,t,l,r,a,268);const d=(t.body||"").split(/\n{2,}/).filter(Boolean);let u=r+6;d.slice(0,3).forEach(h=>{u=om(n,h,o,u,c,{size:10,color:t.dark?Lg(Xo,s.deep,.2):Ib,leading:16,maxLines:7}),u+=26}),t.bullets.length&&sY(n,t.bullets.slice(0,5),o,Math.min(u,Gf-150),c,{font:$u,size:9.5,color:t.dark?Xo:N3,accent:s.accent,gap:7}),Ov(s,t.dark)}function $Kn(s,t){Fv(s,t.dark?s.deep:vB);const{doc:n}=s,r=Lb(s,t.kicker||"What others are saying",t.headline,t.subhead||null,{dark:t.dark}),a=t.testimonials.filter(m=>{var f;return(f=m.quote)==null?void 0:f.trim()}).slice(0,6),i=a.length<=2?a.length||1:a.length>4?3:2,l=18,o=(vd-wa*2-l*(i-1))/i,c=Math.ceil(a.length/i)||1,d=Gf-72-r,u=c>1?Math.min(150,(d-l*(c-1))/c):Math.min(200,d),h=c>1?i===3?4:3:7;a.forEach((m,f)=>{const g=wa+f%i*(o+l),x=r+Math.floor(f/i)*(u+l);T1(n,g,x,o,u,10,t.dark?Lg(s.deep,Xo,.08):Xo,"FD",$w),n.setFillColor(...s.accent),n.rect(g,x,3,u,"F"),n.setFont(SW,"bold"),n.setFontSize(30),n.setTextColor(...Lg(s.accent,t.dark?s.deep:Xo,.4)),n.text("“",g+18,x+40),om(n,m.quote,g+18,x+56,o-40,{size:9.5,color:t.dark?Lg(Xo,s.deep,.2):Ib,leading:14,maxLines:h}),n.setDrawColor(...s.accent),n.setLineWidth(1.2),n.line(g+18,x+u-32,g+42,x+u-32),n.setFont($u,"bold"),n.setFontSize(8),n.setTextColor(...s.brand);const y=[m.name,m.detail].filter(Boolean).join(" · ");y&&iy(n,y.toUpperCase(),g+18,x+u-16,o-36,8,{style:"bold",color:t.dark?Xo:s.brand,charSpace:1.1})}),t.body&&om(n,t.body,wa,Math.min(r+c*(u+l)+14,Gf-88),vd-wa*2-120,{size:9.5,color:t.dark?Lg(Xo,s.deep,.2):E_,leading:14,maxLines:2}),Ov(s,t.dark)}function UKn(s,t){Fv(s,t.dark?s.deep:Kie);const{doc:n}=s,r=Lb(s,t.kicker||"Track record",t.headline,t.subhead||null,{dark:t.dark}),a=t.stats.filter(i=>{var l,o;return((l=i.value)==null?void 0:l.trim())||((o=i.label)==null?void 0:o.trim())}).slice(0,4);if(a.length){const l=(vd-wa*2-18*(a.length-1))/a.length,o=150;a.forEach((c,d)=>{const u=wa+d*(l+18);T1(n,u,r,l,o,10,t.dark?Lg(s.deep,Xo,.1):Xo,"FD",$w),n.setFillColor(...s.accent),n.rect(u,r,l,3,"F"),iy(n,c.value||"—",u+l/2,r+76,l-28,34,{style:"bold",color:t.dark?Xo:s.brand,align:"center"}),om(n,c.label||"",u+20,r+100,l-40,{size:9,color:t.dark?Lg(Xo,s.deep,.3):E_,leading:12,maxLines:2,align:"center"})}),t.body&&om(n,t.body,wa,r+o+40,vd-wa*2-140,{size:10,color:t.dark?Lg(Xo,s.deep,.2):Ib,leading:15,maxLines:3})}else t.body&&om(n,t.body,wa,r,vd-wa*2-140,{size:10.5,color:t.dark?Xo:Ib,leading:16});Ov(s,t.dark)}function qKn(s,t){Fv(s,t.dark?s.deep:Xo);const{doc:n}=s,r=Lb(s,t.kicker||"Our promise",t.headline,t.subhead||null,{dark:t.dark}),i=!!Iot(s,t)||!!s.hero,l=i?vd-wa*2-280:vd-wa*2-140;let o=r;t.body&&(o=om(n,t.body,wa,o,l,{size:10,color:t.dark?Lg(Xo,s.deep,.2):Ib,leading:15,maxLines:3})+28),t.bullets.filter(d=>d==null?void 0:d.trim()).slice(0,7).forEach(d=>{T1(n,wa,o-9,14,14,4,s.accent),n.setFont($u,"bold"),n.setFontSize(8),n.setTextColor(...Xo),n.text("✓",wa+7,o+1,{align:"center"}),o=om(n,d,wa+26,o,l-26,{size:10,color:t.dark?Xo:N3,leading:14,maxLines:2})+22}),i&&wss(s,t,vd-wa-240,r,240,250),Ov(s,t.dark)}function VKn(s,t){Fv(s,s.deep);const{doc:n}=s,r=Iot(s,t)||s.hero;r&&Wie(n,r,0,0,vd,Gf,{tint:{color:s.deep,amount:.82},darken:.28,dpi:s.dpi}),nY(s,t.kicker||"Our approach",wa,Gf/2-84),n.setFont($u,"bold"),n.setFontSize(30),n.setTextColor(...Xo);const a=n.splitTextToSize(t.headline||"",vd-wa*2-140).slice(0,4);a.forEach((i,l)=>n.text(i,wa,Gf/2-44+l*38)),t.body&&om(n,t.body,wa,Gf/2+a.length*38-24,480,{size:10.5,color:Lg(Xo,s.deep,.2),leading:16,maxLines:4}),Ov(s,!0)}function s3t(s,t){switch(t.layout){case"testimonials":return $Kn(s,t);case"stats":return UKn(s,t);case"checklist":return qKn(s,t);case"statement":return VKn(s,t);case"story":default:return BKn(s,t)}}async function HKn(s,t,n){var I,P,R,D;const r=n==="print"?4:2,a=n==="print"?2600:1600,i=hKn((I=t.pages)==null?void 0:I.theme);Kie=Y$(i.paper),vB=Y$(i.paperCool),$w=Y$(i.softLine),Ib=Y$(i.bodyInk),SW=i.headFont;const l=Y$((i.useAgentColors?t.agent.brandColor:i.brand)||i.brand||"#0E1B2C"),o=Y$((i.useAgentColors?t.agent.accentColor:i.accent)||i.accent||"#B8965A"),c=Lg(l,[0,0,0],i.id==="luxury"?.35:.2),d=(P=t.coAgent)!=null&&P.enabled&&((R=t.coAgent.name)!=null&&R.trim())?t.coAgent:null,u=(t.customPages||[]).filter(O=>O.enabled).sort((O,U)=>O.order-U.order),[h,m,f,g,...x]=await Promise.all([hX(t.property.photoUrl,a),hX(t.agent.headshotUrl,700),hX(t.agent.brokerageLogoUrl,800),hX((d==null?void 0:d.headshotUrl)||null,700),...u.map(O=>hX(O.imageUrl||null,a))]),y={};u.forEach((O,U)=>{y[O.id]=x[U]??null}),pKn(t.focal);const v={doc:s,data:t,brand:l,accent:o,deep:c,hero:h,headshot:m,coHeadshot:g,logo:f,customImages:y,dpi:r,pageNo:1},b=new Set(((D=t.pages)==null?void 0:D.hidden)||[]),w=[...t.services].filter(O=>O.enabled).sort((O,U)=>O.order-U.order),S=O=>w.find(U=>U.key===O);AKn(v),b.has("welcome")||EKn(v),b.has("agent")||TKn(v),u.filter(O=>O.placement!=="end").forEach(O=>s3t(v,O)),b.has("overview")||MKn(v,w);const C=new Set,E=(O,U)=>{const W=S(O);W&&(C.add(O),U(W))};E("photography",O=>t3t(v,O,{kicker:"First impressions",headline:"Buyers will see your home at its absolute best.",sub:"Strong presentation earns the click before a showing is ever scheduled.",note:"Every image has one job: earn the next click."})),E("video",O=>t3t(v,O,{kicker:"More ways to experience it",headline:"Photos introduce the home. Video helps buyers feel it.",sub:"A cinematic walk-through gives the listing movement, emotion, and shareability.",note:"The right format for every screen.",dark:!0,flip:!0})),E("mls",O=>PKn(v,O)),E("syndication",O=>IKn(v,O)),E("website",O=>LKn(v,O)),E("social",O=>RKn(v,O)),E("email",O=>DKn(v,O)),E("openhouse",O=>FKn(v,O)),E("communication",O=>OKn(v,O)),w.filter(O=>!C.has(O.key)).forEach(O=>{Fv(v);const U=Lb(v,"Marketing",O.title,null),W=R6(O,6),V=om(s,O.body,wa,U,vd-wa*2-160,{size:10.5,color:Ib,leading:16});W.length&&sY(s,W,wa,V+30,vd-wa*2-160,{font:$u,size:9.5,color:N3,accent:v.accent,gap:8}),Ov(v)}),u.filter(O=>O.placement==="end").forEach(O=>s3t(v,O)),b.has("closing")||zKn(v)}const n3t=[{id:"signature",name:"Signature",description:"Editorial full-bleed cover with a brand-tinted photo motif throughout.",render:HKn}];function GKn(s){return n3t.find(t=>t.id===s)||n3t[0]}async function jss(s,t,n="screen"){const r=new Go({unit:"pt",format:"letter",orientation:"landscape",compress:!0});return await GKn(t).render(r,s,n),r.setProperties({title:s.title||`${s.property.addressLine1} — Listing Presentation`,subject:`Listing presentation for ${s.property.addressLine1}`,author:s.agent.name,creator:"LevelUp Hub — Listing Presentation Studio"}),r}function WKn(s){return`${(s.property.addressLine1||s.title||"listing-presentation").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")||"listing-presentation"}-presentation.pdf`}const KKn={name:"Your Name",headshotUrl:null,brokerageName:null,brokerageLogoUrl:null,licenseNumber:null,licenseState:null,phone:null,email:null,website:null,brandColor:"#2a4c64",accentColor:"#B8965A",tagline:null};async function pPe(s){if(!s)return null;const{data:t}=await q.storage.from(UL).createSignedUrl(s,3600);return(t==null?void 0:t.signedUrl)??null}function gPe(s,t,n){const r=s.agent_snapshot||{},a={...KKn,...t||{},...Object.fromEntries(Object.entries(r).filter(([,i])=>i!=null&&i!==""))};return{title:s.title,property:{addressLine1:s.property_address_line1||"",city:s.city||"",state:s.state||"",postalCode:s.postal_code||"",listPrice:s.list_price!=null?Number(s.list_price):null,beds:s.beds!=null?Number(s.beds):null,baths:s.baths!=null?Number(s.baths):null,sqft:s.sqft!=null?Number(s.sqft):null,photoUrl:n??null},agent:a,coAgent:Nts(s.co_agent),customPages:Sts(s.custom_pages),services:lZe(s.services),pages:s.page_settings&&Object.keys(s.page_settings).length?s.page_settings:iZe,focal:s.photo_focal||oZe}}async function Nss(s,t){if(s.property.photoUrl||!t)return s;const n=await pPe(t);return{...s,property:{...s.property,photoUrl:n}}}async function kss(s,t,n){const r=await Nss(s,n);return(await jss(r,t,"screen")).output("blob")}async function Sss(s,t,n="print",r){const a=await Nss(s,r),l=(await jss(a,t,n)).output("blob"),o=URL.createObjectURL(l),c=document.createElement("a");return c.href=o,c.download=WKn(a),document.body.appendChild(c),c.click(),c.remove(),setTimeout(()=>URL.revokeObjectURL(o),4e3),l}async function Css(s,t,n){const r=`${s}/${t}/presentation.pdf`,{error:a}=await q.storage.from(UL).upload(r,n,{upsert:!0,contentType:"application/pdf"});return a?null:(await q.from("listing_presentations").update({pdf_path:r,last_generated_at:new Date().toISOString(),status:"final"}).eq("id",t),r)}async function Ass(s,t=2400){const n=URL.createObjectURL(s);try{const r=await new Promise((c,d)=>{const u=new Image;u.onload=()=>c(u),u.onerror=d,u.src=n});if(r.naturalWidth<=t&&s.size<3e6)return s;const a=Math.min(1,t/r.naturalWidth),i=document.createElement("canvas");return i.width=Math.round(r.naturalWidth*a),i.height=Math.round(r.naturalHeight*a),i.getContext("2d").drawImage(r,0,0,i.width,i.height),await new Promise(c=>i.toBlob(c,"image/jpeg",.9))||s}catch{return s}finally{URL.revokeObjectURL(n)}}async function YKn(s,t,n){const r=await Ass(n),a=`${s}/${t}/photo.jpg`,{error:i}=await q.storage.from(UL).upload(a,r,{upsert:!0,contentType:"image/jpeg"});if(i)throw i;return a}async function ZKn(s,t,n="presentation",r=1800){const a=await Ass(t,r),i=`${s}/${n}-${Date.now()}.jpg`,{error:l}=await q.storage.from("avatars").upload(i,a,{upsert:!0,contentType:"image/jpeg"});if(l)throw l;const{data:o}=q.storage.from("avatars").getPublicUrl(i);return o.publicUrl}function XKn({path:s,alt:t}){const[n,r]=j.useState(null),[a,i]=j.useState(!1);return j.useEffect(()=>{let l=!0;if(r(null),i(!1),!!s)return xHn(s,3600).then(o=>{l&&r(o)}),()=>{l=!1}},[s]),n&&!a?e.jsx("div",{className:"h-32 w-full overflow-hidden bg-muted",children:e.jsx("img",{src:n,alt:t,loading:"lazy",onError:()=>i(!0),className:"h-32 w-full object-cover transition-transform duration-300 group-hover:scale-[1.03]"})}):e.jsx("div",{className:"flex h-32 items-center justify-center bg-gradient-to-br from-primary/15 to-accent/10",children:e.jsx(va,{className:"h-8 w-8 text-primary/50"})})}const r3t=60*60*24*30;function Ess({open:s,onOpenChange:t,row:n,brand:r,photoUrl:a}){const{user:i}=vs(),[l,o]=j.useState([]),[c,d]=j.useState(""),[u,h]=j.useState([]),[m,f]=j.useState(!1),[g,x]=j.useState(""),[y,v]=j.useState(""),[b,w]=j.useState(!1),S=j.useRef(null),C=(n==null?void 0:n.property_address_line1)||(n==null?void 0:n.title)||"your home";j.useEffect(()=>{!s||!n||(o([]),d(""),h([]),x(`Your listing presentation for ${C}`),v(`Hi {{first_name}}, Thank you for the opportunity to talk about selling ${C}. I put together a presentation that walks through my pricing strategy, marketing plan, and what to expect at every step. Take a look and let me know what questions come up — I'm happy to walk through it together.`))},[s,n==null?void 0:n.id]),j.useEffect(()=>{S.current&&clearTimeout(S.current);const D=c.trim();if(!i||D.length<2||/\S+@\S+\.\S+/.test(D)){h([]);return}return S.current=setTimeout(async()=>{f(!0);const O=`%${D}%`,U=q,{data:W}=await U.from("innercircle_contacts").select("id, first_name, last_name, email").eq("owner_user_id",i.id).not("email","is",null).or(`first_name.ilike.${O},last_name.ilike.${O},email.ilike.${O}`).order("first_name",{ascending:!0}).limit(6);f(!1),h(W||[])},200),()=>{S.current&&clearTimeout(S.current)}},[c,i==null?void 0:i.id]);const E=D=>{D.email&&(o(O=>O.some(U=>U.email.toLowerCase()===D.email.toLowerCase())?O:[...O,D]),d(""),h([]))},I=()=>{const D=c.trim();if(!/\S+@\S+\.\S+/.test(D)){re.error("Enter a valid email address");return}E({email:D})},P=j.useMemo(()=>!!n&&l.length>0&&g.trim().length>0&&!b,[n,l,g,b]),R=async()=>{if(!(!n||!i)){if(!n.property_photo_path){re.error("Add the primary exterior photo before emailing the presentation");return}w(!0);try{const D=await kss(gPe(n,r,a??null),n.template_id,n.property_photo_path),O=await Css(i.id,n.id,D)||n.pdf_path;if(!O)throw new Error("Could not save the presentation PDF");const{data:U,error:W}=await q.storage.from(UL).createSignedUrl(O,r3t);if(W||!(U!=null&&U.signedUrl))throw new Error("Could not create a share link");const V=await pPe(n.property_photo_path).then(ae=>ae).catch(()=>null),{data:G}=await q.storage.from(UL).createSignedUrl(n.property_photo_path,r3t),{data:Y,error:X}=await q.functions.invoke("listing-presentation-email",{body:{presentation_id:n.id,subject:g,message:y,pdf_url:U.signedUrl,photo_url:(G==null?void 0:G.signedUrl)||V,recipients:l}});if(X)throw X;if(!(Y!=null&&Y.success))throw new Error((Y==null?void 0:Y.error)||"Could not send the email");re.success(Y.failed?`Sent to ${Y.sent} · ${Y.failed} failed`:`Presentation emailed to ${Y.sent} ${Y.sent===1?"contact":"contacts"}`),t(!1)}catch(D){re.error((D==null?void 0:D.message)||"Could not send the presentation")}finally{w(!1)}}};return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Os,{className:"max-w-lg",children:[e.jsxs(Us,{children:[e.jsxs(Bs,{className:"flex items-center gap-2",children:[e.jsx(mn,{className:"h-4 w-4"})," Email this presentation"]}),e.jsxs(Ir,{children:["Sends a branded email with a secure link to the PDF. Use ",e.jsx("code",{children:"{{first_name}}"})," to personalize."]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"To"}),l.length>0&&e.jsx("div",{className:"flex flex-wrap gap-1.5",children:l.map(D=>e.jsxs(Be,{variant:"secondary",className:"gap-1 py-1",children:[[D.first_name,D.last_name].filter(Boolean).join(" ")||D.email,e.jsx("button",{type:"button",onClick:()=>o(O=>O.filter(U=>U.email!==D.email)),"aria-label":`Remove ${D.email}`,children:e.jsx(gr,{className:"h-3 w-3"})})]},D.email))}),e.jsxs("div",{className:"relative",children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsx(pe,{value:c,onChange:D=>d(D.target.value),onKeyDown:D=>{D.key==="Enter"&&(D.preventDefault(),I())},placeholder:"Search contacts or type an email"}),e.jsx($,{type:"button",variant:"outline",size:"icon",onClick:I,children:e.jsx(dn,{className:"h-4 w-4"})})]}),(u.length>0||m)&&e.jsxs("div",{className:"absolute z-50 mt-1 w-full overflow-hidden rounded-md border bg-popover shadow-lg",children:[m&&e.jsxs("div",{className:"flex items-center gap-2 p-3 text-sm text-muted-foreground",children:[e.jsx(kt,{className:"h-3 w-3 animate-spin"})," Searching…"]}),u.map(D=>e.jsxs("button",{type:"button",className:"flex w-full items-center gap-2 px-3 py-2 text-left text-sm hover:bg-accent",onClick:()=>E({email:D.email,first_name:D.first_name,last_name:D.last_name,contact_id:D.id}),children:[e.jsx(sl,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"truncate",children:[D.first_name,D.last_name].filter(Boolean).join(" ")||D.email}),e.jsx("span",{className:"ml-auto truncate text-xs text-muted-foreground",children:D.email})]},D.id))]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"pres-subject",children:"Subject"}),e.jsx(pe,{id:"pres-subject",value:g,onChange:D=>x(D.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"pres-message",children:"Message"}),e.jsx(Rs,{id:"pres-message",rows:7,value:y,onChange:D=>v(D.target.value)})]})]}),e.jsxs(Ar,{children:[e.jsx($,{variant:"outline",onClick:()=>t(!1),disabled:b,children:"Cancel"}),e.jsxs($,{onClick:R,disabled:!P,className:"gap-2",children:[b?e.jsx(kt,{className:"h-4 w-4 animate-spin"}):e.jsx(Yr,{className:"h-4 w-4"}),b?"Sending…":`Send${l.length?` (${l.length})`:""}`]})]})]})})}const QKn=()=>{const s=Qn(),{presentations:t,isLoading:n,create:r,duplicate:a,remove:i,update:l}=_ts(),{data:o}=pHn(),{data:c}=A6e(),{savedTemplates:d,remove:u}=bts(),[h,m]=j.useState(null),[f,g]=j.useState(""),[x,y]=j.useState(null),[v,b]=j.useState(null),[w,S]=j.useState(null),C=j.useMemo(()=>{var R,D;return(D=(R=o==null?void 0:o[0])==null?void 0:R.default_services)!=null&&D.length?o[0].default_services:dPe},[o]),E=async()=>{var D;if(!c)return;const R=await r.mutateAsync({title:"Untitled Presentation",template_id:((D=o==null?void 0:o[0])==null?void 0:D.slug)||"signature",agent_snapshot:c,services:C});s(`/apps/listing-presentation-studio/${R.id}`)},I=async R=>{var O;const D=await r.mutateAsync({title:`${R.name} — new listing`,template_id:R.template_id||"signature",agent_snapshot:R.agent_snapshot,co_agent:R.co_agent,custom_pages:R.custom_pages,services:(O=R.services)!=null&&O.length?R.services:C,page_settings:R.page_settings});s(`/apps/listing-presentation-studio/${D.id}`)},P=async R=>{try{b(R.id),await Sss(gPe(R,c),R.template_id,"print",R.property_photo_path)}catch(D){re.error((D==null?void 0:D.message)||"Could not build the PDF")}finally{b(null)}};return e.jsxs(Vs,{children:[e.jsxs("div",{className:"space-y-8",children:[e.jsx("div",{className:"relative overflow-hidden rounded-2xl border bg-gradient-to-br from-primary/10 via-background to-accent/10 p-8",children:e.jsxs("div",{className:"flex flex-col gap-6 md:flex-row md:items-center md:justify-between",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsxs(Be,{variant:"secondary",className:"gap-1",children:[e.jsx(Nn,{className:"h-3 w-3"})," Listing Presentation Studio"]}),e.jsx("h1",{className:"text-3xl font-semibold tracking-tight",children:"Win the listing before you walk in"}),e.jsx("p",{className:"max-w-2xl text-sm text-muted-foreground",children:"Enter an address, drop in one exterior photo, and get a beautiful 12-page seller presentation branded with your profile — ready to present or print in under two minutes."})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs($,{size:"lg",onClick:E,disabled:r.isPending||!c,className:"gap-2",children:[r.isPending?e.jsx(kt,{className:"h-4 w-4 animate-spin"}):e.jsx(dn,{className:"h-4 w-4"}),"New presentation"]}),d.length>0&&e.jsxs(Uu,{children:[e.jsx(qu,{asChild:!0,children:e.jsxs($,{size:"lg",variant:"outline",className:"gap-2",children:[e.jsx(M0,{className:"h-4 w-4"})," From template",e.jsx(Tl,{className:"h-4 w-4"})]})}),e.jsx(Eu,{align:"end",className:"w-64",children:d.map(R=>e.jsxs(ja,{onClick:()=>I(R),children:[e.jsx(M0,{className:"mr-2 h-4 w-4 shrink-0"}),e.jsx("span",{className:"truncate",children:R.name})]},R.id))})]})]})]})}),d.length>0&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-lg font-semibold tracking-tight",children:"Your saved templates"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Start a new presentation from a saved setup — just add the address and photo."})]}),e.jsx("div",{className:"grid gap-3 sm:grid-cols-2 lg:grid-cols-3",children:d.map(R=>e.jsx(Ne,{className:"transition-shadow hover:shadow-md",children:e.jsxs(Ie,{className:"flex items-start justify-between gap-3 p-4",children:[e.jsxs("button",{className:"min-w-0 flex-1 text-left",onClick:()=>I(R),disabled:r.isPending,children:[e.jsxs("p",{className:"flex items-center gap-2 truncate font-medium",children:[e.jsx(M0,{className:"h-4 w-4 shrink-0 text-muted-foreground"}),R.name]}),e.jsx("p",{className:"mt-1 line-clamp-2 text-xs text-muted-foreground",children:R.description||"Branding, theme, page wording, and marketing plan saved."})]}),e.jsx($,{variant:"ghost",size:"icon",className:"h-8 w-8 shrink-0 text-muted-foreground hover:text-destructive",onClick:()=>u.mutate(R.id),children:e.jsx(Wn,{className:"h-4 w-4"})})]})},R.id))})]}),n?e.jsx("div",{className:"grid gap-5 sm:grid-cols-2 lg:grid-cols-3",children:[0,1,2].map(R=>e.jsx(yn,{className:"h-56 rounded-xl"},R))}):t.length===0?e.jsx(Ne,{className:"border-dashed",children:e.jsxs(Ie,{className:"flex flex-col items-center gap-4 py-16 text-center",children:[e.jsx("div",{className:"flex h-14 w-14 items-center justify-center rounded-full bg-muted",children:e.jsx(Jr,{className:"h-7 w-7 text-muted-foreground"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:"No presentations yet"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Create your first seller presentation — it takes about two minutes."})]}),e.jsxs($,{onClick:E,disabled:r.isPending||!c,className:"gap-2",children:[e.jsx(dn,{className:"h-4 w-4"})," New presentation"]})]})}):e.jsx("div",{className:"grid gap-5 sm:grid-cols-2 lg:grid-cols-3",children:t.map(R=>{const D=R.property_address_line1||"No address yet",O=[R.city,R.state].filter(Boolean).join(", ");return e.jsxs(Ne,{className:"group overflow-hidden transition-shadow hover:shadow-lg",children:[e.jsx("button",{className:"block w-full text-left",onClick:()=>s(`/apps/listing-presentation-studio/${R.id}`),children:e.jsx(XKn,{path:R.property_photo_path,alt:`${D} property photo`})}),e.jsxs(Ie,{className:"space-y-3 p-4",children:[e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"truncate font-medium",children:R.title}),e.jsxs("p",{className:"truncate text-xs text-muted-foreground",children:[D,O?` · ${O}`:""]})]}),e.jsxs(Uu,{children:[e.jsx(qu,{asChild:!0,children:e.jsx($,{variant:"ghost",size:"icon",className:"h-8 w-8 shrink-0",children:e.jsx(ty,{className:"h-4 w-4"})})}),e.jsxs(Eu,{align:"end",children:[e.jsxs(ja,{onClick:()=>s(`/apps/listing-presentation-studio/${R.id}`),children:[e.jsx(gi,{className:"mr-2 h-4 w-4"})," Open"]}),e.jsxs(ja,{onClick:()=>{m(R),g(R.title)},children:[e.jsx(Jr,{className:"mr-2 h-4 w-4"})," Rename"]}),e.jsxs(ja,{onClick:()=>a.mutate(R),children:[e.jsx(Ha,{className:"mr-2 h-4 w-4"})," Duplicate"]}),e.jsxs(ja,{onClick:()=>P(R),children:[e.jsx(di,{className:"mr-2 h-4 w-4"})," Download PDF"]}),e.jsxs(ja,{onClick:()=>S(R),children:[e.jsx(mn,{className:"mr-2 h-4 w-4"})," Email to a contact"]}),e.jsx(R0,{}),e.jsxs(ja,{className:"text-destructive",onClick:()=>y(R),children:[e.jsx(Wn,{className:"mr-2 h-4 w-4"})," Delete"]})]})]})]}),e.jsxs("div",{className:"flex items-center justify-between text-xs text-muted-foreground",children:[e.jsxs("span",{children:["Updated ",en(new Date(R.updated_at),"MMM d, yyyy")]}),R.last_generated_at?e.jsx(Be,{variant:"secondary",className:"text-[10px]",children:"PDF ready"}):e.jsx(Be,{variant:"outline",className:"text-[10px]",children:"Draft"})]}),e.jsxs($,{variant:"outline",size:"sm",className:"w-full gap-2",disabled:v===R.id,onClick:()=>P(R),children:[v===R.id?e.jsx(kt,{className:"h-4 w-4 animate-spin"}):e.jsx(di,{className:"h-4 w-4"}),"Download PDF"]})]})]},R.id)})})]}),e.jsx(zs,{open:!!h,onOpenChange:R=>!R&&m(null),children:e.jsxs(Os,{className:"sm:max-w-md",children:[e.jsx(Us,{children:e.jsx(Bs,{children:"Rename presentation"})}),e.jsx(pe,{value:f,onChange:R=>g(R.target.value),autoFocus:!0}),e.jsxs(Ar,{children:[e.jsx($,{variant:"outline",onClick:()=>m(null),children:"Cancel"}),e.jsx($,{onClick:async()=>{h&&(await l.mutateAsync({id:h.id,title:f.trim()||"Untitled Presentation"}),m(null),re.success("Renamed"))},children:"Save"})]})]})}),e.jsx(kc,{open:!!x,onOpenChange:R=>!R&&y(null),children:e.jsxs(cc,{children:[e.jsxs(dc,{children:[e.jsx(hc,{children:"Delete this presentation?"}),e.jsx(mc,{children:"This permanently removes the presentation, its property photo, and the generated PDF."})]}),e.jsxs(uc,{children:[e.jsx(fc,{children:"Cancel"}),e.jsx(tc,{className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",onClick:()=>{x&&i.mutate(x),y(null)},children:"Delete"})]})]})}),e.jsx(Ess,{open:!!w,onOpenChange:R=>!R&&S(null),row:w,brand:c})]})};var ite={};ite.d=(s,t)=>{for(var n in t)ite.o(t,n)&&!ite.o(s,n)&&Object.defineProperty(s,n,{enumerable:!0,get:t[n]})};ite.o=(s,t)=>Object.prototype.hasOwnProperty.call(s,t);var ud=globalThis.pdfjsLib={};ite.d(ud,{AbortException:()=>x9,AnnotationEditorLayer:()=>MXe,AnnotationEditorParamsType:()=>nd,AnnotationEditorType:()=>Od,AnnotationEditorUIManager:()=>_B,AnnotationLayer:()=>ZZn,AnnotationMode:()=>PP,ColorPicker:()=>bPe,DOMSVGFactory:()=>Hot,DrawLayer:()=>RXe,FeatureTest:()=>T_,GlobalWorkerOptions:()=>pE,ImageKind:()=>O3e,InvalidPDFException:()=>Mss,MissingPDFException:()=>g9,OPS:()=>xS,OutputScale:()=>kZe,PDFDataRangeTransport:()=>Cns,PDFDateString:()=>Oot,PDFWorker:()=>VV,PasswordResponses:()=>sYn,PermissionFlag:()=>tYn,PixelsPerInch:()=>VL,RenderingCancelledException:()=>Dot,TextLayer:()=>wne,UnexpectedResponseException:()=>$De,Util:()=>ol,VerbosityLevel:()=>ODe,XfaLayer:()=>Ens,build:()=>TZn,createValidAbsoluteUrl:()=>iYn,fetchData:()=>qDe,getDocument:()=>_Zn,getFilenameFromUrl:()=>pYn,getPdfFilenameFromUrl:()=>gYn,getXfaPageViewport:()=>xYn,isDataScheme:()=>VDe,isPdfFile:()=>Fot,noContextMenu:()=>yk,normalizeUnicode:()=>hYn,setLayerDimensions:()=>bB,shadow:()=>th,version:()=>EZn});const y1=typeof process=="object"&&process+""=="[object process]"&&!process.versions.nw&&!(process.versions.electron&&process.type&&process.type!=="browser"),Tss=[1,0,0,1,0,0],_Ze=[.001,0,0,.001,0,0],JKn=1e7,R$e=1.35,qj={ANY:1,DISPLAY:2,PRINT:4,ANNOTATIONS_FORMS:16,ANNOTATIONS_STORAGE:32,ANNOTATIONS_DISABLE:64,IS_EDITING:128,OPLIST:256},PP={DISABLE:0,ENABLE:1,ENABLE_FORMS:2,ENABLE_STORAGE:3},eYn="pdfjs_internal_editor_",Od={DISABLE:-1,NONE:0,FREETEXT:3,HIGHLIGHT:9,STAMP:13,INK:15},nd={RESIZE:1,CREATE:2,FREETEXT_SIZE:11,FREETEXT_COLOR:12,FREETEXT_OPACITY:13,INK_COLOR:21,INK_THICKNESS:22,INK_OPACITY:23,HIGHLIGHT_COLOR:31,HIGHLIGHT_DEFAULT_COLOR:32,HIGHLIGHT_THICKNESS:33,HIGHLIGHT_FREE:34,HIGHLIGHT_SHOW_ALL:35},tYn={PRINT:4,MODIFY_CONTENTS:8,COPY:16,MODIFY_ANNOTATIONS:32,FILL_INTERACTIVE_FORMS:256,COPY_FOR_ACCESSIBILITY:512,ASSEMBLE:1024,PRINT_HIGH_QUALITY:2048},s1={FILL:0,STROKE:1,FILL_STROKE:2,INVISIBLE:3,FILL_STROKE_MASK:3,ADD_TO_PATH_FLAG:4},O3e={GRAYSCALE_1BPP:1,RGB_24BPP:2,RGBA_32BPP:3},i0={TEXT:1,LINK:2,FREETEXT:3,LINE:4,SQUARE:5,CIRCLE:6,POLYGON:7,POLYLINE:8,HIGHLIGHT:9,UNDERLINE:10,SQUIGGLY:11,STRIKEOUT:12,STAMP:13,CARET:14,INK:15,POPUP:16,FILEATTACHMENT:17,WIDGET:20},mX={SOLID:1,DASHED:2,BEVELED:3,INSET:4,UNDERLINE:5},ODe={ERRORS:0,WARNINGS:1,INFOS:5},xS={dependency:1,setLineWidth:2,setLineCap:3,setLineJoin:4,setMiterLimit:5,setDash:6,setRenderingIntent:7,setFlatness:8,setGState:9,save:10,restore:11,transform:12,moveTo:13,lineTo:14,curveTo:15,curveTo2:16,curveTo3:17,closePath:18,rectangle:19,stroke:20,closeStroke:21,fill:22,eoFill:23,fillStroke:24,eoFillStroke:25,closeFillStroke:26,closeEOFillStroke:27,endPath:28,clip:29,eoClip:30,beginText:31,endText:32,setCharSpacing:33,setWordSpacing:34,setHScale:35,setLeading:36,setFont:37,setTextRenderingMode:38,setTextRise:39,moveText:40,setLeadingMoveText:41,setTextMatrix:42,nextLine:43,showText:44,showSpacedText:45,nextLineShowText:46,nextLineSetSpacingShowText:47,setCharWidth:48,setCharWidthAndBounds:49,setStrokeColorSpace:50,setFillColorSpace:51,setStrokeColor:52,setStrokeColorN:53,setFillColor:54,setFillColorN:55,setStrokeGray:56,setFillGray:57,setStrokeRGBColor:58,setFillRGBColor:59,setStrokeCMYKColor:60,setFillCMYKColor:61,shadingFill:62,beginInlineImage:63,beginImageData:64,endInlineImage:65,paintXObject:66,markPoint:67,markPointProps:68,beginMarkedContent:69,beginMarkedContentProps:70,endMarkedContent:71,beginCompat:72,endCompat:73,paintFormXObjectBegin:74,paintFormXObjectEnd:75,beginGroup:76,endGroup:77,beginAnnotation:80,endAnnotation:81,paintImageMaskXObject:83,paintImageMaskXObjectGroup:84,paintImageXObject:85,paintInlineImageXObject:86,paintInlineImageXObjectGroup:87,paintImageXObjectRepeat:88,paintImageMaskXObjectRepeat:89,paintSolidColorImageMask:90,constructPath:91,setStrokeTransparent:92,setFillTransparent:93},sYn={NEED_PASSWORD:1,INCORRECT_PASSWORD:2};let zDe=ODe.WARNINGS;function nYn(s){Number.isInteger(s)&&(zDe=s)}function rYn(){return zDe}function BDe(s){zDe>=ODe.INFOS&&console.log(`Info: ${s}`)}function nu(s){zDe>=ODe.WARNINGS&&console.log(`Warning: ${s}`)}function kp(s){throw new Error(s)}function j0(s,t){s||kp(t)}function aYn(s){switch(s==null?void 0:s.protocol){case"http:":case"https:":case"ftp:":case"mailto:":case"tel:":return!0;default:return!1}}function iYn(s,t=null,n=null){if(!s)return null;try{if(n&&typeof s=="string"){if(n.addDefaultProtocol&&s.startsWith("www.")){const a=s.match(/\./g);(a==null?void 0:a.length)>=2&&(s=`http://${s}`)}if(n.tryConvertEncoding)try{s=uYn(s)}catch{}}const r=t?new URL(s,t):new URL(s);if(aYn(r))return r}catch{}return null}function th(s,t,n,r=!1){return Object.defineProperty(s,t,{value:n,enumerable:!r,configurable:!0,writable:!1}),n}const D6=function(){function t(n,r){this.message=n,this.name=r}return t.prototype=new Error,t.constructor=t,t}();class wZe extends D6{constructor(t,n){super(t,"PasswordException"),this.code=n}}class jZe extends D6{constructor(t,n){super(t,"UnknownErrorException"),this.details=n}}class Mss extends D6{constructor(t){super(t,"InvalidPDFException")}}class g9 extends D6{constructor(t){super(t,"MissingPDFException")}}class $De extends D6{constructor(t,n){super(t,"UnexpectedResponseException"),this.status=n}}class oYn extends D6{constructor(t){super(t,"FormatError")}}class x9 extends D6{constructor(t){super(t,"AbortException")}}function Pss(s){(typeof s!="object"||(s==null?void 0:s.length)===void 0)&&kp("Invalid argument for bytesToString");const t=s.length,n=8192;if(t>24&255,s>>16&255,s>>8&255,s&255)}function Lot(s){const t=Object.create(null);for(const[n,r]of s)t[n]=r;return t}function cYn(){const s=new Uint8Array(4);return s[0]=1,new Uint32Array(s.buffer,0,1)[0]===1}function dYn(){try{return new Function(""),!0}catch{return!1}}class T_{static get isLittleEndian(){return th(this,"isLittleEndian",cYn())}static get isEvalSupported(){return th(this,"isEvalSupported",dYn())}static get isOffscreenCanvasSupported(){return th(this,"isOffscreenCanvasSupported",typeof OffscreenCanvas<"u")}static get platform(){return typeof navigator<"u"&&typeof(navigator==null?void 0:navigator.platform)=="string"?th(this,"platform",{isMac:navigator.platform.includes("Mac"),isWindows:navigator.platform.includes("Win"),isFirefox:typeof(navigator==null?void 0:navigator.userAgent)=="string"&&navigator.userAgent.includes("Firefox")}):th(this,"platform",{isMac:!1,isWindows:!1,isFirefox:!1})}static get isCSSRoundSupported(){var t,n;return th(this,"isCSSRoundSupported",(n=(t=globalThis.CSS)==null?void 0:t.supports)==null?void 0:n.call(t,"width: round(1.5px, 1px)"))}}const D$e=Array.from(Array(256).keys(),s=>s.toString(16).padStart(2,"0"));var rT,z3e,NZe;class ol{static makeHexColor(t,n,r){return`#${D$e[t]}${D$e[n]}${D$e[r]}`}static scaleMinMax(t,n){let r;t[0]?(t[0]<0&&(r=n[0],n[0]=n[2],n[2]=r),n[0]*=t[0],n[2]*=t[0],t[3]<0&&(r=n[1],n[1]=n[3],n[3]=r),n[1]*=t[3],n[3]*=t[3]):(r=n[0],n[0]=n[1],n[1]=r,r=n[2],n[2]=n[3],n[3]=r,t[1]<0&&(r=n[1],n[1]=n[3],n[3]=r),n[1]*=t[1],n[3]*=t[1],t[2]<0&&(r=n[0],n[0]=n[2],n[2]=r),n[0]*=t[2],n[2]*=t[2]),n[0]+=t[4],n[1]+=t[5],n[2]+=t[4],n[3]+=t[5]}static transform(t,n){return[t[0]*n[0]+t[2]*n[1],t[1]*n[0]+t[3]*n[1],t[0]*n[2]+t[2]*n[3],t[1]*n[2]+t[3]*n[3],t[0]*n[4]+t[2]*n[5]+t[4],t[1]*n[4]+t[3]*n[5]+t[5]]}static applyTransform(t,n){const r=t[0]*n[0]+t[1]*n[2]+n[4],a=t[0]*n[1]+t[1]*n[3]+n[5];return[r,a]}static applyInverseTransform(t,n){const r=n[0]*n[3]-n[1]*n[2],a=(t[0]*n[3]-t[1]*n[2]+n[2]*n[5]-n[4]*n[3])/r,i=(-t[0]*n[1]+t[1]*n[0]+n[4]*n[1]-n[5]*n[0])/r;return[a,i]}static getAxialAlignedBoundingBox(t,n){const r=this.applyTransform(t,n),a=this.applyTransform(t.slice(2,4),n),i=this.applyTransform([t[0],t[3]],n),l=this.applyTransform([t[2],t[1]],n);return[Math.min(r[0],a[0],i[0],l[0]),Math.min(r[1],a[1],i[1],l[1]),Math.max(r[0],a[0],i[0],l[0]),Math.max(r[1],a[1],i[1],l[1])]}static inverseTransform(t){const n=t[0]*t[3]-t[1]*t[2];return[t[3]/n,-t[1]/n,-t[2]/n,t[0]/n,(t[2]*t[5]-t[4]*t[3])/n,(t[4]*t[1]-t[5]*t[0])/n]}static singularValueDecompose2dScale(t){const n=[t[0],t[2],t[1],t[3]],r=t[0]*n[0]+t[1]*n[2],a=t[0]*n[1]+t[1]*n[3],i=t[2]*n[0]+t[3]*n[2],l=t[2]*n[1]+t[3]*n[3],o=(r+l)/2,c=Math.sqrt((r+l)**2-4*(r*l-i*a))/2,d=o+c||1,u=o-c||1;return[Math.sqrt(d),Math.sqrt(u)]}static normalizeRect(t){const n=t.slice(0);return t[0]>t[2]&&(n[0]=t[2],n[2]=t[0]),t[1]>t[3]&&(n[1]=t[3],n[3]=t[1]),n}static intersect(t,n){const r=Math.max(Math.min(t[0],t[2]),Math.min(n[0],n[2])),a=Math.min(Math.max(t[0],t[2]),Math.max(n[0],n[2]));if(r>a)return null;const i=Math.max(Math.min(t[1],t[3]),Math.min(n[1],n[3])),l=Math.min(Math.max(t[1],t[3]),Math.max(n[1],n[3]));return i>l?null:[r,i,a,l]}static bezierBoundingBox(t,n,r,a,i,l,o,c,d){return d?(d[0]=Math.min(d[0],t,o),d[1]=Math.min(d[1],n,c),d[2]=Math.max(d[2],t,o),d[3]=Math.max(d[3],n,c)):d=[Math.min(t,o),Math.min(n,c),Math.max(t,o),Math.max(n,c)],ls(this,rT,NZe).call(this,t,r,i,o,n,a,l,c,3*(-t+3*(r-i)+o),6*(t-2*r+i),3*(r-t),d),ls(this,rT,NZe).call(this,t,r,i,o,n,a,l,c,3*(-n+3*(a-l)+c),6*(n-2*a+l),3*(a-n),d),d}}rT=new WeakSet,z3e=function(t,n,r,a,i,l,o,c,d,u){if(d<=0||d>=1)return;const h=1-d,m=d*d,f=m*d,g=h*(h*(h*t+3*d*n)+3*m*r)+f*a,x=h*(h*(h*i+3*d*l)+3*m*o)+f*c;u[0]=Math.min(u[0],g),u[1]=Math.min(u[1],x),u[2]=Math.max(u[2],g),u[3]=Math.max(u[3],x)},NZe=function(t,n,r,a,i,l,o,c,d,u,h,m){if(Math.abs(d)<1e-12){Math.abs(u)>=1e-12&&ls(this,rT,z3e).call(this,t,n,r,a,i,l,o,c,-h/u,m);return}const f=u**2-4*h*d;if(f<0)return;const g=Math.sqrt(f),x=2*d;ls(this,rT,z3e).call(this,t,n,r,a,i,l,o,c,(-u+g)/x,m),ls(this,rT,z3e).call(this,t,n,r,a,i,l,o,c,(-u-g)/x,m)},bs(ol,rT);function uYn(s){return decodeURIComponent(escape(s))}let F$e=null,a3t=null;function hYn(s){return F$e||(F$e=/([\u00a0\u00b5\u037e\u0eb3\u2000-\u200a\u202f\u2126\ufb00-\ufb04\ufb06\ufb20-\ufb36\ufb38-\ufb3c\ufb3e\ufb40-\ufb41\ufb43-\ufb44\ufb46-\ufba1\ufba4-\ufba9\ufbae-\ufbb1\ufbd3-\ufbdc\ufbde-\ufbe7\ufbea-\ufbf8\ufbfc-\ufbfd\ufc00-\ufc5d\ufc64-\ufcf1\ufcf5-\ufd3d\ufd88\ufdf4\ufdfa-\ufdfb\ufe71\ufe77\ufe79\ufe7b\ufe7d]+)|(\ufb05+)/gu,a3t=new Map([["ſt","ſt"]])),s.replaceAll(F$e,(t,n,r)=>n?n.normalize("NFKC"):a3t.get(r))}function mYn(){if(typeof crypto<"u"&&typeof(crypto==null?void 0:crypto.randomUUID)=="function")return crypto.randomUUID();const s=new Uint8Array(32);if(typeof crypto<"u"&&typeof(crypto==null?void 0:crypto.getRandomValues)=="function")crypto.getRandomValues(s);else for(let t=0;t<32;t++)s[t]=Math.floor(Math.random()*255);return Pss(s)}const Rot="pdfjs_internal_id_",dA={BEZIER_CURVE_TO:0,MOVE_TO:1,LINE_TO:2,QUADRATIC_CURVE_TO:3,RESTORE:4,SAVE:5,SCALE:6,TRANSFORM:7,TRANSLATE:8};function fYn(s){return Uint8Array.prototype.toBase64?s.toBase64():btoa(Pss(s))}const jA="http://www.w3.org/2000/svg",n8=class n8{};Nr(n8,"CSS",96),Nr(n8,"PDF",72),Nr(n8,"PDF_TO_CSS_UNITS",n8.CSS/n8.PDF);let VL=n8;async function qDe(s,t="text"){if(EQ(s,document.baseURI)){const n=await fetch(s);if(!n.ok)throw new Error(n.statusText);switch(t){case"arraybuffer":return n.arrayBuffer();case"blob":return n.blob();case"json":return n.json()}return n.text()}return new Promise((n,r)=>{const a=new XMLHttpRequest;a.open("GET",s,!0),a.responseType=t,a.onreadystatechange=()=>{if(a.readyState===XMLHttpRequest.DONE){if(a.status===200||a.status===0){switch(t){case"arraybuffer":case"blob":case"json":n(a.response);return}n(a.responseText);return}r(new Error(a.statusText))}},a.send(null)})}class Zie{constructor({viewBox:t,scale:n,rotation:r,offsetX:a=0,offsetY:i=0,dontFlip:l=!1}){this.viewBox=t,this.scale=n,this.rotation=r,this.offsetX=a,this.offsetY=i;const o=(t[2]+t[0])/2,c=(t[3]+t[1])/2;let d,u,h,m;switch(r%=360,r<0&&(r+=360),r){case 180:d=-1,u=0,h=0,m=1;break;case 90:d=0,u=1,h=1,m=0;break;case 270:d=0,u=-1,h=-1,m=0;break;case 0:d=1,u=0,h=0,m=-1;break;default:throw new Error("PageViewport: Invalid rotation, must be a multiple of 90 degrees.")}l&&(h=-h,m=-m);let f,g,x,y;d===0?(f=Math.abs(c-t[1])*n+a,g=Math.abs(o-t[0])*n+i,x=(t[3]-t[1])*n,y=(t[2]-t[0])*n):(f=Math.abs(o-t[0])*n+a,g=Math.abs(c-t[1])*n+i,x=(t[2]-t[0])*n,y=(t[3]-t[1])*n),this.transform=[d*n,u*n,h*n,m*n,f-d*n*o-h*n*c,g-u*n*o-m*n*c],this.width=x,this.height=y}get rawDims(){const{viewBox:t}=this;return th(this,"rawDims",{pageWidth:t[2]-t[0],pageHeight:t[3]-t[1],pageX:t[0],pageY:t[1]})}clone({scale:t=this.scale,rotation:n=this.rotation,offsetX:r=this.offsetX,offsetY:a=this.offsetY,dontFlip:i=!1}={}){return new Zie({viewBox:this.viewBox.slice(),scale:t,rotation:n,offsetX:r,offsetY:a,dontFlip:i})}convertToViewportPoint(t,n){return ol.applyTransform([t,n],this.transform)}convertToViewportRectangle(t){const n=ol.applyTransform([t[0],t[1]],this.transform),r=ol.applyTransform([t[2],t[3]],this.transform);return[n[0],n[1],r[0],r[1]]}convertToPdfPoint(t,n){return ol.applyInverseTransform([t,n],this.transform)}}class Dot extends D6{constructor(t,n=0){super(t,"RenderingCancelledException"),this.extraDelay=n}}function VDe(s){const t=s.length;let n=0;for(;n=1&&a<=12?a-1:0;let i=parseInt(n[3],10);i=i>=1&&i<=31?i:1;let l=parseInt(n[4],10);l=l>=0&&l<=23?l:0;let o=parseInt(n[5],10);o=o>=0&&o<=59?o:0;let c=parseInt(n[6],10);c=c>=0&&c<=59?c:0;const d=n[7]||"Z";let u=parseInt(n[8],10);u=u>=0&&u<=23?u:0;let h=parseInt(n[9],10)||0;return h=h>=0&&h<=59?h:0,d==="-"?(l+=u,o+=h):d==="+"&&(l-=u,o-=h),new Date(Date.UTC(r,a,i,l,o,c))}}tre=new WeakMap,bs(Oot,tre);function xYn(s,{scale:t=1,rotation:n=0}){const{width:r,height:a}=s.attributes.style,i=[0,0,parseInt(r),parseInt(a)];return new Zie({viewBox:i,scale:t,rotation:n})}function zot(s){if(s.startsWith("#")){const t=parseInt(s.slice(1),16);return[(t&16711680)>>16,(t&65280)>>8,t&255]}return s.startsWith("rgb(")?s.slice(4,-1).split(",").map(t=>parseInt(t)):s.startsWith("rgba(")?s.slice(5,-1).split(",").map(t=>parseInt(t)).slice(0,3):(nu(`Not a valid color format: "${s}"`),[0,0,0])}function yYn(s){const t=document.createElement("span");t.style.visibility="hidden",document.body.append(t);for(const n of s.keys()){t.style.color=n;const r=window.getComputedStyle(t).color;s.set(n,zot(r))}t.remove()}function wg(s){const{a:t,b:n,c:r,d:a,e:i,f:l}=s.getTransform();return[t,n,r,a,i,l]}function uA(s){const{a:t,b:n,c:r,d:a,e:i,f:l}=s.getTransform().invertSelf();return[t,n,r,a,i,l]}function bB(s,t,n=!1,r=!0){if(t instanceof Zie){const{pageWidth:a,pageHeight:i}=t.rawDims,{style:l}=s,o=T_.isCSSRoundSupported,c=`var(--scale-factor) * ${a}px`,d=`var(--scale-factor) * ${i}px`,u=o?`round(down, ${c}, var(--scale-round-x, 1px))`:`calc(${c})`,h=o?`round(down, ${d}, var(--scale-round-y, 1px))`:`calc(${d})`;!n||t.rotation%180===0?(l.width=u,l.height=h):(l.width=h,l.height=u)}r&&s.setAttribute("data-main-rotation",t.rotation)}class kZe{constructor(){const t=window.devicePixelRatio||1;this.sx=t,this.sy=t}get scaled(){return this.sx!==1||this.sy!==1}get symmetric(){return this.sx===this.sy}}var UP,B8,bS,$8,sre,nre,cIe,Iss,I_,Lss,Rss,B3e,Dss,CZe;const PA=class PA{constructor(t){bs(this,I_);bs(this,UP,null);bs(this,B8,null);bs(this,bS);bs(this,$8,null);bs(this,sre,null);Kt(this,bS,t),ye(PA,nre)||Kt(PA,nre,Object.freeze({freetext:"pdfjs-editor-remove-freetext-button",highlight:"pdfjs-editor-remove-highlight-button",ink:"pdfjs-editor-remove-ink-button",stamp:"pdfjs-editor-remove-stamp-button"}))}render(){const t=Kt(this,UP,document.createElement("div"));t.classList.add("editToolbar","hidden"),t.setAttribute("role","toolbar");const n=ye(this,bS)._uiManager._signal;t.addEventListener("contextmenu",yk,{signal:n}),t.addEventListener("pointerdown",ls(PA,cIe,Iss),{signal:n});const r=Kt(this,$8,document.createElement("div"));r.className="buttons",t.append(r);const a=ye(this,bS).toolbarPosition;if(a){const{style:i}=t,l=ye(this,bS)._uiManager.direction==="ltr"?1-a[0]:a[0];i.insetInlineEnd=`${100*l}%`,i.top=`calc(${100*a[1]}% + var(--editor-toolbar-vert-offset))`}return ls(this,I_,Dss).call(this),t}get div(){return ye(this,UP)}hide(){var t;ye(this,UP).classList.add("hidden"),(t=ye(this,B8))==null||t.hideDropdown()}show(){var t;ye(this,UP).classList.remove("hidden"),(t=ye(this,sre))==null||t.shown()}async addAltText(t){const n=await t.render();ls(this,I_,B3e).call(this,n),ye(this,$8).prepend(n,ye(this,I_,CZe)),Kt(this,sre,t)}addColorPicker(t){Kt(this,B8,t);const n=t.renderButton();ls(this,I_,B3e).call(this,n),ye(this,$8).prepend(n,ye(this,I_,CZe))}remove(){var t;ye(this,UP).remove(),(t=ye(this,B8))==null||t.destroy(),Kt(this,B8,null)}};UP=new WeakMap,B8=new WeakMap,bS=new WeakMap,$8=new WeakMap,sre=new WeakMap,nre=new WeakMap,cIe=new WeakSet,Iss=function(t){t.stopPropagation()},I_=new WeakSet,Lss=function(t){ye(this,bS)._focusEventsAllowed=!1,t.preventDefault(),t.stopPropagation()},Rss=function(t){ye(this,bS)._focusEventsAllowed=!0,t.preventDefault(),t.stopPropagation()},B3e=function(t){const n=ye(this,bS)._uiManager._signal;t.addEventListener("focusin",ls(this,I_,Lss).bind(this),{capture:!0,signal:n}),t.addEventListener("focusout",ls(this,I_,Rss).bind(this),{capture:!0,signal:n}),t.addEventListener("contextmenu",yk,{signal:n})},Dss=function(){const{editorType:t,_uiManager:n}=ye(this,bS),r=document.createElement("button");r.className="delete",r.tabIndex=0,r.setAttribute("data-l10n-id",ye(PA,nre)[t]),ls(this,I_,B3e).call(this,r),r.addEventListener("click",a=>{n.delete()},{signal:n._signal}),ye(this,$8).append(r)},CZe=function(){const t=document.createElement("div");return t.className="divider",t},bs(PA,cIe),bs(PA,nre,null);let SZe=PA;var rre,U8,q8,XL,Fss,Oss,zss;class vYn{constructor(t){bs(this,XL);bs(this,rre,null);bs(this,U8,null);bs(this,q8);Kt(this,q8,t)}show(t,n,r){const[a,i]=ls(this,XL,Oss).call(this,n,r),{style:l}=ye(this,U8)||Kt(this,U8,ls(this,XL,Fss).call(this));t.append(ye(this,U8)),l.insetInlineEnd=`${100*a}%`,l.top=`calc(${100*i}% + var(--editor-toolbar-vert-offset))`}hide(){ye(this,U8).remove()}}rre=new WeakMap,U8=new WeakMap,q8=new WeakMap,XL=new WeakSet,Fss=function(){const t=Kt(this,U8,document.createElement("div"));t.className="editToolbar",t.setAttribute("role","toolbar"),t.addEventListener("contextmenu",yk,{signal:ye(this,q8)._signal});const n=Kt(this,rre,document.createElement("div"));return n.className="buttons",t.append(n),ls(this,XL,zss).call(this),t},Oss=function(t,n){let r=0,a=0;for(const i of t){const l=i.y+i.height;if(lr){a=o,r=l;continue}n?o>a&&(a=o):o{ye(this,q8).highlightSelection("floating_button")},{signal:r}),ye(this,rre).append(t)};function xPe(s,t,n){for(const r of n)t.addEventListener(r,s[r].bind(s))}function bYn(s){return Math.round(Math.min(255,Math.max(1,255*s))).toString(16).padStart(2,"0")}var dIe;class _Yn{constructor(){bs(this,dIe,0)}get id(){return`${eYn}${J0(this,dIe)._++}`}}dIe=new WeakMap;var uH,are,i1,hH,$3e;const idt=class idt{constructor(){bs(this,hH);bs(this,uH,mYn());bs(this,are,0);bs(this,i1,null)}static get _isSVGFittingCanvas(){const t='data:image/svg+xml;charset=UTF-8,',r=new OffscreenCanvas(1,3).getContext("2d",{willReadFrequently:!0}),a=new Image;a.src=t;const i=a.decode().then(()=>(r.drawImage(a,0,0,1,1,0,0,1,3),new Uint32Array(r.getImageData(0,0,1,1).data.buffer)[0]===0));return th(this,"_isSVGFittingCanvas",i)}async getFromFile(t){const{lastModified:n,name:r,size:a,type:i}=t;return ls(this,hH,$3e).call(this,`${n}_${r}_${a}_${i}`,t)}async getFromUrl(t){return ls(this,hH,$3e).call(this,t,t)}async getFromBlob(t,n){const r=await n;return ls(this,hH,$3e).call(this,t,r)}async getFromId(t){ye(this,i1)||Kt(this,i1,new Map);const n=ye(this,i1).get(t);if(!n)return null;if(n.bitmap)return n.refCounter+=1,n;if(n.file)return this.getFromFile(n.file);if(n.blobPromise){const{blobPromise:r}=n;return delete n.blobPromise,this.getFromBlob(n.id,r)}return this.getFromUrl(n.url)}getFromCanvas(t,n){ye(this,i1)||Kt(this,i1,new Map);let r=ye(this,i1).get(t);if(r!=null&&r.bitmap)return r.refCounter+=1,r;const a=new OffscreenCanvas(n.width,n.height);return a.getContext("2d").drawImage(n,0,0),r={bitmap:a.transferToImageBitmap(),id:`image_${ye(this,uH)}_${J0(this,are)._++}`,refCounter:1,isSvg:!1},ye(this,i1).set(t,r),ye(this,i1).set(r.id,r),r}getSvgUrl(t){const n=ye(this,i1).get(t);return n!=null&&n.isSvg?n.svgUrl:null}deleteId(t){var a;ye(this,i1)||Kt(this,i1,new Map);const n=ye(this,i1).get(t);if(!n||(n.refCounter-=1,n.refCounter!==0))return;const{bitmap:r}=n;if(!n.url&&!n.file){const i=new OffscreenCanvas(r.width,r.height);i.getContext("bitmaprenderer").transferFromImageBitmap(r),n.blobPromise=i.convertToBlob()}(a=r.close)==null||a.call(r),n.bitmap=null}isValidId(t){return t.startsWith(`image_${ye(this,uH)}_`)}};uH=new WeakMap,are=new WeakMap,i1=new WeakMap,hH=new WeakSet,$3e=async function(t,n){ye(this,i1)||Kt(this,i1,new Map);let r=ye(this,i1).get(t);if(r===null)return null;if(r!=null&&r.bitmap)return r.refCounter+=1,r;try{r||(r={bitmap:null,id:`image_${ye(this,uH)}_${J0(this,are)._++}`,refCounter:0,isSvg:!1});let a;if(typeof n=="string"?(r.url=n,a=await qDe(n,"blob")):n instanceof File?a=r.file=n:n instanceof Blob&&(a=n),a.type==="image/svg+xml"){const i=idt._isSVGFittingCanvas,l=new FileReader,o=new Image,c=new Promise((d,u)=>{o.onload=()=>{r.bitmap=o,r.isSvg=!0,d()},l.onload=async()=>{const h=r.svgUrl=l.result;o.src=await i?`${h}#svgView(preserveAspectRatio(none))`:h},o.onerror=l.onerror=u});l.readAsDataURL(a),await c}else r.bitmap=await createImageBitmap(a);r.refCounter=1}catch(a){console.error(a),r=null}return ye(this,i1).set(t,r),r&&ye(this,i1).set(r.id,r),r};let AZe=idt;var rv,qP,ire,av;class wYn{constructor(t=128){bs(this,rv,[]);bs(this,qP,!1);bs(this,ire);bs(this,av,-1);Kt(this,ire,t)}add({cmd:t,undo:n,post:r,mustExec:a,type:i=NaN,overwriteIfSameType:l=!1,keepUndo:o=!1}){if(a&&t(),ye(this,qP))return;const c={cmd:t,undo:n,post:r,type:i};if(ye(this,av)===-1){ye(this,rv).length>0&&(ye(this,rv).length=0),Kt(this,av,0),ye(this,rv).push(c);return}if(l&&ye(this,rv)[ye(this,av)].type===i){o&&(c.undo=ye(this,rv)[ye(this,av)].undo),ye(this,rv)[ye(this,av)]=c;return}const d=ye(this,av)+1;d===ye(this,ire)?ye(this,rv).splice(0,1):(Kt(this,av,d),di===n[l]))return hIe._colorsMapping.get(r);return n}getHexCode(t){const n=this._colors.get(t);return n?ol.makeHexColor(...n):t}};Nr(hIe,"_colorsMapping",new Map([["CanvasText",[0,0,0]],["Canvas",[255,255,255]]]));let EZe=hIe;var mH,Lj,c0,Jv,fH,qA,pH,_S,VP,gH,V8,O5,wS,H8,ore,lre,xH,cre,z5,HP,yH,GP,B5,mIe,WP,dre,KP,G8,ure,hre,iv,Sm,VA,W8,mre,fre,YP,$5,HA,pre,NN,Ji,U3e,TZe,$ss,Uss,q3e,qss,Vss,Hss,MZe,Gss,PZe,IZe,Wss,r_,JM,Kss,Yss,LZe,Zss,TQ,RZe;const jq=class jq{constructor(t,n,r,a,i,l,o,c,d,u,h){bs(this,Ji);bs(this,mH,new AbortController);bs(this,Lj,null);bs(this,c0,new Map);bs(this,Jv,new Map);bs(this,fH,null);bs(this,qA,null);bs(this,pH,null);bs(this,_S,new wYn);bs(this,VP,null);bs(this,gH,0);bs(this,V8,new Set);bs(this,O5,null);bs(this,wS,null);bs(this,H8,new Set);bs(this,ore,!1);bs(this,lre,!1);bs(this,xH,!1);bs(this,cre,null);bs(this,z5,null);bs(this,HP,null);bs(this,yH,null);bs(this,GP,!1);bs(this,B5,null);bs(this,mIe,new _Yn);bs(this,WP,!1);bs(this,dre,!1);bs(this,KP,null);bs(this,G8,null);bs(this,ure,null);bs(this,hre,null);bs(this,iv,Od.NONE);bs(this,Sm,new Set);bs(this,VA,null);bs(this,W8,null);bs(this,mre,null);bs(this,fre,{isEditing:!1,isEmpty:!0,hasSomethingToUndo:!1,hasSomethingToRedo:!1,hasSelectedEditor:!1,hasSelectedText:!1});bs(this,YP,[0,0]);bs(this,$5,null);bs(this,HA,null);bs(this,pre,null);bs(this,NN,null);const m=this._signal=ye(this,mH).signal;Kt(this,HA,t),Kt(this,pre,n),Kt(this,fH,r),this._eventBus=a,a._on("editingaction",this.onEditingAction.bind(this),{signal:m}),a._on("pagechanging",this.onPageChanging.bind(this),{signal:m}),a._on("scalechanging",this.onScaleChanging.bind(this),{signal:m}),a._on("rotationchanging",this.onRotationChanging.bind(this),{signal:m}),a._on("setpreference",this.onSetPreference.bind(this),{signal:m}),a._on("switchannotationeditorparams",f=>this.updateParams(f.type,f.value),{signal:m}),ls(this,Ji,qss).call(this),ls(this,Ji,Wss).call(this),ls(this,Ji,MZe).call(this),Kt(this,qA,i.annotationStorage),Kt(this,cre,i.filterFactory),Kt(this,W8,l),Kt(this,yH,o||null),Kt(this,ore,c),Kt(this,lre,d),Kt(this,xH,u),Kt(this,hre,h||null),this.viewParameters={realScale:VL.PDF_TO_CSS_UNITS,rotation:0},this.isShiftKeyDown=!1}static get _keyboardManager(){const t=jq.prototype,n=l=>ye(l,HA).contains(document.activeElement)&&document.activeElement.tagName!=="BUTTON"&&l.hasSomethingToControl(),r=(l,{target:o})=>{if(o instanceof HTMLInputElement){const{type:c}=o;return c!=="text"&&c!=="number"}return!0},a=this.TRANSLATE_SMALL,i=this.TRANSLATE_BIG;return th(this,"_keyboardManager",new Xie([[["ctrl+a","mac+meta+a"],t.selectAll,{checker:r}],[["ctrl+z","mac+meta+z"],t.undo,{checker:r}],[["ctrl+y","ctrl+shift+z","mac+meta+shift+z","ctrl+shift+Z","mac+meta+shift+Z"],t.redo,{checker:r}],[["Backspace","alt+Backspace","ctrl+Backspace","shift+Backspace","mac+Backspace","mac+alt+Backspace","mac+ctrl+Backspace","Delete","ctrl+Delete","shift+Delete","mac+Delete"],t.delete,{checker:r}],[["Enter","mac+Enter"],t.addNewEditorFromKeyboard,{checker:(l,{target:o})=>!(o instanceof HTMLButtonElement)&&ye(l,HA).contains(o)&&!l.isEnterHandled}],[[" ","mac+ "],t.addNewEditorFromKeyboard,{checker:(l,{target:o})=>!(o instanceof HTMLButtonElement)&&ye(l,HA).contains(document.activeElement)}],[["Escape","mac+Escape"],t.unselectAll],[["ArrowLeft","mac+ArrowLeft"],t.translateSelectedEditors,{args:[-a,0],checker:n}],[["ctrl+ArrowLeft","mac+shift+ArrowLeft"],t.translateSelectedEditors,{args:[-i,0],checker:n}],[["ArrowRight","mac+ArrowRight"],t.translateSelectedEditors,{args:[a,0],checker:n}],[["ctrl+ArrowRight","mac+shift+ArrowRight"],t.translateSelectedEditors,{args:[i,0],checker:n}],[["ArrowUp","mac+ArrowUp"],t.translateSelectedEditors,{args:[0,-a],checker:n}],[["ctrl+ArrowUp","mac+shift+ArrowUp"],t.translateSelectedEditors,{args:[0,-i],checker:n}],[["ArrowDown","mac+ArrowDown"],t.translateSelectedEditors,{args:[0,a],checker:n}],[["ctrl+ArrowDown","mac+shift+ArrowDown"],t.translateSelectedEditors,{args:[0,i],checker:n}]]))}destroy(){var t,n,r,a;(t=ye(this,NN))==null||t.resolve(),Kt(this,NN,null),(n=ye(this,mH))==null||n.abort(),Kt(this,mH,null),this._signal=null;for(const i of ye(this,Jv).values())i.destroy();ye(this,Jv).clear(),ye(this,c0).clear(),ye(this,H8).clear(),Kt(this,Lj,null),ye(this,Sm).clear(),ye(this,_S).destroy(),(r=ye(this,fH))==null||r.destroy(),(a=ye(this,B5))==null||a.hide(),Kt(this,B5,null),ye(this,z5)&&(clearTimeout(ye(this,z5)),Kt(this,z5,null)),ye(this,$5)&&(clearTimeout(ye(this,$5)),Kt(this,$5,null))}combinedSignal(t){return AbortSignal.any([this._signal,t.signal])}get mlManager(){return ye(this,hre)}get useNewAltTextFlow(){return ye(this,lre)}get useNewAltTextWhenAddingImage(){return ye(this,xH)}get hcmFilter(){return th(this,"hcmFilter",ye(this,W8)?ye(this,cre).addHCMFilter(ye(this,W8).foreground,ye(this,W8).background):"none")}get direction(){return th(this,"direction",getComputedStyle(ye(this,HA)).direction)}get highlightColors(){return th(this,"highlightColors",ye(this,yH)?new Map(ye(this,yH).split(",").map(t=>t.split("=").map(n=>n.trim()))):null)}get highlightColorNames(){return th(this,"highlightColorNames",this.highlightColors?new Map(Array.from(this.highlightColors,t=>t.reverse())):null)}setMainHighlightColorPicker(t){Kt(this,ure,t)}editAltText(t,n=!1){var r;(r=ye(this,fH))==null||r.editAltText(this,t,n)}switchToMode(t,n){this._eventBus.on("annotationeditormodechanged",n,{once:!0,signal:this._signal}),this._eventBus.dispatch("showannotationeditorui",{source:this,mode:t})}setPreference(t,n){this._eventBus.dispatch("setpreference",{source:this,name:t,value:n})}onSetPreference({name:t,value:n}){switch(t){case"enableNewAltTextWhenAddingImage":Kt(this,xH,n);break}}onPageChanging({pageNumber:t}){Kt(this,gH,t-1)}focusMainContainer(){ye(this,HA).focus()}findParent(t,n){for(const r of ye(this,Jv).values()){const{x:a,y:i,width:l,height:o}=r.div.getBoundingClientRect();if(t>=a&&t<=a+l&&n>=i&&n<=i+o)return r}return null}disableUserSelect(t=!1){ye(this,pre).classList.toggle("noUserSelect",t)}addShouldRescale(t){ye(this,H8).add(t)}removeShouldRescale(t){ye(this,H8).delete(t)}onScaleChanging({scale:t}){this.commitOrRemove(),this.viewParameters.realScale=t*VL.PDF_TO_CSS_UNITS;for(const n of ye(this,H8))n.onScaleChanging()}onRotationChanging({pagesRotation:t}){this.commitOrRemove(),this.viewParameters.rotation=t}highlightSelection(t=""){const n=document.getSelection();if(!n||n.isCollapsed)return;const{anchorNode:r,anchorOffset:a,focusNode:i,focusOffset:l}=n,o=n.toString(),d=ls(this,Ji,U3e).call(this,n).closest(".textLayer"),u=this.getSelectionBoxes(d);if(!u)return;n.empty();const h=ls(this,Ji,TZe).call(this,d),m=ye(this,iv)===Od.NONE,f=()=>{h==null||h.createAndAddNewEditor({x:0,y:0},!1,{methodOfCreation:t,boxes:u,anchorNode:r,anchorOffset:a,focusNode:i,focusOffset:l,text:o}),m&&this.showAllEditors("highlight",!0,!0)};if(m){this.switchToMode(Od.HIGHLIGHT,f);return}f()}addToAnnotationStorage(t){!t.isEmpty()&&ye(this,qA)&&!ye(this,qA).has(t.id)&&ye(this,qA).setValue(t.id,t)}blur(){if(this.isShiftKeyDown=!1,ye(this,GP)&&(Kt(this,GP,!1),ls(this,Ji,q3e).call(this,"main_toolbar")),!this.hasSelection)return;const{activeElement:t}=document;for(const n of ye(this,Sm))if(n.div.contains(t)){Kt(this,G8,[n,t]),n._focusEventsAllowed=!1;break}}focus(){if(!ye(this,G8))return;const[t,n]=ye(this,G8);Kt(this,G8,null),n.addEventListener("focusin",()=>{t._focusEventsAllowed=!0},{once:!0,signal:this._signal}),n.focus()}addEditListeners(){ls(this,Ji,MZe).call(this),ls(this,Ji,PZe).call(this)}removeEditListeners(){ls(this,Ji,Gss).call(this),ls(this,Ji,IZe).call(this)}dragOver(t){for(const{type:n}of t.dataTransfer.items)for(const r of ye(this,wS))if(r.isHandlingMimeForPasting(n)){t.dataTransfer.dropEffect="copy",t.preventDefault();return}}drop(t){for(const n of t.dataTransfer.items)for(const r of ye(this,wS))if(r.isHandlingMimeForPasting(n.type)){r.paste(n,this.currentLayer),t.preventDefault();return}}copy(t){var r;if(t.preventDefault(),(r=ye(this,Lj))==null||r.commitOrRemove(),!this.hasSelection)return;const n=[];for(const a of ye(this,Sm)){const i=a.serialize(!0);i&&n.push(i)}n.length!==0&&t.clipboardData.setData("application/pdfjs",JSON.stringify(n))}cut(t){this.copy(t),this.delete()}async paste(t){t.preventDefault();const{clipboardData:n}=t;for(const i of n.items)for(const l of ye(this,wS))if(l.isHandlingMimeForPasting(i.type)){l.paste(i,this.currentLayer);return}let r=n.getData("application/pdfjs");if(!r)return;try{r=JSON.parse(r)}catch(i){nu(`paste: "${i.message}".`);return}if(!Array.isArray(r))return;this.unselectAll();const a=this.currentLayer;try{const i=[];for(const c of r){const d=await a.deserialize(c);if(!d)return;i.push(d)}const l=()=>{for(const c of i)ls(this,Ji,LZe).call(this,c);ls(this,Ji,RZe).call(this,i)},o=()=>{for(const c of i)c.remove()};this.addCommands({cmd:l,undo:o,mustExec:!0})}catch(i){nu(`paste: "${i.message}".`)}}keydown(t){!this.isShiftKeyDown&&t.key==="Shift"&&(this.isShiftKeyDown=!0),ye(this,iv)!==Od.NONE&&!this.isEditorHandlingKeyboard&&jq._keyboardManager.exec(this,t)}keyup(t){this.isShiftKeyDown&&t.key==="Shift"&&(this.isShiftKeyDown=!1,ye(this,GP)&&(Kt(this,GP,!1),ls(this,Ji,q3e).call(this,"main_toolbar")))}onEditingAction({name:t}){switch(t){case"undo":case"redo":case"delete":case"selectAll":this[t]();break;case"highlightSelection":this.highlightSelection("context_menu");break}}setEditingState(t){t?(ls(this,Ji,Vss).call(this),ls(this,Ji,PZe).call(this),ls(this,Ji,r_).call(this,{isEditing:ye(this,iv)!==Od.NONE,isEmpty:ls(this,Ji,TQ).call(this),hasSomethingToUndo:ye(this,_S).hasSomethingToUndo(),hasSomethingToRedo:ye(this,_S).hasSomethingToRedo(),hasSelectedEditor:!1})):(ls(this,Ji,Hss).call(this),ls(this,Ji,IZe).call(this),ls(this,Ji,r_).call(this,{isEditing:!1}),this.disableUserSelect(!1))}registerEditorTypes(t){if(!ye(this,wS)){Kt(this,wS,t);for(const n of ye(this,wS))ls(this,Ji,JM).call(this,n.defaultPropertiesToUpdate)}}getId(){return ye(this,mIe).id}get currentLayer(){return ye(this,Jv).get(ye(this,gH))}getLayer(t){return ye(this,Jv).get(t)}get currentPageIndex(){return ye(this,gH)}addLayer(t){ye(this,Jv).set(t.pageIndex,t),ye(this,WP)?t.enable():t.disable()}removeLayer(t){ye(this,Jv).delete(t.pageIndex)}async updateMode(t,n=null,r=!1){if(ye(this,iv)!==t&&!(ye(this,NN)&&(await ye(this,NN).promise,!ye(this,NN)))){if(Kt(this,NN,Promise.withResolvers()),Kt(this,iv,t),t===Od.NONE){this.setEditingState(!1),ls(this,Ji,Yss).call(this),ye(this,NN).resolve();return}this.setEditingState(!0),await ls(this,Ji,Kss).call(this),this.unselectAll();for(const a of ye(this,Jv).values())a.updateMode(t);if(!n){r&&this.addNewEditorFromKeyboard(),ye(this,NN).resolve();return}for(const a of ye(this,c0).values())a.annotationElementId===n?(this.setSelected(a),a.enterInEditMode()):a.unselect();ye(this,NN).resolve()}}addNewEditorFromKeyboard(){this.currentLayer.canCreateNewEmptyEditor()&&this.currentLayer.addNewEditor()}updateToolbar(t){t!==ye(this,iv)&&this._eventBus.dispatch("switchannotationeditormode",{source:this,mode:t})}updateParams(t,n){var r;if(ye(this,wS)){switch(t){case nd.CREATE:this.currentLayer.addNewEditor();return;case nd.HIGHLIGHT_DEFAULT_COLOR:(r=ye(this,ure))==null||r.updateColor(n);break;case nd.HIGHLIGHT_SHOW_ALL:this._eventBus.dispatch("reporttelemetry",{source:this,details:{type:"editing",data:{type:"highlight",action:"toggle_visibility"}}}),(ye(this,mre)||Kt(this,mre,new Map)).set(t,n),this.showAllEditors("highlight",n);break}for(const a of ye(this,Sm))a.updateParams(t,n);for(const a of ye(this,wS))a.updateDefaultParams(t,n)}}showAllEditors(t,n,r=!1){var i;for(const l of ye(this,c0).values())l.editorType===t&&l.show(n);(((i=ye(this,mre))==null?void 0:i.get(nd.HIGHLIGHT_SHOW_ALL))??!0)!==n&&ls(this,Ji,JM).call(this,[[nd.HIGHLIGHT_SHOW_ALL,n]])}enableWaiting(t=!1){if(ye(this,dre)!==t){Kt(this,dre,t);for(const n of ye(this,Jv).values())t?n.disableClick():n.enableClick(),n.div.classList.toggle("waiting",t)}}getEditors(t){const n=[];for(const r of ye(this,c0).values())r.pageIndex===t&&n.push(r);return n}getEditor(t){return ye(this,c0).get(t)}addEditor(t){ye(this,c0).set(t.id,t)}removeEditor(t){var n;t.div.contains(document.activeElement)&&(ye(this,z5)&&clearTimeout(ye(this,z5)),Kt(this,z5,setTimeout(()=>{this.focusMainContainer(),Kt(this,z5,null)},0))),ye(this,c0).delete(t.id),this.unselect(t),(!t.annotationElementId||!ye(this,V8).has(t.annotationElementId))&&((n=ye(this,qA))==null||n.remove(t.id))}addDeletedAnnotationElement(t){ye(this,V8).add(t.annotationElementId),this.addChangedExistingAnnotation(t),t.deleted=!0}isDeletedAnnotationElement(t){return ye(this,V8).has(t)}removeDeletedAnnotationElement(t){ye(this,V8).delete(t.annotationElementId),this.removeChangedExistingAnnotation(t),t.deleted=!1}setActiveEditor(t){ye(this,Lj)!==t&&(Kt(this,Lj,t),t&&ls(this,Ji,JM).call(this,t.propertiesToUpdate))}updateUI(t){ye(this,Ji,Zss)===t&&ls(this,Ji,JM).call(this,t.propertiesToUpdate)}toggleSelected(t){if(ye(this,Sm).has(t)){ye(this,Sm).delete(t),t.unselect(),ls(this,Ji,r_).call(this,{hasSelectedEditor:this.hasSelection});return}ye(this,Sm).add(t),t.select(),ls(this,Ji,JM).call(this,t.propertiesToUpdate),ls(this,Ji,r_).call(this,{hasSelectedEditor:!0})}setSelected(t){for(const n of ye(this,Sm))n!==t&&n.unselect();ye(this,Sm).clear(),ye(this,Sm).add(t),t.select(),ls(this,Ji,JM).call(this,t.propertiesToUpdate),ls(this,Ji,r_).call(this,{hasSelectedEditor:!0})}isSelected(t){return ye(this,Sm).has(t)}get firstSelectedEditor(){return ye(this,Sm).values().next().value}unselect(t){t.unselect(),ye(this,Sm).delete(t),ls(this,Ji,r_).call(this,{hasSelectedEditor:this.hasSelection})}get hasSelection(){return ye(this,Sm).size!==0}get isEnterHandled(){return ye(this,Sm).size===1&&this.firstSelectedEditor.isEnterHandled}undo(){ye(this,_S).undo(),ls(this,Ji,r_).call(this,{hasSomethingToUndo:ye(this,_S).hasSomethingToUndo(),hasSomethingToRedo:!0,isEmpty:ls(this,Ji,TQ).call(this)})}redo(){ye(this,_S).redo(),ls(this,Ji,r_).call(this,{hasSomethingToUndo:!0,hasSomethingToRedo:ye(this,_S).hasSomethingToRedo(),isEmpty:ls(this,Ji,TQ).call(this)})}addCommands(t){ye(this,_S).add(t),ls(this,Ji,r_).call(this,{hasSomethingToUndo:!0,hasSomethingToRedo:!1,isEmpty:ls(this,Ji,TQ).call(this)})}delete(){if(this.commitOrRemove(),!this.hasSelection)return;const t=[...ye(this,Sm)],n=()=>{for(const a of t)a.remove()},r=()=>{for(const a of t)ls(this,Ji,LZe).call(this,a)};this.addCommands({cmd:n,undo:r,mustExec:!0})}commitOrRemove(){var t;(t=ye(this,Lj))==null||t.commitOrRemove()}hasSomethingToControl(){return ye(this,Lj)||this.hasSelection}selectAll(){for(const t of ye(this,Sm))t.commit();ls(this,Ji,RZe).call(this,ye(this,c0).values())}unselectAll(){if(!(ye(this,Lj)&&(ye(this,Lj).commitOrRemove(),ye(this,iv)!==Od.NONE))&&this.hasSelection){for(const t of ye(this,Sm))t.unselect();ye(this,Sm).clear(),ls(this,Ji,r_).call(this,{hasSelectedEditor:!1})}}translateSelectedEditors(t,n,r=!1){if(r||this.commitOrRemove(),!this.hasSelection)return;ye(this,YP)[0]+=t,ye(this,YP)[1]+=n;const[a,i]=ye(this,YP),l=[...ye(this,Sm)],o=1e3;ye(this,$5)&&clearTimeout(ye(this,$5)),Kt(this,$5,setTimeout(()=>{Kt(this,$5,null),ye(this,YP)[0]=ye(this,YP)[1]=0,this.addCommands({cmd:()=>{for(const c of l)ye(this,c0).has(c.id)&&c.translateInPage(a,i)},undo:()=>{for(const c of l)ye(this,c0).has(c.id)&&c.translateInPage(-a,-i)},mustExec:!1})},o));for(const c of l)c.translateInPage(t,n)}setUpDragSession(){if(this.hasSelection){this.disableUserSelect(!0),Kt(this,O5,new Map);for(const t of ye(this,Sm))ye(this,O5).set(t,{savedX:t.x,savedY:t.y,savedPageIndex:t.pageIndex,newX:0,newY:0,newPageIndex:-1})}}endDragSession(){if(!ye(this,O5))return!1;this.disableUserSelect(!1);const t=ye(this,O5);Kt(this,O5,null);let n=!1;for(const[{x:a,y:i,pageIndex:l},o]of t)o.newX=a,o.newY=i,o.newPageIndex=l,n||(n=a!==o.savedX||i!==o.savedY||l!==o.savedPageIndex);if(!n)return!1;const r=(a,i,l,o)=>{if(ye(this,c0).has(a.id)){const c=ye(this,Jv).get(o);c?a._setParentAndPosition(c,i,l):(a.pageIndex=o,a.x=i,a.y=l)}};return this.addCommands({cmd:()=>{for(const[a,{newX:i,newY:l,newPageIndex:o}]of t)r(a,i,l,o)},undo:()=>{for(const[a,{savedX:i,savedY:l,savedPageIndex:o}]of t)r(a,i,l,o)},mustExec:!0}),!0}dragSelectedEditors(t,n){if(ye(this,O5))for(const r of ye(this,O5).keys())r.drag(t,n)}rebuild(t){if(t.parent===null){const n=this.getLayer(t.pageIndex);n?(n.changeParent(t),n.addOrRebuild(t)):(this.addEditor(t),this.addToAnnotationStorage(t),t.rebuild())}else t.parent.addOrRebuild(t)}get isEditorHandlingKeyboard(){var t;return((t=this.getActive())==null?void 0:t.shouldGetKeyboardEvents())||ye(this,Sm).size===1&&this.firstSelectedEditor.shouldGetKeyboardEvents()}isActive(t){return ye(this,Lj)===t}getActive(){return ye(this,Lj)}getMode(){return ye(this,iv)}get imageManager(){return th(this,"imageManager",new AZe)}getSelectionBoxes(t){if(!t)return null;const n=document.getSelection();for(let d=0,u=n.rangeCount;d({x:(u-a)/l,y:1-(d+h-r)/i,width:m/l,height:h/i});break;case"180":o=(d,u,h,m)=>({x:1-(d+h-r)/i,y:1-(u+m-a)/l,width:h/i,height:m/l});break;case"270":o=(d,u,h,m)=>({x:1-(u+m-a)/l,y:(d-r)/i,width:m/l,height:h/i});break;default:o=(d,u,h,m)=>({x:(d-r)/i,y:(u-a)/l,width:h/i,height:m/l});break}const c=[];for(let d=0,u=n.rangeCount;d{m.type==="pointerup"&&m.button!==0||(d.abort(),c==null||c.toggleDrawing(!0),m.type==="pointerup"&&ls(this,Ji,q3e).call(this,"main_toolbar"))};window.addEventListener("pointerup",h,{signal:u}),window.addEventListener("blur",h,{signal:u})}},q3e=function(t=""){ye(this,iv)===Od.HIGHLIGHT?this.highlightSelection(t):ye(this,ore)&&ls(this,Ji,$ss).call(this)},qss=function(){document.addEventListener("selectionchange",ls(this,Ji,Uss).bind(this),{signal:this._signal})},Vss=function(){if(ye(this,HP))return;Kt(this,HP,new AbortController);const t=this.combinedSignal(ye(this,HP));window.addEventListener("focus",this.focus.bind(this),{signal:t}),window.addEventListener("blur",this.blur.bind(this),{signal:t})},Hss=function(){var t;(t=ye(this,HP))==null||t.abort(),Kt(this,HP,null)},MZe=function(){if(ye(this,KP))return;Kt(this,KP,new AbortController);const t=this.combinedSignal(ye(this,KP));window.addEventListener("keydown",this.keydown.bind(this),{signal:t}),window.addEventListener("keyup",this.keyup.bind(this),{signal:t})},Gss=function(){var t;(t=ye(this,KP))==null||t.abort(),Kt(this,KP,null)},PZe=function(){if(ye(this,VP))return;Kt(this,VP,new AbortController);const t=this.combinedSignal(ye(this,VP));document.addEventListener("copy",this.copy.bind(this),{signal:t}),document.addEventListener("cut",this.cut.bind(this),{signal:t}),document.addEventListener("paste",this.paste.bind(this),{signal:t})},IZe=function(){var t;(t=ye(this,VP))==null||t.abort(),Kt(this,VP,null)},Wss=function(){const t=this._signal;document.addEventListener("dragover",this.dragOver.bind(this),{signal:t}),document.addEventListener("drop",this.drop.bind(this),{signal:t})},r_=function(t){Object.entries(t).some(([r,a])=>ye(this,fre)[r]!==a)&&(this._eventBus.dispatch("annotationeditorstateschanged",{source:this,details:Object.assign(ye(this,fre),t)}),ye(this,iv)===Od.HIGHLIGHT&&t.hasSelectedEditor===!1&&ls(this,Ji,JM).call(this,[[nd.HIGHLIGHT_FREE,!0]]))},JM=function(t){this._eventBus.dispatch("annotationeditorparamschanged",{source:this,details:t})},Kss=async function(){if(!ye(this,WP)){Kt(this,WP,!0);const t=[];for(const n of ye(this,Jv).values())t.push(n.enable());await Promise.all(t);for(const n of ye(this,c0).values())n.enable()}},Yss=function(){if(this.unselectAll(),ye(this,WP)){Kt(this,WP,!1);for(const t of ye(this,Jv).values())t.disable();for(const t of ye(this,c0).values())t.disable()}},LZe=function(t){const n=ye(this,Jv).get(t.pageIndex);n?n.addOrRebuild(t):(this.addEditor(t),this.addToAnnotationStorage(t))},Zss=function(){let t=null;for(t of ye(this,Sm));return t},TQ=function(){if(ye(this,c0).size===0)return!0;if(ye(this,c0).size===1)for(const t of ye(this,c0).values())return t.isEmpty();return!1},RZe=function(t){for(const n of ye(this,Sm))n.unselect();ye(this,Sm).clear();for(const n of t)n.isEmpty()||(ye(this,Sm).add(n),n.select());ls(this,Ji,r_).call(this,{hasSelectedEditor:this.hasSelection})},Nr(jq,"TRANSLATE_SMALL",1),Nr(jq,"TRANSLATE_BIG",10);let _B=jq;var ov,U5,jS,vH,q5,Rj,bH,V5,dw,GA,K8,H5,ZP,KS,MQ,V3e;const i_=class i_{constructor(t){bs(this,KS);bs(this,ov,null);bs(this,U5,!1);bs(this,jS,null);bs(this,vH,null);bs(this,q5,null);bs(this,Rj,null);bs(this,bH,!1);bs(this,V5,null);bs(this,dw,null);bs(this,GA,null);bs(this,K8,null);bs(this,H5,!1);Kt(this,dw,t),Kt(this,H5,t._uiManager.useNewAltTextFlow),ye(i_,ZP)||Kt(i_,ZP,Object.freeze({added:"pdfjs-editor-new-alt-text-added-button","added-label":"pdfjs-editor-new-alt-text-added-button-label",missing:"pdfjs-editor-new-alt-text-missing-button","missing-label":"pdfjs-editor-new-alt-text-missing-button-label",review:"pdfjs-editor-new-alt-text-to-review-button","review-label":"pdfjs-editor-new-alt-text-to-review-button-label"}))}static initialize(t){i_._l10n??(i_._l10n=t)}async render(){const t=Kt(this,jS,document.createElement("button"));t.className="altText",t.tabIndex="0";const n=Kt(this,vH,document.createElement("span"));t.append(n),ye(this,H5)?(t.classList.add("new"),t.setAttribute("data-l10n-id",ye(i_,ZP).missing),n.setAttribute("data-l10n-id",ye(i_,ZP)["missing-label"])):(t.setAttribute("data-l10n-id","pdfjs-editor-alt-text-button"),n.setAttribute("data-l10n-id","pdfjs-editor-alt-text-button-label"));const r=ye(this,dw)._uiManager._signal;t.addEventListener("contextmenu",yk,{signal:r}),t.addEventListener("pointerdown",i=>i.stopPropagation(),{signal:r});const a=i=>{i.preventDefault(),ye(this,dw)._uiManager.editAltText(ye(this,dw)),ye(this,H5)&&ye(this,dw)._reportTelemetry({action:"pdfjs.image.alt_text.image_status_label_clicked",data:{label:ye(this,KS,MQ)}})};return t.addEventListener("click",a,{capture:!0,signal:r}),t.addEventListener("keydown",i=>{i.target===t&&i.key==="Enter"&&(Kt(this,bH,!0),a(i))},{signal:r}),await ls(this,KS,V3e).call(this),t}finish(){ye(this,jS)&&(ye(this,jS).focus({focusVisible:ye(this,bH)}),Kt(this,bH,!1))}isEmpty(){return ye(this,H5)?ye(this,ov)===null:!ye(this,ov)&&!ye(this,U5)}hasData(){return ye(this,H5)?ye(this,ov)!==null||!!ye(this,GA):this.isEmpty()}get guessedText(){return ye(this,GA)}async setGuessedText(t){ye(this,ov)===null&&(Kt(this,GA,t),Kt(this,K8,await i_._l10n.get("pdfjs-editor-new-alt-text-generated-alt-text-with-disclaimer",{generatedAltText:t})),ls(this,KS,V3e).call(this))}toggleAltTextBadge(t=!1){var n;if(!ye(this,H5)||ye(this,ov)){(n=ye(this,V5))==null||n.remove(),Kt(this,V5,null);return}if(!ye(this,V5)){const r=Kt(this,V5,document.createElement("div"));r.className="noAltTextBadge",ye(this,dw).div.append(r)}ye(this,V5).classList.toggle("hidden",!t)}serialize(t){let n=ye(this,ov);return!t&&ye(this,GA)===n&&(n=ye(this,K8)),{altText:n,decorative:ye(this,U5),guessedText:ye(this,GA),textWithDisclaimer:ye(this,K8)}}get data(){return{altText:ye(this,ov),decorative:ye(this,U5)}}set data({altText:t,decorative:n,guessedText:r,textWithDisclaimer:a,cancel:i=!1}){r&&(Kt(this,GA,r),Kt(this,K8,a)),!(ye(this,ov)===t&&ye(this,U5)===n)&&(i||(Kt(this,ov,t),Kt(this,U5,n)),ls(this,KS,V3e).call(this))}toggle(t=!1){ye(this,jS)&&(!t&&ye(this,Rj)&&(clearTimeout(ye(this,Rj)),Kt(this,Rj,null)),ye(this,jS).disabled=!t)}shown(){ye(this,dw)._reportTelemetry({action:"pdfjs.image.alt_text.image_status_label_displayed",data:{label:ye(this,KS,MQ)}})}destroy(){var t,n;(t=ye(this,jS))==null||t.remove(),Kt(this,jS,null),Kt(this,vH,null),Kt(this,q5,null),(n=ye(this,V5))==null||n.remove(),Kt(this,V5,null)}};ov=new WeakMap,U5=new WeakMap,jS=new WeakMap,vH=new WeakMap,q5=new WeakMap,Rj=new WeakMap,bH=new WeakMap,V5=new WeakMap,dw=new WeakMap,GA=new WeakMap,K8=new WeakMap,H5=new WeakMap,ZP=new WeakMap,KS=new WeakSet,MQ=function(){return ye(this,ov)&&"added"||ye(this,ov)===null&&this.guessedText&&"review"||"missing"},V3e=async function(){var a,i,l;const t=ye(this,jS);if(!t)return;if(ye(this,H5)){if(t.classList.toggle("done",!!ye(this,ov)),t.setAttribute("data-l10n-id",ye(i_,ZP)[ye(this,KS,MQ)]),(a=ye(this,vH))==null||a.setAttribute("data-l10n-id",ye(i_,ZP)[`${ye(this,KS,MQ)}-label`]),!ye(this,ov)){(i=ye(this,q5))==null||i.remove();return}}else{if(!ye(this,ov)&&!ye(this,U5)){t.classList.remove("done"),(l=ye(this,q5))==null||l.remove();return}t.classList.add("done"),t.setAttribute("data-l10n-id","pdfjs-editor-alt-text-edit-button")}let n=ye(this,q5);if(!n){Kt(this,q5,n=document.createElement("span")),n.className="tooltip",n.setAttribute("role","tooltip"),n.id=`alt-text-tooltip-${ye(this,dw).id}`;const o=100,c=ye(this,dw)._uiManager._signal;c.addEventListener("abort",()=>{clearTimeout(ye(this,Rj)),Kt(this,Rj,null)},{once:!0}),t.addEventListener("mouseenter",()=>{Kt(this,Rj,setTimeout(()=>{Kt(this,Rj,null),ye(this,q5).classList.add("show"),ye(this,dw)._reportTelemetry({action:"alt_text_tooltip"})},o))},{signal:c}),t.addEventListener("mouseleave",()=>{var d;ye(this,Rj)&&(clearTimeout(ye(this,Rj)),Kt(this,Rj,null)),(d=ye(this,q5))==null||d.classList.remove("show")},{signal:c})}ye(this,U5)?n.setAttribute("data-l10n-id","pdfjs-editor-alt-text-decorative-tooltip"):(n.removeAttribute("data-l10n-id"),n.textContent=ye(this,ov)),n.parentNode||t.append(n);const r=ye(this,dw).getImageForAltText();r==null||r.setAttribute("aria-describedby",n.id)},bs(i_,ZP,null),Nr(i_,"_l10n",null);let yPe=i_;var Y8,NS,vg,_H,Z8,eb,X8,XP,gre,Q8,QP,xre,J8,WA,G5,wH,jH,kN,yre,fIe,Kd,DZe,vre,FZe,OZe,Xss,Qss,zZe,BZe,$Ze,Jss,UZe,ens,tns,sns,qZe,PQ;const gm=class gm{constructor(t){bs(this,Kd);bs(this,Y8,null);bs(this,NS,null);bs(this,vg,null);bs(this,_H,!1);bs(this,Z8,!1);bs(this,eb,null);bs(this,X8,null);bs(this,XP,null);bs(this,gre,"");bs(this,Q8,!1);bs(this,QP,null);bs(this,xre,!1);bs(this,J8,!1);bs(this,WA,!1);bs(this,G5,null);bs(this,wH,0);bs(this,jH,0);bs(this,kN,null);Nr(this,"_editToolbar",null);Nr(this,"_initialOptions",Object.create(null));Nr(this,"_initialData",null);Nr(this,"_isVisible",!0);Nr(this,"_uiManager",null);Nr(this,"_focusEventsAllowed",!0);bs(this,yre,!1);bs(this,fIe,gm._zIndex++);this.parent=t.parent,this.id=t.id,this.width=this.height=null,this.pageIndex=t.parent.pageIndex,this.name=t.name,this.div=null,this._uiManager=t.uiManager,this.annotationElementId=null,this._willKeepAspectRatio=!1,this._initialOptions.isCentered=t.isCentered,this._structTreeParentId=null;const{rotation:n,rawDims:{pageWidth:r,pageHeight:a,pageX:i,pageY:l}}=this.parent.viewport;this.rotation=n,this.pageRotation=(360+n-this._uiManager.viewParameters.rotation)%360,this.pageDimensions=[r,a],this.pageTranslation=[i,l];const[o,c]=this.parentDimensions;this.x=t.x/o,this.y=t.y/c,this.isAttachedToDOM=!1,this.deleted=!1}static get _resizerKeyboardManager(){const t=gm.prototype._resizeWithKeyboard,n=_B.TRANSLATE_SMALL,r=_B.TRANSLATE_BIG;return th(this,"_resizerKeyboardManager",new Xie([[["ArrowLeft","mac+ArrowLeft"],t,{args:[-n,0]}],[["ctrl+ArrowLeft","mac+shift+ArrowLeft"],t,{args:[-r,0]}],[["ArrowRight","mac+ArrowRight"],t,{args:[n,0]}],[["ctrl+ArrowRight","mac+shift+ArrowRight"],t,{args:[r,0]}],[["ArrowUp","mac+ArrowUp"],t,{args:[0,-n]}],[["ctrl+ArrowUp","mac+shift+ArrowUp"],t,{args:[0,-r]}],[["ArrowDown","mac+ArrowDown"],t,{args:[0,n]}],[["ctrl+ArrowDown","mac+shift+ArrowDown"],t,{args:[0,r]}],[["Escape","mac+Escape"],gm.prototype._stopResizingWithKeyboard]]))}get editorType(){return Object.getPrototypeOf(this).constructor._type}static get _defaultLineColor(){return th(this,"_defaultLineColor",this._colorManager.getHexCode("CanvasText"))}static deleteAnnotationElement(t){const n=new jYn({id:t.parent.getNextId(),parent:t.parent,uiManager:t._uiManager});n.annotationElementId=t.annotationElementId,n.deleted=!0,n._uiManager.addToAnnotationStorage(n)}static initialize(t,n){if(gm._l10n??(gm._l10n=t),gm._l10nResizer||(gm._l10nResizer=Object.freeze({topLeft:"pdfjs-editor-resizer-top-left",topMiddle:"pdfjs-editor-resizer-top-middle",topRight:"pdfjs-editor-resizer-top-right",middleRight:"pdfjs-editor-resizer-middle-right",bottomRight:"pdfjs-editor-resizer-bottom-right",bottomMiddle:"pdfjs-editor-resizer-bottom-middle",bottomLeft:"pdfjs-editor-resizer-bottom-left",middleLeft:"pdfjs-editor-resizer-middle-left"})),gm._borderLineWidth!==-1)return;const r=getComputedStyle(document.documentElement);gm._borderLineWidth=parseFloat(r.getPropertyValue("--outline-width"))||0}static updateDefaultParams(t,n){}static get defaultPropertiesToUpdate(){return[]}static isHandlingMimeForPasting(t){return!1}static paste(t,n){kp("Not implemented")}get propertiesToUpdate(){return[]}get _isDraggable(){return ye(this,yre)}set _isDraggable(t){var n;Kt(this,yre,t),(n=this.div)==null||n.classList.toggle("draggable",t)}get isEnterHandled(){return!0}center(){const[t,n]=this.pageDimensions;switch(this.parentRotation){case 90:this.x-=this.height*n/(t*2),this.y+=this.width*t/(n*2);break;case 180:this.x+=this.width/2,this.y+=this.height/2;break;case 270:this.x+=this.height*n/(t*2),this.y-=this.width*t/(n*2);break;default:this.x-=this.width/2,this.y-=this.height/2;break}this.fixAndSetPosition()}addCommands(t){this._uiManager.addCommands(t)}get currentLayer(){return this._uiManager.currentLayer}setInBackground(){this.div.style.zIndex=0}setInForeground(){this.div.style.zIndex=ye(this,fIe)}setParent(t){t!==null?(this.pageIndex=t.pageIndex,this.pageDimensions=t.pageDimensions):ls(this,Kd,PQ).call(this),this.parent=t}focusin(t){this._focusEventsAllowed&&(ye(this,Q8)?Kt(this,Q8,!1):this.parent.setSelected(this))}focusout(t){var r;if(!this._focusEventsAllowed||!this.isAttachedToDOM)return;const n=t.relatedTarget;n!=null&&n.closest(`#${this.id}`)||(t.preventDefault(),(r=this.parent)!=null&&r.isMultipleSelection||this.commitOrRemove())}commitOrRemove(){this.isEmpty()?this.remove():this.commit()}commit(){this.addToAnnotationStorage()}addToAnnotationStorage(){this._uiManager.addToAnnotationStorage(this)}setAt(t,n,r,a){const[i,l]=this.parentDimensions;[r,a]=this.screenToPageTranslation(r,a),this.x=(t+r)/i,this.y=(n+a)/l,this.fixAndSetPosition()}translate(t,n){ls(this,Kd,DZe).call(this,this.parentDimensions,t,n)}translateInPage(t,n){ye(this,QP)||Kt(this,QP,[this.x,this.y]),ls(this,Kd,DZe).call(this,this.pageDimensions,t,n),this.div.scrollIntoView({block:"nearest"})}drag(t,n){ye(this,QP)||Kt(this,QP,[this.x,this.y]);const[r,a]=this.parentDimensions;if(this.x+=t/r,this.y+=n/a,this.parent&&(this.x<0||this.x>1||this.y<0||this.y>1)){const{x:d,y:u}=this.div.getBoundingClientRect();this.parent.findNewParent(this,d,u)&&(this.x-=Math.floor(this.x),this.y-=Math.floor(this.y))}let{x:i,y:l}=this;const[o,c]=this.getBaseTranslation();i+=o,l+=c,this.div.style.left=`${(100*i).toFixed(2)}%`,this.div.style.top=`${(100*l).toFixed(2)}%`,this.div.scrollIntoView({block:"nearest"})}get _hasBeenMoved(){return!!ye(this,QP)&&(ye(this,QP)[0]!==this.x||ye(this,QP)[1]!==this.y)}getBaseTranslation(){const[t,n]=this.parentDimensions,{_borderLineWidth:r}=gm,a=r/t,i=r/n;switch(this.rotation){case 90:return[-a,i];case 180:return[a,i];case 270:return[a,-i];default:return[-a,-i]}}get _mustFixPosition(){return!0}fixAndSetPosition(t=this.rotation){const[n,r]=this.pageDimensions;let{x:a,y:i,width:l,height:o}=this;if(l*=n,o*=r,a*=n,i*=r,this._mustFixPosition)switch(t){case 0:a=Math.max(0,Math.min(n-l,a)),i=Math.max(0,Math.min(r-o,i));break;case 90:a=Math.max(0,Math.min(n-o,a)),i=Math.min(r,Math.max(l,i));break;case 180:a=Math.min(n,Math.max(l,a)),i=Math.min(r,Math.max(o,i));break;case 270:a=Math.min(n,Math.max(o,a)),i=Math.max(0,Math.min(r-l,i));break}this.x=a/=n,this.y=i/=r;const[c,d]=this.getBaseTranslation();a+=c,i+=d;const{style:u}=this.div;u.left=`${(100*a).toFixed(2)}%`,u.top=`${(100*i).toFixed(2)}%`,this.moveInDOM()}screenToPageTranslation(t,n){var r;return ls(r=gm,vre,FZe).call(r,t,n,this.parentRotation)}pageTranslationToScreen(t,n){var r;return ls(r=gm,vre,FZe).call(r,t,n,360-this.parentRotation)}get parentScale(){return this._uiManager.viewParameters.realScale}get parentRotation(){return(this._uiManager.viewParameters.rotation+this.pageRotation)%360}get parentDimensions(){const{parentScale:t,pageDimensions:[n,r]}=this;return[n*t,r*t]}setDims(t,n){const[r,a]=this.parentDimensions;this.div.style.width=`${(100*t/r).toFixed(2)}%`,ye(this,Z8)||(this.div.style.height=`${(100*n/a).toFixed(2)}%`)}fixDims(){const{style:t}=this.div,{height:n,width:r}=t,a=r.endsWith("%"),i=!ye(this,Z8)&&n.endsWith("%");if(a&&i)return;const[l,o]=this.parentDimensions;a||(t.width=`${(100*parseFloat(r)/l).toFixed(2)}%`),!ye(this,Z8)&&!i&&(t.height=`${(100*parseFloat(n)/o).toFixed(2)}%`)}getInitialTranslation(){return[0,0]}altTextFinish(){var t;(t=ye(this,vg))==null||t.finish()}async addEditToolbar(){return this._editToolbar||ye(this,J8)?this._editToolbar:(this._editToolbar=new SZe(this),this.div.append(this._editToolbar.render()),ye(this,vg)&&await this._editToolbar.addAltText(ye(this,vg)),this._editToolbar)}removeEditToolbar(){var t;this._editToolbar&&(this._editToolbar.remove(),this._editToolbar=null,(t=ye(this,vg))==null||t.destroy())}addContainer(t){var r;const n=(r=this._editToolbar)==null?void 0:r.div;n?n.before(t):this.div.append(t)}getClientDimensions(){return this.div.getBoundingClientRect()}async addAltTextButton(){ye(this,vg)||(yPe.initialize(gm._l10n),Kt(this,vg,new yPe(this)),ye(this,Y8)&&(ye(this,vg).data=ye(this,Y8),Kt(this,Y8,null)),await this.addEditToolbar())}get altTextData(){var t;return(t=ye(this,vg))==null?void 0:t.data}set altTextData(t){ye(this,vg)&&(ye(this,vg).data=t)}get guessedAltText(){var t;return(t=ye(this,vg))==null?void 0:t.guessedText}async setGuessedAltText(t){var n;await((n=ye(this,vg))==null?void 0:n.setGuessedText(t))}serializeAltText(t){var n;return(n=ye(this,vg))==null?void 0:n.serialize(t)}hasAltText(){return!!ye(this,vg)&&!ye(this,vg).isEmpty()}hasAltTextData(){var t;return((t=ye(this,vg))==null?void 0:t.hasData())??!1}render(){this.div=document.createElement("div"),this.div.setAttribute("data-editor-rotation",(360-this.rotation)%360),this.div.className=this.name,this.div.setAttribute("id",this.id),this.div.tabIndex=ye(this,_H)?-1:0,this._isVisible||this.div.classList.add("hidden"),this.setInForeground(),ls(this,Kd,UZe).call(this);const[t,n]=this.parentDimensions;this.parentRotation%180!==0&&(this.div.style.maxWidth=`${(100*n/t).toFixed(2)}%`,this.div.style.maxHeight=`${(100*t/n).toFixed(2)}%`);const[r,a]=this.getInitialTranslation();return this.translate(r,a),xPe(this,this.div,["pointerdown"]),this.div}pointerdown(t){const{isMac:n}=T_.platform;if(t.button!==0||t.ctrlKey&&n){t.preventDefault();return}if(Kt(this,Q8,!0),this._isDraggable){ls(this,Kd,Jss).call(this,t);return}ls(this,Kd,$Ze).call(this,t)}get isSelected(){return this._uiManager.isSelected(this)}moveInDOM(){ye(this,G5)&&clearTimeout(ye(this,G5)),Kt(this,G5,setTimeout(()=>{var t;Kt(this,G5,null),(t=this.parent)==null||t.moveEditorInDOM(this)},0))}_setParentAndPosition(t,n,r){t.changeParent(this),this.x=n,this.y=r,this.fixAndSetPosition()}getRect(t,n,r=this.rotation){const a=this.parentScale,[i,l]=this.pageDimensions,[o,c]=this.pageTranslation,d=t/a,u=n/a,h=this.x*i,m=this.y*l,f=this.width*i,g=this.height*l;switch(r){case 0:return[h+d+o,l-m-u-g+c,h+d+f+o,l-m-u+c];case 90:return[h+u+o,l-m+d+c,h+u+g+o,l-m+d+f+c];case 180:return[h-d-f+o,l-m+u+c,h-d+o,l-m+u+g+c];case 270:return[h-u-g+o,l-m-d-f+c,h-u+o,l-m-d+c];default:throw new Error("Invalid rotation")}}getRectInCurrentCoords(t,n){const[r,a,i,l]=t,o=i-r,c=l-a;switch(this.rotation){case 0:return[r,n-l,o,c];case 90:return[r,n-a,c,o];case 180:return[i,n-a,o,c];case 270:return[i,n-l,c,o];default:throw new Error("Invalid rotation")}}onceAdded(){}isEmpty(){return!1}enableEditMode(){Kt(this,J8,!0)}disableEditMode(){Kt(this,J8,!1)}isInEditMode(){return ye(this,J8)}shouldGetKeyboardEvents(){return ye(this,WA)}needsToBeRebuilt(){return this.div&&!this.isAttachedToDOM}rebuild(){ls(this,Kd,UZe).call(this)}rotate(t){}serializeDeleted(){var t;return{id:this.annotationElementId,deleted:!0,pageIndex:this.pageIndex,popupRef:((t=this._initialData)==null?void 0:t.popupRef)||""}}serialize(t=!1,n=null){kp("An editor must be serializable")}static async deserialize(t,n,r){const a=new this.prototype.constructor({parent:n,id:n.getNextId(),uiManager:r});a.rotation=t.rotation,Kt(a,Y8,t.accessibilityData);const[i,l]=a.pageDimensions,[o,c,d,u]=a.getRectInCurrentCoords(t.rect,l);return a.x=o/i,a.y=c/l,a.width=d/i,a.height=u/l,a}get hasBeenModified(){return!!this.annotationElementId&&(this.deleted||this.serialize()!==null)}remove(){var t;if((t=ye(this,XP))==null||t.abort(),Kt(this,XP,null),this.isEmpty()||this.commit(),this.parent?this.parent.remove(this):this._uiManager.removeEditor(this),ye(this,G5)&&(clearTimeout(ye(this,G5)),Kt(this,G5,null)),ls(this,Kd,PQ).call(this),this.removeEditToolbar(),ye(this,kN)){for(const n of ye(this,kN).values())clearTimeout(n);Kt(this,kN,null)}this.parent=null}get isResizable(){return!1}makeResizable(){this.isResizable&&(ls(this,Kd,Xss).call(this),ye(this,eb).classList.remove("hidden"),xPe(this,this.div,["keydown"]))}get toolbarPosition(){return null}keydown(t){if(!this.isResizable||t.target!==this.div||t.key!=="Enter")return;this._uiManager.setSelected(this),Kt(this,X8,{savedX:this.x,savedY:this.y,savedWidth:this.width,savedHeight:this.height});const n=ye(this,eb).children;if(!ye(this,NS)){Kt(this,NS,Array.from(n));const l=ls(this,Kd,ens).bind(this),o=ls(this,Kd,tns).bind(this),c=this._uiManager._signal;for(const d of ye(this,NS)){const u=d.getAttribute("data-resizer-name");d.setAttribute("role","spinbutton"),d.addEventListener("keydown",l,{signal:c}),d.addEventListener("blur",o,{signal:c}),d.addEventListener("focus",ls(this,Kd,sns).bind(this,u),{signal:c}),d.setAttribute("data-l10n-id",gm._l10nResizer[u])}}const r=ye(this,NS)[0];let a=0;for(const l of n){if(l===r)break;a++}const i=(360-this.rotation+this.parentRotation)%360/90*(ye(this,NS).length/4);if(i!==a){if(ia)for(let o=0;o{var a,i;(a=this.div)!=null&&a.classList.contains("selectedEditor")&&((i=this._editToolbar)==null||i.show())});return}(n=this._editToolbar)==null||n.show(),(r=ye(this,vg))==null||r.toggleAltTextBadge(!1)}unselect(){var t,n,r,a,i;(t=ye(this,eb))==null||t.classList.add("hidden"),(n=this.div)==null||n.classList.remove("selectedEditor"),(r=this.div)!=null&&r.contains(document.activeElement)&&this._uiManager.currentLayer.div.focus({preventScroll:!0}),(a=this._editToolbar)==null||a.hide(),(i=ye(this,vg))==null||i.toggleAltTextBadge(!0)}updateParams(t,n){}disableEditing(){}enableEditing(){}enterInEditMode(){}getImageForAltText(){return null}get contentDiv(){return this.div}get isEditing(){return ye(this,xre)}set isEditing(t){Kt(this,xre,t),this.parent&&(t?(this.parent.setSelected(this),this.parent.setActiveEditor(this)):this.parent.setActiveEditor(null))}setAspectRatio(t,n){Kt(this,Z8,!0);const r=t/n,{style:a}=this.div;a.aspectRatio=r,a.height="auto"}static get MIN_SIZE(){return 16}static canCreateNewEmptyEditor(){return!0}get telemetryInitialData(){return{action:"added"}}get telemetryFinalData(){return null}_reportTelemetry(t,n=!1){if(n){ye(this,kN)||Kt(this,kN,new Map);const{action:r}=t;let a=ye(this,kN).get(r);a&&clearTimeout(a),a=setTimeout(()=>{this._reportTelemetry(t),ye(this,kN).delete(r),ye(this,kN).size===0&&Kt(this,kN,null)},gm._telemetryTimeout),ye(this,kN).set(r,a);return}t.type||(t.type=this.editorType),this._uiManager._eventBus.dispatch("reporttelemetry",{source:this,details:{type:"editing",data:t}})}show(t=this._isVisible){this.div.classList.toggle("hidden",!t),this._isVisible=t}enable(){this.div&&(this.div.tabIndex=0),Kt(this,_H,!1)}disable(){this.div&&(this.div.tabIndex=-1),Kt(this,_H,!0)}renderAnnotationElement(t){let n=t.container.querySelector(".annotationContent");if(!n)n=document.createElement("div"),n.classList.add("annotationContent",this.editorType),t.container.prepend(n);else if(n.nodeName==="CANVAS"){const r=n;n=document.createElement("div"),n.classList.add("annotationContent",this.editorType),r.before(n)}return n}resetAnnotationElement(t){const{firstChild:n}=t.container;(n==null?void 0:n.nodeName)==="DIV"&&n.classList.contains("annotationContent")&&n.remove()}};Y8=new WeakMap,NS=new WeakMap,vg=new WeakMap,_H=new WeakMap,Z8=new WeakMap,eb=new WeakMap,X8=new WeakMap,XP=new WeakMap,gre=new WeakMap,Q8=new WeakMap,QP=new WeakMap,xre=new WeakMap,J8=new WeakMap,WA=new WeakMap,G5=new WeakMap,wH=new WeakMap,jH=new WeakMap,kN=new WeakMap,yre=new WeakMap,fIe=new WeakMap,Kd=new WeakSet,DZe=function([t,n],r,a){[r,a]=this.screenToPageTranslation(r,a),this.x+=r/t,this.y+=a/n,this.fixAndSetPosition()},vre=new WeakSet,FZe=function(t,n,r){switch(r){case 90:return[n,-t];case 180:return[-t,-n];case 270:return[-n,t];default:return[t,n]}},OZe=function(t){switch(t){case 90:{const[n,r]=this.pageDimensions;return[0,-n/r,r/n,0]}case 180:return[-1,0,0,-1];case 270:{const[n,r]=this.pageDimensions;return[0,n/r,-r/n,0]}default:return[1,0,0,1]}},Xss=function(){if(ye(this,eb))return;Kt(this,eb,document.createElement("div")),ye(this,eb).classList.add("resizers");const t=this._willKeepAspectRatio?["topLeft","topRight","bottomRight","bottomLeft"]:["topLeft","topMiddle","topRight","middleRight","bottomRight","bottomMiddle","bottomLeft","middleLeft"],n=this._uiManager._signal;for(const r of t){const a=document.createElement("div");ye(this,eb).append(a),a.classList.add("resizer",r),a.setAttribute("data-resizer-name",r),a.addEventListener("pointerdown",ls(this,Kd,Qss).bind(this,r),{signal:n}),a.addEventListener("contextmenu",yk,{signal:n}),a.tabIndex=-1}this.div.prepend(ye(this,eb))},Qss=function(t,n){var g;n.preventDefault();const{isMac:r}=T_.platform;if(n.button!==0||n.ctrlKey&&r)return;(g=ye(this,vg))==null||g.toggle(!1);const a=this._isDraggable;this._isDraggable=!1;const i=new AbortController,l=this._uiManager.combinedSignal(i);this.parent.togglePointerEvents(!1),window.addEventListener("pointermove",ls(this,Kd,BZe).bind(this,t),{passive:!0,capture:!0,signal:l}),window.addEventListener("contextmenu",yk,{signal:l});const o=this.x,c=this.y,d=this.width,u=this.height,h=this.parent.div.style.cursor,m=this.div.style.cursor;this.div.style.cursor=this.parent.div.style.cursor=window.getComputedStyle(n.target).cursor;const f=()=>{var x;i.abort(),this.parent.togglePointerEvents(!0),(x=ye(this,vg))==null||x.toggle(!0),this._isDraggable=a,this.parent.div.style.cursor=h,this.div.style.cursor=m,ls(this,Kd,zZe).call(this,o,c,d,u)};window.addEventListener("pointerup",f,{signal:l}),window.addEventListener("blur",f,{signal:l})},zZe=function(t,n,r,a){const i=this.x,l=this.y,o=this.width,c=this.height;i===t&&l===n&&o===r&&c===a||this.addCommands({cmd:()=>{this.width=o,this.height=c,this.x=i,this.y=l;const[d,u]=this.parentDimensions;this.setDims(d*o,u*c),this.fixAndSetPosition()},undo:()=>{this.width=r,this.height=a,this.x=t,this.y=n;const[d,u]=this.parentDimensions;this.setDims(d*r,u*a),this.fixAndSetPosition()},mustExec:!0})},BZe=function(t,n){const[r,a]=this.parentDimensions,i=this.x,l=this.y,o=this.width,c=this.height,d=gm.MIN_SIZE/r,u=gm.MIN_SIZE/a,h=X=>Math.round(X*1e4)/1e4,m=ls(this,Kd,OZe).call(this,this.rotation),f=(X,ae)=>[m[0]*X+m[2]*ae,m[1]*X+m[3]*ae],g=ls(this,Kd,OZe).call(this,360-this.rotation),x=(X,ae)=>[g[0]*X+g[2]*ae,g[1]*X+g[3]*ae];let y,v,b=!1,w=!1;switch(t){case"topLeft":b=!0,y=(X,ae)=>[0,0],v=(X,ae)=>[X,ae];break;case"topMiddle":y=(X,ae)=>[X/2,0],v=(X,ae)=>[X/2,ae];break;case"topRight":b=!0,y=(X,ae)=>[X,0],v=(X,ae)=>[0,ae];break;case"middleRight":w=!0,y=(X,ae)=>[X,ae/2],v=(X,ae)=>[0,ae/2];break;case"bottomRight":b=!0,y=(X,ae)=>[X,ae],v=(X,ae)=>[0,0];break;case"bottomMiddle":y=(X,ae)=>[X/2,ae],v=(X,ae)=>[X/2,0];break;case"bottomLeft":b=!0,y=(X,ae)=>[0,ae],v=(X,ae)=>[X,0];break;case"middleLeft":w=!0,y=(X,ae)=>[0,ae/2],v=(X,ae)=>[X,ae/2];break}const S=y(o,c),C=v(o,c);let E=f(...C);const I=h(i+E[0]),P=h(l+E[1]);let R=1,D=1,[O,U]=this.screenToPageTranslation(n.movementX,n.movementY);if([O,U]=x(O/r,U/a),b){const X=Math.hypot(o,c);R=D=Math.max(Math.min(Math.hypot(C[0]-S[0]-O,C[1]-S[1]-U)/X,1/o,1/c),d/o,u/c)}else w?R=Math.max(d,Math.min(1,Math.abs(C[0]-S[0]-O)))/o:D=Math.max(u,Math.min(1,Math.abs(C[1]-S[1]-U)))/c;const W=h(o*R),V=h(c*D);E=f(...v(W,V));const G=I-E[0],Y=P-E[1];this.width=W,this.height=V,this.x=G,this.y=Y,this.setDims(r*W,a*V),this.fixAndSetPosition()},$Ze=function(t){const{isMac:n}=T_.platform;t.ctrlKey&&!n||t.shiftKey||t.metaKey&&n?this.parent.toggleSelected(this):this.parent.setSelected(this)},Jss=function(t){const{isSelected:n}=this;this._uiManager.setUpDragSession();const r=new AbortController,a=this._uiManager.combinedSignal(r);if(n){this.div.classList.add("moving"),Kt(this,wH,t.clientX),Kt(this,jH,t.clientY);const l=o=>{const{clientX:c,clientY:d}=o,[u,h]=this.screenToPageTranslation(c-ye(this,wH),d-ye(this,jH));Kt(this,wH,c),Kt(this,jH,d),this._uiManager.dragSelectedEditors(u,h)};window.addEventListener("pointermove",l,{passive:!0,capture:!0,signal:a})}const i=()=>{r.abort(),n&&this.div.classList.remove("moving"),Kt(this,Q8,!1),this._uiManager.endDragSession()||ls(this,Kd,$Ze).call(this,t)};window.addEventListener("pointerup",i,{signal:a}),window.addEventListener("blur",i,{signal:a})},UZe=function(){if(ye(this,XP)||!this.div)return;Kt(this,XP,new AbortController);const t=this._uiManager.combinedSignal(ye(this,XP));this.div.addEventListener("focusin",this.focusin.bind(this),{signal:t}),this.div.addEventListener("focusout",this.focusout.bind(this),{signal:t})},ens=function(t){gm._resizerKeyboardManager.exec(this,t)},tns=function(t){var n;ye(this,WA)&&((n=t.relatedTarget)==null?void 0:n.parentNode)!==ye(this,eb)&&ls(this,Kd,PQ).call(this)},sns=function(t){Kt(this,gre,ye(this,WA)?t:"")},qZe=function(t){if(ye(this,NS))for(const n of ye(this,NS))n.tabIndex=t},PQ=function(){if(Kt(this,WA,!1),ls(this,Kd,qZe).call(this,-1),ye(this,X8)){const{savedX:t,savedY:n,savedWidth:r,savedHeight:a}=ye(this,X8);ls(this,Kd,zZe).call(this,t,n,r,a),Kt(this,X8,null)}},bs(gm,vre),Nr(gm,"_l10n",null),Nr(gm,"_l10nResizer",null),Nr(gm,"_borderLineWidth",-1),Nr(gm,"_colorManager",new EZe),Nr(gm,"_zIndex",1),Nr(gm,"_telemetryTimeout",1e3);let Em=gm;class jYn extends Em{constructor(t){super(t),this.annotationElementId=t.annotationElementId,this.deleted=!0}serialize(){return this.serializeDeleted()}}const l3t=3285377520,fN=4294901760,l5=65535;class nns{constructor(t){this.h1=t?t&4294967295:l3t,this.h2=t?t&4294967295:l3t}update(t){let n,r;if(typeof t=="string"){n=new Uint8Array(t.length*2),r=0;for(let x=0,y=t.length;x>>8,n[r++]=v&255)}}else if(ArrayBuffer.isView(t))n=t.slice(),r=n.byteLength;else throw new Error("Invalid data format, must be a string or TypedArray.");const a=r>>2,i=r-a*4,l=new Uint32Array(n.buffer,0,a);let o=0,c=0,d=this.h1,u=this.h2;const h=3432918353,m=461845907,f=h&l5,g=m&l5;for(let x=0;x>>17,o=o*m&fN|o*g&l5,d^=o,d=d<<13|d>>>19,d=d*5+3864292196):(c=l[x],c=c*h&fN|c*f&l5,c=c<<15|c>>>17,c=c*m&fN|c*g&l5,u^=c,u=u<<13|u>>>19,u=u*5+3864292196);switch(o=0,i){case 3:o^=n[a*4+2]<<16;case 2:o^=n[a*4+1]<<8;case 1:o^=n[a*4],o=o*h&fN|o*f&l5,o=o<<15|o>>>17,o=o*m&fN|o*g&l5,a&1?d^=o:u^=o}this.h1=d,this.h2=u}hexdigest(){let t=this.h1,n=this.h2;return t^=n>>>1,t=t*3981806797&fN|t*36045&l5,n=n*4283543511&fN|((n<<16|t>>>16)*2950163797&fN)>>>16,t^=n>>>1,t=t*444984403&fN|t*60499&l5,n=n*3301882366&fN|((n<<16|t>>>16)*3120437893&fN)>>>16,t^=n>>>1,(t>>>0).toString(16).padStart(8,"0")+(n>>>0).toString(16).padStart(8,"0")}}const VZe=Object.freeze({map:null,hash:"",transfer:void 0});var ez,tz,lv,pIe,rns;class Bot{constructor(){bs(this,pIe);bs(this,ez,!1);bs(this,tz,null);bs(this,lv,new Map);this.onSetModified=null,this.onResetModified=null,this.onAnnotationEditor=null}getValue(t,n){const r=ye(this,lv).get(t);return r===void 0?n:Object.assign(n,r)}getRawValue(t){return ye(this,lv).get(t)}remove(t){if(ye(this,lv).delete(t),ye(this,lv).size===0&&this.resetModified(),typeof this.onAnnotationEditor=="function"){for(const n of ye(this,lv).values())if(n instanceof Em)return;this.onAnnotationEditor(null)}}setValue(t,n){const r=ye(this,lv).get(t);let a=!1;if(r!==void 0)for(const[i,l]of Object.entries(n))r[i]!==l&&(a=!0,r[i]=l);else a=!0,ye(this,lv).set(t,n);a&&ls(this,pIe,rns).call(this),n instanceof Em&&typeof this.onAnnotationEditor=="function"&&this.onAnnotationEditor(n.constructor._type)}has(t){return ye(this,lv).has(t)}getAll(){return ye(this,lv).size>0?Lot(ye(this,lv)):null}setAll(t){for(const[n,r]of Object.entries(t))this.setValue(n,r)}get size(){return ye(this,lv).size}resetModified(){ye(this,ez)&&(Kt(this,ez,!1),typeof this.onResetModified=="function"&&this.onResetModified())}get print(){return new ans(this)}get serializable(){if(ye(this,lv).size===0)return VZe;const t=new Map,n=new nns,r=[],a=Object.create(null);let i=!1;for(const[l,o]of ye(this,lv)){const c=o instanceof Em?o.serialize(!1,a):o;c&&(t.set(l,c),n.update(`${l}:${JSON.stringify(c)}`),i||(i=!!c.bitmap))}if(i)for(const l of t.values())l.bitmap&&r.push(l.bitmap);return t.size>0?{map:t,hash:n.hexdigest(),transfer:r}:VZe}get editorStats(){let t=null;const n=new Map;for(const r of ye(this,lv).values()){if(!(r instanceof Em))continue;const a=r.telemetryFinalData;if(!a)continue;const{type:i}=a;n.has(i)||n.set(i,Object.getPrototypeOf(r).constructor),t||(t=Object.create(null));const l=t[i]||(t[i]=new Map);for(const[o,c]of Object.entries(a)){if(o==="type")continue;let d=l.get(o);d||(d=new Map,l.set(o,d));const u=d.get(c)??0;d.set(c,u+1)}}for(const[r,a]of n)t[r]=a.computeTelemetryFinalData(t[r]);return t}resetModifiedIds(){Kt(this,tz,null)}get modifiedIds(){if(ye(this,tz))return ye(this,tz);const t=[];for(const n of ye(this,lv).values())!(n instanceof Em)||!n.annotationElementId||!n.serialize()||t.push(n.annotationElementId);return Kt(this,tz,{ids:new Set(t),hash:t.join(",")})}}ez=new WeakMap,tz=new WeakMap,lv=new WeakMap,pIe=new WeakSet,rns=function(){ye(this,ez)||(Kt(this,ez,!0),typeof this.onSetModified=="function"&&this.onSetModified())};var bre;class ans extends Bot{constructor(n){super();bs(this,bre);const{map:r,hash:a,transfer:i}=n.serializable,l=structuredClone(r,i?{transfer:i}:null);Kt(this,bre,{map:l,hash:a,transfer:i})}get print(){kp("Should not call PrintAnnotationStorage.print")}get serializable(){return ye(this,bre)}get modifiedIds(){return th(this,"modifiedIds",{ids:new Set,hash:""})}}bre=new WeakMap;var NH;class NYn{constructor({ownerDocument:t=globalThis.document,styleElement:n=null}){bs(this,NH,new Set);this._document=t,this.nativeFontFaces=new Set,this.styleElement=null,this.loadingRequests=[],this.loadTestFontId=0}addNativeFontFace(t){this.nativeFontFaces.add(t),this._document.fonts.add(t)}removeNativeFontFace(t){this.nativeFontFaces.delete(t),this._document.fonts.delete(t)}insertRule(t){this.styleElement||(this.styleElement=this._document.createElement("style"),this._document.documentElement.getElementsByTagName("head")[0].append(this.styleElement));const n=this.styleElement.sheet;n.insertRule(t,n.cssRules.length)}clear(){for(const t of this.nativeFontFaces)this._document.fonts.delete(t);this.nativeFontFaces.clear(),ye(this,NH).clear(),this.styleElement&&(this.styleElement.remove(),this.styleElement=null)}async loadSystemFont({systemFontInfo:t,_inspectFont:n}){if(!(!t||ye(this,NH).has(t.loadedName))){if(j0(!this.disableFontFace,"loadSystemFont shouldn't be called when `disableFontFace` is set."),this.isFontLoadingAPISupported){const{loadedName:r,src:a,style:i}=t,l=new FontFace(r,a,i);this.addNativeFontFace(l);try{await l.load(),ye(this,NH).add(r),n==null||n(t)}catch{nu(`Cannot load system font: ${t.baseFontName}, installing it could help to improve PDF rendering.`),this.removeNativeFontFace(l)}return}kp("Not implemented: loadSystemFont without the Font Loading API.")}}async bind(t){if(t.attached||t.missingFile&&!t.systemFontInfo)return;if(t.attached=!0,t.systemFontInfo){await this.loadSystemFont(t);return}if(this.isFontLoadingAPISupported){const r=t.createNativeFontFace();if(r){this.addNativeFontFace(r);try{await r.loaded}catch(a){throw nu(`Failed to load font '${r.family}': '${a}'.`),t.disableFontFace=!0,a}}return}const n=t.createFontFaceRule();if(n){if(this.insertRule(n),this.isSyncFontLoadingSupported)return;await new Promise(r=>{const a=this._queueLoadingCallback(r);this._prepareFontLoadEvent(t,a)})}}get isFontLoadingAPISupported(){var n;const t=!!((n=this._document)!=null&&n.fonts);return th(this,"isFontLoadingAPISupported",t)}get isSyncFontLoadingSupported(){let t=!1;return(y1||typeof navigator<"u"&&typeof(navigator==null?void 0:navigator.userAgent)=="string"&&/Mozilla\/5.0.*?rv:\d+.*? Gecko/.test(navigator.userAgent))&&(t=!0),th(this,"isSyncFontLoadingSupported",t)}_queueLoadingCallback(t){function n(){for(j0(!a.done,"completeRequest() cannot be called twice."),a.done=!0;r.length>0&&r[0].done;){const i=r.shift();setTimeout(i.callback,0)}}const{loadingRequests:r}=this,a={done:!1,complete:n,callback:t};return r.push(a),a}get _loadTestFont(){const t=atob("T1RUTwALAIAAAwAwQ0ZGIDHtZg4AAAOYAAAAgUZGVE1lkzZwAAAEHAAAABxHREVGABQAFQAABDgAAAAeT1MvMlYNYwkAAAEgAAAAYGNtYXABDQLUAAACNAAAAUJoZWFk/xVFDQAAALwAAAA2aGhlYQdkA+oAAAD0AAAAJGhtdHgD6AAAAAAEWAAAAAZtYXhwAAJQAAAAARgAAAAGbmFtZVjmdH4AAAGAAAAAsXBvc3T/hgAzAAADeAAAACAAAQAAAAEAALZRFsRfDzz1AAsD6AAAAADOBOTLAAAAAM4KHDwAAAAAA+gDIQAAAAgAAgAAAAAAAAABAAADIQAAAFoD6AAAAAAD6AABAAAAAAAAAAAAAAAAAAAAAQAAUAAAAgAAAAQD6AH0AAUAAAKKArwAAACMAooCvAAAAeAAMQECAAACAAYJAAAAAAAAAAAAAQAAAAAAAAAAAAAAAFBmRWQAwAAuAC4DIP84AFoDIQAAAAAAAQAAAAAAAAAAACAAIAABAAAADgCuAAEAAAAAAAAAAQAAAAEAAAAAAAEAAQAAAAEAAAAAAAIAAQAAAAEAAAAAAAMAAQAAAAEAAAAAAAQAAQAAAAEAAAAAAAUAAQAAAAEAAAAAAAYAAQAAAAMAAQQJAAAAAgABAAMAAQQJAAEAAgABAAMAAQQJAAIAAgABAAMAAQQJAAMAAgABAAMAAQQJAAQAAgABAAMAAQQJAAUAAgABAAMAAQQJAAYAAgABWABYAAAAAAAAAwAAAAMAAAAcAAEAAAAAADwAAwABAAAAHAAEACAAAAAEAAQAAQAAAC7//wAAAC7////TAAEAAAAAAAABBgAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMAAAAAAAD/gwAyAAAAAQAAAAAAAAAAAAAAAAAAAAABAAQEAAEBAQJYAAEBASH4DwD4GwHEAvgcA/gXBIwMAYuL+nz5tQXkD5j3CBLnEQACAQEBIVhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYAAABAQAADwACAQEEE/t3Dov6fAH6fAT+fPp8+nwHDosMCvm1Cvm1DAz6fBQAAAAAAAABAAAAAMmJbzEAAAAAzgTjFQAAAADOBOQpAAEAAAAAAAAADAAUAAQAAAABAAAAAgABAAAAAAAAAAAD6AAAAAAAAA==");return th(this,"_loadTestFont",t)}_prepareFontLoadEvent(t,n){function r(S,C){return S.charCodeAt(C)<<24|S.charCodeAt(C+1)<<16|S.charCodeAt(C+2)<<8|S.charCodeAt(C+3)&255}function a(S,C,E,I){const P=S.substring(0,C),R=S.substring(C+E);return P+I+R}let i,l;const o=this._document.createElement("canvas");o.width=1,o.height=1;const c=o.getContext("2d");let d=0;function u(S,C){if(++d>30){nu("Load test font never loaded."),C();return}if(c.font="30px "+S,c.fillText(".",0,20),c.getImageData(0,0,1,1).data[3]>0){C();return}setTimeout(u.bind(null,S,C))}const h=`lt${Date.now()}${this.loadTestFontId++}`;let m=this._loadTestFont;m=a(m,976,h.length,h);const g=16,x=1482184792;let y=r(m,g);for(i=0,l=h.length-3;i{w.remove(),n.complete()})}}NH=new WeakMap;class kYn{constructor(t,{disableFontFace:n=!1,inspectFont:r=null}){this.compiledGlyphs=Object.create(null);for(const a in t)this[a]=t[a];this.disableFontFace=n===!0,this._inspectFont=r}createNativeFontFace(){var n;if(!this.data||this.disableFontFace)return null;let t;if(!this.cssFontInfo)t=new FontFace(this.loadedName,this.data,{});else{const r={weight:this.cssFontInfo.fontWeight};this.cssFontInfo.italicAngle&&(r.style=`oblique ${this.cssFontInfo.italicAngle}deg`),t=new FontFace(this.cssFontInfo.fontFamily,this.data,r)}return(n=this._inspectFont)==null||n.call(this,this),t}createFontFaceRule(){var r;if(!this.data||this.disableFontFace)return null;const t=`url(data:${this.mimetype};base64,${fYn(this.data)});`;let n;if(!this.cssFontInfo)n=`@font-face {font-family:"${this.loadedName}";src:${t}}`;else{let a=`font-weight: ${this.cssFontInfo.fontWeight};`;this.cssFontInfo.italicAngle&&(a+=`font-style: oblique ${this.cssFontInfo.italicAngle}deg;`),n=`@font-face {font-family:"${this.cssFontInfo.fontFamily}";${a}src:${t}}`}return(r=this._inspectFont)==null||r.call(this,this,t),n}getPathGenerator(t,n){if(this.compiledGlyphs[n]!==void 0)return this.compiledGlyphs[n];let r;try{r=t.get(this.loadedName+"_path_"+n)}catch(i){nu(`getPathGenerator - ignoring character: "${i}".`)}if(!Array.isArray(r)||r.length===0)return this.compiledGlyphs[n]=function(i,l){};const a=[];for(let i=0,l=r.length;if.bezierCurveTo(o,c,d,u,h,m)),i+=6}break;case dA.MOVE_TO:{const[o,c]=r.slice(i,i+2);a.push(d=>d.moveTo(o,c)),i+=2}break;case dA.LINE_TO:{const[o,c]=r.slice(i,i+2);a.push(d=>d.lineTo(o,c)),i+=2}break;case dA.QUADRATIC_CURVE_TO:{const[o,c,d,u]=r.slice(i,i+4);a.push(h=>h.quadraticCurveTo(o,c,d,u)),i+=4}break;case dA.RESTORE:a.push(o=>o.restore());break;case dA.SAVE:a.push(o=>o.save());break;case dA.SCALE:j0(a.length===2,"Scale command is only valid at the third position.");break;case dA.TRANSFORM:{const[o,c,d,u,h,m]=r.slice(i,i+6);a.push(f=>f.transform(o,c,d,u,h,m)),i+=6}break;case dA.TRANSLATE:{const[o,c]=r.slice(i,i+2);a.push(d=>d.translate(o,c)),i+=2}break}return this.compiledGlyphs[n]=function(l,o){a[0](l),a[1](l),l.scale(o,-o);for(let c=2,d=a.length;c({cMapData:r,isCompressed:this.isCompressed})).catch(r=>{throw new Error(`Unable to load ${this.isCompressed?"binary ":""}CMap at: ${n}`)})}async _fetch(t){kp("Abstract method `_fetch` called.")}}class lns extends ons{async _fetch(t){const n=await qDe(t,this.isCompressed?"arraybuffer":"text");return n instanceof ArrayBuffer?new Uint8Array(n):UDe(n)}}class cns{addFilter(t){return"none"}addHCMFilter(t,n){return"none"}addAlphaFilter(t){return"none"}addLuminosityFilter(t){return"none"}addHighlightHCMFilter(t,n,r,a,i){return"none"}destroy(t=!1){}}var sz,nz,W5,KA,o1,gIe,rz,jo,n1,AU,EU,H3e,TU,dns,HZe,MU,IQ,LQ,GZe,RQ;class CYn extends cns{constructor({docId:n,ownerDocument:r=globalThis.document}){super();bs(this,jo);bs(this,sz);bs(this,nz);bs(this,W5);bs(this,KA);bs(this,o1);bs(this,gIe);bs(this,rz,0);Kt(this,KA,n),Kt(this,o1,r)}addFilter(n){if(!n)return"none";let r=ye(this,jo,n1).get(n);if(r)return r;const[a,i,l]=ls(this,jo,H3e).call(this,n),o=n.length===1?a:`${a}${i}${l}`;if(r=ye(this,jo,n1).get(o),r)return ye(this,jo,n1).set(n,r),r;const c=`g_${ye(this,KA)}_transfer_map_${J0(this,rz)._++}`,d=ls(this,jo,TU).call(this,c);ye(this,jo,n1).set(n,d),ye(this,jo,n1).set(o,d);const u=ls(this,jo,MU).call(this,c);return ls(this,jo,LQ).call(this,a,i,l,u),d}addHCMFilter(n,r){var g;const a=`${n}-${r}`,i="base";let l=ye(this,jo,AU).get(i);if((l==null?void 0:l.key)===a||(l?((g=l.filter)==null||g.remove(),l.key=a,l.url="none",l.filter=null):(l={key:a,url:"none",filter:null},ye(this,jo,AU).set(i,l)),!n||!r))return l.url;const o=ls(this,jo,RQ).call(this,n);n=ol.makeHexColor(...o);const c=ls(this,jo,RQ).call(this,r);if(r=ol.makeHexColor(...c),ye(this,jo,EU).style.color="",n==="#000000"&&r==="#ffffff"||n===r)return l.url;const d=new Array(256);for(let x=0;x<=255;x++){const y=x/255;d[x]=y<=.03928?y/12.92:((y+.055)/1.055)**2.4}const u=d.join(","),h=`g_${ye(this,KA)}_hcm_filter`,m=l.filter=ls(this,jo,MU).call(this,h);ls(this,jo,LQ).call(this,u,u,u,m),ls(this,jo,HZe).call(this,m);const f=(x,y)=>{const v=o[x]/255,b=c[x]/255,w=new Array(y+1);for(let S=0;S<=y;S++)w[S]=v+S/y*(b-v);return w.join(",")};return ls(this,jo,LQ).call(this,f(0,5),f(1,5),f(2,5),m),l.url=ls(this,jo,TU).call(this,h),l.url}addAlphaFilter(n){let r=ye(this,jo,n1).get(n);if(r)return r;const[a]=ls(this,jo,H3e).call(this,[n]),i=`alpha_${a}`;if(r=ye(this,jo,n1).get(i),r)return ye(this,jo,n1).set(n,r),r;const l=`g_${ye(this,KA)}_alpha_map_${J0(this,rz)._++}`,o=ls(this,jo,TU).call(this,l);ye(this,jo,n1).set(n,o),ye(this,jo,n1).set(i,o);const c=ls(this,jo,MU).call(this,l);return ls(this,jo,GZe).call(this,a,c),o}addLuminosityFilter(n){let r=ye(this,jo,n1).get(n||"luminosity");if(r)return r;let a,i;if(n?([a]=ls(this,jo,H3e).call(this,[n]),i=`luminosity_${a}`):i="luminosity",r=ye(this,jo,n1).get(i),r)return ye(this,jo,n1).set(n,r),r;const l=`g_${ye(this,KA)}_luminosity_map_${J0(this,rz)._++}`,o=ls(this,jo,TU).call(this,l);ye(this,jo,n1).set(n,o),ye(this,jo,n1).set(i,o);const c=ls(this,jo,MU).call(this,l);return ls(this,jo,dns).call(this,c),n&&ls(this,jo,GZe).call(this,a,c),o}addHighlightHCMFilter(n,r,a,i,l){var b;const o=`${r}-${a}-${i}-${l}`;let c=ye(this,jo,AU).get(n);if((c==null?void 0:c.key)===o||(c?((b=c.filter)==null||b.remove(),c.key=o,c.url="none",c.filter=null):(c={key:o,url:"none",filter:null},ye(this,jo,AU).set(n,c)),!r||!a))return c.url;const[d,u]=[r,a].map(ls(this,jo,RQ).bind(this));let h=Math.round(.2126*d[0]+.7152*d[1]+.0722*d[2]),m=Math.round(.2126*u[0]+.7152*u[1]+.0722*u[2]),[f,g]=[i,l].map(ls(this,jo,RQ).bind(this));m{const E=new Array(256),I=(m-h)/C,P=w/255,R=(S-w)/(255*C);let D=0;for(let O=0;O<=C;O++){const U=Math.round(h+O*I),W=P+O*R;for(let V=D;V<=U;V++)E[V]=W;D=U+1}for(let O=D;O<256;O++)E[O]=E[D-1];return E.join(",")},y=`g_${ye(this,KA)}_hcm_${n}_filter`,v=c.filter=ls(this,jo,MU).call(this,y);return ls(this,jo,HZe).call(this,v),ls(this,jo,LQ).call(this,x(f[0],g[0],5),x(f[1],g[1],5),x(f[2],g[2],5),v),c.url=ls(this,jo,TU).call(this,y),c.url}destroy(n=!1){n&&ye(this,jo,AU).size!==0||(ye(this,W5)&&(ye(this,W5).parentNode.parentNode.remove(),Kt(this,W5,null)),ye(this,nz)&&(ye(this,nz).clear(),Kt(this,nz,null)),Kt(this,rz,0))}}sz=new WeakMap,nz=new WeakMap,W5=new WeakMap,KA=new WeakMap,o1=new WeakMap,gIe=new WeakMap,rz=new WeakMap,jo=new WeakSet,n1=function(){return ye(this,nz)||Kt(this,nz,new Map)},AU=function(){return ye(this,gIe)||Kt(this,gIe,new Map)},EU=function(){if(!ye(this,W5)){const n=ye(this,o1).createElement("div"),{style:r}=n;r.visibility="hidden",r.contain="strict",r.width=r.height=0,r.position="absolute",r.top=r.left=0,r.zIndex=-1;const a=ye(this,o1).createElementNS(jA,"svg");a.setAttribute("width",0),a.setAttribute("height",0),Kt(this,W5,ye(this,o1).createElementNS(jA,"defs")),n.append(a),a.append(ye(this,W5)),ye(this,o1).body.append(n)}return ye(this,W5)},H3e=function(n){if(n.length===1){const d=n[0],u=new Array(256);for(let m=0;m<256;m++)u[m]=d[m]/255;const h=u.join(",");return[h,h,h]}const[r,a,i]=n,l=new Array(256),o=new Array(256),c=new Array(256);for(let d=0;d<256;d++)l[d]=r[d]/255,o[d]=a[d]/255,c[d]=i[d]/255;return[l.join(","),o.join(","),c.join(",")]},TU=function(n){if(ye(this,sz)===void 0){Kt(this,sz,"");const r=ye(this,o1).URL;r!==ye(this,o1).baseURI&&(VDe(r)?nu('#createUrl: ignore "data:"-URL for performance reasons.'):Kt(this,sz,r.split("#",1)[0]))}return`url(${ye(this,sz)}#${n})`},dns=function(n){const r=ye(this,o1).createElementNS(jA,"feColorMatrix");r.setAttribute("type","matrix"),r.setAttribute("values","0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.3 0.59 0.11 0 0"),n.append(r)},HZe=function(n){const r=ye(this,o1).createElementNS(jA,"feColorMatrix");r.setAttribute("type","matrix"),r.setAttribute("values","0.2126 0.7152 0.0722 0 0 0.2126 0.7152 0.0722 0 0 0.2126 0.7152 0.0722 0 0 0 0 0 1 0"),n.append(r)},MU=function(n){const r=ye(this,o1).createElementNS(jA,"filter");return r.setAttribute("color-interpolation-filters","sRGB"),r.setAttribute("id",n),ye(this,jo,EU).append(r),r},IQ=function(n,r,a){const i=ye(this,o1).createElementNS(jA,r);i.setAttribute("type","discrete"),i.setAttribute("tableValues",a),n.append(i)},LQ=function(n,r,a,i){const l=ye(this,o1).createElementNS(jA,"feComponentTransfer");i.append(l),ls(this,jo,IQ).call(this,l,"feFuncR",n),ls(this,jo,IQ).call(this,l,"feFuncG",r),ls(this,jo,IQ).call(this,l,"feFuncB",a)},GZe=function(n,r){const a=ye(this,o1).createElementNS(jA,"feComponentTransfer");r.append(a),ls(this,jo,IQ).call(this,a,"feFuncA",n)},RQ=function(n){return ye(this,jo,EU).style.color=n,zot(getComputedStyle(ye(this,jo,EU)).getPropertyValue("color"))};class uns{constructor({baseUrl:t=null}){this.baseUrl=t}async fetch({filename:t}){if(!this.baseUrl)throw new Error("Ensure that the `standardFontDataUrl` API parameter is provided.");if(!t)throw new Error("Font filename must be specified.");const n=`${this.baseUrl}${t}`;return this._fetch(n).catch(r=>{throw new Error(`Unable to load font data at: ${n}`)})}async _fetch(t){kp("Abstract method `_fetch` called.")}}class hns extends uns{async _fetch(t){const n=await qDe(t,"arraybuffer");return new Uint8Array(n)}}if(y1){var WZe=Promise.withResolvers(),ote=null;(async()=>{const t=await ri(()=>import("./__vite-browser-external-BIHI7g3E.js"),[]),n=await ri(()=>import("./__vite-browser-external-BIHI7g3E.js"),[]),r=await ri(()=>import("./__vite-browser-external-BIHI7g3E.js"),[]),a=await ri(()=>import("./__vite-browser-external-BIHI7g3E.js"),[]);let i,l;return new Map(Object.entries({fs:t,http:n,https:r,url:a,canvas:i,path2d:l}))})().then(t=>{ote=t,WZe.resolve()},t=>{nu(`loadPackages: ${t}`),ote=new Map,WZe.resolve()})}class HL{static get promise(){return WZe.promise}static get(t){return ote==null?void 0:ote.get(t)}}async function mns(s){const n=await HL.get("fs").promises.readFile(s);return new Uint8Array(n)}class AYn extends cns{}class EYn extends ins{_createCanvas(t,n){return HL.get("canvas").createCanvas(t,n)}}class TYn extends ons{async _fetch(t){return mns(t)}}class MYn extends uns{async _fetch(t){return mns(t)}}const f_={FILL:"Fill",STROKE:"Stroke",SHADING:"Shading"};function KZe(s,t){if(!t)return;const n=t[2]-t[0],r=t[3]-t[1],a=new Path2D;a.rect(t[0],t[1],n,r),s.clip(a)}class $ot{getPattern(){kp("Abstract method `getPattern` called.")}}class PYn extends $ot{constructor(t){super(),this._type=t[1],this._bbox=t[2],this._colorStops=t[3],this._p0=t[4],this._p1=t[5],this._r0=t[6],this._r1=t[7],this.matrix=null}_createGradient(t){let n;this._type==="axial"?n=t.createLinearGradient(this._p0[0],this._p0[1],this._p1[0],this._p1[1]):this._type==="radial"&&(n=t.createRadialGradient(this._p0[0],this._p0[1],this._r0,this._p1[0],this._p1[1],this._r1));for(const r of this._colorStops)n.addColorStop(r[0],r[1]);return n}getPattern(t,n,r,a){let i;if(a===f_.STROKE||a===f_.FILL){const l=n.current.getClippedPathBoundingBox(a,wg(t))||[0,0,0,0],o=Math.ceil(l[2]-l[0])||1,c=Math.ceil(l[3]-l[1])||1,d=n.cachedCanvases.getCanvas("pattern",o,c),u=d.context;u.clearRect(0,0,u.canvas.width,u.canvas.height),u.beginPath(),u.rect(0,0,u.canvas.width,u.canvas.height),u.translate(-l[0],-l[1]),r=ol.transform(r,[1,0,0,1,l[0],l[1]]),u.transform(...n.baseTransform),this.matrix&&u.transform(...this.matrix),KZe(u,this._bbox),u.fillStyle=this._createGradient(u),u.fill(),i=t.createPattern(d.canvas,"no-repeat");const h=new DOMMatrix(r);i.setTransform(h)}else KZe(t,this._bbox),i=this._createGradient(t);return i}}function O$e(s,t,n,r,a,i,l,o){const c=t.coords,d=t.colors,u=s.data,h=s.width*4;let m;c[n+1]>c[r+1]&&(m=n,n=r,r=m,m=i,i=l,l=m),c[r+1]>c[a+1]&&(m=r,r=a,a=m,m=l,l=o,o=m),c[n+1]>c[r+1]&&(m=n,n=r,r=m,m=i,i=l,l=m);const f=(c[n]+t.offsetX)*t.scaleX,g=(c[n+1]+t.offsetY)*t.scaleY,x=(c[r]+t.offsetX)*t.scaleX,y=(c[r+1]+t.offsetY)*t.scaleY,v=(c[a]+t.offsetX)*t.scaleX,b=(c[a+1]+t.offsetY)*t.scaleY;if(g>=b)return;const w=d[i],S=d[i+1],C=d[i+2],E=d[l],I=d[l+1],P=d[l+2],R=d[o],D=d[o+1],O=d[o+2],U=Math.round(g),W=Math.round(b);let V,G,Y,X,ae,ie,ne,te;for(let J=U;J<=W;J++){if(Jb?ve=1:y===b?ve=0:ve=(y-J)/(y-b),V=x-(x-v)*ve,G=E-(E-R)*ve,Y=I-(I-D)*ve,X=P-(P-O)*ve}let ce;Jb?ce=1:ce=(g-J)/(g-b),ae=f-(f-v)*ce,ie=w-(w-R)*ce,ne=S-(S-D)*ce,te=C-(C-O)*ce;const _e=Math.round(Math.min(V,ae)),he=Math.round(Math.max(V,ae));let ue=h*J+_e*4;for(let ve=_e;ve<=he;ve++)ce=(V-ve)/(V-ae),ce<0?ce=0:ce>1&&(ce=1),u[ue++]=G-(G-ie)*ce|0,u[ue++]=Y-(Y-ne)*ce|0,u[ue++]=X-(X-te)*ce|0,u[ue++]=255}}function IYn(s,t,n){const r=t.coords,a=t.colors;let i,l;switch(t.type){case"lattice":const o=t.verticesPerRow,c=Math.floor(r.length/o)-1,d=o-1;for(i=0;i=D?S=c:E=!0,R>=O?C=d:I=!0;const U=this.getSizeAndScale(S,this.ctx.canvas.width,b),W=this.getSizeAndScale(C,this.ctx.canvas.height,w),V=t.cachedCanvases.getCanvas("pattern",U.size,W.size),G=V.context,Y=o.createCanvasGraphics(G);if(Y.groupLevel=t.groupLevel,this.setFillAndStrokeStyleToContext(Y,a,l),G.translate(-U.scale*u,-W.scale*h),Y.transform(U.scale,0,0,W.scale,0,0),G.save(),this.clipBbox(Y,u,h,m,f),Y.baseTransform=wg(Y.ctx),Y.executeOperatorList(r),Y.endDrawing(),G.restore(),E||I){const X=V.canvas;E&&(S=c),I&&(C=d);const ae=this.getSizeAndScale(S,this.ctx.canvas.width,b),ie=this.getSizeAndScale(C,this.ctx.canvas.height,w),ne=ae.size,te=ie.size,J=t.cachedCanvases.getCanvas("pattern-workaround",ne,te),ce=J.context,_e=E?Math.floor(g/c):0,he=I?Math.floor(x/d):0;for(let ue=0;ue<=_e;ue++)for(let ve=0;ve<=he;ve++)ce.drawImage(X,ne*ue,te*ve,ne,te,0,0,ne,te);return{canvas:J.canvas,scaleX:ae.scale,scaleY:ie.scale,offsetX:u,offsetY:h}}return{canvas:V.canvas,scaleX:U.scale,scaleY:W.scale,offsetX:u,offsetY:h}}getSizeAndScale(t,n,r){const a=Math.max(xIe.MAX_PATTERN_SIZE,n);let i=Math.ceil(t*r);return i>=a?i=a:r=i/t,{scale:r,size:i}}clipBbox(t,n,r,a,i){const l=a-n,o=i-r;t.ctx.rect(n,r,l,o),t.current.updateRectMinMax(wg(t.ctx),[n,r,a,i]),t.clip(),t.endPath()}setFillAndStrokeStyleToContext(t,n,r){const a=t.ctx,i=t.current;switch(n){case c3t.COLORED:const l=this.ctx;a.fillStyle=l.fillStyle,a.strokeStyle=l.strokeStyle,i.fillColor=l.fillStyle,i.strokeColor=l.strokeStyle;break;case c3t.UNCOLORED:const o=ol.makeHexColor(r[0],r[1],r[2]);a.fillStyle=o,a.strokeStyle=o,i.fillColor=o,i.strokeColor=o;break;default:throw new oYn(`Unsupported paint type: ${n}`)}}getPattern(t,n,r,a){let i=r;a!==f_.SHADING&&(i=ol.transform(i,n.baseTransform),this.matrix&&(i=ol.transform(i,this.matrix)));const l=this.createPatternCanvas(n);let o=new DOMMatrix(i);o=o.translate(l.offsetX,l.offsetY),o=o.scale(1/l.scaleX,1/l.scaleY);const c=t.createPattern(l.canvas,"repeat");return c.setTransform(o),c}};Nr(xIe,"MAX_PATTERN_SIZE",3e3);let YZe=xIe;function FYn({src:s,srcPos:t=0,dest:n,width:r,height:a,nonBlackColor:i=4294967295,inverseDecode:l=!1}){const o=T_.isLittleEndian?4278190080:255,[c,d]=l?[i,o]:[o,i],u=r>>3,h=r&7,m=s.length;n=new Uint32Array(n.buffer);let f=0;for(let g=0;g{s.save=s.__originalSave,s.restore=s.__originalRestore,s.rotate=s.__originalRotate,s.scale=s.__originalScale,s.translate=s.__originalTranslate,s.transform=s.__originalTransform,s.setTransform=s.__originalSetTransform,s.resetTransform=s.__originalResetTransform,s.clip=s.__originalClip,s.moveTo=s.__originalMoveTo,s.lineTo=s.__originalLineTo,s.bezierCurveTo=s.__originalBezierCurveTo,s.rect=s.__originalRect,s.closePath=s.__originalClosePath,s.beginPath=s.__originalBeginPath,delete s._removeMirroring},s.save=function(){t.save(),this.__originalSave()},s.restore=function(){t.restore(),this.__originalRestore()},s.translate=function(r,a){t.translate(r,a),this.__originalTranslate(r,a)},s.scale=function(r,a){t.scale(r,a),this.__originalScale(r,a)},s.transform=function(r,a,i,l,o,c){t.transform(r,a,i,l,o,c),this.__originalTransform(r,a,i,l,o,c)},s.setTransform=function(r,a,i,l,o,c){t.setTransform(r,a,i,l,o,c),this.__originalSetTransform(r,a,i,l,o,c)},s.resetTransform=function(){t.resetTransform(),this.__originalResetTransform()},s.rotate=function(r){t.rotate(r),this.__originalRotate(r)},s.clip=function(r){t.clip(r),this.__originalClip(r)},s.moveTo=function(n,r){t.moveTo(n,r),this.__originalMoveTo(n,r)},s.lineTo=function(n,r){t.lineTo(n,r),this.__originalLineTo(n,r)},s.bezierCurveTo=function(n,r,a,i,l,o){t.bezierCurveTo(n,r,a,i,l,o),this.__originalBezierCurveTo(n,r,a,i,l,o)},s.rect=function(n,r,a,i){t.rect(n,r,a,i),this.__originalRect(n,r,a,i)},s.closePath=function(){t.closePath(),this.__originalClosePath()},s.beginPath=function(){t.beginPath(),this.__originalBeginPath()}}class BYn{constructor(t){this.canvasFactory=t,this.cache=Object.create(null)}getCanvas(t,n,r){let a;return this.cache[t]!==void 0?(a=this.cache[t],this.canvasFactory.reset(a,n,r)):(a=this.canvasFactory.create(n,r),this.cache[t]=a),a}delete(t){delete this.cache[t]}clear(){for(const t in this.cache){const n=this.cache[t];this.canvasFactory.destroy(n),delete this.cache[t]}}}function Pue(s,t,n,r,a,i,l,o,c,d){const[u,h,m,f,g,x]=wg(s);if(h===0&&m===0){const b=l*u+g,w=Math.round(b),S=o*f+x,C=Math.round(S),E=(l+c)*u+g,I=Math.abs(Math.round(E)-w)||1,P=(o+d)*f+x,R=Math.abs(Math.round(P)-C)||1;return s.setTransform(Math.sign(u),0,0,Math.sign(f),w,C),s.drawImage(t,n,r,a,i,0,0,I,R),s.setTransform(u,h,m,f,g,x),[I,R]}if(u===0&&f===0){const b=o*m+g,w=Math.round(b),S=l*h+x,C=Math.round(S),E=(o+d)*m+g,I=Math.abs(Math.round(E)-w)||1,P=(l+c)*h+x,R=Math.abs(Math.round(P)-C)||1;return s.setTransform(0,Math.sign(h),Math.sign(m),0,w,C),s.drawImage(t,n,r,a,i,0,0,R,I),s.setTransform(u,h,m,f,g,x),[R,I]}s.drawImage(t,n,r,a,i,l,o,c,d);const y=Math.hypot(u,h),v=Math.hypot(m,f);return[y*c,v*d]}function $Yn(s){const{width:t,height:n}=s;if(t>m3t||n>m3t)return null;const r=1e3,a=new Uint8Array([0,2,4,0,1,0,5,4,8,10,0,8,0,2,1,0]),i=t+1;let l=new Uint8Array(i*(n+1)),o,c,d;const u=t+7&-8;let h=new Uint8Array(u*n),m=0;for(const v of s.data){let b=128;for(;b>0;)h[m++]=v&b?0:255,b>>=1}let f=0;for(m=0,h[m]!==0&&(l[0]=1,++f),c=1;c>2)+(h[m+1]?4:0)+(h[m-u+1]?8:0),a[v]&&(l[d+c]=a[v],++f),m++;if(h[m-u]!==h[m]&&(l[d+c]=h[m]?2:4,++f),f>r)return null}for(m=u*(n-1),d=o*i,h[m]!==0&&(l[d]=8,++f),c=1;cr)return null;const g=new Int32Array([0,i,-1,0,-i,0,0,0,1]),x=new Path2D;for(o=0;f&&o<=n;o++){let v=o*i;const b=v+t;for(;v>4,l[v]&=S>>2|S<<2),x.lineTo(v%i,v/i|0),l[v]||--f}while(w!==v);--o}return h=null,l=null,function(v){v.save(),v.scale(1/t,-1/n),v.translate(0,-n),v.fill(x),v.beginPath(),v.restore()}}class f3t{constructor(t,n){this.alphaIsShape=!1,this.fontSize=0,this.fontSizeScale=1,this.textMatrix=Tss,this.textMatrixScale=1,this.fontMatrix=_Ze,this.leading=0,this.x=0,this.y=0,this.lineX=0,this.lineY=0,this.charSpacing=0,this.wordSpacing=0,this.textHScale=1,this.textRenderingMode=s1.FILL,this.textRise=0,this.fillColor="#000000",this.strokeColor="#000000",this.patternFill=!1,this.fillAlpha=1,this.strokeAlpha=1,this.lineWidth=1,this.activeSMask=null,this.transferMaps="none",this.startNewPathAndClipBox([0,0,t,n])}clone(){const t=Object.create(this);return t.clipBox=this.clipBox.slice(),t}setCurrentPoint(t,n){this.x=t,this.y=n}updatePathMinMax(t,n,r){[n,r]=ol.applyTransform([n,r],t),this.minX=Math.min(this.minX,n),this.minY=Math.min(this.minY,r),this.maxX=Math.max(this.maxX,n),this.maxY=Math.max(this.maxY,r)}updateRectMinMax(t,n){const r=ol.applyTransform(n,t),a=ol.applyTransform(n.slice(2),t),i=ol.applyTransform([n[0],n[3]],t),l=ol.applyTransform([n[2],n[1]],t);this.minX=Math.min(this.minX,r[0],a[0],i[0],l[0]),this.minY=Math.min(this.minY,r[1],a[1],i[1],l[1]),this.maxX=Math.max(this.maxX,r[0],a[0],i[0],l[0]),this.maxY=Math.max(this.maxY,r[1],a[1],i[1],l[1])}updateScalingPathMinMax(t,n){ol.scaleMinMax(t,n),this.minX=Math.min(this.minX,n[0]),this.minY=Math.min(this.minY,n[1]),this.maxX=Math.max(this.maxX,n[2]),this.maxY=Math.max(this.maxY,n[3])}updateCurvePathMinMax(t,n,r,a,i,l,o,c,d,u){const h=ol.bezierBoundingBox(n,r,a,i,l,o,c,d,u);u||this.updateRectMinMax(t,h)}getPathBoundingBox(t=f_.FILL,n=null){const r=[this.minX,this.minY,this.maxX,this.maxY];if(t===f_.STROKE){n||kp("Stroke bounding box must include transform.");const a=ol.singularValueDecompose2dScale(n),i=a[0]*this.lineWidth/2,l=a[1]*this.lineWidth/2;r[0]-=i,r[1]-=l,r[2]+=i,r[3]+=l}return r}updateClipFromPath(){const t=ol.intersect(this.clipBox,this.getPathBoundingBox());this.startNewPathAndClipBox(t||[0,0,0,0])}isEmptyClip(){return this.minX===1/0}startNewPathAndClipBox(t){this.clipBox=t,this.minX=1/0,this.minY=1/0,this.maxX=0,this.maxY=0}getClippedPathBoundingBox(t=f_.FILL,n=null){return ol.intersect(this.clipBox,this.getPathBoundingBox(t,n))}}function p3t(s,t){if(typeof ImageData<"u"&&t instanceof ImageData){s.putImageData(t,0,0);return}const n=t.height,r=t.width,a=n%fw,i=(n-a)/fw,l=a===0?i:i+1,o=s.createImageData(r,fw);let c=0,d;const u=t.data,h=o.data;let m,f,g,x;if(t.kind===O3e.GRAYSCALE_1BPP){const y=u.byteLength,v=new Uint32Array(h.buffer,0,h.byteLength>>2),b=v.length,w=r+7>>3,S=4294967295,C=T_.isLittleEndian?4278190080:255;for(m=0;mw?r:E*8-7,R=P&-8;let D=0,O=0;for(;I>=1}for(;d=i&&(g=a,x=r*g),d=0,f=x;f--;)h[d++]=u[c++],h[d++]=u[c++],h[d++]=u[c++],h[d++]=255;s.putImageData(o,0,m*fw)}else throw new Error(`bad image kind: ${t.kind}`)}function g3t(s,t){if(t.bitmap){s.drawImage(t.bitmap,0,0);return}const n=t.height,r=t.width,a=n%fw,i=(n-a)/fw,l=a===0?i:i+1,o=s.createImageData(r,fw);let c=0;const d=t.data,u=o.data;for(let h=0;hh3t&&typeof r=="function",u=d?Date.now()+OYn:0;let h=0;const m=this.commonObjs,f=this.objs;let g;for(;;){if(a!==void 0&&o===a.nextBreakPoint)return a.breakIt(o,r),o;if(g=l[o],g!==xS.dependency)this[g].apply(this,i[o]);else for(const x of i[o]){const y=x.startsWith("g_")?m:f;if(!y.has(x))return y.get(x,r),o}if(o++,o===c)return o;if(d&&++h>h3t){if(Date.now()>u)return r(),o;h=0}}}endDrawing(){ls(this,QL,ZZe).call(this),this.cachedCanvases.clear(),this.cachedPatterns.clear();for(const t of this._cachedBitmapsMap.values()){for(const n of t.values())typeof HTMLCanvasElement<"u"&&n instanceof HTMLCanvasElement&&(n.width=n.height=0);t.clear()}this._cachedBitmapsMap.clear(),ls(this,QL,XZe).call(this)}_scaleImage(t,n){const r=t.width??t.displayWidth,a=t.height??t.displayHeight;let i=Math.max(Math.hypot(n[0],n[1]),1),l=Math.max(Math.hypot(n[2],n[3]),1),o=r,c=a,d="prescale1",u,h;for(;i>2&&o>1||l>2&&c>1;){let m=o,f=c;i>2&&o>1&&(m=o>=16384?Math.floor(o/2)-1||1:Math.ceil(o/2),i/=o/m),l>2&&c>1&&(f=c>=16384?Math.floor(c/2)-1||1:Math.ceil(c)/2,l/=c/f),u=this.cachedCanvases.getCanvas(d,m,f),h=u.context,h.clearRect(0,0,m,f),h.drawImage(t,0,0,o,c,0,0,m,f),t=u.canvas,o=m,c=f,d=d==="prescale1"?"prescale2":"prescale1"}return{img:t,paintWidth:o,paintHeight:c}}_createMaskCanvas(t){const n=this.ctx,{width:r,height:a}=t,i=this.current.fillColor,l=this.current.patternFill,o=wg(n);let c,d,u,h;if((t.bitmap||t.data)&&t.count>1){const P=t.bitmap||t.data.buffer;d=JSON.stringify(l?o:[o.slice(0,4),i]),c=this._cachedBitmapsMap.get(P),c||(c=new Map,this._cachedBitmapsMap.set(P,c));const R=c.get(d);if(R&&!l){const D=Math.round(Math.min(o[0],o[2])+o[4]),O=Math.round(Math.min(o[1],o[3])+o[5]);return{canvas:R,offsetX:D,offsetY:O}}u=R}u||(h=this.cachedCanvases.getCanvas("maskCanvas",r,a),g3t(h.context,t));let m=ol.transform(o,[1/r,0,0,-1/a,0,0]);m=ol.transform(m,[1,0,0,1,0,-a]);const[f,g,x,y]=ol.getAxialAlignedBoundingBox([0,0,r,a],m),v=Math.round(x-f)||1,b=Math.round(y-g)||1,w=this.cachedCanvases.getCanvas("fillCanvas",v,b),S=w.context,C=f,E=g;S.translate(-C,-E),S.transform(...m),u||(u=this._scaleImage(h.canvas,uA(S)),u=u.img,c&&l&&c.set(d,u)),S.imageSmoothingEnabled=x3t(wg(S),t.interpolate),Pue(S,u,0,0,u.width,u.height,0,0,r,a),S.globalCompositeOperation="source-in";const I=ol.transform(uA(S),[1,0,0,1,-C,-E]);return S.fillStyle=l?i.getPattern(n,this,I,f_.FILL):i,S.fillRect(0,0,r,a),c&&!l&&(this.cachedCanvases.delete("fillCanvas"),c.set(d,w.canvas)),{canvas:w.canvas,offsetX:Math.round(C),offsetY:Math.round(E)}}setLineWidth(t){t!==this.current.lineWidth&&(this._cachedScaleForStroking[0]=-1),this.current.lineWidth=t,this.ctx.lineWidth=t}setLineCap(t){this.ctx.lineCap=UYn[t]}setLineJoin(t){this.ctx.lineJoin=qYn[t]}setMiterLimit(t){this.ctx.miterLimit=t}setDash(t,n){const r=this.ctx;r.setLineDash!==void 0&&(r.setLineDash(t),r.lineDashOffset=n)}setRenderingIntent(t){}setFlatness(t){}setGState(t){for(const[n,r]of t)switch(n){case"LW":this.setLineWidth(r);break;case"LC":this.setLineCap(r);break;case"LJ":this.setLineJoin(r);break;case"ML":this.setMiterLimit(r);break;case"D":this.setDash(r[0],r[1]);break;case"RI":this.setRenderingIntent(r);break;case"FL":this.setFlatness(r);break;case"Font":this.setFont(r[0],r[1]);break;case"CA":this.current.strokeAlpha=r;break;case"ca":this.current.fillAlpha=r,this.ctx.globalAlpha=r;break;case"BM":this.ctx.globalCompositeOperation=r;break;case"SMask":this.current.activeSMask=r?this.tempSMask:null,this.tempSMask=null,this.checkSMaskState();break;case"TR":this.ctx.filter=this.current.transferMaps=this.filterFactory.addFilter(r);break}}get inSMaskMode(){return!!this.suspendedCtx}checkSMaskState(){const t=this.inSMaskMode;this.current.activeSMask&&!t?this.beginSMaskMode():!this.current.activeSMask&&t&&this.endSMaskMode()}beginSMaskMode(){if(this.inSMaskMode)throw new Error("beginSMaskMode called while already in smask mode");const t=this.ctx.canvas.width,n=this.ctx.canvas.height,r="smaskGroupAt"+this.groupLevel,a=this.cachedCanvases.getCanvas(r,t,n);this.suspendedCtx=this.ctx,this.ctx=a.context;const i=this.ctx;i.setTransform(...wg(this.suspendedCtx)),fX(this.suspendedCtx,i),zYn(i,this.suspendedCtx),this.setGState([["BM","source-over"],["ca",1],["CA",1]])}endSMaskMode(){if(!this.inSMaskMode)throw new Error("endSMaskMode called while not in smask mode");this.ctx._removeMirroring(),fX(this.ctx,this.suspendedCtx),this.ctx=this.suspendedCtx,this.suspendedCtx=null}compose(t){if(!this.current.activeSMask)return;t?(t[0]=Math.floor(t[0]),t[1]=Math.floor(t[1]),t[2]=Math.ceil(t[2]),t[3]=Math.ceil(t[3])):t=[0,0,this.ctx.canvas.width,this.ctx.canvas.height];const n=this.current.activeSMask,r=this.suspendedCtx;this.composeSMask(r,n,this.ctx,t),this.ctx.save(),this.ctx.setTransform(1,0,0,1,0,0),this.ctx.clearRect(0,0,this.ctx.canvas.width,this.ctx.canvas.height),this.ctx.restore()}composeSMask(t,n,r,a){const i=a[0],l=a[1],o=a[2]-i,c=a[3]-l;o===0||c===0||(this.genericComposeSMask(n.context,r,o,c,n.subtype,n.backdrop,n.transferMap,i,l,n.offsetX,n.offsetY),t.save(),t.globalAlpha=1,t.globalCompositeOperation="source-over",t.setTransform(1,0,0,1,0,0),t.drawImage(r.canvas,0,0),t.restore())}genericComposeSMask(t,n,r,a,i,l,o,c,d,u,h){let m=t.canvas,f=c-u,g=d-h;if(l){const y=ol.makeHexColor(...l);if(f<0||g<0||f+r>m.width||g+a>m.height){const v=this.cachedCanvases.getCanvas("maskExtension",r,a),b=v.context;b.drawImage(m,-f,-g),b.globalCompositeOperation="destination-atop",b.fillStyle=y,b.fillRect(0,0,r,a),b.globalCompositeOperation="source-over",m=v.canvas,f=g=0}else{t.save(),t.globalAlpha=1,t.setTransform(1,0,0,1,0,0);const v=new Path2D;v.rect(f,g,r,a),t.clip(v),t.globalCompositeOperation="destination-atop",t.fillStyle=y,t.fillRect(f,g,r,a),t.restore()}}n.save(),n.globalAlpha=1,n.setTransform(1,0,0,1,0,0),i==="Alpha"&&o?n.filter=this.filterFactory.addAlphaFilter(o):i==="Luminosity"&&(n.filter=this.filterFactory.addLuminosityFilter(o));const x=new Path2D;x.rect(c,d,r,a),n.clip(x),n.globalCompositeOperation="destination-in",n.drawImage(m,f,g,r,a,c,d,r,a),n.restore()}save(){this.inSMaskMode?(fX(this.ctx,this.suspendedCtx),this.suspendedCtx.save()):this.ctx.save();const t=this.current;this.stateStack.push(t),this.current=t.clone()}restore(){this.stateStack.length===0&&this.inSMaskMode&&this.endSMaskMode(),this.stateStack.length!==0&&(this.current=this.stateStack.pop(),this.inSMaskMode?(this.suspendedCtx.restore(),fX(this.suspendedCtx,this.ctx)):this.ctx.restore(),this.checkSMaskState(),this.pendingClip=null,this._cachedScaleForStroking[0]=-1,this._cachedGetSinglePixelWidth=null)}transform(t,n,r,a,i,l){this.ctx.transform(t,n,r,a,i,l),this._cachedScaleForStroking[0]=-1,this._cachedGetSinglePixelWidth=null}constructPath(t,n,r){const a=this.ctx,i=this.current;let l=i.x,o=i.y,c,d;const u=wg(a),h=u[0]===0&&u[3]===0||u[1]===0&&u[2]===0,m=h?r.slice(0):null;for(let f=0,g=0,x=t.length;fu3t&&(d=u3t),this.current.fontSizeScale=n/d,this.ctx.font=`${c} ${o} ${d}px ${l}`}setTextRenderingMode(t){this.current.textRenderingMode=t}setTextRise(t){this.current.textRise=t}moveText(t,n){this.current.x=this.current.lineX+=t,this.current.y=this.current.lineY+=n}setLeadingMoveText(t,n){this.setLeading(-n),this.moveText(t,n)}setTextMatrix(t,n,r,a,i,l){this.current.textMatrix=[t,n,r,a,i,l],this.current.textMatrixScale=Math.hypot(t,n),this.current.x=this.current.lineX=0,this.current.y=this.current.lineY=0}nextLine(){this.moveText(0,this.current.leading)}paintChar(t,n,r,a){const i=this.ctx,l=this.current,o=l.font,c=l.textRenderingMode,d=l.fontSize/l.fontSizeScale,u=c&s1.FILL_STROKE_MASK,h=!!(c&s1.ADD_TO_PATH_FLAG),m=l.patternFill&&!o.missingFile;let f;(o.disableFontFace||h||m)&&(f=o.getPathGenerator(this.commonObjs,t)),o.disableFontFace||m?(i.save(),i.translate(n,r),i.beginPath(),f(i,d),a&&i.setTransform(...a),(u===s1.FILL||u===s1.FILL_STROKE)&&i.fill(),(u===s1.STROKE||u===s1.FILL_STROKE)&&i.stroke(),i.restore()):((u===s1.FILL||u===s1.FILL_STROKE)&&i.fillText(t,n,r),(u===s1.STROKE||u===s1.FILL_STROKE)&&i.strokeText(t,n,r)),h&&(this.pendingTextPaths||(this.pendingTextPaths=[])).push({transform:wg(i),x:n,y:r,fontSize:d,addToPath:f})}get isFontSubpixelAAEnabled(){const{context:t}=this.cachedCanvases.getCanvas("isFontSubpixelAAEnabled",10,10);t.scale(1.5,1),t.fillText("I",0,10);const n=t.getImageData(0,0,10,10).data;let r=!1;for(let a=3;a0&&n[a]<255){r=!0;break}return th(this,"isFontSubpixelAAEnabled",r)}showText(t){const n=this.current,r=n.font;if(r.isType3Font)return this.showType3Text(t);const a=n.fontSize;if(a===0)return;const i=this.ctx,l=n.fontSizeScale,o=n.charSpacing,c=n.wordSpacing,d=n.fontDirection,u=n.textHScale*d,h=t.length,m=r.vertical,f=m?1:-1,g=r.defaultVMetrics,x=a*n.fontMatrix[0],y=n.textRenderingMode===s1.FILL&&!r.disableFontFace&&!n.patternFill;i.save(),i.transform(...n.textMatrix),i.translate(n.x,n.y+n.textRise),d>0?i.scale(u,-1):i.scale(u,1);let v;if(n.patternFill){i.save();const E=n.fillColor.getPattern(i,this,uA(i),f_.FILL);v=wg(i),i.restore(),i.fillStyle=E}let b=n.lineWidth;const w=n.textMatrixScale;if(w===0||b===0){const E=n.textRenderingMode&s1.FILL_STROKE_MASK;(E===s1.STROKE||E===s1.FILL_STROKE)&&(b=this.getSinglePixelWidth())}else b/=w;if(l!==1&&(i.scale(l,l),b/=l),i.lineWidth=b,r.isInvalidPDFjsFont){const E=[];let I=0;for(const P of t)E.push(P.unicode),I+=P.width;i.fillText(E.join(""),0,0),n.x+=I*x*u,i.restore(),this.compose();return}let S=0,C;for(C=0;C0){const G=i.measureText(R).width*1e3/a*l;if(Wnew odt(l,this.commonObjs,this.objs,this.canvasFactory,this.filterFactory,{optionalContentConfig:this.optionalContentConfig,markedContentStack:this.markedContentStack})};n=new YZe(t,r,this.ctx,i,a)}else n=this._getPattern(t[1],t[2]);return n}setStrokeColorN(){this.current.strokeColor=this.getColorN_Pattern(arguments)}setFillColorN(){this.current.fillColor=this.getColorN_Pattern(arguments),this.current.patternFill=!0}setStrokeRGBColor(t,n,r){this.ctx.strokeStyle=this.current.strokeColor=ol.makeHexColor(t,n,r)}setStrokeTransparent(){this.ctx.strokeStyle=this.current.strokeColor="transparent"}setFillRGBColor(t,n,r){this.ctx.fillStyle=this.current.fillColor=ol.makeHexColor(t,n,r),this.current.patternFill=!1}setFillTransparent(){this.ctx.fillStyle=this.current.fillColor="transparent",this.current.patternFill=!1}_getPattern(t,n=null){let r;return this.cachedPatterns.has(t)?r=this.cachedPatterns.get(t):(r=DYn(this.getObject(t)),this.cachedPatterns.set(t,r)),n&&(r.matrix=n),r}shadingFill(t){if(!this.contentVisible)return;const n=this.ctx;this.save();const r=this._getPattern(t);n.fillStyle=r.getPattern(n,this,uA(n),f_.SHADING);const a=uA(n);if(a){const{width:i,height:l}=n.canvas,[o,c,d,u]=ol.getAxialAlignedBoundingBox([0,0,i,l],a);this.ctx.fillRect(o,c,d-o,u-c)}else this.ctx.fillRect(-1e10,-1e10,2e10,2e10);this.compose(this.current.getClippedPathBoundingBox()),this.restore()}beginInlineImage(){kp("Should not call beginInlineImage")}beginImageData(){kp("Should not call beginImageData")}paintFormXObjectBegin(t,n){if(this.contentVisible&&(this.save(),this.baseTransformStack.push(this.baseTransform),t&&this.transform(...t),this.baseTransform=wg(this.ctx),n)){const r=n[2]-n[0],a=n[3]-n[1];this.ctx.rect(n[0],n[1],r,a),this.current.updateRectMinMax(wg(this.ctx),n),this.clip(),this.endPath()}}paintFormXObjectEnd(){this.contentVisible&&(this.restore(),this.baseTransform=this.baseTransformStack.pop())}beginGroup(t){if(!this.contentVisible)return;this.save(),this.inSMaskMode&&(this.endSMaskMode(),this.current.activeSMask=null);const n=this.ctx;t.isolated||BDe("TODO: Support non-isolated groups."),t.knockout&&nu("Knockout groups not supported.");const r=wg(n);if(t.matrix&&n.transform(...t.matrix),!t.bbox)throw new Error("Bounding box is required.");let a=ol.getAxialAlignedBoundingBox(t.bbox,wg(n));const i=[0,0,n.canvas.width,n.canvas.height];a=ol.intersect(a,i)||[0,0,0,0];const l=Math.floor(a[0]),o=Math.floor(a[1]),c=Math.max(Math.ceil(a[2])-l,1),d=Math.max(Math.ceil(a[3])-o,1);this.current.startNewPathAndClipBox([0,0,c,d]);let u="groupAt"+this.groupLevel;t.smask&&(u+="_smask_"+this.smaskCounter++%2);const h=this.cachedCanvases.getCanvas(u,c,d),m=h.context;m.translate(-l,-o),m.transform(...r),t.smask?this.smaskStack.push({canvas:h.canvas,context:m,offsetX:l,offsetY:o,subtype:t.smask.subtype,backdrop:t.smask.backdrop,transferMap:t.smask.transferMap||null,startTransformInverse:null}):(n.setTransform(1,0,0,1,0,0),n.translate(l,o),n.save()),fX(n,m),this.ctx=m,this.setGState([["BM","source-over"],["ca",1],["CA",1]]),this.groupStack.push(n),this.groupLevel++}endGroup(t){if(!this.contentVisible)return;this.groupLevel--;const n=this.ctx,r=this.groupStack.pop();if(this.ctx=r,this.ctx.imageSmoothingEnabled=!1,t.smask)this.tempSMask=this.smaskStack.pop(),this.restore();else{this.ctx.restore();const a=wg(this.ctx);this.restore(),this.ctx.save(),this.ctx.setTransform(...a);const i=ol.getAxialAlignedBoundingBox([0,0,n.canvas.width,n.canvas.height],a);this.ctx.drawImage(n.canvas,0,0),this.ctx.restore(),this.compose(i)}}beginAnnotation(t,n,r,a,i){if(ls(this,QL,ZZe).call(this),Iue(this.ctx),this.ctx.save(),this.save(),this.baseTransform&&this.ctx.setTransform(...this.baseTransform),n){const l=n[2]-n[0],o=n[3]-n[1];if(i&&this.annotationCanvasMap){r=r.slice(),r[4]-=n[0],r[5]-=n[1],n=n.slice(),n[0]=n[1]=0,n[2]=l,n[3]=o;const[c,d]=ol.singularValueDecompose2dScale(wg(this.ctx)),{viewportScale:u}=this,h=Math.ceil(l*this.outputScaleX*u),m=Math.ceil(o*this.outputScaleY*u);this.annotationCanvas=this.canvasFactory.create(h,m);const{canvas:f,context:g}=this.annotationCanvas;this.annotationCanvasMap.set(t,f),this.annotationCanvas.savedCtx=this.ctx,this.ctx=g,this.ctx.save(),this.ctx.setTransform(c,0,0,-d,0,o*d),Iue(this.ctx)}else Iue(this.ctx),this.endPath(),this.ctx.rect(n[0],n[1],l,o),this.ctx.clip(),this.ctx.beginPath()}this.current=new f3t(this.ctx.canvas.width,this.ctx.canvas.height),this.transform(...r),this.transform(...a)}endAnnotation(){this.annotationCanvas&&(this.ctx.restore(),ls(this,QL,XZe).call(this),this.ctx=this.annotationCanvas.savedCtx,delete this.annotationCanvas.savedCtx,delete this.annotationCanvas)}paintImageMaskXObject(t){if(!this.contentVisible)return;const n=t.count;t=this.getObject(t.data,t),t.count=n;const r=this.ctx,a=this.processingType3;if(a&&(a.compiled===void 0&&(a.compiled=$Yn(t)),a.compiled)){a.compiled(r);return}const i=this._createMaskCanvas(t),l=i.canvas;r.save(),r.setTransform(1,0,0,1,0,0),r.drawImage(l,i.offsetX,i.offsetY),r.restore(),this.compose()}paintImageMaskXObjectRepeat(t,n,r=0,a=0,i,l){if(!this.contentVisible)return;t=this.getObject(t.data,t);const o=this.ctx;o.save();const c=wg(o);o.transform(n,r,a,i,0,0);const d=this._createMaskCanvas(t);o.setTransform(1,0,0,1,d.offsetX-c[4],d.offsetY-c[5]);for(let u=0,h=l.length;uh?u/h:1,o=d>h?d/h:1}}this._cachedScaleForStroking[0]=l,this._cachedScaleForStroking[1]=o}return this._cachedScaleForStroking}rescaleAndStroke(t){const{ctx:n}=this,{lineWidth:r}=this.current,[a,i]=this.getScaleForStroking();if(n.lineWidth=r||1,a===1&&i===1){n.stroke();return}const l=n.getLineDash();if(t&&n.save(),n.scale(a,i),l.length>0){const o=Math.max(a,i);n.setLineDash(l.map(c=>c/o)),n.lineDashOffset/=o}n.stroke(),t&&n.restore()}isContentVisible(){for(let t=this.markedContentStack.length-1;t>=0;t--)if(!this.markedContentStack[t].visible)return!1;return!0}};QL=new WeakSet,ZZe=function(){for(;this.stateStack.length||this.inSMaskMode;)this.restore();this.current.activeSMask=null,this.ctx.restore(),this.transparentCanvas&&(this.ctx=this.compositeCtx,this.ctx.save(),this.ctx.setTransform(1,0,0,1,0,0),this.ctx.drawImage(this.transparentCanvas,0,0),this.ctx.restore(),this.transparentCanvas=null)},XZe=function(){if(this.pageColors){const t=this.filterFactory.addHCMFilter(this.pageColors.foreground,this.pageColors.background);if(t!=="none"){const n=this.ctx.filter;this.ctx.filter=t,this.ctx.drawImage(this.ctx.canvas,0,0),this.ctx.filter=n}}};let qV=odt;for(const s in xS)qV.prototype[s]!==void 0&&(qV.prototype[xS[s]]=qV.prototype[s]);var wre,jre;class pE{static get workerPort(){return ye(this,wre)}static set workerPort(t){if(!(typeof Worker<"u"&&t instanceof Worker)&&t!==null)throw new Error("Invalid `workerPort` type.");Kt(this,wre,t)}static get workerSrc(){return ye(this,jre)}static set workerSrc(t){if(typeof t!="string")throw new Error("Invalid `workerSrc` type.");Kt(this,jre,t)}}wre=new WeakMap,jre=new WeakMap,bs(pE,wre,null),bs(pE,jre,"");const Lue={DATA:1,ERROR:2},Ay={CANCEL:1,CANCEL_COMPLETE:2,CLOSE:3,ENQUEUE:4,ERROR:5,PULL:6,PULL_COMPLETE:7,START_COMPLETE:8};function kj(s){switch(s instanceof Error||typeof s=="object"&&s!==null||kp('wrapReason: Expected "reason" to be a (possibly cloned) Error.'),s.name){case"AbortException":return new x9(s.message);case"MissingPDFException":return new g9(s.message);case"PasswordException":return new wZe(s.message,s.code);case"UnexpectedResponseException":return new $De(s.message,s.status);case"UnknownErrorException":return new jZe(s.message,s.details);default:return new jZe(s.message,s.toString())}}var kH,dk,fns,pns,gns,G3e;class DQ{constructor(t,n,r){bs(this,dk);bs(this,kH,new AbortController);this.sourceName=t,this.targetName=n,this.comObj=r,this.callbackId=1,this.streamId=1,this.streamSinks=Object.create(null),this.streamControllers=Object.create(null),this.callbackCapabilities=Object.create(null),this.actionHandler=Object.create(null),r.addEventListener("message",ls(this,dk,fns).bind(this),{signal:ye(this,kH).signal})}on(t,n){const r=this.actionHandler;if(r[t])throw new Error(`There is already an actionName called "${t}"`);r[t]=n}send(t,n,r){this.comObj.postMessage({sourceName:this.sourceName,targetName:this.targetName,action:t,data:n},r)}sendWithPromise(t,n,r){const a=this.callbackId++,i=Promise.withResolvers();this.callbackCapabilities[a]=i;try{this.comObj.postMessage({sourceName:this.sourceName,targetName:this.targetName,action:t,callbackId:a,data:n},r)}catch(l){i.reject(l)}return i.promise}sendWithStream(t,n,r,a){const i=this.streamId++,l=this.sourceName,o=this.targetName,c=this.comObj;return new ReadableStream({start:d=>{const u=Promise.withResolvers();return this.streamControllers[i]={controller:d,startCall:u,pullCall:null,cancelCall:null,isClosed:!1},c.postMessage({sourceName:l,targetName:o,action:t,streamId:i,data:n,desiredSize:d.desiredSize},a),u.promise},pull:d=>{const u=Promise.withResolvers();return this.streamControllers[i].pullCall=u,c.postMessage({sourceName:l,targetName:o,stream:Ay.PULL,streamId:i,desiredSize:d.desiredSize}),u.promise},cancel:d=>{j0(d instanceof Error,"cancel must have a valid reason");const u=Promise.withResolvers();return this.streamControllers[i].cancelCall=u,this.streamControllers[i].isClosed=!0,c.postMessage({sourceName:l,targetName:o,stream:Ay.CANCEL,streamId:i,reason:kj(d)}),u.promise}},r)}destroy(){var t;(t=ye(this,kH))==null||t.abort(),Kt(this,kH,null)}}kH=new WeakMap,dk=new WeakSet,fns=function({data:t}){if(t.targetName!==this.sourceName)return;if(t.stream){ls(this,dk,gns).call(this,t);return}if(t.callback){const r=t.callbackId,a=this.callbackCapabilities[r];if(!a)throw new Error(`Cannot resolve callback ${r}`);if(delete this.callbackCapabilities[r],t.callback===Lue.DATA)a.resolve(t.data);else if(t.callback===Lue.ERROR)a.reject(kj(t.reason));else throw new Error("Unexpected callback case");return}const n=this.actionHandler[t.action];if(!n)throw new Error(`Unknown action from worker: ${t.action}`);if(t.callbackId){const r=this.sourceName,a=t.sourceName,i=this.comObj;new Promise(function(l){l(n(t.data))}).then(function(l){i.postMessage({sourceName:r,targetName:a,callback:Lue.DATA,callbackId:t.callbackId,data:l})},function(l){i.postMessage({sourceName:r,targetName:a,callback:Lue.ERROR,callbackId:t.callbackId,reason:kj(l)})});return}if(t.streamId){ls(this,dk,pns).call(this,t);return}n(t.data)},pns=function(t){const n=t.streamId,r=this.sourceName,a=t.sourceName,i=this.comObj,l=this,o=this.actionHandler[t.action],c={enqueue(d,u=1,h){if(this.isCancelled)return;const m=this.desiredSize;this.desiredSize-=u,m>0&&this.desiredSize<=0&&(this.sinkCapability=Promise.withResolvers(),this.ready=this.sinkCapability.promise),i.postMessage({sourceName:r,targetName:a,stream:Ay.ENQUEUE,streamId:n,chunk:d},h)},close(){this.isCancelled||(this.isCancelled=!0,i.postMessage({sourceName:r,targetName:a,stream:Ay.CLOSE,streamId:n}),delete l.streamSinks[n])},error(d){j0(d instanceof Error,"error must have a valid reason"),!this.isCancelled&&(this.isCancelled=!0,i.postMessage({sourceName:r,targetName:a,stream:Ay.ERROR,streamId:n,reason:kj(d)}))},sinkCapability:Promise.withResolvers(),onPull:null,onCancel:null,isCancelled:!1,desiredSize:t.desiredSize,ready:null};c.sinkCapability.resolve(),c.ready=c.sinkCapability.promise,this.streamSinks[n]=c,new Promise(function(d){d(o(t.data,c))}).then(function(){i.postMessage({sourceName:r,targetName:a,stream:Ay.START_COMPLETE,streamId:n,success:!0})},function(d){i.postMessage({sourceName:r,targetName:a,stream:Ay.START_COMPLETE,streamId:n,reason:kj(d)})})},gns=function(t){const n=t.streamId,r=this.sourceName,a=t.sourceName,i=this.comObj,l=this.streamControllers[n],o=this.streamSinks[n];switch(t.stream){case Ay.START_COMPLETE:t.success?l.startCall.resolve():l.startCall.reject(kj(t.reason));break;case Ay.PULL_COMPLETE:t.success?l.pullCall.resolve():l.pullCall.reject(kj(t.reason));break;case Ay.PULL:if(!o){i.postMessage({sourceName:r,targetName:a,stream:Ay.PULL_COMPLETE,streamId:n,success:!0});break}o.desiredSize<=0&&t.desiredSize>0&&o.sinkCapability.resolve(),o.desiredSize=t.desiredSize,new Promise(function(c){var d;c((d=o.onPull)==null?void 0:d.call(o))}).then(function(){i.postMessage({sourceName:r,targetName:a,stream:Ay.PULL_COMPLETE,streamId:n,success:!0})},function(c){i.postMessage({sourceName:r,targetName:a,stream:Ay.PULL_COMPLETE,streamId:n,reason:kj(c)})});break;case Ay.ENQUEUE:if(j0(l,"enqueue should have stream controller"),l.isClosed)break;l.controller.enqueue(t.chunk);break;case Ay.CLOSE:if(j0(l,"close should have stream controller"),l.isClosed)break;l.isClosed=!0,l.controller.close(),ls(this,dk,G3e).call(this,l,n);break;case Ay.ERROR:j0(l,"error should have stream controller"),l.controller.error(kj(t.reason)),ls(this,dk,G3e).call(this,l,n);break;case Ay.CANCEL_COMPLETE:t.success?l.cancelCall.resolve():l.cancelCall.reject(kj(t.reason)),ls(this,dk,G3e).call(this,l,n);break;case Ay.CANCEL:if(!o)break;new Promise(function(c){var d;c((d=o.onCancel)==null?void 0:d.call(o,kj(t.reason)))}).then(function(){i.postMessage({sourceName:r,targetName:a,stream:Ay.CANCEL_COMPLETE,streamId:n,success:!0})},function(c){i.postMessage({sourceName:r,targetName:a,stream:Ay.CANCEL_COMPLETE,streamId:n,reason:kj(c)})}),o.sinkCapability.reject(kj(t.reason)),o.isCancelled=!0,delete this.streamSinks[n];break;default:throw new Error("Unexpected stream case")}},G3e=async function(t,n){var r,a,i;await Promise.allSettled([(r=t.startCall)==null?void 0:r.promise,(a=t.pullCall)==null?void 0:a.promise,(i=t.cancelCall)==null?void 0:i.promise]),delete this.streamControllers[n]};var az,Nre;class HYn{constructor({parsedData:t,rawData:n}){bs(this,az);bs(this,Nre);Kt(this,az,t),Kt(this,Nre,n)}getRaw(){return ye(this,Nre)}get(t){return ye(this,az).get(t)??null}getAll(){return Lot(ye(this,az))}has(t){return ye(this,az).has(t)}}az=new WeakMap,Nre=new WeakMap;const PU=Symbol("INTERNAL");var kre,Sre,Cre,SH;class GYn{constructor(t,{name:n,intent:r,usage:a,rbGroups:i}){bs(this,kre,!1);bs(this,Sre,!1);bs(this,Cre,!1);bs(this,SH,!0);Kt(this,kre,!!(t&qj.DISPLAY)),Kt(this,Sre,!!(t&qj.PRINT)),this.name=n,this.intent=r,this.usage=a,this.rbGroups=i}get visible(){if(ye(this,Cre))return ye(this,SH);if(!ye(this,SH))return!1;const{print:t,view:n}=this.usage;return ye(this,kre)?(n==null?void 0:n.viewState)!=="OFF":ye(this,Sre)?(t==null?void 0:t.printState)!=="OFF":!0}_setVisible(t,n,r=!1){t!==PU&&kp("Internal method `_setVisible` called."),Kt(this,Cre,r),Kt(this,SH,n)}}kre=new WeakMap,Sre=new WeakMap,Cre=new WeakMap,SH=new WeakMap;var JP,Cm,CH,AH,Are,QZe;class WYn{constructor(t,n=qj.DISPLAY){bs(this,Are);bs(this,JP,null);bs(this,Cm,new Map);bs(this,CH,null);bs(this,AH,null);if(this.renderingIntent=n,this.name=null,this.creator=null,t!==null){this.name=t.name,this.creator=t.creator,Kt(this,AH,t.order);for(const r of t.groups)ye(this,Cm).set(r.id,new GYn(n,r));if(t.baseState==="OFF")for(const r of ye(this,Cm).values())r._setVisible(PU,!1);for(const r of t.on)ye(this,Cm).get(r)._setVisible(PU,!0);for(const r of t.off)ye(this,Cm).get(r)._setVisible(PU,!1);Kt(this,CH,this.getHash())}}isVisible(t){if(ye(this,Cm).size===0)return!0;if(!t)return BDe("Optional content group not defined."),!0;if(t.type==="OCG")return ye(this,Cm).has(t.id)?ye(this,Cm).get(t.id).visible:(nu(`Optional content group not found: ${t.id}`),!0);if(t.type==="OCMD"){if(t.expression)return ls(this,Are,QZe).call(this,t.expression);if(!t.policy||t.policy==="AnyOn"){for(const n of t.ids){if(!ye(this,Cm).has(n))return nu(`Optional content group not found: ${n}`),!0;if(ye(this,Cm).get(n).visible)return!0}return!1}else if(t.policy==="AllOn"){for(const n of t.ids){if(!ye(this,Cm).has(n))return nu(`Optional content group not found: ${n}`),!0;if(!ye(this,Cm).get(n).visible)return!1}return!0}else if(t.policy==="AnyOff"){for(const n of t.ids){if(!ye(this,Cm).has(n))return nu(`Optional content group not found: ${n}`),!0;if(!ye(this,Cm).get(n).visible)return!0}return!1}else if(t.policy==="AllOff"){for(const n of t.ids){if(!ye(this,Cm).has(n))return nu(`Optional content group not found: ${n}`),!0;if(ye(this,Cm).get(n).visible)return!1}return!0}return nu(`Unknown optional content policy ${t.policy}.`),!0}return nu(`Unknown group type ${t.type}.`),!0}setVisibility(t,n=!0,r=!0){var i;const a=ye(this,Cm).get(t);if(!a){nu(`Optional content group not found: ${t}`);return}if(r&&n&&a.rbGroups.length)for(const l of a.rbGroups)for(const o of l)o!==t&&((i=ye(this,Cm).get(o))==null||i._setVisible(PU,!1,!0));a._setVisible(PU,!!n,!0),Kt(this,JP,null)}setOCGState({state:t,preserveRB:n}){let r;for(const a of t){switch(a){case"ON":case"OFF":case"Toggle":r=a;continue}const i=ye(this,Cm).get(a);if(i)switch(r){case"ON":this.setVisibility(a,!0,n);break;case"OFF":this.setVisibility(a,!1,n);break;case"Toggle":this.setVisibility(a,!i.visible,n);break}}Kt(this,JP,null)}get hasInitialVisibility(){return ye(this,CH)===null||this.getHash()===ye(this,CH)}getOrder(){return ye(this,Cm).size?ye(this,AH)?ye(this,AH).slice():[...ye(this,Cm).keys()]:null}getGroups(){return ye(this,Cm).size>0?Lot(ye(this,Cm)):null}getGroup(t){return ye(this,Cm).get(t)||null}getHash(){if(ye(this,JP)!==null)return ye(this,JP);const t=new nns;for(const[n,r]of ye(this,Cm))t.update(`${n}:${r.visible}`);return Kt(this,JP,t.hexdigest())}}JP=new WeakMap,Cm=new WeakMap,CH=new WeakMap,AH=new WeakMap,Are=new WeakSet,QZe=function(t){const n=t.length;if(n<2)return!0;const r=t[0];for(let a=1;a0){const c=i instanceof Uint8Array&&i.byteLength===i.buffer.byteLength?i.buffer:new Uint8Array(i).buffer;this._queuedChunks.push(c)}this._pdfDataRangeTransport=t,this._isStreamingSupported=!r,this._isRangeSupported=!n,this._contentLength=a,this._fullRequestReader=null,this._rangeReaders=[],t.addRangeListener((c,d)=>{this._onReceiveData({begin:c,chunk:d})}),t.addProgressListener((c,d)=>{this._onProgress({loaded:c,total:d})}),t.addProgressiveReadListener(c=>{this._onReceiveData({chunk:c})}),t.addProgressiveDoneListener(()=>{this._onProgressiveDone()}),t.transportReady()}_onReceiveData({begin:t,chunk:n}){const r=n instanceof Uint8Array&&n.byteLength===n.buffer.byteLength?n.buffer:new Uint8Array(n).buffer;if(t===void 0)this._fullRequestReader?this._fullRequestReader._enqueue(r):this._queuedChunks.push(r);else{const a=this._rangeReaders.some(function(i){return i._begin!==t?!1:(i._enqueue(r),!0)});j0(a,"_onReceiveData - no `PDFDataTransportStreamRangeReader` instance found.")}}get _progressiveDataLength(){var t;return((t=this._fullRequestReader)==null?void 0:t._loaded)??0}_onProgress(t){var n,r,a,i;t.total===void 0?(r=(n=this._rangeReaders[0])==null?void 0:n.onProgress)==null||r.call(n,{loaded:t.loaded}):(i=(a=this._fullRequestReader)==null?void 0:a.onProgress)==null||i.call(a,{loaded:t.loaded,total:t.total})}_onProgressiveDone(){var t;(t=this._fullRequestReader)==null||t.progressiveDone(),this._progressiveDone=!0}_removeRangeReader(t){const n=this._rangeReaders.indexOf(t);n>=0&&this._rangeReaders.splice(n,1)}getFullReader(){j0(!this._fullRequestReader,"PDFDataTransportStream.getFullReader can only be called once.");const t=this._queuedChunks;return this._queuedChunks=null,new YYn(this,t,this._progressiveDone,this._contentDispositionFilename)}getRangeReader(t,n){if(n<=this._progressiveDataLength)return null;const r=new ZYn(this,t,n);return this._pdfDataRangeTransport.requestDataRange(t,n),this._rangeReaders.push(r),r}cancelAllRequests(t){var n;(n=this._fullRequestReader)==null||n.cancel(t);for(const r of this._rangeReaders.slice(0))r.cancel(t);this._pdfDataRangeTransport.abort()}}class YYn{constructor(t,n,r=!1,a=null){this._stream=t,this._done=r||!1,this._filename=Fot(a)?a:null,this._queuedChunks=n||[],this._loaded=0;for(const i of this._queuedChunks)this._loaded+=i.byteLength;this._requests=[],this._headersReady=Promise.resolve(),t._fullRequestReader=this,this.onProgress=null}_enqueue(t){this._done||(this._requests.length>0?this._requests.shift().resolve({value:t,done:!1}):this._queuedChunks.push(t),this._loaded+=t.byteLength)}get headersReady(){return this._headersReady}get filename(){return this._filename}get isRangeSupported(){return this._stream._isRangeSupported}get isStreamingSupported(){return this._stream._isStreamingSupported}get contentLength(){return this._stream._contentLength}async read(){if(this._queuedChunks.length>0)return{value:this._queuedChunks.shift(),done:!1};if(this._done)return{value:void 0,done:!0};const t=Promise.withResolvers();return this._requests.push(t),t.promise}cancel(t){this._done=!0;for(const n of this._requests)n.resolve({value:void 0,done:!0});this._requests.length=0}progressiveDone(){this._done||(this._done=!0)}}class ZYn{constructor(t,n,r){this._stream=t,this._begin=n,this._end=r,this._queuedChunk=null,this._requests=[],this._done=!1,this.onProgress=null}_enqueue(t){if(!this._done){if(this._requests.length===0)this._queuedChunk=t;else{this._requests.shift().resolve({value:t,done:!1});for(const r of this._requests)r.resolve({value:void 0,done:!0});this._requests.length=0}this._done=!0,this._stream._removeRangeReader(this)}}get isStreamingSupported(){return!1}async read(){if(this._queuedChunk){const n=this._queuedChunk;return this._queuedChunk=null,{value:n,done:!1}}if(this._done)return{value:void 0,done:!0};const t=Promise.withResolvers();return this._requests.push(t),t.promise}cancel(t){this._done=!0;for(const n of this._requests)n.resolve({value:void 0,done:!0});this._requests.length=0,this._stream._removeRangeReader(this)}}function XYn(s){let t=!0,n=r("filename\\*","i").exec(s);if(n){n=n[1];let u=o(n);return u=unescape(u),u=c(u),u=d(u),i(u)}if(n=l(s),n){const u=d(n);return i(u)}if(n=r("filename","i").exec(s),n){n=n[1];let u=o(n);return u=d(u),i(u)}function r(u,h){return new RegExp("(?:^|;)\\s*"+u+'\\s*=\\s*([^";\\s][^;\\s]*|"(?:[^"\\\\]|\\\\"?)+"?)',h)}function a(u,h){if(u){if(!/^[\x00-\xFF]+$/.test(h))return h;try{const m=new TextDecoder(u,{fatal:!0}),f=UDe(h);h=m.decode(f),t=!1}catch{}}return h}function i(u){return t&&/[\x80-\xff]/.test(u)&&(u=a("utf-8",u),t&&(u=a("iso-8859-1",u))),u}function l(u){const h=[];let m;const f=r("filename\\*((?!0\\d)\\d+)(\\*?)","ig");for(;(m=f.exec(u))!==null;){let[,x,y,v]=m;if(x=parseInt(x,10),x in h){if(x===0)break;continue}h[x]=[y,v]}const g=[];for(let x=0;x{if(!xns(i.status))throw HDe(i.status,a);this._reader=i.body.getReader(),this._headersCapability.resolve();const l=i.headers,{allowRangeRequests:o,suggestedLength:c}=qot({responseHeaders:l,isHttp:t.isHttp,rangeChunkSize:this._rangeChunkSize,disableRange:this._disableRange});this._isRangeSupported=o,this._contentLength=c||this._contentLength,this._filename=Vot(l),!this._isStreamingSupported&&this._isRangeSupported&&this.cancel(new x9("Streaming is disabled."))}).catch(this._headersCapability.reject),this.onProgress=null}get headersReady(){return this._headersCapability.promise}get filename(){return this._filename}get contentLength(){return this._contentLength}get isRangeSupported(){return this._isRangeSupported}get isStreamingSupported(){return this._isStreamingSupported}async read(){var r;await this._headersCapability.promise;const{value:t,done:n}=await this._reader.read();return n?{value:t,done:n}:(this._loaded+=t.byteLength,(r=this.onProgress)==null||r.call(this,{loaded:this._loaded,total:this._contentLength}),{value:vns(t),done:!1})}cancel(t){var n;(n=this._reader)==null||n.cancel(t),this._abortController.abort()}}class JYn{constructor(t,n,r){this._stream=t,this._reader=null,this._loaded=0;const a=t.source;this._withCredentials=a.withCredentials||!1,this._readCapability=Promise.withResolvers(),this._isStreamingSupported=!a.disableStream,this._abortController=new AbortController;const i=new Headers(t.headers);i.append("Range",`bytes=${n}-${r-1}`);const l=a.url;fetch(l,yns(i,this._withCredentials,this._abortController)).then(o=>{if(!xns(o.status))throw HDe(o.status,l);this._readCapability.resolve(),this._reader=o.body.getReader()}).catch(this._readCapability.reject),this.onProgress=null}get isStreamingSupported(){return this._isStreamingSupported}async read(){var r;await this._readCapability.promise;const{value:t,done:n}=await this._reader.read();return n?{value:t,done:n}:(this._loaded+=t.byteLength,(r=this.onProgress)==null||r.call(this,{loaded:this._loaded}),{value:vns(t),done:!1})}cancel(t){var n;(n=this._reader)==null||n.cancel(t),this._abortController.abort()}}const z$e=200,B$e=206;function eZn(s){const t=s.response;return typeof t!="string"?t:UDe(t).buffer}class tZn{constructor({url:t,httpHeaders:n,withCredentials:r}){this.url=t,this.isHttp=/^https?:/i.test(t),this.headers=Uot(this.isHttp,n),this.withCredentials=r||!1,this.currXhrId=0,this.pendingRequests=Object.create(null)}requestRange(t,n,r){const a={begin:t,end:n};for(const i in r)a[i]=r[i];return this.request(a)}requestFull(t){return this.request(t)}request(t){const n=new XMLHttpRequest,r=this.currXhrId++,a=this.pendingRequests[r]={xhr:n};n.open("GET",this.url),n.withCredentials=this.withCredentials;for(const[i,l]of this.headers)n.setRequestHeader(i,l);return this.isHttp&&"begin"in t&&"end"in t?(n.setRequestHeader("Range",`bytes=${t.begin}-${t.end-1}`),a.expectedStatus=B$e):a.expectedStatus=z$e,n.responseType="arraybuffer",t.onError&&(n.onerror=function(i){t.onError(n.status)}),n.onreadystatechange=this.onStateChange.bind(this,r),n.onprogress=this.onProgress.bind(this,r),a.onHeadersReceived=t.onHeadersReceived,a.onDone=t.onDone,a.onError=t.onError,a.onProgress=t.onProgress,n.send(null),r}onProgress(t,n){var a;const r=this.pendingRequests[t];r&&((a=r.onProgress)==null||a.call(r,n))}onStateChange(t,n){var c,d,u;const r=this.pendingRequests[t];if(!r)return;const a=r.xhr;if(a.readyState>=2&&r.onHeadersReceived&&(r.onHeadersReceived(),delete r.onHeadersReceived),a.readyState!==4||!(t in this.pendingRequests))return;if(delete this.pendingRequests[t],a.status===0&&this.isHttp){(c=r.onError)==null||c.call(r,a.status);return}const i=a.status||z$e;if(!(i===z$e&&r.expectedStatus===B$e)&&i!==r.expectedStatus){(d=r.onError)==null||d.call(r,a.status);return}const o=eZn(a);if(i===B$e){const h=a.getResponseHeader("Content-Range"),m=/bytes (\d+)-(\d+)\/(\d+)/.exec(h);r.onDone({begin:parseInt(m[1],10),chunk:o})}else o?r.onDone({begin:0,chunk:o}):(u=r.onError)==null||u.call(r,a.status)}getRequestXhr(t){return this.pendingRequests[t].xhr}isPendingRequest(t){return t in this.pendingRequests}abortRequest(t){const n=this.pendingRequests[t].xhr;delete this.pendingRequests[t],n.abort()}}class sZn{constructor(t){this._source=t,this._manager=new tZn(t),this._rangeChunkSize=t.rangeChunkSize,this._fullRequestReader=null,this._rangeRequestReaders=[]}_onRangeRequestReaderClosed(t){const n=this._rangeRequestReaders.indexOf(t);n>=0&&this._rangeRequestReaders.splice(n,1)}getFullReader(){return j0(!this._fullRequestReader,"PDFNetworkStream.getFullReader can only be called once."),this._fullRequestReader=new nZn(this._manager,this._source),this._fullRequestReader}getRangeReader(t,n){const r=new rZn(this._manager,t,n);return r.onClosed=this._onRangeRequestReaderClosed.bind(this),this._rangeRequestReaders.push(r),r}cancelAllRequests(t){var n;(n=this._fullRequestReader)==null||n.cancel(t);for(const r of this._rangeRequestReaders.slice(0))r.cancel(t)}}class nZn{constructor(t,n){this._manager=t;const r={onHeadersReceived:this._onHeadersReceived.bind(this),onDone:this._onDone.bind(this),onError:this._onError.bind(this),onProgress:this._onProgress.bind(this)};this._url=n.url,this._fullRequestId=t.requestFull(r),this._headersCapability=Promise.withResolvers(),this._disableRange=n.disableRange||!1,this._contentLength=n.length,this._rangeChunkSize=n.rangeChunkSize,!this._rangeChunkSize&&!this._disableRange&&(this._disableRange=!0),this._isStreamingSupported=!1,this._isRangeSupported=!1,this._cachedChunks=[],this._requests=[],this._done=!1,this._storedError=void 0,this._filename=null,this.onProgress=null}_onHeadersReceived(){const t=this._fullRequestId,n=this._manager.getRequestXhr(t),r=new Headers(n.getAllResponseHeaders().trim().split(/[\r\n]+/).map(l=>{const[o,...c]=l.split(": ");return[o,c.join(": ")]})),{allowRangeRequests:a,suggestedLength:i}=qot({responseHeaders:r,isHttp:this._manager.isHttp,rangeChunkSize:this._rangeChunkSize,disableRange:this._disableRange});a&&(this._isRangeSupported=!0),this._contentLength=i||this._contentLength,this._filename=Vot(r),this._isRangeSupported&&this._manager.abortRequest(t),this._headersCapability.resolve()}_onDone(t){if(t&&(this._requests.length>0?this._requests.shift().resolve({value:t.chunk,done:!1}):this._cachedChunks.push(t.chunk)),this._done=!0,!(this._cachedChunks.length>0)){for(const n of this._requests)n.resolve({value:void 0,done:!0});this._requests.length=0}}_onError(t){this._storedError=HDe(t,this._url),this._headersCapability.reject(this._storedError);for(const n of this._requests)n.reject(this._storedError);this._requests.length=0,this._cachedChunks.length=0}_onProgress(t){var n;(n=this.onProgress)==null||n.call(this,{loaded:t.loaded,total:t.lengthComputable?t.total:this._contentLength})}get filename(){return this._filename}get isRangeSupported(){return this._isRangeSupported}get isStreamingSupported(){return this._isStreamingSupported}get contentLength(){return this._contentLength}get headersReady(){return this._headersCapability.promise}async read(){if(this._storedError)throw this._storedError;if(this._cachedChunks.length>0)return{value:this._cachedChunks.shift(),done:!1};if(this._done)return{value:void 0,done:!0};const t=Promise.withResolvers();return this._requests.push(t),t.promise}cancel(t){this._done=!0,this._headersCapability.reject(t);for(const n of this._requests)n.resolve({value:void 0,done:!0});this._requests.length=0,this._manager.isPendingRequest(this._fullRequestId)&&this._manager.abortRequest(this._fullRequestId),this._fullRequestReader=null}}class rZn{constructor(t,n,r){this._manager=t;const a={onDone:this._onDone.bind(this),onError:this._onError.bind(this),onProgress:this._onProgress.bind(this)};this._url=t.url,this._requestId=t.requestRange(n,r,a),this._requests=[],this._queuedChunk=null,this._done=!1,this._storedError=void 0,this.onProgress=null,this.onClosed=null}_close(){var t;(t=this.onClosed)==null||t.call(this,this)}_onDone(t){const n=t.chunk;this._requests.length>0?this._requests.shift().resolve({value:n,done:!1}):this._queuedChunk=n,this._done=!0;for(const r of this._requests)r.resolve({value:void 0,done:!0});this._requests.length=0,this._close()}_onError(t){this._storedError=HDe(t,this._url);for(const n of this._requests)n.reject(this._storedError);this._requests.length=0,this._queuedChunk=null}_onProgress(t){var n;this.isStreamingSupported||(n=this.onProgress)==null||n.call(this,{loaded:t.loaded})}get isStreamingSupported(){return!1}async read(){if(this._storedError)throw this._storedError;if(this._queuedChunk!==null){const n=this._queuedChunk;return this._queuedChunk=null,{value:n,done:!1}}if(this._done)return{value:void 0,done:!0};const t=Promise.withResolvers();return this._requests.push(t),t.promise}cancel(t){this._done=!0;for(const n of this._requests)n.resolve({value:void 0,done:!0});this._requests.length=0,this._manager.isPendingRequest(this._requestId)&&this._manager.abortRequest(this._requestId),this._close()}}const aZn=/^[a-z][a-z0-9\-+.]+:/i;function iZn(s){if(aZn.test(s))return new URL(s);const t=HL.get("url");return new URL(t.pathToFileURL(s))}function bns(s,t,n){return s.protocol==="http:"?HL.get("http").request(s,{headers:t},n):HL.get("https").request(s,{headers:t},n)}class oZn{constructor(t){this.source=t,this.url=iZn(t.url),this.isHttp=this.url.protocol==="http:"||this.url.protocol==="https:",this.isFsUrl=this.url.protocol==="file:",this.headers=Uot(this.isHttp,t.httpHeaders),this._fullRequestReader=null,this._rangeRequestReaders=[]}get _progressiveDataLength(){var t;return((t=this._fullRequestReader)==null?void 0:t._loaded)??0}getFullReader(){return j0(!this._fullRequestReader,"PDFNodeStream.getFullReader can only be called once."),this._fullRequestReader=this.isFsUrl?new dZn(this):new lZn(this),this._fullRequestReader}getRangeReader(t,n){if(n<=this._progressiveDataLength)return null;const r=this.isFsUrl?new uZn(this,t,n):new cZn(this,t,n);return this._rangeRequestReaders.push(r),r}cancelAllRequests(t){var n;(n=this._fullRequestReader)==null||n.cancel(t);for(const r of this._rangeRequestReaders.slice(0))r.cancel(t)}}class _ns{constructor(t){this._url=t.url,this._done=!1,this._storedError=null,this.onProgress=null;const n=t.source;this._contentLength=n.length,this._loaded=0,this._filename=null,this._disableRange=n.disableRange||!1,this._rangeChunkSize=n.rangeChunkSize,!this._rangeChunkSize&&!this._disableRange&&(this._disableRange=!0),this._isStreamingSupported=!n.disableStream,this._isRangeSupported=!n.disableRange,this._readableStream=null,this._readCapability=Promise.withResolvers(),this._headersCapability=Promise.withResolvers()}get headersReady(){return this._headersCapability.promise}get filename(){return this._filename}get contentLength(){return this._contentLength}get isRangeSupported(){return this._isRangeSupported}get isStreamingSupported(){return this._isStreamingSupported}async read(){var r;if(await this._readCapability.promise,this._done)return{value:void 0,done:!0};if(this._storedError)throw this._storedError;const t=this._readableStream.read();return t===null?(this._readCapability=Promise.withResolvers(),this.read()):(this._loaded+=t.length,(r=this.onProgress)==null||r.call(this,{loaded:this._loaded,total:this._contentLength}),{value:new Uint8Array(t).buffer,done:!1})}cancel(t){if(!this._readableStream){this._error(t);return}this._readableStream.destroy(t)}_error(t){this._storedError=t,this._readCapability.resolve()}_setReadableStream(t){this._readableStream=t,t.on("readable",()=>{this._readCapability.resolve()}),t.on("end",()=>{t.destroy(),this._done=!0,this._readCapability.resolve()}),t.on("error",n=>{this._error(n)}),!this._isStreamingSupported&&this._isRangeSupported&&this._error(new x9("streaming is disabled")),this._storedError&&this._readableStream.destroy(this._storedError)}}class wns{constructor(t){this._url=t.url,this._done=!1,this._storedError=null,this.onProgress=null,this._loaded=0,this._readableStream=null,this._readCapability=Promise.withResolvers();const n=t.source;this._isStreamingSupported=!n.disableStream}get isStreamingSupported(){return this._isStreamingSupported}async read(){var r;if(await this._readCapability.promise,this._done)return{value:void 0,done:!0};if(this._storedError)throw this._storedError;const t=this._readableStream.read();return t===null?(this._readCapability=Promise.withResolvers(),this.read()):(this._loaded+=t.length,(r=this.onProgress)==null||r.call(this,{loaded:this._loaded}),{value:new Uint8Array(t).buffer,done:!1})}cancel(t){if(!this._readableStream){this._error(t);return}this._readableStream.destroy(t)}_error(t){this._storedError=t,this._readCapability.resolve()}_setReadableStream(t){this._readableStream=t,t.on("readable",()=>{this._readCapability.resolve()}),t.on("end",()=>{t.destroy(),this._done=!0,this._readCapability.resolve()}),t.on("error",n=>{this._error(n)}),this._storedError&&this._readableStream.destroy(this._storedError)}}class lZn extends _ns{constructor(t){super(t);const n=Object.fromEntries(t.headers),r=a=>{if(a.statusCode===404){const c=new g9(`Missing PDF "${this._url}".`);this._storedError=c,this._headersCapability.reject(c);return}this._headersCapability.resolve(),this._setReadableStream(a);const i=new Headers(this._readableStream.headers),{allowRangeRequests:l,suggestedLength:o}=qot({responseHeaders:i,isHttp:t.isHttp,rangeChunkSize:this._rangeChunkSize,disableRange:this._disableRange});this._isRangeSupported=l,this._contentLength=o||this._contentLength,this._filename=Vot(i)};this._request=bns(this._url,n,r),this._request.on("error",a=>{this._storedError=a,this._headersCapability.reject(a)}),this._request.end()}}class cZn extends wns{constructor(t,n,r){super(t);const a=Object.fromEntries(t.headers);a.Range=`bytes=${n}-${r-1}`;const i=l=>{if(l.statusCode===404){const o=new g9(`Missing PDF "${this._url}".`);this._storedError=o;return}this._setReadableStream(l)};this._request=bns(this._url,a,i),this._request.on("error",l=>{this._storedError=l}),this._request.end()}}class dZn extends _ns{constructor(t){super(t);const n=HL.get("fs");n.promises.lstat(this._url).then(r=>{this._contentLength=r.size,this._setReadableStream(n.createReadStream(this._url)),this._headersCapability.resolve()},r=>{r.code==="ENOENT"&&(r=new g9(`Missing PDF "${this._url}".`)),this._storedError=r,this._headersCapability.reject(r)})}}class uZn extends wns{constructor(t,n,r){super(t);const a=HL.get("fs");this._setReadableStream(a.createReadStream(this._url,{start:n,end:r-1}))}}const hZn=1e5,rw=30,mZn=.8;var IIt,eI,uw,Ere,Tre,iz,YA,Mre,Pre,oz,EH,TH,tI,MH,Ire,PH,lz,Lre,Rre,cz,dz,Dre,sI,IH,kT,jns,Nns,JZe,T2,W3e,eXe,kns,Sns;const o0=class o0{constructor({textContentSource:t,container:n,viewport:r}){bs(this,kT);bs(this,eI,Promise.withResolvers());bs(this,uw,null);bs(this,Ere,!1);bs(this,Tre,!!((IIt=globalThis.FontInspector)!=null&&IIt.enabled));bs(this,iz,null);bs(this,YA,null);bs(this,Mre,0);bs(this,Pre,0);bs(this,oz,null);bs(this,EH,null);bs(this,TH,0);bs(this,tI,0);bs(this,MH,Object.create(null));bs(this,Ire,[]);bs(this,PH,null);bs(this,lz,[]);bs(this,Lre,new WeakMap);bs(this,Rre,null);var c;if(t instanceof ReadableStream)Kt(this,PH,t);else if(typeof t=="object")Kt(this,PH,new ReadableStream({start(d){d.enqueue(t),d.close()}}));else throw new Error('No "textContentSource" parameter specified.');Kt(this,uw,Kt(this,EH,n)),Kt(this,tI,r.scale*(globalThis.devicePixelRatio||1)),Kt(this,TH,r.rotation),Kt(this,YA,{div:null,properties:null,ctx:null});const{pageWidth:a,pageHeight:i,pageX:l,pageY:o}=r.rawDims;Kt(this,Rre,[1,0,0,-1,-l,o+i]),Kt(this,Pre,a),Kt(this,Mre,i),ls(c=o0,T2,kns).call(c),bB(n,r),ye(this,eI).promise.finally(()=>{ye(o0,IH).delete(this),Kt(this,YA,null),Kt(this,MH,null)}).catch(()=>{})}static get fontFamilyMap(){const{isWindows:t,isFirefox:n}=T_.platform;return th(this,"fontFamilyMap",new Map([["sans-serif",`${t&&n?"Calibri, ":""}sans-serif`],["monospace",`${t&&n?"Lucida Console, ":""}monospace`]]))}render(){const t=()=>{ye(this,oz).read().then(({value:n,done:r})=>{if(r){ye(this,eI).resolve();return}ye(this,iz)??Kt(this,iz,n.lang),Object.assign(ye(this,MH),n.styles),ls(this,kT,jns).call(this,n.items),t()},ye(this,eI).reject)};return Kt(this,oz,ye(this,PH).getReader()),ye(o0,IH).add(this),t(),ye(this,eI).promise}update({viewport:t,onBefore:n=null}){var i;const r=t.scale*(globalThis.devicePixelRatio||1),a=t.rotation;if(a!==ye(this,TH)&&(n==null||n(),Kt(this,TH,a),bB(ye(this,EH),{rotation:a})),r!==ye(this,tI)){n==null||n(),Kt(this,tI,r);const l={div:null,properties:null,ctx:ls(i=o0,T2,W3e).call(i,ye(this,iz))};for(const o of ye(this,lz))l.properties=ye(this,Lre).get(o),l.div=o,ls(this,kT,JZe).call(this,l)}}cancel(){var n;const t=new x9("TextLayer task cancelled.");(n=ye(this,oz))==null||n.cancel(t).catch(()=>{}),Kt(this,oz,null),ye(this,eI).reject(t)}get textDivs(){return ye(this,lz)}get textContentItemsStr(){return ye(this,Ire)}static cleanup(){if(!(ye(this,IH).size>0)){ye(this,cz).clear();for(const{canvas:t}of ye(this,dz).values())t.remove();ye(this,dz).clear()}}};eI=new WeakMap,uw=new WeakMap,Ere=new WeakMap,Tre=new WeakMap,iz=new WeakMap,YA=new WeakMap,Mre=new WeakMap,Pre=new WeakMap,oz=new WeakMap,EH=new WeakMap,TH=new WeakMap,tI=new WeakMap,MH=new WeakMap,Ire=new WeakMap,PH=new WeakMap,lz=new WeakMap,Lre=new WeakMap,Rre=new WeakMap,cz=new WeakMap,dz=new WeakMap,Dre=new WeakMap,sI=new WeakMap,IH=new WeakMap,kT=new WeakSet,jns=function(t){var a,i;if(ye(this,Ere))return;(i=ye(this,YA)).ctx??(i.ctx=ls(a=o0,T2,W3e).call(a,ye(this,iz)));const n=ye(this,lz),r=ye(this,Ire);for(const l of t){if(n.length>hZn){nu("Ignoring additional textDivs for performance reasons."),Kt(this,Ere,!0);return}if(l.str===void 0){if(l.type==="beginMarkedContentProps"||l.type==="beginMarkedContent"){const o=ye(this,uw);Kt(this,uw,document.createElement("span")),ye(this,uw).classList.add("markedContent"),l.id!==null&&ye(this,uw).setAttribute("id",`${l.id}`),o.append(ye(this,uw))}else l.type==="endMarkedContent"&&Kt(this,uw,ye(this,uw).parentNode);continue}r.push(l.str),ls(this,kT,Nns).call(this,l)}},Nns=function(t){var x;const n=document.createElement("span"),r={angle:0,canvasWidth:0,hasText:t.str!=="",hasEOL:t.hasEOL,fontSize:0};ye(this,lz).push(n);const a=ol.transform(ye(this,Rre),t.transform);let i=Math.atan2(a[1],a[0]);const l=ye(this,MH)[t.fontName];l.vertical&&(i+=Math.PI/2);let o=ye(this,Tre)&&l.fontSubstitution||l.fontFamily;o=o0.fontFamilyMap.get(o)||o;const c=Math.hypot(a[2],a[3]),d=c*ls(x=o0,T2,Sns).call(x,o,ye(this,iz));let u,h;i===0?(u=a[4],h=a[5]-d):(u=a[4]+d*Math.sin(i),h=a[5]-d*Math.cos(i));const m="calc(var(--scale-factor)*",f=n.style;ye(this,uw)===ye(this,EH)?(f.left=`${(100*u/ye(this,Pre)).toFixed(2)}%`,f.top=`${(100*h/ye(this,Mre)).toFixed(2)}%`):(f.left=`${m}${u.toFixed(2)}px)`,f.top=`${m}${h.toFixed(2)}px)`),f.fontSize=`${m}${(ye(o0,sI)*c).toFixed(2)}px)`,f.fontFamily=o,r.fontSize=c,n.setAttribute("role","presentation"),n.textContent=t.str,n.dir=t.dir,ye(this,Tre)&&(n.dataset.fontName=l.fontSubstitutionLoadedName||t.fontName),i!==0&&(r.angle=i*(180/Math.PI));let g=!1;if(t.str.length>1)g=!0;else if(t.str!==" "&&t.transform[0]!==t.transform[3]){const y=Math.abs(t.transform[0]),v=Math.abs(t.transform[3]);y!==v&&Math.max(y,v)/Math.min(y,v)>1.5&&(g=!0)}if(g&&(r.canvasWidth=l.vertical?t.height:t.width),ye(this,Lre).set(n,r),ye(this,YA).div=n,ye(this,YA).properties=r,ls(this,kT,JZe).call(this,ye(this,YA)),r.hasText&&ye(this,uw).append(n),r.hasEOL){const y=document.createElement("br");y.setAttribute("role","presentation"),ye(this,uw).append(y)}},JZe=function(t){var o;const{div:n,properties:r,ctx:a}=t,{style:i}=n;let l="";if(ye(o0,sI)>1&&(l=`scale(${1/ye(o0,sI)})`),r.canvasWidth!==0&&r.hasText){const{fontFamily:c}=i,{canvasWidth:d,fontSize:u}=r;ls(o=o0,T2,eXe).call(o,a,u*ye(this,tI),c);const{width:h}=a.measureText(n.textContent);h>0&&(l=`scaleX(${d*ye(this,tI)/h}) ${l}`)}r.angle!==0&&(l=`rotate(${r.angle}deg) ${l}`),l.length>0&&(i.transform=l)},T2=new WeakSet,W3e=function(t=null){let n=ye(this,dz).get(t||(t=""));if(!n){const r=document.createElement("canvas");r.className="hiddenCanvasElement",r.lang=t,document.body.append(r),n=r.getContext("2d",{alpha:!1,willReadFrequently:!0}),ye(this,dz).set(t,n),ye(this,Dre).set(n,{size:0,family:""})}return n},eXe=function(t,n,r){const a=ye(this,Dre).get(t);n===a.size&&r===a.family||(t.font=`${n}px ${r}`,a.size=n,a.family=r)},kns=function(){if(ye(this,sI)!==null)return;const t=document.createElement("div");t.style.opacity=0,t.style.lineHeight=1,t.style.fontSize="1px",t.style.position="absolute",t.textContent="X",document.body.append(t),Kt(this,sI,t.getBoundingClientRect().height),t.remove()},Sns=function(t,n){const r=ye(this,cz).get(t);if(r)return r;const a=ls(this,T2,W3e).call(this,n);a.canvas.width=a.canvas.height=rw,ls(this,T2,eXe).call(this,a,rw,t);const i=a.measureText("");let l=i.fontBoundingBoxAscent,o=Math.abs(i.fontBoundingBoxDescent);if(l){const u=l/(l+o);return ye(this,cz).set(t,u),a.canvas.width=a.canvas.height=0,u}a.strokeStyle="red",a.clearRect(0,0,rw,rw),a.strokeText("g",0,0);let c=a.getImageData(0,0,rw,rw).data;o=0;for(let u=c.length-1-3;u>=0;u-=4)if(c[u]>0){o=Math.ceil(u/4/rw);break}a.clearRect(0,0,rw,rw),a.strokeText("A",0,rw),c=a.getImageData(0,0,rw,rw).data,l=0;for(let u=0,h=c.length;u0){l=rw-Math.floor(u/4/rw);break}a.canvas.width=a.canvas.height=0;const d=l?l/(l+o):mZn;return ye(this,cz).set(t,d),d},bs(o0,T2),bs(o0,cz,new Map),bs(o0,dz,new Map),bs(o0,Dre,new WeakMap),bs(o0,sI,null),bs(o0,IH,new Set);let wne=o0;class jne{static textContent(t){const n=[],r={items:n,styles:Object.create(null)};function a(i){var c;if(!i)return;let l=null;const o=i.name;if(o==="#text")l=i.value;else if(jne.shouldBuildText(o))(c=i==null?void 0:i.attributes)!=null&&c.textContent?l=i.attributes.textContent:i.value&&(l=i.value);else return;if(l!==null&&n.push({str:l}),!!i.children)for(const d of i.children)a(d)}return a(t),r}static shouldBuildText(t){return!(t==="textarea"||t==="input"||t==="option"||t==="select")}}const fZn=65536,pZn=100,gZn=5e3,xZn=y1?EYn:SYn,yZn=y1?TYn:lns,vZn=y1?AYn:CYn,bZn=y1?MYn:hns;function _Zn(s={}){typeof s=="string"||s instanceof URL?s={url:s}:(s instanceof ArrayBuffer||ArrayBuffer.isView(s))&&(s={data:s});const t=new tXe,{docId:n}=t,r=s.url?wZn(s.url):null,a=s.data?jZn(s.data):null,i=s.httpHeaders||null,l=s.withCredentials===!0,o=s.password??null,c=s.range instanceof Cns?s.range:null,d=Number.isInteger(s.rangeChunkSize)&&s.rangeChunkSize>0?s.rangeChunkSize:fZn;let u=s.worker instanceof VV?s.worker:null;const h=s.verbosity,m=typeof s.docBaseUrl=="string"&&!VDe(s.docBaseUrl)?s.docBaseUrl:null,f=typeof s.cMapUrl=="string"?s.cMapUrl:null,g=s.cMapPacked!==!1,x=s.CMapReaderFactory||yZn,y=typeof s.standardFontDataUrl=="string"?s.standardFontDataUrl:null,v=s.StandardFontDataFactory||bZn,b=s.stopAtErrors!==!0,w=Number.isInteger(s.maxImageSize)&&s.maxImageSize>-1?s.maxImageSize:-1,S=s.isEvalSupported!==!1,C=typeof s.isOffscreenCanvasSupported=="boolean"?s.isOffscreenCanvasSupported:!y1,E=typeof s.isChrome=="boolean"?s.isChrome:!T_.platform.isFirefox&&typeof window<"u"&&!!(window!=null&&window.chrome),I=Number.isInteger(s.canvasMaxAreaInBytes)?s.canvasMaxAreaInBytes:-1,P=typeof s.disableFontFace=="boolean"?s.disableFontFace:y1,R=s.fontExtraProperties===!0,D=s.enableXfa===!0,O=s.ownerDocument||globalThis.document,U=s.disableRange===!0,W=s.disableStream===!0,V=s.disableAutoFetch===!0,G=s.pdfBug===!0,Y=s.CanvasFactory||xZn,X=s.FilterFactory||vZn,ae=s.enableHWA===!0,ie=c?c.length:s.length??NaN,ne=typeof s.useSystemFonts=="boolean"?s.useSystemFonts:!y1&&!P,te=typeof s.useWorkerFetch=="boolean"?s.useWorkerFetch:x===lns&&v===hns&&f&&y&&EQ(f,document.baseURI)&&EQ(y,document.baseURI);s.canvasFactory&&o3t("`canvasFactory`-instance option, please use `CanvasFactory` instead."),s.filterFactory&&o3t("`filterFactory`-instance option, please use `FilterFactory` instead.");const J=null;nYn(h);const ce={canvasFactory:new Y({ownerDocument:O,enableHWA:ae}),filterFactory:new X({docId:n,ownerDocument:O}),cMapReaderFactory:te?null:new x({baseUrl:f,isCompressed:g}),standardFontDataFactory:te?null:new v({baseUrl:y})};if(!u){const ue={verbosity:h,port:pE.workerPort};u=ue.port?VV.fromPort(ue):new VV(ue),t._worker=u}const _e={docId:n,apiVersion:"4.8.69",data:a,password:o,disableAutoFetch:V,rangeChunkSize:d,length:ie,docBaseUrl:m,enableXfa:D,evaluatorOptions:{maxImageSize:w,disableFontFace:P,ignoreErrors:b,isEvalSupported:S,isOffscreenCanvasSupported:C,isChrome:E,canvasMaxAreaInBytes:I,fontExtraProperties:R,useSystemFonts:ne,cMapUrl:te?f:null,standardFontDataUrl:te?y:null}},he={disableFontFace:P,fontExtraProperties:R,ownerDocument:O,pdfBug:G,styleElement:J,loadingParams:{disableAutoFetch:V,enableXfa:D}};return u.promise.then(function(){if(t.destroyed)throw new Error("Loading aborted");if(u.destroyed)throw new Error("Worker was destroyed");const ue=u.messageHandler.sendWithPromise("GetDocRequest",_e,a?[a.buffer]:null);let ve;if(c)ve=new KYn(c,{disableRange:U,disableStream:W});else if(!a){if(!r)throw new Error("getDocument - no `url` parameter provided.");let Ee;y1?Ee=typeof fetch<"u"&&typeof Response<"u"&&"body"in Response.prototype&&EQ(r)?v3t:oZn:Ee=EQ(r)?v3t:sZn,ve=new Ee({url:r,length:ie,httpHeaders:i,withCredentials:l,rangeChunkSize:d,disableRange:U,disableStream:W})}return ue.then(Ee=>{if(t.destroyed)throw new Error("Loading aborted");if(u.destroyed)throw new Error("Worker was destroyed");const Se=new DQ(n,Ee,u.port),Le=new CZn(Se,t,ve,he,ce);t._transport=Le,Se.send("Ready",null)})}).catch(t._capability.reject),t}function wZn(s){if(s instanceof URL)return s.href;try{return new URL(s,window.location).href}catch{if(y1&&typeof s=="string")return s}throw new Error("Invalid PDF url data: either string or URL-object is expected in the url property.")}function jZn(s){if(y1&&typeof Buffer<"u"&&s instanceof Buffer)throw new Error("Please provide binary data as `Uint8Array`, rather than `Buffer`.");if(s instanceof Uint8Array&&s.byteLength===s.buffer.byteLength)return s;if(typeof s=="string")return UDe(s);if(s instanceof ArrayBuffer||ArrayBuffer.isView(s)||typeof s=="object"&&!isNaN(s==null?void 0:s.length))return new Uint8Array(s);throw new Error("Invalid PDF binary data: either TypedArray, string, or array-like object is expected in the data property.")}function b3t(s){return typeof s=="object"&&Number.isInteger(s==null?void 0:s.num)&&s.num>=0&&Number.isInteger(s==null?void 0:s.gen)&&s.gen>=0}var yIe;const vIe=class vIe{constructor(){this._capability=Promise.withResolvers(),this._transport=null,this._worker=null,this.docId=`d${J0(vIe,yIe)._++}`,this.destroyed=!1,this.onPassword=null,this.onProgress=null}get promise(){return this._capability.promise}async destroy(){var t,n,r;this.destroyed=!0;try{(t=this._worker)!=null&&t.port&&(this._worker._pendingDestroy=!0),await((n=this._transport)==null?void 0:n.destroy())}catch(a){throw(r=this._worker)!=null&&r.port&&delete this._worker._pendingDestroy,a}this._transport=null,this._worker&&(this._worker.destroy(),this._worker=null)}};yIe=new WeakMap,bs(vIe,yIe,0);let tXe=vIe;class Cns{constructor(t,n,r=!1,a=null){this.length=t,this.initialData=n,this.progressiveDone=r,this.contentDispositionFilename=a,this._rangeListeners=[],this._progressListeners=[],this._progressiveReadListeners=[],this._progressiveDoneListeners=[],this._readyCapability=Promise.withResolvers()}addRangeListener(t){this._rangeListeners.push(t)}addProgressListener(t){this._progressListeners.push(t)}addProgressiveReadListener(t){this._progressiveReadListeners.push(t)}addProgressiveDoneListener(t){this._progressiveDoneListeners.push(t)}onDataRange(t,n){for(const r of this._rangeListeners)r(t,n)}onDataProgress(t,n){this._readyCapability.promise.then(()=>{for(const r of this._progressListeners)r(t,n)})}onDataProgressiveRead(t){this._readyCapability.promise.then(()=>{for(const n of this._progressiveReadListeners)n(t)})}onDataProgressiveDone(){this._readyCapability.promise.then(()=>{for(const t of this._progressiveDoneListeners)t()})}transportReady(){this._readyCapability.resolve()}requestDataRange(t,n){kp("Abstract method PDFDataRangeTransport.requestDataRange")}abort(){}}class NZn{constructor(t,n){this._pdfInfo=t,this._transport=n}get annotationStorage(){return this._transport.annotationStorage}get canvasFactory(){return this._transport.canvasFactory}get filterFactory(){return this._transport.filterFactory}get numPages(){return this._pdfInfo.numPages}get fingerprints(){return this._pdfInfo.fingerprints}get isPureXfa(){return th(this,"isPureXfa",!!this._transport._htmlForXfa)}get allXfaHtml(){return this._transport._htmlForXfa}getPage(t){return this._transport.getPage(t)}getPageIndex(t){return this._transport.getPageIndex(t)}getDestinations(){return this._transport.getDestinations()}getDestination(t){return this._transport.getDestination(t)}getPageLabels(){return this._transport.getPageLabels()}getPageLayout(){return this._transport.getPageLayout()}getPageMode(){return this._transport.getPageMode()}getViewerPreferences(){return this._transport.getViewerPreferences()}getOpenAction(){return this._transport.getOpenAction()}getAttachments(){return this._transport.getAttachments()}getJSActions(){return this._transport.getDocJSActions()}getOutline(){return this._transport.getOutline()}getOptionalContentConfig({intent:t="display"}={}){const{renderingIntent:n}=this._transport.getRenderingIntent(t);return this._transport.getOptionalContentConfig(n)}getPermissions(){return this._transport.getPermissions()}getMetadata(){return this._transport.getMetadata()}getMarkInfo(){return this._transport.getMarkInfo()}getData(){return this._transport.getData()}saveDocument(){return this._transport.saveDocument()}getDownloadInfo(){return this._transport.downloadInfoCapability.promise}cleanup(t=!1){return this._transport.startCleanup(t||this.isPureXfa)}destroy(){return this.loadingTask.destroy()}cachedPageNumber(t){return this._transport.cachedPageNumber(t)}get loadingParams(){return this._transport.loadingParams}get loadingTask(){return this._transport.loadingTask}getFieldObjects(){return this._transport.getFieldObjects()}hasJSActions(){return this._transport.hasJSActions()}getCalculationOrderIds(){return this._transport.getCalculationOrderIds()}}var nI,ZA,VN,IU,K3e;class kZn{constructor(t,n,r,a=!1){bs(this,VN);bs(this,nI,null);bs(this,ZA,!1);this._pageIndex=t,this._pageInfo=n,this._transport=r,this._stats=a?new i3t:null,this._pdfBug=a,this.commonObjs=r.commonObjs,this.objs=new Ans,this._maybeCleanupAfterRender=!1,this._intentStates=new Map,this.destroyed=!1}get pageNumber(){return this._pageIndex+1}get rotate(){return this._pageInfo.rotate}get ref(){return this._pageInfo.ref}get userUnit(){return this._pageInfo.userUnit}get view(){return this._pageInfo.view}getViewport({scale:t,rotation:n=this.rotate,offsetX:r=0,offsetY:a=0,dontFlip:i=!1}={}){return new Zie({viewBox:this.view,scale:t,rotation:n,offsetX:r,offsetY:a,dontFlip:i})}getAnnotations({intent:t="display"}={}){const{renderingIntent:n}=this._transport.getRenderingIntent(t);return this._transport.getAnnotations(this._pageIndex,n)}getJSActions(){return this._transport.getPageJSActions(this._pageIndex)}get filterFactory(){return this._transport.filterFactory}get isPureXfa(){return th(this,"isPureXfa",!!this._transport._htmlForXfa)}async getXfa(){var t;return((t=this._transport._htmlForXfa)==null?void 0:t.children[this._pageIndex])||null}render({canvasContext:t,viewport:n,intent:r="display",annotationMode:a=PP.ENABLE,transform:i=null,background:l=null,optionalContentConfigPromise:o=null,annotationCanvasMap:c=null,pageColors:d=null,printAnnotationStorage:u=null,isEditing:h=!1}){var S,C;(S=this._stats)==null||S.time("Overall");const m=this._transport.getRenderingIntent(r,a,u,h),{renderingIntent:f,cacheKey:g}=m;Kt(this,ZA,!1),ls(this,VN,K3e).call(this),o||(o=this._transport.getOptionalContentConfig(f));let x=this._intentStates.get(g);x||(x=Object.create(null),this._intentStates.set(g,x)),x.streamReaderCancelTimeout&&(clearTimeout(x.streamReaderCancelTimeout),x.streamReaderCancelTimeout=null);const y=!!(f&qj.PRINT);x.displayReadyCapability||(x.displayReadyCapability=Promise.withResolvers(),x.operatorList={fnArray:[],argsArray:[],lastChunk:!1,separateAnnots:null},(C=this._stats)==null||C.time("Page Request"),this._pumpOperatorList(m));const v=E=>{var I;x.renderTasks.delete(b),(this._maybeCleanupAfterRender||y)&&Kt(this,ZA,!0),ls(this,VN,IU).call(this,!y),E?(b.capability.reject(E),this._abortOperatorList({intentState:x,reason:E instanceof Error?E:new Error(E)})):b.capability.resolve(),this._stats&&(this._stats.timeEnd("Rendering"),this._stats.timeEnd("Overall"),(I=globalThis.Stats)!=null&&I.enabled&&globalThis.Stats.add(this.pageNumber,this._stats))},b=new nXe({callback:v,params:{canvasContext:t,viewport:n,transform:i,background:l},objs:this.objs,commonObjs:this.commonObjs,annotationCanvasMap:c,operatorList:x.operatorList,pageIndex:this._pageIndex,canvasFactory:this._transport.canvasFactory,filterFactory:this._transport.filterFactory,useRequestAnimationFrame:!y,pdfBug:this._pdfBug,pageColors:d});(x.renderTasks||(x.renderTasks=new Set)).add(b);const w=b.task;return Promise.all([x.displayReadyCapability.promise,o]).then(([E,I])=>{var P;if(this.destroyed){v();return}if((P=this._stats)==null||P.time("Rendering"),!(I.renderingIntent&f))throw new Error("Must use the same `intent`-argument when calling the `PDFPageProxy.render` and `PDFDocumentProxy.getOptionalContentConfig` methods.");b.initializeGraphics({transparency:E,optionalContentConfig:I}),b.operatorListChanged()}).catch(v),w}getOperatorList({intent:t="display",annotationMode:n=PP.ENABLE,printAnnotationStorage:r=null,isEditing:a=!1}={}){var d;function i(){o.operatorList.lastChunk&&(o.opListReadCapability.resolve(o.operatorList),o.renderTasks.delete(c))}const l=this._transport.getRenderingIntent(t,n,r,a,!0);let o=this._intentStates.get(l.cacheKey);o||(o=Object.create(null),this._intentStates.set(l.cacheKey,o));let c;return o.opListReadCapability||(c=Object.create(null),c.operatorListChanged=i,o.opListReadCapability=Promise.withResolvers(),(o.renderTasks||(o.renderTasks=new Set)).add(c),o.operatorList={fnArray:[],argsArray:[],lastChunk:!1,separateAnnots:null},(d=this._stats)==null||d.time("Page Request"),this._pumpOperatorList(l)),o.opListReadCapability.promise}streamTextContent({includeMarkedContent:t=!1,disableNormalization:n=!1}={}){return this._transport.messageHandler.sendWithStream("GetTextContent",{pageIndex:this._pageIndex,includeMarkedContent:t===!0,disableNormalization:n===!0},{highWaterMark:100,size(a){return a.items.length}})}getTextContent(t={}){if(this._transport._htmlForXfa)return this.getXfa().then(r=>jne.textContent(r));const n=this.streamTextContent(t);return new Promise(function(r,a){function i(){l.read().then(function({value:c,done:d}){if(d){r(o);return}o.lang??(o.lang=c.lang),Object.assign(o.styles,c.styles),o.items.push(...c.items),i()},a)}const l=n.getReader(),o={items:[],styles:Object.create(null),lang:null};i()})}getStructTree(){return this._transport.getStructTree(this._pageIndex)}_destroy(){this.destroyed=!0;const t=[];for(const n of this._intentStates.values())if(this._abortOperatorList({intentState:n,reason:new Error("Page was destroyed."),force:!0}),!n.opListReadCapability)for(const r of n.renderTasks)t.push(r.completed),r.cancel();return this.objs.clear(),Kt(this,ZA,!1),ls(this,VN,K3e).call(this),Promise.all(t)}cleanup(t=!1){Kt(this,ZA,!0);const n=ls(this,VN,IU).call(this,!1);return t&&n&&this._stats&&(this._stats=new i3t),n}_startRenderPage(t,n){var a,i;const r=this._intentStates.get(n);r&&((a=this._stats)==null||a.timeEnd("Page Request"),(i=r.displayReadyCapability)==null||i.resolve(t))}_renderPageChunk(t,n){for(let r=0,a=t.length;r{c.read().then(({value:h,done:m})=>{if(m){d.streamReader=null;return}this._transport.destroyed||(this._renderPageChunk(h,d),u())},h=>{if(d.streamReader=null,!this._transport.destroyed){if(d.operatorList){d.operatorList.lastChunk=!0;for(const m of d.renderTasks)m.operatorListChanged();ls(this,VN,IU).call(this,!0)}if(d.displayReadyCapability)d.displayReadyCapability.reject(h);else if(d.opListReadCapability)d.opListReadCapability.reject(h);else throw h}})};u()}_abortOperatorList({intentState:t,reason:n,force:r=!1}){if(t.streamReader){if(t.streamReaderCancelTimeout&&(clearTimeout(t.streamReaderCancelTimeout),t.streamReaderCancelTimeout=null),!r){if(t.renderTasks.size>0)return;if(n instanceof Dot){let a=pZn;n.extraDelay>0&&n.extraDelay<1e3&&(a+=n.extraDelay),t.streamReaderCancelTimeout=setTimeout(()=>{t.streamReaderCancelTimeout=null,this._abortOperatorList({intentState:t,reason:n,force:!0})},a);return}}if(t.streamReader.cancel(new x9(n.message)).catch(()=>{}),t.streamReader=null,!this._transport.destroyed){for(const[a,i]of this._intentStates)if(i===t){this._intentStates.delete(a);break}this.cleanup()}}}get stats(){return this._stats}}nI=new WeakMap,ZA=new WeakMap,VN=new WeakSet,IU=function(t=!1){if(ls(this,VN,K3e).call(this),!ye(this,ZA)||this.destroyed)return!1;if(t)return Kt(this,nI,setTimeout(()=>{Kt(this,nI,null),ls(this,VN,IU).call(this,!1)},gZn)),!1;for(const{renderTasks:n,operatorList:r}of this._intentStates.values())if(n.size>0||!r.lastChunk)return!1;return this._intentStates.clear(),this.objs.clear(),Kt(this,ZA,!1),!0},K3e=function(){ye(this,nI)&&(clearTimeout(ye(this,nI)),Kt(this,nI,null))};var XA,bIe;class SZn{constructor(){bs(this,XA,new Map);bs(this,bIe,Promise.resolve())}postMessage(t,n){const r={data:structuredClone(t,n?{transfer:n}:null)};ye(this,bIe).then(()=>{for(const[a]of ye(this,XA))a.call(this,r)})}addEventListener(t,n,r=null){let a=null;if((r==null?void 0:r.signal)instanceof AbortSignal){const{signal:i}=r;if(i.aborted){nu("LoopbackPort - cannot use an `aborted` signal.");return}const l=()=>this.removeEventListener(t,n);a=()=>i.removeEventListener("abort",l),i.addEventListener("abort",l)}ye(this,XA).set(n,a)}removeEventListener(t,n){const r=ye(this,XA).get(n);r==null||r(),ye(this,XA).delete(n)}terminate(){for(const[,t]of ye(this,XA))t==null||t();ye(this,XA).clear()}}XA=new WeakMap,bIe=new WeakMap;var _Ie,uz,hz,LH,Y3e,RH,Z3e;const Bp=class Bp{constructor({name:t=null,port:n=null,verbosity:r=rYn()}={}){bs(this,LH);var a;if(this.name=t,this.destroyed=!1,this.verbosity=r,this._readyCapability=Promise.withResolvers(),this._port=null,this._webWorker=null,this._messageHandler=null,n){if((a=ye(Bp,hz))!=null&&a.has(n))throw new Error("Cannot use more than one PDFWorker per port.");(ye(Bp,hz)||Kt(Bp,hz,new WeakMap)).set(n,this),this._initializeFromPort(n);return}this._initialize()}get promise(){return y1?Promise.all([HL.promise,this._readyCapability.promise]):this._readyCapability.promise}get port(){return this._port}get messageHandler(){return this._messageHandler}_initializeFromPort(t){this._port=t,this._messageHandler=new DQ("main","worker",t),this._messageHandler.on("ready",function(){}),ls(this,LH,Y3e).call(this)}_initialize(){if(ye(Bp,uz)||ye(Bp,RH,Z3e)){this._setupFakeWorker();return}let{workerSrc:t}=Bp;try{Bp._isSameOrigin(window.location.href,t)||(t=Bp._createCDNWrapper(new URL(t,window.location).href));const n=new Worker(t,{type:"module"}),r=new DQ("main","worker",n),a=()=>{i.abort(),r.destroy(),n.terminate(),this.destroyed?this._readyCapability.reject(new Error("Worker was destroyed")):this._setupFakeWorker()},i=new AbortController;n.addEventListener("error",()=>{this._webWorker||a()},{signal:i.signal}),r.on("test",o=>{if(i.abort(),this.destroyed||!o){a();return}this._messageHandler=r,this._port=n,this._webWorker=n,ls(this,LH,Y3e).call(this)}),r.on("ready",o=>{if(i.abort(),this.destroyed){a();return}try{l()}catch{this._setupFakeWorker()}});const l=()=>{const o=new Uint8Array;r.send("test",o,[o.buffer])};l();return}catch{BDe("The worker has been disabled.")}this._setupFakeWorker()}_setupFakeWorker(){ye(Bp,uz)||(nu("Setting up fake worker."),Kt(Bp,uz,!0)),Bp._setupFakeWorkerGlobal.then(t=>{if(this.destroyed){this._readyCapability.reject(new Error("Worker was destroyed"));return}const n=new SZn;this._port=n;const r=`fake${J0(Bp,_Ie)._++}`,a=new DQ(r+"_worker",r,n);t.setup(a,n),this._messageHandler=new DQ(r,r+"_worker",n),ls(this,LH,Y3e).call(this)}).catch(t=>{this._readyCapability.reject(new Error(`Setting up fake worker failed: "${t.message}".`))})}destroy(){var t;this.destroyed=!0,this._webWorker&&(this._webWorker.terminate(),this._webWorker=null),(t=ye(Bp,hz))==null||t.delete(this._port),this._port=null,this._messageHandler&&(this._messageHandler.destroy(),this._messageHandler=null)}static fromPort(t){var r;if(!(t!=null&&t.port))throw new Error("PDFWorker.fromPort - invalid method signature.");const n=(r=ye(this,hz))==null?void 0:r.get(t.port);if(n){if(n._pendingDestroy)throw new Error("PDFWorker.fromPort - the worker is being destroyed.\nPlease remember to await `PDFDocumentLoadingTask.destroy()`-calls.");return n}return new Bp(t)}static get workerSrc(){if(pE.workerSrc)return pE.workerSrc;throw new Error('No "GlobalWorkerOptions.workerSrc" specified.')}static get _setupFakeWorkerGlobal(){return th(this,"_setupFakeWorkerGlobal",(async()=>ye(this,RH,Z3e)?ye(this,RH,Z3e):(await import(this.workerSrc)).WorkerMessageHandler)())}};_Ie=new WeakMap,uz=new WeakMap,hz=new WeakMap,LH=new WeakSet,Y3e=function(){this._readyCapability.resolve(),this._messageHandler.send("configure",{verbosity:this.verbosity})},RH=new WeakSet,Z3e=function(){var t;try{return((t=globalThis.pdfjsWorker)==null?void 0:t.WorkerMessageHandler)||null}catch{return null}},bs(Bp,RH),bs(Bp,_Ie,0),bs(Bp,uz,!1),bs(Bp,hz),y1&&(Kt(Bp,uz,!0),pE.workerSrc||(pE.workerSrc="./pdf.worker.mjs")),Bp._isSameOrigin=(t,n)=>{let r;try{if(r=new URL(t),!r.origin||r.origin==="null")return!1}catch{return!1}const a=new URL(n,r);return r.origin===a.origin},Bp._createCDNWrapper=t=>{const n=`await import("${t}");`;return URL.createObjectURL(new Blob([n],{type:"text/javascript"}))};let VV=Bp;var QA,K5,DH,FH,Y5,mz,FQ;class CZn{constructor(t,n,r,a,i){bs(this,mz);bs(this,QA,new Map);bs(this,K5,new Map);bs(this,DH,new Map);bs(this,FH,new Map);bs(this,Y5,null);this.messageHandler=t,this.loadingTask=n,this.commonObjs=new Ans,this.fontLoader=new NYn({ownerDocument:a.ownerDocument,styleElement:a.styleElement}),this.loadingParams=a.loadingParams,this._params=a,this.canvasFactory=i.canvasFactory,this.filterFactory=i.filterFactory,this.cMapReaderFactory=i.cMapReaderFactory,this.standardFontDataFactory=i.standardFontDataFactory,this.destroyed=!1,this.destroyCapability=null,this._networkStream=r,this._fullReader=null,this._lastProgress=null,this.downloadInfoCapability=Promise.withResolvers(),this.setupMessageHandler()}get annotationStorage(){return th(this,"annotationStorage",new Bot)}getRenderingIntent(t,n=PP.ENABLE,r=null,a=!1,i=!1){let l=qj.DISPLAY,o=VZe;switch(t){case"any":l=qj.ANY;break;case"display":break;case"print":l=qj.PRINT;break;default:nu(`getRenderingIntent - invalid intent: ${t}`)}const c=l&qj.PRINT&&r instanceof ans?r:this.annotationStorage;switch(n){case PP.DISABLE:l+=qj.ANNOTATIONS_DISABLE;break;case PP.ENABLE:break;case PP.ENABLE_FORMS:l+=qj.ANNOTATIONS_FORMS;break;case PP.ENABLE_STORAGE:l+=qj.ANNOTATIONS_STORAGE,o=c.serializable;break;default:nu(`getRenderingIntent - invalid annotationMode: ${n}`)}a&&(l+=qj.IS_EDITING),i&&(l+=qj.OPLIST);const{ids:d,hash:u}=c.modifiedIds,h=[l,o.hash,u];return{renderingIntent:l,cacheKey:h.join("_"),annotationStorageSerializable:o,modifiedIds:d}}destroy(){var r;if(this.destroyCapability)return this.destroyCapability.promise;this.destroyed=!0,this.destroyCapability=Promise.withResolvers(),(r=ye(this,Y5))==null||r.reject(new Error("Worker was destroyed during onPassword callback"));const t=[];for(const a of ye(this,K5).values())t.push(a._destroy());ye(this,K5).clear(),ye(this,DH).clear(),ye(this,FH).clear(),this.hasOwnProperty("annotationStorage")&&this.annotationStorage.resetModified();const n=this.messageHandler.sendWithPromise("Terminate",null);return t.push(n),Promise.all(t).then(()=>{var a;this.commonObjs.clear(),this.fontLoader.clear(),ye(this,QA).clear(),this.filterFactory.destroy(),wne.cleanup(),(a=this._networkStream)==null||a.cancelAllRequests(new x9("Worker was terminated.")),this.messageHandler&&(this.messageHandler.destroy(),this.messageHandler=null),this.destroyCapability.resolve()},this.destroyCapability.reject),this.destroyCapability.promise}setupMessageHandler(){const{messageHandler:t,loadingTask:n}=this;t.on("GetReader",(r,a)=>{j0(this._networkStream,"GetReader - no `IPDFStream` instance available."),this._fullReader=this._networkStream.getFullReader(),this._fullReader.onProgress=i=>{this._lastProgress={loaded:i.loaded,total:i.total}},a.onPull=()=>{this._fullReader.read().then(function({value:i,done:l}){if(l){a.close();return}j0(i instanceof ArrayBuffer,"GetReader - expected an ArrayBuffer."),a.enqueue(new Uint8Array(i),1,[i])}).catch(i=>{a.error(i)})},a.onCancel=i=>{this._fullReader.cancel(i),a.ready.catch(l=>{if(!this.destroyed)throw l})}}),t.on("ReaderHeadersReady",async r=>{var o;await this._fullReader.headersReady;const{isStreamingSupported:a,isRangeSupported:i,contentLength:l}=this._fullReader;return(!a||!i)&&(this._lastProgress&&((o=n.onProgress)==null||o.call(n,this._lastProgress)),this._fullReader.onProgress=c=>{var d;(d=n.onProgress)==null||d.call(n,{loaded:c.loaded,total:c.total})}),{isStreamingSupported:a,isRangeSupported:i,contentLength:l}}),t.on("GetRangeReader",(r,a)=>{j0(this._networkStream,"GetRangeReader - no `IPDFStream` instance available.");const i=this._networkStream.getRangeReader(r.begin,r.end);if(!i){a.close();return}a.onPull=()=>{i.read().then(function({value:l,done:o}){if(o){a.close();return}j0(l instanceof ArrayBuffer,"GetRangeReader - expected an ArrayBuffer."),a.enqueue(new Uint8Array(l),1,[l])}).catch(l=>{a.error(l)})},a.onCancel=l=>{i.cancel(l),a.ready.catch(o=>{if(!this.destroyed)throw o})}}),t.on("GetDoc",({pdfInfo:r})=>{this._numPages=r.numPages,this._htmlForXfa=r.htmlForXfa,delete r.htmlForXfa,n._capability.resolve(new NZn(r,this))}),t.on("DocException",function(r){let a;switch(r.name){case"PasswordException":a=new wZe(r.message,r.code);break;case"InvalidPDFException":a=new Mss(r.message);break;case"MissingPDFException":a=new g9(r.message);break;case"UnexpectedResponseException":a=new $De(r.message,r.status);break;case"UnknownErrorException":a=new jZe(r.message,r.details);break;default:kp("DocException - expected a valid Error.")}n._capability.reject(a)}),t.on("PasswordRequest",r=>{if(Kt(this,Y5,Promise.withResolvers()),n.onPassword){const a=i=>{i instanceof Error?ye(this,Y5).reject(i):ye(this,Y5).resolve({password:i})};try{n.onPassword(a,r.code)}catch(i){ye(this,Y5).reject(i)}}else ye(this,Y5).reject(new wZe(r.message,r.code));return ye(this,Y5).promise}),t.on("DataLoaded",r=>{var a;(a=n.onProgress)==null||a.call(n,{loaded:r.length,total:r.length}),this.downloadInfoCapability.resolve(r)}),t.on("StartRenderPage",r=>{if(this.destroyed)return;ye(this,K5).get(r.pageIndex)._startRenderPage(r.transparency,r.cacheKey)}),t.on("commonobj",([r,a,i])=>{var l;if(this.destroyed||this.commonObjs.has(r))return null;switch(a){case"Font":const{disableFontFace:o,fontExtraProperties:c,pdfBug:d}=this._params;if("error"in i){const f=i.error;nu(`Error during font loading: ${f}`),this.commonObjs.resolve(r,f);break}const u=d&&((l=globalThis.FontInspector)!=null&&l.enabled)?(f,g)=>globalThis.FontInspector.fontAdded(f,g):null,h=new kYn(i,{disableFontFace:o,inspectFont:u});this.fontLoader.bind(h).catch(()=>t.sendWithPromise("FontFallback",{id:r})).finally(()=>{!c&&h.data&&(h.data=null),this.commonObjs.resolve(r,h)});break;case"CopyLocalImage":const{imageRef:m}=i;j0(m,"The imageRef must be defined.");for(const f of ye(this,K5).values())for(const[,g]of f.objs)if((g==null?void 0:g.ref)===m)return g.dataLen?(this.commonObjs.resolve(r,structuredClone(g)),g.dataLen):null;break;case"FontPath":case"Image":case"Pattern":this.commonObjs.resolve(r,i);break;default:throw new Error(`Got unknown common object type ${a}`)}return null}),t.on("obj",([r,a,i,l])=>{var c;if(this.destroyed)return;const o=ye(this,K5).get(a);if(!o.objs.has(r)){if(o._intentStates.size===0){(c=l==null?void 0:l.bitmap)==null||c.close();return}switch(i){case"Image":o.objs.resolve(r,l),(l==null?void 0:l.dataLen)>JKn&&(o._maybeCleanupAfterRender=!0);break;case"Pattern":o.objs.resolve(r,l);break;default:throw new Error(`Got unknown object type ${i}`)}}}),t.on("DocProgress",r=>{var a;this.destroyed||(a=n.onProgress)==null||a.call(n,{loaded:r.loaded,total:r.total})}),t.on("FetchBuiltInCMap",async r=>{if(this.destroyed)throw new Error("Worker was destroyed.");if(!this.cMapReaderFactory)throw new Error("CMapReaderFactory not initialized, see the `useWorkerFetch` parameter.");return this.cMapReaderFactory.fetch(r)}),t.on("FetchStandardFontData",async r=>{if(this.destroyed)throw new Error("Worker was destroyed.");if(!this.standardFontDataFactory)throw new Error("StandardFontDataFactory not initialized, see the `useWorkerFetch` parameter.");return this.standardFontDataFactory.fetch(r)})}getData(){return this.messageHandler.sendWithPromise("GetData",null)}saveDocument(){var r;this.annotationStorage.size<=0&&nu("saveDocument called while `annotationStorage` is empty, please use the getData-method instead.");const{map:t,transfer:n}=this.annotationStorage.serializable;return this.messageHandler.sendWithPromise("SaveDocument",{isPureXfa:!!this._htmlForXfa,numPages:this._numPages,annotationStorage:t,filename:((r=this._fullReader)==null?void 0:r.filename)??null},n).finally(()=>{this.annotationStorage.resetModified()})}getPage(t){if(!Number.isInteger(t)||t<=0||t>this._numPages)return Promise.reject(new Error("Invalid page request."));const n=t-1,r=ye(this,DH).get(n);if(r)return r;const a=this.messageHandler.sendWithPromise("GetPage",{pageIndex:n}).then(i=>{if(this.destroyed)throw new Error("Transport destroyed");i.refStr&&ye(this,FH).set(i.refStr,t);const l=new kZn(n,i,this,this._params.pdfBug);return ye(this,K5).set(n,l),l});return ye(this,DH).set(n,a),a}getPageIndex(t){return b3t(t)?this.messageHandler.sendWithPromise("GetPageIndex",{num:t.num,gen:t.gen}):Promise.reject(new Error("Invalid pageIndex request."))}getAnnotations(t,n){return this.messageHandler.sendWithPromise("GetAnnotations",{pageIndex:t,intent:n})}getFieldObjects(){return ls(this,mz,FQ).call(this,"GetFieldObjects")}hasJSActions(){return ls(this,mz,FQ).call(this,"HasJSActions")}getCalculationOrderIds(){return this.messageHandler.sendWithPromise("GetCalculationOrderIds",null)}getDestinations(){return this.messageHandler.sendWithPromise("GetDestinations",null)}getDestination(t){return typeof t!="string"?Promise.reject(new Error("Invalid destination request.")):this.messageHandler.sendWithPromise("GetDestination",{id:t})}getPageLabels(){return this.messageHandler.sendWithPromise("GetPageLabels",null)}getPageLayout(){return this.messageHandler.sendWithPromise("GetPageLayout",null)}getPageMode(){return this.messageHandler.sendWithPromise("GetPageMode",null)}getViewerPreferences(){return this.messageHandler.sendWithPromise("GetViewerPreferences",null)}getOpenAction(){return this.messageHandler.sendWithPromise("GetOpenAction",null)}getAttachments(){return this.messageHandler.sendWithPromise("GetAttachments",null)}getDocJSActions(){return ls(this,mz,FQ).call(this,"GetDocJSActions")}getPageJSActions(t){return this.messageHandler.sendWithPromise("GetPageJSActions",{pageIndex:t})}getStructTree(t){return this.messageHandler.sendWithPromise("GetStructTree",{pageIndex:t})}getOutline(){return this.messageHandler.sendWithPromise("GetOutline",null)}getOptionalContentConfig(t){return ls(this,mz,FQ).call(this,"GetOptionalContentConfig").then(n=>new WYn(n,t))}getPermissions(){return this.messageHandler.sendWithPromise("GetPermissions",null)}getMetadata(){const t="GetMetadata",n=ye(this,QA).get(t);if(n)return n;const r=this.messageHandler.sendWithPromise(t,null).then(a=>{var i,l;return{info:a[0],metadata:a[1]?new HYn(a[1]):null,contentDispositionFilename:((i=this._fullReader)==null?void 0:i.filename)??null,contentLength:((l=this._fullReader)==null?void 0:l.contentLength)??null}});return ye(this,QA).set(t,r),r}getMarkInfo(){return this.messageHandler.sendWithPromise("GetMarkInfo",null)}async startCleanup(t=!1){if(!this.destroyed){await this.messageHandler.sendWithPromise("Cleanup",null);for(const n of ye(this,K5).values())if(!n.cleanup())throw new Error(`startCleanup: Page ${n.pageNumber} is currently rendering.`);this.commonObjs.clear(),t||this.fontLoader.clear(),ye(this,QA).clear(),this.filterFactory.destroy(!0),wne.cleanup()}}cachedPageNumber(t){if(!b3t(t))return null;const n=t.gen===0?`${t.num}R`:`${t.num}R${t.gen}`;return ye(this,FH).get(n)??null}}QA=new WeakMap,K5=new WeakMap,DH=new WeakMap,FH=new WeakMap,Y5=new WeakMap,mz=new WeakSet,FQ=function(t,n=null){const r=ye(this,QA).get(t);if(r)return r;const a=this.messageHandler.sendWithPromise(t,n);return ye(this,QA).set(t,a),a};const Rue=Symbol("INITIAL_DATA");var kS,Fre,sXe;class Ans{constructor(){bs(this,Fre);bs(this,kS,Object.create(null))}get(t,n=null){if(n){const a=ls(this,Fre,sXe).call(this,t);return a.promise.then(()=>n(a.data)),null}const r=ye(this,kS)[t];if(!r||r.data===Rue)throw new Error(`Requesting object that isn't resolved yet ${t}.`);return r.data}has(t){const n=ye(this,kS)[t];return!!n&&n.data!==Rue}resolve(t,n=null){const r=ls(this,Fre,sXe).call(this,t);r.data=n,r.resolve()}clear(){var t;for(const n in ye(this,kS)){const{data:r}=ye(this,kS)[n];(t=r==null?void 0:r.bitmap)==null||t.close()}Kt(this,kS,Object.create(null))}*[Symbol.iterator](){for(const t in ye(this,kS)){const{data:n}=ye(this,kS)[t];n!==Rue&&(yield[t,n])}}}kS=new WeakMap,Fre=new WeakSet,sXe=function(t){var n;return(n=ye(this,kS))[t]||(n[t]={...Promise.withResolvers(),data:Rue})};var rI;class AZn{constructor(t){bs(this,rI,null);Kt(this,rI,t),this.onContinue=null}get promise(){return ye(this,rI).capability.promise}cancel(t=0){ye(this,rI).cancel(null,t)}get separateAnnots(){const{separateAnnots:t}=ye(this,rI).operatorList;if(!t)return!1;const{annotationCanvasMap:n}=ye(this,rI);return t.form||t.canvas&&(n==null?void 0:n.size)>0}}rI=new WeakMap;var aI,fz;const r8=class r8{constructor({callback:t,params:n,objs:r,commonObjs:a,annotationCanvasMap:i,operatorList:l,pageIndex:o,canvasFactory:c,filterFactory:d,useRequestAnimationFrame:u=!1,pdfBug:h=!1,pageColors:m=null}){bs(this,aI,null);this.callback=t,this.params=n,this.objs=r,this.commonObjs=a,this.annotationCanvasMap=i,this.operatorListIdx=null,this.operatorList=l,this._pageIndex=o,this.canvasFactory=c,this.filterFactory=d,this._pdfBug=h,this.pageColors=m,this.running=!1,this.graphicsReadyCallback=null,this.graphicsReady=!1,this._useRequestAnimationFrame=u===!0&&typeof window<"u",this.cancelled=!1,this.capability=Promise.withResolvers(),this.task=new AZn(this),this._cancelBound=this.cancel.bind(this),this._continueBound=this._continue.bind(this),this._scheduleNextBound=this._scheduleNext.bind(this),this._nextBound=this._next.bind(this),this._canvas=n.canvasContext.canvas}get completed(){return this.capability.promise.catch(function(){})}initializeGraphics({transparency:t=!1,optionalContentConfig:n}){var o,c;if(this.cancelled)return;if(this._canvas){if(ye(r8,fz).has(this._canvas))throw new Error("Cannot use the same canvas during multiple render() operations. Use different canvas or ensure previous operations were cancelled or completed.");ye(r8,fz).add(this._canvas)}this._pdfBug&&((o=globalThis.StepperManager)!=null&&o.enabled)&&(this.stepper=globalThis.StepperManager.create(this._pageIndex),this.stepper.init(this.operatorList),this.stepper.nextBreakPoint=this.stepper.getNextBreakPoint());const{canvasContext:r,viewport:a,transform:i,background:l}=this.params;this.gfx=new qV(r,this.commonObjs,this.objs,this.canvasFactory,this.filterFactory,{optionalContentConfig:n},this.annotationCanvasMap,this.pageColors),this.gfx.beginDrawing({transform:i,viewport:a,transparency:t,background:l}),this.operatorListIdx=0,this.graphicsReady=!0,(c=this.graphicsReadyCallback)==null||c.call(this)}cancel(t=null,n=0){var r;this.running=!1,this.cancelled=!0,(r=this.gfx)==null||r.endDrawing(),ye(this,aI)&&(window.cancelAnimationFrame(ye(this,aI)),Kt(this,aI,null)),ye(r8,fz).delete(this._canvas),this.callback(t||new Dot(`Rendering cancelled, page ${this._pageIndex+1}`,n))}operatorListChanged(){var t;if(!this.graphicsReady){this.graphicsReadyCallback||(this.graphicsReadyCallback=this._continueBound);return}(t=this.stepper)==null||t.updateOperatorList(this.operatorList),!this.running&&this._continue()}_continue(){this.running=!0,!this.cancelled&&(this.task.onContinue?this.task.onContinue(this._scheduleNextBound):this._scheduleNext())}_scheduleNext(){this._useRequestAnimationFrame?Kt(this,aI,window.requestAnimationFrame(()=>{Kt(this,aI,null),this._nextBound().catch(this._cancelBound)})):Promise.resolve().then(this._nextBound).catch(this._cancelBound)}async _next(){this.cancelled||(this.operatorListIdx=this.gfx.executeOperatorList(this.operatorList,this.operatorListIdx,this._continueBound,this.stepper),this.operatorListIdx===this.operatorList.argsArray.length&&(this.running=!1,this.operatorList.lastChunk&&(this.gfx.endDrawing(),ye(r8,fz).delete(this._canvas),this.callback())))}};aI=new WeakMap,fz=new WeakMap,bs(r8,fz,new WeakSet);let nXe=r8;const EZn="4.8.69",TZn="3634dab10";function _3t(s){return Math.floor(Math.max(0,Math.min(1,s))*255).toString(16).padStart(2,"0")}function pX(s){return Math.max(0,Math.min(255,255*s))}class w3t{static CMYK_G([t,n,r,a]){return["G",1-Math.min(1,.3*t+.59*r+.11*n+a)]}static G_CMYK([t]){return["CMYK",0,0,0,1-t]}static G_RGB([t]){return["RGB",t,t,t]}static G_rgb([t]){return t=pX(t),[t,t,t]}static G_HTML([t]){const n=_3t(t);return`#${n}${n}${n}`}static RGB_G([t,n,r]){return["G",.3*t+.59*n+.11*r]}static RGB_rgb(t){return t.map(pX)}static RGB_HTML(t){return`#${t.map(_3t).join("")}`}static T_HTML(){return"#00000000"}static T_rgb(){return[null]}static CMYK_RGB([t,n,r,a]){return["RGB",1-Math.min(1,t+a),1-Math.min(1,r+a),1-Math.min(1,n+a)]}static CMYK_rgb([t,n,r,a]){return[pX(1-Math.min(1,t+a)),pX(1-Math.min(1,r+a)),pX(1-Math.min(1,n+a))]}static CMYK_HTML(t){const n=this.CMYK_RGB(t).slice(1);return this.RGB_HTML(n)}static RGB_CMYK([t,n,r]){const a=1-t,i=1-n,l=1-r,o=Math.min(a,i,l);return["CMYK",a,i,l,o]}}class MZn{create(t,n,r=!1){if(t<=0||n<=0)throw new Error("Invalid SVG dimensions");const a=this._createSVG("svg:svg");return a.setAttribute("version","1.1"),r||(a.setAttribute("width",`${t}px`),a.setAttribute("height",`${n}px`)),a.setAttribute("preserveAspectRatio","none"),a.setAttribute("viewBox",`0 0 ${t} ${n}`),a}createElement(t){if(typeof t!="string")throw new Error("Invalid SVG element type");return this._createSVG(t)}_createSVG(t){kp("Abstract method `_createSVG` called.")}}class Hot extends MZn{_createSVG(t){return document.createElementNS(jA,t)}}class Ens{static setupStorage(t,n,r,a,i){const l=a.getValue(n,{value:null});switch(r.name){case"textarea":if(l.value!==null&&(t.textContent=l.value),i==="print")break;t.addEventListener("input",o=>{a.setValue(n,{value:o.target.value})});break;case"input":if(r.attributes.type==="radio"||r.attributes.type==="checkbox"){if(l.value===r.attributes.xfaOn?t.setAttribute("checked",!0):l.value===r.attributes.xfaOff&&t.removeAttribute("checked"),i==="print")break;t.addEventListener("change",o=>{a.setValue(n,{value:o.target.checked?o.target.getAttribute("xfaOn"):o.target.getAttribute("xfaOff")})})}else{if(l.value!==null&&t.setAttribute("value",l.value),i==="print")break;t.addEventListener("input",o=>{a.setValue(n,{value:o.target.value})})}break;case"select":if(l.value!==null){t.setAttribute("value",l.value);for(const o of r.children)o.attributes.value===l.value?o.attributes.selected=!0:o.attributes.hasOwnProperty("selected")&&delete o.attributes.selected}t.addEventListener("input",o=>{const c=o.target.options,d=c.selectedIndex===-1?"":c[c.selectedIndex].value;a.setValue(n,{value:d})});break}}static setAttributes({html:t,element:n,storage:r=null,intent:a,linkService:i}){const{attributes:l}=n,o=t instanceof HTMLAnchorElement;l.type==="radio"&&(l.name=`${l.name}-${a}`);for(const[c,d]of Object.entries(l))if(d!=null)switch(c){case"class":d.length&&t.setAttribute(c,d.join(" "));break;case"dataId":break;case"id":t.setAttribute("data-element-id",d);break;case"style":Object.assign(t.style,d);break;case"textContent":t.textContent=d;break;default:(!o||c!=="href"&&c!=="newWindow")&&t.setAttribute(c,d)}o&&i.addLinkAttributes(t,l.href,l.newWindow),r&&l.dataId&&this.setupStorage(t,l.dataId,n,r)}static render(t){var h,m;const n=t.annotationStorage,r=t.linkService,a=t.xfaHtml,i=t.intent||"display",l=document.createElement(a.name);a.attributes&&this.setAttributes({html:l,element:a,intent:i,linkService:r});const o=i!=="richText",c=t.div;if(c.append(l),t.viewport){const f=`matrix(${t.viewport.transform.join(",")})`;c.style.transform=f}o&&c.setAttribute("class","xfaLayer xfaFont");const d=[];if(a.children.length===0){if(a.value){const f=document.createTextNode(a.value);l.append(f),o&&jne.shouldBuildText(a.name)&&d.push(f)}return{textDivs:d}}const u=[[a,-1,l]];for(;u.length>0;){const[f,g,x]=u.at(-1);if(g+1===f.children.length){u.pop();continue}const y=f.children[++u.at(-1)[1]];if(y===null)continue;const{name:v}=y;if(v==="#text"){const w=document.createTextNode(y.value);d.push(w),x.append(w);continue}const b=(h=y==null?void 0:y.attributes)!=null&&h.xmlns?document.createElementNS(y.attributes.xmlns,v):document.createElement(v);if(x.append(b),y.attributes&&this.setAttributes({html:b,element:y,storage:n,intent:i,linkService:r}),((m=y.children)==null?void 0:m.length)>0)u.push([y,-1,b]);else if(y.value){const w=document.createTextNode(y.value);o&&jne.shouldBuildText(v)&&d.push(w),b.append(w)}}for(const f of c.querySelectorAll(".xfaNonInteractive input, .xfaNonInteractive textarea"))f.setAttribute("readOnly",!0);return{textDivs:d}}static update(t){const n=`matrix(${t.viewport.transform.join(",")})`;t.div.style.transform=n,t.div.hidden=!1}}const Qie=1e3,PZn=9,wB=new WeakSet;function YE(s){return{width:s[2]-s[0],height:s[3]-s[1]}}class IZn{static create(t){switch(t.data.annotationType){case i0.LINK:return new Tns(t);case i0.TEXT:return new LZn(t);case i0.WIDGET:switch(t.data.fieldType){case"Tx":return new RZn(t);case"Btn":return t.data.radioButton?new Ins(t):t.data.checkBox?new FZn(t):new OZn(t);case"Ch":return new zZn(t);case"Sig":return new DZn(t)}return new y9(t);case i0.POPUP:return new aXe(t);case i0.FREETEXT:return new Ons(t);case i0.LINE:return new $Zn(t);case i0.SQUARE:return new UZn(t);case i0.CIRCLE:return new qZn(t);case i0.POLYLINE:return new zns(t);case i0.CARET:return new HZn(t);case i0.INK:return new Got(t);case i0.POLYGON:return new VZn(t);case i0.HIGHLIGHT:return new Bns(t);case i0.UNDERLINE:return new GZn(t);case i0.SQUIGGLY:return new WZn(t);case i0.STRIKEOUT:return new KZn(t);case i0.STAMP:return new $ns(t);case i0.FILEATTACHMENT:return new YZn(t);default:return new gy(t)}}}var pz,OH,zH,Ore,rXe;const ldt=class ldt{constructor(t,{isRenderable:n=!1,ignoreBorder:r=!1,createQuadrilaterals:a=!1}={}){bs(this,Ore);bs(this,pz,null);bs(this,OH,!1);bs(this,zH,null);this.isRenderable=n,this.data=t.data,this.layer=t.layer,this.linkService=t.linkService,this.downloadManager=t.downloadManager,this.imageResourcesPath=t.imageResourcesPath,this.renderForms=t.renderForms,this.svgFactory=t.svgFactory,this.annotationStorage=t.annotationStorage,this.enableScripting=t.enableScripting,this.hasJSActions=t.hasJSActions,this._fieldObjects=t.fieldObjects,this.parent=t.parent,n&&(this.container=this._createContainer(r)),a&&this._createQuadrilaterals()}static _hasPopupData({titleObj:t,contentsObj:n,richText:r}){return!!(t!=null&&t.str||n!=null&&n.str||r!=null&&r.str)}get _isEditable(){return this.data.isEditable}get hasPopupData(){return ldt._hasPopupData(this.data)}updateEdited(t){var r;if(!this.container)return;ye(this,pz)||Kt(this,pz,{rect:this.data.rect.slice(0)});const{rect:n}=t;n&&ls(this,Ore,rXe).call(this,n),(r=ye(this,zH))==null||r.popup.updateEdited(t)}resetEdited(){var t;ye(this,pz)&&(ls(this,Ore,rXe).call(this,ye(this,pz).rect),(t=ye(this,zH))==null||t.popup.resetEdited(),Kt(this,pz,null))}_createContainer(t){const{data:n,parent:{page:r,viewport:a}}=this,i=document.createElement("section");i.setAttribute("data-annotation-id",n.id),this instanceof y9||(i.tabIndex=Qie);const{style:l}=i;if(l.zIndex=this.parent.zIndex++,n.alternativeText&&(i.title=n.alternativeText),n.noRotate&&i.classList.add("norotate"),!n.rect||this instanceof aXe){const{rotation:x}=n;return!n.hasOwnCanvas&&x!==0&&this.setRotation(x,i),i}const{width:o,height:c}=YE(n.rect);if(!t&&n.borderStyle.width>0){l.borderWidth=`${n.borderStyle.width}px`;const x=n.borderStyle.horizontalCornerRadius,y=n.borderStyle.verticalCornerRadius;if(x>0||y>0){const b=`calc(${x}px * var(--scale-factor)) / calc(${y}px * var(--scale-factor))`;l.borderRadius=b}else if(this instanceof Ins){const b=`calc(${o}px * var(--scale-factor)) / calc(${c}px * var(--scale-factor))`;l.borderRadius=b}switch(n.borderStyle.style){case mX.SOLID:l.borderStyle="solid";break;case mX.DASHED:l.borderStyle="dashed";break;case mX.BEVELED:nu("Unimplemented border style: beveled");break;case mX.INSET:nu("Unimplemented border style: inset");break;case mX.UNDERLINE:l.borderBottomStyle="solid";break}const v=n.borderColor||null;v?(Kt(this,OH,!0),l.borderColor=ol.makeHexColor(v[0]|0,v[1]|0,v[2]|0)):l.borderWidth=0}const d=ol.normalizeRect([n.rect[0],r.view[3]-n.rect[1]+r.view[1],n.rect[2],r.view[3]-n.rect[3]+r.view[1]]),{pageWidth:u,pageHeight:h,pageX:m,pageY:f}=a.rawDims;l.left=`${100*(d[0]-m)/u}%`,l.top=`${100*(d[1]-f)/h}%`;const{rotation:g}=n;return n.hasOwnCanvas||g===0?(l.width=`${100*o/u}%`,l.height=`${100*c/h}%`):this.setRotation(g,i),i}setRotation(t,n=this.container){if(!this.data.rect)return;const{pageWidth:r,pageHeight:a}=this.parent.viewport.rawDims,{width:i,height:l}=YE(this.data.rect);let o,c;t%180===0?(o=100*i/r,c=100*l/a):(o=100*l/r,c=100*i/a),n.style.width=`${o}%`,n.style.height=`${c}%`,n.setAttribute("data-main-rotation",(360-t)%360)}get _commonActions(){const t=(n,r,a)=>{const i=a.detail[n],l=i[0],o=i.slice(1);a.target.style[r]=w3t[`${l}_HTML`](o),this.annotationStorage.setValue(this.data.id,{[r]:w3t[`${l}_rgb`](o)})};return th(this,"_commonActions",{display:n=>{const{display:r}=n.detail,a=r%2===1;this.container.style.visibility=a?"hidden":"visible",this.annotationStorage.setValue(this.data.id,{noView:a,noPrint:r===1||r===2})},print:n=>{this.annotationStorage.setValue(this.data.id,{noPrint:!n.detail.print})},hidden:n=>{const{hidden:r}=n.detail;this.container.style.visibility=r?"hidden":"visible",this.annotationStorage.setValue(this.data.id,{noPrint:r,noView:r})},focus:n=>{setTimeout(()=>n.target.focus({preventScroll:!1}),0)},userName:n=>{n.target.title=n.detail.userName},readonly:n=>{n.target.disabled=n.detail.readonly},required:n=>{this._setRequired(n.target,n.detail.required)},bgColor:n=>{t("bgColor","backgroundColor",n)},fillColor:n=>{t("fillColor","backgroundColor",n)},fgColor:n=>{t("fgColor","color",n)},textColor:n=>{t("textColor","color",n)},borderColor:n=>{t("borderColor","borderColor",n)},strokeColor:n=>{t("strokeColor","borderColor",n)},rotation:n=>{const r=n.detail.rotation;this.setRotation(r),this.annotationStorage.setValue(this.data.id,{rotation:r})}})}_dispatchEventFromSandbox(t,n){const r=this._commonActions;for(const a of Object.keys(n.detail)){const i=t[a]||r[a];i==null||i(n)}}_setDefaultPropertiesFromJS(t){if(!this.enableScripting)return;const n=this.annotationStorage.getRawValue(this.data.id);if(!n)return;const r=this._commonActions;for(const[a,i]of Object.entries(n)){const l=r[a];if(l){const o={detail:{[a]:i},target:t};l(o),delete n[a]}}}_createQuadrilaterals(){if(!this.container)return;const{quadPoints:t}=this.data;if(!t)return;const[n,r,a,i]=this.data.rect.map(x=>Math.fround(x));if(t.length===8){const[x,y,v,b]=t.subarray(2,6);if(a===x&&i===y&&n===v&&r===b)return}const{style:l}=this.container;let o;if(ye(this,OH)){const{borderColor:x,borderWidth:y}=l;l.borderWidth=0,o=["url('data:image/svg+xml;utf8,",'',``],this.container.classList.add("hasBorder")}const c=a-n,d=i-r,{svgFactory:u}=this,h=u.createElement("svg");h.classList.add("quadrilateralsContainer"),h.setAttribute("width",0),h.setAttribute("height",0);const m=u.createElement("defs");h.append(m);const f=u.createElement("clipPath"),g=`clippath_${this.data.id}`;f.setAttribute("id",g),f.setAttribute("clipPathUnits","objectBoundingBox"),m.append(f);for(let x=2,y=t.length;x`)}ye(this,OH)&&(o.push("')"),l.backgroundImage=o.join("")),this.container.append(h),this.container.style.clipPath=`url(#${g})`}_createPopup(){const{data:t}=this,n=Kt(this,zH,new aXe({data:{color:t.color,titleObj:t.titleObj,modificationDate:t.modificationDate,contentsObj:t.contentsObj,richText:t.richText,parentRect:t.rect,borderStyle:0,id:`popup_${t.id}`,rotation:t.rotation},parent:this.parent,elements:[this]}));this.parent.div.append(n.render())}render(){kp("Abstract method `AnnotationElement.render` called")}_getElementsByName(t,n=null){const r=[];if(this._fieldObjects){const a=this._fieldObjects[t];if(a)for(const{page:i,id:l,exportValues:o}of a){if(i===-1||l===n)continue;const c=typeof o=="string"?o:null,d=document.querySelector(`[data-element-id="${l}"]`);if(d&&!wB.has(d)){nu(`_getElementsByName - element not allowed: ${l}`);continue}r.push({id:l,exportValue:c,domElement:d})}return r}for(const a of document.getElementsByName(t)){const{exportValue:i}=a,l=a.getAttribute("data-element-id");l!==n&&wB.has(a)&&r.push({id:l,exportValue:i,domElement:a})}return r}show(){var t;this.container&&(this.container.hidden=!1),(t=this.popup)==null||t.maybeShow()}hide(){var t;this.container&&(this.container.hidden=!0),(t=this.popup)==null||t.forceHide()}getElementsToTriggerPopup(){return this.container}addHighlightArea(){const t=this.getElementsToTriggerPopup();if(Array.isArray(t))for(const n of t)n.classList.add("highlightArea");else t.classList.add("highlightArea")}_editOnDoubleClick(){if(!this._isEditable)return;const{annotationEditorType:t,data:{id:n}}=this;this.container.addEventListener("dblclick",()=>{var r;(r=this.linkService.eventBus)==null||r.dispatch("switchannotationeditormode",{source:this,mode:t,editId:n})})}};pz=new WeakMap,OH=new WeakMap,zH=new WeakMap,Ore=new WeakSet,rXe=function(t){const{container:{style:n},data:{rect:r,rotation:a},parent:{viewport:{rawDims:{pageWidth:i,pageHeight:l,pageX:o,pageY:c}}}}=this;r==null||r.splice(0,4,...t);const{width:d,height:u}=YE(t);n.left=`${100*(t[0]-o)/i}%`,n.top=`${100*(l-t[3]+c)/l}%`,a===0?(n.width=`${100*d/i}%`,n.height=`${100*u/l}%`):this.setRotation(a)};let gy=ldt;var Yj,VO,Mns,Pns;class Tns extends gy{constructor(n,r=null){super(n,{isRenderable:!0,ignoreBorder:!!(r!=null&&r.ignoreBorder),createQuadrilaterals:!0});bs(this,Yj);this.isTooltipOnly=n.data.isTooltipOnly}render(){const{data:n,linkService:r}=this,a=document.createElement("a");a.setAttribute("data-element-id",n.id);let i=!1;return n.url?(r.addLinkAttributes(a,n.url,n.newWindow),i=!0):n.action?(this._bindNamedAction(a,n.action),i=!0):n.attachment?(ls(this,Yj,Mns).call(this,a,n.attachment,n.attachmentDest),i=!0):n.setOCGState?(ls(this,Yj,Pns).call(this,a,n.setOCGState),i=!0):n.dest?(this._bindLink(a,n.dest),i=!0):(n.actions&&(n.actions.Action||n.actions["Mouse Up"]||n.actions["Mouse Down"])&&this.enableScripting&&this.hasJSActions&&(this._bindJSAction(a,n),i=!0),n.resetForm?(this._bindResetFormAction(a,n.resetForm),i=!0):this.isTooltipOnly&&!i&&(this._bindLink(a,""),i=!0)),this.container.classList.add("linkAnnotation"),i&&this.container.append(a),this.container}_bindLink(n,r){n.href=this.linkService.getDestinationHash(r),n.onclick=()=>(r&&this.linkService.goToDestination(r),!1),(r||r==="")&&ls(this,Yj,VO).call(this)}_bindNamedAction(n,r){n.href=this.linkService.getAnchorUrl(""),n.onclick=()=>(this.linkService.executeNamedAction(r),!1),ls(this,Yj,VO).call(this)}_bindJSAction(n,r){n.href=this.linkService.getAnchorUrl("");const a=new Map([["Action","onclick"],["Mouse Up","onmouseup"],["Mouse Down","onmousedown"]]);for(const i of Object.keys(r.actions)){const l=a.get(i);l&&(n[l]=()=>{var o;return(o=this.linkService.eventBus)==null||o.dispatch("dispatcheventinsandbox",{source:this,detail:{id:r.id,name:i}}),!1})}n.onclick||(n.onclick=()=>!1),ls(this,Yj,VO).call(this)}_bindResetFormAction(n,r){const a=n.onclick;if(a||(n.href=this.linkService.getAnchorUrl("")),ls(this,Yj,VO).call(this),!this._fieldObjects){nu('_bindResetFormAction - "resetForm" action not supported, ensure that the `fieldObjects` parameter is provided.'),a||(n.onclick=()=>!1);return}n.onclick=()=>{var h;a==null||a();const{fields:i,refs:l,include:o}=r,c=[];if(i.length!==0||l.length!==0){const m=new Set(l);for(const f of i){const g=this._fieldObjects[f]||[];for(const{id:x}of g)m.add(x)}for(const f of Object.values(this._fieldObjects))for(const g of f)m.has(g.id)===o&&c.push(g)}else for(const m of Object.values(this._fieldObjects))c.push(...m);const d=this.annotationStorage,u=[];for(const m of c){const{id:f}=m;switch(u.push(f),m.type){case"text":{const x=m.defaultValue||"";d.setValue(f,{value:x});break}case"checkbox":case"radiobutton":{const x=m.defaultValue===m.exportValues;d.setValue(f,{value:x});break}case"combobox":case"listbox":{const x=m.defaultValue||"";d.setValue(f,{value:x});break}default:continue}const g=document.querySelector(`[data-element-id="${f}"]`);if(g){if(!wB.has(g)){nu(`_bindResetFormAction - element not allowed: ${f}`);continue}}else continue;g.dispatchEvent(new Event("resetform"))}return this.enableScripting&&((h=this.linkService.eventBus)==null||h.dispatch("dispatcheventinsandbox",{source:this,detail:{id:"app",ids:u,name:"ResetForm"}})),!1}}}Yj=new WeakSet,VO=function(){this.container.setAttribute("data-internal-link","")},Mns=function(n,r,a=null){n.href=this.linkService.getAnchorUrl(""),r.description&&(n.title=r.description),n.onclick=()=>{var i;return(i=this.downloadManager)==null||i.openOrDownloadData(r.content,r.filename,a),!1},ls(this,Yj,VO).call(this)},Pns=function(n,r){n.href=this.linkService.getAnchorUrl(""),n.onclick=()=>(this.linkService.executeSetOCGState(r),!1),ls(this,Yj,VO).call(this)};class LZn extends gy{constructor(t){super(t,{isRenderable:!0})}render(){this.container.classList.add("textAnnotation");const t=document.createElement("img");return t.src=this.imageResourcesPath+"annotation-"+this.data.name.toLowerCase()+".svg",t.setAttribute("data-l10n-id","pdfjs-text-annotation-type"),t.setAttribute("data-l10n-args",JSON.stringify({type:this.data.name})),!this.data.popupRef&&this.hasPopupData&&this._createPopup(),this.container.append(t),this.container}}class y9 extends gy{render(){return this.container}showElementAndHideCanvas(t){var n;this.data.hasOwnCanvas&&(((n=t.previousSibling)==null?void 0:n.nodeName)==="CANVAS"&&(t.previousSibling.hidden=!0),t.hidden=!1)}_getKeyModifier(t){return T_.platform.isMac?t.metaKey:t.ctrlKey}_setEventListener(t,n,r,a,i){r.includes("mouse")?t.addEventListener(r,l=>{var o;(o=this.linkService.eventBus)==null||o.dispatch("dispatcheventinsandbox",{source:this,detail:{id:this.data.id,name:a,value:i(l),shift:l.shiftKey,modifier:this._getKeyModifier(l)}})}):t.addEventListener(r,l=>{var o;if(r==="blur"){if(!n.focused||!l.relatedTarget)return;n.focused=!1}else if(r==="focus"){if(n.focused)return;n.focused=!0}i&&((o=this.linkService.eventBus)==null||o.dispatch("dispatcheventinsandbox",{source:this,detail:{id:this.data.id,name:a,value:i(l)}}))})}_setEventListeners(t,n,r,a){var i,l,o;for(const[c,d]of r)(d==="Action"||(i=this.data.actions)!=null&&i[d])&&((d==="Focus"||d==="Blur")&&(n||(n={focused:!1})),this._setEventListener(t,n,c,d,a),d==="Focus"&&!((l=this.data.actions)!=null&&l.Blur)?this._setEventListener(t,n,"blur","Blur",null):d==="Blur"&&!((o=this.data.actions)!=null&&o.Focus)&&this._setEventListener(t,n,"focus","Focus",null))}_setBackgroundColor(t){const n=this.data.backgroundColor||null;t.style.backgroundColor=n===null?"transparent":ol.makeHexColor(n[0],n[1],n[2])}_setTextStyle(t){const n=["left","center","right"],{fontColor:r}=this.data.defaultAppearanceData,a=this.data.defaultAppearanceData.fontSize||PZn,i=t.style;let l;const o=2,c=d=>Math.round(10*d)/10;if(this.data.multiLine){const d=Math.abs(this.data.rect[3]-this.data.rect[1]-o),u=Math.round(d/(R$e*a))||1,h=d/u;l=Math.min(a,c(h/R$e))}else{const d=Math.abs(this.data.rect[3]-this.data.rect[1]-o);l=Math.min(a,c(d/R$e))}i.fontSize=`calc(${l}px * var(--scale-factor))`,i.color=ol.makeHexColor(r[0],r[1],r[2]),this.data.textAlignment!==null&&(i.textAlign=n[this.data.textAlignment])}_setRequired(t,n){n?t.setAttribute("required",!0):t.removeAttribute("required"),t.setAttribute("aria-required",n)}}class RZn extends y9{constructor(t){const n=t.renderForms||t.data.hasOwnCanvas||!t.data.hasAppearance&&!!t.data.fieldValue;super(t,{isRenderable:n})}setPropertyOnSiblings(t,n,r,a){const i=this.annotationStorage;for(const l of this._getElementsByName(t.name,t.id))l.domElement&&(l.domElement[n]=r),i.setValue(l.id,{[a]:r})}render(){var a,i;const t=this.annotationStorage,n=this.data.id;this.container.classList.add("textWidgetAnnotation");let r=null;if(this.renderForms){const l=t.getValue(n,{value:this.data.fieldValue});let o=l.value||"";const c=t.getValue(n,{charLimit:this.data.maxLen}).charLimit;c&&o.length>c&&(o=o.slice(0,c));let d=l.formattedValue||((a=this.data.textContent)==null?void 0:a.join(` `))||null;d&&this.data.comb&&(d=d.replaceAll(/\s+/g,""));const u={userValue:o,formattedValue:d,lastCommittedValue:null,commitKey:1,focused:!1};this.data.multiLine?(r=document.createElement("textarea"),r.textContent=d??o,this.data.doNotScroll&&(r.style.overflowY="hidden")):(r=document.createElement("input"),r.type="text",r.setAttribute("value",d??o),this.data.doNotScroll&&(r.style.overflowX="hidden")),this.data.hasOwnCanvas&&(r.hidden=!0),wB.add(r),r.setAttribute("data-element-id",n),r.disabled=this.data.readOnly,r.name=this.data.fieldName,r.tabIndex=Qie,this._setRequired(r,this.data.required),c&&(r.maxLength=c),r.addEventListener("input",m=>{t.setValue(n,{value:m.target.value}),this.setPropertyOnSiblings(r,"value",m.target.value,"value"),u.formattedValue=null}),r.addEventListener("resetform",m=>{const f=this.data.defaultFieldValue??"";r.value=u.userValue=f,u.formattedValue=null});let h=m=>{const{formattedValue:f}=u;f!=null&&(m.target.value=f),m.target.scrollLeft=0};if(this.enableScripting&&this.hasJSActions){r.addEventListener("focus",f=>{var x;if(u.focused)return;const{target:g}=f;u.userValue&&(g.value=u.userValue),u.lastCommittedValue=g.value,u.commitKey=1,(x=this.data.actions)!=null&&x.Focus||(u.focused=!0)}),r.addEventListener("updatefromsandbox",f=>{this.showElementAndHideCanvas(f.target);const g={value(x){u.userValue=x.detail.value??"",t.setValue(n,{value:u.userValue.toString()}),x.target.value=u.userValue},formattedValue(x){const{formattedValue:y}=x.detail;u.formattedValue=y,y!=null&&x.target!==document.activeElement&&(x.target.value=y),t.setValue(n,{formattedValue:y})},selRange(x){x.target.setSelectionRange(...x.detail.selRange)},charLimit:x=>{var w;const{charLimit:y}=x.detail,{target:v}=x;if(y===0){v.removeAttribute("maxLength");return}v.setAttribute("maxLength",y);let b=u.userValue;!b||b.length<=y||(b=b.slice(0,y),v.value=u.userValue=b,t.setValue(n,{value:b}),(w=this.linkService.eventBus)==null||w.dispatch("dispatcheventinsandbox",{source:this,detail:{id:n,name:"Keystroke",value:b,willCommit:!0,commitKey:1,selStart:v.selectionStart,selEnd:v.selectionEnd}}))}};this._dispatchEventFromSandbox(g,f)}),r.addEventListener("keydown",f=>{var y;u.commitKey=1;let g=-1;if(f.key==="Escape"?g=0:f.key==="Enter"&&!this.data.multiLine?g=2:f.key==="Tab"&&(u.commitKey=3),g===-1)return;const{value:x}=f.target;u.lastCommittedValue!==x&&(u.lastCommittedValue=x,u.userValue=x,(y=this.linkService.eventBus)==null||y.dispatch("dispatcheventinsandbox",{source:this,detail:{id:n,name:"Keystroke",value:x,willCommit:!0,commitKey:g,selStart:f.target.selectionStart,selEnd:f.target.selectionEnd}}))});const m=h;h=null,r.addEventListener("blur",f=>{var x,y;if(!u.focused||!f.relatedTarget)return;(x=this.data.actions)!=null&&x.Blur||(u.focused=!1);const{value:g}=f.target;u.userValue=g,u.lastCommittedValue!==g&&((y=this.linkService.eventBus)==null||y.dispatch("dispatcheventinsandbox",{source:this,detail:{id:n,name:"Keystroke",value:g,willCommit:!0,commitKey:u.commitKey,selStart:f.target.selectionStart,selEnd:f.target.selectionEnd}})),m(f)}),(i=this.data.actions)!=null&&i.Keystroke&&r.addEventListener("beforeinput",f=>{var C;u.lastCommittedValue=null;const{data:g,target:x}=f,{value:y,selectionStart:v,selectionEnd:b}=x;let w=v,S=b;switch(f.inputType){case"deleteWordBackward":{const E=y.substring(0,v).match(/\w*[^\w]*$/);E&&(w-=E[0].length);break}case"deleteWordForward":{const E=y.substring(v).match(/^[^\w]*\w*/);E&&(S+=E[0].length);break}case"deleteContentBackward":v===b&&(w-=1);break;case"deleteContentForward":v===b&&(S+=1);break}f.preventDefault(),(C=this.linkService.eventBus)==null||C.dispatch("dispatcheventinsandbox",{source:this,detail:{id:n,name:"Keystroke",value:y,change:g||"",willCommit:!1,selStart:w,selEnd:S}})}),this._setEventListeners(r,u,[["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"]],f=>f.target.value)}if(h&&r.addEventListener("blur",h),this.data.comb){const f=(this.data.rect[2]-this.data.rect[0])/c;r.classList.add("comb"),r.style.letterSpacing=`calc(${f}px * var(--scale-factor) - 1ch)`}}else r=document.createElement("div"),r.textContent=this.data.fieldValue,r.style.verticalAlign="middle",r.style.display="table-cell",this.data.hasOwnCanvas&&(r.hidden=!0);return this._setTextStyle(r),this._setBackgroundColor(r),this._setDefaultPropertiesFromJS(r),this.container.append(r),this.container}}class DZn extends y9{constructor(t){super(t,{isRenderable:!!t.data.hasOwnCanvas})}}class FZn extends y9{constructor(t){super(t,{isRenderable:t.renderForms})}render(){const t=this.annotationStorage,n=this.data,r=n.id;let a=t.getValue(r,{value:n.exportValue===n.fieldValue}).value;typeof a=="string"&&(a=a!=="Off",t.setValue(r,{value:a})),this.container.classList.add("buttonWidgetAnnotation","checkBox");const i=document.createElement("input");return wB.add(i),i.setAttribute("data-element-id",r),i.disabled=n.readOnly,this._setRequired(i,this.data.required),i.type="checkbox",i.name=n.fieldName,a&&i.setAttribute("checked",!0),i.setAttribute("exportValue",n.exportValue),i.tabIndex=Qie,i.addEventListener("change",l=>{const{name:o,checked:c}=l.target;for(const d of this._getElementsByName(o,r)){const u=c&&d.exportValue===n.exportValue;d.domElement&&(d.domElement.checked=u),t.setValue(d.id,{value:u})}t.setValue(r,{value:c})}),i.addEventListener("resetform",l=>{const o=n.defaultFieldValue||"Off";l.target.checked=o===n.exportValue}),this.enableScripting&&this.hasJSActions&&(i.addEventListener("updatefromsandbox",l=>{const o={value(c){c.target.checked=c.detail.value!=="Off",t.setValue(r,{value:c.target.checked})}};this._dispatchEventFromSandbox(o,l)}),this._setEventListeners(i,null,[["change","Validate"],["change","Action"],["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"]],l=>l.target.checked)),this._setBackgroundColor(i),this._setDefaultPropertiesFromJS(i),this.container.append(i),this.container}}class Ins extends y9{constructor(t){super(t,{isRenderable:t.renderForms})}render(){this.container.classList.add("buttonWidgetAnnotation","radioButton");const t=this.annotationStorage,n=this.data,r=n.id;let a=t.getValue(r,{value:n.fieldValue===n.buttonValue}).value;if(typeof a=="string"&&(a=a!==n.buttonValue,t.setValue(r,{value:a})),a)for(const l of this._getElementsByName(n.fieldName,r))t.setValue(l.id,{value:!1});const i=document.createElement("input");if(wB.add(i),i.setAttribute("data-element-id",r),i.disabled=n.readOnly,this._setRequired(i,this.data.required),i.type="radio",i.name=n.fieldName,a&&i.setAttribute("checked",!0),i.tabIndex=Qie,i.addEventListener("change",l=>{const{name:o,checked:c}=l.target;for(const d of this._getElementsByName(o,r))t.setValue(d.id,{value:!1});t.setValue(r,{value:c})}),i.addEventListener("resetform",l=>{const o=n.defaultFieldValue;l.target.checked=o!=null&&o===n.buttonValue}),this.enableScripting&&this.hasJSActions){const l=n.buttonValue;i.addEventListener("updatefromsandbox",o=>{const c={value:d=>{const u=l===d.detail.value;for(const h of this._getElementsByName(d.target.name)){const m=u&&h.id===r;h.domElement&&(h.domElement.checked=m),t.setValue(h.id,{value:m})}}};this._dispatchEventFromSandbox(c,o)}),this._setEventListeners(i,null,[["change","Validate"],["change","Action"],["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"]],o=>o.target.checked)}return this._setBackgroundColor(i),this._setDefaultPropertiesFromJS(i),this.container.append(i),this.container}}class OZn extends Tns{constructor(t){super(t,{ignoreBorder:t.data.hasAppearance})}render(){const t=super.render();t.classList.add("buttonWidgetAnnotation","pushButton");const n=t.lastChild;return this.enableScripting&&this.hasJSActions&&n&&(this._setDefaultPropertiesFromJS(n),n.addEventListener("updatefromsandbox",r=>{this._dispatchEventFromSandbox({},r)})),t}}class zZn extends y9{constructor(t){super(t,{isRenderable:t.renderForms})}render(){this.container.classList.add("choiceWidgetAnnotation");const t=this.annotationStorage,n=this.data.id,r=t.getValue(n,{value:this.data.fieldValue}),a=document.createElement("select");wB.add(a),a.setAttribute("data-element-id",n),a.disabled=this.data.readOnly,this._setRequired(a,this.data.required),a.name=this.data.fieldName,a.tabIndex=Qie;let i=this.data.combo&&this.data.options.length>0;this.data.combo||(a.size=this.data.options.length,this.data.multiSelect&&(a.multiple=!0)),a.addEventListener("resetform",u=>{const h=this.data.defaultFieldValue;for(const m of a.options)m.selected=m.value===h});for(const u of this.data.options){const h=document.createElement("option");h.textContent=u.displayValue,h.value=u.exportValue,r.value.includes(u.exportValue)&&(h.setAttribute("selected",!0),i=!1),a.append(h)}let l=null;if(i){const u=document.createElement("option");u.value=" ",u.setAttribute("hidden",!0),u.setAttribute("selected",!0),a.prepend(u),l=()=>{u.remove(),a.removeEventListener("input",l),l=null},a.addEventListener("input",l)}const o=u=>{const h=u?"value":"textContent",{options:m,multiple:f}=a;return f?Array.prototype.filter.call(m,g=>g.selected).map(g=>g[h]):m.selectedIndex===-1?null:m[m.selectedIndex][h]};let c=o(!1);const d=u=>{const h=u.target.options;return Array.prototype.map.call(h,m=>({displayValue:m.textContent,exportValue:m.value}))};return this.enableScripting&&this.hasJSActions?(a.addEventListener("updatefromsandbox",u=>{const h={value(m){l==null||l();const f=m.detail.value,g=new Set(Array.isArray(f)?f:[f]);for(const x of a.options)x.selected=g.has(x.value);t.setValue(n,{value:o(!0)}),c=o(!1)},multipleSelection(m){a.multiple=!0},remove(m){const f=a.options,g=m.detail.remove;f[g].selected=!1,a.remove(g),f.length>0&&Array.prototype.findIndex.call(f,y=>y.selected)===-1&&(f[0].selected=!0),t.setValue(n,{value:o(!0),items:d(m)}),c=o(!1)},clear(m){for(;a.length!==0;)a.remove(0);t.setValue(n,{value:null,items:[]}),c=o(!1)},insert(m){const{index:f,displayValue:g,exportValue:x}=m.detail.insert,y=a.children[f],v=document.createElement("option");v.textContent=g,v.value=x,y?y.before(v):a.append(v),t.setValue(n,{value:o(!0),items:d(m)}),c=o(!1)},items(m){const{items:f}=m.detail;for(;a.length!==0;)a.remove(0);for(const g of f){const{displayValue:x,exportValue:y}=g,v=document.createElement("option");v.textContent=x,v.value=y,a.append(v)}a.options.length>0&&(a.options[0].selected=!0),t.setValue(n,{value:o(!0),items:d(m)}),c=o(!1)},indices(m){const f=new Set(m.detail.indices);for(const g of m.target.options)g.selected=f.has(g.index);t.setValue(n,{value:o(!0)}),c=o(!1)},editable(m){m.target.disabled=!m.detail.editable}};this._dispatchEventFromSandbox(h,u)}),a.addEventListener("input",u=>{var f;const h=o(!0),m=o(!1);t.setValue(n,{value:h}),u.preventDefault(),(f=this.linkService.eventBus)==null||f.dispatch("dispatcheventinsandbox",{source:this,detail:{id:n,name:"Keystroke",value:c,change:m,changeEx:h,willCommit:!1,commitKey:1,keyDown:!1}})}),this._setEventListeners(a,null,[["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"],["input","Action"],["input","Validate"]],u=>u.target.value)):a.addEventListener("input",function(u){t.setValue(n,{value:o(!0)})}),this.data.combo&&this._setTextStyle(a),this._setBackgroundColor(a),this._setDefaultPropertiesFromJS(a),this.container.append(a),this.container}}class aXe extends gy{constructor(t){const{data:n,elements:r}=t;super(t,{isRenderable:gy._hasPopupData(n)}),this.elements=r,this.popup=null}render(){this.container.classList.add("popupAnnotation");const t=this.popup=new BZn({container:this.container,color:this.data.color,titleObj:this.data.titleObj,modificationDate:this.data.modificationDate,contentsObj:this.data.contentsObj,richText:this.data.richText,rect:this.data.rect,parentRect:this.data.parentRect||null,parent:this.parent,elements:this.elements,open:this.data.open}),n=[];for(const r of this.elements)r.popup=t,r.container.ariaHasPopup="dialog",n.push(r.data.id),r.addHighlightArea();return this.container.setAttribute("aria-controls",n.map(r=>`${Rot}${r}`).join(",")),this.container}}var BH,wIe,jIe,$H,gz,hx,JA,UH,zre,Bre,qH,eE,SS,tE,$re,sE,Ure,xz,yz,lf,X3e,iXe,Lns,Rns,Dns,Fns,Q3e,J3e,oXe;class BZn{constructor({container:t,color:n,elements:r,titleObj:a,modificationDate:i,contentsObj:l,richText:o,parent:c,rect:d,parentRect:u,open:h}){bs(this,lf);bs(this,BH,ls(this,lf,Dns).bind(this));bs(this,wIe,ls(this,lf,oXe).bind(this));bs(this,jIe,ls(this,lf,J3e).bind(this));bs(this,$H,ls(this,lf,Q3e).bind(this));bs(this,gz,null);bs(this,hx,null);bs(this,JA,null);bs(this,UH,null);bs(this,zre,null);bs(this,Bre,null);bs(this,qH,null);bs(this,eE,!1);bs(this,SS,null);bs(this,tE,null);bs(this,$re,null);bs(this,sE,null);bs(this,Ure,null);bs(this,xz,null);bs(this,yz,!1);var m;Kt(this,hx,t),Kt(this,Ure,a),Kt(this,JA,l),Kt(this,sE,o),Kt(this,Bre,c),Kt(this,gz,n),Kt(this,$re,d),Kt(this,qH,u),Kt(this,zre,r),Kt(this,UH,Oot.toDateObject(i)),this.trigger=r.flatMap(f=>f.getElementsToTriggerPopup());for(const f of this.trigger)f.addEventListener("click",ye(this,$H)),f.addEventListener("mouseenter",ye(this,jIe)),f.addEventListener("mouseleave",ye(this,wIe)),f.classList.add("popupTriggerArea");for(const f of r)(m=f.container)==null||m.addEventListener("keydown",ye(this,BH));ye(this,hx).hidden=!0,h&&ls(this,lf,Q3e).call(this)}render(){if(ye(this,SS))return;const t=Kt(this,SS,document.createElement("div"));if(t.className="popup",ye(this,gz)){const i=t.style.outlineColor=ol.makeHexColor(...ye(this,gz));CSS.supports("background-color","color-mix(in srgb, red 30%, white)")?t.style.backgroundColor=`color-mix(in srgb, ${i} 30%, white)`:t.style.backgroundColor=ol.makeHexColor(...ye(this,gz).map(o=>Math.floor(.7*(255-o)+o)))}const n=document.createElement("span");n.className="header";const r=document.createElement("h1");if(n.append(r),{dir:r.dir,str:r.textContent}=ye(this,Ure),t.append(n),ye(this,UH)){const i=document.createElement("span");i.classList.add("popupDate"),i.setAttribute("data-l10n-id","pdfjs-annotation-date-time-string"),i.setAttribute("data-l10n-args",JSON.stringify({dateObj:ye(this,UH).valueOf()})),n.append(i)}const a=ye(this,lf,X3e);if(a)Ens.render({xfaHtml:a,intent:"richText",div:t}),t.lastChild.classList.add("richText","popupContent");else{const i=this._formatContents(ye(this,JA));t.append(i)}ye(this,hx).append(t)}_formatContents({str:t,dir:n}){const r=document.createElement("p");r.classList.add("popupContent"),r.dir=n;const a=t.split(/(?:\r\n?|\n)/);for(let i=0,l=a.length;i{l.key==="Enter"&&(i?l.metaKey:l.ctrlKey)&&ls(this,Yre,lXe).call(this)}),!r.popupRef&&this.hasPopupData?this._createPopup():a.classList.add("popupTriggerArea"),n.append(a),n}getElementsToTriggerPopup(){return ye(this,Kre)}addHighlightArea(){this.container.classList.add("highlightArea")}}Kre=new WeakMap,Yre=new WeakSet,lXe=function(){var n;(n=this.downloadManager)==null||n.openOrDownloadData(this.content,this.filename)};var Zre,vz,bz,Xre,EB,Uns,cXe;class ZZn{constructor({div:t,accessibilityManager:n,annotationCanvasMap:r,annotationEditorUIManager:a,page:i,viewport:l,structTreeLayer:o}){bs(this,EB);bs(this,Zre,null);bs(this,vz,null);bs(this,bz,new Map);bs(this,Xre,null);this.div=t,Kt(this,Zre,n),Kt(this,vz,r),Kt(this,Xre,o||null),this.page=i,this.viewport=l,this.zIndex=0,this._annotationEditorUIManager=a}hasEditableAnnotations(){return ye(this,bz).size>0}async render(t){var l;const{annotations:n}=t,r=this.div;bB(r,this.viewport);const a=new Map,i={data:null,layer:r,linkService:t.linkService,downloadManager:t.downloadManager,imageResourcesPath:t.imageResourcesPath||"",renderForms:t.renderForms!==!1,svgFactory:new Hot,annotationStorage:t.annotationStorage||new Bot,enableScripting:t.enableScripting===!0,hasJSActions:t.hasJSActions,fieldObjects:t.fieldObjects,parent:this,elements:null};for(const o of n){if(o.noHTML)continue;const c=o.annotationType===i0.POPUP;if(c){const h=a.get(o.id);if(!h)continue;i.elements=h}else{const{width:h,height:m}=YE(o.rect);if(h<=0||m<=0)continue}i.data=o;const d=IZn.create(i);if(!d.isRenderable)continue;if(!c&&o.popupRef){const h=a.get(o.popupRef);h?h.push(d):a.set(o.popupRef,[d])}const u=d.render();o.hidden&&(u.style.visibility="hidden"),await ls(this,EB,Uns).call(this,u,o.id),d._isEditable&&(ye(this,bz).set(d.data.id,d),(l=this._annotationEditorUIManager)==null||l.renderAnnotationElement(d))}ls(this,EB,cXe).call(this)}update({viewport:t}){const n=this.div;this.viewport=t,bB(n,{rotation:t.rotation}),ls(this,EB,cXe).call(this),n.hidden=!1}getEditableAnnotations(){return Array.from(ye(this,bz).values())}getEditableAnnotation(t){return ye(this,bz).get(t)}}Zre=new WeakMap,vz=new WeakMap,bz=new WeakMap,Xre=new WeakMap,EB=new WeakSet,Uns=async function(t,n){var l,o;const r=t.firstChild||t,a=r.id=`${Rot}${n}`,i=await((l=ye(this,Xre))==null?void 0:l.getAriaAttributes(a));if(i)for(const[c,d]of i)r.setAttribute(c,d);this.div.append(t),(o=ye(this,Zre))==null||o.moveElementInDOM(this.div,t,r,!1)},cXe=function(){if(!ye(this,vz))return;const t=this.div;for(const[n,r]of ye(this,vz)){const a=t.querySelector(`[data-annotation-id="${n}"]`);if(!a)continue;r.className="annotationContent";const{firstChild:i}=a;i?i.nodeName==="CANVAS"?i.replaceWith(r):i.classList.contains("annotationContent")?i.after(r):i.before(r):a.append(r)}ye(this,vz).clear()};const Due=/\r\n?|\n/g;var CS,Dj,Qre,_z,Fj,Gy,qns,Vns,Hns,eAe,aT,tAe,sAe,Gns,uXe,Wns;const Uf=class Uf extends Em{constructor(n){super({...n,name:"freeTextEditor"});bs(this,Gy);bs(this,CS);bs(this,Dj,"");bs(this,Qre,`${this.id}-editor`);bs(this,_z,null);bs(this,Fj);Kt(this,CS,n.color||Uf._defaultColor||Em._defaultLineColor),Kt(this,Fj,n.fontSize||Uf._defaultFontSize)}static get _keyboardManager(){const n=Uf.prototype,r=l=>l.isEmpty(),a=_B.TRANSLATE_SMALL,i=_B.TRANSLATE_BIG;return th(this,"_keyboardManager",new Xie([[["ctrl+s","mac+meta+s","ctrl+p","mac+meta+p"],n.commitOrRemove,{bubbles:!0}],[["ctrl+Enter","mac+meta+Enter","Escape","mac+Escape"],n.commitOrRemove],[["ArrowLeft","mac+ArrowLeft"],n._translateEmpty,{args:[-a,0],checker:r}],[["ctrl+ArrowLeft","mac+shift+ArrowLeft"],n._translateEmpty,{args:[-i,0],checker:r}],[["ArrowRight","mac+ArrowRight"],n._translateEmpty,{args:[a,0],checker:r}],[["ctrl+ArrowRight","mac+shift+ArrowRight"],n._translateEmpty,{args:[i,0],checker:r}],[["ArrowUp","mac+ArrowUp"],n._translateEmpty,{args:[0,-a],checker:r}],[["ctrl+ArrowUp","mac+shift+ArrowUp"],n._translateEmpty,{args:[0,-i],checker:r}],[["ArrowDown","mac+ArrowDown"],n._translateEmpty,{args:[0,a],checker:r}],[["ctrl+ArrowDown","mac+shift+ArrowDown"],n._translateEmpty,{args:[0,i],checker:r}]]))}static initialize(n,r){Em.initialize(n,r);const a=getComputedStyle(document.documentElement);this._internalPadding=parseFloat(a.getPropertyValue("--freetext-padding"))}static updateDefaultParams(n,r){switch(n){case nd.FREETEXT_SIZE:Uf._defaultFontSize=r;break;case nd.FREETEXT_COLOR:Uf._defaultColor=r;break}}updateParams(n,r){switch(n){case nd.FREETEXT_SIZE:ls(this,Gy,qns).call(this,r);break;case nd.FREETEXT_COLOR:ls(this,Gy,Vns).call(this,r);break}}static get defaultPropertiesToUpdate(){return[[nd.FREETEXT_SIZE,Uf._defaultFontSize],[nd.FREETEXT_COLOR,Uf._defaultColor||Em._defaultLineColor]]}get propertiesToUpdate(){return[[nd.FREETEXT_SIZE,ye(this,Fj)],[nd.FREETEXT_COLOR,ye(this,CS)]]}_translateEmpty(n,r){this._uiManager.translateSelectedEditors(n,r,!0)}getInitialTranslation(){const n=this.parentScale;return[-Uf._internalPadding*n,-(Uf._internalPadding+ye(this,Fj))*n]}rebuild(){this.parent&&(super.rebuild(),this.div!==null&&(this.isAttachedToDOM||this.parent.add(this)))}enableEditMode(){if(this.isInEditMode())return;this.parent.setEditingState(!1),this.parent.updateToolbar(Od.FREETEXT),super.enableEditMode(),this.overlayDiv.classList.remove("enabled"),this.editorDiv.contentEditable=!0,this._isDraggable=!1,this.div.removeAttribute("aria-activedescendant"),Kt(this,_z,new AbortController);const n=this._uiManager.combinedSignal(ye(this,_z));this.editorDiv.addEventListener("keydown",this.editorDivKeydown.bind(this),{signal:n}),this.editorDiv.addEventListener("focus",this.editorDivFocus.bind(this),{signal:n}),this.editorDiv.addEventListener("blur",this.editorDivBlur.bind(this),{signal:n}),this.editorDiv.addEventListener("input",this.editorDivInput.bind(this),{signal:n}),this.editorDiv.addEventListener("paste",this.editorDivPaste.bind(this),{signal:n})}disableEditMode(){var n;this.isInEditMode()&&(this.parent.setEditingState(!0),super.disableEditMode(),this.overlayDiv.classList.add("enabled"),this.editorDiv.contentEditable=!1,this.div.setAttribute("aria-activedescendant",ye(this,Qre)),this._isDraggable=!0,(n=ye(this,_z))==null||n.abort(),Kt(this,_z,null),this.div.focus({preventScroll:!0}),this.isEditing=!1,this.parent.div.classList.add("freetextEditing"))}focusin(n){this._focusEventsAllowed&&(super.focusin(n),n.target!==this.editorDiv&&this.editorDiv.focus())}onceAdded(){var n;this.width||(this.enableEditMode(),this.editorDiv.focus(),(n=this._initialOptions)!=null&&n.isCentered&&this.center(),this._initialOptions=null)}isEmpty(){return!this.editorDiv||this.editorDiv.innerText.trim()===""}remove(){this.isEditing=!1,this.parent&&(this.parent.setEditingState(!0),this.parent.div.classList.add("freetextEditing")),super.remove()}commit(){if(!this.isInEditMode())return;super.commit(),this.disableEditMode();const n=ye(this,Dj),r=Kt(this,Dj,ls(this,Gy,Hns).call(this).trimEnd());if(n===r)return;const a=i=>{if(Kt(this,Dj,i),!i){this.remove();return}ls(this,Gy,sAe).call(this),this._uiManager.rebuild(this),ls(this,Gy,eAe).call(this)};this.addCommands({cmd:()=>{a(r)},undo:()=>{a(n)},mustExec:!1}),ls(this,Gy,eAe).call(this)}shouldGetKeyboardEvents(){return this.isInEditMode()}enterInEditMode(){this.enableEditMode(),this.editorDiv.focus()}dblclick(n){this.enterInEditMode()}keydown(n){n.target===this.div&&n.key==="Enter"&&(this.enterInEditMode(),n.preventDefault())}editorDivKeydown(n){Uf._keyboardManager.exec(this,n)}editorDivFocus(n){this.isEditing=!0}editorDivBlur(n){this.isEditing=!1}editorDivInput(n){this.parent.div.classList.toggle("freetextEditing",this.isEmpty())}disableEditing(){this.editorDiv.setAttribute("role","comment"),this.editorDiv.removeAttribute("aria-multiline")}enableEditing(){this.editorDiv.setAttribute("role","textbox"),this.editorDiv.setAttribute("aria-multiline",!0)}render(){if(this.div)return this.div;let n,r;this.width&&(n=this.x,r=this.y),super.render(),this.editorDiv=document.createElement("div"),this.editorDiv.className="internal",this.editorDiv.setAttribute("id",ye(this,Qre)),this.editorDiv.setAttribute("data-l10n-id","pdfjs-free-text2"),this.editorDiv.setAttribute("data-l10n-attrs","default-content"),this.enableEditing(),this.editorDiv.contentEditable=!0;const{style:a}=this.editorDiv;if(a.fontSize=`calc(${ye(this,Fj)}px * var(--scale-factor))`,a.color=ye(this,CS),this.div.append(this.editorDiv),this.overlayDiv=document.createElement("div"),this.overlayDiv.classList.add("overlay","enabled"),this.div.append(this.overlayDiv),xPe(this,this.div,["dblclick","keydown"]),this.width){const[i,l]=this.parentDimensions;if(this.annotationElementId){const{position:o}=this._initialData;let[c,d]=this.getInitialTranslation();[c,d]=this.pageTranslationToScreen(c,d);const[u,h]=this.pageDimensions,[m,f]=this.pageTranslation;let g,x;switch(this.rotation){case 0:g=n+(o[0]-m)/u,x=r+this.height-(o[1]-f)/h;break;case 90:g=n+(o[0]-m)/u,x=r-(o[1]-f)/h,[c,d]=[d,-c];break;case 180:g=n-this.width+(o[0]-m)/u,x=r-(o[1]-f)/h,[c,d]=[-c,-d];break;case 270:g=n+(o[0]-m-this.height*h)/u,x=r+(o[1]-f-this.width*u)/h,[c,d]=[-d,c];break}this.setAt(g*i,x*l,c,d)}else this.setAt(n*i,r*l,this.width*i,this.height*l);ls(this,Gy,sAe).call(this),this._isDraggable=!0,this.editorDiv.contentEditable=!1}else this._isDraggable=!1,this.editorDiv.contentEditable=!0;return this.div}editorDivPaste(n){var g,x,y;const r=n.clipboardData||window.clipboardData,{types:a}=r;if(a.length===1&&a[0]==="text/plain")return;n.preventDefault();const i=ls(g=Uf,aT,uXe).call(g,r.getData("text")||"").replaceAll(Due,` `);if(!i)return;const l=window.getSelection();if(!l.rangeCount)return;this.editorDiv.normalize(),l.deleteFromDocument();const o=l.getRangeAt(0);if(!i.includes(` `)){o.insertNode(document.createTextNode(i)),this.editorDiv.normalize(),l.collapseToStart();return}const{startContainer:c,startOffset:d}=o,u=[],h=[];if(c.nodeType===Node.TEXT_NODE){const v=c.parentElement;if(h.push(c.nodeValue.slice(d).replaceAll(Due,"")),v!==this.editorDiv){let b=u;for(const w of this.editorDiv.childNodes){if(w===v){b=h;continue}b.push(ls(x=Uf,aT,tAe).call(x,w))}}u.push(c.nodeValue.slice(0,d).replaceAll(Due,""))}else if(c===this.editorDiv){let v=u,b=0;for(const w of this.editorDiv.childNodes)b++===d&&(v=h),v.push(ls(y=Uf,aT,tAe).call(y,w))}Kt(this,Dj,`${u.join(` `)}${i}${h.join(` `)}`),ls(this,Gy,sAe).call(this);const m=new Range;let f=u.reduce((v,b)=>v+b.length,0);for(const{firstChild:v}of this.editorDiv.childNodes)if(v.nodeType===Node.TEXT_NODE){const b=v.nodeValue.length;if(f<=b){m.setStart(v,f),m.setEnd(v,f);break}f-=b}l.removeAllRanges(),l.addRange(m)}get contentDiv(){return this.editorDiv}static async deserialize(n,r,a){var o;let i=null;if(n instanceof Ons){const{data:{defaultAppearanceData:{fontSize:c,fontColor:d},rect:u,rotation:h,id:m,popupRef:f},textContent:g,textPosition:x,parent:{page:{pageNumber:y}}}=n;if(!g||g.length===0)return null;i=n={annotationType:Od.FREETEXT,color:Array.from(d),fontSize:c,value:g.join(` `),position:x,pageIndex:y-1,rect:u.slice(0),rotation:h,id:m,deleted:!1,popupRef:f}}const l=await super.deserialize(n,r,a);return Kt(l,Fj,n.fontSize),Kt(l,CS,ol.makeHexColor(...n.color)),Kt(l,Dj,ls(o=Uf,aT,uXe).call(o,n.value)),l.annotationElementId=n.id||null,l._initialData=i,l}serialize(n=!1){if(this.isEmpty())return null;if(this.deleted)return this.serializeDeleted();const r=Uf._internalPadding*this.parentScale,a=this.getRect(r,r),i=Em._colorManager.convert(this.isAttachedToDOM?getComputedStyle(this.editorDiv).color:ye(this,CS)),l={annotationType:Od.FREETEXT,color:i,fontSize:ye(this,Fj),value:ls(this,Gy,Gns).call(this),pageIndex:this.pageIndex,rect:a,rotation:this.rotation,structTreeParentId:this._structTreeParentId};return n?l:this.annotationElementId&&!ls(this,Gy,Wns).call(this,l)?null:(l.id=this.annotationElementId,l)}renderAnnotationElement(n){const r=super.renderAnnotationElement(n);if(this.deleted)return r;const{style:a}=r;a.fontSize=`calc(${ye(this,Fj)}px * var(--scale-factor))`,a.color=ye(this,CS),r.replaceChildren();for(const l of ye(this,Dj).split(` `)){const o=document.createElement("div");o.append(l?document.createTextNode(l):document.createElement("br")),r.append(o)}const i=Uf._internalPadding*this.parentScale;return n.updateEdited({rect:this.getRect(i,i),popupContent:ye(this,Dj)}),r}resetAnnotationElement(n){super.resetAnnotationElement(n),n.resetEdited()}};CS=new WeakMap,Dj=new WeakMap,Qre=new WeakMap,_z=new WeakMap,Fj=new WeakMap,Gy=new WeakSet,qns=function(n){const r=i=>{this.editorDiv.style.fontSize=`calc(${i}px * var(--scale-factor))`,this.translate(0,-(i-ye(this,Fj))*this.parentScale),Kt(this,Fj,i),ls(this,Gy,eAe).call(this)},a=ye(this,Fj);this.addCommands({cmd:r.bind(this,n),undo:r.bind(this,a),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:nd.FREETEXT_SIZE,overwriteIfSameType:!0,keepUndo:!0})},Vns=function(n){const r=i=>{Kt(this,CS,this.editorDiv.style.color=i)},a=ye(this,CS);this.addCommands({cmd:r.bind(this,n),undo:r.bind(this,a),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:nd.FREETEXT_COLOR,overwriteIfSameType:!0,keepUndo:!0})},Hns=function(){var a;const n=[];this.editorDiv.normalize();let r=null;for(const i of this.editorDiv.childNodes)(r==null?void 0:r.nodeType)===Node.TEXT_NODE&&i.nodeName==="BR"||(n.push(ls(a=Uf,aT,tAe).call(a,i)),r=i);return n.join(` `)},eAe=function(){const[n,r]=this.parentDimensions;let a;if(this.isAttachedToDOM)a=this.div.getBoundingClientRect();else{const{currentLayer:i,div:l}=this,o=l.style.display,c=l.classList.contains("hidden");l.classList.remove("hidden"),l.style.display="hidden",i.div.append(this.div),a=l.getBoundingClientRect(),l.remove(),l.style.display=o,l.classList.toggle("hidden",c)}this.rotation%180===this.parentRotation%180?(this.width=a.width/n,this.height=a.height/r):(this.width=a.height/n,this.height=a.width/r),this.fixAndSetPosition()},aT=new WeakSet,tAe=function(n){return(n.nodeType===Node.TEXT_NODE?n.nodeValue:n.innerText).replaceAll(Due,"")},sAe=function(){if(this.editorDiv.replaceChildren(),!!ye(this,Dj))for(const n of ye(this,Dj).split(` `)){const r=document.createElement("div");r.append(n?document.createTextNode(n):document.createElement("br")),this.editorDiv.append(r)}},Gns=function(){return ye(this,Dj).replaceAll(" "," ")},uXe=function(n){return n.replaceAll(" "," ")},Wns=function(n){const{value:r,fontSize:a,color:i,pageIndex:l}=this._initialData;return this._hasBeenMoved||n.value!==r||n.fontSize!==a||n.color.some((o,c)=>o!==i[c])||n.pageIndex!==l},bs(Uf,aT),Nr(Uf,"_freeTextDefaultContent",""),Nr(Uf,"_internalPadding",0),Nr(Uf,"_defaultColor",null),Nr(Uf,"_defaultFontSize",10),Nr(Uf,"_type","freetext"),Nr(Uf,"_editorType",Od.FREETEXT);let dXe=Uf;class Kns{toSVGPath(){kp("Abstract method `toSVGPath` must be implemented.")}get box(){kp("Abstract getter `box` must be implemented.")}serialize(t,n){kp("Abstract method `serialize` must be implemented.")}get classNamesForDrawing(){kp("Abstract getter `classNamesForDrawing` must be implemented.")}get classNamesForOutlining(){kp("Abstract getter `classNamesForOutlining` must be implemented.")}get mustRemoveSelfIntersections(){return!1}}var Oj,AS,VH,HH,Z5,hu,wz,jz,Jre,eae,GH,WH,iI,tae,NIe,kIe,E0,OQ,Yns,Zns,Xns,Qns,Jns,ers;const IA=class IA{constructor({x:t,y:n},r,a,i,l,o=0){bs(this,E0);bs(this,Oj);bs(this,AS,[]);bs(this,VH);bs(this,HH);bs(this,Z5,[]);bs(this,hu,new Float64Array(18));bs(this,wz);bs(this,jz);bs(this,Jre);bs(this,eae);bs(this,GH);bs(this,WH);bs(this,iI,[]);Kt(this,Oj,r),Kt(this,WH,i*a),Kt(this,HH,l),ye(this,hu).set([NaN,NaN,NaN,NaN,t,n],6),Kt(this,VH,o),Kt(this,eae,ye(IA,tae)*a),Kt(this,Jre,ye(IA,kIe)*a),Kt(this,GH,a),ye(this,iI).push(t,n)}isEmpty(){return isNaN(ye(this,hu)[8])}add({x:t,y:n}){var R;Kt(this,wz,t),Kt(this,jz,n);const[r,a,i,l]=ye(this,Oj);let[o,c,d,u]=ye(this,hu).subarray(8,12);const h=t-d,m=n-u,f=Math.hypot(h,m);if(f=6;a-=6)isNaN(n[a])?r.push(`L${n[a+4]} ${n[a+5]}`):r.push(`C${n[a]} ${n[a+1]} ${n[a+2]} ${n[a+3]} ${n[a+4]} ${n[a+5]}`);return ls(this,E0,Zns).call(this,r),r.join(" ")}newFreeDrawOutline(t,n,r,a,i,l){return new trs(t,n,r,a,i,l)}getOutlines(){var h;const t=ye(this,Z5),n=ye(this,AS),r=ye(this,hu),[a,i,l,o]=ye(this,Oj),c=new Float64Array((((h=ye(this,iI))==null?void 0:h.length)??0)+2);for(let m=0,f=c.length-2;m=6;m-=6)for(let f=0;f<6;f+=2){if(isNaN(n[m+f])){d[u]=d[u+1]=NaN,u+=2;continue}d[u]=n[m+f],d[u+1]=n[m+f+1],u+=2}return ls(this,E0,Jns).call(this,d,u),this.newFreeDrawOutline(d,c,ye(this,Oj),ye(this,GH),ye(this,VH),ye(this,HH))}};Oj=new WeakMap,AS=new WeakMap,VH=new WeakMap,HH=new WeakMap,Z5=new WeakMap,hu=new WeakMap,wz=new WeakMap,jz=new WeakMap,Jre=new WeakMap,eae=new WeakMap,GH=new WeakMap,WH=new WeakMap,iI=new WeakMap,tae=new WeakMap,NIe=new WeakMap,kIe=new WeakMap,E0=new WeakSet,OQ=function(){const t=ye(this,hu).subarray(4,6),n=ye(this,hu).subarray(16,18),[r,a,i,l]=ye(this,Oj);return[(ye(this,wz)+(t[0]-n[0])/2-r)/i,(ye(this,jz)+(t[1]-n[1])/2-a)/l,(ye(this,wz)+(n[0]-t[0])/2-r)/i,(ye(this,jz)+(n[1]-t[1])/2-a)/l]},Yns=function(){const[t,n,r,a]=ye(this,Oj),[i,l,o,c]=ls(this,E0,OQ).call(this);return`M${(ye(this,hu)[2]-t)/r} ${(ye(this,hu)[3]-n)/a} L${(ye(this,hu)[4]-t)/r} ${(ye(this,hu)[5]-n)/a} L${i} ${l} L${o} ${c} L${(ye(this,hu)[16]-t)/r} ${(ye(this,hu)[17]-n)/a} L${(ye(this,hu)[14]-t)/r} ${(ye(this,hu)[15]-n)/a} Z`},Zns=function(t){const n=ye(this,AS);t.push(`L${n[4]} ${n[5]} Z`)},Xns=function(t){const[n,r,a,i]=ye(this,Oj),l=ye(this,hu).subarray(4,6),o=ye(this,hu).subarray(16,18),[c,d,u,h]=ls(this,E0,OQ).call(this);t.push(`L${(l[0]-n)/a} ${(l[1]-r)/i} L${c} ${d} L${u} ${h} L${(o[0]-n)/a} ${(o[1]-r)/i}`)},Qns=function(t){const n=ye(this,hu),[r,a,i,l]=ye(this,Oj),[o,c,d,u]=ls(this,E0,OQ).call(this),h=new Float64Array(36);return h.set([NaN,NaN,NaN,NaN,(n[2]-r)/i,(n[3]-a)/l,NaN,NaN,NaN,NaN,(n[4]-r)/i,(n[5]-a)/l,NaN,NaN,NaN,NaN,o,c,NaN,NaN,NaN,NaN,d,u,NaN,NaN,NaN,NaN,(n[16]-r)/i,(n[17]-a)/l,NaN,NaN,NaN,NaN,(n[14]-r)/i,(n[15]-a)/l],0),this.newFreeDrawOutline(h,t,ye(this,Oj),ye(this,GH),ye(this,VH),ye(this,HH))},Jns=function(t,n){const r=ye(this,AS);return t.set([NaN,NaN,NaN,NaN,r[4],r[5]],n),n+=6},ers=function(t,n){const r=ye(this,hu).subarray(4,6),a=ye(this,hu).subarray(16,18),[i,l,o,c]=ye(this,Oj),[d,u,h,m]=ls(this,E0,OQ).call(this);return t.set([NaN,NaN,NaN,NaN,(r[0]-i)/o,(r[1]-l)/c,NaN,NaN,NaN,NaN,d,u,NaN,NaN,NaN,NaN,h,m,NaN,NaN,NaN,NaN,(a[0]-i)/o,(a[1]-l)/c],n),n+=24},bs(IA,tae,8),bs(IA,NIe,2),bs(IA,kIe,ye(IA,tae)+ye(IA,NIe));let vPe=IA;var KH,Nz,nE,sae,zj,nae,Xx,Aw,zQ,BQ,srs;class trs extends Kns{constructor(n,r,a,i,l,o){super();bs(this,Aw);bs(this,KH);bs(this,Nz,null);bs(this,nE);bs(this,sae);bs(this,zj);bs(this,nae);bs(this,Xx);Kt(this,Xx,n),Kt(this,zj,r),Kt(this,KH,a),Kt(this,nae,i),Kt(this,nE,l),Kt(this,sae,o),ls(this,Aw,srs).call(this,o);const{x:c,y:d,width:u,height:h}=ye(this,Nz);for(let m=0,f=n.length;mn[0]-r[0]||n[1]-r[1]||n[2]-r[2]);const t=[];for(const n of ye(this,oI))n[3]?(t.push(...ls(this,L_,hXe).call(this,n)),ls(this,L_,rrs).call(this,n)):(ls(this,L_,ars).call(this,n),t.push(...ls(this,L_,hXe).call(this,n)));return ls(this,L_,nrs).call(this,t)}}rae=new WeakMap,oI=new WeakMap,ES=new WeakMap,L_=new WeakSet,nrs=function(t){const n=[],r=new Set;for(const l of t){const[o,c,d]=l;n.push([o,c,l],[o,d,l])}n.sort((l,o)=>l[1]-o[1]||l[0]-o[0]);for(let l=0,o=n.length;l0;){const l=r.values().next().value;let[o,c,d,u,h]=l;r.delete(l);let m=o,f=c;for(i=[o,d],a.push(i);;){let g;if(r.has(u))g=u;else if(r.has(h))g=h;else break;r.delete(g),[o,c,d,u,h]=g,m!==o&&(i.push(m,f,o,f===c?c:d),m=o),f=f===c?d:c}i.push(m,f)}return new XZn(a,ye(this,rae))},nAe=function(t){const n=ye(this,ES);let r=0,a=n.length-1;for(;r<=a;){const i=r+a>>1,l=n[i][0];if(l===t)return i;l=0;a--){const[i,l]=ye(this,ES)[a];if(i!==t)break;if(i===t&&l===n){ye(this,ES).splice(a,1);return}}},hXe=function(t){const[n,r,a]=t,i=[[n,r,a]],l=ls(this,L_,nAe).call(this,a);for(let o=0;o=c){if(f>d)i[u][1]=d;else{if(h===1)return[];i.splice(u,1),u--,h--}continue}i[u][2]=c,f>d&&i.push([n,d,f])}}}return i};var aae,YH;class XZn extends Kns{constructor(n,r){super();bs(this,aae);bs(this,YH);Kt(this,YH,n),Kt(this,aae,r)}toSVGPath(){const n=[];for(const r of ye(this,YH)){let[a,i]=r;n.push(`M${a} ${i}`);for(let l=2;l-1?(Kt(this,hw,!0),ls(this,kd,rAe).call(this,n),ls(this,kd,GO).call(this)):ye(this,rE)&&(Kt(this,JH,n.anchorNode),Kt(this,dae,n.anchorOffset),Kt(this,uae,n.focusNode),Kt(this,hae,n.focusOffset),ls(this,kd,xXe).call(this),ls(this,kd,GO).call(this),this.rotate(this.rotation))}static get _keyboardManager(){const n=em.prototype;return th(this,"_keyboardManager",new Xie([[["ArrowLeft","mac+ArrowLeft"],n._moveCaret,{args:[0]}],[["ArrowRight","mac+ArrowRight"],n._moveCaret,{args:[1]}],[["ArrowUp","mac+ArrowUp"],n._moveCaret,{args:[2]}],[["ArrowDown","mac+ArrowDown"],n._moveCaret,{args:[3]}]]))}get telemetryInitialData(){return{action:"added",type:ye(this,hw)?"free_highlight":"highlight",color:this._uiManager.highlightColorNames.get(this.color),thickness:ye(this,CN),methodOfCreation:ye(this,mae)}}get telemetryFinalData(){return{type:"highlight",color:this._uiManager.highlightColorNames.get(this.color)}}static computeTelemetryFinalData(n){return{numberOfColors:n.get("color").size}}static initialize(n,r){var a;Em.initialize(n,r),em._defaultColor||(em._defaultColor=((a=r.highlightColors)==null?void 0:a.values().next().value)||"#fff066")}static updateDefaultParams(n,r){switch(n){case nd.HIGHLIGHT_DEFAULT_COLOR:em._defaultColor=r;break;case nd.HIGHLIGHT_THICKNESS:em._defaultThickness=r;break}}translateInPage(n,r){}get toolbarPosition(){return ye(this,tG)}updateParams(n,r){switch(n){case nd.HIGHLIGHT_COLOR:ls(this,kd,ors).call(this,r);break;case nd.HIGHLIGHT_THICKNESS:ls(this,kd,lrs).call(this,r);break}}static get defaultPropertiesToUpdate(){return[[nd.HIGHLIGHT_DEFAULT_COLOR,em._defaultColor],[nd.HIGHLIGHT_THICKNESS,em._defaultThickness]]}get propertiesToUpdate(){return[[nd.HIGHLIGHT_COLOR,this.color||em._defaultColor],[nd.HIGHLIGHT_THICKNESS,ye(this,CN)||em._defaultThickness],[nd.HIGHLIGHT_FREE,ye(this,hw)]]}async addEditToolbar(){const n=await super.addEditToolbar();return n?(this._uiManager.highlightColors&&(Kt(this,eG,new bPe({editor:this})),n.addColorPicker(ye(this,eG))),n):null}disableEditing(){super.disableEditing(),this.div.classList.toggle("disabled",!0)}enableEditing(){super.enableEditing(),this.div.classList.toggle("disabled",!1)}fixAndSetPosition(){return super.fixAndSetPosition(ls(this,kd,$Q).call(this))}getBaseTranslation(){return[0,0]}getRect(n,r){return super.getRect(n,r,ls(this,kd,$Q).call(this))}onceAdded(){this.annotationElementId||this.parent.addUndoableEditor(this),this.div.focus()}remove(){ls(this,kd,yXe).call(this),this._reportTelemetry({action:"deleted"}),super.remove()}rebuild(){this.parent&&(super.rebuild(),this.div!==null&&(ls(this,kd,GO).call(this),this.isAttachedToDOM||this.parent.add(this)))}setParent(n){var a;let r=!1;this.parent&&!n?ls(this,kd,yXe).call(this):n&&(ls(this,kd,GO).call(this,n),r=!this.parent&&((a=this.div)==null?void 0:a.classList.contains("selectedEditor"))),super.setParent(n),this.show(this._isVisible),r&&this.select()}rotate(n){var i,l,o;const{drawLayer:r}=this.parent;let a;ye(this,hw)?(n=(n-this.rotation+360)%360,a=ls(i=em,HN,LU).call(i,ye(this,PS).box,n)):a=ls(l=em,HN,LU).call(l,this,n),r.rotate(ye(this,l1),n),r.rotate(ye(this,u0),n),r.updateBox(ye(this,l1),a),r.updateBox(ye(this,u0),ls(o=em,HN,LU).call(o,ye(this,SN).box,n))}render(){if(this.div)return this.div;const n=super.render();ye(this,sG)&&(n.setAttribute("aria-label",ye(this,sG)),n.setAttribute("role","mark")),ye(this,hw)?n.classList.add("free"):this.div.addEventListener("keydown",ls(this,kd,drs).bind(this),{signal:this._uiManager._signal});const r=Kt(this,Cz,document.createElement("div"));n.append(r),r.setAttribute("aria-hidden","true"),r.className="internal",r.style.clipPath=ye(this,Sz);const[a,i]=this.parentDimensions;return this.setDims(this.width*a,this.height*i),xPe(this,ye(this,Cz),["pointerover","pointerleave"]),this.enableEditing(),n}pointerover(){this.isSelected||this.parent.drawLayer.addClass(ye(this,u0),"hovered")}pointerleave(){this.isSelected||this.parent.drawLayer.removeClass(ye(this,u0),"hovered")}_moveCaret(n){switch(this.parent.unselect(this),n){case 0:case 2:ls(this,kd,aAe).call(this,!0);break;case 1:case 3:ls(this,kd,aAe).call(this,!1);break}}select(){var n,r;super.select(),ye(this,u0)&&((n=this.parent)==null||n.drawLayer.removeClass(ye(this,u0),"hovered"),(r=this.parent)==null||r.drawLayer.addClass(ye(this,u0),"selected"))}unselect(){var n;super.unselect(),ye(this,u0)&&((n=this.parent)==null||n.drawLayer.removeClass(ye(this,u0),"selected"),ye(this,hw)||ls(this,kd,aAe).call(this,!1))}get _mustFixPosition(){return!ye(this,hw)}show(n=this._isVisible){super.show(n),this.parent&&(this.parent.drawLayer.show(ye(this,l1),n),this.parent.drawLayer.show(ye(this,u0),n))}static startHighlighting(n,r,{target:a,x:i,y:l}){const{x:o,y:c,width:d,height:u}=a.getBoundingClientRect(),h=new AbortController,m=n.combinedSignal(h),f=x=>{x.preventDefault(),x.stopPropagation()},g=x=>{h.abort(),ls(this,HN,frs).call(this,n,x)};window.addEventListener("blur",g,{signal:m}),window.addEventListener("pointerup",g,{signal:m}),window.addEventListener("pointerdown",f,{capture:!0,passive:!1,signal:m}),window.addEventListener("contextmenu",yk,{signal:m}),a.addEventListener("pointermove",ls(this,HN,mrs).bind(this,n),{signal:m}),this._freeHighlight=new mXe({x:i,y:l},[o,c,d,u],n.scale,this._defaultThickness/2,r,.001),{id:this._freeHighlightId,clipPathId:this._freeHighlightClipId}=n.drawLayer.draw(this._freeHighlight,this._defaultColor,this._defaultOpacity,!0)}static async deserialize(n,r,a){var x,y,v,b;let i=null;if(n instanceof Bns){const{data:{quadPoints:w,rect:S,rotation:C,id:E,color:I,opacity:P,popupRef:R},parent:{page:{pageNumber:D}}}=n;i=n={annotationType:Od.HIGHLIGHT,color:Array.from(I),opacity:P,quadPoints:w,boxes:null,pageIndex:D-1,rect:S.slice(0),rotation:C,id:E,deleted:!1,popupRef:R}}else if(n instanceof Got){const{data:{inkLists:w,rect:S,rotation:C,id:E,color:I,borderStyle:{rawWidth:P},popupRef:R},parent:{page:{pageNumber:D}}}=n;i=n={annotationType:Od.HIGHLIGHT,color:Array.from(I),thickness:P,inkLists:w,boxes:null,pageIndex:D-1,rect:S.slice(0),rotation:C,id:E,deleted:!1,popupRef:R}}const{color:l,quadPoints:o,inkLists:c,opacity:d}=n,u=await super.deserialize(n,r,a);u.color=ol.makeHexColor(...l),Kt(u,aE,d||1),c&&Kt(u,CN,n.thickness),u.annotationElementId=n.id||null,u._initialData=i;const[h,m]=u.pageDimensions,[f,g]=u.pageTranslation;if(o){const w=Kt(u,rE,[]);for(let S=0;S=0)Kt(this,l1,r),Kt(this,Sz,a),this.parent.drawLayer.finalizeLine(r,n),Kt(this,u0,this.parent.drawLayer.drawOutline(ye(this,SN)));else if(this.parent){const f=this.parent.viewport.rotation;this.parent.drawLayer.updateLine(ye(this,l1),n),this.parent.drawLayer.updateBox(ye(this,l1),ls(h=em,HN,LU).call(h,ye(this,PS).box,(f-this.rotation+360)%360)),this.parent.drawLayer.updateLine(ye(this,u0),ye(this,SN)),this.parent.drawLayer.updateBox(ye(this,u0),ls(m=em,HN,LU).call(m,ye(this,SN).box,f))}const{x:l,y:o,width:c,height:d}=n.box;switch(this.rotation){case 0:this.x=l,this.y=o,this.width=c,this.height=d;break;case 90:{const[f,g]=this.parentDimensions;this.x=o,this.y=1-l,this.width=c*g/f,this.height=d*f/g;break}case 180:this.x=1-l,this.y=1-o,this.width=c,this.height=d;break;case 270:{const[f,g]=this.parentDimensions;this.x=1-o,this.y=l,this.width=c*g/f,this.height=d*f/g;break}}const{lastPoint:u}=ye(this,SN).box;Kt(this,tG,[(u[0]-l)/c,(u[1]-o)/d])},ors=function(n){const r=(l,o)=>{var c,d,u;this.color=l,(c=this.parent)==null||c.drawLayer.changeColor(ye(this,l1),l),(d=ye(this,eG))==null||d.updateColor(l),Kt(this,aE,o),(u=this.parent)==null||u.drawLayer.changeOpacity(ye(this,l1),o)},a=this.color,i=ye(this,aE);this.addCommands({cmd:r.bind(this,n,em._defaultOpacity),undo:r.bind(this,a,i),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:nd.HIGHLIGHT_COLOR,overwriteIfSameType:!0,keepUndo:!0}),this._reportTelemetry({action:"color_changed",color:this._uiManager.highlightColorNames.get(n)},!0)},lrs=function(n){const r=ye(this,CN),a=i=>{Kt(this,CN,i),ls(this,kd,crs).call(this,i)};this.addCommands({cmd:a.bind(this,n),undo:a.bind(this,r),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:nd.INK_THICKNESS,overwriteIfSameType:!0,keepUndo:!0}),this._reportTelemetry({action:"thickness_changed",thickness:n},!0)},crs=function(n){if(!ye(this,hw))return;ls(this,kd,rAe).call(this,{highlightOutlines:ye(this,PS).getNewOutline(n/2)}),this.fixAndSetPosition();const[r,a]=this.parentDimensions;this.setDims(this.width*r,this.height*a)},yXe=function(){ye(this,l1)===null||!this.parent||(this.parent.drawLayer.remove(ye(this,l1)),Kt(this,l1,null),this.parent.drawLayer.remove(ye(this,u0)),Kt(this,u0,null))},GO=function(n=this.parent){ye(this,l1)===null&&({id:J0(this,l1)._,clipPathId:J0(this,Sz)._}=n.drawLayer.draw(ye(this,PS),this.color,ye(this,aE)),Kt(this,u0,n.drawLayer.drawOutline(ye(this,SN))),ye(this,Cz)&&(ye(this,Cz).style.clipPath=ye(this,Sz)))},HN=new WeakSet,LU=function({x:n,y:r,width:a,height:i},l){switch(l){case 90:return{x:1-r-i,y:n,width:i,height:a};case 180:return{x:1-n-a,y:1-r-i,width:a,height:i};case 270:return{x:r,y:1-n-a,width:i,height:a}}return{x:n,y:r,width:a,height:i}},drs=function(n){em._keyboardManager.exec(this,n)},aAe=function(n){if(!ye(this,JH))return;const r=window.getSelection();n?r.setPosition(ye(this,JH),ye(this,dae)):r.setPosition(ye(this,uae),ye(this,hae))},$Q=function(){return ye(this,hw)?this.rotation:0},urs=function(){if(ye(this,hw))return null;const[n,r]=this.pageDimensions,[a,i]=this.pageTranslation,l=ye(this,rE),o=new Float32Array(l.length*8);let c=0;for(const{x:d,y:u,width:h,height:m}of l){const f=d*n+a,g=(1-u-m)*r+i;o[c]=o[c+4]=f,o[c+1]=o[c+3]=g,o[c+2]=o[c+6]=f+h*n,o[c+5]=o[c+7]=g+m*r,c+=8}return o},hrs=function(n){return ye(this,PS).serialize(n,ls(this,kd,$Q).call(this))},mrs=function(n,r){this._freeHighlight.add(r)&&n.drawLayer.updatePath(this._freeHighlightId,this._freeHighlight)},frs=function(n,r){this._freeHighlight.isEmpty()?n.drawLayer.remove(this._freeHighlightId):n.createAndAddNewEditor(r,!1,{highlightId:this._freeHighlightId,highlightOutlines:this._freeHighlight.getOutlines(),clipPathId:this._freeHighlightClipId,methodOfCreation:"main_toolbar"}),this._freeHighlightId=-1,this._freeHighlight=null,this._freeHighlightClipId=""},prs=function(n){const{color:r}=this._initialData;return n.color.some((a,i)=>a!==r[i])},bs(em,HN),Nr(em,"_defaultColor",null),Nr(em,"_defaultOpacity",1),Nr(em,"_defaultThickness",12),Nr(em,"_type","highlight"),Nr(em,"_editorType",Od.HIGHLIGHT),Nr(em,"_freeHighlightId",-1),Nr(em,"_freeHighlight",null),Nr(em,"_freeHighlightClipId","");let _Pe=em;var Az,Ez,X5,iE,AN,Tz,Mz,Pz,oE,nG,Iz,Lz,cI,Gi,grs,xrs,yrs,vrs,bXe,brs,_Xe,_rs,wrs,jrs,Nrs,krs,WO,wXe,jXe,NXe,iAe,oAe,RU,kXe,lAe,ST,Srs,SXe,Crs,Ars,CXe,cAe,UQ;const xg=class xg extends Em{constructor(n){super({...n,name:"inkEditor"});bs(this,Gi);bs(this,Az,0);bs(this,Ez,0);bs(this,X5,null);bs(this,iE,new Path2D);bs(this,AN,!1);bs(this,Tz,null);bs(this,Mz,!1);bs(this,Pz,!1);bs(this,oE,null);bs(this,nG,null);bs(this,Iz,0);bs(this,Lz,0);bs(this,cI,null);this.color=n.color||null,this.thickness=n.thickness||null,this.opacity=n.opacity||null,this.paths=[],this.bezierPath2D=[],this.allRawPaths=[],this.currentPath=[],this.scaleFactor=1,this.translationX=this.translationY=0,this.x=0,this.y=0,this._willKeepAspectRatio=!0}static initialize(n,r){Em.initialize(n,r)}static updateDefaultParams(n,r){switch(n){case nd.INK_THICKNESS:xg._defaultThickness=r;break;case nd.INK_COLOR:xg._defaultColor=r;break;case nd.INK_OPACITY:xg._defaultOpacity=r/100;break}}updateParams(n,r){switch(n){case nd.INK_THICKNESS:ls(this,Gi,grs).call(this,r);break;case nd.INK_COLOR:ls(this,Gi,xrs).call(this,r);break;case nd.INK_OPACITY:ls(this,Gi,yrs).call(this,r);break}}static get defaultPropertiesToUpdate(){return[[nd.INK_THICKNESS,xg._defaultThickness],[nd.INK_COLOR,xg._defaultColor||Em._defaultLineColor],[nd.INK_OPACITY,Math.round(xg._defaultOpacity*100)]]}get propertiesToUpdate(){return[[nd.INK_THICKNESS,this.thickness||xg._defaultThickness],[nd.INK_COLOR,this.color||xg._defaultColor||Em._defaultLineColor],[nd.INK_OPACITY,Math.round(100*(this.opacity??xg._defaultOpacity))]]}rebuild(){this.parent&&(super.rebuild(),this.div!==null&&(this.canvas||(ls(this,Gi,iAe).call(this),ls(this,Gi,oAe).call(this)),this.isAttachedToDOM||(this.parent.add(this),ls(this,Gi,RU).call(this)),ls(this,Gi,UQ).call(this)))}remove(){var n;this.canvas!==null&&(this.isEmpty()||this.commit(),this.canvas.width=this.canvas.height=0,this.canvas.remove(),this.canvas=null,ye(this,X5)&&(clearTimeout(ye(this,X5)),Kt(this,X5,null)),(n=ye(this,oE))==null||n.disconnect(),Kt(this,oE,null),super.remove())}setParent(n){!this.parent&&n?this._uiManager.removeShouldRescale(this):this.parent&&n===null&&this._uiManager.addShouldRescale(this),super.setParent(n)}onScaleChanging(){const[n,r]=this.parentDimensions,a=this.width*n,i=this.height*r;this.setDimensions(a,i)}enableEditMode(){ye(this,AN)||this.canvas===null||(super.enableEditMode(),this._isDraggable=!1,ls(this,Gi,wXe).call(this))}disableEditMode(){!this.isInEditMode()||this.canvas===null||(super.disableEditMode(),this._isDraggable=!this.isEmpty(),this.div.classList.remove("editing"),ls(this,Gi,jXe).call(this))}onceAdded(){this._isDraggable=!this.isEmpty()}isEmpty(){return this.paths.length===0||this.paths.length===1&&this.paths[0].length===0}commit(){ye(this,AN)||(super.commit(),this.isEditing=!1,this.disableEditMode(),this.setInForeground(),Kt(this,AN,!0),this.div.classList.add("disabled"),ls(this,Gi,UQ).call(this,!0),this.select(),this.parent.addInkEditorIfNeeded(!0),this.moveInDOM(),this.div.focus({preventScroll:!0}))}focusin(n){this._focusEventsAllowed&&(super.focusin(n),this.enableEditMode())}canvasPointerdown(n){n.button!==0||!this.isInEditMode()||ye(this,AN)||(this.setInForeground(),n.preventDefault(),this.div.contains(document.activeElement)||this.div.focus({preventScroll:!0}),ls(this,Gi,brs).call(this,n.offsetX,n.offsetY))}canvasPointermove(n){n.preventDefault(),ls(this,Gi,_Xe).call(this,n.offsetX,n.offsetY)}canvasPointerup(n){n.preventDefault(),ls(this,Gi,NXe).call(this,n)}canvasPointerleave(n){ls(this,Gi,NXe).call(this,n)}get isResizable(){return!this.isEmpty()&&ye(this,AN)}render(){if(this.div)return this.div;let n,r;this.width&&(n=this.x,r=this.y),super.render(),this.div.setAttribute("data-l10n-id","pdfjs-ink");const[a,i,l,o]=ls(this,Gi,vrs).call(this);if(this.setAt(a,i,0,0),this.setDims(l,o),ls(this,Gi,iAe).call(this),this.width){const[c,d]=this.parentDimensions;this.setAspectRatio(this.width*c,this.height*d),this.setAt(n*c,r*d,this.width*c,this.height*d),Kt(this,Pz,!0),ls(this,Gi,RU).call(this),this.setDims(this.width*c,this.height*d),ls(this,Gi,WO).call(this),this.div.classList.add("disabled")}else this.div.classList.add("editing"),this.enableEditMode();return ls(this,Gi,oAe).call(this),this.div}setDimensions(n,r){const a=Math.round(n),i=Math.round(r);if(ye(this,Iz)===a&&ye(this,Lz)===i)return;Kt(this,Iz,a),Kt(this,Lz,i),this.canvas.style.visibility="hidden";const[l,o]=this.parentDimensions;this.width=n/l,this.height=r/o,this.fixAndSetPosition(),ye(this,AN)&&ls(this,Gi,kXe).call(this,n,r),ls(this,Gi,RU).call(this),ls(this,Gi,WO).call(this),this.canvas.style.visibility="visible",this.fixDims()}static async deserialize(n,r,a){var y,v,b;if(n instanceof Got)return null;const i=await super.deserialize(n,r,a);i.thickness=n.thickness,i.color=ol.makeHexColor(...n.color),i.opacity=n.opacity;const[l,o]=i.pageDimensions,c=i.width*l,d=i.height*o,u=i.parentScale,h=n.thickness/2;Kt(i,AN,!0),Kt(i,Iz,Math.round(c)),Kt(i,Lz,Math.round(d));const{paths:m,rect:f,rotation:g}=n;for(let{bezier:w}of m){w=ls(y=xg,ST,Crs).call(y,w,f,g);const S=[];i.paths.push(S);let C=u*(w[0]-h),E=u*(w[1]-h);for(let P=2,R=w.length;P{this.thickness=i,ls(this,Gi,UQ).call(this)},a=this.thickness;this.addCommands({cmd:r.bind(this,n),undo:r.bind(this,a),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:nd.INK_THICKNESS,overwriteIfSameType:!0,keepUndo:!0})},xrs=function(n){const r=i=>{this.color=i,ls(this,Gi,WO).call(this)},a=this.color;this.addCommands({cmd:r.bind(this,n),undo:r.bind(this,a),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:nd.INK_COLOR,overwriteIfSameType:!0,keepUndo:!0})},yrs=function(n){const r=i=>{this.opacity=i,ls(this,Gi,WO).call(this)};n/=100;const a=this.opacity;this.addCommands({cmd:r.bind(this,n),undo:r.bind(this,a),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:nd.INK_OPACITY,overwriteIfSameType:!0,keepUndo:!0})},vrs=function(){const{parentRotation:n,parentDimensions:[r,a]}=this;switch(n){case 90:return[0,a,a,r];case 180:return[r,a,r,a];case 270:return[r,0,a,r];default:return[0,0,r,a]}},bXe=function(){const{ctx:n,color:r,opacity:a,thickness:i,parentScale:l,scaleFactor:o}=this;n.lineWidth=i*l/o,n.lineCap="round",n.lineJoin="round",n.miterLimit=10,n.strokeStyle=`${r}${bYn(a)}`},brs=function(n,r){this.canvas.addEventListener("contextmenu",yk,{signal:this._uiManager._signal}),ls(this,Gi,jXe).call(this),Kt(this,Tz,new AbortController);const a=this._uiManager.combinedSignal(ye(this,Tz));this.canvas.addEventListener("pointerleave",this.canvasPointerleave.bind(this),{signal:a}),this.canvas.addEventListener("pointermove",this.canvasPointermove.bind(this),{signal:a}),this.canvas.addEventListener("pointerup",this.canvasPointerup.bind(this),{signal:a}),this.isEditing=!0,ye(this,Pz)||(Kt(this,Pz,!0),ls(this,Gi,RU).call(this),this.thickness||(this.thickness=xg._defaultThickness),this.color||(this.color=xg._defaultColor||Em._defaultLineColor),this.opacity??(this.opacity=xg._defaultOpacity)),this.currentPath.push([n,r]),Kt(this,Mz,!1),ls(this,Gi,bXe).call(this),Kt(this,cI,()=>{ls(this,Gi,jrs).call(this),ye(this,cI)&&window.requestAnimationFrame(ye(this,cI))}),window.requestAnimationFrame(ye(this,cI))},_Xe=function(n,r){const[a,i]=this.currentPath.at(-1);if(this.currentPath.length>1&&n===a&&r===i)return;const l=this.currentPath;let o=ye(this,iE);if(l.push([n,r]),Kt(this,Mz,!0),l.length<=2){o.moveTo(...l[0]),o.lineTo(n,r);return}l.length===3&&(Kt(this,iE,o=new Path2D),o.moveTo(...l[0])),ls(this,Gi,Nrs).call(this,o,...l.at(-3),...l.at(-2),n,r)},_rs=function(){if(this.currentPath.length===0)return;const n=this.currentPath.at(-1);ye(this,iE).lineTo(...n)},wrs=function(n,r){Kt(this,cI,null),n=Math.min(Math.max(n,0),this.canvas.width),r=Math.min(Math.max(r,0),this.canvas.height),ls(this,Gi,_Xe).call(this,n,r),ls(this,Gi,_rs).call(this);let a;if(this.currentPath.length!==1)a=ls(this,Gi,krs).call(this);else{const d=[n,r];a=[[d,d.slice(),d.slice(),d]]}const i=ye(this,iE),l=this.currentPath;this.currentPath=[],Kt(this,iE,new Path2D);const o=()=>{this.allRawPaths.push(l),this.paths.push(a),this.bezierPath2D.push(i),this._uiManager.rebuild(this)},c=()=>{this.allRawPaths.pop(),this.paths.pop(),this.bezierPath2D.pop(),this.paths.length===0?this.remove():(this.canvas||(ls(this,Gi,iAe).call(this),ls(this,Gi,oAe).call(this)),ls(this,Gi,UQ).call(this))};this.addCommands({cmd:o,undo:c,mustExec:!0})},jrs=function(){if(!ye(this,Mz))return;Kt(this,Mz,!1);const n=Math.ceil(this.thickness*this.parentScale),r=this.currentPath.slice(-3),a=r.map(o=>o[0]),i=r.map(o=>o[1]);Math.min(...a)-n,Math.max(...a)+n,Math.min(...i)-n,Math.max(...i)+n;const{ctx:l}=this;l.save(),l.clearRect(0,0,this.canvas.width,this.canvas.height);for(const o of this.bezierPath2D)l.stroke(o);l.stroke(ye(this,iE)),l.restore()},Nrs=function(n,r,a,i,l,o,c){const d=(r+i)/2,u=(a+l)/2,h=(i+o)/2,m=(l+c)/2;n.bezierCurveTo(d+2*(i-d)/3,u+2*(l-u)/3,h+2*(i-h)/3,m+2*(l-m)/3,h,m)},krs=function(){const n=this.currentPath;if(n.length<=2)return[[n[0],n[0],n.at(-1),n.at(-1)]];const r=[];let a,[i,l]=n[0];for(a=1;a{Kt(this,X5,null),this.canvas.removeEventListener("contextmenu",yk)},10)),ls(this,Gi,wrs).call(this,n.offsetX,n.offsetY),this.addToAnnotationStorage(),this.setInBackground()},iAe=function(){this.canvas=document.createElement("canvas"),this.canvas.width=this.canvas.height=0,this.canvas.className="inkEditorCanvas",this.canvas.setAttribute("data-l10n-id","pdfjs-ink-canvas"),this.div.append(this.canvas),this.ctx=this.canvas.getContext("2d")},oAe=function(){Kt(this,oE,new ResizeObserver(n=>{const r=n[0].contentRect;r.width&&r.height&&this.setDimensions(r.width,r.height)})),ye(this,oE).observe(this.div),this._uiManager._signal.addEventListener("abort",()=>{var n;(n=ye(this,oE))==null||n.disconnect(),Kt(this,oE,null)},{once:!0})},RU=function(){if(!ye(this,Pz))return;const[n,r]=this.parentDimensions;this.canvas.width=Math.ceil(this.width*n),this.canvas.height=Math.ceil(this.height*r),ls(this,Gi,lAe).call(this)},kXe=function(n,r){const a=ls(this,Gi,cAe).call(this),i=(n-a)/ye(this,Ez),l=(r-a)/ye(this,Az);this.scaleFactor=Math.min(i,l)},lAe=function(){const n=ls(this,Gi,cAe).call(this)/2;this.ctx.setTransform(this.scaleFactor,0,0,this.scaleFactor,this.translationX*this.scaleFactor+n,this.translationY*this.scaleFactor+n)},ST=new WeakSet,Srs=function(n){const r=new Path2D;for(let a=0,i=n.length;a`image/${r}`))}static get supportedTypesStr(){return th(this,"supportedTypesStr",this.supportedTypes.join(","))}static isHandlingMimeForPasting(n){return this.supportedTypes.includes(n)}static paste(n,r){r.pasteEditor(Od.STAMP,{bitmapFile:n.getAsFile()})}altTextFinish(){this._uiManager.useNewAltTextFlow&&(this.div.hidden=!1),super.altTextFinish()}get telemetryFinalData(){var n;return{type:"stamp",hasAltText:!!((n=this.altTextData)!=null&&n.altText)}}static computeTelemetryFinalData(n){const r=n.get("hasAltText");return{hasAltText:r.get(!0)??0,hasNoAltText:r.get(!1)??0}}async mlGuessAltText(n=null,r=!0){if(this.hasAltTextData())return null;const{mlManager:a}=this._uiManager;if(!a)throw new Error("No ML.");if(!await a.isEnabledFor("altText"))throw new Error("ML isn't enabled for alt text.");const{data:i,width:l,height:o}=n||this.copyCanvas(null,null,!0).imageData,c=await a.guess({name:"altText",request:{data:i,width:l,height:o,channels:i.length/(l*o)}});if(!c)throw new Error("No response from the AI service.");if(c.error)throw new Error("Error from the AI service.");if(c.cancel)return null;if(!c.output)throw new Error("No valid response from the AI service.");const d=c.output;return await this.setGuessedAltText(d),r&&!this.hasAltTextData()&&(this.altTextData={alt:d,decorative:!1}),d}remove(){var n,r;ye(this,tb)&&(Kt(this,bg,null),this._uiManager.imageManager.deleteId(ye(this,tb)),(n=ye(this,Q5))==null||n.remove(),Kt(this,Q5,null),(r=ye(this,cE))==null||r.disconnect(),Kt(this,cE,null),ye(this,J5)&&(clearTimeout(ye(this,J5)),Kt(this,J5,null))),super.remove()}rebuild(){if(!this.parent){ye(this,tb)&&ls(this,zu,dAe).call(this);return}super.rebuild(),this.div!==null&&(ye(this,tb)&&ye(this,Q5)===null&&ls(this,zu,dAe).call(this),this.isAttachedToDOM||this.parent.add(this))}onceAdded(){this._isDraggable=!0,this.div.focus()}isEmpty(){return!(ye(this,dI)||ye(this,bg)||ye(this,lE)||ye(this,uI)||ye(this,tb))}get isResizable(){return!0}render(){if(this.div)return this.div;let n,r;if(this.width&&(n=this.x,r=this.y),super.render(),this.div.hidden=!0,this.div.setAttribute("role","figure"),this.addAltTextButton(),ye(this,bg)?ls(this,zu,EXe).call(this):ls(this,zu,dAe).call(this),this.width&&!this.annotationElementId){const[a,i]=this.parentDimensions;this.setAt(n*a,r*i,this.width*a,this.height*i)}return this.div}copyCanvas(n,r,a=!1){var f;n||(n=224);const{width:i,height:l}=ye(this,bg),o=new kZe;let c=ye(this,bg),d=i,u=l,h=null;if(r){if(i>r||l>r){const P=Math.min(r/i,r/l);d=Math.floor(i*P),u=Math.floor(l*P)}h=document.createElement("canvas");const g=h.width=Math.ceil(d*o.sx),x=h.height=Math.ceil(u*o.sy);ye(this,Bj)||(c=ls(this,zu,uAe).call(this,g,x));const y=h.getContext("2d");y.filter=this._uiManager.hcmFilter;let v="white",b="#cfcfd8";this._uiManager.hcmFilter!=="none"?b="black":(f=window.matchMedia)!=null&&f.call(window,"(prefers-color-scheme: dark)").matches&&(v="#8f8f9d",b="#42414d");const w=15,S=w*o.sx,C=w*o.sy,E=new OffscreenCanvas(S*2,C*2),I=E.getContext("2d");I.fillStyle=v,I.fillRect(0,0,S*2,C*2),I.fillStyle=b,I.fillRect(0,0,S,C),I.fillRect(S,C,S,C),y.fillStyle=y.createPattern(E,"repeat"),y.fillRect(0,0,g,x),y.drawImage(c,0,0,c.width,c.height,0,0,g,x)}let m=null;if(a){let g,x;if(o.symmetric&&c.widthn||l>n){const b=Math.min(n/i,n/l);g=Math.floor(i*b),x=Math.floor(l*b),ye(this,Bj)||(c=ls(this,zu,uAe).call(this,g,x))}const v=new OffscreenCanvas(g,x).getContext("2d",{willReadFrequently:!0});v.drawImage(c,0,0,c.width,c.height,0,0,g,x),m={width:g,height:x,data:v.getImageData(0,0,g,x).data}}return{canvas:h,width:d,height:u,imageData:m}}getImageForAltText(){return ye(this,Q5)}static async deserialize(n,r,a){var x;let i=null;if(n instanceof $ns){const{data:{rect:y,rotation:v,id:b,structParent:w,popupRef:S},container:C,parent:{page:{pageNumber:E}}}=n,I=C.querySelector("canvas"),P=a.imageManager.getFromCanvas(C.id,I);I.remove();const R=((x=await r._structTree.getAriaAttributes(`${Rot}${b}`))==null?void 0:x.get("aria-label"))||"";i=n={annotationType:Od.STAMP,bitmapId:P.id,bitmap:P.bitmap,pageIndex:E-1,rect:y.slice(0),rotation:v,id:b,deleted:!1,accessibilityData:{decorative:!1,altText:R},isSvg:!1,structParent:w,popupRef:S}}const l=await super.deserialize(n,r,a),{rect:o,bitmap:c,bitmapUrl:d,bitmapId:u,isSvg:h,accessibilityData:m}=n;u&&a.imageManager.isValidId(u)?(Kt(l,tb,u),c&&Kt(l,bg,c)):Kt(l,lE,d),Kt(l,Bj,h);const[f,g]=l.pageDimensions;return l.width=(o[2]-o[0])/f,l.height=(o[3]-o[1])/g,l.annotationElementId=n.id||null,m&&(l.altTextData=m),l._initialData=i,Kt(l,aG,!!i),l}serialize(n=!1,r=null){if(this.isEmpty())return null;if(this.deleted)return this.serializeDeleted();const a={annotationType:Od.STAMP,bitmapId:ye(this,tb),pageIndex:this.pageIndex,rect:this.getRect(0,0),rotation:this.rotation,isSvg:ye(this,Bj),structTreeParentId:this._structTreeParentId};if(n)return a.bitmapUrl=ls(this,zu,hAe).call(this,!0),a.accessibilityData=this.serializeAltText(!0),a;const{decorative:i,altText:l}=this.serializeAltText(!1);if(!i&&l&&(a.accessibilityData={type:"Figure",alt:l}),this.annotationElementId){const c=ls(this,zu,Mrs).call(this,a);if(c.isSame)return null;c.isSameAltText?delete a.accessibilityData:a.accessibilityData.structParent=this._initialData.structParent??-1}if(a.id=this.annotationElementId,r===null)return a;r.stamps||(r.stamps=new Map);const o=ye(this,Bj)?(a.rect[2]-a.rect[0])*(a.rect[3]-a.rect[1]):null;if(!r.stamps.has(ye(this,tb)))r.stamps.set(ye(this,tb),{area:o,serialized:a}),a.bitmap=ls(this,zu,hAe).call(this,!1);else if(ye(this,Bj)){const c=r.stamps.get(ye(this,tb));o>c.area&&(c.area=o,c.serialized.bitmap.close(),c.serialized.bitmap=ls(this,zu,hAe).call(this,!1))}return a}renderAnnotationElement(n){return n.updateEdited({rect:this.getRect(0,0)}),null}};bg=new WeakMap,tb=new WeakMap,dI=new WeakMap,lE=new WeakMap,uI=new WeakMap,rG=new WeakMap,Q5=new WeakMap,cE=new WeakMap,J5=new WeakMap,Bj=new WeakMap,aG=new WeakMap,zu=new WeakSet,qQ=function(n,r=!1){if(!n){this.remove();return}Kt(this,bg,n.bitmap),r||(Kt(this,tb,n.id),Kt(this,Bj,n.isSvg)),n.file&&Kt(this,rG,n.file.name),ls(this,zu,EXe).call(this)},VQ=function(){if(Kt(this,dI,null),this._uiManager.enableWaiting(!1),!!ye(this,Q5)){if(this._uiManager.useNewAltTextWhenAddingImage&&this._uiManager.useNewAltTextFlow&&ye(this,bg)){this._editToolbar.hide(),this._uiManager.editAltText(this,!0);return}if(!this._uiManager.useNewAltTextWhenAddingImage&&this._uiManager.useNewAltTextFlow&&ye(this,bg)){this._reportTelemetry({action:"pdfjs.image.image_added",data:{alt_text_modal:!1,alt_text_type:"empty"}});try{this.mlGuessAltText()}catch{}}this.div.focus()}},dAe=function(){if(ye(this,tb)){this._uiManager.enableWaiting(!0),this._uiManager.imageManager.getFromId(ye(this,tb)).then(a=>ls(this,zu,qQ).call(this,a,!0)).finally(()=>ls(this,zu,VQ).call(this));return}if(ye(this,lE)){const a=ye(this,lE);Kt(this,lE,null),this._uiManager.enableWaiting(!0),Kt(this,dI,this._uiManager.imageManager.getFromUrl(a).then(i=>ls(this,zu,qQ).call(this,i)).finally(()=>ls(this,zu,VQ).call(this)));return}if(ye(this,uI)){const a=ye(this,uI);Kt(this,uI,null),this._uiManager.enableWaiting(!0),Kt(this,dI,this._uiManager.imageManager.getFromFile(a).then(i=>ls(this,zu,qQ).call(this,i)).finally(()=>ls(this,zu,VQ).call(this)));return}const n=document.createElement("input");n.type="file",n.accept=Ste.supportedTypesStr;const r=this._uiManager._signal;Kt(this,dI,new Promise(a=>{n.addEventListener("change",async()=>{if(!n.files||n.files.length===0)this.remove();else{this._uiManager.enableWaiting(!0);const i=await this._uiManager.imageManager.getFromFile(n.files[0]);this._reportTelemetry({action:"pdfjs.image.image_selected",data:{alt_text_modal:this._uiManager.useNewAltTextFlow}}),ls(this,zu,qQ).call(this,i)}a()},{signal:r}),n.addEventListener("cancel",()=>{this.remove(),a()},{signal:r})}).finally(()=>ls(this,zu,VQ).call(this))),n.click()},EXe=function(){const{div:n}=this;let{width:r,height:a}=ye(this,bg);const[i,l]=this.pageDimensions,o=.75;if(this.width)r=this.width*i,a=this.height*l;else if(r>o*i||a>o*l){const h=Math.min(o*i/r,o*l/a);r*=h,a*=h}const[c,d]=this.parentDimensions;this.setDims(r*c/i,a*d/l),this._uiManager.enableWaiting(!1);const u=Kt(this,Q5,document.createElement("canvas"));u.setAttribute("role","img"),this.addContainer(u),(!this._uiManager.useNewAltTextWhenAddingImage||!this._uiManager.useNewAltTextFlow||this.annotationElementId)&&(n.hidden=!1),ls(this,zu,TXe).call(this,r,a),ls(this,zu,Trs).call(this),ye(this,aG)||(this.parent.addUndoableEditor(this),Kt(this,aG,!0)),this._reportTelemetry({action:"inserted_image"}),ye(this,rG)&&u.setAttribute("aria-label",ye(this,rG))},Ers=function(n,r){var o;const[a,i]=this.parentDimensions;this.width=n/a,this.height=r/i,(o=this._initialOptions)!=null&&o.isCentered?this.center():this.fixAndSetPosition(),this._initialOptions=null,ye(this,J5)!==null&&clearTimeout(ye(this,J5)),Kt(this,J5,setTimeout(()=>{Kt(this,J5,null),ls(this,zu,TXe).call(this,n,r)},200))},uAe=function(n,r){const{width:a,height:i}=ye(this,bg);let l=a,o=i,c=ye(this,bg);for(;l>2*n||o>2*r;){const d=l,u=o;l>2*n&&(l=l>=16384?Math.floor(l/2)-1:Math.ceil(l/2)),o>2*r&&(o=o>=16384?Math.floor(o/2)-1:Math.ceil(o/2));const h=new OffscreenCanvas(l,o);h.getContext("2d").drawImage(c,0,0,d,u,0,0,l,o),c=h.transferToImageBitmap()}return c},TXe=function(n,r){const a=new kZe,i=Math.ceil(n*a.sx),l=Math.ceil(r*a.sy),o=ye(this,Q5);if(!o||o.width===i&&o.height===l)return;o.width=i,o.height=l;const c=ye(this,Bj)?ye(this,bg):ls(this,zu,uAe).call(this,i,l),d=o.getContext("2d");d.filter=this._uiManager.hcmFilter,d.drawImage(c,0,0,c.width,c.height,0,0,i,l)},hAe=function(n){if(n){if(ye(this,Bj)){const i=this._uiManager.imageManager.getSvgUrl(ye(this,tb));if(i)return i}const r=document.createElement("canvas");return{width:r.width,height:r.height}=ye(this,bg),r.getContext("2d").drawImage(ye(this,bg),0,0),r.toDataURL()}if(ye(this,Bj)){const[r,a]=this.pageDimensions,i=Math.round(this.width*r*VL.PDF_TO_CSS_UNITS),l=Math.round(this.height*a*VL.PDF_TO_CSS_UNITS),o=new OffscreenCanvas(i,l);return o.getContext("2d").drawImage(ye(this,bg),0,0,ye(this,bg).width,ye(this,bg).height,0,0,i,l),o.transferToImageBitmap()}return structuredClone(ye(this,bg))},Trs=function(){this._uiManager._signal&&(Kt(this,cE,new ResizeObserver(n=>{const r=n[0].contentRect;r.width&&r.height&&ls(this,zu,Ers).call(this,r.width,r.height)})),ye(this,cE).observe(this.div),this._uiManager._signal.addEventListener("abort",()=>{var n;(n=ye(this,cE))==null||n.disconnect(),Kt(this,cE,null)},{once:!0}))},Mrs=function(n){var d;const{rect:r,pageIndex:a,accessibilityData:{altText:i}}=this._initialData,l=n.rect.every((u,h)=>Math.abs(u-r[h])<1),o=n.pageIndex===a,c=(((d=n.accessibilityData)==null?void 0:d.alt)||"")===i;return{isSame:l&&o&&c,isSameAltText:c}},Nr(Ste,"_type","stamp"),Nr(Ste,"_editorType",Od.STAMP);let AXe=Ste;var Rz,iG,e4,hI,dE,$j,mI,oG,lG,c1,uE,Rl,fI,Cb,Prs,PXe,IXe,LXe,mAe;const pS=class pS{constructor({uiManager:t,pageIndex:n,div:r,structTreeLayer:a,accessibilityManager:i,annotationLayer:l,drawLayer:o,textLayer:c,viewport:d,l10n:u}){bs(this,Cb);bs(this,Rz);bs(this,iG,!1);bs(this,e4,null);bs(this,hI,null);bs(this,dE,null);bs(this,$j,new Map);bs(this,mI,!1);bs(this,oG,!1);bs(this,lG,!1);bs(this,c1,null);bs(this,uE,null);bs(this,Rl);const h=[...ye(pS,fI).values()];if(!pS._initialized){pS._initialized=!0;for(const m of h)m.initialize(u,t)}t.registerEditorTypes(h),Kt(this,Rl,t),this.pageIndex=n,this.div=r,Kt(this,Rz,i),Kt(this,e4,l),this.viewport=d,Kt(this,c1,c),this.drawLayer=o,this._structTree=a,ye(this,Rl).addLayer(this)}get isEmpty(){return ye(this,$j).size===0}get isInvisible(){return this.isEmpty&&ye(this,Rl).getMode()===Od.NONE}updateToolbar(t){ye(this,Rl).updateToolbar(t)}updateMode(t=ye(this,Rl).getMode()){switch(ls(this,Cb,mAe).call(this),t){case Od.NONE:this.disableTextSelection(),this.togglePointerEvents(!1),this.toggleAnnotationLayerPointerEvents(!0),this.disableClick();return;case Od.INK:this.addInkEditorIfNeeded(!1),this.disableTextSelection(),this.togglePointerEvents(!0),this.disableClick();break;case Od.HIGHLIGHT:this.enableTextSelection(),this.togglePointerEvents(!1),this.disableClick();break;default:this.disableTextSelection(),this.togglePointerEvents(!0),this.enableClick()}this.toggleAnnotationLayerPointerEvents(!1);const{classList:n}=this.div;for(const r of ye(pS,fI).values())n.toggle(`${r._type}Editing`,t===r._editorType);this.div.hidden=!1}hasTextLayer(t){var n;return t===((n=ye(this,c1))==null?void 0:n.div)}addInkEditorIfNeeded(t){if(ye(this,Rl).getMode()!==Od.INK)return;if(!t){for(const r of ye(this,$j).values())if(r.isEmpty()){r.setInBackground();return}}this.createAndAddNewEditor({offsetX:0,offsetY:0},!1).setInBackground()}setEditingState(t){ye(this,Rl).setEditingState(t)}addCommands(t){ye(this,Rl).addCommands(t)}toggleDrawing(t=!1){this.div.classList.toggle("drawing",!t)}togglePointerEvents(t=!1){this.div.classList.toggle("disabled",!t)}toggleAnnotationLayerPointerEvents(t=!1){var n;(n=ye(this,e4))==null||n.div.classList.toggle("disabled",!t)}async enable(){this.div.tabIndex=0,this.togglePointerEvents(!0);const t=new Set;for(const r of ye(this,$j).values())r.enableEditing(),r.show(!0),r.annotationElementId&&(ye(this,Rl).removeChangedExistingAnnotation(r),t.add(r.annotationElementId));if(!ye(this,e4))return;const n=ye(this,e4).getEditableAnnotations();for(const r of n){if(r.hide(),ye(this,Rl).isDeletedAnnotationElement(r.data.id)||t.has(r.data.id))continue;const a=await this.deserialize(r);a&&(this.addOrRebuild(a),a.enableEditing())}}disable(){var a;Kt(this,lG,!0),this.div.tabIndex=-1,this.togglePointerEvents(!1);const t=new Map,n=new Map;for(const i of ye(this,$j).values())if(i.disableEditing(),!!i.annotationElementId){if(i.serialize()!==null){t.set(i.annotationElementId,i);continue}else n.set(i.annotationElementId,i);(a=this.getEditableAnnotation(i.annotationElementId))==null||a.show(),i.remove()}if(ye(this,e4)){const i=ye(this,e4).getEditableAnnotations();for(const l of i){const{id:o}=l.data;if(ye(this,Rl).isDeletedAnnotationElement(o))continue;let c=n.get(o);if(c){c.resetAnnotationElement(l),c.show(!1),l.show();continue}c=t.get(o),c&&(ye(this,Rl).addChangedExistingAnnotation(c),c.renderAnnotationElement(l)&&c.show(!1)),l.show()}}ls(this,Cb,mAe).call(this),this.isEmpty&&(this.div.hidden=!0);const{classList:r}=this.div;for(const i of ye(pS,fI).values())r.remove(`${i._type}Editing`);this.disableTextSelection(),this.toggleAnnotationLayerPointerEvents(!0),Kt(this,lG,!1)}getEditableAnnotation(t){var n;return((n=ye(this,e4))==null?void 0:n.getEditableAnnotation(t))||null}setActiveEditor(t){ye(this,Rl).getActive()!==t&&ye(this,Rl).setActiveEditor(t)}enableTextSelection(){var t;if(this.div.tabIndex=-1,(t=ye(this,c1))!=null&&t.div&&!ye(this,uE)){Kt(this,uE,new AbortController);const n=ye(this,Rl).combinedSignal(ye(this,uE));ye(this,c1).div.addEventListener("pointerdown",ls(this,Cb,Prs).bind(this),{signal:n}),ye(this,c1).div.classList.add("highlighting")}}disableTextSelection(){var t;this.div.tabIndex=0,(t=ye(this,c1))!=null&&t.div&&ye(this,uE)&&(ye(this,uE).abort(),Kt(this,uE,null),ye(this,c1).div.classList.remove("highlighting"))}enableClick(){if(ye(this,hI))return;Kt(this,hI,new AbortController);const t=ye(this,Rl).combinedSignal(ye(this,hI));this.div.addEventListener("pointerdown",this.pointerdown.bind(this),{signal:t}),this.div.addEventListener("pointerup",this.pointerup.bind(this),{signal:t})}disableClick(){var t;(t=ye(this,hI))==null||t.abort(),Kt(this,hI,null)}attach(t){ye(this,$j).set(t.id,t);const{annotationElementId:n}=t;n&&ye(this,Rl).isDeletedAnnotationElement(n)&&ye(this,Rl).removeDeletedAnnotationElement(t)}detach(t){var n;ye(this,$j).delete(t.id),(n=ye(this,Rz))==null||n.removePointerInTextLayer(t.contentDiv),!ye(this,lG)&&t.annotationElementId&&ye(this,Rl).addDeletedAnnotationElement(t)}remove(t){this.detach(t),ye(this,Rl).removeEditor(t),t.div.remove(),t.isAttachedToDOM=!1,ye(this,oG)||this.addInkEditorIfNeeded(!1)}changeParent(t){var n;t.parent!==this&&(t.parent&&t.annotationElementId&&(ye(this,Rl).addDeletedAnnotationElement(t.annotationElementId),Em.deleteAnnotationElement(t),t.annotationElementId=null),this.attach(t),(n=t.parent)==null||n.detach(t),t.setParent(this),t.div&&t.isAttachedToDOM&&(t.div.remove(),this.div.append(t.div)))}add(t){if(!(t.parent===this&&t.isAttachedToDOM)){if(this.changeParent(t),ye(this,Rl).addEditor(t),this.attach(t),!t.isAttachedToDOM){const n=t.render();this.div.append(n),t.isAttachedToDOM=!0}t.fixAndSetPosition(),t.onceAdded(),ye(this,Rl).addToAnnotationStorage(t),t._reportTelemetry(t.telemetryInitialData)}}moveEditorInDOM(t){var r;if(!t.isAttachedToDOM)return;const{activeElement:n}=document;t.div.contains(n)&&!ye(this,dE)&&(t._focusEventsAllowed=!1,Kt(this,dE,setTimeout(()=>{Kt(this,dE,null),t.div.contains(document.activeElement)?t._focusEventsAllowed=!0:(t.div.addEventListener("focusin",()=>{t._focusEventsAllowed=!0},{once:!0,signal:ye(this,Rl)._signal}),n.focus())},0))),t._structTreeParentId=(r=ye(this,Rz))==null?void 0:r.moveElementInDOM(this.div,t.div,t.contentDiv,!0)}addOrRebuild(t){t.needsToBeRebuilt()?(t.parent||(t.parent=this),t.rebuild(),t.show()):this.add(t)}addUndoableEditor(t){const n=()=>t._uiManager.rebuild(t),r=()=>{t.remove()};this.addCommands({cmd:n,undo:r,mustExec:!1})}getNextId(){return ye(this,Rl).getId()}combinedSignal(t){return ye(this,Rl).combinedSignal(t)}canCreateNewEmptyEditor(){var t;return(t=ye(this,Cb,PXe))==null?void 0:t.canCreateNewEmptyEditor()}pasteEditor(t,n){ye(this,Rl).updateToolbar(t),ye(this,Rl).updateMode(t);const{offsetX:r,offsetY:a}=ls(this,Cb,LXe).call(this),i=this.getNextId(),l=ls(this,Cb,IXe).call(this,{parent:this,id:i,x:r,y:a,uiManager:ye(this,Rl),isCentered:!0,...n});l&&this.add(l)}async deserialize(t){var n;return await((n=ye(pS,fI).get(t.annotationType??t.annotationEditorType))==null?void 0:n.deserialize(t,this,ye(this,Rl)))||null}createAndAddNewEditor(t,n,r={}){const a=this.getNextId(),i=ls(this,Cb,IXe).call(this,{parent:this,id:a,x:t.offsetX,y:t.offsetY,uiManager:ye(this,Rl),isCentered:n,...r});return i&&this.add(i),i}addNewEditor(){this.createAndAddNewEditor(ls(this,Cb,LXe).call(this),!0)}setSelected(t){ye(this,Rl).setSelected(t)}toggleSelected(t){ye(this,Rl).toggleSelected(t)}unselect(t){ye(this,Rl).unselect(t)}pointerup(t){const{isMac:n}=T_.platform;if(!(t.button!==0||t.ctrlKey&&n)&&t.target===this.div&&ye(this,mI)){if(Kt(this,mI,!1),!ye(this,iG)){Kt(this,iG,!0);return}if(ye(this,Rl).getMode()===Od.STAMP){ye(this,Rl).unselectAll();return}this.createAndAddNewEditor(t,!1)}}pointerdown(t){if(ye(this,Rl).getMode()===Od.HIGHLIGHT&&this.enableTextSelection(),ye(this,mI)){Kt(this,mI,!1);return}const{isMac:n}=T_.platform;if(t.button!==0||t.ctrlKey&&n||t.target!==this.div)return;Kt(this,mI,!0);const r=ye(this,Rl).getActive();Kt(this,iG,!r||r.isEmpty())}findNewParent(t,n,r){const a=ye(this,Rl).findParent(n,r);return a===null||a===this?!1:(a.changeParent(t),!0)}destroy(){var t,n;((t=ye(this,Rl).getActive())==null?void 0:t.parent)===this&&(ye(this,Rl).commitOrRemove(),ye(this,Rl).setActiveEditor(null)),ye(this,dE)&&(clearTimeout(ye(this,dE)),Kt(this,dE,null));for(const r of ye(this,$j).values())(n=ye(this,Rz))==null||n.removePointerInTextLayer(r.contentDiv),r.setParent(null),r.isAttachedToDOM=!1,r.div.remove();this.div=null,ye(this,$j).clear(),ye(this,Rl).removeLayer(this)}render({viewport:t}){this.viewport=t,bB(this.div,t);for(const n of ye(this,Rl).getEditors(this.pageIndex))this.add(n),n.rebuild();this.updateMode()}update({viewport:t}){ye(this,Rl).commitOrRemove(),ls(this,Cb,mAe).call(this);const n=this.viewport.rotation,r=t.rotation;if(this.viewport=t,bB(this.div,{rotation:r}),n!==r)for(const a of ye(this,$j).values())a.rotate(r);this.addInkEditorIfNeeded(!1)}get pageDimensions(){const{pageWidth:t,pageHeight:n}=this.viewport.rawDims;return[t,n]}get scale(){return ye(this,Rl).viewParameters.realScale}};Rz=new WeakMap,iG=new WeakMap,e4=new WeakMap,hI=new WeakMap,dE=new WeakMap,$j=new WeakMap,mI=new WeakMap,oG=new WeakMap,lG=new WeakMap,c1=new WeakMap,uE=new WeakMap,Rl=new WeakMap,fI=new WeakMap,Cb=new WeakSet,Prs=function(t){ye(this,Rl).unselectAll();const{target:n}=t;if(n===ye(this,c1).div||(n.getAttribute("role")==="img"||n.classList.contains("endOfContent"))&&ye(this,c1).div.contains(n)){const{isMac:r}=T_.platform;if(t.button!==0||t.ctrlKey&&r)return;ye(this,Rl).showAllEditors("highlight",!0,!0),ye(this,c1).div.classList.add("free"),this.toggleDrawing(),_Pe.startHighlighting(this,ye(this,Rl).direction==="ltr",{target:ye(this,c1).div,x:t.x,y:t.y}),ye(this,c1).div.addEventListener("pointerup",()=>{ye(this,c1).div.classList.remove("free"),this.toggleDrawing(!0)},{once:!0,signal:ye(this,Rl)._signal}),t.preventDefault()}},PXe=function(){return ye(pS,fI).get(ye(this,Rl).getMode())},IXe=function(t){const n=ye(this,Cb,PXe);return n?new n.prototype.constructor(t):null},LXe=function(){const{x:t,y:n,width:r,height:a}=this.div.getBoundingClientRect(),i=Math.max(0,t),l=Math.max(0,n),o=Math.min(window.innerWidth,t+r),c=Math.min(window.innerHeight,n+a),d=(i+o)/2-t,u=(l+c)/2-n,[h,m]=this.viewport.rotation%180===0?[d,u]:[u,d];return{offsetX:h,offsetY:m}},mAe=function(){Kt(this,oG,!0);for(const t of ye(this,$j).values())t.isEmpty()&&t.remove();Kt(this,oG,!1)},Nr(pS,"_initialized",!1),bs(pS,fI,new Map([dXe,vXe,AXe,_Pe].map(t=>[t._editorType,t])));let MXe=pS;var t4,fae,My,hE,pae,DXe,TB,FXe,Irs;const Qv=class Qv{constructor({pageIndex:t}){bs(this,TB);bs(this,t4,null);bs(this,fae,0);bs(this,My,new Map);bs(this,hE,new Map);this.pageIndex=t}setParent(t){if(!ye(this,t4)){Kt(this,t4,t);return}if(ye(this,t4)!==t){if(ye(this,My).size>0)for(const n of ye(this,My).values())n.remove(),t.append(n);Kt(this,t4,t)}}static get _svgFactory(){return th(this,"_svgFactory",new Hot)}draw(t,n,r,a=!1){const i=J0(this,fae)._++,l=ls(this,TB,FXe).call(this,t.box);l.classList.add(...t.classNamesForDrawing);const o=Qv._svgFactory.createElement("defs");l.append(o);const c=Qv._svgFactory.createElement("path");o.append(c);const d=`path_p${this.pageIndex}_${i}`;c.setAttribute("id",d),c.setAttribute("d",t.toSVGPath()),a&&ye(this,hE).set(i,c);const u=ls(this,TB,Irs).call(this,o,d),h=Qv._svgFactory.createElement("use");return l.append(h),l.setAttribute("fill",n),l.setAttribute("fill-opacity",r),h.setAttribute("href",`#${d}`),ye(this,My).set(i,l),{id:i,clipPathId:`url(#${u})`}}drawOutline(t){const n=J0(this,fae)._++,r=ls(this,TB,FXe).call(this,t.box);r.classList.add(...t.classNamesForOutlining);const a=Qv._svgFactory.createElement("defs");r.append(a);const i=Qv._svgFactory.createElement("path");a.append(i);const l=`path_p${this.pageIndex}_${n}`;i.setAttribute("id",l),i.setAttribute("d",t.toSVGPath()),i.setAttribute("vector-effect","non-scaling-stroke");let o;if(t.mustRemoveSelfIntersections){const u=Qv._svgFactory.createElement("mask");a.append(u),o=`mask_p${this.pageIndex}_${n}`,u.setAttribute("id",o),u.setAttribute("maskUnits","objectBoundingBox");const h=Qv._svgFactory.createElement("rect");u.append(h),h.setAttribute("width","1"),h.setAttribute("height","1"),h.setAttribute("fill","white");const m=Qv._svgFactory.createElement("use");u.append(m),m.setAttribute("href",`#${l}`),m.setAttribute("stroke","none"),m.setAttribute("fill","black"),m.setAttribute("fill-rule","nonzero"),m.classList.add("mask")}const c=Qv._svgFactory.createElement("use");r.append(c),c.setAttribute("href",`#${l}`),o&&c.setAttribute("mask",`url(#${o})`);const d=c.cloneNode();return r.append(d),c.classList.add("mainOutline"),d.classList.add("secondaryOutline"),ye(this,My).set(n,r),n}finalizeLine(t,n){const r=ye(this,hE).get(t);ye(this,hE).delete(t),this.updateBox(t,n.box),r.setAttribute("d",n.toSVGPath())}updateLine(t,n){ye(this,My).get(t).firstChild.firstChild.setAttribute("d",n.toSVGPath())}updatePath(t,n){ye(this,hE).get(t).setAttribute("d",n.toSVGPath())}updateBox(t,n){var r;ls(r=Qv,pae,DXe).call(r,ye(this,My).get(t),n)}show(t,n){ye(this,My).get(t).classList.toggle("hidden",!n)}rotate(t,n){ye(this,My).get(t).setAttribute("data-main-rotation",n)}changeColor(t,n){ye(this,My).get(t).setAttribute("fill",n)}changeOpacity(t,n){ye(this,My).get(t).setAttribute("fill-opacity",n)}addClass(t,n){ye(this,My).get(t).classList.add(n)}removeClass(t,n){ye(this,My).get(t).classList.remove(n)}getSVGRoot(t){return ye(this,My).get(t)}remove(t){ye(this,hE).delete(t),ye(this,t4)!==null&&(ye(this,My).get(t).remove(),ye(this,My).delete(t))}destroy(){Kt(this,t4,null);for(const t of ye(this,My).values())t.remove();ye(this,My).clear(),ye(this,hE).clear()}};t4=new WeakMap,fae=new WeakMap,My=new WeakMap,hE=new WeakMap,pae=new WeakSet,DXe=function(t,{x:n=0,y:r=0,width:a=1,height:i=1}={}){const{style:l}=t;l.top=`${100*r}%`,l.left=`${100*n}%`,l.width=`${100*a}%`,l.height=`${100*i}%`},TB=new WeakSet,FXe=function(t){var r;const n=Qv._svgFactory.create(1,1,!0);return ye(this,t4).append(n),n.setAttribute("aria-hidden",!0),ls(r=Qv,pae,DXe).call(r,n,t),n},Irs=function(t,n){const r=Qv._svgFactory.createElement("clipPath");t.append(r);const a=`clip_${n}`;r.setAttribute("id",a),r.setAttribute("clipPathUnits","objectBoundingBox");const i=Qv._svgFactory.createElement("use");return r.append(i),i.setAttribute("href",`#${n}`),i.classList.add("clip"),a},bs(Qv,pae);let RXe=Qv;ud.AbortException;ud.AnnotationEditorLayer;ud.AnnotationEditorParamsType;ud.AnnotationEditorType;ud.AnnotationEditorUIManager;ud.AnnotationLayer;ud.AnnotationMode;ud.ColorPicker;ud.DOMSVGFactory;ud.DrawLayer;ud.FeatureTest;var Wot=ud.GlobalWorkerOptions;ud.ImageKind;ud.InvalidPDFException;ud.MissingPDFException;ud.OPS;ud.OutputScale;ud.PDFDataRangeTransport;ud.PDFDateString;ud.PDFWorker;ud.PasswordResponses;ud.PermissionFlag;ud.PixelsPerInch;ud.RenderingCancelledException;ud.TextLayer;ud.UnexpectedResponseException;ud.Util;ud.VerbosityLevel;ud.XfaLayer;ud.build;ud.createValidAbsoluteUrl;ud.fetchData;var wPe=ud.getDocument;ud.getFilenameFromUrl;ud.getPdfFilenameFromUrl;ud.getXfaPageViewport;ud.isDataScheme;ud.isPdfFile;ud.noContextMenu;ud.normalizeUnicode;ud.setLayerDimensions;ud.shadow;ud.version;const Kot="/assets/pdf.worker.min-GB3t0DcA.mjs";Wot.workerSrc=Kot;const JZn=({blob:s,scale:t=1.5})=>{const n=j.useRef(null),[r,a]=j.useState(!1),[i,l]=j.useState(null);return j.useEffect(()=>{let o=!1;const c=n.current;return!s||!c?void 0:((async()=>{a(!0),l(null);try{const u=await s.arrayBuffer(),h=await wPe({data:u}).promise;if(o)return;c.innerHTML="";for(let m=1;m<=h.numPages;m+=1){const f=await h.getPage(m);if(o)return;const g=f.getViewport({scale:t}),x=document.createElement("canvas");x.width=Math.floor(g.width),x.height=Math.floor(g.height),x.className="mx-auto w-full max-w-[900px] rounded-md border border-border bg-white shadow-sm";const y=x.getContext("2d");y&&(c.appendChild(x),await f.render({canvasContext:y,viewport:g}).promise)}}catch(u){o||l((u==null?void 0:u.message)||"Could not render the preview")}finally{o||a(!1)}})(),()=>{o=!0})},[s,t]),e.jsxs("div",{className:"relative h-full overflow-y-auto bg-muted/40 p-4",children:[r&&e.jsx("div",{className:"absolute inset-0 z-10 flex items-center justify-center bg-background/70",children:e.jsx(kt,{className:"h-6 w-6 animate-spin text-muted-foreground"})}),i&&e.jsx("p",{className:"p-4 text-sm text-destructive",children:i}),e.jsx("div",{ref:n,className:"space-y-4"})]})};function v9({label:s,value:t,onChange:n,prefix:r="presentation",hint:a,urlPlaceholder:i="…or paste an image URL",round:l=!1,className:o}){const{user:c}=vs(),d=j.useRef(null),[u,h]=j.useState(!1),m=async f=>{if(!(!f||!c)){if(!f.type.startsWith("image/")){re.error("Please choose an image file");return}if(f.size>20*1024*1024){re.error("That photo is larger than 20 MB");return}h(!0);try{const g=await ZKn(c.id,f,r);n(g),re.success("Photo uploaded")}catch(g){re.error((g==null?void 0:g.message)||"Upload failed")}finally{h(!1),d.current&&(d.current.value="")}}};return e.jsxs("div",{className:Pt("space-y-2",o),children:[e.jsx(ee,{className:"text-xs",children:s}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:Pt("relative shrink-0 overflow-hidden border bg-muted",l?"h-16 w-16 rounded-full":"h-16 w-24 rounded-md"),children:t?e.jsx("img",{src:t,alt:s,className:"h-full w-full object-cover"}):e.jsx("div",{className:"flex h-full w-full items-center justify-center text-muted-foreground",children:e.jsx(Mc,{className:"h-5 w-5"})})}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("input",{ref:d,type:"file",accept:"image/*",className:"hidden",onChange:f=>{var g;return m((g=f.target.files)==null?void 0:g[0])}}),e.jsxs($,{type:"button",variant:"outline",size:"sm",className:"gap-2",disabled:u,onClick:()=>{var f;return(f=d.current)==null?void 0:f.click()},children:[u?e.jsx(kt,{className:"h-4 w-4 animate-spin"}):e.jsx(Av,{className:"h-4 w-4"}),t?"Replace photo":"Upload photo"]}),t&&e.jsxs($,{type:"button",variant:"ghost",size:"sm",className:"gap-1 text-muted-foreground",onClick:()=>n(null),children:[e.jsx(gr,{className:"h-4 w-4"})," Remove"]})]})]}),e.jsx(pe,{value:t||"",onChange:f=>n(f.target.value||null),placeholder:i}),a&&e.jsx("p",{className:"text-xs text-muted-foreground",children:a})]})}function eXn({value:s,onChange:t}){return e.jsxs(Ne,{children:[e.jsxs(Ct,{className:"pb-3",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Zn,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(At,{className:"text-base",children:"Co-listing agent"})]}),e.jsx(Sn,{checked:s.enabled,onCheckedChange:n=>t({enabled:n})})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Adds a second agent to the cover, the About page, and the closing contact card."})]}),s.enabled&&e.jsxs(Ie,{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Name"}),e.jsx(pe,{value:s.name,onChange:n=>t({name:n.target.value}),placeholder:"Jordan Ellis"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Title"}),e.jsx(pe,{value:s.title||"",onChange:n=>t({title:n.target.value}),placeholder:"Co-listing agent"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Phone"}),e.jsx(pe,{value:s.phone||"",onChange:n=>t({phone:n.target.value})})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Email"}),e.jsx(pe,{value:s.email||"",onChange:n=>t({email:n.target.value})})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Brokerage"}),e.jsx(pe,{value:s.brokerageName||"",onChange:n=>t({brokerageName:n.target.value})})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"License #"}),e.jsx(pe,{value:s.licenseNumber||"",onChange:n=>t({licenseNumber:n.target.value})})]})]}),e.jsx(v9,{label:"Headshot",value:s.headshotUrl,onChange:n=>t({headshotUrl:n||""}),prefix:"co-agent",round:!0}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Shared bio (optional)"}),e.jsx(Rs,{rows:4,value:s.bio||"",onChange:n=>t({bio:n.target.value}),placeholder:"Replaces the intro paragraph on the About page when both agents are shown."})]})]})]})}function tXn({value:s,onChange:t}){return e.jsxs(Ne,{children:[e.jsxs(Ct,{className:"pb-3",children:[e.jsx(At,{className:"text-base",children:"Presentation theme"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Themes restyle every page — paper, headline type, and palette. Signature follows your own brand colors."})]}),e.jsx(Ie,{className:"grid gap-2 sm:grid-cols-2",children:bZe.map(n=>{const r=n.id===s;return e.jsxs("button",{type:"button",onClick:()=>t(n.id),className:Pt("group relative overflow-hidden rounded-xl border p-3 text-left transition-all hover:shadow-sm",r?"border-primary ring-1 ring-primary":"border-border"),children:[e.jsx("div",{className:"flex h-10 w-full overflow-hidden rounded-md",children:n.swatch.map(a=>e.jsx("div",{className:"flex-1",style:{backgroundColor:a}},a))}),e.jsxs("div",{className:"mt-2 flex items-center justify-between gap-2",children:[e.jsx("span",{className:"text-sm font-medium",children:n.name}),r&&e.jsx(la,{className:"h-4 w-4 text-primary"})]}),e.jsx("p",{className:"mt-1 text-xs leading-snug text-muted-foreground",children:n.description})]},n.id)})})]})}const sXn={cover:[{key:"kicker",label:"Cover eyebrow"},{key:"body",label:"Cover paragraph",long:!0}],welcome:[{key:"kicker",label:"Eyebrow"},{key:"headline",label:"Headline",long:!0},{key:"subhead",label:"Subhead",long:!0}],agent:[{key:"kicker",label:"Eyebrow"},{key:"headline",label:"Headline",long:!0},{key:"subhead",label:"Subhead (defaults to your tagline)",long:!0}],overview:[{key:"kicker",label:"Eyebrow"},{key:"headline",label:"Headline",long:!0},{key:"subhead",label:"Subhead",long:!0}],closing:[{key:"kicker",label:"Eyebrow"},{key:"headline",label:"Headline",long:!0},{key:"body",label:"Closing paragraph",long:!0}]},nXn=["cover","welcome","agent","overview","closing"];function rXn({pages:s,onChange:t}){const n=new Set(s.hidden||[]),r=(i,l,o)=>{t({...s,copy:{...s.copy||{},[i]:{...(s.copy||{})[i]||{},[l]:o}}})},a=i=>{const l={...s.copy||{}};delete l[i],t({...s,copy:l})};return e.jsxs(Ne,{children:[e.jsxs(Ct,{className:"pb-3",children:[e.jsx(At,{className:"text-base",children:"Edit page wording"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Rewrite the headlines on the built-in pages. The preview updates as you type."})]}),e.jsx(Ie,{children:e.jsx(WB,{type:"multiple",className:"w-full",children:nXn.filter(i=>i==="cover"||!n.has(i)).map(i=>{const l=wts(s,i);return e.jsxs(p6,{value:i,children:[e.jsx(g6,{className:"text-sm",children:yHn[i]}),e.jsxs(x6,{className:"space-y-3 pt-1",children:[sXn[i].map(o=>e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{className:"text-xs",children:o.label}),o.long?e.jsx(Rs,{rows:2,value:l[o.key]||"",placeholder:aZe[i][o.key],onChange:c=>r(i,o.key,c.target.value)}):e.jsx(pe,{value:l[o.key]||"",placeholder:aZe[i][o.key],onChange:c=>r(i,o.key,c.target.value)})]},o.key)),e.jsxs($,{variant:"ghost",size:"sm",className:"gap-2",onClick:()=>a(i),children:[e.jsx(Ex,{className:"h-3.5 w-3.5"})," Reset to default wording"]})]})]},i)})})})]})}function aXn({pages:s,onChange:t}){const n=[...s].sort((o,c)=>o.order-c.order),r=(o,c)=>t(n.map(d=>d.id===o?{...d,...c}:d)),a=o=>t([...n,Not(o,n.length)]),i=o=>t(n.filter(c=>c.id!==o).map((c,d)=>({...c,order:d}))),l=(o,c)=>{const d=n.findIndex(m=>m.id===o),u=d+c;if(d<0||u<0||u>=n.length)return;const h=[...n];[h[d],h[u]]=[h[u],h[d]],t(h.map((m,f)=>({...m,order:f})))};return e.jsxs(Ne,{children:[e.jsxs(Ct,{className:"pb-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(m2,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(At,{className:"text-base",children:"Your own pages"})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Add About Us, testimonials, track record, or a statement page. Each one is styled to match the rest of the presentation and can be toggled on or off."})]}),e.jsxs(Ie,{className:"space-y-4",children:[e.jsx("div",{className:"grid gap-2 sm:grid-cols-2",children:h$e.map(o=>e.jsxs("button",{type:"button",onClick:()=>a(o.layout),className:"rounded-lg border p-3 text-left transition-colors hover:border-primary hover:bg-muted/50",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("span",{className:"text-sm font-medium",children:o.name}),e.jsx(dn,{className:"h-3.5 w-3.5 text-muted-foreground"})]}),e.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:o.description})]},o.layout))}),n.length>0&&e.jsxs(e.Fragment,{children:[e.jsx(Gc,{}),e.jsx(WB,{type:"multiple",className:"w-full",children:n.map((o,c)=>{var d,u,h;return e.jsxs(p6,{value:o.id,children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Sn,{checked:o.enabled,onCheckedChange:m=>r(o.id,{enabled:m})}),e.jsx(g6,{className:"flex-1 text-left text-sm",children:e.jsxs("span",{className:"flex items-center gap-2",children:[((d=o.headline)==null?void 0:d.trim())||((u=h$e.find(m=>m.layout===o.layout))==null?void 0:u.name),e.jsx(Be,{variant:"secondary",className:"text-[10px]",children:(h=h$e.find(m=>m.layout===o.layout))==null?void 0:h.name})]})}),e.jsx($,{variant:"ghost",size:"icon",className:"h-7 w-7",disabled:c===0,onClick:()=>l(o.id,-1),children:e.jsx(Zf,{className:"h-3.5 w-3.5"})}),e.jsx($,{variant:"ghost",size:"icon",className:"h-7 w-7",disabled:c===n.length-1,onClick:()=>l(o.id,1),children:e.jsx(Dg,{className:"h-3.5 w-3.5"})}),e.jsx($,{variant:"ghost",size:"icon",className:"h-7 w-7 text-destructive",onClick:()=>i(o.id),children:e.jsx(Wn,{className:"h-3.5 w-3.5"})})]}),e.jsxs(x6,{className:"space-y-3 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(ee,{className:"text-xs",children:"Placement"}),e.jsxs(ms,{value:o.placement,onValueChange:m=>r(o.id,{placement:m}),children:[e.jsx(us,{children:e.jsx(fs,{})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"after-agent",children:'After "About your agent"'}),e.jsx(Ge,{value:"end",children:"Before the closing page"})]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{className:"text-xs",children:"Style"}),e.jsxs("div",{className:"flex h-10 items-center gap-2 rounded-md border px-3",children:[e.jsx(Sn,{checked:o.dark,onCheckedChange:m=>r(o.id,{dark:m})}),e.jsx("span",{className:"text-sm",children:"Dark background"})]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{className:"text-xs",children:"Eyebrow"}),e.jsx(pe,{value:o.kicker,onChange:m=>r(o.id,{kicker:m.target.value})})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{className:"text-xs",children:"Headline"}),e.jsx(pe,{value:o.headline,onChange:m=>r(o.id,{headline:m.target.value})})]}),o.layout!=="statement"&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{className:"text-xs",children:"Subhead"}),e.jsx(pe,{value:o.subhead,onChange:m=>r(o.id,{subhead:m.target.value})})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{className:"text-xs",children:"Body copy"}),e.jsx(Rs,{rows:5,value:o.body,onChange:m=>r(o.id,{body:m.target.value}),placeholder:"Leave a blank line between paragraphs."})]}),(o.layout==="story"||o.layout==="checklist"||o.layout==="statement")&&e.jsx(v9,{label:"Photo (optional)",value:o.imageUrl,onChange:m=>r(o.id,{imageUrl:m}),prefix:"custom-page",urlPlaceholder:"…or paste an image URL",hint:"Defaults to the property photo when left empty."}),o.layout==="story"&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{className:"text-xs",children:"Photo side"}),e.jsxs(ms,{value:o.imageSide,onValueChange:m=>r(o.id,{imageSide:m}),children:[e.jsx(us,{children:e.jsx(fs,{})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"right",children:"Right"}),e.jsx(Ge,{value:"left",children:"Left"})]})]})]}),(o.layout==="story"||o.layout==="checklist")&&e.jsxs("div",{className:"space-y-2 rounded-lg border bg-muted/30 p-3",children:[e.jsx(ee,{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"List items"}),o.bullets.map((m,f)=>e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(pe,{value:m,onChange:g=>{const x=[...o.bullets];x[f]=g.target.value,r(o.id,{bullets:x})}}),e.jsx($,{variant:"ghost",size:"icon",className:"h-8 w-8 text-destructive",onClick:()=>r(o.id,{bullets:o.bullets.filter((g,x)=>x!==f)}),children:e.jsx(Wn,{className:"h-3.5 w-3.5"})})]},f)),e.jsxs($,{variant:"outline",size:"sm",className:"gap-2",disabled:o.bullets.length>=7,onClick:()=>r(o.id,{bullets:[...o.bullets,""]}),children:[e.jsx(dn,{className:"h-3.5 w-3.5"})," Add item"]})]}),o.layout==="testimonials"&&e.jsxs("div",{className:"space-y-3 rounded-lg border bg-muted/30 p-3",children:[e.jsx(ee,{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Testimonials (up to 4)"}),o.testimonials.map((m,f)=>e.jsxs("div",{className:"space-y-2 rounded-md border bg-background p-3",children:[e.jsx(Rs,{rows:3,value:m.quote,placeholder:"Client quote",onChange:g=>{const x=[...o.testimonials];x[f]={...m,quote:g.target.value},r(o.id,{testimonials:x})}}),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsx(pe,{value:m.name,placeholder:"Name",onChange:g=>{const x=[...o.testimonials];x[f]={...m,name:g.target.value},r(o.id,{testimonials:x})}}),e.jsx(pe,{value:m.detail,placeholder:"Neighborhood or year",onChange:g=>{const x=[...o.testimonials];x[f]={...m,detail:g.target.value},r(o.id,{testimonials:x})}})]}),e.jsxs($,{variant:"ghost",size:"sm",className:"gap-2 text-destructive",onClick:()=>r(o.id,{testimonials:o.testimonials.filter((g,x)=>x!==f)}),children:[e.jsx(Wn,{className:"h-3.5 w-3.5"})," Remove"]})]},f)),e.jsxs($,{variant:"outline",size:"sm",className:"gap-2",disabled:o.testimonials.length>=4,onClick:()=>r(o.id,{testimonials:[...o.testimonials,{quote:"",name:"",detail:""}]}),children:[e.jsx(dn,{className:"h-3.5 w-3.5"})," Add testimonial"]})]}),o.layout==="stats"&&e.jsxs("div",{className:"space-y-2 rounded-lg border bg-muted/30 p-3",children:[e.jsx(ee,{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Stats (up to 4)"}),o.stats.map((m,f)=>e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(pe,{className:"w-28",value:m.value,placeholder:"27",onChange:g=>{const x=[...o.stats];x[f]={...m,value:g.target.value},r(o.id,{stats:x})}}),e.jsx(pe,{value:m.label,placeholder:"Homes sold",onChange:g=>{const x=[...o.stats];x[f]={...m,label:g.target.value},r(o.id,{stats:x})}}),e.jsx($,{variant:"ghost",size:"icon",className:"h-8 w-8 text-destructive",onClick:()=>r(o.id,{stats:o.stats.filter((g,x)=>x!==f)}),children:e.jsx(Wn,{className:"h-3.5 w-3.5"})})]},f)),e.jsxs($,{variant:"outline",size:"sm",className:"gap-2",disabled:o.stats.length>=4,onClick:()=>r(o.id,{stats:[...o.stats,{value:"",label:""}]}),children:[e.jsx(dn,{className:"h-3.5 w-3.5"})," Add stat"]}),e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"Only use numbers you can back up — leave a stat blank to hide it."})]})]})]},o.id)})})]})]})]})}function iXn({open:s,onOpenChange:t,defaultName:n,saving:r,onSave:a}){const[i,l]=j.useState(""),[o,c]=j.useState("");return j.useEffect(()=>{s&&(l((n==null?void 0:n.trim())||"My listing presentation"),c(""))},[s,n]),e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Os,{className:"sm:max-w-md",children:[e.jsxs(Us,{children:[e.jsx(Bs,{children:"Save as a reusable template"}),e.jsx(Ir,{children:"Saves your branding, co-listing agent, theme, page wording, custom pages, and marketing plan. The property address and photo are not saved — you add those each time."})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Template name"}),e.jsx(pe,{value:i,onChange:d=>l(d.target.value),autoFocus:!0})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Notes (optional)"}),e.jsx(Rs,{rows:2,value:o,onChange:d=>c(d.target.value),placeholder:"Luxury version with co-listing agent and testimonials"})]})]}),e.jsxs(Ar,{children:[e.jsx($,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsxs($,{disabled:!i.trim()||r,onClick:async()=>{await a(i.trim(),o.trim()),t(!1)},className:"gap-2",children:[r&&e.jsx(kt,{className:"h-4 w-4 animate-spin"})," Save template"]})]})]})})}const N3t=["welcome","agent","overview","closing"],oXn=()=>{const{id:s}=Wi(),t=Qn(),{user:n}=vs(),{data:r}=A6e(),{data:a,isLoading:i,refetch:l}=gHn(s),{update:o}=_ts(),{save:c}=bts(),[d,u]=j.useState(null),[h,m]=j.useState(null),[f,g]=j.useState(lZe(null)),[x,y]=j.useState(jts),[v,b]=j.useState([]),[w,S]=j.useState(iZe),[C,E]=j.useState(oZe),[I,P]=j.useState(null),[R,D]=j.useState(null),[O,U]=j.useState(!1),[W,V]=j.useState(!1),[G,Y]=j.useState(null),[X,ae]=j.useState(!1),[ie,ne]=j.useState(!1),[te,J]=j.useState(!1),[ce,_e]=j.useState(!1),[he,ue]=j.useState(!0),[ve,Ee]=j.useState(!1),Se=j.useRef(null);j.useEffect(()=>{if(!a||d)return;u({title:a.title||"",addressLine1:a.property_address_line1||"",city:a.city||"",state:a.state||"",postalCode:a.postal_code||"",listPrice:a.list_price!=null?String(a.list_price):"",beds:a.beds!=null?String(a.beds):"",baths:a.baths!=null?String(a.baths):"",sqft:a.sqft!=null?String(a.sqft):""});const Xe=a.agent_snapshot;m({...r,...Xe||{}}),g(lZe(a.services)),y(Nts(a.co_agent)),b(Sts(a.custom_pages)),S(a.page_settings&&Object.keys(a.page_settings).length?a.page_settings:iZe),E(a.photo_focal||oZe),P(a.property_photo_path)},[a,r,d]),j.useEffect(()=>{let Xe=!1;return I?pPe(I).then(it=>{Xe||D(it)}):D(null),()=>{Xe=!0}},[I]);const Le=j.useMemo(()=>!a||!d?null:{...a,title:d.title,property_address_line1:d.addressLine1,city:d.city,state:d.state,postal_code:d.postalCode,list_price:d.listPrice?Number(d.listPrice):null,beds:d.beds?Number(d.beds):null,baths:d.baths?Number(d.baths):null,sqft:d.sqft?Number(d.sqft):null,agent_snapshot:h||{},co_agent:x,custom_pages:v,services:f,page_settings:w,photo_focal:C,property_photo_path:I},[a,d,h,x,v,f,w,C,I]),Fe=Xe=>u(it=>it&&{...it,...Xe}),ke=Xe=>m(it=>it&&{...it,...Xe}),Ve=Xe=>(w.hidden||[]).includes(Xe),je=(Xe,it)=>S(at=>{const Ke=new Set(at.hidden||[]);return it?Ke.delete(Xe):Ke.add(Xe),{...at,hidden:Array.from(Ke)}}),Ae=f.filter(Xe=>Xe.enabled),Ce=1+N3t.filter(Xe=>!Ve(Xe)&&Xe!=="overview").length+(Ve("overview")?0:1)+Ae.filter(Xe=>Xe.key!=="communication").length+v.filter(Xe=>Xe.enabled).length,qe=async(Xe=!1)=>{if(Le){_e(!0);try{await o.mutateAsync({id:Le.id,title:Le.title||"Untitled Presentation",property_address_line1:Le.property_address_line1,city:Le.city,state:Le.state,postal_code:Le.postal_code,list_price:Le.list_price,beds:Le.beds,baths:Le.baths,sqft:Le.sqft,agent_snapshot:Le.agent_snapshot,co_agent:Le.co_agent,custom_pages:Le.custom_pages,services:Le.services,page_settings:Le.page_settings,photo_focal:Le.photo_focal,property_photo_path:Le.property_photo_path}),Xe||re.success("Presentation saved")}finally{_e(!1)}}},ze=async Xe=>{if(!(!n||!s)){if(!Xe.type.startsWith("image/")){re.error("Please choose a JPG or PNG photo");return}if(Xe.size>25*1024*1024){re.error("That photo is larger than 25 MB");return}U(!0);try{const it=await YKn(n.id,s,Xe);P(it);const at=await pPe(it);D(at?`${at}${at.includes("?")?"&":"?"}v=${Date.now()}`:null),await o.mutateAsync({id:s,property_photo_path:it}),re.success("Photo uploaded")}catch(it){re.error((it==null?void 0:it.message)||"Upload failed")}finally{U(!1)}}},$e=async()=>{if(Le){ae(!0);try{const Xe=await kss(gPe(Le,r,R),Le.template_id,I);Y(Xe)}catch(Xe){re.error((Xe==null?void 0:Xe.message)||"Could not build the preview")}finally{ae(!1)}}};j.useEffect(()=>{if(!he||!Le)return;const Xe=setTimeout(()=>{$e()},900);return()=>clearTimeout(Xe)},[he,Le]);const ct=async()=>{if(!(!Le||!n)){if(!Le.property_photo_path){re.error("Add the primary exterior photo before generating the PDF");return}ne(!0);try{await qe(!0);const Xe=await Sss(gPe(Le,r,R),Le.template_id,"print",I);await Css(n.id,Le.id,Xe),await l(),re.success("Presentation downloaded")}catch(Xe){re.error((Xe==null?void 0:Xe.message)||"Could not build the PDF")}finally{ne(!1)}}};return i||!d||!a?e.jsx(Vs,{children:e.jsxs("div",{className:"space-y-4",children:[e.jsx(yn,{className:"h-10 w-64"}),e.jsx(yn,{className:"h-[60vh] w-full rounded-xl"})]})}):e.jsxs(Vs,{children:[e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx($,{variant:"ghost",size:"icon",onClick:()=>t("/apps/listing-presentation-studio"),children:e.jsx(qa,{className:"h-4 w-4"})}),e.jsxs("div",{children:[e.jsx(pe,{value:d.title,onChange:Xe=>Fe({title:Xe.target.value}),className:"h-9 border-none bg-transparent px-0 text-xl font-semibold shadow-none focus-visible:ring-0",placeholder:"Untitled Presentation"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[Ae.length," services selected · ",Ce," pages"]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs($,{variant:"outline",onClick:()=>qe(),disabled:ce,className:"gap-2",children:[ce?e.jsx(kt,{className:"h-4 w-4 animate-spin"}):e.jsx(tl,{className:"h-4 w-4"})," Save"]}),e.jsxs($,{variant:"outline",onClick:()=>Ee(!0),className:"gap-2",children:[e.jsx(qI,{className:"h-4 w-4"})," Save as template"]}),e.jsxs($,{variant:"outline",onClick:$e,disabled:X,className:"gap-2",children:[X?e.jsx(kt,{className:"h-4 w-4 animate-spin"}):e.jsx(Ca,{className:"h-4 w-4"})," Preview"]}),e.jsxs($,{variant:"outline",onClick:async()=>{await qe(!0),J(!0)},className:"gap-2",children:[e.jsx(mn,{className:"h-4 w-4"})," Email"]}),e.jsxs($,{onClick:ct,disabled:ie,className:"gap-2",children:[ie?e.jsx(kt,{className:"h-4 w-4 animate-spin"}):e.jsx(di,{className:"h-4 w-4"}),"Generate PDF"]})]})]}),e.jsxs("div",{className:"grid gap-6 lg:grid-cols-[minmax(0,440px)_minmax(0,1fr)]",children:[e.jsxs(ha,{defaultValue:"property",className:"space-y-4",children:[e.jsxs(ma,{className:"grid w-full grid-cols-4",children:[e.jsx(Zt,{value:"property",children:"Property"}),e.jsx(Zt,{value:"branding",children:"Branding"}),e.jsx(Zt,{value:"plan",children:"Plan"}),e.jsx(Zt,{value:"pages",children:"Pages"})]}),e.jsxs(Xt,{value:"property",className:"space-y-4",children:[e.jsxs(Ne,{children:[e.jsx(Ct,{className:"pb-3",children:e.jsx(At,{className:"text-base",children:"Property address"})}),e.jsxs(Ie,{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Street address"}),e.jsx(pe,{value:d.addressLine1,onChange:Xe=>Fe({addressLine1:Xe.target.value}),placeholder:"1408 Elmwood Drive"})]}),e.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[e.jsxs("div",{className:"col-span-2 space-y-1.5",children:[e.jsx(ee,{children:"City"}),e.jsx(pe,{value:d.city,onChange:Xe=>Fe({city:Xe.target.value})})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"State"}),e.jsx(pe,{value:d.state,onChange:Xe=>Fe({state:Xe.target.value})})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"ZIP"}),e.jsx(pe,{value:d.postalCode,onChange:Xe=>Fe({postalCode:Xe.target.value})})]}),e.jsx(Gc,{}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"List price (optional)"}),e.jsx(pe,{inputMode:"numeric",value:d.listPrice,onChange:Xe=>Fe({listPrice:Xe.target.value.replace(/[^0-9.]/g,"")}),placeholder:"649000"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Square feet"}),e.jsx(pe,{inputMode:"numeric",value:d.sqft,onChange:Xe=>Fe({sqft:Xe.target.value.replace(/[^0-9]/g,"")})})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Beds"}),e.jsx(pe,{inputMode:"numeric",value:d.beds,onChange:Xe=>Fe({beds:Xe.target.value.replace(/[^0-9.]/g,"")})})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Baths"}),e.jsx(pe,{inputMode:"numeric",value:d.baths,onChange:Xe=>Fe({baths:Xe.target.value.replace(/[^0-9.]/g,"")})})]})]})]})]}),e.jsxs(Ne,{children:[e.jsx(Ct,{className:"pb-3",children:e.jsxs(At,{className:"text-base",children:["Primary exterior photo ",e.jsx("span",{className:"text-destructive",children:"*"})]})}),e.jsxs(Ie,{className:"space-y-3",children:[e.jsx("div",{role:"button",tabIndex:0,onClick:()=>{var Xe;return(Xe=Se.current)==null?void 0:Xe.click()},onKeyDown:Xe=>{var it;return Xe.key==="Enter"&&((it=Se.current)==null?void 0:it.click())},onDragOver:Xe=>{Xe.preventDefault(),V(!0)},onDragLeave:()=>V(!1),onDrop:Xe=>{var at;Xe.preventDefault(),V(!1);const it=(at=Xe.dataTransfer.files)==null?void 0:at[0];it&&ze(it)},className:Pt("relative flex h-48 w-full cursor-pointer items-center justify-center overflow-hidden rounded-lg border border-dashed bg-muted/40 transition-colors hover:bg-muted",W&&"border-primary bg-primary/10"),children:R?e.jsx("img",{src:R,alt:"Property exterior",className:"h-full w-full object-cover",style:{objectPosition:`${C.x*100}% ${C.y*100}%`}}):e.jsxs("div",{className:"flex flex-col items-center gap-2 text-muted-foreground",children:[O?e.jsx(kt,{className:"h-6 w-6 animate-spin"}):e.jsx(Av,{className:"h-6 w-6"}),e.jsx("span",{className:"text-sm",children:"Drag & drop the front exterior photo"}),e.jsx("span",{className:"text-xs",children:"or click to browse · JPG or PNG · landscape works best"})]})}),e.jsx("input",{ref:Se,type:"file",accept:"image/*",className:"hidden",onChange:Xe=>{var at;const it=(at=Xe.target.files)==null?void 0:at[0];it&&ze(it),Xe.target.value=""}}),R&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-3 rounded-lg border bg-muted/30 p-3",children:[e.jsxs("div",{className:"flex items-center gap-2 text-xs font-medium text-muted-foreground",children:[e.jsx(WJ,{className:"h-3.5 w-3.5"})," Reposition crop"]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{className:"text-xs",children:"Horizontal"}),e.jsx(kx,{value:[C.x*100],min:0,max:100,step:1,onValueChange:([Xe])=>E(it=>({...it,x:Xe/100}))})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{className:"text-xs",children:"Vertical"}),e.jsx(kx,{value:[C.y*100],min:0,max:100,step:1,onValueChange:([Xe])=>E(it=>({...it,y:Xe/100}))})]})]}),e.jsxs($,{variant:"outline",size:"sm",className:"w-full gap-2",onClick:()=>{var Xe;return(Xe=Se.current)==null?void 0:Xe.click()},disabled:O,children:[e.jsx(ro,{className:"h-4 w-4"})," Replace photo"]})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"This photo anchors the cover and appears on a few key pages — photography, video, the property website, and the closing page."})]})]})]}),e.jsxs(Xt,{value:"branding",className:"space-y-4",children:[e.jsx(tXn,{value:w.theme||uKn,onChange:Xe=>S(it=>({...it,theme:Xe}))}),e.jsxs(Ne,{children:[e.jsx(Ct,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(At,{className:"text-base",children:"Your details"}),e.jsx(Be,{variant:"secondary",className:"text-[10px]",children:"Loaded from your LevelUp profile"})]})}),e.jsx(Ie,{className:"space-y-3",children:h&&e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Edits here apply to this presentation only — your LevelUp profile stays unchanged."}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Name"}),e.jsx(pe,{value:h.name,onChange:Xe=>ke({name:Xe.target.value})})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Tagline"}),e.jsx(pe,{value:h.tagline||"",onChange:Xe=>ke({tagline:Xe.target.value}),placeholder:"Helping families move with confidence"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Phone"}),e.jsx(pe,{value:h.phone||"",onChange:Xe=>ke({phone:Xe.target.value})})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Email"}),e.jsx(pe,{value:h.email||"",onChange:Xe=>ke({email:Xe.target.value})})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Website"}),e.jsx(pe,{value:h.website||"",onChange:Xe=>ke({website:Xe.target.value})})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Brokerage"}),e.jsx(pe,{value:h.brokerageName||"",onChange:Xe=>ke({brokerageName:Xe.target.value})})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"License #"}),e.jsx(pe,{value:h.licenseNumber||"",onChange:Xe=>ke({licenseNumber:Xe.target.value})})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"License state"}),e.jsx(pe,{value:h.licenseState||"",onChange:Xe=>ke({licenseState:Xe.target.value})})]})]}),e.jsx(Gc,{}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Primary color"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("input",{type:"color",value:h.brandColor,onChange:Xe=>ke({brandColor:Xe.target.value}),className:"h-9 w-12 cursor-pointer rounded border bg-transparent"}),e.jsx(pe,{value:h.brandColor,onChange:Xe=>ke({brandColor:Xe.target.value})})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Accent color"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("input",{type:"color",value:h.accentColor,onChange:Xe=>ke({accentColor:Xe.target.value}),className:"h-9 w-12 cursor-pointer rounded border bg-transparent"}),e.jsx(pe,{value:h.accentColor,onChange:Xe=>ke({accentColor:Xe.target.value})})]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Headshot URL"}),e.jsx(pe,{value:h.headshotUrl||"",onChange:Xe=>ke({headshotUrl:Xe.target.value}),placeholder:"Pulled from your profile photo"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Brokerage logo URL"}),e.jsx(pe,{value:h.brokerageLogoUrl||"",onChange:Xe=>ke({brokerageLogoUrl:Xe.target.value})})]}),r&&e.jsxs($,{variant:"outline",size:"sm",className:"w-full gap-2",onClick:()=>m({...r}),children:[e.jsx(ro,{className:"h-4 w-4"})," Reset to my LevelUp profile"]})]})})]}),e.jsx(eXn,{value:x,onChange:Xe=>y(it=>({...it,...Xe}))})]}),e.jsx(Xt,{value:"plan",className:"space-y-4",children:e.jsxs(Ne,{children:[e.jsxs(Ct,{className:"pb-3",children:[e.jsx(At,{className:"text-base",children:"Marketing plan"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Only the services you turn on appear in the PDF. Uncheck any line item you do not offer."})]}),e.jsx(Ie,{children:e.jsx(WB,{type:"multiple",className:"w-full",children:f.slice().sort((Xe,it)=>Xe.order-it.order).map(Xe=>{var it;return e.jsxs(p6,{value:Xe.key,children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Sn,{checked:Xe.enabled,onCheckedChange:at=>g(Ke=>Ke.map(nt=>nt.key===Xe.key?{...nt,enabled:at}:nt))}),e.jsx(g6,{className:"flex-1 text-left text-sm",children:Xe.title})]}),e.jsxs(x6,{className:"space-y-3 pt-2",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Headline"}),e.jsx(pe,{value:Xe.title,onChange:at=>g(Ke=>Ke.map(nt=>nt.key===Xe.key?{...nt,title:at.target.value}:nt))})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Description"}),e.jsx(Rs,{rows:4,value:Xe.body,onChange:at=>g(Ke=>Ke.map(nt=>nt.key===Xe.key?{...nt,body:at.target.value}:nt))})]}),!!((it=Xe.options)!=null&&it.length)&&e.jsxs("div",{className:"space-y-2 rounded-lg border bg-muted/30 p-3",children:[e.jsx(ee,{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Included in this page"}),Xe.options.map(at=>e.jsxs("label",{className:"flex items-start gap-2 text-sm",children:[e.jsx(ai,{className:"mt-0.5",checked:at.enabled,onCheckedChange:Ke=>g(nt=>nt.map(xt=>{var rt;return xt.key===Xe.key?{...xt,options:(rt=xt.options)==null?void 0:rt.map(Yt=>Yt.key===at.key?{...Yt,enabled:!!Ke}:Yt)}:xt}))}),e.jsx("span",{className:"leading-snug",children:at.label})]},at.key))]})]})]},Xe.key)})})})]})}),e.jsxs(Xt,{value:"pages",className:"space-y-4",children:[e.jsxs(Ne,{children:[e.jsxs(Ct,{className:"pb-3",children:[e.jsx(At,{className:"text-base",children:"Page visibility"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"The cover and every enabled service page always print. These supporting pages are optional."})]}),e.jsxs(Ie,{className:"space-y-3",children:[N3t.map(Xe=>e.jsxs("div",{className:"flex items-center justify-between rounded-lg border p-3",children:[e.jsx("span",{className:"text-sm",children:bHn[Xe]}),e.jsx(Sn,{checked:!Ve(Xe),onCheckedChange:it=>je(Xe,it)})]},Xe)),e.jsxs("div",{className:"rounded-lg border bg-muted/30 p-3 text-sm",children:[e.jsx("div",{className:"font-medium",children:"Page order"}),e.jsxs("ol",{className:"mt-2 space-y-1 text-xs text-muted-foreground",children:[e.jsx("li",{children:"01 · Cover"}),!Ve("welcome")&&e.jsx("li",{children:"Marketing commitment"}),!Ve("agent")&&e.jsx("li",{children:"About your agent"}),v.filter(Xe=>Xe.enabled&&Xe.placement!=="end").sort((Xe,it)=>Xe.order-it.order).map(Xe=>e.jsx("li",{children:Xe.headline||"Custom page"},Xe.id)),!Ve("overview")&&e.jsx("li",{children:"Marketing plan overview"}),Ae.filter(Xe=>Xe.key!=="communication").map(Xe=>e.jsx("li",{children:Xe.title},Xe.key)),v.filter(Xe=>Xe.enabled&&Xe.placement==="end").sort((Xe,it)=>Xe.order-it.order).map(Xe=>e.jsx("li",{children:Xe.headline||"Custom page"},Xe.id)),!Ve("closing")&&e.jsx("li",{children:"Communication & closing commitment"})]})]})]})]}),e.jsx(rXn,{pages:w,onChange:S}),e.jsxs(Ne,{children:[e.jsxs(Ct,{className:"pb-3",children:[e.jsx(At,{className:"text-base",children:"What they're saying"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Add a testimonial page and drop in up to six client quotes. It styles itself to your theme."})]}),e.jsx(Ie,{children:e.jsx($,{variant:"outline",size:"sm",className:"w-full",onClick:()=>b(Xe=>[...Xe,{...Not("testimonials",Xe.length),placement:"end"}]),children:`Add a "What they're saying" page`})})]}),e.jsx(aXn,{pages:v,onChange:b})]})]}),e.jsxs(Ne,{className:"min-h-[70vh] overflow-hidden",children:[e.jsxs(Ct,{className:"flex flex-row items-center justify-between space-y-0 pb-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(At,{className:"text-base",children:"Live preview"}),e.jsxs("label",{className:"flex items-center gap-1.5 text-xs text-muted-foreground",children:[e.jsx(Sn,{checked:he,onCheckedChange:ue}),"Auto-update"]})]}),e.jsxs($,{variant:"ghost",size:"sm",onClick:$e,disabled:X,className:"gap-2",children:[X?e.jsx(kt,{className:"h-4 w-4 animate-spin"}):e.jsx(ro,{className:"h-4 w-4"}),"Refresh"]})]}),e.jsx(Ie,{className:"h-[calc(70vh-60px)] p-0",children:G?e.jsx(JZn,{blob:G}):e.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-3 bg-muted/30 text-center",children:[e.jsx(Ca,{className:"h-8 w-8 text-muted-foreground"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Fill in the address, upload the photo, then generate the preview."}),e.jsxs($,{onClick:$e,disabled:X,className:"gap-2",children:[X?e.jsx(kt,{className:"h-4 w-4 animate-spin"}):e.jsx(Ca,{className:"h-4 w-4"}),"Generate preview"]})]})})]})]})]}),e.jsx(iXn,{open:ve,onOpenChange:Ee,defaultName:d.title,saving:c.isPending,onSave:async(Xe,it)=>{await c.mutateAsync({name:Xe,description:it||null,template_id:a.template_id,agent_snapshot:h||{},co_agent:x,custom_pages:v,services:f,page_settings:w})}}),e.jsx(Ess,{open:te,onOpenChange:J,row:Le,brand:r,photoUrl:R})]})};function lXn(s,t,n,r){const a=d=>d*Math.PI/180,l=a(n-s),o=a(r-t),c=Math.sin(l/2)**2+Math.cos(a(s))*Math.cos(a(n))*Math.sin(o/2)**2;return 2*3958.8*Math.asin(Math.sqrt(c))}const Lrs="popby_geocode_cache_v1";function cXn(){try{return JSON.parse(localStorage.getItem(Lrs)||"{}")}catch{return{}}}function dXn(s){try{localStorage.setItem(Lrs,JSON.stringify(s))}catch{}}function uXn({contacts:s,onLogPopby:t}){const[n,r]=j.useState(null),[a,i]=j.useState("idle"),[l,o]=j.useState(5),[c,d]=j.useState(""),[u,h]=j.useState(new Map),[m,f]=j.useState(!1);j.useEffect(()=>{(async()=>{const{data:b}=await q.from("settings").select("value").eq("key","mapbox_public_token").maybeSingle();b!=null&&b.value&&d(b.value)})()},[]);const g=j.useMemo(()=>s.filter(b=>b.isDue&&(b.address||b.city&&b.state||b.zip)),[s]),x=()=>{if(!("geolocation"in navigator)){i("unavailable");return}i("loading"),navigator.geolocation.getCurrentPosition(b=>{r({lat:b.coords.latitude,lng:b.coords.longitude}),i("ok")},()=>{i("denied")},{enableHighAccuracy:!0,timeout:1e4,maximumAge:6e4})};j.useEffect(()=>{if(!c||!n||g.length===0)return;let b=!1;const w=cXn(),S=new Map;g.forEach(E=>{const I=[E.address,E.city,E.state,E.zip].filter(Boolean).join("|").toLowerCase();w[I]&&S.set(E.id,w[I])}),h(new Map(S));const C=g.filter(E=>!([E.address,E.city,E.state,E.zip].filter(Boolean).join("|").toLowerCase()in w));if(C.length!==0)return f(!0),(async()=>{const E=[...C],I=async()=>{var P,R;for(;E.length&&!b;){const D=E.shift(),O=[D.address,D.city,D.state,D.zip].filter(Boolean),U=O.join("|").toLowerCase(),W=O.join(", ");try{const G=await(await fetch(`https://api.mapbox.com/geocoding/v5/mapbox.places/${encodeURIComponent(W)}.json?limit=1&access_token=${c}`)).json();if((R=(P=G==null?void 0:G.features)==null?void 0:P[0])!=null&&R.center){const[Y,X]=G.features[0].center;w[U]={lat:X,lng:Y},S.set(D.id,{lat:X,lng:Y})}else w[U]=null}catch{}}};await Promise.all([I(),I(),I(),I()]),b||(dXn(w),h(new Map(S)),f(!1))})(),()=>{b=!0}},[c,n,g]);const y=j.useMemo(()=>{if(!n)return[];const b=[];return g.forEach(w=>{const S=u.get(w.id);if(!S)return;const C=lXn(n.lat,n.lng,S.lat,S.lng);C<=l&&b.push({...w,distanceMiles:C,lat:S.lat,lng:S.lng})}),b.sort((w,S)=>w.distanceMiles-S.distanceMiles)},[n,g,u,l]),v=b=>{const S=/iPad|iPhone|iPod/.test(navigator.userAgent)?`https://maps.apple.com/?daddr=${b.lat},${b.lng}`:`https://www.google.com/maps/dir/?api=1&destination=${b.lat},${b.lng}`;window.open(S,"_blank","noopener")};return e.jsxs(Ne,{className:"border-primary/30 bg-gradient-to-br from-primary/5 to-transparent",children:[e.jsx(Ct,{className:"pb-3",children:e.jsxs("div",{className:"flex items-start justify-between gap-3 flex-wrap",children:[e.jsxs("div",{children:[e.jsxs(At,{className:"flex items-center gap-2 text-lg",children:[e.jsx(Hq,{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(ms,{value:String(l),onValueChange:b=>o(Number(b)),children:[e.jsx(us,{className:"w-[110px] h-9",children:e.jsx(fs,{})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"2",children:"2 miles"}),e.jsx(Ge,{value:"5",children:"5 miles"}),e.jsx(Ge,{value:"10",children:"10 miles"}),e.jsx(Ge,{value:"25",children:"25 miles"})]})]}),e.jsxs($,{size:"sm",variant:a==="ok"?"outline":"default",onClick:x,disabled:a==="loading",children:[a==="loading"?e.jsx(ro,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(Hq,{className:"h-4 w-4 mr-1"}),a==="ok"?"Refresh":"Use my location"]})]})]})}),e.jsxs(Ie,{className:"space-y-3",children:[a==="idle"&&e.jsxs("div",{className:"text-center py-6 text-sm text-muted-foreground",children:[e.jsx(ci,{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(ll,{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&&g.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&&g.length>0&&m&&y.length===0&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(yn,{className:"h-14 w-full"}),e.jsx(yn,{className:"h-14 w-full"}),e.jsx("p",{className:"text-xs text-muted-foreground text-center",children:"Locating contacts…"})]}),a==="ok"&&c&&!m&&y.length===0&&g.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."]}),y.length>0&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(Be,{variant:"secondary",className:"font-medium",children:[y.length," nearby"]}),m&&e.jsxs("span",{className:"text-xs text-muted-foreground flex items-center gap-1",children:[e.jsx(ro,{className:"h-3 w-3 animate-spin"})," still locating…"]})]}),e.jsx("div",{className:"space-y-2",children:y.map(b=>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:[b.first_name," ",b.last_name]}),e.jsx(Be,{variant:"outline",className:"text-xs",children:b.distanceMiles<1?`${(b.distanceMiles*5280).toFixed(0)} ft`:`${b.distanceMiles.toFixed(1)} mi`}),b.daysOverdue>0&&e.jsxs(Be,{variant:"destructive",className:"text-xs",children:[b.daysOverdue,"d overdue"]})]}),e.jsx("p",{className:"text-xs text-muted-foreground truncate mt-0.5",children:[b.address,b.city,b.state].filter(Boolean).join(", ")})]}),e.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[b.phone&&e.jsx($,{size:"icon",variant:"ghost",asChild:!0,className:"h-9 w-9",title:"Call",children:e.jsx("a",{href:`tel:${b.phone}`,children:e.jsx(Da,{className:"h-4 w-4"})})}),e.jsx($,{size:"icon",variant:"ghost",onClick:()=>v(b),className:"h-9 w-9",title:"Directions",children:e.jsx(KJ,{className:"h-4 w-4"})}),e.jsxs($,{size:"sm",onClick:()=>t(b),children:[e.jsx(ul,{className:"h-4 w-4 mr-1"}),"Log"]})]})]},b.id))})]})]})]})}const hXn="0dde5abb-0005-4c8c-a471-30d0cbc9e280",mXn=[{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 fXn(){const s=Qn(),t=OQt(),{data:n}=t9n(),{data:r}=Yw(),{data:a}=wit(),{data:i}=cDe(90),{data:l}=z_(),o=i9n(),c=r9n(),d=n9n(),u=a9n(),{data:h=[],isLoading:m}=tt({queryKey:["popby-templates"],queryFn:async()=>{const{data:G,error:Y}=await q.from("canva_templates").select(` *, category:template_categories(id, name), type:template_types(id, name) `).eq("category_id",hXn).order("publish_date",{ascending:!1});if(Y)throw Y;const{data:X}=await q.from("template_likes").select("template_id"),{data:ae}=await q.from("template_comments").select("template_id"),ie=new Map;X==null||X.forEach(te=>{ie.set(te.template_id,(ie.get(te.template_id)||0)+1)});const ne=new Map;return ae==null||ae.forEach(te=>{ne.set(te.template_id,(ne.get(te.template_id)||0)+1)}),(G||[]).map(te=>({...te,likesCount:ie.get(te.id)||0,commentsCount:ne.get(te.id)||0}))}}),f=G=>{const Y=l==null?void 0:l.find(X=>X.id===G);return Y?`${Y.first_name} ${Y.last_name||""}`.trim():"Unknown"},g=G=>{if(!G)return null;const Y=n==null?void 0:n.find(X=>X.id===G);return(Y==null?void 0:Y.name)||null},[x,y]=j.useState(null),[v,b]=j.useState(!1),[w,S]=j.useState(!1),[C,E]=j.useState(!1),[I,P]=j.useState({popby_item_id:"",notes:""}),[R,D]=j.useState({name:"",description:""}),O=async()=>{x&&(await c.mutateAsync({contact_id:x.id,popby_item_id:I.popby_item_id||void 0,notes:I.notes||void 0}),b(!1),y(null),P({popby_item_id:"",notes:""}))},U=async()=>{R.name.trim()&&(await d.mutateAsync({name:R.name.trim(),description:R.description.trim()||void 0}),E(!1),D({name:"",description:""}))},W=async(G,Y)=>{await u.mutateAsync({relationship_type_id:G,frequency_days:parseInt(Y)})},V=G=>{var X;const Y=a==null?void 0:a.find(ae=>ae.relationship_type_id===G);return((X=Y==null?void 0:Y.frequency_days)==null?void 0:X.toString())||"90"};return e.jsx(Vs,{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(Ne,{children:e.jsxs(Ie,{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(Ne,{children:e.jsxs(Ie,{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(Ne,{children:e.jsxs(Ie,{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($,{onClick:()=>s("/mission-control/popbys/map"),children:[e.jsx(ci,{className:"h-4 w-4 mr-2"}),"View Map"]}),e.jsxs($,{variant:"outline",onClick:()=>S(!0),children:[e.jsx(Sd,{className:"h-4 w-4 mr-2"}),"Frequency Settings"]}),e.jsxs($,{variant:"outline",onClick:()=>E(!0),children:[e.jsx(dn,{className:"h-4 w-4 mr-2"}),"Add Popby Idea"]})]}),e.jsxs(ha,{defaultValue:"due",children:[e.jsxs(ma,{children:[e.jsx(Zt,{value:"due",children:"Due for Popby"}),e.jsx(Zt,{value:"activity",children:"Recent Activity"}),e.jsx(Zt,{value:"library",children:"Popby Library"}),e.jsx(Zt,{value:"templates",children:"Popby Templates"})]}),e.jsxs(Xt,{value:"due",className:"space-y-4 mt-4",children:[e.jsx(uXn,{contacts:t||[],onLogPopby:G=>{y(G),b(!0)}}),!t||t.length===0?e.jsx(Ne,{children:e.jsxs(Ie,{className:"p-8 text-center text-muted-foreground",children:[e.jsx(ul,{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(G=>e.jsx(Ne,{className:"hover:shadow-md transition-shadow",children:e.jsx(Ie,{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:[G.first_name," ",G.last_name]}),G.daysOverdue>0&&e.jsxs(Be,{variant:"destructive",className:"text-xs",children:[G.daysOverdue,"+ days overdue"]}),G.daysSinceLastPopby===null&&e.jsx(Be,{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:[oX(G).hasAddress&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(ci,{className:"h-3 w-3"}),oX(G).city||oX(G).line,oX(G).isSecondary&&e.jsxs("span",{className:"text-xs",children:["(",oX(G).label,")"]})]}),G.tags&&G.tags.length>0&&e.jsx("span",{children:G.tags.map(Y=>{var X;return(X=Y.relationship_type)==null?void 0:X.name}).join(", ")})]}),G.lastPopby&&e.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:["Last popby: ",en(new Date(G.lastPopby),"MMM d, yyyy")]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[G.phone&&e.jsx($,{size:"sm",variant:"ghost",asChild:!0,children:e.jsx("a",{href:`tel:${G.phone}`,children:e.jsx(Da,{className:"h-4 w-4"})})}),e.jsxs($,{size:"sm",onClick:()=>{y(G),b(!0)},children:[e.jsx(Nc,{className:"h-4 w-4 mr-1"}),"Log Popby"]})]})]})})},G.id))})]}),e.jsx(Xt,{value:"activity",className:"space-y-4 mt-4",children:!i||i.length===0?e.jsx(Ne,{children:e.jsxs(Ie,{className:"p-8 text-center text-muted-foreground",children:[e.jsx(da,{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(Ne,{children:[e.jsx(Ct,{children:e.jsx(At,{className:"text-lg",children:"Recent Popby Log"})}),e.jsx(Ie,{className:"space-y-3",children:i.map(G=>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(ul,{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:f(G.contact_id)}),g(G.popby_item_id)&&e.jsx(Be,{variant:"secondary",className:"text-xs",children:g(G.popby_item_id)})]}),e.jsx("div",{className:"text-sm text-muted-foreground",children:en(new Date(G.completed_at),"MMM d, yyyy h:mm a")}),G.notes&&e.jsx("p",{className:"text-sm text-muted-foreground mt-1 line-clamp-2",children:G.notes})]})]},G.id))})]})}),e.jsx(Xt,{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:[n==null?void 0:n.map(G=>e.jsx(Ne,{children:e.jsx(Ie,{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(ul,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{className:"flex-1",children:[e.jsx("h3",{className:"font-medium",children:G.name}),G.description&&e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:G.description}),!G.owner_user_id&&e.jsx(Be,{variant:"secondary",className:"mt-2 text-xs",children:"Shared"})]})]})})},G.id)),e.jsx(Ne,{className:"border-dashed cursor-pointer hover:bg-muted/50 transition-colors",onClick:()=>E(!0),children:e.jsx(Ie,{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(dn,{className:"h-8 w-8 mx-auto mb-2"}),e.jsx("p",{children:"Add New Popby Idea"})]})})})]})}),e.jsxs(Xt,{value:"templates",className:"space-y-4 mt-4",children:[e.jsxs("div",{className:"text-sm text-muted-foreground",children:[h.length," template",h.length!==1?"s":""," found"]}),m&&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((G,Y)=>e.jsx(Ne,{children:e.jsxs(Ie,{className:"p-4",children:[e.jsx(yn,{className:"aspect-[3/2] w-full rounded-lg mb-4"}),e.jsx(yn,{className:"h-5 w-3/4 mb-2"}),e.jsx(yn,{className:"h-4 w-full mb-4"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(yn,{className:"h-5 w-16"}),e.jsx(yn,{className:"h-5 w-20"})]})]})},Y))}),!m&&h.length===0&&e.jsx(Ne,{children:e.jsxs(Ie,{className:"p-8 text-center text-muted-foreground",children:[e.jsx(vm,{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."})]})}),!m&&h.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:h.map(G=>e.jsxs(Ne,{className:"group overflow-hidden hover:shadow-lg transition-all duration-200 cursor-pointer",onClick:()=>s(`/templates/${G.id}`),children:[e.jsx("div",{className:"relative overflow-hidden bg-muted aspect-[3/2]",children:G.preview_image_url?e.jsx("img",{src:G.preview_image_url,alt:G.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(Ie,{className:"p-4 flex flex-col",children:[e.jsx("h3",{className:"font-semibold text-foreground line-clamp-1 mb-1",children:G.name}),G.description&&e.jsx("p",{className:"text-sm text-muted-foreground line-clamp-2 mb-3 flex-1",children:Vte(G.description)}),e.jsx("div",{className:"flex flex-wrap gap-2 mb-3",children:e.jsx(Be,{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(Vy,{className:"h-3.5 w-3.5"}),G.likesCount]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Th,{className:"h-3.5 w-3.5"}),G.commentsCount]})]}),e.jsxs($,{size:"sm",className:"w-full gap-2",onClick:Y=>{Y.stopPropagation(),s(`/templates/${G.id}`)},children:[e.jsx(kr,{className:"h-4 w-4"}),"View Template"]})]})]},G.id))})]})]}),e.jsx(zs,{open:v,onOpenChange:b,children:e.jsxs(Os,{children:[e.jsx(Us,{children:e.jsxs(Bs,{children:["Log Popby for ",x==null?void 0:x.first_name," ",x==null?void 0:x.last_name]})}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Popby Item (optional)"}),e.jsxs(ms,{value:I.popby_item_id,onValueChange:G=>P(Y=>({...Y,popby_item_id:G})),children:[e.jsx(us,{children:e.jsx(fs,{placeholder:"Select a popby item..."})}),e.jsx(hs,{children:n==null?void 0:n.map(G=>e.jsx(Ge,{value:G.id,children:G.name},G.id))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Notes (optional)"}),e.jsx(Rs,{placeholder:"Any notes about this popby...",value:I.notes,onChange:G=>P(Y=>({...Y,notes:G.target.value}))})]})]}),e.jsxs(Ar,{children:[e.jsx($,{variant:"outline",onClick:()=>b(!1),children:"Cancel"}),e.jsx($,{onClick:O,disabled:c.isPending,children:"Log Popby"})]})]})}),e.jsx(zs,{open:w,onOpenChange:S,children:e.jsxs(Os,{className:"max-w-md",children:[e.jsx(Us,{children:e.jsx(Bs,{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."}),r==null?void 0:r.map(G=>e.jsxs("div",{className:"flex items-center justify-between gap-4",children:[e.jsx(ee,{className:"font-medium",children:G.name}),e.jsxs(ms,{value:V(G.id),onValueChange:Y=>W(G.id,Y),children:[e.jsx(us,{className:"w-[180px]",children:e.jsx(fs,{})}),e.jsx(hs,{children:mXn.map(Y=>e.jsx(Ge,{value:Y.value,children:Y.label},Y.value))})]})]},G.id))]}),e.jsx(Ar,{children:e.jsx($,{onClick:()=>S(!1),children:"Done"})})]})}),e.jsx(zs,{open:C,onOpenChange:E,children:e.jsxs(Os,{children:[e.jsx(Us,{children:e.jsx(Bs,{children:"Add Popby Idea"})}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Name *"}),e.jsx(pe,{placeholder:"e.g., Homemade cookies",value:R.name,onChange:G=>D(Y=>({...Y,name:G.target.value}))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Description"}),e.jsx(Rs,{placeholder:"Optional description...",value:R.description,onChange:G=>D(Y=>({...Y,description:G.target.value}))})]})]}),e.jsxs(Ar,{children:[e.jsx($,{variant:"outline",onClick:()=>E(!1),children:"Cancel"}),e.jsx($,{onClick:U,disabled:!R.name.trim()||d.isPending,children:"Add Item"})]})]})})]})})}const pXn=H2({property_address:vl().min(1,"Property address is required"),city:vl().optional(),state:vl().optional(),zip:vl().optional(),transaction_type:btt(["buyer","seller"]),close_date:vl().min(1,"Close date is required"),sale_price:vee().min(0,"Sale price must be positive"),commission_amount:vee().optional(),lead_source_id:vl().optional(),client_type_id:vl().optional(),contact_id:vl().optional(),notes:vl().optional(),is_win:HTs()});function Rrs({open:s,onOpenChange:t,transaction:n}){const[r,a]=j.useState(!1),[i,l]=j.useState(""),[o,c]=j.useState(!1),[d,u]=j.useState(""),h=T6e(),m=WWs(),{data:f}=HB(),{data:g}=Yw(),{data:x}=z_(),y=j6e(),v=fnt(),{data:b}=M6e(),w=(b==null?void 0:b.show_commission)??!0,S=NLe({resolver:kLe(pXn),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}});j.useEffect(()=>{n?S.reset({property_address:n.property_address,city:n.city||"",state:n.state||"",zip:n.zip||"",transaction_type:n.transaction_type,close_date:n.close_date,sale_price:Number(n.sale_price),commission_amount:n.commission_amount?Number(n.commission_amount):void 0,lead_source_id:n.lead_source_id||void 0,client_type_id:n.client_type_id||void 0,contact_id:n.contact_id||void 0,notes:n.notes||"",is_win:n.is_win}):S.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})},[n,S]);const C=async R=>{const D={property_address:R.property_address,transaction_type:R.transaction_type,close_date:R.close_date,sale_price:R.sale_price,is_win:R.is_win,commission_amount:R.commission_amount||null,lead_source_id:R.lead_source_id||null,client_type_id:R.client_type_id||null,contact_id:R.contact_id||null,city:R.city||null,state:R.state||null,zip:R.zip||null,notes:R.notes||null};n?await m.mutateAsync({id:n.id,...D}):await h.mutateAsync(D),t(!1)},E=async()=>{if(!i.trim())return;const[R,...D]=i.trim().split(" "),O=D.join(" ")||null,U=await y.mutateAsync({first_name:R,last_name:O,tagIds:[]});U&&(S.setValue("contact_id",U.id),l(""),c(!1),a(!1))},I=async()=>{if(!d.trim())return;const R=await v.mutateAsync(d.trim());R&&(S.setValue("lead_source_id",R.id),u(""))},P=x==null?void 0:x.find(R=>R.id===S.watch("contact_id"));return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Os,{className:"max-w-lg max-h-[90vh]",children:[e.jsx(Us,{children:e.jsx(Bs,{children:n?"Edit Transaction":"Add Transaction"})}),e.jsx(uo,{className:"max-h-[70vh] pr-4",children:e.jsx(ELe,{...S,children:e.jsxs("form",{onSubmit:S.handleSubmit(C),className:"space-y-4",children:[e.jsx(jg,{control:S.control,name:"property_address",render:({field:R})=>e.jsxs(Up,{children:[e.jsx(qp,{children:"Property Address *"}),e.jsx(Vp,{children:e.jsx(pe,{placeholder:"123 Main St",...R})}),e.jsx(y_,{})]})}),e.jsxs("div",{className:"grid grid-cols-3 gap-2",children:[e.jsx(jg,{control:S.control,name:"city",render:({field:R})=>e.jsxs(Up,{children:[e.jsx(qp,{children:"City"}),e.jsx(Vp,{children:e.jsx(pe,{placeholder:"City",...R})})]})}),e.jsx(jg,{control:S.control,name:"state",render:({field:R})=>e.jsxs(Up,{children:[e.jsx(qp,{children:"State"}),e.jsx(Vp,{children:e.jsx(pe,{placeholder:"TX",...R})})]})}),e.jsx(jg,{control:S.control,name:"zip",render:({field:R})=>e.jsxs(Up,{children:[e.jsx(qp,{children:"Zip"}),e.jsx(Vp,{children:e.jsx(pe,{placeholder:"75001",...R})})]})})]}),e.jsx(jg,{control:S.control,name:"transaction_type",render:({field:R})=>e.jsxs(Up,{children:[e.jsx(qp,{children:"Transaction Type *"}),e.jsxs(ms,{onValueChange:R.onChange,value:R.value,children:[e.jsx(Vp,{children:e.jsx(us,{children:e.jsx(fs,{placeholder:"Select type"})})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"buyer",children:"Buyer"}),e.jsx(Ge,{value:"seller",children:"Seller"})]})]}),e.jsx(y_,{})]})}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsx(jg,{control:S.control,name:"close_date",render:({field:R})=>e.jsxs(Up,{children:[e.jsx(qp,{children:"Close Date *"}),e.jsx(Vp,{children:e.jsx(pe,{type:"date",...R})}),e.jsx(y_,{})]})}),e.jsx(jg,{control:S.control,name:"sale_price",render:({field:R})=>e.jsxs(Up,{children:[e.jsx(qp,{children:"Sale Price *"}),e.jsx(Vp,{children:e.jsx(pe,{type:"number",placeholder:"0",...R,onChange:D=>R.onChange(Number(D.target.value))})}),e.jsx(y_,{})]})})]}),w&&e.jsx(jg,{control:S.control,name:"commission_amount",render:({field:R})=>e.jsxs(Up,{children:[e.jsx(qp,{children:"Commission"}),e.jsx(Vp,{children:e.jsx(pe,{type:"number",placeholder:"0",...R,value:R.value??"",onChange:D=>R.onChange(D.target.value?Number(D.target.value):void 0)})})]})}),e.jsx(jg,{control:S.control,name:"lead_source_id",render:({field:R})=>e.jsxs(Up,{children:[e.jsx(qp,{children:"Lead Source"}),e.jsxs(ms,{onValueChange:R.onChange,value:R.value||"",children:[e.jsx(Vp,{children:e.jsx(us,{children:e.jsx(fs,{placeholder:"Select source"})})}),e.jsx(hs,{children:f==null?void 0:f.map(D=>e.jsx(Ge,{value:D.id,children:D.name},D.id))})]})]})}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(pe,{placeholder:"Add custom source...",value:d,onChange:R=>u(R.target.value),className:"flex-1"}),e.jsx($,{type:"button",variant:"outline",size:"icon",onClick:I,disabled:!d.trim(),children:e.jsx(dn,{className:"h-4 w-4"})})]}),e.jsx(jg,{control:S.control,name:"client_type_id",render:({field:R})=>e.jsxs(Up,{children:[e.jsx(qp,{children:"Client Type"}),e.jsxs(ms,{onValueChange:R.onChange,value:R.value||"",children:[e.jsx(Vp,{children:e.jsx(us,{children:e.jsx(fs,{placeholder:"Select client type"})})}),e.jsx(hs,{children:g==null?void 0:g.map(D=>e.jsx(Ge,{value:D.id,children:D.name},D.id))})]})]})}),e.jsx(jg,{control:S.control,name:"contact_id",render:({field:R})=>e.jsxs(Up,{children:[e.jsx(qp,{children:"Client Contact"}),e.jsxs(Yd,{open:r,onOpenChange:a,children:[e.jsx(Zd,{asChild:!0,children:e.jsx(Vp,{children:e.jsxs($,{variant:"outline",role:"combobox",className:Pt("w-full justify-between",!R.value&&"text-muted-foreground"),children:[P?`${P.first_name} ${P.last_name||""}`.trim():"Select contact",e.jsx(Pw,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})})}),e.jsxs(Bd,{className:"w-full p-0",align:"start",children:[e.jsxs(P2,{children:[e.jsx(I2,{placeholder:"Search contacts..."}),e.jsxs(L2,{children:[e.jsx(R2,{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($,{variant:"outline",size:"sm",className:"w-full",onClick:()=>c(!0),children:[e.jsx(dn,{className:"h-4 w-4 mr-2"}),"Add New Contact"]})]})}),e.jsx(Uw,{children:x==null?void 0:x.map(D=>e.jsxs(g1,{value:`${D.first_name} ${D.last_name||""}`,onSelect:()=>{R.onChange(D.id),a(!1)},children:[e.jsx(la,{className:Pt("mr-2 h-4 w-4",D.id===R.value?"opacity-100":"opacity-0")}),D.first_name," ",D.last_name||""]},D.id))})]})]}),o&&e.jsxs("div",{className:"p-2 border-t space-y-2",children:[e.jsx(pe,{placeholder:"Enter contact name...",value:i,onChange:D=>l(D.target.value)}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx($,{size:"sm",onClick:E,disabled:!i.trim()||y.isPending,children:"Add Contact"}),e.jsx($,{size:"sm",variant:"outline",onClick:()=>{c(!1),l("")},children:"Cancel"})]})]})]})]})]})}),e.jsx(jg,{control:S.control,name:"notes",render:({field:R})=>e.jsxs(Up,{children:[e.jsx(qp,{children:"Notes"}),e.jsx(Vp,{children:e.jsx(Rs,{placeholder:"Any notes about this transaction...",...R})})]})}),e.jsx(jg,{control:S.control,name:"is_win",render:({field:R})=>e.jsxs(Up,{className:"flex items-center justify-between rounded-lg border p-3",children:[e.jsxs("div",{className:"space-y-0.5",children:[e.jsx(qp,{children:"Mark as Win 🏆"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Highlight this as a notable success"})]}),e.jsx(Vp,{children:e.jsx(Sn,{checked:R.value,onCheckedChange:R.onChange})})]})}),e.jsxs("div",{className:"flex justify-end gap-2 pt-4",children:[e.jsx($,{type:"button",variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsxs($,{type:"submit",disabled:h.isPending||m.isPending,children:[n?"Update":"Add"," Transaction"]})]})]})})})]})})}function Yot({transactions:s,showCommission:t,isLoading:n,agentNameMap:r,readOnly:a}){const[i,l]=j.useState(null),[o,c]=j.useState(null),[d,u]=j.useState(""),[h,m]=j.useState("all"),[f,g]=j.useState("all"),[x,y]=j.useState("all"),[v,b]=j.useState(!1),w=KWs(),S=T6e(),{data:C}=HB(),{data:E}=Yw(),I=$K(),P=O=>{const{id:U,created_at:W,updated_at:V,lead_source:G,client_type:Y,contact:X,...ae}=O;S.mutate(ae)},R=()=>{o&&(w.mutate(o),c(null))},D=s.filter(O=>{var X,ae,ie,ne;const U=d===""||O.property_address.toLowerCase().includes(d.toLowerCase())||((ae=(X=O.contact)==null?void 0:X.first_name)==null?void 0:ae.toLowerCase().includes(d.toLowerCase()))||((ne=(ie=O.contact)==null?void 0:ie.last_name)==null?void 0:ne.toLowerCase().includes(d.toLowerCase())),W=h==="all"||O.transaction_type===h,V=f==="all"||O.lead_source_id===f,G=x==="all"||O.client_type_id===x,Y=!v||O.is_win;return U&&W&&V&&G&&Y});return n?e.jsx(Ne,{children:e.jsx(Ie,{className:"p-6 space-y-4",children:[1,2,3].map(O=>e.jsx(yn,{className:"h-16 w-full"},O))})}):e.jsxs(e.Fragment,{children:[e.jsxs(Ne,{children:[e.jsx(Ct,{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(At,{children:["Transactions (",D.length,")"]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs("div",{className:"relative",children:[e.jsx(Kr,{className:"absolute left-2.5 top-2.5 h-4 w-4 text-muted-foreground"}),e.jsx(pe,{placeholder:"Search...",value:d,onChange:O=>u(O.target.value),className:"pl-8 w-[150px]"})]}),e.jsxs(ms,{value:h,onValueChange:m,children:[e.jsx(us,{className:"w-[100px]",children:e.jsx(fs,{placeholder:"Type"})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"all",children:"All Types"}),e.jsx(Ge,{value:"buyer",children:"Buyer"}),e.jsx(Ge,{value:"seller",children:"Seller"})]})]}),e.jsxs(ms,{value:f,onValueChange:g,children:[e.jsx(us,{className:"w-[130px]",children:e.jsx(fs,{placeholder:"Lead Source"})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"all",children:"All Sources"}),C==null?void 0:C.map(O=>e.jsx(Ge,{value:O.id,children:O.name},O.id))]})]}),e.jsxs($,{variant:v?"default":"outline",size:"sm",onClick:()=>b(!v),children:[e.jsx(Rm,{className:"h-4 w-4 mr-1"}),"Wins"]})]})]})}),e.jsx(Ie,{children:D.length===0?e.jsx("p",{className:"text-center text-muted-foreground py-8",children:"No transactions found"}):I?e.jsx("div",{className:"space-y-3",children:D.map(O=>e.jsxs(Ne,{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:O.property_address}),O.is_win&&e.jsx(Rm,{className:"h-4 w-4 text-yellow-500 flex-shrink-0"})]}),e.jsxs("div",{className:"text-sm text-muted-foreground",children:[O.city,O.state?`, ${O.state}`:""]})]}),e.jsx(Be,{variant:O.transaction_type==="buyer"?"default":"secondary",children:O.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: "}),Ngt(O.close_date)]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Price: "}),Qm(O.sale_price)]}),t&&O.commission_amount&&e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Commission: "}),Qm(O.commission_amount)]}),O.lead_source&&e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Source: "}),O.lead_source.name]}),O.contact&&e.jsxs("div",{className:"col-span-2",children:[e.jsx("span",{className:"text-muted-foreground",children:"Client: "}),O.contact.first_name," ",O.contact.last_name]}),r&&e.jsxs("div",{className:"col-span-2",children:[e.jsx("span",{className:"text-muted-foreground",children:"Agent: "}),r[O.owner_user_id]||"Unknown"]})]}),!a&&e.jsxs("div",{className:"flex justify-end gap-2 mt-3 pt-3 border-t",children:[e.jsx($,{variant:"ghost",size:"sm",onClick:()=>l(O),children:e.jsx(_p,{className:"h-4 w-4"})}),e.jsx($,{variant:"ghost",size:"sm",onClick:()=>P(O),children:e.jsx(Ha,{className:"h-4 w-4"})}),e.jsx($,{variant:"ghost",size:"sm",onClick:()=>c(O.id),children:e.jsx(Wn,{className:"h-4 w-4 text-destructive"})})]})]},O.id))}):e.jsx("div",{className:"overflow-x-auto",children:e.jsxs(mi,{children:[e.jsx(fi,{children:e.jsxs(En,{children:[r&&e.jsx(Dt,{children:"Agent"}),e.jsx(Dt,{children:"Property"}),e.jsx(Dt,{children:"Type"}),e.jsx(Dt,{children:"Close Date"}),e.jsx(Dt,{children:"Sale Price"}),t&&e.jsx(Dt,{children:"Commission"}),e.jsx(Dt,{children:"Lead Source"}),e.jsx(Dt,{children:"Client"}),!a&&e.jsx(Dt,{className:"w-[50px]"})]})}),e.jsx(pi,{children:D.map(O=>{var U;return e.jsxs(En,{children:[r&&e.jsx(wt,{className:"font-medium text-sm",children:r[O.owner_user_id]||"Unknown"}),e.jsx(wt,{children:e.jsxs("div",{className:"flex items-center gap-2",children:[O.is_win&&e.jsx(Rm,{className:"h-4 w-4 text-yellow-500"}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:O.property_address}),e.jsxs("div",{className:"text-sm text-muted-foreground",children:[O.city,O.state?`, ${O.state}`:""]})]})]})}),e.jsx(wt,{children:e.jsx(Be,{variant:O.transaction_type==="buyer"?"default":"secondary",children:O.transaction_type})}),e.jsx(wt,{children:Ngt(O.close_date)}),e.jsx(wt,{children:Qm(O.sale_price)}),t&&e.jsx(wt,{children:O.commission_amount?Qm(O.commission_amount):"-"}),e.jsx(wt,{children:((U=O.lead_source)==null?void 0:U.name)||"-"}),e.jsx(wt,{children:O.contact?`${O.contact.first_name} ${O.contact.last_name||""}`.trim():"-"}),!a&&e.jsx(wt,{children:e.jsxs(Uu,{children:[e.jsx(qu,{asChild:!0,children:e.jsx($,{variant:"ghost",size:"icon",children:e.jsx(ty,{className:"h-4 w-4"})})}),e.jsxs(Eu,{align:"end",children:[e.jsxs(ja,{onClick:()=>l(O),children:[e.jsx(_p,{className:"h-4 w-4 mr-2"}),"Edit"]}),e.jsxs(ja,{onClick:()=>P(O),children:[e.jsx(Ha,{className:"h-4 w-4 mr-2"}),"Duplicate"]}),e.jsxs(ja,{onClick:()=>c(O.id),className:"text-destructive",children:[e.jsx(Wn,{className:"h-4 w-4 mr-2"}),"Delete"]})]})]})})]},O.id)})})]})})})]}),e.jsx(Rrs,{open:!!i,onOpenChange:O=>!O&&l(null),transaction:i||void 0}),e.jsx(kc,{open:!!o,onOpenChange:O=>!O&&c(null),children:e.jsxs(cc,{children:[e.jsxs(dc,{children:[e.jsx(hc,{children:"Delete Transaction?"}),e.jsx(mc,{children:"This action cannot be undone. This will permanently delete this transaction."})]}),e.jsxs(uc,{children:[e.jsx(fc,{children:"Cancel"}),e.jsx(tc,{onClick:R,className:"bg-destructive text-destructive-foreground",children:"Delete"})]})]})})]})}function Drs({goals:s,stats:t,year:n,showCommission:r}){const a=new Date().getMonth()+1,i=new Date().getFullYear()===n?a:12,l=12-i,o=(m,f)=>{if(!f||f===0)return null;const g=Math.min(m/f*100,100),x=Math.max(f-m,0),y=l>0?x/l:0,v=i/12*100,b=g>=v?"ahead":g>=v*.8?"on-track":"behind";return{percent:g,remaining:x,pace:y,status:b}},c=o(t.totalTransactions,s.transactions_goal),d=o(t.totalVolume,s.volume_goal),u=r?o(t.totalCommission,s.gci_goal):null,h=m=>{switch(m){case"ahead":return e.jsxs(Be,{className:"bg-green-500 text-white",children:[e.jsx(Yl,{className:"h-3 w-3 mr-1"}),"Ahead"]});case"on-track":return e.jsxs(Be,{variant:"secondary",children:[e.jsx(tk,{className:"h-3 w-3 mr-1"}),"On Track"]});case"behind":return e.jsxs(Be,{variant:"destructive",children:[e.jsx(rC,{className:"h-3 w-3 mr-1"}),"Behind"]});default:return null}};return!s.transactions_goal&&!s.volume_goal&&!s.gci_goal?null:e.jsxs(Ne,{children:[e.jsx(Ct,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(rh,{className:"h-5 w-5 text-primary"}),e.jsxs(At,{children:[n," Goals Progress"]})]})}),e.jsx(Ie,{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"}),h(c.status)]}),e.jsx(Yi,{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"}),h(d.status)]}),e.jsx(Yi,{value:d.percent,className:"h-2"}),e.jsxs("div",{className:"flex justify-between text-sm text-muted-foreground",children:[e.jsxs("span",{children:[Qm(t.totalVolume,!0)," of ",Qm(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 ",Qm(d.pace,!0),"/month"]})]}),r&&s.gci_goal&&u&&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"}),h(u.status)]}),e.jsx(Yi,{value:u.percent,className:"h-2"}),e.jsxs("div",{className:"flex justify-between text-sm text-muted-foreground",children:[e.jsxs("span",{children:[Qm(t.totalCommission,!0)," of ",Qm(s.gci_goal,!0)]}),e.jsxs("span",{children:[Math.round(u.percent),"%"]})]}),u.remaining>0&&l>0&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Need ",Qm(u.pace,!0),"/month"]})]})]})})]})}const gXn={light:"",dark:".dark"},Frs=j.createContext(null);function Ors(){const s=j.useContext(Frs);if(!s)throw new Error("useChart must be used within a ");return s}const zrs=j.forwardRef(({id:s,className:t,children:n,config:r,...a},i)=>{const l=j.useId(),o=`chart-${s||l.replace(/:/g,"")}`;return e.jsx(Frs.Provider,{value:{config:r},children:e.jsxs("div",{"data-chart":o,ref:i,className:Pt("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(xXn,{id:o,config:r}),e.jsx(A_,{children:n})]})})});zrs.displayName="Chart";const xXn=({id:s,config:t})=>{const n=Object.entries(t).filter(([r,a])=>a.theme||a.color);return n.length?e.jsx("style",{dangerouslySetInnerHTML:{__html:Object.entries(gXn).map(([r,a])=>` ${a} [data-chart=${s}] { ${n.map(([i,l])=>{var c;const o=((c=l.theme)==null?void 0:c[r])||l.color;return o?` --color-${i}: ${o};`:null}).join(` `)} } `).join(` `)}}):null},Brs=j.forwardRef(({active:s,payload:t,className:n,indicator:r="dot",hideLabel:a=!1,hideIndicator:i=!1,label:l,labelFormatter:o,labelClassName:c,formatter:d,color:u,nameKey:h,labelKey:m},f)=>{const{config:g}=Ors(),x=j.useMemo(()=>{var C;if(a||!(t!=null&&t.length))return null;const[v]=t,b=`${m||v.dataKey||v.name||"value"}`,w=OXe(g,v,b),S=!m&&typeof l=="string"?((C=g[l])==null?void 0:C.label)||l:w==null?void 0:w.label;return o?e.jsx("div",{className:Pt("font-medium",c),children:o(S,t)}):S?e.jsx("div",{className:Pt("font-medium",c),children:S}):null},[l,o,t,a,c,g,m]);if(!s||!(t!=null&&t.length))return null;const y=t.length===1&&r!=="dot";return e.jsxs("div",{ref:f,className:Pt("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",n),children:[y?null:x,e.jsx("div",{className:"grid gap-1.5",children:t.map((v,b)=>{const w=`${h||v.name||v.dataKey||"value"}`,S=OXe(g,v,w),C=u||v.payload.fill||v.color;return e.jsx("div",{className:Pt("flex w-full flex-wrap items-stretch gap-2 [&>svg]:h-2.5 [&>svg]:w-2.5 [&>svg]:text-muted-foreground",r==="dot"&&"items-center"),children:d&&(v==null?void 0:v.value)!==void 0&&v.name?d(v.value,v.name,v,b,v.payload):e.jsxs(e.Fragment,{children:[S!=null&&S.icon?e.jsx(S.icon,{}):!i&&e.jsx("div",{className:Pt("shrink-0 rounded-[2px] border-[--color-border] bg-[--color-bg]",{"h-2.5 w-2.5":r==="dot","w-1":r==="line","w-0 border-[1.5px] border-dashed bg-transparent":r==="dashed","my-0.5":y&&r==="dashed"}),style:{"--color-bg":C,"--color-border":C}}),e.jsxs("div",{className:Pt("flex flex-1 justify-between leading-none",y?"items-end":"items-center"),children:[e.jsxs("div",{className:"grid gap-1.5",children:[y?x:null,e.jsx("span",{className:"text-muted-foreground",children:(S==null?void 0:S.label)||v.name})]}),v.value&&e.jsx("span",{className:"font-mono font-medium tabular-nums text-foreground",children:v.value.toLocaleString()})]})]})},v.dataKey)})})]})});Brs.displayName="ChartTooltip";const yXn=j.forwardRef(({className:s,hideIcon:t=!1,payload:n,verticalAlign:r="bottom",nameKey:a},i)=>{const{config:l}=Ors();return n!=null&&n.length?e.jsx("div",{ref:i,className:Pt("flex items-center justify-center gap-4",r==="top"?"pb-3":"pt-3",s),children:n.map(o=>{const c=`${a||o.dataKey||"value"}`,d=OXe(l,o,c);return e.jsxs("div",{className:Pt("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});yXn.displayName="ChartLegend";function OXe(s,t,n){if(typeof t!="object"||t===null)return;const r="payload"in t&&typeof t.payload=="object"&&t.payload!==null?t.payload:void 0;let a=n;return n in t&&typeof t[n]=="string"?a=t[n]:r&&n in r&&typeof r[n]=="string"&&(a=r[n]),a in s?s[a]:s[n]}const Fue=["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 Zot({stats:s,year:t}){const n=s.transactionsByMonth.some(a=>a.count>0),r=s.leadSourceBreakdown.length>0;return!n&&!r?e.jsx(Ne,{children:e.jsx(Ie,{className:"py-12 text-center text-muted-foreground",children:"Add transactions to see your performance charts"})}):e.jsxs("div",{className:"grid gap-6",children:[n&&e.jsxs(Ne,{className:"overflow-hidden",children:[e.jsx(Ct,{children:e.jsx(At,{className:"text-base",children:"Transactions by Month"})}),e.jsx(Ie,{className:"overflow-hidden",children:e.jsx(zrs,{config:{count:{label:"Transactions",color:"hsl(var(--primary))"}},className:"h-[250px]",children:e.jsx(A_,{width:"100%",height:"100%",children:e.jsxs(OK,{data:s.transactionsByMonth,margin:{top:5,right:10,left:0,bottom:5},children:[e.jsx(vT,{strokeDasharray:"3 3",className:"stroke-muted"}),e.jsx(Mb,{dataKey:"month",tick:{fontSize:11},className:"fill-muted-foreground",interval:0}),e.jsx(Pb,{allowDecimals:!1,tick:{fontSize:12},className:"fill-muted-foreground",width:30}),e.jsx(Ag,{content:e.jsx(Brs,{})}),e.jsx(qw,{dataKey:"count",fill:"hsl(var(--primary))",radius:[4,4,0,0],name:"Transactions"})]})})})})]}),r&&e.jsxs(Ne,{children:[e.jsx(Ct,{children:e.jsx(At,{className:"text-base",children:"Lead Sources"})}),e.jsxs(Ie,{children:[e.jsx("div",{className:"h-[250px]",children:e.jsx(A_,{width:"100%",height:"100%",children:e.jsxs(OXt,{children:[e.jsx(g3,{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(t9,{fill:Fue[i%Fue.length]},`cell-${i}`))}),e.jsx(Ag,{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:Fue[i%Fue.length]}}),e.jsx("span",{className:"text-muted-foreground",children:a.name})]},a.name))})]})]})]})}function vXn(s){if(!s||!s.trim())return null;const t=s.trim(),n=["yyyy-MM-dd","M/d/yyyy","MM/dd/yyyy","M-d-yyyy","MM-dd-yyyy","MM/dd/yy","M/d/yy"];for(const r of n)try{const a=Ltt(t,r,new Date);if(XHe(a))return en(a,"yyyy-MM-dd")}catch{}try{const r=new Date(t);if(XHe(r))return en(r,"yyyy-MM-dd")}catch{}return null}const bXn=["property_address","city","state","zip","transaction_type","close_date","sale_price","commission_amount","lead_source","client_type","is_win","notes"];function _Xn({open:s,onOpenChange:t}){const[n,r]=j.useState([]),[a,i]=j.useState(!1),[l,o]=j.useState(0),{data:c}=HB(),{data:d}=Yw(),u=T6e(),h=()=>{const v=bXn.join(","),b=["123 Main St","Dallas","TX","75001","buyer","2024-06-15","450000","13500","Referral","Past Client","yes","Great transaction!"].join(","),w=`${v} ${b}`,S=new Blob([w],{type:"text/csv"}),C=URL.createObjectURL(S),E=document.createElement("a");E.href=C,E.download="transaction-import-template.csv",E.click(),URL.revokeObjectURL(C)},m=v=>{const b=v.split(` `).filter(S=>S.trim());if(b.length<2)return[];const w=b[0].split(",").map(S=>S.trim().toLowerCase().replace(/['"]/g,""));return b.slice(1).map((S,C)=>{var X,ae,ie,ne;const E=[];let I="",P=!1;for(const te of S)te==='"'?P=!P:te===","&&!P?(E.push(I.trim()),I=""):I+=te;E.push(I.trim());const R=te=>{var ce;const J=w.indexOf(te);return J>=0?(ce=E[J])==null?void 0:ce.replace(/^["']|["']$/g,"").trim():""},D=(X=R("transaction_type"))==null?void 0:X.toLowerCase(),O=(ae=R("sale_price"))==null?void 0:ae.replace(/[$,]/g,""),U=(ie=R("commission_amount"))==null?void 0:ie.replace(/[$,]/g,""),W=(ne=R("is_win"))==null?void 0:ne.toLowerCase(),V=R("close_date"),G=vXn(V);let Y;return R("property_address")?["buyer","seller"].includes(D)?G?(!O||isNaN(Number(O)))&&(Y="Invalid sale price"):Y=`Invalid date format: "${V}" - use MM/DD/YYYY or YYYY-MM-DD`:Y='Transaction type must be "buyer" or "seller"':Y="Missing property address",{property_address:R("property_address"),city:R("city"),state:R("state"),zip:R("zip"),transaction_type:D==="seller"?"seller":"buyer",close_date:G||"",sale_price:Number(O)||0,commission_amount:U?Number(U):null,lead_source_name:R("lead_source"),client_type_name:R("client_type"),is_win:["yes","true","1"].includes(W),notes:R("notes"),error:Y}})},f=v=>{var S;const b=(S=v.target.files)==null?void 0:S[0];if(!b)return;const w=new FileReader;w.onload=C=>{var P;const E=(P=C.target)==null?void 0:P.result,I=m(E);r(I)},w.readAsText(b)},g=async()=>{const v=n.filter(S=>!S.error);if(v.length===0){re.error("No valid transactions to import");return}i(!0),o(0);let b=0,w=0;for(let S=0;SP.name.toLowerCase()===C.lead_source_name.toLowerCase()),I=d==null?void 0:d.find(P=>P.name.toLowerCase()===C.client_type_name.toLowerCase());await u.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,lead_source_id:(E==null?void 0:E.id)||null,client_type_id:(I==null?void 0:I.id)||null,contact_id:null,notes:C.notes||null,is_win:C.is_win}),b++}catch(E){w++,console.error("Failed to import transaction:",E)}o(Math.round((S+1)/v.length*100))}i(!1),b>0&&re.success(`Imported ${b} transaction${b>1?"s":""}`),w>0&&re.error(`Failed to import ${w} transaction${w>1?"s":""}`),r([]),t(!1)},x=n.filter(v=>!v.error).length,y=n.filter(v=>v.error).length;return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Os,{className:"max-w-2xl max-h-[90vh]",children:[e.jsxs(Us,{children:[e.jsx(Bs,{children:"Import Transactions"}),e.jsx(Ir,{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($,{variant:"outline",onClick:h,children:[e.jsx(di,{className:"h-4 w-4 mr-2"}),"Template"]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"csv-file",children:"Upload CSV File"}),e.jsx(pe,{id:"csv-file",type:"file",accept:".csv",onChange:f})]}),n.length>0&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(Be,{variant:"outline",children:[n.length," rows found"]}),x>0&&e.jsxs(Be,{className:"bg-green-500 text-white",children:[e.jsx(la,{className:"h-3 w-3 mr-1"}),x," valid"]}),y>0&&e.jsxs(Be,{variant:"destructive",children:[e.jsx(ll,{className:"h-3 w-3 mr-1"}),y," errors"]})]}),e.jsx(uo,{className:"h-[200px] border rounded-lg",children:e.jsxs("div",{className:"p-2 space-y-2",children:[n.slice(0,10).map((v,b)=>e.jsxs("div",{className:`p-2 rounded text-sm ${v.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:v.property_address||"(no address)"}),e.jsx(Be,{variant:v.transaction_type==="buyer"?"default":"secondary",children:v.transaction_type})]}),e.jsxs("div",{className:"text-muted-foreground",children:[v.close_date," • $",v.sale_price.toLocaleString()]}),v.error&&e.jsx(Mse,{variant:"destructive",className:"mt-1 py-1",children:e.jsx(Pse,{className:"text-xs",children:v.error})})]},b)),n.length>10&&e.jsxs("p",{className:"text-center text-sm text-muted-foreground",children:["...and ",n.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($,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsxs($,{onClick:g,disabled:x===0||a,children:[e.jsx(ni,{className:"h-4 w-4 mr-2"}),"Import ",x," Transaction",x!==1?"s":""]})]})]})]})})}const wXn=H2({transactions_goal:vee().min(0).optional(),volume_goal:vee().min(0).optional(),gci_goal:vee().min(0).optional()});function jXn({open:s,onOpenChange:t,year:n,existingGoals:r}){const a=YWs(),{data:i}=M6e(),l=(i==null?void 0:i.show_commission)??!0,o=NLe({resolver:kLe(wXn),defaultValues:{transactions_goal:void 0,volume_goal:void 0,gci_goal:void 0}});j.useEffect(()=>{r?o.reset({transactions_goal:r.transactions_goal??void 0,volume_goal:r.volume_goal?Number(r.volume_goal):void 0,gci_goal:r.gci_goal?Number(r.gci_goal):void 0}):o.reset({transactions_goal:void 0,volume_goal:void 0,gci_goal:void 0})},[r,o,s]);const c=async d=>{await a.mutateAsync({year:n,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(zs,{open:s,onOpenChange:t,children:e.jsxs(Os,{className:"max-w-md",children:[e.jsxs(Us,{children:[e.jsxs(Bs,{children:[n," Goals"]}),e.jsx(Ir,{children:"Set your annual targets to track your progress throughout the year."})]}),e.jsx(ELe,{...o,children:e.jsxs("form",{onSubmit:o.handleSubmit(c),className:"space-y-4",children:[e.jsx(jg,{control:o.control,name:"transactions_goal",render:({field:d})=>e.jsxs(Up,{children:[e.jsx(qp,{children:"Transactions Goal"}),e.jsx(Vp,{children:e.jsx(pe,{type:"number",placeholder:"e.g., 24",...d,value:d.value??"",onChange:u=>d.onChange(u.target.value?Number(u.target.value):void 0)})}),e.jsx(X4e,{children:"Total number of deals you want to close"}),e.jsx(y_,{})]})}),e.jsx(jg,{control:o.control,name:"volume_goal",render:({field:d})=>e.jsxs(Up,{children:[e.jsx(qp,{children:"Volume Goal ($)"}),e.jsx(Vp,{children:e.jsx(pe,{type:"number",placeholder:"e.g., 5000000",...d,value:d.value??"",onChange:u=>d.onChange(u.target.value?Number(u.target.value):void 0)})}),e.jsx(X4e,{children:"Total sales volume you want to achieve"}),e.jsx(y_,{})]})}),l&&e.jsx(jg,{control:o.control,name:"gci_goal",render:({field:d})=>e.jsxs(Up,{children:[e.jsx(qp,{children:"GCI Goal ($)"}),e.jsx(Vp,{children:e.jsx(pe,{type:"number",placeholder:"e.g., 150000",...d,value:d.value??"",onChange:u=>d.onChange(u.target.value?Number(u.target.value):void 0)})}),e.jsx(X4e,{children:"Gross commission income target"}),e.jsx(y_,{})]})}),e.jsxs("div",{className:"flex justify-end gap-2 pt-4",children:[e.jsx($,{type:"button",variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsx($,{type:"submit",disabled:a.isPending,children:"Save Goals"})]})]})})]})})}function Xot({transactions:s,isLoading:t}){const n=j.useRef(null),r=j.useRef(null),a=j.useRef([]),i=j.useRef(null),{isAdmin:l}=vs(),[o,c]=j.useState(""),[d,u]=j.useState(!0),[h,m]=j.useState(0),[f,g]=j.useState(!1),x=s.filter(v=>v.latitude!=null&&v.longitude!=null),y=s.filter(v=>v.latitude==null||v.longitude==null);return j.useEffect(()=>{(async()=>{u(!0);try{const{data:b}=await q.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)}u(!1)})()},[]),j.useEffect(()=>{if(!o||y.length===0||f)return;(async()=>{var w;g(!0);let b=0;for(const S of y){const C=[S.property_address,S.city,S.state,S.zip].filter(Boolean).join(", ");if(C)try{const I=await(await fetch(`https://api.mapbox.com/geocoding/v5/mapbox.places/${encodeURIComponent(C)}.json?access_token=${o}&limit=1`)).json();if((w=I.features)!=null&&w[0]){const[P,R]=I.features[0].center;await q.from("scorecard_transactions").update({latitude:R,longitude:P}).eq("id",S.id),S.latitude=R,S.longitude=P,b++}}catch(E){console.error("Geocode error:",E)}}m(b),g(!1)})()},[o,s]),j.useEffect(()=>{if(!n.current||!o||r.current)return;ju.accessToken=o;const v=s.filter(S=>S.latitude!=null&&S.longitude!=null);let b=[-98.5795,39.8283],w=4;if(v.length>0){const S=v.reduce((E,I)=>E+I.longitude,0)/v.length,C=v.reduce((E,I)=>E+I.latitude,0)/v.length;b=[S,C],w=v.length===1?12:10}return r.current=new ju.Map({container:n.current,style:"mapbox://styles/mapbox/light-v11",zoom:w,center:b}),r.current.addControl(new ju.NavigationControl,"top-right"),()=>{var S;(S=r.current)==null||S.remove(),r.current=null}},[o]),j.useEffect(()=>{var b;if(!r.current||!o)return;a.current.forEach(w=>w.remove()),a.current=[],(b=i.current)==null||b.remove();const v=s.filter(w=>w.latitude!=null&&w.longitude!=null);if(v.forEach(w=>{var R;const S=w.transaction_type==="buyer",C=S?"#3B82F6":"#10B981",E=document.createElement("div");E.className="cursor-pointer",E.innerHTML=`
${S?'':''}
`;const I=new ju.Popup({offset:25,closeButton:!0}).setHTML(`
${w.property_address}
${w.city?`
${w.city}${w.state?", "+w.state:""} ${w.zip||""}
`:""}
${S?"Buyer":"Seller"} $${Number(w.sale_price).toLocaleString()}
Closed: ${Ch(w.close_date).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"})} ${(R=w.lead_source)!=null&&R.name?" · "+w.lead_source.name:""}
${w.contact?`
Client: ${w.contact.first_name} ${w.contact.last_name||""}
`:""}
`),P=new ju.Marker(E).setLngLat([w.longitude,w.latitude]).setPopup(I).addTo(r.current);a.current.push(P)}),v.length>1){const w=new ju.LngLatBounds;v.forEach(S=>w.extend([S.longitude,S.latitude])),r.current.fitBounds(w,{padding:60,maxZoom:13})}else v.length===1&&r.current.flyTo({center:[v[0].longitude,v[0].latitude],zoom:12})},[s,o,f]),d||t?e.jsx(Ne,{children:e.jsx(Ie,{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(Ne,{children:e.jsxs(Ie,{className:"flex flex-col items-center justify-center h-[50vh] text-center gap-3",children:[e.jsx(ci,{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:[x.length," of ",s.length," mapped",f&&" · Geocoding..."]})]}),e.jsx("div",{ref:n,className:"w-full h-[55vh] rounded-lg shadow-lg border"})]}):e.jsx(Ne,{children:e.jsxs(Ie,{className:"flex flex-col items-center justify-center h-[50vh] text-center gap-3",children:[e.jsx(ll,{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 $rs=()=>{const{data:s}=Hw();return tt({queryKey:["team-scorecard-members",s==null?void 0:s.teamId],queryFn:async()=>{const{data:t,error:n}=await q.from("team_members").select("user_id").eq("team_id",s.teamId);if(n)throw n;const r=t.map(l=>l.user_id),{data:a,error:i}=await q.from("profiles").select("id, name, email, avatar_url").in("id",r);if(i)throw i;return a||[]},enabled:!!(s!=null&&s.teamId)&&(s==null?void 0:s.role)==="team_leader"})},NXn=s=>{const{data:t}=Hw(),{data:n}=$rs();return tt({queryKey:["team-scorecard-transactions",t==null?void 0:t.teamId,s],queryFn:async()=>{const r=n.map(o=>o.id);let a=q.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",r).order("close_date",{ascending:!1});s&&(a=a.gte("close_date",`${s}-01-01`).lte("close_date",`${s}-12-31`));const{data:i,error:l}=await a;if(l)throw l;return i},enabled:!!n&&n.length>0})};function kXn(s,t){const n=t.filter(i=>i.owner_user_id===s.id),r=n.reduce((i,l)=>i+Number(l.sale_price),0),a=n.reduce((i,l)=>i+(Number(l.commission_amount)||0),0);return{member:s,totalTransactions:n.length,buyerCount:n.filter(i=>i.transaction_type==="buyer").length,sellerCount:n.filter(i=>i.transaction_type==="seller").length,totalVolume:r,averagePrice:n.length>0?r/n.length:0,totalGCI:a}}function SXn(s,t){return s?s.split(" ").map(n=>n[0]).join("").toUpperCase().slice(0,2):t[0].toUpperCase()}function CXn({year:s}){var m;const{data:t,isLoading:n}=$rs(),{data:r,isLoading:a}=NXn(s),i=Qn(),l=n||a,{aggregate:o,memberStats:c,topPerformer:d,agentNameMap:u,teamChartStats:h}=j.useMemo(()=>{if(!t||!r)return{aggregate:null,memberStats:[],topPerformer:null,agentNameMap:{},teamChartStats:null};const f=t.map(D=>kXn(D,r));f.sort((D,O)=>O.totalVolume-D.totalVolume);const g={};t.forEach(D=>{g[D.id]=D.name||D.email});const x=r.length,y=r.reduce((D,O)=>D+Number(O.sale_price),0),v=r.reduce((D,O)=>D+(Number(O.commission_amount)||0),0),b=r.filter(D=>D.transaction_type==="buyer").length,w=r.filter(D=>D.transaction_type==="seller").length,S={};r.forEach(D=>{var U;const O=((U=D.lead_source)==null?void 0:U.name)||"Unknown";S[O]=(S[O]||0)+1});const C=Object.entries(S).sort((D,O)=>O[1]-D[1])[0],E={};r.forEach(D=>{const O=Ch(D.close_date).toLocaleString("default",{month:"short"});E[O]=(E[O]||0)+1});const P=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"].map(D=>({month:D,count:E[D]||0})),R=Object.entries(S).map(([D,O])=>({name:D,count:O})).sort((D,O)=>O.count-D.count);return{aggregate:{totalTxns:x,buyerCount:b,sellerCount:w,totalVolume:y,avgPrice:x>0?y/x:0,totalGCI:v,topSource:C?{name:C[0],count:C[1]}:null,memberCount:t.length},memberStats:f,topPerformer:f[0]||null,agentNameMap:g,teamChartStats:{transactionsByMonth:P,leadSourceBreakdown:R}}},[t,r]);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(f=>e.jsx(yn,{className:"h-24"},f))}),e.jsx(yn,{className:"h-64"})]}):!o||c.length===0?e.jsx(Ne,{className:"py-12",children:e.jsxs(Ie,{className:"text-center space-y-2",children:[e.jsx(Zn,{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(Ne,{children:e.jsxs(Ie,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(Zn,{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(Ne,{children:e.jsxs(Ie,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(va,{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(Ne,{children:e.jsxs(Ie,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(ru,{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:Qm(o.totalVolume,!0)})]})}),e.jsx(Ne,{children:e.jsxs(Ie,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(Yl,{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:Qm(o.avgPrice,!0)})]})}),e.jsx(Ne,{children:e.jsxs(Ie,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(ru,{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:Qm(o.totalGCI,!0)})]})}),e.jsx(Ne,{children:e.jsxs(Ie,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(Rm,{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:((m=o.topSource)==null?void 0:m.name)||"-"}),o.topSource&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:[o.topSource.count," deals"]})]})})]}),d&&d.totalTransactions>0&&e.jsx(Ne,{className:"border-primary/30 bg-primary/5",children:e.jsxs(Ie,{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(Kl,{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:Qm(d.totalVolume,!0)})]})]})}),e.jsxs(Ne,{children:[e.jsx(Ct,{children:e.jsx(At,{className:"text-lg",children:"Member Performance"})}),e.jsx(Ie,{children:e.jsx("div",{className:"overflow-x-auto",children:e.jsxs(mi,{children:[e.jsx(fi,{children:e.jsxs(En,{children:[e.jsx(Dt,{children:"Agent"}),e.jsx(Dt,{className:"text-center",children:"Transactions"}),e.jsx(Dt,{className:"text-center",children:"B / S"}),e.jsx(Dt,{className:"text-right",children:"Volume"}),e.jsx(Dt,{className:"text-right",children:"Avg Price"}),e.jsx(Dt,{className:"text-right",children:"GCI"}),e.jsx(Dt,{className:"text-right"})]})}),e.jsx(pi,{children:c.map((f,g)=>e.jsxs(En,{children:[e.jsx(wt,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("div",{className:"relative",children:[g===0&&f.totalTransactions>0&&e.jsx(Kl,{className:"absolute -top-2 -right-2 h-3.5 w-3.5 text-amber-500"}),e.jsxs(Oa,{className:"h-8 w-8",children:[e.jsx(Li,{src:f.member.avatar_url||void 0}),e.jsx(za,{className:"text-xs",children:SXn(f.member.name,f.member.email)})]})]}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-sm",children:f.member.name||f.member.email}),f.member.name&&e.jsx("p",{className:"text-xs text-muted-foreground",children:f.member.email})]})]})}),e.jsx(wt,{className:"text-center font-semibold",children:f.totalTransactions}),e.jsxs(wt,{className:"text-center text-sm",children:[f.buyerCount," / ",f.sellerCount]}),e.jsx(wt,{className:"text-right font-medium",children:Qm(f.totalVolume,!0)}),e.jsx(wt,{className:"text-right text-sm",children:Qm(f.averagePrice,!0)}),e.jsx(wt,{className:"text-right font-medium",children:Qm(f.totalGCI,!0)}),e.jsx(wt,{className:"text-right",children:e.jsx($,{variant:"ghost",size:"sm",onClick:()=>i(`/mission-control/scorecard/${f.member.id}`),children:e.jsx(Ca,{className:"h-4 w-4"})})})]},f.member.id))})]})})})]}),e.jsxs(ha,{defaultValue:"transactions",className:"space-y-4",children:[e.jsxs(ma,{children:[e.jsxs(Zt,{value:"transactions",children:[e.jsx(P0,{className:"h-4 w-4 mr-1"}),"All Transactions"]}),e.jsxs(Zt,{value:"charts",children:[e.jsx(Wl,{className:"h-4 w-4 mr-1"}),"Charts"]}),e.jsxs(Zt,{value:"map",children:[e.jsx(ci,{className:"h-4 w-4 mr-1"}),"Map"]})]}),e.jsx(Xt,{value:"transactions",children:e.jsx(Yot,{transactions:r||[],showCommission:!0,isLoading:a,agentNameMap:u,readOnly:!0})}),e.jsx(Xt,{value:"charts",children:h&&e.jsx(Zot,{stats:h,year:s})}),e.jsx(Xt,{value:"map",children:e.jsx(Xot,{transactions:r||[],isLoading:a})})]})]})}const fAe=new Date().getFullYear(),k3t=Array.from({length:10},(s,t)=>fAe-t),Oue="all";function AXn(){var O;const[s,t]=j.useState(fAe),n=s===null?Oue:String(s),r=U=>t(U===Oue?null:Number(U)),[a,i]=j.useState(!1),[l,o]=j.useState(!1),[c,d]=j.useState(!1),[u,h]=j.useState(!1),[m,f]=j.useState("my"),{data:g}=Hw(),x=(g==null?void 0:g.role)==="team_leader",{data:y,isLoading:v}=pnt(s??void 0),{yearStats:b,lifetimeStats:w,showCommission:S}=aqt(s??void 0),{data:C,isLoading:E}=rqt(s??fAe),{data:I}=M6e(),P=ZWs(),R=()=>{if(!y||y.length===0)return;const U=["Property Address","City","State","Zip","Transaction Type","Close Date","Sale Price",...S?["Commission"]:[],"Lead Source","Client Type","Contact Name","Is Win","Notes"],W=y.map(ae=>{var ie,ne;return[ae.property_address,ae.city||"",ae.state||"",ae.zip||"",ae.transaction_type,ae.close_date,ae.sale_price,...S?[ae.commission_amount||""]:[],((ie=ae.lead_source)==null?void 0:ie.name)||"",((ne=ae.client_type)==null?void 0:ne.name)||"",ae.contact?`${ae.contact.first_name} ${ae.contact.last_name||""}`.trim():"",ae.is_win?"Yes":"No",ae.notes||""]}),V=[U,...W].map(ae=>ae.map(ie=>`"${String(ie).replace(/"/g,'""')}"`).join(",")).join(` `),G=new Blob([V],{type:"text/csv"}),Y=URL.createObjectURL(G),X=document.createElement("a");X.href=Y,X.download=s===null?"transactions-all.csv":`transactions-${s}.csv`,X.click(),URL.revokeObjectURL(Y)},D=!y||y.length===0;return e.jsxs(Vs,{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($,{variant:m==="my"?"default":"ghost",size:"sm",onClick:()=>f("my"),className:"h-8",children:"My Scorecard"}),e.jsxs($,{variant:m==="team"?"default":"ghost",size:"sm",onClick:()=>f("team"),className:"h-8",children:[e.jsx(Zn,{className:"h-4 w-4 mr-1.5"}),"Team"]})]}),m==="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(ms,{value:n,onValueChange:r,children:[e.jsx(us,{className:"w-[140px]",children:e.jsx(fs,{})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:Oue,children:"All Years"}),k3t.map(U=>e.jsx(Ge,{value:String(U),children:U},U))]})]})]}),e.jsx(CXn,{year:s??void 0})]}):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(ms,{value:n,onValueChange:r,children:[e.jsx(us,{className:"w-[140px]",children:e.jsx(fs,{})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:Oue,children:"All Years"}),k3t.map(U=>e.jsx(Ge,{value:String(U),children:U},U))]})]}),e.jsx($,{variant:"outline",size:"icon",onClick:()=>h(!u),children:e.jsx(Sd,{className:"h-4 w-4"})})]})]}),u&&e.jsxs(Ne,{children:[e.jsx(Ct,{className:"pb-3",children:e.jsx(At,{className:"text-lg",children:"Settings"})}),e.jsx(Ie,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"space-y-0.5",children:[e.jsx(ee,{children:"Show Commission"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Display commission fields and include in stats"})]}),e.jsx(Sn,{checked:(I==null?void 0:I.show_commission)??!0,onCheckedChange:U=>P.mutate({show_commission:U})})]})})]}),D&&!v?e.jsx(Ne,{className:"py-12",children:e.jsxs(Ie,{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(Wl,{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($,{onClick:()=>i(!0),children:[e.jsx(dn,{className:"h-4 w-4 mr-2"}),"Add Your First Transaction"]}),e.jsxs($,{variant:"outline",onClick:()=>o(!0),children:[e.jsx(ni,{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($,{variant:"link",className:"h-auto p-0",asChild:!0,children:e.jsxs("a",{href:"/templates/transaction-import-template.csv",download:!0,children:[e.jsx(di,{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($,{onClick:()=>i(!0),children:[e.jsx(dn,{className:"h-4 w-4 mr-2"}),"Add Transaction"]}),e.jsxs($,{variant:"outline",onClick:()=>d(!0),children:[e.jsx(rh,{className:"h-4 w-4 mr-2"}),"Set Goals"]}),e.jsxs($,{variant:"outline",onClick:()=>o(!0),children:[e.jsx(ni,{className:"h-4 w-4 mr-2"}),"Import"]}),e.jsxs($,{variant:"outline",onClick:R,disabled:D,children:[e.jsx(di,{className:"h-4 w-4 mr-2"}),"Export"]}),e.jsx($,{variant:"ghost",size:"sm",asChild:!0,children:e.jsxs("a",{href:"/templates/transaction-import-template.csv",download:!0,children:[e.jsx(di,{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(Ne,{children:e.jsxs(Ie,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(va,{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:[w.totalTransactions," lifetime"]})]})}),e.jsx(Ne,{children:e.jsxs(Ie,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(Zn,{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(Ne,{children:e.jsxs(Ie,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(ru,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs font-medium",children:"Volume"})]}),e.jsx("p",{className:"text-2xl font-bold",children:Qm(b.totalVolume,!0)}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[Qm(w.totalVolume,!0)," lifetime"]})]})}),e.jsx(Ne,{children:e.jsxs(Ie,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(Yl,{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:Qm(b.averagePrice,!0)})]})}),e.jsx(Ne,{children:e.jsxs(Ie,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(Rm,{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:((O=b.topLeadSource)==null?void 0:O.name)||"-"}),b.topLeadSource&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:[b.topLeadSource.count," deals"]})]})}),S&&e.jsx(Ne,{children:e.jsxs(Ie,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(ru,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs font-medium",children:"GCI"})]}),e.jsx("p",{className:"text-2xl font-bold",children:Qm(b.totalCommission,!0)}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[Qm(w.totalCommission,!0)," lifetime"]})]})}),S&&b.totalNetToAgent>0&&b.totalNetToAgent!==b.totalCommission&&e.jsx(Ne,{children:e.jsxs(Ie,{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(ru,{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:Qm(b.totalNetToAgent,!0)}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[Qm(w.totalNetToAgent,!0)," lifetime"]})]})})]}),s!==null&&C&&e.jsx(Drs,{goals:C,stats:b,year:s,showCommission:S}),e.jsxs(ha,{defaultValue:"transactions",className:"space-y-4",children:[e.jsxs(ma,{children:[e.jsx(Zt,{value:"transactions",children:"Transactions"}),e.jsx(Zt,{value:"charts",children:"Charts"}),e.jsxs(Zt,{value:"map",children:[e.jsx(ci,{className:"h-4 w-4 mr-1"}),"Map"]})]}),e.jsx(Xt,{value:"transactions",children:e.jsx(Yot,{transactions:y||[],showCommission:S,isLoading:v})}),e.jsx(Xt,{value:"charts",children:e.jsx(Zot,{stats:b,year:s??void 0})}),e.jsx(Xt,{value:"map",children:e.jsx(Xot,{transactions:y||[],isLoading:v})})]})]})]})]}),e.jsx(Rrs,{open:a,onOpenChange:i}),e.jsx(_Xn,{open:l,onOpenChange:o}),e.jsx(jXn,{open:c,onOpenChange:d,year:s??fAe,existingGoals:C})]})}const EXn=s=>tt({queryKey:["listing-launch-kit",s],enabled:!!s,queryFn:async()=>{const[t,n]=await Promise.all([q.from("listing_launch_kits").select("*").eq("listing_id",s).maybeSingle(),q.from("listing_community_guides").select("*").eq("listing_id",s).maybeSingle()]);return{kit:t.data??null,guide:n.data??null}}}),TXn=()=>{const s=Vt();return ft({mutationFn:async({listingId:t,regenerate:n})=>{const{data:r,error:a}=await q.functions.invoke("listing-launch-kit",{body:{listingId:t,regenerate:!!n}});if(a){const i=r==null?void 0:r.error;throw new Error(i||a.message||"Could not build the launch kit.")}if(r!=null&&r.error)throw new Error(r.error);return r},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["listing-launch-kit",n.listingId]})}})},MXn=()=>{const s=Vt();return ft({mutationFn:async({guideId:t,enabled:n})=>{const{error:r}=await q.from("listing_community_guides").update({is_enabled:n}).eq("id",t);if(r)throw r},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["listing-launch-kit",n.listingId]})}})};function PM({label:s,value:t,multiline:n=!0}){const[r,a]=j.useState(!1);if(!t)return null;const i=async()=>{await navigator.clipboard.writeText(t),a(!0),re.success(`${s} copied`),setTimeout(()=>a(!1),1800)};return e.jsxs("div",{className:"rounded-xl border border-border bg-card/60 overflow-hidden",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3 px-4 py-2.5 border-b border-border bg-muted/40",children:[e.jsx("span",{className:"text-[11px] font-semibold uppercase tracking-[0.16em] text-muted-foreground",children:s}),e.jsxs($,{size:"sm",variant:"ghost",className:"h-7 px-2 text-xs",onClick:i,children:[r?e.jsx(la,{className:"h-3.5 w-3.5 mr-1 text-primary"}):e.jsx(Ha,{className:"h-3.5 w-3.5 mr-1"}),r?"Copied":"Copy"]})]}),e.jsx("p",{className:`px-4 py-3 text-sm leading-relaxed text-foreground ${n?"whitespace-pre-wrap":""}`,children:t})]})}function Urs({listingId:s,open:t,onOpenChange:n,listingAddress:r,listingSlug:a,autoGenerate:i}){var S,C,E,I,P,R,D,O,U,W,V,G,Y,X,ae,ie;const l=Qn(),{data:o,isLoading:c}=EXn(t?s:null),d=TXn(),u=MXn(),[h,m]=j.useState(!1),f=(o==null?void 0:o.kit)??null,g=(o==null?void 0:o.guide)??null,x=d.isPending;j.useEffect(()=>{if(!t){m(!1);return}c||h||f||!s||(i||!f)&&(m(!0),d.mutate({listingId:s},{onError:ne=>re.error((ne==null?void 0:ne.message)||"Could not build the launch kit.")}))},[t,c,f,s,i,h]);const y=j.useMemo(()=>{const ne=a||s;return ne?`${window.location.origin}/public/listing/${ne}`:null},[a,s]),v=ne=>{ne&&(sessionStorage.setItem("social-studio-seed",JSON.stringify({caption:ne,source:"listing-launch-kit",sourceRef:s})),n(!1),l("/social-studio"),re.success("Draft ready in Social Studio"))},b=()=>{s&&d.mutate({listingId:s,regenerate:!0},{onSuccess:()=>re.success("Fresh launch kit ready"),onError:ne=>re.error((ne==null?void 0:ne.message)||"Could not rebuild the launch kit.")})},w=((S=f==null?void 0:f.social)==null?void 0:S.hashtags)??[];return e.jsx(zs,{open:t,onOpenChange:n,children:e.jsxs(Os,{className:"max-w-4xl p-0 gap-0 overflow-hidden border-border flex flex-col max-h-[92vh]",children:[e.jsxs("div",{className:"relative bg-gradient-to-br from-slate-900 via-slate-900 to-primary/30 px-6 pt-6 pb-5",children:[e.jsx("div",{className:"absolute inset-0 opacity-30 bg-[radial-gradient(circle_at_top_right,hsl(var(--primary)/0.5),transparent_60%)]"}),e.jsxs("div",{className:"relative",children:[e.jsxs("div",{className:"flex items-center gap-2 text-[11px] uppercase tracking-[0.22em] text-white/60 mb-2",children:[e.jsx(qg,{className:"h-3.5 w-3.5"}),"Listing Launch Kit"]}),e.jsx("h2",{className:"font-display text-2xl sm:text-[28px] font-semibold text-white leading-tight",children:((C=f==null?void 0:f.angle)==null?void 0:C.headline)||r||"Your listing, ready to launch"}),((E=f==null?void 0:f.angle)==null?void 0:E.target_buyer)&&e.jsxs("p",{className:"mt-2 text-sm text-white/70 flex items-start gap-2 max-w-2xl",children:[e.jsx(rh,{className:"h-4 w-4 mt-0.5 shrink-0 text-primary-foreground/80"}),f.angle.target_buyer]}),e.jsxs("div",{className:"mt-4 flex flex-wrap items-center gap-2",children:[(((I=f==null?void 0:f.angle)==null?void 0:I.pillars)??[]).map((ne,te)=>e.jsxs(Be,{variant:"outline",className:"border-white/20 bg-white/10 text-white/90 font-normal backdrop-blur-sm",children:[e.jsx(Nn,{className:"h-3 w-3 mr-1"}),ne]},te)),e.jsx("div",{className:"ml-auto",children:e.jsxs($,{size:"sm",variant:"outline",className:"h-8 border-white/25 bg-white/10 text-white hover:bg-white/20 hover:text-white",onClick:b,disabled:x||!s,children:[e.jsx(ro,{className:`h-3.5 w-3.5 mr-1.5 ${x?"animate-spin":""}`}),x?"Building…":"Regenerate"]})})]})]})]}),x&&!f?e.jsxs("div",{className:"p-6 space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(kt,{className:"h-4 w-4 animate-spin text-primary"}),"Writing your scripts, captions, sphere emails and community guide…"]}),e.jsx(yn,{className:"h-24 w-full"}),e.jsx(yn,{className:"h-24 w-full"}),e.jsx(yn,{className:"h-24 w-full"})]}):f?e.jsxs(ha,{defaultValue:"video",className:"w-full flex-1 min-h-0 flex flex-col",children:[e.jsx("div",{className:"px-4 pt-4 border-b border-border",children:e.jsx(ma,{className:"w-full justify-start gap-1 bg-transparent p-0 h-auto flex-wrap",children:[{v:"video",label:"Video & Reels",icon:ua},{v:"social",label:"Social",icon:zd},{v:"sphere",label:"Sphere Blast",icon:Yr},{v:"openhouse",label:"Open House",icon:d2},{v:"guide",label:"Community Guide",icon:Xf}].map(({v:ne,label:te,icon:J})=>e.jsxs(Zt,{value:ne,className:"rounded-t-lg rounded-b-none border-b-2 border-transparent px-3 py-2 text-sm data-[state=active]:border-primary data-[state=active]:bg-primary/5 data-[state=active]:text-primary data-[state=active]:shadow-none",children:[e.jsx(J,{className:"h-4 w-4 mr-1.5"}),te]},ne))})}),e.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto overscroll-contain",children:e.jsxs("div",{className:"p-5 space-y-4",children:[e.jsxs(Xt,{value:"video",className:"m-0 space-y-4",children:[e.jsx(PM,{label:"3-second hook",value:(R=(P=f.video)==null?void 0:P.reel_script)==null?void 0:R.hook}),e.jsx(PM,{label:"Walkthrough script",value:(O=(D=f.video)==null?void 0:D.reel_script)==null?void 0:O.walkthrough}),e.jsx(PM,{label:"Call to action",value:(W=(U=f.video)==null?void 0:U.reel_script)==null?void 0:W.cta}),(((V=f.video)==null?void 0:V.hooks)??[]).length>0&&e.jsxs("div",{className:"rounded-xl border border-border bg-card/60 overflow-hidden",children:[e.jsx("div",{className:"px-4 py-2.5 border-b border-border bg-muted/40 text-[11px] font-semibold uppercase tracking-[0.16em] text-muted-foreground",children:"Story & Reel text overlays"}),e.jsx("ul",{className:"divide-y divide-border",children:f.video.hooks.map((ne,te)=>e.jsxs("li",{className:"flex items-center justify-between gap-3 px-4 py-2.5",children:[e.jsx("span",{className:"text-sm",children:ne}),e.jsx($,{size:"sm",variant:"ghost",className:"h-7 px-2 text-xs shrink-0",onClick:()=>{navigator.clipboard.writeText(ne),re.success("Copied")},children:e.jsx(Ha,{className:"h-3.5 w-3.5"})})]},te))})]})]}),e.jsxs(Xt,{value:"social",className:"m-0 space-y-4",children:[["instagram","facebook","linkedin"].map(ne=>{var ce;const te=(ce=f.social)==null?void 0:ce[ne];if(!te)return null;const J=ne==="linkedin"?"LinkedIn":ne==="instagram"?"Instagram":"Facebook";return e.jsxs("div",{className:"space-y-2",children:[e.jsx(PM,{label:`${J} caption`,value:te}),e.jsxs($,{size:"sm",variant:"secondary",onClick:()=>v(te),children:[e.jsx(Yr,{className:"h-3.5 w-3.5 mr-1.5"}),"Send to Social Studio"]})]},ne)}),w.length>0&&e.jsxs("div",{className:"rounded-xl border border-border bg-card/60 p-4",children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsx("span",{className:"text-[11px] font-semibold uppercase tracking-[0.16em] text-muted-foreground",children:"Hashtags"}),e.jsxs($,{size:"sm",variant:"ghost",className:"h-7 px-2 text-xs",onClick:()=>{navigator.clipboard.writeText(w.join(" ")),re.success("Hashtags copied")},children:[e.jsx(Ha,{className:"h-3.5 w-3.5 mr-1"}),"Copy all"]})]}),e.jsx("div",{className:"flex flex-wrap gap-1.5",children:w.map((ne,te)=>e.jsx(Be,{variant:"secondary",className:"font-normal",children:ne},te))})]})]}),e.jsxs(Xt,{value:"sphere",className:"m-0 space-y-4",children:[e.jsx(PM,{label:"Email subject",value:(G=f.outreach)==null?void 0:G.email_subject,multiline:!1}),e.jsx(PM,{label:"Email to your sphere",value:(Y=f.outreach)==null?void 0:Y.email_body}),e.jsx(PM,{label:"VIP text message",value:(X=f.outreach)==null?void 0:X.sms})]}),e.jsxs(Xt,{value:"openhouse",className:"m-0 space-y-4",children:[e.jsx(PM,{label:"60-second door pitch",value:(ae=f.open_house)==null?void 0:ae.pitch}),(((ie=f.open_house)==null?void 0:ie.neighborhood_points)??[]).length>0&&e.jsxs("div",{className:"rounded-xl border border-border bg-card/60 overflow-hidden",children:[e.jsx("div",{className:"px-4 py-2.5 border-b border-border bg-muted/40 text-[11px] font-semibold uppercase tracking-[0.16em] text-muted-foreground",children:"Neighborhood talking points"}),e.jsx("ul",{className:"divide-y divide-border",children:f.open_house.neighborhood_points.map((ne,te)=>e.jsxs("li",{className:"px-4 py-2.5 text-sm flex gap-2",children:[e.jsx("span",{className:"text-primary",children:"•"}),ne]},te))})]})]}),e.jsx(Xt,{value:"guide",className:"m-0 space-y-4",children:g?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"rounded-xl border border-primary/25 bg-primary/5 p-4",children:[e.jsxs("div",{className:"flex items-start justify-between gap-4",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("p",{className:"font-medium text-sm flex items-center gap-2",children:[e.jsx(Zn,{className:"h-4 w-4 text-primary"}),"Show the free guide download on your public listing page"]}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:"Visitors trade their name, email and cell for the guide — each one lands in your CRM as a new lead."})]}),e.jsx(Sn,{checked:g.is_enabled,disabled:u.isPending,onCheckedChange:ne=>u.mutate({guideId:g.id,enabled:ne,listingId:s},{onSuccess:()=>re.success(ne?"Guide download is live":"Guide download hidden"),onError:()=>re.error("Could not update the guide")})})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-3 mt-4",children:[e.jsxs(Be,{variant:"secondary",className:"font-normal",children:[g.download_count," download",g.download_count===1?"":"s"]}),y&&e.jsxs($,{size:"sm",variant:"outline",onClick:()=>{navigator.clipboard.writeText(y),re.success("Share link copied — great for neighborhood groups")},children:[e.jsx(bd,{className:"h-3.5 w-3.5 mr-1.5"}),"Copy share link"]})]})]}),e.jsx("div",{className:"rounded-xl border border-border bg-card/60 p-5",children:e.jsx(O7t,{title:g.title,subtitle:g.subtitle,areaLabel:g.area_label,sections:g.sections??[]})})]}):e.jsx("p",{className:"text-sm text-muted-foreground py-8 text-center",children:"No community guide was generated for this listing yet. Try Regenerate."})})]})})]}):e.jsxs("div",{className:"p-10 text-center",children:[e.jsx("p",{className:"text-sm text-muted-foreground mb-4",children:"No launch kit yet for this listing."}),e.jsxs($,{onClick:b,disabled:!s,children:[e.jsx(Nn,{className:"h-4 w-4 mr-2"}),"Build my launch kit"]})]})]})})}const PXn={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"},IXn={active:"Active",coming_soon:"Coming Soon",office_exclusive:"Office Exclusive",pre_market:"Pre-Market",price_improvement:"Price Improvement",under_contract:"Under Contract",sold:"Sold"},LXn={single_family:"Single Family",condo:"Condo",townhouse:"Townhouse",land:"Land",multi_family:"Multi-Family",luxury:"Luxury",commercial:"Commercial",other:"Other"};function RXn({listing:s,onClick:t,onEdit:n,onDelete:r,onCreateMusicVideo:a,onLaunchKit:i,showActions:l}){var C,E;const{user:o}=vs(),{data:c}=W$t(s.id),d=G$t(),[u,h]=j.useState(!1),m=I=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(I),f=((C=s.photos)==null?void 0:C.find(I=>I.is_primary))||((E=s.photos)==null?void 0:E[0]),g=D$t(s.agent_id)||(o==null?void 0:o.id)===s.agent_id,x=s.listing_class==="commercial",y=s.commercial??null,v=s.lifecycle_stage==="pitch",b=x?[bE(y==null?void 0:y.building_sf)?`${bE(y==null?void 0:y.building_sf)} building`:null,bE(y==null?void 0:y.available_sf)?`${bE(y==null?void 0:y.available_sf)} available`:null,LEe(y==null?void 0:y.cap_rate)?`${LEe(y==null?void 0:y.cap_rate)} cap`:null,(y==null?void 0:y.price_per_sf)!=null?`${BN(y.price_per_sf,2)}/SF`:null,(y==null?void 0:y.units)!=null?`${y.units} units`:null].filter(Boolean).slice(0,3):[],w=async I=>{I.stopPropagation();try{const P=await d.mutateAsync(s.id);re.success(P.saved?"Listing saved!":"Listing removed from saved")}catch{re.error("Failed to save listing")}},S=I=>{if(I.stopPropagation(),o)h(!0);else{const P=`${s.listing_class==="commercial"?"https://commercial.relevelup.com":"https://listings.relevelup.com"}/${s.slug||s.id}`;navigator.clipboard.writeText(P),re.success("Link copied to clipboard!")}};return e.jsxs(Ne,{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:[f?e.jsx("img",{src:f.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(C_,{className:"h-12 w-12"})}),e.jsxs("div",{className:"absolute top-2 left-2 flex flex-wrap gap-1",children:[e.jsx(Be,{className:`${PXn[s.status]} text-white border-0`,children:x&&v?"Pitch":IXn[s.status]}),x&&e.jsx(Be,{className:"border-0 bg-[#0b0f14]/90 text-white",children:y!=null&&y.deal_type?ML[y.deal_type]:"Commercial"})]}),s.is_featured&&e.jsx("div",{className:"absolute top-2 right-2 p-1.5 bg-amber-500 rounded-full",children:e.jsx(Ja,{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($,{size:"icon",variant:"secondary",className:"h-8 w-8",onClick:w,children:e.jsx(Jo,{className:`h-4 w-4 ${c?"fill-pink-500 text-pink-500":""}`})}),e.jsx($,{size:"icon",variant:"secondary",className:"h-8 w-8",onClick:S,title:g?"Copy link":"Share & earn leads",children:g?e.jsx(zd,{className:"h-4 w-4"}):e.jsx(Nn,{className:"h-4 w-4 text-amber-500"})})]})]}),e.jsx(w6e,{open:u,onOpenChange:h,listingId:s.id,listingSlug:s.slug||null,listingTitle:s.property_address||`${s.city}, ${s.state}`,isCommercial:s.listing_class==="commercial"}),e.jsxs(Ie,{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:x?EG(y,s.price):m(s.price)}),s.open_to_referrals&&e.jsxs(Be,{variant:"outline",className:"text-xs",children:[e.jsx(Zn,{className:"h-3 w-3 mr-1"}),"Referrals"]})]}),e.jsxs("div",{children:[x?e.jsx("p",{className:"font-medium truncate",children:iL(s,y)}):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(ci,{className:"h-3 w-3"}),x?Kae(s,y):`${s.city}, ${s.state}${s.neighborhood?` • ${s.neighborhood}`:""}`]})]}),e.jsx("div",{className:"flex items-center gap-4 text-sm text-muted-foreground",children:x?b.map(I=>e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(C_,{className:"h-4 w-4"}),I]},I)):e.jsxs(e.Fragment,{children:[s.bedrooms&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(l2,{className:"h-4 w-4"}),s.bedrooms," bd"]}),s.bathrooms&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(T0,{className:"h-4 w-4"}),s.bathrooms," ba"]}),s.square_footage&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(C_,{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(Be,{variant:"secondary",className:"text-xs",children:x?y!=null&&y.commercial_type?c6[y.commercial_type]:"Commercial":LXn[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(Ca,{className:"h-3 w-3"}),s.view_count]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(zd,{className:"h-3 w-3"}),s.share_count]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Jo,{className:"h-3 w-3"}),s.save_count]})]}),l&&(n||r||a||i)&&e.jsxs("div",{className:"flex flex-wrap gap-2",children:[i&&e.jsxs($,{variant:"outline",size:"sm",className:"flex-1 min-w-[140px] gap-1.5 border-primary/50 text-primary hover:bg-primary/10",onClick:I=>{I.stopPropagation(),i()},children:[e.jsx(qg,{className:"h-4 w-4"}),"Launch Kit"]}),a&&e.jsxs($,{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:I=>{I.stopPropagation(),a()},children:[e.jsx(Zq,{className:"h-4 w-4"}),"Music Video"]}),n&&e.jsxs($,{variant:"outline",size:"sm",className:"flex-1",onClick:I=>{I.stopPropagation(),n()},children:[e.jsx(_p,{className:"h-4 w-4 mr-2"}),"Edit"]}),r&&e.jsx($,{variant:"destructive",size:"sm",onClick:I=>{I.stopPropagation(),r()},children:e.jsx(Wn,{className:"h-4 w-4"})})]})]})]})}const Qot="lu_listing_selection_v1",jPe=24,NPe=new Set;function qrs(){try{return JSON.parse(sessionStorage.getItem(Qot)||"{}")}catch{return{}}}function $$e(s){try{sessionStorage.setItem(Qot,JSON.stringify(s))}catch{}NPe.forEach(t=>t())}let NA=qrs();function DXn(){NA=qrs(),NPe.forEach(s=>s())}typeof window<"u"&&window.addEventListener("storage",s=>{s.key===Qot&&DXn()});const _P={getSnapshot:()=>NA,subscribe(s){return NPe.add(s),()=>NPe.delete(s)},toggle(s){const t={...NA};if(t[s.mlsNumber])delete t[s.mlsNumber];else{if(Object.keys(t).length>=jPe)return!1;t[s.mlsNumber]=s}return NA=t,$$e(t),!0},remove(s){const t={...NA};delete t[s],NA=t,$$e(t)},clear(){NA={},$$e({})},has(s){return!!NA[s]},all(){return Object.values(NA)}};function Vrs(){const s=j.useSyncExternalStore(_P.subscribe,_P.getSnapshot,_P.getSnapshot);return{selected:Object.values(s),selectedIds:new Set(Object.keys(s)),count:Object.keys(s).length,has:t=>!!s[t],toggle:_P.toggle,remove:_P.remove,clear:_P.clear}}const FXn=new Set(["office_exclusive","coming_soon","pre_market"]);function OXn(s){const t=(s.photos??[]).slice().sort((i,l)=>(l.is_primary?1:0)-(i.is_primary?1:0)||(i.sort_order??0)-(l.sort_order??0)).map(i=>i.photo_url).filter(Boolean),n=s.status||"active",r=FXn.has(n);return{mlsNumber:`lx-${s.id}`,address:s.property_address||`${s.city??""}, ${s.state??""}`.trim(),city:s.city||"",state:s.state||"",zip:s.zip_code||s.zip||"",price:Number(s.price)||0,bedrooms:Number(s.bedrooms)||0,bathrooms:Number(s.bathrooms)||0,sqft:Number(s.square_footage)||0,lotSize:s.lot_size?String(s.lot_size):"",yearBuilt:s.year_built??null,propertyType:s.property_type||"",propertySubType:null,description:s.description||"",photos:t,status:n,listDate:s.created_at||new Date().toISOString(),soldDate:null,soldPrice:null,latitude:s.latitude??null,longitude:s.longitude??null,garageSpaces:null,stories:null,hoaFee:null,hoaFrequency:null,taxAmount:null,taxYear:null,heating:null,cooling:null,basement:null,pool:null,fireplace:null,virtualTourUrl:s.virtual_tour_url??null,features:[],appliances:[],flooring:[],parking:null,waterSource:null,sewer:null,externalUrl:r?null:`https://listings.relevelup.com/${s.slug||s.id}`,is_private:r}}function gX(s){const{has:t}=Vrs(),n=`lx-${s.listing.id}`,r=t(n);return e.jsxs("div",{className:"relative",children:[e.jsx(RXn,{...s}),e.jsx("button",{type:"button",onClick:a=>{a.stopPropagation(),_P.toggle(OXn(s.listing))||re.error(`You can select up to ${jPe} listings`)},title:r?"Remove from email":"Add to email",className:`absolute top-3 right-3 z-10 h-8 w-8 rounded-full flex items-center justify-center shadow-md border transition ${r?"bg-primary text-primary-foreground border-primary":"bg-white/95 text-foreground border-white hover:bg-white"}`,children:r?e.jsx(la,{className:"h-4 w-4"}):e.jsx(mn,{className:"h-4 w-4"})})]})}function zXn({open:s,onOpenChange:t,listings:n}){const{user:r}=vs(),{leadSite:a}=ng(),[i,l]=j.useState("grid"),[o,c]=j.useState(""),[d,u]=j.useState(""),[h,m]=j.useState(""),[f,g]=j.useState(new Set),[x,y]=j.useState(!1),[v,b]=j.useState(!1),{data:w}=oie(),[S,C]=j.useState(!1);j.useEffect(()=>{!s||!(r!=null&&r.id)||q.from("gmail_integrations").select("gmail_email").eq("user_id",r.id).maybeSingle().then(({data:G})=>b(!!(G!=null&&G.gmail_email)))},[s,r==null?void 0:r.id]),j.useEffect(()=>{if(s){if(!o){const G=Array.from(new Set(n.map(X=>X.city).filter(Boolean))),Y=G.length===1?` in ${G[0]}`:"";c(n.length===1?`New listing for you${Y}`:`${n.length} hand-picked listings${Y}`)}d||u(`Hi {{first_name}}, Thought of you — I just picked a few properties I think you'll love. Take a look and let me know if anything catches your eye. Happy to set up a private showing whenever works.`)}},[s]);const{data:E=[],isLoading:I}=tt({queryKey:["send-listings-contacts",r==null?void 0:r.id],queryFn:async()=>{const{data:G}=await q.from("innercircle_contacts").select("id, first_name, last_name, email, city").eq("owner_user_id",r.id).not("email","is",null).neq("email","").order("first_name");return G||[]},enabled:!!(r!=null&&r.id)&&s}),{data:P}=tt({queryKey:["send-listings-suggestions",n.map(G=>G.mlsNumber).join(",")],queryFn:async()=>{const{data:G,error:Y}=await q.functions.invoke("listing-email-suggestions",{body:{listings:n.map(X=>({mlsNumber:X.mlsNumber,city:X.city,state:X.state,price:X.price,bedrooms:X.bedrooms,bathrooms:X.bathrooms}))}});if(Y)throw Y;return G},enabled:s&&n.length>0}),R=(P==null?void 0:P.suggestions)||[],D=j.useMemo(()=>{const G=h.trim().toLowerCase();return G?E.filter(Y=>`${Y.first_name??""} ${Y.last_name??""} ${Y.email} ${Y.city??""}`.toLowerCase().includes(G)):E},[E,h]),O=G=>{g(Y=>{const X=new Set(Y);return X.has(G)?X.delete(G):X.add(G),X})},U=()=>{g(G=>{const Y=new Set(G);return R.forEach(X=>Y.add(X.contact_id)),Y})},W=n.length>0&&n.every(G=>G.mlsNumber.startsWith("lx-")),V=async()=>{if(!W&&!(a!=null&&a.id)){re.error("You need an active lead site to send listings.");return}if(!o.trim())return re.error("Subject is required");if(f.size===0)return re.error("Pick at least one recipient");if(!v&&w&&!w.hasVerifiedSes){C(!0);return}const G=E.filter(Y=>f.has(Y.id)).map(Y=>({contact_id:Y.id,email:Y.email,first_name:Y.first_name,last_name:Y.last_name}));y(!0);try{const{data:Y,error:X}=await q.functions.invoke("listing-email-send",{body:{lead_site_id:(a==null?void 0:a.id)||null,layout:i,subject:o.trim(),intro_message:d.trim()||null,listings:n.map(ae=>({mlsNumber:ae.mlsNumber,address:ae.address,city:ae.city,state:ae.state,zip:ae.zip,price:ae.price,bedrooms:ae.bedrooms,bathrooms:ae.bathrooms,sqft:ae.sqft,status:ae.status,photos:(ae.photos||[]).slice(0,1),description:ae.description||"",external_url:ae.externalUrl||null,is_private:ae.is_private===!0})),recipients:G}});if(X)throw X;if(!(Y!=null&&Y.success))throw new Error((Y==null?void 0:Y.error)||"Send failed");re.success(`Sent ${Y.sent}/${G.length} via ${v?"Gmail":"Amazon SES"}${Y.failed?` · ${Y.failed} failed`:""}`),_P.clear(),g(new Set),t(!1)}catch(Y){re.error((Y==null?void 0:Y.message)||"Failed to send")}finally{y(!1)}};return e.jsxs(zs,{open:s,onOpenChange:t,children:[e.jsxs(Os,{className:"max-w-5xl max-h-[92vh] overflow-hidden p-0 flex flex-col",children:[e.jsxs(Us,{className:"px-6 pt-6 pb-2",children:[e.jsxs(Bs,{className:"flex items-center gap-2",children:[e.jsx(mn,{className:"h-5 w-5 text-primary"}),"Email ",n.length," ",n.length===1?"Listing":"Listings"]}),e.jsx(Ir,{children:W?"Send your Listing Exchange properties. Recipients land on listings.relevelup.com and clicks track back to the contact.":"Drive traffic to your site. Recipients land on your lead site and clicks show up on Mission Control."})]}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-0 flex-1 overflow-hidden",children:[e.jsxs("div",{className:"overflow-y-auto px-6 pb-4 space-y-4 border-r",children:[e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Selected listings"}),e.jsx("div",{className:"mt-2 flex gap-2 overflow-x-auto pb-1",children:n.map(G=>{var Y;return e.jsxs("div",{className:"shrink-0 w-32 rounded-lg overflow-hidden border bg-muted",children:[e.jsx("div",{className:"h-20 w-full bg-muted",children:((Y=G.photos)==null?void 0:Y[0])&&e.jsx("img",{src:G.photos[0],alt:"",className:"h-full w-full object-cover"})}),e.jsxs("div",{className:"p-1.5",children:[e.jsxs("div",{className:"text-[11px] font-semibold truncate",children:["$",(G.price/1e3).toFixed(0),"k"]}),e.jsxs("div",{className:"text-[10px] text-muted-foreground truncate",children:[G.city,", ",G.state]})]})]},G.mlsNumber)})})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Layout"}),e.jsxs("div",{className:"grid grid-cols-2 gap-2 mt-2",children:[e.jsxs("button",{type:"button",onClick:()=>l("grid"),className:`rounded-lg border p-3 text-left transition ${i==="grid"?"border-primary bg-primary/5":"hover:bg-muted/50"}`,children:[e.jsx(Qf,{className:"h-4 w-4 mb-1.5"}),e.jsx("div",{className:"text-sm font-medium",children:"Magazine grid"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Clean card stack"})]}),e.jsxs("button",{type:"button",onClick:()=>l("hero"),className:`rounded-lg border p-3 text-left transition ${i==="hero"?"border-primary bg-primary/5":"hover:bg-muted/50"}`,children:[e.jsx(Mc,{className:"h-4 w-4 mb-1.5"}),e.jsx("div",{className:"text-sm font-medium",children:"Hero + list"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"First listing gets spotlight"})]})]})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"subject",children:"Subject"}),e.jsx(pe,{id:"subject",value:o,onChange:G=>c(G.target.value),placeholder:"Subject line",className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"intro",children:"Personal message"}),e.jsx(Rs,{id:"intro",value:d,onChange:G=>u(G.target.value),placeholder:"Optional intro shown above the listings…",className:"mt-1 min-h-[120px]"}),e.jsxs("p",{className:"text-[11px] text-muted-foreground mt-1",children:["Use ",e.jsx("code",{className:"px-1 rounded bg-muted",children:"{{first_name}}"})," to personalize."]})]}),e.jsxs("div",{className:"rounded-lg border bg-muted/40 p-3 text-xs text-muted-foreground",children:["Sending via"," ",e.jsx("span",{className:"font-medium text-foreground",children:v?"your connected Gmail":"Amazon SES"}),". Every click tracks back to the contact and triggers a buyer signal."]})]}),e.jsxs("div",{className:"flex flex-col overflow-hidden",children:[e.jsxs("div",{className:"px-6 pt-4 pb-2 space-y-3",children:[R.length>0&&e.jsxs(Ne,{className:"p-3 bg-amber-50/50 border-amber-200",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Nn,{className:"h-4 w-4 text-amber-600"}),e.jsxs("div",{className:"text-sm font-medium",children:[R.length," smart ",R.length===1?"match":"matches"]})]}),e.jsx($,{size:"sm",variant:"outline",onClick:U,children:"Add all"})]}),e.jsx(uo,{className:"max-h-32 mt-2",children:e.jsx("div",{className:"space-y-1",children:R.slice(0,12).map(G=>{const Y=f.has(G.contact_id);return e.jsxs("label",{className:"flex items-start gap-2 text-xs py-1 cursor-pointer",children:[e.jsx(ai,{checked:Y,onCheckedChange:()=>O(G.contact_id),className:"mt-0.5"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"font-medium truncate",children:[G.first_name," ",G.last_name??""," ",e.jsxs("span",{className:"text-muted-foreground font-normal",children:["· ",G.email]})]}),e.jsx("div",{className:"text-muted-foreground truncate",children:G.reason})]})]},G.contact_id)})})})]}),e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs(ee,{className:"text-xs uppercase tracking-wide text-muted-foreground",children:["All contacts (",D.length,")"]}),f.size>0&&e.jsxs(Be,{variant:"secondary",children:[f.size," selected"]})]}),e.jsx(pe,{placeholder:"Search contacts…",value:h,onChange:G=>m(G.target.value)})]}),e.jsx("div",{className:"flex-1 overflow-hidden px-6 pb-2",children:e.jsx("div",{className:"border rounded-md h-full",children:e.jsx(uo,{className:"h-full",children:I?e.jsx("div",{className:"p-4 text-sm text-muted-foreground",children:"Loading…"}):D.length===0?e.jsx("div",{className:"p-4 text-sm text-muted-foreground text-center",children:"No contacts found"}):e.jsx("div",{className:"divide-y",children:D.map(G=>{const Y=f.has(G.id);return e.jsxs("label",{className:"flex items-center gap-2 px-3 py-2 cursor-pointer hover:bg-muted/40",children:[e.jsx(ai,{checked:Y,onCheckedChange:()=>O(G.id)}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"text-sm font-medium truncate",children:[G.first_name," ",G.last_name??""]}),e.jsxs("div",{className:"text-xs text-muted-foreground truncate",children:[G.email,G.city&&e.jsxs(e.Fragment,{children:[" · ",G.city]})]})]})]},G.id)})})})})}),e.jsxs("div",{className:"px-6 py-2 text-xs text-muted-foreground border-t flex items-center justify-between",children:[e.jsxs("span",{children:[e.jsx("strong",{className:"text-foreground",children:f.size})," recipients"]}),f.size>0&&e.jsxs($,{variant:"ghost",size:"sm",className:"h-7 text-xs",onClick:()=>g(new Set),children:[e.jsx(gr,{className:"h-3 w-3 mr-1"}),"Clear"]})]})]})]}),e.jsxs(Ar,{className:"px-6 py-4 border-t bg-muted/30",children:[e.jsx($,{variant:"outline",onClick:()=>t(!1),disabled:x,children:"Cancel"}),e.jsx($,{onClick:V,disabled:x||f.size===0,children:x?e.jsxs(e.Fragment,{children:[e.jsx(kt,{className:"h-4 w-4 mr-2 animate-spin"}),"Sending…"]}):e.jsxs(e.Fragment,{children:[e.jsx(Yr,{className:"h-4 w-4 mr-2"}),"Send to ",f.size," ",f.size===1?"contact":"contacts"]})})]})]}),e.jsx(S6e,{open:S,onOpenChange:C,hasPending:!!(w!=null&&w.hasPendingSes),pendingEmails:w==null?void 0:w.pendingEmails})]})}function BXn(){const{selected:s,count:t,remove:n,clear:r}=Vrs(),[a,i]=j.useState(!1);return t===0?null:e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"fixed bottom-4 left-1/2 -translate-x-1/2 z-50 w-[min(96vw,820px)]",children:e.jsxs("div",{className:"rounded-2xl border bg-background/95 backdrop-blur shadow-2xl p-3 flex items-center gap-3",children:[e.jsxs("div",{className:"flex items-center gap-2 px-2",children:[e.jsx("div",{className:"h-9 w-9 rounded-full bg-primary/10 text-primary flex items-center justify-center font-semibold",children:t}),e.jsxs("div",{className:"text-sm",children:[e.jsxs("div",{className:"font-medium leading-tight",children:[t," listing",t===1?"":"s"," selected"]}),e.jsx("div",{className:"text-xs text-muted-foreground",children:t>=jPe?"Max reached":`Pick up to ${jPe}`})]})]}),e.jsx("div",{className:"flex-1 overflow-x-auto hidden sm:block",children:e.jsxs("div",{className:"flex items-center gap-2",children:[s.slice(0,6).map(l=>{var o;return e.jsxs("div",{className:"group relative shrink-0 h-12 w-16 rounded-md overflow-hidden border bg-muted",title:l.address,children:[(o=l.photos)!=null&&o[0]?e.jsx("img",{src:l.photos[0],alt:"",className:"h-full w-full object-cover"}):e.jsx("div",{className:"h-full w-full"}),e.jsx("button",{"aria-label":"Remove",onClick:()=>n(l.mlsNumber),className:"absolute inset-0 bg-black/50 opacity-0 group-hover:opacity-100 flex items-center justify-center transition",children:e.jsx(gr,{className:"h-4 w-4 text-white"})})]},l.mlsNumber)}),t>6&&e.jsxs("div",{className:"shrink-0 h-12 w-12 rounded-md border bg-muted flex items-center justify-center text-xs font-medium text-muted-foreground",children:["+",t-6]})]})}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs($,{variant:"ghost",size:"sm",onClick:r,className:"gap-1.5",children:[e.jsx(Wn,{className:"h-4 w-4"})," Clear"]}),e.jsxs($,{size:"sm",className:"gap-1.5",onClick:()=>i(!0),children:[e.jsx(Yr,{className:"h-4 w-4"}),"Email these ",t===1?"listing":"listings"]})]})]})}),e.jsx(zXn,{open:a,onOpenChange:i,listings:s})]})}const $Xn=[{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"}],UXn=[{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 qXn({filters:s,onFiltersChange:t,onClose:n,showCommercial:r}){const a=s.commercial??{},i=o=>t({...s,commercial:{...a,...o}}),l=()=>{t({sortBy:"newest"})};return e.jsxs(Ne,{children:[e.jsxs(Ct,{className:"flex flex-row items-center justify-between pb-3",children:[e.jsx(At,{className:"text-lg",children:"Filters"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx($,{variant:"ghost",size:"sm",onClick:l,children:"Clear All"}),e.jsx($,{variant:"ghost",size:"icon",onClick:n,children:e.jsx(gr,{className:"h-4 w-4"})})]})]}),e.jsxs(Ie,{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(ee,{children:"Status"}),e.jsxs(ms,{value:s.status||"all",onValueChange:o=>t({...s,status:o==="all"?void 0:o}),children:[e.jsx(us,{children:e.jsx(fs,{placeholder:"All statuses"})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"all",children:"All Statuses"}),$Xn.map(o=>e.jsx(Ge,{value:o.value,children:o.label},o.value))]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Property Type"}),e.jsxs(ms,{value:s.propertyType||"all",onValueChange:o=>t({...s,propertyType:o==="all"?void 0:o}),children:[e.jsx(us,{children:e.jsx(fs,{placeholder:"All types"})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"all",children:"All Types"}),UXn.map(o=>e.jsx(Ge,{value:o.value,children:o.label},o.value))]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Min Price"}),e.jsx(pe,{type:"number",placeholder:"No minimum",value:s.minPrice||"",onChange:o=>t({...s,minPrice:o.target.value?Number(o.target.value):void 0})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Max Price"}),e.jsx(pe,{type:"number",placeholder:"No maximum",value:s.maxPrice||"",onChange:o=>t({...s,maxPrice:o.target.value?Number(o.target.value):void 0})})]})]}),r&&e.jsxs("div",{className:"mt-4 grid grid-cols-1 gap-4 border-t pt-4 sm:grid-cols-2 lg:grid-cols-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Deal Type"}),e.jsxs(ms,{value:a.dealType||"all",onValueChange:o=>i({dealType:o==="all"?void 0:o}),children:[e.jsx(us,{children:e.jsx(fs,{placeholder:"Any"})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"all",children:"Any deal type"}),Object.entries(ML).map(([o,c])=>e.jsx(Ge,{value:o,children:c},o))]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Asset Type"}),e.jsxs(ms,{value:a.commercialType||"all",onValueChange:o=>i({commercialType:o==="all"?void 0:o}),children:[e.jsx(us,{children:e.jsx(fs,{placeholder:"Any"})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"all",children:"Any asset type"}),Object.entries(c6).map(([o,c])=>e.jsx(Ge,{value:o,children:c},o))]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Min Building SF"}),e.jsx(pe,{type:"number",placeholder:"Any size",value:a.minBuildingSf??"",onChange:o=>i({minBuildingSf:o.target.value?Number(o.target.value):void 0})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Min Cap Rate (%)"}),e.jsx(pe,{type:"number",step:"0.1",placeholder:"Any",value:a.minCapRate??"",onChange:o=>i({minCapRate:o.target.value?Number(o.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(ee,{children:"Open to Referrals Only"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Show only listings accepting buyer referrals"})]}),e.jsx(Sn,{checked:s.openToReferrals||!1,onCheckedChange:o=>t({...s,openToReferrals:o||void 0})})]})]})]})}function VXn({leaderboard:s}){const t=r=>{switch(r){case 0:return e.jsx(Kl,{className:"h-5 w-5 text-amber-500"});case 1:return e.jsx(PE,{className:"h-5 w-5 text-gray-400"});case 2:return e.jsx(Rm,{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:r+1})}},n=(r,a)=>!r||r.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:r.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(Be,{variant:l===0?"default":"secondary",children:[i.count," ",a]})]},i.agentId))});return e.jsxs("div",{className:"space-y-6",children:[e.jsxs(Ne,{children:[e.jsx(Ct,{children:e.jsxs(At,{className:"flex items-center gap-2",children:[e.jsx(Kl,{className:"h-5 w-5 text-amber-500"}),"Community Badges"]})}),e.jsx(Ie,{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(zd,{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(va,{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(PE,{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(Kl,{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(Ne,{children:[e.jsx(Ct,{children:e.jsx(At,{children:"Community Leaderboard"})}),e.jsx(Ie,{children:e.jsxs(ha,{defaultValue:"sharers",children:[e.jsxs(ma,{className:"w-full",children:[e.jsxs(Zt,{value:"sharers",className:"flex-1",children:[e.jsx(zd,{className:"h-4 w-4 mr-2"}),"Top Sharers"]}),e.jsxs(Zt,{value:"listers",className:"flex-1",children:[e.jsx(va,{className:"h-4 w-4 mr-2"}),"Top Contributors"]})]}),e.jsx(Xt,{value:"sharers",className:"mt-4",children:n(s==null?void 0:s.topSharers,"shares")}),e.jsx(Xt,{value:"listers",className:"mt-4",children:n(s==null?void 0:s.topListers,"listings")})]})})]})]})}const S3t={coming_soon:"#F59E0B",office_exclusive:"#6366F1",pre_market:"#06B6D4",active:"#10B981",price_improvement:"#8B5CF6",under_contract:"#3B82F6",sold:"#A855F7"},C3t={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 HXn(s){return s>=1e6?`$${(s/1e6).toFixed(1)}M`:`$${(s/1e3).toFixed(0)}K`}function GXn({listings:s,isLoading:t}){const n=Qn(),r=j.useRef(null),a=j.useRef(null),i=j.useRef([]),{isAdmin:l}=vs(),[o,c]=j.useState(""),[d,u]=j.useState(!0),[h,m]=j.useState(!1),f=s.filter(x=>x.latitude!=null&&x.longitude!=null),g=s.filter(x=>(x.latitude==null||x.longitude==null)&&(x.property_address||x.city));return j.useEffect(()=>{(async()=>{u(!0);try{const{data:y}=await q.from("settings").select("value").eq("key","mapbox_public_token").maybeSingle();y!=null&&y.value&&c(y.value)}catch(y){console.error("Error fetching mapbox token:",y)}u(!1)})()},[]),j.useEffect(()=>{if(!o||g.length===0||h)return;(async()=>{var y;m(!0);for(const v of g){const b=[v.property_address,v.city,v.state].filter(Boolean).join(", ");if(b)try{const S=await(await fetch(`https://api.mapbox.com/geocoding/v5/mapbox.places/${encodeURIComponent(b)}.json?access_token=${o}&limit=1`)).json();if((y=S.features)!=null&&y[0]){const[C,E]=S.features[0].center;await q.from("listings").update({latitude:E,longitude:C}).eq("id",v.id),v.latitude=E,v.longitude=C}}catch(w){console.error("Geocode error:",w)}}m(!1)})()},[o,s]),j.useEffect(()=>{if(!r.current||!o||a.current)return;ju.accessToken=o;const x=s.filter(b=>b.latitude!=null&&b.longitude!=null);let y=[-98.5795,39.8283],v=4;if(x.length>0){const b=x.reduce((S,C)=>S+C.longitude,0)/x.length,w=x.reduce((S,C)=>S+C.latitude,0)/x.length;y=[b,w],v=x.length===1?12:10}return a.current=new ju.Map({container:r.current,style:"mapbox://styles/mapbox/light-v11",zoom:v,center:y}),a.current.addControl(new ju.NavigationControl,"top-right"),()=>{var b;(b=a.current)==null||b.remove(),a.current=null}},[o]),j.useEffect(()=>{if(!a.current||!o)return;i.current.forEach(y=>y.remove()),i.current=[];const x=s.filter(y=>y.latitude!=null&&y.longitude!=null);if(x.forEach(y=>{var E,I,P;const v=S3t[y.status]||"#10B981",b=((E=y.photos)==null?void 0:E.find(R=>R.is_primary))||((I=y.photos)==null?void 0:I[0]),w=document.createElement("div");w.className="cursor-pointer",w.innerHTML=`
`;const S=new ju.Popup({offset:25,closeButton:!0,maxWidth:"280px"}).setHTML(`
${b!=null&&b.photo_url?``:""}
${HXn(y.price)}
${y.property_address||""}
${y.city}, ${y.state}
${C3t[y.status]||y.status} ${y.bedrooms?`${y.bedrooms} bed`:""} ${y.bathrooms?`${y.bathrooms} bath`:""}
${(P=y.agent)!=null&&P.name?`
Listed by ${y.agent.name}
`:""}
Click to view details →
`),C=new ju.Marker(w).setLngLat([y.longitude,y.latitude]).setPopup(S).addTo(a.current);i.current.push(C)}),x.length>1){const y=new ju.LngLatBounds;x.forEach(v=>y.extend([v.longitude,v.latitude])),a.current.fitBounds(y,{padding:60,maxZoom:13})}else x.length===1&&a.current.flyTo({center:[x[0].longitude,x[0].latitude],zoom:12})},[s,o,h]),j.useEffect(()=>(window.__navigateToListing__=x=>{n(`/mission-control/listings/${x}`)},()=>{delete window.__navigateToListing__}),[n]),d||t?e.jsx(Ne,{children:e.jsx(Ie,{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(Ne,{children:e.jsxs(Ie,{className:"flex flex-col items-center justify-center h-[60vh] text-center gap-3",children:[e.jsx(ci,{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(S3t).map(([x,y])=>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:y}}),e.jsx("span",{className:"text-xs",children:C3t[x]})]},x)),e.jsxs("span",{className:"text-muted-foreground ml-auto text-xs",children:[f.length," of ",s.length," mapped",h&&" · Geocoding..."]})]}),e.jsx("div",{ref:r,className:"w-full h-[60vh] rounded-lg shadow-lg border"})]}):e.jsx(Ne,{children:e.jsxs(Ie,{className:"flex flex-col items-center justify-center h-[60vh] text-center gap-3",children:[e.jsx(ll,{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 zXe="homereel_mv_prefill",BXe="homereel_mv_badge_default";function Hrs(s){try{sessionStorage.setItem(zXe,JSON.stringify(s)),s.badge&&s.badge.type!=="none"&&sessionStorage.setItem(BXe,JSON.stringify(s.badge))}catch{}}function ACr(){try{const s=sessionStorage.getItem(zXe);return s?(sessionStorage.removeItem(zXe),JSON.parse(s)):null}catch{return null}}function ECr(){try{const s=sessionStorage.getItem(BXe);return s?(sessionStorage.removeItem(BXe),JSON.parse(s)):null}catch{return null}}function Grs(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 WXn(){var X,ae,ie,ne,te,J,ce,_e;const s=Qn(),{brokerageId:t}=vs(),{data:n,isLoading:r}=F$t(),[a,i]=j.useState("feed"),[l,o]=j.useState(!1),[c,d]=j.useState(null),[u,h]=j.useState(""),[m,f]=j.useState("all"),[g,x]=j.useState({sortBy:"newest"}),{data:y,isLoading:v}=O$t({...g,listingClass:m==="all"?void 0:m,city:u||g.city}),{data:b,isLoading:w}=Iqs(),{data:S,isLoading:C}=Qst(),{data:E,isLoading:I}=Fqs(),{data:P,isLoading:R}=Bqs(),{data:D}=zqs(),O=$$t(),U=g.commercial,W=(y??[]).filter(he=>{if(!U||he.listing_class!=="commercial")return!U||Object.values(U).every(ve=>ve===void 0)||he.listing_class!=="commercial";const ue=he.commercial??{};return!(U.dealType&&ue.deal_type!==U.dealType||U.commercialType&&ue.commercial_type!==U.commercialType||U.minBuildingSf&&Number(ue.building_sf??0)he.lifecycle_stage==="pitch"),G=he=>s(he.listing_class==="commercial"?`/mission-control/listings/${he.id}/commercial`:`/mission-control/listings/${he.id}`),Y=async he=>{if(await fo("Are you sure you want to delete this listing? This action cannot be undone."))try{await O.mutateAsync(he),re.success("Listing deleted successfully")}catch{re.error("Failed to delete listing")}};return r?e.jsx(Vs,{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"})})}):n?e.jsxs(Vs,{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($,{onClick:()=>s("/mission-control/listings/new"),children:[e.jsx(dn,{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(Ne,{children:e.jsxs(Ie,{className:"p-4 flex items-center gap-3",children:[e.jsx("div",{className:"p-2 bg-primary/10 rounded-lg",children:e.jsx(va,{className:"h-5 w-5 text-primary"})}),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:"Active Listings"})]})]})}),e.jsx(Ne,{children:e.jsxs(Ie,{className:"p-4 flex items-center gap-3",children:[e.jsx("div",{className:"p-2 bg-pink-500/10 rounded-lg",children:e.jsx(Jo,{className:"h-5 w-5 text-pink-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:"Saved"})]})]})}),e.jsx(Ne,{children:e.jsxs(Ie,{className:"p-4 flex items-center gap-3",children:[e.jsx("div",{className:"p-2 bg-emerald-500/10 rounded-lg",children:e.jsx(VI,{className:"h-5 w-5 text-emerald-500"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:(S==null?void 0:S.length)||0}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"My Listings"})]})]})}),e.jsx(Ne,{children:e.jsxs(Ie,{className:"p-4 flex items-center gap-3",children:[e.jsx("div",{className:"p-2 bg-sky-500/10 rounded-lg",children:e.jsx(Zn,{className:"h-5 w-5 text-sky-500"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:(((X=E==null?void 0:E.sent)==null?void 0:X.length)||0)+(((ae=E==null?void 0:E.received)==null?void 0:ae.length)||0)}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Referrals"})]})]})})]}),e.jsxs(ha,{value:a,onValueChange:i,children:[e.jsxs(ma,{className:"w-full justify-start overflow-x-auto",children:[e.jsx(Zt,{value:"feed",children:"Community Feed"}),t&&e.jsx(Zt,{value:"brokerage",children:"Brokerage"}),e.jsx(Zt,{value:"my-listings",children:"My Listings"}),V.length>0&&e.jsxs(Zt,{value:"pitches",children:["Pitches (",V.length,")"]}),e.jsx(Zt,{value:"saved",children:"Saved"}),e.jsx(Zt,{value:"referrals",children:"Referrals"}),e.jsx(Zt,{value:"map",children:"Map"}),e.jsx(Zt,{value:"leaderboard",children:"Leaderboard"})]}),e.jsxs(Xt,{value:"feed",className:"space-y-4",children:[e.jsx("div",{className:"inline-flex rounded-lg border bg-muted/40 p-1",children:["all","residential","commercial"].map(he=>e.jsx("button",{type:"button",onClick:()=>f(he),className:`rounded-md px-4 py-1.5 text-sm font-medium capitalize transition ${m===he?"bg-background shadow-sm":"text-muted-foreground hover:text-foreground"}`,children:he==="all"?"All listings":he},he))}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-3",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(Kr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(pe,{placeholder:"Search by city or neighborhood...",value:u,onChange:he=>h(he.target.value),className:"pl-9"})]}),e.jsxs(ms,{value:g.sortBy,onValueChange:he=>x({...g,sortBy:he}),children:[e.jsx(us,{className:"w-[180px]",children:e.jsx(fs,{placeholder:"Sort by"})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"newest",children:"Newest First"}),e.jsx(Ge,{value:"updated",children:"Recently Updated"}),e.jsx(Ge,{value:"price_asc",children:"Price: Low to High"}),e.jsx(Ge,{value:"price_desc",children:"Price: High to Low"})]})]}),e.jsxs($,{variant:"outline",onClick:()=>o(!l),children:[e.jsx(Iw,{className:"h-4 w-4 mr-2"}),"Filters"]})]}),l&&e.jsx(qXn,{filters:g,onFiltersChange:x,onClose:()=>o(!1),showCommercial:m!=="residential"}),v?e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:[...Array(6)].map((he,ue)=>e.jsxs(Ne,{children:[e.jsx(yn,{className:"h-48 w-full"}),e.jsxs(Ie,{className:"p-4 space-y-2",children:[e.jsx(yn,{className:"h-5 w-3/4"}),e.jsx(yn,{className:"h-4 w-1/2"}),e.jsx(yn,{className:"h-4 w-1/4"})]})]},ue))}):(y==null?void 0:y.length)===0?e.jsx(Ne,{children:e.jsxs(Ie,{className:"py-12 text-center",children:[e.jsx(va,{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($,{onClick:()=>s("/mission-control/listings/new"),children:[e.jsx(dn,{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:W.map(he=>e.jsx(gX,{listing:he,onClick:()=>G(he)},he.id))})]}),e.jsx(Xt,{value:"my-listings",className:"space-y-4",children:C?e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:[...Array(3)].map((he,ue)=>e.jsxs(Ne,{children:[e.jsx(yn,{className:"h-48 w-full"}),e.jsxs(Ie,{className:"p-4 space-y-2",children:[e.jsx(yn,{className:"h-5 w-3/4"}),e.jsx(yn,{className:"h-4 w-1/2"})]})]},ue))}):(S==null?void 0:S.length)===0?e.jsx(Ne,{children:e.jsxs(Ie,{className:"py-12 text-center",children:[e.jsx(VI,{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($,{onClick:()=>s("/mission-control/listings/new"),children:[e.jsx(dn,{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:S==null?void 0:S.map(he=>e.jsx(gX,{listing:he,showActions:!0,onClick:()=>G(he),onEdit:()=>s(he.listing_class==="commercial"?`/mission-control/listings/${he.id}/commercial`:`/mission-control/listings/${he.id}/edit`),onDelete:()=>Y(he.id),onLaunchKit:()=>d(he),onCreateMusicVideo:()=>{const ue=(he.photos??[]).slice().sort((ve,Ee)=>(Ee.is_primary?1:0)-(ve.is_primary?1:0)||(ve.sort_order??0)-(Ee.sort_order??0)).map(ve=>ve.photo_url).filter(Boolean);if(ue.length===0){re.error("Add photos to this listing first.");return}Hrs({photos:ue,details:{address:he.property_address||`${he.city??""} ${he.state??""}`.trim(),beds:he.bedrooms?String(he.bedrooms):"",baths:he.bathrooms?String(he.bathrooms):"",sqft:he.square_footage?String(he.square_footage):"",price:he.price?String(he.price):"",highlights:he.description||""},sourceLabel:"My Listings",badge:Grs(he.status,he.price)}),s("/admin/beta/homereel?tab=music-video")}},he.id))})}),e.jsxs(Xt,{value:"pitches",className:"space-y-4",children:[e.jsx(Ne,{className:"border-dashed",children:e.jsx(Ie,{className:"py-4 text-sm text-muted-foreground",children:"Pitches are private to you. They never appear in the Exchange, public search, or sitemaps until you mark the assignment as won."})}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:V.map(he=>e.jsx(gX,{listing:he,showActions:!0,onClick:()=>s(`/mission-control/listings/${he.id}/commercial`),onEdit:()=>s(`/mission-control/listings/${he.id}/commercial`),onDelete:()=>Y(he.id)},he.id))})]}),e.jsx(Xt,{value:"saved",className:"space-y-4",children:w?e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:[...Array(3)].map((he,ue)=>e.jsxs(Ne,{children:[e.jsx(yn,{className:"h-48 w-full"}),e.jsxs(Ie,{className:"p-4 space-y-2",children:[e.jsx(yn,{className:"h-5 w-3/4"}),e.jsx(yn,{className:"h-4 w-1/2"})]})]},ue))}):(b==null?void 0:b.length)===0?e.jsx(Ne,{children:e.jsxs(Ie,{className:"py-12 text-center",children:[e.jsx(Jo,{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:b==null?void 0:b.map(he=>e.jsx(gX,{listing:he.listing,onClick:()=>G(he.listing)},he.id))})}),e.jsx(Xt,{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(zd,{className:"h-4 w-4"}),"Referrals Sent (",((ie=E==null?void 0:E.sent)==null?void 0:ie.length)||0,")"]}),((ne=E==null?void 0:E.sent)==null?void 0:ne.length)===0?e.jsx(Ne,{children:e.jsx(Ie,{className:"py-8 text-center text-muted-foreground",children:"No referrals sent yet"})}):e.jsx("div",{className:"space-y-3",children:(te=E==null?void 0:E.sent)==null?void 0:te.map(he=>{var ue,ve;return e.jsx(Ne,{children:e.jsx(Ie,{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:he.buyer_name}),e.jsx("p",{className:"text-sm text-muted-foreground",children:((ue=he.listing)==null?void 0:ue.property_address)||((ve=he.listing)==null?void 0:ve.city)})]}),e.jsx(Be,{variant:he.status==="closed"?"default":"secondary",children:he.status.replace("_"," ")})]})})},he.id)})})]}),e.jsxs("div",{children:[e.jsxs("h3",{className:"font-semibold mb-3 flex items-center gap-2",children:[e.jsx(Zn,{className:"h-4 w-4"}),"Referrals Received (",((J=E==null?void 0:E.received)==null?void 0:J.length)||0,")"]}),((ce=E==null?void 0:E.received)==null?void 0:ce.length)===0?e.jsx(Ne,{children:e.jsx(Ie,{className:"py-8 text-center text-muted-foreground",children:"No referrals received yet"})}):e.jsx("div",{className:"space-y-3",children:(_e=E==null?void 0:E.received)==null?void 0:_e.map(he=>{var ue;return e.jsx(Ne,{children:e.jsxs(Ie,{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:he.buyer_name}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:["From: ",(ue=he.sender)==null?void 0:ue.name]})]}),e.jsx(Be,{variant:he.status==="closed"?"default":"secondary",children:he.status.replace("_"," ")})]}),e.jsx($,{size:"sm",variant:"outline",className:"w-full mt-2",onClick:()=>s(`/mission-control/listings/${he.listing_id}`),children:"View Listing"})]})},he.id)})})]})]})}),t&&e.jsx(Xt,{value:"brokerage",className:"space-y-4",children:R?e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:[...Array(3)].map((he,ue)=>e.jsxs(Ne,{children:[e.jsx(yn,{className:"h-48 w-full"}),e.jsxs(Ie,{className:"p-4 space-y-2",children:[e.jsx(yn,{className:"h-5 w-3/4"}),e.jsx(yn,{className:"h-4 w-1/2"})]})]},ue))}):(P==null?void 0:P.length)===0?e.jsx(Ne,{children:e.jsxs(Ie,{className:"py-12 text-center",children:[e.jsx(VI,{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($,{onClick:()=>s("/mission-control/listings/new"),children:[e.jsx(dn,{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:P==null?void 0:P.map(he=>e.jsx(gX,{listing:he,onClick:()=>G(he)},he.id))})}),e.jsx(Xt,{value:"map",children:e.jsx(GXn,{listings:y||[],isLoading:v})}),e.jsx(Xt,{value:"leaderboard",children:e.jsx(VXn,{leaderboard:D})})]})]}),e.jsx(BXn,{}),e.jsx(Urs,{listingId:(c==null?void 0:c.id)??null,open:!!c,onOpenChange:he=>!he&&d(null),listingAddress:c==null?void 0:c.property_address,listingSlug:(c==null?void 0:c.slug)??null})]}):e.jsx(Vs,{title:"Listing Exchange",description:"Community-powered listing collaboration",children:e.jsx(Ne,{children:e.jsxs(Ie,{className:"py-12 text-center",children:[e.jsx(va,{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!"})]})})})}const KXn=s=>s<1024?`${s} B`:s<1024*1024?`${(s/1024).toFixed(0)} KB`:`${(s/(1024*1024)).toFixed(1)} MB`;function YXn({listingId:s,ownerOnly:t=!1}){const{data:n=[]}=d6e(s),r=t?n:n.filter(i=>i.visible_on_exchange);if(r.length===0)return null;const a=async i=>{try{const l=await Jst(i);window.open(l,"_blank")}catch{re.error("Failed to open document")}};return e.jsxs(Ne,{children:[e.jsx(Ct,{children:e.jsxs(At,{className:"text-lg flex items-center gap-2",children:[e.jsx(Jr,{className:"h-5 w-5"}),"Documents & Disclosures (",r.length,")"]})}),e.jsx(Ie,{children:e.jsx("div",{className:"space-y-2",children:r.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(Jr,{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:KXn(i.file_size)})]}),e.jsx(di,{className:"h-4 w-4 text-muted-foreground group-hover:text-primary"})]},i.id))})})]})}function jw(s){const t=s.expected_commission,n=Number(s.bonus_amount)||0;if(!t)return n>0?n:null;if((s.commission_calc_method||"standard")==="referral_first"){let i=t;s.referral_fee_pct&&(i-=t*(s.referral_fee_pct/100));let l=i;return s.brokerage_split_pct&&(l-=i*(s.brokerage_split_pct/100)),s.team_split_pct&&(l-=t*(s.team_split_pct/100)),s.franchise_fee_pct&&(l-=t*(s.franchise_fee_pct/100)),s.transaction_fee&&(l-=s.transaction_fee),Math.max(0,l)+n}let a=t;return s.brokerage_split_pct&&(a-=t*(s.brokerage_split_pct/100)),s.team_split_pct&&(a-=t*(s.team_split_pct/100)),s.franchise_fee_pct&&(a-=t*(s.franchise_fee_pct/100)),s.referral_fee_pct&&(a-=t*(s.referral_fee_pct/100)),s.transaction_fee&&(a-=s.transaction_fee),Math.max(0,a)+n}function Jie(){const s=Sa();return tt({queryKey:["deal-pipeline-stages",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await q.from("deal_pipeline_stages").select("*").eq("owner_user_id",s).order("sort_order",{ascending:!0});if(n)throw n;return t},enabled:!!s})}function Wrs(){const s=Sa(),t=Vt();return ft({mutationFn:async()=>{if(!s)throw new Error("Not authenticated");const{error:n}=await q.rpc("initialize_deal_pipeline_stages",{p_user_id:s});if(n)throw n},onSuccess:()=>{t.invalidateQueries({queryKey:["deal-pipeline-stages"]})}})}function rY(){const s=Sa();return tt({queryKey:["deal-pipeline-deals",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await q.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(n)throw n;return t},enabled:!!s})}function Krs(){const s=Sa(),t=Vt();return ft({mutationFn:async n=>{if(!s)throw new Error("Not authenticated");const{data:r,error:a}=await q.from("deal_pipeline").insert({deal_name:n.deal_name,deal_type:n.deal_type,stage_id:n.stage_id||null,contact_id:n.contact_id||null,listing_id:n.listing_id||null,property_address:n.property_address||null,city:n.city||null,state:n.state||null,zip_code:n.zip_code||null,expected_price:n.expected_price||null,expected_commission:n.expected_commission||null,commission_percentage:n.commission_percentage||3,target_close_date:n.target_close_date||null,contract_date:n.contract_date||null,listing_date:n.listing_date||null,priority:n.priority||"medium",probability:n.probability||50,notes:n.notes||null,owner_user_id:s}).select().single();if(a)throw a;return await q.from("deal_activities").insert([{deal_id:r.id,activity_type:"system",title:"Deal created",description:`Deal "${n.deal_name}" was created`}]),r},onSuccess:()=>{t.invalidateQueries({queryKey:["deal-pipeline-deals"]}),t.invalidateQueries({queryKey:["deal-pipeline-stats"]})}})}function Yrs(){const s=Vt();return ft({mutationFn:async({id:t,...n})=>{const{data:r,error:a}=await q.from("deal_pipeline").update(n).eq("id",t).select().single();if(a)throw a;return r},onSuccess:()=>{s.invalidateQueries({queryKey:["deal-pipeline-deals"]}),s.invalidateQueries({queryKey:["deal-pipeline-stats"]})}})}function ZXn(){const s=Vt();return ft({mutationFn:async({dealId:t,stageId:n,stageName:r})=>{const{data:a}=await q.from("deal_pipeline_stages").select("default_probability").eq("id",n).maybeSingle(),i={stage_id:n};typeof(a==null?void 0:a.default_probability)=="number"&&(i.probability=a.default_probability);const{data:l,error:o}=await q.from("deal_pipeline").update(i).eq("id",t).select().single();if(o)throw o;return await q.from("deal_activities").insert({deal_id:t,activity_type:"stage_change",title:`Moved to ${r}`,metadata:{new_stage_id:n,new_stage_name:r}}),l},onSuccess:()=>{s.invalidateQueries({queryKey:["deal-pipeline-deals"]}),s.invalidateQueries({queryKey:["deal-activities"]})}})}function XXn(){const s=Vt();return ft({mutationFn:async t=>{const{error:n}=await q.from("deal_pipeline").delete().eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["deal-pipeline-deals"]}),s.invalidateQueries({queryKey:["deal-pipeline-stats"]})}})}function QXn(s){return tt({queryKey:["deal-activities",s],queryFn:async()=>{const{data:t,error:n}=await q.from("deal_activities").select("*").eq("deal_id",s).order("created_at",{ascending:!1});if(n)throw n;return t},enabled:!!s})}function JXn(){const s=Vt();return ft({mutationFn:async t=>{const{data:n,error:r}=await q.from("deal_activities").insert([{deal_id:t.deal_id,activity_type:t.activity_type,title:t.title,description:t.description||null}]).select().single();if(r)throw r;return n},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["deal-activities",n.deal_id]})}})}function eQn(s){return tt({queryKey:["deal-checklist",s],queryFn:async()=>{const{data:t,error:n}=await q.from("deal_checklist_items").select("*").eq("deal_id",s).order("sort_order",{ascending:!0});if(n)throw n;return t},enabled:!!s})}function tQn(){const s=Vt();return ft({mutationFn:async({id:t,is_completed:n,deal_id:r})=>{const{data:a,error:i}=await q.from("deal_checklist_items").update({is_completed:n,completed_at:n?new Date().toISOString():null}).eq("id",t).select().single();if(i)throw i;return a},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["deal-checklist",n.deal_id]})}})}function sQn(){const s=Vt();return ft({mutationFn:async t=>{const{data:n,error:r}=await q.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(r)throw r;return n},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["deal-checklist",n.deal_id]})}})}function nQn(){const s=Sa();return tt({queryKey:["deal-pipeline-stats",s],queryFn:async()=>{if(!s)return null;const{data:t,error:n}=await q.from("deal_pipeline").select("*, deal_pipeline_stages(name, is_won_stage, is_lost_stage)").eq("owner_user_id",s);if(n)throw n;const r=(t==null?void 0:t.filter(o=>{var c,d,u;return!((c=o.deal_pipeline_stages)!=null&&c.is_won_stage)&&!((d=o.deal_pipeline_stages)!=null&&d.is_lost_stage)&&((u=o.deal_pipeline_stages)==null?void 0:u.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:r.length,wonDeals:a.length,pipelineValue:r.reduce((o,c)=>o+(c.expected_price||0),0),expectedCommission:r.reduce((o,c)=>o+(c.expected_commission||0)+(c.bonus_amount||0),0),expectedNetToAgent:r.reduce((o,c)=>o+(jw(c)||0),0),wonValue:a.reduce((o,c)=>o+(c.expected_price||0),0),weightedGCI:r.reduce((o,c)=>{const d=(c.probability??50)/100;return o+((c.expected_commission||0)+(c.bonus_amount||0))*d},0),weightedNet:r.reduce((o,c)=>{const d=(c.probability??50)/100;return o+(jw(c)||0)*d},0),ytdWonDeals:l.length,ytdWonGCI:l.reduce((o,c)=>o+(c.expected_commission||0)+(c.bonus_amount||0),0),ytdWonNet:l.reduce((o,c)=>o+(jw(c)||0),0),projectedAnnualNet:l.reduce((o,c)=>o+(jw(c)||0),0)+r.reduce((o,c)=>{const d=(c.probability??50)/100;return o+(jw(c)||0)*d},0)}},enabled:!!s})}function rQn(s){const t=Sa();return tt({queryKey:["deal-by-listing",s,t],queryFn:async()=>{if(!t||!s)return null;const{data:n,error:r}=await q.from("deal_pipeline").select(` *, deal_pipeline_stages(id, name, color) `).eq("owner_user_id",t).eq("listing_id",s).maybeSingle();if(r)throw r;return n},enabled:!!t&&!!s})}function aQn(){const s=Vt();return ft({mutationFn:async({dealId:t,listingId:n})=>{const{data:r,error:a}=await q.from("deal_pipeline").update({listing_id:n}).eq("id",t).select().single();if(a)throw a;return await q.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:n}}),r},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["deal-pipeline-deals"]}),s.invalidateQueries({queryKey:["deal-by-listing",n.listingId]})}})}function iQn(){const s=Vt();return ft({mutationFn:async({dealId:t,listingId:n})=>{const{data:r,error:a}=await q.from("deal_pipeline").update({listing_id:null}).eq("id",t).select().single();if(a)throw a;return{data:r,listingId:n}},onSuccess:t=>{s.invalidateQueries({queryKey:["deal-pipeline-deals"]}),s.invalidateQueries({queryKey:["deal-by-listing",t.listingId]})}})}function oQn({listing:s}){const t=Qn(),[n,r]=j.useState(""),[a,i]=j.useState(!1),{data:l,isLoading:o}=rQn(s.id),{data:c,isLoading:d}=Jie(),{data:u,isLoading:h}=rY(),m=Wrs(),f=aQn(),g=iQn(),x=Krs(),y=(u==null?void 0:u.filter(C=>!C.listing_id))||[],v=C=>{if(!(c!=null&&c.length))return null;switch(C){case"coming_soon":case"active":case"price_improvement":return c.find(E=>E.name==="Active");case"under_contract":return c.find(E=>E.name==="Under Contract");case"sold":return c.find(E=>E.is_won_stage);default:return c.find(E=>E.name==="Active")}},b=async()=>{i(!0);try{c!=null&&c.length||await m.mutateAsync();const C=v(s.status);await x.mutateAsync({deal_name:s.property_address?`${s.property_address}, ${s.city}`:`${s.city}, ${s.state}`,deal_type:"seller",stage_id:(C==null?void 0:C.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}),re.success("Deal created and linked to listing!")}catch(C){console.error("Failed to create deal:",C),re.error("Failed to create deal")}finally{i(!1)}},w=async()=>{if(!n){re.error("Please select a deal");return}try{await f.mutateAsync({dealId:n,listingId:s.id}),re.success("Listing linked to deal!"),r("")}catch{re.error("Failed to link listing")}},S=async()=>{if(l)try{await g.mutateAsync({dealId:l.id,listingId:s.id}),re.success("Listing unlinked from deal")}catch{re.error("Failed to unlink listing")}};return o||d?e.jsxs(Ne,{children:[e.jsx(Ct,{children:e.jsxs(At,{className:"flex items-center gap-2 text-base",children:[e.jsx(h2,{className:"h-4 w-4"}),"Deal Pipeline"]})}),e.jsx(Ie,{children:e.jsx("div",{className:"flex items-center justify-center py-4",children:e.jsx(kt,{className:"h-5 w-5 animate-spin text-muted-foreground"})})})]}):l?e.jsxs(Ne,{className:"border-primary/20 bg-primary/5",children:[e.jsx(Ct,{className:"pb-2",children:e.jsxs(At,{className:"flex items-center gap-2 text-base",children:[e.jsx(bd,{className:"h-4 w-4 text-primary"}),"Linked to Pipeline"]})}),e.jsxs(Ie,{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(Be,{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($,{variant:"outline",size:"sm",className:"flex-1",onClick:()=>t("/mission-control/pipeline"),children:["View Pipeline",e.jsx(ei,{className:"h-3 w-3 ml-1"})]}),e.jsx($,{variant:"ghost",size:"sm",onClick:S,disabled:g.isPending,children:g.isPending?e.jsx(kt,{className:"h-4 w-4 animate-spin"}):e.jsx($E,{className:"h-4 w-4"})})]})]})]}):e.jsxs(Ne,{children:[e.jsx(Ct,{className:"pb-2",children:e.jsxs(At,{className:"flex items-center gap-2 text-base",children:[e.jsx(h2,{className:"h-4 w-4"}),"Deal Pipeline"]})}),e.jsxs(Ie,{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($,{onClick:b,disabled:a||x.isPending,className:"w-full",size:"sm",children:[a||x.isPending?e.jsx(kt,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(dn,{className:"h-4 w-4 mr-2"}),"Create New Deal"]}),y.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(ms,{value:n,onValueChange:r,children:[e.jsx(us,{className:"flex-1 text-sm",children:e.jsx(fs,{placeholder:"Link to existing deal..."})}),e.jsx(hs,{children:y.map(C=>e.jsx(Ge,{value:C.id,children:C.deal_name},C.id))})]}),e.jsx($,{variant:"secondary",size:"icon",onClick:w,disabled:!n||f.isPending,children:f.isPending?e.jsx(kt,{className:"h-4 w-4 animate-spin"}):e.jsx(bd,{className:"h-4 w-4"})})]})]})]})]})}const lQn={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"},cQn={active:"Active",coming_soon:"Coming Soon",office_exclusive:"Office Exclusive",pre_market:"Pre-Market",price_improvement:"Price Improvement",under_contract:"Under Contract",sold:"Sold"},A3t={single_family:"Single Family",condo:"Condo",townhouse:"Townhouse",land:"Land",multi_family:"Multi-Family",luxury:"Luxury",commercial:"Commercial",other:"Other"};function dQn(){var he,ue,ve,Ee,Se,Le,Fe,ke,Ve;const{listingId:s}=Wi(),t=Qn(),{user:n,isAdmin:r}=vs(),{data:a,isLoading:i}=tie(s||""),{data:l}=W$t(s||""),{data:o}=Rqs(s||""),c=G$t(),d=Lqs(),u=Dqs(),h=$$t(),m=Oqs(),[f,g]=j.useState(!1),[x,y]=j.useState(!1),[v,b]=j.useState(!1),[w,S]=j.useState(!1),[C,E]=gc();j.useEffect(()=>{C.get("launchkit")==="1"&&(S(!0),C.delete("launchkit"),E(C,{replace:!0}))},[C,E]);const[I,P]=j.useState(!1),[R,D]=j.useState(!1),[O,U]=j.useState(!1),[W,V]=j.useState(null),[G,Y]=j.useState({buyerName:"",buyerType:"",notes:""}),X=D$t(a==null?void 0:a.agent_id),ae=(n==null?void 0:n.id)===(a==null?void 0:a.agent_id)||X,ie=je=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(je),ne=async je=>{const Ae=`https://listings.relevelup.com/${(a==null?void 0:a.slug)||(a==null?void 0:a.id)}`,Ce=`Check out this listing: ${(a==null?void 0:a.property_address)||(a==null?void 0:a.city)}`;u.mutate({listingId:a.id,shareType:je});try{switch(je){case"facebook":window.open(`https://www.facebook.com/sharer/sharer.php?u=${encodeURIComponent(Ae)}`,"_blank");break;case"copy":await navigator.clipboard.writeText(Ae),re.success("Link copied to clipboard!");break;case"text":window.open(`sms:?body=${encodeURIComponent(`${Ce} ${Ae}`)}`);break;case"email":window.open(`mailto:?subject=${encodeURIComponent(Ce)}&body=${encodeURIComponent(`Check out this listing: ${Ae}`)}`);break}}catch(qe){console.error("Share error:",qe),re.error("Failed to share")}},te=async()=>{try{await h.mutateAsync(a.id),re.success("Listing deleted"),t("/mission-control/listings")}catch{re.error("Failed to delete listing")}},J=async()=>{if(!G.buyerName.trim()){re.error("Please enter buyer name");return}try{await m.mutateAsync({listingId:a.id,listingAgentId:a.agent_id,buyerName:G.buyerName,buyerType:G.buyerType||void 0,notes:G.notes||void 0}),re.success("Referral sent successfully!"),y(!1),Y({buyerName:"",buyerType:"",notes:""})}catch{re.error("Failed to send referral")}},ce=je=>{var Xe,it;const Ae=(a==null?void 0:a.property_address)||`${a==null?void 0:a.city}, ${a==null?void 0:a.state}`,Ce=ie((a==null?void 0:a.price)||0),qe=a!=null&&a.bedrooms?`${a.bedrooms}BD`:"",ze=a!=null&&a.bathrooms?`${a.bathrooms}BA`:"",$e=a!=null&&a.square_footage?`${a.square_footage.toLocaleString()}SF`:"",ct=[qe,ze,$e].filter(Boolean).join(" | ");switch(je){case"just_listed":return`🏡 JUST LISTED! ${Ae} ${Ce} ${ct} ${(a==null?void 0:a.description)||"Schedule your showing today!"} #JustListed #RealEstate #HomeForSale #${(Xe=a==null?void 0:a.city)==null?void 0:Xe.replace(/\s/g,"")}`;case"price_improvement":return`📣 PRICE IMPROVEMENT! ${Ae} Now ${Ce}! ${ct} Don't miss this opportunity! #PriceReduced #RealEstate #HomeForSale`;case"teaser":return`Looking for a ${A3t[(a==null?void 0:a.property_type)||"single_family"].toLowerCase()} in ${a==null?void 0:a.city}? 👀 I've got just the one for you! ${ct} DM me for details! 📩 #ComingSoon #RealEstate #${(it=a==null?void 0:a.city)==null?void 0:it.replace(/\s/g,"")}`;default:return""}};if(a&&a.listing_class==="commercial")return e.jsx(Fd,{to:`/mission-control/listings/${a.id}/commercial`,replace:!0});if(i)return e.jsx(Vs,{title:"Listing",description:"",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(yn,{className:"h-10 w-32"}),e.jsx(yn,{className:"h-[400px] w-full"}),e.jsxs("div",{className:"grid md:grid-cols-3 gap-6",children:[e.jsx(yn,{className:"h-48"}),e.jsx(yn,{className:"h-48"}),e.jsx(yn,{className:"h-48"})]})]})});if(!a)return e.jsx(Vs,{title:"Listing Not Found",description:"",children:e.jsx(Ne,{children:e.jsxs(Ie,{className:"py-12 text-center",children:[e.jsx("p",{className:"text-muted-foreground mb-4",children:"This listing could not be found."}),e.jsx($,{onClick:()=>t("/mission-control/listings"),children:"Back to Listings"})]})})});const _e=((he=a.photos)==null?void 0:he.find(je=>je.is_primary))||((ue=a.photos)==null?void 0:ue[0]);return e.jsxs(Vs,{title:"",description:"",children:[e.jsxs("div",{className:"space-y-6",children:[e.jsxs($,{variant:"ghost",onClick:()=>t("/mission-control/listings"),children:[e.jsx(qa,{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:()=>_e&&V(_e.photo_url),children:_e?e.jsx("img",{src:_e.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:(ve=a.photos)==null?void 0:ve.slice(1,5).map((je,Ae)=>e.jsx("div",{className:"aspect-square rounded-lg overflow-hidden bg-muted cursor-pointer",onClick:()=>V(je.photo_url),children:e.jsx("img",{src:je.photo_url,alt:`Photo ${Ae+2}`,className:"w-full h-full object-cover"})},je.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(Ne,{children:e.jsxs(Ie,{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(Be,{className:`${lQn[a.status]} text-white border-0`,children:cQn[a.status]}),a.is_featured&&e.jsxs(Be,{variant:"outline",className:"border-amber-500 text-amber-500",children:[e.jsx(Ja,{className:"h-3 w-3 mr-1 fill-amber-500"}),"Featured"]}),a.open_to_referrals&&e.jsxs(Be,{variant:"outline",children:[e.jsx(Zn,{className:"h-3 w-3 mr-1"}),"Open to Referrals"]})]}),e.jsx("h1",{className:"text-3xl font-bold text-primary mb-2",children:ie(a.price)}),a.property_address&&e.jsx("p",{className:"text-xl font-medium",children:a.property_address}),e.jsxs("p",{className:"text-muted-foreground flex items-center gap-1",children:[e.jsx(ci,{className:"h-4 w-4"}),a.city,", ",a.state,a.neighborhood&&` • ${a.neighborhood}`]})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx($,{variant:"outline",size:"icon",onClick:()=>c.mutate(a.id),children:e.jsx(Jo,{className:`h-4 w-4 ${l?"fill-pink-500 text-pink-500":""}`})}),e.jsx($,{variant:"outline",size:"icon",onClick:()=>d.mutate(a.id),children:o?e.jsx(XS,{className:"h-4 w-4"}):e.jsx(qy,{className:"h-4 w-4"})}),!ae&&e.jsxs($,{variant:"outline",className:"border-amber-500 text-amber-600 hover:bg-amber-50",onClick:()=>b(!0),children:[e.jsx(Nn,{className:"h-4 w-4 mr-2"}),"Share & Earn Leads"]}),e.jsxs(Uu,{children:[e.jsx(qu,{asChild:!0,children:e.jsxs($,{variant:"outline",children:[e.jsx(zd,{className:"h-4 w-4 mr-2"}),"Share"]})}),e.jsxs(Eu,{children:[e.jsxs(ja,{onClick:()=>ne("copy"),children:[e.jsx(Ha,{className:"h-4 w-4 mr-2"}),"Copy Link"]}),e.jsxs(ja,{onClick:()=>ne("facebook"),children:[e.jsx(Qp,{className:"h-4 w-4 mr-2"}),"Facebook"]}),e.jsxs(ja,{onClick:()=>ne("text"),children:[e.jsx(eo,{className:"h-4 w-4 mr-2"}),"Text"]}),e.jsxs(ja,{onClick:()=>ne("email"),children:[e.jsx(mn,{className:"h-4 w-4 mr-2"}),"Email"]})]})]}),ae&&e.jsxs(e.Fragment,{children:[e.jsxs($,{variant:"outline",onClick:()=>{const je=(a.photos??[]).slice().sort((Ae,Ce)=>(Ce.is_primary?1:0)-(Ae.is_primary?1:0)||(Ae.sort_order??0)-(Ce.sort_order??0)).map(Ae=>Ae.photo_url).filter(Boolean);if(je.length===0){re.error("Add photos to this listing first.");return}Hrs({photos:je,details:{address:a.property_address||`${a.city??""} ${a.state??""}`.trim(),beds:a.bedrooms?String(a.bedrooms):"",baths:a.bathrooms?String(a.bathrooms):"",sqft:a.square_footage?String(a.square_footage):"",price:a.price?String(a.price):"",highlights:a.description||""},sourceLabel:"Listing Exchange",badge:Grs(a.status,a.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(Zq,{className:"h-4 w-4"}),"Create Music Video"]}),e.jsxs($,{onClick:()=>S(!0),className:"gap-2 bg-gradient-to-r from-slate-900 to-primary text-white shadow-md hover:opacity-95",children:[e.jsx(qg,{className:"h-4 w-4"}),"Launch Kit"]}),r&&e.jsxs($,{variant:"outline",className:"gap-2",onClick:()=>t(`/mission-control/direct-mail?listing=${s}`),children:[e.jsx(mn,{className:"h-4 w-4"}),"Mail Studio"]}),e.jsxs($,{variant:"outline",onClick:()=>D(!0),className:"gap-2 border-amber-500/60 text-amber-600 hover:bg-amber-50",children:[e.jsx(Nn,{className:"h-4 w-4"}),"Just Listed Graphic"]}),e.jsxs($,{variant:"outline",onClick:()=>U(!0),className:"gap-2",children:[e.jsx(Jp,{className:"h-4 w-4"}),"QR Code"]}),e.jsxs($,{variant:"outline",onClick:()=>P(!0),className:"gap-2",children:[e.jsx(mn,{className:"h-4 w-4"}),"Email My Sphere"]}),e.jsxs($,{onClick:()=>t(`/mission-control/listings/${a.id}/customize`),className:"gap-2 bg-gradient-to-r from-primary to-primary/80 hover:opacity-95 text-primary-foreground shadow-md",children:[e.jsx(Nn,{className:"h-4 w-4"}),"Customize Public Page"]}),e.jsxs($,{variant:"outline",onClick:()=>t(`/mission-control/listings/${a.id}/edit`),children:[e.jsx(_p,{className:"h-4 w-4 mr-2"}),"Edit"]}),e.jsx($,{variant:"destructive",size:"icon",onClick:()=>g(!0),children:e.jsx(Wn,{className:"h-4 w-4"})})]})]})]}),e.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-4 py-4 border-y",children:[a.bedrooms&&e.jsxs("div",{className:"text-center",children:[e.jsx(l2,{className:"h-5 w-5 mx-auto mb-1 text-muted-foreground"}),e.jsx("p",{className:"font-semibold",children:a.bedrooms}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Beds"})]}),a.bathrooms&&e.jsxs("div",{className:"text-center",children:[e.jsx(T0,{className:"h-5 w-5 mx-auto mb-1 text-muted-foreground"}),e.jsx("p",{className:"font-semibold",children:a.bathrooms}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Baths"})]}),a.square_footage&&e.jsxs("div",{className:"text-center",children:[e.jsx(C_,{className:"h-5 w-5 mx-auto mb-1 text-muted-foreground"}),e.jsx("p",{className:"font-semibold",children:a.square_footage.toLocaleString()}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Sq Ft"})]}),a.year_built&&e.jsxs("div",{className:"text-center",children:[e.jsx(Ta,{className:"h-5 w-5 mx-auto mb-1 text-muted-foreground"}),e.jsx("p",{className:"font-semibold",children:a.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(Be,{variant:"secondary",children:[e.jsx(ji,{className:"h-3 w-3 mr-1"}),A3t[a.property_type]]}),a.lot_size&&e.jsxs(Be,{variant:"secondary",children:["Lot: ",a.lot_size]}),a.has_hoa&&e.jsx(Be,{variant:"secondary",children:"HOA"})]}),a.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:a.description})]}),a.agent_notes&&a.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:a.agent_notes})]}),a.co_agent_name&&e.jsxs("div",{children:[e.jsx("h3",{className:"font-medium mb-2",children:"Co-Listing Agent"}),e.jsxs("div",{className:"flex items-center gap-3 rounded-lg border p-3",children:[a.co_agent_photo_url?e.jsx("img",{src:a.co_agent_photo_url,alt:a.co_agent_name,className:"h-12 w-12 rounded-full object-cover"}):e.jsx("div",{className:"h-12 w-12 rounded-full bg-muted flex items-center justify-center text-sm font-medium",children:a.co_agent_name.charAt(0)}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"font-medium truncate",children:a.co_agent_name}),a.co_agent_brokerage&&e.jsx("p",{className:"text-sm text-muted-foreground truncate",children:a.co_agent_brokerage}),e.jsx("p",{className:"text-sm text-muted-foreground truncate",children:[a.co_agent_email,a.co_agent_phone].filter(Boolean).join(" · ")})]})]})]}),a.mls_link&&e.jsx($,{variant:"outline",asChild:!0,children:e.jsxs("a",{href:a.mls_link,target:"_blank",rel:"noopener noreferrer",children:[e.jsx(kr,{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(Ca,{className:"h-4 w-4"}),a.view_count," views"]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(zd,{className:"h-4 w-4"}),a.share_count," shares"]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Jo,{className:"h-4 w-4"}),a.save_count," saves"]})]})]})}),a.allow_sharing&&e.jsxs(Ne,{children:[e.jsx(Ct,{children:e.jsx(At,{className:"text-lg",children:"Share Content"})}),e.jsx(Ie,{className:"space-y-4",children:["just_listed","price_improvement","teaser"].map(je=>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:[je.replace("_"," ")," Caption"]}),e.jsx($,{size:"sm",variant:"ghost",onClick:()=>{navigator.clipboard.writeText(ce(je)),re.success("Caption copied!")},children:e.jsx(Ha,{className:"h-3 w-3"})})]}),e.jsx("p",{className:"text-xs text-muted-foreground whitespace-pre-wrap",children:ce(je)})]},je))})]}),e.jsx(YXn,{listingId:a.id,ownerOnly:ae})]}),e.jsxs("div",{className:"space-y-6",children:[e.jsxs(Ne,{children:[e.jsx(Ct,{children:e.jsx(At,{className:"text-lg",children:"Listing Agent"})}),e.jsxs(Ie,{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:((Se=(Ee=a.agent)==null?void 0:Ee.name)==null?void 0:Se.charAt(0))||"?"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:((Le=a.agent)==null?void 0:Le.name)||"Unknown"}),((ke=(Fe=a.agent)==null?void 0:Fe.brokerage)==null?void 0:ke.name)&&e.jsx("p",{className:"text-sm text-muted-foreground",children:a.agent.brokerage.name})]})]}),!ae&&e.jsx("div",{className:"space-y-2",children:((Ve=a.agent)==null?void 0:Ve.email)&&e.jsx($,{variant:"outline",className:"w-full",asChild:!0,children:e.jsxs("a",{href:`mailto:${a.agent.email}`,children:[e.jsx(mn,{className:"h-4 w-4 mr-2"}),"Email Agent"]})})})]})]}),ae&&e.jsx(oQn,{listing:a}),!ae&&a.open_to_referrals&&e.jsxs(Ne,{children:[e.jsx(Ct,{children:e.jsxs(At,{className:"text-lg flex items-center gap-2",children:[e.jsx(Zn,{className:"h-5 w-5"}),"Send a Buyer"]})}),e.jsxs(Ie,{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($,{className:"w-full",onClick:()=>y(!0),children:"Send Referral"})]})]})]})]})]}),e.jsx(zs,{open:!!W,onOpenChange:()=>V(null),children:e.jsx(Os,{className:"max-w-4xl",children:e.jsx("img",{src:W||"",alt:"Full size",className:"w-full h-auto"})})}),e.jsx(zs,{open:f,onOpenChange:g,children:e.jsxs(Os,{children:[e.jsxs(Us,{children:[e.jsx(Bs,{children:"Delete Listing"}),e.jsx(Ir,{children:"Are you sure you want to delete this listing? This action cannot be undone."})]}),e.jsxs(Ar,{children:[e.jsx($,{variant:"outline",onClick:()=>g(!1),children:"Cancel"}),e.jsx($,{variant:"destructive",onClick:te,disabled:h.isPending,children:h.isPending?"Deleting...":"Delete"})]})]})}),e.jsx(zs,{open:x,onOpenChange:y,children:e.jsxs(Os,{children:[e.jsxs(Us,{children:[e.jsx(Bs,{children:"Send Buyer Referral"}),e.jsx(Ir,{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(ee,{children:"Buyer Name *"}),e.jsx(pe,{value:G.buyerName,onChange:je=>Y({...G,buyerName:je.target.value}),placeholder:"Enter buyer's name"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Buyer Type"}),e.jsxs(ms,{value:G.buyerType,onValueChange:je=>Y({...G,buyerType:je}),children:[e.jsx(us,{children:e.jsx(fs,{placeholder:"Select type"})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"first_time",children:"First-Time Buyer"}),e.jsx(Ge,{value:"investor",children:"Investor"}),e.jsx(Ge,{value:"relocating",children:"Relocating"}),e.jsx(Ge,{value:"upgrade",children:"Upgrading"}),e.jsx(Ge,{value:"downsize",children:"Downsizing"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Notes"}),e.jsx(Rs,{value:G.notes,onChange:je=>Y({...G,notes:je.target.value}),placeholder:"Any additional information..."})]})]}),e.jsxs(Ar,{children:[e.jsx($,{variant:"outline",onClick:()=>y(!1),children:"Cancel"}),e.jsx($,{onClick:J,disabled:m.isPending,children:m.isPending?"Sending...":"Send Referral"})]})]})}),e.jsx(PUt,{open:O,onOpenChange:U,url:`https://listings.relevelup.com/${a.slug||a.id}`,title:a.property_address||`${a.city}, ${a.state}`,fileBase:a.slug||a.property_address||a.city}),e.jsx(w6e,{open:v,onOpenChange:b,listingId:(a==null?void 0:a.id)||"",listingSlug:(a==null?void 0:a.slug)||null,listingTitle:(a==null?void 0:a.property_address)||`${a==null?void 0:a.city}, ${a==null?void 0:a.state}`}),a&&e.jsx(VUt,{open:I,onOpenChange:P,listing:a}),e.jsx(lnt,{listingId:(a==null?void 0:a.id)||null,open:R,onOpenChange:D,initialStatus:JEe(a==null?void 0:a.status)}),e.jsx(Urs,{listingId:(a==null?void 0:a.id)||null,open:w,onOpenChange:S,listingAddress:(a==null?void 0:a.property_address)||`${a==null?void 0:a.city}, ${a==null?void 0:a.state}`,listingSlug:(a==null?void 0:a.slug)||null,autoGenerate:!0})]})}function uQn({onImport:s}){const[t,n]=j.useState(""),[r,a]=j.useState([]),[i,l]=j.useState(!1),[o,c]=j.useState(!1),[d,u]=j.useState(null),h=j.useRef(),m=j.useRef(null);j.useEffect(()=>{const b=w=>{m.current&&!m.current.contains(w.target)&&c(!1)};return document.addEventListener("mousedown",b),()=>document.removeEventListener("mousedown",b)},[]);const f=async b=>{if(b.trim().length<3){a([]),c(!1);return}l(!0);try{const{data:w,error:S}=await q.functions.invoke("mls-listing-search",{body:{query:b}});if(S)throw S;a((w==null?void 0:w.listings)||[]),c(!0)}catch(w){console.error("MLS search error:",w),a([])}finally{l(!1)}},g=b=>{n(b),h.current&&clearTimeout(h.current),h.current=setTimeout(()=>f(b),400)},x=b=>{u(b.mlsNumber),s(b),c(!1),n(`${b.address}, ${b.city}`),re.success(`Imported: ${b.address}`,{description:"Property details and photos have been auto-filled."}),u(null)},y=b=>b?`$${b.toLocaleString()}`:"",v=b=>{const w=(b||"").toLowerCase();return w.includes("single")||w.includes("detached")?"Single Family":w.includes("condo")?"Condo":w.includes("town")?"Townhouse":w.includes("land")||w.includes("lot")?"Land":w.includes("multi")?"Multi-Family":w.includes("commercial")?"Commercial":b||"Other"};return e.jsxs(Ne,{className:"border-primary/30 bg-primary/5",children:[e.jsxs(Ct,{className:"pb-3",children:[e.jsxs(At,{className:"text-base flex items-center gap-2",children:[e.jsx(di,{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(Ie,{children:e.jsxs("div",{ref:m,className:"relative",children:[e.jsxs("div",{className:"relative",children:[e.jsx(Kr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(pe,{value:t,onChange:b=>g(b.target.value),onFocus:()=>r.length>0&&c(!0),placeholder:"Start typing a property address...",className:"pl-9 pr-9"}),i&&e.jsx(kt,{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:()=>{n(""),a([]),c(!1)},className:"absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground",children:e.jsx(gr,{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:r.length===0&&!i?e.jsx("div",{className:"p-4 text-center text-sm text-muted-foreground",children:"No properties found. Try a different address."}):r.map(b=>e.jsxs("button",{type:"button",onClick:()=>x(b),disabled:d===b.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:[b.photos[0]?e.jsx("img",{src:b.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(ci,{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:b.address}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[b.city,", ",b.state," ",b.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:y(b.price)}),b.bedrooms>0&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(l2,{className:"h-3 w-3"})," ",b.bedrooms]}),b.bathrooms>0&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(T0,{className:"h-3 w-3"})," ",b.bathrooms]}),b.sqft>0&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(R4,{className:"h-3 w-3"})," ",b.sqft.toLocaleString()]})]})]}),e.jsxs("div",{className:"flex-shrink-0 flex flex-col items-end gap-1",children:[e.jsx(Be,{variant:"outline",className:"text-[10px]",children:v(b.propertyType)}),b.photos.length>0&&e.jsxs("span",{className:"text-[10px] text-muted-foreground",children:[b.photos.length," photos"]})]})]},b.mlsNumber))})]})})]})}function hQn({selectedVideoId:s,onVideoSelect:t,listingId:n}){const r=Qn(),{user:a}=vs(),[i,l]=j.useState(!1),[o,c]=j.useState([]),[d,u]=j.useState(!1),[h,m]=j.useState(null),[f,g]=j.useState({});j.useEffect(()=>{s&&a?x():m(null)},[s,a]);const x=async()=>{if(!s)return;const{data:R,error:D}=await q.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();!D&&R&&(m(R),y(R))},y=async R=>{try{const{data:D,error:O}=await q.functions.invoke("bunny-upload",{body:{action:"asset-urls",videoId:R.bunny_video_id,isAgentVideo:!0}});!O&&(D!=null&&D.thumbnailUrl)&&g(U=>({...U,[R.id]:{thumbnailUrl:D.thumbnailUrl}}))}catch(D){console.warn("Failed to get signed URL",D)}},v=async()=>{if(a){u(!0);try{const{data:R,error:D}=await q.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(D)throw D;c(R||[]),R!=null&&R.length&&b(R)}catch(R){console.error("Error fetching videos:",R),re.error("Failed to load videos")}finally{u(!1)}}},b=async R=>{var D;try{const O=R.map(Y=>Y.bunny_video_id),{data:U,error:W}=await q.functions.invoke("bunny-upload",{body:{action:"bulk-asset-urls",videoIds:O,isAgentVideo:!0}});if(W)throw W;const V=(U==null?void 0:U.assets)||{},G={};for(const Y of R)(D=V[Y.bunny_video_id])!=null&&D.thumbnailUrl&&(G[Y.id]={thumbnailUrl:V[Y.bunny_video_id].thumbnailUrl});g(Y=>({...Y,...G}))}catch(O){console.warn("Failed to bulk-fetch signed URLs",O)}},w=()=>{l(!0),v()},S=R=>{t(R.id),m(R),l(!1),re.success("Video selected")},C=()=>{t(null),m(null)},E=()=>{const R=n?`/mission-control/listings/${n}/edit`:"/mission-control/listings/new";r(`/mission-control/video?returnUrl=${encodeURIComponent(R)}`)},I=R=>{if(!R)return"0:00";const D=Math.floor(R/60),O=R%60;return`${D}:${O.toString().padStart(2,"0")}`},P=R=>{var D;return((D=f[R.id])==null?void 0:D.thumbnailUrl)||R.thumbnail_url};return e.jsxs("div",{className:"space-y-3",children:[h?e.jsx(Ne,{className:"overflow-hidden",children:e.jsx(Ie,{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:[P(h)?e.jsx("img",{src:P(h),alt:h.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(ua,{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(Bu,{className:"h-6 w-6 text-white fill-white"})}),h.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:I(h.duration_seconds)})]}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-medium text-sm truncate",children:h.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($,{type:"button",variant:"outline",size:"sm",onClick:w,children:"Change"}),e.jsx($,{type:"button",variant:"ghost",size:"sm",onClick:C,className:"text-destructive hover:text-destructive",children:e.jsx(gr,{className:"h-4 w-4"})})]})]})})}):e.jsx(Ne,{className:"border-dashed",children:e.jsx(Ie,{className:"p-6",children:e.jsxs("div",{className:"text-center",children:[e.jsx(ua,{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($,{type:"button",variant:"outline",onClick:w,className:"gap-2",children:[e.jsx(f2,{className:"h-4 w-4"}),"Select from Library"]}),e.jsxs($,{type:"button",variant:"outline",onClick:E,className:"gap-2",children:[e.jsx(Cx,{className:"h-4 w-4"}),"Record New Video"]})]})]})})}),e.jsx(zs,{open:i,onOpenChange:l,children:e.jsxs(Os,{className:"max-w-2xl max-h-[80vh] overflow-hidden flex flex-col",children:[e.jsx(Us,{children:e.jsxs(Bs,{className:"flex items-center gap-2",children:[e.jsx(f2,{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(kt,{className:"h-8 w-8 animate-spin text-muted-foreground"})}):o.length===0?e.jsxs("div",{className:"text-center py-12",children:[e.jsx(ua,{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($,{onClick:E,className:"gap-2",children:[e.jsx(Cx,{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(R=>e.jsxs("button",{type:"button",onClick:()=>S(R),className:`group relative rounded-lg overflow-hidden border-2 transition-all text-left ${s===R.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:[P(R)?e.jsx("img",{src:P(R),alt:R.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(ua,{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(Bu,{className:"h-8 w-8 text-white opacity-0 group-hover:opacity-100 transition-opacity"})}),R.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:I(R.duration_seconds)})]}),e.jsx("div",{className:"p-2 bg-card",children:e.jsx("p",{className:"text-xs font-medium truncate",children:R.title||"Untitled Video"})})]},R.id))})}),e.jsxs("div",{className:"flex justify-between items-center pt-4 border-t",children:[e.jsxs($,{type:"button",variant:"ghost",onClick:E,className:"gap-2",children:[e.jsx(Cx,{className:"h-4 w-4"}),"Record New Video"]}),e.jsx($,{type:"button",variant:"outline",onClick:()=>l(!1),children:"Cancel"})]})]})})]})}const mQn=s=>s<1024?`${s} B`:s<1024*1024?`${(s/1024).toFixed(0)} KB`:`${(s/(1024*1024)).toFixed(1)} MB`;function fQn({listingId:s}){const t=j.useRef(null),{data:n=[],isLoading:r}=d6e(s),a=K$t(),i=Y$t(),l=Hqs(),o=async d=>{if(!(!d||d.length===0)){for(const u of Array.from(d)){if(u.size>25*1024*1024){re.error(`${u.name} exceeds 25MB limit`);continue}try{await a.mutateAsync({listingId:s,file:u})}catch(h){re.error(`Failed to upload ${u.name}: ${h.message}`)}}t.current&&(t.current.value=""),re.success("Documents uploaded")}},c=async d=>{try{const u=await Jst(d);window.open(u,"_blank")}catch{re.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($,{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(kt,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(ni,{className:"h-4 w-4 mr-2"}),"Upload PDFs (disclosures, etc.)"]}),r?e.jsx("p",{className:"text-sm text-muted-foreground",children:"Loading..."}):n.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:n.map(d=>e.jsxs(Ne,{className:"p-3 flex items-center gap-3",children:[e.jsx("div",{className:"p-2 rounded-md bg-primary/10",children:e.jsx(Jr,{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:mQn(d.file_size)})]}),e.jsxs("div",{className:"flex items-center gap-1 text-xs text-muted-foreground",children:[d.visible_on_exchange?e.jsx(Ca,{className:"h-3 w-3"}):e.jsx($g,{className:"h-3 w-3"}),e.jsx("span",{className:"hidden sm:inline",children:d.visible_on_exchange?"Visible":"Hidden"}),e.jsx(Sn,{checked:d.visible_on_exchange,onCheckedChange:u=>l.mutate({id:d.id,visible:u,listingId:s}),className:"ml-1"})]}),e.jsx($,{type:"button",variant:"ghost",size:"icon",onClick:()=>c(d.storage_path),children:e.jsx(di,{className:"h-4 w-4"})}),e.jsx($,{type:"button",variant:"ghost",size:"icon",onClick:async()=>{await fo(`Delete ${d.file_name}?`)&&i.mutate({id:d.id,storage_path:d.storage_path,listingId:s})},children:e.jsx(gr,{className:"h-4 w-4 text-destructive"})})]},d.id))})]})}const pQn=[{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"}],gQn=[{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 xQn({id:s,url:t,index:n,onRemove:r}){const{attributes:a,listeners:i,setNodeRef:l,transform:o,transition:c,isDragging:d}=_6e({id:s}),u={transform:RL.Transform.toString(o),transition:c};return e.jsxs("div",{ref:l,style:u,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(Ug,{className:"h-3.5 w-3.5"})}),e.jsx("button",{type:"button",onClick:()=>r(n),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(gr,{className:"h-3 w-3"})}),n===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(Ja,{className:"h-2.5 w-2.5 fill-current"})," Primary"]})]})}function yQn({photoUrls:s,pendingPhotos:t,onRemove:n,onReorder:r,uploading:a,onUpload:i}){const l=h6e(IG(fK,{activationConstraint:{distance:5}})),o=s.map((d,u)=>`pending-${u}`),c=d=>{const{active:u,over:h}=d;if(!h||u.id===h.id)return;const m=o.indexOf(u.id),f=o.indexOf(h.id),g=[...s],x=[...t],[y]=g.splice(m,1),[v]=x.splice(m,1);g.splice(f,0,y),x.splice(f,0,v),r(g,x)};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(y6e,{sensors:l,collisionDetection:m6e,onDragEnd:c,children:e.jsx(b6e,{items:o,strategy:aie,children:e.jsxs("div",{className:"grid grid-cols-3 sm:grid-cols-4 gap-4",children:[s.map((d,u)=>e.jsx(xQn,{id:o[u],url:d,index:u,onRemove:n},o[u])),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(kt,{className:"h-8 w-8 animate-spin"}):e.jsxs(e.Fragment,{children:[e.jsx(ni,{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 E3t(){const{listingId:s}=Wi(),[t]=gc(),n=t.get("brokerage"),r=Qn(),{user:a}=vs(),{hasLeadSite:i}=ng(),l=!!s&&s!=="new",o=!!n&&!l,[c,d]=j.useState([]),[u,h]=j.useState({open:!1,listingId:null,nextPath:"/mission-control/listings"}),{data:m,isLoading:f}=tie(l?s:""),g=z$t(),x=Pqs(),y=B$t(),v=U$t(),b=q$t(),w=V$t(),S=H$t(),{data:C=[]}=tt({queryKey:["brokerage-agents",n],queryFn:async()=>{if(!n)return[];const{data:Ae,error:Ce}=await q.from("profiles").select("id, name, email").eq("brokerage_id",n).order("name");if(Ce)throw Ce;return Ae||[]},enabled:o}),[E,I]=j.useState(""),{data:P=[]}=Dae(),R=P.filter(Ae=>Ae.role==="team_leader").map(Ae=>Ae.teamId),D=P.map(Ae=>Ae.teamId),O=R.length>0,{data:U=[]}=tt({queryKey:["team-agent-profiles",D.join(",")],queryFn:async()=>{if(!D.length)return[];const{data:Ae,error:Ce}=await q.from("team_members").select("user_id").in("team_id",D);if(Ce)throw Ce;const qe=Array.from(new Set((Ae||[]).map(ct=>ct.user_id)));if(!qe.length)return[];const{data:ze,error:$e}=await q.from("profiles").select("id, name, email, phone, avatar_url, brokerage_name").in("id",qe).order("name");if($e)throw $e;return ze||[]},enabled:D.length>0}),[W,V]=j.useState(""),G=W||(a==null?void 0:a.id)||"",Y=O&&!o&&U.length>1,[X,ae]=j.useState(!1),[ie,ne]=j.useState([]),[te,J]=j.useState([]),[ce,_e]=j.useState(!1),he=async Ae=>{if(Ae.size>5*1024*1024){re.error("Image must be under 5MB");return}_e(!0);try{const Ce=Ae.name.split(".").pop()||"jpg",qe=`${(a==null?void 0:a.id)||"anon"}/co-agents/${Date.now()}.${Ce}`,{error:ze}=await q.storage.from("listing-photos").upload(qe,Ae,{upsert:!0});if(ze)throw ze;const{data:$e}=q.storage.from("listing-photos").getPublicUrl(qe);ve(ct=>({...ct,co_agent_photo_url:$e.publicUrl})),re.success("Headshot uploaded")}catch(Ce){re.error((Ce==null?void 0:Ce.message)||"Failed to upload headshot")}finally{_e(!1)}},[ue,ve]=j.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,co_agent_name:"",co_agent_email:"",co_agent_phone:"",co_agent_brokerage:"",co_agent_photo_url:"",allow_sharing:!0,open_to_referrals:!0,open_to_social_promotion:!0,share_with_brokerage:!1,is_public:!0,site_only:!1,show_on_lead_site:!0});j.useEffect(()=>{var Ae,Ce,qe,ze,$e;m&&l&&(ve({property_address:m.property_address||"",city:m.city||"",state:m.state||"",neighborhood:m.neighborhood||"",price:((Ae=m.price)==null?void 0:Ae.toString())||"",property_type:m.property_type,status:m.status,bedrooms:((Ce=m.bedrooms)==null?void 0:Ce.toString())||"",bathrooms:((qe=m.bathrooms)==null?void 0:qe.toString())||"",square_footage:((ze=m.square_footage)==null?void 0:ze.toString())||"",lot_size:m.lot_size||"",year_built:(($e=m.year_built)==null?void 0:$e.toString())||"",has_hoa:m.has_hoa,description:m.description||"",agent_notes:m.agent_notes||"",agent_notes_public:m.agent_notes_public,mls_link:m.mls_link||"",video_link:m.video_link||"",video_id:m.video_id||null,co_agent_name:m.co_agent_name||"",co_agent_email:m.co_agent_email||"",co_agent_phone:m.co_agent_phone||"",co_agent_brokerage:m.co_agent_brokerage||"",co_agent_photo_url:m.co_agent_photo_url||"",allow_sharing:m.allow_sharing,open_to_referrals:m.open_to_referrals,open_to_social_promotion:m.open_to_social_promotion,share_with_brokerage:m.share_with_brokerage??!1,is_public:m.is_public,site_only:m.site_only??!1,show_on_lead_site:m.show_on_lead_site??!0}),V(m.agent_id||""))},[m,l]);const Ee=Ae=>{var $e,ct;const Ce={"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"},qe=(Ae.propertyType||"").toLowerCase(),ze=(($e=Object.entries(Ce).find(([Xe])=>qe.includes(Xe)))==null?void 0:$e[1])||"other";ve(Xe=>({...Xe,property_address:Ae.address||Xe.property_address,city:Ae.city||Xe.city,state:Ae.state||Xe.state,price:Ae.price?String(Ae.price):Xe.price,property_type:ze,bedrooms:Ae.bedrooms?String(Ae.bedrooms):Xe.bedrooms,bathrooms:Ae.bathrooms?String(Ae.bathrooms):Xe.bathrooms,square_footage:Ae.sqft?String(Ae.sqft):Xe.square_footage,lot_size:Ae.lotSize?String(Ae.lotSize):Xe.lot_size,year_built:Ae.yearBuilt?String(Ae.yearBuilt):Xe.year_built,description:Ae.description||Xe.description})),((ct=Ae.photos)==null?void 0:ct.length)>0&&(d(Ae.photos),te.forEach(Xe=>URL.revokeObjectURL(Xe)),ne([]),J([]))},Se=Ae=>{if(!Ae)return;const Ce=Array.from(Ae);ne(ze=>[...ze,...Ce]);const qe=Ce.map(ze=>URL.createObjectURL(ze));J(ze=>[...ze,...qe])},Le=Ae=>{URL.revokeObjectURL(te[Ae]),ne(Ce=>Ce.filter((qe,ze)=>ze!==Ae)),J(Ce=>Ce.filter((qe,ze)=>ze!==Ae))},Fe=async Ae=>{var Ce;if(!(!Ae||!m)){ae(!0);try{for(const qe of Array.from(Ae)){const ze=qe.name.split(".").pop(),$e=`${a==null?void 0:a.id}/${m.id}/${Date.now()}.${ze}`,{error:ct}=await q.storage.from("listing-photos").upload($e,qe);if(ct)throw ct;const{data:{publicUrl:Xe}}=q.storage.from("listing-photos").getPublicUrl($e);await v.mutateAsync({listingId:m.id,photoUrl:Xe,isPrimary:!((Ce=m.photos)!=null&&Ce.length)})}re.success("Photos uploaded!")}catch(qe){console.error("Upload error:",qe),re.error("Failed to upload photos")}finally{ae(!1)}}},ke=async Ae=>{for(let Ce=0;Ce{if(m)try{await b.mutateAsync({photoId:Ae,listingId:m.id}),re.success("Photo removed")}catch{re.error("Failed to remove photo")}},je=async Ae=>{if(Ae.preventDefault(),!ue.city.trim()||!ue.state.trim()||!ue.price){re.error("Please fill in required fields (City, State, Price)");return}if(o&&!E){re.error("Please select an agent to assign this listing to");return}try{const Ce={property_address:ue.property_address||null,city:ue.city,state:ue.state,neighborhood:ue.neighborhood||null,price:Number(ue.price),property_type:ue.property_type,status:ue.status,bedrooms:ue.bedrooms?Number(ue.bedrooms):null,bathrooms:ue.bathrooms?Number(ue.bathrooms):null,square_footage:ue.square_footage?Number(ue.square_footage):null,lot_size:ue.lot_size||null,year_built:ue.year_built?Number(ue.year_built):null,has_hoa:ue.has_hoa,description:ue.description||null,agent_notes:ue.agent_notes||null,agent_notes_public:ue.agent_notes_public,mls_link:ue.mls_link||null,video_link:ue.video_link||null,video_id:ue.video_id||null,co_agent_name:ue.co_agent_name||null,co_agent_email:ue.co_agent_email||null,co_agent_phone:ue.co_agent_phone||null,co_agent_brokerage:ue.co_agent_brokerage||null,co_agent_photo_url:ue.co_agent_photo_url||null,allow_sharing:ue.allow_sharing,open_to_referrals:ue.open_to_referrals,open_to_social_promotion:ue.open_to_social_promotion,share_with_brokerage:ue.share_with_brokerage,is_public:ue.site_only?!1:ue.is_public,site_only:ue.site_only,show_on_lead_site:ue.site_only?!0:ue.show_on_lead_site};if(l){const qe=Y&&G&&G!==(m==null?void 0:m.agent_id)?{agent_id:G}:{},ze=m==null?void 0:m.status;await y.mutateAsync({id:s,...Ce,...qe}),re.success("Listing updated!");const $e=`/mission-control/listings/${s}`;ze&&ze!==ue.status?h({open:!0,listingId:s,nextPath:$e,socialStatus:JEe(ue.status)}):r($e)}else{ae(!0);let qe;if(o&&E?qe=await x.mutateAsync({agentId:E,...Ce}):Y&&G&&G!==(a==null?void 0:a.id)?qe=await x.mutateAsync({agentId:G,...Ce}):qe=await g.mutateAsync(Ce),ie.length>0)try{await ke(qe.id),te.forEach($e=>URL.revokeObjectURL($e)),ne([]),J([])}catch($e){console.error("Photo upload error:",$e),re.error("Listing created but some photos failed to upload")}if(c.length>0)try{for(let $e=0;$er(o?"/my-brokerage":"/mission-control/listings"),children:[e.jsx(qa,{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(Ne,{children:[e.jsx(Ct,{children:e.jsx(At,{children:"Assign to Agent *"})}),e.jsxs(Ie,{children:[e.jsxs(ms,{value:E,onValueChange:I,children:[e.jsx(us,{children:e.jsx(fs,{placeholder:"Select an agent..."})}),e.jsx(hs,{children:C.map(Ae=>e.jsx(Ge,{value:Ae.id,children:Ae.name||Ae.email},Ae.id))})]}),e.jsx("p",{className:"text-sm text-muted-foreground mt-2",children:"This listing will appear on the selected agent's Listing Exchange."})]})]}),Y&&e.jsxs(Ne,{children:[e.jsx(Ct,{children:e.jsx(At,{children:"Primary Listing Agent"})}),e.jsxs(Ie,{children:[e.jsxs(ms,{value:G,onValueChange:V,children:[e.jsx(us,{children:e.jsx(fs,{placeholder:"Select the listing agent..."})}),e.jsx(hs,{children:U.map(Ae=>e.jsx(Ge,{value:Ae.id,children:(Ae.name||Ae.email)+(Ae.id===(a==null?void 0:a.id)?" (you)":"")},Ae.id))})]}),e.jsx("p",{className:"text-sm text-muted-foreground mt-2",children:"As a team leader you can credit this listing to any agent on your team. It will appear on their Listing Exchange and website."})]})]}),!l&&i&&!o&&e.jsx(uQn,{onImport:Ee}),c.length>0&&e.jsxs(Ne,{className:"border-primary/30 bg-primary/5",children:[e.jsxs(Ct,{className:"pb-3",children:[e.jsxs(At,{className:"text-base flex items-center gap-2",children:[e.jsx(di,{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(Ie,{children:[e.jsxs("div",{className:"grid grid-cols-4 sm:grid-cols-6 gap-2",children:[c.slice(0,12).map((Ae,Ce)=>e.jsx("div",{className:"aspect-square rounded overflow-hidden bg-muted",children:e.jsx("img",{src:Ae,alt:"",className:"w-full h-full object-cover"})},Ce)),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($,{type:"button",variant:"ghost",size:"sm",className:"mt-2 text-destructive",onClick:()=>d([]),children:[e.jsx(gr,{className:"h-3 w-3 mr-1"})," Clear MLS photos"]})]})]}),e.jsxs(Ne,{children:[e.jsx(Ct,{children:e.jsx(At,{children:"Property Details"})}),e.jsx(Ie,{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(ee,{children:"Property Address"}),e.jsx(pe,{value:ue.property_address,onChange:Ae=>ve({...ue,property_address:Ae.target.value}),placeholder:"123 Main St"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"City *"}),e.jsx(pe,{value:ue.city,onChange:Ae=>ve({...ue,city:Ae.target.value}),placeholder:"City",required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"State *"}),e.jsx(pe,{value:ue.state,onChange:Ae=>ve({...ue,state:Ae.target.value}),placeholder:"State",required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Neighborhood"}),e.jsx(pe,{value:ue.neighborhood,onChange:Ae=>ve({...ue,neighborhood:Ae.target.value}),placeholder:"Neighborhood"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Price *"}),e.jsx(pe,{type:"number",value:ue.price,onChange:Ae=>ve({...ue,price:Ae.target.value}),placeholder:"500000",required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Property Type"}),e.jsxs(ms,{value:ue.property_type,onValueChange:Ae=>ve({...ue,property_type:Ae}),children:[e.jsx(us,{children:e.jsx(fs,{})}),e.jsx(hs,{children:gQn.map(Ae=>e.jsx(Ge,{value:Ae.value,children:Ae.label},Ae.value))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Status"}),e.jsxs(ms,{value:ue.status,onValueChange:Ae=>ve({...ue,status:Ae}),children:[e.jsx(us,{children:e.jsx(fs,{})}),e.jsx(hs,{children:pQn.map(Ae=>e.jsx(Ge,{value:Ae.value,children:Ae.label},Ae.value))})]})]})]})})]}),e.jsxs(Ne,{children:[e.jsx(Ct,{children:e.jsx(At,{children:"Property Specs (Optional)"})}),e.jsx(Ie,{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(ee,{children:"Bedrooms"}),e.jsx(pe,{type:"number",value:ue.bedrooms,onChange:Ae=>ve({...ue,bedrooms:Ae.target.value}),placeholder:"3"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Bathrooms"}),e.jsx(pe,{type:"number",step:"0.5",value:ue.bathrooms,onChange:Ae=>ve({...ue,bathrooms:Ae.target.value}),placeholder:"2"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Sq Ft"}),e.jsx(pe,{type:"number",value:ue.square_footage,onChange:Ae=>ve({...ue,square_footage:Ae.target.value}),placeholder:"2000"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Lot Size"}),e.jsx(pe,{value:ue.lot_size,onChange:Ae=>ve({...ue,lot_size:Ae.target.value}),placeholder:"0.25 acres"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Year Built"}),e.jsx(pe,{type:"number",value:ue.year_built,onChange:Ae=>ve({...ue,year_built:Ae.target.value}),placeholder:"2005"})]}),e.jsxs("div",{className:"flex items-center gap-2 pt-6",children:[e.jsx(Sn,{checked:ue.has_hoa,onCheckedChange:Ae=>ve({...ue,has_hoa:Ae})}),e.jsx(ee,{children:"Has HOA"})]})]})})]}),e.jsxs(Ne,{children:[e.jsx(Ct,{children:e.jsx(At,{children:"Description & Links"})}),e.jsxs(Ie,{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Description"}),e.jsx(Rs,{value:ue.description,onChange:Ae=>ve({...ue,description:Ae.target.value}),placeholder:"Tell the story of this property...",rows:4})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Agent Notes"}),e.jsx(Rs,{value:ue.agent_notes,onChange:Ae=>ve({...ue,agent_notes:Ae.target.value}),placeholder:"Notes for other agents...",rows:2}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Sn,{checked:ue.agent_notes_public,onCheckedChange:Ae=>ve({...ue,agent_notes_public:Ae})}),e.jsx(ee,{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(ee,{children:"MLS Link"}),e.jsx(pe,{value:ue.mls_link,onChange:Ae=>ve({...ue,mls_link:Ae.target.value}),placeholder:"https://..."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Video Link"}),e.jsx(pe,{value:ue.video_link,onChange:Ae=>ve({...ue,video_link:Ae.target.value}),placeholder:"YouTube or Vimeo URL"})]})]})]})]}),e.jsxs(Ne,{children:[e.jsx(Ct,{children:e.jsx(At,{children:"Co-Listing Agent (optional)"})}),e.jsxs(Ie,{className:"space-y-4",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Credit a second agent on this listing. Their info appears on the listing page alongside yours."}),U.length>1&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Choose a team member"}),e.jsxs(ms,{value:"",onValueChange:Ae=>{const Ce=U.find(qe=>qe.id===Ae);Ce&&(ve(qe=>({...qe,co_agent_name:Ce.name||qe.co_agent_name,co_agent_email:Ce.email||"",co_agent_phone:Ce.phone||"",co_agent_brokerage:Ce.brokerage_name||qe.co_agent_brokerage,co_agent_photo_url:Ce.avatar_url||""})),re.success("Co-listing agent details filled in"))},children:[e.jsx(us,{children:e.jsx(fs,{placeholder:"Auto-fill from your team..."})}),e.jsx(hs,{children:U.filter(Ae=>Ae.id!==G).map(Ae=>e.jsx(Ge,{value:Ae.id,children:Ae.name||Ae.email},Ae.id))})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Details fill in automatically and stay editable. For agents outside your team, just type below."})]}),e.jsxs("div",{className:"grid sm:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Name"}),e.jsx(pe,{value:ue.co_agent_name,onChange:Ae=>ve({...ue,co_agent_name:Ae.target.value}),placeholder:"Jordan Ellis"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Brokerage"}),e.jsx(pe,{value:ue.co_agent_brokerage,onChange:Ae=>ve({...ue,co_agent_brokerage:Ae.target.value}),placeholder:"Brokerage name"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Email"}),e.jsx(pe,{type:"email",value:ue.co_agent_email,onChange:Ae=>ve({...ue,co_agent_email:Ae.target.value}),placeholder:"agent@email.com"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Phone"}),e.jsx(pe,{value:ue.co_agent_phone,onChange:Ae=>ve({...ue,co_agent_phone:Ae.target.value}),placeholder:"(555) 123-4567"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Headshot"}),e.jsxs("div",{className:"flex items-center gap-4",children:[ue.co_agent_photo_url?e.jsx("img",{src:ue.co_agent_photo_url,alt:"Co-listing agent headshot",className:"h-20 w-20 rounded-full object-cover border"}):e.jsx("div",{className:"h-20 w-20 rounded-full border border-dashed flex items-center justify-center text-muted-foreground",children:e.jsx(ni,{className:"h-5 w-5"})}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("input",{id:"co-agent-headshot",type:"file",accept:"image/*",className:"hidden",onChange:Ae=>{var qe;const Ce=(qe=Ae.target.files)==null?void 0:qe[0];Ae.target.value="",Ce&&he(Ce)}}),e.jsx($,{type:"button",variant:"outline",disabled:ce,onClick:()=>{var Ae;return(Ae=document.getElementById("co-agent-headshot"))==null?void 0:Ae.click()},children:ce?e.jsxs(e.Fragment,{children:[e.jsx(kt,{className:"h-4 w-4 mr-2 animate-spin"})," Uploading…"]}):e.jsxs(e.Fragment,{children:[e.jsx(ni,{className:"h-4 w-4 mr-2"})," ",ue.co_agent_photo_url?"Replace photo":"Upload photo"]})}),ue.co_agent_photo_url&&e.jsxs($,{type:"button",variant:"ghost",onClick:()=>ve(Ae=>({...Ae,co_agent_photo_url:""})),children:[e.jsx(gr,{className:"h-4 w-4 mr-1"})," Remove"]})]})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"JPG or PNG, up to 5MB."})]})]})]}),e.jsxs(Ne,{children:[e.jsx(Ct,{children:e.jsxs(At,{className:"flex items-center gap-2",children:[e.jsx(ua,{className:"h-5 w-5"}),"Property Video"]})}),e.jsx(Ie,{children:e.jsx(hQn,{selectedVideoId:ue.video_id,onVideoSelect:Ae=>ve({...ue,video_id:Ae}),listingId:l?s:void 0})})]}),e.jsxs(Ne,{children:[e.jsx(Ct,{children:e.jsx(At,{children:"Photos"})}),e.jsx(Ie,{children:l&&(m!=null&&m.photos)?e.jsx(vUt,{photos:m.photos,uploading:X,onUpload:Ae=>Fe(Ae),onRemove:Ae=>Ve(Ae),onReorder:Ae=>{w.mutate({photos:Ae.map(Ce=>({id:Ce.id,sort_order:Ce.sort_order,is_primary:Ce.is_primary}))})},onSetPrimary:Ae=>{m&&S.mutate({photoId:Ae,listingId:m.id})}}):e.jsx(yQn,{photoUrls:te,onRemove:Le,onReorder:(Ae,Ce)=>{J(Ae),ne(Ce)},pendingPhotos:ie,uploading:X,onUpload:Se})})]}),e.jsxs(Ne,{children:[e.jsx(Ct,{children:e.jsxs(At,{className:"flex items-center gap-2",children:[e.jsx(di,{className:"h-5 w-5"}),"Documents & Disclosures"]})}),e.jsx(Ie,{children:l&&s?e.jsx(fQn,{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(Ne,{children:[e.jsx(Ct,{children:e.jsx(At,{children:"Sharing & Collaboration"})}),e.jsxs(Ie,{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(ee,{children:"Allow Sharing"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Other agents can share this listing"})]}),e.jsx(Sn,{checked:ue.allow_sharing,onCheckedChange:Ae=>ve({...ue,allow_sharing:Ae})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(ee,{children:"Open to Referrals"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Accept buyer referrals"})]}),e.jsx(Sn,{checked:ue.open_to_referrals,onCheckedChange:Ae=>ve({...ue,open_to_referrals:Ae})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(ee,{children:"Social Promotion"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Can be promoted on social media"})]}),e.jsx(Sn,{checked:ue.open_to_social_promotion,onCheckedChange:Ae=>ve({...ue,open_to_social_promotion:Ae})})]}),e.jsxs("div",{className:"flex items-center justify-between pt-2 border-t",children:[e.jsxs("div",{children:[e.jsx(ee,{children:"Share with Brokerage"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Visible to agents in your brokerage"})]}),e.jsx(Sn,{checked:ue.share_with_brokerage,onCheckedChange:Ae=>ve({...ue,share_with_brokerage:Ae})})]}),i&&e.jsxs("div",{className:"flex items-center justify-between pt-2 border-t",children:[e.jsxs("div",{children:[e.jsx(ee,{children:"My Website Only"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Hide from the Listing Exchange and other agents — only show it on your own website"})]}),e.jsx(Sn,{checked:ue.site_only,onCheckedChange:Ae=>ve({...ue,site_only:Ae,is_public:Ae?!1:ue.is_public,show_on_lead_site:Ae?!0:ue.show_on_lead_site,share_with_brokerage:Ae?!1:ue.share_with_brokerage})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(ee,{children:"Make Public"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Publish on listings.relevelup.com to get leads"})]}),e.jsx(Sn,{checked:ue.is_public,disabled:ue.site_only,onCheckedChange:Ae=>ve({...ue,is_public:Ae})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(ee,{children:"Show on My Website"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:ue.status==="sold"?"Sold listings are hidden from the Listing Exchange and public marketplace — they only build your track record on your website's Sold page.":"Feature this listing on your lead site homepage and listings page"})]}),e.jsx(Sn,{checked:ue.show_on_lead_site,onCheckedChange:Ae=>ve({...ue,show_on_lead_site:Ae})})]})]})]}),e.jsx($,{type:"submit",className:"w-full",size:"lg",disabled:g.isPending||y.isPending,children:g.isPending||y.isPending?e.jsxs(e.Fragment,{children:[e.jsx(kt,{className:"h-4 w-4 mr-2 animate-spin"}),"Saving..."]}):l?"Update Listing":"Create Listing"})]})]})]}),e.jsx(lnt,{listingId:u.listingId,open:u.open,initialStatus:u.socialStatus,onOpenChange:Ae=>{if(!Ae){const{nextPath:Ce}=u;h({open:!1,listingId:null,nextPath:Ce}),r(Ce)}}})]})}const $Xe=[{key:"stats",label:"Stats strip",hint:"Beds, baths, sqft, lot, year"},{key:"story",label:"The Story",hint:"Property description"},{key:"agent_note",label:"Agent note",hint:"Personal note callout"},{key:"gallery",label:"Photo gallery",hint:"Bento gallery + lightbox"},{key:"video",label:"Video tour",hint:"Uses the linked video"},{key:"map",label:"Location map",hint:"Neighborhood map"},{key:"payment",label:"Payment calc",hint:"Interactive mortgage estimator"},{key:"agent_card",label:"Agent card",hint:"Your info + contact form"}],Zrs=[{type:"extra_video",label:"Extra Video / Reel",icon:ua,desc:"Add a YouTube, Vimeo, or MP4 embed",accent:"from-rose-500/20 to-rose-500/5"},{type:"tour_3d",label:"3D Tour",icon:yJ,desc:"Matterport, iGuide, or Kuula embed",accent:"from-indigo-500/20 to-indigo-500/5"},{type:"floor_plans",label:"Floor Plans",icon:Mc,desc:"Upload floor plan images",accent:"from-sky-500/20 to-sky-500/5"},{type:"testimonial",label:"Testimonial",icon:x2,desc:"A quote from a past client",accent:"from-amber-500/20 to-amber-500/5"},{type:"countdown",label:"Offer Countdown",icon:da,desc:'"Offers due Friday 5pm"',accent:"from-emerald-500/20 to-emerald-500/5"},{type:"custom_cta",label:"Custom CTA Button",icon:Ad,desc:"Link to a brochure or booking page",accent:"from-violet-500/20 to-violet-500/5"}],vQn=["#0f172a","#406E71","#c9a84c","#b91c1c","#0d7a5f","#4f46e5","#e85d3a","#111827"],U$e={sections:Object.fromEntries($Xe.map(s=>[s.key,!0])),hero_style:"photo",accent_color:null,custom_note:"",addons:[]},bQn=()=>Math.random().toString(36).slice(2,10);function _Qn(){const{listingId:s}=Wi(),t=Qn(),{user:n}=vs(),r=Vt(),[a,i]=j.useState("desktop"),[l,o]=j.useState(U$e),[c,d]=j.useState(!1),[u,h]=j.useState(0),{data:m,isLoading:f}=tt({queryKey:["listing-customize",s],queryFn:async()=>{const{data:D,error:O}=await q.from("listings").select("id, agent_id, slug, property_address, city, state, price, page_config, page_theme").eq("id",s).single();if(O)throw O;return D},enabled:!!s});j.useEffect(()=>{var D,O;m!=null&&m.page_config&&o({...U$e,...m.page_config||{},sections:{...U$e.sections,...((D=m.page_config)==null?void 0:D.sections)||{}},addons:((O=m.page_config)==null?void 0:O.addons)||[]})},[m==null?void 0:m.id]);const g=!!n&&!!m&&n.id===m.agent_id,x=j.useMemo(()=>m?`/public/listing/${m.slug||m.id}?preview=1&t=${u}`:"",[m,u]),y=j.useMemo(()=>m?`https://listings.relevelup.com/${m.slug||m.id}`:"",[m]),v=ft({mutationFn:async()=>{const{error:D}=await q.from("listings").update({page_config:l}).eq("id",s);if(D)throw D},onSuccess:()=>{re.success("Saved. Your public page is live."),d(!1),r.invalidateQueries({queryKey:["listing-customize",s]}),r.invalidateQueries({queryKey:["public-listing"]}),h(D=>D+1)},onError:D=>re.error(`Save failed: ${D.message||"Try again"}`)}),b=D=>{o(O=>({...O,...D})),d(!0)},w=(D,O)=>b({sections:{...l.sections||{},[D]:O}}),S=D=>b({addons:[...l.addons||[],{id:bQn(),type:D,data:{}}]}),C=(D,O)=>b({addons:(l.addons||[]).map(U=>U.id===D?{...U,data:{...U.data,...O}}:U)}),E=D=>b({addons:(l.addons||[]).filter(O=>O.id!==D)}),I=(D,O)=>{const U=[...l.addons||[]],W=U.findIndex(G=>G.id===D);if(W<0)return;const V=W+O;V<0||V>=U.length||([U[W],U[V]]=[U[V],U[W]],b({addons:U}))};if(f)return e.jsx(Vs,{title:"",description:"",children:e.jsx("div",{className:"p-8 text-sm text-muted-foreground",children:"Loading…"})});if(!m)return e.jsx(Vs,{title:"",description:"",children:e.jsx("div",{className:"p-8",children:"Listing not found."})});if(!g)return e.jsx(Vs,{title:"",description:"",children:e.jsxs("div",{className:"p-8",children:[e.jsx("p",{children:"You can only customize your own listing pages."}),e.jsx($,{className:"mt-3",onClick:()=>t(`/mission-control/listings/${m.id}`),children:"Back"})]})});const P=(l.addons||[]).length,R=Object.values(l.sections||{}).filter(Boolean).length;return e.jsxs(Vs,{title:"",description:"",children:[e.jsxs("div",{className:"sticky top-0 z-30 -mx-4 sm:-mx-6 px-4 sm:px-6 py-3 bg-background/85 backdrop-blur border-b flex items-center gap-3",children:[e.jsxs($,{variant:"ghost",size:"sm",onClick:()=>t(`/mission-control/listings/${m.id}`),children:[e.jsx(qa,{className:"h-4 w-4 mr-1.5"})," Back"]}),e.jsxs("div",{className:"hidden md:flex flex-col leading-tight",children:[e.jsx("p",{className:"text-[10px] uppercase tracking-widest text-muted-foreground",children:"Customize Public Page"}),e.jsx("p",{className:"text-sm font-medium truncate max-w-[420px]",children:m.property_address||`${m.city}, ${m.state}`})]}),e.jsxs("div",{className:"ml-auto flex items-center gap-2",children:[c&&e.jsx("span",{className:"text-xs text-amber-600 hidden sm:inline",children:"Unsaved changes"}),e.jsxs("div",{className:"hidden md:inline-flex rounded-lg border bg-muted p-0.5",children:[e.jsxs("button",{onClick:()=>i("desktop"),className:`h-8 px-2.5 rounded-md text-xs flex items-center gap-1.5 ${a==="desktop"?"bg-background shadow-sm":"text-muted-foreground"}`,children:[e.jsx(sk,{className:"h-3.5 w-3.5"})," Desktop"]}),e.jsxs("button",{onClick:()=>i("mobile"),className:`h-8 px-2.5 rounded-md text-xs flex items-center gap-1.5 ${a==="mobile"?"bg-background shadow-sm":"text-muted-foreground"}`,children:[e.jsx(_1,{className:"h-3.5 w-3.5"})," Mobile"]})]}),e.jsxs($,{variant:"outline",size:"sm",onClick:()=>h(D=>D+1),children:[e.jsx(ro,{className:"h-3.5 w-3.5 mr-1.5"})," Refresh"]}),e.jsx($,{variant:"outline",size:"sm",asChild:!0,children:e.jsxs("a",{href:y,target:"_blank",rel:"noopener noreferrer",children:[e.jsx(kr,{className:"h-3.5 w-3.5 mr-1.5"})," Open live"]})}),e.jsx($,{size:"sm",onClick:()=>v.mutate(),disabled:!c||v.isPending,children:v.isPending?"Saving…":e.jsxs(e.Fragment,{children:[e.jsx(tl,{className:"h-3.5 w-3.5 mr-1.5"})," Save & Publish"]})})]})]}),e.jsxs("div",{className:"grid lg:grid-cols-[minmax(360px,440px)_1fr] gap-6 mt-4",children:[e.jsx(uo,{className:"lg:h-[calc(100vh-140px)] pr-2",children:e.jsxs("div",{className:"space-y-6 pb-16",children:[e.jsx(xX,{icon:e.jsx(Nn,{className:"h-4 w-4"}),title:"Hero",desc:"What visitors see first",children:e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs",children:"Hero style"}),e.jsx("div",{className:"mt-2 grid grid-cols-3 gap-2",children:["photo","video","slideshow"].map(D=>e.jsx("button",{onClick:()=>b({hero_style:D}),className:`text-xs rounded-lg border py-3 capitalize transition ${l.hero_style===D?"border-primary bg-primary/5 text-primary font-medium":"border-border hover:bg-muted"}`,children:D},D))})]})}),e.jsx(xX,{icon:e.jsx(Yc,{className:"h-4 w-4"}),title:"Accent color",desc:"Highlights on the public page",children:e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("button",{onClick:()=>b({accent_color:null}),className:`h-9 px-3 rounded-full text-xs border ${l.accent_color?"border-border hover:bg-muted":"border-primary bg-primary/5 text-primary"}`,children:"Default"}),vQn.map(D=>e.jsx("button",{onClick:()=>b({accent_color:D}),className:`h-9 w-9 rounded-full border-2 transition ${l.accent_color===D?"ring-2 ring-offset-2 ring-primary border-white":"border-white/20"}`,style:{background:D},"aria-label":D},D))]})}),e.jsx(xX,{icon:e.jsx(sy,{className:"h-4 w-4"}),title:"Personal note",desc:"Shows in a beautiful callout on the public page",children:e.jsx(Rs,{value:l.custom_note||"",onChange:D=>b({custom_note:D.target.value}),placeholder:"Why we love this home… (optional)",rows:3})}),e.jsx(xX,{icon:e.jsx(DA,{className:"h-4 w-4"}),title:"Page sections",desc:"Toggle any default section on or off",rightLabel:`${R} of ${$Xe.length} on`,children:e.jsx("div",{className:"divide-y rounded-xl border",children:$Xe.map(D=>{var U;const O=((U=l.sections)==null?void 0:U[D.key])!==!1;return e.jsxs("div",{className:"flex items-center justify-between p-3.5",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-sm font-medium",children:D.label}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:D.hint})]}),e.jsx(Sn,{checked:O,onCheckedChange:W=>w(D.key,W)})]},D.key)})})}),e.jsxs(xX,{icon:e.jsx(dn,{className:"h-4 w-4"}),title:"Add-on modules",desc:"Drop in extras to make this page unique",rightLabel:P?`${P} added`:void 0,children:[e.jsx("div",{className:"grid grid-cols-2 gap-2",children:Zrs.map(D=>e.jsxs("button",{onClick:()=>S(D.type),className:`group text-left rounded-xl border p-3 hover:shadow-md transition bg-gradient-to-br ${D.accent}`,children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx("div",{className:"h-7 w-7 rounded-md bg-background border flex items-center justify-center",children:e.jsx(D.icon,{className:"h-3.5 w-3.5"})}),e.jsx("span",{className:"text-sm font-medium",children:D.label})]}),e.jsx("p",{className:"text-[11px] text-muted-foreground leading-snug",children:D.desc})]},D.type))}),(l.addons||[]).length>0&&e.jsxs("div",{className:"mt-4 space-y-3",children:[e.jsx("p",{className:"text-[10px] uppercase tracking-widest text-muted-foreground",children:"On this page · drag to reorder"}),(l.addons||[]).map((D,O)=>e.jsx(wQn,{addon:D,onChange:U=>C(D.id,U),onRemove:()=>E(D.id),onMoveUp:O>0?()=>I(D.id,-1):void 0,onMoveDown:OI(D.id,1):void 0},D.id))]})]}),e.jsx("div",{className:"lg:hidden",children:e.jsx($,{className:"w-full",onClick:()=>v.mutate(),disabled:!c||v.isPending,children:v.isPending?"Saving…":e.jsxs(e.Fragment,{children:[e.jsx(tl,{className:"h-4 w-4 mr-1.5"})," Save & Publish"]})})})]})}),e.jsx("div",{className:"lg:h-[calc(100vh-140px)]",children:e.jsxs(Ne,{className:"h-full overflow-hidden bg-neutral-100 p-4 lg:p-6 border rounded-2xl",children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[e.jsx(Ca,{className:"h-3.5 w-3.5"}),"Live preview",c&&e.jsx(Be,{variant:"outline",className:"text-[10px] border-amber-400 text-amber-700 bg-amber-50 ml-1",children:"Save to update"}),!c&&e.jsxs("span",{className:"inline-flex items-center gap-1 text-emerald-600 ml-1",children:[e.jsx(la,{className:"h-3 w-3"})," In sync"]})]}),e.jsxs("div",{className:"lg:hidden inline-flex rounded-lg border bg-background p-0.5",children:[e.jsx("button",{onClick:()=>i("desktop"),className:`h-7 px-2 rounded ${a==="desktop"?"bg-muted":""}`,children:e.jsx(sk,{className:"h-3.5 w-3.5"})}),e.jsx("button",{onClick:()=>i("mobile"),className:`h-7 px-2 rounded ${a==="mobile"?"bg-muted":""}`,children:e.jsx(_1,{className:"h-3.5 w-3.5"})})]})]}),e.jsx("div",{className:"h-[calc(100%-32px)] w-full flex items-start justify-center overflow-auto",children:e.jsx("div",{className:`bg-neutral-950 rounded-xl shadow-2xl overflow-hidden transition-all mx-auto ${a==="mobile"?"w-[390px] h-[800px]":"w-full h-full min-h-[720px]"}`,children:e.jsx("iframe",{src:x,title:"Preview",className:"w-full h-full border-0"},u)})})]})})]})]})}function xX({icon:s,title:t,desc:n,rightLabel:r,children:a}){return e.jsxs("div",{className:"rounded-2xl border bg-card p-5",children:[e.jsxs("div",{className:"flex items-start justify-between mb-4",children:[e.jsxs("div",{className:"flex items-start gap-2.5",children:[e.jsx("div",{className:"h-8 w-8 rounded-lg bg-primary/10 text-primary flex items-center justify-center shrink-0",children:s}),e.jsxs("div",{children:[e.jsx("h3",{className:"text-sm font-semibold leading-tight",children:t}),n&&e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5",children:n})]})]}),r&&e.jsx("span",{className:"text-[10px] uppercase tracking-widest text-muted-foreground",children:r})]}),e.jsx("div",{className:"space-y-3",children:a})]})}function wQn({addon:s,onChange:t,onRemove:n,onMoveUp:r,onMoveDown:a}){const i=Zrs.find(o=>o.type===s.type),l=i.icon;return e.jsxs("div",{className:"rounded-xl border bg-background p-3.5",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[e.jsx("div",{className:"flex flex-col -my-1",children:e.jsx("button",{onClick:r,disabled:!r,className:"text-muted-foreground/50 hover:text-foreground disabled:opacity-30 leading-none",children:e.jsx(Ug,{className:"h-3.5 w-3.5"})})}),e.jsx("div",{className:"h-7 w-7 rounded-md bg-primary/10 text-primary flex items-center justify-center",children:e.jsx(l,{className:"h-3.5 w-3.5"})}),e.jsx("p",{className:"text-sm font-medium flex-1",children:i.label}),e.jsxs("div",{className:"flex items-center gap-1",children:[a&&e.jsx($,{size:"icon",variant:"ghost",className:"h-7 w-7",onClick:a,"aria-label":"Move down",children:e.jsx(Ug,{className:"h-3.5 w-3.5 rotate-180"})}),e.jsx($,{size:"icon",variant:"ghost",className:"h-7 w-7 text-destructive hover:text-destructive",onClick:n,"aria-label":"Remove",children:e.jsx(Wn,{className:"h-3.5 w-3.5"})})]})]}),s.type==="extra_video"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{className:"text-xs",children:"Video URL"}),e.jsx(pe,{placeholder:"https://youtu.be/…",value:s.data.url||"",onChange:o=>t({url:o.target.value})}),e.jsx(ee,{className:"text-xs",children:"Title (optional)"}),e.jsx(pe,{placeholder:"e.g. Sunset drone flyover",value:s.data.title||"",onChange:o=>t({title:o.target.value})})]}),s.type==="tour_3d"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{className:"text-xs",children:"3D tour embed URL"}),e.jsx(pe,{placeholder:"https://my.matterport.com/show/?m=…",value:s.data.url||"",onChange:o=>t({url:o.target.value})})]}),s.type==="floor_plans"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{className:"text-xs",children:"Floor plan image URLs (one per line)"}),e.jsx(Rs,{rows:3,placeholder:`https://…/floor1.jpg https://…/floor2.jpg`,value:(s.data.urls||[]).join(` `),onChange:o=>t({urls:o.target.value.split(` `).map(c=>c.trim()).filter(Boolean)})})]}),s.type==="testimonial"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{className:"text-xs",children:"Quote"}),e.jsx(Rs,{rows:3,placeholder:`"Best home-buying experience we've ever had."`,value:s.data.quote||"",onChange:o=>t({quote:o.target.value})}),e.jsx(ee,{className:"text-xs",children:"Attribution"}),e.jsx(pe,{placeholder:"Sarah & Mike, past clients",value:s.data.author||"",onChange:o=>t({author:o.target.value})})]}),s.type==="countdown"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{className:"text-xs",children:"Headline"}),e.jsx(pe,{placeholder:"Offers due",value:s.data.headline||"",onChange:o=>t({headline:o.target.value})}),e.jsx(ee,{className:"text-xs",children:"Deadline (date & time)"}),e.jsx(pe,{type:"datetime-local",value:s.data.deadline||"",onChange:o=>t({deadline:o.target.value})})]}),s.type==="custom_cta"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{className:"text-xs",children:"Button label"}),e.jsx(pe,{placeholder:"Download brochure",value:s.data.label||"",onChange:o=>t({label:o.target.value})}),e.jsx(ee,{className:"text-xs",children:"Link URL"}),e.jsx(pe,{placeholder:"https://…",value:s.data.url||"",onChange:o=>t({url:o.target.value})})]})]})}const Xrs="teleprompter_settings",q$e={scrollSpeed:30,fontSize:24,lineHeight:1.6,opacity:.85,position:"top",isMirrored:!1};function jQn(){try{const s=localStorage.getItem(Xrs);return s?{...q$e,...JSON.parse(s)}:q$e}catch{return q$e}}function NQn(s){try{localStorage.setItem(Xrs,JSON.stringify(s))}catch{}}function Jot({text:s,isVisible:t,onToggleVisibility:n,isRecording:r=!1,startCountdown:a=!1,onCountdownComplete:i,className:l}){const o=j.useRef(null),c=j.useRef(null),d=j.useRef(0),u=j.useRef(0),[h,m]=j.useState(jQn),{scrollSpeed:f,fontSize:g,lineHeight:x,opacity:y,position:v,isMirrored:b}=h,w=j.useCallback((U,W)=>{m(V=>{const G={...V,[U]:W};return NQn(G),G})},[]),[S,C]=j.useState(!1),[E,I]=j.useState(null),P=j.useCallback(U=>{if(!o.current)return;d.current===0&&(d.current=U);const W=U-d.current;d.current=U,u.current+=f*W/1e3;const V=Math.floor(u.current);V>0&&(o.current.scrollTop+=V,u.current-=V);const{scrollTop:G,scrollHeight:Y,clientHeight:X}=o.current;if(G+X>=Y){C(!1);return}c.current=requestAnimationFrame(P)},[f]);j.useEffect(()=>(S?(d.current=0,u.current=0,c.current=requestAnimationFrame(P)):c.current&&cancelAnimationFrame(c.current),()=>{c.current&&cancelAnimationFrame(c.current)}),[S,P]),j.useEffect(()=>{if(r&&t)if(o.current&&(o.current.scrollTop=0),a){I(3);let U=3;const W=setInterval(()=>{U-=1,U<=0?(clearInterval(W),I(null),i==null||i(),C(!0)):I(U)},1e3);return()=>clearInterval(W)}else setTimeout(()=>C(!0),100);else r||(C(!1),I(null))},[r,t,a,i]);const R=j.useCallback(()=>{o.current&&(o.current.scrollTop=0),C(!1)},[]),D=j.useCallback(()=>{C(U=>!U)},[]);if(!t)return e.jsx("div",{className:Pt("absolute top-4 right-4 pointer-events-auto z-10",l),children:e.jsxs($,{variant:"secondary",size:"sm",onClick:n,className:"bg-black/50 hover:bg-black/70 text-white border-0",children:[e.jsx(Ca,{className:"h-4 w-4 mr-2"}),"Show Script"]})});const O={top:"top-0 pt-16",center:"top-1/2 -translate-y-1/2",bottom:"bottom-0 pb-24"};return e.jsxs("div",{className:Pt("absolute inset-0 pointer-events-none",l),children:[E!==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:E},E),e.jsx("p",{className:"text-white/80 text-lg font-medium drop-shadow-md",children:"Get ready…"})]})}),e.jsx("div",{className:Pt("absolute left-0 right-0 h-[60%] overflow-hidden pointer-events-auto",O[v],E!==null&&"opacity-30"),style:{opacity:E!==null?.3:y},children:e.jsxs("div",{ref:o,className:Pt("mx-auto max-w-2xl px-6 overflow-y-auto scrollbar-hide h-full",b&&"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:`${g}px`,lineHeight:x,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(Yd,{children:[e.jsx(Zd,{asChild:!0,children:e.jsx($,{variant:"secondary",size:"icon",className:"h-9 w-9 bg-black/50 hover:bg-black/70 text-white border-0",children:e.jsx(Sd,{className:"h-4 w-4"})})}),e.jsx(Bd,{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(ee,{className:"text-xs",children:"Scroll Speed"}),e.jsx("span",{className:"text-xs text-muted-foreground",children:f})]}),e.jsx(kx,{value:[f],onValueChange:([U])=>w("scrollSpeed",U),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(ee,{className:"text-xs",children:"Font Size"}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[g,"px"]})]}),e.jsx(kx,{value:[g],onValueChange:([U])=>w("fontSize",U),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(ee,{className:"text-xs",children:"Line Spacing"}),e.jsx("span",{className:"text-xs text-muted-foreground",children:x.toFixed(1)})]}),e.jsx(kx,{value:[x*10],onValueChange:([U])=>w("lineHeight",U/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(ee,{className:"text-xs",children:"Opacity"}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[Math.round(y*100),"%"]})]}),e.jsx(kx,{value:[y*100],onValueChange:([U])=>w("opacity",U/100),min:30,max:100,step:5})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{className:"text-xs",children:"Position"}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx($,{variant:v==="top"?"default":"outline",size:"sm",onClick:()=>w("position","top"),children:e.jsx(v1,{className:"h-4 w-4"})}),e.jsx($,{variant:v==="center"?"default":"outline",size:"sm",onClick:()=>w("position","center"),children:e.jsx(tk,{className:"h-4 w-4"})}),e.jsx($,{variant:v==="bottom"?"default":"outline",size:"sm",onClick:()=>w("position","bottom"),children:e.jsx(Tl,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(ee,{className:"text-xs",children:"Mirror Mode"}),e.jsx(Sn,{checked:b,onCheckedChange:U=>w("isMirrored",U)})]})]})})]}),e.jsx($,{variant:"secondary",size:"icon",onClick:D,className:"h-9 w-9 bg-black/50 hover:bg-black/70 text-white border-0",children:S?e.jsx(Tv,{className:"h-4 w-4"}):e.jsx(Bu,{className:"h-4 w-4"})}),e.jsx($,{variant:"secondary",size:"icon",onClick:R,className:"h-9 w-9 bg-black/50 hover:bg-black/70 text-white border-0",children:e.jsx(Ex,{className:"h-4 w-4"})}),e.jsxs($,{variant:"secondary",size:"sm",onClick:n,className:"bg-black/50 hover:bg-black/70 text-white border-0",children:[e.jsx($g,{className:"h-4 w-4 mr-2"}),"Hide"]})]})]})}function kQn({onSelectScript:s,onCreateNew:t,selectedScriptId:n,className:r}){const{toast:a}=Bi(),[i,l]=j.useState(""),[o,c]=j.useState(null),[d,u]=j.useState("levelup"),{data:h,isLoading:m}=D9n(),{data:f,isLoading:g}=F9n(),{data:x,isLoading:y}=O9n(),v=z9n(),b=j.useMemo(()=>f?f.filter(I=>{const P=!i||I.title.toLowerCase().includes(i.toLowerCase())||I.script_text.toLowerCase().includes(i.toLowerCase())||I.tags.some(D=>D.toLowerCase().includes(i.toLowerCase())),R=!o||I.category_id===o;return P&&R}):[],[f,i,o]),w=j.useMemo(()=>x?x.filter(I=>!i||I.title.toLowerCase().includes(i.toLowerCase())||I.script_text.toLowerCase().includes(i.toLowerCase())):[],[x,i]),S=I=>{s({title:I.title,text:I.script_text})},C=async I=>{try{await v.mutateAsync(I),a({title:"Script saved to My Scripts"})}catch{a({title:"Failed to save script",variant:"destructive"})}},E=m||g||y;return e.jsxs("div",{className:Pt("flex flex-col h-full",r),children:[e.jsx("div",{className:"p-4 border-b",children:e.jsxs("div",{className:"relative",children:[e.jsx(Kr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(pe,{placeholder:"Search scripts...",value:i,onChange:I=>l(I.target.value),className:"pl-9"})]})}),e.jsxs(ha,{value:d,onValueChange:I=>u(I),className:"flex-1 flex flex-col",children:[e.jsxs(ma,{className:"mx-4 mt-4 grid grid-cols-2",children:[e.jsxs(Zt,{value:"levelup",children:[e.jsx(Jr,{className:"h-4 w-4 mr-2"}),"LevelUp Scripts"]}),e.jsxs(Zt,{value:"my-scripts",children:[e.jsx(M0,{className:"h-4 w-4 mr-2"}),"My Scripts"]})]}),e.jsxs(Xt,{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(Be,{variant:o?"outline":"default",className:"cursor-pointer",onClick:()=>c(null),children:"All"}),h==null?void 0:h.map(I=>e.jsx(Be,{variant:o===I.id?"default":"outline",className:"cursor-pointer",onClick:()=>c(I.id),children:I.name},I.id))]}),e.jsx(uo,{className:"flex-1 max-h-[50vh]",children:E?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(kt,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):b.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(Jr,{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:b.map(I=>e.jsxs(Ne,{className:Pt("cursor-pointer hover:bg-accent/50 transition-colors",n===I.id&&"ring-2 ring-primary"),onClick:()=>S(I),children:[e.jsx(Ct,{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(At,{className:"text-sm font-medium truncate",children:I.title}),I.category&&e.jsx(Be,{variant:"secondary",className:"mt-1 text-xs",children:I.category.name})]}),e.jsxs("div",{className:"flex items-center gap-1 ml-2",children:[e.jsx($,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:P=>{P.stopPropagation(),C(I)},children:e.jsx(M0,{className:"h-4 w-4"})}),e.jsx(Di,{className:"h-4 w-4 text-muted-foreground"})]})]})}),e.jsx(Ie,{className:"p-3 pt-0",children:e.jsx("p",{className:"text-xs text-muted-foreground line-clamp-2",children:I.script_text})})]},I.id))})})]}),e.jsxs(Xt,{value:"my-scripts",className:"flex-1 flex flex-col mt-0 p-4",children:[t&&e.jsxs($,{variant:"outline",className:"mb-4",onClick:t,children:[e.jsx(dn,{className:"h-4 w-4 mr-2"}),"Create New Script"]}),e.jsx(uo,{className:"flex-1 max-h-[50vh]",children:y?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(kt,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):w.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(M0,{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:w.map(I=>e.jsxs(Ne,{className:Pt("cursor-pointer hover:bg-accent/50 transition-colors",n===I.id&&"ring-2 ring-primary"),onClick:()=>S(I),children:[e.jsx(Ct,{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(At,{className:"text-sm font-medium truncate",children:I.title}),e.jsx("div",{className:"flex items-center gap-2 mt-1",children:I.is_custom?e.jsx(Be,{variant:"outline",className:"text-xs",children:"Custom"}):e.jsx(Be,{variant:"secondary",className:"text-xs",children:"Saved"})})]}),e.jsx(Di,{className:"h-4 w-4 text-muted-foreground ml-2"})]})}),e.jsx(Ie,{className:"p-3 pt-0",children:e.jsx("p",{className:"text-xs text-muted-foreground line-clamp-2",children:I.script_text})})]},I.id))})})]})]})]})}function SQn({selectedTemplate:s,onSelect:t,contactName:n,saving:r=!1}){const[a,i]=j.useState(()=>{const o=kV(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(ee,{className:"text-sm font-medium",children:"Share Page Template"}),r&&e.jsx(kt,{className:"h-3 w-3 animate-spin text-muted-foreground"})]}),e.jsx("div",{className:"space-y-3",children:Sqs.map(o=>{const c=Cqs(o.id),d=a.has(o.id),u=c.some(h=>h.id===s);return e.jsxs(j1,{open:d,onOpenChange:()=>l(o.id),children:[e.jsxs(N1,{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,")"]}),u&&!d&&e.jsx("span",{className:"text-xs bg-primary/10 text-primary px-1.5 py-0.5 rounded-full",children:"✓"})]}),e.jsx(Tl,{className:Pt("h-4 w-4 text-muted-foreground transition-transform",d&&"rotate-180")})]}),e.jsx(k1,{className:"pt-2",children:e.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 gap-2",children:c.map(h=>{const m=s===h.id;return e.jsxs("button",{type:"button",onClick:()=>t(h.id),disabled:r,className:Pt("relative rounded-lg border-2 p-2.5 text-left transition-all hover:shadow-sm disabled:opacity-50 disabled:cursor-not-allowed",m?"border-primary ring-1 ring-primary/20 bg-primary/5":"border-muted hover:border-muted-foreground/30"),children:[m&&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(la,{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:h.icon}),e.jsx("span",{className:"text-sm font-medium truncate",children:h.name})]})]},h.id)})})})]},o.id)})}),n&&s!=="default"&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:['Will show: "',kV(s).headerText(n),'"']})]})}function Qrs({open:s,onOpenChange:t,video:n,contactName:r,onTemplateUpdated:a}){const[i,l]=j.useState(n.page_template||"default"),[o,c]=j.useState(!1),[d,u]=j.useState(!1),[h,m]=j.useState(n.page_template||"default"),[f,g]=j.useState([]),[x,y]=j.useState(n.contact_id&&r?{id:n.contact_id,name:r,email:null}:null),[v,b]=j.useState(!1),[w,S]=j.useState(!1),C=n.share_token?`https://video.relevelup.com/${n.share_token}`:"";j.useEffect(()=>{s&&f.length===0&&E()},[s]);const E=async()=>{S(!0);try{const{data:G,error:Y}=await q.from("innercircle_contacts").select("id, first_name, last_name, email").order("first_name",{ascending:!0}).limit(500);if(Y)throw Y;const X=(G||[]).map(ae=>({id:ae.id,name:[ae.first_name,ae.last_name].filter(Boolean).join(" ")||"Unnamed",email:ae.email||null}));g(X)}catch(G){console.error("Failed to fetch contacts:",G)}finally{S(!1)}},I=async G=>{y(G),b(!1),c(!0);try{const{error:Y}=await q.from("agent_videos").update({contact_id:(G==null?void 0:G.id)||null,recipient_name:(G==null?void 0:G.name)||null}).eq("id",n.id);if(Y)throw Y;re.success(G?`Assigned to ${G.name}`:"Contact removed"),a==null||a()}catch(Y){console.error("Failed to update contact:",Y),re.error("Failed to update contact")}finally{c(!1)}},P=async G=>{l(G),c(!0);try{const{error:Y}=await q.from("agent_videos").update({page_template:G}).eq("id",n.id);if(Y)throw Y;m(G),re.success("Template saved!"),a==null||a()}catch(Y){console.error("Failed to save template:",Y),re.error("Failed to save template"),l(h)}finally{c(!1)}},R=(x==null?void 0:x.name)||null,D=()=>{const G=n.title||"Video Message",Y=n.share_token?`https://video.relevelup.com/thumb/${n.share_token}`:n.thumbnail_url||"";return``},O=async()=>{if(!n.thumbnail_url){re.error("Video thumbnail not available yet");return}const G=D(),Y=`Watch: ${n.title||"Video Message"} ${C}`;try{const X=new Blob([G],{type:"text/html"}),ae=new Blob([Y],{type:"text/plain"}),ie=new ClipboardItem({"text/html":X,"text/plain":ae});await navigator.clipboard.write([ie]),re.success("Copied! Paste into Gmail - the thumbnail will appear after sending.")}catch{await navigator.clipboard.writeText(Y+` `+G),re.success("Copied! Paste into your email.")}},U=async()=>{await navigator.clipboard.writeText(C),u(!0),re.success("Share link copied!"),setTimeout(()=>u(!1),2e3)},W=()=>{const Y=kV(i).headerText(R),X=i==="default"?`Check out this video: ${C}`:`${Y} Check out this special video: ${C}`;window.open(`sms:?body=${encodeURIComponent(X)}`,"_self")},V=()=>{const G=kV(i),Y=G.headerText(R),X=i==="default"?n.title||"Video Message":Y,ae=`${G.subText} Watch the video: ${C}`,ie=x!=null&&x.email?encodeURIComponent(x.email):"";window.open(`mailto:${ie}?subject=${encodeURIComponent(X)}&body=${encodeURIComponent(ae)}`,"_self")};return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Os,{className:"max-w-lg max-h-[90vh] overflow-y-auto",children:[e.jsxs(Us,{children:[e.jsxs(Bs,{className:"flex items-center gap-2",children:[e.jsx(Ad,{className:"h-5 w-5"}),"Share Video"]}),e.jsx(Ir,{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(ee,{className:"text-sm font-medium",children:"Personalize for Contact (Optional)"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(Yd,{open:v,onOpenChange:b,children:[e.jsx(Zd,{asChild:!0,children:e.jsxs($,{variant:"outline",role:"combobox","aria-expanded":v,className:"flex-1 justify-between",disabled:o,children:[x?e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(sl,{className:"h-4 w-4 text-muted-foreground"}),x.name]}):e.jsx("span",{className:"text-muted-foreground",children:"Select a contact..."}),e.jsx(Pw,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(Bd,{className:"w-[300px] p-0",align:"start",children:e.jsxs(P2,{children:[e.jsx(I2,{placeholder:"Search contacts..."}),e.jsxs(L2,{children:[e.jsx(R2,{children:w?"Loading...":"No contacts found."}),e.jsx(Uw,{children:f.map(G=>e.jsxs(g1,{value:G.name,onSelect:()=>I(G),children:[e.jsx(la,{className:Pt("mr-2 h-4 w-4",(x==null?void 0:x.id)===G.id?"opacity-100":"opacity-0")}),G.name]},G.id))})]})]})})]}),x&&e.jsx($,{variant:"ghost",size:"icon",onClick:()=>I(null),disabled:o,className:"shrink-0",children:e.jsx(gr,{className:"h-4 w-4"})})]}),x&&i!=="default"&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:['Page will show: "',kV(i).headerText(x.name),'"']})]}),e.jsx(SQn,{selectedTemplate:i,onSelect:P,contactName:R,saving:o}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Share Link"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(pe,{value:C,readOnly:!0,className:"font-mono text-sm"}),e.jsx($,{onClick:U,variant:d?"default":"outline",className:"shrink-0 gap-2",children:d?e.jsxs(e.Fragment,{children:[e.jsx(la,{className:"h-4 w-4"}),"Copied"]}):e.jsxs(e.Fragment,{children:[e.jsx(Ha,{className:"h-4 w-4"}),"Copy"]})})]})]}),n.thumbnail_url&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Share for Email"}),e.jsxs($,{variant:"outline",className:"w-full gap-2",onClick:O,children:[e.jsx(Mc,{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(ee,{children:"Quick Share"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs($,{variant:"outline",className:"flex-1 gap-2",onClick:W,children:[e.jsx(eo,{className:"h-4 w-4"}),"Text"]}),e.jsxs($,{variant:"outline",className:"flex-1 gap-2",onClick:V,children:[e.jsx(mn,{className:"h-4 w-4"}),"Email"]})]})]})]}),e.jsx(Ar,{children:e.jsx($,{variant:"outline",onClick:()=>t(!1),children:"Done"})})]})})}function CQn(){var qe;const s=Qn(),[t]=gc(),{toast:n}=Bi(),r=t.get("contact_id"),a=t.get("task_id"),{canRecord:i,remainingMb:l,usagePercent:o,isNearLimit:c}=HQt(),{data:d}=z_(),u=x3(),h=V9n(),[m,f]=j.useState("record"),[g,x]=j.useState(""),[y,v]=j.useState(!1),[b,w]=j.useState(!1),[S,C]=j.useState(!1),[E,I]=j.useState(null),[P,R]=j.useState(0),[D,O]=j.useState(0),[U,W]=j.useState(null),[V,G]=j.useState(null),[Y,X]=j.useState(r||""),[ae,ie]=j.useState(""),[ne,te]=j.useState(""),[J,ce]=j.useState(null),[_e,he]=j.useState(null),[ue,ve]=j.useState(null),[Ee,Se]=j.useState(!1),Le=j.useCallback(async(ze,$e)=>{I(ze),f("uploading");try{const{videoId:ct,uploadUrl:Xe}=await P6(ae||"Quick Video Touch");W(ct);const{apiKey:it}=await I6(ct),at=new XMLHttpRequest;at.upload.onprogress=rt=>{rt.lengthComputable&&R(rt.loaded/rt.total*100)},await new Promise((rt,Yt)=>{at.onload=()=>{at.status>=200&&at.status<300?rt():Yt(new Error(`Upload failed: ${at.status}`))},at.onerror=()=>Yt(new Error("Upload failed")),at.open("PUT",Xe),at.setRequestHeader("AccessKey",it),at.send(ze)}),f("processing");let Ke=0;const nt=Date.now(),xt=90*1e3;for(;Ke<4;){if(await new Promise(Yt=>setTimeout(Yt,3e3)),Date.now()-nt>xt){const Yt=ze.size/1048576,qt=`https://iframe.mediadelivery.net/play/${ct}/${ct}`;await u.mutateAsync({bunny_video_id:ct,playback_url:qt,file_size_mb:Yt,title:ae||"Quick Video Touch",notes:ne||void 0,contact_id:Y&&Y!=="none"?Y:void 0,status:"processing",touch_type:"video_touch"}),n({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 rt=await gk(ct);if(Ke=rt.status,O(rt.encodeProgress||0),Ke===4)G({playbackUrl:rt.directPlayUrl,thumbnailUrl:rt.thumbnailUrl,previewUrl:rt.previewUrl||null,duration:rt.length||$e,fileSizeMb:(rt.storageSize||ze.size)/(1024*1024)});else if(Ke===5||Ke===6)throw new Error("Video processing failed")}f("details")}catch(ct){console.error("Upload error:",ct),n({title:"Upload failed",description:"Please try recording again.",variant:"destructive"}),f("record")}},[ae,n]),Fe=async()=>{if(!(!U||!V))try{const ze=Y&&Y!=="none"?Y:null,$e=await u.mutateAsync({bunny_video_id:U,contact_id:ze,playback_url:V.playbackUrl,thumbnail_url:V.thumbnailUrl,preview_url:V.previewUrl,duration_seconds:V.duration,file_size_mb:V.fileSizeMb,title:ae||"Quick Video Touch",notes:ne,task_id:a||null,status:"ready"});ce($e.id),he($e.share_token||null),ze&&await h.mutateAsync({contactId:ze,videoId:$e.id,notes:ne}),n({title:"Video saved successfully!"}),f("share")}catch(ze){console.error("Save video error:",ze),n({title:"Failed to save video",description:(ze==null?void 0:ze.message)||"Please try again.",variant:"destructive"})}},ke=(ze,$e)=>{navigator.clipboard.writeText($e),ve(ze),setTimeout(()=>ve(null),2e3),n({title:"Copied to clipboard!"})},Ve=()=>_e?`https://video.relevelup.com/${_e}`:(V==null?void 0:V.playbackUrl)||"",je=()=>{const ze=d==null?void 0:d.find(at=>at.id===Y),$e=ze?`${ze.first_name}`:"",ct=(ze==null?void 0:ze.phone)||"",Xe=(ze==null?void 0:ze.email)||"",it=Ve();return{text:`Hey${$e?` ${$e}`:""}! I recorded a quick video for you: ${it}`,link:it,contactPhone:ct,contactEmail:Xe}},Ae=()=>{const{text:ze,contactPhone:$e}=je(),ct=$e?`sms:${$e}?body=${encodeURIComponent(ze)}`:`sms:?body=${encodeURIComponent(ze)}`;window.open(ct,"_self")},Ce=()=>{const{link:ze,contactEmail:$e}=je(),ct="Check out this video",Xe=`I recorded a quick video for you: ${ze}`,it=$e?`mailto:${$e}?subject=${encodeURIComponent(ct)}&body=${encodeURIComponent(Xe)}`:`mailto:?subject=${encodeURIComponent(ct)}&body=${encodeURIComponent(Xe)}`;window.open(it,"_self")};return i?e.jsx(Vs,{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($,{variant:"ghost",size:"icon",onClick:()=>s(-1),children:e.jsx(qa,{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($,{variant:"outline",size:"sm",onClick:()=>s("/mission-control/video-library"),className:"gap-1.5",children:[e.jsx(Jr,{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"]})]})]})]}),m==="record"&&e.jsxs("div",{className:"grid gap-6 lg:grid-cols-3",children:[e.jsxs("div",{className:"lg:col-span-2",children:[e.jsx(BT,{maxDurationSeconds:600,onRecordingComplete:Le,onRecordingStateChange:C,className:"w-full",teleprompterContent:y&&g&&e.jsx(Jot,{text:g,isVisible:y,onToggleVisibility:()=>v(!1),isRecording:S,startCountdown:!1})}),!y&&g&&e.jsxs($,{variant:"outline",className:"mt-4",onClick:()=>v(!0),children:[e.jsx(Jr,{className:"h-4 w-4 mr-2"}),"Show Teleprompter"]})]}),e.jsxs(Ne,{className:"lg:col-span-1",children:[e.jsx(Ct,{className:"pb-2",children:e.jsx(At,{className:"text-lg",children:"Teleprompter Script"})}),e.jsxs(Ie,{className:"space-y-4",children:[e.jsx(Rs,{placeholder:"Type or paste your script here...",value:g,onChange:ze=>x(ze.target.value),rows:6}),e.jsxs(Wy,{open:b,onOpenChange:w,children:[e.jsx(Fae,{asChild:!0,children:e.jsxs($,{variant:"outline",className:"w-full",children:[e.jsx(Jr,{className:"h-4 w-4 mr-2"}),"Browse Scripts"]})}),e.jsxs(py,{side:"right",className:"w-[400px] sm:w-[540px] p-0",children:[e.jsx(D0,{className:"p-4 border-b",children:e.jsx(F0,{children:"Select a Script"})}),e.jsx(kQn,{onSelectScript:ze=>{x(ze.text),w(!1),v(!0)},className:"h-[calc(100vh-80px)]"})]})]}),g&&e.jsx($,{className:"w-full",onClick:()=>v(!0),children:"Use Script"})]})]})]}),m==="uploading"&&e.jsx(Ne,{className:"max-w-md mx-auto",children:e.jsxs(Ie,{className:"pt-6 text-center",children:[e.jsx(ni,{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(Yi,{value:P,className:"mb-2"}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[P.toFixed(0),"%"]})]})}),m==="processing"&&e.jsx(Ne,{className:"max-w-md mx-auto",children:e.jsxs(Ie,{className:"pt-6 text-center space-y-4",children:[e.jsx(kt,{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(Yi,{value:D,className:"mb-2"}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[D.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.`})]})}),m==="details"&&e.jsxs(Ne,{className:"max-w-lg mx-auto",children:[e.jsx(Ct,{children:e.jsx(At,{children:"Video Details"})}),e.jsxs(Ie,{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(ee,{children:"Title"}),e.jsx(pe,{value:ae,onChange:ze=>ie(ze.target.value),placeholder:"Quick Video Touch"})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Attach to Contact (Optional)"}),e.jsxs(ms,{value:Y,onValueChange:X,children:[e.jsx(us,{children:e.jsx(fs,{placeholder:"No contact - use anywhere"})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"none",children:e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground",children:[e.jsx(Ad,{className:"h-4 w-4"}),"No contact - use anywhere"]})}),d==null?void 0:d.map(ze=>e.jsx(Ge,{value:ze.id,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(sl,{className:"h-4 w-4"}),ze.first_name," ",ze.last_name]})},ze.id))]})]})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Notes"}),e.jsx(Rs,{value:ne,onChange:ze=>te(ze.target.value),placeholder:"Add notes about this video...",rows:3})]}),e.jsxs($,{className:"w-full",onClick:Fe,disabled:u.isPending,children:[u.isPending&&e.jsx(kt,{className:"h-4 w-4 mr-2 animate-spin"}),"Save Video"]})]})]}),m==="share"&&e.jsxs(Ne,{className:"max-w-lg mx-auto",children:[e.jsx(Ct,{children:e.jsxs(At,{className:"flex items-center gap-2",children:[e.jsx(la,{className:"h-5 w-5 text-green-500"}),"Video Saved!"]})}),e.jsxs(Ie,{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($,{variant:"outline",className:"justify-start",onClick:Ae,children:[e.jsx(eo,{className:"h-4 w-4 mr-2"}),"Text Contact Video"]}),e.jsxs($,{variant:"outline",className:"justify-start",onClick:Ce,children:[e.jsx(mn,{className:"h-4 w-4 mr-2"}),"Email Contact Video"]}),e.jsxs($,{variant:"outline",className:"justify-start",onClick:()=>ke("link",je().link),children:[e.jsx(Ad,{className:"h-4 w-4 mr-2"}),"Copy Video Link",ue==="link"&&e.jsx(la,{className:"h-4 w-4 ml-auto text-green-500"})]}),e.jsxs($,{variant:"outline",className:"justify-start",onClick:()=>Se(!0),children:[e.jsx(Yc,{className:"h-4 w-4 mr-2"}),"Send with Page Template"]})]}),e.jsxs("div",{className:"flex gap-3 pt-4",children:[e.jsx($,{variant:"outline",onClick:()=>s("/mission-control/video-library"),children:"View Library"}),e.jsx($,{onClick:()=>{f("record"),I(null),W(null),G(null)},children:"Record Another"})]})]})]}),J&&_e&&e.jsx(Qrs,{open:Ee,onOpenChange:Se,video:{id:J,share_token:_e,title:ae||null,contact_id:Y||null,thumbnail_url:(V==null?void 0:V.thumbnailUrl)||null},contactName:((qe=d==null?void 0:d.find(ze=>ze.id===Y))==null?void 0:qe.first_name)||null})]})}):e.jsx(Vs,{title:"QuickVid",children:e.jsxs("div",{className:"max-w-2xl mx-auto text-center py-12",children:[e.jsx(wl,{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($,{onClick:()=>s("/mission-control/video-library"),children:"Open Video Library"})]})})}function AQn({open:s,onOpenChange:t,video:n,gmailEmail:r,signedThumbnailUrl:a,onSendComplete:i}){const[l,o]=j.useState([]),[c,d]=j.useState(null),[u,h]=j.useState(!1),[m,f]=j.useState(!1),[g,x]=j.useState(""),[y,v]=j.useState(""),[b,w]=j.useState(""),[S,C]=j.useState(!1),E=BQt(),I=n.share_token?`https://video.relevelup.com/share/video/${n.share_token}`:"",P=n.share_token?`https://video.relevelup.com/thumb/${n.share_token}`:a||n.thumbnail_url||"",R=n.title||"Video Message";j.useEffect(()=>{s&&l.length===0&&D()},[s]),j.useEffect(()=>{if(s&&(v(`I recorded a video for you — ${R}`),w("Hey! I recorded a quick video just for you. Click below to watch it:"),d(null),x(""),n.contact_id)){const Y=l.find(X=>X.id===n.contact_id);Y&&(d(Y),x(Y.email||""))}},[s,n.contact_id,l]);const D=async()=>{f(!0);try{const{data:Y,error:X}=await q.from("innercircle_contacts").select("id, first_name, last_name, email").order("first_name",{ascending:!0}).limit(500);if(X)throw X;o(Y||[])}catch{console.error("Failed to fetch contacts")}finally{f(!1)}},O=Y=>{d(Y),h(!1),x(Y.email||""),w(`Hey ${Y.first_name}! I recorded a quick video just for you. Click below to watch it:`),v(`I recorded a video for you — ${R}`)},U=()=>{d(null),x(""),w("Hey! I recorded a quick video just for you. Click below to watch it:")},W=Y=>{const X=`${Y.first_name||""} ${Y.last_name||""}`.replace(/<[^>]*>/g," ").replace(/\s+/g," ").trim();return X?X.length>60?`${X.slice(0,60)}…`:X:Y.email||"Unnamed contact"},V=Y=>{const X=b.split(/\n\n+/).map(ne=>`

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

`).join(""),ae=Y?UQt(Y):I,ie=Y?``:"";return`
${X}

▶ Watch Video

${ie}
`},G=async()=>{var Y;if(!g){re.error("Please enter a recipient email");return}if(!I){re.error("Video does not have a share link");return}C(!0);try{let X;try{const J=c?W(c):g.split("@")[0];X=(await E.mutateAsync({video_id:n.id,recipient_email:g,recipient_name:J,contact_id:(c==null?void 0:c.id)||null,sent_via:"gmail"})).share_token}catch(J){console.warn("Failed to create tracking record, sending without tracking:",J)}const ae=V(X),{data:ie,error:ne}=await q.functions.invoke("gmail-send",{body:{to:g,subject:y,body:ae,contactId:(c==null?void 0:c.id)||null}});let te=null;if(ne&&((Y=ne.context)!=null&&Y.json))try{te=await ne.context.json()}catch{}if((te==null?void 0:te.error)==="insufficient_scope"||(ie==null?void 0:ie.error)==="insufficient_scope"){re.error((te==null?void 0:te.message)||"Gmail is missing send permission. Please disconnect and reconnect Gmail, allowing 'Send email on your behalf'.",{duration:1e4});return}if(ne)throw new Error((te==null?void 0:te.message)||ne.message);if(!(ie!=null&&ie.success))throw new Error((ie==null?void 0:ie.error)||"Failed to send");re.success("Video email sent!"),t(!1),i==null||i()}catch(X){console.error("Gmail send error:",X),re.error("Failed to send: "+(X instanceof Error?X.message:"Unknown error"))}finally{C(!1)}};return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Os,{className:"sm:max-w-[560px] max-h-[90vh] overflow-y-auto",children:[e.jsxs(Us,{children:[e.jsxs(Bs,{className:"flex items-center gap-2",children:[e.jsx(mn,{className:"h-5 w-5 text-red-500"}),"Send Video via Gmail"]}),r&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Sending from ",e.jsx("span",{className:"font-medium",children:r})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Send to Contact"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(Yd,{open:u,onOpenChange:h,children:[e.jsx(Zd,{asChild:!0,children:e.jsxs($,{variant:"outline",role:"combobox",className:"flex-1 justify-between",children:[c?e.jsxs("span",{className:"flex items-center gap-2 min-w-0",children:[e.jsx(sl,{className:"h-4 w-4 shrink-0 text-muted-foreground"}),e.jsx("span",{className:"truncate",children:W(c)}),c.email&&e.jsxs("span",{className:"text-muted-foreground text-xs truncate",children:["(",c.email,")"]})]}):e.jsx("span",{className:"text-muted-foreground",children:"Select a contact..."}),e.jsx(Pw,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(Bd,{className:"w-[350px] p-0",align:"start",children:e.jsxs(P2,{children:[e.jsx(I2,{placeholder:"Search contacts..."}),e.jsxs(L2,{children:[e.jsx(R2,{children:m?"Loading...":"No contacts found."}),e.jsx(Uw,{children:l.filter(Y=>Y.email).map(Y=>e.jsxs(g1,{value:`${W(Y)} ${Y.email||""}`,onSelect:()=>O(Y),children:[e.jsx(la,{className:Pt("mr-2 h-4 w-4",(c==null?void 0:c.id)===Y.id?"opacity-100":"opacity-0")}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"font-medium truncate",children:W(Y)}),e.jsx("div",{className:"text-xs text-muted-foreground truncate",children:Y.email})]})]},Y.id))})]})]})})]}),c&&e.jsx($,{variant:"ghost",size:"icon",onClick:U,className:"shrink-0",children:e.jsx(gr,{className:"h-4 w-4"})})]})]}),!c&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{htmlFor:"video-to",children:"Or type email address"}),e.jsx(pe,{id:"video-to",value:g,onChange:Y=>x(Y.target.value),placeholder:"recipient@example.com",type:"email"})]}),e.jsx(Gc,{}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{htmlFor:"video-subject",children:"Subject"}),e.jsx(pe,{id:"video-subject",value:y,onChange:Y=>v(Y.target.value)})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{htmlFor:"video-message",children:"Personal Message"}),e.jsx(Rs,{id:"video-message",value:b,onChange:Y=>w(Y.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(ee,{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:[P?e.jsx("img",{src:P,alt:R,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(Bu,{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(Bu,{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($,{variant:"outline",onClick:()=>t(!1),disabled:S,children:"Cancel"}),e.jsxs($,{onClick:G,disabled:S||!g||!y,className:"gap-2",children:[S?e.jsx(kt,{className:"h-4 w-4 animate-spin"}):e.jsx(Yr,{className:"h-4 w-4"}),S?"Sending...":"Send Video Email"]})]})]})]})})}const EQn=()=>{const{user:s}=vs();return tt({queryKey:["team-videos",s==null?void 0:s.id],queryFn:async()=>{const{data:t,error:n}=await q.rpc("get_team_videos",{_user_id:s.id});if(n)throw n;return t||[]},enabled:!!s})};function TQn({recipient:s}){return s.watched_at?e.jsxs(Be,{className:"bg-emerald-100 text-emerald-800 text-[10px]",children:[e.jsx(Bu,{className:"h-2.5 w-2.5 mr-0.5"}),"Watched"]}):s.clicked_at?e.jsxs(Be,{className:"bg-blue-100 text-blue-800 text-[10px]",children:[e.jsx(hb,{className:"h-2.5 w-2.5 mr-0.5"}),"Clicked"]}):s.opened_at?e.jsxs(Be,{className:"bg-amber-100 text-amber-800 text-[10px]",children:[e.jsx(Ca,{className:"h-2.5 w-2.5 mr-0.5"}),"Opened"]}):e.jsxs(Be,{variant:"outline",className:"text-[10px]",children:[e.jsx(Yr,{className:"h-2.5 w-2.5 mr-0.5"}),"Sent"]})}function MQn({open:s,onOpenChange:t,videoId:n,videoTitle:r}){const{data:a=[],isLoading:i}=v9n(n);return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Os,{className:"max-w-2xl max-h-[80vh]",children:[e.jsx(Us,{children:e.jsxs(Bs,{className:"flex items-center gap-2",children:[e.jsx(Wl,{className:"h-5 w-5"}),"Send Analytics: ",r]})}),i?e.jsx("div",{className:"space-y-2",children:[...Array(3)].map((l,o)=>e.jsx(yn,{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(uo,{className:"h-[400px]",children:e.jsxs(mi,{children:[e.jsx(fi,{children:e.jsxs(En,{children:[e.jsx(Dt,{children:"Recipient"}),e.jsx(Dt,{children:"Status"}),e.jsx(Dt,{children:"Sent"}),e.jsx(Dt,{children:"Last Activity"})]})}),e.jsx(pi,{children:a.map(l=>e.jsxs(En,{children:[e.jsx(wt,{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(wt,{children:e.jsx(TQn,{recipient:l})}),e.jsx(wt,{className:"text-xs text-muted-foreground",children:en(new Date(l.sent_at),"MMM d, h:mm a")}),e.jsx(wt,{className:"text-xs text-muted-foreground",children:l.last_activity_at?mu(new Date(l.last_activity_at),{addSuffix:!0}):"—"})]},l.id))})]})})]})]})})}function PQn(){const{data:s,isLoading:t}=b9n(),{data:n=[],isLoading:r}=_9n(),[a,i]=j.useState(null),l=t||r,o=n.reduce((c,d)=>{const u=d.agent_videos,h=(u==null?void 0:u.id)||d.video_id;return c[h]||(c[h]={videoId:h,title:(u==null?void 0:u.title)||"Untitled",thumbnailUrl:u==null?void 0:u.thumbnail_url,recipients:[]}),c[h].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(Ne,{children:[e.jsx(Ct,{className:"pb-2",children:e.jsx(yn,{className:"h-4 w-20"})}),e.jsx(Ie,{children:e.jsx(yn,{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(Ne,{children:[e.jsxs(Ct,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(At,{className:"text-sm font-medium",children:"Total Sent"}),e.jsx(Yr,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsx(Ie,{children:e.jsx("div",{className:"text-2xl font-bold",children:(s==null?void 0:s.totalSent)||0})})]}),e.jsxs(Ne,{children:[e.jsxs(Ct,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(At,{className:"text-sm font-medium",children:"Open Rate"}),e.jsx(Ca,{className:"h-4 w-4 text-amber-500"})]}),e.jsxs(Ie,{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(Ne,{children:[e.jsxs(Ct,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(At,{className:"text-sm font-medium",children:"Click Rate"}),e.jsx(hb,{className:"h-4 w-4 text-blue-500"})]}),e.jsxs(Ie,{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(Ne,{children:[e.jsxs(Ct,{children:[e.jsx(At,{className:"text-sm font-medium",children:"Send History by Video"}),e.jsx(Gn,{children:"Click a video to see individual recipient tracking"})]}),e.jsx(Ie,{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(h=>h.opened_at).length,u=c.recipients.filter(h=>h.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:h=>{const m=h.currentTarget;m.style.display="none",m.parentElement.innerHTML='
'}}):e.jsx("div",{className:"h-full w-full flex items-center justify-center",children:e.jsx(ua,{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(Yr,{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(Ca,{className:"h-3 w-3"})," ",d]}),e.jsxs("span",{className:"text-xs text-blue-600 flex items-center gap-1",children:[e.jsx(hb,{className:"h-3 w-3"})," ",u]})]})]}),e.jsx(Yl,{className:"h-4 w-4 text-muted-foreground"})]},c.videoId)})})})]}),e.jsx(MQn,{open:!!a,onOpenChange:c=>!c&&i(null),videoId:(a==null?void 0:a.id)||null,videoTitle:(a==null?void 0:a.title)||""})]})}function IQn({previewSrc:s,thumbnailSrc:t,alt:n,isHovered:r}){const[a,i]=j.useState(!1),[l,o]=j.useState(!1),c=r&&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(ua,{className:"h-12 w-12 text-muted-foreground"})}):e.jsxs(e.Fragment,{children:[d&&e.jsx("img",{src:t,alt:n,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:n,className:"w-full h-full object-cover absolute inset-0",onError:()=>i(!0)})]})}function LQn({video:s,previewSrc:t,thumbnailSrc:n,onOpen:r,onDelete:a,onRename:i,onNavigateToContact:l,onGetEmbedCode:o,onCopyEmailHtml:c,onEmbedToCrm:d,onShareWithTemplate:u,onSendViaGmail:h,isGmailConnected:m,getContactName:f,getShareUrl:g,copyToClipboard:x,formatDuration:y}){const[v,b]=j.useState(!1);return e.jsxs(Ne,{className:"overflow-hidden group cursor-pointer",onClick:r,onMouseEnter:()=>b(!0),onMouseLeave:()=>b(!1),children:[e.jsxs("div",{className:"relative aspect-video bg-muted overflow-hidden",children:[e.jsx(IQn,{previewSrc:t,thumbnailSrc:n,alt:s.title||"Video preview",isHovered:v}),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(Bu,{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:y(s.duration_seconds)}),s.status!=="ready"&&e.jsx(Be,{variant:s.status==="processing"?"secondary":"destructive",className:"absolute top-2 left-2",children:s.status})]}),e.jsx(Ie,{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(sl,{className:"h-3 w-3"}),e.jsx("span",{className:"truncate",children:f(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(da,{className:"h-3 w-3"}),e.jsx("span",{children:en(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(Ca,{className:"h-3 w-3"}),e.jsxs("span",{children:[s.view_count," ",s.view_count===1?"view":"views"]})]})]}),m&&s.share_token&&e.jsxs($,{variant:"outline",size:"sm",className:"mt-2 gap-1.5 text-xs h-7",onClick:w=>{w.stopPropagation(),h==null||h()},children:[e.jsx(mn,{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(sl,{className:"h-3 w-3"}),e.jsx("span",{className:"truncate",children:f(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(da,{className:"h-3 w-3"}),e.jsx("span",{children:en(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(Ca,{className:"h-3 w-3"}),e.jsxs("span",{children:[s.view_count," ",s.view_count===1?"view":"views"]})]})]})]}),e.jsxs(Uu,{children:[e.jsx(qu,{asChild:!0,children:e.jsx($,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:w=>w.stopPropagation(),children:e.jsx(ty,{className:"h-4 w-4"})})}),e.jsxs(Eu,{align:"end",className:"bg-popover",children:[e.jsxs(ja,{onClick:w=>{w.stopPropagation(),r()},children:[e.jsx(Ca,{className:"h-4 w-4 mr-2"}),"Watch"]}),e.jsx(R0,{}),e.jsxs(ja,{onClick:w=>{w.stopPropagation(),u()},children:[e.jsx(Yc,{className:"h-4 w-4 mr-2"}),"Share with Template"]}),e.jsxs(ja,{onClick:w=>{w.stopPropagation(),x(g(s),"Share link")},children:[e.jsx(Ad,{className:"h-4 w-4 mr-2"}),"Copy Share Link"]}),e.jsxs(ja,{onClick:w=>{w.stopPropagation(),o()},children:[e.jsx(EE,{className:"h-4 w-4 mr-2"}),"Get Embed Code"]}),e.jsxs(ja,{onClick:w=>{w.stopPropagation(),c()},children:[e.jsx(mn,{className:"h-4 w-4 mr-2"}),"Copy HTML for Email"]}),e.jsxs(ja,{onClick:w=>{w.stopPropagation(),d()},children:[e.jsx(kr,{className:"h-4 w-4 mr-2"}),"Embed to CRM"]}),m&&s.share_token&&e.jsxs(ja,{onClick:w=>{w.stopPropagation(),h==null||h()},children:[e.jsx(Yr,{className:"h-4 w-4 mr-2"}),"Send via Gmail"]}),e.jsxs(ja,{onClick:w=>{w.stopPropagation(),i()},children:[e.jsx(gi,{className:"h-4 w-4 mr-2"}),"Rename"]}),e.jsx(R0,{}),s.contact_id&&e.jsxs(ja,{onClick:w=>{w.stopPropagation(),l()},children:[e.jsx(sl,{className:"h-4 w-4 mr-2"}),"View Contact"]}),e.jsxs(ja,{onClick:w=>{w.stopPropagation(),a()},className:"text-destructive",children:[e.jsx(Wn,{className:"h-4 w-4 mr-2"}),"Delete"]})]})]})]})})]})}function RQn(){var ts,ys;const s=Qn(),{data:t,isLoading:n,refetch:r}=B9n(),{data:a}=hDe(),{data:i}=z_(),l=q9n(),o=U9n(),{isGmailConnected:c,gmailEmail:d}=yy(),{data:u}=Hw(),{data:h=[],isLoading:m}=EQn(),[f,g]=j.useState("my"),[x,y]=j.useState(""),[v,b]=j.useState(null),[w,S]=j.useState(!1),[C,E]=j.useState(!1),[I,P]=j.useState(!1),[R,D]=j.useState(!1),[O,U]=j.useState(!1),[W,V]=j.useState(""),[G,Y]=j.useState(!1),[X,ae]=j.useState(!1),[ie,ne]=j.useState(!1),[te,J]=j.useState(!1),[ce,_e]=j.useState(""),[he,ue]=j.useState({}),ve=Bt=>{if(!Bt)return"Unassigned";const Ft=i==null?void 0:i.find(rs=>rs.id===Bt);return Ft?`${Ft.first_name} ${Ft.last_name||""}`.trim():"Unknown"},Ee=Bt=>{if(!Bt)return"0:00";const Ft=Math.floor(Bt/60),rs=Bt%60;return`${Ft}:${rs.toString().padStart(2,"0")}`},[Se,Le]=j.useState("all"),Fe=t==null?void 0:t.filter(Bt=>{const Ft=Bt.category||"general";if(Se==="general"&&Ft!=="general"||Se==="open_house"&&Ft!=="open_house")return!1;if(!x)return!0;const rs=ve(Bt.contact_id).toLowerCase(),St=(Bt.title||"").toLowerCase(),Xs=(Bt.notes||"").toLowerCase();return rs.includes(x.toLowerCase())||St.includes(x.toLowerCase())||Xs.includes(x.toLowerCase())}),ke=(t==null?void 0:t.filter(Bt=>(Bt.category||"general")==="open_house").length)||0,Ve=(t==null?void 0:t.filter(Bt=>(Bt.category||"general")==="general").length)||0,je=(t||[]).filter(Bt=>Bt.status==="processing"&&Bt.bunny_video_id).map(Bt=>Bt.id).join(",");j.useEffect(()=>{(async()=>{if(!(t!=null&&t.length))return;const Ft=t.filter(St=>St.status==="processing"&&St.bunny_video_id);if(!Ft.length)return;let rs=!1;for(const St of Ft)try{const{data:Xs,error:vt}=await q.functions.invoke("bunny-upload",{body:{action:"status",videoId:St.bunny_video_id,isAgentVideo:!0}});if(vt||!Xs)continue;Xs.status===4&&(await q.from("agent_videos").update({status:"ready",playback_url:Xs.directPlayUrl,thumbnail_url:Xs.thumbnailUrl,preview_url:Xs.previewUrl,duration_seconds:Xs.length||St.duration_seconds,updated_at:new Date().toISOString()}).eq("id",St.id),rs=!0)}catch(Xs){console.warn("Reconcile check failed for video",St.id,Xs)}rs&&r()})()},[je,r]),j.useEffect(()=>{(async()=>{if(!(t!=null&&t.length))return;const Ft=t.filter(gs=>(gs==null?void 0:gs.bunny_video_id)&&!he[gs.id]);if(!Ft.length)return;const rs=Ft.map(gs=>gs.bunny_video_id),{data:St,error:Xs}=await q.functions.invoke("bunny-upload",{body:{action:"bulk-asset-urls",videoIds:rs,isAgentVideo:!0}});if(Xs)throw Xs;const vt=(St==null?void 0:St.assets)||{};ue(gs=>{const Ss={...gs};for(const Is of Ft)vt[Is.bunny_video_id]&&(Ss[Is.id]={previewUrl:vt[Is.bunny_video_id].previewUrl,thumbnailUrl:vt[Is.bunny_video_id].thumbnailUrl});return Ss})})().catch(Ft=>console.warn("Failed to load signed Bunny asset URLs",Ft))},[t,he]);const Ae=(a==null?void 0:a.total_storage_mb)||0,Ce=(a==null?void 0:a.max_storage_mb)||1024,qe=Ae/Ce*100,ze=qe>=80,$e=qe>=100,ct=async(Bt,Ft)=>{await navigator.clipboard.writeText(Bt),re.success(`${Ft} copied to clipboard`)},Xe=Bt=>Bt.share_token?`https://video.relevelup.com/${Bt.share_token}`:Bt.playback_url||"",it=Bt=>{const Ft=Xe(Bt),rs=i==null?void 0:i.find(Is=>Is.id===Bt.contact_id),St=ve(Bt.contact_id),Xs=St!=="Unassigned"?St.split(" ")[0]:"",vt=(rs==null?void 0:rs.phone)||"",gs=`Hey${Xs?` ${Xs}`:""}! I recorded a quick video message for you. Check it out: ${Ft}`,Ss=vt?`sms:${vt}?body=${encodeURIComponent(gs)}`:`sms:?body=${encodeURIComponent(gs)}`;window.open(Ss,"_self")},at=Bt=>{const Ft=i==null?void 0:i.find(Ss=>Ss.id===Bt.contact_id),rs=(Ft==null?void 0:Ft.email)||"",St=Xe(Bt),Xs="Check out this video",vt=`I recorded a quick video for you: ${St}`,gs=rs?`mailto:${rs}?subject=${encodeURIComponent(Xs)}&body=${encodeURIComponent(vt)}`:`mailto:?subject=${encodeURIComponent(Xs)}&body=${encodeURIComponent(vt)}`;window.open(gs,"_self")},Ke=Bt=>{var Xs;const Ft=Xe(Bt),rs=Bt.title||"Video Message",St=Bt.share_token?`https://video.relevelup.com/thumb/${Bt.share_token}`:((Xs=he[Bt.id])==null?void 0:Xs.thumbnailUrl)||Bt.thumbnail_url||"";return``},nt=async Bt=>{if(!Bt.thumbnail_url&&!Bt.share_token){re.error("Video thumbnail not available yet");return}const Ft=Ke(Bt),rs=Xe(Bt),St=`Watch: ${Bt.title||"Video Message"} ${rs}`;try{const Xs=new Blob([Ft],{type:"text/html"}),vt=new Blob([St],{type:"text/plain"}),gs=new ClipboardItem({"text/html":Xs,"text/plain":vt});await navigator.clipboard.write([gs]),re.success("Copied! Paste into Gmail - the thumbnail will appear after sending.")}catch{await navigator.clipboard.writeText(St+` `+Ft),re.success("Copied! Paste into your email.")}},xt=async Bt=>{try{re.loading("Preparing download...",{id:"download"});const{data:Ft,error:rs}=await q.functions.invoke("bunny-upload",{body:{action:"download-url",videoId:Bt.bunny_video_id,isAgentVideo:!0}});if(rs||!(Ft!=null&&Ft.downloadUrl))throw new Error((rs==null?void 0:rs.message)||"Failed to get download URL");const Xs=`${((Bt.title||"video").toString().trim()||"video").replace(/[\\/:*?"<>|]+/g,"-")}.mp4`,vt=await fetch(Ft.downloadUrl);if(!vt.ok)throw new Error("Failed to fetch video file");const gs=await vt.blob(),Ss=URL.createObjectURL(gs),Is=document.createElement("a");Is.href=Ss,Is.download=Xs,Is.rel="noreferrer",document.body.appendChild(Is),Is.click(),Is.remove(),URL.revokeObjectURL(Ss),re.success("Download started",{id:"download"})}catch(Ft){console.error("Download error:",Ft),re.error("Could not force download (your browser may block it).",{id:"download"})}},rt=async Bt=>{b(Bt),Y(!0),V(""),U(!0);try{const{data:Ft,error:rs}=await q.functions.invoke("bunny-upload",{body:{action:"crm-embed",videoId:Bt.bunny_video_id,title:Bt.title,isAgentVideo:!0,shareToken:Bt.share_token}});if(rs||!(Ft!=null&&Ft.html))throw new Error("Failed to generate CRM embed code");V(Ft.html)}catch(Ft){console.error("CRM embed error:",Ft),re.error("Failed to generate CRM embed code"),U(!1)}finally{Y(!1)}},Yt=Bt=>{b(Bt),S(!0)},qt=async()=>{if(v)try{await l.mutateAsync({id:v.id,bunnyVideoId:v.bunny_video_id,hardDelete:!0}),E(!1),b(null),re.success("Video deleted successfully")}catch{re.error("Failed to delete video")}};return e.jsx(Vs,{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:()=>g("my"),className:`px-3 py-1.5 rounded-md text-sm font-medium transition-colors ${f==="my"?"bg-background text-foreground shadow-sm":"text-muted-foreground hover:text-foreground"}`,children:"My Videos"}),u&&((ts=u.team)==null?void 0:ts.shared_videos_enabled)&&e.jsxs("button",{onClick:()=>g("team"),className:`px-3 py-1.5 rounded-md text-sm font-medium transition-colors flex items-center gap-1.5 ${f==="team"?"bg-background text-foreground shadow-sm":"text-muted-foreground hover:text-foreground"}`,children:[e.jsx(Zn,{className:"h-3.5 w-3.5"}),"Team"]}),e.jsxs("button",{onClick:()=>g("analytics"),className:`px-3 py-1.5 rounded-md text-sm font-medium transition-colors flex items-center gap-1.5 ${f==="analytics"?"bg-background text-foreground shadow-sm":"text-muted-foreground hover:text-foreground"}`,children:[e.jsx(Wl,{className:"h-3.5 w-3.5"}),"Analytics"]})]})]}),f==="my"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs($,{variant:"outline",onClick:()=>P(!0),children:[e.jsx(ni,{className:"h-4 w-4 mr-2"}),"Upload Video"]}),e.jsxs($,{onClick:()=>s("/mission-control/video/record"),children:[e.jsx(dn,{className:"h-4 w-4 mr-2"}),"Record New Video"]})]})]}),f==="team"?e.jsx(DQn,{videos:h,isLoading:m,searchTerm:x,setSearchTerm:y}):f==="analytics"?e.jsx(PQn,{}):e.jsxs(e.Fragment,{children:[e.jsx(Ne,{className:ze?"border-amber-500":$e?"border-destructive":"",children:e.jsxs(Ie,{className:"py-4",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx(PJ,{className:`h-5 w-5 ${$e?"text-destructive":ze?"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:[Ae.toFixed(1)," MB / ",Ce>=1024?`${(Ce/1024).toFixed(0)} GB`:`${Ce} MB`]})]}),e.jsx(Yi,{value:Math.min(qe,100),className:`h-2 ${$e?"[&>div]:bg-destructive":ze?"[&>div]:bg-amber-500":""}`})]}),ze&&!$e&&e.jsxs(Be,{variant:"outline",className:"border-amber-500 text-amber-600",children:[e.jsx(ll,{className:"h-3 w-3 mr-1"}),"Near Limit"]}),$e&&e.jsxs(Be,{variant:"destructive",children:[e.jsx(ll,{className:"h-3 w-3 mr-1"}),"At Limit"]})]}),$e&&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:Ve},{id:"open_house",label:"Open House Tours",count:ke}].map(Bt=>e.jsxs("button",{onClick:()=>Le(Bt.id),className:`px-3 py-1.5 rounded-md text-sm font-medium transition-colors ${Se===Bt.id?"bg-background text-foreground shadow-sm":"text-muted-foreground hover:text-foreground"}`,children:[Bt.label," ",e.jsx("span",{className:"ml-1 text-xs text-muted-foreground",children:Bt.count})]},Bt.id))}),e.jsxs("div",{className:"relative",children:[e.jsx(Kr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(pe,{placeholder:"Search videos by contact, title, or notes...",value:x,onChange:Bt=>y(Bt.target.value),className:"pl-10"})]}),n?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"})}):(Fe==null?void 0:Fe.length)===0?e.jsx(Ne,{children:e.jsxs(Ie,{className:"py-12 text-center",children:[e.jsx(ua,{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($,{onClick:()=>s("/mission-control/video/record"),children:[e.jsx(dn,{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:Fe==null?void 0:Fe.map(Bt=>{var Ft,rs;return e.jsx(LQn,{video:Bt,previewSrc:(Ft=he[Bt.id])==null?void 0:Ft.previewUrl,thumbnailSrc:(rs=he[Bt.id])==null?void 0:rs.thumbnailUrl,onOpen:()=>Yt(Bt),onDelete:()=>{b(Bt),E(!0)},onRename:()=>{b(Bt),_e(Bt.title||""),J(!0)},onNavigateToContact:()=>s(`/mission-control/contacts/${Bt.contact_id}`),onGetEmbedCode:()=>{b(Bt),D(!0)},onCopyEmailHtml:()=>nt(Bt),onEmbedToCrm:()=>rt(Bt),onShareWithTemplate:()=>{b(Bt),ae(!0)},onSendViaGmail:()=>{b(Bt),ne(!0)},isGmailConnected:c,getContactName:ve,getShareUrl:Xe,copyToClipboard:ct,formatDuration:Ee},Bt.id)})}),e.jsx(zs,{open:w,onOpenChange:S,children:e.jsxs(Os,{className:"max-w-2xl",children:[e.jsxs(Us,{children:[e.jsx(Bs,{children:(v==null?void 0:v.title)||"Video Preview"}),e.jsx(Ir,{children:(v==null?void 0:v.contact_id)&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(sl,{className:"h-3 w-3"}),ve(v.contact_id)]})})]}),v&&e.jsxs("div",{className:"space-y-4",children:[v.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(kt,{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($,{variant:"outline",size:"sm",onClick:()=>{S(!1),r()},children:[e.jsx(ro,{className:"h-4 w-4 mr-2"}),"Refresh Library"]})]}):e.jsx("div",{className:"relative w-full",style:{paddingBottom:"56.25%"},children:v.playback_url?(()=>{let Bt=v.playback_url;return Bt.includes("iframe.mediadelivery.net/play/")&&(Bt=Bt.replace("/play/","/embed/"),Bt+=(Bt.includes("?")?"&":"?")+"autoplay=false&responsive=true"),Bt.includes("iframe.mediadelivery.net")?e.jsx("iframe",{src:Bt,title:v.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:v.playback_url,controls:!0,playsInline:!0,preload:"metadata",poster:v.thumbnail_url||void 0,className:"absolute top-0 left-0 w-full h-full rounded-lg object-cover",onError:()=>re.error("Video preview failed to load")},v.playback_url)})():e.jsxs("div",{className:"absolute inset-0 flex items-center justify-center bg-muted rounded-lg",children:[e.jsx(ua,{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($,{variant:"outline",onClick:()=>it(v),children:[e.jsx(eo,{className:"h-4 w-4 mr-2"}),"Text Contact Video"]}),!c&&e.jsxs($,{variant:"outline",onClick:()=>at(v),children:[e.jsx(mn,{className:"h-4 w-4 mr-2"}),"Email Contact Video"]}),e.jsxs($,{variant:"outline",onClick:()=>ct(Xe(v),"Share link"),children:[e.jsx(Ha,{className:"h-4 w-4 mr-2"}),"Copy Share Link"]}),e.jsxs($,{variant:"outline",onClick:()=>nt(v),children:[e.jsx(mn,{className:"h-4 w-4 mr-2"}),"Copy HTML for Email"]}),e.jsxs($,{variant:"outline",onClick:()=>xt(v),children:[e.jsx(di,{className:"h-4 w-4 mr-2"}),"Download Video"]}),e.jsxs($,{variant:"outline",onClick:()=>{S(!1),rt(v)},children:[e.jsx(kr,{className:"h-4 w-4 mr-2"}),"Embed to CRM"]}),e.jsxs($,{variant:"outline",onClick:()=>{S(!1),ae(!0)},children:[e.jsx(Yc,{className:"h-4 w-4 mr-2"}),"Send with Page Template"]}),c&&(v==null?void 0:v.share_token)&&e.jsxs($,{variant:"outline",onClick:()=>{S(!1),ne(!0)},children:[e.jsx(Yr,{className:"h-4 w-4 mr-2"}),"Send via Gmail"]})]}),e.jsx("div",{className:"flex justify-end pt-2 border-t",children:e.jsxs($,{variant:"destructive",onClick:()=>{S(!1),E(!0)},children:[e.jsx(Wn,{className:"h-4 w-4 mr-2"}),"Delete Video"]})})]})]})}),e.jsx(zs,{open:C,onOpenChange:E,children:e.jsxs(Os,{children:[e.jsxs(Us,{children:[e.jsx(Bs,{children:"Delete Video"}),e.jsx(Ir,{children:"Are you sure you want to delete this video? This action cannot be undone."})]}),e.jsxs(Ar,{children:[e.jsx($,{variant:"outline",onClick:()=>E(!1),children:"Cancel"}),e.jsx($,{variant:"destructive",onClick:qt,disabled:l.isPending,children:l.isPending?"Deleting...":"Delete"})]})]})}),e.jsx(GQt,{open:I,onOpenChange:P}),e.jsx(zs,{open:R,onOpenChange:D,children:e.jsxs(Os,{className:"sm:max-w-lg",children:[e.jsxs(Us,{children:[e.jsx(Bs,{children:"Embed Video"}),e.jsx(Ir,{children:"Copy this code to embed the video on your website."})]}),v&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Embed Code"}),e.jsx(Rs,{readOnly:!0,rows:5,value:``,className:"font-mono text-xs"})]}),e.jsx("div",{className:"flex gap-2",children:e.jsxs($,{className:"flex-1",onClick:()=>{const Bt=``;ct(Bt,"Embed code")},children:[e.jsx(Ha,{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."})]})]})}),v&&e.jsx(Qrs,{open:X,onOpenChange:ae,video:v,contactName:ve(v.contact_id)}),v&&e.jsx(AQn,{open:ie,onOpenChange:ne,video:v,gmailEmail:d,signedThumbnailUrl:(ys=he[v.id])==null?void 0:ys.thumbnailUrl}),e.jsx(zs,{open:te,onOpenChange:J,children:e.jsxs(Os,{className:"max-w-sm",children:[e.jsxs(Us,{children:[e.jsx(Bs,{children:"Rename Video"}),e.jsx(Ir,{children:"Enter a new title for this video."})]}),e.jsx(pe,{value:ce,onChange:Bt=>_e(Bt.target.value),placeholder:"Video title",autoFocus:!0,onKeyDown:Bt=>{Bt.key==="Enter"&&ce.trim()&&o.mutate({id:v.id,title:ce.trim()},{onSuccess:()=>{re.success("Video renamed"),J(!1)}})}}),e.jsxs(Ar,{children:[e.jsx($,{variant:"outline",onClick:()=>J(!1),children:"Cancel"}),e.jsx($,{disabled:!ce.trim()||o.isPending,onClick:()=>{o.mutate({id:v.id,title:ce.trim()},{onSuccess:()=>{re.success("Video renamed"),J(!1)}})},children:o.isPending?"Saving...":"Save"})]})]})}),e.jsx(zs,{open:O,onOpenChange:U,children:e.jsxs(Os,{className:"sm:max-w-lg",children:[e.jsxs(Us,{children:[e.jsxs(Bs,{className:"flex items-center gap-2",children:[e.jsx(kr,{className:"h-5 w-5"}),"Embed to CRM"]}),e.jsx(Ir,{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."})]}),G?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(kt,{className:"h-8 w-8 animate-spin text-muted-foreground"})}):W?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"CRM Email HTML"}),e.jsx(Rs,{readOnly:!0,rows:12,value:W,className:"font-mono text-xs"})]}),e.jsxs($,{className:"w-full",onClick:()=>{ct(W,"CRM embed code")},children:[e.jsx(Ha,{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 DQn({videos:s,isLoading:t,searchTerm:n,setSearchTerm:r}){const a=j.useMemo(()=>{if(!n)return s;const o=n.toLowerCase();return s.filter(c=>(c.title||"").toLowerCase().includes(o)||(c.owner_name||"").toLowerCase().includes(o)||(c.recipient_name||"").toLowerCase().includes(o))},[s,n]),i=j.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(Kr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(pe,{placeholder:"Search team videos by title, owner, or recipient...",value:n,onChange:o=>r(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(Ne,{children:e.jsxs(Ie,{className:"py-12 text-center",children:[e.jsx(Zn,{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(Oa,{className:"h-7 w-7",children:[e.jsx(Li,{src:c.avatar||""}),e.jsx(za,{children:(c.name||"?").charAt(0).toUpperCase()})]}),e.jsx("h3",{className:"font-semibold text-sm",children:c.name}),e.jsx(Be,{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(Ne,{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:u=>{u.target.style.display="none"}}):e.jsx(ua,{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(Ie,{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(sl,{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(Ca,{className:"h-3 w-3"}),d.view_count]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(da,{className:"h-3 w-3"}),en(new Date(d.created_at),"MMM d")]})]})]})]},d.id))})]},o))})]})}const FQn=()=>{const{user:s}=vs();return tt({queryKey:["team-deals",s==null?void 0:s.id],queryFn:async()=>{const{data:t,error:n}=await q.rpc("get_team_deals",{_user_id:s.id});if(n)throw n;return t||[]},enabled:!!s})},T3t=["#8B5CF6","#EC4899","#F59E0B","#10B981","#3B82F6","#EF4444","#06B6D4","#F97316"];function OQn({open:s,onOpenChange:t}){const{data:n,isLoading:r}=FQn(),[a,i]=j.useState(""),[l,o]=j.useState("all"),c=j.useMemo(()=>{if(!n)return new Map;const g=new Map;let x=0;return n.forEach(y=>{g.has(y.owner_user_id)||(g.set(y.owner_user_id,{name:y.owner_name||"Unknown",avatar:y.owner_avatar_url,color:T3t[x%T3t.length]}),x++)}),g},[n]),d=j.useMemo(()=>Array.from(c.entries()).map(([g,x])=>({id:g,...x})),[c]),u=j.useMemo(()=>{if(!n)return[];let g=n;if(l!=="all"&&(g=g.filter(x=>x.owner_user_id===l)),a.trim()){const x=a.toLowerCase();g=g.filter(y=>{var v,b,w,S;return y.deal_name.toLowerCase().includes(x)||((v=y.contact_name)==null?void 0:v.toLowerCase().includes(x))||((b=y.property_address)==null?void 0:b.toLowerCase().includes(x))||((w=y.city)==null?void 0:w.toLowerCase().includes(x))||((S=y.owner_name)==null?void 0:S.toLowerCase().includes(x))})}return g},[n,a,l]),h=j.useMemo(()=>{const g=new Map;return u.forEach(x=>{const y=x.stage_name||"Unknown";g.has(y)||g.set(y,{name:y,color:x.stage_color,icon:x.stage_icon,deals:[],totalValue:0});const v=g.get(y);v.deals.push(x),v.totalValue+=x.sale_price||0}),Array.from(g.values())},[u]),m=g=>g>=1e6?`$${(g/1e6).toFixed(1)}M`:g>=1e3?`$${(g/1e3).toFixed(0)}K`:`$${g.toFixed(0)}`,f=g=>g?new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(g):null;return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Os,{className:"max-w-[95vw] w-full max-h-[90vh] flex flex-col",children:[e.jsx(Us,{children:e.jsxs(Bs,{className:"flex items-center gap-2",children:[e.jsx(Zn,{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(Kr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(pe,{placeholder:"Search deals...",value:a,onChange:g=>i(g.target.value),className:"pl-9"})]}),e.jsxs(ms,{value:l,onValueChange:o,children:[e.jsx(us,{className:"w-[180px]",children:e.jsx(fs,{placeholder:"All Members"})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"all",children:"All Members"}),d.map(g=>e.jsx(Ge,{value:g.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:g.color}}),g.name]})},g.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(g=>e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx("span",{className:"h-2 w-2 rounded-full",style:{backgroundColor:g.color}}),g.name.split(" ")[0]]},g.id)),d.length>6&&e.jsxs("span",{children:["+",d.length-6," more"]})]})]}),e.jsx("div",{className:"flex-1 overflow-hidden mt-2",children:r?e.jsx("div",{className:"flex gap-4 h-full",children:[1,2,3,4].map(g=>e.jsxs("div",{className:"min-w-[260px] flex-1",children:[e.jsx(yn,{className:"h-12 w-full mb-2 rounded-lg"}),e.jsx(yn,{className:"h-24 w-full mb-2 rounded-lg"}),e.jsx(yn,{className:"h-24 w-full rounded-lg"})]},g))}):h.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(Zn,{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:h.map(g=>{const x=g.icon&&HIe[g.icon]||Og;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:g.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:g.color?`${g.color}20`:void 0},children:e.jsx(x,{className:"h-3.5 w-3.5",style:{color:g.color||void 0}})}),e.jsx("h3",{className:"font-semibold text-sm",children:g.name})]}),e.jsx(Be,{variant:"secondary",className:"text-xs px-2",children:g.deals.length})]}),g.totalValue>0&&e.jsx("p",{className:"text-xs text-muted-foreground ml-8",children:m(g.totalValue)})]}),e.jsx(uo,{className:"flex-1 p-2",children:e.jsx("div",{className:"space-y-2",children:g.deals.map(y=>{const v=c.get(y.owner_user_id);return e.jsx(zQn,{deal:y,ownerColor:(v==null?void 0:v.color)||"#888",ownerName:(v==null?void 0:v.name)||"Unknown",ownerAvatar:(v==null?void 0:v.avatar)||null,formatPrice:f},y.id)})})})]},g.name)})})}),e.jsxs("p",{className:"text-xs text-muted-foreground text-center pt-2 border-t shrink-0",children:[u.length," deal",u.length!==1?"s":""," across ",h.length," stage",h.length!==1?"s":""," from ",d.length," member",d.length!==1?"s":""]})]})})}function zQn({deal:s,ownerColor:t,ownerName:n,ownerAvatar:r,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(Oa,{className:"h-4 w-4",children:[e.jsx(Li,{src:r||""}),e.jsx(za,{className:"text-[8px] font-semibold text-white",style:{backgroundColor:t},children:n.charAt(0).toUpperCase()})]}),e.jsx("span",{className:"text-[10px] font-medium truncate",style:{color:t},children:n})]}),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(Be,{variant:"outline",className:Pt("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(va,{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(ru,{className:"h-3 w-3 text-emerald-500 shrink-0"}),e.jsx("span",{className:"font-semibold text-foreground",children:a(s.sale_price)})]})]})}function BQn({members:s,enabledMembers:t,onToggleMember:n,isOpen:r,onToggleOpen:a,showOwnDeals:i=!0,onToggleOwnDeals:l}){const o=t.size+(i?1:0);return e.jsxs("div",{className:Pt("shrink-0 border-r border-border/50 bg-muted/20 transition-all duration-300 flex flex-col",r?"w-[220px]":"w-[48px]"),children:[e.jsx("div",{className:"p-2 border-b border-border/50 shrink-0",children:e.jsxs($,{variant:"ghost",size:"sm",className:"w-full justify-start gap-2 px-2",onClick:a,children:[e.jsx(Zn,{className:"h-4 w-4 shrink-0 text-primary"}),r&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"text-xs font-semibold flex-1 text-left",children:"Team"}),o>0&&e.jsx("span",{className:"text-[10px] bg-primary text-primary-foreground rounded-full px-1.5 py-0.5",children:o}),e.jsx(Cd,{className:"h-3 w-3 text-muted-foreground"})]}),!r&&o>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:o})]})}),r?e.jsxs(uo,{className:"flex-1 p-2",children:[e.jsxs("div",{className:"space-y-1",children:[l&&e.jsxs(e.Fragment,{children:[e.jsxs("button",{onClick:l,className:Pt("w-full flex items-center gap-2 px-2 py-2 rounded-lg text-left transition-colors",i?"bg-primary/10 hover:bg-primary/15":"hover:bg-muted/50"),children:[e.jsx("div",{className:"h-7 w-7 rounded-full bg-primary/20 flex items-center justify-center shrink-0",children:e.jsx(Zn,{className:"h-3.5 w-3.5 text-primary"})}),e.jsx("span",{className:Pt("text-xs truncate flex-1",i?"font-medium text-foreground":"text-muted-foreground"),children:"My deals"}),e.jsx(Sn,{checked:i,onCheckedChange:l,className:"scale-75",onClick:c=>c.stopPropagation()})]}),e.jsx("div",{className:"h-px bg-border/60 my-1"})]}),s.map(c=>{const d=t.has(c.id);return e.jsxs("button",{onClick:()=>n(c.id),className:Pt("w-full flex items-center gap-2 px-2 py-2 rounded-lg text-left transition-colors",d?"bg-primary/10 hover:bg-primary/15":"hover:bg-muted/50"),children:[e.jsxs("div",{className:"relative",children:[e.jsxs(Oa,{className:"h-7 w-7",children:[e.jsx(Li,{src:c.avatar_url||""}),e.jsx(za,{className:"text-[10px] font-semibold text-white",style:{backgroundColor:c.color},children:c.name.charAt(0).toUpperCase()})]}),d&&e.jsx("div",{className:"absolute -bottom-0.5 -right-0.5 w-3 h-3 rounded-full border-2 border-background",style:{backgroundColor:c.color}})]}),e.jsx("span",{className:Pt("text-xs truncate flex-1",d?"font-medium text-foreground":"text-muted-foreground"),children:c.name}),e.jsx(Sn,{checked:d,onCheckedChange:()=>n(c.id),className:"scale-75",onClick:u=>u.stopPropagation()})]},c.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(c=>{const d=t.has(c.id);return e.jsx("button",{onClick:()=>n(c.id),className:"relative",title:c.name,children:e.jsxs(Oa,{className:Pt("h-7 w-7 transition-all",d?"ring-2 ring-offset-1 ring-offset-background":"opacity-50"),style:d?{"--tw-ring-color":c.color}:{},children:[e.jsx(Li,{src:c.avatar_url||""}),e.jsx(za,{className:"text-[10px] font-semibold text-white",style:{backgroundColor:c.color},children:c.name.charAt(0).toUpperCase()})]})},c.id)}),s.length>5&&e.jsxs("span",{className:"text-[10px] text-muted-foreground",children:["+",s.length-5]})]})]})}const M3t=["#8B5CF6","#EC4899","#F59E0B","#10B981","#3B82F6","#EF4444","#06B6D4","#F97316"];function $Qn(){const s=Sa(),{data:t}=Hw(),n=(t==null?void 0:t.role)==="team_leader",r=t==null?void 0:t.teamId,a=tt({queryKey:["team-pipeline-members",r,s],queryFn:async()=>{const{data:i,error:l}=await q.from("team_members").select("user_id, role").eq("team_id",r).neq("user_id",s);if(l)throw l;if(!i||i.length===0)return[];const o=i.map(u=>u.user_id),{data:c,error:d}=await q.from("profiles").select("id, name, avatar_url").in("id",o);if(d)throw d;return(c||[]).map((u,h)=>({id:u.id,name:u.name||"Unknown",avatar_url:u.avatar_url,color:M3t[h%M3t.length]}))},enabled:!!r&&!!s&&n,staleTime:5*60*1e3});return{isTeamLeader:n,teamMembers:a.data||[],isLoadingMembers:a.isLoading}}function UQn(s){return tt({queryKey:["team-member-deals",s],queryFn:async()=>{if(s.length===0)return[];const{data:t,error:n}=await q.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(n)throw n;return(t||[]).map(r=>{var a;return{...r,_stage_name:((a=r.deal_pipeline_stages)==null?void 0:a.name)||null}})},enabled:s.length>0})}function qQn(){const s=Sa();return tt({queryKey:["all-deal-tags-map",s],queryFn:async()=>{if(!s)return{tags:[],byDeal:{},unique:[]};const{data:t,error:n}=await q.from("deal_tags").select("id, deal_id, tag").eq("owner_user_id",s);if(n)throw n;const r=t||[],a={},i=new Set;r.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:r,byDeal:a,unique:l}},enabled:!!s})}function Jrs({stages:s,currentStageId:t,onStageSelect:n,disabled:r}){const[a,i]=j.useState(!1),l=s.find(c=>c.id===t),o=c=>{c.id!==t&&n(c.id,c.name),i(!1)};return e.jsxs(Uu,{open:a,onOpenChange:i,children:[e.jsx(qu,{asChild:!0,children:e.jsxs($,{variant:"outline",size:"sm",className:"h-7 text-xs gap-1.5",disabled:r,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(Di,{className:"h-3 w-3 shrink-0"})]})}),e.jsx(Eu,{align:"end",className:"w-48 z-50 bg-popover",onClick:c=>c.stopPropagation(),children:s.map(c=>{const d=c.icon&&HIe[c.icon]||Og,u=c.id===t;return e.jsxs(ja,{onClick:()=>o(c),className:Pt("flex items-center gap-2 cursor-pointer",u&&"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}),u&&e.jsx(la,{className:"h-4 w-4 text-primary"})]},c.id)})})]})}const VQn={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"}},HQn={low:{color:"bg-slate-100 text-slate-600",dot:"bg-slate-400",stripe:"bg-slate-300"},medium:{color:"bg-amber-100 text-amber-700",dot:"bg-amber-500",stripe:"bg-amber-400"},high:{color:"bg-orange-100 text-orange-700",dot:"bg-orange-500",stripe:"bg-orange-500"},urgent:{color:"bg-red-100 text-red-700",dot:"bg-red-500",stripe:"bg-red-500"}};function eas({deal:s,onClick:t,isDragging:n,stages:r,onStageChange:a,showStagePicker:i=!1,isWonStage:l=!1,isLostStage:o=!1,ownerInfo:c=null,tags:d=[],overdueTaskCount:u=0}){var E,I;const h=$K(),m=VQn[s.deal_type],f=HQn[s.priority],g=j.useMemo(()=>s.target_close_date?mk(Ch(s.target_close_date),new Date):null,[s.target_close_date]),x=l||o||!!s.actual_close_date,y=!x&&g!==null&&g<0,v=!x&&g!==null&&g<=7&&g>=0,b=j.useMemo(()=>{var D;if(s.deal_type!=="seller"&&s.deal_type!=="dual")return null;const P=((D=s.listing)==null?void 0:D.created_at)||s.listing_date;if(!P)return null;const R=s.contract_date?Ch(s.contract_date):new Date;return mk(R,Ch(P))},[s]),w=l&&!s.scorecard_transaction_id,S=!!s.scorecard_transaction_id,C=P=>P?new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(P):null;return e.jsxs(Ne,{className:Pt("cursor-pointer transition-all duration-200 hover:shadow-md hover:border-primary/30 group overflow-hidden",n&&"opacity-50 rotate-2 shadow-xl",y&&"border-red-200 bg-red-50/30",w&&"border-amber-300 bg-amber-50/30 dark:bg-amber-950/20"),onClick:t,style:c?{borderLeftWidth:4,borderLeftColor:c.color}:void 0,children:[!c&&e.jsx("div",{className:Pt("h-1 w-full",f.stripe),"aria-hidden":!0}),e.jsxs(Ie,{className:"p-3 space-y-2.5",children:[c&&e.jsxs("div",{className:"flex items-center gap-1.5 -mt-0.5 mb-1",children:[e.jsxs(Oa,{className:"h-4 w-4",children:[e.jsx(Li,{src:c.avatar_url||""}),e.jsx(za,{className:"text-[8px] font-semibold text-white",style:{backgroundColor:c.color},children:c.name.charAt(0).toUpperCase()})]}),e.jsx("span",{className:"text-[10px] font-medium",style:{color:c.color},children:c.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(Be,{variant:"outline",className:Pt("text-[10px] px-1.5 py-0 shrink-0",m.color),children:m.label})]}),s.contact&&e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[e.jsx(Oa,{className:"h-5 w-5",children:e.jsxs(za,{className:"text-[10px] bg-primary/10 text-primary",children:[(E=s.contact.first_name)==null?void 0:E[0],(I=s.contact.last_name)==null?void 0:I[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(bd,{className:"h-3 w-3 text-primary shrink-0"}),e.jsx("span",{className:"text-primary truncate",children:"Linked to Listing Exchange"})]}),w&&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(Kl,{className:"h-3 w-3 shrink-0"}),e.jsx("span",{className:"truncate font-medium",children:"Add to Scorecard"})]}),S&&l&&e.jsxs("div",{className:"flex items-center gap-1.5 text-xs text-green-600 dark:text-green-400",children:[e.jsx(qr,{className:"h-3 w-3 shrink-0"}),e.jsx("span",{className:"truncate",children:"Synced to Scorecard"})]}),b!==null&&e.jsxs("div",{className:"flex items-center gap-1.5 text-xs",children:[e.jsx(Au,{className:"h-3 w-3 text-muted-foreground shrink-0"}),e.jsxs("span",{className:Pt("font-medium",b>90?"text-red-600":b>60?"text-amber-600":"text-muted-foreground"),children:[b," 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(va,{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(ru,{className:"h-3 w-3 text-emerald-500 shrink-0"}),e.jsx("span",{className:"font-semibold text-foreground",children:C(s.expected_price)}),s.expected_commission&&e.jsxs("span",{className:"text-muted-foreground",children:["• ",C(s.expected_commission)," GCI"]}),(()=>{const P=jw(s);return P!==null&&P!==s.expected_commission?e.jsxs("span",{className:"text-teal-600 dark:text-teal-400",children:["• ",C(P)," Net"]}):null})()]}),u>0&&e.jsxs("div",{className:"flex items-center gap-1.5 rounded bg-destructive/10 px-2 py-1 text-xs font-medium text-destructive",children:[e.jsx(Ev,{className:"h-3 w-3 shrink-0"}),e.jsxs("span",{children:[u," overdue task",u>1?"s":""]})]}),d.length>0&&e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[d.slice(0,3).map(P=>e.jsx(JQt,{label:P},P)),d.length>3&&e.jsxs("span",{className:"inline-flex h-6 items-center rounded-full bg-muted px-2 text-[11px] font-medium text-muted-foreground",children:["+",d.length-3]})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex items-center justify-between text-[10px] text-muted-foreground",children:[e.jsx("span",{children:"Win probability"}),e.jsxs("span",{className:"font-semibold text-foreground",children:[s.probability,"%"]})]}),e.jsx("div",{className:"h-1.5 w-full overflow-hidden rounded-full bg-muted",children:e.jsx("div",{className:"h-full rounded-full bg-primary transition-all",style:{width:`${Math.min(100,Math.max(0,s.probability??0))}%`}})})]}),e.jsxs("div",{className:"flex items-center justify-between pt-1 border-t border-border/50",children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs("div",{className:Pt("flex items-center gap-1 px-1.5 py-0.5 rounded text-[10px]",f.color),children:[e.jsx("div",{className:Pt("w-1.5 h-1.5 rounded-full",f.dot)}),e.jsx("span",{className:"capitalize",children:s.priority})]})}),i&&h&&r&&a?e.jsx(Jrs,{stages:r,currentStageId:s.stage_id||"",onStageSelect:(P,R)=>a(s.id,P,R)}):s.target_close_date?e.jsxs("div",{className:Pt("flex items-center gap-1 text-[10px]",y&&"text-red-600",v&&!y&&"text-amber-600",!y&&!v&&"text-muted-foreground"),children:[y?e.jsx(ll,{className:"h-3 w-3"}):e.jsx(Ta,{className:"h-3 w-3"}),e.jsx("span",{children:y?`${Math.abs(g)}d overdue`:v?`${g}d left`:en(Ch(s.target_close_date),"MMM d")})]}):null]})]})]})}function GQn({stage:s,deals:t,onDealClick:n,onAddDeal:r,onDragStart:a,onDragOver:i,onDrop:l,isDragOver:o,isWonStage:c=!1,isLostStage:d=!1,getOwnerInfo:u,tagsByDeal:h={},overdueTasksByDeal:m={}}){const f=j.useRef(null),[g,x]=j.useState(!1),y=t.reduce((C,E)=>C+(E.expected_price||0),0),v=t.reduce((C,E)=>C+(E.expected_commission||0),0),b=t.reduce((C,E)=>C+(jw(E)||0),0),w=C=>C>=1e6?`$${(C/1e6).toFixed(1)}M`:C>=1e3?`$${(C/1e3).toFixed(0)}K`:`$${C.toFixed(0)}`,S=s.icon&&HIe[s.icon]||Og;return g?e.jsxs("div",{className:"flex h-full w-12 shrink-0 flex-col items-center gap-3 rounded-xl border border-border/50 bg-muted/30 py-3",style:{borderTopColor:s.color,borderTopWidth:3},children:[e.jsx("button",{onClick:()=>x(!1),"aria-label":`Expand ${s.name}`,className:"text-muted-foreground transition-colors hover:text-foreground",children:e.jsx(Di,{className:"h-4 w-4"})}),e.jsx(Be,{variant:"secondary",className:"px-1.5 text-[10px]",children:t.length}),e.jsx("span",{className:"mt-1 whitespace-nowrap text-xs font-semibold",style:{writingMode:"vertical-rl",color:s.color},children:s.name})]}):e.jsxs("div",{ref:f,className:Pt("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:C=>i(C,s.id),onDrop:C=>l(C,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(S,{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.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(Be,{variant:"secondary",className:"text-xs font-medium px-2",children:t.length}),e.jsx("button",{onClick:()=>x(!0),"aria-label":`Collapse ${s.name}`,className:"rounded p-0.5 text-muted-foreground transition-colors hover:bg-accent hover:text-foreground",children:e.jsx(Cd,{className:"h-3.5 w-3.5"})})]})]}),y>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:w(y)}),e.jsx("span",{children:"•"}),e.jsxs("span",{children:[w(v)," GCI"]}),b>0&&b!==v&&e.jsxs(e.Fragment,{children:[e.jsx("span",{children:"•"}),e.jsxs("span",{className:"text-teal-600 dark:text-teal-400",children:[w(b)," Net"]})]})]})]}),e.jsx(uo,{className:"flex-1 p-2",children:e.jsxs("div",{className:"space-y-2",children:[t.map(C=>e.jsx("div",{draggable:!0,onDragStart:E=>{E.dataTransfer.effectAllowed="move",a(C.id,s.id)},children:e.jsx(eas,{deal:C,onClick:()=>n(C),isWonStage:c,isLostStage:d,ownerInfo:(u==null?void 0:u(C))||null,tags:h[C.id]||[],overdueTaskCount:m[C.id]||0})},C.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($,{variant:"ghost",size:"sm",className:"w-full justify-start text-muted-foreground hover:text-foreground",onClick:()=>r(s.id),children:[e.jsx(dn,{className:"h-4 w-4 mr-2"}),"Add Deal"]})})]})}const ok=q;function WQn(s,t=!1){return tt({queryKey:["commission-plans",s,t],enabled:!!s,queryFn:async()=>{let n=ok.from("brokerage_commission_plans").select("*").eq("brokerage_id",s).order("name",{ascending:!0});t||(n=n.eq("is_active",!0));const{data:r,error:a}=await n;if(a)throw a;return r||[]}})}function KQn(s){const t=Vt();return ft({mutationFn:async n=>{const r={brokerage_id:s,name:n.name,description:n.description||null,agent_split_pct:n.agent_split_pct??70,team_split_pct:n.team_split_pct??0,cap_amount:n.cap_amount??null,monthly_fee:n.monthly_fee??0,transaction_fee:n.transaction_fee??0,franchise_fee_pct:n.franchise_fee_pct??0,referral_fee_pct:n.referral_fee_pct??null,commission_calc_method:n.commission_calc_method||"standard",is_active:n.is_active??!0};if(n.id){const{error:a}=await ok.from("brokerage_commission_plans").update(r).eq("id",n.id);if(a)throw a}else{const{error:a}=await ok.from("brokerage_commission_plans").insert(r);if(a)throw a}},onSuccess:()=>{t.invalidateQueries({queryKey:["commission-plans",s]}),re.success("Commission plan saved")},onError:n=>re.error(n.message||"Could not save plan")})}function YQn(s){return tt({queryKey:["cap-progress",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await ok.rpc("get_agent_cap_progress",{_agent_user_id:s});if(n)throw n;return(t||[])[0]??null}})}function ZQn(s){return tt({queryKey:["agent-plan-roster",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await q.from("profiles").select("id, name, email, avatar_url").eq("brokerage_id",s).order("name",{ascending:!0});if(n)throw n;const{data:r,error:a}=await ok.from("agent_plan_assignments").select("*").eq("brokerage_id",s).is("end_date",null);if(a)throw a;const i=[...new Set((r||[]).map(c=>c.plan_id))];let l=[];if(i.length){const{data:c,error:d}=await ok.from("brokerage_commission_plans").select("*").in("id",i);if(d)throw d;l=c||[]}return await Promise.all((t||[]).map(async c=>{const d=(r||[]).find(m=>m.agent_user_id===c.id)||null,u=d&&l.find(m=>m.id===d.plan_id)||null;let h=null;if(d){const{data:m}=await ok.rpc("get_agent_cap_progress",{_agent_user_id:c.id});h=(m||[])[0]??null}return{agentId:c.id,name:c.name||c.email,email:c.email,avatarUrl:c.avatar_url||null,assignment:d,plan:u,progress:h}}))}})}function XQn(s){const t=Vt();return ft({mutationFn:async n=>{const{error:r}=await ok.from("agent_plan_assignments").update({end_date:n.start_date}).eq("brokerage_id",s).eq("agent_user_id",n.agent_user_id).is("end_date",null);if(r)throw r;const{error:a}=await ok.from("agent_plan_assignments").insert({agent_user_id:n.agent_user_id,brokerage_id:s,plan_id:n.plan_id,start_date:n.start_date,anniversary_date:n.anniversary_date||null,notes:n.notes||null});if(a)throw a},onSuccess:()=>{t.invalidateQueries({queryKey:["agent-plan-roster",s]}),re.success("Plan assigned")},onError:n=>re.error(n.message||"Could not assign plan")})}function QQn(s){const t=Vt();return ft({mutationFn:async n=>{const r=new Date().toISOString().slice(0,10),{error:a}=await ok.from("agent_plan_assignments").update({end_date:r}).eq("id",n);if(a)throw a},onSuccess:()=>{t.invalidateQueries({queryKey:["agent-plan-roster",s]}),re.success("Plan removed from agent")},onError:n=>re.error(n.message||"Could not remove plan")})}function tas(){const{user:s}=vs();return tt({queryKey:["my-commission-plan",s==null?void 0:s.id],enabled:!!s,staleTime:5*6e4,queryFn:async()=>{const{data:t,error:n}=await ok.from("agent_plan_assignments").select("*").eq("agent_user_id",s.id).is("end_date",null).order("start_date",{ascending:!1}).limit(1).maybeSingle();if(n)throw n;if(!t)return null;const{data:r,error:a}=await ok.from("brokerage_commission_plans").select("*").eq("id",t.plan_id).maybeSingle();if(a)throw a;return r?{assignment:t,plan:r}:null}})}function JQn({formData:s,onChange:t,isEditing:n}){const{isAdmin:r}=vs(),[a,i]=j.useState(s.portal_enabled);if(!r)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(Nn,{className:"h-4 w-4 text-primary"}),e.jsx("h4",{className:"font-medium text-sm",children:"Client Portal"}),e.jsx(Be,{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(j1,{open:a,onOpenChange:i,children:e.jsxs("div",{className:"border rounded-lg",children:[e.jsxs(N1,{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(Nn,{className:"h-4 w-4 text-primary"}),e.jsx("h4",{className:"font-medium text-sm",children:"Client Portal"}),s.portal_enabled&&e.jsx(Be,{className:"text-xs bg-emerald-500/10 text-emerald-600 border-emerald-200",variant:"outline",children:"Enabled"})]}),e.jsx(Tl,{className:Pt("h-4 w-4 text-muted-foreground transition-transform",a&&"rotate-180")})]}),e.jsx(k1,{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(ee,{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(Sn,{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(ee,{className:"text-sm font-medium",children:"Portal Visibility"}),e.jsxs(kw,{value:s.visibility,onValueChange:o=>l({visibility:o}),className:"grid grid-cols-2 gap-3",children:[e.jsxs("label",{className:Pt("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(Ym,{value:"private"}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(pc,{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:Pt("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(Ym,{value:"public"}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(dl,{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(ai,{id:"require_onboarding",checked:s.require_onboarding,onCheckedChange:o=>l({require_onboarding:!!o}),className:"mt-0.5"}),e.jsxs("div",{children:[e.jsx(ee,{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(ai,{id:"allow_spouse",checked:s.allow_spouse,onCheckedChange:o=>l({allow_spouse:!!o})}),e.jsx(ee,{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(ee,{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(ee,{className:"text-xs text-muted-foreground",children:"Client Full Name"}),e.jsx(pe,{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(ee,{className:"text-xs text-muted-foreground",children:"Email"}),e.jsx(pe,{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(ee,{className:"text-xs text-muted-foreground",children:"Phone"}),e.jsx(pe,{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(ee,{className:"text-xs text-muted-foreground",children:"Preferred Invite Method"}),e.jsxs(ms,{value:s.invite_method,onValueChange:o=>l({invite_method:o}),children:[e.jsx(us,{children:e.jsx(fs,{})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"email",children:"Email"}),e.jsxs(Ge,{value:"sms",disabled:!s.client_phone,children:["SMS ",!s.client_phone&&"(add phone first)"]})]})]})]})]})]})]})]})})]})})}const eJn=[{value:"buyer",label:"Buyer"},{value:"seller",label:"Seller"},{value:"dual",label:"Dual Agency"},{value:"referral",label:"Referral"},{value:"lease",label:"Lease"}],tJn=[{value:"low",label:"Low"},{value:"medium",label:"Medium"},{value:"high",label:"High"},{value:"urgent",label:"Urgent"}];function V$e({label:s,date:t,onChange:n,placeholder:r="Pick a date",disabled:a}){const[i,l]=j.useState(t?en(t,"MM/dd/yyyy"):"");j.useEffect(()=>{const c=Svt(i);t&&c&&c.getTime()===t.getTime()||l(t?en(t,"MM/dd/yyyy"):"")},[t]);const o=c=>{l(c);const d=Svt(c);d?n(d):c.trim()||n(void 0)};return e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:s}),e.jsxs(Yd,{children:[e.jsx(Zd,{asChild:!0,children:e.jsxs($,{variant:"outline",className:Pt("w-full justify-start text-left font-normal",!t&&"text-muted-foreground"),disabled:a,children:[e.jsx(Ta,{className:"mr-2 h-4 w-4"}),t?en(t,"PPP"):r]})}),e.jsxs(Bd,{className:"w-auto p-0",align:"start",children:[e.jsx("div",{className:"p-3 border-b",children:e.jsx(pe,{type:"text",placeholder:"MM/DD/YYYY",value:i,onChange:c=>o(c.target.value),className:"h-8 text-sm"})}),e.jsx(D2,{mode:"single",selected:t,onSelect:c=>{n(c),l(c?en(c,"MM/dd/yyyy"):"")},initialFocus:!0,className:"pointer-events-auto",captionLayout:"dropdown",fromYear:1900,toYear:2100})]})]})]})}function sJn({open:s,onOpenChange:t,deal:n,defaultStageId:r}){const{data:a}=Jie(),{data:i}=z_(),{data:l}=Qst(),o=j6e(),c=Krs(),d=Yrs(),u=Cit(),{data:h}=tas(),{data:m}=Dae(),f=((m==null?void 0:m.length)??0)>0,g=j.useMemo(()=>{const X=h==null?void 0:h.plan;return X?{brokerage_split_pct:String(Math.max(0,100-(X.agent_split_pct??100))),team_split_pct:f&&X.team_split_pct?String(X.team_split_pct):"",franchise_fee_pct:X.franchise_fee_pct?String(X.franchise_fee_pct):"",transaction_fee:X.transaction_fee?String(X.transaction_fee):"",referral_fee_pct:X.referral_fee_pct!=null?String(X.referral_fee_pct):"",commission_calc_method:X.commission_calc_method||"standard"}:{brokerage_split_pct:"",team_split_pct:"",franchise_fee_pct:"",transaction_fee:"",referral_fee_pct:"",commission_calc_method:"standard"}},[h,f]);j.useEffect(()=>{if(!s||n||!h)return;const X=h.plan;O(ae=>ae.brokerage_split_pct||ae.franchise_fee_pct||ae.transaction_fee||ae.referral_fee_pct||ae.team_split_pct?ae:{...ae,brokerage_split_pct:String(Math.max(0,100-(X.agent_split_pct??100))),team_split_pct:f&&X.team_split_pct?String(X.team_split_pct):"",franchise_fee_pct:X.franchise_fee_pct?String(X.franchise_fee_pct):"",transaction_fee:X.transaction_fee?String(X.transaction_fee):"",referral_fee_pct:X.referral_fee_pct!=null?String(X.referral_fee_pct):"",commission_calc_method:X.commission_calc_method||"standard"})},[h,s,n,f]);const[x,y]=j.useState({portal_enabled:!1,visibility:"private",require_onboarding:!0,allow_spouse:!1,client_name:"",client_email:"",client_phone:"",invite_method:"email"}),[v,b]=j.useState(""),[w,S]=j.useState(!1),[C,E]=j.useState(!1),[I,P]=j.useState({first_name:"",last_name:"",email:"",phone:""}),R=(l==null?void 0:l.filter(X=>((n==null?void 0:n.listing_id)===X.id,!0)))||[],[D,O]=j.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:"",bonus_amount:"",commission_calc_method:"standard",target_close_date:void 0,contract_date:void 0,listing_date:void 0,priority:"medium",probability:"50",notes:""});j.useEffect(()=>{var X,ae,ie,ne,te,J,ce,_e,he,ue;s&&(n?(O({deal_name:n.deal_name,deal_type:n.deal_type,stage_id:n.stage_id||"",contact_id:n.contact_id||"",listing_id:n.listing_id||"",property_address:n.property_address||"",city:n.city||"",state:n.state||"",zip_code:n.zip_code||"",expected_price:((X=n.expected_price)==null?void 0:X.toString())||"",commission_percentage:((ae=n.commission_percentage)==null?void 0:ae.toString())||"3",brokerage_split_pct:((ie=n.brokerage_split_pct)==null?void 0:ie.toString())||"",team_split_pct:((ne=n.team_split_pct)==null?void 0:ne.toString())||"",referral_fee_pct:((te=n.referral_fee_pct)==null?void 0:te.toString())||"",franchise_fee_pct:((J=n.franchise_fee_pct)==null?void 0:J.toString())||"",transaction_fee:((ce=n.transaction_fee)==null?void 0:ce.toString())||"",bonus_amount:((_e=n.bonus_amount)==null?void 0:_e.toString())||"",commission_calc_method:n.commission_calc_method||"standard",target_close_date:n.target_close_date?Ch(n.target_close_date):void 0,contract_date:n.contract_date?Ch(n.contract_date):void 0,listing_date:n.listing_date?Ch(n.listing_date):void 0,priority:n.priority,probability:n.probability.toString(),notes:n.notes||""}),n.contact&&b(`${n.contact.first_name} ${n.contact.last_name}`)):(O({deal_name:"",deal_type:"buyer",stage_id:r||((he=a==null?void 0:a[0])==null?void 0:he.id)||"",contact_id:"",listing_id:"",property_address:"",city:"",state:"",zip_code:"",expected_price:"",commission_percentage:"3",brokerage_split_pct:g.brokerage_split_pct,team_split_pct:g.team_split_pct,referral_fee_pct:g.referral_fee_pct,franchise_fee_pct:g.franchise_fee_pct,transaction_fee:g.transaction_fee,bonus_amount:"",commission_calc_method:g.commission_calc_method,target_close_date:void 0,contract_date:void 0,listing_date:void 0,priority:"medium",probability:String(((ue=a==null?void 0:a.find(ve=>{var Ee;return ve.id===(r||((Ee=a==null?void 0:a[0])==null?void 0:Ee.id))}))==null?void 0:ue.default_probability)??50),notes:""}),b(""),y({portal_enabled:!1,visibility:"private",require_onboarding:!0,allow_spouse:!1,client_name:"",client_email:"",client_phone:"",invite_method:"email"})))},[s,n,r,a]);const U=i==null?void 0:i.filter(X=>{var ue,ve,Ee,Se,Le;const ae=v.toLowerCase().trim();if(!ae)return!0;const ie=((ue=X.first_name)==null?void 0:ue.toLowerCase())||"",ne=((ve=X.last_name)==null?void 0:ve.toLowerCase())||"",te=((Ee=X.email)==null?void 0:Ee.toLowerCase())||"",J=((Le=(Se=X.phone)==null?void 0:Se.toLowerCase)==null?void 0:Le.call(Se))||"",ce=`${ie} ${ne}`.trim(),_e=`${ne} ${ie}`.trim();if(ce.includes(ae)||_e.includes(ae)||ie.includes(ae)||ne.includes(ae)||te.includes(ae)||J.includes(ae))return!0;const he=ae.split(/\s+/).filter(Boolean);return he.length>1?he.every(Fe=>ie.includes(Fe)||ne.includes(Fe)||te.includes(Fe)||J.includes(Fe)):!1}).slice(0,8),W=()=>{const X=parseFloat(D.expected_price)||0,ae=parseFloat(D.commission_percentage)||0;return X*(ae/100)},V=()=>{const X=W(),ae=parseFloat(D.bonus_amount)||0;if(!X)return ae>0?ae:null;const ie=parseFloat(D.brokerage_split_pct)||0,ne=parseFloat(D.team_split_pct)||0,te=parseFloat(D.referral_fee_pct)||0,J=parseFloat(D.franchise_fee_pct)||0,ce=parseFloat(D.transaction_fee)||0,_e=parseFloat(D.bonus_amount)||0;if(D.commission_calc_method==="referral_first"){let ue=X;te&&(ue-=X*te/100);let ve=ue;return ie&&(ve-=ue*ie/100),ne&&(ve-=X*ne/100),J&&(ve-=X*J/100),ce&&(ve-=ce),Math.max(0,ve)+_e}let he=X;return ie&&(he=he*((100-ie)/100)),ne&&(he=he*((100-ne)/100)),te&&(he=he-X*te/100),J&&(he=he-X*J/100),ce&&(he=he-ce),Math.max(0,he)+_e},G=async X=>{var ae,ie,ne;if(X.preventDefault(),!D.deal_name.trim()){re.error("Please enter a deal name");return}try{const te={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:W()||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,bonus_amount:D.bonus_amount?parseFloat(D.bonus_amount):null,commission_calc_method:D.commission_calc_method,target_close_date:((ae=D.target_close_date)==null?void 0:ae.toISOString().split("T")[0])||null,contract_date:((ie=D.contract_date)==null?void 0:ie.toISOString().split("T")[0])||null,listing_date:((ne=D.listing_date)==null?void 0:ne.toISOString().split("T")[0])||null,priority:D.priority,probability:parseInt(D.probability)||50,notes:D.notes||null};if(n)await d.mutateAsync({id:n.id,...te}),re.success("Deal updated successfully");else{const J=await c.mutateAsync(te);if(re.success("Deal created successfully"),x.portal_enabled&&(J!=null&&J.id))try{await u.mutateAsync({deal_id:J.id,visibility:x.visibility,require_onboarding:x.require_onboarding,allow_spouse:x.allow_spouse,client_name:x.client_name||null,client_email:x.client_email||null,client_phone:x.client_phone||null,invite_method:x.invite_method}),re.success("Client portal created!")}catch{re.error("Deal created, but portal setup failed")}}t(!1)}catch{re.error("Failed to save deal")}},Y=c.isPending||d.isPending;return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Os,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsxs(Us,{children:[e.jsx(Bs,{children:n?"Edit Deal":"Add New Deal"}),e.jsx(Ir,{children:n?"Update the deal details below.":"Enter the details for your new deal."})]}),e.jsxs("form",{onSubmit:G,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(ee,{htmlFor:"deal_name",children:"Deal Name *"}),e.jsx(pe,{id:"deal_name",value:D.deal_name,onChange:X=>O(ae=>({...ae,deal_name:X.target.value})),placeholder:"e.g., Smith Family - 123 Main St"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Deal Type"}),e.jsxs(ms,{value:D.deal_type,onValueChange:X=>O(ae=>({...ae,deal_type:X})),children:[e.jsx(us,{children:e.jsx(fs,{})}),e.jsx(hs,{children:eJn.map(X=>e.jsx(Ge,{value:X.value,children:X.label},X.value))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Stage"}),e.jsxs(ms,{value:D.stage_id||"none",onValueChange:X=>{const ae=X==="none"?"":X,ie=a==null?void 0:a.find(ne=>ne.id===ae);O(ne=>({...ne,stage_id:ae,probability:typeof(ie==null?void 0:ie.default_probability)=="number"?String(ie.default_probability):ne.probability}))},children:[e.jsx(us,{children:e.jsx(fs,{placeholder:"Select stage"})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"none",children:"No Stage"}),a==null?void 0:a.map(X=>e.jsx(Ge,{value:X.id,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"w-2 h-2 rounded-full",style:{backgroundColor:X.color}}),X.name]})},X.id))]})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Link to Contact"}),e.jsxs("div",{className:"relative",children:[e.jsx(Kr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(pe,{value:v,onChange:X=>{b(X.target.value),S(!0),E(!1),X.target.value||O(ae=>({...ae,contact_id:""}))},onFocus:()=>S(!0),placeholder:"Search contacts...",className:"pl-9"}),w&&v&&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:[U&&U.length>0?U.map(X=>e.jsxs("button",{type:"button",className:"w-full px-3 py-2 text-left hover:bg-muted flex items-center gap-2",onClick:()=>{O(ae=>({...ae,contact_id:X.id})),b(`${X.first_name} ${X.last_name}`),S(!1)},children:[e.jsx(sl,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("span",{children:[X.first_name," ",X.last_name]}),X.email&&e.jsx("span",{className:"text-xs text-muted-foreground ml-auto",children:X.email})]},X.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 X=v.trim().split(/\s+/);P({first_name:X[0]||"",last_name:X.slice(1).join(" ")||"",email:"",phone:""}),E(!0),S(!1)},children:[e.jsx(sc,{className:"h-4 w-4"}),e.jsxs("span",{children:['Create new contact "',v.trim(),'"']})]})]})]}),C&&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(sc,{className:"h-3.5 w-3.5"}),"Quick Add Contact"]}),e.jsx($,{type:"button",variant:"ghost",size:"sm",className:"h-6 px-2 text-xs",onClick:()=>E(!1),children:"Cancel"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsx(pe,{placeholder:"First name *",value:I.first_name,onChange:X=>P(ae=>({...ae,first_name:X.target.value})),className:"h-8 text-sm"}),e.jsx(pe,{placeholder:"Last name",value:I.last_name,onChange:X=>P(ae=>({...ae,last_name:X.target.value})),className:"h-8 text-sm"}),e.jsx(pe,{placeholder:"Email",type:"email",value:I.email,onChange:X=>P(ae=>({...ae,email:X.target.value})),className:"h-8 text-sm"}),e.jsx(pe,{placeholder:"Phone",type:"tel",value:I.phone,onChange:X=>P(ae=>({...ae,phone:X.target.value})),className:"h-8 text-sm"})]}),e.jsx($,{type:"button",size:"sm",className:"w-full h-8",disabled:!I.first_name.trim()||o.isPending,onClick:async()=>{try{const X=await o.mutateAsync({first_name:I.first_name.trim(),last_name:I.last_name.trim()||null,email:I.email.trim()||null,phone:I.phone.trim()||null});X&&(O(ae=>({...ae,contact_id:X.id})),b(`${X.first_name} ${X.last_name||""}`.trim()),E(!1))}catch{}},children:o.isPending?e.jsxs(e.Fragment,{children:[e.jsx(kt,{className:"h-3.5 w-3.5 mr-1 animate-spin"})," Creating..."]}):e.jsxs(e.Fragment,{children:[e.jsx(sc,{className:"h-3.5 w-3.5 mr-1"})," Add & Link Contact"]})})]})]}),R.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ee,{className:"flex items-center gap-2",children:[e.jsx(bd,{className:"h-4 w-4"}),"Link to Listing Exchange"]}),e.jsxs(ms,{value:D.listing_id||"none",onValueChange:X=>{const ae=X==="none"?"":X,ie=R.find(ne=>ne.id===ae);O(ie?ne=>{var te;return{...ne,listing_id:ae,deal_type:"seller",property_address:ie.property_address||ne.property_address,city:ie.city||ne.city,state:ie.state||ne.state,expected_price:((te=ie.price)==null?void 0:te.toString())||ne.expected_price}}:ne=>({...ne,listing_id:ae}))},children:[e.jsx(us,{children:e.jsx(fs,{placeholder:"Select a listing to sync status..."})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"none",children:"None"}),R.map(X=>e.jsx(Ge,{value:X.id,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{children:X.property_address||`${X.city}, ${X.state}`}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:["$",(X.price/1e3).toFixed(0),"K"]})]})},X.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(ee,{htmlFor:"property_address",children:"Address"}),e.jsx(pe,{id:"property_address",value:D.property_address,onChange:X=>O(ae=>({...ae,property_address:X.target.value})),placeholder:"123 Main Street"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"city",children:"City"}),e.jsx(pe,{id:"city",value:D.city,onChange:X=>O(ae=>({...ae,city:X.target.value}))})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"state",children:"State"}),e.jsx(pe,{id:"state",value:D.state,onChange:X=>O(ae=>({...ae,state:X.target.value})),maxLength:2,placeholder:"TX"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"zip_code",children:"ZIP"}),e.jsx(pe,{id:"zip_code",value:D.zip_code,onChange:X=>O(ae=>({...ae,zip_code:X.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(ee,{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(pe,{id:"expected_price",type:"number",value:D.expected_price,onChange:X=>O(ae=>({...ae,expected_price:X.target.value})),className:"pl-7",placeholder:"500000"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"commission_percentage",children:"Commission %"}),e.jsxs("div",{className:"relative",children:[e.jsx(pe,{id:"commission_percentage",type:"number",step:"0.1",value:D.commission_percentage,onChange:X=>O(ae=>({...ae,commission_percentage:X.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(ee,{children:"Expected GCI"}),e.jsx(pe,{value:W()?`$${W().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(ee,{className:"text-xs whitespace-nowrap",children:"Calculation Method:"}),e.jsxs(ms,{value:D.commission_calc_method,onValueChange:X=>O(ae=>({...ae,commission_calc_method:X})),children:[e.jsx(us,{className:"h-7 text-xs",children:e.jsx(fs,{})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"standard",children:"Standard (all splits on GCI)"}),e.jsx(Ge,{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(ee,{className:"text-xs",children:"Brokerage Split"}),e.jsxs("div",{className:"relative",children:[e.jsx(pe,{type:"number",step:"1",min:"0",max:"100",value:D.brokerage_split_pct,onChange:X=>O(ae=>({...ae,brokerage_split_pct:X.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(ee,{className:"text-xs",children:"Team Split"}),e.jsxs("div",{className:"relative",children:[e.jsx(pe,{type:"number",step:"1",min:"0",max:"100",value:D.team_split_pct,onChange:X=>O(ae=>({...ae,team_split_pct:X.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(ee,{className:"text-xs",children:"Referral Fee"}),e.jsxs("div",{className:"relative",children:[e.jsx(pe,{type:"number",step:"1",min:"0",max:"100",value:D.referral_fee_pct,onChange:X=>O(ae=>({...ae,referral_fee_pct:X.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(ee,{className:"text-xs",children:"Franchise Fee"}),e.jsxs("div",{className:"relative",children:[e.jsx(pe,{type:"number",step:"1",min:"0",max:"100",value:D.franchise_fee_pct,onChange:X=>O(ae=>({...ae,franchise_fee_pct:X.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(ee,{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(pe,{type:"number",step:"1",min:"0",value:D.transaction_fee,onChange:X=>O(ae=>({...ae,transaction_fee:X.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(ee,{className:"text-xs",children:"Bonus"}),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(pe,{type:"number",step:"1",min:"0",value:D.bonus_amount,onChange:X=>O(ae=>({...ae,bonus_amount:X.target.value})),className:"pl-7 h-8 text-sm",placeholder:"5000"})]}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"Builder/other bonus — paid on top, not split"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{className:"text-xs",children:"Net to Agent"}),e.jsx(pe,{value:V()?`$${Math.round(V()).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.jsx(V$e,{label:"Target Close Date",date:D.target_close_date,onChange:X=>O(ae=>({...ae,target_close_date:X}))}),e.jsx(V$e,{label:"Contract Date",date:D.contract_date,onChange:X=>O(ae=>({...ae,contract_date:X}))}),(D.deal_type==="seller"||D.deal_type==="dual")&&!D.listing_id&&e.jsxs("div",{className:"space-y-2 col-span-2",children:[e.jsx(V$e,{label:"Listing Date (for Days on Market)",date:D.listing_date,onChange:X=>O(ae=>({...ae,listing_date:X}))}),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(ee,{children:"Priority"}),e.jsxs(ms,{value:D.priority,onValueChange:X=>O(ae=>({...ae,priority:X})),children:[e.jsx(us,{children:e.jsx(fs,{})}),e.jsx(hs,{children:tJn.map(X=>e.jsx(Ge,{value:X.value,children:X.label},X.value))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Win Probability"}),e.jsxs("div",{className:"relative",children:[e.jsx(pe,{type:"number",min:"0",max:"100",value:D.probability,onChange:X=>O(ae=>({...ae,probability:X.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(ee,{htmlFor:"notes",children:"Notes"}),e.jsx(Rs,{id:"notes",value:D.notes,onChange:X=>O(ae=>({...ae,notes:X.target.value})),placeholder:"Add any additional notes about this deal...",rows:3})]}),!n&&e.jsx(JQn,{formData:x,onChange:y}),e.jsxs("div",{className:"flex justify-end gap-3 pt-4 border-t",children:[e.jsx($,{type:"button",variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsxs($,{type:"submit",disabled:Y,children:[Y&&e.jsx(kt,{className:"h-4 w-4 mr-2 animate-spin"}),n?"Update Deal":"Create Deal"]})]})]})]})})}function nJn({dealId:s}){const t=Sa(),n=Vt(),[r,a]=j.useState(""),[i,l]=j.useState(!1),{data:o=[]}=tt({queryKey:["deal-tags",s],queryFn:async()=>{const{data:g,error:x}=await q.from("deal_tags").select("*").eq("deal_id",s).order("created_at");if(x)throw x;return g},enabled:!!s}),{data:c=[]}=tt({queryKey:["all-deal-tags",t],queryFn:async()=>{if(!t)return[];const{data:g,error:x}=await q.from("deal_tags").select("tag").eq("owner_user_id",t);if(x)throw x;return[...new Set(g.map(v=>v.tag))].sort()},enabled:!!t}),d=ft({mutationFn:async g=>{if(!t)throw new Error("Not authenticated");const{error:x}=await q.from("deal_tags").insert({deal_id:s,owner_user_id:t,tag:g.trim()});if(x)throw x},onSuccess:()=>{n.invalidateQueries({queryKey:["deal-tags",s]}),n.invalidateQueries({queryKey:["all-deal-tags"]}),a("")}}),u=ft({mutationFn:async g=>{const{error:x}=await q.from("deal_tags").delete().eq("id",g);if(x)throw x},onSuccess:()=>{n.invalidateQueries({queryKey:["deal-tags",s]})}}),h=()=>{const g=r.trim();g&&(o.some(x=>x.tag.toLowerCase()===g.toLowerCase())||d.mutate(g))},m=o.map(g=>g.tag.toLowerCase()),f=c.filter(g=>g.toLowerCase().includes(r.toLowerCase())&&!m.includes(g.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(g=>e.jsxs(Be,{variant:"secondary",className:"gap-1 text-xs",children:[g.tag,e.jsx("button",{type:"button",onClick:()=>u.mutate(g.id),className:"ml-0.5 hover:text-destructive",children:e.jsx(gr,{className:"h-3 w-3"})})]},g.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(dn,{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(pe,{value:r,onChange:g=>a(g.target.value),onKeyDown:g=>{g.key==="Enter"&&(g.preventDefault(),h()),g.key==="Escape"&&(l(!1),a(""))},placeholder:"Type tag name...",className:"h-8 text-xs flex-1",autoFocus:!0}),e.jsx("button",{type:"button",onClick:h,disabled:!r.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"})]}),r&&f.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:f.map(g=>e.jsx("button",{type:"button",className:"w-full px-3 py-2 text-left text-xs hover:bg-muted active:bg-muted",onClick:x=>{x.preventDefault(),d.mutate(g)},children:g},g))})]})]})}function rJn(s){return tt({queryKey:["deal-files",s],queryFn:async()=>{const{data:t,error:n}=await q.from("deal_files").select("id, deal_id, owner_user_id, file_name, file_size, file_type, storage_path, visible_on_portal, client_visible, compliance_item_id, version_no, is_current, source, source_ref, created_at").eq("deal_id",s).eq("is_current",!0).order("created_at",{ascending:!1});if(n)throw n;return t},enabled:!!s})}function aJn(){const s=Sa(),t=Vt();return ft({mutationFn:async({dealId:n,file:r})=>{if(!s)throw new Error("Not authenticated");const a=r.name.split(".").pop(),i=`${s}/${n}/${crypto.randomUUID()}.${a}`,{error:l}=await q.storage.from("deal-files").upload(i,r);if(l)throw l;const{data:o,error:c}=await q.from("deal_files").insert({deal_id:n,owner_user_id:s,file_name:r.name,file_size:r.size,file_type:r.type||null,storage_path:i,source:"levelup"}).select().single();if(c)throw c;return o},onSuccess:(n,r)=>{t.invalidateQueries({queryKey:["deal-files",r.dealId]})}})}function iJn(){const s=Vt();return ft({mutationFn:async({fileId:t,storagePath:n,dealId:r})=>{await q.storage.from("deal-files").remove([n]);const{error:a}=await q.from("deal_files").delete().eq("id",t);if(a)throw a;return r},onSuccess:t=>{s.invalidateQueries({queryKey:["deal-files",t]})}})}function oJn(){const s=Vt();return ft({mutationFn:async({fileId:t,visible:n,dealId:r})=>{const{error:a}=await q.from("deal_files").update({visible_on_portal:n}).eq("id",t);if(a)throw a;return r},onSuccess:t=>{s.invalidateQueries({queryKey:["deal-files",t]})}})}async function lJn(s){const{data:t,error:n}=await q.storage.from("deal-files").createSignedUrl(s,3600);if(n)throw n;return t.signedUrl}const cJn={pending:"bg-muted text-muted-foreground",submitted:"bg-amber-500/15 text-amber-600",approved:"bg-emerald-500/15 text-emerald-600",rejected:"bg-destructive/15 text-destructive"},dJn={pending:"Needed",submitted:"In review",approved:"Approved",rejected:"Changes requested"};function sas({dealId:s,canReview:t=!1,canUpload:n=!1}){const{data:r=[],isLoading:a}=Gzt(s),{data:i=[]}=JLs(s),l=XLs(),o=e6s(),[c,d]=j.useState(null),[u,h]=j.useState(""),[m,f]=j.useState(null),[g,x]=j.useState(null),y=j.useRef(null),v=j.useRef(null),b=C=>{var E;v.current=C,(E=y.current)==null||E.click()},w=async C=>{const E=v.current;if(!(!C||!E)){x(E.id);try{await o.mutateAsync({item:E,file:C}),re.success("Document uploaded for review")}catch(I){re.error(I.message||"Upload failed")}finally{x(null),v.current=null,y.current&&(y.current.value="")}}},S=async C=>{try{await l.mutateAsync({item:C,status:"rejected",note:u.trim()||"Changes requested"}),d(null),h("")}catch(E){re.error(E.message||"Could not update item")}};return a?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx(kt,{className:"h-5 w-5 animate-spin text-muted-foreground"})}):r.length===0?e.jsx("p",{className:"py-6 text-center text-sm text-muted-foreground",children:"No compliance checklist on this deal yet."}):e.jsxs("div",{className:"space-y-2",children:[e.jsx("input",{ref:y,type:"file",className:"hidden",onChange:C=>{var E;return w((E=C.target.files)==null?void 0:E[0])}}),r.map(C=>{var R;const E=i.filter(D=>D.compliance_item_id===C.id),I=E.find(D=>D.is_current)||E[0],P=C.status!=="approved"&&C.due_date&&C.due_dateD.value===C.phase))==null?void 0:R.label)||C.phase}),C.due_date&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(da,{className:"h-3 w-3"})," Due ",C.due_date]}),E.length>0&&e.jsxs("button",{className:"flex items-center gap-1 hover:text-foreground",onClick:()=>f(m===C.id?null:C.id),children:[e.jsx(Lw,{className:"h-3 w-3"})," ",E.length," version",E.length>1?"s":""]})]}),C.status==="rejected"&&C.review_note&&e.jsx("p",{className:"mt-2 rounded-md bg-destructive/10 p-2 text-xs text-destructive",children:C.review_note})]}),e.jsxs("div",{className:"flex flex-shrink-0 items-center gap-1",children:[I&&e.jsx($,{variant:"ghost",size:"icon",onClick:()=>Byt(I.storage_path),children:e.jsx(di,{className:"h-4 w-4"})}),n&&C.requires_document&&e.jsx($,{variant:"outline",size:"sm",onClick:()=>b(C),disabled:g===C.id,children:g===C.id?e.jsx(kt,{className:"h-4 w-4 animate-spin"}):e.jsxs(e.Fragment,{children:[e.jsx(SJ,{className:"mr-1 h-4 w-4"}),I?"Replace":"Upload"]})}),t&&e.jsxs(e.Fragment,{children:[e.jsx($,{variant:"ghost",size:"icon",title:"Approve",onClick:()=>l.mutate({item:C,status:"approved",note:null}),children:e.jsx(qr,{className:"h-4 w-4 text-emerald-600"})}),e.jsx($,{variant:"ghost",size:"icon",title:"Request changes",onClick:()=>{d(c===C.id?null:C.id),h("")},children:e.jsx(ku,{className:"h-4 w-4 text-destructive"})})]})]})]}),c===C.id&&e.jsxs("div",{className:"mt-3 space-y-2",children:[e.jsx(Rs,{rows:2,placeholder:"What needs to change?",value:u,onChange:D=>h(D.target.value)}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx($,{variant:"outline",size:"sm",onClick:()=>d(null),children:"Cancel"}),e.jsx($,{size:"sm",onClick:()=>S(C),children:"Send back to agent"})]})]}),m===C.id&&E.length>0&&e.jsx("div",{className:"mt-3 space-y-1 border-t pt-2",children:E.map(D=>e.jsxs("button",{onClick:()=>Byt(D.storage_path),className:"flex w-full items-center justify-between rounded px-2 py-1 text-left text-xs hover:bg-muted",children:[e.jsxs("span",{className:"truncate",children:["v",D.version_no," — ",D.file_name]}),e.jsx("span",{className:"text-muted-foreground",children:new Date(D.created_at).toLocaleDateString()})]},D.id))})]},C.id)})]})}function nas({dealId:s,brokerageId:t,role:n,counterpartName:r}){const{user:a}=vs(),{data:i=[],isLoading:l}=t6s(s),o=s6s(),c=n6s(),[d,u]=j.useState(""),h=j.useRef(null),m=j.useRef(null);j.useEffect(()=>{var g;(g=h.current)==null||g.scrollIntoView({block:"nearest"})},[i.length]),j.useEffect(()=>{if(l||m.current===s)return;i.some(x=>x.sender_role!==n&&!x.read_at)&&(m.current=s,c.mutate({dealId:s,senderRole:n}))},[s,l,i,n,c]);const f=async()=>{const g=d.trim();if(g)try{await o.mutateAsync({dealId:s,brokerageId:t,body:g,senderRole:n}),u(""),re.success("Message sent — an email notification is on the way")}catch(x){re.error(x.message||"Could not send the message")}};return e.jsxs("div",{className:"space-y-3",children:[e.jsxs("p",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[e.jsx(mn,{className:"h-3.5 w-3.5"}),n==="staff"?`Private thread with ${r||"the agent"} — they get an email for every message.`:"Private thread with your transaction team — they get an email for every message."]}),e.jsxs("div",{className:"max-h-[320px] space-y-3 overflow-y-auto rounded-lg border bg-muted/20 p-3",children:[l?e.jsx("div",{className:"flex justify-center py-6",children:e.jsx(kt,{className:"h-4 w-4 animate-spin text-muted-foreground"})}):i.length===0?e.jsx("p",{className:"py-6 text-center text-sm text-muted-foreground",children:"No messages yet. Start the conversation about what this file still needs."}):i.map(g=>{const x=g.sender_user_id===(a==null?void 0:a.id);return e.jsx("div",{className:`flex ${x?"justify-end":"justify-start"}`,children:e.jsxs("div",{className:`max-w-[85%] rounded-lg px-3 py-2 text-sm ${x?"bg-primary text-primary-foreground":"bg-background border"}`,children:[e.jsxs("p",{className:`mb-1 text-[11px] ${x?"text-primary-foreground/75":"text-muted-foreground"}`,children:[x?"You":g.sender_name||(g.sender_role==="staff"?"Transaction team":"Agent")," ·"," ",new Date(g.created_at).toLocaleString("en-US",{timeZone:"America/New_York",month:"short",day:"numeric",hour:"numeric",minute:"2-digit"})]}),e.jsx("p",{className:"whitespace-pre-wrap leading-relaxed",children:g.body})]})},g.id)}),e.jsx("div",{ref:h})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Rs,{value:d,onChange:g=>u(g.target.value),rows:3,placeholder:n==="staff"?"e.g. Please upload the signed disclosure — we need it before Friday.":"Ask a question or let the team know what you uploaded…"}),e.jsx("div",{className:"flex justify-end",children:e.jsxs($,{onClick:f,disabled:!d.trim()||o.isPending,className:"gap-2",children:[o.isPending?e.jsx(kt,{className:"h-4 w-4 animate-spin"}):e.jsx(Yr,{className:"h-4 w-4"}),"Send & notify"]})})]})]})}function uJn({dealId:s}){var a;const{data:t=[]}=Gzt(s);if(t.length===0)return null;const n=((a=t[0])==null?void 0:a.brokerage_id)??null,r=t.filter(i=>i.status==="approved").length;return e.jsxs("div",{className:"rounded-lg border p-3",children:[e.jsxs("div",{className:"mb-3 flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(bm,{className:"h-4 w-4 text-primary"}),e.jsx("span",{className:"text-sm font-medium",children:"Brokerage compliance"})]}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[r," of ",t.length," approved"]})]}),e.jsx("p",{className:"mb-3 text-xs text-muted-foreground",children:"This file is shared with your brokerage's compliance team. Upload each required document below."}),e.jsx(sas,{dealId:s,canUpload:!0}),n&&e.jsxs("div",{className:"mt-4 border-t pt-4",children:[e.jsx("p",{className:"mb-2 text-sm font-medium",children:"Messages with your transaction team"}),e.jsx(nas,{dealId:s,brokerageId:n,role:"agent"})]})]})}/*! ***************************************************************************** Copyright (c) Microsoft Corporation. Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ***************************************************************************** */var UXe=function(s,t){return UXe=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,r){n.__proto__=r}||function(n,r){for(var a in r)r.hasOwnProperty(a)&&(n[a]=r[a])},UXe(s,t)};function Si(s,t){UXe(s,t);function n(){this.constructor=s}s.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}var Vc=function(){return Vc=Object.assign||function(t){for(var n,r=1,a=arguments.length;r0&&i[i.length-1])&&(d[0]===6||d[0]===2)){n=0;continue}if(d[0]===3&&(!i||d[1]>i[0]&&d[1]>2],t+=gq[(s[r]&3)<<4|s[r+1]>>4],t+=gq[(s[r+1]&15)<<2|s[r+2]>>6],t+=gq[s[r+2]&63];return n%3===2?t=t.substring(0,t.length-1)+"=":n%3===1&&(t=t.substring(0,t.length-2)+"=="),t},P3t=function(s){var t=s.length*.75,n=s.length,r,a=0,i,l,o,c;s[s.length-1]==="="&&(t--,s[s.length-2]==="="&&t--);var d=new Uint8Array(t);for(r=0;r>4,d[a++]=(l&15)<<4|o>>2,d[a++]=(o&3)<<6|c&63;return d},fJn=/^(data)?:?([\w\/\+]+)?;?(charset=[\w-]+|base64)?.*,/i,pJn=function(s){var t=s.trim(),n=t.substring(0,100),r=n.match(fJn);if(!r)return P3t(t);var a=r[0],i=t.substring(a.length);return P3t(i)},zc=function(s){return s.charCodeAt(0)},gJn=function(s){return s.codePointAt(0)},eoe=function(s,t){return $S(s.toString(16),t,"0").toUpperCase()},GDe=function(s){return eoe(s,2)},ZE=function(s){return String.fromCharCode(s)},xJn=function(s){return ZE(parseInt(s,16))},$S=function(s,t,n){for(var r="",a=0,i=t-s.length;a=55296&&n<=56319&&s.length>a&&(r=s.charCodeAt(a),r>=56320&&r<=57343&&(i=2)),[s.slice(t,t+i),i]},bJn=function(s){for(var t=[],n=0,r=s.length;nn&&d(),l+=m,o+=f}}return d(),c},jJn=/^D:(\d\d\d\d)(\d\d)?(\d\d)?(\d\d)?(\d\d)?(\d\d)?([+\-Z])?(\d\d)?'?(\d\d)?'?$/,las=function(s){var t=s.match(jJn);if(t){var n=t[1],r=t[2],a=r===void 0?"01":r,i=t[3],l=i===void 0?"01":i,o=t[4],c=o===void 0?"00":o,d=t[5],u=d===void 0?"00":d,h=t[6],m=h===void 0?"00":h,f=t[7],g=f===void 0?"Z":f,x=t[8],y=x===void 0?"00":x,v=t[9],b=v===void 0?"00":v,w=g==="Z"?"Z":""+g+y+":"+b,S=new Date(n+"-"+a+"-"+l+"T"+c+":"+u+":"+m+w);return S}},elt=function(s,t){for(var n,r=0,a;r=0&&s<=65535},LJn=function(s){return s>=65536&&s<=1114111},das=function(s){return Math.floor((s-65536)/1024)+55296},uas=function(s){return(s-65536)%1024+56320},xL;(function(s){s.BigEndian="BigEndian",s.LittleEndian="LittleEndian"})(xL||(xL={}));var vX="�".codePointAt(0),has=function(s,t){if(t===void 0&&(t=!0),s.length<=1)return String.fromCodePoint(vX);for(var n=t?DJn(s):xL.BigEndian,r=t?2:0,a=[];s.length-r>=2;){var i=L3t(s[r++],s[r++],n);if(RJn(i))if(s.length-r<2)a.push(vX);else{var l=L3t(s[r++],s[r++],n);I3t(l)?a.push(i,l):a.push(vX)}else I3t(i)?(r+=2,a.push(vX)):a.push(i)}return r=55296&&s<=56319},I3t=function(s){return s>=56320&&s<=57343},L3t=function(s,t,n){if(n===xL.LittleEndian)return t<<8|s;if(n===xL.BigEndian)return s<<8|t;throw new Error("Invalid byteOrder: "+n)},DJn=function(s){return mas(s)?xL.BigEndian:fas(s)?xL.LittleEndian:xL.BigEndian},mas=function(s){return s[0]===254&&s[1]===255},fas=function(s){return s[0]===255&&s[1]===254},pas=function(s){return mas(s)||fas(s)},FJn=function(s){var t=String(s);if(Math.abs(s)<1){var n=parseInt(s.toString().split("e-")[1]);if(n){var r=s<0;r&&(s*=-1),s*=Math.pow(10,n-1),t="0."+new Array(n).join("0")+s.toString().substring(2),r&&(t="-"+t)}}else{var n=parseInt(s.toString().split("+")[1]);n>20&&(n-=20,s/=Math.pow(10,n),t=s.toString()+new Array(n+1).join("0"))}return t},pAe=function(s){return Math.ceil(s.toString(2).length/8)},X$=function(s){for(var t=new Uint8Array(pAe(s)),n=1;n<=t.length;n++)t[n-1]=s>>(t.length-n)*8;return t},soe=function(s){throw new Error(s)},$T={};(function(s){var t=typeof Uint8Array<"u"&&typeof Uint16Array<"u"&&typeof Int32Array<"u";function n(i,l){return Object.prototype.hasOwnProperty.call(i,l)}s.assign=function(i){for(var l=Array.prototype.slice.call(arguments,1);l.length;){var o=l.shift();if(o){if(typeof o!="object")throw new TypeError(o+"must be non-object");for(var c in o)n(o,c)&&(i[c]=o[c])}}return i},s.shrinkBuf=function(i,l){return i.length===l?i:i.subarray?i.subarray(0,l):(i.length=l,i)};var r={arraySet:function(i,l,o,c,d){if(l.subarray&&i.subarray){i.set(l.subarray(o,o+c),d);return}for(var u=0;u=0;)s[t]=0}var $Jn=0,gas=1,UJn=2,qJn=3,VJn=258,tlt=29,roe=256,Nne=roe+1+tlt,HV=30,slt=19,xas=2*Nne+1,C8=15,H$e=16,HJn=7,nlt=256,yas=16,vas=17,bas=18,VXe=[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],gAe=[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],GJn=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7],_as=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],WJn=512,FA=new Array((Nne+2)*2);iY(FA);var lte=new Array(HV*2);iY(lte);var kne=new Array(WJn);iY(kne);var Sne=new Array(VJn-qJn+1);iY(Sne);var rlt=new Array(tlt);iY(rlt);var SPe=new Array(HV);iY(SPe);function G$e(s,t,n,r,a){this.static_tree=s,this.extra_bits=t,this.extra_base=n,this.elems=r,this.max_length=a,this.has_stree=s&&s.length}var was,jas,Nas;function W$e(s,t){this.dyn_tree=s,this.max_code=0,this.stat_desc=t}function kas(s){return s<256?kne[s]:kne[256+(s>>>7)]}function Cne(s,t){s.pending_buf[s.pending++]=t&255,s.pending_buf[s.pending++]=t>>>8&255}function Cw(s,t,n){s.bi_valid>H$e-n?(s.bi_buf|=t<>H$e-s.bi_valid,s.bi_valid+=n-H$e):(s.bi_buf|=t<>>=1,n<<=1;while(--t>0);return n>>>1}function KJn(s){s.bi_valid===16?(Cne(s,s.bi_buf),s.bi_buf=0,s.bi_valid=0):s.bi_valid>=8&&(s.pending_buf[s.pending++]=s.bi_buf&255,s.bi_buf>>=8,s.bi_valid-=8)}function YJn(s,t){var n=t.dyn_tree,r=t.max_code,a=t.stat_desc.static_tree,i=t.stat_desc.has_stree,l=t.stat_desc.extra_bits,o=t.stat_desc.extra_base,c=t.stat_desc.max_length,d,u,h,m,f,g,x=0;for(m=0;m<=C8;m++)s.bl_count[m]=0;for(n[s.heap[s.heap_max]*2+1]=0,d=s.heap_max+1;dc&&(m=c,x++),n[u*2+1]=m,!(u>r)&&(s.bl_count[m]++,f=0,u>=o&&(f=l[u-o]),g=n[u*2],s.opt_len+=g*(m+f),i&&(s.static_len+=g*(a[u*2+1]+f)));if(x!==0){do{for(m=c-1;s.bl_count[m]===0;)m--;s.bl_count[m]--,s.bl_count[m+1]+=2,s.bl_count[c]--,x-=2}while(x>0);for(m=c;m!==0;m--)for(u=s.bl_count[m];u!==0;)h=s.heap[--d],!(h>r)&&(n[h*2+1]!==m&&(s.opt_len+=(m-n[h*2+1])*n[h*2],n[h*2+1]=m),u--)}}function Cas(s,t,n){var r=new Array(C8+1),a=0,i,l;for(i=1;i<=C8;i++)r[i]=a=a+n[i-1]<<1;for(l=0;l<=t;l++){var o=s[l*2+1];o!==0&&(s[l*2]=Sas(r[o]++,o))}}function ZJn(){var s,t,n,r,a,i=new Array(C8+1);for(n=0,r=0;r>=7;r8?Cne(s,s.bi_buf):s.bi_valid>0&&(s.pending_buf[s.pending++]=s.bi_buf),s.bi_buf=0,s.bi_valid=0}function XJn(s,t,n,r){Eas(s),Cne(s,n),Cne(s,~n),OJn.arraySet(s.pending_buf,s.window,t,n,s.pending),s.pending+=n}function F3t(s,t,n,r){var a=t*2,i=n*2;return s[a]>1;l>=1;l--)K$e(s,n,l);d=i;do l=s.heap[1],s.heap[1]=s.heap[s.heap_len--],K$e(s,n,1),o=s.heap[1],s.heap[--s.heap_max]=l,s.heap[--s.heap_max]=o,n[d*2]=n[l*2]+n[o*2],s.depth[d]=(s.depth[l]>=s.depth[o]?s.depth[l]:s.depth[o])+1,n[l*2+1]=n[o*2+1]=d,s.heap[1]=d++,K$e(s,n,1);while(s.heap_len>=2);s.heap[--s.heap_max]=s.heap[1],YJn(s,t),Cas(n,c,s.bl_count)}function z3t(s,t,n){var r,a=-1,i,l=t[0*2+1],o=0,c=7,d=4;for(l===0&&(c=138,d=3),t[(n+1)*2+1]=65535,r=0;r<=n;r++)i=l,l=t[(r+1)*2+1],!(++o=3&&s.bl_tree[_as[t]*2+1]===0;t--);return s.opt_len+=3*(t+1)+5+5+4,t}function JJn(s,t,n,r){var a;for(Cw(s,t-257,5),Cw(s,n-1,5),Cw(s,r-4,4),a=0;a>>=1)if(t&1&&s.dyn_ltree[n*2]!==0)return R3t;if(s.dyn_ltree[9*2]!==0||s.dyn_ltree[10*2]!==0||s.dyn_ltree[13*2]!==0)return D3t;for(n=32;n0?(s.strm.data_type===BJn&&(s.strm.data_type=eer(s)),HXe(s,s.l_desc),HXe(s,s.d_desc),l=QJn(s),a=s.opt_len+3+7>>>3,i=s.static_len+3+7>>>3,i<=a&&(a=i)):a=i=n+5,n+4<=a&&t!==-1?Tas(s,t,n,r):s.strategy===zJn||i===a?(Cw(s,(gas<<1)+(r?1:0),3),O3t(s,FA,lte)):(Cw(s,(UJn<<1)+(r?1:0),3),JJn(s,s.l_desc.max_code+1,s.d_desc.max_code+1,l+1),O3t(s,s.dyn_ltree,s.dyn_dtree)),Aas(s),r&&Eas(s)}function rer(s,t,n){return s.pending_buf[s.d_buf+s.last_lit*2]=t>>>8&255,s.pending_buf[s.d_buf+s.last_lit*2+1]=t&255,s.pending_buf[s.l_buf+s.last_lit]=n&255,s.last_lit++,t===0?s.dyn_ltree[n*2]++:(s.matches++,t--,s.dyn_ltree[(Sne[n]+roe+1)*2]++,s.dyn_dtree[kas(t)*2]++),s.last_lit===s.lit_bufsize-1}aY._tr_init=ter;aY._tr_stored_block=Tas;aY._tr_flush_block=ner;aY._tr_tally=rer;aY._tr_align=ser;function aer(s,t,n,r){for(var a=s&65535|0,i=s>>>16&65535|0,l=0;n!==0;){l=n>2e3?2e3:n,n-=l;do a=a+t[r++]|0,i=i+a|0;while(--l);a%=65521,i%=65521}return a|i<<16|0}var Mas=aer;function ier(){for(var s,t=[],n=0;n<256;n++){s=n;for(var r=0;r<8;r++)s=s&1?3988292384^s>>>1:s>>>1;t[n]=s}return t}var oer=ier();function ler(s,t,n,r){var a=oer,i=r+n;s^=-1;for(var l=r;l>>8^a[(s^t[l])&255];return s^-1}var Pas=ler,alt={2:"need dictionary",1:"stream end",0:"","-1":"file error","-2":"stream error","-3":"data error","-4":"insufficient memory","-5":"buffer error","-6":"incompatible version"},p_=$T,lk=aY,Ias=Mas,tP=Pas,cer=alt,b9=0,der=1,uer=3,yL=4,U3t=5,f4=0,q3t=1,ck=-2,her=-3,Y$e=-5,mer=-1,fer=1,Bue=2,per=3,ger=4,xer=0,yer=2,WDe=8,ver=9,ber=15,_er=8,wer=29,jer=256,GXe=jer+1+wer,Ner=30,ker=19,Ser=2*GXe+1,Cer=15,Ju=3,CI=258,hC=CI+Ju+1,Aer=32,KDe=42,WXe=69,xAe=73,yAe=91,vAe=103,A8=113,GQ=666,N0=1,aoe=2,jB=3,oY=4,Eer=3;function AI(s,t){return s.msg=cer[t],t}function V3t(s){return(s<<1)-(s>4?9:0)}function IP(s){for(var t=s.length;--t>=0;)s[t]=0}function sP(s){var t=s.state,n=t.pending;n>s.avail_out&&(n=s.avail_out),n!==0&&(p_.arraySet(s.output,t.pending_buf,t.pending_out,n,s.next_out),s.next_out+=n,t.pending_out+=n,s.total_out+=n,s.avail_out-=n,t.pending-=n,t.pending===0&&(t.pending_out=0))}function yb(s,t){lk._tr_flush_block(s,s.block_start>=0?s.block_start:-1,s.strstart-s.block_start,t),s.block_start=s.strstart,sP(s.strm)}function zh(s,t){s.pending_buf[s.pending++]=t}function bX(s,t){s.pending_buf[s.pending++]=t>>>8&255,s.pending_buf[s.pending++]=t&255}function Ter(s,t,n,r){var a=s.avail_in;return a>r&&(a=r),a===0?0:(s.avail_in-=a,p_.arraySet(t,s.input,s.next_in,a,n),s.state.wrap===1?s.adler=Ias(s.adler,t,a,n):s.state.wrap===2&&(s.adler=tP(s.adler,t,a,n)),s.next_in+=a,s.total_in+=a,a)}function Las(s,t){var n=s.max_chain_length,r=s.strstart,a,i,l=s.prev_length,o=s.nice_match,c=s.strstart>s.w_size-hC?s.strstart-(s.w_size-hC):0,d=s.window,u=s.w_mask,h=s.prev,m=s.strstart+CI,f=d[r+l-1],g=d[r+l];s.prev_length>=s.good_match&&(n>>=2),o>s.lookahead&&(o=s.lookahead);do if(a=t,!(d[a+l]!==g||d[a+l-1]!==f||d[a]!==d[r]||d[++a]!==d[r+1])){r+=2,a++;do;while(d[++r]===d[++a]&&d[++r]===d[++a]&&d[++r]===d[++a]&&d[++r]===d[++a]&&d[++r]===d[++a]&&d[++r]===d[++a]&&d[++r]===d[++a]&&d[++r]===d[++a]&&rl){if(s.match_start=t,l=i,i>=o)break;f=d[r+l-1],g=d[r+l]}}while((t=h[t&u])>c&&--n!==0);return l<=s.lookahead?l:s.lookahead}function NB(s){var t=s.w_size,n,r,a,i,l;do{if(i=s.window_size-s.lookahead-s.strstart,s.strstart>=t+(t-hC)){p_.arraySet(s.window,s.window,t,t,0),s.match_start-=t,s.strstart-=t,s.block_start-=t,r=s.hash_size,n=r;do a=s.head[--n],s.head[n]=a>=t?a-t:0;while(--r);r=t,n=r;do a=s.prev[--n],s.prev[n]=a>=t?a-t:0;while(--r);i+=t}if(s.strm.avail_in===0)break;if(r=Ter(s.strm,s.window,s.strstart+s.lookahead,i),s.lookahead+=r,s.lookahead+s.insert>=Ju)for(l=s.strstart-s.insert,s.ins_h=s.window[l],s.ins_h=(s.ins_h<s.pending_buf_size-5&&(n=s.pending_buf_size-5);;){if(s.lookahead<=1){if(NB(s),s.lookahead===0&&t===b9)return N0;if(s.lookahead===0)break}s.strstart+=s.lookahead,s.lookahead=0;var r=s.block_start+n;if((s.strstart===0||s.strstart>=r)&&(s.lookahead=s.strstart-r,s.strstart=r,yb(s,!1),s.strm.avail_out===0)||s.strstart-s.block_start>=s.w_size-hC&&(yb(s,!1),s.strm.avail_out===0))return N0}return s.insert=0,t===yL?(yb(s,!0),s.strm.avail_out===0?jB:oY):(s.strstart>s.block_start&&(yb(s,!1),s.strm.avail_out===0),N0)}function Z$e(s,t){for(var n,r;;){if(s.lookahead=Ju&&(s.ins_h=(s.ins_h<=Ju)if(r=lk._tr_tally(s,s.strstart-s.match_start,s.match_length-Ju),s.lookahead-=s.match_length,s.match_length<=s.max_lazy_match&&s.lookahead>=Ju){s.match_length--;do s.strstart++,s.ins_h=(s.ins_h<=Ju&&(s.ins_h=(s.ins_h<4096)&&(s.match_length=Ju-1)),s.prev_length>=Ju&&s.match_length<=s.prev_length){a=s.strstart+s.lookahead-Ju,r=lk._tr_tally(s,s.strstart-1-s.prev_match,s.prev_length-Ju),s.lookahead-=s.prev_length-1,s.prev_length-=2;do++s.strstart<=a&&(s.ins_h=(s.ins_h<=Ju&&s.strstart>0&&(a=s.strstart-1,r=l[a],r===l[++a]&&r===l[++a]&&r===l[++a])){i=s.strstart+CI;do;while(r===l[++a]&&r===l[++a]&&r===l[++a]&&r===l[++a]&&r===l[++a]&&r===l[++a]&&r===l[++a]&&r===l[++a]&&as.lookahead&&(s.match_length=s.lookahead)}if(s.match_length>=Ju?(n=lk._tr_tally(s,1,s.match_length-Ju),s.lookahead-=s.match_length,s.strstart+=s.match_length,s.match_length=0):(n=lk._tr_tally(s,0,s.window[s.strstart]),s.lookahead--,s.strstart++),n&&(yb(s,!1),s.strm.avail_out===0))return N0}return s.insert=0,t===yL?(yb(s,!0),s.strm.avail_out===0?jB:oY):s.last_lit&&(yb(s,!1),s.strm.avail_out===0)?N0:aoe}function Ier(s,t){for(var n;;){if(s.lookahead===0&&(NB(s),s.lookahead===0)){if(t===b9)return N0;break}if(s.match_length=0,n=lk._tr_tally(s,0,s.window[s.strstart]),s.lookahead--,s.strstart++,n&&(yb(s,!1),s.strm.avail_out===0))return N0}return s.insert=0,t===yL?(yb(s,!0),s.strm.avail_out===0?jB:oY):s.last_lit&&(yb(s,!1),s.strm.avail_out===0)?N0:aoe}function c5(s,t,n,r,a){this.good_length=s,this.max_lazy=t,this.nice_length=n,this.max_chain=r,this.func=a}var xq;xq=[new c5(0,0,0,0,Mer),new c5(4,4,8,4,Z$e),new c5(4,5,16,8,Z$e),new c5(4,6,32,32,Z$e),new c5(4,4,16,16,Q$),new c5(8,16,32,32,Q$),new c5(8,16,128,128,Q$),new c5(8,32,128,256,Q$),new c5(32,128,258,1024,Q$),new c5(32,258,258,4096,Q$)];function Ler(s){s.window_size=2*s.w_size,IP(s.head),s.max_lazy_match=xq[s.level].max_lazy,s.good_match=xq[s.level].good_length,s.nice_match=xq[s.level].nice_length,s.max_chain_length=xq[s.level].max_chain,s.strstart=0,s.block_start=0,s.lookahead=0,s.insert=0,s.match_length=s.prev_length=Ju-1,s.match_available=0,s.ins_h=0}function Rer(){this.strm=null,this.status=0,this.pending_buf=null,this.pending_buf_size=0,this.pending_out=0,this.pending=0,this.wrap=0,this.gzhead=null,this.gzindex=0,this.method=WDe,this.last_flush=-1,this.w_size=0,this.w_bits=0,this.w_mask=0,this.window=null,this.window_size=0,this.prev=null,this.head=null,this.ins_h=0,this.hash_size=0,this.hash_bits=0,this.hash_mask=0,this.hash_shift=0,this.block_start=0,this.match_length=0,this.prev_match=0,this.match_available=0,this.strstart=0,this.match_start=0,this.lookahead=0,this.prev_length=0,this.max_chain_length=0,this.max_lazy_match=0,this.level=0,this.strategy=0,this.good_match=0,this.nice_match=0,this.dyn_ltree=new p_.Buf16(Ser*2),this.dyn_dtree=new p_.Buf16((2*Ner+1)*2),this.bl_tree=new p_.Buf16((2*ker+1)*2),IP(this.dyn_ltree),IP(this.dyn_dtree),IP(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new p_.Buf16(Cer+1),this.heap=new p_.Buf16(2*GXe+1),IP(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new p_.Buf16(2*GXe+1),IP(this.depth),this.l_buf=0,this.lit_bufsize=0,this.last_lit=0,this.d_buf=0,this.opt_len=0,this.static_len=0,this.matches=0,this.insert=0,this.bi_buf=0,this.bi_valid=0}function Ras(s){var t;return!s||!s.state?AI(s,ck):(s.total_in=s.total_out=0,s.data_type=yer,t=s.state,t.pending=0,t.pending_out=0,t.wrap<0&&(t.wrap=-t.wrap),t.status=t.wrap?KDe:A8,s.adler=t.wrap===2?0:1,t.last_flush=b9,lk._tr_init(t),f4)}function Das(s){var t=Ras(s);return t===f4&&Ler(s.state),t}function Der(s,t){return!s||!s.state||s.state.wrap!==2?ck:(s.state.gzhead=t,f4)}function Fas(s,t,n,r,a,i){if(!s)return ck;var l=1;if(t===mer&&(t=6),r<0?(l=0,r=-r):r>15&&(l=2,r-=16),a<1||a>ver||n!==WDe||r<8||r>15||t<0||t>9||i<0||i>ger)return AI(s,ck);r===8&&(r=9);var o=new Rer;return s.state=o,o.strm=s,o.wrap=l,o.gzhead=null,o.w_bits=r,o.w_size=1<U3t||t<0)return s?AI(s,ck):ck;if(r=s.state,!s.output||!s.input&&s.avail_in!==0||r.status===GQ&&t!==yL)return AI(s,s.avail_out===0?Y$e:ck);if(r.strm=s,n=r.last_flush,r.last_flush=t,r.status===KDe)if(r.wrap===2)s.adler=0,zh(r,31),zh(r,139),zh(r,8),r.gzhead?(zh(r,(r.gzhead.text?1:0)+(r.gzhead.hcrc?2:0)+(r.gzhead.extra?4:0)+(r.gzhead.name?8:0)+(r.gzhead.comment?16:0)),zh(r,r.gzhead.time&255),zh(r,r.gzhead.time>>8&255),zh(r,r.gzhead.time>>16&255),zh(r,r.gzhead.time>>24&255),zh(r,r.level===9?2:r.strategy>=Bue||r.level<2?4:0),zh(r,r.gzhead.os&255),r.gzhead.extra&&r.gzhead.extra.length&&(zh(r,r.gzhead.extra.length&255),zh(r,r.gzhead.extra.length>>8&255)),r.gzhead.hcrc&&(s.adler=tP(s.adler,r.pending_buf,r.pending,0)),r.gzindex=0,r.status=WXe):(zh(r,0),zh(r,0),zh(r,0),zh(r,0),zh(r,0),zh(r,r.level===9?2:r.strategy>=Bue||r.level<2?4:0),zh(r,Eer),r.status=A8);else{var l=WDe+(r.w_bits-8<<4)<<8,o=-1;r.strategy>=Bue||r.level<2?o=0:r.level<6?o=1:r.level===6?o=2:o=3,l|=o<<6,r.strstart!==0&&(l|=Aer),l+=31-l%31,r.status=A8,bX(r,l),r.strstart!==0&&(bX(r,s.adler>>>16),bX(r,s.adler&65535)),s.adler=1}if(r.status===WXe)if(r.gzhead.extra){for(a=r.pending;r.gzindex<(r.gzhead.extra.length&65535)&&!(r.pending===r.pending_buf_size&&(r.gzhead.hcrc&&r.pending>a&&(s.adler=tP(s.adler,r.pending_buf,r.pending-a,a)),sP(s),a=r.pending,r.pending===r.pending_buf_size));)zh(r,r.gzhead.extra[r.gzindex]&255),r.gzindex++;r.gzhead.hcrc&&r.pending>a&&(s.adler=tP(s.adler,r.pending_buf,r.pending-a,a)),r.gzindex===r.gzhead.extra.length&&(r.gzindex=0,r.status=xAe)}else r.status=xAe;if(r.status===xAe)if(r.gzhead.name){a=r.pending;do{if(r.pending===r.pending_buf_size&&(r.gzhead.hcrc&&r.pending>a&&(s.adler=tP(s.adler,r.pending_buf,r.pending-a,a)),sP(s),a=r.pending,r.pending===r.pending_buf_size)){i=1;break}r.gzindexa&&(s.adler=tP(s.adler,r.pending_buf,r.pending-a,a)),i===0&&(r.gzindex=0,r.status=yAe)}else r.status=yAe;if(r.status===yAe)if(r.gzhead.comment){a=r.pending;do{if(r.pending===r.pending_buf_size&&(r.gzhead.hcrc&&r.pending>a&&(s.adler=tP(s.adler,r.pending_buf,r.pending-a,a)),sP(s),a=r.pending,r.pending===r.pending_buf_size)){i=1;break}r.gzindexa&&(s.adler=tP(s.adler,r.pending_buf,r.pending-a,a)),i===0&&(r.status=vAe)}else r.status=vAe;if(r.status===vAe&&(r.gzhead.hcrc?(r.pending+2>r.pending_buf_size&&sP(s),r.pending+2<=r.pending_buf_size&&(zh(r,s.adler&255),zh(r,s.adler>>8&255),s.adler=0,r.status=A8)):r.status=A8),r.pending!==0){if(sP(s),s.avail_out===0)return r.last_flush=-1,f4}else if(s.avail_in===0&&V3t(t)<=V3t(n)&&t!==yL)return AI(s,Y$e);if(r.status===GQ&&s.avail_in!==0)return AI(s,Y$e);if(s.avail_in!==0||r.lookahead!==0||t!==b9&&r.status!==GQ){var c=r.strategy===Bue?Ier(r,t):r.strategy===per?Per(r,t):xq[r.level].func(r,t);if((c===jB||c===oY)&&(r.status=GQ),c===N0||c===jB)return s.avail_out===0&&(r.last_flush=-1),f4;if(c===aoe&&(t===der?lk._tr_align(r):t!==U3t&&(lk._tr_stored_block(r,0,0,!1),t===uer&&(IP(r.head),r.lookahead===0&&(r.strstart=0,r.block_start=0,r.insert=0))),sP(s),s.avail_out===0))return r.last_flush=-1,f4}return t!==yL?f4:r.wrap<=0?q3t:(r.wrap===2?(zh(r,s.adler&255),zh(r,s.adler>>8&255),zh(r,s.adler>>16&255),zh(r,s.adler>>24&255),zh(r,s.total_in&255),zh(r,s.total_in>>8&255),zh(r,s.total_in>>16&255),zh(r,s.total_in>>24&255)):(bX(r,s.adler>>>16),bX(r,s.adler&65535)),sP(s),r.wrap>0&&(r.wrap=-r.wrap),r.pending!==0?f4:q3t)}function zer(s){var t;return!s||!s.state?ck:(t=s.state.status,t!==KDe&&t!==WXe&&t!==xAe&&t!==yAe&&t!==vAe&&t!==A8&&t!==GQ?AI(s,ck):(s.state=null,t===A8?AI(s,her):f4))}function Ber(s,t){var n=t.length,r,a,i,l,o,c,d,u;if(!s||!s.state||(r=s.state,l=r.wrap,l===2||l===1&&r.status!==KDe||r.lookahead))return ck;for(l===1&&(s.adler=Ias(s.adler,t,n,0)),r.wrap=0,n>=r.w_size&&(l===0&&(IP(r.head),r.strstart=0,r.block_start=0,r.insert=0),u=new p_.Buf8(r.w_size),p_.arraySet(u,t,n-r.w_size,r.w_size,0),t=u,n=r.w_size),o=s.avail_in,c=s.next_in,d=s.input,s.avail_in=n,s.next_in=0,s.input=t,NB(r);r.lookahead>=Ju;){a=r.strstart,i=r.lookahead-(Ju-1);do r.ins_h=(r.ins_h<=252?6:IM>=248?5:IM>=240?4:IM>=224?3:IM>=192?2:1;Ane[254]=Ane[254]=1;_9.string2buf=function(s){var t,n,r,a,i,l=s.length,o=0;for(a=0;a>>6,t[i++]=128|n&63):n<65536?(t[i++]=224|n>>>12,t[i++]=128|n>>>6&63,t[i++]=128|n&63):(t[i++]=240|n>>>18,t[i++]=128|n>>>12&63,t[i++]=128|n>>>6&63,t[i++]=128|n&63);return t};function Bas(s,t){if(t<65534&&(s.subarray&&zas||!s.subarray&&Oas))return String.fromCharCode.apply(null,YDe.shrinkBuf(s,t));for(var n="",r=0;r4){o[r++]=65533,n+=i-1;continue}for(a&=i===2?31:i===3?15:7;i>1&&n1){o[r++]=65533;continue}a<65536?o[r++]=a:(a-=65536,o[r++]=55296|a>>10&1023,o[r++]=56320|a&1023)}return Bas(o,r)};_9.utf8border=function(s,t){var n;for(t=t||s.length,t>s.length&&(t=s.length),n=t-1;n>=0&&(s[n]&192)===128;)n--;return n<0||n===0?t:n+Ane[s[n]]>t?n:t};function $er(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0}var $as=$er,cte=k3,dte=$T,KXe=_9,YXe=alt,Uer=$as,Uas=Object.prototype.toString,qer=0,X$e=4,GV=0,H3t=1,G3t=2,Ver=-1,Her=0,Ger=8;function kB(s){if(!(this instanceof kB))return new kB(s);this.options=dte.assign({level:Ver,method:Ger,chunkSize:16384,windowBits:15,memLevel:8,strategy:Her,to:""},s||{});var t=this.options;t.raw&&t.windowBits>0?t.windowBits=-t.windowBits:t.gzip&&t.windowBits>0&&t.windowBits<16&&(t.windowBits+=16),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new Uer,this.strm.avail_out=0;var n=cte.deflateInit2(this.strm,t.level,t.method,t.windowBits,t.memLevel,t.strategy);if(n!==GV)throw new Error(YXe[n]);if(t.header&&cte.deflateSetHeader(this.strm,t.header),t.dictionary){var r;if(typeof t.dictionary=="string"?r=KXe.string2buf(t.dictionary):Uas.call(t.dictionary)==="[object ArrayBuffer]"?r=new Uint8Array(t.dictionary):r=t.dictionary,n=cte.deflateSetDictionary(this.strm,r),n!==GV)throw new Error(YXe[n]);this._dict_set=!0}}kB.prototype.push=function(s,t){var n=this.strm,r=this.options.chunkSize,a,i;if(this.ended)return!1;i=t===~~t?t:t===!0?X$e:qer,typeof s=="string"?n.input=KXe.string2buf(s):Uas.call(s)==="[object ArrayBuffer]"?n.input=new Uint8Array(s):n.input=s,n.next_in=0,n.avail_in=n.input.length;do{if(n.avail_out===0&&(n.output=new dte.Buf8(r),n.next_out=0,n.avail_out=r),a=cte.deflate(n,i),a!==H3t&&a!==GV)return this.onEnd(a),this.ended=!0,!1;(n.avail_out===0||n.avail_in===0&&(i===X$e||i===G3t))&&(this.options.to==="string"?this.onData(KXe.buf2binstring(dte.shrinkBuf(n.output,n.next_out))):this.onData(dte.shrinkBuf(n.output,n.next_out)))}while((n.avail_in>0||n.avail_out===0)&&a!==H3t);return i===X$e?(a=cte.deflateEnd(this.strm),this.onEnd(a),this.ended=!0,a===GV):(i===G3t&&(this.onEnd(GV),n.avail_out=0),!0)};kB.prototype.onData=function(s){this.chunks.push(s)};kB.prototype.onEnd=function(s){s===GV&&(this.options.to==="string"?this.result=this.chunks.join(""):this.result=dte.flattenChunks(this.chunks)),this.chunks=[],this.err=s,this.msg=this.strm.msg};function ilt(s,t){var n=new kB(t);if(n.push(s,!0),n.err)throw n.msg||YXe[n.err];return n.result}function Wer(s,t){return t=t||{},t.raw=!0,ilt(s,t)}function Ker(s,t){return t=t||{},t.gzip=!0,ilt(s,t)}noe.Deflate=kB;noe.deflate=ilt;noe.deflateRaw=Wer;noe.gzip=Ker;var ioe={},IC={},$ue=30,Yer=12,Zer=function(t,n){var r,a,i,l,o,c,d,u,h,m,f,g,x,y,v,b,w,S,C,E,I,P,R,D,O;r=t.state,a=t.next_in,D=t.input,i=a+(t.avail_in-5),l=t.next_out,O=t.output,o=l-(n-t.avail_out),c=l+(t.avail_out-257),d=r.dmax,u=r.wsize,h=r.whave,m=r.wnext,f=r.window,g=r.hold,x=r.bits,y=r.lencode,v=r.distcode,b=(1<>>24,g>>>=C,x-=C,C=S>>>16&255,C===0)O[l++]=S&65535;else if(C&16){E=S&65535,C&=15,C&&(x>>=C,x-=C),x<15&&(g+=D[a++]<>>24,g>>>=C,x-=C,C=S>>>16&255,C&16){if(I=S&65535,C&=15,xd){t.msg="invalid distance too far back",r.mode=$ue;break e}if(g>>>=C,x-=C,C=l-o,I>C){if(C=I-C,C>h&&r.sane){t.msg="invalid distance too far back",r.mode=$ue;break e}if(P=0,R=f,m===0){if(P+=u-C,C2;)O[l++]=R[P++],O[l++]=R[P++],O[l++]=R[P++],E-=3;E&&(O[l++]=R[P++],E>1&&(O[l++]=R[P++]))}else{P=l-I;do O[l++]=O[P++],O[l++]=O[P++],O[l++]=O[P++],E-=3;while(E>2);E&&(O[l++]=O[P++],E>1&&(O[l++]=O[P++]))}}else if(C&64){t.msg="invalid distance code",r.mode=$ue;break e}else{S=v[(S&65535)+(g&(1<>3,a-=E,x-=E<<3,g&=(1<=1&&U[f]===0;f--);if(g>f&&(g=f),f===0)return i[l++]=1<<24|64<<16|0,i[l++]=1<<24|64<<16|0,c.bits=1,0;for(m=1;m0&&(t===Z3t||f!==1))return-1;for(W[1]=0,u=1;uK3t||t===X3t&&b>Y3t)return 1;for(;;){Y=u-y,o[h]O?(X=V[G+o[h]],ae=R[D+o[h]]):(X=96,ae=0),S=1<>y)+C]=Y<<24|X<<16|ae|0;while(C!==0);for(S=1<>=1;if(S!==0?(w&=S-1,w+=S):w=0,h++,--U[u]===0){if(u===f)break;u=n[r+o[h]]}if(u>g&&(w&I)!==E){for(y===0&&(y=g),P+=m,x=u-y,v=1<K3t||t===X3t&&b>Y3t)return 1;E=w&I,i[E]=g<<24|x<<16|P-l|0}}return w!==0&&(i[P+w]=u-y<<24|64<<16|0),c.bits=g,0},r2=$T,ZXe=Mas,d5=Pas,str=Zer,ute=ttr,ntr=0,qas=1,Vas=2,Q3t=4,rtr=5,Uue=6,SB=0,atr=1,itr=2,vk=-2,Has=-3,Gas=-4,otr=-5,J3t=8,Was=1,eAt=2,tAt=3,sAt=4,nAt=5,rAt=6,aAt=7,iAt=8,oAt=9,lAt=10,CPe=11,hA=12,J$e=13,cAt=14,eUe=15,dAt=16,uAt=17,hAt=18,mAt=19,que=20,Vue=21,fAt=22,pAt=23,gAt=24,xAt=25,yAt=26,tUe=27,vAt=28,bAt=29,Op=30,Kas=31,ltr=32,ctr=852,dtr=592,utr=15,htr=utr;function _At(s){return(s>>>24&255)+(s>>>8&65280)+((s&65280)<<8)+((s&255)<<24)}function mtr(){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 r2.Buf16(320),this.work=new r2.Buf16(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}function Yas(s){var t;return!s||!s.state?vk:(t=s.state,s.total_in=s.total_out=t.total=0,s.msg="",t.wrap&&(s.adler=t.wrap&1),t.mode=Was,t.last=0,t.havedict=0,t.dmax=32768,t.head=null,t.hold=0,t.bits=0,t.lencode=t.lendyn=new r2.Buf32(ctr),t.distcode=t.distdyn=new r2.Buf32(dtr),t.sane=1,t.back=-1,SB)}function Zas(s){var t;return!s||!s.state?vk:(t=s.state,t.wsize=0,t.whave=0,t.wnext=0,Yas(s))}function Xas(s,t){var n,r;return!s||!s.state||(r=s.state,t<0?(n=0,t=-t):(n=(t>>4)+1,t<48&&(t&=15)),t&&(t<8||t>15))?vk:(r.window!==null&&r.wbits!==t&&(r.window=null),r.wrap=n,r.wbits=t,Zas(s))}function Qas(s,t){var n,r;return s?(r=new mtr,s.state=r,r.window=null,n=Xas(s,t),n!==SB&&(s.state=null),n):vk}function ftr(s){return Qas(s,htr)}var wAt=!0,sUe,nUe;function ptr(s){if(wAt){var t;for(sUe=new r2.Buf32(512),nUe=new r2.Buf32(32),t=0;t<144;)s.lens[t++]=8;for(;t<256;)s.lens[t++]=9;for(;t<280;)s.lens[t++]=7;for(;t<288;)s.lens[t++]=8;for(ute(qas,s.lens,0,288,sUe,0,s.work,{bits:9}),t=0;t<32;)s.lens[t++]=5;ute(Vas,s.lens,0,32,nUe,0,s.work,{bits:5}),wAt=!1}s.lencode=sUe,s.lenbits=9,s.distcode=nUe,s.distbits=5}function Jas(s,t,n,r){var a,i=s.state;return i.window===null&&(i.wsize=1<=i.wsize?(r2.arraySet(i.window,t,n-i.wsize,i.wsize,0),i.wnext=0,i.whave=i.wsize):(a=i.wsize-i.wnext,a>r&&(a=r),r2.arraySet(i.window,t,n-r,a,i.wnext),r-=a,r?(r2.arraySet(i.window,t,n-r,r,0),i.wnext=r,i.whave=i.wsize):(i.wnext+=a,i.wnext===i.wsize&&(i.wnext=0),i.whave>>8&255,n.check=d5(n.check,R,2,0),d=0,u=0,n.mode=eAt;break}if(n.flags=0,n.head&&(n.head.done=!1),!(n.wrap&1)||(((d&255)<<8)+(d>>8))%31){s.msg="incorrect header check",n.mode=Op;break}if((d&15)!==J3t){s.msg="unknown compression method",n.mode=Op;break}if(d>>>=4,u-=4,I=(d&15)+8,n.wbits===0)n.wbits=I;else if(I>n.wbits){s.msg="invalid window size",n.mode=Op;break}n.dmax=1<>8&1),n.flags&512&&(R[0]=d&255,R[1]=d>>>8&255,n.check=d5(n.check,R,2,0)),d=0,u=0,n.mode=tAt;case tAt:for(;u<32;){if(o===0)break e;o--,d+=r[i++]<>>8&255,R[2]=d>>>16&255,R[3]=d>>>24&255,n.check=d5(n.check,R,4,0)),d=0,u=0,n.mode=sAt;case sAt:for(;u<16;){if(o===0)break e;o--,d+=r[i++]<>8),n.flags&512&&(R[0]=d&255,R[1]=d>>>8&255,n.check=d5(n.check,R,2,0)),d=0,u=0,n.mode=nAt;case nAt:if(n.flags&1024){for(;u<16;){if(o===0)break e;o--,d+=r[i++]<>>8&255,n.check=d5(n.check,R,2,0)),d=0,u=0}else n.head&&(n.head.extra=null);n.mode=rAt;case rAt:if(n.flags&1024&&(f=n.length,f>o&&(f=o),f&&(n.head&&(I=n.head.extra_len-n.length,n.head.extra||(n.head.extra=new Array(n.head.extra_len)),r2.arraySet(n.head.extra,r,i,f,I)),n.flags&512&&(n.check=d5(n.check,r,f,i)),o-=f,i+=f,n.length-=f),n.length))break e;n.length=0,n.mode=aAt;case aAt:if(n.flags&2048){if(o===0)break e;f=0;do I=r[i+f++],n.head&&I&&n.length<65536&&(n.head.name+=String.fromCharCode(I));while(I&&f>9&1,n.head.done=!0),s.adler=n.check=0,n.mode=hA;break;case lAt:for(;u<32;){if(o===0)break e;o--,d+=r[i++]<>>=u&7,u-=u&7,n.mode=tUe;break}for(;u<3;){if(o===0)break e;o--,d+=r[i++]<>>=1,u-=1,d&3){case 0:n.mode=cAt;break;case 1:if(ptr(n),n.mode=que,t===Uue){d>>>=2,u-=2;break e}break;case 2:n.mode=uAt;break;case 3:s.msg="invalid block type",n.mode=Op}d>>>=2,u-=2;break;case cAt:for(d>>>=u&7,u-=u&7;u<32;){if(o===0)break e;o--,d+=r[i++]<>>16^65535)){s.msg="invalid stored block lengths",n.mode=Op;break}if(n.length=d&65535,d=0,u=0,n.mode=eUe,t===Uue)break e;case eUe:n.mode=dAt;case dAt:if(f=n.length,f){if(f>o&&(f=o),f>c&&(f=c),f===0)break e;r2.arraySet(a,r,i,f,l),o-=f,i+=f,c-=f,l+=f,n.length-=f;break}n.mode=hA;break;case uAt:for(;u<14;){if(o===0)break e;o--,d+=r[i++]<>>=5,u-=5,n.ndist=(d&31)+1,d>>>=5,u-=5,n.ncode=(d&15)+4,d>>>=4,u-=4,n.nlen>286||n.ndist>30){s.msg="too many length or distance symbols",n.mode=Op;break}n.have=0,n.mode=hAt;case hAt:for(;n.have>>=3,u-=3}for(;n.have<19;)n.lens[U[n.have++]]=0;if(n.lencode=n.lendyn,n.lenbits=7,D={bits:n.lenbits},P=ute(ntr,n.lens,0,19,n.lencode,0,n.work,D),n.lenbits=D.bits,P){s.msg="invalid code lengths set",n.mode=Op;break}n.have=0,n.mode=mAt;case mAt:for(;n.have>>24,b=y>>>16&255,w=y&65535,!(v<=u);){if(o===0)break e;o--,d+=r[i++]<>>=v,u-=v,n.lens[n.have++]=w;else{if(w===16){for(O=v+2;u>>=v,u-=v,n.have===0){s.msg="invalid bit length repeat",n.mode=Op;break}I=n.lens[n.have-1],f=3+(d&3),d>>>=2,u-=2}else if(w===17){for(O=v+3;u>>=v,u-=v,I=0,f=3+(d&7),d>>>=3,u-=3}else{for(O=v+7;u>>=v,u-=v,I=0,f=11+(d&127),d>>>=7,u-=7}if(n.have+f>n.nlen+n.ndist){s.msg="invalid bit length repeat",n.mode=Op;break}for(;f--;)n.lens[n.have++]=I}}if(n.mode===Op)break;if(n.lens[256]===0){s.msg="invalid code -- missing end-of-block",n.mode=Op;break}if(n.lenbits=9,D={bits:n.lenbits},P=ute(qas,n.lens,0,n.nlen,n.lencode,0,n.work,D),n.lenbits=D.bits,P){s.msg="invalid literal/lengths set",n.mode=Op;break}if(n.distbits=6,n.distcode=n.distdyn,D={bits:n.distbits},P=ute(Vas,n.lens,n.nlen,n.ndist,n.distcode,0,n.work,D),n.distbits=D.bits,P){s.msg="invalid distances set",n.mode=Op;break}if(n.mode=que,t===Uue)break e;case que:n.mode=Vue;case Vue:if(o>=6&&c>=258){s.next_out=l,s.avail_out=c,s.next_in=i,s.avail_in=o,n.hold=d,n.bits=u,str(s,m),l=s.next_out,a=s.output,c=s.avail_out,i=s.next_in,r=s.input,o=s.avail_in,d=n.hold,u=n.bits,n.mode===hA&&(n.back=-1);break}for(n.back=0;y=n.lencode[d&(1<>>24,b=y>>>16&255,w=y&65535,!(v<=u);){if(o===0)break e;o--,d+=r[i++]<>S)],v=y>>>24,b=y>>>16&255,w=y&65535,!(S+v<=u);){if(o===0)break e;o--,d+=r[i++]<>>=S,u-=S,n.back+=S}if(d>>>=v,u-=v,n.back+=v,n.length=w,b===0){n.mode=yAt;break}if(b&32){n.back=-1,n.mode=hA;break}if(b&64){s.msg="invalid literal/length code",n.mode=Op;break}n.extra=b&15,n.mode=fAt;case fAt:if(n.extra){for(O=n.extra;u>>=n.extra,u-=n.extra,n.back+=n.extra}n.was=n.length,n.mode=pAt;case pAt:for(;y=n.distcode[d&(1<>>24,b=y>>>16&255,w=y&65535,!(v<=u);){if(o===0)break e;o--,d+=r[i++]<>S)],v=y>>>24,b=y>>>16&255,w=y&65535,!(S+v<=u);){if(o===0)break e;o--,d+=r[i++]<>>=S,u-=S,n.back+=S}if(d>>>=v,u-=v,n.back+=v,b&64){s.msg="invalid distance code",n.mode=Op;break}n.offset=w,n.extra=b&15,n.mode=gAt;case gAt:if(n.extra){for(O=n.extra;u>>=n.extra,u-=n.extra,n.back+=n.extra}if(n.offset>n.dmax){s.msg="invalid distance too far back",n.mode=Op;break}n.mode=xAt;case xAt:if(c===0)break e;if(f=m-c,n.offset>f){if(f=n.offset-f,f>n.whave&&n.sane){s.msg="invalid distance too far back",n.mode=Op;break}f>n.wnext?(f-=n.wnext,g=n.wsize-f):g=n.wnext-f,f>n.length&&(f=n.length),x=n.window}else x=a,g=l-n.offset,f=n.length;f>c&&(f=c),c-=f,n.length-=f;do a[l++]=x[g++];while(--f);n.length===0&&(n.mode=Vue);break;case yAt:if(c===0)break e;a[l++]=n.length,c--,n.mode=Vue;break;case tUe:if(n.wrap){for(;u<32;){if(o===0)break e;o--,d|=r[i++]<=0&&t.windowBits<16&&(t.windowBits=-t.windowBits,t.windowBits===0&&(t.windowBits=-15)),t.windowBits>=0&&t.windowBits<16&&!(s&&s.windowBits)&&(t.windowBits+=32),t.windowBits>15&&t.windowBits<48&&(t.windowBits&15||(t.windowBits|=15)),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new wtr,this.strm.avail_out=0;var n=WV.inflateInit2(this.strm,t.windowBits);if(n!==Zx.Z_OK)throw new Error(XXe[n]);if(this.header=new jtr,WV.inflateGetHeader(this.strm,this.header),t.dictionary&&(typeof t.dictionary=="string"?t.dictionary=bAe.string2buf(t.dictionary):tis.call(t.dictionary)==="[object ArrayBuffer]"&&(t.dictionary=new Uint8Array(t.dictionary)),t.raw&&(n=WV.inflateSetDictionary(this.strm,t.dictionary),n!==Zx.Z_OK)))throw new Error(XXe[n])}CB.prototype.push=function(s,t){var n=this.strm,r=this.options.chunkSize,a=this.options.dictionary,i,l,o,c,d,u=!1;if(this.ended)return!1;l=t===~~t?t:t===!0?Zx.Z_FINISH:Zx.Z_NO_FLUSH,typeof s=="string"?n.input=bAe.binstring2buf(s):tis.call(s)==="[object ArrayBuffer]"?n.input=new Uint8Array(s):n.input=s,n.next_in=0,n.avail_in=n.input.length;do{if(n.avail_out===0&&(n.output=new hte.Buf8(r),n.next_out=0,n.avail_out=r),i=WV.inflate(n,Zx.Z_NO_FLUSH),i===Zx.Z_NEED_DICT&&a&&(i=WV.inflateSetDictionary(this.strm,a)),i===Zx.Z_BUF_ERROR&&u===!0&&(i=Zx.Z_OK,u=!1),i!==Zx.Z_STREAM_END&&i!==Zx.Z_OK)return this.onEnd(i),this.ended=!0,!1;n.next_out&&(n.avail_out===0||i===Zx.Z_STREAM_END||n.avail_in===0&&(l===Zx.Z_FINISH||l===Zx.Z_SYNC_FLUSH))&&(this.options.to==="string"?(o=bAe.utf8border(n.output,n.next_out),c=n.next_out-o,d=bAe.buf2string(n.output,o),n.next_out=c,n.avail_out=r-c,c&&hte.arraySet(n.output,n.output,o,c,0),this.onData(d)):this.onData(hte.shrinkBuf(n.output,n.next_out))),n.avail_in===0&&n.avail_out===0&&(u=!0)}while((n.avail_in>0||n.avail_out===0)&&i!==Zx.Z_STREAM_END);return i===Zx.Z_STREAM_END&&(l=Zx.Z_FINISH),l===Zx.Z_FINISH?(i=WV.inflateEnd(this.strm),this.onEnd(i),this.ended=!0,i===Zx.Z_OK):(l===Zx.Z_SYNC_FLUSH&&(this.onEnd(Zx.Z_OK),n.avail_out=0),!0)};CB.prototype.onData=function(s){this.chunks.push(s)};CB.prototype.onEnd=function(s){s===Zx.Z_OK&&(this.options.to==="string"?this.result=this.chunks.join(""):this.result=hte.flattenChunks(this.chunks)),this.chunks=[],this.err=s,this.msg=this.strm.msg};function olt(s,t){var n=new CB(t);if(n.push(s,!0),n.err)throw n.msg||XXe[n.err];return n.result}function Ntr(s,t){return t=t||{},t.raw=!0,olt(s,t)}ioe.Inflate=CB;ioe.inflate=olt;ioe.inflateRaw=Ntr;ioe.ungzip=olt;var ktr=$T.assign,Str=noe,Ctr=ioe,Atr=eis,sis={};ktr(sis,Str,Ctr,Atr);var Etr=sis;const ZDe=au(Etr);var jAt="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",WQ=new Uint8Array(256);for(var Hue=0;Hue>4,d[a++]=(l&15)<<4|o>>2,d[a++]=(o&3)<<6|c&63;return d},Mtr=function(s){for(var t="",n=0;nr)throw new Error(m0(t)+" must be at least "+n+" and at most "+r+", but was actually "+s)},lS=function(s,t,n,r){Pr(s,t,["number","undefined"]),typeof s=="number"&&a2(s,t,n,r)},ais=function(s,t,n){if(Pr(s,t,["number"]),s%n!==0)throw new Error(m0(t)+" must be a multiple of "+n+", but was actually "+s)},rsr=function(s,t){if(!Number.isInteger(s))throw new Error(m0(t)+" must be an integer, but was actually "+s)},QDe=function(s,t){if(![1,0].includes(Math.sign(s)))throw new Error(m0(t)+" must be a positive number or 0, but was actually "+s)},Zc=new Uint16Array(256);for(var Kue=0;Kue<256;Kue++)Zc[Kue]=Kue;Zc[22]=zc("");Zc[24]=zc("˘");Zc[25]=zc("ˇ");Zc[26]=zc("ˆ");Zc[27]=zc("˙");Zc[28]=zc("˝");Zc[29]=zc("˛");Zc[30]=zc("˚");Zc[31]=zc("˜");Zc[127]=zc("�");Zc[128]=zc("•");Zc[129]=zc("†");Zc[130]=zc("‡");Zc[131]=zc("…");Zc[132]=zc("—");Zc[133]=zc("–");Zc[134]=zc("ƒ");Zc[135]=zc("⁄");Zc[136]=zc("‹");Zc[137]=zc("›");Zc[138]=zc("−");Zc[139]=zc("‰");Zc[140]=zc("„");Zc[141]=zc("“");Zc[142]=zc("”");Zc[143]=zc("‘");Zc[144]=zc("’");Zc[145]=zc("‚");Zc[146]=zc("™");Zc[147]=zc("fi");Zc[148]=zc("fl");Zc[149]=zc("Ł");Zc[150]=zc("Œ");Zc[151]=zc("Š");Zc[152]=zc("Ÿ");Zc[153]=zc("Ž");Zc[154]=zc("ı");Zc[155]=zc("ł");Zc[156]=zc("œ");Zc[157]=zc("š");Zc[158]=zc("ž");Zc[159]=zc("�");Zc[160]=zc("€");Zc[173]=zc("�");var iis=function(s){for(var t=new Array(s.length),n=0,r=s.length;n=un.ExclamationPoint&&s<=un.Tilde&&!ult[s]},TAt={},MAt=new Map,sn=function(s){Si(t,s);function t(n,r){var a=this;if(n!==TAt)throw new llt("PDFName");a=s.call(this)||this;for(var i="/",l=0,o=r.length;l=un.Zero&&d<=un.Nine||d>=un.a&&d<=un.f||d>=un.A&&d<=un.F?(r+=c,(r.length===2||!(u>="0"&&u<="9"||u>="a"&&u<="f"||u>="A"&&u<="F"))&&(i(parseInt(r,16)),r="")):i(d):d===un.Hash?a=!0:i(d)}return new Uint8Array(n)},t.prototype.decodeText=function(){var n=this.asBytes();return String.fromCharCode.apply(String,Array.from(n))},t.prototype.asString=function(){return this.encodedName},t.prototype.value=function(){return this.encodedName},t.prototype.clone=function(){return this},t.prototype.toString=function(){return this.encodedName},t.prototype.sizeInBytes=function(){return this.encodedName.length},t.prototype.copyBytesInto=function(n,r){return r+=xb(this.encodedName,n,r),this.encodedName.length},t.of=function(n){var r=wsr(n),a=MAt.get(r);return a||(a=new t(TAt,r),MAt.set(r,a)),a},t.Length=t.of("Length"),t.FlateDecode=t.of("FlateDecode"),t.Resources=t.of("Resources"),t.Font=t.of("Font"),t.XObject=t.of("XObject"),t.ExtGState=t.of("ExtGState"),t.Contents=t.of("Contents"),t.Type=t.of("Type"),t.Parent=t.of("Parent"),t.MediaBox=t.of("MediaBox"),t.Page=t.of("Page"),t.Annots=t.of("Annots"),t.TrimBox=t.of("TrimBox"),t.ArtBox=t.of("ArtBox"),t.BleedBox=t.of("BleedBox"),t.CropBox=t.of("CropBox"),t.Rotate=t.of("Rotate"),t.Title=t.of("Title"),t.Author=t.of("Author"),t.Subject=t.of("Subject"),t.Creator=t.of("Creator"),t.Keywords=t.of("Keywords"),t.Producer=t.of("Producer"),t.CreationDate=t.of("CreationDate"),t.ModDate=t.of("ModDate"),t}(M_),Nsr=function(s){Si(t,s);function t(){return s!==null&&s.apply(this,arguments)||this}return t.prototype.asNull=function(){return null},t.prototype.clone=function(){return this},t.prototype.toString=function(){return"null"},t.prototype.sizeInBytes=function(){return 4},t.prototype.copyBytesInto=function(n,r){return n[r++]=un.n,n[r++]=un.u,n[r++]=un.l,n[r++]=un.l,4},t}(M_);const vw=new Nsr;var dd=function(s){Si(t,s);function t(n,r){var a=s.call(this)||this;return a.dict=n,a.context=r,a}return t.prototype.keys=function(){return Array.from(this.dict.keys())},t.prototype.values=function(){return Array.from(this.dict.values())},t.prototype.entries=function(){return Array.from(this.dict.entries())},t.prototype.set=function(n,r){this.dict.set(n,r)},t.prototype.get=function(n,r){r===void 0&&(r=!1);var a=this.dict.get(n);if(!(a===vw&&!r))return a},t.prototype.has=function(n){var r=this.dict.get(n);return r!==void 0&&r!==vw},t.prototype.lookupMaybe=function(n){for(var r,a=[],i=1;ithis.largestObjectNumber&&(this.largestObjectNumber=t.objectNumber)},s.prototype.nextRef=function(){return this.largestObjectNumber+=1,am.of(this.largestObjectNumber)},s.prototype.register=function(t){var n=this.nextRef();return this.assign(n,t),n},s.prototype.delete=function(t){return this.indirectObjects.delete(t)},s.prototype.lookupMaybe=function(t){for(var n=[],r=1;r1?(this.subsections.push([t]),this.chunkIdx+=1,this.chunkLength=1):(n.push(t),this.chunkLength+=1)},s.create=function(){return new s({ref:am.of(0,65535),offset:0,deleted:!0})},s.createEmpty=function(){return new s},s}(),mlt=function(){function s(t){this.lastXRefOffset=String(t)}return s.prototype.toString=function(){return`startxref `+this.lastXRefOffset+` %%EOF`},s.prototype.sizeInBytes=function(){return 16+this.lastXRefOffset.length},s.prototype.copyBytesInto=function(t,n){var r=n;return t[n++]=un.s,t[n++]=un.t,t[n++]=un.a,t[n++]=un.r,t[n++]=un.t,t[n++]=un.x,t[n++]=un.r,t[n++]=un.e,t[n++]=un.f,t[n++]=un.Newline,n+=xb(this.lastXRefOffset,t,n),t[n++]=un.Newline,t[n++]=un.Percent,t[n++]=un.Percent,t[n++]=un.E,t[n++]=un.O,t[n++]=un.F,n-r},s.forLastCrossRefSectionOffset=function(t){return new s(t)},s}(),Csr=function(){function s(t){this.dict=t}return s.prototype.toString=function(){return`trailer `+this.dict.toString()},s.prototype.sizeInBytes=function(){return 8+this.dict.sizeInBytes()},s.prototype.copyBytesInto=function(t,n){var r=n;return t[n++]=un.t,t[n++]=un.r,t[n++]=un.a,t[n++]=un.i,t[n++]=un.l,t[n++]=un.e,t[n++]=un.r,t[n++]=un.Newline,n+=this.dict.copyBytesInto(t,n),n-r},s.of=function(t){return new s(t)},s}(),cis=function(s){Si(t,s);function t(n,r,a){a===void 0&&(a=!0);var i=s.call(this,n.obj({}),a)||this;return i.objects=r,i.offsets=i.computeObjectOffsets(),i.offsetsString=i.computeOffsetsString(),i.dict.set(sn.of("Type"),sn.of("ObjStm")),i.dict.set(sn.of("N"),Ec.of(i.objects.length)),i.dict.set(sn.of("First"),Ec.of(i.offsetsString.length)),i}return t.prototype.getObjectsCount=function(){return this.objects.length},t.prototype.clone=function(n){return t.withContextAndObjects(n||this.dict.context,this.objects.slice(),this.encode)},t.prototype.getContentsString=function(){for(var n=this.offsetsString,r=0,a=this.objects.length;r1&&(l.push(o),l.push(u.ref.objectNumber),o=0),o+=1}return l.push(o),l},i.computeEntryTuples=function(){for(var l=new Array(i.entries.length),o=0,c=i.entries.length;oo[0]&&(o[0]=g),x>o[1]&&(o[1]=x),y>o[2]&&(o[2]=y)}return o},i.entries=r||[],i.entryTuplesCache=XE.populatedBy(i.computeEntryTuples),i.maxByteWidthsCache=XE.populatedBy(i.computeMaxEntryByteWidths),i.indexCache=XE.populatedBy(i.computeIndex),n.set(sn.of("Type"),sn.of("XRef")),i}return t.prototype.addDeletedEntry=function(n,r){var a=wP.Deleted;this.entries.push({type:a,ref:n,nextFreeObjectNumber:r}),this.entryTuplesCache.invalidate(),this.maxByteWidthsCache.invalidate(),this.indexCache.invalidate(),this.contentsCache.invalidate()},t.prototype.addUncompressedEntry=function(n,r){var a=wP.Uncompressed;this.entries.push({type:a,ref:n,offset:r}),this.entryTuplesCache.invalidate(),this.maxByteWidthsCache.invalidate(),this.indexCache.invalidate(),this.contentsCache.invalidate()},t.prototype.addCompressedEntry=function(n,r,a){var i=wP.Compressed;this.entries.push({type:i,ref:n,objectStreamRef:r,index:a}),this.entryTuplesCache.invalidate(),this.maxByteWidthsCache.invalidate(),this.indexCache.invalidate(),this.contentsCache.invalidate()},t.prototype.clone=function(n){var r=this,a=r.dict,i=r.entries,l=r.encode;return t.of(a.clone(n),i.slice(),l)},t.prototype.getContentsString=function(){for(var n=this.entryTuplesCache.access(),r=this.maxByteWidthsCache.access(),a="",i=0,l=n.length;i=0;g--)a+=(h[g]||0).toString(2);for(var g=r[1]-1;g>=0;g--)a+=(m[g]||0).toString(2);for(var g=r[2]-1;g>=0;g--)a+=(f[g]||0).toString(2)}return a},t.prototype.getUnencodedContents=function(){for(var n=this.entryTuplesCache.access(),r=this.maxByteWidthsCache.access(),a=new Uint8Array(this.getUnencodedContentsSize()),i=0,l=0,o=n.length;l=0;x--)a[i++]=m[x]||0;for(var x=r[1]-1;x>=0;x--)a[i++]=f[x]||0;for(var x=r[2]-1;x>=0;x--)a[i++]=g[x]||0}return a},t.prototype.getUnencodedContentsSize=function(){var n=this.maxByteWidthsCache.access(),r=AJn(n);return r*this.entries.length},t.prototype.updateDict=function(){s.prototype.updateDict.call(this);var n=this.maxByteWidthsCache.access(),r=this.indexCache.access(),a=this.dict.context;this.dict.set(sn.of("W"),a.obj(n)),this.dict.set(sn.of("Index"),a.obj(r))},t.create=function(n,r){r===void 0&&(r=!0);var a=new t(n,[],r);return a.addDeletedEntry(am.of(0,65535),0),a},t.of=function(n,r,a){return a===void 0&&(a=!0),new t(n,r,a)},t}(hlt),Esr=function(s){Si(t,s);function t(n,r,a,i){var l=s.call(this,n,r)||this;return l.encodeStreams=a,l.objectsPerStream=i,l}return t.prototype.computeBufferSize=function(){return gd(this,void 0,void 0,function(){var n,r,a,i,l,o,c,d,g,x,u,v,h,m,y,f,g,x,y,v,b,w,S,C;return xd(this,function(E){switch(E.label){case 0:n=this.context.largestObjectNumber+1,r=JDe.forVersion(1,7),a=r.sizeInBytes()+2,i=Asr.create(this.createTrailerDict(),this.encodeStreams),l=[],o=[],c=[],d=this.context.enumerateIndirectObjects(),g=0,x=d.length,E.label=1;case 1:return g"},t.prototype.sizeInBytes=function(){return this.value.length+2},t.prototype.copyBytesInto=function(n,r){return n[r++]=un.LessThan,r+=xb(this.value,n,r),n[r++]=un.GreaterThan,this.value.length+2},t.of=function(n){return new t(n)},t.fromText=function(n){for(var r=PJn(n),a="",i=0,l=r.length;i> def /CMapName /Adobe-Identity-UCS def /CMapType 2 def 1 begincodespacerange <0000> endcodespacerange `+s.length+` beginbfchar `+s.map(function(t){var n=t[0],r=t[1];return n+" "+r}).join(` `)+` endbfchar endcmap CMapName currentdict /CMap defineresource pop end end`},RAt=function(){for(var s=[],t=0;t"},_Ae=function(s){return eoe(s,4)},Psr=function(s){if(IJn(s))return _Ae(s);if(LJn(s)){var t=das(s),n=uas(s);return""+_Ae(t)+_Ae(n)}var r=GDe(s),a="0x"+r+" is not a valid UTF-8 or UTF-16 codepoint.";throw new Error(a)},Isr=function(s){var t=0,n=function(r){t|=1<=un.Zero&&d<=un.Seven?(r+=c,(r.length===3||!(u>="0"&&u<="7"))&&(i(parseInt(r,8)),r="")):i(d):d===un.BackSlash?a=!0:i(d)}return new Uint8Array(n)},t.prototype.decodeText=function(){var n=this.asBytes();return pas(n)?has(n):iis(n)},t.prototype.decodeDate=function(){var n=this.decodeText(),r=las(n);if(!r)throw new ois(n);return r},t.prototype.asString=function(){return this.value},t.prototype.clone=function(){return t.of(this.value)},t.prototype.toString=function(){return"("+this.value+")"},t.prototype.sizeInBytes=function(){return this.value.length+2},t.prototype.copyBytesInto=function(n,r){return n[r++]=un.LeftParen,r+=xb(this.value,n,r),n[r++]=un.RightParen,this.value.length+2},t.of=function(n){return new t(n)},t.fromDate=function(n){var r=$S(String(n.getUTCFullYear()),4,"0"),a=$S(String(n.getUTCMonth()+1),2,"0"),i=$S(String(n.getUTCDate()),2,"0"),l=$S(String(n.getUTCHours()),2,"0"),o=$S(String(n.getUTCMinutes()),2,"0"),c=$S(String(n.getUTCSeconds()),2,"0");return new t("D:"+r+a+i+l+o+c+"Z")},t}(M_),flt=function(){function s(t,n,r,a){var i=this;this.allGlyphsInFontSortedById=function(){for(var l=new Array(i.font.characterSet.length),o=0,c=l.length;o>3)]>>7-((f&7)<<0)&1,O=3*D;o[w]=S[O],o[w+1]=S[O+1],o[w+2]=S[O+2],o[w+3]=D>2)]>>6-((f&3)<<1)&3,O=3*D;o[w]=S[O],o[w+1]=S[O+1],o[w+2]=S[O+2],o[w+3]=D>1)]>>4-((f&1)<<2)&15,O=3*D;o[w]=S[O],o[w+1]=S[O+1],o[w+2]=S[O+2],o[w+3]=D>>3)]>>>7-(Y&7)&1),X=W==y*255?0:255;c[G+Y]=X<<24|W<<16|W<<8|W}else if(u==2)for(var Y=0;Y>>2)]>>>6-((Y&3)<<1)&3),X=W==y*85?0:255;c[G+Y]=X<<24|W<<16|W<<8|W}else if(u==4)for(var Y=0;Y>>1)]>>>4-((Y&1)<<2)&15),X=W==y*17?0:255;c[G+Y]=X<<24|W<<16|W<<8|W}else if(u==8)for(var Y=0;Y>>2<<3));a==0;){if(a=y(t,m,1),i=y(t,m+1,2),m+=3,i==0){m&7&&(m+=8-(m&7));var P=(m>>>3)+4,R=t[P-4]|t[P-3]<<8;I&&(n=s.H.W(n,h+R)),n.set(new r(t.buffer,t.byteOffset+P,R),h),m=P+R<<3,h+=R;continue}if(I&&(n=s.H.W(n,h+(1<<17))),i==1&&(f=E.J,g=E.h,d=511,u=31),i==2){l=v(t,m,5)+257,o=v(t,m+5,5)+1,c=v(t,m+10,4)+4,m+=14;for(var D=1,O=0;O<38;O+=2)E.Q[O]=0,E.Q[O+1]=0;for(var O=0;OD&&(D=U)}m+=3*c,w(E.Q,D),S(E.Q,D,E.u),f=E.w,g=E.d,m=b(E.u,(1<>>4;if(!(Y>>>8))n[h++]=Y;else{if(Y==256)break;var X=h+Y-254;if(Y>264){var ae=E.q[Y-257];X=h+(ae>>>3)+v(t,m,ae&7),m+=ae&7}var ie=g[C(t,m)&u];m+=ie&15;var ne=ie>>>4,te=E.c[ne],J=(te>>>4)+y(t,m,te&15);for(m+=te&15;h>>4;if(h<=15)l[d]=h,d++;else{var m=0,f=0;h==16?(f=3+o(a,i,2),i+=2,m=l[d-1]):h==17?(f=3+o(a,i,3),i+=3):h==18&&(f=11+o(a,i,7),i+=7);for(var g=d+f;d>>1;li&&(i=c),l++}for(;l>1,d=t[o+1],u=c<<4|d,h=n-d,m=t[o]<>>15-n;r[g]=u,m++}},s.H.l=function(t,n){for(var r=s.H.m.r,a=15-n,i=0;i>>a}},s.H.M=function(t,n,r){r=r<<(n&7);var a=n>>>3;t[a]|=r,t[a+1]|=r>>>8},s.H.I=function(t,n,r){r=r<<(n&7);var a=n>>>3;t[a]|=r,t[a+1]|=r>>>8,t[a+2]|=r>>>16},s.H.e=function(t,n,r){return(t[n>>>3]|t[(n>>>3)+1]<<8)>>>(n&7)&(1<>>3]|t[(n>>>3)+1]<<8|t[(n>>>3)+2]<<16)>>>(n&7)&(1<>>3]|t[(n>>>3)+1]<<8|t[(n>>>3)+2]<<16)>>>(n&7)},s.H.i=function(t,n){return(t[n>>>3]|t[(n>>>3)+1]<<8|t[(n>>>3)+2]<<16|t[(n>>>3)+3]<<24)>>>(n&7)},s.H.m=function(){var t=Uint16Array,n=Uint32Array;return{K:new t(16),j:new t(16),X:[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],S:[3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258,999,999,999],T:[0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0],q:new t(32),p:[1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,65535,65535],z:[0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0],c:new n(32),J:new t(512),_:[],h:new t(32),$:[],w:new t(32768),C:[],v:[],d:new t(32768),D:[],u:new t(512),Q:[],r:new t(32768),s:new n(286),Y:new n(30),a:new n(19),t:new n(15e3),k:new t(65536),g:new t(32768)}}(),function(){for(var t=s.H.m,n=32768,r=0;r>>1|(a&1431655765)<<1,a=(a&3435973836)>>>2|(a&858993459)<<2,a=(a&4042322160)>>>4|(a&252645135)<<4,a=(a&4278255360)>>>8|(a&16711935)<<8,t.r[r]=(a>>>16|a<<16)>>>17}function i(l,o,c){for(;o--!=0;)l.push(0,c)}for(var r=0;r<32;r++)t.q[r]=t.S[r]<<3|t.T[r],t.c[r]=t.p[r]<<4|t.z[r];i(t._,144,8),i(t._,112,9),i(t._,24,7),i(t._,8,8),s.H.n(t._,9),s.H.A(t._,9,t.J),s.H.l(t._,9),i(t.$,32,5),s.H.n(t.$,5),s.H.A(t.$,5,t.h),s.H.l(t.$,5),i(t.Q,19,0),i(t.C,286,0),i(t.D,30,0),i(t.v,320,0)}(),s.H.N}();Qa.decode._readInterlace=function(s,t){for(var n=t.width,r=t.height,a=Qa.decode._getBPP(t),i=a>>3,l=Math.ceil(n*a/8),o=new Uint8Array(r*l),c=0,d=[0,0,4,0,2,0,1],u=[0,4,0,2,0,1,0],h=[8,8,8,4,4,2,2],m=[8,8,4,4,2,2,1],f=0;f<7;){for(var g=h[f],x=m[f],y=0,v=0,b=d[f];b>3];R=R>>7-(P&7)&1,o[E*l+(I>>3)]|=R<<7-((I&7)<<0)}if(a==2){var R=s[P>>3];R=R>>6-(P&7)&3,o[E*l+(I>>2)]|=R<<6-((I&3)<<1)}if(a==4){var R=s[P>>3];R=R>>4-(P&7)&15,o[E*l+(I>>1)]|=R<<4-((I&1)<<2)}if(a>=8)for(var D=E*l+I*i,O=0;O>3)+O];P+=a,I+=x}C++,E+=g}y*v!=0&&(c+=v*(1+S)),f=f+1}return o};Qa.decode._getBPP=function(s){var t=[1,null,3,1,2,null,4][s.ctype];return t*s.depth};Qa.decode._filterZero=function(s,t,n,r,a){var i=Qa.decode._getBPP(t),l=Math.ceil(r*i/8),o=Qa.decode._paeth;i=Math.ceil(i/8);var c=0,d=1,u=s[n],h=0;if(u>1&&(s[n]=[0,0,1][u-2]),u==3)for(h=i;h>>1)&255;for(var m=0;m>>1);for(;h>>1)}else{for(;h>8&255,s[t+1]=n&255},readUint:function(s,t){return s[t]*(256*256*256)+(s[t+1]<<16|s[t+2]<<8|s[t+3])},writeUint:function(s,t,n){s[t]=n>>24&255,s[t+1]=n>>16&255,s[t+2]=n>>8&255,s[t+3]=n&255},readASCII:function(s,t,n){for(var r="",a=0;a=0&&o>=0?(h=f*t+g<<2,m=(o+f)*a+l+g<<2):(h=(-o+f)*t-l+g<<2,m=f*a+g<<2),c==0)r[m]=s[h],r[m+1]=s[h+1],r[m+2]=s[h+2],r[m+3]=s[h+3];else if(c==1){var x=s[h+3]*.00392156862745098,y=s[h]*x,v=s[h+1]*x,b=s[h+2]*x,w=r[m+3]*(1/255),S=r[m]*w,C=r[m+1]*w,E=r[m+2]*w,I=1-x,P=x+w*I,R=P==0?0:1/P;r[m+3]=255*P,r[m+0]=(y+S*I)*R,r[m+1]=(v+C*I)*R,r[m+2]=(b+E*I)*R}else if(c==2){var x=s[h+3],y=s[h],v=s[h+1],b=s[h+2],w=r[m+3],S=r[m],C=r[m+1],E=r[m+2];x==w&&y==S&&v==C&&b==E?(r[m]=0,r[m+1]=0,r[m+2]=0,r[m+3]=0):(r[m]=y,r[m+1]=v,r[m+2]=b,r[m+3]=x)}else if(c==3){var x=s[h+3],y=s[h],v=s[h+1],b=s[h+2],w=r[m+3],S=r[m],C=r[m+1],E=r[m+2];if(x==w&&y==S&&v==C&&b==E)continue;if(x<220&&w>20)return!1}return!0};Qa.encode=function(s,t,n,r,a,i,l){r==null&&(r=0),l==null&&(l=!1);var o=Qa.encode.compress(s,t,n,r,[!1,!1,!1,0,l]);return Qa.encode.compressPNG(o,-1),Qa.encode._main(o,t,n,a,i)};Qa.encodeLL=function(s,t,n,r,a,i,l,o){for(var c={ctype:0+(r==1?0:2)+(a==0?0:4),depth:i,frames:[]},d=(r+a)*i,u=d*t,h=0;h1,h=!1,m=33+(u?20:0);if(a.sRGB!=null&&(m+=13),a.pHYs!=null&&(m+=21),s.ctype==3){for(var f=s.plte.length,g=0;g>>24!=255&&(h=!0);m+=8+f*3+4+(h?8+f*1+4:0)}for(var x=0;x>>8&255,I=S>>>16&255;v[d+w+0]=C,v[d+w+1]=E,v[d+w+2]=I}if(d+=f*3,l(v,d,i(v,d-f*3-4,f*3+4)),d+=4,h){l(v,d,f),d+=4,c(v,d,"tRNS"),d+=4;for(var g=0;g>>24&255;d+=f,l(v,d,i(v,d-f-4,f+4)),d+=4}}for(var P=0,x=0;x>2,U>>2));for(var f=0;fG&&X==V[y-G])Y[y]=Y[y-G];else{var ae=w[X];if(ae==null&&(w[X]=ae=S.length,S.push(X),S.length>=300))break;Y[y]=ae}}}var ie=S.length;ie<=256&&d==!1&&(ie<=2?h=1:ie<=4?h=2:ie<=16?h=4:h=8,h=Math.max(h,c));for(var f=0;f>1)]|=he[ve+Ee]<<4-(Ee&1)*4;else if(h==2)for(var Ee=0;Ee>2)]|=he[ve+Ee]<<6-(Ee&3)*2;else if(h==1)for(var Ee=0;Ee>3)]|=he[ve+Ee]<<7-(Ee&7)*1}te=_e,u=3,ce=1}else if(v==!1&&b.length==1){for(var _e=new Uint8Array(G*ne*3),Se=G*ne,y=0;yI&&(I=D),RP&&(P=R))}I==-1&&(C=E=I=P=0),a&&((C&1)==1&&C--,(E&1)==1&&E--);var U=(I-C+1)*(P-E+1);Uy&&(y=S),Cv&&(v=C))}y==-1&&(g=x=y=v=0),l&&((g&1)==1&&g--,(x&1)==1&&x--),i={x:g,y:x,width:y-g+1,height:v-x+1};var P=r[a];P.rect=i,P.blend=1,P.img=new Uint8Array(i.width*i.height*4),r[a-1].dispose==0?(Qa._copyTile(d,t,n,P.img,i.width,i.height,-i.x,-i.y,0),Qa.encode._prepareDiff(m,t,n,P.img,i)):Qa._copyTile(m,t,n,P.img,i.width,i.height,-i.x,-i.y,0)};Qa.encode._prepareDiff=function(s,t,n,r,a){Qa._copyTile(s,t,n,r,a.width,a.height,-a.x,-a.y,2)};Qa.encode._filterZero=function(s,t,n,r,a,i,l){var o=[],c=[0,1,2,3,4];i!=-1?c=[i]:(t*r>5e5||n==1)&&(c=[0]);var d;l&&(d={level:0});for(var u=l&&UZIP!=null?UZIP:ZDe,h=0;h>1)+256&255;if(i==4)for(var d=a;d>1)&255;for(var d=a;d>1)&255}if(i==4){for(var d=0;d>>1:n=n>>>1;s[t]=n}return s}(),update:function(s,t,n,r){for(var a=0;a>>8;return s},crc:function(s,t,n){return Qa.crc.update(4294967295,s,t,n)^4294967295}};Qa.quantize=function(s,t){var n=new Uint8Array(s),r=n.slice(0),a=new Uint32Array(r.buffer),i=Qa.quantize.getKDtree(r,t),l=i[0],o=i[1];Qa.quantize.planeDst;for(var c=n,d=a,u=c.length,h=new Uint8Array(n.length>>2),m=0;m>2]=v.ind,d[m>>2]=v.est.rgba}return{abuf:r.buffer,inds:h,plte:o}};Qa.quantize.getKDtree=function(s,t,n){n==null&&(n=1e-4);var r=new Uint32Array(s.buffer),a={i0:0,i1:s.length,bst:null,est:null,tdst:0,left:null,right:null};a.bst=Qa.quantize.stats(s,a.i0,a.i1),a.est=Qa.quantize.estats(a.bst);for(var i=[a];i.lengthl&&(l=i[c].est.L,o=c);if(l=u||d.i1<=u;if(h){d.est.L=0;continue}var m={i0:d.i0,i1:u,bst:null,est:null,tdst:0,left:null,right:null};m.bst=Qa.quantize.stats(s,m.i0,m.i1),m.est=Qa.quantize.estats(m.bst);var f={i0:u,i1:d.i1,bst:null,est:null,tdst:0,left:null,right:null};f.bst={R:[],m:[],N:d.bst.N-m.bst.N};for(var c=0;c<16;c++)f.bst.R[c]=d.bst.R[c]-m.bst.R[c];for(var c=0;c<4;c++)f.bst.m[c]=d.bst.m[c]-m.bst.m[c];f.est=Qa.quantize.estats(f.bst),d.left=m,d.right=f,i[o]=m,i.push(f)}i.sort(function(g,x){return x.bst.N-g.bst.N});for(var c=0;c0&&(l=s.right,o=s.left);var c=Qa.quantize.getNearest(l,t,n,r,a);if(c.tdst<=i*i)return c;var d=Qa.quantize.getNearest(o,t,n,r,a);return d.tdsti;)r-=4;if(n>=r)break;var o=t[n>>2];t[n>>2]=t[r>>2],t[r>>2]=o,n+=4,r-=4}for(;l(s,n,a)>i;)n-=4;return n+4};Qa.quantize.vecDot=function(s,t,n){return s[t]*n[0]+s[t+1]*n[1]+s[t+2]*n[2]+s[t+3]*n[3]};Qa.quantize.stats=function(s,t,n){for(var r=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],a=[0,0,0,0],i=n-t>>2,l=t;l>>0}};Qa.M4={multVec:function(s,t){return[s[0]*t[0]+s[1]*t[1]+s[2]*t[2]+s[3]*t[3],s[4]*t[0]+s[5]*t[1]+s[6]*t[2]+s[7]*t[3],s[8]*t[0]+s[9]*t[1]+s[10]*t[2]+s[11]*t[3],s[12]*t[0]+s[13]*t[1]+s[14]*t[2]+s[15]*t[3]]},dot:function(s,t){return s[0]*t[0]+s[1]*t[1]+s[2]*t[2]+s[3]*t[3]},sml:function(s,t){return[s*t[0],s*t[1],s*t[2],s*t[3]]}};Qa.encode.concatRGBA=function(s){for(var t=0,n=0;n1)throw new Error("Animated PNGs are not supported");var a=new Uint8Array(r[0]),i=zsr(a),l=i.rgbChannel,o=i.alphaChannel;this.rgbChannel=l;var c=o.some(function(d){return d<255});c&&(this.alphaChannel=o),this.type=Osr(n.ctype),this.width=n.width,this.height=n.height,this.bitsPerComponent=8}return s.load=function(t){return new s(t)},s}(),mis=function(){function s(t){this.image=t,this.bitsPerComponent=t.bitsPerComponent,this.width=t.width,this.height=t.height,this.colorSpace="DeviceRGB"}return s.for=function(t){return gd(this,void 0,void 0,function(){var n;return xd(this,function(r){return n=Bsr.load(t),[2,new s(n)]})})},s.prototype.embedIntoContext=function(t,n){return gd(this,void 0,void 0,function(){var r,a;return xd(this,function(i){return r=this.embedAlphaChannel(t),a=t.flateStream(this.image.rgbChannel,{Type:"XObject",Subtype:"Image",BitsPerComponent:this.image.bitsPerComponent,Width:this.image.width,Height:this.image.height,ColorSpace:this.colorSpace,SMask:r}),n?(t.assign(n,a),[2,n]):[2,t.register(a)]})})},s.prototype.embedAlphaChannel=function(t){if(this.image.alphaChannel){var n=t.flateStream(this.image.alphaChannel,{Type:"XObject",Subtype:"Image",Height:this.image.height,Width:this.image.width,BitsPerComponent:this.image.bitsPerComponent,ColorSpace:"DeviceGray",Decode:[0,1]});return t.register(n)}},s}(),fis=function(){function s(t,n,r){this.bytes=t,this.start=n||0,this.pos=this.start,this.end=n&&r?n+r:this.bytes.length}return Object.defineProperty(s.prototype,"length",{get:function(){return this.end-this.start},enumerable:!1,configurable:!0}),Object.defineProperty(s.prototype,"isEmpty",{get:function(){return this.length===0},enumerable:!1,configurable:!0}),s.prototype.getByte=function(){return this.pos>=this.end?-1:this.bytes[this.pos++]},s.prototype.getUint16=function(){var t=this.getByte(),n=this.getByte();return t===-1||n===-1?-1:(t<<8)+n},s.prototype.getInt32=function(){var t=this.getByte(),n=this.getByte(),r=this.getByte(),a=this.getByte();return(t<<24)+(n<<16)+(r<<8)+a},s.prototype.getBytes=function(t,n){n===void 0&&(n=!1);var r=this.bytes,a=this.pos,i=this.end;if(t){var o=a+t;o>i&&(o=i),this.pos=o;var l=r.subarray(a,o);return n?new Uint8ClampedArray(l):l}else{var l=r.subarray(a,i);return n?new Uint8ClampedArray(l):l}},s.prototype.peekByte=function(){var t=this.getByte();return this.pos--,t},s.prototype.peekBytes=function(t,n){n===void 0&&(n=!1);var r=this.getBytes(t,n);return this.pos-=r.length,r},s.prototype.skip=function(t){t||(t=1),this.pos+=t},s.prototype.reset=function(){this.pos=this.start},s.prototype.moveStart=function(){this.start=this.pos},s.prototype.makeSubStream=function(t,n){return new s(this.bytes,t,n)},s.prototype.decode=function(){return this.bytes},s}(),$sr=new Uint8Array(0),ooe=function(){function s(t){if(this.pos=0,this.bufferLength=0,this.eof=!1,this.buffer=$sr,this.minBufferLength=512,t)for(;this.minBufferLengthi&&(r=i)}else{for(;!this.eof;)this.readBlock();r=this.bufferLength}this.pos=r;var l=this.buffer.subarray(a,r);return n&&!(l instanceof Uint8ClampedArray)?new Uint8ClampedArray(l):l},s.prototype.peekByte=function(){var t=this.getByte();return this.pos--,t},s.prototype.peekBytes=function(t,n){n===void 0&&(n=!1);var r=this.getBytes(t,n);return this.pos-=r.length,r},s.prototype.skip=function(t){t||(t=1),this.pos+=t},s.prototype.reset=function(){this.pos=0},s.prototype.makeSubStream=function(t,n){for(var r=t+n;this.bufferLength<=r&&!this.eof;)this.readBlock();return new fis(this.buffer,t,n)},s.prototype.decode=function(){for(;!this.eof;)this.readBlock();return this.buffer.subarray(0,this.bufferLength)},s.prototype.readBlock=function(){throw new ZN(this.constructor.name,"readBlock")},s.prototype.ensureBuffer=function(t){var n=this.buffer;if(t<=n.byteLength)return n;for(var r=this.minBufferLength;r=0;--d)c[o+d]=h&255,h>>=8}},t}(ooe),qsr=function(s){Si(t,s);function t(n,r){var a=s.call(this,r)||this;return a.stream=n,a.firstDigit=-1,r&&(r=.5*r),a}return t.prototype.readBlock=function(){var n=8e3,r=this.stream.getBytes(n);if(!r.length){this.eof=!0;return}for(var a=r.length+1>>1,i=this.ensureBuffer(this.bufferLength+a),l=this.bufferLength,o=this.firstDigit,c=0,d=r.length;c=48&&u<=57)h=u&15;else if(u>=65&&u<=70||u>=97&&u<=102)h=(u&15)+9;else if(u===62){this.eof=!0;break}else continue;o<0?o=h:(i[l++]=o<<4|h,o=-1)}o>=0&&this.eof&&(i[l++]=o<<4,o=-1),this.firstDigit=o,this.bufferLength=l},t}(ooe),OAt=new Int32Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),Vsr=new Int32Array([3,4,5,6,7,8,9,10,65547,65549,65551,65553,131091,131095,131099,131103,196643,196651,196659,196667,262211,262227,262243,262259,327811,327843,327875,327907,258,258,258]),Hsr=new Int32Array([1,2,3,4,65541,65543,131081,131085,196625,196633,262177,262193,327745,327777,393345,393409,459009,459137,524801,525057,590849,591361,657409,658433,724993,727041,794625,798721,868353,876545]),Gsr=[new Int32Array([459008,524368,524304,524568,459024,524400,524336,590016,459016,524384,524320,589984,524288,524416,524352,590048,459012,524376,524312,589968,459028,524408,524344,590032,459020,524392,524328,59e4,524296,524424,524360,590064,459010,524372,524308,524572,459026,524404,524340,590024,459018,524388,524324,589992,524292,524420,524356,590056,459014,524380,524316,589976,459030,524412,524348,590040,459022,524396,524332,590008,524300,524428,524364,590072,459009,524370,524306,524570,459025,524402,524338,590020,459017,524386,524322,589988,524290,524418,524354,590052,459013,524378,524314,589972,459029,524410,524346,590036,459021,524394,524330,590004,524298,524426,524362,590068,459011,524374,524310,524574,459027,524406,524342,590028,459019,524390,524326,589996,524294,524422,524358,590060,459015,524382,524318,589980,459031,524414,524350,590044,459023,524398,524334,590012,524302,524430,524366,590076,459008,524369,524305,524569,459024,524401,524337,590018,459016,524385,524321,589986,524289,524417,524353,590050,459012,524377,524313,589970,459028,524409,524345,590034,459020,524393,524329,590002,524297,524425,524361,590066,459010,524373,524309,524573,459026,524405,524341,590026,459018,524389,524325,589994,524293,524421,524357,590058,459014,524381,524317,589978,459030,524413,524349,590042,459022,524397,524333,590010,524301,524429,524365,590074,459009,524371,524307,524571,459025,524403,524339,590022,459017,524387,524323,589990,524291,524419,524355,590054,459013,524379,524315,589974,459029,524411,524347,590038,459021,524395,524331,590006,524299,524427,524363,590070,459011,524375,524311,524575,459027,524407,524343,590030,459019,524391,524327,589998,524295,524423,524359,590062,459015,524383,524319,589982,459031,524415,524351,590046,459023,524399,524335,590014,524303,524431,524367,590078,459008,524368,524304,524568,459024,524400,524336,590017,459016,524384,524320,589985,524288,524416,524352,590049,459012,524376,524312,589969,459028,524408,524344,590033,459020,524392,524328,590001,524296,524424,524360,590065,459010,524372,524308,524572,459026,524404,524340,590025,459018,524388,524324,589993,524292,524420,524356,590057,459014,524380,524316,589977,459030,524412,524348,590041,459022,524396,524332,590009,524300,524428,524364,590073,459009,524370,524306,524570,459025,524402,524338,590021,459017,524386,524322,589989,524290,524418,524354,590053,459013,524378,524314,589973,459029,524410,524346,590037,459021,524394,524330,590005,524298,524426,524362,590069,459011,524374,524310,524574,459027,524406,524342,590029,459019,524390,524326,589997,524294,524422,524358,590061,459015,524382,524318,589981,459031,524414,524350,590045,459023,524398,524334,590013,524302,524430,524366,590077,459008,524369,524305,524569,459024,524401,524337,590019,459016,524385,524321,589987,524289,524417,524353,590051,459012,524377,524313,589971,459028,524409,524345,590035,459020,524393,524329,590003,524297,524425,524361,590067,459010,524373,524309,524573,459026,524405,524341,590027,459018,524389,524325,589995,524293,524421,524357,590059,459014,524381,524317,589979,459030,524413,524349,590043,459022,524397,524333,590011,524301,524429,524365,590075,459009,524371,524307,524571,459025,524403,524339,590023,459017,524387,524323,589991,524291,524419,524355,590055,459013,524379,524315,589975,459029,524411,524347,590039,459021,524395,524331,590007,524299,524427,524363,590071,459011,524375,524311,524575,459027,524407,524343,590031,459019,524391,524327,589999,524295,524423,524359,590063,459015,524383,524319,589983,459031,524415,524351,590047,459023,524399,524335,590015,524303,524431,524367,590079]),9],Wsr=[new Int32Array([327680,327696,327688,327704,327684,327700,327692,327708,327682,327698,327690,327706,327686,327702,327694,0,327681,327697,327689,327705,327685,327701,327693,327709,327683,327699,327691,327707,327687,327703,327695,0]),5],Ksr=function(s){Si(t,s);function t(n,r){var a=s.call(this,r)||this;a.stream=n;var i=n.getByte(),l=n.getByte();if(i===-1||l===-1)throw new Error("Invalid header in flate stream: "+i+", "+l);if((i&15)!==8)throw new Error("Unknown compression method in flate stream: "+i+", "+l);if(((i<<8)+l)%31!==0)throw new Error("Bad FCHECK in flate stream: "+i+", "+l);if(l&32)throw new Error("FDICT bit set in flate stream: "+i+", "+l);return a.codeSize=0,a.codeBuf=0,a}return t.prototype.readBlock=function(){var n,r,a=this.stream,i=this.getBits(3);if(i&1&&(this.eof=!0),i>>=1,i===0){var l=void 0;if((l=a.getByte())===-1)throw new Error("Bad block header in flate stream");var o=l;if((l=a.getByte())===-1)throw new Error("Bad block header in flate stream");if(o|=l<<8,(l=a.getByte())===-1)throw new Error("Bad block header in flate stream");var c=l;if((l=a.getByte())===-1)throw new Error("Bad block header in flate stream");if(c|=l<<8,c!==(~o&65535)&&(o!==0||c!==0))throw new Error("Bad uncompressed block length in flate stream");this.codeBuf=0,this.codeSize=0;var d=this.bufferLength;n=this.ensureBuffer(d+o);var u=d+o;if(this.bufferLength=u,o===0)a.peekByte()===-1&&(this.eof=!0);else for(var h=d;h0;)C[b++]=P}m=this.generateHuffmanTable(C.subarray(0,g)),f=this.generateHuffmanTable(C.subarray(g,S))}else throw new Error("Unknown block type in flate stream");n=this.buffer;for(var O=n?n.length:0,U=this.bufferLength;;){var W=this.getCode(m);if(W<256){U+1>=O&&(n=this.ensureBuffer(U+1),O=n.length),n[U++]=W;continue}if(W===256){this.bufferLength=U;return}W-=257,W=Vsr[W];var V=W>>16;V>0&&(V=this.getBits(V)),r=(W&65535)+V,W=this.getCode(f),W=Hsr[W],V=W>>16,V>0&&(V=this.getBits(V));var G=(W&65535)+V;U+r>=O&&(n=this.ensureBuffer(U+r),O=n.length);for(var Y=0;Y>n,this.codeSize=a-=n,l},t.prototype.getCode=function(n){for(var r=this.stream,a=n[0],i=n[1],l=this.codeSize,o=this.codeBuf,c;l>16,h=d&65535;if(u<1||l>u,this.codeSize=l-u,h},t.prototype.generateHuffmanTable=function(n){var r=n.length,a=0,i;for(i=0;ia&&(a=n[i]);for(var l=1<>=1;for(i=m;i0;if(!C||C<256)y[0]=C,v=1;else if(C>=258)if(C=0;l--)y[l]=h[o],o=f[o];else y[v++]=y[0];else if(C===256){g=9,u=258,v=0;continue}else{this.eof=!0,delete this.lzwState;break}if(E&&(f[u]=x,m[u]=m[x]+1,h[u]=y[0],u++,g=u+d&u+d-1?g:Math.min(Math.log(u+d)/.6931471805599453+1,12)|0),x=C,b+=v,r>>r&(1<0){var l=this.stream.getBytes(i);r.set(l,a),a+=i}}else{i=257-i;var o=n[1];r=this.ensureBuffer(a+i+1);for(var c=0;cr.size())throw new EPe(n,0,r.size());r.remove(n)}else{if(n!==0)throw new EPe(n,0,0);this.setKids([])}},t.prototype.normalizedEntries=function(){var n=this.Kids();return n||(n=this.dict.context.obj([this.ref]),this.dict.set(sn.of("Kids"),n)),{Kids:n}},t.fromDict=function(n,r){return new t(n,r)},t}(xis),plt=function(s){Si(t,s);function t(){return s!==null&&s.apply(this,arguments)||this}return t.prototype.Opt=function(){return this.dict.lookupMaybe(sn.of("Opt"),rm,lc,Nh)},t.prototype.setOpt=function(n){this.dict.set(sn.of("Opt"),this.dict.context.obj(n))},t.prototype.getExportValues=function(){var n=this.Opt();if(n){if(n instanceof rm||n instanceof lc)return[n];for(var r=[],a=0,i=n.size();ar.size())throw new EPe(n,0,r.size());r.remove(n)}},t.prototype.normalizeExportValues=function(){for(var n,r,a,i,l=(n=this.getExportValues())!==null&&n!==void 0?n:[],o=[],c=this.getWidgets(),d=0,u=c.length;d1){if(!this.hasFlag(tm.MultiSelect))throw new dsr;this.dict.set(sn.of("V"),this.dict.context.obj(n))}this.updateSelectedIndices(n)},t.prototype.valuesAreValid=function(n){for(var r=this.getOptions(),a=function(c,d){var u=n[c].decodeText();if(!r.find(function(h){return u===(h.display||h.value).decodeText()}))return{value:!1}},i=0,l=n.length;i1){for(var r=new Array(n.length),a=this.getOptions(),i=function(c,d){var u=n[c].decodeText();r[c]=a.findIndex(function(h){return u===(h.display||h.value).decodeText()})},l=0,o=n.length;l0){var o=l.lookup(0,rm,lc),c=l.lookupMaybe(1,rm,lc);r.push({value:o,display:c||o})}}return r}return[]},t}(lY),tFe=function(s){Si(t,s);function t(){return s!==null&&s.apply(this,arguments)||this}return t.fromDict=function(n,r){return new t(n,r)},t.create=function(n){var r=n.obj({FT:"Ch",Ff:tm.Combo,Kids:[]}),a=n.register(r);return new t(r,a)},t}(yis),PPe=function(s){Si(t,s);function t(){return s!==null&&s.apply(this,arguments)||this}return t.prototype.addField=function(n){var r=this.normalizedEntries().Kids;r==null||r.push(n)},t.prototype.normalizedEntries=function(){var n=this.Kids();return n||(n=this.dict.context.obj([]),this.dict.set(sn.of("Kids"),n)),{Kids:n}},t.fromDict=function(n,r){return new t(n,r)},t.create=function(n){var r=n.obj({}),a=n.register(r);return new t(r,a)},t}(xis),glt=function(s){Si(t,s);function t(){return s!==null&&s.apply(this,arguments)||this}return t.fromDict=function(n,r){return new t(n,r)},t}(lY),sFe=function(s){Si(t,s);function t(){return s!==null&&s.apply(this,arguments)||this}return t.prototype.MaxLen=function(){var n=this.dict.lookup(sn.of("MaxLen"));if(n instanceof Ec)return n},t.prototype.Q=function(){var n=this.dict.lookup(sn.of("Q"));if(n instanceof Ec)return n},t.prototype.setMaxLength=function(n){this.dict.set(sn.of("MaxLen"),Ec.of(n))},t.prototype.removeMaxLength=function(){this.dict.delete(sn.of("MaxLen"))},t.prototype.getMaxLength=function(){var n;return(n=this.MaxLen())===null||n===void 0?void 0:n.asNumber()},t.prototype.setQuadding=function(n){this.dict.set(sn.of("Q"),Ec.of(n))},t.prototype.getQuadding=function(){var n;return(n=this.Q())===null||n===void 0?void 0:n.asNumber()},t.prototype.setValue=function(n){this.dict.set(sn.of("V"),n)},t.prototype.removeValue=function(){this.dict.delete(sn.of("V"))},t.prototype.getValue=function(){var n=this.V();if(n instanceof rm||n instanceof lc)return n},t.fromDict=function(n,r){return new t(n,r)},t.create=function(n){var r=n.obj({FT:"Tx",Kids:[]}),a=n.register(r);return new t(r,a)},t}(lY),nFe=function(s){Si(t,s);function t(){return s!==null&&s.apply(this,arguments)||this}return t.fromDict=function(n,r){return new t(n,r)},t.create=function(n){var r=n.obj({FT:"Btn",Ff:DN.PushButton,Kids:[]}),a=n.register(r);return new t(r,a)},t}(plt),rFe=function(s){Si(t,s);function t(){return s!==null&&s.apply(this,arguments)||this}return t.prototype.setValue=function(n){var r=this.getOnValues();if(!r.includes(n)&&n!==sn.of("Off"))throw new dlt;this.dict.set(sn.of("V"),n);for(var a=this.getWidgets(),i=0,l=a.length;ii)throw new CAt(r,i);for(var l=r,o=0,c=a.size();ol)return u.insertLeafNode(n,l)||d;l-=u.Count().asNumber()}u instanceof QE&&(l-=1)}if(l===0){this.insertLeafKid(a.size(),n);return}throw new AAt(r,"insertLeafNode")},t.prototype.removeLeafNode=function(n,r){r===void 0&&(r=!0);var a=this.Kids(),i=this.Count().asNumber();if(n>=i)throw new CAt(n,i);for(var l=n,o=0,c=a.size();ol){u.removeLeafNode(l,r),r&&u.Kids().size()===0&&a.remove(o);return}else l-=u.Count().asNumber();if(u instanceof QE)if(l===0){this.removeKid(o);return}else l-=1}throw new AAt(n,"removeLeafNode")},t.prototype.ascend=function(n){n(this);var r=this.Parent();r&&r.ascend(n)},t.prototype.traverse=function(n){for(var r=this.Kids(),a=0,i=r.size();aNumber.MAX_SAFE_INTEGER)if(this.capNumbers){var a="Parsed number that is too large for some PDF readers: "+t+", using Number.MAX_SAFE_INTEGER instead.";return console.warn(a),Number.MAX_SAFE_INTEGER}else{var a="Parsed number that is too large for some PDF readers: "+t+", not capping.";console.warn(a)}return r},s.prototype.skipWhitespace=function(){for(;!this.bytes.done()&&UT[this.bytes.peek()];)this.bytes.next()},s.prototype.skipLine=function(){for(;!this.bytes.done();){var t=this.bytes.peek();if(t===$At||t===UAt)return;this.bytes.next()}},s.prototype.skipComment=function(){if(this.bytes.peek()!==un.Percent)return!1;for(;!this.bytes.done();){var t=this.bytes.peek();if(t===$At||t===UAt)return!0;this.bytes.next()}return!0},s.prototype.skipWhitespaceAndComments=function(){for(this.skipWhitespace();this.skipComment();)this.skipWhitespace()},s.prototype.matchKeyword=function(t){for(var n=this.bytes.offset(),r=0,a=t.length;r=this.length},s.prototype.offset=function(){return this.idx},s.prototype.slice=function(t,n){return this.bytes.slice(t,n)},s.prototype.position=function(){return{line:this.line,column:this.column,offset:this.idx}},s.of=function(t){return new s(t)},s.fromPDFRawStream=function(t){return s.of(pis(t).decode())},s}(),onr=un.Space,jX=un.CarriageReturn,NX=un.Newline,kX=[un.s,un.t,un.r,un.e,un.a,un.m],Zue=[un.e,un.n,un.d,un.s,un.t,un.r,un.e,un.a,un.m],Wm={header:[un.Percent,un.P,un.D,un.F,un.Dash],eof:[un.Percent,un.Percent,un.E,un.O,un.F],obj:[un.o,un.b,un.j],endobj:[un.e,un.n,un.d,un.o,un.b,un.j],xref:[un.x,un.r,un.e,un.f],trailer:[un.t,un.r,un.a,un.i,un.l,un.e,un.r],startxref:[un.s,un.t,un.a,un.r,un.t,un.x,un.r,un.e,un.f],true:[un.t,un.r,un.u,un.e],false:[un.f,un.a,un.l,un.s,un.e],null:[un.n,un.u,un.l,un.l],stream:kX,streamEOF1:eh(kX,[onr,jX,NX]),streamEOF2:eh(kX,[jX,NX]),streamEOF3:eh(kX,[jX]),streamEOF4:eh(kX,[NX]),endstream:Zue,EOF1endstream:eh([jX,NX],Zue),EOF2endstream:eh([jX],Zue),EOF3endstream:eh([NX],Zue)},jis=function(s){Si(t,s);function t(n,r,a){a===void 0&&(a=!1);var i=s.call(this,n,a)||this;return i.context=r,i}return t.prototype.parseObject=function(){if(this.skipWhitespaceAndComments(),this.matchKeyword(Wm.true))return Tne.True;if(this.matchKeyword(Wm.false))return Tne.False;if(this.matchKeyword(Wm.null))return vw;var n=this.bytes.peek();if(n===un.LessThan&&this.bytes.peekAhead(1)===un.LessThan)return this.parseDictOrStream();if(n===un.LessThan)return this.parseHexString();if(n===un.LeftParen)return this.parseString();if(n===un.ForwardSlash)return this.parseName();if(n===un.LeftSquareBracket)return this.parseArray();if(vlt[n])return this.parseNumberOrRef();throw new fsr(this.bytes.position(),n)},t.prototype.parseNumberOrRef=function(){var n=this.parseRawNumber();this.skipWhitespaceAndComments();var r=this.bytes.offset();if(M1[this.bytes.peek()]){var a=this.parseRawNumber();if(this.skipWhitespaceAndComments(),this.bytes.peek()===un.R)return this.bytes.assertNext(un.R),am.of(n,a)}return this.bytes.moveTo(r),Ec.of(n)},t.prototype.parseHexString=function(){var n="";for(this.bytes.assertNext(un.LessThan);!this.bytes.done()&&this.bytes.peek()!==un.GreaterThan;)n+=ZE(this.bytes.next());return this.bytes.assertNext(un.GreaterThan),lc.of(n)},t.prototype.parseString=function(){for(var n=0,r=!1,a="";!this.bytes.done();){var i=this.bytes.next();if(a+=ZE(i),r||(i===un.LeftParen&&(n+=1),i===un.RightParen&&(n-=1)),i===un.BackSlash?r=!r:r&&(r=!1),n===0)return rm.of(a.substring(1,a.length-1))}throw new xsr(this.bytes.position())},t.prototype.parseName=function(){this.bytes.assertNext(un.ForwardSlash);for(var n="";!this.bytes.done();){var r=this.bytes.peek();if(UT[r]||Lk[r])break;n+=ZE(r),this.bytes.next()}return sn.of(n)},t.prototype.parseArray=function(){this.bytes.assertNext(un.LeftSquareBracket),this.skipWhitespaceAndComments();for(var n=Nh.withContext(this.context);this.bytes.peek()!==un.RightSquareBracket;){var r=this.parseObject();n.push(r),this.skipWhitespaceAndComments()}return this.bytes.assertNext(un.RightSquareBracket),n},t.prototype.parseDict=function(){this.bytes.assertNext(un.LessThan),this.bytes.assertNext(un.LessThan),this.skipWhitespaceAndComments();for(var n=new Map;!this.bytes.done()&&this.bytes.peek()!==un.GreaterThan&&this.bytes.peekAhead(1)!==un.GreaterThan;){var r=this.parseName(),a=this.parseObject();n.set(r,a),this.skipWhitespaceAndComments()}this.skipWhitespaceAndComments(),this.bytes.assertNext(un.GreaterThan),this.bytes.assertNext(un.GreaterThan);var i=n.get(sn.of("Type"));return i===sn.of("Catalog")?_is.fromMapWithContext(n,this.context):i===sn.of("Pages")?wis.fromMapWithContext(n,this.context):i===sn.of("Page")?QE.fromMapWithContext(n,this.context):dd.fromMapWithContext(n,this.context)},t.prototype.parseDictOrStream=function(){var n=this.bytes.position(),r=this.parseDict();if(this.skipWhitespaceAndComments(),!this.matchKeyword(Wm.streamEOF1)&&!this.matchKeyword(Wm.streamEOF2)&&!this.matchKeyword(Wm.streamEOF3)&&!this.matchKeyword(Wm.streamEOF4)&&!this.matchKeyword(Wm.stream))return r;var a=this.bytes.offset(),i,l=r.get(sn.of("Length"));l instanceof Ec?(i=a+l.asNumber(),this.bytes.moveTo(i),this.skipWhitespaceAndComments(),this.matchKeyword(Wm.endstream)||(this.bytes.moveTo(a),i=this.findEndOfStreamFallback(n))):i=this.findEndOfStreamFallback(n);var o=this.bytes.slice(a,i);return Mne.of(r,o)},t.prototype.findEndOfStreamFallback=function(n){for(var r=1,a=this.bytes.offset();!this.bytes.done()&&(a=this.bytes.offset(),this.matchKeyword(Wm.stream)?r+=1:this.matchKeyword(Wm.EOF1endstream)||this.matchKeyword(Wm.EOF2endstream)||this.matchKeyword(Wm.EOF3endstream)||this.matchKeyword(Wm.endstream)?r-=1:this.bytes.next(),r!==0););if(r!==0)throw new gsr(n);return a},t.forBytes=function(n,r,a){return new t(oFe.of(n),r,a)},t.forByteStream=function(n,r,a){return a===void 0&&(a=!1),new t(n,r,a)},t}(inr),lnr=function(s){Si(t,s);function t(n,r){var a=s.call(this,oFe.fromPDFRawStream(n),n.dict.context)||this,i=n.dict;return a.alreadyParsed=!1,a.shouldWaitForTick=r||function(){return!1},a.firstOffset=i.lookup(sn.of("First"),Ec).asNumber(),a.objectCount=i.lookup(sn.of("N"),Ec).asNumber(),a}return t.prototype.parseIntoContext=function(){return gd(this,void 0,void 0,function(){var n,r,a,i,l,o,c,d;return xd(this,function(u){switch(u.label){case 0:if(this.alreadyParsed)throw new clt("PDFObjectStreamParser","parseIntoContext");this.alreadyParsed=!0,n=this.parseOffsetsAndObjectNumbers(),r=0,a=n.length,u.label=1;case 1:return r=un.Space&&r<=un.Tilde;if(a&&(this.matchKeyword(Wm.xref)||this.matchKeyword(Wm.trailer)||this.matchKeyword(Wm.startxref)||this.matchIndirectObjectHeader())){this.bytes.moveTo(n);break}this.bytes.next()}},t.prototype.skipBinaryHeaderComment=function(){this.skipWhitespaceAndComments();try{var n=this.bytes.offset();this.parseIndirectObjectHeader(),this.bytes.moveTo(n)}catch{this.bytes.next(),this.skipWhitespaceAndComments()}},t.forBytesWithOptions=function(n,r,a,i){return new t(n,r,a,i)},t}(jis),u5=function(s){return 1<0&&(r[r.length]=+a),n[n.length]={cmd:t,args:r},r=[],a="",i=!1),t=d;else if([" ",","].includes(d)||d==="-"&&a.length>0&&a[a.length-1]!=="e"||d==="."&&i){if(a.length===0)continue;r.length===l?(n[n.length]={cmd:t,args:r},r=[+a],t==="M"&&(t="L"),t==="m"&&(t="l")):r[r.length]=+a,i=d===".",a=["-","."].includes(d)?d:""}else a+=d,d==="."&&(i=!0)}return a.length>0&&(r.length===l?(n[n.length]={cmd:t,args:r},r=[+a],t==="M"&&(t="L"),t==="m"&&(t="l")):r[r.length]=+a),n[n.length]={cmd:t,args:r},n},jnr=function(s){al=il=Lu=Ru=KQ=YQ=0;for(var t=[],n=0;n1&&(m=Math.sqrt(m),n*=m,r*=m);var f=h/n,g=u/n,x=-u/r,y=h/r,v=f*o+g*c,b=x*o+y*c,w=f*s+g*t,S=x*s+y*t,C=(w-v)*(w-v)+(S-b)*(S-b),E=1/C-.25;E<0&&(E=0);var I=Math.sqrt(E);i===a&&(I=-I);var P=.5*(v+w)-I*(S-b),R=.5*(b+S)+I*(w-v),D=Math.atan2(b-R,v-P),O=Math.atan2(S-R,w-P),U=O-D;U<0&&i===1?U+=2*Math.PI:U>0&&i===0&&(U-=2*Math.PI);for(var W=Math.ceil(Math.abs(U/(Math.PI*.5+.001))),V=[],G=0;Gs.length)return a-1;var y=t.heightAtSize(a),v=y+y*.2,b=v*i;if(b>Math.abs(n.height))return a-1;a+=1}return a},Hnr=function(s,t,n,r){for(var a=n.width/r,i=n.height,l=$is,o=bJn(s);la*.75;if(h)return l-1}var m=t.heightAtSize(l,{descender:!1});if(m>i)return l-1;l+=1}return l},Gnr=function(s){for(var t=s.length;t>0;t--)if(/\s/.test(s[t]))return t},Wnr=function(s,t,n,r){for(var a,i=s.length;i>0;){var l=s.substring(0,i),o=n.encodeText(l),c=n.widthOfTextAtSize(l,r);if(cm&&(m=I+C),g+o>f&&(f=g+o),d.push({text:w,encoded:S,width:C,height:o,x:I,y:g}),v=E==null?void 0:E.trim()}return{fontSize:r,lineHeight:c,lines:d,bounds:{x:u,y:h,width:m-u,height:f-h}}},Knr=function(s,t){var n=t.fontSize,r=t.font,a=t.bounds,i=t.cellCount,l=ias(toe(s));if(l.length>i)throw new Unr(l.length,i);(n===void 0||n===0)&&(n=Hnr(l,r,a,i));for(var o=a.width/i,c=r.heightAtSize(n,{descender:!1}),d=a.y+(a.height/2-c/2),u=[],h=a.x,m=a.y,f=a.x+a.width,g=a.y+a.height,x=0,y=0;xf&&(f=I+C),d+c>g&&(g=d+c),u.push({text:l,encoded:S,width:C,height:c,x:I,y:d}),x+=1,y+=w}return{fontSize:n,cells:u,bounds:{x:h,y:m,width:f-h,height:g-m}}},OPe=function(s,t){var n=t.alignment,r=t.fontSize,a=t.font,i=t.bounds,l=ias(toe(s));(r===void 0||r===0)&&(r=qis([l],a,i));var o=a.encodeText(l),c=a.widthOfTextAtSize(l,r),d=a.heightAtSize(r,{descender:!1}),u=n===y0.Left?i.x:n===y0.Center?i.x+i.width/2-c/2:n===y0.Right?i.x+i.width-c:i.x,h=i.y+(i.height/2-d/2);return{fontSize:r,line:{text:l,encoded:o,width:c,height:d,x:u,y:h},bounds:{x:u,y:h,width:c,height:d}}},dY=function(s){return"normal"in s?s:{normal:s}},Ynr=/\/([^\0\t\n\f\r\ ]+)[\0\t\n\f\r\ ]+(\d*\.\d+|\d+)[\0\t\n\f\r\ ]+Tf/,KL=function(s){var t,n,r=(t=s.getDefaultAppearance())!==null&&t!==void 0?t:"",a=(n=elt(r,Ynr).match)!==null&&n!==void 0?n:[],i=Number(a[2]);return isFinite(i)?i:void 0},Znr=/(\d*\.\d+|\d+)[\0\t\n\f\r\ ]*(\d*\.\d+|\d+)?[\0\t\n\f\r\ ]*(\d*\.\d+|\d+)?[\0\t\n\f\r\ ]*(\d*\.\d+|\d+)?[\0\t\n\f\r\ ]+(g|rg|k)/,bk=function(s){var t,n=(t=s.getDefaultAppearance())!==null&&t!==void 0?t:"",r=elt(n,Znr).match,a=r??[],i=a[1],l=a[2],o=a[3],c=a[4],d=a[5];if(d==="g"&&i)return Dis(Number(i));if(d==="rg"&&i&&l&&o)return Ah(Number(i),Number(l),Number(o));if(d==="k"&&i&&l&&o&&c)return Fis(Number(i),Number(l),Number(o),Number(c))},_k=function(s,t,n,r){var a;r===void 0&&(r=0);var i=[N9(t).toString(),jlt((a=n==null?void 0:n.name)!==null&&a!==void 0?a:"dummy__noop",r).toString()].join(` `);s.setDefaultAppearance(i)},Xnr=function(s,t){var n,r,a,i=bk(t),l=bk(s.acroField),o=t.getRectangle(),c=t.getAppearanceCharacteristics(),d=t.getBorderStyle(),u=(n=d==null?void 0:d.getWidth())!==null&&n!==void 0?n:0,h=qT(c==null?void 0:c.getRotation()),m=w9(o,h),f=m.width,g=m.height,x=O6(Vc(Vc({},o),{rotation:h})),y=Ah(0,0,0),v=(r=P_(c==null?void 0:c.getBorderColor()))!==null&&r!==void 0?r:y,b=P_(c==null?void 0:c.getBackgroundColor()),w=P_(c==null?void 0:c.getBackgroundColor(),.8),S=(a=i??l)!==null&&a!==void 0?a:y;_k(i?t:s.acroField,S);var C={x:0+u/2,y:0+u/2,width:f-u,height:g-u,thickness:1.5,borderWidth:u,borderColor:v,markColor:S};return{normal:{on:eh(x,Jue(Vc(Vc({},C),{color:b,filled:!0}))),off:eh(x,Jue(Vc(Vc({},C),{color:b,filled:!1})))},down:{on:eh(x,Jue(Vc(Vc({},C),{color:w,filled:!0}))),off:eh(x,Jue(Vc(Vc({},C),{color:w,filled:!1})))}}},Qnr=function(s,t){var n,r,a,i=bk(t),l=bk(s.acroField),o=t.getRectangle(),c=t.getAppearanceCharacteristics(),d=t.getBorderStyle(),u=(n=d==null?void 0:d.getWidth())!==null&&n!==void 0?n:0,h=qT(c==null?void 0:c.getRotation()),m=w9(o,h),f=m.width,g=m.height,x=O6(Vc(Vc({},o),{rotation:h})),y=Ah(0,0,0),v=(r=P_(c==null?void 0:c.getBorderColor()))!==null&&r!==void 0?r:y,b=P_(c==null?void 0:c.getBackgroundColor()),w=P_(c==null?void 0:c.getBackgroundColor(),.8),S=(a=i??l)!==null&&a!==void 0?a:y;_k(i?t:s.acroField,S);var C={x:f/2,y:g/2,width:f-u,height:g-u,borderWidth:u,borderColor:v,dotColor:S};return{normal:{on:eh(x,ehe(Vc(Vc({},C),{color:b,filled:!0}))),off:eh(x,ehe(Vc(Vc({},C),{color:b,filled:!1})))},down:{on:eh(x,ehe(Vc(Vc({},C),{color:w,filled:!0}))),off:eh(x,ehe(Vc(Vc({},C),{color:w,filled:!1})))}}},Jnr=function(s,t,n){var r,a,i,l,o,c=bk(t),d=bk(s.acroField),u=KL(t),h=KL(s.acroField),m=t.getRectangle(),f=t.getAppearanceCharacteristics(),g=t.getBorderStyle(),x=f==null?void 0:f.getCaptions(),y=(r=x==null?void 0:x.normal)!==null&&r!==void 0?r:"",v=(i=(a=x==null?void 0:x.down)!==null&&a!==void 0?a:y)!==null&&i!==void 0?i:"",b=(l=g==null?void 0:g.getWidth())!==null&&l!==void 0?l:0,w=qT(f==null?void 0:f.getRotation()),S=w9(m,w),C=S.width,E=S.height,I=O6(Vc(Vc({},m),{rotation:w})),P=Ah(0,0,0),R=P_(f==null?void 0:f.getBorderColor()),D=P_(f==null?void 0:f.getBackgroundColor()),O=P_(f==null?void 0:f.getBackgroundColor(),.8),U={x:b,y:b,width:C-b*2,height:E-b*2},W=OPe(y,{alignment:y0.Center,fontSize:u??h,font:n,bounds:U}),V=OPe(v,{alignment:y0.Center,fontSize:u??h,font:n,bounds:U}),G=Math.min(W.fontSize,V.fontSize),Y=(o=c??d)!==null&&o!==void 0?o:P;_k(c||u!==void 0?t:s.acroField,Y,n,G);var X={x:0+b/2,y:0+b/2,width:C-b,height:E-b,borderWidth:b,borderColor:R,textColor:Y,font:n.name,fontSize:G};return{normal:eh(I,YAt(Vc(Vc({},X),{color:D,textLines:[W.line]}))),down:eh(I,YAt(Vc(Vc({},X),{color:O,textLines:[V.line]})))}},err=function(s,t,n){var r,a,i,l,o=bk(t),c=bk(s.acroField),d=KL(t),u=KL(s.acroField),h=t.getRectangle(),m=t.getAppearanceCharacteristics(),f=t.getBorderStyle(),g=(r=s.getText())!==null&&r!==void 0?r:"",x=(a=f==null?void 0:f.getWidth())!==null&&a!==void 0?a:0,y=qT(m==null?void 0:m.getRotation()),v=w9(h,y),b=v.width,w=v.height,S=O6(Vc(Vc({},h),{rotation:y})),C=Ah(0,0,0),E=P_(m==null?void 0:m.getBorderColor()),I=P_(m==null?void 0:m.getBackgroundColor()),P,R,D=s.isCombed()?0:1,O={x:x+D,y:x+D,width:b-(x+D)*2,height:w-(x+D)*2};if(s.isMultiline()){var U=Vis(g,{alignment:s.getAlignment(),fontSize:d??u,font:n,bounds:O});P=U.lines,R=U.fontSize}else if(s.isCombed()){var U=Knr(g,{fontSize:d??u,font:n,bounds:O,cellCount:(i=s.getMaxLength())!==null&&i!==void 0?i:0});P=U.cells,R=U.fontSize}else{var U=OPe(g,{alignment:s.getAlignment(),fontSize:d??u,font:n,bounds:O});P=[U.line],R=U.fontSize}var W=(l=o??c)!==null&&l!==void 0?l:C;_k(o||d!==void 0?t:s.acroField,W,n,R);var V={x:0+x/2,y:0+x/2,width:b-x,height:w-x,borderWidth:x??0,borderColor:E,textColor:W,font:n.name,fontSize:R,color:I,textLines:P,padding:D};return eh(S,zis(V))},trr=function(s,t,n){var r,a,i,l=bk(t),o=bk(s.acroField),c=KL(t),d=KL(s.acroField),u=t.getRectangle(),h=t.getAppearanceCharacteristics(),m=t.getBorderStyle(),f=(r=s.getSelected()[0])!==null&&r!==void 0?r:"",g=(a=m==null?void 0:m.getWidth())!==null&&a!==void 0?a:0,x=qT(h==null?void 0:h.getRotation()),y=w9(u,x),v=y.width,b=y.height,w=O6(Vc(Vc({},u),{rotation:x})),S=Ah(0,0,0),C=P_(h==null?void 0:h.getBorderColor()),E=P_(h==null?void 0:h.getBackgroundColor()),I=1,P={x:g+I,y:g+I,width:v-(g+I)*2,height:b-(g+I)*2},R=OPe(f,{alignment:y0.Left,fontSize:c??d,font:n,bounds:P}),D=R.line,O=R.fontSize,U=(i=l??o)!==null&&i!==void 0?i:S;_k(l||c!==void 0?t:s.acroField,U,n,O);var W={x:0+g/2,y:0+g/2,width:v-g,height:b-g,borderWidth:g??0,borderColor:C,textColor:U,font:n.name,fontSize:O,color:E,textLines:[D],padding:I};return eh(w,zis(W))},srr=function(s,t,n){var r,a,i=bk(t),l=bk(s.acroField),o=KL(t),c=KL(s.acroField),d=t.getRectangle(),u=t.getAppearanceCharacteristics(),h=t.getBorderStyle(),m=(r=h==null?void 0:h.getWidth())!==null&&r!==void 0?r:0,f=qT(u==null?void 0:u.getRotation()),g=w9(d,f),x=g.width,y=g.height,v=O6(Vc(Vc({},d),{rotation:f})),b=Ah(0,0,0),w=P_(u==null?void 0:u.getBorderColor()),S=P_(u==null?void 0:u.getBackgroundColor()),C=s.getOptions(),E=s.getSelected();s.isSorted()&&C.sort();for(var I="",P=0,R=C.length;P1||a.length===1&&r)&&this.enableMultiselect();for(var o=new Array(a.length),c=0,d=a.length;c1||a.length===1&&r)&&this.enableMultiselect();for(var l=new Array(a.length),o=0,c=a.length;or)throw new qnr(n.length,r,this.getName());this.markAsDirty(),this.disableRichFormatting(),n?this.acroField.setValue(lc.fromText(n)):this.acroField.removeValue()},t.prototype.getAlignment=function(){var n=this.acroField.getQuadding();return n===0?y0.Left:n===1?y0.Center:n===2?y0.Right:y0.Left},t.prototype.setAlignment=function(n){EI(n,"alignment",y0),this.markAsDirty(),this.acroField.setQuadding(n)},t.prototype.getMaxLength=function(){return this.acroField.getMaxLength()},t.prototype.setMaxLength=function(n){if(lS(n,"maxLength",0,Number.MAX_SAFE_INTEGER),this.markAsDirty(),n===void 0)this.acroField.removeMaxLength();else{var r=this.getText();if(r&&r.length>n)throw new Vnr(r.length,n,this.getName());this.acroField.setMaxLength(n)}},t.prototype.removeMaxLength=function(){this.markAsDirty(),this.acroField.removeMaxLength()},t.prototype.setImage=function(n){for(var r=this.getAlignment(),a=r===y0.Center?vL.Center:r===y0.Right?vL.Right:vL.Left,i=this.acroField.getWidgets(),l=0,o=i.length;l{let l=null;try{const o=i.acroField.getWidgets()[0],c=o==null?void 0:o.P();if(c){const d=n.findIndex(u=>u.ref===c);l=d>=0?d:null}}catch{l=null}return{name:i.getName(),type:Gis(i),page:l}})}catch{r=[]}return{pageCount:n.length,hasAcroform:r.length>0,fields:r}}function ZAt(s,t){return s.mapping_mode==="blank"?"":s.mapping_mode==="static"||!s.merge_key?s.static_value||"":t[s.merge_key]??""}async function Wis(s,t,n){const r=await n3.load(s,{updateMetadata:!1}),a=await r.embedFont(EW.Helvetica),i={},l=[],o=t.filter(u=>u.mapping_mode!=="overlay"&&u.pdf_field_name);if(o.length){const u=r.getForm();for(const h of o){const m=ZAt(h,n),f=h.pdf_field_name;if(!m){l.push(f);continue}try{const g=u.getField(f),x=Gis(g);if(x==="text")g.setText(m);else if(x==="checkbox")/^(true|yes|x|1|checked)$/i.test(m.trim())?g.check():g.uncheck();else if(x==="dropdown"||x==="optionlist")g.select(m);else if(x==="radio")g.select(m);else{l.push(f);continue}i[f]=m}catch{l.push(f)}}try{u.updateFieldAppearances(a)}catch{}try{u.flatten()}catch{}}const c=t.filter(u=>u.mapping_mode==="overlay"&&(u.field_kind==null||u.field_kind==="data"));if(c.length){const u=r.getPages();for(const h of c){const m=ZAt(h,n),f=h.pdf_field_name||h.merge_key||h.field_kind||"overlay",g=u[h.page_index??0];if(!m||!g||h.pos_x==null||h.pos_y==null){l.push(f);continue}const{width:x,height:y}=g.getSize(),v=!!h.coords_normalized,b=Number(h.pos_x)*(v?x:1),w=Number(h.width??(v?.2:120))*(v?x:1),S=Number(h.height??(v?.03:18))*(v?y:1),C=Number(h.pos_y)*(v?y:1),E=v?y-C-S:C,I=Number(h.font_size)||(v?Math.min(11,Math.max(7,S*.7)):10);g.drawText(m,{x:v?b+1:b,y:v?E+Math.max(2,(S-I)/2):E,size:I,font:a,color:Ah(0,0,0),maxWidth:v?Math.max(10,w-2):void 0}),i[f]=m}}return{bytes:await r.save(),applied:i,skipped:l}}function Elt(s){const t=s instanceof Error?s.message:String(s);return/encrypt/i.test(t)?"This PDF is password-protected or encrypted. Please upload an unlocked copy.":/xfa/i.test(t)?"This PDF uses an XFA form layer that LevelUp cannot read yet.":/Failed to parse|Invalid PDF|no PDF header/i.test(t)?"That file could not be read as a PDF.":t||"Something went wrong reading the PDF."}const Kis=20*1024*1024,Tlt=[{value:"purchase",label:"Purchase"},{value:"listing",label:"Listing"},{value:"disclosure",label:"Disclosure"},{value:"addendum",label:"Addendum"},{value:"other",label:"Other"}];function wx(s){var t;return(t=s==null?void 0:s.versions)!=null&&t.length?[...s.versions].sort((n,r)=>r.version_number-n.version_number)[0]:null}function Mlt(s=!1){const t=Sa();return tt({queryKey:["form-templates",t,s],enabled:!!t,queryFn:async()=>{let n=q.from("form_templates").select("*, versions:form_template_versions(*)").or(`owner_user_id.eq.${t},brokerage_id.not.is.null`).order("created_at",{ascending:!1});s||(n=n.eq("is_archived",!1));const{data:r,error:a}=await n;if(a)throw a;return(r||[]).map(i=>({...i,scope:i.brokerage_id?"brokerage":"mine"}))}})}function drr(s,t=!1){return tt({queryKey:["brokerage-form-templates",s,t],enabled:!!s,queryFn:async()=>{let n=q.from("form_templates").select("*, versions:form_template_versions(*)").eq("brokerage_id",s).order("created_at",{ascending:!1});t||(n=n.eq("is_archived",!1));const{data:r,error:a}=await n;if(a)throw a;return(r||[]).map(i=>({...i,scope:"brokerage"}))}})}function urr(){const s=Sa(),t=Vt();return ft({mutationFn:async({name:n,description:r,category:a,file:i,templateId:l,brokerageId:o})=>{var v;if(!s)throw new Error("Not authenticated");if(i.type!=="application/pdf"&&!i.name.toLowerCase().endsWith(".pdf"))throw new Error("Only PDF files can be uploaded.");if(i.size>Kis)throw new Error("That PDF is larger than the 20MB limit.");let c;try{c=await crr(await i.arrayBuffer())}catch(b){throw new Error(Elt(b))}let d=l;if(!d){const{data:b,error:w}=await q.from("form_templates").insert({owner_user_id:s,name:n,description:r||null,category:a,source_type:o?"brokerage":"user_upload",brokerage_id:o||null,is_published:!1}).select().single();if(w)throw w;d=b.id}const{data:u,error:h}=await q.from("form_template_versions").select("version_number").eq("template_id",d).order("version_number",{ascending:!1}).limit(1);if(h)throw h;const m=(((v=u==null?void 0:u[0])==null?void 0:v.version_number)??0)+1,f=`${s}/${d}/v${m}-${crypto.randomUUID()}.pdf`,{error:g}=await q.storage.from("form-templates").upload(f,i,{contentType:"application/pdf"});if(g)throw g;const{data:x,error:y}=await q.from("form_template_versions").insert({template_id:d,version_number:m,storage_path:f,file_name:i.name,file_size:i.size,page_count:c.pageCount,has_acroform:c.hasAcroform,detected_fields:c.fields,mapping_status:c.hasAcroform?"needs_mapping":"needs_placement",effective_date:new Date().toISOString().slice(0,10),created_by:s}).select().single();if(y)throw await q.storage.from("form-templates").remove([f]),y;return{templateId:d,version:x}},onSuccess:()=>{t.invalidateQueries({queryKey:["form-templates"]}),t.invalidateQueries({queryKey:["form-template"]})}})}function Yis(){const s=Vt();return ft({mutationFn:async({id:t,patch:n})=>{const{error:r}=await q.from("form_templates").update(n).eq("id",t);if(r)throw r;return t},onSuccess:()=>{s.invalidateQueries({queryKey:["form-templates"]}),s.invalidateQueries({queryKey:["brokerage-form-templates"]}),s.invalidateQueries({queryKey:["form-template"]})}})}function hrr(){const s=Sa(),t=Vt();return ft({mutationFn:async n=>{if(!s)throw new Error("Not authenticated");const r=wx(n);if(!r)throw new Error("That template has no uploaded PDF yet.");const a=await hFe(r.storage_path),{data:i,error:l}=await q.from("form_templates").insert({owner_user_id:s,name:`${n.name} (copy)`,description:n.description,category:n.category,source_type:"user_upload"}).select().single();if(l)throw l;const o=`${s}/${i.id}/v1-${crypto.randomUUID()}.pdf`,{error:c}=await q.storage.from("form-templates").upload(o,new Blob([a],{type:"application/pdf"}),{contentType:"application/pdf"});if(c)throw c;const{data:d,error:u}=await q.from("form_template_versions").insert({template_id:i.id,version_number:1,storage_path:o,file_name:r.file_name,file_size:r.file_size,page_count:r.page_count,has_acroform:r.has_acroform,detected_fields:r.detected_fields,mapping_status:r.mapping_status,effective_date:new Date().toISOString().slice(0,10),created_by:s}).select().single();if(u)throw await q.storage.from("form-templates").remove([o]),u;const{data:h}=await q.from("form_field_mappings").select("*").eq("version_id",r.id);if(h!=null&&h.length){const m=h.map(({id:g,created_at:x,updated_at:y,version_id:v,...b})=>({...b,version_id:d.id})),{error:f}=await q.from("form_field_mappings").insert(m);if(f)throw f}return i.id},onSuccess:()=>{t.invalidateQueries({queryKey:["form-templates"]})}})}function Zis(){const s=Vt();return ft({mutationFn:async t=>{const n=(t.versions||[]).map(a=>a.storage_path);n.length&&await q.storage.from("form-templates").remove(n);const{error:r}=await q.from("form_templates").delete().eq("id",t.id);if(r)throw r;return t.id},onSuccess:()=>{s.invalidateQueries({queryKey:["form-templates"]})}})}async function hFe(s){const{data:t,error:n}=await q.storage.from("form-templates").download(s);if(n||!t)throw n||new Error("Could not download the template PDF.");return await t.arrayBuffer()}function aS(s){if(!s)return"";try{const t=Ch(s);if(Number.isNaN(t.getTime()))return"";const n=String(t.getMonth()+1).padStart(2,"0"),r=String(t.getDate()).padStart(2,"0");return`${n}/${r}/${t.getFullYear()}`}catch{return""}}function mrr(){const s=new Date,t=String(s.getMonth()+1).padStart(2,"0"),n=String(s.getDate()).padStart(2,"0");return`${t}/${n}/${s.getFullYear()}`}function frr(s){if(s==null||Number.isNaN(s))return"";const t=Math.round(s*100)%100!==0;return new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",minimumFractionDigits:t?2:0,maximumFractionDigits:t?2:0}).format(s)}function Plt(s){return s?s<1024*1024?`${(s/1024).toFixed(0)} KB`:`${(s/(1024*1024)).toFixed(1)} MB`:"0 KB"}const TW=[{key:"deal.name",label:"Deal name",group:"Deal",aliases:["deal","transaction name","file name"]},{key:"deal.type",label:"Deal type",group:"Deal",aliases:["transaction type","side"]},{key:"deal.property_address",label:"Property address",group:"Deal",aliases:["property","subject property","street","address of property","premises"]},{key:"deal.city",label:"Property city",group:"Deal",aliases:["property city","city"]},{key:"deal.state",label:"Property state",group:"Deal",aliases:["property state","state"]},{key:"deal.zip",label:"Property ZIP",group:"Deal",aliases:["zip","zipcode","postal"]},{key:"deal.price",label:"Price",group:"Deal",aliases:["purchase price","sale price","sales price","list price","offer price","amount"]},{key:"deal.contract_date",label:"Contract date",group:"Deal",aliases:["contract","acceptance date","effective date","binding date"]},{key:"deal.target_close_date",label:"Target close date",group:"Deal",aliases:["closing date","close date","settlement date","coe"]},{key:"deal.actual_close_date",label:"Actual close date",group:"Deal",aliases:["closed date","actual close"]},{key:"deal.listing_date",label:"Listing date",group:"Deal",aliases:["list date","listing start"]},{key:"deal.inspection_date",label:"Inspection date",group:"Deal",aliases:["inspection"]},{key:"deal.inspection_contingency_date",label:"Inspection contingency date",group:"Deal",aliases:["inspection contingency","due diligence"]},{key:"deal.appraisal_date",label:"Appraisal date",group:"Deal",aliases:["appraisal"]},{key:"deal.loan_approval_date",label:"Loan approval date",group:"Deal",aliases:["loan approval","financing contingency","mortgage commitment"]},{key:"deal.earnest_money_due_date",label:"Earnest money due date",group:"Deal",aliases:["earnest money","emd","deposit due"]},{key:"deal.title_docs_due_date",label:"Title docs due date",group:"Deal",aliases:["title","title commitment"]},{key:"deal.final_walkthrough_date",label:"Final walkthrough date",group:"Deal",aliases:["walkthrough","walk through","final walk"]},{key:"contact.first_name",label:"Client first name",group:"Contact",aliases:["buyer first","seller first","client first","first name"]},{key:"contact.last_name",label:"Client last name",group:"Contact",aliases:["buyer last","seller last","client last","last name","surname"]},{key:"contact.full_name",label:"Client full name",group:"Contact",aliases:["buyer name","seller name","client name","purchaser","buyer","seller","client"]},{key:"contact.email",label:"Client email",group:"Contact",aliases:["buyer email","seller email","client email","email"]},{key:"contact.phone",label:"Client phone",group:"Contact",aliases:["buyer phone","seller phone","client phone","phone","telephone","mobile"]},{key:"contact.address",label:"Client address",group:"Contact",aliases:["buyer address","seller address","mailing address","client address"]},{key:"contact.city",label:"Client city",group:"Contact",aliases:["buyer city","seller city"]},{key:"contact.state",label:"Client state",group:"Contact",aliases:["buyer state","seller state"]},{key:"contact.zip",label:"Client ZIP",group:"Contact",aliases:["buyer zip","seller zip"]},{key:"contact.spouse_name",label:"Spouse name",group:"Contact",aliases:["spouse","co buyer","cobuyer","co seller","partner name","buyer 2","seller 2"]},{key:"contact.spouse_email",label:"Spouse email",group:"Contact",aliases:["spouse email","co buyer email","buyer 2 email"]},{key:"agent.name",label:"Agent name",group:"Agent",aliases:["agent","realtor","listing agent","broker name","salesperson"]},{key:"agent.email",label:"Agent email",group:"Agent",aliases:["agent email","broker email"]},{key:"agent.phone",label:"Agent phone",group:"Agent",aliases:["agent phone","broker phone"]},{key:"agent.brokerage_name",label:"Brokerage name",group:"Agent",aliases:["brokerage","firm","company","office"]},{key:"agent.license_number",label:"Agent license number",group:"Agent",aliases:["license","license no","dre","bre","lic"]},{key:"agent.license_state",label:"Agent license state",group:"Agent",aliases:["license state"]},{key:"agent.website_url",label:"Agent website",group:"Agent",aliases:["website","web site","url"]},{key:"agent.title",label:"Agent title",group:"Agent",aliases:["agent title","designation"]},{key:"today",label:"Today's date",group:"Other",aliases:["date","today","date signed","dated"]}],Xis=new Map(TW.map(s=>[s.key,s])),prr={buyer:"Buyer",seller:"Seller",dual:"Dual",referral:"Referral",lease:"Lease"};function grr(s){const t=s.deal||{},n=s.contact||{},r=s.profile||{},a=s.brand||{},i=[n.first_name,n.last_name].filter(Boolean).join(" ").trim(),l=t.sale_price??t.expected_price??null;return{"deal.name":t.deal_name||"","deal.type":prr[t.deal_type]||t.deal_type||"","deal.property_address":t.property_address||"","deal.city":t.city||"","deal.state":t.state||"","deal.zip":t.zip_code||"","deal.price":frr(l),"deal.contract_date":aS(t.contract_date),"deal.target_close_date":aS(t.target_close_date),"deal.actual_close_date":aS(t.actual_close_date),"deal.listing_date":aS(t.listing_date),"deal.inspection_date":aS(t.inspection_date),"deal.inspection_contingency_date":aS(t.inspection_contingency_date),"deal.appraisal_date":aS(t.appraisal_date),"deal.loan_approval_date":aS(t.loan_approval_date),"deal.earnest_money_due_date":aS(t.earnest_money_due_date),"deal.title_docs_due_date":aS(t.title_docs_due_date),"deal.final_walkthrough_date":aS(t.final_walkthrough_date),"contact.first_name":n.first_name||"","contact.last_name":n.last_name||"","contact.full_name":i,"contact.email":n.email||"","contact.phone":n.phone||"","contact.address":n.address||"","contact.city":n.city||"","contact.state":n.state||"","contact.zip":n.zip||n.zip_code||"","contact.spouse_name":n.spouse_name||"","contact.spouse_email":n.spouse_email||"","agent.name":r.name||"","agent.email":r.email||"","agent.phone":r.phone||"","agent.brokerage_name":r.brokerage_name||a.brokerage_name||"","agent.license_number":a.license_number||"","agent.license_state":a.license_state||"","agent.website_url":r.website_url||"","agent.title":r.title||"",today:mrr()}}function Ilt(s){const t=Sa();return tt({queryKey:["form-merge-data",s,t],enabled:!!s&&!!t,queryFn:async()=>{const{data:n,error:r}=await q.from("deal_pipeline").select("*").eq("id",s).maybeSingle();if(r)throw r;let a=null;if(n!=null&&n.contact_id){const{data:c}=await q.from("innercircle_contacts").select("*").eq("id",n.contact_id).maybeSingle();a=c}const[{data:i},{data:l}]=await Promise.all([q.from("profiles").select("*").eq("id",t).maybeSingle(),q.from("agent_brand_profiles").select("*").eq("user_id",t).maybeSingle()]),o={deal:n,contact:a,profile:i,brand:l};return{sources:o,values:grr(o)}}})}function xrr(s){return tt({queryKey:["form-generations",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await q.from("form_generations").select("*, template:form_templates(name), version:form_template_versions(version_number)").eq("deal_id",s).order("created_at",{ascending:!1});if(n)throw n;return t||[]}})}function yrr(){const s=Sa(),t=Vt();return ft({mutationFn:async({dealId:n,template:r,version:a,values:i})=>{if(!s)throw new Error("Not authenticated");const{data:l,error:o}=await q.from("form_field_mappings").select("*").eq("version_id",a.id);if(o)throw o;if(!(l!=null&&l.length))throw new Error("This template has no field mapping yet.");const c=await hFe(a.storage_path);let d;try{d=await Wis(c,l,i)}catch(w){throw new Error(Elt(w))}const h=`${r.name.replace(/[^a-zA-Z0-9-_ ]/g,"").trim()||"Form"} - v${a.version_number}.pdf`,m=d.bytes.buffer.slice(d.bytes.byteOffset,d.bytes.byteOffset+d.bytes.byteLength),f=new Blob([m],{type:"application/pdf"}),g=`${s}/${n}/${crypto.randomUUID()}.pdf`,{error:x}=await q.storage.from("deal-files").upload(g,f,{contentType:"application/pdf"});if(x)throw x;const{data:y,error:v}=await q.from("deal_files").insert({deal_id:n,owner_user_id:s,file_name:h,file_size:f.size,file_type:"application/pdf",storage_path:g}).select().single();if(v)throw v;const{error:b}=await q.from("form_generations").insert({owner_user_id:s,deal_id:n,template_id:r.id,version_id:a.id,deal_file_id:y.id,merge_snapshot:{values:i,applied:d.applied,skipped:d.skipped}});if(b)throw b;return await q.from("deal_activities").insert({deal_id:n,activity_type:"document",title:`Generated ${r.name}`,description:`${h} was generated from a LevelUp form template (v${a.version_number}).`,metadata:{template_id:r.id,version_id:a.id,deal_file_id:y.id}}),{dealFile:y,blob:f,fileName:h,skipped:d.skipped}},onSuccess:(n,r)=>{t.invalidateQueries({queryKey:["deal-files",r.dealId]}),t.invalidateQueries({queryKey:["deal-activities"]}),t.invalidateQueries({queryKey:["form-generations",r.dealId]})}})}function uoe(s){return tt({queryKey:["form-field-mappings",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await q.from("form_field_mappings").select("*").eq("version_id",s).order("created_at",{ascending:!0});if(n)throw n;return t||[]}})}function vrr(){const s=Vt();return ft({mutationFn:async({versionId:t,mappings:n,hasAcroform:r})=>{const{error:a}=await q.from("form_field_mappings").delete().eq("version_id",t);if(a)throw a;const i=n.map(d=>({version_id:t,pdf_field_name:d.pdf_field_name,mapping_mode:d.mapping_mode,merge_key:d.merge_key,static_value:d.static_value,page_index:d.page_index??null,pos_x:d.pos_x??null,pos_y:d.pos_y??null,font_size:d.font_size??null}));if(i.length){const{error:d}=await q.from("form_field_mappings").insert(i);if(d)throw d}const l=n.some(d=>d.mapping_mode==="acroform"&&d.merge_key||d.mapping_mode==="static"||d.mapping_mode==="overlay"&&d.merge_key),o=r?l?"mapped":"needs_mapping":l?"mapped":"needs_placement",{error:c}=await q.from("form_template_versions").update({mapping_status:o}).eq("id",t);if(c)throw c;return t},onSuccess:t=>{s.invalidateQueries({queryKey:["form-field-mappings",t]}),s.invalidateQueries({queryKey:["form-templates"]}),s.invalidateQueries({queryKey:["form-template"]})}})}function Qis({open:s,onOpenChange:t,dealId:n,dealName:r,initialTemplateId:a}){const{data:i=[],isLoading:l}=Mlt(),[o,c]=j.useState(a),{data:d,isLoading:u,error:h}=Ilt(s?n:void 0),m=yrr(),f=j.useMemo(()=>i.find(E=>E.id===o),[i,o]),g=wx(f),{data:x=[],isLoading:y}=uoe(s?g==null?void 0:g.id:void 0);j.useEffect(()=>{s&&a&&c(a)},[s,a]);const v=i.filter(E=>{var I;return((I=wx(E))==null?void 0:I.mapping_status)==="mapped"}),b=j.useMemo(()=>d?x.filter(E=>E.merge_key||E.static_value).map(E=>{var I;return{field:E.pdf_field_name||E.merge_key||"",label:E.merge_key?((I=Xis.get(E.merge_key))==null?void 0:I.label)||E.merge_key:"Fixed text",value:E.mapping_mode==="static"?E.static_value||"":d.values[E.merge_key||""]||""}}):[],[x,d]),w=b.filter(E=>!E.value).length,S=async()=>{if(!(!f||!g||!d))try{const E=await m.mutateAsync({dealId:n,template:f,version:g,values:d.values});re.success(`${E.fileName} saved to this deal's files`),t(!1)}catch(E){re.error((E==null?void 0:E.message)||"Could not generate the form")}},C=(g==null?void 0:g.mapping_status)==="mapped";return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Os,{className:"max-w-2xl max-h-[90vh] overflow-hidden flex flex-col",children:[e.jsxs(Us,{children:[e.jsx(Bs,{children:"Prepare a form"}),e.jsx(Ir,{children:r?`Fill a template with data from ${r}.`:"Fill a template with this deal’s data."})]}),e.jsxs("div",{className:"space-y-4 overflow-y-auto",children:[e.jsxs(ms,{value:o,onValueChange:c,disabled:l,children:[e.jsx(us,{children:e.jsx(fs,{placeholder:l?"Loading templates…":"Choose a template"})}),e.jsx(hs,{children:i.map(E=>{const I=wx(E);return e.jsxs(Ge,{value:E.id,disabled:(I==null?void 0:I.mapping_status)!=="mapped",children:[E.name,E.scope==="brokerage"?" · Brokerage":"",(I==null?void 0:I.mapping_status)!=="mapped"?" — needs mapping":""]},E.id)})})]}),!l&&i.length===0&&e.jsx("p",{className:"rounded-lg border border-dashed p-6 text-center text-sm text-muted-foreground",children:"No form templates yet. Upload one in Forms Library first."}),!l&&i.length>0&&v.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"None of your templates are mapped yet. Finish mapping one in Forms Library."}),h&&e.jsx("p",{className:"text-sm text-destructive",children:"Could not load this deal’s data. Please try again."}),f&&e.jsxs(e.Fragment,{children:[(u||y)&&e.jsx("div",{className:"flex justify-center py-6",children:e.jsx(kt,{className:"h-5 w-5 animate-spin text-muted-foreground"})}),!u&&!y&&C&&e.jsxs("div",{className:"rounded-lg border",children:[e.jsxs("div",{className:"flex items-center justify-between border-b px-3 py-2 text-xs font-medium text-muted-foreground",children:[e.jsx("span",{children:"What will be filled in"}),w>0&&e.jsxs(Be,{variant:"outline",className:"gap-1 text-[10px]",children:[e.jsx(wl,{className:"h-3 w-3"})," ",w," blank"]})]}),e.jsx(uo,{className:"max-h-[280px]",children:e.jsxs("div",{className:"divide-y",children:[b.map((E,I)=>e.jsxs("div",{className:"flex items-center gap-3 px-3 py-2 text-sm",children:[e.jsx("span",{className:"w-1/3 shrink-0 truncate text-muted-foreground",children:E.label}),e.jsx("span",{className:E.value?"truncate":"truncate italic text-muted-foreground/60",children:E.value||"not set"})]},`${E.field}-${I}`)),b.length===0&&e.jsx("p",{className:"p-4 text-center text-sm text-muted-foreground",children:"This template has no mapped fields yet."})]})})]}),!C&&g&&e.jsx("p",{className:"rounded-lg bg-muted/50 p-3 text-sm text-muted-foreground",children:g.has_acroform?"This template still needs its fields mapped.":"This PDF has no fillable fields, so it needs field placement before it can be used."})]})]}),e.jsxs(Ar,{children:[e.jsx($,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsxs($,{onClick:S,disabled:!C||m.isPending||b.length===0,children:[m.isPending?e.jsx(kt,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(qz,{className:"mr-2 h-4 w-4"}),m.isPending?"Generating…":"Generate & save to deal"]})]})]})})}const brr=["Client","Co-Buyer","Co-Seller","Spouse","Lender","Title Company","Inspector","Appraiser","Attorney","Contractor","Other"];function Jis(s){return tt({queryKey:["deal-contacts",s],queryFn:async()=>{const{data:t,error:n}=await q.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(n)throw n;return t||[]},enabled:!!s})}function _rr(){const s=Vt();return ft({mutationFn:async({dealId:t,contactId:n,role:r})=>{const{data:a,error:i}=await q.from("deal_contacts").insert({deal_id:t,contact_id:n,role:r}).select().single();if(i)throw i;return a},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["deal-contacts",n.dealId]}),re.success("Contact linked to deal")},onError:t=>{var n;(n=t.message)!=null&&n.includes("duplicate")?re.error("This contact is already linked to this deal"):re.error("Failed to link contact")}})}function wrr(){const s=Vt();return ft({mutationFn:async({id:t,dealId:n})=>{const{error:r}=await q.from("deal_contacts").delete().eq("id",t);if(r)throw r},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["deal-contacts",n.dealId]}),re.success("Contact removed from deal")},onError:()=>{re.error("Failed to remove contact")}})}const Llt=[{value:"buyer_1",label:"Buyer 1"},{value:"buyer_2",label:"Buyer 2"},{value:"seller_1",label:"Seller 1"},{value:"seller_2",label:"Seller 2"},{value:"agent",label:"Agent (you)"}];function mFe(s){var t;return((t=Llt.find(n=>n.value===s))==null?void 0:t.label)||s||"Signer"}function jrr(s){const t=Sa();return tt({queryKey:["form-envelopes",t,s||"all"],enabled:!!t,queryFn:async()=>{let n=q.from("form_envelopes").select("*, template:form_templates(name), version:form_template_versions(version_number), signers:form_envelope_signers(*)").eq("owner_user_id",t).neq("status","draft").order("created_at",{ascending:!1});s&&(n=n.eq("deal_id",s));const{data:r,error:a}=await n;if(a)throw a;return r||[]}})}function Nrr(){const s=Sa(),t=Vt();return ft({mutationFn:async({dealId:n,template:r,version:a,title:i,message:l,values:o,signers:c})=>{if(!s)throw new Error("Not authenticated");const{data:d,error:u}=await q.from("form_envelopes").insert({owner_user_id:s,deal_id:n,template_id:r.id,version_id:a.id,title:i,message:l||null,merge_snapshot:o}).select("id").single();if(u)throw u;const{data:h,error:m}=await q.functions.invoke("forms-envelope-send",{body:{action:"send",envelope_id:d.id,signers:c}});if(m)throw new Error(m.message||"Could not send the signature request");if(h!=null&&h.error)throw new Error(h.error);return await q.from("deal_activities").insert({deal_id:n,activity_type:"document",title:`Sent for signature: ${i}`,description:`${r.name} (v${a.version_number}) sent to ${c.length} signer${c.length===1?"":"s"}.`,metadata:{envelope_id:d.id,template_id:r.id,version_id:a.id}}),{envelopeId:d.id,result:h}},onSuccess:(n,r)=>{t.invalidateQueries({queryKey:["form-envelopes"]}),t.invalidateQueries({queryKey:["deal-activities"]})}})}function krr(){const s=Vt();return ft({mutationFn:async({envelopeId:t,action:n,reason:r})=>{const{data:a,error:i}=await q.functions.invoke("forms-envelope-send",{body:{action:n,envelope_id:t,reason:r}});if(i)throw new Error(i.message||"That action failed");if(a!=null&&a.error)throw new Error(a.error);return a},onSuccess:()=>{s.invalidateQueries({queryKey:["form-envelopes"]})}})}function eos(){const s=Sa();return tt({queryKey:["form-packets",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await q.from("form_packets").select("*, items:form_packet_items(*)").eq("owner_user_id",s).eq("is_archived",!1).order("created_at",{ascending:!1});if(n)throw n;return t||[]}})}function Rlt(s,t){var n;return(n=s==null?void 0:s.items)!=null&&n.length?[...s.items].sort((r,a)=>r.sort_order-a.sort_order).map(r=>t.find(a=>a.id===r.template_id)).filter(Boolean):[]}function Srr(){const s=Sa(),t=Vt();return ft({mutationFn:async({id:n,name:r,description:a,templateIds:i})=>{if(!s)throw new Error("Not authenticated");let l=n;if(l){const{error:o}=await q.from("form_packets").update({name:r,description:a||null,updated_at:new Date().toISOString()}).eq("id",l);if(o)throw o;const{error:c}=await q.from("form_packet_items").delete().eq("packet_id",l);if(c)throw c}else{const{data:o,error:c}=await q.from("form_packets").insert({owner_user_id:s,name:r,description:a||null}).select("id").single();if(c)throw c;l=o.id}if(i.length){const{error:o}=await q.from("form_packet_items").insert(i.map((c,d)=>({packet_id:l,template_id:c,sort_order:d})));if(o)throw o}return l},onSuccess:()=>t.invalidateQueries({queryKey:["form-packets"]})})}function Crr(){const s=Vt();return ft({mutationFn:async t=>{const{error:n}=await q.from("form_packets").delete().eq("id",t);if(n)throw n;return t},onSuccess:()=>s.invalidateQueries({queryKey:["form-packets"]})})}function Arr(){const s=Sa(),t=Vt();return ft({mutationFn:async({dealId:n,packet:r,templates:a,titlePrefix:i,message:l,values:o,signers:c})=>{if(!s)throw new Error("Not authenticated");const d=Rlt(r,a);if(!d.length)throw new Error("This packet has no templates in it yet.");const u=crypto.randomUUID(),h=[];for(let m=0;mE.field_kind&&E.field_kind!=="data"&&E.signer_role).map(E=>E.signer_role)),w=c.filter(E=>b.has(E.signer_role));if(!w.length)throw new Error(`${f.name} has no signature fields placed yet.`);const{data:S,error:C}=await q.functions.invoke("forms-envelope-send",{body:{action:"send",envelope_id:x.id,signers:w.map((E,I)=>({...E,order_index:I})),notify:m===0}});if(C)throw new Error(C.message||"Could not send the packet");if(S!=null&&S.error)throw new Error(S.error)}return await q.from("deal_activities").insert({deal_id:n,activity_type:"document",title:`Sent packet for signature: ${r.name}`,description:`${d.length} document${d.length===1?"":"s"} sent to ${c.length} signer${c.length===1?"":"s"}.`,metadata:{packet_id:r.id,packet_run_id:u,envelope_ids:h}}),{runId:u,envelopeIds:h}},onSuccess:()=>{t.invalidateQueries({queryKey:["form-envelopes"]}),t.invalidateQueries({queryKey:["deal-activities"]})}})}function tos({open:s,onOpenChange:t,dealId:n,dealName:r,initialTemplateId:a}){const{data:i=[],isLoading:l}=Mlt(),[o,c]=j.useState(a),{data:d,isLoading:u}=Ilt(s?n:void 0),{data:h=[]}=Jis(n),{data:m=[]}=eos(),f=Nrr(),g=Arr(),[x,y]=j.useState("single"),[v,b]=j.useState(void 0),w=j.useMemo(()=>m.find(ce=>ce.id===v),[m,v]),S=j.useMemo(()=>Rlt(w,i),[w,i]),{data:C=[],isLoading:E}=tt({queryKey:["packet-signer-roles",v,S.map(ce=>{var _e;return(_e=wx(ce))==null?void 0:_e.id}).join(",")],enabled:x==="packet"&&S.length>0,queryFn:async()=>{const ce=S.map(ve=>{var Ee;return(Ee=wx(ve))==null?void 0:Ee.id}).filter(Boolean);if(!ce.length)return[];const{data:_e,error:he}=await q.from("form_field_mappings").select("field_kind, signer_role").in("version_id",ce);if(he)throw he;const ue=new Set;for(const ve of _e||[])ve.field_kind&&ve.field_kind!=="data"&&ve.signer_role&&ue.add(ve.signer_role);return[...ue]}}),I=j.useMemo(()=>i.find(ce=>ce.id===o),[i,o]),P=wx(I),{data:R=[],isLoading:D}=uoe(s?P==null?void 0:P.id:void 0),[O,U]=j.useState(""),[W,V]=j.useState(""),[G,Y]=j.useState({});j.useEffect(()=>{s&&a&&c(a)},[s,a]);const X=j.useMemo(()=>{const ce=new Set;if(x==="packet")for(const he of C)ce.add(he);else for(const he of R)he.field_kind&&he.field_kind!=="data"&&he.signer_role&&ce.add(he.signer_role);const _e=Llt.map(he=>he.value);return[...ce].sort((he,ue)=>_e.indexOf(he)-_e.indexOf(ue))},[R,x,C]);j.useEffect(()=>{var ue,ve,Ee;const ce={},_e=h.filter(Se=>Se.contact);let he=0;for(const Se of X)if(Se==="agent"){const Le=(ue=d==null?void 0:d.sources)==null?void 0:ue.profile;ce[Se]={name:(Le==null?void 0:Le.full_name)||"",email:(Le==null?void 0:Le.email)||"",contact_id:null}}else{const Le=_e[he++],Fe=Le!=null&&Le.contact?`${Le.contact.first_name||""} ${Le.contact.last_name||""}`.trim():"";ce[Se]={name:Fe,email:((ve=Le==null?void 0:Le.contact)==null?void 0:ve.email)||"",contact_id:((Ee=Le==null?void 0:Le.contact)==null?void 0:Ee.id)||null}}Y(ce),x==="single"&&I&&!O&&U(r?`${I.name} – ${r}`:I.name)},[X,h,d,o,v,x]);const ae=(P==null?void 0:P.mapping_status)==="mapped",ie=(ce,_e)=>Y(he=>({...he,[ce]:{...he[ce],..._e}})),ne=X.length>0&&X.every(ce=>{var _e,he,ue;return((he=(_e=G[ce])==null?void 0:_e.name)==null?void 0:he.trim())&&/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(((ue=G[ce])==null?void 0:ue.email)||"")}),te=f.isPending||g.isPending,J=async()=>{if(!d)return;const ce=X.map((_e,he)=>({full_name:G[_e].name.trim(),email:G[_e].email.trim(),signer_role:_e,contact_id:G[_e].contact_id,is_agent:_e==="agent",order_index:he}));try{if(x==="packet"){if(!w)return;await g.mutateAsync({dealId:n,packet:w,templates:i,titlePrefix:r||"",message:W.trim()||void 0,values:d.values,signers:ce}),re.success(`${S.length} documents sent to ${ce[0].full_name}`)}else{if(!I||!P)return;await f.mutateAsync({dealId:n,template:I,version:P,title:O.trim()||I.name,message:W.trim()||void 0,values:d.values,signers:ce}),re.success(`Signature request sent to ${ce[0].full_name}`)}t(!1)}catch(_e){re.error((_e==null?void 0:_e.message)||"Could not send the signature request")}};return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Os,{className:"flex max-h-[90vh] max-w-xl flex-col overflow-hidden",children:[e.jsxs(Us,{children:[e.jsx(Bs,{children:"Send for signature"}),e.jsx(Ir,{children:r?`Fill a template with ${r}'s data, then email it for e-signature.`:"Fill a template with this deal’s data, then email it for e-signature."})]}),e.jsxs("div",{className:"space-y-4 overflow-y-auto",children:[m.length>0&&e.jsx("div",{className:"flex gap-1 rounded-lg bg-muted p-1",children:["single","packet"].map(ce=>e.jsx("button",{onClick:()=>y(ce),className:`flex-1 rounded-md px-3 py-1.5 text-xs font-medium transition-colors ${x===ce?"bg-background shadow-sm":"text-muted-foreground hover:text-foreground"}`,children:ce==="single"?"One form":"Packet"},ce))}),x==="packet"?e.jsxs(e.Fragment,{children:[e.jsxs(ms,{value:v,onValueChange:b,children:[e.jsx(us,{children:e.jsx(fs,{placeholder:"Choose a packet"})}),e.jsx(hs,{children:m.map(ce=>{var _e;return e.jsxs(Ge,{value:ce.id,children:[ce.name," (",((_e=ce.items)==null?void 0:_e.length)??0," forms)"]},ce.id)})})]}),S.length>0&&e.jsxs("div",{className:"rounded-lg border bg-muted/40 p-3 text-xs",children:[e.jsx("p",{className:"mb-1.5 font-semibold",children:"Signers move through these in one session:"}),e.jsx("ol",{className:"ml-4 list-decimal space-y-0.5 text-muted-foreground",children:S.map(ce=>{var _e;return e.jsxs("li",{children:[ce.name,((_e=wx(ce))==null?void 0:_e.mapping_status)!=="mapped"?" — not ready":""]},ce.id)})})]})]}):e.jsxs(ms,{value:o,onValueChange:c,disabled:l,children:[e.jsx(us,{children:e.jsx(fs,{placeholder:l?"Loading templates…":"Choose a template"})}),e.jsx(hs,{children:i.map(ce=>{const _e=wx(ce);return e.jsxs(Ge,{value:ce.id,disabled:(_e==null?void 0:_e.mapping_status)!=="mapped",children:[ce.name,ce.scope==="brokerage"?" · Brokerage":"",(_e==null?void 0:_e.mapping_status)!=="mapped"?" — not ready":""]},ce.id)})})]}),(x==="packet"?w:I)&&(u||D||E)&&e.jsx("div",{className:"flex justify-center py-6",children:e.jsx(kt,{className:"h-5 w-5 animate-spin text-muted-foreground"})}),(x==="packet"?!!w&&!E:!!I&&!D&&ae)&&X.length===0&&e.jsxs("div",{className:"flex items-start gap-2 rounded-lg bg-muted/50 p-3 text-sm text-muted-foreground",children:[e.jsx(wl,{className:"mt-0.5 h-4 w-4 shrink-0"}),e.jsxs("span",{children:["This template has no signature fields yet. Open it in the Forms Library and use"," ",e.jsx("strong",{children:"Place fields & signatures"})," to add signature, initials, and date boxes first."]})]}),X.length>0&&e.jsxs(e.Fragment,{children:[x==="single"&&I&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{className:"text-xs",children:"Document title"}),e.jsx(pe,{value:O,onChange:ce=>U(ce.target.value),placeholder:I.name})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(ee,{className:"text-xs",children:"Signers (sign in this order)"}),e.jsxs(Be,{variant:"outline",className:"text-[10px]",children:[X.length," signer",X.length===1?"":"s"]})]}),X.map((ce,_e)=>{var he,ue,ve;return e.jsxs("div",{className:"space-y-2 rounded-lg border p-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("span",{className:"text-xs font-semibold",children:[_e+1,". ",mFe(ce)]}),ce!=="agent"&&h.length>0&&e.jsxs(ms,{value:((he=G[ce])==null?void 0:he.contact_id)||"",onValueChange:Ee=>{const Se=h.find(Le=>{var Fe;return((Fe=Le.contact)==null?void 0:Fe.id)===Ee});Se!=null&&Se.contact&&ie(ce,{contact_id:Ee,name:`${Se.contact.first_name||""} ${Se.contact.last_name||""}`.trim(),email:Se.contact.email||""})},children:[e.jsx(us,{className:"h-7 w-44 text-[11px]",children:e.jsx(fs,{placeholder:"Pick deal contact…"})}),e.jsx(hs,{children:h.map(Ee=>Ee.contact?e.jsxs(Ge,{value:Ee.contact.id,className:"text-xs",children:[Ee.contact.first_name," ",Ee.contact.last_name]},Ee.contact.id):null)})]})]}),e.jsxs("div",{className:"grid gap-2 sm:grid-cols-2",children:[e.jsx(pe,{className:"h-8 text-xs",placeholder:"Full name",value:((ue=G[ce])==null?void 0:ue.name)||"",onChange:Ee=>ie(ce,{name:Ee.target.value,contact_id:null})}),e.jsx(pe,{className:"h-8 text-xs",type:"email",placeholder:"Email address",value:((ve=G[ce])==null?void 0:ve.email)||"",onChange:Ee=>ie(ce,{email:Ee.target.value,contact_id:null})})]})]},ce)})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{className:"text-xs",children:"Message (optional)"}),e.jsx(Rs,{rows:2,placeholder:"Added to the signature request email",value:W,onChange:ce=>V(ce.target.value)})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:x==="packet"?"The first signer gets one secure email link and moves straight through every document in the packet with the same adopted signature. Reminders go out automatically on day 3 and day 10.":"The first signer gets a secure email link now; each next signer is notified automatically after the previous one signs. The agent countersigns last, inside LevelUp. Reminders go out automatically on day 3 and day 10."})]})]}),e.jsxs(Ar,{children:[e.jsx($,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsxs($,{onClick:J,disabled:!ne||te||u,children:[te?e.jsx(kt,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(wf,{className:"mr-2 h-4 w-4"}),te?"Sending…":x==="packet"?`Send ${S.length||""} document${S.length===1?"":"s"}`.replace(" "," "):"Send signature request"]})]})]})})}function Err({status:s}){switch(s){case"completed":return e.jsx(Be,{className:"bg-emerald-500/15 text-emerald-600 hover:bg-emerald-500/15",children:"Completed"});case"partially_signed":return e.jsx(Be,{className:"bg-amber-500/15 text-amber-600 hover:bg-amber-500/15",children:"Partially signed"});case"sent":return e.jsx(Be,{variant:"secondary",children:"Sent"});case"declined":return e.jsx(Be,{variant:"destructive",children:"Declined"});case"voided":return e.jsx(Be,{variant:"outline",children:"Voided"});case"expired":return e.jsx(Be,{variant:"outline",children:"Expired"});case"finalize_failed":return e.jsx(Be,{variant:"destructive",children:"Needs attention"});default:return e.jsx(Be,{variant:"secondary",children:s})}}function Trr({envelope:s}){const t=Qn(),n=krr(),r=[...s.signers||[]].sort((m,f)=>m.order_index-f.order_index),a=r.some((m,f)=>m.is_agent&&m.status!=="signed"&&r.slice(0,f).every(g=>g.status==="signed")),i=s.status==="sent"||s.status==="partially_signed",l=r.find(m=>m.declined_at),o=i&&s.expires_at?Math.ceil((new Date(s.expires_at).getTime()-Date.now())/864e5):null,c=async()=>{try{const m=await n.mutateAsync({envelopeId:s.id,action:"audit_pdf"});if(!(m!=null&&m.pdf_base64))throw new Error("No audit trail was returned");const f=atob(m.pdf_base64),g=new Uint8Array(f.length);for(let v=0;v{if(!s.completed_storage_path)return;const{data:m,error:f}=await q.storage.from("deal-files").createSignedUrl(s.completed_storage_path,300);if(f||!m)return re.error("Could not download the signed document");window.open(m.signedUrl,"_blank")},u=async()=>{try{const m=await n.mutateAsync({envelopeId:s.id,action:"agent_link"});m!=null&&m.path&&t(m.path)}catch(m){re.error((m==null?void 0:m.message)||"Could not open countersigning")}},h=async()=>{const m=window.prompt("Why is this being voided? (optional)")??void 0;if(m!==void 0)try{await n.mutateAsync({envelopeId:s.id,action:"void",reason:m}),re.success("Envelope voided")}catch(f){re.error((f==null?void 0:f.message)||"Could not void")}};return e.jsxs("div",{className:"rounded-lg border bg-background p-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"flex h-8 w-8 shrink-0 items-center justify-center rounded bg-primary/10",children:e.jsx(wf,{className:"h-4 w-4 text-primary"})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"truncate text-sm font-medium",children:s.title}),e.jsx("p",{className:"text-xs text-muted-foreground",children:r.map(m=>`${m.full_name} (${mFe(m.signer_role)}): ${m.status.replace("_"," ")}`).join(" · ")})]}),e.jsx(Err,{status:s.status})]}),l&&e.jsxs("div",{className:"mt-2 ml-11 rounded-md border border-destructive/30 bg-destructive/5 p-2 text-xs text-destructive",children:[e.jsxs("span",{className:"font-semibold",children:[l.full_name," declined."]})," ",l.decline_reason||"No reason was given."]}),o!==null&&o<=4&&e.jsx("p",{className:"mt-2 ml-11 text-xs text-amber-600",children:o>0?`Expires in ${o} day${o===1?"":"s"} — reminders go out automatically.`:"Expires today — reminders go out automatically."}),(i||s.status==="completed"||s.status==="declined")&&e.jsxs("div",{className:"mt-2 flex flex-wrap gap-2 pl-11",children:[i&&e.jsxs($,{variant:"outline",size:"sm",className:"h-7 text-xs",disabled:n.isPending,onClick:async()=>{try{await n.mutateAsync({envelopeId:s.id,action:"remind"}),re.success("Reminder sent")}catch(m){re.error((m==null?void 0:m.message)||"Could not send a reminder")}},children:[e.jsx(QS,{className:"mr-1 h-3 w-3"})," Remind"]}),a&&e.jsxs($,{size:"sm",className:"h-7 text-xs",disabled:n.isPending,onClick:u,children:[e.jsx(RE,{className:"mr-1 h-3 w-3"})," Countersign now"]}),s.status==="completed"&&e.jsxs($,{variant:"outline",size:"sm",className:"h-7 text-xs",onClick:d,children:[e.jsx(di,{className:"mr-1 h-3 w-3"})," Signed PDF"]}),e.jsxs($,{variant:"ghost",size:"sm",className:"h-7 text-xs",disabled:n.isPending,onClick:c,children:[e.jsx(nV,{className:"mr-1 h-3 w-3"})," Audit trail"]}),i&&e.jsxs($,{variant:"ghost",size:"sm",className:"h-7 text-xs text-destructive",disabled:n.isPending,onClick:h,children:[e.jsx(zz,{className:"mr-1 h-3 w-3"})," Void"]})]})]})}function Mrr({dealId:s,dealName:t}){const[n,r]=j.useState(!1),[a,i]=j.useState(!1),{data:l=[],isLoading:o,error:c}=xrr(s),{data:d=[]}=jrr(s);return e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row",children:[e.jsxs($,{className:"flex-1",onClick:()=>i(!0),children:[e.jsx(wf,{className:"mr-2 h-4 w-4"})," Send for signature"]}),e.jsxs($,{variant:"outline",className:"flex-1",onClick:()=>r(!0),children:[e.jsx(Dq,{className:"mr-2 h-4 w-4"})," Prepare a form"]}),e.jsxs($,{variant:"outline",className:"sm:w-auto",onClick:()=>window.open("/mission-control/forms","_blank","noopener,noreferrer"),children:[e.jsx(kr,{className:"mr-2 h-4 w-4"})," Forms Library"]})]}),d.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:"Signature requests"}),d.map(u=>e.jsx(Trr,{envelope:u},u.id))]}),o&&e.jsx("div",{className:"flex justify-center py-6",children:e.jsx(kt,{className:"h-5 w-5 animate-spin text-muted-foreground"})}),c&&e.jsx("p",{className:"text-sm text-destructive",children:"Could not load generated forms."}),!o&&!c&&l.length===0&&d.length===0&&e.jsx("p",{className:"rounded-lg border border-dashed py-8 text-center text-sm text-muted-foreground",children:"No forms generated for this deal yet."}),l.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:"Generated forms"}),l.map(u=>{var h,m;return e.jsxs("div",{className:"flex items-center gap-3 rounded-lg border bg-background p-3",children:[e.jsx("div",{className:"flex h-8 w-8 shrink-0 items-center justify-center rounded bg-muted",children:e.jsx(Jr,{className:"h-4 w-4 text-muted-foreground"})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"truncate text-sm font-medium",children:((h=u.template)==null?void 0:h.name)||"Deleted template"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["v",((m=u.version)==null?void 0:m.version_number)??"—"," · ",en(new Date(u.created_at),"MMM d, yyyy")]})]})]},u.id)})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Signature requests email each signer a secure link and remind them automatically on day 3 and day 10. The completed, audit-certified PDF lands in this deal’s Files tab and is emailed to everyone who signed."}),e.jsx(Qis,{open:n,onOpenChange:r,dealId:s,dealName:t}),e.jsx(tos,{open:a,onOpenChange:i,dealId:s,dealName:t})]})}const XAt={text:"Short Text",textarea:"Long Text",dropdown:"Dropdown",toggle:"Yes / No"};function sos({open:s,onOpenChange:t}){const{data:n,isLoading:r}=wUn(),a=jUn(),i=NUn(),l=kUn(),[o,c]=j.useState(!1),[d,u]=j.useState({question_text:"",field_type:"text",options:[],is_required:!1}),[h,m]=j.useState(""),f=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:((n==null?void 0:n.length)||0)+1}),u({question_text:"",field_type:"text",options:[],is_required:!1}),m(""),c(!1),re.success("Question added")}catch{re.error("Failed to add question")}},g=async b=>{try{await l.mutateAsync(b),re.success("Question removed")}catch{re.error("Failed to remove question")}},x=async(b,w)=>{try{await i.mutateAsync({id:b,is_required:w})}catch{re.error("Failed to update question")}},y=()=>{h.trim()&&(u(b=>({...b,options:[...b.options,h.trim()]})),m(""))},v=b=>{u(w=>({...w,options:w.options.filter((S,C)=>C!==b)}))};return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Os,{className:"max-w-md max-h-[85vh] flex flex-col",children:[e.jsxs(Us,{children:[e.jsx(Bs,{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(uo,{className:"flex-1",children:e.jsxs("div",{className:"space-y-3 pr-2",children:[r&&e.jsx("div",{className:"flex justify-center py-8",children:e.jsx(kt,{className:"h-5 w-5 animate-spin text-muted-foreground"})}),n==null?void 0:n.map(b=>{var w;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(Ug,{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:b.question_text}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx(Be,{variant:"secondary",className:"text-xs",children:XAt[b.field_type]||b.field_type}),b.is_required&&e.jsx(Be,{variant:"outline",className:"text-xs",children:"Required"})]}),b.field_type==="dropdown"&&((w=b.options)==null?void 0:w.length)>0&&e.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:["Options: ",b.options.join(", ")]})]}),e.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0",children:[e.jsx(Sn,{checked:b.is_required,onCheckedChange:S=>x(b.id,S),className:"scale-75"}),e.jsx($,{variant:"ghost",size:"icon",className:"h-7 w-7 text-muted-foreground hover:text-destructive",onClick:()=>g(b.id),children:e.jsx(Wn,{className:"h-3.5 w-3.5"})})]})]})},b.id)}),!r&&(n==null?void 0:n.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(ee,{className:"text-sm font-medium",children:"Question"}),e.jsx(pe,{value:d.question_text,onChange:b=>u(w=>({...w,question_text:b.target.value})),className:"mt-1",placeholder:"e.g., Do you have a home to sell first?",autoFocus:!0})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-sm font-medium",children:"Answer Type"}),e.jsx("div",{className:"flex flex-wrap gap-1.5 mt-1.5",children:Object.entries(XAt).map(([b,w])=>e.jsx("button",{type:"button",onClick:()=>u(S=>({...S,field_type:b,options:[]})),className:`px-3 py-1.5 rounded-full text-xs font-medium border transition-colors ${d.field_type===b?"bg-primary text-primary-foreground border-primary":"bg-background text-muted-foreground border-input hover:border-primary/50"}`,children:w},b))})]}),d.field_type==="dropdown"&&e.jsxs("div",{children:[e.jsx(ee,{className:"text-sm font-medium",children:"Options"}),e.jsxs("div",{className:"space-y-1.5 mt-1.5",children:[d.options.map((b,w)=>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:b}),e.jsx("button",{onClick:()=>v(w),className:"text-muted-foreground hover:text-destructive",children:e.jsx(gr,{className:"h-3.5 w-3.5"})})]},w)),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(pe,{value:h,onChange:b=>m(b.target.value),onKeyDown:b=>b.key==="Enter"&&(b.preventDefault(),y()),placeholder:"Add option...",className:"h-8 text-sm"}),e.jsx($,{variant:"outline",size:"sm",onClick:y,disabled:!h.trim(),className:"h-8",children:e.jsx(dn,{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(Sn,{checked:d.is_required,onCheckedChange:b=>u(w=>({...w,is_required:b}))}),e.jsx(ee,{className:"text-xs text-muted-foreground",children:"Required"})]})}),e.jsxs("div",{className:"flex gap-2 pt-1",children:[e.jsx($,{variant:"outline",size:"sm",onClick:()=>c(!1),className:"flex-1",children:"Cancel"}),e.jsxs($,{size:"sm",onClick:f,disabled:!d.question_text.trim()||a.isPending,className:"flex-1",children:[a.isPending?e.jsx(kt,{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($,{variant:"outline",size:"sm",onClick:()=>c(!0),children:[e.jsx(dn,{className:"h-4 w-4 mr-1"})," Add Question"]}),e.jsx($,{variant:"ghost",size:"sm",onClick:()=>t(!1),children:"Done"})]})]})})}function Prr({override:s,onChange:t}){const n=Sa(),{data:r}=l$t(),[a,i]=j.useState(null),l=d=>t({...s,...d}),o=async(d,u)=>{if(n){if(d.size>5*1024*1024){re.error("Image must be under 5MB");return}i(u);try{const h=await c$t(n,d,`${u}`);l(u==="logo"?{logo_url:h}:{cover_photo_url:h})}catch(h){re.error(`Upload failed: ${h.message||h}`)}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(Nn,{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(QAt,{label:"Logo",value:s.logo_url??null,globalValue:(r==null?void 0:r.logo_url)??null,uploading:a==="logo",onUpload:d=>o(d,"logo"),onClear:()=>l({logo_url:null}),aspect:"square"}),e.jsx(QAt,{label:"Cover Photo",value:s.cover_photo_url??null,globalValue:(r==null?void 0:r.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(JAt,{label:"Brand Color",value:s.brand_color??null,globalValue:(r==null?void 0:r.brand_color)??null,onChange:d=>l({brand_color:d})}),e.jsx(JAt,{label:"Accent Color",value:s.accent_color??null,globalValue:(r==null?void 0:r.accent_color)??null,onChange:d=>l({accent_color:d})})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-sm font-medium",children:"Tagline"}),e.jsx(pe,{value:s.tagline||"",onChange:d=>l({tagline:d.target.value||null}),placeholder:(r==null?void 0:r.tagline)||"Your trusted real estate advisor",maxLength:80,className:"mt-1"})]}),c&&e.jsxs($,{variant:"ghost",size:"sm",onClick:()=>t({}),className:"text-xs text-muted-foreground hover:text-destructive",children:[e.jsx(Wn,{className:"h-3 w-3 mr-1"}),"Clear all overrides"]})]})}function QAt({label:s,value:t,globalValue:n,uploading:r,onUpload:a,onClear:i,aspect:l}){const o=t||n,c=!!t;return e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx(ee,{className:"text-sm font-medium",children:s}),c?e.jsx("span",{className:"text-[10px] font-medium text-primary",children:"Overridden"}):n?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:Pt("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(Mc,{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 h;const u=(h=d.target.files)==null?void 0:h[0];u&&a(u),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:[r?e.jsx(kt,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(ni,{className:"h-3.5 w-3.5"}),t?"Replace":"Override"]})]}),t&&e.jsx($,{variant:"ghost",size:"sm",onClick:i,className:"text-muted-foreground hover:text-destructive",children:e.jsx(Wn,{className:"h-3.5 w-3.5"})})]})]})]})}function JAt({label:s,value:t,globalValue:n,onChange:r}){const a=t||n||"#000000",i=!!t;return e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(ee,{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:Pt("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=>r(l.target.value),className:"h-6 w-8 rounded cursor-pointer border-0 bg-transparent"}),e.jsx(pe,{value:t||"",onChange:l=>r(l.target.value||null),placeholder:n||"#406E71",className:"border-0 h-7 px-1 focus-visible:ring-0 text-xs font-mono"}),t&&e.jsx($,{variant:"ghost",size:"sm",onClick:()=>r(null),className:"h-6 w-6 p-0 text-muted-foreground hover:text-destructive",children:e.jsx(Wn,{className:"h-3 w-3"})})]})]})}function Irr({portalId:s,agentUserId:t}){const n=Vt(),{data:r,isLoading:a}=tt({queryKey:["portal-vendor-manage",s,t],queryFn:async()=>{const{data:h}=await q.from("profiles").select("brokerage_id").eq("id",t).maybeSingle(),m=h==null?void 0:h.brokerage_id,f=q.from("vendors").select("*").eq("is_active",!0),g=m?f.or(`and(owner_type.eq.agent,owner_user_id.eq.${t}),and(owner_type.eq.brokerage,owner_brokerage_id.eq.${m})`):f.eq("owner_type","agent").eq("owner_user_id",t),[{data:x,error:y},{data:v},{data:b}]=await Promise.all([g.order("sort_order",{ascending:!0}).order("name",{ascending:!0}),q.from("agent_vendor_selections").select("vendor_id, is_visible").eq("agent_user_id",t),q.from("portal_vendor_overrides").select("vendor_id, is_visible").eq("portal_id",s)]);if(y)throw y;const w=new Map;(v||[]).forEach(C=>w.set(C.vendor_id,C.is_visible));const S=new Map;return(b||[]).forEach(C=>S.set(C.vendor_id,C.is_visible)),{vendors:x||[],selMap:w,overrideMap:S}}}),i=ft({mutationFn:async({vendorId:h,isVisible:m})=>{const{data:f}=await q.from("portal_vendor_overrides").select("id").eq("portal_id",s).eq("vendor_id",h).maybeSingle();if(f){const{error:g}=await q.from("portal_vendor_overrides").update({is_visible:m}).eq("id",f.id);if(g)throw g}else{const{error:g}=await q.from("portal_vendor_overrides").insert({portal_id:s,vendor_id:h,is_visible:m});if(g)throw g}},onSuccess:()=>{n.invalidateQueries({queryKey:["portal-vendor-manage",s,t]}),n.invalidateQueries({queryKey:["portal-vendors",s]})},onError:h=>re.error(h.message)});if(a)return e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(kt,{className:"w-5 h-5 animate-spin text-muted-foreground"})});const l=(r==null?void 0:r.vendors)||[],o=(r==null?void 0:r.selMap)||new Map,c=(r==null?void 0:r.overrideMap)||new Map;if(l.length===0)return e.jsxs("div",{className:"text-center py-12 border-2 border-dashed rounded-xl",children:[e.jsx(wb,{className:"w-10 h-10 text-muted-foreground mx-auto mb-3"}),e.jsx("h3",{className:"font-semibold",children:"No vendors in your library yet"}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:"Add vendors in the Vendors tab of Client Portals, then toggle them here per portal."})]});const d=h=>{const m=c.get(h.id);if(m!==void 0)return m;if(h.is_required)return!0;const f=o.get(h.id);return f===void 0?!0:f!==!1},u=h=>{var m;return((m=dK.find(f=>f.value===h))==null?void 0:m.label)||h};return e.jsxs("div",{className:"space-y-3",children:[e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Choose which vendors from your library appear in ",e.jsx("em",{children:"this specific portal"}),". Changes here only affect this deal — your global vendor library and other portals are unaffected."]}),e.jsx(uo,{className:"h-[400px] rounded-lg border",children:e.jsx("div",{className:"divide-y",children:l.map(h=>{const m=d(h);return e.jsxs("div",{className:"flex items-center gap-3 p-3",children:[e.jsx("div",{className:"w-10 h-10 rounded-lg bg-muted border flex items-center justify-center overflow-hidden shrink-0",children:h.logo_url?e.jsx("img",{src:h.logo_url,alt:h.name,className:"w-full h-full object-cover"}):e.jsx("span",{className:"text-sm font-semibold text-muted-foreground",children:h.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("p",{className:"font-medium text-sm truncate",children:h.company||h.name}),e.jsx(Be,{variant:"outline",className:"text-[10px] shrink-0",children:u(h.category)}),h.owner_type==="brokerage"&&e.jsx(Be,{variant:"secondary",className:"text-[10px] shrink-0",children:"Brokerage"}),h.is_required&&e.jsx(Be,{className:"text-[10px] shrink-0",children:"Required"})]}),h.company&&h.name&&e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:h.name})]}),e.jsx(Sn,{checked:m,disabled:h.is_required||i.isPending,onCheckedChange:f=>i.mutate({vendorId:h.id,isVisible:f})})]},h.id)})})})]})}function Lrr({portalId:s,ownerId:t,clientEmail:n,linkedPortalId:r,onLink:a}){const[i,l]=j.useState(""),[o,c]=j.useState(!1),{data:d,isLoading:u}=tt({queryKey:["all-owner-portals",t],queryFn:async()=>{const{data:g,error:x}=await q.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(x)throw x;return g},enabled:o||!!r}),h=j.useMemo(()=>!r||!d?null:d.find(g=>g.id===r),[r,d]),m=j.useMemo(()=>!d||!n?[]:d.filter(g=>{var x;return((x=g.client_email)==null?void 0:x.toLowerCase())===n.toLowerCase()&&g.id!==s}),[d,n,s]),f=j.useMemo(()=>{if(!d||!i.trim())return[];const g=i.toLowerCase();return d.filter(x=>{var v,b,w,S;const y=x.deal_pipeline;return((v=x.client_name)==null?void 0:v.toLowerCase().includes(g))||((b=x.client_email)==null?void 0:b.toLowerCase().includes(g))||((w=y==null?void 0:y.deal_name)==null?void 0:w.toLowerCase().includes(g))||((S=y==null?void 0:y.property_address)==null?void 0:S.toLowerCase().includes(g))})},[d,i]);if(r){const g=h==null?void 0:h.deal_pipeline;return e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{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(bd,{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:(h==null?void 0:h.client_name)||(g==null?void 0:g.deal_name)||"Linked Portal"}),e.jsxs("p",{className:"text-xs text-muted-foreground truncate",children:[(g==null?void 0:g.deal_type)==="listing"?"🏠 Listing":"🔑 Purchase"," · ",(g==null?void 0:g.property_address)||"No address"]})]}),e.jsxs($,{variant:"ghost",size:"sm",className:"text-xs text-destructive hover:text-destructive shrink-0",onClick:()=>a(null),children:[e.jsx($E,{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(ee,{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($,{variant:"outline",size:"sm",className:"text-xs",onClick:()=>c(!o),children:[e.jsx(bd,{className:"h-3 w-3 mr-1"}),o?"Cancel":"Link"]})]}),!o&&m.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)"}),m.map(g=>{const x=g.deal_pipeline;return e.jsxs("button",{onClick:()=>a(g.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(Be,{variant:"outline",className:"text-[10px] shrink-0 bg-amber-100 border-amber-300 text-amber-700",children:(x==null?void 0:x.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:(x==null?void 0:x.deal_name)||g.client_name}),e.jsx("p",{className:"text-[11px] text-muted-foreground truncate",children:x==null?void 0:x.property_address})]}),e.jsx(bd,{className:"h-3.5 w-3.5 text-amber-600 shrink-0"})]},g.id)})]}),o&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"relative",children:[e.jsx(Kr,{className:"absolute left-2.5 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground"}),e.jsx(pe,{value:i,onChange:g=>l(g.target.value),placeholder:"Search by name, email, or address...",className:"pl-8 h-8 text-xs",autoFocus:!0})]}),u&&e.jsx("div",{className:"flex items-center justify-center py-4",children:e.jsx(kt,{className:"h-4 w-4 animate-spin text-muted-foreground"})}),f.length>0&&e.jsx("div",{className:"space-y-1 max-h-[200px] overflow-y-auto",children:f.map(g=>{const x=g.deal_pipeline;return e.jsxs("button",{onClick:()=>{a(g.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(Be,{variant:"outline",className:"text-[10px] shrink-0",children:(x==null?void 0:x.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:(x==null?void 0:x.deal_name)||g.client_name}),e.jsx("p",{className:"text-[11px] text-muted-foreground truncate",children:g.client_email})]})]},g.id)})}),i&&f.length===0&&!u&&e.jsx("p",{className:"text-xs text-muted-foreground text-center py-3",children:"No portals found"})]})]})}function Dlt({contactId:s,onVideoReady:t}){const[n,r]=j.useState(!1),[a,i]=j.useState("record"),[l,o]=j.useState(0),[c,d]=j.useState(0),u=x3(),h=()=>{i("record"),o(0),d(0)},m=g=>{!g&&(a==="uploading"||a==="processing")||(r(g),g||h())},f=j.useCallback(async(g,x)=>{i("uploading");try{const y="Card Video",{videoId:v,libraryId:b}=await P6(y),{uploadUrl:w,apiKey:S}=await I6(v),C=new XMLHttpRequest;C.upload.onprogress=U=>{U.lengthComputable&&o(U.loaded/U.total*100)},await new Promise((U,W)=>{C.onload=()=>C.status>=200&&C.status<300?U():W(new Error("Upload failed")),C.onerror=()=>W(new Error("Upload failed")),C.open("PUT",w),C.setRequestHeader("AccessKey",S),C.send(g)}),i("processing");let E=0;const I=Date.now(),P=9e4,R=`https://iframe.mediadelivery.net/embed/${b}/${v}`;for(;E<4;){if(await new Promise(W=>setTimeout(W,3e3)),Date.now()-I>P){const W=g.size/1048576;await u.mutateAsync({bunny_video_id:v,playback_url:`https://iframe.mediadelivery.net/play/${b}/${v}`,file_size_mb:W,title:y,contact_id:s||void 0,status:"processing",touch_type:"video"}),t(R),re.success("Video saved — still encoding. It will be ready shortly."),i("done"),setTimeout(()=>{r(!1),h()},1500);return}const U=await gk(v);if(E=U.status,d(U.encodeProgress||0),E===5||E===6)throw new Error("Video processing failed")}const D=await gk(v),O=(D.storageSize||g.size)/(1024*1024);await u.mutateAsync({bunny_video_id:v,contact_id:s||void 0,playback_url:D.directPlayUrl||R,thumbnail_url:D.thumbnailUrl,preview_url:D.previewUrl||null,duration_seconds:D.length||x,file_size_mb:O,title:y,status:"ready",touch_type:"video"}),t(R),re.success("Video recorded & added to your library!"),i("done"),setTimeout(()=>{r(!1),h()},1500)}catch(y){console.error("Recording upload error:",y),re.error("Failed to process video. Please try again."),i("record")}},[s,t,u]);return e.jsxs(zs,{open:n,onOpenChange:m,children:[e.jsx(jl,{asChild:!0,children:e.jsxs($,{variant:"outline",size:"sm",className:"gap-1.5 w-full",children:[e.jsx(ua,{className:"h-3.5 w-3.5"}),"Record Video"]})}),e.jsxs(Os,{className:"sm:max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(Us,{children:e.jsx(Bs,{children:"Record a Video for Your Card"})}),a==="record"&&e.jsx(BT,{maxDurationSeconds:600,onRecordingComplete:f,onError:g=>re.error(g)}),a==="uploading"&&e.jsxs("div",{className:"flex flex-col items-center gap-4 py-12",children:[e.jsx(kt,{className:"h-10 w-10 animate-spin text-primary"}),e.jsx("p",{className:"text-sm font-medium",children:"Uploading video..."}),e.jsx(Yi,{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(kt,{className:"h-10 w-10 animate-spin text-primary"}),e.jsx("p",{className:"text-sm font-medium",children:"Processing video..."}),e.jsx(Yi,{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(Nc,{className:"h-12 w-12 text-emerald-500"}),e.jsx("p",{className:"text-sm font-medium",children:"Video attached to your card!"})]})]})]})}const Rrr=s=>`portal-settings-draft:${s}`;function Flt({open:s,onOpenChange:t,portal:n,dealOwnerId:r}){const a=UK(),[i,l]=j.useState(!1),o=j.useMemo(()=>Rrr(n.id),[n.id]),[c,d]=j.useState(!1),[u,h]=j.useState(n.next_step_text||""),[m,f]=j.useState(n.next_step_video_url||""),[g,x]=j.useState(n.inspection_date||""),[y,v]=j.useState(n.appraisal_date||""),[b,w]=j.useState(n.welcome_message||""),[S,C]=j.useState(n.review_url||""),[E,I]=j.useState(n.show_post_close_tips),[P,R]=j.useState(n.notify_client),[D,O]=j.useState(n.require_onboarding),[U,W]=j.useState(n.allow_spouse),[V,G]=j.useState(n.visibility),[Y,X]=j.useState(n.stage_mapping||[]),[ae,ie]=j.useState(null),[ne,te]=j.useState(n.linked_portal_id||null),[J,ce]=j.useState(n.referral_enabled??!0),[_e,he]=j.useState(n.referral_reward_text||""),[ue,ve]=j.useState(n.referral_cta_headline||""),[Ee,Se]=j.useState(n.homeowner_hub_video_url||""),[Le,Fe]=j.useState(n.branding_override||{}),ke=()=>{h(n.next_step_text||""),f(n.next_step_video_url||""),x(n.inspection_date||""),v(n.appraisal_date||""),w(n.welcome_message||""),C(n.review_url||""),I(n.show_post_close_tips),R(n.notify_client),O(n.require_onboarding),W(n.allow_spouse),G(n.visibility),X(n.stage_mapping||[]),te(n.linked_portal_id||null),ce(n.referral_enabled??!0),he(n.referral_reward_text||""),ve(n.referral_cta_headline||""),Se(n.homeowner_hub_video_url||""),Fe(n.branding_override||{})};j.useEffect(()=>{d(!1);const $e=localStorage.getItem(o);if($e)try{const ct=JSON.parse($e);h(ct.nextStepText||""),f(ct.nextStepVideo||""),x(ct.inspectionDate||""),v(ct.appraisalDate||""),w(ct.welcomeMessage||""),C(ct.reviewUrl||""),I(!!ct.showPostClose),R(!!ct.notifyClient),O(!!ct.requireOnboarding),W(!!ct.allowSpouse),G(ct.visibility||n.visibility),X(ct.stageMapping||[]),te(ct.linkedPortalId??null),ce(ct.referralEnabled??!0),he(ct.referralRewardText||""),ve(ct.referralCtaHeadline||""),Se(ct.homeownerHubVideoUrl||""),Fe(ct.brandingOverride||{}),d(!0);return}catch{localStorage.removeItem(o)}ke(),d(!0)},[o,n]),j.useEffect(()=>{if(!c)return;const $e={nextStepText:u,nextStepVideo:m,inspectionDate:g,appraisalDate:y,welcomeMessage:b,reviewUrl:S,showPostClose:E,notifyClient:P,requireOnboarding:D,allowSpouse:U,visibility:V,stageMapping:Y,linkedPortalId:ne,referralEnabled:J,referralRewardText:_e,referralCtaHeadline:ue,homeownerHubVideoUrl:Ee,brandingOverride:Le};u!==(n.next_step_text||"")||m!==(n.next_step_video_url||"")||g!==(n.inspection_date||"")||y!==(n.appraisal_date||"")||b!==(n.welcome_message||"")||S!==(n.review_url||"")||E!==n.show_post_close_tips||P!==n.notify_client||D!==n.require_onboarding||U!==n.allow_spouse||V!==n.visibility||JSON.stringify(Y)!==JSON.stringify(n.stage_mapping||[])||ne!==(n.linked_portal_id||null)||J!==(n.referral_enabled??!0)||_e!==(n.referral_reward_text||"")||ue!==(n.referral_cta_headline||"")||Ee!==(n.homeowner_hub_video_url||"")||JSON.stringify(Le)!==JSON.stringify(n.branding_override||{})?localStorage.setItem(o,JSON.stringify($e)):localStorage.removeItem(o)},[u,m,g,y,b,S,E,P,D,U,V,Y,ne,J,_e,ue,Ee,Le,o,c,n]);const Ve=()=>{localStorage.removeItem(o),ke()},je=async()=>{try{await a.mutateAsync({id:n.id,next_step_text:u||null,next_step_video_url:m||null,inspection_date:g||null,appraisal_date:y||null,welcome_message:b||null,review_url:S||null,show_post_close_tips:E,notify_client:P,require_onboarding:D,allow_spouse:U,visibility:V,stage_mapping:Y.length>0?Y:null,linked_portal_id:ne,referral_enabled:J,referral_reward_text:_e||null,referral_cta_headline:ue||null,homeowner_hub_video_url:Ee||null,branding_override:Object.values(Le).some(ct=>ct!=null&&ct!=="")?Le:null});const $e=n.linked_portal_id;ne&&ne!==$e&&await q.from("client_portals").update({linked_portal_id:n.id}).eq("id",ne),!ne&&$e&&await q.from("client_portals").update({linked_portal_id:null}).eq("id",$e),localStorage.removeItem(o),re.success("Portal settings saved"),t(!1)}catch{re.error("Failed to save settings")}},Ae=()=>{X([...Y,{label:""}])},Ce=$e=>{X(Y.filter((ct,Xe)=>Xe!==$e)),ae===$e&&ie(null)},qe=($e,ct,Xe)=>{const it=[...Y];it[$e]={...it[$e],[ct]:Xe},X(it)},ze=()=>{const ct=n6e(null).map(Xe=>({label:Xe.label,description:Xe.description,stageId:void 0}));X(ct)};return e.jsxs(e.Fragment,{children:[e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Os,{className:"max-w-lg max-h-[85vh] flex flex-col",children:[e.jsx(Us,{children:e.jsx(Bs,{children:"Portal Settings"})}),e.jsxs(ha,{defaultValue:"general",className:"flex-1 overflow-hidden flex flex-col",children:[e.jsxs(ma,{className:"grid grid-cols-5 shrink-0",children:[e.jsx(Zt,{value:"general",children:"General"}),e.jsx(Zt,{value:"timeline",children:"Timeline"}),e.jsx(Zt,{value:"content",children:"Content"}),e.jsx(Zt,{value:"vendors",children:"Vendors"}),e.jsx(Zt,{value:"branding",children:"Branding"})]}),e.jsxs("div",{className:"flex-1 overflow-y-auto mt-4 min-h-0",children:[e.jsxs(Xt,{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(ee,{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($e=>e.jsx("button",{onClick:()=>G($e),className:`px-3 py-1.5 rounded-full text-xs font-medium border transition-colors ${V===$e?"bg-primary text-primary-foreground border-primary":"bg-background text-muted-foreground border-input hover:border-primary/50"}`,children:$e.charAt(0).toUpperCase()+$e.slice(1)},$e))})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(ee,{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(Sn,{checked:D,onCheckedChange:O})]}),D&&e.jsxs("div",{className:"flex items-center justify-between pl-4 border-l-2 border-primary/20",children:[e.jsxs("div",{children:[e.jsx(ee,{className:"text-sm font-medium",children:"Custom Questions"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Manage intake form questions"})]}),e.jsx($,{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(ee,{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(Sn,{checked:U,onCheckedChange:W})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(ee,{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(Sn,{checked:E,onCheckedChange:I})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(ee,{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(Sn,{checked:P,onCheckedChange:R})]}),e.jsx("div",{className:"border-t pt-4",children:e.jsx(Lrr,{portalId:n.id,ownerId:r,clientEmail:n.client_email,linkedPortalId:ne,onLink:te})}),e.jsx("div",{children:e.jsx(pe,{type:"date",value:g,onChange:$e=>x($e.target.value),className:"mt-1"})}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-sm font-medium",children:"Appraisal Date"}),e.jsx(pe,{type:"date",value:y,onChange:$e=>v($e.target.value),className:"mt-1"})]})]}),e.jsx(Xt,{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(ee,{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($,{variant:"outline",size:"sm",onClick:ze,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.'}),Y.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($,{variant:"outline",size:"sm",onClick:ze,children:"Customize journey labels"})]}),e.jsx("div",{className:"space-y-2 mt-2",children:Y.map(($e,ct)=>e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ug,{className:"h-4 w-4 text-muted-foreground/50 flex-shrink-0"}),e.jsx(pe,{value:$e.label,onChange:Xe=>qe(ct,"label",Xe.target.value),placeholder:`Stage ${ct+1} label`,className:"flex-1 h-9 text-sm"}),e.jsx($,{variant:"ghost",size:"sm",className:"h-9 px-2 text-xs text-muted-foreground hover:text-primary",onClick:()=>ie(ae===ct?null:ct),children:ae===ct?"Less":"More"}),e.jsx($,{variant:"ghost",size:"icon",className:"h-9 w-9 text-muted-foreground hover:text-destructive",onClick:()=>Ce(ct),children:e.jsx(Wn,{className:"h-3.5 w-3.5"})})]}),ae===ct&&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(ee,{className:"text-xs text-muted-foreground",children:"Description"}),e.jsx("textarea",{value:$e.description||"",onChange:Xe=>qe(ct,"description",Xe.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(ee,{className:"text-xs text-muted-foreground",children:"Video"}),$e.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:$e.video_url.length>40?$e.video_url.slice(0,40)+"...":$e.video_url}),e.jsx($,{variant:"ghost",size:"sm",className:"h-7 text-xs text-destructive hover:text-destructive",onClick:()=>qe(ct,"video_url",""),children:"Remove"})]}):e.jsxs("div",{className:"mt-1 flex items-center gap-1.5",children:[e.jsx(Dlt,{onVideoReady:Xe=>qe(ct,"video_url",Xe)}),e.jsx(o9,{userId:r,onSelect:Xe=>qe(ct,"video_url",Xe),triggerSize:"sm",triggerClassName:"gap-1.5 shrink-0 flex-1"}),e.jsxs($,{variant:"ghost",size:"sm",className:"gap-1 text-xs text-muted-foreground flex-1",onClick:()=>{const Xe=prompt("Paste a YouTube or Loom URL:");Xe&&qe(ct,"video_url",Xe)},children:[e.jsx(Ad,{className:"h-3 w-3"}),"Paste URL"]})]})]})]})]},ct))}),Y.length>0&&e.jsxs($,{variant:"outline",size:"sm",onClick:Ae,className:"mt-2 text-xs w-full",children:[e.jsx(dn,{className:"h-3 w-3 mr-1"})," Add Stage"]})]})}),e.jsxs(Xt,{value:"content",className:"space-y-4 mt-0 px-1",children:[e.jsxs("div",{children:[e.jsx(ee,{className:"text-sm font-medium",children:"Welcome Message"}),e.jsx("textarea",{value:b,onChange:$e=>w($e.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(ee,{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:u,onChange:$e=>h($e.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(ee,{className:"text-sm font-medium",children:"Next Step Video (optional)"}),e.jsx(pe,{value:m,onChange:$e=>f($e.target.value),className:"mt-1",placeholder:"YouTube or Loom URL"})]}),e.jsxs("div",{children:[e.jsx(ee,{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(pe,{value:S,onChange:$e=>C($e.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(ee,{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(ee,{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(Sn,{checked:J,onCheckedChange:ce})]}),J&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{children:[e.jsx(ee,{className:"text-sm font-medium",children:"Headline"}),e.jsx(pe,{value:ue,onChange:$e=>ve($e.target.value),className:"mt-1",placeholder:"Know someone buying or selling?"})]}),e.jsxs("div",{children:[e.jsx(ee,{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(pe,{value:_e,onChange:$e=>he($e.target.value),className:"mt-1",placeholder:"$250 gift card • Donation to your charity • Closing gift"})]}),e.jsxs("div",{children:[e.jsx(ee,{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(pe,{value:Ee,onChange:$e=>Se($e.target.value),className:"mt-1",placeholder:"YouTube, Loom, or direct video URL"})]})]})]})]}),e.jsx(Xt,{value:"vendors",className:"space-y-4 mt-0 px-1",children:e.jsx(Irr,{portalId:n.id,agentUserId:r})}),e.jsx(Xt,{value:"branding",className:"space-y-4 mt-0 px-1",children:e.jsx(Prr,{override:Le,onChange:Fe})})]})]}),e.jsxs("div",{className:"flex justify-between gap-2 pt-4 border-t shrink-0",children:[e.jsx($,{variant:"ghost",onClick:Ve,children:"Reset Draft"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx($,{variant:"outline",onClick:()=>t(!1),children:"Close"}),e.jsxs($,{onClick:je,disabled:a.isPending,children:[a.isPending?e.jsx(kt,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(tl,{className:"h-4 w-4 mr-2"}),"Save Settings"]})]})]})]})}),e.jsx(sos,{open:i,onOpenChange:l})]})}const Drr=s=>`portal-update-draft:${s}`;function Olt({open:s,onOpenChange:t,portalId:n,portalSlug:r,notifyClient:a}){const i=j.useMemo(()=>Drr(n),[n]),[l,o]=j.useState(""),[c,d]=j.useState(""),[u,h]=j.useState(""),[m,f]=j.useState(!1),[g,x]=j.useState(a??!0),[y,v]=j.useState(!1),b=dJt();j.useEffect(()=>{v(!1);const C=localStorage.getItem(i);if(C)try{const E=JSON.parse(C);o(E.title||""),d(E.content||""),h(E.videoUrl||""),f(!!E.isStageChange),x(typeof E.sendNotification=="boolean"?E.sendNotification:a??!0),v(!0);return}catch{localStorage.removeItem(i)}o(""),d(""),h(""),f(!1),x(a??!0),v(!0)},[i,a]),j.useEffect(()=>{if(!y)return;const C={title:l,content:c,videoUrl:u,isStageChange:m,sendNotification:g};l.trim()||c.trim()||u.trim()||m||g!==(a??!0)?localStorage.setItem(i,JSON.stringify(C)):localStorage.removeItem(i)},[l,c,u,m,g,y,i,a]);const w=()=>{localStorage.removeItem(i),o(""),d(""),h(""),f(!1),x(a??!0)},S=async()=>{if(l.trim())try{if(await b.mutateAsync({portal_id:n,title:l.trim(),content:c.trim()||void 0,video_url:u.trim()||void 0,is_stage_change:m}),g&&r)try{const C=dC(r),{data:E,error:I}=await q.functions.invoke("send-portal-notification",{body:{portal_id:n,update_title:l.trim(),update_content:c.trim()||null,video_url:u.trim()||null,is_stage_change:m,portal_url:C,force:!0}});if(I)throw I;E!=null&&E.emailSent?re.success("Update posted & client emailed"):re.success(`Update posted (${(E==null?void 0:E.reason)||"no email sent"})`)}catch(C){console.error("Notification failed:",C),re.success("Update posted (notification failed to send)")}else re.success("Update posted to portal");w(),t(!1)}catch{re.error("Failed to post update")}};return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Os,{className:"max-w-md",children:[e.jsx(Us,{children:e.jsx(Bs,{children:"Post Portal Update"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(ee,{className:"text-sm font-medium",children:"Title *"}),e.jsx(pe,{value:l,onChange:C=>o(C.target.value),className:"mt-1",placeholder:"Inspection cleared!"})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-sm font-medium",children:"Message"}),e.jsx("textarea",{value:c,onChange:C=>d(C.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(ee,{className:"text-sm font-medium",children:"Video URL (optional)"}),e.jsxs("div",{className:"relative mt-1",children:[e.jsx(pe,{value:u,onChange:C=>h(C.target.value),className:"pl-9",placeholder:"YouTube or Loom link"}),e.jsx(ua,{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:()=>f(!m),className:`px-3 py-1.5 rounded-full text-xs font-medium border transition-colors ${m?"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:()=>x(!g),className:`px-3 py-1.5 rounded-full text-xs font-medium border transition-colors flex items-center gap-1.5 ${g?"bg-blue-500/10 text-blue-700 border-blue-200":"bg-background text-muted-foreground border-input"}`,children:[g?e.jsx(qy,{className:"h-3 w-3"}):e.jsx(XS,{className:"h-3 w-3"}),g?"Notify Client":"No Notification"]})]})]}),e.jsxs("div",{className:"flex justify-between gap-2 pt-2",children:[e.jsx($,{variant:"ghost",onClick:w,children:"Clear Draft"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx($,{variant:"outline",onClick:()=>t(!1),children:"Close"}),e.jsxs($,{onClick:S,disabled:!l.trim()||b.isPending,children:[b.isPending?e.jsx(kt,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Yr,{className:"h-4 w-4 mr-2"}),"Post Update"]})]})]})]})})}function zlt({open:s,onOpenChange:t,portal:n,dealName:r}){const a=UK(),{isGmailConnected:i,gmailEmail:l}=yy(),[o,c]=j.useState(n.client_name||""),[d,u]=j.useState(n.client_email||""),[h,m]=j.useState(!1),[f,g]=j.useState(!1),x=dC(n.slug),y=o.split(" ")[0]||"there",v=`Your Transaction Portal – ${r}`,b=`Hi ${y}, I've set up a dedicated portal where you can track the progress of your transaction in real-time. Here's your link: ${x} You can view your timeline, key dates, documents, and any updates I post along the way. Let me know if you have any questions!`,w=()=>{navigator.clipboard.writeText(x),g(!0),setTimeout(()=>g(!1),2e3),re.success("Portal link copied!")},S=async()=>{if(!d.trim()){re.error("Please enter the client email");return}m(!0);try{await a.mutateAsync({id:n.id,client_name:o||null,client_email:d||null,invite_sent_at:new Date().toISOString(),invite_method:"email"});const{error:E}=await q.functions.invoke("gmail-send",{body:{to:d,subject:v,body:b.replace(/\n/g,"
")}});if(E){let I="";try{const P=E==null?void 0:E.context;if(P&&typeof P.json=="function"){const R=await P.json();I=(R==null?void 0:R.message)||(R==null?void 0:R.error)||""}}catch{}throw new Error(I||E.message||"Failed to send invite")}re.success(`Invite sent to ${d}`),t(!1)}catch(E){re.error(E.message||"Failed to send invite")}finally{m(!1)}},C=()=>{const E=encodeURIComponent(v),I=encodeURIComponent(b);window.open(`mailto:${d}?subject=${E}&body=${I}`,"_blank"),a.mutateAsync({id:n.id,client_name:o||null,client_email:d||null,invite_sent_at:new Date().toISOString(),invite_method:"email"}).catch(()=>{})};return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Os,{className:"max-w-md",children:[e.jsx(Us,{children:e.jsx(Bs,{children:"Invite Client to Portal"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(ee,{className:"text-sm font-medium",children:"Client Name"}),e.jsx(pe,{value:o,onChange:E=>c(E.target.value),className:"mt-1",placeholder:"John Doe"})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-sm font-medium",children:"Client Email"}),e.jsx(pe,{type:"email",value:d,onChange:E=>u(E.target.value),className:"mt-1",placeholder:"john@example.com"})]}),e.jsxs("div",{children:[e.jsx(ee,{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:x})}),e.jsx($,{variant:"outline",size:"icon",onClick:w,className:"shrink-0",children:f?e.jsx(la,{className:"h-4 w-4 text-emerald-600"}):e.jsx(Ha,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{className:"space-y-2 pt-2 border-t",children:[i?e.jsxs($,{onClick:S,disabled:h||!d.trim(),className:"w-full",children:[h?e.jsx(kt,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(mn,{className:"h-4 w-4 mr-2"}),"Send via Gmail (",l,")"]}):e.jsxs($,{onClick:C,disabled:!d.trim(),className:"w-full",variant:"outline",children:[e.jsx(kr,{className:"h-4 w-4 mr-2"}),"Open in Email App"]}),e.jsxs($,{variant:"ghost",onClick:w,className:"w-full text-muted-foreground",children:[e.jsx(Ha,{className:"h-4 w-4 mr-2"}),"Just Copy Link"]})]})]})]})})}function Frr({deal:s}){const{isAdmin:t,user:n}=vs(),{data:r,isLoading:a}=bUn(s.id),i=Cit(),l=UK(),[o,c]=j.useState(!1),[d,u]=j.useState(!1),[h,m]=j.useState(!1),[f,g]=j.useState(!1),x=`portal-management-ui:${s.id}`;if(j.useEffect(()=>{const E=sessionStorage.getItem(x);if(E)try{const I=JSON.parse(E);u(!!I.settingsOpen),m(!!I.composerOpen),g(!!I.inviteOpen)}catch{sessionStorage.removeItem(x)}},[x]),j.useEffect(()=>{d||h||f?sessionStorage.setItem(x,JSON.stringify({settingsOpen:d,composerOpen:h,inviteOpen:f})):sessionStorage.removeItem(x)},[d,h,f,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(Nn,{className:"h-4 w-4 text-primary"}),e.jsx("span",{className:"font-medium text-sm",children:"Client Portal"}),e.jsx(kt,{className:"h-3 w-3 animate-spin ml-auto"})]})});const y=async()=>{var E,I;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:((E=s.contact)==null?void 0:E.email)||void 0,client_phone:((I=s.contact)==null?void 0:I.phone)||void 0}),re.success("Client portal enabled!")}catch{re.error("Failed to create portal")}finally{c(!1)}},v=async E=>{if(r)try{await l.mutateAsync({id:r.id,is_enabled:E}),re.success(E?"Portal enabled":"Portal disabled")}catch{re.error("Failed to update portal")}},b=()=>{if(!r)return;const E=dC(r.slug);navigator.clipboard.writeText(E),re.success("Portal link copied!")},w=()=>{if(!r)return;const E=dC(r.slug);window.open(E,"_blank")};if(!r)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(Nn,{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($,{onClick:y,disabled:o,size:"sm",className:"w-full",children:[o?e.jsx(kt,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Nn,{className:"h-4 w-4 mr-2"}),"Enable Client Portal"]})]});const S=dC(r.slug),C=(n==null?void 0:n.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(Nn,{className:"h-4 w-4 text-primary"}),e.jsx("span",{className:"font-medium text-sm",children:"Client Portal"}),e.jsx(Be,{variant:"outline",className:r.is_enabled?"text-xs bg-emerald-500/10 text-emerald-600 border-emerald-200":"text-xs bg-muted text-muted-foreground",children:r.is_enabled?"Active":"Disabled"})]}),e.jsx(Sn,{checked:r.is_enabled,onCheckedChange:v})]}),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(Be,{variant:"outline",className:"text-[10px] px-1.5 py-0",children:r.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:r.require_onboarding?"Required":"Disabled"})]}),r.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:r.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:S})}),e.jsxs("div",{className:"grid grid-cols-3 gap-2 mb-2 w-full",children:[e.jsxs($,{variant:"outline",size:"sm",onClick:b,className:"text-xs w-full min-w-0 px-2",children:[e.jsx(Ha,{className:"h-3 w-3 mr-1 shrink-0"}),e.jsx("span",{className:"truncate",children:"Copy"})]}),e.jsxs($,{variant:"outline",size:"sm",onClick:w,className:"text-xs w-full min-w-0 px-2",children:[e.jsx(kr,{className:"h-3 w-3 mr-1 shrink-0"}),e.jsx("span",{className:"truncate",children:"Preview"})]}),e.jsxs($,{variant:"outline",size:"sm",onClick:()=>g(!0),className:"text-xs w-full min-w-0 px-2",children:[e.jsx(Yr,{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($,{variant:"ghost",size:"sm",onClick:()=>m(!0),className:"text-xs text-muted-foreground w-full min-w-0 px-2",children:[e.jsx(p4,{className:"h-3 w-3 mr-1 shrink-0"}),e.jsx("span",{className:"truncate",children:"Post Update"})]}),e.jsxs($,{variant:"ghost",size:"sm",onClick:()=>u(!0),className:"text-xs text-muted-foreground w-full min-w-0 px-2",children:[e.jsx(Sd,{className:"h-3 w-3 mr-1 shrink-0"}),e.jsx("span",{className:"truncate",children:"Settings"})]})]}),e.jsxs(wr,{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(ul,{className:"h-3 w-3"}),"View incoming referrals"]})]}),e.jsx(Flt,{open:d,onOpenChange:u,portal:r,dealOwnerId:C}),e.jsx(Olt,{open:h,onOpenChange:m,portalId:r.id,portalSlug:r.slug,notifyClient:r.notify_client}),e.jsx(zlt,{open:f,onOpenChange:g,portal:r,dealName:s.deal_name})]})}function Orr({dealId:s,primaryContactId:t}){const n=Qn(),{data:r,isLoading:a}=Jis(s),{data:i}=z_(),l=_rr(),o=wrr(),[c,d]=j.useState(!1),[u,h]=j.useState(""),[m,f]=j.useState("Client"),g=new Set((r==null?void 0:r.map(w=>w.contact_id))||[]);t&&g.add(t);const x=i==null?void 0:i.filter(w=>{var C,E,I;if(g.has(w.id))return!1;if(!u.trim())return!0;const S=u.toLowerCase();return((C=w.first_name)==null?void 0:C.toLowerCase().includes(S))||((E=w.last_name)==null?void 0:E.toLowerCase().includes(S))||((I=w.email)==null?void 0:I.toLowerCase().includes(S))}).slice(0,8),y=w=>{l.mutate({dealId:s,contactId:w,role:m}),d(!1),h("")},v=w=>{o.mutate({id:w,dealId:s})},b={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!(r!=null&&r.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(Zn,{className:"h-4 w-4"}),"Additional Contacts"]})}),e.jsxs(Yd,{open:c,onOpenChange:d,children:[e.jsx(Zd,{asChild:!0,children:e.jsxs($,{variant:"outline",size:"sm",className:"w-full text-muted-foreground",children:[e.jsx(dn,{className:"h-3.5 w-3.5 mr-1"}),"Link a contact (lender, spouse, vendor...)"]})}),e.jsx(Bd,{className:"w-80 p-3",align:"start",children:e.jsx(eEt,{search:u,setSearch:h,selectedRole:m,setSelectedRole:f,filteredContacts:x,onAdd:y})})]})]}):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(Zn,{className:"h-4 w-4"}),"Linked Contacts",r&&r.length>0&&e.jsx(Be,{variant:"secondary",className:"text-[10px] px-1.5",children:r.length})]}),e.jsxs(Yd,{open:c,onOpenChange:d,children:[e.jsx(Zd,{asChild:!0,children:e.jsx($,{variant:"ghost",size:"sm",className:"h-7 px-2",children:e.jsx(dn,{className:"h-3.5 w-3.5"})})}),e.jsx(Bd,{className:"w-80 p-3",align:"end",children:e.jsx(eEt,{search:u,setSearch:h,selectedRole:m,setSelectedRole:f,filteredContacts:x,onAdd:y})})]})]}),e.jsx("div",{className:"space-y-1.5",children:r==null?void 0:r.map(w=>{var S,C,E,I,P,R,D,O;return e.jsxs("div",{className:"flex items-center gap-2 p-2 rounded-md bg-muted/40 group",children:[e.jsx(Oa,{className:"h-7 w-7",children:e.jsxs(za,{className:"text-[10px] bg-primary/10 text-primary",children:[(C=(S=w.contact)==null?void 0:S.first_name)==null?void 0:C[0],(I=(E=w.contact)==null?void 0:E.last_name)==null?void 0:I[0]]})}),e.jsx("div",{className:"flex-1 min-w-0",children:e.jsxs("button",{onClick:()=>n(`/mission-control/contacts/${w.contact_id}`),className:"text-sm font-medium hover:underline text-primary truncate block",children:[(P=w.contact)==null?void 0:P.first_name," ",(R=w.contact)==null?void 0:R.last_name]})}),e.jsx(Be,{variant:"outline",className:`text-[10px] px-1.5 py-0 shrink-0 ${b[w.role]||b.Other}`,children:w.role}),e.jsxs("div",{className:"flex gap-0.5 opacity-0 group-hover:opacity-100 transition-opacity",children:[((D=w.contact)==null?void 0:D.phone)&&e.jsx($,{variant:"ghost",size:"icon",className:"h-6 w-6",asChild:!0,children:e.jsx("a",{href:`tel:${w.contact.phone}`,children:e.jsx(Da,{className:"h-3 w-3"})})}),((O=w.contact)==null?void 0:O.email)&&e.jsx($,{variant:"ghost",size:"icon",className:"h-6 w-6",asChild:!0,children:e.jsx("a",{href:`mailto:${w.contact.email}`,children:e.jsx(mn,{className:"h-3 w-3"})})}),e.jsx($,{variant:"ghost",size:"icon",className:"h-6 w-6 text-destructive",onClick:()=>v(w.id),children:e.jsx(Wn,{className:"h-3 w-3"})})]})]},w.id)})})]})}function eEt({search:s,setSearch:t,selectedRole:n,setSelectedRole:r,filteredContacts:a,onAdd:i}){return e.jsxs("div",{className:"space-y-3",children:[e.jsxs(ms,{value:n,onValueChange:r,children:[e.jsx(us,{className:"h-8 text-sm",children:e.jsx(fs,{placeholder:"Role"})}),e.jsx(hs,{children:brr.map(l=>e.jsx(Ge,{value:l,children:l},l))})]}),e.jsxs("div",{className:"relative",children:[e.jsx(Kr,{className:"absolute left-2 top-2.5 h-3.5 w-3.5 text-muted-foreground"}),e.jsx(pe,{value:s,onChange:l=>t(l.target.value),placeholder:"Search contacts...",className:"pl-7 h-8 text-sm",autoFocus:!0})]}),e.jsx(uo,{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 QQ=[{key:"contract_date",label:"Contract Accepted",short:"Contract"},{key:"earnest_money_due_date",label:"Earnest Money Due",short:"Earnest $"},{key:"inspection_date",label:"Inspection",short:"Inspection"},{key:"inspection_contingency_date",label:"Inspection Deadline",short:"Insp. Deadline"},{key:"appraisal_date",label:"Appraisal",short:"Appraisal"},{key:"loan_approval_date",label:"Loan Approval",short:"Loan"},{key:"title_docs_due_date",label:"Title / Disclosures",short:"Title"},{key:"final_walkthrough_date",label:"Final Walkthrough",short:"Walkthrough"},{key:"target_close_date",label:"Target Closing",short:"Closing"}],zrr=[{value:"stage_entry",label:"When the deal enters this stage"},{value:"contract_date",label:"Contract accepted date"},{value:"earnest_money_due_date",label:"Earnest money due date"},{value:"inspection_date",label:"Inspection date"},{value:"inspection_contingency_date",label:"Inspection deadline"},{value:"appraisal_date",label:"Appraisal date"},{value:"loan_approval_date",label:"Loan approval date"},{value:"title_docs_due_date",label:"Title / disclosures date"},{value:"final_walkthrough_date",label:"Final walkthrough date"},{value:"target_close_date",label:"Target closing date"},{value:"listing_date",label:"Listing date"},{value:"actual_close_date",label:"Actual close date"}];function Brr(){const s=Vt();return ft({mutationFn:async({dealId:t,dates:n})=>{const r={};Object.entries(n).forEach(([i,l])=>{r[i]=l&&l.trim()!==""?l:null});const{error:a}=await q.from("deal_pipeline").update(r).eq("id",t);if(a)throw a},onSuccess:()=>{s.invalidateQueries({queryKey:["deals"]}),s.invalidateQueries({queryKey:["deal-pipeline"]}),s.invalidateQueries({queryKey:["tc-dashboard"]})}})}function $rr(){const s=Vt();return ft({mutationFn:async({dealId:t,completed:n})=>{const{error:r}=await q.from("deal_pipeline").update({completed_key_dates:n}).eq("id",t);if(r)throw r},onSuccess:()=>{s.invalidateQueries({queryKey:["deals"]}),s.invalidateQueries({queryKey:["deal-pipeline"]}),s.invalidateQueries({queryKey:["tc-dashboard"]})}})}function Urr(){return tt({queryKey:["tc-playbooks"],queryFn:async()=>{const{data:s,error:t}=await q.from("tc_playbooks").select("*").eq("is_active",!0).order("sort_order");if(t)throw t;const{data:n,error:r}=await q.from("tc_playbook_tasks").select("*").order("sort_order");if(r)throw r;return(s||[]).map(a=>({...a,tasks:(n||[]).filter(i=>i.playbook_id===a.id)}))},staleTime:10*6e4})}function qrr(){const s=Sa(),t=Vt();return ft({mutationFn:async({playbookId:n,dealId:r})=>{if(!s)throw new Error("Not authenticated");const[{data:a,error:i},{data:l,error:o}]=await Promise.all([q.from("deal_pipeline").select("*").eq("id",r).single(),q.from("tc_playbook_tasks").select("*").eq("playbook_id",n).order("sort_order")]);if(i)throw i;if(o)throw o;if(!l||l.length===0)return 0;const{data:c}=await q.from("deal_tasks").select("title").eq("deal_id",r),d=new Set((c||[]).map(g=>String(g.title).toLowerCase())),u=a,h=(g,x)=>{const y=g==="stage_entry"?null:u[g],v=y?new Date(`${y}T12:00:00`):new Date;return v.setDate(v.getDate()+(x||0)),v.toISOString().split("T")[0]},m=l.filter(g=>!d.has(String(g.title).toLowerCase())).map((g,x)=>({owner_user_id:s,deal_id:r,contact_id:u.contact_id,stage_id:u.stage_id,title:g.title,description:g.description,priority:g.priority,status:"todo",due_date:h(g.due_anchor,g.due_offset_days),sort_order:x}));if(m.length===0)return 0;const{error:f}=await q.from("deal_tasks").insert(m);if(f)throw f;return m.length},onSuccess:()=>{t.invalidateQueries({queryKey:["deal-tasks"]}),t.invalidateQueries({queryKey:["tc-dashboard"]})}})}function Vrr(){const s=Sa(),t=Vt();return ft({mutationFn:async({playbookId:n,stageId:r})=>{if(!s)throw new Error("Not authenticated");const[{data:a},{data:i,error:l}]=await Promise.all([q.from("tc_playbooks").select("deal_type").eq("id",n).single(),q.from("tc_playbook_tasks").select("*").eq("playbook_id",n).order("sort_order")]);if(l)throw l;if(!i||i.length===0)return 0;const{data:o}=await q.from("deal_task_templates").select("title").eq("owner_user_id",s).eq("stage_id",r),c=new Set((o||[]).map(h=>String(h.title).toLowerCase())),d=i.filter(h=>!c.has(String(h.title).toLowerCase())).map((h,m)=>({owner_user_id:s,stage_id:r,title:h.title,description:h.description,priority:h.priority,due_anchor:h.due_anchor,default_due_offset_days:h.due_offset_days,deal_type:(a==null?void 0:a.deal_type)??null,playbook_id:n,sort_order:m}));if(d.length===0)return 0;const{error:u}=await q.from("deal_task_templates").insert(d);if(u)throw u;return d.length},onSuccess:()=>{t.invalidateQueries({queryKey:["deal-task-templates"]})}})}function Hrr(){const s=Sa();return tt({queryKey:["tc-dashboard",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await q.from("deal_pipeline").select(` id, deal_name, deal_type, property_address, city, state, expected_price, expected_commission, stage_id, contact_id, contract_date, target_close_date, actual_close_date, inspection_date, inspection_contingency_date, appraisal_date, loan_approval_date, earnest_money_due_date, title_docs_due_date, final_walkthrough_date, stage:deal_pipeline_stages(id, name, color, is_won_stage, is_lost_stage), contact:innercircle_contacts(id, first_name, last_name, email, phone) `).eq("owner_user_id",s);if(n)throw n;const r=(t||[]).filter(l=>{var o,c;return!((o=l.stage)!=null&&o.is_lost_stage)&&!((c=l.stage)!=null&&c.is_won_stage)}),a=r.map(l=>l.id);let i={};if(a.length>0){const{data:l}=await q.from("deal_tasks").select("id, deal_id, title, status, priority, due_date").in("deal_id",a).order("due_date",{ascending:!0,nullsFirst:!1});(l||[]).forEach(o=>{var c;o.deal_id&&(i[c=o.deal_id]||(i[c]=[])).push(o)})}return r.map(l=>({...l,tasks:i[l.id]||[]}))},enabled:!!s})}function Blt(s){if(!s)return null;const[t,n,r]=String(s).split(/[-/T]/).map(Number);return!t||!n||!r?null:new Date(t,n-1,r)}function A5(s){const t=Blt(s);if(!t)return null;const n=new Date;return n.setHours(0,0,0,0),t.setHours(0,0,0,0),Math.round((t.getTime()-n.getTime())/864e5)}function Grr(s){return s===null?"none":s<0?"overdue":s===0?"today":s<=3?"soon":"upcoming"}const Wrr={done:"border-emerald-500/40 bg-emerald-500/10 text-emerald-700 dark:text-emerald-400",overdue:"border-destructive/40 bg-destructive/10 text-destructive",today:"border-amber-500/40 bg-amber-500/10 text-amber-700 dark:text-amber-400",soon:"border-amber-500/30 bg-amber-500/5 text-amber-700 dark:text-amber-400",upcoming:"border-border bg-muted/40 text-foreground",none:"border-dashed border-border bg-transparent text-muted-foreground"};function cUe(s){const t=Blt(s);return t?t.toLocaleDateString("en-US",{month:"short",day:"numeric"}):null}function tEt(s,t){return s==="done"?"Completed":t===null?"Not set":t===0?"Today":t<0?`${Math.abs(t)}d past due`:`in ${t}d`}function Krr({deal:s,compact:t=!1}){const n=Brr(),r=$rr(),[a,i]=j.useState(!1),[l,o]=j.useState({}),c=Array.isArray(s==null?void 0:s.completed_key_dates)?s.completed_key_dates:[],[d,u]=j.useState(c),h=c.join(","),m=j.useRef(h);j.useEffect(()=>{m.current!==h&&(m.current=h,u(c))},[h]);const f=d,g=()=>{const G={};QQ.forEach(Y=>{G[Y.key]=(s==null?void 0:s[Y.key])??""}),o(G),i(!0)},x=async()=>{try{await n.mutateAsync({dealId:s.id,dates:l}),re.success("Transaction dates updated"),i(!1)}catch(G){re.error((G==null?void 0:G.message)||"Could not save dates")}},y=async(G,Y)=>{const X=f;u(G);try{await r.mutateAsync({dealId:s.id,completed:G}),re.success(Y)}catch(ae){u(X),re.error((ae==null?void 0:ae.message)||"Could not update milestone")}},v=j.useMemo(()=>QQ.map(G=>{const Y=(s==null?void 0:s[G.key])??null,X=A5(Y),ae=f.includes(G.key),ie=Y?ae?"done":Grr(X):"none";return{...G,value:Y,days:X,isDone:ae,state:ie}}),[s,f.join(",")]),b=v.filter(G=>G.value).length,w=v.filter(G=>G.state==="done").length,S=A5(s==null?void 0:s.target_close_date),C=v.filter(G=>G.value&&!G.isDone&&G.days!==null&&G.days>=0).sort((G,Y)=>(G.days??0)-(Y.days??0))[0],E=v.filter(G=>G.state==="overdue"),I=()=>{const G=Array.from(new Set([...f,...E.map(Y=>Y.key)]));y(G,"Past milestones marked complete")},P=(G,Y)=>{const X=Y?f.filter(ae=>ae!==G):[...f,G];y(X,Y?"Marked as not complete":"Milestone completed")},[R,D]=j.useState(null),[O,U]=j.useState(""),W=G=>{U((s==null?void 0:s[G])??""),D(G)},V=async(G,Y)=>{try{await n.mutateAsync({dealId:s.id,dates:{[G]:Y}}),re.success(Y?"Date saved":"Date cleared"),D(null)}catch(X){re.error((X==null?void 0:X.message)||"Could not save date")}};return e.jsx(jk,{delayDuration:200,children:e.jsxs("div",{className:"rounded-xl border bg-card overflow-hidden",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3 px-4 py-3 border-b bg-muted/30",children:[e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsx("div",{className:"h-8 w-8 rounded-lg bg-primary/10 flex items-center justify-center shrink-0",children:e.jsx(Au,{className:"h-4 w-4 text-primary"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-sm font-semibold leading-tight",children:"Transaction Timeline"}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:f.includes("target_close_date")||s!=null&&s.actual_close_date?`Closed${cUe((s==null?void 0:s.actual_close_date)||(s==null?void 0:s.target_close_date))?` ${cUe((s==null?void 0:s.actual_close_date)||(s==null?void 0:s.target_close_date))}`:""} · ${w}/${b} milestones done`:S!==null?S>=0?`${S} day${S===1?"":"s"} to closing · ${w}/${b} milestones done`:`Closing was ${Math.abs(S)} day${Math.abs(S)===1?"":"s"} ago`:`${b} of ${QQ.length} key dates set`})]})]}),e.jsxs(zs,{open:a,onOpenChange:G=>G?g():i(!1),children:[e.jsx(jl,{asChild:!0,children:e.jsxs($,{variant:"outline",size:"sm",className:"shrink-0 gap-1.5",children:[e.jsx(gi,{className:"h-3.5 w-3.5"}),t?"":"Edit dates"]})}),e.jsxs(Os,{className:"max-w-lg",children:[e.jsx(Us,{children:e.jsx(Bs,{children:"Key transaction dates"})}),e.jsx("div",{className:"grid sm:grid-cols-2 gap-3 max-h-[60vh] overflow-y-auto pr-1",children:QQ.map(G=>e.jsxs("div",{className:"space-y-1",children:[e.jsx(ee,{htmlFor:`kd-${G.key}`,className:"text-xs text-muted-foreground",children:G.label}),e.jsx(pe,{id:`kd-${G.key}`,type:"date",value:l[G.key]??"",onChange:Y=>o(X=>({...X,[G.key]:Y.target.value})),className:"h-9"})]},G.key))}),e.jsxs(Ar,{children:[e.jsx($,{variant:"ghost",size:"sm",onClick:()=>i(!1),children:"Cancel"}),e.jsxs($,{size:"sm",onClick:x,disabled:n.isPending,children:[n.isPending?e.jsx(kt,{className:"h-3.5 w-3.5 mr-1 animate-spin"}):e.jsx(la,{className:"h-3.5 w-3.5 mr-1"}),"Save all"]})]})]})]})]}),e.jsxs("div",{className:"p-3",children:[e.jsx("div",{className:"grid grid-cols-3 sm:grid-cols-3 gap-2",children:v.map(G=>{const Y=!!G.value;return e.jsxs("div",{className:"relative",children:[e.jsxs(ly,{children:[e.jsx(cy,{asChild:!0,children:e.jsxs("button",{type:"button",disabled:r.isPending,onClick:()=>Y?P(G.key,G.isDone):W(G.key),className:Pt("relative text-left rounded-lg border px-2.5 py-2 transition-colors w-full",Wrr[G.state],"hover:brightness-105 cursor-pointer"),children:[e.jsx("p",{className:"text-[10px] uppercase tracking-wide opacity-70 truncate pr-10",children:G.short}),e.jsx("p",{className:"text-sm font-semibold leading-tight truncate",children:cUe(G.value)??"Set date"}),G.value&&e.jsx("p",{className:"text-[10px] opacity-80 truncate",children:tEt(G.state,G.days)}),Y&&e.jsx("span",{className:Pt("absolute top-1.5 right-7 h-4 w-4 rounded-full border flex items-center justify-center",G.isDone?"bg-emerald-500 border-emerald-500 text-white":"border-current opacity-40"),children:G.isDone&&e.jsx(la,{className:"h-2.5 w-2.5"})})]})}),e.jsx(Nx,{side:"top",children:G.value?G.isDone?`${G.label} completed — click to reopen`:`Click to mark ${G.label} complete`:`${G.label} — click to set the date`})]}),e.jsxs(Yd,{open:R===G.key,onOpenChange:X=>X?W(G.key):D(null),children:[e.jsx(Zd,{asChild:!0,children:e.jsx("button",{type:"button","aria-label":`Edit ${G.label}`,className:"absolute top-1 right-1 h-5 w-5 rounded-md flex items-center justify-center text-muted-foreground hover:bg-muted hover:text-foreground transition-colors",children:e.jsx(gi,{className:"h-3 w-3"})})}),e.jsxs(Bd,{className:"w-64 p-3",align:"end",children:[e.jsx(ee,{className:"text-xs text-muted-foreground",children:G.label}),e.jsx(pe,{type:"date",autoFocus:!0,value:O,onChange:X=>U(X.target.value),className:"h-9 mt-1"}),e.jsxs("div",{className:"flex items-center justify-between gap-2 mt-3",children:[e.jsx($,{variant:"ghost",size:"sm",onClick:()=>V(G.key,""),disabled:n.isPending||!G.value,children:"Clear"}),e.jsxs($,{size:"sm",onClick:()=>V(G.key,O),disabled:n.isPending,children:[n.isPending?e.jsx(kt,{className:"h-3.5 w-3.5 mr-1 animate-spin"}):e.jsx(la,{className:"h-3.5 w-3.5 mr-1"}),"Save"]})]})]})]})]},G.key)})}),(E.length>0||C||w>0)&&e.jsxs("div",{className:"mt-3 flex flex-wrap items-center gap-2 text-xs",children:[w>0&&e.jsxs("span",{className:"inline-flex items-center gap-1 rounded-full bg-emerald-500/10 text-emerald-700 dark:text-emerald-400 px-2.5 py-1 font-medium",children:[e.jsx(Bz,{className:"h-3 w-3"}),w," completed"]}),E.length>0&&e.jsxs("span",{className:"inline-flex items-center gap-1 rounded-full bg-destructive/10 text-destructive px-2.5 py-1 font-medium",children:[e.jsx(wl,{className:"h-3 w-3"}),E.length," awaiting confirmation"]}),C&&e.jsxs("span",{className:"inline-flex items-center gap-1 rounded-full bg-primary/10 text-primary px-2.5 py-1 font-medium",children:["Next: ",C.label," · ",tEt(C.state,C.days)]}),E.length>0&&e.jsxs("button",{type:"button",onClick:I,disabled:r.isPending,className:"ml-auto inline-flex items-center gap-1 rounded-full border px-2.5 py-1 font-medium hover:bg-muted transition-colors",children:[e.jsx(Bz,{className:"h-3 w-3"}),"Mark past dates complete"]})]}),E.length>0&&e.jsx("p",{className:"mt-2 text-[11px] text-muted-foreground",children:"Dates in the past show as awaiting confirmation until you check them off — tap a tile to mark it complete."}),b===0&&e.jsx("p",{className:"mt-3 text-xs text-muted-foreground text-center",children:"No key dates yet. Add them to unlock automatic deadline reminders."})]})]})})}const Yrr={Home:va,FileSignature:m_,Handshake:wb,CalendarClock:Au,Sparkles:Nn,ClipboardCheck:JN},Zrr={urgent:"bg-destructive/10 text-destructive",high:"bg-amber-500/10 text-amber-700 dark:text-amber-400",medium:"bg-primary/10 text-primary",low:"bg-muted text-muted-foreground"};function Xrr(s,t){var a;const n=((a=zrr.find(i=>i.value===s))==null?void 0:a.label)??s;if(s==="stage_entry")return t===0?"Due immediately":`${t} days after stage entry`;const r=n.replace(/ date$/i,"");return t===0?`On ${r.toLowerCase()}`:t<0?`${Math.abs(t)} days before ${r.toLowerCase()}`:`${t} days after ${r.toLowerCase()}`}function nos({open:s,onOpenChange:t,dealId:n,dealName:r}){const{data:a,isLoading:i}=Urr(),{data:l}=Jie(),o=qrr(),c=Vrr(),[d,u]=j.useState(null),[h,m]=j.useState({}),f=y=>{if(h[y.id])return h[y.id];const v=l==null?void 0:l.find(b=>{var w,S;return((w=b.name)==null?void 0:w.toLowerCase())===((S=y.target_stage_name)==null?void 0:S.toLowerCase())});return(v==null?void 0:v.id)??""},g=async y=>{if(n){u(y.id);try{const v=await o.mutateAsync({playbookId:y.id,dealId:n});re.success(v>0?`Added ${v} task${v===1?"":"s"} to this deal`:"All tasks already exist on this deal"),v>0&&t(!1)}catch(v){re.error((v==null?void 0:v.message)||"Could not apply playbook")}finally{u(null)}}},x=async y=>{const v=f(y);if(!v){re.error("Pick which stage this playbook should trigger on");return}u(`install-${y.id}`);try{const b=await c.mutateAsync({playbookId:y.id,stageId:v});re.success(b>0?`Automated — ${b} task${b===1?"":"s"} will now be created every time a deal reaches this stage`:"This playbook is already automated for that stage")}catch(b){re.error((b==null?void 0:b.message)||"Could not automate playbook")}finally{u(null)}};return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Os,{className:"sm:max-w-2xl max-h-[85vh] flex flex-col p-0",children:[e.jsx(Us,{className:"p-6 pb-4 border-b",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"h-9 w-9 rounded-lg bg-primary/10 flex items-center justify-center",children:e.jsx(Xf,{className:"h-4.5 w-4.5 text-primary"})}),e.jsxs("div",{children:[e.jsx(Bs,{children:"Transaction Playbooks"}),e.jsx(Ir,{children:r?`Drop a proven checklist onto ${r} — deadlines calculate from its real dates.`:"Proven checklists that run themselves. Automate one and every future deal gets it."})]})]})}),e.jsx(uo,{className:"flex-1 min-h-0 overflow-y-auto",children:e.jsx("div",{className:"p-6 pt-4",children:i?e.jsx("div",{className:"flex justify-center py-12",children:e.jsx(kt,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):e.jsx(WB,{type:"single",collapsible:!0,className:"space-y-3",children:(a||[]).map(y=>{const v=Yrr[y.icon||"ClipboardCheck"]||JN,b=y.accent_color||"hsl(var(--primary))";return e.jsxs(p6,{value:y.id,className:"border rounded-xl px-0 overflow-hidden bg-card",children:[e.jsx(g6,{className:"px-4 py-3 hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-3 text-left flex-1 min-w-0",children:[e.jsx("div",{className:"h-10 w-10 rounded-lg flex items-center justify-center shrink-0",style:{backgroundColor:`${b}1a`},children:e.jsx(v,{className:"h-5 w-5",style:{color:b}})}),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-semibold text-sm",children:y.name}),e.jsxs(Be,{variant:"secondary",className:"text-[10px]",children:[y.tasks.length," steps"]}),y.deal_type&&e.jsx(Be,{variant:"outline",className:"text-[10px] capitalize",children:y.deal_type})]}),e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5 line-clamp-1",children:y.description})]})]})}),e.jsxs(x6,{className:"px-4 pb-4",children:[e.jsx("div",{className:"space-y-1.5 mb-4",children:y.tasks.map((w,S)=>e.jsxs("div",{className:"flex items-start gap-2.5 rounded-lg border bg-background px-3 py-2",children:[e.jsx("span",{className:"text-[10px] font-mono text-muted-foreground mt-0.5 w-4 shrink-0",children:S+1}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"text-sm font-medium leading-tight",children:w.title}),w.description&&e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5",children:w.description}),e.jsx("p",{className:"text-[11px] text-muted-foreground mt-1",children:Xrr(w.due_anchor,w.due_offset_days)})]}),e.jsx("span",{className:Pt("text-[10px] px-1.5 py-0.5 rounded-full shrink-0 capitalize",Zrr[w.priority]),children:w.priority})]},w.id))}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-2 pt-2 border-t",children:[n&&e.jsxs($,{size:"sm",className:"gap-1.5",onClick:()=>g(y),disabled:d===y.id,children:[d===y.id?e.jsx(kt,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(eg,{className:"h-3.5 w-3.5"}),"Add to this deal"]}),e.jsxs("div",{className:"flex gap-2 flex-1",children:[e.jsxs(ms,{value:f(y),onValueChange:w=>m(S=>({...S,[y.id]:w})),children:[e.jsx(us,{className:"h-9 text-xs flex-1",children:e.jsx(fs,{placeholder:"Trigger stage"})}),e.jsx(hs,{children:(l||[]).map(w=>e.jsx(Ge,{value:w.id,children:w.name},w.id))})]}),e.jsxs($,{size:"sm",variant:"outline",className:"gap-1.5 shrink-0",onClick:()=>x(y),disabled:d===`install-${y.id}`,children:[d===`install-${y.id}`?e.jsx(kt,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(zE,{className:"h-3.5 w-3.5"}),"Automate"]})]})]}),e.jsxs("p",{className:"text-[11px] text-muted-foreground mt-2 flex items-center gap-1",children:[e.jsx(qr,{className:"h-3 w-3"}),"Automating adds these steps to every future deal that reaches that stage."]})]})]},y.id)})})})})]})})}function Qrr(s){return tt({queryKey:["deal-email-links",s],queryFn:async()=>{const{data:t,error:n}=await q.from("deal_email_links").select("id, gmail_message_id, gmail_thread_id, subject, from_address, participants, sent_at, note, created_at").eq("deal_id",s).order("sent_at",{ascending:!1,nullsFirst:!1}).range(0,999);if(n)throw n;return t},enabled:!!s})}function Jrr(s){const t=Vt();return ft({mutationFn:async n=>{const{error:r}=await q.from("deal_email_links").delete().eq("id",n);if(r)throw r},onSuccess:()=>{t.invalidateQueries({queryKey:["deal-email-links",s]})}})}function ear(s,t){return s?`https://mail.google.com/mail/u/0/#all/${encodeURIComponent(s)}`:`https://mail.google.com/mail/u/0/#all/${encodeURIComponent(t)}`}function tar({dealId:s}){const{data:t=[],isLoading:n,error:r}=Qrr(s),a=Jrr(s);return e.jsxs("section",{"aria-labelledby":"linked-emails-heading",className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("h3",{id:"linked-emails-heading",className:"flex items-center gap-2 text-sm font-medium",children:[e.jsx(mn,{className:"h-4 w-4 text-primary"})," Linked emails"]}),t.length>0&&e.jsxs("span",{className:"text-xs text-muted-foreground",children:[t.length," connected"]})]}),n?e.jsx("p",{className:"text-sm text-muted-foreground",children:"Loading linked emails…"}):r?e.jsx("p",{className:"rounded-md border border-destructive/30 bg-destructive/5 p-3 text-sm text-destructive",children:"We couldn't load the emails linked to this transaction. Please refresh and try again."}):t.length===0?e.jsx("p",{className:"rounded-md border border-dashed p-3 text-sm text-muted-foreground",children:"No emails linked yet — attach one from Gmail with the LevelUp Companion extension."}):e.jsx("div",{className:"divide-y rounded-md border",children:t.map(i=>{const l=i.sent_at||i.created_at;return e.jsxs("div",{className:"flex items-start gap-3 p-3",children:[e.jsx(mn,{className:"mt-0.5 h-4 w-4 shrink-0 text-muted-foreground"}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"truncate text-sm font-medium",children:i.subject||"Email from Gmail"}),e.jsxs("p",{className:"truncate text-xs text-muted-foreground",children:[i.from_address||"Unknown sender",l?` · ${en(Ch(l),"MMM d, yyyy")}`:"",i.sent_at?"":" (attached)"]}),i.note&&e.jsx("p",{className:"mt-1 line-clamp-2 text-xs text-muted-foreground",children:i.note})]}),e.jsx($,{variant:"ghost",size:"icon",asChild:!0,title:"Open in Gmail",children:e.jsx("a",{href:ear(i.gmail_thread_id,i.gmail_message_id),target:"_blank",rel:"noreferrer",children:e.jsx(kr,{className:"h-4 w-4"})})}),e.jsx($,{variant:"ghost",size:"icon",title:"Remove link",disabled:a.isPending,onClick:()=>a.mutate(i.id),children:e.jsx(Wn,{className:"h-4 w-4"})})]},i.id)})})]})}const sar=10*1024*1024;function nar({dealId:s,photoUrl:t}){const n=j.useRef(null),r=Vt(),[a,i]=j.useState(!1),l=async d=>{const{error:u}=await q.from("deal_pipeline").update({property_photo_url:d}).eq("id",s);if(u)throw u;r.invalidateQueries({queryKey:["deal-pipeline-deals"]}),r.invalidateQueries({queryKey:["deals"]})},o=async d=>{var u;if(!d.type.startsWith("image/")){re.error("Please choose an image file");return}if(d.size>sar){re.error("Image must be under 10MB");return}i(!0);try{const{data:h}=await q.auth.getUser(),m=(d.name.split(".").pop()||"jpg").toLowerCase(),f=`deal-photos/${(u=h.user)==null?void 0:u.id}/${s}-${Date.now()}.${m}`,{error:g}=await q.storage.from("agent-uploads").upload(f,d,{upsert:!0,contentType:d.type});if(g)throw g;const{data:x}=q.storage.from("agent-uploads").getPublicUrl(f);await l(x.publicUrl),re.success("Property photo updated")}catch(h){re.error(h.message||"Upload failed")}finally{i(!1),n.current&&(n.current.value="")}},c=async()=>{i(!0);try{await l(null),re.success("Photo removed")}catch(d){re.error(d.message||"Could not remove photo")}finally{i(!1)}};return e.jsxs("div",{className:"col-span-2",children:[e.jsxs("button",{type:"button",onClick:()=>{var d;return(d=n.current)==null?void 0:d.click()},disabled:a,className:"group relative w-full h-36 rounded-lg overflow-hidden border border-border bg-muted/40 focus:outline-none focus-visible:ring-2 focus-visible:ring-ring","aria-label":t?"Change property photo":"Add property photo",children:[t?e.jsx("img",{src:t,alt:"Property",className:"h-full w-full object-cover"}):e.jsxs("span",{className:"flex h-full w-full flex-col items-center justify-center gap-1 text-muted-foreground",children:[e.jsx(va,{className:"h-5 w-5"}),e.jsx("span",{className:"text-xs",children:"Add property photo"})]}),e.jsx("span",{className:"absolute inset-0 bg-foreground/50 opacity-0 group-hover:opacity-100 transition-opacity flex items-center justify-center",children:a?e.jsx(kt,{className:"h-5 w-5 text-background animate-spin"}):e.jsx(Cx,{className:"h-5 w-5 text-background"})})]}),e.jsxs("div",{className:"flex items-center justify-between mt-1",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Shows on the deal and in the Gmail companion panel."}),t&&e.jsxs($,{variant:"ghost",size:"sm",className:"gap-1.5 text-muted-foreground",onClick:c,disabled:a,children:[e.jsx(Wn,{className:"h-3.5 w-3.5"}),"Remove"]})]}),e.jsx("input",{ref:n,type:"file",accept:"image/*",className:"hidden",onChange:d=>{var h;const u=(h=d.target.files)==null?void 0:h[0];u&&o(u)}})]})}const rar={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"}},aar={note:eo,call:Da,email:mn,meeting:Ta,stage_change:kr,task_completed:qr,document:va,system:da};function iar({deal:s,open:t,onOpenChange:n,onEdit:r,onAddToScorecard:a,isWonStage:i}){var Le,Fe;const l=Qn(),{data:o,isLoading:c}=QXn((s==null?void 0:s.id)||""),{data:d,isLoading:u}=eQn((s==null?void 0:s.id)||""),h=JXn(),m=sQn(),f=tQn(),g=XXn(),{data:x,isLoading:y}=rJn((s==null?void 0:s.id)||""),v=aJn(),b=iJn(),w=oJn(),S=j.useRef(null),[C,E]=j.useState(""),[I,P]=j.useState(""),[R,D]=j.useState(!1),[O,U]=j.useState(!1),[W,V]=j.useState(!1);if(!s)return null;const G=rar[s.deal_type],Y=(()=>{var je;if(s.deal_type!=="seller"&&s.deal_type!=="dual")return null;const ke=((je=s.listing)==null?void 0:je.created_at)||s.listing_date;if(!ke)return null;const Ve=s.contract_date?Ch(s.contract_date):new Date;return mk(Ve,Ch(ke))})(),X=ke=>ke?new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(ke):"-",ae=async()=>{if(C.trim())try{await h.mutateAsync({deal_id:s.id,activity_type:"note",title:"Note added",description:C}),E(""),re.success("Note added")}catch{re.error("Failed to add note")}},ie=async()=>{if(I.trim())try{await m.mutateAsync({deal_id:s.id,title:I,sort_order:((d==null?void 0:d.length)||0)+1}),P(""),re.success("Task added")}catch{re.error("Failed to add task")}},ne=async(ke,Ve)=>{try{await f.mutateAsync({id:ke,is_completed:Ve,deal_id:s.id})}catch{re.error("Failed to update task")}},te=async()=>{try{await g.mutateAsync(s.id),re.success("Deal deleted"),n(!1)}catch{re.error("Failed to delete deal")}},J=(d==null?void 0:d.filter(ke=>ke.is_completed).length)||0,ce=(d==null?void 0:d.length)||0,_e=(x==null?void 0:x.length)||0,he=ke=>ke<1024?`${ke} B`:ke<1024*1024?`${(ke/1024).toFixed(1)} KB`:`${(ke/(1024*1024)).toFixed(1)} MB`,ue=ke=>ke?ke.startsWith("image/")?Mc:ke.includes("pdf")?Jr:Fq:Fq,ve=async ke=>{const Ve=ke.target.files;if(!(!Ve||!s)){V(!0);try{for(const je of Array.from(Ve)){if(je.size>20*1024*1024){re.error(`${je.name} exceeds 20MB limit`);continue}await v.mutateAsync({dealId:s.id,file:je})}re.success("File(s) uploaded")}catch{re.error("Failed to upload file")}finally{V(!1),S.current&&(S.current.value="")}}},Ee=async(ke,Ve)=>{if(s)try{await b.mutateAsync({fileId:ke,storagePath:Ve,dealId:s.id}),re.success("File deleted")}catch{re.error("Failed to delete file")}},Se=async(ke,Ve)=>{try{const je=await lJn(ke),Ae=document.createElement("a");Ae.href=je,Ae.download=Ve,Ae.target="_blank",document.body.appendChild(Ae),Ae.click(),document.body.removeChild(Ae)}catch{re.error("Failed to download file")}};return e.jsxs(e.Fragment,{children:[e.jsx(Wy,{open:t,onOpenChange:n,children:e.jsxs(py,{className:"w-full sm:max-w-xl p-0 flex flex-col",children:[e.jsx(D0,{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(Be,{variant:"outline",className:Pt("text-xs",G.color),children:G.label}),e.jsxs(Be,{variant:"secondary",className:"text-xs capitalize",children:[s.priority," priority"]})]}),e.jsx(F0,{className:"text-xl",children:s.deal_name}),e.jsx("div",{className:"mt-2",children:e.jsx(nJn,{dealId:s.id})})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx($,{variant:"outline",size:"icon",onClick:()=>r(s),children:e.jsx(_p,{className:"h-4 w-4"})}),e.jsx($,{variant:"outline",size:"icon",className:"text-destructive hover:bg-destructive/10",onClick:()=>U(!0),children:e.jsx(Wn,{className:"h-4 w-4"})})]})]})}),e.jsx(uo,{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.jsxs("button",{type:"button",onClick:()=>{n(!1),l(`/mission-control/contacts/${s.contact_id}`)},className:"flex items-center gap-3 flex-1 min-w-0 text-left hover:opacity-80 transition-opacity group",children:[e.jsx(Oa,{className:"h-10 w-10",children:e.jsxs(za,{className:"bg-primary/10 text-primary",children:[(Le=s.contact.first_name)==null?void 0:Le[0],(Fe=s.contact.last_name)==null?void 0:Fe[0]]})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("p",{className:"font-medium group-hover:text-primary group-hover:underline truncate",children:[s.contact.first_name," ",s.contact.last_name]}),s.contact.email&&e.jsx("p",{className:"text-sm text-muted-foreground truncate",children:s.contact.email})]})]}),e.jsxs("div",{className:"flex gap-2 shrink-0",children:[s.contact.phone&&e.jsx($,{variant:"outline",size:"icon",asChild:!0,children:e.jsx("a",{href:`tel:${s.contact.phone}`,children:e.jsx(Da,{className:"h-4 w-4"})})}),s.contact.email&&e.jsx($,{variant:"outline",size:"icon",asChild:!0,children:e.jsx("a",{href:`mailto:${s.contact.email}`,children:e.jsx(mn,{className:"h-4 w-4"})})}),e.jsx($,{variant:"outline",size:"icon",title:"Open contact record",onClick:()=>{n(!1),l(`/mission-control/contacts/${s.contact_id}`)},children:e.jsx(kr,{className:"h-4 w-4"})})]})]}),e.jsx(Orr,{dealId:s.id,primaryContactId:s.contact_id}),e.jsx(tar,{dealId:s.id}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsx(nar,{dealId:s.id,photoUrl:s.property_photo_url}),(s.property_address||s.city)&&e.jsxs("div",{className:"col-span-2 flex items-start gap-2 text-sm",children:[e.jsx(va,{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:X(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:X(s.expected_commission)})]}),(s.brokerage_split_pct||s.team_split_pct||s.referral_fee_pct||s.franchise_fee_pct||s.transaction_fee||s.bonus_amount)&&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?` (${X(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:X(s.transaction_fee)})]}),s.bonus_amount!=null&&Number(s.bonus_amount)>0&&e.jsxs("div",{className:"flex justify-between text-sm",children:[e.jsx("span",{className:"text-muted-foreground",children:"Bonus (not split)"}),e.jsxs("span",{className:"text-emerald-600",children:["+",X(s.bonus_amount)]})]}),jw(s)!=null&&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:X(jw(s))})]})})]}),i&&!s.scorecard_transaction_id&&a&&e.jsxs($,{onClick:()=>a(s),className:"w-full bg-green-600 hover:bg-green-700",children:[e.jsx(Kl,{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(qr,{className:"h-4 w-4 text-green-600"}),e.jsx("span",{children:"Synced to Scorecard"})]}),Y!==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:Pt("text-lg font-bold",Y>90?"text-red-600":Y>60?"text-amber-600":"text-foreground"),children:[Y," ",s.contract_date?"(final)":"days"]})]}),s.target_close_date&&e.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[e.jsx(Ta,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("span",{children:["Close: ",en(Ch(s.target_close_date),"MMM d, yyyy")]})]}),e.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[e.jsx(ru,{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(Krr,{deal:s}),e.jsx(Frr,{deal:s}),e.jsxs(ha,{defaultValue:"tasks",className:"w-full",children:[e.jsxs(ma,{className:"w-full grid grid-cols-4",children:[e.jsxs(Zt,{value:"tasks",className:"gap-1",children:[e.jsx(qr,{className:"h-4 w-4"}),"Tasks ",ce>0&&`(${J}/${ce})`]}),e.jsxs(Zt,{value:"files",className:"gap-1",children:[e.jsx(QI,{className:"h-4 w-4"}),"Files ",_e>0&&`(${_e})`]}),e.jsxs(Zt,{value:"forms",className:"gap-1",children:[e.jsx(m_,{className:"h-4 w-4"}),"Forms"]}),e.jsxs(Zt,{value:"activity",className:"gap-1",children:[e.jsx(da,{className:"h-4 w-4"}),"Activity"]})]}),e.jsx(Xt,{value:"forms",className:"mt-4",children:e.jsx(Mrr,{dealId:s.id,dealName:s.deal_name})}),e.jsxs(Xt,{value:"tasks",className:"mt-4 space-y-3",children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsx(pe,{placeholder:"Add a new task...",value:I,onChange:ke=>P(ke.target.value),onKeyDown:ke=>ke.key==="Enter"&&ie()}),e.jsx($,{onClick:ie,disabled:!I.trim(),children:e.jsx(dn,{className:"h-4 w-4"})}),e.jsxs($,{variant:"outline",className:"gap-1.5 shrink-0",onClick:()=>D(!0),children:[e.jsx(Xf,{className:"h-4 w-4"}),"Playbooks"]})]}),e.jsxs("div",{className:"space-y-2",children:[d==null?void 0:d.map(ke=>e.jsxs("div",{className:Pt("flex items-center gap-3 p-3 rounded-lg border transition-colors",ke.is_completed?"bg-muted/50 border-border":"bg-background"),children:[e.jsx(ai,{checked:ke.is_completed,onCheckedChange:Ve=>ne(ke.id,!!Ve)}),e.jsx("span",{className:Pt("flex-1 text-sm",ke.is_completed&&"line-through text-muted-foreground"),children:ke.title}),ke.due_date&&e.jsx("span",{className:"text-xs text-muted-foreground",children:en(new Date(ke.due_date),"MMM d")})]},ke.id)),(d==null?void 0:d.length)===0&&e.jsx("p",{className:"text-center text-muted-foreground text-sm py-4",children:"No tasks yet. Add one above!"})]})]}),e.jsxs(Xt,{value:"files",className:"mt-4 space-y-3",children:[(s==null?void 0:s.id)&&e.jsx(uJn,{dealId:s.id}),e.jsx("input",{type:"file",ref:S,className:"hidden",multiple:!0,onChange:ve,accept:".pdf,.doc,.docx,.xls,.xlsx,.jpg,.jpeg,.png,.webp,.gif,.txt,.csv"}),e.jsxs($,{variant:"outline",className:"w-full border-dashed",onClick:()=>{var ke;return(ke=S.current)==null?void 0:ke.click()},disabled:W,children:[W?e.jsx(kt,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(ni,{className:"h-4 w-4 mr-2"}),W?"Uploading...":"Upload Files"]}),e.jsxs("div",{className:"space-y-2",children:[x==null?void 0:x.map(ke=>{const Ve=ue(ke.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(Ve,{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:ke.file_name}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[he(ke.file_size)," · ",en(new Date(ke.created_at),"MMM d, yyyy")]})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(jk,{children:e.jsxs(ly,{children:[e.jsx(cy,{asChild:!0,children:e.jsx($,{variant:"ghost",size:"icon",className:`h-8 w-8 transition-colors ${ke.visible_on_portal?"text-primary bg-primary/10 hover:bg-primary/20":"text-muted-foreground/40 hover:text-muted-foreground"}`,onClick:()=>w.mutate({fileId:ke.id,visible:!ke.visible_on_portal,dealId:s.id}),children:ke.visible_on_portal?e.jsx(Ca,{className:"h-4 w-4"}):e.jsx($g,{className:"h-4 w-4"})})}),e.jsx(Nx,{side:"top",children:ke.visible_on_portal?"Visible on client portal":"Hidden from client portal"})]})}),e.jsx($,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>Se(ke.storage_path,ke.file_name),children:e.jsx(di,{className:"h-4 w-4"})}),e.jsx($,{variant:"ghost",size:"icon",className:"h-8 w-8 text-destructive hover:text-destructive",onClick:()=>Ee(ke.id,ke.storage_path),children:e.jsx(gr,{className:"h-4 w-4"})})]})]},ke.id)}),(x==null?void 0:x.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(Xt,{value:"activity",className:"mt-4 space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(Rs,{placeholder:"Add a note...",value:C,onChange:ke=>E(ke.target.value),rows:2}),e.jsxs($,{onClick:ae,disabled:!C.trim(),size:"sm",className:"w-full",children:[e.jsx(Yr,{className:"h-4 w-4 mr-2"}),"Add Note"]})]}),e.jsxs("div",{className:"space-y-3",children:[o==null?void 0:o.map(ke=>{const Ve=aar[ke.activity_type]||da;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(Ve,{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:ke.title}),ke.description&&e.jsx("p",{className:"text-sm text-muted-foreground mt-0.5",children:ke.description}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:mu(new Date(ke.created_at),{addSuffix:!0})})]})]},ke.id)}),(o==null?void 0:o.length)===0&&e.jsx("p",{className:"text-center text-muted-foreground text-sm py-4",children:"No activity yet"})]})]})]})]})})]})}),e.jsx(nos,{open:R,onOpenChange:D,dealId:s==null?void 0:s.id,dealName:s==null?void 0:s.deal_name}),e.jsx(kc,{open:O,onOpenChange:U,children:e.jsxs(cc,{children:[e.jsxs(dc,{children:[e.jsx(hc,{children:"Delete Deal?"}),e.jsxs(mc,{children:['This will permanently delete "',s.deal_name,'" and all associated data. This action cannot be undone.']})]}),e.jsxs(uc,{children:[e.jsx(fc,{children:"Cancel"}),e.jsx(tc,{onClick:te,className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Delete"})]})]})})]})}function oar({open:s,onOpenChange:t,deal:n,onComplete:r}){const a=T6e(),i=Yrs(),{data:l}=HB(),{data:o}=Yw(),[c,d]=j.useState({property_address:"",city:"",state:"",zip:"",transaction_type:"buyer",close_date:en(new Date,"yyyy-MM-dd"),sale_price:0,commission_amount:0,lead_source_id:"",client_type_id:"",notes:""});j.useEffect(()=>{if(n&&s){const m=n.deal_type==="seller"?"seller":"buyer",f=n.expected_price||0,g=n.commission_percentage||3,x=n.expected_commission||f*g/100;d({property_address:n.property_address||n.deal_name||"",city:n.city||"",state:n.state||"",zip:n.zip_code||"",transaction_type:m,close_date:n.actual_close_date||n.target_close_date||en(new Date,"yyyy-MM-dd"),sale_price:f,commission_amount:x,lead_source_id:"",client_type_id:"",notes:n.notes||""})}},[n,s]);const u=async m=>{if(m.preventDefault(),!!n)try{const f=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:n.brokerage_split_pct||null,team_split_pct:n.team_split_pct||null,franchise_fee_pct:n.franchise_fee_pct||null,referral_fee_pct:n.referral_fee_pct||null,transaction_fee:n.transaction_fee||null,lead_source_id:c.lead_source_id||null,client_type_id:c.client_type_id||null,contact_id:n.contact_id||null,notes:c.notes||null,is_win:!0});await i.mutateAsync({id:n.id,scorecard_transaction_id:f.id,actual_close_date:c.close_date}),re.success("Deal added to Scorecard! 🎉"),t(!1),r==null||r()}catch(f){console.error("Error syncing to scorecard:",f),re.error("Failed to add to scorecard")}},h=m=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",minimumFractionDigits:0,maximumFractionDigits:0}).format(m);return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Os,{className:"sm:max-w-[550px] max-h-[90vh] overflow-y-auto",children:[e.jsxs(Us,{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(Kl,{className:"h-6 w-6 text-green-600 dark:text-green-400"})}),e.jsx(Bs,{className:"text-center text-xl",children:"Congratulations on Closing! 🎉"}),e.jsx(Ir,{className:"text-center",children:"Review and confirm the details before adding this deal to your Scorecard."})]}),e.jsxs("form",{onSubmit:u,className:"space-y-4 mt-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ee,{htmlFor:"property_address",className:"flex items-center gap-2",children:[e.jsx(va,{className:"h-4 w-4 text-muted-foreground"}),"Property Address *"]}),e.jsx(pe,{id:"property_address",value:c.property_address,onChange:m=>d(f=>({...f,property_address:m.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(ee,{htmlFor:"city",children:"City"}),e.jsx(pe,{id:"city",value:c.city,onChange:m=>d(f=>({...f,city:m.target.value})),placeholder:"City"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"state",children:"State"}),e.jsx(pe,{id:"state",value:c.state,onChange:m=>d(f=>({...f,state:m.target.value})),placeholder:"TX",maxLength:2})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"zip",children:"Zip"}),e.jsx(pe,{id:"zip",value:c.zip,onChange:m=>d(f=>({...f,zip:m.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(ee,{children:"Transaction Type *"}),e.jsxs(ms,{value:c.transaction_type,onValueChange:m=>d(f=>({...f,transaction_type:m})),children:[e.jsx(us,{children:e.jsx(fs,{})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"buyer",children:"Buyer"}),e.jsx(Ge,{value:"seller",children:"Seller"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ee,{htmlFor:"close_date",className:"flex items-center gap-2",children:[e.jsx(Ta,{className:"h-4 w-4 text-muted-foreground"}),"Close Date *"]}),e.jsx(pe,{id:"close_date",type:"date",value:c.close_date,onChange:m=>d(f=>({...f,close_date:m.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(ee,{htmlFor:"sale_price",className:"flex items-center gap-2",children:[e.jsx(ru,{className:"h-4 w-4 text-muted-foreground"}),"Sale Price *"]}),e.jsx(pe,{id:"sale_price",type:"number",value:c.sale_price||"",onChange:m=>d(f=>({...f,sale_price:Number(m.target.value)})),placeholder:"450000",required:!0,min:0}),c.sale_price>0&&e.jsx("p",{className:"text-xs text-muted-foreground",children:h(c.sale_price)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ee,{htmlFor:"commission_amount",className:"flex items-center gap-2",children:[e.jsx(Rw,{className:"h-4 w-4 text-muted-foreground"}),"GCI (Commission)"]}),e.jsx(pe,{id:"commission_amount",type:"number",value:c.commission_amount||"",onChange:m=>d(f=>({...f,commission_amount:Number(m.target.value)})),placeholder:"13500",min:0}),c.commission_amount>0&&e.jsx("p",{className:"text-xs text-muted-foreground",children:h(c.commission_amount)})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Lead Source"}),e.jsxs(ms,{value:c.lead_source_id,onValueChange:m=>d(f=>({...f,lead_source_id:m})),children:[e.jsx(us,{children:e.jsx(fs,{placeholder:"Select source"})}),e.jsx(hs,{children:l==null?void 0:l.map(m=>e.jsx(Ge,{value:m.id,children:m.name},m.id))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Client Type"}),e.jsxs(ms,{value:c.client_type_id,onValueChange:m=>d(f=>({...f,client_type_id:m})),children:[e.jsx(us,{children:e.jsx(fs,{placeholder:"Select type"})}),e.jsx(hs,{children:o==null?void 0:o.map(m=>e.jsx(Ge,{value:m.id,children:m.name},m.id))})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"notes",children:"Notes"}),e.jsx(Rs,{id:"notes",value:c.notes,onChange:m=>d(f=>({...f,notes:m.target.value})),placeholder:"Any additional notes about this transaction...",rows:2})]}),e.jsxs(Ar,{className:"gap-2 sm:gap-0 pt-4",children:[e.jsx($,{type:"button",variant:"outline",onClick:()=>t(!1),children:"Skip for now"}),e.jsx($,{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(ei,{className:"ml-2 h-4 w-4"})]})})]})]})]})})}const lar={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"}},sEt={urgent:0,high:1,medium:2,low:3};function car({deals:s,stages:t,onDealClick:n,onStageChange:r}){const[a,i]=j.useState("target_close_date"),[l,o]=j.useState("asc"),c=f=>{a===f?o(g=>g==="asc"?"desc":"asc"):(i(f),o("asc"))},d=j.useMemo(()=>[...s].sort((f,g)=>{var y,v;let x=0;switch(a){case"deal_name":x=f.deal_name.localeCompare(g.deal_name);break;case"stage":{const b=((y=t.find(S=>S.id===f.stage_id))==null?void 0:y.sort_order)||0,w=((v=t.find(S=>S.id===g.stage_id))==null?void 0:v.sort_order)||0;x=b-w;break}case"expected_price":x=(f.expected_price||0)-(g.expected_price||0);break;case"expected_commission":x=(f.expected_commission||0)-(g.expected_commission||0);break;case"target_close_date":{const b=f.target_close_date?Ch(f.target_close_date).getTime():1/0,w=g.target_close_date?Ch(g.target_close_date).getTime():1/0;x=b-w;break}case"priority":x=sEt[f.priority]-sEt[g.priority];break}return l==="asc"?x:-x}),[s,t,a,l]),u=f=>f?new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(f):"—",h=f=>f?t.find(g=>g.id===f):null,m=({field:f,children:g})=>e.jsxs($,{variant:"ghost",size:"sm",className:"h-8 -ml-3 font-medium",onClick:()=>c(f),children:[g,a===f?l==="asc"?e.jsx(Zf,{className:"ml-2 h-4 w-4"}):e.jsx(Dg,{className:"ml-2 h-4 w-4"}):e.jsx(By,{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(mi,{children:[e.jsx(fi,{children:e.jsxs(En,{className:"bg-muted/50",children:[e.jsx(Dt,{className:"w-[250px]",children:e.jsx(m,{field:"deal_name",children:"Deal Name"})}),e.jsx(Dt,{className:"w-[150px]",children:e.jsx(m,{field:"stage",children:"Stage"})}),e.jsx(Dt,{className:"w-[100px]",children:"Type"}),e.jsx(Dt,{className:"w-[120px]",children:e.jsx(m,{field:"expected_price",children:"Price"})}),e.jsx(Dt,{className:"w-[120px]",children:e.jsx(m,{field:"expected_commission",children:"GCI"})}),e.jsx(Dt,{className:"w-[130px]",children:e.jsx(m,{field:"target_close_date",children:"Close Date"})}),e.jsx(Dt,{className:"w-[100px]",children:e.jsx(m,{field:"priority",children:"Priority"})})]})}),e.jsx(pi,{children:d.map(f=>{const g=h(f.stage_id),x=lar[f.deal_type],y=f.target_close_date?mk(Ch(f.target_close_date),new Date):null,v=!!(g!=null&&g.is_won_stage)||!!(g!=null&&g.is_lost_stage)||!!f.actual_close_date,b=!v&&y!==null&&y<0,w=!v&&y!==null&&y<=7&&y>=0;return e.jsxs(En,{className:Pt("cursor-pointer hover:bg-muted/50 transition-colors",b&&"bg-red-50/50"),onClick:()=>n(f),children:[e.jsx(wt,{className:"font-medium",children:e.jsxs("div",{children:[e.jsx("p",{className:"truncate max-w-[230px]",children:f.deal_name}),f.contact&&e.jsxs("p",{className:"text-xs text-muted-foreground truncate",children:[f.contact.first_name," ",f.contact.last_name]})]})}),e.jsx(wt,{onClick:S=>S.stopPropagation(),children:e.jsx(Jrs,{stages:t,currentStageId:f.stage_id||"",onStageSelect:(S,C)=>r(f.id,S,C)})}),e.jsx(wt,{children:e.jsx(Be,{variant:"outline",className:Pt("text-xs",x.color),children:x.label})}),e.jsx(wt,{children:e.jsx("span",{className:"font-medium",children:u(f.expected_price)})}),e.jsx(wt,{children:e.jsx("span",{className:"text-emerald-600",children:u(f.expected_commission)})}),e.jsx(wt,{children:f.target_close_date?e.jsxs("div",{className:Pt("flex items-center gap-1 text-sm",b&&"text-red-600",w&&!b&&"text-amber-600"),children:[b&&e.jsx(ll,{className:"h-3.5 w-3.5"}),e.jsx("span",{children:en(Ch(f.target_close_date),"MMM d, yyyy")})]}):e.jsx("span",{className:"text-muted-foreground",children:"—"})}),e.jsx(wt,{children:e.jsx(Be,{variant:"outline",className:Pt("text-xs capitalize",f.priority==="urgent"&&"border-red-200 bg-red-50 text-red-700",f.priority==="high"&&"border-orange-200 bg-orange-50 text-orange-700",f.priority==="medium"&&"border-amber-200 bg-amber-50 text-amber-700",f.priority==="low"&&"border-slate-200 bg-slate-50 text-slate-600"),children:f.priority})})]},f.id)})})]})})}function ros(){const s=Sa();return tt({queryKey:["deal-tasks",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await q.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(n)throw n;return t},enabled:!!s})}function dar(s){const t=Sa();return tt({queryKey:["deal-tasks","deal",s,t],queryFn:async()=>{if(!t||!s)return[];const{data:n,error:r}=await q.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(r)throw r;return n},enabled:!!t&&!!s})}function uar(){const s=Sa(),t=Vt();return ft({mutationFn:async n=>{if(!s)throw new Error("Not authenticated");const{data:r,error:a}=await q.from("deal_tasks").insert({owner_user_id:s,title:n.title,description:n.description||null,deal_id:n.deal_id||null,contact_id:n.contact_id||null,stage_id:n.stage_id||null,priority:n.priority||"medium",status:n.status||"todo",due_date:n.due_date||null,sort_order:n.sort_order||0}).select().single();if(a)throw a;return r},onSuccess:()=>{t.invalidateQueries({queryKey:["deal-tasks"]})}})}function har(){const s=Vt();return ft({mutationFn:async({id:t,...n})=>{const{data:r,error:a}=await q.from("deal_tasks").update(n).eq("id",t).select().single();if(a)throw a;return r},onSuccess:()=>{s.invalidateQueries({queryKey:["deal-tasks"]})}})}function mar(){const s=Vt();return ft({mutationFn:async t=>{const{error:n}=await q.from("deal_tasks").delete().eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["deal-tasks"]})}})}function fFe(){const s=Vt();return ft({mutationFn:async({id:t,status:n})=>{const{data:r,error:a}=await q.from("deal_tasks").update({status:n,completed_at:n==="done"?new Date().toISOString():null}).eq("id",t).select().single();if(a)throw a;return r},onSuccess:()=>{s.invalidateQueries({queryKey:["deal-tasks"]})}})}function far(){const s=Vt();return ft({mutationFn:async t=>{if(t.length===0)return;const{error:n}=await q.from("deal_tasks").update({status:"done",completed_at:new Date().toISOString()}).in("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["deal-tasks"]})}})}function par(s){const t=Sa();return tt({queryKey:["deal-task-templates",t,s],queryFn:async()=>{if(!t)return[];let n=q.from("deal_task_templates").select("*").eq("owner_user_id",t).order("sort_order",{ascending:!0});s&&(n=n.eq("stage_id",s));const{data:r,error:a}=await n;if(a)throw a;return r},enabled:!!t})}function gar(){const s=Sa(),t=Vt();return ft({mutationFn:async n=>{if(!s)throw new Error("Not authenticated");const{data:r,error:a}=await q.from("deal_task_templates").insert({owner_user_id:s,stage_id:n.stage_id,title:n.title,description:n.description||null,priority:n.priority||"medium",default_due_offset_days:n.default_due_offset_days||null,sort_order:n.sort_order||0}).select().single();if(a)throw a;return r},onSuccess:()=>{t.invalidateQueries({queryKey:["deal-task-templates"]})}})}function xar(){const s=Vt();return ft({mutationFn:async t=>{const{error:n}=await q.from("deal_task_templates").delete().eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["deal-task-templates"]})}})}function yar(){const s=Sa(),t=Vt();return ft({mutationFn:async({dealId:n,stageId:r})=>{if(!s)throw new Error("Not authenticated");const{data:a,error:i}=await q.from("deal_task_templates").select("*").eq("owner_user_id",s).eq("stage_id",r).order("sort_order");if(i)throw i;if(!a||a.length===0)return[];const{data:l}=await q.from("deal_tasks").select("title, stage_id").eq("deal_id",n).eq("stage_id",r),o=new Set((l||[]).map(h=>h.title)),c=a.filter(h=>!o.has(h.title)).map((h,m)=>({owner_user_id:s,deal_id:n,stage_id:r,title:h.title,description:h.description,priority:h.priority,due_date:h.default_due_offset_days?new Date(Date.now()+h.default_due_offset_days*864e5).toISOString().split("T")[0]:null,sort_order:m,status:"todo"}));if(c.length===0)return[];const{data:d,error:u}=await q.from("deal_tasks").insert(c).select();if(u)throw u;return d},onSuccess:()=>{t.invalidateQueries({queryKey:["deal-tasks"]})}})}const bar={urgent:"🔴",high:"🟠",medium:"🟡",low:"🟢"};function _ar({open:s,onOpenChange:t,dealId:n,dealName:r,fromStageName:a,toStageName:i,toStageId:l,onConfirm:o}){const{data:c,isLoading:d}=dar(s?n:void 0),u=far(),h=yar(),[m,f]=j.useState(new Set),[g,x]=j.useState(!1),y=(c||[]).filter(S=>S.status!=="done");j.useEffect(()=>{y.length>0&&f(new Set(y.map(S=>S.id)))},[c]);const v=S=>{f(C=>{const E=new Set(C);return E.has(S)?E.delete(S):E.add(S),E})},b=async()=>{x(!0);try{const S=Array.from(m);S.length>0&&await u.mutateAsync(S),await o(),await h.mutateAsync({dealId:n,stageId:l}),t(!1)}catch(S){console.error("Stage move failed:",S),re.error((S==null?void 0:S.message)||"Failed to move deal. Please try again.")}finally{x(!1)}},w=async()=>{x(!0);try{await o(),await h.mutateAsync({dealId:n,stageId:l}),t(!1)}catch(S){console.error("Stage move (skip) failed:",S),re.error((S==null?void 0:S.message)||"Failed to move deal. Please try again.")}finally{x(!1)}};return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Os,{className:"sm:max-w-[480px]",children:[e.jsxs(Us,{children:[e.jsx(Bs,{children:"Move Deal"}),e.jsxs(Ir,{children:["Moving ",e.jsx("span",{className:"font-medium text-foreground",children:r})]})]}),e.jsxs("div",{className:"flex items-center justify-center gap-3 py-2",children:[e.jsx(Be,{variant:"outline",className:"text-sm",children:a}),e.jsx(ei,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(Be,{className:"text-sm bg-primary",children:i})]}),d?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx(kt,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):y.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:y.length})," incomplete task",y.length!==1?"s":"",". Select which to mark as done:"]}),e.jsx(uo,{className:"max-h-[250px]",children:e.jsx("div",{className:"space-y-1",children:y.map(S=>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(ai,{checked:m.has(S.id),onCheckedChange:()=>v(S.id)}),e.jsxs("span",{className:"text-sm flex-1",children:[bar[S.priority]," ",S.title]}),S.stage&&e.jsx("span",{className:"text-[10px] px-1.5 py-0.5 rounded-full",style:{backgroundColor:S.stage.color+"20",color:S.stage.color},children:S.stage.name})]},S.id))})}),e.jsxs("div",{className:"flex items-center justify-between gap-2 pt-2",children:[e.jsx($,{variant:"ghost",size:"sm",onClick:()=>{m.size===y.length?f(new Set):f(new Set(y.map(S=>S.id)))},children:m.size===y.length?"Deselect All":"Select All"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx($,{variant:"outline",size:"sm",onClick:w,disabled:g,children:"Skip"}),e.jsxs($,{size:"sm",onClick:b,disabled:g,children:[g&&e.jsx(kt,{className:"h-4 w-4 mr-1 animate-spin"}),m.size>0?`Complete ${m.size} & Move`:"Move Deal"]})]})]})]}):e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"text-center py-4",children:[e.jsx(qr,{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($,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsxs($,{onClick:b,disabled:g,children:[g&&e.jsx(kt,{className:"h-4 w-4 mr-1 animate-spin"}),"Move to ",i]})]})]})]})})}const war=[{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"}],jar=[{id:"noir",name:"Luxury — Noir & Gold",description:"Dark, editorial, high-end concierge feel.",bg:"#0d0d0d",surface:"#171717",accent:"#c9a84c",ink:"#f5f2ea"},{id:"azure",name:"Professional Blue",description:"Light, clean and corporate — easy to read.",bg:"#f5f8fc",surface:"#ffffff",accent:"#1259ce",ink:"#1a2433"}];function aos({open:s,onOpenChange:t}){const n=Sa(),{data:r,isLoading:a}=l$t(),i=q9s(),[l,o]=j.useState({logo_url:null,cover_photo_url:null,brand_color:null,accent_color:null,tagline:null,welcome_message:null,portal_theme:"noir"}),[c,d]=j.useState(null);j.useEffect(()=>{s&&o({logo_url:(r==null?void 0:r.logo_url)??null,cover_photo_url:(r==null?void 0:r.cover_photo_url)??null,brand_color:(r==null?void 0:r.brand_color)??null,accent_color:(r==null?void 0:r.accent_color)??null,tagline:(r==null?void 0:r.tagline)??null,welcome_message:(r==null?void 0:r.welcome_message)??null,portal_theme:(r==null?void 0:r.portal_theme)??"noir"})},[s,r]);const u=f=>o(g=>({...g,...f})),h=async(f,g)=>{if(n){if(f.size>5*1024*1024){re.error("Image must be under 5MB");return}d(g);try{const x=await c$t(n,f,g);u(g==="logo"?{logo_url:x}:{cover_photo_url:x})}catch(x){re.error(`Upload failed: ${x.message||x}`)}finally{d(null)}}},m=async()=>{try{await i.mutateAsync(l),re.success("Portal branding saved"),t(!1)}catch{re.error("Failed to save branding")}};return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Os,{className:"max-w-lg max-h-[90vh] flex flex-col",children:[e.jsxs(Us,{children:[e.jsxs(Bs,{className:"flex items-center gap-2",children:[e.jsx(Yc,{className:"h-5 w-5 text-primary"}),"Portal Branding"]}),e.jsx(Ir,{children:"Customize how your client portals look. These defaults apply to every portal — you can override them per deal."})]}),e.jsx(uo,{className:"flex-1 pr-3 -mr-3",children:a?e.jsx("div",{className:"py-12 flex justify-center",children:e.jsx(kt,{className:"h-5 w-5 animate-spin text-muted-foreground"})}):e.jsxs("div",{className:"space-y-6 py-2",children:[e.jsx(Nar,{draft:l}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(ee,{className:"text-sm font-medium",children:"Portal Theme"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"The overall look and feel your clients see when they open their portal."})]}),e.jsx("div",{className:"grid grid-cols-2 gap-3",children:jar.map(f=>{const g=(l.portal_theme??"noir")===f.id;return e.jsxs("button",{type:"button",onClick:()=>u({portal_theme:f.id}),className:Pt("rounded-xl border-2 p-3 text-left transition-all",g?"border-primary ring-2 ring-primary/20":"border-input hover:border-primary/40"),children:[e.jsx("div",{className:"rounded-lg overflow-hidden mb-2",style:{background:f.bg},children:e.jsxs("div",{className:"p-3 space-y-1.5",children:[e.jsx("div",{className:"h-1.5 w-10 rounded-full",style:{background:f.accent}}),e.jsx("div",{className:"h-2.5 w-20 rounded",style:{background:f.ink,opacity:.85}}),e.jsx("div",{className:"h-6 rounded-md",style:{background:f.surface,border:`1px solid ${f.accent}44`}})]})}),e.jsx("div",{className:"text-sm font-medium text-foreground",children:f.name}),e.jsx("div",{className:"text-[11px] text-muted-foreground leading-snug",children:f.description})]},f.id)})})]}),e.jsx(nEt,{label:"Logo",hint:"Shown above your name on the portal. PNG with transparent background works best.",value:l.logo_url,uploading:c==="logo",onUpload:f=>h(f,"logo"),onClear:()=>u({logo_url:null}),aspect:"square"}),e.jsx(nEt,{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:f=>h(f,"cover"),onClear:()=>u({cover_photo_url:null}),aspect:"cover"}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(ee,{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:war.map(f=>{const g=l.brand_color===f.brand&&l.accent_color===f.accent;return e.jsxs("button",{type:"button",onClick:()=>u({brand_color:f.brand,accent_color:f.accent}),className:Pt("group relative rounded-lg border-2 p-2 text-left transition-all",g?"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:f.brand}}),e.jsx("div",{className:"flex-1",style:{background:f.accent}})]}),e.jsx("div",{className:"text-[11px] mt-1.5 font-medium text-foreground",children:f.name})]},f.name)})}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsx(rEt,{label:"Brand",value:l.brand_color,onChange:f=>u({brand_color:f})}),e.jsx(rEt,{label:"Accent",value:l.accent_color,onChange:f=>u({accent_color:f})})]})]}),e.jsxs("div",{children:[e.jsx(ee,{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(pe,{value:l.tagline||"",onChange:f=>u({tagline:f.target.value}),placeholder:"Your trusted real estate advisor",maxLength:80})]}),e.jsxs("div",{children:[e.jsx(ee,{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:f=>u({welcome_message:f.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($,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsxs($,{onClick:m,disabled:i.isPending,children:[i.isPending?e.jsx(kt,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(tl,{className:"h-4 w-4 mr-2"}),"Save Branding"]})]})]})})}function Nar({draft:s}){const t=s.brand_color||"#2a4c64",n=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, ${n}cc), url(${s.cover_photo_url}) center/cover`:`linear-gradient(135deg, ${t}, ${n})`},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 nEt({label:s,hint:t,value:n,uploading:r,onUpload:a,onClear:i,aspect:l}){return e.jsxs("div",{children:[e.jsx(ee,{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:Pt("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:n?e.jsx("img",{src:n,alt:s,className:"h-full w-full object-cover"}):e.jsx(Mc,{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:[r?e.jsx(kt,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(ni,{className:"h-3.5 w-3.5"}),n?"Replace":"Upload"]})]}),n&&e.jsx($,{variant:"ghost",size:"sm",onClick:i,className:"text-muted-foreground hover:text-destructive",children:e.jsx(Wn,{className:"h-3.5 w-3.5"})})]})]})]})}function rEt({label:s,value:t,onChange:n}){const r=t||"#000000";return e.jsxs("div",{children:[e.jsx(ee,{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:r,onChange:a=>n(a.target.value),className:"h-6 w-8 rounded cursor-pointer border-0 bg-transparent"}),e.jsx(pe,{value:t||"",onChange:a=>n(a.target.value||null),placeholder:"#406E71",className:"border-0 h-7 px-1 focus-visible:ring-0 text-xs font-mono"})]})]})}function kar(){const s=Sa();return tt({queryKey:["all-client-portals",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await q.from("client_portals").select("*").eq("owner_user_id",s);if(n)throw n;return t||[]},enabled:!!s})}function Sar({dealId:s,dealName:t,contactName:n,portal:r,onSettingsOpen:a,onComposerOpen:i,onInviteOpen:l,onDeleteConfirm:o}){const c=Cit(),d=UK(),u=oJt(),h=lJt(),[m,f]=j.useState(!1),g=!!(r!=null&&r.archived_at),x=async()=>{f(!0);try{await c.mutateAsync({deal_id:s,visibility:"private",require_onboarding:!0}),re.success("Portal enabled!")}catch{re.error("Failed to create portal")}finally{f(!1)}},y=async C=>{if(r)try{await d.mutateAsync({id:r.id,is_enabled:C}),re.success(C?"Portal enabled":"Portal disabled")}catch{re.error("Failed to update portal")}},v=()=>{r&&(navigator.clipboard.writeText(dC(r.slug)),re.success("Link copied!"))},b=()=>{r&&window.open(dC(r.slug),"_blank")},w=async()=>{if(r)try{await u.mutateAsync(r.id),re.success("Portal archived")}catch{re.error("Failed to archive portal")}},S=async()=>{if(r)try{await h.mutateAsync(r.id),re.success("Portal restored")}catch{re.error("Failed to restore portal")}};return r?g?e.jsxs("div",{className:"flex items-center gap-4 p-4 border rounded-lg opacity-60 bg-muted/30",children:[e.jsxs(wr,{to:`/mission-control/client-portals/${r.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(Be,{variant:"outline",className:"text-[10px] bg-muted text-muted-foreground",children:"Archived"})]}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:r.client_name||n||"No client name"})]}),e.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[e.jsxs($,{variant:"ghost",size:"sm",onClick:S,className:"text-xs gap-1",children:[e.jsx(UI,{className:"h-3.5 w-3.5"}),"Restore"]}),e.jsxs($,{variant:"ghost",size:"sm",onClick:()=>o(r),className:"text-xs gap-1 text-destructive hover:text-destructive",children:[e.jsx(Wn,{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(wr,{to:`/mission-control/client-portals/${r.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(Be,{variant:"outline",className:r.is_enabled?"text-[10px] bg-emerald-500/10 text-emerald-600 border-emerald-200":"text-[10px] bg-muted text-muted-foreground",children:r.is_enabled?"Active":"Disabled"}),e.jsx(Di,{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:r.client_name||n||"No client name"})]}),e.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[e.jsx($,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:v,title:"Copy link",children:e.jsx(Ha,{className:"h-3.5 w-3.5"})}),e.jsx($,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:b,title:"Preview",children:e.jsx(kr,{className:"h-3.5 w-3.5"})}),e.jsx($,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>l(r,t),title:"Invite client",children:e.jsx(Yr,{className:"h-3.5 w-3.5"})}),e.jsx($,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>i(r),title:"Post update",children:e.jsx(p4,{className:"h-3.5 w-3.5"})}),e.jsx($,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>a(r),title:"Settings",children:e.jsx(Sd,{className:"h-3.5 w-3.5"})}),e.jsxs(Uu,{children:[e.jsx(qu,{asChild:!0,children:e.jsx($,{variant:"ghost",size:"icon",className:"h-8 w-8",children:e.jsx(h_,{className:"h-3.5 w-3.5"})})}),e.jsx(Eu,{align:"end",children:e.jsxs(ja,{onClick:w,children:[e.jsx(Sv,{className:"h-4 w-4 mr-2"}),"Archive Portal"]})})]}),e.jsx(Sn,{checked:r.is_enabled,onCheckedChange:y,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:n||"No contact"})]}),e.jsxs($,{size:"sm",onClick:x,disabled:m,className:"shrink-0 ml-4",children:[m?e.jsx(kt,{className:"h-3 w-3 animate-spin mr-1"}):e.jsx(Nn,{className:"h-3 w-3 mr-1"}),"Enable Portal"]})]})}function ios(){const{data:s,isLoading:t}=rY(),{data:n,isLoading:r}=kar(),[a,i]=j.useState(""),[l,o]=j.useState("all"),c=cJt(),[d,u]=j.useState(null),[h,m]=j.useState(null),[f,g]=j.useState(null),[x,y]=j.useState(null),[v,b]=j.useState(!1),w=Sa(),S=t||r,C=new Map;n==null||n.forEach(U=>C.set(U.deal_id,U));const I=[...(s||[]).filter(U=>{var X,ae,ie,ne,te;const W=C.get(U.id),V=a.toLowerCase(),G=!V||U.deal_name.toLowerCase().includes(V)||((ae=(X=U.contact)==null?void 0:X.first_name)==null?void 0:ae.toLowerCase().includes(V))||((ne=(ie=U.contact)==null?void 0:ie.last_name)==null?void 0:ne.toLowerCase().includes(V))||((te=W==null?void 0:W.client_name)==null?void 0:te.toLowerCase().includes(V));let Y=!0;return l==="active"?Y=!!(W!=null&&W.is_enabled)&&!(W!=null&&W.archived_at):l==="disabled"?Y=!!W&&!W.is_enabled&&!W.archived_at:l==="archived"?Y=!!(W!=null&&W.archived_at):l==="none"?Y=!W:l==="all"&&(Y=!(W!=null&&W.archived_at)||!W),G&&Y})].sort((U,W)=>{const V=C.get(U.id),G=C.get(W.id);if(V!=null&&V.archived_at&&!(G!=null&&G.archived_at))return 1;if(!(V!=null&&V.archived_at)&&(G!=null&&G.archived_at)||V&&!G)return-1;if(!V&&G)return 1;if(V&&G){if(V.is_enabled&&!G.is_enabled)return-1;if(!V.is_enabled&&G.is_enabled)return 1}return 0}),P=(n==null?void 0:n.filter(U=>!U.archived_at).length)||0,R=(n==null?void 0:n.filter(U=>U.is_enabled&&!U.archived_at).length)||0,D=(n==null?void 0:n.filter(U=>U.archived_at).length)||0,O=async()=>{if(x)try{await c.mutateAsync({id:x.id,dealId:x.deal_id}),re.success("Portal permanently deleted"),y(null)}catch{re.error("Failed to delete portal")}};return S?e.jsx("div",{className:"flex items-center justify-center py-16",children:e.jsx(kt,{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(Nn,{className:"h-4 w-4 text-primary"}),e.jsxs("span",{className:"font-medium",children:[P," Portals"]})]}),e.jsxs("span",{className:"text-muted-foreground",children:[R," active · ",P-R," disabled",D>0&&` · ${D} archived`]})]}),e.jsxs($,{variant:"outline",size:"sm",onClick:()=>b(!0),className:"gap-1.5",children:[e.jsx(Yc,{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(Kr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(pe,{placeholder:"Search deals or clients...",value:a,onChange:U=>i(U.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(gr,{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(U=>e.jsx($,{variant:l===U?"secondary":"ghost",size:"sm",onClick:()=>o(U),className:"text-xs px-3 capitalize",children:U==="none"?"No Portal":U},U))})]}),e.jsx(uo,{className:"h-[calc(100vh-22rem)]",children:e.jsxs("div",{className:"space-y-2 pb-4",children:[I.map(U=>{const W=C.get(U.id)||null,V=U.contact?`${U.contact.first_name||""} ${U.contact.last_name||""}`.trim():"";return e.jsx(Sar,{dealId:U.id,dealName:U.deal_name,contactName:V,portal:W,onSettingsOpen:u,onComposerOpen:G=>m(G),onInviteOpen:(G,Y)=>g({portal:G,dealName:Y}),onDeleteConfirm:y},U.id)}),I.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(Nn,{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(Flt,{open:!!d,onOpenChange:U=>!U&&u(null),portal:d,dealOwnerId:w||""}),h&&e.jsx(Olt,{open:!!h,onOpenChange:U=>!U&&m(null),portalId:h.id,portalSlug:h.slug,notifyClient:h.notify_client}),f&&e.jsx(zlt,{open:!!f,onOpenChange:U=>!U&&g(null),portal:f.portal,dealName:f.dealName}),e.jsx(aos,{open:v,onOpenChange:b}),e.jsx(kc,{open:!!x,onOpenChange:U=>!U&&y(null),children:e.jsxs(cc,{children:[e.jsxs(dc,{children:[e.jsx(hc,{children:"Permanently delete this portal?"}),e.jsx(mc,{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(uc,{children:[e.jsx(fc,{children:"Cancel"}),e.jsx(tc,{onClick:O,className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Delete Permanently"})]})]})})]})}function Car({summary:s,stats:t,search:n,onSearchChange:r,onAddDeal:a,onRefresh:i,onTeam:l,viewControls:o,filters:c,activeFilters:d=[],onClearAll:u,resultLabel:h,showSearch:m=!0}){return e.jsx("section",{className:"hub-ink relative overflow-hidden rounded-2xl p-4 sm:p-6",children:e.jsxs("div",{className:"relative flex flex-col gap-4",children:[e.jsxs("div",{className:"flex flex-col gap-3 lg:flex-row lg:items-start lg:justify-between",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-xs uppercase tracking-wider hub-ink-muted",children:"Agent OS"}),e.jsx("h1",{className:"mt-1 text-2xl font-bold sm:text-3xl",children:"Deal Pipeline"}),e.jsx("p",{className:"mt-1 text-sm hub-ink-muted",children:s})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs("button",{onClick:a,className:"inline-flex items-center gap-2 rounded-full bg-background px-4 py-2 text-sm font-semibold text-foreground shadow-sm transition-transform hover:scale-[1.02]",children:[e.jsx(dn,{className:"h-4 w-4"}),"Add Deal"]}),l&&e.jsxs("button",{onClick:l,className:"hub-glass inline-flex items-center gap-2 rounded-full px-4 py-2 text-sm font-medium transition-colors",children:[e.jsx(Zn,{className:"h-4 w-4",style:{color:"hsl(var(--hub-glow))"}}),"Team"]}),e.jsx("button",{onClick:i,"aria-label":"Refresh pipeline",className:"hub-glass inline-flex h-9 w-9 items-center justify-center rounded-full transition-colors",children:e.jsx(ro,{className:"h-4 w-4"})}),o]})]}),t.length>0&&e.jsx("div",{className:"-mx-1 flex gap-2 overflow-x-auto px-1 pb-1 sm:grid sm:grid-cols-3 sm:overflow-visible lg:grid-cols-5",children:t.map(f=>{const g=f.onClick?"button":"div";return e.jsxs(g,{type:f.onClick?"button":void 0,onClick:f.onClick,title:f.hint,className:Pt("hub-glass min-w-[130px] shrink-0 rounded-xl px-3 py-2.5 text-left transition-all sm:min-w-0",f.onClick&&"hover:scale-[1.02]",f.active&&"ring-2"),style:f.active?{boxShadow:"0 0 0 2px hsl(var(--hub-glow))"}:void 0,children:[e.jsx("p",{className:"text-[11px] uppercase tracking-wide hub-ink-muted",children:f.label}),e.jsx("p",{className:"mt-0.5 text-lg font-bold leading-tight",children:f.value}),f.subtitle&&e.jsx("p",{className:"text-[11px] hub-ink-muted",children:f.subtitle})]},f.label)})}),m&&e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs("div",{className:"relative min-w-[200px] flex-1 sm:max-w-sm",children:[e.jsx(Kr,{className:"pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 opacity-70"}),e.jsx("input",{value:n,onChange:f=>r(f.target.value),placeholder:"Search deals, contacts, addresses, tags...",className:"hub-glass h-10 w-full rounded-full border-0 pl-9 pr-8 text-sm outline-none placeholder:opacity-60 focus:ring-2 focus:ring-white/30"}),n&&e.jsx("button",{onClick:()=>r(""),"aria-label":"Clear search",className:"absolute right-3 top-1/2 -translate-y-1/2 opacity-70 hover:opacity-100",children:e.jsx(gr,{className:"h-4 w-4"})})]}),c]}),(d.length>0||h)&&e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[d.map(f=>e.jsxs("button",{onClick:f.onClear,className:"hub-glass inline-flex items-center gap-1.5 rounded-full px-3 py-1 text-xs font-medium",children:[f.label,e.jsx(gr,{className:"h-3 w-3 opacity-70"})]},f.key)),d.length>0&&u&&e.jsx("button",{onClick:u,className:"text-xs font-medium underline underline-offset-2 hub-ink-muted hover:opacity-90",children:"Clear all"}),h&&e.jsx("span",{className:"text-xs hub-ink-muted",children:h})]})]})]})})}const Aar={closing_soon:{label:"Closing in 7 days",icon:Au,tone:"text-primary"},past_due:{label:"Past close date",icon:wl,tone:"text-destructive"},overdue_tasks:{label:"Overdue tasks",icon:Kj,tone:"text-amber-600 dark:text-amber-400"},stalled:{label:"Stalled 14+ days",icon:LJ,tone:"text-muted-foreground"}};function Ear({items:s,active:t,onToggle:n}){const r=s.filter(a=>a.count>0);return r.length===0?null:e.jsxs("div",{className:"-mx-1 flex items-center gap-2 overflow-x-auto px-1 pb-1",children:[e.jsx("span",{className:"shrink-0 text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:"Needs attention"}),r.map(({key:a,count:i})=>{const l=Aar[a],o=l.icon,c=t===a;return e.jsxs("button",{onClick:()=>n(a),className:Pt("inline-flex shrink-0 items-center gap-1.5 rounded-full border px-3 py-1.5 text-xs font-medium transition-colors",c?"border-primary bg-primary/10 text-primary":"border-border bg-card text-foreground hover:bg-accent"),children:[e.jsx(o,{className:Pt("h-3.5 w-3.5",!c&&l.tone)}),l.label,e.jsx("span",{className:Pt("ml-0.5 rounded-full px-1.5 text-[10px] font-bold",c?"bg-primary text-primary-foreground":"bg-muted text-muted-foreground"),children:i})]},a)})]})}const I7=s=>{const t=Number(s);return Number.isFinite(t)?t:0};function LC(s){if(!s)return null;const[t,n,r]=s.split(/[-/T]/).map(a=>parseInt(a,10));return!t||!n||!r?null:{y:t,m:n,d:r}}function MW(s){return I7(s.sale_price)||I7(s.expected_price)}function PW(s){const t=I7(s.expected_commission);if(t>0)return t;const n=I7(s.commission_percentage);return n>0?MW(s)*n/100:0}function Lne(s){const t=PW(s);return t*I7(s.brokerage_split_pct)/100+t*I7(s.franchise_fee_pct)/100+I7(s.transaction_fee)}const Tar=s=>!!s.actual_close_date,Mar=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function Par(s){const t=new Date,n=t.getFullYear(),r=t.getMonth()+1,a=n*1e4+r*100+t.getDate(),i=new Date(t.getTime()+30*864e5),l=i.getFullYear()*1e4+(i.getMonth()+1)*100+i.getDate(),o={activeDeals:0,closedThisYear:0,pipelineVolume:0,pipelineGci:0,brokerageShare:0,closingThisMonth:0,closingNext30:0,closedVolumeThisYear:0,closedCompanyDollarYtd:0,needsReview:0,changesRequested:0,overdueItems:0,agents:[],outlook:[],totalVolume:0},c=new Map,d=new Map;for(let u=0;u<6;u++){const h=(r-1+u)%12+1,m=n+Math.floor((r-1+u)/12),f=`${m}-${String(h).padStart(2,"0")}`;d.set(f,{key:f,label:`${Mar[h-1]} ${String(m).slice(2)}`,deals:0,volume:0,gci:0,closed:!1})}return s.forEach(u=>{const h=MW(u),m=PW(u),f=Tar(u);o.totalVolume+=h,o.overdueItems+=u.overdue_items,u.submitted_items>0&&(o.needsReview+=1),u.rejected_items>0&&(o.changesRequested+=1);const g=LC(u.actual_close_date||u.target_close_date);if(f)(g==null?void 0:g.y)===n&&(o.closedThisYear+=1,o.closedVolumeThisYear+=h,o.closedCompanyDollarYtd+=Lne(u));else if(o.activeDeals+=1,o.pipelineVolume+=h,o.pipelineGci+=m,o.brokerageShare+=Lne(u),g){const y=g.y*1e4+g.m*100+g.d;g.y===n&&g.m===r&&(o.closingThisMonth+=1),y>=a&&y<=l&&(o.closingNext30+=1)}if(g){const y=`${g.y}-${String(g.m).padStart(2,"0")}`,v=d.get(y);v&&(v.deals+=1,v.volume+=h,v.gci+=m,f&&(v.closed=!0))}const x=c.get(u.owner_user_id)||{userId:u.owner_user_id,name:u.agent_name||"Agent",avatarUrl:u.agent_avatar_url,activeDeals:0,closedDeals:0,volume:0,gci:0,overdue:0};f?x.closedDeals+=1:x.activeDeals+=1,x.volume+=h,x.gci+=m,x.overdue+=u.overdue_items,c.set(u.owner_user_id,x)}),o.agents=Array.from(c.values()).sort((u,h)=>h.volume-u.volume||h.activeDeals-u.activeDeals),o.outlook=Array.from(d.values()).sort((u,h)=>u.key.localeCompare(h.key)),o}function Wf(s){return s?Math.abs(s)>=1e6?`$${(s/1e6).toFixed(1)}M`:Math.abs(s)>=1e3?`$${Math.round(s/1e3)}K`:`$${Math.round(s).toLocaleString()}`:"$0"}function Iar(){var i;const{user:s}=vs(),{data:t}=tas(),{data:n}=YQn(t?s==null?void 0:s.id:null);if(!t)return null;const{plan:r}=t,a=Math.max(0,100-r.agent_split_pct);return e.jsx(Ne,{className:"border-border/60",children:e.jsxs(Ie,{className:"flex flex-col gap-3 p-4 sm:flex-row sm:items-center sm:gap-6",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("span",{className:"flex h-9 w-9 shrink-0 items-center justify-center rounded-lg bg-teal-500/10 text-teal-600",children:e.jsx(Rw,{className:"h-4.5 w-4.5"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Your commission plan"}),e.jsx("p",{className:"text-sm font-semibold",children:r.name})]})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-x-5 gap-y-1 text-[12px] text-muted-foreground",children:[e.jsxs("span",{children:[e.jsxs("span",{className:"font-medium text-foreground",children:[r.agent_split_pct,"/",a]})," split"]}),r.transaction_fee>0&&e.jsxs("span",{children:[e.jsxs("span",{className:"font-medium text-foreground",children:["$",r.transaction_fee.toLocaleString()]})," per deal"]}),r.franchise_fee_pct>0&&e.jsxs("span",{children:[e.jsxs("span",{className:"font-medium text-foreground",children:[r.franchise_fee_pct,"%"]})," franchise fee"]}),(r.team_split_pct??0)>0&&e.jsxs("span",{children:[e.jsxs("span",{className:"font-medium text-foreground",children:[r.team_split_pct,"%"]})," team split"]})]}),r.cap_amount&&n&&e.jsxs("div",{className:"min-w-[200px] flex-1",children:[e.jsxs("div",{className:"mb-1 flex justify-between text-[11px] text-muted-foreground",children:[e.jsxs("span",{children:["$",Math.round(n.cap_progress).toLocaleString()," of ",Wf(r.cap_amount)," cap"]}),e.jsxs("span",{children:[Math.round(n.pct_to_cap??0),"%"]})]}),e.jsx(Yi,{value:Math.min(100,n.pct_to_cap??0),className:"h-1.5"}),e.jsxs("p",{className:"mt-1 text-[11px] text-muted-foreground",children:["Resets ",((i=n.anniversary_year_end)==null?void 0:i.split(/[-/T]/).slice(0,3).join("/"))||"annually"]})]})]})})}class Lar extends j.Component{constructor(t){super(t),this.state={hasError:!1,error:null}}static getDerivedStateFromError(t){return{hasError:!0,error:t}}componentDidCatch(t,n){console.error("DealPipeline error:",t,n)}render(){return this.state.hasError?e.jsx(Vs,{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 SX="deal-pipeline-detail-sheet";function CX(s){return s>=1e6?`$${(s/1e6).toFixed(1)}M`:s>=1e3?`$${(s/1e3).toFixed(0)}K`:`$${Math.round(s).toLocaleString()}`}function Rar(){var Er;const s=$K(),{data:t,isLoading:n}=Jie(),{data:r,isLoading:a,refetch:i}=rY(),{data:l,isLoading:o}=nQn(),c=Wrs(),d=ZXn(),[u,h]=j.useState("board"),[m,f]=j.useState(!1),[g,x]=j.useState(!1),[y,v]=j.useState(null),[b,w]=j.useState(null),[S,C]=j.useState(null),[E,I]=j.useState(null),[P,R]=j.useState(!1),[D,O]=j.useState(null),[U,W]=j.useState(""),[V,G]=j.useState("all"),[Y,X]=j.useState("all"),[ae,ie]=j.useState("all"),[ne,te]=j.useState(null),{data:J}=ros(),{data:ce}=qQn(),[_e,he]=j.useState(!1),[ue,ve]=j.useState(!1),[Ee,Se]=j.useState(new Set),[Le,Fe]=j.useState(!0),ke=j.useRef(!1),[Ve,je]=j.useState(null),{data:Ae}=Hw(),{isTeamLeader:Ce,teamMembers:qe}=$Qn(),ze=j.useMemo(()=>Array.from(Ee),[Ee]),{data:$e}=UQn(ze),ct=j.useMemo(()=>{const qn=new Map;return qe.forEach(hn=>qn.set(hn.id,{name:hn.name,avatar_url:hn.avatar_url,color:hn.color})),qn},[qe]),Xe=j.useCallback(qn=>qn.owner_user_id&&ct.get(qn.owner_user_id)||null,[ct]),it=j.useCallback(qn=>{Se(hn=>{const Fn=new Set(hn);return Fn.has(qn)?Fn.delete(qn):Fn.add(qn),Fn})},[]);j.useEffect(()=>{!n&&t&&t.length===0&&c.mutate()},[n,t]);const[at,Ke]=gc(),nt=j.useRef(!1);j.useEffect(()=>{const qn=at.get("deal");if(qn&&r&&r.length>0&&!nt.current){const hn=r.find(Fn=>Fn.id===qn);hn&&(nt.current=!0,v(hn),x(!0),at.delete("deal"),Ke(at,{replace:!0}))}},[r,at]);const xt=j.useMemo(()=>{if(!$e||!t)return[];const qn=new Map(t.map(hn=>[hn.name,hn.id]));return $e.map(hn=>{const Fn=hn._stage_name&&qn.get(hn._stage_name)||null;return{...hn,stage_id:Fn||hn.stage_id}})},[$e,t]),rt=j.useMemo(()=>[...Ce&&!Le?[]:r||[],...xt],[r,xt,Ce,Le]);j.useEffect(()=>{if(ke.current||rt.length===0)return;ke.current=!0;const qn=sessionStorage.getItem(SX);if(qn)try{const hn=JSON.parse(qn);if(!hn.open||!hn.dealId)return;const Fn=rt.find(vn=>vn.id===hn.dealId);Fn&&(v(Fn),x(!0))}catch{sessionStorage.removeItem(SX)}},[rt]),j.useEffect(()=>{g&&(y!=null&&y.id)?sessionStorage.setItem(SX,JSON.stringify({dealId:y.id,open:!0})):sessionStorage.removeItem(SX)},[g,y==null?void 0:y.id]);const Yt=j.useMemo(()=>{const qn={},hn=new Date;return hn.setHours(0,0,0,0),(J||[]).forEach(Fn=>{!Fn.deal_id||Fn.status==="done"||!Fn.due_date||Ch(Fn.due_date){const qn=new Set((t||[]).filter(Or=>Or.is_won_stage).map(Or=>Or.id)),hn=new Set((t||[]).filter(Or=>Or.is_lost_stage).map(Or=>Or.id)),Fn=new Date;Fn.setHours(0,0,0,0);const vn=new Date(Fn);vn.setDate(vn.getDate()+7);const xs=new Date(Fn);xs.setDate(xs.getDate()-14);const Lr={closing_soon:new Set,past_due:new Set,overdue_tasks:new Set,stalled:new Set};return rt.forEach(Or=>{if(!(Or.stage_id&&(qn.has(Or.stage_id)||hn.has(Or.stage_id)))){if(Or.target_close_date){const Jn=Ch(Or.target_close_date);Jn[{key:"closing_soon",count:ys.closing_soon.size},{key:"past_due",count:ys.past_due.size},{key:"overdue_tasks",count:ys.overdue_tasks.size},{key:"stalled",count:ys.stalled.size}],[ys]),Ft=rt.filter(qn=>{var Un,ur,Pa,ii,$i,Rn;const hn=U.toLowerCase(),Fn=qt[qn.id]||[],vn=!hn||qn.deal_name.toLowerCase().includes(hn)||((ur=(Un=qn.contact)==null?void 0:Un.first_name)==null?void 0:ur.toLowerCase().includes(hn))||((ii=(Pa=qn.contact)==null?void 0:Pa.last_name)==null?void 0:ii.toLowerCase().includes(hn))||(($i=qn.property_address)==null?void 0:$i.toLowerCase().includes(hn))||((Rn=qn.city)==null?void 0:Rn.toLowerCase().includes(hn))||Fn.some(xa=>xa.toLowerCase().includes(hn)),xs=V==="all"||qn.deal_type===V,Lr=Y==="all"||Fn.includes(Y),Or=qn.actual_close_date||qn.target_close_date||qn.contract_date||qn.created_at,ca=Or?String(Or).slice(0,4):null,Jn=ae==="all"||ca===ae,Sr=!ne||ys[ne].has(qn.id);return vn&&xs&&Lr&&Jn&&Sr}),rs=j.useMemo(()=>{const qn=new Set;return qn.add(String(new Date().getFullYear())),rt.forEach(hn=>{const Fn=hn.actual_close_date||hn.target_close_date||hn.contract_date||hn.created_at;Fn&&qn.add(String(Fn).slice(0,4))}),Array.from(qn).sort((hn,Fn)=>Number(Fn)-Number(hn))},[rt]),St=j.useMemo(()=>{if(!t)return l||null;const qn=new Set(t.filter(Or=>Or.is_won_stage).map(Or=>Or.id)),hn=new Set(t.filter(Or=>Or.is_lost_stage).map(Or=>Or.id)),Fn=rt.filter(Or=>Or.stage_id&&!qn.has(Or.stage_id)&&!hn.has(Or.stage_id)),vn=rt.filter(Or=>Or.stage_id&&qn.has(Or.stage_id)),xs=new Date().getFullYear(),Lr=vn.filter(Or=>Or.actual_close_date?new Date(Or.actual_close_date).getFullYear()===xs:!0);return{totalDeals:rt.length,activeDeals:Fn.length,wonDeals:vn.length,pipelineValue:Fn.reduce((Or,ca)=>Or+(ca.expected_price||0),0),expectedCommission:Fn.reduce((Or,ca)=>Or+(ca.expected_commission||0),0),expectedNetToAgent:Fn.reduce((Or,ca)=>Or+(jw(ca)||0),0),wonValue:vn.reduce((Or,ca)=>Or+(ca.expected_price||0),0),weightedGCI:Fn.reduce((Or,ca)=>Or+(ca.expected_commission||0)*((ca.probability??50)/100),0),weightedNet:Fn.reduce((Or,ca)=>Or+(jw(ca)||0)*((ca.probability??50)/100),0),ytdWonDeals:Lr.length,ytdWonGCI:Lr.reduce((Or,ca)=>Or+(ca.expected_commission||0),0),ytdWonNet:Lr.reduce((Or,ca)=>Or+(jw(ca)||0),0),projectedAnnualNet:Lr.reduce((Or,ca)=>Or+(jw(ca)||0),0)+Fn.reduce((Or,ca)=>Or+(jw(ca)||0)*((ca.probability??50)/100),0)}},[rt,t,l]),Xs=qn=>{v(qn),x(!0)},vt=qn=>{w(qn||null),v(null),f(!0)},gs=qn=>{v(qn),x(!1),f(!0)},Ss=qn=>{x(qn),qn||sessionStorage.removeItem(SX)},Is=(qn,hn)=>{C(qn)},Ys=(qn,hn)=>{qn.preventDefault(),qn.dataTransfer.dropEffect="move",I(hn)},cs=async(qn,hn)=>{if(qn.preventDefault(),I(null),!S)return;const Fn=r==null?void 0:r.find(Lr=>Lr.id===S),vn=t==null?void 0:t.find(Lr=>Lr.id===hn),xs=t==null?void 0:t.find(Lr=>Lr.id===(Fn==null?void 0:Fn.stage_id));if(!Fn||!vn||Fn.stage_id===hn){C(null);return}je({dealId:S,dealName:Fn.deal_name,fromStageName:(xs==null?void 0:xs.name)||"Unknown",toStageName:vn.name,toStageId:hn,isWonStage:vn.is_won_stage,deal:Fn}),C(null)},js=async()=>{if(!Ve)return;const{dealId:qn,toStageId:hn,toStageName:Fn,isWonStage:vn,deal:xs}=Ve;if(await d.mutateAsync({dealId:qn,stageId:hn,stageName:Fn}),re.success(`Moved to ${Fn}`),vn&&!xs.scorecard_transaction_id){const Lr={...xs,stage_id:hn};O(Lr),R(!0)}},kn=j.useCallback(async(qn,hn,Fn)=>{const vn=r==null?void 0:r.find(Or=>Or.id===qn),xs=t==null?void 0:t.find(Or=>Or.id===hn),Lr=t==null?void 0:t.find(Or=>Or.id===(vn==null?void 0:vn.stage_id));!vn||!xs||vn.stage_id===hn||je({dealId:qn,dealName:vn.deal_name,fromStageName:(Lr==null?void 0:Lr.name)||"Unknown",toStageName:Fn,toStageId:hn,isWonStage:xs.is_won_stage,deal:vn})},[r,t]),Ws=qn=>Ft.filter(hn=>hn.stage_id===qn),On=n||a,ds=s?"list":u,gn=[{label:"Active Deals",value:(St==null?void 0:St.activeDeals)||0,hint:"Deals still in play"},{label:"Weighted GCI",value:CX((St==null?void 0:St.weightedGCI)||0),hint:"GCI adjusted by each deal's win probability"},{label:"Weighted Net",value:CX((St==null?void 0:St.weightedNet)||0),hint:"Net to agent adjusted by each deal's win probability"},{label:"YTD Closed Net",value:CX((St==null?void 0:St.ytdWonNet)||0),subtitle:`${(St==null?void 0:St.ytdWonDeals)||0} deals`,hint:"Net commission from deals closed this year"},{label:"Projected Annual",value:CX((St==null?void 0:St.projectedAnnualNet)||0),hint:"YTD closed net + weighted active net"}],As=[...V!=="all"?[{key:"type",label:`Type: ${V}`,onClear:()=>G("all")}]:[],...ae!=="all"?[{key:"year",label:`Year: ${ae}`,onClear:()=>ie("all")}]:[],...Y!=="all"?[{key:"tag",label:`Tag: ${Y}`,onClear:()=>X("all")}]:[],...U?[{key:"search",label:`"${U}"`,onClear:()=>W("")}]:[],...ne?[{key:"attention",label:"Needs attention",onClear:()=>te(null)}]:[]],hr=()=>{W(""),G("all"),X("all"),ie("all"),te(null)};return e.jsxs(Vs,{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.jsx(Car,{summary:`${(St==null?void 0:St.activeDeals)||0} active deals • ${CX((St==null?void 0:St.weightedNet)||0)} weighted net`,stats:ds==="portals"?[]:gn,search:U,onSearchChange:W,onAddDeal:()=>vt(),onRefresh:()=>i(),onTeam:Ae&&!Ce?()=>he(!0):void 0,showSearch:ds!=="portals",activeFilters:As,onClearAll:hr,resultLabel:As.length>0?`${Ft.length} of ${rt.length} deals`:null,viewControls:s?null:e.jsx(jk,{children:e.jsx("div",{className:"hub-glass flex items-center gap-0.5 rounded-full p-1",children:[{mode:"board",icon:Qf,label:"Board",hint:"Kanban board view"},{mode:"list",icon:P0,label:"List",hint:"Grouped list view"},{mode:"table",icon:lV,label:"Table",hint:"Sortable table view"},{mode:"portals",icon:Nn,label:"Portals",hint:"Client portal management"}].map(({mode:qn,icon:hn,label:Fn,hint:vn})=>e.jsxs(ly,{children:[e.jsx(cy,{asChild:!0,children:e.jsxs("button",{onClick:()=>h(qn),className:Pt("inline-flex items-center gap-1.5 rounded-full px-3 py-1.5 text-xs font-medium transition-colors",u===qn?"bg-background text-foreground shadow-sm":"opacity-80 hover:opacity-100"),children:[e.jsx(hn,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:Fn})]})}),e.jsx(Nx,{children:vn})]},qn))})}),filters:ds!=="portals"?e.jsxs(e.Fragment,{children:[e.jsxs(ms,{value:V,onValueChange:G,children:[e.jsx(us,{className:"hub-glass h-10 w-[130px] rounded-full border-0 text-sm",children:e.jsx(fs,{placeholder:"All Types"})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"all",children:"All Types"}),e.jsx(Ge,{value:"buyer",children:"Buyer"}),e.jsx(Ge,{value:"seller",children:"Seller"}),e.jsx(Ge,{value:"dual",children:"Dual"}),e.jsx(Ge,{value:"referral",children:"Referral"}),e.jsx(Ge,{value:"lease",children:"Lease"})]})]}),e.jsxs(ms,{value:ae,onValueChange:ie,children:[e.jsx(us,{className:"hub-glass h-10 w-[110px] rounded-full border-0 text-sm",children:e.jsx(fs,{placeholder:"Year"})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"all",children:"All Years"}),rs.map(qn=>e.jsx(Ge,{value:qn,children:qn},qn))]})]}),e.jsxs(ms,{value:Y,onValueChange:X,children:[e.jsxs(us,{className:"hub-glass h-10 w-[150px] rounded-full border-0 text-sm",children:[e.jsx(Ap,{className:"mr-1.5 h-3.5 w-3.5 opacity-70"}),e.jsx(fs,{placeholder:"All Tags"})]}),e.jsxs(hs,{className:"max-h-[300px]",children:[e.jsx(Ge,{value:"all",children:"All Tags"}),ts.length===0&&e.jsx("div",{className:"px-2 py-1.5 text-xs text-muted-foreground",children:"No tags yet"}),ts.map(qn=>e.jsx(Ge,{value:qn,children:qn},qn))]})]})]}):null}),e.jsx(Iar,{}),ds!=="portals"&&e.jsx(Ear,{items:Bt,active:ne,onToggle:qn=>te(hn=>hn===qn?null:qn)})]}),e.jsxs("div",{className:"flex-1 min-h-0 flex",children:[Ce&&!s&&qe.length>0&&e.jsx(BQn,{members:qe,enabledMembers:Ee,onToggleMember:it,isOpen:ue,onToggleOpen:()=>ve(qn=>!qn),showOwnDeals:Le,onToggleOwnDeals:()=>Fe(qn=>!qn)}),e.jsx("div",{className:"flex-1 min-w-0 min-h-0 p-4 md:p-6 pt-4",children:On?e.jsx("div",{className:"flex gap-4 h-full",children:[1,2,3,4].map(qn=>e.jsx("div",{className:"min-w-[280px] max-w-[320px] flex-shrink-0",children:e.jsx(yn,{className:"h-full rounded-xl"})},qn))}):ds==="board"?e.jsxs(uo,{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(qn=>e.jsx(GQn,{stage:qn,deals:Ws(qn.id),onDealClick:Xs,onAddDeal:vt,onDragStart:Is,onDragOver:Ys,onDrop:cs,isDragOver:E===qn.id,isWonStage:qn.is_won_stage,isLostStage:qn.is_lost_stage,getOwnerInfo:Xe,tagsByDeal:qt,overdueTasksByDeal:Yt},qn.id))}),e.jsx(Bae,{orientation:"horizontal"})]}):ds==="table"?e.jsx(uo,{className:"h-full",children:e.jsx(car,{deals:Ft,stages:t||[],onDealClick:Xs,onStageChange:kn})}):ds==="portals"?e.jsx(ios,{}):e.jsx(uo,{className:"h-full",children:e.jsxs("div",{className:"space-y-6",children:[t==null?void 0:t.map(qn=>{const hn=Ws(qn.id);return hn.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:qn.color}}),e.jsx("h3",{className:"font-semibold",children:qn.name}),e.jsxs("span",{className:"text-muted-foreground text-sm",children:["(",hn.length,")"]})]}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-3",children:hn.map(Fn=>e.jsx(eas,{deal:Fn,onClick:()=>Xs(Fn),stages:t,onStageChange:kn,showStagePicker:!0,isWonStage:qn.is_won_stage,isLostStage:qn.is_lost_stage,ownerInfo:Xe(Fn),tags:qt[Fn.id]||[],overdueTaskCount:Yt[Fn.id]||0},Fn.id))})]},qn.id)}),(r==null?void 0:r.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(Qf,{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($,{onClick:()=>vt(),children:[e.jsx(dn,{className:"h-4 w-4 mr-2"}),"Add Your First Deal"]})]}),((r==null?void 0:r.length)||0)>0&&Ft.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(Kr,{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($,{variant:"outline",onClick:hr,children:"Clear Filters"})]})]})})})]})]}),e.jsx(sJn,{open:m,onOpenChange:f,deal:y,defaultStageId:b}),e.jsx(iar,{deal:y,open:g,onOpenChange:Ss,onEdit:gs,isWonStage:y?(Er=t==null?void 0:t.find(qn=>qn.id===y.stage_id))==null?void 0:Er.is_won_stage:!1,onAddToScorecard:qn=>{O(qn),R(!0),x(!1)}}),e.jsx(oar,{open:P,onOpenChange:R,deal:D,onComplete:()=>{i(),O(null)}}),Ve&&e.jsx(_ar,{open:!!Ve,onOpenChange:qn=>{qn||je(null)},dealId:Ve.dealId,dealName:Ve.dealName,fromStageName:Ve.fromStageName,toStageName:Ve.toStageName,toStageId:Ve.toStageId,onConfirm:js}),e.jsx(OQn,{open:_e,onOpenChange:he})]})}function Dar(){return e.jsx(Lar,{children:e.jsx(Rar,{})})}function zPe({open:s,onOpenChange:t,templateId:n,templateName:r,brokerageId:a,onUploaded:i}){const l=!!n,o=j.useRef(null),[c,d]=j.useState(null),[u,h]=j.useState(""),[m,f]=j.useState(""),[g,x]=j.useState("other"),[y,v]=j.useState(!1),b=urr(),w=()=>{d(null),h(""),f(""),x("other"),v(!1),o.current&&(o.current.value="")},S=E=>{if(E){if(E.type!=="application/pdf"&&!E.name.toLowerCase().endsWith(".pdf")){re.error("Only PDF files can be uploaded.");return}if(E.size>Kis){re.error("That PDF is larger than the 20MB limit.");return}d(E),!u&&!l&&h(E.name.replace(/\.pdf$/i,""))}},C=async()=>{if(c)try{const E=await b.mutateAsync({name:u.trim()||c.name.replace(/\.pdf$/i,""),description:m,category:g,file:c,templateId:n,brokerageId:a});re.success(E.version.has_acroform?`Found ${E.version.detected_fields.length} fillable fields — map them next.`:"Uploaded. This PDF has no fillable fields yet."),i==null||i(E.templateId,E.version.id),w(),t(!1)}catch(E){re.error((E==null?void 0:E.message)||"Upload failed")}};return e.jsx(zs,{open:s,onOpenChange:E=>{E||w(),t(E)},children:e.jsxs(Os,{className:"max-w-lg max-h-[90vh] overflow-y-auto",children:[e.jsxs(Us,{children:[e.jsx(Bs,{children:l?`New version of ${r}`:"Upload a form template"}),e.jsxs(Ir,{children:["PDF only, up to 20MB."," ",a?"Brokerage templates stay in draft until you publish them to your agents.":"Templates stay private to your account."]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsx("input",{ref:o,type:"file",accept:"application/pdf,.pdf",className:"hidden",onChange:E=>{var I;return S((I=E.target.files)==null?void 0:I[0])}}),e.jsx("button",{type:"button",onClick:()=>{var E;return(E=o.current)==null?void 0:E.click()},className:"w-full rounded-lg border border-dashed p-6 text-center transition-colors hover:bg-muted/50",children:c?e.jsxs("div",{className:"flex items-center justify-center gap-3",children:[e.jsx(Jr,{className:"h-5 w-5 text-primary"}),e.jsxs("div",{className:"text-left",children:[e.jsx("p",{className:"text-sm font-medium",children:c.name}),e.jsx("p",{className:"text-xs text-muted-foreground",children:Plt(c.size)})]})]}):e.jsxs("div",{className:"flex flex-col items-center gap-2 text-muted-foreground",children:[e.jsx(ni,{className:"h-6 w-6"}),e.jsx("span",{className:"text-sm",children:"Choose a blank PDF form"})]})}),!l&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"tpl-name",children:"Template name"}),e.jsx(pe,{id:"tpl-name",value:u,onChange:E=>h(E.target.value),placeholder:"Residential Purchase Agreement"})]}),e.jsxs("div",{className:"grid gap-2",children:[e.jsx(ee,{children:"Category"}),e.jsxs(ms,{value:g,onValueChange:E=>x(E),children:[e.jsx(us,{children:e.jsx(fs,{})}),e.jsx(hs,{children:Tlt.map(E=>e.jsx(Ge,{value:E.value,children:E.label},E.value))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"tpl-desc",children:"Description (optional)"}),e.jsx(Rs,{id:"tpl-desc",rows:2,value:m,onChange:E=>f(E.target.value)})]})]}),e.jsxs("label",{className:"flex items-start gap-3 rounded-lg bg-muted/50 p-3 text-xs text-muted-foreground",children:[e.jsx(ai,{checked:y,onCheckedChange:E=>v(!!E),className:"mt-0.5"}),e.jsx("span",{children:"I confirm I am legally permitted to use and store this form. LevelUp does not provide or license association forms."})]})]}),e.jsxs(Ar,{children:[e.jsx($,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsxs($,{onClick:C,disabled:!c||!y||b.isPending,children:[b.isPending&&e.jsx(kt,{className:"mr-2 h-4 w-4 animate-spin"}),b.isPending?"Reading PDF…":"Upload"]})]})]})})}function lQe(s){return s.replace(/([a-z])([A-Z])/g,"$1 $2").replace(/[^a-zA-Z0-9]+/g," ").toLowerCase().trim()}function aEt(s){return lQe(s).split(" ").filter(Boolean)}function Far(s,t,n){const r=lQe(s),a=new Set(aEt(s));let i=0;const l=[t,...n];for(const o of l){const c=lQe(o);if(!c)continue;if(r===c){i=Math.max(i,100);continue}if(r.includes(c)){i=Math.max(i,60+Math.min(c.length,30));continue}const d=aEt(o),u=d.filter(h=>a.has(h)).length;u>0&&(i=Math.max(i,Math.round(u/d.length*45)))}return i}function Oar(s){if(!s)return null;let t=null;for(const n of TW){const r=Far(s,n.label,n.aliases);r>0&&(!t||r>t.confidence)&&(t={mergeKey:n.key,confidence:r})}return!t||t.confidence<35?null:t}const zar=["Deal","Contact","Agent","Other"],dUe="__blank__",uUe="__static__";function oos({version:s}){const{data:t,isLoading:n}=uoe(s.id),r=vrr(),[a,i]=j.useState([]),[l,o]=j.useState("");j.useEffect(()=>{if(n)return;const f=new Map((t||[]).map(g=>[g.pdf_field_name||"",g]));i((s.detected_fields||[]).map(g=>{const x=f.get(g.name),y=Oar(g.name);return{pdf_field_name:g.name,mapping_mode:(x==null?void 0:x.mapping_mode)||"acroform",merge_key:(x==null?void 0:x.merge_key)??null,static_value:(x==null?void 0:x.static_value)??null,suggested:(y==null?void 0:y.mergeKey)??null}}))},[t,n,s.id,s.detected_fields]);const c=j.useMemo(()=>{if(!l.trim())return a;const f=l.toLowerCase();return a.filter(g=>(g.pdf_field_name||"").toLowerCase().includes(f))},[a,l]),d=a.filter(f=>f.merge_key||f.mapping_mode==="static"&&f.static_value).length,u=(f,g)=>{i(x=>x.map(y=>y.pdf_field_name===f?{...y,...g}:y))},h=()=>{let f=0;i(g=>g.map(x=>x.merge_key||!x.suggested?x:(f+=1,{...x,mapping_mode:"acroform",merge_key:x.suggested}))),re.success(f?`Applied ${f} suggestion${f===1?"":"s"}`:"No new suggestions to apply")},m=async()=>{try{await r.mutateAsync({versionId:s.id,hasAcroform:s.has_acroform,mappings:a.map(({suggested:f,...g})=>g)}),re.success("Field mapping saved")}catch(f){re.error((f==null?void 0:f.message)||"Could not save the mapping")}};return s.has_acroform?n?e.jsx("div",{className:"flex justify-center py-10",children:e.jsx(kt,{className:"h-5 w-5 animate-spin text-muted-foreground"})}):e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between",children:[e.jsxs("div",{className:"text-sm text-muted-foreground",children:[d," of ",a.length," fields mapped"]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs($,{variant:"outline",size:"sm",onClick:h,children:[e.jsx(Nn,{className:"mr-1.5 h-4 w-4"})," Apply suggestions"]}),e.jsxs($,{size:"sm",onClick:m,disabled:r.isPending,children:[r.isPending?e.jsx(kt,{className:"mr-1.5 h-4 w-4 animate-spin"}):e.jsx(tl,{className:"mr-1.5 h-4 w-4"}),"Save mapping"]})]})]}),e.jsxs("div",{className:"relative",children:[e.jsx(Kr,{className:"pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(pe,{className:"pl-9",placeholder:"Search fields…",value:l,onChange:f=>o(f.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[c.map(f=>{var x;const g=f.mapping_mode==="static"?uUe:f.merge_key?f.merge_key:dUe;return e.jsxs("div",{className:"flex flex-col gap-2 rounded-lg border bg-background p-3 sm:flex-row sm:items-center",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"truncate text-sm font-medium",children:f.pdf_field_name}),f.suggested&&!f.merge_key&&e.jsxs(Be,{variant:"secondary",className:"mt-1 text-[10px]",children:["Suggested: ",(x=TW.find(y=>y.key===f.suggested))==null?void 0:x.label]})]}),e.jsxs("div",{className:"flex w-full gap-2 sm:w-[420px]",children:[e.jsxs(ms,{value:g,onValueChange:y=>{y===dUe?u(f.pdf_field_name,{mapping_mode:"blank",merge_key:null,static_value:null}):y===uUe?u(f.pdf_field_name,{mapping_mode:"static",merge_key:null}):u(f.pdf_field_name,{mapping_mode:"acroform",merge_key:y,static_value:null})},children:[e.jsx(us,{className:"flex-1",children:e.jsx(fs,{placeholder:"Leave blank"})}),e.jsxs(hs,{className:"max-h-[320px]",children:[e.jsx(Ge,{value:dUe,children:"Leave blank"}),e.jsx(Ge,{value:uUe,children:"Fixed text…"}),zar.map(y=>e.jsxs(aPs,{children:[e.jsx(Ezt,{children:y}),TW.filter(v=>v.group===y).map(v=>e.jsx(Ge,{value:v.key,children:v.label},v.key))]},y))]})]}),f.mapping_mode==="static"&&e.jsx(pe,{className:"flex-1",placeholder:"Fixed text",value:f.static_value||"",onChange:y=>u(f.pdf_field_name,{static_value:y.target.value})})]})]},f.pdf_field_name)}),c.length===0&&e.jsx("p",{className:"py-8 text-center text-sm text-muted-foreground",children:"No fields match that search."})]})]}):e.jsx(Ne,{children:e.jsxs(Ie,{className:"p-6 text-center space-y-2",children:[e.jsx("p",{className:"font-medium",children:"Needs field placement"}),e.jsx("p",{className:"text-sm text-muted-foreground max-w-md mx-auto",children:"This PDF has no fillable form fields, so there is nothing to map yet. Visual field placement for flat PDFs is coming next — for now, upload a fillable (AcroForm) version of this form to use it from a deal."})]})})}Wot.workerSrc=Kot;const SAe={data:{w:.24,h:.028,label:"Data field"},signature:{w:.28,h:.055,label:"Signature"},initials:{w:.1,h:.035,label:"Initials"},date_signed:{w:.14,h:.028,label:"Date signed"},printed_name:{w:.24,h:.03,label:"Printed name"},text:{w:.24,h:.03,label:"Text input"}},hUe=["signature","initials","date_signed","printed_name","text"],iEt=12,Bar={buyer_1:"border-emerald-500 bg-emerald-500/15 text-emerald-700",buyer_2:"border-emerald-500 bg-emerald-500/15 text-emerald-700",seller_1:"border-sky-500 bg-sky-500/15 text-sky-700",seller_2:"border-sky-500 bg-sky-500/15 text-sky-700",agent:"border-amber-500 bg-amber-500/15 text-amber-700"},the=s=>Math.min(1,Math.max(0,s));function los({version:s,templateName:t,open:n,onOpenChange:r}){const a=Vt(),{data:i=[],isLoading:l}=uoe(n?s.id:void 0),[o,c]=j.useState(null),[d,u]=j.useState(null),[h,m]=j.useState([]),[f,g]=j.useState("select"),[x,y]=j.useState(null),[v,b]=j.useState(!1),[w,S]=j.useState(!1),C=j.useRef(null),E=j.useRef([]),I=j.useRef(null),P=Math.min(s.page_count||1,iEt);j.useEffect(()=>{if(!n)return;let X=!1;return c(null),u(null),hFe(s.storage_path).then(ae=>{X||c(new Blob([ae],{type:"application/pdf"}))}).catch(()=>!X&&u("Could not load the template PDF.")),()=>{X=!0}},[n,s.storage_path]),j.useEffect(()=>{let X=!1;const ae=C.current;return!o||!ae?void 0:((async()=>{try{const ne=await o.arrayBuffer(),te=await wPe({data:ne}).promise;if(X)return;ae.innerHTML="",E.current=[];const J=Math.min(ae.clientWidth-32||720,860);for(let ce=1;ce<=te.numPages;ce++){const _e=await te.getPage(ce);if(X)return;const he=_e.getViewport({scale:1}),ue=J/he.width,ve=_e.getViewport({scale:ue*(window.devicePixelRatio||1)}),Ee=document.createElement("div");Ee.className="relative mx-auto shadow-sm",Ee.style.width=`${J}px`,Ee.style.height=`${he.height*ue}px`,Ee.dataset.pageIndex=String(ce-1);const Se=document.createElement("canvas");Se.width=Math.floor(ve.width),Se.height=Math.floor(ve.height),Se.style.width="100%",Se.style.height="100%",Se.className="rounded-md border border-border bg-white",Ee.appendChild(Se),ae.appendChild(Ee),E.current[ce-1]=Ee;const Le=Se.getContext("2d");Le&&await _e.render({canvasContext:Le,viewport:ve}).promise}X||m(ce=>[...ce])}catch(ne){X||u((ne==null?void 0:ne.message)||"Could not render the PDF")}})(),()=>{X=!0})},[o]),j.useEffect(()=>{if(!n||l)return;const X=i.filter(ae=>ae.field_kind!=="data"||ae.mapping_mode==="overlay").filter(ae=>ae.pos_x!=null&&ae.pos_y!=null).map(ae=>({key:ae.id,page_index:ae.page_index??0,x:Number(ae.pos_x),y:Number(ae.pos_y),w:Number(ae.width??.2),h:Number(ae.height??.03),field_kind:ae.field_kind||"data",merge_key:ae.merge_key,static_value:ae.static_value,signer_role:ae.signer_role,label:ae.label,is_required:ae.is_required??!0,font_size:ae.font_size,source:ae.source||"manual"}));m(X),y(null)},[n,l,i]),j.useEffect(()=>{const X=ie=>{const ne=I.current;if(!ne)return;const te=(ie.clientX-ne.startX)/ne.pageW,J=(ie.clientY-ne.startY)/ne.pageH;m(ce=>ce.map(_e=>_e.key!==ne.key?_e:ne.mode==="move"?{..._e,x:the(Math.min(ne.orig.x+te,1-_e.w)),y:the(Math.min(ne.orig.y+J,1-_e.h))}:{..._e,w:Math.min(Math.max(.04,ne.orig.w+te),1-_e.x),h:Math.min(Math.max(.015,ne.orig.h+J),1-_e.y)}))},ae=()=>{I.current=null};return window.addEventListener("pointermove",X),window.addEventListener("pointerup",ae),()=>{window.removeEventListener("pointermove",X),window.removeEventListener("pointerup",ae)}},[]);const R=(X,ae,ie)=>{X.stopPropagation(),X.preventDefault();const ne=E.current[ae.page_index];if(!ne)return;const te=ne.getBoundingClientRect();I.current={key:ae.key,mode:ie,startX:X.clientX,startY:X.clientY,orig:ae,pageW:te.width,pageH:te.height},y(ae.key)},D=(X,ae)=>{if(f==="select"){y(null);return}const ie=E.current[ae];if(!ie)return;const ne=ie.getBoundingClientRect(),te=SAe[f],J=the((X.clientX-ne.left)/ne.width-te.w/2),ce=the((X.clientY-ne.top)/ne.height-te.h/2),_e={key:crypto.randomUUID(),page_index:ae,x:Math.min(J,1-te.w),y:Math.min(ce,1-te.h),w:te.w,h:te.h,field_kind:f,merge_key:null,static_value:null,signer_role:hUe.includes(f)?"buyer_1":null,label:null,is_required:!0,font_size:null};m(he=>[...he,_e]),y(_e.key),g("select")},O=h.find(X=>X.key===x)||null,U=X=>{O&&m(ae=>ae.map(ie=>ie.key===O.key?{...ie,...X}:ie))},W=async(X=!1)=>{if(o){S(!0);try{const ae=await o.arrayBuffer(),ie=await wPe({data:ae}).promise,ne=Math.min(ie.numPages,iEt),te=[];for(let ue=1;ue<=ne;ue++){const ve=await ie.getPage(ue),Ee=ve.getViewport({scale:1}),Se=ve.getViewport({scale:Math.min(1e3/Ee.width,1.6)}),Le=document.createElement("canvas");Le.width=Math.floor(Se.width),Le.height=Math.floor(Se.height);const Fe=Le.getContext("2d");Fe&&(Fe.fillStyle="#ffffff",Fe.fillRect(0,0,Le.width,Le.height),await ve.render({canvasContext:Fe,viewport:Se}).promise,te.push({index:ue-1,image:Le.toDataURL("image/jpeg",.7)}))}const{data:J,error:ce}=await q.functions.invoke("forms-autoplace",{body:{version_id:s.id,pages:te,force:X}});if(ce)throw new Error(ce.message||"The field scan failed.");if(J!=null&&J.error)throw new Error(J.error);const _e=(J==null?void 0:J.fields)||[];if(!_e.length){re.info("The scan did not find any blank fields on this form. Place them manually below.");return}const he=_e.map(ue=>({key:crypto.randomUUID(),page_index:ue.page_index,x:ue.x,y:ue.y,w:ue.w,h:ue.h,field_kind:ue.field_kind,merge_key:null,static_value:null,signer_role:ue.signer_role||"buyer_1",label:ue.label,is_required:!0,font_size:null,source:"ai"}));m(ue=>[...ue,...he]),y(null),re.success(`${he.length} field${he.length===1?"":"s"} placed${J!=null&&J.cached?" (from the earlier scan)":""}. Review, nudge, then save.`)}catch(ae){re.error((ae==null?void 0:ae.message)||"Could not scan this document. You can still place fields manually.")}finally{S(!1)}}},V=async()=>{const X=h.filter(ae=>hUe.includes(ae.field_kind));for(const ae of X)if(!ae.signer_role){re.error("Every signer field needs a role (Buyer 1, Seller 1, Agent…)");return}b(!0);try{const{error:ae}=await q.from("form_field_mappings").delete().eq("version_id",s.id).or("field_kind.neq.data,mapping_mode.eq.overlay");if(ae)throw ae;const ie=h.map((ce,_e)=>({version_id:s.id,pdf_field_name:null,mapping_mode:(ce.field_kind==="data"&&ce.static_value&&!ce.merge_key,"overlay"),field_kind:ce.field_kind,merge_key:ce.field_kind==="data"?ce.merge_key:null,static_value:ce.field_kind==="data"?ce.static_value:null,signer_role:hUe.includes(ce.field_kind)?ce.signer_role:null,label:ce.label,is_required:ce.is_required,page_index:ce.page_index,pos_x:ce.x,pos_y:ce.y,width:ce.w,height:ce.h,coords_normalized:!0,font_size:ce.font_size,source:ce.source||"manual",sort_order:_e}));if(ie.length){const{error:ce}=await q.from("form_field_mappings").insert(ie);if(ce)throw ce}const te=h.some(ce=>ce.field_kind==="data"&&(ce.merge_key||ce.static_value))||i.some(ce=>ce.field_kind==="data"&&ce.mapping_mode!=="overlay"&&(ce.mapping_mode==="acroform"&&ce.merge_key||ce.mapping_mode==="static"))||X.length?"mapped":s.has_acroform?"needs_mapping":"needs_placement",{error:J}=await q.from("form_template_versions").update({mapping_status:te}).eq("id",s.id);if(J)throw J;re.success("Placement saved"),a.invalidateQueries({queryKey:["form-field-mappings",s.id]}),a.invalidateQueries({queryKey:["form-templates"]}),r(!1)}catch(ae){re.error((ae==null?void 0:ae.message)||"Could not save placement")}finally{b(!1)}},G=[{tool:"select",label:"Select",icon:GJ},{tool:"data",label:"Merge field",icon:aP},{tool:"signature",label:"Signature",icon:wf},{tool:"initials",label:"Initials",icon:hV},{tool:"date_signed",label:"Date signed",icon:Kc},{tool:"printed_name",label:"Printed name",icon:sl},{tool:"text",label:"Text input",icon:uV}],Y=s.page_count||1;return e.jsx(zs,{open:n,onOpenChange:r,children:e.jsxs(Os,{className:"flex h-[94vh] max-w-6xl flex-col overflow-hidden p-0",children:[e.jsxs(Us,{className:"border-b px-5 py-3 text-left",children:[e.jsxs(Bs,{className:"text-base",children:["Place fields — ",t," (v",s.version_number,")"]}),e.jsx("p",{className:"text-xs font-normal text-muted-foreground",children:"Pick a field type on the left, then click on the document where it belongs. Drag to move, pull the corner to resize."})]}),e.jsxs("div",{className:"flex min-h-0 flex-1",children:[e.jsxs("div",{className:"w-36 shrink-0 space-y-1 overflow-y-auto border-r p-3 sm:w-44",children:[e.jsxs($,{size:"sm",variant:"secondary",className:"mb-2 h-auto w-full flex-col items-start gap-0.5 py-2 text-left",disabled:w||!o,onClick:()=>W(!!s.autoplace_ran_at),children:[e.jsxs("span",{className:"flex items-center gap-1.5 text-xs font-semibold",children:[w?e.jsx(kt,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(Nn,{className:"h-3.5 w-3.5"}),w?"Scanning…":s.autoplace_ran_at?"Re-scan with AI":"Find fields with AI"]}),e.jsx("span",{className:"text-[10px] font-normal opacity-70",children:s.autoplace_ran_at?"Runs a fresh scan":`Scan ${P} page${P===1?"":"s"}`})]}),G.map(X=>e.jsxs("button",{onClick:()=>g(X.tool),className:`flex w-full items-center gap-2 rounded-md px-2.5 py-2 text-left text-xs font-medium transition-colors ${f===X.tool?"bg-primary text-primary-foreground":"hover:bg-muted"}`,children:[e.jsx(X.icon,{className:"h-3.5 w-3.5 shrink-0"}),X.label]},X.tool)),e.jsx("div",{className:"pt-3 text-[11px] leading-snug text-muted-foreground",children:"Merge fields fill automatically from the deal. Signature fields are assigned to a signer."})]}),e.jsxs("div",{className:"relative min-w-0 flex-1 overflow-auto bg-muted/40 p-4",children:[(l||!o)&&!d&&e.jsx("div",{className:"flex h-full items-center justify-center",children:e.jsx(kt,{className:"h-6 w-6 animate-spin text-muted-foreground"})}),d&&e.jsx("p",{className:"p-6 text-center text-sm text-destructive",children:d}),e.jsx("div",{ref:C,className:"space-y-4",onClickCapture:X=>{const ae=X.target.closest("[data-page-index]");ae&&D(X,Number(ae.dataset.pageIndex))}})]}),e.jsxs("div",{className:"hidden w-64 shrink-0 flex-col border-l sm:flex",children:[e.jsx("div",{className:"border-b px-4 py-3 text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:O?SAe[O.field_kind].label:"Field settings"}),e.jsx(uo,{className:"flex-1 p-4",children:O?e.jsxs("div",{className:"space-y-4",children:[O.field_kind==="data"?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{className:"text-xs",children:"Merge value"}),e.jsxs(ms,{value:O.merge_key||"",onValueChange:X=>U({merge_key:X||null,static_value:null}),children:[e.jsx(us,{className:"h-8 text-xs",children:e.jsx(fs,{placeholder:"Choose data…"})}),e.jsx(hs,{children:["Deal","Contact","Agent","Other"].map(X=>e.jsxs("div",{children:[e.jsx("div",{className:"px-2 py-1 text-[10px] font-semibold uppercase text-muted-foreground",children:X}),TW.filter(ae=>ae.group===X).map(ae=>e.jsx(Ge,{value:ae.key,className:"text-xs",children:ae.label},ae.key))]},X))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{className:"text-xs",children:"…or fixed text"}),e.jsx(pe,{className:"h-8 text-xs",placeholder:"Printed exactly as typed",value:O.merge_key?"":O.static_value||"",disabled:!!O.merge_key,onChange:X=>U({static_value:X.target.value||null})})]})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{className:"text-xs",children:"Who signs this?"}),e.jsxs(ms,{value:O.signer_role||"",onValueChange:X=>U({signer_role:X}),children:[e.jsx(us,{className:"h-8 text-xs",children:e.jsx(fs,{placeholder:"Choose signer…"})}),e.jsx(hs,{children:Llt.map(X=>e.jsx(Ge,{value:X.value,className:"text-xs",children:X.label},X.value))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{className:"text-xs",children:"Label shown to signer"}),e.jsx(pe,{className:"h-8 text-xs",placeholder:SAe[O.field_kind].label,value:O.label||"",onChange:X=>U({label:X.target.value||null})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(ee,{className:"text-xs",children:"Required"}),e.jsx(Sn,{checked:O.is_required,onCheckedChange:X=>U({is_required:X})})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{className:"text-xs",children:"Font size (optional)"}),e.jsx(pe,{className:"h-8 text-xs",type:"number",min:6,max:24,value:O.font_size??"",onChange:X=>U({font_size:X.target.value?Number(X.target.value):null})})]}),e.jsxs("div",{className:"flex gap-2 pt-2",children:[O.page_index+1{const X={...O,key:crypto.randomUUID(),page_index:O.page_index+1};m(ae=>[...ae,X]),y(X.key)},children:[e.jsx(Ha,{className:"mr-1 h-3 w-3"})," Next page"]}),e.jsxs($,{variant:"outline",size:"sm",className:"h-8 flex-1 text-xs text-destructive",onClick:()=>{m(X=>X.filter(ae=>ae.key!==O.key)),y(null)},children:[e.jsx(Wn,{className:"mr-1 h-3 w-3"})," Remove"]})]})]}):e.jsx("p",{className:"text-xs text-muted-foreground",children:"Select a box on the document to edit what it fills and who signs it."})}),e.jsx("div",{className:"border-t p-4",children:e.jsxs($,{className:"w-full",onClick:V,disabled:v,children:[v?e.jsx(kt,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(tl,{className:"mr-2 h-4 w-4"}),"Save placement"]})})]})]}),e.jsx($ar,{boxes:h,pageRefs:E,selectedKey:x,onSelect:y,onDragStart:R})]})})}function $ar({boxes:s,pageRefs:t,selectedKey:n,onSelect:r,onDragStart:a}){const[,i]=j.useState(0);return j.useEffect(()=>{const l=setTimeout(()=>i(o=>o+1),300);return()=>clearTimeout(l)},[s.length===0]),e.jsx(e.Fragment,{children:s.map(l=>{var c;const o=t.current[l.page_index];return o?e.jsx(Uar,{target:o,children:e.jsxs("div",{onPointerDown:d=>a(d,l,"move"),onClick:d=>d.stopPropagation(),className:`absolute cursor-move rounded-sm border-2 transition-shadow ${l.field_kind==="data"?"border-primary bg-primary/10 text-primary":Bar[l.signer_role||""]||"border-muted-foreground bg-muted/40"} ${n===l.key?"ring-2 ring-ring shadow-md":""}`,style:{left:`${l.x*100}%`,top:`${l.y*100}%`,width:`${l.w*100}%`,height:`${l.h*100}%`},children:[e.jsx("span",{className:"pointer-events-none absolute left-0.5 top-0 max-w-full truncate text-[9px] font-semibold leading-tight",children:l.field_kind==="data"?l.merge_key?((c=TW.find(d=>d.key===l.merge_key))==null?void 0:c.label)||l.merge_key:l.static_value||"Data":`${l.label||SAe[l.field_kind].label} · ${mFe(l.signer_role)}`}),n===l.key&&e.jsx("span",{onPointerDown:d=>a(d,l,"resize"),className:"absolute -bottom-1.5 -right-1.5 h-3.5 w-3.5 cursor-nwse-resize rounded-full border-2 border-background bg-primary"})]})},l.key):null})})}function Uar({target:s,children:t}){return wv.createPortal(t,s)}function qar({templates:s}){const{data:t=[],isLoading:n}=eos(),r=Srr(),a=Crr(),[i,l]=j.useState(null),[o,c]=j.useState(""),[d,u]=j.useState(""),[h,m]=j.useState([]);j.useEffect(()=>{i&&(i==="new"?(c(""),u(""),m([])):(c(i.name),u(i.description||""),m([...i.items||[]].sort((v,b)=>v.sort_order-b.sort_order).map(v=>v.template_id))))},[i]);const f=s.filter(v=>{var b;return((b=wx(v))==null?void 0:b.mapping_status)==="mapped"}),g=v=>m(b=>b.includes(v)?b.filter(w=>w!==v):[...b,v]),x=(v,b)=>m(w=>{const S=[...w],C=v+b;return C<0||C>=S.length?w:([S[v],S[C]]=[S[C],S[v]],S)}),y=async()=>{if(!o.trim())return re.error("Give the packet a name");if(!h.length)return re.error("Add at least one form to the packet");try{await r.mutateAsync({id:i==="new"?void 0:i.id,name:o.trim(),description:d.trim()||null,templateIds:h}),re.success(i==="new"?"Packet created":"Packet updated"),l(null)}catch(v){re.error((v==null?void 0:v.message)||"Could not save the packet")}};return e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-end justify-between gap-3",children:[e.jsxs("div",{children:[e.jsxs("h2",{className:"flex items-center gap-2 text-lg font-semibold tracking-tight",children:[e.jsx(L4,{className:"h-4 w-4 text-primary"})," Form packets"]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Bundle the forms you always send together. Signers sign the whole packet in one session."})]}),e.jsxs($,{variant:"outline",size:"sm",onClick:()=>l("new"),disabled:f.length===0,children:[e.jsx(dn,{className:"mr-2 h-4 w-4"})," New packet"]})]}),n?e.jsx("div",{className:"flex justify-center py-6",children:e.jsx(kt,{className:"h-5 w-5 animate-spin text-muted-foreground"})}):t.length===0?e.jsx(Ne,{className:"border-dashed",children:e.jsx(Ie,{className:"p-6 text-center text-sm text-muted-foreground",children:f.length===0?"Once at least one template is ready to send, you can bundle templates into a packet.":"No packets yet — build a “New Buyer Packet” or “Listing Agreement Bundle” and send it in one click."})}):e.jsx("div",{className:"grid gap-3 sm:grid-cols-2 lg:grid-cols-3",children:t.map(v=>{const b=Rlt(v,s);return e.jsx(Ne,{children:e.jsxs(Ie,{className:"space-y-3 p-4",children:[e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"flex h-10 w-10 shrink-0 items-center justify-center rounded-lg bg-primary/10",children:e.jsx(L4,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"truncate font-medium",children:v.name}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[b.length," form",b.length===1?"":"s"]})]})]}),e.jsx("ol",{className:"ml-4 list-decimal space-y-0.5 text-xs text-muted-foreground",children:b.map(w=>e.jsx("li",{className:"truncate",children:w.name},w.id))}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(Be,{variant:"outline",className:"text-[10px]",children:"Send from any deal"}),e.jsxs("div",{className:"flex gap-1",children:[e.jsxs($,{variant:"ghost",size:"sm",className:"h-7 text-xs",onClick:()=>l(v),children:[e.jsx(gi,{className:"mr-1 h-3 w-3"})," Edit"]}),e.jsx($,{variant:"ghost",size:"sm",className:"h-7 text-xs text-destructive",onClick:async()=>{await fo(`Delete the "${v.name}" packet? The forms themselves are kept.`)&&(await a.mutateAsync(v.id),re.success("Packet deleted"))},children:e.jsx(Wn,{className:"h-3 w-3"})})]})]})]})},v.id)})}),e.jsx(zs,{open:!!i,onOpenChange:v=>!v&&l(null),children:e.jsxs(Os,{className:"flex max-h-[88vh] max-w-lg flex-col overflow-hidden",children:[e.jsxs(Us,{children:[e.jsx(Bs,{children:i==="new"?"New form packet":"Edit packet"}),e.jsx(Ir,{children:"Pick the forms and the order signers see them in. Only templates that are ready to send can be added."})]}),e.jsxs("div",{className:"space-y-4 overflow-y-auto",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{className:"text-xs",children:"Packet name"}),e.jsx(pe,{value:o,onChange:v=>c(v.target.value),placeholder:"New Buyer Packet"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{className:"text-xs",children:"Description (optional)"}),e.jsx(Rs,{rows:2,value:d,onChange:v=>u(v.target.value)})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{className:"text-xs",children:"Forms in this packet"}),e.jsx(uo,{className:"max-h-56 rounded-lg border",children:e.jsx("div",{className:"divide-y",children:f.map(v=>e.jsxs("label",{className:"flex cursor-pointer items-center gap-3 p-2.5 text-sm hover:bg-muted/50",children:[e.jsx(ai,{checked:h.includes(v.id),onCheckedChange:()=>g(v.id)}),e.jsx("span",{className:"min-w-0 flex-1 truncate",children:v.name})]},v.id))})})]}),h.length>0&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{className:"text-xs",children:"Signing order"}),e.jsx("div",{className:"space-y-1 rounded-lg border p-2",children:h.map((v,b)=>{const w=s.find(S=>S.id===v);return e.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[e.jsxs("span",{className:"w-4 text-muted-foreground",children:[b+1,"."]}),e.jsx("span",{className:"min-w-0 flex-1 truncate",children:(w==null?void 0:w.name)||"Removed template"}),e.jsx($,{variant:"ghost",size:"icon",className:"h-6 w-6",onClick:()=>x(b,-1),children:e.jsx(Zf,{className:"h-3 w-3"})}),e.jsx($,{variant:"ghost",size:"icon",className:"h-6 w-6",onClick:()=>x(b,1),children:e.jsx(Dg,{className:"h-3 w-3"})})]},v)})})]})]}),e.jsxs(Ar,{children:[e.jsx($,{variant:"outline",onClick:()=>l(null),children:"Cancel"}),e.jsxs($,{onClick:y,disabled:r.isPending,children:[r.isPending&&e.jsx(kt,{className:"mr-2 h-4 w-4 animate-spin"}),"Save packet"]})]})]})})]})}function Var(s){const t=s.indexOf(",");if(t<0)return null;try{const n=atob(s.slice(t+1)),r=new Uint8Array(n.length);for(let a=0;ad.field_kind==null||d.field_kind==="data"),n=await Wis(s.templateBytes,t,s.values),r=n.bytes.buffer.slice(n.bytes.byteOffset,n.bytes.byteOffset+n.bytes.byteLength),a=await n3.load(r,{updateMetadata:!1}),i=await a.embedFont(EW.Helvetica),l=a.getPages(),o=[...n.skipped];for(const d of s.signerBoxes){const u=s.entries[d.id],h=l[d.page_index??0];if(!h||d.pos_x==null||d.pos_y==null)continue;if(!u||!u.png&&!((c=u.text)!=null&&c.trim())){o.push(d.static_value||d.field_kind||"signature");continue}const{width:m,height:f}=h.getSize(),g=d.coords_normalized!==!1,x=Number(d.pos_x)*(g?m:1),y=Number(d.width??(g?.2:140))*(g?m:1),v=Number(d.height??(g?.04:24))*(g?f:1),b=Number(d.pos_y)*(g?f:1),w=g?f-b-v:b;if(u.png){const S=Var(u.png);if(!S){o.push("signature");continue}const C=await a.embedPng(S),E=Math.min(y/C.width,v/C.height),I=C.width*E,P=C.height*E;h.drawImage(C,{x:x+(y-I)/2,y:w+(v-P)/2,width:I,height:P})}else{const S=u.text.trim(),C=Math.min(11,Math.max(7,v*.6));h.drawText(S,{x:x+1,y:w+Math.max(2,(v-C)/2),size:C,font:i,color:Ah(0,0,0),maxWidth:Math.max(10,y-2)})}}return{bytes:await a.save(),skipped:o}}const cos='"Segoe Script","Brush Script MT",cursive';function Gar(s){const t=document.createElement("canvas");t.width=640,t.height=200;const n=t.getContext("2d");return n.clearRect(0,0,t.width,t.height),n.fillStyle="#12233f",n.textAlign="center",n.font=`72px ${cos}`,n.fillText(s,t.width/2,t.height/2+24),t.toDataURL("image/png")}function War({label:s,onAdopt:t}){const n=j.useRef(null),r=j.useRef(!1),[a,i]=j.useState(""),[l,o]=j.useState(!1),c=m=>{const f=n.current,g=f.getBoundingClientRect();return{x:(m.clientX-g.left)/g.width*f.width,y:(m.clientY-g.top)/g.height*f.height}},d=m=>{const f=n.current;if(!f)return;r.current=!0,f.setPointerCapture(m.pointerId);const g=f.getContext("2d");g.lineWidth=3,g.lineCap="round",g.strokeStyle="#12233f";const x=c(m);g.beginPath(),g.moveTo(x.x,x.y)},u=m=>{if(!r.current)return;const f=n.current.getContext("2d"),g=c(m);f.lineTo(g.x,g.y),f.stroke(),o(!0)},h=()=>{r.current=!1};return e.jsxs(ha,{defaultValue:"draw",className:"w-full",children:[e.jsxs(ma,{className:"grid w-full grid-cols-2",children:[e.jsx(Zt,{value:"draw",children:"Draw"}),e.jsx(Zt,{value:"type",children:"Type"})]}),e.jsxs(Xt,{value:"draw",className:"space-y-3 pt-3",children:[e.jsx("canvas",{ref:n,width:640,height:200,className:"h-36 w-full touch-none rounded-lg border bg-white",onPointerDown:d,onPointerMove:u,onPointerUp:h,onPointerLeave:h}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs($,{type:"button",variant:"outline",size:"sm",onClick:()=>{var f;const m=n.current;(f=m==null?void 0:m.getContext("2d"))==null||f.clearRect(0,0,m.width,m.height),o(!1)},children:[e.jsx(Rq,{className:"mr-1 h-3.5 w-3.5"})," Clear"]}),e.jsxs($,{type:"button",size:"sm",className:"flex-1",disabled:!l,onClick:()=>{const m=n.current;m&&t(m.toDataURL("image/png"))},children:["Use this ",s]})]})]}),e.jsxs(Xt,{value:"type",className:"space-y-3 pt-3",children:[e.jsx(pe,{value:a,onChange:m=>i(m.target.value),placeholder:"Type your name"}),e.jsx("div",{className:"flex h-24 items-center justify-center rounded-lg border bg-white",children:e.jsx("span",{className:"text-3xl text-[#12233f]",style:{fontFamily:cos},children:a||" "})}),e.jsxs($,{type:"button",size:"sm",className:"w-full",disabled:!a.trim(),onClick:()=>t(Gar(a.trim())),children:["Use this ",s]})]})]})}const Kar=["signature","initials","date_signed","printed_name","text"],Yar={signature:"Signature",initials:"Initials",date_signed:"Date signed",printed_name:"Printed name",text:"Text"};function Zar({open:s,onOpenChange:t,template:n,version:r}){const a=Sa(),{data:i=[],isLoading:l}=uoe(s?r.id:void 0),{data:o=[]}=rY(),[c,d]=j.useState(""),{data:u}=Ilt(s&&c?c:void 0),[h,m]=j.useState({}),[f,g]=j.useState({}),[x,y]=j.useState(null),[v,b]=j.useState(!1),w=j.useMemo(()=>i.filter(R=>(R.field_kind==null||R.field_kind==="data")&&R.mapping_mode!=="blank"&&(R.merge_key||R.pdf_field_name||R.static_value)),[i]),S=j.useMemo(()=>i.filter(R=>R.field_kind&&Kar.includes(R.field_kind)),[i]);j.useEffect(()=>{u&&m(R=>{const D={...R};for(const[O,U]of Object.entries(u.values))U&&!D[O]&&(D[O]=U);return D})},[u]),j.useEffect(()=>{s||(m({}),g({}),y(null),d(""))},[s]);const C=R=>R.merge_key||R.pdf_field_name||R.id,E=R=>{y(R),g(D=>{var U;const O={...D};for(const W of S)(W.field_kind==="signature"||W.field_kind==="initials")&&(O[W.id]={png:R}),W.field_kind==="date_signed"&&!((U=O[W.id])!=null&&U.text)&&(O[W.id]={text:new Date().toLocaleDateString("en-US")});return O}),re.success("Signature applied to the document")},I=S.filter(R=>{var D,O,U;return((D=f[R.id])==null?void 0:D.png)||((U=(O=f[R.id])==null?void 0:O.text)==null?void 0:U.trim())}).length,P=async()=>{b(!0);try{const R=await hFe(r.storage_path),D={...h},{bytes:O}=await Har({templateBytes:R,mappings:i,values:D,signerBoxes:S,entries:f}),W=`${n.name.replace(/[^a-zA-Z0-9-_ ]/g,"").trim()||"Form"} - signed.pdf`,V=O.buffer.slice(O.byteOffset,O.byteOffset+O.byteLength),G=new Blob([V],{type:"application/pdf"}),Y=URL.createObjectURL(G),X=document.createElement("a");if(X.href=Y,X.download=W,X.click(),URL.revokeObjectURL(Y),c&&a){const ae=`${a}/${c}/${crypto.randomUUID()}.pdf`,{error:ie}=await q.storage.from("deal-files").upload(ae,G,{contentType:"application/pdf"});if(ie)throw ie;const{error:ne}=await q.from("deal_files").insert({deal_id:c,owner_user_id:a,file_name:W,file_size:G.size,file_type:"application/pdf",storage_path:ae});if(ne)throw ne;await q.from("deal_activities").insert({deal_id:c,activity_type:"document",title:`Filled and signed ${n.name}`,description:`${W} was completed in LevelUp (v${r.version_number}).`,metadata:{template_id:n.id,version_id:r.id}}),re.success("Saved to the deal and downloaded")}else re.success("Your signed PDF is downloading");t(!1)}catch(R){re.error(Elt(R))}finally{b(!1)}};return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Os,{className:"flex max-h-[90vh] max-w-2xl flex-col overflow-hidden",children:[e.jsxs(Us,{children:[e.jsxs(Bs,{children:["Fill & sign — ",n.name]}),e.jsx(Ir,{children:"Type in the details, sign once and download the completed PDF. Nothing is emailed to anyone."})]}),e.jsxs("div",{className:"space-y-5 overflow-y-auto pr-1",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Prefill from a deal (optional)"}),e.jsxs(ms,{value:c||"none",onValueChange:R=>d(R==="none"?"":R),children:[e.jsx(us,{children:e.jsx(fs,{placeholder:"No deal — I'll type everything"})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"none",children:"No deal — I'll type everything"}),o.map(R=>e.jsx(Ge,{value:R.id,children:R.deal_name},R.id))]})]}),c&&e.jsx("p",{className:"text-xs text-muted-foreground",children:"The finished PDF is also saved to this deal's files."})]}),l?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx(kt,{className:"h-5 w-5 animate-spin text-muted-foreground"})}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-3",children:[e.jsx("p",{className:"text-sm font-medium",children:"Form details"}),w.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"This form has no data fields — just sign it below."}),e.jsx("div",{className:"grid gap-3 sm:grid-cols-2",children:w.map(R=>{var W;const D=C(R),O=R.merge_key?((W=Xis.get(R.merge_key))==null?void 0:W.label)||R.merge_key:R.pdf_field_name||"Field",U=R.mapping_mode==="static";return e.jsxs("div",{className:"space-y-1",children:[e.jsx(ee,{className:"text-xs text-muted-foreground",children:O}),e.jsx(pe,{value:U?R.static_value||"":h[D]??"",disabled:U,onChange:V=>m(G=>({...G,[D]:V.target.value}))})]},R.id)})})]}),e.jsxs("div",{className:"space-y-3 rounded-lg border p-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("p",{className:"flex items-center gap-2 text-sm font-medium",children:[e.jsx(wf,{className:"h-4 w-4"})," Your signature"]}),S.length>0&&e.jsxs(Be,{variant:I===S.length?"default":"outline",children:[I,"/",S.length," placed"]})]}),S.length===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:"No signature spots are placed on this form yet. Use “Place fields & signatures” first."}):e.jsxs(e.Fragment,{children:[x?e.jsxs("div",{className:"flex items-center gap-3 rounded-md border bg-white p-3",children:[e.jsx("img",{src:x,alt:"Your signature",className:"h-12 object-contain"}),e.jsx($,{variant:"ghost",size:"sm",onClick:()=>y(null),children:"Redo"})]}):e.jsx(War,{label:"signature",onAdopt:E}),e.jsx("div",{className:"space-y-2",children:S.filter(R=>R.field_kind==="printed_name"||R.field_kind==="text"||R.field_kind==="date_signed").map(R=>{var D;return e.jsxs("div",{className:"space-y-1",children:[e.jsxs(ee,{className:"text-xs text-muted-foreground",children:[Yar[R.field_kind||"text"]," · page ",(R.page_index??0)+1,R.signer_role?` · ${mFe(R.signer_role)}`:""]}),e.jsx(pe,{value:((D=f[R.id])==null?void 0:D.text)??"",onChange:O=>g(U=>({...U,[R.id]:{text:O.target.value}}))})]},R.id)})}),e.jsxs("p",{className:"flex items-start gap-2 text-xs text-muted-foreground",children:[e.jsx(qr,{className:"mt-0.5 h-3.5 w-3.5 shrink-0"}),"By signing you agree your electronic signature is legally binding on this document."]})]})]})]})]}),e.jsxs(Ar,{children:[e.jsx($,{variant:"outline",onClick:()=>t(!1),disabled:v,children:"Cancel"}),e.jsxs($,{onClick:P,disabled:v||l,children:[v?e.jsx(kt,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(di,{className:"mr-2 h-4 w-4"}),"Finish & download"]})]})]})})}function Xar({status:s}){return s==="mapped"?e.jsx(Be,{className:"bg-emerald-500/15 text-emerald-600 hover:bg-emerald-500/15",children:"Ready"}):s==="needs_placement"?e.jsx(Be,{variant:"outline",children:"Needs field placement"}):e.jsx(Be,{variant:"secondary",children:"Needs mapping"})}function Qar(){var X,ae;const{data:s=[],isLoading:t,error:n}=Mlt(),{data:r=[]}=rY(),a=Yis(),i=Zis(),l=hrr(),[o,c]=j.useState(!1),[d,u]=j.useState(null),[h,m]=j.useState(null),[f,g]=j.useState(""),[x,y]=j.useState(null),[v,b]=j.useState(""),[w,S]=j.useState(null),[C,E]=j.useState("generate"),[I,P]=j.useState(null),[R,D]=j.useState("all"),O=s.some(ie=>ie.scope==="brokerage"),U=s.filter(ie=>ie.name.toLowerCase().includes(f.trim().toLowerCase())).filter(ie=>R==="all"||(ie.scope||"mine")===R).sort((ie,ne)=>(ie.scope==="brokerage"?1:0)-(ne.scope==="brokerage"?1:0)),W=async ie=>{try{await l.mutateAsync(ie),re.success(`"${ie.name}" copied to your forms`)}catch(ne){re.error((ne==null?void 0:ne.message)||"Could not copy that form")}},V=h?s.find(ie=>ie.id===h.id)||h:null,G=wx(V),Y=async ie=>{if(await fo(`Delete "${ie.name}" and all of its versions? Forms already generated stay on their deals.`))try{await i.mutateAsync(ie),(h==null?void 0:h.id)===ie.id&&m(null),re.success("Template deleted")}catch(ne){re.error((ne==null?void 0:ne.message)||"Could not delete the template")}};return e.jsxs(Vs,{children:[e.jsxs("div",{className:"mx-auto w-full max-w-6xl space-y-6 px-4 py-6 sm:px-6",children:[e.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-end sm:justify-between",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-semibold tracking-tight",children:"Forms Library"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Upload blank PDF forms you are permitted to use, map their fields once, then fill them from any deal."})]}),e.jsxs($,{onClick:()=>c(!0),children:[e.jsx(dn,{className:"mr-2 h-4 w-4"})," Upload template"]})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsxs("div",{className:"relative w-full max-w-sm",children:[e.jsx(Kr,{className:"pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(pe,{className:"pl-9",placeholder:"Search templates…",value:f,onChange:ie=>g(ie.target.value)})]}),O&&e.jsx("div",{className:"flex gap-1 rounded-lg border p-1",children:[["all","All"],["mine","My forms"],["brokerage","Brokerage forms"]].map(([ie,ne])=>e.jsx($,{size:"sm",variant:R===ie?"secondary":"ghost",className:"h-7 text-xs",onClick:()=>D(ie),children:ne},ie))})]}),t&&e.jsx("div",{className:"flex justify-center py-16",children:e.jsx(kt,{className:"h-6 w-6 animate-spin text-muted-foreground"})}),n&&e.jsx(Ne,{children:e.jsx(Ie,{className:"p-6 text-center text-sm text-destructive",children:"Could not load your templates. Please refresh and try again."})}),!t&&!n&&s.length===0&&e.jsx(Ne,{className:"border-dashed",children:e.jsxs(Ie,{className:"flex flex-col items-center gap-3 p-12 text-center",children:[e.jsx("div",{className:"flex h-12 w-12 items-center justify-center rounded-full bg-muted",children:e.jsx(Jr,{className:"h-6 w-6 text-muted-foreground"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:"No form templates yet"}),e.jsx("p",{className:"mx-auto max-w-sm text-sm text-muted-foreground",children:"Upload a blank PDF form you are legally permitted to use. LevelUp reads its fillable fields so you can map them to your deal, contact and agent data."})]}),e.jsxs($,{onClick:()=>c(!0),children:[e.jsx(ni,{className:"mr-2 h-4 w-4"})," Upload your first template"]})]})}),!t&&!n&&s.length>0&&e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2 lg:grid-cols-3",children:[U.map(ie=>{var J;const ne=wx(ie),te=ie.scope==="brokerage";return e.jsx(Ne,{className:"transition-shadow hover:shadow-md",children:e.jsxs(Ie,{className:"space-y-3 p-4",children:[e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"flex h-10 w-10 shrink-0 items-center justify-center rounded-lg bg-primary/10",children:e.jsx(Jr,{className:"h-5 w-5 text-primary"})}),e.jsxs("button",{className:"min-w-0 flex-1 text-left",onClick:()=>m(ie),children:[e.jsx("p",{className:"truncate font-medium",children:ie.name}),te&&e.jsxs(Be,{variant:"outline",className:"mt-1 gap-1 text-[10px]",children:[e.jsx(ji,{className:"h-3 w-3"})," Brokerage form"]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[(J=Tlt.find(ce=>ce.value===ie.category))==null?void 0:J.label," · v",(ne==null?void 0:ne.version_number)??1,ne?` · ${ne.page_count} page${ne.page_count===1?"":"s"}`:""]})]}),e.jsxs(Uu,{children:[e.jsx(qu,{asChild:!0,children:e.jsx($,{variant:"ghost",size:"icon",className:"h-8 w-8",children:e.jsx(ty,{className:"h-4 w-4"})})}),e.jsx(Eu,{align:"end",children:te?e.jsxs(e.Fragment,{children:[e.jsx(ja,{onClick:()=>m(ie),children:"View details"}),e.jsxs(ja,{disabled:l.isPending,onClick:()=>W(ie),children:[e.jsx(Ha,{className:"mr-2 h-4 w-4"})," Copy to my forms"]}),e.jsxs(ja,{disabled:(ne==null?void 0:ne.mapping_status)!=="mapped",onClick:()=>P(ie),children:[e.jsx(wf,{className:"mr-2 h-4 w-4"})," Fill & sign"]})]}):e.jsxs(e.Fragment,{children:[e.jsx(ja,{onClick:()=>m(ie),children:"Open & map fields"}),e.jsxs(ja,{onClick:()=>S(ie),children:[e.jsx(Qf,{className:"mr-2 h-4 w-4"})," Place fields & signatures"]}),e.jsxs(ja,{disabled:(ne==null?void 0:ne.mapping_status)!=="mapped",onClick:()=>{E("sign"),y(ie),b("")},children:[e.jsx(wf,{className:"mr-2 h-4 w-4"})," Send for signature"]}),e.jsxs(ja,{disabled:(ne==null?void 0:ne.mapping_status)!=="mapped",onClick:()=>P(ie),children:[e.jsx(wf,{className:"mr-2 h-4 w-4"})," Fill & sign myself"]}),e.jsxs(ja,{onClick:()=>u(ie),children:[e.jsx(ni,{className:"mr-2 h-4 w-4"})," Upload new version"]}),e.jsxs(ja,{onClick:()=>a.mutate({id:ie.id,patch:{is_archived:!0}}),children:[e.jsx(Sv,{className:"mr-2 h-4 w-4"})," Archive"]}),e.jsxs(ja,{className:"text-destructive",onClick:()=>Y(ie),children:[e.jsx(Wn,{className:"mr-2 h-4 w-4"})," Delete"]})]})})]})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(Xar,{status:ne==null?void 0:ne.mapping_status}),e.jsxs("div",{className:"flex gap-1",children:[e.jsxs($,{variant:"ghost",size:"sm",disabled:(ne==null?void 0:ne.mapping_status)!=="mapped",onClick:()=>P(ie),children:[e.jsx(wf,{className:"mr-1.5 h-4 w-4"})," Fill & sign"]}),e.jsxs($,{variant:"ghost",size:"sm",disabled:(ne==null?void 0:ne.mapping_status)!=="mapped",onClick:()=>{E("sign"),y(ie),b("")},children:[e.jsx(wf,{className:"mr-1.5 h-4 w-4"})," Send"]}),e.jsxs($,{variant:"ghost",size:"sm",disabled:(ne==null?void 0:ne.mapping_status)!=="mapped",onClick:()=>{E("generate"),y(ie),b("")},children:[e.jsx(Dq,{className:"mr-1.5 h-4 w-4"})," Use"]})]})]})]})},ie.id)}),U.length===0&&e.jsx("p",{className:"col-span-full py-10 text-center text-sm text-muted-foreground",children:"No templates match that search."})]}),!t&&!n&&s.length>0&&e.jsx("div",{className:"border-t pt-6",children:e.jsx(qar,{templates:s})})]}),e.jsx(Wy,{open:!!V,onOpenChange:ie=>!ie&&m(null),children:e.jsxs(py,{side:"right",className:"w-full overflow-y-auto sm:max-w-2xl",children:[e.jsxs(D0,{className:"space-y-1 text-left",children:[e.jsxs("button",{className:"flex items-center gap-1 text-xs text-muted-foreground sm:hidden",onClick:()=>m(null),children:[e.jsx(qa,{className:"h-3 w-3"})," Back"]}),e.jsx(F0,{children:V==null?void 0:V.name}),G&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["v",G.version_number," · ",G.file_name," · ",Plt(G.file_size)," · uploaded ",en(new Date(G.created_at),"MMM d, yyyy")]})]}),e.jsxs("div",{className:"mt-5 space-y-4",children:[(V==null?void 0:V.description)&&e.jsx("p",{className:"text-sm text-muted-foreground",children:V.description}),G?e.jsx(e.Fragment,{children:(V==null?void 0:V.scope)==="brokerage"?e.jsxs("div",{className:"rounded-lg border bg-muted/40 p-4 text-sm text-muted-foreground",children:[e.jsxs("p",{className:"flex items-center gap-2 font-medium text-foreground",children:[e.jsx(ji,{className:"h-4 w-4"})," Managed by your brokerage"]}),e.jsx("p",{className:"mt-1",children:"Fields on this form are set up by your brokerage. You can fill it from any deal or send it for signature. Need your own version? Use “Copy to my forms”."}),e.jsxs($,{variant:"outline",className:"mt-3 w-full",disabled:l.isPending,onClick:()=>V&&W(V),children:[e.jsx(Ha,{className:"mr-2 h-4 w-4"})," Copy to my forms"]})]}):e.jsxs(e.Fragment,{children:[e.jsxs($,{variant:"outline",className:"w-full",onClick:()=>V&&S(V),children:[e.jsx(Qf,{className:"mr-2 h-4 w-4"})," Place fields & signatures on the document"]}),e.jsx(oos,{version:G})]})}):e.jsx("p",{className:"text-sm text-muted-foreground",children:"This template has no uploaded version yet."})]})]})}),e.jsx(zPe,{open:o,onOpenChange:c}),e.jsx(zPe,{open:!!d,onOpenChange:ie=>!ie&&u(null),templateId:d==null?void 0:d.id,templateName:d==null?void 0:d.name}),e.jsx(Wy,{open:!!x&&!v,onOpenChange:ie=>!ie&&y(null),children:e.jsxs(py,{side:"bottom",className:"space-y-4",children:[e.jsx(D0,{className:"text-left",children:e.jsx(F0,{children:"Choose a deal"})}),r.length===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:"You don’t have any deals yet."}):e.jsxs(ms,{value:v,onValueChange:b,children:[e.jsx(us,{className:"max-w-md",children:e.jsx(fs,{placeholder:"Select a deal"})}),e.jsx(hs,{children:r.map(ie=>e.jsx(Ge,{value:ie.id,children:ie.deal_name},ie.id))})]})]})}),x&&v&&C==="generate"&&e.jsx(Qis,{open:!0,onOpenChange:ie=>{ie||(y(null),b(""))},dealId:v,dealName:(X=r.find(ie=>ie.id===v))==null?void 0:X.deal_name,initialTemplateId:x.id}),x&&v&&C==="sign"&&e.jsx(tos,{open:!0,onOpenChange:ie=>{ie||(y(null),b(""))},dealId:v,dealName:(ae=r.find(ie=>ie.id===v))==null?void 0:ae.deal_name,initialTemplateId:x.id}),w&&wx(w)&&e.jsx(los,{open:!0,onOpenChange:ie=>!ie&&S(null),version:wx(w),templateName:w.name}),I&&wx(I)&&e.jsx(Zar,{open:!0,onOpenChange:ie=>!ie&&P(null),template:I,version:wx(I)})]})}function dos({open:s,onOpenChange:t,editTask:n,defaultDealId:r,defaultStageId:a}){var W;const i=uar(),l=har(),{data:o}=rY(),c=Sa(),{data:d}=tt({queryKey:["contacts-for-tasks",c],queryFn:async()=>{if(!c)return[];const{data:V,error:G}=await q.from("innercircle_contacts").select("id, first_name, last_name").eq("owner_user_id",c).order("first_name").limit(500);if(G)throw G;return V},enabled:!!c&&s}),[u,h]=j.useState(""),[m,f]=j.useState(""),[g,x]=j.useState("none"),[y,v]=j.useState("none"),[b,w]=j.useState("medium"),[S,C]=j.useState("todo"),[E,I]=j.useState(),[P,R]=j.useState(!1),[D,O]=j.useState(!1);j.useEffect(()=>{n?(h(n.title),f(n.description||""),x(n.deal_id||"none"),v(n.contact_id||"none"),w(n.priority),C(n.status),I(n.due_date?vv(n.due_date):void 0)):(h(""),f(""),x(r||"none"),v("none"),w("medium"),C("todo"),I(void 0))},[n,s,r]);const U=async()=>{if(!u.trim()){re.error("Task title is required");return}try{const V={title:u.trim(),description:m.trim()||null,deal_id:g==="none"?null:g,contact_id:y==="none"?null:y,stage_id:a||null,priority:b,status:S,due_date:E?en(E,"yyyy-MM-dd"):null};n?(await l.mutateAsync({id:n.id,...V}),re.success("Task updated")):(await i.mutateAsync(V),re.success("Task created")),t(!1)}catch{re.error("Failed to save task")}};return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Os,{className:"sm:max-w-[480px]",children:[e.jsx(Us,{children:e.jsx(Bs,{children:n?"Edit Task":"New Task"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(ee,{children:"Title *"}),e.jsx(pe,{value:u,onChange:V=>h(V.target.value),placeholder:"e.g., Send inspection report"})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Description"}),e.jsx(Rs,{value:m,onChange:V=>f(V.target.value),placeholder:"Optional details...",rows:2})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(ee,{children:"Priority"}),e.jsxs(ms,{value:b,onValueChange:V=>w(V),children:[e.jsx(us,{children:e.jsx(fs,{})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"low",children:"🟢 Low"}),e.jsx(Ge,{value:"medium",children:"🟡 Medium"}),e.jsx(Ge,{value:"high",children:"🟠 High"}),e.jsx(Ge,{value:"urgent",children:"🔴 Urgent"})]})]})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Status"}),e.jsxs(ms,{value:S,onValueChange:V=>C(V),children:[e.jsx(us,{children:e.jsx(fs,{})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"todo",children:"To Do"}),e.jsx(Ge,{value:"in_progress",children:"In Progress"}),e.jsx(Ge,{value:"done",children:"Done"})]})]})]})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Due Date"}),e.jsxs(Yd,{children:[e.jsx(Zd,{asChild:!0,children:e.jsxs($,{variant:"outline",className:Pt("w-full justify-start text-left font-normal",!E&&"text-muted-foreground"),children:[e.jsx(Ta,{className:"mr-2 h-4 w-4"}),E?en(E,"PPP"):"Pick a date"]})}),e.jsx(Bd,{className:"w-auto p-0",align:"start",children:e.jsx(D2,{mode:"single",selected:E,onSelect:I,initialFocus:!0,className:"p-3 pointer-events-auto"})})]})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Link to Deal"}),e.jsxs(Yd,{open:P,onOpenChange:R,children:[e.jsx(Zd,{asChild:!0,children:e.jsxs($,{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(ji,{className:"h-3.5 w-3.5 text-muted-foreground shrink-0"}),g!=="none"?((W=o==null?void 0:o.find(V=>V.id===g))==null?void 0:W.deal_name)||"Select deal":"No Deal"]}),e.jsx(Pw,{className:"h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(Bd,{className:"w-[--radix-popover-trigger-width] p-0",align:"start",children:e.jsxs(P2,{children:[e.jsx(I2,{placeholder:"Search deals..."}),e.jsxs(L2,{children:[e.jsx(R2,{children:"No deals found."}),e.jsxs(Uw,{children:[e.jsxs(g1,{value:"no-deal",onSelect:()=>{x("none"),R(!1)},children:[e.jsx(la,{className:Pt("mr-2 h-4 w-4",g==="none"?"opacity-100":"opacity-0")}),"No Deal"]}),o==null?void 0:o.map(V=>e.jsxs(g1,{value:V.deal_name,onSelect:()=>{x(V.id),R(!1)},children:[e.jsx(la,{className:Pt("mr-2 h-4 w-4",g===V.id?"opacity-100":"opacity-0")}),V.deal_name]},V.id))]})]})]})})]})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Link to Contact"}),e.jsxs(Yd,{open:D,onOpenChange:O,children:[e.jsx(Zd,{asChild:!0,children:e.jsxs($,{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(sl,{className:"h-3.5 w-3.5 text-muted-foreground shrink-0"}),y!=="none"?(()=>{const V=d==null?void 0:d.find(G=>G.id===y);return V?`${V.first_name} ${V.last_name}`:"Select contact"})():"No Contact"]}),e.jsx(Pw,{className:"h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(Bd,{className:"w-[--radix-popover-trigger-width] p-0",align:"start",children:e.jsxs(P2,{children:[e.jsx(I2,{placeholder:"Search contacts..."}),e.jsxs(L2,{children:[e.jsx(R2,{children:"No contacts found."}),e.jsxs(Uw,{children:[e.jsxs(g1,{value:"no-contact",onSelect:()=>{v("none"),O(!1)},children:[e.jsx(la,{className:Pt("mr-2 h-4 w-4",y==="none"?"opacity-100":"opacity-0")}),"No Contact"]}),d==null?void 0:d.map(V=>e.jsxs(g1,{value:`${V.first_name} ${V.last_name}`,onSelect:()=>{v(V.id),O(!1)},children:[e.jsx(la,{className:Pt("mr-2 h-4 w-4",y===V.id?"opacity-100":"opacity-0")}),V.first_name," ",V.last_name]},V.id))]})]})]})})]})]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[e.jsx($,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsx($,{onClick:U,disabled:i.isPending||l.isPending,children:n?"Save Changes":"Create Task"})]})]})]})})}const Jar={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 eir({tasks:s}){const t=fFe(),n=mar(),r=Qn(),[a,i]=j.useState(null),l=async u=>{const h=u.status==="done"?"todo":"done";try{await t.mutateAsync({id:u.id,status:h})}catch{re.error("Failed to update task")}},o=async u=>{try{await n.mutateAsync(u),re.success("Task deleted")}catch{re.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(qr,{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(u=>{if(u.deal){const h=c.get(u.deal.id)||{dealName:u.deal.deal_name,tasks:[]};h.tasks.push(u),c.set(u.deal.id,h)}else d.push(u)}),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(u=>e.jsx(oEt,{task:u,onToggle:l,onDelete:o,onEdit:i,onNavigateDeal:h=>r(`/mission-control/pipeline?deal=${h}`)},u.id))]}),Array.from(c.entries()).map(([u,h])=>e.jsxs("div",{className:"border rounded-lg overflow-hidden",children:[e.jsxs("button",{onClick:()=>r(`/mission-control/pipeline?deal=${u}`),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(ji,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("h3",{className:"font-medium text-sm",children:h.dealName}),e.jsxs(Be,{variant:"secondary",className:"ml-auto text-xs",children:[h.tasks.filter(m=>m.status==="done").length,"/",h.tasks.length]}),e.jsx(Di,{className:"h-3.5 w-3.5 text-muted-foreground"})]}),h.tasks.map(m=>e.jsx(oEt,{task:m,onToggle:l,onDelete:o,onEdit:i,onNavigateDeal:f=>r(`/mission-control/pipeline?deal=${f}`)},m.id))]},u)),a&&e.jsx(dos,{open:!!a,onOpenChange:()=>i(null),editTask:a})]})}function oEt({task:s,onToggle:t,onDelete:n,onEdit:r,onNavigateDeal:a}){const i=s.status==="done",l=!i&&s.due_date&&z4(vv(s.due_date))&&!Nv(vv(s.due_date)),o=!i&&s.due_date&&Nv(vv(s.due_date)),c=Jar[s.priority];return e.jsxs("div",{className:Pt("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(qr,{className:"h-5 w-5 text-emerald-500"}):e.jsx(Og,{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:Pt("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(sl,{className:"h-2.5 w-2.5"}),s.contact.first_name," ",s.contact.last_name]})]})]}),e.jsxs(Be,{variant:"outline",className:Pt("text-[10px] shrink-0",c.color),children:[c.dot," ",c.label]}),s.due_date&&e.jsxs("span",{className:Pt("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(da,{className:"h-3 w-3"}),en(vv(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:()=>r(s),className:"p-1 hover:bg-muted rounded",children:e.jsx(_p,{className:"h-3.5 w-3.5 text-muted-foreground"})}),e.jsx("button",{onClick:()=>n(s.id),className:"p-1 hover:bg-destructive/10 rounded",children:e.jsx(Wn,{className:"h-3.5 w-3.5 text-destructive"})})]})]})}const tir=[{status:"todo",label:"To Do",icon:Og,color:"border-t-slate-400"},{status:"in_progress",label:"In Progress",icon:tf,color:"border-t-blue-500"},{status:"done",label:"Done",icon:qr,color:"border-t-emerald-500"}],sir={urgent:"🔴",high:"🟠",medium:"🟡",low:"🟢"};function nir({tasks:s}){const t=fFe(),n=j.useMemo(()=>{const i={todo:[],in_progress:[],done:[]};return s.forEach(l=>i[l.status].push(l)),i},[s]),r=(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{re.error("Failed to move task")}};return e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:tir.map(i=>e.jsxs("div",{className:Pt("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(Be,{variant:"secondary",className:"ml-auto text-xs",children:n[i.status].length})]}),e.jsxs("div",{className:"p-2 space-y-2 min-h-[200px]",children:[n[i.status].map(l=>e.jsx(rir,{task:l,onDragStart:r},l.id)),n[i.status].length===0&&e.jsx("p",{className:"text-xs text-muted-foreground text-center py-8",children:"Drag tasks here"})]})]},i.status))})}function rir({task:s,onDragStart:t}){const n=s.status==="done",r=!n&&s.due_date&&z4(vv(s.due_date))&&!Nv(vv(s.due_date)),a=!n&&s.due_date&&Nv(vv(s.due_date));return e.jsx("div",{draggable:!0,onDragStart:i=>t(i,s.id),className:Pt("bg-background border rounded-lg p-3 cursor-grab active:cursor-grabbing shadow-sm hover:shadow-md transition-shadow",r&&"border-destructive/50"),children:e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx("span",{className:"text-xs mt-0.5",children:sir[s.priority]}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:Pt("text-sm font-medium",n&&"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(ji,{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(sl,{className:"h-2.5 w-2.5"}),s.contact.first_name," ",s.contact.last_name]})]}),s.due_date&&e.jsxs("div",{className:Pt("text-[10px] mt-1.5 flex items-center gap-1",r&&"text-destructive font-medium",a&&"text-amber-600 font-medium",!r&&!a&&"text-muted-foreground"),children:[e.jsx(da,{className:"h-2.5 w-2.5"}),r?"Overdue — ":a?"Due today — ":"",en(vv(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 lEt={urgent:"🔴",high:"🟠",medium:"🟡",low:"🟢"};function air({tasks:s}){const[t,n]=j.useState(new Date),r=fFe(),a=Xm(t),i=yw(t),l=C1(a),o=DLe(i),c=jPs({start:l,end:o}),d=j.useMemo(()=>{const m=new Map;return s.forEach(f=>{if(!f.due_date)return;const g=f.due_date,x=m.get(g)||[];x.push(f),m.set(g,x)}),m},[s]),u=j.useMemo(()=>s.filter(m=>!m.due_date),[s]),h=async m=>{const f=m.status==="done"?"todo":"done";try{await r.mutateAsync({id:m.id,status:f})}catch{re.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($,{variant:"ghost",size:"icon",onClick:()=>n(d8(t,1)),children:e.jsx(Cd,{className:"h-4 w-4"})}),e.jsx("h3",{className:"font-semibold",children:en(t,"MMMM yyyy")}),e.jsx($,{variant:"ghost",size:"icon",onClick:()=>n(Mv(t,1)),children:e.jsx(Di,{className:"h-4 w-4"})})]}),e.jsx("div",{className:"grid grid-cols-7 text-center",children:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"].map(m=>e.jsx("div",{className:"text-xs font-medium text-muted-foreground py-2",children:m},m))}),e.jsx("div",{className:"grid grid-cols-7 border-l border-t",children:c.map(m=>{const f=en(m,"yyyy-MM-dd"),g=d.get(f)||[],x=qae(m,t),y=Nv(m);return e.jsxs("div",{className:Pt("border-r border-b min-h-[100px] p-1",!x&&"bg-muted/30",y&&"bg-primary/5"),children:[e.jsx("div",{className:Pt("text-xs font-medium mb-1 text-right px-1",!x&&"text-muted-foreground/40",y&&"text-primary font-bold"),children:en(m,"d")}),e.jsxs("div",{className:"space-y-0.5",children:[g.slice(0,3).map(v=>e.jsxs("button",{onClick:()=>h(v),className:Pt("w-full text-left text-[10px] px-1 py-0.5 rounded truncate flex items-center gap-0.5 hover:bg-muted transition-colors",v.status==="done"?"text-muted-foreground line-through":"text-foreground"),children:[v.status==="done"?e.jsx(qr,{className:"h-2.5 w-2.5 text-emerald-500 shrink-0"}):e.jsx(Og,{className:"h-2.5 w-2.5 shrink-0"}),e.jsxs("span",{className:"truncate",children:[lEt[v.priority]," ",v.title]})]},v.id)),g.length>3&&e.jsxs("p",{className:"text-[9px] text-muted-foreground text-center",children:["+",g.length-3," more"]})]})]},f)})}),u.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 (",u.length,")"]}),e.jsx("div",{className:"space-y-1",children:u.map(m=>e.jsxs("button",{onClick:()=>h(m),className:Pt("w-full text-left text-xs px-2 py-1.5 rounded flex items-center gap-2 hover:bg-muted transition-colors",m.status==="done"&&"opacity-50 line-through"),children:[m.status==="done"?e.jsx(qr,{className:"h-3.5 w-3.5 text-emerald-500 shrink-0"}):e.jsx(Og,{className:"h-3.5 w-3.5 shrink-0"}),e.jsxs("span",{className:"truncate",children:[lEt[m.priority]," ",m.title]}),m.deal&&e.jsxs("span",{className:"text-muted-foreground ml-auto shrink-0",children:["• ",m.deal.deal_name]})]},m.id))})]})]})}const iir={urgent:"🔴",high:"🟠",medium:"🟡",low:"🟢"};function oir({open:s,onOpenChange:t,stages:n}){var v;const[r,a]=j.useState(((v=n[0])==null?void 0:v.id)||""),{data:i,isLoading:l}=par(r||void 0),o=gar(),c=xar(),[d,u]=j.useState(""),[h,m]=j.useState("medium"),[f,g]=j.useState(""),x=async()=>{if(!(!d.trim()||!r))try{await o.mutateAsync({stage_id:r,title:d.trim(),priority:h,default_due_offset_days:f?parseInt(f):null,sort_order:((i==null?void 0:i.length)||0)+1}),u(""),g(""),re.success("Template added")}catch{re.error("Failed to add template")}},y=async b=>{try{await c.mutateAsync(b),re.success("Template deleted")}catch{re.error("Failed to delete template")}};return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Os,{className:"sm:max-w-[560px]",children:[e.jsx(Us,{children:e.jsxs(Bs,{className:"flex items-center gap-2",children:[e.jsx(kJ,{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(ee,{children:"Pipeline Stage"}),e.jsx("div",{className:"flex flex-wrap gap-1.5 mt-1.5",children:n.filter(b=>!b.is_won_stage&&!b.is_lost_stage).map(b=>e.jsx("button",{onClick:()=>a(b.id),className:Pt("px-3 py-1.5 rounded-full text-xs font-medium border transition-colors",r===b.id?"border-primary bg-primary/10 text-primary":"border-border hover:bg-muted"),children:b.name},b.id))})]}),e.jsx(uo,{className:"max-h-[250px]",children:e.jsxs("div",{className:"space-y-1.5",children:[i==null?void 0:i.map((b,w)=>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:iir[b.priority]}),e.jsx("span",{className:"text-sm flex-1 truncate",children:b.title}),b.default_due_offset_days&&e.jsxs(Be,{variant:"outline",className:"text-[10px]",children:["+",b.default_due_offset_days,"d"]}),e.jsx("button",{onClick:()=>y(b.id),className:"opacity-0 group-hover:opacity-100 p-1 hover:bg-destructive/10 rounded transition-opacity",children:e.jsx(Wn,{className:"h-3.5 w-3.5 text-destructive"})})]},b.id)),(i==null?void 0:i.length)===0&&r&&e.jsx("p",{className:"text-sm text-muted-foreground text-center py-6",children:"No templates for this stage yet"})]})}),r&&e.jsxs("div",{className:"space-y-3 border-t pt-3",children:[e.jsx(ee,{className:"text-xs text-muted-foreground",children:"Add Template Task"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(pe,{placeholder:"Task title...",value:d,onChange:b=>u(b.target.value),className:"flex-1",onKeyDown:b=>b.key==="Enter"&&x()}),e.jsxs(ms,{value:h,onValueChange:b=>m(b),children:[e.jsx(us,{className:"w-[100px]",children:e.jsx(fs,{})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"low",children:"🟢 Low"}),e.jsx(Ge,{value:"medium",children:"🟡 Med"}),e.jsx(Ge,{value:"high",children:"🟠 High"}),e.jsx(Ge,{value:"urgent",children:"🔴 Urgent"})]})]})]}),e.jsxs("div",{className:"flex gap-2 items-end",children:[e.jsxs("div",{className:"flex-1",children:[e.jsx(ee,{className:"text-xs",children:"Due offset (days from entering stage)"}),e.jsx(pe,{type:"number",placeholder:"e.g., 7",value:f,onChange:b=>g(b.target.value)})]}),e.jsxs($,{onClick:x,disabled:!d.trim()||o.isPending,children:[e.jsx(dn,{className:"h-4 w-4 mr-1"}),"Add"]})]})]})]})})}function lir(){const{data:s,isLoading:t}=ros(),{data:n}=Jie(),[r,a]=j.useState("list"),[i,l]=j.useState(""),[o,c]=j.useState("active"),[d,u]=j.useState("all"),[h,m]=j.useState("all"),[f,g]=j.useState(!1),[x,y]=j.useState(!1),v=j.useMemo(()=>{if(!s)return[];const S=new Map;return s.forEach(C=>{C.deal&&S.set(C.deal.id,C.deal.deal_name)}),Array.from(S,([C,E])=>({id:C,name:E}))},[s]),b=j.useMemo(()=>s?s.filter(S=>{var D,O,U,W;const C=i.toLowerCase(),E=!C||S.title.toLowerCase().includes(C)||((O=(D=S.deal)==null?void 0:D.deal_name)==null?void 0:O.toLowerCase().includes(C))||`${((U=S.contact)==null?void 0:U.first_name)||""} ${((W=S.contact)==null?void 0:W.last_name)||""}`.toLowerCase().includes(C),I=o==="all"||o==="active"&&S.status!=="done"||o==="todo"&&S.status==="todo"||o==="in_progress"&&S.status==="in_progress"||o==="done"&&S.status==="done"||o==="overdue"&&S.status!=="done"&&S.due_date&&z4(vv(S.due_date))&&!Nv(vv(S.due_date)),P=d==="all"||S.priority===d,R=h==="all"||h==="no_deal"&&!S.deal_id||S.deal_id===h;return E&&I&&P&&R}):[],[s,i,o,d,h]),w=j.useMemo(()=>{if(!s)return{total:0,overdue:0,dueToday:0,dueThisWeek:0,completed:0};const S=s.filter(C=>C.status!=="done");return{total:S.length,overdue:S.filter(C=>C.due_date&&z4(vv(C.due_date))&&!Nv(vv(C.due_date))).length,dueToday:S.filter(C=>C.due_date&&Nv(vv(C.due_date))).length,dueThisWeek:S.filter(C=>C.due_date&&bLs(vv(C.due_date))).length,completed:s.filter(C=>C.status==="done").length}},[s]);return e.jsx(Vs,{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($,{variant:"outline",size:"sm",onClick:()=>y(!0),children:[e.jsx(Iw,{className:"h-4 w-4 mr-1"}),"Templates"]}),e.jsxs($,{size:"sm",onClick:()=>g(!0),children:[e.jsx(dn,{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(P0,{className:"h-3.5 w-3.5"}),"Active"]}),e.jsx("p",{className:"text-xl font-bold mt-1",children:w.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(wl,{className:"h-3.5 w-3.5"}),"Overdue"]}),e.jsx("p",{className:"text-xl font-bold mt-1 text-destructive",children:w.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(da,{className:"h-3.5 w-3.5"}),"Due Today"]}),e.jsx("p",{className:"text-xl font-bold mt-1",children:w.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(Kc,{className:"h-3.5 w-3.5"}),"This Week"]}),e.jsx("p",{className:"text-xl font-bold mt-1",children:w.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(qr,{className:"h-3.5 w-3.5"}),"Completed"]}),e.jsx("p",{className:"text-xl font-bold mt-1",children:w.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(Kr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(pe,{placeholder:"Search tasks...",value:i,onChange:S=>l(S.target.value),className:"pl-9"})]}),e.jsxs(ms,{value:d,onValueChange:u,children:[e.jsx(us,{className:"w-[130px]",children:e.jsx(fs,{placeholder:"Priority"})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"all",children:"All Priorities"}),e.jsx(Ge,{value:"urgent",children:"🔴 Urgent"}),e.jsx(Ge,{value:"high",children:"🟠 High"}),e.jsx(Ge,{value:"medium",children:"🟡 Medium"}),e.jsx(Ge,{value:"low",children:"🟢 Low"})]})]}),e.jsxs(ms,{value:h,onValueChange:m,children:[e.jsx(us,{className:"w-[160px]",children:e.jsx(fs,{placeholder:"Deal"})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"all",children:"All Deals"}),e.jsx(Ge,{value:"no_deal",children:"No Deal"}),v.map(S=>e.jsx(Ge,{value:S.id,children:S.name},S.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 ${r==="list"?"bg-primary text-primary-foreground":"text-muted-foreground hover:text-foreground"}`,children:e.jsx(P0,{className:"h-4 w-4"})}),e.jsx("button",{onClick:()=>a("kanban"),className:`p-1.5 rounded-md transition-colors ${r==="kanban"?"bg-primary text-primary-foreground":"text-muted-foreground hover:text-foreground"}`,children:e.jsx(h2,{className:"h-4 w-4"})}),e.jsx("button",{onClick:()=>a("calendar"),className:`p-1.5 rounded-md transition-colors ${r==="calendar"?"bg-primary text-primary-foreground":"text-muted-foreground hover:text-foreground"}`,children:e.jsx(Kc,{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:[r==="list"&&e.jsx(eir,{tasks:b}),r==="kanban"&&e.jsx(nir,{tasks:b}),r==="calendar"&&e.jsx(air,{tasks:b})]}),e.jsx(dos,{open:f,onOpenChange:g}),e.jsx(oir,{open:x,onOpenChange:y,stages:n||[]})]})})}function cir(s){const t=Blt(s);return t?t.toLocaleDateString("en-US",{weekday:"short",month:"short",day:"numeric"}):""}function dir({value:s,size:t=52}){const r=(t-5)/2,a=2*Math.PI*r,i=a-Math.min(100,Math.max(0,s))/100*a;return e.jsxs("div",{className:"relative shrink-0",style:{width:t,height:t},children:[e.jsxs("svg",{width:t,height:t,className:"-rotate-90",children:[e.jsx("circle",{cx:t/2,cy:t/2,r,fill:"none",strokeWidth:5,className:"stroke-muted"}),e.jsx("circle",{cx:t/2,cy:t/2,r,fill:"none",strokeWidth:5,strokeLinecap:"round",strokeDasharray:a,strokeDashoffset:i,className:"stroke-primary transition-all duration-500"})]}),e.jsxs("span",{className:"absolute inset-0 flex items-center justify-center text-[11px] font-bold",children:[Math.round(s),"%"]})]})}function she({icon:s,label:t,value:n,tone:r="default",hint:a}){const i={default:"bg-primary/10 text-primary",danger:"bg-destructive/10 text-destructive",warn:"bg-amber-500/10 text-amber-600 dark:text-amber-400",good:"bg-emerald-500/10 text-emerald-600 dark:text-emerald-400"};return e.jsxs("div",{className:"rounded-xl border bg-card p-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:Pt("h-9 w-9 rounded-lg flex items-center justify-center shrink-0",i[r]),children:e.jsx(s,{className:"h-4 w-4"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-2xl font-bold leading-none",children:n}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1 truncate",children:t})]})]}),a&&e.jsx("p",{className:"text-[11px] text-muted-foreground mt-2",children:a})]})}function uir(){const s=Qn(),{data:t,isLoading:n}=Hrr(),r=fFe(),[a,i]=j.useState(""),[l,o]=j.useState(!1),[c,d]=j.useState("all"),u=j.useMemo(()=>{let b=t||[];c==="contract"&&(b=b.filter(S=>!!S.contract_date));const w=a.trim().toLowerCase();return w&&(b=b.filter(S=>{var C,E,I,P;return((C=S.deal_name)==null?void 0:C.toLowerCase().includes(w))||((E=S.property_address)==null?void 0:E.toLowerCase().includes(w))||`${((I=S.contact)==null?void 0:I.first_name)??""} ${((P=S.contact)==null?void 0:P.last_name)??""}`.toLowerCase().includes(w)})),b},[t,a,c]),h=j.useMemo(()=>{const b=[];return(u||[]).forEach(w=>{QQ.forEach(S=>{const C=w[S.key],E=A5(C);C&&E!==null&&E<=30&&b.push({id:`${w.id}-${S.key}`,kind:"date",label:S.label,dealId:w.id,dealName:w.deal_name,date:C,days:E})}),w.tasks.filter(S=>S.status!=="done"&&S.due_date).forEach(S=>{const C=A5(S.due_date);C!==null&&C<=30&&b.push({id:S.id,kind:"task",label:S.title,dealId:w.id,dealName:w.deal_name,date:S.due_date,days:C,priority:S.priority})})}),b.sort((w,S)=>w.days-S.days)},[u]),m=j.useMemo(()=>({overdue:h.filter(b=>b.days<0),today:h.filter(b=>b.days===0),week:h.filter(b=>b.days>0&&b.days<=7),later:h.filter(b=>b.days>7)}),[h]),f=j.useMemo(()=>{const b=t||[],w=b.filter(E=>{const I=A5(E.target_close_date);return I!==null&&I>=0&&I<=7}).length,S=b.reduce((E,I)=>E+I.tasks.filter(P=>{const R=A5(P.due_date);return P.status!=="done"&&R!==null&&R<0}).length,0),C=b.reduce((E,I)=>E+(Number(I.expected_price)||0),0);return{active:b.length,closingSoon:w,overdueTasks:S,volume:C}},[t]),g=b=>b.tasks.length===0?0:b.tasks.filter(w=>w.status==="done").length/b.tasks.length*100,x=b=>s(`/mission-control/pipeline?deal=${b}`),y=async b=>{try{await r.mutateAsync({id:b,status:"done"}),re.success("Task completed")}catch{re.error("Could not update task")}},v=({title:b,items:w,tone:S})=>{if(w.length===0)return null;const C=S==="danger"?"bg-destructive":S==="warn"?"bg-amber-500":"bg-primary";return e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("div",{className:"flex items-center gap-2 px-1",children:[e.jsx("span",{className:Pt("h-1.5 w-1.5 rounded-full",C)}),e.jsx("p",{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:b}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:["(",w.length,")"]})]}),w.slice(0,12).map(E=>e.jsxs("div",{className:Pt("group flex items-center gap-3 rounded-lg border px-3 py-2 transition-colors hover:bg-muted/50",S==="danger"&&"border-destructive/30 bg-destructive/5"),children:[E.kind==="task"?e.jsx(ai,{className:"shrink-0",onCheckedChange:()=>y(E.id),"aria-label":`Complete ${E.label}`}):e.jsx(Au,{className:"h-4 w-4 text-muted-foreground shrink-0"}),e.jsxs("button",{type:"button",onClick:()=>x(E.dealId),className:"flex-1 min-w-0 text-left",children:[e.jsx("p",{className:"text-sm font-medium leading-tight truncate",children:E.label}),e.jsxs("p",{className:"text-xs text-muted-foreground truncate",children:[E.dealName," · ",cir(E.date)]})]}),e.jsx("span",{className:Pt("text-[11px] font-semibold shrink-0 tabular-nums",E.days<0?"text-destructive":E.days<=3?"text-amber-600":"text-muted-foreground"),children:E.days<0?`${Math.abs(E.days)}d late`:E.days===0?"Today":`${E.days}d`})]},E.id))]})};return e.jsxs(Vs,{children:[e.jsxs("div",{className:"p-4 sm:p-6 space-y-6 max-w-[1400px] mx-auto",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold tracking-tight",children:"Transaction Coordinator"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Every deadline, every checklist, one screen. Nothing slips."})]}),e.jsxs($,{onClick:()=>o(!0),className:"gap-2 shrink-0",children:[e.jsx(Xf,{className:"h-4 w-4"}),"Playbooks"]})]}),e.jsxs("div",{className:"grid grid-cols-2 lg:grid-cols-4 gap-3",children:[e.jsx(she,{icon:zg,label:"Active transactions",value:f.active}),e.jsx(she,{icon:nh,label:"Closing within 7 days",value:f.closingSoon,tone:"warn"}),e.jsx(she,{icon:wl,label:"Overdue tasks",value:f.overdueTasks,tone:f.overdueTasks>0?"danger":"good"}),e.jsx(she,{icon:Yl,label:"Pipeline volume",value:f.volume>=1e6?`$${(f.volume/1e6).toFixed(1)}M`:`$${Math.round(f.volume/1e3)}K`,tone:"good"})]}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-2",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(Kr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(pe,{placeholder:"Search transactions, addresses, or clients...",value:a,onChange:b=>i(b.target.value),className:"pl-9"})]}),e.jsxs("div",{className:"flex gap-1 rounded-lg border p-1 bg-card",children:[e.jsx($,{size:"sm",variant:c==="all"?"default":"ghost",onClick:()=>d("all"),className:"h-8",children:"All active"}),e.jsx($,{size:"sm",variant:c==="contract"?"default":"ghost",onClick:()=>d("contract"),className:"h-8",children:"Under contract"})]})]}),n?e.jsx("div",{className:"flex justify-center py-20",children:e.jsx(kt,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):e.jsxs("div",{className:"grid lg:grid-cols-5 gap-6",children:[e.jsx("div",{className:"lg:col-span-2 space-y-4",children:e.jsxs("div",{className:"rounded-xl border bg-card p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-4",children:[e.jsx(Au,{className:"h-4 w-4 text-primary"}),e.jsx("h2",{className:"text-sm font-semibold",children:"Deadline Radar"}),e.jsx(Be,{variant:"secondary",className:"text-[10px] ml-auto",children:"next 30 days"})]}),h.length===0?e.jsxs("div",{className:"text-center py-10",children:[e.jsx(qr,{className:"h-8 w-8 text-emerald-500 mx-auto mb-2"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Nothing due in the next 30 days."})]}):e.jsxs("div",{className:"space-y-4",children:[e.jsx(v,{title:"Overdue",items:m.overdue,tone:"danger"}),e.jsx(v,{title:"Today",items:m.today,tone:"warn"}),e.jsx(v,{title:"This week",items:m.week,tone:"warn"}),e.jsx(v,{title:"Coming up",items:m.later,tone:"default"})]})]})}),e.jsx("div",{className:"lg:col-span-3 space-y-3",children:u.length===0?e.jsxs("div",{className:"rounded-xl border border-dashed p-12 text-center",children:[e.jsx(va,{className:"h-8 w-8 text-muted-foreground mx-auto mb-3"}),e.jsx("p",{className:"font-medium",children:"No active transactions"}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:"Deals in progress will appear here with their full deadline chain."}),e.jsx($,{variant:"outline",className:"mt-4",onClick:()=>s("/mission-control/pipeline"),children:"Go to Deal Pipeline"})]}):u.map(b=>{const w=g(b),S=A5(b.target_close_date),C=b.tasks.filter(P=>P.status!=="done"),E=C.filter(P=>{const R=A5(P.due_date);return R!==null&&R<0}),I=C.filter(P=>P.due_date).sort((P,R)=>(A5(P.due_date)??0)-(A5(R.due_date)??0))[0];return e.jsx("button",{type:"button",onClick:()=>x(b.id),className:"w-full text-left rounded-xl border bg-card p-4 hover:border-primary/40 hover:shadow-sm transition-all group",children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx(dir,{value:w}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"font-semibold truncate group-hover:text-primary transition-colors",children:b.deal_name}),e.jsxs("p",{className:"text-xs text-muted-foreground truncate",children:[b.property_address||"Address TBD",b.contact&&` · ${b.contact.first_name} ${b.contact.last_name}`]})]}),e.jsx(Di,{className:"h-4 w-4 text-muted-foreground shrink-0 mt-0.5"})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5 mt-2",children:[b.stage&&e.jsx("span",{className:"text-[10px] px-2 py-0.5 rounded-full font-medium",style:{backgroundColor:`${b.stage.color}1f`,color:b.stage.color},children:b.stage.name}),e.jsx(Be,{variant:"outline",className:"text-[10px] capitalize",children:b.deal_type}),S!==null&&e.jsx(Be,{variant:"secondary",className:Pt("text-[10px]",S<0&&"bg-destructive/10 text-destructive",S>=0&&S<=7&&"bg-amber-500/10 text-amber-700 dark:text-amber-400"),children:S<0?`Closing ${Math.abs(S)}d overdue`:`Closes in ${S}d`}),E.length>0&&e.jsxs(Be,{className:"text-[10px] bg-destructive/10 text-destructive hover:bg-destructive/10",children:[E.length," overdue"]})]}),e.jsxs("div",{className:"mt-3",children:[e.jsx(Yi,{value:w,className:"h-1.5"}),e.jsxs("div",{className:"flex items-center justify-between mt-1.5 gap-2",children:[e.jsxs("p",{className:"text-[11px] text-muted-foreground",children:[b.tasks.filter(P=>P.status==="done").length," of"," ",b.tasks.length," steps complete"]}),I&&e.jsxs("p",{className:"text-[11px] text-muted-foreground truncate max-w-[55%]",children:["Next: ",I.title]})]})]}),b.tasks.length===0&&e.jsx("p",{className:"text-[11px] text-muted-foreground mt-2 italic",children:"No checklist yet — open the deal and apply a playbook."})]})]})},b.id)})})]})]}),e.jsx(nos,{open:l,onOpenChange:o})]})}function uos(){const s=Sa();return tt({queryKey:["portal-referrals",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await q.from("portal_referrals").select("*, client_portals!inner(slug, client_name, deal_id)").eq("owner_user_id",s).order("created_at",{ascending:!1});if(n)throw n;return t||[]},enabled:!!s})}function hir(){const s=Vt();return ft({mutationFn:async({id:t,...n})=>{const{data:r,error:a}=await q.from("portal_referrals").update(n).eq("id",t).select().single();if(a)throw a;return r},onSuccess:()=>{s.invalidateQueries({queryKey:["portal-referrals"]})}})}function mir(){const s=Vt();return ft({mutationFn:async t=>{const{error:n}=await q.from("portal_referrals").delete().eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["portal-referrals"]})}})}const fir=s=>new Intl.DateTimeFormat("en-US",{timeZone:"America/New_York",month:"short",day:"numeric",year:"numeric"}).format(new Date(s)),mUe=[{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"}],pir={buying:"Buying",selling:"Selling",both:"Buying & Selling",unsure:"Not sure yet"};function hos(){const{data:s=[],isLoading:t}=uos(),n=hir(),r=mir(),[a,i]=j.useState("all"),[l,o]=j.useState({}),c=j.useMemo(()=>a==="all"?s:s.filter(f=>f.status===a),[s,a]),d=j.useMemo(()=>({total:s.length,new:s.filter(f=>f.status==="new").length,converted:s.filter(f=>f.status==="converted").length}),[s]),u=(f,g)=>{n.mutate({id:f.id,status:g}),re.success("Status updated")},h=f=>{const g=l[f.id];n.mutate({id:f.id,agent_notes:g}),o(x=>{const{[f.id]:y,...v}=x;return v}),re.success("Notes saved")},m=async f=>{await fo(`Delete referral for ${f.friend_name}?`)&&r.mutate(f.id)};return e.jsxs("div",{className:"container max-w-5xl py-6 px-4",children:[e.jsx(Ml,{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(ul,{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"},...mUe.map(f=>({v:f.value,l:f.label}))].map(f=>e.jsx("button",{onClick:()=>i(f.v),className:`px-3 py-1.5 rounded-full text-xs font-medium border transition-colors ${a===f.v?"bg-primary text-primary-foreground border-primary":"bg-background text-muted-foreground border-input hover:border-primary/50"}`,children:f.l},f.v))}),t?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(kt,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):c.length===0?e.jsx(Ne,{children:e.jsxs(Ie,{className:"py-12 text-center",children:[e.jsx(ul,{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(f=>{var v,b;const g=mUe.find(w=>w.value===f.status),x=(v=f.client_portals)==null?void 0:v.slug,y=f.referrer_name||((b=f.client_portals)==null?void 0:b.client_name)||"Anonymous client";return e.jsxs(Ne,{children:[e.jsx(Ct,{className:"pb-3",children:e.jsxs("div",{className:"flex items-start justify-between flex-wrap gap-2",children:[e.jsxs("div",{children:[e.jsx(At,{className:"text-lg",children:f.friend_name}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-1 flex items-center gap-1.5",children:[e.jsx(Ta,{className:"h-3 w-3"}),"Referred by ",e.jsx("span",{className:"font-medium text-foreground",children:y})," ·"," ",fir(f.created_at)]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Be,{variant:"outline",className:g==null?void 0:g.className,children:(g==null?void 0:g.label)||f.status}),e.jsxs(ms,{value:f.status,onValueChange:w=>u(f,w),children:[e.jsx(us,{className:"h-8 w-[130px] text-xs",children:e.jsx(fs,{})}),e.jsx(hs,{children:mUe.map(w=>e.jsx(Ge,{value:w.value,className:"text-xs",children:w.label},w.value))})]})]})]})}),e.jsxs(Ie,{className:"space-y-3",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[f.friend_interest&&e.jsx(Be,{variant:"secondary",className:"text-xs",children:pir[f.friend_interest]||f.friend_interest}),f.friend_email&&e.jsxs("a",{href:`mailto:${f.friend_email}`,className:"inline-flex items-center gap-1 text-xs text-primary hover:underline",children:[e.jsx(mn,{className:"h-3 w-3"}),f.friend_email]}),f.friend_phone&&e.jsxs(e.Fragment,{children:[e.jsxs("a",{href:`tel:${f.friend_phone}`,className:"inline-flex items-center gap-1 text-xs text-primary hover:underline",children:[e.jsx(Da,{className:"h-3 w-3"}),f.friend_phone]}),e.jsxs("a",{href:`sms:${f.friend_phone}`,className:"inline-flex items-center gap-1 text-xs text-primary hover:underline",children:[e.jsx(Th,{className:"h-3 w-3"}),"Text"]})]})]}),f.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:['"',f.friend_message,'"']})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-[11px] uppercase tracking-wide text-muted-foreground mb-1",children:"Your notes"}),l[f.id]!==void 0?e.jsxs("div",{className:"space-y-2",children:[e.jsx(Rs,{value:l[f.id],onChange:w=>o(S=>({...S,[f.id]:w.target.value})),rows:3,className:"text-sm"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx($,{size:"sm",onClick:()=>h(f),children:"Save"}),e.jsx($,{size:"sm",variant:"ghost",onClick:()=>o(w=>{const{[f.id]:S,...C}=w;return C}),children:"Cancel"})]})]}):e.jsx("button",{onClick:()=>o(w=>({...w,[f.id]:f.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:f.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:[x&&e.jsxs("a",{href:`/portal/${x}`,target:"_blank",rel:"noopener noreferrer",className:"text-xs text-muted-foreground hover:text-primary inline-flex items-center gap-1",children:[e.jsx(kr,{className:"h-3 w-3"}),"View source portal"]}),e.jsx($,{variant:"ghost",size:"sm",onClick:()=>m(f),className:"text-destructive hover:text-destructive ml-auto h-8",children:e.jsx(Wn,{className:"h-3.5 w-3.5"})})]})]})]},f.id)})})]})}function mos({vendor:s,onEdit:t,onDelete:n,onToggleVisible:r,isVisible:a,showOwnerBadge:i,clickCount:l}){var c;const o=((c=dK.find(d=>d.value===s.category))==null?void 0:c.label)||s.category;return e.jsxs(Ne,{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(pc,{className:"w-3.5 h-3.5 text-amber-600","aria-label":"Required"}),s.is_featured&&e.jsx(Ja,{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(Be,{variant:"secondary",className:"text-[10px]",children:o}),i==="brokerage"&&e.jsx(Be,{variant:"outline",className:"text-[10px]",children:"Brokerage"}),i==="agent"&&e.jsx(Be,{variant:"outline",className:"text-[10px]",children:"Personal"}),!s.is_active&&e.jsx(Be,{variant:"destructive",className:"text-[10px]",children:"Inactive"}),typeof l=="number"&&l>0&&e.jsxs(Be,{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(Da,{className:"w-3 h-3"}),s.phone]}),s.email&&e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(mn,{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(dl,{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(Ta,{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(ci,{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:[r&&e.jsxs($,{size:"sm",variant:a?"default":"outline",onClick:()=>r(!a),disabled:s.is_required&&!a,className:"flex-1",children:[a?e.jsx(Ca,{className:"w-3.5 h-3.5 mr-1.5"}):e.jsx($g,{className:"w-3.5 h-3.5 mr-1.5"}),a?"Showing in portals":"Hidden"]}),t&&e.jsx($,{size:"sm",variant:"ghost",onClick:t,children:e.jsx(_p,{className:"w-3.5 h-3.5"})}),n&&e.jsx($,{size:"sm",variant:"ghost",onClick:n,className:"text-destructive",children:e.jsx(Wn,{className:"w-3.5 h-3.5"})})]})]})}function fos({open:s,onOpenChange:t,vendor:n,ownerType:r,brokerageId:a,agentUserId:i,showBrokerageOnlyFields:l}){const o=T9s(),[c,d]=j.useState({}),[u,h]=j.useState(!1),m=j.useRef(null),f=async y=>{if(!y.type.startsWith("image/")){re.error("Please select an image");return}if(y.size>5*1024*1024){re.error("Image must be under 5MB");return}h(!0);try{const v=y.name.split(".").pop()||"png",b=`${r}/${a||i||"misc"}/${Date.now()}.${v}`,{error:w}=await q.storage.from("vendor-logos").upload(b,y,{upsert:!0,contentType:y.type});if(w)throw w;const{data:S}=q.storage.from("vendor-logos").getPublicUrl(b);d(C=>({...C,logo_url:S.publicUrl})),re.success("Logo uploaded")}catch(v){re.error(v.message||"Upload failed")}finally{h(!1)}};j.useEffect(()=>{s&&d(n||{owner_type:r,owner_brokerage_id:r==="brokerage"&&a||null,owner_user_id:r==="agent"&&i||null,category:"other",action_type:"call",is_active:!0,is_featured:!1,is_required:!1})},[s,n,r,a,i]);const g=(y,v)=>d(b=>({...b,[y]:v})),x=async()=>{var y;if(!((y=c.name)!=null&&y.trim())){re.error("Name is required");return}try{await o.mutateAsync(c),re.success(n?"Vendor updated":"Vendor added"),t(!1)}catch(v){re.error(v.message||"Failed to save vendor")}};return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Os,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(Us,{children:e.jsx(Bs,{children:n?"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(ee,{children:"Contact Name *"}),e.jsx(pe,{value:c.name||"",onChange:y=>g("name",y.target.value),placeholder:"Bob Smith"})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Company"}),e.jsx(pe,{value:c.company||"",onChange:y=>g("company",y.target.value),placeholder:"Smith Inspections"})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Category"}),e.jsxs(ms,{value:c.category,onValueChange:y=>g("category",y),children:[e.jsx(us,{children:e.jsx(fs,{})}),e.jsx(hs,{children:dK.map(y=>e.jsx(Ge,{value:y.value,children:y.label},y.value))})]})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Phone"}),e.jsx(pe,{value:c.phone||"",onChange:y=>g("phone",y.target.value),placeholder:"(555) 123-4567"})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Email"}),e.jsx(pe,{type:"email",value:c.email||"",onChange:y=>g("email",y.target.value),placeholder:"bob@smithinsp.com"})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Website"}),e.jsx(pe,{value:c.website||"",onChange:y=>g("website",y.target.value),placeholder:"https://..."})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Logo"}),e.jsx("input",{ref:m,type:"file",accept:"image/*",className:"hidden",onChange:y=>{var b;const v=(b=y.target.files)==null?void 0:b[0];v&&f(v),y.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:()=>g("logo_url",""),className:"absolute -top-2 -right-2 bg-background border rounded-full p-0.5 shadow","aria-label":"Remove logo",children:e.jsx(gr,{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(ni,{className:"h-5 w-5"})}),e.jsxs($,{type:"button",variant:"outline",size:"sm",onClick:()=>{var y;return(y=m.current)==null?void 0:y.click()},disabled:u,children:[u?e.jsx(kt,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(ni,{className:"h-4 w-4 mr-2"}),c.logo_url?"Replace":"Upload Logo"]})]})]}),e.jsxs("div",{className:"md:col-span-2",children:[e.jsx(ee,{children:"Address"}),e.jsx(pe,{value:c.address||"",onChange:y=>g("address",y.target.value)})]}),e.jsxs("div",{className:"md:col-span-2",children:[e.jsx(ee,{children:"Description"}),e.jsx(Rs,{rows:3,value:c.description||"",onChange:y=>g("description",y.target.value),placeholder:"Why your clients should use this vendor..."})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Primary Action"}),e.jsxs(ms,{value:c.action_type,onValueChange:y=>g("action_type",y),children:[e.jsx(us,{children:e.jsx(fs,{})}),e.jsx(hs,{children:C9s.map(y=>e.jsx(Ge,{value:y.value,children:y.label},y.value))})]})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Booking URL (Calendly etc.)"}),e.jsx(pe,{value:c.booking_url||"",onChange:y=>g("booking_url",y.target.value),placeholder:"https://calendly.com/..."})]}),e.jsxs("div",{className:"md:col-span-2",children:[e.jsx(ee,{children:"Compliance Disclosure (optional)"}),e.jsx(Rs,{rows:2,value:c.disclosure_text||"",onChange:y=>g("disclosure_text",y.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(ee,{className:"font-medium",children:"Active"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Show this vendor in client portals"})]}),e.jsx(Sn,{checked:!!c.is_active,onCheckedChange:y=>g("is_active",y)})]}),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(ee,{className:"font-medium",children:"Featured"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Highlight in agent library"})]}),e.jsx(Sn,{checked:!!c.is_featured,onCheckedChange:y=>g("is_featured",y)})]}),e.jsxs("div",{className:"flex items-center justify-between border rounded-lg p-3",children:[e.jsxs("div",{children:[e.jsx(ee,{className:"font-medium",children:"Required"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Agents cannot hide"})]}),e.jsx(Sn,{checked:!!c.is_required,onCheckedChange:y=>g("is_required",y)})]})]})]}),e.jsxs(Ar,{children:[e.jsx($,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsx($,{onClick:x,disabled:o.isPending,children:o.isPending?"Saving...":"Save Vendor"})]})]})})}function pos({embedded:s=!1}={}){const t=Sa(),{brokerageId:n}=vs(),{data:r,isLoading:a}=E9s(),{data:i={}}=e$t("agent",t),l=Q9t(),o=M9s(),[c,d]=j.useState(null),[u,h]=j.useState(!1),[m,f]=j.useState(""),[g,x]=j.useState("all"),y=(r==null?void 0:r.vendors)||[],v=(r==null?void 0:r.selections)||[],b=j.useMemo(()=>{const D=new Map;return v.forEach(O=>D.set(O.vendor_id,O.is_visible)),D},[v]),w=j.useMemo(()=>y.filter(D=>!(g!=="all"&&D.category!==g||m&&!`${D.name} ${D.company||""}`.toLowerCase().includes(m.toLowerCase()))),[y,m,g]),S=w.filter(D=>D.owner_type==="agent"),C=w.filter(D=>D.owner_type==="brokerage"),E=async D=>{if(await fo("Delete this vendor?"))try{await l.mutateAsync(D),re.success("Vendor deleted")}catch(O){re.error(O.message)}},I=async(D,O)=>{try{await o.mutateAsync({vendorId:D,isVisible:O})}catch(U){re.error(U.message)}},P=D=>D.is_required?!0:b.get(D.id)??D.owner_type==="agent",R=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(Sx,{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($,{onClick:()=>{d(null),h(!0)},children:[e.jsx(dn,{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(Kr,{className:"w-4 h-4 absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground"}),e.jsx(pe,{className:"pl-9",placeholder:"Search vendors...",value:m,onChange:D=>f(D.target.value)})]}),e.jsxs("select",{value:g,onChange:D=>x(D.target.value),className:"border rounded-md px-3 py-2 text-sm bg-background",children:[e.jsx("option",{value:"all",children:"All categories"}),dK.map(D=>e.jsx("option",{value:D.value,children:D.label},D.value))]})]}),a?e.jsx("div",{className:"text-center text-muted-foreground py-12",children:"Loading vendors..."}):e.jsxs(ha,{defaultValue:n?"all":"personal",children:[e.jsxs(ma,{children:[e.jsxs(Zt,{value:"all",children:["All (",w.length,")"]}),n&&e.jsxs(Zt,{value:"brokerage",children:["From Brokerage (",C.length,")"]}),e.jsxs(Zt,{value:"personal",children:["My Personal (",S.length,")"]})]}),e.jsx(Xt,{value:"all",className:"mt-4",children:e.jsx(fUe,{vendors:w,isVisibleInPortals:P,onToggle:I,onEdit:D=>{d(D),h(!0)},onDelete:E,userId:t,clicks:i})}),n&&e.jsx(Xt,{value:"brokerage",className:"mt-4",children:C.length===0?e.jsx(cEt,{icon:e.jsx(Nn,{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(fUe,{vendors:C,isVisibleInPortals:P,onToggle:I,userId:t,clicks:i})}),e.jsx(Xt,{value:"personal",className:"mt-4",children:S.length===0?e.jsx(cEt,{icon:e.jsx(Sx,{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($,{onClick:()=>{d(null),h(!0)},children:[e.jsx(dn,{className:"w-4 h-4 mr-2"})," Add Your First Vendor"]})}):e.jsx(fUe,{vendors:S,isVisibleInPortals:P,onToggle:I,onEdit:D=>{d(D),h(!0)},onDelete:E,userId:t,clicks:i})})]}),e.jsx(fos,{open:u,onOpenChange:h,vendor:c,ownerType:"agent",agentUserId:t})]});return s?R:e.jsx(Vs,{children:R})}function fUe({vendors:s,isVisibleInPortals:t,onToggle:n,onEdit:r,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(mos,{vendor:o,isVisible:t(o),onToggleVisible:c=>n(o.id,c),onEdit:o.owner_type==="agent"&&o.owner_user_id===i?()=>r==null?void 0:r(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 cEt({icon:s,title:t,desc:n,action:r}){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:n}),r]})}function gir(s){return tt({queryKey:["brokerage-form-folders",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await q.from("brokerage_form_folders").select("*").eq("brokerage_id",s).order("sort_order",{ascending:!0}).order("name",{ascending:!0});if(n)throw n;return t||[]}})}function xir(s){const t=Vt(),n=()=>{t.invalidateQueries({queryKey:["brokerage-form-folders",s]}),t.invalidateQueries({queryKey:["form-templates"]})},r=ft({mutationFn:async o=>{var h;const{data:c}=await q.auth.getUser(),{data:d,error:u}=await q.from("brokerage_form_folders").insert({brokerage_id:s,name:o,created_by:((h=c.user)==null?void 0:h.id)??null}).select().single();if(u)throw u;return d},onSuccess:n}),a=ft({mutationFn:async({id:o,name:c})=>{const{error:d}=await q.from("brokerage_form_folders").update({name:c}).eq("id",o);if(d)throw d},onSuccess:n}),i=ft({mutationFn:async o=>{const{error:c}=await q.from("brokerage_form_folders").delete().eq("id",o);if(c)throw c},onSuccess:n}),l=ft({mutationFn:async({templateId:o,folderId:c})=>{const{error:d}=await q.from("form_templates").update({folder_id:c}).eq("id",o);if(d)throw d},onSuccess:n});return{createFolder:r,renameFolder:a,deleteFolder:i,moveTemplate:l}}function yir({status:s}){return s==="mapped"?e.jsx(Be,{className:"bg-emerald-500/15 text-emerald-600 hover:bg-emerald-500/15",children:"Ready"}):s==="needs_placement"?e.jsx(Be,{variant:"outline",children:"Needs field placement"}):e.jsx(Be,{variant:"secondary",children:"Needs mapping"})}function vir(){const{brokerageId:s,isBrokerageManager:t,isAdmin:n,loading:r}=vs(),{data:a=[],isLoading:i}=drr(s),l=Yis(),o=Zis(),[c,d]=j.useState(!1),[u,h]=j.useState(null),[m,f]=j.useState(null),[g,x]=j.useState(null),[y,v]=j.useState(""),[b,w]=j.useState("all"),{data:S=[]}=gir(s),{createFolder:C,deleteFolder:E,moveTemplate:I}=xir(s),P=async()=>{var G;const V=(G=window.prompt("Folder name (for example: Onboarding, Listing paperwork)"))==null?void 0:G.trim();if(V)try{const Y=await C.mutateAsync(V);w(Y.id),re.success("Folder created")}catch(Y){re.error((Y==null?void 0:Y.message)||"Could not create the folder")}};if(r)return e.jsx(Vs,{children:e.jsx("div",{className:"p-8",children:"Loading…"})});if(!t&&!n)return e.jsx(Vs,{children:e.jsx("div",{className:"p-8 text-center",children:e.jsx("h2",{className:"text-xl font-semibold",children:"Brokerage managers only"})})});const R=a.filter(V=>V.name.toLowerCase().includes(y.trim().toLowerCase())).filter(V=>b==="all"?!0:b==="unfiled"?!V.folder_id:V.folder_id===b),D=m?a.find(V=>V.id===m.id)||m:null,O=wx(D),U=async(V,G)=>{const Y=wx(V);if(G&&(Y==null?void 0:Y.mapping_status)!=="mapped"){re.error("Map and place the fields before publishing this form to your agents.");return}try{await l.mutateAsync({id:V.id,patch:{is_published:G}}),re.success(G?"Published to your agents":"Unpublished — agents can no longer use it")}catch(X){re.error((X==null?void 0:X.message)||"Could not update the form")}},W=async V=>{if(await fo(`Delete "${V.name}"? Agents will lose access. Forms already generated stay on their deals.`))try{await o.mutateAsync(V),(m==null?void 0:m.id)===V.id&&f(null),re.success("Form deleted")}catch(G){re.error((G==null?void 0:G.message)||"Could not delete the form")}};return e.jsxs(Vs,{children:[e.jsxs("div",{className:"mx-auto w-full max-w-6xl space-y-6 px-4 py-6 sm:px-6",children:[e.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-end sm:justify-between",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-semibold tracking-tight",children:"Brokerage Forms"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Build the official set of forms your agents can pick from. Map the fields once, publish, and every agent can fill them straight from a deal."})]}),e.jsxs($,{onClick:()=>d(!0),children:[e.jsx(dn,{className:"mr-2 h-4 w-4"})," Upload form"]})]}),e.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-center",children:[e.jsxs("div",{className:"relative max-w-sm flex-1",children:[e.jsx(Kr,{className:"pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(pe,{className:"pl-9",placeholder:"Search forms…",value:y,onChange:V=>v(V.target.value)})]}),e.jsxs($,{variant:"outline",size:"sm",onClick:P,children:[e.jsx(EJ,{className:"mr-2 h-4 w-4"})," New folder"]})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx($,{size:"sm",variant:b==="all"?"default":"outline",onClick:()=>w("all"),children:"All forms"}),S.map(V=>e.jsxs("div",{className:"flex items-center",children:[e.jsxs($,{size:"sm",variant:b===V.id?"default":"outline",className:"rounded-r-none",onClick:()=>w(V.id),children:[e.jsx(Oq,{className:"mr-2 h-4 w-4"}),V.name]}),e.jsx($,{size:"sm",variant:b===V.id?"default":"outline",className:"rounded-l-none border-l-0 px-2","aria-label":`Delete ${V.name} folder`,onClick:async()=>{await fo(`Delete the "${V.name}" folder? The forms inside stay in your library.`)&&(await E.mutateAsync(V.id),b===V.id&&w("all"))},children:e.jsx(Wn,{className:"h-3.5 w-3.5"})})]},V.id)),S.length>0&&e.jsx($,{size:"sm",variant:b==="unfiled"?"default":"outline",onClick:()=>w("unfiled"),children:"Unfiled"})]}),i&&e.jsx("div",{className:"flex justify-center py-16",children:e.jsx(kt,{className:"h-6 w-6 animate-spin text-muted-foreground"})}),!i&&a.length===0&&e.jsx(Ne,{className:"border-dashed",children:e.jsxs(Ie,{className:"flex flex-col items-center gap-3 p-12 text-center",children:[e.jsx("div",{className:"flex h-12 w-12 items-center justify-center rounded-full bg-muted",children:e.jsx(ji,{className:"h-6 w-6 text-muted-foreground"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:"No brokerage forms yet"}),e.jsx("p",{className:"mx-auto max-w-sm text-sm text-muted-foreground",children:"Upload the blank PDFs your office uses. Once you map their fields and publish, your agents can pick them from their Forms library and Deal → Forms tab."})]}),e.jsxs($,{onClick:()=>d(!0),children:[e.jsx(ni,{className:"mr-2 h-4 w-4"})," Upload your first form"]})]})}),!i&&a.length>0&&e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2 lg:grid-cols-3",children:[R.map(V=>{var Y;const G=wx(V);return e.jsx(Ne,{className:"transition-shadow hover:shadow-md",children:e.jsxs(Ie,{className:"space-y-3 p-4",children:[e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"flex h-10 w-10 shrink-0 items-center justify-center rounded-lg bg-primary/10",children:e.jsx(Jr,{className:"h-5 w-5 text-primary"})}),e.jsxs("button",{className:"min-w-0 flex-1 text-left",onClick:()=>f(V),children:[e.jsx("p",{className:"truncate font-medium",children:V.name}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[(Y=Tlt.find(X=>X.value===V.category))==null?void 0:Y.label," · v",(G==null?void 0:G.version_number)??1,G?` · ${G.page_count} page${G.page_count===1?"":"s"}`:""]})]}),e.jsxs(Uu,{children:[e.jsx(qu,{asChild:!0,children:e.jsx($,{variant:"ghost",size:"icon",className:"h-8 w-8",children:e.jsx(ty,{className:"h-4 w-4"})})}),e.jsxs(Eu,{align:"end",children:[e.jsx(ja,{onClick:()=>f(V),children:"Open & map fields"}),e.jsxs(ja,{onClick:()=>x(V),children:[e.jsx(Qf,{className:"mr-2 h-4 w-4"})," Place fields & signatures"]}),e.jsxs(ja,{onClick:()=>h(V),children:[e.jsx(ni,{className:"mr-2 h-4 w-4"})," Upload new version"]}),S.length>0&&e.jsxs(e.Fragment,{children:[e.jsx(R0,{}),e.jsx(SL,{className:"text-xs font-normal text-muted-foreground",children:"Move to folder"}),S.map(X=>e.jsxs(ja,{disabled:V.folder_id===X.id,onClick:()=>I.mutate({templateId:V.id,folderId:X.id}),children:[e.jsx(Oq,{className:"mr-2 h-4 w-4"})," ",X.name]},X.id)),V.folder_id&&e.jsx(ja,{onClick:()=>I.mutate({templateId:V.id,folderId:null}),children:"Remove from folder"}),e.jsx(R0,{})]}),e.jsxs(ja,{onClick:()=>l.mutate({id:V.id,patch:{is_archived:!0,is_published:!1}}),children:[e.jsx(Sv,{className:"mr-2 h-4 w-4"})," Archive"]}),e.jsxs(ja,{className:"text-destructive",onClick:()=>W(V),children:[e.jsx(Wn,{className:"mr-2 h-4 w-4"})," Delete"]})]})]})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(yir,{status:G==null?void 0:G.mapping_status}),e.jsxs("label",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[V.is_published?"Published":"Draft",e.jsx(Sn,{checked:!!V.is_published,onCheckedChange:X=>U(V,X)})]})]})]})},V.id)}),R.length===0&&e.jsx("p",{className:"col-span-full py-10 text-center text-sm text-muted-foreground",children:"No forms match that search."})]})]}),e.jsx(Wy,{open:!!D,onOpenChange:V=>!V&&f(null),children:e.jsxs(py,{side:"right",className:"w-full overflow-y-auto sm:max-w-2xl",children:[e.jsxs(D0,{className:"space-y-1 text-left",children:[e.jsx(F0,{children:D==null?void 0:D.name}),O&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["v",O.version_number," · ",O.file_name," ·"," ",Plt(O.file_size)," · uploaded"," ",en(new Date(O.created_at),"MMM d, yyyy")]})]}),e.jsxs("div",{className:"mt-5 space-y-4",children:[(D==null?void 0:D.description)&&e.jsx("p",{className:"text-sm text-muted-foreground",children:D.description}),O?e.jsxs(e.Fragment,{children:[e.jsxs($,{variant:"outline",className:"w-full",onClick:()=>D&&x(D),children:[e.jsx(Qf,{className:"mr-2 h-4 w-4"})," Place fields & signatures on the document"]}),e.jsx(oos,{version:O})]}):e.jsx("p",{className:"text-sm text-muted-foreground",children:"This form has no uploaded version yet."})]})]})}),e.jsx(zPe,{open:c,onOpenChange:d,brokerageId:s}),e.jsx(zPe,{open:!!u,onOpenChange:V=>!V&&h(null),templateId:u==null?void 0:u.id,templateName:u==null?void 0:u.name,brokerageId:s}),g&&wx(g)&&e.jsx(los,{open:!0,onOpenChange:V=>!V&&x(null),version:wx(g),templateName:g.name})]})}function bir(){const{brokerageId:s,isBrokerageManager:t,isAdmin:n,loading:r}=vs(),{data:a=[],isLoading:i}=A9s(s),{data:l={}}=e$t("brokerage",s),o=Q9t(),[c,d]=j.useState(null),[u,h]=j.useState(!1),[m,f]=j.useState(""),[g,x]=j.useState("all");if(r)return e.jsx(Vs,{children:e.jsx("div",{className:"p-8",children:"Loading..."})});if(!t&&!n)return e.jsx(Vs,{children:e.jsx("div",{className:"p-8 text-center",children:e.jsx("h2",{className:"text-xl font-semibold",children:"Brokerage managers only"})})});const y=a.filter(b=>!(g!=="all"&&b.category!==g||m&&!`${b.name} ${b.company||""}`.toLowerCase().includes(m.toLowerCase()))),v=async b=>{if(await fo("Delete this vendor? This will remove it from all agent libraries."))try{await o.mutateAsync(b),re.success("Vendor deleted")}catch(w){re.error(w.message)}};return e.jsx(Vs,{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(ji,{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($,{onClick:()=>{d(null),h(!0)},children:[e.jsx(dn,{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(Kr,{className:"w-4 h-4 absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground"}),e.jsx(pe,{className:"pl-9",placeholder:"Search vendors...",value:m,onChange:b=>f(b.target.value)})]}),e.jsxs("select",{value:g,onChange:b=>x(b.target.value),className:"border rounded-md px-3 py-2 text-sm bg-background",children:[e.jsx("option",{value:"all",children:"All categories"}),dK.map(b=>e.jsx("option",{value:b.value,children:b.label},b.value))]})]}),i?e.jsx("div",{className:"text-center text-muted-foreground py-12",children:"Loading vendors..."}):y.length===0?e.jsxs("div",{className:"text-center py-16 border-2 border-dashed rounded-xl",children:[e.jsx(ji,{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($,{onClick:()=>{d(null),h(!0)},children:[e.jsx(dn,{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:y.map(b=>e.jsx(mos,{vendor:b,onEdit:()=>{d(b),h(!0)},onDelete:()=>v(b.id),clickCount:l[b.id]},b.id))}),e.jsx(fos,{open:u,onOpenChange:h,vendor:c,ownerType:"brokerage",brokerageId:s,showBrokerageOnlyFields:!0})]})})}function gos({portalId:s,portalSlug:t,clientName:n,agentName:r}){const{data:a,isLoading:i}=n$t(s),l=r$t(),o=L9s(),[c,d]=j.useState(""),u=j.useRef(null),h=(a||[]).filter(f=>f.sender_type==="client"&&!f.read_at).length;j.useEffect(()=>{h>0&&o.mutate(s)},[h,s]),j.useEffect(()=>{var f;(f=u.current)==null||f.scrollIntoView({block:"nearest"})},[a==null?void 0:a.length]);const m=async()=>{const f=c.trim();if(f)try{await l.mutateAsync({portalId:s,senderType:"agent",senderName:r||null,body:f,portalUrl:t?`https://clients.relevelup.com/${t}`:void 0}),d(""),re.success("Message sent — your client was emailed")}catch(g){re.error((g==null?void 0:g.message)||"Could not send message")}};return e.jsx(Ne,{children:e.jsxs(Ie,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center justify-between mb-4",children:[e.jsxs("h3",{className:"font-semibold",children:["Conversation with ",n||"your client"]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Both sides get an email for every message"})]}),e.jsxs("div",{className:"space-y-3 max-h-[420px] overflow-y-auto pr-1",children:[i&&e.jsx("div",{className:"flex justify-center py-8",children:e.jsx(kt,{className:"w-4 h-4 animate-spin text-muted-foreground"})}),!i&&(!a||a.length===0)&&e.jsxs("div",{className:"text-center py-10 border-2 border-dashed rounded-lg",children:[e.jsx("p",{className:"text-sm font-medium",children:"No messages yet"}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Start the conversation — your client can reply right inside their portal."})]}),a==null?void 0:a.map(f=>{const g=f.sender_type==="agent";return e.jsx("div",{className:`flex ${g?"justify-end":"justify-start"}`,children:e.jsxs("div",{className:`max-w-[80%] rounded-lg px-3 py-2 border ${g?"bg-primary/10 border-primary/20":"bg-muted border-border"}`,children:[e.jsxs("p",{className:"text-[11px] text-muted-foreground mb-1",children:[g?r||"You":f.sender_name||n||"Client"," ·"," ",en(new Date(f.created_at),"MMM d, h:mm a")]}),e.jsx("p",{className:"text-sm whitespace-pre-wrap",children:f.body})]})},f.id)}),e.jsx("div",{ref:u})]}),e.jsxs("div",{className:"mt-4 space-y-2",children:[e.jsx(Rs,{value:c,onChange:f=>d(f.target.value),rows:3,placeholder:`Reply to ${n||"your client"}...`}),e.jsx("div",{className:"flex justify-end",children:e.jsxs($,{onClick:m,disabled:l.isPending||!c.trim(),size:"sm",children:[l.isPending?e.jsx(kt,{className:"w-4 h-4 mr-1.5 animate-spin"}):e.jsx(Yr,{className:"w-4 h-4 mr-1.5"}),"Send & notify"]})})]})]})})}function _ir({selectedPortalId:s,onSelectPortal:t}){const{data:n,isLoading:r}=a$t(),[a,i]=j.useState(""),[l,o]=j.useState(!1),[c,d]=j.useState(s??null);j.useEffect(()=>{s&&d(s)},[s]);const u=j.useMemo(()=>{const g=a.trim().toLowerCase();return(n||[]).filter(x=>l&&x.unreadCount===0?!1:g?(x.clientName||"").toLowerCase().includes(g)||(x.clientEmail||"").toLowerCase().includes(g):!0)},[n,a,l]),h=j.useRef(!1);j.useEffect(()=>{if(h.current||c||u.length===0)return;h.current=!0;const g=u.find(x=>x.messageCount>0)||u[0];d(g.portalId)},[u,c]);const m=g=>{h.current=!0,d(g),t==null||t(g)},f=(n||[]).find(g=>g.portalId===c)||null;return r?e.jsx("div",{className:"flex justify-center py-16",children:e.jsx(kt,{className:"w-5 h-5 animate-spin text-muted-foreground"})}):!n||n.length===0?e.jsx(Ne,{children:e.jsxs(Ie,{className:"p-10 text-center",children:[e.jsx(eo,{className:"w-6 h-6 mx-auto text-muted-foreground mb-3"}),e.jsx("p",{className:"font-medium",children:"No client portals yet"}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:"Create a portal from a deal and your conversations will appear here."})]})}):e.jsxs("div",{className:"grid gap-4 md:grid-cols-[320px_1fr]",children:[e.jsx("div",{className:`${f?"hidden md:block":"block"}`,children:e.jsxs(Ne,{className:"overflow-hidden",children:[e.jsxs("div",{className:"p-3 space-y-2 border-b",children:[e.jsxs("div",{className:"relative",children:[e.jsx(Kr,{className:"w-4 h-4 absolute left-2.5 top-1/2 -translate-y-1/2 text-muted-foreground"}),e.jsx(pe,{value:a,onChange:g=>i(g.target.value),placeholder:"Search clients",className:"pl-8"})]}),e.jsx($,{variant:l?"default":"outline",size:"sm",onClick:()=>o(g=>!g),children:"Unread only"})]}),e.jsxs("div",{className:"max-h-[560px] overflow-y-auto divide-y",children:[u.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground p-4",children:"No conversations match."}),u.map(g=>{const x=g.portalId===c;return e.jsxs("button",{onClick:()=>m(g.portalId),className:`w-full text-left p-3 transition-colors hover:bg-muted/60 ${x?"bg-muted":""}`,children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("span",{className:"font-medium text-sm truncate",children:g.clientName||"Unnamed client"}),g.unreadCount>0&&e.jsx(Be,{className:"shrink-0",children:g.unreadCount})]}),e.jsx("p",{className:"text-xs text-muted-foreground truncate mt-0.5",children:g.lastMessage?`${g.lastMessage.sender_type==="agent"?"You: ":""}${g.lastMessage.body}`:"No messages yet"}),g.lastMessage&&e.jsx("p",{className:"text-[11px] text-muted-foreground mt-1",children:mu(new Date(g.lastMessage.created_at),{addSuffix:!0})})]},g.portalId)})]})]})}),e.jsx("div",{className:`${f?"block":"hidden md:block"}`,children:f?e.jsxs("div",{className:"space-y-3",children:[e.jsxs($,{variant:"ghost",size:"sm",className:"md:hidden",onClick:()=>m(null),children:[e.jsx(qa,{className:"w-4 h-4 mr-1.5"}),"All conversations"]}),e.jsx(gos,{portalId:f.portalId,portalSlug:f.slug,clientName:f.clientName})]}):e.jsx(Ne,{children:e.jsx(Ie,{className:"p-10 text-center text-sm text-muted-foreground",children:"Pick a client to see the conversation."})})})]})}const wir=[{value:"overview",label:"Portals",icon:Qf},{value:"messages",label:"Messages",icon:eo},{value:"vendors",label:"Vendors",icon:wb},{value:"referrals",label:"Referrals",icon:ul},{value:"branding",label:"Branding",icon:Yc},{value:"questions",label:"Onboarding",icon:Ev}];function jir(){const[s,t]=gc(),n=s.get("tab")||"overview",[r,a]=j.useState(n),[i,l]=j.useState(!1),[o,c]=j.useState(!1),d=s.get("portal"),{data:u}=a$t(),h=(u||[]).reduce((m,f)=>m+f.unreadCount,0);return j.useEffect(()=>{t(m=>{const f=new URLSearchParams(m);return f.set("tab",r),r!=="messages"&&f.delete("portal"),f},{replace:!0})},[r,t]),e.jsxs(Vs,{children:[e.jsx(Ml,{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(Nn,{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(c7,{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($,{asChild:!0,variant:"outline",size:"sm",className:"shrink-0",children:e.jsx(wr,{to:"/mission-control/pipeline",children:"Open Deal Pipeline"})})]})}),e.jsxs(ha,{value:r,onValueChange:a,className:"w-full",children:[e.jsx(ma,{className:"w-full justify-start overflow-x-auto h-auto flex-wrap",children:wir.map(m=>e.jsxs(Zt,{value:m.value,className:"gap-2",children:[e.jsx(m.icon,{className:"w-4 h-4"}),m.label,m.value==="messages"&&h>0&&e.jsx(Be,{className:"ml-1 h-5 px-1.5",children:h})]},m.value))}),e.jsx(Xt,{value:"overview",className:"mt-6",children:e.jsx(ios,{})}),e.jsx(Xt,{value:"messages",className:"mt-6",children:e.jsx(_ir,{selectedPortalId:d,onSelectPortal:m=>t(f=>{const g=new URLSearchParams(f);return g.set("tab","messages"),m?g.set("portal",m):g.delete("portal"),g},{replace:!0})})}),e.jsx(Xt,{value:"vendors",className:"mt-6",children:e.jsx(Nir,{})}),e.jsx(Xt,{value:"referrals",className:"mt-6",children:e.jsx(kir,{})}),e.jsx(Xt,{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(Yc,{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($,{onClick:()=>l(!0),children:[e.jsx(Sd,{className:"w-4 h-4 mr-2"}),"Edit Branding Defaults"]})]})]})})}),e.jsx(Xt,{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(Ev,{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($,{onClick:()=>c(!0),children:[e.jsx(Sd,{className:"w-4 h-4 mr-2"}),"Manage Questions"]})]})]})})})]})]}),e.jsx(aos,{open:i,onOpenChange:l}),e.jsx(sos,{open:o,onOpenChange:c})]})}function Nir(){return e.jsx(pos,{embedded:!0})}function kir(){return e.jsx(hos,{})}const sU=s=>new Intl.DateTimeFormat("en-US",{timeZone:"America/New_York",month:"short",day:"numeric",year:"numeric"}).format(new Date(s));function Sir(s){return tt({queryKey:["client-portal-by-id",s],queryFn:async()=>{if(!s)return null;const{data:t,error:n}=await q.from("client_portals").select("*").eq("id",s).maybeSingle();if(n)throw n;if(!t)return{portal:null,deal:null};const{data:r,error:a}=await q.from("deal_pipeline").select("deal_name, contact_id").eq("id",t.deal_id).maybeSingle();if(a)throw a;let i=null;if(r!=null&&r.contact_id){const{data:l,error:o}=await q.from("innercircle_contacts").select("first_name, last_name, email, phone").eq("id",r.contact_id).maybeSingle();if(o)throw o;i=l}return{portal:t,deal:r?{deal_name:r.deal_name,contact_id:r.contact_id,contact:i}:null}},enabled:!!s})}function Cir(){const{portalId:s}=Wi(),t=Qn(),n=Sa(),{data:r,isLoading:a}=Sir(s),{data:i=[]}=_Un(s),{data:l=[]}=uos(),o=UK(),c=oJt(),d=lJt(),u=cJt(),[h,m]=j.useState(!1),[f,g]=j.useState(!1),[x,y]=j.useState(!1),[v,b]=j.useState(!1),w=(r==null?void 0:r.portal)??null,S=(r==null?void 0:r.deal)??null,C=j.useMemo(()=>w?l.filter(Y=>Y.portal_id===w.id):[],[l,w==null?void 0:w.id]);if(a)return e.jsx(Vs,{children:e.jsx("div",{className:"flex items-center justify-center py-24",children:e.jsx(kt,{className:"h-6 w-6 animate-spin text-muted-foreground"})})});if(!w)return e.jsx(Vs,{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($,{asChild:!0,variant:"outline",children:e.jsxs(wr,{to:"/mission-control/client-portals",children:[e.jsx(qa,{className:"w-4 h-4 mr-2"}),"Back to Portals"]})})]})});const E=dC(w.slug),I=(S==null?void 0:S.deal_name)||"Untitled deal",P=S==null?void 0:S.contact,R=P?`${P.first_name||""} ${P.last_name||""}`.trim():"",D=!!w.archived_at,O=()=>{navigator.clipboard.writeText(E),re.success("Portal link copied!")},U=async Y=>{try{await o.mutateAsync({id:w.id,is_enabled:Y}),re.success(Y?"Portal enabled":"Portal disabled")}catch{re.error("Failed to update")}},W=async()=>{try{await c.mutateAsync(w.id),re.success("Portal archived")}catch{re.error("Failed to archive")}},V=async()=>{try{await d.mutateAsync(w.id),re.success("Portal restored")}catch{re.error("Failed to restore")}},G=async()=>{try{await u.mutateAsync({id:w.id,dealId:w.deal_id}),re.success("Portal deleted"),t("/mission-control/client-portals")}catch{re.error("Failed to delete")}};return e.jsxs(Vs,{children:[e.jsx(Ml,{children:e.jsxs("title",{children:[I," — 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($,{asChild:!0,variant:"ghost",size:"sm",className:"-ml-2 text-muted-foreground",children:e.jsxs(wr,{to:"/mission-control/client-portals?tab=overview",children:[e.jsx(qa,{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(Nn,{className:"w-5 h-5 text-primary"}),e.jsx("h1",{className:"text-2xl font-bold truncate",children:I}),e.jsx(Be,{variant:"outline",className:D?"bg-muted text-muted-foreground":w.is_enabled?"bg-emerald-500/10 text-emerald-700 border-emerald-200":"bg-muted text-muted-foreground",children:D?"Archived":w.is_enabled?"Active":"Disabled"}),e.jsx(Be,{variant:"outline",className:"capitalize text-xs",children:w.visibility})]}),e.jsxs("p",{className:"text-sm text-muted-foreground flex items-center gap-2 flex-wrap",children:[e.jsx(sl,{className:"w-3.5 h-3.5"}),w.client_name||R||"No client name set",(P==null?void 0:P.email)&&e.jsxs(e.Fragment,{children:["· ",e.jsx(mn,{className:"w-3.5 h-3.5"}),e.jsx("span",{className:"truncate",children:P.email})]}),(P==null?void 0:P.phone)&&e.jsxs(e.Fragment,{children:["· ",e.jsx(Da,{className:"w-3.5 h-3.5"}),P.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:E})})]}),!D&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:"Live"}),e.jsx(Sn,{checked:w.is_enabled,onCheckedChange:U})]})]}),e.jsxs("div",{className:"mt-5 flex items-center gap-2 flex-wrap",children:[e.jsxs($,{onClick:O,variant:"outline",size:"sm",children:[e.jsx(Ha,{className:"w-4 h-4 mr-1.5"})," Copy Link"]}),e.jsxs($,{onClick:()=>window.open(E,"_blank"),variant:"outline",size:"sm",children:[e.jsx(kr,{className:"w-4 h-4 mr-1.5"})," Preview"]}),e.jsxs($,{onClick:()=>y(!0),size:"sm",children:[e.jsx(Yr,{className:"w-4 h-4 mr-1.5"})," Invite Client"]}),e.jsxs($,{onClick:()=>g(!0),variant:"outline",size:"sm",children:[e.jsx(p4,{className:"w-4 h-4 mr-1.5"})," Post Update"]}),e.jsxs($,{onClick:()=>m(!0),variant:"outline",size:"sm",children:[e.jsx(Sd,{className:"w-4 h-4 mr-1.5"})," Settings"]}),e.jsxs("div",{className:"ml-auto flex items-center gap-2",children:[D?e.jsxs($,{onClick:V,variant:"outline",size:"sm",children:[e.jsx(UI,{className:"w-4 h-4 mr-1.5"})," Restore"]}):e.jsxs($,{onClick:W,variant:"ghost",size:"sm",children:[e.jsx(Sv,{className:"w-4 h-4 mr-1.5"})," Archive"]}),e.jsx($,{onClick:()=>b(!0),variant:"ghost",size:"sm",className:"text-destructive hover:text-destructive",children:e.jsx(Wn,{className:"w-4 h-4"})})]})]})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-3",children:[e.jsx(nhe,{icon:p4,label:"Updates Posted",value:i.length}),e.jsx(nhe,{icon:ul,label:"Referrals",value:C.length}),e.jsx(nhe,{icon:Ta,label:"Inspection",value:w.inspection_date?sU(w.inspection_date):"—"}),e.jsx(nhe,{icon:Ta,label:"Appraisal",value:w.appraisal_date?sU(w.appraisal_date):"—"})]}),e.jsxs(ha,{defaultValue:"updates",className:"w-full",children:[e.jsxs(ma,{children:[e.jsxs(Zt,{value:"updates",children:["Updates (",i.length,")"]}),e.jsx(Zt,{value:"messages",children:"Messages"}),e.jsxs(Zt,{value:"referrals",children:["Referrals (",C.length,")"]}),e.jsx(Zt,{value:"branding",children:"Branding"}),e.jsx(Zt,{value:"details",children:"Details"})]}),e.jsx(Xt,{value:"messages",className:"mt-4",children:e.jsx(gos,{portalId:w.id,portalSlug:w.slug,clientName:w.client_name})}),e.jsx(Xt,{value:"updates",className:"mt-4",children:e.jsx(Ne,{children:e.jsxs(Ie,{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($,{size:"sm",onClick:()=>g(!0),children:[e.jsx(p4,{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(p4,{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(Y=>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:Y.title}),Y.is_stage_change&&e.jsx(Be,{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:sU(Y.created_at)}),Y.content&&e.jsx("p",{className:"text-sm text-muted-foreground mt-2 whitespace-pre-wrap",children:Y.content}),Y.video_url&&e.jsxs("a",{href:Y.video_url,target:"_blank",rel:"noreferrer",className:"inline-flex items-center gap-1 text-xs text-primary hover:underline mt-2",children:[e.jsx(ua,{className:"w-3 h-3"})," View video"]})]})})},Y.id))})]})})}),e.jsx(Xt,{value:"referrals",className:"mt-4",children:e.jsx(Ne,{children:e.jsxs(Ie,{className:"p-4",children:[e.jsx("h3",{className:"font-semibold mb-4",children:"Referrals from this Portal"}),C.length===0?e.jsxs("div",{className:"text-center py-12 border-2 border-dashed rounded-lg",children:[e.jsx(ul,{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:C.map(Y=>e.jsx(wr,{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:Y.friend_name}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[Y.friend_email||Y.friend_phone||"No contact info"," · ",sU(Y.created_at)]})]}),e.jsx(Be,{variant:"outline",className:"text-xs capitalize",children:Y.status})]})},Y.id))})]})})}),e.jsx(Xt,{value:"branding",className:"mt-4",children:e.jsx(Ne,{children:e.jsx(Ie,{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(Yc,{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($,{onClick:()=>m(!0),children:[e.jsx(Sd,{className:"w-4 h-4 mr-2"}),"Edit Branding (in Settings)"]})]})]})})})}),e.jsx(Xt,{value:"details",className:"mt-4",children:e.jsx(Ne,{children:e.jsxs(Ie,{className:"p-6 space-y-4",children:[e.jsx(RM,{label:"Visibility",value:w.visibility}),e.jsx(RM,{label:"Onboarding Required",value:w.require_onboarding?"Yes":"No"}),e.jsx(RM,{label:"Allow Spouse",value:w.allow_spouse?"Yes":"No"}),e.jsx(RM,{label:"Notify Client on Updates",value:w.notify_client?"Yes":"No"}),e.jsx(RM,{label:"Show Post-Close Tips",value:w.show_post_close_tips?"Yes":"No"}),e.jsx(RM,{label:"Slug",value:w.slug,mono:!0}),e.jsx(RM,{label:"Created",value:sU(w.created_at)}),e.jsx(RM,{label:"Last Updated",value:sU(w.updated_at)}),e.jsx("div",{className:"pt-2",children:e.jsxs($,{variant:"outline",onClick:()=>m(!0),children:[e.jsx(Sd,{className:"w-4 h-4 mr-2"})," Edit All Settings"]})})]})})})]})]}),e.jsx(Flt,{open:h,onOpenChange:m,portal:w,dealOwnerId:n||""}),e.jsx(Olt,{open:f,onOpenChange:g,portalId:w.id,portalSlug:w.slug,notifyClient:w.notify_client}),e.jsx(zlt,{open:x,onOpenChange:y,portal:w,dealName:I}),e.jsx(kc,{open:v,onOpenChange:b,children:e.jsxs(cc,{children:[e.jsxs(dc,{children:[e.jsx(hc,{children:"Permanently delete this portal?"}),e.jsx(mc,{children:"This removes the portal and all its updates. The client will lose access. This action cannot be undone."})]}),e.jsxs(uc,{children:[e.jsx(fc,{children:"Cancel"}),e.jsx(tc,{onClick:G,className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Delete Permanently"})]})]})})]})}function nhe({icon:s,label:t,value:n}){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:n})]})}function RM({label:s,value:t,mono:n}){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 ${n?"font-mono text-xs":""} text-right truncate`,children:t})]})}const cQe=[{value:"video_intro",label:"Video Intro",icon:ua,description:"Add an intro video"},{value:"testimonials",label:"Testimonials",icon:LE,description:"Client testimonials carousel"},{value:"specialties",label:"Specialties",icon:Ap,description:"Tags for your specialties"},{value:"custom_links",label:"Custom Links",icon:bd,description:"Custom CTA buttons"},{value:"social_media",label:"Social Media",icon:zd,description:"Links to your social profiles"}],Air=["First-Time Buyers","Luxury Homes","Investment Properties","Relocation","New Construction","Condos & Townhomes","Waterfront","Commercial","Land & Lots","Senior Living","Military/VA","Short Sales & Foreclosures"],Eir={video_intro:{video_url:""},testimonials:{testimonials:[{name:"",quote:"",role:""}]},specialties:{tags:[]},custom_links:{links:[{label:"",url:""}]},social_media:{platforms:[]}};function xos({cardId:s}){const{data:t,isLoading:n}=YDs(s),r=ZDs(),a=XDs(),i=QDs(),[l,o]=j.useState(!1),[c,d]=j.useState(""),[u,h]=j.useState(null);if(n)return e.jsxs("div",{className:"space-y-3",children:[e.jsx(yn,{className:"h-16 w-full"}),e.jsx(yn,{className:"h-16 w-full"})]});const m=()=>{c&&r.mutate({card_id:s,block_type:c,sort_order:(t==null?void 0:t.length)||0,config:Eir[c]||{}},{onSuccess:()=>{o(!1),d("")}})},f=b=>{a.mutate({id:b.id,is_visible:!b.is_visible})},g=(b,w)=>{if(!t)return;const S=t.findIndex(I=>I.id===b.id),C=w==="up"?S-1:S+1;if(C<0||C>=t.length)return;const E=t[C];a.mutate({id:b.id,sort_order:E.sort_order}),a.mutate({id:E.id,sort_order:b.sort_order})},x=async b=>{await fo("Remove this block from this card?")&&i.mutate(b.id)},y=(b,w)=>{a.mutate({id:b.id,config:w},{onSuccess:()=>h(null)})},v=b=>cQe.find(w=>w.value===b);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($,{size:"sm",onClick:()=>o(!0),children:[e.jsx(dn,{className:"h-4 w-4 mr-1"})," Add Block"]})]}):e.jsxs(e.Fragment,{children:[t.map((b,w)=>{const S=v(b.block_type),C=(S==null?void 0:S.icon)||Ap;return e.jsx(Ne,{className:b.is_visible?"":"opacity-50",children:e.jsx(Ie,{className:"p-3",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ug,{className:"h-4 w-4 text-muted-foreground flex-shrink-0"}),e.jsx(C,{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:(S==null?void 0:S.label)||b.block_type}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:Tir(b)})]}),e.jsxs("div",{className:"flex items-center gap-0.5",children:[e.jsx($,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:()=>g(b,"up"),disabled:w===0,children:e.jsx(Zf,{className:"h-3 w-3"})}),e.jsx($,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:()=>g(b,"down"),disabled:w===t.length-1,children:e.jsx(Dg,{className:"h-3 w-3"})}),e.jsx($,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:()=>f(b),children:b.is_visible?e.jsx(Ca,{className:"h-3 w-3"}):e.jsx($g,{className:"h-3 w-3"})}),e.jsx($,{variant:"ghost",size:"sm",className:"h-7 text-xs",onClick:()=>h(b),children:"Edit"}),e.jsx($,{variant:"ghost",size:"icon",className:"h-7 w-7 text-destructive",onClick:()=>x(b),children:e.jsx(Wn,{className:"h-3 w-3"})})]})]})})},b.id)}),e.jsxs($,{variant:"outline",size:"sm",className:"w-full",onClick:()=>o(!0),children:[e.jsx(dn,{className:"h-4 w-4 mr-1"})," Add Block"]})]}),e.jsx(zs,{open:l,onOpenChange:o,children:e.jsxs(Os,{children:[e.jsx(Us,{children:e.jsx(Bs,{children:"Add Block"})}),e.jsx("div",{className:"grid gap-3",children:cQe.map(b=>{const w=b.icon;return e.jsxs("button",{onClick:()=>d(b.value),className:`flex items-center gap-3 p-3 rounded-lg border text-left transition-colors ${c===b.value?"border-primary bg-primary/5":"border-border hover:bg-muted"}`,children:[e.jsx(w,{className:"h-5 w-5 text-primary flex-shrink-0"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-sm",children:b.label}),e.jsx("p",{className:"text-xs text-muted-foreground",children:b.description})]})]},b.value)})}),e.jsxs(Ar,{children:[e.jsx($,{variant:"outline",onClick:()=>o(!1),children:"Cancel"}),e.jsx($,{onClick:m,disabled:!c||r.isPending,children:"Add Block"})]})]})}),u&&e.jsx(Mir,{block:u,onSave:b=>y(u,b),onClose:()=>h(null)})]})}function Tir(s){var n;const t=s.config;switch(s.block_type){case"video_intro":return t.video_url?"Video configured":"No video set";case"testimonials":{const r=((n=t.testimonials)==null?void 0:n.length)||0;return`${r} testimonial${r!==1?"s":""}`}case"specialties":{const r=t.tags||[];return r.length?r.slice(0,3).join(", ")+(r.length>3?"...":""):"No tags"}case"custom_links":{const r=t.links||[];return`${r.length} link${r.length!==1?"s":""}`}case"social_media":{const r=t.platforms||[];return r.length?r.map(a=>a.platform).join(", "):"No platforms"}default:return""}}function Mir({block:s,onSave:t,onClose:n}){const[r,a]=j.useState(s.config),i=cQe.find(l=>l.value===s.block_type);return e.jsx(zs,{open:!0,onOpenChange:n,children:e.jsxs(Os,{className:"max-w-lg max-h-[80vh] overflow-y-auto",children:[e.jsx(Us,{children:e.jsxs(Bs,{children:["Edit ",i==null?void 0:i.label]})}),s.block_type==="video_intro"&&e.jsx(Pir,{config:r,onChange:a,cardId:s.card_id}),s.block_type==="testimonials"&&e.jsx(Iir,{config:r,onChange:a}),s.block_type==="specialties"&&e.jsx(Lir,{config:r,onChange:a}),s.block_type==="custom_links"&&e.jsx(Rir,{config:r,onChange:a}),s.block_type==="social_media"&&e.jsx(Dir,{config:r,onChange:a}),e.jsxs(Ar,{children:[e.jsx($,{variant:"outline",onClick:n,children:"Cancel"}),e.jsx($,{onClick:()=>t(r),children:"Save"})]})]})})}function Pir({config:s,onChange:t,cardId:n}){var f,g;const[r,a]=j.useState(""),[i,l]=j.useState((f=s.video_url)!=null&&f.includes("youtube")||(g=s.video_url)!=null&&g.includes("youtu.be")?"youtube":"library"),{data:o}=tt({queryKey:["card-owner",n],queryFn:async()=>{const{data:x}=await q.from("agent_cards").select("user_id").eq("id",n).single();return x==null?void 0:x.user_id},enabled:!!n}),{data:c,isLoading:d}=tt({queryKey:["agent-videos-library",o],queryFn:async()=>{const{data:x,error:y}=await q.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(y)throw y;return x||[]},enabled:!!o}),u=(c==null?void 0:c.filter(x=>!r||(x.title||"").toLowerCase().includes(r.toLowerCase())))||[],h=s.bunny_video_id,m=x=>{var w;const y=(w=x.playback_url)==null?void 0:w.match(/\/(?:play|embed)\/(\d+)\//),b=`https://iframe.mediadelivery.net/embed/${y?y[1]:"570924"}/${x.bunny_video_id}?autoplay=false&responsive=true`;t({...s,video_url:b,bunny_video_id:x.bunny_video_id,video_source:"library"})};return e.jsx("div",{className:"space-y-4",children:e.jsxs(ha,{value:i,onValueChange:l,children:[e.jsxs(ma,{className:"w-full",children:[e.jsx(Zt,{value:"library",className:"flex-1",children:"Video Library"}),e.jsx(Zt,{value:"youtube",className:"flex-1",children:"YouTube URL"})]}),e.jsxs(Xt,{value:"library",className:"space-y-3 mt-3",children:[e.jsxs("div",{className:"relative",children:[e.jsx(Kr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(pe,{placeholder:"Search videos...",value:r,onChange:x=>a(x.target.value),className:"pl-9"})]}),e.jsx(uo,{className:"h-[240px]",children:d?e.jsxs("div",{className:"space-y-2",children:[e.jsx(yn,{className:"h-14 w-full"}),e.jsx(yn,{className:"h-14 w-full"})]}):u.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:u.map(x=>e.jsxs("button",{onClick:()=>m(x),className:`w-full flex items-center gap-3 p-2 rounded-lg border text-left transition-colors ${h===x.bunny_video_id?"border-primary bg-primary/5":"border-border hover:bg-muted"}`,children:[x.thumbnail_url?e.jsx("img",{src:x.thumbnail_url,alt:"",className:"h-10 w-16 rounded object-cover flex-shrink-0 bg-muted",onError:y=>{var v;y.currentTarget.style.display="none",(v=y.currentTarget.nextElementSibling)==null||v.classList.remove("hidden")}}):null,e.jsx("div",{className:`h-10 w-16 rounded bg-muted flex items-center justify-center flex-shrink-0 ${x.thumbnail_url?"hidden":""}`,children:e.jsx(ua,{className:"h-4 w-4 text-muted-foreground"})}),e.jsx("span",{className:"text-sm font-medium truncate flex-1",children:x.title||"Untitled Video"}),h===x.bunny_video_id&&e.jsx(la,{className:"h-4 w-4 text-primary flex-shrink-0"})]},x.id))})})]}),e.jsx(Xt,{value:"youtube",className:"space-y-3 mt-3",children:e.jsxs("div",{children:[e.jsx(ee,{children:"YouTube URL"}),e.jsx(pe,{placeholder:"https://www.youtube.com/watch?v=...",value:s.video_source==="youtube"&&s.video_url||"",onChange:x=>t({...s,video_url:x.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 Iir({config:s,onChange:t}){const n=s.testimonials||[],r=(l,o,c)=>{const d=[...n];d[l]={...d[l],[o]:c},t({...s,testimonials:d})},a=()=>t({...s,testimonials:[...n,{name:"",quote:"",role:""}]}),i=l=>t({...s,testimonials:n.filter((o,c)=>c!==l)});return e.jsxs("div",{className:"space-y-4",children:[n.map((l,o)=>e.jsx(Ne,{children:e.jsxs(Ie,{className:"p-3 space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(ee,{className:"text-xs font-medium",children:["Testimonial ",o+1]}),n.length>1&&e.jsx($,{variant:"ghost",size:"icon",className:"h-6 w-6 text-destructive",onClick:()=>i(o),children:e.jsx(Wn,{className:"h-3 w-3"})})]}),e.jsx(pe,{placeholder:"Client name",value:l.name,onChange:c=>r(o,"name",c.target.value)}),e.jsx(pe,{placeholder:"Role/title (optional)",value:l.role||"",onChange:c=>r(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=>r(o,"quote",c.target.value)})]})},o)),e.jsxs($,{variant:"outline",size:"sm",onClick:a,className:"w-full",children:[e.jsx(dn,{className:"h-4 w-4 mr-1"})," Add Testimonial"]})]})}function Lir({config:s,onChange:t}){const n=s.tags||[],[r,a]=j.useState(""),i=o=>{t({...s,tags:n.includes(o)?n.filter(c=>c!==o):[...n,o]})},l=()=>{r.trim()&&!n.includes(r.trim())&&(t({...s,tags:[...n,r.trim()]}),a(""))};return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(ee,{className:"text-sm mb-2 block",children:"Preset Specialties"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:Air.map(o=>e.jsx("button",{onClick:()=>i(o),className:`px-3 py-1.5 text-xs rounded-full border transition-colors ${n.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(ee,{className:"text-sm mb-2 block",children:"Custom Tag"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(pe,{placeholder:"Add your own...",value:r,onChange:o=>a(o.target.value),onKeyDown:o=>o.key==="Enter"&&(o.preventDefault(),l())}),e.jsx($,{variant:"outline",size:"sm",onClick:l,children:"Add"})]})]}),n.length>0&&e.jsxs("div",{children:[e.jsxs(ee,{className:"text-xs text-muted-foreground mb-1 block",children:["Selected (",n.length,")"]}),e.jsx("div",{className:"flex flex-wrap gap-1.5",children:n.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 Rir({config:s,onChange:t}){const n=s.links||[],r=(l,o,c)=>{const d=[...n];d[l]={...d[l],[o]:c},t({...s,links:d})},a=()=>t({...s,links:[...n,{label:"",url:""}]}),i=l=>t({...s,links:n.filter((o,c)=>c!==l)});return e.jsxs("div",{className:"space-y-3",children:[n.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(pe,{placeholder:"Button label",value:l.label,onChange:c=>r(o,"label",c.target.value)}),e.jsx(pe,{placeholder:"https://...",value:l.url,onChange:c=>r(o,"url",c.target.value)})]}),n.length>1&&e.jsx($,{variant:"ghost",size:"icon",className:"h-8 w-8 mt-1 text-destructive",onClick:()=>i(o),children:e.jsx(Wn,{className:"h-3 w-3"})})]},o)),e.jsxs($,{variant:"outline",size:"sm",onClick:a,className:"w-full",children:[e.jsx(dn,{className:"h-4 w-4 mr-1"})," Add Link"]})]})}const dEt=[{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 Dir({config:s,onChange:t}){const n=s.platforms||[],r=c=>{n.find(d=>d.platform===c)||t({...s,platforms:[...n,{platform:c,url:""}]})},a=(c,d)=>{const u=[...n];u[c]={...u[c],url:d},t({...s,platforms:u})},i=c=>{t({...s,platforms:n.filter((d,u)=>u!==c)})},l=dEt.filter(c=>!n.find(d=>d.platform===c.value)),o=c=>{const d=cGe[c],u=dEt.find(h=>h.value===c);return{label:(u==null?void 0:u.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:[n.length>0&&e.jsx("div",{className:"space-y-3",children:n.map((c,d)=>{const u=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:u.color+"30",backgroundColor:u.color+"10"},children:u.iconPath&&e.jsx("svg",{viewBox:"0 0 24 24",width:16,height:16,fill:u.color,children:e.jsx("path",{d:u.iconPath})})}),e.jsx("div",{className:"flex-1",children:e.jsx(pe,{placeholder:`Your ${u.label} profile URL`,value:c.url,onChange:h=>a(d,h.target.value)})}),e.jsx($,{variant:"ghost",size:"icon",className:"h-8 w-8 text-destructive flex-shrink-0",onClick:()=>i(d),children:e.jsx(Wn,{className:"h-3.5 w-3.5"})})]},d)})}),l.length>0&&e.jsxs("div",{children:[e.jsx(ee,{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=cGe[c.value];return e.jsxs("button",{onClick:()=>r(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)})})]}),n.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."})]})}function Fir({slug:s,agentName:t}){const n=j.useRef(null),r=`https://cards.relevelup.com/${s}`,a=j.useCallback(()=>{var h;const i=(h=n.current)==null?void 0:h.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),u=new Image;u.onload=()=>{c.fillStyle="#ffffff",c.fillRect(0,0,o,o),c.drawImage(u,0,0,o,o);const m=document.createElement("a");m.download=`${s}-qr-code.png`,m.href=l.toDataURL("image/png"),m.click(),re.success("QR code downloaded!")},u.src="data:image/svg+xml;base64,"+btoa(unescape(encodeURIComponent(d)))},[s]);return e.jsxs("div",{className:"space-y-3",children:[e.jsx(ee,{className:"text-sm font-medium",children:"QR Code"}),e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx("div",{ref:n,className:"bg-white p-3 rounded-lg border shadow-sm shrink-0",children:e.jsx(fk,{value:r,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($,{variant:"outline",size:"sm",onClick:a,className:"gap-1.5",children:[e.jsx(di,{className:"h-3.5 w-3.5"}),"Download PNG"]})]})]})]})}function pUe(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 Oir(){const{user:s}=vs(),{data:t,isLoading:n}=GDs(s==null?void 0:s.id),r=$K(),[a,i]=j.useState(null),l=j.useMemo(()=>a||(t?pUe(t):null),[a,t]);if(n)return e.jsx(Vs,{children:e.jsxs("div",{className:"max-w-2xl mx-auto p-4 space-y-4",children:[e.jsx(yn,{className:"h-8 w-48"}),e.jsx(yn,{className:"h-32 w-full"}),e.jsx(yn,{className:"h-32 w-full"})]})});if(!t)return e.jsx(Vs,{children:e.jsx(Bir,{userId:s==null?void 0:s.id})});const o=l||pUe(t),c=d=>{i(u=>{const h=u||pUe(t);return typeof d=="function"?d(h):d})};return e.jsx(Vs,{children:e.jsxs("div",{className:"flex gap-6 items-start",children:[e.jsxs("div",{className:`${r?"w-full":"flex-1 min-w-0"} max-w-2xl p-4 space-y-6 animate-fade-in`,children:[e.jsx($ir,{card:t}),e.jsx(Hir,{card:t,form:o,setForm:c})]}),!r&&e.jsx("div",{className:"w-[400px] shrink-0","aria-hidden":"true"}),!r&&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(sk,{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(zir,{card:t,form:o})})]})})]})})}function zir({card:s,form:t}){const{data:n}=tt({queryKey:["card-preview-profile",s.user_id],queryFn:async()=>{const{data:a}=await q.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 q.storage.from("avatars").list(`${s.user_id}`);if(l&&l.length>0){const{data:o}=q.storage.from("avatars").getPublicUrl(`${s.user_id}/${l[0].name}`);i=`${o.publicUrl}?t=${Date.now()}`}}return{...a,avatar_url:i}}}),r=j.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:(n==null?void 0:n.name)||null,email:t.display_email||(n==null?void 0:n.email)||null,phone:(n==null?void 0:n.phone)||null,brokerage_id:(n==null?void 0:n.brokerage_id)||null},brokerage_name:t.brokerage_display_name||null,avatar_url:(n==null?void 0:n.avatar_url)||null}),[s,t,n]);return e.jsx("div",{className:"transform scale-[0.85] origin-top",children:e.jsx(ist,{card:r})})}function Bir({userId:s}){var c;const[t,n]=j.useState(""),r=Z7t(),{data:a}=tt({queryKey:["my-profile-for-card",s],queryFn:async()=>{if(!s)return null;const{data:d}=await q.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){re.error("Please enter a URL slug for your card");return}r.mutate({user_id:s,slug:d,is_published:!0},{onSuccess:()=>re.success("Your digital card has been created!")})},o=[{icon:dl,title:"Shareable Link",desc:"One link that works everywhere"},{icon:eg,title:"Lead Capture",desc:"Collect leads automatically"},{icon:Mf,title:"Always Up-to-Date",desc:"Edit anytime, changes are instant"},{icon:Yc,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(Nn,{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(Ne,{className:"shadow-lg border-2",children:[e.jsxs(Ct,{className:"text-center pb-2",children:[e.jsx(At,{className:"text-xl",children:"Set Up Your Card"}),e.jsx(Gn,{children:"Choose a URL slug — this is the link you'll share with clients"})]}),e.jsxs(Ie,{className:"p-6 pt-2 space-y-5",children:[e.jsxs("div",{children:[e.jsx(ee,{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(pe,{value:t||i,onChange:d=>n(d.target.value),placeholder:"your-name",className:"rounded-l-none"})]})]}),e.jsxs($,{onClick:l,disabled:r.isPending,className:"w-full h-11 text-base font-semibold",size:"lg",children:[e.jsx(Nn,{className:"h-4 w-4 mr-2"}),r.isPending?"Creating...":"Create My Card"]})]})]})]})}function $ir({card:s}){const n=`https://cards.relevelup.com/${s.slug}`,r=()=>{navigator.clipboard.writeText(n),re.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(Be,{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(dl,{className:"h-3.5 w-3.5"}),"cards.relevelup.com/",s.slug]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs($,{variant:"outline",size:"sm",onClick:r,className:"gap-1.5",children:[e.jsx(Ha,{className:"h-3.5 w-3.5"})," Copy Link"]}),e.jsx($,{size:"sm",asChild:!0,className:"gap-1.5",children:e.jsxs("a",{href:n,target:"_blank",rel:"noopener noreferrer",children:[e.jsx(kr,{className:"h-3.5 w-3.5"})," Preview"]})})]})]})})}function Uir({userId:s}){const t=Vt(),n=j.useRef(null),[r,a]=j.useState(!1),[i,l]=j.useState(""),{data:o,isLoading:c}=tt({queryKey:["card-editor-profile",s],queryFn:async()=>{const{data:O}=await q.from("profiles").select("name, email, phone, avatar_url").eq("id",s).single();let U=(O==null?void 0:O.avatar_url)||null;if(!U){const{data:W}=await q.storage.from("avatars").list(`${s}`);if(W&&W.length>0){const{data:V}=q.storage.from("avatars").getPublicUrl(`${s}/${W[0].name}`);U=`${V.publicUrl}?t=${Date.now()}`,await q.from("profiles").update({avatar_url:U}).eq("id",s)}}return{...O,avatar_url:U}}}),[d,u]=j.useState(null),[h,m]=j.useState(null),[f,g]=j.useState(null),[x,y]=j.useState(!1),v=d??(o==null?void 0:o.name)??"",b=h??(o==null?void 0:o.phone)??"",w=f??(o==null?void 0:o.email)??"",S=o==null?void 0:o.avatar_url,C=((o==null?void 0:o.name)||"A").split(" ").map(O=>O[0]).join("").toUpperCase().slice(0,2),E=!(o!=null&&o.avatar_url)||!(o!=null&&o.phone),I=ft({mutationFn:async O=>{const{error:U}=await q.from("profiles").update(O).eq("id",s);if(U)throw U},onSuccess:()=>{t.invalidateQueries({queryKey:["card-editor-profile",s]}),t.invalidateQueries({queryKey:["card-preview-profile",s]}),t.invalidateQueries({queryKey:["agent-card-user"]}),re.success("Profile updated!")},onError:()=>re.error("Failed to update profile")}),P=()=>{const O={};if(d!==null&&d!==(o==null?void 0:o.name)&&(O.name=d),h!==null&&h!==(o==null?void 0:o.phone)&&(O.phone=h||null),f!==null&&f!==(o==null?void 0:o.email)&&(O.email=f),Object.keys(O).length===0){re.info("No changes to save");return}I.mutate(O)},R=O=>{var V;const U=(V=O.target.files)==null?void 0:V[0];if(!U)return;if(!U.type.startsWith("image/")){re.error("Please select an image file");return}const W=new FileReader;W.onloadend=()=>{l(W.result),a(!0)},W.readAsDataURL(U),O.target.value=""},D=async O=>{y(!0);try{const{data:U}=await q.storage.from("avatars").list(`${s}`);U&&U.length>0&&await q.storage.from("avatars").remove(U.map(X=>`${s}/${X.name}`));const W=`${s}/avatar.jpg`,{error:V}=await q.storage.from("avatars").upload(W,O,{upsert:!0,contentType:"image/jpeg"});if(V)throw V;const{data:G}=q.storage.from("avatars").getPublicUrl(W),Y=G.publicUrl+"?t="+Date.now();await q.from("profiles").update({avatar_url:Y}).eq("id",s),t.invalidateQueries({queryKey:["card-editor-profile",s]}),t.invalidateQueries({queryKey:["card-preview-profile",s]}),t.invalidateQueries({queryKey:["agent-card-user"]}),re.success("Photo updated!")}catch{re.error("Failed to upload photo")}finally{y(!1)}};return c?e.jsx(yn,{className:"h-32 w-full rounded-xl"}):e.jsxs(e.Fragment,{children:[e.jsx(Ne,{className:E?"border-amber-300 dark:border-amber-700":"",children:e.jsxs(Ie,{className:"p-5 space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx(ee,{className:"text-sm font-semibold",children:"Profile Info"}),E&&e.jsxs("span",{className:"inline-flex items-center gap-1 text-xs text-amber-600 dark:text-amber-400 font-medium",children:[e.jsx(ll,{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 O;return(O=n.current)==null?void 0:O.click()},children:[e.jsxs(Oa,{className:"h-16 w-16 ring-2 ring-muted",children:[e.jsx(Li,{src:S||void 0,alt:v}),e.jsx(za,{className:"text-lg font-semibold bg-primary/10 text-primary",children:C})]}),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(Cx,{className:"h-5 w-5 text-white"})}),e.jsx("input",{ref:n,type:"file",accept:"image/*",className:"hidden",onChange:R})]}),e.jsxs("div",{className:"flex-1 space-y-0.5",children:[e.jsx("p",{className:"text-sm font-medium",children:x?"Uploading...":S?"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(ee,{className:"text-xs font-medium text-muted-foreground",children:"Full Name"}),e.jsx(pe,{value:v,onChange:O=>u(O.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(ee,{className:"text-xs font-medium text-muted-foreground",children:"Phone Number"}),e.jsx(pe,{value:b,onChange:O=>m(O.target.value),placeholder:"(555) 123-4567",className:"h-10",type:"tel"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{className:"text-xs font-medium text-muted-foreground",children:"Email"}),e.jsx(pe,{value:w,onChange:O=>g(O.target.value),placeholder:"you@example.com",className:"h-10",type:"email"})]})]})]}),e.jsx($,{variant:"outline",size:"sm",onClick:P,disabled:I.isPending,className:"w-full",children:I.isPending?"Saving...":"Update Profile Info"})]})}),e.jsx(rrt,{open:r,onClose:()=>a(!1),imageSrc:i,onCropComplete:D,aspectRatio:1})]})}function qir({form:s,setForm:t,userId:n}){const[r,a]=j.useState(null),[i,l]=j.useState(s.brokerage_logo_url?"logo":"name"),[o,c]=j.useState(s.team_logo_url?"logo":"name"),d=f=>{l(f),t(f==="name"?g=>({...g,brokerage_logo_url:""}):g=>({...g,brokerage_display_name:""}))},u=f=>{c(f),t(f==="name"?g=>({...g,team_logo_url:""}):g=>({...g,team_name:""}))},h=async(f,g)=>{var y;const x=(y=f.target.files)==null?void 0:y[0];if(x){if(!x.type.startsWith("image/")){re.error("Please select an image file");return}a(g);try{const v=x.name.split(".").pop()||"png",w=`${n}/${g==="brokerage_logo_url"?"brokerage-logo":"team-logo"}.${v}`,{error:S}=await q.storage.from("card-logos").upload(w,x,{upsert:!0});if(S)throw S;const{data:C}=q.storage.from("card-logos").getPublicUrl(w),E=C.publicUrl+"?t="+Date.now();t(g==="brokerage_logo_url"?I=>({...I,[g]:E,brokerage_display_name:""}):I=>({...I,[g]:E,team_name:""})),re.success("Logo uploaded!")}catch{re.error("Failed to upload logo")}finally{a(null),f.target.value=""}}},m=f=>{t(g=>({...g,[f]:""}))};return e.jsx(Ne,{children:e.jsxs(Ie,{className:"p-5 space-y-5",children:[e.jsxs("div",{children:[e.jsx(ee,{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(ee,{className:"text-xs font-semibold uppercase tracking-wider text-muted-foreground",children:"Brokerage"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx($,{type:"button",variant:i==="name"?"default":"outline",size:"sm",className:"text-xs",onClick:()=>d("name"),children:"Use Name"}),e.jsx($,{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(ee,{className:"text-xs font-medium text-muted-foreground",children:"Brokerage Name"}),e.jsx(pe,{value:s.brokerage_display_name,onChange:f=>t(g=>({...g,brokerage_display_name:f.target.value})),placeholder:"e.g. Keller Williams Realty",className:"h-10"})]}):e.jsxs("div",{className:"space-y-3",children:[e.jsx(ee,{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:()=>m("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(Cx,{className:"h-3.5 w-3.5"}),r==="brokerage_logo_url"?"Uploading...":s.brokerage_logo_url?"Change":"Upload Logo"]}),e.jsx("input",{type:"file",accept:"image/*",className:"hidden",onChange:f=>h(f,"brokerage_logo_url"),disabled:r!==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(ee,{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(kx,{value:[s.brokerage_logo_size||56],onValueChange:([f])=>t(g=>({...g,brokerage_logo_size:f})),min:24,max:120,step:4})]})]})]}),e.jsxs("div",{className:"space-y-3 p-3 rounded-lg bg-muted/30 border",children:[e.jsx(ee,{className:"text-xs font-semibold uppercase tracking-wider text-muted-foreground",children:"Team"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx($,{type:"button",variant:o==="name"?"default":"outline",size:"sm",className:"text-xs",onClick:()=>u("name"),children:"Use Name"}),e.jsx($,{type:"button",variant:o==="logo"?"default":"outline",size:"sm",className:"text-xs",onClick:()=>u("logo"),children:"Use Logo"})]}),o==="name"?e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{className:"text-xs font-medium text-muted-foreground",children:"Team Name"}),e.jsx(pe,{value:s.team_name,onChange:f=>t(g=>({...g,team_name:f.target.value})),placeholder:"e.g. The Smith Group",className:"h-10"})]}):e.jsxs("div",{className:"space-y-3",children:[e.jsx(ee,{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:()=>m("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(Cx,{className:"h-3.5 w-3.5"}),r==="team_logo_url"?"Uploading...":s.team_logo_url?"Change":"Upload Logo"]}),e.jsx("input",{type:"file",accept:"image/*",className:"hidden",onChange:f=>h(f,"team_logo_url"),disabled:r!==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(ee,{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(kx,{value:[s.team_logo_size||56],onValueChange:([f])=>t(g=>({...g,team_logo_size:f})),min:24,max:120,step:4})]})]})]})]})})}function Vir({form:s,setForm:t}){const n={accent:"#ff5722",dark:"#1a1a2e",button:"#ff5722"},r=s.bold_theme_colors||n,a=(o,c)=>{t(d=>({...d,bold_theme_colors:{...n,...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(ee,{className:"text-sm font-semibold flex items-center gap-1.5",children:[e.jsx(Yc,{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($,{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:r[o],onChange:u=>a(o,u.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:r[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(pe,{value:r[o],onChange:u=>{const h=u.target.value;/^#[0-9a-fA-F]{0,6}$/.test(h)&&a(o,h)},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:r.accent}}),e.jsx("div",{className:"h-6 w-12 rounded",style:{backgroundColor:r.dark}}),e.jsx("div",{className:"h-6 w-12 rounded",style:{backgroundColor:r.button}})]})]})]})}function Hir({card:s,form:t,setForm:n}){var x;const r=X7t(),a=Vt(),{data:i}=Q7t(s.id),[l,o]=j.useState(s.slug),[c,d]=j.useState(!1),[u,h]=j.useState("idle"),m=j.useRef(JSON.stringify(t)),f=j.useRef(null);j.useEffect(()=>{const y=JSON.stringify(t);if(y!==m.current)return f.current&&clearTimeout(f.current),f.current=setTimeout(()=>{h("saving"),r.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:()=>{m.current=y,h("saved"),setTimeout(()=>h("idle"),2e3)},onError:()=>h("idle")})},1500),()=>{f.current&&clearTimeout(f.current)}},[t]);const g=async()=>{const y=l.trim().toLowerCase().replace(/[^a-z0-9-]/g,"-").replace(/-+/g,"-").replace(/(^-|-$)/g,"");if(!y){re.error("Please enter a valid URL");return}if(y===s.slug){re.info("No changes to save");return}d(!0);try{const{data:v}=await q.from("agent_cards").select("id").eq("slug",y).neq("id",s.id).maybeSingle();if(v){re.error("This URL is already taken. Try another one.");return}const{error:b}=await q.from("agent_cards").update({slug:y}).eq("id",s.id);if(b)throw b;o(y),a.invalidateQueries({queryKey:["agent-card"]}),re.success("Card address updated!")}catch{re.error("Failed to update card address")}finally{d(!1)}};return e.jsxs("div",{className:"space-y-4",children:[e.jsxs(ha,{defaultValue:"content",children:[e.jsxs(ma,{className:"w-full h-11 p-1",children:[e.jsxs(Zt,{value:"content",className:"flex-1 gap-1.5 data-[state=active]:shadow-sm",children:[e.jsx(Cv,{className:"h-3.5 w-3.5 hidden sm:inline"}),"Content"]}),e.jsxs(Zt,{value:"sections",className:"flex-1 gap-1.5 data-[state=active]:shadow-sm",children:[e.jsx(Ca,{className:"h-3.5 w-3.5 hidden sm:inline"}),"Sections"]}),e.jsxs(Zt,{value:"blocks",className:"flex-1 gap-1.5 data-[state=active]:shadow-sm",children:[e.jsx(eg,{className:"h-3.5 w-3.5 hidden sm:inline"}),"Blocks"]}),e.jsxs(Zt,{value:"qrcode",className:"flex-1 gap-1.5 data-[state=active]:shadow-sm",children:[e.jsx(Jp,{className:"h-3.5 w-3.5 hidden sm:inline"}),"QR Code"]}),e.jsxs(Zt,{value:"analytics",className:"flex-1 gap-1.5 data-[state=active]:shadow-sm",children:[e.jsx(Lm,{className:"h-3.5 w-3.5 hidden sm:inline"}),"Analytics"]})]}),e.jsxs(Xt,{value:"content",className:"mt-4 space-y-4",children:[e.jsx(Uir,{userId:s.user_id}),e.jsx(qir,{form:t,setForm:n,userId:s.user_id}),e.jsx(Ne,{children:e.jsxs(Ie,{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(ee,{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(Sn,{checked:t.is_published,onCheckedChange:y=>n(v=>({...v,is_published:y}))})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{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(pe,{value:l,onChange:y=>o(y.target.value.toLowerCase().replace(/[^a-z0-9-]/g,"-")),placeholder:"your-name",className:"rounded-l-none h-10"})]}),e.jsx($,{variant:"outline",size:"sm",onClick:g,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(ee,{className:"text-sm font-medium",children:"Card Email (Override)"}),e.jsx(pe,{value:t.display_email,onChange:y=>n(v=>({...v,display_email:y.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(ee,{className:"text-sm font-medium",children:"Theme"}),e.jsxs(ms,{value:t.theme,onValueChange:y=>n(v=>({...v,theme:y})),children:[e.jsx(us,{className:"h-11",children:e.jsx(fs,{})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"standard",children:"✨ Standard — Modern & Clean"}),e.jsx(Ge,{value:"luxury",children:"🌙 Luxury — Dark & Gold"}),e.jsx(Ge,{value:"bold",children:"🔥 Bold — Vibrant & Punchy"}),e.jsx(Ge,{value:"classic",children:"📋 Classic — Professional"})]})]})]}),t.theme==="bold"&&e.jsx(Vir,{form:t,setForm:n}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{className:"text-sm font-medium",children:"Title / Tagline"}),e.jsx(pe,{value:t.title,onChange:y=>n(v=>({...v,title:y.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(ee,{className:"text-sm font-medium",children:"Positioning Statement"}),e.jsx(pe,{value:t.positioning_statement,onChange:y=>n(v=>({...v,positioning_statement:y.target.value})),placeholder:"Your home journey, handled with care.",className:"h-11"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{className:"text-sm font-medium",children:"Bio"}),e.jsx(Rs,{value:t.bio,onChange:y=>n(v=>({...v,bio:y.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(ee,{className:"text-sm font-medium",children:"Review Snippet"}),e.jsx(pe,{value:t.review_snippet,onChange:y=>n(v=>({...v,review_snippet:y.target.value})),placeholder:"Best agent we've ever worked with...",className:"h-11"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{className:"text-sm font-medium",children:"Review Source URL"}),e.jsx(pe,{value:t.review_source_url,onChange:y=>n(v=>({...v,review_source_url:y.target.value})),placeholder:"https://g.page/your-business/review",className:"h-11"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{className:"text-sm font-medium",children:"Booking URL"}),e.jsx(pe,{value:t.booking_url,onChange:y=>n(v=>({...v,booking_url:y.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(ee,{className:"text-sm font-medium",children:"Custom CTA Label"}),e.jsx(pe,{value:t.custom_cta_label,onChange:y=>n(v=>({...v,custom_cta_label:y.target.value})),placeholder:"Book a Call",className:"h-11"})]})]})})]}),e.jsx(Xt,{value:"sections",className:"mt-4",children:e.jsx(Ne,{children:e.jsx(Ie,{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:y,label:v,desc:b})=>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(ee,{className:"text-sm font-medium",children:v}),e.jsx("p",{className:"text-xs text-muted-foreground",children:b})]}),e.jsx(Sn,{checked:t[y],onCheckedChange:w=>n(S=>({...S,[y]:w}))})]},y))})})}),e.jsx(Xt,{value:"blocks",className:"mt-4",children:e.jsx(xos,{cardId:s.id})}),e.jsx(Xt,{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:Ca,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:Lm,color:"text-amber-600 bg-amber-100 dark:text-amber-400 dark:bg-amber-900/30"},{label:"Leads",value:((x=i==null?void 0:i.leads)==null?void 0:x.length)??0,icon:sc,color:"text-emerald-600 bg-emerald-100 dark:text-emerald-400 dark:bg-emerald-900/30"}].map(y=>e.jsx(Ne,{className:"overflow-hidden",children:e.jsxs(Ie,{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 ${y.color}`,children:e.jsx(y.icon,{className:"h-3.5 w-3.5"})}),e.jsx("span",{className:"text-xs font-medium text-muted-foreground",children:y.label})]}),e.jsx("div",{className:"text-2xl font-bold",children:y.value})]})},y.label))}),i&&i.leads.length>0&&e.jsxs(Ne,{children:[e.jsx(Ct,{className:"pb-3",children:e.jsx(At,{className:"text-base",children:"Recent Leads"})}),e.jsx(Ie,{className:"pt-0 space-y-2",children:i.leads.slice(0,5).map(y=>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:y.name}),y.phone&&e.jsx("span",{className:"text-muted-foreground ml-2",children:y.phone})]}),y.intent&&e.jsx(Be,{variant:"secondary",className:"text-xs",children:y.intent})]},y.id))})]}),(!i||i.leads.length===0)&&e.jsx(Ne,{children:e.jsxs(Ie,{className:"p-8 text-center",children:[e.jsx(Lm,{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(Xt,{value:"qrcode",className:"mt-4 space-y-4",children:e.jsx(Ne,{children:e.jsx(Ie,{className:"p-6",children:e.jsx(Fir,{slug:s.slug})})})})]}),e.jsxs("div",{className:"flex items-center justify-center gap-2 py-2 text-sm text-muted-foreground",children:[u==="saving"&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"h-2 w-2 rounded-full bg-amber-400 animate-pulse"})," Saving..."]}),u==="saved"&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"h-2 w-2 rounded-full bg-green-500"})," All changes saved"]}),u==="idle"&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"h-2 w-2 rounded-full bg-muted-foreground/30"})," Changes auto-save"]})]})]})}function Gir(){const s=Vt(),[t,n]=j.useState(""),[r,a]=j.useState(!1),[i,l]=j.useState(!1),[o,c]=j.useState(null),[d,u]=j.useState(!1),[h,m]=j.useState(!1),[f,g]=j.useState(null),[x,y]=j.useState(null),[v,b]=j.useState(0),[w,S]=j.useState(""),[C,E]=j.useState(!1),{data:I,isLoading:P}=tt({queryKey:["boldtrail-status"],queryFn:async()=>{const{data:ie,error:ne}=await q.functions.invoke("boldtrail-sync",{body:{action:"status"}});if(ne)throw ne;return ie}}),R=ft({mutationFn:async ie=>{const{data:ne,error:te}=await q.functions.invoke("boldtrail-sync",{body:{action:"save_token",api_token:ie}});if(te)throw te;if(ne!=null&&ne.error)throw new Error(ne.error);return ne},onSuccess:()=>{s.invalidateQueries({queryKey:["boldtrail-status"]}),n(""),re.success("BoldTrail connected successfully!")},onError:ie=>{re.error(ie.message||"Failed to connect BoldTrail")}}),D=ft({mutationFn:async()=>{const{data:ie,error:ne}=await q.functions.invoke("boldtrail-sync",{body:{action:"disconnect"}});if(ne)throw ne;return ie},onSuccess:()=>{s.invalidateQueries({queryKey:["boldtrail-status"]}),re.success("BoldTrail disconnected")},onError:()=>re.error("Failed to disconnect")}),O=ft({mutationFn:async ie=>{const{data:ne,error:te}=await q.functions.invoke("boldtrail-sync",{body:{action:"save_direction",sync_direction:ie}});if(te)throw te;if(ne!=null&&ne.error)throw new Error(ne.error);return ne},onSuccess:()=>{s.invalidateQueries({queryKey:["boldtrail-status"]}),re.success("Sync direction saved")},onError:ie=>{re.error(ie.message||"Failed to save sync direction")}}),U=ft({mutationFn:async()=>{const{data:ie,error:ne}=await q.functions.invoke("boldtrail-sync",{body:{action:"detect_owner"}});if(ne)throw ne;if(ie!=null&&ie.error)throw new Error(ie.error);return ie},onSuccess:ie=>{if(s.invalidateQueries({queryKey:["boldtrail-status"]}),ie.kvcore_user_id){const ne=ie.detected_name||ie.detected_email||`ID ${ie.kvcore_user_id}`;re.success(`Detected your BoldTrail account: ${ne}`)}else if(ie.candidates&&ie.candidates.length>0){const ne=ie.candidates.slice(0,5).map(te=>`${te.id} (${te.count} contacts)`).join(", ");re.warning(`Couldn't auto-detect your ID. Owner IDs found in your contacts: ${ne}. Pick yours and enter it below.`,{duration:12e3}),E(!0)}else re.warning("Couldn't auto-detect your BoldTrail user ID. Please find it in BoldTrail (My Profile URL) and enter it manually."),E(!0)},onError:ie=>re.error(ie.message||"Detection failed")}),W=ft({mutationFn:async ie=>{const{data:ne,error:te}=await q.functions.invoke("boldtrail-sync",{body:{action:"save_owner_settings",...ie}});if(te)throw te;if(ne!=null&&ne.error)throw new Error(ne.error);return ne},onSuccess:()=>{s.invalidateQueries({queryKey:["boldtrail-status"]}),re.success("Settings saved"),E(!1)},onError:ie=>re.error(ie.message||"Failed to save settings")}),V=ft({mutationFn:async()=>{const{data:ie,error:ne}=await q.functions.invoke("boldtrail-sync",{body:{action:"sync_preview"}});if(ne)throw ne;if(ie!=null&&ie.error)throw new Error(ie.error);return ie},onSuccess:ie=>{g(null),c(ie),a(!0)},onError:ie=>{re.error(ie.message||"Failed to generate sync preview")}}),G=ft({mutationFn:async()=>{y("Initializing sync..."),b(5);const{data:ie,error:ne}=await q.functions.invoke("boldtrail-sync",{body:{action:"sync",phase:"init",sync_direction:ae}});if(ne)throw ne;if(ie!=null&&ie.error)throw new Error(ie.error);const te=ie;let J=te.sync_log_id,ce=te.next_phase,_e=te.next_offset,he=te.push_total||0,ue=te.pull_total||0,ve=0,Ee=0;for(;ce!=="finalize";){const Fe=he+ue;ce==="fetch_bt"?y("Fetching BoldTrail contacts..."):ce==="analyze"?(y("Analyzing contacts..."),b(15)):ce==="push"?(y(`Pushing contacts to BoldTrail... (${ve}/${he})`),b(Fe>0?ve/Fe*100:0)):ce==="pull"&&(y(`Pulling contacts from BoldTrail... (${Ee}/${ue})`),b(Fe>0?(he+Ee)/Fe*100:0));const{data:ke,error:Ve}=await q.functions.invoke("boldtrail-sync",{body:{action:"sync",phase:ce,offset:_e,sync_log_id:J,sync_direction:ae}});if(Ve)throw Ve;if(ke!=null&&ke.error)throw new Error(ke.error);const je=ke;ve+=je.chunk_pushed||0,Ee+=je.chunk_pulled||0,je.push_total!==void 0&&(he=je.push_total||0),je.pull_total!==void 0&&(ue=je.pull_total||0),je.progress&&y(je.progress),ce==="pull"&&ue>0?b(Math.min(95,Ee/ue*100)):ce==="push"&&he>0&&b(Math.min(95,ve/he*100)),ce=je.next_phase,_e=je.next_offset}y("Finalizing sync..."),b(95);const{data:Se,error:Le}=await q.functions.invoke("boldtrail-sync",{body:{action:"sync",phase:"finalize",sync_log_id:J,sync_direction:ae}});if(Le)throw Le;return b(100),Se},onSuccess:ie=>{y(null),b(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"]}),re.success(`Sync complete! Pushed ${ie.contacts_pushed||0}, pulled ${ie.contacts_pulled||0}, skipped ${ie.contacts_skipped||0} duplicates.`)},onError:ie=>{y(null),b(0),re.error(ie.message||"Sync failed")}}),Y=I==null?void 0:I.connected,X=(I==null?void 0:I.sync_direction)||"bidirectional",ae=f??X;return e.jsxs(e.Fragment,{children:[e.jsxs(Ne,{children:[e.jsx(Ct,{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(By,{className:"h-5 w-5 text-emerald-600"})}),e.jsxs("div",{children:[e.jsxs(At,{className:"text-lg flex items-center gap-2",children:["BoldTrail",Y&&e.jsx(Be,{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(tf,{className:"h-3.5 w-3.5"}),"Learn More"]})]}),e.jsx(Gn,{children:"Sync contacts bidirectionally between Agent OS and your BoldTrail (kvCORE) CRM."})]})]})}),e.jsx(Ie,{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(Nc,{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(Nc,{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(Nc,{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"})]}),Y?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"}),(I==null?void 0:I.last_sync_at)&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Last sync: ",new Date(I.last_sync_at).toLocaleString(),I.last_sync_status&&e.jsx(Be,{variant:I.last_sync_status==="success"?"default":"secondary",className:"ml-2 text-[10px]",children:I.last_sync_status})]}),(I==null?void 0:I.boldtrail_contact_count)!=null&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:[I.boldtrail_contact_count," contacts in BoldTrail"]}),(I==null?void 0:I.last_sync_message)&&e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:I.last_sync_message})]}),e.jsxs(kc,{children:[e.jsx(jx,{asChild:!0,children:e.jsx($,{variant:"ghost",size:"icon",className:"text-destructive hover:text-destructive",children:e.jsx(Wn,{className:"h-4 w-4"})})}),e.jsxs(cc,{children:[e.jsxs(dc,{children:[e.jsx(hc,{children:"Disconnect BoldTrail?"}),e.jsx(mc,{children:"This will remove your API token. Previously synced contacts will remain in both systems."})]}),e.jsxs(uc,{children:[e.jsx(fc,{children:"Cancel"}),e.jsx(tc,{onClick:()=>D.mutate(),className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Disconnect"})]})]})]})]})}),e.jsx("div",{className:"rounded-lg border p-3",children:e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(y2,{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:"Include contacts without an email address"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Phone or name-only leads come across too. Turn this off to sync only contacts that have an email address."})]}),e.jsx(Sn,{checked:(I==null?void 0:I.sync_include_no_email)!==!1,onCheckedChange:ie=>W.mutate({sync_include_no_email:ie}),disabled:W.isPending})]})}),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(y2,{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(Sn,{checked:!!(I!=null&&I.sync_only_owned),onCheckedChange:ie=>W.mutate({sync_only_owned:ie}),disabled:W.isPending})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(ee,{className:"text-xs",children:"Your BoldTrail Agent ID"}),C?e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(pe,{type:"number",placeholder:"e.g. 12345",value:w,onChange:ie=>S(ie.target.value),className:"h-8 text-sm"}),e.jsx($,{size:"sm",onClick:()=>{const ie=w.trim()===""?null:Number(w);W.mutate({kvcore_user_id:ie})},disabled:W.isPending,children:"Save"}),e.jsx($,{size:"sm",variant:"ghost",onClick:()=>E(!1),children:"Cancel"})]}):e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("span",{className:"text-sm font-mono",children:(I==null?void 0:I.kvcore_user_id)??e.jsx("span",{className:"text-muted-foreground",children:"Not set"})}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs($,{size:"sm",variant:"outline",onClick:()=>U.mutate(),disabled:U.isPending,children:[U.isPending?e.jsx(ro,{className:"h-3 w-3 mr-1 animate-spin"}):null,"Auto-detect"]}),e.jsx($,{size:"sm",variant:"ghost",onClick:()=>{var ie;S(((ie=I==null?void 0:I.kvcore_user_id)==null?void 0:ie.toString())??""),E(!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(ePe,{value:X,onChange:ie=>O.mutate(ie)})}),e.jsx("div",{className:"flex gap-2",children:e.jsxs($,{onClick:()=>V.mutate(),disabled:V.isPending||G.isPending,variant:"outline",className:"gap-2",children:[V.isPending?e.jsx(ro,{className:"h-4 w-4 animate-spin"}):e.jsx(Ca,{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(pe,{type:"password",placeholder:"Paste your BoldTrail API token",value:t,onChange:ie=>n(ie.target.value),className:"flex-1"}),e.jsxs($,{onClick:()=>R.mutate(t),disabled:!t||t.length<10||R.isPending,children:[R.isPending?e.jsx(ro,{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(zs,{open:r,onOpenChange:ie=>{G.isPending||a(ie)},children:e.jsxs(Os,{className:"sm:max-w-lg",children:[e.jsxs(Us,{children:[e.jsxs(Bs,{className:"flex items-center gap-2",children:[e.jsx(By,{className:"h-5 w-5 text-emerald-600"}),"Sync Preview"]}),e.jsx(Ir,{children:"Review what will happen when you sync your contacts."})]}),o&&(()=>{const ie=ae==="pull_only"?0:o.to_push,ne=ae==="push_only"?0:o.to_pull;return e.jsxs("div",{className:"space-y-4",children:[e.jsx(ePe,{value:ae,onChange:g,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(y2,{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 ${ae==="pull_only"?"opacity-40":""}`,children:[e.jsx("p",{className:"text-2xl font-bold text-emerald-600",children:ie}),e.jsxs("p",{className:"text-xs text-muted-foreground flex items-center justify-center gap-1",children:[e.jsx(Zf,{className:"h-3 w-3"})," Push to BoldTrail"]})]}),e.jsxs("div",{className:`rounded-lg border p-3 text-center ${ae==="push_only"?"opacity-40":""}`,children:[e.jsx("p",{className:"text-2xl font-bold text-blue-600",children:ne}),e.jsxs("p",{className:"text-xs text-muted-foreground flex items-center justify-center gap-1",children:[e.jsx(Dg,{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(Zn,{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"]}),G.isPending&&e.jsxs("div",{className:"space-y-2 py-2",children:[e.jsx(Yi,{value:v||10,className:"h-2"}),e.jsx("p",{className:"text-xs text-muted-foreground text-center",children:x||"Sync in progress..."})]}),ie>0&&e.jsxs(j1,{open:d,onOpenChange:u,children:[e.jsx(N1,{asChild:!0,children:e.jsxs($,{variant:"ghost",size:"sm",className:"w-full justify-between text-xs",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Zf,{className:"h-3 w-3 text-emerald-600"}),ie," contacts to push to BoldTrail"]}),e.jsx(Tl,{className:`h-3 w-3 transition-transform ${d?"rotate-180":""}`})]})}),e.jsx(k1,{children:e.jsxs("div",{className:"rounded border divide-y max-h-40 overflow-y-auto",children:[o.push_preview.map((te,J)=>e.jsxs("div",{className:"px-3 py-1.5 text-xs flex justify-between",children:[e.jsx("span",{className:"font-medium",children:te.name||"No name"}),e.jsx("span",{className:"text-muted-foreground",children:te.email})]},J)),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"]})]})})]}),ne>0&&e.jsxs(j1,{open:h,onOpenChange:m,children:[e.jsx(N1,{asChild:!0,children:e.jsxs($,{variant:"ghost",size:"sm",className:"w-full justify-between text-xs",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Dg,{className:"h-3 w-3 text-blue-600"}),ne," contacts to pull from BoldTrail"]}),e.jsx(Tl,{className:`h-3 w-3 transition-transform ${h?"rotate-180":""}`})]})}),e.jsx(k1,{children:e.jsxs("div",{className:"rounded border divide-y max-h-40 overflow-y-auto",children:[o.pull_preview.map((te,J)=>e.jsxs("div",{className:"px-3 py-1.5 text-xs flex justify-between",children:[e.jsx("span",{className:"font-medium",children:te.name||"No name"}),e.jsx("span",{className:"text-muted-foreground",children:te.email})]},J)),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"]})]})})]}),ie===0&&ne===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($,{variant:"outline",onClick:()=>a(!1),disabled:G.isPending,children:"Cancel"}),e.jsxs($,{onClick:()=>G.mutate(),disabled:G.isPending||ie===0&&ne===0,className:"gap-2",children:[G.isPending?e.jsx(ro,{className:"h-4 w-4 animate-spin"}):e.jsx(By,{className:"h-4 w-4"}),G.isPending?"Syncing...":"Sync Now"]})]})]})})()]})}),e.jsx(zs,{open:i,onOpenChange:l,children:e.jsxs(Os,{className:"sm:max-w-2xl p-0 overflow-hidden",children:[e.jsx(Us,{className:"p-6 pb-0",children:e.jsxs(Bs,{className:"flex items-center gap-2",children:[e.jsx(By,{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"})})]})})]})}const nU=async s=>{const{data:t,error:n}=await q.functions.invoke("lofty-sync",{body:s});if(n)throw new Error(n.message);if(t!=null&&t.error)throw new Error(typeof t.error=="string"?t.error:JSON.stringify(t.error));return t};function Wir(){const s=Vt(),[t,n]=j.useState(""),[r,a]=j.useState(""),[i,l]=j.useState(!1),[o,c]=j.useState(0),[d,u]=j.useState(null),[h,m]=j.useState(null),{data:f,isLoading:g}=tt({queryKey:["lofty-status"],queryFn:async()=>await nU({action:"status"})}),x=()=>s.invalidateQueries({queryKey:["lofty-status"]}),y=ft({mutationFn:async()=>nU({action:"save_token",api_token:t.trim()}),onSuccess:E=>{re.success(E!=null&&E.contact_count?`Connected to Lofty — ${E.contact_count} contacts found`:"Connected to Lofty"),n(""),x()},onError:E=>re.error(E.message)}),v=ft({mutationFn:async()=>nU({action:"disconnect"}),onSuccess:()=>{re.success("Lofty disconnected"),x()},onError:E=>re.error(E.message)}),b=ft({mutationFn:async E=>nU({action:"save_settings",...E}),onSuccess:()=>x(),onError:E=>re.error(E.message)}),w=ft({mutationFn:async()=>nU({action:"detect_owner"}),onSuccess:E=>{const I=(E==null?void 0:E.candidates)||[];m(I),I.length===0?re.info("No assigned-agent IDs found on your Lofty contacts."):I.length===1?(b.mutate({lofty_user_id:I[0].id}),re.success(`Using Lofty agent ID ${I[0].id}`)):re.success("Pick which Lofty agent ID is yours below.")},onError:E=>re.error(E.message)}),S=async()=>{l(!0),c(2),u("Starting Lofty sync…");try{let E="start",I=0,P=null,R=0;for(;E&&R<400;){R++;const D=await nU({action:"sync",phase:E,offset:I,sync_log_id:P});P=D.sync_log_id||P,D.progress&&u(D.progress),c(O=>Math.min(95,O+4)),E=D.next_phase,I=D.next_offset||0,E||(c(100),u(D.message||"Sync complete"),re.success(D.message||"Lofty sync complete"))}}catch(E){re.error(E.message||"Lofty sync failed"),u(null)}finally{l(!1),setTimeout(()=>c(0),2500),x()}},C=!!(f!=null&&f.connected);return e.jsxs(Ne,{children:[e.jsx(Ct,{children:e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsxs(At,{className:"flex items-center gap-2",children:["Lofty",C?e.jsxs(Be,{variant:"secondary",className:"gap-1",children:[e.jsx(Nc,{className:"h-3 w-3"})," Connected"]}):e.jsx(Be,{variant:"outline",children:"Not connected"})]}),e.jsx(Gn,{children:"Sync your Lofty (formerly Chime) contacts — names, emails, phones, address, source, stage, tags and notes — into Agent OS."})]}),C&&e.jsxs(kc,{children:[e.jsx(jx,{asChild:!0,children:e.jsx($,{variant:"ghost",size:"icon","aria-label":"Disconnect Lofty",children:e.jsx(Wn,{className:"h-4 w-4"})})}),e.jsxs(cc,{children:[e.jsxs(dc,{children:[e.jsx(hc,{children:"Disconnect Lofty?"}),e.jsx(mc,{children:"Your API key and sync settings will be removed. Contacts already imported into Agent OS stay put."})]}),e.jsxs(uc,{children:[e.jsx(fc,{children:"Cancel"}),e.jsx(tc,{onClick:()=>v.mutate(),children:"Disconnect"})]})]})]})]})}),e.jsx(Ie,{className:"space-y-5",children:g?e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(kt,{className:"h-4 w-4 animate-spin"})," Loading…"]}):C?e.jsxs("div",{className:"space-y-5",children:[e.jsx(ePe,{value:(f==null?void 0:f.sync_direction)||"pull_only",onChange:E=>b.mutate({sync_direction:E}),size:"sm"}),e.jsxs("div",{className:"space-y-3 rounded-lg border p-3",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",children:"Only my contacts"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Skip team/brokerage contacts assigned to other Lofty agents."})]}),e.jsx(Sn,{checked:!!(f!=null&&f.sync_only_owned),onCheckedChange:E=>b.mutate({sync_only_owned:E})})]}),(f==null?void 0:f.sync_only_owned)&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs($,{size:"sm",variant:"outline",onClick:()=>w.mutate(),disabled:w.isPending,children:[w.isPending?e.jsx(kt,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(Zn,{className:"h-3.5 w-3.5"}),"Detect my Lofty agent ID"]}),(f==null?void 0:f.lofty_user_id)&&e.jsxs(Be,{variant:"secondary",children:["Agent ID ",f.lofty_user_id]})]}),h&&h.length>1&&e.jsx("div",{className:"flex flex-wrap gap-2",children:h.map(E=>e.jsxs($,{size:"sm",variant:(f==null?void 0:f.lofty_user_id)===E.id?"default":"outline",onClick:()=>b.mutate({lofty_user_id:E.id}),children:[E.id," · ",E.count," contacts"]},E.id))})]}),e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",children:"Import notes"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Pull each contact's Lofty notes into their Agent OS notes (deduped)."})]}),e.jsx(Sn,{checked:!!(f!=null&&f.import_notes),onCheckedChange:E=>b.mutate({import_notes:E})})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{htmlFor:"lofty-tags",className:"text-sm",children:"Tag filter (optional)"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(pe,{id:"lofty-tags",placeholder:((f==null?void 0:f.pull_tag_filter)||[]).join(", ")||"e.g. Sphere, Buyer",value:r,onChange:E=>a(E.target.value)}),e.jsx($,{variant:"outline",onClick:()=>b.mutate({pull_tag_filter:r.split(",").map(E=>E.trim()).filter(Boolean)}),children:"Save"})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Leave empty to import every contact. Comma-separated Lofty tags."})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs($,{onClick:S,disabled:i,children:[i?e.jsx(kt,{className:"h-4 w-4 animate-spin"}):e.jsx(ro,{className:"h-4 w-4"}),i?"Syncing…":"Sync Now"]}),(f==null?void 0:f.last_sync_at)&&e.jsxs("span",{className:"text-xs text-muted-foreground",children:["Last sync ",new Date(f.last_sync_at).toLocaleString("en-US",{timeZone:"America/New_York"})]})]}),(i||o>0)&&e.jsxs("div",{className:"space-y-1",children:[e.jsx(Yi,{value:o}),d&&e.jsx("p",{className:"text-xs text-muted-foreground",children:d})]}),(f==null?void 0:f.last_sync_message)&&!i&&e.jsx("p",{className:"text-xs text-muted-foreground",children:f.last_sync_message})]}),((f==null?void 0:f.logs)||[]).length>0&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("p",{className:"text-sm font-medium",children:"Recent syncs"}),e.jsx("div",{className:"space-y-1",children:f.logs.map(E=>e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2 rounded-md border px-3 py-2 text-xs",children:[e.jsx("span",{className:"text-muted-foreground",children:new Date(E.created_at).toLocaleString("en-US",{timeZone:"America/New_York"})}),e.jsxs("span",{children:[E.contacts_pulled," imported · ",E.contacts_pushed," pushed ·"," ",E.contacts_skipped," skipped"]}),e.jsx(Be,{variant:E.status==="completed"?"secondary":"destructive",children:E.status})]},E.id))})]})]}):e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{htmlFor:"lofty-key",children:"Lofty API Key"}),e.jsx(pe,{id:"lofty-key",type:"password",placeholder:"Paste your Lofty API key",value:t,onChange:E=>n(E.target.value),autoComplete:"off"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["In Lofty go to ",e.jsx("strong",{children:"Settings → Integrations → API Key Management"})," and create a key with contact access."]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs($,{onClick:()=>y.mutate(),disabled:t.trim().length<10||y.isPending,children:[y.isPending?e.jsx(kt,{className:"h-4 w-4 animate-spin"}):e.jsx(g2,{className:"h-4 w-4"}),"Connect Lofty"]}),e.jsx($,{variant:"ghost",size:"sm",asChild:!0,children:e.jsxs("a",{href:"https://developer.lofty.com/",target:"_blank",rel:"noreferrer",children:["Lofty API docs ",e.jsx(kr,{className:"ml-1 h-3 w-3"})]})})]})]})})]})}function Kir(){const s=Vt(),[t,n]=j.useState(""),[r,a]=j.useState(!1),[i,l]=j.useState(0),[o,c]=j.useState(null),{data:d,isLoading:u}=tt({queryKey:["fub-status"],queryFn:async()=>{const{data:x,error:y}=await q.functions.invoke("followupboss-sync",{body:{action:"status"}});if(y)throw y;return x}}),h=ft({mutationFn:async x=>{const{data:y,error:v}=await q.functions.invoke("followupboss-sync",{body:{action:"save_token",api_key:x}});if(v)throw v;if(y!=null&&y.error)throw new Error(y.error);return y},onSuccess:()=>{re.success("Connected to Follow Up Boss"),n(""),s.invalidateQueries({queryKey:["fub-status"]})},onError:x=>re.error(x.message)}),m=ft({mutationFn:async()=>{const{error:x}=await q.functions.invoke("followupboss-sync",{body:{action:"disconnect"}});if(x)throw x},onSuccess:()=>{re.success("Disconnected"),s.invalidateQueries({queryKey:["fub-status"]})}}),f=ft({mutationFn:async x=>{const{error:y}=await q.functions.invoke("followupboss-sync",{body:{action:"set_direction",sync_direction:x}});if(y)throw y},onSuccess:()=>s.invalidateQueries({queryKey:["fub-status"]})}),g=async()=>{a(!0),l(0),c("Pulling from FUB…");let x=0,y=0,v=0,b=0;try{for(;;){const{data:E,error:I}=await q.functions.invoke("followupboss-sync",{body:{action:"sync",offset:x}});if(I)throw I;if(E!=null&&E.error)throw new Error(E.error);y+=E.chunk_created||0,v+=E.chunk_updated||0,b+=E.chunk_skipped||0,x=E.next_offset;const P=E.total?Math.min(100,Math.round(x/E.total*100)):100;if(l(P),c(`Pulling · ${x} / ${E.total||"?"}`),E.done)break;await new Promise(R=>setTimeout(R,400))}let w=0,S=0;if((d==null?void 0:d.sync_direction)==="bidirectional"){let E=0;for(l(0),c("Pushing to FUB…");;){const{data:I,error:P}=await q.functions.invoke("followupboss-sync",{body:{action:"push",offset:E}});if(P)throw P;if(I!=null&&I.error)throw new Error(I.error);w+=I.chunk_pushed||0,S+=I.chunk_failed||0,E=I.next_offset;const R=I.total?Math.min(100,Math.round(E/I.total*100)):100;if(l(R),c(`Pushing · ${E} / ${I.total||"?"}`),I.done)break;await new Promise(D=>setTimeout(D,400))}}const C=w||S?` · pushed ${w}${S?`, ${S} failed`:""}`:"";re.success(`Sync complete · ${y} new, ${v} updated${b?`, ${b} skipped`:""}${C}`),s.invalidateQueries({queryKey:["fub-status"]})}catch(w){re.error(w.message||"Sync failed")}finally{a(!1),setTimeout(()=>{l(0),c(null)},2500)}};return e.jsxs(Ne,{children:[e.jsx(Ct,{children:e.jsx("div",{className:"flex items-start justify-between gap-3",children:e.jsxs("div",{children:[e.jsxs(At,{className:"flex items-center gap-2",children:[e.jsx(g2,{className:"h-5 w-5 text-primary"}),"Follow Up Boss",(d==null?void 0:d.connected)&&e.jsxs(Be,{variant:"default",className:"ml-1",children:[e.jsx(Nc,{className:"h-3 w-3 mr-1"})," Connected"]})]}),e.jsx(Gn,{children:"Sync your Follow Up Boss contacts into Agent OS."})]})})}),e.jsx(Ie,{className:"space-y-4",children:u?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(Sn,{checked:d.sync_direction==="bidirectional",onCheckedChange:x=>f.mutate(x?"bidirectional":"pull_only"),disabled:r||f.isPending})]}),o&&e.jsxs("div",{className:"space-y-1",children:[e.jsx(Yi,{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($,{onClick:g,disabled:r,children:[e.jsx(ro,{className:`h-4 w-4 mr-2 ${r?"animate-spin":""}`}),r?"Syncing…":"Sync Now"]}),e.jsxs(kc,{children:[e.jsx(jx,{asChild:!0,children:e.jsxs($,{variant:"outline",disabled:r,children:[e.jsx(Wn,{className:"h-4 w-4 mr-2"})," Disconnect"]})}),e.jsxs(cc,{children:[e.jsxs(dc,{children:[e.jsx(hc,{children:"Disconnect Follow Up Boss?"}),e.jsx(mc,{children:"Your API key will be removed. Synced contacts stay in Agent OS."})]}),e.jsxs(uc,{children:[e.jsx(fc,{children:"Cancel"}),e.jsx(tc,{onClick:()=>m.mutate(),children:"Disconnect"})]})]})]})]})]}):e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"fub-key",children:"Follow Up Boss API Key"}),e.jsx(pe,{id:"fub-key",type:"password",placeholder:"fka_live_...",value:t,onChange:x=>n(x.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(kr,{className:"h-3 w-3"})]})]})]}),e.jsx($,{onClick:()=>h.mutate(t),disabled:!t.trim()||h.isPending,children:h.isPending?"Connecting…":"Connect"})]})})]})}function Yir(){var V;const s=Vt(),[t,n]=j.useState(""),[r,a]=j.useState(""),[i,l]=j.useState(!1),[o,c]=j.useState(0),[d,u]=j.useState(null),[h,m]=j.useState(!1),[f,g]=j.useState(null),[x,y]=j.useState(!1),[v,b]=j.useState(new Set),{data:w,isLoading:S}=tt({queryKey:["cloze-status"],queryFn:async()=>{const{data:G,error:Y}=await q.functions.invoke("cloze-sync",{body:{action:"status"}});if(Y)throw Y;return G}}),C=ft({mutationFn:async()=>{const{data:G,error:Y}=await q.functions.invoke("cloze-sync",{body:{action:"save_token",api_key:t.trim(),account_email:r.trim()}});if(Y)throw Y;if(G!=null&&G.error)throw new Error(G.error);return G},onSuccess:()=>{re.success("Connected to Cloze"),n(""),a(""),s.invalidateQueries({queryKey:["cloze-status"]})},onError:G=>re.error(G.message)}),E=ft({mutationFn:async()=>{const{error:G}=await q.functions.invoke("cloze-sync",{body:{action:"disconnect"}});if(G)throw G},onSuccess:()=>{re.success("Cloze disconnected"),s.invalidateQueries({queryKey:["cloze-status"]})}}),I=ft({mutationFn:async G=>{const{error:Y}=await q.functions.invoke("cloze-sync",{body:{action:"set_direction",sync_direction:G}});if(Y)throw Y},onSuccess:()=>s.invalidateQueries({queryKey:["cloze-status"]})}),P=ft({mutationFn:async G=>{const{error:Y}=await q.functions.invoke("cloze-sync",{body:{action:"set_scope",...G}});if(Y)throw Y},onSuccess:()=>s.invalidateQueries({queryKey:["cloze-status"]})}),R=async()=>{y(!0);try{const{data:G,error:Y}=await q.functions.invoke("cloze-sync",{body:{action:"list_segments"}});if(Y)throw Y;if(G!=null&&G.error)throw new Error(G.error);g(G.segments||[]),b(new Set((w==null?void 0:w.selected_segments)||[])),m(!0)}catch(G){re.error(G.message||"Failed to load segments")}finally{y(!1)}},D=async()=>{const G=Array.from(v);await P.mutateAsync({sync_scope:"segments",selected_segments:G}),re.success(`Saved · ${G.length} segment(s) selected`),m(!1)},O=async()=>{const G=(w==null?void 0:w.sync_direction)||"pull_only";l(!0),c(0);try{if(G==="pull_only"||G==="bidirectional"){u("Pulling from Cloze…");let Y=0,X=0,ae=0;for(;;){const{data:ie,error:ne}=await q.functions.invoke("cloze-sync",{body:{action:"sync",offset:Y}});if(ne)throw ne;if(ie!=null&&ie.error)throw new Error(ie.error);if(X+=ie.chunk_created||0,ae+=ie.chunk_updated||0,Y=ie.next_offset,u(`Pulling · ${X+ae} contacts processed`),c(ie.done?100:Math.min(95,(X+ae)%200/2)),ie.done)break;await new Promise(te=>setTimeout(te,300))}re.success(`Pulled · ${X} new, ${ae} updated`)}if(G==="push_only"||G==="bidirectional"){c(0),u("Pushing to Cloze…");let Y=0,X=0,ae=0;for(;;){const{data:ie,error:ne}=await q.functions.invoke("cloze-sync",{body:{action:"push",offset:Y}});if(ne)throw ne;if(ie!=null&&ie.error)throw new Error(ie.error);X+=ie.chunk_pushed||0,ae+=ie.chunk_failed||0,Y=ie.next_offset;const te=ie.total?Math.min(100,Math.round(Y/ie.total*100)):100;if(c(te),u(`Pushing · ${Y} / ${ie.total||"?"}`),ie.done)break;await new Promise(J=>setTimeout(J,300))}re.success(`Pushed · ${X}${ae?`, ${ae} failed`:""}`)}s.invalidateQueries({queryKey:["cloze-status"]})}catch(Y){re.error(Y.message||"Sync failed")}finally{l(!1),setTimeout(()=>{c(0),u(null)},2e3)}},U=(w==null?void 0:w.sync_scope)||"all",W=((V=w==null?void 0:w.selected_segments)==null?void 0:V.length)||0;return e.jsxs(Ne,{children:[e.jsx(Ct,{children:e.jsx("div",{className:"flex items-start justify-between gap-3",children:e.jsxs("div",{children:[e.jsxs(At,{className:"flex items-center gap-2",children:[e.jsx(g2,{className:"h-5 w-5 text-primary"}),"Cloze",(w==null?void 0:w.connected)&&e.jsxs(Be,{variant:"default",className:"ml-1",children:[e.jsx(Nc,{className:"h-3 w-3 mr-1"})," Connected"]})]}),e.jsx(Gn,{children:"Sync contacts between Cloze and Agent OS using your personal Cloze API key."})]})})}),e.jsx(Ie,{className:"space-y-4",children:S?e.jsx("p",{className:"text-sm text-muted-foreground",children:"Loading…"}):w!=null&&w.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:"Account"}),e.jsx("p",{className:"font-medium break-all",children:w.account_email})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-muted-foreground",children:"Last sync"}),e.jsx("p",{className:"font-medium",children:w.last_sync_at?new Date(w.last_sync_at).toLocaleString():"Never"})]})]}),w.last_sync_status==="error"&&e.jsx("p",{className:"text-sm text-destructive",children:w.last_sync_message}),e.jsx("div",{className:"rounded-lg border px-3 py-2 space-y-2",children:e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",children:"Sync direction"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Choose which way contacts should flow."})]}),e.jsxs(ms,{value:w.sync_direction||"pull_only",onValueChange:G=>I.mutate(G),disabled:i||I.isPending,children:[e.jsx(us,{className:"w-[180px]",children:e.jsx(fs,{})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"pull_only",children:"Pull from Cloze"}),e.jsx(Ge,{value:"push_only",children:"Push to Cloze"}),e.jsx(Ge,{value:"bidirectional",children:"Two-way sync"})]})]})]})}),e.jsxs("div",{className:"rounded-lg border px-3 py-2 space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",children:"What to sync"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:U==="all"?"All Cloze contacts.":`${W} segment${W===1?"":"s"} selected.`})]}),e.jsxs(ms,{value:U,onValueChange:G=>{G==="all"?P.mutate({sync_scope:"all",selected_segments:[]}):(P.mutate({sync_scope:"segments",selected_segments:w.selected_segments||[]}),R())},disabled:i||P.isPending,children:[e.jsx(us,{className:"w-[180px]",children:e.jsx(fs,{})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"all",children:"All contacts"}),e.jsx(Ge,{value:"segments",children:"Selected segments"})]})]})]}),U==="segments"&&e.jsxs("div",{children:[e.jsxs($,{variant:"outline",size:"sm",onClick:R,disabled:x,children:[e.jsx(aee,{className:"h-4 w-4 mr-2"}),x?"Loading segments…":"Choose segments"]}),h&&f&&e.jsxs("div",{className:"mt-3 space-y-2",children:[e.jsxs("div",{className:"max-h-96 overflow-y-auto rounded-md border divide-y",children:[f.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground p-3",children:"No segments found in your Cloze account."}),f.map(G=>{const Y=v.has(G.id);return e.jsxs("label",{className:"flex items-center gap-3 p-2 cursor-pointer hover:bg-muted/50",children:[e.jsx(ai,{checked:Y,onCheckedChange:X=>{const ae=new Set(v);X?ae.add(G.id):ae.delete(G.id),b(ae)}}),e.jsx("span",{className:"flex-1 text-sm",children:G.name}),G.count!=null&&e.jsx(Be,{variant:"secondary",className:"text-xs",children:G.count})]},G.id)})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs($,{size:"sm",onClick:D,disabled:P.isPending,children:["Save selection (",v.size,")"]}),e.jsx($,{size:"sm",variant:"ghost",onClick:()=>m(!1),children:"Cancel"})]})]})]})]}),d&&e.jsxs("div",{className:"space-y-1",children:[e.jsx(Yi,{value:o}),e.jsx("p",{className:"text-xs text-muted-foreground",children:d})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(kc,{children:[e.jsx(jx,{asChild:!0,children:e.jsxs($,{disabled:i,children:[e.jsx(ro,{className:`h-4 w-4 mr-2 ${i?"animate-spin":""}`}),i?"Syncing…":"Sync Now"]})}),e.jsxs(cc,{children:[e.jsxs(dc,{children:[e.jsx(hc,{children:"Preview sync"}),e.jsx(mc,{asChild:!0,children:e.jsx(Zir,{segments:f})})]}),e.jsxs(uc,{children:[e.jsx(fc,{children:"Cancel"}),e.jsx(tc,{onClick:O,children:"Start Sync"})]})]})]}),e.jsxs(kc,{children:[e.jsx(jx,{asChild:!0,children:e.jsxs($,{variant:"outline",disabled:i,children:[e.jsx(Wn,{className:"h-4 w-4 mr-2"})," Disconnect"]})}),e.jsxs(cc,{children:[e.jsxs(dc,{children:[e.jsx(hc,{children:"Disconnect Cloze?"}),e.jsx(mc,{children:"Your API key will be removed. Contacts already synced will remain."})]}),e.jsxs(uc,{children:[e.jsx(fc,{children:"Cancel"}),e.jsx(tc,{onClick:()=>E.mutate(),children:"Disconnect"})]})]})]})]})]}):e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"cloze-email",children:"Cloze Account Email"}),e.jsx(pe,{id:"cloze-email",type:"email",placeholder:"you@example.com",value:r,onChange:G=>a(G.target.value)})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"cloze-key",children:"Cloze API Key"}),e.jsx(pe,{id:"cloze-key",type:"password",placeholder:"Your personal Cloze API key",value:t,onChange:G=>n(G.target.value)}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-1 flex items-center gap-1",children:["Generate one in Cloze → Settings → API Keys.",e.jsxs("a",{href:"https://app.cloze.com/app/#/settings/apikeys",target:"_blank",rel:"noreferrer",className:"inline-flex items-center gap-0.5 text-primary hover:underline",children:["Open ",e.jsx(kr,{className:"h-3 w-3"})]})]})]}),e.jsx($,{onClick:()=>C.mutate(),disabled:!t.trim()||!r.trim()||C.isPending,children:C.isPending?"Connecting…":"Connect Cloze"})]})})]})}function Zir({segments:s}){var h;const[t,n]=j.useState(!0),[r,a]=j.useState(null),[i,l]=j.useState(null);if(j.useEffect(()=>{(async()=>{try{const{data:m,error:f}=await q.functions.invoke("cloze-sync",{body:{action:"preview"}});if(f)throw f;if(m!=null&&m.error)throw new Error(m.error);a(m)}catch(m){l(m.message||"Could not load preview")}finally{n(!1)}})()},[]),t)return e.jsx("span",{className:"text-sm",children:"Calculating…"});if(i)return e.jsx("span",{className:"text-sm text-destructive",children:i});const o=new Map((s||[]).map(m=>[m.id,m.name])),c=r.total_incoming??0,d=r.already_synced??0,u=Math.max(0,c-d);return e.jsxs("div",{className:"space-y-3 text-sm text-foreground",children:[e.jsxs("div",{className:"rounded-md border p-3 space-y-1",children:[e.jsxs("div",{className:"flex justify-between",children:[e.jsxs("span",{children:["Contacts in Cloze (",r.scope==="segments"?"selected segments":"all",")"]}),e.jsx("strong",{children:c.toLocaleString()})]}),e.jsxs("div",{className:"flex justify-between text-muted-foreground",children:[e.jsx("span",{children:"Already linked to Cloze in your CRM"}),e.jsx("span",{children:d.toLocaleString()})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{children:"Estimated new contacts"}),e.jsxs("strong",{children:["~",u.toLocaleString()]})]})]}),r.scope==="segments"&&((h=r.segment_counts)==null?void 0:h.length)>0&&e.jsx("div",{className:"rounded-md border p-3 space-y-1 max-h-40 overflow-auto",children:r.segment_counts.map(m=>e.jsxs("div",{className:"flex justify-between text-xs",children:[e.jsx("span",{children:o.get(m.id)||m.id}),e.jsx("span",{className:"text-muted-foreground",children:m.total})]},m.id))}),e.jsx("p",{className:"text-xs text-muted-foreground",children:r.note})]})}function Xir(){const s=Vt(),[t,n]=j.useState(""),[r,a]=j.useState(!1),[i,l]=j.useState(0),[o,c]=j.useState(null),{data:d,isLoading:u}=tt({queryKey:["boomtown-status"],queryFn:async()=>{const{data:x,error:y}=await q.functions.invoke("boomtown-sync",{body:{action:"status"}});if(y)throw y;return x}}),h=ft({mutationFn:async x=>{const{data:y,error:v}=await q.functions.invoke("boomtown-sync",{body:{action:"save_token",api_key:x}});if(v)throw v;if(y!=null&&y.error)throw new Error(y.error);return y},onSuccess:()=>{re.success("Connected to Boomtown"),n(""),s.invalidateQueries({queryKey:["boomtown-status"]})},onError:x=>re.error(x.message)}),m=ft({mutationFn:async()=>{const{error:x}=await q.functions.invoke("boomtown-sync",{body:{action:"disconnect"}});if(x)throw x},onSuccess:()=>{re.success("Disconnected"),s.invalidateQueries({queryKey:["boomtown-status"]})}}),f=ft({mutationFn:async x=>{const{error:y}=await q.functions.invoke("boomtown-sync",{body:{action:"set_direction",sync_direction:x}});if(y)throw y},onSuccess:()=>s.invalidateQueries({queryKey:["boomtown-status"]})}),g=async()=>{a(!0),l(0),c("Pulling from Boomtown…");let x=0,y=0,v=0,b=0;try{for(;;){const{data:E,error:I}=await q.functions.invoke("boomtown-sync",{body:{action:"sync",offset:x}});if(I)throw I;if(E!=null&&E.error)throw new Error(E.error);y+=E.chunk_created||0,v+=E.chunk_updated||0,b+=E.chunk_skipped||0,x=E.next_offset;const P=E.total?Math.min(100,Math.round(x/E.total*100)):100;if(l(P),c(`Pulling · ${x} / ${E.total||"?"}`),E.done)break;await new Promise(R=>setTimeout(R,400))}let w=0,S=0;if((d==null?void 0:d.sync_direction)==="bidirectional"){let E=0;for(l(0),c("Pushing to Boomtown…");;){const{data:I,error:P}=await q.functions.invoke("boomtown-sync",{body:{action:"push",offset:E}});if(P)throw P;if(I!=null&&I.error)throw new Error(I.error);w+=I.chunk_pushed||0,S+=I.chunk_failed||0,E=I.next_offset;const R=I.total?Math.min(100,Math.round(E/I.total*100)):100;if(l(R),c(`Pushing · ${E} / ${I.total||"?"}`),I.done)break;await new Promise(D=>setTimeout(D,400))}}const C=w||S?` · pushed ${w}${S?`, ${S} failed`:""}`:"";re.success(`Sync complete · ${y} new, ${v} updated${b?`, ${b} skipped`:""}${C}`),s.invalidateQueries({queryKey:["boomtown-status"]})}catch(w){re.error(w.message||"Sync failed")}finally{a(!1),setTimeout(()=>{l(0),c(null)},2500)}};return e.jsxs(Ne,{children:[e.jsx(Ct,{children:e.jsx("div",{className:"flex items-start justify-between gap-3",children:e.jsxs("div",{children:[e.jsxs(At,{className:"flex items-center gap-2",children:[e.jsx(g2,{className:"h-5 w-5 text-primary"}),"Boomtown",(d==null?void 0:d.connected)&&e.jsxs(Be,{variant:"default",className:"ml-1",children:[e.jsx(Nc,{className:"h-3 w-3 mr-1"})," Connected"]})]}),e.jsx(Gn,{children:"Sync your Boomtown contacts into Agent OS."})]})})}),e.jsx(Ie,{className:"space-y-4",children:u?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:"Boomtown contacts"}),e.jsx("p",{className:"font-medium",children:d.boomtown_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 Boomtown only. On = also push new Agent OS contacts to Boomtown."})]}),e.jsx(Sn,{checked:d.sync_direction==="bidirectional",onCheckedChange:x=>f.mutate(x?"bidirectional":"pull_only"),disabled:r||f.isPending})]}),o&&e.jsxs("div",{className:"space-y-1",children:[e.jsx(Yi,{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($,{onClick:g,disabled:r,children:[e.jsx(ro,{className:`h-4 w-4 mr-2 ${r?"animate-spin":""}`}),r?"Syncing…":"Sync Now"]}),e.jsxs(kc,{children:[e.jsx(jx,{asChild:!0,children:e.jsxs($,{variant:"outline",disabled:r,children:[e.jsx(Wn,{className:"h-4 w-4 mr-2"})," Disconnect"]})}),e.jsxs(cc,{children:[e.jsxs(dc,{children:[e.jsx(hc,{children:"Disconnect Boomtown?"}),e.jsx(mc,{children:"Your API key will be removed. Synced contacts stay in Agent OS."})]}),e.jsxs(uc,{children:[e.jsx(fc,{children:"Cancel"}),e.jsx(tc,{onClick:()=>m.mutate(),children:"Disconnect"})]})]})]})]})]}):e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"boomtown-key",children:"Boomtown API Key"}),e.jsx(pe,{id:"boomtown-key",type:"password",placeholder:"Paste your Boomtown Ambassador API key",value:t,onChange:x=>n(x.target.value)}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Requires a Boomtown Ambassador/Partner API key with contact access."})]}),e.jsxs("div",{className:"rounded-lg border bg-muted/40 p-3 space-y-2",children:[e.jsx("p",{className:"text-sm font-medium",children:"How to get your API key"}),e.jsxs("ol",{className:"text-xs text-muted-foreground space-y-1 list-decimal list-inside",children:[e.jsx("li",{children:"Log in to Boomtown as an admin or manager."}),e.jsxs("li",{children:["Go to ",e.jsx("strong",{children:"Settings → Integrations → API Keys"}),"."]}),e.jsxs("li",{children:["Generate a key with ",e.jsx("strong",{children:"Contact read/write"})," scope."]}),e.jsx("li",{children:"Copy the key and paste it above, then click Connect."})]}),e.jsxs("a",{href:"https://backoffice.boomtownroi.com/#/settings/integrations",target:"_blank",rel:"noreferrer",className:"inline-flex items-center gap-1 text-xs text-primary hover:underline",children:["Open Boomtown settings ",e.jsx(kr,{className:"h-3 w-3"})]})]}),e.jsx($,{onClick:()=>h.mutate(t),disabled:!t.trim()||h.isPending,children:h.isPending?"Connecting…":"Connect"})]})})]})}function yos(){const s=Qn(),[t,n]=j.useState(""),[r,a]=j.useState(""),[i,l]=j.useState("Test from ReLevelUp"),[o,c]=j.useState(!1),{data:d,isLoading:u}=tt({queryKey:["ses-config"],queryFn:async()=>{const f=await gne();return(await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/ses-send-campaign",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${f}`},body:JSON.stringify({action:"check_config"})})).json()}}),h=async()=>{if(!t||!r){re.error("Please fill in From and To email addresses");return}c(!0);try{const f=await gne(),x=await(await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/ses-send-campaign",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${f}`},body:JSON.stringify({action:"test_send",to:t,from_email:r,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();x.success?re.success(`Test email sent! Message ID: ${x.messageId}`):re.error(x.error||"Failed to send test email")}catch(f){re.error(f.message||"Failed to send test email")}finally{c(!1)}},m=(d==null?void 0:d.configured)===!0;return e.jsxs(Ne,{children:[e.jsx(Ct,{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(mn,{className:"h-5 w-5 text-orange-600"})}),e.jsxs("div",{children:[e.jsx(At,{className:"text-lg",children:"Amazon SES — Mass Email"}),e.jsx(Gn,{children:"Send bulk email campaigns via Amazon SES"})]})]}),e.jsx(Be,{variant:m?"default":"secondary",children:u?"Checking...":m?e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Nc,{className:"h-3 w-3"})," Connected"]}):e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(ll,{className:"h-3 w-3"})," Not Configured"]})})]})}),m&&e.jsxs(Ie,{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(ee,{className:"text-xs",children:"From Email"}),e.jsx(pe,{placeholder:"notifications@mail.relevelup.com",value:r,onChange:f=>a(f.target.value),className:"text-sm"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(ee,{className:"text-xs",children:"To Email"}),e.jsx(pe,{placeholder:"your@email.com",value:t,onChange:f=>n(f.target.value),className:"text-sm"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(ee,{className:"text-xs",children:"Subject"}),e.jsx(pe,{value:i,onChange:f=>l(f.target.value),className:"text-sm"})]})]}),e.jsxs($,{onClick:h,disabled:o,size:"sm",children:[o?e.jsx(kt,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Yr,{className:"h-4 w-4 mr-2"}),"Send Test"]})]}),e.jsxs($,{onClick:()=>s("/admin/email-campaigns"),className:"w-full",children:[e.jsx(xm,{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)"]})]})]}),!m&&!u&&e.jsx(Ie,{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 gUe(s){const t=await gne(),n=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/ses-verify-sender",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(s)}),r=await n.json();if(!n.ok)throw new Error(r.error||"Request failed");return r}function Qir({status:s}){return s==="verified"?e.jsxs(Be,{className:"bg-green-500/10 text-green-700 hover:bg-green-500/20 border-green-500/20",children:[e.jsx(qr,{className:"h-3 w-3 mr-1"})," Verified"]}):s==="pending"?e.jsxs(Be,{variant:"secondary",children:[e.jsx(da,{className:"h-3 w-3 mr-1"})," Pending — check inbox"]}):s==="failed"||s==="temporary_failure"?e.jsxs(Be,{variant:"destructive",children:[e.jsx(ll,{className:"h-3 w-3 mr-1"})," Failed"]}):e.jsxs(Be,{variant:"outline",children:[e.jsx(ll,{className:"h-3 w-3 mr-1"})," Not started"]})}function vos({brokerageId:s,onVerifiedSelect:t}){const n=Vt(),[r,a]=j.useState(""),[i,l]=j.useState(""),[o,c]=j.useState(!1),[d,u]=j.useState(null),[h,m]=j.useState(null),{data:f,isLoading:g}=tt({queryKey:["brokerage-verified-senders",s],queryFn:async()=>{const{data:b,error:w}=await q.from("brokerage_verified_senders").select("*").eq("brokerage_id",s).order("created_at",{ascending:!1});if(w)throw w;return b||[]}}),x=ft({mutationFn:async()=>gUe({action:"request_verification",brokerage_id:s,email:r,display_name:i||void 0}),onSuccess:()=>{n.invalidateQueries({queryKey:["brokerage-verified-senders",s]}),re.success("Verification email sent",{description:`Check ${r} and click the AWS verification link.`}),a(""),l(""),c(!1)},onError:b=>re.error(b.message)}),y=async b=>{var w,S;u(b.id);try{const C=await gUe({action:"check_status",sender_id:b.id});n.invalidateQueries({queryKey:["brokerage-verified-senders",s]}),((w=C.sender)==null?void 0:w.status)==="verified"?re.success(`${b.email} is verified! 🎉`):re.info(`Status: ${((S=C.sender)==null?void 0:S.status)||"unknown"}`)}catch(C){re.error(C.message)}finally{u(null)}},v=ft({mutationFn:async b=>gUe({action:"delete",sender_id:b}),onSuccess:()=>{n.invalidateQueries({queryKey:["brokerage-verified-senders",s]}),re.success("Sender removed"),m(null)},onError:b=>re.error(b.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."})]}),g?e.jsx("div",{className:"text-xs text-muted-foreground py-3",children:"Loading…"}):f&&f.length>0?e.jsx("div",{className:"space-y-2",children:f.map(b=>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(mn,{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:b.email}),e.jsx(Qir,{status:b.status})]}),b.display_name&&e.jsxs("p",{className:"text-xs text-muted-foreground truncate",children:['"',b.display_name,'"']})]})]}),e.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[b.status==="verified"&&t&&e.jsx($,{size:"sm",variant:"outline",onClick:()=>t(b.email),children:"Use"}),b.status!=="verified"&&e.jsx($,{size:"sm",variant:"ghost",onClick:()=>y(b),disabled:d===b.id,title:"Refresh status from AWS",children:d===b.id?e.jsx(kt,{className:"h-4 w-4 animate-spin"}):e.jsx(ro,{className:"h-4 w-4"})}),e.jsx($,{size:"sm",variant:"ghost",onClick:()=>m(b),className:"text-destructive hover:text-destructive",children:e.jsx(Wn,{className:"h-4 w-4"})})]})]},b.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(ee,{className:"text-xs",children:"Email Address *"}),e.jsx(pe,{type:"email",value:r,onChange:b=>a(b.target.value),placeholder:"broker@yourbrokerage.com",className:"text-sm"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(ee,{className:"text-xs",children:"Display Name (optional)"}),e.jsx(pe,{value:i,onChange:b=>l(b.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($,{size:"sm",onClick:()=>x.mutate(),disabled:!r.trim()||x.isPending,children:[x.isPending?e.jsx(kt,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(mn,{className:"h-4 w-4 mr-2"}),"Send Verification Email"]}),e.jsx($,{size:"sm",variant:"ghost",onClick:()=>{c(!1),a(""),l("")},children:"Cancel"})]})]}):e.jsxs($,{size:"sm",variant:"outline",onClick:()=>c(!0),children:[e.jsx(dn,{className:"h-4 w-4 mr-1"})," Add Sender Address"]}),e.jsx(kc,{open:!!h,onOpenChange:b=>!b&&m(null),children:e.jsxs(cc,{children:[e.jsxs(dc,{children:[e.jsx(hc,{children:"Remove this sender?"}),e.jsxs(mc,{children:['"',h==null?void 0:h.email,`" will be removed from your verified senders and from Amazon SES. You'd need to verify it again to use it.`]})]}),e.jsxs(uc,{children:[e.jsx(fc,{children:"Cancel"}),e.jsx(tc,{onClick:()=>h&&v.mutate(h.id),className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Remove"})]})]})})]})}async function xUe(s){const t=await gne(),n=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/ses-verify-sender",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(s)}),r=await n.json();if(!n.ok)throw new Error(r.error||"Request failed");return r}function Jir({status:s}){return s==="verified"?e.jsxs(Be,{className:"bg-green-500/10 text-green-700 hover:bg-green-500/20 border-green-500/20",children:[e.jsx(qr,{className:"h-3 w-3 mr-1"})," Verified"]}):s==="pending"?e.jsxs(Be,{variant:"secondary",children:[e.jsx(da,{className:"h-3 w-3 mr-1"})," Pending — check inbox"]}):s==="failed"||s==="temporary_failure"?e.jsxs(Be,{variant:"destructive",children:[e.jsx(ll,{className:"h-3 w-3 mr-1"})," Failed"]}):e.jsxs(Be,{variant:"outline",children:[e.jsx(ll,{className:"h-3 w-3 mr-1"})," Not started"]})}function eor({userId:s,onVerifiedSelect:t}){const n=Vt(),[r,a]=j.useState(""),[i,l]=j.useState(""),[o,c]=j.useState(!1),[d,u]=j.useState(null),[h,m]=j.useState(null),{data:f,isLoading:g}=tt({queryKey:["user-verified-senders",s],queryFn:async()=>{const{data:b,error:w}=await q.from("user_verified_senders").select("*").eq("user_id",s).order("created_at",{ascending:!1});if(w)throw w;return b||[]}}),x=ft({mutationFn:async()=>xUe({action:"request_verification",scope:"user",email:r,display_name:i||void 0}),onSuccess:b=>{n.invalidateQueries({queryKey:["user-verified-senders",s]}),re.success("Verification email sent",{description:`Check ${r} and click the AWS verification link.`}),b!=null&&b.domain_warning&&re.warning("Heads up about this address",{description:b.domain_warning,duration:15e3}),a(""),l(""),c(!1)},onError:b=>re.error(b.message)}),y=async b=>{var w,S;u(b.id);try{const C=await xUe({action:"check_status",sender_id:b.id});n.invalidateQueries({queryKey:["user-verified-senders",s]}),((w=C.sender)==null?void 0:w.status)==="verified"?re.success(`${b.email} is verified! 🎉`):re.info(`Status: ${((S=C.sender)==null?void 0:S.status)||"unknown"}`)}catch(C){re.error(C.message)}finally{u(null)}},v=ft({mutationFn:async b=>xUe({action:"delete",sender_id:b}),onSuccess:()=>{n.invalidateQueries({queryKey:["user-verified-senders",s]}),re.success("Sender removed"),m(null)},onError:b=>re.error(b.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."]})]}),g?e.jsx("div",{className:"text-xs text-muted-foreground py-3",children:"Loading…"}):f&&f.length>0?e.jsx("div",{className:"space-y-2",children:f.map(b=>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(mn,{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:b.email}),e.jsx(Jir,{status:b.status})]}),b.display_name&&e.jsxs("p",{className:"text-xs text-muted-foreground truncate",children:['"',b.display_name,'"']})]})]}),e.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[b.status==="verified"&&t&&e.jsx($,{size:"sm",variant:"outline",onClick:()=>t(b.email),children:"Use"}),b.status!=="verified"&&e.jsx($,{size:"sm",variant:"ghost",onClick:()=>y(b),disabled:d===b.id,title:"Refresh status from AWS",children:d===b.id?e.jsx(kt,{className:"h-4 w-4 animate-spin"}):e.jsx(ro,{className:"h-4 w-4"})}),e.jsx($,{size:"sm",variant:"ghost",onClick:()=>m(b),className:"text-destructive hover:text-destructive",children:e.jsx(Wn,{className:"h-4 w-4"})})]})]},b.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(ee,{className:"text-xs",children:"Email Address *"}),e.jsx(pe,{type:"email",value:r,onChange:b=>a(b.target.value),placeholder:"you@yourdomain.com",className:"text-sm"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(ee,{className:"text-xs",children:"Display Name (optional)"}),e.jsx(pe,{value:i,onChange:b=>l(b.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($,{size:"sm",onClick:()=>x.mutate(),disabled:!r.trim()||x.isPending,children:[x.isPending?e.jsx(kt,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(mn,{className:"h-4 w-4 mr-2"}),"Send Verification Email"]}),e.jsx($,{size:"sm",variant:"ghost",onClick:()=>{c(!1),a(""),l("")},children:"Cancel"})]})]}):e.jsxs($,{size:"sm",variant:"outline",onClick:()=>c(!0),children:[e.jsx(dn,{className:"h-4 w-4 mr-1"})," Add Sender Address"]}),e.jsx(kc,{open:!!h,onOpenChange:b=>!b&&m(null),children:e.jsxs(cc,{children:[e.jsxs(dc,{children:[e.jsx(hc,{children:"Remove this sender?"}),e.jsxs(mc,{children:['"',h==null?void 0:h.email,`" will be removed from your verified senders and from Amazon. You'd need to verify it again to use it.`]})]}),e.jsxs(uc,{children:[e.jsx(fc,{children:"Cancel"}),e.jsx(tc,{onClick:()=>h&&v.mutate(h.id),className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Remove"})]})]})})]})}function tor(){var S,C,E,I,P;const{user:s,isBrokerageManager:t,isAdmin:n,managedBrokerages:r,selectedBrokerageId:a}=vs(),i=a||((S=r==null?void 0:r[0])==null?void 0:S.id)||null,l=(t||n)&&!!i,o=Vt(),[c,d]=j.useState(!1),[u,h]=j.useState(""),[m,f]=j.useState(""),{data:g}=tt({queryKey:["mass-email-settings",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:R,error:D}=await q.from("mass_email_settings").select("*").eq("user_id",s.id).maybeSingle();if(D)throw D;return R}}),{data:x}=tt({queryKey:["agent-profile-email",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:R,error:D}=await q.from("profiles").select("email, name").eq("id",s.id).single();if(D)throw D;return R}}),y=((C=g==null?void 0:g.reply_to_email)==null?void 0:C.trim())||((E=x==null?void 0:x.email)==null?void 0:E.trim())||"",v=((I=g==null?void 0:g.display_name)==null?void 0:I.trim())||((P=x==null?void 0:x.name)==null?void 0:P.trim())||"";j.useEffect(()=>{c||(h(y),f(v))},[c,y,v]);const b=ft({mutationFn:async()=>{if(!s||!u.trim())throw new Error("Please enter a reply-to email");const R={reply_to_email:u.trim(),display_name:m.trim()||null,updated_at:new Date().toISOString()};if(g){const{error:D}=await q.from("mass_email_settings").update(R).eq("user_id",s.id);if(D)throw D}else{const{error:D}=await q.from("mass_email_settings").insert({user_id:s.id,...R});if(D)throw D}},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]}),re.success("Reply-to email saved!"),d(!1)},onError:R=>re.error(R.message)}),w=!!y;return e.jsxs(Ne,{children:[e.jsx(Ct,{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(Yr,{className:"h-5 w-5 text-orange-600"})}),e.jsxs("div",{children:[e.jsxs(At,{className:"text-lg flex items-center gap-2",children:["Mass Email",w?e.jsxs(Be,{variant:"default",className:"text-xs bg-green-600",children:[e.jsx(Nc,{className:"h-3 w-3 mr-1"})," Set Up"]}):e.jsx(Be,{variant:"secondary",className:"text-xs",children:"Setup Required"})]}),e.jsx(Gn,{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(Ie,{className:"space-y-3",children:[w&&!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:v||"No display name"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:y})]}),e.jsxs($,{variant:"ghost",size:"sm",onClick:()=>d(!0),children:[e.jsx(gi,{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(ee,{className:"text-xs",children:"Display Name"}),e.jsx(pe,{placeholder:"e.g. 🏡 Karen Hall",value:m,onChange:R=>f(R.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(ee,{className:"text-xs",children:"Reply-To Email *"}),e.jsx(pe,{type:"email",placeholder:"your@email.com",value:u,onChange:R=>h(R.target.value)})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs($,{size:"sm",onClick:()=>b.mutate(),disabled:b.isPending||!u.trim(),children:[e.jsx(tl,{className:"h-4 w-4 mr-1"})," Save"]}),c&&e.jsxs($,{size:"sm",variant:"outline",onClick:()=>{d(!1),h(y),f(v)},children:[e.jsx(gr,{className:"h-4 w-4 mr-1"})," Cancel"]})]})]}),s&&e.jsxs(e.Fragment,{children:[e.jsx(Gc,{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(bm,{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(eor,{userId:s.id,onVerifiedSelect:R=>{h(R),d(!0)}})]})]}),l&&e.jsxs(e.Fragment,{children:[e.jsx(Gc,{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(bm,{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(vos,{brokerageId:i})]})]})]})]})}function bos(){var f,g,x,y,v,b;const{user:s,isAdmin:t}=vs(),n=Vt(),r=wrt(),a=rGt(),i=aGt(),[l,o]=j.useState(!1),c=!!((f=r.data)!=null&&f.connected),d=tt({queryKey:["canva-imports",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:w,error:S}=await q.from("canva_imports").select("id, workflow, design_title, format, pages, bucket, storage_paths, created_at").order("created_at",{ascending:!1}).limit(24);if(S)throw S;return w||[]}}),u=tt({queryKey:["canva-import-thumbs",(g=d.data)==null?void 0:g.map(w=>w.id).join()],enabled:!!((x=d.data)!=null&&x.length),queryFn:async()=>{const w={};return await Promise.all((d.data||[]).map(async S=>{if(S.format==="pdf"||!S.storage_paths[0]){w[S.id]=null;return}const{data:C}=await q.storage.from(S.bucket).createSignedUrl(S.storage_paths[0],3600,{transform:{width:400,resize:"contain"}});w[S.id]=(C==null?void 0:C.signedUrl)??null})),w}}),h=async w=>{for(const S of w.storage_paths){const{data:C}=await q.storage.from(w.bucket).createSignedUrl(S,300,{download:!0});C!=null&&C.signedUrl&&window.open(C.signedUrl,"_blank","noopener")}},m=ft({mutationFn:async w=>{w.workflow==="library"&&await q.storage.from(w.bucket).remove(w.storage_paths);const{error:S}=await q.from("canva_imports").delete().eq("id",w.id);if(S)throw S},onSuccess:()=>{n.invalidateQueries({queryKey:["canva-imports"]}),re.success("Removed from your Canva library")},onError:()=>re.error("Couldn't remove that design")});return e.jsxs("div",{className:"space-y-4",children:[e.jsxs(Ne,{className:"border-primary/25 shadow-sm",children:[e.jsxs(Ct,{children:[e.jsxs(At,{className:"flex items-center gap-2 font-display text-xl",children:[e.jsx(Yc,{className:"h-5 w-5 text-primary"}),"Canva"]}),e.jsx(Gn,{children:"Connect your own Canva account to bring finished designs into LevelUp. LevelUp can only view and export your designs — it can't change or delete anything in Canva. Editing happens in Canva."})]}),e.jsx(Ie,{className:"space-y-3",children:r.isLoading?e.jsx(kt,{className:"h-5 w-5 animate-spin"}):r.data&&!r.data.configured?e.jsx("p",{className:"text-sm text-muted-foreground",children:"Canva isn't set up for LevelUp yet. An admin needs to finish the Canva app setup."}):c?e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs(Be,{variant:"secondary",children:["Connected",(y=r.data)!=null&&y.display_name?` as ${r.data.display_name}`:""]}),e.jsxs($,{size:"sm",onClick:()=>o(!0),children:[e.jsx(di,{className:"mr-1.5 h-4 w-4"}),"Import from Canva"]}),e.jsx($,{size:"sm",variant:"outline",asChild:!0,children:e.jsxs("a",{href:"https://www.canva.com/",target:"_blank",rel:"noreferrer",children:[e.jsx(kr,{className:"mr-1.5 h-4 w-4"}),"Design with Canva"]})}),t&&e.jsx($,{size:"sm",variant:"outline",asChild:!0,children:e.jsxs(wr,{to:"/mission-control/direct-mail",children:[e.jsx(mn,{className:"mr-1.5 h-4 w-4"}),"Mail Studio"]})}),t&&e.jsxs($,{size:"sm",variant:"outline",onClick:()=>a.mutate({client:"public"}),disabled:a.isPending,title:"Try the new Canva app connection — replaces only your own connection if you approve it",children:[a.isPending?e.jsx(kt,{className:"mr-1.5 h-4 w-4 animate-spin"}):e.jsx(I4,{className:"mr-1.5 h-4 w-4"}),"Test public Canva app"]}),e.jsxs($,{size:"sm",variant:"ghost",className:"text-destructive",onClick:()=>i.mutate(),disabled:i.isPending,children:[e.jsx($E,{className:"mr-1.5 h-4 w-4"}),"Disconnect"]})]}):e.jsxs("div",{className:"space-y-2",children:[((v=r.data)==null?void 0:v.needs_reconnect)&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"Your Canva connection needs to be renewed."}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs($,{onClick:()=>a.mutate({}),disabled:a.isPending,children:[a.isPending?e.jsx(kt,{className:"mr-1.5 h-4 w-4 animate-spin"}):e.jsx(bd,{className:"mr-1.5 h-4 w-4"}),"Connect Canva"]}),t&&e.jsxs($,{variant:"outline",onClick:()=>a.mutate({client:"public"}),disabled:a.isPending,children:[a.isPending?e.jsx(kt,{className:"mr-1.5 h-4 w-4 animate-spin"}):e.jsx(I4,{className:"mr-1.5 h-4 w-4"}),"Test public Canva app"]})]}),t&&e.jsx("p",{className:"text-xs text-muted-foreground",children:'Admins: "Test public Canva app" tries the new Canva app connection without affecting your current one.'})]})})]}),!!((b=d.data)!=null&&b.length)&&e.jsxs(Ne,{children:[e.jsxs(Ct,{children:[e.jsx(At,{className:"text-base",children:"Designs saved from Canva"}),e.jsx(Gn,{children:"Permanent copies kept in LevelUp, even if you later change or delete them in Canva."})]}),e.jsx(Ie,{className:"grid gap-3 sm:grid-cols-3",children:d.data.map(w=>{var S;return e.jsxs("div",{className:"overflow-hidden rounded-lg border",children:[(S=u.data)!=null&&S[w.id]?e.jsx("img",{src:u.data[w.id],alt:w.design_title||"Canva design",className:"h-28 w-full bg-muted object-contain"}):e.jsx("div",{className:"flex h-28 w-full items-center justify-center bg-muted text-xs uppercase text-muted-foreground",children:w.format}),e.jsxs("div",{className:"space-y-1 p-2",children:[e.jsx("p",{className:"truncate text-xs font-medium",children:w.design_title||"Untitled design"}),e.jsxs("p",{className:"text-[11px] text-muted-foreground",children:[w.workflow==="mail_studio"?"Mail Studio":"Library"," · ",w.pages.length," page",w.pages.length===1?"":"s"]}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx($,{size:"sm",variant:"ghost",className:"h-7 px-2",onClick:()=>h(w),children:e.jsx(di,{className:"h-3.5 w-3.5"})}),e.jsx($,{size:"sm",variant:"ghost",className:"h-7 px-2 text-destructive",onClick:()=>m.mutate(w),disabled:m.isPending,children:e.jsx(Wn,{className:"h-3.5 w-3.5"})})]})]})]},w.id)})})]}),e.jsx(iGt,{open:l,onOpenChange:o,mode:"library",workflow:"library",onImported:w=>{re.success(`Saved ${w.files.length} page${w.files.length===1?"":"s"} to LevelUp`)}})]})}function sor({authUserId:s,actingAsUserId:t}){const n=s??null,r=t??null,a=!!r&&!!n&&r!==n,i=a?r:n;return{scopeUserId:i,isDelegated:a,canViewConnections:!!i&&!a,canManageConnections:!!i&&!a}}const nor=[{id:"all",label:"All tools",icon:Qf},{id:"crm",label:"Real estate CRMs",icon:v0},{id:"social",label:"Social media",icon:zd},{id:"communication",label:"Communication",icon:mn},{id:"marketing",label:"AI & marketing",icon:Nn}],ror={gmail:"Gmail","mass-email":"Mass Email",facebook:"Facebook",instagram:"Instagram",linkedin:"LinkedIn","google-business":"Google Business",boldtrail:"BoldTrail",lofty:"Lofty",followupboss:"Follow Up Boss",cloze:"Cloze",boomtown:"BoomTown",chatgpt:"ChatGPT",canva:"Canva",ses:"Amazon SES"};function aor({connected:s,label:t}){return s?e.jsxs(Be,{className:"border-0 bg-success/10 text-success hover:bg-success/10",children:[e.jsx("span",{className:"mr-1.5 h-1.5 w-1.5 rounded-full bg-success"}),"Connected"]}):e.jsx(Be,{variant:"outline",className:"text-muted-foreground",children:t||"Available"})}function aw({title:s,description:t,icon:n,connected:r,statusLabel:a,selected:i,onClick:l,badge:o}){return e.jsxs("button",{type:"button",onClick:l,className:`group flex min-h-36 w-full flex-col justify-between rounded-lg border bg-card p-4 text-left shadow-sm transition-[border-color,box-shadow,transform] duration-200 hover:-translate-y-0.5 hover:border-primary/45 hover:shadow-md focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring ${i?"border-primary ring-1 ring-primary/20":"border-border"}`,children:[e.jsxs("div",{className:"flex w-full items-start justify-between gap-3",children:[e.jsx("div",{className:"flex h-10 w-10 items-center justify-center rounded-md bg-primary/10 text-primary",children:n}),e.jsxs("div",{className:"flex flex-wrap justify-end gap-1.5",children:[o&&e.jsx(Be,{variant:"secondary",className:"text-[10px] uppercase",children:o}),e.jsx(aor,{connected:r,label:a})]})]}),e.jsxs("div",{className:"mt-5",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("h3",{className:"font-display text-base font-semibold text-foreground",children:s}),e.jsx(Di,{className:"h-4 w-4 text-muted-foreground transition-transform duration-200 group-hover:translate-x-0.5 group-hover:text-primary"})]}),e.jsx("p",{className:"mt-1 line-clamp-2 text-sm leading-5 text-muted-foreground",children:t})]})]})}function ior(){const s=Qn(),{isAdmin:t,user:n}=vs(),{actingAsAgent:r,effectiveUserId:a}=Iae(),i=Vt(),[l,o]=j.useState(!1),[c,d]=j.useState(!1),[u,h]=j.useState(!1),[m,f]=j.useState(!1),[g,x]=j.useState("all"),[y,v]=j.useState(null),{data:b}=wrt(),{scopeUserId:w,isDelegated:S}=sor({authUserId:n==null?void 0:n.id,actingAsUserId:(r==null?void 0:r.id)??a}),{data:C,isLoading:E}=tt({queryKey:["gmail-integration",w],enabled:!!w&&!S,queryFn:async()=>{const{data:je,error:Ae}=await q.from("gmail_integrations").select("*").eq("user_id",w).maybeSingle();if(Ae)throw Ae;return je}}),{data:I}=tt({queryKey:["social-accounts",w],enabled:!!w&&!S,queryFn:async()=>{const{data:je,error:Ae}=await q.from("social_accounts").select("*").eq("user_id",w).order("created_at",{ascending:!1});if(Ae)throw Ae;return je}}),{data:P}=tt({queryKey:["google-business-status",w],enabled:!!w&&!S,queryFn:async()=>{const{data:je,error:Ae}=await q.functions.invoke("google-business-oauth",{body:{action:"get_status"}});if(Ae)throw Ae;return je}}),R=ft({mutationFn:async je=>{const{error:Ae}=await q.functions.invoke("google-business-oauth",{body:{action:"set_primary_location",locationId:je}});if(Ae)throw Ae},onSuccess:()=>{re.success("Business updated"),i.invalidateQueries({queryKey:["google-business-status",w]}),i.invalidateQueries({queryKey:["social-accounts",w]})},onError:()=>re.error("Could not update your business selection")}),D=ft({mutationFn:async()=>{const{error:je}=await q.functions.invoke("google-business-oauth",{body:{action:"disconnect"}});if(je)throw je},onSuccess:()=>{i.invalidateQueries({queryKey:["google-business-status",w]}),i.invalidateQueries({queryKey:["social-accounts",w]}),re.success("Google Business disconnected")},onError:()=>re.error("Could not disconnect Google Business")}),O=ft({mutationFn:async()=>{const{data:je,error:Ae}=await q.functions.invoke("google-business-oauth",{body:{action:"rescan_locations"}});if(Ae)throw Ae;return je},onSuccess:je=>{i.invalidateQueries({queryKey:["google-business-status",w]}),je!=null&&je.success&&je.locationsCount?re.success(je.message??"Locations updated"):re.error((je==null?void 0:je.message)??"No business locations were found on this Google account.")},onError:()=>re.error("Could not check Google for your business")}),U=async()=>{if(S){re.error("Account connections must be made by the agent from their own login.");return}f(!0);try{const{data:je,error:Ae}=await q.functions.invoke("google-business-oauth",{body:{action:"get_auth_url",returnPath:"/mission-control/integrations"}});if(Ae)throw Ae;if(je!=null&&je.authUrl)window.location.href=je.authUrl;else throw new Error("Failed to get Google authorization URL")}catch(je){console.error("Google Business OAuth error:",je),re.error("Failed to start Google connection. Please try again."),f(!1)}},W=async()=>{if(S){re.error("Account connections must be made by the agent from their own login.");return}o(!0);try{const{data:je,error:Ae}=await q.functions.invoke("gmail-oauth",{body:{action:"get_auth_url"}});if(Ae)throw Ae;if(je!=null&&je.authUrl)window.location.href=je.authUrl;else throw new Error("Failed to get authorization URL")}catch(je){console.error("Gmail OAuth error:",je),re.error("Failed to start Gmail connection"),o(!1)}},V=async je=>{if(S){re.error("Account connections must be made by the agent from their own login.");return}d(!0);try{sessionStorage.setItem("social-connect-return-to",window.location.pathname);const{data:Ae,error:Ce}=await q.functions.invoke("meta-oauth",{body:{action:"get_auth_url",callbackPath:"/social-connections/callback",authMode:je}});if(Ce)throw Ce;if(Ae!=null&&Ae.authUrl)window.location.href=Ae.authUrl;else throw new Error("Failed to get authorization URL")}catch(Ae){console.error("Meta OAuth error:",Ae),re.error("Failed to start connection. Make sure Meta App credentials are configured."),d(!1)}},G=async()=>{if(S){re.error("Account connections must be made by the agent from their own login.");return}h(!0);try{const{data:je,error:Ae}=await q.functions.invoke("linkedin-oauth",{body:{action:"get_auth_url",callbackPath:"/social-connections/linkedin-callback"}});if(Ae)throw Ae;if(je!=null&&je.authUrl)window.location.href=je.authUrl;else throw new Error("Failed to get LinkedIn authorization URL")}catch(je){console.error("LinkedIn OAuth error:",je),re.error("Failed to start LinkedIn connection. Please try again."),h(!1)}},Y=ft({mutationFn:async je=>{const{error:Ae}=await q.from("gmail_integrations").delete().eq("id",je).eq("user_id",w);if(Ae)throw Ae},onSuccess:()=>{i.invalidateQueries({queryKey:["gmail-integration",w]}),re.success("Gmail disconnected")},onError:()=>{re.error("Failed to disconnect Gmail")}}),X=ft({mutationFn:async je=>{const{error:Ae}=await q.from("social_accounts").delete().eq("id",je).eq("user_id",w);if(Ae)throw Ae},onSuccess:()=>{i.invalidateQueries({queryKey:["social-accounts",w]}),re.success("Account disconnected")},onError:()=>{re.error("Failed to disconnect account")}}),ae=!S&&!!(C!=null&&C.is_active),ie=(I==null?void 0:I.filter(je=>je.platform==="facebook"))||[],ne=(I==null?void 0:I.filter(je=>je.platform==="instagram"))||[],te=(I==null?void 0:I.filter(je=>je.platform==="linkedin"))||[],J=(I==null?void 0:I.filter(je=>je.platform==="google_business"))||[],{data:ce}=tt({queryKey:["mass-email-settings",n==null?void 0:n.id],enabled:!!(n!=null&&n.id),queryFn:async()=>{const{data:je,error:Ae}=await q.from("mass_email_settings").select("reply_to_email").eq("user_id",n==null?void 0:n.id).maybeSingle();if(Ae)throw Ae;return je}}),_e=(je,Ae)=>({queryKey:[je],queryFn:async()=>{const{data:Ce,error:qe}=await q.functions.invoke(Ae,{body:{action:"status"}});if(qe)throw qe;return Ce},staleTime:6e4}),{data:he}=tt(_e("boldtrail-status","boldtrail-sync")),{data:ue}=tt(_e("lofty-status","lofty-sync")),{data:ve}=tt(_e("fub-status","followupboss-sync")),{data:Ee}=tt(_e("cloze-status","cloze-sync")),{data:Se}=tt(_e("boomtown-status","boomtown-sync")),Le=[ae,!!(ce!=null&&ce.reply_to_email),ie.length>0,ne.length>0,te.length>0,!!(he!=null&&he.connected),!!(ue!=null&&ue.connected),!!(ve!=null&&ve.connected),!!(Ee!=null&&Ee.connected),!!(Se!=null&&Se.connected)].filter(Boolean).length,Fe=je=>{v(Ae=>Ae===je?null:je)},ke=je=>{const Ae=je==="facebook"?ie:je==="instagram"?ne:te,Ce=je==="facebook"?Qp:je==="instagram"?Tf:hy,qe=je==="facebook"?"Facebook":je==="instagram"?"Instagram":"LinkedIn",ze=je==="linkedin"?G:()=>V(je),$e=je==="linkedin"?u:c;return e.jsxs(Ne,{className:"border-primary/25 shadow-sm",children:[e.jsxs(Ct,{children:[e.jsxs(At,{className:"font-display text-xl",children:["Manage ",qe]}),e.jsx(Gn,{children:je==="instagram"?"Connect a Business or Creator account. Personal Instagram accounts are not supported.":`Manage the ${qe} account used for publishing LevelUp content.`})]}),e.jsxs(Ie,{className:"space-y-3",children:[Ae.map(ct=>e.jsxs("div",{className:"flex items-center justify-between rounded-md border bg-muted/20 p-3",children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-3",children:[e.jsxs(Oa,{className:"h-9 w-9",children:[e.jsx(Li,{src:ct.profile_picture_url||""}),e.jsx(za,{children:e.jsx(Ce,{className:"h-4 w-4"})})]}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"truncate text-sm font-medium",children:ct.page_name||ct.platform_username||`${qe} account`}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Connected"})]})]}),e.jsxs(kc,{children:[e.jsx(jx,{asChild:!0,children:e.jsx($,{variant:"ghost",size:"icon",className:"text-destructive hover:text-destructive","aria-label":`Disconnect ${qe}`,children:e.jsx(Wn,{className:"h-4 w-4"})})}),e.jsxs(cc,{children:[e.jsxs(dc,{children:[e.jsxs(hc,{children:["Disconnect ",qe,"?"]}),e.jsx(mc,{children:"You will need to reconnect this account before publishing again."})]}),e.jsxs(uc,{children:[e.jsx(fc,{children:"Cancel"}),e.jsx(tc,{onClick:()=>X.mutate(ct.id),className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Disconnect"})]})]})]})]},ct.id)),e.jsxs($,{variant:"outline",onClick:ze,disabled:$e||S,children:[$e?e.jsx(ro,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(dn,{className:"mr-2 h-4 w-4"}),Ae.length?`Add another ${qe} account`:`Connect ${qe}`]})]})]})},Ve=(()=>{var je,Ae,Ce;switch(y){case"gmail":return e.jsxs(Ne,{className:"border-primary/25 shadow-sm",children:[e.jsxs(Ct,{children:[e.jsx(At,{className:"font-display text-xl",children:"Manage Gmail"}),e.jsx(Gn,{children:"Send personalized emails from contact pages and automatically record the activity."})]}),e.jsxs(Ie,{className:"space-y-4",children:[e.jsx("div",{className:"grid gap-2 sm:grid-cols-3",children:["Send from your Gmail account","Log email touchpoints","Compose from any contact"].map($e=>e.jsxs("div",{className:"flex items-start gap-2 rounded-md bg-muted/25 p-3 text-sm",children:[e.jsx(la,{className:"mt-0.5 h-4 w-4 shrink-0 text-success"}),$e]},$e))}),ae?e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3 rounded-md border p-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",children:C.gmail_email}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Connected Gmail account"})]}),e.jsxs(kc,{children:[e.jsx(jx,{asChild:!0,children:e.jsxs($,{variant:"outline",size:"sm",className:"text-destructive",children:[e.jsx(Wn,{className:"mr-2 h-4 w-4"}),"Disconnect"]})}),e.jsxs(cc,{children:[e.jsxs(dc,{children:[e.jsx(hc,{children:"Disconnect Gmail?"}),e.jsx(mc,{children:"You will need to reconnect before sending emails from Gmail."})]}),e.jsxs(uc,{children:[e.jsx(fc,{children:"Cancel"}),e.jsx(tc,{onClick:()=>Y.mutate(C.id),className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Disconnect"})]})]})]})]}):e.jsxs($,{onClick:W,disabled:l||E||S,children:[l?e.jsx(ro,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(mn,{className:"mr-2 h-4 w-4"}),"Connect Gmail"]})]})]});case"mass-email":return e.jsx(tor,{});case"canva":return e.jsx(bos,{});case"facebook":return ke("facebook");case"instagram":return ke("instagram");case"linkedin":return ke("linkedin");case"google-business":const qe=(P==null?void 0:P.connected)===!0,ze=((je=P==null?void 0:P.locations)==null?void 0:je.find($e=>$e.is_primary))??((Ae=P==null?void 0:P.locations)==null?void 0:Ae[0]);return e.jsxs(Ne,{className:"border-primary/25 shadow-sm",children:[e.jsxs(Ct,{children:[e.jsx(At,{className:"font-display text-xl",children:"Google Business Profile"}),e.jsx(Gn,{children:"Post updates and manage reviews from your Google Business Profile."})]}),e.jsxs(Ie,{className:"space-y-3",children:[(P==null?void 0:P.needsReconnect)&&qe&&e.jsx("div",{className:"rounded-md border border-warning/40 bg-warning/10 p-3 text-sm",children:"We upgraded our Google connection. Please reconnect once so posting and reviews keep working."}),qe&&e.jsxs("div",{className:"flex items-center justify-between rounded-md border bg-muted/20 p-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"truncate text-sm font-medium",children:(ze==null?void 0:ze.location_name)||(P==null?void 0:P.email)||"Google Business"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Connected"})]}),e.jsxs(kc,{children:[e.jsx(jx,{asChild:!0,children:e.jsx($,{variant:"ghost",size:"icon",className:"text-destructive hover:text-destructive","aria-label":"Disconnect Google Business",children:e.jsx(Wn,{className:"h-4 w-4"})})}),e.jsxs(cc,{children:[e.jsxs(dc,{children:[e.jsx(hc,{children:"Disconnect Google Business?"}),e.jsx(mc,{children:"You will need to reconnect before posting or syncing reviews again."})]}),e.jsxs(uc,{children:[e.jsx(fc,{children:"Cancel"}),e.jsx(tc,{onClick:()=>D.mutate(),className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Disconnect"})]})]})]})]}),(((Ce=P==null?void 0:P.locations)==null?void 0:Ce.length)??0)>1&&e.jsxs("div",{className:"space-y-2 rounded-md border p-3",children:[e.jsx("p",{className:"text-sm font-medium",children:"Which business should we use?"}),P.locations.map($e=>e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("span",{className:"truncate text-sm",children:$e.location_name||$e.location_id}),$e.is_primary?e.jsx(Be,{className:"shrink-0 text-xs",children:"Active"}):e.jsx($,{size:"sm",variant:"outline",className:"shrink-0",disabled:R.isPending,onClick:()=>R.mutate($e.location_id),children:"Use this"})]},$e.id))]}),qe&&(P==null?void 0:P.missingBusinessScope)&&e.jsxs("div",{className:"rounded-md border border-amber-300 bg-amber-50 p-3 text-sm text-amber-800",children:["Google signed you in, but didn't give LevelUp access to your Business Profile. Click Reconnect below and make sure the",e.jsx("strong",{children:" Business Profile "})," checkbox is ticked on Google's permission screen."]}),qe&&!(P!=null&&P.missingBusinessScope)&&(P==null?void 0:P.apiAccessPending)&&e.jsxs("div",{className:"space-y-2 rounded-md border border-amber-300 bg-amber-50 p-3 text-sm text-amber-800",children:[e.jsxs("p",{children:["We couldn't find a business listing on ",(P==null?void 0:P.email)||"this Google account",". Make sure you signed in with the Google account that manages your Business Profile, then check again."]}),e.jsxs($,{size:"sm",variant:"outline",disabled:O.isPending,onClick:()=>O.mutate(),children:[O.isPending?e.jsx(ro,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(ro,{className:"mr-2 h-4 w-4"}),"Check again"]})]}),e.jsxs($,{variant:qe&&!(P!=null&&P.needsReconnect)?"outline":"default",onClick:U,disabled:m||S,children:[m?e.jsx(ro,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(dn,{className:"mr-2 h-4 w-4"}),qe?"Reconnect Google Business":"Connect Google Business"]})]})]});case"boldtrail":return e.jsx(Gir,{});case"lofty":return e.jsx(Wir,{});case"followupboss":return e.jsx(Kir,{});case"cloze":return e.jsx(Yir,{});case"boomtown":return e.jsx(Xir,{});case"chatgpt":return e.jsxs(Ne,{className:"border-primary/25 shadow-sm",children:[e.jsxs(Ct,{children:[e.jsx(At,{className:"font-display text-xl",children:"ChatGPT"}),e.jsx(Gn,{children:"Connect ChatGPT to LevelUp so it can use LevelUp tools on your behalf."})]}),e.jsx(Ie,{children:e.jsxs($,{variant:"outline",onClick:()=>s("/connect-chatgpt"),children:["View connection instructions ",e.jsx(ei,{className:"ml-2 h-4 w-4"})]})})]});case"ses":return t?e.jsx(yos,{}):null;default:return null}})();return e.jsx(Vs,{children:e.jsxs("div",{className:"integrations-hub mx-auto max-w-7xl animate-fade-in px-4 py-5 sm:px-6 lg:px-8",children:[e.jsxs("header",{className:"flex flex-col gap-4 border-b pb-6 sm:flex-row sm:items-end sm:justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"mb-2 text-xs font-semibold uppercase text-primary",children:"Connected workspace"}),e.jsx("h1",{className:"font-display text-3xl font-semibold text-foreground sm:text-4xl",children:"Integrations"}),e.jsx("p",{className:"mt-2 max-w-2xl text-sm text-muted-foreground sm:text-base",children:"Connect the services that power your communication, marketing, and contact workflows."})]}),e.jsxs(Be,{variant:"outline",className:"w-fit gap-2 border-primary/25 bg-card px-3 py-1.5 text-sm text-foreground",children:[e.jsx("span",{className:"h-2 w-2 rounded-full bg-success"}),Le," services active"]})]}),S&&e.jsx(Ne,{className:"mt-5 border-warning/40 bg-warning/5",children:e.jsxs(Ct,{className:"flex flex-row items-start gap-3 space-y-0",children:[e.jsx(pc,{className:"mt-0.5 h-5 w-5 text-warning"}),e.jsxs("div",{children:[e.jsx(At,{className:"text-base",children:"Connected accounts are hidden"}),e.jsxs(Gn,{children:["You're working on behalf of ",r==null?void 0:r.name,". Email and social account connections are private to each agent and can only be viewed or changed from their own login."]})]})]})}),e.jsxs("div",{className:"mt-6 grid gap-6 lg:grid-cols-[220px_minmax(0,1fr)]",children:[e.jsx("nav",{"aria-label":"Integration categories",className:"min-w-0",children:e.jsx("div",{className:"flex gap-2 overflow-x-auto pb-2 lg:sticky lg:top-5 lg:flex-col lg:overflow-visible",children:nor.map(je=>{const Ae=je.icon,Ce=g===je.id;return e.jsxs($,{variant:Ce?"secondary":"ghost",className:`shrink-0 justify-start gap-2 ${Ce?"text-primary":"text-muted-foreground"}`,onClick:()=>{x(je.id),v(null)},children:[e.jsx(Ae,{className:"h-4 w-4"}),je.label]},je.id)})})}),e.jsxs("main",{className:"min-w-0 space-y-8",children:[(g==="all"||g==="communication")&&e.jsxs("section",{"aria-labelledby":"email-connections",children:[e.jsxs("div",{className:"mb-3 flex items-end justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("h2",{id:"email-connections",className:"font-display text-xl font-semibold",children:"Email connections"}),e.jsx("p",{className:"mt-1 text-sm text-muted-foreground",children:"Your highest-priority tools for individual and campaign email."})]}),e.jsxs(Be,{variant:"secondary",className:"hidden sm:flex",children:[e.jsx(xm,{className:"mr-1.5 h-3.5 w-3.5"}),"Priority"]})]}),e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2",children:[e.jsx(aw,{title:"Gmail",description:"Send personal emails and automatically log each touchpoint.",icon:e.jsx(mn,{className:"h-5 w-5"}),connected:ae,selected:y==="gmail",onClick:()=>Fe("gmail"),badge:"Priority"}),e.jsx(aw,{title:"Mass Email",description:"Send polished campaigns from a verified sender address.",icon:e.jsx(Yr,{className:"h-5 w-5"}),connected:!!(ce!=null&&ce.reply_to_email),statusLabel:"Setup required",selected:y==="mass-email",onClick:()=>Fe("mass-email"),badge:"Priority"})]})]}),(g==="all"||g==="crm")&&e.jsxs("section",{"aria-labelledby":"crm-connections",children:[e.jsxs("div",{className:"mb-3",children:[e.jsx("h2",{id:"crm-connections",className:"font-display text-xl font-semibold",children:"Real estate CRMs"}),e.jsx("p",{className:"mt-1 text-sm text-muted-foreground",children:"Bring contacts into LevelUp and control how they stay synchronized."})]}),e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2 xl:grid-cols-3",children:[e.jsx(aw,{title:"BoldTrail",description:"Sync contacts, ownership, tags, notes, and lead details.",icon:e.jsx(v0,{className:"h-5 w-5"}),connected:he==null?void 0:he.connected,selected:y==="boldtrail",onClick:()=>Fe("boldtrail")}),e.jsx(aw,{title:"Lofty",description:"Connect Lofty contacts and control sync direction.",icon:e.jsx(v0,{className:"h-5 w-5"}),connected:ue==null?void 0:ue.connected,selected:y==="lofty",onClick:()=>Fe("lofty")}),e.jsx(aw,{title:"Follow Up Boss",description:"Keep Follow Up Boss contacts aligned with LevelUp.",icon:e.jsx(v0,{className:"h-5 w-5"}),connected:ve==null?void 0:ve.connected,selected:y==="followupboss",onClick:()=>Fe("followupboss")}),e.jsx(aw,{title:"Cloze",description:"Sync contacts from your Cloze account or selected segments.",icon:e.jsx(v0,{className:"h-5 w-5"}),connected:Ee==null?void 0:Ee.connected,selected:y==="cloze",onClick:()=>Fe("cloze")}),e.jsx(aw,{title:"BoomTown",description:"Import and synchronize your BoomTown contact database.",icon:e.jsx(v0,{className:"h-5 w-5"}),connected:Se==null?void 0:Se.connected,selected:y==="boomtown",onClick:()=>Fe("boomtown")})]})]}),(g==="all"||g==="social")&&e.jsxs("section",{"aria-labelledby":"social-connections",children:[e.jsxs("div",{className:"mb-3",children:[e.jsx("h2",{id:"social-connections",className:"font-display text-xl font-semibold",children:"Social media"}),e.jsx("p",{className:"mt-1 text-sm text-muted-foreground",children:"Connect the profiles and pages used by Social Studio."})]}),e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2 xl:grid-cols-3",children:[e.jsx(aw,{title:"Facebook",description:"Publish to your connected Facebook Pages.",icon:e.jsx(Qp,{className:"h-5 w-5"}),connected:ie.length>0,selected:y==="facebook",onClick:()=>Fe("facebook")}),e.jsx(aw,{title:"Instagram",description:"Schedule content to a Business or Creator account.",icon:e.jsx(Tf,{className:"h-5 w-5"}),connected:ne.length>0,selected:y==="instagram",onClick:()=>Fe("instagram")}),e.jsx(aw,{title:"LinkedIn",description:"Share content with your professional network.",icon:e.jsx(hy,{className:"h-5 w-5"}),connected:te.length>0,selected:y==="linkedin",onClick:()=>Fe("linkedin")}),e.jsx(aw,{title:"Google Business",description:"Post updates and manage reviews on your Google Business Profile.",icon:e.jsx(ji,{className:"h-5 w-5"}),connected:J.length>0&&!(P!=null&&P.needsReconnect),statusLabel:P!=null&&P.needsReconnect?"Reconnect":void 0,selected:y==="google-business",onClick:()=>Fe("google-business")})]})]}),(g==="all"||g==="marketing")&&e.jsxs("section",{"aria-labelledby":"marketing-connections",children:[e.jsxs("div",{className:"mb-3",children:[e.jsx("h2",{id:"marketing-connections",className:"font-display text-xl font-semibold",children:"AI & marketing"}),e.jsx("p",{className:"mt-1 text-sm text-muted-foreground",children:"Extend LevelUp with AI tools and managed delivery services."})]}),e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2 xl:grid-cols-3",children:[e.jsx(aw,{title:"Canva",description:"Bring your own Canva designs into Mail Studio and your LevelUp library.",icon:e.jsx(Yc,{className:"h-5 w-5"}),connected:!!(b!=null&&b.connected),statusLabel:b!=null&&b.needs_reconnect?"Reconnect":void 0,selected:y==="canva",onClick:()=>Fe("canva")}),e.jsx(aw,{title:"ChatGPT",description:"Use your LevelUp tools directly from ChatGPT.",icon:e.jsx(M4,{className:"h-5 w-5"}),statusLabel:"View setup",selected:y==="chatgpt",onClick:()=>Fe("chatgpt")}),t&&e.jsx(aw,{title:"Amazon SES",description:"Manage the platform-level mass email delivery service.",icon:e.jsx(sC,{className:"h-5 w-5"}),statusLabel:"Admin only",badge:"Admin",selected:y==="ses",onClick:()=>Fe("ses")})]})]})]})]}),e.jsx(Wy,{open:y!==null,onOpenChange:je=>{je||v(null)},children:e.jsxs(py,{side:"right",className:"integrations-hub w-full overflow-y-auto border-l bg-background p-0 sm:max-w-2xl lg:max-w-3xl [&>button]:z-20",children:[e.jsxs(D0,{className:"sticky top-0 z-10 border-b bg-background px-5 py-5 pr-12 text-left sm:px-7",children:[e.jsxs(F0,{className:"font-display text-xl",children:[y?ror[y]:"Integration"," settings"]}),e.jsx($B,{children:"Review the connection and update its settings here."})]}),e.jsx("div",{className:"p-4 sm:p-7",children:Ve})]})})]})})}const oor="https://chromewebstore.google.com/detail/levelup-companion/lppakdeaencigddecnkcifdcemlfpkkk";function lor(){const[s,t]=j.useState(null),[n,r]=j.useState(!1),[a,i]=j.useState(0),[l,o]=j.useState(!1),c="/levelup-extension.zip",d="https://tile-portal.lovable.app/levelup-extension.zip",u=window.location.hostname.startsWith("id-preview--"),h=async y=>{const v=new Uint8Array(await y.slice(0,4).arrayBuffer());return v[0]===80&&v[1]===75&&v[2]===3&&v[3]===4||v[0]===80&&v[1]===75&&v[2]===5&&v[3]===6||v[0]===80&&v[1]===75&&v[2]===7&&v[3]===8},m=y=>{const v=document.createElement("a");v.href=y,v.download="levelup-extension.zip",v.rel="noopener noreferrer",v.target="_blank",document.body.appendChild(v),v.click(),v.remove()},f=async()=>{o(!0);try{if(u){m(`${d}?v=${Date.now()}`);return}const y=await fetch(`${c}?v=${Date.now()}`,{cache:"no-store"});if(!y.ok)throw new Error(`Download failed (${y.status})`);const v=await y.blob();if(!await h(v)){m(`${d}?v=${Date.now()}`);return}const b=new Blob([v],{type:"application/zip"}),w=URL.createObjectURL(b),S=document.createElement("a");S.href=w,S.download="levelup-extension.zip",document.body.appendChild(S),S.click(),S.remove(),setTimeout(()=>URL.revokeObjectURL(w),1e3)}catch(y){re.error(y.message||"Download failed")}finally{o(!1)}},g=async()=>{r(!0);try{await q.auth.refreshSession();const{data:y}=await q.auth.getSession();if(!y.session){re.error("Your session has expired. Please sign in again.");return}const{data:v,error:b}=await q.functions.invoke("extension-pair-start",{headers:{Authorization:`Bearer ${y.session.access_token}`}});if(b)throw b;t(v.code),i(v.expires_in||300);const w=setInterval(()=>{i(S=>S<=1?(clearInterval(w),t(null),0):S-1)},1e3)}catch(y){console.error("generateCode error",y),re.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{r(!1)}},x=()=>{s&&(navigator.clipboard.writeText(s),re.success("Copied"))};return e.jsx(Vs,{title:"Browser Extension",children:e.jsxs("div",{className:"container max-w-3xl mx-auto py-8 px-4 space-y-6",children:[e.jsxs(Ml,{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($z,{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(Ne,{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($,{size:"lg",className:"w-full",onClick:()=>window.open(oor,"_blank","noopener,noreferrer"),children:[e.jsx($z,{className:"w-4 h-4 mr-2"}),"Add to Chrome",e.jsx(kr,{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(Ne,{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($,{onClick:x,variant:"outline",className:"flex-1",children:[e.jsx(Ha,{className:"w-4 h-4 mr-2"})," Copy"]}),e.jsxs($,{onClick:g,variant:"outline",className:"flex-1",children:[e.jsx(ro,{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(la,{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($,{onClick:g,disabled:n,size:"lg",className:"w-full",children:n?e.jsxs(e.Fragment,{children:[e.jsx(ro,{className:"w-4 h-4 mr-2 animate-spin"}),"Generating…"]}):"Generate pairing code"})]}),e.jsxs(Ne,{className:"p-6 space-y-4 bg-muted/30 border-dashed",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(vm,{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($,{variant:"link",className:"h-auto p-0 text-sm",onClick:f,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 cor(){const[s]=gc(),t=Qn(),[n,r]=j.useState("loading"),[a,i]=j.useState("Connecting your Gmail account...");return j.useEffect(()=>{(async()=>{const o=s.get("code"),c=s.get("error"),d=s.get("error_description"),u=s.get("state");if(c){r("error"),i(d||"Authorization was denied"),re.error("Connection failed: "+(d||c));return}if(!o){r("error"),i("No authorization code received"),re.error("No authorization code received");return}try{const{data:h,error:m}=await q.functions.invoke("gmail-oauth",{body:{action:"exchange_code",code:o,state:u}});if(m)throw m;if(h!=null&&h.success)r("success"),i(h.message||"Gmail connected successfully!"),re.success("Gmail connected!");else throw new Error((h==null?void 0:h.error)||"Unknown error")}catch(h){console.error("Gmail OAuth callback error:",h),r("error"),i(h instanceof Error?h.message:"Failed to connect Gmail"),re.error("Failed to connect: "+(h instanceof Error?h.message:"Unknown error"))}})()},[s]),e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-background p-4",children:e.jsxs(Ne,{className:"w-full max-w-md",children:[e.jsxs(Ct,{className:"text-center",children:[n==="loading"&&e.jsx(kt,{className:"h-12 w-12 animate-spin mx-auto text-primary"}),n==="success"&&e.jsx(Nc,{className:"h-12 w-12 mx-auto text-green-500"}),n==="error"&&e.jsx(ku,{className:"h-12 w-12 mx-auto text-destructive"}),e.jsxs(At,{className:"mt-4",children:[n==="loading"&&"Connecting...",n==="success"&&"Connected!",n==="error"&&"Connection Failed"]}),e.jsx(Gn,{children:a})]}),e.jsx(Ie,{className:"flex justify-center",children:n!=="loading"&&e.jsx($,{onClick:()=>t("/mission-control/integrations"),children:n==="success"?"Back to Integrations":"Try Again"})})]})})}function dor(){const s=Qn();return j.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 uor(){const[s]=gc(),t=Qn(),[n,r]=j.useState("loading"),a=j.useRef(!1),[i,l]=j.useState("Processing your connection...");return j.useEffect(()=>{if(a.current)return;a.current=!0,(async()=>{var m;const c=s.get("code"),d=s.get("error"),u=s.get("error_description"),h=s.get("state");if(d){r("error"),l(u||"Authorization was denied"),re.error("Connection failed: "+(u||d));return}if(!c){r("error"),l("No authorization code received"),re.error("No authorization code received");return}try{const{data:f,error:g}=await q.functions.invoke("meta-oauth",{body:{action:"exchange_code",code:c,state:h,callbackPath:"/mission-control/integrations/meta/callback"}});if(f&&f.success===!1)throw new Error(f.error||"Failed to connect accounts");if(g){let x=g.message||"Failed to connect accounts";try{const y=g.context;if(y&&typeof y.json=="function"){const v=await y.json();v!=null&&v.error&&(x=v.error)}}catch{}throw new Error(x)}if(f!=null&&f.success)r("success"),l(`Successfully connected ${((m=f.accounts)==null?void 0:m.length)||0} account(s)!`),re.success("Social accounts connected successfully!");else throw new Error((f==null?void 0:f.error)||"Unknown error")}catch(f){console.error("OAuth callback error:",f),r("error"),l(f instanceof Error?f.message:"Failed to connect accounts"),re.error("Failed to connect: "+(f instanceof Error?f.message:"Unknown error"))}})()},[s]),e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-background p-4",children:e.jsxs(Ne,{className:"w-full max-w-md",children:[e.jsxs(Ct,{className:"text-center",children:[n==="loading"&&e.jsx(kt,{className:"h-12 w-12 animate-spin mx-auto text-primary"}),n==="success"&&e.jsx(Nc,{className:"h-12 w-12 mx-auto text-green-500"}),n==="error"&&e.jsx(ku,{className:"h-12 w-12 mx-auto text-destructive"}),e.jsxs(At,{className:"mt-4",children:[n==="loading"&&"Connecting...",n==="success"&&"Connected!",n==="error"&&"Connection Failed"]}),e.jsx(Gn,{children:i})]}),e.jsx(Ie,{className:"flex justify-center",children:n!=="loading"&&e.jsx($,{onClick:()=>t("/mission-control/integrations"),children:n==="success"?"View Integrations":"Try Again"})})]})})}const _os=new Date().getFullYear(),hor=Array.from({length:5},(s,t)=>_os-t);function mor(){const[s,t]=j.useState(_os),n=Qn(),{data:r,isLoading:a}=XWs();return a?e.jsx(Vs,{title:"Scorecard Admin",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(yn,{className:"h-8 w-64"}),e.jsx("div",{className:"grid grid-cols-4 gap-4",children:[1,2,3,4].map(i=>e.jsx(yn,{className:"h-24"},i))}),e.jsx(yn,{className:"h-96"})]})}):e.jsx(Vs,{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(ms,{value:String(s),onValueChange:i=>t(Number(i)),children:[e.jsx(us,{className:"w-[120px]",children:e.jsx(fs,{})}),e.jsx(hs,{children:hor.map(i=>e.jsx(Ge,{value:String(i),children:i},i))})]})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[e.jsx(Ne,{children:e.jsxs(Ie,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(Zn,{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:(r==null?void 0:r.length)||0})]})}),e.jsx(Ne,{children:e.jsxs(Ie,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(Wl,{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:(r==null?void 0:r.length)||0}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"with transactions"})]})})]}),e.jsxs(Ne,{children:[e.jsxs(Ct,{children:[e.jsx(At,{children:"Agents with Scorecards"}),e.jsx(Gn,{children:"Click to view individual agent scorecards"})]}),e.jsx(Ie,{children:!r||r.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(Wl,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{children:"No agents have added transactions yet"})]}):e.jsxs(mi,{children:[e.jsx(fi,{children:e.jsxs(En,{children:[e.jsx(Dt,{children:"Agent"}),e.jsx(Dt,{children:"Email"}),e.jsx(Dt,{className:"text-right",children:"Actions"})]})}),e.jsx(pi,{children:r.map(i=>e.jsxs(En,{children:[e.jsx(wt,{className:"font-medium",children:i.name}),e.jsx(wt,{className:"text-muted-foreground",children:i.email}),e.jsx(wt,{className:"text-right",children:e.jsxs($,{variant:"ghost",size:"sm",onClick:()=>n(`/admin/scorecard/${i.id}`),children:[e.jsx(Ca,{className:"h-4 w-4 mr-2"}),"View Scorecard"]})})]},i.id))})]})})]})]})})}const por="00000000-0000-0000-0000-000000000000",gor=s=>{if(!s)return"—";const[t,n,r]=s.split(/[-/T]/);return`${n}/${r}/${t}`};function xor(s){if(s.total_agents===0)return{label:"Empty",className:"bg-muted text-muted-foreground"};const t=s.active_90d/s.total_agents;return t>=.4?{label:"Healthy",className:"bg-emerald-100 text-emerald-800"}:t>=.15?{label:"At risk",className:"bg-amber-100 text-amber-800"}:{label:"Dormant",className:"bg-red-100 text-red-800"}}const yor={never_started:"Never started",signed_in_empty:"Signed in, empty",started:"Started, gone quiet",active:"Active"};function vor(){const s=Vt(),[t,n]=j.useState(null),[r,a]=j.useState(""),[i,l]=j.useState(null),{data:o=[]}=tt({queryKey:["agent-activation-settings"],queryFn:async()=>{const{data:S,error:C}=await q.from("agent_activation_settings").select("*");if(C)throw C;return S}}),{data:c=[],isLoading:d}=tt({queryKey:["brokerage-adoption-stats"],queryFn:async()=>{const{data:S,error:C}=await q.rpc("get_brokerage_adoption_stats");if(C)throw C;return S}}),{data:u}=tt({queryKey:["agent-activation-metrics"],refetchInterval:6e4,queryFn:async()=>{const S=async D=>{const{count:O}=await D(q.from("agent_activation_sends").select("id",{count:"exact",head:!0}));return O??0},[C,E,I]=await Promise.all([S(D=>D.eq("status","sent")),S(D=>D.not("opened_at","is",null)),S(D=>D.not("clicked_at","is",null))]),{count:P}=await q.from("agent_activation_state").select("user_id",{count:"exact",head:!0}),{count:R}=await q.from("agent_activation_state").select("user_id",{count:"exact",head:!0}).eq("exit_reason","active");return{sent:C,opened:E,clicked:I,inSequence:P??0,activated:R??0}}}),h=o.find(S=>S.brokerage_id===null),m=!!(h!=null&&h.enabled),f=S=>o.find(C=>C.brokerage_id===S),g=ft({mutationFn:async({brokerageId:S,enabled:C})=>{const{data:E}=await q.from("agent_activation_settings").select("id").eq("brokerage_id",S??por).maybeSingle();let I=E;if(S===null){const{data:P}=await q.from("agent_activation_settings").select("id").is("brokerage_id",null).maybeSingle();I=P}if(I){const{error:P}=await q.from("agent_activation_settings").update({enabled:C,updated_at:new Date().toISOString()}).eq("id",I.id);if(P)throw P}else{const{error:P}=await q.from("agent_activation_settings").insert({brokerage_id:S,enabled:C});if(P)throw P}},onSuccess:()=>{s.invalidateQueries({queryKey:["agent-activation-settings"]}),re.success("Setting saved")},onError:()=>re.error("Could not save setting")}),x=ft({mutationFn:async S=>{const{data:C,error:E}=await q.functions.invoke("agent-activation-run",{body:{action:"preview",step:S,brokerage_name:t==null?void 0:t.brokerage_name}});if(E)throw E;return C},onSuccess:l,onError:()=>re.error("Preview failed")}),y=ft({mutationFn:async S=>{const{data:C,error:E}=await q.functions.invoke("agent-activation-run",{body:{action:"test_send",step:S,brokerage_name:t==null?void 0:t.brokerage_name}});if(E)throw E;if(C!=null&&C.error)throw new Error(C.error);return C},onSuccess:S=>re.success(`Test email sent to ${S.sent_to}`),onError:S=>re.error(S.message||"Test send failed")}),v=c.filter(S=>S.brokerage_name.toLowerCase().includes(r.toLowerCase())),b=u!=null&&u.sent?Math.round(u.opened/u.sent*100):0,w=u!=null&&u.sent?Math.round(u.clicked/u.sent*100):0;return e.jsx(Vs,{title:"Agent Activation",children:e.jsxs("div",{className:"container mx-auto py-6 space-y-6 max-w-7xl",children:[t?e.jsxs("div",{className:"space-y-4",children:[e.jsxs($,{variant:"ghost",size:"sm",className:"gap-2 text-muted-foreground hover:text-foreground",onClick:()=>n(null),children:[e.jsx(Cd,{className:"h-4 w-4"}),"Back to all brokerages"]}),e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold",children:t.brokerage_name}),e.jsx("p",{className:"text-muted-foreground",children:"Agent Activation · manage this brokerage's agents and sequence."})]})]}):e.jsx(Fm,{title:"Agent Activation",description:"Find dormant agents and walk them into the product with a branded email sequence. Nothing sends until you turn it on."}),e.jsx("div",{className:"grid gap-4 grid-cols-2 lg:grid-cols-5",children:[{label:"Emails sent",value:(u==null?void 0:u.sent)??0,hint:"across all brokerages"},{label:"Opened",value:(u==null?void 0:u.opened)??0,hint:`${b}% open rate`},{label:"Clicked",value:(u==null?void 0:u.clicked)??0,hint:`${w}% click rate`},{label:"Agents in sequence",value:(u==null?void 0:u.inSequence)??0,hint:"currently receiving"},{label:"Activated",value:(u==null?void 0:u.activated)??0,hint:"signed in and working"}].map(S=>e.jsx(Ne,{children:e.jsxs(Ie,{className:"pt-5",children:[e.jsx("div",{className:"text-xs uppercase tracking-wide text-muted-foreground",children:S.label}),e.jsx("div",{className:"text-2xl font-bold",children:S.value.toLocaleString()}),e.jsx("div",{className:"text-xs text-muted-foreground",children:S.hint})]})},S.label))}),e.jsx(Ne,{className:m?"border-emerald-300":"border-amber-300",children:e.jsx(Ct,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs(At,{className:"flex items-center gap-2 text-lg",children:[e.jsx(af,{className:"h-5 w-5"}),"Master switch"]}),e.jsx(Gn,{children:m?"Activation emails are LIVE for brokerages you enable below.":"OFF worldwide. No activation emails can be sent to anyone."})]}),e.jsx(Sn,{checked:m,onCheckedChange:S=>g.mutate({brokerageId:null,enabled:S})})]})})}),e.jsxs(Ne,{children:[e.jsxs(Ct,{children:[e.jsxs(At,{className:"text-lg flex items-center gap-2",children:[e.jsx(mn,{className:"h-5 w-5"})," The sequence"]}),e.jsx(Gn,{children:"Five emails, all sent from LevelUp. Preview any step or send a test to yourself."})]}),e.jsx(Ie,{className:"flex flex-wrap gap-2",children:[1,2,3,4,5].map(S=>e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsxs($,{variant:"outline",size:"sm",onClick:()=>x.mutate(S),disabled:x.isPending,children:[e.jsx(Ca,{className:"h-3.5 w-3.5 mr-1"})," Step ",S]}),e.jsx($,{variant:"ghost",size:"sm",onClick:()=>y.mutate(S),disabled:y.isPending,title:"Send test to my email",children:e.jsx(Yr,{className:"h-3.5 w-3.5"})})]},S))})]}),t?e.jsx(bor,{brokerage:t,settings:f(t.brokerage_id),masterOn:m,onBack:()=>n(null),onToggle:S=>g.mutate({brokerageId:t.brokerage_id,enabled:S})}):e.jsxs(Ne,{children:[e.jsx(Ct,{children:e.jsxs("div",{className:"flex items-center justify-between gap-4 flex-wrap",children:[e.jsxs("div",{children:[e.jsx(At,{className:"text-lg",children:"Brokerage adoption"}),e.jsx(Gn,{children:"Select a brokerage to manage agents and enable the sequence."})]}),e.jsx(pe,{placeholder:"Search brokerages…",value:r,onChange:S=>a(S.target.value),className:"max-w-xs"})]})}),e.jsx(Ie,{children:d?e.jsx("div",{className:"flex justify-center py-12",children:e.jsx(kt,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):e.jsxs(mi,{children:[e.jsx(fi,{children:e.jsxs(En,{children:[e.jsx(Dt,{children:"Brokerage"}),e.jsx(Dt,{children:"Health"}),e.jsx(Dt,{className:"text-right",children:"Agents"}),e.jsx(Dt,{className:"text-right",children:"Never in"}),e.jsx(Dt,{className:"text-right",children:"Active 90d"}),e.jsx(Dt,{className:"text-right",children:"With data"}),e.jsx(Dt,{className:"text-right",children:"Activation"})]})}),e.jsx(pi,{children:v.map(S=>{var I;const C=xor(S),E=!!((I=f(S.brokerage_id))!=null&&I.enabled);return e.jsxs(En,{className:"cursor-pointer",onClick:()=>n(S),children:[e.jsx(wt,{className:"font-medium",children:S.brokerage_name}),e.jsx(wt,{children:e.jsx(Be,{variant:"secondary",className:C.className,children:C.label})}),e.jsx(wt,{className:"text-right",children:S.total_agents}),e.jsx(wt,{className:"text-right",children:S.never_logged_in}),e.jsx(wt,{className:"text-right",children:S.active_90d}),e.jsx(wt,{className:"text-right",children:S.with_contacts+S.with_deals>0?`${S.with_contacts}`:0}),e.jsx(wt,{className:"text-right",children:e.jsx(Be,{variant:E?"default":"outline",children:E?"On":"Off"})})]},S.brokerage_id)})})]})})]}),e.jsx(zs,{open:!!i,onOpenChange:()=>l(null),children:e.jsxs(Os,{className:"max-w-3xl max-h-[85vh] overflow-y-auto",children:[e.jsxs(Us,{children:[e.jsx(Bs,{children:i==null?void 0:i.subject}),e.jsx(Ir,{children:"Exactly as the agent will receive it."})]}),i&&e.jsx("iframe",{title:"Email preview",sandbox:"",srcDoc:i.html,className:"w-full h-[560px] rounded-md border"})]})})]})})}function bor({brokerage:s,settings:t,masterOn:n,onBack:r,onToggle:a}){const i=Vt(),[l,o]=j.useState(""),{data:c=[],isLoading:d}=tt({queryKey:["brokerage-agent-activation",s.brokerage_id],queryFn:async()=>{const{data:x,error:y}=await q.rpc("get_brokerage_agent_activation",{_brokerage_id:s.brokerage_id});if(y)throw y;return x}}),u=ft({mutationFn:async({userId:x,skip:y})=>{if(y){const{error:v}=await q.from("agent_activation_state").upsert({user_id:x,brokerage_id:s.brokerage_id,exited_at:new Date().toISOString(),exit_reason:"manual_skip",updated_at:new Date().toISOString()},{onConflict:"user_id"});if(v)throw v}else{const{error:v}=await q.from("agent_activation_state").update({exited_at:null,exit_reason:null,updated_at:new Date().toISOString()}).eq("user_id",x);if(v)throw v}},onSuccess:()=>{i.invalidateQueries({queryKey:["brokerage-agent-activation",s.brokerage_id]}),re.success("Agent updated")},onError:()=>re.error("Update failed")}),h=ft({mutationFn:async x=>{const{data:y,error:v}=await q.functions.invoke("agent-activation-run",{body:{action:"send_now",user_id:x,brokerage_id:s.brokerage_id}});if(v)throw v;if(y!=null&&y.error)throw new Error(y.error);return y},onSuccess:()=>{i.invalidateQueries({queryKey:["brokerage-agent-activation",s.brokerage_id]}),re.success("Email sent")},onError:x=>re.error(x.message||"Send failed")}),m=!!(t!=null&&t.enabled),f=m&&n,g=c.filter(x=>(x.name||"").toLowerCase().includes(l.toLowerCase())||(x.email||"").toLowerCase().includes(l.toLowerCase()));return e.jsxs(Ne,{children:[e.jsxs(Ct,{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($,{variant:"ghost",size:"sm",onClick:r,children:e.jsx(Cd,{className:"h-4 w-4"})}),e.jsxs("div",{children:[e.jsx(At,{className:"text-lg",children:s.brokerage_name}),e.jsxs(Gn,{children:[s.total_agents," agents · ",s.never_logged_in," never logged in ·"," ",s.active_90d," active in 90 days"]})]})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"text-sm text-muted-foreground",children:f?"Sequence LIVE for this brokerage":n?"Off for this brokerage":"Master switch is off"}),e.jsx(Sn,{checked:m,onCheckedChange:a})]})]}),e.jsx("div",{className:"pt-2",children:e.jsx(pe,{placeholder:"Search agents…",value:l,onChange:x=>o(x.target.value),className:"max-w-xs"})})]}),e.jsx(Ie,{children:d?e.jsx("div",{className:"flex justify-center py-12",children:e.jsx(kt,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):e.jsxs(mi,{children:[e.jsx(fi,{children:e.jsxs(En,{children:[e.jsx(Dt,{children:"Agent"}),e.jsx(Dt,{children:"Stage"}),e.jsx(Dt,{className:"text-right",children:"Logins"}),e.jsx(Dt,{children:"Last login"}),e.jsx(Dt,{className:"text-right",children:"Contacts"}),e.jsx(Dt,{className:"text-right",children:"Deals"}),e.jsx(Dt,{className:"text-right",children:"Step"}),e.jsx(Dt,{className:"text-right",children:"Emails"}),e.jsx(Dt,{className:"text-right",children:"Actions"})]})}),e.jsx(pi,{children:g.map(x=>{const y=x.exit_reason==="manual_skip";return e.jsxs(En,{children:[e.jsxs(wt,{children:[e.jsx("div",{className:"font-medium",children:x.name||"—"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:x.email})]}),e.jsx(wt,{children:e.jsx(Be,{variant:x.stage==="active"?"default":"secondary",children:y?"Skipped":yor[x.stage]})}),e.jsx(wt,{className:"text-right",children:x.login_count}),e.jsx(wt,{children:gor(x.last_login)}),e.jsx(wt,{className:"text-right",children:x.contact_count}),e.jsx(wt,{className:"text-right",children:x.deal_count}),e.jsxs(wt,{className:"text-right",children:[x.step,"/5"]}),e.jsx(wt,{className:"text-right",children:e.jsxs("span",{className:"inline-flex items-center gap-1",children:[x.last_opened_at?e.jsx(Kz,{className:"h-3.5 w-3.5 text-emerald-600"}):e.jsx(mn,{className:"h-3.5 w-3.5 text-muted-foreground"}),x.emails_sent]})}),e.jsx(wt,{className:"text-right",children:e.jsxs("div",{className:"flex justify-end gap-1",children:[e.jsx($,{variant:"ghost",size:"sm",disabled:!f||!!x.exited_at||h.isPending,onClick:()=>h.mutate(x.user_id),title:"Send the next step now",children:e.jsx(Yr,{className:"h-3.5 w-3.5"})}),e.jsx($,{variant:"ghost",size:"sm",onClick:()=>u.mutate({userId:x.user_id,skip:!y}),title:y?"Include in sequence":"Skip this agent",children:e.jsx(pV,{className:`h-3.5 w-3.5 ${y?"text-red-500":""}`})})]})})]},x.user_id)})})]})})]})}const wos=new Date().getFullYear(),_or=Array.from({length:10},(s,t)=>wos-t);function uEt(){var g;const{userId:s}=Wi(),t=Qn(),r=fu().pathname.startsWith("/mission-control"),[a,i]=j.useState(wos),{data:l,isLoading:o}=tt({queryKey:["agent-profile",s],queryFn:async()=>{const{data:x,error:y}=await q.from("profiles").select("id, name, email").eq("id",s).single();if(y)throw y;return x},enabled:!!s}),{data:c,isLoading:d}=pnt(a,s),{yearStats:u,lifetimeStats:h,showCommission:m}=aqt(a,s),{data:f}=rqt(a,s);return o?e.jsx(Vs,{title:"Agent Scorecard",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(yn,{className:"h-8 w-64"}),e.jsx("div",{className:"grid grid-cols-4 gap-4",children:[1,2,3,4].map(x=>e.jsx(yn,{className:"h-24"},x))})]})}):e.jsx(Vs,{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($,{variant:"ghost",size:"icon",onClick:()=>t(r?"/mission-control/scorecard":"/admin/scorecard"),children:e.jsx(qa,{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(ms,{value:String(a),onValueChange:x=>i(Number(x)),children:[e.jsx(us,{className:"w-[120px]",children:e.jsx(fs,{})}),e.jsx(hs,{children:_or.map(x=>e.jsx(Ge,{value:String(x),children:x},x))})]})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 lg:grid-cols-5 gap-4",children:[e.jsx(Ne,{children:e.jsxs(Ie,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(va,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs font-medium",children:"Transactions"})]}),e.jsx("p",{className:"text-2xl font-bold",children:u.totalTransactions}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[h.totalTransactions," lifetime"]})]})}),e.jsx(Ne,{children:e.jsxs(Ie,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(Zn,{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:[u.buyerCount,"/",u.sellerCount]})]})}),e.jsx(Ne,{children:e.jsxs(Ie,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(ru,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs font-medium",children:"Volume"})]}),e.jsx("p",{className:"text-2xl font-bold",children:Qm(u.totalVolume,!0)})]})}),e.jsx(Ne,{children:e.jsxs(Ie,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(Yl,{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:Qm(u.averagePrice,!0)})]})}),e.jsx(Ne,{children:e.jsxs(Ie,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(Rm,{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:((g=u.topLeadSource)==null?void 0:g.name)||"-"})]})})]}),f&&e.jsx(Drs,{goals:f,stats:u,year:a,showCommission:m}),e.jsxs(ha,{defaultValue:"transactions",className:"space-y-4",children:[e.jsxs(ma,{children:[e.jsx(Zt,{value:"transactions",children:"Transactions"}),e.jsx(Zt,{value:"charts",children:"Charts"}),e.jsxs(Zt,{value:"map",children:[e.jsx(ci,{className:"h-4 w-4 mr-1"}),"Map"]})]}),e.jsx(Xt,{value:"transactions",children:e.jsx(Yot,{transactions:c||[],showCommission:m,isLoading:d})}),e.jsx(Xt,{value:"charts",children:e.jsx(Zot,{stats:u,year:a})}),e.jsx(Xt,{value:"map",children:e.jsx(Xot,{transactions:c||[],isLoading:d})})]})]})})}function wor(){const s=Vt(),[t,n]=j.useState(""),[r,a]=j.useState("all"),[i,l]=j.useState(null);Rae();const{data:o,refetch:c}=tt({queryKey:["listing-exchange-flag"],queryFn:async()=>{const{data:R}=await q.from("feature_flags").select("enabled").eq("key","listing_exchange_enabled").single();return(R==null?void 0:R.enabled)??!1}}),{data:d,isLoading:u}=tt({queryKey:["admin-listings"],queryFn:async()=>{const{data:R,error:D}=await q.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(D)throw D;return R}}),{data:h}=tt({queryKey:["admin-listing-stats"],queryFn:async()=>{const{data:R}=await q.from("listings").select("id, is_approved, status"),{data:D}=await q.from("listing_shares").select("id"),{data:O}=await q.from("listing_views").select("id"),{count:U}=await q.from("listing_leads").select("id",{count:"exact",head:!0}),W=new Date(Date.now()-7*24*60*60*1e3).toISOString(),{count:V}=await q.from("listing_leads").select("id",{count:"exact",head:!0}).gte("created_at",W);return{total:(R==null?void 0:R.length)||0,pending:(R==null?void 0:R.filter(G=>!G.is_approved).length)||0,active:(R==null?void 0:R.filter(G=>G.status==="active").length)||0,totalShares:(D==null?void 0:D.length)||0,totalViews:(O==null?void 0:O.length)||0,totalLeads:U||0,leadsLast7:V||0}}}),{data:m}=tt({queryKey:["admin-listing-lead-counts"],queryFn:async()=>{const R={};let D=0;const O=1e3;for(;;){const{data:U,error:W}=await q.from("listing_leads").select("listing_id").range(D,D+O-1);if(W)throw W;if(!U||U.length===0)break;for(const V of U)V.listing_id&&(R[V.listing_id]=(R[V.listing_id]||0)+1);if(U.length{const{data:R,error:D}=await q.from("listing_leads").select("*").eq("listing_id",i.listingId).order("created_at",{ascending:!1});if(D)throw D;return R}}),x=async(R,D,O="submit_url")=>{try{const{data:{session:U}}=await q.auth.getSession();if(!U)return;const{data:W,error:V}=await q.functions.invoke("google-indexing",{body:{action:O,listing_id:R,listing_slug:D}});if(V)throw V;if((W==null?void 0:W.configured)===!1)return;W!=null&&W.success&&re.success("Submitted to Google for indexing")}catch(U){console.error("Google indexing submission failed:",U)}},y=ft({mutationFn:async()=>{const{data:{session:R}}=await q.auth.getSession();if(!R)throw new Error("Not authenticated");const{data:D,error:O}=await q.functions.invoke("google-indexing",{body:{action:"submit_all"}});if(O)throw O;return D},onSuccess:R=>{if((R==null?void 0:R.configured)===!1){re.error("Google Indexing API not configured. Add the GOOGLE_INDEXING_SERVICE_ACCOUNT secret.");return}re.success(`Submitted ${(R==null?void 0:R.succeeded)||0} URLs to Google (${(R==null?void 0:R.failed)||0} failed)`)},onError:R=>{re.error("Failed to submit to Google"),console.error(R)}}),v=ft({mutationFn:async({id:R,approved:D,slug:O})=>{const{error:U}=await q.from("listings").update({is_approved:D}).eq("id",R);if(U)throw U;return{id:R,approved:D,slug:O}},onSuccess:R=>{s.invalidateQueries({queryKey:["admin-listings"]}),s.invalidateQueries({queryKey:["admin-listing-stats"]}),re.success(R.approved?"Listing approved":"Listing unapproved"),R.approved?x(R.id,R.slug||null,"submit_url"):x(R.id,R.slug||null,"remove_url")}}),b=ft({mutationFn:async({id:R,featured:D})=>{const{error:O}=await q.from("listings").update({is_featured:D}).eq("id",R);if(O)throw O},onSuccess:(R,{featured:D})=>{s.invalidateQueries({queryKey:["admin-listings"]}),re.success(D?"Listing featured":"Listing unfeatured")}}),w=ft({mutationFn:async R=>{const{error:D}=await q.from("listings").delete().eq("id",R);if(D)throw D},onSuccess:()=>{s.invalidateQueries({queryKey:["admin-listings"]}),s.invalidateQueries({queryKey:["admin-listing-stats"]}),re.success("Listing deleted")}}),S=ft({mutationFn:async R=>{const{error:D}=await q.from("feature_flags").update({enabled:R}).eq("key","listing_exchange_enabled");if(D)throw D},onSuccess:()=>{c(),re.success("Feature flag updated")}}),C=o??!1,E=d==null?void 0:d.filter(R=>{var U,W,V,G;const D=((U=R.city)==null?void 0:U.toLowerCase().includes(t.toLowerCase()))||((V=(W=R.agent)==null?void 0:W.name)==null?void 0:V.toLowerCase().includes(t.toLowerCase()))||((G=R.property_address)==null?void 0:G.toLowerCase().includes(t.toLowerCase())),O=r==="all"||r==="pending"&&!R.is_approved||r==="approved"&&R.is_approved;return D&&O}),I=R=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(R),P=R=>{const D={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 D[R]||D.active};return e.jsxs(Vs,{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($,{variant:"outline",size:"sm",onClick:()=>y.mutate(),disabled:y.isPending,className:"gap-2",children:[y.isPending?e.jsx(kt,{className:"h-4 w-4 animate-spin"}):e.jsx(dl,{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(Sn,{checked:C,onCheckedChange:R=>S.mutate(R)})]})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-6 gap-4",children:[e.jsx(Ne,{children:e.jsxs(Ie,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ji,{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:(h==null?void 0:h.total)||0})]})}),e.jsx(Ne,{children:e.jsxs(Ie,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Yl,{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:(h==null?void 0:h.active)||0})]})}),e.jsx(Ne,{children:e.jsxs(Ie,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Zn,{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:(h==null?void 0:h.pending)||0})]})}),e.jsx(Ne,{children:e.jsxs(Ie,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ca,{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:(h==null?void 0:h.totalViews)||0})]})}),e.jsx(Ne,{children:e.jsxs(Ie,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(zd,{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:(h==null?void 0:h.totalShares)||0})]})}),e.jsx(Ne,{children:e.jsxs(Ie,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(sc,{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:(h==null?void 0:h.totalLeads)||0}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-0.5",children:[(h==null?void 0:h.leadsLast7)||0," in last 7 days"]})]})})]}),e.jsx(Ne,{children:e.jsx(Ie,{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(Kr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(pe,{placeholder:"Search by city, address, or agent...",value:t,onChange:R=>n(R.target.value),className:"pl-9"})]}),e.jsx(ha,{value:r,onValueChange:R=>a(R),children:e.jsxs(ma,{children:[e.jsx(Zt,{value:"all",children:"All"}),e.jsx(Zt,{value:"pending",children:"Pending"}),e.jsx(Zt,{value:"approved",children:"Approved"})]})})]})})}),e.jsxs(Ne,{children:[e.jsx(Ct,{children:e.jsxs(At,{children:["Listings (",(E==null?void 0:E.length)||0,")"]})}),e.jsx(Ie,{children:e.jsx("div",{className:"overflow-x-auto",children:e.jsxs(mi,{children:[e.jsx(fi,{children:e.jsxs(En,{children:[e.jsx(Dt,{children:"Property"}),e.jsx(Dt,{children:"Agent"}),e.jsx(Dt,{children:"Price"}),e.jsx(Dt,{children:"Status"}),e.jsx(Dt,{className:"text-center",children:"Approved"}),e.jsx(Dt,{className:"text-center",children:"Featured"}),e.jsx(Dt,{children:"Views"}),e.jsx(Dt,{children:"Shares"}),e.jsx(Dt,{children:"Leads"}),e.jsx(Dt,{children:"Date"}),e.jsx(Dt,{})]})}),e.jsx(pi,{children:u?e.jsx(En,{children:e.jsx(wt,{colSpan:11,className:"text-center py-8 text-muted-foreground",children:"Loading..."})}):(E==null?void 0:E.length)===0?e.jsx(En,{children:e.jsx(wt,{colSpan:11,className:"text-center py-8 text-muted-foreground",children:"No listings found"})}):E==null?void 0:E.map(R=>{var D,O,U,W,V;return e.jsxs(En,{children:[e.jsx(wt,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[(O=(D=R.photos)==null?void 0:D[0])!=null&&O.photo_url?e.jsx("img",{src:R.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(ji,{className:"h-5 w-5 text-muted-foreground"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-sm",children:R.property_address||`${R.city}, ${R.state}`}),e.jsx("p",{className:"text-xs text-muted-foreground",children:(U=R.property_type)==null?void 0:U.replace("_"," ")})]})]})}),e.jsx(wt,{children:e.jsx("p",{className:"text-sm",children:((W=R.agent)==null?void 0:W.name)||"Unknown"})}),e.jsx(wt,{className:"font-medium",children:I(R.price)}),e.jsx(wt,{children:e.jsx(Be,{variant:"outline",className:P(R.status),children:(V=R.status)==null?void 0:V.replace("_"," ")})}),e.jsx(wt,{className:"text-center",children:e.jsx(Sn,{checked:R.is_approved??!1,onCheckedChange:G=>v.mutate({id:R.id,approved:G,slug:R.slug})})}),e.jsx(wt,{className:"text-center",children:e.jsx(Sn,{checked:R.is_featured??!1,onCheckedChange:G=>b.mutate({id:R.id,featured:G})})}),e.jsx(wt,{children:R.view_count||0}),e.jsx(wt,{children:R.share_count||0}),e.jsx(wt,{children:((m==null?void 0:m[R.id])??0)>0?e.jsx($,{variant:"link",size:"sm",className:"px-0 h-auto font-semibold text-teal-600",onClick:()=>l({listingId:R.id,label:R.property_address||`${R.city}, ${R.state}`}),children:m==null?void 0:m[R.id]}):e.jsx("span",{className:"text-muted-foreground",children:"0"})}),e.jsx(wt,{className:"text-sm text-muted-foreground",children:en(new Date(R.created_at),"MMM d, yyyy")}),e.jsx(wt,{children:e.jsxs(Uu,{children:[e.jsx(qu,{asChild:!0,children:e.jsx($,{variant:"ghost",size:"icon",children:e.jsx(h_,{className:"h-4 w-4"})})}),e.jsxs(Eu,{align:"end",children:[e.jsxs(ja,{onClick:()=>window.open(`/mission-control/listings/${R.id}`,"_blank"),children:[e.jsx(Ca,{className:"h-4 w-4 mr-2"}),"View Listing"]}),e.jsxs(ja,{onClick:()=>b.mutate({id:R.id,featured:!R.is_featured}),children:[e.jsx(Ja,{className:"h-4 w-4 mr-2"}),R.is_featured?"Unfeature":"Feature"]}),e.jsxs(ja,{className:"text-destructive",onClick:async()=>{await fo("Are you sure you want to delete this listing?")&&w.mutate(R.id)},children:[e.jsx(gr,{className:"h-4 w-4 mr-2"}),"Delete"]})]})]})})]},R.id)})})]})})})]})]}),e.jsx(zs,{open:!!i,onOpenChange:R=>!R&&l(null),children:e.jsxs(Os,{className:"max-w-3xl max-h-[80vh] overflow-y-auto",children:[e.jsxs(Us,{children:[e.jsx(Bs,{children:"Leads from listing"}),e.jsx(Ir,{children:i==null?void 0:i.label})]}),g?e.jsxs("div",{className:"py-8 text-center text-muted-foreground",children:[e.jsx(kt,{className:"h-5 w-5 animate-spin inline mr-2"}),"Loading leads..."]}):!f||f.length===0?e.jsx("div",{className:"py-8 text-center text-muted-foreground",children:"No leads yet."}):e.jsxs(mi,{children:[e.jsx(fi,{children:e.jsxs(En,{children:[e.jsx(Dt,{children:"Name"}),e.jsx(Dt,{children:"Email"}),e.jsx(Dt,{children:"Phone"}),e.jsx(Dt,{children:"Type"}),e.jsx(Dt,{children:"Captured"})]})}),e.jsx(pi,{children:f.map(R=>{var D;return e.jsxs(En,{children:[e.jsx(wt,{className:"font-medium",children:[R.first_name,R.last_name].filter(Boolean).join(" ")||"—"}),e.jsx(wt,{children:R.email}),e.jsx(wt,{children:R.phone||"—"}),e.jsx(wt,{children:e.jsx(Be,{variant:"outline",children:(D=R.lead_type)==null?void 0:D.replace("_"," ")})}),e.jsx(wt,{className:"text-sm text-muted-foreground",children:en(new Date(R.created_at),"MMM d, yyyy h:mm a")})]},R.id)})})]})]})})]})}function jor(s){return s?new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(s):"—"}function Nor(){const[s,t]=j.useState(""),[n,r]=j.useState("all"),[a,i]=j.useState("all"),{data:l,isLoading:o}=tt({queryKey:["admin-all-listing-leads"],queryFn:async()=>{const h=[];let m=0;const f=1e3;for(;;){const{data:g,error:x}=await q.from("listing_leads").select(` id, listing_id, agent_id, referred_by_agent_id, first_name, last_name, email, phone, lead_type, showing_mode, preferred_date, preferred_time, message, created_at, listing:listings!listing_leads_listing_id_fkey(id, slug, property_address, city, state, price), agent:profiles!listing_leads_agent_id_fkey(id, name, email), referrer:profiles!listing_leads_referred_by_agent_id_fkey(id, name, email) `).order("created_at",{ascending:!1}).range(m,m+f-1);if(x)throw x;if(!g||g.length===0||(h.push(...g),g.length{if(!l)return[];const h=n==="all"?0:Date.now()-parseInt(n)*24*60*60*1e3,m=s.trim().toLowerCase();return l.filter(f=>{var x,y,v,b,w,S;return h&&new Date(f.created_at).getTime(){const h=c.length,m=c.filter(x=>x.lead_type==="showing_request").length,f=new Set(c.map(x=>x.agent_id)).size,g=new Set(c.map(x=>x.listing_id)).size;return{total:h,showings:m,uniqueAgents:f,uniqueListings:g}},[c]),u=()=>{const m=[["Date","Name","Email","Phone","Type","Showing Date","Property","City","Price","Assigned Agent","Agent Email","Referred By","Message"],...c.map(y=>{var v,b,w,S,C,E;return[en(new Date(y.created_at),"yyyy-MM-dd HH:mm"),`${y.first_name||""} ${y.last_name||""}`.trim(),y.email,y.phone||"",y.lead_type,y.preferred_date?`${y.preferred_date} ${y.preferred_time||""}`:"",((v=y.listing)==null?void 0:v.property_address)||"",((b=y.listing)==null?void 0:b.city)||"",(w=y.listing)!=null&&w.price?String(y.listing.price):"",((S=y.agent)==null?void 0:S.name)||"",((C=y.agent)==null?void 0:C.email)||"",((E=y.referrer)==null?void 0:E.name)||"",(y.message||"").replace(/[\r\n]+/g," ")]})].map(y=>y.map(v=>`"${String(v).replace(/"/g,'""')}"`).join(",")).join(` `),f=new Blob([m],{type:"text/csv"}),g=URL.createObjectURL(f),x=document.createElement("a");x.href=g,x.download=`listing-leads-${en(new Date,"yyyy-MM-dd")}.csv`,x.click(),URL.revokeObjectURL(g)};return e.jsx(Vs,{title:"Listing Leads",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 Leads"}),e.jsx("p",{className:"text-muted-foreground",children:"All leads submitted through the public listings site"})]}),e.jsxs($,{variant:"outline",onClick:u,disabled:!c.length,className:"gap-2",children:[e.jsx(di,{className:"h-4 w-4"}),"Export CSV"]})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[e.jsx(Ne,{children:e.jsxs(Ie,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(sc,{className:"h-4 w-4 text-teal-600"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"Total Leads"})]}),e.jsx("p",{className:"text-2xl font-bold mt-1",children:d.total})]})}),e.jsx(Ne,{children:e.jsxs(Ie,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ta,{className:"h-4 w-4 text-purple-600"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"Showing Requests"})]}),e.jsx("p",{className:"text-2xl font-bold mt-1",children:d.showings})]})}),e.jsx(Ne,{children:e.jsxs(Ie,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(va,{className:"h-4 w-4 text-blue-600"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"Properties"})]}),e.jsx("p",{className:"text-2xl font-bold mt-1",children:d.uniqueListings})]})}),e.jsx(Ne,{children:e.jsxs(Ie,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(sc,{className:"h-4 w-4 text-amber-600"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"Agents w/ Leads"})]}),e.jsx("p",{className:"text-2xl font-bold mt-1",children:d.uniqueAgents})]})})]}),e.jsx(Ne,{children:e.jsx(Ie,{className:"p-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(Kr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(pe,{placeholder:"Search name, email, property, agent...",value:s,onChange:h=>t(h.target.value),className:"pl-9"})]}),e.jsxs(ms,{value:a,onValueChange:h=>i(h),children:[e.jsx(us,{className:"w-full sm:w-48",children:e.jsx(fs,{})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"all",children:"All Types"}),e.jsx(Ge,{value:"info_request",children:"Info Request"}),e.jsx(Ge,{value:"showing_request",children:"Showing Request"})]})]}),e.jsxs(ms,{value:n,onValueChange:h=>r(h),children:[e.jsx(us,{className:"w-full sm:w-40",children:e.jsx(fs,{})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"all",children:"All Time"}),e.jsx(Ge,{value:"7",children:"Last 7 days"}),e.jsx(Ge,{value:"30",children:"Last 30 days"}),e.jsx(Ge,{value:"90",children:"Last 90 days"})]})]})]})})}),e.jsxs(Ne,{children:[e.jsx(Ct,{children:e.jsxs(At,{children:["Leads (",c.length,")"]})}),e.jsx(Ie,{children:e.jsx("div",{className:"overflow-x-auto",children:e.jsxs(mi,{children:[e.jsx(fi,{children:e.jsxs(En,{children:[e.jsx(Dt,{children:"Date"}),e.jsx(Dt,{children:"Lead"}),e.jsx(Dt,{children:"Contact"}),e.jsx(Dt,{children:"Property"}),e.jsx(Dt,{children:"Type"}),e.jsx(Dt,{children:"Assigned To"}),e.jsx(Dt,{children:"Referred By"}),e.jsx(Dt,{children:"Message"})]})}),e.jsx(pi,{children:o?e.jsx(En,{children:e.jsx(wt,{colSpan:8,className:"text-center py-8 text-muted-foreground",children:"Loading..."})}):c.length===0?e.jsx(En,{children:e.jsx(wt,{colSpan:8,className:"text-center py-8 text-muted-foreground",children:"No leads found"})}):c.map(h=>{var m,f;return e.jsxs(En,{children:[e.jsxs(wt,{className:"whitespace-nowrap text-sm",children:[en(new Date(h.created_at),"MMM d, yyyy"),e.jsx("div",{className:"text-xs text-muted-foreground",children:en(new Date(h.created_at),"h:mm a")})]}),e.jsx(wt,{children:e.jsx("div",{className:"font-medium",children:`${h.first_name||""} ${h.last_name||""}`.trim()||"—"})}),e.jsx(wt,{children:e.jsxs("div",{className:"flex flex-col gap-1 text-sm",children:[e.jsxs("a",{href:`mailto:${h.email}`,className:"flex items-center gap-1 hover:underline",children:[e.jsx(mn,{className:"h-3 w-3"}),h.email]}),h.phone&&e.jsxs("a",{href:`tel:${h.phone}`,className:"flex items-center gap-1 text-muted-foreground hover:underline",children:[e.jsx(Da,{className:"h-3 w-3"}),h.phone]})]})}),e.jsx(wt,{children:h.listing?e.jsxs(wr,{to:`/public/listing/${h.listing.slug||h.listing.id}`,target:"_blank",className:"group",children:[e.jsxs("div",{className:"font-medium text-sm group-hover:underline flex items-center gap-1",children:[h.listing.property_address||"Untitled",e.jsx(kr,{className:"h-3 w-3 opacity-60"})]}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[[h.listing.city,h.listing.state].filter(Boolean).join(", ")," · ",jor(h.listing.price)]})]}):e.jsx("span",{className:"text-muted-foreground text-sm",children:"—"})}),e.jsxs(wt,{children:[e.jsx(Be,{variant:h.lead_type==="showing_request"?"default":"secondary",className:"text-xs",children:h.lead_type==="showing_request"?"Showing":"Info"}),h.preferred_date&&e.jsxs("div",{className:"text-xs text-muted-foreground mt-1",children:[h.preferred_date," ",h.preferred_time||""]}),h.showing_mode&&e.jsx("div",{className:"text-xs text-muted-foreground capitalize",children:h.showing_mode.replace("_"," ")})]}),e.jsxs(wt,{children:[e.jsx("div",{className:"text-sm font-medium",children:((m=h.agent)==null?void 0:m.name)||"—"}),((f=h.agent)==null?void 0:f.email)&&e.jsx("div",{className:"text-xs text-muted-foreground",children:h.agent.email})]}),e.jsx(wt,{children:h.referrer?e.jsxs("div",{children:[e.jsx("div",{className:"text-sm",children:h.referrer.name}),e.jsx("div",{className:"text-xs text-muted-foreground",children:h.referrer.email})]}):e.jsx("span",{className:"text-muted-foreground text-sm",children:"Direct"})}),e.jsx(wt,{className:"max-w-xs",children:h.message?e.jsxs("div",{className:"text-xs text-muted-foreground line-clamp-3 flex items-start gap-1",children:[e.jsx(eo,{className:"h-3 w-3 mt-0.5 shrink-0"}),h.message]}):e.jsx("span",{className:"text-muted-foreground text-sm",children:"—"})})]},h.id)})})]})})})]})]})})}const rU={new_listing_alerts:{label:"New Listing Alerts",icon:qy,color:"bg-amber-100 text-amber-800"},exit_intent:{label:"Exit Intent",icon:Wz,color:"bg-rose-100 text-rose-800"},saved_listing:{label:"Saved Home",icon:Jo,color:"bg-pink-100 text-pink-800"},saved_search:{label:"Saved Search",icon:Kr,color:"bg-blue-100 text-blue-800"},buyer_guide:{label:"Buyer's Guide",icon:Xf,color:"bg-emerald-100 text-emerald-800"}},hEt=[{key:"24h",label:"Last 24h",days:1},{key:"7d",label:"Last 7 days",days:7},{key:"30d",label:"Last 30 days",days:30},{key:"all",label:"All time",days:0}];function mEt(s){return new Date(s).toLocaleString("en-US",{timeZone:"America/New_York",month:"short",day:"numeric",year:"numeric",hour:"numeric",minute:"2-digit"})}function kor(){const[s,t]=j.useState([]),[n,r]=j.useState(!0),[a,i]=j.useState("30d"),[l,o]=j.useState("all"),[c,d]=j.useState("");j.useEffect(()=>{let f=!1;return(async()=>{r(!0);let g=q.from("public_site_leads").select("*").order("created_at",{ascending:!1}).limit(2e3);const x=hEt.find(b=>b.key===a);if(x&&x.days>0){const b=new Date(Date.now()-x.days*864e5).toISOString();g=g.gte("created_at",b)}const{data:y,error:v}=await g;f||(v?(console.error(v),t([])):t(y||[]),r(!1))})(),()=>{f=!0}},[a]);const u=j.useMemo(()=>s.filter(f=>{if(l!=="all"&&f.lead_type!==l)return!1;if(c){const g=c.toLowerCase();if(![f.email,f.first_name,f.last_name,f.phone,f.source_page,f.referrer].filter(Boolean).join(" ").toLowerCase().includes(g))return!1}return!0}),[s,l,c]),h=j.useMemo(()=>{const f=u.length,g=new Set(u.map(y=>y.email.toLowerCase())).size,x={};return u.forEach(y=>{x[y.lead_type]=(x[y.lead_type]||0)+1}),{total:f,uniqueEmails:g,byType:x}},[u]),m=()=>{const g=[["Date (ET)","Type","Email","First","Last","Phone","Listing ID","Source Page","Referrer","Criteria"].join(",")];u.forEach(b=>{var S;const w=[mEt(b.created_at),((S=rU[b.lead_type])==null?void 0:S.label)||b.lead_type,b.email,b.first_name||"",b.last_name||"",b.phone||"",b.listing_id||"",b.source_page||"",b.referrer||"",b.criteria?JSON.stringify(b.criteria):""].map(C=>`"${String(C).replace(/"/g,'""')}"`);g.push(w.join(","))});const x=new Blob([g.join(` `)],{type:"text/csv"}),y=URL.createObjectURL(x),v=document.createElement("a");v.href=y,v.download=`public-site-leads-${new Date().toISOString().slice(0,10)}.csv`,v.click(),URL.revokeObjectURL(y)};return e.jsxs("div",{className:"min-h-screen bg-slate-50",children:[e.jsx(Ml,{children:e.jsx("title",{children:"Public Site Leads — Admin"})}),e.jsx("div",{className:"border-b bg-white",children:e.jsxs("div",{className:"max-w-7xl mx-auto px-6 py-4 flex items-center justify-between gap-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(wr,{to:"/admin",children:e.jsxs($,{variant:"ghost",size:"sm",children:[e.jsx(qa,{className:"h-4 w-4 mr-1"}),"Admin"]})}),e.jsxs("div",{children:[e.jsx("h1",{className:"text-lg font-semibold",children:"Public Site Leads"}),e.jsx("p",{className:"text-xs text-slate-500",children:"listings.relevelup.com — alerts, exit intent & saved homes"})]})]}),e.jsxs($,{onClick:m,variant:"outline",size:"sm",children:[e.jsx(di,{className:"h-4 w-4 mr-1"})," Export CSV"]})]})}),e.jsxs("div",{className:"max-w-7xl mx-auto px-6 py-6 space-y-6",children:[e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-5 gap-3",children:[e.jsx(Ne,{children:e.jsxs(Ie,{className:"p-4",children:[e.jsx("div",{className:"text-xs text-slate-500 uppercase tracking-wide",children:"Total Leads"}),e.jsx("div",{className:"text-2xl font-bold mt-1",children:h.total}),e.jsxs("div",{className:"text-xs text-slate-500 mt-1",children:[h.uniqueEmails," unique"]})]})}),Object.keys(rU).map(f=>{const g=rU[f],x=g.icon;return e.jsx(Ne,{children:e.jsxs(Ie,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-1.5 text-xs text-slate-500 uppercase tracking-wide",children:[e.jsx(x,{className:"h-3.5 w-3.5"}),g.label]}),e.jsx("div",{className:"text-2xl font-bold mt-1",children:h.byType[f]||0})]})},f)})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs(ms,{value:a,onValueChange:f=>i(f),children:[e.jsx(us,{className:"w-[160px] bg-white",children:e.jsx(fs,{})}),e.jsx(hs,{children:hEt.map(f=>e.jsx(Ge,{value:f.key,children:f.label},f.key))})]}),e.jsxs(ms,{value:l,onValueChange:o,children:[e.jsx(us,{className:"w-[200px] bg-white",children:e.jsx(fs,{})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"all",children:"All lead types"}),Object.keys(rU).map(f=>e.jsx(Ge,{value:f,children:rU[f].label},f))]})]}),e.jsxs("div",{className:"relative flex-1 min-w-[200px] max-w-md",children:[e.jsx(Kr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-slate-400"}),e.jsx(pe,{placeholder:"Search name, email, phone…",value:c,onChange:f=>d(f.target.value),className:"pl-9 bg-white"})]}),e.jsxs("div",{className:"ml-auto text-sm text-slate-500",children:[u.length," ",u.length===1?"lead":"leads"]})]}),e.jsx(Ne,{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-slate-50 text-left text-xs uppercase tracking-wide text-slate-500",children:[e.jsx("th",{className:"px-4 py-3",children:"Date"}),e.jsx("th",{className:"px-4 py-3",children:"Type"}),e.jsx("th",{className:"px-4 py-3",children:"Contact"}),e.jsx("th",{className:"px-4 py-3",children:"Phone"}),e.jsx("th",{className:"px-4 py-3",children:"Details"}),e.jsx("th",{className:"px-4 py-3",children:"Source"})]})}),e.jsx("tbody",{children:n?e.jsx("tr",{children:e.jsx("td",{colSpan:6,className:"px-4 py-12 text-center text-slate-500",children:"Loading…"})}):u.length===0?e.jsx("tr",{children:e.jsx("td",{colSpan:6,className:"px-4 py-12 text-center text-slate-500",children:"No leads yet in this range."})}):u.map(f=>{const g=rU[f.lead_type],x=g==null?void 0:g.icon,y=[f.first_name,f.last_name].filter(Boolean).join(" ")||"—";return e.jsxs("tr",{className:"border-b hover:bg-slate-50/60",children:[e.jsx("td",{className:"px-4 py-3 whitespace-nowrap text-slate-600 text-xs",children:mEt(f.created_at)}),e.jsx("td",{className:"px-4 py-3 whitespace-nowrap",children:e.jsxs(Be,{className:`${(g==null?void 0:g.color)||""} font-normal`,variant:"secondary",children:[x?e.jsx(x,{className:"h-3 w-3 mr-1"}):null,(g==null?void 0:g.label)||f.lead_type]})}),e.jsxs("td",{className:"px-4 py-3",children:[e.jsx("div",{className:"font-medium text-slate-900",children:y}),e.jsxs("a",{href:`mailto:${f.email}`,className:"text-xs text-blue-600 hover:underline inline-flex items-center gap-1",children:[e.jsx(mn,{className:"h-3 w-3"}),f.email]})]}),e.jsx("td",{className:"px-4 py-3 whitespace-nowrap",children:f.phone?e.jsxs("a",{href:`tel:${f.phone}`,className:"text-xs text-blue-600 hover:underline inline-flex items-center gap-1",children:[e.jsx(Da,{className:"h-3 w-3"}),f.phone]}):e.jsx("span",{className:"text-slate-400 text-xs",children:"—"})}),e.jsxs("td",{className:"px-4 py-3 text-xs text-slate-600 max-w-xs",children:[f.listing_id&&e.jsxs("div",{className:"mb-0.5",children:["Listing: ",e.jsxs("span",{className:"font-mono text-[10px]",children:[f.listing_id.slice(0,8),"…"]})]}),f.criteria&&Object.keys(f.criteria).length>0&&e.jsx("div",{className:"text-slate-500 line-clamp-2",children:Object.entries(f.criteria).map(([v,b])=>`${v}: ${b}`).join(" · ")})]}),e.jsxs("td",{className:"px-4 py-3 text-xs text-slate-500 max-w-xs truncate",children:[f.source_page&&e.jsxs("div",{className:"inline-flex items-center gap-1",children:[e.jsx(kr,{className:"h-3 w-3"}),e.jsx("span",{className:"truncate",children:f.source_page})]}),f.referrer&&e.jsxs("div",{className:"text-slate-400 truncate",children:["from ",f.referrer]})]})]},f.id)})})]})})})]})]})}const Sor=()=>{var h,m;const[s,t]=j.useState(""),[n,r]=j.useState(null),{data:a,isLoading:i}=tt({queryKey:["membership-reviews"],queryFn:async()=>{const{data:f,error:g}=await q.from("membership_reviews").select("*").order("created_at",{ascending:!1});if(g)throw g;const x=(f==null?void 0:f.map(b=>b.user_id))||[],{data:y}=await q.from("profiles").select("id, name, email").in("id",x);return f==null?void 0:f.map(b=>({...b,profiles:(y==null?void 0:y.find(w=>w.id===b.user_id))||null}))}}),l=a==null?void 0:a.filter(f=>{var x,y,v,b,w;const g=s.toLowerCase();return((y=(x=f.profiles)==null?void 0:x.name)==null?void 0:y.toLowerCase().includes(g))||((b=(v=f.profiles)==null?void 0:v.email)==null?void 0:b.toLowerCase().includes(g))||((w=f.review_text)==null?void 0:w.toLowerCase().includes(g))}),o=a!=null&&a.length?(a.reduce((f,g)=>f+g.rating,0)/a.length).toFixed(1):"0.0",c=a==null?void 0:a.reduce((f,g)=>(f[g.rating]=(f[g.rating]||0)+1,f),{}),d=(a==null?void 0:a.filter(f=>f.posted_to_google).length)||0,u=f=>e.jsx("div",{className:"flex gap-0.5",children:[1,2,3,4,5].map(g=>e.jsx(Ja,{className:Pt("h-4 w-4",f>=g?"fill-yellow-400 text-yellow-400":"text-muted-foreground")},g))});return e.jsx(Vs,{children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(Fm,{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(Ne,{children:e.jsxs(Ct,{className:"pb-2",children:[e.jsx(Gn,{children:"Total Reviews"}),e.jsx(At,{className:"text-3xl",children:(a==null?void 0:a.length)||0})]})}),e.jsx(Ne,{children:e.jsxs(Ct,{className:"pb-2",children:[e.jsx(Gn,{children:"Average Rating"}),e.jsxs(At,{className:"flex items-center gap-2 text-3xl",children:[o,e.jsx(Ja,{className:"h-6 w-6 fill-yellow-400 text-yellow-400"})]})]})}),e.jsx(Ne,{children:e.jsxs(Ct,{className:"pb-2",children:[e.jsx(Gn,{children:"5-Star Reviews"}),e.jsx(At,{className:"text-3xl",children:(c==null?void 0:c[5])||0})]})}),e.jsx(Ne,{children:e.jsxs(Ct,{className:"pb-2",children:[e.jsx(Gn,{children:"Posted to Google"}),e.jsxs(At,{className:"flex items-center gap-2 text-3xl",children:[d,e.jsx(kr,{className:"h-5 w-5 text-muted-foreground"})]})]})})]}),e.jsxs("div",{className:"relative max-w-sm",children:[e.jsx(Kr,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(pe,{placeholder:"Search by name, email, or review...",value:s,onChange:f=>t(f.target.value),className:"pl-9"})]}),e.jsx(Ne,{children:e.jsx(Ie,{className:"p-0",children:e.jsxs(mi,{children:[e.jsx(fi,{children:e.jsxs(En,{children:[e.jsx(Dt,{children:"Member"}),e.jsx(Dt,{children:"Rating"}),e.jsx(Dt,{className:"hidden md:table-cell",children:"Review"}),e.jsx(Dt,{children:"Google"}),e.jsx(Dt,{children:"Date"})]})}),e.jsx(pi,{children:i?e.jsx(En,{children:e.jsx(wt,{colSpan:5,className:"text-center py-8",children:"Loading reviews..."})}):(l==null?void 0:l.length)===0?e.jsx(En,{children:e.jsx(wt,{colSpan:5,className:"text-center py-8 text-muted-foreground",children:"No reviews found"})}):l==null?void 0:l.map(f=>{var g,x;return e.jsxs(En,{className:"cursor-pointer hover:bg-muted/50",onClick:()=>r(f),children:[e.jsx(wt,{children:e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:((g=f.profiles)==null?void 0:g.name)||"Unknown"}),e.jsx("div",{className:"text-sm text-muted-foreground",children:(x=f.profiles)==null?void 0:x.email})]})}),e.jsx(wt,{children:u(f.rating)}),e.jsx(wt,{className:"hidden md:table-cell max-w-xs",children:e.jsx("p",{className:"truncate text-sm text-muted-foreground",children:f.review_text||"-"})}),e.jsx(wt,{children:f.posted_to_google?e.jsx(Be,{variant:"secondary",className:"bg-green-100 text-green-800",children:"Posted"}):e.jsx(Be,{variant:"outline",children:"No"})}),e.jsx(wt,{className:"text-sm text-muted-foreground",children:en(new Date(f.created_at),"MMM d, yyyy")})]},f.id)})})]})})}),e.jsx(zs,{open:!!n,onOpenChange:()=>r(null),children:e.jsxs(Os,{className:"max-w-lg",children:[e.jsx(Us,{children:e.jsx(Bs,{children:"Review Details"})}),n&&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:((h=n.profiles)==null?void 0:h.name)||"Unknown Member"}),((m=n.profiles)==null?void 0:m.email)&&e.jsxs("a",{href:`mailto:${n.profiles.email}`,className:"flex items-center gap-1 text-sm text-muted-foreground hover:text-primary",children:[e.jsx(mn,{className:"h-3 w-3"}),n.profiles.email]})]}),e.jsxs("div",{className:"text-right",children:[u(n.rating),e.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:[n.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:n.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(Ta,{className:"h-4 w-4"}),en(new Date(n.created_at),"MMMM d, yyyy 'at' h:mm a")]}),n.posted_to_google?e.jsxs(Be,{variant:"secondary",className:"bg-green-100 text-green-800",children:[e.jsx(kr,{className:"h-3 w-3 mr-1"}),"Posted to Google"]}):e.jsx(Be,{variant:"outline",children:"Not posted to Google"})]})]})]})})]})})},fEt={agent_card:"Agent Card",listing:"Listing",lead_site:"Lead Site",guest_book:"Guest Book",landing_page:"Landing Page",connect_page:"Connect Page",booking:"Booking"},Cor={sent:"bg-green-100 text-green-800",backfilled:"bg-blue-100 text-blue-800",failed:"bg-red-100 text-red-800",pending:"bg-yellow-100 text-yellow-800"};function Aor(){const[s,t]=j.useState(""),[n,r]=j.useState("all"),[a,i]=j.useState("all"),[l,o]=j.useState("7"),{data:c,isLoading:d}=tt({queryKey:["lead-notification-log",l],queryFn:async()=>{const m=new Date(Date.now()-Number(l)*864e5).toISOString(),{data:f,error:g}=await q.from("lead_notification_log").select("*").gte("created_at",m).order("created_at",{ascending:!1}).limit(2e3);if(g)throw g;return f||[]}}),u=j.useMemo(()=>{const m=s.trim().toLowerCase();return(c||[]).filter(f=>n!=="all"&&f.source!==n||a!=="all"&&f.status!==a?!1:m?[f.agent_name,f.agent_email,f.lead_name,f.lead_email,f.lead_phone,f.subject].some(g=>(g||"").toLowerCase().includes(m)):!0)},[c,s,n,a]),h=j.useMemo(()=>{const m=u.length,f=u.filter(y=>y.status==="sent"||y.status==="backfilled").length,g=u.filter(y=>y.status==="failed").length,x=new Set(u.map(y=>y.agent_user_id).filter(Boolean)).size;return{total:m,sent:f,failed:g,agents:x}},[u]);return e.jsx(Vs,{children:e.jsxs("div",{className:"container mx-auto py-6 space-y-6",children:[e.jsx(Fm,{title:"Lead Notifications",description:"Every new-lead notification sent to agents — agent cards, listings, lead sites, guest book sign-ins, landing pages, connect pages, and bookings."}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[e.jsx(Ne,{children:e.jsxs(Ie,{className:"p-4",children:[e.jsx("div",{className:"text-sm text-muted-foreground",children:"Total"}),e.jsx("div",{className:"text-2xl font-bold",children:h.total})]})}),e.jsx(Ne,{children:e.jsxs(Ie,{className:"p-4",children:[e.jsx("div",{className:"text-sm text-muted-foreground",children:"Sent"}),e.jsx("div",{className:"text-2xl font-bold text-green-600",children:h.sent})]})}),e.jsx(Ne,{children:e.jsxs(Ie,{className:"p-4",children:[e.jsx("div",{className:"text-sm text-muted-foreground",children:"Failed"}),e.jsx("div",{className:"text-2xl font-bold text-red-600",children:h.failed})]})}),e.jsx(Ne,{children:e.jsxs(Ie,{className:"p-4",children:[e.jsx("div",{className:"text-sm text-muted-foreground",children:"Unique Agents"}),e.jsx("div",{className:"text-2xl font-bold",children:h.agents})]})})]}),e.jsxs("div",{className:"flex flex-col md:flex-row gap-3",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(Kr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(pe,{placeholder:"Search agent or lead name, email, phone…",value:s,onChange:m=>t(m.target.value),className:"pl-9"})]}),e.jsxs(ms,{value:n,onValueChange:r,children:[e.jsx(us,{className:"w-full md:w-48",children:e.jsx(fs,{placeholder:"Source"})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"all",children:"All Sources"}),Object.entries(fEt).map(([m,f])=>e.jsx(Ge,{value:m,children:f},m))]})]}),e.jsxs(ms,{value:a,onValueChange:i,children:[e.jsx(us,{className:"w-full md:w-40",children:e.jsx(fs,{placeholder:"Status"})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"all",children:"All Statuses"}),e.jsx(Ge,{value:"sent",children:"Sent"}),e.jsx(Ge,{value:"backfilled",children:"Backfilled"}),e.jsx(Ge,{value:"failed",children:"Failed"})]})]}),e.jsxs(ms,{value:l,onValueChange:o,children:[e.jsx(us,{className:"w-full md:w-36",children:e.jsx(fs,{})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"1",children:"Last 24h"}),e.jsx(Ge,{value:"7",children:"Last 7 days"}),e.jsx(Ge,{value:"14",children:"Last 14 days"}),e.jsx(Ge,{value:"30",children:"Last 30 days"})]})]})]}),e.jsx(Ne,{children:e.jsx(Ie,{className:"p-0",children:e.jsxs(mi,{children:[e.jsx(fi,{children:e.jsxs(En,{children:[e.jsx(Dt,{children:"When"}),e.jsx(Dt,{children:"Source"}),e.jsx(Dt,{children:"Agent"}),e.jsx(Dt,{children:"Lead"}),e.jsx(Dt,{children:"Status"})]})}),e.jsx(pi,{children:d?e.jsx(En,{children:e.jsx(wt,{colSpan:5,className:"text-center py-8 text-muted-foreground",children:"Loading…"})}):u.length===0?e.jsx(En,{children:e.jsx(wt,{colSpan:5,className:"text-center py-8 text-muted-foreground",children:"No notifications match the current filters."})}):u.map(m=>e.jsxs(En,{children:[e.jsx(wt,{className:"whitespace-nowrap text-sm",children:en(new Date(m.created_at),"MMM d, yyyy h:mm a")}),e.jsx(wt,{children:e.jsx(Be,{variant:"secondary",children:fEt[m.source]||m.source})}),e.jsxs(wt,{children:[e.jsx("div",{className:"font-medium",children:m.agent_name||"—"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:m.agent_email||"—"})]}),e.jsxs(wt,{children:[e.jsx("div",{className:"font-medium",children:m.lead_name||"—"}),e.jsxs("div",{className:"text-xs text-muted-foreground flex flex-wrap gap-x-3 gap-y-1",children:[m.lead_email&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(mn,{className:"h-3 w-3"}),m.lead_email]}),m.lead_phone&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Da,{className:"h-3 w-3"}),m.lead_phone]})]})]}),e.jsxs(wt,{children:[e.jsx(Be,{className:Cor[m.status]||"",children:m.status}),m.error_message&&e.jsx("div",{className:"text-xs text-red-600 mt-1 max-w-[220px] truncate",title:m.error_message,children:m.error_message})]})]},m.id))})]})})}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Historical entries (before this feature was enabled) are marked as ",e.jsx("em",{children:"backfilled"})," and reconstructed from the underlying lead records. New leads are logged automatically going forward."]})]})})}const Eor=[{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"}],Tor=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 Mor(){const s=Vt(),{user:t}=vs(),[n,r]=j.useState(!1),[a,i]=j.useState(!1),[l,o]=j.useState(!1),{data:c,isLoading:d}=tt({queryKey:["weekly-digest-settings"],queryFn:async()=>{const{data:P,error:R}=await q.from("weekly_digest_settings").select("*").single();if(R)throw R;return P}}),{data:u,isLoading:h}=tt({queryKey:["weekly-digest-logs"],queryFn:async()=>{const{data:P,error:R}=await q.from("weekly_digest_logs").select("*").order("sent_at",{ascending:!1}).limit(100);if(R)throw R;return P}}),{data:m}=tt({queryKey:["digest-subscriber-count"],queryFn:async()=>{const{count:P,error:R}=await q.from("profiles").select("id",{count:"exact",head:!0}).eq("digest_opt_out",!1).not("email","is",null);if(R)throw R;return P||0}}),{data:f,refetch:g}=tt({queryKey:["digest-queue-status"],queryFn:async()=>{const P=new Date;P.setUTCHours(0,0,0,0);const[R,D,O,U]=await Promise.all([q.from("weekly_digest_send_queue").select("id",{count:"exact",head:!0}).eq("status","pending").gte("created_at",P.toISOString()),q.from("weekly_digest_send_queue").select("id",{count:"exact",head:!0}).eq("status","processing").gte("created_at",P.toISOString()),q.from("weekly_digest_send_queue").select("id",{count:"exact",head:!0}).eq("status","sent").gte("created_at",P.toISOString()),q.from("weekly_digest_send_queue").select("id",{count:"exact",head:!0}).eq("status","failed").gte("created_at",P.toISOString())]);return{pending:R.count||0,processing:D.count||0,sent:O.count||0,failed:U.count||0,total:(R.count||0)+(D.count||0)+(O.count||0)+(U.count||0)}},refetchInterval:5e3});j.useEffect(()=>{if(f&&(f.pending>0||f.processing>0)){const P=setInterval(()=>{g(),s.invalidateQueries({queryKey:["weekly-digest-logs"]}),s.invalidateQueries({queryKey:["digest-today-failed-count"]}),s.invalidateQueries({queryKey:["digest-today-missing-count"]})},5e3);return()=>clearInterval(P)}},[f,g,s]);const{data:x=0}=tt({queryKey:["digest-today-failed-count"],queryFn:async()=>{const P=new Date;P.setUTCHours(0,0,0,0);const{count:R,error:D}=await q.from("weekly_digest_logs").select("id",{count:"exact",head:!0}).eq("delivery_status","failed").gte("sent_at",P.toISOString());if(D)throw D;return R||0}}),y=ft({mutationFn:async P=>{const{error:R}=await q.from("weekly_digest_settings").update(P).eq("id",c==null?void 0:c.id);if(R)throw R},onSuccess:()=>{s.invalidateQueries({queryKey:["weekly-digest-settings"]}),re.success("Settings updated")},onError:P=>{re.error("Failed to update settings: "+P.message)}}),v=async()=>{r(!0);try{const{data:P,error:R}=await q.functions.invoke("send-weekly-digest",{body:{manual:!0}});if(R)throw R;P.queued?re.success(`${P.queued.toLocaleString()} emails queued! They'll be sent automatically (~80/minute).`):P.sent!==void 0&&re.success(`Digest sent! ${P.sent} emails delivered, ${P.failed} failed`),g(),s.invalidateQueries({queryKey:["weekly-digest-logs"]})}catch(P){re.error("Failed to send digest: "+P.message)}finally{r(!1)}},b=async()=>{var P,R,D,O,U,W;if(!(t!=null&&t.email)){re.error("No email found for your account");return}i(!0);try{const{data:V,error:G}=await q.functions.invoke("send-weekly-digest",{body:{preview:!0,previewEmail:t.email}});if(G)throw G;const Y=V==null?void 0:V.resendId,X=V==null?void 0:V.resendDetails,ae=X==null?void 0:X.status,ie=((P=X==null?void 0:X.body)==null?void 0:P.status)||((D=(R=X==null?void 0:X.body)==null?void 0:R.data)==null?void 0:D.status),ne=((U=(O=X==null?void 0:X.body)==null?void 0:O.error)==null?void 0:U.message)||((W=X==null?void 0:X.body)==null?void 0:W.message);re.success(Y?`Preview accepted by email provider (id: ${Y})${ae?`, status check: ${ae}`:""}${ie?`, provider: ${ie}`:""}${ne?` (${ne})`:""}. Check spam/promotions—delivery can take a few minutes.`:"Preview accepted by email provider. Check spam/promotions—delivery can take a few minutes.")}catch(V){re.error("Failed to send preview: "+V.message)}finally{i(!1)}},w=async()=>{o(!0);try{const{data:P,error:R}=await q.functions.invoke("send-weekly-digest",{body:{retryFailed:!0}});if(R)throw R;P.queued===0||P.sent===0&&P.failed===0&&!P.queued?re.info("No failed emails to retry"):P.queued?re.success(`${P.queued} emails queued for retry!`):re.success(`Retry complete! ${P.sent} emails delivered, ${P.failed} failed`),g(),s.invalidateQueries({queryKey:["weekly-digest-logs"]}),s.invalidateQueries({queryKey:["digest-today-failed-count"]}),s.invalidateQueries({queryKey:["digest-today-missing-count"]})}catch(P){re.error("Failed to retry: "+P.message)}finally{o(!1)}},S=f!=null&&f.total?Math.round((f.sent+f.failed)/f.total*100):0,C=((f==null?void 0:f.pending)||0)>0||((f==null?void 0:f.processing)||0)>0,{data:E}=tt({queryKey:["digest-delivery-stats"],queryFn:async()=>{var W,V;const P=new Date;P.setUTCHours(0,0,0,0);const[R,D,O,U]=await Promise.all([q.from("weekly_digest_logs").select("id",{count:"exact",head:!0}).eq("delivery_status","sent").gte("sent_at",P.toISOString()),q.from("weekly_digest_logs").select("id",{count:"exact",head:!0}).eq("delivery_status","failed").gte("sent_at",P.toISOString()),q.from("weekly_digest_logs").select("id",{count:"exact",head:!0}).eq("has_agent_os_activity",!0).gte("sent_at",P.toISOString()),q.from("weekly_digest_logs").select("sent_at").order("sent_at",{ascending:!1}).limit(1)]);return{totalSent:R.count||0,totalFailed:D.count||0,agentOsEngaged:O.count||0,lastSent:((V=(W=U.data)==null?void 0:W[0])==null?void 0:V.sent_at)||null}},refetchInterval:C?5e3:!1}),I={totalSent:(E==null?void 0:E.totalSent)||0,totalFailed:(E==null?void 0:E.totalFailed)||0,lastSent:E==null?void 0:E.lastSent,agentOsEngaged:(E==null?void 0:E.agentOsEngaged)||0};return d?e.jsx(Vs,{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(Vs,{title:"Weekly Digest",description:"Configure and manage automated weekly email digests for members",children:e.jsxs(ha,{defaultValue:"settings",className:"space-y-6",children:[e.jsxs(ma,{children:[e.jsxs(Zt,{value:"settings",className:"flex items-center gap-2",children:[e.jsx(Sd,{className:"h-4 w-4"}),"Settings"]}),e.jsxs(Zt,{value:"stats",className:"flex items-center gap-2",children:[e.jsx(Wl,{className:"h-4 w-4"}),"Delivery Stats"]})]}),e.jsxs(Xt,{value:"settings",className:"space-y-6",children:[C&&f&&e.jsx(Ne,{className:"border-primary/50 bg-primary/5",children:e.jsxs(Ie,{className:"pt-6",children:[e.jsxs("div",{className:"flex items-center gap-4 mb-4",children:[e.jsx(kt,{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:[f.sent.toLocaleString()," sent, ",f.pending.toLocaleString()," pending",f.failed>0&&`, ${f.failed} failed`]})]}),e.jsxs("span",{className:"text-sm font-medium",children:[S,"%"]})]}),e.jsx(Yi,{value:S,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(f.pending/80)," min"]})]})}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-4 gap-4",children:[e.jsx(Ne,{children:e.jsx(Ie,{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(Zn,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:m}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Subscribers"})]})]})})}),e.jsx(Ne,{children:e.jsx(Ie,{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(qr,{className:"h-5 w-5 text-emerald-500"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:I.totalSent}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Delivered"})]})]})})}),e.jsx(Ne,{children:e.jsx(Ie,{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(ku,{className:"h-5 w-5 text-destructive"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:I.totalFailed}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Failed"})]})]})})}),e.jsx(Ne,{children:e.jsx(Ie,{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(da,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:I.lastSent?en(new Date(I.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(Ne,{children:[e.jsxs(Ct,{children:[e.jsxs(At,{className:"flex items-center gap-2",children:[e.jsx(da,{className:"h-5 w-5"}),"Schedule"]}),e.jsx(Gn,{children:"Configure when the digest is sent"})]}),e.jsxs(Ie,{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(ee,{children:"Enable Weekly Digest"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Send automated weekly emails to members"})]}),e.jsx(Sn,{checked:c==null?void 0:c.is_enabled,onCheckedChange:P=>y.mutate({is_enabled:P})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Cron Frequency"}),e.jsxs(ms,{value:(c==null?void 0:c.cron_frequency)||"daily",onValueChange:P=>y.mutate({cron_frequency:P}),children:[e.jsx(us,{children:e.jsx(fs,{})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"daily",children:"Daily (runs once at selected time)"}),e.jsx(Ge,{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(ee,{children:"Day of Week"}),e.jsxs(ms,{value:String(c==null?void 0:c.send_day),onValueChange:P=>y.mutate({send_day:parseInt(P)}),children:[e.jsx(us,{children:e.jsx(fs,{})}),e.jsx(hs,{children:Eor.map(P=>e.jsx(Ge,{value:P.value,children:P.label},P.value))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Time (UTC)"}),e.jsxs(ms,{value:String(c==null?void 0:c.send_hour),onValueChange:P=>y.mutate({send_hour:parseInt(P)}),disabled:(c==null?void 0:c.cron_frequency)==="daily",children:[e.jsx(us,{children:e.jsx(fs,{})}),e.jsx(hs,{children:Tor.map(P=>e.jsx(Ge,{value:P.value,children:P.label},P.value))})]})]})]}),e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsxs($,{onClick:b,disabled:a,variant:"outline",className:"flex-1",children:[e.jsx(Ca,{className:"h-4 w-4 mr-2"}),a?"Sending...":"Send Preview to Me"]}),e.jsxs($,{onClick:v,disabled:n,className:"flex-1",children:[e.jsx(Yr,{className:"h-4 w-4 mr-2"}),n?"Sending...":"Send to All"]})]}),x>0&&e.jsxs($,{onClick:w,disabled:l,variant:"outline",className:"w-full",children:[e.jsx(ro,{className:`h-4 w-4 mr-2 ${l?"animate-spin":""}`}),l?"Retrying...":`Retry ${x} Failed`]})]})]})]}),e.jsxs(Ne,{children:[e.jsxs(Ct,{children:[e.jsxs(At,{className:"flex items-center gap-2",children:[e.jsx(Jr,{className:"h-5 w-5"}),"Content Sections"]}),e.jsx(Gn,{children:"Choose what to include in the digest"})]}),e.jsxs(Ie,{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(Jr,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(ee,{children:"New Resources"})]}),e.jsx(Sn,{checked:c==null?void 0:c.include_new_resources,onCheckedChange:P=>y.mutate({include_new_resources:P})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Zn,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(ee,{children:"Community Highlights"})]}),e.jsx(Sn,{checked:c==null?void 0:c.include_community_posts,onCheckedChange:P=>y.mutate({include_community_posts:P})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Wl,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(ee,{children:"Agent OS Stats"})]}),e.jsx(Sn,{checked:c==null?void 0:c.include_agent_os_stats,onCheckedChange:P=>y.mutate({include_agent_os_stats:P})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ta,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(ee,{children:"Upcoming Events"})]}),e.jsx(Sn,{checked:c==null?void 0:c.include_upcoming_events,onCheckedChange:P=>y.mutate({include_upcoming_events:P})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(rh,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(ee,{children:"Goals Progress"})]}),e.jsx(Sn,{checked:c==null?void 0:c.include_goals_progress,onCheckedChange:P=>y.mutate({include_goals_progress:P})})]})]})]})]}),e.jsxs(Ne,{children:[e.jsxs(Ct,{children:[e.jsx(At,{children:"Custom Introduction"}),e.jsx(Gn,{children:"Personalize the intro message (optional)"})]}),e.jsx(Ie,{children:e.jsx(Rs,{placeholder:"Here's what's new this week to help you grow your business...",value:(c==null?void 0:c.custom_intro_text)||"",onChange:P=>y.mutate({custom_intro_text:P.target.value||null}),rows:3})})]})]}),e.jsx(Xt,{value:"stats",children:e.jsxs(Ne,{children:[e.jsxs(Ct,{children:[e.jsxs(At,{className:"flex items-center gap-2",children:[e.jsx(mn,{className:"h-5 w-5"}),"Delivery History"]}),e.jsx(Gn,{children:"Recent digest emails sent to members"})]}),e.jsx(Ie,{children:h?e.jsx("div",{className:"animate-pulse space-y-2",children:[1,2,3,4,5].map(P=>e.jsx("div",{className:"h-12 bg-muted rounded"},P))}):u&&u.length>0?e.jsxs(mi,{children:[e.jsx(fi,{children:e.jsxs(En,{children:[e.jsx(Dt,{children:"Email"}),e.jsx(Dt,{children:"Sent At"}),e.jsx(Dt,{children:"Status"}),e.jsx(Dt,{children:"Resources"}),e.jsx(Dt,{children:"Agent OS"})]})}),e.jsx(pi,{children:u.map(P=>e.jsxs(En,{children:[e.jsx(wt,{className:"font-medium",children:P.email_sent_to}),e.jsx(wt,{children:en(new Date(P.sent_at),"MMM d, yyyy h:mm a")}),e.jsx(wt,{children:e.jsx(Be,{variant:P.delivery_status==="sent"?"default":"destructive",children:P.delivery_status})}),e.jsx(wt,{children:P.resources_count}),e.jsx(wt,{children:P.has_agent_os_activity?e.jsx(Be,{variant:"secondary",children:"Active"}):e.jsx(Be,{variant:"outline",children:"Not Started"})})]},P.id))})]}):e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(mn,{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 Por={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 Ior(){var J,ce,_e;const s=Vt(),[t,n]=j.useState(""),[r,a]=j.useState(null),[i,l]=j.useState(!1),[o,c]=j.useState(!1),[d,u]=j.useState(""),[h,m]=j.useState(""),[f,g]=j.useState(!0),[x,y]=j.useState(!1),[v,b]=j.useState(""),[w,S]=j.useState(null),{data:C,isLoading:E}=tt({queryKey:["admin-agent-points"],queryFn:async()=>{const{data:he,error:ue}=await q.from("agent_attendance_stats").select("*").order("total_points",{ascending:!1});if(ue)throw ue;const ve=(he==null?void 0:he.map(Le=>Le.user_id))||[],{data:Ee}=await q.from("profiles").select("id, name, email").in("id",ve),Se=new Map((Ee==null?void 0:Ee.map(Le=>[Le.id,{name:Le.name,email:Le.email}]))||[]);return he==null?void 0:he.map(Le=>({...Le,profile:Se.get(Le.user_id)||null}))}}),{data:I}=tt({queryKey:["all-profiles-for-points",C],queryFn:async()=>{const ue=[];let ve=0;for(;;){const{data:Ee,error:Se}=await q.from("profiles").select("id, name, email").order("name").range(ve,ve+1e3-1);if(Se)throw Se;if(ue.push(...Ee),!Ee||Ee.length<1e3)break;ve+=1e3}return ue}}),R=((I==null?void 0:I.filter(he=>!(C!=null&&C.some(ue=>ue.user_id===he.id))))||[]).filter(he=>{var ve,Ee;if(!v)return!0;const ue=v.toLowerCase();return((ve=he.name)==null?void 0:ve.toLowerCase().includes(ue))||((Ee=he.email)==null?void 0:Ee.toLowerCase().includes(ue))}),{data:D,isLoading:O}=tt({queryKey:["agent-point-history",r==null?void 0:r.user_id],queryFn:async()=>{if(!(r!=null&&r.user_id))return[];const{data:he,error:ue}=await q.from("agent_points").select("*").eq("user_id",r.user_id).order("created_at",{ascending:!1});if(ue)throw ue;return he},enabled:!!(r!=null&&r.user_id)&&o}),{data:U}=tt({queryKey:["agent-badges",r==null?void 0:r.user_id],queryFn:async()=>{if(!(r!=null&&r.user_id))return[];const{data:he,error:ue}=await q.from("agent_badges").select("*").eq("user_id",r.user_id).order("earned_at",{ascending:!1});if(ue)throw ue;return he},enabled:!!(r!=null&&r.user_id)}),W=ft({mutationFn:async({userId:he,points:ue,reason:ve})=>{const{error:Ee}=await q.from("agent_points").insert({user_id:he,points:ue,reason:ve});if(Ee)throw Ee;const{data:Se}=await q.from("agent_attendance_stats").select("total_points, spendable_points").eq("user_id",he).maybeSingle(),Le=((Se==null?void 0:Se.total_points)||0)+ue,Fe=((Se==null?void 0:Se.spendable_points)||0)+ue,{error:ke}=await q.from("agent_attendance_stats").upsert({user_id:he,total_points:Math.max(0,Le),spendable_points:Math.max(0,Fe),updated_at:new Date().toISOString()},{onConflict:"user_id"});if(ke)throw ke},onSuccess:()=>{s.invalidateQueries({queryKey:["admin-agent-points"]}),s.invalidateQueries({queryKey:["agent-point-history"]}),l(!1),u(""),m(""),re.success(f?"Points awarded successfully!":"Points deducted successfully!")},onError:he=>{console.error("Error modifying points:",he),re.error("Failed to modify points")}}),V=()=>{if(!r||!d||!h){re.error("Please fill in all fields");return}const he=parseInt(d);if(isNaN(he)||he<=0){re.error("Please enter a valid positive number");return}W.mutate({userId:r.user_id,points:f?he:-he,reason:h})},G=()=>{if(!w||!d||!h){re.error("Please fill in all fields");return}const he=parseInt(d);if(isNaN(he)||he<=0){re.error("Please enter a valid positive number");return}W.mutate({userId:w.id,points:he,reason:h},{onSuccess:()=>{y(!1),S(null),b("")}})},Y=(he,ue)=>{a(he),g(ue),l(!0)},X=he=>{a(he),c(!0)},ae=C==null?void 0:C.filter(he=>{var Se,Le,Fe,ke;const ue=((Le=(Se=he.profile)==null?void 0:Se.name)==null?void 0:Le.toLowerCase())||"",ve=((ke=(Fe=he.profile)==null?void 0:Fe.email)==null?void 0:ke.toLowerCase())||"",Ee=t.toLowerCase();return ue.includes(Ee)||ve.includes(Ee)}),ie=(C==null?void 0:C.reduce((he,ue)=>he+ue.total_points,0))||0,ne=(C==null?void 0:C.length)||0,te=ne>0?Math.round(ie/ne):0;return E?e.jsx(Vs,{title:"Agent Points",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(yn,{className:"h-8 w-64"}),e.jsx("div",{className:"grid grid-cols-3 gap-4",children:[1,2,3].map(he=>e.jsx(yn,{className:"h-24"},he))}),e.jsx(yn,{className:"h-96"})]})}):e.jsx(Vs,{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(Ne,{children:e.jsxs(Ie,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(Zn,{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:ne}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"with points tracked"})]})}),e.jsx(Ne,{children:e.jsxs(Ie,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(Kl,{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:ie.toLocaleString()}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"awarded across all agents"})]})}),e.jsx(Ne,{children:e.jsxs(Ie,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(Yl,{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:te}),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(Kr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(pe,{placeholder:"Search agents...",value:t,onChange:he=>n(he.target.value),className:"pl-10"})]}),e.jsxs($,{onClick:()=>y(!0),children:[e.jsx(dn,{className:"h-4 w-4 mr-2"}),"Award Points to New Agent"]})]}),e.jsxs(Ne,{children:[e.jsxs(Ct,{children:[e.jsx(At,{children:"Agent Leaderboard"}),e.jsx(Gn,{children:"All agents with their points, events, and streaks"})]}),e.jsx(Ie,{children:!ae||ae.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(Kl,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{children:"No agents with points yet"})]}):e.jsxs(mi,{children:[e.jsx(fi,{children:e.jsxs(En,{children:[e.jsx(Dt,{className:"w-12",children:"#"}),e.jsx(Dt,{children:"Agent"}),e.jsx(Dt,{className:"text-center",children:"Total Points"}),e.jsx(Dt,{className:"text-center",children:"Spendable"}),e.jsx(Dt,{className:"text-center",children:"Events"}),e.jsx(Dt,{className:"text-center",children:"Streak"}),e.jsx(Dt,{className:"text-right",children:"Actions"})]})}),e.jsx(pi,{children:ae.map((he,ue)=>{var ve,Ee,Se,Le;return e.jsxs(En,{children:[e.jsx(wt,{className:"font-medium",children:ue<3?e.jsx("div",{className:`w-6 h-6 rounded-full flex items-center justify-center ${ue===0?"bg-yellow-100 text-yellow-700":ue===1?"bg-gray-100 text-gray-600":"bg-amber-100 text-amber-700"}`,children:ue+1}):e.jsx("span",{className:"text-muted-foreground",children:ue+1})}),e.jsx(wt,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Oa,{className:"h-8 w-8",children:e.jsx(za,{children:((Ee=(ve=he.profile)==null?void 0:ve.name)==null?void 0:Ee.charAt(0))||"?"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:((Se=he.profile)==null?void 0:Se.name)||"Unknown"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:(Le=he.profile)==null?void 0:Le.email})]})]})}),e.jsx(wt,{className:"text-center",children:e.jsxs(Be,{variant:"secondary",className:"font-bold",children:[e.jsx(Ja,{className:"h-3 w-3 mr-1"}),he.total_points]})}),e.jsx(wt,{className:"text-center",children:e.jsxs(Be,{variant:"outline",className:"font-bold text-primary",children:[e.jsx(ul,{className:"h-3 w-3 mr-1"}),he.spendable_points||0]})}),e.jsx(wt,{className:"text-center",children:e.jsxs("div",{className:"flex items-center justify-center gap-1",children:[e.jsx(Ta,{className:"h-3 w-3 text-muted-foreground"}),he.total_events_attended]})}),e.jsx(wt,{className:"text-center",children:e.jsxs("div",{className:"flex items-center justify-center gap-1",children:[e.jsx(nh,{className:"h-3 w-3 text-orange-500"}),he.current_streak]})}),e.jsx(wt,{className:"text-right",children:e.jsxs("div",{className:"flex items-center justify-end gap-1",children:[e.jsx($,{variant:"ghost",size:"sm",onClick:()=>Y(he,!0),title:"Award points",children:e.jsx(dn,{className:"h-4 w-4 text-green-600"})}),e.jsx($,{variant:"ghost",size:"sm",onClick:()=>Y(he,!1),title:"Deduct points",children:e.jsx(tk,{className:"h-4 w-4 text-red-600"})}),e.jsx($,{variant:"ghost",size:"sm",onClick:()=>X(he),title:"View history",children:e.jsx(Lw,{className:"h-4 w-4"})})]})})]},he.user_id)})})]})})]}),e.jsx(zs,{open:i,onOpenChange:l,children:e.jsxs(Os,{children:[e.jsxs(Us,{children:[e.jsx(Bs,{children:f?"Award Points":"Deduct Points"}),e.jsxs(Ir,{children:[f?"Award":"Deduct"," points ",f?"to":"from"," ",((J=r==null?void 0:r.profile)==null?void 0:J.name)||"this agent"]})]}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"points",children:"Points Amount"}),e.jsx(pe,{id:"points",type:"number",min:"1",placeholder:"Enter points...",value:d,onChange:he=>u(he.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"reason",children:"Reason"}),e.jsx(Rs,{id:"reason",placeholder:"Enter reason for this adjustment...",value:h,onChange:he=>m(he.target.value)})]})]}),e.jsxs(Ar,{children:[e.jsx($,{variant:"outline",onClick:()=>l(!1),children:"Cancel"}),e.jsx($,{onClick:V,disabled:W.isPending,className:f?"bg-green-600 hover:bg-green-700":"bg-red-600 hover:bg-red-700",children:W.isPending?"Saving...":f?"Award Points":"Deduct Points"})]})]})}),e.jsx(zs,{open:o,onOpenChange:c,children:e.jsxs(Os,{className:"max-w-2xl",children:[e.jsxs(Us,{children:[e.jsxs(Bs,{children:["Point History: ",(ce=r==null?void 0:r.profile)==null?void 0:ce.name]}),e.jsx(Ir,{children:"View all point transactions and badges for this agent"})]}),e.jsxs(ha,{defaultValue:"history",className:"w-full",children:[e.jsxs(ma,{className:"grid w-full grid-cols-2",children:[e.jsx(Zt,{value:"history",children:"Point History"}),e.jsx(Zt,{value:"badges",children:"Badges"})]}),e.jsx(Xt,{value:"history",className:"mt-4",children:O?e.jsx("div",{className:"space-y-2",children:[1,2,3].map(he=>e.jsx(yn,{className:"h-12"},he))}):!D||D.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(Lw,{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:D.map(he=>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:he.reason}),e.jsx("p",{className:"text-xs text-muted-foreground",children:en(new Date(he.created_at),"MMM d, yyyy h:mm a")})]}),e.jsxs(Be,{variant:he.points>=0?"default":"destructive",className:he.points>=0?"bg-green-100 text-green-800":"",children:[he.points>=0?"+":"",he.points]})]},he.id))})}),e.jsx(Xt,{value:"badges",className:"mt-4",children:!U||U.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(Rm,{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:U.map(he=>e.jsxs("div",{className:`p-3 rounded-lg ${Por[he.badge_type]||"bg-gray-100"}`,children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Rm,{className:"h-5 w-5"}),e.jsx("span",{className:"font-medium",children:he.badge_name})]}),he.badge_description&&e.jsx("p",{className:"text-xs mt-1 opacity-80",children:he.badge_description}),e.jsxs("p",{className:"text-xs mt-1 opacity-60",children:["Earned ",en(new Date(he.earned_at),"MMM d, yyyy")]})]},he.id))})})]})]})}),e.jsx(zs,{open:x,onOpenChange:he=>{y(he),he||(S(null),b(""),u(""),m(""))},children:e.jsxs(Os,{className:"max-w-md",children:[e.jsxs(Us,{children:[e.jsx(Bs,{children:"Award Points to New Agent"}),e.jsx(Ir,{children:"Select an agent who doesn't have points yet and award them points"})]}),e.jsx("div",{className:"space-y-4 py-4",children:w?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-3 p-3 bg-muted/50 rounded-lg",children:[e.jsx(Oa,{className:"h-10 w-10",children:e.jsx(za,{children:((_e=w.name)==null?void 0:_e.charAt(0))||"?"})}),e.jsxs("div",{className:"flex-1",children:[e.jsx("p",{className:"font-medium",children:w.name||"Unknown"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:w.email})]}),e.jsx($,{variant:"ghost",size:"sm",onClick:()=>S(null),children:"Change"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"new-points",children:"Points Amount"}),e.jsx(pe,{id:"new-points",type:"number",min:"1",placeholder:"Enter points...",value:d,onChange:he=>u(he.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"new-reason",children:"Reason"}),e.jsx(Rs,{id:"new-reason",placeholder:"Enter reason for awarding points...",value:h,onChange:he=>m(he.target.value)})]})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Search Agent"}),e.jsxs("div",{className:"relative",children:[e.jsx(Kr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(pe,{placeholder:"Search by name or email...",value:v,onChange:he=>b(he.target.value),className:"pl-10"})]})]}),e.jsx("div",{className:"max-h-60 overflow-y-auto border rounded-lg",children:R.length===0?e.jsxs("div",{className:"text-center py-4 text-muted-foreground",children:[e.jsx(Zn,{className:"h-6 w-6 mx-auto mb-2 opacity-50"}),e.jsx("p",{className:"text-sm",children:v?"No matching agents found":"All agents already have points"})]}):R.slice(0,20).map(he=>{var ue;return e.jsxs("button",{onClick:()=>S(he),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(Oa,{className:"h-8 w-8",children:e.jsx(za,{children:((ue=he.name)==null?void 0:ue.charAt(0))||"?"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-medium truncate",children:he.name||"Unknown"}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:he.email})]})]},he.id)})})]})}),e.jsxs(Ar,{children:[e.jsx($,{variant:"outline",onClick:()=>y(!1),children:"Cancel"}),w&&e.jsxs($,{onClick:G,disabled:W.isPending,className:"bg-green-600 hover:bg-green-700",children:[e.jsx(dn,{className:"h-4 w-4 mr-2"}),"Award Points"]})]})]})})]})})}function Lor(){const{data:s,isLoading:t}=HDs(),[n,r]=j.useState(null),[a,i]=j.useState(!1),[l,o]=j.useState(""),[c,d]=j.useState("all"),[u,h]=j.useState("newest"),[m,f]=j.useState("table"),g=j.useMemo(()=>(s==null?void 0:s.map(w=>w.user_id))||[],[s]),x=j.useMemo(()=>(s==null?void 0:s.map(w=>w.id))||[],[s]),{data:y}=tt({queryKey:["card-profiles-lookup",g],queryFn:async()=>{if(g.length===0)return{};const{data:w}=await q.from("profiles").select("id, name, email").in("id",g),S={};return w==null||w.forEach(C=>{S[C.id]={name:C.name||"",email:C.email||""}}),S},enabled:g.length>0}),{data:v}=tt({queryKey:["card-stats-all",x],queryFn:async()=>{if(x.length===0)return{};const w={};x.forEach(E=>{w[E]={views:0,leads:0}});const{data:S}=await q.from("agent_card_interactions").select("card_id").in("card_id",x).eq("interaction_type","card_view");S==null||S.forEach(E=>{w[E.card_id]&&w[E.card_id].views++});const{data:C}=await q.from("agent_card_leads").select("card_id").in("card_id",x);return C==null||C.forEach(E=>{w[E.card_id]&&w[E.card_id].leads++}),w},enabled:x.length>0}),b=j.useMemo(()=>{if(!s)return[];let w=[...s];if(c==="live"?w=w.filter(S=>S.is_published):c==="draft"&&(w=w.filter(S=>!S.is_published)),l.trim()){const S=l.toLowerCase();w=w.filter(C=>{var I,P;const E=y==null?void 0:y[C.user_id];return C.slug.toLowerCase().includes(S)||((I=E==null?void 0:E.name)==null?void 0:I.toLowerCase().includes(S))||((P=E==null?void 0:E.email)==null?void 0:P.toLowerCase().includes(S))})}return u==="newest"?w.sort((S,C)=>new Date(C.created_at).getTime()-new Date(S.created_at).getTime()):u==="oldest"?w.sort((S,C)=>new Date(S.created_at).getTime()-new Date(C.created_at).getTime()):u==="name"?w.sort((S,C)=>{var E,I;return(((E=y==null?void 0:y[S.user_id])==null?void 0:E.name)||"").localeCompare(((I=y==null?void 0:y[C.user_id])==null?void 0:I.name)||"")}):u==="slug"?w.sort((S,C)=>S.slug.localeCompare(C.slug)):u==="views_desc"?w.sort((S,C)=>{var E,I;return(((E=v==null?void 0:v[C.id])==null?void 0:E.views)||0)-(((I=v==null?void 0:v[S.id])==null?void 0:I.views)||0)}):u==="views_asc"?w.sort((S,C)=>{var E,I;return(((E=v==null?void 0:v[S.id])==null?void 0:E.views)||0)-(((I=v==null?void 0:v[C.id])==null?void 0:I.views)||0)}):u==="leads_desc"?w.sort((S,C)=>{var E,I;return(((E=v==null?void 0:v[C.id])==null?void 0:E.leads)||0)-(((I=v==null?void 0:v[S.id])==null?void 0:I.leads)||0)}):u==="leads_asc"&&w.sort((S,C)=>{var E,I;return(((E=v==null?void 0:v[S.id])==null?void 0:E.leads)||0)-(((I=v==null?void 0:v[C.id])==null?void 0:I.leads)||0)}),w},[s,c,l,u,y]);return e.jsxs(Vs,{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($,{onClick:()=>i(!0),children:[e.jsx(dn,{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(Kr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(pe,{placeholder:"Search by name, email, or slug...",value:l,onChange:w=>o(w.target.value),className:"pl-9"})]}),e.jsxs(ms,{value:c,onValueChange:d,children:[e.jsx(us,{className:"w-full sm:w-36",children:e.jsx(fs,{placeholder:"Status"})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"all",children:"All Status"}),e.jsx(Ge,{value:"live",children:"Live"}),e.jsx(Ge,{value:"draft",children:"Draft"})]})]}),e.jsxs(ms,{value:u,onValueChange:h,children:[e.jsx(us,{className:"w-full sm:w-44",children:e.jsx(fs,{placeholder:"Sort by"})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"newest",children:"Newest First"}),e.jsx(Ge,{value:"oldest",children:"Oldest First"}),e.jsx(Ge,{value:"name",children:"Name A–Z"}),e.jsx(Ge,{value:"slug",children:"Slug A–Z"}),e.jsx(Ge,{value:"views_desc",children:"Most Views"}),e.jsx(Ge,{value:"views_asc",children:"Fewest Views"}),e.jsx(Ge,{value:"leads_desc",children:"Most Leads"}),e.jsx(Ge,{value:"leads_asc",children:"Fewest Leads"})]})]}),e.jsxs("div",{className:"flex border rounded-md",children:[e.jsx($,{variant:m==="table"?"default":"ghost",size:"sm",onClick:()=>f("table"),className:"rounded-r-none",children:e.jsx(lV,{className:"h-4 w-4"})}),e.jsx($,{variant:m==="grid"?"default":"ghost",size:"sm",onClick:()=>f("grid"),className:"rounded-l-none",children:e.jsx(Qf,{className:"h-4 w-4"})})]})]}),!t&&s&&s.length>0&&e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Showing ",b.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(w=>e.jsx(yn,{className:"h-48"},w))}):b.length>0?m==="table"?e.jsx(Ror,{cards:b,cardProfiles:y,cardStats:v,onEdit:r,sortBy:u,setSortBy:h}):e.jsx("div",{className:"grid gap-4 md:grid-cols-2 lg:grid-cols-3",children:b.map(w=>e.jsx(Dor,{card:w,onEdit:()=>r(w),stats:v==null?void 0:v[w.id]},w.id))}):s&&s.length>0?e.jsx(Ne,{children:e.jsxs(Ie,{className:"flex flex-col items-center justify-center py-12",children:[e.jsx(Kr,{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(Ne,{children:e.jsxs(Ie,{className:"flex flex-col items-center justify-center py-12",children:[e.jsx(Zn,{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($,{onClick:()=>i(!0),children:[e.jsx(dn,{className:"h-4 w-4 mr-2"}),"Create Card"]})]})})]}),e.jsx(For,{open:a,onOpenChange:i}),n&&e.jsx(Oor,{card:n,open:!!n,onOpenChange:w=>!w&&r(null)})]})}function Ror({cards:s,cardProfiles:t,cardStats:n,onEdit:r,sortBy:a,setSortBy:i}){const l=c=>{a===`${c}_desc`?i(`${c}_asc`):i(`${c}_desc`)},o=({field:c})=>a===`${c}_desc`?e.jsx(Dg,{className:"h-3 w-3"}):a===`${c}_asc`?e.jsx(Zf,{className:"h-3 w-3"}):e.jsx(By,{className:"h-3 w-3 opacity-40"});return e.jsx(Ne,{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(Zf,{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],u=n==null?void 0:n[c.id],h=`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(Be,{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:(u==null?void 0:u.views)??0}),e.jsx("td",{className:"p-3 text-right tabular-nums font-medium",children:(u==null?void 0:u.leads)??0}),e.jsx("td",{className:"p-3",children:e.jsxs("div",{className:"flex items-center justify-end gap-1",children:[e.jsx($,{variant:"ghost",size:"sm",onClick:()=>r(c),className:"h-8 w-8 p-0",children:e.jsx(gi,{className:"h-3.5 w-3.5"})}),e.jsx($,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>{navigator.clipboard.writeText(h),re.success("Link copied!")},children:e.jsx(Ha,{className:"h-3.5 w-3.5"})}),e.jsx($,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",asChild:!0,children:e.jsx("a",{href:h,target:"_blank",rel:"noopener noreferrer",children:e.jsx(kr,{className:"h-3.5 w-3.5"})})})]})})]},c.id)})})]})})})}function Dor({card:s,onEdit:t,stats:n}){const[r,a]=j.useState(null);j.useEffect(()=>{(async()=>{const{data:c}=await q.from("profiles").select("name").eq("id",s.user_id).single();let d=null;try{const{data:u}=await q.storage.from("avatars").list(`${s.user_id}`);if(u&&u.length>0){const{data:h}=q.storage.from("avatars").getPublicUrl(`${s.user_id}/${u[0].name}`);d=h.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),re.success("Link copied!")};return e.jsx(Ne,{children:e.jsxs(Ie,{className:"p-4",children:[e.jsxs("div",{className:"flex items-start gap-3 mb-3",children:[e.jsxs(Oa,{className:"h-10 w-10",children:[e.jsx(Li,{src:(r==null?void 0:r.avatar_url)||void 0}),e.jsx(za,{children:((r==null?void 0:r.name)||"U")[0]})]}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("h3",{className:"font-semibold truncate",children:(r==null?void 0:r.name)||"Loading..."}),e.jsxs("p",{className:"text-xs text-muted-foreground truncate",children:["/card/",s.slug]})]}),e.jsx(Be,{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(Ca,{className:"h-3.5 w-3.5"}),(n==null?void 0:n.views)??0," views"]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Zn,{className:"h-3.5 w-3.5"}),(n==null?void 0:n.leads)??0," leads"]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs($,{variant:"outline",size:"sm",onClick:t,className:"flex-1",children:[e.jsx(gi,{className:"h-3 w-3 mr-1"}),"Edit"]}),e.jsx($,{variant:"outline",size:"sm",onClick:l,children:e.jsx(Ha,{className:"h-3 w-3"})}),e.jsx($,{variant:"outline",size:"sm",asChild:!0,children:e.jsx("a",{href:i,target:"_blank",rel:"noopener noreferrer",children:e.jsx(kr,{className:"h-3 w-3"})})})]})]})})}function For({open:s,onOpenChange:t}){const[n,r]=j.useState(""),[a,i]=j.useState(""),[l,o]=j.useState(""),[c,d]=j.useState(!1),u=Z7t(),h=l.trim(),{data:m}=tt({queryKey:["profiles-search-for-cards",h],queryFn:async()=>{let b=q.from("profiles").select("id, name, email").order("name").limit(50);h.length>=2&&(b=b.or(`name.ilike.%${h}%,email.ilike.%${h}%`));const{data:w}=await b;return w||[]},enabled:s}),[f,g]=j.useState(null),x=(m==null?void 0:m.find(b=>b.id===n))||f,y=()=>{if(!n||!a.trim()){re.error("Select an agent and enter a slug");return}u.mutate({user_id:n,slug:a.trim().toLowerCase().replace(/[^a-z0-9-]/g,"-"),is_published:!0},{onSuccess:()=>{t(!1),r(""),i(""),o("")}})},v=b=>{var S;r(b),d(!1);const w=m==null?void 0:m.find(C=>C.id===b);w&&(g(w),i(((S=w.name)==null?void 0:S.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/(^-|-$)/g,""))||""))};return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Os,{children:[e.jsxs(Us,{children:[e.jsx(Bs,{children:"Create Agent Card"}),e.jsx(Ir,{children:"Select an agent and set their card URL slug."})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(ee,{children:"Agent"}),e.jsxs(Yd,{open:c,onOpenChange:d,children:[e.jsx(Zd,{asChild:!0,children:e.jsxs($,{variant:"outline",role:"combobox","aria-expanded":c,className:"w-full justify-between font-normal",children:[x?`${x.name} (${x.email})`:"Search for an agent...",e.jsx(Pw,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(Bd,{className:"w-[--radix-popover-trigger-width] p-0",align:"start",children:e.jsxs(P2,{shouldFilter:!1,children:[e.jsx(I2,{placeholder:"Search by name or email...",value:l,onValueChange:o}),e.jsxs(L2,{children:[e.jsx(R2,{children:"No agents found."}),e.jsx(Uw,{children:(m||[]).map(b=>e.jsxs(g1,{value:b.id,onSelect:v,children:[e.jsx(la,{className:Pt("mr-2 h-4 w-4",n===b.id?"opacity-100":"opacity-0")}),b.name," (",b.email,")"]},b.id))})]})]})})]})]}),e.jsxs("div",{children:[e.jsx(ee,{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(pe,{value:a,onChange:b=>i(b.target.value),placeholder:"john-doe"})]})]}),e.jsx($,{onClick:y,disabled:u.isPending,className:"w-full",children:u.isPending?"Creating...":"Create Card"})]})]})})}function Oor({card:s,open:t,onOpenChange:n}){const r=X7t(),{data:a}=Q7t(s.id),i=Vt(),[l,o]=j.useState(null),[c,d]=j.useState(!1),[u,h]=j.useState(!1),[m,f]=j.useState(""),[g,x]=j.useState(s.slug),[y,v]=j.useState(!1),[b,w]=j.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});j.useEffect(()=>{t&&(async()=>{try{const{data:D}=await q.storage.from("avatars").list(`${s.user_id}`);if(D&&D.length>0){const{data:O}=q.storage.from("avatars").getPublicUrl(`${s.user_id}/${D[0].name}`);o(`${O.publicUrl}?t=${Date.now()}`)}}catch{}})()},[s.user_id,t]);const S=R=>{var U;const D=(U=R.target.files)==null?void 0:U[0];if(!D)return;if(!D.type.startsWith("image/")){re.error("Please select an image file");return}if(D.size>5*1024*1024){re.error("Image must be under 5MB");return}const O=new FileReader;O.onloadend=()=>{f(O.result),h(!0)},O.readAsDataURL(D),R.target.value=""},C=async R=>{d(!0);try{const{data:D}=await q.storage.from("avatars").list(`${s.user_id}`);D&&D.length>0&&await q.storage.from("avatars").remove(D.map(G=>`${s.user_id}/${G.name}`));const O=`${s.user_id}/avatar.jpg`,{error:U}=await q.storage.from("avatars").upload(O,R,{upsert:!0,contentType:"image/jpeg"});if(U)throw U;const{data:W}=q.storage.from("avatars").getPublicUrl(O),V=`${W.publicUrl}?t=${Date.now()}`;o(V),await q.from("profiles").update({avatar_url:V}).eq("id",s.user_id),i.invalidateQueries({queryKey:["agent-card-public"]}),re.success("Photo updated!")}catch(D){re.error(D.message||"Upload failed")}finally{d(!1)}},E=async()=>{const R=g.trim().toLowerCase().replace(/[^a-z0-9-]/g,"-").replace(/-+/g,"-").replace(/(^-|-$)/g,"");if(!R){re.error("Please enter a valid URL");return}if(R===s.slug){re.info("No changes to save");return}v(!0);try{const{data:D}=await q.from("agent_cards").select("id").eq("slug",R).neq("id",s.id).maybeSingle();if(D){re.error("This URL is already taken. Try another one.");return}const{error:O}=await q.from("agent_cards").update({slug:R}).eq("id",s.id);if(O)throw O;x(R),i.invalidateQueries({queryKey:["agent-cards-admin"]}),re.success("Card address updated!")}catch{re.error("Failed to update card address")}finally{v(!1)}},I=async(R,D)=>{var U;const O=(U=R.target.files)==null?void 0:U[0];if(O){if(!O.type.startsWith("image/")){re.error("Please select an image file");return}try{const W=O.name.split(".").pop()||"png",V=D==="brokerage_logo_url"?"brokerage-logo":"team-logo",G=`${s.user_id}/${V}.${W}`,{error:Y}=await q.storage.from("card-logos").upload(G,O,{upsert:!0});if(Y)throw Y;const{data:X}=q.storage.from("card-logos").getPublicUrl(G),ae=X.publicUrl+"?t="+Date.now();w(D==="brokerage_logo_url"?ie=>({...ie,[D]:ae,brokerage_display_name:""}):ie=>({...ie,[D]:ae,team_name:""})),re.success("Logo uploaded!")}catch{re.error("Failed to upload logo")}finally{R.target.value=""}}},P=()=>{r.mutate({id:s.id,...b,title:b.title||null,positioning_statement:b.positioning_statement||null,bio:b.bio||null,review_snippet:b.review_snippet||null,review_source_url:b.review_source_url||null,booking_url:b.booking_url||null,custom_cta_label:b.custom_cta_label||null,custom_cta_url:b.custom_cta_url||null,brokerage_display_name:b.brokerage_display_name||null,brokerage_logo_url:b.brokerage_logo_url||null,brokerage_logo_size:b.brokerage_logo_size,team_name:b.team_name||null,team_logo_url:b.team_logo_url||null,team_logo_size:b.team_logo_size},{onSuccess:()=>n(!1)})};return e.jsxs(e.Fragment,{children:[e.jsx(zs,{open:t,onOpenChange:n,children:e.jsxs(Os,{className:"max-w-2xl max-h-[85vh] overflow-y-auto",children:[e.jsxs(Us,{children:[e.jsx(Bs,{children:"Edit Agent Card"}),e.jsxs(Ir,{children:["/card/",s.slug]})]}),e.jsxs(ha,{defaultValue:"content",children:[e.jsxs(ma,{className:"w-full",children:[e.jsx(Zt,{value:"content",className:"flex-1",children:"Content"}),e.jsx(Zt,{value:"sections",className:"flex-1",children:"Sections"}),e.jsx(Zt,{value:"blocks",className:"flex-1",children:"Blocks"}),e.jsx(Zt,{value:"analytics",className:"flex-1",children:"Analytics"})]}),e.jsxs(Xt,{value:"content",className:"space-y-4 mt-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(ee,{children:"Published"}),e.jsx(Sn,{checked:b.is_published,onCheckedChange:R=>w(D=>({...D,is_published:R}))})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Agent Photo"}),e.jsxs("div",{className:"flex items-center gap-4 mt-1",children:[e.jsxs(Oa,{className:"h-16 w-16",children:[e.jsx(Li,{src:l||void 0}),e.jsx(za,{children:"?"})]}),e.jsxs("label",{className:"cursor-pointer",children:[e.jsx("input",{type:"file",accept:"image/*",className:"hidden",onChange:S,disabled:c}),e.jsx($,{variant:"outline",size:"sm",asChild:!0,disabled:c,children:e.jsx("span",{children:c?e.jsxs(e.Fragment,{children:[e.jsx(kt,{className:"h-3 w-3 mr-1 animate-spin"}),"Uploading..."]}):e.jsxs(e.Fragment,{children:[e.jsx(ni,{className:"h-3 w-3 mr-1"}),"Change Photo"]})})})]})]})]}),e.jsxs("div",{children:[e.jsx(ee,{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(pe,{value:g,onChange:R=>x(R.target.value.toLowerCase().replace(/[^a-z0-9-]/g,"-")),placeholder:"agent-name",className:"rounded-l-none"})]}),e.jsx($,{variant:"outline",size:"sm",onClick:E,disabled:y||g===s.slug,className:"shrink-0",children:y?"Saving...":"Update"})]})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Theme"}),e.jsxs(ms,{value:b.theme,onValueChange:R=>w(D=>({...D,theme:R})),children:[e.jsx(us,{children:e.jsx(fs,{})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"standard",children:"✨ Standard (Modern Clean)"}),e.jsx(Ge,{value:"luxury",children:"🌙 Luxury (Dark & Gold)"}),e.jsx(Ge,{value:"bold",children:"🔥 Bold (Vibrant & Punchy)"}),e.jsx(Ge,{value:"classic",children:"📋 Classic (Professional)"})]})]})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Title / Tagline"}),e.jsx(pe,{value:b.title,onChange:R=>w(D=>({...D,title:R.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(ee,{children:"Positioning Statement"}),e.jsx(pe,{value:b.positioning_statement,onChange:R=>w(D=>({...D,positioning_statement:R.target.value})),placeholder:"Your home journey, handled with care."})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Bio"}),e.jsx(Rs,{value:b.bio,onChange:R=>w(D=>({...D,bio:R.target.value})),placeholder:"Short about me...",rows:3})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Review Snippet"}),e.jsx(pe,{value:b.review_snippet,onChange:R=>w(D=>({...D,review_snippet:R.target.value})),placeholder:"Best agent we've ever worked with..."})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Review Source URL"}),e.jsx(pe,{value:b.review_source_url,onChange:R=>w(D=>({...D,review_source_url:R.target.value})),placeholder:"https://g.page/your-business/review"})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Booking URL (optional — if empty, shows lead form)"}),e.jsx(pe,{value:b.booking_url,onChange:R=>w(D=>({...D,booking_url:R.target.value})),placeholder:"https://calendly.com/your-link"})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Custom CTA Label (optional)"}),e.jsx(pe,{value:b.custom_cta_label,onChange:R=>w(D=>({...D,custom_cta_label:R.target.value})),placeholder:"Book a Call"})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Custom CTA URL (optional)"}),e.jsx(pe,{value:b.custom_cta_url,onChange:R=>w(D=>({...D,custom_cta_url:R.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(ee,{className:"text-xs font-semibold uppercase tracking-wider text-muted-foreground",children:"Brokerage Branding"}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(pe,{value:b.brokerage_display_name,onChange:R=>w(D=>({...D,brokerage_display_name:R.target.value,brokerage_logo_url:""})),placeholder:"Brokerage name (or upload logo below)",disabled:!!b.brokerage_logo_url}),e.jsxs("div",{className:"flex items-center gap-3",children:[b.brokerage_logo_url&&e.jsxs("div",{className:"relative group",children:[e.jsx("img",{src:b.brokerage_logo_url,alt:"Brokerage logo",style:{height:`${b.brokerage_logo_size||56}px`},className:"max-w-[200px] object-contain rounded border bg-white p-1"}),e.jsx("button",{onClick:()=>w(R=>({...R,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(ni,{className:"h-3.5 w-3.5"}),b.brokerage_logo_url?"Change Logo":"Upload Logo"]}),e.jsx("input",{type:"file",accept:"image/*",className:"hidden",onChange:R=>I(R,"brokerage_logo_url")})]})]}),b.brokerage_logo_url&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(ee,{className:"text-xs font-medium text-muted-foreground",children:"Logo Size"}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[b.brokerage_logo_size||56,"px"]})]}),e.jsx(kx,{value:[b.brokerage_logo_size||56],onValueChange:([R])=>w(D=>({...D,brokerage_logo_size:R})),min:24,max:120,step:4})]})]})]}),e.jsxs("div",{className:"space-y-3 p-3 rounded-lg bg-muted/30 border",children:[e.jsx(ee,{className:"text-xs font-semibold uppercase tracking-wider text-muted-foreground",children:"Team Branding"}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(pe,{value:b.team_name,onChange:R=>w(D=>({...D,team_name:R.target.value,team_logo_url:""})),placeholder:"Team name (or upload logo below)",disabled:!!b.team_logo_url}),e.jsxs("div",{className:"flex items-center gap-3",children:[b.team_logo_url&&e.jsxs("div",{className:"relative group",children:[e.jsx("img",{src:b.team_logo_url,alt:"Team logo",style:{height:`${b.team_logo_size||56}px`},className:"max-w-[200px] object-contain rounded border bg-white p-1"}),e.jsx("button",{onClick:()=>w(R=>({...R,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(ni,{className:"h-3.5 w-3.5"}),b.team_logo_url?"Change Logo":"Upload Logo"]}),e.jsx("input",{type:"file",accept:"image/*",className:"hidden",onChange:R=>I(R,"team_logo_url")})]})]}),b.team_logo_url&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(ee,{className:"text-xs font-medium text-muted-foreground",children:"Logo Size"}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[b.team_logo_size||56,"px"]})]}),e.jsx(kx,{value:[b.team_logo_size||56],onValueChange:([R])=>w(D=>({...D,team_logo_size:R})),min:24,max:120,step:4})]})]})]})]}),e.jsx(Xt,{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:R,label:D,hint:O})=>e.jsxs("div",{className:"flex items-center justify-between py-2",children:[e.jsxs("div",{children:[e.jsx(ee,{children:D}),O&&e.jsxs("p",{className:"text-xs text-muted-foreground mt-0.5",children:[O," ",R==="show_photo"&&e.jsx("a",{href:"/profile",target:"_blank",rel:"noopener noreferrer",className:"text-primary underline hover:no-underline",children:"Update Profile"})]})]}),e.jsx(Sn,{checked:b[R],onCheckedChange:U=>w(W=>({...W,[R]:U}))})]},R))}),e.jsx(Xt,{value:"blocks",className:"mt-4",children:e.jsx(xos,{cardId:s.id})}),e.jsx(Xt,{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(Ne,{children:e.jsxs(Ie,{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(Ne,{children:e.jsxs(Ie,{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(Ne,{children:e.jsxs(Ie,{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(R=>e.jsxs("div",{className:"text-sm p-2 bg-muted/50 rounded-lg",children:[e.jsx("span",{className:"font-medium",children:R.name}),R.phone&&e.jsxs("span",{className:"text-muted-foreground",children:[" · ",R.phone]}),R.intent&&e.jsx(Be,{variant:"secondary",className:"ml-2 text-xs",children:R.intent})]},R.id))})]})]}):e.jsx("p",{className:"text-center text-muted-foreground py-8",children:"No analytics data yet"})})]}),e.jsx($,{onClick:P,disabled:r.isPending,className:"w-full mt-4",children:r.isPending?"Saving...":"Save Changes"})]})}),e.jsx(rrt,{open:u,onClose:()=>h(!1),imageSrc:m,onCropComplete:C,aspectRatio:1})]})}const YV={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"},$lt={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 Ult(s=!0){return tt({queryKey:["marketplace-categories",s],queryFn:async()=>{let t=q.from("marketplace_categories").select("*").order("sort_order",{ascending:!0});s&&(t=t.eq("is_active",!0));const{data:n,error:r}=await t;if(r)throw r;return n}})}function zor(){const s=Vt();return ft({mutationFn:async t=>{const{data:n,error:r}=await q.from("marketplace_categories").insert([t]).select().single();if(r)throw r;return n},onSuccess:()=>{s.invalidateQueries({queryKey:["marketplace-categories"]}),re.success("Category created successfully")},onError:t=>{re.error("Failed to create category: "+t.message)}})}function Bor(){const s=Vt();return ft({mutationFn:async({id:t,...n})=>{const{data:r,error:a}=await q.from("marketplace_categories").update(n).eq("id",t).select().single();if(a)throw a;return r},onSuccess:()=>{s.invalidateQueries({queryKey:["marketplace-categories"]}),re.success("Category updated successfully")},onError:t=>{re.error("Failed to update category: "+t.message)}})}function $or(){const s=Vt();return ft({mutationFn:async t=>{const{error:n}=await q.from("marketplace_categories").delete().eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["marketplace-categories"]}),re.success("Category deleted successfully")},onError:t=>{re.error("Failed to delete category: "+t.message)}})}function jos(s,t=!0){return tt({queryKey:["marketplace-products",s,t],queryFn:async()=>{let n=q.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&&(n=n.eq("category_id",s)),t&&(n=n.eq("is_active",!0));const{data:r,error:a}=await n;if(a)throw a;return r}})}function Uor(s){return tt({queryKey:["marketplace-product",s],queryFn:async()=>{const{data:t,error:n}=await q.from("marketplace_products").select(` *, category:marketplace_categories(*), images:marketplace_product_images(*), video:marketplace_product_videos(*), variants:marketplace_product_variants(*) `).eq("id",s).single();if(n)throw n;return t},enabled:!!s})}function qor(){const s=Vt();return ft({mutationFn:async t=>{const{data:n,error:r}=await q.from("marketplace_products").insert([t]).select().single();if(r)throw r;return n},onSuccess:()=>{s.invalidateQueries({queryKey:["marketplace-products"]}),re.success("Product created successfully")},onError:t=>{re.error("Failed to create product: "+t.message)}})}function Vor(){const s=Vt();return ft({mutationFn:async({id:t,...n})=>{const{data:r,error:a}=await q.from("marketplace_products").update(n).eq("id",t).select().single();if(a)throw a;return r},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["marketplace-products"]}),s.invalidateQueries({queryKey:["marketplace-product",n.id]}),re.success("Product updated successfully")},onError:t=>{re.error("Failed to update product: "+t.message)}})}function Hor(){const s=Vt();return ft({mutationFn:async t=>{const{error:n}=await q.from("marketplace_products").delete().eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["marketplace-products"]}),re.success("Product deleted successfully")},onError:t=>{re.error("Failed to delete product: "+t.message)}})}function Gor(){const s=Vt();return ft({mutationFn:async t=>{const{data:n,error:r}=await q.from("marketplace_product_images").insert([t]).select().single();if(r)throw r;return n},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["marketplace-products"]}),s.invalidateQueries({queryKey:["marketplace-product",n.product_id]})}})}function Wor(){const s=Vt();return ft({mutationFn:async({id:t,productId:n})=>{const{error:r}=await q.from("marketplace_product_images").delete().eq("id",t);if(r)throw r;return n},onSuccess:t=>{s.invalidateQueries({queryKey:["marketplace-products"]}),s.invalidateQueries({queryKey:["marketplace-product",t]}),re.success("Image deleted successfully")},onError:t=>{re.error("Failed to delete image: "+t.message)}})}function Kor(){const s=Vt();return ft({mutationFn:async({imageId:t,productId:n})=>{const{error:r}=await q.from("marketplace_product_images").update({is_primary:!1}).eq("product_id",n);if(r)throw r;const{error:a}=await q.from("marketplace_product_images").update({is_primary:!0}).eq("id",t);if(a)throw a;return n},onSuccess:t=>{s.invalidateQueries({queryKey:["marketplace-products"]}),s.invalidateQueries({queryKey:["marketplace-product",t]}),re.success("Primary image updated")},onError:t=>{re.error("Failed to set primary image: "+t.message)}})}function Yor(){const s=Vt();return ft({mutationFn:async t=>{const{data:n,error:r}=await q.from("marketplace_product_variants").insert([t]).select().single();if(r)throw r;return n},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["marketplace-products"]}),s.invalidateQueries({queryKey:["marketplace-product",n.product_id]}),re.success("Variant added successfully")}})}function Zor(){const s=Vt();return ft({mutationFn:async({id:t,productId:n})=>{const{error:r}=await q.from("marketplace_product_variants").delete().eq("id",t);if(r)throw r;return n},onSuccess:t=>{s.invalidateQueries({queryKey:["marketplace-products"]}),s.invalidateQueries({queryKey:["marketplace-product",t]}),re.success("Variant deleted successfully")}})}function Xor(){const s=Vt();return ft({mutationFn:async({productId:t,videoUrl:n})=>{await q.from("marketplace_product_videos").delete().eq("product_id",t);const{data:r,error:a}=await q.from("marketplace_product_videos").insert({product_id:t,video_url:n}).select().single();if(a)throw a;return r},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["marketplace-products"]}),s.invalidateQueries({queryKey:["marketplace-product",n.productId]}),re.success("Video updated successfully")}})}function Qor(s){const{isAdmin:t}=vs();return tt({queryKey:["marketplace-orders",s,t],queryFn:async()=>{let n=q.from("marketplace_orders").select(` *, items:marketplace_order_items(*), status_history:marketplace_order_status_history(*) `).order("created_at",{ascending:!1});const{data:r,error:a}=await n;if(a)throw a;if(t&&r){const i=[...new Set(r.map(c=>c.user_id))],{data:l}=await q.from("profiles").select("id, name, email").in("id",i),o=new Map((l==null?void 0:l.map(c=>[c.id,c]))||[]);return r.map(c=>({...c,user:o.get(c.user_id)}))}return r}})}function Jor(){const{user:s}=vs();return tt({queryKey:["my-marketplace-orders",s==null?void 0:s.id],queryFn:async()=>{const{data:t,error:n}=await q.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(n)throw n;return t},enabled:!!(s!=null&&s.id)})}function elr(s){return tt({queryKey:["marketplace-order",s],queryFn:async()=>{const{data:t,error:n}=await q.from("marketplace_orders").select(` *, items:marketplace_order_items(*), status_history:marketplace_order_status_history(*) `).eq("id",s).single();if(n)throw n;return t},enabled:!!s})}function tlr(){const s=Vt(),{user:t}=vs();return ft({mutationFn:async({orderId:n,status:r,notes:a,trackingNumber:i,trackingUrl:l,previousStatus:o})=>{const c={status:r};i!==void 0&&(c.tracking_number=i),l!==void 0&&(c.tracking_url=l);const{error:d}=await q.from("marketplace_orders").update(c).eq("id",n);if(d)throw d;const{error:u}=await q.from("marketplace_order_status_history").insert({order_id:n,status:r,notes:a,created_by:t==null?void 0:t.id});if(u)throw u;if(["shipped","in_production","processing","completed"].includes(r)&&r!==o)try{await q.functions.invoke("marketplace-order-notify",{body:{orderId:n,notificationType:r==="shipped"?"shipped":"status_update",newStatus:r,trackingNumber:i,trackingUrl:l}})}catch(m){console.error("Failed to send notification email:",m)}},onSuccess:(n,r)=>{s.invalidateQueries({queryKey:["marketplace-orders"]}),s.invalidateQueries({queryKey:["marketplace-order",r.orderId]}),s.invalidateQueries({queryKey:["my-marketplace-orders"]}),re.success("Order status updated")},onError:n=>{re.error("Failed to update order: "+n.message)}})}function slr(){const s=Vt();return ft({mutationFn:async({itemId:t,proofUrl:n,proofNotes:r,orderId:a})=>{const{error:i}=await q.from("marketplace_order_items").update({proof_url:n,proof_notes:r,proof_status:"pending"}).eq("id",t);if(i)throw i;await q.from("marketplace_orders").update({status:"awaiting_proof_approval"}).eq("id",a);try{await q.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"]}),re.success("Proof uploaded & customer notified")}})}function nlr(){const s=Vt();return ft({mutationFn:async({itemId:t,orderId:n})=>{const{error:r}=await q.from("marketplace_order_items").update({proof_status:"approved"}).eq("id",t);if(r)throw r;return n},onSuccess:t=>{s.invalidateQueries({queryKey:["marketplace-orders"]}),s.invalidateQueries({queryKey:["marketplace-order",t]}),s.invalidateQueries({queryKey:["my-marketplace-orders"]}),re.success("Proof approved")}})}function rlr(){const s=Vt();return ft({mutationFn:async({itemId:t,orderId:n,reason:r})=>{const{error:a}=await q.from("marketplace_order_items").update({proof_status:"rejected",proof_notes:r}).eq("id",t);if(a)throw a;return n},onSuccess:t=>{s.invalidateQueries({queryKey:["marketplace-orders"]}),s.invalidateQueries({queryKey:["marketplace-order",t]}),s.invalidateQueries({queryKey:["my-marketplace-orders"]}),re.success("Proof rejected - please upload a new proof")}})}function alr(){const{data:s,isLoading:t}=Ult(!1),n=zor(),r=Bor(),a=$or(),[i,l]=j.useState(!1),[o,c]=j.useState(null),[d,u]=j.useState({name:"",description:"",image_url:"",sort_order:0,is_active:!0}),h=()=>{u({name:"",description:"",image_url:"",sort_order:0,is_active:!0}),c(null)},m=x=>{c(x),u({name:x.name,description:x.description||"",image_url:x.image_url||"",sort_order:x.sort_order,is_active:x.is_active}),l(!0)},f=async x=>{x.preventDefault(),o?await r.mutateAsync({id:o.id,...d}):await n.mutateAsync(d),l(!1),h()},g=async x=>{await fo("Are you sure you want to delete this category?")&&await a.mutateAsync(x)};return t?e.jsxs(Ne,{children:[e.jsx(Ct,{children:e.jsx(yn,{className:"h-8 w-48"})}),e.jsx(Ie,{children:e.jsx("div",{className:"space-y-4",children:[1,2,3].map(x=>e.jsx(yn,{className:"h-12 w-full"},x))})})]}):e.jsxs(Ne,{children:[e.jsxs(Ct,{className:"flex flex-row items-center justify-between",children:[e.jsx(At,{children:"Categories"}),e.jsxs(zs,{open:i,onOpenChange:x=>{l(x),x||h()},children:[e.jsx(jl,{asChild:!0,children:e.jsxs($,{children:[e.jsx(dn,{className:"h-4 w-4 mr-2"}),"Add Category"]})}),e.jsxs(Os,{children:[e.jsx(Us,{children:e.jsx(Bs,{children:o?"Edit Category":"Add Category"})}),e.jsxs("form",{onSubmit:f,className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"name",children:"Name"}),e.jsx(pe,{id:"name",value:d.name,onChange:x=>u({...d,name:x.target.value}),required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"description",children:"Description"}),e.jsx(Rs,{id:"description",value:d.description,onChange:x=>u({...d,description:x.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"image_url",children:"Image URL"}),e.jsx(pe,{id:"image_url",value:d.image_url,onChange:x=>u({...d,image_url:x.target.value}),placeholder:"https://..."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"sort_order",children:"Sort Order"}),e.jsx(pe,{id:"sort_order",type:"number",value:d.sort_order,onChange:x=>u({...d,sort_order:parseInt(x.target.value)||0})})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Sn,{id:"is_active",checked:d.is_active,onCheckedChange:x=>u({...d,is_active:x})}),e.jsx(ee,{htmlFor:"is_active",children:"Active"})]}),e.jsx($,{type:"submit",className:"w-full",disabled:n.isPending||r.isPending,children:o?"Update Category":"Create Category"})]})]})]})]}),e.jsx(Ie,{children:s&&s.length>0?e.jsxs(mi,{children:[e.jsx(fi,{children:e.jsxs(En,{children:[e.jsx(Dt,{children:"Name"}),e.jsx(Dt,{children:"Description"}),e.jsx(Dt,{children:"Sort Order"}),e.jsx(Dt,{children:"Status"}),e.jsx(Dt,{className:"text-right",children:"Actions"})]})}),e.jsx(pi,{children:s.map(x=>e.jsxs(En,{children:[e.jsx(wt,{className:"font-medium",children:x.name}),e.jsx(wt,{className:"max-w-xs truncate",children:x.description}),e.jsx(wt,{children:x.sort_order}),e.jsx(wt,{children:e.jsx("span",{className:`px-2 py-1 rounded-full text-xs ${x.is_active?"bg-green-100 text-green-800":"bg-gray-100 text-gray-800"}`,children:x.is_active?"Active":"Inactive"})}),e.jsx(wt,{className:"text-right",children:e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx($,{variant:"ghost",size:"icon",onClick:()=>m(x),children:e.jsx(gi,{className:"h-4 w-4"})}),e.jsx($,{variant:"ghost",size:"icon",onClick:()=>g(x.id),disabled:a.isPending,children:e.jsx(Wn,{className:"h-4 w-4 text-destructive"})})]})})]},x.id))})]}):e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:"No categories yet. Create your first category to get started."})})]})}function ilr(){var te,J;const{data:s,isLoading:t}=jos(void 0,!1),{data:n}=Ult(!1),r=qor(),a=Vor(),i=Hor(),l=Gor(),o=Wor(),c=Kor(),d=Yor(),u=Zor(),h=Xor(),[m,f]=j.useState(!1),[g,x]=j.useState(!1),[y,v]=j.useState(!1),[b,w]=j.useState(null),[S,C]=j.useState(null),[E,I]=j.useState(!1),[P,R]=j.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}),[D,O]=j.useState({name:"",price_adjustment:0}),[U,W]=j.useState(""),V=()=>{R({name:"",description:"",base_price:0,shipping_fee:0,category_id:"",allow_artwork_upload:!1,requires_proof_approval:!1,is_active:!0,sort_order:0}),w(null)},G=ce=>{w(ce),R({name:ce.name,description:ce.description||"",base_price:Number(ce.base_price),shipping_fee:Number(ce.shipping_fee),category_id:ce.category_id||"",allow_artwork_upload:ce.allow_artwork_upload,requires_proof_approval:ce.requires_proof_approval,is_active:ce.is_active,sort_order:ce.sort_order}),f(!0)},Y=async ce=>{ce.preventDefault();const _e={...P,category_id:P.category_id||null};b?await a.mutateAsync({id:b.id,..._e}):await r.mutateAsync(_e),f(!1),V()},X=async ce=>{await fo("Are you sure you want to delete this product?")&&await i.mutateAsync(ce)},ae=async ce=>{if(!S||!ce.target.files||ce.target.files.length===0)return;I(!0);const _e=ce.target.files[0],he=_e.name.split(".").pop(),ue=`products/${S.id}/${Date.now()}.${he}`;try{const{error:ve}=await q.storage.from("marketplace").upload(ue,_e);if(ve)throw ve;const{data:{publicUrl:Ee}}=q.storage.from("marketplace").getPublicUrl(ue);await l.mutateAsync({product_id:S.id,image_url:Ee,is_primary:!S.images||S.images.length===0}),re.success("Image uploaded successfully")}catch(ve){re.error("Failed to upload image: "+ve.message)}finally{I(!1)}},ie=async ce=>{ce.preventDefault(),S&&(await d.mutateAsync({product_id:S.id,name:D.name,price_adjustment:D.price_adjustment}),O({name:"",price_adjustment:0}))},ne=async()=>{!S||!U||(await h.mutateAsync({productId:S.id,videoUrl:U}),W(""))};return t?e.jsxs(Ne,{children:[e.jsx(Ct,{children:e.jsx(yn,{className:"h-8 w-48"})}),e.jsx(Ie,{children:e.jsx("div",{className:"grid gap-4 md:grid-cols-2 lg:grid-cols-3",children:[1,2,3].map(ce=>e.jsx(yn,{className:"h-64 w-full"},ce))})})]}):e.jsxs(e.Fragment,{children:[e.jsxs(Ne,{children:[e.jsxs(Ct,{className:"flex flex-row items-center justify-between",children:[e.jsx(At,{children:"Products"}),e.jsxs(zs,{open:m,onOpenChange:ce=>{f(ce),ce||V()},children:[e.jsx(jl,{asChild:!0,children:e.jsxs($,{children:[e.jsx(dn,{className:"h-4 w-4 mr-2"}),"Add Product"]})}),e.jsxs(Os,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(Us,{children:e.jsx(Bs,{children:b?"Edit Product":"Add Product"})}),e.jsxs("form",{onSubmit:Y,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(ee,{htmlFor:"name",children:"Product Name"}),e.jsx(pe,{id:"name",value:P.name,onChange:ce=>R({...P,name:ce.target.value}),required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"category",children:"Category"}),e.jsxs(ms,{value:P.category_id,onValueChange:ce=>R({...P,category_id:ce}),children:[e.jsx(us,{children:e.jsx(fs,{placeholder:"Select category"})}),e.jsx(hs,{children:n==null?void 0:n.map(ce=>e.jsx(Ge,{value:ce.id,children:ce.name},ce.id))})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"description",children:"Description"}),e.jsx(Rs,{id:"description",value:P.description,onChange:ce=>R({...P,description:ce.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(ee,{htmlFor:"base_price",children:"Base Price ($)"}),e.jsx(pe,{id:"base_price",type:"number",step:"0.01",min:"0",value:P.base_price,onChange:ce=>R({...P,base_price:parseFloat(ce.target.value)||0}),required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"shipping_fee",children:"Shipping Fee ($)"}),e.jsx(pe,{id:"shipping_fee",type:"number",step:"0.01",min:"0",value:P.shipping_fee,onChange:ce=>R({...P,shipping_fee:parseFloat(ce.target.value)||0})})]})]}),e.jsx("div",{className:"grid grid-cols-2 gap-4",children:e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"sort_order",children:"Sort Order"}),e.jsx(pe,{id:"sort_order",type:"number",value:P.sort_order,onChange:ce=>R({...P,sort_order:parseInt(ce.target.value)||0})})]})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Sn,{id:"allow_artwork_upload",checked:P.allow_artwork_upload,onCheckedChange:ce=>R({...P,allow_artwork_upload:ce})}),e.jsx(ee,{htmlFor:"allow_artwork_upload",children:"Allow customer to upload artwork"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Sn,{id:"requires_proof_approval",checked:P.requires_proof_approval,onCheckedChange:ce=>R({...P,requires_proof_approval:ce})}),e.jsx(ee,{htmlFor:"requires_proof_approval",children:"Requires proof approval"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Sn,{id:"is_active",checked:P.is_active,onCheckedChange:ce=>R({...P,is_active:ce})}),e.jsx(ee,{htmlFor:"is_active",children:"Active"})]})]}),e.jsx($,{type:"submit",className:"w-full",disabled:r.isPending||a.isPending,children:b?"Update Product":"Create Product"})]})]})]})]}),e.jsx(Ie,{children:s&&s.length>0?e.jsx("div",{className:"grid gap-4 md:grid-cols-2 lg:grid-cols-3",children:s.map(ce=>{var _e,he;return e.jsxs(Ne,{className:"overflow-hidden",children:[e.jsxs("div",{className:"aspect-video bg-muted relative",children:[ce.images&&ce.images.length>0?e.jsx("img",{src:((_e=ce.images.find(ue=>ue.is_primary))==null?void 0:_e.image_url)||ce.images[0].image_url,alt:ce.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"}),!ce.is_active&&e.jsx(Be,{variant:"secondary",className:"absolute top-2 right-2",children:"Inactive"})]}),e.jsxs(Ie,{className:"p-4",children:[e.jsx("h3",{className:"font-semibold mb-1",children:ce.name}),e.jsx("p",{className:"text-sm text-muted-foreground mb-2",children:((he=ce.category)==null?void 0:he.name)||"No category"}),e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsxs("span",{className:"font-bold",children:["$",Number(ce.base_price).toFixed(2)]}),Number(ce.shipping_fee)>0&&e.jsxs("span",{className:"text-sm text-muted-foreground",children:["+$",Number(ce.shipping_fee).toFixed(2)," shipping"]})]}),e.jsxs("div",{className:"flex flex-wrap gap-1 mb-3",children:[ce.allow_artwork_upload&&e.jsx(Be,{variant:"outline",className:"text-xs",children:"Artwork Upload"}),ce.requires_proof_approval&&e.jsx(Be,{variant:"outline",className:"text-xs",children:"Proof Required"}),ce.variants&&ce.variants.length>0&&e.jsxs(Be,{variant:"outline",className:"text-xs",children:[ce.variants.length," Variants"]})]}),e.jsxs("div",{className:"flex gap-2 flex-wrap",children:[e.jsxs($,{variant:"outline",size:"sm",onClick:()=>G(ce),children:[e.jsx(gi,{className:"h-3 w-3 mr-1"}),"Edit"]}),e.jsxs($,{variant:"outline",size:"sm",onClick:()=>{C(ce),x(!0)},children:[e.jsx(Av,{className:"h-3 w-3 mr-1"}),"Images"]}),e.jsxs($,{variant:"outline",size:"sm",onClick:()=>{C(ce),v(!0)},children:[e.jsx(Ap,{className:"h-3 w-3 mr-1"}),"Variants"]}),e.jsx($,{variant:"ghost",size:"sm",onClick:()=>X(ce.id),children:e.jsx(Wn,{className:"h-3 w-3 text-destructive"})})]})]})]},ce.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(zs,{open:g,onOpenChange:x,children:e.jsxs(Os,{className:"max-w-2xl",children:[e.jsx(Us,{children:e.jsxs(Bs,{children:["Manage Images - ",S==null?void 0:S.name]})}),e.jsxs("div",{className:"space-y-4",children:[e.jsx("div",{className:"grid grid-cols-3 gap-4",children:(te=S==null?void 0:S.images)==null?void 0:te.map(ce=>e.jsxs("div",{className:"relative group",children:[e.jsx("img",{src:ce.image_url,alt:"",className:"w-full aspect-square object-cover rounded-lg"}),ce.is_primary&&e.jsx(Be,{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:[!ce.is_primary&&e.jsx($,{variant:"secondary",size:"icon",onClick:async()=>{var _e;await c.mutateAsync({imageId:ce.id,productId:S.id}),C({...S,images:(_e=S.images)==null?void 0:_e.map(he=>({...he,is_primary:he.id===ce.id}))})},disabled:c.isPending,title:"Set as primary",children:e.jsx(Ja,{className:"h-4 w-4"})}),e.jsx($,{variant:"destructive",size:"icon",onClick:async()=>{var he;await o.mutateAsync({id:ce.id,productId:S.id});const _e=s==null?void 0:s.find(ue=>ue.id===S.id);_e&&C({..._e,images:(he=_e.images)==null?void 0:he.filter(ue=>ue.id!==ce.id)})},disabled:o.isPending,children:e.jsx(Wn,{className:"h-4 w-4"})})]})]},ce.id))}),e.jsxs("div",{className:"border-2 border-dashed rounded-lg p-6 text-center",children:[e.jsx("input",{type:"file",accept:"image/*",onChange:ae,className:"hidden",id:"image-upload",disabled:E}),e.jsxs("label",{htmlFor:"image-upload",className:"cursor-pointer",children:[e.jsx(Av,{className:"h-8 w-8 mx-auto mb-2 text-muted-foreground"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:E?"Uploading...":"Click to upload an image"})]})]}),e.jsxs("div",{className:"border-t pt-4 mt-4",children:[e.jsx(ee,{children:"Product Video (optional)"}),e.jsxs("div",{className:"flex gap-2 mt-2",children:[e.jsx(pe,{placeholder:"Enter video URL (YouTube, Vimeo, etc.)",value:U,onChange:ce=>W(ce.target.value)}),e.jsxs($,{onClick:ne,disabled:!U,children:[e.jsx(ua,{className:"h-4 w-4 mr-2"}),"Set Video"]})]}),(S==null?void 0:S.video)&&e.jsxs("p",{className:"text-sm text-muted-foreground mt-2",children:["Current video: ",S.video.video_url]})]})]})]})}),e.jsx(zs,{open:y,onOpenChange:v,children:e.jsxs(Os,{children:[e.jsx(Us,{children:e.jsxs(Bs,{children:["Manage Variants - ",S==null?void 0:S.name]})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("form",{onSubmit:ie,className:"flex gap-2",children:[e.jsx(pe,{placeholder:"Variant name (e.g., 500 count)",value:D.name,onChange:ce=>O({...D,name:ce.target.value}),required:!0}),e.jsx(pe,{type:"number",step:"0.01",placeholder:"Price adj.",value:D.price_adjustment,onChange:ce=>O({...D,price_adjustment:parseFloat(ce.target.value)||0}),className:"w-32"}),e.jsx($,{type:"submit",children:"Add"})]}),e.jsxs("div",{className:"space-y-2",children:[(J=S==null?void 0:S.variants)==null?void 0:J.map(ce=>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:ce.name}),e.jsxs("span",{className:"text-sm text-muted-foreground ml-2",children:[Number(ce.price_adjustment)>=0?"+":"","$",Number(ce.price_adjustment).toFixed(2)]})]}),e.jsx($,{variant:"ghost",size:"icon",onClick:()=>u.mutateAsync({id:ce.id,productId:S.id}),children:e.jsx(Wn,{className:"h-4 w-4 text-destructive"})})]},ce.id)),(!(S!=null&&S.variants)||S.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 olr=["pending_payment","order_submitted","awaiting_proof_approval","proof_approved","processing","in_production","shipped","completed","cancelled","refunded"];function llr(){var x,y,v;const{data:s,isLoading:t}=Qor(),n=tlr(),r=slr(),[a,i]=j.useState(null),[l,o]=j.useState(!1),[c,d]=j.useState({status:"",notes:"",trackingNumber:"",trackingUrl:""}),[u,h]=j.useState(!1),m=b=>{i(b),d({status:b.status,notes:"",trackingNumber:b.tracking_number||"",trackingUrl:b.tracking_url||""}),o(!0)},f=async()=>{a&&(await n.mutateAsync({orderId:a.id,status:c.status,notes:c.notes,trackingNumber:c.trackingNumber,trackingUrl:c.trackingUrl,previousStatus:a.status}),o(!1))},g=async(b,w)=>{if(!a||!b.target.files||b.target.files.length===0)return;h(!0);const S=b.target.files[0],C=S.name.split(".").pop(),E=`proofs/${a.id}/${w}/${Date.now()}.${C}`;try{const{error:I}=await q.storage.from("marketplace").upload(E,S);if(I)throw I;const{data:{publicUrl:P}}=q.storage.from("marketplace").getPublicUrl(E);await r.mutateAsync({itemId:w,proofUrl:P,orderId:a.id}),re.success("Proof uploaded successfully")}catch(I){re.error("Failed to upload proof: "+I.message)}finally{h(!1)}};return t?e.jsxs(Ne,{children:[e.jsx(Ct,{children:e.jsx(yn,{className:"h-8 w-48"})}),e.jsx(Ie,{children:e.jsx("div",{className:"space-y-4",children:[1,2,3].map(b=>e.jsx(yn,{className:"h-16 w-full"},b))})})]}):e.jsxs(e.Fragment,{children:[e.jsxs(Ne,{children:[e.jsx(Ct,{children:e.jsx(At,{children:"Orders"})}),e.jsx(Ie,{children:s&&s.length>0?e.jsxs(mi,{children:[e.jsx(fi,{children:e.jsxs(En,{children:[e.jsx(Dt,{children:"Order #"}),e.jsx(Dt,{children:"Customer"}),e.jsx(Dt,{children:"Date"}),e.jsx(Dt,{children:"Total"}),e.jsx(Dt,{children:"Status"}),e.jsx(Dt,{className:"text-right",children:"Actions"})]})}),e.jsx(pi,{children:s.map(b=>{var w,S;return e.jsxs(En,{children:[e.jsx(wt,{className:"font-mono",children:b.order_number}),e.jsx(wt,{children:e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:((w=b.user)==null?void 0:w.name)||"Unknown"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:(S=b.user)==null?void 0:S.email})]})}),e.jsx(wt,{children:en(new Date(b.created_at),"MMM d, yyyy")}),e.jsxs(wt,{className:"font-bold",children:["$",Number(b.total).toFixed(2)]}),e.jsx(wt,{children:e.jsx(Be,{className:$lt[b.status],children:YV[b.status]})}),e.jsx(wt,{className:"text-right",children:e.jsxs($,{variant:"ghost",size:"sm",onClick:()=>m(b),children:[e.jsx(Ca,{className:"h-4 w-4 mr-1"}),"View"]})})]},b.id)})})]}):e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:"No orders yet."})})]}),e.jsx(zs,{open:l,onOpenChange:o,children:e.jsxs(Os,{className:"max-w-3xl max-h-[90vh] overflow-y-auto",children:[e.jsx(Us,{children:e.jsxs(Bs,{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:(x=a.user)==null?void 0:x.name}),e.jsx("p",{className:"text-sm text-muted-foreground",children:(y=a.user)==null?void 0:y.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:(v=a.items)==null?void 0:v.map(b=>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:b.product_name}),b.variant_name&&e.jsx("p",{className:"text-sm text-muted-foreground",children:b.variant_name})]}),e.jsxs("p",{className:"font-bold",children:["$",Number(b.unit_price).toFixed(2)," x ",b.quantity]})]}),b.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:b.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(Be,{variant:b.proof_status==="approved"?"default":"secondary",children:b.proof_status||"No proof yet"})]}),b.proof_url?e.jsx("a",{href:b.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:w=>g(w,b.id),className:"hidden",id:`proof-${b.id}`,disabled:u}),e.jsx("label",{htmlFor:`proof-${b.id}`,children:e.jsx($,{variant:"outline",size:"sm",asChild:!0,children:e.jsxs("span",{children:[e.jsx(ni,{className:"h-4 w-4 mr-1"}),u?"Uploading...":"Upload Proof"]})})})]})]})})]},b.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(ee,{children:"Status"}),e.jsxs(ms,{value:c.status,onValueChange:b=>d({...c,status:b}),children:[e.jsx(us,{children:e.jsx(fs,{})}),e.jsx(hs,{children:olr.map(b=>e.jsx(Ge,{value:b,children:YV[b]},b))})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Tracking Number"}),e.jsx(pe,{value:c.trackingNumber,onChange:b=>d({...c,trackingNumber:b.target.value}),placeholder:"Enter tracking number"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Tracking URL"}),e.jsx(pe,{value:c.trackingUrl,onChange:b=>d({...c,trackingUrl:b.target.value}),placeholder:"https://..."})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Notes (optional)"}),e.jsx(Rs,{value:c.notes,onChange:b=>d({...c,notes:b.target.value}),placeholder:"Add a note about this status change..."})]}),e.jsxs($,{onClick:f,disabled:n.isPending,className:"w-full",children:[e.jsx(vm,{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(b=>e.jsxs("div",{className:"flex justify-between text-sm p-2 bg-muted rounded",children:[e.jsxs("div",{children:[e.jsx(Be,{variant:"outline",children:YV[b.status]}),b.notes&&e.jsx("p",{className:"text-muted-foreground mt-1",children:b.notes})]}),e.jsx("span",{className:"text-muted-foreground",children:en(new Date(b.created_at),"MMM d, h:mm a")})]},b.id))})]})]})]})})]})}function clr(){const[s,t]=j.useState("products"),n=Qn();return e.jsx(Vs,{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($,{variant:"outline",onClick:()=>n("/marketplace"),children:[e.jsx(kr,{className:"h-4 w-4 mr-2"}),"View Store"]})]}),e.jsxs(ha,{value:s,onValueChange:t,children:[e.jsxs(ma,{className:"grid w-full grid-cols-3",children:[e.jsxs(Zt,{value:"products",className:"flex items-center gap-2",children:[e.jsx(vm,{className:"h-4 w-4"}),"Products"]}),e.jsxs(Zt,{value:"categories",className:"flex items-center gap-2",children:[e.jsx(_b,{className:"h-4 w-4"}),"Categories"]}),e.jsxs(Zt,{value:"orders",className:"flex items-center gap-2",children:[e.jsx(nC,{className:"h-4 w-4"}),"Orders"]})]}),e.jsx(Xt,{value:"products",children:e.jsx(ilr,{})}),e.jsx(Xt,{value:"categories",children:e.jsx(alr,{})}),e.jsx(Xt,{value:"orders",children:e.jsx(llr,{})})]})]})})}function Nos(){return tt({queryKey:["reward-categories"],queryFn:async()=>{const{data:s,error:t}=await q.from("reward_store_categories").select("*").order("sort_order",{ascending:!0});if(t)throw t;return s}})}function dlr(s){return tt({queryKey:["reward-items",s],queryFn:async()=>{let t=q.from("reward_store_items").select(` *, category:reward_store_categories(*) `).order("created_at",{ascending:!1});const{data:n,error:r}=await t;if(r)throw r;return n}})}function ulr(s){return tt({queryKey:["active-reward-items",s],queryFn:async()=>{let t=q.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:n,error:r}=await t;if(r)throw r;return n}})}function hlr(s){return tt({queryKey:["user-purchases",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await q.from("reward_store_purchases").select(` *, item:reward_store_items(*) `).eq("user_id",s).order("purchased_at",{ascending:!1});if(n)throw n;return t},enabled:!!s})}function mlr(){return tt({queryKey:["all-reward-purchases"],queryFn:async()=>{const{data:s,error:t}=await q.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 n=[...new Set(s.map(l=>l.user_id))],{data:r,error:a}=await q.from("profiles").select("id, name, email").in("id",n);if(a)throw a;const i=new Map((r==null?void 0:r.map(l=>[l.id,l]))||[]);return s.map(l=>({...l,user:i.get(l.user_id)||null}))}})}function flr(s){return tt({queryKey:["spendable-points",s],queryFn:async()=>{if(!s)return 0;const{data:t,error:n}=await q.from("agent_attendance_stats").select("spendable_points").eq("user_id",s).single();if(n&&n.code!=="PGRST116")throw n;return(t==null?void 0:t.spendable_points)||0},enabled:!!s})}function plr(){const s=Vt();return ft({mutationFn:async t=>{const{data:n,error:r}=await q.rpc("purchase_reward_item",{p_item_id:t});if(r)throw r;const a=n;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 glr(){const s=Vt();return ft({mutationFn:async t=>{const{data:n,error:r}=await q.from("reward_store_categories").insert([t]).select().single();if(r)throw r;return n},onSuccess:()=>{s.invalidateQueries({queryKey:["reward-categories"]})}})}function xlr(){const s=Vt();return ft({mutationFn:async({id:t,...n})=>{const{data:r,error:a}=await q.from("reward_store_categories").update(n).eq("id",t).select().single();if(a)throw a;return r},onSuccess:()=>{s.invalidateQueries({queryKey:["reward-categories"]})}})}function ylr(){const s=Vt();return ft({mutationFn:async t=>{const{error:n}=await q.from("reward_store_categories").delete().eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["reward-categories"]})}})}function vlr(){const s=Vt();return ft({mutationFn:async t=>{const{data:n,error:r}=await q.from("reward_store_items").insert([t]).select().single();if(r)throw r;return n},onSuccess:()=>{s.invalidateQueries({queryKey:["reward-items"]}),s.invalidateQueries({queryKey:["active-reward-items"]})}})}function blr(){const s=Vt();return ft({mutationFn:async({id:t,...n})=>{const{data:r,error:a}=await q.from("reward_store_items").update(n).eq("id",t).select().single();if(a)throw a;return r},onSuccess:()=>{s.invalidateQueries({queryKey:["reward-items"]}),s.invalidateQueries({queryKey:["active-reward-items"]})}})}function _lr(){const s=Vt();return ft({mutationFn:async t=>{const{error:n}=await q.from("reward_store_items").delete().eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["reward-items"]}),s.invalidateQueries({queryKey:["active-reward-items"]})}})}function wlr(s){const t=s.match(/\/storage\/v1\/object\/public\/([^/]+)\/(.+)$/);return t?{bucket:t[1],path:t[2]}:null}async function yUe(s,t){const n=wlr(s);if(n)try{const{data:r,error:a}=await q.storage.from(n.bucket).download(n.path);if(a){console.error("Error downloading file:",a),re.error("Failed to download file");return}const i=URL.createObjectURL(r),l=document.createElement("a");l.href=i,l.download=t||n.path.split("/").pop()||"download",document.body.appendChild(l),l.click(),document.body.removeChild(l),setTimeout(()=>URL.revokeObjectURL(i),100)}catch(r){console.error("Download error:",r),re.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(r){console.error("External download error:",r),re.error("Failed to download file")}}function kos(){return tt({queryKey:["point-reward-settings"],queryFn:async()=>{const{data:s,error:t}=await q.from("point_reward_settings").select("*").order("action_name");if(t)throw t;return s}})}function jlr(){const s=Vt();return ft({mutationFn:async({id:t,points:n,is_active:r})=>{const a={points:n};r!==void 0&&(a.is_active=r);const{data:i,error:l}=await q.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 Nlr(){const{user:s}=vs(),[t,n]=j.useState("items"),[r,a]=j.useState(!1),[i,l]=j.useState(null),[o,c]=j.useState(""),[d,u]=j.useState(""),[h,m]=j.useState(""),[f,g]=j.useState(null),[x,y]=j.useState(!1),[v,b]=j.useState(null),[w,S]=j.useState(""),[C,E]=j.useState(""),[I,P]=j.useState(null),[R,D]=j.useState(""),[O,U]=j.useState("file"),[W,V]=j.useState(""),[G,Y]=j.useState(""),[X,ae]=j.useState(""),[ie,ne]=j.useState(!0),[te,J]=j.useState(null),[ce,_e]=j.useState(!1),[he,ue]=j.useState(!1),ve=j.useRef(null),Ee=j.useRef(null),{data:Se,isLoading:Le}=Nos(),{data:Fe,isLoading:ke}=dlr(),{data:Ve,isLoading:je}=mlr(),{data:Ae,isLoading:Ce}=kos(),qe=glr(),ze=xlr(),$e=ylr(),ct=vlr(),Xe=blr(),it=_lr(),at=jlr(),[Ke,nt]=j.useState({}),xt=St=>{St?(l(St),c(St.name),u(St.description||""),m(St.icon||"")):(l(null),c(""),u(""),m("")),a(!0)},rt=async()=>{if(!o.trim()){re.error("Please enter a category name");return}try{i?(await ze.mutateAsync({id:i.id,name:o,description:d||null,icon:h||null}),re.success("Category updated successfully")):(await qe.mutateAsync({name:o,description:d||null,icon:h||null,sort_order:((Se==null?void 0:Se.length)||0)+1}),re.success("Category created successfully")),a(!1)}catch(St){console.error("Error saving category:",St),re.error("Failed to save category")}},Yt=async()=>{if(f)try{await $e.mutateAsync(f),re.success("Category deleted successfully"),g(null)}catch(St){console.error("Error deleting category:",St),re.error("Failed to delete category")}},qt=St=>{var Xs;St?(b(St),S(St.name),E(St.description||""),P(St.category_id),D(St.points_cost.toString()),U(St.item_type),V(St.file_url||""),Y(St.preview_image_url||""),ae(((Xs=St.max_quantity)==null?void 0:Xs.toString())||""),ne(St.is_active)):(b(null),S(""),E(""),P(null),D(""),U("file"),V(""),Y(""),ae(""),ne(!0)),y(!0)},ts=async(St,Xs)=>{Xs==="file"?_e(!0):ue(!0);try{const vt=St.name.split(".").pop(),gs=`${Date.now()}-${Math.random().toString(36).substring(7)}.${vt}`,Ss=`${Xs==="file"?"items":"previews"}/${gs}`,{error:Is}=await q.storage.from("reward-store").upload(Ss,St);if(Is)throw Is;const{data:{publicUrl:Ys}}=q.storage.from("reward-store").getPublicUrl(Ss);Xs==="file"?V(Ys):Y(Ys),re.success("File uploaded successfully")}catch(vt){console.error("Error uploading file:",vt),re.error("Failed to upload file")}finally{Xs==="file"?_e(!1):ue(!1)}},ys=async()=>{if(!w.trim()){re.error("Please enter an item name");return}if(!R||parseInt(R)<0){re.error("Please enter a valid points cost");return}try{const St={name:w,description:C||null,category_id:I,points_cost:parseInt(R),item_type:O,file_url:W||null,preview_image_url:G||null,max_quantity:X?parseInt(X):null,current_quantity:X?parseInt(X):null,is_active:ie,created_by:s==null?void 0:s.id};v?(await Xe.mutateAsync({id:v.id,...St,current_quantity:v.max_quantity!==(X?parseInt(X):null)?X?parseInt(X):null:v.current_quantity}),re.success("Item updated successfully")):(await ct.mutateAsync(St),re.success("Item created successfully")),y(!1)}catch(St){console.error("Error saving item:",St),re.error("Failed to save item")}},Bt=async()=>{if(te)try{await it.mutateAsync(te),re.success("Item deleted successfully"),J(null)}catch(St){console.error("Error deleting item:",St),re.error("Failed to delete item")}},Ft=async(St,Xs)=>{const vt=Ke[St];if(vt===void 0||vt===Xs.toString())return;const gs=parseInt(vt);if(isNaN(gs)||gs<0){re.error("Please enter a valid positive number");return}try{await at.mutateAsync({id:St,points:gs}),re.success("Points updated successfully"),nt(Ss=>{const Is={...Ss};return delete Is[St],Is})}catch(Ss){console.error("Error updating points:",Ss),re.error("Failed to update points")}};return Le||ke||je||Ce?e.jsx(Vs,{title:"Reward Store",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(yn,{className:"h-8 w-64"}),e.jsx(yn,{className:"h-96"})]})}):e.jsxs(Vs,{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(Ne,{children:e.jsxs(Ie,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(vm,{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:(Fe==null?void 0:Fe.length)||0}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[(Fe==null?void 0:Fe.filter(St=>St.is_active).length)||0," active"]})]})}),e.jsx(Ne,{children:e.jsxs(Ie,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(_b,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs font-medium",children:"Categories"})]}),e.jsx("p",{className:"text-2xl font-bold",children:(Se==null?void 0:Se.length)||0})]})}),e.jsx(Ne,{children:e.jsxs(Ie,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(Ja,{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:[Fe&&Fe.length>0?Math.round(Fe.reduce((St,Xs)=>St+Xs.points_cost,0)/Fe.length):0," pts"]})]})})]}),e.jsxs(ha,{value:t,onValueChange:n,children:[e.jsxs(ma,{children:[e.jsx(Zt,{value:"items",children:"Items"}),e.jsx(Zt,{value:"categories",children:"Categories"}),e.jsx(Zt,{value:"purchases",children:"Purchases"}),e.jsx(Zt,{value:"point-settings",children:"Point Settings"})]}),e.jsx(Xt,{value:"items",className:"mt-4",children:e.jsxs(Ne,{children:[e.jsxs(Ct,{className:"flex flex-row items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(At,{children:"Store Items"}),e.jsx(Gn,{children:"Manage rewards that agents can purchase"})]}),e.jsxs($,{onClick:()=>qt(),children:[e.jsx(dn,{className:"h-4 w-4 mr-2"}),"Add Item"]})]}),e.jsx(Ie,{children:!Fe||Fe.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(ul,{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(mi,{children:[e.jsx(fi,{children:e.jsxs(En,{children:[e.jsx(Dt,{children:"Item"}),e.jsx(Dt,{children:"Category"}),e.jsx(Dt,{className:"text-center",children:"Cost"}),e.jsx(Dt,{className:"text-center",children:"Type"}),e.jsx(Dt,{className:"text-center",children:"Quantity"}),e.jsx(Dt,{className:"text-center",children:"Status"}),e.jsx(Dt,{className:"text-right",children:"Actions"})]})}),e.jsx(pi,{children:Fe.map(St=>e.jsxs(En,{children:[e.jsx(wt,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[St.preview_image_url?e.jsx("img",{src:St.preview_image_url,alt:St.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(ul,{className:"h-5 w-5 text-muted-foreground"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:St.name}),e.jsx("p",{className:"text-xs text-muted-foreground line-clamp-1",children:St.description||"No description"})]})]})}),e.jsx(wt,{children:St.category?e.jsx(Be,{variant:"outline",children:St.category.name}):e.jsx("span",{className:"text-muted-foreground",children:"—"})}),e.jsx(wt,{className:"text-center",children:e.jsxs(Be,{variant:"secondary",className:"font-bold",children:[e.jsx(Ja,{className:"h-3 w-3 mr-1"}),St.points_cost]})}),e.jsx(wt,{className:"text-center",children:e.jsxs("div",{className:"flex items-center justify-center gap-1",children:[St.item_type==="file"?e.jsx(Jr,{className:"h-4 w-4 text-muted-foreground"}):e.jsx(Ad,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"text-xs capitalize",children:St.item_type})]})}),e.jsx(wt,{className:"text-center",children:St.max_quantity!==null?e.jsxs("span",{className:St.current_quantity===0?"text-red-500":"",children:[St.current_quantity,"/",St.max_quantity]}):e.jsx("span",{className:"text-muted-foreground",children:"Unlimited"})}),e.jsx(wt,{className:"text-center",children:e.jsx(Be,{variant:St.is_active?"default":"secondary",children:St.is_active?"Active":"Inactive"})}),e.jsx(wt,{className:"text-right",children:e.jsxs("div",{className:"flex items-center justify-end gap-1",children:[e.jsx($,{variant:"ghost",size:"sm",onClick:()=>qt(St),children:e.jsx(gi,{className:"h-4 w-4"})}),e.jsx($,{variant:"ghost",size:"sm",onClick:()=>J(St.id),children:e.jsx(Wn,{className:"h-4 w-4 text-destructive"})})]})})]},St.id))})]})})]})}),e.jsx(Xt,{value:"categories",className:"mt-4",children:e.jsxs(Ne,{children:[e.jsxs(Ct,{className:"flex flex-row items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(At,{children:"Categories"}),e.jsx(Gn,{children:"Organize your store items into categories"})]}),e.jsxs($,{onClick:()=>xt(),children:[e.jsx(dn,{className:"h-4 w-4 mr-2"}),"Add Category"]})]}),e.jsx(Ie,{children:!Se||Se.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(_b,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{children:"No categories yet. Add your first category!"})]}):e.jsxs(mi,{children:[e.jsx(fi,{children:e.jsxs(En,{children:[e.jsx(Dt,{children:"Name"}),e.jsx(Dt,{children:"Description"}),e.jsx(Dt,{className:"text-center",children:"Items"}),e.jsx(Dt,{className:"text-right",children:"Actions"})]})}),e.jsx(pi,{children:Se.map(St=>e.jsxs(En,{children:[e.jsxs(wt,{className:"font-medium",children:[St.icon&&e.jsx("span",{className:"mr-2",children:St.icon}),St.name]}),e.jsx(wt,{className:"text-muted-foreground",children:St.description||"—"}),e.jsx(wt,{className:"text-center",children:(Fe==null?void 0:Fe.filter(Xs=>Xs.category_id===St.id).length)||0}),e.jsx(wt,{className:"text-right",children:e.jsxs("div",{className:"flex items-center justify-end gap-1",children:[e.jsx($,{variant:"ghost",size:"sm",onClick:()=>xt(St),children:e.jsx(gi,{className:"h-4 w-4"})}),e.jsx($,{variant:"ghost",size:"sm",onClick:()=>g(St.id),children:e.jsx(Wn,{className:"h-4 w-4 text-destructive"})})]})})]},St.id))})]})})]})}),e.jsx(Xt,{value:"purchases",className:"mt-4",children:e.jsxs(Ne,{children:[e.jsxs(Ct,{children:[e.jsxs(At,{className:"flex items-center gap-2",children:[e.jsx(nC,{className:"h-5 w-5"}),"Purchase History"]}),e.jsx(Gn,{children:"View all reward redemptions by agents"})]}),e.jsx(Ie,{children:!Ve||Ve.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(nC,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{children:"No purchases yet."})]}):e.jsxs(mi,{children:[e.jsx(fi,{children:e.jsxs(En,{children:[e.jsx(Dt,{children:"Date"}),e.jsx(Dt,{children:"Agent"}),e.jsx(Dt,{children:"Item"}),e.jsx(Dt,{className:"text-center",children:"Points Spent"})]})}),e.jsx(pi,{children:Ve.map(St=>{var Xs,vt,gs,Ss;return e.jsxs(En,{children:[e.jsx(wt,{className:"text-muted-foreground",children:en(new Date(St.purchased_at),"MMM d, yyyy 'at' h:mm a")}),e.jsx(wt,{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(sl,{className:"h-4 w-4 text-muted-foreground"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:((Xs=St.user)==null?void 0:Xs.name)||"Unknown"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:((vt=St.user)==null?void 0:vt.email)||"—"})]})]})}),e.jsx(wt,{children:e.jsxs("div",{className:"flex items-center gap-2",children:[(gs=St.item)!=null&&gs.preview_image_url?e.jsx("img",{src:St.item.preview_image_url,alt:St.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(ul,{className:"h-4 w-4 text-muted-foreground"})}),e.jsx("span",{children:((Ss=St.item)==null?void 0:Ss.name)||"Deleted item"})]})}),e.jsx(wt,{className:"text-center",children:e.jsxs(Be,{variant:"secondary",className:"font-bold",children:[e.jsx(Ja,{className:"h-3 w-3 mr-1"}),St.points_spent]})})]},St.id)})})]})})]})})]})]}),e.jsx(zs,{open:r,onOpenChange:a,children:e.jsxs(Os,{children:[e.jsxs(Us,{children:[e.jsx(Bs,{children:i?"Edit Category":"Add Category"}),e.jsx(Ir,{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(ee,{htmlFor:"categoryName",children:"Name"}),e.jsx(pe,{id:"categoryName",value:o,onChange:St=>c(St.target.value),placeholder:"e.g., Templates, Resources"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"categoryDescription",children:"Description"}),e.jsx(Rs,{id:"categoryDescription",value:d,onChange:St=>u(St.target.value),placeholder:"Optional description..."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"categoryIcon",children:"Icon (emoji)"}),e.jsx(pe,{id:"categoryIcon",value:h,onChange:St=>m(St.target.value),placeholder:"e.g., 📄, 🎁"})]})]}),e.jsxs(Ar,{children:[e.jsx($,{variant:"outline",onClick:()=>a(!1),children:"Cancel"}),e.jsx($,{onClick:rt,disabled:qe.isPending||ze.isPending,children:qe.isPending||ze.isPending?"Saving...":"Save"})]})]})}),e.jsx(zs,{open:x,onOpenChange:y,children:e.jsxs(Os,{className:"max-w-lg max-h-[90vh] overflow-y-auto",children:[e.jsxs(Us,{children:[e.jsx(Bs,{children:v?"Edit Item":"Add Item"}),e.jsx(Ir,{children:v?"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(ee,{htmlFor:"itemName",children:"Name *"}),e.jsx(pe,{id:"itemName",value:w,onChange:St=>S(St.target.value),placeholder:"e.g., Premium Template Pack"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"itemDescription",children:"Description"}),e.jsx(Rs,{id:"itemDescription",value:C,onChange:St=>E(St.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(ee,{htmlFor:"itemCategory",children:"Category"}),e.jsxs(ms,{value:I||"none",onValueChange:St=>P(St==="none"?null:St),children:[e.jsx(us,{children:e.jsx(fs,{placeholder:"Select category"})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"none",children:"No category"}),Se==null?void 0:Se.map(St=>e.jsxs(Ge,{value:St.id,children:[St.icon&&`${St.icon} `,St.name]},St.id))]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"itemPointsCost",children:"Points Cost *"}),e.jsx(pe,{id:"itemPointsCost",type:"number",min:"0",value:R,onChange:St=>D(St.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(ee,{htmlFor:"itemType",children:"Type"}),e.jsxs(ms,{value:O,onValueChange:U,children:[e.jsx(us,{children:e.jsx(fs,{})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"file",children:"File Download"}),e.jsx(Ge,{value:"link",children:"External Link"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"itemMaxQuantity",children:"Max Quantity"}),e.jsx(pe,{id:"itemMaxQuantity",type:"number",min:"1",value:X,onChange:St=>ae(St.target.value),placeholder:"Leave empty for unlimited"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"File / Link URL"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(pe,{value:W,onChange:St=>V(St.target.value),placeholder:O==="file"?"Upload a file or paste URL":"Paste external link"}),O==="file"&&e.jsxs(e.Fragment,{children:[e.jsx($,{type:"button",variant:"outline",size:"icon",onClick:()=>{var St;return(St=ve.current)==null?void 0:St.click()},disabled:ce,children:e.jsx(ni,{className:"h-4 w-4"})}),e.jsx("input",{ref:ve,type:"file",className:"hidden",onChange:St=>{var vt;const Xs=(vt=St.target.files)==null?void 0:vt[0];Xs&&ts(Xs,"file")}})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Preview Image"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(pe,{value:G,onChange:St=>Y(St.target.value),placeholder:"Upload an image or paste URL"}),e.jsx($,{type:"button",variant:"outline",size:"icon",onClick:()=>{var St;return(St=Ee.current)==null?void 0:St.click()},disabled:he,children:e.jsx(Mc,{className:"h-4 w-4"})}),e.jsx("input",{ref:Ee,type:"file",accept:"image/*",className:"hidden",onChange:St=>{var vt;const Xs=(vt=St.target.files)==null?void 0:vt[0];Xs&&ts(Xs,"preview")}})]}),G&&e.jsx("img",{src:G,alt:"Preview",className:"mt-2 h-24 rounded object-cover"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Sn,{id:"itemIsActive",checked:ie,onCheckedChange:ne}),e.jsx(ee,{htmlFor:"itemIsActive",children:"Active (visible to agents)"})]})]}),e.jsxs(Ar,{children:[e.jsx($,{variant:"outline",onClick:()=>y(!1),children:"Cancel"}),e.jsx($,{onClick:ys,disabled:ct.isPending||Xe.isPending,children:ct.isPending||Xe.isPending?"Saving...":"Save"})]})]})}),e.jsx(kc,{open:!!f,onOpenChange:()=>g(null),children:e.jsxs(cc,{children:[e.jsxs(dc,{children:[e.jsx(hc,{children:"Delete Category"}),e.jsx(mc,{children:"Are you sure you want to delete this category? Items in this category will become uncategorized."})]}),e.jsxs(uc,{children:[e.jsx(fc,{children:"Cancel"}),e.jsx(tc,{onClick:Yt,className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Delete"})]})]})}),e.jsx(kc,{open:!!te,onOpenChange:()=>J(null),children:e.jsxs(cc,{children:[e.jsxs(dc,{children:[e.jsx(hc,{children:"Delete Item"}),e.jsx(mc,{children:"Are you sure you want to delete this item? This action cannot be undone."})]}),e.jsxs(uc,{children:[e.jsx(fc,{children:"Cancel"}),e.jsx(tc,{onClick:Bt,className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Delete"})]})]})}),t==="point-settings"&&e.jsxs(Ne,{className:"mt-4",children:[e.jsx(Ct,{children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Sd,{className:"h-5 w-5"}),e.jsxs("div",{children:[e.jsx(At,{children:"Point Reward Settings"}),e.jsx(Gn,{children:"Configure how many points agents earn for various actions. Adjust these values to run double-points promotions."})]})]})}),e.jsx(Ie,{children:!Ae||Ae.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(Sd,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{children:"No point settings configured."})]}):e.jsxs(mi,{children:[e.jsx(fi,{children:e.jsxs(En,{children:[e.jsx(Dt,{children:"Action"}),e.jsx(Dt,{children:"Description"}),e.jsx(Dt,{className:"text-center w-32",children:"Points"}),e.jsx(Dt,{className:"text-right w-24",children:"Save"})]})}),e.jsx(pi,{children:Ae.map(St=>e.jsxs(En,{children:[e.jsx(wt,{children:e.jsx("p",{className:"font-medium",children:St.action_name})}),e.jsx(wt,{children:e.jsx("p",{className:"text-sm text-muted-foreground",children:St.description})}),e.jsx(wt,{className:"text-center",children:e.jsx(pe,{type:"number",min:"0",className:"w-20 mx-auto text-center",value:Ke[St.id]??St.points.toString(),onChange:Xs=>nt(vt=>({...vt,[St.id]:Xs.target.value}))})}),e.jsx(wt,{className:"text-right",children:e.jsx($,{size:"sm",variant:"outline",disabled:Ke[St.id]===void 0||Ke[St.id]===St.points.toString()||at.isPending,onClick:()=>Ft(St.id,St.points),children:e.jsx(tl,{className:"h-4 w-4"})})})]},St.id))})]})})]})]})}function klr(){const s=Qn();return e.jsx(Vs,{children:e.jsxs("div",{className:"space-y-6 p-4 md:p-8",children:[e.jsx(Fm,{title:"Integrations",description:"Manage platform-level service connections"}),e.jsxs(Ne,{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(zd,{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($,{onClick:()=>s("/admin/social-connections"),children:["View ",e.jsx(ei,{className:"h-4 w-4 ml-1"})]})]}),e.jsx(bos,{}),e.jsx(yos,{})]})})}const pEt=s=>{const t="h-4 w-4";return s==="facebook"?e.jsx(Qp,{className:t}):s==="instagram"?e.jsx(Tf,{className:t}):s==="linkedin"?e.jsx(hy,{className:t}):s==="google"?e.jsx(mn,{className:t}):null},Slr=s=>s?new Intl.DateTimeFormat("en-US",{timeZone:"America/New_York",year:"numeric",month:"short",day:"numeric"}).format(new Date(s)):"—";function Clr(){const[s,t]=j.useState([]),[n,r]=j.useState(!0),[a,i]=j.useState(""),[l,o]=j.useState("all");j.useEffect(()=>{(async()=>{r(!0);const{data:m,error:f}=await q.rpc("admin_get_social_connections");if(f){re.error(f.message),r(!1);return}t(m||[]),r(!1)})()},[]);const c=j.useMemo(()=>{const m=a.trim().toLowerCase();return s.filter(f=>l!=="all"&&f.platform!==l?!1:m?(f.user_name||"").toLowerCase().includes(m)||(f.user_email||"").toLowerCase().includes(m)||(f.page_name||"").toLowerCase().includes(m)||(f.platform_username||"").toLowerCase().includes(m):!0)},[s,a,l]),d=j.useMemo(()=>{const m=new Map;return s.forEach(f=>{const g=m.get(f.user_id)||{name:f.user_name,email:f.user_email,platforms:new Set,count:0};g.platforms.add(f.platform),g.count+=1,m.set(f.user_id,g)}),Array.from(m.entries()).map(([f,g])=>({user_id:f,...g}))},[s]),u=j.useMemo(()=>{const m=new Map;return s.forEach(f=>m.set(f.platform,(m.get(f.platform)||0)+1)),{uniqueUsers:d.length,totalConnections:s.length,byPlatform:Array.from(m.entries())}},[s,d]),h=m=>m&&new Date(m).getTime()e.jsxs(Ne,{className:"p-4",children:[e.jsxs("div",{className:"text-sm text-muted-foreground capitalize flex items-center gap-2",children:[pEt(m)," ",m]}),e.jsx("div",{className:"text-2xl font-bold",children:f})]},m))]}),e.jsxs("div",{className:"flex flex-col md:flex-row gap-3",children:[e.jsx(pe,{placeholder:"Search by user, email, page, or handle…",value:a,onChange:m=>i(m.target.value),className:"md:max-w-md"}),e.jsxs(ms,{value:l,onValueChange:o,children:[e.jsx(us,{className:"md:w-48",children:e.jsx(fs,{placeholder:"All platforms"})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"all",children:"All platforms"}),e.jsx(Ge,{value:"facebook",children:"Facebook"}),e.jsx(Ge,{value:"instagram",children:"Instagram"}),e.jsx(Ge,{value:"linkedin",children:"LinkedIn"}),e.jsx(Ge,{value:"google",children:"Google"})]})]})]}),e.jsx(Ne,{children:n?e.jsx("div",{className:"flex items-center justify-center p-12",children:e.jsx(kt,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):e.jsxs(mi,{children:[e.jsx(fi,{children:e.jsxs(En,{children:[e.jsx(Dt,{children:"User"}),e.jsx(Dt,{children:"Platform"}),e.jsx(Dt,{children:"Page / Account"}),e.jsx(Dt,{children:"Status"}),e.jsx(Dt,{children:"Connected"})]})}),e.jsx(pi,{children:c.length===0?e.jsx(En,{children:e.jsx(wt,{colSpan:5,className:"text-center text-muted-foreground py-8",children:"No connections found."})}):c.map(m=>{const f=h(m.token_expires_at);return e.jsxs(En,{children:[e.jsxs(wt,{children:[e.jsx("div",{className:"font-medium",children:m.user_name||"—"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:m.user_email})]}),e.jsx(wt,{children:e.jsxs("div",{className:"flex items-center gap-2 capitalize",children:[pEt(m.platform)," ",m.platform]})}),e.jsxs(wt,{children:[e.jsx("div",{className:"font-medium",children:m.page_name||m.platform_username||"—"}),m.instagram_business_id&&e.jsxs("div",{className:"text-xs text-muted-foreground",children:["IG Business: ",m.instagram_business_id]})]}),e.jsx(wt,{children:m.is_active?f?e.jsxs(Be,{variant:"destructive",className:"gap-1",children:[e.jsx(ll,{className:"h-3 w-3"})," Expired"]}):e.jsx(Be,{children:"Active"}):e.jsx(Be,{variant:"secondary",children:"Inactive"})}),e.jsx(wt,{className:"text-sm text-muted-foreground",children:Slr(m.created_at)})]},m.id)})})]})})]})})}const Alr={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 AX(s,t=18,n=10){return s.length<=t+n+3?s:`${s.slice(0,t)}…${s.slice(-n)}`}function Elr(){var O,U,W,V,G;const s=Vt(),[t,n]=j.useState("Test Push"),[r,a]=j.useState("Testing web push notification"),[i,l]=j.useState("/community"),[o,c]=j.useState(!1),[d,u]=j.useState(!1),[h,m]=j.useState({isSupported:typeof window<"u"&&"serviceWorker"in navigator&&"PushManager"in window}),[f,g]=j.useState(null),[x,y]=j.useState(null),{data:v,isLoading:b}=tt({queryKey:["push-notification-settings"],queryFn:async()=>{const{data:Y,error:X}=await q.from("push_notification_settings").select("*").order("setting_key");if(X)throw X;return Y}}),{data:w,isLoading:S}=tt({queryKey:["push-subscription-stats"],queryFn:async()=>{const{count:Y,error:X}=await q.from("push_subscriptions").select("*",{count:"exact",head:!0});if(X)throw X;return{totalSubscriptions:Y||0}}}),C=ft({mutationFn:async({settingKey:Y,isEnabled:X})=>{const{error:ae}=await q.from("push_notification_settings").update({is_enabled:X}).eq("setting_key",Y);if(ae)throw ae},onSuccess:()=>{s.invalidateQueries({queryKey:["push-notification-settings"]}),re.success("Notification setting updated")},onError:Y=>{re.error("Failed to update setting: "+Y.message)}}),E=j.useMemo(()=>{var Y,X;return h.isSupported?`perm=${h.permission??"unknown"} · controller=${h.controllerPresent?"yes":"no"} · sw=${((Y=h.serviceWorker)==null?void 0:Y.activeState)??"unknown"} · sub=${(X=h.subscription)!=null&&X.endpoint?"yes":"no"}`:"Push not supported in this browser."},[h]);j.useEffect(()=>{let Y=!0;const X=async()=>{var te,J,ce,_e,he,ue,ve;const ie="serviceWorker"in navigator&&"PushManager"in window,ne={isSupported:ie,permission:typeof Notification<"u"?Notification.permission:void 0,controllerPresent:!!((te=navigator.serviceWorker)!=null&&te.controller)};if(!ie){Y&&m(ne);return}try{const{data:Ee,error:Se}=await q.functions.invoke("get-vapid-public-key",{body:{}});if(Se)throw Se;ne.vapidPublicKey=Ee==null?void 0:Ee.vapidPublicKey;const Fe=(await navigator.serviceWorker.getRegistrations()).find(ke=>{var je,Ae,Ce;return(((je=ke.active)==null?void 0:je.scriptURL)||((Ae=ke.waiting)==null?void 0:Ae.scriptURL)||((Ce=ke.installing)==null?void 0:Ce.scriptURL)||"").includes("/sw.js")});if(Fe){ne.pushWorkerScriptUrl=((J=Fe.active)==null?void 0:J.scriptURL)||((ce=Fe.waiting)==null?void 0:ce.scriptURL)||((_e=Fe.installing)==null?void 0:_e.scriptURL),ne.serviceWorker={scope:Fe.scope,activeState:(he=Fe.active)==null?void 0:he.state};const ke=await Fe.pushManager.getSubscription();if(ke){const Ve=ke.toJSON();ne.subscription={endpoint:Ve.endpoint,p256dh:(ue=Ve.keys)==null?void 0:ue.p256dh,auth:(ve=Ve.keys)==null?void 0:ve.auth}}}}catch(Ee){ne.error=(Ee==null?void 0:Ee.message)||String(Ee)}Y&&m(ne)};X();const ae=window.setInterval(X,4e3);return()=>{Y=!1,window.clearInterval(ae)}},[]);const I=async()=>{if(typeof Notification>"u"){re.error("Notifications API not available in this browser.");return}try{if(Notification.permission!=="granted"&&await Notification.requestPermission()!=="granted"){re.error("Notification permission not granted.");return}new Notification("Local notification test",{body:"If you see this, OS/browser notifications can display."}),re.success("Triggered a local notification (not push).")}catch(Y){re.error(`Local notification failed: ${(Y==null?void 0:Y.message)||String(Y)}`)}},P=async()=>{c(!0),g(null);try{const{data:Y,error:X}=await q.functions.invoke("send-push-notification",{body:{title:t,body:r,url:i}});if(X)throw X;g({sent:Y==null?void 0:Y.sent,failed:Y==null?void 0:Y.failed,expiredCleaned:Y==null?void 0:Y.expiredCleaned,vapidPublicKey:Y==null?void 0:Y.vapidPublicKey}),(Y==null?void 0:Y.sent)>0?re.success(`Test notification sent to ${Y.sent} subscriber(s)`):(Y==null?void 0:Y.failed)>0?re.warning(`Notification failed for ${Y.failed} subscriber(s). ${Y.expired||0} expired subscriptions cleaned up.`):re.info("No active subscriptions to send to")}catch(Y){console.error("Error sending test notification:",Y),g({error:(Y==null?void 0:Y.message)||String(Y)}),re.error("Failed to send test notification: "+(Y.message||"Unknown error"))}finally{c(!1)}},R=async()=>{u(!0),y(null);try{const{data:Y,error:X}=await q.functions.invoke("generate-vapid-keys",{body:{}});if(X)throw X;const ae=Y==null?void 0:Y.publicKey,ie=Y==null?void 0:Y.privateKey;if(!ae||!ie)throw new Error("generate-vapid-keys did not return keys");y({publicKey:ae,privateKey:ie}),re.success("Generated new VAPID keys. Update backend secrets, then clear + re-subscribe.")}catch(Y){console.error("Error generating VAPID keys:",Y),re.error("Failed to generate VAPID keys: "+((Y==null?void 0:Y.message)||"Unknown error"))}finally{u(!1)}},D=ft({mutationFn:async()=>{const{error:Y}=await q.from("push_subscriptions").delete().neq("id","00000000-0000-0000-0000-000000000000");if(Y)throw Y},onSuccess:()=>{re.success("All subscriptions cleared. Users will need to re-enable notifications."),s.invalidateQueries({queryKey:["push-subscription-stats"]})},onError:Y=>{re.error("Failed to clear subscriptions: "+Y.message)}});return e.jsx(Vs,{title:"Notification Settings",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(Fm,{title:"Notification Settings",description:"Manage push notifications and test the notification system"}),e.jsxs(Ne,{children:[e.jsxs(Ct,{children:[e.jsxs(At,{className:"flex items-center gap-2",children:[e.jsx(Zn,{className:"h-5 w-5"}),"Push Notification Subscribers"]}),e.jsx(Gn,{children:"Current active push notification subscriptions"})]}),e.jsx(Ie,{children:e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx("div",{className:"text-4xl font-bold",children:S?"...":(w==null?void 0:w.totalSubscriptions)||0}),e.jsx("div",{className:"text-sm text-muted-foreground",children:"active subscriptions"})]})})]}),e.jsxs(Ne,{children:[e.jsxs(Ct,{children:[e.jsxs(At,{className:"flex items-center gap-2",children:[e.jsx(Sd,{className:"h-5 w-5"}),"Notification Types"]}),e.jsx(Gn,{children:"Control which types of push notifications are sent to users"})]}),e.jsx(Ie,{children:b?e.jsx("div",{className:"text-sm text-muted-foreground",children:"Loading settings..."}):e.jsx("div",{className:"space-y-4",children:v==null?void 0:v.map(Y=>{const X=Alr[Y.setting_key]||{label:Y.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:X.icon}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:X.label}),e.jsx("div",{className:"text-sm text-muted-foreground",children:Y.description})]})]}),e.jsx(Sn,{checked:Y.is_enabled,onCheckedChange:ae=>C.mutate({settingKey:Y.setting_key,isEnabled:ae}),disabled:C.isPending})]},Y.id)})})})]}),e.jsxs(Ne,{children:[e.jsxs(Ct,{children:[e.jsxs(At,{className:"flex items-center gap-2",children:[e.jsx(qy,{className:"h-5 w-5"}),"Send Test Notification"]}),e.jsx(Gn,{children:"Send a test push notification to all subscribed users"})]}),e.jsxs(Ie,{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:E}),h.error&&e.jsx("div",{className:"mt-2 text-destructive",children:h.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:h.vapidPublicKey?AX(h.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: ",(O=h.serviceWorker)!=null&&O.scope?AX(h.serviceWorker.scope,24,8):"none"]}),e.jsxs("div",{children:["active: ",((U=h.serviceWorker)==null?void 0:U.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: ",(W=h.subscription)!=null&&W.endpoint?AX(h.subscription.endpoint,40,12):"none"]}),e.jsxs("div",{children:["p256dh: ",(V=h.subscription)!=null&&V.p256dh?AX(h.subscription.p256dh,22,10):"none"]}),e.jsxs("div",{children:["auth: ",(G=h.subscription)!=null&&G.auth?AX(h.subscription.auth,22,10):"none"]})]})]})]}),e.jsxs("div",{className:"mt-3 flex flex-wrap gap-2",children:[e.jsx($,{variant:"outline",onClick:I,children:"Local notification test"}),e.jsx($,{variant:"outline",onClick:()=>window.location.reload(),children:"Reload page"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"test-title",children:"Notification Title"}),e.jsx(pe,{id:"test-title",value:t,onChange:Y=>n(Y.target.value),placeholder:"Enter notification title"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"test-body",children:"Notification Body"}),e.jsx(Rs,{id:"test-body",value:r,onChange:Y=>a(Y.target.value),placeholder:"Enter notification message",rows:3})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"test-url",children:"Click URL (optional)"}),e.jsx(pe,{id:"test-url",value:i,onChange:Y=>l(Y.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($,{onClick:P,disabled:o||!t||!r,className:"w-full sm:w-auto",children:[e.jsx(Yr,{className:"h-4 w-4 mr-2"}),o?"Sending...":"Send Test Notification"]}),f&&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"}),f.error?e.jsxs("div",{className:"mt-1 text-destructive",children:["Error: ",f.error]}):e.jsxs("div",{className:"mt-1 space-y-1 text-muted-foreground",children:[e.jsxs("div",{children:["Result: ",f.sent??0," sent, ",f.failed??0," failed, ",f.expiredCleaned??0," expired cleaned"]}),f.vapidPublicKey?e.jsxs("div",{className:"break-all",children:["Backend VAPID public key: ",e.jsx("span",{className:"font-mono",children:f.vapidPublicKey})]}):e.jsx("div",{children:"Backend VAPID public key: (not returned)"})]})]})]})]}),e.jsxs(Ne,{children:[e.jsxs(Ct,{children:[e.jsxs(At,{className:"flex items-center gap-2 text-destructive",children:[e.jsx(Wn,{className:"h-5 w-5"}),"Subscription Maintenance"]}),e.jsx(Gn,{children:"Clear all push subscriptions if VAPID keys were changed or subscriptions are invalid"})]}),e.jsxs(Ie,{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($,{variant:"destructive",onClick:()=>D.mutate(),disabled:D.isPending,children:[e.jsx(Wn,{className:"h-4 w-4 mr-2"}),D.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($,{variant:"outline",onClick:R,disabled:d,children:d?"Generating…":"Generate VAPID keys"})}),x&&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:x.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:x.privateKey})]})]})]})]})]})]})})}function Tlr(){const{toast:s}=Bi(),[t,n]=j.useState([]),[r,a]=j.useState({totalPresentations:0,totalViews:0,totalLeads:0,totalCtaClicks:0,agentsUsing:0}),[i,l]=j.useState(!0),{sortKey:o,sortDirection:c,handleSort:d,sortData:u}=Nie("presentation_count","desc"),h=u(t,{name:g=>{var x;return((x=g.name)==null?void 0:x.toLowerCase())||""},presentations:g=>g.presentation_count,views:g=>g.total_views,leads:g=>g.total_leads,cta_clicks:g=>g.total_cta_clicks,conversion:g=>g.total_views>0?g.total_leads/g.total_views*100:0});j.useEffect(()=>{m()},[]);const m=async()=>{try{l(!0);const{data:g,error:x}=await q.rpc("get_admin_presentation_stats");if(x)throw x;if(!g||g.length===0){l(!1);return}const y=g.map(C=>C.owner_user_id),{data:v,error:b}=await q.from("profiles").select("id, name, email, avatar_url").in("id",y);if(b)throw b;const w=new Map((v==null?void 0:v.map(C=>[C.id,C]))||[]),S=g.map(C=>{const E=w.get(C.owner_user_id);return{owner_user_id:C.owner_user_id,name:(E==null?void 0:E.name)||"Unknown",email:(E==null?void 0:E.email)||"",avatar_url:(E==null?void 0:E.avatar_url)||null,presentation_count:Number(C.presentation_count),total_views:Number(C.total_views),total_leads:Number(C.total_leads),total_cta_clicks:Number(C.total_cta_clicks)}});n(S),n(S),a({totalPresentations:S.reduce((C,E)=>C+E.presentation_count,0),totalViews:S.reduce((C,E)=>C+E.total_views,0),totalLeads:S.reduce((C,E)=>C+E.total_leads,0),totalCtaClicks:S.reduce((C,E)=>C+E.total_cta_clicks,0),agentsUsing:S.length})}catch(g){console.error("Error loading presentation stats:",g),s({title:"Error",description:"Failed to load presentation analytics",variant:"destructive"})}finally{l(!1)}},f=[{label:"Agents Using",value:r.agentsUsing,icon:Zn,color:"text-blue-600"},{label:"Total Presentations",value:r.totalPresentations,icon:jb,color:"text-violet-600"},{label:"Total Views",value:r.totalViews,icon:Ca,color:"text-emerald-600"},{label:"Total Leads",value:r.totalLeads,icon:sc,color:"text-amber-600"},{label:"CTA Clicks",value:r.totalCtaClicks,icon:Lm,color:"text-rose-600"}];return e.jsx(Vs,{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:f.map(g=>e.jsxs(Ne,{children:[e.jsxs(Ct,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(At,{className:"text-sm font-medium",children:g.label}),e.jsx(g.icon,{className:`h-4 w-4 ${g.color}`})]}),e.jsx(Ie,{children:i?e.jsx(yn,{className:"h-8 w-16"}):e.jsx("div",{className:"text-2xl font-bold",children:g.value.toLocaleString()})})]},g.label))}),e.jsxs(Ne,{children:[e.jsx(Ct,{children:e.jsxs(At,{className:"flex items-center gap-2",children:[e.jsx(Yl,{className:"h-5 w-5"}),"Agent Breakdown"]})}),e.jsx(Ie,{children:i?e.jsx("div",{className:"space-y-3",children:[...Array(5)].map((g,x)=>e.jsx(yn,{className:"h-12 w-full"},x))}):t.length===0?e.jsx("p",{className:"text-muted-foreground text-center py-8",children:"No presentations created yet."}):e.jsxs(mi,{children:[e.jsx(fi,{children:e.jsxs(En,{children:[e.jsx(Im,{sortKey:"name",currentSortKey:o,currentDirection:c,onSort:d,children:"Agent"}),e.jsx(Im,{sortKey:"presentations",currentSortKey:o,currentDirection:c,onSort:d,className:"text-center",children:"Presentations"}),e.jsx(Im,{sortKey:"views",currentSortKey:o,currentDirection:c,onSort:d,className:"text-center",children:"Views"}),e.jsx(Im,{sortKey:"leads",currentSortKey:o,currentDirection:c,onSort:d,className:"text-center",children:"Leads"}),e.jsx(Im,{sortKey:"cta_clicks",currentSortKey:o,currentDirection:c,onSort:d,className:"text-center",children:"CTA Clicks"}),e.jsx(Im,{sortKey:"conversion",currentSortKey:o,currentDirection:c,onSort:d,className:"text-center",children:"Conversion"})]})}),e.jsx(pi,{children:h.map(g=>{var y,v;const x=g.total_views>0?(g.total_leads/g.total_views*100).toFixed(1):"0.0";return e.jsxs(En,{children:[e.jsx(wt,{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:g.avatar_url?e.jsx("img",{src:g.avatar_url,alt:"",className:"h-full w-full object-cover"}):e.jsx("span",{className:"text-xs font-medium text-muted-foreground",children:((v=(y=g.name)==null?void 0:y.charAt(0))==null?void 0:v.toUpperCase())||"?"})}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium text-sm",children:g.name}),e.jsx("div",{className:"text-xs text-muted-foreground",children:g.email})]})]})}),e.jsx(wt,{className:"text-center font-medium",children:g.presentation_count}),e.jsx(wt,{className:"text-center",children:g.total_views.toLocaleString()}),e.jsx(wt,{className:"text-center",children:g.total_leads>0?e.jsx(Be,{variant:"secondary",children:g.total_leads}):e.jsx("span",{className:"text-muted-foreground",children:"0"})}),e.jsx(wt,{className:"text-center",children:g.total_cta_clicks}),e.jsx(wt,{className:"text-center",children:e.jsxs("span",{className:Number(x)>0?"text-emerald-600 font-medium":"text-muted-foreground",children:[x,"%"]})})]},g.owner_user_id)})})]})})]})]})})}const vUe=s=>s?new Intl.DateTimeFormat("en-US",{timeZone:"America/New_York",month:"short",day:"numeric",year:"numeric"}).format(new Date(s)):"—",Mlr=s=>s==null?"—":`$${Number(s).toLocaleString("en-US",{maximumFractionDigits:0})}`;function Plr(){const{toast:s}=Bi(),[t,n]=j.useState(!0),[r,a]=j.useState([]),[i,l]=j.useState({}),[o,c]=j.useState("");j.useEffect(()=>{(async()=>{try{n(!0);const y=[],v=1e3;for(let S=0;;S+=v){const{data:C,error:E}=await q.from("listing_presentations").select("id, owner_user_id, title, status, property_address_line1, city, state, list_price, template_id, last_generated_at, created_at, updated_at").order("created_at",{ascending:!1}).range(S,S+v-1);if(E)throw E;if(y.push(...C??[]),!C||C.lengthS.owner_user_id))),w={};for(let S=0;S{w[E.id]={name:E.name??"Unknown",email:E.email??""}})}l(w)}catch(y){console.error(y),s({title:"Error",description:"Failed to load presentation data",variant:"destructive"})}finally{n(!1)}})()},[s]);const d=j.useMemo(()=>{const x=Date.now(),y=x-7*24*60*60*1e3,v=x-30*24*60*60*1e3;return{total:r.length,generated:r.filter(b=>!!b.last_generated_at).length,agents:new Set(r.map(b=>b.owner_user_id)).size,thisWeek:r.filter(b=>new Date(b.created_at).getTime()>=y).length,thisMonth:r.filter(b=>new Date(b.created_at).getTime()>=v).length}},[r]),u=j.useMemo(()=>{const x=new Map;return r.forEach(y=>{const v=i[y.owner_user_id],b=x.get(y.owner_user_id)??{user_id:y.owner_user_id,name:(v==null?void 0:v.name)??"Unknown",email:(v==null?void 0:v.email)??"",total:0,generated:0,last_activity:y.updated_at};b.total+=1,y.last_generated_at&&(b.generated+=1),new Date(y.updated_at)>new Date(b.last_activity)&&(b.last_activity=y.updated_at),x.set(y.owner_user_id,b)}),Array.from(x.values()).sort((y,v)=>v.total-y.total)},[r,i]),h=o.trim().toLowerCase(),m=h?u.filter(x=>x.name.toLowerCase().includes(h)||x.email.toLowerCase().includes(h)):u,f=h?r.filter(x=>{const y=i[x.owner_user_id];return(x.title??"").toLowerCase().includes(h)||(x.property_address_line1??"").toLowerCase().includes(h)||(x.city??"").toLowerCase().includes(h)||((y==null?void 0:y.name)??"").toLowerCase().includes(h)||((y==null?void 0:y.email)??"").toLowerCase().includes(h)}):r,g=[{label:"Total presentations",value:d.total,icon:Jr,sub:"All time"},{label:"Agents using it",value:d.agents,icon:Zn,sub:"Created at least one"},{label:"PDFs generated",value:d.generated,icon:Nn,sub:"Rendered at least once"},{label:"Created last 30 days",value:d.thisMonth,icon:Au,sub:`${d.thisWeek} in last 7 days`}];return e.jsx(Vs,{title:"Listing Presentation Studio",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(Fm,{title:"Listing Presentation Studio",description:"Adoption and usage of the Listing Presentation Studio across all agents"}),t?e.jsx("div",{className:"grid gap-4 md:grid-cols-2 lg:grid-cols-4",children:[0,1,2,3].map(x=>e.jsx(yn,{className:"h-28 w-full"},x))}):e.jsx("div",{className:"grid gap-4 md:grid-cols-2 lg:grid-cols-4",children:g.map(x=>e.jsxs(Ne,{children:[e.jsxs(Ct,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(At,{className:"text-sm font-medium",children:x.label}),e.jsx(x.icon,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Ie,{children:[e.jsx("div",{className:"text-2xl font-bold",children:x.value}),e.jsx("p",{className:"text-xs text-muted-foreground",children:x.sub})]})]},x.label))}),e.jsxs("div",{className:"relative max-w-md",children:[e.jsx(Kr,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(pe,{className:"pl-9",placeholder:"Search agents, addresses, titles...",value:o,onChange:x=>c(x.target.value)})]}),e.jsxs(ha,{defaultValue:"agents",className:"space-y-4",children:[e.jsxs(ma,{children:[e.jsxs(Zt,{value:"agents",children:["By agent (",m.length,")"]}),e.jsxs(Zt,{value:"all",children:["All presentations (",f.length,")"]})]}),e.jsx(Xt,{value:"agents",children:e.jsx(Ne,{children:e.jsx(Ie,{className:"p-0",children:e.jsxs(mi,{children:[e.jsx(fi,{children:e.jsxs(En,{children:[e.jsx(Dt,{children:"Agent"}),e.jsx(Dt,{className:"text-right",children:"Presentations"}),e.jsx(Dt,{className:"text-right",children:"Generated"}),e.jsx(Dt,{children:"Last activity"})]})}),e.jsxs(pi,{children:[m.map(x=>e.jsxs(En,{children:[e.jsxs(wt,{children:[e.jsx("div",{className:"font-medium",children:x.name}),e.jsx("div",{className:"text-xs text-muted-foreground",children:x.email})]}),e.jsx(wt,{className:"text-right font-semibold",children:x.total}),e.jsx(wt,{className:"text-right",children:x.generated}),e.jsx(wt,{children:vUe(x.last_activity)})]},x.user_id)),!t&&m.length===0&&e.jsx(En,{children:e.jsx(wt,{colSpan:4,className:"py-10 text-center text-muted-foreground",children:"No agents have created a listing presentation yet."})})]})]})})})}),e.jsx(Xt,{value:"all",children:e.jsx(Ne,{children:e.jsx(Ie,{className:"p-0",children:e.jsxs(mi,{children:[e.jsx(fi,{children:e.jsxs(En,{children:[e.jsx(Dt,{children:"Presentation"}),e.jsx(Dt,{children:"Agent"}),e.jsx(Dt,{children:"Property"}),e.jsx(Dt,{children:"Price"}),e.jsx(Dt,{children:"Status"}),e.jsx(Dt,{children:"Created"}),e.jsx(Dt,{children:"Last generated"})]})}),e.jsxs(pi,{children:[f.slice(0,300).map(x=>{var y,v;return e.jsxs(En,{children:[e.jsx(wt,{className:"font-medium",children:x.title||"Untitled"}),e.jsxs(wt,{children:[e.jsx("div",{children:((y=i[x.owner_user_id])==null?void 0:y.name)??"Unknown"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:((v=i[x.owner_user_id])==null?void 0:v.email)??""})]}),e.jsx(wt,{className:"text-sm",children:[x.property_address_line1,x.city,x.state].filter(Boolean).join(", ")||"—"}),e.jsx(wt,{children:Mlr(x.list_price)}),e.jsx(wt,{children:e.jsx(Be,{variant:x.last_generated_at?"default":"secondary",children:x.last_generated_at?"Generated":x.status||"Draft"})}),e.jsx(wt,{children:vUe(x.created_at)}),e.jsx(wt,{children:vUe(x.last_generated_at)})]},x.id)}),!t&&f.length===0&&e.jsx(En,{children:e.jsx(wt,{colSpan:7,className:"py-10 text-center text-muted-foreground",children:"No presentations found."})})]})]})})})})]})]})})}const yte="listing_revival";function Ilr(){const{user:s,loading:t,isAdmin:n}=vs(),{data:r}=tt({queryKey:["feature-entitlement",yte,s==null?void 0:s.id],enabled:!!s&&!n,staleTime:5*60*1e3,queryFn:async()=>{const{data:a,error:i}=await q.from("feature_entitlements").select("enabled, expires_at, tier").eq("user_id",s.id).eq("feature_key",yte).maybeSingle();if(i)throw i;return{tier:(a==null?void 0:a.tier)??null}}});return{hasAccess:!0,tier:n?"admin":(r==null?void 0:r.tier)??null,isLoading:t}}const Llr=s=>s?new Intl.DateTimeFormat("en-US",{timeZone:"America/New_York",month:"short",day:"numeric",year:"numeric"}).format(new Date(s)):"—";function Rlr(){var u,h;const{user:s}=vs(),t=Vt(),[n,r]=j.useState(""),a=tt({queryKey:["lr-admin-stats"],queryFn:async()=>{const{data:m,error:f}=await q.rpc("get_admin_listing_revival_stats");if(f)throw f;return m??[]}}),i=tt({queryKey:["lr-admin-members",n],queryFn:async()=>{let m=q.from("profiles").select("id, name, email").order("name").limit(200);if(n.trim()){const b=`%${n.trim()}%`;m=m.or(`email.ilike.${b},name.ilike.${b}`)}const{data:f,error:g}=await m;if(g)throw g;const x=(f??[]).map(b=>b.id),{data:y}=await q.from("feature_entitlements").select("user_id, enabled, tier").eq("feature_key",yte).in("user_id",x.length?x:["00000000-0000-0000-0000-000000000000"]),v=new Map((y??[]).map(b=>[b.user_id,b]));return(f??[]).map(b=>{var w;return{user_id:b.id,name:b.name,email:b.email,enabled:!!((w=v.get(b.id))!=null&&w.enabled)}})}}),l=ft({mutationFn:async({userId:m,enabled:f})=>{const{error:g}=await q.from("feature_entitlements").upsert({user_id:m,feature_key:yte,enabled:f,tier:"member",enabled_by:s.id,enabled_at:new Date().toISOString()},{onConflict:"user_id,feature_key"});if(g)throw g;await q.from("feature_entitlement_audit").insert({feature_key:yte,target_user_id:m,action:f?"grant":"revoke",performed_by:s.id})},onSuccess:(m,f)=>{t.invalidateQueries({queryKey:["lr-admin-members"]}),re.success(f.enabled?"Access granted":"Access revoked")},onError:m=>re.error(m.message)}),o=tt({queryKey:["lr-admin-stat-profiles",(a.data??[]).length],enabled:!!((u=a.data)!=null&&u.length),queryFn:async()=>{const m=(a.data??[]).map(g=>g.owner_user_id),{data:f}=await q.from("profiles").select("id, name, email").in("id",m);return new Map((f??[]).map(g=>[g.id,g]))}}),c=j.useMemo(()=>{const m=a.data??[];return{agents:m.length,campaigns:m.reduce((f,g)=>f+Number(g.campaign_count),0),leads:m.reduce((f,g)=>f+Number(g.lead_count),0),hot:m.reduce((f,g)=>f+Number(g.hot_lead_count),0)}},[a.data]),d=[{label:"Agents using it",value:c.agents,icon:Zn},{label:"Campaigns built",value:c.campaigns,icon:Nn},{label:"Seller leads",value:c.leads,icon:qg},{label:"Hot leads",value:c.hot,icon:nh}];return e.jsxs(Vs,{title:"Listing Revival Admin",children:[e.jsx(Fm,{title:"Listing Revival",description:"Track adoption, campaign output and seller leads — and control who gets access."}),e.jsx("div",{className:"grid gap-4 sm:grid-cols-2 lg:grid-cols-4 mt-6",children:d.map(m=>e.jsx(Ne,{children:e.jsxs(Ie,{className:"p-5 flex items-center gap-4",children:[e.jsx("div",{className:"rounded-xl bg-amber-500/15 text-amber-600 p-3",children:e.jsx(m.icon,{className:"h-5 w-5"})}),e.jsxs("div",{children:[e.jsx("div",{className:"text-2xl font-bold tabular-nums",children:a.isLoading?"—":m.value}),e.jsx("div",{className:"text-xs text-muted-foreground uppercase tracking-wider",children:m.label})]})]})},m.label))}),e.jsxs(ha,{defaultValue:"usage",className:"mt-6",children:[e.jsxs(ma,{children:[e.jsx(Zt,{value:"usage",children:"Agent usage"}),e.jsx(Zt,{value:"access",children:"Access"})]}),e.jsx(Xt,{value:"usage",className:"mt-4",children:e.jsxs(Ne,{children:[e.jsx(Ct,{children:e.jsx(At,{className:"text-base",children:"Usage by agent"})}),e.jsx(Ie,{children:a.isLoading?e.jsx("div",{className:"space-y-2",children:[0,1,2].map(m=>e.jsx(yn,{className:"h-10 w-full"},m))}):(h=a.data)!=null&&h.length?e.jsxs(mi,{children:[e.jsx(fi,{children:e.jsxs(En,{children:[e.jsx(Dt,{children:"Agent"}),e.jsx(Dt,{className:"text-right",children:"Campaigns"}),e.jsx(Dt,{className:"text-right",children:"Live pages"}),e.jsx(Dt,{className:"text-right",children:"Leads"}),e.jsx(Dt,{className:"text-right",children:"Hot"}),e.jsx(Dt,{className:"text-right",children:"Engagement"}),e.jsx(Dt,{className:"text-right",children:"Last activity"})]})}),e.jsx(pi,{children:[...a.data].sort((m,f)=>Number(f.campaign_count)-Number(m.campaign_count)).map(m=>{var g;const f=(g=o.data)==null?void 0:g.get(m.owner_user_id);return e.jsxs(En,{children:[e.jsxs(wt,{children:[e.jsx("div",{className:"font-medium",children:(f==null?void 0:f.name)??"Agent"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:(f==null?void 0:f.email)??m.owner_user_id.slice(0,8)})]}),e.jsx(wt,{className:"text-right tabular-nums",children:m.campaign_count}),e.jsx(wt,{className:"text-right tabular-nums",children:m.published_count}),e.jsx(wt,{className:"text-right tabular-nums",children:m.lead_count}),e.jsx(wt,{className:"text-right",children:Number(m.hot_lead_count)>0?e.jsx(Be,{className:"bg-red-500/15 text-red-600 hover:bg-red-500/15",children:m.hot_lead_count}):e.jsx("span",{className:"text-muted-foreground",children:"0"})}),e.jsx(wt,{className:"text-right tabular-nums",children:m.event_count}),e.jsx(wt,{className:"text-right text-sm text-muted-foreground",children:Llr(m.last_activity)})]},m.owner_user_id)})})]}):e.jsx("p",{className:"text-sm text-muted-foreground py-6",children:"No campaigns have been created yet."})})]})}),e.jsx(Xt,{value:"access",className:"mt-4",children:e.jsxs(Ne,{children:[e.jsx(Ct,{children:e.jsx(At,{className:"text-base",children:"Who can use Listing Revival"})}),e.jsxs(Ie,{className:"space-y-4",children:[e.jsxs("div",{className:"relative max-w-sm",children:[e.jsx(Kr,{className:"h-4 w-4 absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground"}),e.jsx(pe,{className:"pl-9",placeholder:"Search agents by name or email",value:n,onChange:m=>r(m.target.value)})]}),i.isLoading?e.jsx("div",{className:"space-y-2",children:[0,1,2].map(m=>e.jsx(yn,{className:"h-10 w-full"},m))}):e.jsxs(mi,{children:[e.jsx(fi,{children:e.jsxs(En,{children:[e.jsx(Dt,{children:"Agent"}),e.jsx(Dt,{children:"Email"}),e.jsx(Dt,{className:"text-right",children:"Access"})]})}),e.jsx(pi,{children:(i.data??[]).map(m=>e.jsxs(En,{children:[e.jsx(wt,{className:"font-medium",children:m.name??"—"}),e.jsx(wt,{className:"text-muted-foreground",children:m.email??"—"}),e.jsx(wt,{className:"text-right",children:e.jsx(Sn,{checked:m.enabled,onCheckedChange:f=>l.mutate({userId:m.user_id,enabled:f})})})]},m.user_id))})]})]})]})})]})]})}function Dlr(){const{toast:s}=Bi(),[t,n]=j.useState([]),[r,a]=j.useState({totalOpenHouses:0,totalVisitors:0,totalLeads:0,activeOpenHouses:0,agentsUsing:0}),[i,l]=j.useState(!0);j.useEffect(()=>{o()},[]);const o=async()=>{try{l(!0);const{data:d,error:u}=await q.rpc("get_admin_guest_book_stats");if(u)throw u;if(!d||d.length===0){l(!1);return}const h=d.map(y=>y.agent_id),{data:m,error:f}=await q.from("profiles").select("id, name, email, avatar_url").in("id",h);if(f)throw f;const g=new Map((m==null?void 0:m.map(y=>[y.id,y]))||[]),x=d.map(y=>{const v=g.get(y.agent_id);return{agent_id:y.agent_id,name:(v==null?void 0:v.name)||"Unknown",email:(v==null?void 0:v.email)||"",avatar_url:(v==null?void 0:v.avatar_url)||null,open_house_count:Number(y.open_house_count),total_visitors:Number(y.total_visitors),total_leads:Number(y.total_leads),active_count:Number(y.active_count)}});x.sort((y,v)=>v.total_visitors-y.total_visitors),n(x),a({totalOpenHouses:x.reduce((y,v)=>y+v.open_house_count,0),totalVisitors:x.reduce((y,v)=>y+v.total_visitors,0),totalLeads:x.reduce((y,v)=>y+v.total_leads,0),activeOpenHouses:x.reduce((y,v)=>y+v.active_count,0),agentsUsing:x.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:r.agentsUsing,icon:Zn,color:"text-blue-600"},{label:"Total Open Houses",value:r.totalOpenHouses,icon:va,color:"text-violet-600"},{label:"Active Now",value:r.activeOpenHouses,icon:Nc,color:"text-emerald-600"},{label:"Total Visitors",value:r.totalVisitors,icon:Ca,color:"text-amber-600"},{label:"Leads Created",value:r.totalLeads,icon:sc,color:"text-rose-600"}];return e.jsx(Vs,{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(Ne,{children:[e.jsxs(Ct,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(At,{className:"text-sm font-medium",children:d.label}),e.jsx(d.icon,{className:`h-4 w-4 ${d.color}`})]}),e.jsx(Ie,{children:i?e.jsx(yn,{className:"h-8 w-16"}):e.jsx("div",{className:"text-2xl font-bold",children:d.value.toLocaleString()})})]},d.label))}),e.jsxs(Ne,{children:[e.jsx(Ct,{children:e.jsxs(At,{className:"flex items-center gap-2",children:[e.jsx(Yl,{className:"h-5 w-5"}),"Agent Breakdown"]})}),e.jsx(Ie,{children:i?e.jsx("div",{className:"space-y-3",children:[...Array(5)].map((d,u)=>e.jsx(yn,{className:"h-12 w-full"},u))}):t.length===0?e.jsx("p",{className:"text-muted-foreground text-center py-8",children:"No open houses created yet."}):e.jsxs(mi,{children:[e.jsx(fi,{children:e.jsxs(En,{children:[e.jsx(Dt,{children:"Agent"}),e.jsx(Dt,{className:"text-center",children:"Open Houses"}),e.jsx(Dt,{className:"text-center",children:"Active"}),e.jsx(Dt,{className:"text-center",children:"Visitors"}),e.jsx(Dt,{className:"text-center",children:"Leads"}),e.jsx(Dt,{className:"text-center",children:"Conversion"})]})}),e.jsx(pi,{children:t.map(d=>{var h,m;const u=d.total_visitors>0?(d.total_leads/d.total_visitors*100).toFixed(1):"0.0";return e.jsxs(En,{children:[e.jsx(wt,{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:((m=(h=d.name)==null?void 0:h.charAt(0))==null?void 0:m.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(wt,{className:"text-center font-medium",children:d.open_house_count}),e.jsx(wt,{className:"text-center",children:d.active_count>0?e.jsx(Be,{variant:"secondary",className:"bg-emerald-100 text-emerald-700",children:d.active_count}):e.jsx("span",{className:"text-muted-foreground",children:"0"})}),e.jsx(wt,{className:"text-center",children:d.total_visitors.toLocaleString()}),e.jsx(wt,{className:"text-center",children:d.total_leads>0?e.jsx(Be,{variant:"secondary",children:d.total_leads}):e.jsx("span",{className:"text-muted-foreground",children:"0"})}),e.jsx(wt,{className:"text-center",children:e.jsxs("span",{className:Number(u)>0?"text-emerald-600 font-medium":"text-muted-foreground",children:[u,"%"]})})]},d.agent_id)})})]})})]})]})})}function Flr(){const[s]=gc(),t=Qn(),[n,r]=j.useState("loading"),a=j.useRef(!1),[i,l]=j.useState("Processing connection...");return j.useEffect(()=>{if(a.current)return;a.current=!0,(async()=>{const c=s.get("code"),d=s.get("error"),u=s.get("error_description"),h=s.get("state");if(d){r("error"),l(u||"Authorization was denied"),re.error("Failed to connect: "+(u||d));return}if(!c){r("error"),l("No authorization code received"),re.error("Failed to connect: No authorization code");return}try{const{data:m,error:f}=await q.functions.invoke("meta-oauth",{body:{action:"exchange_code",code:c,state:h}});if(m&&m.success===!1)throw new Error(m.error||"Failed to connect accounts");if(f){let g=f.message||"Failed to connect accounts";try{const x=f.context;if(x&&typeof x.json=="function"){const y=await x.json();y!=null&&y.error&&(g=y.error)}}catch{}throw new Error(g)}if(m!=null&&m.success)r("success"),l(m.message||"Accounts connected successfully!"),re.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),r("error"),l(m.message||"Failed to complete connection"),re.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(Ne,{className:"w-full max-w-md",children:[e.jsxs(Ct,{className:"text-center",children:[e.jsxs("div",{className:"mx-auto mb-4",children:[n==="loading"&&e.jsx(kt,{className:"h-12 w-12 animate-spin text-primary"}),n==="success"&&e.jsx(Nc,{className:"h-12 w-12 text-green-500"}),n==="error"&&e.jsx(ku,{className:"h-12 w-12 text-destructive"})]}),e.jsxs(At,{children:[n==="loading"&&"Connecting...",n==="success"&&"Connected!",n==="error"&&"Connection Failed"]}),e.jsx(Gn,{children:i})]}),e.jsx(Ie,{className:"flex justify-center",children:e.jsx($,{onClick:()=>t("/admin/integrations"),children:n==="success"?"View Integrations":"Back to Integrations"})})]})})}function Olr(){const s=Vt(),[t,n]=j.useState(""),[r,a]=j.useState(""),[i,l]=j.useState([]),o=j.useRef(null),{data:c,isLoading:d}=tt({queryKey:["prospect-emails"],queryFn:async()=>{const{data:b,error:w}=await q.from("prospect_emails").select("*").order("sent_at",{ascending:!1});if(w)throw w;return b}}),u=(c==null?void 0:c.filter(b=>b.status==="live_lead"))||[],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,liveLeads:u.length,conversionRate:c!=null&&c.length?Math.round(c.filter(b=>b.status==="converted").length/c.length*100):0},m=ft({mutationFn:async b=>{const{data:w,error:S}=await q.functions.invoke("send-prospect-email",{body:{emails:b}});if(S)throw S;return w},onSuccess:b=>{s.invalidateQueries({queryKey:["prospect-emails"]}),re.success(`${b.sent} email${b.sent>1?"s":""} sent successfully!`),n(""),a(""),l([])},onError:b=>{re.error("Failed to send: "+b.message)}}),f=ft({mutationFn:async()=>{var C,E;const{data:{user:b}}=await q.auth.getUser();if(!(b!=null&&b.email))throw new Error("Could not get your email");const{data:w,error:S}=await q.functions.invoke("send-prospect-email",{body:{emails:[{email:b.email,first_name:(E=(C=b.user_metadata)==null?void 0:C.name)==null?void 0:E.split(" ")[0]}],test_mode:!0}});if(S)throw S;return w},onSuccess:()=>{re.success("Test email sent to your inbox!")},onError:b=>{re.error("Failed to send test: "+b.message)}}),g=ft({mutationFn:async()=>{const{data:b,error:w}=await q.functions.invoke("send-prospect-email",{body:{mode:"live_leads"}});if(w)throw w;return b},onSuccess:b=>{s.invalidateQueries({queryKey:["prospect-emails"]}),re.success(`${b.sent} live lead invite${b.sent===1?"":"s"} sent!`)},onError:b=>{re.error("Failed to send live lead invites: "+b.message)}}),x=()=>{if(!t.trim()){re.error("Please enter an email address");return}if(c==null?void 0:c.find(w=>w.email.toLowerCase()===t.trim().toLowerCase())){re.error("This email has already been prospected");return}m.mutate([{email:t.trim(),first_name:r.trim()||void 0}])},y=b=>{var C;const w=(C=b.target.files)==null?void 0:C[0];if(!w)return;const S=new FileReader;S.onload=E=>{var O,U;const P=((O=E.target)==null?void 0:O.result).split(` `).filter(W=>W.trim()),R=[],D=(U=P[0])!=null&&U.toLowerCase().includes("email")?1:0;for(let W=D;WX.trim().replace(/"/g,"")),G=V[0],Y=V[1];G&&G.includes("@")&&R.push({email:G,first_name:Y||void 0})}l(R),re.success(`${R.length} entries loaded from CSV`)},S.readAsText(w),o.current&&(o.current.value="")},v=()=>{if(i.length===0){re.error("No entries to send");return}const b=new Set((c==null?void 0:c.map(S=>S.email.toLowerCase()))||[]),w=i.filter(S=>!b.has(S.email.toLowerCase()));if(w.length===0){re.error("All emails have already been prospected");return}w.length0&&e.jsxs(Ne,{className:"border-red-200/50 bg-red-500/[0.02]",children:[e.jsxs(Ct,{children:[e.jsxs(At,{className:"flex items-center gap-2",children:[e.jsx(Nb,{className:"h-5 w-5 text-red-600"}),"Live Event Leads",e.jsx(Be,{variant:"secondary",className:"ml-2",children:h.liveLeads})]}),e.jsx(Gn,{children:"These agents registered on a LevelUp Live page but haven't received a free trial invite yet."})]}),e.jsx(Ie,{children:e.jsxs($,{onClick:()=>g.mutate(),disabled:g.isPending,className:"gap-2",children:[g.isPending?e.jsx(kt,{className:"h-4 w-4 animate-spin"}):e.jsx(Yr,{className:"h-4 w-4"}),"Send free trial invite to all live leads"]})})]}),e.jsxs(Ne,{children:[e.jsxs(Ct,{children:[e.jsxs(At,{className:"flex items-center gap-2",children:[e.jsx(rh,{className:"h-5 w-5"}),"Send Prospect Email"]}),e.jsxs(Gn,{className:"flex items-center justify-between",children:[e.jsx("span",{children:"Send a beautiful free trial invitation email to potential members"}),e.jsxs($,{variant:"outline",size:"sm",onClick:()=>f.mutate(),disabled:f.isPending,className:"gap-2 ml-4 shrink-0",children:[f.isPending?e.jsx(kt,{className:"h-3 w-3 animate-spin"}):e.jsx(mn,{className:"h-3 w-3"}),"Send Test to Me"]})]})]}),e.jsx(Ie,{children:e.jsxs(ha,{defaultValue:"single",children:[e.jsxs(ma,{className:"mb-4",children:[e.jsxs(Zt,{value:"single",children:[e.jsx(Yr,{className:"h-4 w-4 mr-2"}),"Single Send"]}),e.jsxs(Zt,{value:"bulk",children:[e.jsx(ni,{className:"h-4 w-4 mr-2"}),"Bulk CSV"]})]}),e.jsx(Xt,{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(ee,{htmlFor:"prospect-email",className:"sr-only",children:"Email"}),e.jsx(pe,{id:"prospect-email",type:"email",placeholder:"agent@example.com",value:t,onChange:b=>n(b.target.value),onKeyDown:b=>b.key==="Enter"&&x()})]}),e.jsxs("div",{className:"w-full sm:w-48",children:[e.jsx(ee,{htmlFor:"prospect-name",className:"sr-only",children:"First Name"}),e.jsx(pe,{id:"prospect-name",placeholder:"First name (optional)",value:r,onChange:b=>a(b.target.value),onKeyDown:b=>b.key==="Enter"&&x()})]}),e.jsxs($,{onClick:x,disabled:m.isPending,className:"gap-2",children:[m.isPending?e.jsx(kt,{className:"h-4 w-4 animate-spin"}):e.jsx(Yr,{className:"h-4 w-4"}),"Send Invite"]})]})}),e.jsx(Xt,{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($,{variant:"outline",onClick:()=>{var b;return(b=o.current)==null?void 0:b.click()},className:"gap-2",children:[e.jsx(Jr,{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(Be,{variant:"secondary",className:"gap-1",children:[e.jsx(Zn,{className:"h-3 w-3"}),i.length," entries ready"]}),e.jsxs($,{variant:"ghost",size:"sm",onClick:()=>l([]),children:[e.jsx(gr,{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,w)=>e.jsxs("div",{className:"text-muted-foreground",children:[b.email,b.first_name?` — ${b.first_name}`:""]},w)),i.length>20&&e.jsxs("div",{className:"text-muted-foreground/60",children:["...and ",i.length-20," more"]})]}),e.jsxs($,{onClick:v,disabled:m.isPending,className:"gap-2",children:[m.isPending?e.jsx(kt,{className:"h-4 w-4 animate-spin"}):e.jsx(Yr,{className:"h-4 w-4"}),"Send ",i.length," Invites"]})]})]})})]})})]}),e.jsxs(Ne,{children:[e.jsxs(Ct,{children:[e.jsxs(At,{className:"flex items-center gap-2",children:[e.jsx(mn,{className:"h-5 w-5"}),"Prospect Log"]}),e.jsx(Gn,{children:"Track all sent invitations and their conversion status"})]}),e.jsx(Ie,{children:d?e.jsx("div",{className:"space-y-3",children:[...Array(5)].map((b,w)=>e.jsx(yn,{className:"h-12 w-full"},w))}):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:"Source"}),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=>{var w;return 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:en(new Date(b.sent_at),"MMM d, yyyy")}),e.jsx("td",{className:"py-3 px-4",children:b.status==="converted"?e.jsxs(Be,{className:"bg-green-500/10 text-green-700 hover:bg-green-500/20 border-0",children:[e.jsx(qr,{className:"h-3 w-3 mr-1"}),"Converted"]}):b.status==="live_lead"?e.jsxs(Be,{className:"bg-red-500/10 text-red-700 hover:bg-red-500/20 border-0 gap-1",children:[e.jsx(Nb,{className:"h-3 w-3"}),"Live lead"]}):e.jsxs(Be,{variant:"secondary",className:"gap-1",children:[e.jsx(da,{className:"h-3 w-3"}),"Sent"]})}),e.jsx("td",{className:"py-3 px-4 text-sm text-muted-foreground",children:(w=b.utm_source)!=null&&w.startsWith("toolbox:")?e.jsxs(Be,{variant:"outline",className:"gap-1 font-normal",children:[e.jsx(Jr,{className:"h-3 w-3"}),b.utm_source.replace("toolbox:","")]}):b.utm_source||"—"}),e.jsx("td",{className:"py-3 px-4 text-sm text-muted-foreground",children:b.converted_at?en(new Date(b.converted_at),"MMM d, yyyy"):"—"})]},b.id)})})]})}):e.jsxs("div",{className:"text-center py-12",children:[e.jsx(rh,{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 S9(s){const t=Vt(),{toast:n}=Bi(),r=tt({queryKey:["recruit-stages",s],queryFn:async()=>{if(!s)return[];const{data:c,error:d}=await q.from("recruit_pipeline_stages").select("*").eq("brokerage_id",s).order("sort_order");if(d)throw d;return c},enabled:!!s}),a=tt({queryKey:["recruit-prospects",s],queryFn:async()=>{if(!s)return[];const c=1e3;let d=[],u=0,h=!0;for(;h;){const{data:m,error:f}=await q.from("recruit_prospects").select("*").eq("brokerage_id",s).order("created_at",{ascending:!1}).range(u,u+c-1);if(f)throw f;d=d.concat(m),h=m.length===c,u+=c}return d},enabled:!!s}),i=ft({mutationFn:async c=>{const{data:{user:d}}=await q.auth.getUser();if(!d)throw new Error("Not authenticated");const u={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:h,error:m}=await q.from("recruit_prospects").insert(u).select().single();if(m)throw m;return h},onSuccess:()=>{t.invalidateQueries({queryKey:["recruit-prospects",s]}),n({title:"Prospect added"})},onError:c=>n({title:"Error",description:c.message,variant:"destructive"})}),l=ft({mutationFn:async({id:c,...d})=>{const{data:u,error:h}=await q.from("recruit_prospects").update({...d,updated_at:new Date().toISOString()}).eq("id",c).select().single();if(h)throw h;return u},onSuccess:()=>{t.invalidateQueries({queryKey:["recruit-prospects",s]})},onError:c=>n({title:"Error",description:c.message,variant:"destructive"})}),o=ft({mutationFn:async c=>{const{error:d}=await q.from("recruit_prospects").delete().eq("id",c);if(d)throw d},onSuccess:()=>{t.invalidateQueries({queryKey:["recruit-prospects",s]}),n({title:"Prospect removed"})}});return{stages:r.data||[],prospects:a.data||[],isLoading:r.isLoading||a.isLoading,addProspect:i,updateProspect:l,deleteProspect:o}}function zlr(s){const t=Vt(),{toast:n}=Bi(),r=tt({queryKey:["recruit-activities",s],queryFn:async()=>{if(!s)return[];const{data:i,error:l}=await q.from("recruit_activities").select("*").eq("prospect_id",s).order("created_at",{ascending:!1});if(l)throw l;return i},enabled:!!s}),a=ft({mutationFn:async i=>{const{data:{user:l}}=await q.auth.getUser();if(!l)throw new Error("Not authenticated");const{data:o,error:c}=await q.from("recruit_activities").insert({...i,created_by:l.id}).select().single();if(c)throw c;return o},onSuccess:()=>{t.invalidateQueries({queryKey:["recruit-activities",s]}),n({title:"Activity logged"})},onError:i=>n({title:"Error",description:i.message,variant:"destructive"})});return{activities:r.data||[],isLoading:r.isLoading,addActivity:a}}const gEt=(s,t)=>{var n;return{first_name:"",last_name:"",email:"",phone:"",current_brokerage:"",license_number:"",experience_years:"",annual_production:"",source:"manual",notes:"",stage_id:s||((n=t==null?void 0:t[0])==null?void 0:n.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 qlt({open:s,onOpenChange:t,stages:n,defaultStageId:r,onSubmit:a,isSubmitting:i}){const[l,o]=j.useState(gEt(r,n)),c=u=>h=>o(m=>({...m,[u]:h.target.value})),d=u=>{u.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(gEt(r,n)),t(!1)};return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Os,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(Us,{children:e.jsx(Bs,{children:"Add Recruit Prospect"})}),e.jsxs("form",{onSubmit:d,className:"space-y-4",children:[e.jsxs(ha,{defaultValue:"basic",className:"w-full",children:[e.jsxs(ma,{className:"grid w-full grid-cols-4",children:[e.jsx(Zt,{value:"basic",children:"Basic Info"}),e.jsx(Zt,{value:"production",children:"Production"}),e.jsx(Zt,{value:"social",children:"Social & Web"}),e.jsx(Zt,{value:"personal",children:"Personal"})]}),e.jsxs(Xt,{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(ee,{children:"First Name *"}),e.jsx(pe,{required:!0,value:l.first_name,onChange:c("first_name")})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Last Name"}),e.jsx(pe,{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(ee,{children:"Email"}),e.jsx(pe,{type:"email",value:l.email,onChange:c("email")})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Phone"}),e.jsx(pe,{value:l.phone,onChange:c("phone")})]})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Current Brokerage"}),e.jsx(pe,{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(ee,{children:"License #"}),e.jsx(pe,{value:l.license_number,onChange:c("license_number")})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Experience (years)"}),e.jsx(pe,{type:"number",min:"0",value:l.experience_years,onChange:c("experience_years")})]})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Address"}),e.jsx(pe,{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(ee,{children:"City"}),e.jsx(pe,{value:l.city,onChange:c("city")})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"State"}),e.jsx(pe,{value:l.state,onChange:c("state")})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Zip"}),e.jsx(pe,{value:l.zip_code,onChange:c("zip_code")})]})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Pipeline Stage"}),e.jsxs(ms,{value:l.stage_id,onValueChange:u=>o(h=>({...h,stage_id:u})),children:[e.jsx(us,{children:e.jsx(fs,{})}),e.jsx(hs,{children:n.map(u=>e.jsx(Ge,{value:u.id,children:u.name},u.id))})]})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Referred By"}),e.jsx(pe,{placeholder:"Who referred this prospect?",value:l.referred_by,onChange:c("referred_by")})]})]}),e.jsxs(Xt,{value:"production",className:"space-y-4 mt-4",children:[e.jsxs("div",{children:[e.jsx(ee,{children:"Annual Production Volume"}),e.jsx(pe,{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(ee,{children:"Last Year Volume"}),e.jsx(pe,{placeholder:"e.g. $8.2M",value:l.last_year_volume,onChange:c("last_year_volume")})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Last Year Transactions"}),e.jsx(pe,{type:"number",min:"0",placeholder:"e.g. 24",value:l.last_year_transactions,onChange:c("last_year_transactions")})]})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Avg Sale Price"}),e.jsx(pe,{placeholder:"e.g. $350K",value:l.avg_sale_price,onChange:c("avg_sale_price")})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Specialties / Niche"}),e.jsx(pe,{placeholder:"e.g. Luxury, First-time buyers, Investment",value:l.specialties,onChange:c("specialties")})]})]}),e.jsxs(Xt,{value:"social",className:"space-y-4 mt-4",children:[e.jsxs("div",{children:[e.jsx(ee,{children:"LinkedIn URL"}),e.jsx(pe,{type:"url",placeholder:"https://linkedin.com/in/...",value:l.linkedin_url,onChange:c("linkedin_url")})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Website URL"}),e.jsx(pe,{type:"url",placeholder:"https://...",value:l.website_url,onChange:c("website_url")})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Instagram Handle"}),e.jsx(pe,{placeholder:"@handle",value:l.instagram_handle,onChange:c("instagram_handle")})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Facebook URL"}),e.jsx(pe,{type:"url",placeholder:"https://facebook.com/...",value:l.facebook_url,onChange:c("facebook_url")})]})]}),e.jsxs(Xt,{value:"personal",className:"space-y-4 mt-4",children:[e.jsxs("div",{children:[e.jsx(ee,{children:"Birthday"}),e.jsx(pe,{type:"date",value:l.birthday,onChange:c("birthday")})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Spouse / Partner Name"}),e.jsx(pe,{value:l.spouse_name,onChange:c("spouse_name")})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Interests / Hobbies"}),e.jsx(pe,{placeholder:"Golf, travel, community events...",value:l.interests,onChange:c("interests")})]})]})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Notes"}),e.jsx(Rs,{value:l.notes,onChange:c("notes"),rows:3})]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[e.jsx($,{type:"button",variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsx($,{type:"submit",disabled:i,children:"Add Prospect"})]})]})]})})}function pFe(){const{user:s}=vs();return tt({queryKey:["recruit-email-senders",s==null?void 0:s.id],enabled:!!s,staleTime:6e4,queryFn:async()=>{const[t,n]=await Promise.all([q.from("user_verified_senders").select("email, display_name, status").eq("user_id",s.id).eq("status","verified").limit(1).maybeSingle(),q.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:n.data?{email:n.data.gmail_email}:null}}})}function Vlt({value:s,onChange:t}){const{data:n,isLoading:r}=pFe();return e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs",children:"Send from"}),e.jsxs(ms,{value:s,onValueChange:a=>t(a),disabled:r,children:[e.jsx(us,{className:"mt-1",children:e.jsx(fs,{})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"default",children:e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(ji,{className:"h-3.5 w-3.5"})," Brokerage default sender"]})}),e.jsx(Ge,{value:"mass_email",disabled:!(n!=null&&n.massEmail),children:e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(Gz,{className:"h-3.5 w-3.5"}),"Mass Email",n!=null&&n.massEmail?` (${n.massEmail.email})`:" — not configured"]})}),e.jsx(Ge,{value:"gmail",disabled:!(n!=null&&n.gmail),children:e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(mn,{className:"h-3.5 w-3.5"}),"Gmail",n!=null&&n.gmail?` (${n.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 Sos({open:s,onOpenChange:t,recruitVideoId:n,brokerageId:r,prospectName:a,prospectEmail:i,videoTitle:l,defaultMessage:o}){const c=(a||"").split(" ")[0]||"there",[d,u]=j.useState(""),[h,m]=j.useState(""),[f,g]=j.useState("default"),[x,y]=j.useState(!1),v=Vt(),{data:b}=pFe();j.useEffect(()=>{s&&(u(`${c}, I made you a quick video 🎥`),m(o||""),g(b!=null&&b.massEmail?"mass_email":b!=null&&b.gmail?"gmail":"default"))},[s,c,o,b==null?void 0:b.massEmail,b==null?void 0:b.gmail]);const w=async()=>{var S,C;if(!i){re.error("This prospect has no email address on file.");return}y(!0);try{const{data:E,error:I}=await q.functions.invoke("send-recruit-video-email",{body:{recruit_video_ids:[n],brokerage_id:r,subject_override:d.trim()||void 0,message_override:h.trim()||void 0,send_via:f}});if(I)throw I;if(((E==null?void 0:E.sent)??0)>0)re.success(`Email sent to ${i}`),v.invalidateQueries({queryKey:["recruit-videos"]}),v.invalidateQueries({queryKey:["recruit-videos-prospect"]}),t(!1);else{const R=((C=(S=E==null?void 0:E.results)==null?void 0:S[0])==null?void 0:C.error)||"Failed to send";re.error(R)}}catch(E){re.error((E==null?void 0:E.message)||"Failed to send email")}finally{y(!1)}};return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Os,{className:"max-w-lg",children:[e.jsx(Us,{children:e.jsxs(Bs,{className:"flex items-center gap-2",children:[e.jsx(mn,{className:"h-5 w-5"})," Email video to ",a]})}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs",children:"To"}),e.jsx(pe,{value:i||"— no email on file —",disabled:!0,className:"mt-1"})]}),e.jsx(Vlt,{value:f,onChange:g}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs",children:"Subject"}),e.jsx(pe,{value:d,onChange:S=>u(S.target.value),className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs",children:"Personal message (optional)"}),e.jsx(Rs,{value:h,onChange:S=>m(S.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(Ar,{children:[e.jsx($,{variant:"ghost",onClick:()=>t(!1),disabled:x,children:"Cancel"}),e.jsxs($,{onClick:w,disabled:x||!i,children:[x?e.jsx(kt,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Yr,{className:"h-4 w-4 mr-2"}),"Send Email"]})]})]})})}function j4(s){return s?s.share_token?`https://video.relevelup.com/thumb/${s.share_token}`:s.thumbnail_url||s.preview_url||null:null}const dQe=[{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 Blr(s){return tt({queryKey:["recruit-videos",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await q.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(n)throw n;return t},enabled:!!s})}function $lr(s){return tt({queryKey:["recruit-videos-prospect",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await q.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(n)throw n;return t},enabled:!!s})}function Cos(){const s=Vt(),{toast:t}=Bi();return ft({mutationFn:async n=>{const{data:{user:r}}=await q.auth.getUser();if(!r)throw new Error("Not authenticated");const{data:a,error:i}=await q.from("recruit_videos").insert({prospect_id:n.prospect_id,video_id:n.video_id,brokerage_id:n.brokerage_id,message:n.message||null,created_by:r.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:n=>{s.invalidateQueries({queryKey:["recruit-videos"]}),s.invalidateQueries({queryKey:["recruit-videos-prospect",n.prospect_id]}),t({title:"Video linked to prospect"})},onError:n=>t({title:"Error",description:n.message,variant:"destructive"})})}function Aos(){const s=Vt();return ft({mutationFn:async({id:t,sent_via:n})=>{const{error:r}=await q.from("recruit_videos").update({sent_at:new Date().toISOString(),sent_via:n,updated_at:new Date().toISOString()}).eq("id",t);if(r)throw r},onSuccess:()=>{s.invalidateQueries({queryKey:["recruit-videos"]})}})}function Eos(s){return tt({queryKey:["recruit-video-scripts",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await q.from("recruit_video_scripts").select("*").or(`brokerage_id.eq.${s},is_global.eq.true`).order("created_at",{ascending:!1});if(n)throw n;return t},enabled:!!s})}function Ulr(){const s=Vt(),{toast:t}=Bi();return ft({mutationFn:async n=>{const{data:{user:r}}=await q.auth.getUser();if(!r)throw new Error("Not authenticated");const{data:a,error:i}=await q.from("recruit_video_scripts").insert({...n,created_by:r.id}).select().single();if(i)throw i;return a},onSuccess:()=>{s.invalidateQueries({queryKey:["recruit-video-scripts"]}),t({title:"Script saved"})},onError:n=>t({title:"Error",description:n.message,variant:"destructive"})})}function qlr(){const s=Vt();return ft({mutationFn:async t=>{const{error:n}=await q.from("recruit_video_scripts").delete().eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["recruit-video-scripts"]})}})}function Vlr({prospectId:s,prospectName:t,prospectEmail:n,brokerageId:r}){var G;const{data:a=[],isLoading:i}=$lr(s),{data:l=[]}=Eos(r),o=Cos(),c=x3();Aos();const[d,u]=j.useState("idle"),[h,m]=j.useState(0),[f,g]=j.useState(0),[x,y]=j.useState(""),[v,b]=j.useState(""),[w,S]=j.useState(!1),[C,E]=j.useState(null),[I,P]=j.useState(null),[R,D]=j.useState(null),O=((G=l.find(Y=>Y.id===x))==null?void 0:G.script_text)||"",U=()=>{u("idle"),m(0),g(0),y(""),b("")},W=j.useCallback(async(Y,X)=>{u("uploading");try{const ae=`Recruiting: ${t}`,{videoId:ie,libraryId:ne}=await P6(ae),{uploadUrl:te,apiKey:J}=await I6(ie),ce=new XMLHttpRequest;ce.upload.onprogress=Fe=>{Fe.lengthComputable&&m(Fe.loaded/Fe.total*100)},await new Promise((Fe,ke)=>{ce.onload=()=>ce.status>=200&&ce.status<300?Fe():ke(new Error("Upload failed")),ce.onerror=()=>ke(new Error("Upload failed")),ce.open("PUT",te),ce.setRequestHeader("AccessKey",J),ce.send(Y)}),u("processing");let _e=0;const he=Date.now(),ue=9e4,ve=`https://iframe.mediadelivery.net/embed/${ne}/${ie}`;for(;_e<4&&(await new Promise(ke=>setTimeout(ke,3e3)),!(Date.now()-he>ue));){const Fe=await gk(ie);if(_e=Fe.status,g(Fe.encodeProgress||0),_e===5||_e===6)throw new Error("Video processing failed")}const Ee=await gk(ie),Se=(Ee.storageSize||Y.size)/(1024*1024),Le=await c.mutateAsync({bunny_video_id:ie,playback_url:Ee.directPlayUrl||ve,thumbnail_url:Ee.thumbnailUrl,preview_url:Ee.previewUrl||null,duration_seconds:Ee.length||X,file_size_mb:Se,title:ae,status:_e>=4?"ready":"processing",touch_type:"recruiting"});await o.mutateAsync({prospect_id:s,video_id:Le.id,brokerage_id:r,message:v||void 0}),u("done"),re.success("Video recorded and linked to prospect!"),setTimeout(()=>{S(!1),U()},1500)}catch(ae){re.error(ae.message||"Failed to upload video"),u("record")}},[s,t,r,v,c,o]),V=Y=>{Y&&(navigator.clipboard.writeText(`${window.location.origin}/recruit-video/${Y}`),re.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(ua,{className:"h-4 w-4"})," Video Outreach"]}),e.jsxs(zs,{open:w,onOpenChange:Y=>{!Y&&(d==="uploading"||d==="processing")||(S(Y),Y||U())},children:[e.jsx(jl,{asChild:!0,children:e.jsxs($,{size:"sm",variant:"outline",onClick:()=>u("script"),children:[e.jsx(dn,{className:"h-3.5 w-3.5 mr-1"})," Record Video"]})}),e.jsxs(Os,{className:"max-w-2xl",children:[e.jsx(Us,{children:e.jsxs(Bs,{children:["Record Video for ",t]})}),d==="script"&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs",children:"Choose a Script (optional)"}),e.jsxs(ms,{value:x,onValueChange:y,children:[e.jsx(us,{className:"mt-1",children:e.jsx(fs,{placeholder:"No script — speak freely"})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"none",children:"No script"}),l.map(Y=>{var X;return e.jsx(Ge,{value:Y.id,children:e.jsxs("span",{className:"flex items-center gap-2",children:[Y.title,e.jsx(Be,{variant:"outline",className:"text-[9px] ml-1",children:(X=dQe.find(ae=>ae.value===Y.category))==null?void 0:X.label})]})},Y.id)})]})]}),O&&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:O})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs",children:"Personal Message (shown on landing page)"}),e.jsx(Rs,{value:v,onChange:Y=>b(Y.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($,{onClick:()=>u("record"),className:"w-full",children:[e.jsx(ua,{className:"h-4 w-4 mr-2"})," Start Recording"]})]}),d==="record"&&e.jsx(BT,{maxDurationSeconds:600,onRecordingComplete:W,teleprompterContent:O||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(Yi,{value:h,className:"mx-auto max-w-sm"}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[Math.round(h),"%"]})]}),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(Yi,{value:f,className:"mx-auto max-w-sm"}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[Math.round(f),"%"]})]}),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(Bu,{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(Y=>{var X;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:j4(Y.video)?e.jsx("img",{src:j4(Y.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(ua,{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:((X=Y.video)==null?void 0:X.title)||"Untitled"}),e.jsxs("div",{className:"flex items-center gap-2 mt-0.5",children:[Y.view_count>0?e.jsxs(Be,{variant:"secondary",className:"text-[9px] h-4",children:[e.jsx(Ca,{className:"h-2.5 w-2.5 mr-0.5"}),Y.view_count]}):Y.sent_at?e.jsxs(Be,{variant:"outline",className:"text-[9px] h-4",children:[e.jsx(Yr,{className:"h-2.5 w-2.5 mr-0.5"}),"Sent"]}):e.jsxs(Be,{variant:"outline",className:"text-[9px] h-4",children:[e.jsx(da,{className:"h-2.5 w-2.5 mr-0.5"}),"Draft"]}),e.jsx("span",{className:"text-[10px] text-muted-foreground",children:en(new Date(Y.created_at),"MMM d")})]})]}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx($,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:()=>V(Y.share_token),title:"Copy link",children:e.jsx(Ha,{className:"h-3 w-3"})}),e.jsxs($,{variant:Y.sent_at?"ghost":"default",size:"sm",className:"h-7 gap-1",disabled:!n,onClick:()=>{var ae;E(Y.id),P(((ae=Y.video)==null?void 0:ae.title)||null),D(Y.message||null)},title:n?"Email video to prospect":"No email on file",children:[e.jsx(mn,{className:"h-3 w-3"}),e.jsx("span",{className:"text-[10px]",children:Y.sent_at?"Resend":"Email"})]})]})]},Y.id)})}),C&&e.jsx(Sos,{open:!!C,onOpenChange:Y=>{Y||E(null)},recruitVideoId:C,brokerageId:r,prospectName:t,prospectEmail:n,videoTitle:I,defaultMessage:R})]})}function Hlr({brokerageId:s,onSelect:t}){const{data:n=[],isLoading:r}=tt({queryKey:["recruit-email-templates",s??"global-only"],queryFn:async()=>{let i=q.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=n.reduce((i,l)=>{var o;return(i[o=l.category]||(i[o]=[])).push(l),i},{});return e.jsxs(Uu,{children:[e.jsx(qu,{asChild:!0,children:e.jsxs($,{variant:"outline",size:"sm",className:"gap-2",type:"button",children:[e.jsx(Jr,{className:"h-4 w-4"}),"Use Template",e.jsx(Tl,{className:"h-3.5 w-3.5 opacity-60"})]})}),e.jsx(Eu,{align:"end",className:"w-80 max-h-[420px] overflow-y-auto",children:r?e.jsx("div",{className:"flex items-center justify-center py-4",children:e.jsx(kt,{className:"h-4 w-4 animate-spin text-muted-foreground"})}):n.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(R0,{}),e.jsx(SL,{className:"text-[11px] uppercase tracking-wide text-muted-foreground",children:i}),l.map(c=>e.jsxs(ja,{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(Be,{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 Glr({open:s,onOpenChange:t,prospectId:n,brokerageId:r,prospectName:a,prospectEmail:i}){const{user:l}=vs(),o=(a||"").split(" ")[0]||"there",[c,d]=j.useState(""),[u,h]=j.useState(""),[m,f]=j.useState("default"),[g,x]=j.useState(!1),[y,v]=j.useState(null),[b,w]=j.useState(!1),S=Vt(),{data:C}=pFe();j.useEffect(()=>{if(s){d(`Hi ${o}`),h("");const O=C!=null&&C.massEmail?"mass_email":C!=null&&C.gmail?"gmail":"default";f(O),v(null),w(!1)}},[s,o,C==null?void 0:C.massEmail,C==null?void 0:C.gmail]);const{data:E=[],isLoading:I}=tt({queryKey:["prospect-email-video-library",l==null?void 0:l.id],queryFn:async()=>{const{data:O,error:U}=await q.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(U)throw U;return O??[]},enabled:s&&!!(l!=null&&l.id)}),P=E.find(O=>O.id===y)||null,R=async()=>{var O,U;if(!i){re.error("This prospect has no email address on file.");return}if(!c.trim()||!u.trim()){re.error("Subject and message are required.");return}x(!0);try{if(y){const{data:W}=await q.from("recruit_videos").select("id").eq("prospect_id",n).eq("video_id",y).maybeSingle();let V=W==null?void 0:W.id;if(!V){const{data:ae,error:ie}=await q.from("recruit_videos").insert({prospect_id:n,video_id:y,brokerage_id:r,message:u.trim(),created_by:l.id}).select("id").single();if(ie)throw ie;V=ae.id}const{data:G,error:Y}=await q.functions.invoke("send-recruit-video-email",{body:{recruit_video_ids:[V],brokerage_id:r,subject_override:c.trim(),message_override:u.trim(),send_via:m}});if(Y)throw Y;if(((G==null?void 0:G.sent)??0)>0)re.success(`Email sent to ${i}`),S.invalidateQueries({queryKey:["recruit-videos"]}),S.invalidateQueries({queryKey:["recruit-videos-prospect",n]}),S.invalidateQueries({queryKey:["recruit-activities",n]}),S.invalidateQueries({queryKey:["recruit-sent-emails"]}),t(!1);else{const ae=((U=(O=G==null?void 0:G.results)==null?void 0:O[0])==null?void 0:U.error)||"Failed to send";re.error(ae)}}else{const{data:W,error:V}=await q.functions.invoke("send-recruit-prospect-email",{body:{prospect_id:n,brokerage_id:r,subject:c.trim(),message:u.trim(),send_via:m}});if(V)throw V;W!=null&&W.success?(re.success(`Email sent to ${i}`),S.invalidateQueries({queryKey:["recruit-activities",n]}),S.invalidateQueries({queryKey:["recruit-sent-emails"]}),t(!1)):re.error((W==null?void 0:W.error)||"Failed to send")}}catch(W){re.error((W==null?void 0:W.message)||"Failed to send email")}finally{x(!1)}},D=O=>{const U=W=>W.replace(/\[First Name\]/gi,o);d(U(O.subject)),h(U(O.body)),re.success(`Loaded "${O.title}"`)};return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Os,{className:"max-w-lg max-h-[90vh] overflow-y-auto",children:[e.jsx(Us,{children:e.jsxs(Bs,{className:"flex items-center gap-2",children:[e.jsx(mn,{className:"h-5 w-5"})," Email ",a]})}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs",children:"To"}),e.jsx(pe,{value:i||"— no email on file —",disabled:!0,className:"mt-1"})]}),e.jsx(Vlt,{value:m,onChange:f}),e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx(ee,{className:"text-xs",children:"Subject"}),e.jsx(Hlr,{brokerageId:r,onSelect:D})]}),e.jsx(pe,{value:c,onChange:O=>d(O.target.value)}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs",children:"Message"}),e.jsx(Rs,{value:u,onChange:O=>h(O.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(ee,{className:"text-xs flex items-center gap-1.5",children:[e.jsx(ua,{className:"h-3.5 w-3.5"})," Include a video"]}),P?e.jsxs($,{type:"button",variant:"ghost",size:"sm",className:"h-7 text-xs",onClick:()=>{v(null),w(!1)},children:[e.jsx(gr,{className:"h-3 w-3 mr-1"})," Remove"]}):e.jsx($,{type:"button",variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>w(O=>!O),children:b?"Hide library":"Pick from library"})]}),P&&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:j4(P)?e.jsx("img",{src:j4(P),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(ua,{className:"h-4 w-4 text-muted-foreground"})})}),e.jsx("p",{className:"text-xs font-medium truncate flex-1",children:P.title||"Untitled video"})]}),!P&&b&&e.jsx("div",{className:"max-h-56 overflow-y-auto space-y-1 -mx-1 px-1",children:I?e.jsx("div",{className:"flex items-center justify-center py-4",children:e.jsx(kt,{className:"h-4 w-4 animate-spin text-muted-foreground"})}):E.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."}):E.map(O=>e.jsxs("button",{type:"button",onClick:()=>{v(O.id),w(!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:j4(O)?e.jsx("img",{src:j4(O),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(ua,{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:O.title||"Untitled video"}),O.duration_seconds&&e.jsxs("p",{className:"text-[10px] text-muted-foreground",children:[Math.floor(O.duration_seconds/60),":",String(Math.floor(O.duration_seconds%60)).padStart(2,"0")]})]})]},O.id))}),P&&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(Ar,{children:[e.jsx($,{variant:"ghost",onClick:()=>t(!1),disabled:g,children:"Cancel"}),e.jsxs($,{onClick:R,disabled:g||!i,children:[g?e.jsx(kt,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Yr,{className:"h-4 w-4 mr-2"}),"Send Email"]})]})]})})}function Wlr(s){return tt({queryKey:["recruit-campaign-sends",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await q.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(n)throw n;return t},enabled:!!s})}const xEt=[{value:"call",label:"Phone Call",icon:Da},{value:"email",label:"Email",icon:mn},{value:"text",label:"Text Message",icon:eo},{value:"meeting",label:"Meeting",icon:Ta},{value:"note",label:"Note",icon:Jr},{value:"campaign_email",label:"Campaign Email",icon:Yr}];function Sj({label:s,value:t,icon:n}){return t?e.jsxs("div",{children:[e.jsxs("span",{className:"text-xs text-muted-foreground flex items-center gap-1",children:[n&&e.jsx(n,{className:"h-3 w-3"})," ",s]}),e.jsx("p",{className:"font-medium text-sm",children:t})]}):null}function rhe({label:s,url:t,icon:n}){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(n,{className:"h-3.5 w-3.5"})," ",s," ",e.jsx(kr,{className:"h-3 w-3 opacity-50"})]}):null}function xp({label:s,value:t,onChange:n,type:r="text",placeholder:a}){return e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs",children:s}),e.jsx(pe,{type:r,value:t,onChange:i=>n(i.target.value),placeholder:a,className:"mt-1 h-8 text-sm"})]})}function Hlt({prospect:s,stages:t,brokerageId:n,open:r,onOpenChange:a,onUpdate:i,onDelete:l}){const{activities:o,addActivity:c}=zlr((s==null?void 0:s.id)||null),{data:d=[]}=Wlr((s==null?void 0:s.id)||null),[u,h]=j.useState({type:"note",title:"",description:""}),[m,f]=j.useState(!1),[g,x]=j.useState(!1),[y,v]=j.useState({}),[b,w]=j.useState(!1);if(!s)return null;const S=()=>{var V,G;v({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:((V=s.experience_years)==null?void 0:V.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:((G=s.last_year_transactions)==null?void 0:G.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||""}),x(!0)},C=()=>{const V={id:s.id};for(const[G,Y]of Object.entries(y))G==="experience_years"||G==="last_year_transactions"?V[G]=Y?parseInt(Y):null:V[G]=Y||null;i(V),x(!1)},E=()=>x(!1),I=V=>G=>v(Y=>({...Y,[V]:G})),P=()=>{u.title.trim()&&(c.mutate({prospect_id:s.id,activity_type:u.type,title:u.title,description:u.description||null}),h({type:"note",title:"",description:""}),f(!1))},R=t.find(V=>V.id===s.stage_id),D=s.address||s.city||s.state,O=s.last_year_volume||s.last_year_transactions||s.avg_sale_price||s.specialties||s.annual_production,U=s.linkedin_url||s.website_url||s.instagram_handle||s.facebook_url,W=s.birthday||s.spouse_name||s.interests||s.referred_by;return e.jsxs(Wy,{open:r,onOpenChange:V=>{V||x(!1),a(V)},children:[e.jsx(py,{className:"w-full sm:max-w-lg p-0",children:e.jsx(uo,{className:"h-full",children:e.jsxs("div",{className:"p-6 space-y-5",children:[e.jsx(D0,{children:e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsxs("div",{children:[e.jsxs(F0,{className:"text-xl",children:[s.first_name," ",s.last_name]}),R&&e.jsx(Be,{variant:"outline",style:{borderColor:R.color,color:R.color},className:"mt-1",children:R.name})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[g?e.jsxs(e.Fragment,{children:[e.jsx($,{variant:"ghost",size:"icon",onClick:E,children:e.jsx(gr,{className:"h-4 w-4"})}),e.jsx($,{variant:"default",size:"icon",onClick:C,children:e.jsx(tl,{className:"h-4 w-4"})})]}):e.jsx($,{variant:"ghost",size:"icon",onClick:S,title:"Edit prospect",children:e.jsx(gi,{className:"h-4 w-4"})}),e.jsxs(kc,{children:[e.jsx(jx,{asChild:!0,children:e.jsx($,{variant:"ghost",size:"icon",className:"text-destructive hover:text-destructive",children:e.jsx(Wn,{className:"h-4 w-4"})})}),e.jsxs(cc,{children:[e.jsxs(dc,{children:[e.jsx(hc,{children:"Delete prospect?"}),e.jsx(mc,{children:"This will permanently remove this prospect and all their activity history."})]}),e.jsxs(uc,{children:[e.jsx(fc,{children:"Cancel"}),e.jsx(tc,{onClick:()=>{l(s.id),a(!1)},children:"Delete"})]})]})]})]})]})}),!g&&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(mn,{className:"h-3.5 w-3.5 flex-shrink-0"}),e.jsx("span",{className:"truncate",children:s.email})]}),e.jsxs($,{size:"sm",variant:"outline",className:"h-7 gap-1.5 flex-shrink-0",onClick:()=>w(!0),children:[e.jsx(mn,{className:"h-3 w-3"})," Email"]})]}),s.phone&&e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground",children:[e.jsx(Da,{className:"h-3.5 w-3.5"})," ",s.phone]}),D&&e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground",children:[e.jsx(ci,{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(ee,{className:"text-xs text-muted-foreground",children:"Move to Stage"}),e.jsxs(ms,{value:s.stage_id||"",onValueChange:V=>i({id:s.id,stage_id:V}),children:[e.jsx(us,{className:"mt-1",children:e.jsx(fs,{})}),e.jsx(hs,{children:t.map(V=>e.jsx(Ge,{value:V.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:V.color}}),V.name]})},V.id))})]})]}),e.jsxs(ha,{defaultValue:"details",className:"w-full",children:[e.jsxs(ma,{className:"grid w-full grid-cols-4 h-8 text-xs",children:[e.jsx(Zt,{value:"details",className:"text-xs",children:"Details"}),e.jsx(Zt,{value:"production",className:"text-xs",children:"Production"}),e.jsx(Zt,{value:"social",className:"text-xs",children:"Social"}),e.jsx(Zt,{value:"personal",className:"text-xs",children:"Personal"})]}),g?e.jsxs(e.Fragment,{children:[e.jsxs(Xt,{value:"details",className:"mt-3 space-y-3",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsx(xp,{label:"First Name",value:y.first_name,onChange:I("first_name")}),e.jsx(xp,{label:"Last Name",value:y.last_name,onChange:I("last_name")})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsx(xp,{label:"Email",value:y.email,onChange:I("email"),type:"email"}),e.jsx(xp,{label:"Phone",value:y.phone,onChange:I("phone")})]}),e.jsx(xp,{label:"Current Brokerage",value:y.current_brokerage,onChange:I("current_brokerage")}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsx(xp,{label:"License #",value:y.license_number,onChange:I("license_number")}),e.jsx(xp,{label:"Experience (years)",value:y.experience_years,onChange:I("experience_years"),type:"number"})]}),e.jsx(xp,{label:"Address",value:y.address,onChange:I("address"),placeholder:"Street address"}),e.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[e.jsx(xp,{label:"City",value:y.city,onChange:I("city")}),e.jsx(xp,{label:"State",value:y.state,onChange:I("state")}),e.jsx(xp,{label:"Zip",value:y.zip_code,onChange:I("zip_code")})]}),e.jsx(xp,{label:"Source",value:y.source,onChange:I("source")}),e.jsx(xp,{label:"Referred By",value:y.referred_by,onChange:I("referred_by")}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs",children:"Notes"}),e.jsx(Rs,{value:y.notes,onChange:V=>v(G=>({...G,notes:V.target.value})),rows:3,className:"mt-1 text-sm"})]})]}),e.jsxs(Xt,{value:"production",className:"mt-3 space-y-3",children:[e.jsx(xp,{label:"Annual Production",value:y.annual_production,onChange:I("annual_production"),placeholder:"e.g. $5M"}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsx(xp,{label:"Last Year Volume",value:y.last_year_volume,onChange:I("last_year_volume"),placeholder:"e.g. $8.2M"}),e.jsx(xp,{label:"Last Year Transactions",value:y.last_year_transactions,onChange:I("last_year_transactions"),type:"number",placeholder:"e.g. 24"})]}),e.jsx(xp,{label:"Avg Sale Price",value:y.avg_sale_price,onChange:I("avg_sale_price"),placeholder:"e.g. $350K"}),e.jsx(xp,{label:"Specialties / Niche",value:y.specialties,onChange:I("specialties"),placeholder:"e.g. Luxury, Investment"})]}),e.jsxs(Xt,{value:"social",className:"mt-3 space-y-3",children:[e.jsx(xp,{label:"LinkedIn URL",value:y.linkedin_url,onChange:I("linkedin_url"),type:"url",placeholder:"https://linkedin.com/in/..."}),e.jsx(xp,{label:"Website URL",value:y.website_url,onChange:I("website_url"),type:"url",placeholder:"https://..."}),e.jsx(xp,{label:"Instagram Handle",value:y.instagram_handle,onChange:I("instagram_handle"),placeholder:"@handle"}),e.jsx(xp,{label:"Facebook URL",value:y.facebook_url,onChange:I("facebook_url"),type:"url",placeholder:"https://facebook.com/..."})]}),e.jsxs(Xt,{value:"personal",className:"mt-3 space-y-3",children:[e.jsx(xp,{label:"Birthday",value:y.birthday,onChange:I("birthday"),type:"date"}),e.jsx(xp,{label:"Spouse / Partner",value:y.spouse_name,onChange:I("spouse_name")}),e.jsx(xp,{label:"Interests / Hobbies",value:y.interests,onChange:I("interests"),placeholder:"Golf, travel, community events..."})]})]}):e.jsxs(e.Fragment,{children:[e.jsxs(Xt,{value:"details",className:"mt-3",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsx(Sj,{label:"Current Brokerage",value:s.current_brokerage}),e.jsx(Sj,{label:"License #",value:s.license_number}),e.jsx(Sj,{label:"Experience",value:s.experience_years!=null?`${s.experience_years} years`:null}),e.jsx(Sj,{label:"Referred By",value:s.referred_by}),e.jsx(Sj,{label:"Source",value:s.source})]}),s.notes&&e.jsxs("div",{className:"mt-3",children:[e.jsx(ee,{className:"text-xs text-muted-foreground",children:"Notes"}),e.jsx("p",{className:"text-sm mt-1 whitespace-pre-wrap",children:s.notes})]})]}),e.jsx(Xt,{value:"production",className:"mt-3",children:O?e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsx(Sj,{label:"Annual Production",value:s.annual_production}),e.jsx(Sj,{label:"Last Year Volume",value:s.last_year_volume}),e.jsx(Sj,{label:"Last Year Transactions",value:s.last_year_transactions}),e.jsx(Sj,{label:"Avg Sale Price",value:s.avg_sale_price}),e.jsx(Sj,{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(Xt,{value:"social",className:"mt-3",children:U?e.jsxs("div",{className:"space-y-2",children:[e.jsx(rhe,{label:"LinkedIn",url:s.linkedin_url,icon:hy}),e.jsx(rhe,{label:"Website",url:s.website_url,icon:dl}),s.instagram_handle&&e.jsx(rhe,{label:s.instagram_handle,url:`https://instagram.com/${s.instagram_handle.replace("@","")}`,icon:Tf}),e.jsx(rhe,{label:"Facebook",url:s.facebook_url,icon:Qp})]}):e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"No social profiles added yet"})}),e.jsx(Xt,{value:"personal",className:"mt-3",children:W?e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsx(Sj,{label:"Birthday",value:s.birthday?en(new Date(s.birthday+"T00:00:00"),"MMMM d, yyyy"):null,icon:ul}),e.jsx(Sj,{label:"Spouse / Partner",value:s.spouse_name,icon:Jo}),e.jsx("div",{className:"col-span-2",children:e.jsx(Sj,{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(Vlr,{prospectId:s.id,prospectName:`${s.first_name} ${s.last_name||""}`,prospectEmail:s.email,brokerageId:n}),e.jsx(Gc,{}),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($,{size:"sm",variant:"outline",onClick:()=>f(!m),children:[e.jsx(dn,{className:"h-3.5 w-3.5 mr-1"})," Log Activity"]})]}),m&&e.jsxs("div",{className:"border rounded-lg p-3 mb-4 space-y-3 bg-muted/30",children:[e.jsxs(ms,{value:u.type,onValueChange:V=>h(G=>({...G,type:V})),children:[e.jsx(us,{children:e.jsx(fs,{})}),e.jsx(hs,{children:xEt.map(V=>e.jsx(Ge,{value:V.value,children:V.label},V.value))})]}),e.jsx(pe,{placeholder:"Subject / Title",value:u.title,onChange:V=>h(G=>({...G,title:V.target.value}))}),e.jsx(Rs,{placeholder:"Details (optional)",value:u.description,onChange:V=>h(G=>({...G,description:V.target.value})),rows:2}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx($,{size:"sm",variant:"ghost",onClick:()=>f(!1),children:"Cancel"}),e.jsx($,{size:"sm",onClick:P,disabled:!u.title.trim(),children:"Save"})]})]}),e.jsx("div",{className:"space-y-3",children:(()=>{const V=[...o.map(G=>({type:"manual",data:G,date:G.created_at})),...d.map(G=>({type:"campaign_email",data:G,date:G.sent_at||G.created_at}))].sort((G,Y)=>new Date(Y.date).getTime()-new Date(G.date).getTime());return V.length===0?e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"No activity logged yet"}):V.map(G=>{if(G.type==="manual"){const X=G.data,ae=xEt.find(ne=>ne.value===X.activity_type),ie=(ae==null?void 0:ae.icon)||Jr;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(ie,{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:X.title}),X.description&&e.jsx("p",{className:"text-muted-foreground text-xs mt-0.5",children:X.description}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:en(new Date(X.created_at),"MMM d, yyyy h:mm a")})]})]},`activity-${X.id}`)}const Y=G.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(Yr,{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 #",Y.email_number]}),e.jsx("p",{className:"text-muted-foreground text-xs mt-0.5",children:Y.subject}),e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5 mt-1.5",children:[Y.status==="failed"?e.jsx(Be,{variant:"destructive",className:"text-[10px] px-1.5 py-0 h-4",children:"Failed"}):e.jsxs(Be,{variant:"outline",className:"text-[10px] px-1.5 py-0 h-4 border-green-500 text-green-600",children:[e.jsx(Yr,{className:"h-2.5 w-2.5 mr-0.5"})," Sent"]}),Y.opened_at?e.jsxs(Be,{variant:"outline",className:"text-[10px] px-1.5 py-0 h-4 border-blue-500 text-blue-600",children:[e.jsx(Ca,{className:"h-2.5 w-2.5 mr-0.5"})," Opened ",en(new Date(Y.opened_at),"MMM d, h:mm a")]}):Y.status!=="failed"?e.jsx(Be,{variant:"outline",className:"text-[10px] px-1.5 py-0 h-4 text-muted-foreground",children:"Not opened"}):null,Y.clicked_at&&e.jsxs(Be,{variant:"outline",className:"text-[10px] px-1.5 py-0 h-4 border-purple-500 text-purple-600",children:[e.jsx(hb,{className:"h-2.5 w-2.5 mr-0.5"})," Clicked ",en(new Date(Y.clicked_at),"MMM d, h:mm a")]})]}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:en(new Date(Y.sent_at||Y.created_at),"MMM d, yyyy h:mm a")})]})]},`send-${Y.id}`)})})()})]})]})})}),e.jsx(Glr,{open:b,onOpenChange:w,prospectId:s.id,brokerageId:s.brokerage_id,prospectName:`${s.first_name} ${s.last_name??""}`.trim(),prospectEmail:s.email})]})}const Klr=["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 Glt({open:s,onOpenChange:t,brokerageId:n,stages:r}){var D;const{toast:a}=Bi(),i=Vt(),l=j.useRef(null),[o,c]=j.useState([]),[d,u]=j.useState([]),[h,m]=j.useState({}),[f,g]=j.useState(((D=r[0])==null?void 0:D.id)||""),[x,y]=j.useState(!1),[v,b]=j.useState("upload"),[w,S]=j.useState(0),C=()=>{c([]),u([]),m({}),b("upload"),S(0)},E=O=>{var V;const U=(V=O.target.files)==null?void 0:V[0];if(!U)return;const W=new FileReader;W.onload=G=>{var J;const X=((J=G.target)==null?void 0:J.result).split(/\r?\n/).filter(ce=>ce.trim());if(X.length<2){a({title:"Invalid CSV",description:"File must have a header row and at least one data row",variant:"destructive"});return}const ae=I(X[0]);u(ae);const ie={},ne=new Set;ae.forEach((ce,_e)=>{const he=ce.toLowerCase().replace(/[^a-z0-9]/g,"");let ue=null;/^firstname$/.test(he)||he==="first"?ue="first_name":/^lastname$/.test(he)||he==="last"?ue="last_name":/^email$/.test(he)||he==="emailaddress"?ue="email":/^mobile$|^phone$|^cellphone$|^mobilephone$/.test(he)?ue="phone":/officename|currentbrokerage|brokerage|company/.test(he)?ue="current_brokerage":/membernumber|licensenumber|license/.test(he)?ue="license_number":/experienceyears|yearsexperience/.test(he)?ue="experience_years":/^totalvolume$|annualproduction/.test(he)?ue="annual_production":/^address$/.test(he)?ue="address":/^city$/.test(he)?ue="city":/^state$/.test(he)?ue="state":/^postalcode$|^zip$|^zipcode$/.test(he)?ue="zip_code":/listsidevolume|lastyearvolume/.test(he)?ue="last_year_volume":/^totalcount$|lastyeartransactions/.test(he)?ue="last_year_transactions":/avgsaleprice|averageprice/.test(he)?ue="avg_sale_price":/linkedin/.test(he)?ue="linkedin_url":/website/.test(he)?ue="website_url":/specialt/.test(he)?ue="specialties":/referr/.test(he)?ue="referred_by":/^notes$|^note$/.test(he)&&(ue="notes"),ue&&!ne.has(ue)&&(ie[String(_e)]=ue,ne.add(ue))}),m(ie);const te=X.slice(1).map(ce=>{const _e=I(ce),he={};return ae.forEach((ue,ve)=>{he[String(ve)]=_e[ve]||""}),he});c(te),b("map")},W.readAsText(U)},I=O=>{const U=[];let W="",V=!1;for(const G of O)G==='"'?V=!V:G===","&&!V?(U.push(W.trim()),W=""):W+=G;return U.push(W.trim()),U},P=async()=>{y(!0);try{const{data:{user:O}}=await q.auth.getUser();if(!O)throw new Error("Not authenticated");const U=o.map(V=>{const G={brokerage_id:n,created_by:O.id,stage_id:f,source:"csv_import",first_name:"Unknown"},Y=G;return Object.entries(h).forEach(([X,ae])=>{var ne;const ie=(ne=V[X])==null?void 0:ne.trim();ie&&(ae==="experience_years"||ae==="last_year_transactions"?Y[ae]=parseInt(ie.replace(/[^0-9.-]/g,""))||null:ae==="annual_production"||ae==="last_year_volume"||ae==="avg_sale_price"?Y[ae]=ie.replace(/[^0-9.$,.-]/g,""):Y[ae]=ie)}),G});let W=0;for(let V=0;V{const O=`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`,U=new Blob([O],{type:"text/csv"}),W=URL.createObjectURL(U),V=document.createElement("a");V.href=W,V.download="recruit-prospects-template.csv",V.click(),URL.revokeObjectURL(W)};return e.jsx(zs,{open:s,onOpenChange:O=>{O||C(),t(O)},children:e.jsxs(Os,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(Us,{children:e.jsx(Bs,{children:"Import Prospects from CSV"})}),v==="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(ek,{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:E}),e.jsxs($,{onClick:()=>{var O;return(O=l.current)==null?void 0:O.click()},children:[e.jsx(ni,{className:"h-4 w-4 mr-2"})," Choose File"]})]}),e.jsx($,{variant:"link",className:"text-xs",onClick:R,children:"Download CSV template"})]}),v==="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(ms,{value:f,onValueChange:g,children:[e.jsx(us,{className:"w-[180px]",children:e.jsx(fs,{})}),e.jsx(hs,{children:r.map(O=>e.jsx(Ge,{value:O.id,children:O.name},O.id))})]})]})]}),e.jsx("div",{className:"border rounded-lg overflow-hidden",children:e.jsxs(mi,{children:[e.jsx(fi,{children:e.jsxs(En,{children:[e.jsx(Dt,{className:"w-[140px]",children:"CSV Column"}),e.jsx(Dt,{className:"w-[160px]",children:"Map To"}),e.jsx(Dt,{children:"Preview"})]})}),e.jsx(pi,{children:d.map((O,U)=>{var W;return e.jsxs(En,{children:[e.jsx(wt,{className:"font-medium text-xs",children:O}),e.jsx(wt,{children:e.jsxs(ms,{value:h[String(U)]||"skip",onValueChange:V=>m(G=>({...G,[String(U)]:V==="skip"?"":V})),children:[e.jsx(us,{className:"h-8 text-xs",children:e.jsx(fs,{})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"skip",children:"— Skip —"}),Klr.map(V=>e.jsx(Ge,{value:V,children:V.replace(/_/g," ")},V))]})]})}),e.jsx(wt,{className:"text-xs text-muted-foreground truncate max-w-[200px]",children:((W=o[0])==null?void 0:W[String(U)])||"—"})]},U)})})]})}),!Object.values(h).includes("first_name")&&e.jsxs("div",{className:"flex items-center gap-2 text-amber-600 text-sm",children:[e.jsx(ll,{className:"h-4 w-4"}),' Map at least "first name" to proceed']}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx($,{variant:"outline",onClick:()=>{C()},children:"Back"}),e.jsx($,{onClick:P,disabled:x||!Object.values(h).includes("first_name"),children:x?"Importing...":`Import ${o.length} Prospects`})]})]}),v==="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(la,{className:"h-6 w-6 text-green-600"})}),e.jsxs("p",{className:"font-semibold",children:[w," prospects imported successfully!"]}),e.jsx($,{onClick:()=>{C(),t(!1)},children:"Close"})]})]})})}function Tos({brokerageId:s}){const{stages:t,prospects:n,isLoading:r,addProspect:a,updateProspect:i,deleteProspect:l}=S9(s),[o,c]=j.useState(!1),[d,u]=j.useState(),[h,m]=j.useState(null),[f,g]=j.useState(!1),[x,y]=j.useState(!1),[v,b]=j.useState(null),[w,S]=j.useState(""),[C,E]=j.useState("all");if(r)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 I=[...new Set(n.map(G=>G.source).filter(G=>!!G))].sort(),P=n.filter(G=>{const Y=w.trim().toLowerCase();return(!Y||`${G.first_name} ${G.last_name||""} ${G.current_brokerage||""} ${G.email||""}`.toLowerCase().includes(Y))&&(C==="all"||G.source===C)}),R=G=>P.filter(Y=>Y.stage_id===G),D=(G,Y)=>{b(Y),G.dataTransfer.effectAllowed="move"},O=G=>{G.preventDefault(),G.dataTransfer.dropEffect="move"},U=(G,Y)=>{G.preventDefault(),v&&(i.mutate({id:v,stage_id:Y}),b(null))},W=G=>{u(G),c(!0)},V=G=>{m(G),g(!0)};return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex flex-col gap-3 rounded-md border bg-card p-3 lg:flex-row lg:items-center lg:justify-between",children:[e.jsxs("div",{className:"flex min-w-0 flex-1 flex-col gap-2 sm:flex-row",children:[e.jsxs("div",{className:"relative min-w-0 flex-1 sm:max-w-sm",children:[e.jsx(Kr,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(pe,{className:"h-9 pl-9",value:w,onChange:G=>S(G.target.value),placeholder:"Search pipeline…"})]}),e.jsxs(ms,{value:C,onValueChange:E,children:[e.jsxs(us,{className:"h-9 w-full sm:w-[190px]",children:[e.jsx(Iw,{className:"mr-2 h-3.5 w-3.5"}),e.jsx(fs,{})]}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"all",children:"All sources"}),I.map(G=>e.jsx(Ge,{value:G,children:G.replace(/_/g," ")},G))]})]})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs($,{variant:"outline",onClick:()=>y(!0),children:[e.jsx(ni,{className:"h-4 w-4 mr-2"})," Import CSV"]}),e.jsxs($,{onClick:()=>{u(void 0),c(!0)},children:[e.jsx(dn,{className:"h-4 w-4 mr-2"})," Add Prospect"]})]})]}),e.jsxs("div",{className:"flex items-center justify-between px-1",children:[e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Showing ",P.length," of ",n.length," prospects"]}),(w||C!=="all")&&e.jsx($,{variant:"ghost",size:"sm",className:"h-7 text-xs",onClick:()=>{S(""),E("all")},children:"Clear filters"})]}),e.jsxs(uo,{className:"w-full",children:[e.jsx("div",{className:"flex gap-4 pb-4",style:{minWidth:t.length*300},children:t.map(G=>{const Y=R(G.id);return e.jsxs("div",{className:"w-[280px] flex-shrink-0 flex flex-col",onDragOver:O,onDrop:X=>U(X,G.id),children:[e.jsxs("div",{className:"mb-3 flex items-center justify-between border-b pb-2 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:G.color}}),e.jsx("h3",{className:"font-semibold text-sm",children:G.name}),e.jsx(Be,{variant:"secondary",className:"text-xs h-5 px-1.5",children:Y.length})]}),e.jsx($,{variant:"ghost",size:"icon",className:"h-6 w-6",onClick:()=>W(G.id),children:e.jsx(dn,{className:"h-3.5 w-3.5"})})]}),e.jsx("div",{className:"min-h-[220px] space-y-2 rounded-md border border-dashed bg-muted/20 p-2",children:Y.map(X=>e.jsx(Ne,{className:"group cursor-pointer rounded-md border-l-4 p-3 shadow-xs transition-all hover:-translate-y-0.5 hover:border-primary/40 hover:shadow-md motion-reduce:hover:translate-y-0",style:{borderLeftColor:G.color},draggable:!0,onDragStart:ae=>D(ae,X.id),onClick:()=>V(X),children:e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(Ug,{className:"mt-0.5 h-4 w-4 cursor-grab text-muted-foreground/40 opacity-40 transition-opacity group-hover:opacity-100"}),e.jsxs("div",{className:"flex-1 min-w-0 space-y-1.5",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("span",{className:"truncate text-sm font-semibold",children:[X.first_name," ",X.last_name]}),X.source&&e.jsx(Be,{variant:"secondary",className:"h-5 shrink-0 px-1.5 text-[9px] capitalize",children:X.source.replace(/_/g," ")})]}),X.current_brokerage&&e.jsxs("div",{className:"flex items-center gap-1.5 text-xs text-muted-foreground",children:[e.jsx(ji,{className:"h-3 w-3"}),e.jsx("span",{className:"truncate",children:X.current_brokerage})]}),(X.annual_production||X.last_year_volume||X.specialties)&&e.jsx("p",{className:"truncate text-[11px] font-medium text-primary",children:X.last_year_volume||X.annual_production||X.specialties}),e.jsxs("div",{className:"flex items-center justify-between gap-2 border-t pt-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[X.email&&e.jsx(mn,{className:"h-3 w-3 text-muted-foreground"}),X.phone&&e.jsx(Da,{className:"h-3 w-3 text-muted-foreground"}),!X.email&&!X.phone&&e.jsx("span",{className:"text-[10px] text-amber-700",children:"Contact info needed"})]}),X.experience_years!=null&&e.jsxs(Be,{variant:"secondary",className:"text-[10px] h-4 px-1",children:[X.experience_years,"yr"]})]})]})]})},X.id))})]},G.id)})}),e.jsx(Bae,{orientation:"horizontal"})]}),e.jsx(qlt,{open:o,onOpenChange:c,stages:t,defaultStageId:d,onSubmit:G=>a.mutate(G),isSubmitting:a.isPending}),e.jsx(Hlt,{prospect:h,stages:t,brokerageId:s,open:f,onOpenChange:g,onUpdate:G=>{i.mutate(G),m(Y=>Y?{...Y,...G}:null)},onDelete:G=>l.mutate(G)}),e.jsx(Glt,{open:x,onOpenChange:y,brokerageId:s,stages:t})]})}function uQe({brokerageId:s}){const{stages:t,prospects:n,isLoading:r,addProspect:a,updateProspect:i,deleteProspect:l}=S9(s),{user:o}=vs(),c=Vt(),[d,u]=j.useState(!1),[h,m]=j.useState(null),[f,g]=j.useState(!1),[x,y]=j.useState(!1),[v,b]=j.useState(""),[w,S]=j.useState("all"),[C,E]=j.useState("all"),[I,P]=j.useState("all"),[R,D]=j.useState(null),[O,U]=j.useState("asc"),[W,V]=j.useState(new Set),[G,Y]=j.useState(!1),[X,ae]=j.useState(""),ie=j.useMemo(()=>{const ke=new Set;return n.forEach(Ve=>{Ve.current_brokerage&&ke.add(Ve.current_brokerage)}),Array.from(ke).sort()},[n]),{data:ne=[]}=tt({queryKey:["recruit-campaigns-list",s],queryFn:async()=>{const{data:ke,error:Ve}=await q.from("recruit_campaigns").select("id, name, warmth_level").or(`brokerage_id.is.null,brokerage_id.eq.${s}`).order("name");if(Ve)throw Ve;return ke}}),{data:te=[]}=tt({queryKey:["recruit-campaign-assignments-lookup",s],queryFn:async()=>{let Ve=[],je=0;for(;;){const{data:Ae,error:Ce}=await q.from("recruit_campaign_assignments").select("prospect_id, campaign_id, status").eq("brokerage_id",s).range(je,je+1e3-1);if(Ce)throw Ce;if(Ve=Ve.concat(Ae??[]),!Ae||Ae.length<1e3)break;je+=1e3}return Ve}}),J=j.useMemo(()=>{const ke=new Map;return te.forEach(Ve=>{ke.has(Ve.prospect_id)||ke.set(Ve.prospect_id,new Set),ke.get(Ve.prospect_id).add(Ve.campaign_id)}),ke},[te]),ce=ke=>{R===ke?U(Ve=>Ve==="asc"?"desc":"asc"):(D(ke),U("asc"))},_e=({column:ke})=>R!==ke?e.jsx(By,{className:"h-3.5 w-3.5 ml-1 text-muted-foreground/50"}):O==="asc"?e.jsx(Zf,{className:"h-3.5 w-3.5 ml-1 text-primary"}):e.jsx(Dg,{className:"h-3.5 w-3.5 ml-1 text-primary"}),he=ke=>t.find(Ve=>Ve.id===ke),ue=j.useMemo(()=>{let ke=n.filter(Ve=>{var ze,$e,ct;const je=!v||`${Ve.first_name} ${Ve.last_name}`.toLowerCase().includes(v.toLowerCase())||((ze=Ve.email)==null?void 0:ze.toLowerCase().includes(v.toLowerCase()))||(($e=Ve.current_brokerage)==null?void 0:$e.toLowerCase().includes(v.toLowerCase())),Ae=w==="all"||Ve.stage_id===w,Ce=C==="all"||Ve.current_brokerage===C;let qe=!0;return I==="in_campaign"?qe=J.has(Ve.id):I==="not_in_campaign"?qe=!J.has(Ve.id):I!=="all"&&(qe=((ct=J.get(Ve.id))==null?void 0:ct.has(I))??!1),je&&Ae&&Ce&&qe});return R&&(ke=[...ke].sort((Ve,je)=>{var ze,$e;let Ae=null,Ce=null;switch(R){case"name":Ae=`${Ve.first_name} ${Ve.last_name||""}`.toLowerCase(),Ce=`${je.first_name} ${je.last_name||""}`.toLowerCase();break;case"stage":Ae=((ze=he(Ve.stage_id))==null?void 0:ze.sort_order)??999,Ce=(($e=he(je.stage_id))==null?void 0:$e.sort_order)??999;break;case"brokerage":Ae=(Ve.current_brokerage||"").toLowerCase(),Ce=(je.current_brokerage||"").toLowerCase();break;case"experience":Ae=Ve.experience_years??-1,Ce=je.experience_years??-1;break;case"production":Ae=(Ve.annual_production||"").toLowerCase(),Ce=(je.annual_production||"").toLowerCase();break;case"source":Ae=(Ve.source||"").toLowerCase(),Ce=(je.source||"").toLowerCase();break;default:return 0}if(Ae===Ce)return 0;if(Ae==null)return 1;if(Ce==null)return-1;const qe=Ae0&&ue.every(ke=>W.has(ke.id)),Ee=ue.some(ke=>W.has(ke.id)),Se=()=>{V(ve?new Set:new Set(ue.map(ke=>ke.id)))},Le=ke=>{V(Ve=>{const je=new Set(Ve);return je.has(ke)?je.delete(ke):je.add(ke),je})},Fe=ft({mutationFn:async()=>{if(!X||!(o!=null&&o.id))throw new Error("Select a campaign");const ke=new Set(te.filter(Ae=>Ae.campaign_id===X).map(Ae=>Ae.prospect_id)),Ve=Array.from(W).filter(Ae=>!ke.has(Ae)).map(Ae=>({prospect_id:Ae,campaign_id:X,brokerage_id:s,assigned_by:o.id,status:"active",current_email_number:0}));if(Ve.length===0)throw new Error("All selected prospects are already in this campaign");const{error:je}=await q.from("recruit_campaign_assignments").insert(Ve);if(je)throw je;return Ve.length},onSuccess:ke=>{re.success(`${ke} prospect(s) added to campaign`),Y(!1),V(new Set),ae(""),c.invalidateQueries({queryKey:["recruit-campaign-assignments-lookup"]})},onError:ke=>re.error(ke.message)});return 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"})}):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(Kr,{className:"absolute left-2.5 top-2.5 h-4 w-4 text-muted-foreground"}),e.jsx(pe,{placeholder:"Search prospects...",value:v,onChange:ke=>b(ke.target.value),className:"pl-8"})]}),e.jsxs("div",{className:"flex gap-2",children:[W.size>0&&e.jsxs($,{variant:"secondary",onClick:()=>Y(!0),className:"gap-1.5",children:[e.jsx(Yr,{className:"h-4 w-4"})," Add ",W.size," to Campaign"]}),e.jsxs($,{variant:"outline",onClick:()=>y(!0),children:[e.jsx(ni,{className:"h-4 w-4 mr-2"})," Import CSV"]}),e.jsxs($,{onClick:()=>u(!0),children:[e.jsx(dn,{className:"h-4 w-4 mr-2"})," Add Prospect"]})]})]}),e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx(Iw,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs(ms,{value:w,onValueChange:S,children:[e.jsx(us,{className:"w-[160px] h-8 text-xs",children:e.jsx(fs,{placeholder:"All stages"})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"all",children:"All stages"}),t.map(ke=>e.jsx(Ge,{value:ke.id,children:ke.name},ke.id))]})]}),e.jsxs(ms,{value:C,onValueChange:E,children:[e.jsxs(us,{className:"w-[200px] h-8 text-xs",children:[e.jsx(ji,{className:"h-3.5 w-3.5 mr-1.5"}),e.jsx(fs,{placeholder:"All brokerages"})]}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"all",children:"All brokerages"}),ie.map(ke=>e.jsx(Ge,{value:ke,children:ke},ke))]})]}),e.jsxs(ms,{value:I,onValueChange:P,children:[e.jsxs(us,{className:"w-[200px] h-8 text-xs",children:[e.jsx(mn,{className:"h-3.5 w-3.5 mr-1.5"}),e.jsx(fs,{placeholder:"Campaign status"})]}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"all",children:"All contacts"}),e.jsx(Ge,{value:"in_campaign",children:"In any campaign"}),e.jsx(Ge,{value:"not_in_campaign",children:"Not in any campaign"}),ne.map(ke=>e.jsxs(Ge,{value:ke.id,children:["In: ",ke.name]},ke.id))]})]}),(w!=="all"||C!=="all"||I!=="all")&&e.jsx($,{variant:"ghost",size:"sm",className:"h-8 text-xs text-muted-foreground",onClick:()=>{S("all"),E("all"),P("all")},children:"Clear filters"})]}),e.jsx("div",{className:"rounded-md border",children:e.jsxs(mi,{children:[e.jsx(fi,{children:e.jsxs(En,{children:[e.jsx(Dt,{className:"w-[40px]",children:e.jsx(ai,{checked:ve,onCheckedChange:Se,"aria-label":"Select all",...Ee&&!ve?{"data-state":"indeterminate"}:{}})}),e.jsx(Dt,{className:"cursor-pointer select-none",onClick:()=>ce("name"),children:e.jsxs("span",{className:"inline-flex items-center",children:["Name ",e.jsx(_e,{column:"name"})]})}),e.jsx(Dt,{className:"cursor-pointer select-none",onClick:()=>ce("stage"),children:e.jsxs("span",{className:"inline-flex items-center",children:["Stage ",e.jsx(_e,{column:"stage"})]})}),e.jsx(Dt,{className:"hidden md:table-cell cursor-pointer select-none",onClick:()=>ce("brokerage"),children:e.jsxs("span",{className:"inline-flex items-center",children:["Brokerage ",e.jsx(_e,{column:"brokerage"})]})}),e.jsx(Dt,{className:"hidden md:table-cell",children:"Contact"}),e.jsx(Dt,{className:"hidden lg:table-cell cursor-pointer select-none",onClick:()=>ce("experience"),children:e.jsxs("span",{className:"inline-flex items-center",children:["Experience ",e.jsx(_e,{column:"experience"})]})}),e.jsx(Dt,{className:"hidden lg:table-cell cursor-pointer select-none",onClick:()=>ce("production"),children:e.jsxs("span",{className:"inline-flex items-center",children:["Production ",e.jsx(_e,{column:"production"})]})}),e.jsx(Dt,{className:"hidden lg:table-cell",children:"Campaigns"}),e.jsx(Dt,{className:"w-[50px]"})]})}),e.jsx(pi,{children:ue.length===0?e.jsx(En,{children:e.jsx(wt,{colSpan:9,className:"text-center text-muted-foreground py-8",children:"No prospects found"})}):ue.map(ke=>{const Ve=he(ke.stage_id),je=J.get(ke.id),Ae=(je==null?void 0:je.size)??0;return e.jsxs(En,{className:"cursor-pointer",onClick:()=>{m(ke),g(!0)},children:[e.jsx(wt,{onClick:Ce=>Ce.stopPropagation(),children:e.jsx(ai,{checked:W.has(ke.id),onCheckedChange:()=>Le(ke.id),"aria-label":`Select ${ke.first_name}`})}),e.jsxs(wt,{className:"font-medium",children:[ke.first_name," ",ke.last_name]}),e.jsx(wt,{children:Ve?e.jsxs(Be,{variant:"outline",className:"text-xs gap-1 whitespace-nowrap",style:{borderColor:Ve.color,color:Ve.color,backgroundColor:`${Ve.color}10`},children:[e.jsx("span",{className:"h-1.5 w-1.5 rounded-full inline-block",style:{backgroundColor:Ve.color}}),Ve.name]}):e.jsx("span",{className:"text-muted-foreground text-xs",children:"—"})}),e.jsx(wt,{className:"hidden md:table-cell",children:ke.current_brokerage?e.jsxs("div",{className:"flex items-center gap-1.5 text-sm",children:[e.jsx(ji,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"truncate max-w-[150px]",children:ke.current_brokerage})]}):e.jsx("span",{className:"text-muted-foreground",children:"—"})}),e.jsx(wt,{className:"hidden md:table-cell",children:e.jsxs("div",{className:"flex items-center gap-2",children:[ke.email&&e.jsx(mn,{className:"h-3.5 w-3.5 text-muted-foreground"}),ke.phone&&e.jsx(Da,{className:"h-3.5 w-3.5 text-muted-foreground"}),!ke.email&&!ke.phone&&e.jsx("span",{className:"text-muted-foreground",children:"—"})]})}),e.jsx(wt,{className:"hidden lg:table-cell",children:ke.experience_years!=null?`${ke.experience_years} yr`:"—"}),e.jsx(wt,{className:"hidden lg:table-cell",children:ke.annual_production||"—"}),e.jsx(wt,{className:"hidden lg:table-cell",children:Ae>0?e.jsxs(Be,{variant:"secondary",className:"text-xs",children:[Ae," campaign",Ae>1?"s":""]}):e.jsx("span",{className:"text-muted-foreground text-xs",children:"None"})}),e.jsx(wt,{children:e.jsx($,{variant:"ghost",size:"icon",className:"h-7 w-7 text-muted-foreground hover:text-destructive",onClick:Ce=>{Ce.stopPropagation(),l.mutate(ke.id)},children:e.jsx(Wn,{className:"h-3.5 w-3.5"})})})]},ke.id)})})]})}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[W.size>0&&e.jsxs("span",{className:"font-medium text-foreground",children:[W.size," selected · "]}),ue.length," of ",n.length," prospects"]}),e.jsx(zs,{open:G,onOpenChange:Y,children:e.jsxs(Os,{className:"sm:max-w-md",children:[e.jsx(Us,{children:e.jsx(Bs,{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:W.size})," selected prospect(s) to a recruiting campaign drip."]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Campaign"}),e.jsxs(ms,{value:X,onValueChange:ae,children:[e.jsx(us,{children:e.jsx(fs,{placeholder:"Select a campaign..."})}),e.jsx(hs,{children:ne.map(ke=>e.jsxs(Ge,{value:ke.id,children:[ke.name," ",e.jsxs("span",{className:"text-muted-foreground ml-1",children:["(",ke.warmth_level,")"]})]},ke.id))})]})]})]}),e.jsxs(Ar,{children:[e.jsx($,{variant:"outline",onClick:()=>Y(!1),children:"Cancel"}),e.jsx($,{onClick:()=>Fe.mutate(),disabled:!X||Fe.isPending,children:Fe.isPending?"Adding...":"Add to Campaign"})]})]})}),e.jsx(qlt,{open:d,onOpenChange:u,stages:t,onSubmit:ke=>a.mutate(ke),isSubmitting:a.isPending}),e.jsx(Hlt,{prospect:h,stages:t,brokerageId:s,open:f,onOpenChange:g,onUpdate:ke=>{i.mutate(ke),m(Ve=>Ve?{...Ve,...ke}:null)},onDelete:ke=>l.mutate(ke)}),e.jsx(Glt,{open:x,onOpenChange:y,brokerageId:s,stages:t})]})}function Mos({brokerageId:s}){const{stages:t,prospects:n,isLoading:r}=S9(s),a=j.useMemo(()=>{if(!t.length||!n.length)return null;const i=n.length,l=t.find(v=>v.name==="Signed"),o=t.find(v=>v.name==="Onboarded"),c=n.filter(v=>v.stage_id===(l==null?void 0:l.id)||v.stage_id===(o==null?void 0:o.id)).length,d=i>0?(c/i*100).toFixed(1):"0",u=new Date,h=i>0?Math.round(n.reduce((v,b)=>v+mk(u,new Date(b.created_at)),0)/i):0,m=t.map(v=>({...v,count:n.filter(b=>b.stage_id===v.id).length})),f={};n.forEach(v=>{const b=v.source||"unknown";f[b]=(f[b]||0)+1});const g=Object.entries(f).sort((v,b)=>b[1]-v[1]),x=new Date;x.setDate(x.getDate()-30);const y=n.filter(v=>new Date(v.created_at)>=x).length;return{total:i,signed:c,conversionRate:d,avgDays:h,byStage:m,bySrc:g,recentCount:y}},[t,n]);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"})}):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(Ne,{children:e.jsx(Ie,{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(Zn,{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(Ne,{children:e.jsx(Ie,{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(Yl,{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(Ne,{children:e.jsx(Ie,{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(da,{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(Ne,{children:e.jsx(Ie,{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(rh,{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(Ne,{children:[e.jsx(Ct,{children:e.jsx(At,{className:"text-base",children:"Pipeline Breakdown"})}),e.jsx(Ie,{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(Ne,{children:[e.jsx(Ct,{children:e.jsx(At,{className:"text-base",children:"Lead Sources"})}),e.jsxs(Ie,{className:"space-y-3",children:[a.bySrc.map(([i,l])=>e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(Be,{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 Ylr=["Outreach","Follow-up","Interview","Offer","Referral","Other"];function Pos({brokerageId:s}){const{toast:t}=Bi(),{user:n}=vs(),r=Vt(),[a,i]=j.useState(null),[l,o]=j.useState(null),[c,d]=j.useState(!1),[u,h]=j.useState(null),{data:m=[],isLoading:f}=tt({queryKey:["recruit-email-templates-manage",s],queryFn:async()=>{const{data:S,error:C}=await q.from("recruit_email_templates").select("*").or(`brokerage_id.is.null,brokerage_id.eq.${s}`).order("sort_order");if(C)throw C;return S}}),g=ft({mutationFn:async S=>{if(S.id){const{error:C}=await q.from("recruit_email_templates").update({category:S.category,title:S.title,subject:S.subject,body:S.body}).eq("id",S.id);if(C)throw C}else{const{error:C}=await q.from("recruit_email_templates").insert({brokerage_id:s,category:S.category||"Outreach",title:S.title,subject:S.subject,body:S.body,created_by:n==null?void 0:n.id,sort_order:100});if(C)throw C}},onSuccess:()=>{r.invalidateQueries({queryKey:["recruit-email-templates-manage",s]}),r.invalidateQueries({queryKey:["recruit-email-templates"]}),t({title:"Template saved"}),d(!1),h(null)},onError:S=>t({title:"Save failed",description:S.message,variant:"destructive"})}),x=ft({mutationFn:async S=>{const{error:C}=await q.from("recruit_email_templates").delete().eq("id",S);if(C)throw C},onSuccess:()=>{r.invalidateQueries({queryKey:["recruit-email-templates-manage",s]}),r.invalidateQueries({queryKey:["recruit-email-templates"]}),t({title:"Template deleted"})},onError:S=>t({title:"Delete failed",description:S.message,variant:"destructive"})}),y=(S,C)=>{navigator.clipboard.writeText(S),i(C),t({title:"Copied to clipboard!"}),setTimeout(()=>i(null),2e3)},v=()=>{h({category:"Outreach",title:"",subject:"",body:""}),d(!0)},b=S=>{h(S),d(!0)},w=Array.from(new Set(m.map(S=>S.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($,{onClick:v,size:"sm",className:"gap-1.5",children:[e.jsx(dn,{className:"h-4 w-4"})," New Template"]})]}),f?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(kt,{className:"h-5 w-5 animate-spin text-muted-foreground"})}):w.map(S=>e.jsxs("div",{className:"space-y-3",children:[e.jsxs("h3",{className:"font-semibold text-sm flex items-center gap-2",children:[e.jsx(mn,{className:"h-4 w-4"})," ",S]}),m.filter(C=>C.category===S).map(C=>{const E=C.brokerage_id!==null;return e.jsxs(Ne,{className:`transition-all ${l===C.id?"ring-2 ring-primary/20":"hover:shadow-sm"}`,children:[e.jsx(Ct,{className:"pb-2 cursor-pointer",onClick:()=>o(l===C.id?null:C.id),children:e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs(At,{className:"text-sm flex items-center gap-2",children:[e.jsx("span",{className:"truncate",children:C.title}),!E&&e.jsx(Be,{variant:"secondary",className:"text-[10px] shrink-0",children:"Built-in"}),E&&e.jsx(Be,{className:"text-[10px] shrink-0",children:"Custom"})]}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-0.5 truncate",children:["Subject: ",C.subject]})]}),e.jsx(Be,{variant:"outline",className:"text-[10px] shrink-0",children:C.category})]})}),l===C.id&&e.jsxs(Ie,{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:C.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:C.body})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs($,{size:"sm",variant:"outline",onClick:()=>y(C.subject,C.id+"-s"),children:[a===C.id+"-s"?e.jsx(la,{className:"h-3.5 w-3.5 mr-1"}):e.jsx(Ha,{className:"h-3.5 w-3.5 mr-1"}),"Copy Subject"]}),e.jsxs($,{size:"sm",variant:"outline",onClick:()=>y(C.body,C.id+"-b"),children:[a===C.id+"-b"?e.jsx(la,{className:"h-3.5 w-3.5 mr-1"}):e.jsx(Ha,{className:"h-3.5 w-3.5 mr-1"}),"Copy Body"]}),E&&e.jsxs(e.Fragment,{children:[e.jsxs($,{size:"sm",variant:"outline",onClick:()=>b(C),children:[e.jsx(gi,{className:"h-3.5 w-3.5 mr-1"})," Edit"]}),e.jsxs($,{size:"sm",variant:"outline",className:"text-destructive hover:text-destructive",onClick:async()=>{await fo("Delete this template?")&&x.mutate(C.id)},children:[e.jsx(Wn,{className:"h-3.5 w-3.5 mr-1"})," Delete"]})]})]})]})]},C.id)})]},S)),e.jsx(zs,{open:c,onOpenChange:d,children:e.jsxs(Os,{className:"max-w-2xl",children:[e.jsx(Us,{children:e.jsx(Bs,{children:u!=null&&u.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(ee,{className:"text-xs",children:"Title"}),e.jsx(pe,{value:(u==null?void 0:u.title)||"",onChange:S=>h(C=>({...C,title:S.target.value})),className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs",children:"Category"}),e.jsx("select",{value:(u==null?void 0:u.category)||"Outreach",onChange:S=>h(C=>({...C,category:S.target.value})),className:"mt-1 flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm",children:Ylr.map(S=>e.jsx("option",{value:S,children:S},S))})]})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs",children:"Subject"}),e.jsx(pe,{value:(u==null?void 0:u.subject)||"",onChange:S=>h(C=>({...C,subject:S.target.value})),className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs",children:"Body"}),e.jsx(Rs,{value:(u==null?void 0:u.body)||"",onChange:S=>h(C=>({...C,body:S.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(Ar,{children:[e.jsx($,{variant:"ghost",onClick:()=>d(!1),children:"Cancel"}),e.jsxs($,{onClick:()=>g.mutate(u||{}),disabled:g.isPending||!(u!=null&&u.title)||!(u!=null&&u.subject)||!(u!=null&&u.body),children:[g.isPending&&e.jsx(kt,{className:"h-4 w-4 mr-2 animate-spin"}),"Save Template"]})]})]})})]})}const yEt={call:Da,email:mn,text:eo,meeting:Ta,note:Jr};function Ios({brokerageId:s}){const{data:t,isLoading:n}=tt({queryKey:["recruit-activity-report",s],queryFn:async()=>{const{data:r,error:a}=await q.from("recruit_prospects").select("id, created_by").eq("brokerage_id",s);if(a)throw a;const i=(r==null?void 0:r.map(f=>f.id))||[];if(i.length===0)return{recruiters:[],recentActivities:[]};const{data:l,error:o}=await q.from("recruit_activities").select("*").in("prospect_id",i).order("created_at",{ascending:!1});if(o)throw o;const c=[...new Set([...r.map(f=>f.created_by),...(l||[]).map(f=>f.created_by)])],{data:d}=await q.from("profiles").select("id, name, email").in("id",c),u=Object.fromEntries((d||[]).map(f=>[f.id,f])),h=J4e(new Date,30);return{recruiters:c.map(f=>{var b,w;const g=(l||[]).filter(S=>S.created_by===f),x=g.filter(S=>new Date(S.created_at)>=h),y={};x.forEach(S=>{y[S.activity_type]=(y[S.activity_type]||0)+1});const v=r.filter(S=>S.created_by===f).length;return{id:f,name:((b=u[f])==null?void 0:b.name)||"Unknown",email:((w=u[f])==null?void 0:w.email)||"",totalActivities:g.length,recentActivities:x.length,byType:y,prospectsCreated:v}}).sort((f,g)=>g.recentActivities-f.recentActivities),recentActivities:(l||[]).slice(0,20)}},enabled:!!s});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"})}):t!=null&&t.recruiters.length?e.jsxs("div",{className:"space-y-6",children:[e.jsxs(Ne,{children:[e.jsx(Ct,{children:e.jsx(At,{className:"text-base",children:"Recruiter Leaderboard (Last 30 Days)"})}),e.jsx(Ie,{className:"space-y-4",children:t.recruiters.map((r,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(sl,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"font-medium text-sm",children:r.name})]}),e.jsx("div",{className:"flex flex-wrap gap-1.5 mt-1.5",children:Object.entries(r.byType).map(([i,l])=>{const o=yEt[i]||Jr;return e.jsxs(Be,{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:r.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:r.prospectsCreated}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"prospects"})]})]},r.id))})]}),e.jsxs(Ne,{children:[e.jsx(Ct,{children:e.jsx(At,{className:"text-base",children:"Recent Activity"})}),e.jsx(Ie,{className:"space-y-3",children:t.recentActivities.map(r=>{const a=yEt[r.activity_type]||Jr;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:r.title}),r.description&&e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:r.description}),e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5",children:en(new Date(r.created_at),"MMM d, h:mm a")})]})]},r.id)})})]})]}):e.jsx("p",{className:"text-sm text-muted-foreground text-center py-8",children:"No recruiter activity yet."})}function Los({brokerageId:s}){const{toast:t}=Bi(),n=Vt(),[r,a]=j.useState(!1),[i,l]=j.useState({first_name:"",last_name:"",email:"",phone:"",current_brokerage:"",notes:""}),{data:o=[],isLoading:c}=tt({queryKey:["recruit-referrals",s],queryFn:async()=>{const{data:y,error:v}=await q.from("recruit_referrals").select("*").eq("brokerage_id",s).order("created_at",{ascending:!1});if(v)throw v;return y}}),d=[...new Set(o.map(y=>y.referred_by))],{data:u=[]}=tt({queryKey:["referral-profiles",d],queryFn:async()=>{if(!d.length)return[];const{data:y}=await q.from("profiles").select("id, name, email").in("id",d);return y||[]},enabled:d.length>0}),h=Object.fromEntries(u.map(y=>[y.id,y])),m=ft({mutationFn:async y=>{const{data:{user:v}}=await q.auth.getUser();if(!v)throw new Error("Not authenticated");const{error:b}=await q.from("recruit_referrals").insert({brokerage_id:s,referred_by:v.id,referee_first_name:y.first_name,referee_last_name:y.last_name||null,referee_email:y.email||null,referee_phone:y.phone||null,referee_current_brokerage:y.current_brokerage||null,notes:y.notes||null});if(b)throw b},onSuccess:()=>{n.invalidateQueries({queryKey:["recruit-referrals",s]}),t({title:"Referral submitted!"}),l({first_name:"",last_name:"",email:"",phone:"",current_brokerage:"",notes:""}),a(!1)},onError:y=>t({title:"Error",description:y.message,variant:"destructive"})}),f=ft({mutationFn:async({id:y,status:v,incentive_status:b})=>{const w={updated_at:new Date().toISOString()};v&&(w.status=v),b&&(w.incentive_status=b);const{error:S}=await q.from("recruit_referrals").update(w).eq("id",y);if(S)throw S},onSuccess:()=>n.invalidateQueries({queryKey:["recruit-referrals",s]})}),g=y=>y==="approved"||y==="signed"?e.jsx(la,{className:"h-3 w-3"}):y==="rejected"?e.jsx(ku,{className:"h-3 w-3"}):e.jsx(da,{className:"h-3 w-3"}),x=y=>y==="approved"||y==="signed"||y==="paid"?"bg-green-500/10 text-green-600 border-green-200":y==="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($,{onClick:()=>a(!0),children:[e.jsx(dn,{className:"h-4 w-4 mr-2"})," Submit Referral"]})]}),o.length===0?e.jsxs(Ne,{className:"py-12 text-center",children:[e.jsx(sc,{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(y=>{var v;return e.jsx(Ne,{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:[y.referee_first_name," ",y.referee_last_name]}),e.jsxs(Be,{variant:"outline",className:x(y.status),children:[g(y.status)," ",y.status]}),y.incentive_status&&e.jsxs(Be,{variant:"outline",className:x(y.incentive_status),children:[e.jsx(ul,{className:"h-3 w-3 mr-1"})," ",y.incentive_status]})]}),e.jsxs("div",{className:"text-xs text-muted-foreground space-y-0.5",children:[y.referee_email&&e.jsx("p",{children:y.referee_email}),y.referee_phone&&e.jsx("p",{children:y.referee_phone}),y.referee_current_brokerage&&e.jsxs("p",{children:["Currently at: ",y.referee_current_brokerage]}),e.jsxs("p",{children:["Referred by: ",((v=h[y.referred_by])==null?void 0:v.name)||"Unknown"," • ",en(new Date(y.created_at),"MMM d, yyyy")]})]}),y.notes&&e.jsx("p",{className:"text-xs text-muted-foreground mt-1 italic",children:y.notes})]}),e.jsxs("div",{className:"flex gap-1",children:[e.jsxs(ms,{value:y.status,onValueChange:b=>f.mutate({id:y.id,status:b}),children:[e.jsx(us,{className:"h-7 text-xs w-[110px]",children:e.jsx(fs,{})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"pending",children:"Pending"}),e.jsx(Ge,{value:"contacted",children:"Contacted"}),e.jsx(Ge,{value:"approved",children:"Approved"}),e.jsx(Ge,{value:"signed",children:"Signed"}),e.jsx(Ge,{value:"rejected",children:"Rejected"})]})]}),e.jsxs(ms,{value:y.incentive_status||"pending",onValueChange:b=>f.mutate({id:y.id,incentive_status:b}),children:[e.jsx(us,{className:"h-7 text-xs w-[100px]",children:e.jsx(fs,{})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"pending",children:"Unpaid"}),e.jsx(Ge,{value:"paid",children:"Paid"}),e.jsx(Ge,{value:"n/a",children:"N/A"})]})]})]})]})},y.id)})}),e.jsx(zs,{open:r,onOpenChange:a,children:e.jsxs(Os,{children:[e.jsx(Us,{children:e.jsx(Bs,{children:"Submit a Recruit Referral"})}),e.jsxs("form",{onSubmit:y=>{y.preventDefault(),m.mutate(i)},className:"space-y-3",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(ee,{children:"First Name *"}),e.jsx(pe,{required:!0,value:i.first_name,onChange:y=>l(v=>({...v,first_name:y.target.value}))})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Last Name"}),e.jsx(pe,{value:i.last_name,onChange:y=>l(v=>({...v,last_name:y.target.value}))})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(ee,{children:"Email"}),e.jsx(pe,{type:"email",value:i.email,onChange:y=>l(v=>({...v,email:y.target.value}))})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Phone"}),e.jsx(pe,{value:i.phone,onChange:y=>l(v=>({...v,phone:y.target.value}))})]})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Current Brokerage"}),e.jsx(pe,{value:i.current_brokerage,onChange:y=>l(v=>({...v,current_brokerage:y.target.value}))})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Notes"}),e.jsx(Rs,{value:i.notes,onChange:y=>l(v=>({...v,notes:y.target.value})),rows:2})]}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx($,{type:"button",variant:"outline",onClick:()=>a(!1),children:"Cancel"}),e.jsx($,{type:"submit",disabled:m.isPending,children:"Submit"})]})]})]})})]})}function Ros({brokerageId:s}){const{toast:t}=Bi(),n=Vt(),[r,a]=j.useState(!1),{data:i}=tt({queryKey:["brokerage-recruit-form",s],queryFn:async()=>{const{data:m,error:f}=await q.from("brokerages").select("id, name, recruit_form_slug, recruit_form_enabled").eq("id",s).single();if(f)throw f;return m}}),{data:l=[]}=tt({queryKey:["recruit-interest-submissions",s],queryFn:async()=>{const{data:m,error:f}=await q.from("recruit_interest_submissions").select("*").eq("brokerage_id",s).order("created_at",{ascending:!1});if(f)throw f;return m}}),o=ft({mutationFn:async m=>{const{error:f}=await q.from("brokerages").update({recruit_form_enabled:m}).eq("id",s);if(f)throw f},onSuccess:()=>{n.invalidateQueries({queryKey:["brokerage-recruit-form",s]}),t({title:i!=null&&i.recruit_form_enabled?"Form disabled":"Form enabled"})}}),c=ft({mutationFn:async({id:m,status:f})=>{const{error:g}=await q.from("recruit_interest_submissions").update({status:f}).eq("id",m);if(g)throw g},onSuccess:()=>n.invalidateQueries({queryKey:["recruit-interest-submissions",s]})}),d=`https://bestbrokerage.relevelup.com/join-brokerage/${(i==null?void 0:i.recruit_form_slug)||""}`,u=()=>{navigator.clipboard.writeText(d),a(!0),t({title:"Link copied!"}),setTimeout(()=>a(!1),2e3)},h=m=>m==="contacted"||m==="converted"?"bg-green-500/10 text-green-600":m==="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(Ne,{children:[e.jsx(Ct,{children:e.jsx(At,{className:"text-base",children:"Public Interest Form"})}),e.jsxs(Ie,{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(ee,{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(Sn,{checked:(i==null?void 0:i.recruit_form_enabled)||!1,onCheckedChange:m=>o.mutate(m)})]}),(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($,{size:"sm",variant:"outline",onClick:u,children:r?e.jsx(la,{className:"h-3.5 w-3.5"}):e.jsx(Ha,{className:"h-3.5 w-3.5"})}),e.jsx($,{size:"sm",variant:"outline",asChild:!0,children:e.jsx("a",{href:d,target:"_blank",rel:"noopener noreferrer",children:e.jsx(kr,{className:"h-3.5 w-3.5"})})})]})]})]}),e.jsxs(Ne,{children:[e.jsx(Ct,{children:e.jsxs(At,{className:"text-base",children:["Interest Submissions (",l.length,")"]})}),e.jsx(Ie,{children:l.length===0?e.jsxs("div",{className:"text-center py-8",children:[e.jsx(sc,{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(m=>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:[m.first_name," ",m.last_name]}),e.jsx(Be,{variant:"outline",className:h(m.status),children:m.status})]}),e.jsxs("div",{className:"flex flex-wrap gap-3 text-xs text-muted-foreground",children:[m.email&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(mn,{className:"h-3 w-3"}),m.email]}),m.phone&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Da,{className:"h-3 w-3"}),m.phone]}),m.current_brokerage&&e.jsxs("span",{children:["From: ",m.current_brokerage]}),m.experience_years&&e.jsxs("span",{children:[m.experience_years,"yr exp"]})]}),m.why_interested&&e.jsxs("p",{className:"text-xs text-muted-foreground mt-1 italic",children:['"',m.why_interested,'"']}),e.jsx("p",{className:"text-[10px] text-muted-foreground mt-1",children:en(new Date(m.created_at),"MMM d, yyyy h:mm a")})]}),e.jsxs(ms,{value:m.status,onValueChange:f=>c.mutate({id:m.id,status:f}),children:[e.jsx(us,{className:"h-7 text-xs w-[110px]",children:e.jsx(fs,{})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"new",children:"New"}),e.jsx(Ge,{value:"contacted",children:"Contacted"}),e.jsx(Ge,{value:"converted",children:"Converted"}),e.jsx(Ge,{value:"dismissed",children:"Dismissed"})]})]})]},m.id))})})]})]})}function Dos({brokerageId:s}){const{toast:t}=Bi(),n=Vt(),[r,a]=j.useState(!1),[i,l]=j.useState({prospect_id:"",title:"",description:"",due_date:en(Tm(new Date,1),"yyyy-MM-dd'T'HH:mm")}),[o,c]=j.useState("pending"),{data:d=[]}=tt({queryKey:["recruit-prospects-list",s],queryFn:async()=>{const{data:C,error:E}=await q.from("recruit_prospects").select("id, first_name, last_name").eq("brokerage_id",s).order("first_name");if(E)throw E;return C}}),{data:u=[],isLoading:h}=tt({queryKey:["recruit-follow-ups",s],queryFn:async()=>{const C=d.map(P=>P.id);if(!C.length)return[];const{data:E,error:I}=await q.from("recruit_follow_ups").select("*").in("prospect_id",C).order("due_date");if(I)throw I;return E},enabled:d.length>0}),m=Object.fromEntries(d.map(C=>[C.id,C])),f=ft({mutationFn:async C=>{const{data:{user:E}}=await q.auth.getUser();if(!E)throw new Error("Not authenticated");const{error:I}=await q.from("recruit_follow_ups").insert({prospect_id:C.prospect_id,assigned_to:E.id,title:C.title,description:C.description||null,due_date:new Date(C.due_date).toISOString()});if(I)throw I},onSuccess:()=>{n.invalidateQueries({queryKey:["recruit-follow-ups",s]}),t({title:"Follow-up scheduled"}),l({prospect_id:"",title:"",description:"",due_date:en(Tm(new Date,1),"yyyy-MM-dd'T'HH:mm")}),a(!1)},onError:C=>t({title:"Error",description:C.message,variant:"destructive"})}),g=ft({mutationFn:async({id:C,completed:E})=>{const{error:I}=await q.from("recruit_follow_ups").update({completed_at:E?new Date().toISOString():null}).eq("id",C);if(I)throw I},onSuccess:()=>n.invalidateQueries({queryKey:["recruit-follow-ups",s]})}),x=u.filter(C=>o==="pending"?!C.completed_at:o==="completed"?!!C.completed_at:!0),y=x.filter(C=>!C.completed_at&&z4(new Date(C.due_date))&&!Nv(new Date(C.due_date))),v=x.filter(C=>!C.completed_at&&Nv(new Date(C.due_date))),b=x.filter(C=>!C.completed_at&&!z4(new Date(C.due_date))&&!Nv(new Date(C.due_date))),w=x.filter(C=>!!C.completed_at),S=C=>{const E=m[C.prospect_id],I=!C.completed_at&&z4(new Date(C.due_date))&&!Nv(new Date(C.due_date));return e.jsxs("div",{className:"flex items-start gap-3 p-3 border rounded-lg",children:[e.jsx(ai,{checked:!!C.completed_at,onCheckedChange:P=>g.mutate({id:C.id,completed:P}),className:"mt-0.5"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:`text-sm font-medium ${C.completed_at?"line-through text-muted-foreground":""}`,children:C.title}),C.description&&e.jsx("p",{className:"text-xs text-muted-foreground",children:C.description}),e.jsxs("div",{className:"flex items-center gap-2 mt-1 text-xs text-muted-foreground",children:[E&&e.jsxs(Be,{variant:"secondary",className:"text-[10px]",children:[E.first_name," ",E.last_name]}),e.jsxs("span",{className:`flex items-center gap-1 ${I?"text-destructive font-medium":""}`,children:[I?e.jsx(ll,{className:"h-3 w-3"}):e.jsx(Ta,{className:"h-3 w-3"}),en(new Date(C.due_date),"MMM d, h:mm a")]}),C.is_automated&&e.jsx(Be,{variant:"outline",className:"text-[10px]",children:"Auto"})]})]})]},C.id)};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.jsx("div",{className:"flex gap-2",children:["pending","completed","all"].map(C=>e.jsxs($,{size:"sm",variant:o===C?"default":"outline",onClick:()=>c(C),className:"capitalize text-xs",children:[C," ",C==="pending"&&y.length+v.length+b.length>0&&`(${y.length+v.length+b.length})`]},C))}),e.jsxs($,{size:"sm",onClick:()=>a(!0),children:[e.jsx(dn,{className:"h-4 w-4 mr-1"})," Add Follow-up"]})]}),o!=="completed"&&y.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(ll,{className:"h-3.5 w-3.5"})," Overdue (",y.length,")"]}),y.map(S)]}),o!=="completed"&&v.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(da,{className:"h-3.5 w-3.5"})," Today (",v.length,")"]}),v.map(S)]}),o!=="completed"&&b.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(Ta,{className:"h-3.5 w-3.5"})," Upcoming (",b.length,")"]}),b.map(S)]}),o!=="pending"&&w.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(la,{className:"h-3.5 w-3.5"})," Completed (",w.length,")"]}),w.map(S)]}),x.length===0&&e.jsxs("p",{className:"text-sm text-muted-foreground text-center py-8",children:["No follow-ups ",o!=="all"?`(${o})`:""]}),e.jsx(zs,{open:r,onOpenChange:a,children:e.jsxs(Os,{children:[e.jsx(Us,{children:e.jsx(Bs,{children:"Schedule Follow-up"})}),e.jsxs("form",{onSubmit:C=>{C.preventDefault(),f.mutate(i)},className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(ee,{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:C=>l(E=>({...E,prospect_id:C.target.value})),children:[e.jsx("option",{value:"",children:"Select prospect..."}),d.map(C=>e.jsxs("option",{value:C.id,children:[C.first_name," ",C.last_name]},C.id))]})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Task *"}),e.jsx(pe,{required:!0,value:i.title,onChange:C=>l(E=>({...E,title:C.target.value})),placeholder:"e.g. Follow-up call"})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Details"}),e.jsx(Rs,{value:i.description,onChange:C=>l(E=>({...E,description:C.target.value})),rows:2})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Due Date *"}),e.jsx(pe,{type:"datetime-local",required:!0,value:i.due_date,onChange:C=>l(E=>({...E,due_date:C.target.value}))})]}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx($,{type:"button",variant:"outline",onClick:()=>a(!1),children:"Cancel"}),e.jsx($,{type:"submit",disabled:f.isPending,children:"Schedule"})]})]})]})})]})}const Zlr=[{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 Fos({brokerageId:s}){const{toast:t}=Bi(),n=Vt(),[r,a]=j.useState(null),{data:i,isLoading:l}=tt({queryKey:["recruit-landing-settings",s],queryFn:async()=>{const{data:y,error:v}=await q.from("recruit_landing_page_settings").select("*").eq("brokerage_id",s).maybeSingle();if(v)throw v;return y}}),[o,c]=j.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:Zlr,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});j.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=ft({mutationFn:async()=>{const y={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:v}=await q.from("recruit_landing_page_settings").update(y).eq("id",o.id);if(v)throw v}else{const{error:v}=await q.from("recruit_landing_page_settings").insert(y);if(v)throw v}},onSuccess:()=>{n.invalidateQueries({queryKey:["recruit-landing-settings",s]}),t({title:"Landing page saved!"})},onError:y=>t({title:"Error",description:y.message,variant:"destructive"})}),u=async(y,v)=>{const b=y.name.split(".").pop(),w=`${s}/${v}-${Date.now()}.${b}`,{error:S}=await q.storage.from("recruit-landing").upload(w,y);if(S)throw S;const{data:{publicUrl:C}}=q.storage.from("recruit-landing").getPublicUrl(w);return C},h=async(y,v)=>{var w;const b=(w=y.target.files)==null?void 0:w[0];if(b){a(v);try{const S=await u(b,v);c(C=>({...C,[v]:S})),t({title:"Image uploaded!"})}catch(S){t({title:"Upload failed",description:S.message,variant:"destructive"})}finally{a(null)}}},m=async y=>{var b;const v=(b=y.target.files)==null?void 0:b[0];if(v){a("gallery");try{const w=await u(v,"gallery");c(S=>({...S,gallery_images:[...S.gallery_images,w]})),t({title:"Gallery image added!"})}catch(w){t({title:"Upload failed",description:w.message,variant:"destructive"})}finally{a(null)}}},f=async(y,v)=>{var w;const b=(w=y.target.files)==null?void 0:w[0];if(b){a(`testimonial-${v}`);try{const S=await u(b,`testimonial-${v}`);c(C=>{const E=[...C.testimonials];return E[v]={...E[v],photo_url:S},{...C,testimonials:E}})}catch(S){t({title:"Upload failed",description:S.message,variant:"destructive"})}finally{a(null)}}},{data:g}=tt({queryKey:["brokerage-slug-for-landing",s],queryFn:async()=>{const{data:y,error:v}=await q.from("brokerages").select("recruit_form_slug, recruit_form_enabled").eq("id",s).single();if(v)throw v;return y}}),x=`https://bestbrokerage.relevelup.com/join-brokerage/${(g==null?void 0:g.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:[(g==null?void 0:g.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:x}),e.jsx($,{size:"sm",variant:"outline",asChild:!0,children:e.jsxs("a",{href:x,target:"_blank",rel:"noopener noreferrer",children:[e.jsx(kr,{className:"h-3.5 w-3.5 mr-1"})," Preview"]})})]}),e.jsxs(Ne,{children:[e.jsx(Ct,{children:e.jsx(At,{className:"text-base",children:"Branding"})}),e.jsx(Ie,{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(ee,{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($,{variant:"outline",size:"sm",asChild:!0,disabled:r==="logo_url",children:e.jsxs("span",{children:[e.jsx(ni,{className:"h-3.5 w-3.5 mr-1"}),r==="logo_url"?"Uploading...":"Upload Logo"]})}),e.jsx("input",{type:"file",accept:"image/*",className:"hidden",onChange:y=>h(y,"logo_url")})]})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(ee,{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:y=>c(v=>({...v,primary_color:y.target.value})),className:"h-9 w-12 rounded border cursor-pointer"}),e.jsx(pe,{value:o.primary_color,onChange:y=>c(v=>({...v,primary_color:y.target.value})),className:"font-mono text-xs"})]})]}),e.jsxs("div",{children:[e.jsx(ee,{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:y=>c(v=>({...v,accent_color:y.target.value})),className:"h-9 w-12 rounded border cursor-pointer"}),e.jsx(pe,{value:o.accent_color,onChange:y=>c(v=>({...v,accent_color:y.target.value})),className:"font-mono text-xs"})]})]})]})]})})]}),e.jsxs(Ne,{children:[e.jsx(Ct,{children:e.jsx(At,{className:"text-base",children:"Hero Section"})}),e.jsxs(Ie,{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(ee,{children:"Headline"}),e.jsx(pe,{value:o.hero_headline,onChange:y=>c(v=>({...v,hero_headline:y.target.value})),placeholder:"Join Our Team"})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Subtext"}),e.jsx(Rs,{value:o.hero_subtext,onChange:y=>c(v=>({...v,hero_subtext:y.target.value})),rows:2,placeholder:"Take your career to the next level..."})]}),e.jsxs("div",{children:[e.jsx(ee,{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($,{variant:"outline",size:"sm",asChild:!0,disabled:r==="hero_image_url",children:e.jsxs("span",{children:[e.jsx(ni,{className:"h-3.5 w-3.5 mr-1"}),r==="hero_image_url"?"Uploading...":"Upload Image"]})}),e.jsx("input",{type:"file",accept:"image/*",className:"hidden",onChange:y=>h(y,"hero_image_url")})]}),o.hero_image_url&&e.jsx($,{variant:"ghost",size:"sm",onClick:()=>c(y=>({...y,hero_image_url:null})),children:e.jsx(Wn,{className:"h-3.5 w-3.5"})})]})]})]})]}),e.jsxs(Ne,{children:[e.jsxs(Ct,{className:"flex flex-row items-center justify-between",children:[e.jsx(At,{className:"text-base",children:"Benefits / Why Join Us"}),e.jsxs($,{size:"sm",variant:"outline",onClick:()=>c(y=>({...y,benefits:[...y.benefits,{title:"",description:"",icon:"✨"}]})),children:[e.jsx(dn,{className:"h-3.5 w-3.5 mr-1"})," Add"]})]}),e.jsxs(Ie,{className:"space-y-3",children:[o.benefits.map((y,v)=>e.jsxs("div",{className:"flex items-start gap-3 p-3 border rounded-lg",children:[e.jsx(Ug,{className:"h-4 w-4 mt-2 text-muted-foreground"}),e.jsx(pe,{value:y.icon,onChange:b=>{const w=[...o.benefits];w[v]={...y,icon:b.target.value},c(S=>({...S,benefits:w}))},className:"w-14 text-center"}),e.jsxs("div",{className:"flex-1 space-y-2",children:[e.jsx(pe,{value:y.title,onChange:b=>{const w=[...o.benefits];w[v]={...y,title:b.target.value},c(S=>({...S,benefits:w}))},placeholder:"Benefit title"}),e.jsx(pe,{value:y.description,onChange:b=>{const w=[...o.benefits];w[v]={...y,description:b.target.value},c(S=>({...S,benefits:w}))},placeholder:"Short description"})]}),e.jsx($,{variant:"ghost",size:"sm",onClick:()=>c(b=>({...b,benefits:b.benefits.filter((w,S)=>S!==v)})),children:e.jsx(Wn,{className:"h-3.5 w-3.5 text-destructive"})})]},v)),o.benefits.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"No benefits added yet"})]})]}),e.jsxs(Ne,{children:[e.jsxs(Ct,{className:"flex flex-row items-center justify-between",children:[e.jsx(At,{className:"text-base",children:"Testimonials"}),e.jsxs($,{size:"sm",variant:"outline",onClick:()=>c(y=>({...y,testimonials:[...y.testimonials,{name:"",role:"",quote:""}]})),children:[e.jsx(dn,{className:"h-3.5 w-3.5 mr-1"})," Add"]})]}),e.jsxs(Ie,{className:"space-y-3",children:[o.testimonials.map((y,v)=>{var b;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:[y.photo_url?e.jsx("img",{src:y.photo_url,alt:y.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:((b=y.name)==null?void 0:b[0])||"?"}),e.jsxs("label",{className:"cursor-pointer",children:[e.jsx("span",{className:"text-[10px] text-primary hover:underline",children:r===`testimonial-${v}`?"...":"Photo"}),e.jsx("input",{type:"file",accept:"image/*",className:"hidden",onChange:w=>f(w,v)})]})]}),e.jsxs("div",{className:"flex-1 space-y-2",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsx(pe,{value:y.name,onChange:w=>{const S=[...o.testimonials];S[v]={...y,name:w.target.value},c(C=>({...C,testimonials:S}))},placeholder:"Name"}),e.jsx(pe,{value:y.role,onChange:w=>{const S=[...o.testimonials];S[v]={...y,role:w.target.value},c(C=>({...C,testimonials:S}))},placeholder:"Role / Title"})]}),e.jsx(Rs,{value:y.quote,onChange:w=>{const S=[...o.testimonials];S[v]={...y,quote:w.target.value},c(C=>({...C,testimonials:S}))},placeholder:"What they say about working here...",rows:2})]}),e.jsx($,{variant:"ghost",size:"sm",onClick:()=>c(w=>({...w,testimonials:w.testimonials.filter((S,C)=>C!==v)})),children:e.jsx(Wn,{className:"h-3.5 w-3.5 text-destructive"})})]},v)}),o.testimonials.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"No testimonials added yet"})]})]}),e.jsxs(Ne,{children:[e.jsxs(Ct,{className:"flex flex-row items-center justify-between",children:[e.jsx(At,{className:"text-base",children:"Team & Culture Gallery"}),e.jsxs("label",{className:"cursor-pointer",children:[e.jsx($,{size:"sm",variant:"outline",asChild:!0,disabled:r==="gallery",children:e.jsxs("span",{children:[e.jsx(Mc,{className:"h-3.5 w-3.5 mr-1"}),r==="gallery"?"Uploading...":"Add Photo"]})}),e.jsx("input",{type:"file",accept:"image/*",className:"hidden",onChange:m})]})]}),e.jsx(Ie,{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((y,v)=>e.jsxs("div",{className:"relative group",children:[e.jsx("img",{src:y,alt:`Gallery ${v+1}`,className:"h-24 w-full object-cover rounded-lg"}),e.jsx($,{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(b=>({...b,gallery_images:b.gallery_images.filter((w,S)=>S!==v)})),children:e.jsx(Wn,{className:"h-3 w-3"})})]},v))}):e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"No gallery images added yet"})})]}),e.jsxs(Ne,{children:[e.jsx(Ct,{children:e.jsxs(At,{className:"text-base flex items-center gap-2",children:[e.jsx(Nn,{className:"h-4 w-4 text-primary"})," Form Style & Trust"]})}),e.jsxs(Ie,{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(ee,{children:"Application Form Style"}),e.jsxs(ms,{value:o.form_style,onValueChange:y=>c(v=>({...v,form_style:y})),children:[e.jsx(us,{className:"mt-1.5",children:e.jsx(fs,{})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"classic",children:"Classic — single-page form (all fields visible)"}),e.jsx(Ge,{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(pc,{className:"h-4 w-4 mt-0.5 text-primary"}),e.jsxs("div",{children:[e.jsx(ee,{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(Sn,{checked:o.confidential_messaging,onCheckedChange:y=>c(v=>({...v,confidential_messaging:y}))})]})]})]}),e.jsxs(Ne,{children:[e.jsxs(Ct,{className:"flex flex-row items-center justify-between",children:[e.jsxs(At,{className:"text-base flex items-center gap-2",children:[e.jsx(c2,{className:"h-4 w-4 text-primary"})," Split & Income Calculator"]}),e.jsx(Sn,{checked:o.calculator_enabled,onCheckedChange:y=>c(v=>({...v,calculator_enabled:y}))})]}),o.calculator_enabled&&e.jsxs(Ie,{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(ee,{className:"text-xs",children:"Calculator Headline"}),e.jsx(pe,{value:o.calculator_config.headline||"",onChange:y=>c(v=>({...v,calculator_config:{...v.calculator_config,headline:y.target.value}})),placeholder:"See What You Could Earn With Us"})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs",children:"Subtext"}),e.jsx(pe,{value:o.calculator_config.subtext||"",onChange:y=>c(v=>({...v,calculator_config:{...v.calculator_config,subtext:y.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(ee,{className:"text-xs",children:"Pre-Cap Split % (agent keeps)"}),e.jsx(pe,{type:"number",value:o.calculator_config.commission_split_pct??80,onChange:y=>c(v=>({...v,calculator_config:{...v.calculator_config,commission_split_pct:parseFloat(y.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(ee,{className:"text-xs",children:"Cap Amount ($)"}),e.jsx(pe,{type:"number",value:o.calculator_config.cap_amount??16e3,onChange:y=>c(v=>({...v,calculator_config:{...v.calculator_config,cap_amount:parseFloat(y.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(ee,{className:"text-xs",children:"Post-Cap Split % (agent keeps)"}),e.jsx(pe,{type:"number",value:o.calculator_config.post_cap_split_pct??100,onChange:y=>c(v=>({...v,calculator_config:{...v.calculator_config,post_cap_split_pct:parseFloat(y.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(ee,{className:"text-xs",children:"Monthly Fee ($)"}),e.jsx(pe,{type:"number",value:o.calculator_config.monthly_fee??99,onChange:y=>c(v=>({...v,calculator_config:{...v.calculator_config,monthly_fee:parseFloat(y.target.value)||0}}))})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs",children:"Per-Transaction Fee ($)"}),e.jsx(pe,{type:"number",value:o.calculator_config.transaction_fee??0,onChange:y=>c(v=>({...v,calculator_config:{...v.calculator_config,transaction_fee:parseFloat(y.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(ee,{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(Sn,{checked:o.calculator_config.show_email_capture!==!1,onCheckedChange:y=>c(v=>({...v,calculator_config:{...v.calculator_config,show_email_capture:y}}))})]})]})]}),e.jsxs(Ne,{children:[e.jsxs(Ct,{className:"flex flex-row items-center justify-between",children:[e.jsxs(At,{className:"text-base flex items-center gap-2",children:[e.jsx(u2,{className:"h-4 w-4 text-primary"})," Lead Magnet (Gated PDF)"]}),e.jsx(Sn,{checked:o.lead_magnet_enabled,onCheckedChange:y=>c(v=>({...v,lead_magnet_enabled:y}))})]}),o.lead_magnet_enabled&&e.jsxs(Ie,{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(ee,{className:"text-xs",children:"Title"}),e.jsx(pe,{value:o.lead_magnet_config.title||"",onChange:y=>c(v=>({...v,lead_magnet_config:{...v.lead_magnet_config,title:y.target.value}})),placeholder:"Get the Full Comp Plan PDF"})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs",children:"Description"}),e.jsx(Rs,{rows:2,value:o.lead_magnet_config.description||"",onChange:y=>c(v=>({...v,lead_magnet_config:{...v.lead_magnet_config,description:y.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(ee,{className:"text-xs",children:"Button Text"}),e.jsx(pe,{value:o.lead_magnet_config.button_text||"",onChange:y=>c(v=>({...v,lead_magnet_config:{...v.lead_magnet_config,button_text:y.target.value}})),placeholder:"Email Me the PDF"})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs",children:"PDF / File URL"}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx(pe,{value:o.lead_magnet_config.pdf_url||"",onChange:y=>c(v=>({...v,lead_magnet_config:{...v.lead_magnet_config,pdf_url:y.target.value||null}})),placeholder:"https://...",className:"flex-1"}),e.jsxs("label",{className:"cursor-pointer",children:[e.jsx($,{variant:"outline",size:"sm",asChild:!0,disabled:r==="lead_magnet_pdf",children:e.jsxs("span",{children:[e.jsx(ni,{className:"h-3.5 w-3.5 mr-1"}),r==="lead_magnet_pdf"?"...":"Upload"]})}),e.jsx("input",{type:"file",accept:"application/pdf,.pdf,.doc,.docx",className:"hidden",onChange:async y=>{var b;const v=(b=y.target.files)==null?void 0:b[0];if(v){a("lead_magnet_pdf");try{const w=await u(v,"lead-magnet");c(S=>({...S,lead_magnet_config:{...S.lead_magnet_config,pdf_url:w}})),t({title:"PDF uploaded!"})}catch(w){t({title:"Upload failed",description:w.message,variant:"destructive"})}finally{a(null)}}}})]})]})]})]})]})]}),e.jsx(Xlr,{brokerageId:s}),e.jsx("div",{className:"flex justify-end",children:e.jsxs($,{onClick:()=>d.mutate(),disabled:d.isPending,size:"lg",children:[e.jsx(tl,{className:"h-4 w-4 mr-2"}),d.isPending?"Saving...":"Save Landing Page"]})})]})}function Xlr({brokerageId:s}){const{data:t=[]}=tt({queryKey:["lead-magnet-downloads",s],queryFn:async()=>{const{data:n,error:r}=await q.from("recruit_lead_magnet_downloads").select("*").eq("brokerage_id",s).order("created_at",{ascending:!1}).limit(100);if(r)throw r;return n}});return t.length===0?null:e.jsxs(Ne,{children:[e.jsx(Ct,{children:e.jsxs(At,{className:"text-base flex items-center gap-2",children:[e.jsx(di,{className:"h-4 w-4 text-primary"})," Lead Magnet Downloads (",t.length,")"]})}),e.jsx(Ie,{children:e.jsx("div",{className:"space-y-2 max-h-80 overflow-y-auto",children:t.map(n=>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:[n.first_name||"—"," · ",n.email]}),e.jsxs("div",{className:"text-[11px] text-muted-foreground",children:[en(new Date(n.created_at),"MMM d, yyyy h:mm a")," · via ",n.source]})]})},n.id))})})]})}function Oos({brokerageId:s,trigger:t,initialProspectId:n,open:r,onOpenChange:a}){const[i,l]=j.useState(!1),o=r??i,c=a??l,[d,u]=j.useState("pick-recipients"),[h,m]=j.useState(new Set(n?[n]:[])),[f,g]=j.useState("all"),[x,y]=j.useState(""),[v,b]=j.useState(null),[w,S]=j.useState(""),[C,E]=j.useState(0),[I,P]=j.useState(0),[R,D]=j.useState(""),[O,U]=j.useState(""),{data:W}=pFe(),[V,G]=j.useState("default");j.useEffect(()=>{G(W!=null&&W.massEmail?"mass_email":W!=null&&W.gmail?"gmail":"default")},[W==null?void 0:W.massEmail,W==null?void 0:W.gmail]);const[Y,X]=j.useState(null),{prospects:ae,stages:ie}=S9(s),ne=Cos(),te=x3(),{data:J=[]}=tt({queryKey:["brokerage-recruit-video-pool",s],queryFn:async()=>{const{data:ke,error:Ve}=await q.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(Ve)throw Ve;return ke??[]},enabled:o&&d==="pick-video"}),ce=j.useCallback(()=>{u("pick-recipients"),m(new Set(n?[n]:[])),g("all"),y(""),b(null),S(""),E(0),P(0),D(""),U(""),G("default"),X(null)},[n]),_e=ke=>{!ke&&(d==="uploading"||d==="processing"||d==="sending")||(c(ke),ke||setTimeout(ce,200))},he=j.useMemo(()=>ae.filter(ke=>{if(!ke.email||f!=="all"&&ke.stage_id!==f)return!1;if(x){const Ve=x.toLowerCase();if(!`${ke.first_name} ${ke.last_name??""}`.toLowerCase().includes(Ve)&&!ke.email.toLowerCase().includes(Ve))return!1}return!0}),[ae,f,x]),ue=ke=>{m(Ve=>{const je=new Set(Ve);return je.has(ke)?je.delete(ke):je.add(ke),je})},ve=()=>{h.size===he.length?m(new Set):m(new Set(he.map(ke=>ke.id)))},Ee=j.useCallback(async(ke,Ve)=>{u("uploading");try{const je=`Recruiting blast (${h.size} recipients)`,{videoId:Ae,libraryId:Ce}=await P6(je),{uploadUrl:qe,apiKey:ze}=await I6(Ae),$e=new XMLHttpRequest;$e.upload.onprogress=rt=>{rt.lengthComputable&&E(rt.loaded/rt.total*100)},await new Promise((rt,Yt)=>{$e.onload=()=>$e.status>=200&&$e.status<300?rt():Yt(new Error("Upload failed")),$e.onerror=()=>Yt(new Error("Upload failed")),$e.open("PUT",qe),$e.setRequestHeader("AccessKey",ze),$e.send(ke)}),u("processing");const ct=`https://iframe.mediadelivery.net/embed/${Ce}/${Ae}`;let Xe=0;const it=Date.now(),at=9e4;for(;Xe<4&&(await new Promise(Yt=>setTimeout(Yt,3e3)),!(Date.now()-it>at));){const rt=await gk(Ae);if(Xe=rt.status,P(rt.encodeProgress||0),Xe===5||Xe===6)throw new Error("Video processing failed")}const Ke=await gk(Ae),nt=(Ke.storageSize||ke.size)/(1024*1024),xt=await te.mutateAsync({bunny_video_id:Ae,playback_url:Ke.directPlayUrl||ct,thumbnail_url:Ke.thumbnailUrl,preview_url:Ke.previewUrl||null,duration_seconds:Ke.length||Ve,file_size_mb:nt,title:je,status:Xe>=4?"ready":"processing",touch_type:"recruiting"});b(xt.id),S(je),u("compose")}catch(je){re.error((je==null?void 0:je.message)||"Failed to upload video"),u("pick-video")}},[h.size,te]),Se=j.useCallback(async()=>{if(!(!v||h.size===0)){u("sending");try{const ke=[];for(const Ae of h){const Ce=await ne.mutateAsync({prospect_id:Ae,video_id:v,brokerage_id:s,message:O||void 0});ke.push(Ce.id)}const{data:Ve,error:je}=await q.functions.invoke("send-recruit-video-email",{body:{recruit_video_ids:ke,brokerage_id:s,subject_override:R||void 0,message_override:O||void 0,send_via:V}});if(je)throw new Error(je.message);X({sent:(Ve==null?void 0:Ve.sent)??0,total:(Ve==null?void 0:Ve.total)??ke.length}),u("done"),re.success(`Sent ${(Ve==null?void 0:Ve.sent)??0} of ${(Ve==null?void 0:Ve.total)??ke.length} videos`)}catch(ke){re.error((ke==null?void 0:ke.message)||"Failed to send"),u("compose")}}},[v,h,s,O,R,V,ne]),Le=h.size,Fe=ae.filter(ke=>!ke.email).length;return e.jsxs(zs,{open:o,onOpenChange:_e,children:[t&&e.jsx(jl,{asChild:!0,children:t}),e.jsxs(Os,{className:"max-w-3xl max-h-[90vh] overflow-hidden flex flex-col",children:[e.jsx(Us,{children:e.jsxs(Bs,{className:"flex items-center gap-2",children:[e.jsx(ua,{className:"h-5 w-5 text-primary"}),"Send Recruiting Video",Le>0&&e.jsxs(Be,{variant:"secondary",className:"ml-2",children:[e.jsx(Zn,{className:"h-3 w-3 mr-1"}),Le," ",Le===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(Kr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(pe,{placeholder:"Search prospects...",value:x,onChange:ke=>y(ke.target.value),className:"pl-9"})]}),e.jsxs(ms,{value:f,onValueChange:g,children:[e.jsx(us,{className:"w-48",children:e.jsx(fs,{})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"all",children:"All stages"}),ie.map(ke=>e.jsx(Ge,{value:ke.id,children:ke.name},ke.id))]})]})]}),e.jsxs("div",{className:"flex items-center justify-between text-xs text-muted-foreground",children:[e.jsxs("button",{onClick:ve,className:"hover:underline",children:[h.size===he.length&&he.length>0?"Deselect all":"Select all"," ","(",he.length,")"]}),Fe>0&&e.jsxs("span",{children:[Fe," prospect(s) hidden — no email on file"]})]}),e.jsx(uo,{className:"flex-1 border rounded-md",children:he.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:he.map(ke=>{const Ve=h.has(ke.id),je=ie.find(Ae=>Ae.id===ke.stage_id);return e.jsxs("label",{className:"flex items-center gap-3 p-3 hover:bg-muted/30 cursor-pointer",children:[e.jsx(ai,{checked:Ve,onCheckedChange:()=>ue(ke.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:[ke.first_name," ",ke.last_name]}),je&&e.jsx(Be,{variant:"outline",className:"text-[10px]",style:{borderColor:je.color,color:je.color},children:je.name})]}),e.jsxs("p",{className:"text-xs text-muted-foreground truncate",children:[ke.email," ",ke.current_brokerage&&`· ${ke.current_brokerage}`]})]})]},ke.id)})})}),e.jsxs(Ar,{children:[e.jsx($,{variant:"outline",onClick:()=>_e(!1),children:"Cancel"}),e.jsx($,{disabled:Le===0,onClick:()=>u("pick-video"),children:"Next: Choose Video"})]})]}),d==="pick-video"&&e.jsxs("div",{className:"flex-1 overflow-hidden flex flex-col",children:[e.jsxs(ha,{defaultValue:"record",className:"flex-1 flex flex-col overflow-hidden",children:[e.jsxs(ma,{className:"self-start",children:[e.jsxs(Zt,{value:"record",children:[e.jsx(dn,{className:"h-3.5 w-3.5 mr-1"}),"Record New"]}),e.jsxs(Zt,{value:"library",children:[e.jsx(f2,{className:"h-3.5 w-3.5 mr-1"}),"Use Existing"]})]}),e.jsx(Xt,{value:"record",className:"flex-1 overflow-auto",children:e.jsxs("div",{className:"text-center py-8 space-y-4",children:[e.jsx(rf,{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 ",Le," ",Le===1?"recipient":"recipients"," — each gets their own tracked link."]})]}),e.jsxs($,{onClick:()=>u("record"),children:[e.jsx(ua,{className:"h-4 w-4 mr-2"}),"Start Recording"]})]})}),e.jsx(Xt,{value:"library",className:"flex-1 overflow-auto",children:J.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:J.map(ke=>e.jsxs("button",{onClick:()=>{b(ke.id),S(ke.title||"Untitled"),u("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:j4(ke)?e.jsx("img",{src:j4(ke),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(ua,{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:ke.title||"Untitled"})})]},ke.id))})})]}),e.jsx(Ar,{children:e.jsx($,{variant:"outline",onClick:()=>u("pick-recipients"),children:"Back"})})]}),d==="record"&&e.jsxs("div",{className:"flex-1 overflow-auto",children:[e.jsx(BT,{maxDurationSeconds:600,onRecordingComplete:Ee}),e.jsx("div",{className:"mt-2 flex justify-start",children:e.jsx($,{variant:"ghost",size:"sm",onClick:()=>u("pick-video"),children:"← Back"})})]}),(d==="uploading"||d==="processing")&&e.jsxs("div",{className:"py-12 space-y-4 text-center",children:[e.jsx(kt,{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(Yi,{value:d==="uploading"?C:I,className:"mx-auto max-w-sm"}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[Math.round(d==="uploading"?C:I),"%"]})]}),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(qr,{className:"h-4 w-4 text-primary"}),e.jsxs("div",{className:"flex-1 text-sm",children:[e.jsx("span",{className:"font-medium",children:w})," selected · sending to ",e.jsx("strong",{children:Le})," recipient",Le===1?"":"s"]})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs",children:"Subject (optional override)"}),e.jsx(pe,{value:R,onChange:ke=>D(ke.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(ee,{className:"text-xs",children:"Personal message shown in the email & on the landing page"}),e.jsx(Rs,{value:O,onChange:ke=>U(ke.target.value),placeholder:"Hey there — wanted to share a quick thought on what we're building here...",rows:5,className:"mt-1"})]}),e.jsx(Vlt,{value:V,onChange:G}),e.jsxs(Ar,{children:[e.jsx($,{variant:"outline",onClick:()=>u("pick-video"),children:"Back"}),e.jsxs($,{onClick:Se,disabled:!v||Le===0,children:[e.jsx(Yr,{className:"h-4 w-4 mr-2"})," Send to ",Le," ",Le===1?"prospect":"prospects"]})]})]}),d==="sending"&&e.jsxs("div",{className:"py-12 text-center space-y-3",children:[e.jsx(kt,{className:"h-8 w-8 animate-spin mx-auto text-primary"}),e.jsxs("p",{className:"font-medium",children:["Sending to ",Le," recipient",Le===1?"":"s","…"]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Each prospect gets their own tracked share link."})]}),d==="done"&&Y&&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 ${Y.sent===Y.total?"bg-primary/10":"bg-muted"}`,children:Y.sent===Y.total?e.jsx(qr,{className:"h-8 w-8 text-primary"}):e.jsx(ll,{className:"h-8 w-8 text-muted-foreground"})}),e.jsxs("div",{children:[e.jsxs("p",{className:"font-semibold text-lg",children:[Y.sent," of ",Y.total," sent"]}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:"View engagement under the Video Outreach tab."})]}),e.jsx($,{onClick:()=>_e(!1),children:"Done"})]})]})]})}function Qlr(s){if(!s)return"—";const t=Math.floor(s/60),n=s%60;return t>0?`${t}m ${n}s`:`${n}s`}function Jlr({video:s}){return s.cta_clicked_at?e.jsx(Be,{className:"bg-emerald-500/10 text-emerald-600 border-emerald-200",children:"CTA Clicked"}):s.view_count>0?e.jsxs(Be,{className:"bg-blue-500/10 text-blue-600 border-blue-200",children:[e.jsx(Ca,{className:"h-3 w-3 mr-1"}),s.view_count," views"]}):s.sent_at?e.jsxs(Be,{variant:"secondary",children:[e.jsx(Yr,{className:"h-3 w-3 mr-1"}),"Sent"]}):e.jsxs(Be,{variant:"outline",children:[e.jsx(da,{className:"h-3 w-3 mr-1"}),"Draft"]})}function zos({brokerageId:s}){var w,S,C,E;const{data:t=[],isLoading:n}=Blr(s),{data:r=[]}=Eos(s),a=Ulr(),i=qlr(),l=Aos(),[o,c]=j.useState(""),[d,u]=j.useState(!1),[h,m]=j.useState({title:"",script_text:"",category:"general"}),[f,g]=j.useState(null),x=t.filter(I=>{var R,D,O,U;return o?`${((R=I.prospect)==null?void 0:R.first_name)||""} ${((D=I.prospect)==null?void 0:D.last_name)||""}`.toLowerCase().includes(o.toLowerCase())||((U=(O=I.video)==null?void 0:O.title)==null?void 0:U.toLowerCase().includes(o.toLowerCase())):!0}),y={total:t.length,sent:t.filter(I=>I.sent_at).length,viewed:t.filter(I=>I.view_count>0).length,ctaClicked:t.filter(I=>I.cta_clicked_at).length},v=j.useCallback(I=>{if(!I)return;const P=`${window.location.origin}/recruit-video/${I}`;navigator.clipboard.writeText(P),re.success("Share link copied")},[]);j.useCallback((I,P)=>{l.mutate({id:I,sent_via:P})},[l]);const b=()=>{!h.title.trim()||!h.script_text.trim()||a.mutate({brokerage_id:s,...h},{onSuccess:()=>{m({title:"",script_text:"",category:"general"}),u(!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:y.total,icon:ua,color:"text-primary"},{label:"Sent",value:y.sent,icon:Yr,color:"text-blue-500"},{label:"Viewed",value:y.viewed,icon:Ca,color:"text-amber-500"},{label:"CTA Clicked",value:y.ctaClicked,icon:qr,color:"text-emerald-500"}].map(I=>e.jsx(Ne,{children:e.jsxs(Ie,{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 ${I.color}`,children:e.jsx(I.icon,{className:"h-5 w-5"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:I.value}),e.jsx("p",{className:"text-xs text-muted-foreground",children:I.label})]})]})},I.label))}),e.jsxs(ha,{defaultValue:"videos",className:"space-y-4",children:[e.jsxs(ma,{children:[e.jsxs(Zt,{value:"videos",children:[e.jsx(ua,{className:"h-4 w-4 mr-1.5"}),"All Videos"]}),e.jsxs(Zt,{value:"scripts",children:[e.jsx(Jr,{className:"h-4 w-4 mr-1.5"}),"Script Library"]}),e.jsxs(Zt,{value:"analytics",children:[e.jsx(Wl,{className:"h-4 w-4 mr-1.5"}),"Engagement"]})]}),e.jsx(Xt,{value:"videos",children:e.jsxs(Ne,{children:[e.jsx(Ct,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center justify-between gap-2 flex-wrap",children:[e.jsx(At,{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(Kr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(pe,{placeholder:"Search by name or title...",value:o,onChange:I=>c(I.target.value),className:"pl-9"})]}),e.jsx(Oos,{brokerageId:s,trigger:e.jsxs($,{size:"sm",className:"gap-1.5",children:[e.jsx(mn,{className:"h-4 w-4"})," Send Video Email"]})})]})]})}),e.jsx(Ie,{children: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"})}):x.length===0?e.jsxs("div",{className:"text-center py-12 text-muted-foreground",children:[e.jsx(ua,{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:x.map(I=>{var P,R,D,O,U,W,V;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:[j4(I.video)?e.jsx("img",{src:j4(I.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(ua,{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:Qlr(((P=I.video)==null?void 0:P.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:[(R=I.prospect)==null?void 0:R.first_name," ",(D=I.prospect)==null?void 0:D.last_name]}),e.jsx(Jlr,{video:I})]}),e.jsx("p",{className:"text-sm text-muted-foreground truncate",children:((O=I.video)==null?void 0:O.title)||"Untitled video"}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-0.5",children:[en(new Date(I.created_at),"MMM d, yyyy"),((U=I.prospect)==null?void 0:U.current_brokerage)&&` · ${I.prospect.current_brokerage}`]})]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx($,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>v(I.share_token),title:"Copy share link",children:e.jsx(Ha,{className:"h-4 w-4"})}),e.jsxs($,{variant:I.sent_at?"ghost":"default",size:"sm",className:"h-8 gap-1.5",onClick:()=>g(I),disabled:!((W=I.prospect)!=null&&W.email),title:(V=I.prospect)!=null&&V.email?"Email this video to the prospect":"Prospect has no email",children:[e.jsx(mn,{className:"h-4 w-4"}),I.sent_at?"Resend":"Email"]}),I.share_token&&e.jsx($,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>window.open(`/recruit-video/${I.share_token}`,"_blank"),title:"Preview landing page",children:e.jsx(kr,{className:"h-4 w-4"})})]})]},I.id)})})})]})}),e.jsx(Xt,{value:"scripts",children:e.jsxs(Ne,{children:[e.jsx(Ct,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(At,{className:"text-lg",children:"Recruiting Scripts"}),e.jsxs(zs,{open:d,onOpenChange:u,children:[e.jsx(jl,{asChild:!0,children:e.jsxs($,{size:"sm",children:[e.jsx(dn,{className:"h-4 w-4 mr-1.5"}),"New Script"]})}),e.jsxs(Os,{children:[e.jsx(Us,{children:e.jsx(Bs,{children:"Create Recruiting Script"})}),e.jsxs("div",{className:"space-y-4 mt-2",children:[e.jsxs("div",{children:[e.jsx(ee,{children:"Title"}),e.jsx(pe,{value:h.title,onChange:I=>m(P=>({...P,title:I.target.value})),placeholder:"e.g., Why Switch to Our Brokerage"})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Category"}),e.jsxs(ms,{value:h.category,onValueChange:I=>m(P=>({...P,category:I})),children:[e.jsx(us,{children:e.jsx(fs,{})}),e.jsx(hs,{children:dQe.map(I=>e.jsx(Ge,{value:I.value,children:I.label},I.value))})]})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Script"}),e.jsx(Rs,{value:h.script_text,onChange:I=>m(P=>({...P,script_text:I.target.value})),placeholder:"Hi [Name], I noticed you've been doing great work at [Brokerage]...",rows:8})]}),e.jsx($,{onClick:b,disabled:!h.title.trim()||!h.script_text.trim(),className:"w-full",children:"Save Script"})]})]})]})]})}),e.jsx(Ie,{children:r.length===0?e.jsxs("div",{className:"text-center py-12 text-muted-foreground",children:[e.jsx(Jr,{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:r.map(I=>{var R;const P=((R=dQe.find(D=>D.value===I.category))==null?void 0:R.label)||I.category;return e.jsx(Ne,{className:"relative group",children:e.jsxs(Ie,{className:"p-4",children:[e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsxs("div",{children:[e.jsx(Be,{variant:"outline",className:"text-[10px] mb-2",children:P}),e.jsx("h4",{className:"font-medium text-sm",children:I.title})]}),e.jsx($,{variant:"ghost",size:"icon",className:"h-7 w-7 opacity-0 group-hover:opacity-100 transition-opacity text-destructive",onClick:()=>i.mutate(I.id),children:e.jsx(Wn,{className:"h-3.5 w-3.5"})})]}),e.jsx("p",{className:"text-xs text-muted-foreground mt-2 line-clamp-3",children:I.script_text}),I.is_global&&e.jsx(Be,{variant:"secondary",className:"mt-2 text-[10px]",children:"Template"})]})},I.id)})})})]})}),e.jsx(Xt,{value:"analytics",children:e.jsxs(Ne,{children:[e.jsx(Ct,{children:e.jsx(At,{className:"text-lg",children:"Engagement Funnel"})}),e.jsxs(Ie,{children:[e.jsx("div",{className:"space-y-4",children:[{label:"Videos Created",count:y.total,pct:100,color:"bg-primary"},{label:"Sent to Prospects",count:y.sent,pct:y.total?Math.round(y.sent/y.total*100):0,color:"bg-blue-500"},{label:"Viewed by Prospect",count:y.viewed,pct:y.sent?Math.round(y.viewed/y.sent*100):0,color:"bg-amber-500"},{label:"CTA Clicked",count:y.ctaClicked,pct:y.viewed?Math.round(y.ctaClicked/y.viewed*100):0,color:"bg-emerald-500"}].map(I=>e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("div",{className:"flex justify-between text-sm",children:[e.jsx("span",{children:I.label}),e.jsxs("span",{className:"font-medium",children:[I.count," (",I.pct,"%)"]})]}),e.jsx("div",{className:"h-3 bg-muted rounded-full overflow-hidden",children:e.jsx("div",{className:`h-full ${I.color} rounded-full transition-all`,style:{width:`${I.pct}%`}})})]},I.label))}),t.filter(I=>I.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(I=>I.view_count>0).sort((I,P)=>P.view_count-I.view_count).slice(0,5).map(I=>{var P,R;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:[(P=I.prospect)==null?void 0:P.first_name," ",(R=I.prospect)==null?void 0:R.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(Ca,{className:"h-3.5 w-3.5"})," ",I.view_count]}),I.cta_clicked_at&&e.jsx(qr,{className:"h-4 w-4 text-emerald-500"})]})]},I.id)})})]})]})]})})]}),f&&e.jsx(Sos,{open:!!f,onOpenChange:I=>{I||g(null)},recruitVideoId:f.id,brokerageId:s,prospectName:`${((w=f.prospect)==null?void 0:w.first_name)||""} ${((S=f.prospect)==null?void 0:S.last_name)||""}`.trim(),prospectEmail:(C=f.prospect)==null?void 0:C.email,videoTitle:(E=f.video)==null?void 0:E.title,defaultMessage:f.message})]})}function Bos({brokerageId:s}){const{toast:t}=Bi(),n=Vt(),{stages:r,prospects:a}=S9(s),[i,l]=j.useState(!1),[o,c]=j.useState({title:"",target_count:"10",target_stage_id:"",period_start:en(new Date,"yyyy-MM-dd"),period_end:en(new Date(new Date().getFullYear(),new Date().getMonth()+3,0),"yyyy-MM-dd")}),{data:d=[],isLoading:u}=tt({queryKey:["recruit-goals",s],queryFn:async()=>{const{data:g,error:x}=await q.from("recruit_goals").select("*").eq("brokerage_id",s).order("period_end",{ascending:!1});if(x)throw x;return g}}),h=ft({mutationFn:async g=>{const{data:{user:x}}=await q.auth.getUser();if(!x)throw new Error("Not authenticated");const{error:y}=await q.from("recruit_goals").insert({brokerage_id:s,title:g.title,target_count:parseInt(g.target_count),target_stage_id:g.target_stage_id||null,period_start:g.period_start,period_end:g.period_end,created_by:x.id});if(y)throw y},onSuccess:()=>{n.invalidateQueries({queryKey:["recruit-goals",s]}),t({title:"Goal created"}),l(!1)},onError:g=>t({title:"Error",description:g.message,variant:"destructive"})}),m=ft({mutationFn:async g=>{const{error:x}=await q.from("recruit_goals").delete().eq("id",g);if(x)throw x},onSuccess:()=>{n.invalidateQueries({queryKey:["recruit-goals",s]}),t({title:"Goal removed"})}}),f=g=>{const x=r.find(v=>v.id===g.target_stage_id);return{count:a.filter(v=>RS(new Date(v.created_at),{start:new Date(g.period_start),end:new Date(g.period_end)})?g.target_stage_id?v.stage_id===g.target_stage_id:!0:!1).length,stage:x}};return u?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($,{size:"sm",onClick:()=>l(!0),children:[e.jsx(dn,{className:"h-4 w-4 mr-1"})," New Goal"]})]}),d.length===0?e.jsxs(Ne,{className:"py-12 text-center",children:[e.jsx(rh,{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(g=>{const{count:x,stage:y}=f(g),v=Math.min(100,x/g.target_count*100),b=RS(new Date,{start:new Date(g.period_start),end:new Date(g.period_end)});return e.jsxs(Ne,{className:b?"":"opacity-60",children:[e.jsx(Ct,{className:"pb-2",children:e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsxs("div",{children:[e.jsx(At,{className:"text-sm",children:g.title}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-0.5",children:[en(new Date(g.period_start),"MMM d")," – ",en(new Date(g.period_end),"MMM d, yyyy")]})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[b?e.jsx(Be,{className:"text-[10px]",children:"Active"}):e.jsx(Be,{variant:"secondary",className:"text-[10px]",children:"Ended"}),e.jsx($,{variant:"ghost",size:"icon",className:"h-6 w-6 text-muted-foreground",onClick:()=>m.mutate(g.id),children:e.jsx(Wn,{className:"h-3.5 w-3.5"})})]})]})}),e.jsxs(Ie,{className:"space-y-2",children:[y&&e.jsxs(Be,{variant:"outline",className:"text-[10px]",style:{borderColor:y.color,color:y.color},children:["Stage: ",y.name]}),e.jsxs("div",{className:"flex items-center justify-between text-sm",children:[e.jsx("span",{className:"font-bold text-lg",children:x}),e.jsxs("span",{className:"text-muted-foreground",children:["/ ",g.target_count]})]}),e.jsx(Yi,{value:v,className:"h-2"}),e.jsxs("p",{className:"text-xs text-muted-foreground text-right",children:[v.toFixed(0),"% complete"]})]})]},g.id)})}),e.jsx(zs,{open:i,onOpenChange:l,children:e.jsxs(Os,{children:[e.jsx(Us,{children:e.jsx(Bs,{children:"Create Recruiting Goal"})}),e.jsxs("form",{onSubmit:g=>{g.preventDefault(),h.mutate(o)},className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(ee,{children:"Goal Title *"}),e.jsx(pe,{required:!0,value:o.title,onChange:g=>c(x=>({...x,title:g.target.value})),placeholder:"e.g. Q2 Recruiting Target"})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Target Count *"}),e.jsx(pe,{type:"number",min:"1",required:!0,value:o.target_count,onChange:g=>c(x=>({...x,target_count:g.target.value}))})]}),e.jsxs("div",{children:[e.jsx(ee,{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:g=>c(x=>({...x,target_stage_id:g.target.value})),children:[e.jsx("option",{value:"",children:"All stages (total prospects)"}),r.map(g=>e.jsx("option",{value:g.id,children:g.name},g.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(ee,{children:"Start Date"}),e.jsx(pe,{type:"date",required:!0,value:o.period_start,onChange:g=>c(x=>({...x,period_start:g.target.value}))})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"End Date"}),e.jsx(pe,{type:"date",required:!0,value:o.period_end,onChange:g=>c(x=>({...x,period_end:g.target.value}))})]})]}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx($,{type:"button",variant:"outline",onClick:()=>l(!1),children:"Cancel"}),e.jsx($,{type:"submit",disabled:h.isPending,children:"Create Goal"})]})]})]})})]})}const ecr={first_name:"Sarah",brokerage_name:"ABC Realty",city:"Austin",sender_name:"Jeremy"};function $os({email:s,mergeValues:t=ecr,selectedSubjectIndex:n,onClose:r}){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=n??0,o=i[l]||s.subject_line;return e.jsx(zs,{open:!0,onOpenChange:()=>r(),children:e.jsxs(Os,{className:"max-w-2xl max-h-[85vh] overflow-y-auto p-0",children:[e.jsxs(Us,{className:"px-6 pt-6 pb-4 border-b",children:[e.jsxs(Bs,{className:"text-base",children:["Email #",s.email_number," — ",s.title]}),e.jsxs("div",{className:"flex items-center gap-3 mt-2",children:[e.jsxs(Be,{variant:"outline",className:"text-xs gap-1",children:[e.jsx(da,{className:"h-3 w-3"}),s.email_number===1?"Sent immediately":`Day ${s.delay_days}`]}),i.length>1&&e.jsxs(Be,{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,u)=>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 ${u===l?"bg-primary/10 text-primary":"bg-muted text-muted-foreground"}`,children:u===l?"Selected":u===0?"Primary":`Alt ${u}`}),e.jsx("span",{className:"text-sm",children:a(d)})]},u))})]}),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 Wlt({brokerageId:s}){const t=Vt(),{user:n}=vs(),[r,a]=j.useState(""),[i,l]=j.useState(!1),[o,c]=j.useState({brokerage_id:s,sender_name:"LevelUp",sender_email:"recruiting@relevelup.com",reply_to_email:"",merge_fields:{city:"",broker_name:""}}),{data:d}=tt({queryKey:["brokerage-recruit-settings",s],queryFn:async()=>{const{data:g,error:x}=await q.from("brokerage_recruit_settings").select("*").eq("brokerage_id",s).maybeSingle();if(x)throw x;return g}}),{data:u}=tt({queryKey:["brokerage-detail",s],queryFn:async()=>{const{data:g,error:x}=await q.from("brokerages").select("name, city, state").eq("id",s).single();if(x)throw x;return g}});j.useEffect(()=>{d?c({...d,merge_fields:d.merge_fields||{city:"",broker_name:""}}):u&&c(g=>({...g,merge_fields:{...g.merge_fields,brokerage_name:u.name,city:u.city||""}}))},[d,u]),j.useEffect(()=>{n!=null&&n.id&&q.from("profiles").select("recruit_cta_url").eq("id",n.id).single().then(({data:g})=>a((g==null?void 0:g.recruit_cta_url)||""))},[n==null?void 0:n.id]);const h=async()=>{if(!(n!=null&&n.id))return;l(!0);const{error:g}=await q.from("profiles").update({recruit_cta_url:r.trim()||null}).eq("id",n.id);l(!1),g?re.error(g.message):re.success("Scheduling link saved!")},m=ft({mutationFn:async()=>{const g={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:x}=await q.from("brokerage_recruit_settings").update(g).eq("id",d.id);if(x)throw x}else{const{error:x}=await q.from("brokerage_recruit_settings").insert(g);if(x)throw x}},onSuccess:()=>{t.invalidateQueries({queryKey:["brokerage-recruit-settings",s]}),re.success("Recruiting email settings saved!")},onError:g=>re.error(g.message)}),f=(g,x)=>{c(y=>({...y,merge_fields:{...y.merge_fields,[g]:x}}))};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(Ta,{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(pe,{value:r,onChange:g=>a(g.target.value),placeholder:"https://calendly.com/your-name/intro"}),e.jsxs($,{onClick:h,disabled:i,size:"sm",children:[e.jsx(tl,{className:"h-4 w-4 mr-1"})," Save"]})]}),!r&&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(ee,{className:"text-xs",children:"Sender Display Name"}),e.jsx(pe,{value:o.sender_name,onChange:g=>c({...o,sender_name:g.target.value}),placeholder:"e.g. Jeremy at LevelUp"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(ee,{className:"text-xs",children:"Sender Email Address"}),e.jsx(pe,{value:o.sender_email,onChange:g=>c({...o,sender_email:g.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(ee,{className:"text-xs",children:"Reply-To Email (optional)"}),e.jsx(pe,{value:o.reply_to_email,onChange:g=>c({...o,reply_to_email:g.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(bm,{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(vos,{brokerageId:s,onVerifiedSelect:g=>{c(x=>({...x,sender_email:g})),re.success(`Sender set to ${g}`)}})]}),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(ee,{className:"text-xs",children:"{{brokerage_name}}"}),e.jsx(pe,{value:o.merge_fields.brokerage_name||"",onChange:g=>f("brokerage_name",g.target.value),placeholder:(u==null?void 0:u.name)||"Brokerage Name"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(ee,{className:"text-xs",children:"{{city}}"}),e.jsx(pe,{value:o.merge_fields.city||"",onChange:g=>f("city",g.target.value),placeholder:"e.g. Austin"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(ee,{className:"text-xs",children:"{{sender_name}}"}),e.jsx(pe,{value:o.merge_fields.sender_name||"",onChange:g=>f("sender_name",g.target.value),placeholder:"e.g. Jeremy"})]})]})]}),e.jsxs($,{onClick:()=>m.mutate(),disabled:m.isPending,className:"w-full",children:[e.jsx(tl,{className:"h-4 w-4 mr-1"})," Save Settings"]})]})}const Uos=xC.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",ep(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()}}}),vEt=[{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 Zv({onClick:s,active:t,disabled:n,icon:r,tooltip:a}){return e.jsxs(ly,{children:[e.jsx(cy,{asChild:!0,children:e.jsx($,{type:"button",variant:"ghost",size:"sm",onClick:s,disabled:n,className:`h-8 w-8 p-0 ${t?"bg-accent text-accent-foreground":"text-muted-foreground hover:text-foreground"}`,children:e.jsx(r,{className:"h-4 w-4"})})}),e.jsx(Nx,{side:"bottom",className:"text-xs",children:a})]})}function tcr({content:s,onChange:t}){const n=G6e({extensions:[W6e.configure({heading:{levels:[1,2,3]}}),Uos,Y6e.configure({openOnClick:!1,HTMLAttributes:{class:"text-primary underline cursor-pointer"}}),Z6e.configure({types:["heading","paragraph"]}),trt,BXt],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())}});j.useEffect(()=>{n&&s!==n.getHTML()&&n.commands.setContent(s)},[s,n]);const r=j.useCallback(()=>{if(!n)return;const i=n.getAttributes("link").href,l=window.prompt("Enter URL",i);if(l!==null){if(l===""){n.chain().focus().extendMarkRange("link").unsetLink().run();return}n.chain().focus().extendMarkRange("link").setLink({href:l}).run()}},[n]),a=j.useCallback(i=>{n&&n.chain().focus().insertContent(`{{${i}}}`).run()},[n]);return n?e.jsx(jk,{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(Zv,{onClick:()=>n.chain().focus().toggleBold().run(),active:n.isActive("bold"),icon:AE,tooltip:"Bold"}),e.jsx(Zv,{onClick:()=>n.chain().focus().toggleItalic().run(),active:n.isActive("italic"),icon:ME,tooltip:"Italic"}),e.jsx(Zv,{onClick:()=>n.chain().focus().toggleUnderline().run(),active:n.isActive("underline"),icon:i7,tooltip:"Underline"}),e.jsx(Zv,{onClick:()=>n.chain().focus().toggleStrike().run(),active:n.isActive("strike"),icon:ree,tooltip:"Strikethrough"}),e.jsx(Gc,{orientation:"vertical",className:"mx-1 h-6"}),e.jsx(Zv,{onClick:()=>n.chain().focus().toggleHeading({level:1}).run(),active:n.isActive("heading",{level:1}),icon:Bq,tooltip:"Heading 1"}),e.jsx(Zv,{onClick:()=>n.chain().focus().toggleHeading({level:2}).run(),active:n.isActive("heading",{level:2}),icon:Hz,tooltip:"Heading 2"}),e.jsx(Zv,{onClick:()=>n.chain().focus().toggleHeading({level:3}).run(),active:n.isActive("heading",{level:3}),icon:$q,tooltip:"Heading 3"}),e.jsx(Gc,{orientation:"vertical",className:"mx-1 h-6"}),e.jsx(Zv,{onClick:()=>n.chain().focus().toggleBulletList().run(),active:n.isActive("bulletList"),icon:P0,tooltip:"Bullet List"}),e.jsx(Zv,{onClick:()=>n.chain().focus().toggleOrderedList().run(),active:n.isActive("orderedList"),icon:p2,tooltip:"Numbered List"}),e.jsx(Zv,{onClick:()=>n.chain().focus().toggleBlockquote().run(),active:n.isActive("blockquote"),icon:x2,tooltip:"Blockquote"}),e.jsx(Zv,{onClick:()=>n.chain().focus().setHorizontalRule().run(),icon:tk,tooltip:"Divider"}),e.jsx(Gc,{orientation:"vertical",className:"mx-1 h-6"}),e.jsx(Zv,{onClick:()=>n.chain().focus().setTextAlign("left").run(),active:n.isActive({textAlign:"left"}),icon:BI,tooltip:"Align Left"}),e.jsx(Zv,{onClick:()=>n.chain().focus().setTextAlign("center").run(),active:n.isActive({textAlign:"center"}),icon:zI,tooltip:"Align Center"}),e.jsx(Zv,{onClick:()=>n.chain().focus().setTextAlign("right").run(),active:n.isActive({textAlign:"right"}),icon:$I,tooltip:"Align Right"}),e.jsx(Gc,{orientation:"vertical",className:"mx-1 h-6"}),e.jsx(Zv,{onClick:r,active:n.isActive("link"),icon:Ad,tooltip:"Insert Link"}),e.jsx(Gc,{orientation:"vertical",className:"mx-1 h-6"}),e.jsx(Zv,{onClick:()=>n.chain().focus().undo().run(),disabled:!n.can().undo(),icon:BE,tooltip:"Undo"}),e.jsx(Zv,{onClick:()=>n.chain().focus().redo().run(),disabled:!n.can().redo(),icon:OE,tooltip:"Redo"}),e.jsx("div",{className:"flex-1"}),e.jsx($,{type:"button",variant:"outline",size:"sm",className:"h-8 gap-1.5 text-xs font-medium",onClick:()=>{n&&n.chain().focus().insertContent('

Learn More About Us

').run()},children:"🔘 CTA Button"}),e.jsxs(Uu,{children:[e.jsx(qu,{asChild:!0,children:e.jsxs($,{type:"button",variant:"outline",size:"sm",className:"h-8 gap-1.5 text-xs font-medium",children:[e.jsx(gV,{className:"h-3.5 w-3.5"}),"Merge Tags"]})}),e.jsx(Eu,{align:"end",className:"w-56",children:vEt.map(i=>e.jsxs(ja,{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(H6e,{editor:n,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:"}),vEt.map(i=>e.jsx(Be,{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 scr({open:s,onClose:t,campaignName:n,stat:r}){return e.jsx(zs,{open:s,onOpenChange:a=>!a&&t(),children:e.jsxs(Os,{className:"max-w-3xl max-h-[85vh] overflow-y-auto",children:[e.jsxs(Us,{children:[e.jsxs(Bs,{className:"flex items-center gap-2",children:[e.jsx(Yl,{className:"h-5 w-5 text-primary"}),n," — Engagement Stats"]}),e.jsx(Ir,{children:"Per-email breakdown of sends, opens, and clicks for this campaign at your brokerage."})]}),!r||r.sent===0?e.jsxs("div",{className:"text-center py-12 text-muted-foreground",children:[e.jsx(Yr,{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(ahe,{icon:mn,color:"text-blue-500",label:"Total Sent",value:r.sent.toLocaleString()}),e.jsx(ahe,{icon:Ca,color:"text-amber-500",label:"Opens",value:`${r.opened.toLocaleString()}`,sub:`${r.openRate.toFixed(1)}% open rate`}),e.jsx(ahe,{icon:Lm,color:"text-green-500",label:"Clicks",value:`${r.clicked.toLocaleString()}`,sub:`${r.clickRate.toFixed(1)}% click rate`}),e.jsx(ahe,{icon:wl,color:"text-destructive",label:"Failed",value:r.failed.toLocaleString()})]}),r.lastSentAt&&e.jsxs("p",{className:"text-xs text-muted-foreground flex items-center gap-1.5",children:[e.jsx(da,{className:"h-3 w-3"})," Last sent: ",en(new Date(r.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:r.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(Ne,{className:"overflow-hidden",children:e.jsxs(Ie,{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(Be,{variant:"outline",className:"text-[10px] gap-1",children:[e.jsx(mn,{className:"h-2.5 w-2.5"})," ",a.sent_count.toLocaleString()," sent"]}),e.jsxs(Be,{variant:"outline",className:"text-[10px] gap-1 border-amber-500/30 text-amber-600",children:[e.jsx(Ca,{className:"h-2.5 w-2.5"})," ",a.opened_count.toLocaleString()," (",i.toFixed(1),"%)"]}),e.jsxs(Be,{variant:"outline",className:"text-[10px] gap-1 border-green-500/30 text-green-600",children:[e.jsx(Lm,{className:"h-2.5 w-2.5"})," ",a.clicked_count.toLocaleString()," (",l.toFixed(1),"%)"]}),a.failed_count>0&&e.jsxs(Be,{variant:"outline",className:"text-[10px] gap-1 border-destructive/30 text-destructive",children:[e.jsx(wl,{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 ahe({icon:s,color:t,label:n,value:r,sub:a}){return e.jsx(Ne,{children:e.jsx(Ie,{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:r}),e.jsx("p",{className:"text-[10px] text-muted-foreground mt-1",children:n}),a&&e.jsx("p",{className:"text-[10px] text-muted-foreground",children:a})]})]})})})}function Klt(s){return tt({queryKey:["recruit-campaign-stats",s],enabled:!!s,staleTime:6e4,queryFn:async()=>{const{data:t,error:n}=await q.from("recruit_campaign_email_stats").select("*").eq("brokerage_id",s);if(n)throw n;const r=t??[],a={};for(const i of r){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 bEt={cold:{icon:t2,color:"text-blue-500",bg:"bg-blue-50 dark:bg-blue-950/30",label:"Cold — Curiosity"},warm:{icon:rk,color:"text-amber-500",bg:"bg-amber-50 dark:bg-amber-950/30",label:"Warm — Growth"},hot:{icon:nh,color:"text-red-500",bg:"bg-red-50 dark:bg-red-950/30",label:"Hot — Private Invite"}};function qos({brokerageId:s}){var ve,Ee,Se,Le;const{user:t}=vs(),n=Vt(),[r,a]=j.useState(null),[i,l]=j.useState(null),[o,c]=j.useState(null),[d,u]=j.useState(!1),[h,m]=j.useState(!1),[f,g]=j.useState("editor"),[x,y]=j.useState(null),[v,b]=j.useState(null),{data:w={}}=Klt(s),[S,C]=j.useState({name:"",description:"",theme:"",goal:"",primary_cta:"Learn more",warmth_level:"warm",sender_name:"",sender_email:"",reply_to_email:""}),{data:E}=tt({queryKey:["brokerage-detail",s],queryFn:async()=>{const{data:Fe,error:ke}=await q.from("brokerages").select("name, city, state").eq("id",s).single();if(ke)throw ke;return Fe}}),{data:I}=tt({queryKey:["brokerage-recruit-settings",s],queryFn:async()=>{const{data:Fe,error:ke}=await q.from("brokerage_recruit_settings").select("*").eq("brokerage_id",s).maybeSingle();if(ke)throw ke;return Fe}}),P={first_name:"Sarah",brokerage_name:((ve=I==null?void 0:I.merge_fields)==null?void 0:ve.brokerage_name)||(E==null?void 0:E.name)||"Your Brokerage",city:((Ee=I==null?void 0:I.merge_fields)==null?void 0:Ee.city)||(E==null?void 0:E.city)||"Your City",sender_name:((Se=I==null?void 0:I.merge_fields)==null?void 0:Se.sender_name)||(I==null?void 0:I.sender_name)||"Your Name"},R=Fe=>Fe.replace(/\{\{first_name\}\}/g,P.first_name).replace(/\{\{brokerage_name\}\}/g,P.brokerage_name).replace(/\{\{city\}\}/g,P.city).replace(/\{\{sender_name\}\}/g,P.sender_name),{data:D=[],isLoading:O}=tt({queryKey:["recruit-campaigns",s],queryFn:async()=>{const{data:Fe,error:ke}=await q.from("recruit_campaigns").select("*").or(`brokerage_id.is.null,brokerage_id.eq.${s}`).order("sort_order");if(ke)throw ke;return Fe}}),{data:U={}}=tt({queryKey:["recruit-campaign-emails",s],enabled:D.length>0,queryFn:async()=>{const Fe=D.map(Ae=>Ae.id),{data:ke,error:Ve}=await q.from("recruit_campaign_emails").select("*").in("campaign_id",Fe).order("email_number");if(Ve)throw Ve;const je={};return ke.forEach(Ae=>{je[Ae.campaign_id]||(je[Ae.campaign_id]=[]),je[Ae.campaign_id].push(Ae)}),je}}),W=Object.values(U).flat().map(Fe=>Fe.id),{data:V=[]}=tt({queryKey:["recruit-subject-overrides",s],enabled:W.length>0,queryFn:async()=>{const{data:Fe,error:ke}=await q.from("recruit_brokerage_subject_overrides").select("*").eq("brokerage_id",s);if(ke)throw ke;return Fe}}),G={};V.forEach(Fe=>{G[Fe.campaign_email_id]=Fe.selected_subject_index});const Y=ft({mutationFn:async({campaignEmailId:Fe,selectedIndex:ke})=>{const{error:Ve}=await q.from("recruit_brokerage_subject_overrides").upsert({brokerage_id:s,campaign_email_id:Fe,selected_subject_index:ke,updated_at:new Date().toISOString()},{onConflict:"brokerage_id,campaign_email_id"});if(Ve)throw Ve},onSuccess:()=>{n.invalidateQueries({queryKey:["recruit-subject-overrides",s]}),re.success("Subject line updated for your brokerage")},onError:Fe=>re.error(Fe.message)}),X=ft({mutationFn:async Fe=>{const{error:ke}=await q.from("recruit_campaign_emails").update({title:Fe.title,subject_line:Fe.subject_line,subject_line_options:Fe.subject_line_options,body_html:Fe.body_html,body_text:Fe.body_text,delay_days:Fe.delay_days,updated_at:new Date().toISOString()}).eq("id",Fe.id);if(ke)throw ke},onSuccess:()=>{n.invalidateQueries({queryKey:["recruit-campaign-emails"]}),re.success("Email template saved!"),l(null)},onError:Fe=>re.error(Fe.message)}),ae=ft({mutationFn:async()=>{const Fe=S.name.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/(^-|-$)/g,""),{data:ke,error:Ve}=await q.from("recruit_campaigns").insert({name:S.name,slug:Fe,description:S.description||null,theme:S.theme||null,goal:S.goal||null,primary_cta:S.primary_cta||"Learn more",warmth_level:S.warmth_level,brokerage_id:s,created_by:t==null?void 0:t.id,sender_name:S.sender_name||null,sender_email:S.sender_email||null,reply_to_email:S.reply_to_email||null,is_active:!0,sort_order:D.length+1}).select().single();if(Ve)throw Ve;const je=[{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:Ae}=await q.from("recruit_campaign_emails").insert(je.map(Ce=>({campaign_id:ke.id,...Ce,body_html:"

Hi {{first_name}},

Write your message here...

Best,
{{sender_name}}

",body_text:"",subject_line_options:[],is_active:!0})));if(Ae)throw Ae;return ke},onSuccess:()=>{n.invalidateQueries({queryKey:["recruit-campaigns"]}),n.invalidateQueries({queryKey:["recruit-campaign-emails"]}),re.success("Campaign created with 4 starter emails!"),m(!1),C({name:"",description:"",theme:"",goal:"",primary_cta:"Learn more",warmth_level:"warm",sender_name:"",sender_email:"",reply_to_email:""})},onError:Fe=>re.error(Fe.message)}),ie=ft({mutationFn:async Fe=>{const{error:ke}=await q.from("recruit_campaigns").update({name:Fe.name,description:Fe.description,theme:Fe.theme,goal:Fe.goal,primary_cta:Fe.primary_cta,warmth_level:Fe.warmth_level,sender_name:Fe.sender_name,sender_email:Fe.sender_email,reply_to_email:Fe.reply_to_email,updated_at:new Date().toISOString()}).eq("id",Fe.id);if(ke)throw ke},onSuccess:()=>{n.invalidateQueries({queryKey:["recruit-campaigns"]}),re.success("Campaign settings saved!"),y(null)},onError:Fe=>re.error(Fe.message)}),ne=ft({mutationFn:async Fe=>{var qe,ze;const{data:ke}=await q.from("recruit_campaign_emails").select("email_number, delay_days").eq("campaign_id",Fe).order("email_number",{ascending:!1}).limit(1),Ve=((qe=ke==null?void 0:ke[0])==null?void 0:qe.email_number)??0,je=((ze=ke==null?void 0:ke[0])==null?void 0:ze.delay_days)??0,Ae=Ve+1,{error:Ce}=await q.from("recruit_campaign_emails").insert({campaign_id:Fe,email_number:Ae,title:`Email ${Ae}`,subject_line:"Hey {{first_name}}",subject_line_options:[],body_html:"

Hi {{first_name}},

Write your message here...

Best,
{{sender_name}}

",body_text:"",delay_days:je+7,is_active:!0});if(Ce)throw Ce},onSuccess:()=>{n.invalidateQueries({queryKey:["recruit-campaign-emails"]}),re.success("Email added to campaign!")},onError:Fe=>re.error(Fe.message)}),te=ft({mutationFn:async Fe=>{const{error:ke}=await q.from("recruit_campaigns").delete().eq("id",Fe);if(ke)throw ke},onSuccess:()=>{n.invalidateQueries({queryKey:["recruit-campaigns"]}),n.invalidateQueries({queryKey:["recruit-campaign-emails"]}),re.success("Campaign deleted")},onError:Fe=>re.error(Fe.message)}),J=ft({mutationFn:async Fe=>{const{error:ke}=await q.from("recruit_campaign_emails").delete().eq("id",Fe);if(ke)throw ke},onSuccess:()=>{n.invalidateQueries({queryKey:["recruit-campaign-emails"]}),re.success("Email removed from campaign")},onError:Fe=>re.error(Fe.message)}),ce=ft({mutationFn:async({emailId:Fe,delay_days:ke})=>{const{error:Ve}=await q.from("recruit_campaign_emails").update({delay_days:ke,updated_at:new Date().toISOString()}).eq("id",Fe);if(Ve)throw Ve},onSuccess:()=>{n.invalidateQueries({queryKey:["recruit-campaign-emails"]}),re.success("Send delay updated")},onError:Fe=>re.error(Fe.message)});if(O)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 _e=D.filter(Fe=>!Fe.brokerage_id),he=D.filter(Fe=>Fe.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($,{variant:"outline",size:"sm",onClick:()=>u(!0),className:"gap-1.5",children:[e.jsx(Sd,{className:"h-4 w-4"})," Default Settings"]}),e.jsxs($,{size:"sm",onClick:()=>m(!0),className:"gap-1.5",children:[e.jsx(dn,{className:"h-4 w-4"})," New Campaign"]})]})]}),e.jsx(Ne,{className:"border-primary/20 bg-primary/5",children:e.jsx(Ie,{className:"py-3",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(Nn,{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(Sd,{className:"inline h-3.5 w-3.5"})," icon on any campaign to customize."]})]})]})})}),he.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(Wq,{className:"h-4 w-4"})," Your Custom Campaigns"]}),e.jsx("div",{className:"space-y-3",children:he.map(Fe=>ue(Fe,!0))})]}),_e.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(Nn,{className:"h-4 w-4"})," System Campaigns"]}),e.jsx("div",{className:"space-y-3",children:_e.map(Fe=>ue(Fe,!1))})]}),D.length===0&&e.jsx(Ne,{children:e.jsxs(Ie,{className:"py-12 text-center text-muted-foreground",children:[e.jsx(mn,{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($,{className:"mt-4",onClick:()=>m(!0),children:[e.jsx(dn,{className:"h-4 w-4 mr-1"})," Create Campaign"]})]})}),e.jsx(scr,{open:!!v,onClose:()=>b(null),campaignName:(v==null?void 0:v.name)||"",stat:v&&w[v.id]||null}),o&&e.jsx($os,{email:o,mergeValues:P,selectedSubjectIndex:G[o.id],onClose:()=>c(null)}),e.jsx(zs,{open:!!i,onOpenChange:Fe=>!Fe&&l(null),children:e.jsxs(Os,{className:"max-w-4xl max-h-[90vh] overflow-y-auto p-0",children:[e.jsxs(Us,{className:"px-6 pt-6 pb-4 border-b",children:[e.jsxs(Bs,{className:"flex items-center gap-2",children:[e.jsx(WI,{className:"h-5 w-5 text-primary"}),"Edit Email #",i==null?void 0:i.email_number]}),e.jsx(Ir,{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(ee,{className:"text-xs font-medium text-muted-foreground uppercase tracking-wider",children:"Email Title"}),e.jsx(pe,{value:i.title,onChange:Fe=>l({...i,title:Fe.target.value}),className:"h-9"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{className:"text-xs font-medium text-muted-foreground uppercase tracking-wider",children:"Delay (days after previous)"}),e.jsx(pe,{type:"number",min:0,max:90,value:i.delay_days,onChange:Fe=>l({...i,delay_days:parseInt(Fe.target.value)||7}),className:"h-9"})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{className:"text-xs font-medium text-muted-foreground uppercase tracking-wider",children:"Subject Line"}),e.jsx(pe,{value:i.subject_line,onChange:Fe=>l({...i,subject_line:Fe.target.value}),placeholder:"e.g. Hey {{first_name}}, quick question...",className:"h-9"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs(ee,{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(Rs,{value:((Le=i.subject_line_options)==null?void 0:Le.join(` `))||"",onChange:Fe=>l({...i,subject_line_options:Fe.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(ee,{className:"text-xs font-medium text-muted-foreground uppercase tracking-wider",children:"Email Body"}),e.jsx(ha,{value:f,onValueChange:Fe=>g(Fe),children:e.jsxs(ma,{className:"h-7",children:[e.jsx(Zt,{value:"editor",className:"text-xs px-3 h-6",children:"Editor"}),e.jsx(Zt,{value:"preview",className:"text-xs px-3 h-6",children:"Preview"})]})})]}),f==="editor"?e.jsx(tcr,{content:i.body_html,onChange:Fe=>l({...i,body_html:Fe})}):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:[P.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:[P.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:R(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:R(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($,{variant:"outline",size:"sm",onClick:()=>l(null),children:"Cancel"}),e.jsxs($,{size:"sm",onClick:()=>X.mutate(i),disabled:X.isPending,className:"gap-1.5",children:[e.jsx(tl,{className:"h-3.5 w-3.5"})," Save Changes"]})]})]})]})]})}),e.jsx(zs,{open:h,onOpenChange:m,children:e.jsxs(Os,{className:"max-w-lg",children:[e.jsxs(Us,{children:[e.jsxs(Bs,{className:"flex items-center gap-2",children:[e.jsx(dn,{className:"h-5 w-5 text-primary"})," Create Custom Campaign"]}),e.jsx(Ir,{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(ee,{className:"text-xs font-medium",children:"Campaign Name *"}),e.jsx(pe,{value:S.name,onChange:Fe=>C({...S,name:Fe.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(ee,{className:"text-xs font-medium",children:"Warmth Level"}),e.jsxs(ms,{value:S.warmth_level,onValueChange:Fe=>C({...S,warmth_level:Fe}),children:[e.jsx(us,{children:e.jsx(fs,{})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"cold",children:"❄️ Cold — Curiosity"}),e.jsx(Ge,{value:"warm",children:"☀️ Warm — Growth"}),e.jsx(Ge,{value:"hot",children:"🔥 Hot — Private Invite"})]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{className:"text-xs font-medium",children:"Primary CTA"}),e.jsx(pe,{value:S.primary_cta,onChange:Fe=>C({...S,primary_cta:Fe.target.value}),placeholder:"Learn more"})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{className:"text-xs font-medium",children:"Description"}),e.jsx(Rs,{value:S.description,onChange:Fe=>C({...S,description:Fe.target.value}),placeholder:"What is this campaign about?",rows:2})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{className:"text-xs font-medium",children:"Goal"}),e.jsx(pe,{value:S.goal,onChange:Fe=>C({...S,goal:Fe.target.value}),placeholder:"e.g. Convert warm leads to meetings"})]}),e.jsxs(j1,{children:[e.jsx(N1,{asChild:!0,children:e.jsxs($,{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(mn,{className:"h-3.5 w-3.5"})," Email Settings Override"]}),e.jsx(Tl,{className:"h-3.5 w-3.5"})]})}),e.jsxs(k1,{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(ee,{className:"text-xs",children:"Sender Name"}),e.jsx(pe,{value:S.sender_name,onChange:Fe=>C({...S,sender_name:Fe.target.value}),placeholder:"e.g. Jeremy at LevelUp"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{className:"text-xs",children:"Sender Email"}),e.jsx(pe,{value:S.sender_email,onChange:Fe=>C({...S,sender_email:Fe.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(ee,{className:"text-xs",children:"Reply-To Email"}),e.jsx(pe,{value:S.reply_to_email,onChange:Fe=>C({...S,reply_to_email:Fe.target.value}),placeholder:"e.g. jeremy@mybrokerage.com"})]})]})]}),e.jsxs($,{className:"w-full",disabled:!S.name.trim()||ae.isPending,onClick:()=>ae.mutate(),children:[e.jsx(dn,{className:"h-4 w-4 mr-1"})," Create Campaign"]})]})]})}),e.jsx(zs,{open:!!x,onOpenChange:Fe=>!Fe&&y(null),children:e.jsxs(Os,{className:"max-w-lg",children:[e.jsxs(Us,{children:[e.jsxs(Bs,{className:"flex items-center gap-2",children:[e.jsx(Sd,{className:"h-5 w-5 text-primary"})," Campaign Email Settings"]}),e.jsx(Ir,{children:"Override the default sender for this campaign. Leave blank to use brokerage defaults."})]}),x&&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(ee,{className:"text-xs font-medium",children:"Campaign Name"}),e.jsx(pe,{value:x.name,onChange:Fe=>y({...x,name:Fe.target.value})})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{className:"text-xs font-medium",children:"Warmth Level"}),e.jsxs(ms,{value:x.warmth_level,onValueChange:Fe=>y({...x,warmth_level:Fe}),children:[e.jsx(us,{children:e.jsx(fs,{})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"cold",children:"❄️ Cold"}),e.jsx(Ge,{value:"warm",children:"☀️ Warm"}),e.jsx(Ge,{value:"hot",children:"🔥 Hot"})]})]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{className:"text-xs font-medium",children:"Goal"}),e.jsx(pe,{value:x.goal||"",onChange:Fe=>y({...x,goal:Fe.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(mn,{className:"h-4 w-4 text-primary"})," Email Sender Override"]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{className:"text-xs",children:"Sender Name"}),e.jsx(pe,{value:x.sender_name||"",onChange:Fe=>y({...x,sender_name:Fe.target.value}),placeholder:"Uses brokerage default"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{className:"text-xs",children:"Sender Email"}),e.jsx(pe,{value:x.sender_email||"",onChange:Fe=>y({...x,sender_email:Fe.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(ee,{className:"text-xs",children:"Reply-To Email"}),e.jsx(pe,{value:x.reply_to_email||"",onChange:Fe=>y({...x,reply_to_email:Fe.target.value}),placeholder:"Uses brokerage default"})]})]}),e.jsxs($,{className:"w-full",onClick:()=>ie.mutate(x),disabled:ie.isPending,children:[e.jsx(tl,{className:"h-4 w-4 mr-1"})," Save Campaign Settings"]})]})]})}),e.jsx(zs,{open:d,onOpenChange:u,children:e.jsxs(Os,{className:"max-w-lg",children:[e.jsxs(Us,{children:[e.jsx(Bs,{children:"Default Recruiting Email Settings"}),e.jsx(Ir,{children:"These defaults apply to campaigns without their own overrides."})]}),e.jsx(Wlt,{brokerageId:s})]})})]});function ue(Fe,ke){const Ve=bEt[Fe.warmth_level]||bEt.cold,je=Ve.icon,Ae=U[Fe.id]||[],Ce=r===Fe.id,qe=!!(Fe.sender_name||Fe.sender_email||Fe.reply_to_email),ze=w[Fe.id];return e.jsxs(Ne,{className:"overflow-hidden transition-shadow hover:shadow-md",children:[e.jsx(Ct,{className:"cursor-pointer hover:bg-muted/40 transition-colors py-4",onClick:()=>a(Ce?null:Fe.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 ${Ve.bg} flex items-center justify-center`,children:e.jsx(je,{className:`h-5 w-5 ${Ve.color}`})}),e.jsxs("div",{children:[e.jsxs(At,{className:"text-base flex items-center gap-2",children:[Fe.name,e.jsx(Be,{variant:Fe.is_active?"default":"secondary",className:"text-[10px] px-1.5",children:Fe.is_active?"Active":"Draft"}),ke&&e.jsx(Be,{variant:"outline",className:"text-[10px] px-1.5",children:"Custom"}),qe&&e.jsxs(Be,{variant:"outline",className:"text-[10px] px-1.5 border-primary/30 text-primary",children:[e.jsx(mn,{className:"h-2.5 w-2.5 mr-0.5"})," Custom Sender"]})]}),e.jsx(Gn,{className:"text-xs mt-0.5",children:Fe.theme||Fe.description})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx($,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:$e=>{$e.stopPropagation(),y({...Fe})},children:e.jsx(Sd,{className:"h-4 w-4 text-muted-foreground"})}),ke&&e.jsx($,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0 text-destructive hover:text-destructive hover:bg-destructive/10",onClick:async $e=>{$e.stopPropagation(),await fo("Delete this campaign and all its emails? This cannot be undone.")&&te.mutate(Fe.id)},children:e.jsx(Wn,{className:"h-4 w-4"})}),ze&&ze.sent>0&&e.jsxs("div",{className:"hidden md:flex items-center gap-1.5",children:[e.jsxs(Be,{variant:"outline",className:"text-[10px] gap-1 font-medium",title:"Total emails sent",children:[e.jsx(mn,{className:"h-2.5 w-2.5"})," ",ze.sent.toLocaleString()]}),e.jsxs(Be,{variant:"outline",className:"text-[10px] gap-1 border-amber-500/30 text-amber-600 font-medium",title:`${ze.openRate.toFixed(1)}% open rate`,children:[e.jsx(Ca,{className:"h-2.5 w-2.5"})," ",ze.opened.toLocaleString()," (",ze.openRate.toFixed(0),"%)"]}),e.jsxs(Be,{variant:"outline",className:"text-[10px] gap-1 border-green-500/30 text-green-600 font-medium",title:`${ze.clickRate.toFixed(1)}% click rate`,children:[e.jsx(Lm,{className:"h-2.5 w-2.5"})," ",ze.clicked.toLocaleString()," (",ze.clickRate.toFixed(1),"%)"]})]}),e.jsxs($,{variant:"outline",size:"sm",className:"h-7 px-2 gap-1 text-xs",onClick:$e=>{$e.stopPropagation(),b(Fe)},title:"View detailed engagement stats",children:[e.jsx(Wl,{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(mn,{className:"h-3.5 w-3.5"}),e.jsxs("span",{children:[Ae.length," emails"]})]}),e.jsx("div",{className:"h-7 w-7 rounded-md flex items-center justify-center",children:Ce?e.jsx(v1,{className:"h-4 w-4 text-muted-foreground"}):e.jsx(Tl,{className:"h-4 w-4 text-muted-foreground"})})]})]})}),Ce&&e.jsxs(Ie,{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:Fe.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:Fe.primary_cta||"—"})]})]}),qe&&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(mn,{className:"h-3 w-3"})," Campaign Sender Override"]}),e.jsxs("div",{className:"grid grid-cols-3 gap-2 text-xs text-muted-foreground",children:[Fe.sender_name&&e.jsxs("p",{children:[e.jsx("span",{className:"font-medium",children:"Name:"})," ",Fe.sender_name]}),Fe.sender_email&&e.jsxs("p",{children:[e.jsx("span",{className:"font-medium",children:"Email:"})," ",Fe.sender_email]}),Fe.reply_to_email&&e.jsxs("p",{children:[e.jsx("span",{className:"font-medium",children:"Reply-To:"})," ",Fe.reply_to_email]})]})]}),e.jsx("div",{className:"relative",children:Ae.map(($e,ct)=>{var Xe,it;return e.jsxs("div",{className:"relative flex gap-4 pb-4 last:pb-0",children:[ctat.stopPropagation(),onBlur:at=>{const Ke=parseInt(at.target.value)||0;Ke!==$e.delay_days&&ce.mutate({emailId:$e.id,delay_days:Ke})},onKeyDown:at=>{at.key==="Enter"&&at.target.blur()}}),"days"]})]}):e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(da,{className:"h-3 w-3"}),$e.email_number===1?"Sent immediately":`Day ${$e.delay_days}`]}),e.jsx("span",{className:"text-border",children:"•"}),e.jsxs("span",{className:"truncate",children:["Subject: ",R(((Xe=$e.subject_line_options)==null?void 0:Xe.length)>0&&$e.subject_line_options[G[$e.id]??0]||$e.subject_line)]})]}),((it=$e.subject_line_options)==null?void 0:it.length)>1&&e.jsx("div",{className:"mt-2",children:e.jsxs(ms,{value:String(G[$e.id]??0),onValueChange:at=>Y.mutate({campaignEmailId:$e.id,selectedIndex:parseInt(at)}),children:[e.jsx(us,{className:"h-7 text-xs w-full max-w-sm",children:e.jsx(fs,{placeholder:"Choose subject line"})}),e.jsx(hs,{children:$e.subject_line_options.map((at,Ke)=>e.jsxs(Ge,{value:String(Ke),className:"text-xs",children:[e.jsxs("span",{className:"font-medium mr-1.5",children:[Ke===0?"Primary":`Alt ${Ke}`,":"]}),R(at)]},Ke))})]})})]}),e.jsxs("div",{className:"flex items-center gap-1 opacity-0 group-hover:opacity-100 transition-opacity shrink-0",children:[e.jsx($,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>c($e),children:e.jsx(Ca,{className:"h-4 w-4"})}),e.jsx($,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>{l({...$e}),g("editor")},children:e.jsx(gi,{className:"h-4 w-4"})}),ke&&Ae.length>1&&e.jsx($,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0 text-destructive hover:text-destructive hover:bg-destructive/10",onClick:async()=>{await fo("Delete this email from the sequence?")&&J.mutate($e.id)},children:e.jsx(Wn,{className:"h-4 w-4"})})]})]})})]},$e.id)})}),ke&&e.jsxs($,{variant:"outline",size:"sm",className:"w-full gap-1.5",onClick:()=>ne.mutate(Fe.id),disabled:ne.isPending,children:[e.jsx(dn,{className:"h-3.5 w-3.5"})," Add Email to Sequence"]})]})]},Fe.id)}}const _Et={active:{icon:Bu,color:"bg-green-500/10 text-green-600",label:"Active"},paused:{icon:Tv,color:"bg-amber-500/10 text-amber-600",label:"Paused"},completed:{icon:Nc,color:"bg-blue-500/10 text-blue-600",label:"Completed"},cancelled:{icon:ku,color:"bg-red-500/10 text-red-600",label:"Cancelled"}},wEt={sent:{icon:mn,color:"text-blue-500"},opened:{icon:Ca,color:"text-amber-500"},clicked:{icon:Lm,color:"text-green-500"},failed:{icon:wl,color:"text-destructive"}};function Vos({brokerageId:s}){var Le,Fe,ke,Ve,je;const{user:t}=vs(),n=Vt(),[r,a]=j.useState(!1),[i,l]=j.useState(""),[o,c]=j.useState(new Set),[d,u]=j.useState("assignments"),[h,m]=j.useState(null),[f,g]=j.useState(""),[x,y]=j.useState("all"),[v,b]=j.useState("all"),[w,S]=j.useState(!1),{data:C}=oie(),{data:E={}}=tt({queryKey:["recruit-campaign-emails-for-preview",s],queryFn:async()=>{const{data:Ae,error:Ce}=await q.from("recruit_campaign_emails").select("*").order("email_number");if(Ce)throw Ce;const qe={};return(Ae??[]).forEach(ze=>{qe[ze.campaign_id]||(qe[ze.campaign_id]=[]),qe[ze.campaign_id].push(ze)}),qe}}),{data:I}=tt({queryKey:["brokerage-detail",s],queryFn:async()=>{const{data:Ae,error:Ce}=await q.from("brokerages").select("name, city, state").eq("id",s).single();if(Ce)throw Ce;return Ae}}),{data:P}=tt({queryKey:["brokerage-recruit-settings",s],queryFn:async()=>{const{data:Ae,error:Ce}=await q.from("brokerage_recruit_settings").select("*").eq("brokerage_id",s).maybeSingle();if(Ce)throw Ce;return Ae}}),{data:R=[]}=tt({queryKey:["recruit-subject-overrides",s],queryFn:async()=>{const{data:Ae,error:Ce}=await q.from("recruit_brokerage_subject_overrides").select("*").eq("brokerage_id",s);if(Ce)throw Ce;return Ae}}),D={};R.forEach(Ae=>{D[Ae.campaign_email_id]=Ae.selected_subject_index});const O={first_name:((Le=h==null?void 0:h.prospect)==null?void 0:Le.first_name)||"Sarah",brokerage_name:((Fe=P==null?void 0:P.merge_fields)==null?void 0:Fe.brokerage_name)||(I==null?void 0:I.name)||"Your Brokerage",city:((ke=P==null?void 0:P.merge_fields)==null?void 0:ke.city)||(I==null?void 0:I.city)||"Your City",sender_name:((Ve=P==null?void 0:P.merge_fields)==null?void 0:Ve.sender_name)||(P==null?void 0:P.sender_name)||"Your Name"},U=Ae=>{const Ce=E[Ae.campaign_id]||[],qe=Ae.current_email_number+1;return Ce.find(ze=>ze.email_number===qe)||null},{data:W=[],isLoading:V}=tt({queryKey:["recruit-campaign-assignments",s],queryFn:async()=>{let Ce=[],qe=0;for(;;){const{data:ze,error:$e}=await q.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(qe,qe+1e3-1);if($e)throw $e;if(Ce=Ce.concat(ze??[]),!ze||ze.length<1e3)break;qe+=1e3}return Ce}}),{data:G=[]}=tt({queryKey:["recruit-campaign-sends",s],queryFn:async()=>{const{data:Ae,error:Ce}=await q.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(Ce)throw Ce;return Ae}}),{data:Y=[]}=tt({queryKey:["recruit-campaigns"],queryFn:async()=>{const{data:Ae,error:Ce}=await q.from("recruit_campaigns").select("id, name, warmth_level").eq("is_active",!0).order("sort_order");if(Ce)throw Ce;return Ae}}),{data:X=[]}=tt({queryKey:["recruit-prospects-for-assign",s],queryFn:async()=>{let Ce=[],qe=0;for(;;){const{data:ze,error:$e}=await q.from("recruit_prospects").select("id, first_name, last_name, email").eq("brokerage_id",s).order("first_name").range(qe,qe+1e3-1);if($e)throw $e;if(Ce=Ce.concat(ze??[]),!ze||ze.length<1e3)break;qe+=1e3}return Ce}}),ae=new Set(W.map(Ae=>`${Ae.prospect_id}-${Ae.campaign_id}`)),ie=ft({mutationFn:async()=>{if(!i||o.size===0)throw new Error("Select a campaign and at least one prospect");const Ae=new Date,Ce=Array.from(o).filter(ze=>!ae.has(`${ze}-${i}`)).map(ze=>({prospect_id:ze,campaign_id:i,brokerage_id:s,assigned_by:t.id,status:"active",current_email_number:0,next_send_at:Ae.toISOString(),started_at:Ae.toISOString()}));if(Ce.length===0)throw new Error("All selected prospects are already assigned to this campaign");const{error:qe}=await q.from("recruit_campaign_assignments").insert(Ce);if(qe)throw qe},onSuccess:()=>{n.invalidateQueries({queryKey:["recruit-campaign-assignments",s]}),re.success(`Campaign assigned to ${o.size} prospect(s)!`),a(!1),l(""),c(new Set)},onError:Ae=>re.error(Ae.message)}),ne=ft({mutationFn:async({id:Ae,newStatus:Ce})=>{const{error:qe}=await q.from("recruit_campaign_assignments").update({status:Ce,updated_at:new Date().toISOString()}).eq("id",Ae);if(qe)throw qe},onSuccess:()=>{n.invalidateQueries({queryKey:["recruit-campaign-assignments",s]}),re.success("Assignment updated")}}),te=ft({mutationFn:async()=>{const{data:Ae,error:Ce}=await q.functions.invoke("ses-recruit-drip",{body:{action:"process_drips"}});if(Ce)throw Ce;return Ae},onSuccess:Ae=>{n.invalidateQueries({queryKey:["recruit-campaign-assignments",s]}),n.invalidateQueries({queryKey:["recruit-campaign-sends",s]}),re.success(`Wave sent! ${Ae.sent} emails delivered, ${Ae.skipped} skipped, ${Ae.failed} failed`)},onError:Ae=>re.error(`Send failed: ${Ae.message}`)}),J=W.filter(Ae=>Ae.status==="active").length;W.filter(Ae=>Ae.status==="completed").length;const ce=W.filter(Ae=>Ae.status==="active"&&Ae.next_send_at&&new Date(Ae.next_send_at)<=new Date).length,{data:_e={}}=Klt(s),he=W.reduce((Ae,Ce)=>Ae+Math.max(0,Ce.current_email_number||0),0),ue=Object.values(_e).reduce((Ae,Ce)=>Ae+Ce.opened,0),ve=Object.values(_e).reduce((Ae,Ce)=>Ae+Ce.clicked,0);Object.values(_e).reduce((Ae,Ce)=>Ae+Ce.failed,0);const Ee=he>0?Math.round(ue/he*100):0,Se=he>0?ve/he*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:[ce>0&&e.jsxs($,{variant:"outline",onClick:()=>{te.mutate()},disabled:te.isPending,className:"border-amber-500/50 text-amber-600 hover:bg-amber-500/10",children:[e.jsx(eg,{className:"h-4 w-4 mr-1"}),te.isPending?"Sending...":`Send Next Wave (${ce})`]}),e.jsxs($,{onClick:()=>a(!0),children:[e.jsx(Yr,{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(Ne,{children:e.jsxs(Ie,{className:"pt-3 pb-2 flex items-center gap-3",children:[e.jsx(Zn,{className:"h-7 w-7 text-primary"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xl font-bold",children:W.length}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Assigned"})]})]})}),e.jsx(Ne,{children:e.jsxs(Ie,{className:"pt-3 pb-2 flex items-center gap-3",children:[e.jsx(Bu,{className:"h-7 w-7 text-green-500"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xl font-bold",children:J}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Active"})]})]})}),e.jsx(Ne,{children:e.jsxs(Ie,{className:"pt-3 pb-2 flex items-center gap-3",children:[e.jsx(mn,{className:"h-7 w-7 text-blue-500"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xl font-bold",children:he.toLocaleString()}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Emails Sent"})]})]})}),e.jsx(Ne,{children:e.jsxs(Ie,{className:"pt-3 pb-2 flex items-center gap-3",children:[e.jsx(Ca,{className:"h-7 w-7 text-amber-500"}),e.jsxs("div",{children:[e.jsxs("p",{className:"text-xl font-bold",children:[Ee,"%"]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Open Rate (",ue.toLocaleString(),")"]})]})]})}),e.jsx(Ne,{children:e.jsxs(Ie,{className:"pt-3 pb-2 flex items-center gap-3",children:[e.jsx(Lm,{className:"h-7 w-7 text-green-500"}),e.jsxs("div",{children:[e.jsxs("p",{className:"text-xl font-bold",children:[Se.toFixed(1),"%"]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Click Rate (",ve.toLocaleString(),")"]})]})]})})]}),e.jsxs(ha,{value:d,onValueChange:u,children:[e.jsxs(ma,{children:[e.jsxs(Zt,{value:"assignments",children:["Active Drips (",J,")"]}),e.jsxs(Zt,{value:"history",children:["Send History (",he.toLocaleString(),")"]})]}),e.jsx(Xt,{value:"assignments",className:"mt-4",children:V?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"})}):W.length===0?e.jsx(Ne,{children:e.jsxs(Ie,{className:"py-12 text-center text-muted-foreground",children:[e.jsx(Yr,{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:W.map(Ae=>{var Xe,it,at,Ke;const Ce=_Et[Ae.status]||_Et.active,qe=Ce.icon,$e=(E[Ae.campaign_id]||[]).length||4,ct=U(Ae);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(Be,{className:`text-xs ${Ce.color} border-0`,children:[e.jsx(qe,{className:"h-3 w-3 mr-1"}),Ce.label]}),e.jsxs("div",{className:"min-w-0",children:[e.jsxs("p",{className:"font-medium text-sm",children:[(Xe=Ae.prospect)==null?void 0:Xe.first_name," ",(it=Ae.prospect)==null?void 0:it.last_name,e.jsx("span",{className:"text-muted-foreground font-normal ml-2",children:(at=Ae.prospect)==null?void 0:at.email})]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[(Ke=Ae.campaign)==null?void 0:Ke.name," · Email ",Ae.current_email_number,"/",$e,Ae.next_send_at&&Ae.status==="active"&&e.jsxs(e.Fragment,{children:[" ","· ",e.jsx(da,{className:"h-3 w-3 inline"})," Next: ",en(new Date(Ae.next_send_at),"MMM d, h:mm a"),new Date(Ae.next_send_at)<=new Date&&e.jsx(Be,{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:[ct&&e.jsx($,{variant:"ghost",size:"sm",title:"Preview next email",onClick:()=>m(Ae),children:e.jsx(Ca,{className:"h-3.5 w-3.5"})}),Ae.status==="active"&&e.jsx($,{variant:"ghost",size:"sm",onClick:()=>ne.mutate({id:Ae.id,newStatus:"paused"}),children:e.jsx(Tv,{className:"h-3.5 w-3.5"})}),Ae.status==="paused"&&e.jsx($,{variant:"ghost",size:"sm",onClick:()=>ne.mutate({id:Ae.id,newStatus:"active"}),children:e.jsx(Bu,{className:"h-3.5 w-3.5"})}),(Ae.status==="active"||Ae.status==="paused")&&e.jsx($,{variant:"ghost",size:"sm",className:"text-destructive",onClick:()=>ne.mutate({id:Ae.id,newStatus:"cancelled"}),children:e.jsx(ku,{className:"h-3.5 w-3.5"})})]})]},Ae.id)})})}),e.jsxs(Xt,{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(ms,{value:x,onValueChange:y,children:[e.jsx(us,{className:"w-[220px] h-8 text-xs",children:e.jsx(fs,{placeholder:"All campaigns"})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"all",children:"All campaigns"}),Y.map(Ae=>e.jsx(Ge,{value:Ae.id,children:Ae.name},Ae.id))]})]}),e.jsxs(ms,{value:v,onValueChange:b,children:[e.jsx(us,{className:"w-[160px] h-8 text-xs",children:e.jsx(fs,{placeholder:"All statuses"})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"all",children:"All statuses"}),e.jsx(Ge,{value:"sent",children:"Sent (no engagement)"}),e.jsx(Ge,{value:"opened",children:"Opened"}),e.jsx(Ge,{value:"clicked",children:"Clicked"})]})]}),(x!=="all"||v!=="all")&&e.jsx($,{variant:"ghost",size:"sm",className:"h-8 text-xs",onClick:()=>{y("all"),b("all")},children:"Clear"})]}),(()=>{var Ce;const Ae=G.filter(qe=>{var ze;return!(x!=="all"&&((ze=qe.campaign_email)==null?void 0:ze.campaign_id)!==x||v==="opened"&&!qe.opened_at||v==="clicked"&&!qe.clicked_at||v==="sent"&&(qe.opened_at||qe.clicked_at))});return Ae.length===0?e.jsx(Ne,{children:e.jsxs(Ie,{className:"py-12 text-center text-muted-foreground",children:[e.jsx(mn,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{className:"font-medium",children:G.length===0?"No emails sent yet":"No emails match these filters"}),e.jsx("p",{className:"text-sm",children:G.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 ",Ae.length," of ",G.length," recent sends",x!=="all"&&` · ${(Ce=Y.find(qe=>qe.id===x))==null?void 0:Ce.name}`]}),e.jsx("div",{className:"space-y-1",children:Ae.map(qe=>{var Xe,it,at;const ze=wEt[qe.status]||wEt.sent,$e=ze.icon,ct=(Xe=Y.find(Ke=>{var nt;return Ke.id===((nt=qe.campaign_email)==null?void 0:nt.campaign_id)}))==null?void 0:Xe.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($e,{className:`h-4 w-4 flex-shrink-0 ${ze.color}`}),e.jsxs("div",{className:"min-w-0",children:[e.jsxs("p",{className:"font-medium text-sm truncate",children:[(it=qe.prospect)==null?void 0:it.first_name," ",(at=qe.prospect)==null?void 0:at.last_name,e.jsxs("span",{className:"text-muted-foreground font-normal ml-2",children:["Email #",qe.email_number]}),ct&&e.jsx(Be,{variant:"outline",className:"ml-2 text-[10px] px-1.5 py-0 font-normal",children:ct})]}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:qe.subject})]})]}),e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground flex-shrink-0",children:[qe.opened_at&&e.jsxs("span",{className:"flex items-center gap-1 text-amber-500",children:[e.jsx(Ca,{className:"h-3 w-3"})," ",en(new Date(qe.opened_at),"MMM d")]}),qe.clicked_at&&e.jsxs("span",{className:"flex items-center gap-1 text-green-500",children:[e.jsx(Lm,{className:"h-3 w-3"})," ",en(new Date(qe.clicked_at),"MMM d")]}),e.jsx("span",{children:en(new Date(qe.sent_at),"MMM d, h:mm a")})]})]},qe.id)})})]})})()]})]}),e.jsx(zs,{open:r,onOpenChange:Ae=>{a(Ae),Ae||(g(""),c(new Set),l(""))},children:e.jsxs(Os,{className:"max-w-lg max-h-[85vh] flex flex-col p-0",children:[e.jsxs(Us,{className:"px-6 pt-6 pb-4",children:[e.jsx(Bs,{children:"Assign Campaign to Prospects"}),e.jsx(Ir,{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(ee,{className:"text-sm font-medium",children:"1. Select Campaign"}),e.jsxs(ms,{value:i,onValueChange:l,children:[e.jsx(us,{children:e.jsx(fs,{placeholder:"Choose a campaign..."})}),e.jsx(hs,{children:Y.map(Ae=>e.jsx(Ge,{value:Ae.id,children:Ae.name},Ae.id))})]})]}),i&&(()=>{const Ae=f.toLowerCase(),Ce=X.filter($e=>`${$e.first_name} ${$e.last_name}`.toLowerCase().includes(Ae)||$e.email.toLowerCase().includes(Ae)),qe=Ce.filter($e=>!ae.has(`${$e.id}-${i}`)),ze=qe.length>0&&qe.every($e=>o.has($e.id));return e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(ee,{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(Kr,{className:"absolute left-2.5 top-2.5 h-4 w-4 text-muted-foreground"}),e.jsx(pe,{placeholder:"Search by name or email...",value:f,onChange:$e=>g($e.target.value),className:"pl-9 h-9"})]}),e.jsxs($,{variant:"outline",size:"sm",className:"h-9 whitespace-nowrap",onClick:()=>{if(ze){const $e=new Set(o);qe.forEach(ct=>$e.delete(ct.id)),c($e)}else{const $e=new Set(o);qe.forEach(ct=>$e.add(ct.id)),c($e)}},children:[e.jsx(Bz,{className:"h-3.5 w-3.5 mr-1"}),ze?"Deselect All":`Select All (${qe.length})`]})]}),e.jsx("div",{className:"border rounded-lg max-h-60 overflow-y-auto divide-y",children:Ce.length===0?e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:f?"No prospects match your search":"No prospects found for this brokerage"}):Ce.map($e=>{const ct=ae.has(`${$e.id}-${i}`);return e.jsxs("label",{className:`flex items-center gap-3 p-2.5 hover:bg-muted/50 cursor-pointer ${ct?"opacity-40":""}`,children:[e.jsx(ai,{checked:o.has($e.id),disabled:ct,onCheckedChange:Xe=>{const it=new Set(o);Xe?it.add($e.id):it.delete($e.id),c(it)}}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("p",{className:"text-sm font-medium truncate",children:[$e.first_name," ",$e.last_name]}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:$e.email})]}),ct&&e.jsx(Be,{variant:"outline",className:"text-[10px] shrink-0",children:"Already assigned"})]},$e.id)})}),Ce.length>0&&e.jsxs("p",{className:"text-[11px] text-muted-foreground",children:["Showing ",Ce.length," of ",X.length," prospects",qe.length0&&e.jsx(Ne,{className:"bg-primary/5 border-primary/20",children:e.jsxs(Ie,{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:(je=Y.find(Ae=>Ae.id===i))==null?void 0:je.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(Ar,{className:"px-6 py-4 border-t",children:[e.jsx($,{variant:"outline",onClick:()=>a(!1),children:"Cancel"}),e.jsxs($,{onClick:()=>{ie.mutate()},disabled:ie.isPending||!i||o.size===0,children:[e.jsx(Yr,{className:"h-4 w-4 mr-1"}),ie.isPending?"Assigning...":`Assign & Start (${o.size})`]})]})]})}),h&&(()=>{const Ae=U(h);return Ae?e.jsx($os,{email:Ae,mergeValues:O,selectedSubjectIndex:D[Ae.id],onClose:()=>m(null)}):null})(),e.jsx(S6e,{open:w,onOpenChange:S,hasPending:C==null?void 0:C.hasPendingSes,pendingEmails:C==null?void 0:C.pendingEmails})]})}function Hos({brokerageId:s}){const t=Vt(),[n,r]=j.useState([]),[a,i]=j.useState([]),[l,o]=j.useState(!1),c=j.useRef(!1),{data:d,isLoading:u}=tt({queryKey:["recruit-stages-editor",s],queryFn:async()=>{const{data:y,error:v}=await q.from("recruit_pipeline_stages").select("*").eq("brokerage_id",s).order("sort_order");if(v)throw v;return y},enabled:!!s});j.useEffect(()=>{if(d){if(c.current){c.current=!1;return}r(d.map(y=>({id:y.id,name:y.name,color:y.color,sort_order:y.sort_order}))),i([]),o(!1)}},[d]);const h=ft({mutationFn:async()=>{for(const b of a){const{error:w}=await q.from("recruit_pipeline_stages").delete().eq("id",b);if(w)throw w}const y=n.filter(b=>b.id&&!b.isNew),v=n.filter(b=>!b.id||b.isNew);for(const b of y){const{error:w}=await q.from("recruit_pipeline_stages").update({name:b.name,color:b.color,sort_order:b.sort_order}).eq("id",b.id);if(w)throw w}if(v.length>0){const{error:b}=await q.from("recruit_pipeline_stages").insert(v.map(w=>({brokerage_id:s,name:w.name,color:w.color,sort_order:w.sort_order})));if(b)throw b}},onSuccess:()=>{i([]),t.invalidateQueries({queryKey:["recruit-stages-editor",s]}),t.invalidateQueries({queryKey:["recruit-stages",s]}),re.success("Pipeline stages saved!"),o(!1)},onError:y=>re.error(y.message)}),m=(y,v,b)=>{r(w=>w.map((S,C)=>C===y?{...S,[v]:b}:S)),o(!0)},f=()=>{const y=n.length>0?Math.max(...n.map(v=>v.sort_order)):0;r(v=>[...v,{name:"",color:"#6366f1",sort_order:y+1,isNew:!0}]),o(!0)},g=y=>{const v=n[y];v.id&&!v.isNew&&i(b=>[...b,v.id]),r(b=>b.filter((w,S)=>S!==y)),o(!0)},x=(y,v)=>{const b=y+v;if(b<0||b>=n.length)return;const w=[...n];[w[y],w[b]]=[w[b],w[y]],w.forEach((S,C)=>S.sort_order=C+1),r(w),o(!0)};return u?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:n.map((y,v)=>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:()=>x(v,-1),disabled:v===0,className:"text-muted-foreground hover:text-foreground disabled:opacity-30 text-xs",children:"▲"}),e.jsx("button",{type:"button",onClick:()=>x(v,1),disabled:v===n.length-1,className:"text-muted-foreground hover:text-foreground disabled:opacity-30 text-xs",children:"▼"})]}),e.jsx(Ug,{className:"h-4 w-4 text-muted-foreground/50 shrink-0"}),e.jsx("input",{type:"color",value:y.color,onChange:b=>m(v,"color",b.target.value),className:"h-8 w-8 rounded cursor-pointer border-0 p-0 shrink-0"}),e.jsx(pe,{value:y.name,onChange:b=>m(v,"name",b.target.value),placeholder:"Stage name…",className:"flex-1"}),e.jsx("span",{className:"text-xs text-muted-foreground w-6 text-center shrink-0",children:v+1}),e.jsx($,{variant:"ghost",size:"icon",onClick:()=>g(v),className:"text-destructive hover:text-destructive shrink-0 h-8 w-8",children:e.jsx(Wn,{className:"h-4 w-4"})})]},y.id||`new-${v}`))}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs($,{variant:"outline",size:"sm",onClick:f,className:"gap-1",children:[e.jsx(dn,{className:"h-4 w-4"})," Add Stage"]}),l&&e.jsxs($,{size:"sm",onClick:()=>h.mutate(),disabled:h.isPending,className:"gap-1",children:[e.jsx(tl,{className:"h-4 w-4"})," Save Changes"]})]}),n.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 ncr({brokerageId:s}){const{data:t=[],isLoading:n}=tt({queryKey:["recruit-unsubscribed",s],queryFn:async()=>{const{data:r,error:a}=await q.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 r||[]},enabled:!!s});return n?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(t7,{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(Be,{variant:"secondary",className:"text-base px-3 py-1",children:[t.length," total"]})]}),t.length===0?e.jsx(Ne,{children:e.jsxs(Ie,{className:"py-12 text-center text-muted-foreground",children:[e.jsx(t7,{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(r=>e.jsxs(Ne,{className:"hover:shadow-sm transition-shadow",children:[e.jsx(Ct,{className:"pb-3",children:e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsxs(At,{className:"text-base",children:[r.first_name," ",r.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(mn,{className:"h-3 w-3"}),r.email]}),r.current_brokerage&&e.jsxs("span",{children:["· ",r.current_brokerage]})]})]}),e.jsxs("div",{className:"flex items-center gap-1.5 text-xs text-muted-foreground whitespace-nowrap",children:[e.jsx(Ta,{className:"h-3 w-3"}),r.unsubscribed_at&&en(new Date(r.unsubscribed_at),"MMM d, yyyy")]})]})}),r.unsubscribe_reason&&e.jsx(Ie,{className:"pt-0",children:e.jsxs("div",{className:"text-sm bg-muted/40 rounded-md px-3 py-2 italic text-muted-foreground",children:['"',r.unsubscribe_reason,'"']})})]},r.id))})]})}function rcr(){var o;const[s,t]=j.useState(""),[n,r]=j.useState("board"),{data:a=[],isLoading:i}=tt({queryKey:["all-brokerages"],queryFn:async()=>{const{data:c,error:d}=await q.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(Vs,{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(Vs,{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(ms,{value:l,onValueChange:t,children:[e.jsxs(us,{className:"w-[280px]",children:[e.jsx(ji,{className:"mr-2 h-4 w-4"}),e.jsx(fs,{placeholder:"Select brokerage"})]}),e.jsx(hs,{children:a.map(c=>e.jsx(Ge,{value:c.id,children:c.name},c.id))})]})]}):e.jsx("div",{}),l&&e.jsx(Oos,{brokerageId:l,trigger:e.jsxs($,{size:"sm",className:"gap-1.5",children:[e.jsx(ua,{className:"h-4 w-4"})," Record & Send Video"]})})]}),l?e.jsxs(ha,{defaultValue:"pipeline",className:"space-y-4",children:[e.jsxs(ma,{className:"flex-wrap h-auto gap-1",children:[e.jsx(Zt,{value:"pipeline",children:"Pipeline"}),e.jsxs(Zt,{value:"contacts",children:[e.jsx(Zn,{className:"h-3.5 w-3.5 mr-1"}),"Contacts"]}),e.jsxs(Zt,{value:"video-outreach",children:[e.jsx(ua,{className:"h-3.5 w-3.5 mr-1"}),"Video Outreach"]}),e.jsx(Zt,{value:"follow-ups",children:"Follow-ups"}),e.jsx(Zt,{value:"referrals",children:"Referrals"}),e.jsx(Zt,{value:"interest",children:"Interest Form"}),e.jsx(Zt,{value:"landing-page",children:"Landing Page"}),e.jsx(Zt,{value:"goals",children:"Goals"}),e.jsx(Zt,{value:"metrics",children:"Metrics"}),e.jsx(Zt,{value:"templates",children:"Email Templates"}),e.jsxs(Zt,{value:"campaigns",children:[e.jsx(mn,{className:"h-3.5 w-3.5 mr-1"}),"Campaigns"]}),e.jsxs(Zt,{value:"drip-assignments",children:[e.jsx(Yr,{className:"h-3.5 w-3.5 mr-1"}),"Drip Assignments"]}),e.jsx(Zt,{value:"activity",children:"Recruiter Activity"}),e.jsxs(Zt,{value:"email-settings",children:[e.jsx(Sd,{className:"h-3.5 w-3.5 mr-1"}),"Email Settings"]}),e.jsxs(Zt,{value:"pipeline-stages",children:[e.jsx(JI,{className:"h-3.5 w-3.5 mr-1"}),"Pipeline Stages"]}),e.jsxs(Zt,{value:"unsubscribed",children:[e.jsx(t7,{className:"h-3.5 w-3.5 mr-1"}),"Unsubscribed"]})]}),e.jsxs(Xt,{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($,{variant:n==="board"?"default":"ghost",size:"sm",className:"h-7 px-2.5 gap-1.5",onClick:()=>r("board"),children:[e.jsx(Qf,{className:"h-3.5 w-3.5"})," Board"]}),e.jsxs($,{variant:n==="table"?"default":"ghost",size:"sm",className:"h-7 px-2.5 gap-1.5",onClick:()=>r("table"),children:[e.jsx(cV,{className:"h-3.5 w-3.5"})," Table"]})]})}),n==="board"?e.jsx(Tos,{brokerageId:l}):e.jsx(uQe,{brokerageId:l})]}),e.jsx(Xt,{value:"contacts",children:e.jsx(uQe,{brokerageId:l})}),e.jsx(Xt,{value:"video-outreach",children:e.jsx(zos,{brokerageId:l})}),e.jsx(Xt,{value:"follow-ups",children:e.jsx(Dos,{brokerageId:l})}),e.jsx(Xt,{value:"referrals",children:e.jsx(Los,{brokerageId:l})}),e.jsx(Xt,{value:"interest",children:e.jsx(Ros,{brokerageId:l})}),e.jsx(Xt,{value:"landing-page",children:e.jsx(Fos,{brokerageId:l})}),e.jsx(Xt,{value:"goals",children:e.jsx(Bos,{brokerageId:l})}),e.jsx(Xt,{value:"metrics",children:e.jsx(Mos,{brokerageId:l})}),e.jsx(Xt,{value:"templates",children:e.jsx(Pos,{brokerageId:l})}),e.jsx(Xt,{value:"campaigns",children:e.jsx(qos,{brokerageId:l})}),e.jsx(Xt,{value:"drip-assignments",children:e.jsx(Vos,{brokerageId:l})}),e.jsx(Xt,{value:"activity",children:e.jsx(Ios,{brokerageId:l})}),e.jsx(Xt,{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(Wlt,{brokerageId:l})]})}),e.jsx(Xt,{value:"pipeline-stages",children:e.jsx("div",{className:"max-w-2xl",children:e.jsx(Hos,{brokerageId:l})})}),e.jsx(Xt,{value:"unsubscribed",children:e.jsx(ncr,{brokerageId:l})})]}):e.jsxs("div",{className:"text-center py-12 text-muted-foreground",children:[e.jsx(ji,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{children:"No brokerages found. Create a brokerage first."})]})]})})}const jEt=()=>{const s=new Date;return new Date(s.getFullYear(),s.getMonth(),s.getDate()).getTime()},aU=s=>{const t=s.split(/[-/T]/).slice(0,3).map(Number);return new Date(t[0],(t[1]||1)-1,t[2]||1).getTime()},iU=s=>Date.parse(s);async function EX(s,t,n){const a=[];for(let i=0;;i+=1e3){const l=n(q.from(s).select(t)).range(i,i+1e3-1),{data:o,error:c}=await l;if(c)throw c;if(a.push(...o??[]),!o||o.length<1e3)break}return a}function acr(s){var o;const t=S9(s),n=Klt(s),r=tt({queryKey:["recruit-command-sources",s,t.prospects.length],enabled:!!s&&!t.isLoading,queryFn:async()=>{if(!s)return{followUps:[],activities:[],goals:[],assignments:[],campaigns:[]};const c=t.prospects.map(g=>g.id),[d,u,h,m,f]=await Promise.all([c.length?EX("recruit_follow_ups","id, prospect_id, title, due_date, completed_at, assigned_to",g=>g.in("prospect_id",c).order("due_date")):Promise.resolve([]),c.length?EX("recruit_activities","id, prospect_id, activity_type, title, created_by, created_at",g=>g.in("prospect_id",c).order("created_at",{ascending:!1})):Promise.resolve([]),EX("recruit_goals","id, title, target_count, target_stage_id, period_start, period_end",g=>g.eq("brokerage_id",s).order("period_end",{ascending:!1})),EX("recruit_campaign_assignments","id, prospect_id, status",g=>g.eq("brokerage_id",s)),EX("recruit_campaigns","id, name, is_active, brokerage_id",g=>g.or(`brokerage_id.is.null,brokerage_id.eq.${s}`))]);return{followUps:d,activities:u,goals:h,assignments:m,campaigns:f}}}),a=j.useMemo(()=>{var d;const c=new Set;return t.prospects.forEach(u=>u.created_by&&c.add(u.created_by)),(((d=r.data)==null?void 0:d.activities)??[]).forEach(u=>u.created_by&&c.add(u.created_by)),[...c]},[t.prospects,(o=r.data)==null?void 0:o.activities]),i=tt({queryKey:["recruit-command-profiles",s,a],enabled:a.length>0,queryFn:async()=>{const{data:c,error:d}=await q.from("profiles").select("id, name, email").in("id",a);if(d)throw d;return c??[]}});return{...j.useMemo(()=>{var _e,he,ue,ve,Ee;const c=t.prospects,d=t.stages,u=((_e=r.data)==null?void 0:_e.followUps)??[],h=((he=r.data)==null?void 0:he.activities)??[],m=((ue=r.data)==null?void 0:ue.goals)??[],f=((ve=r.data)==null?void 0:ve.assignments)??[],g=((Ee=r.data)==null?void 0:Ee.campaigns)??[],x=jEt(),y=x+864e5,v=Date.now()-30*864e5,b=Date.now()-21*864e5,w=new Map(c.map(Se=>[Se.id,Se])),S=u.filter(Se=>!Se.completed_at),C=S.filter(Se=>iU(Se.due_date){const Le=iU(Se.due_date);return Le>=x&&Le{const Le=w.get(Se.prospect_id);if(!Le)return[];const Fe=iU(Se.due_date)Se.prospect_id));c.filter(Se=>iU(Se.updated_at)I.push({id:`stalled-${Se.id}`,prospect:Se,title:"No next step scheduled",detail:"No movement in 21+ days",tone:"stalled",dueAt:null}));const R=d.map(Se=>({...Se,count:c.filter(Le=>Le.stage_id===Se.id).length,stalled:c.filter(Le=>Le.stage_id===Se.id&&iU(Le.updated_at)aU(Se.period_start)<=D&&aU(Se.period_end)>=D)??null,U=O?c.filter(Se=>aU(Se.created_at)>=aU(O.period_start)&&aU(Se.created_at)<=aU(O.period_end)&&(!O.target_stage_id||Se.stage_id===O.target_stage_id)).length:0,W=Object.values(n.data??{}),V=W.reduce((Se,Le)=>Se+Le.sent,0),G=W.reduce((Se,Le)=>Se+Le.opened,0),Y=V?Math.round(G/V*100):0,X=new Map((i.data??[]).map(Se=>[Se.id,Se])),ae=a.map(Se=>{var Ve;const Le=h.filter(je=>je.created_by===Se),Fe=Le.filter(je=>iU(je.created_at)>=v),ke=X.get(Se);return{id:Se,name:(ke==null?void 0:ke.name)||(ke==null?void 0:ke.email)||"Unknown recruiter",email:(ke==null?void 0:ke.email)||"",prospects:c.filter(je=>je.created_by===Se).length,activities30d:Fe.length,lastActivityAt:((Ve=Le[0])==null?void 0:Ve.created_at)??null}}).sort((Se,Le)=>Le.activities30d-Se.activities30d),ie=new Map;c.forEach(Se=>{const Le=(Se.source||"Not recorded").replace(/_/g," ");ie.set(Le,(ie.get(Le)??0)+1)});const ne=[...ie.entries()].sort((Se,Le)=>Le[1]-Se[1]).slice(0,6),te=new Set(["signed","onboarded","hired","joined"]),J=new Set(d.filter(Se=>te.has(Se.name.toLowerCase())).map(Se=>Se.id)),ce=c.filter(Se=>Se.stage_id&&J.has(Se.stage_id)).length;return{prospects:c,stages:R,followUps:u,activities:h,priority:I.slice(0,12),overdueCount:C.length,dueTodayCount:E.length,currentGoal:O,goalCurrent:U,goalPercent:O?Math.min(100,Math.round(U/Math.max(1,O.target_count)*100)):0,campaignOpenRate:Y,campaignSent:V,activeCampaigns:g.filter(Se=>Se.is_active).length,activeAssignments:f.filter(Se=>Se.status==="active").length,recruiters:ae,sources:ne,converted:ce,conversionRate:c.length?Math.round(ce/c.length*100):0}},[t.prospects,t.stages,r.data,n.data,i.data,a]),pipeline:t,isLoading:t.isLoading||r.isLoading||n.isLoading||i.isLoading}}const icr=s=>s.split(/\s+/).filter(Boolean).slice(0,2).map(t=>t[0]).join("").toUpperCase(),ocr=s=>{if(!s)return"No activity";const t=Math.max(0,Math.floor((Date.now()-Date.parse(s))/864e5));return t===0?"Today":t===1?"Yesterday":`${t}d ago`},ihe=({label:s,value:t,detail:n,icon:r,tone:a,onClick:i})=>e.jsxs("button",{type:"button",onClick:i,className:"flex min-h-[112px] w-full items-start justify-between rounded-md border bg-card p-4 text-left shadow-xs transition-colors hover:border-primary/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-[11px] font-semibold uppercase text-muted-foreground",children:s}),e.jsx("p",{className:"mt-1 font-['Outfit'] text-3xl font-bold text-foreground",children:t}),e.jsx("p",{className:"mt-1 truncate text-xs text-muted-foreground",children:n})]}),e.jsx("span",{className:Pt("flex h-10 w-10 shrink-0 items-center justify-center rounded-full",a),children:e.jsx(r,{className:"h-5 w-5"})})]});function lcr({brokerageId:s,onNavigate:t,onOpenProspect:n,onAddProspect:r}){var u;const a=acr(s),[i,l]=j.useState("all"),o=i==="all"?a.priority:a.priority.filter(h=>h.tone===i),c=Math.max(1,...a.stages.map(h=>h.count)),d=Math.max(1,...a.sources.map(([,h])=>h));return a.isLoading?e.jsxs("div",{className:"space-y-4","aria-busy":"true",children:[e.jsx("div",{className:"grid gap-3 sm:grid-cols-2 xl:grid-cols-4",children:[0,1,2,3].map(h=>e.jsx(yn,{className:"h-28 rounded-md"},h))}),e.jsxs("div",{className:"grid gap-4 xl:grid-cols-[minmax(0,1.5fr)_minmax(300px,.8fr)]",children:[e.jsx(yn,{className:"h-[520px] rounded-md"}),e.jsx(yn,{className:"h-[520px] rounded-md"})]})]}):e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2 xl:grid-cols-4",children:[e.jsx(ihe,{label:"Active pipeline",value:a.prospects.length,detail:`${a.converted} converted · ${a.conversionRate}% rate`,icon:v0,tone:"bg-primary/10 text-primary",onClick:()=>t("pipeline-board")}),e.jsx(ihe,{label:"Follow-ups due",value:a.overdueCount+a.dueTodayCount,detail:`${a.overdueCount} overdue · ${a.dueTodayCount} today`,icon:Pq,tone:a.overdueCount?"bg-destructive/10 text-destructive":"bg-amber-500/10 text-amber-700",onClick:()=>t("pipeline-follow-ups")}),e.jsx(ihe,{label:"Campaign engagement",value:`${a.campaignOpenRate}%`,detail:`${a.campaignSent} sent · ${a.activeAssignments} enrolled`,icon:Gq,tone:"bg-emerald-500/10 text-emerald-700",onClick:()=>t("campaigns-manager")}),e.jsx(ihe,{label:"Current goal",value:a.currentGoal?`${a.goalCurrent}/${a.currentGoal.target_count}`:"—",detail:((u=a.currentGoal)==null?void 0:u.title)||"No active goal set",icon:rh,tone:"bg-recruit-gold/15 text-recruit-navy",onClick:()=>t("reporting-goals")})]}),e.jsxs("div",{className:"grid gap-4 xl:grid-cols-[minmax(0,1.55fr)_minmax(310px,.75fr)]",children:[e.jsxs("section",{className:"overflow-hidden rounded-md border bg-card shadow-xs",children:[e.jsxs("header",{className:"flex flex-col gap-3 border-b p-4 sm:flex-row sm:items-center sm:justify-between",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"font-['Outfit'] text-base font-semibold",children:"Needs attention"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"The next recruiting moves with the most urgency"})]}),e.jsx("div",{className:"flex flex-wrap gap-1 rounded-md bg-muted/50 p-1",children:["all","overdue","today","stalled"].map(h=>e.jsx($,{size:"sm",variant:i===h?"default":"ghost",className:"h-7 px-2.5 text-xs capitalize",onClick:()=>l(h),children:h},h))})]}),e.jsxs("div",{className:"divide-y",children:[o.length===0&&e.jsxs("div",{className:"px-4 py-12 text-center",children:[e.jsx(qr,{className:"mx-auto mb-2 h-7 w-7 text-emerald-600"}),e.jsx("p",{className:"text-sm font-medium",children:"Your priority queue is clear."}),e.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:"Add a prospect or review the full pipeline for your next move."})]}),o.slice(0,8).map(h=>{const m=`${h.prospect.first_name} ${h.prospect.last_name||""}`.trim();return e.jsxs("button",{type:"button",onClick:()=>n(h.prospect),className:"group flex w-full items-center gap-3 px-4 py-3 text-left transition-colors hover:bg-muted/30 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring",children:[e.jsx(Oa,{className:"h-9 w-9",children:e.jsx(za,{className:"bg-primary/10 text-xs font-semibold text-primary",children:icr(m)})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("p",{className:"truncate text-sm font-semibold",children:m}),e.jsx(Be,{className:Pt("border-0 text-[10px]",h.tone==="overdue"?"bg-destructive/10 text-destructive":h.tone==="today"?"bg-amber-500/10 text-amber-700":"bg-muted text-muted-foreground"),children:h.tone==="stalled"?"Stalled":h.tone==="today"?"Due today":"Overdue"})]}),e.jsxs("p",{className:"truncate text-xs text-muted-foreground",children:[h.title," · ",h.prospect.current_brokerage||h.detail]})]}),e.jsx(ei,{className:"h-4 w-4 shrink-0 text-muted-foreground transition-transform group-hover:translate-x-0.5 group-hover:text-primary"})]},h.id)})]}),e.jsxs("footer",{className:"flex flex-wrap items-center justify-between gap-2 border-t bg-muted/10 px-4 py-3",children:[e.jsxs($,{variant:"ghost",size:"sm",onClick:()=>t("pipeline-follow-ups"),children:["View all follow-ups ",e.jsx(ei,{className:"ml-1.5 h-3.5 w-3.5"})]}),e.jsxs($,{size:"sm",onClick:r,children:[e.jsx(sc,{className:"mr-1.5 h-3.5 w-3.5"}),"Add prospect"]})]})]}),e.jsxs("section",{className:"rounded-md border bg-card p-4 shadow-xs",children:[e.jsxs("div",{className:"mb-4 flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"font-['Outfit'] text-base font-semibold",children:"Goal pace"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Progress toward the current target"})]}),e.jsxs("span",{className:"font-['Outfit'] text-xl font-bold text-primary",children:[a.goalPercent,"%"]})]}),e.jsx(Yi,{value:a.goalPercent,className:"h-2.5"}),e.jsxs("div",{className:"mt-5 border-t pt-4",children:[e.jsxs("div",{className:"mb-3 flex items-center justify-between",children:[e.jsx("h3",{className:"font-['Outfit'] text-sm font-semibold",children:"Recruiter accountability"}),e.jsx($,{variant:"ghost",size:"sm",className:"h-7 text-xs",onClick:()=>t("reporting-activity"),children:"Full activity"})]}),e.jsxs("div",{className:"space-y-3",children:[a.recruiters.slice(0,5).map((h,m)=>e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("span",{className:"flex h-7 w-7 items-center justify-center rounded-full bg-muted text-xs font-bold",children:m+1}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"truncate text-sm font-medium",children:h.name}),e.jsxs("p",{className:"text-[11px] text-muted-foreground",children:["Last activity ",ocr(h.lastActivityAt)]})]}),e.jsxs("div",{className:"text-right",children:[e.jsx("p",{className:"font-['Outfit'] text-base font-bold",children:h.activities30d}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"30d moves"})]})]},h.id)),!a.recruiters.length&&e.jsx("p",{className:"py-5 text-center text-sm text-muted-foreground",children:"Recruiter activity will appear here."})]})]})]})]}),e.jsxs("div",{className:"grid gap-4 lg:grid-cols-2",children:[e.jsxs(Ne,{className:"rounded-md p-4 shadow-xs",children:[e.jsxs("div",{className:"mb-4 flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"font-['Outfit'] text-base font-semibold",children:"Pipeline momentum"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Volume and stalled prospects by stage"})]}),e.jsx($,{variant:"ghost",size:"sm",onClick:()=>t("pipeline-board"),children:"Open board"})]}),e.jsxs("div",{className:"space-y-3",children:[a.stages.map(h=>e.jsxs("div",{children:[e.jsxs("div",{className:"mb-1 flex items-center justify-between text-xs",children:[e.jsxs("span",{className:"flex min-w-0 items-center gap-2 font-medium",children:[e.jsx("span",{className:"h-2.5 w-2.5 shrink-0 rounded-full",style:{backgroundColor:h.color}}),e.jsx("span",{className:"truncate",children:h.name}),h.stalled>0&&e.jsxs("span",{className:"text-amber-700",children:[h.stalled," stalled"]})]}),e.jsx("span",{className:"font-bold",children:h.count})]}),e.jsx("div",{className:"h-2 overflow-hidden rounded-full bg-muted",children:e.jsx("div",{className:"h-full rounded-full bg-primary transition-[width] motion-reduce:transition-none",style:{width:`${Math.max(h.count?5:0,h.count/c*100)}%`}})})]},h.id)),!a.stages.length&&e.jsx("p",{className:"py-8 text-center text-sm text-muted-foreground",children:"Set up pipeline stages to see momentum."})]})]}),e.jsxs(Ne,{className:"rounded-md p-4 shadow-xs",children:[e.jsxs("div",{className:"mb-4 flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"font-['Outfit'] text-base font-semibold",children:"Source intelligence"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Where recruiting relationships originate"})]}),e.jsxs("span",{className:"flex items-center gap-1 text-xs font-semibold text-primary",children:[e.jsx(Yl,{className:"h-3.5 w-3.5"}),a.conversionRate,"% conversion"]})]}),e.jsxs("div",{className:"space-y-3",children:[a.sources.map(([h,m])=>e.jsxs("div",{className:"grid grid-cols-[minmax(100px,1fr)_2fr_32px] items-center gap-3",children:[e.jsx("span",{className:"truncate text-xs font-medium capitalize",children:h}),e.jsx("div",{className:"h-2 overflow-hidden rounded-full bg-muted",children:e.jsx("div",{className:"h-full rounded-full bg-recruit-gold",style:{width:`${Math.max(6,m/d*100)}%`}})}),e.jsx("span",{className:"text-right text-xs font-bold",children:m})]},h)),!a.sources.length&&e.jsx("p",{className:"py-8 text-center text-sm text-muted-foreground",children:"Source data will appear as prospects are added."})]}),e.jsxs($,{variant:"outline",size:"sm",className:"mt-5 w-full",onClick:()=>t("reporting-metrics"),children:[e.jsx(Wl,{className:"mr-1.5 h-3.5 w-3.5"}),"Open recruiting analytics"]})]})]})]})}function ccr({brokerageId:s}){const[t,n]=j.useState(""),[r,a]=j.useState("all"),{data:i,isLoading:l}=tt({queryKey:["recruit-sent-emails",s],queryFn:async()=>{var y;const{data:d,error:u}=await q.from("recruit_prospects").select("id, first_name, last_name, email").eq("brokerage_id",s);if(u)throw u;const h=new Map((d||[]).map(v=>[v.id,v]));if(Array.from(h.keys()).length===0)return[];const{data:f}=await q.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:g}=await q.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}),x=[];for(const v of f||[]){const b=h.get(v.prospect_id);b&&x.push({id:`v-${v.id}`,kind:"video",prospect_id:v.prospect_id,prospect_name:`${b.first_name||""} ${b.last_name||""}`.trim()||"—",prospect_email:b.email,subject:(y=v.video)!=null&&y.title?`Video: ${v.video.title}`:"Recruiting Video",status:v.cta_clicked_at?"clicked":v.first_viewed_at?"viewed":"sent",sent_at:v.sent_at,opened_at:v.first_viewed_at,clicked_at:v.cta_clicked_at,view_count:v.view_count,share_token:v.share_token})}for(const v of g||[]){if(!v.sent_at)continue;const b=h.get(v.prospect_id);b&&x.push({id:`c-${v.id}`,kind:"campaign",prospect_id:v.prospect_id,prospect_name:`${b.first_name||""} ${b.last_name||""}`.trim()||"—",prospect_email:b.email,subject:v.subject||`Email #${v.email_number}`,status:v.status||"sent",sent_at:v.sent_at,opened_at:v.opened_at,clicked_at:v.clicked_at,error:v.error_message})}return x.sort((v,b)=>new Date(b.sent_at).getTime()-new Date(v.sent_at).getTime()),x}}),o=j.useMemo(()=>{const d=i||[];return{total:d.length,videos:d.filter(u=>u.kind==="video").length,campaigns:d.filter(u=>u.kind==="campaign").length,opened:d.filter(u=>u.opened_at).length,clicked:d.filter(u=>u.clicked_at).length}},[i]),c=j.useMemo(()=>(i||[]).filter(u=>{if(r!=="all"&&u.kind!==r)return!1;if(!t)return!0;const h=t.toLowerCase();return u.prospect_name.toLowerCase().includes(h)||(u.prospect_email||"").toLowerCase().includes(h)||u.subject.toLowerCase().includes(h)}),[i,t,r]);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:Yr,color:"text-primary"},{label:"Video Emails",value:o.videos,icon:ua,color:"text-blue-500"},{label:"Campaign Emails",value:o.campaigns,icon:mn,color:"text-violet-500"},{label:"Opened / Viewed",value:o.opened,icon:Ca,color:"text-amber-500"},{label:"Clicked",value:o.clicked,icon:Lm,color:"text-emerald-500"}].map(d=>e.jsx(Ne,{children:e.jsxs(Ie,{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(Ne,{children:[e.jsx(Ct,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center justify-between gap-2 flex-wrap",children:[e.jsx(At,{className:"text-lg",children:"Sent Emails"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ha,{value:r,onValueChange:d=>a(d),children:e.jsxs(ma,{className:"h-8",children:[e.jsx(Zt,{value:"all",className:"text-xs h-7",children:"All"}),e.jsx(Zt,{value:"video",className:"text-xs h-7",children:"Video"}),e.jsx(Zt,{value:"campaign",className:"text-xs h-7",children:"Campaign"})]})}),e.jsxs("div",{className:"relative w-56",children:[e.jsx(Kr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(pe,{placeholder:"Search recruit, subject...",value:t,onChange:d=>n(d.target.value),className:"pl-9 h-9"})]})]})]})}),e.jsx(Ie,{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(mn,{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(Be,{variant:"outline",className:"gap-1",children:[e.jsx(ua,{className:"h-3 w-3"}),"Video"]}):e.jsxs(Be,{variant:"outline",className:"gap-1",children:[e.jsx(mn,{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(Be,{variant:"destructive",className:"gap-1",children:[e.jsx(ll,{className:"h-3 w-3"}),d.status]}):d.clicked_at?e.jsxs(Be,{className:"bg-emerald-500/15 text-emerald-700 border-emerald-200 gap-1",children:[e.jsx(Lm,{className:"h-3 w-3"}),"Clicked"]}):d.opened_at?e.jsxs(Be,{className:"bg-blue-500/15 text-blue-700 border-blue-200 gap-1",children:[e.jsx(Ca,{className:"h-3 w-3"}),"Opened"]}):e.jsxs(Be,{variant:"secondary",className:"gap-1",children:[e.jsx(Yr,{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:[en(new Date(d.sent_at),"MMM d, yyyy"),e.jsx("div",{className:"text-[10px]",children:en(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(Ca,{className:"h-3 w-3"}),d.view_count]}),d.kind==="video"&&d.share_token&&e.jsx($,{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(kr,{className:"h-3.5 w-3.5"})})]})})]},d.id))})]})})})]})]})}const NEt={pipeline:[{value:"pipeline-board",label:"Board",icon:Qf},{value:"pipeline-table",label:"Table",icon:cV},{value:"pipeline-contacts",label:"Contacts",icon:Zn},{value:"pipeline-follow-ups",label:"Follow-ups",icon:zg},{value:"pipeline-referrals",label:"Referrals",icon:fV}],outreach:[{value:"outreach-video",label:"Video outreach",icon:ua},{value:"outreach-templates",label:"Email templates",icon:Wq},{value:"outreach-sent",label:"Sent emails",icon:mn}],campaigns:[{value:"campaigns-manager",label:"Campaigns",icon:mn},{value:"campaigns-assignments",label:"Drip assignments",icon:Yr}],assets:[{value:"assets-landing",label:"Landing page",icon:IN},{value:"assets-interest",label:"Interest form",icon:zg}],reporting:[{value:"reporting-metrics",label:"Analytics",icon:Wl},{value:"reporting-goals",label:"Goals",icon:rh},{value:"reporting-activity",label:"Recruiter activity",icon:Zn}],settings:[{value:"settings-email",label:"Email settings",icon:Sd},{value:"settings-stages",label:"Pipeline stages",icon:JI}]},Gos=[{value:"command",label:"Command"},{value:"pipeline",label:"Pipeline"},{value:"outreach",label:"Outreach"},{value:"campaigns",label:"Campaigns"},{value:"assets",label:"Growth assets"},{value:"reporting",label:"Reporting"},{value:"settings",label:"Settings"}],dcr=s=>{var t;return((t=Gos.find(n=>s===n.value||s.startsWith(`${n.value}-`)))==null?void 0:t.value)??"command"};function ucr(){var I;const{managedBrokerages:s,selectedBrokerageId:t,setSelectedBrokerageId:n}=vs(),r=t||((I=s[0])==null?void 0:I.id)||"",a=S9(r||null),[i,l]=j.useState("command"),[o,c]=j.useState(!1),[d,u]=j.useState(!1),[h,m]=j.useState(null),[f,g]=j.useState(!1),[x,y]=j.useState(""),v=dcr(i),b=s.find(P=>P.id===r),w=j.useMemo(()=>{const P=x.trim().toLowerCase();return P?a.prospects.filter(R=>`${R.first_name} ${R.last_name||""} ${R.current_brokerage||""} ${R.email||""}`.toLowerCase().includes(P)).slice(0,6):[]},[a.prospects,x]),S=P=>l(P),C=P=>{m(P),g(!0),y("")},E=P=>l(P==="command"?"command":NEt[P][0].value);return s.length===0?e.jsx(Vs,{title:"Recruiting",description:"Brokerage recruiting command center",children:e.jsxs("div",{className:"py-16 text-center text-muted-foreground",children:[e.jsx(ji,{className:"mx-auto mb-4 h-12 w-12 opacity-50"}),e.jsx("p",{children:"No brokerages assigned to you. Contact an admin for access."})]})}):e.jsx(Vs,{title:"Recruiting",description:"Brokerage recruiting command center",children:e.jsxs("div",{className:"recruiting-console -m-4 min-h-[calc(100vh-72px)] bg-background font-['Figtree'] sm:-m-6 lg:-m-8",children:[e.jsxs("header",{className:"bg-secondary px-4 py-4 text-secondary-foreground sm:px-6 lg:px-8",children:[e.jsxs("div",{className:"flex flex-col gap-4 xl:flex-row xl:items-center xl:justify-between",children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-4",children:[e.jsx("span",{className:"flex h-10 w-10 shrink-0 items-center justify-center rounded-md bg-primary text-primary-foreground",children:e.jsx(fV,{className:"h-5 w-5"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("h1",{className:"truncate text-xl font-bold",children:"Recruiting Command"}),e.jsxs("p",{className:"truncate text-xs text-secondary-foreground/70",children:[(b==null?void 0:b.name)||"Brokerage"," · Pipeline, outreach and growth"]})]})]}),e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:items-center",children:[e.jsxs("div",{className:"relative min-w-0 sm:w-72",children:[e.jsx(Kr,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-secondary-foreground/60"}),e.jsx(pe,{value:x,onChange:P=>y(P.target.value),placeholder:"Search prospects…",className:"border-secondary-foreground/15 bg-primary/40 pl-9 text-secondary-foreground placeholder:text-secondary-foreground/55 focus-visible:ring-recruit-gold"}),x.trim()&&e.jsxs("div",{className:"absolute left-0 right-0 top-[calc(100%+6px)] z-40 overflow-hidden rounded-md border bg-popover text-popover-foreground shadow-lg",children:[w.map(P=>e.jsxs("button",{type:"button",className:"flex w-full items-center justify-between gap-3 border-b px-3 py-2.5 text-left text-sm last:border-0 hover:bg-accent",onClick:()=>C(P),children:[e.jsxs("span",{className:"truncate font-medium",children:[P.first_name," ",P.last_name]}),e.jsx("span",{className:"truncate text-xs text-muted-foreground",children:P.current_brokerage||"Prospect"})]},P.id)),w.length===0&&e.jsx("p",{className:"px-3 py-4 text-sm text-muted-foreground",children:"No matching prospects."})]})]}),e.jsxs(Uu,{children:[e.jsx(qu,{asChild:!0,children:e.jsxs($,{className:"bg-recruit-gold text-recruit-navy hover:bg-recruit-gold/90",children:[e.jsx(dn,{className:"mr-1.5 h-4 w-4"}),"New prospect ",e.jsx(Tl,{className:"ml-2 h-3.5 w-3.5"})]})}),e.jsxs(Eu,{align:"end",children:[e.jsxs(ja,{onSelect:()=>c(!0),children:[e.jsx(dn,{className:"mr-2 h-4 w-4"}),"Add prospect"]}),e.jsxs(ja,{onSelect:()=>u(!0),children:[e.jsx(ni,{className:"mr-2 h-4 w-4"}),"Import CSV"]})]})]})]})]}),e.jsx("nav",{className:"-mx-4 mt-4 overflow-x-auto px-4 sm:-mx-6 sm:px-6 lg:-mx-8 lg:px-8","aria-label":"Recruiting sections",children:e.jsx("div",{className:"flex min-w-max items-center gap-1",children:Gos.map(P=>e.jsx($,{variant:"ghost",size:"sm",onClick:()=>E(P.value),className:Pt("h-9 rounded-none border-b-2 px-3 text-secondary-foreground/70 hover:bg-secondary-foreground/5 hover:text-secondary-foreground",v===P.value?"border-recruit-gold text-recruit-gold":"border-transparent"),children:P.label},P.value))})})]}),e.jsxs("div",{className:"px-4 py-5 sm:px-6 lg:px-8",children:[s.length>1&&e.jsxs("div",{className:"mb-4 flex items-center gap-3",children:[e.jsx("span",{className:"text-sm text-muted-foreground",children:"Managing:"}),e.jsxs(ms,{value:r,onValueChange:n,children:[e.jsxs(us,{className:"w-[280px] bg-card",children:[e.jsx(ji,{className:"mr-2 h-4 w-4"}),e.jsx(fs,{})]}),e.jsx(hs,{children:s.map(P=>e.jsx(Ge,{value:P.id,children:P.name},P.id))})]})]}),v!=="command"&&e.jsx("div",{className:"mb-5 overflow-x-auto pb-1",children:e.jsx(ha,{value:i,onValueChange:l,children:e.jsx(ma,{className:"h-auto min-w-max rounded-md border bg-card p-1",children:NEt[v].map(P=>{const R=P.icon;return e.jsxs(Zt,{value:P.value,className:"gap-1.5",children:[e.jsx(R,{className:"h-3.5 w-3.5"}),P.label]},P.value)})})})}),v==="command"&&r&&e.jsx(lcr,{brokerageId:r,onNavigate:S,onOpenProspect:C,onAddProspect:()=>c(!0)}),i==="pipeline-board"&&e.jsx(Tos,{brokerageId:r}),(i==="pipeline-table"||i==="pipeline-contacts")&&e.jsx(uQe,{brokerageId:r}),i==="pipeline-follow-ups"&&e.jsx(Dos,{brokerageId:r}),i==="pipeline-referrals"&&e.jsx(Los,{brokerageId:r}),i==="outreach-video"&&e.jsx(zos,{brokerageId:r}),i==="outreach-templates"&&e.jsx(Pos,{brokerageId:r}),i==="outreach-sent"&&e.jsx(ccr,{brokerageId:r}),i==="campaigns-manager"&&e.jsx(qos,{brokerageId:r}),i==="campaigns-assignments"&&e.jsx(Vos,{brokerageId:r}),i==="assets-landing"&&e.jsx(Fos,{brokerageId:r}),i==="assets-interest"&&e.jsx(Ros,{brokerageId:r}),i==="reporting-metrics"&&e.jsx(Mos,{brokerageId:r}),i==="reporting-goals"&&e.jsx(Bos,{brokerageId:r}),i==="reporting-activity"&&e.jsx(Ios,{brokerageId:r}),i==="settings-email"&&e.jsxs("div",{className:"max-w-3xl rounded-md border bg-card p-5",children:[e.jsxs("div",{className:"mb-5",children:[e.jsx("h2",{className:"font-['Outfit'] text-lg font-semibold",children:"Email settings"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Configure sender identity, merge fields and brokerage location."})]}),e.jsx(Wlt,{brokerageId:r})]}),i==="settings-stages"&&e.jsx("div",{className:"max-w-3xl rounded-md border bg-card p-5",children:e.jsx(Hos,{brokerageId:r})})]}),e.jsx(qlt,{open:o,onOpenChange:c,stages:a.stages,onSubmit:P=>a.addProspect.mutate(P),isSubmitting:a.addProspect.isPending}),e.jsx(Glt,{open:d,onOpenChange:u,brokerageId:r,stages:a.stages}),e.jsx(Hlt,{prospect:h,stages:a.stages,brokerageId:r,open:f,onOpenChange:g,onUpdate:P=>{a.updateProspect.mutate(P),m(R=>R?{...R,...P}:null)},onDelete:P=>a.deleteProspect.mutate(P)})]})})}const hcr=[{key:"license_number",label:"License #"},{key:"license_state",label:"License state"},{key:"license_expiration",label:"License expiration",type:"date"},{key:"eo_carrier",label:"E&O carrier"},{key:"eo_policy_number",label:"E&O policy #"},{key:"eo_expiration",label:"E&O expiration",type:"date"},{key:"first_year_licensed",label:"First year licensed",type:"number"},{key:"anniversary_date",label:"Anniversary",type:"date"},{key:"birthday",label:"Birthday",type:"date"},{key:"mobile_phone",label:"Mobile"},{key:"personal_email",label:"Personal email"},{key:"address_line1",label:"Address"},{key:"city",label:"City"},{key:"state",label:"State"},{key:"postal_code",label:"Zip"},{key:"specialization",label:"Specialization"},{key:"prior_firm",label:"Prior firm"},{key:"designations",label:"Designations"},{key:"goal_amount",label:"Production goal",type:"number"},{key:"internal_role",label:"Role"}],mcr=({brokerageId:s,agentUserId:t,readOnly:n})=>{const{toast:r}=Bi(),{data:a}=tDn(s,t),{saveRecord:i}=nDe(s),[l,o]=j.useState({brokerage_id:s,agent_user_id:t});return j.useEffect(()=>{o({brokerage_id:s,agent_user_id:t,...a||{}})},[a,s,t]),e.jsxs("div",{className:"space-y-5",children:[e.jsx("div",{className:"grid gap-4 sm:grid-cols-2 xl:grid-cols-3",children:hcr.map(c=>e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{className:"text-xs uppercase tracking-wide text-muted-foreground",children:c.label}),e.jsx(pe,{type:c.type||"text",disabled:n,value:l[c.key]??"",onChange:d=>o({...l,[c.key]:c.type==="number"?d.target.value===""?null:Number(d.target.value):d.target.value||null})})]},String(c.key)))}),!n&&e.jsxs($,{onClick:async()=>{await i.mutateAsync(l),r({title:"Record saved"})},children:[e.jsx(tl,{className:"mr-2 h-4 w-4"})," Save record"]})]})},fcr=({brokerageId:s,agentUserId:t})=>{const{data:n=[]}=sDn(s,t),{data:r=[]}=HXt(s,t),{addNote:a,deleteNote:i}=nDe(s),[l,o]=j.useState("");return e.jsxs("div",{className:"grid gap-6 xl:grid-cols-2",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(pc,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("h3",{className:"font-medium",children:"Private notes"}),e.jsx(Be,{variant:"secondary",children:"Managers only"})]}),e.jsx(Rs,{rows:3,value:l,onChange:c=>o(c.target.value),placeholder:"Add a note about this agent…"}),e.jsx($,{size:"sm",disabled:!l.trim(),onClick:async()=>{await a.mutateAsync({agentUserId:t,body:l.trim()}),o("")},children:"Add note"}),e.jsxs("div",{className:"space-y-2",children:[n.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"No notes yet."}),n.map(c=>e.jsxs("div",{className:"rounded-md border bg-card p-3",children:[e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsx("p",{className:"whitespace-pre-wrap text-sm",children:c.body}),e.jsx($,{size:"icon",variant:"ghost",className:"text-destructive",onClick:()=>i.mutate({id:c.id,agentUserId:t}),"aria-label":"Delete note",children:e.jsx(Wn,{className:"h-4 w-4"})})]}),e.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:new Date(c.created_at).toLocaleString("en-US",{timeZone:"America/New_York"})})]},c.id))]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(af,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("h3",{className:"font-medium",children:"Activity"})]}),e.jsxs("div",{className:"space-y-2",children:[r.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"Nothing yet."}),r.map(c=>e.jsxs("div",{className:"relative border-l-2 border-primary/40 bg-muted/30 px-4 py-2.5",children:[e.jsx("p",{className:"text-sm",children:c.description}),e.jsx("p",{className:"text-xs text-muted-foreground",children:new Date(c.created_at).toLocaleString("en-US",{timeZone:"America/New_York"})})]},c.id))]})]})]})},kEt=s=>s.split(/\s+/).filter(Boolean).slice(0,2).map(t=>t[0]).join("").toUpperCase(),Wos=s=>s?s.split(/[-/T]/).slice(0,3).join("/"):null,pcr=s=>s.assignment?s.total>0&&s.done===s.total?{label:"Completed",className:"bg-emerald-500/10 text-emerald-700"}:s.overdue>0?{label:"Overdue",className:"bg-destructive/10 text-destructive"}:s.needsReview>0?{label:"Waiting on review",className:"bg-amber-500/10 text-amber-700"}:{label:"In progress",className:"bg-primary/10 text-primary"}:{label:"Not started",className:"bg-muted/70 text-muted-foreground"},ohe=({label:s,value:t,icon:n,active:r,tone:a,onClick:i})=>e.jsxs("button",{type:"button",onClick:i,"aria-pressed":r,className:Pt("flex min-h-[92px] w-full items-center justify-between rounded-md border bg-card p-4 text-left shadow-xs transition-colors hover:border-primary/40 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",r&&"border-primary bg-primary/5 ring-1 ring-primary/20"),children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-[11px] font-semibold uppercase text-muted-foreground",children:s}),e.jsx("p",{className:"mt-1 font-['Outfit'] text-3xl font-bold text-foreground",children:t})]}),e.jsx("span",{className:Pt("flex h-10 w-10 items-center justify-center rounded-full",a),children:e.jsx(n,{className:"h-5 w-5"})})]}),gcr=({brokerageId:s,agentUserId:t})=>{const{data:n=[]}=HXt(s,t);return e.jsxs("aside",{className:"rounded-md border bg-card p-4",children:[e.jsxs("div",{className:"mb-4 flex items-center justify-between",children:[e.jsx("h3",{className:"font-['Outfit'] text-sm font-semibold",children:"Recent activity"}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"Latest updates"})]}),e.jsxs("div",{className:"space-y-4",children:[n.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"No activity yet."}),n.slice(0,6).map((r,a)=>e.jsxs("div",{className:"relative flex gap-3",children:[e.jsx("span",{className:Pt("mt-1.5 h-2.5 w-2.5 shrink-0 rounded-full ring-4 ring-background",a===0?"bg-primary":"bg-muted-foreground/40")}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-sm leading-snug",children:r.description}),e.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:Wos(r.created_at)})]})]},r.id))]})]})},xcr=({brokerageId:s})=>{var O,U;const{toast:t}=Bi(),{data:n=[],isLoading:r}=qXt(s),{data:a=[]}=UXt(s),{assignTemplate:i,removeAssignment:l}=nDe(s),[o,c]=j.useState(""),[d,u]=j.useState("all"),[h,m]=j.useState(null),[f,g]=j.useState(!1),[x,y]=j.useState(null),[v,b]=j.useState(""),w=j.useMemo(()=>{const W=o.trim().toLowerCase();return n.filter(V=>{if(W&&!V.name.toLowerCase().includes(W)&&!V.email.toLowerCase().includes(W))return!1;const G=!!V.assignment&&V.total>0&&V.done===V.total;return d==="not_started"?!V.assignment:d==="in_progress"?!!V.assignment&&!G:d==="finished"?G:d==="review"?V.needsReview>0:d==="overdue"?V.overdue>0:!0})},[n,o,d]);j.useEffect(()=>{var W;h&&w.some(V=>V.agentId===h)||m(((W=w[0])==null?void 0:W.agentId)??null)},[w,h]);const S=n.find(W=>W.agentId===h)||null,{data:C}=VXt((O=S==null?void 0:S.assignment)==null?void 0:O.id),E=(C==null?void 0:C.steps)||[],I=E.filter(mE).length,P=E.length?Math.round(I/E.length*100):0,R=j.useMemo(()=>{const W=n.filter(V=>V.assignment);return{inProgress:W.filter(V=>!(V.total>0&&V.done===V.total)).length,finished:W.filter(V=>V.total>0&&V.done===V.total).length,needsReview:n.reduce((V,G)=>V+G.needsReview,0),overdue:n.reduce((V,G)=>V+G.overdue,0)}},[n]),D=W=>{m(W),g(!0)};return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2 xl:grid-cols-4",children:[e.jsx(ohe,{label:"In progress",value:R.inProgress,icon:v0,active:d==="in_progress",tone:"bg-primary/10 text-primary",onClick:()=>u(d==="in_progress"?"all":"in_progress")}),e.jsx(ohe,{label:"Finished",value:R.finished,icon:qr,active:d==="finished",tone:"bg-emerald-500/10 text-emerald-700",onClick:()=>u(d==="finished"?"all":"finished")}),e.jsx(ohe,{label:"Waiting on review",value:R.needsReview,icon:Pq,active:d==="review",tone:"bg-amber-500/10 text-amber-700",onClick:()=>u(d==="review"?"all":"review")}),e.jsx(ohe,{label:"Overdue steps",value:R.overdue,icon:wl,active:d==="overdue",tone:"bg-destructive/10 text-destructive",onClick:()=>u(d==="overdue"?"all":"overdue")})]}),e.jsxs("div",{className:"grid min-h-[620px] overflow-hidden rounded-md border bg-card shadow-sm lg:grid-cols-[310px_minmax(0,1fr)] xl:grid-cols-[340px_minmax(0,1fr)]",children:[e.jsxs("section",{className:Pt("border-r bg-muted/10",f&&"hidden lg:block"),children:[e.jsxs("header",{className:"border-b p-4",children:[e.jsx("h2",{className:"font-['Outfit'] text-base font-semibold",children:"Agents"}),e.jsx("p",{className:"mb-3 text-xs text-muted-foreground",children:"Track each agent’s onboarding"}),e.jsxs("div",{className:"relative mb-2",children:[e.jsx(Kr,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(pe,{className:"h-9 bg-background pl-9",placeholder:"Search agents",value:o,onChange:W=>c(W.target.value)})]}),e.jsxs(ms,{value:d,onValueChange:W=>u(W),children:[e.jsx(us,{className:"h-9 bg-background",children:e.jsx(fs,{})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"all",children:"All agents"}),e.jsx(Ge,{value:"not_started",children:"Not started"}),e.jsx(Ge,{value:"in_progress",children:"In progress"}),e.jsx(Ge,{value:"finished",children:"Finished"}),e.jsx(Ge,{value:"review",children:"Waiting on review"}),e.jsx(Ge,{value:"overdue",children:"Overdue"})]})]})]}),e.jsxs("div",{className:"max-h-[650px] overflow-y-auto p-2",children:[r&&e.jsx("p",{className:"p-3 text-sm text-muted-foreground",children:"Loading…"}),!r&&w.length===0&&e.jsx("p",{className:"p-3 text-sm text-muted-foreground",children:"No agents match."}),w.map(W=>{const V=W.total?Math.round(W.done/W.total*100):0,G=pcr(W);return e.jsxs("button",{type:"button",onClick:()=>D(W.agentId),className:Pt("mb-1 flex w-full items-center gap-3 rounded-md border border-transparent p-2.5 text-left transition-colors hover:bg-muted/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",W.agentId===h&&"border-primary/30 bg-primary/5"),children:[e.jsxs(Oa,{className:"h-10 w-10 border-2 border-background shadow-xs",children:[e.jsx(Li,{src:W.avatarUrl||void 0,alt:W.name,className:"object-cover"}),e.jsx(za,{className:"bg-primary/10 text-xs font-semibold text-primary",children:kEt(W.name)})]}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"truncate text-sm font-semibold",children:W.name}),e.jsx("p",{className:"truncate text-xs text-muted-foreground",children:W.assignment?`${V}% complete`:"No flow assigned"}),e.jsx(Be,{className:Pt("mt-1 border-0 px-1.5 py-0 text-[10px] font-medium",G.className),children:G.label})]}),W.needsReview>0&&e.jsx("span",{className:"flex h-6 min-w-6 items-center justify-center rounded-full bg-amber-500/10 px-1.5 text-[10px] font-bold text-amber-700",children:W.needsReview})]},W.agentId)})]})]}),e.jsx("section",{className:Pt("min-w-0",!f&&"hidden lg:block"),children:S?e.jsxs(e.Fragment,{children:[e.jsxs("header",{className:"border-b bg-card p-4 md:p-5",children:[e.jsxs($,{variant:"ghost",size:"sm",className:"mb-3 -ml-2 lg:hidden",onClick:()=>g(!1),children:[e.jsx(qa,{className:"mr-2 h-4 w-4"}),"All agents"]}),e.jsxs("div",{className:"flex flex-col gap-4 xl:flex-row xl:items-start xl:justify-between",children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-3",children:[e.jsxs(Oa,{className:"h-14 w-14 border shadow-xs",children:[e.jsx(Li,{src:S.avatarUrl||void 0,alt:S.name,className:"object-cover"}),e.jsx(za,{className:"bg-primary text-base font-semibold text-primary-foreground",children:kEt(S.name)})]}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("h2",{className:"truncate font-['Outfit'] text-xl font-bold",children:S.name}),e.jsx("p",{className:"truncate text-sm text-muted-foreground",children:S.email}),e.jsxs("p",{className:"mt-0.5 text-xs text-muted-foreground",children:[((U=S.assignment)==null?void 0:U.template_name)||"No flow assigned",S.joinedAt?` · Joined ${Wos(S.joinedAt)}`:""]})]})]}),S.assignment?e.jsxs($,{variant:"outline",className:"text-destructive",onClick:async()=>{await l.mutateAsync(S.assignment),t({title:"Onboarding removed"})},children:[e.jsx(Wn,{className:"mr-2 h-4 w-4"}),"Remove checklist"]}):e.jsxs($,{onClick:()=>{var W,V;y(S),b(((W=a.find(G=>G.is_default))==null?void 0:W.id)||((V=a[0])==null?void 0:V.id)||"")},disabled:a.length===0,children:[e.jsx(Bu,{className:"mr-2 h-4 w-4"}),"Start onboarding"]})]}),S.assignment&&e.jsxs("div",{className:"mt-5",children:[e.jsxs("div",{className:"mb-2 flex items-center justify-between text-sm",children:[e.jsx("span",{className:"font-medium",children:"Onboarding progress"}),e.jsxs("span",{className:"font-['Outfit'] text-lg font-bold text-primary",children:[P,"%"]})]}),e.jsx(Yi,{value:P,className:"h-2.5 bg-muted"}),e.jsxs("p",{className:"mt-1.5 text-right text-xs text-muted-foreground",children:[I," of ",E.length," steps complete"]})]}),a.length===0&&!S.assignment&&e.jsxs("p",{className:"mt-3 flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(wl,{className:"h-4 w-4"}),"Build an onboarding flow first on the Flows tab."]})]}),e.jsx("div",{className:"p-4 md:p-5",children:e.jsxs(ha,{defaultValue:"checklist",className:"space-y-4",children:[e.jsx("div",{className:"overflow-x-auto pb-1",children:e.jsxs(ma,{className:"grid h-auto min-w-[500px] grid-cols-4 rounded-md border bg-muted/40 p-1",children:[e.jsx(Zt,{value:"checklist",children:"Checklist"}),e.jsx(Zt,{value:"record",children:"Record"}),e.jsx(Zt,{value:"notes",children:"Notes & activity"}),e.jsx(Zt,{value:"documents",children:"Documents"})]})}),e.jsx(Xt,{value:"checklist",children:S.assignment?e.jsxs("div",{className:"grid gap-4 xl:grid-cols-[minmax(0,1.6fr)_minmax(240px,.8fr)]",children:[e.jsx(NYe,{brokerageId:s,agentUserId:S.agentId,steps:E,documents:(C==null?void 0:C.documents)||[],mode:"manager"}),e.jsx(gcr,{brokerageId:s,agentUserId:S.agentId})]}):e.jsx("p",{className:"py-12 text-center text-sm text-muted-foreground",children:"No checklist assigned yet."})}),e.jsx(Xt,{value:"record",children:e.jsx(mcr,{brokerageId:s,agentUserId:S.agentId})}),e.jsx(Xt,{value:"notes",children:e.jsx(fcr,{brokerageId:s,agentUserId:S.agentId})}),e.jsx(Xt,{value:"documents",children:S.assignment?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"mb-4 flex items-center gap-2",children:[e.jsx(qz,{className:"h-4 w-4 text-primary"}),e.jsx("h3",{className:"font-['Outfit'] font-semibold",children:"Onboarding documents"})]}),e.jsx(NYe,{brokerageId:s,agentUserId:S.agentId,steps:E,documents:(C==null?void 0:C.documents)||[],mode:"manager",displayMode:"documents"})]}):e.jsx("p",{className:"py-12 text-center text-sm text-muted-foreground",children:"No documents yet."})})]})})]}):e.jsxs("div",{className:"flex min-h-[620px] flex-col items-center justify-center text-center",children:[e.jsx(JN,{className:"mb-3 h-10 w-10 text-muted-foreground"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Select an agent to see their onboarding."})]})})]}),e.jsx(zs,{open:!!x,onOpenChange:W=>!W&&y(null),children:e.jsxs(Os,{children:[e.jsxs(Us,{children:[e.jsx(Bs,{children:"Start onboarding"}),e.jsxs(Ir,{children:["Pick the flow for ",x==null?void 0:x.name,". Later flow edits will not change this checklist."]})]}),e.jsxs(ms,{value:v,onValueChange:b,children:[e.jsx(us,{children:e.jsx(fs,{placeholder:"Choose a flow"})}),e.jsx(hs,{children:a.map(W=>e.jsx(Ge,{value:W.id,children:W.name},W.id))})]}),e.jsxs(Ar,{children:[e.jsx($,{variant:"outline",onClick:()=>y(null),children:"Cancel"}),e.jsxs($,{disabled:!v||!x,onClick:async()=>{if(x)try{await i.mutateAsync({agentUserId:x.agentId,templateId:v}),t({title:"Onboarding started"}),y(null)}catch(W){t({title:"Could not start",description:W.message,variant:"destructive"})}},children:[e.jsx(lP,{className:"mr-2 h-4 w-4"}),"Start"]})]})]})})]})},ycr=s=>s==="document"?Jr:s==="form"?m_:Kj,vcr=({brokerageId:s})=>{var W,V;const{toast:t}=Bi(),{data:n=[],isLoading:r}=UXt(s),[a,i]=j.useState(null),l=a??((W=n[0])==null?void 0:W.id)??null,o=n.find(G=>G.id===l)||null,{data:c=[]}=JRn(l),{createTemplate:d,updateTemplate:u,deleteTemplate:h,upsertStep:m,deleteStep:f,reorderSteps:g}=nDn(s),{data:x=[]}=tt({queryKey:["brokerage-form-templates",s],queryFn:async()=>{const{data:G,error:Y}=await q.from("form_templates").select("id, name").eq("brokerage_id",s).eq("is_archived",!1).order("name");if(Y)throw Y;return G||[]}}),[y,v]=j.useState(!1),[b,w]=j.useState(""),[S,C]=j.useState(""),[E,I]=j.useState(!1),[P,R]=j.useState(null),D=()=>R({title:"",description:"",step_type:"document",assignee:"agent",due_days:null}),O=async()=>{var G;!l||!((G=P==null?void 0:P.title)!=null&&G.trim())||(await m.mutateAsync({...P.id?{id:P.id}:{},template_id:l,title:P.title.trim(),description:P.description||null,step_type:P.step_type||"document",assignee:P.assignee||"agent",form_template_id:P.step_type==="form"&&P.form_template_id||null,due_days:P.due_days??null,sort_order:P.sort_order??c.length}),I(!1),R(null),t({title:"Step saved"}))},U=async(G,Y)=>{const X=[...c],ae=G+Y;ae<0||ae>=X.length||([X[G],X[ae]]=[X[ae],X[G]],await g.mutateAsync({steps:X,templateId:l}))};return e.jsxs("div",{className:"grid min-h-[620px] overflow-hidden rounded-md border bg-card shadow-sm lg:grid-cols-[300px_minmax(0,1fr)]",children:[e.jsxs(Ne,{className:"rounded-none border-0 border-r shadow-none",children:[e.jsxs(Ct,{className:"pb-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(At,{className:"text-base",children:"Onboarding flows"}),e.jsx($,{size:"sm",variant:"outline",onClick:()=>v(!0),children:e.jsx(dn,{className:"h-4 w-4"})})]}),e.jsx(Gn,{children:"Reusable checklists for new agents"})]}),e.jsxs(Ie,{className:"space-y-2",children:[r&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"Loading…"}),!r&&n.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"No flows yet. Create your first one."}),n.map(G=>e.jsxs("button",{onClick:()=>i(G.id),className:`w-full rounded-md border p-3 text-left transition-colors ${G.id===l?"border-primary bg-primary/5":"hover:bg-muted/50"}`,children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("span",{className:"font-medium text-sm",children:G.name}),G.is_default&&e.jsxs(Be,{variant:"secondary",className:"gap-1",children:[e.jsx(Ja,{className:"h-3 w-3"})," Default"]})]}),G.description&&e.jsx("p",{className:"mt-1 line-clamp-2 text-xs text-muted-foreground",children:G.description})]},G.id))]})]}),e.jsx(Ne,{className:"rounded-none border-0 shadow-none",children:o?e.jsxs(e.Fragment,{children:[e.jsx(Ct,{children:e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx(At,{children:o.name}),e.jsx(Gn,{children:o.description||"No description"})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs($,{size:"sm",variant:"outline",onClick:()=>u.mutate({id:o.id,is_default:!o.is_default}),children:[e.jsx(Ja,{className:"mr-2 h-4 w-4"}),o.is_default?"Unset default":"Set default"]}),e.jsxs($,{size:"sm",variant:"outline",onClick:()=>{D(),I(!0)},children:[e.jsx(dn,{className:"mr-2 h-4 w-4"})," Add step"]}),e.jsx($,{size:"sm",variant:"ghost",className:"text-destructive",onClick:async()=>{await h.mutateAsync(o.id),i(null)},children:e.jsx(Wn,{className:"h-4 w-4"})})]})]})}),e.jsxs(Ie,{className:"space-y-2",children:[c.length===0&&e.jsx("p",{className:"py-8 text-center text-sm text-muted-foreground",children:"No steps yet — add documents, forms and tasks agents need to complete."}),c.map((G,Y)=>{const X=ycr(G.step_type);return e.jsxs("div",{className:"flex items-start gap-3 rounded-md border p-3 transition-colors hover:bg-muted/40",children:[e.jsx("div",{className:"mt-0.5 flex h-8 w-8 shrink-0 items-center justify-center rounded-md bg-primary/10 text-primary",children:e.jsx(X,{className:"h-4 w-4"})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("span",{className:"font-medium text-sm",children:G.title}),e.jsx(Be,{variant:"outline",className:"capitalize",children:G.step_type}),e.jsx(Be,{variant:"secondary",className:"capitalize",children:G.assignee}),G.due_days!=null&&e.jsxs("span",{className:"text-xs text-muted-foreground",children:["due in ",G.due_days,"d"]})]}),G.description&&e.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:G.description})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx($,{size:"icon",variant:"ghost",onClick:()=>U(Y,-1),"aria-label":"Move up",children:e.jsx(Zf,{className:"h-4 w-4"})}),e.jsx($,{size:"icon",variant:"ghost",onClick:()=>U(Y,1),"aria-label":"Move down",children:e.jsx(Dg,{className:"h-4 w-4"})}),e.jsx($,{size:"icon",variant:"ghost",onClick:()=>{R(G),I(!0)},"aria-label":"Edit step",children:e.jsx(gi,{className:"h-4 w-4"})}),e.jsx($,{size:"icon",variant:"ghost",className:"text-destructive",onClick:()=>f.mutate({id:G.id,templateId:o.id}),"aria-label":"Delete step",children:e.jsx(Wn,{className:"h-4 w-4"})})]})]},G.id)})]})]}):e.jsxs(Ie,{className:"flex flex-col items-center justify-center py-16 text-center",children:[e.jsx(zg,{className:"mb-3 h-10 w-10 text-muted-foreground"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Select or create an onboarding flow."})]})}),e.jsx(zs,{open:y,onOpenChange:v,children:e.jsxs(Os,{children:[e.jsxs(Us,{children:[e.jsx(Bs,{children:"New onboarding flow"}),e.jsx(Ir,{children:"Name it for the kind of agent it fits."})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Name"}),e.jsx(pe,{value:b,onChange:G=>w(G.target.value),placeholder:"New Agent Onboarding"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Description"}),e.jsx(Rs,{value:S,onChange:G=>C(G.target.value),rows:3})]})]}),e.jsxs(Ar,{children:[e.jsx($,{variant:"outline",onClick:()=>v(!1),children:"Cancel"}),e.jsx($,{disabled:!b.trim(),onClick:async()=>{const G=await d.mutateAsync({name:b.trim(),description:S});i(G.id),w(""),C(""),v(!1)},children:"Create"})]})]})}),e.jsx(zs,{open:E,onOpenChange:I,children:e.jsxs(Os,{children:[e.jsx(Us,{children:e.jsx(Bs,{children:P!=null&&P.id?"Edit step":"Add step"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Title"}),e.jsx(pe,{value:(P==null?void 0:P.title)||"",onChange:G=>R({...P,title:G.target.value}),placeholder:"Independent contractor agreement"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Instructions"}),e.jsx(Rs,{rows:2,value:(P==null?void 0:P.description)||"",onChange:G=>R({...P,description:G.target.value})})]}),e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Type"}),e.jsxs(ms,{value:(P==null?void 0:P.step_type)||"document",onValueChange:G=>R({...P,step_type:G}),children:[e.jsx(us,{children:e.jsx(fs,{})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"document",children:"Document upload"}),e.jsx(Ge,{value:"form",children:"Form from library"}),e.jsx(Ge,{value:"task",children:"Task / check off"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Who completes it"}),e.jsxs(ms,{value:(P==null?void 0:P.assignee)||"agent",onValueChange:G=>R({...P,assignee:G}),children:[e.jsx(us,{children:e.jsx(fs,{})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"agent",children:"Agent"}),e.jsx(Ge,{value:"manager",children:"Manager"})]})]})]})]}),(P==null?void 0:P.step_type)==="form"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Form"}),e.jsxs(ms,{value:(P==null?void 0:P.form_template_id)||"",onValueChange:G=>R({...P,form_template_id:G}),children:[e.jsx(us,{children:e.jsx(fs,{placeholder:"Choose a form"})}),e.jsx(hs,{children:x.map(G=>e.jsx(Ge,{value:G.id,children:G.name},G.id))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Due (days after start)"}),e.jsx(pe,{type:"number",min:0,value:(P==null?void 0:P.due_days)??"",onChange:G=>R({...P,due_days:G.target.value===""?null:Number(G.target.value)}),placeholder:"Optional"})]})]}),e.jsxs(Ar,{children:[e.jsx($,{variant:"outline",onClick:()=>I(!1),children:"Cancel"}),e.jsx($,{onClick:O,disabled:!((V=P==null?void 0:P.title)!=null&&V.trim()),children:"Save step"})]})]})})]})},bcr=()=>{const{user:s,isBrokerageManager:t,isAdmin:n,brokerageId:r,managedBrokerages:a,selectedBrokerageId:i,setSelectedBrokerageId:l}=vs(),o=Qn(),[c,d]=j.useState(!1),u=i||(a.length>0?a[0].id:r);return j.useEffect(()=>{if(s){if(!t&&!n){o("/dashboard");return}!i&&a.length>0&&l(a[0].id),d(!0)}},[s,t,n,o,a,i,l]),c?e.jsx(Vs,{title:"Agent Onboarding",description:"Build your onboarding flow, collect documents and keep notes",children:e.jsxs("div",{className:"onboarding-console space-y-5 font-['Figtree']",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(ms,{value:i||"",onValueChange:l,children:[e.jsxs(us,{className:"w-[280px]",children:[e.jsx(ji,{className:"mr-2 h-4 w-4"}),e.jsx(fs,{placeholder:"Select brokerage"})]}),e.jsx(hs,{children:a.map(h=>e.jsx(Ge,{value:h.id,children:h.name},h.id))})]})]}),u?e.jsxs(ha,{defaultValue:"board",className:"space-y-4",children:[e.jsxs(ma,{className:"grid h-10 w-full max-w-sm grid-cols-2 rounded-md border bg-muted/40 p-1",children:[e.jsx(Zt,{value:"board",children:"Agents"}),e.jsx(Zt,{value:"flows",children:"Flows"})]}),e.jsx(Xt,{value:"board",children:e.jsx(xcr,{brokerageId:u})}),e.jsx(Xt,{value:"flows",children:e.jsx(vcr,{brokerageId:u})})]}):e.jsxs("div",{className:"flex flex-col items-center justify-center py-16 text-center",children:[e.jsx(ji,{className:"mb-4 h-12 w-12 text-muted-foreground"}),e.jsx("h2",{className:"mb-1 text-xl font-semibold",children:"No Brokerage Assigned"}),e.jsx("p",{className:"text-muted-foreground",children:"You don't have any brokerages to manage."})]})]})}):null},_cr={checklist_applied:"Checklist applied",document_uploaded:"Document uploaded",item_approved:"Item approved",item_rejected:"Changes requested",item_added:"Item added",item_updated:"Item updated"};function wcr({dealId:s}){const{data:t=[]}=ZLs(s),[n,r]=j.useState({});return j.useEffect(()=>{const a=Array.from(new Set(t.map(i=>i.actor_user_id).filter(Boolean)));a.length!==0&&(async()=>{const{data:i}=await q.from("profiles").select("id, name, email").in("id",a),l={};(i||[]).forEach(o=>{l[o.id]=o.name||o.email||"Someone"}),r(l)})()},[t]),t.length===0?e.jsx("p",{className:"py-6 text-center text-sm text-muted-foreground",children:"No compliance activity yet."}):e.jsx("div",{className:"space-y-3",children:t.map(a=>e.jsxs("div",{className:"flex gap-3 text-sm",children:[e.jsx("div",{className:"mt-1.5 h-2 w-2 flex-shrink-0 rounded-full bg-primary/60"}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"font-medium",children:_cr[a.event_type]||a.event_type}),a.detail&&e.jsx("p",{className:"text-xs text-muted-foreground",children:a.detail}),e.jsxs("p",{className:"text-[11px] text-muted-foreground",children:[a.actor_user_id?n[a.actor_user_id]||"Someone":"System"," ·"," ",new Date(a.created_at).toLocaleString()]})]})]},a.id))})}function jcr({brokerageId:s,deal:t,open:n,onOpenChange:r}){const{data:a=[]}=Hzt(s),i=QLs(),[l,o]=j.useState("");if(!t)return null;const c=eGe(t),d=async()=>{if(l)try{await i.mutateAsync({dealId:t.deal_id,brokerageId:s,templateId:l,deal:{contract_date:t.contract_date,target_close_date:t.target_close_date}}),re.success("Checklist added to this file")}catch(u){re.error(u.message||"Could not apply checklist")}};return e.jsx(Wy,{open:n,onOpenChange:r,children:e.jsxs(py,{className:"w-full overflow-y-auto sm:max-w-xl",children:[e.jsxs(D0,{className:"text-left",children:[e.jsx(F0,{className:"pr-8",children:t.property_address||t.deal_name}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2 pt-1",children:[e.jsx(Be,{variant:"secondary",children:t.agent_name||"Agent"}),t.stage_name&&e.jsx(Be,{variant:"outline",children:t.stage_name}),e.jsx(Be,{variant:c==="compliant"?"default":"outline",children:Vzt[c]})]})]}),e.jsxs("div",{className:"mt-5 grid grid-cols-3 gap-3 rounded-lg border p-3 text-center text-xs",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-muted-foreground",children:"Contract"}),e.jsx("p",{className:"font-medium",children:t.contract_date||"—"})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-muted-foreground",children:"Target close"}),e.jsx("p",{className:"font-medium",children:t.target_close_date||"—"})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-muted-foreground",children:"Approved"}),e.jsxs("p",{className:"font-medium",children:[t.approved_items,"/",t.total_items]})]})]}),e.jsxs(ha,{defaultValue:"checklist",className:"mt-5",children:[e.jsxs(ma,{className:"grid w-full grid-cols-3",children:[e.jsx(Zt,{value:"checklist",children:"Checklist"}),e.jsx(Zt,{value:"messages",children:"Messages"}),e.jsx(Zt,{value:"audit",children:"Audit trail"})]}),e.jsxs(Xt,{value:"checklist",className:"mt-4 space-y-4",children:[t.total_items===0&&a.length>0&&e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(ms,{value:l,onValueChange:o,children:[e.jsx(us,{children:e.jsx(fs,{placeholder:"Apply a checklist"})}),e.jsx(hs,{children:a.map(u=>e.jsx(Ge,{value:u.id,children:u.name},u.id))})]}),e.jsx($,{onClick:d,disabled:!l||i.isPending,children:"Apply"})]}),e.jsx(sas,{dealId:t.deal_id,canReview:!0})]}),e.jsx(Xt,{value:"messages",className:"mt-4",children:e.jsx(nas,{dealId:t.deal_id,brokerageId:s,role:"staff",counterpartName:t.agent_name})}),e.jsx(Xt,{value:"audit",className:"mt-4",children:e.jsx(wcr,{dealId:t.deal_id})})]})]})})}function Ncr({metrics:s}){const t=[{label:"Active transactions",value:String(s.activeDeals),caption:`${s.closedThisYear} closed this year`,icon:ji,tint:"bg-blue-500/10 text-blue-600"},{label:"Pipeline volume",value:Wf(s.pipelineVolume),caption:`${Wf(s.closedVolumeThisYear)} closed YTD`,icon:Yl,tint:"bg-indigo-500/10 text-indigo-600"},{label:"Projected commission",value:Wf(s.pipelineGci),caption:"Gross on active files",icon:ru,tint:"bg-emerald-500/10 text-emerald-600"},{label:"Est. brokerage share",value:Wf(s.brokerageShare),caption:`${Wf(s.closedCompanyDollarYtd)} company dollar YTD`,icon:ZJ,tint:"bg-teal-500/10 text-teal-600"},{label:"Closing soon",value:String(s.closingNext30),caption:`${s.closingThisMonth} this month`,icon:Au,tint:"bg-amber-500/10 text-amber-600"}],n=[{label:"Files awaiting review",value:s.needsReview,icon:qz,tint:"text-blue-600"},{label:"Changes requested",value:s.changesRequested,icon:VJ,tint:"text-destructive"},{label:"Overdue items",value:s.overdueItems,icon:wl,tint:"text-amber-600"}];return e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"grid grid-cols-1 gap-3 sm:grid-cols-2 xl:grid-cols-5",children:t.map(r=>e.jsx(Ne,{className:"border-border/60",children:e.jsx(Ie,{className:"p-4",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("span",{className:Pt("flex h-9 w-9 shrink-0 items-center justify-center rounded-lg",r.tint),children:e.jsx(r.icon,{className:"h-4.5 w-4.5"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:r.label}),e.jsx("p",{className:"text-2xl font-bold tabular-nums tracking-tight",children:r.value}),e.jsx("p",{className:"mt-0.5 truncate text-[11px] text-muted-foreground",children:r.caption})]})]})})},r.label))}),e.jsx(Ne,{className:"border-border/60",children:e.jsx(Ie,{className:"flex flex-wrap items-center gap-x-8 gap-y-3 p-4",children:n.map(r=>e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(r.icon,{className:Pt("h-4 w-4",r.tint)}),e.jsx("span",{className:"text-sm font-semibold tabular-nums",children:r.value}),e.jsx("span",{className:"text-xs text-muted-foreground",children:r.label})]},r.label))})})]})}function kcr({outlook:s}){const t=s.some(n=>n.deals>0);return e.jsxs(Ne,{className:"border-border/60",children:[e.jsxs(Ct,{className:"pb-2",children:[e.jsx(At,{className:"text-base",children:"Closing outlook"}),e.jsx(Gn,{children:"Expected closings over the next 6 months"})]}),e.jsx(Ie,{className:"pt-2",children:t?e.jsx("div",{className:"h-[220px] w-full",children:e.jsx(A_,{width:"100%",height:"100%",children:e.jsxs(OK,{data:s,margin:{top:8,right:8,left:0,bottom:0},children:[e.jsx(vT,{strokeDasharray:"3 3",vertical:!1,stroke:"hsl(var(--border))"}),e.jsx(Mb,{dataKey:"label",tickLine:!1,axisLine:!1,fontSize:11,stroke:"hsl(var(--muted-foreground))"}),e.jsx(Pb,{tickLine:!1,axisLine:!1,fontSize:11,stroke:"hsl(var(--muted-foreground))",tickFormatter:n=>Wf(Number(n)),width:54}),e.jsx(Ag,{cursor:{fill:"hsl(var(--muted) / 0.4)"},contentStyle:{background:"hsl(var(--popover))",border:"1px solid hsl(var(--border))",borderRadius:8,fontSize:12,color:"hsl(var(--popover-foreground))"},formatter:(n,r,a)=>{var i,l;return[`${Wf(Number(n))} · ${((i=a==null?void 0:a.payload)==null?void 0:i.deals)??0} deal${((l=a==null?void 0:a.payload)==null?void 0:l.deals)===1?"":"s"}`,"Volume"]}}),e.jsx(qw,{dataKey:"volume",radius:[6,6,0,0],children:s.map(n=>e.jsx(t9,{fill:n.closed?"hsl(var(--primary))":"hsl(var(--primary) / 0.45)"},n.key))})]})})}):e.jsx("p",{className:"py-10 text-center text-sm text-muted-foreground",children:"No closing dates set on the current transactions yet."})})]})}function Scr({agents:s,totalVolume:t,selectedAgentId:n,onSelectAgent:r}){return s.length===0?null:e.jsxs(Ne,{className:"border-border/60",children:[e.jsxs(Ct,{className:"pb-2",children:[e.jsx(At,{className:"text-base",children:"Agent production"}),e.jsx(Gn,{children:"Company-visible transactions by agent — tap a row to filter the board"})]}),e.jsx(Ie,{className:"space-y-1 pt-2",children:s.slice(0,12).map(a=>{const i=t>0?Math.round(a.volume/t*100):0,l=n===a.userId;return e.jsxs("button",{onClick:()=>r(l?"all":a.userId),className:`flex w-full items-center gap-3 rounded-lg px-2 py-2 text-left transition-colors hover:bg-muted/60 ${l?"bg-muted":""}`,children:[e.jsxs(Oa,{className:"h-8 w-8 shrink-0",children:[e.jsx(Li,{src:a.avatarUrl||void 0,alt:a.name}),e.jsx(za,{className:"text-[11px]",children:a.name.slice(0,2).toUpperCase()})]}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"truncate text-sm font-medium",children:a.name}),e.jsxs("p",{className:"text-[11px] text-muted-foreground",children:[a.activeDeals," active · ",a.closedDeals," closed",a.overdue>0?` · ${a.overdue} overdue`:""]}),e.jsx("div",{className:"mt-1.5 h-1.5 w-full overflow-hidden rounded-full bg-muted",children:e.jsx("div",{className:"h-full rounded-full bg-primary",style:{width:`${i}%`}})})]}),e.jsxs("div",{className:"shrink-0 text-right",children:[e.jsx("p",{className:"text-sm font-semibold tabular-nums",children:Wf(a.volume)}),e.jsxs("p",{className:"text-[11px] text-muted-foreground tabular-nums",children:[Wf(a.gci)," GCI"]})]})]},a.userId)})})]})}const SEt={ownerUserId:"",dealName:"",dealType:"buyer",stageId:"",propertyAddress:"",city:"",state:"",zipCode:"",contractDate:"",targetCloseDate:"",actualCloseDate:"",price:"",commissionPercentage:"",notes:""};function Ccr({brokerageId:s,open:t,onOpenChange:n}){const[r,a]=j.useState(SEt),[i,l]=j.useState(""),{data:o=[],isLoading:c}=r6s(t?s:null),{data:d=[],isLoading:u}=a6s(r.ownerUserId||null),h=i6s();j.useEffect(()=>{t||(a(SEt),l(""))},[t]),j.useEffect(()=>{d.length>0&&!d.some(w=>w.id===r.stageId)&&a(w=>({...w,stageId:d[0].id}))},[d,r.stageId]);const m=j.useMemo(()=>{const w=i.trim().toLowerCase();return w?o.filter(S=>`${S.name??""} ${S.email??""}`.toLowerCase().includes(w)):o},[o,i]),f=(w,S)=>a(C=>({...C,[w]:S})),g=r.price?Number(r.price):null,x=r.commissionPercentage?Number(r.commissionPercentage):null,y=g!=null&&x!=null&&Number.isFinite(g)&&Number.isFinite(x)?Math.round(g*(x/100)*100)/100:null,v=!!r.ownerUserId&&!!r.stageId&&r.dealName.trim().length>0&&!h.isPending,b=async()=>{try{await h.mutateAsync({brokerageId:s,ownerUserId:r.ownerUserId,dealName:r.dealName,dealType:r.dealType,stageId:r.stageId||null,propertyAddress:r.propertyAddress,city:r.city,state:r.state,zipCode:r.zipCode,contractDate:r.contractDate,targetCloseDate:r.targetCloseDate,actualCloseDate:r.actualCloseDate,price:g!=null&&Number.isFinite(g)?g:null,commissionPercentage:x!=null&&Number.isFinite(x)?x:null,notes:r.notes});const w=o.find(S=>S.id===r.ownerUserId);re.success(`Deal added to ${(w==null?void 0:w.name)||"the agent"}'s pipeline.`),n(!1)}catch(w){re.error((w==null?void 0:w.message)||"Could not add the deal.")}};return e.jsx(zs,{open:t,onOpenChange:n,children:e.jsxs(Os,{className:"max-h-[90vh] max-w-2xl overflow-y-auto",children:[e.jsxs(Us,{children:[e.jsx(Bs,{children:"Add a deal for an agent"}),e.jsx(Ir,{children:"The deal is created in the agent's own pipeline, so it shows up here and in their account."})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Agent"}),e.jsx(pe,{placeholder:"Search agents by name or email",value:i,onChange:w=>l(w.target.value)}),e.jsxs(ms,{value:r.ownerUserId,onValueChange:w=>f("ownerUserId",w),children:[e.jsx(us,{children:e.jsx(fs,{placeholder:c?"Loading agents…":"Select an agent"})}),e.jsx(hs,{children:m.map(w=>e.jsx(Ge,{value:w.id,children:w.name||w.email||"Agent"},w.id))})]})]}),e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-2 sm:col-span-2",children:[e.jsx(ee,{children:"Deal name"}),e.jsx(pe,{placeholder:"Client name or property address",value:r.dealName,onChange:w=>f("dealName",w.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Type"}),e.jsxs(ms,{value:r.dealType,onValueChange:w=>f("dealType",w),children:[e.jsx(us,{children:e.jsx(fs,{})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"buyer",children:"Buyer"}),e.jsx(Ge,{value:"seller",children:"Seller"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Stage"}),e.jsxs(ms,{value:r.stageId,onValueChange:w=>f("stageId",w),disabled:!r.ownerUserId||u,children:[e.jsx(us,{children:e.jsx(fs,{placeholder:r.ownerUserId?u?"Loading stages…":"Select a stage":"Pick an agent first"})}),e.jsx(hs,{children:d.map(w=>e.jsx(Ge,{value:w.id,children:w.name},w.id))})]})]}),e.jsxs("div",{className:"space-y-2 sm:col-span-2",children:[e.jsx(ee,{children:"Property address"}),e.jsx(pe,{value:r.propertyAddress,onChange:w=>f("propertyAddress",w.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"City"}),e.jsx(pe,{value:r.city,onChange:w=>f("city",w.target.value)})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"State"}),e.jsx(pe,{value:r.state,onChange:w=>f("state",w.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"ZIP"}),e.jsx(pe,{value:r.zipCode,onChange:w=>f("zipCode",w.target.value)})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Contract date"}),e.jsx(pe,{type:"date",value:r.contractDate,onChange:w=>f("contractDate",w.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Target close date"}),e.jsx(pe,{type:"date",value:r.targetCloseDate,onChange:w=>f("targetCloseDate",w.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Actual close date"}),e.jsx(pe,{type:"date",value:r.actualCloseDate,onChange:w=>f("actualCloseDate",w.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Price"}),e.jsx(pe,{type:"number",inputMode:"decimal",value:r.price,onChange:w=>f("price",w.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Commission %"}),e.jsx(pe,{type:"number",inputMode:"decimal",step:"0.01",value:r.commissionPercentage,onChange:w=>f("commissionPercentage",w.target.value)}),y!=null&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Expected commission: $",y.toLocaleString()]})]}),e.jsxs("div",{className:"space-y-2 sm:col-span-2",children:[e.jsx(ee,{children:"Notes"}),e.jsx(Rs,{rows:3,value:r.notes,onChange:w=>f("notes",w.target.value)})]})]})]}),e.jsxs(Ar,{children:[e.jsx($,{variant:"outline",onClick:()=>n(!1),children:"Cancel"}),e.jsxs($,{onClick:b,disabled:!v,children:[h.isPending&&e.jsx(kt,{className:"mr-2 h-4 w-4 animate-spin"}),"Add deal"]})]})]})})}const Acr={not_started:"bg-muted text-muted-foreground",in_review:"bg-amber-500/15 text-amber-600",changes_requested:"bg-destructive/15 text-destructive",compliant:"bg-emerald-500/15 text-emerald-600"};function Ecr({brokerageId:s,canAddDeals:t=!1}){const{data:n=[],isLoading:r}=Dtt(s),[a,i]=j.useState(""),[l,o]=j.useState("all"),[c,d]=j.useState("all"),[u,h]=j.useState("all"),[m,f]=j.useState("stage"),[g,x]=j.useState(null),[y,v]=j.useState(!1),b=j.useMemo(()=>Par(n),[n]),w=j.useMemo(()=>{const I=new Map;return n.forEach(P=>I.set(P.owner_user_id,P.agent_name||"Agent")),Array.from(I,([P,R])=>({id:P,name:R}))},[n]),S=j.useMemo(()=>{const I=new Set;return n.forEach(P=>P.stage_name&&I.add(P.stage_name)),Array.from(I).sort((P,R)=>P.localeCompare(R))},[n]),C=j.useMemo(()=>{const I=a.trim().toLowerCase();return n.filter(P=>{if(c!=="all"&&P.owner_user_id!==c||u!=="all"&&(P.stage_name||"No stage")!==u)return!1;const R=eGe(P);return(l==="overdue"?P.overdue_items===0:l!=="all"&&l!==R)?!1:I?[P.deal_name,P.property_address,P.city,P.agent_name].filter(Boolean).some(D=>D.toLowerCase().includes(I)):!0})},[n,a,l,c,u]),E=j.useMemo(()=>{const I=[...C],P=R=>R.actual_close_date||R.target_close_date||"";return I.sort((R,D)=>{switch(m){case"agent":return(R.agent_name||"").localeCompare(D.agent_name||"");case"close":return(P(R)||"9999").localeCompare(P(D)||"9999");case"overdue":return D.overdue_items-R.overdue_items;case"progress":{const O=U=>U.total_items?U.approved_items/U.total_items:0;return O(R)-O(D)}case"stage":default:{const O=(R.stage_name||"zzz").localeCompare(D.stage_name||"zzz");return O!==0?O:(R.agent_name||"").localeCompare(D.agent_name||"")}}}),I},[C,m]);return r?e.jsx("div",{className:"flex justify-center py-16",children:e.jsx(kt,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):e.jsxs("div",{className:"space-y-4",children:[t&&e.jsx("div",{className:"flex justify-end",children:e.jsxs($,{onClick:()=>v(!0),children:[e.jsx(dn,{className:"mr-2 h-4 w-4"}),"Add deal"]})}),t&&e.jsx(Ccr,{brokerageId:s,open:y,onOpenChange:v}),n.length>0&&e.jsxs(e.Fragment,{children:[e.jsx(Ncr,{metrics:b}),e.jsxs("div",{className:"grid gap-3 lg:grid-cols-2",children:[e.jsx(kcr,{outlook:b.outlook}),e.jsx(Scr,{agents:b.agents,totalVolume:b.totalVolume,selectedAgentId:c,onSelectAgent:d})]})]}),e.jsxs("div",{className:"flex flex-col gap-3 lg:flex-row",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(Kr,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(pe,{className:"pl-9",placeholder:"Search address, agent or file name",value:a,onChange:I=>i(I.target.value)})]}),e.jsxs(ms,{value:l,onValueChange:o,children:[e.jsx(us,{className:"lg:w-[180px]",children:e.jsx(fs,{})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"all",children:"All statuses"}),e.jsx(Ge,{value:"not_started",children:"Not started"}),e.jsx(Ge,{value:"in_review",children:"In review"}),e.jsx(Ge,{value:"changes_requested",children:"Changes requested"}),e.jsx(Ge,{value:"compliant",children:"Compliant"}),e.jsx(Ge,{value:"overdue",children:"Has overdue items"})]})]}),e.jsxs(ms,{value:u,onValueChange:h,children:[e.jsx(us,{className:"lg:w-[180px]",children:e.jsx(fs,{})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"all",children:"All stages"}),S.map(I=>e.jsx(Ge,{value:I,children:I},I))]})]}),e.jsxs(ms,{value:m,onValueChange:f,children:[e.jsx(us,{className:"lg:w-[180px]",children:e.jsx(fs,{})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"stage",children:"Sort: Deal stage"}),e.jsx(Ge,{value:"agent",children:"Sort: Agent"}),e.jsx(Ge,{value:"close",children:"Sort: Closing date"}),e.jsx(Ge,{value:"overdue",children:"Sort: Most overdue"}),e.jsx(Ge,{value:"progress",children:"Sort: Least complete"})]})]}),e.jsxs(ms,{value:c,onValueChange:d,children:[e.jsx(us,{className:"lg:w-[180px]",children:e.jsx(fs,{})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"all",children:"All agents"}),w.map(I=>e.jsx(Ge,{value:I.id,children:I.name},I.id))]})]})]}),E.length===0?e.jsx(Ne,{children:e.jsxs(Ie,{className:"flex flex-col items-center justify-center py-16 text-center",children:[e.jsx(_b,{className:"mb-3 h-10 w-10 text-muted-foreground"}),e.jsx("p",{className:"font-medium",children:"No transactions to review"}),e.jsx("p",{className:"mt-1 max-w-md text-sm text-muted-foreground",children:"Deals appear here once an agent reaches a company-visible phase — everything earlier stays private to the agent."})]})}):e.jsx("div",{className:"space-y-2",children:E.map(I=>{const P=eGe(I),R=I.total_items?Math.round(I.approved_items/I.total_items*100):0;return e.jsxs("button",{onClick:()=>x(I),className:"w-full rounded-lg border p-4 text-left transition-colors hover:bg-muted/50",children:[e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"truncate font-medium",children:I.property_address||I.deal_name}),e.jsxs("p",{className:"mt-0.5 text-xs text-muted-foreground",children:[I.agent_name,I.stage_name?` · ${I.stage_name}`:"",I.actual_close_date?` · Closed ${I.actual_close_date}`:I.target_close_date?` · Closes ${I.target_close_date}`:""]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[I.overdue_items>0&&e.jsxs(Be,{variant:"destructive",className:"gap-1 text-[10px]",children:[e.jsx(wl,{className:"h-3 w-3"})," ",I.overdue_items," overdue"]}),e.jsx("span",{className:`rounded-full px-2 py-0.5 text-[11px] font-medium ${Acr[P]}`,children:Vzt[P]})]})]}),e.jsxs("div",{className:"mt-3 flex items-center gap-3",children:[e.jsx(Yi,{value:R,className:"h-1.5 flex-1"}),e.jsxs("span",{className:"w-24 text-right text-[11px] text-muted-foreground",children:[I.approved_items," of ",I.total_items," approved"]})]})]},I.deal_id)})}),e.jsx(jcr,{brokerageId:s,deal:g,open:!!g,onOpenChange:I=>!I&&x(null)})]})}const CEt=[{value:"any",label:"Any deal type"},{value:"listing",label:"Listing"},{value:"buyer",label:"Buyer"},{value:"lease",label:"Lease"},{value:"referral",label:"Referral"}];function Tcr({brokerageId:s}){var b,w;const{data:t=[],isLoading:n}=Hzt(s),r=GLs(),a=WLs(),[i,l]=j.useState(null),o=i??((b=t[0])==null?void 0:b.id)??null,c=t.find(S=>S.id===o)||null,{data:d=[]}=HLs(o),u=KLs(),h=YLs(),[m,f]=j.useState(!1),[g,x]=j.useState(null),y=async()=>{try{const S=await r.mutateAsync({brokerage_id:s,name:"New checklist",deal_type:null,is_active:!0});l(S)}catch(S){re.error(S.message||"Could not create checklist")}},v=async()=>{var S;if(!(!o||!((S=g==null?void 0:g.title)!=null&&S.trim())))try{await u.mutateAsync({...g,template_id:o,title:g.title.trim(),sort_order:g.sort_order??d.length}),f(!1),x(null)}catch(C){re.error(C.message||"Could not save item")}};return n?e.jsx("div",{className:"flex justify-center py-10",children:e.jsx(kt,{className:"h-5 w-5 animate-spin text-muted-foreground"})}):e.jsxs("div",{className:"grid gap-6 lg:grid-cols-[280px_1fr]",children:[e.jsxs(Ne,{children:[e.jsxs(Ct,{className:"flex-row items-center justify-between space-y-0",children:[e.jsx(At,{className:"text-base",children:"Checklists"}),e.jsx($,{size:"sm",variant:"outline",onClick:y,children:e.jsx(dn,{className:"h-4 w-4"})})]}),e.jsx(Ie,{className:"space-y-2",children:t.length===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:"Create a checklist per deal type — Listing, Buyer, Lease."}):t.map(S=>{var C;return e.jsxs("button",{onClick:()=>l(S.id),className:`w-full rounded-lg border p-3 text-left transition-colors ${S.id===o?"border-primary bg-primary/5":"hover:bg-muted"}`,children:[e.jsx("p",{className:"truncate text-sm font-medium",children:S.name}),e.jsx("p",{className:"text-xs text-muted-foreground",children:(C=CEt.find(E=>E.value===(S.deal_type||"any")))==null?void 0:C.label})]},S.id)})})]}),c?e.jsxs(Ne,{children:[e.jsxs(Ct,{children:[e.jsx(At,{className:"text-lg",children:"Checklist details"}),e.jsx(Gn,{children:"Applied automatically when a deal becomes company-visible."})]}),e.jsxs(Ie,{className:"space-y-6",children:[e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Name"}),e.jsx(pe,{defaultValue:c.name,onBlur:S=>r.mutate({id:c.id,brokerage_id:s,name:S.target.value})})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Applies to"}),e.jsxs(ms,{value:c.deal_type||"any",onValueChange:S=>r.mutate({id:c.id,brokerage_id:s,deal_type:S==="any"?null:S}),children:[e.jsx(us,{children:e.jsx(fs,{})}),e.jsx(hs,{children:CEt.map(S=>e.jsx(Ge,{value:S.value,children:S.label},S.value))})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(ee,{children:"Required items"}),e.jsxs($,{size:"sm",variant:"outline",onClick:()=>{x({phase:"contract",requires_document:!0,required_for_closing:!0}),f(!0)},children:[e.jsx(dn,{className:"mr-1 h-4 w-4"})," Add item"]})]}),d.length===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:"No items yet."}):e.jsx("div",{className:"space-y-2",children:d.map(S=>{var C;return e.jsxs("div",{className:"flex items-start justify-between gap-3 rounded-lg border p-3",children:[e.jsxs("button",{className:"min-w-0 flex-1 text-left",onClick:()=>{x(S),f(!0)},children:[e.jsx("p",{className:"truncate text-sm font-medium",children:S.title}),e.jsxs("div",{className:"mt-1 flex flex-wrap gap-1.5",children:[e.jsx(Be,{variant:"secondary",className:"text-[10px]",children:((C=PEe.find(E=>E.value===S.phase))==null?void 0:C.label)||S.phase}),S.requires_document&&e.jsx(Be,{variant:"outline",className:"text-[10px]",children:"Document"}),S.required_for_closing&&e.jsx(Be,{variant:"outline",className:"text-[10px]",children:"Required to close"}),S.due_anchor&&e.jsxs(Be,{variant:"outline",className:"text-[10px]",children:[S.due_offset_days??0,"d after"," ",S.due_anchor==="contract_date"?"contract":"target close"]})]})]}),e.jsx($,{variant:"ghost",size:"icon",onClick:()=>h.mutate({id:S.id,templateId:c.id}),children:e.jsx(Wn,{className:"h-4 w-4 text-destructive"})})]},S.id)})})]}),e.jsxs($,{variant:"outline",className:"text-destructive",onClick:async()=>{await fo(`Delete "${c.name}"?`)&&(a.mutate({id:c.id,brokerageId:s}),l(null))},children:[e.jsx(Wn,{className:"mr-2 h-4 w-4"})," Delete checklist"]})]})]}):e.jsx(Ne,{children:e.jsxs(Ie,{className:"flex flex-col items-center justify-center py-16 text-center",children:[e.jsx(Jr,{className:"mb-3 h-10 w-10 text-muted-foreground"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Select or create a checklist to add required documents."})]})}),e.jsx(zs,{open:m,onOpenChange:f,children:e.jsxs(Os,{children:[e.jsx(Us,{children:e.jsx(Bs,{children:g!=null&&g.id?"Edit item":"Add item"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Title"}),e.jsx(pe,{value:(g==null?void 0:g.title)||"",onChange:S=>x(C=>({...C,title:S.target.value})),placeholder:"Purchase agreement (fully executed)"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Instructions for the agent"}),e.jsx(Rs,{rows:2,value:(g==null?void 0:g.description)||"",onChange:S=>x(C=>({...C,description:S.target.value}))})]}),e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Phase"}),e.jsxs(ms,{value:(g==null?void 0:g.phase)||"contract",onValueChange:S=>x(C=>({...C,phase:S})),children:[e.jsx(us,{children:e.jsx(fs,{})}),e.jsx(hs,{children:PEe.map(S=>e.jsx(Ge,{value:S.value,children:S.label},S.value))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Due"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(pe,{type:"number",className:"w-20",value:(g==null?void 0:g.due_offset_days)??"",onChange:S=>x(C=>({...C,due_offset_days:S.target.value===""?null:Number(S.target.value)})),placeholder:"days"}),e.jsxs(ms,{value:(g==null?void 0:g.due_anchor)||"none",onValueChange:S=>x(C=>({...C,due_anchor:S==="none"?null:S})),children:[e.jsx(us,{children:e.jsx(fs,{})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"none",children:"No due date"}),e.jsx(Ge,{value:"contract_date",children:"after contract date"}),e.jsx(Ge,{value:"target_close_date",children:"after target close"})]})]})]})]})]}),e.jsxs("div",{className:"flex items-center justify-between rounded-lg border p-3",children:[e.jsx(ee,{className:"text-sm",children:"Requires an uploaded document"}),e.jsx(Sn,{checked:(g==null?void 0:g.requires_document)??!0,onCheckedChange:S=>x(C=>({...C,requires_document:S}))})]}),e.jsxs("div",{className:"flex items-center justify-between rounded-lg border p-3",children:[e.jsx(ee,{className:"text-sm",children:"Required before closing"}),e.jsx(Sn,{checked:(g==null?void 0:g.required_for_closing)??!0,onCheckedChange:S=>x(C=>({...C,required_for_closing:S}))})]})]}),e.jsxs(Ar,{children:[e.jsx($,{variant:"outline",onClick:()=>f(!1),children:"Cancel"}),e.jsxs($,{onClick:v,disabled:!((w=g==null?void 0:g.title)!=null&&w.trim())||u.isPending,children:[u.isPending&&e.jsx(kt,{className:"mr-2 h-4 w-4 animate-spin"}),"Save"]})]})]})})]})}function Mcr({brokerageId:s}){const{data:t,isLoading:n}=qLs(s),r=VLs(),{data:a=[]}=BLs(s),i=$Ls(),l=ULs(),[o,c]=j.useState(["contract","closing","closed"]),[d,u]=j.useState(!0),[h,m]=j.useState(!0),[f,g]=j.useState(""),[x,y]=j.useState(!1);j.useEffect(()=>{t&&(c(t.visible_phases||[]),u(t.include_contract_dated_deals),m(t.is_enabled))},[t]);const v=S=>c(C=>C.includes(S)?C.filter(E=>E!==S):[...C,S]),b=async()=>{try{await r.mutateAsync({brokerage_id:s,visible_phases:o,include_contract_dated_deals:d,is_enabled:h}),re.success("Compliance settings saved")}catch(S){re.error(S.message||"Could not save settings")}},w=async()=>{const S=f.trim().toLowerCase();if(S){y(!0);try{const{data:C,error:E}=await q.from("profiles").select("id, email").ilike("email",S).maybeSingle();if(E)throw E;if(!C){re.error("No LevelUp account found with that email");return}await i.mutateAsync({brokerageId:s,userId:C.id}),g(""),re.success("Transaction admin added")}catch(C){re.error(C.message||"Could not add transaction admin")}finally{y(!1)}}};return n?e.jsx("div",{className:"flex justify-center py-10",children:e.jsx(kt,{className:"h-5 w-5 animate-spin text-muted-foreground"})}):e.jsxs("div",{className:"grid gap-6 lg:grid-cols-2",children:[e.jsxs(Ne,{children:[e.jsxs(Ct,{children:[e.jsx(At,{className:"text-lg",children:"What the company can see"}),e.jsx(Gn,{children:"Agent leads, consultations and early conversations stay private. Deals become visible to compliance once they reach one of the phases below."})]}),e.jsxs(Ie,{className:"space-y-5",children:[e.jsxs("div",{className:"flex items-center justify-between rounded-lg border p-3",children:[e.jsxs("div",{children:[e.jsx(ee,{className:"text-sm font-medium",children:"Compliance tracking on"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Turn off to hide all agent deals from the company view."})]}),e.jsx(Sn,{checked:h,onCheckedChange:m})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{className:"text-sm font-medium",children:"Company-visible phases"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:PEe.map(S=>e.jsx("button",{type:"button",onClick:()=>v(S.value),className:`rounded-full border px-3 py-1.5 text-xs font-medium transition-colors ${o.includes(S.value)?"border-primary bg-primary/10 text-primary":"border-border text-muted-foreground hover:bg-muted"}`,children:S.label},S.value))})]}),e.jsxs("div",{className:"flex items-center justify-between rounded-lg border p-3",children:[e.jsxs("div",{children:[e.jsx(ee,{className:"text-sm font-medium",children:"Include any deal with a contract date"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:'Recommended — catches "agreement signed" deals even when an agent uses custom stage names.'})]}),e.jsx(Sn,{checked:d,onCheckedChange:u})]}),e.jsxs($,{onClick:b,disabled:r.isPending,children:[r.isPending&&e.jsx(kt,{className:"mr-2 h-4 w-4 animate-spin"}),"Save settings"]})]})]}),e.jsxs(Ne,{children:[e.jsxs(Ct,{children:[e.jsxs(At,{className:"flex items-center gap-2 text-lg",children:[e.jsx(bm,{className:"h-4 w-4"})," Transaction admins"]}),e.jsx(Gn,{children:"Give staff compliance-only access — deals, documents, checklists and notes. No recruiting or billing."})]}),e.jsxs(Ie,{className:"space-y-4",children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsx(pe,{placeholder:"admin@yourbrokerage.com",value:f,onChange:S=>g(S.target.value),onKeyDown:S=>S.key==="Enter"&&w()}),e.jsx($,{onClick:w,disabled:x||!f.trim(),children:x?e.jsx(kt,{className:"h-4 w-4 animate-spin"}):e.jsx(sc,{className:"h-4 w-4"})})]}),a.length===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:"No transaction admins yet."}):e.jsx("div",{className:"space-y-2",children:a.map(S=>e.jsxs("div",{className:"flex items-center justify-between rounded-lg border p-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"truncate text-sm font-medium",children:S.name||S.email}),e.jsx("p",{className:"truncate text-xs text-muted-foreground",children:S.email})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Be,{variant:"secondary",className:"text-[10px]",children:"Compliance"}),e.jsx($,{variant:"ghost",size:"icon",onClick:()=>l.mutate({id:S.id,brokerageId:s}),children:e.jsx(Wn,{className:"h-4 w-4 text-destructive"})})]})]},S.id))})]})]})]})}const Pcr=()=>{const{user:s,isBrokerageManager:t,isAdmin:n,brokerageId:r,managedBrokerages:a,selectedBrokerageId:i,setSelectedBrokerageId:l}=vs(),o=Qn(),{data:c=[],isLoading:d}=Rtt(),[u,h]=j.useState(!1),m=c.length>0,f=t||n,g=j.useMemo(()=>{var x;return i||(a.length>0?a[0].id:null)||((x=c[0])==null?void 0:x.brokerage_id)||r},[i,a,c,r]);return j.useEffect(()=>{if(!(!s||d)){if(!f&&!m){o("/dashboard");return}!i&&a.length>0&&l(a[0].id),h(!0)}},[s,d,f,m,o,a,i,l]),u?e.jsx(Vs,{title:"Transactions & Compliance",description:"Review agent files, required documents and closing compliance",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(ms,{value:i||"",onValueChange:l,children:[e.jsxs(us,{className:"w-[280px]",children:[e.jsx(ji,{className:"mr-2 h-4 w-4"}),e.jsx(fs,{placeholder:"Select brokerage"})]}),e.jsx(hs,{children:a.map(x=>e.jsx(Ge,{value:x.id,children:x.name},x.id))})]})]}),g?e.jsxs(ha,{defaultValue:"board",className:"space-y-4",children:[e.jsxs(ma,{className:`grid w-full ${f?"max-w-lg grid-cols-3":"max-w-xs grid-cols-1"}`,children:[e.jsx(Zt,{value:"board",children:"Transactions"}),f&&e.jsx(Zt,{value:"checklists",children:"Checklists"}),f&&e.jsx(Zt,{value:"settings",children:"Settings"})]}),e.jsx(Xt,{value:"board",children:e.jsx(Ecr,{brokerageId:g,canAddDeals:f||m})}),f&&e.jsx(Xt,{value:"checklists",children:e.jsx(Tcr,{brokerageId:g})}),f&&e.jsx(Xt,{value:"settings",children:e.jsx(Mcr,{brokerageId:g})})]}):e.jsxs("div",{className:"flex flex-col items-center justify-center py-16 text-center",children:[e.jsx(ji,{className:"mb-4 h-12 w-12 text-muted-foreground"}),e.jsx("h2",{className:"mb-1 text-xl font-semibold",children:"No Brokerage Assigned"}),e.jsx("p",{className:"text-muted-foreground",children:"You don't have any brokerages to manage."})]})]})}):null},Rne=q,bUe={draft:"Draft",approved:"Approved",paid:"Paid",void:"Void"},u_=s=>{const t=Number(s);return Number.isFinite(t)?t:0};function IW(s){const t=u_(s.gross_commission),n=u_(s.referral_amount)>0?u_(s.referral_amount):t*u_(s.referral_fee_pct)/100,r=Math.max(0,t-n),a=r*(100-u_(s.agent_split_pct))/100,i=r*u_(s.franchise_fee_pct)/100,l=u_(s.transaction_fee),o=(s.line_items||[]).reduce((u,h)=>u+u_(h.amount),0),c=a+i+l,d=r-c-o;return{gross:t,referral:n,adjustedGross:r,brokerageSplit:a,franchiseFee:i,transactionFee:l,otherCharges:o,companyDollar:c,agentNet:d}}function Icr(s,t){const n=u_(s.brokerage_split_pct),r=(t==null?void 0:t.agent_split_pct)!=null?u_(t.agent_split_pct):n?100-n:70;return{deal_id:s.deal_id,agent_user_id:s.owner_user_id,status:"draft",property_address:s.property_address||s.deal_name,escrow_company:null,escrow_number:null,closing_date:s.actual_close_date||s.target_close_date,sale_price:MW(s),gross_commission:PW(s),agent_split_pct:r,franchise_fee_pct:s.franchise_fee_pct!=null?u_(s.franchise_fee_pct):u_(t==null?void 0:t.franchise_fee_pct),transaction_fee:s.transaction_fee!=null?u_(s.transaction_fee):u_(t==null?void 0:t.transaction_fee),referral_fee_pct:u_(t==null?void 0:t.referral_fee_pct),referral_amount:0,referral_payee:null,line_items:[],notes:null}}function Kos(s){return tt({queryKey:["disbursements",s],enabled:!!s,queryFn:async()=>{const t=[];for(let r=0;;r+=1e3){const{data:a,error:i}=await Rne.from("brokerage_disbursements").select("*").eq("brokerage_id",s).order("closing_date",{ascending:!1,nullsFirst:!1}).range(r,r+1e3-1);if(i)throw i;if(t.push(...a||[]),!a||a.length<1e3)break}return t.map(r=>({...r,line_items:r.line_items||[]}))}})}function Lcr(s){const t=Vt(),{user:n}=vs();return ft({mutationFn:async r=>{const a=IW(r),i={brokerage_id:s,deal_id:r.deal_id,agent_user_id:r.agent_user_id,status:r.status,property_address:r.property_address,escrow_company:r.escrow_company,escrow_number:r.escrow_number,closing_date:r.closing_date,sale_price:r.sale_price||0,gross_commission:r.gross_commission||0,agent_split_pct:r.agent_split_pct||0,franchise_fee_pct:r.franchise_fee_pct||0,transaction_fee:r.transaction_fee||0,referral_fee_pct:r.referral_fee_pct||0,referral_amount:r.referral_amount||0,referral_payee:r.referral_payee,line_items:r.line_items||[],notes:r.notes,company_dollar:a.companyDollar,agent_net:a.agentNet};if(r.id){const{error:l}=await Rne.from("brokerage_disbursements").update(i).eq("id",r.id);if(l)throw l}else{i.created_by=(n==null?void 0:n.id)??null;const{error:l}=await Rne.from("brokerage_disbursements").insert(i);if(l)throw l}},onSuccess:()=>{t.invalidateQueries({queryKey:["disbursements",s]}),re.success("Disbursement saved")},onError:r=>re.error(r.message||"Could not save the disbursement")})}function Rcr(s){const t=Vt(),{user:n}=vs();return ft({mutationFn:async({id:r,status:a})=>{const i={status:a};a==="approved"&&(i.approved_at=new Date().toISOString(),i.approved_by=(n==null?void 0:n.id)??null),a==="paid"&&(i.paid_at=new Date().toISOString());const{error:l}=await Rne.from("brokerage_disbursements").update(i).eq("id",r);if(l)throw l},onSuccess:()=>t.invalidateQueries({queryKey:["disbursements",s]}),onError:r=>re.error(r.message||"Could not update the status")})}function Dcr(s){const t=Vt();return ft({mutationFn:async n=>{const{error:r}=await Rne.from("brokerage_disbursements").delete().eq("id",n);if(r)throw r},onSuccess:()=>{t.invalidateQueries({queryKey:["disbursements",s]}),re.success("Disbursement removed")},onError:n=>re.error(n.message||"Could not remove the disbursement")})}function Yos(s){return tt({queryKey:["brokerage-agent-records",s],enabled:!!s,queryFn:async()=>{const t=[];for(let r=0;;r+=1e3){const{data:a,error:i}=await q.from("brokerage_agent_records").select("*").eq("brokerage_id",s).range(r,r+1e3-1);if(i)throw i;if(t.push(...a||[]),!a||a.length<1e3)break}return t}})}const BPe=q;function Fcr(s){return tt({queryKey:["ops-follow-ups",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await BPe.from("recruit_prospects").select("id, first_name, last_name").eq("brokerage_id",s).limit(1e3);if(n)throw n;const r=t||[];if(!r.length)return[];const a=new Map(r.map(o=>[o.id,[o.first_name,o.last_name].filter(Boolean).join(" ")])),{data:i,error:l}=await BPe.from("recruit_follow_ups").select("id, title, due_date, prospect_id, completed_at").in("prospect_id",r.map(o=>o.id)).is("completed_at",null).order("due_date",{ascending:!0}).limit(500);if(l)throw l;return(i||[]).map(o=>({id:o.id,title:o.title,due_date:o.due_date,prospectName:a.get(o.prospect_id)||null}))}})}function Ocr(s){return tt({queryKey:["ops-help-requests",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await BPe.from("brokerage_help_requests").select("id, title, request_type, event_start_at, requester_user_id").eq("brokerage_id",s).eq("status","open").order("event_start_at",{ascending:!0}).limit(200);if(n)throw n;const r=t||[],a=Array.from(new Set(r.map(l=>l.requester_user_id).filter(Boolean))),i=new Map;if(a.length){const{data:l}=await BPe.from("profiles").select("id, name").in("id",a);(l||[]).forEach(o=>i.set(o.id,o.name))}return r.map(l=>({id:l.id,title:l.title,request_type:l.request_type,event_start_at:l.event_start_at,requesterName:i.get(l.requester_user_id)??null}))}})}const r3=q,Zos=[{value:"general",label:"General"},{value:"compliance",label:"Compliance"},{value:"disbursements",label:"Disbursements"},{value:"renewals",label:"Renewals"},{value:"onboarding",label:"Onboarding"},{value:"recruiting",label:"Recruiting"},{value:"help_board",label:"Help Board"},{value:"marketing",label:"Marketing"},{value:"listings",label:"Listings"}],$Pe=Object.fromEntries(Zos.map(s=>[s.value,s.label])),hQe={todo:"To do",in_progress:"In progress",done:"Done"},zcr={low:"Low",medium:"Medium",high:"High",urgent:"Urgent"};function Bcr(s){return tt({queryKey:["ops-tasks",s],enabled:!!s,queryFn:async()=>{const t=[];for(let r=0;;r+=1e3){const{data:a,error:i}=await r3.from("brokerage_operations_tasks").select("*").eq("brokerage_id",s).order("created_at",{ascending:!1}).range(r,r+1e3-1);if(i)throw i;if(t.push(...a||[]),!a||a.length<1e3)break}return t}})}function $cr(s){const t=Vt(),{user:n}=vs();return ft({mutationFn:async r=>{var o;const a={brokerage_id:s,assignee_user_id:r.assignee_user_id||null,category:r.category||"general",title:r.title.trim(),description:((o=r.description)==null?void 0:o.trim())||null,status:r.status||"todo",priority:r.priority||"medium",due_date:r.due_date||null,source_type:r.source_type||"manual",source_id:r.source_id||null,source_url:r.source_url||null};if(a.status==="done"&&(a.completed_at=new Date().toISOString()),r.id){const{error:c}=await r3.from("brokerage_operations_tasks").update(a).eq("id",r.id);if(c)throw c;return r.id}a.created_by=(n==null?void 0:n.id)??null;const{data:i,error:l}=await r3.from("brokerage_operations_tasks").insert(a).select("id").single();if(l)throw l;return i.id},onSuccess:()=>{t.invalidateQueries({queryKey:["ops-tasks",s]}),t.invalidateQueries({queryKey:["my-ops-tasks"]}),re.success("Task saved")},onError:r=>re.error(r.message||"Could not save task")})}function Ucr(s){const t=Vt();return ft({mutationFn:async({id:n,status:r})=>{const{error:a}=await r3.from("brokerage_operations_tasks").update({status:r,completed_at:r==="done"?new Date().toISOString():null}).eq("id",n);if(a)throw a},onSuccess:()=>{t.invalidateQueries({queryKey:["ops-tasks",s]}),t.invalidateQueries({queryKey:["my-ops-tasks"]})},onError:n=>re.error(n.message||"Could not update task")})}function qcr(s){const t=Vt();return ft({mutationFn:async n=>{const{error:r}=await r3.from("brokerage_operations_tasks").delete().eq("id",n);if(r)throw r},onSuccess:()=>{t.invalidateQueries({queryKey:["ops-tasks",s]}),t.invalidateQueries({queryKey:["my-ops-tasks"]}),re.success("Task removed")},onError:n=>re.error(n.message||"Could not remove task")})}function Vcr(s){const t=Vt(),{user:n}=vs();return ft({mutationFn:async r=>{const{error:a}=await r3.from("brokerage_operations_tasks").insert({brokerage_id:s,created_by:(n==null?void 0:n.id)??null,title:r.title,category:r.category,status:"done",source_type:r.sourceType,source_id:r.sourceId,dismissed_at:new Date().toISOString(),dismissed_by:(n==null?void 0:n.id)??null,completed_at:new Date().toISOString()});if(a)throw a},onSuccess:()=>{t.invalidateQueries({queryKey:["ops-tasks",s]}),re.success("Dismissed")},onError:r=>re.error(r.message||"Could not dismiss")})}function Hcr(s){return tt({queryKey:["ops-task-comments",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await r3.from("brokerage_operations_task_comments").select("*").eq("task_id",s).order("created_at",{ascending:!0});if(n)throw n;return t||[]}})}function Gcr(){const s=Vt(),{user:t}=vs();return ft({mutationFn:async({taskId:n,body:r})=>{const{error:a}=await r3.from("brokerage_operations_task_comments").insert({task_id:n,body:r.trim(),author_user_id:t==null?void 0:t.id});if(a)throw a},onSuccess:(n,r)=>s.invalidateQueries({queryKey:["ops-task-comments",r.taskId]}),onError:n=>re.error(n.message||"Could not add note")})}function Wcr(s){const{user:t}=vs();return tt({queryKey:["ops-digest-prefs",s,t==null?void 0:t.id],enabled:!!s&&!!t,queryFn:async()=>{const{data:n,error:r}=await r3.from("brokerage_operations_digest_prefs").select("*").eq("brokerage_id",s).eq("user_id",t.id).maybeSingle();if(r)throw r;return n||null}})}function Kcr(s){const t=Vt(),{user:n}=vs();return ft({mutationFn:async r=>{const{error:a}=await r3.from("brokerage_operations_digest_prefs").upsert({user_id:n.id,brokerage_id:s,email_enabled:r.email_enabled??!1,push_enabled:r.push_enabled??!1,send_day:r.send_day??1},{onConflict:"user_id,brokerage_id"});if(a)throw a},onSuccess:()=>{t.invalidateQueries({queryKey:["ops-digest-prefs",s]}),re.success("Notification settings saved")},onError:r=>re.error(r.message||"Could not save settings")})}const Ycr={license:"License renewal",eo:"E&O insurance",anniversary:"Work anniversary",birthday:"Birthday"},Xos=864e5,Qos=()=>{const s=new Date;return{y:s.getFullYear(),m:s.getMonth()+1,d:s.getDate()}},vq=(s,t,n)=>Date.UTC(s,t-1,n),Ylt=s=>{const t=LC(s);return t?new Intl.DateTimeFormat("en-US",{month:"short",day:"numeric",year:"numeric",timeZone:"UTC"}).format(new Date(Date.UTC(t.y,t.m-1,t.d))):s},UPe=s=>String(s).padStart(2,"0");function AEt(s){const t=LC(s||"");if(!t)return null;const n=Qos(),r=Math.round((vq(t.y,t.m,t.d)-vq(n.y,n.m,n.d))/Xos);return{dueDate:`${t.y}-${UPe(t.m)}-${UPe(t.d)}`,daysUntil:r,expired:r<0}}function EEt(s){const t=LC(s||"");if(!t)return null;const n=Qos();let r=n.y;vq(r,t.m,t.d)[i.agentId,i])),a=[];return s.forEach(i=>{const l=r.get(i.agent_user_id),o={agentId:i.agent_user_id,agentName:(l==null?void 0:l.name)||"Agent",avatarUrl:(l==null?void 0:l.avatarUrl)??null},c=AEt(i.license_expiration);c&&a.push({...o,kind:"license",sourceDate:i.license_expiration,detail:[i.license_state,i.license_number].filter(Boolean).join(" · ")||null,...c});const d=AEt(i.eo_expiration);d&&a.push({...o,kind:"eo",sourceDate:i.eo_expiration,detail:[i.eo_carrier,i.eo_policy_number].filter(Boolean).join(" · ")||null,...d});const u=EEt(i.anniversary_date);u&&a.push({...o,kind:"anniversary",sourceDate:i.anniversary_date,detail:u.years?`${u.years} year${u.years===1?"":"s"} with the brokerage`:null,...u});const h=EEt(i.birthday);h&&a.push({...o,kind:"birthday",sourceDate:i.birthday,detail:null,dueDate:h.dueDate,daysUntil:h.daysUntil,expired:!1})}),a.filter(i=>i.expired||i.daysUntil<=n).sort((i,l)=>i.daysUntil-l.daysUntil||i.agentName.localeCompare(l.agentName))}function Zcr(s,t,n){const r=new Map(n.map(i=>[i.userId,i])),a=new Map(t.map(i=>[i.agentId,i]));return s.filter(i=>Number(i.goal_amount)>0).map(i=>{const l=a.get(i.agent_user_id),o=r.get(i.agent_user_id),c=Number(i.goal_amount)||0,d=(o==null?void 0:o.volume)||0;return{agentId:i.agent_user_id,name:(l==null?void 0:l.name)||"Agent",avatarUrl:(l==null?void 0:l.avatarUrl)??null,goal:c,volume:d,gci:(o==null?void 0:o.gci)||0,closedDeals:(o==null?void 0:o.closedDeals)||0,pct:c>0?Math.min(999,d/c*100):0}}).sort((i,l)=>l.pct-i.pct)}const Xcr=864e5;function TX(s){const t=LC(s||"");if(!t)return null;const n=new Date,r=Date.UTC(n.getFullYear(),n.getMonth(),n.getDate());return Math.round((Date.UTC(t.y,t.m-1,t.d)-r)/Xcr)}function Qcr(s){const t=new Set(s.tasks.filter(i=>i.source_id&&(i.dismissed_at||i.status==="done"||i.source_type!=="manual")).map(i=>`${i.source_type}:${i.source_id}`)),n=[],r=i=>{t.has(`${i.sourceType}:${i.sourceId}`)||n.push(i)};s.complianceDeals.forEach(i=>{i.submitted_items>0&&r({key:`compliance-review-${i.deal_id}`,sourceType:"compliance",sourceId:`review:${i.deal_id}`,category:"compliance",title:`${i.submitted_items} document${i.submitted_items===1?"":"s"} awaiting review`,context:i.deal_name,agentName:i.agent_name,avatarUrl:i.agent_avatar_url,dueDate:i.target_close_date,daysUntil:TX(i.target_close_date),overdue:i.overdue_items>0,priority:i.overdue_items>0?"urgent":"high",url:"/brokerage/transactions",actionLabel:"Review"}),i.rejected_items>0&&r({key:`compliance-rejected-${i.deal_id}`,sourceType:"compliance",sourceId:`rejected:${i.deal_id}`,category:"compliance",title:`${i.rejected_items} item${i.rejected_items===1?"":"s"} need changes`,context:i.deal_name,agentName:i.agent_name,avatarUrl:i.agent_avatar_url,dueDate:i.target_close_date,daysUntil:TX(i.target_close_date),overdue:!1,priority:"medium",url:"/brokerage/transactions",actionLabel:"Open file"})}),s.disbursements.forEach(i=>{var o;if(i.status!=="draft"&&i.status!=="approved")return;const l=TX(i.closing_date);r({key:`disbursement-${i.id}`,sourceType:"disbursement",sourceId:i.id,category:"disbursements",title:i.status==="draft"?"Disbursement awaiting approval":"Approved disbursement awaiting payment",context:i.property_address||"Commission disbursement",agentName:((o=s.nameFor)==null?void 0:o.call(s,i.agent_user_id))??null,avatarUrl:null,dueDate:i.closing_date,daysUntil:l,overdue:l!==null&&l<0,priority:i.status==="draft"?"high":"medium",url:"/brokerage/commission-plans",actionLabel:i.status==="draft"?"Approve":"Mark paid"})}),Jos(s.agentRecords,s.renewalAgents,30).filter(i=>i.kind==="license"||i.kind==="eo").forEach(i=>{r({key:`renewal-${i.kind}-${i.agentId}`,sourceType:"renewal",sourceId:`${i.kind}:${i.agentId}:${i.dueDate}`,category:"renewals",title:i.expired?`${i.kind==="license"?"License":"E&O policy"} expired`:`${i.kind==="license"?"License":"E&O policy"} expires in ${i.daysUntil} day${i.daysUntil===1?"":"s"}`,context:i.detail||null,agentName:i.agentName,avatarUrl:i.avatarUrl,dueDate:i.dueDate,daysUntil:i.daysUntil,overdue:i.expired,priority:i.expired?"urgent":"high",url:"/brokerage/commission-plans",actionLabel:"Open record"})}),s.roster.forEach(i=>{i.overdue>0&&r({key:`onboarding-overdue-${i.agentId}`,sourceType:"onboarding",sourceId:`overdue:${i.agentId}`,category:"onboarding",title:`${i.overdue} onboarding step${i.overdue===1?"":"s"} overdue`,context:"Agent onboarding",agentName:i.name,avatarUrl:i.avatarUrl,dueDate:null,daysUntil:null,overdue:!0,priority:"high",url:"/brokerage/onboarding",actionLabel:"Open"}),i.needsReview>0&&r({key:`onboarding-review-${i.agentId}`,sourceType:"onboarding",sourceId:`review:${i.agentId}`,category:"onboarding",title:`${i.needsReview} onboarding item${i.needsReview===1?"":"s"} to review`,context:"Agent onboarding",agentName:i.name,avatarUrl:i.avatarUrl,dueDate:null,daysUntil:null,overdue:!1,priority:"medium",url:"/brokerage/onboarding",actionLabel:"Review"})}),s.followUps.forEach(i=>{const l=TX(i.due_date?i.due_date.slice(0,10):null);l===null||l>0||r({key:`recruiting-${i.id}`,sourceType:"recruiting",sourceId:i.id,category:"recruiting",title:i.title||"Recruiting follow-up",context:i.prospectName,agentName:null,avatarUrl:null,dueDate:i.due_date?i.due_date.slice(0,10):null,daysUntil:l,overdue:l<0,priority:l<0?"high":"medium",url:"/brokerage/recruiting",actionLabel:"Follow up"})}),s.helpRequests.forEach(i=>{const l=i.event_start_at?i.event_start_at.slice(0,10):null,o=TX(l);r({key:`help-${i.id}`,sourceType:"help_board",sourceId:i.id,category:"help_board",title:i.title||"Coverage needed",context:i.requesterName?`Posted by ${i.requesterName}`:"Help Board",agentName:null,avatarUrl:null,dueDate:l,daysUntil:o,overdue:o!==null&&o<0,priority:o!==null&&o<=2?"high":"low",url:`/brokerage/help-board/${i.id}`,actionLabel:"Open"})});const a={urgent:0,high:1,medium:2,low:3};return n.sort((i,l)=>{if(i.overdue!==l.overdue)return i.overdue?-1:1;if(a[i.priority]!==a[l.priority])return a[i.priority]-a[l.priority];const o=i.daysUntil??9999,c=l.daysUntil??9999;return o-c})}const Jcr={urgent:"bg-destructive/10 text-destructive border-destructive/30",high:"bg-amber-500/10 text-amber-700 border-amber-500/30 dark:text-amber-400",medium:"bg-muted text-muted-foreground border-border",low:"bg-muted text-muted-foreground border-border"},edr=s=>(s||"?").split(" ").map(t=>t[0]).filter(Boolean).slice(0,2).join("").toUpperCase();function tdr({items:s,loading:t,onDismiss:n,onTrack:r}){const a=Qn(),[i,l]=j.useState("all"),o=j.useMemo(()=>{const h=new Set(s.map(m=>m.category));return Array.from(h)},[s]),c=j.useMemo(()=>i==="all"?s:s.filter(h=>h.category===i),[s,i]),d=s.filter(h=>h.overdue).length,u=s.filter(h=>!h.overdue&&h.daysUntil!==null&&h.daysUntil<=7).length;return t?e.jsx("div",{className:"space-y-3",children:[0,1,2,3].map(h=>e.jsx(yn,{className:"h-20 w-full"},h))}):e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[e.jsx(Ne,{children:e.jsxs(Ie,{className:"p-4",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Needs attention"}),e.jsx("p",{className:"text-2xl font-semibold",children:s.length})]})}),e.jsx(Ne,{children:e.jsxs(Ie,{className:"p-4",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Overdue"}),e.jsx("p",{className:Pt("text-2xl font-semibold",d>0&&"text-destructive"),children:d})]})}),e.jsx(Ne,{children:e.jsxs(Ie,{className:"p-4",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Due this week"}),e.jsx("p",{className:"text-2xl font-semibold",children:u})]})})]}),e.jsxs(Ne,{children:[e.jsxs(Ct,{className:"flex-row items-start justify-between gap-3 space-y-0",children:[e.jsxs("div",{children:[e.jsx(At,{className:"text-base",children:"What needs your attention"}),e.jsx(Gn,{children:"Pulled live from compliance, financials, onboarding, recruiting and the help board."})]}),e.jsxs(ms,{value:i,onValueChange:l,children:[e.jsx(us,{className:"w-[160px] shrink-0",children:e.jsx(fs,{})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"all",children:"All areas"}),o.map(h=>e.jsx(Ge,{value:h,children:$Pe[h]||h},h))]})]})]}),e.jsx(Ie,{className:"space-y-2",children:c.length===0?e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(qr,{className:"mb-3 h-10 w-10 text-emerald-500"}),e.jsx("p",{className:"font-medium",children:"Nothing needs attention right now"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"New items appear here as files, renewals and requests come in."})]}):c.map(h=>e.jsxs("div",{className:Pt("flex flex-col gap-3 rounded-lg border p-3 sm:flex-row sm:items-center",h.overdue&&"border-destructive/40 bg-destructive/[0.03]"),children:[e.jsxs(Oa,{className:"h-9 w-9 shrink-0",children:[h.avatarUrl&&e.jsx(Li,{src:h.avatarUrl,alt:""}),e.jsx(za,{className:"text-xs",children:edr(h.agentName)})]}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("span",{className:"font-medium",children:h.title}),e.jsx(Be,{variant:"outline",className:Pt("text-[10px]",Jcr[h.priority]),children:$Pe[h.category]||h.category})]}),e.jsxs("div",{className:"mt-1 flex flex-wrap items-center gap-x-3 gap-y-1 text-xs text-muted-foreground",children:[h.agentName&&e.jsx("span",{children:h.agentName}),h.context&&e.jsx("span",{className:"truncate",children:h.context}),h.dueDate&&e.jsxs("span",{className:Pt("flex items-center gap-1",h.overdue&&"font-medium text-destructive"),children:[h.overdue?e.jsx(wl,{className:"h-3 w-3"}):e.jsx(Au,{className:"h-3 w-3"}),Ylt(h.dueDate)]})]})]}),e.jsxs("div",{className:"flex shrink-0 items-center gap-2",children:[e.jsx($,{size:"sm",onClick:()=>a(h.url),children:h.actionLabel}),e.jsx($,{size:"sm",variant:"outline",title:"Track as a task",onClick:()=>r({title:h.title,description:[h.agentName,h.context].filter(Boolean).join(" — ")||null,category:h.category,priority:h.priority,due_date:h.dueDate,source_type:h.sourceType,source_id:h.sourceId,source_url:h.url}),children:e.jsx(FJ,{className:"h-4 w-4"})}),e.jsx($,{size:"sm",variant:"ghost",title:"Dismiss",onClick:()=>n(h),children:e.jsx(gr,{className:"h-4 w-4"})})]})]},h.key))})]})]})}const lhe=["todo","in_progress","done"],sdr={urgent:"bg-destructive",high:"bg-amber-500",medium:"bg-primary/60",low:"bg-muted-foreground/40"};function ndr({tasks:s,people:t,loading:n,onNew:r,onEdit:a,onStatus:i,onDelete:l}){const[o,c]=j.useState("all"),[d,u]=j.useState("all"),h=j.useMemo(()=>s.filter(x=>!x.dismissed_at).filter(x=>o==="all"?!0:o==="unassigned"?!x.assignee_user_id:x.assignee_user_id===o).filter(x=>d==="all"?!0:x.category===d),[s,o,d]),m=x=>{var y;return x?((y=t.find(v=>v.id===x))==null?void 0:y.name)||"Team member":"Unassigned"},f=j.useMemo(()=>Array.from(new Set(s.map(x=>x.category))),[s]);if(n)return e.jsx(yn,{className:"h-72 w-full"});const g=(x,y)=>{const v=lhe.indexOf(x.status),b=lhe[v+y];b&&i(x,b)};return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs(ms,{value:o,onValueChange:c,children:[e.jsx(us,{className:"w-[180px]",children:e.jsx(fs,{})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"all",children:"Everyone"}),e.jsx(Ge,{value:"unassigned",children:"Unassigned"}),t.map(x=>e.jsx(Ge,{value:x.id,children:x.name},x.id))]})]}),e.jsxs(ms,{value:d,onValueChange:u,children:[e.jsx(us,{className:"w-[170px]",children:e.jsx(fs,{})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"all",children:"All categories"}),f.map(x=>e.jsx(Ge,{value:x,children:$Pe[x]||x},x))]})]}),e.jsxs($,{className:"ml-auto",onClick:r,children:[e.jsx(dn,{className:"mr-2 h-4 w-4"})," New task"]})]}),e.jsx("div",{className:"grid gap-4 md:grid-cols-3",children:lhe.map(x=>{const y=h.filter(v=>v.status===x);return e.jsxs(Ne,{className:"flex flex-col",children:[e.jsx(Ct,{className:"pb-3",children:e.jsxs(At,{className:"flex items-center justify-between text-sm",children:[hQe[x],e.jsx(Be,{variant:"secondary",children:y.length})]})}),e.jsxs(Ie,{className:"space-y-2",children:[y.length===0&&e.jsx("p",{className:"py-6 text-center text-sm text-muted-foreground",children:"Nothing here"}),y.map(v=>{const b=!!v.due_date&&v.status!=="done"&&v.due_datea(v),children:[e.jsx("p",{className:"truncate font-medium",children:v.title}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[$Pe[v.category]||v.category," · ",m(v.assignee_user_id)]})]}),e.jsxs(Uu,{children:[e.jsx(qu,{asChild:!0,children:e.jsx($,{size:"icon",variant:"ghost",className:"h-7 w-7",children:e.jsx(ty,{className:"h-4 w-4"})})}),e.jsxs(Eu,{align:"end",children:[e.jsxs(ja,{onClick:()=>a(v),children:[e.jsx(gi,{className:"mr-2 h-4 w-4"})," Edit"]}),lhe.filter(w=>w!==v.status).map(w=>e.jsxs(ja,{onClick:()=>i(v,w),children:["Move to ",hQe[w]]},w)),e.jsxs(ja,{className:"text-destructive",onClick:()=>l(v),children:[e.jsx(Wn,{className:"mr-2 h-4 w-4"})," Delete"]})]})]})]}),v.due_date&&e.jsxs("p",{className:Pt("mt-2 flex items-center gap-1 text-xs",b?"text-destructive":"text-muted-foreground"),children:[e.jsx(Au,{className:"h-3 w-3"})," ",Ylt(v.due_date)]}),e.jsxs("div",{className:"mt-2 flex gap-1 md:hidden",children:[e.jsx($,{size:"sm",variant:"outline",className:"flex-1",disabled:x==="todo",onClick:()=>g(v,-1),children:e.jsx(qa,{className:"h-4 w-4"})}),e.jsx($,{size:"sm",variant:"outline",className:"flex-1",disabled:x==="done",onClick:()=>g(v,1),children:e.jsx(ei,{className:"h-4 w-4"})})]})]},v.id)})]})]},x)})})]})}const rdr=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],TEt=(s,t,n)=>`${s}-${String(t+1).padStart(2,"0")}-${String(n).padStart(2,"0")}`;function adr({items:s,tasks:t,closings:n}){const r=new Date,[a,i]=j.useState({y:r.getFullYear(),m:r.getMonth()}),[l,o]=j.useState(null),c=j.useMemo(()=>{const b=[];return s.forEach(w=>{w.dueDate&&b.push({id:w.key,label:w.title,tone:"bg-amber-500",date:w.dueDate})}),t.filter(w=>!w.dismissed_at&&w.due_date&&w.status!=="done").forEach(w=>b.push({id:w.id,label:w.title,tone:"bg-primary",date:w.due_date})),n.forEach(w=>{w.date&&b.push({id:`close-${w.id}`,label:`Closing — ${w.label}`,tone:"bg-emerald-500",date:w.date.slice(0,10)})}),b},[s,t,n]),d=j.useMemo(()=>{const b=new Map;return c.forEach(w=>{const S=b.get(w.date)||[];S.push(w),b.set(w.date,S)}),b},[c]),u=new Date(Date.UTC(a.y,a.m,1)),h=u.getUTCDay(),m=new Date(Date.UTC(a.y,a.m+1,0)).getUTCDate(),f=[...Array.from({length:h},()=>null),...Array.from({length:m},(b,w)=>w+1)],g=new Intl.DateTimeFormat("en-US",{month:"long",year:"numeric",timeZone:"UTC"}).format(u),x=TEt(r.getFullYear(),r.getMonth(),r.getDate()),y=l?d.get(l)||[]:[],v=b=>i(w=>{const S=w.m+b;return S<0?{y:w.y-1,m:11}:S>11?{y:w.y+1,m:0}:{y:w.y,m:S}});return e.jsxs("div",{className:"grid gap-4 lg:grid-cols-[2fr,1fr]",children:[e.jsxs(Ne,{children:[e.jsxs(Ct,{className:"flex-row items-center justify-between space-y-0",children:[e.jsxs("div",{children:[e.jsx(At,{className:"text-base",children:g}),e.jsx(Gn,{children:"Closings, renewals and due dates in one place."})]}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx($,{size:"icon",variant:"outline",onClick:()=>v(-1),children:e.jsx(Cd,{className:"h-4 w-4"})}),e.jsx($,{size:"icon",variant:"outline",onClick:()=>v(1),children:e.jsx(Di,{className:"h-4 w-4"})})]})]}),e.jsxs(Ie,{children:[e.jsx("div",{className:"grid grid-cols-7 gap-1 text-center text-xs text-muted-foreground",children:rdr.map(b=>e.jsx("div",{className:"py-1",children:b},b))}),e.jsx("div",{className:"grid grid-cols-7 gap-1",children:f.map((b,w)=>{if(b===null)return e.jsx("div",{},`pad-${w}`);const S=TEt(a.y,a.m,b),C=d.get(S)||[];return e.jsxs("button",{onClick:()=>o(S),className:Pt("flex min-h-[64px] flex-col items-start rounded-md border p-1 text-left text-xs transition hover:bg-muted/60",S===x&&"border-primary",l===S&&"bg-muted"),children:[e.jsx("span",{className:Pt("mb-1 font-medium",S===x&&"text-primary"),children:b}),e.jsx("span",{className:"flex flex-wrap gap-0.5",children:C.slice(0,4).map(E=>e.jsx("span",{className:Pt("h-1.5 w-1.5 rounded-full",E.tone)},E.id))}),C.length>0&&e.jsxs("span",{className:"mt-auto text-[10px] text-muted-foreground",children:[C.length," item",C.length===1?"":"s"]})]},S)})})]})]}),e.jsxs(Ne,{children:[e.jsxs(Ct,{children:[e.jsx(At,{className:"text-base",children:l?new Intl.DateTimeFormat("en-US",{dateStyle:"medium",timeZone:"UTC"}).format(new Date(`${l}T12:00:00Z`)):"Pick a day"}),e.jsx(Gn,{children:l?`${y.length} item${y.length===1?"":"s"}`:"Select a date to see what is happening."})]}),e.jsxs(Ie,{className:"space-y-2",children:[l&&y.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"Nothing scheduled."}),y.map(b=>e.jsxs("div",{className:"flex items-start gap-2 rounded-md border p-2 text-sm",children:[e.jsx("span",{className:Pt("mt-1.5 h-2 w-2 shrink-0 rounded-full",b.tone)}),e.jsx("span",{className:"min-w-0 flex-1",children:b.label})]},b.id)),e.jsx("div",{className:"pt-2",children:e.jsxs("div",{className:"flex flex-wrap gap-2 text-xs text-muted-foreground",children:[e.jsxs(Be,{variant:"outline",children:[e.jsx("span",{className:"mr-1 h-2 w-2 rounded-full bg-emerald-500"})," Closings"]}),e.jsxs(Be,{variant:"outline",children:[e.jsx("span",{className:"mr-1 h-2 w-2 rounded-full bg-amber-500"})," Action items"]}),e.jsxs(Be,{variant:"outline",children:[e.jsx("span",{className:"mr-1 h-2 w-2 rounded-full bg-primary"})," Tasks"]})]})})]})]})]})}function idr({taskId:s,people:t}){const{data:n=[]}=Hcr(s),r=Gcr(),[a,i]=j.useState(""),l=o=>{var c;return((c=t.find(d=>d.id===o))==null?void 0:c.name)||"Team member"};return e.jsxs("div",{className:"space-y-2 rounded-lg border p-3",children:[e.jsx(ee,{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Notes"}),e.jsxs("div",{className:"space-y-2",children:[n.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"No notes yet."}),n.map(o=>e.jsxs("div",{className:"rounded-md bg-muted/50 p-2 text-sm",children:[e.jsxs("p",{className:"text-xs text-muted-foreground",children:[l(o.author_user_id)," · ",new Date(o.created_at).toLocaleDateString()]}),e.jsx("p",{className:"whitespace-pre-wrap",children:o.body})]},o.id))]}),e.jsx(Rs,{rows:2,placeholder:"Add a note…",value:a,onChange:o=>i(o.target.value)}),e.jsx($,{size:"sm",variant:"outline",disabled:!a.trim()||r.isPending,onClick:()=>r.mutate({taskId:s,body:a},{onSuccess:()=>i("")}),children:"Add note"})]})}const MEt={title:"",description:"",category:"general",status:"todo",priority:"medium",due_date:null,assignee_user_id:null};function odr({open:s,onOpenChange:t,task:n,initial:r,people:a,onSave:i,saving:l}){const[o,c]=j.useState(MEt);j.useEffect(()=>{s&&c(n?{id:n.id,title:n.title,description:n.description||"",category:n.category,status:n.status,priority:n.priority,due_date:n.due_date,assignee_user_id:n.assignee_user_id,source_type:n.source_type,source_id:n.source_id,source_url:n.source_url}:{...MEt,...r||{}})},[s,n,r]);const d=u=>c(h=>({...h,...u}));return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Os,{className:"max-h-[90vh] max-w-lg overflow-y-auto",children:[e.jsxs(Us,{children:[e.jsx(Bs,{children:n?"Edit task":"New task"}),e.jsx(Ir,{children:"Assign office work to yourself or another manager."})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"ops-title",children:"Title"}),e.jsx(pe,{id:"ops-title",value:o.title,onChange:u=>d({title:u.target.value}),placeholder:"Order new signage for the Maple listing"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"ops-desc",children:"Details"}),e.jsx(Rs,{id:"ops-desc",rows:3,value:o.description||"",onChange:u=>d({description:u.target.value})})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Category"}),e.jsxs(ms,{value:o.category,onValueChange:u=>d({category:u}),children:[e.jsx(us,{children:e.jsx(fs,{})}),e.jsx(hs,{children:Zos.map(u=>e.jsx(Ge,{value:u.value,children:u.label},u.value))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Priority"}),e.jsxs(ms,{value:o.priority,onValueChange:u=>d({priority:u}),children:[e.jsx(us,{children:e.jsx(fs,{})}),e.jsx(hs,{children:Object.entries(zcr).map(([u,h])=>e.jsx(Ge,{value:u,children:h},u))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Status"}),e.jsxs(ms,{value:o.status,onValueChange:u=>d({status:u}),children:[e.jsx(us,{children:e.jsx(fs,{})}),e.jsx(hs,{children:Object.entries(hQe).map(([u,h])=>e.jsx(Ge,{value:u,children:h},u))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"ops-due",children:"Due date"}),e.jsx(pe,{id:"ops-due",type:"date",value:o.due_date||"",onChange:u=>d({due_date:u.target.value||null})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Assigned to"}),e.jsxs(ms,{value:o.assignee_user_id||"unassigned",onValueChange:u=>d({assignee_user_id:u==="unassigned"?null:u}),children:[e.jsx(us,{children:e.jsx(fs,{})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"unassigned",children:"Unassigned"}),a.map(u=>e.jsx(Ge,{value:u.id,children:u.name},u.id))]})]})]}),n&&e.jsx(idr,{taskId:n.id,people:a})]}),e.jsxs(Ar,{children:[e.jsx($,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsx($,{disabled:!o.title.trim()||l,onClick:()=>i(o),children:l?"Saving…":"Save task"})]})]})})}const ldr=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];function cdr({brokerageId:s}){const{data:t}=Wcr(s),n=Kcr(s),[r,a]=j.useState(!1),[i,l]=j.useState(!1),[o,c]=j.useState("1");return j.useEffect(()=>{a((t==null?void 0:t.email_enabled)??!1),l((t==null?void 0:t.push_enabled)??!1),c(String((t==null?void 0:t.send_day)??1))},[t]),e.jsxs(Ne,{children:[e.jsxs(Ct,{children:[e.jsx(At,{className:"text-base",children:"Weekly summary"}),e.jsx(Gn,{children:"Off by default. Turn it on and you alone get a weekly rundown of what is open, due and overdue."})]}),e.jsxs(Ie,{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between gap-4 rounded-lg border p-3",children:[e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"digest-email",children:"Email me the weekly summary"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Sent once a week to your account email."})]}),e.jsx(Sn,{id:"digest-email",checked:r,onCheckedChange:a})]}),e.jsxs("div",{className:"flex items-center justify-between gap-4 rounded-lg border p-3",children:[e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"digest-push",children:"Send me a phone notification"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Same summary, delivered as a push alert."})]}),e.jsx(Sn,{id:"digest-push",checked:i,onCheckedChange:l})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Send day"}),e.jsxs(ms,{value:o,onValueChange:c,disabled:!r&&!i,children:[e.jsx(us,{className:"w-[200px]",children:e.jsx(fs,{})}),e.jsx(hs,{children:ldr.map((d,u)=>e.jsx(Ge,{value:String(u),children:d},d))})]})]}),e.jsx($,{disabled:n.isPending,onClick:()=>n.mutate({email_enabled:r,push_enabled:i,send_day:Number(o)}),children:n.isPending?"Saving…":"Save settings"})]})]})}const ddr=()=>{const{user:s,rolesLoading:t,isBrokerageManager:n,isAdmin:r,brokerageId:a,managedBrokerages:i,selectedBrokerageId:l,setSelectedBrokerageId:o}=vs(),c=Qn(),{data:d=[],isLoading:u}=Rtt(),[h,m]=j.useState(!1),f=d.length>0,g=n||r,x=j.useMemo(()=>{var ve;return l||(i.length>0?i[0].id:null)||((ve=d[0])==null?void 0:ve.brokerage_id)||a},[l,i,d,a]);j.useEffect(()=>{if(!(!s||u||t)){if(!g&&!f){c("/dashboard");return}!l&&i.length>0&&o(i[0].id),m(!0)}},[s,u,t,g,f,c,i,l,o]);const{data:y=[],isLoading:v}=Dtt(x),{data:b=[]}=Kos(x),{data:w=[]}=Yos(x),{data:S=[]}=qXt(x),{data:C=[]}=Fcr(x),{data:E=[]}=Ocr(x),{data:I=[],isLoading:P}=Bcr(x),R=$cr(x),D=Ucr(x),O=qcr(x),U=Vcr(x),[W,V]=j.useState(!1),[G,Y]=j.useState(null),[X,ae]=j.useState(null),ie=j.useMemo(()=>S.map(ve=>({id:ve.agentId,name:ve.name})),[S]),ne=ve=>{var Ee;return ve?((Ee=ie.find(Se=>Se.id===ve))==null?void 0:Ee.name)??null:null},te=j.useMemo(()=>Qcr({complianceDeals:y,disbursements:b,agentRecords:w,renewalAgents:S.map(ve=>({agentId:ve.agentId,name:ve.name,avatarUrl:ve.avatarUrl})),roster:S.map(ve=>({agentId:ve.agentId,name:ve.name,avatarUrl:ve.avatarUrl,overdue:ve.overdue,needsReview:ve.needsReview})),followUps:C,helpRequests:E,tasks:I,nameFor:ne}),[y,b,w,S,C,E,I]),J=j.useMemo(()=>y.filter(ve=>ve.target_close_date).map(ve=>({id:ve.deal_id,label:ve.property_address||ve.deal_name,date:ve.target_close_date})),[y]),ce=()=>{Y(null),ae(null),V(!0)},_e=ve=>{Y(null),ae(ve),V(!0)},he=ve=>{Y(ve),ae(null),V(!0)},ue=ve=>U.mutate({sourceType:ve.sourceType,sourceId:ve.sourceId,title:ve.title,category:ve.category});return h?e.jsx(Vs,{title:"Operations",description:"Everything that needs a decision today, plus your office task board and calendar",children:e.jsxs("div",{className:"space-y-6",children:[i.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(ms,{value:l||"",onValueChange:o,children:[e.jsxs(us,{className:"w-[280px]",children:[e.jsx(ji,{className:"mr-2 h-4 w-4"}),e.jsx(fs,{placeholder:"Select brokerage"})]}),e.jsx(hs,{children:i.map(ve=>e.jsx(Ge,{value:ve.id,children:ve.name},ve.id))})]})]}),x?e.jsxs(ha,{defaultValue:"today",className:"space-y-4",children:[e.jsx("div",{className:"overflow-x-auto pb-1",children:e.jsxs(ma,{className:"grid h-auto min-w-[460px] grid-cols-4",children:[e.jsx(Zt,{value:"today",children:"Today"}),e.jsx(Zt,{value:"tasks",children:"Task board"}),e.jsx(Zt,{value:"calendar",children:"Calendar"}),e.jsx(Zt,{value:"notifications",children:"Notifications"})]})}),e.jsx(Xt,{value:"today",children:e.jsx(tdr,{items:te,loading:v,onDismiss:ue,onTrack:_e})}),e.jsx(Xt,{value:"tasks",children:e.jsx(ndr,{tasks:I,people:ie,loading:P,onNew:ce,onEdit:he,onStatus:(ve,Ee)=>D.mutate({id:ve.id,status:Ee}),onDelete:ve=>O.mutate(ve.id)})}),e.jsx(Xt,{value:"calendar",children:e.jsx(adr,{items:te,tasks:I,closings:J})}),e.jsx(Xt,{value:"notifications",children:e.jsx(cdr,{brokerageId:x})})]}):e.jsxs("div",{className:"flex flex-col items-center justify-center py-16 text-center",children:[e.jsx(ji,{className:"mb-4 h-12 w-12 text-muted-foreground"}),e.jsx("h2",{className:"mb-1 text-xl font-semibold",children:"No Brokerage Assigned"}),e.jsx("p",{className:"text-muted-foreground",children:"You don't have any brokerages to manage."})]}),e.jsx(odr,{open:W,onOpenChange:V,task:G,initial:X,people:ie,saving:R.isPending,onSave:ve=>R.mutate(ve,{onSuccess:()=>V(!1)})})]})}):null},PEt="id, agent_id, brokerage_id, team_id, owner_type, subdomain_slug, custom_domain, site_title, org_name, org_logo_url, brand_color, is_active, created_at";function _Ue(s,t){return t?`https://${t}`:s?`https://${s}.thelocalmove.com`:null}function els(){const{user:s,isAdmin:t,isBrokerageManager:n,managedBrokerages:r,brokerageId:a,selectedBrokerageId:i}=vs(),{data:l=[]}=Dae(),o=j.useMemo(()=>l.filter(f=>f.role==="team_leader"),[l]),c=j.useMemo(()=>r.length?r:(n||t)&&a?[{id:a,name:"My brokerage"}]:[],[r,n,t,a]),d=j.useMemo(()=>c.map(f=>f.id),[c]),u=j.useMemo(()=>o.map(f=>f.teamId),[o]),h=tt({queryKey:["my-websites",s==null?void 0:s.id,d.join(","),u.join(",")],enabled:!!(s!=null&&s.id),staleTime:60*1e3,queryFn:async()=>{const[f,g]=await Promise.all([q.from("lead_sites").select(PEt).eq("agent_id",s.id).order("created_at",{ascending:!0}),d.length||u.length?q.from("lead_sites").select(PEt).or([d.length?`brokerage_id.in.(${d.join(",")})`:"",u.length?`team_id.in.(${u.join(",")})`:""].filter(Boolean).join(",")):Promise.resolve({data:[],error:null})]);if(f.error)throw f.error;if(g.error)throw g.error;return{own:(f.data||[]).filter(x=>(x.owner_type||"agent")==="agent"),org:g.data||[]}}}),m=j.useMemo(()=>{var v,b,w;const f=((v=h.data)==null?void 0:v.own)||[],g=((b=h.data)==null?void 0:b.org)||[],x=[],y=f.find(S=>S.is_active)||f[0]||null;y?x.push({kind:"agent",id:y.id,ownerId:null,name:y.site_title||"My website",kindLabel:"My agent site",slug:y.subdomain_slug,customDomain:y.custom_domain,isActive:!!y.is_active,logoUrl:null,brandColor:y.brand_color,editPath:`/my-website/${y.id}/edit`,publicUrl:_Ue(y.subdomain_slug,y.custom_domain),exists:!0}):x.push({kind:"agent",id:null,ownerId:null,name:"My agent site",kindLabel:"My agent site",slug:null,customDomain:null,isActive:!1,logoUrl:null,brandColor:null,editPath:"/need-a-website",publicUrl:null,exists:!1});for(const S of c){const C=g.find(E=>E.owner_type==="brokerage"&&E.brokerage_id===S.id)||null;x.push({kind:"brokerage",id:(C==null?void 0:C.id)??null,ownerId:S.id,name:(C==null?void 0:C.org_name)||(C==null?void 0:C.site_title)||S.name,kindLabel:"Company site",slug:(C==null?void 0:C.subdomain_slug)??null,customDomain:(C==null?void 0:C.custom_domain)??null,isActive:!!(C!=null&&C.is_active),logoUrl:(C==null?void 0:C.org_logo_url)??null,brandColor:(C==null?void 0:C.brand_color)??null,editPath:"/brokerage/website",publicUrl:_Ue((C==null?void 0:C.subdomain_slug)??null,(C==null?void 0:C.custom_domain)??null),exists:!!C})}for(const S of o){const C=g.find(E=>E.owner_type==="team"&&E.team_id===S.teamId)||null;x.push({kind:"team",id:(C==null?void 0:C.id)??null,ownerId:S.teamId,name:(C==null?void 0:C.org_name)||(C==null?void 0:C.site_title)||((w=S.team)==null?void 0:w.name)||"My team",kindLabel:"Team site",slug:(C==null?void 0:C.subdomain_slug)??null,customDomain:(C==null?void 0:C.custom_domain)??null,isActive:!!(C!=null&&C.is_active),logoUrl:(C==null?void 0:C.org_logo_url)??null,brandColor:(C==null?void 0:C.brand_color)??null,editPath:`/team/website?teamId=${S.teamId}`,publicUrl:_Ue((C==null?void 0:C.subdomain_slug)??null,(C==null?void 0:C.custom_domain)??null),exists:!!C})}return x},[h.data,c,o]);return{websites:m,isLoading:h.isLoading,ledTeams:o,hasOrgSites:m.some(f=>f.kind!=="agent")}}const udr={agent:dl,brokerage:ji,team:Zn};function hdr({site:s}){const t=Qn(),n=udr[s.kind],r=s.customDomain||(s.slug?`${s.slug}.thelocalmove.com`:null);return e.jsx(Ne,{className:"overflow-hidden transition-shadow hover:shadow-md",children:e.jsxs(Ie,{className:"flex flex-col gap-5 p-6 sm:flex-row sm:items-center",children:[e.jsx("div",{className:"flex h-16 w-16 shrink-0 items-center justify-center overflow-hidden rounded-xl",style:{backgroundColor:s.brandColor||"hsl(var(--muted))"},children:s.logoUrl?e.jsx("img",{src:s.logoUrl,alt:"",className:"max-h-full max-w-full object-contain"}):e.jsx(n,{className:`h-7 w-7 ${s.brandColor?"text-white":"text-muted-foreground"}`})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("p",{className:"truncate text-lg font-semibold",children:s.name}),s.exists?s.isActive?e.jsx(Be,{children:"Live"}):e.jsx(Be,{variant:"secondary",children:"Private preview"}):e.jsx(Be,{variant:"outline",children:"Not created yet"})]}),e.jsx("p",{className:"mt-1 text-sm text-muted-foreground",children:s.kindLabel}),e.jsx("p",{className:"mt-1 truncate text-sm text-muted-foreground",children:r||"Pick a web address when you create it"})]}),e.jsxs("div",{className:"flex shrink-0 flex-wrap gap-2",children:[s.exists&&s.publicUrl&&e.jsx($,{variant:"outline",asChild:!0,children:e.jsxs("a",{href:s.publicUrl,target:"_blank",rel:"noreferrer",children:[e.jsx(kr,{className:"mr-2 h-4 w-4"})," View"]})}),e.jsx($,{onClick:()=>t(s.editPath),children:s.exists?e.jsxs(e.Fragment,{children:[e.jsx(gi,{className:"mr-2 h-4 w-4"})," Edit site"]}):e.jsxs(e.Fragment,{children:[e.jsx(dn,{className:"mr-2 h-4 w-4"})," Create site"]})})]})]})})}function mdr(){const{websites:s,isLoading:t}=els();return e.jsx(Vs,{title:"My Websites",description:"Every website you can edit, in one place",children:e.jsx("div",{className:"mx-auto max-w-4xl space-y-4 p-4 lg:p-8",children:t?[0,1].map(n=>e.jsx("div",{className:"h-32 animate-pulse rounded-xl bg-muted"},n)):e.jsxs(e.Fragment,{children:[s.map(n=>e.jsx(hdr,{site:n},`${n.kind}-${n.ownerId||"me"}`)),e.jsxs("p",{className:"pt-2 text-center text-sm text-muted-foreground",children:["Looking for lead magnets, pop-ups and other add-ons?"," ",e.jsx(wr,{to:"/website-apps",className:"underline",children:"Website Apps"})]})]})})})}const IEt={bold_national:{display:"'Archivo', 'Helvetica Neue', Arial, sans-serif",body:"'Inter', system-ui, sans-serif",radius:"0.25rem"},editorial_boutique:{display:"'Playfair Display', Georgia, serif",body:"'Inter', system-ui, sans-serif",radius:"0px"},modern_minimal:{display:"'Sora', system-ui, sans-serif",body:"'Manrope', system-ui, sans-serif",radius:"0.75rem"},coastal_luxury:{display:"'Cormorant Garamond', Georgia, serif",body:"'Karla', system-ui, sans-serif",radius:"0.5rem"}};function TCr(s,t){var a;const n=(t==null?void 0:t.orgPreset)||((a=s==null?void 0:s.themeConfig)==null?void 0:a.orgPreset)||"editorial_boutique",r=IEt[n]||IEt.editorial_boutique;return{primary:(s==null?void 0:s.brandColor)||(t==null?void 0:t.primaryColor)||"#12222e",accent:(s==null?void 0:s.accentColor)||(t==null?void 0:t.accentColor)||"#c9a96e",display:r.display,body:r.body,radius:r.radius,name:(s==null?void 0:s.orgName)||(s==null?void 0:s.siteTitle)||"Our Company",logoUrl:(s==null?void 0:s.orgLogoUrl)||(s==null?void 0:s.teamLogoUrl)||null,logoDarkUrl:(s==null?void 0:s.orgLogoDarkUrl)||(s==null?void 0:s.orgLogoUrl)||(s==null?void 0:s.teamLogoUrl)||null}}const tls=[{key:"bold_national",label:"Bold National",description:"Confident, bold type and a tight grid — national franchise energy."},{key:"editorial_boutique",label:"Editorial Boutique",description:"Serif display type and magazine layouts for a boutique feel."},{key:"modern_minimal",label:"Modern Minimal",description:"Clean geometry, generous whitespace, soft rounded cards."},{key:"coastal_luxury",label:"Coastal Luxury",description:"Airy, elegant serif with warm light and wide imagery."}];function sls(s){return(s==null?void 0:s.orgProfile)||{}}function MCr(s){const t=(s==null?void 0:s.ownerType)==="team";return{isTeam:t,org:t?"team":"brokerage",people:t?"Our Team":"Our Agents",meetPeople:t?"Meet Our Team":"Meet Our Agents",peopleNoun:t?"team members":"agents",joinShort:t?"Join Our Team":"Join Us",joinTitle:t?"Join Our Team":"Careers"}}function PCr(s){var n;if((s==null?void 0:s.ownerType)!=="team")return null;const t=(n=sls(s).affiliation)==null?void 0:n.trim();return t||null}function ICr(s){const t=sls(s),n=(t.offices||[]).filter(o=>o&&(o.address||o.city||o.phone||o.email)),r=n[0]||{},a=[r.name||null,r.address||null,[r.city,r.state].filter(Boolean).join(", ")+(r.zip?` ${r.zip}`:"")].filter(o=>!!o&&o.trim().length>0),i=[{label:"Facebook",url:t.facebookUrl},{label:"Instagram",url:t.instagramUrl},{label:"LinkedIn",url:t.linkedinUrl},{label:"YouTube",url:t.youtubeUrl}].filter(o=>!!o.url),l=s!=null&&s.brokerageLicenseNumber?`License #${s.brokerageLicenseNumber}${s!=null&&s.licenseState?` (${s.licenseState})`:""}`:null;return{phone:r.phone||null,email:r.email||null,addressLines:a,hours:r.hours||null,offices:n,social:i,legalName:(s==null?void 0:s.brokerageLegalName)||null,licenseLine:l}}const fdr=10*1024*1024;function wUe({label:s,hint:t,value:n,onChange:r,slot:a,siteId:i,dark:l,className:o}){const c=j.useRef(null),[d,u]=j.useState(!1),[h,m]=j.useState(!1),f=async g=>{if(!g.type.startsWith("image/")){re.error("Please choose an image file");return}if(g.size>fdr){re.error("Image must be under 10MB");return}u(!0);try{const x=(g.name.split(".").pop()||"png").toLowerCase(),y=`org-sites/${i}/${a}-${Date.now()}.${x}`,{error:v}=await q.storage.from("agent-uploads").upload(y,g,{upsert:!0,contentType:g.type});if(v)throw v;const{data:b}=q.storage.from("agent-uploads").getPublicUrl(y);r(b.publicUrl),re.success(`${s} uploaded`)}catch(x){re.error(x.message||"Upload failed")}finally{u(!1),c.current&&(c.current.value="")}};return e.jsxs("div",{className:o,children:[e.jsx(ee,{className:"text-sm font-medium",children:s}),t&&e.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:t}),e.jsxs("div",{onDragOver:g=>{g.preventDefault(),m(!0)},onDragLeave:()=>m(!1),onDrop:g=>{var y;g.preventDefault(),m(!1);const x=(y=g.dataTransfer.files)==null?void 0:y[0];x&&f(x)},onClick:()=>{var g;return!d&&((g=c.current)==null?void 0:g.click())},className:`mt-2 flex cursor-pointer items-center gap-4 rounded-lg border-2 border-dashed p-4 transition-colors ${h?"border-primary bg-primary/5":"border-muted-foreground/25 hover:border-muted-foreground/50"}`,children:[e.jsx("div",{className:`flex h-20 w-28 shrink-0 items-center justify-center overflow-hidden rounded-md ${l?"bg-slate-900":"bg-muted"}`,children:n?e.jsx("img",{src:n,alt:s,className:"max-h-full max-w-full object-contain"}):e.jsx(Mc,{className:"h-6 w-6 text-muted-foreground"})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"text-sm font-medium",children:d?"Uploading…":n?"Replace image":"Drag an image here, or click to choose"}),e.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:"PNG, JPG or SVG up to 10MB"})]}),d?e.jsx(kt,{className:"h-4 w-4 animate-spin text-muted-foreground"}):e.jsx(ni,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsx("input",{ref:c,type:"file",accept:"image/*",className:"hidden",onChange:g=>{var y;const x=(y=g.target.files)==null?void 0:y[0];x&&f(x)}}),e.jsxs("div",{className:"mt-2 flex items-center gap-2",children:[e.jsx(pe,{value:n||"",onChange:g=>r(g.target.value||null),placeholder:"…or paste an image URL",className:"h-9 text-xs"}),n&&e.jsx($,{type:"button",variant:"ghost",size:"icon",className:"h-9 w-9 shrink-0",onClick:()=>r(null),children:e.jsx(Wn,{className:"h-4 w-4"})})]})]})}const pdr="id, agent_id, subdomain_slug, custom_domain, site_title, site_tagline, is_active, brand_color, accent_color, theme_config, owner_type, org_tier, org_name, org_logo_url, org_logo_dark_url, org_profile, brokerage_id, team_id";function gdr(s){const{brokerageId:t,teamId:n}=s;return tt({queryKey:["org-site",t,n],enabled:!!(t||n),queryFn:async()=>{let r=q.from("lead_sites").select(pdr).limit(1);r=n?r.eq("team_id",n).eq("owner_type","team"):r.eq("brokerage_id",t).eq("owner_type","brokerage");const{data:a,error:i}=await r.maybeSingle();if(i)throw i;return a??null}})}function xdr(s){return tt({queryKey:["org-site-roster-admin",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await q.from("org_site_agents").select("id, site_id, user_id, display_order, is_featured, is_visible, profile_slug, headline, blurb, specialties, languages").eq("site_id",s).order("display_order",{ascending:!0});if(n)throw n;const r=t||[];if(!r.length)return[];const{data:a}=await q.from("profiles").select("id, name, avatar_url, email, title").in("id",r.map(l=>l.user_id)),i=new Map((a||[]).map(l=>[l.id,l]));return r.map(l=>({...l,profile:i.get(l.user_id)}))}})}function ydr(s){const t=Vt();return ft({mutationFn:async()=>{const{data:n,error:r}=await q.rpc("sync_org_site_roster",{p_site_id:s});if(r)throw r;return n},onSuccess:n=>{t.invalidateQueries({queryKey:["org-site-roster-admin",s]}),t.invalidateQueries({queryKey:["org-site-roster",s]}),re.success(n?`${n} agent${n===1?"":"s"} added to the roster.`:"Roster is already up to date.")},onError:n=>re.error(n.message||"Could not refresh the roster.")})}function vdr(s){const t=Vt();return ft({mutationFn:async({id:n,patch:r})=>{const{error:a}=await q.from("org_site_agents").update(r).eq("id",n);if(a)throw a},onSuccess:()=>{t.invalidateQueries({queryKey:["org-site-roster-admin",s]}),t.invalidateQueries({queryKey:["org-site-roster",s]})},onError:n=>re.error(n.message||"Could not save that change.")})}function bdr(s){const t=Vt();return ft({mutationFn:async n=>{const{error:r}=await q.from("lead_sites").update(n).eq("id",s);if(r)throw r},onSuccess:()=>{t.invalidateQueries({queryKey:["org-site"]}),re.success("Saved.")},onError:n=>re.error(n.message||"Could not save the website.")})}function che(s){return s.toLowerCase().trim().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"").slice(0,40)}function Zlt({brokerageId:s,teamId:t,orgLabel:n="brokerage"}){const{data:r,isLoading:a,refetch:i}=gdr({brokerageId:s,teamId:t});return a?e.jsx("div",{className:"flex h-40 items-center justify-center",children:e.jsx("div",{className:"h-6 w-6 animate-spin rounded-full border-2 border-primary border-t-transparent"})}):r?e.jsx(wdr,{site:r,orgLabel:n}):e.jsx(_dr,{brokerageId:s,teamId:t,orgLabel:n,onCreated:()=>i()})}function _dr({brokerageId:s,teamId:t,orgLabel:n,onCreated:r}){const{user:a}=vs(),[i,l]=j.useState(""),[o,c]=j.useState(""),[d,u]=j.useState("editorial_boutique"),[h,m]=j.useState(!1),[f,g]=j.useState(null);j.useEffect(()=>{let y=!1;return(async()=>{if(t){const{data:S}=await q.from("teams").select("name, description, avatar_url, brokerage_id").eq("id",t).maybeSingle();if(y||!S)return;const C=S.name||"";C&&(l(P=>P||C),c(P=>P||che(C)));let E=null,I=null;if(S.brokerage_id){const[{data:P},{data:R}]=await Promise.all([q.from("brokerages").select("name").eq("id",S.brokerage_id).maybeSingle(),q.from("brokerage_brand_profiles").select("primary_color, accent_color, legal_name, license_number").eq("brokerage_id",S.brokerage_id).maybeSingle()]);E=(P==null?void 0:P.name)||null,I=R}if(y)return;g({logo:S.avatar_url||null,primary:(I==null?void 0:I.primary_color)||null,accent:(I==null?void 0:I.accent_color)||null,legalName:(I==null?void 0:I.legal_name)||null,license:(I==null?void 0:I.license_number)||null,about:S.description||null,affiliation:E});return}if(!s)return;const[{data:v},{data:b}]=await Promise.all([q.from("brokerage_brand_profiles").select("logo_url, primary_color, accent_color, legal_name, license_number").eq("brokerage_id",s).maybeSingle(),q.from("brokerages").select("name").eq("id",s).maybeSingle()]);if(y)return;const w=(b==null?void 0:b.name)||"";w&&(l(S=>S||w),c(S=>S||che(w))),g({logo:(v==null?void 0:v.logo_url)||null,primary:(v==null?void 0:v.primary_color)||null,accent:(v==null?void 0:v.accent_color)||null,legalName:(v==null?void 0:v.legal_name)||null,license:(v==null?void 0:v.license_number)||null,about:null,affiliation:null})})(),()=>{y=!0}},[s,t]);const x=async()=>{if(!a||!s&&!t)return;if(!i.trim()||!o.trim()){re.error(`Add a ${n} name and web address.`);return}m(!0);const{error:y}=await q.from("lead_sites").insert({agent_id:a.id,brokerage_id:t?null:s,team_id:t||null,owner_type:t?"team":"brokerage",org_tier:"essential",org_name:i.trim(),site_title:i.trim(),subdomain_slug:o.trim(),is_active:!1,org_logo_url:(f==null?void 0:f.logo)||null,brand_color:(f==null?void 0:f.primary)||"#12222e",accent_color:(f==null?void 0:f.accent)||"#c9a96e",brokerage_legal_name:(f==null?void 0:f.legalName)||null,brokerage_license_number:(f==null?void 0:f.license)||null,org_profile:{offices:[{name:t?`${i.trim()} — Office`:`${i.trim()} — Main Office`}],...f!=null&&f.about?{about:f.about}:{},...f!=null&&f.affiliation?{affiliation:f.affiliation}:{}},theme_config:{orgPreset:d}});if(m(!1),y){re.error(y.message.includes("duplicate")?"That web address is taken — try another.":y.message);return}re.success("Website created as a private preview."),r()};return e.jsxs(Ne,{children:[e.jsxs(Ct,{children:[e.jsxs(At,{className:"flex items-center gap-2",children:[e.jsx(dl,{className:"h-5 w-5"})," Create your ",n," website"]}),e.jsxs(Gn,{children:["One site for your whole ",n," — every agent's profile, every listing, city pages, blog, recruiting page and lead capture straight into LevelUp. It starts as a private preview that only you can see."]})]}),e.jsxs(Ie,{className:"space-y-5",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:n==="team"?"Team name":"Company name"}),e.jsx(pe,{value:i,onChange:y=>{l(y.target.value),o||c(che(y.target.value))},placeholder:n==="team"?"The Bishop Group":"RE/MAX Executives"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Web address"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(pe,{value:o,onChange:y=>c(che(y.target.value)),placeholder:"bishop-group"}),e.jsx("span",{className:"whitespace-nowrap text-sm text-muted-foreground",children:".thelocalmove.com"})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"You can point your own domain at it later."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Design"}),e.jsx("div",{className:"grid gap-3 sm:grid-cols-2",children:tls.map(y=>e.jsxs("button",{type:"button",onClick:()=>u(y.key),className:`rounded-lg border p-4 text-left transition-colors ${d===y.key?"border-primary bg-primary/5":"border-border hover:border-primary/40"}`,children:[e.jsx("p",{className:"font-medium",children:y.label}),e.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:y.description})]},y.key))})]}),(f==null?void 0:f.logo)&&e.jsx("p",{className:"text-xs text-muted-foreground",children:"We'll start the site with your company logo and brand colors — you can change them anytime."}),e.jsx($,{onClick:x,disabled:h,className:"w-full",children:h?"Creating…":"Create website"})]})]})}function wdr({site:s,orgLabel:t}){var X;const{isAdmin:n}=vs(),r=bdr(s.id),{data:a=[],isLoading:i}=xdr(s.id),l=ydr(s.id),o=vdr(s.id),[c,d]=j.useState(s.site_title||""),[u,h]=j.useState(s.site_tagline||""),[m,f]=j.useState(s.org_name||""),[g,x]=j.useState(s.org_logo_url||null),[y,v]=j.useState(s.org_logo_dark_url||null),[b,w]=j.useState(s.org_profile||{}),S=(ae,ie)=>w(ne=>({...ne,[ae]:ie})),C=b.offices||[],E=(ae,ie)=>S("offices",C.map((ne,te)=>te===ae?{...ne,...ie}:ne)),I=b.stats||[],[P,R]=j.useState(s.brand_color||"#12222e"),[D,O]=j.useState(s.accent_color||"#c9a96e"),[U,W]=j.useState(s.custom_domain||""),V=((X=s.theme_config)==null?void 0:X.orgPreset)||"editorial_boutique",G=s.custom_domain?`https://${s.custom_domain}`:`https://${s.subdomain_slug}.thelocalmove.com`,Y=`${G}?previewSlug=${s.subdomain_slug}`;return e.jsxs("div",{className:"space-y-6",children:[e.jsx(Ne,{children:e.jsxs(Ct,{className:"flex-row items-start justify-between gap-4 space-y-0",children:[e.jsxs("div",{children:[e.jsxs(At,{className:"flex flex-wrap items-center gap-2",children:[s.org_name||s.site_title,e.jsx(Be,{variant:s.is_active?"default":"secondary",children:s.is_active?"Live":"Preview"}),e.jsx(Be,{variant:"outline",children:s.org_tier==="pro"?"Pro (IDX)":"Essential"})]}),e.jsx(Gn,{children:G})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx($,{variant:"outline",size:"sm",asChild:!0,children:e.jsxs("a",{href:s.is_active?G:Y,target:"_blank",rel:"noreferrer",children:[e.jsx(kr,{className:"mr-2 h-4 w-4"})," Preview"]})}),e.jsxs("div",{className:"flex items-center gap-2 rounded-md border px-3 py-2",children:[e.jsx("span",{className:"text-sm",children:"Published"}),e.jsx(Sn,{checked:s.is_active,onCheckedChange:ae=>r.mutate({is_active:ae})})]})]})]})}),e.jsxs(ha,{defaultValue:"brand",children:[e.jsxs(ma,{className:"h-auto flex-wrap justify-start gap-1",children:[e.jsx(Zt,{value:"brand",children:"Identity"}),e.jsx(Zt,{value:"story",children:"Story"}),e.jsx(Zt,{value:"offices",children:"Offices"}),e.jsx(Zt,{value:"social",children:"Social"}),e.jsxs(Zt,{value:"agents",children:["Agents (",a.length,")"]}),e.jsx(Zt,{value:"domain",children:"Address"}),e.jsx(Zt,{value:"plan",children:"Plan"})]}),e.jsx(Xt,{value:"brand",className:"mt-6",children:e.jsxs(Ne,{children:[e.jsxs(Ct,{children:[e.jsx(At,{children:"Brand & content"}),e.jsx(Gn,{children:"The look adapts to your colors, logo and chosen design."})]}),e.jsxs(Ie,{className:"space-y-5",children:[e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:t==="team"?"Team name":"Company name"}),e.jsx(pe,{value:m,onChange:ae=>f(ae.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Headline"}),e.jsx(pe,{value:c,onChange:ae=>d(ae.target.value)})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Tagline"}),e.jsx(Rs,{rows:2,value:u,onChange:ae=>h(ae.target.value)})]}),t==="team"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Brokerage the team hangs its license with"}),e.jsx(pe,{value:b.affiliation||"",onChange:ae=>S("affiliation",ae.target.value),placeholder:"RE/MAX Integrity"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Shown quietly in the footer and on the About page — most states require a team's advertising to name the brokerage."})]}),e.jsxs("div",{className:"grid gap-5 sm:grid-cols-2",children:[e.jsx(wUe,{label:t==="team"?"Team logo":"Company logo",hint:"Shown in the header. Use a version that reads well on white.",value:g,onChange:x,slot:"logo",siteId:s.id}),e.jsx(wUe,{label:"Logo for dark backgrounds",hint:"Optional — used in the footer and dark headers.",value:y,onChange:v,slot:"logo-dark",siteId:s.id,dark:!0})]}),e.jsx(wUe,{label:"Homepage hero image",hint:"A wide photo of your market, office or team. 2000px wide works best.",value:b.heroImageUrl,onChange:ae=>S("heroImageUrl",ae||void 0),slot:"hero",siteId:s.id}),e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Primary color"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx("input",{type:"color",value:P,onChange:ae=>R(ae.target.value),className:"h-10 w-14 rounded border"}),e.jsx(pe,{value:P,onChange:ae=>R(ae.target.value)})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Accent color"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx("input",{type:"color",value:D,onChange:ae=>O(ae.target.value),className:"h-10 w-14 rounded border"}),e.jsx(pe,{value:D,onChange:ae=>O(ae.target.value)})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Design"}),e.jsx("div",{className:"grid gap-3 sm:grid-cols-2",children:tls.map(ae=>e.jsxs("button",{type:"button",onClick:()=>r.mutate({theme_config:{...s.theme_config||{},orgPreset:ae.key}}),className:`rounded-lg border p-4 text-left transition-colors ${V===ae.key?"border-primary bg-primary/5":"border-border hover:border-primary/40"}`,children:[e.jsx("p",{className:"font-medium",children:ae.label}),e.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:ae.description})]},ae.key))})]}),e.jsx($,{onClick:()=>r.mutate({org_name:m||null,site_title:c||null,site_tagline:u||null,org_logo_url:g||null,org_logo_dark_url:y||null,org_profile:b,brand_color:P,accent_color:D}),disabled:r.isPending,children:r.isPending?"Saving…":"Save changes"})]})]})}),e.jsx(Xt,{value:"story",className:"mt-6",children:e.jsxs(Ne,{children:[e.jsxs(Ct,{children:[e.jsx(At,{children:"Your story"}),e.jsxs(Gn,{children:["This is your ",t," speaking — not any individual agent. It fills the About page and the homepage numbers."]})]}),e.jsxs(Ie,{className:"space-y-5",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ee,{children:["About ",t==="team"?"the team":"the company"]}),e.jsx(Rs,{rows:7,value:b.about||"",onChange:ae=>S("about",ae.target.value),placeholder:"Who you are, how long you've served the area, and what clients can expect."})]}),e.jsx("div",{className:"grid gap-4 sm:grid-cols-2",children:e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Founded"}),e.jsx(pe,{value:b.foundedYear||"",onChange:ae=>S("foundedYear",ae.target.value),placeholder:"1998"})]})}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Why agents join us"}),e.jsx(Rs,{rows:4,value:b.whyJoin||"",onChange:ae=>S("whyJoin",ae.target.value),placeholder:"Shown on your careers page and the homepage recruiting section."})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx(ee,{children:"Homepage numbers"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Up to four. Leave empty and we'll show agent, listing and market counts automatically."}),I.map((ae,ie)=>e.jsxs("div",{className:"flex gap-2",children:[e.jsx(pe,{value:ae.value,onChange:ne=>S("stats",I.map((te,J)=>J===ie?{...te,value:ne.target.value}:te)),placeholder:"$412M",className:"max-w-[140px]"}),e.jsx(pe,{value:ae.label,onChange:ne=>S("stats",I.map((te,J)=>J===ie?{...te,label:ne.target.value}:te)),placeholder:"Sold last year"}),e.jsx($,{variant:"ghost",size:"icon",onClick:()=>S("stats",I.filter((ne,te)=>te!==ie)),children:e.jsx(Wn,{className:"h-4 w-4"})})]},ie)),I.length<4&&e.jsxs($,{variant:"outline",size:"sm",onClick:()=>S("stats",[...I,{label:"",value:""}]),children:[e.jsx(dn,{className:"mr-2 h-4 w-4"})," Add a number"]})]}),e.jsx($,{onClick:()=>r.mutate({org_profile:b}),disabled:r.isPending,children:r.isPending?"Saving…":"Save story"})]})]})}),e.jsx(Xt,{value:"offices",className:"mt-6",children:e.jsxs(Ne,{children:[e.jsxs(Ct,{children:[e.jsx(At,{children:"Offices"}),e.jsx(Gn,{children:"These appear on your contact page and in the footer. The first one is your main office."})]}),e.jsxs(Ie,{className:"space-y-5",children:[C.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"No offices yet — add your main office so visitors can reach you."}),C.map((ae,ie)=>e.jsxs("div",{className:"space-y-3 rounded-lg border p-4",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("p",{className:"text-sm font-medium",children:ie===0?"Main office":`Office ${ie+1}`}),e.jsx($,{variant:"ghost",size:"icon",onClick:()=>S("offices",C.filter((ne,te)=>te!==ie)),children:e.jsx(Wn,{className:"h-4 w-4"})})]}),e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2",children:[e.jsx(pe,{value:ae.name||"",onChange:ne=>E(ie,{name:ne.target.value}),placeholder:"Office name"}),e.jsx(pe,{value:ae.phone||"",onChange:ne=>E(ie,{phone:ne.target.value}),placeholder:"Phone"}),e.jsx(pe,{value:ae.email||"",onChange:ne=>E(ie,{email:ne.target.value}),placeholder:"Email"}),e.jsx(pe,{value:ae.hours||"",onChange:ne=>E(ie,{hours:ne.target.value}),placeholder:"Mon–Fri 9–5"}),e.jsx(pe,{value:ae.address||"",onChange:ne=>E(ie,{address:ne.target.value}),placeholder:"Street address"}),e.jsxs("div",{className:"grid grid-cols-3 gap-2",children:[e.jsx(pe,{value:ae.city||"",onChange:ne=>E(ie,{city:ne.target.value}),placeholder:"City"}),e.jsx(pe,{value:ae.state||"",onChange:ne=>E(ie,{state:ne.target.value}),placeholder:"ST"}),e.jsx(pe,{value:ae.zip||"",onChange:ne=>E(ie,{zip:ne.target.value}),placeholder:"ZIP"})]})]})]},ie)),e.jsxs("div",{className:"flex flex-wrap gap-3",children:[e.jsxs($,{variant:"outline",size:"sm",onClick:()=>S("offices",[...C,{}]),children:[e.jsx(dn,{className:"mr-2 h-4 w-4"})," Add an office"]}),e.jsx($,{onClick:()=>r.mutate({org_profile:b}),disabled:r.isPending,children:r.isPending?"Saving…":"Save offices"})]})]})]})}),e.jsx(Xt,{value:"social",className:"mt-6",children:e.jsxs(Ne,{children:[e.jsxs(Ct,{children:[e.jsx(At,{children:"Social profiles"}),e.jsxs(Gn,{children:["Your ",t," accounts — linked in the footer and on the contact page."]})]}),e.jsxs(Ie,{className:"space-y-4",children:[e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Facebook"}),e.jsx(pe,{value:b.facebookUrl||"",onChange:ae=>S("facebookUrl",ae.target.value),placeholder:"https://facebook.com/…"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Instagram"}),e.jsx(pe,{value:b.instagramUrl||"",onChange:ae=>S("instagramUrl",ae.target.value),placeholder:"https://instagram.com/…"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"LinkedIn"}),e.jsx(pe,{value:b.linkedinUrl||"",onChange:ae=>S("linkedinUrl",ae.target.value),placeholder:"https://linkedin.com/company/…"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"YouTube"}),e.jsx(pe,{value:b.youtubeUrl||"",onChange:ae=>S("youtubeUrl",ae.target.value),placeholder:"https://youtube.com/@…"})]})]}),e.jsx($,{onClick:()=>r.mutate({org_profile:b}),disabled:r.isPending,children:r.isPending?"Saving…":"Save social links"})]})]})}),e.jsx(Xt,{value:"agents",className:"mt-6",children:e.jsxs(Ne,{children:[e.jsxs(Ct,{className:"flex-row items-start justify-between gap-4 space-y-0",children:[e.jsxs("div",{children:[e.jsx(At,{children:"Agent roster"}),e.jsx(Gn,{children:"Everyone here gets a profile page on your site with their own listings."})]}),e.jsxs($,{variant:"outline",size:"sm",onClick:()=>l.mutate(),disabled:l.isPending,children:[e.jsx(ro,{className:`mr-2 h-4 w-4 ${l.isPending?"animate-spin":""}`})," Refresh from LevelUp"]})]}),e.jsx(Ie,{className:"space-y-3",children:i?e.jsx("p",{className:"py-8 text-center text-sm text-muted-foreground",children:"Loading roster…"}):a.length===0?e.jsx("p",{className:"py-8 text-center text-sm text-muted-foreground",children:"No agents yet — click “Refresh from LevelUp” to pull in your agents."}):a.map(ae=>{var ie,ne,te,J;return e.jsxs("div",{className:"flex flex-wrap items-center gap-4 rounded-lg border p-4",children:[(ie=ae.profile)!=null&&ie.avatar_url?e.jsx("img",{src:ae.profile.avatar_url,alt:"",className:"h-11 w-11 rounded-full object-cover object-top"}):e.jsx("div",{className:"h-11 w-11 rounded-full bg-muted"}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"truncate font-medium",children:((ne=ae.profile)==null?void 0:ne.name)||"Unnamed agent"}),e.jsx("p",{className:"truncate text-xs text-muted-foreground",children:ae.headline||((te=ae.profile)==null?void 0:te.title)||((J=ae.profile)==null?void 0:J.email)})]}),e.jsxs($,{variant:ae.is_featured?"default":"outline",size:"sm",onClick:()=>o.mutate({id:ae.id,patch:{is_featured:!ae.is_featured}}),children:[e.jsx(Ja,{className:"mr-2 h-4 w-4"})," ",ae.is_featured?"Featured":"Feature"]}),e.jsxs($,{variant:"ghost",size:"sm",onClick:()=>o.mutate({id:ae.id,patch:{is_visible:!ae.is_visible}}),children:[ae.is_visible?e.jsx(Ca,{className:"mr-2 h-4 w-4"}):e.jsx($g,{className:"mr-2 h-4 w-4"}),ae.is_visible?"Shown":"Hidden"]})]},ae.id)})})]})}),e.jsx(Xt,{value:"domain",className:"mt-6",children:e.jsxs(Ne,{children:[e.jsxs(Ct,{children:[e.jsx(At,{children:"Web address"}),e.jsx(Gn,{children:"Use the free address or point your own domain at the site."})]}),e.jsxs(Ie,{className:"space-y-5",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Free address"}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[s.subdomain_slug,".thelocalmove.com"]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Your own domain"}),e.jsx(pe,{value:U,onChange:ae=>W(ae.target.value.trim().toLowerCase()),placeholder:"www.yourcompany.com"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Add the domain here, then point its DNS to LevelUp. Our team confirms it once the DNS is in place."})]}),e.jsx($,{onClick:()=>r.mutate({custom_domain:U||null}),disabled:r.isPending,children:r.isPending?"Saving…":"Save address"})]})]})}),e.jsxs(Xt,{value:"plan",className:"mt-6 space-y-5",children:[e.jsxs("div",{className:"grid gap-5 md:grid-cols-2",children:[e.jsxs(Ne,{className:s.org_tier==="essential"?"border-primary":"",children:[e.jsxs(Ct,{children:[e.jsx(At,{children:"Essential"}),e.jsx(Gn,{children:"Everything except live MLS search."})]}),e.jsxs(Ie,{className:"space-y-2 text-sm text-muted-foreground",children:[e.jsx("p",{children:"• Company homepage, about and contact"}),e.jsx("p",{children:"• Full agent roster with individual profile pages"}),e.jsx("p",{children:"• Every agent's Listing Exchange listings"}),e.jsx("p",{children:"• Blog, city pages, SEO and lead capture"}),e.jsx("p",{children:"• Recruiting page tied to your pipeline"})]})]}),e.jsxs(Ne,{className:s.org_tier==="pro"?"border-primary":"",children:[e.jsxs(Ct,{children:[e.jsxs(At,{className:"flex items-center gap-2",children:[e.jsx(Nn,{className:"h-4 w-4"})," Pro"]}),e.jsx(Gn,{children:"Everything in Essential, plus live MLS."})]}),e.jsxs(Ie,{className:"space-y-2 text-sm text-muted-foreground",children:[e.jsx("p",{children:"• Full IDX property search"}),e.jsx("p",{children:"• Office listing feed and sold comps"}),e.jsx("p",{children:"• Saved searches and buyer alerts"}),e.jsx("p",{children:"• Market reports and CMA tools"}),e.jsx("p",{className:"pt-2 text-foreground",children:s.org_tier==="pro"?"Your site is on Pro.":"Ask your LevelUp rep to switch this site to Pro — nothing gets rebuilt."})]})]})]}),n&&e.jsxs(Ne,{children:[e.jsxs(Ct,{children:[e.jsx(At,{className:"text-base",children:"Admin: plan control"}),e.jsx(Gn,{children:"Switch this site between Essential and Pro."})]}),e.jsxs(Ie,{className:"flex items-center gap-3",children:[e.jsx($,{variant:s.org_tier==="essential"?"default":"outline",size:"sm",onClick:()=>r.mutate({org_tier:"essential"}),children:"Essential"}),e.jsx($,{variant:s.org_tier==="pro"?"default":"outline",size:"sm",onClick:()=>r.mutate({org_tier:"pro"}),children:"Pro (IDX)"})]})]})]})]})]})}const LEt={agent:dl,brokerage:ji,team:Zn};function nls({current:s,className:t}){const n=Qn(),{websites:r}=els();if(r.length<2)return null;const a=r.find(l=>l.kind===s.kind&&(!s.ownerId||l.ownerId===s.ownerId))||r.find(l=>l.kind===s.kind),i=LEt[(a==null?void 0:a.kind)||"agent"];return e.jsx("div",{className:t,children:e.jsxs(Uu,{children:[e.jsx(qu,{asChild:!0,children:e.jsxs($,{variant:"outline",className:"h-auto w-full justify-between gap-3 py-2.5 sm:w-auto sm:min-w-[320px]",children:[e.jsxs("span",{className:"flex min-w-0 items-center gap-3 text-left",children:[e.jsx(i,{className:"h-4 w-4 shrink-0 text-muted-foreground"}),e.jsxs("span",{className:"min-w-0",children:[e.jsx("span",{className:"block truncate text-sm font-medium",children:(a==null?void 0:a.name)||"Choose a website"}),e.jsx("span",{className:"block text-xs text-muted-foreground",children:a==null?void 0:a.kindLabel})]})]}),e.jsx(Pw,{className:"h-4 w-4 shrink-0 text-muted-foreground"})]})}),e.jsxs(Eu,{align:"start",className:"w-[320px]",children:[e.jsx(SL,{children:"Switch website"}),r.map(l=>{const o=LEt[l.kind],c=l===a;return e.jsxs(ja,{onSelect:()=>n(l.editPath),className:"gap-3 py-2.5",children:[e.jsx(o,{className:"h-4 w-4 shrink-0 text-muted-foreground"}),e.jsxs("span",{className:"min-w-0 flex-1",children:[e.jsx("span",{className:"block truncate text-sm",children:l.name}),e.jsx("span",{className:"block text-xs text-muted-foreground",children:l.kindLabel})]}),l.exists?l.isActive?null:e.jsx(Be,{variant:"secondary",className:"shrink-0 text-[10px]",children:"Preview"}):e.jsx(Be,{variant:"outline",className:"shrink-0 text-[10px]",children:"Not created"}),c&&e.jsx(la,{className:"h-4 w-4 shrink-0"})]},`${l.kind}-${l.ownerId||"me"}`)}),e.jsx(R0,{}),e.jsxs(ja,{onSelect:()=>n("/websites"),className:"gap-3",children:[e.jsx(Qf,{className:"h-4 w-4 text-muted-foreground"})," See all my websites"]})]})]})})}function jdr(){const s=Qn(),[t]=gc(),{data:n=[],isLoading:r}=Dae(),a=j.useMemo(()=>n.filter(o=>o.role==="team_leader"),[n]),i=t.get("teamId"),l=a.find(o=>o.teamId===i)||a[0]||null;return j.useEffect(()=>{!r&&a.length===0&&s("/websites")},[r,a.length,s]),e.jsx(Vs,{title:"Team Website",description:"Your team site — members, listings and leads",children:e.jsxs("div",{className:"mx-auto max-w-5xl space-y-6 p-4 lg:p-8",children:[e.jsx(nls,{current:{kind:"team",ownerId:l==null?void 0:l.teamId}}),r?e.jsx("div",{className:"h-40 animate-pulse rounded-xl bg-muted"}):l?e.jsx(Zlt,{teamId:l.teamId,orgLabel:"team"}):e.jsx(Ne,{children:e.jsx(Ie,{className:"p-8 text-center text-sm text-muted-foreground",children:"Only team leaders can build a team website."})})]})})}function Ndr(){const{user:s,isAdmin:t,isBrokerageManager:n,rolesLoading:r,brokerageId:a,managedBrokerages:i,selectedBrokerageId:l}=vs(),o=Qn(),c=j.useMemo(()=>{var d;return l||((d=i[0])==null?void 0:d.id)||a},[l,i,a]);return j.useEffect(()=>{r||!s||!t&&!n&&o("/dashboard")},[r,s,t,n,o]),e.jsx(Vs,{title:"Company Website",description:"Your brokerage website — agents, listings, recruiting and leads",children:e.jsxs("div",{className:"mx-auto max-w-5xl space-y-6 p-4 lg:p-8",children:[e.jsx(nls,{current:{kind:"brokerage",ownerId:c}}),e.jsx(Zlt,{brokerageId:c,orgLabel:"brokerage"})]})})}const REt={name:"",description:"",agent_split_pct:"70",team_split_pct:"",cap_amount:"",monthly_fee:"",transaction_fee:"",franchise_fee_pct:"",referral_fee_pct:"",commission_calc_method:"standard",is_active:!0};function kdr({open:s,onOpenChange:t,plan:n,onSave:r,saving:a}){const[i,l]=j.useState(REt);j.useEffect(()=>{var d,u;s&&l(n?{name:n.name,description:n.description||"",agent_split_pct:String(n.agent_split_pct),team_split_pct:n.team_split_pct?String(n.team_split_pct):"",cap_amount:((d=n.cap_amount)==null?void 0:d.toString())||"",monthly_fee:n.monthly_fee?String(n.monthly_fee):"",transaction_fee:n.transaction_fee?String(n.transaction_fee):"",franchise_fee_pct:n.franchise_fee_pct?String(n.franchise_fee_pct):"",referral_fee_pct:((u=n.referral_fee_pct)==null?void 0:u.toString())||"",commission_calc_method:n.commission_calc_method||"standard",is_active:n.is_active}:REt)},[s,n]);const o=(d,u)=>l(h=>({...h,[d]:u})),c=()=>{r({id:n==null?void 0:n.id,name:i.name.trim(),description:i.description.trim()||null,agent_split_pct:parseFloat(i.agent_split_pct)||0,team_split_pct:i.team_split_pct?Math.min(100,Math.max(0,parseFloat(i.team_split_pct)||0)):0,cap_amount:i.cap_amount?parseFloat(i.cap_amount):null,monthly_fee:i.monthly_fee?parseFloat(i.monthly_fee):0,transaction_fee:i.transaction_fee?parseFloat(i.transaction_fee):0,franchise_fee_pct:i.franchise_fee_pct?parseFloat(i.franchise_fee_pct):0,referral_fee_pct:i.referral_fee_pct?parseFloat(i.referral_fee_pct):null,commission_calc_method:i.commission_calc_method,is_active:i.is_active})};return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Os,{className:"max-h-[90vh] overflow-y-auto sm:max-w-lg",children:[e.jsxs(Us,{children:[e.jsx(Bs,{children:n?"Edit commission plan":"New commission plan"}),e.jsx(Ir,{children:n?"Saving creates a new version — the previous terms stay on record.":'A named plan you can assign to agents, e.g. "70/30 with $16K cap".'})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{htmlFor:"plan-name",children:"Plan name"}),e.jsx(pe,{id:"plan-name",value:i.name,onChange:d=>o("name",d.target.value),placeholder:"70/30 split"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{htmlFor:"plan-desc",children:"Description (optional)"}),e.jsx(Rs,{id:"plan-desc",value:i.description,onChange:d=>o("description",d.target.value),rows:2})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{htmlFor:"plan-split",children:"Agent split %"}),e.jsx(pe,{id:"plan-split",type:"number",min:"0",max:"100",step:"0.5",value:i.agent_split_pct,onChange:d=>o("agent_split_pct",d.target.value)}),e.jsxs("p",{className:"text-[11px] text-muted-foreground",children:["Brokerage keeps ",Math.max(0,100-(parseFloat(i.agent_split_pct)||0)),"%"]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{htmlFor:"plan-cap",children:"Annual cap ($)"}),e.jsx(pe,{id:"plan-cap",type:"number",min:"0",value:i.cap_amount,onChange:d=>o("cap_amount",d.target.value),placeholder:"No cap"}),e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"Total brokerage takes before 100%"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{htmlFor:"plan-monthly",children:"Monthly desk fee ($)"}),e.jsx(pe,{id:"plan-monthly",type:"number",min:"0",value:i.monthly_fee,onChange:d=>o("monthly_fee",d.target.value),placeholder:"0"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{htmlFor:"plan-txn",children:"Per-transaction fee ($)"}),e.jsx(pe,{id:"plan-txn",type:"number",min:"0",value:i.transaction_fee,onChange:d=>o("transaction_fee",d.target.value),placeholder:"0"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{htmlFor:"plan-franchise",children:"Franchise fee %"}),e.jsx(pe,{id:"plan-franchise",type:"number",min:"0",step:"0.1",value:i.franchise_fee_pct,onChange:d=>o("franchise_fee_pct",d.target.value),placeholder:"0"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{htmlFor:"plan-referral",children:"Default referral fee %"}),e.jsx(pe,{id:"plan-referral",type:"number",min:"0",step:"0.1",value:i.referral_fee_pct,onChange:d=>o("referral_fee_pct",d.target.value),placeholder:"Optional"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{htmlFor:"plan-team",children:"Team split %"}),e.jsx(pe,{id:"plan-team",type:"number",min:"0",max:"100",step:"0.5",value:i.team_split_pct,onChange:d=>o("team_split_pct",d.target.value),placeholder:"0"}),e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"Only applies to agents on a team"})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Calculation method"}),e.jsxs(ms,{value:i.commission_calc_method,onValueChange:d=>o("commission_calc_method",d),children:[e.jsx(us,{children:e.jsx(fs,{})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"standard",children:"Standard — all fees off gross commission"}),e.jsx(Ge,{value:"referral_first",children:"Referral first — split applies after referral fee"})]})]})]}),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:"Active"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Only active plans can be assigned to agents"})]}),e.jsx(Sn,{checked:i.is_active,onCheckedChange:d=>o("is_active",d)})]})]}),e.jsxs(Ar,{children:[e.jsx($,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsx($,{onClick:c,disabled:a||!i.name.trim(),children:a?"Saving…":n?"Save new version":"Create plan"})]})]})})}const DEt=()=>new Date().toISOString().slice(0,10);function Sdr({open:s,onOpenChange:t,agent:n,plans:r,onAssign:a,saving:i}){const[l,o]=j.useState(""),[c,d]=j.useState(DEt()),[u,h]=j.useState(""),[m,f]=j.useState("");return j.useEffect(()=>{var g,x,y,v,b;s&&(o(((g=n==null?void 0:n.plan)==null?void 0:g.id)||((x=r[0])==null?void 0:x.id)||""),d(((y=n==null?void 0:n.assignment)==null?void 0:y.start_date)||DEt()),h(((v=n==null?void 0:n.assignment)==null?void 0:v.anniversary_date)||""),f(((b=n==null?void 0:n.assignment)==null?void 0:b.notes)||""))},[s,n,r]),e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Os,{className:"sm:max-w-md",children:[e.jsxs(Us,{children:[e.jsxs(Bs,{children:[n!=null&&n.assignment?"Change plan":"Assign plan"," — ",n==null?void 0:n.name]}),e.jsx(Ir,{children:n!=null&&n.assignment?"The current plan ends on the new start date; cap tracking starts fresh.":"The plan pre-fills commission splits and fees on the agent’s new deals."})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Commission plan"}),e.jsxs(ms,{value:l,onValueChange:o,children:[e.jsx(us,{children:e.jsx(fs,{placeholder:"Choose a plan"})}),e.jsx(hs,{children:r.map(g=>e.jsxs(Ge,{value:g.id,children:[g.name," — ",g.agent_split_pct,"/",Math.max(0,100-g.agent_split_pct),g.cap_amount?` · $${g.cap_amount.toLocaleString()} cap`:" · no cap"]},g.id))})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{htmlFor:"ap-start",children:"Start date"}),e.jsx(pe,{id:"ap-start",type:"date",value:c,onChange:g=>d(g.target.value)})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{htmlFor:"ap-anniv",children:"Anniversary date"}),e.jsx(pe,{id:"ap-anniv",type:"date",value:u,onChange:g=>h(g.target.value)}),e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"Cap resets yearly on this date (defaults to start date)"})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{htmlFor:"ap-notes",children:"Notes (optional)"}),e.jsx(Rs,{id:"ap-notes",rows:2,value:m,onChange:g=>f(g.target.value),placeholder:"e.g. Negotiated 80/20 for first year"})]})]}),e.jsxs(Ar,{children:[e.jsx($,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsx($,{disabled:i||!l||!c||!n,onClick:()=>n&&a({agent_user_id:n.agentId,plan_id:l,start_date:c,anniversary_date:u||null,notes:m.trim()||null}),children:i?"Saving…":"Save assignment"})]})]})})}const gFe=q,CAe={monthly_fee:"Monthly desk fee",transaction_fee:"Transaction fee",adjustment:"Adjustment",payment:"Payment received"};function Cdr(s){return tt({queryKey:["fee-ledger",s],enabled:!!s,queryFn:async()=>{const t=[];for(let r=0;;r+=1e3){const{data:a,error:i}=await gFe.from("agent_fee_ledger").select("*").eq("brokerage_id",s).order("entry_date",{ascending:!1}).range(r,r+1e3-1);if(i)throw i;if(t.push(...a||[]),!a||a.length<1e3)break}return t}})}function Adr(s){const t=Vt(),{user:n}=vs();return ft({mutationFn:async r=>{const{error:a}=await gFe.from("agent_fee_ledger").insert({agent_user_id:r.agent_user_id,brokerage_id:s,entry_type:r.entry_type,amount:r.amount,entry_date:r.entry_date,note:r.note||null,created_by:(n==null?void 0:n.id)??null});if(a)throw a},onSuccess:()=>{t.invalidateQueries({queryKey:["fee-ledger",s]}),re.success("Ledger entry added")},onError:r=>re.error(r.message||"Could not add entry")})}function Edr(s){const t=Vt();return ft({mutationFn:async n=>{const{error:r}=await gFe.from("agent_fee_ledger").delete().eq("id",n);if(r)throw r},onSuccess:()=>{t.invalidateQueries({queryKey:["fee-ledger",s]}),re.success("Entry removed")},onError:n=>re.error(n.message||"Could not remove entry")})}function Tdr(s){const t=Vt(),{user:n}=vs();return ft({mutationFn:async r=>{const a=`${r.month}-01`,i=new Set(r.existing.filter(c=>c.entry_type==="monthly_fee"&&(c.entry_date||"").slice(0,7)===r.month).map(c=>c.agent_user_id)),l=r.agents.filter(c=>c.monthlyFee>0&&!i.has(c.agentId)).map(c=>({agent_user_id:c.agentId,brokerage_id:s,entry_type:"monthly_fee",amount:c.monthlyFee,entry_date:a,note:`Desk fee ${r.month}`,created_by:(n==null?void 0:n.id)??null}));if(!l.length)return 0;const{error:o}=await gFe.from("agent_fee_ledger").insert(l);if(o)throw o;return l.length},onSuccess:r=>{t.invalidateQueries({queryKey:["fee-ledger",s]}),re.success(r?`Posted ${r} desk fee${r===1?"":"s"}`:"All desk fees already posted")},onError:r=>re.error(r.message||"Could not post desk fees")})}const Mdr=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function rls(s,t){return s.filter(n=>{const r=LC(n.actual_close_date);return!!r&&r.y===t})}function als(s,t,n,r=[]){const a=rls(s,n),i=Array.from({length:12},(c,d)=>({key:`${n}-${String(d+1).padStart(2,"0")}`,label:Mdr[d],companyDollar:0,gci:0,deals:0})),l=new Map;r.forEach(c=>l.set(c.agentId,{userId:c.agentId,name:c.name,avatarUrl:c.avatarUrl,closedDeals:0,volume:0,gci:0,companyDollar:0,agentShare:0,feesCharged:0,feesPaid:0,balance:0}));const o={year:n,closedDeals:a.length,volume:0,gci:0,companyDollar:0,agentShare:0,feesOutstanding:0,months:i,agents:[]};return a.forEach(c=>{const d=MW(c),u=PW(c),h=Lne(c),m=Math.max(0,u-h);o.volume+=d,o.gci+=u,o.companyDollar+=h,o.agentShare+=m;const f=LC(c.actual_close_date);if(f){const x=i[f.m-1];x&&(x.companyDollar+=h,x.gci+=u,x.deals+=1)}const g=l.get(c.owner_user_id)||{userId:c.owner_user_id,name:c.agent_name||"Agent",avatarUrl:c.agent_avatar_url,closedDeals:0,volume:0,gci:0,companyDollar:0,agentShare:0,feesCharged:0,feesPaid:0,balance:0};g.closedDeals+=1,g.volume+=d,g.gci+=u,g.companyDollar+=h,g.agentShare+=m,l.set(c.owner_user_id,g)}),t.forEach(c=>{const d=Number(c.amount)||0,u=l.get(c.agent_user_id);u&&(c.entry_type==="payment"?u.feesPaid+=Math.abs(d):u.feesCharged+=d)}),l.forEach(c=>{c.balance=c.feesCharged-c.feesPaid,o.feesOutstanding+=c.balance}),o.agents=Array.from(l.values()).filter(c=>c.closedDeals>0||c.feesCharged>0||c.feesPaid>0).sort((c,d)=>d.companyDollar-c.companyDollar||d.volume-c.volume),o}const Pdr=[64,110,113],jUe=[42,76,100],DM=[110,118,125],Cj=s=>`$${Math.round(s).toLocaleString("en-US")}`,FEt=s=>{const t=LC(s);return t?`${String(t.m).padStart(2,"0")}/${String(t.d).padStart(2,"0")}/${String(t.y).slice(2)}`:"—"},OEt=(s,t,n)=>{let r=t||"";for(;r.length>3&&s.getTextWidth(r)>n;)r=r.slice(0,-1);return r===t?r:`${r.trim()}…`};function Idr(s){const t=new Go({unit:"pt",format:"letter"}),n=t.internal.pageSize.getWidth(),r=t.internal.pageSize.getHeight(),a=48;let i=0;t.setFillColor(...jUe),t.rect(0,0,n,92,"F"),t.setTextColor(255,255,255),t.setFont("helvetica","bold"),t.setFontSize(18),t.text(s.brokerageName||"Brokerage",a,40),t.setFont("helvetica","normal"),t.setFontSize(11),t.text(`Agent commission statement · ${s.year}`,a,60),t.setFontSize(9),t.text(`Generated ${new Date().toLocaleDateString("en-US")}`,n-a,60,{align:"right"}),i=122,t.setTextColor(0,0,0),t.setFont("helvetica","bold"),t.setFontSize(14),t.text(s.agentName,a,i),t.setFont("helvetica","normal"),t.setFontSize(9),t.setTextColor(...DM);const l=[s.agentEmail,s.planName?`Plan: ${s.planName}`:null,s.planSummary].filter(Boolean).join(" · ");l&&t.text(l,a,i+14),i+=40;const o=s.deals.reduce((v,b)=>{const w=PW(b),S=Lne(b);return v.volume+=MW(b),v.gci+=w,v.company+=S,v.agent+=Math.max(0,w-S),v},{volume:0,gci:0,company:0,agent:0}),c=s.ledger.filter(v=>v.entry_type!=="payment").reduce((v,b)=>v+(Number(b.amount)||0),0),d=s.ledger.filter(v=>v.entry_type==="payment").reduce((v,b)=>v+Math.abs(Number(b.amount)||0),0),u=c-d,h=[{label:"Closed sides",value:String(s.deals.length)},{label:"Volume",value:Cj(o.volume)},{label:"Gross commission",value:Cj(o.gci)},{label:"Agent share",value:Cj(o.agent)}],m=(n-a*2-18)/4;if(h.forEach((v,b)=>{const w=a+b*(m+6);t.setDrawColor(224,228,232),t.setFillColor(248,250,250),t.roundedRect(w,i,m,48,6,6,"FD"),t.setFontSize(8),t.setTextColor(...DM),t.text(v.label,w+10,i+17),t.setFontSize(13),t.setFont("helvetica","bold"),t.setTextColor(...jUe),t.text(v.value,w+10,i+36),t.setFont("helvetica","normal")}),i+=72,s.capAmount){const v=Math.min(100,(s.capProgress||0)/s.capAmount*100);t.setFontSize(9),t.setTextColor(...DM),t.text(`Cap progress: ${Cj(s.capProgress||0)} of ${Cj(s.capAmount)} (${Math.round(v)}%)`,a,i);const b=n-a*2;t.setFillColor(232,236,238),t.roundedRect(a,i+6,b,7,3.5,3.5,"F"),t.setFillColor(...Pdr),t.roundedRect(a,i+6,Math.max(2,b*v/100),7,3.5,3.5,"F"),i+=34}const f=v=>{i>r-120&&(t.addPage(),i=60),t.setFont("helvetica","bold"),t.setFontSize(11),t.setTextColor(...jUe),t.text(v,a,i),t.setFont("helvetica","normal"),i+=14},g=()=>{t.setDrawColor(234,238,240),t.line(a,i,n-a,i)};f("Closed transactions");const x=[a,a+62,a+280,a+360,a+440];t.setFontSize(8),t.setTextColor(...DM),t.text("Closed",x[0],i),t.text("Property",x[1],i),t.text("Volume",x[2],i,{align:"right"}),t.text("GCI",x[3],i,{align:"right"}),t.text("Agent share",n-a,i,{align:"right"}),i+=5,g(),i+=13,t.setTextColor(30,34,38),t.setFontSize(9),s.deals.length||(t.setTextColor(...DM),t.text("No closed transactions in this period.",a,i),i+=18,t.setTextColor(30,34,38)),s.deals.slice().sort((v,b)=>(v.actual_close_date||"").localeCompare(b.actual_close_date||"")).forEach(v=>{i>r-90&&(t.addPage(),i=60);const b=PW(v),w=Math.max(0,b-Lne(v));t.text(FEt(v.actual_close_date),x[0],i),t.text(OEt(t,v.property_address||v.deal_name||"Transaction",205),x[1],i),t.text(Cj(MW(v)),x[2],i,{align:"right"}),t.text(Cj(b),x[3],i,{align:"right"}),t.text(Cj(w),n-a,i,{align:"right"}),i+=16}),i+=4,g(),i+=15,t.setFont("helvetica","bold"),t.text("Totals",x[1],i),t.text(Cj(o.volume),x[2],i,{align:"right"}),t.text(Cj(o.gci),x[3],i,{align:"right"}),t.text(Cj(o.agent),n-a,i,{align:"right"}),t.setFont("helvetica","normal"),i+=34,f("Fees & payments"),t.setFontSize(8),t.setTextColor(...DM),t.text("Date",x[0],i),t.text("Item",x[1],i),t.text("Amount",n-a,i,{align:"right"}),i+=5,g(),i+=13,t.setFontSize(9),t.setTextColor(30,34,38),s.ledger.length||(t.setTextColor(...DM),t.text("No fees or payments recorded.",a,i),i+=18,t.setTextColor(30,34,38)),s.ledger.slice().sort((v,b)=>(v.entry_date||"").localeCompare(b.entry_date||"")).forEach(v=>{i>r-90&&(t.addPage(),i=60);const b=Number(v.amount)||0,w=v.entry_type==="payment",S=CAe[v.entry_type]||v.entry_type;t.text(FEt(v.entry_date),x[0],i),t.text(OEt(t,v.note?`${S} — ${v.note}`:S,330),x[1],i),t.text(`${w?"-":""}${Cj(Math.abs(b))}`,n-a,i,{align:"right"}),i+=16}),i+=4,g(),i+=15,t.setFont("helvetica","bold"),t.text("Balance due to brokerage",x[1],i),t.text(Cj(u),n-a,i,{align:"right"});const y=t.getNumberOfPages();for(let v=1;v<=y;v++)t.setPage(v),t.setFont("helvetica","normal"),t.setFontSize(8),t.setTextColor(...DM),t.text("Estimated figures based on recorded transactions and plan terms. Not an accounting document.",a,r-28),t.text(`Page ${v} of ${y}`,n-a,r-28,{align:"right"});return t}function Ldr(s){const t=Idr(s),n=s.agentName.replace(/[^a-z0-9]+/gi,"-").toLowerCase();t.save(`statement-${n}-${s.year}.pdf`)}const zEt=s=>`$${Math.round(s).toLocaleString()}`;function Rdr({deals:s,ledger:t,roster:n,brokerageName:r,loading:a}){const i=new Date().getFullYear(),[l,o]=j.useState(String(i)),c=j.useMemo(()=>{const m=new Set([i]);return s.forEach(f=>{const g=LC(f.actual_close_date);g&&m.add(g.y)}),Array.from(m).sort((f,g)=>g-f)},[s,i]),d=j.useMemo(()=>als(s,t,Number(l),n.map(m=>({agentId:m.agentId,name:m.name,avatarUrl:m.avatarUrl}))),[s,t,n,l]),u=Math.max(1,...d.months.map(m=>m.companyDollar)),h=m=>{var y,v,b;const f=n.find(w=>w.agentId===m),g=d.agents.find(w=>w.userId===m),x=rls(s,Number(l)).filter(w=>w.owner_user_id===m);Ldr({brokerageName:r,agentName:(f==null?void 0:f.name)||(g==null?void 0:g.name)||"Agent",agentEmail:(f==null?void 0:f.email)||null,planName:((y=f==null?void 0:f.plan)==null?void 0:y.name)||null,planSummary:f!=null&&f.plan?`${f.plan.agent_split_pct}/${Math.max(0,100-f.plan.agent_split_pct)} split`:null,year:Number(l),deals:x,ledger:t.filter(w=>w.agent_user_id===m&&(w.entry_date||"").slice(0,4)===l),capAmount:((v=f==null?void 0:f.plan)==null?void 0:v.cap_amount)??null,capProgress:((b=f==null?void 0:f.progress)==null?void 0:b.cap_progress)??null})};return a?e.jsxs("div",{className:"space-y-3",children:[e.jsx(yn,{className:"h-24 w-full rounded-xl"}),e.jsx(yn,{className:"h-64 w-full rounded-xl"})]}):e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Closed business and company dollar earned, by month and by agent."}),e.jsxs(ms,{value:l,onValueChange:o,children:[e.jsx(us,{className:"w-32",children:e.jsx(fs,{})}),e.jsx(hs,{children:c.map(m=>e.jsx(Ge,{value:String(m),children:m},m))})]})]}),e.jsx("div",{className:"grid grid-cols-2 gap-3 lg:grid-cols-4",children:[{label:"Closed sides",value:String(d.closedDeals)},{label:"Closed volume",value:Wf(d.volume)},{label:"Gross commission",value:Wf(d.gci)},{label:"Company dollar",value:Wf(d.companyDollar),accent:!0}].map(m=>e.jsx(Ne,{className:"border-border/60",children:e.jsxs(Ie,{className:"p-4",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:m.label}),e.jsx("p",{className:`text-2xl font-bold tabular-nums tracking-tight ${m.accent?"text-teal-600":""}`,children:m.value})]})},m.label))}),e.jsxs(Ne,{className:"border-border/60",children:[e.jsxs(Ct,{className:"pb-2",children:[e.jsxs(At,{className:"flex items-center gap-2 text-base",children:[e.jsx(Yl,{className:"h-4 w-4 text-teal-600"})," Company dollar by month"]}),e.jsx(Gn,{children:"Brokerage split, franchise fees and transaction fees on closed deals"})]}),e.jsx(Ie,{children:e.jsx("div",{className:"flex h-40 items-end gap-1.5",children:d.months.map(m=>e.jsxs("div",{className:"group flex flex-1 flex-col items-center gap-1",children:[e.jsx("span",{className:"text-[10px] font-medium tabular-nums text-muted-foreground opacity-0 transition group-hover:opacity-100",children:Wf(m.companyDollar)}),e.jsx("div",{className:"w-full rounded-t bg-teal-500/80 transition group-hover:bg-teal-600",style:{height:`${Math.max(2,m.companyDollar/u*110)}px`},title:`${m.label}: ${zEt(m.companyDollar)} from ${m.deals} closed`}),e.jsx("span",{className:"text-[10px] text-muted-foreground",children:m.label})]},m.key))})})]}),e.jsxs(Ne,{className:"border-border/60",children:[e.jsxs(Ct,{className:"pb-2",children:[e.jsx(At,{className:"text-base",children:"Agent production & statements"}),e.jsx(Gn,{children:"Download a per-agent statement with closed deals, fees and balance"})]}),e.jsx(Ie,{className:"pt-1",children:d.agents.length===0?e.jsx("p",{className:"py-8 text-center text-sm text-muted-foreground",children:"No closed deals recorded yet."}):e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full min-w-[640px] text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b text-[11px] uppercase tracking-wide text-muted-foreground",children:[e.jsx("th",{className:"py-2 text-left font-medium",children:"Agent"}),e.jsx("th",{className:"py-2 text-right font-medium",children:"Closed"}),e.jsx("th",{className:"py-2 text-right font-medium",children:"Volume"}),e.jsx("th",{className:"py-2 text-right font-medium",children:"GCI"}),e.jsx("th",{className:"py-2 text-right font-medium",children:"Company $"}),e.jsx("th",{className:"py-2 text-right font-medium",children:"Balance"}),e.jsx("th",{className:"py-2"})]})}),e.jsx("tbody",{children:d.agents.map(m=>e.jsxs("tr",{className:"border-b last:border-0 hover:bg-muted/40",children:[e.jsx("td",{className:"py-2.5",children:e.jsxs("div",{className:"flex items-center gap-2.5",children:[e.jsxs(Oa,{className:"h-7 w-7",children:[e.jsx(Li,{src:m.avatarUrl||void 0,alt:m.name}),e.jsx(za,{className:"text-[10px]",children:m.name.slice(0,2).toUpperCase()})]}),e.jsx("span",{className:"truncate font-medium",children:m.name})]})}),e.jsx("td",{className:"py-2.5 text-right tabular-nums",children:m.closedDeals}),e.jsx("td",{className:"py-2.5 text-right tabular-nums",children:Wf(m.volume)}),e.jsx("td",{className:"py-2.5 text-right tabular-nums",children:Wf(m.gci)}),e.jsx("td",{className:"py-2.5 text-right font-medium tabular-nums text-teal-700",children:Wf(m.companyDollar)}),e.jsx("td",{className:"py-2.5 text-right tabular-nums",children:m.balance>0?e.jsx(Be,{variant:"outline",className:"border-amber-300 text-amber-700",children:zEt(m.balance)}):e.jsx("span",{className:"text-muted-foreground",children:"—"})}),e.jsx("td",{className:"py-2.5 text-right",children:e.jsxs($,{variant:"ghost",size:"sm",onClick:()=>h(m.userId),children:[e.jsx(u2,{className:"mr-1.5 h-4 w-4"})," Statement"]})})]},m.userId))})]})})})]})]})}const BEt=s=>`$${Math.round(s).toLocaleString()}`,Ddr=()=>new Date().toISOString().slice(0,10),Fdr=()=>new Date().toISOString().slice(0,7);function Odr({brokerageId:s,ledger:t,roster:n,loading:r}){const a=Adr(s),i=Edr(s),l=Tdr(s),[o,c]=j.useState(!1),[d,u]=j.useState(""),[h,m]=j.useState("adjustment"),[f,g]=j.useState(""),[x,y]=j.useState(Ddr()),[v,b]=j.useState(""),[w,S]=j.useState(Fdr()),[C,E]=j.useState("all"),I=V=>{var G;return((G=n.find(Y=>Y.agentId===V))==null?void 0:G.name)||"Agent"},P=j.useMemo(()=>{const V=new Map;return t.forEach(G=>{const Y=Number(G.amount)||0,X=G.entry_type==="payment"?-Math.abs(Y):Y;V.set(G.agent_user_id,(V.get(G.agent_user_id)||0)+X)}),V},[t]),R=j.useMemo(()=>Array.from(P.values()).reduce((V,G)=>V+Math.max(0,G),0),[P]),D=j.useMemo(()=>t.filter(V=>V.entry_type==="payment").reduce((V,G)=>V+Math.abs(Number(G.amount)||0),0),[t]),O=j.useMemo(()=>C==="all"?t:t.filter(V=>V.agent_user_id===C),[t,C]),U=n.filter(V=>V.plan&&(V.plan.monthly_fee||0)>0).map(V=>({agentId:V.agentId,name:V.name,monthlyFee:V.plan.monthly_fee})),W=()=>{const V=parseFloat(f);!d||!Number.isFinite(V)||V<=0||a.mutate({agent_user_id:d,entry_type:h,amount:V,entry_date:x,note:v},{onSuccess:()=>{c(!1),g(""),b("")}})};return r?e.jsx(yn,{className:"h-64 w-full rounded-xl"}):e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-1 gap-3 sm:grid-cols-3",children:[e.jsx(Ne,{className:"border-border/60",children:e.jsxs(Ie,{className:"p-4",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Outstanding fees"}),e.jsx("p",{className:"text-2xl font-bold tabular-nums text-amber-600",children:Wf(R)})]})}),e.jsx(Ne,{className:"border-border/60",children:e.jsxs(Ie,{className:"p-4",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Payments recorded"}),e.jsx("p",{className:"text-2xl font-bold tabular-nums text-emerald-600",children:Wf(D)})]})}),e.jsx(Ne,{className:"border-border/60",children:e.jsxs(Ie,{className:"p-4",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Agents with a desk fee"}),e.jsx("p",{className:"text-2xl font-bold tabular-nums",children:U.length})]})})]}),e.jsxs(Ne,{className:"border-border/60",children:[e.jsx(Ct,{className:"pb-3",children:e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx(At,{className:"text-base",children:"Fee ledger"}),e.jsx(Gn,{children:"Desk fees, transaction fees, adjustments and payments received"})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(pe,{type:"month",value:w,onChange:V=>S(V.target.value),className:"h-9 w-[150px]"}),e.jsxs($,{variant:"outline",size:"sm",disabled:l.isPending||U.length===0,onClick:()=>l.mutate({month:w,agents:U,existing:t}),children:[e.jsx(jv,{className:"mr-1.5 h-4 w-4"})," Post desk fees"]}),e.jsxs($,{size:"sm",onClick:()=>c(!0),children:[e.jsx(dn,{className:"mr-1.5 h-4 w-4"})," Add entry"]})]})]})}),e.jsxs(Ie,{className:"space-y-3",children:[e.jsxs(ms,{value:C,onValueChange:E,children:[e.jsx(us,{className:"h-9 w-full sm:w-64",children:e.jsx(fs,{placeholder:"All agents"})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"all",children:"All agents"}),n.map(V=>e.jsxs(Ge,{value:V.agentId,children:[V.name,P.get(V.agentId)?` · ${BEt(P.get(V.agentId))}`:""]},V.agentId))]})]}),O.length===0?e.jsx("p",{className:"py-10 text-center text-sm text-muted-foreground",children:"No ledger entries yet. Post this month's desk fees or add an entry."}):e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full min-w-[620px] text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b text-[11px] uppercase tracking-wide text-muted-foreground",children:[e.jsx("th",{className:"py-2 text-left font-medium",children:"Date"}),e.jsx("th",{className:"py-2 text-left font-medium",children:"Agent"}),e.jsx("th",{className:"py-2 text-left font-medium",children:"Item"}),e.jsx("th",{className:"py-2 text-right font-medium",children:"Amount"}),e.jsx("th",{className:"py-2"})]})}),e.jsx("tbody",{children:O.map(V=>e.jsxs("tr",{className:"border-b last:border-0 hover:bg-muted/40",children:[e.jsx("td",{className:"py-2.5 tabular-nums text-muted-foreground",children:V.entry_date}),e.jsx("td",{className:"py-2.5 font-medium",children:I(V.agent_user_id)}),e.jsx("td",{className:"py-2.5",children:e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[e.jsx(Be,{variant:V.entry_type==="payment"?"secondary":"outline",children:CAe[V.entry_type]||V.entry_type}),V.note&&e.jsx("span",{className:"text-xs text-muted-foreground",children:V.note})]})}),e.jsxs("td",{className:`py-2.5 text-right font-medium tabular-nums ${V.entry_type==="payment"?"text-emerald-600":""}`,children:[V.entry_type==="payment"?"-":"",BEt(Math.abs(Number(V.amount)||0))]}),e.jsx("td",{className:"py-2.5 text-right",children:e.jsx($,{variant:"ghost",size:"icon",className:"h-8 w-8 text-muted-foreground",onClick:()=>i.mutate(V.id),children:e.jsx(Wn,{className:"h-4 w-4"})})})]},V.id))})]})})]})]}),e.jsx(zs,{open:o,onOpenChange:c,children:e.jsxs(Os,{className:"sm:max-w-md",children:[e.jsxs(Us,{children:[e.jsx(Bs,{children:"Add ledger entry"}),e.jsx(Ir,{children:"Record a fee charged to an agent, or a payment they made."})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Agent"}),e.jsxs(ms,{value:d,onValueChange:u,children:[e.jsx(us,{children:e.jsx(fs,{placeholder:"Choose an agent"})}),e.jsx(hs,{children:n.map(V=>e.jsx(Ge,{value:V.agentId,children:V.name},V.agentId))})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Type"}),e.jsxs(ms,{value:h,onValueChange:V=>m(V),children:[e.jsx(us,{children:e.jsx(fs,{})}),e.jsx(hs,{children:Object.keys(CAe).map(V=>e.jsx(Ge,{value:V,children:CAe[V]},V))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Amount"}),e.jsx(pe,{type:"number",min:"0",step:"0.01",value:f,onChange:V=>g(V.target.value),placeholder:"0.00"})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Date"}),e.jsx(pe,{type:"date",value:x,onChange:V=>y(V.target.value)})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Note (optional)"}),e.jsx(Rs,{rows:2,value:v,onChange:V=>b(V.target.value)})]})]}),e.jsxs(Ar,{children:[e.jsx($,{variant:"outline",onClick:()=>c(!1),children:"Cancel"}),e.jsx($,{onClick:W,disabled:a.isPending||!d||!f,children:"Add entry"})]})]})})]})}const zdr={license:RJ,eo:bm,anniversary:Ax,birthday:Fg},Bdr=[30,60,90,180];function $dr({records:s,roster:t,deals:n,loading:r}){const[a,i]=j.useState(90),l=j.useMemo(()=>t.map(y=>({agentId:y.agentId,name:y.name,avatarUrl:y.avatarUrl})),[t]),o=j.useMemo(()=>Jos(s,l,a),[s,l,a]),c=o.filter(y=>y.expired),d=o.filter(y=>!y.expired&&(y.kind==="license"||y.kind==="eo")),u=o.filter(y=>y.kind==="anniversary"||y.kind==="birthday"),h=j.useMemo(()=>{const y=new Map(s.map(v=>[v.agent_user_id,v]));return t.filter(v=>{const b=y.get(v.agentId);return!(b!=null&&b.license_expiration)||!(b!=null&&b.eo_expiration)})},[s,t]),m=new Date().getFullYear(),f=j.useMemo(()=>als(n,[],m,l).agents,[n,l,m]),g=j.useMemo(()=>Zcr(s,l,f),[s,l,f]);if(r)return e.jsx("div",{className:"space-y-3",children:Array.from({length:3}).map((y,v)=>e.jsx(yn,{className:"h-32 w-full rounded-xl"},v))});const x=(y,v)=>{const b=zdr[y.kind];return e.jsxs("div",{className:"flex items-center gap-3 rounded-lg px-2 py-2.5 hover:bg-muted/50",children:[e.jsxs(Oa,{className:"h-8 w-8 shrink-0",children:[e.jsx(Li,{src:y.avatarUrl||void 0,alt:y.agentName}),e.jsx(za,{className:"text-[10px]",children:y.agentName.slice(0,2).toUpperCase()})]}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"truncate text-sm font-medium",children:y.agentName}),e.jsxs("p",{className:"flex items-center gap-1.5 truncate text-[11px] text-muted-foreground",children:[e.jsx(b,{className:"h-3 w-3"}),Ycr[y.kind],y.detail?` · ${y.detail}`:""]})]}),e.jsxs("div",{className:"shrink-0 text-right",children:[e.jsx("p",{className:"text-xs font-medium tabular-nums",children:Ylt(y.dueDate)}),y.expired?e.jsxs(Be,{variant:"destructive",className:"mt-0.5 h-5 text-[10px]",children:[Math.abs(y.daysUntil)," days overdue"]}):e.jsx("p",{className:`text-[11px] ${y.daysUntil<=30?"font-medium text-amber-600":"text-muted-foreground"}`,children:y.daysUntil===0?"Today":`in ${y.daysUntil} days`})]})]},`${y.agentId}-${y.kind}-${v}`)};return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-1 gap-3 sm:grid-cols-3",children:[e.jsx(Ne,{className:"border-border/60",children:e.jsxs(Ie,{className:"flex items-center gap-3 p-4",children:[e.jsx("span",{className:"flex h-9 w-9 items-center justify-center rounded-lg bg-red-500/10 text-red-600",children:e.jsx(wl,{className:"h-4 w-4"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Expired"}),e.jsx("p",{className:"text-2xl font-bold tabular-nums tracking-tight",children:c.length})]})]})}),e.jsx(Ne,{className:"border-border/60",children:e.jsxs(Ie,{className:"flex items-center gap-3 p-4",children:[e.jsx("span",{className:"flex h-9 w-9 items-center justify-center rounded-lg bg-amber-500/10 text-amber-600",children:e.jsx(Au,{className:"h-4 w-4"})}),e.jsxs("div",{children:[e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Due in ",a," days"]}),e.jsx("p",{className:"text-2xl font-bold tabular-nums tracking-tight",children:d.length})]})]})}),e.jsx(Ne,{className:"border-border/60",children:e.jsxs(Ie,{className:"flex items-center gap-3 p-4",children:[e.jsx("span",{className:"flex h-9 w-9 items-center justify-center rounded-lg bg-slate-500/10 text-slate-600",children:e.jsx(bm,{className:"h-4 w-4"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Missing license or E&O date"}),e.jsx("p",{className:"text-2xl font-bold tabular-nums tracking-tight",children:h.length})]})]})})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[e.jsx("span",{className:"mr-1 text-xs text-muted-foreground",children:"Look ahead:"}),Bdr.map(y=>e.jsxs($,{size:"sm",variant:a===y?"default":"outline",onClick:()=>i(y),children:[y," days"]},y))]}),e.jsxs("div",{className:"grid gap-4 lg:grid-cols-2",children:[e.jsxs(Ne,{className:"border-border/60",children:[e.jsxs(Ct,{className:"pb-2",children:[e.jsx(At,{className:"text-base",children:"License & E&O renewals"}),e.jsx(Gn,{children:"Expired items first, then everything due inside your window"})]}),e.jsx(Ie,{className:"space-y-0.5 pt-2",children:c.length===0&&d.length===0?e.jsxs("p",{className:"py-8 text-center text-sm text-muted-foreground",children:["Nothing expiring in the next ",a," days."]}):[...c,...d].map(x)})]}),e.jsxs(Ne,{className:"border-border/60",children:[e.jsxs(Ct,{className:"pb-2",children:[e.jsx(At,{className:"text-base",children:"Anniversaries & birthdays"}),e.jsx(Gn,{children:"Reach out before the day — retention lives here"})]}),e.jsx(Ie,{className:"space-y-0.5 pt-2",children:u.length===0?e.jsxs("p",{className:"py-8 text-center text-sm text-muted-foreground",children:["No milestones in the next ",a," days."]}):u.map(x)})]})]}),e.jsxs(Ne,{className:"border-border/60",children:[e.jsxs(Ct,{className:"pb-2",children:[e.jsxs(At,{className:"flex items-center gap-2 text-base",children:[e.jsx(rh,{className:"h-4 w-4 text-teal-600"})," Production goals — ",m]}),e.jsx(Gn,{children:"Goal amounts come from each agent's record; progress uses closed volume this year"})]}),e.jsx(Ie,{className:"space-y-2 pt-2",children:g.length===0?e.jsx("p",{className:"py-8 text-center text-sm text-muted-foreground",children:"No production goals set yet — add one on an agent's record in Onboarding."}):g.map(y=>e.jsxs("div",{className:"rounded-lg px-2 py-2.5 hover:bg-muted/50",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs(Oa,{className:"h-8 w-8 shrink-0",children:[e.jsx(Li,{src:y.avatarUrl||void 0,alt:y.name}),e.jsx(za,{className:"text-[10px]",children:y.name.slice(0,2).toUpperCase()})]}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"truncate text-sm font-medium",children:y.name}),e.jsxs("p",{className:"text-[11px] text-muted-foreground",children:[Wf(y.volume)," of ",Wf(y.goal)," · ",y.closedDeals," closed"]})]}),e.jsxs("span",{className:"shrink-0 text-sm font-semibold tabular-nums",children:[Math.round(y.pct),"%"]})]}),e.jsx(Yi,{value:Math.min(100,y.pct),className:"mt-2 h-1.5"})]},y.agentId))})]})]})}const dhe=s=>`${s<0?"-":""}$${Math.abs(Math.round(s)).toLocaleString()}`;function Udr({open:s,onOpenChange:t,draft:n,roster:r,onSave:a,saving:i}){const[l,o]=j.useState(n);j.useEffect(()=>o(n),[n]);const c=j.useMemo(()=>IW(l||{}),[l]);if(!l)return null;const d=m=>o({...l,...m}),u=(m,f,g)=>e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{className:"text-xs",children:f}),e.jsxs("div",{className:"relative",children:[e.jsx(pe,{type:"number",value:l[m]??0,onChange:x=>d({[m]:parseFloat(x.target.value)||0})}),g&&e.jsx("span",{className:"pointer-events-none absolute right-3 top-1/2 -translate-y-1/2 text-xs text-muted-foreground",children:g})]})]}),h=(m,f)=>{const g=[...l.line_items||[]];g[m]={...g[m],...f},d({line_items:g})};return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Os,{className:"max-h-[90vh] max-w-3xl overflow-y-auto",children:[e.jsxs(Us,{children:[e.jsx(Bs,{children:l.id?"Edit disbursement":"New disbursement"}),e.jsx(Ir,{children:"Set the closing details and how the commission is split. The CDA is generated from these numbers."})]}),e.jsxs("div",{className:"grid grid-cols-1 gap-4 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{className:"text-xs",children:"Agent"}),e.jsxs(ms,{value:l.agent_user_id,onValueChange:m=>d({agent_user_id:m}),children:[e.jsx(us,{children:e.jsx(fs,{placeholder:"Choose an agent"})}),e.jsx(hs,{children:r.map(m=>e.jsx(Ge,{value:m.agentId,children:m.name},m.agentId))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{className:"text-xs",children:"Closing date"}),e.jsx(pe,{type:"date",value:l.closing_date||"",onChange:m=>d({closing_date:m.target.value||null})})]}),e.jsxs("div",{className:"space-y-1.5 sm:col-span-2",children:[e.jsx(ee,{className:"text-xs",children:"Property"}),e.jsx(pe,{value:l.property_address||"",onChange:m=>d({property_address:m.target.value}),placeholder:"123 Main St, Nashville TN"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{className:"text-xs",children:"Escrow / title company"}),e.jsx(pe,{value:l.escrow_company||"",onChange:m=>d({escrow_company:m.target.value})})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{className:"text-xs",children:"Escrow / file number"}),e.jsx(pe,{value:l.escrow_number||"",onChange:m=>d({escrow_number:m.target.value})})]}),u("sale_price","Sale price","$"),u("gross_commission","Gross commission","$"),u("agent_split_pct","Agent split","%"),u("franchise_fee_pct","Franchise fee","%"),u("transaction_fee","Transaction fee","$"),u("referral_fee_pct","Referral fee","%"),u("referral_amount","Referral flat amount","$"),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{className:"text-xs",children:"Referral paid to"}),e.jsx(pe,{value:l.referral_payee||"",onChange:m=>d({referral_payee:m.target.value})})]})]}),e.jsxs("div",{className:"space-y-2 rounded-lg border border-border/60 p-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("p",{className:"text-sm font-medium",children:"Other charges & credits"}),e.jsxs($,{type:"button",size:"sm",variant:"outline",onClick:()=>d({line_items:[...l.line_items||[],{label:"",amount:0}]}),children:[e.jsx(dn,{className:"mr-1 h-3.5 w-3.5"})," Add line"]})]}),(l.line_items||[]).length===0&&e.jsx("p",{className:"text-xs text-muted-foreground",children:"Positive amounts are deducted from the agent; use a negative amount for a credit."}),(l.line_items||[]).map((m,f)=>e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(pe,{className:"flex-1",value:m.label,placeholder:"E&O fee, sign rental, admin fee…",onChange:g=>h(f,{label:g.target.value})}),e.jsx(pe,{className:"w-32",type:"number",value:m.amount,onChange:g=>h(f,{amount:parseFloat(g.target.value)||0})}),e.jsx($,{type:"button",size:"icon",variant:"ghost",onClick:()=>d({line_items:(l.line_items||[]).filter((g,x)=>x!==f)}),children:e.jsx(Wn,{className:"h-4 w-4 text-muted-foreground"})})]},f))]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{className:"text-xs",children:"Notes for escrow"}),e.jsx(Rs,{rows:2,value:l.notes||"",onChange:m=>d({notes:m.target.value}),placeholder:"Wire instructions, check delivery, anything escrow should know"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3 rounded-lg bg-muted/50 p-3 sm:grid-cols-4",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"Gross"}),e.jsx("p",{className:"font-semibold tabular-nums",children:dhe(c.gross)})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"Referral"}),e.jsx("p",{className:"font-semibold tabular-nums",children:dhe(c.referral)})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"Brokerage"}),e.jsx("p",{className:"font-semibold tabular-nums text-teal-600",children:dhe(c.companyDollar+c.otherCharges)})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"Agent net"}),e.jsx("p",{className:"font-semibold tabular-nums text-emerald-600",children:dhe(c.agentNet)})]})]}),e.jsxs(Ar,{children:[e.jsx($,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsx($,{disabled:!l.agent_user_id||i,onClick:()=>a(l),children:i?"Saving…":"Save disbursement"})]})]})})}const NUe=[42,76,100],$Et=[64,110,113],kUe=[110,118,125],uhe=s=>`${s<0?"-":""}$${Math.abs(Math.round(s)).toLocaleString("en-US")}`,UEt=s=>{const t=LC(s);return t?new Intl.DateTimeFormat("en-US",{month:"long",day:"numeric",year:"numeric",timeZone:"America/New_York"}).format(new Date(Date.UTC(t.y,t.m-1,t.d))):"—"};function qdr(s){const t=s.disbursement,n=IW(t),r=new Go({unit:"pt",format:"letter"}),a=r.internal.pageSize.getWidth(),i=r.internal.pageSize.getHeight(),l=48;r.setFillColor(...NUe),r.rect(0,0,a,86,"F"),r.setTextColor(255,255,255),r.setFont("helvetica","bold"),r.setFontSize(16),r.text("Commission Disbursement Authorization",l,40),r.setFont("helvetica","normal"),r.setFontSize(10),r.text(s.brokerageName,l,60),r.text(`Issued ${UEt(new Date().toISOString().slice(0,10))}`,a-l,60,{align:"right"});let o=118;const c=(h,m,f,g)=>{r.setFontSize(8),r.setTextColor(...kUe),r.text(h.toUpperCase(),f,o),r.setFontSize(10.5),r.setTextColor(25,30,35),r.text(r.splitTextToSize(m||"—",g)[0],f,o+15)},d=(a-l*2)/2;c("Property",t.property_address||"—",l,d-12),c("Closing date",UEt(t.closing_date),l+d,d),o+=40,c("Escrow / title company",t.escrow_company||"—",l,d-12),c("Escrow / file number",t.escrow_number||"—",l+d,d),o+=40,c("Agent",s.agentName,l,d-12),c("Sale price",uhe(t.sale_price),l+d,d),o+=46,r.setDrawColor(224,228,232),r.line(l,o,a-l,o),o+=24,r.setFont("helvetica","bold"),r.setFontSize(11),r.setTextColor(...NUe),r.text("Disbursement of commission",l,o),r.setFont("helvetica","normal"),o+=20;const u=(h,m,f)=>{o>i-140&&(r.addPage(),o=60),r.setFont("helvetica",f!=null&&f.bold?"bold":"normal"),r.setFontSize(10);const g=f!=null&&f.teal?$Et:[25,30,35];r.setTextColor(g[0],g[1],g[2]),r.text(h,l,o),r.text(uhe(m),a-l,o,{align:"right"}),o+=8,r.setDrawColor(238,241,243),r.line(l,o,a-l,o),o+=14,r.setFont("helvetica","normal")};return u("Gross commission due at closing",n.gross,{bold:!0}),n.referral>0&&u(`Referral fee${t.referral_payee?` — ${t.referral_payee}`:""}`,-n.referral),n.referral>0&&u("Adjusted gross commission",n.adjustedGross,{bold:!0}),u(`Brokerage split (${Math.round(100-Number(t.agent_split_pct||0))}% to brokerage)`,-n.brokerageSplit),n.franchiseFee>0&&u(`Franchise fee (${t.franchise_fee_pct}%)`,-n.franchiseFee),n.transactionFee>0&&u("Transaction fee",-n.transactionFee),(t.line_items||[]).forEach(h=>u(h.label||"Adjustment",-Number(h.amount||0))),o+=6,r.setFillColor(246,249,249),r.roundedRect(l,o-4,a-l*2,76,6,6,"F"),o+=16,r.setFont("helvetica","bold"),r.setFontSize(11),r.setTextColor(...NUe),r.text(`Pay to ${s.brokerageName}`,l+14,o),r.text(uhe(n.companyDollar+n.otherCharges),a-l-14,o,{align:"right"}),o+=24,r.setTextColor(...$Et),r.text(`Pay to ${s.agentName}`,l+14,o),r.text(uhe(n.agentNet),a-l-14,o,{align:"right"}),r.setFont("helvetica","normal"),o+=52,t.notes&&(r.setFontSize(9),r.setTextColor(...kUe),r.splitTextToSize(t.notes,a-l*2).forEach(h=>{r.text(h,l,o),o+=12}),o+=10),o>i-130&&(r.addPage(),o=80),o=Math.max(o,i-150),r.setDrawColor(150,158,165),r.line(l,o,l+220,o),r.line(a-l-160,o,a-l,o),r.setFontSize(8),r.setTextColor(...kUe),r.text("Authorized broker signature",l,o+13),r.text("Date",a-l-160,o+13),r.setFontSize(7.5),r.text("This authorization instructs the escrow or title company to disburse the commission as set out above. Amounts are subject to the final settlement statement.",l,i-44,{maxWidth:a-l*2}),r}function Vdr(s){const t=(s.disbursement.property_address||s.agentName||"cda").replace(/[^a-z0-9]+/gi,"-").toLowerCase().slice(0,48);qdr(s).save(`cda-${t}.pdf`)}const Hdr=s=>{const t=s==null?"":String(s);return/[",\n]/.test(t)?`"${t.replace(/"/g,'""')}"`:t},SR=s=>Math.round(s*100)/100,Gdr=["Date","Ref Number","Name","Account","Memo","Debit","Credit"];function Wdr(s,t){const n=[];return s.forEach((r,a)=>{const i=IW(r),l=r.closing_date||r.created_at.slice(0,10),o=r.escrow_number||`CDA-${String(a+1).padStart(4,"0")}`,c=t(r.agent_user_id),d=r.property_address||"Commission disbursement";n.push({date:l,refNumber:o,name:c,account:"Commission Income",memo:d,debit:"",credit:SR(i.gross)}),i.referral>0&&n.push({date:l,refNumber:o,name:r.referral_payee||"Referral partner",account:"Referral Fees",memo:d,debit:SR(i.referral),credit:""}),i.agentNet!==0&&n.push({date:l,refNumber:o,name:c,account:"Agent Commission Expense",memo:d,debit:SR(i.agentNet),credit:""}),i.franchiseFee>0&&n.push({date:l,refNumber:o,name:c,account:"Franchise Fees",memo:d,debit:SR(i.franchiseFee),credit:""}),(r.line_items||[]).forEach(h=>{const m=Number(h.amount)||0;m&&n.push({date:l,refNumber:o,name:c,account:h.label||"Agent Charges",memo:d,debit:m<0?SR(-m):"",credit:m>0?SR(m):""})});const u=SR(i.gross-i.referral-i.agentNet-i.franchiseFee);u!==0&&n.push({date:l,refNumber:o,name:c,account:"Undeposited Funds",memo:d,debit:u>0?u:"",credit:u<0?-u:""})}),n}function Kdr(s){const t=[Gdr.join(",")];return s.forEach(n=>t.push([n.date,n.refNumber,n.name,n.account,n.memo,n.debit,n.credit].map(Hdr).join(","))),t.join(` `)}function Ydr(s,t,n=`quickbooks-disbursements-${new Date().toISOString().slice(0,10)}.csv`){const r=new Blob([Kdr(Wdr(s,t))],{type:"text/csv;charset=utf-8"}),a=URL.createObjectURL(r),i=document.createElement("a");i.href=a,i.download=n,i.click(),URL.revokeObjectURL(a)}const Zdr={draft:"bg-muted text-muted-foreground",approved:"bg-blue-500/10 text-blue-600",paid:"bg-emerald-500/10 text-emerald-600",void:"bg-destructive/10 text-destructive"},SUe=s=>`${s<0?"-":""}$${Math.abs(Math.round(s)).toLocaleString()}`,Xdr=s=>{const t=LC(s);return t?`${t.m}/${t.d}/${String(t.y).slice(2)}`:"—"};function Qdr({brokerageId:s,disbursements:t,deals:n,roster:r,brokerageName:a,loading:i}){const l=Lcr(s),o=Rcr(s),c=Dcr(s),[d,u]=j.useState(null),[h,m]=j.useState("all"),f=w=>{var S;return((S=r.find(C=>C.agentId===w))==null?void 0:S.name)||"Agent"},g=j.useMemo(()=>h==="all"?t:t.filter(w=>w.status===h),[t,h]),x=j.useMemo(()=>t.filter(S=>S.status!=="void").reduce((S,C)=>{const E=IW(C);return S.gross+=E.gross,S.company+=E.companyDollar+E.otherCharges,S.agent+=E.agentNet,C.status==="draft"&&(S.pending+=1),S},{gross:0,company:0,agent:0,pending:0}),[t]),y=j.useMemo(()=>{const w=new Set(t.map(S=>S.deal_id).filter(Boolean));return n.filter(S=>!!S.actual_close_date&&!w.has(S.deal_id)).slice(0,20)},[n,t]),v=w=>{var C;const S=((C=r.find(E=>E.agentId===w.owner_user_id))==null?void 0:C.plan)||null;u(Icr(w,S))},b=()=>{var w,S,C,E,I,P,R;return{deal_id:null,agent_user_id:((w=r[0])==null?void 0:w.agentId)||"",status:"draft",property_address:"",escrow_company:null,escrow_number:null,closing_date:new Date().toISOString().slice(0,10),sale_price:0,gross_commission:0,agent_split_pct:((C=(S=r[0])==null?void 0:S.plan)==null?void 0:C.agent_split_pct)??70,franchise_fee_pct:((I=(E=r[0])==null?void 0:E.plan)==null?void 0:I.franchise_fee_pct)??0,transaction_fee:((R=(P=r[0])==null?void 0:P.plan)==null?void 0:R.transaction_fee)??0,referral_fee_pct:0,referral_amount:0,referral_payee:null,line_items:[],notes:null}};return i?e.jsx(yn,{className:"h-64 w-full rounded-xl"}):e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-1 gap-3 sm:grid-cols-4",children:[e.jsx(Ne,{className:"border-border/60",children:e.jsxs(Ie,{className:"p-4",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Commission authorized"}),e.jsx("p",{className:"text-2xl font-bold tabular-nums",children:Wf(x.gross)})]})}),e.jsx(Ne,{className:"border-border/60",children:e.jsxs(Ie,{className:"p-4",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"To the brokerage"}),e.jsx("p",{className:"text-2xl font-bold tabular-nums text-teal-600",children:Wf(x.company)})]})}),e.jsx(Ne,{className:"border-border/60",children:e.jsxs(Ie,{className:"p-4",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"To agents"}),e.jsx("p",{className:"text-2xl font-bold tabular-nums text-emerald-600",children:Wf(x.agent)})]})}),e.jsx(Ne,{className:"border-border/60",children:e.jsxs(Ie,{className:"p-4",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Awaiting approval"}),e.jsx("p",{className:"text-2xl font-bold tabular-nums text-amber-600",children:x.pending})]})})]}),y.length>0&&e.jsxs(Ne,{className:"border-border/60",children:[e.jsxs(Ct,{className:"pb-2",children:[e.jsx(At,{className:"text-base",children:"Closed deals without a disbursement"}),e.jsx(Gn,{children:"Start a CDA prefilled from the deal and the agent's commission plan"})]}),e.jsx(Ie,{className:"flex flex-wrap gap-2 pt-2",children:y.map(w=>e.jsxs($,{size:"sm",variant:"outline",onClick:()=>v(w),children:[e.jsx(Jq,{className:"mr-1.5 h-3.5 w-3.5"}),w.property_address||w.deal_name]},w.deal_id))})]}),e.jsxs(Ne,{className:"border-border/60",children:[e.jsxs(Ct,{className:"flex flex-row flex-wrap items-center justify-between gap-3 pb-2",children:[e.jsxs("div",{children:[e.jsx(At,{className:"text-base",children:"Disbursement authorizations"}),e.jsx(Gn,{children:"Approve, mark paid, print the CDA or export to QuickBooks"})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs(ms,{value:h,onValueChange:w=>m(w),children:[e.jsx(us,{className:"h-9 w-[150px]",children:e.jsx(fs,{})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"all",children:"All statuses"}),Object.keys(bUe).map(w=>e.jsx(Ge,{value:w,children:bUe[w]},w))]})]}),e.jsxs($,{size:"sm",variant:"outline",disabled:!g.length,onClick:()=>Ydr(g,f),children:[e.jsx(di,{className:"mr-1.5 h-4 w-4"})," QuickBooks CSV"]}),e.jsxs($,{size:"sm",disabled:!r.length,onClick:()=>u(b()),children:[e.jsx(dn,{className:"mr-1.5 h-4 w-4"})," New CDA"]})]})]}),e.jsxs(Ie,{className:"space-y-1 pt-2",children:[!g.length&&e.jsx("p",{className:"py-8 text-center text-sm text-muted-foreground",children:"No disbursements yet — start one from a closed deal above."}),g.map(w=>{const S=IW(w);return e.jsxs("div",{className:"flex flex-wrap items-center gap-3 rounded-lg border border-border/50 p-3",children:[e.jsxs("div",{className:"min-w-[180px] flex-1",children:[e.jsx("p",{className:"truncate text-sm font-medium",children:w.property_address||"Transaction"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[f(w.agent_user_id)," · closed ",Xdr(w.closing_date),w.escrow_number?` · file ${w.escrow_number}`:""]})]}),e.jsxs("div",{className:"text-right",children:[e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"Gross"}),e.jsx("p",{className:"text-sm font-semibold tabular-nums",children:SUe(S.gross)})]}),e.jsxs("div",{className:"text-right",children:[e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"Brokerage"}),e.jsx("p",{className:"text-sm font-semibold tabular-nums text-teal-600",children:SUe(S.companyDollar+S.otherCharges)})]}),e.jsxs("div",{className:"text-right",children:[e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"Agent"}),e.jsx("p",{className:"text-sm font-semibold tabular-nums text-emerald-600",children:SUe(S.agentNet)})]}),e.jsx(Be,{variant:"secondary",className:Zdr[w.status],children:bUe[w.status]}),e.jsxs($,{size:"sm",variant:"outline",onClick:()=>Vdr({disbursement:w,brokerageName:a,agentName:f(w.agent_user_id)}),children:[e.jsx(Jr,{className:"mr-1.5 h-3.5 w-3.5"})," CDA"]}),e.jsxs(Uu,{children:[e.jsx(qu,{asChild:!0,children:e.jsx($,{size:"icon",variant:"ghost",children:e.jsx(ty,{className:"h-4 w-4"})})}),e.jsxs(Eu,{align:"end",children:[e.jsx(ja,{onClick:()=>u({...w}),children:"Edit"}),w.status==="draft"&&e.jsxs(ja,{onClick:()=>o.mutate({id:w.id,status:"approved"}),children:[e.jsx(qr,{className:"mr-2 h-4 w-4"})," Approve"]}),w.status!=="paid"&&w.status!=="void"&&e.jsxs(ja,{onClick:()=>o.mutate({id:w.id,status:"paid"}),children:[e.jsx(l7,{className:"mr-2 h-4 w-4"})," Mark paid"]}),w.status!=="void"&&e.jsx(ja,{onClick:()=>o.mutate({id:w.id,status:"void"}),children:"Void"}),e.jsxs(ja,{className:"text-destructive",onClick:()=>c.mutate(w.id),children:[e.jsx(Wn,{className:"mr-2 h-4 w-4"})," Delete"]})]})]})]},w.id)})]})]}),e.jsx(Udr,{open:!!d,onOpenChange:w=>!w&&u(null),draft:d,roster:r,saving:l.isPending,onSave:w=>l.mutate(w,{onSuccess:()=>u(null)})})]})}const hhe=s=>`$${Math.round(s).toLocaleString()}`,Jdr=()=>{var G;const{brokerageId:s,managedBrokerages:t,selectedBrokerageId:n}=vs(),r=j.useMemo(()=>{var Y;return n||((Y=t[0])==null?void 0:Y.id)||s},[n,t,s]),{data:a=[],isLoading:i}=WQn(r,!0),{data:l=[],isLoading:o}=ZQn(r),c=KQn(r),d=XQn(r),u=QQn(r),{data:h=[],isLoading:m}=Dtt(r),{data:f=[],isLoading:g}=Cdr(r),{data:x=[],isLoading:y}=Yos(r),{data:v=[],isLoading:b}=Kos(r),w=((G=t.find(Y=>Y.id===r))==null?void 0:G.name)||"Brokerage",[S,C]=j.useState(!1),[E,I]=j.useState(null),[P,R]=j.useState(!1),[D,O]=j.useState(null),U=a.filter(Y=>Y.is_active),W=l.filter(Y=>Y.assignment),V=W.reduce((Y,X)=>{var ae;return Y+(((ae=X.plan)==null?void 0:ae.monthly_fee)||0)},0);return e.jsxs(Vs,{title:"Brokerage Financials",description:"Commission plans, cap progress, company dollar and agent fee statements",children:[e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"grid grid-cols-1 gap-3 sm:grid-cols-3",children:[e.jsx(Ne,{className:"border-border/60",children:e.jsxs(Ie,{className:"flex items-center gap-3 p-4",children:[e.jsx("span",{className:"flex h-9 w-9 items-center justify-center rounded-lg bg-teal-500/10 text-teal-600",children:e.jsx(Rw,{className:"h-4.5 w-4.5"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Active plans"}),e.jsx("p",{className:"text-2xl font-bold tabular-nums tracking-tight",children:U.length})]})]})}),e.jsx(Ne,{className:"border-border/60",children:e.jsxs(Ie,{className:"flex items-center gap-3 p-4",children:[e.jsx("span",{className:"flex h-9 w-9 items-center justify-center rounded-lg bg-blue-500/10 text-blue-600",children:e.jsx(Zn,{className:"h-4.5 w-4.5"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Agents on a plan"}),e.jsxs("p",{className:"text-2xl font-bold tabular-nums tracking-tight",children:[W.length,e.jsxs("span",{className:"text-sm font-normal text-muted-foreground",children:[" of ",l.length]})]})]})]})}),e.jsx(Ne,{className:"border-border/60",children:e.jsxs(Ie,{className:"flex items-center gap-3 p-4",children:[e.jsx("span",{className:"flex h-9 w-9 items-center justify-center rounded-lg bg-emerald-500/10 text-emerald-600",children:e.jsx(l7,{className:"h-4.5 w-4.5"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Monthly desk fees"}),e.jsx("p",{className:"text-2xl font-bold tabular-nums tracking-tight",children:Wf(V)}),e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"expected across assigned agents"})]})]})})]}),e.jsxs(ha,{defaultValue:"agents",className:"space-y-4",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsx("div",{className:"overflow-x-auto pb-1",children:e.jsxs(ma,{children:[e.jsx(Zt,{value:"agents",children:"Agents"}),e.jsx(Zt,{value:"plans",children:"Plans"}),e.jsx(Zt,{value:"company",children:"Company dollar"}),e.jsx(Zt,{value:"ledger",children:"Fees & statements"}),e.jsx(Zt,{value:"disbursements",children:"Disbursements"}),e.jsx(Zt,{value:"renewals",children:"Renewals & goals"})]})}),e.jsxs($,{size:"sm",onClick:()=>{I(null),C(!0)},children:[e.jsx(dn,{className:"mr-1.5 h-4 w-4"})," New plan"]})]}),e.jsx(Xt,{value:"agents",className:"space-y-2",children:e.jsxs(Ne,{className:"border-border/60",children:[e.jsxs(Ct,{className:"pb-2",children:[e.jsx(At,{className:"text-base",children:"Agent plans & cap progress"}),e.jsx(Gn,{children:"Assign a plan to each agent — their new deals inherit the splits and fees automatically"})]}),e.jsx(Ie,{className:"space-y-1 pt-2",children:o?Array.from({length:4}).map((Y,X)=>e.jsx(yn,{className:"h-16 w-full rounded-lg"},X)):l.length===0?e.jsx("p",{className:"py-8 text-center text-sm text-muted-foreground",children:"No agents in this brokerage yet."}):l.map(Y=>{var ae;const X=(ae=Y.progress)==null?void 0:ae.pct_to_cap;return e.jsxs("div",{className:"flex flex-col gap-3 rounded-lg px-2 py-3 hover:bg-muted/50 sm:flex-row sm:items-center",children:[e.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-3",children:[e.jsxs(Oa,{className:"h-9 w-9 shrink-0",children:[e.jsx(Li,{src:Y.avatarUrl||void 0,alt:Y.name}),e.jsx(za,{className:"text-[11px]",children:Y.name.slice(0,2).toUpperCase()})]}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"truncate text-sm font-medium",children:Y.name}),e.jsx("p",{className:"truncate text-[11px] text-muted-foreground",children:Y.email})]})]}),e.jsx("div",{className:"min-w-0 flex-1",children:Y.plan?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[e.jsx(Be,{variant:"secondary",className:"font-medium",children:Y.plan.name}),e.jsxs("span",{className:"text-[11px] text-muted-foreground",children:[Y.plan.agent_split_pct,"/",Math.max(0,100-Y.plan.agent_split_pct),Y.plan.cap_amount?` · ${Wf(Y.plan.cap_amount)} cap`:" · no cap"]})]}),Y.plan.cap_amount&&Y.progress?e.jsxs("div",{className:"mt-1.5 max-w-xs",children:[e.jsxs("div",{className:"mb-1 flex justify-between text-[11px] text-muted-foreground",children:[e.jsxs("span",{children:[hhe(Y.progress.cap_progress)," to cap"]}),e.jsxs("span",{children:[Math.round(X??0),"%"]})]}),e.jsx(Yi,{value:Math.min(100,X??0),className:"h-1.5"})]}):e.jsx("p",{className:"mt-1 text-[11px] text-muted-foreground",children:"No cap on this plan"})]}):e.jsx("p",{className:"text-[12px] italic text-muted-foreground",children:"No plan assigned"})}),e.jsxs("div",{className:"flex shrink-0 items-center gap-1.5",children:[e.jsx($,{variant:"outline",size:"sm",disabled:U.length===0,onClick:()=>{O(Y),R(!0)},children:Y.assignment?"Change plan":"Assign plan"}),Y.assignment&&e.jsx($,{variant:"ghost",size:"icon",className:"h-8 w-8 text-muted-foreground",title:"Remove plan",onClick:()=>u.mutate(Y.assignment.id),children:e.jsx(pV,{className:"h-4 w-4"})})]})]},Y.agentId)})})]})}),e.jsx(Xt,{value:"plans",className:"space-y-3",children:i?e.jsx("div",{className:"grid gap-3 md:grid-cols-2",children:Array.from({length:2}).map((Y,X)=>e.jsx(yn,{className:"h-44 w-full rounded-xl"},X))}):a.length===0?e.jsx(Ne,{className:"border-dashed",children:e.jsxs(Ie,{className:"flex flex-col items-center gap-3 py-12 text-center",children:[e.jsx("span",{className:"flex h-11 w-11 items-center justify-center rounded-xl bg-teal-500/10 text-teal-600",children:e.jsx(Rw,{className:"h-5 w-5"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:"No commission plans yet"}),e.jsx("p",{className:"mt-1 text-sm text-muted-foreground",children:"Create your first plan — e.g. a 70/30 split with an annual cap — then assign it to agents."})]}),e.jsxs($,{onClick:()=>{I(null),C(!0)},children:[e.jsx(dn,{className:"mr-1.5 h-4 w-4"})," Create plan"]})]})}):e.jsx("div",{className:"grid gap-3 md:grid-cols-2",children:a.map(Y=>e.jsxs(Ne,{className:`border-border/60 ${Y.is_active?"":"opacity-60"}`,children:[e.jsx(Ct,{className:"pb-2",children:e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsxs("div",{children:[e.jsx(At,{className:"text-base",children:Y.name}),Y.description&&e.jsx(Gn,{className:"mt-1",children:Y.description})]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[!Y.is_active&&e.jsx(Be,{variant:"outline",children:"Retired"}),e.jsxs(Be,{variant:"secondary",children:["v",Y.version_no]}),e.jsx($,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>{I(Y),C(!0)},children:e.jsx(gi,{className:"h-4 w-4"})})]})]})}),e.jsxs(Ie,{className:"grid grid-cols-2 gap-x-4 gap-y-2 pt-1 text-sm",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"Split (agent/brokerage)"}),e.jsxs("p",{className:"font-medium tabular-nums",children:[Y.agent_split_pct,"/",Math.max(0,100-Y.agent_split_pct)]})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"Annual cap"}),e.jsx("p",{className:"font-medium tabular-nums",children:Y.cap_amount?hhe(Y.cap_amount):"None"})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"Monthly desk fee"}),e.jsx("p",{className:"font-medium tabular-nums",children:Y.monthly_fee?hhe(Y.monthly_fee):"—"})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"Per-transaction fee"}),e.jsx("p",{className:"font-medium tabular-nums",children:Y.transaction_fee?hhe(Y.transaction_fee):"—"})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"Franchise fee"}),e.jsx("p",{className:"font-medium tabular-nums",children:Y.franchise_fee_pct?`${Y.franchise_fee_pct}%`:"—"})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"Team split"}),e.jsx("p",{className:"font-medium tabular-nums",children:Y.team_split_pct?`${Y.team_split_pct}%`:"—"})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"Agents on plan"}),e.jsx("p",{className:"font-medium tabular-nums",children:l.filter(X=>{var ae;return((ae=X.plan)==null?void 0:ae.id)===Y.id}).length})]})]})]},Y.id))})}),e.jsx(Xt,{value:"company",children:e.jsx(Rdr,{deals:h,ledger:f,roster:l,brokerageName:w,loading:m||o})}),e.jsx(Xt,{value:"ledger",children:e.jsx(Odr,{brokerageId:r,ledger:f,roster:l,loading:g||o})}),e.jsx(Xt,{value:"renewals",children:e.jsx($dr,{records:x,roster:l,deals:h,loading:y||o})}),e.jsx(Xt,{value:"disbursements",children:e.jsx(Qdr,{brokerageId:r,disbursements:v,deals:h,roster:l,brokerageName:w,loading:b||o})})]})]}),e.jsx(kdr,{open:S,onOpenChange:C,plan:E,saving:c.isPending,onSave:Y=>c.mutate(Y,{onSuccess:()=>C(!1)})}),e.jsx(Sdr,{open:P,onOpenChange:R,agent:D,plans:U,saving:d.isPending,onAssign:Y=>d.mutate(Y,{onSuccess:()=>R(!1)})})]})};function eur(){const[s,t]=j.useState(""),{data:n,isLoading:r}=tt({queryKey:["admin-brokerage-content-activity"],queryFn:async()=>{const{data:o}=await q.from("brokerages").select("id, name");if(!o)return[];const{data:c}=await q.from("brokerage_content").select("id, brokerage_id, content_type, created_at"),{data:d}=await q.from("brokerage_content_categories").select("id, brokerage_id"),u=c||[],h=d||[],m=o.map(f=>{const g=u.filter(v=>v.brokerage_id===f.id),x=h.filter(v=>v.brokerage_id===f.id),y=g.length>0?g.reduce((v,b)=>b.created_at>v?b.created_at:v,g[0].created_at):null;return{brokerage_id:f.id,brokerage_name:f.name,total_items:g.length,videos:g.filter(v=>v.content_type==="video").length,pdfs:g.filter(v=>v.content_type==="pdf").length,links:g.filter(v=>v.content_type==="link"||v.content_type==="canva_link").length,events:g.filter(v=>v.content_type==="event").length,graphics:g.filter(v=>v.content_type==="graphic").length,latest_item_date:y,categories:x.length}});return m.sort((f,g)=>g.total_items-f.total_items),m}}),a=(n||[]).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(Vs,{title:"Brokerage Content Activity",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(Fm,{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(Ne,{children:[e.jsx(Ct,{className:"pb-2",children:e.jsx(At,{className:"text-sm font-medium text-muted-foreground",children:"Active Brokerages"})}),e.jsxs(Ie,{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(Ne,{children:[e.jsx(Ct,{className:"pb-2",children:e.jsx(At,{className:"text-sm font-medium text-muted-foreground",children:"Total Content Items"})}),e.jsxs(Ie,{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(Ne,{children:[e.jsx(Ct,{className:"pb-2",children:e.jsx(At,{className:"text-sm font-medium text-muted-foreground",children:"Total Brokerages"})}),e.jsxs(Ie,{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(Kr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(pe,{placeholder:"Search brokerages...",value:s,onChange:o=>t(o.target.value),className:"pl-9"})]}),e.jsx(Ne,{children:e.jsx(Ie,{className:"p-0",children:e.jsxs(mi,{children:[e.jsx(fi,{children:e.jsxs(En,{children:[e.jsx(Dt,{children:"Brokerage"}),e.jsx(Dt,{className:"text-center",children:"Total"}),e.jsx(Dt,{className:"text-center",children:e.jsxs("div",{className:"flex items-center justify-center gap-1",children:[e.jsx(ua,{className:"h-3 w-3"})," Videos"]})}),e.jsx(Dt,{className:"text-center",children:e.jsxs("div",{className:"flex items-center justify-center gap-1",children:[e.jsx(Jr,{className:"h-3 w-3"})," PDFs"]})}),e.jsx(Dt,{className:"text-center",children:e.jsxs("div",{className:"flex items-center justify-center gap-1",children:[e.jsx(bd,{className:"h-3 w-3"})," Links"]})}),e.jsx(Dt,{className:"text-center",children:e.jsxs("div",{className:"flex items-center justify-center gap-1",children:[e.jsx(Kc,{className:"h-3 w-3"})," Events"]})}),e.jsx(Dt,{className:"text-center",children:e.jsxs("div",{className:"flex items-center justify-center gap-1",children:[e.jsx(Mc,{className:"h-3 w-3"})," Graphics"]})}),e.jsx(Dt,{className:"text-center",children:"Categories"}),e.jsx(Dt,{children:"Last Upload"})]})}),e.jsx(pi,{children:r?e.jsx(En,{children:e.jsx(wt,{colSpan:9,className:"text-center py-8 text-muted-foreground",children:"Loading..."})}):a.length===0?e.jsx(En,{children:e.jsx(wt,{colSpan:9,className:"text-center py-8 text-muted-foreground",children:"No brokerages found"})}):a.map(o=>e.jsxs(En,{className:o.total_items===0?"opacity-50":"",children:[e.jsx(wt,{children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ji,{className:"h-4 w-4 text-muted-foreground shrink-0"}),e.jsx("span",{className:"font-medium",children:o.brokerage_name})]})}),e.jsx(wt,{className:"text-center",children:o.total_items>0?e.jsx(Be,{variant:"secondary",className:"font-bold",children:o.total_items}):e.jsx("span",{className:"text-muted-foreground",children:"0"})}),e.jsx(wt,{className:"text-center",children:o.videos||"–"}),e.jsx(wt,{className:"text-center",children:o.pdfs||"–"}),e.jsx(wt,{className:"text-center",children:o.links||"–"}),e.jsx(wt,{className:"text-center",children:o.events||"–"}),e.jsx(wt,{className:"text-center",children:o.graphics||"–"}),e.jsx(wt,{className:"text-center",children:o.categories||"–"}),e.jsx(wt,{children:o.latest_item_date?e.jsx("span",{className:"text-sm text-muted-foreground",children:en(new Date(o.latest_item_date),"MMM d, yyyy")}):e.jsx("span",{className:"text-muted-foreground",children:"–"})})]},o.brokerage_id))})]})})})]})})}const tur=[{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:"📉"}],qEt=[{value:"instagram-square",label:"Instagram Post",dimensions:"1080×1080",icon:e.jsx(Tf,{className:"h-4 w-4"})},{value:"instagram-story",label:"Instagram Story",dimensions:"1080×1920",icon:e.jsx(Tf,{className:"h-4 w-4"})},{value:"facebook-post",label:"Facebook Post",dimensions:"1200×630",icon:e.jsx(Qp,{className:"h-4 w-4"})}],sur=[{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:"📰"}],VEt=s=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(s),HEt={"luxury-dark":Drt,"modern-clean":Frt,"bold-colorful":Ort,editorial:zrt};function nur(){const[s,t]=j.useState(""),[n,r]=j.useState("address"),[a,i]=j.useState(!1),[l,o]=j.useState([]),[c,d]=j.useState(null),[u,h]=j.useState(0),[m,f]=j.useState("just-listed"),[g,x]=j.useState(["instagram-square"]),[y,v]=j.useState("luxury-dark"),[b,w]=j.useState(!1),[S,C]=j.useState(""),[E,I]=j.useState(""),[P,R]=j.useState(""),[D,O]=j.useState(!1),[U,W]=j.useState(!1),[V,G]=j.useState([]),[Y,X]=j.useState("search"),ae=j.useRef({});j.useEffect(()=>{(async()=>{const{data:{user:Ee}}=await q.auth.getUser();if(!Ee)return;const{data:Se}=await q.from("profiles").select("name, avatar_url, brokerages(name)").eq("id",Ee.id).single();if(Se){C(Se.name||""),R(Se.avatar_url||"");const Le=Se.brokerages;I((Le==null?void 0:Le.name)||"")}})()},[]);const ie=async()=>{var ve;if(s.trim()){i(!0),o([]);try{const{data:Ee,error:Se}=await q.functions.invoke("repliers-mls-search",{body:{searchType:n,query:s.trim()}});if(Se)throw Se;if(Ee.error)throw new Error(Ee.error);o(Ee.listings||[]),((ve=Ee.listings)==null?void 0:ve.length)===0&&re.info("No listings found. Try a different search.")}catch(Ee){re.error(Ee.message||"Search failed")}finally{i(!1)}}},ne=ve=>{var Ee;d(ve),h(0),X("customize"),ve.soldDate||(Ee=ve.status)!=null&&Ee.toLowerCase().includes("sold")?f("just-sold"):f("just-listed")},te=ve=>{x(Ee=>Ee.includes(ve)?Ee.filter(Se=>Se!==ve):[...Ee,ve])},J=j.useCallback(async()=>{if(!(!c||g.length===0)){O(!0),G([]),X("generate");try{await new Promise(Ee=>setTimeout(Ee,500));const ve=[];for(const Ee of g){const Se=`${y}-${Ee}`,Le=ae.current[Se];if(!Le)continue;const Fe=jI[Ee],ke=await $G(Le,{width:Fe.width,height:Fe.height,pixelRatio:1,cacheBust:!0,style:{transform:"none",transformOrigin:"top left"}});ve.push({format:Ee,imageUrl:ke})}G(ve),re.success(`Generated ${ve.length} social post${ve.length>1?"s":""}!`)}catch(ve){re.error(ve.message||"Generation failed")}finally{O(!1)}}},[c,g,y,u,b,S,E,P,m]),ce=async()=>{if(!(!c||g.length===0)){O(!0),G([]),X("generate");try{const ve={...c,photos:c.photos.length>0?[c.photos[u]]:[]},Ee=[];for(const Se of g){const{data:Le,error:Fe}=await q.functions.invoke("generate-listing-social-post",{body:{listing:ve,postType:m,format:Se,branding:b?{enabled:!0,agentName:S,brokerage:E}:{enabled:!1}}});if(Fe)throw Fe;if(Le.error)throw new Error(Le.error);Ee.push({format:Se,imageUrl:Le.imageUrl})}G(Ee),re.success(`Generated ${Ee.length} AI post${Ee.length>1?"s":""}!`)}catch(ve){re.error(ve.message||"AI generation failed")}finally{O(!1)}}},_e=()=>U?ce():J(),he=(ve,Ee)=>{var Le;const Se=document.createElement("a");Se.href=ve,Se.download=`${((Le=c==null?void 0:c.address)==null?void 0:Le.replace(/\s+/g,"-"))||"listing"}-${m}-${Ee}.png`,document.body.appendChild(Se),Se.click(),document.body.removeChild(Se)},ue=c?{listing:c,postType:m,format:"instagram-square",branding:b?{enabled:!0,agentName:S,brokerage:E,agentPhotoUrl:P||void 0}:{enabled:!1},selectedPhotoIndex:u}:null;return e.jsx(Vs,{children:e.jsxs("div",{className:"space-y-6 p-4 md:p-8",children:[e.jsx(Fm,{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:()=>X("search"),className:`flex items-center gap-1.5 px-3 py-1.5 rounded-full transition-colors ${Y==="search"?"bg-primary text-primary-foreground":"bg-muted text-muted-foreground hover:text-foreground"}`,children:[e.jsx(Kr,{className:"h-3.5 w-3.5"})," 1. Find Listing"]}),e.jsx(Di,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("button",{onClick:()=>c&&X("customize"),disabled:!c,className:`flex items-center gap-1.5 px-3 py-1.5 rounded-full transition-colors ${Y==="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(Nn,{className:"h-3.5 w-3.5"})," 2. Customize"]}),e.jsx(Di,{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 ${Y==="generate"?"bg-primary text-primary-foreground":"bg-muted text-muted-foreground/50"}`,children:[e.jsx(Mc,{className:"h-3.5 w-3.5"})," 3. Generate"]})]}),Y==="search"&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs(Ne,{children:[e.jsxs(Ct,{children:[e.jsxs(At,{className:"flex items-center gap-2",children:[e.jsx(Kr,{className:"h-5 w-5 text-primary"})," Search MLS Listings ",e.jsx(JUt,{})]}),e.jsx(Gn,{children:"Find a listing by MLS number or property address using Repliers.io"})]}),e.jsxs(Ie,{className:"space-y-4",children:[e.jsx(ha,{value:n,onValueChange:ve=>r(ve),children:e.jsxs(ma,{children:[e.jsxs(Zt,{value:"address",children:[e.jsx(ci,{className:"h-4 w-4 mr-1.5"})," Address"]}),e.jsxs(Zt,{value:"mls",children:[e.jsx(Ap,{className:"h-4 w-4 mr-1.5"})," MLS #"]})]})}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(pe,{value:s,onChange:ve=>t(ve.target.value),placeholder:n==="mls"?"Enter MLS number...":"Enter property address...",className:"flex-1",onKeyDown:ve=>ve.key==="Enter"&&ie()}),e.jsxs($,{onClick:ie,disabled:a||!s.trim(),children:[a?e.jsx(kt,{className:"h-4 w-4 animate-spin"}):e.jsx(Kr,{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((ve,Ee)=>{var Se;return e.jsx(Ne,{className:"cursor-pointer hover:border-primary/50 hover:shadow-md transition-all group",onClick:()=>ne(ve),children:e.jsx(Ie,{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:(Se=ve.photos)!=null&&Se[0]?e.jsx("img",{src:ve.photos[0],alt:ve.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(va,{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:VEt(ve.price)}),e.jsx("p",{className:"text-sm text-muted-foreground truncate",children:ve.address}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[ve.city,", ",ve.state," ",ve.zip]}),e.jsxs("div",{className:"flex items-center gap-3 mt-1.5 text-xs text-muted-foreground",children:[ve.bedrooms>0&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(T4,{className:"h-3 w-3"})," ",ve.bedrooms]}),ve.bathrooms>0&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(T0,{className:"h-3 w-3"})," ",ve.bathrooms]}),ve.sqft>0&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(Zz,{className:"h-3 w-3"})," ",ve.sqft.toLocaleString()]})]}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx(Be,{variant:"outline",className:"text-[10px]",children:ve.mlsNumber}),e.jsx(Be,{variant:"outline",className:"text-[10px]",children:ve.status})]})]})]})})},ve.mlsNumber||Ee)})})]})]}),Y==="customize"&&c&&e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-3 gap-6",children:[e.jsxs(Ne,{className:"lg:col-span-1",children:[e.jsx(Ct,{className:"pb-3",children:e.jsx(At,{className:"text-base",children:"Selected Listing"})}),e.jsxs(Ie,{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[u],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($,{variant:"outline",size:"icon",className:"h-7 w-7",onClick:()=>h(ve=>Math.max(0,ve-1)),disabled:u===0,children:e.jsx(Cd,{className:"h-4 w-4"})}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[u+1," of ",c.photos.length]}),e.jsx($,{variant:"outline",size:"icon",className:"h-7 w-7",onClick:()=>h(ve=>Math.min(c.photos.length-1,ve+1)),disabled:u===c.photos.length-1,children:e.jsx(Di,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{children:[e.jsx("p",{className:"font-bold text-lg",children:VEt(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($,{variant:"outline",size:"sm",className:"w-full",onClick:()=>{X("search"),d(null)},children:[e.jsx(Ex,{className:"h-3.5 w-3.5 mr-1.5"})," Choose Different Listing"]})]})]}),e.jsxs(Ne,{className:"lg:col-span-2",children:[e.jsxs(Ct,{children:[e.jsxs(At,{className:"flex items-center gap-2",children:[e.jsx(Nn,{className:"h-5 w-5 text-primary"})," Customize Your Post"]}),e.jsx(Gn,{children:"Choose template, post type, format, and branding"})]}),e.jsxs(Ie,{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(Yc,{className:"h-4 w-4 text-primary"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",children:U?"AI Custom Generation":"Template-Based (Free)"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:U?"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(Sn,{checked:U,onCheckedChange:W}),U&&e.jsx(sy,{className:"h-4 w-4 text-purple-500"})]})]}),!U&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ee,{className:"text-sm font-medium flex items-center gap-2",children:[e.jsx(Yc,{className:"h-4 w-4"})," Template Style"]}),e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-2",children:sur.map(ve=>e.jsxs("button",{onClick:()=>v(ve.value),className:`flex flex-col items-center gap-1 px-3 py-3 rounded-lg border-2 transition-all text-center ${y===ve.value?"border-primary bg-primary/5":"border-border hover:border-primary/30"}`,children:[e.jsx("span",{className:"text-2xl",children:ve.preview}),e.jsx("span",{className:"text-sm font-medium",children:ve.label}),e.jsx("span",{className:"text-[10px] text-muted-foreground leading-tight",children:ve.description})]},ve.value))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{className:"text-sm font-medium",children:"Post Type"}),e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-2",children:tur.map(ve=>e.jsxs("button",{onClick:()=>f(ve.value),className:`flex items-center gap-2 px-3 py-2.5 rounded-lg border-2 transition-all text-sm font-medium ${m===ve.value?"border-primary bg-primary/5":"border-border hover:border-primary/30"}`,children:[e.jsx("span",{className:"text-lg",children:ve.icon})," ",ve.label]},ve.value))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{className:"text-sm font-medium",children:"Output Formats"}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-2",children:qEt.map(ve=>e.jsxs("button",{onClick:()=>te(ve.value),className:`flex items-center gap-2 px-3 py-2.5 rounded-lg border-2 transition-all text-sm ${g.includes(ve.value)?"border-primary bg-primary/5":"border-border hover:border-primary/30"}`,children:[ve.icon,e.jsxs("div",{className:"text-left",children:[e.jsx("p",{className:"font-medium",children:ve.label}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:ve.dimensions})]})]},ve.value))})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(ee,{className:"text-sm font-medium flex items-center gap-2",children:[e.jsx(sl,{className:"h-4 w-4"})," Agent Branding"]}),e.jsx(Sn,{checked:b,onCheckedChange:w})]}),b&&e.jsxs("div",{className:"space-y-3 pl-6 border-l-2 border-primary/20",children:[P&&e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("img",{src:P,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(ee,{className:"text-xs text-muted-foreground",children:"Agent Name"}),e.jsx(pe,{value:S,onChange:ve=>C(ve.target.value),placeholder:"Jane Smith"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(ee,{className:"text-xs text-muted-foreground",children:"Brokerage (optional)"}),e.jsx(pe,{value:E,onChange:ve=>I(ve.target.value),placeholder:"XYZ Realty"})]})]})]})]}),!U&&ue&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{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*(jI[g[0]||"instagram-square"].height/jI[g[0]||"instagram-square"].width)},children:(()=>{const ve=HEt[y],Ee=g[0]||"instagram-square";return e.jsx(ve,{...ue,format:Ee})})()})})]}),e.jsx($,{onClick:_e,disabled:g.length===0||D,size:"lg",className:"w-full gap-2",children:D?e.jsxs(e.Fragment,{children:[e.jsx(kt,{className:"h-5 w-5 animate-spin"})," Generating ",g.length," post",g.length>1?"s":"","..."]}):e.jsxs(e.Fragment,{children:[U?e.jsx(sy,{className:"h-5 w-5"}):e.jsx(Nn,{className:"h-5 w-5"}),"Generate ",g.length," Social Post",g.length>1?"s":"",U&&e.jsx(Be,{variant:"outline",className:"ml-2 text-[10px]",children:"Uses Credits"})]})})]})]})]}),Y==="generate"&&e.jsxs("div",{className:"space-y-4",children:[D&&e.jsx(Ne,{children:e.jsxs(Ie,{className:"flex flex-col items-center justify-center py-16",children:[e.jsx(kt,{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:U?"AI is creating your unique designs":"Rendering templates to high-res images"})]})}),V.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($,{variant:"outline",size:"sm",onClick:()=>X("customize"),children:[e.jsx(Ex,{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:V.map((ve,Ee)=>{const Se=qEt.find(Le=>Le.value===ve.format);return e.jsxs(Ne,{className:"overflow-hidden",children:[e.jsx("div",{className:"bg-muted/30 p-1",children:e.jsx("img",{src:ve.imageUrl,alt:`${ve.format} social post`,className:"w-full rounded"})}),e.jsxs(Ie,{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:[Se==null?void 0:Se.icon,e.jsx("span",{className:"text-sm font-medium",children:Se==null?void 0:Se.label})]}),e.jsx(Be,{variant:"outline",className:"text-[10px]",children:Se==null?void 0:Se.dimensions})]}),e.jsxs($,{size:"sm",className:"w-full gap-1.5",onClick:()=>he(ve.imageUrl,ve.format),children:[e.jsx(di,{className:"h-3.5 w-3.5"})," Download"]})]})]},Ee)})})]})]}),Y==="generate"&&!U&&c&&ue&&e.jsx("div",{style:{position:"absolute",left:"-9999px",top:0},"aria-hidden":!0,children:g.map(ve=>{const Ee=HEt[y],Se=jI[ve];return e.jsx("div",{style:{width:Se.width,height:Se.height},children:e.jsx(Ee,{ref:Le=>{ae.current[`${y}-${ve}`]=Le},...ue,format:ve})},`${y}-${ve}`)})})]})})}function rur(){return tt({queryKey:["lms-courses-admin"],queryFn:async()=>{const{data:s,error:t}=await q.from("lms_courses").select("*, modules:lms_modules(count), access:lms_course_access(*)").order("sort_order");if(t)throw t;return s}})}function aur(s){return tt({queryKey:["lms-course-admin",s],queryFn:async()=>{if(!s)return null;const{data:t,error:n}=await q.from("lms_courses").select("*, modules:lms_modules(*, resources:lms_module_resources(*)), access:lms_course_access(*)").eq("id",s).single();if(n)throw n;return t!=null&&t.modules&&(t.modules.sort((r,a)=>r.sort_order-a.sort_order),t.modules.forEach(r=>{r.resources&&r.resources.sort((a,i)=>a.sort_order-i.sort_order)})),t},enabled:!!s})}function iur(){const s=Vt();return ft({mutationFn:async t=>{const{data:n,error:r}=await q.from("lms_courses").insert(t).select().single();if(r)throw r;return n},onSuccess:()=>s.invalidateQueries({queryKey:["lms-courses"]})})}function ils(){const s=Vt();return ft({mutationFn:async({id:t,...n})=>{const{data:r,error:a}=await q.from("lms_courses").update({...n,updated_at:new Date().toISOString()}).eq("id",t).select().single();if(a)throw a;return r},onSuccess:()=>{s.invalidateQueries({queryKey:["lms-courses"]}),s.invalidateQueries({queryKey:["lms-course"]}),s.invalidateQueries({queryKey:["lms-courses-admin"]}),s.invalidateQueries({queryKey:["lms-course-admin"]})}})}function our(){const s=Vt();return ft({mutationFn:async t=>{const{error:n}=await q.from("lms_courses").delete().eq("id",t);if(n)throw n},onSuccess:()=>s.invalidateQueries({queryKey:["lms-courses"]})})}function lur(){const s=Vt();return ft({mutationFn:async t=>{const{data:n,error:r}=await q.from("lms_modules").insert(t).select().single();if(r)throw r;return n},onSuccess:()=>{s.invalidateQueries({queryKey:["lms-course"]}),s.invalidateQueries({queryKey:["lms-course-admin"]})}})}function cur(){const s=Vt();return ft({mutationFn:async({id:t,...n})=>{const{data:r,error:a}=await q.from("lms_modules").update({...n,updated_at:new Date().toISOString()}).eq("id",t).select().single();if(a)throw a;return r},onSuccess:()=>{s.invalidateQueries({queryKey:["lms-course"]}),s.invalidateQueries({queryKey:["lms-course-admin"]})}})}function dur(){const s=Vt();return ft({mutationFn:async t=>{const{error:n}=await q.from("lms_modules").delete().eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["lms-course"]}),s.invalidateQueries({queryKey:["lms-course-admin"]})}})}function uur(){const s=Vt();return ft({mutationFn:async t=>{const{data:n,error:r}=await q.from("lms_module_resources").insert(t).select().single();if(r)throw r;return n},onSuccess:()=>{s.invalidateQueries({queryKey:["lms-course"]}),s.invalidateQueries({queryKey:["lms-course-admin"]})}})}function hur(){const s=Vt();return ft({mutationFn:async t=>{const{error:n}=await q.from("lms_module_resources").delete().eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["lms-course"]}),s.invalidateQueries({queryKey:["lms-course-admin"]})}})}function mur(){const s=Vt();return ft({mutationFn:async({courseId:t,accessRules:n})=>{const{error:r}=await q.from("lms_course_access").delete().eq("course_id",t);if(r)throw r;if(n.length>0){const a=n.map(l=>({...l,course_id:t})),{error:i}=await q.from("lms_course_access").insert(a);if(i)throw i}},onSuccess:()=>{s.invalidateQueries({queryKey:["lms-courses"]}),s.invalidateQueries({queryKey:["lms-course"]})}})}function fur(){return tt({queryKey:["lms-courses-agent"],queryFn:async()=>{const{data:s,error:t}=await q.from("lms_courses").select("*, modules:lms_modules(id)").eq("is_published",!0).order("sort_order");if(t)throw t;return s}})}function pur(s){return tt({queryKey:["lms-course-agent",s],queryFn:async()=>{if(!s)return null;const{data:t,error:n}=await q.from("lms_courses").select("*, modules:lms_modules(*, resources:lms_module_resources(*))").eq("id",s).single();if(n)throw n;return t!=null&&t.modules&&(t.modules.sort((r,a)=>r.sort_order-a.sort_order),t.modules.forEach(r=>{r.resources&&r.resources.sort((a,i)=>a.sort_order-i.sort_order)})),t},enabled:!!s})}function ols(s){return tt({queryKey:["lms-progress",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await q.from("lms_progress").select("*").eq("course_id",s);if(n)throw n;return t},enabled:!!s})}function gur(){const s=Vt();return ft({mutationFn:async({courseId:t,moduleId:n,userId:r})=>{const{data:a,error:i}=await q.from("lms_progress").upsert({user_id:r,course_id:t,module_id:n,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 xur(){const{user:s}=vs(),t=Qn(),{data:n,isLoading:r}=rur(),a=iur(),i=ils(),l=our(),[o,c]=j.useState(!1),[d,u]=j.useState(""),[h,m]=j.useState(""),[f,g]=j.useState(!0),x=async()=>{if(!(!d.trim()||!s))try{const b=await a.mutateAsync({title:d.trim(),description:h.trim()||void 0,is_sequential:f,created_by:s.id});re.success("Course created"),c(!1),u(""),m(""),g(!0),t(`/admin/lms/${b.id}`)}catch{re.error("Failed to create course")}},y=async b=>{try{await i.mutateAsync({id:b.id,is_published:!b.is_published}),re.success(b.is_published?"Course unpublished":"Course published")}catch{re.error("Failed to update course")}},v=async b=>{if(await fo("Delete this course and all its modules? This cannot be undone."))try{await l.mutateAsync(b),re.success("Course deleted")}catch{re.error("Failed to delete")}};return e.jsxs(Vs,{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(of,{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($,{variant:"outline",onClick:()=>t("/admin/lms/stats"),children:[e.jsx(Wl,{className:"h-4 w-4 mr-2"}),"Analytics"]}),e.jsxs($,{onClick:()=>c(!0),children:[e.jsx(dn,{className:"h-4 w-4 mr-2"}),"New Course"]})]})]}),r?e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-4",children:[1,2,3].map(b=>e.jsx(Ne,{className:"animate-pulse",children:e.jsxs(Ct,{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"})]})},b))}):n!=null&&n.length?e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-4",children:n.map(b=>{var E,I;const w=((I=(E=b.modules)==null?void 0:E[0])==null?void 0:I.count)??0,S=b.access||[],C=S.length===0?"No access set":S.some(P=>P.access_type==="all")?"All agents":`${S.length} rule(s)`;return e.jsxs(Ne,{className:"group hover:shadow-md transition-all hover:border-primary/50 cursor-pointer",onClick:()=>t(`/admin/lms/${b.id}`),children:[e.jsx(Ct,{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(At,{className:"text-base truncate",children:b.title}),b.description&&e.jsx(Gn,{className:"mt-1 line-clamp-2",children:b.description})]}),e.jsx(Be,{variant:b.is_published?"default":"secondary",className:"ml-2 shrink-0",children:b.is_published?"Published":"Draft"})]})}),e.jsxs(Ie,{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(Xf,{className:"h-3.5 w-3.5"}),w," module",w!==1?"s":""]}),e.jsxs("span",{className:"flex items-center gap-1",children:[b.is_sequential?e.jsx(p2,{className:"h-3.5 w-3.5"}):e.jsx(n7,{className:"h-3.5 w-3.5"}),b.is_sequential?"Sequential":"Free order"]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Zn,{className:"h-3.5 w-3.5"}),C]})]}),e.jsxs("div",{className:"flex items-center gap-2 mt-3 opacity-0 group-hover:opacity-100 transition-opacity",children:[e.jsxs($,{size:"sm",variant:"ghost",onClick:P=>{P.stopPropagation(),y(b)},children:[b.is_published?e.jsx($g,{className:"h-3.5 w-3.5 mr-1"}):e.jsx(Ca,{className:"h-3.5 w-3.5 mr-1"}),b.is_published?"Unpublish":"Publish"]}),e.jsx($,{size:"sm",variant:"ghost",className:"text-destructive",onClick:P=>{P.stopPropagation(),v(b.id)},children:e.jsx(Wn,{className:"h-3.5 w-3.5"})}),e.jsx("div",{className:"flex-1"}),e.jsx(ei,{className:"h-4 w-4 text-muted-foreground"})]})]})]},b.id)})}):e.jsx(Ne,{className:"border-dashed",children:e.jsxs(Ie,{className:"flex flex-col items-center justify-center py-16 text-center",children:[e.jsx(Xf,{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($,{onClick:()=>c(!0),children:[e.jsx(dn,{className:"h-4 w-4 mr-2"}),"Create Course"]})]})})]}),e.jsx(zs,{open:o,onOpenChange:c,children:e.jsxs(Os,{children:[e.jsxs(Us,{children:[e.jsx(Bs,{children:"Create New Course"}),e.jsx(Ir,{children:"Set up a new training course for your agents"})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(ee,{children:"Course Title"}),e.jsx(pe,{value:d,onChange:b=>u(b.target.value),placeholder:"e.g. LevelUp Onboarding"})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Description"}),e.jsx(Rs,{value:h,onChange:b=>m(b.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(Sn,{checked:f,onCheckedChange:g})]})]}),e.jsxs(Ar,{children:[e.jsx($,{variant:"outline",onClick:()=>c(!1),children:"Cancel"}),e.jsx($,{onClick:x,disabled:!d.trim()||a.isPending,children:a.isPending?"Creating...":"Create Course"})]})]})})]})}function yur(){const{courseId:s}=Wi(),t=Qn(),{data:n,isLoading:r}=aur(s),a=ils(),i=lur(),l=cur(),o=dur(),c=uur(),d=hur(),u=mur(),{data:h}=tt({queryKey:["all-brokerages"],queryFn:async()=>{const{data:it}=await q.from("brokerages").select("id, name").order("name");return it||[]}}),[m,f]=j.useState(null),[g,x]=j.useState(!1),[y,v]=j.useState({title:"",description:"",video_url:"",text_content:"",duration_minutes:""}),[b,w]=j.useState(null),[S,C]=j.useState({title:"",resource_type:"link",url:""}),[E,I]=j.useState(new Set),[P,R]=j.useState(null),[D,O]=j.useState(0),[U,W]=j.useState(!1),V=j.useRef(null),G=j.useRef(null),[Y,X]=j.useState(!1),[ae,ie]=j.useState(""),[ne,te]=j.useState(""),[J,ce]=j.useState(""),[_e,he]=j.useState(!1);if(r)return e.jsx(Vs,{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(!n)return e.jsx(Vs,{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($,{variant:"outline",className:"mt-4",onClick:()=>t("/admin/lms"),children:[e.jsx(qa,{className:"h-4 w-4 mr-2"})," Back to Courses"]})]})});const ue=n.modules||[],ve=n.access||[],Ee=ve.some(it=>it.access_type==="all"),Se=ve.filter(it=>it.access_type==="brokerage").map(it=>it.brokerage_id),Le=(h||[]).filter(it=>it.name.toLowerCase().includes(ae.toLowerCase())),Fe=it=>{const at=new Set(E);at.has(it)?at.delete(it):at.add(it),I(at)},ke=async()=>{if(!P)return null;W(!0),O(0);try{const{data:it,error:at}=await q.functions.invoke("bunny-upload",{body:{action:"create",title:P.name}});if(at)throw new Error(at.message);const{videoId:Ke,libraryId:nt}=it,{data:xt,error:rt}=await q.functions.invoke("bunny-upload",{body:{action:"upload-url",videoId:Ke,libraryId:nt}});if(rt)throw new Error(rt.message);const Yt=new XMLHttpRequest;return await new Promise((qt,ts)=>{Yt.upload.onprogress=ys=>{ys.lengthComputable&&O(Math.round(ys.loaded/ys.total*100))},Yt.onload=()=>Yt.status>=200&&Yt.status<300?qt():ts(new Error(`Upload failed: ${Yt.status}`)),Yt.onerror=()=>ts(new Error("Upload failed")),Yt.open("PUT",xt.uploadUrl),Yt.setRequestHeader("AccessKey",xt.apiKey),Yt.send(P)}),`https://iframe.mediadelivery.net/embed/${nt}/${Ke}`}catch(it){return console.error("Bunny upload error:",it),re.error("Video upload failed"),null}finally{W(!1),O(0)}},Ve=async()=>{if(y.title.trim())try{let it=y.video_url.trim()||void 0;if(P){const at=await ke();if(!at)return;it=at}await i.mutateAsync({course_id:n.id,title:y.title.trim(),description:y.description.trim()||void 0,video_url:it,text_content:y.text_content.trim()||void 0,duration_minutes:y.duration_minutes?parseInt(y.duration_minutes):void 0,sort_order:ue.length}),re.success("Module added"),x(!1),v({title:"",description:"",video_url:"",text_content:"",duration_minutes:""}),R(null)}catch{re.error("Failed to add module")}},je=async()=>{if(m)try{let it=y.video_url.trim()||null;if(P){const at=await ke();if(!at)return;it=at}await l.mutateAsync({id:m.id,title:y.title.trim(),description:y.description.trim()||null,video_url:it,text_content:y.text_content.trim()||null,duration_minutes:y.duration_minutes?parseInt(y.duration_minutes):null}),re.success("Module updated"),f(null),R(null)}catch{re.error("Failed to update")}},Ae=async it=>{if(await fo("Delete this module?"))try{await o.mutateAsync(it),re.success("Module deleted")}catch{re.error("Failed to delete")}},Ce=async it=>{if(S.title.trim())try{await c.mutateAsync({module_id:it,title:S.title.trim(),resource_type:S.resource_type,url:S.url.trim()||void 0}),re.success("Resource added"),w(null),C({title:"",resource_type:"link",url:""})}catch{re.error("Failed to add resource")}},qe=async()=>{try{await u.mutateAsync({courseId:n.id,accessRules:[{access_type:"all"}]}),re.success("Access updated: All brokerages / all agents")}catch{re.error("Failed to update access")}},ze=async it=>{const at=ve.filter(rt=>rt.access_type==="brokerage").map(rt=>rt.brokerage_id),Ke=at.includes(it);let nt;Ke?nt=at.filter(rt=>rt!==it):nt=[...at,it];const xt=nt.map(rt=>({access_type:"brokerage",brokerage_id:rt}));try{await u.mutateAsync({courseId:n.id,accessRules:xt}),re.success(Ke?"Brokerage removed":"Brokerage added")}catch{re.error("Failed to update access")}},$e=async()=>{try{await u.mutateAsync({courseId:n.id,accessRules:[]}),re.success("Access cleared")}catch{re.error("Failed")}},ct=async(it,at)=>{const Ke=at==="up"?it-1:it+1;if(!(Ke<0||Ke>=ue.length))try{await Promise.all([l.mutateAsync({id:ue[it].id,sort_order:Ke}),l.mutateAsync({id:ue[Ke].id,sort_order:it})])}catch{re.error("Failed to reorder")}},Xe=async()=>{try{await a.mutateAsync({id:n.id,title:ne,description:J||null}),re.success("Course updated"),he(!1)}catch{re.error("Failed to update")}};return e.jsxs(Vs,{title:n.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($,{variant:"ghost",size:"icon",onClick:()=>t("/admin/lms"),children:e.jsx(qa,{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:n.title}),e.jsx(Be,{variant:n.is_published?"default":"secondary",children:n.is_published?"Published":"Draft"})]}),n.description&&e.jsx("p",{className:"text-muted-foreground mt-1",children:n.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:[n.is_sequential?e.jsx(p2,{className:"h-3.5 w-3.5"}):e.jsx(n7,{className:"h-3.5 w-3.5"}),n.is_sequential?"Sequential":"Free order"]}),e.jsxs("span",{children:[ue.length," module",ue.length!==1?"s":""]})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs($,{variant:"outline",size:"sm",onClick:()=>{te(n.title),ce(n.description||""),he(!0)},children:[e.jsx(gi,{className:"h-3.5 w-3.5 mr-1"})," Edit"]}),e.jsxs($,{variant:n.is_published?"secondary":"default",size:"sm",onClick:()=>a.mutateAsync({id:n.id,is_published:!n.is_published}).then(()=>re.success(n.is_published?"Unpublished":"Published")),children:[n.is_published?e.jsx($g,{className:"h-3.5 w-3.5 mr-1"}):e.jsx(Ca,{className:"h-3.5 w-3.5 mr-1"}),n.is_published?"Unpublish":"Publish"]})]})]}),e.jsxs(ha,{defaultValue:"modules",className:"w-full",children:[e.jsxs(ma,{children:[e.jsx(Zt,{value:"modules",children:"Modules"}),e.jsx(Zt,{value:"access",children:"Access & Permissions"}),e.jsx(Zt,{value:"settings",children:"Settings"})]}),e.jsxs(Xt,{value:"modules",className:"mt-6 space-y-4",children:[ue.map((it,at)=>e.jsxs(Ne,{className:"overflow-hidden",children:[e.jsxs("div",{className:"flex items-center gap-3 p-4 cursor-pointer hover:bg-muted/50 transition-colors",onClick:()=>Fe(it.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:Ke=>{Ke.stopPropagation(),ct(at,"up")},disabled:at===0,className:"hover:text-foreground disabled:opacity-30",children:e.jsx(v1,{className:"h-3.5 w-3.5"})}),e.jsx("button",{onClick:Ke=>{Ke.stopPropagation(),ct(at,"down")},disabled:at===ue.length-1,className:"hover:text-foreground disabled:opacity-30",children:e.jsx(Tl,{className:"h-3.5 w-3.5"})})]})}),e.jsx(Be,{variant:"outline",className:"shrink-0 font-mono text-xs",children:at+1}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-medium text-sm truncate",children:it.title}),e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground mt-0.5",children:[it.video_url&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(ua,{className:"h-3 w-3"})," Video"]}),it.text_content&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(Jr,{className:"h-3 w-3"})," Text"]}),it.duration_minutes&&e.jsxs("span",{children:[it.duration_minutes," min"]}),it.resources&&it.resources.length>0&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(bd,{className:"h-3 w-3"})," ",it.resources.length," resource(s)"]})]})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx($,{size:"sm",variant:"ghost",onClick:Ke=>{var nt;Ke.stopPropagation(),f(it),v({title:it.title,description:it.description||"",video_url:it.video_url||"",text_content:it.text_content||"",duration_minutes:((nt=it.duration_minutes)==null?void 0:nt.toString())||""})},children:e.jsx(gi,{className:"h-3.5 w-3.5"})}),e.jsx($,{size:"sm",variant:"ghost",className:"text-destructive",onClick:Ke=>{Ke.stopPropagation(),Ae(it.id)},children:e.jsx(Wn,{className:"h-3.5 w-3.5"})})]})]}),E.has(it.id)&&e.jsxs("div",{className:"border-t bg-muted/30 p-4 space-y-3",children:[it.description&&e.jsx("p",{className:"text-sm text-muted-foreground",children:it.description}),it.video_url&&e.jsxs("div",{className:"text-xs",children:[e.jsx("span",{className:"text-muted-foreground",children:"Video: "}),e.jsx("a",{href:it.video_url,target:"_blank",rel:"noreferrer",className:"text-primary hover:underline break-all",children:it.video_url})]}),it.text_content&&e.jsx("div",{className:"text-sm bg-background rounded-md p-3 border max-h-40 overflow-auto whitespace-pre-wrap",children:it.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($,{size:"sm",variant:"outline",className:"h-7 text-xs",onClick:()=>{w(it.id),C({title:"",resource_type:"link",url:""})},children:[e.jsx(dn,{className:"h-3 w-3 mr-1"})," Add Resource"]})]}),it.resources&&it.resources.length>0?e.jsx("div",{className:"space-y-1",children:it.resources.map(Ke=>e.jsxs("div",{className:"flex items-center gap-2 text-sm bg-background rounded p-2 border",children:[e.jsx(Be,{variant:"outline",className:"text-[10px]",children:Ke.resource_type}),e.jsx("span",{className:"flex-1 truncate",children:Ke.title}),Ke.url&&e.jsx("a",{href:Ke.url,target:"_blank",rel:"noreferrer",className:"text-primary hover:underline text-xs",children:"Open"}),e.jsx($,{size:"sm",variant:"ghost",className:"h-6 w-6 p-0 text-destructive",onClick:()=>d.mutateAsync(Ke.id),children:e.jsx(gr,{className:"h-3 w-3"})})]},Ke.id))}):e.jsx("p",{className:"text-xs text-muted-foreground",children:"No resources yet"})]})]})]},it.id)),e.jsxs($,{variant:"outline",className:"w-full border-dashed",onClick:()=>{x(!0),v({title:"",description:"",video_url:"",text_content:"",duration_minutes:""})},children:[e.jsx(dn,{className:"h-4 w-4 mr-2"})," Add Module"]})]}),e.jsx(Xt,{value:"access",className:"mt-6 space-y-4",children:e.jsxs(Ne,{children:[e.jsx(Ct,{children:e.jsx(At,{className:"text-base",children:"Who can access this course?"})}),e.jsxs(Ie,{className:"space-y-5",children:[e.jsxs("div",{className:Pt("flex items-center gap-3 p-4 rounded-xl border-2 cursor-pointer transition-all",Ee?"border-primary bg-primary/5":"border-muted hover:border-muted-foreground/30"),onClick:qe,children:[e.jsx("div",{className:Pt("h-10 w-10 rounded-full flex items-center justify-center shrink-0",Ee?"bg-primary/15 text-primary":"bg-muted text-muted-foreground"),children:e.jsx(dl,{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(Sn,{checked:Ee,onCheckedChange:qe})]}),!Ee&&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:Se.length===0?"No brokerages selected — agents won't see this course":`${Se.length} brokerage${Se.length!==1?"s":""} selected`})]}),Se.length>0&&e.jsx($,{size:"sm",variant:"ghost",className:"text-xs text-muted-foreground",onClick:$e,children:"Clear all"})]}),e.jsx(pe,{placeholder:"Search brokerages...",value:ae,onChange:it=>ie(it.target.value),className:"h-9"}),e.jsx("div",{className:"border rounded-lg divide-y max-h-[360px] overflow-auto",children:Le.length===0?e.jsx("div",{className:"p-4 text-center text-sm text-muted-foreground",children:"No brokerages found"}):Le.map(it=>{const at=Se.includes(it.id);return e.jsxs("div",{className:Pt("flex items-center gap-3 px-3 py-2.5 cursor-pointer transition-colors",at?"bg-primary/5":"hover:bg-muted/50"),onClick:()=>ze(it.id),children:[e.jsx("div",{className:Pt("h-5 w-5 rounded border-2 flex items-center justify-center shrink-0 transition-colors",at?"bg-primary border-primary":"border-muted-foreground/30"),children:at&&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(ji,{className:"h-4 w-4 text-muted-foreground shrink-0"}),e.jsx("span",{className:"text-sm flex-1 truncate",children:it.name}),at&&e.jsx(Be,{variant:"secondary",className:"text-[10px] shrink-0",children:"Active"})]},it.id)})})]})]})]})}),e.jsxs(Xt,{value:"settings",className:"mt-6 space-y-4",children:[e.jsxs(Ne,{children:[e.jsx(Ct,{children:e.jsx(At,{className:"text-base",children:"Course Thumbnail"})}),e.jsx(Ie,{children:e.jsxs("div",{className:"flex items-start gap-6",children:[n.thumbnail_url?e.jsxs("div",{className:"relative group",children:[e.jsx("img",{src:n.thumbnail_url,alt:"Course thumbnail",className:"w-48 h-28 object-cover rounded-lg border"}),e.jsx("button",{onClick:()=>a.mutateAsync({id:n.id,thumbnail_url:null}).then(()=>re.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(gr,{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(Av,{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:G,type:"file",accept:"image/*",className:"hidden",onChange:async it=>{var Ke;const at=(Ke=it.target.files)==null?void 0:Ke[0];if(!(!at||!n)){X(!0);try{const nt=at.name.split(".").pop(),xt=`${n.id}/thumbnail.${nt}`,{error:rt}=await q.storage.from("lms-thumbnails").upload(xt,at,{upsert:!0});if(rt)throw rt;const{data:Yt}=q.storage.from("lms-thumbnails").getPublicUrl(xt),qt=`${Yt.publicUrl}?t=${Date.now()}`;await a.mutateAsync({id:n.id,thumbnail_url:qt}),re.success("Thumbnail uploaded")}catch{re.error("Failed to upload thumbnail")}finally{X(!1),G.current&&(G.current.value="")}}}}),e.jsxs($,{variant:"outline",size:"sm",disabled:Y,onClick:()=>{var it;return(it=G.current)==null?void 0:it.click()},children:[Y?e.jsx(kt,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(ni,{className:"h-4 w-4 mr-2"}),Y?"Uploading...":"Upload Thumbnail"]})]})]})})]}),e.jsxs(Ne,{children:[e.jsx(Ct,{children:e.jsx(At,{className:"text-base",children:"Course Settings"})}),e.jsxs(Ie,{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(Sn,{checked:n.is_sequential,onCheckedChange:it=>a.mutateAsync({id:n.id,is_sequential:it}).then(()=>re.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(Sn,{checked:n.is_published,onCheckedChange:it=>a.mutateAsync({id:n.id,is_published:it}).then(()=>re.success("Updated"))})]})]})]})]})]})]}),e.jsx(zs,{open:g||!!m,onOpenChange:it=>{it||(x(!1),f(null))},children:e.jsxs(Os,{className:"max-w-lg",children:[e.jsxs(Us,{children:[e.jsx(Bs,{children:m?"Edit Module":"Add Module"}),e.jsx(Ir,{children:"Configure the module content"})]}),e.jsxs("div",{className:"space-y-4 max-h-[60vh] overflow-auto",children:[e.jsxs("div",{children:[e.jsx(ee,{children:"Title"}),e.jsx(pe,{value:y.title,onChange:it=>v(at=>({...at,title:it.target.value})),placeholder:"Module title"})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Description"}),e.jsx(Rs,{value:y.description,onChange:it=>v(at=>({...at,description:it.target.value})),placeholder:"Brief description",rows:2})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Video"}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:Pt("border-2 border-dashed rounded-lg p-4 text-center cursor-pointer transition-colors hover:border-primary/50",P?"border-primary bg-primary/5":"border-muted-foreground/25"),onClick:()=>{var it;return(it=V.current)==null?void 0:it.click()},children:[e.jsx("input",{ref:V,type:"file",accept:"video/*",className:"hidden",onChange:it=>{var Ke;const at=(Ke=it.target.files)==null?void 0:Ke[0];at&&(R(at),v(nt=>({...nt,video_url:""})))}}),P?e.jsxs("div",{className:"flex items-center justify-center gap-2 text-sm",children:[e.jsx(ua,{className:"h-4 w-4 text-primary"}),e.jsx("span",{className:"font-medium text-primary",children:P.name}),e.jsx($,{type:"button",size:"sm",variant:"ghost",className:"h-6 w-6 p-0",onClick:it=>{it.stopPropagation(),R(null)},children:e.jsx(gr,{className:"h-3 w-3"})})]}):e.jsxs("div",{className:"flex flex-col items-center gap-1 text-muted-foreground",children:[e.jsx(ni,{className:"h-5 w-5"}),e.jsx("span",{className:"text-xs",children:"Click to upload a video file"})]})]}),U&&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(kt,{className:"h-3.5 w-3.5 animate-spin"}),e.jsxs("span",{children:["Uploading to Bunny.net... ",D,"%"]})]}),e.jsx(Yi,{value:D,className:"h-1.5"})]}),!P&&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(pe,{value:y.video_url,onChange:it=>v(at=>({...at,video_url:it.target.value})),placeholder:"YouTube, Vimeo, or Bunny.net URL"})]})]})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Text Content"}),e.jsx(Rs,{value:y.text_content,onChange:it=>v(at=>({...at,text_content:it.target.value})),placeholder:"Additional text content, instructions, notes...",rows:4})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Duration (minutes)"}),e.jsx(pe,{type:"number",value:y.duration_minutes,onChange:it=>v(at=>({...at,duration_minutes:it.target.value})),placeholder:"e.g. 15"})]})]}),e.jsxs(Ar,{children:[e.jsx($,{variant:"outline",onClick:()=>{x(!1),f(null),R(null)},children:"Cancel"}),e.jsxs($,{onClick:m?je:Ve,disabled:!y.title.trim()||U,children:[U?e.jsx(kt,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(tl,{className:"h-4 w-4 mr-2"}),U?"Uploading...":m?"Save Changes":"Add Module"]})]})]})}),e.jsx(zs,{open:!!b,onOpenChange:it=>{it||w(null)},children:e.jsxs(Os,{children:[e.jsxs(Us,{children:[e.jsx(Bs,{children:"Add Resource"}),e.jsx(Ir,{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(ee,{children:"Title"}),e.jsx(pe,{value:S.title,onChange:it=>C(at=>({...at,title:it.target.value})),placeholder:"Resource title"})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Type"}),e.jsxs(ms,{value:S.resource_type,onValueChange:it=>C(at=>({...at,resource_type:it})),children:[e.jsx(us,{children:e.jsx(fs,{})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"link",children:"Link"}),e.jsx(Ge,{value:"pdf",children:"PDF"}),e.jsx(Ge,{value:"template",children:"Template"}),e.jsx(Ge,{value:"worksheet",children:"Worksheet"})]})]})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"URL"}),e.jsx(pe,{value:S.url,onChange:it=>C(at=>({...at,url:it.target.value})),placeholder:"https://..."})]})]}),e.jsxs(Ar,{children:[e.jsx($,{variant:"outline",onClick:()=>w(null),children:"Cancel"}),e.jsx($,{onClick:()=>b&&Ce(b),disabled:!S.title.trim(),children:"Add Resource"})]})]})}),e.jsx(zs,{open:_e,onOpenChange:he,children:e.jsxs(Os,{children:[e.jsxs(Us,{children:[e.jsx(Bs,{children:"Edit Course"}),e.jsx(Ir,{children:"Update the course title and description"})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(ee,{children:"Title"}),e.jsx(pe,{value:ne,onChange:it=>te(it.target.value)})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Description"}),e.jsx(Rs,{value:J,onChange:it=>ce(it.target.value),rows:3})]})]}),e.jsxs(Ar,{children:[e.jsx($,{variant:"outline",onClick:()=>he(!1),children:"Cancel"}),e.jsx($,{onClick:Xe,disabled:!ne.trim(),children:"Save"})]})]})})]})}function vur(){return tt({queryKey:["lms-stats-overview"],queryFn:async()=>{const{data:s,error:t}=await q.rpc("get_lms_stats");if(t)throw t;return s}})}function bur(){return tt({queryKey:["lms-stats-courses"],queryFn:async()=>{const{data:s,error:t}=await q.rpc("get_lms_course_stats");if(t)throw t;return s||[]}})}function _ur(s){return tt({queryKey:["lms-stats-agents",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await q.rpc("get_lms_agent_progress",{p_course_id:s});if(n)throw n;return t||[]},enabled:!!s})}function wur(){const s=Qn(),{data:t,isLoading:n}=vur(),{data:r,isLoading:a}=bur(),[i,l]=j.useState(null),{data:o,isLoading:c}=_ur(i),[d,u]=j.useState(""),h=r==null?void 0:r.find(g=>g.course_id===i),m=o==null?void 0:o.filter(g=>{var x,y;return!d||((x=g.agent_name)==null?void 0:x.toLowerCase().includes(d.toLowerCase()))||((y=g.email)==null?void 0:y.toLowerCase().includes(d.toLowerCase()))}),f=[{label:"Total Courses",value:(t==null?void 0:t.total_courses)??0,icon:Xf,color:"text-primary"},{label:"Published",value:(t==null?void 0:t.published_courses)??0,icon:qr,color:"text-emerald-500"},{label:"Enrolled Agents",value:(t==null?void 0:t.total_enrollments)??0,icon:Zn,color:"text-blue-500"},{label:"Modules Completed",value:(t==null?void 0:t.total_completions)??0,icon:Kl,color:"text-amber-500"},{label:"Active (30d)",value:(t==null?void 0:t.active_learners)??0,icon:Yl,color:"text-violet-500"},{label:"Total Modules",value:(t==null?void 0:t.total_modules)??0,icon:Wl,color:"text-rose-500"}];return e.jsx(Vs,{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($,{variant:"ghost",size:"icon",onClick:()=>s("/admin/lms"),children:e.jsx(qa,{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(of,{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:f.map(g=>e.jsx(Ne,{className:Pt("transition-all",n&&"animate-pulse"),children:e.jsxs(Ie,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx(g.icon,{className:Pt("h-4 w-4",g.color)}),e.jsx("span",{className:"text-xs font-medium text-muted-foreground",children:g.label})]}),e.jsx("p",{className:"text-2xl font-bold text-foreground",children:n?"—":g.value})]})},g.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(Wl,{className:"h-5 w-5 text-primary"}),"Course Breakdown"]}),a?e.jsx("div",{className:"space-y-3",children:[1,2,3].map(g=>e.jsx(Ne,{className:"animate-pulse",children:e.jsx(Ie,{className:"p-4",children:e.jsx("div",{className:"h-16 bg-muted rounded"})})},g))}):r!=null&&r.length?e.jsx("div",{className:"space-y-2",children:r.map(g=>{const x=i===g.course_id;return e.jsx(Ne,{className:Pt("cursor-pointer transition-all hover:shadow-md",x?"border-primary ring-1 ring-primary/30 shadow-md":"hover:border-primary/40"),onClick:()=>l(x?null:g.course_id),children:e.jsxs(Ie,{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:g.course_title}),e.jsx(Be,{variant:g.is_published?"default":"secondary",className:"shrink-0 text-[10px] px-1.5 py-0",children:g.is_published?"Live":"Draft"})]})}),e.jsx(Di,{className:Pt("h-4 w-4 text-muted-foreground transition-transform shrink-0 ml-2",x&&"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:g.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:g.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:g.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:[g.avg_completion_pct,"%"]})]}),e.jsx(Yi,{value:g.avg_completion_pct,className:"h-2"})]})]})},g.course_id)})}):e.jsx(Ne,{className:"border-dashed",children:e.jsx(Ie,{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(y2,{className:"h-5 w-5 text-primary"}),h?`Agent Progress — ${h.course_title}`:"Agent Progress"]}),i?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"relative",children:[e.jsx(Kr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(pe,{value:d,onChange:g=>u(g.target.value),placeholder:"Search agents...",className:"pl-9"})]}),c?e.jsx("div",{className:"space-y-2",children:[1,2,3,4].map(g=>e.jsx(Ne,{className:"animate-pulse",children:e.jsx(Ie,{className:"p-4",children:e.jsx("div",{className:"h-12 bg-muted rounded"})})},g))}):m!=null&&m.length?e.jsx("div",{className:"space-y-2 max-h-[600px] overflow-y-auto pr-1",children:m.map((g,x)=>{const y=g.completion_pct>=100;return e.jsx(Ne,{className:Pt("transition-all",y&&"border-emerald-200 bg-emerald-50/30 dark:border-emerald-900/40 dark:bg-emerald-950/10"),children:e.jsx(Ie,{className:"p-4",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:Pt("flex items-center justify-center w-7 h-7 rounded-full text-xs font-bold shrink-0",x===0?"bg-amber-100 text-amber-700 dark:bg-amber-900/30 dark:text-amber-400":x===1?"bg-slate-100 text-slate-600 dark:bg-slate-800 dark:text-slate-400":x===2?"bg-orange-100 text-orange-700 dark:bg-orange-900/30 dark:text-orange-400":"bg-muted text-muted-foreground"),children:x+1}),e.jsxs(Oa,{className:"h-9 w-9 shrink-0",children:[e.jsx(Li,{src:g.avatar_url||void 0}),e.jsx(za,{className:"text-xs bg-primary/10 text-primary",children:(g.agent_name||g.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:g.agent_name||g.email}),y&&e.jsxs(Be,{variant:"default",className:"text-[10px] px-1.5 py-0 bg-emerald-500 hover:bg-emerald-600 shrink-0",children:[e.jsx(qr,{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:[g.modules_completed,"/",g.total_modules," modules"]}),g.last_activity&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(da,{className:"h-3 w-3"}),en(new Date(g.last_activity),"MMM d, yyyy")]})]})]}),e.jsxs("div",{className:"text-right shrink-0 w-20",children:[e.jsxs("p",{className:Pt("text-sm font-bold",y?"text-emerald-600 dark:text-emerald-400":"text-foreground"),children:[g.completion_pct,"%"]}),e.jsx(Yi,{value:g.completion_pct,className:"h-1.5 mt-1"})]})]})})},g.user_id)})}):e.jsx(Ne,{className:"border-dashed",children:e.jsx(Ie,{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(Ne,{className:"border-dashed",children:e.jsxs(Ie,{className:"py-16 text-center",children:[e.jsx(Zn,{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 jur(){const{user:s}=vs(),t=Qn(),{data:n,isLoading:r}=fur();return e.jsx(Vs,{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(of,{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"})]}),r?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(Ne,{className:"animate-pulse",children:e.jsxs(Ie,{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))}):n!=null&&n.length?e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:n.map(a=>e.jsx(Nur,{course:a,userId:s==null?void 0:s.id,onClick:()=>t(`/levelup-u/${a.id}`)},a.id))}):e.jsx(Ne,{className:"border-dashed",children:e.jsxs(Ie,{className:"flex flex-col items-center justify-center py-16 text-center",children:[e.jsx(Xf,{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 Nur({course:s,userId:t,onClick:n}){var o;const r=((o=s.modules)==null?void 0:o.length)??0,{data:a}=ols(s.id),i=(a==null?void 0:a.filter(c=>c.completed).length)??0,l=r>0?Math.round(i/r*100):0;return e.jsxs(Ne,{className:"group cursor-pointer hover:shadow-lg transition-all hover:border-primary/50 overflow-hidden",onClick:n,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(of,{className:"h-10 w-10 text-primary/40"})}),e.jsxs(Ie,{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(Xf,{className:"h-3.5 w-3.5"}),r," module",r!==1?"s":""]}),e.jsxs("span",{className:"flex items-center gap-1",children:[s.is_sequential?e.jsx(p2,{className:"h-3.5 w-3.5"}):e.jsx(n7,{className:"h-3.5 w-3.5"}),s.is_sequential?"In order":"Any order"]})]}),r>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 ",r," completed"]}),e.jsxs("span",{className:"font-medium text-foreground",children:[l,"%"]})]}),e.jsx(Yi,{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(Di,{className:"h-3.5 w-3.5"})]})})]})]})}function kur(){const{courseId:s}=Wi(),t=Qn(),{user:n}=vs(),{data:r,isLoading:a}=pur(s),{data:i}=ols(s),l=gur(),[o,c]=j.useState(null),d=(r==null?void 0:r.modules)||[],u=new Set((i==null?void 0:i.filter(b=>b.completed).map(b=>b.module_id))||[]),h=u.size,m=d.length>0?Math.round(h/d.length*100):0;j.useEffect(()=>{if(d.length>0&&!o){const b=d.find(w=>!u.has(w.id));c((b==null?void 0:b.id)||d[0].id)}},[d,o,u]);const f=d.find(b=>b.id===o),g=d.findIndex(b=>b.id===o),x=(b,w)=>{if(!(r!=null&&r.is_sequential)||w===0)return!1;for(let S=0;S{if(!(!f||!n||!s))try{await l.mutateAsync({courseId:s,moduleId:f.id,userId:n.id}),re.success("Module completed! 🎉"),g{const w=b.match(/(?:youtube\.com\/(?:watch\?v=|embed\/)|youtu\.be\/)([a-zA-Z0-9_-]{11})/);if(w)return`https://www.youtube.com/embed/${w[1]}`;const S=b.match(/vimeo\.com\/(\d+)/);if(S)return`https://player.vimeo.com/video/${S[1]}`;const C=b.match(/(?:iframe\.mediadelivery\.net|video\.bunnycdn\.com)\/(?:play|embed)\/(\d+)\/([a-f0-9-]+)/);return C?`https://iframe.mediadelivery.net/embed/${C[1]}/${C[2]}?responsive=true`:b};return a?e.jsx(Vs,{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"})})}):r?e.jsx(Vs,{title:r.title,children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx($,{variant:"ghost",size:"icon",onClick:()=>t("/levelup-u"),children:e.jsx(qa,{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:r.title}),e.jsxs("div",{className:"flex items-center gap-3 text-xs text-muted-foreground mt-0.5",children:[e.jsxs("span",{children:[h,"/",d.length," completed"]}),e.jsxs("span",{children:[m,"%"]})]})]}),e.jsx("div",{className:"w-32",children:e.jsx(Yi,{value:m,className:"h-2"})})]}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-[320px_1fr] gap-4 items-start",children:[e.jsx(Ne,{className:"lg:sticky lg:top-4",children:e.jsxs(Ie,{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(uo,{className:"max-h-[calc(100vh-280px)]",children:e.jsx("div",{className:"p-1",children:d.map((b,w)=>{const S=x(b,w),C=u.has(b.id),E=b.id===o;return e.jsxs("button",{disabled:S,onClick:()=>!S&&c(b.id),className:Pt("w-full flex items-center gap-3 p-3 rounded-lg text-left transition-all text-sm",E?"bg-primary/10 text-primary":"hover:bg-muted/50",S&&"opacity-50 cursor-not-allowed"),children:[e.jsx("div",{className:"shrink-0",children:S?e.jsx(pc,{className:"h-4 w-4 text-muted-foreground"}):C?e.jsx(qr,{className:"h-4 w-4 text-green-500"}):e.jsx(Og,{className:"h-4 w-4 text-muted-foreground"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("p",{className:Pt("font-medium truncate",E&&"text-primary"),children:[w+1,". ",b.title]}),b.duration_minutes&&e.jsxs("span",{className:"text-[11px] text-muted-foreground flex items-center gap-0.5 mt-0.5",children:[e.jsx(da,{className:"h-3 w-3"})," ",b.duration_minutes," min"]})]})]},b.id)})})})]})}),e.jsx("div",{className:"space-y-4",children:f?e.jsxs(e.Fragment,{children:[f.video_url&&e.jsx(Ne,{className:"overflow-hidden",children:e.jsx("div",{className:"aspect-video bg-black",children:e.jsx("iframe",{src:v(f.video_url),className:"w-full h-full",allow:"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture",allowFullScreen:!0})})}),e.jsx(Ne,{children:e.jsxs(Ie,{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:f.title}),f.description&&e.jsx("p",{className:"text-muted-foreground mt-1",children:f.description})]}),u.has(f.id)?e.jsxs(Be,{className:"bg-green-500/15 text-green-600 border-green-500/30 shrink-0",children:[e.jsx(qr,{className:"h-3.5 w-3.5 mr-1"})," Completed"]}):e.jsxs($,{size:"sm",onClick:y,disabled:l.isPending,children:[e.jsx(qr,{className:"h-4 w-4 mr-1"}),"Mark Complete"]})]}),f.text_content&&e.jsx("div",{className:"prose prose-sm max-w-none text-foreground border-t pt-4 whitespace-pre-wrap",children:f.text_content}),f.resources&&f.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:f.resources.map(b=>e.jsxs("a",{href:b.url||b.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:[b.resource_type==="pdf"?e.jsx(Jr,{className:"h-4 w-4 text-red-500 shrink-0"}):b.resource_type==="template"?e.jsx(of,{className:"h-4 w-4 text-purple-500 shrink-0"}):e.jsx(bd,{className:"h-4 w-4 text-blue-500 shrink-0"}),e.jsx("span",{className:"flex-1 truncate",children:b.title}),e.jsx(kr,{className:"h-3.5 w-3.5 text-muted-foreground shrink-0"})]},b.id))})]}),e.jsxs("div",{className:"flex items-center justify-between border-t pt-4",children:[e.jsxs($,{variant:"outline",size:"sm",disabled:g===0,onClick:()=>g>0&&c(d[g-1].id),children:[e.jsx(qa,{className:"h-3.5 w-3.5 mr-1"})," Previous"]}),gc(d[g+1].id),children:["Next ",e.jsx(Di,{className:"h-3.5 w-3.5 ml-1"})]}):m===100&&e.jsx(Be,{className:"bg-green-500/15 text-green-600 border-green-500/30 text-sm px-3 py-1.5",children:"🎉 Course Complete!"})]})]})})]}):e.jsx(Ne,{children:e.jsx(Ie,{className:"flex items-center justify-center py-16 text-muted-foreground",children:"Select a module to begin"})})})]})]})}):e.jsx(Vs,{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($,{variant:"outline",className:"mt-4",onClick:()=>t("/levelup-u"),children:[e.jsx(qa,{className:"h-4 w-4 mr-2"})," Back"]})]})})}function Sur({headline:s,subtext:t,primaryColor:n,accentColor:r,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, ${r} 0%, ${n} 50%, ${r}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(Br.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(Br.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(Br.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(Br.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(Br.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:r},children:["Get In Touch",e.jsx(ei,{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(Br.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 $2({children:s,className:t="",delay:n=0,direction:r="up"}){const a=j.useRef(null),i=v9s(a,{once:!0,margin:"-80px"}),l={hidden:{opacity:0,y:r==="up"?40:0,x:r==="left"?-40:r==="right"?40:0},visible:{opacity:1,y:0,x:0}};return e.jsx(Br.div,{ref:a,initial:"hidden",animate:i?"visible":"hidden",variants:l,transition:{duration:.7,delay:n,ease:[.25,.46,.45,.94]},className:t,children:s})}function Cur({benefits:s,accentColor:t,primaryColor:n}){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($2,{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:n},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:n}})]})}),e.jsx("div",{className:"grid md:grid-cols-2 lg:grid-cols-3 gap-6 md:gap-8",children:s.map((r,a)=>e.jsx($2,{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, ${n}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:`${n}12`},children:r.icon}),e.jsx("h3",{className:"text-xl font-bold mb-3 tracking-tight",style:{color:t},children:r.title}),e.jsx("p",{className:"text-gray-500 leading-relaxed text-[15px]",children:r.description})]})]})},a))})]})})}function Aur({images:s,primaryColor:t,accentColor:n}){const[r,a]=j.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($2,{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(Zn,{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:n},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($2,{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))})]})}),r!==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(gr,{className:"h-8 w-8"})}),e.jsx("img",{src:s[r],alt:"Gallery",className:"max-w-full max-h-[85vh] object-contain rounded-lg",onClick:i=>i.stopPropagation()})]})]})}function Eur({testimonials:s,primaryColor:t,accentColor:n}){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($2,{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:n},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((r,a)=>{var i;return e.jsx($2,{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(x2,{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:['"',r.quote,'"']}),e.jsxs("div",{className:"flex items-center gap-4",children:[r.photo_url?e.jsx("img",{src:r.photo_url,alt:r.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}, ${n})`},children:((i=r.name)==null?void 0:i[0])||"?"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-semibold text-base",style:{color:n},children:r.name}),r.role&&e.jsx("p",{className:"text-sm text-gray-500",children:r.role})]})]})]})},a)})})]})})}function Tur({form:s,setForm:t,onSubmit:n,isPending:r,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($2,{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($2,{delay:.2,children:e.jsxs("form",{onSubmit:l=>{l.preventDefault(),n()},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(ee,{className:"text-gray-700 text-sm font-medium",children:"First Name *"}),e.jsx(pe,{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(ee,{className:"text-gray-700 text-sm font-medium",children:"Last Name"}),e.jsx(pe,{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(ee,{className:"text-gray-700 text-sm font-medium",children:"Email *"}),e.jsx(pe,{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(ee,{className:"text-gray-700 text-sm font-medium",children:"Phone"}),e.jsx(pe,{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(ee,{className:"text-gray-700 text-sm font-medium",children:"Current Brokerage"}),e.jsx(pe,{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(ee,{className:"text-gray-700 text-sm font-medium",children:"License #"}),e.jsx(pe,{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(ee,{className:"text-gray-700 text-sm font-medium",children:"Years Experience"}),e.jsx(pe,{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(ee,{className:"text-gray-700 text-sm font-medium",children:"Annual Production"}),e.jsx(pe,{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(ee,{className:"text-gray-700 text-sm font-medium",children:"Why are you interested?"}),e.jsx(Rs,{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($,{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:r,children:r?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(ei,{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(Mf,{className:"h-3.5 w-3.5"}),e.jsx("span",{children:"Your information is confidential and will not be shared."})]})]})})]})]})}function Mur({form:s,setForm:t,onSubmit:n,isPending:r,primaryColor:a,accentColor:i,showConfidentialBadges:l=!0}){const[o,c]=j.useState(1),[d,u]=j.useState(""),h=3,m=!!s.first_name&&!!s.email,f=g=>{u(g),t(x=>({...x,why_interested:g})),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($2,{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(pc,{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($2,{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(g=>e.jsx("div",{className:"h-1 flex-1 rounded-full transition-colors duration-500",style:{backgroundColor:g<=o?a:"#e5e7eb"}},g)),e.jsxs("span",{className:"text-xs text-gray-400 ml-2",children:[o,"/",h]})]}),e.jsxs(cK,{mode:"wait",children:[o===1&&e.jsxs(Br.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(g=>e.jsxs("button",{type:"button",onClick:()=>f(g.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:g.icon}),e.jsx("span",{className:"font-medium text-gray-700 group-hover:text-gray-900 flex-1",children:g.label}),e.jsx(ei,{className:"h-4 w-4 text-gray-300 group-hover:text-gray-500 group-hover:translate-x-1 transition-all"})]},g.val))]},"step1"),o===2&&e.jsxs(Br.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(ee,{className:"text-gray-700 text-sm font-medium",children:"First Name *"}),e.jsx(pe,{required:!0,value:s.first_name,onChange:g=>t(x=>({...x,first_name:g.target.value})),className:"h-11",placeholder:"John"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{className:"text-gray-700 text-sm font-medium",children:"Last Name"}),e.jsx(pe,{value:s.last_name,onChange:g=>t(x=>({...x,last_name:g.target.value})),className:"h-11",placeholder:"Smith"})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{className:"text-gray-700 text-sm font-medium",children:"Email *"}),e.jsx(pe,{type:"email",required:!0,value:s.email,onChange:g=>t(x=>({...x,email:g.target.value})),className:"h-11",placeholder:"john@email.com"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{className:"text-gray-700 text-sm font-medium",children:"Phone (preferred)"}),e.jsx(pe,{value:s.phone,onChange:g=>t(x=>({...x,phone:g.target.value})),className:"h-11",placeholder:"(555) 123-4567"})]}),e.jsxs("div",{className:"flex gap-2 pt-2",children:[e.jsxs($,{type:"button",variant:"ghost",onClick:()=>c(1),className:"h-11",children:[e.jsx(qa,{className:"h-4 w-4 mr-1"})," Back"]}),e.jsxs($,{type:"button",disabled:!m,onClick:()=>c(3),className:"flex-1 h-11 text-white font-semibold",style:{background:`linear-gradient(135deg, ${a}, ${i})`},children:["Continue ",e.jsx(ei,{className:"h-4 w-4 ml-1"})]})]})]},"step2"),o===3&&e.jsxs(Br.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(ee,{className:"text-gray-700 text-sm font-medium",children:"Current Brokerage"}),e.jsx(pe,{value:s.current_brokerage,onChange:g=>t(x=>({...x,current_brokerage:g.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(ee,{className:"text-gray-700 text-sm font-medium",children:"Years Experience"}),e.jsx(pe,{type:"number",min:"0",value:s.experience_years,onChange:g=>t(x=>({...x,experience_years:g.target.value})),className:"h-11"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{className:"text-gray-700 text-sm font-medium",children:"Annual Production"}),e.jsx(pe,{value:s.annual_production,onChange:g=>t(x=>({...x,annual_production:g.target.value})),className:"h-11",placeholder:"e.g. $5M"})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{className:"text-gray-700 text-sm font-medium",children:"Anything else?"}),e.jsx(Rs,{value:s.why_interested,onChange:g=>t(x=>({...x,why_interested:g.target.value})),rows:2,className:"resize-none",placeholder:"Optional message..."})]}),e.jsxs("div",{className:"flex gap-2 pt-2",children:[e.jsxs($,{type:"button",variant:"ghost",onClick:()=>c(2),className:"h-11",children:[e.jsx(qa,{className:"h-4 w-4 mr-1"})," Back"]}),e.jsx($,{type:"button",onClick:n,disabled:r,className:"flex-1 h-12 text-white font-semibold rounded-xl",style:{background:`linear-gradient(135deg, ${a}, ${i})`},children:r?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(la,{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(Mf,{className:"h-3 w-3"})," Confidential"]}),e.jsxs("div",{className:"flex items-center gap-1 justify-center",children:[e.jsx(eo,{className:"h-3 w-3"})," Text first"]}),e.jsxs("div",{className:"flex items-center gap-1 justify-center",children:[e.jsx(Da,{className:"h-3 w-3"})," No spam"]})]})]})})]})]})}function Pur({config:s,primaryColor:t,accentColor:n,brokerageId:r,brokerageName:a}){const{toast:i}=Bi(),[l,o]=j.useState("250000"),[c,d]=j.useState("12"),[u,h]=j.useState("70"),[m,f]=j.useState("150"),[g,x]=j.useState(""),[y,v]=j.useState(!1),[b,w]=j.useState(!1),S=s.commission_split_pct??80,C=s.cap_amount??16e3,E=s.post_cap_split_pct??100,I=s.monthly_fee??99,P=s.transaction_fee??0,R=j.useMemo(()=>{const U=parseFloat(l)||0,W=Math.max(0,parseInt(c,10)||0),V=parseFloat(u)||0,G=parseFloat(m)||0,Y=U*(V/100)-G*12-P*W,X=1-S/100,ae=X>0?C/X:U,ie=Math.min(U,ae),ne=Math.max(0,U-ae),te=ie*X+ne*(1-E/100),J=U-te-I*12-P*W,ce=J-Y;return{currentNet:Y,newNet:J,diff:ce}},[l,c,u,m,S,C,E,I,P]),D=U=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(U),O=async U=>{if(U.preventDefault(),!!g){w(!0);try{const{error:W}=await q.from("recruit_lead_magnet_downloads").insert({brokerage_id:r,email:g,source:"calculator"});if(W)throw W;const{error:V}=await q.functions.invoke("send-calculator-breakdown",{body:{brokerage_id:r,brokerage_name:a,email:g,inputs:{gci:parseFloat(l)||0,transactions:parseInt(c,10)||0,current_split_pct:parseFloat(u)||0,current_monthly_fee:parseFloat(m)||0},plan:{commission_split_pct:S,cap_amount:C,post_cap_split_pct:E,monthly_fee:I,transaction_fee:P},result:R,primary_color:t,accent_color:n}});V&&console.error("Breakdown email failed:",V),v(!0),i({title:"Sent!",description:"Check your email for the full breakdown."})}catch(W){i({title:"Error",description:W.message,variant:"destructive"})}finally{w(!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($2,{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:n},children:[e.jsx(pc,{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:n},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($2,{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(c2,{className:"h-5 w-5",style:{color:t}}),e.jsx("h3",{className:"font-semibold",style:{color:n},children:"Your Numbers"})]}),e.jsxs("div",{className:"space-y-5",children:[e.jsxs("div",{children:[e.jsx(ee,{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(pe,{type:"number",value:l,onChange:U=>o(U.target.value),className:"pl-7 h-11 text-base",placeholder:"250,000"})]})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-gray-600 text-sm",children:"Transactions per Year"}),e.jsx(pe,{type:"number",min:"0",value:c,onChange:U=>d(U.target.value),className:"mt-1.5 h-11 text-base",placeholder:"12"})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-gray-600 text-sm",children:"Your Current Commission Split (%)"}),e.jsx(pe,{type:"number",value:u,onChange:U=>h(U.target.value),className:"mt-1.5 h-11 text-base",placeholder:"70"})]}),e.jsxs("div",{children:[e.jsx(ee,{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(pe,{type:"number",value:m,onChange:U=>f(U.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, ${n}, ${t})`},children:[e.jsxs("div",{className:"flex items-center gap-2 mb-6",children:[e.jsx(Yl,{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:D(R.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:D(R.newNet)})]})]}),e.jsxs(Br.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:R.diff>=0?"You could earn":"Difference"}),e.jsxs("p",{className:"text-4xl font-bold mb-1",children:[R.diff>=0?"+":"",D(R.diff)]}),e.jsx("p",{className:"text-white/70 text-xs",children:R.diff>=0?"more per year":"per year"})]},R.diff),s.show_email_capture&&!y&&e.jsxs("form",{onSubmit:O,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(pe,{type:"email",required:!0,value:g,onChange:U=>x(U.target.value),placeholder:"you@email.com",className:"bg-white/95 border-0 text-gray-900 h-10 text-sm"}),e.jsx($,{type:"submit",disabled:b,className:"h-10 bg-white text-gray-900 hover:bg-white/90 text-sm font-semibold",children:"Send"})]})]}),y&&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(la,{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 Iur({config:s,primaryColor:t,accentColor:n,brokerageId:r}){const{toast:a}=Bi(),[i,l]=j.useState(""),[o,c]=j.useState(""),[d,u]=j.useState(!1),[h,m]=j.useState(!1),f=async g=>{g.preventDefault(),m(!0);try{const{error:x}=await q.from("recruit_lead_magnet_downloads").insert({brokerage_id:r,email:i,first_name:o||null,source:"lead_magnet",user_agent:navigator.userAgent,referrer:document.referrer||null});if(x)throw x;u(!0),s.pdf_url&&window.open(s.pdf_url,"_blank","noopener,noreferrer")}catch(x){a({title:"Error",description:x.message,variant:"destructive"})}finally{m(!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($2,{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, ${n}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}, ${n})`},children:e.jsx(u2,{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:n},children:[e.jsx(pc,{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:n},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(la,{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:f,className:"space-y-3",children:[e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-3",children:[e.jsx(pe,{value:o,onChange:g=>c(g.target.value),placeholder:"First name (optional)",className:"h-11"}),e.jsx(pe,{type:"email",required:!0,value:i,onChange:g=>l(g.target.value),placeholder:"your@email.com",className:"h-11"})]}),e.jsxs($,{type:"submit",disabled:h,className:"w-full sm:w-auto h-12 px-6 text-white font-semibold",style:{background:`linear-gradient(135deg, ${t}, ${n})`},children:[e.jsx(u2,{className:"h-4 w-4 mr-2"}),h?"Sending...":s.button_text||"Email Me the PDF"]})]})]})]})})})})})}function Lur(){const{slug:s}=Wi(),{toast:t}=Bi(),[n,r]=j.useState(!1),[a,i]=j.useState({first_name:"",last_name:"",email:"",phone:"",current_brokerage:"",experience_years:"",annual_production:"",license_number:"",why_interested:""});j.useEffect(()=>{document.body.classList.add("recruit-landing-page");const R=()=>{['[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(W=>document.querySelectorAll(W).forEach(V=>V.style.display="none"))};R();const D=[setTimeout(R,500),setTimeout(R,1500),setTimeout(R,3e3)],O=new MutationObserver(R);return O.observe(document.body,{childList:!0,subtree:!0}),()=>{document.body.classList.remove("recruit-landing-page"),D.forEach(clearTimeout),O.disconnect()}},[]);const{data:l,isLoading:o,error:c}=tt({queryKey:["recruit-form-brokerage",s],queryFn:async()=>{const{data:R,error:D}=await q.from("brokerages").select("id, name, recruit_form_enabled").eq("recruit_form_slug",s).single();if(D)throw D;return R},enabled:!!s}),{data:d}=tt({queryKey:["recruit-landing-public",l==null?void 0:l.id],queryFn:async()=>{const{data:R,error:D}=await q.from("recruit_landing_page_settings").select("*").eq("brokerage_id",l.id).single();if(D&&D.code!=="PGRST116")throw D;return R},enabled:!!(l!=null&&l.id)}),u=ft({mutationFn:async()=>{const R={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:D}=await q.from("recruit_interest_submissions").insert(R);if(D)throw D;q.functions.invoke("recruit-lead-notify",{body:{lead:R,brokerage_id:l.id}}).catch(O=>console.error("Lead notification error:",O))},onSuccess:()=>r(!0),onError:R=>t({title:"Error",description:R.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(ji,{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 h=d,m=(h==null?void 0:h.primary_color)||"#406E71",f=(h==null?void 0:h.accent_color)||"#2a4c64",g=(h==null?void 0:h.benefits)||[],x=(h==null?void 0:h.testimonials)||[],y=(h==null?void 0:h.gallery_images)||[],v=(h==null?void 0:h.hero_headline)||`Join ${l.name}`,b=(h==null?void 0:h.hero_subtext)||"Take your real estate career to the next level with a brokerage that invests in your growth.",w=(h==null?void 0:h.calculator_enabled)===!0,S=(h==null?void 0:h.calculator_config)||{},C=(h==null?void 0:h.lead_magnet_enabled)===!0,E=(h==null?void 0:h.lead_magnet_config)||{},I=(h==null?void 0:h.form_style)||"classic",P=(h==null?void 0:h.confidential_messaging)!==!1;return n?e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-white",children:e.jsxs(Br.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, ${m}, ${f})`},children:e.jsx(la,{className:"h-10 w-10 text-white"})}),e.jsx("h2",{className:"text-3xl font-bold mb-3 tracking-tight",style:{color:f},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:f},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:m}})]})}):e.jsxs("div",{className:"min-h-screen bg-white",style:{"--recruit-primary":m,"--recruit-accent":f},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:[(h==null?void 0:h.logo_url)&&e.jsx("img",{src:h.logo_url,alt:l.name,className:"h-8 w-auto"}),e.jsx("span",{className:"font-semibold text-sm tracking-tight",style:{color:f},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, ${m}, ${f})`},children:["Apply Now ",e.jsx(ei,{className:"h-3.5 w-3.5"})]})]})}),e.jsx(Sur,{headline:v,subtext:b,primaryColor:m,accentColor:f,heroImageUrl:h==null?void 0:h.hero_image_url,logoUrl:h==null?void 0:h.logo_url,brokerageName:l.name}),e.jsx(Cur,{benefits:g,accentColor:f,primaryColor:m}),e.jsx(Aur,{images:y,primaryColor:m,accentColor:f}),e.jsx(Eur,{testimonials:x,primaryColor:m,accentColor:f}),w&&e.jsx(Pur,{config:S,primaryColor:m,accentColor:f,brokerageId:l.id,brokerageName:l.name}),C&&e.jsx(Iur,{config:E,primaryColor:m,accentColor:f,brokerageId:l.id}),I==="multi_step"?e.jsx(Mur,{form:a,setForm:i,onSubmit:()=>u.mutate(),isPending:u.isPending,primaryColor:m,accentColor:f,showConfidentialBadges:P}):e.jsx(Tur,{form:a,setForm:i,onSubmit:()=>u.mutate(),isPending:u.isPending,primaryColor:m,accentColor:f}),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 Rur(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 Dur(){var m,f,g,x;const{shareToken:s}=Wi(),t=j.useRef(!1),{data:n,isLoading:r,error:a}=tt({queryKey:["public-recruit-video",s],queryFn:async()=>{var C;if(!s)throw new Error("No token");const{data:y,error:v}=await q.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(v)throw v;const{data:b}=await q.from("profiles").select("name, avatar_url, title, recruit_cta_url").eq("id",(C=y.video)==null?void 0:C.owner_user_id).single(),{data:w}=await q.from("brokerages").select("name").eq("id",y.brokerage_id).single(),{data:S}=await q.from("recruit_landing_page_settings").select("logo_url, primary_color, accent_color, hero_headline").eq("brokerage_id",y.brokerage_id).maybeSingle();return{rv:y,profile:b,brokerage:w,settings:S}},enabled:!!s});if(j.useEffect(()=>{var y;!((y=n==null?void 0:n.rv)!=null&&y.id)||t.current||(t.current=!0,q.rpc("log_recruit_video_view",{p_recruit_video_id:n.rv.id,p_user_agent:navigator.userAgent,p_referrer:document.referrer||null}).then(()=>{}))},[(m=n==null?void 0:n.rv)==null?void 0:m.id]),r)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||!n)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}=n,d=(c==null?void 0:c.primary_color)||"#3b82f6",u=((f=i.prospect)==null?void 0:f.first_name)||"there",h=(g=i.video)!=null&&g.playback_url?Rur(i.video.playback_url):null;return e.jsxs(e.Fragment,{children:[e.jsx(Ml,{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 ",u,", ",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})]}),h&&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:h,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:((x=l==null?void 0:l.name)==null?void 0:x.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($,{size:"lg",asChild:!0,className:"text-white shadow-lg hover:shadow-xl transition-shadow px-8",style:{backgroundColor:d},onClick:()=>{q.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(Ta,{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 Fur="relzejiswnotikjgvjhz",GEt=`https://${Fur}.supabase.co/functions/v1/recruit-unsubscribe`;function Our(){const[s]=gc(),t=s.get("token")||"",[n,r]=j.useState(!0),[a,i]=j.useState(!1),[l,o]=j.useState(!1),[c,d]=j.useState(""),[u,h]=j.useState({});j.useEffect(()=>{document.body.classList.add("recruit-unsubscribe-page");const f=()=>{['[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(v=>document.querySelectorAll(v).forEach(b=>b.style.display="none"))};f();const g=[setTimeout(f,500),setTimeout(f,1500),setTimeout(f,3e3)],x=new MutationObserver(f);return x.observe(document.body,{childList:!0,subtree:!0}),()=>{document.body.classList.remove("recruit-unsubscribe-page"),g.forEach(clearTimeout),x.disconnect()}},[]),j.useEffect(()=>{if(!t){h({error:"Missing unsubscribe token in link."}),r(!1);return}fetch(`${GEt}?token=${encodeURIComponent(t)}`).then(async f=>{const g=await f.json();if(!f.ok)throw new Error(g.error||"Lookup failed");h(g),g.already_unsubscribed&&o(!0)}).catch(f=>h({error:f.message||"Could not load status"})).finally(()=>r(!1))},[t]);const m=async()=>{i(!0);try{const f=await fetch(GEt,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:t,reason:c.trim()||null})}),g=await f.json();if(!f.ok)throw new Error(g.error||"Failed");o(!0)}catch(f){h({...u,error:f.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:n?e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 gap-3 text-slate-500",children:[e.jsx(kt,{className:"h-8 w-8 animate-spin"}),e.jsx("p",{className:"text-sm",children:"Loading…"})]}):u.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(ll,{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:u.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(qr,{className:"h-7 w-7 text-emerald-500"})}),e.jsxs("h1",{className:"text-xl font-semibold text-slate-800",children:["You're unsubscribed",u.first_name?`, ${u.first_name}`:""]}),e.jsxs("p",{className:"text-sm text-slate-500",children:["You won't receive any more recruiting emails from ",u.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(bm,{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(bm,{className:"h-7 w-7 text-slate-500"})}),e.jsxs("h1",{className:"text-xl font-semibold text-slate-800",children:["Unsubscribe",u.first_name?`, ${u.first_name}`:"","?"]}),e.jsxs("p",{className:"text-sm text-slate-500",children:["You'll be removed from ",u.brokerage_name||"this brokerage","'s recruiting emails immediately. Everything stays confidential."]}),u.email&&e.jsx("p",{className:"text-xs text-slate-400",children:u.email})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"reason",className:"text-xs text-slate-500",children:"Optional — what's the main reason? (helps us improve)"}),e.jsx(Rs,{id:"reason",value:c,onChange:f=>d(f.target.value),placeholder:"e.g. Not currently looking, too many emails, already moved…",rows:3,className:"resize-none"})]}),e.jsx($,{onClick:m,disabled:a,className:"w-full h-11",variant:"default",children:a?e.jsxs(e.Fragment,{children:[e.jsx(kt,{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."})]})})})}const zur="relzejiswnotikjgvjhz",WEt=`https://${zur}.supabase.co/functions/v1/event-invite-unsubscribe`;function Bur(){const[s]=gc(),t=s.get("token")||"",[n,r]=j.useState(!0),[a,i]=j.useState(!1),[l,o]=j.useState(!1),[c,d]=j.useState({});j.useEffect(()=>(document.body.classList.add("event-invite-unsubscribe-page"),()=>{document.body.classList.remove("event-invite-unsubscribe-page")}),[]),j.useEffect(()=>{if(!t){d({error:"Missing unsubscribe token in link."}),r(!1);return}fetch(`${WEt}?token=${encodeURIComponent(t)}`).then(async h=>{const m=await h.json();if(!h.ok)throw new Error(m.error||"Lookup failed");d(m),m.already_unsubscribed&&o(!0)}).catch(h=>d({error:h.message||"Could not load status"})).finally(()=>r(!1))},[t]);const u=async()=>{i(!0);try{const h=await fetch(WEt,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:t})}),m=await h.json();if(!h.ok)throw new Error(m.error||"Failed");o(!0)}catch(h){d({...c,error:h.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:n?e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 gap-3 text-slate-500",children:[e.jsx(kt,{className:"h-8 w-8 animate-spin"}),e.jsx("p",{className:"text-sm",children:"Loading…"})]}):c.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(ll,{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:c.error})]}):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(qr,{className:"h-7 w-7 text-emerald-500"})}),e.jsxs("h1",{className:"text-xl font-semibold text-slate-800",children:["You're unsubscribed",c.first_name?`, ${c.first_name}`:""]}),e.jsx("p",{className:"text-sm text-slate-500",children:"You won't receive event invite emails from LevelUp anymore."}),e.jsxs("div",{className:"mt-4 rounded-xl bg-slate-50 border border-slate-200 p-4 text-left",children:[e.jsx("p",{className:"text-sm font-medium text-slate-800 mb-1",children:"You'll still get:"}),e.jsxs("ul",{className:"text-sm text-slate-600 space-y-1 list-disc list-inside",children:[e.jsx("li",{children:"The Monday weekly digest"}),e.jsx("li",{children:"Account & billing notifications"}),e.jsx("li",{children:"Anything you directly requested"})]})]}),e.jsxs("div",{className:"flex items-center justify-center gap-2 text-xs text-slate-400 pt-2",children:[e.jsx(bm,{className:"h-3.5 w-3.5"}),"Preference saved · You can turn this back on anytime in your Profile."]})]}):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(bJ,{className:"h-7 w-7 text-slate-500"})}),e.jsxs("h1",{className:"text-xl font-semibold text-slate-800",children:["Unsubscribe from event invites",c.first_name?`, ${c.first_name}`:"","?"]}),e.jsxs("p",{className:"text-sm text-slate-500",children:["You'll stop receiving event invite emails from LevelUp. Your ",e.jsx("span",{className:"font-medium text-slate-700",children:"Monday weekly digest"})," will keep coming."]}),c.email&&e.jsx("p",{className:"text-xs text-slate-400",children:c.email})]}),e.jsx($,{onClick:u,disabled:a,className:"w-full h-11",variant:"default",children:a?e.jsxs(e.Fragment,{children:[e.jsx(kt,{className:"h-4 w-4 mr-2 animate-spin"}),"Unsubscribing…"]}):"Unsubscribe from event invites only"}),e.jsx("p",{className:"text-[11px] text-slate-400 text-center",children:"No login required. You can re-enable event invites anytime in your Profile."})]})})})}function $ur(){var R,D,O;const s=Qn(),t=Vt(),{isAdmin:n}=vs(),[r,a]=j.useState(!1),[i,l]=j.useState(null),[o,c]=j.useState(null),{data:d,isLoading:u}=tt({queryKey:["my-social-accounts"],queryFn:async()=>{const{data:{user:U},error:W}=await q.auth.getUser();if(W)throw W;if(!U)return[];const{data:V,error:G}=await q.from("social_accounts").select("*").eq("user_id",U.id).order("created_at",{ascending:!1});if(G)throw G;return V}}),{data:h}=tt({queryKey:["google-business-status"],queryFn:async()=>{const{data:U,error:W}=await q.functions.invoke("google-business-oauth",{body:{action:"get_status"}});if(W)throw W;return U}}),m=ft({mutationFn:async U=>{const{data:W,error:V}=await q.functions.invoke("google-business-oauth",{body:{action:"set_primary_location",locationId:U}});if(V)throw V;return W},onSuccess:()=>{re.success("Business updated"),t.invalidateQueries({queryKey:["google-business-status"]}),t.invalidateQueries({queryKey:["my-social-accounts"]})},onError:()=>re.error("Could not update your business selection")}),f=ft({mutationFn:async()=>{const{error:U}=await q.functions.invoke("google-business-oauth",{body:{action:"disconnect"}});if(U)throw U},onSuccess:()=>{t.invalidateQueries({queryKey:["google-business-status"]}),t.invalidateQueries({queryKey:["my-social-accounts"]}),t.invalidateQueries({queryKey:["social-accounts-for-post"]}),re.success("Google Business disconnected")},onError:()=>re.error("Failed to disconnect Google Business")}),g=ft({mutationFn:async U=>{const{data:{user:W},error:V}=await q.auth.getUser();if(V)throw V;if(!W)throw new Error("Not authenticated");const{error:G}=await q.from("social_accounts").delete().eq("id",U).eq("user_id",W.id);if(G)throw G},onSuccess:()=>{t.invalidateQueries({queryKey:["my-social-accounts"]}),t.invalidateQueries({queryKey:["social-accounts-for-post"]}),re.success("Account disconnected successfully")},onError:()=>{re.error("Failed to disconnect account")}}),x=async U=>{a(!0),sessionStorage.setItem("social-connect-return-to",window.location.pathname);try{const{data:W,error:V}=await q.functions.invoke("meta-oauth",{body:{action:"get_auth_url",callbackPath:"/social-connections/callback",authMode:U}});if(V)throw V;if(W!=null&&W.authUrl)window.location.href=W.authUrl;else throw new Error("Failed to get authorization URL")}catch(W){console.error("Meta OAuth error:",W),re.error("Failed to start connection. Please try again."),a(!1)}},y=async()=>{a(!0);try{const{data:U,error:W}=await q.functions.invoke("linkedin-oauth",{body:{action:"get_auth_url",callbackPath:"/social-connections/linkedin-callback"}});if(W)throw W;if(U!=null&&U.authUrl)window.location.href=U.authUrl;else throw new Error("Failed to get LinkedIn authorization URL")}catch(U){console.error("LinkedIn OAuth error:",U),re.error("Failed to start LinkedIn connection. Please try again."),a(!1)}},v=async()=>{a(!0);try{const{data:U,error:W}=await q.functions.invoke("google-business-oauth",{body:{action:"get_auth_url",returnPath:"/social-connections"}});if(W)throw W;if(U!=null&&U.authUrl)window.location.href=U.authUrl;else throw new Error("Failed to get Google authorization URL")}catch(U){console.error("Google OAuth error:",U),re.error("Failed to start Google connection. Please try again."),a(!1)}},b=(d==null?void 0:d.filter(U=>U.platform==="facebook"))||[],w=(d==null?void 0:d.filter(U=>U.platform==="instagram"))||[],S=(d==null?void 0:d.filter(U=>U.platform==="linkedin"))||[];d!=null&&d.filter(U=>U.platform==="google_business");const C=(h==null?void 0:h.connected)===!0,E=((R=h==null?void 0:h.locations)==null?void 0:R.find(U=>U.is_primary))??((D=h==null?void 0:h.locations)==null?void 0:D[0]),I=((d==null?void 0:d.length)||0)>0,P=async(U,W)=>{l(U),c(null);try{const{data:V,error:G}=await q.functions.invoke("meta-api-test",{body:{testType:"all",accountId:U}});if(G)throw G;c(V.results||[]),re.success(V.summary||"API tests completed")}catch(V){console.error("Meta API test error:",V),re.error("Failed to run API tests")}finally{l(null)}};return e.jsx(Vs,{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(Be,{variant:"secondary",className:"bg-white/20 text-white border-0 backdrop-blur-sm",children:[e.jsx(Nn,{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($,{variant:"ghost",onClick:()=>s("/social-studio"),className:"gap-2",children:[e.jsx(qa,{className:"h-4 w-4"}),"Back to Social Studio"]}),I&&e.jsx(Ne,{className:"border-green-200 bg-green-50 dark:bg-green-950/20 dark:border-green-900",children:e.jsxs(Ie,{className:"flex items-center gap-4 p-4",children:[e.jsx("div",{className:"rounded-full bg-green-500 p-2",children:e.jsx(Nc,{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(Ne,{children:[e.jsx(Ct,{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(Qp,{className:"h-6 w-6 text-blue-600"})}),e.jsxs("div",{children:[e.jsx(At,{className:"text-lg",children:"Facebook"}),e.jsx(Gn,{children:"Connect your Facebook Page"})]})]})}),e.jsxs(Ie,{className:"space-y-4",children:[u?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(ro,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):b.length>0?e.jsx("div",{className:"space-y-3",children:b.map(U=>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(Oa,{className:"h-10 w-10",children:[e.jsx(Li,{src:U.profile_picture_url||""}),e.jsx(za,{children:e.jsx(Qp,{className:"h-5 w-5"})})]}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:U.page_name||U.platform_username||"Facebook Page"}),e.jsx(Be,{variant:U.is_active?"default":"secondary",className:"text-xs",children:U.is_active?"Connected":"Inactive"})]})]}),e.jsxs(kc,{children:[e.jsx(jx,{asChild:!0,children:e.jsx($,{variant:"ghost",size:"icon",className:"text-destructive hover:text-destructive",children:e.jsx(Wn,{className:"h-4 w-4"})})}),e.jsxs(cc,{children:[e.jsxs(dc,{children:[e.jsx(hc,{children:"Disconnect Facebook?"}),e.jsx(mc,{children:"This will remove the connection. You'll need to reconnect to post content."})]}),e.jsxs(uc,{children:[e.jsx(fc,{children:"Cancel"}),e.jsx(tc,{onClick:()=>g.mutate(U.id),className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Disconnect"})]})]})]})]},U.id))}):e.jsx("p",{className:"text-sm text-muted-foreground py-4 text-center",children:"No Facebook pages connected yet"}),e.jsxs($,{onClick:()=>x("facebook"),disabled:r,className:"w-full gap-2",variant:"outline",children:[r?e.jsx(ro,{className:"h-4 w-4 animate-spin"}):e.jsx(dn,{className:"h-4 w-4"}),b.length>0?"Connect Another Page":"Connect Facebook Page"]})]})]}),e.jsxs(Ne,{children:[e.jsx(Ct,{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(Tf,{className:"h-6 w-6 text-pink-600"})}),e.jsxs("div",{children:[e.jsx(At,{className:"text-lg",children:"Instagram"}),e.jsx(Gn,{children:"Connect your Instagram Business or Creator account"})]})]})}),e.jsxs(Ie,{className:"space-y-4",children:[u?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(ro,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):w.length>0?e.jsx("div",{className:"space-y-3",children:w.map(U=>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(Oa,{className:"h-10 w-10",children:[e.jsx(Li,{src:U.profile_picture_url||""}),e.jsx(za,{children:e.jsx(Tf,{className:"h-5 w-5"})})]}),e.jsxs("div",{children:[e.jsxs("p",{className:"font-medium",children:["@",U.platform_username||"Instagram Account"]}),e.jsx(Be,{variant:U.is_active?"default":"secondary",className:"text-xs",children:U.is_active?"Connected":"Inactive"})]})]}),e.jsxs(kc,{children:[e.jsx(jx,{asChild:!0,children:e.jsx($,{variant:"ghost",size:"icon",className:"text-destructive hover:text-destructive",children:e.jsx(Wn,{className:"h-4 w-4"})})}),e.jsxs(cc,{children:[e.jsxs(dc,{children:[e.jsx(hc,{children:"Disconnect Instagram?"}),e.jsx(mc,{children:"This will remove the connection. You'll need to reconnect to post content."})]}),e.jsxs(uc,{children:[e.jsx(fc,{children:"Cancel"}),e.jsx(tc,{onClick:()=>g.mutate(U.id),className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Disconnect"})]})]})]})]},U.id))}):e.jsx("p",{className:"text-sm text-muted-foreground py-4 text-center",children:"No Instagram accounts connected yet"}),e.jsxs($,{onClick:()=>x("instagram"),disabled:r,className:"w-full gap-2",variant:"outline",children:[r?e.jsx(ro,{className:"h-4 w-4 animate-spin"}):e.jsx(dn,{className:"h-4 w-4"}),w.length>0?"Reconnect Instagram":"Connect Instagram"]}),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(Ne,{children:[e.jsx(Ct,{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(hy,{className:"h-6 w-6 text-blue-700"})}),e.jsxs("div",{children:[e.jsx(At,{className:"text-lg",children:"LinkedIn"}),e.jsx(Gn,{children:"Connect your LinkedIn profile"})]})]})}),e.jsxs(Ie,{className:"space-y-4",children:[u?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(ro,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):S.length>0?e.jsx("div",{className:"space-y-3",children:S.map(U=>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(Oa,{className:"h-10 w-10",children:[e.jsx(Li,{src:U.profile_picture_url||""}),e.jsx(za,{children:e.jsx(hy,{className:"h-5 w-5"})})]}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:U.platform_username||"LinkedIn Account"}),e.jsx(Be,{variant:U.is_active?"default":"secondary",className:"text-xs",children:U.is_active?"Connected":"Inactive"})]})]}),e.jsxs(kc,{children:[e.jsx(jx,{asChild:!0,children:e.jsx($,{variant:"ghost",size:"icon",className:"text-destructive hover:text-destructive",children:e.jsx(Wn,{className:"h-4 w-4"})})}),e.jsxs(cc,{children:[e.jsxs(dc,{children:[e.jsx(hc,{children:"Disconnect LinkedIn?"}),e.jsx(mc,{children:"This will remove the connection. You'll need to reconnect to post content."})]}),e.jsxs(uc,{children:[e.jsx(fc,{children:"Cancel"}),e.jsx(tc,{onClick:()=>g.mutate(U.id),className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Disconnect"})]})]})]})]},U.id))}):e.jsx("p",{className:"text-sm text-muted-foreground py-4 text-center",children:"No LinkedIn account connected yet"}),e.jsxs($,{onClick:y,disabled:r,className:"w-full gap-2",variant:S.length>0?"outline":"default",children:[r?e.jsx(ro,{className:"h-4 w-4 animate-spin"}):e.jsx(dn,{className:"h-4 w-4"}),S.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(Ne,{className:"relative overflow-hidden",children:[e.jsx(Ct,{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(ci,{className:"h-6 w-6 text-red-600"})}),e.jsxs("div",{children:[e.jsx(At,{className:"text-lg",children:"Google Business"}),e.jsx(Gn,{children:"Connect your Google Business Profile"})]})]})}),e.jsxs(Ie,{className:"space-y-4",children:[(h==null?void 0:h.needsReconnect)&&C&&e.jsx("div",{className:"rounded-lg border border-amber-300 bg-amber-50 p-3 text-sm text-amber-900 dark:border-amber-900 dark:bg-amber-950/30 dark:text-amber-200",children:"We upgraded our Google connection. Please reconnect once so posting and reviews keep working."}),u?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(ro,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):C?e.jsx("div",{className:"space-y-3",children: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.jsx(Oa,{className:"h-10 w-10",children:e.jsx(za,{children:e.jsx(ci,{className:"h-5 w-5"})})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:(E==null?void 0:E.location_name)||(h==null?void 0:h.email)||"Google Business"}),e.jsx(Be,{variant:"default",className:"text-xs",children:"Connected"})]})]}),e.jsxs(kc,{children:[e.jsx(jx,{asChild:!0,children:e.jsx($,{variant:"ghost",size:"icon",className:"text-destructive hover:text-destructive",children:e.jsx(Wn,{className:"h-4 w-4"})})}),e.jsxs(cc,{children:[e.jsxs(dc,{children:[e.jsx(hc,{children:"Disconnect Google Business?"}),e.jsx(mc,{children:"This will remove the connection. You'll need to reconnect to post content."})]}),e.jsxs(uc,{children:[e.jsx(fc,{children:"Cancel"}),e.jsx(tc,{onClick:()=>f.mutate(),className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Disconnect"})]})]})]})]})}):e.jsx("p",{className:"text-sm text-muted-foreground py-4 text-center",children:"No Google Business account connected yet"}),(((O=h==null?void 0:h.locations)==null?void 0:O.length)??0)>1&&e.jsxs("div",{className:"space-y-2 rounded-lg border p-3",children:[e.jsx("p",{className:"text-sm font-medium",children:"Which business should we use?"}),h.locations.map(U=>e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("span",{className:"text-sm truncate",children:U.location_name||U.location_id}),U.is_primary?e.jsx(Be,{variant:"default",className:"text-xs shrink-0",children:"Active"}):e.jsx($,{size:"sm",variant:"outline",className:"shrink-0",disabled:m.isPending,onClick:()=>m.mutate(U.location_id),children:"Use this"})]},U.id))]}),e.jsxs($,{onClick:v,disabled:r,className:"w-full gap-2",variant:C&&!(h!=null&&h.needsReconnect)?"outline":"default",children:[r?e.jsx(ro,{className:"h-4 w-4 animate-spin"}):e.jsx(dn,{className:"h-4 w-4"}),C?"Reconnect Google Business":"Connect Google Business"]}),e.jsx("p",{className:"text-xs text-muted-foreground text-center",children:"Post updates and manage reviews from your Google Business Profile"})]})]})]}),n&&(b.length>0||w.length>0)&&e.jsxs(Ne,{className:"border-amber-200 bg-amber-50 dark:bg-amber-950/20 dark:border-amber-900",children:[e.jsx(Ct,{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(I4,{className:"h-6 w-6 text-amber-600"})}),e.jsxs("div",{children:[e.jsx(At,{className:"text-lg",children:"Meta API Testing (Admin Only)"}),e.jsx(Gn,{children:"Run API tests to trigger all required permissions for Meta App Review"})]})]})}),e.jsxs(Ie,{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:[b.map(U=>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(Qp,{className:"h-5 w-5 text-blue-600"}),e.jsx("span",{className:"font-medium",children:U.page_name||"Facebook Page"})]}),e.jsx($,{size:"sm",variant:"outline",onClick:()=>P(U.id),disabled:i===U.id,children:i===U.id?e.jsxs(e.Fragment,{children:[e.jsx(kt,{className:"h-4 w-4 mr-2 animate-spin"}),"Testing..."]}):e.jsxs(e.Fragment,{children:[e.jsx(I4,{className:"h-4 w-4 mr-2"}),"Run Tests"]})})]},`test-fb-${U.id}`)),w.map(U=>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(Tf,{className:"h-5 w-5 text-pink-600"}),e.jsxs("span",{className:"font-medium",children:["@",U.platform_username||"Instagram"]})]}),e.jsx($,{size:"sm",variant:"outline",onClick:()=>P(U.id),disabled:i===U.id,children:i===U.id?e.jsxs(e.Fragment,{children:[e.jsx(kt,{className:"h-4 w-4 mr-2 animate-spin"}),"Testing..."]}):e.jsxs(e.Fragment,{children:[e.jsx(I4,{className:"h-4 w-4 mr-2"}),"Run Tests"]})})]},`test-ig-${U.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((U,W)=>e.jsxs("div",{className:"flex items-start gap-2 text-sm",children:[U.status==="success"?e.jsx(qr,{className:"h-4 w-4 text-green-600 mt-0.5 shrink-0"}):U.status==="pending"?e.jsx(kt,{className:"h-4 w-4 text-amber-600 mt-0.5 shrink-0"}):e.jsx(ku,{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:U.test}),e.jsx("span",{className:"ml-2 text-muted-foreground",children:U.details})]})]},W))})]}),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(Ne,{children:[e.jsx(Ct,{children:e.jsx(At,{className:"text-lg",children:"How it works"})}),e.jsx(Ie,{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 Uur(){const[s]=gc(),t=Qn(),[n,r]=j.useState("loading"),a=j.useRef(!1),[i,l]=j.useState("Processing your connection..."),[o,c]=j.useState(null),[d,u]=j.useState(!1),h=(()=>{const m=sessionStorage.getItem("social-connect-return-to");return m&&m.startsWith("/")&&!m.startsWith("/admin")?m:"/social-connections"})();return j.useEffect(()=>{if(a.current)return;a.current=!0,(async()=>{var v;const f=s.get("code"),g=s.get("error"),x=s.get("error_description"),y=s.get("state");if(g){r("error"),l(x||"Authorization was denied"),re.error("Connection failed: "+(x||g));return}if(!f){r("error"),l("No authorization code received"),re.error("No authorization code received");return}try{const{data:b,error:w}=await q.functions.invoke("meta-oauth",{body:{action:"exchange_code",code:f,state:y,callbackPath:"/social-connections/callback"}});if(w)throw w;if(b!=null&&b.success)r("success"),l(`Successfully connected ${((v=b.accounts)==null?void 0:v.length)||0} account(s)!`),re.success("Social accounts connected successfully!");else throw c((b==null?void 0:b.code)||null),u(!!(b!=null&&b.existingConnectionPreserved)),new Error((b==null?void 0:b.error)||"Unknown error")}catch(b){console.error("OAuth callback error:",b),r("error");const w=b instanceof Error?b.message:"Failed to connect accounts";l(w),re.error("Failed to connect: "+(b instanceof Error?b.message:"Unknown error"))}})()},[s]),e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-background p-4",children:e.jsxs(Ne,{className:"w-full max-w-md",children:[e.jsxs(Ct,{className:"text-center",children:[n==="loading"&&e.jsx(kt,{className:"h-12 w-12 animate-spin mx-auto text-primary"}),n==="success"&&e.jsx(Nc,{className:"h-12 w-12 mx-auto text-green-500"}),n==="error"&&e.jsx(ku,{className:"h-12 w-12 mx-auto text-destructive"}),e.jsxs(At,{className:"mt-4",children:[n==="loading"&&"Connecting...",n==="success"&&"Connected!",n==="error"&&"Connection Failed"]}),e.jsx(Gn,{children:i})]}),e.jsxs(Ie,{className:"flex flex-col items-center gap-4",children:[n==="error"&&o==="no_managed_pages"&&e.jsxs("div",{className:"w-full rounded-lg border bg-muted/40 p-4 text-left text-sm space-y-3",children:[e.jsx("p",{className:"font-medium text-foreground",children:"How to connect your Facebook Page"}),e.jsxs("ol",{className:"list-decimal space-y-1.5 pl-5 text-muted-foreground",children:[e.jsxs("li",{children:["Click ",e.jsx("span",{className:"font-medium text-foreground",children:"Try Again"})," below."]}),e.jsxs("li",{children:["On the Meta screen that lists your Pages, choose your Page by name — or pick",e.jsx("span",{className:"font-medium text-foreground",children:" Opt in to all current and future Pages"}),"."]}),e.jsx("li",{children:"Leave every permission switched on, then finish."}),e.jsx("li",{children:"If your Page still doesn’t appear, try once more so LevelUp can recover the exact Page selected in Meta."})]}),d&&e.jsx("p",{className:"font-medium text-foreground",children:"Your existing Facebook Page connection is still active."})]}),n!=="loading"&&e.jsx($,{onClick:()=>t(h),children:n==="success"?"View Connected Accounts":"Try Again"})]})]})})}function qur(){const[s]=gc(),t=Qn();return j.useEffect(()=>{const n=new URLSearchParams,r=s.get("error");r?n.set("google_error",r):s.get("code")&&n.set("google_error","legacy_callback_retry");const a=n.toString();t(`/apps/reviews${a?`?${a}`:""}`,{replace:!0})},[s,t]),e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-background",children:e.jsx(kt,{className:"h-8 w-8 animate-spin text-primary"})})}function Vur(){const[s]=gc(),t=Qn(),[n,r]=j.useState("loading"),[a,i]=j.useState("Connecting your LinkedIn account...");return j.useEffect(()=>{(async()=>{var h;const o=s.get("code"),c=s.get("state"),d=s.get("error"),u=s.get("error_description");if(d){console.error("LinkedIn OAuth error:",d,u),r("error"),i(u||"Failed to connect LinkedIn account"),re.error(u||"Failed to connect LinkedIn");return}if(!o){r("error"),i("No authorization code received"),re.error("No authorization code received");return}try{const{data:m,error:f}=await q.functions.invoke("linkedin-oauth",{body:{action:"exchange_code",code:o,state:c,callbackPath:"/social-connections/linkedin-callback"}});if(f)throw f;if(m!=null&&m.success)r("success"),i(`Successfully connected ${((h=m.accounts)==null?void 0:h.length)||1} LinkedIn account`),re.success("LinkedIn connected successfully!");else throw new Error((m==null?void 0:m.error)||"Failed to connect LinkedIn account")}catch(m){console.error("LinkedIn callback error:",m),r("error"),i(m instanceof Error?m.message:"Failed to connect LinkedIn account"),re.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(Ne,{className:"w-full max-w-md",children:[e.jsxs(Ct,{className:"text-center",children:[e.jsxs("div",{className:"mx-auto mb-4 rounded-full bg-blue-600/10 p-4 w-fit",children:[n==="loading"&&e.jsx(kt,{className:"h-8 w-8 animate-spin text-blue-600"}),n==="success"&&e.jsx(Nc,{className:"h-8 w-8 text-green-600"}),n==="error"&&e.jsx(ku,{className:"h-8 w-8 text-red-600"})]}),e.jsxs(At,{className:"flex items-center justify-center gap-2",children:[e.jsx(hy,{className:"h-5 w-5 text-blue-600"}),n==="loading"&&"Connecting...",n==="success"&&"Connected!",n==="error"&&"Connection Failed"]}),e.jsx(Gn,{children:a})]}),e.jsx(Ie,{className:"flex justify-center",children:e.jsx($,{onClick:()=>t("/mission-control/integrations"),disabled:n==="loading",children:n==="success"?"View Integrations":"Back to Integrations"})})]})})}function Hur(){const s=Qn(),[t,n]=j.useState(null),{data:r,isLoading:a}=jos(t||void 0,!0),{data:i,isLoading:l}=Ult(!0),{cartItems:o}=VLe(),c=o.reduce((u,h)=>u+h.quantity,0),d=u=>{s(`/marketplace/${u.id}`)};return a||l?e.jsx(Vs,{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(u=>e.jsx(yn,{className:"h-10 w-24 flex-shrink-0"},u))}),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(u=>e.jsx(yn,{className:"h-72 w-full"},u))})]})}):e.jsx(Vs,{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($,{variant:"outline",onClick:()=>s("/marketplace/cart"),className:"relative",children:[e.jsx(nC,{className:"h-4 w-4 mr-2"}),"Cart",c>0&&e.jsx(Be,{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($,{variant:t===null?"default":"outline",size:"sm",onClick:()=>n(null),children:"All"}),i.map(u=>e.jsx($,{variant:t===u.id?"default":"outline",size:"sm",onClick:()=>n(u.id),children:u.name},u.id))]}),r&&r.length>0?e.jsx("div",{className:"grid gap-4 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4",children:r.map(u=>{var h;return e.jsxs(Ne,{className:"overflow-hidden cursor-pointer hover:shadow-lg transition-shadow",onClick:()=>d(u),children:[e.jsxs("div",{className:"aspect-square bg-muted relative",children:[u.images&&u.images.length>0?e.jsx("img",{src:((h=u.images.find(m=>m.is_primary))==null?void 0:h.image_url)||u.images[0].image_url,alt:u.name,className:"w-full h-full object-cover"}):e.jsx("div",{className:"flex items-center justify-center h-full",children:e.jsx(vm,{className:"h-12 w-12 text-muted-foreground"})}),u.category&&e.jsx(Be,{className:"absolute top-2 left-2",variant:"secondary",children:u.category.name})]}),e.jsxs(Ie,{className:"p-4",children:[e.jsx("h3",{className:"font-semibold mb-1 line-clamp-1",children:u.name}),u.description&&e.jsx("p",{className:"text-sm text-muted-foreground mb-2 line-clamp-2",children:u.description}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("span",{className:"font-bold text-lg",children:["$",Number(u.base_price).toFixed(2)]}),u.variants&&u.variants.length>0&&e.jsxs("span",{className:"text-xs text-muted-foreground",children:[u.variants.length," options"]})]})]})]},u.id)})}):e.jsxs("div",{className:"text-center py-12",children:[e.jsx(vm,{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 lls=j.forwardRef(({...s},t)=>e.jsx("nav",{ref:t,"aria-label":"breadcrumb",...s}));lls.displayName="Breadcrumb";const cls=j.forwardRef(({className:s,...t},n)=>e.jsx("ol",{ref:n,className:Pt("flex flex-wrap items-center gap-1.5 break-words text-sm text-muted-foreground sm:gap-2.5",s),...t}));cls.displayName="BreadcrumbList";const AAe=j.forwardRef(({className:s,...t},n)=>e.jsx("li",{ref:n,className:Pt("inline-flex items-center gap-1.5",s),...t}));AAe.displayName="BreadcrumbItem";const mQe=j.forwardRef(({asChild:s,className:t,...n},r)=>{const a=s?set:"a";return e.jsx(a,{ref:r,className:Pt("transition-colors hover:text-foreground",t),...n})});mQe.displayName="BreadcrumbLink";const dls=j.forwardRef(({className:s,...t},n)=>e.jsx("span",{ref:n,role:"link","aria-disabled":"true","aria-current":"page",className:Pt("font-normal text-foreground",s),...t}));dls.displayName="BreadcrumbPage";const fQe=({children:s,className:t,...n})=>e.jsx("li",{role:"presentation","aria-hidden":"true",className:Pt("[&>svg]:size-3.5",t),...n,children:s??e.jsx(Di,{})});fQe.displayName="BreadcrumbSeparator";function Gur(){var W,V;const{productId:s}=Wi(),t=Qn(),{data:n,isLoading:r}=Uor(s||""),{addToCart:a,cartItems:i}=VLe(),[l,o]=j.useState(null),[c,d]=j.useState(1),[u,h]=j.useState(0),[m,f]=j.useState(null),[g,x]=j.useState(!1),[y,v]=j.useState(!1),b=(W=n==null?void 0:n.variants)==null?void 0:W.find(G=>G.id===l),w=((V=n==null?void 0:n.variants)==null?void 0:V.filter(G=>G.is_active))||[],S=Number((n==null?void 0:n.base_price)||0),C=b?Number(b.price_adjustment):0,E=S+C,I=Number((n==null?void 0:n.shipping_fee)||0),P=i.reduce((G,Y)=>G+Y.quantity,0),R=async G=>{if(!G.target.files||G.target.files.length===0)return;x(!0);const Y=G.target.files[0],X=Y.name.split(".").pop(),ae=`artwork/${Date.now()}-${Math.random().toString(36).substring(7)}.${X}`;try{const{error:ie}=await q.storage.from("marketplace").upload(ae,Y);if(ie)throw ie;const{data:{publicUrl:ne}}=q.storage.from("marketplace").getPublicUrl(ae);f(ne),re.success("Artwork uploaded successfully")}catch(ie){re.error("Failed to upload artwork: "+ie.message)}finally{x(!1)}},D=()=>{if(n){if(w.length>0&&!l){re.error("Please select an option");return}a(n,b||void 0,c,m||void 0),v(!0),re.success("Added to cart!"),setTimeout(()=>v(!1),2e3)}},O=()=>{n!=null&&n.images&&h(G=>(G+1)%n.images.length)},U=()=>{n!=null&&n.images&&h(G=>(G-1+n.images.length)%n.images.length)};return r?e.jsx(Vs,{title:"Product",children:e.jsxs("div",{className:"grid gap-8 lg:grid-cols-2",children:[e.jsx(yn,{className:"aspect-square w-full"}),e.jsxs("div",{className:"space-y-4",children:[e.jsx(yn,{className:"h-8 w-3/4"}),e.jsx(yn,{className:"h-6 w-1/4"}),e.jsx(yn,{className:"h-24 w-full"}),e.jsx(yn,{className:"h-12 w-full"})]})]})}):n?e.jsxs(Vs,{title:n.name,children:[e.jsx(lls,{className:"mb-6",children:e.jsxs(cls,{children:[e.jsx(AAe,{children:e.jsx(mQe,{asChild:!0,children:e.jsx(wr,{to:"/marketplace",children:"Marketplace"})})}),n.category&&e.jsxs(e.Fragment,{children:[e.jsx(fQe,{}),e.jsx(AAe,{children:e.jsx(mQe,{asChild:!0,children:e.jsx(wr,{to:`/marketplace?category=${n.category.id}`,children:n.category.name})})})]}),e.jsx(fQe,{}),e.jsx(AAe,{children:e.jsx(dls,{children:n.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:n.images&&n.images.length>0?e.jsxs(e.Fragment,{children:[e.jsx("img",{src:n.images[u].image_url,alt:n.name,className:"max-w-full max-h-full object-contain"}),n.images.length>1&&e.jsxs(e.Fragment,{children:[e.jsx($,{variant:"ghost",size:"icon",className:"absolute left-2 top-1/2 -translate-y-1/2 bg-background/80 hover:bg-background",onClick:U,children:e.jsx(Cd,{className:"h-6 w-6"})}),e.jsx($,{variant:"ghost",size:"icon",className:"absolute right-2 top-1/2 -translate-y-1/2 bg-background/80 hover:bg-background",onClick:O,children:e.jsx(Di,{className:"h-6 w-6"})})]})]}):e.jsx("div",{className:"flex items-center justify-center h-full",children:e.jsx(vm,{className:"h-24 w-24 text-muted-foreground"})})}),n.images&&n.images.length>1&&e.jsx("div",{className:"flex gap-2 overflow-x-auto pb-2",children:n.images.map((G,Y)=>e.jsx("button",{onClick:()=>h(Y),className:`w-16 h-16 flex-shrink-0 rounded-md overflow-hidden border-2 ${Y===u?"border-primary":"border-transparent"}`,children:e.jsx("img",{src:G.image_url,alt:"",className:"w-full h-full object-cover"})},G.id))}),n.video&&e.jsx(Ne,{children:e.jsxs(Ie,{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:n.video.video_url,className:"w-full h-full rounded-lg",allowFullScreen:!0})})]})})]}),e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{children:[n.category&&e.jsx(Be,{variant:"secondary",className:"mb-2",children:n.category.name}),e.jsx("h1",{className:"text-3xl font-bold mb-2",children:n.name}),e.jsxs("div",{className:"flex items-baseline gap-2",children:[e.jsxs("span",{className:"text-3xl font-bold",children:["$",E.toFixed(2)]}),I>0&&e.jsxs("span",{className:"text-muted-foreground",children:["+ $",I.toFixed(2)," shipping"]})]})]}),n.description&&e.jsx("div",{className:"prose prose-sm max-w-none",children:e.jsx("p",{className:"text-muted-foreground whitespace-pre-wrap",children:n.description})}),w.length>0&&e.jsxs("div",{className:"space-y-3",children:[e.jsx(ee,{children:"Select Option"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:w.map(G=>e.jsxs($,{variant:l===G.id?"default":"outline",onClick:()=>o(G.id),children:[G.name,Number(G.price_adjustment)!==0&&e.jsxs("span",{className:"ml-1 opacity-70",children:["(",Number(G.price_adjustment)>0?"+":"","$",Number(G.price_adjustment).toFixed(2),")"]})]},G.id))})]}),n.allow_artwork_upload&&e.jsxs("div",{className:"space-y-3",children:[e.jsx(ee,{children:"Upload Your Artwork (Optional)"}),m?e.jsxs("div",{className:"relative inline-block",children:[e.jsx("img",{src:m,alt:"Your artwork",className:"h-24 w-auto rounded-lg border"}),e.jsx($,{variant:"ghost",size:"sm",className:"absolute -top-2 -right-2",onClick:()=>f(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:R,className:"hidden",id:"artwork-upload",disabled:g}),e.jsxs("label",{htmlFor:"artwork-upload",className:"flex flex-col items-center cursor-pointer",children:[e.jsx(ni,{className:"h-8 w-8 text-muted-foreground mb-2"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:g?"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(ee,{children:"Quantity"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx($,{variant:"outline",size:"icon",onClick:()=>d(G=>Math.max(1,G-1)),children:"-"}),e.jsx(pe,{type:"number",value:c,onChange:G=>d(Math.max(1,parseInt(G.target.value)||1)),className:"w-20 text-center",min:"1"}),e.jsx($,{variant:"outline",size:"icon",onClick:()=>d(G=>G+1),children:"+"})]})]}),e.jsxs("div",{className:"flex gap-4",children:[e.jsx($,{size:"lg",className:"flex-1",onClick:D,disabled:y,children:y?e.jsxs(e.Fragment,{children:[e.jsx(la,{className:"h-5 w-5 mr-2"}),"Added!"]}):e.jsxs(e.Fragment,{children:[e.jsx(nC,{className:"h-5 w-5 mr-2"}),"Add to Cart"]})}),e.jsxs($,{variant:"outline",size:"lg",onClick:()=>t("/marketplace/cart"),className:"relative",children:[e.jsx(nC,{className:"h-5 w-5"}),P>0&&e.jsx(Be,{className:"absolute -top-2 -right-2 h-5 w-5 flex items-center justify-center p-0 text-xs",children:P})]})]}),n.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(Vs,{title:"Product Not Found",children:e.jsxs("div",{className:"text-center py-12",children:[e.jsx(vm,{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($,{onClick:()=>t("/marketplace"),children:"Back to Marketplace"})]})})}function Wur(){const s=Qn(),{cartItems:t,removeFromCart:n,updateQuantity:r,getItemPrice:a,getSubtotal:i,getShippingTotal:l,getTotal:o,clearCart:c}=VLe(),[d,u]=j.useState(!1),[h,m]=j.useState(""),f=async()=>{if(t.length===0){re.error("Your cart is empty");return}u(!0);try{const{data:g,error:x}=await q.functions.invoke("marketplace-checkout",{body:{items:t.map(y=>{var v;return{product_id:y.product.id,variant_id:((v=y.variant)==null?void 0:v.id)||null,quantity:y.quantity,artwork_url:y.artworkUrl||null}}),notes:h.trim()||null}});if(x)throw x;if(g!=null&&g.url)c(),window.open(g.url,"_blank");else throw new Error("No checkout URL received")}catch(g){re.error("Checkout failed: "+g.message)}finally{u(!1)}};return t.length===0?e.jsx(Vs,{title:"Shopping Cart",children:e.jsxs("div",{className:"text-center py-12",children:[e.jsx(D4,{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($,{onClick:()=>s("/marketplace"),children:"Browse Marketplace"})]})}):e.jsx(Vs,{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(g=>{var x,y;return e.jsx(Ne,{children:e.jsx(Ie,{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:g.product.images&&g.product.images.length>0?e.jsx("img",{src:((x=g.product.images.find(v=>v.is_primary))==null?void 0:x.image_url)||g.product.images[0].image_url,alt:g.product.name,className:"w-full h-full object-cover"}):e.jsx("div",{className:"flex items-center justify-center h-full",children:e.jsx(D4,{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:g.product.name}),g.variant&&e.jsx("p",{className:"text-sm text-muted-foreground",children:g.variant.name}),e.jsxs("p",{className:"font-medium mt-1",children:["$",a(g).toFixed(2),Number(g.product.shipping_fee)>0&&e.jsxs("span",{className:"text-sm text-muted-foreground ml-2",children:["+ $",Number(g.product.shipping_fee).toFixed(2)," shipping"]})]}),g.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($,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>{var v;return n(g.product.id,(v=g.variant)==null?void 0:v.id)},children:e.jsx(Wn,{className:"h-4 w-4 text-destructive"})}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx($,{variant:"outline",size:"icon",className:"h-8 w-8",onClick:()=>{var v;return r(g.product.id,(v=g.variant)==null?void 0:v.id,g.quantity-1)},disabled:g.quantity<=1,children:e.jsx(tk,{className:"h-3 w-3"})}),e.jsx(pe,{type:"number",value:g.quantity,onChange:v=>{var b;return r(g.product.id,(b=g.variant)==null?void 0:b.id,parseInt(v.target.value)||1)},className:"w-14 h-8 text-center text-sm",min:"1"}),e.jsx($,{variant:"outline",size:"icon",className:"h-8 w-8",onClick:()=>{var v;return r(g.product.id,(v=g.variant)==null?void 0:v.id,g.quantity+1)},children:e.jsx(dn,{className:"h-3 w-3"})})]})]})]})})},`${g.product.id}-${((y=g.variant)==null?void 0:y.id)||"base"}`)}),e.jsx($,{variant:"ghost",className:"text-destructive",onClick:c,children:"Clear Cart"})]}),e.jsx("div",{children:e.jsxs(Ne,{className:"sticky top-4",children:[e.jsx(Ct,{children:e.jsx(At,{children:"Order Summary"})}),e.jsxs(Ie,{className:"space-y-4",children:[e.jsxs("div",{className:"flex justify-between text-sm",children:[e.jsxs("span",{children:["Subtotal (",t.reduce((g,x)=>g+x.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(Gc,{}),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(Gc,{}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"orderNotes",children:"Order Notes (Optional)"}),e.jsx(Rs,{id:"orderNotes",placeholder:"Add any special instructions, design notes, or comments for your order...",value:h,onChange:g=>m(g.target.value),rows:3,className:"resize-none"})]}),e.jsx($,{className:"w-full",size:"lg",onClick:f,disabled:d,children:d?e.jsxs(e.Fragment,{children:[e.jsx(kt,{className:"h-5 w-5 mr-2 animate-spin"}),"Processing..."]}):e.jsxs(e.Fragment,{children:["Checkout",e.jsx(ei,{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 Kur(){const s=Qn(),{data:t,isLoading:n}=Jor();return n?e.jsx(Vs,{title:"My Orders",children:e.jsx("div",{className:"space-y-4",children:[1,2,3].map(r=>e.jsx(yn,{className:"h-32 w-full"},r))})}):!t||t.length===0?e.jsx(Vs,{title:"My Orders",children:e.jsxs("div",{className:"text-center py-12",children:[e.jsx(vm,{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($,{onClick:()=>s("/marketplace"),children:"Browse Marketplace"})]})}):e.jsx(Vs,{title:"My Orders",children:e.jsx("div",{className:"space-y-4",children:t.map(r=>{var a,i,l;return e.jsx(Ne,{className:"cursor-pointer hover:shadow-md transition-shadow",onClick:()=>s(`/marketplace/orders/${r.id}`),children:e.jsxs(Ie,{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:r.order_number}),e.jsx("span",{className:"text-muted-foreground text-sm ml-2",children:en(new Date(r.created_at),"MMM d, yyyy")})]}),e.jsx(Be,{className:$lt[r.status],children:YV[r.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=r.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)),r.items&&r.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:["+",r.items.length-3]})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm",children:((i=r.items)==null?void 0:i.length)===1?r.items[0].product_name:`${(l=r.items)==null?void 0:l.length} items`}),e.jsxs("p",{className:"font-semibold",children:["$",Number(r.total).toFixed(2)]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[r.tracking_url&&e.jsxs($,{variant:"outline",size:"sm",onClick:o=>{o.stopPropagation(),window.open(r.tracking_url,"_blank")},children:[e.jsx(kr,{className:"h-4 w-4 mr-1"}),"Track"]}),e.jsx(Di,{className:"h-5 w-5 text-muted-foreground"})]})]})]})},r.id)})})})}const KEt=["order_submitted","awaiting_proof_approval","proof_approved","processing","in_production","shipped","completed"];function Yur({currentStatus:s,statusHistory:t}){const n=KEt.indexOf(s);return e.jsx("div",{className:"space-y-3",children:KEt.map((r,a)=>{const i=t==null?void 0:t.find(d=>d.status===r),l=an;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(qr,{className:"h-4 w-4"}):o?e.jsx(da,{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:YV[r]}),i&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:[en(new Date(i.created_at),"MMM d, yyyy h:mm a"),i.notes&&` — ${i.notes}`]})]})]},r)})})}function Zur(){var v;const{orderId:s}=Wi(),t=Qn(),{data:n,isLoading:r,refetch:a}=elr(s||""),i=nlr(),l=rlr(),[o,c]=j.useState(!1),[d,u]=j.useState(null),[h,m]=j.useState(""),[f,g]=j.useState(null),x=async b=>{g(b);try{await i.mutateAsync({orderId:s,itemId:b}),re.success("Proof approved!"),a()}catch{re.error("Failed to approve proof")}finally{g(null)}},y=async()=>{if(d){g(d);try{await l.mutateAsync({orderId:s,itemId:d,reason:h}),re.success("Revision requested"),c(!1),m(""),u(null),a()}catch{re.error("Failed to request revision")}finally{g(null)}}};return r?e.jsx(Vs,{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(yn,{className:"h-64 w-full"}),e.jsx(yn,{className:"h-48 w-full"})]}),e.jsx(yn,{className:"h-96 w-full"})]})}):n?e.jsxs(Vs,{title:`Order ${n.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(Ne,{children:[e.jsxs(Ct,{className:"flex flex-row items-center justify-between",children:[e.jsx(At,{children:"Order Status"}),e.jsx(Be,{className:$lt[n.status],children:YV[n.status]})]}),e.jsx(Ie,{children:e.jsx(Yur,{currentStatus:n.status,statusHistory:n.status_history})})]}),e.jsxs(Ne,{children:[e.jsx(Ct,{children:e.jsx(At,{children:"Items"})}),e.jsx(Ie,{className:"space-y-4",children:(v=n.items)==null?void 0:v.map(b=>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:b.product_name}),b.variant_name&&e.jsx("p",{className:"text-sm text-muted-foreground",children:b.variant_name}),e.jsxs("p",{className:"text-sm",children:["Qty: ",b.quantity," × $",Number(b.unit_price).toFixed(2)]})]}),e.jsxs("p",{className:"font-semibold",children:["$",(Number(b.unit_price)*b.quantity).toFixed(2)]})]}),b.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:b.artwork_url,target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-2 text-primary hover:underline",children:[e.jsx(GI,{className:"h-4 w-4"}),"View Artwork",e.jsx(kr,{className:"h-3 w-3"})]})]}),b.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:b.proof_url,target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-2 text-primary hover:underline mb-3",children:[e.jsx(GI,{className:"h-4 w-4"}),"View Proof",e.jsx(kr,{className:"h-3 w-3"})]}),b.proof_status==="pending"&&e.jsxs("div",{className:"flex gap-2 mt-3",children:[e.jsxs($,{size:"sm",onClick:()=>x(b.id),disabled:f===b.id,children:[f===b.id?e.jsx(kt,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(Vy,{className:"h-4 w-4 mr-1"}),"Approve"]}),e.jsxs($,{size:"sm",variant:"outline",onClick:()=>{u(b.id),c(!0)},disabled:f===b.id,children:[e.jsx(iee,{className:"h-4 w-4 mr-1"}),"Request Changes"]})]}),b.proof_status==="approved"&&e.jsxs(Be,{className:"bg-green-100 text-green-800",children:[e.jsx(qr,{className:"h-3 w-3 mr-1"}),"Proof Approved"]}),b.proof_status==="rejected"&&b.proof_notes&&e.jsxs("div",{className:"mt-2",children:[e.jsx(Be,{variant:"destructive",className:"mb-2",children:"Revision Requested"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:b.proof_notes})]})]})]},b.id))})]}),n.shipping_name&&e.jsxs(Ne,{children:[e.jsx(Ct,{children:e.jsxs(At,{className:"flex items-center gap-2",children:[e.jsx(oee,{className:"h-5 w-5"}),"Shipping"]})}),e.jsxs(Ie,{children:[e.jsx("p",{className:"font-medium",children:n.shipping_name}),e.jsxs("p",{className:"text-muted-foreground",children:[n.shipping_address,e.jsx("br",{}),n.shipping_city,", ",n.shipping_state," ",n.shipping_zip]}),n.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:n.tracking_number}),n.tracking_url&&e.jsxs($,{variant:"link",className:"p-0 h-auto mt-1",onClick:()=>window.open(n.tracking_url,"_blank"),children:["Track Package",e.jsx(kr,{className:"h-3 w-3 ml-1"})]})]})]})]})]}),e.jsx("div",{children:e.jsxs(Ne,{className:"sticky top-4",children:[e.jsx(Ct,{children:e.jsx(At,{children:"Order Summary"})}),e.jsxs(Ie,{className:"space-y-4",children:[e.jsxs("div",{className:"text-sm text-muted-foreground",children:["Placed on ",en(new Date(n.created_at),"MMMM d, yyyy")]}),e.jsx(Gc,{}),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(n.subtotal).toFixed(2)]})]}),e.jsxs("div",{className:"flex justify-between text-sm",children:[e.jsx("span",{children:"Shipping"}),e.jsxs("span",{children:["$",Number(n.shipping_total).toFixed(2)]})]})]}),e.jsx(Gc,{}),e.jsxs("div",{className:"flex justify-between font-bold text-lg",children:[e.jsx("span",{children:"Total"}),e.jsxs("span",{children:["$",Number(n.total).toFixed(2)]})]}),n.notes&&e.jsxs(e.Fragment,{children:[e.jsx(Gc,{}),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:n.notes})]})]})]})]})})]}),e.jsx(zs,{open:o,onOpenChange:c,children:e.jsxs(Os,{children:[e.jsxs(Us,{children:[e.jsx(Bs,{children:"Request Changes"}),e.jsx(Ir,{children:"Please describe what changes you'd like made to the proof."})]}),e.jsx(Rs,{placeholder:"Describe the changes needed...",value:h,onChange:b=>m(b.target.value),rows:4}),e.jsxs(Ar,{children:[e.jsx($,{variant:"outline",onClick:()=>c(!1),children:"Cancel"}),e.jsxs($,{onClick:y,disabled:!h.trim()||f!==null,children:[f?e.jsx(kt,{className:"h-4 w-4 mr-2 animate-spin"}):null,"Submit Request"]})]})]})})]}):e.jsx(Vs,{title:"Order Not Found",children:e.jsxs("div",{className:"text-center py-12",children:[e.jsx(vm,{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($,{onClick:()=>t("/marketplace/orders"),children:"View All Orders"})]})})}function Xur(){const s=Qn(),[t]=gc();return t.get("session_id"),j.useEffect(()=>{localStorage.removeItem("marketplace-cart")},[]),e.jsx(Vs,{title:"Order Confirmed",children:e.jsx("div",{className:"max-w-lg mx-auto text-center py-8",children:e.jsx(Ne,{children:e.jsxs(Ie,{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(qr,{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(vm,{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($,{className:"flex-1",onClick:()=>s("/marketplace/orders"),children:["View My Orders",e.jsx(ei,{className:"h-4 w-4 ml-2"})]}),e.jsx($,{variant:"outline",className:"flex-1",onClick:()=>s("/marketplace"),children:"Continue Shopping"})]})]})})})})}function Qur(){const{user:s}=vs(),[t,n]=j.useState("store"),[r,a]=j.useState(null),[i,l]=j.useState(null),[o,c]=j.useState(!1),[d,u]=j.useState(5),[h,m]=j.useState(""),[f,g]=j.useState(!1),[x,y]=j.useState(!1),[v,b]=j.useState(""),[w,S]=j.useState(null),[C,E]=j.useState(!1),{hasSubmittedReview:I,submitReview:P,markPostedToGoogle:R}=f7t(),{data:D}=kos(),{data:O,isLoading:U}=Nos(),{data:W,isLoading:V}=ulr(r),{data:G,isLoading:Y}=hlr(s==null?void 0:s.id),{data:X=0}=flr(s==null?void 0:s.id),ae=plr(),ie=new Set((G==null?void 0:G.map(ue=>ue.item_id))||[]),ne=async()=>{if(i)try{const ue=await ae.mutateAsync(i.id);i.item_type==="reelflow_credits"?re.success(`🎬 ${i.max_quantity} ReelFlow credits added to your balance!`):re.success(`Successfully purchased "${i.name}"!`),l(null)}catch(ue){re.error(ue.message||"Failed to purchase item")}},te=async()=>{if(!h.trim()){re.error("Please write a review");return}g(!0);const ue=await P(d,h);g(!1),ue.success?(re.success("Thank you for your review! You earned 25 points!"),b(h),y(!0),m(""),u(5)):re.error(ue.error||"Failed to submit review")},J=()=>{navigator.clipboard.writeText(v),re.success("Review copied to clipboard!")},ce=()=>{R(),window.open("https://g.page/r/CT8bqTBTm7nJEBM/review","_blank")},_e=()=>{y(!1),c(!1),b("")};return U||V||Y?e.jsx(Vs,{title:"Reward Store",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(yn,{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(ue=>e.jsx(yn,{className:"h-64"},ue))})]})}):e.jsxs(Vs,{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(Ne,{className:"bg-gradient-to-r from-primary/10 to-primary/5 border-primary/20",children:e.jsx(Ie,{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(Ja,{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:X.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(Kl,{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(nh,{className:"h-4 w-4 text-orange-500"}),e.jsx("span",{children:"Streak bonuses add extra points!"})]})]})]})})}),e.jsx(j1,{open:C,onOpenChange:E,children:e.jsxs(Ne,{className:"border-primary/20",children:[e.jsx(N1,{asChild:!0,children:e.jsx(Ct,{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(Kl,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{children:[e.jsx(At,{className:"text-base",children:"How to Earn Points"}),e.jsx(Gn,{children:"See all the ways you can earn spendable points"})]})]}),C?e.jsx(v1,{className:"h-5 w-5 text-muted-foreground"}):e.jsx(Tl,{className:"h-5 w-5 text-muted-foreground"})]})})}),e.jsx(k1,{children:e.jsx(Ie,{className:"pt-0",children:e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-3",children:[D==null?void 0:D.filter(ue=>ue.is_active).map(ue=>{const ve=Ee=>{switch(Ee){case"event_attendance":return e.jsx(Ta,{className:"h-5 w-5"});case"leave_review":return e.jsx(Ja,{className:"h-5 w-5"});case"add_listing":return e.jsx(va,{className:"h-5 w-5"});case"first_contact":return e.jsx(Zn,{className:"h-5 w-5"});case"first_video":return e.jsx(ua,{className:"h-5 w-5"});case"first_community_post":return e.jsx(eo,{className:"h-5 w-5"});default:return e.jsx(ul,{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:ve(ue.action_key)}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-medium text-sm",children:ue.action_name}),ue.description&&e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:ue.description})]}),e.jsxs(Be,{variant:"secondary",className:"font-bold shrink-0",children:["+",ue.points]})]},ue.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(nh,{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(Be,{variant:"outline",className:"font-bold shrink-0 border-orange-500/50 text-orange-600",children:"+Bonus"})]})]})})})]})}),!I&&e.jsx(Ne,{className:"bg-gradient-to-r from-yellow-500/10 to-orange-500/10 border-yellow-500/20",children:e.jsx(Ie,{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(eo,{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($,{onClick:()=>c(!0),className:"bg-yellow-600 hover:bg-yellow-700",children:[e.jsx(Ja,{className:"h-4 w-4 mr-2"}),"Leave Review"]})]})})}),e.jsxs(ha,{value:t,onValueChange:n,children:[e.jsxs(ma,{children:[e.jsxs(Zt,{value:"store",className:"flex items-center gap-2",children:[e.jsx(D4,{className:"h-4 w-4"}),"Store"]}),e.jsxs(Zt,{value:"my-rewards",className:"flex items-center gap-2",children:[e.jsx(vm,{className:"h-4 w-4"}),"My Rewards",G&&G.length>0&&e.jsx(Be,{variant:"secondary",className:"ml-1",children:G.length})]})]}),e.jsxs(Xt,{value:"store",className:"mt-6",children:[O&&O.length>0&&e.jsxs("div",{className:"flex flex-wrap gap-2 mb-6",children:[e.jsx($,{variant:r===null?"default":"outline",size:"sm",onClick:()=>a(null),children:"All"}),O.map(ue=>e.jsxs($,{variant:r===ue.id?"default":"outline",size:"sm",onClick:()=>a(ue.id),children:[ue.icon&&`${ue.icon} `,ue.name]},ue.id))]}),!W||W.length===0?e.jsx(Ne,{children:e.jsx(Ie,{className:"py-12",children:e.jsxs("div",{className:"text-center text-muted-foreground",children:[e.jsx(ul,{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:W.map(ue=>{const ve=ue.item_type==="reelflow_credits",Ee=!ve&&ie.has(ue.id),Se=!ve&&ue.max_quantity!==null&&ue.current_quantity===0,Le=X>=ue.points_cost;return e.jsxs(Ne,{className:`overflow-hidden transition-all cursor-pointer hover:shadow-lg ${Ee?"ring-2 ring-green-500/50 bg-green-500/5":""}`,onClick:()=>S(ue),children:[ue.preview_image_url?e.jsxs("div",{className:"aspect-video relative overflow-hidden bg-muted",children:[e.jsx("img",{src:ue.preview_image_url,alt:ue.name,className:"w-full h-full object-cover"}),Ee&&e.jsx("div",{className:"absolute top-2 right-2",children:e.jsxs(Be,{className:"bg-green-500 text-white",children:[e.jsx(qr,{className:"h-3 w-3 mr-1"}),"Owned"]})}),Se&&!Ee&&e.jsx("div",{className:"absolute inset-0 bg-black/50 flex items-center justify-center",children:e.jsx(Be,{variant:"destructive",children:"Sold Out"})})]}):e.jsxs("div",{className:"aspect-video bg-muted flex items-center justify-center relative",children:[e.jsx(ul,{className:"h-12 w-12 text-muted-foreground/50"}),Ee&&e.jsx("div",{className:"absolute top-2 right-2",children:e.jsxs(Be,{className:"bg-green-500 text-white",children:[e.jsx(qr,{className:"h-3 w-3 mr-1"}),"Owned"]})})]}),e.jsxs(Ct,{className:"pb-2",children:[e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsx(At,{className:"text-lg",children:ue.name}),e.jsxs(Be,{variant:"secondary",className:"font-bold shrink-0",children:[e.jsx(Ja,{className:"h-3 w-3 mr-1"}),ue.points_cost]})]}),ue.category&&e.jsxs(Be,{variant:"outline",className:"w-fit",children:[ue.category.icon&&`${ue.category.icon} `,ue.category.name]})]}),e.jsxs(Ie,{children:[e.jsx(Gn,{className:"mb-4 line-clamp-2",children:ue.description||"No description available"}),ue.max_quantity!==null&&!Ee&&!ve&&e.jsxs("p",{className:"text-xs text-muted-foreground mb-3",children:[ue.current_quantity," of ",ue.max_quantity," remaining"]}),ve&&e.jsxs("p",{className:"text-xs text-violet-600 font-medium mb-3",children:["🎬 Grants ",ue.max_quantity," ReelFlow credits per purchase"]}),Ee?e.jsx($,{className:"w-full",onClick:Fe=>{Fe.stopPropagation(),ue.file_url&&yUe(ue.file_url,ue.name)},disabled:!ue.file_url,children:ue.item_type==="file"?e.jsxs(e.Fragment,{children:[e.jsx(di,{className:"h-4 w-4 mr-2"}),"Download"]}):e.jsxs(e.Fragment,{children:[e.jsx(kr,{className:"h-4 w-4 mr-2"}),"Access"]})}):e.jsx($,{className:"w-full",onClick:Fe=>{Fe.stopPropagation(),l(ue)},disabled:Se||!Le,children:Se?"Sold Out":Le?e.jsxs(e.Fragment,{children:[e.jsx(D4,{className:"h-4 w-4 mr-2"}),"Purchase"]}):`Need ${ue.points_cost-X} more pts`})]})]},ue.id)})})]}),e.jsx(Xt,{value:"my-rewards",className:"mt-6",children:!G||G.length===0?e.jsx(Ne,{children:e.jsx(Ie,{className:"py-12",children:e.jsxs("div",{className:"text-center text-muted-foreground",children:[e.jsx(vm,{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:G.map(ue=>{var ve,Ee,Se,Le,Fe,ke,Ve;return e.jsxs(Ne,{className:"overflow-hidden",children:[(ve=ue.item)!=null&&ve.preview_image_url?e.jsx("div",{className:"aspect-video relative overflow-hidden bg-muted",children:e.jsx("img",{src:ue.item.preview_image_url,alt:((Ee=ue.item)==null?void 0:Ee.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(ul,{className:"h-12 w-12 text-muted-foreground/50"})}),e.jsxs(Ct,{className:"pb-2",children:[e.jsx(At,{className:"text-lg",children:((Se=ue.item)==null?void 0:Se.name)||"Unknown Item"}),e.jsxs(Gn,{className:"text-xs",children:["Purchased for ",ue.points_spent," points • ",new Date(ue.purchased_at).toLocaleDateString()]})]}),e.jsx(Ie,{children:((Le=ue.item)==null?void 0:Le.item_type)==="reelflow_credits"?e.jsxs($,{className:"w-full",variant:"outline",disabled:!0,children:[e.jsx(qr,{className:"h-4 w-4 mr-2 text-green-500"}),(Fe=ue.item)==null?void 0:Fe.max_quantity," Credits Applied"]}):e.jsx($,{className:"w-full",onClick:()=>{var je,Ae;(je=ue.item)!=null&&je.file_url&&yUe(ue.item.file_url,(Ae=ue.item)==null?void 0:Ae.name)},disabled:!((ke=ue.item)!=null&&ke.file_url),children:((Ve=ue.item)==null?void 0:Ve.item_type)==="file"?e.jsxs(e.Fragment,{children:[e.jsx(di,{className:"h-4 w-4 mr-2"}),"Download"]}):e.jsxs(e.Fragment,{children:[e.jsx(kr,{className:"h-4 w-4 mr-2"}),"Access"]})})})]},ue.id)})})})]})]}),e.jsx(kc,{open:!!i,onOpenChange:()=>l(null),children:e.jsxs(cc,{children:[e.jsxs(dc,{children:[e.jsx(hc,{children:"Confirm Purchase"}),e.jsxs(mc,{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:[X," points"]}),". After this purchase, you'll have"," ",e.jsxs("strong",{children:[X-((i==null?void 0:i.points_cost)||0)," points"]})," remaining."]})]}),e.jsxs(uc,{children:[e.jsx(fc,{children:"Cancel"}),e.jsx(tc,{onClick:ne,disabled:ae.isPending,children:ae.isPending?"Purchasing...":"Confirm Purchase"})]})]})}),e.jsx(zs,{open:o,onOpenChange:ue=>{!ue&&x?_e():c(ue)},children:e.jsx(Os,{children:x?e.jsxs(e.Fragment,{children:[e.jsxs(Us,{children:[e.jsxs(Bs,{className:"flex items-center gap-2",children:[e.jsx(qr,{className:"h-5 w-5 text-green-500"}),"Thank You for Your Review!"]}),e.jsx(Ir,{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:['"',v,'"']})]}),e.jsxs($,{variant:"outline",className:"w-full",onClick:J,children:[e.jsx(Ha,{className:"h-4 w-4 mr-2"}),"Copy Review to Clipboard"]})]}),e.jsxs(Ar,{className:"flex-col sm:flex-row gap-2",children:[e.jsx($,{variant:"outline",onClick:_e,children:"Maybe Later"}),e.jsxs($,{onClick:ce,className:"bg-blue-600 hover:bg-blue-700",children:[e.jsx(kr,{className:"h-4 w-4 mr-2"}),"Leave Google Review"]})]})]}):e.jsxs(e.Fragment,{children:[e.jsxs(Us,{children:[e.jsx(Bs,{children:"Leave a Review"}),e.jsx(Ir,{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(ue=>e.jsx("button",{type:"button",onClick:()=>u(ue),className:"focus:outline-none",children:e.jsx(Ja,{className:`h-8 w-8 transition-colors ${d>=ue?"fill-yellow-400 text-yellow-400":"text-muted-foreground hover:text-yellow-400"}`})},ue))})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium mb-2 block",children:"Your Review"}),e.jsx(Rs,{placeholder:"What do you love about LevelUp? How has it helped your business?",value:h,onChange:ue=>m(ue.target.value),rows:4})]})]}),e.jsxs(Ar,{children:[e.jsx($,{variant:"outline",onClick:()=>c(!1),children:"Cancel"}),e.jsx($,{onClick:te,disabled:f,className:"bg-yellow-600 hover:bg-yellow-700",children:f?"Submitting...":"Submit & Earn 25 Points"})]})]})})}),e.jsx(zs,{open:!!w,onOpenChange:()=>S(null),children:e.jsxs(Os,{className:"max-w-lg",children:[e.jsxs(Us,{children:[e.jsxs(Bs,{className:"flex items-center gap-2",children:[w==null?void 0:w.name,e.jsxs(Be,{variant:"secondary",className:"font-bold",children:[e.jsx(Ja,{className:"h-3 w-3 mr-1"}),w==null?void 0:w.points_cost]})]}),(w==null?void 0:w.category)&&e.jsxs(Be,{variant:"outline",className:"w-fit",children:[w.category.icon&&`${w.category.icon} `,w.category.name]})]}),(w==null?void 0:w.preview_image_url)&&e.jsx("div",{className:"aspect-video relative overflow-hidden bg-muted rounded-lg",children:e.jsx("img",{src:w.preview_image_url,alt:w.name,className:"w-full h-full object-cover"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsx("p",{className:"text-muted-foreground",children:(w==null?void 0:w.description)||"No description available"}),(w==null?void 0:w.item_type)==="reelflow_credits"&&e.jsxs("p",{className:"text-sm text-violet-600 font-medium",children:["🎬 Grants ",w==null?void 0:w.max_quantity," ReelFlow credits per purchase"]}),(w==null?void 0:w.item_type)!=="reelflow_credits"&&(w==null?void 0:w.max_quantity)!==null&&!ie.has((w==null?void 0:w.id)||"")&&e.jsxs("p",{className:"text-sm text-muted-foreground",children:[w==null?void 0:w.current_quantity," of ",w==null?void 0:w.max_quantity," remaining"]})]}),e.jsx(Ar,{children:w&&w.item_type!=="reelflow_credits"&&ie.has(w.id)?e.jsx($,{className:"w-full",onClick:()=>{w.file_url&&yUe(w.file_url,w.name)},disabled:!w.file_url,children:w.item_type==="file"?e.jsxs(e.Fragment,{children:[e.jsx(di,{className:"h-4 w-4 mr-2"}),"Download"]}):e.jsxs(e.Fragment,{children:[e.jsx(kr,{className:"h-4 w-4 mr-2"}),"Access"]})}):w&&e.jsx($,{className:"w-full",onClick:()=>{S(null),l(w)},disabled:w.item_type!=="reelflow_credits"&&w.max_quantity!==null&&w.current_quantity===0||X{s&&Y()},[s==null?void 0:s.id]);const Y=async()=>{if(!s)return;o(!0),v(!1),x(!0);const{data:Fe}=await q.from("point_reward_settings").select("action_key, points").in("action_key",["referral_signup","referral_paid"]);Fe==null||Fe.forEach(Ae=>{Ae.action_key==="referral_signup"&&h(Ae.points),Ae.action_key==="referral_paid"&&f(Ae.points)});const{data:ke}=await q.from("profiles").select("name").eq("id",s.id).maybeSingle();ke!=null&&ke.name&&w(ke.name);let{data:Ve}=await q.from("agent_referral_codes").select("code").eq("user_id",s.id).maybeSingle();if(!Ve){const{data:Ae}=await q.rpc("generate_agent_referral_code",{_user_id:s.id}),Ce=Ae||`agent${s.id.slice(0,6)}`,{data:qe,error:ze}=await q.from("agent_referral_codes").insert({user_id:s.id,code:Ce}).select("code").maybeSingle();!ze&&qe&&(Ve=qe)}i((Ve==null?void 0:Ve.code)??null);const{data:je}=await q.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(je&&je.length>0){const Ae=je.map(ze=>ze.referred_user_id),{data:Ce}=await q.from("profiles").select("id, name, email").in("id",Ae),qe=new Map((Ce==null?void 0:Ce.map(ze=>[ze.id,ze]))??[]);d(je.map(ze=>({...ze,referred_profile:qe.get(ze.referred_user_id)??null})))}else d([]);o(!1)},X=j.useMemo(()=>a?`${Jur}/trial?ref=${a}`:"",[a]),ae=c.length,ie=c.filter(Fe=>Fe.status==="qualified").length,ne=c.filter(Fe=>Fe.signup_points_awarded).length*u+c.filter(Fe=>Fe.paid_points_awarded).length*m,te=async()=>{X&&(await navigator.clipboard.writeText(X),re.success("Referral link copied!"))},J=()=>{const Fe=encodeURIComponent("Join me on LevelUp"),ke=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: ${X} Let me know if you have any questions!`);window.location.href=`mailto:?subject=${Fe}&body=${ke}`},ce=()=>{const Fe=encodeURIComponent(`Hey! I think you'd love LevelUp for your business — sign up with my link: ${X}`);window.location.href=`sms:?&body=${Fe}`},_e=async()=>{if(navigator.share&&X)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:X})}catch{}else te()},he=Fe=>/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(Fe.trim()),ue=Fe=>{const ke=(Fe??E).trim().replace(/,$/,"");if(!ke)return;const Ve=ke.split(/[\s,;]+/).filter(Boolean),je=[...P];let Ae=0;for(const Ce of Ve){if(!he(Ce)){re.error(`Invalid email: ${Ce}`);continue}je.includes(Ce)||(je.push(Ce),Ae++)}R(je),Ae>0&&I("")},ve=Fe=>R(P.filter(ke=>ke!==Fe)),Ee=()=>{W(`${b?b.split(" ")[0]+" invited you to":"Join me on"} LevelUp`),O("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."),C(!0)},Se=Fe=>{const ke=Fe.replace(/&/g,"&").replace(//g,">").replace(/\n/g,"
"),Ve=b||"A fellow agent",je="https://relzejiswnotikjgvjhz.supabase.co/storage/v1/object/public/email-assets/levelup-logo-email.png",Ae=X;return`
LevelUp
You're Invited

${Ve} thinks you'd love LevelUp 🎉

${ke}

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:
${Ae}

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

`.trim()},Le=async()=>{if(P.length===0&&(E.trim()&&ue(),P.length===0)){re.error("Add at least one recipient");return}if(!U.trim()){re.error("Subject is required");return}G(!0);const Fe=Se(D);let ke=0,Ve=0;for(const je of P)try{const{data:Ae,error:Ce}=await q.functions.invoke("gmail-send",{body:{to:je,subject:U,body:Fe,source:"referral_invite"}});if(Ce||Ae!=null&&Ae.error)throw new Error((Ce==null?void 0:Ce.message)||(Ae==null?void 0:Ae.error));ke++}catch(Ae){console.error("Gmail send failed for",je,Ae),Ve++}G(!1),ke>0?(re.success(`Invite sent to ${ke} ${ke===1?"person":"people"}`+(Ve>0?` (${Ve} failed)`:"")),R([]),I(""),C(!1)):re.error("Failed to send invites")};return!y&&!g?e.jsx(Vs,{title:"Refer & Earn",children:e.jsxs("div",{className:"container max-w-3xl mx-auto p-4 md:p-8",children:[e.jsx(Ml,{children:e.jsx("title",{children:"Refer & Earn | LevelUp"})}),e.jsxs(Ne,{className:"border-2 border-dashed",children:[e.jsxs(Ct,{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(pc,{className:"h-6 w-6 text-muted-foreground"})}),e.jsx(At,{children:"Refer & Earn is for active members"}),e.jsx(Gn,{children:"Activate your subscription to unlock your personal referral link and start earning points."})]}),e.jsx(Ie,{className:"flex justify-center",children:e.jsx($,{onClick:()=>t("/subscription"),children:"View Subscription"})})]})]})}):e.jsxs(Vs,{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(Ml,{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(ul,{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:[u," points"]})," when they sign up and"," ",e.jsxs("span",{className:"font-semibold text-foreground",children:[m," more"]})," when they activate a paid plan."]})]}),e.jsxs("div",{className:"grid gap-3 md:grid-cols-3",children:[e.jsx(Ne,{children:e.jsxs(Ie,{className:"p-4 flex items-center gap-3",children:[e.jsx(Zn,{className:"h-5 w-5 text-muted-foreground"}),e.jsxs("div",{children:[e.jsx("div",{className:"text-2xl font-bold",children:ae}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Friends signed up"})]})]})}),e.jsx(Ne,{children:e.jsxs(Ie,{className:"p-4 flex items-center gap-3",children:[e.jsx(qr,{className:"h-5 w-5 text-emerald-600"}),e.jsxs("div",{children:[e.jsx("div",{className:"text-2xl font-bold",children:ie}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Activated paid plan"})]})]})}),e.jsx(Ne,{children:e.jsxs(Ie,{className:"p-4 flex items-center gap-3",children:[e.jsx(Kl,{className:"h-5 w-5 text-amber-500"}),e.jsxs("div",{children:[e.jsx("div",{className:"text-2xl font-bold",children:ne.toLocaleString()}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Points earned"})]})]})})]}),e.jsxs(Ne,{children:[e.jsxs(Ct,{children:[e.jsxs(At,{className:"flex items-center gap-2",children:[e.jsx(Nn,{className:"h-5 w-5 text-primary"}),"Your referral link"]}),e.jsx(Gn,{children:"Anyone who signs up through this link is credited to you."})]}),e.jsxs(Ie,{className:"space-y-4",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row gap-2",children:[e.jsx(pe,{readOnly:!0,value:l?"Loading…":X,className:"font-mono text-sm",onFocus:Fe=>Fe.currentTarget.select()}),e.jsxs($,{onClick:te,disabled:!X,children:[e.jsx(Ha,{className:"h-4 w-4 mr-2"}),"Copy link"]})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[n&&e.jsxs($,{size:"sm",onClick:Ee,disabled:!X,className:"bg-primary hover:bg-primary/90",children:[e.jsx(Yr,{className:"h-4 w-4 mr-2"})," Send via Gmail"]}),e.jsxs($,{variant:"outline",size:"sm",onClick:J,disabled:!X,children:[e.jsx(mn,{className:"h-4 w-4 mr-2"})," Email"]}),e.jsxs($,{variant:"outline",size:"sm",onClick:ce,disabled:!X,children:[e.jsx(eo,{className:"h-4 w-4 mr-2"})," Text"]}),e.jsxs($,{variant:"outline",size:"sm",onClick:_e,disabled:!X,children:[e.jsx(zd,{className:"h-4 w-4 mr-2"})," More…"]})]}),!n&&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(Ne,{children:[e.jsxs(Ct,{children:[e.jsx(At,{children:"Your Referrals"}),e.jsx(Gn,{children:"Track who joined and when they upgrade."})]}),e.jsx(Ie,{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(Zn,{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(Fe=>{var je,Ae;const ke=((je=Fe.referred_profile)==null?void 0:je.name)||((Ae=Fe.referred_profile)==null?void 0:Ae.email)||"New agent",Ve=new Intl.DateTimeFormat("en-US",{timeZone:"America/New_York",month:"short",day:"numeric",year:"numeric"}).format(new Date(Fe.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:ke}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:["Joined ",Ve]})]}),Fe.status==="qualified"?e.jsxs(Be,{className:"bg-emerald-100 text-emerald-700 border-emerald-200 hover:bg-emerald-100",children:[e.jsx(qr,{className:"h-3 w-3 mr-1"})," Paid · +",u+m," pts"]}):e.jsxs(Be,{variant:"secondary",children:[e.jsx(da,{className:"h-3 w-3 mr-1"})," Signed up · +",u," pts"]})]},Fe.id)})})})]}),e.jsx(Ne,{className:"bg-muted/30",children:e.jsxs(Ie,{className:"p-6",children:[e.jsxs("h3",{className:"font-semibold mb-3 flex items-center gap-2",children:[e.jsx(Nn,{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:[u," points"]}),"."]}),e.jsxs("li",{children:["When they activate a paid plan, you earn another ",e.jsxs("strong",{className:"text-foreground",children:[m," points"]}),"."]}),e.jsxs("li",{children:["Redeem points in the ",e.jsx("a",{href:"/reward-store",className:"text-primary underline",children:"Reward Store"}),"."]})]})]})}),e.jsx(Gc,{className:"opacity-0"})]}),e.jsx(zs,{open:S,onOpenChange:C,children:e.jsxs(Os,{className:"sm:max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsxs(Us,{children:[e.jsxs(Bs,{className:"flex items-center gap-2",children:[e.jsx(Yr,{className:"h-5 w-5 text-primary"})," Send referral invites via Gmail"]}),e.jsxs(Ir,{children:["Sending from ",e.jsx("span",{className:"font-medium text-foreground",children:r}),". 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(ee,{children:"Recipients"}),e.jsxs("div",{className:"flex flex-wrap gap-1.5 p-2 border rounded-md min-h-[44px] bg-background",children:[P.map(Fe=>e.jsxs(Be,{variant:"secondary",className:"gap-1 pr-1",children:[Fe,e.jsx("button",{type:"button",onClick:()=>ve(Fe),className:"hover:bg-muted-foreground/20 rounded-full p-0.5","aria-label":`Remove ${Fe}`,children:e.jsx(gr,{className:"h-3 w-3"})})]},Fe)),e.jsx("input",{type:"email",value:E,onChange:Fe=>I(Fe.target.value),onKeyDown:Fe=>{Fe.key==="Enter"||Fe.key===","||Fe.key===" "?(Fe.preventDefault(),ue()):Fe.key==="Backspace"&&!E&&P.length>0&&R(P.slice(0,-1))},onBlur:()=>E.trim()&&ue(),onPaste:Fe=>{const ke=Fe.clipboardData.getData("text");/[\s,;]/.test(ke)&&(Fe.preventDefault(),ue(ke))},placeholder:P.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(ee,{htmlFor:"email-subject",children:"Subject"}),e.jsx(pe,{id:"email-subject",value:U,onChange:Fe=>W(Fe.target.value),placeholder:"Subject line"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"personal-note",children:"Your personal note"}),e.jsx(Rs,{id:"personal-note",value:D,onChange:Fe=>O(Fe.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(ee,{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: ",r]}),e.jsxs("span",{className:"truncate ml-2",children:["Subject: ",U||"(no subject)"]})]}),e.jsx("iframe",{title:"Email preview",srcDoc:Se(D),className:"w-full h-[420px] bg-white"})]})]})]}),e.jsxs(Ar,{children:[e.jsx($,{variant:"outline",onClick:()=>C(!1),disabled:V,children:"Cancel"}),e.jsxs($,{onClick:Le,disabled:V,children:[e.jsx(Yr,{className:"h-4 w-4 mr-2"}),V?"Sending…":`Send${P.length>0?` to ${P.length}`:""}`]})]})]})})]})}const uls=()=>{const{user:s}=vs(),t=Vt(),n=tt({queryKey:["smart-presentations",s==null?void 0:s.id],queryFn:async()=>{const{data:d,error:u}=await q.from("smart_presentations").select("*").eq("owner_user_id",s.id).neq("status","archived").order("created_at",{ascending:!1});if(u)throw u;return d||[]},enabled:!!s}),r=tt({queryKey:["smart-presentation-templates",s==null?void 0:s.id],queryFn:async()=>{const{data:d,error:u}=await q.from("smart_presentation_templates").select("*").eq("is_active",!0).order("created_at",{ascending:!0});if(u)throw u;return d||[]},enabled:!!s}),a=ft({mutationFn:async d=>{const{data:u,error:h}=await q.from("smart_presentations").insert({owner_user_id:s.id,...d}).select().single();if(h)throw h;return u},onSuccess:()=>{t.invalidateQueries({queryKey:["smart-presentations"]})}}),i=ft({mutationFn:async({id:d,...u})=>{const{data:h,error:m}=await q.from("smart_presentations").update(u).eq("id",d).select().single();if(m)throw m;return h},onSuccess:()=>{t.invalidateQueries({queryKey:["smart-presentations"]})}}),l=ft({mutationFn:async d=>{const{data:u,error:h}=await q.from("smart_presentations").update({status:"published",published_at:new Date().toISOString()}).eq("id",d).select().single();if(h)throw h;return u},onSuccess:()=>{t.invalidateQueries({queryKey:["smart-presentations"]}),re.success("Presentation published!")}}),o=ft({mutationFn:async d=>{const{error:u}=await q.from("smart_presentations").update({status:"archived"}).eq("id",d);if(u)throw u},onSuccess:()=>{t.invalidateQueries({queryKey:["smart-presentations"]}),re.success("Presentation archived")}}),c=ft({mutationFn:async d=>{const{error:u}=await q.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(u)throw u},onSuccess:()=>{t.invalidateQueries({queryKey:["smart-presentation-templates"]}),re.success("Saved as template!")}});return{presentations:n.data||[],templates:r.data||[],isLoading:n.isLoading,templatesLoading:r.isLoading,createPresentation:a,updatePresentation:i,publishPresentation:l,archivePresentation:o,saveAsTemplate:c}},thr=()=>{const s=Qn(),{presentations:t,isLoading:n,archivePresentation:r,saveAsTemplate:a}=uls(),i=o=>o.status==="draft"?e.jsx(Be,{variant:"outline",className:"text-xs",children:"Draft"}):o.view_count>1?e.jsx(Be,{className:"text-xs bg-emerald-100 text-emerald-700 border-emerald-200",children:"Revisited"}):o.view_count===1?e.jsx(Be,{className:"text-xs bg-blue-100 text-blue-700 border-blue-200",children:"Opened"}):e.jsx(Be,{variant:"secondary",className:"text-xs",children:"Not Opened"}),l=o=>{const c=`https://presentations.relevelup.com/${o}`;navigator.clipboard.writeText(c),re.success("Link copied!")};return e.jsx(Vs,{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($,{onClick:()=>s("/mission-control/presentations/new"),className:"gap-2",children:[e.jsx(dn,{className:"h-4 w-4"}),"Create Presentation"]})]}),n?e.jsx("div",{className:"space-y-3",children:[1,2,3].map(o=>e.jsx(yn,{className:"h-20 w-full rounded-lg"},o))}):t.length===0?e.jsx(Ne,{children:e.jsxs(Ie,{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(jb,{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($,{onClick:()=>s("/mission-control/presentations/new"),className:"gap-2",children:[e.jsx(dn,{className:"h-4 w-4"}),"Create Your First Presentation"]})]})}):e.jsx("div",{className:"space-y-3",children:t.map(o=>e.jsx(Ne,{className:"hover:shadow-sm transition-shadow",children:e.jsx(Ie,{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(Jr,{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 ",en(new Date(o.created_at),"MMM d, yyyy")]}),o.view_count>0&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Ca,{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($,{variant:"outline",size:"sm",onClick:()=>l(o.share_token),children:[e.jsx(Ha,{className:"h-3.5 w-3.5 mr-1"}),"Copy Link"]}),o.status==="published"&&e.jsx($,{variant:"outline",size:"sm",onClick:()=>s(`/mission-control/presentations/${o.id}?edit=true`),children:"Edit"}),e.jsx($,{variant:"outline",size:"sm",onClick:()=>s(`/mission-control/presentations/${o.id}`),children:o.status==="draft"?"Edit":"View"}),e.jsxs(Uu,{children:[e.jsx(qu,{asChild:!0,children:e.jsx($,{variant:"ghost",size:"icon",className:"h-8 w-8",children:e.jsx(ty,{className:"h-4 w-4"})})}),e.jsxs(Eu,{align:"end",children:[o.status==="published"&&o.share_token&&e.jsxs(ja,{onClick:()=>window.open(`https://presentations.relevelup.com/${o.share_token}`,"_blank"),children:[e.jsx(kr,{className:"h-4 w-4 mr-2"}),"Preview Link"]}),e.jsxs(ja,{onClick:()=>a.mutate(o),children:[e.jsx(Jr,{className:"h-4 w-4 mr-2"}),"Save as Template"]}),e.jsxs(ja,{onClick:()=>r.mutate(o.id),className:"text-destructive",children:[e.jsx(Sv,{className:"h-4 w-4 mr-2"}),"Archive"]})]})]})]})]})})]})})},o.id))})]})})},YEt={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."}]},shr=[{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 nhr(s){const t=YEt[s];if(t)return t;const n=s.toLowerCase();for(const[r,a]of Object.entries(YEt))if(n.includes(r.toLowerCase())||r.toLowerCase().includes(n))return a;return shr}function rhr({sectionTitle:s,contactId:t,onVideoReady:n}){const[r,a]=j.useState(!1),[i,l]=j.useState("script"),[o,c]=j.useState(0),[d,u]=j.useState(0),{canRecord:h}=HQt(),m=x3(),[f,g]=j.useState(""),[x,y]=j.useState(!1),[v,b]=j.useState(!0),[w,S]=j.useState(!1),[C,E]=j.useState(null),I=nhr(s),P=()=>{l("script"),c(0),u(0),g(""),y(!1),b(!0),S(!1),E(null)},R=V=>{!V&&(i==="uploading"||i==="processing")||(a(V),V||P())},D=V=>{E(V),g(I[V].text),y(!1)},O=()=>{l("record"),b(f.trim().length>0)},U=()=>{g(""),b(!1),l("record")},W=j.useCallback(async(V,G)=>{l("uploading");try{const Y=s||"Presentation Video",{videoId:X,uploadUrl:ae,libraryId:ie}=await P6(Y),{apiKey:ne}=await I6(X),te=new XMLHttpRequest;te.upload.onprogress=ue=>{ue.lengthComputable&&c(ue.loaded/ue.total*100)},await new Promise((ue,ve)=>{te.onload=()=>te.status>=200&&te.status<300?ue():ve(new Error("Upload failed")),te.onerror=()=>ve(new Error("Upload failed")),te.open("PUT",ae),te.setRequestHeader("AccessKey",ne),te.send(V)}),l("processing");let J=0;const ce=Date.now(),_e=9e4;let he=null;for(;J<4;){if(await new Promise(ve=>setTimeout(ve,3e3)),Date.now()-ce>_e){const ve=V.size/1048576,Ee=`https://iframe.mediadelivery.net/embed/${ie}/${X}?responsive=true`;await m.mutateAsync({bunny_video_id:X,playback_url:Ee,file_size_mb:ve,title:Y,contact_id:t||void 0,status:"processing",touch_type:"presentation"}),n(Ee),re.success("Video saved — still encoding. It will be ready shortly."),l("done"),setTimeout(()=>a(!1),1500);return}const ue=await gk(X);if(J=ue.status,u(ue.encodeProgress||0),J===4)he={playbackUrl:ue.directPlayUrl,thumbnailUrl:ue.thumbnailUrl,previewUrl:ue.previewUrl||null,duration:ue.length||G,fileSizeMb:(ue.storageSize||V.size)/(1024*1024)};else if(J===5||J===6)throw new Error("Video processing failed")}if(!he)throw new Error("No video data");await m.mutateAsync({bunny_video_id:X,contact_id:t||void 0,playback_url:he.playbackUrl,thumbnail_url:he.thumbnailUrl,preview_url:he.previewUrl,duration_seconds:he.duration,file_size_mb:he.fileSizeMb,title:Y,status:"ready",touch_type:"presentation"}),n(he.playbackUrl),re.success("Video recorded, saved to library & attached!"),l("done"),setTimeout(()=>a(!1),1500)}catch(Y){console.error("Recording upload error:",Y),re.error("Failed to process video. Please try again."),l("record")}},[s,t,n,m]);return e.jsxs(zs,{open:r,onOpenChange:R,children:[e.jsx(jl,{asChild:!0,children:e.jsxs($,{variant:"outline",size:"sm",className:"gap-1.5 shrink-0",title:"Record a video",children:[e.jsx(ua,{className:"h-3.5 w-3.5"}),"Record"]})}),e.jsxs(Os,{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(Us,{children:e.jsxs(Bs,{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:I.map((V,G)=>e.jsxs("button",{onClick:()=>D(G),className:Pt("text-left p-3 rounded-lg border transition-all hover:bg-accent/50",C===G?"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(Jr,{className:"h-3.5 w-3.5 text-primary shrink-0"}),e.jsx("span",{className:"text-sm font-medium",children:V.label})]}),e.jsx("p",{className:"text-xs text-muted-foreground line-clamp-2 ml-5.5",children:V.text})]},G))})]}),f&&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"}),!x&&e.jsxs($,{variant:"ghost",size:"sm",onClick:()=>y(!0),className:"h-7 text-xs gap-1",children:[e.jsx(gi,{className:"h-3 w-3"}),"Edit"]})]}),x?e.jsx(Rs,{value:f,onChange:V=>g(V.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:f})]}),!f&&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(Rs,{value:f,onChange:V=>{g(V.target.value),E(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($,{variant:"ghost",size:"sm",onClick:U,className:"text-muted-foreground",children:"Skip — no teleprompter"}),e.jsx($,{onClick:O,disabled:!1,children:f.trim()?"Continue with Script":"Continue Without Script"})]})]}),!h&&i==="record"?e.jsxs("div",{className:"flex flex-col items-center gap-3 py-8 text-center",children:[e.jsx(wl,{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."}),f.trim()&&e.jsxs($,{variant:"ghost",size:"sm",onClick:()=>b(!v),className:"h-7 text-xs gap-1",children:[v?e.jsx($g,{className:"h-3 w-3"}):e.jsx(Ca,{className:"h-3 w-3"}),v?"Hide Script":"Show Script"]})]}),e.jsx(BT,{maxDurationSeconds:600,onRecordingComplete:W,onRecordingStateChange:S,onError:V=>re.error(V),teleprompterContent:f.trim()?e.jsx(Jot,{text:f,isVisible:v,onToggleVisibility:()=>b(!v),isRecording:w,startCountdown:!1}):void 0}),e.jsx($,{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(kt,{className:"h-10 w-10 animate-spin text-primary"}),e.jsxs("div",{className:"w-full max-w-xs space-y-2",children:[e.jsx(Yi,{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(kt,{className:"h-10 w-10 animate-spin text-primary"}),e.jsxs("div",{className:"w-full max-w-xs space-y-2",children:[e.jsx(Yi,{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(Nc,{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 ahr({sectionTitle:s,contactId:t,onVideoReady:n}){const[r,a]=j.useState(!1),[i,l]=j.useState(null),[o,c]=j.useState("idle"),[d,u]=j.useState(0),h=j.useRef(null),m=x3(),{data:f}=hDe(),g=(f==null?void 0:f.total_storage_mb)||0,y=((f==null?void 0:f.max_storage_mb)||1024)-g,v=()=>{l(null),c("idle"),u(0)},b=I=>{!I&&o!=="idle"&&o!=="done"||(a(I),I||v())},w=I=>{var D;const P=(D=I.target.files)==null?void 0:D[0];if(!P)return;if(!P.type.startsWith("video/")){re.error("Please select a video file");return}const R=P.size/(1024*1024);if(R>500){re.error("Video file must be less than 500MB");return}if(R>y){re.error(`Not enough storage. You have ${y.toFixed(1)} MB remaining.`);return}l(P)},S=j.useCallback(async()=>{if(i){c("creating"),u(0);try{const I=s||i.name,{data:P,error:R}=await q.functions.invoke("bunny-upload",{body:{action:"create",title:I,isAgentVideo:!0}});if(R)throw new Error(R.message);const{videoId:D,libraryId:O}=P;c("uploading");const{data:U,error:W}=await q.functions.invoke("bunny-upload",{body:{action:"upload-url",videoId:D,isAgentVideo:!0}});if(W)throw new Error(W.message);await new Promise((Y,X)=>{const ae=new XMLHttpRequest;ae.upload.addEventListener("progress",ie=>{ie.lengthComputable&&u(Math.round(ie.loaded/ie.total*100))}),ae.addEventListener("load",()=>ae.status>=200&&ae.status<300?Y():X(new Error(`Upload failed (${ae.status})`))),ae.addEventListener("error",()=>X(new Error("Upload failed"))),ae.open("PUT",U.uploadUrl),ae.setRequestHeader("AccessKey",U.apiKey),ae.send(i)}),c("processing");const V=i.size/(1024*1024),G=`https://iframe.mediadelivery.net/embed/${O}/${D}`;await m.mutateAsync({bunny_video_id:D,playback_url:G,file_size_mb:V,title:I,contact_id:t||void 0,status:"processing",touch_type:"presentation"}),n(G),c("done"),re.success("Video uploaded & attached to section!"),setTimeout(()=>a(!1),1200)}catch(I){console.error("Upload error:",I),re.error(I instanceof Error?I.message:"Failed to upload video"),c("idle")}}},[i,s,t,n,m]),C=()=>{switch(o){case"creating":return"Preparing upload...";case"uploading":return`Uploading... ${d}%`;case"processing":return"Saving video...";case"done":return"Done!";default:return""}},E=o!=="idle"&&o!=="done";return e.jsxs(zs,{open:r,onOpenChange:b,children:[e.jsx(jl,{asChild:!0,children:e.jsxs($,{variant:"outline",size:"sm",className:"gap-1.5 shrink-0",title:"Upload a video file",children:[e.jsx(ni,{className:"h-3.5 w-3.5"}),"Upload"]})}),e.jsxs(Os,{className:"sm:max-w-md",children:[e.jsx(Us,{children:e.jsxs(Bs,{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(ua,{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"]})]}),!E&&e.jsx($,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>l(null),children:e.jsx(gr,{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 I;return(I=h.current)==null?void 0:I.click()},children:[e.jsx(ni,{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:h,type:"file",accept:"video/*",className:"hidden",onChange:w,disabled:E}),E&&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(kt,{className:"h-4 w-4 animate-spin"}),e.jsx("span",{children:C()})]}),e.jsx(Yi,{value:o==="uploading"?d:o==="processing"?100:10})]})]}),e.jsxs(Ar,{children:[e.jsx($,{variant:"outline",onClick:()=>b(!1),disabled:E,children:"Cancel"}),e.jsx($,{onClick:S,disabled:!i||E,children:E?e.jsxs(e.Fragment,{children:[e.jsx(kt,{className:"h-4 w-4 mr-2 animate-spin"}),"Uploading..."]}):e.jsxs(e.Fragment,{children:[e.jsx(ni,{className:"h-4 w-4 mr-2"}),"Upload & Attach"]})})]})]})]})}const ZEt=[{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"}],XEt=()=>{const s=Qn(),{id:t}=Wi(),{user:n}=vs(),{templates:r,templatesLoading:a,createPresentation:i,updatePresentation:l,publishPresentation:o}=uls(),{isGmailConnected:c,gmailEmail:d}=yy(),[u,h]=j.useState(!1),[m,f]=j.useState("client"),[g,x]=j.useState(!1),[y,v]=j.useState(""),[b,w]=j.useState([]),[S,C]=j.useState(!1),[E,I]=j.useState(null),[P,R]=j.useState(!1),[D,O]=j.useState(""),[U,W]=j.useState(""),[V,G]=j.useState(""),[Y,X]=j.useState("buyer"),[ae,ie]=j.useState(""),[ne,te]=j.useState(null),[J,ce]=j.useState(""),[_e,he]=j.useState([]),[ue,ve]=j.useState("schedule_call"),[Ee,Se]=j.useState("Schedule a Call"),[Le,Fe]=j.useState(""),[ke,Ve]=j.useState(""),[je,Ae]=j.useState(null),[Ce,qe]=j.useState(t||null),[ze,$e]=j.useState(null),[ct,Xe]=j.useState(!1),it=async(St,Xs)=>{if(!n)return;const vt=5*1024*1024;if(St.size>vt){re.error("Image must be under 5MB");return}if(!St.type.startsWith("image/")){re.error("Please upload an image file");return}Ae(Xs);try{const gs=St.name.split(".").pop()||"jpg",Ss=`${n.id}/${Date.now()}.${gs}`,{error:Is}=await q.storage.from("listing-photos").upload(Ss,St);if(Is)throw Is;const{data:{publicUrl:Ys}}=q.storage.from("listing-photos").getPublicUrl(Ss);Yt(Xs,{image_url:Ys}),re.success("Image uploaded")}catch{re.error("Failed to upload image")}finally{Ae(null)}};j.useEffect(()=>{t&&at(t)},[t]);const at=async St=>{const{data:Xs,error:vt}=await q.from("smart_presentations").select("*").eq("id",St).single();if(vt||!Xs)return;const gs=Xs;if(x(!0),ce(gs.title),O(gs.client_name||""),ie(gs.property_address||""),he(gs.sections||[]),ve(gs.cta_type||"schedule_call"),Se(gs.cta_label||"Schedule a Call"),Fe(gs.cta_url||""),Ve(gs.heading||""),$e(gs.share_token),Xe(gs.status==="published"),qe(gs.id),f("builder"),gs.contact_id){const{data:Ss}=await q.from("innercircle_contacts").select("id, first_name, last_name, email, phone").eq("id",gs.contact_id).maybeSingle();Ss&&(I(Ss),W(Ss.email||""),G(Ss.phone||""))}};j.useEffect(()=>{if(!n||y.length<1){w([]);return}const St=setTimeout(async()=>{C(!0);const{data:Xs}=await q.from("innercircle_contacts").select("id, first_name, last_name, email, phone, lead_source").eq("owner_user_id",n.id).or(`first_name.ilike.%${y}%,last_name.ilike.%${y}%,email.ilike.%${y}%`).limit(10);w(Xs||[]),C(!1)},300);return()=>clearTimeout(St)},[y,n]);const Ke=St=>{I(St),O(`${St.first_name} ${St.last_name||""}`.trim()),W(St.email||""),G(St.phone||""),R(!1)},nt=async()=>{if(!D.trim()){re.error("Client name is required");return}const St=D.trim().split(" "),Xs=St[0],vt=St.slice(1).join(" ")||null,{data:gs,error:Ss}=await q.from("innercircle_contacts").insert({owner_user_id:n.id,first_name:Xs,last_name:vt,email:U||null,phone:V||null,lead_source:"Smart Presentation"}).select().single();if(Ss){re.error("Failed to create client");return}I(gs),re.success("Client created & saved to Agent OS"),f("template")},xt=St=>{te(St);const Xs=(St.sections||[]).map(vt=>({...vt,is_visible:!0,video_url:"",text:""}));if(he(Xs),ce(St.name+(D?` for ${D}`:"")),St.cta_config){const vt=St.cta_config;ve(vt.type||"schedule_call"),Se(vt.label||"Schedule a Call")}f("builder")},rt=()=>{he([{title:"Welcome",description:"A personal welcome",type:"video",icon:"👋",is_visible:!0}]),ce(D?`Presentation for ${D}`:"New Presentation"),f("builder")},Yt=(St,Xs)=>{he(vt=>vt.map((gs,Ss)=>Ss===St?{...gs,...Xs}:gs))},qt=St=>{Yt(St,{is_visible:!_e[St].is_visible})},ts=()=>{he(St=>[...St,{title:"New Section",description:"",type:"video",icon:"📝",is_visible:!0}])},ys=St=>{he(Xs=>Xs.filter((vt,gs)=>gs!==St))},Bt=async()=>{if(!J.trim()){re.error("Title is required");return}try{if(Ce){const St=await l.mutateAsync({id:Ce,title:J,sections:_e,client_name:D,property_address:ae||null,cta_type:ue,cta_label:Ee,cta_url:Le||null,heading:ke||null});re.success("Saved")}else{const St=await i.mutateAsync({title:J,contact_id:(E==null?void 0:E.id)||void 0,client_name:D,property_address:ae||void 0,template_id:(ne==null?void 0:ne.id)||void 0,sections:_e,cta_type:ue,cta_label:Ee,cta_url:Le||void 0,heading:ke||void 0});qe(St.id),$e(St.share_token),re.success("Presentation created!")}}catch(St){console.error("Failed to save presentation:",St);const Xs=(St==null?void 0:St.message)||(St==null?void 0:St.toString())||"Unknown error";re.error(`Failed to save: ${Xs}`)}},Ft=async()=>{try{await Bt();const St=Ce;if(St){const Xs=await o.mutateAsync(St);$e(Xs.share_token),Xe(!0),f("share")}}catch(St){console.error("Failed to publish presentation:",St),re.error(`Failed to publish: ${(St==null?void 0:St.message)||"Unknown error"}`)}},rs=ze?`https://presentations.relevelup.com/${ze}`:"";return e.jsx(Vs,{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($,{variant:"ghost",size:"icon",onClick:()=>s("/mission-control/presentations"),children:e.jsx(qa,{className:"h-4 w-4"})}),e.jsxs("div",{children:[e.jsx("h1",{className:"text-xl font-serif font-bold text-foreground",children:g?"Edit Presentation":"Create Smart Presentation"}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[m==="client"&&"Who is this presentation for?",m==="template"&&"Choose a starting template",m==="builder"&&"Customize your presentation",m==="share"&&"Share with your client"]})]})]}),!g&&e.jsx("div",{className:"flex items-center gap-2",children:["client","template","builder","share"].map((St,Xs)=>e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:Pt("w-8 h-8 rounded-full flex items-center justify-center text-sm font-medium transition-colors",m===St?"bg-primary text-primary-foreground":Xs<["client","template","builder","share"].indexOf(m)?"bg-emerald-100 text-emerald-700":"bg-muted text-muted-foreground"),children:Xs<["client","template","builder","share"].indexOf(m)?e.jsx(la,{className:"h-4 w-4"}):Xs+1}),e.jsx("span",{className:"text-sm font-medium capitalize hidden sm:inline",children:St}),Xs<3&&e.jsx("div",{className:"w-8 h-px bg-border"})]},St))}),m==="client"&&e.jsxs("div",{className:"space-y-6",children:[e.jsxs("button",{onClick:()=>{I(null),O(""),W(""),G(""),R(!1),f("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(Yr,{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(ei,{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(Ne,{children:[e.jsx(Ct,{className:"pb-3",children:e.jsxs(At,{className:"text-base flex items-center gap-2",children:[e.jsx(Kr,{className:"h-4 w-4 text-muted-foreground"}),"Select Existing Client"]})}),e.jsxs(Ie,{className:"space-y-3",children:[e.jsxs("div",{className:"relative",children:[e.jsx(Kr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(pe,{placeholder:"Search by name or email...",value:y,onChange:St=>v(St.target.value),className:"pl-10"})]}),e.jsxs("div",{className:"space-y-2 max-h-56 overflow-y-auto",children:[S&&e.jsx(yn,{className:"h-12 w-full"}),b.map(St=>e.jsxs("button",{onClick:()=>Ke(St),className:Pt("w-full text-left p-3 rounded-lg border transition-colors",(E==null?void 0:E.id)===St.id?"border-primary bg-primary/5":"border-border hover:border-primary/50"),children:[e.jsxs("p",{className:"font-medium text-sm",children:[St.first_name," ",St.last_name]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:St.email||St.phone||"No contact info"})]},St.id)),!y&&e.jsx("p",{className:"text-sm text-muted-foreground text-center py-6",children:"Start typing to search your contacts"}),y&&b.length===0&&!S&&e.jsx("p",{className:"text-sm text-muted-foreground text-center py-6",children:"No clients found"})]}),E&&e.jsxs($,{onClick:()=>f("template"),className:"w-full gap-2",children:["Continue with ",E.first_name,e.jsx(ei,{className:"h-4 w-4"})]})]})]}),e.jsxs(Ne,{children:[e.jsx(Ct,{className:"pb-3",children:e.jsxs(At,{className:"text-base flex items-center gap-2",children:[e.jsx(sc,{className:"h-4 w-4 text-muted-foreground"}),"Add New Client"]})}),e.jsxs(Ie,{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(ee,{className:"text-xs",children:"Name *"}),e.jsx(pe,{value:D,onChange:St=>{O(St.target.value),R(!0),I(null)},placeholder:"Sarah & Mike Johnson"})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs",children:"Email"}),e.jsx(pe,{value:U,onChange:St=>W(St.target.value),placeholder:"Optional",type:"email"})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs",children:"Phone"}),e.jsx(pe,{value:V,onChange:St=>G(St.target.value),placeholder:"Optional"})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs",children:"Client Type"}),e.jsxs(ms,{value:Y,onValueChange:X,children:[e.jsx(us,{children:e.jsx(fs,{})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"buyer",children:"Buyer"}),e.jsx(Ge,{value:"seller",children:"Seller"}),e.jsx(Ge,{value:"recruit",children:"Recruit"}),e.jsx(Ge,{value:"other",children:"Other"})]})]})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs",children:"Property Address"}),e.jsx(pe,{value:ae,onChange:St=>ie(St.target.value),placeholder:"Optional"})]})]}),P&&D&&e.jsxs($,{onClick:nt,className:"w-full gap-2",children:["Create Client & Continue",e.jsx(ei,{className:"h-4 w-4"})]})]})]})]})]}),m==="template"&&e.jsxs("div",{className:"space-y-6",children:[e.jsxs(ha,{defaultValue:"system",children:[e.jsxs(ma,{children:[e.jsx(Zt,{value:"mine",children:"My Core Templates"}),e.jsx(Zt,{value:"system",children:"LevelUp Smart Templates"}),e.jsx(Zt,{value:"blank",children:"+ Start Blank"})]}),e.jsx(Xt,{value:"mine",className:"mt-4",children:a?e.jsx("div",{className:"grid grid-cols-2 gap-4",children:[1,2].map(St=>e.jsx(yn,{className:"h-32"},St))}):e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:r.filter(St=>!St.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!"}):r.filter(St=>!St.is_system).map(St=>e.jsx(QEt,{template:St,onSelect:xt},St.id))})}),e.jsx(Xt,{value:"system",className:"mt-4",children:e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:r.filter(St=>St.is_system).map(St=>e.jsx(QEt,{template:St,onSelect:xt},St.id))})}),e.jsx(Xt,{value:"blank",className:"mt-4",children:e.jsx(Ne,{children:e.jsxs(Ie,{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($,{onClick:rt,children:"Start from Scratch"})]})})})]}),e.jsxs($,{variant:"outline",onClick:()=>f("client"),className:"gap-2",children:[e.jsx(qa,{className:"h-4 w-4"}),"Back"]})]}),m==="builder"&&e.jsxs("div",{className:"space-y-6",children:[e.jsx(Ne,{children:e.jsxs(Ie,{className:"pt-6 space-y-4",children:[e.jsxs("div",{children:[e.jsx(ee,{children:"Presentation Title"}),e.jsx(pe,{value:J,onChange:St=>ce(St.target.value)})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Page Heading"}),e.jsx(pe,{value:ke,onChange:St=>Ve(St.target.value),placeholder:D?`Welcome, ${D}!`:"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(ee,{children:"Client Name"}),e.jsx(pe,{value:D,onChange:St=>O(St.target.value)})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Property Address"}),e.jsx(pe,{value:ae,onChange:St=>ie(St.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($,{variant:"outline",size:"sm",onClick:ts,children:"+ Add Section"})]}),e.jsx("div",{className:"space-y-3",children:_e.map((St,Xs)=>e.jsx(Ne,{className:Pt(!St.is_visible&&"opacity-50"),children:e.jsx(Ie,{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(Ug,{className:"h-4 w-4 text-muted-foreground cursor-grab"}),e.jsx("span",{className:"text-lg",children:St.icon})]}),e.jsxs("div",{className:"flex-1 space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(pe,{value:St.title,onChange:vt=>Yt(Xs,{title:vt.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($,{variant:"ghost",size:"icon",onClick:()=>qt(Xs),children:St.is_visible?e.jsx(Ca,{className:"h-4 w-4"}):e.jsx($g,{className:"h-4 w-4"})}),e.jsx($,{variant:"ghost",size:"icon",onClick:()=>ys(Xs),className:"text-destructive hover:text-destructive",children:e.jsx(Wn,{className:"h-4 w-4"})})]})]}),e.jsx(pe,{value:St.description||"",onChange:vt=>Yt(Xs,{description:vt.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(ee,{className:"text-xs",children:"Video URL"}),e.jsx(pe,{value:St.video_url||"",onChange:vt=>Yt(Xs,{video_url:vt.target.value}),placeholder:"Paste a YouTube or video URL...",className:"text-sm"})]}),e.jsx(rhr,{sectionTitle:St.title,contactId:E==null?void 0:E.id,onVideoReady:vt=>Yt(Xs,{video_url:vt})}),e.jsx(ahr,{sectionTitle:St.title,contactId:E==null?void 0:E.id,onVideoReady:vt=>Yt(Xs,{video_url:vt})}),e.jsx(o9,{userId:n==null?void 0:n.id,onSelect:vt=>Yt(Xs,{video_url:vt})})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs",children:"Image (optional — shown if no video is set)"}),St.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:St.image_url,alt:"",className:"w-full max-h-40 object-cover"}),e.jsx($,{variant:"destructive",size:"icon",className:"absolute top-2 right-2 h-7 w-7 opacity-0 group-hover:opacity-100 transition-opacity",onClick:()=>Yt(Xs,{image_url:""}),children:e.jsx(gr,{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:[je===Xs?e.jsx(kt,{className:"h-4 w-4 animate-spin text-muted-foreground"}):e.jsx(Av,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:je===Xs?"Uploading...":"Click to upload an image"}),e.jsx("input",{type:"file",accept:"image/*",className:"hidden",disabled:je===Xs,onChange:vt=>{var Ss;const gs=(Ss=vt.target.files)==null?void 0:Ss[0];gs&&it(gs,Xs),vt.target.value=""}})]})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs",children:"Text (optional)"}),e.jsx(Ek,{content:St.text||"",onChange:vt=>Yt(Xs,{text:vt}),placeholder:"Add supporting text...",minHeight:"80px",compact:!0})]})]})]})})},Xs))})]}),e.jsxs(Ne,{children:[e.jsx(Ct,{children:e.jsx(At,{className:"text-base",children:"Call to Action"})}),e.jsxs(Ie,{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(ee,{children:"CTA Type"}),e.jsxs(ms,{value:ue,onValueChange:St=>{ve(St);const Xs=ZEt.find(vt=>vt.value===St);Xs&&Se(Xs.label)},children:[e.jsx(us,{children:e.jsx(fs,{})}),e.jsx(hs,{children:ZEt.map(St=>e.jsx(Ge,{value:St.value,children:St.label},St.value))})]})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Button Label"}),e.jsx(pe,{value:Ee,onChange:St=>Se(St.target.value)})]}),e.jsxs("div",{children:[e.jsxs(ee,{children:["Link URL ",e.jsx("span",{className:"text-muted-foreground",children:"(optional — leave blank to show a lead capture form instead)"})]}),e.jsx(pe,{value:Le,onChange:St=>Fe(St.target.value),placeholder:"https://calendly.com/..."}),!Le&&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:[!g&&e.jsxs($,{variant:"outline",onClick:()=>f("template"),className:"gap-2",children:[e.jsx(qa,{className:"h-4 w-4"}),"Back"]}),e.jsxs("div",{className:"flex gap-3 ml-auto",children:[e.jsx($,{variant:"outline",onClick:Bt,disabled:i.isPending||l.isPending,children:"Save Draft"}),e.jsxs($,{onClick:Ft,disabled:o.isPending,className:"gap-2",children:[e.jsx(Yr,{className:"h-4 w-4"}),ct?"Update & Reshare":"Publish & Share"]})]})]})]}),m==="share"&&ze&&e.jsxs("div",{className:"space-y-6",children:[e.jsx(Ne,{children:e.jsxs(Ie,{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(la,{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 ",D||"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(pe,{value:rs,readOnly:!0,className:"text-center font-mono text-sm"}),e.jsx($,{onClick:()=>{navigator.clipboard.writeText(rs),re.success("Link copied!")},children:e.jsx(Ha,{className:"h-4 w-4"})})]}),e.jsxs("div",{className:"flex gap-3 mt-6",children:[e.jsxs($,{variant:"outline",className:"gap-2",onClick:()=>{const St=`Hi ${D||""}! I put together something for you — check it out: ${rs}`;navigator.clipboard.writeText(St),re.success("Message copied!")},children:[e.jsx(eo,{className:"h-4 w-4"}),"Copy Text Message"]}),e.jsxs($,{variant:"outline",className:"gap-2",onClick:()=>{c?h(!0):window.open(`mailto:${U||""}?subject=${encodeURIComponent(J)}&body=${encodeURIComponent(`Hi ${(E==null?void 0:E.first_name)||(D==null?void 0:D.split(" ")[0])||""}, I put together a personalized presentation for you: ${rs} Looking forward to connecting!`)}`)},children:[e.jsx(mn,{className:"h-4 w-4"}),"Send Email"]})]}),c&&e.jsx(Ak,{open:u,onOpenChange:h,contact:E?{id:E.id,first_name:E.first_name,last_name:E.last_name,email:U||E.email||""}:U?{id:"",first_name:(D==null?void 0:D.split(" ")[0])||"",last_name:(D==null?void 0:D.split(" ").slice(1).join(" "))||"",email:U}:void 0,defaultSubject:J,defaultBody:`Hi ${(E==null?void 0:E.first_name)||(D==null?void 0:D.split(" ")[0])||""}, I put together a personalized presentation for you: ${rs} Looking forward to connecting!`,gmailEmail:d})]})}),e.jsxs("div",{className:"flex justify-between",children:[e.jsxs($,{variant:"outline",onClick:()=>f("builder"),children:[e.jsx(qa,{className:"h-4 w-4 mr-2"}),"Edit Presentation"]}),e.jsx($,{onClick:()=>s("/mission-control/presentations"),children:"Done"})]})]})]})})},QEt=({template:s,onSelect:t})=>e.jsx(Ne,{className:"hover:shadow-sm transition-shadow",children:e.jsxs(Ie,{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(Be,{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($,{className:"w-full mt-4",size:"sm",onClick:()=>t(s),children:"Use Template"})]})}),ihr=()=>{var x;const{shareToken:s}=Wi(),[t,n]=j.useState(null),[r,a]=j.useState(!0),[i,l]=j.useState(0),[o,c]=j.useState(!1);j.useEffect(()=>(document.body.classList.add("presentation-page"),()=>{document.body.classList.remove("presentation-page")}),[]),j.useEffect(()=>{s&&d()},[s]);const d=async()=>{const{data:y,error:v}=await q.from("smart_presentations").select("*").eq("share_token",s).eq("status","published").single();if(v||!y){c(!0),a(!1);return}const{data:b}=await q.from("profiles").select("name, email, phone, avatar_url, title, brokerage_id").eq("id",y.owner_user_id).single();let w;if(b!=null&&b.brokerage_id){const{data:C}=await q.from("brokerages").select("name").eq("id",b.brokerage_id).single();w=(C==null?void 0:C.name)||void 0}let S=null;if(y.contact_id){const{data:C}=await q.from("innercircle_contacts").select("first_name, last_name, email, phone").eq("id",y.contact_id).single();S=C}n({...y,owner_name:b==null?void 0:b.name,owner_email:b==null?void 0:b.email,owner_phone:b==null?void 0:b.phone,owner_avatar:b==null?void 0:b.avatar_url,owner_title:(b==null?void 0:b.title)||void 0,brokerage_name:w,contact_name:S?[S.first_name,S.last_name].filter(Boolean).join(" "):void 0,contact_email:(S==null?void 0:S.email)||void 0,contact_phone:(S==null?void 0:S.phone)||void 0}),a(!1);try{await q.rpc("log_presentation_view",{p_presentation_id:y.id,p_section_index:0,p_cta_clicked:!1,p_ip_hash:null,p_user_agent:navigator.userAgent,p_referrer:document.referrer||null})}catch{}},u=async()=>{if(t){try{await q.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(r)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(yn,{className:"h-12 w-3/4 mx-auto"}),e.jsx(yn,{className:"h-64 w-full"}),e.jsx(yn,{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 h=t.sections.filter(y=>y.is_visible!==!1),m=h[i],f=y=>{const v=y.match(/(?:youtube\.com\/watch\?v=|youtu\.be\/)([a-zA-Z0-9_-]+)/);if(v)return`https://www.youtube.com/embed/${v[1]}?rel=0`;if(y.includes("iframe.mediadelivery.net/play/")){const S=y.replace("/play/","/embed/"),C=S.includes("?")?"&":"?";return`${S}${C}responsive=true`}if(y.includes("iframe.mediadelivery.net")){if(y.match(/\/embed\/(\d+)\/([a-f0-9-]+)/)){const C=y.includes("?")?"&":"?";return`${y}${C}responsive=true`}return""}const b=y.match(/loom\.com\/share\/([a-zA-Z0-9]+)/);if(b)return`https://www.loom.com/embed/${b[1]}`;const w=y.match(/video\.bunnycdn\.com\/play\/(\d+)\/([a-f0-9-]+)/);return w?`https://iframe.mediadelivery.net/embed/${w[1]}/${w[2]}?responsive=true`:y},g=!!((x=t.cta_url)!=null&&x.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:[m!=null&&m.video_url&&f(m.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:f(m.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"})}):m!=null&&m.image_url?e.jsx("div",{className:"rounded-xl overflow-hidden shadow-lg",children:e.jsx("img",{src:m.image_url,alt:m.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:m==null?void 0:m.icon}),e.jsx("h3",{className:"text-xl font-semibold text-gray-800",children:m==null?void 0:m.title}),e.jsx("p",{className:"text-gray-500 mt-1 text-sm",children:m==null?void 0:m.description})]}),(m==null?void 0:m.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:m.text}})]}),e.jsx("div",{className:"md:col-span-2 space-y-3",children:h.map((y,v)=>e.jsx("button",{onClick:()=>l(v),className:Pt("w-full text-left p-4 rounded-xl border transition-all",i===v?"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(v+1).padStart(2,"0"),"."]}),e.jsxs("div",{children:[e.jsx("span",{className:"mr-2",children:y.icon}),e.jsx("span",{className:"font-semibold text-gray-900",children:y.title}),e.jsx("p",{className:"text-xs text-gray-500 mt-0.5",children:y.description})]})]})},v))})]}),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?"}),g?e.jsxs($,{size:"lg",onClick:u,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(kr,{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(J7t,{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"})]})},CUe="__none__";function ohr({value:s,onChange:t}){const{data:n=[],isLoading:r}=Fie(),a=jit(),[i,l]=j.useState(!1),o=j.useMemo(()=>n.filter(h=>!h.is_starter),[n]),c=j.useMemo(()=>n.find(h=>h.is_starter&&/open house/i.test(h.name||"")),[n]),d=j.useMemo(()=>o.some(h=>/open house/i.test(h.name||"")),[o]),u=async()=>{if(c){l(!0);try{const h=await a.mutateAsync(c.id);h!=null&&h.id&&t(h.id),_a({title:"Open House Follow-Up added",description:"The 6-email sequence is now in your library and selected here."})}catch(h){_a({title:"Could not add campaign",description:(h==null?void 0:h.message)??"Please try again.",variant:"destructive"})}finally{l(!1)}}};return e.jsxs("div",{className:"space-y-2 rounded-lg border bg-muted/20 p-3",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"space-y-0.5",children:[e.jsxs(ee,{className:"text-sm font-medium flex items-center gap-2",children:[e.jsx(tL,{className:"h-4 w-4 text-emerald-600"}),"Auto follow-up campaign"]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Everyone who signs in with an email is automatically enrolled."})]}),s&&e.jsx(Be,{variant:"outline",className:"text-[10px] border-emerald-300 bg-emerald-500/10 text-emerald-700",children:"On"})]}),e.jsxs(ms,{value:s??CUe,onValueChange:h=>t(h===CUe?null:h),disabled:r,children:[e.jsx(us,{children:e.jsx(fs,{placeholder:"No follow-up campaign"})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:CUe,children:"No follow-up campaign"}),o.map(h=>e.jsxs(Ge,{value:h.id,children:[h.icon?`${h.icon} `:"",h.name,h.is_active?"":" (paused)"]},h.id))]})]}),c&&!d&&e.jsxs($,{type:"button",variant:"outline",size:"sm",className:"w-full gap-1.5 text-xs",onClick:u,disabled:i,children:[i?e.jsx(kt,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(Nn,{className:"h-3.5 w-3.5 text-primary"}),'Add the "Open House Follow-Up" starter (6 emails)']}),o.length===0&&!c&&e.jsx("p",{className:"text-xs text-muted-foreground",children:"Create a campaign in Smart Drips first, then choose it here."})]})}function lhr({openHouseId:s,enableSurvey:t,onToggleSurvey:n}){const{data:r,isLoading:a}=SFs(s),i=TFs(),l=MFs(),o=PFs(),c=IFs(),[d,u]=j.useState(""),[h,m]=j.useState("rating"),f=async v=>{n(v),v&&(!r||r.length===0)&&await c.mutateAsync(s)},g=async()=>{if(!d.trim())return;const v=(r==null?void 0:r.reduce((b,w)=>Math.max(b,w.sort_order),0))??0;await i.mutateAsync({open_house_id:s,question_type:h,question_text:d.trim(),sort_order:v+1}),u("")},x=async v=>{await l.mutateAsync({id:v.id,open_house_id:s,is_active:!v.is_active})},y=async v=>{await o.mutateAsync({id:v.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(ee,{className:"text-sm font-medium flex items-center gap-2",children:[e.jsx(zg,{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(Sn,{checked:t,onCheckedChange:f})]}),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(kt,{className:"h-4 w-4 animate-spin text-muted-foreground"})}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"space-y-2",children:r==null?void 0:r.map(v=>e.jsxs("div",{className:"flex items-center gap-2 p-2 rounded-lg border border-border bg-muted/20",children:[e.jsx(Ug,{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:v.question_text}),e.jsx("p",{className:"text-xs text-muted-foreground capitalize",children:v.question_type.replace("_"," ")})]}),e.jsx(Sn,{checked:v.is_active,onCheckedChange:()=>x(v),className:"scale-75"}),e.jsx($,{variant:"ghost",size:"icon",className:"h-7 w-7 shrink-0 text-muted-foreground hover:text-destructive",onClick:()=>y(v),children:e.jsx(Wn,{className:"h-3.5 w-3.5"})})]},v.id))}),e.jsxs("div",{className:"flex items-end gap-2",children:[e.jsxs("div",{className:"flex-1",children:[e.jsx(ee,{className:"text-xs text-muted-foreground",children:"Add Question"}),e.jsx(pe,{value:d,onChange:v=>u(v.target.value),placeholder:"e.g. How did you hear about this listing?",className:"mt-1 h-9 text-sm",onKeyDown:v=>v.key==="Enter"&&g()})]}),e.jsxs(ms,{value:h,onValueChange:m,children:[e.jsx(us,{className:"w-28 h-9 text-xs",children:e.jsx(fs,{})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"rating",children:"Rating"}),e.jsx(Ge,{value:"open_text",children:"Text"})]})]}),e.jsx($,{size:"sm",variant:"outline",onClick:g,disabled:!d.trim()||i.isPending,className:"h-9",children:e.jsx(dn,{className:"h-3.5 w-3.5"})})]})]})})]})}function chr({openHouseId:s}){const{user:t}=vs(),{data:n=[],isLoading:r}=FFs(s),a=zFs(),i=VFs(),l=(m,f)=>{const g=m+f;if(g<0||g>=n.length)return;const x=n.map(y=>y.id);[x[m],x[g]]=[x[g],x[m]],i.mutate({open_house_id:s,orderedIds:x})},[o,c]=j.useState(""),[d,u]=j.useState(!1),h=async()=>{const m=o.trim();if(m){u(!0);try{await a.mutateAsync({open_house_id:s,name:m,sort_order:n.length}),c("")}finally{u(!1)}}};return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(ee,{className:"text-sm font-medium",children:"Rooms"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Add rooms and upload photos or videos (or pull a clip from your Video Library). Use the up/down arrows to reorder rooms and the arrows on each tile to reorder photos and videos. Visitors swipe through them on mobile and tab through them on desktop."})]}),r?e.jsxs("div",{className:"py-6 text-center text-sm text-muted-foreground",children:[e.jsx(kt,{className:"h-4 w-4 animate-spin inline"})," Loading…"]}):n.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:n.map((m,f)=>e.jsx(dhr,{room:m,index:f,total:n.length,userId:(t==null?void 0:t.id)||"",openHouseId:s,onMoveRoom:l},m.id))}),e.jsxs("div",{className:"flex gap-2 pt-2",children:[e.jsx(pe,{value:o,onChange:m=>c(m.target.value),placeholder:"e.g. Kitchen, Primary Bedroom, Backyard…",onKeyDown:m=>{m.key==="Enter"&&(m.preventDefault(),h())}}),e.jsx($,{onClick:h,disabled:!o.trim()||d,size:"sm",children:d?e.jsx(kt,{className:"h-4 w-4 animate-spin"}):e.jsxs(e.Fragment,{children:[e.jsx(dn,{className:"h-4 w-4 mr-1"})," Add"]})})]})]})}function dhr({room:s,index:t,total:n,userId:r,openHouseId:a,onMoveRoom:i}){const l=BFs(),o=$Fs(),c=UFs(),d=qFs(),u=HFs(),h=j.useRef(null),[m,f]=j.useState(!0),[g,x]=j.useState(s.name),[y,v]=j.useState(s.description||""),[b,w]=j.useState(!1),S=j.useMemo(()=>s.media.filter(U=>U.kind==="video"&&U.agent_video_id).map(U=>U.agent_video_id),[s.media]),{data:C={}}=tt({queryKey:["room-video-statuses",s.id,S.join(",")],enabled:S.length>0,queryFn:async()=>{const{data:U,error:W}=await q.from("agent_videos").select("id, status, bunny_video_id, thumbnail_url, preview_url").in("id",S);if(W)throw W;const V=U||[],G=V.filter(X=>X.status==="processing"&&X.bunny_video_id);await Promise.all(G.map(async X=>{try{const{data:ae}=await q.functions.invoke("bunny-upload",{body:{action:"status",videoId:X.bunny_video_id,isAgentVideo:!0}});ae&&ae.status===4&&(await q.from("agent_videos").update({status:"ready",playback_url:ae.directPlayUrl,thumbnail_url:ae.thumbnailUrl,preview_url:ae.previewUrl,duration_seconds:ae.length||void 0,updated_at:new Date().toISOString()}).eq("id",X.id),X.status="ready",X.thumbnail_url=ae.thumbnailUrl,X.preview_url=ae.previewUrl)}catch{}}));const Y={};return V.forEach(X=>{Y[X.id]={status:X.status,thumbnail_url:X.thumbnail_url,preview_url:X.preview_url}}),Y},refetchInterval:U=>{const W=U.state.data;return W?Object.values(W).some(V=>V.status!=="ready"&&V.status!=="failed")?5e3:!1:5e3}}),E=()=>{g.trim()&&g!==s.name&&l.mutate({id:s.id,open_house_id:a,name:g.trim()})},I=()=>{y!==(s.description||"")&&l.mutate({id:s.id,open_house_id:a,description:y.trim()||null})},P=async()=>{await fo(`Delete "${s.name}" and all its media?`)&&o.mutate({id:s.id,open_house_id:a})},R=U=>i(t,U),D=(U,W)=>{const V=U+W;if(V<0||V>=s.media.length)return;const G=s.media.map(Y=>Y.id);[G[U],G[V]]=[G[V],G[U]],u.mutate({open_house_id:a,room_id:s.id,orderedIds:G})},O=async U=>{const W=Array.from(U.target.files||[]);if(!(!W.length||!r)){w(!0);try{for(const V of W){const G=V.type.startsWith("video/"),Y=G?500*1024*1024:15*1024*1024;if(V.size>Y){_a({title:`${V.name} is too large`,description:G?"Videos must be under 500MB":"Photos must be under 15MB",variant:"destructive"});continue}if(G){try{const te=`${s.name} – ${V.name.replace(/\.[^/.]+$/,"")}`,{data:J,error:ce}=await q.functions.invoke("bunny-upload",{body:{action:"create",title:te,isAgentVideo:!0}});if(ce||!J)throw new Error((ce==null?void 0:ce.message)||"Could not start upload");const{videoId:_e,libraryId:he}=J,{data:ue,error:ve}=await q.functions.invoke("bunny-upload",{body:{action:"upload-url",videoId:_e,isAgentVideo:!0}});if(ve||!ue)throw new Error((ve==null?void 0:ve.message)||"Could not get upload URL");await new Promise((ke,Ve)=>{const je=new XMLHttpRequest;je.addEventListener("load",()=>{je.status>=200&&je.status<300?ke():Ve(new Error(`Upload failed (${je.status})`))}),je.addEventListener("error",()=>Ve(new Error("Upload failed"))),je.open("PUT",ue.uploadUrl),je.setRequestHeader("AccessKey",ue.apiKey),je.send(V)});const Ee=`https://iframe.mediadelivery.net/embed/${he}/${_e}`,Se=V.size/(1024*1024),{data:Le,error:Fe}=await q.from("agent_videos").insert({owner_user_id:r,bunny_video_id:_e,playback_url:Ee,file_size_mb:Se,title:te,status:"processing",touch_type:"open_house_tour",category:"open_house",page_template:"default"}).select().single();if(Fe)throw Fe;await c.mutateAsync({open_house_id:a,room_id:s.id,kind:"video",url:Ee,sort_order:s.media.length,agent_video_id:Le.id}),_a({title:"Video uploaded",description:"Processing in the background — it’ll appear in your Video Library too."})}catch(te){_a({title:"Video upload failed",description:(te==null?void 0:te.message)||"Try again",variant:"destructive"})}continue}const X=V.name.split(".").pop()||"jpg",ae=`${r}/${a}/rooms/${s.id}-${Date.now()}-${Math.random().toString(36).slice(2,7)}.${X}`,{error:ie}=await q.storage.from("open-house-tour-media").upload(ae,V,{upsert:!1,contentType:V.type});if(ie){_a({title:"Upload failed",description:ie.message,variant:"destructive"});continue}const{data:ne}=q.storage.from("open-house-tour-media").getPublicUrl(ae);await c.mutateAsync({open_house_id:a,room_id:s.id,kind:"photo",url:ne.publicUrl,sort_order:s.media.length})}}finally{w(!1),h.current&&(h.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(Ug,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("button",{onClick:()=>f(U=>!U),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($,{size:"icon",variant:"ghost",className:"h-7 w-7",onClick:()=>R(-1),disabled:t===0,children:e.jsx(v1,{className:"h-4 w-4"})}),e.jsx($,{size:"icon",variant:"ghost",className:"h-7 w-7",onClick:()=>R(1),disabled:t===n-1,children:e.jsx(Tl,{className:"h-4 w-4"})}),e.jsx($,{size:"icon",variant:"ghost",className:"h-7 w-7 text-destructive",onClick:P,children:e.jsx(Wn,{className:"h-4 w-4"})})]}),m&&e.jsxs("div",{className:"p-3 space-y-3",children:[e.jsx(pe,{value:g,onChange:U=>x(U.target.value),onBlur:E,placeholder:"Room name",className:"h-9"}),e.jsx(Rs,{value:y,onChange:U=>v(U.target.value),onBlur:I,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((U,W)=>{const V=U.agent_video_id?C[U.agent_video_id]:void 0,G=V==null?void 0:V.status,Y=U.kind==="video"&&G&&G!=="ready"&&G!=="failed",X=U.kind==="video"&&G==="failed",ae=(V==null?void 0:V.thumbnail_url)||(V==null?void 0:V.preview_url);return e.jsxs("div",{className:"relative aspect-square rounded-md overflow-hidden bg-muted group",children:[U.kind==="video"?e.jsxs(e.Fragment,{children:[ae?e.jsx("img",{src:ae,alt:"",className:"w-full h-full object-cover"}):/iframe\.mediadelivery\.net\/embed\//.test(U.url)?e.jsx("div",{className:"w-full h-full bg-slate-800"}):e.jsx("video",{src:U.url,className:"w-full h-full object-cover"}),!Y&&!X&&e.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-black/30 pointer-events-none",children:e.jsx(ua,{className:"h-6 w-6 text-white"})}),Y&&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(kt,{className:"h-5 w-5 animate-spin"}),e.jsx("span",{className:"text-[10px] font-medium uppercase tracking-wide",children:"Processing"})]}),X&&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:U.url,alt:"",className:"w-full h-full object-cover"}),e.jsx("span",{className:"absolute top-1 left-1 px-1.5 h-5 rounded-full bg-black/60 text-white text-[10px] font-semibold flex items-center",children:W+1}),e.jsx("button",{type:"button","aria-label":"Remove media",onClick:()=>d.mutate({id:U.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(gr,{className:"h-3.5 w-3.5"})}),e.jsxs("div",{className:"absolute inset-x-1 bottom-1 flex items-center justify-between opacity-0 group-hover:opacity-100 transition",children:[e.jsx("button",{type:"button","aria-label":"Move earlier",disabled:W===0,onClick:()=>D(W,-1),className:"w-6 h-6 rounded-full bg-black/60 text-white flex items-center justify-center disabled:opacity-30",children:e.jsx(Cd,{className:"h-3.5 w-3.5"})}),e.jsx("button",{type:"button","aria-label":"Move later",disabled:W===s.media.length-1,onClick:()=>D(W,1),className:"w-6 h-6 rounded-full bg-black/60 text-white flex items-center justify-center disabled:opacity-30",children:e.jsx(Di,{className:"h-3.5 w-3.5"})})]})]},U.id)})}),e.jsx("input",{ref:h,type:"file",accept:"image/*,video/*",multiple:!0,onChange:O,className:"hidden"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx($,{variant:"outline",size:"sm",onClick:()=>{var U;return(U=h.current)==null?void 0:U.click()},disabled:b,className:"flex-1",children:b?e.jsx(kt,{className:"h-4 w-4 animate-spin"}):e.jsxs(e.Fragment,{children:[e.jsx(ni,{className:"h-4 w-4 mr-2"})," Upload"]})}),e.jsx(o9,{userId:r,triggerLabel:"From Video Library",triggerClassName:"gap-1.5 flex-1 justify-center",onSelect:()=>{},onSelectVideo:async U=>{try{await c.mutateAsync({open_house_id:a,room_id:s.id,kind:"video",url:U.playback_url||"",sort_order:s.media.length,agent_video_id:U.id}),_a({title:"Video added to room"})}catch(W){_a({title:"Failed to add video",description:W==null?void 0:W.message,variant:"destructive"})}}})]})]})]})}function uhr({open:s,onOpenChange:t,openHouse:n}){const r=tBt(),{user:a}=vs(),i=j.useRef(null),l=j.useRef(null),o=j.useRef(null),c=n.kind==="virtual",[d,u]=j.useState(n.auto_forward_to_card??!1),[h,m]=j.useState(n.disclosure_pdf_url??""),[f,g]=j.useState(n.enable_survey??!1),[x,y]=j.useState(n.ask_visitor_intent??!0),[v,b]=j.useState(n.ask_visitor_address??!1),[w,S]=j.useState(n.photo_url??""),[C,E]=j.useState(!1),[I,P]=j.useState(!1),[R,D]=j.useState(!1),[O,U]=j.useState(n.property_address??""),[W,V]=j.useState(n.city??""),[G,Y]=j.useState(n.state??""),[X,ae]=j.useState(n.zip??""),[ie,ne]=j.useState((n.event_date??"").slice(0,10)),[te,J]=j.useState((n.start_time??"").slice(0,5)),[ce,_e]=j.useState((n.end_time??"").slice(0,5)),[he,ue]=j.useState(n.hero_video_url??""),[ve,Ee]=j.useState(!1),[Se,Le]=j.useState(n.price!=null?String(n.price):""),[Fe,ke]=j.useState(n.beds!=null?String(n.beds):""),[Ve,je]=j.useState(n.baths!=null?String(n.baths):""),[Ae,Ce]=j.useState(n.sqft!=null?String(n.sqft):""),[qe,ze]=j.useState(n.enable_question??!0),[$e,ct]=j.useState(n.enable_showing??!0),[Xe,it]=j.useState(n.enable_disclosures??!0),[at,Ke]=j.useState(n.enable_offer??!0),[nt,xt]=j.useState(n.brand_color_override??""),[rt,Yt]=j.useState(n.property_description??""),[qt,ts]=j.useState(n.drip_campaign_id??null),ys=async vt=>{var js;const gs=(js=vt.target.files)==null?void 0:js[0];if(!gs||!a)return;if(gs.size>200*1024*1024){_a({title:"Video must be under 200MB",variant:"destructive"});return}if(!gs.type.startsWith("video/")){_a({title:"Please upload a video file",variant:"destructive"});return}Ee(!0);const Ss=gs.name.split(".").pop()||"mp4",Is=`${a.id}/${n.id}/hero-${Date.now()}.${Ss}`,{error:Ys}=await q.storage.from("open-house-tour-media").upload(Is,gs,{upsert:!0,contentType:gs.type});if(Ys){_a({title:"Upload failed",description:Ys.message,variant:"destructive"}),Ee(!1);return}const{data:cs}=q.storage.from("open-house-tour-media").getPublicUrl(Is);ue(cs.publicUrl),Ee(!1),_a({title:"Video uploaded!"})},Bt=async vt=>{var js;const gs=(js=vt.target.files)==null?void 0:js[0];if(!gs||!a)return;if(gs.size>10*1024*1024){_a({title:"Image must be under 10MB",variant:"destructive"});return}if(!gs.type.startsWith("image/")){_a({title:"Please upload an image file",variant:"destructive"});return}P(!0);const Ss=gs.name.split(".").pop()||"jpg",Is=`${a.id}/${n.id}-${Date.now()}.${Ss}`,{error:Ys}=await q.storage.from("open-house-photos").upload(Is,gs,{upsert:!0});if(Ys){_a({title:"Upload failed",description:Ys.message,variant:"destructive"}),P(!1);return}const{data:cs}=q.storage.from("open-house-photos").getPublicUrl(Is);S(cs.publicUrl),P(!1),_a({title:"Photo updated!"})},Ft=()=>{S(""),l.current&&(l.current.value="")},rs=async vt=>{var cs;const gs=(cs=vt.target.files)==null?void 0:cs[0];if(!gs||!a)return;if(gs.size>20*1024*1024){_a({title:"File must be under 20MB",variant:"destructive"});return}if(gs.type!=="application/pdf"){_a({title:"Only PDF files are accepted",variant:"destructive"});return}E(!0);const Ss=`${a.id}/disclosures/${n.id}-${Date.now()}.pdf`,{error:Is}=await q.storage.from("open-house-photos").upload(Ss,gs,{upsert:!0});if(Is){_a({title:"Upload failed",description:Is.message,variant:"destructive"}),E(!1);return}const{data:Ys}=q.storage.from("open-house-photos").getPublicUrl(Ss);m(Ys.publicUrl),E(!1),_a({title:"PDF uploaded!"})},St=()=>{m(""),i.current&&(i.current.value="")},Xs=async()=>{if(!O.trim()){_a({title:"Add a property address",variant:"destructive"});return}if(!ie){_a({title:"Pick a date for the open house",variant:"destructive"});return}D(!0);try{const vt={id:n.id,property_address:O.trim(),city:W.trim()||null,state:G.trim()||null,zip:X.trim()||null,event_date:ie,start_time:te||null,end_time:ce||null,auto_forward_to_card:d,disclosure_pdf_url:h||null,enable_survey:f,ask_visitor_intent:x,ask_visitor_address:v,photo_url:w||null,drip_campaign_id:qt};c&&(vt.hero_video_url=he||null,vt.price=Se.trim()?Number(Se):null,vt.beds=Fe.trim()?parseInt(Fe,10):null,vt.baths=Ve.trim()?Number(Ve):null,vt.sqft=Ae.trim()?parseInt(Ae,10):null,vt.enable_question=qe,vt.enable_showing=$e,vt.enable_disclosures=Xe,vt.enable_offer=at,vt.brand_color_override=nt.trim()||null,vt.property_description=rt.trim()||null),(O.trim()!==(n.property_address??"")||(W.trim()||null)!==(n.city??null)||(G.trim()||null)!==(n.state??null)||(X.trim()||null)!==(n.zip??null))&&(vt.latitude=null,vt.longitude=null,vt.geocode_status="pending",vt.geocoded_at=null),await r.mutateAsync(vt),_a({title:"Settings saved!"}),t(!1)}catch{_a({title:"Failed to save",variant:"destructive"})}finally{D(!1)}};return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Os,{className:"sm:max-w-md max-h-[85vh] overflow-y-auto",children:[e.jsxs(Us,{children:[e.jsx(Bs,{children:c?"Virtual Open House Settings":"Guest Book Settings"}),e.jsx(Ir,{className:"truncate",children:n.property_address})]}),e.jsxs("div",{className:"space-y-6 pt-2",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsx(ee,{className:"text-sm font-medium",children:"Date & Time"}),e.jsx("p",{className:"text-xs text-muted-foreground -mt-1",children:"Change when this open house takes place. Updates the sign-in page right away."}),e.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs text-muted-foreground",children:"Date"}),e.jsx(pe,{type:"date",value:ie,onChange:vt=>ne(vt.target.value),className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs text-muted-foreground",children:"Start"}),e.jsx(pe,{type:"time",value:te,onChange:vt=>J(vt.target.value),className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs text-muted-foreground",children:"End"}),e.jsx(pe,{type:"time",value:ce,onChange:vt=>_e(vt.target.value),className:"mt-1"})]})]}),e.jsx(ee,{className:"text-sm font-medium",children:"Property Address"}),e.jsx(pe,{value:O,onChange:vt=>U(vt.target.value),placeholder:"412 Oak St"}),e.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs text-muted-foreground",children:"City"}),e.jsx(pe,{value:W,onChange:vt=>V(vt.target.value),className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs text-muted-foreground",children:"State"}),e.jsx(pe,{value:G,onChange:vt=>Y(vt.target.value),className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs text-muted-foreground",children:"ZIP"}),e.jsx(pe,{value:X,onChange:vt=>ae(vt.target.value),className:"mt-1"})]})]})]}),c&&e.jsxs(e.Fragment,{children:[n.tour_mode==="single_video"?e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ee,{className:"text-sm font-medium flex items-center gap-2",children:[e.jsx(ua,{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:ys,className:"hidden"}),he?e.jsxs("div",{className:"relative rounded-lg overflow-hidden border border-border bg-black",children:[e.jsx("video",{src:he,controls:!0,className:"w-full max-h-48"}),e.jsxs("div",{className:"absolute top-2 right-2 flex gap-2",children:[e.jsx($,{variant:"secondary",size:"sm",className:"h-8",onClick:()=>{var vt;return(vt=o.current)==null?void 0:vt.click()},disabled:ve,children:ve?e.jsx(kt,{className:"h-3.5 w-3.5 animate-spin"}):e.jsxs(e.Fragment,{children:[e.jsx(ni,{className:"h-3.5 w-3.5 mr-1"}),"Replace"]})}),e.jsx($,{variant:"secondary",size:"icon",className:"h-8 w-8",onClick:()=>ue(""),children:e.jsx(gr,{className:"h-4 w-4"})})]})]}):e.jsx("button",{type:"button",onClick:()=>{var vt;return(vt=o.current)==null?void 0:vt.click()},disabled:ve,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:ve?e.jsx(kt,{className:"h-5 w-5 animate-spin"}):e.jsxs(e.Fragment,{children:[e.jsx(ua,{className:"h-5 w-5"}),e.jsx("span",{className:"text-xs",children:"Upload tour video (max 200MB)"})]})})]}):e.jsx(chr,{openHouseId:n.id}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{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(ee,{className:"text-xs text-muted-foreground",children:"Price (USD)"}),e.jsx(pe,{type:"number",value:Se,onChange:vt=>Le(vt.target.value),placeholder:"650000",className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs text-muted-foreground",children:"Sq Ft"}),e.jsx(pe,{type:"number",value:Ae,onChange:vt=>Ce(vt.target.value),placeholder:"2200",className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs text-muted-foreground",children:"Beds"}),e.jsx(pe,{type:"number",value:Fe,onChange:vt=>ke(vt.target.value),placeholder:"3",className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs text-muted-foreground",children:"Baths"}),e.jsx(pe,{type:"number",step:"0.5",value:Ve,onChange:vt=>je(vt.target.value),placeholder:"2.5",className:"mt-1"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{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(Rs,{value:rt,onChange:vt=>Yt(vt.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(ee,{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(Sn,{checked:qe,onCheckedChange:ze})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-sm",children:"Schedule a private showing"}),e.jsx(Sn,{checked:$e,onCheckedChange:ct})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-sm",children:"Request seller disclosures"}),e.jsx(Sn,{checked:Xe,onCheckedChange:it})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-sm",children:"Make an offer / express interest"}),e.jsx(Sn,{checked:at,onCheckedChange:Ke})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{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:nt||"#0f172a",onChange:vt=>xt(vt.target.value),className:"h-10 w-14 rounded-md border border-input cursor-pointer bg-transparent"}),e.jsx(pe,{value:nt,onChange:vt=>xt(vt.target.value),placeholder:"#0f172a",className:"flex-1 font-mono text-sm"}),nt&&e.jsx($,{variant:"ghost",size:"sm",onClick:()=>xt(""),children:"Reset"})]}),e.jsx("div",{className:"flex flex-wrap gap-1.5 pt-1",children:["#0f172a","#406E71","#2a4c64","#7c2d12","#1e3a8a","#581c87","#9f1239","#065f46"].map(vt=>e.jsx("button",{type:"button",onClick:()=>xt(vt),className:"w-6 h-6 rounded-full border border-border hover:scale-110 transition-transform",style:{backgroundColor:vt},"aria-label":vt},vt))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{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:Bt,className:"hidden"}),w?e.jsxs("div",{className:"relative rounded-lg overflow-hidden border border-border",children:[e.jsx("img",{src:w,alt:"Property",className:"w-full h-40 object-cover"}),e.jsxs("div",{className:"absolute top-2 right-2 flex gap-2",children:[e.jsxs($,{variant:"secondary",size:"sm",className:"h-8",onClick:()=>{var vt;return(vt=l.current)==null?void 0:vt.click()},disabled:I,children:[I?e.jsx(kt,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(ni,{className:"h-3.5 w-3.5 mr-1"}),I?"":"Replace"]}),e.jsx($,{variant:"secondary",size:"icon",className:"h-8 w-8",onClick:Ft,children:e.jsx(gr,{className:"h-4 w-4"})})]})]}):e.jsx("button",{type:"button",onClick:()=>{var vt;return(vt=l.current)==null?void 0:vt.click()},disabled:I,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:I?e.jsx(kt,{className:"h-5 w-5 animate-spin"}):e.jsxs(e.Fragment,{children:[e.jsx(Mc,{className:"h-5 w-5"}),e.jsx("span",{className:"text-xs",children:"Upload property photo (max 10MB)"})]})})]}),e.jsx(ohr,{value:qt,onChange:ts}),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(ee,{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(Sn,{checked:d,onCheckedChange:u})]})}),!d&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{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:rs,className:"hidden"}),h?e.jsxs("div",{className:"flex items-center gap-3 p-3 rounded-lg border border-border bg-muted/30",children:[e.jsx(Jr,{className:"h-5 w-5 text-primary shrink-0"}),e.jsx("span",{className:"text-sm truncate flex-1",children:"Disclosure PDF uploaded"}),e.jsx($,{variant:"ghost",size:"icon",className:"h-7 w-7 shrink-0",onClick:St,children:e.jsx(gr,{className:"h-4 w-4"})})]}):e.jsx("button",{type:"button",onClick:()=>{var vt;return(vt=i.current)==null?void 0:vt.click()},disabled:C,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:C?e.jsx(kt,{className:"h-5 w-5 animate-spin"}):e.jsxs(e.Fragment,{children:[e.jsx(ni,{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(ee,{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(Sn,{checked:x,onCheckedChange:y})]})}),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(ee,{className:"text-sm font-medium",children:"Ask for visitor's home address"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Adds an optional address field to the sign-in form — helpful for follow-up and market reports."})]}),e.jsx(Sn,{checked:v,onCheckedChange:b})]})}),e.jsx(lhr,{openHouseId:n.id,enableSurvey:f,onToggleSurvey:g}),e.jsx($,{onClick:Xs,disabled:R,className:"w-full",children:R?"Saving...":"Save Settings"})]})]})})}const hls={5:"Excellent",4:"Good",3:"Neutral",2:"Bad",1:"Very Bad"};function hhr({question:s,responses:t}){const n=t.filter(l=>l.question_id===s.id&&l.rating_value!=null),r=n.length;if(r===0)return null;const a=n.reduce((l,o)=>l+(o.rating_value||0),0)/r,i=[5,4,3,2,1].map(l=>({val:l,count:n.filter(o=>o.rating_value===l).length,pct:Math.round(n.filter(o=>o.rating_value===l).length/r*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 (",r," 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:hls[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 mhr({openHouseId:s}){const{data:t,isLoading:n}=EFs(s),{data:r}=eBt(s),a=j.useMemo(()=>{const h={};return r==null||r.forEach(m=>{h[m.id]=m}),h},[r]);if(n||!t)return null;const{questions:i,responses:l}=t;if(i.length===0)return null;const o=i.filter(h=>h.question_type==="rating"),c=i.filter(h=>h.question_type!=="rating"),d=[...new Set(l.map(h=>h.visitor_id))],u=d.length;return u===0?e.jsxs(Ne,{children:[e.jsx(Ct,{className:"pb-3",children:e.jsxs(At,{className:"text-base flex items-center gap-2",children:[e.jsx(zg,{className:"h-4 w-4"}),"Survey Results"]})}),e.jsx(Ie,{children:e.jsx("p",{className:"text-sm text-muted-foreground",children:"No survey responses yet."})})]}):e.jsxs(Ne,{children:[e.jsx(Ct,{className:"pb-3",children:e.jsxs(At,{className:"text-base flex items-center gap-2",children:[e.jsx(zg,{className:"h-4 w-4"}),"Survey Results",e.jsxs("span",{className:"text-xs font-normal text-muted-foreground ml-auto",children:[u," respondent",u!==1?"s":""]})]})}),e.jsx(Ie,{children:e.jsxs(ha,{defaultValue:"summary",children:[e.jsxs(ma,{className:"mb-4",children:[e.jsxs(Zt,{value:"summary",className:"text-xs gap-1",children:[e.jsx(Wl,{className:"h-3.5 w-3.5"})," Summary"]}),e.jsxs(Zt,{value:"individual",className:"text-xs gap-1",children:[e.jsx(sl,{className:"h-3.5 w-3.5"})," Per Visitor"]})]}),e.jsxs(Xt,{value:"summary",className:"space-y-6",children:[o.map(h=>e.jsx(hhr,{question:h,responses:l},h.id)),c.map(h=>{const m=l.filter(f=>f.question_id===h.id&&f.text_value);return m.length===0?null:e.jsxs("div",{className:"space-y-2",children:[e.jsx("span",{className:"text-sm font-medium",children:h.question_text}),e.jsx("div",{className:"space-y-1.5 max-h-40 overflow-y-auto",children:m.map(f=>{const g=a[f.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:[g?`${g.first_name} ${g.last_name||""}`.trim():"Visitor",":"]}),e.jsx("p",{className:"mt-0.5",children:f.text_value})]},f.id)})})]},h.id)})]}),e.jsx(Xt,{value:"individual",className:"space-y-4",children:d.map(h=>{const m=a[h],f=l.filter(g=>g.visitor_id===h);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:[m?`${m.first_name} ${m.last_name||""}`.trim():"Unknown Visitor",(m==null?void 0:m.email)&&e.jsx("span",{className:"text-xs text-muted-foreground ml-2",children:m.email})]}),e.jsx("div",{className:"space-y-1",children:f.map(g=>{const x=i.find(y=>y.id===g.question_id);return x?e.jsxs("div",{className:"flex items-center justify-between text-sm",children:[e.jsx("span",{className:"text-muted-foreground",children:x.question_text}),e.jsx("span",{className:"font-medium",children:g.rating_value!=null?hls[g.rating_value]||g.rating_value:g.text_value})]},g.id):null})})]},h)})})]})})]})}const fhr={question:{label:"Question",icon:eo,color:"text-sky-700 dark:text-sky-300",bg:"bg-sky-100 dark:bg-sky-950"},showing:{label:"Showing",icon:Ta,color:"text-orange-700 dark:text-orange-300",bg:"bg-orange-100 dark:bg-orange-950"},disclosure:{label:"Disclosures",icon:Jr,color:"text-indigo-700 dark:text-indigo-300",bg:"bg-indigo-100 dark:bg-indigo-950"},offer:{label:"Hot Lead",icon:ru,color:"text-emerald-700 dark:text-emerald-300",bg:"bg-emerald-100 dark:bg-emerald-950"}},JEt={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 phr({openHouseId:s}){const{data:t=[],isLoading:n}=GFs(s),r=WFs(),[a,i]=j.useState(null),[l,o]=j.useState("all"),c=t.filter(h=>l==="all"?!0:l==="new"?h.status==="new":h.action_type===l),d={all:t.length,new:t.filter(h=>h.status==="new").length,question:t.filter(h=>h.action_type==="question").length,showing:t.filter(h=>h.action_type==="showing").length,disclosure:t.filter(h=>h.action_type==="disclosure").length,offer:t.filter(h=>h.action_type==="offer").length},u=(h,m)=>{r.mutate({id:h,status:m,open_house_id:s})};return n?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(Gz,{className:"h-4 w-4"}),"Virtual Open House Leads",e.jsx(Be,{variant:"secondary",className:"ml-1",children:d.all}),d.new>0&&e.jsxs(Be,{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(([h,m,f])=>e.jsxs("button",{onClick:()=>o(h),className:`text-xs px-2.5 py-1 rounded-full transition-colors ${l===h?"bg-foreground text-background":"bg-background hover:bg-muted text-muted-foreground"}`,children:[m," ",e.jsx("span",{className:"opacity-60",children:f})]},h))})]}),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(h=>{const m=fhr[h.action_type],f=m.icon,g=h.payload||{},x=a===h.id,y=h.status==="contacted",v=h.status==="archived";return e.jsxs("li",{className:`transition-colors ${v?"opacity-60":""} ${h.status==="new"?"bg-emerald-50/40 dark:bg-emerald-950/10":""}`,children:[e.jsxs("button",{onClick:()=>i(x?null:h.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 ${m.bg}`,children:e.jsx(f,{className:`h-4 w-4 ${m.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:g.visitor_name||"Visitor"}),e.jsx(Be,{variant:"outline",className:`text-[10px] ${m.color}`,children:m.label}),h.status==="new"&&e.jsx("span",{className:"text-[10px] font-bold text-emerald-600 uppercase tracking-wide",children:"New"}),y&&e.jsxs("span",{className:"text-[10px] font-bold text-muted-foreground uppercase tracking-wide flex items-center gap-1",children:[e.jsx(qr,{className:"h-3 w-3"}),"Contacted"]})]}),g.message&&e.jsxs("p",{className:"text-sm text-muted-foreground line-clamp-1 mt-0.5 italic",children:['"',g.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(da,{className:"h-3 w-3"}),en(new Date(h.created_at),"MMM d, h:mm a")]}),g.email&&e.jsxs("span",{className:"flex items-center gap-1 truncate",children:[e.jsx(mn,{className:"h-3 w-3"}),g.email]}),g.phone&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Da,{className:"h-3 w-3"}),g.phone]})]})]}),x?e.jsx(Tl,{className:"h-4 w-4 mt-1 text-muted-foreground"}):e.jsx(Di,{className:"h-4 w-4 mt-1 text-muted-foreground"})]}),x&&e.jsxs("div",{className:"px-4 pb-4 pl-16 space-y-3",children:[g.message&&e.jsxs("div",{className:"bg-muted/40 rounded-md p-3 text-sm border-l-2 border-foreground/30",children:['"',g.message,'"']}),Object.keys(JEt).some(b=>g[b]!=null&&g[b]!==""&&!(Array.isArray(g[b])&&g[b].length===0))&&e.jsx("div",{className:"grid grid-cols-2 gap-x-4 gap-y-1.5 text-sm",children:Object.entries(JEt).map(([b,w])=>{const S=g[b];return S==null||S===""||Array.isArray(S)&&S.length===0?null:e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] text-muted-foreground uppercase tracking-wide",children:w}),e.jsx("div",{className:"font-medium",children:Array.isArray(S)?S.join(", "):String(S)})]},b)})}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2 pt-1",children:[g.email&&e.jsx("a",{href:`mailto:${g.email}?subject=${encodeURIComponent("Re: your open house inquiry")}`,children:e.jsxs($,{size:"sm",variant:"default",className:"gap-1.5",children:[e.jsx(mn,{className:"h-3.5 w-3.5"}),"Reply"]})}),g.phone&&e.jsx("a",{href:`tel:${String(g.phone).replace(/[^0-9+]/g,"")}`,children:e.jsxs($,{size:"sm",variant:"outline",className:"gap-1.5",children:[e.jsx(Da,{className:"h-3.5 w-3.5"}),"Call"]})}),!y&&e.jsxs($,{size:"sm",variant:"outline",className:"gap-1.5",onClick:()=>u(h.id,"contacted"),children:[e.jsx(qr,{className:"h-3.5 w-3.5"}),"Mark contacted"]}),v?e.jsx($,{size:"sm",variant:"ghost",className:"gap-1.5 text-muted-foreground",onClick:()=>u(h.id,"new"),children:"Restore"}):e.jsxs($,{size:"sm",variant:"ghost",className:"gap-1.5 text-muted-foreground",onClick:()=>u(h.id,"archived"),children:[e.jsx(Sv,{className:"h-3.5 w-3.5"}),"Archive"]})]})]})]},h.id)})})]})}const eTt=s=>{if(!s)return"";const[t,n]=s.split(":"),r=parseInt(t,10),a=r>=12?"PM":"AM";return`${r>12?r-12:r||12}:${n} ${a}`},ghr=s=>{if(!s)return"";const[t,n,r]=s.split(/[-/T]/).map(Number);return!t||!n||!r?"":new Date(t,n-1,r).toLocaleDateString("en-US",{weekday:"long",month:"long",day:"numeric"})},tTt=25;function xhr({open:s,onOpenChange:t,openHouse:n,variant:r="tour"}){var ct;const a=r==="rsvp",{isGmailConnected:i,gmailEmail:l}=yy(),{data:o}=oie(),c=!!(o!=null&&o.hasVerifiedSes),d=Sa(),{data:u=[]}=Yw(),[h,m]=j.useState([]),[f,g]=j.useState(!1),[x,y]=j.useState("all"),[v,b]=j.useState([]),[w,S]=j.useState([]),[C,E]=j.useState(""),[I,P]=j.useState([]),[R,D]=j.useState(""),[O,U]=j.useState(""),[W,V]=j.useState(""),[G,Y]=j.useState("platform"),[X,ae]=j.useState(!1),[ie,ne]=j.useState(0),[te,J]=j.useState(!1),ce=a?`https://guestbook.relevelup.com/rsvp/${n.slug}`:`https://guestbook.relevelup.com/${n.slug}`,_e=ghr(n.event_date),he=n.start_time?`${eTt(n.start_time)}${n.end_time?` – ${eTt(n.end_time)}`:""}`:"",ue=[_e,he].filter(Boolean).join(" · ");j.useEffect(()=>{s&&(U(a?`You're invited: Open House at ${n.property_address}`:`Take a virtual tour of ${n.property_address}`),V(a?`I'm hosting an open house at ${n.property_address}${_e?` on ${_e}`:""}${he?` from ${he}`:""}. I'd love for you to stop by — tap below to RSVP so I can save you a spot.`:`I wanted to share an immersive virtual tour of ${n.property_address} with you. Step inside from anywhere — explore every room at your own pace.`),S([]),b([]),P([]),E(""),y("all"),ne(0),Y(c?"ses":i?"gmail":"platform"),h.length===0&&ve())},[s,n.id,i,c]);const ve=async()=>{if(d){g(!0);try{const Xe=[];let at=0;for(;;){const{data:Ke,error:nt}=await q.from("innercircle_contacts").select("id, first_name, last_name, email, tags:innercircle_contact_tags(relationship_type_id)").eq("owner_user_id",d).eq("email_opt_out",!1).not("email","is",null).neq("email","").order("first_name",{ascending:!0}).order("id",{ascending:!0}).range(at,at+1e3-1);if(nt)throw nt;const xt=Ke||[];if(Xe.push(...xt),xt.length<1e3)break;at+=1e3}m(Xe.map(Ke=>({id:Ke.id,first_name:Ke.first_name,last_name:Ke.last_name,email:Ke.email,tagIds:(Ke.tags||[]).map(nt=>nt.relationship_type_id)})))}catch{re.error("Failed to load contacts")}finally{g(!1)}}},Ee=Xe=>`${Xe.first_name} ${Xe.last_name||""}`.trim(),Se=j.useMemo(()=>{const Xe=R.trim().toLowerCase();return Xe?h.filter(it=>`${Ee(it)} ${it.email||""}`.toLowerCase().includes(Xe)):h},[h,R]),Le=j.useMemo(()=>{const Xe={};return h.forEach(it=>it.tagIds.forEach(at=>{Xe[at]=(Xe[at]||0)+1})),Xe},[h]),Fe=j.useMemo(()=>x==="all"?h:x==="tags"?v.length===0?[]:h.filter(Xe=>Xe.tagIds.some(it=>v.includes(it))):h.filter(Xe=>w.includes(Xe.id)),[x,h,v,w]),ke=j.useMemo(()=>{const Xe=new Set,it=[];return[...Fe.map(at=>({email:at.email,name:Ee(at)})),...I].forEach(at=>{const Ke=at.email.toLowerCase();!at.email||Xe.has(Ke)||(Xe.add(Ke),it.push(at))}),it},[Fe,I]),Ve=()=>{const Xe=C.trim();if(Xe){if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(Xe)){re.error("Invalid email");return}P(it=>[...it,{email:Xe,name:Xe.split("@")[0]}]),E("")}},je=Xe=>Xe.replace(/&/g,"&").replace(//g,">"),Ae=n.photo_url&&n.photo_url.includes("/storage/v1/object/public/")?n.photo_url.replace("/object/public/","/render/image/public/")+"?width=1200&height=630&resize=cover":n.photo_url||"",Ce=Xe=>{const it=Xe?`Hi ${je(Xe)},`:"Hi there,",at=[n.city,n.state].filter(Boolean).join(", "),Ke=je(W).split(/\n\n+/).map(nt=>`

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

`).join("");return`
${Ae?``:""} ${a&&ue?``:""}

${a?"You're Invited":"Virtual Open House"}

${je(n.property_address)}

${at?`

${je(at)}${n.zip?" "+je(n.zip):""}

`:""}
 

When

${je(ue)}

${it}

${Ke}
${a?"RSVP for this Open House":"▶ Start Virtual Tour"}

Or copy this link:
${ce}

`},qe=j.useMemo(()=>Ce("Alex"),[W,n.id,Ae,a,ue]),ze=async()=>{var Xe;if(ke.length===0){re.error("Add at least one recipient");return}ae(!0),ne(0);try{if(G==="gmail"&&i){let it=0;for(const at of ke){const{data:Ke,error:nt}=await q.functions.invoke("gmail-send",{body:{to:at.email,subject:O,body:Ce((Xe=at.name)==null?void 0:Xe.split(" ")[0])}});!nt&&(Ke!=null&&Ke.success)&&(it+=1),ne(it)}if(it===0)throw new Error("Gmail send failed");re.success(`Sent to ${it} of ${ke.length} via Gmail`)}else{let it=0;for(let at=0;at{await navigator.clipboard.writeText(ce),J(!0),setTimeout(()=>J(!1),1500)};return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Os,{className:"sm:max-w-[900px] w-[calc(100vw-2rem)] max-h-[92vh] overflow-y-auto overflow-x-hidden",children:[e.jsxs(Us,{className:"min-w-0",children:[e.jsxs(Bs,{className:"flex items-center gap-2",children:[e.jsx(mn,{className:"h-5 w-5 text-primary"}),a?"Invite to Open House":"Email Virtual Tour"]}),e.jsx(Ir,{className:"truncate",children:n.property_address})]}),e.jsxs("div",{className:"grid gap-5 lg:grid-cols-[1fr_380px] min-w-0",children:[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(Ad,{className:"h-4 w-4 text-muted-foreground shrink-0"}),e.jsx("code",{className:"flex-1 min-w-0 text-xs truncate",children:ce}),e.jsxs($,{variant:"ghost",size:"sm",onClick:$e,className:"shrink-0 h-7 gap-1",children:[te?e.jsx(la,{className:"h-3.5 w-3.5 text-emerald-600"}):e.jsx(Ha,{className:"h-3.5 w-3.5"}),te?"Copied":"Copy"]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ee,{className:"flex items-center gap-1.5",children:[e.jsx(mn,{className:"h-3.5 w-3.5"}),"Send from"]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[c&&e.jsx($,{type:"button",variant:G==="ses"?"default":"outline",size:"sm",onClick:()=>Y("ses"),className:"gap-1.5",children:"Mass Email (your address)"}),i&&e.jsx($,{type:"button",variant:G==="gmail"?"default":"outline",size:"sm",onClick:()=>Y("gmail"),className:"gap-1.5",children:"Gmail"}),e.jsx($,{type:"button",variant:G==="platform"?"default":"outline",size:"sm",onClick:()=>Y("platform"),className:"gap-1.5",children:"LevelUp"})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:G==="ses"&&((ct=o==null?void 0:o.verifiedEmails)!=null&&ct[0])?e.jsxs(e.Fragment,{children:["Sending as ",e.jsx("span",{className:"font-medium",children:o.verifiedEmails[0]})," via your Mass Email setup"]}):G==="gmail"&&l?e.jsxs(e.Fragment,{children:["Sending as ",e.jsx("span",{className:"font-medium",children:l})]}):e.jsx(e.Fragment,{children:"Sending from the LevelUp notifications address with replies going to you"})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ee,{className:"flex items-center gap-1.5",children:[e.jsx(Zn,{className:"h-3.5 w-3.5"}),"Who should receive this?"]}),e.jsxs(ha,{value:x,onValueChange:Xe=>y(Xe),children:[e.jsxs(ma,{className:"grid w-full grid-cols-3",children:[e.jsx(Zt,{value:"all",children:"All contacts"}),e.jsx(Zt,{value:"tags",children:"By tag"}),e.jsx(Zt,{value:"select",children:"Pick people"})]}),e.jsx(Xt,{value:"all",className:"pt-3",children:e.jsx("div",{className:"rounded-lg border p-3 text-sm text-muted-foreground",children:f?"Loading contacts…":e.jsxs(e.Fragment,{children:["Everyone in your database with an email address — ",e.jsx("span",{className:"font-medium text-foreground",children:h.length.toLocaleString()})," contacts."]})})}),e.jsx(Xt,{value:"tags",className:"pt-3",children:e.jsx(uo,{className:"h-[210px] rounded-lg border p-2",children:e.jsxs("div",{className:"space-y-1",children:[u.map(Xe=>{const it=v.includes(Xe.id);return e.jsxs("label",{className:"flex items-center gap-2 rounded-md px-2 py-1.5 hover:bg-muted cursor-pointer",children:[e.jsx(ai,{checked:it,onCheckedChange:()=>b(at=>it?at.filter(Ke=>Ke!==Xe.id):[...at,Xe.id])}),e.jsxs("span",{className:"flex items-center gap-1.5 text-sm flex-1 min-w-0 truncate",children:[e.jsx(Ap,{className:"h-3 w-3 text-muted-foreground shrink-0"}),Xe.name]}),e.jsx("span",{className:"text-xs text-muted-foreground",children:Le[Xe.id]||0})]},Xe.id)}),u.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground p-2",children:"No tags yet."})]})})}),e.jsxs(Xt,{value:"select",className:"pt-3 space-y-2",children:[e.jsxs("div",{className:"relative",children:[e.jsx(Kr,{className:"absolute left-2.5 top-2.5 h-3.5 w-3.5 text-muted-foreground"}),e.jsx(pe,{value:R,onChange:Xe=>D(Xe.target.value),placeholder:"Search contacts...",className:"pl-8 h-9"})]}),e.jsx(uo,{className:"h-[210px] rounded-lg border p-2",children:e.jsxs("div",{className:"space-y-1",children:[Se.slice(0,300).map(Xe=>{const it=w.includes(Xe.id);return e.jsxs("label",{className:"flex items-center gap-2 rounded-md px-2 py-1.5 hover:bg-muted cursor-pointer",children:[e.jsx(ai,{checked:it,onCheckedChange:()=>S(at=>it?at.filter(Ke=>Ke!==Xe.id):[...at,Xe.id])}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"text-sm font-medium truncate",children:Ee(Xe)||"(no name)"}),e.jsx("div",{className:"text-xs text-muted-foreground truncate",children:Xe.email})]})]},Xe.id)}),Se.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground p-2",children:f?"Loading…":"No contacts found."})]})})]})]}),e.jsxs("div",{className:"flex gap-2 pt-1",children:[e.jsx(pe,{value:C,onChange:Xe=>E(Xe.target.value),placeholder:"Also send to an email...",type:"email",onKeyDown:Xe=>{Xe.key==="Enter"&&(Xe.preventDefault(),Ve())}}),e.jsx($,{type:"button",variant:"outline",size:"sm",onClick:Ve,children:"Add"})]}),I.length>0&&e.jsx("div",{className:"flex flex-wrap gap-1.5",children:I.map(Xe=>e.jsxs(Be,{variant:"secondary",className:"gap-1 pl-2 pr-1 py-0.5",children:[e.jsx("span",{className:"text-xs",children:Xe.email}),e.jsx("button",{onClick:()=>P(it=>it.filter(at=>at.email!==Xe.email)),className:"hover:bg-muted-foreground/20 rounded p-0.5",children:e.jsx(gr,{className:"h-3 w-3"})})]},Xe.email))})]}),e.jsx(Gc,{}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{htmlFor:"vt-subject",children:"Subject"}),e.jsx(pe,{id:"vt-subject",value:O,onChange:Xe=>U(Xe.target.value)})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{htmlFor:"vt-message",children:"Message"}),e.jsx(Rs,{id:"vt-message",value:W,onChange:Xe=>V(Xe.target.value),rows:6,className:"resize-y"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Each email opens with a personal greeting using the contact's first name."})]})]}),e.jsxs("div",{className:"space-y-2 min-w-0",children:[e.jsxs(ee,{className:"flex items-center gap-1.5",children:[e.jsx(Ca,{className:"h-3.5 w-3.5"}),"Preview"]}),e.jsx("div",{className:"rounded-xl border overflow-hidden bg-muted/20",children:e.jsx("iframe",{title:"Email preview",srcDoc:`${qe}`,className:"w-full h-[420px] lg:h-[560px] border-0 bg-white",sandbox:""})})]})]}),e.jsxs("div",{className:Pt("flex flex-wrap items-center justify-between gap-3 pt-2 border-t"),children:[e.jsxs("p",{className:"text-sm text-muted-foreground",children:[e.jsx("span",{className:"font-semibold text-foreground",children:ke.length.toLocaleString()})," recipient",ke.length===1?"":"s",X&&ie>0&&e.jsxs("span",{children:[" · sent ",ie]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx($,{variant:"outline",onClick:()=>t(!1),disabled:X,children:"Cancel"}),e.jsxs($,{onClick:ze,disabled:X||ke.length===0||!O.trim(),className:"gap-2",children:[X?e.jsx(kt,{className:"h-4 w-4 animate-spin"}):e.jsx(Yr,{className:"h-4 w-4"}),X?"Sending...":`Send${ke.length?` to ${ke.length}`:""}`]})]})]})]})})}function yhr({openHouseId:s}){const{data:t=[],isLoading:n}=mOs(s),r=pOs(s),a=gOs(s),i=t.filter(l=>l.checked_in_at).length;return e.jsxs("div",{className:"rounded-xl border border-border bg-card/50",children:[e.jsxs("div",{className:"flex items-center justify-between px-4 py-3 border-b border-border",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(bb,{className:"h-4 w-4 text-primary"}),e.jsx("span",{className:"text-sm font-semibold",children:"RSVPs"}),e.jsx(Be,{variant:"secondary",className:"text-[11px]",children:t.length})]}),t.length>0&&e.jsxs("span",{className:"text-xs text-muted-foreground",children:[i," checked in"]})]}),n?e.jsx("div",{className:"px-4 py-6 text-sm text-muted-foreground",children:"Loading RSVPs…"}):t.length===0?e.jsxs("div",{className:"px-4 py-6 text-center",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"No RSVPs yet."}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Send an invite to your database to start filling the list."})]}):e.jsx("ul",{className:"divide-y divide-border",children:t.map(l=>e.jsxs("li",{className:"flex items-center gap-3 px-4 py-3",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("span",{className:"text-sm font-medium truncate",children:[l.first_name,l.last_name].filter(Boolean).join(" ")}),l.checked_in_at&&e.jsxs(Be,{className:"text-[10px] gap-1",children:[e.jsx(la,{className:"h-3 w-3"}),"Checked in"]}),l.has_agent&&e.jsxs(Be,{variant:"outline",className:"text-[10px] gap-1",children:[e.jsx(y2,{className:"h-3 w-3"}),l.working_with_agent_name||"Has an agent"]})]}),e.jsxs("div",{className:"flex items-center gap-3 mt-0.5 text-xs text-muted-foreground flex-wrap",children:[l.email&&e.jsxs("span",{className:"flex items-center gap-1 truncate",children:[e.jsx(mn,{className:"h-3 w-3"}),l.email]}),l.phone&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Da,{className:"h-3 w-3"}),l.phone]})]}),l.message&&e.jsxs("p",{className:"text-xs text-muted-foreground mt-1 italic",children:["“",l.message,"”"]})]}),e.jsx($,{variant:l.checked_in_at?"secondary":"outline",size:"sm",className:"h-8 text-xs",onClick:()=>a.mutate({id:l.id,checkedIn:!l.checked_in_at}),children:l.checked_in_at?"Undo":"Check in"}),e.jsx($,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0 text-muted-foreground hover:text-destructive","aria-label":"Delete RSVP",onClick:()=>r.mutate(l.id),children:e.jsx(Wn,{className:"h-4 w-4"})})]},l.id))})]})}function vhr({summary:s,stats:t,search:n,onSearchChange:r,onCreate:a}){return e.jsx("section",{className:"hub-ink relative overflow-hidden rounded-2xl p-5 sm:p-6",children:e.jsxs("div",{className:"relative flex flex-col gap-5",children:[e.jsxs("div",{className:"flex flex-col gap-4 lg:flex-row lg:items-start lg:justify-between",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-xs uppercase tracking-wider hub-ink-muted",children:"Agent OS"}),e.jsx("h1",{className:"mt-1 text-2xl font-bold sm:text-3xl",children:"Guest Book"}),e.jsx("p",{className:"mt-1 text-sm hub-ink-muted",children:s})]}),e.jsxs("div",{className:"flex flex-col items-start gap-2 sm:items-end",children:[e.jsxs("button",{onClick:a,className:"inline-flex items-center gap-2 rounded-full bg-background px-4 py-2 text-sm font-semibold text-foreground shadow-sm transition-transform hover:scale-[1.02]",children:[e.jsx(dn,{className:"h-4 w-4"}),"New Open House"]}),e.jsxs("span",{className:"inline-flex items-center gap-1.5 text-xs hub-ink-muted",children:[e.jsx(Jp,{className:"h-3.5 w-3.5",style:{color:"hsl(var(--hub-glow))"}}),"Every event gets a sign-in page & QR code"]})]})]}),e.jsxs("div",{className:"relative",children:[e.jsx(Kr,{className:"pointer-events-none absolute left-3.5 top-1/2 h-4 w-4 -translate-y-1/2 opacity-70"}),e.jsx(pe,{value:n,onChange:i=>r(i.target.value),placeholder:"Search by address, event name, or city...",className:"h-11 rounded-xl border-transparent bg-white/10 pl-10 text-current placeholder:text-current/50 focus-visible:ring-2 focus-visible:ring-white/30"})]}),e.jsx("div",{className:"-mx-1 flex gap-2 overflow-x-auto px-1 pb-1 scrollbar-hide",children:t.map(i=>e.jsxs("button",{type:"button",onClick:i.onClick,disabled:!i.onClick,className:Pt("hub-glass min-w-[118px] shrink-0 rounded-xl px-4 py-3 text-left transition-all",i.onClick?"cursor-pointer hover:scale-[1.02]":"cursor-default opacity-80",i.active&&"ring-2 ring-white/50"),children:[e.jsx("div",{className:"text-lg font-bold leading-none",children:i.value}),e.jsx("div",{className:"mt-1.5 text-[11px] uppercase tracking-wide hub-ink-muted",children:i.label})]},i.key))})]})})}const sTt={buying:"bg-emerald-500/10 text-emerald-700 dark:text-emerald-300 border-emerald-500/20",selling:"bg-blue-500/10 text-blue-700 dark:text-blue-300 border-blue-500/20",neighbor:"bg-amber-500/10 text-amber-700 dark:text-amber-300 border-amber-500/20",browsing:"bg-muted text-muted-foreground border-border"};function bhr({visitors:s,onExport:t,onShare:n}){if(!s.length)return e.jsxs("div",{className:"rounded-xl border border-dashed border-border bg-muted/20 px-6 py-10 text-center",children:[e.jsx("div",{className:"mx-auto mb-3 flex h-12 w-12 items-center justify-center rounded-2xl bg-primary/10",children:e.jsx(Zn,{className:"h-6 w-6 text-primary"})}),e.jsx("p",{className:"text-sm font-semibold text-foreground",children:"No sign-ins yet"}),e.jsx("p",{className:"mx-auto mt-1 max-w-sm text-xs text-muted-foreground",children:"Share the link or print the QR flyer so visitors can sign in from their phone."}),n&&e.jsxs($,{variant:"outline",size:"sm",className:"mt-4 gap-1.5",onClick:n,children:[e.jsx(zd,{className:"h-3.5 w-3.5"}),"Get the share link"]})]});const r=s.filter(a=>a.visitor_intent==="buying"&&!a.has_agent).length;return e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("p",{className:"text-xs font-semibold text-foreground",children:[s.length," Visitor",s.length!==1?"s":""]}),r>0&&e.jsxs("span",{className:"inline-flex items-center gap-1 rounded-full border border-orange-500/20 bg-orange-500/10 px-2 py-0.5 text-[11px] font-medium text-orange-700 dark:text-orange-300",children:[e.jsx(nh,{className:"h-3 w-3"}),r," hot"]})]}),e.jsxs("div",{className:"flex gap-1.5",children:[e.jsx(dDe,{className:"h-7 text-xs",label:"Mail visitors",build:()=>({source:"guestbook",contactEmails:s.map(a=>(a.email||"").trim().toLowerCase()).filter(Boolean),name:"Open house thank-you",message:`Hi %FIRST_NAME%, Thank you for stopping by the open house! If you have any questions about the home or the neighborhood, I am always happy to help.`})}),e.jsxs($,{variant:"outline",size:"sm",onClick:t,className:"h-7 gap-1 text-xs",children:[e.jsx(di,{className:"h-3 w-3"}),"Export CSV"]})]})]}),e.jsx("div",{className:"max-h-[420px] overflow-auto rounded-xl border border-border",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{className:"sticky top-0 z-10 bg-muted/80 backdrop-blur",children:e.jsxs("tr",{className:"text-[11px] uppercase tracking-wide text-muted-foreground",children:[e.jsx("th",{className:"p-2.5 text-left font-semibold",children:"Name"}),e.jsx("th",{className:"hidden p-2.5 text-left font-semibold sm:table-cell",children:"Contact"}),e.jsx("th",{className:"hidden p-2.5 text-left font-semibold md:table-cell",children:"Intent"}),e.jsx("th",{className:"p-2.5 text-left font-semibold",children:"Time"})]})}),e.jsx("tbody",{children:s.map(a=>{var o,c;const i=a.visitor_intent==="buying"&&!a.has_agent,l=sTt[a.visitor_intent||""]||sTt.browsing;return e.jsxs("tr",{className:Pt("border-t border-border/50 transition-colors hover:bg-muted/40",i&&"bg-orange-500/[0.06]"),children:[e.jsx("td",{className:"p-2.5",children:e.jsxs("div",{className:"flex items-center gap-2.5",children:[e.jsx("div",{className:Pt("flex h-8 w-8 shrink-0 items-center justify-center rounded-full text-xs font-bold",i?"bg-orange-500/15 text-orange-700 dark:text-orange-300":"bg-primary/10 text-primary"),children:((c=(o=a.first_name)==null?void 0:o[0])==null?void 0:c.toUpperCase())||"?"}),e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"truncate font-medium text-foreground",children:[a.first_name,a.last_name?` ${a.last_name}`:""]}),i&&e.jsx("div",{className:"text-[11px] font-medium text-orange-600 dark:text-orange-400",children:"Buyer · no agent"})]})]})}),e.jsxs("td",{className:"hidden p-2.5 text-muted-foreground sm:table-cell",children:[a.email&&e.jsx("div",{className:"max-w-[200px] truncate",children:a.email}),a.phone&&e.jsx("div",{className:"text-xs",children:a.phone}),a.visitor_address?e.jsx("div",{className:"max-w-[200px] truncate text-xs",children:a.visitor_address}):null]}),e.jsx("td",{className:"hidden p-2.5 md:table-cell",children:a.visitor_intent?e.jsx("span",{className:Pt("inline-flex rounded-full border px-2 py-0.5 text-[11px] font-medium capitalize",l),children:a.visitor_intent}):a.partial_signin?e.jsx("span",{className:"inline-flex rounded-full border border-amber-500/20 bg-amber-500/10 px-2 py-0.5 text-[11px] font-medium text-amber-700 dark:text-amber-300",children:"Didn't finish"}):null}),e.jsx("td",{className:"p-2.5 text-xs text-muted-foreground",children:en(new Date(a.created_at),"h:mm a")})]},a.id)})})]})})]})}const EAe="guestbook.relevelup.com";function _hr(){const{data:s,isLoading:t}=jFs(),n=NFs(),r=tBt(),a=kFs(),[i,l]=j.useState(!1),[o,c]=j.useState(null),[d,u]=j.useState(""),[h,m]=j.useState("all"),[f,g]=j.useState(!1),{user:x}=vs(),y=Sa(),[v,b]=j.useState(null),[w,S]=j.useState(null),[C,E]=j.useState(!1),I=j.useRef(null),[P,R]=j.useState({property_address:"",city:"",state:"",zip:"",event_date:en(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"}),D=te=>{var ce;const J=(ce=te.target.files)==null?void 0:ce[0];if(J){if(J.size>5*1024*1024){_a({title:"Photo must be under 5MB",variant:"destructive"});return}b(J),S(URL.createObjectURL(J))}},O=()=>{b(null),S(null),I.current&&(I.current.value="")},U=async()=>{if(!P.property_address){_a({title:P.event_type==="community"?"Event name is required":"Address is required",variant:"destructive"});return}let te;if(v&&x){E(!0);const ce=v.name.split(".").pop(),_e=`${y}/${Date.now()}.${ce}`,{error:he}=await q.storage.from("open-house-photos").upload(_e,v,{upsert:!0});if(he){_a({title:"Photo upload failed",description:he.message,variant:"destructive"}),E(!1);return}const{data:ue}=q.storage.from("open-house-photos").getPublicUrl(_e);te=ue.publicUrl,E(!1)}const J=P.kind==="virtual"?{...P,start_time:void 0,end_time:void 0,photo_url:te}:{...P,photo_url:te};await n.mutateAsync(J),l(!1),R({property_address:"",city:"",state:"",zip:"",event_date:en(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"}),O()},W=te=>{navigator.clipboard.writeText(`https://${EAe}/${te}`),_a({title:"Link copied!"})},V=en(new Date,"yyyy-MM-dd"),G=j.useMemo(()=>{const te=s??[],J=d.trim().toLowerCase(),ce=ke=>!J||[ke.property_address,ke.city,ke.state].filter(Boolean).join(" ").toLowerCase().includes(J),_e=te.filter(ce),he=_e.filter(ke=>ke.kind==="virtual"),ue=_e.filter(ke=>ke.kind!=="virtual"),ve=ue.filter(ke=>ke.event_date===V),Ee=ue.filter(ke=>ke.event_date>V).sort((ke,Ve)=>ke.event_date.localeCompare(Ve.event_date)),Se=ue.filter(ke=>ke.event_dateVe.event_date.localeCompare(ke.event_date)),Le=te.reduce((ke,Ve)=>ke+(Ve.visitor_count||0),0),Fe=te.reduce((ke,Ve)=>ke+(Ve.qr_scan_count||0),0);return{today:ve,upcoming:Ee,past:Se,virtual:he,totalSignIns:Le,totalScans:Fe}},[s,d,V]),Y=G.today.length+G.upcoming.length,X=Y>0?`${Y} upcoming · ${G.totalSignIns.toLocaleString()} total sign-ins`:`${G.totalSignIns.toLocaleString()} total sign-ins collected`,ae=te=>h==="all"||h===te,ie=te=>m(J=>J===te?"all":te),ne=te=>e.jsx(whr,{openHouse:te,isExpanded:o===te.id,onToggle:()=>c(o===te.id?null:te.id),onCopyLink:()=>W(te.slug||""),onToggleActive:()=>r.mutate({id:te.id,is_active:!te.is_active}),onDelete:()=>a.mutate(te.id),isToday:te.kind!=="virtual"&&te.event_date===V},te.id);return e.jsxs(Vs,{title:"Guest Book",children:[e.jsx(Ml,{children:e.jsx("title",{children:"Guest Book | LevelUp"})}),e.jsxs("div",{className:"space-y-6",children:[e.jsx(vhr,{summary:X,search:d,onSearchChange:u,onCreate:()=>l(!0),stats:[{key:"today",label:"Live Today",value:G.today.length,onClick:()=>ie("today"),active:h==="today"},{key:"upcoming",label:"Upcoming",value:G.upcoming.length,onClick:()=>ie("upcoming"),active:h==="upcoming"},{key:"virtual",label:"Virtual Tours",value:G.virtual.length,onClick:()=>ie("virtual"),active:h==="virtual"},{key:"signins",label:"Total Sign-Ins",value:G.totalSignIns.toLocaleString()},{key:"scans",label:"Total QR Scans",value:G.totalScans.toLocaleString()}]}),e.jsx("div",{className:"flex justify-end",children:e.jsxs(zs,{open:i,onOpenChange:l,children:[e.jsx(jl,{asChild:!0,children:e.jsx("span",{className:"sr-only",children:"Open create dialog"})}),e.jsxs(Os,{className:"sm:max-w-lg max-h-[90vh] flex flex-col",children:[e.jsxs(Us,{children:[e.jsx(Bs,{children:"Create Open House"}),e.jsx(Ir,{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(ee,{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:()=>R(te=>({...te,kind:"physical"})),className:`p-3 rounded-lg border text-left transition-all ${P.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:()=>R(te=>({...te,kind:"virtual",event_type:"property"})),className:`p-3 rounded-lg border text-left transition-all ${P.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"})]})]})]}),P.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:()=>R(te=>({...te,event_type:"property"})),className:`flex-1 px-3 py-2 rounded-md text-sm font-medium transition-colors ${P.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:()=>R(te=>({...te,event_type:"community"})),className:`flex-1 px-3 py-2 rounded-md text-sm font-medium transition-colors ${P.event_type==="community"?"bg-primary text-primary-foreground shadow-sm":"text-muted-foreground hover:text-foreground"}`,children:"Community Event"})]})}),P.kind==="virtual"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{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:()=>R(te=>({...te,tour_mode:"rooms"})),className:`p-3 rounded-lg border text-left transition-all ${P.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:()=>R(te=>({...te,tour_mode:"single_video"})),className:`p-3 rounded-lg border text-left transition-all ${P.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(ee,{children:P.event_type==="community"?"Event Name *":"Property Address *"}),e.jsx(pe,{value:P.property_address,onChange:te=>R(J=>({...J,property_address:te.target.value})),placeholder:P.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(ee,{children:"City"}),e.jsx(pe,{value:P.city,onChange:te=>R(J=>({...J,city:te.target.value})),placeholder:"Austin"})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"State"}),e.jsx(pe,{value:P.state,onChange:te=>R(J=>({...J,state:te.target.value})),placeholder:"TX",maxLength:2})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"ZIP"}),e.jsx(pe,{value:P.zip,onChange:te=>R(J=>({...J,zip:te.target.value})),placeholder:"78701"})]})]}),P.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(ee,{children:"Date"}),e.jsx(pe,{type:"date",value:P.event_date,onChange:te=>R(J=>({...J,event_date:te.target.value}))})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Start Time"}),e.jsx(pe,{type:"time",value:P.start_time,onChange:te=>R(J=>({...J,start_time:te.target.value}))})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"End Time"}),e.jsx(pe,{type:"time",value:P.end_time,onChange:te=>R(J=>({...J,end_time:te.target.value}))})]})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Welcome Message"}),e.jsx(Rs,{value:P.agent_greeting,onChange:te=>R(J=>({...J,agent_greeting:te.target.value})),placeholder:"Welcome! Please sign in below."})]}),e.jsxs("div",{children:[e.jsx(ee,{children:P.event_type==="community"?"Event Photo":"Property Photo"}),e.jsx("input",{ref:I,type:"file",accept:"image/*",onChange:D,className:"hidden"}),w?e.jsxs("div",{className:"relative mt-1 rounded-xl overflow-hidden border border-border",children:[e.jsx("img",{src:w,alt:"Property preview",className:"w-full h-40 object-cover"}),e.jsx("button",{type:"button",onClick:O,className:"absolute top-2 right-2 bg-black/60 hover:bg-black/80 text-white rounded-full p-1 transition-colors",children:e.jsx(gr,{className:"h-4 w-4"})})]}):e.jsxs("button",{type:"button",onClick:()=>{var te;return(te=I.current)==null?void 0:te.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(Av,{className:"h-6 w-6"}),e.jsxs("span",{className:"text-sm",children:["Add a ",P.event_type==="community"?"cover":"property"," photo"]}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"Max 5MB"})]})]}),e.jsx($,{onClick:U,disabled:n.isPending||C,className:"w-full",children:C?"Uploading photo...":n.isPending?"Creating...":P.kind==="virtual"?"Create Virtual Open House":P.event_type==="community"?"Create Community Event":"Create Open House"})]})]})]})}),t?e.jsx("div",{className:"grid gap-4",children:[1,2].map(te=>e.jsx(Ne,{className:"animate-pulse",children:e.jsxs(Ct,{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"})]})},te))}):s!=null&&s.length?e.jsxs("div",{className:"space-y-8",children:[G.today.length>0&&ae("today")&&e.jsxs("section",{className:"space-y-3",children:[e.jsx(AUe,{title:"Happening Today",count:G.today.length,accent:!0}),e.jsx("div",{className:"space-y-4",children:G.today.map(ne)})]}),G.upcoming.length>0&&ae("upcoming")&&e.jsxs("section",{className:"space-y-3",children:[e.jsx(AUe,{title:"Upcoming",count:G.upcoming.length}),e.jsx("div",{className:"space-y-4",children:G.upcoming.map(ne)})]}),G.virtual.length>0&&ae("virtual")&&e.jsxs("section",{className:"space-y-3",children:[e.jsx(AUe,{title:"Virtual Tours",count:G.virtual.length}),e.jsx("div",{className:"space-y-4",children:G.virtual.map(ne)})]}),G.past.length>0&&h==="all"&&e.jsxs("section",{className:"space-y-3",children:[e.jsxs("button",{onClick:()=>g(te=>!te),className:"flex w-full items-center justify-between rounded-xl border border-border bg-card px-4 py-3 text-left transition-colors hover:bg-muted/40",children:[e.jsxs("span",{className:"flex items-center gap-2 text-sm font-semibold text-foreground",children:[e.jsx(Lw,{className:"h-4 w-4 text-muted-foreground"}),"Past Open Houses",e.jsx("span",{className:"rounded-full bg-muted px-2 py-0.5 text-[11px] font-medium text-muted-foreground",children:G.past.length})]}),f?e.jsx(v1,{className:"h-4 w-4 text-muted-foreground"}):e.jsx(Tl,{className:"h-4 w-4 text-muted-foreground"})]}),f&&e.jsx("div",{className:"space-y-4",children:G.past.map(ne)})]}),Y===0&&G.virtual.length===0&&G.past.length===0&&e.jsx(Ne,{className:"border-dashed",children:e.jsxs(Ie,{className:"py-12 text-center text-sm text-muted-foreground",children:["No open houses match “",d,"”."]})})]}):e.jsx(Ne,{className:"border-dashed",children:e.jsxs(Ie,{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(Jp,{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($,{onClick:()=>l(!0),children:[e.jsx(dn,{className:"h-4 w-4 mr-2"}),"Create Your First Open House"]})]})})]})]})}function AUe({title:s,count:t,accent:n}){return e.jsxs("div",{className:"flex items-center gap-2.5",children:[n&&e.jsxs("span",{className:"relative flex h-2.5 w-2.5",children:[e.jsx("span",{className:"absolute inline-flex h-full w-full animate-ping rounded-full bg-emerald-400 opacity-70"}),e.jsx("span",{className:"relative inline-flex h-2.5 w-2.5 rounded-full bg-emerald-500"})]}),e.jsx("h2",{className:"text-sm font-semibold uppercase tracking-wide text-foreground",children:s}),e.jsx("span",{className:"rounded-full bg-muted px-2 py-0.5 text-[11px] font-medium text-muted-foreground",children:t}),e.jsx("div",{className:"h-px flex-1 bg-border"})]})}function whr({openHouse:s,isExpanded:t,onToggle:n,onCopyLink:r,onToggleActive:a,onDelete:i,isToday:l}){const{data:o}=eBt(t?s.id:void 0),{data:c}=tt({queryKey:["agent-profile-flyer",s.agent_id],queryFn:async()=>{const{data:P,error:R}=await q.from("profiles").select("name, avatar_url, phone, title, brokerages:brokerage_id(name)").eq("id",s.agent_id).single();if(R)throw R;const D=P.brokerages;return{...P,brokerage_name:(D==null?void 0:D.name)||null}},enabled:!!s.agent_id}),[d,u]=j.useState(!1),[h,m]=j.useState(!1),[f,g]=j.useState(!1),[x,y]=j.useState(!1),v=j.useRef(null),b=`https://${EAe}/${s.slug}`,w=P=>{if(!P)return"";const[R,D]=P.split(":"),O=parseInt(R),U=O>=12?"PM":"AM";return`${O>12?O-12:O||12}:${D} ${U}`},S=()=>{if(!(o!=null&&o.length))return;const P=["First Name","Last Name","Email","Phone","Address","Intent","Wants Market Updates","Message","Signed In"],R=o.map(V=>[V.first_name,V.last_name||"",V.email||"",V.phone||"",V.visitor_address||"",V.visitor_intent||"",V.wants_market_updates?"Yes":"No",(V.message||"").replace(/"/g,'""'),en(new Date(V.created_at),"MM/dd/yyyy h:mm a")]),D=[P,...R].map(V=>V.map(G=>`"${G}"`).join(",")).join(` `),O=new Blob([D],{type:"text/csv"}),U=URL.createObjectURL(O),W=document.createElement("a");W.href=U,W.download=`${s.property_address.replace(/[^a-zA-Z0-9]/g,"-")}-visitors.csv`,W.click(),URL.revokeObjectURL(U)},C=j.useCallback(()=>{if(!v.current)return;const P=v.current.querySelector("svg");if(!P)return;const R=new XMLSerializer().serializeToString(P),D=document.createElement("canvas");D.width=1024,D.height=1024;const O=D.getContext("2d"),U=new Image;U.onload=()=>{O==null||O.drawImage(U,0,0,1024,1024);const W=document.createElement("a");W.download=`${s.property_address.replace(/[^a-zA-Z0-9]/g,"-")}-qr.png`,W.href=D.toDataURL("image/png"),W.click()},U.src="data:image/svg+xml;base64,"+btoa(unescape(encodeURIComponent(R)))},[s.property_address]),E=j.useCallback(()=>{var Ae;if(!v.current)return;const P=v.current.querySelector("svg");if(!P)return;const R=new XMLSerializer().serializeToString(P),D="data:image/svg+xml;base64,"+btoa(unescape(encodeURIComponent(R))),O=en(new Date(s.event_date+"T00:00:00"),"EEEE, MMMM d, yyyy"),U=s.start_time?`${w(s.start_time)}${s.end_time?" – "+w(s.end_time):""}`:"",W=[s.city,s.state].filter(Boolean).join(", "),V=s.agent_greeting||"Welcome! Please sign in below.",G=!!s.photo_url,Y=!!c,X=G||Y,ae=G&&Y,ie=ae?"0.35in 0.75in 0.3in":"0.55in 0.75in 0.45in",ne=ae?"28px":"34px",te=ae?"0.2in 0.75in":X?"0.3in 0.75in":"0.4in 0.75in",J=X?"0.15in":"0.3in",ce=X?"0.15in":"0.3in",_e=ae?"14px 36px":"22px 44px",he=ae?"20px":"24px",ue=X?"0.2in":"0.35in",ve=ae?"1.8in":"2.4in",Ee=X?"0.15in":"0.3in",Se=ae?"140px":X?"160px":"200px",Le=ae?"16px":"24px",Fe=ae?"10px 20px":"16px 28px",ke=ae?"44px":"56px",Ve="0.15in",je=window.open("","_blank");je&&(je.document.write(` Open House – ${s.property_address}
${s.event_type==="community"?"Community Event":"Open House"}
${s.property_address}
${W?`
${W}${s.zip?" "+s.zip:""}
`:""}
Date
${O}
${U?`
Time
${U}
`:""}
${V}
${c?`
${c.avatar_url?`${c.name}`:`
${((Ae=c.name)==null?void 0:Ae.charAt(0))||"A"}
`}
Hosted By
${c.name}
${c.title?`
${c.title}
`:""} ${c.brokerage_name?`
${c.brokerage_name}
`:""} ${c.phone?`
${c.phone}
`:""}
`:""} ${s.photo_url?`Property`:""}
QR Code
Scan to Sign In
Point your phone camera at the QR code
`),je.document.close(),setTimeout(()=>{je.focus(),je.print()},500))},[s,b,c]),I=async()=>{y(!0);try{const{error:P}=await q.functions.invoke("guestbook-email-link",{body:{openHouseId:s.id}});if(P)throw P;_a({title:"Email sent!",description:"Check your inbox for the guest book link."})}catch(P){_a({title:"Failed to send",description:P.message,variant:"destructive"})}finally{y(!1)}};return e.jsxs(Ne,{className:Pt("relative overflow-hidden transition-all",s.is_active?"border-border hover:border-primary/40 hover:shadow-md":"opacity-70",l&&"border-emerald-500/40 shadow-[0_0_0_1px_hsl(var(--primary)/0.06)]"),children:[e.jsx("span",{className:Pt("absolute inset-y-0 left-0 w-1",l?"bg-emerald-500":s.kind==="virtual"?"bg-purple-500/70":"bg-primary/40")}),e.jsx(Ct,{className:"pb-3 pl-5",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(At,{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:[l&&e.jsxs(Be,{className:"shrink-0 gap-1 border-none bg-emerald-500/15 text-[11px] text-emerald-700 dark:text-emerald-300",children:[e.jsx(Nb,{className:"h-3 w-3"}),"Today"]}),e.jsx(Be,{variant:s.is_active?"default":"secondary",className:"shrink-0 text-[11px]",children:s.is_active?"Active":"Inactive"}),s.kind==="virtual"?e.jsxs(Be,{variant:"outline",className:"shrink-0 gap-1 text-[11px] bg-purple-500/10 text-purple-700 dark:text-purple-300 border-purple-500/20",children:[e.jsx(Ca,{className:"h-3 w-3"}),"Virtual"]}):e.jsxs(Be,{variant:"outline",className:"shrink-0 gap-1 text-[11px] bg-emerald-500/10 text-emerald-700 dark:text-emerald-300 border-emerald-500/20",children:[e.jsx(ci,{className:"h-3 w-3"}),"In-Person"]}),s.agent_name&&e.jsxs(Be,{variant:"outline",className:"shrink-0 gap-1 text-[11px] bg-blue-500/10 text-blue-700 dark:text-blue-300 border-blue-500/20",children:[e.jsx(sl,{className:"h-3 w-3"}),s.agent_name]}),s.event_type==="community"&&e.jsxs(Be,{variant:"outline",className:"shrink-0 gap-1 text-[11px]",children:[e.jsx(ji,{className:"h-3 w-3"}),"Community"]})]})]}),e.jsx($,{variant:"ghost",size:"icon",onClick:n,className:"shrink-0 -mr-2 -mt-1",children:t?e.jsx(v1,{className:"h-4 w-4"}):e.jsx(Tl,{className:"h-4 w-4"})})]}),e.jsxs(Gn,{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(ci,{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(da,{className:"h-3 w-3"}),"Always on"]}):e.jsxs(e.Fragment,{children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Ta,{className:"h-3 w-3"}),en(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(da,{className:"h-3 w-3"}),w(s.start_time),s.end_time?` – ${w(s.end_time)}`:""]})]})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs("span",{className:"inline-flex items-center gap-1.5 rounded-lg bg-muted/60 px-2.5 py-1 text-xs font-semibold text-foreground",children:[e.jsx(Zn,{className:"h-3.5 w-3.5 text-primary"}),s.visitor_count,e.jsx("span",{className:"font-normal text-muted-foreground",children:"signed in"})]}),s.qr_scan_count>0&&e.jsxs("span",{className:"inline-flex items-center gap-1.5 rounded-lg bg-muted/60 px-2.5 py-1 text-xs font-semibold text-foreground",children:[e.jsx(Jp,{className:"h-3.5 w-3.5 text-primary"}),s.qr_scan_count,e.jsx("span",{className:"font-normal text-muted-foreground",children:"scans"})]})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs($,{variant:"outline",size:"sm",onClick:()=>window.location.href=`/mission-control/guest-book/live/${s.id}`,className:"h-8 gap-1.5 text-xs text-emerald-600 border-emerald-500/30 hover:bg-emerald-500/10 dark:text-emerald-400",children:[e.jsx(Nb,{className:"h-3.5 w-3.5"}),"Live"]}),e.jsxs($,{variant:"outline",size:"sm",onClick:r,className:"h-8 gap-1.5 text-xs",children:[e.jsx(Ha,{className:"h-3.5 w-3.5"}),"Copy Link"]}),e.jsxs($,{variant:"outline",size:"sm",onClick:()=>u(!0),className:"h-8 gap-1.5 text-xs",children:[e.jsx(Jp,{className:"h-3.5 w-3.5"}),"QR Code"]}),s.kind==="virtual"?e.jsxs($,{variant:"outline",size:"sm",onClick:()=>g(!0),className:"h-8 gap-1.5 text-xs text-primary border-primary/30 hover:bg-primary/10",children:[e.jsx(zd,{className:"h-3.5 w-3.5"}),"Email Tour"]}):e.jsxs(e.Fragment,{children:[e.jsxs($,{variant:"outline",size:"sm",onClick:()=>g(!0),className:"h-8 gap-1.5 text-xs text-primary border-primary/30 hover:bg-primary/10",children:[e.jsx(mn,{className:"h-3.5 w-3.5"}),"Invite"]}),e.jsxs($,{variant:"outline",size:"sm",onClick:()=>window.open(`${b}?kiosk=1`,"_blank"),className:"h-8 gap-1.5 text-xs",children:[e.jsx(dV,{className:"h-3.5 w-3.5"}),"Tablet Mode"]})]}),e.jsxs($,{variant:"outline",size:"sm",onClick:()=>m(!0),className:"h-8 gap-1.5 text-xs",children:[e.jsx(Sd,{className:"h-3.5 w-3.5"}),"Settings"]}),e.jsxs(Uu,{children:[e.jsx(qu,{asChild:!0,children:e.jsx($,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0","aria-label":"More actions",children:e.jsx(h_,{className:"h-4 w-4"})})}),e.jsxs(Eu,{align:"end",className:"w-52",children:[e.jsxs(ja,{onClick:()=>window.open(b,"_blank"),children:[e.jsx(kr,{className:"mr-2 h-4 w-4"}),"Preview sign-in page"]}),s.kind==="virtual"?e.jsxs(ja,{onClick:()=>window.open(`/guestbook/${s.slug}?preview=1`,"_blank"),children:[e.jsx(Ca,{className:"mr-2 h-4 w-4"}),"Preview tour"]}):e.jsxs(ja,{onClick:()=>window.open(`https://${EAe}/rsvp/${s.slug}`,"_blank"),children:[e.jsx(bb,{className:"mr-2 h-4 w-4"}),"Preview RSVP page"]}),e.jsxs(ja,{onClick:a,children:[s.is_active?e.jsx($g,{className:"mr-2 h-4 w-4"}):e.jsx(Ca,{className:"mr-2 h-4 w-4"}),s.is_active?"Deactivate":"Activate"]}),e.jsx(R0,{}),e.jsxs(ja,{onClick:i,className:"text-destructive focus:text-destructive",children:[e.jsx(Wn,{className:"mr-2 h-4 w-4"}),"Delete"]})]})]})]})]})}),t&&e.jsxs(Ie,{className:"pt-0",children:[e.jsx(Gc,{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://",EAe,"/",s.slug]})]}),e.jsx(bhr,{visitors:o??[],onExport:S}),s.kind!=="virtual"&&e.jsx("div",{className:"mt-4",children:e.jsx(yhr,{openHouseId:s.id})}),s.kind==="virtual"&&e.jsx("div",{className:"mt-4",children:e.jsx(phr,{openHouseId:s.id})}),s.enable_survey&&e.jsx("div",{className:"mt-4",children:e.jsx(mhr,{openHouseId:s.id})})]}),e.jsx(zs,{open:d,onOpenChange:u,children:e.jsxs(Os,{className:"sm:max-w-sm",children:[e.jsxs(Us,{children:[e.jsx(Bs,{children:"QR Code"}),e.jsx(Ir,{className:"truncate",children:s.property_address})]}),e.jsxs("div",{className:"flex flex-col items-center gap-4 py-4",children:[e.jsx("div",{ref:v,className:"bg-white p-4 rounded-xl",children:e.jsx(fk,{value:b,size:240,level:"H"})}),e.jsx("p",{className:"text-xs text-muted-foreground text-center break-all",children:b}),e.jsxs("div",{className:"flex gap-2 w-full",children:[e.jsxs($,{variant:"outline",className:"flex-1",onClick:C,children:[e.jsx(di,{className:"h-4 w-4 mr-2"}),"Download"]}),e.jsxs($,{variant:"outline",className:"flex-1",onClick:E,children:[e.jsx(FE,{className:"h-4 w-4 mr-2"}),"Print Flyer"]})]}),e.jsxs($,{variant:"default",className:"w-full",onClick:I,disabled:x,children:[e.jsx(mn,{className:"h-4 w-4 mr-2"}),x?"Sending...":"Email Link to Me"]})]})]})}),e.jsx(uhr,{open:h,onOpenChange:m,openHouse:s}),e.jsx(xhr,{open:f,onOpenChange:g,variant:s.kind==="virtual"?"tour":"rsvp",openHouse:{id:s.id,slug:s.slug,property_address:s.property_address,city:s.city,state:s.state,zip:s.zip,photo_url:s.photo_url,event_date:s.event_date,start_time:s.start_time,end_time:s.end_time}})]})}const jhr=H2({full_name:vl().trim().min(2,"Please enter your name").max(120),email:vl().trim().email("Please enter a valid email").max(200),brokerage:vl().trim().min(2,"Please enter your brokerage").max(160)}),nTt=s=>s?s.replace(/<\s*(br|\/p|\/div|\/li)\s*\/?\s*>/gi,` `).replace(/<[^>]*>/g,"").replace(/ /g," ").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,'"').replace(/'/g,"'").replace(/\n{2,}/g,` `).trim():"",Nhr=s=>{if(!s)return"";const t=s/(1024*1024);return t>=1?`${t.toFixed(1)} MB`:`${Math.max(1,Math.round(s/1024))} KB`};function khr(){var S;const{slug:s}=Wi(),[t,n]=j.useState(!0),[r,a]=j.useState(null),[i,l]=j.useState([]),[o,c]=j.useState(!1),[d,u]=j.useState({full_name:"",email:"",brokerage:""}),[h,m]=j.useState(""),[f,g]=j.useState(!1),[x,y]=j.useState(!1);j.useEffect(()=>{let C=!0;return(async()=>{n(!0);const{data:E,error:I}=await q.functions.invoke("resource-kit-public",{body:{slug:s}});C&&(I||!(E!=null&&E.kit)?c(!0):(a(E.kit),l(E.files??[])),n(!1))})(),()=>{C=!1}},[s]);const v=async C=>{C.preventDefault(),m("");const E=jhr.safeParse(d);if(!E.success){m(E.error.issues[0].message);return}g(!0);try{const{data:I,error:P}=await q.functions.invoke("resource-kit-unlock",{body:{slug:s,...E.data}});if(P)throw P;if(I!=null&&I.error)throw new Error("Something went wrong. Please try again.");l(I.files??[]),y(!0)}catch(I){m(I.message||"Something went wrong. Please try again.")}finally{g(!1)}};if(t)return e.jsx("div",{className:"min-h-screen bg-slate-950 p-6",children:e.jsxs("div",{className:"max-w-5xl mx-auto space-y-6 pt-16",children:[e.jsx(yn,{className:"h-10 w-2/3 bg-white/10"}),e.jsx(yn,{className:"h-64 w-full bg-white/10"})]})});if(o||!r)return e.jsx("div",{className:"min-h-screen bg-slate-950 flex items-center justify-center px-6 text-center",children:e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold text-white",children:"This resource isn't available"}),e.jsx("p",{className:"mt-2 text-slate-400",children:"The link may have expired or been unpublished."})]})});const b=nTt(r.subheadline),w=(b||`Download ${r.name} — a free resource for real estate agents.`).replace(/\s*\n\s*/g," ").slice(0,155);return e.jsxs("div",{className:"min-h-screen bg-slate-950 text-white",children:[e.jsxs(Ml,{children:[e.jsx("title",{children:`${r.headline} | LevelUp`.slice(0,60)}),e.jsx("meta",{name:"description",content:w}),e.jsx("link",{rel:"canonical",href:`${window.location.origin}/resources/${r.slug}`}),e.jsx("meta",{property:"og:title",content:r.headline}),e.jsx("meta",{property:"og:description",content:w}),e.jsx("meta",{property:"og:type",content:"website"}),e.jsx("meta",{property:"og:url",content:`${window.location.origin}/resources/${r.slug}`}),e.jsx("meta",{name:"twitter:card",content:"summary_large_image"}),r.hero_image_url&&e.jsx("meta",{property:"og:image",content:r.hero_image_url}),r.hero_image_url&&e.jsx("meta",{name:"twitter:image",content:r.hero_image_url})]}),e.jsxs("div",{className:"pointer-events-none fixed inset-0 opacity-60",children:[e.jsx("div",{className:"absolute -top-40 -left-32 h-96 w-96 rounded-full bg-amber-500/20 blur-3xl"}),e.jsx("div",{className:"absolute top-1/3 -right-32 h-96 w-96 rounded-full bg-sky-500/20 blur-3xl"})]}),e.jsxs("div",{className:"relative max-w-6xl mx-auto px-5 py-12 md:py-20",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm font-bold tracking-tight mb-10",children:[e.jsxs("span",{className:"text-white",children:["Level",e.jsx("span",{className:"text-amber-400",children:"Up"})]}),e.jsx("span",{className:"text-slate-500 font-medium",children:"· Free Agent Resource"})]}),e.jsxs("div",{className:"grid lg:grid-cols-[1.15fr_1fr] gap-10 lg:gap-14 items-start",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"inline-flex items-center gap-2 rounded-full border border-white/10 bg-white/5 px-3 py-1 text-[12px] font-semibold text-amber-300",children:[e.jsx(Nn,{className:"h-3.5 w-3.5"})," Instant download"]}),e.jsx("h1",{className:"mt-5 text-4xl md:text-5xl font-black tracking-tight leading-[1.05]",children:r.headline}),b&&e.jsx("p",{className:"mt-5 text-lg text-slate-300 leading-relaxed max-w-xl whitespace-pre-line",children:b}),r.hero_image_url&&e.jsx("div",{className:"mt-8 overflow-hidden rounded-2xl border border-white/10 shadow-2xl",children:e.jsx("img",{src:r.hero_image_url,alt:r.name,loading:"lazy",className:"w-full h-56 md:h-72 object-cover"})}),((S=r.benefits)==null?void 0:S.length)>0&&e.jsx("ul",{className:"mt-8 space-y-3",children:r.benefits.map((C,E)=>e.jsxs("li",{className:"flex items-start gap-3 text-slate-200",children:[e.jsx(qr,{className:"h-5 w-5 shrink-0 text-amber-400 mt-0.5"}),e.jsx("span",{className:"leading-relaxed",children:nTt(C)||C})]},E))}),i.length>0&&e.jsxs("div",{className:"mt-10",children:[e.jsx("div",{className:"text-xs uppercase tracking-widest text-slate-400 font-semibold mb-3",children:"What's inside"}),e.jsx("div",{className:"space-y-2",children:i.map(C=>e.jsxs("div",{className:"flex items-center gap-3 rounded-xl border border-white/10 bg-white/5 px-4 py-3",children:[e.jsx(Jr,{className:"h-4 w-4 text-slate-300 shrink-0"}),e.jsx("span",{className:"flex-1 text-sm text-slate-100 truncate",children:C.name}),e.jsx("span",{className:"text-[11px] text-slate-400",children:Nhr(C.file_size)}),x&&C.file_url?e.jsx($,{asChild:!0,size:"sm",className:"h-8 rounded-full bg-amber-400 text-slate-900 hover:bg-amber-300",children:e.jsxs("a",{href:C.file_url,target:"_blank",rel:"noopener noreferrer",download:!0,children:[e.jsx(di,{className:"h-3.5 w-3.5 mr-1"})," Download"]})}):e.jsx(pc,{className:"h-3.5 w-3.5 text-slate-500"})]},C.id))})]})]}),e.jsx("div",{className:"lg:sticky lg:top-10",children:e.jsx("div",{className:"rounded-3xl border border-white/10 bg-white/[0.06] backdrop-blur p-6 md:p-8 shadow-2xl",children:x?e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"mx-auto h-14 w-14 rounded-2xl bg-emerald-400/15 grid place-items-center",children:e.jsx(qr,{className:"h-7 w-7 text-emerald-400"})}),e.jsx("h2",{className:"mt-4 text-xl font-bold",children:"You're all set"}),e.jsxs("p",{className:"mt-1.5 text-sm text-slate-300",children:["Your files are unlocked on this page and a copy is on the way to ",d.email,"."]}),e.jsx("div",{className:"mt-6 space-y-2 text-left",children:i.map(C=>C.file_url&&e.jsxs("a",{href:C.file_url,target:"_blank",rel:"noopener noreferrer",download:!0,className:"flex items-center gap-3 rounded-xl border border-white/10 bg-white/5 px-4 py-3 hover:bg-white/10 transition",children:[e.jsx(di,{className:"h-4 w-4 text-amber-400"}),e.jsx("span",{className:"text-sm truncate",children:C.name})]},C.id))}),e.jsxs("div",{className:"mt-7 rounded-2xl bg-slate-900/60 border border-white/10 p-5 text-left",children:[e.jsx("div",{className:"font-semibold",children:"Want the whole toolbox?"}),e.jsx("p",{className:"mt-1 text-sm text-slate-300",children:"LevelUp gives agents marketing, CRM, listing tools, and coaching in one place."}),e.jsx($,{asChild:!0,className:"mt-4 w-full h-11 rounded-xl bg-white text-slate-900 font-bold hover:bg-slate-100",children:e.jsx("a",{href:"https://dashboard.relevelup.com/trial",children:"Try LevelUp Free"})})]})]}):e.jsxs(e.Fragment,{children:[e.jsx("h2",{className:"text-xl font-bold",children:"Get instant access"}),e.jsx("p",{className:"mt-1.5 text-sm text-slate-300",children:"Tell us where to send it and the files unlock right here."}),e.jsxs("form",{onSubmit:v,className:"mt-6 space-y-4",children:[e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"full_name",className:"text-slate-200",children:"Agent name"}),e.jsx(pe,{id:"full_name",value:d.full_name,onChange:C=>u({...d,full_name:C.target.value}),placeholder:"Jane Smith",className:"mt-1.5 h-11 bg-white/5 border-white/15 text-white placeholder:text-slate-500"})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"email",className:"text-slate-200",children:"Email"}),e.jsx(pe,{id:"email",type:"email",value:d.email,onChange:C=>u({...d,email:C.target.value}),placeholder:"you@email.com",className:"mt-1.5 h-11 bg-white/5 border-white/15 text-white placeholder:text-slate-500"})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"brokerage",className:"text-slate-200",children:"Brokerage"}),e.jsx(pe,{id:"brokerage",value:d.brokerage,onChange:C=>u({...d,brokerage:C.target.value}),placeholder:"Your brokerage",className:"mt-1.5 h-11 bg-white/5 border-white/15 text-white placeholder:text-slate-500"})]}),h&&e.jsx("p",{className:"text-sm text-red-300",children:h}),e.jsxs($,{type:"submit",disabled:f,className:"w-full h-12 rounded-xl bg-amber-400 text-slate-900 font-bold hover:bg-amber-300",children:[f?"Unlocking…":r.cta_text,e.jsx(ei,{className:"h-4 w-4 ml-1.5"})]}),e.jsxs("p",{className:"flex items-start gap-2 text-[11px] leading-relaxed text-slate-400",children:[e.jsx(bm,{className:"h-3.5 w-3.5 shrink-0 mt-0.5"}),"By downloading, you agree to receive occasional emails from LevelUp about tools and resources for agents. Unsubscribe anytime."]})]})]})})})]})]})]})}Wot.workerSrc=Kot;const Shr={signature:wf,initials:hV,date_signed:Kc,printed_name:sl,text:uV},mls={signature:"Signature",initials:"Initials",date_signed:"Date signed",printed_name:"Printed name",text:"Text"};function fls(){return new Intl.DateTimeFormat("en-US",{timeZone:"America/New_York",month:"2-digit",day:"2-digit",year:"numeric"}).format(new Date)}function Chr(s,t){const n=document.createElement("canvas");n.width=600,n.height=t?200:140;const r=n.getContext("2d");return r.fillStyle="#12233f",r.font=`${t?84:64}px "Segoe Script", "Brush Script MT", "Snell Roundhand", cursive`,r.textAlign="center",r.textBaseline="middle",r.fillText(s,n.width/2,n.height/2+10),n.toDataURL("image/png")}function Ahr(){var G,Y,X,ae;const{token:s}=Wi(),t=Qn(),[n,r]=j.useState(!0),[a,i]=j.useState(null),[l,o]=j.useState(null),[c,d]=j.useState(null),[u,h]=j.useState(null),m=j.useRef(null),f=j.useRef([]),[g,x]=j.useState({}),[y,v]=j.useState({}),[b,w]=j.useState(null),[S,C]=j.useState(!1),[E,I]=j.useState(!1),[P,R]=j.useState(!1);j.useEffect(()=>{let ie=!1;return r(!0),i(null),o(null),d(null),h(null),x({}),C(!1),(async()=>{var J;const{data:ne,error:te}=await q.functions.invoke("forms-sign-public",{body:{action:"load",token:s}});if(!ie){if(te||ne!=null&&ne.error)i((ne==null?void 0:ne.error)||"This signing link could not be loaded.");else if(ne.state==="already_signed")d("signed");else{o(ne);const ce={};for(const _e of ne.fields||[])_e.field_kind==="printed_name"&&(ce[_e.id]={value:((J=ne.signer)==null?void 0:J.full_name)||""}),_e.field_kind==="date_signed"&&(ce[_e.id]={value:fls()});x(ce)}r(!1)}})(),()=>{ie=!0}},[s]),j.useEffect(()=>{let ie=!1;const ne=m.current;if(!(!(l!=null&&l.pdf_url)||!ne))return(async()=>{try{const J=await(await fetch(l.pdf_url)).arrayBuffer(),ce=await wPe({data:J}).promise;if(ie)return;ne.innerHTML="",f.current=[];const _e=Math.min(ne.clientWidth-16||700,820);for(let he=1;he<=ce.numPages;he++){const ue=await ce.getPage(he);if(ie)return;const ve=ue.getViewport({scale:1}),Ee=_e/ve.width,Se=ue.getViewport({scale:Ee*(window.devicePixelRatio||1)}),Le=document.createElement("div");Le.className="relative mx-auto shadow",Le.style.width=`${_e}px`,Le.style.height=`${ve.height*Ee}px`;const Fe=document.createElement("canvas");Fe.width=Math.floor(Se.width),Fe.height=Math.floor(Se.height),Fe.style.width="100%",Fe.style.height="100%",Fe.className="rounded-md border border-border bg-white",Le.appendChild(Fe),ne.appendChild(Le),f.current[he-1]=Le;const ke=Fe.getContext("2d");ke&&await ue.render({canvasContext:ke,viewport:Se}).promise}ie||x(he=>({...he}))}catch{ie||i("The document could not be displayed.")}})(),()=>{ie=!0}},[l==null?void 0:l.pdf_url]);const D=(l==null?void 0:l.fields)||[],O=D.filter(ie=>{var ne,te;return ie.is_required&&!((ne=g[ie.id])!=null&&ne.value)&&!((te=g[ie.id])!=null&&te.png)}),U=async()=>{if(!S){re.error("Please agree to sign electronically first.");return}if(O.length){re.error("Please complete every highlighted field.");return}I(!0);try{const{data:ie,error:ne}=await q.functions.invoke("forms-sign-public",{body:{action:"submit",token:s,consent:!0,fields:D.filter(te=>g[te.id]).map(te=>{var J,ce;return{mapping_id:te.id,value:(J=g[te.id])==null?void 0:J.value,signature_png:(ce=g[te.id])==null?void 0:ce.png}})}});if(ne||ie!=null&&ie.error)throw new Error((ie==null?void 0:ie.error)||(ne==null?void 0:ne.message)||"Could not submit");ie!=null&&ie.next_token&&h({token:ie.next_token,title:ie.next_title??null}),d("signed"),window.scrollTo({top:0})}catch(ie){re.error((ie==null?void 0:ie.message)||"Could not finish signing")}finally{I(!1)}},W=async()=>{const ie=window.prompt("Optional: tell the sender why you are declining.")??"";R(!0),await q.functions.invoke("forms-sign-public",{body:{action:"decline",token:s,reason:ie}}),d("declined"),R(!1)},V=(ie,ne)=>{x(te=>({...te,[ie.id]:ne})),w(null)};return n?e.jsx("div",{className:"flex min-h-screen items-center justify-center bg-slate-100",children:e.jsx(kt,{className:"h-8 w-8 animate-spin text-[#406E71]"})}):a?e.jsx(mhe,{icon:e.jsx(ku,{className:"h-8 w-8 text-destructive"}),title:"Link unavailable",body:a}):c==="declined"?e.jsx(mhe,{icon:e.jsx(ku,{className:"h-8 w-8 text-muted-foreground"}),title:"Document declined",body:"The sender has been notified that you declined to sign this document."}):c==="signed"&&u?e.jsx(mhe,{icon:e.jsx(qr,{className:"h-8 w-8 text-emerald-600"}),title:"Signed — one more to go",body:u.title?`Next up in this packet: ${u.title}. Your signature is saved and ready to reuse.`:"There is one more document in this packet. Your signature is saved and ready to reuse.",action:e.jsx($,{className:"mt-5 bg-[#406E71] hover:bg-[#375d60]",onClick:()=>t(`/sign/${u.token}`),children:"Continue to the next document"})}):c==="signed"||(l==null?void 0:l.state)==="already_signed"?e.jsx(mhe,{icon:e.jsx(qr,{className:"h-8 w-8 text-emerald-600"}),title:"You're all set",body:"Thank you — your signature has been recorded. Once everyone has signed, the completed document is delivered to your agent automatically."}):e.jsxs("div",{className:"min-h-screen bg-slate-100 pb-40",children:[e.jsx("header",{className:"sticky top-0 z-20 border-b bg-[#2a4c64] px-4 py-3 text-white shadow-md",children:e.jsxs("div",{className:"mx-auto max-w-3xl",children:[e.jsx("p",{className:"text-[10px] uppercase tracking-[0.18em] opacity-70",children:"LevelUp Forms"}),e.jsx("h1",{className:"truncate text-base font-semibold",children:(G=l==null?void 0:l.envelope)==null?void 0:G.title}),e.jsxs("p",{className:"text-xs opacity-80",children:["Signing as ",(Y=l==null?void 0:l.signer)==null?void 0:Y.full_name]})]})}),((X=l==null?void 0:l.envelope)==null?void 0:X.message)&&e.jsx("div",{className:"mx-auto mt-4 max-w-3xl rounded-lg border bg-white px-4 py-3 text-sm text-slate-600 shadow-sm",children:l.envelope.message}),e.jsxs("div",{className:"mx-auto mt-4 max-w-3xl space-y-4 px-2",children:[e.jsx("div",{ref:m,className:"space-y-4"}),D.map(ie=>{const ne=f.current[ie.page_index];if(!ne)return null;const te=g[ie.id],J=!!(te!=null&&te.png||te!=null&&te.value),ce=Shr[ie.field_kind];return e.jsx(rTt,{target:ne,children:e.jsx("button",{onClick:()=>w(ie),className:`absolute flex items-center justify-center gap-1 rounded-sm border-2 transition-colors ${J?"border-emerald-500 bg-emerald-500/10":"animate-pulse border-[#406E71] bg-[#406E71]/15 hover:bg-[#406E71]/25"}`,style:{left:`${ie.pos_x*100}%`,top:`${ie.pos_y*100}%`,width:`${ie.width*100}%`,height:`${ie.height*100}%`},children:te!=null&&te.png?e.jsx("img",{src:te.png,alt:ie.label||"Signature",className:"max-h-full max-w-full object-contain"}):te!=null&&te.value?e.jsx("span",{className:"truncate px-1 text-[10px] font-medium text-emerald-800",children:te.value}):e.jsxs("span",{className:"flex items-center gap-1 px-1 text-[10px] font-semibold text-[#2f5c60]",children:[e.jsx(ce,{className:"h-3 w-3"})," ",ie.label||mls[ie.field_kind]]})})},ie.id)}),((l==null?void 0:l.data_overlays)||[]).map(ie=>{const ne=f.current[ie.page_index];return!ne||!ie.value?null:e.jsx(rTt,{target:ne,children:e.jsx("div",{className:"pointer-events-none absolute flex items-center",style:{left:`${ie.pos_x*100}%`,top:`${ie.pos_y*100}%`,width:`${ie.width*100}%`,height:`${ie.height*100}%`},children:e.jsx("span",{className:"truncate px-0.5 text-[10px] text-slate-900",children:ie.value})})},ie.id)})]}),e.jsx("div",{className:"fixed inset-x-0 bottom-0 z-30 border-t bg-white/95 px-4 py-3 shadow-[0_-4px_20px_rgba(0,0,0,0.08)] backdrop-blur",children:e.jsxs("div",{className:"mx-auto flex max-w-3xl flex-col gap-2",children:[e.jsxs("label",{className:"flex items-start gap-2 text-xs text-slate-600",children:[e.jsx(ai,{checked:S,onCheckedChange:ie=>C(!!ie),className:"mt-0.5"}),e.jsx("span",{children:l==null?void 0:l.consent_text})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs($,{className:"flex-1 bg-[#406E71] hover:bg-[#355c5f]",disabled:E||!S||O.length>0,onClick:U,children:[E?e.jsx(kt,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(wf,{className:"mr-2 h-4 w-4"}),O.length>0?`${O.length} field${O.length===1?"":"s"} left`:"Finish signing"]}),e.jsx($,{variant:"ghost",size:"sm",disabled:P,onClick:W,className:"text-muted-foreground",children:"Decline"})]})]})}),e.jsx(Ehr,{field:b,signerName:((ae=l==null?void 0:l.signer)==null?void 0:ae.full_name)||"",current:b?g[b.id]:void 0,adopted:y,onAdopt:(ie,ne)=>{v(te=>({...te,[ie]:ne})),x(te=>{var ce;const J={...te};for(const _e of D)_e.field_kind===ie&&!((ce=J[_e.id])!=null&&ce.png)&&(J[_e.id]={png:ne});return J})},onClose:()=>w(null),onApply:V})]})}function mhe({icon:s,title:t,body:n,action:r}){return e.jsx("div",{className:"flex min-h-screen items-center justify-center bg-slate-100 p-4",children:e.jsxs("div",{className:"w-full max-w-md rounded-2xl border bg-white p-8 text-center shadow-sm",children:[e.jsx("div",{className:"mx-auto mb-4 flex h-14 w-14 items-center justify-center rounded-full bg-slate-100",children:s}),e.jsx("h1",{className:"text-lg font-semibold",children:t}),e.jsx("p",{className:"mt-2 text-sm text-muted-foreground",children:n}),r]})})}function rTt({target:s,children:t}){return wv.createPortal(t,s)}function Ehr({field:s,signerName:t,current:n,adopted:r,onAdopt:a,onClose:i,onApply:l}){const o=(s==null?void 0:s.field_kind)==="signature"||(s==null?void 0:s.field_kind)==="initials",c=(s==null?void 0:s.field_kind)==="initials"?"initials":"signature",[d,u]=j.useState(""),h=j.useRef(null),m=j.useRef(!1),[f,g]=j.useState("");j.useEffect(()=>{if(!s)return;g((n==null?void 0:n.value)||(s.field_kind==="printed_name"?t:s.field_kind==="date_signed"?fls():"")),u(s.field_kind==="initials"?t.split(" ").map(S=>S[0]).join(""):t);const w=h.current;if(w){const S=w.getContext("2d");S==null||S.clearRect(0,0,w.width,w.height)}},[s==null?void 0:s.id]);const x=w=>{const S=h.current;if(!S)return;m.current=!0,S.setPointerCapture(w.pointerId);const C=S.getContext("2d"),E=S.getBoundingClientRect();C.strokeStyle="#12233f",C.lineWidth=3,C.lineCap="round",C.beginPath(),C.moveTo((w.clientX-E.left)/E.width*S.width,(w.clientY-E.top)/E.height*S.height)},y=w=>{if(!m.current)return;const S=h.current;if(!S)return;const C=S.getContext("2d"),E=S.getBoundingClientRect();C.lineTo((w.clientX-E.left)/E.width*S.width,(w.clientY-E.top)/E.height*S.height),C.stroke()},v=()=>{m.current=!1},b=(w,S)=>{s&&(S&&o&&a(c,w),l(s,{png:w}))};return e.jsx(Wy,{open:!!s,onOpenChange:w=>!w&&i(),children:e.jsxs(py,{side:"bottom",className:"mx-auto max-w-lg rounded-t-2xl",children:[e.jsx(D0,{className:"text-left",children:e.jsx(F0,{className:"text-base",children:(s==null?void 0:s.label)||(s?mls[s.field_kind]:"")})}),s&&o&&e.jsxs(ha,{defaultValue:r[c]?"saved":"draw",className:"mt-3",children:[e.jsxs(ma,{className:"grid w-full grid-cols-3",children:[e.jsx(Zt,{value:"draw",children:"Draw"}),e.jsx(Zt,{value:"type",children:"Type"}),e.jsx(Zt,{value:"saved",disabled:!r[c],children:"Saved"})]}),e.jsxs(Xt,{value:"draw",className:"space-y-3 pt-3",children:[e.jsx("canvas",{ref:h,width:640,height:220,className:"h-40 w-full touch-none rounded-lg border bg-white",onPointerDown:x,onPointerMove:y,onPointerUp:v}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs($,{variant:"outline",size:"sm",onClick:()=>{var S;const w=h.current;(S=w==null?void 0:w.getContext("2d"))==null||S.clearRect(0,0,w.width,w.height)},children:[e.jsx(Rq,{className:"mr-1 h-3.5 w-3.5"})," Clear"]}),e.jsxs($,{size:"sm",className:"flex-1 bg-[#406E71] hover:bg-[#355c5f]",onClick:()=>{const w=h.current;w&&b(w.toDataURL("image/png"),!0)},children:["Use this ",s.field_kind==="initials"?"initials":"signature"," everywhere"]})]})]}),e.jsxs(Xt,{value:"type",className:"space-y-3 pt-3",children:[e.jsx(pe,{value:d,onChange:w=>u(w.target.value),placeholder:"Type your name"}),d.trim()&&e.jsx("div",{className:"flex h-24 items-center justify-center rounded-lg border bg-white",children:e.jsx("span",{className:"text-3xl text-[#12233f]",style:{fontFamily:'"Segoe Script","Brush Script MT",cursive'},children:d})}),e.jsx($,{size:"sm",className:"w-full bg-[#406E71] hover:bg-[#355c5f]",disabled:!d.trim(),onClick:()=>b(Chr(d.trim(),s.field_kind==="signature"),!0),children:"Use this everywhere"})]}),e.jsx(Xt,{value:"saved",className:"space-y-3 pt-3",children:r[c]&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"flex h-24 items-center justify-center rounded-lg border bg-white p-2",children:e.jsx("img",{src:r[c],alt:"Saved signature",className:"max-h-full object-contain"})}),e.jsxs($,{size:"sm",className:"w-full bg-[#406E71] hover:bg-[#355c5f]",onClick:()=>b(r[c],!1),children:["Use saved ",s.field_kind==="initials"?"initials":"signature"]})]})})]}),s&&!o&&e.jsxs("div",{className:"mt-3 space-y-3",children:[e.jsx(pe,{value:f,onChange:w=>g(w.target.value),autoFocus:!0}),e.jsx($,{size:"sm",className:"w-full bg-[#406E71] hover:bg-[#355c5f]",disabled:!f.trim(),onClick:()=>l(s,{value:f.trim()}),children:"Apply"})]})]})})}const aTt="https://dashboard.relevelup.com/trial",Thr=["Full LevelUp Agent OS access","300+ marketing templates & AI tools","Cancel anytime — no risk"];function pQe({variant:s="full",className:t=""}){return s==="compact"?e.jsxs("div",{className:`rounded-2xl border border-amber-400/20 bg-gradient-to-br from-amber-500/10 to-transparent p-5 ${t}`,children:[e.jsxs("div",{className:"inline-flex items-center gap-1.5 text-[11px] font-semibold uppercase tracking-widest text-amber-300",children:[e.jsx(Nn,{className:"h-3.5 w-3.5"})," Free trial"]}),e.jsx("h3",{className:"mt-3 text-lg font-bold text-white leading-snug",children:"Try LevelUp free"}),e.jsx("p",{className:"mt-2 text-sm text-slate-300 leading-relaxed",children:"Everything you just read — plus the tools to actually run it. Start your free trial today."}),e.jsxs("a",{href:aTt,className:"mt-4 inline-flex w-full items-center justify-center gap-2 rounded-xl bg-amber-400 px-4 py-2.5 text-sm font-bold text-slate-950 transition hover:bg-amber-300",children:["Start free trial ",e.jsx(ei,{className:"h-4 w-4"})]})]}):e.jsxs("section",{className:`relative overflow-hidden rounded-3xl border border-amber-400/20 bg-gradient-to-br from-amber-500/15 via-slate-900 to-slate-900 p-8 md:p-12 ${t}`,children:[e.jsx("div",{className:"pointer-events-none absolute -top-24 -right-16 h-64 w-64 rounded-full bg-amber-400/20 blur-3xl"}),e.jsxs("div",{className:"relative",children:[e.jsxs("div",{className:"inline-flex items-center gap-2 rounded-full border border-white/10 bg-white/5 px-3 py-1 text-[12px] font-semibold text-amber-300",children:[e.jsx(Nn,{className:"h-3.5 w-3.5"})," Free trial · no credit card hassle"]}),e.jsx("h2",{className:"mt-5 text-3xl md:text-4xl font-black tracking-tight text-white leading-[1.1]",children:"Ready to put this into action?"}),e.jsx("p",{className:"mt-4 max-w-xl text-slate-300 leading-relaxed",children:"LevelUp gives real estate agents the marketing, CRM, and AI tools to win more listings — all in one place. Take it for a spin free."}),e.jsx("ul",{className:"mt-6 grid gap-2 sm:grid-cols-3",children:Thr.map(n=>e.jsxs("li",{className:"flex items-start gap-2 text-sm text-slate-200",children:[e.jsx(la,{className:"mt-0.5 h-4 w-4 shrink-0 text-amber-400"}),e.jsx("span",{children:n})]},n))}),e.jsxs("a",{href:aTt,className:"mt-8 inline-flex items-center gap-2 rounded-xl bg-amber-400 px-6 py-3 text-base font-bold text-slate-950 transition hover:bg-amber-300",children:["Start your free trial ",e.jsx(ei,{className:"h-5 w-5"})]})]})]})}const iTt=s=>{if(!s)return"";const[t,n,r]=s.split(/[-/T]/).map(Number);return new Intl.DateTimeFormat("en-US",{month:"long",day:"numeric",year:"numeric",timeZone:"America/New_York"}).format(new Date(Date.UTC(t,n-1,r,12)))},Mhr=s=>{const t=s.replace(/<[^>]*>/g," ").split(/\s+/).filter(Boolean).length;return Math.max(1,Math.round(t/220))};function Phr(){const[s,t]=j.useState([]),[n,r]=j.useState(!0),[a,i]=j.useState("all");j.useEffect(()=>{(async()=>{const{data:u}=await q.from("blog_posts").select("id, slug, title, excerpt, cover_image_url, category, featured, published_at, content").eq("status","published").order("published_at",{ascending:!1}).limit(200);t(u||[]),r(!1)})()},[]);const l=["all",...Array.from(new Set(s.map(u=>u.category).filter(Boolean)))],o=a==="all"?s:s.filter(u=>u.category===a),[c,...d]=o;return e.jsxs("div",{className:"min-h-screen bg-slate-950 text-white",children:[e.jsxs(Ml,{children:[e.jsx("title",{children:"The LevelUp Blog | Real Estate Growth Insights"}),e.jsx("meta",{name:"description",content:"Strategies, systems, and stories from the founder of LevelUp — helping real estate agents win more listings and build a business they love."}),e.jsx("link",{rel:"canonical",href:`${window.location.origin}/blog`}),e.jsx("meta",{property:"og:title",content:"The LevelUp Blog"}),e.jsx("meta",{property:"og:type",content:"website"}),e.jsx("meta",{property:"og:description",content:"Strategies, systems, and stories from the founder of LevelUp for real estate agents."}),e.jsx("meta",{name:"twitter:card",content:"summary_large_image"})]}),e.jsxs("div",{className:"pointer-events-none fixed inset-0 opacity-60",children:[e.jsx("div",{className:"absolute -top-40 -left-32 h-96 w-96 rounded-full bg-amber-500/20 blur-3xl"}),e.jsx("div",{className:"absolute top-1/3 -right-32 h-96 w-96 rounded-full bg-sky-500/20 blur-3xl"})]}),e.jsxs("div",{className:"relative mx-auto max-w-6xl px-5 py-12 md:py-16",children:[e.jsxs(wr,{to:"/",className:"flex items-center gap-2 text-sm font-bold tracking-tight",children:[e.jsxs("span",{className:"text-white",children:["Level",e.jsx("span",{className:"text-amber-400",children:"Up"})]}),e.jsx("span",{className:"font-medium text-slate-500",children:"· Blog"})]}),e.jsxs("header",{className:"mt-10 max-w-3xl",children:[e.jsxs("h1",{className:"text-4xl font-black leading-[1.05] tracking-tight md:text-6xl",children:["Ideas that move your ",e.jsx("span",{className:"text-amber-400",children:"real estate business"})," forward."]}),e.jsx("p",{className:"mt-5 text-lg leading-relaxed text-slate-300",children:"Strategies, systems, and honest lessons from the founder of LevelUp — written for agents who want to grow on purpose."})]}),l.length>2&&e.jsx("div",{className:"mt-8 flex flex-wrap gap-2",children:l.map(u=>e.jsx("button",{onClick:()=>i(u),className:`rounded-full border px-4 py-1.5 text-sm font-medium transition ${a===u?"border-amber-400/40 bg-amber-400/15 text-amber-200":"border-white/10 bg-white/5 text-slate-300 hover:bg-white/10"}`,children:u==="all"?"All articles":u},u))}),n?e.jsx("div",{className:"mt-12 grid gap-6 md:grid-cols-3",children:[0,1,2].map(u=>e.jsx(yn,{className:"h-72 w-full bg-white/10"},u))}):o.length===0?e.jsx("p",{className:"mt-16 text-slate-400",children:"No articles published yet — check back soon."}):e.jsxs(e.Fragment,{children:[c&&e.jsxs(wr,{to:`/blog/${c.slug}`,className:"group mt-12 grid gap-8 overflow-hidden rounded-3xl border border-white/10 bg-white/5 p-6 transition hover:border-amber-400/30 md:grid-cols-2 md:p-8",children:[c.cover_image_url&&e.jsx("div",{className:"overflow-hidden rounded-2xl",children:e.jsx("img",{src:c.cover_image_url,alt:c.title,className:"h-56 w-full object-cover transition duration-500 group-hover:scale-105 md:h-72"})}),e.jsxs("div",{className:"flex flex-col justify-center",children:[e.jsxs("div",{className:"flex items-center gap-3 text-xs text-slate-400",children:[c.category&&e.jsx(Be,{className:"border-amber-400/30 bg-amber-400/15 text-amber-200",children:c.category}),e.jsx("span",{children:iTt(c.published_at)}),e.jsxs("span",{className:"inline-flex items-center gap-1",children:[e.jsx(da,{className:"h-3 w-3"})," ",Mhr(c.content)," min read"]})]}),e.jsx("h2",{className:"mt-4 text-2xl font-bold leading-tight md:text-3xl",children:c.title}),c.excerpt&&e.jsx("p",{className:"mt-3 leading-relaxed text-slate-300",children:c.excerpt}),e.jsxs("span",{className:"mt-5 inline-flex items-center gap-2 text-sm font-semibold text-amber-300",children:["Read article ",e.jsx(ei,{className:"h-4 w-4 transition group-hover:translate-x-1"})]})]})]}),d.length>0&&e.jsx("div",{className:"mt-8 grid gap-6 md:grid-cols-3",children:d.map(u=>e.jsxs(wr,{to:`/blog/${u.slug}`,className:"group flex flex-col overflow-hidden rounded-2xl border border-white/10 bg-white/5 transition hover:border-amber-400/30",children:[u.cover_image_url?e.jsx("img",{src:u.cover_image_url,alt:u.title,loading:"lazy",className:"h-44 w-full object-cover transition duration-500 group-hover:scale-105"}):e.jsx("div",{className:"h-44 w-full bg-gradient-to-br from-amber-500/20 to-slate-900"}),e.jsxs("div",{className:"flex flex-1 flex-col p-5",children:[e.jsxs("div",{className:"flex items-center gap-2 text-xs text-slate-400",children:[u.category&&e.jsx("span",{className:"text-amber-300",children:u.category}),e.jsx("span",{children:iTt(u.published_at)})]}),e.jsx("h3",{className:"mt-2 text-lg font-bold leading-snug",children:u.title}),u.excerpt&&e.jsx("p",{className:"mt-2 line-clamp-3 text-sm leading-relaxed text-slate-400",children:u.excerpt}),e.jsxs("span",{className:"mt-4 inline-flex items-center gap-1.5 text-sm font-semibold text-amber-300",children:["Read ",e.jsx(ei,{className:"h-3.5 w-3.5 transition group-hover:translate-x-1"})]})]})]},u.id))})]}),e.jsx(pQe,{className:"mt-16"}),e.jsxs("footer",{className:"mt-14 border-t border-white/10 pt-8 text-sm text-slate-500",children:["© ",new Date().getFullYear()," LevelUp · ",e.jsx(wr,{to:"/",className:"hover:text-slate-300",children:"Home"})]})]})]})}const Ihr=s=>(s||"LevelUp Member").split(" ").map(t=>t[0]).slice(0,2).join("").toUpperCase(),Lhr=s=>{const[t,n]=s.split("T"),[r,a,i]=t.split("-").map(Number);return new Intl.DateTimeFormat("en-US",{month:"short",day:"numeric",year:"numeric",timeZone:"America/New_York"}).format(new Date(Date.UTC(r,a-1,i,Number((n||"12").slice(0,2))||12)))};function Rhr({postId:s,allowComments:t}){const{user:n}=vs(),[r,a]=j.useState([]),[i,l]=j.useState(!0),[o,c]=j.useState(""),[d,u]=j.useState(null),[h,m]=j.useState(""),[f,g]=j.useState(!1),x=j.useCallback(async()=>{l(!0);const{data:C,error:E}=await q.from("blog_comments").select("id, post_id, user_id, parent_id, body, created_at").eq("post_id",s).eq("is_hidden",!1).order("created_at",{ascending:!0});if(E){l(!1);return}const I=C||[],P=[...new Set(I.map(R=>R.user_id))];if(P.length){const{data:R}=await q.from("profiles").select("id, name, avatar_url").in("id",P),D=new Map((R||[]).map(O=>[O.id,O]));I.forEach(O=>{O.author=D.get(O.user_id)})}a(I),l(!1)},[s]);j.useEffect(()=>{x()},[x]);const y=async(C,E)=>{if(!n){re.error("Sign in to comment");return}if(!C.trim())return;g(!0);const{error:I}=await q.from("blog_comments").insert({post_id:s,user_id:n.id,parent_id:E,body:C.trim()});if(g(!1),I){re.error(I.message);return}c(""),m(""),u(null),re.success("Comment posted"),x()},v=async C=>{const{error:E}=await q.from("blog_comments").delete().eq("id",C);if(E){re.error(E.message);return}x()},b=r.filter(C=>!C.parent_id),w=C=>r.filter(E=>E.parent_id===C),S=({c:C,nested:E=!1})=>{var I,P,R;return e.jsxs("div",{className:`flex gap-3 ${E?"ml-10 mt-4":"mt-6"}`,children:[e.jsxs(Oa,{className:"h-9 w-9 shrink-0",children:[e.jsx(Li,{src:((I=C.author)==null?void 0:I.avatar_url)||void 0}),e.jsx(za,{className:"bg-white/10 text-xs text-white",children:Ihr((P=C.author)==null?void 0:P.name)})]}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("span",{className:"text-sm font-semibold text-white",children:((R=C.author)==null?void 0:R.name)||"LevelUp Member"}),e.jsx("span",{className:"text-xs text-slate-500",children:Lhr(C.created_at)})]}),e.jsx("p",{className:"mt-1 whitespace-pre-wrap text-[15px] leading-relaxed text-slate-300",children:C.body}),e.jsxs("div",{className:"mt-1.5 flex items-center gap-3",children:[!E&&n&&e.jsxs("button",{className:"inline-flex items-center gap-1 text-xs font-medium text-slate-400 hover:text-amber-300",onClick:()=>{u(d===C.id?null:C.id),m("")},children:[e.jsx(wJ,{className:"h-3 w-3"})," Reply"]}),(n==null?void 0:n.id)===C.user_id&&e.jsxs("button",{className:"inline-flex items-center gap-1 text-xs font-medium text-slate-500 hover:text-red-400",onClick:()=>v(C.id),children:[e.jsx(Wn,{className:"h-3 w-3"})," Delete"]})]}),d===C.id&&e.jsxs("div",{className:"mt-3 space-y-2",children:[e.jsx(Rs,{value:h,onChange:D=>m(D.target.value),placeholder:"Write a reply…",className:"border-white/10 bg-white/5 text-white placeholder:text-slate-500"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs($,{size:"sm",disabled:f,onClick:()=>y(h,C.id),children:[f&&e.jsx(kt,{className:"mr-1.5 h-3.5 w-3.5 animate-spin"})," Post reply"]}),e.jsx($,{size:"sm",variant:"ghost",className:"text-slate-400",onClick:()=>u(null),children:"Cancel"})]})]}),w(C.id).map(D=>e.jsx(S,{c:D,nested:!0},D.id))]})]})};return e.jsxs("section",{id:"comments",className:"mt-14 border-t border-white/10 pt-10",children:[e.jsxs("h2",{className:"flex items-center gap-2 text-xl font-bold text-white",children:[e.jsx(Th,{className:"h-5 w-5 text-amber-400"}),"Discussion ",r.length>0&&e.jsxs("span",{className:"text-slate-500",children:["(",r.length,")"]})]}),t?n?e.jsxs("div",{className:"mt-5 space-y-3",children:[e.jsx(Rs,{value:o,onChange:C=>c(C.target.value),placeholder:"Share your take with the LevelUp community…",rows:4,className:"border-white/10 bg-white/5 text-white placeholder:text-slate-500"}),e.jsxs($,{disabled:f||!o.trim(),onClick:()=>y(o,null),children:[f&&e.jsx(kt,{className:"mr-2 h-4 w-4 animate-spin"})," Post comment"]})]}):e.jsxs("div",{className:"mt-5 rounded-xl border border-white/10 bg-white/5 p-5 text-sm text-slate-300",children:[e.jsx(wr,{to:"/auth",className:"font-semibold text-amber-300 hover:underline",children:"Sign in"})," ","to join the conversation — comments are open to all LevelUp members."]}):e.jsx("p",{className:"mt-4 text-sm text-slate-400",children:"Comments are closed on this article."}),i?e.jsxs("div",{className:"mt-8 flex items-center gap-2 text-sm text-slate-400",children:[e.jsx(kt,{className:"h-4 w-4 animate-spin"})," Loading comments…"]}):b.length===0?e.jsx("p",{className:"mt-8 text-sm text-slate-500",children:"No comments yet — be the first."}):e.jsx("div",{className:"mt-2",children:b.map(C=>e.jsx(S,{c:C},C.id))})]})}const oTt=s=>{if(!s)return"";const[t,n,r]=s.split(/[-/T]/).map(Number);return new Intl.DateTimeFormat("en-US",{month:"long",day:"numeric",year:"numeric",timeZone:"America/New_York"}).format(new Date(Date.UTC(t,n-1,r,12)))},Dhr=s=>Math.max(1,Math.round(s.replace(/<[^>]*>/g," ").split(/\s+/).filter(Boolean).length/220));function Fhr(){var h;const{slug:s=""}=Wi(),[t,n]=j.useState(null),[r,a]=j.useState([]),[i,l]=j.useState(!0);j.useEffect(()=>{(async()=>{l(!0);const{data:m}=await q.from("blog_posts").select("*").eq("slug",s).eq("status","published").maybeSingle();if(n(m||null),l(!1),m){q.rpc("increment_blog_post_views",{_slug:s});const{data:f}=await q.from("blog_posts").select("id, slug, title, excerpt, cover_image_url, category, published_at, content").eq("status","published").neq("slug",s).order("published_at",{ascending:!1}).limit(3);a(f||[])}})()},[s]);const o=typeof window<"u"?`${window.location.origin}/blog/${s}`:"",c=async m=>{const f=encodeURIComponent((t==null?void 0:t.title)||"LevelUp"),g=encodeURIComponent(o),x={facebook:`https://www.facebook.com/sharer/sharer.php?u=${g}`,linkedin:`https://www.linkedin.com/sharing/share-offsite/?url=${g}`,twitter:`https://twitter.com/intent/tweet?url=${g}&text=${f}`,email:`mailto:?subject=${f}&body=${g}`};if(m==="copy"){await navigator.clipboard.writeText(o),re.success("Link copied");return}if(m==="native"&&navigator.share){try{await navigator.share({title:t==null?void 0:t.title,url:o})}catch{}return}window.open(x[m],"_blank","noopener,width=640,height=560")};if(i)return e.jsx("div",{className:"min-h-screen bg-slate-950 p-6",children:e.jsxs("div",{className:"mx-auto max-w-3xl space-y-6 pt-16",children:[e.jsx(yn,{className:"h-12 w-3/4 bg-white/10"}),e.jsx(yn,{className:"h-64 w-full bg-white/10"}),e.jsx(yn,{className:"h-40 w-full bg-white/10"})]})});if(!t)return e.jsx("div",{className:"flex min-h-screen items-center justify-center bg-slate-950 px-6 text-center",children:e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold text-white",children:"Article not found"}),e.jsx("p",{className:"mt-2 text-slate-400",children:"It may have been unpublished or moved."}),e.jsx(wr,{to:"/blog",className:"mt-5 inline-block font-semibold text-amber-300 hover:underline",children:"Back to the blog"})]})});const d=(t.seo_title||t.title).slice(0,60),u=(t.seo_description||t.excerpt||t.title).slice(0,155);return e.jsxs("div",{className:"min-h-screen bg-slate-950 text-white",children:[e.jsxs(Ml,{children:[e.jsx("title",{children:`${d} | LevelUp`}),e.jsx("meta",{name:"description",content:u}),e.jsx("link",{rel:"canonical",href:o}),e.jsx("meta",{property:"og:type",content:"article"}),e.jsx("meta",{property:"og:title",content:t.title}),e.jsx("meta",{property:"og:description",content:u}),e.jsx("meta",{property:"og:url",content:o}),t.cover_image_url&&e.jsx("meta",{property:"og:image",content:t.cover_image_url}),e.jsx("meta",{name:"twitter:card",content:"summary_large_image"}),t.cover_image_url&&e.jsx("meta",{name:"twitter:image",content:t.cover_image_url}),e.jsx("script",{type:"application/ld+json",children:JSON.stringify({"@context":"https://schema.org","@type":"BlogPosting",headline:t.title,description:u,image:t.cover_image_url||void 0,datePublished:t.published_at,author:{"@type":"Person",name:t.author_name},publisher:{"@type":"Organization",name:"LevelUp"},mainEntityOfPage:o})})]}),e.jsx("div",{className:"pointer-events-none fixed inset-0 opacity-50",children:e.jsx("div",{className:"absolute -top-40 -left-32 h-96 w-96 rounded-full bg-amber-500/20 blur-3xl"})}),e.jsxs("div",{className:"relative mx-auto max-w-6xl px-5 py-10 md:py-14",children:[e.jsxs(wr,{to:"/blog",className:"inline-flex items-center gap-2 text-sm font-medium text-slate-400 hover:text-white",children:[e.jsx(qa,{className:"h-4 w-4"})," All articles"]}),e.jsxs("div",{className:"mt-8 grid gap-12 lg:grid-cols-[minmax(0,1fr)_300px]",children:[e.jsxs("article",{className:"min-w-0",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-3 text-xs text-slate-400",children:[t.category&&e.jsx(Be,{className:"border-amber-400/30 bg-amber-400/15 text-amber-200",children:t.category}),e.jsx("span",{children:oTt(t.published_at)}),e.jsxs("span",{className:"inline-flex items-center gap-1",children:[e.jsx(da,{className:"h-3 w-3"})," ",Dhr(t.content)," min read"]})]}),e.jsx("h1",{className:"mt-4 text-3xl font-black leading-[1.1] tracking-tight md:text-5xl",children:t.title}),t.excerpt&&e.jsx("p",{className:"mt-5 text-lg leading-relaxed text-slate-300",children:t.excerpt}),e.jsxs("div",{className:"mt-7 flex items-center gap-3 border-y border-white/10 py-4",children:[e.jsxs(Oa,{className:"h-11 w-11",children:[e.jsx(Li,{src:t.author_avatar_url||void 0}),e.jsx(za,{className:"bg-amber-400/20 text-amber-200",children:t.author_name.split(" ").map(m=>m[0]).slice(0,2).join("")})]}),e.jsxs("div",{className:"flex-1",children:[e.jsx("div",{className:"text-sm font-semibold text-white",children:t.author_name}),e.jsx("div",{className:"text-xs text-slate-400",children:t.author_title})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx("button",{onClick:()=>c("copy"),title:"Copy link",className:"rounded-lg p-2 text-slate-400 hover:bg-white/10 hover:text-white",children:e.jsx(bd,{className:"h-4 w-4"})}),e.jsx("button",{onClick:()=>c("facebook"),title:"Share on Facebook",className:"rounded-lg p-2 text-slate-400 hover:bg-white/10 hover:text-white",children:e.jsx(Qp,{className:"h-4 w-4"})}),e.jsx("button",{onClick:()=>c("linkedin"),title:"Share on LinkedIn",className:"rounded-lg p-2 text-slate-400 hover:bg-white/10 hover:text-white",children:e.jsx(hy,{className:"h-4 w-4"})}),e.jsx("button",{onClick:()=>c("twitter"),title:"Share on X",className:"rounded-lg p-2 text-slate-400 hover:bg-white/10 hover:text-white",children:e.jsx(lee,{className:"h-4 w-4"})}),e.jsx("button",{onClick:()=>c("email"),title:"Share by email",className:"rounded-lg p-2 text-slate-400 hover:bg-white/10 hover:text-white",children:e.jsx(mn,{className:"h-4 w-4"})}),e.jsx("button",{onClick:()=>c("native"),title:"Share",className:"rounded-lg p-2 text-slate-400 hover:bg-white/10 hover:text-white md:hidden",children:e.jsx(zd,{className:"h-4 w-4"})})]})]}),t.cover_image_url&&e.jsx("img",{src:t.cover_image_url,alt:t.title,className:"mt-8 w-full rounded-2xl border border-white/10 object-cover"}),e.jsx("div",{className:"blog-content prose prose-invert mt-10 max-w-none prose-headings:font-bold prose-headings:tracking-tight prose-a:text-amber-300 prose-img:rounded-2xl prose-video:rounded-2xl",dangerouslySetInnerHTML:{__html:t.content}}),((h=t.tags)==null?void 0:h.length)>0&&e.jsx("div",{className:"mt-10 flex flex-wrap gap-2",children:t.tags.map(m=>e.jsxs("span",{className:"rounded-full border border-white/10 bg-white/5 px-3 py-1 text-xs text-slate-300",children:["#",m]},m))}),e.jsx(pQe,{className:"mt-14"}),e.jsx(Rhr,{postId:t.id,allowComments:t.allow_comments})]}),e.jsxs("aside",{className:"space-y-6 lg:sticky lg:top-8 lg:self-start",children:[e.jsx(pQe,{variant:"compact"}),r.length>0&&e.jsxs("div",{className:"rounded-2xl border border-white/10 bg-white/5 p-5",children:[e.jsx("div",{className:"text-xs font-semibold uppercase tracking-widest text-slate-400",children:"Keep reading"}),e.jsx("div",{className:"mt-4 space-y-4",children:r.map(m=>e.jsxs(wr,{to:`/blog/${m.slug}`,className:"group block",children:[e.jsx("div",{className:"text-sm font-semibold leading-snug text-slate-100 group-hover:text-amber-300",children:m.title}),e.jsx("div",{className:"mt-1 text-xs text-slate-500",children:oTt(m.published_at)})]},m.id))})]})]})]}),e.jsxs("footer",{className:"mt-16 border-t border-white/10 pt-8 text-sm text-slate-500",children:["© ",new Date().getFullYear()," LevelUp · ",e.jsx(wr,{to:"/blog",className:"hover:text-slate-300",children:"Blog"})]})]})]})}const Ohr=/^((?:https?:)?\/\/)?((?:www|m|music)\.)?((?:youtube\.com|youtu\.be|youtube-nocookie\.com))(\/(?:[\w-]+\?v=|embed\/|v\/)?)([\w-]+)(\S+)?$/,zhr=/^((?:https?:)?\/\/)?((?:www|m|music)\.)?((?:youtube\.com|youtu\.be|youtube-nocookie\.com))(\/(?:[\w-]+\?v=|embed\/|v\/)?)([\w-]+)(\S+)?$/g,pls=s=>s.match(Ohr),Bhr=(s,t)=>t?"https://www.youtube-nocookie.com/embed/videoseries?list=":s?"https://www.youtube-nocookie.com/embed/":"https://www.youtube.com/embed/",$hr=s=>s.searchParams.has("v")?{id:s.searchParams.get("v")}:s.hostname==="youtu.be"||s.pathname.includes("shorts")||s.pathname.includes("live")?{id:s.pathname.split("/").pop()}:s.searchParams.has("list")?{id:s.searchParams.get("list"),isPlaylist:!0}:null,Uhr=s=>{var t;const{url:n,allowFullscreen:r,autoplay:a,ccLanguage:i,ccLoadPolicy:l,controls:o,disableKBcontrols:c,enableIFrameApi:d,endTime:u,interfaceLanguage:h,ivLoadPolicy:m,loop:f,modestBranding:g,nocookie:x,origin:y,playlist:v,progressBarColor:b,startAt:w,rel:S}=s;if(!pls(n))return null;if(n.includes("/embed/"))return n;const C=new URL(n),{id:E,isPlaylist:I}=(t=$hr(C))!==null&&t!==void 0?t:{};if(!E)return null;const P=new URL(`${Bhr(x,I)}${E}`);return C.searchParams.has("t")&&P.searchParams.set("start",C.searchParams.get("t").replaceAll("s","")),r===!1&&P.searchParams.set("fs","0"),a&&P.searchParams.set("autoplay","1"),i&&P.searchParams.set("cc_lang_pref",i),l&&P.searchParams.set("cc_load_policy","1"),o||P.searchParams.set("controls","0"),c&&P.searchParams.set("disablekb","1"),d&&P.searchParams.set("enablejsapi","1"),u&&P.searchParams.set("end",u.toString()),h&&P.searchParams.set("hl",h),m&&P.searchParams.set("iv_load_policy",m.toString()),f&&P.searchParams.set("loop","1"),g&&P.searchParams.set("modestbranding","1"),y&&P.searchParams.set("origin",y),v&&P.searchParams.set("playlist",v),w&&P.searchParams.set("start",w.toString()),b&&P.searchParams.set("color",b),S!==void 0&&P.searchParams.set("rel",S.toString()),P.toString()},qhr=Rv.create({name:"youtube",addOptions(){return{addPasteHandler:!0,allowFullscreen:!0,autoplay:!1,ccLanguage:void 0,ccLoadPolicy:void 0,controls:!0,disableKBcontrols:!1,enableIFrameApi:!1,endTime:0,height:480,interfaceLanguage:void 0,ivLoadPolicy:0,loop:!1,modestBranding:!1,HTMLAttributes:{},inline:!1,nocookie:!1,origin:"",playlist:"",progressBarColor:void 0,width:640,rel:1}},inline(){return this.options.inline},group(){return this.options.inline?"inline":"block"},draggable:!0,addAttributes(){return{src:{default:null},start:{default:0},width:{default:this.options.width},height:{default:this.options.height}}},parseHTML(){return[{tag:"div[data-youtube-video] iframe"}]},addCommands(){return{setYoutubeVideo:s=>({commands:t})=>pls(s.src)?t.insertContent({type:this.name,attrs:s}):!1}},addPasteRules(){return this.options.addPasteHandler?[NJs({find:zhr,type:this.type,getAttributes:s=>({src:s.input})})]:[]},renderHTML({HTMLAttributes:s}){const t=Uhr({url:s.src,allowFullscreen:this.options.allowFullscreen,autoplay:this.options.autoplay,ccLanguage:this.options.ccLanguage,ccLoadPolicy:this.options.ccLoadPolicy,controls:this.options.controls,disableKBcontrols:this.options.disableKBcontrols,enableIFrameApi:this.options.enableIFrameApi,endTime:this.options.endTime,interfaceLanguage:this.options.interfaceLanguage,ivLoadPolicy:this.options.ivLoadPolicy,loop:this.options.loop,modestBranding:this.options.modestBranding,nocookie:this.options.nocookie,origin:this.options.origin,playlist:this.options.playlist,progressBarColor:this.options.progressBarColor,startAt:s.start||0,rel:this.options.rel});return s.src=t,["div",{"data-youtube-video":""},["iframe",ep(this.options.HTMLAttributes,{width:this.options.width,height:this.options.height,allowfullscreen:this.options.allowFullscreen,autoplay:this.options.autoplay,ccLanguage:this.options.ccLanguage,ccLoadPolicy:this.options.ccLoadPolicy,disableKBcontrols:this.options.disableKBcontrols,enableIFrameApi:this.options.enableIFrameApi,endTime:this.options.endTime,interfaceLanguage:this.options.interfaceLanguage,ivLoadPolicy:this.options.ivLoadPolicy,loop:this.options.loop,modestBranding:this.options.modestBranding,origin:this.options.origin,playlist:this.options.playlist,progressBarColor:this.options.progressBarColor,rel:this.options.rel},s)]]}}),Vhr=Rv.create({name:"videoEmbed",group:"block",atom:!0,draggable:!0,addAttributes(){return{src:{default:null},poster:{default:null}}},parseHTML(){return[{tag:"video[src]"}]},renderHTML({HTMLAttributes:s}){return["video",ep(s,{controls:"true",playsinline:"true",preload:"metadata",class:"w-full rounded-xl"})]}}),r0=({onClick:s,active:t,title:n,children:r,disabled:a})=>e.jsx($,{type:"button",variant:t?"secondary":"ghost",size:"sm",className:"h-8 w-8 p-0",title:n,disabled:a,onClick:s,children:r});function Hhr({content:s,onChange:t,placeholder:n="Write your article…"}){const[r,a]=j.useState(!1),[i,l]=j.useState(""),[o,c]=j.useState(!1),[d,u]=j.useState(""),[h,m]=j.useState(!1),f=j.useRef(null),g=j.useRef(null),x=G6e({extensions:[W6e.configure({heading:{levels:[2,3,4]}}),Uos,Y6e.configure({openOnClick:!1,HTMLAttributes:{class:"text-primary underline"}}),fHt.configure({HTMLAttributes:{class:"rounded-xl w-full"}}),Z6e.configure({types:["heading","paragraph"]}),qhr.configure({width:960,height:540,HTMLAttributes:{class:"w-full aspect-video rounded-xl"}}),Vhr],content:s||"",editorProps:{attributes:{class:"prose prose-slate dark:prose-invert max-w-none min-h-[420px] focus:outline-none px-4 py-4"}},onUpdate:({editor:w})=>t(w.getHTML())});j.useEffect(()=>{x&&s!==x.getHTML()&&x.commands.setContent(s||"",!1)},[s]);const y=j.useCallback(async(w,S)=>{var D;const{data:C}=await q.auth.getUser(),E=(D=C.user)==null?void 0:D.id;if(!E)return re.error("You must be signed in"),null;const I=w.name.split(".").pop()||(S==="image"?"jpg":"mp4"),P=`${E}/blog/${Date.now()}-${Math.random().toString(36).slice(2,8)}.${I}`,{error:R}=await q.storage.from("email-assets").upload(P,w,{cacheControl:"31536000",upsert:!1});return R?(re.error(`Upload failed: ${R.message}`),null):q.storage.from("email-assets").getPublicUrl(P).data.publicUrl},[]),v=async(w,S)=>{if(!w||!x)return;m(!0);const C=await y(w,S);m(!1),C&&(S==="image"?x.chain().focus().setImage({src:C}).run():x.chain().focus().insertContent({type:"videoEmbed",attrs:{src:C}}).run())};if(!x)return null;const b=x;return e.jsxs("div",{className:"rounded-xl border bg-background overflow-hidden",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-0.5 border-b bg-muted/40 px-2 py-1.5 sticky top-0 z-10",children:[e.jsx(r0,{title:"Bold",active:b.isActive("bold"),onClick:()=>b.chain().focus().toggleBold().run(),children:e.jsx(AE,{className:"h-4 w-4"})}),e.jsx(r0,{title:"Italic",active:b.isActive("italic"),onClick:()=>b.chain().focus().toggleItalic().run(),children:e.jsx(ME,{className:"h-4 w-4"})}),e.jsx(r0,{title:"Underline",active:b.isActive("underline"),onClick:()=>b.chain().focus().toggleUnderline().run(),children:e.jsx(i7,{className:"h-4 w-4"})}),e.jsx("div",{className:"mx-1 h-5 w-px bg-border"}),e.jsx(r0,{title:"Heading",active:b.isActive("heading",{level:2}),onClick:()=>b.chain().focus().toggleHeading({level:2}).run(),children:e.jsx(Hz,{className:"h-4 w-4"})}),e.jsx(r0,{title:"Subheading",active:b.isActive("heading",{level:3}),onClick:()=>b.chain().focus().toggleHeading({level:3}).run(),children:e.jsx($q,{className:"h-4 w-4"})}),e.jsx(r0,{title:"Bullet list",active:b.isActive("bulletList"),onClick:()=>b.chain().focus().toggleBulletList().run(),children:e.jsx(P0,{className:"h-4 w-4"})}),e.jsx(r0,{title:"Numbered list",active:b.isActive("orderedList"),onClick:()=>b.chain().focus().toggleOrderedList().run(),children:e.jsx(p2,{className:"h-4 w-4"})}),e.jsx(r0,{title:"Quote",active:b.isActive("blockquote"),onClick:()=>b.chain().focus().toggleBlockquote().run(),children:e.jsx(x2,{className:"h-4 w-4"})}),e.jsx(r0,{title:"Code block",active:b.isActive("codeBlock"),onClick:()=>b.chain().focus().toggleCodeBlock().run(),children:e.jsx(EE,{className:"h-4 w-4"})}),e.jsx("div",{className:"mx-1 h-5 w-px bg-border"}),e.jsx(r0,{title:"Align left",active:b.isActive({textAlign:"left"}),onClick:()=>b.chain().focus().setTextAlign("left").run(),children:e.jsx(BI,{className:"h-4 w-4"})}),e.jsx(r0,{title:"Align center",active:b.isActive({textAlign:"center"}),onClick:()=>b.chain().focus().setTextAlign("center").run(),children:e.jsx(zI,{className:"h-4 w-4"})}),e.jsx(r0,{title:"Align right",active:b.isActive({textAlign:"right"}),onClick:()=>b.chain().focus().setTextAlign("right").run(),children:e.jsx($I,{className:"h-4 w-4"})}),e.jsx("div",{className:"mx-1 h-5 w-px bg-border"}),e.jsx(r0,{title:"Link",active:b.isActive("link"),onClick:()=>{l(b.getAttributes("link").href||""),a(!0)},children:e.jsx(Ad,{className:"h-4 w-4"})}),e.jsx(r0,{title:"Insert image",disabled:h,onClick:()=>{var w;return(w=f.current)==null?void 0:w.click()},children:e.jsx(Av,{className:"h-4 w-4"})}),e.jsx(r0,{title:"Upload video",disabled:h,onClick:()=>{var w;return(w=g.current)==null?void 0:w.click()},children:e.jsx(ua,{className:"h-4 w-4"})}),e.jsx(r0,{title:"Embed YouTube / Vimeo",onClick:()=>{u(""),c(!0)},children:e.jsx(xV,{className:"h-4 w-4"})}),e.jsx(r0,{title:"Divider",onClick:()=>b.chain().focus().setHorizontalRule().run(),children:e.jsx(tk,{className:"h-4 w-4"})}),e.jsx("div",{className:"mx-1 h-5 w-px bg-border"}),e.jsx(r0,{title:"Undo",onClick:()=>b.chain().focus().undo().run(),children:e.jsx(BE,{className:"h-4 w-4"})}),e.jsx(r0,{title:"Redo",onClick:()=>b.chain().focus().redo().run(),children:e.jsx(OE,{className:"h-4 w-4"})}),h&&e.jsxs("span",{className:"ml-2 flex items-center gap-1.5 text-xs text-muted-foreground",children:[e.jsx(kt,{className:"h-3.5 w-3.5 animate-spin"})," Uploading…"]})]}),e.jsx(H6e,{editor:x,"data-placeholder":n}),e.jsx("input",{ref:f,type:"file",accept:"image/*",className:"hidden",onChange:w=>{var S;v((S=w.target.files)==null?void 0:S[0],"image"),w.target.value=""}}),e.jsx("input",{ref:g,type:"file",accept:"video/*",className:"hidden",onChange:w=>{var S;v((S=w.target.files)==null?void 0:S[0],"video"),w.target.value=""}}),e.jsx(zs,{open:r,onOpenChange:a,children:e.jsxs(Os,{children:[e.jsx(Us,{children:e.jsx(Bs,{children:"Insert link"})}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"URL"}),e.jsx(pe,{value:i,onChange:w=>l(w.target.value),placeholder:"https://…"})]}),e.jsxs(Ar,{children:[e.jsx($,{variant:"outline",onClick:()=>{b.chain().focus().unsetLink().run(),a(!1)},children:"Remove link"}),e.jsx($,{onClick:()=>{i.trim()&&b.chain().focus().extendMarkRange("link").setLink({href:i.trim(),target:"_blank"}).run(),a(!1)},children:"Apply"})]})]})}),e.jsx(zs,{open:o,onOpenChange:c,children:e.jsxs(Os,{children:[e.jsx(Us,{children:e.jsx(Bs,{children:"Embed a video"})}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"YouTube or Vimeo URL"}),e.jsx(pe,{value:d,onChange:w=>u(w.target.value),placeholder:"https://youtube.com/watch?v=…"})]}),e.jsx(Ar,{children:e.jsx($,{onClick:()=>{const w=d.trim();if(w){if(/vimeo\.com/i.test(w)){const S=w.split("/").filter(Boolean).pop();b.chain().focus().insertContent(`
`).run()}else b.commands.setYoutubeVideo({src:w});c(!1)}},children:"Embed"})})]})})]})}const fhe=s=>s.toLowerCase().trim().replace(/[^a-z0-9\s-]/g,"").replace(/\s+/g,"-").replace(/-+/g,"-").slice(0,80),Ghr=()=>({title:"",slug:"",excerpt:"",content:"",cover_image_url:null,category:"",tags:[],author_name:"Jeremy Collins",author_title:"Founder, LevelUp",status:"draft",featured:!1,allow_comments:!0});function Whr(){const{user:s}=vs(),[t,n]=j.useState([]),[r,a]=j.useState(!0),[i,l]=j.useState(null),[o,c]=j.useState(!1),[d,u]=j.useState(""),[h,m]=j.useState(""),[f,g]=j.useState(!1),x=j.useRef(null),[y,v]=j.useState([]),b=async()=>{a(!0);const{data:O,error:U}=await q.from("blog_posts").select("*").order("created_at",{ascending:!1});U&&re.error(U.message),n(O||[]),a(!1)},w=async()=>{const{data:O}=await q.from("blog_comments").select("id, body, created_at, is_hidden, user_id, post_id").order("created_at",{ascending:!1}).limit(200),U=O||[],W=[...new Set(U.map(ie=>ie.user_id))],V=[...new Set(U.map(ie=>ie.post_id))],[{data:G},{data:Y}]=await Promise.all([W.length?q.from("profiles").select("id, name, email").in("id",W):Promise.resolve({data:[]}),V.length?q.from("blog_posts").select("id, title, slug").in("id",V):Promise.resolve({data:[]})]),X=new Map((G||[]).map(ie=>[ie.id,ie])),ae=new Map((Y||[]).map(ie=>[ie.id,ie]));v(U.map(ie=>({...ie,author:X.get(ie.user_id),post:ae.get(ie.post_id)})))};j.useEffect(()=>{b(),w()},[]);const S=j.useMemo(()=>t.filter(O=>O.title.toLowerCase().includes(d.toLowerCase())),[t,d]),C=async O=>{if(!O||!s)return;g(!0);const U=O.name.split(".").pop()||"jpg",W=`${s.id}/blog/cover-${Date.now()}.${U}`,{error:V}=await q.storage.from("email-assets").upload(W,O);if(g(!1),V){re.error(V.message);return}const G=q.storage.from("email-assets").getPublicUrl(W).data.publicUrl;l(Y=>({...Y||{},cover_image_url:G}))},E=async O=>{if(!i)return;const U=(i.title||"").trim();if(!U){re.error("Give the article a title");return}const W=fhe(i.slug||U),V=O===void 0?i.status||"draft":O?"published":"draft";c(!0);const G={title:U,slug:W,excerpt:i.excerpt||null,content:i.content||"",cover_image_url:i.cover_image_url||null,category:i.category||null,tags:i.tags||[],author_name:i.author_name||"Jeremy Collins",author_title:i.author_title||"Founder, LevelUp",author_avatar_url:i.author_avatar_url||null,status:V,featured:!!i.featured,allow_comments:i.allow_comments!==!1,seo_title:i.seo_title||null,seo_description:i.seo_description||null,published_at:V==="published"?i.published_at||new Date().toISOString():i.published_at||null};let Y;if(i.id)({error:Y}=await q.from("blog_posts").update(G).eq("id",i.id));else{G.created_by=(s==null?void 0:s.id)||null;const X=await q.from("blog_posts").insert(G).select().single();Y=X.error,X.data&&l(X.data)}if(c(!1),Y){re.error(Y.message);return}re.success(V==="published"?"Published":"Saved"),b()},I=async O=>{if(!confirm("Delete this article and its comments?"))return;const{error:U}=await q.from("blog_posts").delete().eq("id",O);if(U){re.error(U.message);return}re.success("Deleted"),(i==null?void 0:i.id)===O&&l(null),b()},P=async O=>{const U=O.status==="published"?"draft":"published",{error:W}=await q.from("blog_posts").update({status:U,published_at:U==="published"?O.published_at||new Date().toISOString():O.published_at}).eq("id",O.id);if(W){re.error(W.message);return}b()},R=async O=>{const{error:U}=await q.from("blog_comments").update({is_hidden:!O.is_hidden}).eq("id",O.id);if(U){re.error(U.message);return}w()},D=async O=>{const{error:U}=await q.from("blog_comments").delete().eq("id",O);if(U){re.error(U.message);return}w()};return i?e.jsxs("div",{className:"container mx-auto max-w-6xl space-y-6 p-4 md:p-6",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsxs($,{variant:"ghost",onClick:()=>l(null),children:[e.jsx(qa,{className:"mr-2 h-4 w-4"})," Back to articles"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[i.slug&&i.status==="published"&&e.jsx($,{variant:"outline",asChild:!0,children:e.jsxs("a",{href:`/blog/${i.slug}`,target:"_blank",rel:"noreferrer",children:[e.jsx(kr,{className:"mr-2 h-4 w-4"})," View live"]})}),e.jsxs($,{variant:"outline",disabled:o,onClick:()=>E(!1),children:[o&&e.jsx(kt,{className:"mr-2 h-4 w-4 animate-spin"})," Save draft"]}),e.jsxs($,{disabled:o,onClick:()=>E(!0),children:[o&&e.jsx(kt,{className:"mr-2 h-4 w-4 animate-spin"})," Publish"]})]})]}),e.jsxs("div",{className:"grid gap-6 lg:grid-cols-[minmax(0,1fr)_320px]",children:[e.jsxs("div",{className:"space-y-4",children:[e.jsx(pe,{value:i.title||"",onChange:O=>l({...i,title:O.target.value}),placeholder:"Article title",className:"h-14 border-0 bg-transparent px-0 text-3xl font-bold shadow-none focus-visible:ring-0"}),e.jsx(Rs,{value:i.excerpt||"",onChange:O=>l({...i,excerpt:O.target.value}),placeholder:"Short excerpt shown on the blog index and social previews…",rows:2}),e.jsx(Hhr,{content:i.content||"",onChange:O=>l(U=>({...U||{},content:O}))})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsx(Ne,{children:e.jsxs(Ie,{className:"space-y-4 pt-6",children:[e.jsxs("div",{children:[e.jsx(ee,{children:"Cover image"}),i.cover_image_url?e.jsxs("div",{className:"mt-2 space-y-2",children:[e.jsx("img",{src:i.cover_image_url,alt:"cover",className:"h-36 w-full rounded-lg object-cover"}),e.jsx($,{variant:"outline",size:"sm",className:"w-full",onClick:()=>l({...i,cover_image_url:null}),children:"Remove"})]}):e.jsxs($,{variant:"outline",className:"mt-2 w-full",disabled:f,onClick:()=>{var O;return(O=x.current)==null?void 0:O.click()},children:[f?e.jsx(kt,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(Av,{className:"mr-2 h-4 w-4"}),"Upload cover"]}),e.jsx("input",{ref:x,type:"file",accept:"image/*",className:"hidden",onChange:O=>{var U;C((U=O.target.files)==null?void 0:U[0]),O.target.value=""}})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"URL slug"}),e.jsx(pe,{className:"mt-1",value:i.slug||"",onChange:O=>l({...i,slug:O.target.value}),onBlur:O=>l({...i,slug:fhe(O.target.value||i.title||"")}),placeholder:fhe(i.title||"")||"my-article"}),e.jsxs("p",{className:"mt-1 text-xs text-muted-foreground",children:["/blog/",i.slug||fhe(i.title||"")||"…"]})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Category"}),e.jsx(pe,{className:"mt-1",value:i.category||"",onChange:O=>l({...i,category:O.target.value}),placeholder:"e.g. Lead Generation"})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Tags"}),e.jsx("div",{className:"mt-1 flex gap-2",children:e.jsx(pe,{value:h,onChange:O=>m(O.target.value),placeholder:"Add a tag and press Enter",onKeyDown:O=>{O.key==="Enter"&&h.trim()&&(O.preventDefault(),l({...i,tags:[...i.tags||[],h.trim()]}),m(""))}})}),(i.tags||[]).length>0&&e.jsx("div",{className:"mt-2 flex flex-wrap gap-1.5",children:(i.tags||[]).map((O,U)=>e.jsxs(Be,{variant:"secondary",className:"cursor-pointer",onClick:()=>l({...i,tags:(i.tags||[]).filter((W,V)=>V!==U)}),children:[O," ×"]},`${O}-${U}`))})]}),e.jsx(Gc,{}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(ee,{htmlFor:"featured",children:"Featured article"}),e.jsx(Sn,{id:"featured",checked:!!i.featured,onCheckedChange:O=>l({...i,featured:O})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(ee,{htmlFor:"comments",children:"Allow comments"}),e.jsx(Sn,{id:"comments",checked:i.allow_comments!==!1,onCheckedChange:O=>l({...i,allow_comments:O})})]})]})}),e.jsx(Ne,{children:e.jsxs(Ie,{className:"space-y-4 pt-6",children:[e.jsx("div",{className:"text-sm font-semibold",children:"Author"}),e.jsx(pe,{value:i.author_name||"",placeholder:"Author name",onChange:O=>l({...i,author_name:O.target.value})}),e.jsx(pe,{value:i.author_title||"",placeholder:"Author title",onChange:O=>l({...i,author_title:O.target.value})}),e.jsx(pe,{value:i.author_avatar_url||"",placeholder:"Author photo URL (optional)",onChange:O=>l({...i,author_avatar_url:O.target.value})})]})}),e.jsx(Ne,{children:e.jsxs(Ie,{className:"space-y-4 pt-6",children:[e.jsx("div",{className:"text-sm font-semibold",children:"SEO"}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs",children:"SEO title"}),e.jsx(pe,{className:"mt-1",maxLength:60,value:i.seo_title||"",onChange:O=>l({...i,seo_title:O.target.value})})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs",children:"Meta description"}),e.jsx(Rs,{className:"mt-1",maxLength:160,rows:3,value:i.seo_description||"",onChange:O=>l({...i,seo_description:O.target.value})})]})]})})]})]})]}):e.jsxs("div",{className:"container mx-auto max-w-6xl space-y-6 p-4 md:p-6",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold tracking-tight",children:"Blog"}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Founder articles published publicly at ",e.jsx("a",{className:"underline",href:"/blog",target:"_blank",rel:"noreferrer",children:"/blog"})]})]}),e.jsxs($,{onClick:()=>l(Ghr()),children:[e.jsx(dn,{className:"mr-2 h-4 w-4"})," New article"]})]}),e.jsxs(ha,{defaultValue:"articles",children:[e.jsxs(ma,{children:[e.jsxs(Zt,{value:"articles",children:["Articles (",t.length,")"]}),e.jsxs(Zt,{value:"comments",children:["Comments (",y.length,")"]})]}),e.jsxs(Xt,{value:"articles",className:"mt-4 space-y-3",children:[e.jsxs("div",{className:"relative max-w-sm",children:[e.jsx(Kr,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(pe,{className:"pl-9",value:d,onChange:O=>u(O.target.value),placeholder:"Search articles…"})]}),r?e.jsxs("div",{className:"flex items-center gap-2 py-10 text-sm text-muted-foreground",children:[e.jsx(kt,{className:"h-4 w-4 animate-spin"})," Loading…"]}):S.length===0?e.jsx(Ne,{children:e.jsx(Ie,{className:"py-12 text-center text-sm text-muted-foreground",children:"No articles yet. Write your first one."})}):S.map(O=>e.jsx(Ne,{className:"transition hover:border-primary/30",children:e.jsxs(Ie,{className:"flex flex-wrap items-center gap-4 py-4",children:[O.cover_image_url?e.jsx("img",{src:O.cover_image_url,alt:"",className:"h-14 w-20 rounded-md object-cover"}):e.jsx("div",{className:"h-14 w-20 rounded-md bg-muted"}),e.jsxs("button",{className:"min-w-0 flex-1 text-left",onClick:()=>l(O),children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"truncate font-semibold",children:O.title}),O.featured&&e.jsx(Ja,{className:"h-3.5 w-3.5 fill-amber-400 text-amber-400"})]}),e.jsxs("div",{className:"mt-0.5 flex flex-wrap items-center gap-2 text-xs text-muted-foreground",children:[e.jsx(Be,{variant:O.status==="published"?"default":"secondary",children:O.status}),O.category&&e.jsx("span",{children:O.category}),e.jsxs("span",{children:[O.view_count," views"]}),e.jsxs("span",{children:["/blog/",O.slug]})]})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx($,{variant:"ghost",size:"sm",title:"Toggle publish",onClick:()=>P(O),children:O.status==="published"?e.jsx($g,{className:"h-4 w-4"}):e.jsx(Ca,{className:"h-4 w-4"})}),O.status==="published"&&e.jsx($,{variant:"ghost",size:"sm",asChild:!0,children:e.jsx("a",{href:`/blog/${O.slug}`,target:"_blank",rel:"noreferrer",children:e.jsx(kr,{className:"h-4 w-4"})})}),e.jsx($,{variant:"ghost",size:"sm",className:"text-destructive",onClick:()=>I(O.id),children:e.jsx(Wn,{className:"h-4 w-4"})})]})]})},O.id))]}),e.jsx(Xt,{value:"comments",className:"mt-4 space-y-3",children:y.length===0?e.jsx(Ne,{children:e.jsx(Ie,{className:"py-12 text-center text-sm text-muted-foreground",children:"No comments yet."})}):y.map(O=>{var U,W,V;return e.jsx(Ne,{children:e.jsxs(Ie,{className:"flex flex-wrap items-start gap-4 py-4",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"text-sm font-semibold",children:[((U=O.author)==null?void 0:U.name)||((W=O.author)==null?void 0:W.email)||"Member",e.jsxs("span",{className:"ml-2 font-normal text-muted-foreground",children:["on “",((V=O.post)==null?void 0:V.title)||"article","”"]})]}),e.jsx("p",{className:"mt-1 whitespace-pre-wrap text-sm text-muted-foreground",children:O.body})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[O.is_hidden&&e.jsx(Be,{variant:"secondary",children:"hidden"}),e.jsx($,{variant:"ghost",size:"sm",onClick:()=>R(O),children:O.is_hidden?e.jsx(Ca,{className:"h-4 w-4"}):e.jsx($g,{className:"h-4 w-4"})}),e.jsx($,{variant:"ghost",size:"sm",className:"text-destructive",onClick:()=>D(O.id),children:e.jsx(Wn,{className:"h-4 w-4"})})]})]})},O.id)})})]})]})}const Khr=["What was it like working together?","What moment stood out the most?","Would you recommend me to a friend?"],E5="#16283a",lTt="#f7f5f1";function gls(s){var O,U,W,V,G;const t=s.accentColor||"#c9a24b",n=(O=s.videoPrompts)!=null&&O.length?s.videoPrompts:Khr,r=((U=s.agent)==null?void 0:U.name)||"Your agent",a=((V=(W=s.agent)==null?void 0:W.name)==null?void 0:V.split(" ")[0])||"them",[i,l]=j.useState("none"),[o,c]=j.useState(s.recipientName||""),[d,u]=j.useState(5),[h,m]=j.useState(0),[f,g]=j.useState(""),[x,y]=j.useState(!1),[v,b]=j.useState(!1),[w,S]=j.useState(null),C=j.useCallback(()=>{q.functions.invoke("review-public",{body:{action:"clicked",...s.payloadBase}}).catch(()=>{})},[s.payloadBase]),E=j.useCallback(()=>{C(),s.googleReviewLink&&window.open(s.googleReviewLink,"_blank","noopener")},[C,s.googleReviewLink]),I=s.protectionThreshold??3,P=!!s.protectionEnabled&&d<=I,R=!!s.googleReviewLink&&!(P&&s.hideGoogleBelowThreshold),D=j.useCallback(async(Y,X)=>{if(!o.trim()){S("Please add your name first.");return}y(!0),S(null);try{const ae={action:"submit",...s.payloadBase,reviewer_name:o,rating:d,review_text:f||void 0,is_private:!!X};if(Y){const te=Y.type||"video/webm",{data:J,error:ce}=await q.functions.invoke("review-public",{body:{action:"video_upload_url",...s.payloadBase,video_type:te}});if(ce||!(J!=null&&J.path)||!(J!=null&&J.token))throw new Error((J==null?void 0:J.error)||(ce==null?void 0:ce.message)||"Could not start the video upload");const{error:_e}=await q.storage.from(J.bucket||"agent-uploads").uploadToSignedUrl(J.path,J.token,Y,{contentType:te});if(_e)throw new Error(`Video upload failed: ${_e.message}`);ae.video_path=J.path,ae.video_type=te}const{data:ie,error:ne}=await q.functions.invoke("review-public",{body:ae});if(ne||ie!=null&&ie.error)throw new Error((ie==null?void 0:ie.error)||(ne==null?void 0:ne.message)||"Something went wrong");b(!0)}catch(ae){S(ae.message)}finally{y(!1)}},[s.payloadBase,o,d,f]);return v?e.jsx("div",{className:"min-h-screen flex items-center justify-center p-5 sm:p-6",style:{background:lTt},children:e.jsxs("div",{className:"text-center max-w-md w-full",children:[e.jsx("div",{className:"w-16 h-16 sm:w-20 sm:h-20 rounded-full mx-auto mb-5 sm:mb-6 flex items-center justify-center",style:{background:`${t}1f`},children:e.jsx(qr,{className:"h-9 w-9 sm:h-10 sm:w-10",style:{color:t}})}),e.jsx("h1",{className:"text-3xl sm:text-4xl font-serif mb-3",style:{color:E5},children:s.thankYouTitle||"Thank you!"}),e.jsx("p",{className:"text-slate-600 leading-relaxed",children:s.thankYouMessage||`Your words mean the world to ${a}. We truly appreciate you taking the time.`}),s.ctaUrl&&e.jsxs("a",{href:s.ctaUrl,target:"_blank",rel:"noreferrer",className:"inline-flex items-center gap-2 mt-8 px-7 py-3.5 rounded-full font-semibold transition-transform hover:scale-[1.03]",style:{background:t,color:E5},children:[s.ctaLabel||"Visit my website"," ",e.jsx(ei,{className:"h-4 w-4"})]})]})}):e.jsxs("div",{className:"min-h-screen",style:{background:lTt},children:[e.jsxs("header",{className:"relative overflow-hidden",style:{background:E5},children:[s.heroImageUrl&&e.jsx("img",{src:s.heroImageUrl,alt:"",className:"absolute inset-0 w-full h-full object-cover opacity-25"}),e.jsx("div",{className:"absolute inset-0",style:{background:`radial-gradient(circle at 50% 0%, ${t}33, transparent 62%)`}}),e.jsxs("div",{className:"relative max-w-2xl mx-auto px-4 sm:px-6 pt-12 sm:pt-14 pb-14 sm:pb-16 text-center",children:[((G=s.agent)==null?void 0:G.avatar_url)&&e.jsx("img",{src:s.agent.avatar_url,alt:r,className:"w-20 h-20 sm:w-24 sm:h-24 rounded-full object-cover mx-auto mb-5 shadow-2xl",style:{border:`3px solid ${t}`}}),e.jsx("p",{className:"uppercase tracking-[0.25em] sm:tracking-[0.3em] text-[10px] sm:text-[11px] mb-3",style:{color:t},children:"Client Experience"}),e.jsx("h1",{className:"text-3xl sm:text-4xl md:text-5xl font-serif text-white leading-tight break-words",children:s.headline||`Share your experience with ${r}`}),e.jsx("p",{className:"text-white/70 mt-4 leading-relaxed max-w-lg mx-auto text-sm sm:text-base",children:s.subheadline||"Thank you for your trust. It takes less than 60 seconds — and it helps other families find the right agent."})]}),e.jsx("div",{className:"h-px w-full",style:{background:`linear-gradient(90deg,transparent,${t},transparent)`}})]}),e.jsxs("main",{className:"relative z-10 max-w-2xl mx-auto px-4 -mt-9 pb-[max(4rem,env(safe-area-inset-bottom))]",children:[e.jsxs("div",{className:"bg-white rounded-3xl shadow-xl border border-slate-200/70 px-4 sm:px-6 py-6 sm:py-7 text-center",children:[e.jsx("p",{className:"text-sm font-medium text-slate-500 mb-4",children:"How was your experience?"}),e.jsx("div",{className:"flex justify-center gap-1 sm:gap-1.5",onMouseLeave:()=>m(0),children:[1,2,3,4,5].map(Y=>e.jsx("button",{onClick:()=>u(Y),onMouseEnter:()=>m(Y),"aria-label":`${Y} stars`,className:"p-0.5 transition-transform hover:scale-125 active:scale-95",children:e.jsx(Ja,{className:"h-9 w-9 sm:h-10 sm:w-10 transition-colors",style:{fill:Y<=(h||d)?t:"transparent",color:Y<=(h||d)?t:"#cbd5e1"}})},Y))})]}),i==="none"&&P&&e.jsxs("div",{className:"grid gap-4 mt-6",children:[e.jsxs("div",{className:"bg-white rounded-3xl p-6 shadow-xl border border-slate-200/70 text-center",children:[e.jsx("h2",{className:"text-2xl font-serif",style:{color:E5},children:s.privateFeedbackTitle||`How can ${a} make this right?`}),e.jsx("p",{className:"text-sm text-slate-600 mt-2 leading-relaxed",children:s.privateFeedbackMessage||`Your honest feedback goes straight to ${a} in private so it can be addressed personally.`})]}),e.jsx(MX,{accent:t,icon:e.jsx(wf,{className:"h-6 w-6 text-slate-600"}),title:`Share feedback privately with ${a}`,subtitle:"Only they will see it",badge:"Private",onClick:()=>l("private")}),R&&e.jsx(MX,{accent:t,icon:e.jsx(Ja,{className:"h-6 w-6",style:{color:t}}),title:"Post a public Google review",subtitle:"You're always welcome to share your experience publicly",onClick:E})]}),i==="none"&&!P&&e.jsxs("div",{className:"grid gap-4 mt-6",children:[R&&e.jsx(MX,{accent:t,icon:e.jsx(Ja,{className:"h-6 w-6",style:{color:t}}),title:"Leave a Google review",subtitle:`Takes 30 seconds — helps others find ${a}`,badge:"Most helpful",onClick:E}),e.jsx(MX,{accent:t,icon:e.jsx(ua,{className:"h-6 w-6",style:{color:t}}),title:"Record a quick video",subtitle:"60 seconds, right from your phone",onClick:()=>l("video")}),e.jsx(MX,{accent:t,icon:e.jsx(wf,{className:"h-6 w-6 text-slate-600"}),title:"Write a note",subtitle:"A few kind words go a long way",onClick:()=>l("write")})]}),i!=="none"&&e.jsxs("div",{className:"bg-white rounded-3xl p-6 sm:p-8 shadow-xl border border-slate-200/70 space-y-6 mt-6",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium text-slate-700",children:"Your name"}),e.jsx(pe,{value:o,onChange:Y=>c(Y.target.value),placeholder:"Jane Smith",className:"mt-1.5 h-11"})]}),i==="write"&&e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium text-slate-700",children:"Your review"}),e.jsx(Rs,{value:f,onChange:Y=>g(Y.target.value),rows:6,placeholder:"Share a few words about your experience...",className:"mt-1.5"}),e.jsxs("div",{className:"rounded-2xl p-4 mt-4",style:{background:`${t}12`},children:[e.jsx("p",{className:"text-xs font-semibold uppercase tracking-wide mb-2",style:{color:E5},children:"Need a nudge?"}),e.jsx("ul",{className:"text-sm text-slate-600 space-y-1.5",children:n.map(Y=>e.jsxs("li",{className:"flex gap-2",children:[e.jsx(x2,{className:"h-3.5 w-3.5 mt-1 shrink-0",style:{color:t}}),Y]},Y))})]})]}),i==="private"&&e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium text-slate-700",children:"What could have been better?"}),e.jsx(Rs,{value:f,onChange:Y=>g(Y.target.value),rows:6,placeholder:"Tell them what happened...",className:"mt-1.5"}),e.jsx("p",{className:"text-xs text-slate-500 mt-2",children:"This message is private. It will not appear on any public page or website."})]}),i==="video"&&e.jsxs("div",{children:[e.jsxs("div",{className:"rounded-2xl p-4 mb-5",style:{background:`${t}12`},children:[e.jsx("p",{className:"text-xs font-semibold uppercase tracking-wide mb-2",style:{color:E5},children:"Not sure what to say? Try these"}),e.jsx("ul",{className:"text-sm text-slate-600 space-y-1.5",children:n.map(Y=>e.jsxs("li",{className:"flex gap-2",children:[e.jsx(x2,{className:"h-3.5 w-3.5 mt-1 shrink-0",style:{color:t}}),Y]},Y))})]}),e.jsx(BT,{maxDurationSeconds:60,showBackgroundPicker:!1,onRecordingComplete:Y=>D(Y),onError:Y=>S(Y)})]}),w&&e.jsx("p",{className:"text-sm text-red-600",children:w}),e.jsxs("div",{className:"flex flex-col-reverse sm:flex-row gap-2 sm:gap-3 sm:items-center",children:[e.jsxs($,{variant:"ghost",onClick:()=>l("none"),disabled:x,className:"text-slate-500",children:[e.jsx(qa,{className:"h-4 w-4 mr-1.5"})," Back"]}),i==="write"&&e.jsxs($,{onClick:()=>D(),disabled:x||!o.trim()||!f.trim(),className:"flex-1 h-12 rounded-full font-semibold hover:opacity-90",style:{background:E5,color:"#fff"},children:[x?e.jsx(kt,{className:"h-4 w-4 animate-spin mr-2"}):null,"Send my review"]}),i==="private"&&e.jsxs($,{onClick:()=>D(void 0,!0),disabled:x||!o.trim()||!f.trim(),className:"flex-1 h-12 rounded-full font-semibold hover:opacity-90",style:{background:E5,color:"#fff"},children:[x?e.jsx(kt,{className:"h-4 w-4 animate-spin mr-2"}):null,"Send privately"]})]}),i==="video"&&x&&e.jsxs("p",{className:"text-sm text-slate-500 flex items-center gap-2",children:[e.jsx(kt,{className:"h-4 w-4 animate-spin"})," Uploading your video…"]})]}),e.jsx("p",{className:"text-center text-xs text-slate-400 mt-8",children:i==="private"?`Your feedback goes only to ${r}.`:`Your review is shared publicly with ${r}'s permission.`})]})]})}function MX({accent:s,icon:t,title:n,subtitle:r,badge:a,onClick:i}){return e.jsx("button",{onClick:i,className:Pt("group bg-white rounded-2xl p-5 sm:p-6 shadow-sm border border-slate-200 text-left","transition-all hover:shadow-xl hover:-translate-y-0.5"),style:{borderColor:void 0},children:e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx("div",{className:"w-12 h-12 rounded-full flex items-center justify-center shrink-0 transition-transform group-hover:scale-110",style:{background:`${s}1f`},children:t}),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-semibold",style:{color:E5},children:n}),a&&e.jsx("span",{className:"text-[10px] uppercase tracking-wider px-2 py-0.5 rounded-full font-semibold",style:{background:`${s}26`,color:E5},children:a})]}),e.jsx("p",{className:"text-sm text-slate-500 mt-0.5",children:r})]}),e.jsx(ei,{className:"h-5 w-5 text-slate-300 group-hover:translate-x-1 transition-transform"})]})})}function Yhr(){const{token:s}=Wi(),[t,n]=j.useState(null),[r,a]=j.useState(null),[i,l]=j.useState(!0);return j.useEffect(()=>{(async()=>{const{data:o}=await q.rpc("get_review_request_by_token",{_token:s});n(o),l(!1)})()},[s]),j.useEffect(()=>{var o;(o=t==null?void 0:t.agent)!=null&&o.name&&(async()=>{const{data:c}=await q.rpc("get_review_page_style_for_token",{_token:s});c&&a(c)})()},[t,s]),i?e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-[#f7f5f1]",children:e.jsx(kt,{className:"h-8 w-8 animate-spin text-[#406E71]"})}):t?e.jsx(gls,{agent:t.agent,googleReviewLink:t.google_review_link,recipientName:t.recipient_name,headline:r==null?void 0:r.headline,subheadline:r==null?void 0:r.subheadline,accentColor:r==null?void 0:r.accent_color,heroImageUrl:r==null?void 0:r.hero_image_url,videoPrompts:r==null?void 0:r.video_prompts,thankYouTitle:r==null?void 0:r.thank_you_title,thankYouMessage:r==null?void 0:r.thank_you_message,ctaLabel:r==null?void 0:r.cta_label,ctaUrl:r==null?void 0:r.cta_url,protectionEnabled:r==null?void 0:r.protection_enabled,protectionThreshold:r==null?void 0:r.protection_threshold,hideGoogleBelowThreshold:r==null?void 0:r.hide_google_below_threshold,privateFeedbackTitle:r==null?void 0:r.private_feedback_title,privateFeedbackMessage:r==null?void 0:r.private_feedback_message,payloadBase:{token:s||""}}):e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-[#f7f5f1] p-6",children:e.jsx("p",{className:"text-slate-600 text-center",children:"This review link is invalid or has expired."})})}function phe({rating:s,size:t="h-4 w-4"}){return e.jsx("div",{className:"flex gap-0.5",children:[1,2,3,4,5].map(n=>e.jsx(Ja,{className:Pt(t,n<=s?"fill-[#c9a24b] text-[#c9a24b]":"text-slate-300")},n))})}function Zhr(){var d,u;const{slug:s}=Wi(),[t,n]=j.useState(null),[r,a]=j.useState(!0);j.useEffect(()=>{(async()=>{const{data:h}=await q.rpc("get_public_reviews_page",{_slug:s});n(h),a(!1)})()},[s]);const i=j.useMemo(()=>{var h;return((h=t==null?void 0:t.agent)==null?void 0:h.name)??""},[t]);if(j.useEffect(()=>{var m;if(!t)return;document.title=`Reviews for ${i}`;const h=document.createElement("script");return h.type="application/ld+json",h.text=JSON.stringify({"@context":"https://schema.org","@type":"RealEstateAgent",name:i,image:(m=t.agent)==null?void 0:m.avatar_url,aggregateRating:t.stats.total_reviews>0?{"@type":"AggregateRating",ratingValue:t.stats.avg_rating,reviewCount:t.stats.total_reviews}:void 0}),document.head.appendChild(h),()=>{document.head.removeChild(h)}},[t,i]),r)return e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-[#f7f5f1]",children:e.jsx(kt,{className:"h-8 w-8 animate-spin text-[#406E71]"})});if(!t)return e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-[#f7f5f1] p-6",children:e.jsx("p",{className:"text-slate-600",children:"This reviews page isn't available."})});const l=t.reviews.filter(h=>h.source==="video"&&h.video_url),o=t.reviews.filter(h=>h.source==="google"),c=t.reviews.filter(h=>h.source==="video"&&!h.video_url);return e.jsxs("div",{className:"min-h-screen bg-[#f7f5f1]",children:[e.jsxs("header",{className:"bg-[#2a4c64] text-white py-12 sm:py-16 px-4 sm:px-6 text-center",children:[((d=t.agent)==null?void 0:d.avatar_url)&&e.jsx("img",{src:t.agent.avatar_url,alt:i,className:"w-20 h-20 sm:w-24 sm:h-24 rounded-full object-cover mx-auto mb-5 border-4 border-[#c9a24b]/60 shadow-xl"}),e.jsx("h1",{className:"text-3xl sm:text-4xl font-serif break-words",children:i}),((u=t.agent)==null?void 0:u.title)&&e.jsx("p",{className:"text-white/70 mt-1 text-sm sm:text-base",children:t.agent.title}),e.jsxs("div",{className:"flex flex-wrap items-center justify-center gap-x-3 gap-y-1 mt-5",children:[e.jsx(phe,{rating:Math.round(t.stats.avg_rating),size:"h-5 w-5 sm:h-6 sm:w-6"}),e.jsx("span",{className:"text-xl sm:text-2xl font-semibold",children:t.stats.avg_rating}),e.jsxs("span",{className:"text-white/60 text-sm sm:text-base",children:["· ",t.stats.total_reviews," review",t.stats.total_reviews!==1?"s":""]})]}),t.settings.intro_text&&e.jsx("p",{className:"max-w-xl mx-auto mt-5 text-white/80 leading-relaxed text-sm sm:text-base",children:t.settings.intro_text}),e.jsx("a",{href:`/reviews/${t.settings.slug}/new`,className:"inline-flex items-center justify-center gap-2 mt-7 sm:mt-8 w-full sm:w-auto max-w-xs px-7 py-3.5 rounded-full bg-[#c9a24b] text-[#16283a] font-semibold shadow-lg transition-transform hover:scale-[1.03]",children:"Leave a review"})]}),e.jsxs("main",{className:"max-w-4xl mx-auto px-4 py-10 sm:py-12 space-y-12 sm:space-y-14",children:[l.length>0&&e.jsxs("section",{children:[e.jsxs("h2",{className:"text-xl sm:text-2xl font-serif text-[#2a4c64] mb-5 sm:mb-6 flex items-center gap-2",children:[e.jsx(ua,{className:"h-6 w-6 text-[#c9a24b]"})," Video testimonials"]}),e.jsx("div",{className:"grid sm:grid-cols-2 gap-5 sm:gap-6",children:l.map(h=>e.jsxs("figure",{className:"bg-white rounded-2xl overflow-hidden shadow-sm border border-slate-200",children:[e.jsx("video",{src:h.video_url,controls:!0,playsInline:!0,preload:"metadata",className:"w-full aspect-video bg-black"}),e.jsxs("figcaption",{className:"p-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"font-medium text-[#2a4c64]",children:h.reviewer_name}),h.rating&&e.jsx(phe,{rating:h.rating})]}),h.review_text&&e.jsx("p",{className:"text-sm text-slate-600 mt-2",children:h.review_text})]})]},h.id))})]}),o.length>0&&e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl sm:text-2xl font-serif text-[#2a4c64] mb-5 sm:mb-6",children:"Google reviews"}),e.jsx("div",{className:"grid sm:grid-cols-2 gap-5 sm:gap-6",children:o.map(h=>{var m,f;return e.jsxs("blockquote",{className:"bg-white rounded-2xl p-5 sm:p-6 shadow-sm border border-slate-200 flex flex-col",children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[h.rating&&e.jsx(phe,{rating:h.rating}),e.jsxs("span",{className:"inline-flex items-center gap-1 text-xs text-[#406E71] bg-[#406E71]/10 px-2 py-1 rounded-full",children:[e.jsx(RA,{className:"h-3.5 w-3.5"})," Verified Google review"]})]}),h.review_text&&e.jsxs("p",{className:"text-slate-700 leading-relaxed flex-1",children:['"',h.review_text,'"']}),e.jsxs("footer",{className:"mt-4 text-sm font-medium text-[#2a4c64]",children:["— ",h.reviewer_name]}),h.reply_text&&e.jsxs("div",{className:"mt-4 pl-4 border-l-2 border-[#c9a24b]/50 bg-[#f7f5f1] rounded-r-lg p-3",children:[e.jsxs("p",{className:"text-xs font-semibold text-[#2a4c64] flex items-center gap-1 mb-1",children:[e.jsx(qJ,{className:"h-3.5 w-3.5"})," Response from ",(f=(m=t.agent)==null?void 0:m.name)==null?void 0:f.split(" ")[0]]}),e.jsx("p",{className:"text-sm text-slate-600",children:h.reply_text})]})]},h.id)})})]}),c.length>0&&e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl sm:text-2xl font-serif text-[#2a4c64] mb-5 sm:mb-6",children:"Kind words"}),e.jsx("div",{className:"grid sm:grid-cols-2 gap-5 sm:gap-6",children:c.map(h=>e.jsxs("blockquote",{className:"bg-white rounded-2xl p-5 sm:p-6 shadow-sm border border-slate-200",children:[h.rating&&e.jsx(phe,{rating:h.rating}),h.review_text&&e.jsxs("p",{className:"text-slate-700 leading-relaxed mt-3",children:['"',h.review_text,'"']}),e.jsxs("footer",{className:"mt-4 text-sm font-medium text-[#2a4c64]",children:["— ",h.reviewer_name]})]},h.id))})]})]})]})}function Xhr(){const{slug:s}=Wi(),[t,n]=j.useState(null),[r,a]=j.useState(!0);return j.useEffect(()=>{(async()=>{const{data:i}=await q.rpc("get_public_review_intake",{_slug:s});n(i),a(!1)})()},[s]),j.useEffect(()=>{var i;(i=t==null?void 0:t.agent)!=null&&i.name&&(document.title=`Leave a review for ${t.agent.name}`)},[t]),r?e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-[#f7f5f1]",children:e.jsx(kt,{className:"h-8 w-8 animate-spin text-[#406E71]"})}):t?e.jsx(gls,{agent:t.agent,googleReviewLink:t.google_review_link,headline:t.headline,subheadline:t.subheadline,accentColor:t.accent_color,heroImageUrl:t.hero_image_url,videoPrompts:t.video_prompts,thankYouTitle:t.thank_you_title,thankYouMessage:t.thank_you_message,ctaLabel:t.cta_label,ctaUrl:t.cta_url,protectionEnabled:t.protection_enabled,protectionThreshold:t.protection_threshold,hideGoogleBelowThreshold:t.hide_google_below_threshold,privateFeedbackTitle:t.private_feedback_title,privateFeedbackMessage:t.private_feedback_message,payloadBase:{slug:s||""}}):e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-[#f7f5f1] p-6",children:e.jsx("p",{className:"text-slate-600 text-center",children:"This review page isn't accepting reviews right now."})})}const Qhr=[{tag:"{{client_first_name}}",label:"Client's first name"},{tag:"{{agent_name}}",label:"Your name"},{tag:"{{property_address}}",label:"Property address"},{tag:"{{review_link}}",label:"Review link"}],EUe=[{key:"closing_day",name:"Closing Day Celebration",description:"Warm and celebratory — best sent the day of closing.",subject:"Congratulations on closing, {{client_first_name}}!",emailBody:`Congratulations on closing today, {{client_first_name}}! It was an absolute honor helping you through this, and I'm so happy for you. If you have 60 seconds, would you share a few words (or a quick video) about how the experience went? It helps other families find the right agent — and it would truly mean a lot to me.`,smsBody:"Congrats again on closing, {{client_first_name}}! It was an honor. If you have 60 seconds, would you leave me a quick review? {{review_link}} — {{agent_name}}"},{key:"short_casual",name:"Short & Casual",description:"Ten-second read. Highest response rate on mobile.",subject:"Quick favor, {{client_first_name}}?",emailBody:`Hey {{client_first_name}} — quick favor! Would you mind sharing a short note or 60-second video about how things went? It takes less than a minute and helps more than you know. Thank you!`,smsBody:"Hey {{client_first_name}}, it's {{agent_name}} — quick favor? A 60-second review would mean a lot: {{review_link}}"},{key:"luxury",name:"Luxury & High-Touch",description:"Refined and discreet — for high-end clientele.",subject:"Thank you for your trust, {{client_first_name}}",emailBody:`{{client_first_name}}, thank you for trusting me with your recent transaction. Discretion and white-glove service are the standards I hold myself to, and your feedback tells me whether I met them. If you're willing, I would be grateful for a brief review of your experience.`,smsBody:"{{client_first_name}}, thank you again for your trust. If you're willing, I'd be grateful for a brief review of your experience: {{review_link}} — {{agent_name}}"},{key:"past_client",name:"Past Client Reconnect",description:"For clients from 3–12 months ago.",subject:"Hope you are loving the house, {{client_first_name}}",emailBody:`Hi {{client_first_name}}, I hope you're settled in and loving {{property_address}}! I'm updating my client stories and would love to include yours. Would you share a couple of sentences — or a quick video — about what working together was like?`,smsBody:"Hi {{client_first_name}}, {{agent_name}} here — hope you're loving the house! I'm updating my client stories and would love to include yours: {{review_link}}"}];function TUe(s,t){return s.replace(/\{\{\s*client_first_name\s*\}\}/g,t.client_first_name||"there").replace(/\{\{\s*agent_name\s*\}\}/g,t.agent_name||"your agent").replace(/\{\{\s*property_address\s*\}\}/g,t.property_address||"your new home").replace(/\{\{\s*review_link\s*\}\}/g,t.review_link||"")}const Jhr=[{key:"onyx",label:"Onyx & Gold",base:"#0F172A",accent:"#D4AF37"},{key:"navy",label:"Classic Navy",base:"#2a4c64",accent:"#B8965A"},{key:"noir",label:"Modern Noir",base:"#111111",accent:"#F5F5F5"}],emr=s=>{if(!s)return"";const t=s.replace(/\D/g,""),n=t.length===11&&t.startsWith("1")?t.slice(1):t;return n.length!==10?s:`${n.slice(0,3)}-${n.slice(3,6)}-${n.slice(6)}`},tmr=s=>{const t=s.replace("#",""),n=t.length===3?t.split("").map(a=>a+a).join(""):t,r=parseInt(n,16);return Number.isNaN(r)?{r:15,g:23,b:42}:{r:r>>16&255,g:r>>8&255,b:r&255}},CR=(s,t)=>{const{r:n,g:r,b:a}=tmr(s);return`rgba(${n},${r},${a},${t})`},smr=async s=>new Promise((t,n)=>{const r=new Image;r.crossOrigin="anonymous",r.referrerPolicy="no-referrer",r.onload=()=>t(r),r.onerror=n,r.src=s}),nmr=(s,t,n,r,a,i)=>{const l=Math.max(a/t.naturalWidth,i/t.naturalHeight),o=a/l,c=i/l;s.drawImage(t,(t.naturalWidth-o)/2,(t.naturalHeight-c)/2,o,c,n,r,a,i)},TAe=(s,t,n)=>{if(s.measureText(t).width<=n)return t;let r=t;for(;r.length>3&&s.measureText(`${r}…`).width>n;)r=r.slice(0,-1);return`${r.trim()}…`},cTt=(s,t,n,r)=>{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<=n||!l)l=c;else if(i.push(l),l=o,i.length===r)break}return l&&i.length{const a=r*.45;s.beginPath();for(let i=0;i<10;i+=1){const l=i%2===0?r:a,o=Math.PI/5*i-Math.PI/2,c=t+Math.cos(o)*l,d=n+Math.sin(o)*l;i===0?s.moveTo(c,d):s.lineTo(c,d)}s.closePath(),s.fill()},amr=s=>{const t=new Date,n=new Intl.DateTimeFormat("en-CA",{timeZone:s,year:"numeric",month:"2-digit",day:"2-digit"}).formatToParts(t),r=l=>{var o;return((o=n.find(c=>c.type===l))==null?void 0:o.value)??"01"},a=new Date(`${r("year")}-${r("month")}-${r("day")}T00:00:00Z`);return a.setUTCDate(a.getUTCDate()+1),`${a.toISOString().slice(0,10)}T10:00`};function imr({review:s,open:t,onOpenChange:n}){var ne;const r=Qn(),{data:a}=A6e(),{data:i=[]}=jrt(),{timezone:l}=_K(),o=oGt(),[c,d]=j.useState(!1),[u,h]=j.useState(null),[m,f]=j.useState(null),[g,x]=j.useState("brand"),[y,v]=j.useState(""),[b,w]=j.useState(!1),[S,C]=j.useState([]),E=j.useMemo(()=>({key:"brand",label:"My Brand Kit",base:(a==null?void 0:a.brandColor)||"#2a4c64",accent:(a==null?void 0:a.accentColor)||"#B8965A"}),[a==null?void 0:a.brandColor,a==null?void 0:a.accentColor]),I=j.useMemo(()=>[E,...Jhr],[E]),P=I.find(te=>te.key===g)||E,R=emr(a==null?void 0:a.phone),D=(s==null?void 0:s.rating)??5,O=((ne=s==null?void 0:s.reviewer_name)==null?void 0:ne.trim())||"A happy client",U=((s==null?void 0:s.review_text)||"").trim();j.useEffect(()=>{t||(f(null),w(!1),h(null))},[t]),j.useEffect(()=>{t&&C(i.map(te=>te.id))},[t,i.length]),j.useEffect(()=>{if(!t||!s||b)return;const te=R?`call or text ${R}`:"send me a message",J=U.length>220?`${U.slice(0,217).trim()}…`:U,ce=["⭐️⭐️⭐️⭐️⭐️ Client love!",J?`"${J}"`:"",`Thank you, ${O} — this is exactly why I do what I do.`,`Thinking about buying or selling? ${te} and let's talk.`,"#ClientReview #ClientAppreciation #RealEstate #Testimonial"].filter(Boolean);v(ce.join(` `))},[t,s==null?void 0:s.id,b,R]);const W=j.useCallback(async()=>{if(s){d(!0);try{const te=document.createElement("canvas");te.width=1080,te.height=1080;const J=te.getContext("2d");if(!J)throw new Error("Canvas unavailable");const ce=J.createLinearGradient(0,0,1080,1080);ce.addColorStop(0,P.base),ce.addColorStop(1,CR(P.base,.86)),J.fillStyle=ce,J.fillRect(0,0,1080,1080),J.save();const _e=J.createRadialGradient(880,180,40,880,180,520);_e.addColorStop(0,CR(P.accent,.22)),_e.addColorStop(1,CR(P.accent,0)),J.fillStyle=_e,J.fillRect(0,0,1080,1080),J.restore(),J.fillStyle=P.accent,J.fillRect(72,96,72,3),J.font="600 22px Arial, sans-serif",J.textBaseline="middle";let he=164;const ue=s.source==="google"?"GOOGLE REVIEW":s.source==="video"?"CLIENT VIDEO REVIEW":"CLIENT REVIEW";for(const Ae of ue)J.fillText(Ae,he,98),he+=J.measureText(Ae).width+8;J.fillStyle=P.accent;for(let Ae=0;Ae=ve.length-2||Ae===30))break}Le.length===0&&(J.font="500 30px Georgia, serif",Le=cTt(J,ve,900,10),Se=30),J.fillStyle="#F8FAFC",J.font=`500 ${Se}px Georgia, serif`;let Fe=400;Le.forEach(Ae=>{J.fillText(Ae,90,Fe),Fe+=Se*1.35}),J.fillStyle=P.accent,J.fillRect(90,Fe+30,56,3),J.fillStyle="rgba(248,250,252,0.92)",J.font="600 30px Arial, sans-serif",J.fillText(TAe(J,`— ${O}`,860),168,Fe+16);const ke=J.createLinearGradient(0,880,0,1080);ke.addColorStop(0,CR(P.base,.96)),ke.addColorStop(1,P.base),J.fillStyle=ke,J.fillRect(0,880,1080,200),J.fillStyle=P.accent,J.fillRect(0,880,1080,3);const Ve=(a==null?void 0:a.name)||"Agent";J.save(),J.beginPath(),J.arc(124,980,60,0,Math.PI*2),J.closePath(),J.fillStyle=CR(P.accent,.18),J.fill(),J.lineWidth=6,J.strokeStyle=P.accent,J.stroke(),J.clip();let je=!1;if(a!=null&&a.headshotUrl)try{const Ae=await smr(a.headshotUrl);nmr(J,Ae,64,920,120,120),je=!0}catch{je=!1}je||(J.fillStyle=P.accent,J.font="700 48px Arial, sans-serif",J.textAlign="center",J.textBaseline="middle",J.fillText(Ve.charAt(0).toUpperCase(),124,982)),J.restore(),J.textAlign="left",J.textBaseline="alphabetic",J.fillStyle="#F8FAFC",J.font="600 38px Georgia, serif",J.fillText(TAe(J,Ve,R?430:820),212,970),a!=null&&a.brokerageName&&(J.fillStyle=P.accent,J.font="600 20px Arial, sans-serif",J.fillText(TAe(J,a.brokerageName.toUpperCase(),R?430:820),212,1008)),R&&(J.textAlign="right",J.fillStyle=CR(P.accent,.9),J.font="600 16px Arial, sans-serif",J.fillText("CALL · TEXT",1016,958),J.fillStyle="#F8FAFC",J.font="600 38px Arial, sans-serif",J.fillText(R,1016,1008)),f(te.toDataURL("image/png"))}catch(te){console.error("Generate review graphic error",te),re.error("Could not generate graphic")}finally{d(!1)}}},[s,P,a,R,U,D,O]);j.useEffect(()=>{if(!t||!s)return;const te=setTimeout(()=>{W()},250);return()=>clearTimeout(te)},[t,s==null?void 0:s.id,g,a==null?void 0:a.brandColor,a==null?void 0:a.name]);const V=async()=>{var ve;if(!m)throw new Error("No graphic yet");const{data:te}=await q.auth.getUser(),J=(ve=te.user)==null?void 0:ve.id;if(!J)throw new Error("Not signed in");const ce=await(await fetch(m)).blob(),_e=`review-social/${J}/${crypto.randomUUID()}.png`,{error:he}=await q.storage.from("agent-uploads").upload(_e,ce,{contentType:"image/png",upsert:!0});if(he)throw he;const{data:ue}=q.storage.from("agent-uploads").getPublicUrl(_e);return{uid:J,publicUrl:ue.publicUrl}},G=()=>{if(!m)return;const te=document.createElement("a");te.href=m,te.download=`review-${(s==null?void 0:s.id)||"graphic"}.png`,te.click(),re.success("Downloaded!")},Y=async()=>{try{await navigator.clipboard.writeText(y),re.success("Caption copied")}catch{re.error("Copy not supported in this browser")}},X=async()=>{if(m){h("studio");try{const{publicUrl:te}=await V();sessionStorage.setItem("social-studio-seed",JSON.stringify({mediaUrl:te,mediaType:"image",caption:y,source:"other",sourceRef:s==null?void 0:s.id})),n(!1),r("/social-studio"),re.success("Draft ready in Social Studio")}catch(te){console.error("Push to Social Studio failed",te),re.error("Could not send to Social Studio")}finally{h(null)}}},ae=async te=>{if(m){if(S.length===0){re.error("Choose at least one account to post to.");return}h(te);try{const{uid:J,publicUrl:ce}=await V(),_e=te==="schedule"?$Te(amr(l),l).toISOString():null,{data:he,error:ue}=await q.from("social_posts").insert({user_id:J,caption:y.trim()||null,media_type:"image",media_urls:[ce],source:"other",status:te==="schedule"?"scheduled":"publishing",scheduled_for:_e,timezone:l}).select("id").single();if(ue)throw ue;const ve=i.filter(Se=>S.includes(Se.id)).map(Se=>({post_id:he.id,user_id:J,social_account_id:Se.id,platform:Se.platform,caption_override:null,status:"pending"})),{error:Ee}=await q.from("social_post_targets").insert(ve);if(Ee)throw Ee;if(te==="now"){const{data:Se,error:Le}=await q.functions.invoke("social-publish-post",{body:{post_id:he.id}});if(Le)throw Le;const Fe=Se==null?void 0:Se.status;Fe==="failed"?re.error("Publishing failed. Check the Queue tab in Social Studio."):Fe==="partial"?re.warning("Some accounts failed. Check the Queue tab to retry."):re.success("Posted to your accounts.")}else re.success("Scheduled for tomorrow at 10:00 AM");o(),n(!1)}catch(J){console.error("Review post failed",J),re.error(J instanceof Error?J.message:"Could not create the post")}finally{h(null)}}},ie=te=>C(J=>J.includes(te)?J.filter(ce=>ce!==te):[...J,te]);return e.jsx(zs,{open:t,onOpenChange:n,children:e.jsx(Os,{className:"!max-w-[900px] !w-[calc(100vw-2rem)] !p-0 !gap-0 !block overflow-hidden",style:{maxHeight:"calc(100vh - 2rem)"},children:e.jsxs("div",{className:"flex max-h-[calc(100vh-2rem)] flex-col",children:[e.jsxs(Us,{className:"shrink-0 border-b px-5 pb-3 pt-5 text-left",children:[e.jsx(Bs,{className:"text-lg",children:"Share this review"}),e.jsx(Ir,{children:"A branded 1080×1080 post in your colors — schedule it or send it straight to Social Studio."})]}),e.jsxs("div",{className:"min-h-0 flex-1 space-y-4 overflow-y-auto px-5 py-4",children:[e.jsxs("div",{children:[e.jsx("p",{className:"mb-2 text-xs font-medium text-muted-foreground",children:"Colors"}),e.jsx("div",{className:"flex flex-wrap gap-1.5",children:I.map(te=>e.jsxs("button",{type:"button",onClick:()=>x(te.key),className:`flex items-center gap-2 rounded-full border px-2.5 py-1 text-xs transition ${g===te.key?"border-primary ring-2 ring-primary/25":"border-border hover:border-muted-foreground/50"}`,children:[e.jsxs("span",{className:"flex",children:[e.jsx("span",{className:"h-3.5 w-3.5 rounded-l-full",style:{background:te.base}}),e.jsx("span",{className:"h-3.5 w-3.5 rounded-r-full",style:{background:te.accent}})]}),te.label]},te.key))})]}),e.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[e.jsxs("div",{className:"relative mx-auto flex aspect-square w-full max-w-[360px] items-center justify-center overflow-hidden rounded-lg",style:{background:P.base},children:[m?e.jsx("img",{src:m,alt:"Review graphic preview",className:"h-full w-full object-cover"}):e.jsx("div",{className:"text-xs text-white/70",children:"Preparing preview…"}),c&&e.jsxs("div",{className:"absolute inset-0 flex flex-col items-center justify-center gap-2 bg-black/60 text-white/90",children:[e.jsx(kt,{className:"h-7 w-7 animate-spin"}),e.jsx("p",{className:"text-xs",children:"Designing your post…"})]})]}),e.jsxs("div",{className:"flex flex-col",children:[e.jsxs("div",{className:"mb-2 flex items-center justify-between",children:[e.jsx("p",{className:"text-xs font-medium text-muted-foreground",children:"Post text"}),e.jsxs($,{type:"button",variant:"ghost",size:"sm",className:"h-7 gap-1.5 text-xs",onClick:Y,children:[e.jsx(Ha,{className:"h-3.5 w-3.5"})," Copy"]})]}),e.jsx(Rs,{value:y,onChange:te=>{v(te.target.value),w(!0)},rows:11,className:"min-h-[220px] text-sm",placeholder:"Your caption…"}),e.jsxs("div",{className:"mt-4",children:[e.jsx("p",{className:"mb-2 text-xs font-medium text-muted-foreground",children:"Post to"}),i.length===0?e.jsx("p",{className:"text-xs text-muted-foreground",children:"No social accounts connected yet — you can still download the graphic or open Social Studio."}):e.jsx("div",{className:"flex flex-wrap gap-2",children:i.map(te=>{const J=$4(te.platform),ce=S.includes(te.id);return e.jsxs("button",{type:"button",onClick:()=>ie(te.id),className:`flex items-center gap-2 rounded-full border px-2.5 py-1 text-xs transition ${ce?"border-primary bg-primary/10":"border-border hover:border-muted-foreground/50"}`,children:[e.jsxs(Oa,{className:"h-5 w-5",children:[e.jsx(Li,{src:te.profile_picture_url??void 0}),e.jsx(za,{className:"text-[10px]",children:J.label.charAt(0)})]}),te.page_name||te.platform_username||J.label]},te.id)})})]})]})]})]}),e.jsxs("div",{className:"flex shrink-0 flex-wrap justify-end gap-2 border-t bg-background px-5 pb-5 pt-3",children:[e.jsx($,{variant:"ghost",size:"sm",onClick:()=>n(!1),children:"Not now"}),e.jsxs($,{variant:"outline",size:"sm",onClick:G,disabled:!m,className:"gap-1.5",children:[e.jsx(di,{className:"h-3.5 w-3.5"})," Download"]}),e.jsxs($,{variant:"outline",size:"sm",onClick:X,disabled:!m||u!==null,className:"gap-1.5",children:[u==="studio"?e.jsx(kt,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(qg,{className:"h-3.5 w-3.5"}),"Open in Social Studio"]}),e.jsxs($,{variant:"outline",size:"sm",onClick:()=>void ae("schedule"),disabled:!m||u!==null||i.length===0,className:"gap-1.5",children:[u==="schedule"?e.jsx(kt,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(Au,{className:"h-3.5 w-3.5"}),"Schedule tomorrow 10 AM"]}),e.jsxs($,{size:"sm",onClick:()=>void ae("now"),disabled:!m||u!==null||i.length===0,className:"gap-1.5",children:[u==="now"?e.jsx(kt,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(Yr,{className:"h-3.5 w-3.5"}),"Post now"]})]})]})})})}function dTt({rating:s,size:t="h-4 w-4"}){return e.jsx("div",{className:"flex gap-0.5",children:[1,2,3,4,5].map(n=>e.jsx(Ja,{className:Pt(t,n<=s?"fill-[#c9a24b] text-[#c9a24b]":"text-slate-300")},n))})}function uTt(s){return s.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/(^-|-$)/g,"")}function omr(){var cs,js,kn,Ws,On;const{user:s,rolesLoading:t}=vs(),[n,r]=j.useState([]),[a,i]=j.useState([]),[l,o]=j.useState(!0),[c,d]=j.useState({slug:"",intro_text:"",is_published:!1,show_google_reviews:!0,show_video_reviews:!0,headline:"",subheadline:"",accent_color:"#c9a24b",hero_image_url:"",video_prompts:"",thank_you_title:"",thank_you_message:"",cta_label:"",cta_url:"",allow_public_submissions:!0,protection_enabled:!1,protection_threshold:3,hide_google_below_threshold:!1,private_feedback_title:"",private_feedback_message:"",widget_enabled:!1,widget_layout:"carousel",widget_theme:"light",widget_accent:"",widget_title:""}),[u,h]=j.useState(!1),[m,f]=j.useState(!1),[g,x]=j.useState(""),[y,v]=j.useState("email"),[b,w]=j.useState(null),[S,C]=j.useState({}),[E,I]=j.useState(""),[P,R]=j.useState(""),[D,O]=j.useState(""),[U,W]=j.useState("closing_day"),[V,G]=j.useState(!1),[Y,X]=j.useState(null),[ae,ie]=j.useState(null),[ne,te]=j.useState(""),[J,ce]=j.useState(!1),[_e,he]=j.useState(!1),[ue,ve]=j.useState(!1),[Ee,Se]=j.useState(null),Le=Ee?Ee.connected:null,[Fe,ke]=gc(),Ve=j.useRef(!1),je=j.useCallback(async()=>{const{data:ds,error:gn}=await q.functions.invoke("google-business-oauth",{body:{action:"get_status"}});if(gn||ds!=null&&ds.error){Se({connected:!1,email:null,apiAccessPending:!1,hasRefreshToken:!1,connectedAt:null,locations:[]});return}Se(ds)},[]),Ae=j.useCallback(async()=>{if(!s)return;o(!0);const[{data:ds},{data:gn},{data:As}]=await Promise.all([q.from("review_responses").select("*").eq("user_id",s.id).order("is_pinned",{ascending:!1}).order("created_at",{ascending:!1}),q.from("review_requests").select("*").eq("user_id",s.id).order("created_at",{ascending:!1}).limit(100),q.from("agent_review_page_settings").select("*").eq("user_id",s.id).maybeSingle()]);if(r(ds??[]),i(gn??[]),je(),As){const hr=Array.isArray(As.video_prompts)?As.video_prompts:[];d({id:As.id,slug:As.slug??"",intro_text:As.intro_text??"",is_published:As.is_published,show_google_reviews:As.show_google_reviews,show_video_reviews:As.show_video_reviews,headline:As.headline??"",subheadline:As.subheadline??"",accent_color:As.accent_color??"#c9a24b",hero_image_url:As.hero_image_url??"",video_prompts:hr.join(` `),thank_you_title:As.thank_you_title??"",thank_you_message:As.thank_you_message??"",cta_label:As.cta_label??"",cta_url:As.cta_url??"",allow_public_submissions:As.allow_public_submissions??!0,protection_enabled:As.protection_enabled??!1,protection_threshold:As.protection_threshold??3,hide_google_below_threshold:As.hide_google_below_threshold??!1,private_feedback_title:As.private_feedback_title??"",private_feedback_message:As.private_feedback_message??"",widget_enabled:As.widget_enabled??!1,widget_layout:As.widget_layout??"carousel",widget_theme:As.widget_theme??"light",widget_accent:As.widget_accent??"",widget_title:As.widget_title??""})}else{const{data:hr}=await q.from("profiles").select("name").eq("id",s.id).single(),Er=uTt((hr==null?void 0:hr.name)??"");d(qn=>({...qn,slug:qn.slug||Er}))}o(!1)},[s,je]);j.useEffect(()=>{Ae()},[Ae]),j.useEffect(()=>{if(Ve.current)return;const ds=Fe.get("google"),gn=Fe.get("google_error");if(!ds&&!gn)return;if(Ve.current=!0,gn)re.error(gn==="access_denied"?"Google connection was cancelled":gn==="invalid_state"?"That connection link expired — please try again":gn==="not_configured"?"Google Business credentials are not configured yet":gn==="missing_business_permission"?"Google didn't give us access to your Business Profile. Connect again and tick the Business Profile box on Google's screen.":`Google connection failed: ${gn}`,gn==="missing_business_permission"?{duration:1e4}:void 0);else{const hr=Number(Fe.get("locations")??0);re.success(Fe.get("google_pending")?"Google connected — review access is still pending Google approval":`Google Business Profile connected${hr?` (${hr} location${hr>1?"s":""})`:""}`)}const As=new URLSearchParams(Fe);["google","google_error","google_pending","locations"].forEach(hr=>As.delete(hr)),ke(As,{replace:!0}),je()},[Fe,ke,je]);const Ce=async()=>{ve(!0);const{data:ds,error:gn}=await q.functions.invoke("google-business-oauth",{body:{action:"get_auth_url",returnPath:"/apps/reviews"}});if(gn||ds!=null&&ds.error||!(ds!=null&&ds.authUrl))return ve(!1),re.error((ds==null?void 0:ds.error)||(gn==null?void 0:gn.message)||"Could not start Google connection");window.location.href=ds.authUrl},qe=async()=>{const{error:ds}=await q.functions.invoke("google-business-oauth",{body:{action:"disconnect"}});if(ds)return re.error("Could not disconnect");re.success("Google Business Profile disconnected"),je()},[ze,$e]=j.useState(!1),ct=async()=>{$e(!0);const{data:ds,error:gn}=await q.functions.invoke("google-business-oauth",{body:{action:"rescan_locations"}});if($e(!1),gn||ds!=null&&ds.error)return re.error((ds==null?void 0:ds.error)||(gn==null?void 0:gn.message)||"Could not check Google");(ds==null?void 0:ds.success)===!1||!(ds!=null&&ds.locationsCount)?re.error((ds==null?void 0:ds.message)||"No business locations were found on this Google account.",{duration:1e4}):re.success(ds.message),je()},Xe=j.useMemo(()=>{const ds=n.filter(hn=>hn.status!=="hidden"),gn=ds.filter(hn=>hn.rating),As=gn.length?gn.reduce((hn,Fn)=>hn+(Fn.rating??0),0)/gn.length:0,hr=a.filter(hn=>["sent","reminded","clicked"].includes(hn.status)).length,Er=a.filter(hn=>hn.status==="completed").length,qn=a.length?Math.round(Er/a.length*100):0;return{avg:Math.round(As*10)/10,total:ds.length,pending:hr,responseRate:qn,newCount:n.filter(hn=>hn.status==="new").length}},[n,a]),it=async(ds,gn)=>{const{error:As}=await q.from("review_responses").update({status:gn}).eq("id",ds);if(As)return re.error(As.message);r(hr=>hr.map(Er=>Er.id===ds?{...Er,status:gn}:Er))},at=async ds=>{const{error:gn}=await q.from("review_responses").update({is_pinned:!ds.is_pinned}).eq("id",ds.id);if(gn)return re.error(gn.message);r(As=>As.map(hr=>hr.id===ds.id?{...hr,is_pinned:!ds.is_pinned}:hr))},Ke=async ds=>{const gn=!ds.in_widget,{error:As}=await q.from("review_responses").update({in_widget:gn}).eq("id",ds.id);if(As)return re.error(As.message);r(hr=>hr.map(Er=>Er.id===ds.id?{...Er,in_widget:gn}:Er))},nt=async()=>{if(!s)return;if(!c.slug)return re.error("Choose a slug for your page");h(!0);const ds={user_id:s.id,slug:uTt(c.slug),intro_text:c.intro_text||null,is_published:c.is_published,show_google_reviews:c.show_google_reviews,show_video_reviews:c.show_video_reviews,headline:c.headline||null,subheadline:c.subheadline||null,accent_color:c.accent_color||null,hero_image_url:c.hero_image_url||null,video_prompts:c.video_prompts.split(` `).map(As=>As.trim()).filter(Boolean),thank_you_title:c.thank_you_title||null,thank_you_message:c.thank_you_message||null,cta_label:c.cta_label||null,cta_url:c.cta_url||null,allow_public_submissions:c.allow_public_submissions,protection_enabled:c.protection_enabled,protection_threshold:c.protection_threshold,hide_google_below_threshold:c.hide_google_below_threshold,private_feedback_title:c.private_feedback_title||null,private_feedback_message:c.private_feedback_message||null,widget_enabled:c.widget_enabled,widget_layout:c.widget_layout,widget_theme:c.widget_theme,widget_accent:c.widget_accent||null,widget_title:c.widget_title||null},{error:gn}=c.id?await q.from("agent_review_page_settings").update(ds).eq("id",c.id):await q.from("agent_review_page_settings").insert(ds);if(h(!1),gn)return re.error(gn.message.includes("unique")?"That slug is taken — try another":gn.message);re.success(c.is_published?"Your reviews page is live":"Settings saved"),Ae()},xt=async()=>{const gn=g.split(` `).map(hn=>hn.trim()).filter(Boolean).map(hn=>{const[Fn,vn,xs]=hn.split(",").map(Lr=>Lr.trim());return{name:Fn,email:vn,phone:xs}}).filter(hn=>hn.email||hn.phone);if(gn.length===0)return re.error("Add at least one recipient (Name, email, phone — one per line)");if(y!=="email"&&!gn.some(hn=>hn.phone))return re.error("Add a mobile number for each person you want to text");G(!0);const{data:As,error:hr}=await q.functions.invoke("review-request-send",{body:{recipients:gn,channel:y,message:E||void 0,subject:P||void 0,sms_body:D||void 0}});if(G(!1),hr||As!=null&&As.error)return re.error((As==null?void 0:As.error)||(hr==null?void 0:hr.message)||"Send failed");const Er=(As.results??[]).filter(hn=>hn.ok&&hn.emailed).length;if(y!=="email"){const hn=As.prepared??[];if(hn.length===0)return re.error("No mobile numbers to text");Er>0&&re.success(`${Er} email${Er!==1?"s":""} sent — now send your texts`),C({}),w(hn),f(!1),x(""),Ae();return}const qn=(As.results??[]).filter(hn=>hn.ok).length;re.success(`${qn} review request${qn!==1?"s":""} sent`),f(!1),x(""),Ae()},rt=ds=>{const gn=navigator.userAgent,hr=/iPhone|iPad|iPod/.test(gn)||/Macintosh/.test(gn)&&navigator.maxTouchPoints>1?"&":"?";return`sms:${ds.phone}${hr}body=${encodeURIComponent(ds.body)}`},Yt=ds=>C(gn=>({...gn,[ds]:!0})),qt=async()=>{if(!(!Y||!ne.trim())){if(ce(!0),Y.source==="google"){const{data:ds,error:gn}=await q.functions.invoke("google-reviews-sync",{body:{action:"reply",review_id:Y.id,text:ne.trim()}});if(gn||ds!=null&&ds.error)return ce(!1),re.error((ds==null?void 0:ds.error)||(gn==null?void 0:gn.message)||"Reply failed")}else{const{error:ds}=await q.from("review_responses").update({reply_text:ne.trim(),replied_at:new Date().toISOString()}).eq("id",Y.id);if(ds)return ce(!1),re.error(ds.message)}ce(!1),re.success("Reply posted"),X(null),te(""),Ae()}},ts=async()=>{he(!0);const{data:ds,error:gn}=await q.functions.invoke("google-reviews-sync",{body:{action:"sync_mine"}});if(he(!1),gn||ds!=null&&ds.error)return re.error((ds==null?void 0:ds.error)||(gn==null?void 0:gn.message)||"Sync failed");if(ds!=null&&ds.needsReconnect)return re.error("Your Google connection expired — click Connect Google to reconnect");re.success(`Synced ${(ds==null?void 0:ds.synced)??0} reviews`),Ae()},ys=n.filter(ds=>ds.in_widget&&!ds.is_private&&(ds.status==="approved"||ds.status==="featured")),Ft=`